Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as Schema from "effect/Schema";
3import * as SchemaIssue from "effect/SchemaIssue";
4import * as SchemaTransformation from "effect/SchemaTransformation";
5import * as Struct from "effect/Struct";
6import { ProviderOptionSelections } from "./model.ts";
7import { RepositoryIdentity } from "./environment.ts";
8import {
9 ApprovalRequestId,
10 CheckpointRef,
11 CommandId,
12 EventId,
13 IsoDateTime,
14 MessageId,
15 NonNegativeInt,
16 ProjectId,
17 ProviderItemId,
18 ThreadId,
19 TrimmedNonEmptyString,
20 TrimmedString,
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 getFullThreadDiff: "orchestration.getFullThreadDiff",
29 searchThreads: "orchestration.searchThreads",
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 ThreadTitleRegeneration = Schema.Struct({
346 requestId: CommandId,
347 startedAt: IsoDateTime,
348});
349export type ThreadTitleRegeneration = typeof ThreadTitleRegeneration.Type;
350
351export const OrchestrationThread = Schema.Struct({
352 id: ThreadId,
353 projectId: ProjectId,
354 title: TrimmedNonEmptyString,
355 modelSelection: ModelSelection,
356 runtimeMode: RuntimeMode,
357 interactionMode: ProviderInteractionMode.pipe(
358 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),
359 ),
360 branch: Schema.NullOr(TrimmedNonEmptyString),
361 worktreePath: Schema.NullOr(TrimmedNonEmptyString),
362 latestTurn: Schema.NullOr(OrchestrationLatestTurn),
363 createdAt: IsoDateTime,
364 updatedAt: IsoDateTime,
365 archivedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
366 settledOverride: Schema.NullOr(Schema.Literals(["settled", "active"])).pipe(
367 Schema.withDecodingDefault(Effect.succeed(null)),
368 ),
369 settledAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
370 // Snooze is an overlay on the active lifecycle, not a fourth destination:
371 // a snoozed thread stays "active" in the model and is only suppressed from
372 // the inbox until snoozedUntil passes (or the thread raises its hand).
373 // Optional so payloads from pre-snooze servers still decode.
374 snoozedUntil: Schema.optional(Schema.NullOr(IsoDateTime)),
375 snoozedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
376 // Pending-only state. Optional so older servers remain compatible.
377 titleRegeneration: Schema.optional(Schema.NullOr(ThreadTitleRegeneration)),
378 deletedAt: Schema.NullOr(IsoDateTime),
379 messages: Schema.Array(OrchestrationMessage),
380 proposedPlans: Schema.Array(OrchestrationProposedPlan).pipe(
381 Schema.withDecodingDefault(Effect.succeed([])),
382 ),
383 activities: Schema.Array(OrchestrationThreadActivity),
384 checkpoints: Schema.Array(OrchestrationCheckpointSummary),
385 session: Schema.NullOr(OrchestrationSession),
386});
387export type OrchestrationThread = typeof OrchestrationThread.Type;
388
389export const OrchestrationReadModel = Schema.Struct({
390 snapshotSequence: NonNegativeInt,
391 projects: Schema.Array(OrchestrationProject),
392 threads: Schema.Array(OrchestrationThread),
393 updatedAt: IsoDateTime,
394});
395export type OrchestrationReadModel = typeof OrchestrationReadModel.Type;
396
397export const OrchestrationProjectShell = Schema.Struct({
398 id: ProjectId,
399 title: TrimmedNonEmptyString,
400 workspaceRoot: TrimmedNonEmptyString,
401 repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),
402 defaultModelSelection: Schema.NullOr(ModelSelection),
403 scripts: Schema.Array(ProjectScript),
404 createdAt: IsoDateTime,
405 updatedAt: IsoDateTime,
406});
407export type OrchestrationProjectShell = typeof OrchestrationProjectShell.Type;
408
409export const OrchestrationThreadShell = Schema.Struct({
410 id: ThreadId,
411 projectId: ProjectId,
412 title: TrimmedNonEmptyString,
413 modelSelection: ModelSelection,
414 runtimeMode: RuntimeMode,
415 interactionMode: ProviderInteractionMode.pipe(
416 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),
417 ),
418 branch: Schema.NullOr(TrimmedNonEmptyString),
419 worktreePath: Schema.NullOr(TrimmedNonEmptyString),
420 latestTurn: Schema.NullOr(OrchestrationLatestTurn),
421 createdAt: IsoDateTime,
422 updatedAt: IsoDateTime,
423 archivedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
424 settledOverride: Schema.NullOr(Schema.Literals(["settled", "active"])).pipe(
425 Schema.withDecodingDefault(Effect.succeed(null)),
426 ),
427 settledAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
428 snoozedUntil: Schema.optional(Schema.NullOr(IsoDateTime)),
429 snoozedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
430 titleRegeneration: Schema.optional(Schema.NullOr(ThreadTitleRegeneration)),
431 session: Schema.NullOr(OrchestrationSession),
432 latestUserMessageAt: Schema.NullOr(IsoDateTime),
433 hasPendingApprovals: Schema.Boolean,
434 hasPendingUserInput: Schema.Boolean,
435 hasActionableProposedPlan: Schema.Boolean,
436});
437export type OrchestrationThreadShell = typeof OrchestrationThreadShell.Type;
438
439export const OrchestrationShellSnapshot = Schema.Struct({
440 snapshotSequence: NonNegativeInt,
441 projects: Schema.Array(OrchestrationProjectShell),
442 threads: Schema.Array(OrchestrationThreadShell),
443 updatedAt: IsoDateTime,
444});
445export type OrchestrationShellSnapshot = typeof OrchestrationShellSnapshot.Type;
446
447export const OrchestrationShellStreamEvent = Schema.Union([
448 Schema.Struct({
449 kind: Schema.Literal("project-upserted"),
450 sequence: NonNegativeInt,
451 project: OrchestrationProjectShell,
452 }),
453 Schema.Struct({
454 kind: Schema.Literal("project-removed"),
455 sequence: NonNegativeInt,
456 projectId: ProjectId,
457 }),
458 Schema.Struct({
459 kind: Schema.Literal("thread-upserted"),
460 sequence: NonNegativeInt,
461 thread: OrchestrationThreadShell,
462 }),
463 Schema.Struct({
464 kind: Schema.Literal("thread-removed"),
465 sequence: NonNegativeInt,
466 threadId: ThreadId,
467 }),
468]);
469export type OrchestrationShellStreamEvent = typeof OrchestrationShellStreamEvent.Type;
470
471export const OrchestrationShellStreamItem = Schema.Union([
472 Schema.Struct({
473 kind: Schema.Literal("synchronized"),
474 }),
475 Schema.Struct({
476 kind: Schema.Literal("snapshot"),
477 snapshot: OrchestrationShellSnapshot,
478 }),
479 OrchestrationShellStreamEvent,
480]);
481export type OrchestrationShellStreamItem = typeof OrchestrationShellStreamItem.Type;
482
483export const OrchestrationSubscribeShellInput = Schema.Struct({
484 /**
485 * When provided, the server skips the initial full shell snapshot and instead
486 * replays shell events after this sequence before streaming live events.
487 * Clients that already hold a cached (or HTTP-loaded) shell snapshot pass its
488 * sequence here so the subscription resumes without re-sending the entire
489 * projects/threads list (overlapping events are deduped by sequence on the
490 * client).
491 */
492 afterSequence: Schema.optionalKey(NonNegativeInt),
493 /**
494 * Requests an explicit marker after the subscription has emitted its initial
495 * snapshot or catch-up replay and before it begins emitting live events.
496 */
497 requestCompletionMarker: Schema.optionalKey(Schema.Boolean),
498});
499export type OrchestrationSubscribeShellInput = typeof OrchestrationSubscribeShellInput.Type;
500
501export const OrchestrationSubscribeThreadInput = Schema.Struct({
502 threadId: ThreadId,
503 /**
504 * When provided, the server skips the initial snapshot frame and instead
505 * replays events after this sequence before streaming live events. Clients
506 * that load the snapshot over HTTP pass the snapshot's sequence here so the
507 * live subscription resumes without a gap (overlapping events are deduped by
508 * sequence on the client).
509 */
510 afterSequence: Schema.optionalKey(NonNegativeInt),
511 /**
512 * Requests an explicit marker after the subscription has emitted its initial
513 * snapshot or catch-up replay and before it begins emitting live events.
514 */
515 requestCompletionMarker: Schema.optionalKey(Schema.Boolean),
516});
517export type OrchestrationSubscribeThreadInput = typeof OrchestrationSubscribeThreadInput.Type;
518
519export const OrchestrationThreadDetailSnapshot = Schema.Struct({
520 snapshotSequence: NonNegativeInt,
521 thread: OrchestrationThread,
522});
523export type OrchestrationThreadDetailSnapshot = typeof OrchestrationThreadDetailSnapshot.Type;
524
525export const ProjectCreateCommand = Schema.Struct({
526 type: Schema.Literal("project.create"),
527 commandId: CommandId,
528 projectId: ProjectId,
529 title: TrimmedNonEmptyString,
530 workspaceRoot: TrimmedNonEmptyString,
531 createWorkspaceRootIfMissing: Schema.optional(Schema.Boolean),
532 defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
533 createdAt: IsoDateTime,
534});
535
536const ProjectMetaUpdateCommand = Schema.Struct({
537 type: Schema.Literal("project.meta.update"),
538 commandId: CommandId,
539 projectId: ProjectId,
540 title: Schema.optional(TrimmedNonEmptyString),
541 workspaceRoot: Schema.optional(TrimmedNonEmptyString),
542 defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
543 scripts: Schema.optional(Schema.Array(ProjectScript)),
544});
545
546const ProjectDeleteCommand = Schema.Struct({
547 type: Schema.Literal("project.delete"),
548 commandId: CommandId,
549 projectId: ProjectId,
550 force: Schema.optional(Schema.Boolean),
551});
552
553const ThreadCreateCommand = Schema.Struct({
554 type: Schema.Literal("thread.create"),
555 commandId: CommandId,
556 threadId: ThreadId,
557 projectId: ProjectId,
558 title: TrimmedNonEmptyString,
559 modelSelection: ModelSelection,
560 runtimeMode: RuntimeMode,
561 interactionMode: ProviderInteractionMode.pipe(
562 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),
563 ),
564 branch: Schema.NullOr(TrimmedNonEmptyString),
565 worktreePath: Schema.NullOr(TrimmedNonEmptyString),
566 createdAt: IsoDateTime,
567});
568
569const ThreadDeleteCommand = Schema.Struct({
570 type: Schema.Literal("thread.delete"),
571 commandId: CommandId,
572 threadId: ThreadId,
573});
574
575const ThreadArchiveCommand = Schema.Struct({
576 type: Schema.Literal("thread.archive"),
577 commandId: CommandId,
578 threadId: ThreadId,
579});
580
581const ThreadUnarchiveCommand = Schema.Struct({
582 type: Schema.Literal("thread.unarchive"),
583 commandId: CommandId,
584 threadId: ThreadId,
585});
586
587const ThreadSettleCommand = Schema.Struct({
588 type: Schema.Literal("thread.settle"),
589 commandId: CommandId,
590 threadId: ThreadId,
591});
592
593const ThreadUnsettleCommand = Schema.Struct({
594 type: Schema.Literal("thread.unsettle"),
595 commandId: CommandId,
596 threadId: ThreadId,
597 // Commands only carry "user": activity un-settles are decided server-side
598 // (the decider emits thread.unsettled(reason: "activity") events directly,
599 // never through this command), so a client cannot forge the neutral reset.
600 reason: Schema.Literal("user"),
601});
602
603const ThreadSnoozeCommand = Schema.Struct({
604 type: Schema.Literal("thread.snooze"),
605 commandId: CommandId,
606 threadId: ThreadId,
607 // The wake time. Event-based wake conditions (PR merged, review posted)
608 // will arrive as an optional condition field alongside this; time-based
609 // snooze is just the first kind of condition.
610 snoozedUntil: IsoDateTime,
611});
612
613const ThreadUnsnoozeCommand = Schema.Struct({
614 type: Schema.Literal("thread.unsnooze"),
615 commandId: CommandId,
616 threadId: ThreadId,
617 // Commands only carry "user": activity wakes are decided server-side (the
618 // decider emits thread.unsnoozed(reason: "activity") directly), and timer
619 // wakes need no event at all — clients derive visibility from snoozedUntil,
620 // so a passed wake time simply stops classifying as snoozed.
621 reason: Schema.Literal("user"),
622});
623
624const ThreadMetaUpdateCommand = Schema.Struct({
625 type: Schema.Literal("thread.meta.update"),
626 commandId: CommandId,
627 threadId: ThreadId,
628 title: Schema.optional(TrimmedNonEmptyString),
629 regenerateTitle: Schema.optional(Schema.Literal(true)),
630 modelSelection: Schema.optional(ModelSelection),
631 branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
632 expectedBranch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
633 worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
634}).check(
635 Schema.makeFilter(
636 (input) =>
637 !(input.title !== undefined && input.regenerateTitle === true) ||
638 "title and regenerateTitle cannot be specified together",
639 ),
640);
641
642const ThreadRuntimeModeSetCommand = Schema.Struct({
643 type: Schema.Literal("thread.runtime-mode.set"),
644 commandId: CommandId,
645 threadId: ThreadId,
646 runtimeMode: RuntimeMode,
647 createdAt: IsoDateTime,
648});
649
650const ThreadInteractionModeSetCommand = Schema.Struct({
651 type: Schema.Literal("thread.interaction-mode.set"),
652 commandId: CommandId,
653 threadId: ThreadId,
654 interactionMode: ProviderInteractionMode,
655 createdAt: IsoDateTime,
656});
657
658const ThreadTurnStartBootstrapCreateThread = Schema.Struct({
659 projectId: ProjectId,
660 title: TrimmedNonEmptyString,
661 modelSelection: ModelSelection,
662 runtimeMode: RuntimeMode,
663 interactionMode: ProviderInteractionMode,
664 branch: Schema.NullOr(TrimmedNonEmptyString),
665 worktreePath: Schema.NullOr(TrimmedNonEmptyString),
666 createdAt: IsoDateTime,
667});
668
669const ThreadTurnStartBootstrapPrepareWorktree = Schema.Struct({
670 projectCwd: TrimmedNonEmptyString,
671 baseBranch: TrimmedNonEmptyString,
672 branch: Schema.optional(TrimmedNonEmptyString),
673 startFromOrigin: Schema.optional(Schema.Boolean),
674});
675
676const ThreadTurnStartBootstrap = Schema.Struct({
677 createThread: Schema.optional(ThreadTurnStartBootstrapCreateThread),
678 prepareWorktree: Schema.optional(ThreadTurnStartBootstrapPrepareWorktree),
679 runSetupScript: Schema.optional(Schema.Boolean),
680});
681
682export type ThreadTurnStartBootstrap = typeof ThreadTurnStartBootstrap.Type;
683
684export const ThreadTurnStartCommand = Schema.Struct({
685 type: Schema.Literal("thread.turn.start"),
686 commandId: CommandId,
687 threadId: ThreadId,
688 message: Schema.Struct({
689 messageId: MessageId,
690 role: Schema.Literal("user"),
691 text: Schema.String,
692 attachments: Schema.Array(ChatAttachment),
693 }),
694 modelSelection: Schema.optional(ModelSelection),
695 titleSeed: Schema.optional(TrimmedNonEmptyString),
696 runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_RUNTIME_MODE))),
697 interactionMode: ProviderInteractionMode.pipe(
698 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),
699 ),
700 bootstrap: Schema.optional(ThreadTurnStartBootstrap),
701 sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
702 createdAt: IsoDateTime,
703});
704
705const ClientThreadTurnStartCommand = Schema.Struct({
706 type: Schema.Literal("thread.turn.start"),
707 commandId: CommandId,
708 threadId: ThreadId,
709 message: Schema.Struct({
710 messageId: MessageId,
711 role: Schema.Literal("user"),
712 text: Schema.String,
713 attachments: Schema.Array(UploadChatAttachment),
714 }),
715 modelSelection: Schema.optional(ModelSelection),
716 titleSeed: Schema.optional(TrimmedNonEmptyString),
717 runtimeMode: RuntimeMode,
718 interactionMode: ProviderInteractionMode,
719 bootstrap: Schema.optional(ThreadTurnStartBootstrap),
720 sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
721 createdAt: IsoDateTime,
722});
723
724const ThreadTurnInterruptCommand = Schema.Struct({
725 type: Schema.Literal("thread.turn.interrupt"),
726 commandId: CommandId,
727 threadId: ThreadId,
728 turnId: Schema.optional(TurnId),
729 createdAt: IsoDateTime,
730});
731
732const ThreadApprovalRespondCommand = Schema.Struct({
733 type: Schema.Literal("thread.approval.respond"),
734 commandId: CommandId,
735 threadId: ThreadId,
736 requestId: ApprovalRequestId,
737 decision: ProviderApprovalDecision,
738 createdAt: IsoDateTime,
739});
740
741const ThreadUserInputRespondCommand = Schema.Struct({
742 type: Schema.Literal("thread.user-input.respond"),
743 commandId: CommandId,
744 threadId: ThreadId,
745 requestId: ApprovalRequestId,
746 answers: ProviderUserInputAnswers,
747 createdAt: IsoDateTime,
748});
749
750const ThreadCheckpointRevertCommand = Schema.Struct({
751 type: Schema.Literal("thread.checkpoint.revert"),
752 commandId: CommandId,
753 threadId: ThreadId,
754 turnCount: NonNegativeInt,
755 createdAt: IsoDateTime,
756});
757
758const ThreadSessionStopCommand = Schema.Struct({
759 type: Schema.Literal("thread.session.stop"),
760 commandId: CommandId,
761 threadId: ThreadId,
762 createdAt: IsoDateTime,
763});
764
765const DispatchableClientOrchestrationCommand = Schema.Union([
766 ProjectCreateCommand,
767 ProjectMetaUpdateCommand,
768 ProjectDeleteCommand,
769 ThreadCreateCommand,
770 ThreadDeleteCommand,
771 ThreadArchiveCommand,
772 ThreadUnarchiveCommand,
773 ThreadSettleCommand,
774 ThreadUnsettleCommand,
775 ThreadSnoozeCommand,
776 ThreadUnsnoozeCommand,
777 ThreadMetaUpdateCommand,
778 ThreadRuntimeModeSetCommand,
779 ThreadInteractionModeSetCommand,
780 ThreadTurnStartCommand,
781 ThreadTurnInterruptCommand,
782 ThreadApprovalRespondCommand,
783 ThreadUserInputRespondCommand,
784 ThreadCheckpointRevertCommand,
785 ThreadSessionStopCommand,
786]);
787export type DispatchableClientOrchestrationCommand =
788 typeof DispatchableClientOrchestrationCommand.Type;
789
790export const ClientOrchestrationCommand = Schema.Union([
791 ProjectCreateCommand,
792 ProjectMetaUpdateCommand,
793 ProjectDeleteCommand,
794 ThreadCreateCommand,
795 ThreadDeleteCommand,
796 ThreadArchiveCommand,
797 ThreadUnarchiveCommand,
798 ThreadSettleCommand,
799 ThreadUnsettleCommand,
800 ThreadSnoozeCommand,
801 ThreadUnsnoozeCommand,
802 ThreadMetaUpdateCommand,
803 ThreadRuntimeModeSetCommand,
804 ThreadInteractionModeSetCommand,
805 ClientThreadTurnStartCommand,
806 ThreadTurnInterruptCommand,
807 ThreadApprovalRespondCommand,
808 ThreadUserInputRespondCommand,
809 ThreadCheckpointRevertCommand,
810 ThreadSessionStopCommand,
811]);
812export type ClientOrchestrationCommand = typeof ClientOrchestrationCommand.Type;
813
814const ThreadSessionSetCommand = Schema.Struct({
815 type: Schema.Literal("thread.session.set"),
816 commandId: CommandId,
817 threadId: ThreadId,
818 session: OrchestrationSession,
819 createdAt: IsoDateTime,
820});
821
822const ThreadMessageAssistantDeltaCommand = Schema.Struct({
823 type: Schema.Literal("thread.message.assistant.delta"),
824 commandId: CommandId,
825 threadId: ThreadId,
826 messageId: MessageId,
827 delta: Schema.String,
828 turnId: Schema.optional(TurnId),
829 createdAt: IsoDateTime,
830});
831
832const ThreadMessageAssistantCompleteCommand = Schema.Struct({
833 type: Schema.Literal("thread.message.assistant.complete"),
834 commandId: CommandId,
835 threadId: ThreadId,
836 messageId: MessageId,
837 turnId: Schema.optional(TurnId),
838 createdAt: IsoDateTime,
839});
840
841const ThreadProposedPlanUpsertCommand = Schema.Struct({
842 type: Schema.Literal("thread.proposed-plan.upsert"),
843 commandId: CommandId,
844 threadId: ThreadId,
845 proposedPlan: OrchestrationProposedPlan,
846 createdAt: IsoDateTime,
847});
848
849const ThreadTurnDiffCompleteCommand = Schema.Struct({
850 type: Schema.Literal("thread.turn.diff.complete"),
851 commandId: CommandId,
852 threadId: ThreadId,
853 turnId: TurnId,
854 completedAt: IsoDateTime,
855 checkpointRef: CheckpointRef,
856 status: OrchestrationCheckpointStatus,
857 files: Schema.Array(OrchestrationCheckpointFile),
858 assistantMessageId: Schema.optional(MessageId),
859 checkpointTurnCount: NonNegativeInt,
860 createdAt: IsoDateTime,
861});
862
863const ThreadActivityAppendCommand = Schema.Struct({
864 type: Schema.Literal("thread.activity.append"),
865 commandId: CommandId,
866 threadId: ThreadId,
867 activity: OrchestrationThreadActivity,
868 createdAt: IsoDateTime,
869});
870
871const ThreadRevertCompleteCommand = Schema.Struct({
872 type: Schema.Literal("thread.revert.complete"),
873 commandId: CommandId,
874 threadId: ThreadId,
875 turnCount: NonNegativeInt,
876 createdAt: IsoDateTime,
877});
878
879const ThreadTitleRegenerationCompleteCommand = Schema.Struct({
880 type: Schema.Literal("thread.title.regeneration.complete"),
881 commandId: CommandId,
882 threadId: ThreadId,
883 requestId: CommandId,
884 title: Schema.optional(TrimmedNonEmptyString),
885});
886
887const InternalOrchestrationCommand = Schema.Union([
888 ThreadSessionSetCommand,
889 ThreadMessageAssistantDeltaCommand,
890 ThreadMessageAssistantCompleteCommand,
891 ThreadProposedPlanUpsertCommand,
892 ThreadTurnDiffCompleteCommand,
893 ThreadActivityAppendCommand,
894 ThreadRevertCompleteCommand,
895 ThreadTitleRegenerationCompleteCommand,
896]);
897export type InternalOrchestrationCommand = typeof InternalOrchestrationCommand.Type;
898
899export const OrchestrationCommand = Schema.Union([
900 DispatchableClientOrchestrationCommand,
901 InternalOrchestrationCommand,
902]);
903export type OrchestrationCommand = typeof OrchestrationCommand.Type;
904
905export const OrchestrationEventType = Schema.Literals([
906 "project.created",
907 "project.meta-updated",
908 "project.deleted",
909 "thread.created",
910 "thread.deleted",
911 "thread.archived",
912 "thread.unarchived",
913 "thread.settled",
914 "thread.unsettled",
915 "thread.snoozed",
916 "thread.unsnoozed",
917 "thread.meta-updated",
918 "thread.runtime-mode-set",
919 "thread.interaction-mode-set",
920 "thread.message-sent",
921 "thread.turn-start-requested",
922 "thread.turn-interrupt-requested",
923 "thread.approval-response-requested",
924 "thread.user-input-response-requested",
925 "thread.checkpoint-revert-requested",
926 "thread.reverted",
927 "thread.session-stop-requested",
928 "thread.session-set",
929 "thread.proposed-plan-upserted",
930 "thread.turn-diff-completed",
931 "thread.activity-appended",
932]);
933export type OrchestrationEventType = typeof OrchestrationEventType.Type;
934
935export const OrchestrationAggregateKind = Schema.Literals(["project", "thread"]);
936export type OrchestrationAggregateKind = typeof OrchestrationAggregateKind.Type;
937export const OrchestrationActorKind = Schema.Literals(["client", "server", "provider"]);
938
939export const ProjectCreatedPayload = Schema.Struct({
940 projectId: ProjectId,
941 title: TrimmedNonEmptyString,
942 workspaceRoot: TrimmedNonEmptyString,
943 repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),
944 defaultModelSelection: Schema.NullOr(ModelSelection),
945 scripts: Schema.Array(ProjectScript),
946 createdAt: IsoDateTime,
947 updatedAt: IsoDateTime,
948});
949
950export const ProjectMetaUpdatedPayload = Schema.Struct({
951 projectId: ProjectId,
952 title: Schema.optional(TrimmedNonEmptyString),
953 workspaceRoot: Schema.optional(TrimmedNonEmptyString),
954 repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),
955 defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
956 scripts: Schema.optional(Schema.Array(ProjectScript)),
957 updatedAt: IsoDateTime,
958});
959
960export const ProjectDeletedPayload = Schema.Struct({
961 projectId: ProjectId,
962 deletedAt: IsoDateTime,
963});
964
965export const ThreadCreatedPayload = Schema.Struct({
966 threadId: ThreadId,
967 projectId: ProjectId,
968 title: TrimmedNonEmptyString,
969 modelSelection: ModelSelection,
970 runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_RUNTIME_MODE))),
971 interactionMode: ProviderInteractionMode.pipe(
972 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),
973 ),
974 branch: Schema.NullOr(TrimmedNonEmptyString),
975 worktreePath: Schema.NullOr(TrimmedNonEmptyString),
976 createdAt: IsoDateTime,
977 updatedAt: IsoDateTime,
978});
979
980export const ThreadDeletedPayload = Schema.Struct({
981 threadId: ThreadId,
982 deletedAt: IsoDateTime,
983});
984
985export const ThreadArchivedPayload = Schema.Struct({
986 threadId: ThreadId,
987 archivedAt: IsoDateTime,
988 updatedAt: IsoDateTime,
989});
990
991export const ThreadUnarchivedPayload = Schema.Struct({
992 threadId: ThreadId,
993 updatedAt: IsoDateTime,
994});
995
996export const ThreadSettledPayload = Schema.Struct({
997 threadId: ThreadId,
998 settledAt: IsoDateTime,
999 updatedAt: IsoDateTime,
1000});
1001
1002export const ThreadUnsettledPayload = Schema.Struct({
1003 threadId: ThreadId,
1004 reason: Schema.Literals(["user", "activity"]),
1005 updatedAt: IsoDateTime,
1006});
1007
1008export const ThreadSnoozedPayload = Schema.Struct({
1009 threadId: ThreadId,
1010 snoozedUntil: IsoDateTime,
1011 snoozedAt: IsoDateTime,
1012 updatedAt: IsoDateTime,
1013});
1014
1015export const ThreadUnsnoozedPayload = Schema.Struct({
1016 threadId: ThreadId,
1017 // user: explicit "wake now". activity: real work arrived (user message /
1018 // session coming alive) and the decider cleared the snooze — mirrors
1019 // thread.unsettled's activity resets. Timer wakes emit no event: clients
1020 // derive them from snoozedUntil passing.
1021 reason: Schema.Literals(["user", "activity"]),
1022 updatedAt: IsoDateTime,
1023});
1024
1025export const ThreadMetaUpdatedPayload = Schema.Struct({
1026 threadId: ThreadId,
1027 title: Schema.optional(TrimmedNonEmptyString),
1028 /** Intent marker consumed by the title-generation reactor. Keeping this on
1029 the existing event lets older clients safely ignore the new field. */
1030 regenerateTitle: Schema.optional(Schema.Literal(true)),
1031 /** Title at request time, used to avoid overwriting a later manual rename. */
1032 previousTitle: Schema.optional(TrimmedNonEmptyString),
1033 /** Pending state shared with clients. Null clears a matching request. */
1034 titleRegeneration: Schema.optional(Schema.NullOr(ThreadTitleRegeneration)),
1035 modelSelection: Schema.optional(ModelSelection),
1036 branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
1037 worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
1038 updatedAt: IsoDateTime,
1039});
1040
1041export const ThreadRuntimeModeSetPayload = Schema.Struct({
1042 threadId: ThreadId,
1043 runtimeMode: RuntimeMode,
1044 updatedAt: IsoDateTime,
1045});
1046
1047export const ThreadInteractionModeSetPayload = Schema.Struct({
1048 threadId: ThreadId,
1049 interactionMode: ProviderInteractionMode.pipe(
1050 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),
1051 ),
1052 updatedAt: IsoDateTime,
1053});
1054
1055export const ThreadMessageSentPayload = Schema.Struct({
1056 threadId: ThreadId,
1057 messageId: MessageId,
1058 role: OrchestrationMessageRole,
1059 text: Schema.String,
1060 attachments: Schema.optional(Schema.Array(ChatAttachment)),
1061 turnId: Schema.NullOr(TurnId),
1062 streaming: Schema.Boolean,
1063 createdAt: IsoDateTime,
1064 updatedAt: IsoDateTime,
1065});
1066
1067export const ThreadTurnStartRequestedPayload = Schema.Struct({
1068 threadId: ThreadId,
1069 messageId: MessageId,
1070 modelSelection: Schema.optional(ModelSelection),
1071 titleSeed: Schema.optional(TrimmedNonEmptyString),
1072 runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_RUNTIME_MODE))),
1073 interactionMode: ProviderInteractionMode.pipe(
1074 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),
1075 ),
1076 sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
1077 createdAt: IsoDateTime,
1078});
1079
1080export const ThreadTurnInterruptRequestedPayload = Schema.Struct({
1081 threadId: ThreadId,
1082 turnId: Schema.optional(TurnId),
1083 createdAt: IsoDateTime,
1084});
1085
1086export const ThreadApprovalResponseRequestedPayload = Schema.Struct({
1087 threadId: ThreadId,
1088 requestId: ApprovalRequestId,
1089 decision: ProviderApprovalDecision,
1090 createdAt: IsoDateTime,
1091});
1092
1093const ThreadUserInputResponseRequestedPayload = Schema.Struct({
1094 threadId: ThreadId,
1095 requestId: ApprovalRequestId,
1096 answers: ProviderUserInputAnswers,
1097 createdAt: IsoDateTime,
1098});
1099
1100export const ThreadCheckpointRevertRequestedPayload = Schema.Struct({
1101 threadId: ThreadId,
1102 turnCount: NonNegativeInt,
1103 createdAt: IsoDateTime,
1104});
1105
1106export const ThreadRevertedPayload = Schema.Struct({
1107 threadId: ThreadId,
1108 turnCount: NonNegativeInt,
1109});
1110
1111export const ThreadSessionStopRequestedPayload = Schema.Struct({
1112 threadId: ThreadId,
1113 createdAt: IsoDateTime,
1114});
1115
1116export const ThreadSessionSetPayload = Schema.Struct({
1117 threadId: ThreadId,
1118 session: OrchestrationSession,
1119});
1120
1121export const ThreadProposedPlanUpsertedPayload = Schema.Struct({
1122 threadId: ThreadId,
1123 proposedPlan: OrchestrationProposedPlan,
1124});
1125
1126export const ThreadTurnDiffCompletedPayload = Schema.Struct({
1127 threadId: ThreadId,
1128 turnId: TurnId,
1129 checkpointTurnCount: NonNegativeInt,
1130 checkpointRef: CheckpointRef,
1131 status: OrchestrationCheckpointStatus,
1132 files: Schema.Array(OrchestrationCheckpointFile),
1133 assistantMessageId: Schema.NullOr(MessageId),
1134 completedAt: IsoDateTime,
1135});
1136
1137export const ThreadActivityAppendedPayload = Schema.Struct({
1138 threadId: ThreadId,
1139 activity: OrchestrationThreadActivity,
1140});
1141
1142export const OrchestrationEventMetadata = Schema.Struct({
1143 providerTurnId: Schema.optional(TrimmedNonEmptyString),
1144 providerItemId: Schema.optional(ProviderItemId),
1145 adapterKey: Schema.optional(TrimmedNonEmptyString),
1146 requestId: Schema.optional(ApprovalRequestId),
1147 ingestedAt: Schema.optional(IsoDateTime),
1148});
1149export type OrchestrationEventMetadata = typeof OrchestrationEventMetadata.Type;
1150
1151const EventBaseFields = {
1152 sequence: NonNegativeInt,
1153 eventId: EventId,
1154 aggregateKind: OrchestrationAggregateKind,
1155 aggregateId: Schema.Union([ProjectId, ThreadId]),
1156 occurredAt: IsoDateTime,
1157 commandId: Schema.NullOr(CommandId),
1158 causationEventId: Schema.NullOr(EventId),
1159 correlationId: Schema.NullOr(CommandId),
1160 metadata: OrchestrationEventMetadata,
1161} as const;
1162
1163export const OrchestrationEvent = Schema.Union([
1164 Schema.Struct({
1165 ...EventBaseFields,
1166 type: Schema.Literal("project.created"),
1167 payload: ProjectCreatedPayload,
1168 }),
1169 Schema.Struct({
1170 ...EventBaseFields,
1171 type: Schema.Literal("project.meta-updated"),
1172 payload: ProjectMetaUpdatedPayload,
1173 }),
1174 Schema.Struct({
1175 ...EventBaseFields,
1176 type: Schema.Literal("project.deleted"),
1177 payload: ProjectDeletedPayload,
1178 }),
1179 Schema.Struct({
1180 ...EventBaseFields,
1181 type: Schema.Literal("thread.created"),
1182 payload: ThreadCreatedPayload,
1183 }),
1184 Schema.Struct({
1185 ...EventBaseFields,
1186 type: Schema.Literal("thread.deleted"),
1187 payload: ThreadDeletedPayload,
1188 }),
1189 Schema.Struct({
1190 ...EventBaseFields,
1191 type: Schema.Literal("thread.archived"),
1192 payload: ThreadArchivedPayload,
1193 }),
1194 Schema.Struct({
1195 ...EventBaseFields,
1196 type: Schema.Literal("thread.unarchived"),
1197 payload: ThreadUnarchivedPayload,
1198 }),
1199 Schema.Struct({
1200 ...EventBaseFields,
1201 type: Schema.Literal("thread.settled"),
1202 payload: ThreadSettledPayload,
1203 }),
1204 Schema.Struct({
1205 ...EventBaseFields,
1206 type: Schema.Literal("thread.unsettled"),
1207 payload: ThreadUnsettledPayload,
1208 }),
1209 Schema.Struct({
1210 ...EventBaseFields,
1211 type: Schema.Literal("thread.snoozed"),
1212 payload: ThreadSnoozedPayload,
1213 }),
1214 Schema.Struct({
1215 ...EventBaseFields,
1216 type: Schema.Literal("thread.unsnoozed"),
1217 payload: ThreadUnsnoozedPayload,
1218 }),
1219 Schema.Struct({
1220 ...EventBaseFields,
1221 type: Schema.Literal("thread.meta-updated"),
1222 payload: ThreadMetaUpdatedPayload,
1223 }),
1224 Schema.Struct({
1225 ...EventBaseFields,
1226 type: Schema.Literal("thread.runtime-mode-set"),
1227 payload: ThreadRuntimeModeSetPayload,
1228 }),
1229 Schema.Struct({
1230 ...EventBaseFields,
1231 type: Schema.Literal("thread.interaction-mode-set"),
1232 payload: ThreadInteractionModeSetPayload,
1233 }),
1234 Schema.Struct({
1235 ...EventBaseFields,
1236 type: Schema.Literal("thread.message-sent"),
1237 payload: ThreadMessageSentPayload,
1238 }),
1239 Schema.Struct({
1240 ...EventBaseFields,
1241 type: Schema.Literal("thread.turn-start-requested"),
1242 payload: ThreadTurnStartRequestedPayload,
1243 }),
1244 Schema.Struct({
1245 ...EventBaseFields,
1246 type: Schema.Literal("thread.turn-interrupt-requested"),
1247 payload: ThreadTurnInterruptRequestedPayload,
1248 }),
1249 Schema.Struct({
1250 ...EventBaseFields,
1251 type: Schema.Literal("thread.approval-response-requested"),
1252 payload: ThreadApprovalResponseRequestedPayload,
1253 }),
1254 Schema.Struct({
1255 ...EventBaseFields,
1256 type: Schema.Literal("thread.user-input-response-requested"),
1257 payload: ThreadUserInputResponseRequestedPayload,
1258 }),
1259 Schema.Struct({
1260 ...EventBaseFields,
1261 type: Schema.Literal("thread.checkpoint-revert-requested"),
1262 payload: ThreadCheckpointRevertRequestedPayload,
1263 }),
1264 Schema.Struct({
1265 ...EventBaseFields,
1266 type: Schema.Literal("thread.reverted"),
1267 payload: ThreadRevertedPayload,
1268 }),
1269 Schema.Struct({
1270 ...EventBaseFields,
1271 type: Schema.Literal("thread.session-stop-requested"),
1272 payload: ThreadSessionStopRequestedPayload,
1273 }),
1274 Schema.Struct({
1275 ...EventBaseFields,
1276 type: Schema.Literal("thread.session-set"),
1277 payload: ThreadSessionSetPayload,
1278 }),
1279 Schema.Struct({
1280 ...EventBaseFields,
1281 type: Schema.Literal("thread.proposed-plan-upserted"),
1282 payload: ThreadProposedPlanUpsertedPayload,
1283 }),
1284 Schema.Struct({
1285 ...EventBaseFields,
1286 type: Schema.Literal("thread.turn-diff-completed"),
1287 payload: ThreadTurnDiffCompletedPayload,
1288 }),
1289 Schema.Struct({
1290 ...EventBaseFields,
1291 type: Schema.Literal("thread.activity-appended"),
1292 payload: ThreadActivityAppendedPayload,
1293 }),
1294]);
1295export type OrchestrationEvent = typeof OrchestrationEvent.Type;
1296
1297export const OrchestrationThreadStreamItem = Schema.Union([
1298 Schema.Struct({
1299 kind: Schema.Literal("synchronized"),
1300 }),
1301 Schema.Struct({
1302 kind: Schema.Literal("snapshot"),
1303 snapshot: OrchestrationThreadDetailSnapshot,
1304 }),
1305 Schema.Struct({
1306 kind: Schema.Literal("event"),
1307 event: OrchestrationEvent,
1308 }),
1309]);
1310export type OrchestrationThreadStreamItem = typeof OrchestrationThreadStreamItem.Type;
1311
1312export const OrchestrationCommandReceiptStatus = Schema.Literals(["accepted", "rejected"]);
1313export type OrchestrationCommandReceiptStatus = typeof OrchestrationCommandReceiptStatus.Type;
1314
1315export const TurnCountRange = Schema.Struct({
1316 fromTurnCount: NonNegativeInt,
1317 toTurnCount: NonNegativeInt,
1318}).check(
1319 Schema.makeFilter(
1320 (input) =>
1321 input.fromTurnCount <= input.toTurnCount ||
1322 new SchemaIssue.InvalidValue({
1323 message: "fromTurnCount must be less than or equal to toTurnCount",
1324 }),
1325 { identifier: "OrchestrationTurnDiffRange" },
1326 ),
1327);
1328
1329export const ThreadTurnDiff = TurnCountRange.mapFields(
1330 Struct.assign({
1331 threadId: ThreadId,
1332 diff: Schema.String,
1333 }),
1334 { unsafePreserveChecks: true },
1335);
1336
1337export const ProviderSessionRuntimeStatus = Schema.Literals([
1338 "starting",
1339 "running",
1340 "stopped",
1341 "error",
1342]);
1343export type ProviderSessionRuntimeStatus = typeof ProviderSessionRuntimeStatus.Type;
1344
1345const ProjectionThreadTurnStatus = Schema.Literals([
1346 "running",
1347 "completed",
1348 "interrupted",
1349 "error",
1350]);
1351export type ProjectionThreadTurnStatus = typeof ProjectionThreadTurnStatus.Type;
1352
1353const ProjectionCheckpointRow = Schema.Struct({
1354 threadId: ThreadId,
1355 turnId: TurnId,
1356 checkpointTurnCount: NonNegativeInt,
1357 checkpointRef: CheckpointRef,
1358 status: OrchestrationCheckpointStatus,
1359 files: Schema.Array(OrchestrationCheckpointFile),
1360 assistantMessageId: Schema.NullOr(MessageId),
1361 completedAt: IsoDateTime,
1362});
1363export type ProjectionCheckpointRow = typeof ProjectionCheckpointRow.Type;
1364
1365export const ProjectionPendingApprovalStatus = Schema.Literals(["pending", "resolved"]);
1366export type ProjectionPendingApprovalStatus = typeof ProjectionPendingApprovalStatus.Type;
1367
1368export const ProjectionPendingApprovalDecision = Schema.NullOr(ProviderApprovalDecision);
1369export type ProjectionPendingApprovalDecision = typeof ProjectionPendingApprovalDecision.Type;
1370
1371export const DispatchResult = Schema.Struct({
1372 sequence: NonNegativeInt,
1373});
1374export type DispatchResult = typeof DispatchResult.Type;
1375
1376export const OrchestrationGetTurnDiffInput = TurnCountRange.mapFields(
1377 Struct.assign({
1378 threadId: ThreadId,
1379 ignoreWhitespace: Schema.optionalKey(Schema.Boolean),
1380 }),
1381 { unsafePreserveChecks: true },
1382);
1383export type OrchestrationGetTurnDiffInput = typeof OrchestrationGetTurnDiffInput.Type;
1384
1385export const OrchestrationGetTurnDiffResult = ThreadTurnDiff;
1386export type OrchestrationGetTurnDiffResult = typeof OrchestrationGetTurnDiffResult.Type;
1387
1388export const OrchestrationGetFullThreadDiffInput = Schema.Struct({
1389 threadId: ThreadId,
1390 toTurnCount: NonNegativeInt,
1391 ignoreWhitespace: Schema.optionalKey(Schema.Boolean),
1392});
1393export type OrchestrationGetFullThreadDiffInput = typeof OrchestrationGetFullThreadDiffInput.Type;
1394
1395export const OrchestrationGetFullThreadDiffResult = ThreadTurnDiff;
1396export type OrchestrationGetFullThreadDiffResult = typeof OrchestrationGetFullThreadDiffResult.Type;
1397
1398export const OrchestrationThreadSearchSource = Schema.Literals(["user", "assistant"]);
1399export type OrchestrationThreadSearchSource = typeof OrchestrationThreadSearchSource.Type;
1400
1401// The server's SQLite client is synchronous and single-connection. Bound both
1402// scan input and response size so a search cannot monopolize that connection.
1403export const OrchestrationSearchThreadsInput = Schema.Struct({
1404 query: TrimmedString.check(Schema.isMinLength(2), Schema.isMaxLength(200)),
1405 limit: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 50 }))),
1406});
1407export type OrchestrationSearchThreadsInput = typeof OrchestrationSearchThreadsInput.Type;
1408
1409export const OrchestrationThreadSearchMatch = Schema.Struct({
1410 threadId: ThreadId,
1411 projectId: ProjectId,
1412 source: OrchestrationThreadSearchSource,
1413 snippet: Schema.String.check(Schema.isMaxLength(240)),
1414 messageCreatedAt: Schema.NullOr(IsoDateTime),
1415});
1416export type OrchestrationThreadSearchMatch = typeof OrchestrationThreadSearchMatch.Type;
1417
1418export const OrchestrationSearchThreadsResult = Schema.Struct({
1419 matches: Schema.Array(OrchestrationThreadSearchMatch),
1420});
1421export type OrchestrationSearchThreadsResult = typeof OrchestrationSearchThreadsResult.Type;
1422
1423export const OrchestrationRpcSchemas = {
1424 dispatchCommand: {
1425 input: ClientOrchestrationCommand,
1426 output: DispatchResult,
1427 },
1428 getTurnDiff: {
1429 input: OrchestrationGetTurnDiffInput,
1430 output: OrchestrationGetTurnDiffResult,
1431 },
1432 getFullThreadDiff: {
1433 input: OrchestrationGetFullThreadDiffInput,
1434 output: OrchestrationGetFullThreadDiffResult,
1435 },
1436 searchThreads: {
1437 input: OrchestrationSearchThreadsInput,
1438 output: OrchestrationSearchThreadsResult,
1439 },
1440 getArchivedShellSnapshot: {
1441 input: Schema.Struct({}),
1442 output: OrchestrationShellSnapshot,
1443 },
1444 subscribeThread: {
1445 input: OrchestrationSubscribeThreadInput,
1446 output: OrchestrationThreadStreamItem,
1447 },
1448 subscribeShell: {
1449 input: OrchestrationSubscribeShellInput,
1450 output: OrchestrationShellStreamItem,
1451 },
1452} as const;
1453
1454export class OrchestrationGetSnapshotError extends Schema.TaggedErrorClass<OrchestrationGetSnapshotError>()(
1455 "OrchestrationGetSnapshotError",
1456 {
1457 message: TrimmedNonEmptyString,
1458 cause: Schema.optional(Schema.Defect()),
1459 },
1460) {}
1461
1462export class OrchestrationDispatchCommandError extends Schema.TaggedErrorClass<OrchestrationDispatchCommandError>()(
1463 "OrchestrationDispatchCommandError",
1464 {
1465 message: TrimmedNonEmptyString,
1466 cause: Schema.optional(Schema.Defect()),
1467 },
1468) {}
1469
1470export class OrchestrationGetTurnDiffError extends Schema.TaggedErrorClass<OrchestrationGetTurnDiffError>()(
1471 "OrchestrationGetTurnDiffError",
1472 {
1473 message: TrimmedNonEmptyString,
1474 cause: Schema.optional(Schema.Defect()),
1475 },
1476) {}
1477
1478export class OrchestrationGetFullThreadDiffError extends Schema.TaggedErrorClass<OrchestrationGetFullThreadDiffError>()(
1479 "OrchestrationGetFullThreadDiffError",
1480 {
1481 message: TrimmedNonEmptyString,
1482 cause: Schema.optional(Schema.Defect()),
1483 },
1484) {}
1485
1486export class OrchestrationSearchThreadsError extends Schema.TaggedErrorClass<OrchestrationSearchThreadsError>()(
1487 "OrchestrationSearchThreadsError",
1488 {
1489 message: TrimmedNonEmptyString,
1490 cause: Schema.optional(Schema.Defect()),
1491 },
1492) {}