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

orchestration.ts

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