Repository navigation
Expand file tree
/
Copy pathsession.ts
More file actions
835 lines (822 loc) · 34.4 KB
/
Copy pathsession.ts
File metadata and controls
835 lines (822 loc) · 34.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
import { SessionMessage } from "@opencode/schema/session-message"
import { SessionInbox } from "@opencode/schema/session-inbox"
import { PromptInput } from "@opencode/schema/prompt-input"
import { Session } from "@opencode/schema/session"
import { SessionStats } from "@opencode/schema/session-stats"
import { TokenUsage } from "@opencode/schema/token-usage"
import { Money } from "@opencode/schema/money"
import { InstructionEntry } from "@opencode/schema/instruction-entry"
import { Project } from "@opencode/schema/project"
import { DateTimeUtcFromMillis, NonNegativeInt, PositiveInt } from "@opencode/schema/schema"
import { Event } from "@opencode/schema/event"
import { SessionLegacy } from "@opencode/schema/session-legacy"
import { Context, Schema, SchemaGetter, Struct } from "effect"
import { HttpApiEndpoint, HttpApiGroup, HttpApiMiddleware, HttpApiSchema, OpenApi } from "effect/http-api"
import {
ConflictError,
LocationNotFoundError,
CommandExecutionError,
CommandNotFoundError,
FormAlreadySettledError,
FormInvalidAnswerError,
FormNotFoundError,
InvalidCursorError,
InvalidRequestError,
MessageNotFoundError,
ServiceUnavailableError,
SessionBusyError,
SessionNotFoundError,
SkillNotFoundError,
UnknownError,
} from "../errors.js"
import { Agent } from "@opencode/schema/agent"
import { Skill } from "@opencode/schema/skill"
import { Model } from "@opencode/schema/model"
import { Permission } from "@opencode/schema/permission"
import { Location } from "@opencode/schema/location"
import { SessionEvent } from "@opencode/schema/session-event"
import { EventLog } from "@opencode/schema/event-log"
import { FileDiff } from "@opencode/schema/file-diff"
import { Form } from "@opencode/schema/form"
import { PublicSessionMessage } from "./message.js"
const SessionActive = Schema.Struct({
type: Schema.Literal("running"),
}).annotate({ identifier: "SessionActive" })
const PublicSessionInfo = Schema.Struct({
...Struct.omit(Session.Info.fields, ["location"]),
location: Location.PublicRef,
}).annotate({ identifier: "Session.Info" })
const PublicSessionTransfer = Schema.Struct({
info: PublicSessionInfo,
messages: Schema.Array(PublicSessionMessage),
}).annotate({ identifier: "SessionTransfer.Data" })
const PublicMovePayload = Schema.Struct({
...Struct.omit(SessionInbox.MovePayload.fields, ["location"]),
location: Location.PublicRef,
}).annotate({ identifier: "Session.Inbox.MovePayload" })
const PublicMove = Schema.Struct({
...Struct.omit(SessionInbox.Move.fields, ["payload"]),
payload: PublicMovePayload,
}).annotate({ identifier: "Session.Inbox.Move" })
const PublicInboxInfo = Schema.Union([
SessionInbox.User,
SessionInbox.Synthetic,
SessionInbox.Compaction,
PublicMove,
]).annotate({ identifier: "Session.Inbox.Info" })
/** Experimental: the `session.inbox.list` response for clients that opt into `experimental-media-uri`. */
export const SessionMediaInboxResponse = Schema.Struct({
data: Schema.Array(
Schema.Union([SessionInbox.MediaUser, SessionInbox.Synthetic, SessionInbox.Compaction, PublicMove]).annotate({
identifier: "Session.Inbox.MediaInfo",
}),
),
})
// Transcripts exported before v2.1 carry older names for native data. The wire stays plain JSON so any export file
// is accepted; decoding upgrades those names and then validates the current message shape.
const ImportedMessages = Schema.Array(Schema.Json).pipe(
Schema.decodeTo(Schema.Array(Schema.Unknown), {
decode: SchemaGetter.transform(SessionLegacy.messages),
encode: SchemaGetter.passthrough({ strict: false }),
}),
Schema.decodeTo(Schema.Array(PublicSessionMessage), {
decode: SchemaGetter.passthrough({ strict: false }),
encode: SchemaGetter.passthrough({ strict: false }),
}),
)
const FormCreatePayload = Schema.Struct({
id: Form.ID.pipe(Schema.optional),
title: Form.Info.fields.title,
metadata: Form.Info.fields.metadata,
fields: Form.Info.fields.fields,
}).annotate({ identifier: "Form.CreatePayload" })
const BooleanFromString = Schema.Literals(["true", "false"]).pipe(
Schema.decodeTo(Schema.Boolean, {
decode: SchemaGetter.transform((value) => value === "true"),
encode: SchemaGetter.transform((value): "true" | "false" => (value ? "true" : "false")),
}),
)
// Kept so existing imports of SessionsCursor from Protocol keep working.
export const SessionsCursor = Session.ListCursor
export type SessionsCursor = Session.ListCursor
export const SessionsQuery = Schema.Struct({
limit: Schema.NumberFromString.pipe(Schema.decodeTo(PositiveInt), Schema.optional).annotate({
description: "Maximum number of sessions to return. Defaults to the newest 50 sessions.",
}),
...Session.ListFilter.fields,
cursor: Session.ListCursor.pipe(Schema.optional),
}).annotate({ identifier: "SessionsQuery" })
export const makeSessionGroup = <I extends HttpApiMiddleware.AnyId, S, FormI extends HttpApiMiddleware.AnyId, FormS>(
sessionLocationMiddleware: Context.Key<I, S>,
formLocationMiddleware: Context.Key<FormI, FormS>,
) =>
HttpApiGroup.make("server.session")
.add(
HttpApiEndpoint.get("session.list", "/api/session", {
query: SessionsQuery,
success: Schema.Struct({
data: Schema.Array(PublicSessionInfo),
cursor: Schema.Struct({
previous: Session.ListCursor.pipe(Schema.optional),
next: Session.ListCursor.pipe(Schema.optional),
}),
}).annotate({ identifier: "SessionsResponse" }),
error: [InvalidCursorError, InvalidRequestError],
}).annotateMerge(
OpenApi.annotations({
identifier: "session.list",
summary: "List sessions",
description:
"Retrieve sessions in the requested order. Items keep that order across pages; use cursor.next or cursor.previous to move through the ordered list.",
}),
),
)
.add(
HttpApiEndpoint.get("session.stats", "/api/experimental/session/stats", {
query: Schema.Struct({
from: Schema.NumberFromString.pipe(Schema.optional),
to: Schema.NumberFromString.pipe(Schema.optional),
project: Project.ID.pipe(Schema.optional),
timezone: Schema.String.pipe(Schema.optional),
tools: SessionStats.ToolMode.pipe(Schema.optional),
}),
success: Schema.Struct({ data: SessionStats.Info }),
error: InvalidRequestError,
}).annotateMerge(
OpenApi.annotations({
identifier: "experimental.session.stats",
summary: "Get session statistics",
description: "Aggregate local session activity, usage, and tool reliability for a time range.",
}),
),
)
.add(
HttpApiEndpoint.post("session.create", "/api/session", {
payload: Schema.Struct({
id: Session.ID.pipe(Schema.optional),
parentID: Session.ID.pipe(Schema.optional).annotate({
description:
"Set parentID to create a subagent session at the parent's location; set agent to choose its agent (otherwise it uses the default) and start it with session.prompt. After each completed round, the child sends a `<subagent>` report to the parent's inbox and wakes the parent unless it has a staged revert.",
}),
title: Schema.String.pipe(Schema.optional),
agent: Agent.ID.pipe(Schema.optional),
model: Model.Ref.pipe(Schema.optional),
location: Location.PublicRef.pipe(Schema.optional),
metadata: Session.Metadata.pipe(Schema.optional),
permissions: Permission.Ruleset.pipe(Schema.optional),
}),
success: Schema.Struct({ data: PublicSessionInfo }),
error: SessionNotFoundError,
}).annotateMerge(
OpenApi.annotations({
identifier: "session.create",
summary: "Create session",
description:
"Create a session at the requested location. A parentID creates a linked child session at its parent's location.",
}),
),
)
.add(
HttpApiEndpoint.post("session.import", "/api/experimental/session/import", {
payload: Schema.Struct({
info: PublicSessionTransfer.fields.info,
messages: ImportedMessages,
location: Location.PublicRef.pipe(Schema.optional),
}),
success: Schema.Struct({ data: PublicSessionInfo }),
error: [ConflictError, SessionNotFoundError],
}).annotateMerge(
OpenApi.annotations({
identifier: "experimental.session.import",
summary: "Import session",
description:
"Import a projected session transcript at the requested location. Accepts transcripts exported by earlier releases. If parentID is supplied, the parent session must already exist; import parents before children.",
}),
),
)
.add(
HttpApiEndpoint.get("session.export", "/api/experimental/session/:sessionID/export", {
params: { sessionID: Session.ID },
query: Schema.Struct({ sanitize: BooleanFromString.pipe(Schema.optional) }),
success: Schema.Struct({ data: PublicSessionTransfer }),
error: [SessionNotFoundError, UnknownError],
}).annotateMerge(
OpenApi.annotations({
identifier: "experimental.session.export",
summary: "Export session",
description: "Export a complete projected session transcript.",
}),
),
)
.add(
HttpApiEndpoint.get("session.active", "/api/session/active", {
success: Schema.Struct({ data: Schema.Record(Session.ID, SessionActive) }),
}).annotateMerge(
OpenApi.annotations({
identifier: "session.active",
summary: "List active sessions",
description:
"Retrieve foreground Session drains currently owned by this OpenCode process. Sessions absent from the result are inactive.",
}),
),
)
.add(
HttpApiEndpoint.get("session.get", "/api/session/:sessionID", {
params: { sessionID: Session.ID },
success: Schema.Struct({ data: PublicSessionInfo }),
error: SessionNotFoundError,
}).annotateMerge(
OpenApi.annotations({
identifier: "session.get",
summary: "Get session",
description: "Retrieve a session by ID.",
}),
),
)
.add(
HttpApiEndpoint.delete("session.remove", "/api/session/:sessionID", {
params: { sessionID: Session.ID },
success: HttpApiSchema.NoContent,
error: SessionNotFoundError,
}).annotateMerge(
OpenApi.annotations({
identifier: "session.remove",
summary: "Delete session",
description: "Delete a session and its child sessions.",
}),
),
)
.add(
HttpApiEndpoint.post("session.fork", "/api/session/:sessionID/fork", {
params: { sessionID: Session.ID },
payload: Schema.Struct({ before: SessionMessage.ID.pipe(Schema.optional) }),
success: Schema.Struct({ data: PublicSessionInfo }),
error: [SessionNotFoundError, MessageNotFoundError, InvalidRequestError],
}).annotateMerge(
OpenApi.annotations({
identifier: "session.fork",
summary: "Fork session",
description:
"Create a child session by copying projected history before a message. Omit before to copy the full history.",
}),
),
)
.add(
HttpApiEndpoint.post("session.switchAgent", "/api/session/:sessionID/agent", {
params: { sessionID: Session.ID },
payload: Schema.Struct({ agent: Agent.ID }),
success: HttpApiSchema.NoContent,
error: SessionNotFoundError,
}).annotateMerge(
OpenApi.annotations({
identifier: "session.switchAgent",
summary: "Switch session agent",
description: "Switch the agent used by subsequent provider turns.",
}),
),
)
.add(
HttpApiEndpoint.post("session.switchModel", "/api/session/:sessionID/model", {
params: { sessionID: Session.ID },
payload: Schema.Struct({ model: Model.Ref }),
success: HttpApiSchema.NoContent,
error: SessionNotFoundError,
}).annotateMerge(
OpenApi.annotations({
identifier: "session.switchModel",
summary: "Switch session model",
description: "Switch the model used by subsequent provider turns.",
}),
),
)
.add(
HttpApiEndpoint.patch("session.update", "/api/session/:sessionID", {
params: { sessionID: Session.ID },
payload: Schema.Struct({
title: Schema.String.pipe(Schema.optional),
metadata: Session.Metadata.pipe(Schema.optional),
permissions: Permission.Ruleset.pipe(Schema.optional),
archived: Schema.Boolean.pipe(Schema.optional).annotate({
description:
"Archive the session with true or restore it with false. Repeating the current state is a no-op.",
}),
}),
success: HttpApiSchema.NoContent,
error: [SessionNotFoundError, LocationNotFoundError],
}).annotateMerge(
OpenApi.annotations({
identifier: "session.update",
summary: "Update session",
description: "Update mutable session properties.",
}),
),
)
.add(
HttpApiEndpoint.post("session.move", "/api/session/:sessionID/move", {
params: { sessionID: Session.ID },
payload: Schema.Struct({ ...Location.PublicRef.fields, delivery: SessionInbox.Delivery.pipe(Schema.optional) }),
success: HttpApiSchema.NoContent,
error: [SessionNotFoundError, InvalidRequestError],
}).annotateMerge(
OpenApi.annotations({
identifier: "session.move",
summary: "Move session",
description: "Move a session to another project directory at the requested delivery boundary.",
}),
),
)
.add(
HttpApiEndpoint.post("session.prompt", "/api/session/:sessionID/prompt", {
params: { sessionID: Session.ID },
payload: Schema.Struct({
id: SessionMessage.ID.pipe(Schema.optional),
...PromptInput.Prompt.fields,
metadata: SessionInbox.UserPayload.fields.metadata,
delivery: SessionInbox.Delivery.pipe(Schema.optional),
resume: Schema.Boolean.pipe(Schema.optional),
}),
success: Schema.Struct({ data: SessionInbox.User }),
error: [ConflictError, InvalidRequestError, SessionNotFoundError],
})
.middleware(sessionLocationMiddleware)
.annotateMerge(
OpenApi.annotations({
identifier: "session.prompt",
summary: "Send message",
description: "Durably admit one session input and schedule agent-loop execution unless resume is false.",
}),
),
)
.add(
HttpApiEndpoint.post("session.command", "/api/session/:sessionID/command", {
params: { sessionID: Session.ID },
payload: Schema.Struct({
name: Schema.String,
...PromptInput.Prompt.fields,
delivery: SessionInbox.Delivery.pipe(Schema.optional),
}),
success: HttpApiSchema.NoContent,
error: [SessionNotFoundError, CommandNotFoundError, CommandExecutionError],
})
.middleware(sessionLocationMiddleware)
.annotateMerge(
OpenApi.annotations({
identifier: "session.command",
summary: "Run command",
description: "Execute a slash command callback immediately.",
}),
),
)
.add(
HttpApiEndpoint.post("session.skill", "/api/experimental/session/:sessionID/skill", {
params: { sessionID: Session.ID },
payload: Schema.Struct({
id: Skill.ID,
resume: Schema.Boolean.pipe(Schema.optional),
}),
success: HttpApiSchema.NoContent,
error: [SessionNotFoundError, SkillNotFoundError],
})
.middleware(sessionLocationMiddleware)
.annotateMerge(
OpenApi.annotations({
identifier: "experimental.session.skill",
summary: "Activate skill",
description: "Activate a skill for a session by appending a skill message and resuming execution.",
}),
),
)
.add(
HttpApiEndpoint.post("session.synthetic", "/api/session/:sessionID/synthetic", {
params: { sessionID: Session.ID },
payload: Schema.Struct({
id: SessionMessage.ID.pipe(Schema.optional),
text: Schema.String,
description: Schema.String.pipe(Schema.optional),
metadata: SessionMessage.Synthetic.fields.metadata,
delivery: SessionInbox.Delivery.pipe(Schema.optional),
resume: Schema.Boolean.pipe(Schema.optional),
}),
success: Schema.Struct({ data: SessionInbox.Synthetic }),
error: [ConflictError, SessionNotFoundError],
}).annotateMerge(
OpenApi.annotations({
identifier: "session.synthetic",
summary: "Add synthetic message",
description: "Durably admit synthetic session input and schedule execution unless resume is false.",
}),
),
)
.add(
HttpApiEndpoint.post("session.shell", "/api/session/:sessionID/shell", {
params: { sessionID: Session.ID },
payload: Schema.Struct({
id: SessionMessage.ID.pipe(Schema.optional),
command: Schema.String,
}),
success: HttpApiSchema.NoContent,
error: SessionNotFoundError,
})
.middleware(sessionLocationMiddleware)
.annotateMerge(
OpenApi.annotations({
identifier: "session.shell",
summary: "Run shell command",
description:
"Execute one shell command in the session's working directory. Emits a shell.started event before execution and a shell.ended event with the merged output after.",
}),
),
)
.add(
HttpApiEndpoint.post("session.compact", "/api/session/:sessionID/compact", {
params: { sessionID: Session.ID },
payload: Schema.Struct({
id: SessionMessage.ID.pipe(Schema.optional),
delivery: SessionInbox.Delivery.pipe(Schema.optional),
}),
success: Schema.Struct({ data: SessionInbox.Compaction }),
error: [ConflictError, SessionNotFoundError],
}).annotateMerge(
OpenApi.annotations({
identifier: "session.compact",
summary: "Compact session",
description:
"Durably admit a session compaction request. Steers by default: it runs at the next step boundary instead of waiting behind queued prompts.",
}),
),
)
.add(
HttpApiEndpoint.post("session.wait", "/api/experimental/session/:sessionID/wait", {
params: { sessionID: Session.ID },
success: HttpApiSchema.NoContent,
error: [SessionNotFoundError, ServiceUnavailableError],
}).annotateMerge(
OpenApi.annotations({
identifier: "experimental.session.wait",
summary: "Wait for session",
description: "Wait for a session agent loop to become idle.",
}),
),
)
.add(
HttpApiEndpoint.post("session.revert.stage", "/api/session/:sessionID/revert/stage", {
params: { sessionID: Session.ID },
payload: Schema.Struct({ messageID: SessionMessage.ID, files: Schema.Boolean.pipe(Schema.optional) }),
success: Schema.Struct({ data: Session.Revert }),
error: [MessageNotFoundError, SessionNotFoundError, SessionBusyError, UnknownError],
})
.middleware(sessionLocationMiddleware)
.annotateMerge(
OpenApi.annotations({
identifier: "session.revert.stage",
summary: "Stage session revert",
description: "Stage or move a reversible session boundary and optionally apply its file changes.",
}),
),
)
.add(
HttpApiEndpoint.delete("session.revert.clear", "/api/session/:sessionID/revert", {
params: { sessionID: Session.ID },
success: HttpApiSchema.NoContent,
error: [SessionNotFoundError, SessionBusyError, UnknownError],
})
.middleware(sessionLocationMiddleware)
.annotateMerge(OpenApi.annotations({ identifier: "session.revert.clear", summary: "Clear staged revert" })),
)
.add(
HttpApiEndpoint.post("session.revert.commit", "/api/session/:sessionID/revert/commit", {
params: { sessionID: Session.ID },
success: HttpApiSchema.NoContent,
error: [SessionNotFoundError, SessionBusyError],
}).annotateMerge(OpenApi.annotations({ identifier: "session.revert.commit", summary: "Commit staged revert" })),
)
.add(
HttpApiEndpoint.get("session.context", "/api/session/:sessionID/context", {
params: { sessionID: Session.ID },
success: Schema.Struct({ data: Schema.Array(PublicSessionMessage) }),
error: [SessionNotFoundError, UnknownError],
}).annotateMerge(
OpenApi.annotations({
identifier: "session.context",
summary: "Get session context",
description: "Retrieve the active context messages for a session (all messages after the last compaction).",
}),
),
)
.add(
HttpApiEndpoint.get("session.diff", "/api/session/:sessionID/diff", {
params: { sessionID: Session.ID },
query: Schema.Struct({
from: Schema.optional(SessionMessage.ID).annotate({
description: "User message whose turn to diff. Defaults to the turn of the newest user message.",
}),
to: Schema.optional(SessionMessage.ID).annotate({
description: "Later user message whose turn ends the range. Defaults to the turn of `from` alone.",
}),
context: Schema.NumberFromString.pipe(Schema.decodeTo(NonNegativeInt), Schema.optional).annotate({
description: "Unchanged lines around each hunk. Omit for full-file patches.",
}),
}),
success: Schema.Struct({ data: Schema.Array(FileDiff.Info) }),
error: [InvalidRequestError, MessageNotFoundError, SessionNotFoundError, UnknownError, LocationNotFoundError],
}).annotateMerge(
OpenApi.annotations({
identifier: "session.diff",
summary: "Diff session turns",
description:
"Structured per-file diffs of the files a turn changed. A turn runs from the first prompt after the session was last idle until its next idle marker, so prompts steered in while it was busy belong to the same turn; `to` extends the range through a later turn. Compares the range's first recorded snapshot with its last; a step still running in the active session compares against the working copy. Ranges that span a location change are rejected. In sessions without any idle marker, a prompt's turn spans until the next user message.",
}),
),
)
.add(
HttpApiEndpoint.get("session.inbox.list", "/api/session/:sessionID/inbox", {
params: { sessionID: Session.ID },
success: Schema.Struct({ data: Schema.Array(PublicInboxInfo) }),
error: SessionNotFoundError,
}).annotateMerge(
OpenApi.annotations({
identifier: "session.inbox.list",
summary: "List session inbox",
description:
"List durable enqueued session work not yet delivered, ordered by enqueue sequence. Includes user, synthetic, compaction, and move items.",
}),
),
)
.add(
HttpApiEndpoint.delete("session.inbox.cancel", "/api/session/:sessionID/inbox/:inboxID", {
params: { sessionID: Session.ID, inboxID: SessionMessage.ID },
success: HttpApiSchema.NoContent,
error: SessionNotFoundError,
}).annotateMerge(
OpenApi.annotations({
identifier: "session.inbox.cancel",
summary: "Cancel inbox input",
description: "Cancel an inbox item that has not yet been delivered. Unavailable items are a no-op.",
}),
),
)
.add(
HttpApiEndpoint.patch("session.inbox.update", "/api/session/:sessionID/inbox/:inboxID", {
params: { sessionID: Session.ID, inboxID: SessionMessage.ID },
payload: Schema.Struct({ delivery: SessionInbox.Delivery }),
success: HttpApiSchema.NoContent,
error: [ConflictError, SessionNotFoundError],
}).annotateMerge(
OpenApi.annotations({
identifier: "session.inbox.update",
summary: "Update inbox item",
description: "Change a pending inbox item's delivery mode. Steering wakes session execution.",
}),
),
)
.add(
HttpApiEndpoint.get(
"session.instructions.entry.list",
"/api/experimental/session/:sessionID/instructions/entries",
{
params: { sessionID: Session.ID },
success: Schema.Struct({ data: Schema.Array(InstructionEntry.Info) }),
error: SessionNotFoundError,
},
).annotateMerge(
OpenApi.annotations({
identifier: "experimental.session.instructions.entry.list",
summary: "List instruction entries",
description: "List API-managed instruction entries attached to the session.",
}),
),
)
.add(
HttpApiEndpoint.put(
"session.instructions.entry.put",
"/api/experimental/session/:sessionID/instructions/entries/:key",
{
params: { sessionID: Session.ID, key: InstructionEntry.Key },
payload: Schema.Struct({ value: Schema.Json }),
success: HttpApiSchema.NoContent,
error: [SessionNotFoundError, InstructionEntry.ValueTooLargeError],
},
).annotateMerge(
OpenApi.annotations({
identifier: "experimental.session.instructions.entry.put",
summary: "Put instruction entry",
description:
"Attach or replace one durable instruction entry. Changes announce as updates at the next step boundary.",
}),
),
)
.add(
HttpApiEndpoint.delete(
"session.instructions.entry.remove",
"/api/experimental/session/:sessionID/instructions/entries/:key",
{
params: { sessionID: Session.ID, key: InstructionEntry.Key },
success: HttpApiSchema.NoContent,
error: SessionNotFoundError,
},
).annotateMerge(
OpenApi.annotations({
identifier: "experimental.session.instructions.entry.remove",
summary: "Remove instruction entry",
description: "Remove one instruction entry; the removal is announced to the model at the next step boundary.",
}),
),
)
.add(
HttpApiEndpoint.post("session.generate", "/api/session/:sessionID/generate", {
params: { sessionID: Session.ID },
payload: Schema.Struct({ prompt: Schema.String }),
success: Schema.Struct({
// Same `tokens` and `cost` an assistant message reports for a step.
data: Schema.Struct({ text: Schema.String, tokens: TokenUsage.Info, cost: Money.USD }),
}).annotate({ identifier: "SessionGenerateResponse" }),
error: [SessionNotFoundError, ServiceUnavailableError],
})
.middleware(sessionLocationMiddleware)
.annotateMerge(
OpenApi.annotations({
identifier: "session.generate",
summary: "Generate text from session context",
description:
"Generate transient text from the current session context without mutating session history. Its tokens and cost count toward the session's totals.",
}),
),
)
.add(
HttpApiEndpoint.get("session.log", "/api/experimental/session/:sessionID/log", {
params: { sessionID: Session.ID },
query: {
after: Schema.NumberFromString.pipe(Schema.decodeTo(Event.Seq), Schema.optional),
follow: BooleanFromString.pipe(Schema.optional),
},
success: HttpApiSchema.StreamSse({
data: Schema.Union([SessionEvent.Durable, EventLog.Synced]).annotate({ identifier: "SessionLogItem" }),
}),
error: SessionNotFoundError,
}).annotateMerge(
OpenApi.annotations({
identifier: "experimental.session.log",
summary: "Read the session log",
description:
"Experimental durable session event log. Reads events after an exclusive aggregate sequence and continues with live events when follow=true.",
}),
),
)
.add(
HttpApiEndpoint.post("session.interrupt", "/api/session/:sessionID/interrupt", {
params: { sessionID: Session.ID },
query: { resume: BooleanFromString.pipe(Schema.optional) },
success: Schema.Struct({
interrupted: Schema.Boolean.annotate({
description: "Whether an active execution owned by this OpenCode process was interrupted.",
}),
}).annotate({ identifier: "SessionInterruptResponse" }),
error: SessionNotFoundError,
}).annotateMerge(
OpenApi.annotations({
identifier: "session.interrupt",
summary: "Interrupt session execution",
description:
"Interrupt active execution owned by this OpenCode process. Returns interrupted=true when an active execution was interrupted and false for the idle no-op. When resume=true, execution resumes pending steering input and next-in-line control items (manual compaction, moves) while queued prompts remain parked.",
}),
),
)
.add(
HttpApiEndpoint.post("session.background", "/api/session/:sessionID/background", {
params: { sessionID: Session.ID },
success: HttpApiSchema.NoContent,
error: SessionNotFoundError,
}).annotateMerge(
OpenApi.annotations({
identifier: "session.background",
summary: "Background blocking session tools",
description:
"Move active foreground backgroundable tools for this session into background observation. Idle requests are a no-op.",
}),
),
)
.add(
HttpApiEndpoint.get("session.message", "/api/session/:sessionID/message/:messageID", {
params: { sessionID: Session.ID, messageID: SessionMessage.ID },
success: Schema.Struct({ data: PublicSessionMessage }),
error: [SessionNotFoundError, MessageNotFoundError],
}).annotateMerge(
OpenApi.annotations({
identifier: "session.message.get",
summary: "Get session message",
description: "Retrieve one projected message owned by the Session.",
}),
),
)
.add(
HttpApiEndpoint.get("session.form.list", "/api/session/:sessionID/form", {
params: { sessionID: Schema.String },
success: Schema.Struct({ data: Schema.Array(Form.Info) }),
error: SessionNotFoundError,
})
.middleware(formLocationMiddleware)
.annotateMerge(
OpenApi.annotations({
identifier: "session.form.list",
summary: "List session forms",
description: "Retrieve pending forms for a session.",
}),
),
)
.add(
HttpApiEndpoint.post("session.form.create", "/api/session/:sessionID/form", {
params: { sessionID: Schema.String },
payload: FormCreatePayload,
success: Schema.Struct({ data: Form.Info }),
error: [SessionNotFoundError, ConflictError, InvalidRequestError],
})
.middleware(formLocationMiddleware)
.annotateMerge(
OpenApi.annotations({
identifier: "session.form.create",
summary: "Create session form",
description: "Create a form for a session.",
}),
),
)
.add(
HttpApiEndpoint.get("session.form.get", "/api/session/:sessionID/form/:formID", {
params: { sessionID: Schema.String, formID: Form.ID },
success: Schema.Struct({ data: Form.Detail }),
error: [SessionNotFoundError, FormNotFoundError],
})
.middleware(formLocationMiddleware)
.annotateMerge(
OpenApi.annotations({
identifier: "session.form.get",
summary: "Get session form",
description: "Retrieve a form and its current state for a session.",
}),
),
)
.add(
HttpApiEndpoint.post("session.form.reply", "/api/session/:sessionID/form/:formID/reply", {
params: { sessionID: Schema.String, formID: Form.ID },
payload: Form.Reply,
success: HttpApiSchema.NoContent,
error: [SessionNotFoundError, FormAlreadySettledError, FormInvalidAnswerError, FormNotFoundError],
})
.middleware(formLocationMiddleware)
.annotateMerge(
OpenApi.annotations({
identifier: "session.form.reply",
summary: "Reply to form",
description: "Submit an answer to a pending form.",
}),
),
)
.add(
HttpApiEndpoint.delete("session.form.cancel", "/api/session/:sessionID/form/:formID", {
params: { sessionID: Schema.String, formID: Form.ID },
query: Schema.Struct({ message: Schema.optional(Schema.String) }),
success: HttpApiSchema.NoContent,
error: [SessionNotFoundError, FormAlreadySettledError, FormNotFoundError],
})
.middleware(formLocationMiddleware)
.annotateMerge(
OpenApi.annotations({
identifier: "session.form.cancel",
summary: "Cancel form",
description: "Cancel a pending form, optionally telling the asker why it was not answered.",
}),
),
)
.add(
HttpApiEndpoint.put("session.environment", "/api/session/:sessionID/environment", {
params: { sessionID: Session.ID },
payload: Schema.Struct({ variables: Schema.Record(Schema.String, Schema.String) }),
success: HttpApiSchema.NoContent,
error: SessionNotFoundError,
}).annotateMerge(
OpenApi.annotations({
identifier: "session.environment",
summary: "Set session environment",
description: "Replace the process environment used by local shell commands for this session.",
}),
),
)
.add(
HttpApiEndpoint.post("session.view", "/api/session/:sessionID/view", {
params: { sessionID: Session.ID },
payload: Schema.Struct({ idle: DateTimeUtcFromMillis }),
success: HttpApiSchema.NoContent,
error: SessionNotFoundError,
}).annotateMerge(
OpenApi.annotations({
identifier: "session.view",
summary: "View session",
description: "Mark the idle transition observed by the viewer as viewed.",
}),
),
)
.annotateMerge(
OpenApi.annotations({
title: "session",
description: "Experimental session routes.",
}),
)