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

main
ts 1,927 lines 75 KB
Raw
1 import type {
2 OrchestrationV2SearchThreadInput,
3 OrchestrationV2SearchThreadResult,
4 } from "@t3tools/contracts";
5 import type {
6 ActiveThreadListEntry,
7 ProjectionRecordField,
8 ProjectionRecordFilter,
9 ProjectionRecords,
10 ShellSnapshotOptions,
11 } from "./ProjectionStore.ts";
12 import {
13 type ChatAttachment,
14 CommandId,
15 isDelegatedAppThread,
16 isListedThreadLineage,
17 MessageId,
18 OrchestrationV2StopWorkflowError,
19 type OrchestrationV2StopWorkflowInput,
20 OrchestrationV2ForceStopThreadError,
21 type OrchestrationV2ForceStopThreadInput,
22 type OrchestrationV2ForceStopThreadResult,
23 type ModelSelection,
24 type OrchestrationV2Actor,
25 type OrchestrationV2Command,
26 type OrchestrationV2GetTurnItemResult,
27 type OrchestrationV2ServerCommand,
28 type OrchestrationV2ConversationMessage,
29 type OrchestrationV2CreationSource,
30 type OrchestrationV2LinkedSender,
31 type OrchestrationV2Run,
32 type OrchestrationV2ThreadShellSnapshot,
33 type OrchestrationV2ThreadProjection,
34 type OrchestrationV2ThreadTranscript,
35 type OrchestrationV2TurnItem,
36 ProjectId,
37 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
38 ProviderInstanceId,
39 type ProviderSessionId,
40 resolveProjectProviderInstanceEnabled,
41 RunId,
42 type ScheduledTaskId,
43 ThreadId,
44 type TurnItemId,
45 } from "@t3tools/contracts";
46 import { delegatedTaskProgress } from "@t3tools/provider-core/server/subagentProjection";
47 import { threadTranscriptHeader } from "@t3tools/shared/threadTranscript";
48 import { AgentScope } from "@t3tools/shared/AgentScope";
49 import * as Clock from "effect/Clock";
50 import * as Context from "effect/Context";
51 import * as DateTime from "effect/DateTime";
52 import * as Duration from "effect/Duration";
53 import * as Effect from "effect/Effect";
54 import * as Fiber from "effect/Fiber";
55 import * as Layer from "effect/Layer";
56 import * as Option from "effect/Option";
57 import * as Ref from "effect/Ref";
58 import * as Result from "effect/Result";
59 import * as Schema from "effect/Schema";
60 import * as Semaphore from "effect/Semaphore";
61 import * as Stream from "effect/Stream";
62
63 import * as CommandReceiptStore from "./CommandReceiptStore.ts";
64 import * as Orchestrator from "./Orchestrator.ts";
65 import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
66 import { projectedRowEncodedBytes } from "./threadHistoryPaging.ts";
67 import { threadPullRequestsOf } from "../sourceControl/threadPullRequests.ts";
68 import * as ProviderSessionManager from "./ProviderSessionManager.ts";
69 import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
70 import { DispatchModeLimit, exceededDispatchModeLimit } from "./DispatchModeLimit.ts";
71 import { projectTurnItemForDetail } from "./WireProjection.ts";
72 import { cancelledBeforeStart } from "./RestartBackgroundNote.ts";
73 import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts";
74 import * as ServerSettings from "../serverSettings.ts";
75 import { ThreadWorktreeRestore } from "../workspace/restoreMissingWorktree.ts";
76 import { checkOutput, outputRequestProblem } from "./runOutput.ts";
77
78 export type ThreadManagementSendMode = "auto" | "queue" | "steer" | "restart";
79
80 export interface ThreadManagementProvenance {
81 readonly createdBy: OrchestrationV2Actor;
82 readonly creationSource: OrchestrationV2CreationSource;
83 }
84
85 export function withCreationProvenance(
86 command: OrchestrationV2Command,
87 provenance: ThreadManagementProvenance,
88 ): OrchestrationV2Command {
89 switch (command.type) {
90 case "thread.create": {
91 // Only the server stamps a link's origin or folds in a first message, so a client cannot.
92 const {
93 linkOrigin: _linkOrigin,
94 delegatedFrom: _delegatedFrom,
95 initialMessage: _initialMessage,
96 ...rest
97 } = command;
98 return { ...rest, ...provenance };
99 }
100 case "message.dispatch":
101 case "thread.fork":
102 case "thread.merge_back":
103 case "delegated_task.request":
104 return { ...command, ...provenance };
105 default:
106 return command;
107 }
108 }
109
110 function existingThreadIdsForCommand(
111 command: OrchestrationV2ServerCommand,
112 ): ReadonlyArray<ThreadId> {
113 switch (command.type) {
114 case "thread.create":
115 return [];
116 // Read-state commands only rewrite the thread payload's visited/unread
117 // watermark and open stats; they never touch messages, so they do not need the imported
118 // v1 transcript hydrated first. Visits fire on every thread-activity bump
119 // while a thread is open, so keeping them off the import path matters.
120 case "thread.visit":
121 case "thread.mark-unread":
122 return [];
123 case "thread.fork":
124 return [command.sourceThreadId];
125 case "thread.merge_back":
126 return command.sourceThreadId === command.targetThreadId
127 ? [command.sourceThreadId]
128 : [command.sourceThreadId, command.targetThreadId];
129 case "delegated_task.request":
130 case "delegated_task.wake-policy":
131 case "delegated_task.completion-delivery.acknowledge":
132 case "delegated_task.completion-delivery.dispose":
133 case "delegated_task.remote.request":
134 case "delegated_task.remote.complete":
135 case "delegated_task.remote.stop":
136 return [command.parentThreadId];
137 case "thread.created.record":
138 return command.parentThreadId === command.targetThreadId
139 ? [command.parentThreadId]
140 : [command.parentThreadId, command.targetThreadId];
141 default:
142 return [command.threadId];
143 }
144 }
145
146 export type ThreadManagementTerminalRunStatus = Extract<
147 OrchestrationV2Run["status"],
148 "completed" | "failed" | "cancelled" | "interrupted" | "rolled_back"
149 >;
150
151 export interface ThreadManagementSendInput {
152 readonly projectId: ProjectId;
153 readonly commandId: CommandId;
154 readonly threadId: ThreadId;
155 readonly messageId: MessageId;
156 readonly scheduledTaskId?: ScheduledTaskId;
157 readonly senderThreadId?: ThreadId;
158 readonly linkedSender?: OrchestrationV2LinkedSender;
159 readonly text: string;
160 readonly attachments: ReadonlyArray<ChatAttachment>;
161 readonly modelSelection?: ModelSelection;
162 readonly mode: ThreadManagementSendMode;
163 /** Start a new provider session; the orchestrator queues it instead of steering. */
164 readonly freshContext?: boolean;
165 /** Ask the run for a result as data matching this JSON Schema; it is queued, never steered. */
166 readonly outputSchema?: Readonly<Record<string, Schema.Json>>;
167 readonly createdBy: OrchestrationV2Actor;
168 readonly creationSource: OrchestrationV2CreationSource;
169 }
170
171 export interface ThreadManagementSendResult {
172 readonly dispatch: Orchestrator.OrchestratorV2DispatchResult;
173 readonly projection: Pick<
174 OrchestrationV2ThreadProjection,
175 "thread" | "runs" | "messages" | "turnItems"
176 >;
177 readonly message: OrchestrationV2ConversationMessage;
178 readonly run: OrchestrationV2Run;
179 readonly turnItem: Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> | null;
180 readonly delivery: "started" | "queued" | "steered" | "restarted";
181 }
182
183 export interface ThreadManagementWaitInput {
184 readonly projectId: ProjectId;
185 readonly threadId: ThreadId;
186 readonly runId?: RunId;
187 readonly timeoutMs: number;
188 /**
189 * Also wait until the thread's own delegated work settles: an ended run
190 * still owes the thread's answer while a child, a background task or a
191 * completion delivery will wake it again, as a delegated task's result does.
192 */
193 readonly untilDelegatedWorkSettled?: boolean;
194 /**
195 * Also wait until the run has the result it was asked for. A turn may end without one while
196 * its agent waits to be woken, and submit it from a later turn.
197 */
198 readonly untilOutput?: boolean;
199 }
200
201 export interface ThreadManagementWaitResult {
202 readonly threadId: ThreadId;
203 readonly run: OrchestrationV2Run | null;
204 readonly timedOut: boolean;
205 /** With `untilDelegatedWorkSettled`, once settled: the run with the thread's final answer. */
206 readonly resultRun?: OrchestrationV2Run;
207 }
208
209 export interface ThreadManagementInterruptInput {
210 readonly projectId: ProjectId;
211 readonly commandId: CommandId;
212 readonly threadId: ThreadId;
213 readonly runId?: RunId;
214 readonly reason?: string;
215 }
216
217 export type ThreadManagementInterruptResult =
218 | {
219 readonly type: "interrupt_requested";
220 readonly run: OrchestrationV2Run;
221 readonly dispatch: Orchestrator.OrchestratorV2DispatchResult;
222 }
223 | { readonly type: "no_active_run" }
224 | {
225 readonly type: "already_terminal";
226 readonly run: OrchestrationV2Run & { readonly status: ThreadManagementTerminalRunStatus };
227 };
228
229 export class ThreadManagementThreadNotFoundError extends Schema.TaggedError<ThreadManagementThreadNotFoundError>()(
230 "ThreadManagementThreadNotFoundError",
231 {
232 projectId: ProjectId,
233 threadId: ThreadId,
234 },
235 ) {
236 override get message(): string {
237 return `Thread ${this.threadId} was not found in project ${this.projectId}.`;
238 }
239 }
240
241 export class ThreadTranscriptTooLargeError extends Schema.TaggedError<ThreadTranscriptTooLargeError>()(
242 "ThreadTranscriptTooLargeError",
243 { threadId: ThreadId },
244 ) {
245 override get message(): string {
246 return "The thread transcript exceeds the file attachment limit.";
247 }
248 }
249
250 export class ThreadManagementRunNotFoundError extends Schema.TaggedError<ThreadManagementRunNotFoundError>()(
251 "ThreadManagementRunNotFoundError",
252 {
253 threadId: ThreadId,
254 runId: RunId,
255 },
256 ) {
257 override get message(): string {
258 return `Run ${this.runId} does not belong to thread ${this.threadId}.`;
259 }
260 }
261
262 export class ThreadManagementThreadArchivedError extends Schema.TaggedError<ThreadManagementThreadArchivedError>()(
263 "ThreadManagementThreadArchivedError",
264 {
265 threadId: ThreadId,
266 },
267 ) {
268 override get message(): string {
269 return `Thread ${this.threadId} is archived and cannot receive messages.`;
270 }
271 }
272
273 export class ThreadManagementNoSteerableRunError extends Schema.TaggedError<ThreadManagementNoSteerableRunError>()(
274 "ThreadManagementNoSteerableRunError",
275 {
276 threadId: ThreadId,
277 mode: Schema.Literals(["steer", "restart"]),
278 },
279 ) {
280 override get message(): string {
281 return `Thread ${this.threadId} has no running turn that can be ${this.mode === "steer" ? "steered" : "restarted"}.`;
282 }
283 }
284
285 export class ThreadManagementRunOutputRejectedError extends Schema.TaggedError<ThreadManagementRunOutputRejectedError>()(
286 "ThreadManagementRunOutputRejectedError",
287 {
288 threadId: ThreadId,
289 /** One of a few fixed sentences. What a submission got wrong is in `cause`. */
290 problem: Schema.String,
291 cause: Schema.optional(Schema.Defect()),
292 },
293 ) {
294 override get message(): string {
295 return this.problem;
296 }
297 }
298
299 export class ThreadManagementThreadNotInterruptibleError extends Schema.TaggedError<ThreadManagementThreadNotInterruptibleError>()(
300 "ThreadManagementThreadNotInterruptibleError",
301 {
302 threadId: ThreadId,
303 runId: RunId,
304 },
305 ) {
306 override get message(): string {
307 return `Run ${this.runId} is not currently interruptible.`;
308 }
309 }
310
311 export class ThreadManagementProjectionLoadError extends Schema.TaggedError<ThreadManagementProjectionLoadError>()(
312 "ThreadManagementProjectionLoadError",
313 {
314 projectId: ProjectId,
315 threadId: ThreadId,
316 cause: Schema.Defect(),
317 },
318 ) {
319 override get message(): string {
320 return `Unable to load thread ${this.threadId} in project ${this.projectId}.`;
321 }
322 }
323
324 export class ThreadManagementProjectThreadsListError extends Schema.TaggedError<ThreadManagementProjectThreadsListError>()(
325 "ThreadManagementProjectThreadsListError",
326 {
327 projectId: Schema.optional(ProjectId),
328 cause: Schema.Defect(),
329 },
330 ) {
331 override get message(): string {
332 return this.projectId === undefined
333 ? "Unable to list threads."
334 : `Unable to list threads in project ${this.projectId}.`;
335 }
336 }
337
338 export class ThreadManagementDurableRunProjectionError extends Schema.TaggedError<ThreadManagementDurableRunProjectionError>()(
339 "ThreadManagementDurableRunProjectionError",
340 {
341 threadId: ThreadId,
342 messageId: MessageId,
343 },
344 ) {
345 override get message(): string {
346 return `Message ${this.messageId} was accepted on thread ${this.threadId} without a durable run projection.`;
347 }
348 }
349
350 export class ThreadManagementWorktreeRestoreError extends Schema.TaggedError<ThreadManagementWorktreeRestoreError>()(
351 "ThreadManagementWorktreeRestoreError",
352 {
353 threadId: ThreadId,
354 cause: Schema.Defect(),
355 },
356 ) {
357 override get message(): string {
358 const detail = this.cause instanceof Error ? ` ${this.cause.message}` : "";
359 return `Couldn't recreate the missing workspace of thread ${this.threadId}, so the message was not sent.${detail}`;
360 }
361 }
362
363 export class ThreadManagementProviderInstanceDisabledError extends Schema.TaggedError<ThreadManagementProviderInstanceDisabledError>()(
364 "ThreadManagementProviderInstanceDisabledError",
365 {
366 projectId: ProjectId,
367 instanceId: ProviderInstanceId,
368 },
369 ) {
370 override get message(): string {
371 return `Provider instance "${this.instanceId}" is disabled for project ${this.projectId}.`;
372 }
373 }
374
375 export class ThreadManagementBackgroundWaitError extends Schema.TaggedError<ThreadManagementBackgroundWaitError>()(
376 "ThreadManagementBackgroundWaitError",
377 {
378 threadId: ThreadId,
379 reason: Schema.Literals(["unsupported", "unavailable", "failed", "unmatched"]),
380 cause: Schema.optional(Schema.Defect()),
381 },
382 ) {
383 override get message(): string {
384 switch (this.reason) {
385 case "unsupported":
386 return "This provider cannot mark background work as awaited.";
387 case "unavailable":
388 return "This thread has no live provider session.";
389 case "failed":
390 return "Failed to update the awaited background work.";
391 case "unmatched":
392 return "None of these IDs is running background work on this thread, so this request registers no wait for them. If the task already finished, read its output now. Otherwise pass the task ID of a background command or Monitor you started. Subagent, Agent tool, and delegate_task IDs don't go here.";
393 }
394 }
395 }
396
397 export const ThreadManagementError = Schema.Union([
398 ThreadManagementThreadNotFoundError,
399 ThreadManagementRunNotFoundError,
400 ThreadManagementThreadArchivedError,
401 ThreadManagementNoSteerableRunError,
402 ThreadManagementRunOutputRejectedError,
403 ThreadManagementThreadNotInterruptibleError,
404 ThreadManagementProjectionLoadError,
405 ThreadManagementProjectThreadsListError,
406 ThreadManagementDurableRunProjectionError,
407 ThreadManagementProviderInstanceDisabledError,
408 ThreadManagementWorktreeRestoreError,
409 ]);
410 export type ThreadManagementError = typeof ThreadManagementError.Type;
411
412 type ThreadManagementFailure = ThreadManagementError | Orchestrator.OrchestratorV2Error;
413
414 export interface ThreadManagementServiceShape {
415 readonly searchThreadStream: (
416 input: OrchestrationV2SearchThreadInput,
417 ) => Stream.Stream<OrchestrationV2SearchThreadResult, Orchestrator.OrchestratorV2Error>;
418 readonly searchThread: (
419 input: OrchestrationV2SearchThreadInput,
420 ) => Effect.Effect<OrchestrationV2SearchThreadResult, Orchestrator.OrchestratorV2Error>;
421 readonly ensureLegacyTranscript: (
422 threadId: ThreadId,
423 ) => Effect.Effect<void, LegacyV1ThreadImporter.LegacyV1ThreadImportError>;
424 readonly dispatch: (
425 command: OrchestrationV2ServerCommand,
426 ) => Effect.Effect<
427 Orchestrator.OrchestratorV2DispatchResult,
428 Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
429 >;
430 readonly getThreadHistoryPage: Orchestrator.OrchestratorV2["Service"]["getThreadHistoryPage"];
431 readonly getTimelinePage: Orchestrator.OrchestratorV2["Service"]["getTimelinePage"];
432 readonly getMessageCount: Orchestrator.OrchestratorV2["Service"]["getMessageCount"];
433 readonly getRunCount: Orchestrator.OrchestratorV2["Service"]["getRunCount"];
434 readonly getMessagesById: Orchestrator.OrchestratorV2["Service"]["getMessagesById"];
435 readonly getTurnItem: (input: {
436 readonly threadId: ThreadId;
437 readonly itemId: TurnItemId;
438 }) => Effect.Effect<OrchestrationV2GetTurnItemResult, Orchestrator.OrchestratorV2Error>;
439 readonly getThreadRecords: Orchestrator.OrchestratorV2["Service"]["getThreadRecords"];
440 readonly getThreadProjection: (
441 threadId: ThreadId,
442 ) => Effect.Effect<OrchestrationV2ThreadProjection, Orchestrator.OrchestratorV2Error>;
443 readonly getCheckpointContext: Orchestrator.OrchestratorV2["Service"]["getCheckpointContext"];
444 readonly getThreadSnapshot: Orchestrator.OrchestratorV2["Service"]["getThreadSnapshot"];
445 readonly getThreadTranscript: (
446 threadId: ThreadId,
447 ) => Effect.Effect<
448 OrchestrationV2ThreadTranscript,
449 Orchestrator.OrchestratorV2Error | ThreadTranscriptTooLargeError,
450 ServerEnvironment.ServerEnvironmentIdentity
451 >;
452 readonly getThreadSnapshotWindow: Orchestrator.OrchestratorV2["Service"]["getThreadSnapshotWindow"];
453 readonly getProjectThreadRecords: <K extends ProjectionRecordField>(
454 input: { readonly projectId: ProjectId; readonly threadId: ThreadId },
455 fields: ReadonlyArray<K>,
456 filter?: ProjectionRecordFilter,
457 ) => Effect.Effect<
458 ProjectionRecords<K>,
459 ThreadManagementProjectionLoadError | ThreadManagementThreadNotFoundError
460 >;
461 readonly getAgentAwarenessSnapshot: Orchestrator.OrchestratorV2["Service"]["getAgentAwarenessSnapshot"];
462 readonly getShellSnapshot: (
463 options?: Pick<
464 ShellSnapshotOptions,
465 "location" | "projectId" | "unsettledOnly" | "worktreePath" | "threadIds"
466 >,
467 ) => Effect.Effect<OrchestrationV2ThreadShellSnapshot, Orchestrator.OrchestratorV2Error>;
468 readonly listActiveSubagentThreadIds: Orchestrator.OrchestratorV2["Service"]["listActiveSubagentThreadIds"];
469 readonly countThreads: Orchestrator.OrchestratorV2["Service"]["countThreads"];
470 readonly listActiveShellIndex: Orchestrator.OrchestratorV2["Service"]["listActiveShellIndex"];
471 readonly listOlderSettledThreads: Orchestrator.OrchestratorV2["Service"]["listOlderSettledThreads"];
472 readonly readShellSnapshot: (
473 options?: Pick<ShellSnapshotOptions, "location" | "familyOf" | "worktreePath" | "threadIds">,
474 ) => Effect.Effect<
475 Effect.Effect<OrchestrationV2ThreadShellSnapshot, Orchestrator.OrchestratorV2Error>,
476 Orchestrator.OrchestratorV2Error
477 >;
478 readonly getThreadShell: Orchestrator.OrchestratorV2["Service"]["getThreadShell"];
479 readonly listAppOwnedChildThreadIds: Orchestrator.OrchestratorV2["Service"]["listAppOwnedChildThreadIds"];
480 readonly getThreadLinkMetadata: Orchestrator.OrchestratorV2["Service"]["getThreadLinkMetadata"];
481 readonly getThreadTitles: Orchestrator.OrchestratorV2["Service"]["getThreadTitles"];
482 /** Omit `projectId` to list every project's threads. Side chats are never listed. */
483 readonly listProjectThreads: (input: {
484 readonly projectId?: ProjectId | undefined;
485 readonly includeSubagents: boolean;
486 }) => Effect.Effect<ReadonlyArray<ActiveThreadListEntry>, ThreadManagementError>;
487 readonly sendToThread: (
488 input: ThreadManagementSendInput,
489 ) => Effect.Effect<ThreadManagementSendResult, ThreadManagementFailure>;
490 /** Stores what the thread's running turn returns, once it fits the schema that turn declared. */
491 readonly submitRunOutput: (input: {
492 readonly threadId: ThreadId;
493 readonly commandId: CommandId;
494 readonly json: string;
495 }) => Effect.Effect<{ readonly runId: RunId }, ThreadManagementFailure>;
496 readonly assertProviderInstanceEnabled: (input: {
497 readonly projectId: ProjectId;
498 readonly commandId: CommandId;
499 readonly instanceId: ProviderInstanceId;
500 }) => Effect.Effect<void, ThreadManagementProviderInstanceDisabledError>;
501 readonly isProviderInstanceEnabledForProject: (input: {
502 readonly projectId: ProjectId;
503 readonly instanceId: ProviderInstanceId;
504 }) => Effect.Effect<boolean>;
505 /** Receipt replays start no work; skip enablement checks with the same command id so settings cannot reject accepted retries. */
506 readonly hasReceipt: (commandId: CommandId) => Effect.Effect<boolean>;
507 readonly waitForThread: (
508 input: ThreadManagementWaitInput,
509 ) => Effect.Effect<ThreadManagementWaitResult, ThreadManagementError>;
510 /** Waits for the agent's run and automatic follow-ups before settling.
511 * A new user turn or an unsuccessful ending leaves the thread active. */
512 readonly settleAfterRun: (input: {
513 readonly projectId: ProjectId;
514 readonly threadId: ThreadId;
515 readonly runId: RunId;
516 }) => Effect.Effect<void, ThreadManagementFailure>;
517 readonly settleThread: (input: {
518 readonly threadId: ThreadId;
519 readonly commandId: CommandId;
520 readonly byOwnAgent: boolean;
521 }) => Effect.Effect<
522 { readonly sequence: number } | { readonly settlesWhenTurnEnds: true },
523 Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
524 >;
525 readonly interruptThread: (
526 input: ThreadManagementInterruptInput,
527 ) => Effect.Effect<ThreadManagementInterruptResult, ThreadManagementFailure>;
528 readonly stopWorkflow: (
529 input: OrchestrationV2StopWorkflowInput,
530 ) => Effect.Effect<void, OrchestrationV2StopWorkflowError>;
531 /**
532 * Kills the thread's agent for a provider that no longer responds, then ends
533 * its turn as interrupted. Never kills a process other working threads share.
534 */
535 readonly forceStopThread: (
536 input: OrchestrationV2ForceStopThreadInput,
537 ) => Effect.Effect<OrchestrationV2ForceStopThreadResult, OrchestrationV2ForceStopThreadError>;
538 readonly awaitBackgroundTasks: (input: {
539 readonly threadId: ThreadId;
540 readonly taskIds: ReadonlyArray<string>;
541 readonly awaited: boolean;
542 }) => Effect.Effect<
543 { readonly matched: ReadonlyArray<string>; readonly unmatched: ReadonlyArray<string> },
544 ThreadManagementBackgroundWaitError
545 >;
546 readonly stopDelegatedTasks: (input: {
547 readonly remoteDispatch?: Orchestrator.OrchestratorV2["Service"]["dispatch"];
548 readonly threadId: ThreadId;
549 readonly commandId: CommandId;
550 readonly reason?: string | undefined;
551 }) => Effect.Effect<
552 void,
553 Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
554 >;
555 readonly getThreadEventSequence: Orchestrator.OrchestratorV2["Service"]["getThreadEventSequence"];
556 readonly recoverDelegatedTask: Orchestrator.OrchestratorV2["Service"]["recoverDelegatedTask"];
557 readonly cancelDelegatedTask: Orchestrator.OrchestratorV2["Service"]["cancelDelegatedTask"];
558 readonly delegatedTaskResultPending: Orchestrator.OrchestratorV2["Service"]["delegatedTaskResultPending"];
559 readonly streamStoredEvents: Orchestrator.OrchestratorV2["Service"]["streamStoredEvents"];
560 readonly streamStoredEventsFrom: Orchestrator.OrchestratorV2["Service"]["streamStoredEventsFrom"];
561 readonly streamDomainEvents: Orchestrator.OrchestratorV2["Service"]["streamDomainEvents"];
562 }
563
564 export class ThreadManagementService extends Context.Service<
565 ThreadManagementService,
566 ThreadManagementServiceShape
567 >()("t3/orchestration-v2/ThreadManagementService") {}
568
569 export const ACTIVE_RUN_STATUSES = [
570 "preparing",
571 "starting",
572 "running",
573 "waiting",
574 ] as const satisfies ReadonlyArray<OrchestrationV2Run["status"]>;
575
576 export function isActiveRun(run: OrchestrationV2Run): boolean {
577 return (ACTIVE_RUN_STATUSES as ReadonlyArray<OrchestrationV2Run["status"]>).includes(run.status);
578 }
579
580 export function isTerminalRunStatus(
581 status: OrchestrationV2Run["status"],
582 ): status is ThreadManagementTerminalRunStatus {
583 return (
584 status === "completed" ||
585 status === "failed" ||
586 status === "cancelled" ||
587 status === "interrupted" ||
588 status === "rolled_back"
589 );
590 }
591
592 export function latestRun(
593 projection: Pick<OrchestrationV2ThreadProjection, "runs">,
594 ): OrchestrationV2Run | undefined {
595 return projection.runs.toSorted((left, right) => right.ordinal - left.ordinal)[0];
596 }
597
598 function latestRestartContinuation(
599 runs: ReadonlyArray<OrchestrationV2Run>,
600 run: OrchestrationV2Run,
601 ): OrchestrationV2Run {
602 let current = run;
603 for (let hops = 0; hops < runs.length; hops++) {
604 const next = runs.find((candidate) => candidate.restartContinuationOfRunId === current.id);
605 if (next === undefined) break;
606 current = next;
607 }
608 return current;
609 }
610
611 export function latestActiveRun(
612 projection: Pick<OrchestrationV2ThreadProjection, "runs">,
613 ): OrchestrationV2Run | undefined {
614 return projection.runs
615 .filter(isActiveRun)
616 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
617 }
618
619 function latestSteerableRun(
620 projection: Pick<OrchestrationV2ThreadProjection, "runs" | "providerTurns">,
621 ): OrchestrationV2Run | undefined {
622 return projection.runs
623 .filter(
624 (run) =>
625 run.status === "running" &&
626 run.activeAttemptId !== null &&
627 projection.providerTurns.some(
628 (turn) => turn.runAttemptId === run.activeAttemptId && turn.status === "running",
629 ),
630 )
631 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
632 }
633
634 const SETTLE_AFTER_RUN_WAIT_MS = 24 * 60 * 60 * 1_000;
635 const FORCE_STOP_REASON = "Force stopped by user";
636 const FORCE_STOP_RELEASE_WAIT = "10 seconds";
637 const isForceStopThreadError = Schema.is(OrchestrationV2ForceStopThreadError);
638
639 const make = Effect.gen(function* () {
640 const threadDispatch = yield* ThreadCommandExecutor.ThreadCommandExecutor;
641 const orchestrator = yield* Orchestrator.OrchestratorV2;
642 const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
643 const layerScope = yield* Effect.scope;
644 const agentScope = yield* AgentScope;
645 const legacyImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
646 const serverSettings = yield* ServerSettings.ServerSettingsService;
647 const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
648 const worktreeRestore = yield* ThreadWorktreeRestore;
649
650 const assertProviderInstanceEnabled: ThreadManagementServiceShape["assertProviderInstanceEnabled"] =
651 (input) =>
652 receipts.getByCommandId(input.commandId).pipe(
653 Effect.orElseSucceed(() => Option.none()),
654 Effect.flatMap((receipt) =>
655 Option.isSome(receipt)
656 ? Effect.void
657 : serverSettings.getSettings.pipe(
658 Effect.orDie,
659 Effect.flatMap((current) =>
660 resolveProjectProviderInstanceEnabled(current, input.projectId, input.instanceId)
661 ? Effect.void
662 : new ThreadManagementProviderInstanceDisabledError({
663 projectId: input.projectId,
664 instanceId: input.instanceId,
665 }),
666 ),
667 ),
668 ),
669 );
670
671 const isProviderInstanceEnabledForProject: ThreadManagementServiceShape["isProviderInstanceEnabledForProject"] =
672 (input) =>
673 serverSettings.getSettings.pipe(
674 Effect.orDie,
675 Effect.map((current) =>
676 resolveProjectProviderInstanceEnabled(current, input.projectId, input.instanceId),
677 ),
678 );
679
680 const hasReceipt: ThreadManagementServiceShape["hasReceipt"] = (commandId) =>
681 receipts.getByCommandId(commandId).pipe(
682 Effect.orElseSucceed(() => Option.none()),
683 Effect.map(Option.isSome),
684 );
685
686 const ensureLegacyTranscript = Effect.fn(
687 "orchestrationV2.threadManagement.ensureLegacyTranscript",
688 )(function* (threadId: ThreadId) {
689 yield* legacyImporter.ensureTranscript(threadId).pipe(
690 Effect.tapError((cause) =>
691 Effect.logWarning("Unable to hydrate migrated v1 thread transcript", {
692 threadId,
693 cause,
694 }),
695 ),
696 );
697 });
698
699 const ensureProjectionTranscript = (threadId: ThreadId) =>
700 ensureLegacyTranscript(threadId).pipe(
701 Effect.mapError(
702 (cause) =>
703 new Orchestrator.OrchestratorProjectionError({
704 threadId,
705 cause,
706 }),
707 ),
708 );
709
710 const ensureCommandTranscripts = Effect.fn(
711 "orchestrationV2.threadManagement.ensureCommandTranscripts",
712 )(function* (command: OrchestrationV2ServerCommand) {
713 yield* Effect.forEach(
714 existingThreadIdsForCommand(command),
715 (threadId) => ensureLegacyTranscript(threadId),
716 { discard: true },
717 ).pipe(
718 Effect.mapError(
719 (cause) =>
720 new Orchestrator.OrchestratorDispatchError({
721 commandId: command.commandId,
722 commandType: command.type,
723 cause,
724 }),
725 ),
726 );
727 });
728
729 const getThreadProjection: ThreadManagementServiceShape["getThreadProjection"] = (threadId) =>
730 ensureProjectionTranscript(threadId).pipe(
731 Effect.andThen(orchestrator.getThreadProjection(threadId)),
732 );
733
734 const getCheckpointContext: ThreadManagementServiceShape["getCheckpointContext"] = (threadId) =>
735 ensureProjectionTranscript(threadId).pipe(
736 Effect.andThen(orchestrator.getCheckpointContext(threadId)),
737 );
738
739 const getThreadSnapshot: ThreadManagementServiceShape["getThreadSnapshot"] = (threadId) =>
740 ensureProjectionTranscript(threadId).pipe(
741 Effect.andThen(orchestrator.getThreadSnapshot(threadId)),
742 );
743 // Full-thread exports can otherwise hold every SQLite reader and stall ordinary thread opens.
744 const transcriptExportPermits = yield* Semaphore.make(2);
745 const getThreadTranscript = Effect.fn("orchestrationV2.threadManagement.getThreadTranscript")(
746 function* (threadId: ThreadId) {
747 yield* ensureProjectionTranscript(threadId);
748 const byteFloor = yield* orchestrator.getTranscriptByteFloor(
749 threadId,
750 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
751 );
752 if (byteFloor > PROVIDER_SEND_TURN_MAX_FILE_BYTES) {
753 return yield* new ThreadTranscriptTooLargeError({ threadId });
754 }
755 const { projection } = yield* orchestrator.getThreadSnapshot(threadId);
756 const environment = yield* ServerEnvironment.ServerEnvironmentIdentity;
757 const transcript = {
758 threadId: projection.thread.id,
759 title: projection.thread.title,
760 updatedAt: projection.updatedAt,
761 items: projection.visibleTurnItems,
762 };
763 let sizeBytes = Buffer.byteLength(
764 threadTranscriptHeader(yield* environment.getEnvironmentId, transcript),
765 "utf8",
766 );
767 if (sizeBytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) {
768 return yield* new ThreadTranscriptTooLargeError({ threadId });
769 }
770 for (const row of transcript.items) {
771 sizeBytes += projectedRowEncodedBytes(row) + 1;
772 if (sizeBytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) {
773 return yield* new ThreadTranscriptTooLargeError({ threadId });
774 }
775 }
776 return transcript;
777 },
778 transcriptExportPermits.withPermits(1),
779 );
780 const getThreadSnapshotWindow: ThreadManagementServiceShape["getThreadSnapshotWindow"] = (
781 threadId,
782 options,
783 ) =>
784 ensureProjectionTranscript(threadId).pipe(
785 Effect.andThen(orchestrator.getThreadSnapshotWindow(threadId, options)),
786 );
787
788 const assertDispatchTargetEnabled = (command: OrchestrationV2ServerCommand) => {
789 switch (command.type) {
790 case "thread.metadata.update":
791 return command.continuation === undefined
792 ? Effect.void
793 : orchestrator.getThreadRecords(command.threadId, []).pipe(
794 Effect.flatMap((projection) =>
795 assertProviderInstanceEnabled({
796 projectId: projection.thread.projectId,
797 commandId: command.commandId,
798 instanceId: projection.thread.modelSelection.instanceId,
799 }),
800 ),
801 );
802 case "message.dispatch":
803 return orchestrator.getThreadRecords(command.threadId, []).pipe(
804 Effect.flatMap((projection) =>
805 assertProviderInstanceEnabled({
806 projectId: projection.thread.projectId,
807 commandId: command.commandId,
808 instanceId: (command.modelSelection ?? projection.thread.modelSelection).instanceId,
809 }),
810 ),
811 );
812 case "delegated_task.request":
813 return orchestrator.getThreadRecords(command.parentThreadId, []).pipe(
814 Effect.flatMap((parent) =>
815 assertProviderInstanceEnabled({
816 projectId: parent.thread.projectId,
817 commandId: command.commandId,
818 instanceId: command.modelSelection.instanceId,
819 }),
820 ),
821 );
822 case "prepared-run.release":
823 case "prepared-run.retry":
824 return orchestrator
825 .getThreadRecords(command.threadId, ["runs"], { runIds: [command.runId] })
826 .pipe(
827 Effect.flatMap((projection) => {
828 const run = projection.runs.find((candidate) => candidate.id === command.runId);
829 return run === undefined
830 ? Effect.void
831 : assertProviderInstanceEnabled({
832 projectId: projection.thread.projectId,
833 commandId: command.commandId,
834 instanceId: run.providerInstanceId,
835 });
836 }),
837 );
838 default:
839 return Effect.void;
840 }
841 };
842
843 const dispatch: ThreadManagementServiceShape["dispatch"] = (command) =>
844 ensureCommandTranscripts(command).pipe(
845 Effect.andThen(assertDispatchTargetEnabled(command)),
846 Effect.andThen(orchestrator.dispatch(command)),
847 );
848
849 const getProjectThreadRecords: ThreadManagementServiceShape["getProjectThreadRecords"] = (
850 input,
851 fields,
852 filter,
853 ) =>
854 ensureProjectionTranscript(input.threadId).pipe(
855 Effect.andThen(orchestrator.getThreadRecords(input.threadId, fields, filter)),
856 Effect.mapError(
857 (cause) =>
858 new ThreadManagementProjectionLoadError({
859 projectId: input.projectId,
860 threadId: input.threadId,
861 cause,
862 }),
863 ),
864 Effect.filterOrFail(
865 (projection) =>
866 projection.thread.projectId === input.projectId && projection.thread.deletedAt === null,
867 (_projection) =>
868 new ThreadManagementThreadNotFoundError({
869 projectId: input.projectId,
870 threadId: input.threadId,
871 }),
872 ),
873 );
874
875 const listProjectThreads: ThreadManagementServiceShape["listProjectThreads"] = (input) =>
876 orchestrator.listActiveThreads(input.projectId).pipe(
877 Effect.mapError(
878 (cause) =>
879 new ThreadManagementProjectThreadsListError({
880 projectId: input.projectId,
881 cause,
882 }),
883 ),
884 Effect.map((threads) =>
885 threads
886 .filter((thread) =>
887 input.includeSubagents
888 ? thread.lineage.sideChat !== true
889 : isListedThreadLineage(thread.lineage) && !isDelegatedAppThread(thread),
890 )
891 .toSorted(
892 (left, right) =>
893 DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt) ||
894 right.id.localeCompare(left.id),
895 ),
896 ),
897 );
898
899 const sendToThread: ThreadManagementServiceShape["sendToThread"] = Effect.fn(
900 "ThreadManagementService.sendToThread",
901 )(function* (input) {
902 const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
903 if (target.thread.archivedAt !== null) {
904 return yield* new ThreadManagementThreadArchivedError({
905 threadId: input.threadId,
906 });
907 }
908 const schemaProblem =
909 input.outputSchema === undefined ? null : outputRequestProblem(input.outputSchema, input);
910 if (schemaProblem !== null) {
911 return yield* new ThreadManagementRunOutputRejectedError({
912 threadId: input.threadId,
913 problem: schemaProblem,
914 });
915 }
916 const steerableRun = latestSteerableRun(target);
917 // A fresh send, or one that asks for a result, never joins a running turn.
918 const mode =
919 (input.freshContext || input.outputSchema !== undefined) &&
920 (input.mode === "steer" || input.mode === "restart")
921 ? "queue"
922 : input.mode;
923 const explicitSteer = mode === "steer" || mode === "restart";
924 const missingSteeringTarget = explicitSteer && steerableRun === undefined;
925 // A command receipt outlives its target turn. Dispatch validates and replays it.
926 if (missingSteeringTarget && !(yield* hasReceipt(input.commandId))) {
927 return yield* new ThreadManagementNoSteerableRunError({
928 threadId: input.threadId,
929 mode,
930 });
931 }
932
933 let dispatchMode: Extract<
934 OrchestrationV2Command,
935 { readonly type: "message.dispatch" }
936 >["dispatchMode"];
937 if ((explicitSteer || mode === "auto") && steerableRun !== undefined) {
938 dispatchMode = {
939 type: mode === "restart" ? "restart_active" : "steer_active",
940 targetRunId: steerableRun.id,
941 };
942 } else {
943 dispatchMode = {
944 type: mode === "queue" ? "queue_after_active" : "start_immediately",
945 };
946 }
947
948 // Turn start would fail on its own after the send reported success; a replay keeps its answer.
949 // A live steer and a receipt replay without a target turn need no workspace.
950 if (!missingSteeringTarget && dispatchMode.type !== "steer_active") {
951 yield* worktreeRestore
952 .restore(target.thread)
953 .pipe(
954 Effect.catch((cause) =>
955 hasReceipt(input.commandId).pipe(
956 Effect.flatMap((replay) =>
957 replay
958 ? Effect.void
959 : Effect.fail(
960 new ThreadManagementWorktreeRestoreError({ threadId: input.threadId, cause }),
961 ),
962 ),
963 ),
964 ),
965 );
966 }
967
968 const dispatched = yield* dispatch({
969 type: "message.dispatch",
970 commandId: input.commandId,
971 threadId: input.threadId,
972 messageId: input.messageId,
973 ...(input.scheduledTaskId === undefined ? {} : { scheduledTaskId: input.scheduledTaskId }),
974 ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
975 ...(input.linkedSender === undefined ? {} : { linkedSender: input.linkedSender }),
976 text: input.text,
977 attachments: input.attachments,
978 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
979 ...(input.freshContext ? { freshContext: true } : {}),
980 ...(input.outputSchema === undefined ? {} : { outputSchema: input.outputSchema }),
981 dispatchMode,
982 ...(mode === "auto" ? { deliveryIntent: "auto" } : {}),
983 createdBy: input.createdBy,
984 creationSource: input.creationSource,
985 });
986 const projection = yield* getProjectThreadRecords(input, ["runs", "messages", "turnItems"], {
987 messageIds: [input.messageId],
988 turnItemTypes: ["user_message"],
989 });
990 const message = projection.messages.find((candidate) => candidate.id === input.messageId);
991 const run =
992 message?.runId === null || message?.runId === undefined
993 ? undefined
994 : projection.runs.find((candidate) => candidate.id === message.runId);
995 const turnItem =
996 projection.turnItems.find(
997 (
998 candidate,
999 ): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> =>
1000 candidate.type === "user_message" && candidate.messageId === input.messageId,
1001 ) ?? null;
1002 if (
1003 message === undefined ||
1004 run === undefined ||
1005 (turnItem === null && run.status !== "queued")
1006 ) {
1007 return yield* new ThreadManagementDurableRunProjectionError({
1008 threadId: input.threadId,
1009 messageId: input.messageId,
1010 });
1011 }
1012 // A provider without interrupt-and-restart stops the turn and runs the
1013 // restart as the next turn. Read from this command's own events, so a replay agrees.
1014 const restartedAsNextTurn =
1015 mode === "restart" &&
1016 dispatched.storedEvents.some(
1017 ({ event }) =>
1018 event.type === "turn-item.updated" &&
1019 event.payload.type === "run_interrupt_request" &&
1020 event.payload.runId !== run.id,
1021 );
1022 const delivery: ThreadManagementSendResult["delivery"] = restartedAsNextTurn
1023 ? "restarted"
1024 : turnItem === null || turnItem.inputIntent === "queued_turn"
1025 ? "queued"
1026 : turnItem.inputIntent === "turn_start"
1027 ? "started"
1028 : mode === "restart"
1029 ? "restarted"
1030 : "steered";
1031 return { dispatch: dispatched, projection, message, run, turnItem, delivery };
1032 });
1033
1034 const submitRunOutput: ThreadManagementServiceShape["submitRunOutput"] = Effect.fn(
1035 "ThreadManagementService.submitRunOutput",
1036 )(function* (input) {
1037 const records = yield* orchestrator.getThreadRecords(input.threadId, ["runs"]);
1038 const active = latestActiveRun(records);
1039 // A turn that ended without its result still owes it: the agent may have ended it to wait
1040 // for something, and answer from the turn that woke it.
1041 // Only an ended turn can owe one; a queued or running turn asked for one answers for itself.
1042 const owed = records.runs
1043 .filter(
1044 (candidate) =>
1045 candidate.outputSchema !== undefined &&
1046 candidate.output === undefined &&
1047 candidate.status === "completed",
1048 )
1049 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
1050 const run = active?.outputSchema !== undefined ? active : owed;
1051 if (active === undefined || run?.outputSchema === undefined) {
1052 return yield* new ThreadManagementRunOutputRejectedError({
1053 threadId: input.threadId,
1054 problem: "This turn was not asked for a result. Reply in your message instead.",
1055 });
1056 }
1057 const checked = yield* checkOutput(run.outputSchema, input.json);
1058 if (Result.isFailure(checked)) {
1059 return yield* new ThreadManagementRunOutputRejectedError({
1060 threadId: input.threadId,
1061 problem: checked.failure.problem,
1062 ...(checked.failure.cause === undefined ? {} : { cause: checked.failure.cause }),
1063 });
1064 }
1065 yield* dispatch({
1066 type: "run.output.submit",
1067 commandId: input.commandId,
1068 threadId: input.threadId,
1069 runId: run.id,
1070 value: checked.success,
1071 });
1072 return { runId: run.id };
1073 });
1074
1075 const waitForThread: ThreadManagementServiceShape["waitForThread"] = Effect.fn(
1076 "ThreadManagementService.waitForThread",
1077 )(function* (input) {
1078 const loadError = (cause: unknown) =>
1079 new ThreadManagementProjectionLoadError({
1080 projectId: input.projectId,
1081 threadId: input.threadId,
1082 cause,
1083 });
1084 // Taken before the first read, so a run update between that read and
1085 // the subscription below still replays.
1086 const afterSequence = yield* orchestrator
1087 .getThreadEventSequence(input.threadId)
1088 .pipe(Effect.mapError(loadError));
1089 const target = yield* getProjectThreadRecords(input, ["runs"]);
1090 const selectedRun =
1091 input.runId === undefined
1092 ? latestRun(target)
1093 : target.runs.find((candidate) => candidate.id === input.runId);
1094 if (input.runId !== undefined && selectedRun === undefined) {
1095 return yield* new ThreadManagementRunNotFoundError({
1096 threadId: input.threadId,
1097 runId: input.runId,
1098 });
1099 }
1100 if (selectedRun === undefined) {
1101 return { threadId: input.threadId, run: null, timedOut: false };
1102 }
1103 // A restart cuts a run and continues it as a new run. Follow that chain,
1104 // so a cut run is not the answer while its continuation is pending.
1105 // Runs per matching event and is already covered by the waitForThread span.
1106 const outcome = Effect.fnUntraced(function* (runs: ReadonlyArray<OrchestrationV2Run>) {
1107 const current = runs.find((candidate) => candidate.id === selectedRun.id);
1108 if (current === undefined) {
1109 return yield* new ThreadManagementRunNotFoundError({
1110 threadId: input.threadId,
1111 runId: selectedRun.id,
1112 });
1113 }
1114 const run = latestRestartContinuation(runs, current);
1115 const pending =
1116 isTerminalRunStatus(run.status) && (yield* orchestrator.restartContinuationPending(run));
1117 const owesOutput =
1118 input.untilOutput === true && run.status === "completed" && run.output === undefined;
1119 return { run, pending, settled: isTerminalRunStatus(run.status) && !pending && !owesOutput };
1120 });
1121 const untilDelegatedWorkSettled = input.untilDelegatedWorkSettled === true;
1122 const delegatedWorkResult = Effect.gen(function* () {
1123 const records = yield* getProjectThreadRecords(
1124 input,
1125 ["runs", "messages", "subagents", "providerThreads"],
1126 { messageRoles: ["user"], monitorNotificationsOnly: true },
1127 );
1128 const progress = delegatedTaskProgress(records);
1129 // A thread rolled back past all its work, with nothing left running, has no answer to wait for.
1130 if (
1131 progress.resultRun === undefined &&
1132 records.runs.every((run) => isTerminalRunStatus(run.status))
1133 ) {
1134 return latestRun(records);
1135 }
1136 if (progress.state !== "result_available") return undefined;
1137 const pending = yield* orchestrator
1138 .delegatedTaskResultPending(input.threadId)
1139 .pipe(Effect.mapError(loadError));
1140 return pending ? undefined : progress.resultRun;
1141 });
1142 const evaluate = Effect.fn("orchestrationV2.threadManagement.evaluate")(function* (
1143 runs: ReadonlyArray<OrchestrationV2Run>,
1144 ) {
1145 const current = yield* outcome(runs);
1146 if (!current.settled || !untilDelegatedWorkSettled) {
1147 return { ...current, resultRun: undefined };
1148 }
1149 const resultRun = yield* delegatedWorkResult;
1150 return { ...current, settled: resultRun !== undefined, resultRun };
1151 });
1152 const settledResult = (current: Effect.Success<ReturnType<typeof evaluate>>) => ({
1153 threadId: input.threadId,
1154 run: current.run,
1155 timedOut: !current.settled,
1156 ...(current.resultRun === undefined ? {} : { resultRun: current.resultRun }),
1157 });
1158 const initial = yield* evaluate(target.runs);
1159 if (initial.settled) return settledResult(initial);
1160
1161 // A declined continuation records no event, so its effect settling wakes
1162 // the wait too.
1163 const wait = Stream.merge(
1164 Stream.mergeAll(
1165 (
1166 [
1167 "run.updated",
1168 "thread.deleted",
1169 ...(input.untilOutput === true ? (["run.output-submitted"] as const) : []),
1170 // What delegated work reads besides runs: tasks and their
1171 // deliveries, and a provider thread's background tasks.
1172 ...(untilDelegatedWorkSettled
1173 ? (["subagent.updated", "provider-thread.updated"] as const)
1174 : []),
1175 ] as const
1176 ).map((eventType) =>
1177 orchestrator.streamStoredEventsFrom({
1178 threadId: input.threadId,
1179 afterSequence,
1180 eventType,
1181 }),
1182 ),
1183 { concurrency: "unbounded" },
1184 ).pipe(
1185 Stream.mapError(loadError),
1186 Stream.filter(
1187 (stored) =>
1188 untilDelegatedWorkSettled ||
1189 stored.event.type !== "run.updated" ||
1190 stored.event.payload.id === selectedRun.id ||
1191 stored.event.payload.restartContinuationOfRunId !== undefined,
1192 ),
1193 ),
1194 initial.pending
1195 ? Stream.fromEffect(orchestrator.awaitRestartContinuation(initial.run))
1196 : Stream.empty,
1197 ).pipe(
1198 Stream.mapEffect(() =>
1199 getProjectThreadRecords(input, ["runs"]).pipe(
1200 Effect.flatMap((current) => evaluate(current.runs)),
1201 ),
1202 ),
1203 Stream.filter((current) => current.settled),
1204 Stream.runHead,
1205 Effect.timeoutOption(Duration.millis(Math.max(1, input.timeoutMs))),
1206 );
1207 const waited = Option.flatten(yield* wait);
1208 if (Option.isSome(waited)) return settledResult(waited.value);
1209 // The run may have reached a terminal status while the timeout was
1210 // winning the race; the final projection read decides what actually
1211 // happened, so only a still-active run counts as timed out.
1212 return settledResult(yield* evaluate((yield* getProjectThreadRecords(input, ["runs"])).runs));
1213 });
1214
1215 const settleAfterRun: ThreadManagementServiceShape["settleAfterRun"] = Effect.fn(
1216 "orchestrationV2.threadManagement.settleAfterRun",
1217 )(function* (input) {
1218 const requestedAt = yield* DateTime.now;
1219 const { run } = yield* waitForThread({ ...input, timeoutMs: SETTLE_AFTER_RUN_WAIT_MS });
1220 if (run?.status !== "completed") return;
1221 const afterSequence = yield* orchestrator.getThreadEventSequence(input.threadId);
1222 const trySettle = Effect.gen(function* () {
1223 const sequence = yield* orchestrator.getThreadEventSequence(input.threadId);
1224 const records = yield* getProjectThreadRecords(input, ["runs"]);
1225 // Settling ends every watch; one the agent started after asking to settle must outlive it.
1226 if (
1227 threadPullRequestsOf(records.thread).some(
1228 (link) =>
1229 link.watch !== undefined &&
1230 !DateTime.isLessThan(DateTime.makeUnsafe(link.watch.startedAt), requestedAt),
1231 )
1232 )
1233 return true;
1234 const later = records.runs.filter((candidate) => candidate.ordinal > run.ordinal);
1235 const cancelledMessageIds = later
1236 .filter((candidate) => candidate.status === "cancelled")
1237 .map((candidate) => candidate.userMessageId);
1238 // Send now cancels a queued run and moves its message into the running turn.
1239 const steeredMessageIds =
1240 cancelledMessageIds.length === 0
1241 ? new Set()
1242 : new Set(
1243 (yield* getProjectThreadRecords(input, ["messages"], {
1244 messageIds: cancelledMessageIds,
1245 })).messages
1246 .filter((message) => message.runId === run.id)
1247 .map((message) => message.id),
1248 );
1249 const following = later.filter(
1250 (candidate) =>
1251 candidate.status !== "cancelled" || !steeredMessageIds.has(candidate.userMessageId),
1252 );
1253 if (following.length > 0) {
1254 const { messages } = yield* getProjectThreadRecords(input, ["messages"], {
1255 messageRunIds: following.map((candidate) => candidate.id),
1256 messageRoles: ["user"],
1257 });
1258 const automaticMessageIds = new Set(
1259 messages
1260 .filter(
1261 (message) =>
1262 message.role === "user" &&
1263 (message.notification !== undefined || message.delegatedCompletion !== undefined),
1264 )
1265 .map((message) => message.id),
1266 );
1267 if (
1268 messages.some((message) => !automaticMessageIds.has(message.id)) ||
1269 following.some((candidate) => !automaticMessageIds.has(candidate.userMessageId))
1270 ) {
1271 return true;
1272 }
1273 if (
1274 following.some(
1275 (candidate) => candidate.status !== "queued" && !isTerminalRunStatus(candidate.status),
1276 )
1277 )
1278 return false;
1279 // A wake cancelled before it started (its result was already read in-turn) did nothing.
1280 if (
1281 following.some(
1282 (candidate) =>
1283 candidate.status !== "queued" &&
1284 candidate.status !== "completed" &&
1285 !cancelledBeforeStart(candidate),
1286 )
1287 )
1288 return true;
1289 }
1290 const latest = latestRun(records);
1291 if (latest === undefined) return true;
1292 return yield* dispatch({
1293 type: "thread.settle",
1294 commandId: CommandId.make(`server:settle-after-run:${input.runId}:${sequence}`),
1295 threadId: input.threadId,
1296 expectedLatestRunId: latest.id,
1297 }).pipe(
1298 Effect.as(true),
1299 // A notification can start between the projection read and the guarded dispatch.
1300 Effect.catchTags({
1301 OrchestratorDispatchError: () => Effect.succeed(false),
1302 OrchestratorCommandPreviouslyRejectedError: () => Effect.succeed(false),
1303 }),
1304 );
1305 });
1306 yield* Stream.fromEffect(trySettle).pipe(
1307 Stream.concat(
1308 orchestrator
1309 .streamStoredEventsFrom({
1310 threadId: input.threadId,
1311 afterSequence,
1312 eventType: "run.updated",
1313 })
1314 .pipe(Stream.mapEffect(() => trySettle)),
1315 ),
1316 Stream.filter((done) => done),
1317 Stream.runHead,
1318 Effect.timeoutOption(Duration.millis(SETTLE_AFTER_RUN_WAIT_MS)),
1319 );
1320 });
1321
1322 const settleThread: ThreadManagementServiceShape["settleThread"] = Effect.fn(
1323 "orchestrationV2.threadManagement.settleThread",
1324 )(function* (input) {
1325 const shell = input.byOwnAgent ? yield* orchestrator.getThreadShell(input.threadId) : null;
1326 if (shell != null && shell.activeRunId !== null) {
1327 yield* settleAfterRun({
1328 projectId: shell.projectId,
1329 threadId: shell.id,
1330 runId: shell.activeRunId,
1331 }).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(layerScope));
1332 return { settlesWhenTurnEnds: true } as const;
1333 }
1334 const result = yield* dispatch({
1335 type: "thread.settle",
1336 commandId: input.commandId,
1337 threadId: input.threadId,
1338 });
1339 return { sequence: result.sequence };
1340 });
1341
1342 const interruptThread: ThreadManagementServiceShape["interruptThread"] = Effect.fn(
1343 "ThreadManagementService.interruptThread",
1344 )(function* (input) {
1345 const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
1346 const explicitRun =
1347 input.runId === undefined
1348 ? undefined
1349 : target.runs.find((candidate) => candidate.id === input.runId);
1350 if (input.runId !== undefined && explicitRun === undefined) {
1351 return yield* new ThreadManagementRunNotFoundError({
1352 threadId: input.threadId,
1353 runId: input.runId,
1354 });
1355 }
1356 if (explicitRun !== undefined && isTerminalRunStatus(explicitRun.status)) {
1357 return {
1358 type: "already_terminal",
1359 run: explicitRun as OrchestrationV2Run & {
1360 readonly status: ThreadManagementTerminalRunStatus;
1361 },
1362 } as const;
1363 }
1364 const interruptibleRun = latestActiveRun(target);
1365 if (interruptibleRun === undefined) {
1366 if (input.runId === undefined) {
1367 return { type: "no_active_run" } as const;
1368 }
1369 return yield* new ThreadManagementThreadNotInterruptibleError({
1370 threadId: input.threadId,
1371 runId: input.runId,
1372 });
1373 }
1374 if (input.runId !== undefined && interruptibleRun.id !== input.runId) {
1375 return yield* new ThreadManagementThreadNotInterruptibleError({
1376 threadId: input.threadId,
1377 runId: input.runId,
1378 });
1379 }
1380 const dispatch = yield* orchestrator.dispatch({
1381 type: "run.interrupt",
1382 commandId: input.commandId,
1383 threadId: input.threadId,
1384 runId: interruptibleRun.id,
1385 ...(input.reason === undefined ? {} : { reason: input.reason }),
1386 });
1387 return { type: "interrupt_requested", run: interruptibleRun, dispatch } as const;
1388 });
1389
1390 const forceStopThread: ThreadManagementServiceShape["forceStopThread"] = Effect.fn(
1391 "ThreadManagementService.forceStopThread",
1392 )(
1393 function* (input) {
1394 // Under the thread lock no new run can be created between the check and the kill. The
1395 // settlement below dispatches, which takes that lock itself, so it runs after release.
1396 const { records, target, killed } = yield* threadDispatch.withLock(
1397 input.threadId,
1398 Effect.gen(function* () {
1399 const records = yield* orchestrator.getThreadRecords(input.threadId, [
1400 "runs",
1401 "providerThreads",
1402 "providerTurns",
1403 ]);
1404 // The run Force stop acts on: the active one, else the latest that started. Queued
1405 // follow-ups never ran, so they neither count as targets nor supersede the request.
1406 const target =
1407 latestActiveRun(records) ??
1408 records.runs
1409 .filter((run) => run.status !== "queued")
1410 .reduce<OrchestrationV2Run | undefined>(
1411 (current, run) =>
1412 current === undefined || run.ordinal > current.ordinal ? run : current,
1413 undefined,
1414 );
1415 if (input.runId !== undefined && input.runId !== target?.id) {
1416 return yield* new OrchestrationV2ForceStopThreadError({
1417 threadId: input.threadId,
1418 reason: "superseded",
1419 });
1420 }
1421 // Shared scopes are never tracked per thread, so this only kills the thread's own agent.
1422 const killed = yield* agentScope.kill(input.threadId);
1423 return { records, target, killed };
1424 }),
1425 );
1426 const sessionIds = new Set(
1427 records.providerThreads.flatMap((providerThread) =>
1428 providerThread.appThreadId === input.threadId && providerThread.providerSessionId !== null
1429 ? [providerThread.providerSessionId]
1430 : [],
1431 ),
1432 );
1433 // A run that already ended may still hold background work; settling it is a no-op otherwise.
1434 const run = target;
1435 if (run !== undefined) {
1436 const active = isActiveRun(run);
1437 const providerTurn = records.providerTurns.findLast(
1438 (turn) =>
1439 turn.runAttemptId === run.activeAttemptId && (!active || turn.status === "running"),
1440 );
1441 const commandId = CommandId.make(
1442 `server:force-stop:${run.id}:${yield* Clock.currentTimeMillis}`,
1443 );
1444 yield* providerTurn === undefined && !active
1445 ? Effect.void
1446 : providerTurn === undefined
1447 ? orchestrator.dispatch({
1448 type: "run.interrupt",
1449 commandId,
1450 threadId: input.threadId,
1451 runId: run.id,
1452 reason: FORCE_STOP_REASON,
1453 })
1454 : orchestrator.dispatch({
1455 type: "thread.background-work.settle",
1456 commandId,
1457 threadId: input.threadId,
1458 providerThreadId: providerTurn.providerThreadId,
1459 providerTurnId: providerTurn.id,
1460 reason: FORCE_STOP_REASON,
1461 });
1462 }
1463 const ownProviderThreadIds = records.providerThreads.flatMap((providerThread) =>
1464 providerThread.appThreadId === input.threadId ? [providerThread.id] : [],
1465 );
1466 // Settling the target can promote a queued follow-up onto the same session; that run is
1467 // not Force stop's to end. Only a newer run bound to a provider thread on this session
1468 // counts. An unreadable thread counts as one, so its sessions are kept.
1469 const throughRunOrdinal = target?.ordinal ?? 0;
1470 const laterRunActive = (providerSessionId: ProviderSessionId) =>
1471 orchestrator.getThreadRecords(input.threadId, ["runs", "providerThreads"]).pipe(
1472 Effect.map(({ runs, providerThreads }) => {
1473 const onSession = new Set(
1474 providerThreads.flatMap((providerThread) =>
1475 providerThread.providerSessionId === providerSessionId ? [providerThread.id] : [],
1476 ),
1477 );
1478 return runs.some(
1479 (run) =>
1480 run.ordinal > throughRunOrdinal &&
1481 isActiveRun(run) &&
1482 run.providerThreadId !== null &&
1483 onSession.has(run.providerThreadId),
1484 );
1485 }),
1486 Effect.orElseSucceed(() => true),
1487 );
1488 const detach = (providerSessionId: ProviderSessionId) =>
1489 sessions
1490 .detach({ providerSessionId, threadId: input.threadId, detail: FORCE_STOP_REASON })
1491 .pipe(
1492 Effect.catchCause((cause) =>
1493 Effect.logWarning("orchestration-v2.force-stop-detach-failed", {
1494 threadId: input.threadId,
1495 cause,
1496 }),
1497 ),
1498 Effect.forkIn(layerScope),
1499 );
1500 let shared = false;
1501 const sharedWith = new Set<ThreadId>();
1502 const releases: Array<{
1503 readonly providerSessionId: ProviderSessionId;
1504 readonly fiber: Fiber.Fiber<boolean, ProviderSessionManager.ProviderSessionManagerV2Error>;
1505 }> = [];
1506 for (const providerSessionId of sessionIds) {
1507 if (!(yield* sessions.isLive(providerSessionId))) continue;
1508 // Decided just before teardown, so the reply matches what happens to the process.
1509 const others = yield* sessions.otherWorkingThreads({
1510 providerSessionId,
1511 threadId: input.threadId,
1512 });
1513 for (const threadId of others) sharedWith.add(threadId);
1514 if (others.length > 0) {
1515 shared = true;
1516 yield* detach(providerSessionId);
1517 continue;
1518 }
1519 // The session manager re-checks atomically with turn starts and keeps a session a
1520 // sibling began using in the meantime.
1521 const fiber = yield* sessions
1522 .releaseUnlessBusy({
1523 providerSessionId,
1524 ownProviderThreadIds,
1525 throughRunOrdinal,
1526 // A promoted follow-up may not have marked its turn busy yet.
1527 keepIf: laterRunActive(providerSessionId),
1528 reason: "manual_shutdown",
1529 detail: FORCE_STOP_REASON,
1530 })
1531 .pipe(Effect.forkIn(layerScope));
1532 releases.push({ providerSessionId, fiber });
1533 }
1534 // Teardown waits on the provider's own exit paths; past this bound it keeps going on its own.
1535 let releasing = false;
1536 for (const release of releases) {
1537 const released = yield* Fiber.join(release.fiber).pipe(
1538 Effect.timeoutOption(FORCE_STOP_RELEASE_WAIT),
1539 );
1540 if (Option.isNone(released)) {
1541 releasing = true;
1542 } else if (!released.value && !(yield* laterRunActive(release.providerSessionId))) {
1543 shared = true;
1544 yield* detach(release.providerSessionId);
1545 }
1546 }
1547 return {
1548 outcome: killed ? "killed" : shared ? "shared" : releasing ? "releasing" : "released",
1549 sharedWithThreadIds: [...sharedWith],
1550 } as const;
1551 },
1552 (effect, input) =>
1553 effect.pipe(
1554 Effect.mapError((cause) =>
1555 isForceStopThreadError(cause)
1556 ? cause
1557 : new OrchestrationV2ForceStopThreadError({ threadId: input.threadId, cause }),
1558 ),
1559 ),
1560 );
1561
1562 const stopWorkflow: ThreadManagementServiceShape["stopWorkflow"] = Effect.fn(
1563 "ThreadManagementService.stopWorkflow",
1564 )(
1565 function* (input) {
1566 const records = yield* orchestrator
1567 .getThreadRecords(input.threadId, ["subagents", "runs", "providerThreads"])
1568 .pipe(
1569 Effect.mapError(
1570 (cause) =>
1571 new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable", cause }),
1572 ),
1573 );
1574 if (records.thread.deletedAt !== null) {
1575 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable" });
1576 }
1577 // Check mode limits under the lock so users cannot raise modes between validation and Stop.
1578 const limit = yield* DispatchModeLimit;
1579 const exceeded =
1580 limit === undefined ? undefined : exceededDispatchModeLimit(limit, records.thread);
1581 if (limit !== undefined && exceeded !== undefined) {
1582 if (limit.refused !== undefined) {
1583 yield* Ref.set(limit.refused, {
1584 threadId: input.threadId,
1585 runtimeMode: records.thread.runtimeMode,
1586 interactionMode: records.thread.interactionMode,
1587 mode: exceeded,
1588 });
1589 }
1590 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable" });
1591 }
1592 const task = records.subagents.find((candidate) => candidate.id === input.subagentId);
1593 if (
1594 task === undefined ||
1595 task.threadId !== input.threadId ||
1596 task.workflow === undefined ||
1597 task.status !== "running"
1598 ) {
1599 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "not-running" });
1600 }
1601 if (task.origin !== "provider_native" || task.driver !== "claudeAgent") {
1602 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unsupported" });
1603 }
1604 const providerThreadId =
1605 task.providerThreadId ??
1606 records.runs.find((run) => run.id === task.runId)?.providerThreadId;
1607 const providerThread = records.providerThreads.find(
1608 (candidate) =>
1609 candidate.id === providerThreadId &&
1610 candidate.appThreadId === input.threadId &&
1611 candidate.providerInstanceId === task.providerInstanceId &&
1612 candidate.driver === task.driver,
1613 );
1614 const taskId = task.nativeTaskRef?.nativeId;
1615 if (providerThread?.providerSessionId == null || taskId == null || taskId.length === 0) {
1616 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable" });
1617 }
1618 const runtime = yield* sessions
1619 .get(providerThread.providerSessionId)
1620 .pipe(
1621 Effect.mapError(
1622 (cause) =>
1623 new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable", cause }),
1624 ),
1625 );
1626 if (Option.isNone(runtime)) {
1627 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable" });
1628 }
1629 if (runtime.value.stopTask === undefined) {
1630 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unsupported" });
1631 }
1632 // Bounded so a provider that never answers cannot hold the thread lock.
1633 yield* runtime.value.stopTask({ providerThread, taskId }).pipe(
1634 Effect.timeout("15 seconds"),
1635 Effect.mapError(
1636 (cause) =>
1637 new OrchestrationV2StopWorkflowError({
1638 ...input,
1639 reason: "stop-failed",
1640 cause,
1641 }),
1642 ),
1643 );
1644 },
1645 (effect, input) => effect.pipe((effect) => threadDispatch.withLock(input.threadId, effect)),
1646 );
1647
1648 const awaitBackgroundTasks: ThreadManagementServiceShape["awaitBackgroundTasks"] = Effect.fn(
1649 "ThreadManagementService.awaitBackgroundTasks",
1650 )(function* (input) {
1651 const unavailable = (cause?: unknown) =>
1652 new ThreadManagementBackgroundWaitError({
1653 threadId: input.threadId,
1654 reason: "unavailable",
1655 ...(cause === undefined ? {} : { cause }),
1656 });
1657 const records = yield* orchestrator
1658 .getThreadRecords(input.threadId, ["providerThreads"])
1659 .pipe(Effect.mapError(unavailable));
1660 const providerThread = records.providerThreads.find(
1661 (candidate) =>
1662 candidate.id === records.thread.activeProviderThreadId &&
1663 candidate.appThreadId === input.threadId,
1664 );
1665 if (records.thread.deletedAt !== null || providerThread?.providerSessionId == null) {
1666 return yield* unavailable();
1667 }
1668 const runtime = yield* sessions
1669 .get(providerThread.providerSessionId)
1670 .pipe(Effect.mapError(unavailable));
1671 if (Option.isNone(runtime)) {
1672 return yield* unavailable();
1673 }
1674 if (runtime.value.awaitBackgroundTasks === undefined) {
1675 return yield* new ThreadManagementBackgroundWaitError({
1676 threadId: input.threadId,
1677 reason: "unsupported",
1678 });
1679 }
1680 const { matched } = yield* runtime.value
1681 .awaitBackgroundTasks({ providerThread, taskIds: input.taskIds, awaited: input.awaited })
1682 .pipe(
1683 Effect.timeout("15 seconds"),
1684 Effect.mapError(
1685 (cause) =>
1686 new ThreadManagementBackgroundWaitError({
1687 threadId: input.threadId,
1688 reason: "failed",
1689 cause,
1690 }),
1691 ),
1692 );
1693 if (input.awaited && matched.length === 0) {
1694 return yield* new ThreadManagementBackgroundWaitError({
1695 threadId: input.threadId,
1696 reason: "unmatched",
1697 });
1698 }
1699 const matchedIds = new Set(matched);
1700 return { matched, unmatched: input.taskIds.filter((taskId) => !matchedIds.has(taskId)) };
1701 });
1702
1703 const stopDelegatedTasks: ThreadManagementServiceShape["stopDelegatedTasks"] = Effect.fn(
1704 "ThreadManagementService.stopDelegatedTasks",
1705 )(function* (input) {
1706 const { subagents } = yield* orchestrator.getThreadRecords(input.threadId, ["subagents"]);
1707 const failures: Array<
1708 Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
1709 > = [];
1710 const stoppedChildThreadIds = new Set<ThreadId>();
1711 for (const task of subagents) {
1712 if (task.origin !== "app_owned") continue;
1713 if (task.childThreadId === null) {
1714 // A task in a linked environment ends here; its follower then stops it there.
1715 // One with its result keeps it, but its thread there may run follow-up work.
1716 if (task.remoteChild === undefined) continue;
1717 const commandId = CommandId.make(`${input.commandId}:stop:${task.id}`);
1718 yield* (input.remoteDispatch ?? dispatch)(
1719 task.result === null
1720 ? {
1721 type: "delegated_task.remote.complete",
1722 commandId,
1723 parentThreadId: input.threadId,
1724 taskId: task.id,
1725 status: "interrupted",
1726 result:
1727 input.reason === undefined
1728 ? "Stopped with its parent."
1729 : `Stopped with its parent: ${input.reason}`,
1730 }
1731 : {
1732 type: "delegated_task.remote.stop",
1733 commandId,
1734 parentThreadId: input.threadId,
1735 taskId: task.id,
1736 },
1737 ).pipe(
1738 Effect.catch((error) =>
1739 Effect.logWarning("Unable to stop a delegated task", {
1740 parentThreadId: input.threadId,
1741 taskId: task.id,
1742 error,
1743 }).pipe(Effect.andThen(Effect.sync(() => failures.push(error)))),
1744 ),
1745 );
1746 continue;
1747 }
1748 const threadId = task.childThreadId;
1749 // Follow-up tasks reuse a child thread; walk its subtree only once.
1750 if (stoppedChildThreadIds.has(threadId)) continue;
1751 stoppedChildThreadIds.add(threadId);
1752 yield* dispatch({
1753 type: "thread.stop",
1754 commandId: CommandId.make(`${input.commandId}:stop:${threadId}`),
1755 threadId,
1756 stopDelegatedTasks: false,
1757 ...(input.reason === undefined ? {} : { reason: input.reason }),
1758 }).pipe(
1759 Effect.andThen(
1760 stopDelegatedTasks({ threadId, commandId: input.commandId, reason: input.reason }),
1761 ),
1762 Effect.catch((error) =>
1763 Effect.logWarning("Unable to stop a delegated task", {
1764 parentThreadId: input.threadId,
1765 threadId,
1766 error,
1767 }).pipe(Effect.andThen(Effect.sync(() => failures.push(error)))),
1768 ),
1769 );
1770 }
1771 if (failures[0] !== undefined) return yield* failures[0];
1772 });
1773
1774 return ThreadManagementService.of({
1775 ensureLegacyTranscript,
1776 searchThreadStream: (input) =>
1777 Stream.unwrap(
1778 ensureProjectionTranscript(input.threadId).pipe(
1779 Effect.as(orchestrator.searchThreadStream(input)),
1780 ),
1781 ),
1782 searchThread: Effect.fn("ThreadManagementService.searchThread")(function (input) {
1783 return ensureProjectionTranscript(input.threadId).pipe(
1784 Effect.andThen(orchestrator.searchThread(input)),
1785 );
1786 }),
1787 dispatch,
1788 getThreadHistoryPage: Effect.fn("ThreadManagementService.getThreadHistoryPage")(
1789 function (threadId, cursor, throughEntryId, conversationOnly, workMode) {
1790 return ensureProjectionTranscript(threadId).pipe(
1791 Effect.andThen(
1792 orchestrator.getThreadHistoryPage(
1793 threadId,
1794 cursor,
1795 throughEntryId,
1796 conversationOnly,
1797 workMode,
1798 ),
1799 ),
1800 );
1801 },
1802 ),
1803 getTimelinePage: Effect.fn("ThreadManagementService.getTimelinePage")(
1804 function (threadId, options) {
1805 return ensureProjectionTranscript(threadId).pipe(
1806 Effect.andThen(orchestrator.getTimelinePage(threadId, options)),
1807 );
1808 },
1809 ),
1810 getMessageCount: Effect.fn("ThreadManagementService.getMessageCount")(function (threadId) {
1811 return ensureProjectionTranscript(threadId).pipe(
1812 Effect.andThen(orchestrator.getMessageCount(threadId)),
1813 );
1814 }),
1815 getRunCount: Effect.fn("ThreadManagementService.getRunCount")(function (threadId) {
1816 return ensureProjectionTranscript(threadId).pipe(
1817 Effect.andThen(orchestrator.getRunCount(threadId)),
1818 );
1819 }),
1820 getMessagesById: Effect.fn("ThreadManagementService.getMessagesById")(
1821 function (threadId, messageIds) {
1822 return ensureProjectionTranscript(threadId).pipe(
1823 Effect.andThen(orchestrator.getMessagesById(threadId, messageIds)),
1824 );
1825 },
1826 ),
1827 getTurnItem: Effect.fn("ThreadManagementService.getTurnItem")(function (input) {
1828 return ensureProjectionTranscript(input.threadId).pipe(
1829 Effect.andThen(orchestrator.getTurnItem(input)),
1830 Effect.map((item) => ({ item: item === null ? null : projectTurnItemForDetail(item) })),
1831 );
1832 }),
1833 getThreadRecords: Effect.fn("ThreadManagementService.getThreadRecords")(
1834 function (threadId, fields, filter) {
1835 return ensureProjectionTranscript(threadId).pipe(
1836 Effect.andThen(orchestrator.getThreadRecords(threadId, fields, filter)),
1837 );
1838 },
1839 ),
1840 getThreadProjection,
1841 getCheckpointContext,
1842 getThreadSnapshot,
1843 getThreadTranscript,
1844 getThreadSnapshotWindow,
1845 getProjectThreadRecords,
1846 getAgentAwarenessSnapshot: orchestrator.getAgentAwarenessSnapshot,
1847 getShellSnapshot: orchestrator.getShellSnapshot,
1848 listActiveSubagentThreadIds: orchestrator.listActiveSubagentThreadIds,
1849 countThreads: orchestrator.countThreads,
1850 listActiveShellIndex: orchestrator.listActiveShellIndex,
1851 listOlderSettledThreads: orchestrator.listOlderSettledThreads,
1852 readShellSnapshot: orchestrator.readShellSnapshot,
1853 getThreadShell: orchestrator.getThreadShell,
1854 listAppOwnedChildThreadIds: Effect.fn("ThreadManagementService.listAppOwnedChildThreadIds")(
1855 function (threadId) {
1856 return ensureProjectionTranscript(threadId).pipe(
1857 Effect.andThen(orchestrator.listAppOwnedChildThreadIds(threadId)),
1858 );
1859 },
1860 ),
1861 getThreadTitles: orchestrator.getThreadTitles,
1862 getThreadLinkMetadata: orchestrator.getThreadLinkMetadata,
1863 listProjectThreads,
1864 sendToThread,
1865 submitRunOutput,
1866 assertProviderInstanceEnabled,
1867 isProviderInstanceEnabledForProject,
1868 hasReceipt,
1869 waitForThread,
1870 settleAfterRun,
1871 settleThread,
1872 interruptThread,
1873 stopDelegatedTasks,
1874 stopWorkflow,
1875 forceStopThread,
1876 awaitBackgroundTasks,
1877 getThreadEventSequence: orchestrator.getThreadEventSequence,
1878 recoverDelegatedTask: orchestrator.recoverDelegatedTask,
1879 cancelDelegatedTask: orchestrator.cancelDelegatedTask,
1880 delegatedTaskResultPending: orchestrator.delegatedTaskResultPending,
1881 streamStoredEvents: orchestrator.streamStoredEvents,
1882 streamStoredEventsFrom: orchestrator.streamStoredEventsFrom,
1883 streamDomainEvents: orchestrator.streamDomainEvents,
1884 });
1885 });
1886
1887 const layerThreadWorktreeRestoreNoop = Layer.succeed(ThreadWorktreeRestore, {
1888 restore: Effect.fn("ThreadWorktreeRestore.restore")(function () {
1889 return Effect.void;
1890 }),
1891 });
1892
1893 const layerLegacyV1ThreadImporterNoop = Layer.succeed(
1894 LegacyV1ThreadImporter.LegacyV1ThreadImporter,
1895 LegacyV1ThreadImporter.LegacyV1ThreadImporter.of({
1896 pendingThreadCount: Effect.succeed(0),
1897 reconcileShells: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
1898 ensureTranscript: Effect.fn("LegacyV1ThreadImporter.ensureTranscript")(function () {
1899 return Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 });
1900 }),
1901 importPendingTranscripts: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
1902 }),
1903 );
1904
1905 export const layer: Layer.Layer<
1906 ThreadManagementService,
1907 never,
1908 | Orchestrator.OrchestratorV2
1909 | ProviderSessionManager.ProviderSessionManagerV2
1910 | ServerSettings.ServerSettingsService
1911 | CommandReceiptStore.CommandReceiptStoreV2
1912 > = Layer.effect(ThreadManagementService, make).pipe(
1913 Layer.provide(layerLegacyV1ThreadImporterNoop),
1914 Layer.provide(layerThreadWorktreeRestoreNoop),
1915 Layer.provide(ThreadCommandExecutor.layer),
1916 );
1917
1918 export const layerWithLegacyImporter: Layer.Layer<
1919 ThreadManagementService,
1920 never,
1921 | LegacyV1ThreadImporter.LegacyV1ThreadImporter
1922 | ThreadWorktreeRestore
1923 | Orchestrator.OrchestratorV2
1924 | ProviderSessionManager.ProviderSessionManagerV2
1925 | ServerSettings.ServerSettingsService
1926 | CommandReceiptStore.CommandReceiptStoreV2
1927 > = Layer.effect(ThreadManagementService, make).pipe(Layer.provide(ThreadCommandExecutor.layer));