The best way to control Claude Code, Codex and more from any computer or phone

main
ts 4,750 lines 178 KB
Raw
1 import { OrchestrationMessageContext } from "./composerContext.ts";
2 import { withRecordIdTable } from "./orchestrationV2IdTable.ts";
3 import * as DateTime from "effect/DateTime";
4 import * as Effect from "effect/Effect";
5 import * as Schema from "effect/Schema";
6 import * as SchemaAST from "effect/SchemaAST";
7 import * as SchemaGetter from "effect/SchemaGetter";
8 import * as SchemaTransformation from "effect/SchemaTransformation";
9
10 import {
11 CheckpointId,
12 CheckpointRef,
13 CheckpointScopeId,
14 CommandId,
15 ContextHandoffId,
16 ContextTransferId,
17 EventId,
18 GuestMessageId,
19 GuestShareId,
20 IsoDateTime,
21 MessageId,
22 EnvironmentId,
23 NodeId,
24 ForwardCompatibleUnion,
25 ForwardCompatibleUnionArray,
26 hasUnknownUnionTag,
27 isUnknownUnionMember,
28 NonNegativeInt,
29 PlanId,
30 PositiveInt,
31 ProjectId,
32 ProviderSessionId,
33 ProviderThreadId,
34 ProviderTurnId,
35 RawEventId,
36 RunAttemptId,
37 RunId,
38 RuntimeRequestId,
39 ScheduledTaskId,
40 ThreadId,
41 TrimmedNonEmptyString,
42 TurnItemId,
43 } from "./baseSchemas.ts";
44 import { AuthMcpClientAccess } from "./auth.ts";
45 import { ChatAttachment } from "./chatAttachment.ts";
46 import { ThreadGuestShare } from "./guestShare.ts";
47 import { StoredThreadTags, ThreadTag } from "./threadTags.ts";
48 import { ThreadTitleRegenerationOutcome } from "./threadTitle.ts";
49 import {
50 OrchestrationSearchThreadsInput,
51 OrchestrationSearchThreadsResult,
52 } from "./threadSearch.ts";
53 import {
54 OrchestrationGetFullThreadDiffInput,
55 OrchestrationGetFullThreadDiffResult,
56 OrchestrationGetTurnDiffInput,
57 OrchestrationGetTurnDiffResult,
58 } from "./checkpointDiff.ts";
59 import { ModelSelection } from "./modelSelection.ts";
60 import { ThreadIssueKey, ThreadIssueLink, ThreadIssueLinkSource } from "./issue.ts";
61 import {
62 ThreadLinkedPullRequest,
63 ThreadPullRequestLink,
64 ThreadPullRequestKey,
65 ThreadPullRequestLinkSource,
66 ThreadPullRequestSnapshot,
67 ThreadPullRequestStack,
68 ThreadPullRequestWatch,
69 PullRequestWatchUntil,
70 } from "./threadPullRequest.ts";
71 import {
72 ProviderApprovalDecision,
73 ProviderApprovalFullAccessOverride,
74 ProviderApprovalOption,
75 ProviderInteractionMode,
76 ProviderRequestKind,
77 ProviderUserInputAnswers,
78 UserInputAttachments,
79 UserInputAttachmentAnswerPayload,
80 RuntimeMode,
81 } from "./providerPolicy.ts";
82 import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts";
83 import { OrchestrationProjectShell } from "./orchestrationProject.ts";
84 import {
85 TurnTokenUsage,
86 ToolActivitySurface,
87 ToolActivityIcon,
88 ToolActivitySource,
89 } from "./providerRuntime.ts";
90 import { ThreadTokenUsageSnapshot } from "./providerRuntime.ts";
91
92 export const OrchestrationV2Actor = Schema.Literals(["user", "agent", "system"]);
93 export type OrchestrationV2Actor = typeof OrchestrationV2Actor.Type;
94
95 export const OrchestrationV2CreationSource = Schema.Literals([
96 "web",
97 "mobile",
98 "mcp",
99 "provider",
100 "server",
101 ]);
102 export type OrchestrationV2CreationSource = typeof OrchestrationV2CreationSource.Type;
103
104 export const OrchestrationV2ThreadHistoryOrigin = Schema.Literals(["native", "v1_import"]);
105 export type OrchestrationV2ThreadHistoryOrigin = typeof OrchestrationV2ThreadHistoryOrigin.Type;
106
107 const OrchestrationV2CreationFields = {
108 createdBy: OrchestrationV2Actor,
109 creationSource: OrchestrationV2CreationSource,
110 } as const;
111
112 /**
113 * The linked environment whose agent started this work here: the MCP client
114 * session it signed in with, that session's label, and the access it was
115 * paired with. Set when the thread is created and never changed; work derived
116 * from it carries the same origin.
117 */
118 export const OrchestrationV2LinkOrigin = Schema.Struct({
119 sessionId: TrimmedNonEmptyString,
120 label: Schema.String,
121 access: Schema.optional(AuthMcpClientAccess),
122 });
123 export type OrchestrationV2LinkOrigin = typeof OrchestrationV2LinkOrigin.Type;
124
125 /**
126 * Work from a link paired below full access may change only work from the same
127 * link. A full-access link's agents already run as this environment's user,
128 * so fencing T3's own tools would stop nothing they could not do anyway. An
129 * origin stamped before access was recorded stays fenced.
130 */
131 export const linkOriginIsFenced = (origin: OrchestrationV2LinkOrigin) =>
132 origin.access !== "full-access";
133
134 /**
135 * The thread in a linked environment that delegated this one, when it did:
136 * this thread is that parent's subagent, run here instead of there.
137 */
138 export const OrchestrationV2DelegatedFrom = Schema.Struct({
139 environmentId: EnvironmentId,
140 threadId: ThreadId,
141 title: Schema.String,
142 });
143 export type OrchestrationV2DelegatedFrom = typeof OrchestrationV2DelegatedFrom.Type;
144
145 /**
146 * The thread in a linked environment whose agent sent this message here, and its title
147 * then, for a client that cannot reach that environment. `senderThreadId` names only a
148 * thread in this environment.
149 */
150 export const OrchestrationV2LinkedSender = Schema.Struct({
151 environmentId: EnvironmentId,
152 threadId: ThreadId,
153 title: Schema.String,
154 });
155 export type OrchestrationV2LinkedSender = typeof OrchestrationV2LinkedSender.Type;
156
157 export const OrchestrationV2NativeRefStrength = Schema.Literals(["strong", "weak", "none"]);
158 export type OrchestrationV2NativeRefStrength = typeof OrchestrationV2NativeRefStrength.Type;
159
160 export const OrchestrationV2ProviderRef = Schema.Struct({
161 driver: ProviderDriverKind,
162 nativeId: Schema.NullOr(TrimmedNonEmptyString),
163 strength: OrchestrationV2NativeRefStrength,
164 fingerprint: Schema.optional(TrimmedNonEmptyString),
165 ordinal: Schema.optional(NonNegativeInt),
166 });
167 export type OrchestrationV2ProviderRef = typeof OrchestrationV2ProviderRef.Type;
168
169 export const OrchestrationV2AppThreadLineage = Schema.Struct({
170 parentThreadId: Schema.NullOr(ThreadId),
171 relationshipToParent: Schema.NullOr(Schema.Literals(["fork", "subagent"])),
172 rootThreadId: ThreadId,
173 sideChat: Schema.optional(Schema.Boolean),
174 });
175 export type OrchestrationV2AppThreadLineage = typeof OrchestrationV2AppThreadLineage.Type;
176
177 /** Subagents and side chats live inside their parent's view, never in thread lists. */
178 export const isListedThreadLineage = (lineage: OrchestrationV2AppThreadLineage): boolean =>
179 lineage.relationshipToParent !== "subagent" && lineage.sideChat !== true;
180
181 export const OrchestrationV2ContextTransferType = Schema.Literals([
182 "fork",
183 "provider_handoff",
184 "merge_back",
185 "subagent_spawn",
186 "subagent_result",
187 ]);
188 export type OrchestrationV2ContextTransferType = typeof OrchestrationV2ContextTransferType.Type;
189
190 export const OrchestrationV2ContextSourcePoint = Schema.Struct({
191 threadId: ThreadId,
192 runId: Schema.optional(RunId),
193 checkpointId: Schema.optional(CheckpointId),
194 turnItemId: Schema.optional(TurnItemId),
195 providerThreadRef: Schema.optional(OrchestrationV2ProviderRef),
196 providerTurnRef: Schema.optional(OrchestrationV2ProviderRef),
197 });
198 export type OrchestrationV2ContextSourcePoint = typeof OrchestrationV2ContextSourcePoint.Type;
199
200 export const OrchestrationV2ThreadForkSourcePoint = Schema.Union([
201 Schema.Struct({ type: Schema.Literal("latest_stable") }),
202 Schema.Struct({ type: Schema.Literal("run"), runId: RunId }),
203 Schema.Struct({ type: Schema.Literal("checkpoint"), checkpointId: CheckpointId }),
204 ]);
205 export type OrchestrationV2ThreadForkSourcePoint = typeof OrchestrationV2ThreadForkSourcePoint.Type;
206
207 export const OrchestrationV2ContextTransferResolution = Schema.Union([
208 Schema.Struct({
209 strategy: Schema.Literal("native_fork"),
210 providerThreadRef: OrchestrationV2ProviderRef,
211 }),
212 Schema.Struct({
213 strategy: Schema.Literal("portable_context"),
214 contextHandoffId: ContextHandoffId,
215 }),
216 Schema.Struct({
217 strategy: Schema.Literal("delta_context"),
218 contextHandoffId: ContextHandoffId,
219 }),
220 Schema.Struct({
221 strategy: Schema.Literal("fork_delta_context"),
222 contextHandoffId: ContextHandoffId,
223 }),
224 Schema.Struct({
225 strategy: Schema.Literal("checkpoint_context"),
226 contextHandoffId: ContextHandoffId,
227 }),
228 ]);
229 export type OrchestrationV2ContextTransferResolution =
230 typeof OrchestrationV2ContextTransferResolution.Type;
231
232 export const OrchestrationV2ProviderTurnTokenUsage = Schema.Struct({
233 usedTokens: NonNegativeInt,
234 maxTokens: Schema.optional(Schema.NullOr(NonNegativeInt)),
235 inputTokens: Schema.optional(NonNegativeInt),
236 cachedInputTokens: Schema.optional(NonNegativeInt),
237 outputTokens: Schema.optional(NonNegativeInt),
238 reasoningOutputTokens: Schema.optional(NonNegativeInt),
239 promptCacheTtlMs: Schema.optional(PositiveInt),
240 autoCompactThreshold: Schema.optional(PositiveInt),
241 promptCacheExpiresAt: Schema.optional(Schema.String),
242 updatedAt: Schema.String,
243 });
244 export type OrchestrationV2ProviderTurnTokenUsage =
245 typeof OrchestrationV2ProviderTurnTokenUsage.Type;
246
247 export const OrchestrationV2ContextTransfer = Schema.Struct({
248 id: ContextTransferId,
249 type: OrchestrationV2ContextTransferType,
250 sourceThreadId: ThreadId,
251 targetThreadId: ThreadId,
252 sourcePoint: OrchestrationV2ContextSourcePoint,
253 basePoint: Schema.NullOr(OrchestrationV2ContextSourcePoint),
254 sourceProviderInstanceId: Schema.NullOr(ProviderInstanceId),
255 sourceTokenUsage: Schema.optional(OrchestrationV2ProviderTurnTokenUsage),
256 targetProviderInstanceId: Schema.NullOr(ProviderInstanceId),
257 targetRunId: Schema.NullOr(RunId),
258 status: Schema.Literals([
259 "pending",
260 "resolved_native",
261 "resolved_portable",
262 "failed",
263 "consumed",
264 "superseded",
265 ]),
266 resolution: Schema.NullOr(OrchestrationV2ContextTransferResolution),
267 createdBy: OrchestrationV2Actor,
268 error: Schema.NullOr(Schema.String),
269 createdAt: Schema.DateTimeUtc,
270 updatedAt: Schema.DateTimeUtc,
271 consumedAt: Schema.NullOr(Schema.DateTimeUtc),
272 });
273 export type OrchestrationV2ContextTransfer = typeof OrchestrationV2ContextTransfer.Type;
274
275 export const OrchestrationV2SessionCapabilities = Schema.Struct({
276 supportsMultipleProviderThreadsPerSession: Schema.Boolean,
277 supportsModelSwitchInSession: Schema.Boolean,
278 supportsProviderSwitchingViaHandoff: Schema.Boolean,
279 supportsRuntimeModeSwitchInSession: Schema.Boolean,
280 pendingRequestsSurviveRestart: Schema.Boolean,
281 });
282 export type OrchestrationV2SessionCapabilities = typeof OrchestrationV2SessionCapabilities.Type;
283
284 export const OrchestrationV2ThreadCapabilities = Schema.Struct({
285 canCreateEmptyThread: Schema.Boolean,
286 canReadThreadSnapshot: Schema.Boolean,
287 canRollbackThread: Schema.Boolean,
288 canForkThread: Schema.Boolean,
289 canForkFromTurn: Schema.Boolean,
290 // Fork from a completed turn while a later turn in the source is still running.
291 canForkWhileSourceRunning: Schema.optional(Schema.Boolean),
292 canForkFromSubagentThread: Schema.Boolean,
293 exposesNativeThreadId: Schema.Boolean,
294 });
295 export type OrchestrationV2ThreadCapabilities = typeof OrchestrationV2ThreadCapabilities.Type;
296
297 export const OrchestrationV2TurnCapabilities = Schema.Struct({
298 supportsNativeGoals: Schema.optional(Schema.Boolean),
299 exposesNativeTurnId: Schema.Boolean,
300 emitsTurnStarted: Schema.Boolean,
301 emitsTurnCompleted: Schema.Boolean,
302 supportsInterrupt: Schema.Boolean,
303 // Continues an interrupted turn without a new message; absent on sessions recorded before it existed.
304 supportsNativeResume: Schema.optional(Schema.Boolean),
305 supportsActiveSteering: Schema.Boolean,
306 // Some native steering mechanisms cancel pending tools before consuming the message.
307 activeSteeringInterruptsTools: Schema.optional(Schema.Boolean),
308 // Some take text only, so a steer with attachments restarts the turn instead.
309 activeSteeringAcceptsAttachments: Schema.optional(Schema.Boolean),
310 // Only where a steer leaves a running automatic compaction intact; otherwise clients queue.
311 activeSteeringDuringCompaction: Schema.optional(Schema.Boolean),
312 supportsSteeringByInterruptRestart: Schema.Boolean,
313 supportsQueuedMessages: Schema.Boolean,
314 terminalStatusQuality: Schema.Literals(["strong", "weak", "none"]),
315 });
316 export type OrchestrationV2TurnCapabilities = typeof OrchestrationV2TurnCapabilities.Type;
317
318 export const OrchestrationV2StreamingCapabilities = Schema.Struct({
319 streamsAssistantText: Schema.Boolean,
320 streamsReasoning: Schema.Boolean,
321 streamsToolOutput: Schema.Boolean,
322 streamsPlanText: Schema.Boolean,
323 emitsMessageCompleted: Schema.Boolean,
324 });
325 export type OrchestrationV2StreamingCapabilities = typeof OrchestrationV2StreamingCapabilities.Type;
326
327 export const OrchestrationV2ToolCapabilities = Schema.Struct({
328 exposesToolItemIds: Schema.Boolean,
329 emitsToolStarted: Schema.Boolean,
330 emitsToolCompleted: Schema.Boolean,
331 emitsToolOutput: Schema.Boolean,
332 supportsMcpTools: Schema.Boolean,
333 supportsDynamicToolCallbacks: Schema.Boolean,
334 /** The agent can mark background work it resumes from, so the thread holds as waiting. */
335 supportsBackgroundWait: Schema.optional(Schema.Boolean),
336 });
337 export type OrchestrationV2ToolCapabilities = typeof OrchestrationV2ToolCapabilities.Type;
338
339 export const OrchestrationV2ApprovalCapabilities = Schema.Struct({
340 supportsCommandApproval: Schema.Boolean,
341 supportsFileReadApproval: Schema.Boolean,
342 supportsFileChangeApproval: Schema.Boolean,
343 supportsApplyPatchApproval: Schema.Boolean,
344 approvalsHaveNativeRequestIds: Schema.Boolean,
345 approvalCallbacksAreLiveOnly: Schema.Boolean,
346 approvalsCanOriginateFromSubagents: Schema.Boolean,
347 });
348 export type OrchestrationV2ApprovalCapabilities = typeof OrchestrationV2ApprovalCapabilities.Type;
349
350 export const OrchestrationV2PlanningCapabilities = Schema.Struct({
351 emitsPlanUpdated: Schema.Boolean,
352 emitsTodoList: Schema.Boolean,
353 emitsProposedPlan: Schema.Boolean,
354 supportsStructuredQuestions: Schema.Boolean,
355 planDeltasHaveItemIds: Schema.Boolean,
356 });
357 export type OrchestrationV2PlanningCapabilities = typeof OrchestrationV2PlanningCapabilities.Type;
358
359 export const OrchestrationV2SubagentCapabilities = Schema.Struct({
360 supportsSubagents: Schema.Boolean,
361 exposesSubagentThreadIds: Schema.Boolean,
362 emitsSubagentLifecycle: Schema.Boolean,
363 canWaitForSubagents: Schema.Boolean,
364 canCloseSubagents: Schema.Boolean,
365 canForkSubagentThread: Schema.Boolean,
366 });
367 export type OrchestrationV2SubagentCapabilities = typeof OrchestrationV2SubagentCapabilities.Type;
368
369 export const OrchestrationV2ContextCapabilities = Schema.Struct({
370 acceptsSystemContext: Schema.Boolean,
371 acceptsDeveloperContext: Schema.Boolean,
372 acceptsSyntheticUserContext: Schema.Boolean,
373 canGenerateSummaries: Schema.Boolean,
374 canConsumeHandoffSummaries: Schema.Boolean,
375 supportsDeltaHandoff: Schema.Boolean,
376 supportsFullThreadHandoff: Schema.Boolean,
377 maxRecommendedHandoffChars: Schema.NullOr(PositiveInt),
378 });
379 export type OrchestrationV2ContextCapabilities = typeof OrchestrationV2ContextCapabilities.Type;
380
381 export const OrchestrationV2CheckpointCapabilities = Schema.Struct({
382 appCanCheckpointFilesystem: Schema.Boolean,
383 supportsNestedCheckpointScopes: Schema.Boolean,
384 providerCanRollbackConversation: Schema.Boolean,
385 providerRollbackReturnsSnapshot: Schema.Boolean,
386 providerCanReadConversationSnapshot: Schema.Boolean,
387 });
388 export type OrchestrationV2CheckpointCapabilities =
389 typeof OrchestrationV2CheckpointCapabilities.Type;
390
391 export const OrchestrationV2RuntimePolicyCapabilities = Schema.Struct({
392 enforcement: Schema.Literals(["native", "client-boundary"]),
393 });
394 export type OrchestrationV2RuntimePolicyCapabilities =
395 typeof OrchestrationV2RuntimePolicyCapabilities.Type;
396
397 export const OrchestrationV2IdentityCapabilities = Schema.Struct({
398 nativeThreadIds: OrchestrationV2NativeRefStrength,
399 nativeTurnIds: OrchestrationV2NativeRefStrength,
400 nativeItemIds: OrchestrationV2NativeRefStrength,
401 nativeRequestIds: OrchestrationV2NativeRefStrength,
402 });
403 export type OrchestrationV2IdentityCapabilities = typeof OrchestrationV2IdentityCapabilities.Type;
404
405 export const OrchestrationV2ProviderCapabilities = Schema.Struct({
406 sessions: OrchestrationV2SessionCapabilities,
407 threads: OrchestrationV2ThreadCapabilities,
408 turns: OrchestrationV2TurnCapabilities,
409 streaming: OrchestrationV2StreamingCapabilities,
410 tools: OrchestrationV2ToolCapabilities,
411 approvals: OrchestrationV2ApprovalCapabilities,
412 planning: OrchestrationV2PlanningCapabilities,
413 subagents: OrchestrationV2SubagentCapabilities,
414 context: OrchestrationV2ContextCapabilities,
415 checkpointing: OrchestrationV2CheckpointCapabilities,
416 identity: OrchestrationV2IdentityCapabilities,
417 // Replay defaults old events to the weaker client-boundary guarantee.
418 runtimePolicy: OrchestrationV2RuntimePolicyCapabilities.pipe(
419 Schema.withDecodingDefault(Effect.succeed({ enforcement: "client-boundary" as const })),
420 ),
421 });
422 export type OrchestrationV2ProviderCapabilities = typeof OrchestrationV2ProviderCapabilities.Type;
423
424 export const OrchestrationV2LimitRecovery = Schema.Struct({
425 requestId: Schema.optional(CommandId),
426 runId: RunId,
427 resetAt: IsoDateTime,
428 autoResume: Schema.Boolean,
429 snooze: Schema.optional(Schema.Boolean),
430 });
431 export type OrchestrationV2LimitRecovery = typeof OrchestrationV2LimitRecovery.Type;
432
433 export const OrchestrationV2LimitRecoveryUpdate = Schema.Struct({
434 runId: RunId,
435 resetAt: IsoDateTime,
436 autoResume: Schema.optional(Schema.Boolean),
437 snooze: Schema.optional(Schema.Boolean),
438 }).check(
439 Schema.makeFilter(
440 (update) =>
441 update.autoResume !== undefined ||
442 update.snooze !== undefined ||
443 "A recovery update must include autoResume or snooze.",
444 ),
445 );
446 export type OrchestrationV2LimitRecoveryUpdate = typeof OrchestrationV2LimitRecoveryUpdate.Type;
447
448 /**
449 * `score` is an open count that halves every two weeks, as of `openedAt`.
450 * `picks` stores lowercase palette queries, newest first.
451 * Times are epoch milliseconds for ranking arithmetic.
452 */
453 export const OrchestrationV2ThreadOpens = Schema.Struct({
454 openedAt: Schema.Finite,
455 score: Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0)),
456 picks: Schema.Array(
457 Schema.Struct({ query: Schema.String.check(Schema.isMaxLength(32)), at: Schema.Finite }),
458 ).check(Schema.isMaxLength(3)),
459 });
460 export type OrchestrationV2ThreadOpens = typeof OrchestrationV2ThreadOpens.Type;
461
462 // Open stats only rank search results, so a value this build cannot read (an
463 // older or newer shape) becomes null instead of failing the whole thread.
464 const LenientThreadOpens = Schema.NullOr(OrchestrationV2ThreadOpens).pipe(
465 Schema.catchDecoding(() => Effect.succeedSome(null)),
466 );
467
468 const OrchestrationV2LastTitleRegeneration = Schema.Struct({
469 ...ThreadTitleRegenerationOutcome.fields,
470 requestId: CommandId,
471 completedAt: Schema.DateTimeUtc,
472 });
473
474 export const OrchestrationV2AppThread = Schema.Struct({
475 ...OrchestrationV2CreationFields,
476 id: ThreadId,
477 projectId: ProjectId,
478 title: TrimmedNonEmptyString,
479 providerInstanceId: ProviderInstanceId,
480 modelSelection: ModelSelection,
481 runtimeMode: RuntimeMode,
482 interactionMode: ProviderInteractionMode,
483 branch: Schema.NullOr(TrimmedNonEmptyString),
484 worktreePath: Schema.NullOr(TrimmedNonEmptyString),
485 linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),
486 pullRequests: Schema.optional(Schema.Array(ThreadPullRequestLink)),
487 branchPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),
488 /** Issues linked to this thread; optional so pre-linking servers still decode. */
489 issues: Schema.optional(Schema.Array(ThreadIssueLink)),
490 activeProviderThreadId: Schema.NullOr(ProviderThreadId),
491 historyOrigin: Schema.optional(OrchestrationV2ThreadHistoryOrigin),
492 linkOrigin: Schema.optional(OrchestrationV2LinkOrigin),
493 delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom),
494 lineage: OrchestrationV2AppThreadLineage,
495 forkedFrom: Schema.NullOr(
496 Schema.Union([
497 Schema.Struct({ type: Schema.Literal("run"), threadId: ThreadId, runId: RunId }),
498 Schema.Struct({ type: Schema.Literal("node"), nodeId: NodeId }),
499 Schema.Struct({
500 type: Schema.Literal("provider_thread"),
501 providerThreadId: ProviderThreadId,
502 providerTurnId: Schema.optional(ProviderTurnId),
503 }),
504 ]),
505 ),
506 createdAt: Schema.DateTimeUtc,
507 updatedAt: Schema.DateTimeUtc,
508 archivedAt: Schema.NullOr(Schema.DateTimeUtc),
509 settledOverride: Schema.NullOr(Schema.Literals(["settled", "active"])).pipe(
510 Schema.withDecodingDefault(Effect.succeed(null)),
511 ),
512 settledAt: Schema.NullOr(Schema.DateTimeUtc).pipe(
513 Schema.withDecodingDefault(Effect.succeed(null)),
514 ),
515 unsettledAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
516 snoozedUntil: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
517 snoozedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
518 lastSnoozeWakeAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
519 limitRecovery: Schema.optional(Schema.NullOr(OrchestrationV2LimitRecovery)),
520 guestShare: Schema.optional(Schema.NullOr(ThreadGuestShare)),
521 pinnedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
522 autoSettleDisabledAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
523 pinOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
524 activeOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
525 /** Absent on threads written before tags existed; read as empty. */
526 tags: Schema.optional(StoredThreadTags),
527 lastVisitedAt: Schema.NullOr(Schema.DateTimeUtc).pipe(
528 Schema.withDecodingDefault(Effect.succeed(null)),
529 ),
530 opens: Schema.optional(LenientThreadOpens),
531 titleRegeneration: Schema.optional(
532 Schema.NullOr(
533 Schema.Struct({
534 requestId: CommandId,
535 startedAt: Schema.DateTimeUtc,
536 }),
537 ),
538 ),
539 lastTitleRegeneration: Schema.optional(Schema.NullOr(OrchestrationV2LastTitleRegeneration)),
540 /** Set by a rename until a generated title replaces it; absent reads as false. */
541 titleRenamed: Schema.optional(Schema.Boolean),
542 rollbackRequestId: Schema.optional(CommandId),
543 rollbackFailure: Schema.optional(
544 Schema.NullOr(
545 Schema.Struct({
546 requestId: CommandId,
547 message: TrimmedNonEmptyString,
548 }),
549 ),
550 ),
551 deletedAt: Schema.NullOr(Schema.DateTimeUtc),
552 });
553 export type OrchestrationV2AppThread = typeof OrchestrationV2AppThread.Type;
554
555 /** A visit changes read state only, so its event leaves the rest of the thread out. */
556 export const OrchestrationV2ThreadVisit = Schema.Struct({
557 lastVisitedAt: OrchestrationV2AppThread.fields.lastVisitedAt,
558 opens: OrchestrationV2AppThread.fields.opens,
559 });
560 export type OrchestrationV2ThreadVisit = typeof OrchestrationV2ThreadVisit.Type;
561
562 export function applyOrchestrationV2ThreadVisit<Thread extends OrchestrationV2AppThread>(
563 thread: Thread,
564 visit: OrchestrationV2ThreadVisit,
565 ): Thread {
566 return {
567 ...thread,
568 lastVisitedAt: visit.lastVisitedAt,
569 ...(visit.opens === undefined ? {} : { opens: visit.opens }),
570 };
571 }
572
573 /** A thread another agent drives: a local subagent or a task delegated from a linked environment. */
574 export const isDelegatedAppThread = (
575 thread: Pick<OrchestrationV2AppThread, "lineage" | "delegatedFrom">,
576 ): boolean =>
577 // MCP-launched threads store `delegatedFrom: null` at runtime, so check both absent shapes.
578 thread.lineage.relationshipToParent === "subagent" || thread.delegatedFrom != null;
579
580 /** Provider-native children cannot receive messages; T3 delegate_task children can. */
581 export function isProviderNativeSubagentThread(
582 thread: Pick<OrchestrationV2AppThread, "lineage" | "creationSource">,
583 ): boolean {
584 return thread.lineage.relationshipToParent === "subagent" && thread.creationSource === "provider";
585 }
586
587 export const IDLE_COMPACTION_TEXT = "/compact";
588
589 interface CompactionMessageFields {
590 readonly role: string;
591 readonly text: string;
592 readonly attachments?: ReadonlyArray<unknown> | undefined;
593 readonly createdBy?: OrchestrationV2Actor | undefined;
594 readonly creationSource?: OrchestrationV2CreationSource | undefined;
595 readonly idleCompaction?: OrchestrationV2IdleCompaction | undefined;
596 }
597
598 /** A prompt that only asks the provider to compact, so its turn is the compaction itself. */
599 export function isCompactionCommandMessage(message: CompactionMessageFields): boolean {
600 return (
601 message.role === "user" &&
602 message.text.trim().toLowerCase() === IDLE_COMPACTION_TEXT &&
603 (message.attachments?.length ?? 0) === 0
604 );
605 }
606
607 const LEADING_COMMAND = /^\s*(?:\/|\p{Sc}[a-zA-Z0-9:_-]*[a-zA-Z])/u;
608
609 /**
610 * Who sent a message, in a line the model reads before its text, or the text unchanged when a
611 * person typed it. Providers parse slash commands and skill mentions such as `$deploy` from the
612 * start of a prompt, so those stay as sent.
613 */
614 export function withMessageSenderNote(
615 message: {
616 readonly createdBy: OrchestrationV2Actor;
617 readonly creationSource: OrchestrationV2CreationSource;
618 readonly scheduledTaskId?: ScheduledTaskId | undefined;
619 readonly senderThreadId?: ThreadId | undefined;
620 readonly linkedSender?: OrchestrationV2LinkedSender | undefined;
621 },
622 text: string,
623 ): string {
624 const agent = message.createdBy === "agent";
625 const note =
626 agent && message.linkedSender !== undefined
627 ? `[T3 Code: the agent in T3 thread ${JSON.stringify(message.linkedSender.threadId)} on linked environment ${JSON.stringify(message.linkedSender.environmentId)} sent this message, not the user.]`
628 : agent && message.senderThreadId !== undefined
629 ? `[T3 Code: the agent in T3 thread ${JSON.stringify(message.senderThreadId)} sent this message, not the user.]`
630 : message.scheduledTaskId !== undefined
631 ? `[T3 Code: scheduled task ${JSON.stringify(message.scheduledTaskId)} sent this prompt, not the user typing in this chat.]`
632 : agent && message.creationSource === "mcp"
633 ? "[T3 Code: this message came through T3 Code's tools, not from the user typing in this chat.]"
634 : undefined;
635 if (note === undefined || LEADING_COMMAND.test(text)) return text;
636 return text === "" ? note : `${note}\n\n${text}`;
637 }
638
639 export type OrchestrationV2GoalCommand =
640 | { readonly type: "show" }
641 | { readonly type: "clear" }
642 | { readonly type: "pause" }
643 | { readonly type: "resume" }
644 | { readonly type: "set"; readonly objective: string };
645
646 /** Reads a `/goal` control message. Messages with attachments are ordinary prompts. */
647 export function parseGoalCommand(message: {
648 readonly text: string;
649 readonly attachments?: ReadonlyArray<unknown> | undefined;
650 }): OrchestrationV2GoalCommand | null {
651 if ((message.attachments?.length ?? 0) > 0) return null;
652 const match = /^\/goal(?:\s+([\s\S]*))?$/u.exec(message.text.trim());
653 if (match === null) return null;
654 const argument = (match[1] ?? "").trim();
655 switch (argument.toLowerCase()) {
656 case "":
657 case "edit":
658 return { type: "show" };
659 case "clear":
660 return { type: "clear" };
661 case "pause":
662 return { type: "pause" };
663 case "resume":
664 return { type: "resume" };
665 default:
666 return { type: "set", objective: argument };
667 }
668 }
669
670 /** Why T3 Code sent this `/compact` on its own, or undefined for one someone asked for. */
671 export function idleCompactionOf(
672 message: CompactionMessageFields,
673 ): OrchestrationV2IdleCompaction | undefined {
674 if (!isCompactionCommandMessage(message)) return undefined;
675 if (message.idleCompaction !== undefined) return message.idleCompaction;
676 // Servers before `idleCompaction` marked their own as agent-created.
677 return message.createdBy === "agent" && message.creationSource === "server"
678 ? "beforeCacheExpires"
679 : undefined;
680 }
681
682 export const OrchestrationV2RunStatus = Schema.Literals([
683 "preparing",
684 "queued",
685 "starting",
686 "running",
687 "waiting",
688 "completed",
689 "interrupted",
690 "failed",
691 "cancelled",
692 "rolled_back",
693 ]);
694 export type OrchestrationV2RunStatus = typeof OrchestrationV2RunStatus.Type;
695
696 export const OrchestrationV2DelegatedCompletionTaskDeliveryState = Schema.Literals([
697 "pending",
698 "claimed",
699 "acknowledged",
700 "delivered",
701 "disposed",
702 ]);
703 export type OrchestrationV2DelegatedCompletionTaskDeliveryState =
704 typeof OrchestrationV2DelegatedCompletionTaskDeliveryState.Type;
705
706 export const OrchestrationV2DelegatedCompletionTaskDelivery = Schema.Struct({
707 state: OrchestrationV2DelegatedCompletionTaskDeliveryState,
708 observedByRunId: Schema.NullOr(RunId),
709 });
710 export type OrchestrationV2DelegatedCompletionTaskDelivery =
711 typeof OrchestrationV2DelegatedCompletionTaskDelivery.Type;
712
713 export const OrchestrationV2DelegatedCompletionDelivery = Schema.Struct({
714 generation: PositiveInt,
715 messageId: MessageId,
716 taskIds: Schema.Array(NodeId),
717 });
718 export type OrchestrationV2DelegatedCompletionDelivery =
719 typeof OrchestrationV2DelegatedCompletionDelivery.Type;
720
721 export const OrchestrationV2DelegatedCompletionCohort = Schema.Struct({
722 disposition: Schema.Literals(["open", "stopped", "disposed"]),
723 nextGeneration: PositiveInt,
724 delivery: Schema.NullOr(OrchestrationV2DelegatedCompletionDelivery),
725 });
726 export type OrchestrationV2DelegatedCompletionCohort =
727 typeof OrchestrationV2DelegatedCompletionCohort.Type;
728
729 export const OrchestrationV2RestartCancelledBackgroundWork = Schema.Struct({
730 kind: Schema.Literals(["subagent", "shell", "monitor", "task"]),
731 label: TrimmedNonEmptyString,
732 id: Schema.optional(TrimmedNonEmptyString),
733 /** The agent was waiting on this work, so its restart note wakes the agent even for a shell. */
734 awaited: Schema.optional(Schema.Literal(true)),
735 });
736 export type OrchestrationV2RestartCancelledBackgroundWork =
737 typeof OrchestrationV2RestartCancelledBackgroundWork.Type;
738
739 export const OrchestrationV2RunBackgroundWorkCancelled = Schema.Struct({
740 runId: RunId,
741 restartCancelledBackgroundWork: Schema.Array(OrchestrationV2RestartCancelledBackgroundWork),
742 });
743 export type OrchestrationV2RunBackgroundWorkCancelled =
744 typeof OrchestrationV2RunBackgroundWorkCancelled.Type;
745
746 export const OrchestrationV2ThreadLaunchWorkspaceStrategy = Schema.Union([
747 Schema.Struct({
748 type: Schema.Literal("root"),
749 branch: Schema.optional(TrimmedNonEmptyString),
750 }),
751 Schema.Struct({
752 type: Schema.Literal("existing_worktree"),
753 worktreePath: TrimmedNonEmptyString,
754 branch: Schema.optional(TrimmedNonEmptyString),
755 }),
756 Schema.Struct({
757 type: Schema.Literal("worktree"),
758 baseRef: TrimmedNonEmptyString,
759 branch: Schema.optional(TrimmedNonEmptyString),
760 startFromOrigin: Schema.optional(Schema.Boolean),
761 }),
762 ]);
763 export type OrchestrationV2ThreadLaunchWorkspaceStrategy =
764 typeof OrchestrationV2ThreadLaunchWorkspaceStrategy.Type;
765
766 export const ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE = "workspace_preparation_failed";
767
768 /** What a run returned as data: a value the server accepted against the run's `outputSchema`. */
769 export const OrchestrationV2RunOutput = Schema.Struct({
770 value: Schema.Json,
771 // A string, not a DateTime: the run's JSON form only converts its own top-level dates.
772 submittedAt: IsoDateTime,
773 });
774 export type OrchestrationV2RunOutput = typeof OrchestrationV2RunOutput.Type;
775
776 export const OrchestrationV2Run = Schema.Struct({
777 id: RunId,
778 threadId: ThreadId,
779 ordinal: PositiveInt,
780 providerInstanceId: ProviderInstanceId,
781 modelSelection: ModelSelection,
782 providerThreadId: Schema.NullOr(ProviderThreadId),
783 userMessageId: MessageId,
784 rootNodeId: Schema.NullOr(NodeId),
785 activeAttemptId: Schema.NullOr(RunAttemptId),
786 status: OrchestrationV2RunStatus,
787 queuePosition: Schema.optional(Schema.NullOr(PositiveInt)),
788 queueHeld: Schema.optional(Schema.Boolean),
789 steerWhenReadyRunId: Schema.optional(RunId),
790 requestedAt: Schema.DateTimeUtc,
791 startedAt: Schema.NullOr(Schema.DateTimeUtc),
792 completedAt: Schema.NullOr(Schema.DateTimeUtc),
793 checkpointId: Schema.NullOr(CheckpointId),
794 contextHandoffId: Schema.NullOr(ContextHandoffId),
795 restartContinuationOfRunId: Schema.optional(RunId),
796 manualContinuationOfRunId: Schema.optional(RunId),
797 usageLimitContinuationOfRunId: Schema.optional(RunId),
798 delegatedTaskId: Schema.optional(NodeId),
799 workStartedAt: Schema.optional(Schema.DateTimeUtc),
800 restartCancelledBackgroundWork: Schema.optional(
801 Schema.Array(OrchestrationV2RestartCancelledBackgroundWork),
802 ),
803 sourcePlanRef: Schema.optional(
804 Schema.Struct({
805 threadId: ThreadId,
806 planId: PlanId,
807 }),
808 ),
809 delegatedCompletion: Schema.optional(OrchestrationV2DelegatedCompletionCohort),
810 workspacePreparation: Schema.optional(OrchestrationV2ThreadLaunchWorkspaceStrategy),
811 /** Starts a new provider conversation; earlier runs stay visible but never reach the provider. */
812 freshContext: Schema.optional(Schema.Boolean),
813 /** The JSON Schema of the result this run was asked to return as data. */
814 outputSchema: Schema.optional(Schema.Record(Schema.String, Schema.Json)),
815 /**
816 * Its own field, written by its own event: lifecycle writers hold a copy of the run from when
817 * the turn started, and their updates must not put an unanswered run back.
818 */
819 output: Schema.optional(OrchestrationV2RunOutput),
820 });
821 export type OrchestrationV2Run = typeof OrchestrationV2Run.Type;
822
823 export const OrchestrationV2RunOutputSubmitted = Schema.Struct({
824 runId: RunId,
825 output: OrchestrationV2RunOutput,
826 });
827 export type OrchestrationV2RunOutputSubmitted = typeof OrchestrationV2RunOutputSubmitted.Type;
828
829 export function orchestrationV2RunWorkStartedAt(
830 run: Pick<OrchestrationV2Run, "workStartedAt" | "startedAt" | "requestedAt">,
831 ): OrchestrationV2Run["requestedAt"] {
832 return run.workStartedAt ?? run.startedAt ?? run.requestedAt;
833 }
834
835 export const OrchestrationV2RunAttempt = Schema.Struct({
836 id: RunAttemptId,
837 // Provider-thread rows can be reused after recovery; retain the native input destination.
838 nativeThreadId: Schema.optional(Schema.String),
839 runId: RunId,
840 attemptOrdinal: PositiveInt,
841 rootNodeId: NodeId,
842 providerInstanceId: ProviderInstanceId,
843 providerThreadId: ProviderThreadId,
844 providerTurnId: Schema.NullOr(ProviderTurnId),
845 reason: Schema.Literals(["initial", "steering_restart", "retry", "provider_recovery"]),
846 status: Schema.Literals([
847 "pending",
848 "running",
849 "completed",
850 "interrupted",
851 "failed",
852 "cancelled",
853 "superseded",
854 ]),
855 startedAt: Schema.NullOr(Schema.DateTimeUtc),
856 completedAt: Schema.NullOr(Schema.DateTimeUtc),
857 });
858 export type OrchestrationV2RunAttempt = typeof OrchestrationV2RunAttempt.Type;
859
860 export const OrchestrationV2ExecutionNode = Schema.Struct({
861 id: NodeId,
862 threadId: ThreadId,
863 runId: Schema.NullOr(RunId),
864 parentNodeId: Schema.NullOr(NodeId),
865 rootNodeId: NodeId,
866 kind: Schema.Literals([
867 "root_turn",
868 "assistant_message",
869 "reasoning",
870 "plan",
871 "todo_list",
872 "tool_call",
873 "approval_request",
874 "user_input_request",
875 "subagent",
876 "hook",
877 "system",
878 ]),
879 status: Schema.Literals([
880 "idle",
881 "pending",
882 "running",
883 "waiting",
884 "completed",
885 "interrupted",
886 "failed",
887 "cancelled",
888 "rolled_back",
889 ]),
890 countsForRun: Schema.Boolean,
891 providerThreadId: Schema.NullOr(ProviderThreadId),
892 providerTurnId: Schema.NullOr(ProviderTurnId),
893 nativeItemRef: Schema.NullOr(OrchestrationV2ProviderRef),
894 runtimeRequestId: Schema.NullOr(RuntimeRequestId),
895 checkpointScopeId: Schema.NullOr(CheckpointScopeId),
896 startedAt: Schema.NullOr(Schema.DateTimeUtc),
897 completedAt: Schema.NullOr(Schema.DateTimeUtc),
898 });
899 export type OrchestrationV2ExecutionNode = typeof OrchestrationV2ExecutionNode.Type;
900
901 /** Append-only: phases discovered at runtime join when they start. */
902 export const OrchestrationV2WorkflowPhase = Schema.Struct({
903 index: NonNegativeInt,
904 title: TrimmedNonEmptyString,
905 });
906 export type OrchestrationV2WorkflowPhase = typeof OrchestrationV2WorkflowPhase.Type;
907
908 /** Nested timestamps use epoch milliseconds; only top-level DateTimeUtc fields are remapped for JSON. */
909 export const OrchestrationV2WorkflowAgent = Schema.Struct({
910 index: NonNegativeInt,
911 label: TrimmedNonEmptyString,
912 agentId: Schema.optional(TrimmedNonEmptyString),
913 childThreadId: Schema.optional(ThreadId),
914 state: Schema.Literals(["queued", "running", "completed", "failed"]),
915 phaseIndex: Schema.optional(NonNegativeInt),
916 phaseTitle: Schema.optional(TrimmedNonEmptyString),
917 model: Schema.optional(TrimmedNonEmptyString),
918 effort: Schema.optional(TrimmedNonEmptyString),
919 speed: Schema.optional(TrimmedNonEmptyString),
920 attempt: Schema.optional(NonNegativeInt),
921 totalTokens: Schema.optional(NonNegativeInt),
922 toolCalls: Schema.optional(NonNegativeInt),
923 durationMs: Schema.optional(NonNegativeInt),
924 queuedAt: Schema.optional(NonNegativeInt),
925 startedAt: Schema.optional(NonNegativeInt),
926 completedAt: Schema.optional(NonNegativeInt),
927 prompt: Schema.optional(Schema.NonEmptyString),
928 result: Schema.optional(Schema.NonEmptyString),
929 });
930 export type OrchestrationV2WorkflowAgent = typeof OrchestrationV2WorkflowAgent.Type;
931
932 export const OrchestrationV2WorkflowRunHandles = Schema.Struct({
933 runId: Schema.optional(TrimmedNonEmptyString),
934 transcriptDir: Schema.optional(TrimmedNonEmptyString),
935 scriptPath: Schema.optional(TrimmedNonEmptyString),
936 });
937 export type OrchestrationV2WorkflowRunHandles = typeof OrchestrationV2WorkflowRunHandles.Type;
938
939 export const OrchestrationV2SubagentWorkflow = Schema.Struct({
940 name: Schema.optional(TrimmedNonEmptyString),
941 runHandles: Schema.optional(OrchestrationV2WorkflowRunHandles),
942 phases: Schema.Array(OrchestrationV2WorkflowPhase),
943 agents: Schema.Array(OrchestrationV2WorkflowAgent),
944 totalTokens: Schema.optional(NonNegativeInt),
945 toolCalls: Schema.optional(NonNegativeInt),
946 durationMs: Schema.optional(NonNegativeInt),
947 });
948 export type OrchestrationV2SubagentWorkflow = typeof OrchestrationV2SubagentWorkflow.Type;
949
950 /**
951 * Wire-only, for clients that opted in with `acceptDedupedBodies` or `dedupeBodies=1`: the field
952 * was blanked because an earlier record on the same response or stream holds the same value.
953 * Restore with `@t3tools/shared/orchestrationV2DedupedBodies`; never store or forward a marked
954 * value. Clients restore only these fields, so blanking another field needs a new opt-in.
955 */
956 const DedupedBodyMarker = Schema.optionalKey(Schema.Literal(true));
957
958 /**
959 * Where an app-owned task runs when it runs in a linked environment instead
960 * of in a child thread here: that environment and the ordinary thread it runs
961 * as there. Such a task has no `childThreadId`.
962 */
963 export const OrchestrationV2RemoteTaskChild = Schema.Struct({
964 environmentId: EnvironmentId,
965 threadId: ThreadId,
966 label: Schema.String,
967 /** The title it launched with there; absent on tasks recorded before it was kept. */
968 title: Schema.optional(Schema.String),
969 /** The run there that carries the task; absent on tasks recorded before it was kept. */
970 runId: Schema.optional(RunId),
971 /**
972 * Nothing is left to stop there: a stop reached it, was refused for good, or the thread
973 * or link is gone. A run ending there by itself sets it too, unless the task here was
974 * cancelled or stopped and still owes a stop, which its follower keeps sending across
975 * restarts. `false`: a Stop here owes one to a task that already had its result.
976 */
977 stoppedThere: Schema.optional(Schema.Boolean),
978 /**
979 * Stops asked for here once the task had its result. The count names the
980 * one owed, so each reaches the thread there once however often it is sent.
981 */
982 stopCount: Schema.optional(NonNegativeInt),
983 });
984 export type OrchestrationV2RemoteTaskChild = typeof OrchestrationV2RemoteTaskChild.Type;
985
986 export const OrchestrationV2Subagent = Schema.Struct({
987 id: NodeId,
988 threadId: ThreadId,
989 runId: Schema.NullOr(RunId),
990 parentNodeId: NodeId,
991 origin: Schema.Literals(["provider_native", "app_owned"]),
992 createdBy: OrchestrationV2Actor,
993 driver: ProviderDriverKind,
994 providerInstanceId: ProviderInstanceId,
995 providerThreadId: Schema.NullOr(ProviderThreadId),
996 childThreadId: Schema.NullOr(ThreadId),
997 remoteChild: Schema.optional(OrchestrationV2RemoteTaskChild),
998 nativeTaskRef: Schema.NullOr(OrchestrationV2ProviderRef),
999 prompt: Schema.String,
1000 title: Schema.NullOr(Schema.String),
1001 model: Schema.NullOr(Schema.String),
1002 modelSelection: Schema.optional(ModelSelection),
1003 executedModel: Schema.optional(Schema.String),
1004 completionWake: Schema.optional(Schema.Literals(["always", "settled_only"])),
1005 completionDelivery: Schema.optional(OrchestrationV2DelegatedCompletionTaskDelivery),
1006 // The run whose unfinished task was cancelled, committed with its Stop.
1007 cancelledRunId: Schema.optional(RunId),
1008 status: Schema.Literals([
1009 "idle",
1010 "pending",
1011 "running",
1012 "waiting",
1013 "completed",
1014 "failed",
1015 "cancelled",
1016 "interrupted",
1017 ]),
1018 progress: Schema.optional(Schema.String),
1019 workflow: Schema.optional(OrchestrationV2SubagentWorkflow),
1020 result: Schema.NullOr(Schema.String),
1021 startedAt: Schema.NullOr(Schema.DateTimeUtc),
1022 completedAt: Schema.NullOr(Schema.DateTimeUtc),
1023 updatedAt: Schema.DateTimeUtc,
1024 /** Same as this subagent's previous record on this stream: its snapshot or `subagent.updated`. */
1025 promptOmitted: DedupedBodyMarker,
1026 resultOmitted: DedupedBodyMarker,
1027 });
1028 export type OrchestrationV2Subagent = typeof OrchestrationV2Subagent.Type;
1029
1030 export function isOrchestrationV2WorkActive(
1031 status: OrchestrationV2ExecutionNode["status"],
1032 ): boolean {
1033 return status === "pending" || status === "running" || status === "waiting";
1034 }
1035
1036 export const OrchestrationV2CheckpointScope = Schema.Struct({
1037 id: CheckpointScopeId,
1038 threadId: ThreadId,
1039 runId: Schema.NullOr(RunId),
1040 nodeId: NodeId,
1041 parentScopeId: Schema.NullOr(CheckpointScopeId),
1042 providerThreadId: Schema.NullOr(ProviderThreadId),
1043 kind: Schema.Literals(["root_run", "subagent", "tool", "provider_thread", "manual"]),
1044 ordinalWithinParent: NonNegativeInt,
1045 advancesAppRunCount: Schema.Boolean,
1046 cwd: TrimmedNonEmptyString,
1047 createdAt: Schema.DateTimeUtc,
1048 });
1049 export type OrchestrationV2CheckpointScope = typeof OrchestrationV2CheckpointScope.Type;
1050
1051 export const OrchestrationV2ProviderSession = Schema.Struct({
1052 id: ProviderSessionId,
1053 driver: ProviderDriverKind,
1054 providerInstanceId: ProviderInstanceId,
1055 status: Schema.Literals(["starting", "ready", "running", "waiting", "stopped", "error"]),
1056 cwd: TrimmedNonEmptyString,
1057 model: Schema.NullOr(TrimmedNonEmptyString),
1058 capabilities: OrchestrationV2ProviderCapabilities,
1059 extensionStatuses: Schema.optional(
1060 Schema.Array(
1061 Schema.Struct({
1062 key: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)),
1063 text: TrimmedNonEmptyString.check(Schema.isMaxLength(4096)),
1064 }),
1065 ).check(Schema.isMaxLength(32)),
1066 ).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
1067 createdAt: Schema.DateTimeUtc,
1068 updatedAt: Schema.DateTimeUtc,
1069 lastError: Schema.NullOr(Schema.String),
1070 });
1071 export type OrchestrationV2ProviderSession = typeof OrchestrationV2ProviderSession.Type;
1072
1073 export const OrchestrationV2ProviderSessionDetached = Schema.Struct({
1074 providerSessionId: ProviderSessionId,
1075 detachedAt: Schema.DateTimeUtc,
1076 reason: Schema.optional(Schema.String),
1077 });
1078 export type OrchestrationV2ProviderSessionDetached =
1079 typeof OrchestrationV2ProviderSessionDetached.Type;
1080
1081 function encodedKind(member: Schema.Top): string {
1082 const encoded = SchemaAST.toEncoded(member.ast);
1083 const kind = SchemaAST.isObjects(encoded)
1084 ? encoded.propertySignatures.find((property) => property.name === "kind")?.type
1085 : undefined;
1086 if (kind !== undefined && SchemaAST.isLiteral(kind) && typeof kind.literal === "string") {
1087 return kind.literal;
1088 }
1089 throw new Error("Each member of a kind union needs a literal string `kind`.");
1090 }
1091
1092 function kindUnionWithFallback<
1093 const Members extends ReadonlyArray<Schema.Top & { readonly Encoded: { readonly kind: string } }>,
1094 Unknown extends Schema.Top,
1095 >(
1096 members: Members,
1097 unknown: (kind: Schema.optional<Schema.String>) => Unknown,
1098 fallback: (value: Unknown["Type"]) => Schema.Union<Members>["Encoded"],
1099 ) {
1100 const knownKinds: ReadonlySet<string> = new Set(members.map(encodedKind));
1101 const unknownKind = unknown(
1102 Schema.optional(
1103 Schema.String.check(
1104 Schema.makeFilter(
1105 (kind: string) => !knownKinds.has(kind) || "A known kind must decode in full.",
1106 ),
1107 ),
1108 ),
1109 ).pipe(
1110 Schema.decodeTo(Schema.Union(members), {
1111 decode: SchemaGetter.transform(fallback),
1112 encode: SchemaGetter.forbidden(() => "Unknown kinds are decode-only."),
1113 }),
1114 );
1115 return Schema.Union([...members, unknownKind]);
1116 }
1117
1118 const PendingBackgroundTaskFields = {
1119 command: Schema.optional(Schema.String),
1120 itemId: Schema.optional(TurnItemId),
1121 sourceThreadId: Schema.optional(ThreadId),
1122 taskId: TrimmedNonEmptyString,
1123 description: Schema.optional(TrimmedNonEmptyString),
1124 /** The subagent task that started this work and waits on it. */
1125 parentTaskId: Schema.optional(TrimmedNonEmptyString),
1126 /** Native id of the turn item that started this work, when it is not `taskId`. */
1127 nativeItemId: Schema.optional(TrimmedNonEmptyString),
1128 /** The run that was executing when the work first appeared, stamped by the projection. */
1129 runId: Schema.optional(RunId),
1130 /**
1131 * The agent declared it resumes when this work ends, so the thread holds like it does for a
1132 * subagent. Only the agent knows whether a command is a wait or a dev server it left running.
1133 */
1134 awaited: Schema.optional(Schema.Literal(true)),
1135 };
1136
1137 export const OrchestrationV2PendingBackgroundTask = kindUnionWithFallback(
1138 [
1139 Schema.Struct({
1140 ...PendingBackgroundTaskFields,
1141 kind: Schema.Literal("subagent"),
1142 /** The owning provider thread's instance, populated in derived pending work. */
1143 providerInstanceId: Schema.optional(ProviderInstanceId),
1144 childThreadId: Schema.optional(ThreadId),
1145 }),
1146 Schema.Struct({ ...PendingBackgroundTaskFields, kind: Schema.Literal("command") }),
1147 Schema.Struct({ ...PendingBackgroundTaskFields, kind: Schema.Literal("monitor") }),
1148 Schema.Struct({ ...PendingBackgroundTaskFields, kind: Schema.Literal("background_task") }),
1149 ],
1150 (kind) => Schema.Struct({ ...PendingBackgroundTaskFields, kind }),
1151 ({ taskId, description, parentTaskId }) => ({
1152 taskId,
1153 ...(description === undefined ? {} : { description }),
1154 ...(parentTaskId === undefined ? {} : { parentTaskId }),
1155 kind: "background_task",
1156 }),
1157 );
1158 export type OrchestrationV2PendingBackgroundTask = typeof OrchestrationV2PendingBackgroundTask.Type;
1159
1160 export const OrchestrationV2ProviderThreadNativeMetadata = Schema.Struct({
1161 cursorStoreCwd: Schema.optional(TrimmedNonEmptyString),
1162 modelSelection: Schema.optional(ModelSelection),
1163 title: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
1164 updatedAt: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
1165 itemIdentityVersion: Schema.optional(Schema.Literal(2)),
1166 forkHeadMessageId: Schema.optional(TrimmedNonEmptyString),
1167 claudeAttachmentBudget: Schema.optional(
1168 Schema.Struct({ bytesUsed: NonNegativeInt, pagesUsed: NonNegativeInt }),
1169 ),
1170 });
1171 export type OrchestrationV2ProviderThreadNativeMetadata =
1172 typeof OrchestrationV2ProviderThreadNativeMetadata.Type;
1173
1174 export const OrchestrationV2ProviderGoalStatus = Schema.Literals([
1175 "active",
1176 "paused",
1177 "blocked",
1178 "usage_limited",
1179 "budget_limited",
1180 "complete",
1181 ]);
1182 export type OrchestrationV2ProviderGoalStatus = typeof OrchestrationV2ProviderGoalStatus.Type;
1183
1184 export const OrchestrationV2ProviderGoal = Schema.Struct({
1185 objective: TrimmedNonEmptyString,
1186 status: OrchestrationV2ProviderGoalStatus,
1187 tokensUsed: Schema.optional(NonNegativeInt),
1188 tokenBudget: Schema.optional(Schema.NullOr(NonNegativeInt)),
1189 timeUsedSeconds: Schema.optional(NonNegativeInt),
1190 checks: Schema.optional(NonNegativeInt),
1191 lastCheck: Schema.optional(Schema.String),
1192 });
1193 export type OrchestrationV2ProviderGoal = typeof OrchestrationV2ProviderGoal.Type;
1194
1195 export const OrchestrationV2ProviderThread = Schema.Struct({
1196 id: ProviderThreadId,
1197 driver: ProviderDriverKind,
1198 providerInstanceId: ProviderInstanceId,
1199 providerSessionId: Schema.NullOr(ProviderSessionId),
1200 appThreadId: Schema.NullOr(ThreadId),
1201 ownerNodeId: Schema.NullOr(NodeId),
1202 nativeThreadRef: Schema.NullOr(OrchestrationV2ProviderRef),
1203 nativeConversationHeadRef: Schema.NullOr(OrchestrationV2ProviderRef),
1204 status: Schema.Literals(["not_loaded", "idle", "active", "archived", "closed", "error"]),
1205 firstRunOrdinal: Schema.NullOr(PositiveInt),
1206 lastRunOrdinal: Schema.NullOr(PositiveInt),
1207 handoffIds: Schema.Array(ContextHandoffId),
1208 forkedFrom: Schema.NullOr(
1209 Schema.Struct({
1210 providerThreadId: ProviderThreadId,
1211 providerTurnId: Schema.optional(ProviderTurnId),
1212 checkpointId: Schema.optional(CheckpointId),
1213 }),
1214 ),
1215 pendingBackgroundTasks: Schema.optional(Schema.Array(OrchestrationV2PendingBackgroundTask)).pipe(
1216 Schema.withDecodingDefault(Effect.succeed([])),
1217 ),
1218 contextUsage: Schema.optional(Schema.NullOr(ThreadTokenUsageSnapshot)).pipe(
1219 Schema.withDecodingDefault(Effect.succeed(null)),
1220 ),
1221 nativeMetadata: Schema.optional(Schema.NullOr(OrchestrationV2ProviderThreadNativeMetadata)).pipe(
1222 Schema.withDecodingDefault(Effect.succeed(null)),
1223 ),
1224 goal: Schema.optional(Schema.NullOr(OrchestrationV2ProviderGoal)).pipe(
1225 Schema.withDecodingDefault(Effect.succeed(null)),
1226 ),
1227 createdAt: Schema.DateTimeUtc,
1228 updatedAt: Schema.DateTimeUtc,
1229 });
1230 export type OrchestrationV2ProviderThread = typeof OrchestrationV2ProviderThread.Type;
1231
1232 export const OrchestrationV2HistoricalMessage = Schema.Struct({
1233 role: Schema.Literals(["user", "assistant"]),
1234 text: Schema.String,
1235 runStatus: Schema.optional(Schema.String),
1236 threadId: ThreadId,
1237 runId: Schema.NullOr(RunId),
1238 itemId: TurnItemId,
1239 providerThreadId: Schema.NullOr(ProviderThreadId),
1240 status: Schema.String,
1241 kind: Schema.String,
1242 });
1243 export type OrchestrationV2HistoricalMessage = typeof OrchestrationV2HistoricalMessage.Type;
1244
1245 export const OrchestrationV2ContextHandoff = Schema.Struct({
1246 id: ContextHandoffId,
1247 transferId: Schema.optional(Schema.NullOr(ContextTransferId)),
1248 threadId: ThreadId,
1249 targetRunId: RunId,
1250 fromProviderThreadIds: Schema.Array(ProviderThreadId),
1251 toProviderThreadId: ProviderThreadId,
1252 coveredRunOrdinals: Schema.Struct({
1253 from: PositiveInt,
1254 to: PositiveInt,
1255 }),
1256 strategy: Schema.Literals([
1257 "delta_since_target_last_seen",
1258 "fork_delta_summary",
1259 "full_thread_summary",
1260 "checkpoint_summary",
1261 "manual_context",
1262 ]),
1263 status: Schema.Literals(["pending", "ready", "failed", "superseded"]),
1264 summaryMessageId: Schema.NullOr(MessageId),
1265 summaryText: Schema.String,
1266 history: Schema.optional(
1267 Schema.Struct({
1268 messages: Schema.Array(OrchestrationV2HistoricalMessage),
1269 coverage: Schema.String,
1270 omittedItems: NonNegativeInt,
1271 omittedItemIds: Schema.optional(Schema.Array(TurnItemId)),
1272 }),
1273 ),
1274 delivery: Schema.optional(
1275 Schema.Struct({
1276 nativeThreadId: Schema.String,
1277 status: Schema.Literals(["pending", "injected", "inline"]),
1278 itemIds: Schema.Array(TurnItemId),
1279 omittedItemIds: Schema.optional(Schema.Array(TurnItemId)),
1280 }),
1281 ),
1282 detailInTurnItem: Schema.optional(Schema.Literal(true)),
1283 createdByProviderInstanceId: Schema.NullOr(ProviderInstanceId),
1284 createdAt: Schema.DateTimeUtc,
1285 updatedAt: Schema.DateTimeUtc,
1286 });
1287 export type OrchestrationV2ContextHandoff = typeof OrchestrationV2ContextHandoff.Type;
1288
1289 export const OrchestrationV2ProviderTurn = Schema.Struct({
1290 id: ProviderTurnId,
1291 providerThreadId: ProviderThreadId,
1292 nodeId: NodeId,
1293 runAttemptId: Schema.NullOr(RunAttemptId),
1294 nativeTurnRef: Schema.NullOr(OrchestrationV2ProviderRef),
1295 /** The native session that held this turn, when a provider can move a thread between sessions. */
1296 nativeThreadRef: Schema.optional(OrchestrationV2ProviderRef),
1297 ordinal: PositiveInt,
1298 status: Schema.Literals([
1299 "pending",
1300 "running",
1301 "completed",
1302 "interrupted",
1303 "failed",
1304 "cancelled",
1305 ]),
1306 startedAt: Schema.NullOr(Schema.DateTimeUtc),
1307 completedAt: Schema.NullOr(Schema.DateTimeUtc),
1308 tokenUsage: Schema.optional(OrchestrationV2ProviderTurnTokenUsage),
1309 turnTokenUsage: Schema.optional(TurnTokenUsage),
1310 /** The model the provider reported running this turn's root agent, which can differ from the requested one. */
1311 model: Schema.optional(TrimmedNonEmptyString),
1312 });
1313 export type OrchestrationV2ProviderTurn = typeof OrchestrationV2ProviderTurn.Type;
1314
1315 /** Codex goals can span multiple native turns within one attempt. */
1316 export function latestProviderTurnForAttempt<
1317 Turn extends Pick<OrchestrationV2ProviderTurn, "runAttemptId" | "ordinal">,
1318 >(
1319 providerTurns: ReadonlyArray<Turn>,
1320 attemptId: RunAttemptId | null | undefined,
1321 ): Turn | undefined {
1322 let latest: Turn | undefined;
1323 for (const turn of providerTurns) {
1324 if (attemptId == null || turn.runAttemptId !== attemptId) continue;
1325 if (latest === undefined || turn.ordinal > latest.ordinal) latest = turn;
1326 }
1327 return latest;
1328 }
1329
1330 /** A queued provider thread reserves a seat for the next run; it does not own the thread yet. */
1331 export function isQueuedProviderThreadPlaceholder(
1332 providerThread: Pick<
1333 OrchestrationV2ProviderThread,
1334 "status" | "firstRunOrdinal" | "nativeThreadRef" | "providerSessionId"
1335 >,
1336 ): boolean {
1337 return (
1338 providerThread.status === "not_loaded" &&
1339 providerThread.firstRunOrdinal === null &&
1340 providerThread.nativeThreadRef === null &&
1341 providerThread.providerSessionId === null
1342 );
1343 }
1344
1345 export const OrchestrationV2RuntimeRequest = Schema.Struct({
1346 id: RuntimeRequestId,
1347 nodeId: NodeId,
1348 providerTurnId: Schema.NullOr(ProviderTurnId),
1349 nativeRequestRef: Schema.NullOr(OrchestrationV2ProviderRef),
1350 kind: Schema.Union([
1351 ProviderRequestKind,
1352 Schema.Literals(["dynamic_tool_call", "user_input", "auth_refresh"]),
1353 ]),
1354 status: Schema.Literals(["pending", "resolved", "expired", "cancelled"]),
1355 responseCapability: Schema.Union([
1356 Schema.Struct({
1357 type: Schema.Literal("live"),
1358 providerSessionId: ProviderSessionId,
1359 supportsFeedback: Schema.optional(Schema.Boolean),
1360 }),
1361 Schema.Struct({ type: Schema.Literal("message") }),
1362 Schema.Struct({ type: Schema.Literal("not_resumable"), reason: Schema.String }),
1363 ]),
1364 createdAt: Schema.DateTimeUtc,
1365 resolvedAt: Schema.NullOr(Schema.DateTimeUtc),
1366 decision: Schema.optional(ProviderApprovalDecision),
1367 feedback: Schema.optional(Schema.String),
1368 answers: Schema.optional(ProviderUserInputAnswers),
1369 });
1370 export type OrchestrationV2RuntimeRequest = typeof OrchestrationV2RuntimeRequest.Type;
1371
1372 const SubagentNotificationSource = Schema.Struct({
1373 kind: Schema.Literal("subagent"),
1374 childThreadId: Schema.optional(ThreadId),
1375 });
1376 const CommandNotificationSource = Schema.Struct({ kind: Schema.Literal("command") });
1377 const OrchestrationV2NotificationOutcome = Schema.Literals([
1378 "completed",
1379 "failed",
1380 "cancelled",
1381 "updated",
1382 "unknown",
1383 ]);
1384 /** One pull request's part of a wake, which stands alone once the others are outdated. */
1385 const PullRequestWakeSection = Schema.Struct({
1386 text: Schema.String,
1387 outcome: OrchestrationV2NotificationOutcome,
1388 summary: TrimmedNonEmptyString,
1389 });
1390 const MonitorPullRequestStamp = Schema.Struct({
1391 ...ThreadPullRequestKey.fields,
1392 watchStartedAt: IsoDateTime,
1393 /** Null when the wake is not about one head, so a newer push does not outdate it. */
1394 headSha: Schema.NullOr(TrimmedNonEmptyString),
1395 watchEnded: Schema.optional(Schema.Boolean),
1396 /** Set on a wake covering several pull requests. */
1397 section: Schema.optional(PullRequestWakeSection),
1398 });
1399
1400 /** Encode legacy background_command/background_task shapes first so older clients accept command/subagent sources. */
1401 export const OrchestrationV2NotificationSource = kindUnionWithFallback(
1402 [
1403 Schema.Struct({
1404 kind: Schema.Literal("delegated_task"),
1405 taskIds: Schema.Array(NodeId),
1406 childThreadId: Schema.optional(ThreadId),
1407 }),
1408 Schema.Struct({
1409 kind: Schema.Literal("background_task"),
1410 work: Schema.Literal("subagent"),
1411 childThreadId: Schema.optional(ThreadId),
1412 }).pipe(
1413 Schema.decodeTo(Schema.toType(SubagentNotificationSource), {
1414 decode: SchemaGetter.transform(({ childThreadId }) =>
1415 childThreadId === undefined
1416 ? { kind: "subagent" as const }
1417 : { kind: "subagent" as const, childThreadId },
1418 ),
1419 encode: SchemaGetter.transform(({ childThreadId }) => ({
1420 kind: "background_task" as const,
1421 work: "subagent" as const,
1422 ...(childThreadId === undefined ? {} : { childThreadId }),
1423 })),
1424 }),
1425 ),
1426 Schema.Struct({ kind: Schema.Literal("background_command").transform("command") }),
1427 SubagentNotificationSource,
1428 CommandNotificationSource,
1429 Schema.Struct({
1430 kind: Schema.Literal("monitor"),
1431 pullRequest: Schema.optional(MonitorPullRequestStamp),
1432 /** The other pull requests one wake covers; outdated ones leave it before it starts. */
1433 otherPullRequests: Schema.optional(Schema.Array(MonitorPullRequestStamp)),
1434 }),
1435 Schema.Struct({ kind: Schema.Literal("background_task") }),
1436 Schema.Struct({ kind: Schema.Literal("system") }),
1437 ],
1438 (kind) => Schema.Struct({ kind }),
1439 () => ({ kind: "background_task" }),
1440 );
1441 export type OrchestrationV2NotificationSource = typeof OrchestrationV2NotificationSource.Type;
1442
1443 export const OrchestrationV2Notification = Schema.Struct({
1444 source: OrchestrationV2NotificationSource,
1445 outcome: OrchestrationV2NotificationOutcome,
1446 summary: TrimmedNonEmptyString,
1447 detail: Schema.optional(Schema.String),
1448 });
1449 export type OrchestrationV2Notification = typeof OrchestrationV2Notification.Type;
1450
1451 /** Why T3 Code compacted a thread on its own, on the `/compact` it sent. */
1452 export const OrchestrationV2IdleCompaction = Schema.Literals(["beforeCacheExpires", "onReturn"]);
1453 export type OrchestrationV2IdleCompaction = typeof OrchestrationV2IdleCompaction.Type;
1454
1455 export const OrchestrationV2ConversationMessage = Schema.Struct({
1456 notification: Schema.optional(OrchestrationV2Notification),
1457 ...OrchestrationV2CreationFields,
1458 scheduledTaskId: Schema.optional(ScheduledTaskId),
1459 /** A scheduled delivery that named no model; it runs on the thread's selection at start. */
1460 followsThreadSelection: Schema.optional(Schema.Literal(true)),
1461 senderThreadId: Schema.optional(ThreadId),
1462 linkedSender: Schema.optional(OrchestrationV2LinkedSender),
1463 idleCompaction: Schema.optional(OrchestrationV2IdleCompaction),
1464 /**
1465 * The message is the script a provider-native workflow run executes, not prose. Clients show
1466 * the workflow's opening instead and keep the script behind a disclosure.
1467 */
1468 workflowScript: Schema.optional(Schema.Boolean),
1469 id: MessageId,
1470 threadId: ThreadId,
1471 runId: Schema.NullOr(RunId),
1472 nodeId: Schema.NullOr(NodeId),
1473 role: Schema.Literals(["user", "assistant", "system"]),
1474 text: Schema.String,
1475 context: Schema.optional(OrchestrationMessageContext),
1476 attachments: Schema.Array(ChatAttachment),
1477 streaming: Schema.Boolean,
1478 createdAt: Schema.DateTimeUtc,
1479 updatedAt: Schema.DateTimeUtc,
1480 delegatedCompletion: Schema.optional(
1481 Schema.Struct({
1482 parentRunId: RunId,
1483 generation: PositiveInt,
1484 taskIds: Schema.Array(NodeId),
1485 }),
1486 ),
1487 });
1488 export type OrchestrationV2ConversationMessage = typeof OrchestrationV2ConversationMessage.Type;
1489
1490 export const OrchestrationV2PlanStep = Schema.Struct({
1491 id: TrimmedNonEmptyString,
1492 text: TrimmedNonEmptyString,
1493 status: Schema.Literals(["pending", "running", "completed"]),
1494 durationAnchorAt: Schema.optional(IsoDateTime),
1495 durationMs: Schema.optional(NonNegativeInt),
1496 });
1497 export type OrchestrationV2PlanStep = typeof OrchestrationV2PlanStep.Type;
1498
1499 export const OrchestrationV2UserInputQuestion = Schema.Struct({
1500 id: TrimmedNonEmptyString,
1501 header: TrimmedNonEmptyString,
1502 question: TrimmedNonEmptyString,
1503 options: Schema.Array(
1504 Schema.Struct({
1505 label: TrimmedNonEmptyString,
1506 description: TrimmedNonEmptyString,
1507 value: Schema.optional(Schema.String),
1508 preview: Schema.optional(Schema.String),
1509 }),
1510 ),
1511 multiSelect: Schema.optional(Schema.Boolean),
1512 allowCustomAnswer: Schema.optional(Schema.Boolean),
1513 initialAnswer: Schema.optional(Schema.String),
1514 required: Schema.optional(Schema.Boolean),
1515 });
1516 export type OrchestrationV2UserInputQuestion = typeof OrchestrationV2UserInputQuestion.Type;
1517
1518 const OrchestrationV2PlanArtifactBaseFields = {
1519 id: PlanId,
1520 threadId: ThreadId,
1521 runId: Schema.NullOr(RunId),
1522 nodeId: NodeId,
1523 status: Schema.Literals(["draft", "active", "completed", "superseded"]),
1524 detailInTurnItem: Schema.optional(Schema.Literal(true)),
1525 } as const;
1526
1527 export const OrchestrationV2PlanArtifact = Schema.Union([
1528 Schema.Struct({
1529 ...OrchestrationV2PlanArtifactBaseFields,
1530 kind: Schema.Literal("proposed_plan"),
1531 markdown: Schema.String,
1532 }),
1533 Schema.Struct({
1534 ...OrchestrationV2PlanArtifactBaseFields,
1535 kind: Schema.Literal("todo_list"),
1536 steps: Schema.Array(OrchestrationV2PlanStep),
1537 explanation: Schema.optional(Schema.String),
1538 }),
1539 ]);
1540 export type OrchestrationV2PlanArtifact = typeof OrchestrationV2PlanArtifact.Type;
1541
1542 export const OrchestrationV2CheckpointFileSummary = Schema.Struct({
1543 // Exact, as git reports it: file names may start or end with whitespace.
1544 path: Schema.NonEmptyString,
1545 kind: TrimmedNonEmptyString,
1546 additions: NonNegativeInt,
1547 deletions: NonNegativeInt,
1548 });
1549 export type OrchestrationV2CheckpointFileSummary = typeof OrchestrationV2CheckpointFileSummary.Type;
1550
1551 /** Sent only when the wire carries a prefix of `files`; the totals cover the full list. */
1552 export const OrchestrationV2CheckpointFileTotals = Schema.Struct({
1553 count: NonNegativeInt,
1554 additions: NonNegativeInt,
1555 deletions: NonNegativeInt,
1556 });
1557 export type OrchestrationV2CheckpointFileTotals = typeof OrchestrationV2CheckpointFileTotals.Type;
1558
1559 export const OrchestrationV2Checkpoint = Schema.Struct({
1560 id: CheckpointId,
1561 threadId: ThreadId,
1562 scopeId: CheckpointScopeId,
1563 runId: Schema.NullOr(RunId),
1564 nodeId: NodeId,
1565 parentCheckpointId: Schema.NullOr(CheckpointId),
1566 ordinalWithinScope: NonNegativeInt,
1567 appRunOrdinal: Schema.NullOr(PositiveInt),
1568 ref: CheckpointRef,
1569 status: Schema.Literals(["ready", "missing", "error", "stale"]),
1570 files: Schema.Array(OrchestrationV2CheckpointFileSummary),
1571 filesTotal: Schema.optionalKey(OrchestrationV2CheckpointFileTotals),
1572 capturedAt: Schema.DateTimeUtc,
1573 });
1574 export type OrchestrationV2Checkpoint = typeof OrchestrationV2Checkpoint.Type;
1575
1576 export const OrchestrationV2CheckpointRollbackRequest = Schema.Struct({
1577 scopeId: CheckpointScopeId,
1578 checkpointId: CheckpointId,
1579 requestedAt: Schema.DateTimeUtc,
1580 });
1581 export type OrchestrationV2CheckpointRollbackRequest =
1582 typeof OrchestrationV2CheckpointRollbackRequest.Type;
1583
1584 export class OrchestrationV2CheckpointUnavailableError extends Schema.TaggedError<OrchestrationV2CheckpointUnavailableError>()(
1585 "OrchestrationV2CheckpointUnavailableError",
1586 {
1587 threadId: ThreadId,
1588 target: Schema.String,
1589 },
1590 ) {
1591 override get message(): string {
1592 return `Rollback target ${this.target} is unavailable for thread ${this.threadId}.`;
1593 }
1594 }
1595
1596 export const OrchestrationV2TurnItemStatus = Schema.Literals([
1597 "idle",
1598 "pending",
1599 "running",
1600 "waiting",
1601 "completed",
1602 "failed",
1603 "cancelled",
1604 "interrupted",
1605 ]);
1606
1607 export type OrchestrationV2TurnItemStatus = typeof OrchestrationV2TurnItemStatus.Type;
1608
1609 export const OrchestrationV2FileChangeDetail = Schema.Struct({
1610 operation: TrimmedNonEmptyString,
1611 path: TrimmedNonEmptyString,
1612 oldPath: Schema.optional(TrimmedNonEmptyString),
1613 fileType: Schema.optional(TrimmedNonEmptyString),
1614 mimeType: Schema.optional(TrimmedNonEmptyString),
1615 });
1616 export type OrchestrationV2FileChangeDetail = typeof OrchestrationV2FileChangeDetail.Type;
1617
1618 export const OrchestrationV2ProviderFailureClass = Schema.Literals([
1619 "usage_limit",
1620 "provider_error",
1621 "transport_error",
1622 "permission_error",
1623 "validation_error",
1624 "unknown",
1625 ]);
1626 export type OrchestrationV2ProviderFailureClass = typeof OrchestrationV2ProviderFailureClass.Type;
1627
1628 const OrchestrationV2ProviderFailureMessage = TrimmedNonEmptyString.check(
1629 Schema.isMaxLength(4_096),
1630 );
1631 const OrchestrationV2ProviderFailureCode = TrimmedNonEmptyString.check(Schema.isMaxLength(128));
1632
1633 /** Producers must redact credentials before construction. */
1634 export const OrchestrationV2ProviderFailure = Schema.Struct({
1635 class: OrchestrationV2ProviderFailureClass,
1636 message: OrchestrationV2ProviderFailureMessage,
1637 code: Schema.NullOr(OrchestrationV2ProviderFailureCode),
1638 retryable: Schema.NullOr(Schema.Boolean),
1639 resetAt: Schema.optional(Schema.NullOr(IsoDateTime)),
1640 });
1641 export type OrchestrationV2ProviderFailure = typeof OrchestrationV2ProviderFailure.Type;
1642
1643 export const OrchestrationV2ProviderRetry = Schema.Struct({
1644 attempt: PositiveInt,
1645 maxAttempts: Schema.NullOr(PositiveInt),
1646 retryDelayMs: Schema.NullOr(NonNegativeInt),
1647 });
1648 export type OrchestrationV2ProviderRetry = typeof OrchestrationV2ProviderRetry.Type;
1649
1650 export const OrchestrationV2UserMessageInputIntent = Schema.Literals([
1651 "turn_start",
1652 "queued_turn",
1653 "steer",
1654 "promoted_queued_to_steer",
1655 ]);
1656 export type OrchestrationV2UserMessageInputIntent =
1657 typeof OrchestrationV2UserMessageInputIntent.Type;
1658
1659 /** Notices without a level predate it and are warnings. */
1660 const OrchestrationV2SystemNoticeLevel = Schema.Literals(["info", "warning", "error"]);
1661
1662 /** A notice about an MCP server that a sign-in from the thread would fix. */
1663 const OrchestrationV2McpSignIn = Schema.Struct({ server: Schema.String });
1664
1665 /** A same-harness model or effort change that took effect with this message. */
1666 export const OrchestrationV2ModelSwitch = Schema.Struct({
1667 from: ModelSelection,
1668 to: ModelSelection,
1669 });
1670 export type OrchestrationV2ModelSwitch = typeof OrchestrationV2ModelSwitch.Type;
1671
1672 const AssistantMessagePhase = Schema.Literals(["commentary", "partial_answer", "final_answer"]);
1673
1674 const OrchestrationV2TurnItemBaseFields = {
1675 /** Wire-only cursor for collapsed work; persisted items keep their complete history. */
1676 deferredWork: Schema.optionalKey(
1677 Schema.Struct({
1678 cursor: TrimmedNonEmptyString,
1679 itemCount: PositiveInt,
1680 lastOrdinal: NonNegativeInt,
1681 }),
1682 ),
1683 toolNonExecutionKind: Schema.optional(Schema.String),
1684 toolSurface: Schema.optional(ToolActivitySurface),
1685 toolIcon: Schema.optional(ToolActivityIcon),
1686 toolSource: Schema.optional(ToolActivitySource),
1687 id: TurnItemId,
1688 threadId: ThreadId,
1689 runId: Schema.NullOr(RunId),
1690 nodeId: Schema.NullOr(NodeId),
1691 providerThreadId: Schema.NullOr(ProviderThreadId),
1692 providerTurnId: Schema.NullOr(ProviderTurnId),
1693 nativeItemRef: Schema.NullOr(OrchestrationV2ProviderRef),
1694 parentItemId: Schema.NullOr(TurnItemId),
1695 ordinal: NonNegativeInt,
1696 status: OrchestrationV2TurnItemStatus,
1697 title: Schema.NullOr(Schema.String),
1698 startedAt: Schema.NullOr(Schema.DateTimeUtc),
1699 completedAt: Schema.NullOr(Schema.DateTimeUtc),
1700 updatedAt: Schema.DateTimeUtc,
1701 } as const;
1702
1703 export const OrchestrationV2FileSearchResult = Schema.Struct({
1704 fileName: TrimmedNonEmptyString,
1705 line: Schema.optional(PositiveInt),
1706 column: Schema.optional(PositiveInt),
1707 preview: Schema.optional(Schema.String),
1708 });
1709 export type OrchestrationV2FileSearchResult = typeof OrchestrationV2FileSearchResult.Type;
1710
1711 export const OrchestrationV2WebSearchResult = Schema.Struct({
1712 title: Schema.optional(Schema.String),
1713 url: Schema.optional(TrimmedNonEmptyString),
1714 snippet: Schema.optional(Schema.String),
1715 });
1716 export type OrchestrationV2WebSearchResult = typeof OrchestrationV2WebSearchResult.Type;
1717
1718 export const OrchestrationV2SecretRequestStatus = Schema.Literals([
1719 "pending",
1720 "saved",
1721 "declined",
1722 "cancelled",
1723 ]);
1724 export type OrchestrationV2SecretRequestStatus = typeof OrchestrationV2SecretRequestStatus.Type;
1725
1726 /** `file`: the value goes to an owner-only file the agent's shell commands can read. */
1727 export const OrchestrationV2SecretRequestDelivery = Schema.Literal("file");
1728
1729 /** One input of a multi-value card. `secret: false` shows what the user types, such as an email. */
1730 export const OrchestrationV2SecretRequestField = Schema.Struct({
1731 name: TrimmedNonEmptyString,
1732 label: TrimmedNonEmptyString,
1733 placeholder: Schema.optional(Schema.String),
1734 secret: Schema.optional(Schema.Boolean),
1735 });
1736 export type OrchestrationV2SecretRequestField = typeof OrchestrationV2SecretRequestField.Type;
1737
1738 const OrchestrationV2SecretRequestFields = {
1739 type: Schema.Literal("secret_request"),
1740 label: TrimmedNonEmptyString,
1741 reason: Schema.String,
1742 url: Schema.optional(Schema.String),
1743 placeholder: Schema.optional(Schema.String),
1744 delivery: Schema.optional(OrchestrationV2SecretRequestDelivery),
1745 fields: Schema.optional(Schema.Array(OrchestrationV2SecretRequestField)),
1746 secretStatus: OrchestrationV2SecretRequestStatus,
1747 } as const;
1748
1749 export const OrchestrationV2LinkRequestStatus = Schema.Literals([
1750 "pending",
1751 "linked",
1752 "declined",
1753 "cancelled",
1754 "failed",
1755 ]);
1756 export type OrchestrationV2LinkRequestStatus = typeof OrchestrationV2LinkRequestStatus.Type;
1757
1758 /**
1759 * An agent asked the user to link another environment. The user picks the
1760 * access; the pairing code never passes through orchestration, so the item
1761 * carries only what was asked and how it ended.
1762 */
1763 const OrchestrationV2LinkRequestFields = {
1764 type: Schema.Literal("link_request"),
1765 /** The address the agent named, if it named one. */
1766 url: Schema.optional(TrimmedNonEmptyString),
1767 reason: Schema.String,
1768 /**
1769 * The environment the agent named. Without it or `url` the user picks the
1770 * machine in the card. Beside a `url`, this and `label` are what answered
1771 * there on an older server: unauthenticated, so clients ignore both.
1772 */
1773 environmentId: Schema.optional(EnvironmentId),
1774 label: Schema.optional(Schema.String),
1775 /** A phrase from the user's words, such as "vps", that preselects a machine. */
1776 hint: Schema.optional(Schema.String),
1777 /** The access the agent suggested; the user's choice is final. */
1778 requestedAccess: Schema.optional(AuthMcpClientAccess),
1779 linkStatus: OrchestrationV2LinkRequestStatus,
1780 linkedEnvironmentId: Schema.optional(EnvironmentId),
1781 linkedLabel: Schema.optional(Schema.String),
1782 linkedAccess: Schema.optional(AuthMcpClientAccess),
1783 failure: Schema.optional(Schema.String),
1784 } as const;
1785
1786 export const OrchestrationV2TurnItem = Schema.Union([
1787 Schema.Struct({
1788 ...OrchestrationV2TurnItemBaseFields,
1789 type: Schema.Literal("notification"),
1790 ...OrchestrationV2Notification.fields,
1791 }),
1792 Schema.Struct({
1793 ...OrchestrationV2TurnItemBaseFields,
1794 ...OrchestrationV2CreationFields,
1795 type: Schema.Literal("user_message"),
1796 messageId: MessageId,
1797 scheduledTaskId: Schema.optional(ScheduledTaskId),
1798 senderThreadId: Schema.optional(ThreadId),
1799 linkedSender: Schema.optional(OrchestrationV2LinkedSender),
1800 idleCompaction: Schema.optional(OrchestrationV2IdleCompaction),
1801 workflowScript: OrchestrationV2ConversationMessage.fields.workflowScript,
1802 freshContext: OrchestrationV2Run.fields.freshContext,
1803 inputIntent: OrchestrationV2UserMessageInputIntent,
1804 text: Schema.String,
1805 /** Same as the text of message `messageId`. */
1806 textOmitted: DedupedBodyMarker,
1807 context: Schema.optional(OrchestrationMessageContext),
1808 attachments: Schema.Array(ChatAttachment),
1809 modelSwitch: Schema.optional(OrchestrationV2ModelSwitch),
1810 }),
1811 Schema.Struct({
1812 ...OrchestrationV2TurnItemBaseFields,
1813 type: Schema.Literal("assistant_message"),
1814 phase: Schema.optional(AssistantMessagePhase),
1815 messageId: MessageId,
1816 text: Schema.String,
1817 textOmitted: DedupedBodyMarker,
1818 attachments: Schema.optional(Schema.Array(ChatAttachment)),
1819 streaming: Schema.Boolean,
1820 }),
1821 Schema.Struct({
1822 ...OrchestrationV2TurnItemBaseFields,
1823 type: Schema.Literal("reasoning"),
1824 text: Schema.String,
1825 streaming: Schema.Boolean,
1826 }),
1827 Schema.Struct({
1828 ...OrchestrationV2TurnItemBaseFields,
1829 type: Schema.Literal("proposed_plan"),
1830 planId: PlanId,
1831 markdown: Schema.String,
1832 streaming: Schema.Boolean,
1833 }),
1834 Schema.Struct({
1835 ...OrchestrationV2TurnItemBaseFields,
1836 type: Schema.Literal("todo_list"),
1837 planId: PlanId,
1838 steps: Schema.Array(OrchestrationV2PlanStep),
1839 explanation: Schema.optional(Schema.String),
1840 }),
1841 Schema.Struct({
1842 ...OrchestrationV2TurnItemBaseFields,
1843 type: Schema.Literal("user_input_request"),
1844 requestId: RuntimeRequestId,
1845 questions: Schema.Array(OrchestrationV2UserInputQuestion),
1846 questionAnswer: Schema.optional(UserInputAttachmentAnswerPayload),
1847 responseMode: Schema.optional(Schema.Literal("message")),
1848 }),
1849 Schema.Struct({
1850 ...OrchestrationV2TurnItemBaseFields,
1851 type: Schema.Literal("file_change"),
1852 fileName: TrimmedNonEmptyString,
1853 additions: Schema.optional(NonNegativeInt),
1854 deletions: Schema.optional(NonNegativeInt),
1855 diffStr: Schema.optional(Schema.String),
1856 oldStr: Schema.optional(Schema.String),
1857 newStr: Schema.optional(Schema.String),
1858 changes: Schema.optional(Schema.Array(OrchestrationV2FileChangeDetail)),
1859 }),
1860 Schema.Struct({
1861 ...OrchestrationV2TurnItemBaseFields,
1862 type: Schema.Literal("command_execution"),
1863 input: Schema.String,
1864 output: Schema.optional(Schema.String),
1865 /** Set on the wire when output was withheld; fetch it with getTurnItem. */
1866 outputOmitted: Schema.optional(Schema.Boolean),
1867 outputIndicatesFailure: Schema.optional(Schema.Boolean),
1868 exitCode: Schema.optional(Schema.Int),
1869 /** Set when the command is a monitor, so background work lists it as a monitor. */
1870 monitor: Schema.optional(Schema.Boolean),
1871 /** The provider wakes the agent when this command finishes after its turn. */
1872 completionWake: Schema.optional(Schema.Literal("always")),
1873 }),
1874 Schema.Struct({
1875 ...OrchestrationV2TurnItemBaseFields,
1876 type: Schema.Literal("file_search"),
1877 pattern: Schema.optional(Schema.String),
1878 results: Schema.optional(Schema.Array(OrchestrationV2FileSearchResult)),
1879 }),
1880 Schema.Struct({
1881 ...OrchestrationV2TurnItemBaseFields,
1882 type: Schema.Literal("web_search"),
1883 patterns: Schema.optional(Schema.Array(Schema.String)),
1884 results: Schema.optional(Schema.Array(OrchestrationV2WebSearchResult)),
1885 }),
1886 Schema.Struct({
1887 ...OrchestrationV2TurnItemBaseFields,
1888 type: Schema.Literal("approval_request"),
1889 requestId: RuntimeRequestId,
1890 requestKind: ProviderRequestKind,
1891 prompt: Schema.optional(Schema.String),
1892 reason: Schema.optional(Schema.String),
1893 fullAccessOverride: Schema.optional(ProviderApprovalFullAccessOverride),
1894 appName: Schema.optional(Schema.String),
1895 options: Schema.optional(Schema.Array(ProviderApprovalOption)),
1896 }),
1897 Schema.Struct({
1898 ...OrchestrationV2TurnItemBaseFields,
1899 type: Schema.Literal("checkpoint"),
1900 checkpointId: CheckpointId,
1901 scopeId: CheckpointScopeId,
1902 files: Schema.Array(OrchestrationV2CheckpointFileSummary),
1903 filesTotal: Schema.optionalKey(OrchestrationV2CheckpointFileTotals),
1904 /** Same as the files of checkpoint `checkpointId`. */
1905 filesOmitted: DedupedBodyMarker,
1906 }),
1907 Schema.Struct({
1908 ...OrchestrationV2TurnItemBaseFields,
1909 type: Schema.Literal("run_interrupt_request"),
1910 message: Schema.String,
1911 /** Set when the provider did not confirm the stop in time; clients then offer Force stop. */
1912 unresponsiveAt: Schema.optionalKey(Schema.DateTimeUtc),
1913 }),
1914 Schema.Struct({
1915 ...OrchestrationV2TurnItemBaseFields,
1916 type: Schema.Literal("run_interrupt_result"),
1917 message: Schema.String,
1918 }),
1919 Schema.Struct({
1920 ...OrchestrationV2TurnItemBaseFields,
1921 type: Schema.Literal("system_notice"),
1922 message: Schema.String,
1923 level: Schema.optional(OrchestrationV2SystemNoticeLevel),
1924 mcpSignIn: Schema.optional(OrchestrationV2McpSignIn),
1925 }),
1926 Schema.Struct({
1927 ...OrchestrationV2TurnItemBaseFields,
1928 type: Schema.Literal("error"),
1929 failure: OrchestrationV2ProviderFailure,
1930 retry: Schema.optional(OrchestrationV2ProviderRetry),
1931 }),
1932 Schema.Struct({
1933 ...OrchestrationV2TurnItemBaseFields,
1934 type: Schema.Literal("compaction"),
1935 driver: Schema.NullOr(ProviderDriverKind),
1936 summary: Schema.optional(Schema.String),
1937 beforeTokenCount: Schema.optional(NonNegativeInt),
1938 afterTokenCount: Schema.optional(NonNegativeInt),
1939 }),
1940 Schema.Struct({
1941 ...OrchestrationV2TurnItemBaseFields,
1942 type: Schema.Literal("handoff"),
1943 contextHandoffId: ContextHandoffId,
1944 fromProviderThreadIds: Schema.Array(ProviderThreadId),
1945 toProviderThreadId: ProviderThreadId,
1946 fromProviderInstanceIds: Schema.Array(ProviderInstanceId),
1947 toProviderInstanceId: ProviderInstanceId,
1948 fromModelSelections: Schema.optional(Schema.Array(ModelSelection)),
1949 toModel: Schema.optional(Schema.String),
1950 strategy: Schema.Literals([
1951 "delta_since_target_last_seen",
1952 "fork_delta_summary",
1953 "full_thread_summary",
1954 "checkpoint_summary",
1955 "manual_context",
1956 ]),
1957 summary: Schema.optional(Schema.String),
1958 }),
1959 Schema.Struct({
1960 ...OrchestrationV2TurnItemBaseFields,
1961 type: Schema.Literal("fork"),
1962 source: Schema.Union([
1963 Schema.Struct({ type: Schema.Literal("run"), threadId: ThreadId, runId: RunId }),
1964 Schema.Struct({ type: Schema.Literal("node"), nodeId: NodeId }),
1965 Schema.Struct({
1966 type: Schema.Literal("provider_thread"),
1967 providerThreadId: ProviderThreadId,
1968 providerTurnId: Schema.optional(ProviderTurnId),
1969 }),
1970 ]),
1971 targetThreadId: ThreadId,
1972 providerThreadId: Schema.optional(ProviderThreadId),
1973 }),
1974 Schema.Struct({
1975 ...OrchestrationV2TurnItemBaseFields,
1976 type: Schema.Literal("thread_created"),
1977 targetThreadId: ThreadId,
1978 targetRunId: Schema.NullOr(RunId),
1979 targetProviderInstanceId: ProviderInstanceId,
1980 targetModel: TrimmedNonEmptyString,
1981 }),
1982 Schema.Struct({
1983 ...OrchestrationV2TurnItemBaseFields,
1984 ...OrchestrationV2SecretRequestFields,
1985 }),
1986 Schema.Struct({
1987 ...OrchestrationV2TurnItemBaseFields,
1988 ...OrchestrationV2LinkRequestFields,
1989 }),
1990 Schema.Struct({
1991 ...OrchestrationV2TurnItemBaseFields,
1992 type: Schema.Literal("subagent"),
1993 subagentId: NodeId,
1994 origin: Schema.Literals(["provider_native", "app_owned"]),
1995 driver: ProviderDriverKind,
1996 providerInstanceId: ProviderInstanceId,
1997 childThreadId: Schema.NullOr(ThreadId),
1998 remoteChild: Schema.optional(OrchestrationV2RemoteTaskChild),
1999 prompt: Schema.String,
2000 progress: Schema.optional(Schema.String),
2001 result: Schema.NullOr(Schema.String),
2002 /** Same as the prompt and result of subagent `subagentId`. */
2003 promptOmitted: DedupedBodyMarker,
2004 resultOmitted: DedupedBodyMarker,
2005 }),
2006 Schema.Struct({
2007 ...OrchestrationV2TurnItemBaseFields,
2008 type: Schema.Literal("dynamic_tool"),
2009 toolName: Schema.NullOr(TrimmedNonEmptyString),
2010 viewedImagePath: Schema.optional(TrimmedNonEmptyString),
2011 input: Schema.Unknown,
2012 output: Schema.optional(Schema.Unknown),
2013 /** Set on the wire when output was withheld; fetch it with getTurnItem. */
2014 outputOmitted: Schema.optional(Schema.Boolean),
2015 }),
2016 ]);
2017 export type OrchestrationV2TurnItem = typeof OrchestrationV2TurnItem.Type;
2018
2019 const isUnknownTurnItem = hasUnknownUnionTag(OrchestrationV2TurnItem.members, "type");
2020
2021 const turnItemArray = <Members extends ReadonlyArray<Schema.Top & { readonly fields: object }>>(
2022 union: Schema.Union<Members>,
2023 ) => ForwardCompatibleUnionArray(union.members, "type");
2024
2025 const projectedTurnItemArray = <Row extends Schema.Top, Item extends Schema.Top>(
2026 row: Row,
2027 rowWithUnknownItem: Item,
2028 ) =>
2029 Schema.Array(rowWithUnknownItem).pipe(
2030 Schema.decodeTo(
2031 Schema.Array(Schema.toType(row)),
2032 SchemaTransformation.transform<ReadonlyArray<Row["Type"]>, ReadonlyArray<Item["Type"]>>({
2033 decode: (rows) =>
2034 rows.filter(
2035 (projected) => !isUnknownUnionMember((projected as { readonly item: unknown }).item),
2036 ) as ReadonlyArray<Row["Type"]>,
2037 encode: (rows) => rows,
2038 }),
2039 ),
2040 );
2041
2042 export const OrchestrationV2ProjectedTurnItem = Schema.Struct({
2043 position: NonNegativeInt,
2044 visibility: Schema.Literals(["local", "inherited", "synthetic"]),
2045 sourceThreadId: ThreadId,
2046 sourceItemId: TurnItemId,
2047 item: OrchestrationV2TurnItem,
2048 });
2049 export type OrchestrationV2ProjectedTurnItem = typeof OrchestrationV2ProjectedTurnItem.Type;
2050
2051 const OrchestrationV2EventBase = Schema.Struct({
2052 id: EventId,
2053 threadId: ThreadId,
2054 runId: Schema.optional(RunId),
2055 nodeId: Schema.optional(NodeId),
2056 driver: Schema.optional(ProviderDriverKind),
2057 providerInstanceId: Schema.optional(ProviderInstanceId),
2058 rawEventId: Schema.optional(RawEventId),
2059 occurredAt: Schema.DateTimeUtc,
2060 });
2061
2062 export const OrchestrationV2DomainEvent = Schema.Union([
2063 Schema.Struct({
2064 ...OrchestrationV2EventBase.fields,
2065 type: Schema.Literal("thread.created"),
2066 payload: OrchestrationV2AppThread,
2067 }),
2068 Schema.Struct({
2069 ...OrchestrationV2EventBase.fields,
2070 type: Schema.Literals([
2071 "thread.archived",
2072 "thread.unarchived",
2073 "thread.deleted",
2074 "thread.settled",
2075 "thread.unsettled",
2076 "thread.snoozed",
2077 "thread.unsnoozed",
2078 "thread.pinned",
2079 "thread.auto-settle-set",
2080 "thread.unpinned",
2081 "thread.pin-reordered",
2082 "thread.active-reordered",
2083 "thread.tags-updated",
2084 "thread.visited",
2085 "thread.marked-unread",
2086 "thread.metadata-updated",
2087 "thread.pull-request-synced",
2088 "thread.issue-synced",
2089 "thread.runtime-mode-updated",
2090 "thread.interaction-mode-updated",
2091 "thread.model-selection-updated",
2092 "thread.provider-switched",
2093 "thread.guest-share-updated",
2094 ]),
2095 payload: OrchestrationV2AppThread,
2096 }),
2097 Schema.Struct({
2098 ...OrchestrationV2EventBase.fields,
2099 type: Schema.Literal("thread.pull-request-link-updated"),
2100 payload: ThreadPullRequestLink,
2101 }),
2102 Schema.Struct({
2103 ...OrchestrationV2EventBase.fields,
2104 type: Schema.Literal("thread.visit-recorded"),
2105 payload: OrchestrationV2ThreadVisit,
2106 }),
2107 Schema.Struct({
2108 ...OrchestrationV2EventBase.fields,
2109 type: Schema.Literal("run.created"),
2110 payload: OrchestrationV2Run,
2111 }),
2112 Schema.Struct({
2113 ...OrchestrationV2EventBase.fields,
2114 type: Schema.Literal("run.updated"),
2115 payload: OrchestrationV2Run,
2116 }),
2117 Schema.Struct({
2118 ...OrchestrationV2EventBase.fields,
2119 type: Schema.Literal("run.background-work-cancelled"),
2120 payload: OrchestrationV2RunBackgroundWorkCancelled,
2121 }),
2122 Schema.Struct({
2123 ...OrchestrationV2EventBase.fields,
2124 type: Schema.Literal("run.output-submitted"),
2125 payload: OrchestrationV2RunOutputSubmitted,
2126 }),
2127 Schema.Struct({
2128 ...OrchestrationV2EventBase.fields,
2129 type: Schema.Literal("run-attempt.created"),
2130 payload: OrchestrationV2RunAttempt,
2131 }),
2132 Schema.Struct({
2133 ...OrchestrationV2EventBase.fields,
2134 type: Schema.Literal("run-attempt.updated"),
2135 payload: OrchestrationV2RunAttempt,
2136 }),
2137 Schema.Struct({
2138 ...OrchestrationV2EventBase.fields,
2139 type: Schema.Literal("node.updated"),
2140 payload: OrchestrationV2ExecutionNode,
2141 }),
2142 Schema.Struct({
2143 ...OrchestrationV2EventBase.fields,
2144 type: Schema.Literal("subagent.updated"),
2145 payload: OrchestrationV2Subagent,
2146 }),
2147 Schema.Struct({
2148 ...OrchestrationV2EventBase.fields,
2149 type: Schema.Literals(["provider-session.attached", "provider-session.updated"]),
2150 payload: OrchestrationV2ProviderSession,
2151 }),
2152 Schema.Struct({
2153 ...OrchestrationV2EventBase.fields,
2154 type: Schema.Literal("provider-session.detached"),
2155 payload: OrchestrationV2ProviderSessionDetached,
2156 }),
2157 Schema.Struct({
2158 ...OrchestrationV2EventBase.fields,
2159 type: Schema.Literal("provider-thread.updated"),
2160 payload: OrchestrationV2ProviderThread,
2161 }),
2162 Schema.Struct({
2163 ...OrchestrationV2EventBase.fields,
2164 type: Schema.Literal("provider-turn.updated"),
2165 payload: OrchestrationV2ProviderTurn,
2166 }),
2167 Schema.Struct({
2168 ...OrchestrationV2EventBase.fields,
2169 type: Schema.Literal("runtime-request.updated"),
2170 payload: OrchestrationV2RuntimeRequest,
2171 }),
2172 Schema.Struct({
2173 ...OrchestrationV2EventBase.fields,
2174 type: Schema.Literal("message.updated"),
2175 payload: OrchestrationV2ConversationMessage,
2176 }),
2177 Schema.Struct({
2178 ...OrchestrationV2EventBase.fields,
2179 type: Schema.Literal("turn-item.updated"),
2180 payload: OrchestrationV2TurnItem,
2181 }),
2182 Schema.Struct({
2183 ...OrchestrationV2EventBase.fields,
2184 type: Schema.Literal("plan.updated"),
2185 payload: OrchestrationV2PlanArtifact,
2186 }),
2187 Schema.Struct({
2188 ...OrchestrationV2EventBase.fields,
2189 type: Schema.Literal("checkpoint-scope.created"),
2190 payload: OrchestrationV2CheckpointScope,
2191 }),
2192 Schema.Struct({
2193 ...OrchestrationV2EventBase.fields,
2194 type: Schema.Literal("checkpoint.captured"),
2195 payload: OrchestrationV2Checkpoint,
2196 }),
2197 Schema.Struct({
2198 ...OrchestrationV2EventBase.fields,
2199 type: Schema.Literal("checkpoint.rollback-requested"),
2200 payload: OrchestrationV2CheckpointRollbackRequest,
2201 }),
2202 Schema.Struct({
2203 ...OrchestrationV2EventBase.fields,
2204 type: Schema.Literal("context-handoff.updated"),
2205 payload: OrchestrationV2ContextHandoff,
2206 }),
2207 Schema.Struct({
2208 ...OrchestrationV2EventBase.fields,
2209 type: Schema.Literal("context-transfer.created"),
2210 payload: OrchestrationV2ContextTransfer,
2211 }),
2212 Schema.Struct({
2213 ...OrchestrationV2EventBase.fields,
2214 type: Schema.Literal("context-transfer.updated"),
2215 payload: OrchestrationV2ContextTransfer,
2216 }),
2217 ]);
2218 export type OrchestrationV2DomainEvent = typeof OrchestrationV2DomainEvent.Type;
2219
2220 export const OrchestrationV2ThreadProjection = Schema.Struct({
2221 thread: OrchestrationV2AppThread,
2222 runs: Schema.Array(OrchestrationV2Run),
2223 attempts: Schema.Array(OrchestrationV2RunAttempt),
2224 nodes: Schema.Array(OrchestrationV2ExecutionNode),
2225 subagents: Schema.Array(OrchestrationV2Subagent),
2226 providerSessions: Schema.Array(OrchestrationV2ProviderSession),
2227 providerThreads: Schema.Array(OrchestrationV2ProviderThread),
2228 providerTurns: Schema.Array(OrchestrationV2ProviderTurn),
2229 runtimeRequests: Schema.Array(OrchestrationV2RuntimeRequest),
2230 messages: Schema.Array(OrchestrationV2ConversationMessage),
2231 plans: Schema.Array(OrchestrationV2PlanArtifact),
2232 turnItems: turnItemArray(OrchestrationV2TurnItem),
2233 checkpointScopes: Schema.Array(OrchestrationV2CheckpointScope),
2234 checkpoints: Schema.Array(OrchestrationV2Checkpoint),
2235 contextHandoffs: Schema.Array(OrchestrationV2ContextHandoff),
2236 contextTransfers: Schema.Array(OrchestrationV2ContextTransfer),
2237 visibleTurnItems: projectedTurnItemArray(
2238 OrchestrationV2ProjectedTurnItem,
2239 OrchestrationV2ProjectedTurnItem.mapFields((fields) => ({
2240 ...fields,
2241 item: ForwardCompatibleUnion(OrchestrationV2TurnItem.members, "type"),
2242 })),
2243 ),
2244 updatedAt: Schema.DateTimeUtc,
2245 });
2246 export type OrchestrationV2ThreadProjection = typeof OrchestrationV2ThreadProjection.Type;
2247
2248 export const OrchestrationV2ThreadTranscript = Schema.Struct({
2249 threadId: ThreadId,
2250 title: Schema.String,
2251 updatedAt: Schema.DateTimeUtc,
2252 items: Schema.Array(OrchestrationV2ProjectedTurnItem),
2253 });
2254 export type OrchestrationV2ThreadTranscript = typeof OrchestrationV2ThreadTranscript.Type;
2255
2256 export const OrchestrationV2ShellThreadStatus = Schema.Union([
2257 Schema.Literal("idle"),
2258 OrchestrationV2RunStatus,
2259 ]);
2260 export type OrchestrationV2ShellThreadStatus = typeof OrchestrationV2ShellThreadStatus.Type;
2261
2262 export const OrchestrationV2PendingRuntimeRequestSummary = Schema.Struct({
2263 id: RuntimeRequestId,
2264 kind: OrchestrationV2RuntimeRequest.fields.kind,
2265 createdAt: Schema.DateTimeUtc,
2266 /** False for async questions the run keeps working past. Absent from older servers. */
2267 blocking: Schema.optional(Schema.Boolean),
2268 /** Secret and link cards: only the user can answer them, never a coordinating agent. */
2269 userOnly: Schema.optional(Schema.Boolean),
2270 });
2271 export type OrchestrationV2PendingRuntimeRequestSummary =
2272 typeof OrchestrationV2PendingRuntimeRequestSummary.Type;
2273
2274 export const OrchestrationV2LatestVisibleMessageSummary = Schema.Struct({
2275 id: MessageId,
2276 role: OrchestrationV2ConversationMessage.fields.role,
2277 text: Schema.String,
2278 updatedAt: Schema.DateTimeUtc,
2279 });
2280 export type OrchestrationV2LatestVisibleMessageSummary =
2281 typeof OrchestrationV2LatestVisibleMessageSummary.Type;
2282
2283 export const OrchestrationV2ThreadShell = Schema.Struct({
2284 ...OrchestrationV2CreationFields,
2285 id: ThreadId,
2286 projectId: ProjectId,
2287 title: Schema.String,
2288 providerInstanceId: ProviderInstanceId,
2289 modelSelection: ModelSelection,
2290 runtimeMode: RuntimeMode,
2291 interactionMode: ProviderInteractionMode,
2292 branch: Schema.NullOr(TrimmedNonEmptyString),
2293 worktreePath: Schema.NullOr(TrimmedNonEmptyString),
2294 linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),
2295 pullRequests: Schema.optional(Schema.Array(ThreadPullRequestLink)),
2296 branchPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),
2297 /** Issues linked to this thread; optional so pre-linking servers still decode. */
2298 issues: Schema.optional(Schema.Array(ThreadIssueLink)),
2299 lineage: OrchestrationV2AppThreadLineage,
2300 forkedFrom: Schema.NullOr(OrchestrationV2AppThread.fields.forkedFrom),
2301 activeProviderThreadId: Schema.NullOr(ProviderThreadId),
2302 historyOrigin: Schema.optional(OrchestrationV2ThreadHistoryOrigin),
2303 linkOrigin: Schema.optional(OrchestrationV2LinkOrigin),
2304 delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom),
2305 latestRunId: Schema.NullOr(RunId),
2306 latestRunRequestedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
2307 latestRunStartedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
2308 latestRunCompletedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
2309 latestRunStopRequested: Schema.optional(Schema.Boolean),
2310 /** The latest run answers a background-work progress wake, like a Monitor line, not a terminal one. Absent from older servers. */
2311 latestRunBackgroundWake: Schema.optional(Schema.Boolean),
2312 activeRunId: Schema.NullOr(RunId),
2313 activityRunStartedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
2314 activityRunStatus: Schema.optional(
2315 Schema.NullOr(Schema.Literals(["preparing", "starting", "running", "waiting"])),
2316 ),
2317 blockedOnThreadWait: Schema.optional(Schema.Boolean),
2318 status: OrchestrationV2ShellThreadStatus,
2319 lastError: Schema.optional(Schema.NullOr(Schema.String)),
2320 lastErrorClass: Schema.optional(Schema.NullOr(OrchestrationV2ProviderFailureClass)),
2321 lastErrorCode: Schema.optional(Schema.NullOr(Schema.String)),
2322 usageLimitResetAt: Schema.optional(Schema.NullOr(IsoDateTime)),
2323 pendingRuntimeRequest: Schema.NullOr(OrchestrationV2PendingRuntimeRequestSummary),
2324 /** Guest messages waiting for the owner to send or dismiss. Absent from older servers. */
2325 pendingGuestMessageCount: Schema.optional(NonNegativeInt),
2326 latestVisibleMessage: Schema.NullOr(OrchestrationV2LatestVisibleMessageSummary),
2327 latestUserMessageAt: Schema.NullOr(Schema.DateTimeUtc),
2328 /** Excludes wakes and agent messages that advance latestUserMessageAt through the user role. */
2329 latestUserAuthoredMessageAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
2330 hasActionableProposedPlan: Schema.Boolean,
2331 pendingBackgroundTasks: Schema.optional(Schema.Array(OrchestrationV2PendingBackgroundTask)).pipe(
2332 Schema.withDecodingDefault(Effect.succeed([])),
2333 ),
2334 providerInstanceHistory: Schema.optional(Schema.Array(ProviderInstanceId)).pipe(
2335 Schema.withDecodingDefault(Effect.succeed([])),
2336 ),
2337 goal: Schema.optional(Schema.NullOr(OrchestrationV2ProviderGoal)),
2338 itemCount: NonNegativeInt,
2339 visibleItemCount: NonNegativeInt,
2340 createdAt: Schema.DateTimeUtc,
2341 updatedAt: Schema.DateTimeUtc,
2342 archivedAt: Schema.NullOr(Schema.DateTimeUtc),
2343 settledOverride: Schema.NullOr(Schema.Literals(["settled", "active"])),
2344 settledAt: Schema.NullOr(Schema.DateTimeUtc),
2345 unsettledAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
2346 snoozedUntil: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
2347 snoozedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
2348 limitRecovery: Schema.optional(Schema.NullOr(OrchestrationV2LimitRecovery)),
2349 pinnedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
2350 autoSettleDisabledAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
2351 pinOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
2352 activeOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
2353 /** Absent on threads written before tags existed; read as empty. */
2354 tags: Schema.optional(StoredThreadTags),
2355 lastVisitedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
2356 opens: Schema.optional(LenientThreadOpens),
2357 titleRegeneration: Schema.optional(
2358 Schema.NullOr(
2359 Schema.Struct({
2360 requestId: CommandId,
2361 startedAt: Schema.DateTimeUtc,
2362 }),
2363 ),
2364 ),
2365 lastTitleRegeneration: Schema.optional(Schema.NullOr(OrchestrationV2LastTitleRegeneration)),
2366 deletedAt: Schema.NullOr(Schema.DateTimeUtc),
2367 });
2368 export type OrchestrationV2ThreadShell = typeof OrchestrationV2ThreadShell.Type;
2369
2370 const LIVE_SHELL_STATUSES: ReadonlySet<OrchestrationV2ShellThreadStatus> = new Set([
2371 "queued",
2372 "preparing",
2373 "starting",
2374 "running",
2375 "waiting",
2376 ]);
2377
2378 /**
2379 * A subagent child that can still need the user or hold its parent. Shells that omit idle children
2380 * keep these, so every reader of live child rows (pending requests, working parents, background
2381 * work) still finds them.
2382 */
2383 export function isLiveSubagentShell(
2384 thread: Pick<
2385 OrchestrationV2ThreadShell,
2386 "activityRunStatus" | "status" | "pendingRuntimeRequest" | "pendingBackgroundTasks"
2387 >,
2388 ): boolean {
2389 return (
2390 (thread.activityRunStatus ?? null) !== null ||
2391 LIVE_SHELL_STATUSES.has(thread.status) ||
2392 thread.pendingRuntimeRequest !== null ||
2393 (thread.pendingBackgroundTasks?.length ?? 0) > 0
2394 );
2395 }
2396
2397 /**
2398 * A settled top-level thread settled before `beforeMs`. Shells that omit older settled threads
2399 * count every such thread, so the server and clients share this one rule.
2400 */
2401 export function isOlderSettledThreadShell(
2402 thread: Pick<OrchestrationV2ThreadShell, "lineage" | "settledOverride" | "settledAt">,
2403 beforeMs: number,
2404 ): boolean {
2405 return (
2406 isListedThreadLineage(thread.lineage) &&
2407 thread.settledOverride === "settled" &&
2408 thread.settledAt !== null &&
2409 DateTime.toEpochMillis(thread.settledAt) < beforeMs
2410 );
2411 }
2412
2413 export const OrchestrationV2OlderSettledCount = Schema.Struct({
2414 projectId: ProjectId,
2415 count: NonNegativeInt,
2416 });
2417 export type OrchestrationV2OlderSettledCount = typeof OrchestrationV2OlderSettledCount.Type;
2418
2419 /**
2420 * Snapshots that leave out older settled threads (`omitOlderSettled`) name the cut and count, per
2421 * project, every thread `isOlderSettledThreadShell` matches, sent or not. `asOfSequence` is the
2422 * snapshot's own sequence: the counts are exact until a later change.
2423 */
2424 export const OrchestrationV2OlderSettledThreads = Schema.Struct({
2425 before: IsoDateTime,
2426 asOfSequence: NonNegativeInt,
2427 counts: Schema.Array(OrchestrationV2OlderSettledCount),
2428 });
2429 export type OrchestrationV2OlderSettledThreads = typeof OrchestrationV2OlderSettledThreads.Type;
2430
2431 export const OrchestrationV2ThreadShellSnapshot = Schema.Struct({
2432 schemaVersion: PositiveInt,
2433 snapshotSequence: NonNegativeInt,
2434 threads: Schema.Array(OrchestrationV2ThreadShell),
2435 archivedThreads: Schema.Array(OrchestrationV2ThreadShell),
2436 });
2437 export type OrchestrationV2ThreadShellSnapshot = typeof OrchestrationV2ThreadShellSnapshot.Type;
2438
2439 export const OrchestrationV2ShellSnapshot = Schema.Struct({
2440 ...OrchestrationV2ThreadShellSnapshot.fields,
2441 projects: Schema.Array(OrchestrationProjectShell),
2442 olderSettled: Schema.optionalKey(OrchestrationV2OlderSettledThreads),
2443 });
2444 export type OrchestrationV2ShellSnapshot = typeof OrchestrationV2ShellSnapshot.Type;
2445
2446 /** The HTTP shell snapshot. `projectIdentities` names its repository identities; see `knownProjectIdentities`. */
2447 export const OrchestrationV2ShellHttpSnapshot = Schema.Struct({
2448 ...OrchestrationV2ShellSnapshot.fields,
2449 projectIdentities: Schema.optionalKey(Schema.String),
2450 });
2451 export type OrchestrationV2ShellHttpSnapshot = typeof OrchestrationV2ShellHttpSnapshot.Type;
2452
2453 /**
2454 * The HTTP shell route's answer to `resumeFrom` when the socket can replay from that cursor:
2455 * the client keeps its rows and subscribes from the cursor.
2456 */
2457 export const OrchestrationV2ShellResumable = Schema.Struct({
2458 resumable: Schema.Literal(true),
2459 });
2460 export type OrchestrationV2ShellResumable = typeof OrchestrationV2ShellResumable.Type;
2461
2462 export const OrchestrationV2ShellStreamItem = Schema.Union([
2463 Schema.Struct({
2464 kind: Schema.Literal("synchronized"),
2465 }),
2466 /**
2467 * The only item of a resume the server cannot replay when the client asked for
2468 * `httpSnapshotFallback`: load the HTTP snapshot and subscribe again from its cursor.
2469 */
2470 Schema.Struct({
2471 kind: Schema.Literal("snapshot-required"),
2472 }),
2473 Schema.Struct({
2474 kind: Schema.Literal("snapshot"),
2475 snapshot: OrchestrationV2ShellSnapshot,
2476 resolvedRepositoryIdentityRoots: Schema.optionalKey(Schema.Array(Schema.String)),
2477 }),
2478 Schema.Struct({
2479 kind: Schema.Literal("project.updated"),
2480 sequence: NonNegativeInt,
2481 project: OrchestrationProjectShell,
2482 }),
2483 Schema.Struct({
2484 kind: Schema.Literal("project.removed"),
2485 sequence: NonNegativeInt,
2486 projectId: ProjectId,
2487 }),
2488 Schema.Struct({
2489 kind: Schema.Literal("thread.updated"),
2490 sequence: NonNegativeInt,
2491 location: Schema.Literals(["active", "archive"]),
2492 thread: OrchestrationV2ThreadShell,
2493 }),
2494 Schema.Struct({
2495 kind: Schema.Literal("thread.removed"),
2496 sequence: NonNegativeInt,
2497 location: Schema.Literals(["active", "archive"]),
2498 threadId: ThreadId,
2499 }),
2500 ]);
2501 export type OrchestrationV2ShellStreamItem = typeof OrchestrationV2ShellStreamItem.Type;
2502
2503 export const OrchestrationV2StoredEvent = Schema.Struct({
2504 sequence: NonNegativeInt,
2505 commandId: Schema.NullOr(CommandId),
2506 event: OrchestrationV2DomainEvent,
2507 });
2508 export type OrchestrationV2StoredEvent = typeof OrchestrationV2StoredEvent.Type;
2509
2510 export const OrchestrationV2AppThreadJson = OrchestrationV2AppThread.mapFields((fields) => ({
2511 ...fields,
2512 createdAt: Schema.DateTimeUtcFromString,
2513 updatedAt: Schema.DateTimeUtcFromString,
2514 archivedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
2515 settledAt: Schema.NullOr(Schema.DateTimeUtcFromString).pipe(
2516 Schema.withDecodingDefault(Effect.succeed(null)),
2517 ),
2518 unsettledAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)),
2519 snoozedUntil: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)),
2520 snoozedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)),
2521 lastSnoozeWakeAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)),
2522 pinnedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)),
2523 autoSettleDisabledAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)),
2524 lastVisitedAt: Schema.NullOr(Schema.DateTimeUtcFromString).pipe(
2525 Schema.withDecodingDefault(Effect.succeed(null)),
2526 ),
2527 titleRegeneration: Schema.optional(
2528 Schema.NullOr(
2529 Schema.Struct({
2530 requestId: CommandId,
2531 startedAt: Schema.DateTimeUtcFromString,
2532 }),
2533 ),
2534 ),
2535 lastTitleRegeneration: Schema.optional(
2536 Schema.NullOr(
2537 OrchestrationV2LastTitleRegeneration.mapFields((fields) => ({
2538 ...fields,
2539 completedAt: Schema.DateTimeUtcFromString,
2540 })),
2541 ),
2542 ),
2543 deletedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
2544 }));
2545 export type OrchestrationV2AppThreadJson = typeof OrchestrationV2AppThreadJson.Type;
2546
2547 export const OrchestrationV2ThreadVisitJson = Schema.Struct({
2548 lastVisitedAt: OrchestrationV2AppThreadJson.fields.lastVisitedAt,
2549 opens: OrchestrationV2AppThreadJson.fields.opens,
2550 });
2551
2552 export const OrchestrationV2RunJson = OrchestrationV2Run.mapFields((fields) => ({
2553 ...fields,
2554 requestedAt: Schema.DateTimeUtcFromString,
2555 startedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
2556 completedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
2557 workStartedAt: Schema.optional(Schema.DateTimeUtcFromString),
2558 }));
2559 export type OrchestrationV2RunJson = typeof OrchestrationV2RunJson.Type;
2560
2561 export const OrchestrationV2RunAttemptJson = OrchestrationV2RunAttempt.mapFields((fields) => ({
2562 ...fields,
2563 startedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
2564 completedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
2565 }));
2566 export type OrchestrationV2RunAttemptJson = typeof OrchestrationV2RunAttemptJson.Type;
2567
2568 export const OrchestrationV2ExecutionNodeJson = OrchestrationV2ExecutionNode.mapFields(
2569 (fields) => ({
2570 ...fields,
2571 startedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
2572 completedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
2573 }),
2574 );
2575 export type OrchestrationV2ExecutionNodeJson = typeof OrchestrationV2ExecutionNodeJson.Type;
2576
2577 export const OrchestrationV2SubagentJson = OrchestrationV2Subagent.mapFields((fields) => ({
2578 ...fields,
2579 startedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
2580 completedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
2581 updatedAt: Schema.DateTimeUtcFromString,
2582 }));
2583 export type OrchestrationV2SubagentJson = typeof OrchestrationV2SubagentJson.Type;
2584
2585 export const OrchestrationV2CheckpointScopeJson = OrchestrationV2CheckpointScope.mapFields(
2586 (fields) => ({
2587 ...fields,
2588 createdAt: Schema.DateTimeUtcFromString,
2589 }),
2590 );
2591 export type OrchestrationV2CheckpointScopeJson = typeof OrchestrationV2CheckpointScopeJson.Type;
2592
2593 export const OrchestrationV2ProviderSessionJson = OrchestrationV2ProviderSession.mapFields(
2594 (fields) => ({
2595 ...fields,
2596 createdAt: Schema.DateTimeUtcFromString,
2597 updatedAt: Schema.DateTimeUtcFromString,
2598 }),
2599 );
2600 export type OrchestrationV2ProviderSessionJson = typeof OrchestrationV2ProviderSessionJson.Type;
2601
2602 export const OrchestrationV2ProviderSessionDetachedJson =
2603 OrchestrationV2ProviderSessionDetached.mapFields((fields) => ({
2604 ...fields,
2605 detachedAt: Schema.DateTimeUtcFromString,
2606 }));
2607 export type OrchestrationV2ProviderSessionDetachedJson =
2608 typeof OrchestrationV2ProviderSessionDetachedJson.Type;
2609
2610 export const OrchestrationV2ProviderThreadJson = OrchestrationV2ProviderThread.mapFields(
2611 (fields) => ({
2612 ...fields,
2613 createdAt: Schema.DateTimeUtcFromString,
2614 updatedAt: Schema.DateTimeUtcFromString,
2615 }),
2616 );
2617 export type OrchestrationV2ProviderThreadJson = typeof OrchestrationV2ProviderThreadJson.Type;
2618
2619 export const OrchestrationV2ContextHandoffJson = OrchestrationV2ContextHandoff.mapFields(
2620 (fields) => ({
2621 ...fields,
2622 createdAt: Schema.DateTimeUtcFromString,
2623 updatedAt: Schema.DateTimeUtcFromString,
2624 }),
2625 );
2626 export type OrchestrationV2ContextHandoffJson = typeof OrchestrationV2ContextHandoffJson.Type;
2627
2628 export const OrchestrationV2ContextTransferJson = OrchestrationV2ContextTransfer.mapFields(
2629 (fields) => ({
2630 ...fields,
2631 createdAt: Schema.DateTimeUtcFromString,
2632 updatedAt: Schema.DateTimeUtcFromString,
2633 consumedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
2634 }),
2635 );
2636 export type OrchestrationV2ContextTransferJson = typeof OrchestrationV2ContextTransferJson.Type;
2637
2638 export const OrchestrationV2ProviderTurnJson = OrchestrationV2ProviderTurn.mapFields((fields) => ({
2639 ...fields,
2640 startedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
2641 completedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
2642 }));
2643 export type OrchestrationV2ProviderTurnJson = typeof OrchestrationV2ProviderTurnJson.Type;
2644
2645 export const OrchestrationV2RuntimeRequestJson = OrchestrationV2RuntimeRequest.mapFields(
2646 (fields) => ({
2647 ...fields,
2648 createdAt: Schema.DateTimeUtcFromString,
2649 resolvedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
2650 }),
2651 );
2652 export type OrchestrationV2RuntimeRequestJson = typeof OrchestrationV2RuntimeRequestJson.Type;
2653
2654 export const OrchestrationV2ConversationMessageJson = OrchestrationV2ConversationMessage.mapFields(
2655 (fields) => ({
2656 ...fields,
2657 createdAt: Schema.DateTimeUtcFromString,
2658 updatedAt: Schema.DateTimeUtcFromString,
2659 }),
2660 );
2661 export type OrchestrationV2ConversationMessageJson =
2662 typeof OrchestrationV2ConversationMessageJson.Type;
2663
2664 export const OrchestrationV2CheckpointJson = OrchestrationV2Checkpoint.mapFields((fields) => ({
2665 ...fields,
2666 capturedAt: Schema.DateTimeUtcFromString,
2667 }));
2668 export type OrchestrationV2CheckpointJson = typeof OrchestrationV2CheckpointJson.Type;
2669
2670 export const OrchestrationV2CheckpointRollbackRequestJson =
2671 OrchestrationV2CheckpointRollbackRequest.mapFields((fields) => ({
2672 ...fields,
2673 requestedAt: Schema.DateTimeUtcFromString,
2674 }));
2675
2676 const OrchestrationV2TurnItemJsonBaseFields = {
2677 ...OrchestrationV2TurnItemBaseFields,
2678 startedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
2679 completedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
2680 updatedAt: Schema.DateTimeUtcFromString,
2681 } as const;
2682
2683 export const OrchestrationV2TurnItemJson = Schema.Union([
2684 Schema.Struct({
2685 ...OrchestrationV2TurnItemJsonBaseFields,
2686 type: Schema.Literal("notification"),
2687 ...OrchestrationV2Notification.fields,
2688 }),
2689 Schema.Struct({
2690 ...OrchestrationV2TurnItemJsonBaseFields,
2691 ...OrchestrationV2CreationFields,
2692 type: Schema.Literal("user_message"),
2693 messageId: MessageId,
2694 scheduledTaskId: Schema.optional(ScheduledTaskId),
2695 senderThreadId: Schema.optional(ThreadId),
2696 linkedSender: Schema.optional(OrchestrationV2LinkedSender),
2697 idleCompaction: Schema.optional(OrchestrationV2IdleCompaction),
2698 workflowScript: OrchestrationV2ConversationMessage.fields.workflowScript,
2699 freshContext: OrchestrationV2Run.fields.freshContext,
2700 inputIntent: OrchestrationV2UserMessageInputIntent,
2701 text: Schema.String,
2702 context: Schema.optional(OrchestrationMessageContext),
2703 attachments: Schema.Array(ChatAttachment),
2704 modelSwitch: Schema.optional(OrchestrationV2ModelSwitch),
2705 }),
2706 Schema.Struct({
2707 ...OrchestrationV2TurnItemJsonBaseFields,
2708 type: Schema.Literal("assistant_message"),
2709 phase: Schema.optional(AssistantMessagePhase),
2710 messageId: MessageId,
2711 text: Schema.String,
2712 attachments: Schema.optional(Schema.Array(ChatAttachment)),
2713 streaming: Schema.Boolean,
2714 }),
2715 Schema.Struct({
2716 ...OrchestrationV2TurnItemJsonBaseFields,
2717 type: Schema.Literal("reasoning"),
2718 text: Schema.String,
2719 streaming: Schema.Boolean,
2720 }),
2721 Schema.Struct({
2722 ...OrchestrationV2TurnItemJsonBaseFields,
2723 type: Schema.Literal("proposed_plan"),
2724 planId: PlanId,
2725 markdown: Schema.String,
2726 streaming: Schema.Boolean,
2727 }),
2728 Schema.Struct({
2729 ...OrchestrationV2TurnItemJsonBaseFields,
2730 type: Schema.Literal("todo_list"),
2731 planId: PlanId,
2732 steps: Schema.Array(OrchestrationV2PlanStep),
2733 explanation: Schema.optional(Schema.String),
2734 }),
2735 Schema.Struct({
2736 ...OrchestrationV2TurnItemJsonBaseFields,
2737 type: Schema.Literal("user_input_request"),
2738 requestId: RuntimeRequestId,
2739 questions: Schema.Array(OrchestrationV2UserInputQuestion),
2740 questionAnswer: Schema.optional(UserInputAttachmentAnswerPayload),
2741 responseMode: Schema.optional(Schema.Literal("message")),
2742 }),
2743 Schema.Struct({
2744 ...OrchestrationV2TurnItemJsonBaseFields,
2745 type: Schema.Literal("file_change"),
2746 fileName: TrimmedNonEmptyString,
2747 additions: Schema.optional(NonNegativeInt),
2748 deletions: Schema.optional(NonNegativeInt),
2749 diffStr: Schema.optional(Schema.String),
2750 oldStr: Schema.optional(Schema.String),
2751 newStr: Schema.optional(Schema.String),
2752 changes: Schema.optional(Schema.Array(OrchestrationV2FileChangeDetail)),
2753 }),
2754 Schema.Struct({
2755 ...OrchestrationV2TurnItemJsonBaseFields,
2756 type: Schema.Literal("command_execution"),
2757 input: Schema.String,
2758 output: Schema.optional(Schema.String),
2759 /** Set on the wire when output was withheld; fetch it with getTurnItem. */
2760 outputOmitted: Schema.optional(Schema.Boolean),
2761 outputIndicatesFailure: Schema.optional(Schema.Boolean),
2762 exitCode: Schema.optional(Schema.Int),
2763 /** Set when the command is a monitor, so background work lists it as a monitor. */
2764 monitor: Schema.optional(Schema.Boolean),
2765 /** The provider wakes the agent when this command finishes after its turn. */
2766 completionWake: Schema.optional(Schema.Literal("always")),
2767 }),
2768 Schema.Struct({
2769 ...OrchestrationV2TurnItemJsonBaseFields,
2770 type: Schema.Literal("file_search"),
2771 pattern: Schema.optional(Schema.String),
2772 results: Schema.optional(Schema.Array(OrchestrationV2FileSearchResult)),
2773 }),
2774 Schema.Struct({
2775 ...OrchestrationV2TurnItemJsonBaseFields,
2776 type: Schema.Literal("web_search"),
2777 patterns: Schema.optional(Schema.Array(Schema.String)),
2778 results: Schema.optional(Schema.Array(OrchestrationV2WebSearchResult)),
2779 }),
2780 Schema.Struct({
2781 ...OrchestrationV2TurnItemJsonBaseFields,
2782 type: Schema.Literal("approval_request"),
2783 requestId: RuntimeRequestId,
2784 requestKind: ProviderRequestKind,
2785 prompt: Schema.optional(Schema.String),
2786 reason: Schema.optional(Schema.String),
2787 fullAccessOverride: Schema.optional(ProviderApprovalFullAccessOverride),
2788 appName: Schema.optional(Schema.String),
2789 options: Schema.optional(Schema.Array(ProviderApprovalOption)),
2790 }),
2791 Schema.Struct({
2792 ...OrchestrationV2TurnItemJsonBaseFields,
2793 type: Schema.Literal("checkpoint"),
2794 checkpointId: CheckpointId,
2795 scopeId: CheckpointScopeId,
2796 files: Schema.Array(OrchestrationV2CheckpointFileSummary),
2797 }),
2798 Schema.Struct({
2799 ...OrchestrationV2TurnItemJsonBaseFields,
2800 type: Schema.Literal("run_interrupt_request"),
2801 message: Schema.String,
2802 unresponsiveAt: Schema.optionalKey(Schema.DateTimeUtcFromString),
2803 }),
2804 Schema.Struct({
2805 ...OrchestrationV2TurnItemJsonBaseFields,
2806 type: Schema.Literal("run_interrupt_result"),
2807 message: Schema.String,
2808 }),
2809 Schema.Struct({
2810 ...OrchestrationV2TurnItemJsonBaseFields,
2811 type: Schema.Literal("system_notice"),
2812 message: Schema.String,
2813 level: Schema.optional(OrchestrationV2SystemNoticeLevel),
2814 mcpSignIn: Schema.optional(OrchestrationV2McpSignIn),
2815 }),
2816 Schema.Struct({
2817 ...OrchestrationV2TurnItemJsonBaseFields,
2818 type: Schema.Literal("error"),
2819 failure: OrchestrationV2ProviderFailure,
2820 retry: Schema.optional(OrchestrationV2ProviderRetry),
2821 }),
2822 Schema.Struct({
2823 ...OrchestrationV2TurnItemJsonBaseFields,
2824 type: Schema.Literal("compaction"),
2825 driver: Schema.NullOr(ProviderDriverKind),
2826 summary: Schema.optional(Schema.String),
2827 beforeTokenCount: Schema.optional(NonNegativeInt),
2828 afterTokenCount: Schema.optional(NonNegativeInt),
2829 }),
2830 Schema.Struct({
2831 ...OrchestrationV2TurnItemJsonBaseFields,
2832 type: Schema.Literal("handoff"),
2833 contextHandoffId: ContextHandoffId,
2834 fromProviderThreadIds: Schema.Array(ProviderThreadId),
2835 toProviderThreadId: ProviderThreadId,
2836 fromProviderInstanceIds: Schema.Array(ProviderInstanceId),
2837 toProviderInstanceId: ProviderInstanceId,
2838 fromModelSelections: Schema.optional(Schema.Array(ModelSelection)),
2839 toModel: Schema.optional(Schema.String),
2840 strategy: Schema.Literals([
2841 "delta_since_target_last_seen",
2842 "fork_delta_summary",
2843 "full_thread_summary",
2844 "checkpoint_summary",
2845 "manual_context",
2846 ]),
2847 summary: Schema.optional(Schema.String),
2848 }),
2849 Schema.Struct({
2850 ...OrchestrationV2TurnItemJsonBaseFields,
2851 type: Schema.Literal("fork"),
2852 source: Schema.Union([
2853 Schema.Struct({ type: Schema.Literal("run"), threadId: ThreadId, runId: RunId }),
2854 Schema.Struct({ type: Schema.Literal("node"), nodeId: NodeId }),
2855 Schema.Struct({
2856 type: Schema.Literal("provider_thread"),
2857 providerThreadId: ProviderThreadId,
2858 providerTurnId: Schema.optional(ProviderTurnId),
2859 }),
2860 ]),
2861 targetThreadId: ThreadId,
2862 providerThreadId: Schema.optional(ProviderThreadId),
2863 }),
2864 Schema.Struct({
2865 ...OrchestrationV2TurnItemJsonBaseFields,
2866 type: Schema.Literal("thread_created"),
2867 targetThreadId: ThreadId,
2868 targetRunId: Schema.NullOr(RunId),
2869 targetProviderInstanceId: ProviderInstanceId,
2870 targetModel: TrimmedNonEmptyString,
2871 }),
2872 Schema.Struct({
2873 ...OrchestrationV2TurnItemJsonBaseFields,
2874 ...OrchestrationV2SecretRequestFields,
2875 }),
2876 Schema.Struct({
2877 ...OrchestrationV2TurnItemJsonBaseFields,
2878 ...OrchestrationV2LinkRequestFields,
2879 }),
2880 Schema.Struct({
2881 ...OrchestrationV2TurnItemJsonBaseFields,
2882 type: Schema.Literal("subagent"),
2883 subagentId: NodeId,
2884 origin: Schema.Literals(["provider_native", "app_owned"]),
2885 driver: ProviderDriverKind,
2886 providerInstanceId: ProviderInstanceId,
2887 childThreadId: Schema.NullOr(ThreadId),
2888 remoteChild: Schema.optional(OrchestrationV2RemoteTaskChild),
2889 prompt: Schema.String,
2890 progress: Schema.optional(Schema.String),
2891 result: Schema.NullOr(Schema.String),
2892 }),
2893 Schema.Struct({
2894 ...OrchestrationV2TurnItemJsonBaseFields,
2895 type: Schema.Literal("dynamic_tool"),
2896 toolName: Schema.NullOr(TrimmedNonEmptyString),
2897 viewedImagePath: Schema.optional(TrimmedNonEmptyString),
2898 input: Schema.Unknown,
2899 output: Schema.optional(Schema.Unknown),
2900 /** Set on the wire when output was withheld; fetch it with getTurnItem. */
2901 outputOmitted: Schema.optional(Schema.Boolean),
2902 }),
2903 ]);
2904 export type OrchestrationV2TurnItemJson = typeof OrchestrationV2TurnItemJson.Type;
2905
2906 export const OrchestrationV2ProjectedTurnItemJson = OrchestrationV2ProjectedTurnItem.mapFields(
2907 (fields) => ({
2908 ...fields,
2909 item: OrchestrationV2TurnItemJson,
2910 }),
2911 );
2912 export type OrchestrationV2ProjectedTurnItemJson = typeof OrchestrationV2ProjectedTurnItemJson.Type;
2913
2914 export const OrchestrationV2ThreadProjectionJson = OrchestrationV2ThreadProjection.mapFields(
2915 (fields) => ({
2916 ...fields,
2917 thread: OrchestrationV2AppThreadJson,
2918 runs: Schema.Array(OrchestrationV2RunJson),
2919 attempts: Schema.Array(OrchestrationV2RunAttemptJson),
2920 nodes: Schema.Array(OrchestrationV2ExecutionNodeJson),
2921 subagents: Schema.Array(OrchestrationV2SubagentJson),
2922 providerSessions: Schema.Array(OrchestrationV2ProviderSessionJson),
2923 providerThreads: Schema.Array(OrchestrationV2ProviderThreadJson),
2924 providerTurns: Schema.Array(OrchestrationV2ProviderTurnJson),
2925 runtimeRequests: Schema.Array(OrchestrationV2RuntimeRequestJson),
2926 messages: Schema.Array(OrchestrationV2ConversationMessageJson),
2927 plans: Schema.Array(OrchestrationV2PlanArtifact),
2928 turnItems: turnItemArray(OrchestrationV2TurnItemJson),
2929 checkpointScopes: Schema.Array(OrchestrationV2CheckpointScopeJson),
2930 checkpoints: Schema.Array(OrchestrationV2CheckpointJson),
2931 contextHandoffs: Schema.Array(OrchestrationV2ContextHandoffJson),
2932 contextTransfers: Schema.Array(OrchestrationV2ContextTransferJson),
2933 visibleTurnItems: projectedTurnItemArray(
2934 OrchestrationV2ProjectedTurnItemJson,
2935 OrchestrationV2ProjectedTurnItemJson.mapFields((fields) => ({
2936 ...fields,
2937 item: ForwardCompatibleUnion(OrchestrationV2TurnItemJson.members, "type"),
2938 })),
2939 ),
2940 updatedAt: Schema.DateTimeUtcFromString,
2941 }),
2942 );
2943 export type OrchestrationV2ThreadProjectionJson = typeof OrchestrationV2ThreadProjectionJson.Type;
2944
2945 export const OrchestrationV2PendingRuntimeRequestSummaryJson =
2946 OrchestrationV2PendingRuntimeRequestSummary.mapFields((fields) => ({
2947 ...fields,
2948 createdAt: Schema.DateTimeUtcFromString,
2949 }));
2950 export type OrchestrationV2PendingRuntimeRequestSummaryJson =
2951 typeof OrchestrationV2PendingRuntimeRequestSummaryJson.Type;
2952
2953 export const OrchestrationV2LatestVisibleMessageSummaryJson =
2954 OrchestrationV2LatestVisibleMessageSummary.mapFields((fields) => ({
2955 ...fields,
2956 updatedAt: Schema.DateTimeUtcFromString,
2957 }));
2958 export type OrchestrationV2LatestVisibleMessageSummaryJson =
2959 typeof OrchestrationV2LatestVisibleMessageSummaryJson.Type;
2960
2961 export const OrchestrationV2ThreadShellJson = OrchestrationV2ThreadShell.mapFields((fields) => ({
2962 ...fields,
2963 latestRunRequestedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)),
2964 latestRunStartedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)),
2965 latestRunCompletedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)),
2966 activityRunStartedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)),
2967 pendingRuntimeRequest: Schema.NullOr(OrchestrationV2PendingRuntimeRequestSummaryJson),
2968 latestVisibleMessage: Schema.NullOr(OrchestrationV2LatestVisibleMessageSummaryJson),
2969 latestUserMessageAt: Schema.NullOr(Schema.DateTimeUtcFromString),
2970 latestUserAuthoredMessageAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)),
2971 createdAt: Schema.DateTimeUtcFromString,
2972 updatedAt: Schema.DateTimeUtcFromString,
2973 archivedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
2974 settledAt: Schema.NullOr(Schema.DateTimeUtcFromString),
2975 unsettledAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)),
2976 snoozedUntil: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)),
2977 snoozedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)),
2978 pinnedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)),
2979 autoSettleDisabledAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)),
2980 lastVisitedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)),
2981 titleRegeneration: Schema.optional(
2982 Schema.NullOr(
2983 Schema.Struct({
2984 requestId: CommandId,
2985 startedAt: Schema.DateTimeUtcFromString,
2986 }),
2987 ),
2988 ),
2989 lastTitleRegeneration: Schema.optional(
2990 Schema.NullOr(
2991 OrchestrationV2LastTitleRegeneration.mapFields((fields) => ({
2992 ...fields,
2993 completedAt: Schema.DateTimeUtcFromString,
2994 })),
2995 ),
2996 ),
2997 deletedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
2998 }));
2999 export type OrchestrationV2ThreadShellJson = typeof OrchestrationV2ThreadShellJson.Type;
3000
3001 export const OrchestrationV2ShellSnapshotJson = OrchestrationV2ShellSnapshot.mapFields(
3002 (fields) => ({
3003 ...fields,
3004 threads: Schema.Array(OrchestrationV2ThreadShellJson),
3005 archivedThreads: Schema.Array(OrchestrationV2ThreadShellJson),
3006 }),
3007 );
3008 export type OrchestrationV2ShellSnapshotJson = typeof OrchestrationV2ShellSnapshotJson.Type;
3009
3010 const OrchestrationV2JsonEventBaseFields = {
3011 ...OrchestrationV2EventBase.fields,
3012 occurredAt: Schema.DateTimeUtcFromString,
3013 } as const;
3014
3015 export const OrchestrationV2DomainEventJson = Schema.Union([
3016 Schema.Struct({
3017 ...OrchestrationV2JsonEventBaseFields,
3018 type: Schema.Literal("thread.created"),
3019 payload: OrchestrationV2AppThreadJson,
3020 }),
3021 Schema.Struct({
3022 ...OrchestrationV2JsonEventBaseFields,
3023 type: Schema.Literals([
3024 "thread.archived",
3025 "thread.unarchived",
3026 "thread.deleted",
3027 "thread.settled",
3028 "thread.unsettled",
3029 "thread.snoozed",
3030 "thread.unsnoozed",
3031 "thread.pinned",
3032 "thread.auto-settle-set",
3033 "thread.unpinned",
3034 "thread.pin-reordered",
3035 "thread.active-reordered",
3036 "thread.tags-updated",
3037 "thread.visited",
3038 "thread.marked-unread",
3039 "thread.pull-request-synced",
3040 "thread.issue-synced",
3041 "thread.metadata-updated",
3042 "thread.runtime-mode-updated",
3043 "thread.interaction-mode-updated",
3044 "thread.model-selection-updated",
3045 "thread.provider-switched",
3046 "thread.guest-share-updated",
3047 ]),
3048 payload: OrchestrationV2AppThreadJson,
3049 }),
3050 Schema.Struct({
3051 ...OrchestrationV2JsonEventBaseFields,
3052 type: Schema.Literal("thread.pull-request-link-updated"),
3053 payload: ThreadPullRequestLink,
3054 }),
3055 Schema.Struct({
3056 ...OrchestrationV2JsonEventBaseFields,
3057 type: Schema.Literal("thread.visit-recorded"),
3058 payload: OrchestrationV2ThreadVisitJson,
3059 }),
3060 Schema.Struct({
3061 ...OrchestrationV2JsonEventBaseFields,
3062 type: Schema.Literal("run.created"),
3063 payload: OrchestrationV2RunJson,
3064 }),
3065 Schema.Struct({
3066 ...OrchestrationV2JsonEventBaseFields,
3067 type: Schema.Literal("run.updated"),
3068 payload: OrchestrationV2RunJson,
3069 }),
3070 Schema.Struct({
3071 ...OrchestrationV2JsonEventBaseFields,
3072 type: Schema.Literal("run.background-work-cancelled"),
3073 payload: OrchestrationV2RunBackgroundWorkCancelled,
3074 }),
3075 Schema.Struct({
3076 ...OrchestrationV2JsonEventBaseFields,
3077 type: Schema.Literal("run.output-submitted"),
3078 payload: OrchestrationV2RunOutputSubmitted,
3079 }),
3080 Schema.Struct({
3081 ...OrchestrationV2JsonEventBaseFields,
3082 type: Schema.Literal("run-attempt.created"),
3083 payload: OrchestrationV2RunAttemptJson,
3084 }),
3085 Schema.Struct({
3086 ...OrchestrationV2JsonEventBaseFields,
3087 type: Schema.Literal("run-attempt.updated"),
3088 payload: OrchestrationV2RunAttemptJson,
3089 }),
3090 Schema.Struct({
3091 ...OrchestrationV2JsonEventBaseFields,
3092 type: Schema.Literal("node.updated"),
3093 payload: OrchestrationV2ExecutionNodeJson,
3094 }),
3095 Schema.Struct({
3096 ...OrchestrationV2JsonEventBaseFields,
3097 type: Schema.Literal("subagent.updated"),
3098 payload: OrchestrationV2SubagentJson,
3099 }),
3100 Schema.Struct({
3101 ...OrchestrationV2JsonEventBaseFields,
3102 type: Schema.Literals(["provider-session.attached", "provider-session.updated"]),
3103 payload: OrchestrationV2ProviderSessionJson,
3104 }),
3105 Schema.Struct({
3106 ...OrchestrationV2JsonEventBaseFields,
3107 type: Schema.Literal("provider-session.detached"),
3108 payload: OrchestrationV2ProviderSessionDetachedJson,
3109 }),
3110 Schema.Struct({
3111 ...OrchestrationV2JsonEventBaseFields,
3112 type: Schema.Literal("provider-thread.updated"),
3113 payload: OrchestrationV2ProviderThreadJson,
3114 }),
3115 Schema.Struct({
3116 ...OrchestrationV2JsonEventBaseFields,
3117 type: Schema.Literal("provider-turn.updated"),
3118 payload: OrchestrationV2ProviderTurnJson,
3119 }),
3120 Schema.Struct({
3121 ...OrchestrationV2JsonEventBaseFields,
3122 type: Schema.Literal("runtime-request.updated"),
3123 payload: OrchestrationV2RuntimeRequestJson,
3124 }),
3125 Schema.Struct({
3126 ...OrchestrationV2JsonEventBaseFields,
3127 type: Schema.Literal("message.updated"),
3128 payload: OrchestrationV2ConversationMessageJson,
3129 }),
3130 Schema.Struct({
3131 ...OrchestrationV2JsonEventBaseFields,
3132 type: Schema.Literal("turn-item.updated"),
3133 payload: OrchestrationV2TurnItemJson,
3134 }),
3135 Schema.Struct({
3136 ...OrchestrationV2JsonEventBaseFields,
3137 type: Schema.Literal("plan.updated"),
3138 payload: OrchestrationV2PlanArtifact,
3139 }),
3140 Schema.Struct({
3141 ...OrchestrationV2JsonEventBaseFields,
3142 type: Schema.Literal("checkpoint-scope.created"),
3143 payload: OrchestrationV2CheckpointScopeJson,
3144 }),
3145 Schema.Struct({
3146 ...OrchestrationV2JsonEventBaseFields,
3147 type: Schema.Literal("checkpoint.captured"),
3148 payload: OrchestrationV2CheckpointJson,
3149 }),
3150 Schema.Struct({
3151 ...OrchestrationV2JsonEventBaseFields,
3152 type: Schema.Literal("checkpoint.rollback-requested"),
3153 payload: OrchestrationV2CheckpointRollbackRequestJson,
3154 }),
3155 Schema.Struct({
3156 ...OrchestrationV2JsonEventBaseFields,
3157 type: Schema.Literal("context-handoff.updated"),
3158 payload: OrchestrationV2ContextHandoffJson,
3159 }),
3160 Schema.Struct({
3161 ...OrchestrationV2JsonEventBaseFields,
3162 type: Schema.Literal("context-transfer.created"),
3163 payload: OrchestrationV2ContextTransferJson,
3164 }),
3165 Schema.Struct({
3166 ...OrchestrationV2JsonEventBaseFields,
3167 type: Schema.Literal("context-transfer.updated"),
3168 payload: OrchestrationV2ContextTransferJson,
3169 }),
3170 ]);
3171 export type OrchestrationV2DomainEventJson = typeof OrchestrationV2DomainEventJson.Type;
3172
3173 export const OrchestrationV2Command = Schema.Union([
3174 Schema.Struct({
3175 type: Schema.Literal("thread.stop"),
3176 commandId: CommandId,
3177 threadId: ThreadId,
3178 reason: Schema.optional(Schema.String),
3179 /**
3180 * False when the caller stops the thread's delegated tasks itself, as the server's tree walks
3181 * do under their caller's dispatch limit. Otherwise Stop also stops every task under the thread.
3182 */
3183 stopDelegatedTasks: Schema.optional(Schema.Boolean),
3184 }),
3185 Schema.Struct({
3186 type: Schema.Literal("thread.create"),
3187 ...OrchestrationV2CreationFields,
3188 commandId: CommandId,
3189 threadId: ThreadId,
3190 projectId: ProjectId,
3191 title: TrimmedNonEmptyString,
3192 modelSelection: ModelSelection,
3193 runtimeMode: RuntimeMode,
3194 interactionMode: ProviderInteractionMode,
3195 branch: Schema.NullOr(TrimmedNonEmptyString),
3196 worktreePath: Schema.NullOr(TrimmedNonEmptyString),
3197 /** Only the server sets this; a client's thread.create never carries one. */
3198 linkOrigin: Schema.optional(OrchestrationV2LinkOrigin),
3199 /** Only the server sets this, with `linkOrigin`, for a linked environment's delegated task. */
3200 delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom),
3201 importedNativeThread: Schema.optional(
3202 Schema.Struct({
3203 ref: Schema.Struct({
3204 driver: ProviderDriverKind,
3205 nativeId: TrimmedNonEmptyString,
3206 strength: Schema.Literal("strong"),
3207 }),
3208 metadata: Schema.optional(OrchestrationV2ProviderThreadNativeMetadata),
3209 }),
3210 ),
3211 /**
3212 * Only the server sets this. The thread and its first run commit together, so no client sees
3213 * the thread idle before its run exists. The run waits for `workspaceStrategy` when given one.
3214 */
3215 initialMessage: Schema.optional(
3216 Schema.Struct({
3217 messageId: MessageId,
3218 text: Schema.String,
3219 attachments: Schema.Array(ChatAttachment),
3220 context: Schema.optional(OrchestrationMessageContext),
3221 titleSeed: Schema.optional(TrimmedNonEmptyString),
3222 scheduledTaskId: Schema.optional(ScheduledTaskId),
3223 senderThreadId: Schema.optional(ThreadId),
3224 outputSchema: Schema.optional(Schema.Record(Schema.String, Schema.Json)),
3225 workspaceStrategy: Schema.optional(OrchestrationV2ThreadLaunchWorkspaceStrategy),
3226 }),
3227 ),
3228 }),
3229 Schema.Struct({
3230 type: Schema.Literal("thread.archive"),
3231 commandId: CommandId,
3232 threadId: ThreadId,
3233 }),
3234 Schema.Struct({
3235 type: Schema.Literal("thread.guest-share.close"),
3236 commandId: CommandId,
3237 threadId: ThreadId,
3238 }),
3239 Schema.Struct({
3240 type: Schema.Literal("thread.guest-message.dismiss"),
3241 commandId: CommandId,
3242 threadId: ThreadId,
3243 guestMessageId: GuestMessageId,
3244 }),
3245 Schema.Struct({
3246 type: Schema.Literal("thread.unarchive"),
3247 commandId: CommandId,
3248 threadId: ThreadId,
3249 }),
3250 Schema.Struct({
3251 type: Schema.Literal("thread.delete"),
3252 commandId: CommandId,
3253 threadId: ThreadId,
3254 /** Delete only a thread with no runs and no messages; otherwise succeed without a change. */
3255 onlyIfUnused: Schema.optional(Schema.Boolean),
3256 }),
3257 Schema.Struct({
3258 type: Schema.Literal("thread.settle"),
3259 commandId: CommandId,
3260 threadId: ThreadId,
3261 expectedLatestRunId: Schema.optional(RunId),
3262 settledAt: Schema.optional(Schema.DateTimeUtc),
3263 }),
3264 /** Rejects changes since snapshotAt or any explicit settled override to preserve user actions. */
3265 Schema.Struct({
3266 type: Schema.Literal("thread.auto-settle"),
3267 commandId: CommandId,
3268 threadId: ThreadId,
3269 snapshotAt: Schema.DateTimeUtc,
3270 settledAt: Schema.optional(Schema.DateTimeUtc),
3271 }),
3272 Schema.Struct({
3273 type: Schema.Literal("thread.unsettle"),
3274 commandId: CommandId,
3275 threadId: ThreadId,
3276 reason: Schema.Literal("user"),
3277 // Undo of a settle restores the Active anchor it cleared instead of moving the thread to the top.
3278 restoreUnsettledAt: Schema.optional(Schema.NullOr(IsoDateTime)),
3279 }),
3280 Schema.Struct({
3281 type: Schema.Literal("thread.snooze"),
3282 commandId: CommandId,
3283 threadId: ThreadId,
3284 snoozedUntil: IsoDateTime,
3285 }),
3286 Schema.Struct({
3287 type: Schema.Literal("thread.unsnooze"),
3288 commandId: CommandId,
3289 threadId: ThreadId,
3290 reason: Schema.Literal("user"),
3291 }),
3292 Schema.Struct({
3293 type: Schema.Literal("thread.auto-settle.set"),
3294 commandId: CommandId,
3295 threadId: ThreadId,
3296 enabled: Schema.Boolean,
3297 }),
3298 Schema.Struct({
3299 type: Schema.Literal("thread.pin"),
3300 commandId: CommandId,
3301 threadId: ThreadId,
3302 orderKey: Schema.optional(TrimmedNonEmptyString),
3303 }),
3304 Schema.Struct({
3305 type: Schema.Literal("thread.unpin"),
3306 commandId: CommandId,
3307 threadId: ThreadId,
3308 }),
3309 Schema.Struct({
3310 type: Schema.Literal("thread.tag.set"),
3311 commandId: CommandId,
3312 threadId: ThreadId,
3313 tag: ThreadTag,
3314 tagged: Schema.Boolean,
3315 }),
3316 Schema.Struct({
3317 type: Schema.Literal("thread.pin.reorder"),
3318 commandId: CommandId,
3319 threadId: ThreadId,
3320 orderKey: TrimmedNonEmptyString,
3321 }),
3322 Schema.Struct({
3323 type: Schema.Literal("thread.active.reorder"),
3324 commandId: CommandId,
3325 threadId: ThreadId,
3326 orderKey: TrimmedNonEmptyString,
3327 }),
3328 Schema.Struct({
3329 type: Schema.Literal("thread.visit"),
3330 commandId: CommandId,
3331 threadId: ThreadId,
3332 visitedAt: IsoDateTime,
3333 // The user opened the thread, as opposed to new activity on an open one.
3334 // Older servers ignore both fields and only move the read watermark.
3335 opened: Schema.optional(Schema.Boolean),
3336 searchQuery: Schema.optional(Schema.String.check(Schema.isMaxLength(200))),
3337 }),
3338 Schema.Struct({
3339 type: Schema.Literal("thread.mark-unread"),
3340 commandId: CommandId,
3341 threadId: ThreadId,
3342 }),
3343 Schema.Struct({
3344 type: Schema.Literal("thread.metadata.update"),
3345 commandId: CommandId,
3346 threadId: ThreadId,
3347 title: Schema.optional(TrimmedNonEmptyString),
3348 regenerateTitle: Schema.optional(Schema.Boolean),
3349 branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
3350 worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
3351 expectedWorktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
3352 expectedBranch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
3353 /** A message queued in the same commit, so a workspace change cannot settle the thread first. */
3354 continuation: Schema.optional(Schema.Struct({ messageId: MessageId, text: Schema.String })),
3355 /** Reject unless no message or run has landed on this thread. */
3356 expectedEmpty: Schema.optional(Schema.Boolean),
3357 limitRecovery: Schema.optional(Schema.NullOr(OrchestrationV2LimitRecoveryUpdate)),
3358 /** Link (object) or unlink (null) a pull request; absent leaves it unchanged. */
3359 linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),
3360 }),
3361 Schema.Struct({
3362 type: Schema.Literal("thread.pull-request.link"),
3363 commandId: CommandId,
3364 threadId: ThreadId,
3365 ...ThreadPullRequestKey.fields,
3366 url: TrimmedNonEmptyString,
3367 source: ThreadPullRequestLinkSource,
3368 repositoryWebUrl: Schema.optional(TrimmedNonEmptyString),
3369 }),
3370 Schema.Struct({
3371 type: Schema.Literal("thread.pull-request.unlink"),
3372 commandId: CommandId,
3373 threadId: ThreadId,
3374 ...ThreadPullRequestKey.fields,
3375 }),
3376 Schema.Struct({
3377 type: Schema.Literal("thread.pull-request-link.sync"),
3378 commandId: CommandId,
3379 threadId: ThreadId,
3380 ...ThreadPullRequestKey.fields,
3381 snapshot: ThreadPullRequestSnapshot,
3382 stack: Schema.NullOr(ThreadPullRequestStack),
3383 }),
3384 Schema.Struct({
3385 type: Schema.Literal("thread.issue.link"),
3386 commandId: CommandId,
3387 threadId: ThreadId,
3388 ...ThreadIssueKey.fields,
3389 projectId: ProjectId,
3390 url: TrimmedNonEmptyString,
3391 displayKey: TrimmedNonEmptyString,
3392 title: TrimmedNonEmptyString,
3393 source: ThreadIssueLinkSource,
3394 }),
3395 Schema.Struct({
3396 type: Schema.Literal("thread.issue.unlink"),
3397 commandId: CommandId,
3398 threadId: ThreadId,
3399 ...ThreadIssueKey.fields,
3400 }),
3401 Schema.Struct({
3402 type: Schema.Literal("thread.pull-request.watch"),
3403 commandId: CommandId,
3404 threadId: ThreadId,
3405 ...ThreadPullRequestKey.fields,
3406 watching: Schema.Boolean,
3407 /** With `watching`, sets how long the watch holds its thread; absent keeps the current one. */
3408 until: Schema.optional(PullRequestWatchUntil),
3409 /** Whether CI was pending with no failure yet when the watch started, so any failure is news. */
3410 checksPending: Schema.optional(Schema.Boolean),
3411 link: Schema.optional(
3412 Schema.Struct({
3413 url: TrimmedNonEmptyString,
3414 source: ThreadPullRequestLinkSource,
3415 repositoryWebUrl: Schema.optional(TrimmedNonEmptyString),
3416 }),
3417 ),
3418 }),
3419 Schema.Struct({
3420 type: Schema.Literal("thread.pull-request.sync"),
3421 commandId: CommandId,
3422 threadId: ThreadId,
3423 projectId: ProjectId,
3424 snapshotSequence: NonNegativeInt,
3425 expected: Schema.Struct({
3426 workspaceRoot: TrimmedNonEmptyString,
3427 branch: Schema.NullOr(TrimmedNonEmptyString),
3428 worktreePath: Schema.NullOr(TrimmedNonEmptyString),
3429 linkedPullRequest: Schema.NullOr(ThreadLinkedPullRequest),
3430 branchPullRequest: Schema.NullOr(ThreadLinkedPullRequest),
3431 }),
3432 branchPullRequest: Schema.NullOr(ThreadLinkedPullRequest),
3433 linkedPullRequest: Schema.optional(ThreadLinkedPullRequest),
3434 }),
3435 Schema.Struct({
3436 type: Schema.Literal("thread.title.regeneration.complete"),
3437 commandId: CommandId,
3438 threadId: ThreadId,
3439 requestId: CommandId,
3440 title: Schema.optional(TrimmedNonEmptyString),
3441 outcome: Schema.optional(ThreadTitleRegenerationOutcome),
3442 }),
3443 Schema.Struct({
3444 type: Schema.Literal("thread.runtime-mode.set"),
3445 commandId: CommandId,
3446 threadId: ThreadId,
3447 runtimeMode: RuntimeMode,
3448 }),
3449 Schema.Struct({
3450 type: Schema.Literal("thread.interaction-mode.set"),
3451 commandId: CommandId,
3452 threadId: ThreadId,
3453 interactionMode: ProviderInteractionMode,
3454 }),
3455 Schema.Struct({
3456 type: Schema.Literal("thread.model-selection.set"),
3457 commandId: CommandId,
3458 threadId: ThreadId,
3459 modelSelection: ModelSelection,
3460 }),
3461 Schema.Struct({
3462 type: Schema.Literal("provider-session.detach"),
3463 commandId: CommandId,
3464 threadId: ThreadId,
3465 providerSessionId: ProviderSessionId,
3466 reason: Schema.optional(Schema.String),
3467 }),
3468 Schema.Struct({
3469 type: Schema.Literal("message.dispatch"),
3470 notification: Schema.optional(OrchestrationV2Notification),
3471 /** Sends this pending guest message; the server uses the guest's text, not `text`. */
3472 guestMessageId: Schema.optional(GuestMessageId),
3473 ...OrchestrationV2CreationFields,
3474 scheduledTaskId: Schema.optional(ScheduledTaskId),
3475 senderThreadId: Schema.optional(ThreadId),
3476 linkedSender: Schema.optional(OrchestrationV2LinkedSender),
3477 idleCompaction: Schema.optional(OrchestrationV2IdleCompaction),
3478 /** Start a new provider session without the thread's earlier context. Never steers. */
3479 freshContext: Schema.optional(Schema.Boolean),
3480 /** Asks the run for a result as data matching this JSON Schema. Never steers. */
3481 outputSchema: Schema.optional(Schema.Record(Schema.String, Schema.Json)),
3482 commandId: CommandId,
3483 threadId: ThreadId,
3484 messageId: MessageId,
3485 text: Schema.String,
3486 context: Schema.optional(OrchestrationMessageContext),
3487 attachments: Schema.Array(ChatAttachment),
3488 titleSeed: Schema.optional(TrimmedNonEmptyString),
3489 modelSelection: Schema.optional(ModelSelection),
3490 sourcePlanRef: Schema.optional(Schema.Struct({ threadId: ThreadId, planId: PlanId })),
3491 restartContinuationOfRunId: Schema.optional(RunId),
3492 usageLimitContinuationOfRunId: Schema.optional(RunId),
3493 manualContinuationOfRunId: Schema.optional(RunId),
3494 steerFollowUpOfRunId: Schema.optional(RunId),
3495 steerFollowUpAfterRunOrdinal: Schema.optional(NonNegativeInt),
3496 usageLimitRecoveryRequestId: Schema.optional(CommandId),
3497 deliveryIntent: Schema.optional(Schema.Literals(["auto", "steer", "restart"])),
3498 delegatedCompletion: Schema.optional(
3499 Schema.Struct({
3500 parentRunId: RunId,
3501 generation: PositiveInt,
3502 taskIds: Schema.Array(NodeId),
3503 }),
3504 ),
3505 dispatchMode: Schema.Union([
3506 Schema.Struct({
3507 type: Schema.Literal("defer_start"),
3508 workspaceStrategy: Schema.optional(OrchestrationV2ThreadLaunchWorkspaceStrategy),
3509 }),
3510 Schema.Struct({ type: Schema.Literal("steer_active"), targetRunId: RunId }),
3511 Schema.Struct({ type: Schema.Literal("restart_active"), targetRunId: RunId }),
3512 Schema.Struct({ type: Schema.Literal("queue_after_active") }),
3513 Schema.Struct({ type: Schema.Literal("start_immediately") }),
3514 ]),
3515 }),
3516 Schema.Struct({
3517 type: Schema.Literal("prepared-run.release"),
3518 commandId: CommandId,
3519 threadId: ThreadId,
3520 runId: RunId,
3521 }),
3522 Schema.Struct({
3523 type: Schema.Literal("notification.delivery.accept"),
3524 commandId: CommandId,
3525 threadId: ThreadId,
3526 messageId: MessageId,
3527 }),
3528 Schema.Struct({
3529 type: Schema.Literal("prepared-run.progress"),
3530 commandId: CommandId,
3531 threadId: ThreadId,
3532 runId: RunId,
3533 phase: Schema.Literals(["worktree", "setup"]),
3534 }),
3535 Schema.Struct({
3536 type: Schema.Literal("prepared-run.fail"),
3537 commandId: CommandId,
3538 threadId: ThreadId,
3539 runId: RunId,
3540 failure: OrchestrationV2ProviderFailure,
3541 }),
3542 Schema.Struct({
3543 type: Schema.Literal("prepared-run.retry"),
3544 commandId: CommandId,
3545 threadId: ThreadId,
3546 runId: RunId,
3547 }),
3548 Schema.Struct({
3549 type: Schema.Literal("subagent.stop"),
3550 commandId: CommandId,
3551 threadId: ThreadId,
3552 runId: RunId,
3553 subagentId: NodeId,
3554 }),
3555 Schema.Struct({
3556 type: Schema.Literal("run.interrupt"),
3557 commandId: CommandId,
3558 threadId: ThreadId,
3559 runId: RunId,
3560 reason: Schema.optional(Schema.String),
3561 holdQueue: Schema.optional(Schema.Boolean),
3562 }),
3563 Schema.Struct({
3564 type: Schema.Literal("queued-message.promote-to-steer"),
3565 commandId: CommandId,
3566 threadId: ThreadId,
3567 queuedRunId: RunId,
3568 targetRunId: RunId,
3569 }),
3570 Schema.Struct({
3571 type: Schema.Literal("queue.resume"),
3572 commandId: CommandId,
3573 threadId: ThreadId,
3574 }),
3575 Schema.Struct({
3576 type: Schema.Literal("queued-run.start"),
3577 commandId: CommandId,
3578 threadId: ThreadId,
3579 runId: RunId,
3580 }),
3581 Schema.Struct({
3582 type: Schema.Literal("queued-run.reorder"),
3583 commandId: CommandId,
3584 threadId: ThreadId,
3585 runId: RunId,
3586 beforeRunId: Schema.NullOr(RunId),
3587 }),
3588 Schema.Struct({
3589 type: Schema.Literal("queued-run.cancel"),
3590 commandId: CommandId,
3591 threadId: ThreadId,
3592 runId: RunId,
3593 }),
3594 Schema.Struct({
3595 type: Schema.Literal("queued-run.edit"),
3596 context: Schema.optional(OrchestrationMessageContext),
3597 commandId: CommandId,
3598 threadId: ThreadId,
3599 runId: RunId,
3600 text: Schema.String,
3601 // Replaces all attachments; absent preserves them for older clients editing text.
3602 attachments: Schema.optional(Schema.Array(ChatAttachment)),
3603 }),
3604 Schema.Struct({
3605 type: Schema.Literal("runtime-request.respond"),
3606 commandId: CommandId,
3607 threadId: ThreadId,
3608 requestId: RuntimeRequestId,
3609 decision: Schema.optional(ProviderApprovalDecision),
3610 feedback: Schema.optional(Schema.String),
3611 answers: Schema.optional(ProviderUserInputAnswers),
3612 attachmentsByQuestionId: Schema.optional(UserInputAttachments),
3613 }),
3614 Schema.Struct({
3615 type: Schema.Literal("thread.user-input.dismiss"),
3616 commandId: CommandId,
3617 threadId: ThreadId,
3618 requestId: RuntimeRequestId,
3619 }),
3620 Schema.Struct({
3621 type: Schema.Literal("checkpoint.rollback"),
3622 restoreFiles: Schema.optional(Schema.Boolean),
3623 commandId: CommandId,
3624 threadId: ThreadId,
3625 scopeId: CheckpointScopeId,
3626 checkpointId: CheckpointId,
3627 }),
3628 Schema.Struct({
3629 type: Schema.Literal("thread.fork"),
3630 ...OrchestrationV2CreationFields,
3631 commandId: CommandId,
3632 sourceThreadId: ThreadId,
3633 targetThreadId: ThreadId,
3634 sourcePoint: OrchestrationV2ThreadForkSourcePoint,
3635 title: Schema.optional(TrimmedNonEmptyString),
3636 sideChat: Schema.optional(Schema.Boolean),
3637 createdAt: Schema.optional(Schema.DateTimeUtc),
3638 }),
3639 Schema.Struct({
3640 type: Schema.Literal("thread.merge_back"),
3641 ...OrchestrationV2CreationFields,
3642 commandId: CommandId,
3643 sourceThreadId: ThreadId,
3644 targetThreadId: ThreadId,
3645 sourcePoint: OrchestrationV2ThreadForkSourcePoint,
3646 createdAt: Schema.optional(Schema.DateTimeUtc),
3647 }),
3648 Schema.Struct({
3649 type: Schema.Literal("delegated_task.request"),
3650 ...OrchestrationV2CreationFields,
3651 commandId: CommandId,
3652 parentThreadId: ThreadId,
3653 parentRunId: RunId,
3654 parentNodeId: NodeId,
3655 task: TrimmedNonEmptyString,
3656 title: Schema.optional(TrimmedNonEmptyString),
3657 modelSelection: ModelSelection,
3658 runtimeMode: RuntimeMode,
3659 interactionMode: ProviderInteractionMode,
3660 workspaceStrategy: Schema.optional(OrchestrationV2ThreadLaunchWorkspaceStrategy),
3661 // Defaults to settled_only; fire-and-forget wakes require always.
3662 completionWake: Schema.optional(Schema.Literals(["always", "settled_only"])),
3663 createdAt: Schema.optional(Schema.DateTimeUtc),
3664 }),
3665 Schema.Struct({
3666 type: Schema.Literal("delegated_task.wake-policy"),
3667 commandId: CommandId,
3668 parentThreadId: ThreadId,
3669 taskId: NodeId,
3670 completionWake: Schema.Literals(["always", "settled_only"]),
3671 }),
3672 Schema.Struct({
3673 type: Schema.Literal("delegated_task.completion-delivery.acknowledge"),
3674 commandId: CommandId,
3675 parentThreadId: ThreadId,
3676 taskId: NodeId,
3677 observedByRunId: Schema.NullOr(RunId),
3678 }),
3679 Schema.Struct({
3680 type: Schema.Literal("delegated_task.completion-delivery.dispose"),
3681 commandId: CommandId,
3682 parentThreadId: ThreadId,
3683 taskId: NodeId,
3684 }),
3685 Schema.Struct({
3686 type: Schema.Literal("thread.created.record"),
3687 commandId: CommandId,
3688 parentThreadId: ThreadId,
3689 parentRunId: RunId,
3690 parentNodeId: NodeId,
3691 targetThreadId: ThreadId,
3692 targetRunId: Schema.NullOr(RunId),
3693 }),
3694
3695 Schema.Struct({
3696 type: Schema.Literal("provider.switch"),
3697 commandId: CommandId,
3698 threadId: ThreadId,
3699 modelSelection: ModelSelection,
3700 }),
3701 ]);
3702 export type OrchestrationV2Command = typeof OrchestrationV2Command.Type;
3703
3704 // Excluded from dispatchCommand so only the server can send these.
3705 const OrchestrationV2InternalCommand = Schema.Union([
3706 // The server issues this after checking the value against the run's declared schema.
3707 Schema.Struct({
3708 type: Schema.Literal("run.output.submit"),
3709 commandId: CommandId,
3710 threadId: ThreadId,
3711 runId: RunId,
3712 value: Schema.Json,
3713 }),
3714 // Guest share commands the server issues after checking T3 Connect and the guest token.
3715 Schema.Struct({
3716 type: Schema.Literal("thread.guest-share.open"),
3717 commandId: CommandId,
3718 threadId: ThreadId,
3719 shareId: GuestShareId,
3720 host: TrimmedNonEmptyString,
3721 expiresAt: IsoDateTime,
3722 }),
3723 Schema.Struct({
3724 type: Schema.Literal("thread.guest-share.redeem"),
3725 commandId: CommandId,
3726 threadId: ThreadId,
3727 shareId: GuestShareId,
3728 guestName: TrimmedNonEmptyString,
3729 }),
3730 Schema.Struct({
3731 type: Schema.Literal("thread.guest-message.submit"),
3732 commandId: CommandId,
3733 threadId: ThreadId,
3734 shareId: GuestShareId,
3735 guestMessageId: GuestMessageId,
3736 text: Schema.String,
3737 attachments: Schema.optional(Schema.Array(ChatAttachment)),
3738 }),
3739 /** Moves a thread to a project rooted at the folder it already works in, so its cwd never changes. */
3740 Schema.Struct({
3741 type: Schema.Literal("thread.project.adopt-folder"),
3742 commandId: CommandId,
3743 threadId: ThreadId,
3744 projectId: ProjectId,
3745 }),
3746 /**
3747 * After a push, the thread's watches forget whether their checks were running, since the push
3748 * can start new ones. Applied to the watches as they are then, so no earlier read overwrites them.
3749 */
3750 Schema.Struct({
3751 type: Schema.Literal("thread.pull-request-watch.checks-reopen"),
3752 commandId: CommandId,
3753 threadId: ThreadId,
3754 }),
3755 Schema.Struct({
3756 type: Schema.Literal("thread.pull-request-watch.sync"),
3757 commandId: CommandId,
3758 threadId: ThreadId,
3759 ...ThreadPullRequestKey.fields,
3760 startedAt: IsoDateTime,
3761 watch: Schema.NullOr(ThreadPullRequestWatch),
3762 /**
3763 * The watch's `checksPending` when this read started. A push that clears it during the read
3764 * makes the read's answer describe the old head, so the cleared answer stays.
3765 */
3766 checksPendingBefore: Schema.optional(Schema.Boolean),
3767 /** With `watch: null`, the state the ended watch keeps instead of its last saved one. */
3768 endedWatch: Schema.optional(ThreadPullRequestWatch),
3769 /** More watches of this thread recorded together, which `wake` also reports on. */
3770 others: Schema.optional(
3771 Schema.Array(
3772 Schema.Struct({
3773 ...ThreadPullRequestKey.fields,
3774 startedAt: IsoDateTime,
3775 watch: Schema.NullOr(ThreadPullRequestWatch),
3776 checksPendingBefore: Schema.optional(Schema.Boolean),
3777 endedWatch: Schema.optional(ThreadPullRequestWatch),
3778 includesRemarks: Schema.optional(Schema.Boolean),
3779 }),
3780 ),
3781 ),
3782 wake: Schema.optional(
3783 Schema.Struct({
3784 messageId: MessageId,
3785 text: Schema.String,
3786 notification: OrchestrationV2Notification,
3787 /** Comments stay worth reading after a push, so the wake outlives a newer head. */
3788 includesRemarks: Schema.optional(Schema.Boolean),
3789 /** With `others`, each pull request's own part, in the same order. */
3790 sections: Schema.optional(Schema.Array(PullRequestWakeSection)),
3791 }),
3792 ),
3793 }),
3794 /**
3795 * Records a delegated task that runs in a linked environment: the task, its
3796 * node and its turn item on the parent, as `delegated_task.request` does,
3797 * without a child thread here. `remoteChild` is the thread already launched
3798 * there. The ids derive from `commandId`, so a retry records nothing new.
3799 */
3800 Schema.Struct({
3801 type: Schema.Literal("delegated_task.remote.request"),
3802 commandId: CommandId,
3803 parentThreadId: ThreadId,
3804 parentRunId: RunId,
3805 parentNodeId: NodeId,
3806 task: TrimmedNonEmptyString,
3807 title: Schema.optional(TrimmedNonEmptyString),
3808 driver: ProviderDriverKind,
3809 modelSelection: ModelSelection,
3810 remoteChild: OrchestrationV2RemoteTaskChild,
3811 completionWake: Schema.optional(Schema.Literals(["always", "settled_only"])),
3812 }),
3813 /**
3814 * Completes a delegated task that ran in a linked environment, with what its
3815 * thread there ended as. The parent wakes exactly as for a child here. A
3816 * task that already has a result keeps it; `stoppedThere` is still recorded,
3817 * and without it (a Stop or cancel here) the task owes a stop there instead.
3818 */
3819 Schema.Struct({
3820 type: Schema.Literal("delegated_task.remote.complete"),
3821 commandId: CommandId,
3822 parentThreadId: ThreadId,
3823 taskId: NodeId,
3824 status: Schema.Literals(["completed", "failed", "cancelled", "interrupted"]),
3825 result: Schema.String,
3826 executedModel: Schema.optional(Schema.String),
3827 /**
3828 * `ran-out`: the run there ended by itself; `stopped`: a stop from here reached it. Either
3829 * sets `remoteChild.stoppedThere` on a task this report completes. On a task already
3830 * cancelled or stopped here only `stopped` does, since a run that ended by itself leaves
3831 * the stop owed for whatever follows it.
3832 */
3833 stoppedThere: Schema.optional(Schema.Literals(["ran-out", "stopped"])),
3834 /** The stop generation this report acknowledges; absent for the original unnumbered stop. */
3835 stopCount: Schema.optional(NonNegativeInt),
3836 }),
3837 /**
3838 * Owes a stop to the thread there of a remote task that already has its result, as Stop on
3839 * a parent stops a finished child here. The task keeps its status, result and completion
3840 * delivery; its follower sends the stop and reports it with `delegated_task.remote.complete`.
3841 */
3842 Schema.Struct({
3843 type: Schema.Literal("delegated_task.remote.stop"),
3844 commandId: CommandId,
3845 parentThreadId: ThreadId,
3846 taskId: NodeId,
3847 }),
3848 Schema.Struct({
3849 type: Schema.Literal("checkpoint.rollback.fail"),
3850 commandId: CommandId,
3851 threadId: ThreadId,
3852 requestId: CommandId,
3853 message: TrimmedNonEmptyString,
3854 }),
3855 /** Delivering the answer to request `requestId` failed on its last attempt. */
3856 Schema.Struct({
3857 type: Schema.Literal("runtime-request.delivery.fail"),
3858 commandId: CommandId,
3859 threadId: ThreadId,
3860 requestId: RuntimeRequestId,
3861 }),
3862 /** The provider did not confirm a Stop of this turn in time. */
3863 Schema.Struct({
3864 type: Schema.Literal("thread.interrupt.unresponsive"),
3865 commandId: CommandId,
3866 threadId: ThreadId,
3867 providerThreadId: ProviderThreadId,
3868 providerTurnId: ProviderTurnId,
3869 }),
3870 Schema.Struct({
3871 type: Schema.Literal("thread.background-work.settle"),
3872 commandId: CommandId,
3873 threadId: ThreadId,
3874 providerThreadId: ProviderThreadId,
3875 providerTurnId: ProviderTurnId,
3876 /** Replaces the Stop's own reason on the result, as Force stop does. */
3877 reason: Schema.optional(Schema.String),
3878 subagent: Schema.optional(
3879 Schema.Struct({
3880 id: NodeId,
3881 stoppedAt: Schema.DateTimeUtc,
3882 outcome: Schema.Struct({
3883 status: Schema.Literals(["completed", "failed", "cancelled"]),
3884 completedAt: Schema.DateTimeUtc,
3885 result: Schema.NullOr(Schema.String),
3886 }),
3887 }),
3888 ),
3889 }),
3890 /**
3891 * Internal so no client can mark a request saved without the value being
3892 * stored.
3893 */
3894 Schema.Struct({
3895 type: Schema.Literal("secret_request.record"),
3896 commandId: CommandId,
3897 threadId: ThreadId,
3898 runId: RunId,
3899 nodeId: NodeId,
3900 turnItemId: TurnItemId,
3901 label: TrimmedNonEmptyString,
3902 reason: Schema.String,
3903 url: Schema.optional(Schema.String),
3904 placeholder: Schema.optional(Schema.String),
3905 delivery: Schema.optional(OrchestrationV2SecretRequestDelivery),
3906 fields: Schema.optional(Schema.Array(OrchestrationV2SecretRequestField)),
3907 secretStatus: OrchestrationV2SecretRequestStatus,
3908 }),
3909 /**
3910 * Records or updates a link an agent asked the user to make. Internal so no
3911 * client can mark a request linked without the link being made.
3912 */
3913 Schema.Struct({
3914 type: Schema.Literal("link_request.record"),
3915 commandId: CommandId,
3916 threadId: ThreadId,
3917 runId: RunId,
3918 nodeId: NodeId,
3919 turnItemId: TurnItemId,
3920 url: Schema.optional(TrimmedNonEmptyString),
3921 reason: Schema.String,
3922 environmentId: Schema.optional(EnvironmentId),
3923 label: Schema.optional(Schema.String),
3924 hint: Schema.optional(Schema.String),
3925 requestedAccess: Schema.optional(AuthMcpClientAccess),
3926 linkStatus: OrchestrationV2LinkRequestStatus,
3927 linkedEnvironmentId: Schema.optional(EnvironmentId),
3928 linkedLabel: Schema.optional(Schema.String),
3929 linkedAccess: Schema.optional(AuthMcpClientAccess),
3930 failure: Schema.optional(Schema.String),
3931 /**
3932 * Cards still being answered when this one linked. Their own answers end
3933 * them, so the link leaves them open; never stored on a card.
3934 */
3935 answeringTurnItemIds: Schema.optional(Schema.Array(TurnItemId)),
3936 /** Tells the agent how the card ended, in the same commit that closes it. */
3937 wake: Schema.optional(
3938 Schema.Struct({
3939 messageId: MessageId,
3940 text: Schema.String,
3941 notification: OrchestrationV2Notification,
3942 }),
3943 ),
3944 }),
3945 ]);
3946 export type OrchestrationV2InternalCommand = typeof OrchestrationV2InternalCommand.Type;
3947
3948 export type OrchestrationV2ServerCommand = OrchestrationV2Command | OrchestrationV2InternalCommand;
3949
3950 export const ORCHESTRATION_V2_WS_METHODS = {
3951 dispatchCommand: "orchestration.dispatchCommand",
3952 getTurnDiff: "orchestration.getTurnDiff",
3953 getFullThreadDiff: "orchestration.getFullThreadDiff",
3954 searchThreads: "orchestration.searchThreads",
3955 searchThread: "orchestration.searchThread",
3956 searchThreadStream: "orchestration.searchThreadStream",
3957 getArchivedShellSnapshot: "orchestration.getArchivedShellSnapshot",
3958 getThreadFamily: "orchestration.getThreadFamily",
3959 getThreadTitles: "orchestration.getThreadTitles",
3960 getThreadLinkMetadata: "orchestration.getThreadLinkMetadata",
3961 getWorktreeThreadIds: "orchestration.getWorktreeThreadIds",
3962 getOlderSettledThreads: "orchestration.getOlderSettledThreads",
3963 getThreadProjection: "orchestration.getThreadProjection",
3964 getWorkflowScript: "orchestration.getWorkflowScript",
3965 getNativeChildWork: "orchestration.getNativeChildWork",
3966 stopWorkflow: "orchestration.stopWorkflow",
3967 forceStopThread: "orchestration.forceStopThread",
3968 getTurnItem: "orchestration.getTurnItem",
3969 launchThread: "orchestration.launchThread",
3970 subscribeShell: "orchestration.subscribeShell",
3971 subscribeThread: "orchestration.subscribeThread",
3972 subscribeCommandOutput: "orchestration.subscribeCommandOutput",
3973 subscribePromptSuggestion: "orchestration.subscribePromptSuggestion",
3974 } as const;
3975
3976 export const OrchestrationV2SubscribeCommandOutputInput = Schema.Struct({
3977 threadId: ThreadId,
3978 itemId: TurnItemId,
3979 });
3980 export type OrchestrationV2SubscribeCommandOutputInput =
3981 typeof OrchestrationV2SubscribeCommandOutputInput.Type;
3982
3983 /** Unpersisted stream for expanded rows: replace resets the bounded tail, append extends it, and running:false ends it.
3984 * Feed both through @t3tools/shared/terminalOutput appendTerminalOutput to preserve cursor and style escapes. */
3985 export const OrchestrationV2CommandOutputFrame = Schema.Struct({
3986 kind: Schema.Literals(["replace", "append"]),
3987 text: Schema.String,
3988 /** Earlier output was dropped to keep the tail bounded. */
3989 truncated: Schema.Boolean,
3990 running: Schema.Boolean,
3991 });
3992 export type OrchestrationV2CommandOutputFrame = typeof OrchestrationV2CommandOutputFrame.Type;
3993
3994 export class OrchestrationV2CommandOutputError extends Schema.TaggedError<OrchestrationV2CommandOutputError>()(
3995 "OrchestrationV2CommandOutputError",
3996 {
3997 threadId: ThreadId,
3998 message: Schema.String,
3999 cause: Schema.optional(Schema.Defect()),
4000 },
4001 ) {}
4002
4003 export const OrchestrationV2SubscribePromptSuggestionInput = Schema.Struct({
4004 threadId: ThreadId,
4005 });
4006
4007 /** Unpersisted predicted next prompt for the run that produced it; null when there is none. */
4008 export const OrchestrationV2PromptSuggestion = Schema.NullOr(
4009 Schema.Struct({ runId: RunId, text: Schema.String }),
4010 );
4011 export type OrchestrationV2PromptSuggestion = typeof OrchestrationV2PromptSuggestion.Type;
4012
4013 export const OrchestrationV2ArchivedShellSnapshot = Schema.Struct({
4014 schemaVersion: PositiveInt,
4015 snapshotSequence: NonNegativeInt,
4016 projects: Schema.Array(OrchestrationProjectShell),
4017 threads: Schema.Array(OrchestrationV2ThreadShell),
4018 });
4019 export type OrchestrationV2ArchivedShellSnapshot = typeof OrchestrationV2ArchivedShellSnapshot.Type;
4020
4021 export const OrchestrationV2ThreadLaunchInput = Schema.Struct({
4022 commandId: CommandId,
4023 creationSource: Schema.optional(OrchestrationV2CreationSource),
4024 threadId: Schema.optional(ThreadId),
4025 reuseExistingThread: Schema.optional(Schema.Boolean),
4026 projectId: ProjectId,
4027 title: TrimmedNonEmptyString,
4028 generateTitle: Schema.optional(Schema.Boolean),
4029 modelSelection: ModelSelection,
4030 runtimeMode: RuntimeMode,
4031 interactionMode: ProviderInteractionMode,
4032 workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy,
4033 initialMessage: Schema.optional(
4034 Schema.Struct({
4035 messageId: Schema.optional(MessageId),
4036 text: Schema.String,
4037 context: Schema.optional(OrchestrationMessageContext),
4038 attachments: Schema.Array(ChatAttachment),
4039 }),
4040 ),
4041 });
4042 export type OrchestrationV2ThreadLaunchInput = typeof OrchestrationV2ThreadLaunchInput.Type;
4043
4044 export const OrchestrationV2ThreadLaunchResult = Schema.Struct({
4045 threadId: ThreadId,
4046 projection: OrchestrationV2ThreadProjection,
4047 resumed: Schema.Boolean,
4048 /** The initial message's commit sequence. Older servers omit it. */
4049 sequence: Schema.optionalKey(NonNegativeInt),
4050 });
4051 export type OrchestrationV2ThreadLaunchResult = typeof OrchestrationV2ThreadLaunchResult.Type;
4052
4053 export const OrchestrationV2DispatchCommandResult = Schema.Struct({
4054 sequence: NonNegativeInt,
4055 });
4056 export type OrchestrationV2DispatchCommandResult = typeof OrchestrationV2DispatchCommandResult.Type;
4057
4058 export const OrchestrationV2GetThreadProjectionInput = Schema.Struct({
4059 threadId: ThreadId,
4060 });
4061 export type OrchestrationV2GetThreadProjectionInput =
4062 typeof OrchestrationV2GetThreadProjectionInput.Type;
4063
4064 export const OrchestrationV2SubscribeShellInput = Schema.Struct({
4065 afterSequence: Schema.optionalKey(NonNegativeInt),
4066 /**
4067 * With `afterSequence`, a gap the server cannot replay answers `snapshot-required` instead of
4068 * a socket snapshot, which clients without transport compression download over gzip HTTP.
4069 */
4070 httpSnapshotFallback: Schema.optionalKey(Schema.Literal(true)),
4071 /**
4072 * The `projectIdentities` of the HTTP snapshot whose cursor is `afterSequence`, when the client
4073 * changed nothing since. A resume that still has the same identities does not resend them.
4074 */
4075 knownProjectIdentities: Schema.optionalKey(Schema.String),
4076 requestCompletionMarker: Schema.optionalKey(Schema.Boolean),
4077 /**
4078 * Snapshots leave out idle subagent children; read them with `getThreadFamily`. Send only to
4079 * servers that advertise `shellThreadFamilies`.
4080 */
4081 omitIdleSubagents: Schema.optionalKey(Schema.Boolean),
4082 /**
4083 * Snapshots leave out older settled threads and count them in `olderSettled`; read them with
4084 * `getOlderSettledThreads`. Send only to servers that advertise `shellOlderSettled`.
4085 */
4086 omitOlderSettled: Schema.optionalKey(Schema.Boolean),
4087 });
4088 export type OrchestrationV2SubscribeShellInput = typeof OrchestrationV2SubscribeShellInput.Type;
4089
4090 export const OrchestrationV2GetThreadFamilyInput = Schema.Struct({
4091 threadId: ThreadId,
4092 });
4093 export type OrchestrationV2GetThreadFamilyInput = typeof OrchestrationV2GetThreadFamilyInput.Type;
4094
4095 /**
4096 * The active threads that share the requested thread's `lineage.rootThreadId`: the root, its
4097 * forks, and their whole subagent trees, in any run state. An unknown thread has an empty family;
4098 * a deleted one still names its root.
4099 */
4100 export const OrchestrationV2ThreadFamily = Schema.Struct({
4101 snapshotSequence: NonNegativeInt,
4102 threads: Schema.Array(OrchestrationV2ThreadShell),
4103 });
4104 export type OrchestrationV2ThreadFamily = typeof OrchestrationV2ThreadFamily.Type;
4105
4106 export const OrchestrationV2GetThreadTitlesInput = Schema.Struct({
4107 threadIds: Schema.Array(ThreadId),
4108 });
4109
4110 /** Titles of the requested threads that exist, archived ones included. Deleted and unknown ids are absent. */
4111 export const OrchestrationV2ThreadTitles = Schema.Record(ThreadId, Schema.String);
4112
4113 export const OrchestrationV2ThreadLinkMetadata = Schema.Struct({
4114 title: Schema.String,
4115 projectId: Schema.NullOr(ProjectId),
4116 });
4117 export type OrchestrationV2ThreadLinkMetadata = typeof OrchestrationV2ThreadLinkMetadata.Type;
4118
4119 export const OrchestrationV2GetWorktreeThreadIdsInput = Schema.Struct({
4120 worktreePath: TrimmedNonEmptyString,
4121 });
4122 export type OrchestrationV2GetWorktreeThreadIdsInput =
4123 typeof OrchestrationV2GetWorktreeThreadIdsInput.Type;
4124
4125 /**
4126 * The client's thread search. With `olderSettledBefore`, the result also carries the rows of the
4127 * best matching threads settled before it, which shells that omit older settled threads leave out:
4128 * title, branch, pull request and project matches (in `projectIds` when given), then message hits.
4129 * Send the extra keys only to servers that advertise `shellOlderSettled`.
4130 */
4131 export const OrchestrationV2SearchThreadsInput = Schema.Struct({
4132 ...OrchestrationSearchThreadsInput.fields,
4133 olderSettledBefore: Schema.optionalKey(IsoDateTime),
4134 projectIds: Schema.optionalKey(Schema.Array(ProjectId)),
4135 /** The client's name for this environment, which its own ranking also matches. */
4136 environmentLabel: Schema.optionalKey(Schema.String),
4137 /** Skips message search, for pickers that match titles only. */
4138 titlesOnly: Schema.optionalKey(Schema.Boolean),
4139 });
4140 export type OrchestrationV2SearchThreadsInput = typeof OrchestrationV2SearchThreadsInput.Type;
4141
4142 export const OrchestrationV2SearchThreadsResult = Schema.Struct({
4143 ...OrchestrationSearchThreadsResult.fields,
4144 snapshotSequence: Schema.optionalKey(NonNegativeInt),
4145 threads: Schema.optionalKey(Schema.Array(OrchestrationV2ThreadShell)),
4146 });
4147 export type OrchestrationV2SearchThreadsResult = typeof OrchestrationV2SearchThreadsResult.Type;
4148
4149 /** Where a page of older settled threads starts: below this settle time, then after this id. */
4150 export const OrchestrationV2OlderSettledCursor = Schema.Struct({
4151 settledAt: IsoDateTime,
4152 threadId: Schema.optionalKey(ThreadId),
4153 });
4154 export type OrchestrationV2OlderSettledCursor = typeof OrchestrationV2OlderSettledCursor.Type;
4155
4156 export const OrchestrationV2GetOlderSettledThreadsInput = Schema.Struct({
4157 before: OrchestrationV2OlderSettledCursor,
4158 /** Every project when absent. */
4159 projectIds: Schema.optionalKey(Schema.Array(ProjectId)),
4160 /** 0 reads only the counts. */
4161 limit: Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 50 })),
4162 });
4163 export type OrchestrationV2GetOlderSettledThreadsInput =
4164 typeof OrchestrationV2GetOlderSettledThreadsInput.Type;
4165
4166 /**
4167 * Older settled threads below the cursor, newest settle first (`settledAt` desc, then id asc). A
4168 * `limit: 0` read fills `counts` instead: the older settled threads below the cursor per project,
4169 * as `OrchestrationV2OlderSettledThreads.counts` count them. A cursor without an id is strict.
4170 */
4171 export const OrchestrationV2OlderSettledThreadsPage = Schema.Struct({
4172 snapshotSequence: NonNegativeInt,
4173 threads: Schema.Array(OrchestrationV2ThreadShell),
4174 counts: Schema.Array(OrchestrationV2OlderSettledCount),
4175 });
4176 export type OrchestrationV2OlderSettledThreadsPage =
4177 typeof OrchestrationV2OlderSettledThreadsPage.Type;
4178
4179 /** Active threads on a worktree path, including subagent children a shell may leave out. */
4180 export const OrchestrationV2WorktreeThreadIds = Schema.Struct({
4181 threadIds: Schema.Array(ThreadId),
4182 });
4183 export type OrchestrationV2WorktreeThreadIds = typeof OrchestrationV2WorktreeThreadIds.Type;
4184
4185 export const OrchestrationV2SubscribeThreadInput = Schema.Struct({
4186 threadId: ThreadId,
4187 afterSequence: Schema.optionalKey(NonNegativeInt),
4188 requestCompletionMarker: Schema.optionalKey(Schema.Boolean),
4189 acceptBoundedSnapshot: Schema.optionalKey(Schema.Boolean),
4190 acceptDeferredWork: Schema.optionalKey(Schema.Boolean),
4191 acceptCompactTurnItems: Schema.optionalKey(Schema.Boolean),
4192 /** The client restores `*Omitted` bodies from records it already holds. */
4193 acceptDedupedBodies: Schema.optionalKey(Schema.Boolean),
4194 acceptCompactIds: Schema.optionalKey(Schema.Boolean),
4195 });
4196 export type OrchestrationV2SubscribeThreadInput = typeof OrchestrationV2SubscribeThreadInput.Type;
4197
4198 /**
4199 * Server-side only: set it on a response for a client that opted in, and the
4200 * `withRecordIdTable` codec sends that response with an ID table.
4201 */
4202 const IdTableMarker = Schema.optionalKey(Schema.Literal(true));
4203
4204 export const OrchestrationV2ThreadDetailSnapshot = Schema.Struct({
4205 snapshotSequence: NonNegativeInt,
4206 projection: OrchestrationV2ThreadProjection,
4207 /** With hasMoreHistory/cursor, this projection is a bounded window, not a complete timeline. */
4208 historyCursor: Schema.optionalKey(Schema.NullOr(TrimmedNonEmptyString)),
4209 hasMoreHistory: Schema.optionalKey(Schema.Boolean),
4210 latestLocalTurnOrdinal: Schema.optionalKey(Schema.NullOr(NonNegativeInt)),
4211 });
4212 export type OrchestrationV2ThreadDetailSnapshot = typeof OrchestrationV2ThreadDetailSnapshot.Type;
4213
4214 /** Keep historyCursor opaque; resume events with afterSequence = snapshotSequence. */
4215 export const OrchestrationV2ThreadBoundedSnapshot = withRecordIdTable(
4216 Schema.Struct({
4217 snapshotSequence: NonNegativeInt,
4218 projection: OrchestrationV2ThreadProjection,
4219 historyCursor: Schema.NullOr(TrimmedNonEmptyString),
4220 hasMoreHistory: Schema.Boolean,
4221 latestLocalTurnOrdinal: Schema.NullOr(NonNegativeInt),
4222 /**
4223 * Set only for clients that opted in: `projection.turnItems` omits the items
4224 * of local visible rows, which lead the full list. Clients must restore them
4225 * with `boundedSnapshotProjection` before using the projection.
4226 */
4227 turnItemsOmitLocalVisible: Schema.optionalKey(Schema.Literal(true)),
4228 idTable: IdTableMarker,
4229 }),
4230 () => "projection",
4231 );
4232 export type OrchestrationV2ThreadBoundedSnapshot = typeof OrchestrationV2ThreadBoundedSnapshot.Type;
4233
4234 export const OrchestrationV2ThreadHistoryPage = withRecordIdTable(
4235 Schema.Struct({
4236 snapshotSequence: NonNegativeInt,
4237 items: projectedTurnItemArray(
4238 OrchestrationV2ProjectedTurnItem,
4239 OrchestrationV2ProjectedTurnItem.mapFields((fields) => ({
4240 ...fields,
4241 item: ForwardCompatibleUnion(OrchestrationV2TurnItem.members, "type"),
4242 })),
4243 ),
4244 nextCursor: Schema.NullOr(TrimmedNonEmptyString),
4245 hasMoreHistory: Schema.Boolean,
4246 /** Records of the page's subagent items, which a bounded snapshot can omit. */
4247 subagents: Schema.optionalKey(Schema.Array(OrchestrationV2Subagent)),
4248 idTable: IdTableMarker,
4249 }),
4250 () => null,
4251 );
4252 export type OrchestrationV2ThreadHistoryPage = typeof OrchestrationV2ThreadHistoryPage.Type;
4253
4254 const knownDomainEventTypes: ReadonlySet<string> = new Set(
4255 OrchestrationV2DomainEvent.members.flatMap((member) => {
4256 const type = member.fields.type;
4257 return "literals" in type ? type.literals : [type.literal];
4258 }),
4259 );
4260
4261 export function isKnownOrchestrationV2EventType(type: string): boolean {
4262 return knownDomainEventTypes.has(type);
4263 }
4264
4265 // Skip unknown event or turn-item types while advancing the resume cursor.
4266 const OrchestrationV2UnknownThreadStreamEvent = Schema.Struct({
4267 kind: Schema.Literal("event"),
4268 sequence: NonNegativeInt,
4269 event: Schema.Struct({
4270 type: Schema.String,
4271 payload: Schema.optional(Schema.Unknown),
4272 }).check(
4273 Schema.makeFilter(
4274 (event) =>
4275 !knownDomainEventTypes.has(event.type) ||
4276 (event.type === "turn-item.updated" && isUnknownTurnItem(event.payload)) ||
4277 "A known event type must decode in full.",
4278 ),
4279 ),
4280 }).pipe(
4281 Schema.decodeTo(
4282 Schema.Struct({
4283 kind: Schema.Literal("unknown-event"),
4284 sequence: NonNegativeInt,
4285 eventType: Schema.String,
4286 }),
4287 {
4288 decode: SchemaGetter.transform((item) => ({
4289 kind: "unknown-event" as const,
4290 sequence: item.sequence,
4291 eventType: item.event.type,
4292 })),
4293 encode: SchemaGetter.forbidden(() => "Servers never send unknown thread events."),
4294 },
4295 ),
4296 );
4297
4298 export const OrchestrationV2ThreadStreamItem = withRecordIdTable(
4299 Schema.Union([
4300 Schema.Struct({
4301 kind: Schema.Literal("synchronized"),
4302 }),
4303 Schema.Struct({
4304 kind: Schema.Literal("snapshot"),
4305 snapshotSequence: NonNegativeInt,
4306 projection: OrchestrationV2ThreadProjection,
4307 historyCursor: Schema.optionalKey(Schema.NullOr(TrimmedNonEmptyString)),
4308 hasMoreHistory: Schema.optionalKey(Schema.Boolean),
4309 latestLocalTurnOrdinal: Schema.optionalKey(Schema.NullOr(NonNegativeInt)),
4310 turnItemsOmitLocalVisible: Schema.optionalKey(Schema.Literal(true)),
4311 idTable: IdTableMarker,
4312 }),
4313 Schema.Struct({
4314 kind: Schema.Literal("event"),
4315 sequence: NonNegativeInt,
4316 event: OrchestrationV2DomainEvent,
4317 }),
4318 OrchestrationV2UnknownThreadStreamEvent,
4319 ]),
4320 (item) => (item.kind === "snapshot" ? "projection" : undefined),
4321 );
4322 export type OrchestrationV2ThreadStreamItem = typeof OrchestrationV2ThreadStreamItem.Type;
4323
4324 export class OrchestrationV2DispatchCommandError extends Schema.TaggedError<OrchestrationV2DispatchCommandError>()(
4325 "OrchestrationV2DispatchCommandError",
4326 {
4327 commandId: CommandId,
4328 commandType: Schema.String,
4329 message: Schema.String,
4330 detail: Schema.optional(Schema.String),
4331 cause: Schema.optional(Schema.Defect()),
4332 },
4333 ) {}
4334
4335 export class OrchestrationV2GetThreadProjectionError extends Schema.TaggedError<OrchestrationV2GetThreadProjectionError>()(
4336 "OrchestrationV2GetThreadProjectionError",
4337 {
4338 threadId: ThreadId,
4339 message: Schema.String,
4340 cause: Schema.optional(Schema.Defect()),
4341 },
4342 ) {}
4343
4344 export class OrchestrationV2GetShellSnapshotError extends Schema.TaggedError<OrchestrationV2GetShellSnapshotError>()(
4345 "OrchestrationV2GetShellSnapshotError",
4346 {
4347 message: Schema.String,
4348 cause: Schema.optional(Schema.Defect()),
4349 },
4350 ) {}
4351
4352 export class OrchestrationV2ThreadLaunchError extends Schema.TaggedError<OrchestrationV2ThreadLaunchError>()(
4353 "OrchestrationV2ThreadLaunchError",
4354 {
4355 commandId: CommandId,
4356 projectId: ProjectId,
4357 message: Schema.String,
4358 cause: Schema.optional(Schema.Defect()),
4359 },
4360 ) {}
4361
4362 export const OrchestrationV2StopWorkflowInput = Schema.Struct({
4363 threadId: ThreadId,
4364 subagentId: NodeId,
4365 });
4366 export type OrchestrationV2StopWorkflowInput = typeof OrchestrationV2StopWorkflowInput.Type;
4367
4368 export class OrchestrationV2StopWorkflowError extends Schema.TaggedError<OrchestrationV2StopWorkflowError>()(
4369 "OrchestrationV2StopWorkflowError",
4370 {
4371 threadId: ThreadId,
4372 subagentId: NodeId,
4373 reason: Schema.Literals(["not-running", "unsupported", "unavailable", "stop-failed"]),
4374 cause: Schema.optional(Schema.Defect()),
4375 },
4376 ) {
4377 override get message(): string {
4378 switch (this.reason) {
4379 case "not-running":
4380 return "This workflow is no longer running.";
4381 case "unsupported":
4382 return "This provider cannot stop a workflow.";
4383 case "unavailable":
4384 return "This workflow has no live provider task.";
4385 case "stop-failed":
4386 return "Failed to stop the workflow.";
4387 }
4388 }
4389 }
4390
4391 export const OrchestrationV2ForceStopThreadInput = Schema.Struct({
4392 threadId: ThreadId,
4393 /** The run the user saw ignore Stop; Force stop refuses once a newer run has started. */
4394 runId: Schema.optionalKey(RunId),
4395 });
4396 export type OrchestrationV2ForceStopThreadInput = typeof OrchestrationV2ForceStopThreadInput.Type;
4397
4398 export const OrchestrationV2ForceStopThreadResult = Schema.Struct({
4399 /**
4400 * `killed`: its own agent processes were killed. `released`: its provider session was torn
4401 * down (killing the agent's process group) or handed to its newer run. `releasing`: teardown
4402 * continues on the server. `shared`: the agent process also works for `sharedWithThreadIds`,
4403 * so only this thread's turn was ended.
4404 */
4405 outcome: Schema.Literals(["killed", "released", "releasing", "shared"]),
4406 sharedWithThreadIds: Schema.Array(ThreadId),
4407 });
4408 export type OrchestrationV2ForceStopThreadResult = typeof OrchestrationV2ForceStopThreadResult.Type;
4409
4410 export class OrchestrationV2ForceStopThreadError extends Schema.TaggedError<OrchestrationV2ForceStopThreadError>()(
4411 "OrchestrationV2ForceStopThreadError",
4412 {
4413 threadId: ThreadId,
4414 /** `superseded`: a newer run started since the user asked; nothing was stopped. */
4415 reason: Schema.optional(Schema.Literal("superseded")),
4416 cause: Schema.optional(Schema.Defect()),
4417 },
4418 ) {
4419 override get message(): string {
4420 return this.reason === "superseded"
4421 ? "A new turn started, so nothing was force stopped."
4422 : "Failed to force stop the agent.";
4423 }
4424 }
4425
4426 export const OrchestrationV2GetWorkflowScriptInput = Schema.Struct({
4427 threadId: ThreadId,
4428 scriptPath: TrimmedNonEmptyString,
4429 });
4430 export type OrchestrationV2GetWorkflowScriptInput =
4431 typeof OrchestrationV2GetWorkflowScriptInput.Type;
4432
4433 export const OrchestrationV2GetWorkflowScriptResult = Schema.Struct({
4434 scriptPath: TrimmedNonEmptyString,
4435 contents: Schema.String,
4436 truncated: Schema.Boolean,
4437 });
4438 export type OrchestrationV2GetWorkflowScriptResult =
4439 typeof OrchestrationV2GetWorkflowScriptResult.Type;
4440
4441 /** Names a provider-native subagent's child thread. */
4442 export const OrchestrationV2GetNativeChildWorkInput = Schema.Struct({
4443 threadId: ThreadId,
4444 });
4445 export type OrchestrationV2GetNativeChildWorkInput =
4446 typeof OrchestrationV2GetNativeChildWorkInput.Type;
4447
4448 export const OrchestrationV2NativeChildStep = Schema.Struct({
4449 index: NonNegativeInt,
4450 type: Schema.String,
4451 status: Schema.NullOr(Schema.String),
4452 text: Schema.NullOr(Schema.String),
4453 toolCalls: Schema.Array(Schema.Struct({ name: Schema.String, input: Schema.String })),
4454 });
4455 export type OrchestrationV2NativeChildStep = typeof OrchestrationV2NativeChildStep.Type;
4456
4457 /** Read-only: native children cannot take messages. */
4458 export const OrchestrationV2NativeChildWork = Schema.Struct({
4459 conversationId: TrimmedNonEmptyString,
4460 role: Schema.String,
4461 prompt: Schema.String,
4462 /** Null when the provider has no readable transcript for this child. */
4463 steps: Schema.NullOr(Schema.Array(OrchestrationV2NativeChildStep)),
4464 /** Earlier steps were left out to keep the read bounded. */
4465 truncated: Schema.Boolean,
4466 });
4467 export type OrchestrationV2NativeChildWork = typeof OrchestrationV2NativeChildWork.Type;
4468
4469 /** Empty when the provider's records do not prove which children the subagent launched. */
4470 export const OrchestrationV2GetNativeChildWorkResult = Schema.Struct({
4471 children: Schema.Array(OrchestrationV2NativeChildWork),
4472 });
4473 export type OrchestrationV2GetNativeChildWorkResult =
4474 typeof OrchestrationV2GetNativeChildWorkResult.Type;
4475
4476 export class OrchestrationV2GetNativeChildWorkError extends Schema.TaggedError<OrchestrationV2GetNativeChildWorkError>()(
4477 "OrchestrationV2GetNativeChildWorkError",
4478 {
4479 threadId: ThreadId,
4480 cause: Schema.optional(Schema.Defect()),
4481 },
4482 ) {
4483 override get message(): string {
4484 return "Failed to read the subagent's work.";
4485 }
4486 }
4487
4488 const WORKFLOW_FILE_ERROR_MESSAGES = {
4489 "invalid-path": "Workflow files must be absolute paths with the expected extension.",
4490 "root-unavailable": "Workflow file root unavailable.",
4491 "not-found": "Workflow file not found.",
4492 "outside-root": "Path is outside the workflow files root.",
4493 "wrong-extension": "Resolved file has the wrong extension.",
4494 "not-regular-file": "Workflow file is not a regular file.",
4495 "changed-during-read": "Workflow file changed between resolution and open.",
4496 "read-failed": "Workflow file read failed.",
4497 } as const;
4498
4499 export class OrchestrationWorkflowFileError extends Schema.TaggedError<OrchestrationWorkflowFileError>()(
4500 "OrchestrationWorkflowFileError",
4501 {
4502 reason: Schema.Literals([
4503 "invalid-path",
4504 "root-unavailable",
4505 "not-found",
4506 "outside-root",
4507 "wrong-extension",
4508 "not-regular-file",
4509 "changed-during-read",
4510 "read-failed",
4511 ]),
4512 path: Schema.String,
4513 cause: Schema.optional(Schema.Defect()),
4514 },
4515 ) {
4516 override get message(): string {
4517 return WORKFLOW_FILE_ERROR_MESSAGES[this.reason];
4518 }
4519 }
4520
4521 export const OrchestrationV2GetTurnItemInput = Schema.Struct({
4522 threadId: ThreadId,
4523 itemId: TurnItemId,
4524 revision: Schema.optional(Schema.String),
4525 });
4526 export type OrchestrationV2GetTurnItemInput = typeof OrchestrationV2GetTurnItemInput.Type;
4527
4528 export const OrchestrationV2GetTurnItemResult = Schema.Struct({
4529 item: Schema.NullOr(OrchestrationV2TurnItem),
4530 });
4531 export type OrchestrationV2GetTurnItemResult = typeof OrchestrationV2GetTurnItemResult.Type;
4532
4533 const WORKFLOW_SCRIPT_ERROR_MESSAGES = {
4534 "invalid-path": "Workflow scripts must be absolute .js paths.",
4535 "root-unavailable": "Script root unavailable.",
4536 "not-found": "Script not found.",
4537 "outside-root": "Script path is outside the workflow scripts root.",
4538 "not-js": "Resolved script is not a .js file.",
4539 "not-regular-file": "Script is not a regular file.",
4540 "changed-during-read": "Script changed between resolution and open.",
4541 "read-failed": "Script read failed.",
4542 } as const;
4543
4544 export class OrchestrationGetWorkflowScriptError extends Schema.TaggedError<OrchestrationGetWorkflowScriptError>()(
4545 "OrchestrationGetWorkflowScriptError",
4546 {
4547 reason: Schema.Literals([
4548 "invalid-path",
4549 "root-unavailable",
4550 "not-found",
4551 "outside-root",
4552 "not-js",
4553 "not-regular-file",
4554 "changed-during-read",
4555 "read-failed",
4556 ]),
4557 scriptPath: Schema.String,
4558 cause: Schema.optional(Schema.Defect()),
4559 },
4560 ) {
4561 override get message(): string {
4562 return WORKFLOW_SCRIPT_ERROR_MESSAGES[this.reason];
4563 }
4564 }
4565
4566 export const OrchestrationV2SearchThreadInput = Schema.Struct({
4567 threadId: ThreadId,
4568 theme: Schema.optionalKey(Schema.Literals(["dark", "light"])),
4569 skills: Schema.optionalKey(
4570 Schema.Array(
4571 Schema.Struct({
4572 name: Schema.String.check(Schema.isMaxLength(200)),
4573 displayName: Schema.optional(Schema.String.check(Schema.isMaxLength(200))),
4574 }),
4575 ).check(Schema.isMaxLength(1_000)),
4576 ),
4577 query: TrimmedNonEmptyString.check(Schema.isMaxLength(200)),
4578 index: Schema.optionalKey(NonNegativeInt),
4579 offset: Schema.optionalKey(Schema.Int),
4580 start: Schema.optionalKey(
4581 Schema.Struct({ entryId: TrimmedNonEmptyString, occurrence: NonNegativeInt }),
4582 ),
4583 });
4584 export type OrchestrationV2SearchThreadInput = typeof OrchestrationV2SearchThreadInput.Type;
4585
4586 export const OrchestrationV2ThreadFindMatch = Schema.Struct({
4587 entryId: TrimmedNonEmptyString,
4588 runId: Schema.NullOr(RunId),
4589 occurrence: NonNegativeInt,
4590 });
4591 export const OrchestrationV2SearchThreadResult = Schema.Struct({
4592 complete: Schema.optionalKey(Schema.Boolean),
4593 snapshotSequence: NonNegativeInt,
4594 totalMatches: NonNegativeInt,
4595 activeIndex: NonNegativeInt,
4596 match: Schema.NullOr(OrchestrationV2ThreadFindMatch),
4597 navigation: Schema.optionalKey(
4598 Schema.Array(
4599 Schema.Struct({
4600 entryId: TrimmedNonEmptyString,
4601 runId: Schema.NullOr(RunId),
4602 startIndex: NonNegativeInt,
4603 count: NonNegativeInt,
4604 }),
4605 ).check(Schema.isMaxLength(17)),
4606 ),
4607 });
4608 export type OrchestrationV2SearchThreadResult = typeof OrchestrationV2SearchThreadResult.Type;
4609
4610 export class OrchestrationV2SearchThreadError extends Schema.TaggedError<OrchestrationV2SearchThreadError>()(
4611 "OrchestrationV2SearchThreadError",
4612 { cause: Schema.Defect() },
4613 ) {
4614 override get message(): string {
4615 return "Could not search this thread. Please retry.";
4616 }
4617 }
4618
4619 export const OrchestrationV2RpcSchemas = {
4620 searchThread: {
4621 input: OrchestrationV2SearchThreadInput,
4622 output: OrchestrationV2SearchThreadResult,
4623 },
4624 dispatchCommand: {
4625 input: OrchestrationV2Command,
4626 output: OrchestrationV2DispatchCommandResult,
4627 },
4628 getTurnDiff: {
4629 input: OrchestrationGetTurnDiffInput,
4630 output: OrchestrationGetTurnDiffResult,
4631 },
4632 getFullThreadDiff: {
4633 input: OrchestrationGetFullThreadDiffInput,
4634 output: OrchestrationGetFullThreadDiffResult,
4635 },
4636 getArchivedShellSnapshot: {
4637 input: Schema.Struct({}),
4638 output: OrchestrationV2ArchivedShellSnapshot,
4639 },
4640 getThreadFamily: {
4641 input: OrchestrationV2GetThreadFamilyInput,
4642 output: OrchestrationV2ThreadFamily,
4643 },
4644 getThreadTitles: {
4645 input: OrchestrationV2GetThreadTitlesInput,
4646 output: OrchestrationV2ThreadTitles,
4647 },
4648 getThreadLinkMetadata: {
4649 input: OrchestrationV2GetThreadTitlesInput,
4650 output: Schema.Record(ThreadId, OrchestrationV2ThreadLinkMetadata),
4651 },
4652 getWorktreeThreadIds: {
4653 input: OrchestrationV2GetWorktreeThreadIdsInput,
4654 output: OrchestrationV2WorktreeThreadIds,
4655 },
4656 getOlderSettledThreads: {
4657 input: OrchestrationV2GetOlderSettledThreadsInput,
4658 output: OrchestrationV2OlderSettledThreadsPage,
4659 },
4660 getThreadProjection: {
4661 input: OrchestrationV2GetThreadProjectionInput,
4662 output: OrchestrationV2ThreadProjection,
4663 },
4664 stopWorkflow: {
4665 input: OrchestrationV2StopWorkflowInput,
4666 output: Schema.Void,
4667 },
4668 forceStopThread: {
4669 input: OrchestrationV2ForceStopThreadInput,
4670 output: OrchestrationV2ForceStopThreadResult,
4671 },
4672 getWorkflowScript: {
4673 input: OrchestrationV2GetWorkflowScriptInput,
4674 output: OrchestrationV2GetWorkflowScriptResult,
4675 },
4676 getNativeChildWork: {
4677 input: OrchestrationV2GetNativeChildWorkInput,
4678 output: OrchestrationV2GetNativeChildWorkResult,
4679 },
4680 getTurnItem: {
4681 input: OrchestrationV2GetTurnItemInput,
4682 output: OrchestrationV2GetTurnItemResult,
4683 },
4684 launchThread: {
4685 input: OrchestrationV2ThreadLaunchInput,
4686 output: OrchestrationV2ThreadLaunchResult,
4687 },
4688 subscribeShell: {
4689 input: OrchestrationV2SubscribeShellInput,
4690 output: OrchestrationV2ShellStreamItem,
4691 },
4692 subscribeThread: {
4693 input: OrchestrationV2SubscribeThreadInput,
4694 output: OrchestrationV2ThreadStreamItem,
4695 },
4696 subscribeCommandOutput: {
4697 input: OrchestrationV2SubscribeCommandOutputInput,
4698 output: OrchestrationV2CommandOutputFrame,
4699 },
4700 subscribePromptSuggestion: {
4701 input: OrchestrationV2SubscribePromptSuggestionInput,
4702 output: OrchestrationV2PromptSuggestion,
4703 },
4704 } as const;
4705
4706 export const ProviderReplayEntry = Schema.Union([
4707 Schema.Struct({
4708 type: Schema.Literal("expect_outbound"),
4709 label: Schema.optional(TrimmedNonEmptyString),
4710 frame: Schema.Unknown,
4711 }),
4712 Schema.Struct({
4713 type: Schema.Literal("emit_inbound"),
4714 label: Schema.optional(TrimmedNonEmptyString),
4715 frame: Schema.Unknown,
4716 afterMs: Schema.optional(NonNegativeInt),
4717 }),
4718 Schema.Struct({
4719 type: Schema.Literal("runtime_exit"),
4720 status: Schema.Literals(["success", "error", "cancelled"]),
4721 error: Schema.optional(Schema.Unknown),
4722 }),
4723 ]);
4724 export type ProviderReplayEntry = typeof ProviderReplayEntry.Type;
4725
4726 export const ProviderReplayTranscript = Schema.Struct({
4727 provider: TrimmedNonEmptyString,
4728 protocol: TrimmedNonEmptyString,
4729 version: TrimmedNonEmptyString,
4730 scenario: TrimmedNonEmptyString,
4731 metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
4732 entries: Schema.Array(ProviderReplayEntry),
4733 });
4734 export type ProviderReplayTranscript = typeof ProviderReplayTranscript.Type;
4735
4736 export const ProviderReplayTranscriptHeader = Schema.Struct({
4737 type: Schema.Literal("transcript_start"),
4738 provider: TrimmedNonEmptyString,
4739 protocol: TrimmedNonEmptyString,
4740 version: TrimmedNonEmptyString,
4741 scenario: TrimmedNonEmptyString,
4742 metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
4743 });
4744 export type ProviderReplayTranscriptHeader = typeof ProviderReplayTranscriptHeader.Type;
4745
4746 export const ProviderReplayNdjsonRecord = Schema.Union([
4747 ProviderReplayTranscriptHeader,
4748 ProviderReplayEntry,
4749 ]);
4750 export type ProviderReplayNdjsonRecord = typeof ProviderReplayNdjsonRecord.Type;