Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

orchestration.ts

1,470 lines48.8 KB

1import * as Effect from "effect/Effect";
2import * as Option from "effect/Option";
3import * as Schema from "effect/Schema";
4import * as SchemaIssue from "effect/SchemaIssue";
5import * as SchemaTransformation from "effect/SchemaTransformation";
6import * as Struct from "effect/Struct";
7import { ProviderOptionSelections } from "./model.ts";
8import { RepositoryIdentity } from "./environment.ts";
9import {
10 ApprovalRequestId,
11 CheckpointRef,
12 CommandId,
13 EventId,
14 IsoDateTime,
15 MessageId,
16 NonNegativeInt,
17 ProjectId,
18 ProviderItemId,
19 ThreadId,
20 TrimmedNonEmptyString,
21 TurnId,
22} from "./baseSchemas.ts";
23import { ProviderInstanceId } from "./providerInstance.ts";
24​
25export const ORCHESTRATION_WS_METHODS = {
26 dispatchCommand: "orchestration.dispatchCommand",
27 getTurnDiff: "orchestration.getTurnDiff",
28 getThreadActivities: "orchestration.getThreadActivities",
29 getFullThreadDiff: "orchestration.getFullThreadDiff",
30 getArchivedShellSnapshot: "orchestration.getArchivedShellSnapshot",
31 subscribeShell: "orchestration.subscribeShell",
32 subscribeThread: "orchestration.subscribeThread",
33} as const;
34​
35export const ProviderApprovalPolicy = Schema.Literals([
36 "untrusted",
37 "on-failure",
38 "on-request",
39 "never",
40]);
41export type ProviderApprovalPolicy = typeof ProviderApprovalPolicy.Type;
42export const ProviderSandboxMode = Schema.Literals([
43 "read-only",
44 "workspace-write",
45 "danger-full-access",
46]);
47export type ProviderSandboxMode = typeof ProviderSandboxMode.Type;
48​
49/**
50 * `ModelSelection` — selection of a model on a configured provider instance.
51 *
52 * The routing key is `instanceId` (a user-defined slug identifying one
53 * configured provider instance). Drivers, credentials, working-directory
54 * bindings, and any other per-instance state are recovered from the
55 * runtime registry via the instance id.
56 *
57 * Wire legacy: persisted selections produced before the driver/instance
58 * split carried a `provider: <driver-id>` field instead. The schema absorbs
59 * that shape via a pre-decoding transform — `{provider, model}` is promoted
60 * to `{instanceId: defaultInstanceIdForDriver(provider), model}`. No
61 * post-decode compatibility code lives in the runtime; the transform is the
62 * only compat surface.
63 */
64const ModelSelectionWire = Schema.Struct({
65 instanceId: ProviderInstanceId,
66 model: TrimmedNonEmptyString,
67 options: Schema.optionalKey(ProviderOptionSelections),
68});
69​
70// Source shape for persisted legacy payloads. Fields are typed as
71// `Schema.Unknown` so malformed drafts still make it into the transform and
72// fail validation through the target schema (with proper error messages)
73// rather than at the source-struct layer where the error is less actionable.
74const ModelSelectionSource = Schema.Struct({
75 provider: Schema.optional(Schema.Unknown),
76 instanceId: Schema.optional(Schema.Unknown),
77 model: Schema.Unknown,
78 options: Schema.optional(Schema.Unknown),
79});
80​
81export const ModelSelection = ModelSelectionSource.pipe(
82 Schema.decodeTo(
83 ModelSelectionWire,
84 SchemaTransformation.transformOrFail({
85 decode: (raw) => {
86 // Resolve the routing key: prefer an explicit `instanceId`; fall
87 // back to promoting the legacy `provider` slug (the canonical
88 // `defaultInstanceIdForDriver` mapping) so persisted rollout-era
89 // payloads decode without data loss. The target schema brands the
90 // string as `ProviderInstanceId`.
91 const instanceIdSource =
92 raw.instanceId !== undefined
93 ? raw.instanceId
94 : typeof raw.provider === "string"
95 ? raw.provider
96 : undefined;
97 const base: Record<string, unknown> = {
98 instanceId: instanceIdSource,
99 model: raw.model,
100 };
101 if (raw.options !== undefined) base.options = raw.options;
102 return Effect.succeed(base as typeof ModelSelectionWire.Encoded);
103 },
104 encode: (value) => {
105 const base: Record<string, unknown> = {
106 model: value.model,
107 instanceId: value.instanceId,
108 };
109 if (value.options !== undefined) base.options = value.options;
110 return Effect.succeed(base as typeof ModelSelectionSource.Encoded);
111 },
112 }),
113 ),
114);
115export type ModelSelection = typeof ModelSelection.Type;
116​
117export const RuntimeMode = Schema.Literals([
118 "approval-required",
119 "auto-accept-edits",
120 "auto",
121 "full-access",
122]);
123export type RuntimeMode = typeof RuntimeMode.Type;
124export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
125export const ProviderInteractionMode = Schema.Literals(["default", "plan"]);
126export type ProviderInteractionMode = typeof ProviderInteractionMode.Type;
127export const DEFAULT_PROVIDER_INTERACTION_MODE: ProviderInteractionMode = "default";
128export const ProviderRequestKind = Schema.Literals(["command", "file-read", "file-change"]);
129export type ProviderRequestKind = typeof ProviderRequestKind.Type;
130export const AssistantDeliveryMode = Schema.Literals(["buffered", "streaming"]);
131export type AssistantDeliveryMode = typeof AssistantDeliveryMode.Type;
132export const ProviderApprovalDecision = Schema.Literals([
133 "accept",
134 "acceptForSession",
135 "decline",
136 "cancel",
137]);
138export type ProviderApprovalDecision = typeof ProviderApprovalDecision.Type;
139export const ProviderUserInputAnswers = Schema.Record(Schema.String, Schema.Unknown);
140export type ProviderUserInputAnswers = typeof ProviderUserInputAnswers.Type;
141​
142export const PROVIDER_SEND_TURN_MAX_INPUT_CHARS = 120_000;
143export const PROVIDER_SEND_TURN_MAX_ATTACHMENTS = 8;
144export const PROVIDER_SEND_TURN_MAX_IMAGE_BYTES = 10 * 1024 * 1024;
145const PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS = 14_000_000;
146const CHAT_ATTACHMENT_ID_MAX_CHARS = 128;
147// Correlation id is command id by design in this model.
148export const CorrelationId = CommandId;
149export type CorrelationId = typeof CorrelationId.Type;
150​
151const ChatAttachmentId = TrimmedNonEmptyString.check(
152 Schema.isMaxLength(CHAT_ATTACHMENT_ID_MAX_CHARS),
153 Schema.isPattern(/^[a-z0-9_-]+$/i),
154);
155export type ChatAttachmentId = typeof ChatAttachmentId.Type;
156​
157export const ChatImageAttachment = Schema.Struct({
158 type: Schema.Literal("image"),
159 id: ChatAttachmentId,
160 name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
161 mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100), Schema.isPattern(/^image\//i)),
162 sizeBytes: NonNegativeInt.check(Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES)),
163});
164export type ChatImageAttachment = typeof ChatImageAttachment.Type;
165​
166const UploadChatImageAttachment = Schema.Struct({
167 type: Schema.Literal("image"),
168 name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
169 mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100), Schema.isPattern(/^image\//i)),
170 sizeBytes: NonNegativeInt.check(Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES)),
171 dataUrl: TrimmedNonEmptyString.check(
172 Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS),
173 ),
174});
175export type UploadChatImageAttachment = typeof UploadChatImageAttachment.Type;
176​
177export const ChatAttachment = Schema.Union([ChatImageAttachment]);
178export type ChatAttachment = typeof ChatAttachment.Type;
179const UploadChatAttachment = Schema.Union([UploadChatImageAttachment]);
180export type UploadChatAttachment = typeof UploadChatAttachment.Type;
181​
182export const ProjectScriptIcon = Schema.Literals([
183 "play",
184 "test",
185 "lint",
186 "configure",
187 "build",
188 "debug",
189]);
190export type ProjectScriptIcon = typeof ProjectScriptIcon.Type;
191​
192export const ProjectScript = Schema.Struct({
193 id: TrimmedNonEmptyString,
194 name: TrimmedNonEmptyString,
195 command: TrimmedNonEmptyString,
196 icon: ProjectScriptIcon,
197 runOnWorktreeCreate: Schema.Boolean,
198 /**
199 * URL to open in the in-app browser preview when this script runs (or
200 * when the user explicitly requests a preview). Optional; only honored on
201 * the desktop build.
202 */
203 previewUrl: Schema.optional(TrimmedNonEmptyString),
204 /**
205 * When true, automatically open the preview panel pointed at `previewUrl`
206 * the moment this script starts. Ignored without `previewUrl` or on web.
207 */
208 autoOpenPreview: Schema.optional(Schema.Boolean),
209});
210export type ProjectScript = typeof ProjectScript.Type;
211​
212export const OrchestrationProject = Schema.Struct({
213 id: ProjectId,
214 title: TrimmedNonEmptyString,
215 workspaceRoot: TrimmedNonEmptyString,
216 repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),
217 defaultModelSelection: Schema.NullOr(ModelSelection),
218 scripts: Schema.Array(ProjectScript),
219 createdAt: IsoDateTime,
220 updatedAt: IsoDateTime,
221 deletedAt: Schema.NullOr(IsoDateTime),
222});
223export type OrchestrationProject = typeof OrchestrationProject.Type;
224​
225export const OrchestrationMessageRole = Schema.Literals(["user", "assistant", "system"]);
226export type OrchestrationMessageRole = typeof OrchestrationMessageRole.Type;
227​
228export const OrchestrationMessage = Schema.Struct({
229 id: MessageId,
230 role: OrchestrationMessageRole,
231 text: Schema.String,
232 attachments: Schema.optional(Schema.Array(ChatAttachment)),
233 turnId: Schema.NullOr(TurnId),
234 streaming: Schema.Boolean,
235 createdAt: IsoDateTime,
236 updatedAt: IsoDateTime,
237});
238export type OrchestrationMessage = typeof OrchestrationMessage.Type;
239​
240export const OrchestrationProposedPlanId = TrimmedNonEmptyString;
241export type OrchestrationProposedPlanId = typeof OrchestrationProposedPlanId.Type;
242​
243export const OrchestrationProposedPlan = Schema.Struct({
244 id: OrchestrationProposedPlanId,
245 turnId: Schema.NullOr(TurnId),
246 planMarkdown: TrimmedNonEmptyString,
247 implementedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
248 implementationThreadId: Schema.NullOr(ThreadId).pipe(
249 Schema.withDecodingDefault(Effect.succeed(null)),
250 ),
251 createdAt: IsoDateTime,
252 updatedAt: IsoDateTime,
253});
254export type OrchestrationProposedPlan = typeof OrchestrationProposedPlan.Type;
255​
256const SourceProposedPlanReference = Schema.Struct({
257 threadId: ThreadId,
258 planId: OrchestrationProposedPlanId,
259});
260​
261export const OrchestrationSessionStatus = Schema.Literals([
262 "idle",
263 "starting",
264 "running",
265 "ready",
266 "interrupted",
267 "stopped",
268 "error",
269]);
270export type OrchestrationSessionStatus = typeof OrchestrationSessionStatus.Type;
271​
272export const OrchestrationSession = Schema.Struct({
273 threadId: ThreadId,
274 status: OrchestrationSessionStatus,
275 providerName: Schema.NullOr(TrimmedNonEmptyString),
276 providerInstanceId: Schema.optional(ProviderInstanceId),
277 runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_RUNTIME_MODE))),
278 activeTurnId: Schema.NullOr(TurnId),
279 lastError: Schema.NullOr(TrimmedNonEmptyString),
280 updatedAt: IsoDateTime,
281});
282export type OrchestrationSession = typeof OrchestrationSession.Type;
283​
284export const OrchestrationCheckpointFile = Schema.Struct({
285 path: TrimmedNonEmptyString,
286 kind: TrimmedNonEmptyString,
287 additions: NonNegativeInt,
288 deletions: NonNegativeInt,
289});
290export type OrchestrationCheckpointFile = typeof OrchestrationCheckpointFile.Type;
291​
292export const OrchestrationCheckpointStatus = Schema.Literals(["ready", "missing", "error"]);
293export type OrchestrationCheckpointStatus = typeof OrchestrationCheckpointStatus.Type;
294​
295export const OrchestrationCheckpointSummary = Schema.Struct({
296 turnId: TurnId,
297 checkpointTurnCount: NonNegativeInt,
298 checkpointRef: CheckpointRef,
299 status: OrchestrationCheckpointStatus,
300 files: Schema.Array(OrchestrationCheckpointFile),
301 assistantMessageId: Schema.NullOr(MessageId),
302 completedAt: IsoDateTime,
303});
304export type OrchestrationCheckpointSummary = typeof OrchestrationCheckpointSummary.Type;
305​
306export const OrchestrationThreadActivityTone = Schema.Literals([
307 "info",
308 "tool",
309 "approval",
310 "error",
311]);
312export type OrchestrationThreadActivityTone = typeof OrchestrationThreadActivityTone.Type;
313​
314export const OrchestrationThreadActivity = Schema.Struct({
315 id: EventId,
316 tone: OrchestrationThreadActivityTone,
317 kind: TrimmedNonEmptyString,
318 summary: TrimmedNonEmptyString,
319 payload: Schema.Unknown,
320 turnId: Schema.NullOr(TurnId),
321 sequence: Schema.optional(NonNegativeInt),
322 createdAt: IsoDateTime,
323});
324export type OrchestrationThreadActivity = typeof OrchestrationThreadActivity.Type;
325​
326const OrchestrationLatestTurnState = Schema.Literals([
327 "running",
328 "interrupted",
329 "completed",
330 "error",
331]);
332export type OrchestrationLatestTurnState = typeof OrchestrationLatestTurnState.Type;
333​
334export const OrchestrationLatestTurn = Schema.Struct({
335 turnId: TurnId,
336 state: OrchestrationLatestTurnState,
337 requestedAt: IsoDateTime,
338 startedAt: Schema.NullOr(IsoDateTime),
339 completedAt: Schema.NullOr(IsoDateTime),
340 assistantMessageId: Schema.NullOr(MessageId),
341 sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
342});
343export type OrchestrationLatestTurn = typeof OrchestrationLatestTurn.Type;
344​
345export const OrchestrationThread = Schema.Struct({
346 id: ThreadId,
347 projectId: ProjectId,
348 title: TrimmedNonEmptyString,
349 modelSelection: ModelSelection,
350 runtimeMode: RuntimeMode,
351 interactionMode: ProviderInteractionMode.pipe(
352 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),
353 ),
354 branch: Schema.NullOr(TrimmedNonEmptyString),
355 worktreePath: Schema.NullOr(TrimmedNonEmptyString),
356 latestTurn: Schema.NullOr(OrchestrationLatestTurn),
357 createdAt: IsoDateTime,
358 updatedAt: IsoDateTime,
359 archivedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
360 settledOverride: Schema.NullOr(Schema.Literals(["settled", "active"])).pipe(
361 Schema.withDecodingDefault(Effect.succeed(null)),
362 ),
363 settledAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
364 // Snooze is an overlay on the active lifecycle, not a fourth destination:
365 // a snoozed thread stays "active" in the model and is only suppressed from
366 // the inbox until snoozedUntil passes (or the thread raises its hand).
367 // Optional so payloads from pre-snooze servers still decode.
368 snoozedUntil: Schema.optional(Schema.NullOr(IsoDateTime)),
369 snoozedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
370 deletedAt: Schema.NullOr(IsoDateTime),
371 messages: Schema.Array(OrchestrationMessage),
372 proposedPlans: Schema.Array(OrchestrationProposedPlan).pipe(
373 Schema.withDecodingDefault(Effect.succeed([])),
374 ),
375 activities: Schema.Array(OrchestrationThreadActivity),
376 // The detail snapshot windows `activities` to the most recent page; this is
377 // true when older activities exist beyond the window and can be lazy-loaded
378 // via the getThreadActivities RPC. Absent on lightweight (shell) threads.
379 hasMoreActivities: Schema.optional(Schema.Boolean),
380 checkpoints: Schema.Array(OrchestrationCheckpointSummary),
381 session: Schema.NullOr(OrchestrationSession),
382});
383export type OrchestrationThread = typeof OrchestrationThread.Type;
384​
385export const OrchestrationReadModel = Schema.Struct({
386 snapshotSequence: NonNegativeInt,
387 projects: Schema.Array(OrchestrationProject),
388 threads: Schema.Array(OrchestrationThread),
389 updatedAt: IsoDateTime,
390});
391export type OrchestrationReadModel = typeof OrchestrationReadModel.Type;
392​
393export const OrchestrationProjectShell = Schema.Struct({
394 id: ProjectId,
395 title: TrimmedNonEmptyString,
396 workspaceRoot: TrimmedNonEmptyString,
397 repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),
398 defaultModelSelection: Schema.NullOr(ModelSelection),
399 scripts: Schema.Array(ProjectScript),
400 createdAt: IsoDateTime,
401 updatedAt: IsoDateTime,
402});
403export type OrchestrationProjectShell = typeof OrchestrationProjectShell.Type;
404​
405export const OrchestrationThreadShell = Schema.Struct({
406 id: ThreadId,
407 projectId: ProjectId,
408 title: TrimmedNonEmptyString,
409 modelSelection: ModelSelection,
410 runtimeMode: RuntimeMode,
411 interactionMode: ProviderInteractionMode.pipe(
412 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),
413 ),
414 branch: Schema.NullOr(TrimmedNonEmptyString),
415 worktreePath: Schema.NullOr(TrimmedNonEmptyString),
416 latestTurn: Schema.NullOr(OrchestrationLatestTurn),
417 createdAt: IsoDateTime,
418 updatedAt: IsoDateTime,
419 archivedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
420 settledOverride: Schema.NullOr(Schema.Literals(["settled", "active"])).pipe(
421 Schema.withDecodingDefault(Effect.succeed(null)),
422 ),
423 settledAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
424 snoozedUntil: Schema.optional(Schema.NullOr(IsoDateTime)),
425 snoozedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
426 session: Schema.NullOr(OrchestrationSession),
427 latestUserMessageAt: Schema.NullOr(IsoDateTime),
428 hasPendingApprovals: Schema.Boolean,
429 hasPendingUserInput: Schema.Boolean,
430 hasActionableProposedPlan: Schema.Boolean,
431});
432export type OrchestrationThreadShell = typeof OrchestrationThreadShell.Type;
433​
434export const OrchestrationShellSnapshot = Schema.Struct({
435 snapshotSequence: NonNegativeInt,
436 projects: Schema.Array(OrchestrationProjectShell),
437 threads: Schema.Array(OrchestrationThreadShell),
438 updatedAt: IsoDateTime,
439});
440export type OrchestrationShellSnapshot = typeof OrchestrationShellSnapshot.Type;
441​
442export const OrchestrationShellStreamEvent = Schema.Union([
443 Schema.Struct({
444 kind: Schema.Literal("project-upserted"),
445 sequence: NonNegativeInt,
446 project: OrchestrationProjectShell,
447 }),
448 Schema.Struct({
449 kind: Schema.Literal("project-removed"),
450 sequence: NonNegativeInt,
451 projectId: ProjectId,
452 }),
453 Schema.Struct({
454 kind: Schema.Literal("thread-upserted"),
455 sequence: NonNegativeInt,
456 thread: OrchestrationThreadShell,
457 }),
458 Schema.Struct({
459 kind: Schema.Literal("thread-removed"),
460 sequence: NonNegativeInt,
461 threadId: ThreadId,
462 }),
463]);
464export type OrchestrationShellStreamEvent = typeof OrchestrationShellStreamEvent.Type;
465​
466export const OrchestrationShellStreamItem = Schema.Union([
467 Schema.Struct({
468 kind: Schema.Literal("synchronized"),
469 }),
470 Schema.Struct({
471 kind: Schema.Literal("snapshot"),
472 snapshot: OrchestrationShellSnapshot,
473 }),
474 OrchestrationShellStreamEvent,
475]);
476export type OrchestrationShellStreamItem = typeof OrchestrationShellStreamItem.Type;
477​
478export const OrchestrationSubscribeShellInput = Schema.Struct({
479 /**
480 * When provided, the server skips the initial full shell snapshot and instead
481 * replays shell events after this sequence before streaming live events.
482 * Clients that already hold a cached (or HTTP-loaded) shell snapshot pass its
483 * sequence here so the subscription resumes without re-sending the entire
484 * projects/threads list (overlapping events are deduped by sequence on the
485 * client).
486 */
487 afterSequence: Schema.optionalKey(NonNegativeInt),
488 /**
489 * Requests an explicit marker after the subscription has emitted its initial
490 * snapshot or catch-up replay and before it begins emitting live events.
491 */
492 requestCompletionMarker: Schema.optionalKey(Schema.Boolean),
493});
494export type OrchestrationSubscribeShellInput = typeof OrchestrationSubscribeShellInput.Type;
495​
496export const OrchestrationSubscribeThreadInput = Schema.Struct({
497 threadId: ThreadId,
498 /**
499 * When provided, the server skips the initial snapshot frame and instead
500 * replays events after this sequence before streaming live events. Clients
501 * that load the snapshot over HTTP pass the snapshot's sequence here so the
502 * live subscription resumes without a gap (overlapping events are deduped by
503 * sequence on the client).
504 */
505 afterSequence: Schema.optionalKey(NonNegativeInt),
506 /**
507 * Requests an explicit marker after the subscription has emitted its initial
508 * snapshot or catch-up replay and before it begins emitting live events.
509 */
510 requestCompletionMarker: Schema.optionalKey(Schema.Boolean),
511});
512export type OrchestrationSubscribeThreadInput = typeof OrchestrationSubscribeThreadInput.Type;
513​
514export const OrchestrationThreadDetailSnapshot = Schema.Struct({
515 snapshotSequence: NonNegativeInt,
516 thread: OrchestrationThread,
517});
518export type OrchestrationThreadDetailSnapshot = typeof OrchestrationThreadDetailSnapshot.Type;
519​
520export const ProjectCreateCommand = Schema.Struct({
521 type: Schema.Literal("project.create"),
522 commandId: CommandId,
523 projectId: ProjectId,
524 title: TrimmedNonEmptyString,
525 workspaceRoot: TrimmedNonEmptyString,
526 createWorkspaceRootIfMissing: Schema.optional(Schema.Boolean),
527 defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
528 createdAt: IsoDateTime,
529});
530​
531const ProjectMetaUpdateCommand = Schema.Struct({
532 type: Schema.Literal("project.meta.update"),
533 commandId: CommandId,
534 projectId: ProjectId,
535 title: Schema.optional(TrimmedNonEmptyString),
536 workspaceRoot: Schema.optional(TrimmedNonEmptyString),
537 defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
538 scripts: Schema.optional(Schema.Array(ProjectScript)),
539});
540​
541const ProjectDeleteCommand = Schema.Struct({
542 type: Schema.Literal("project.delete"),
543 commandId: CommandId,
544 projectId: ProjectId,
545 force: Schema.optional(Schema.Boolean),
546});
547​
548const ThreadCreateCommand = Schema.Struct({
549 type: Schema.Literal("thread.create"),
550 commandId: CommandId,
551 threadId: ThreadId,
552 projectId: ProjectId,
553 title: TrimmedNonEmptyString,
554 modelSelection: ModelSelection,
555 runtimeMode: RuntimeMode,
556 interactionMode: ProviderInteractionMode.pipe(
557 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),
558 ),
559 branch: Schema.NullOr(TrimmedNonEmptyString),
560 worktreePath: Schema.NullOr(TrimmedNonEmptyString),
561 createdAt: IsoDateTime,
562});
563​
564const ThreadDeleteCommand = Schema.Struct({
565 type: Schema.Literal("thread.delete"),
566 commandId: CommandId,
567 threadId: ThreadId,
568});
569​
570const ThreadArchiveCommand = Schema.Struct({
571 type: Schema.Literal("thread.archive"),
572 commandId: CommandId,
573 threadId: ThreadId,
574});
575​
576const ThreadUnarchiveCommand = Schema.Struct({
577 type: Schema.Literal("thread.unarchive"),
578 commandId: CommandId,
579 threadId: ThreadId,
580});
581​
582const ThreadSettleCommand = Schema.Struct({
583 type: Schema.Literal("thread.settle"),
584 commandId: CommandId,
585 threadId: ThreadId,
586});
587​
588const ThreadUnsettleCommand = Schema.Struct({
589 type: Schema.Literal("thread.unsettle"),
590 commandId: CommandId,
591 threadId: ThreadId,
592 // Commands only carry "user": activity un-settles are decided server-side
593 // (the decider emits thread.unsettled(reason: "activity") events directly,
594 // never through this command), so a client cannot forge the neutral reset.
595 reason: Schema.Literal("user"),
596});
597​
598const ThreadSnoozeCommand = Schema.Struct({
599 type: Schema.Literal("thread.snooze"),
600 commandId: CommandId,
601 threadId: ThreadId,
602 // The wake time. Event-based wake conditions (PR merged, review posted)
603 // will arrive as an optional condition field alongside this; time-based
604 // snooze is just the first kind of condition.
605 snoozedUntil: IsoDateTime,
606});
607​
608const ThreadUnsnoozeCommand = Schema.Struct({
609 type: Schema.Literal("thread.unsnooze"),
610 commandId: CommandId,
611 threadId: ThreadId,
612 // Commands only carry "user": activity wakes are decided server-side (the
613 // decider emits thread.unsnoozed(reason: "activity") directly), and timer
614 // wakes need no event at all — clients derive visibility from snoozedUntil,
615 // so a passed wake time simply stops classifying as snoozed.
616 reason: Schema.Literal("user"),
617});
618​
619const ThreadMetaUpdateCommand = Schema.Struct({
620 type: Schema.Literal("thread.meta.update"),
621 commandId: CommandId,
622 threadId: ThreadId,
623 title: Schema.optional(TrimmedNonEmptyString),
624 modelSelection: Schema.optional(ModelSelection),
625 branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
626 expectedBranch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
627 worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
628});
629​
630const ThreadRuntimeModeSetCommand = Schema.Struct({
631 type: Schema.Literal("thread.runtime-mode.set"),
632 commandId: CommandId,
633 threadId: ThreadId,
634 runtimeMode: RuntimeMode,
635 createdAt: IsoDateTime,
636});
637​
638const ThreadInteractionModeSetCommand = Schema.Struct({
639 type: Schema.Literal("thread.interaction-mode.set"),
640 commandId: CommandId,
641 threadId: ThreadId,
642 interactionMode: ProviderInteractionMode,
643 createdAt: IsoDateTime,
644});
645​
646const ThreadTurnStartBootstrapCreateThread = Schema.Struct({
647 projectId: ProjectId,
648 title: TrimmedNonEmptyString,
649 modelSelection: ModelSelection,
650 runtimeMode: RuntimeMode,
651 interactionMode: ProviderInteractionMode,
652 branch: Schema.NullOr(TrimmedNonEmptyString),
653 worktreePath: Schema.NullOr(TrimmedNonEmptyString),
654 createdAt: IsoDateTime,
655});
656​
657const ThreadTurnStartBootstrapPrepareWorktree = Schema.Struct({
658 projectCwd: TrimmedNonEmptyString,
659 baseBranch: TrimmedNonEmptyString,
660 branch: Schema.optional(TrimmedNonEmptyString),
661 startFromOrigin: Schema.optional(Schema.Boolean),
662});
663​
664const ThreadTurnStartBootstrap = Schema.Struct({
665 createThread: Schema.optional(ThreadTurnStartBootstrapCreateThread),
666 prepareWorktree: Schema.optional(ThreadTurnStartBootstrapPrepareWorktree),
667 runSetupScript: Schema.optional(Schema.Boolean),
668});
669​
670export type ThreadTurnStartBootstrap = typeof ThreadTurnStartBootstrap.Type;
671​
672export const ThreadTurnStartCommand = Schema.Struct({
673 type: Schema.Literal("thread.turn.start"),
674 commandId: CommandId,
675 threadId: ThreadId,
676 message: Schema.Struct({
677 messageId: MessageId,
678 role: Schema.Literal("user"),
679 text: Schema.String,
680 attachments: Schema.Array(ChatAttachment),
681 }),
682 modelSelection: Schema.optional(ModelSelection),
683 titleSeed: Schema.optional(TrimmedNonEmptyString),
684 runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_RUNTIME_MODE))),
685 interactionMode: ProviderInteractionMode.pipe(
686 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),
687 ),
688 bootstrap: Schema.optional(ThreadTurnStartBootstrap),
689 sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
690 createdAt: IsoDateTime,
691});
692​
693const ClientThreadTurnStartCommand = Schema.Struct({
694 type: Schema.Literal("thread.turn.start"),
695 commandId: CommandId,
696 threadId: ThreadId,
697 message: Schema.Struct({
698 messageId: MessageId,
699 role: Schema.Literal("user"),
700 text: Schema.String,
701 attachments: Schema.Array(UploadChatAttachment),
702 }),
703 modelSelection: Schema.optional(ModelSelection),
704 titleSeed: Schema.optional(TrimmedNonEmptyString),
705 runtimeMode: RuntimeMode,
706 interactionMode: ProviderInteractionMode,
707 bootstrap: Schema.optional(ThreadTurnStartBootstrap),
708 sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
709 createdAt: IsoDateTime,
710});
711​
712const ThreadTurnInterruptCommand = Schema.Struct({
713 type: Schema.Literal("thread.turn.interrupt"),
714 commandId: CommandId,
715 threadId: ThreadId,
716 turnId: Schema.optional(TurnId),
717 createdAt: IsoDateTime,
718});
719​
720const ThreadApprovalRespondCommand = Schema.Struct({
721 type: Schema.Literal("thread.approval.respond"),
722 commandId: CommandId,
723 threadId: ThreadId,
724 requestId: ApprovalRequestId,
725 decision: ProviderApprovalDecision,
726 createdAt: IsoDateTime,
727});
728​
729const ThreadUserInputRespondCommand = Schema.Struct({
730 type: Schema.Literal("thread.user-input.respond"),
731 commandId: CommandId,
732 threadId: ThreadId,
733 requestId: ApprovalRequestId,
734 answers: ProviderUserInputAnswers,
735 createdAt: IsoDateTime,
736});
737​
738const ThreadCheckpointRevertCommand = Schema.Struct({
739 type: Schema.Literal("thread.checkpoint.revert"),
740 commandId: CommandId,
741 threadId: ThreadId,
742 turnCount: NonNegativeInt,
743 createdAt: IsoDateTime,
744});
745​
746const ThreadSessionStopCommand = Schema.Struct({
747 type: Schema.Literal("thread.session.stop"),
748 commandId: CommandId,
749 threadId: ThreadId,
750 createdAt: IsoDateTime,
751});
752​
753const DispatchableClientOrchestrationCommand = Schema.Union([
754 ProjectCreateCommand,
755 ProjectMetaUpdateCommand,
756 ProjectDeleteCommand,
757 ThreadCreateCommand,
758 ThreadDeleteCommand,
759 ThreadArchiveCommand,
760 ThreadUnarchiveCommand,
761 ThreadSettleCommand,
762 ThreadUnsettleCommand,
763 ThreadSnoozeCommand,
764 ThreadUnsnoozeCommand,
765 ThreadMetaUpdateCommand,
766 ThreadRuntimeModeSetCommand,
767 ThreadInteractionModeSetCommand,
768 ThreadTurnStartCommand,
769 ThreadTurnInterruptCommand,
770 ThreadApprovalRespondCommand,
771 ThreadUserInputRespondCommand,
772 ThreadCheckpointRevertCommand,
773 ThreadSessionStopCommand,
774]);
775export type DispatchableClientOrchestrationCommand =
776 typeof DispatchableClientOrchestrationCommand.Type;
777​
778export const ClientOrchestrationCommand = Schema.Union([
779 ProjectCreateCommand,
780 ProjectMetaUpdateCommand,
781 ProjectDeleteCommand,
782 ThreadCreateCommand,
783 ThreadDeleteCommand,
784 ThreadArchiveCommand,
785 ThreadUnarchiveCommand,
786 ThreadSettleCommand,
787 ThreadUnsettleCommand,
788 ThreadSnoozeCommand,
789 ThreadUnsnoozeCommand,
790 ThreadMetaUpdateCommand,
791 ThreadRuntimeModeSetCommand,
792 ThreadInteractionModeSetCommand,
793 ClientThreadTurnStartCommand,
794 ThreadTurnInterruptCommand,
795 ThreadApprovalRespondCommand,
796 ThreadUserInputRespondCommand,
797 ThreadCheckpointRevertCommand,
798 ThreadSessionStopCommand,
799]);
800export type ClientOrchestrationCommand = typeof ClientOrchestrationCommand.Type;
801​
802const ThreadSessionSetCommand = Schema.Struct({
803 type: Schema.Literal("thread.session.set"),
804 commandId: CommandId,
805 threadId: ThreadId,
806 session: OrchestrationSession,
807 createdAt: IsoDateTime,
808});
809​
810const ThreadMessageAssistantDeltaCommand = Schema.Struct({
811 type: Schema.Literal("thread.message.assistant.delta"),
812 commandId: CommandId,
813 threadId: ThreadId,
814 messageId: MessageId,
815 delta: Schema.String,
816 turnId: Schema.optional(TurnId),
817 createdAt: IsoDateTime,
818});
819​
820const ThreadMessageAssistantCompleteCommand = Schema.Struct({
821 type: Schema.Literal("thread.message.assistant.complete"),
822 commandId: CommandId,
823 threadId: ThreadId,
824 messageId: MessageId,
825 turnId: Schema.optional(TurnId),
826 createdAt: IsoDateTime,
827});
828​
829const ThreadProposedPlanUpsertCommand = Schema.Struct({
830 type: Schema.Literal("thread.proposed-plan.upsert"),
831 commandId: CommandId,
832 threadId: ThreadId,
833 proposedPlan: OrchestrationProposedPlan,
834 createdAt: IsoDateTime,
835});
836​
837const ThreadTurnDiffCompleteCommand = Schema.Struct({
838 type: Schema.Literal("thread.turn.diff.complete"),
839 commandId: CommandId,
840 threadId: ThreadId,
841 turnId: TurnId,
842 completedAt: IsoDateTime,
843 checkpointRef: CheckpointRef,
844 status: OrchestrationCheckpointStatus,
845 files: Schema.Array(OrchestrationCheckpointFile),
846 assistantMessageId: Schema.optional(MessageId),
847 checkpointTurnCount: NonNegativeInt,
848 createdAt: IsoDateTime,
849});
850​
851const ThreadActivityAppendCommand = Schema.Struct({
852 type: Schema.Literal("thread.activity.append"),
853 commandId: CommandId,
854 threadId: ThreadId,
855 activity: OrchestrationThreadActivity,
856 createdAt: IsoDateTime,
857});
858​
859const ThreadRevertCompleteCommand = Schema.Struct({
860 type: Schema.Literal("thread.revert.complete"),
861 commandId: CommandId,
862 threadId: ThreadId,
863 turnCount: NonNegativeInt,
864 createdAt: IsoDateTime,
865});
866​
867const InternalOrchestrationCommand = Schema.Union([
868 ThreadSessionSetCommand,
869 ThreadMessageAssistantDeltaCommand,
870 ThreadMessageAssistantCompleteCommand,
871 ThreadProposedPlanUpsertCommand,
872 ThreadTurnDiffCompleteCommand,
873 ThreadActivityAppendCommand,
874 ThreadRevertCompleteCommand,
875]);
876export type InternalOrchestrationCommand = typeof InternalOrchestrationCommand.Type;
877​
878export const OrchestrationCommand = Schema.Union([
879 DispatchableClientOrchestrationCommand,
880 InternalOrchestrationCommand,
881]);
882export type OrchestrationCommand = typeof OrchestrationCommand.Type;
883​
884export const OrchestrationEventType = Schema.Literals([
885 "project.created",
886 "project.meta-updated",
887 "project.deleted",
888 "thread.created",
889 "thread.deleted",
890 "thread.archived",
891 "thread.unarchived",
892 "thread.settled",
893 "thread.unsettled",
894 "thread.snoozed",
895 "thread.unsnoozed",
896 "thread.meta-updated",
897 "thread.runtime-mode-set",
898 "thread.interaction-mode-set",
899 "thread.message-sent",
900 "thread.turn-start-requested",
901 "thread.turn-interrupt-requested",
902 "thread.approval-response-requested",
903 "thread.user-input-response-requested",
904 "thread.checkpoint-revert-requested",
905 "thread.reverted",
906 "thread.session-stop-requested",
907 "thread.session-set",
908 "thread.proposed-plan-upserted",
909 "thread.turn-diff-completed",
910 "thread.activity-appended",
911]);
912export type OrchestrationEventType = typeof OrchestrationEventType.Type;
913​
914export const OrchestrationAggregateKind = Schema.Literals(["project", "thread"]);
915export type OrchestrationAggregateKind = typeof OrchestrationAggregateKind.Type;
916export const OrchestrationActorKind = Schema.Literals(["client", "server", "provider"]);
917​
918export const ProjectCreatedPayload = Schema.Struct({
919 projectId: ProjectId,
920 title: TrimmedNonEmptyString,
921 workspaceRoot: TrimmedNonEmptyString,
922 repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),
923 defaultModelSelection: Schema.NullOr(ModelSelection),
924 scripts: Schema.Array(ProjectScript),
925 createdAt: IsoDateTime,
926 updatedAt: IsoDateTime,
927});
928​
929export const ProjectMetaUpdatedPayload = Schema.Struct({
930 projectId: ProjectId,
931 title: Schema.optional(TrimmedNonEmptyString),
932 workspaceRoot: Schema.optional(TrimmedNonEmptyString),
933 repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),
934 defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
935 scripts: Schema.optional(Schema.Array(ProjectScript)),
936 updatedAt: IsoDateTime,
937});
938​
939export const ProjectDeletedPayload = Schema.Struct({
940 projectId: ProjectId,
941 deletedAt: IsoDateTime,
942});
943​
944export const ThreadCreatedPayload = Schema.Struct({
945 threadId: ThreadId,
946 projectId: ProjectId,
947 title: TrimmedNonEmptyString,
948 modelSelection: ModelSelection,
949 runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_RUNTIME_MODE))),
950 interactionMode: ProviderInteractionMode.pipe(
951 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),
952 ),
953 branch: Schema.NullOr(TrimmedNonEmptyString),
954 worktreePath: Schema.NullOr(TrimmedNonEmptyString),
955 createdAt: IsoDateTime,
956 updatedAt: IsoDateTime,
957});
958​
959export const ThreadDeletedPayload = Schema.Struct({
960 threadId: ThreadId,
961 deletedAt: IsoDateTime,
962});
963​
964export const ThreadArchivedPayload = Schema.Struct({
965 threadId: ThreadId,
966 archivedAt: IsoDateTime,
967 updatedAt: IsoDateTime,
968});
969​
970export const ThreadUnarchivedPayload = Schema.Struct({
971 threadId: ThreadId,
972 updatedAt: IsoDateTime,
973});
974​
975export const ThreadSettledPayload = Schema.Struct({
976 threadId: ThreadId,
977 settledAt: IsoDateTime,
978 updatedAt: IsoDateTime,
979});
980​
981export const ThreadUnsettledPayload = Schema.Struct({
982 threadId: ThreadId,
983 reason: Schema.Literals(["user", "activity"]),
984 updatedAt: IsoDateTime,
985});
986​
987export const ThreadSnoozedPayload = Schema.Struct({
988 threadId: ThreadId,
989 snoozedUntil: IsoDateTime,
990 snoozedAt: IsoDateTime,
991 updatedAt: IsoDateTime,
992});
993​
994export const ThreadUnsnoozedPayload = Schema.Struct({
995 threadId: ThreadId,
996 // user: explicit "wake now". activity: real work arrived (user message /
997 // session coming alive) and the decider cleared the snooze — mirrors
998 // thread.unsettled's activity resets. Timer wakes emit no event: clients
999 // derive them from snoozedUntil passing.
1000 reason: Schema.Literals(["user", "activity"]),
1001 updatedAt: IsoDateTime,
1002});
1003​
1004export const ThreadMetaUpdatedPayload = Schema.Struct({
1005 threadId: ThreadId,
1006 title: Schema.optional(TrimmedNonEmptyString),
1007 modelSelection: Schema.optional(ModelSelection),
1008 branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
1009 worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
1010 updatedAt: IsoDateTime,
1011});
1012​
1013export const ThreadRuntimeModeSetPayload = Schema.Struct({
1014 threadId: ThreadId,
1015 runtimeMode: RuntimeMode,
1016 updatedAt: IsoDateTime,
1017});
1018​
1019export const ThreadInteractionModeSetPayload = Schema.Struct({
1020 threadId: ThreadId,
1021 interactionMode: ProviderInteractionMode.pipe(
1022 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),
1023 ),
1024 updatedAt: IsoDateTime,
1025});
1026​
1027export const ThreadMessageSentPayload = Schema.Struct({
1028 threadId: ThreadId,
1029 messageId: MessageId,
1030 role: OrchestrationMessageRole,
1031 text: Schema.String,
1032 attachments: Schema.optional(Schema.Array(ChatAttachment)),
1033 turnId: Schema.NullOr(TurnId),
1034 streaming: Schema.Boolean,
1035 createdAt: IsoDateTime,
1036 updatedAt: IsoDateTime,
1037});
1038​
1039export const ThreadTurnStartRequestedPayload = Schema.Struct({
1040 threadId: ThreadId,
1041 messageId: MessageId,
1042 modelSelection: Schema.optional(ModelSelection),
1043 titleSeed: Schema.optional(TrimmedNonEmptyString),
1044 runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_RUNTIME_MODE))),
1045 interactionMode: ProviderInteractionMode.pipe(
1046 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),
1047 ),
1048 sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
1049 createdAt: IsoDateTime,
1050});
1051​
1052export const ThreadTurnInterruptRequestedPayload = Schema.Struct({
1053 threadId: ThreadId,
1054 turnId: Schema.optional(TurnId),
1055 createdAt: IsoDateTime,
1056});
1057​
1058export const ThreadApprovalResponseRequestedPayload = Schema.Struct({
1059 threadId: ThreadId,
1060 requestId: ApprovalRequestId,
1061 decision: ProviderApprovalDecision,
1062 createdAt: IsoDateTime,
1063});
1064​
1065const ThreadUserInputResponseRequestedPayload = Schema.Struct({
1066 threadId: ThreadId,
1067 requestId: ApprovalRequestId,
1068 answers: ProviderUserInputAnswers,
1069 createdAt: IsoDateTime,
1070});
1071​
1072export const ThreadCheckpointRevertRequestedPayload = Schema.Struct({
1073 threadId: ThreadId,
1074 turnCount: NonNegativeInt,
1075 createdAt: IsoDateTime,
1076});
1077​
1078export const ThreadRevertedPayload = Schema.Struct({
1079 threadId: ThreadId,
1080 turnCount: NonNegativeInt,
1081});
1082​
1083export const ThreadSessionStopRequestedPayload = Schema.Struct({
1084 threadId: ThreadId,
1085 createdAt: IsoDateTime,
1086});
1087​
1088export const ThreadSessionSetPayload = Schema.Struct({
1089 threadId: ThreadId,
1090 session: OrchestrationSession,
1091});
1092​
1093export const ThreadProposedPlanUpsertedPayload = Schema.Struct({
1094 threadId: ThreadId,
1095 proposedPlan: OrchestrationProposedPlan,
1096});
1097​
1098export const ThreadTurnDiffCompletedPayload = Schema.Struct({
1099 threadId: ThreadId,
1100 turnId: TurnId,
1101 checkpointTurnCount: NonNegativeInt,
1102 checkpointRef: CheckpointRef,
1103 status: OrchestrationCheckpointStatus,
1104 files: Schema.Array(OrchestrationCheckpointFile),
1105 assistantMessageId: Schema.NullOr(MessageId),
1106 completedAt: IsoDateTime,
1107});
1108​
1109export const ThreadActivityAppendedPayload = Schema.Struct({
1110 threadId: ThreadId,
1111 activity: OrchestrationThreadActivity,
1112});
1113​
1114export const OrchestrationEventMetadata = Schema.Struct({
1115 providerTurnId: Schema.optional(TrimmedNonEmptyString),
1116 providerItemId: Schema.optional(ProviderItemId),
1117 adapterKey: Schema.optional(TrimmedNonEmptyString),
1118 requestId: Schema.optional(ApprovalRequestId),
1119 ingestedAt: Schema.optional(IsoDateTime),
1120});
1121export type OrchestrationEventMetadata = typeof OrchestrationEventMetadata.Type;
1122​
1123const EventBaseFields = {
1124 sequence: NonNegativeInt,
1125 eventId: EventId,
1126 aggregateKind: OrchestrationAggregateKind,
1127 aggregateId: Schema.Union([ProjectId, ThreadId]),
1128 occurredAt: IsoDateTime,
1129 commandId: Schema.NullOr(CommandId),
1130 causationEventId: Schema.NullOr(EventId),
1131 correlationId: Schema.NullOr(CommandId),
1132 metadata: OrchestrationEventMetadata,
1133} as const;
1134​
1135export const OrchestrationEvent = Schema.Union([
1136 Schema.Struct({
1137 ...EventBaseFields,
1138 type: Schema.Literal("project.created"),
1139 payload: ProjectCreatedPayload,
1140 }),
1141 Schema.Struct({
1142 ...EventBaseFields,
1143 type: Schema.Literal("project.meta-updated"),
1144 payload: ProjectMetaUpdatedPayload,
1145 }),
1146 Schema.Struct({
1147 ...EventBaseFields,
1148 type: Schema.Literal("project.deleted"),
1149 payload: ProjectDeletedPayload,
1150 }),
1151 Schema.Struct({
1152 ...EventBaseFields,
1153 type: Schema.Literal("thread.created"),
1154 payload: ThreadCreatedPayload,
1155 }),
1156 Schema.Struct({
1157 ...EventBaseFields,
1158 type: Schema.Literal("thread.deleted"),
1159 payload: ThreadDeletedPayload,
1160 }),
1161 Schema.Struct({
1162 ...EventBaseFields,
1163 type: Schema.Literal("thread.archived"),
1164 payload: ThreadArchivedPayload,
1165 }),
1166 Schema.Struct({
1167 ...EventBaseFields,
1168 type: Schema.Literal("thread.unarchived"),
1169 payload: ThreadUnarchivedPayload,
1170 }),
1171 Schema.Struct({
1172 ...EventBaseFields,
1173 type: Schema.Literal("thread.settled"),
1174 payload: ThreadSettledPayload,
1175 }),
1176 Schema.Struct({
1177 ...EventBaseFields,
1178 type: Schema.Literal("thread.unsettled"),
1179 payload: ThreadUnsettledPayload,
1180 }),
1181 Schema.Struct({
1182 ...EventBaseFields,
1183 type: Schema.Literal("thread.snoozed"),
1184 payload: ThreadSnoozedPayload,
1185 }),
1186 Schema.Struct({
1187 ...EventBaseFields,
1188 type: Schema.Literal("thread.unsnoozed"),
1189 payload: ThreadUnsnoozedPayload,
1190 }),
1191 Schema.Struct({
1192 ...EventBaseFields,
1193 type: Schema.Literal("thread.meta-updated"),
1194 payload: ThreadMetaUpdatedPayload,
1195 }),
1196 Schema.Struct({
1197 ...EventBaseFields,
1198 type: Schema.Literal("thread.runtime-mode-set"),
1199 payload: ThreadRuntimeModeSetPayload,
1200 }),
1201 Schema.Struct({
1202 ...EventBaseFields,
1203 type: Schema.Literal("thread.interaction-mode-set"),
1204 payload: ThreadInteractionModeSetPayload,
1205 }),
1206 Schema.Struct({
1207 ...EventBaseFields,
1208 type: Schema.Literal("thread.message-sent"),
1209 payload: ThreadMessageSentPayload,
1210 }),
1211 Schema.Struct({
1212 ...EventBaseFields,
1213 type: Schema.Literal("thread.turn-start-requested"),
1214 payload: ThreadTurnStartRequestedPayload,
1215 }),
1216 Schema.Struct({
1217 ...EventBaseFields,
1218 type: Schema.Literal("thread.turn-interrupt-requested"),
1219 payload: ThreadTurnInterruptRequestedPayload,
1220 }),
1221 Schema.Struct({
1222 ...EventBaseFields,
1223 type: Schema.Literal("thread.approval-response-requested"),
1224 payload: ThreadApprovalResponseRequestedPayload,
1225 }),
1226 Schema.Struct({
1227 ...EventBaseFields,
1228 type: Schema.Literal("thread.user-input-response-requested"),
1229 payload: ThreadUserInputResponseRequestedPayload,
1230 }),
1231 Schema.Struct({
1232 ...EventBaseFields,
1233 type: Schema.Literal("thread.checkpoint-revert-requested"),
1234 payload: ThreadCheckpointRevertRequestedPayload,
1235 }),
1236 Schema.Struct({
1237 ...EventBaseFields,
1238 type: Schema.Literal("thread.reverted"),
1239 payload: ThreadRevertedPayload,
1240 }),
1241 Schema.Struct({
1242 ...EventBaseFields,
1243 type: Schema.Literal("thread.session-stop-requested"),
1244 payload: ThreadSessionStopRequestedPayload,
1245 }),
1246 Schema.Struct({
1247 ...EventBaseFields,
1248 type: Schema.Literal("thread.session-set"),
1249 payload: ThreadSessionSetPayload,
1250 }),
1251 Schema.Struct({
1252 ...EventBaseFields,
1253 type: Schema.Literal("thread.proposed-plan-upserted"),
1254 payload: ThreadProposedPlanUpsertedPayload,
1255 }),
1256 Schema.Struct({
1257 ...EventBaseFields,
1258 type: Schema.Literal("thread.turn-diff-completed"),
1259 payload: ThreadTurnDiffCompletedPayload,
1260 }),
1261 Schema.Struct({
1262 ...EventBaseFields,
1263 type: Schema.Literal("thread.activity-appended"),
1264 payload: ThreadActivityAppendedPayload,
1265 }),
1266]);
1267export type OrchestrationEvent = typeof OrchestrationEvent.Type;
1268​
1269export const OrchestrationThreadStreamItem = Schema.Union([
1270 Schema.Struct({
1271 kind: Schema.Literal("synchronized"),
1272 }),
1273 Schema.Struct({
1274 kind: Schema.Literal("snapshot"),
1275 snapshot: OrchestrationThreadDetailSnapshot,
1276 }),
1277 Schema.Struct({
1278 kind: Schema.Literal("event"),
1279 event: OrchestrationEvent,
1280 }),
1281]);
1282export type OrchestrationThreadStreamItem = typeof OrchestrationThreadStreamItem.Type;
1283​
1284export const OrchestrationCommandReceiptStatus = Schema.Literals(["accepted", "rejected"]);
1285export type OrchestrationCommandReceiptStatus = typeof OrchestrationCommandReceiptStatus.Type;
1286​
1287export const TurnCountRange = Schema.Struct({
1288 fromTurnCount: NonNegativeInt,
1289 toTurnCount: NonNegativeInt,
1290}).check(
1291 Schema.makeFilter(
1292 (input) =>
1293 input.fromTurnCount <= input.toTurnCount ||
1294 new SchemaIssue.InvalidValue(Option.some(input.fromTurnCount), {
1295 message: "fromTurnCount must be less than or equal to toTurnCount",
1296 }),
1297 { identifier: "OrchestrationTurnDiffRange" },
1298 ),
1300​
1301export const ThreadTurnDiff = TurnCountRange.mapFields(
1302 Struct.assign({
1303 threadId: ThreadId,
1304 diff: Schema.String,
1305 }),
1306 { unsafePreserveChecks: true },
1308​
1309export const ProviderSessionRuntimeStatus = Schema.Literals([
1310 "starting",
1311 "running",
1312 "stopped",
1313 "error",
1314]);
1315export type ProviderSessionRuntimeStatus = typeof ProviderSessionRuntimeStatus.Type;
1316​
1317const ProjectionThreadTurnStatus = Schema.Literals([
1318 "running",
1319 "completed",
1320 "interrupted",
1321 "error",
1322]);
1323export type ProjectionThreadTurnStatus = typeof ProjectionThreadTurnStatus.Type;
1324​
1325const ProjectionCheckpointRow = Schema.Struct({
1326 threadId: ThreadId,
1327 turnId: TurnId,
1328 checkpointTurnCount: NonNegativeInt,
1329 checkpointRef: CheckpointRef,
1330 status: OrchestrationCheckpointStatus,
1331 files: Schema.Array(OrchestrationCheckpointFile),
1332 assistantMessageId: Schema.NullOr(MessageId),
1333 completedAt: IsoDateTime,
1334});
1335export type ProjectionCheckpointRow = typeof ProjectionCheckpointRow.Type;
1336​
1337export const ProjectionPendingApprovalStatus = Schema.Literals(["pending", "resolved"]);
1338export type ProjectionPendingApprovalStatus = typeof ProjectionPendingApprovalStatus.Type;
1339​
1340export const ProjectionPendingApprovalDecision = Schema.NullOr(ProviderApprovalDecision);
1341export type ProjectionPendingApprovalDecision = typeof ProjectionPendingApprovalDecision.Type;
1342​
1343export const DispatchResult = Schema.Struct({
1344 sequence: NonNegativeInt,
1345});
1346export type DispatchResult = typeof DispatchResult.Type;
1347​
1348export const OrchestrationGetTurnDiffInput = TurnCountRange.mapFields(
1349 Struct.assign({
1350 threadId: ThreadId,
1351 ignoreWhitespace: Schema.optionalKey(Schema.Boolean),
1352 }),
1353 { unsafePreserveChecks: true },
1355export type OrchestrationGetTurnDiffInput = typeof OrchestrationGetTurnDiffInput.Type;
1356​
1357export const OrchestrationGetTurnDiffResult = ThreadTurnDiff;
1358export type OrchestrationGetTurnDiffResult = typeof OrchestrationGetTurnDiffResult.Type;
1359​
1360/**
1361 * Cursor-paginated load of a thread's OLDER activities (lazy-load / infinite
1362 * scroll). Sequenced activity uses `beforeSequence`, the `sequence` of the
1363 * oldest activity the client currently holds. Legacy unsequenced activity uses
1364 * the `(beforeCreatedAt, beforeActivityId)` pair from the oldest loaded
1365 * activity. The server returns the page of activities immediately older than the
1366 * cursor (chronological ascending) plus whether any remain beyond that.
1367 */
1368export const OrchestrationGetThreadActivitiesInput = Schema.Union([
1369 Schema.Struct({
1370 threadId: ThreadId,
1371 beforeSequence: NonNegativeInt,
1372 limit: Schema.optional(NonNegativeInt),
1373 }),
1374 Schema.Struct({
1375 threadId: ThreadId,
1376 beforeCreatedAt: IsoDateTime,
1377 beforeActivityId: EventId,
1378 limit: Schema.optional(NonNegativeInt),
1379 }),
1380]);
1381export type OrchestrationGetThreadActivitiesInput =
1382 typeof OrchestrationGetThreadActivitiesInput.Type;
1383​
1384export const OrchestrationGetThreadActivitiesResult = Schema.Struct({
1385 activities: Schema.Array(OrchestrationThreadActivity),
1386 hasMore: Schema.Boolean,
1387});
1388export type OrchestrationGetThreadActivitiesResult =
1389 typeof OrchestrationGetThreadActivitiesResult.Type;
1390​
1391export const OrchestrationGetFullThreadDiffInput = Schema.Struct({
1392 threadId: ThreadId,
1393 toTurnCount: NonNegativeInt,
1394 ignoreWhitespace: Schema.optionalKey(Schema.Boolean),
1395});
1396export type OrchestrationGetFullThreadDiffInput = typeof OrchestrationGetFullThreadDiffInput.Type;
1397​
1398export const OrchestrationGetFullThreadDiffResult = ThreadTurnDiff;
1399export type OrchestrationGetFullThreadDiffResult = typeof OrchestrationGetFullThreadDiffResult.Type;
1400​
1401export const OrchestrationRpcSchemas = {
1402 dispatchCommand: {
1403 input: ClientOrchestrationCommand,
1404 output: DispatchResult,
1405 },
1406 getTurnDiff: {
1407 input: OrchestrationGetTurnDiffInput,
1408 output: OrchestrationGetTurnDiffResult,
1409 },
1410 getThreadActivities: {
1411 input: OrchestrationGetThreadActivitiesInput,
1412 output: OrchestrationGetThreadActivitiesResult,
1413 },
1414 getFullThreadDiff: {
1415 input: OrchestrationGetFullThreadDiffInput,
1416 output: OrchestrationGetFullThreadDiffResult,
1417 },
1418 getArchivedShellSnapshot: {
1419 input: Schema.Struct({}),
1420 output: OrchestrationShellSnapshot,
1421 },
1422 subscribeThread: {
1423 input: OrchestrationSubscribeThreadInput,
1424 output: OrchestrationThreadStreamItem,
1425 },
1426 subscribeShell: {
1427 input: OrchestrationSubscribeShellInput,
1428 output: OrchestrationShellStreamItem,
1429 },
1430} as const;
1431​
1432export class OrchestrationGetSnapshotError extends Schema.TaggedErrorClass<OrchestrationGetSnapshotError>()(
1433 "OrchestrationGetSnapshotError",
1435 message: TrimmedNonEmptyString,
1436 cause: Schema.optional(Schema.Defect()),
1437 },
1438) {}
1439​
1440export class OrchestrationDispatchCommandError extends Schema.TaggedErrorClass<OrchestrationDispatchCommandError>()(
1441 "OrchestrationDispatchCommandError",
1443 message: TrimmedNonEmptyString,
1444 cause: Schema.optional(Schema.Defect()),
1445 },
1446) {}
1447​
1448export class OrchestrationGetTurnDiffError extends Schema.TaggedErrorClass<OrchestrationGetTurnDiffError>()(
1449 "OrchestrationGetTurnDiffError",
1451 message: TrimmedNonEmptyString,
1452 cause: Schema.optional(Schema.Defect()),
1453 },
1454) {}
1455​
1456export class OrchestrationGetThreadActivitiesError extends Schema.TaggedErrorClass<OrchestrationGetThreadActivitiesError>()(
1457 "OrchestrationGetThreadActivitiesError",
1459 message: TrimmedNonEmptyString,
1460 cause: Schema.optional(Schema.Defect()),
1461 },
1462) {}
1463​
1464export class OrchestrationGetFullThreadDiffError extends Schema.TaggedErrorClass<OrchestrationGetFullThreadDiffError>()(
1465 "OrchestrationGetFullThreadDiffError",
1467 message: TrimmedNonEmptyString,
1468 cause: Schema.optional(Schema.Defect()),
1469 },
1470) {}