Open History to see the last commit
1import type {
2 OrchestrationV2SearchThreadInput,
3 OrchestrationV2SearchThreadResult,
4} from "@t3tools/contracts";
5import type {
6 ProjectionRecordField,
7 ProjectionRecordFilter,
8 ProjectionRecords,
9 ShellSnapshotOptions,
10} from "./ProjectionStore.ts";
11import {
12 type ChatAttachment,
13 CommandId,
14 MessageId,
15 OrchestrationV2StopWorkflowError,
16 type OrchestrationV2StopWorkflowInput,
17 type ModelSelection,
18 type OrchestrationV2Actor,
19 type OrchestrationV2Command,
20 type OrchestrationV2GetTurnItemResult,
21 type OrchestrationV2ServerCommand,
22 type OrchestrationV2ConversationMessage,
23 type OrchestrationV2CreationSource,
24 type OrchestrationV2Run,
25 type OrchestrationV2ThreadShellSnapshot,
26 type OrchestrationV2ThreadProjection,
27 type OrchestrationV2ThreadTranscript,
28 type OrchestrationV2ThreadShell,
29 type OrchestrationV2TurnItem,
30 ProjectId,
31 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
32 ProviderInstanceId,
33 resolveProjectProviderInstanceEnabled,
34 RunId,
35 type ScheduledTaskId,
36 ThreadId,
37 type TurnItemId,
38} from "@t3tools/contracts";
39import { delegatedTaskProgress } from "@t3tools/provider-core/server/subagentProjection";
40import { threadTranscriptHeader } from "@t3tools/shared/threadTranscript";
41import * as Context from "effect/Context";
42import * as DateTime from "effect/DateTime";
43import * as Duration from "effect/Duration";
44import * as Effect from "effect/Effect";
45import * as Layer from "effect/Layer";
46import * as Option from "effect/Option";
47import * as Ref from "effect/Ref";
48import * as Schema from "effect/Schema";
49import * as Stream from "effect/Stream";
50
51import * as CommandReceiptStore from "./CommandReceiptStore.ts";
52import * as Orchestrator from "./Orchestrator.ts";
53import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
54import { projectedRowEncodedBytes } from "./threadHistoryPaging.ts";
55import * as ProviderSessionManager from "./ProviderSessionManager.ts";
56import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
57import { DispatchModeLimit, exceededDispatchModeLimit } from "./DispatchModeLimit.ts";
58import { projectTurnItemForDetail } from "./WireProjection.ts";
59import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts";
60import * as ServerSettings from "../serverSettings.ts";
61
62export type ThreadManagementSendMode = "auto" | "queue" | "steer" | "restart";
63
64export interface ThreadManagementProvenance {
65 readonly createdBy: OrchestrationV2Actor;
66 readonly creationSource: OrchestrationV2CreationSource;
67}
68
69export function withCreationProvenance(
70 command: OrchestrationV2Command,
71 provenance: ThreadManagementProvenance,
72): OrchestrationV2Command {
73 switch (command.type) {
74 case "thread.create": {
75 // Only the server stamps a link's origin, so a client cannot set one.
76 const { linkOrigin: _linkOrigin, delegatedFrom: _delegatedFrom, ...rest } = command;
77 return { ...rest, ...provenance };
78 }
79 case "message.dispatch":
80 case "thread.fork":
81 case "thread.merge_back":
82 case "delegated_task.request":
83 return { ...command, ...provenance };
84 default:
85 return command;
86 }
87}
88
89function existingThreadIdsForCommand(
90 command: OrchestrationV2ServerCommand,
91): ReadonlyArray<ThreadId> {
92 switch (command.type) {
93 case "thread.create":
94 return [];
95 // Read-state commands only rewrite the thread payload's visited/unread
96 // watermark and open stats; they never touch messages, so they do not need the imported
97 // v1 transcript hydrated first. Visits fire on every thread-activity bump
98 // while a thread is open, so keeping them off the import path matters.
99 case "thread.visit":
100 case "thread.mark-unread":
101 return [];
102 case "thread.fork":
103 return [command.sourceThreadId];
104 case "thread.merge_back":
105 return command.sourceThreadId === command.targetThreadId
106 ? [command.sourceThreadId]
107 : [command.sourceThreadId, command.targetThreadId];
108 case "delegated_task.request":
109 case "delegated_task.wake-policy":
110 case "delegated_task.completion-delivery.acknowledge":
111 case "delegated_task.completion-delivery.dispose":
112 case "delegated_task.remote.request":
113 case "delegated_task.remote.complete":
114 case "delegated_task.remote.stop":
115 return [command.parentThreadId];
116 case "thread.created.record":
117 return command.parentThreadId === command.targetThreadId
118 ? [command.parentThreadId]
119 : [command.parentThreadId, command.targetThreadId];
120 default:
121 return [command.threadId];
122 }
123}
124
125export type ThreadManagementTerminalRunStatus = Extract<
126 OrchestrationV2Run["status"],
127 "completed" | "failed" | "cancelled" | "interrupted" | "rolled_back"
128>;
129
130export interface ThreadManagementSendInput {
131 readonly projectId: ProjectId;
132 readonly commandId: CommandId;
133 readonly threadId: ThreadId;
134 readonly messageId: MessageId;
135 readonly scheduledTaskId?: ScheduledTaskId;
136 readonly senderThreadId?: ThreadId;
137 readonly text: string;
138 readonly attachments: ReadonlyArray<ChatAttachment>;
139 readonly modelSelection?: ModelSelection;
140 readonly mode: ThreadManagementSendMode;
141 readonly createdBy: OrchestrationV2Actor;
142 readonly creationSource: OrchestrationV2CreationSource;
143}
144
145export interface ThreadManagementSendResult {
146 readonly dispatch: Orchestrator.OrchestratorV2DispatchResult;
147 readonly projection: Pick<
148 OrchestrationV2ThreadProjection,
149 "thread" | "runs" | "messages" | "turnItems"
150 >;
151 readonly message: OrchestrationV2ConversationMessage;
152 readonly run: OrchestrationV2Run;
153 readonly turnItem: Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> | null;
154 readonly delivery: "started" | "queued" | "steered" | "restarted";
155}
156
157export interface ThreadManagementWaitInput {
158 readonly projectId: ProjectId;
159 readonly threadId: ThreadId;
160 readonly runId?: RunId;
161 readonly timeoutMs: number;
162 /**
163 * Also wait until the thread's own delegated work settles: an ended run
164 * still owes the thread's answer while a child, a background task or a
165 * completion delivery will wake it again, as a delegated task's result does.
166 */
167 readonly untilDelegatedWorkSettled?: boolean;
168}
169
170export interface ThreadManagementWaitResult {
171 readonly threadId: ThreadId;
172 readonly run: OrchestrationV2Run | null;
173 readonly timedOut: boolean;
174 /** With `untilDelegatedWorkSettled`, once settled: the run with the thread's final answer. */
175 readonly resultRun?: OrchestrationV2Run;
176}
177
178export interface ThreadManagementInterruptInput {
179 readonly projectId: ProjectId;
180 readonly commandId: CommandId;
181 readonly threadId: ThreadId;
182 readonly runId?: RunId;
183 readonly reason?: string;
184}
185
186export type ThreadManagementInterruptResult =
187 | {
188 readonly type: "interrupt_requested";
189 readonly run: OrchestrationV2Run;
190 readonly dispatch: Orchestrator.OrchestratorV2DispatchResult;
191 }
192 | { readonly type: "no_active_run" }
193 | {
194 readonly type: "already_terminal";
195 readonly run: OrchestrationV2Run & { readonly status: ThreadManagementTerminalRunStatus };
196 };
197
198export class ThreadManagementThreadNotFoundError extends Schema.TaggedError<ThreadManagementThreadNotFoundError>()(
199 "ThreadManagementThreadNotFoundError",
200 {
201 projectId: ProjectId,
202 threadId: ThreadId,
203 },
204) {
205 override get message(): string {
206 return `Thread ${this.threadId} was not found in project ${this.projectId}.`;
207 }
208}
209
210export class ThreadTranscriptTooLargeError extends Schema.TaggedError<ThreadTranscriptTooLargeError>()(
211 "ThreadTranscriptTooLargeError",
212 { threadId: ThreadId },
213) {
214 override get message(): string {
215 return "The thread transcript exceeds the file attachment limit.";
216 }
217}
218
219export class ThreadManagementRunNotFoundError extends Schema.TaggedError<ThreadManagementRunNotFoundError>()(
220 "ThreadManagementRunNotFoundError",
221 {
222 threadId: ThreadId,
223 runId: RunId,
224 },
225) {
226 override get message(): string {
227 return `Run ${this.runId} does not belong to thread ${this.threadId}.`;
228 }
229}
230
231export class ThreadManagementThreadArchivedError extends Schema.TaggedError<ThreadManagementThreadArchivedError>()(
232 "ThreadManagementThreadArchivedError",
233 {
234 threadId: ThreadId,
235 },
236) {
237 override get message(): string {
238 return `Thread ${this.threadId} is archived and cannot receive messages.`;
239 }
240}
241
242export class ThreadManagementNoSteerableRunError extends Schema.TaggedError<ThreadManagementNoSteerableRunError>()(
243 "ThreadManagementNoSteerableRunError",
244 {
245 threadId: ThreadId,
246 mode: Schema.Literals(["steer", "restart"]),
247 },
248) {
249 override get message(): string {
250 return `Thread ${this.threadId} has no running turn that can be ${this.mode === "steer" ? "steered" : "restarted"}.`;
251 }
252}
253
254export class ThreadManagementThreadNotInterruptibleError extends Schema.TaggedError<ThreadManagementThreadNotInterruptibleError>()(
255 "ThreadManagementThreadNotInterruptibleError",
256 {
257 threadId: ThreadId,
258 runId: RunId,
259 },
260) {
261 override get message(): string {
262 return `Run ${this.runId} is not currently interruptible.`;
263 }
264}
265
266export class ThreadManagementProjectionLoadError extends Schema.TaggedError<ThreadManagementProjectionLoadError>()(
267 "ThreadManagementProjectionLoadError",
268 {
269 projectId: ProjectId,
270 threadId: ThreadId,
271 cause: Schema.Defect(),
272 },
273) {
274 override get message(): string {
275 return `Unable to load thread ${this.threadId} in project ${this.projectId}.`;
276 }
277}
278
279export class ThreadManagementProjectThreadsListError extends Schema.TaggedError<ThreadManagementProjectThreadsListError>()(
280 "ThreadManagementProjectThreadsListError",
281 {
282 projectId: Schema.optional(ProjectId),
283 cause: Schema.Defect(),
284 },
285) {
286 override get message(): string {
287 return this.projectId === undefined
288 ? "Unable to list threads."
289 : `Unable to list threads in project ${this.projectId}.`;
290 }
291}
292
293export class ThreadManagementDurableRunProjectionError extends Schema.TaggedError<ThreadManagementDurableRunProjectionError>()(
294 "ThreadManagementDurableRunProjectionError",
295 {
296 threadId: ThreadId,
297 messageId: MessageId,
298 },
299) {
300 override get message(): string {
301 return `Message ${this.messageId} was accepted on thread ${this.threadId} without a durable run projection.`;
302 }
303}
304
305export class ThreadManagementProviderInstanceDisabledError extends Schema.TaggedError<ThreadManagementProviderInstanceDisabledError>()(
306 "ThreadManagementProviderInstanceDisabledError",
307 {
308 projectId: ProjectId,
309 instanceId: ProviderInstanceId,
310 },
311) {
312 override get message(): string {
313 return `Provider instance "${this.instanceId}" is disabled for project ${this.projectId}.`;
314 }
315}
316
317export class ThreadManagementBackgroundWaitError extends Schema.TaggedError<ThreadManagementBackgroundWaitError>()(
318 "ThreadManagementBackgroundWaitError",
319 {
320 threadId: ThreadId,
321 reason: Schema.Literals(["unsupported", "unavailable", "failed"]),
322 cause: Schema.optional(Schema.Defect()),
323 },
324) {
325 override get message(): string {
326 switch (this.reason) {
327 case "unsupported":
328 return "This provider cannot mark background work as awaited.";
329 case "unavailable":
330 return "This thread has no live provider session.";
331 case "failed":
332 return "Failed to update the awaited background work.";
333 }
334 }
335}
336
337export const ThreadManagementError = Schema.Union([
338 ThreadManagementThreadNotFoundError,
339 ThreadManagementRunNotFoundError,
340 ThreadManagementThreadArchivedError,
341 ThreadManagementNoSteerableRunError,
342 ThreadManagementThreadNotInterruptibleError,
343 ThreadManagementProjectionLoadError,
344 ThreadManagementProjectThreadsListError,
345 ThreadManagementDurableRunProjectionError,
346 ThreadManagementProviderInstanceDisabledError,
347]);
348export type ThreadManagementError = typeof ThreadManagementError.Type;
349
350type ThreadManagementFailure = ThreadManagementError | Orchestrator.OrchestratorV2Error;
351
352export interface ThreadManagementServiceShape {
353 readonly searchThreadStream: (
354 input: OrchestrationV2SearchThreadInput,
355 ) => Stream.Stream<OrchestrationV2SearchThreadResult, Orchestrator.OrchestratorV2Error>;
356 readonly searchThread: (
357 input: OrchestrationV2SearchThreadInput,
358 ) => Effect.Effect<OrchestrationV2SearchThreadResult, Orchestrator.OrchestratorV2Error>;
359 readonly ensureLegacyTranscript: (
360 threadId: ThreadId,
361 ) => Effect.Effect<void, LegacyV1ThreadImporter.LegacyV1ThreadImportError>;
362 readonly dispatch: (
363 command: OrchestrationV2ServerCommand,
364 ) => Effect.Effect<
365 Orchestrator.OrchestratorV2DispatchResult,
366 Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
367 >;
368 readonly getThreadHistoryPage: Orchestrator.OrchestratorV2["Service"]["getThreadHistoryPage"];
369 readonly getTimelinePage: Orchestrator.OrchestratorV2["Service"]["getTimelinePage"];
370 readonly getMessageCount: Orchestrator.OrchestratorV2["Service"]["getMessageCount"];
371 readonly getTurnItem: (input: {
372 readonly threadId: ThreadId;
373 readonly itemId: TurnItemId;
374 }) => Effect.Effect<OrchestrationV2GetTurnItemResult, Orchestrator.OrchestratorV2Error>;
375 readonly getThreadRecords: Orchestrator.OrchestratorV2["Service"]["getThreadRecords"];
376 readonly getThreadProjection: (
377 threadId: ThreadId,
378 ) => Effect.Effect<OrchestrationV2ThreadProjection, Orchestrator.OrchestratorV2Error>;
379 readonly getCheckpointContext: Orchestrator.OrchestratorV2["Service"]["getCheckpointContext"];
380 readonly getThreadSnapshot: Orchestrator.OrchestratorV2["Service"]["getThreadSnapshot"];
381 readonly getThreadTranscript: (
382 threadId: ThreadId,
383 ) => Effect.Effect<
384 OrchestrationV2ThreadTranscript,
385 Orchestrator.OrchestratorV2Error | ThreadTranscriptTooLargeError,
386 ServerEnvironment.ServerEnvironmentIdentity
387 >;
388 readonly getThreadSnapshotWindow: Orchestrator.OrchestratorV2["Service"]["getThreadSnapshotWindow"];
389 readonly getProjectThreadRecords: <K extends ProjectionRecordField>(
390 input: { readonly projectId: ProjectId; readonly threadId: ThreadId },
391 fields: ReadonlyArray<K>,
392 filter?: ProjectionRecordFilter,
393 ) => Effect.Effect<
394 ProjectionRecords<K>,
395 ThreadManagementProjectionLoadError | ThreadManagementThreadNotFoundError
396 >;
397 readonly getShellSnapshot: (options?: {
398 readonly location?: "active" | "archive";
399 }) => Effect.Effect<OrchestrationV2ThreadShellSnapshot, Orchestrator.OrchestratorV2Error>;
400 readonly listActiveSubagentThreadIds: Orchestrator.OrchestratorV2["Service"]["listActiveSubagentThreadIds"];
401 readonly listOlderSettledThreads: Orchestrator.OrchestratorV2["Service"]["listOlderSettledThreads"];
402 readonly readShellSnapshot: (
403 options?: Pick<ShellSnapshotOptions, "location" | "familyOf" | "worktreePath" | "threadIds">,
404 ) => Effect.Effect<
405 Effect.Effect<OrchestrationV2ThreadShellSnapshot, Orchestrator.OrchestratorV2Error>,
406 Orchestrator.OrchestratorV2Error
407 >;
408 readonly getThreadShell: Orchestrator.OrchestratorV2["Service"]["getThreadShell"];
409 /** Omit `projectId` to list every project's threads. */
410 readonly listProjectThreads: (input: {
411 readonly projectId?: ProjectId | undefined;
412 readonly includeSubagents: boolean;
413 }) => Effect.Effect<ReadonlyArray<OrchestrationV2ThreadShell>, ThreadManagementError>;
414 readonly sendToThread: (
415 input: ThreadManagementSendInput,
416 ) => Effect.Effect<ThreadManagementSendResult, ThreadManagementFailure>;
417 readonly assertProviderInstanceEnabled: (input: {
418 readonly projectId: ProjectId;
419 readonly commandId: CommandId;
420 readonly instanceId: ProviderInstanceId;
421 }) => Effect.Effect<void, ThreadManagementProviderInstanceDisabledError>;
422 readonly isProviderInstanceEnabledForProject: (input: {
423 readonly projectId: ProjectId;
424 readonly instanceId: ProviderInstanceId;
425 }) => Effect.Effect<boolean>;
426 /** Receipt replays start no work; skip enablement checks with the same command id so settings cannot reject accepted retries. */
427 readonly hasReceipt: (commandId: CommandId) => Effect.Effect<boolean>;
428 readonly waitForThread: (
429 input: ThreadManagementWaitInput,
430 ) => Effect.Effect<ThreadManagementWaitResult, ThreadManagementError>;
431 /** Waits for the agent's run to end before settling its thread and stopping the session.
432 * Other endings or settle refusals leave the thread active. */
433 readonly settleAfterRun: (input: {
434 readonly projectId: ProjectId;
435 readonly threadId: ThreadId;
436 readonly runId: RunId;
437 }) => Effect.Effect<void, ThreadManagementFailure>;
438 readonly settleThread: (input: {
439 readonly threadId: ThreadId;
440 readonly commandId: CommandId;
441 readonly byOwnAgent: boolean;
442 }) => Effect.Effect<
443 { readonly sequence: number } | { readonly settlesWhenTurnEnds: true },
444 Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
445 >;
446 readonly interruptThread: (
447 input: ThreadManagementInterruptInput,
448 ) => Effect.Effect<ThreadManagementInterruptResult, ThreadManagementFailure>;
449 readonly stopWorkflow: (
450 input: OrchestrationV2StopWorkflowInput,
451 ) => Effect.Effect<void, OrchestrationV2StopWorkflowError>;
452 readonly awaitBackgroundTasks: (input: {
453 readonly threadId: ThreadId;
454 readonly taskIds: ReadonlyArray<string>;
455 readonly awaited: boolean;
456 }) => Effect.Effect<
457 { readonly matched: ReadonlyArray<string>; readonly unmatched: ReadonlyArray<string> },
458 ThreadManagementBackgroundWaitError
459 >;
460 readonly stopDelegatedTasks: (input: {
461 readonly threadId: ThreadId;
462 readonly commandId: CommandId;
463 readonly reason?: string | undefined;
464 }) => Effect.Effect<
465 void,
466 Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
467 >;
468 readonly getThreadEventSequence: Orchestrator.OrchestratorV2["Service"]["getThreadEventSequence"];
469 readonly recoverDelegatedTask: Orchestrator.OrchestratorV2["Service"]["recoverDelegatedTask"];
470 readonly delegatedTaskResultPending: Orchestrator.OrchestratorV2["Service"]["delegatedTaskResultPending"];
471 readonly streamStoredEvents: Orchestrator.OrchestratorV2["Service"]["streamStoredEvents"];
472 readonly streamStoredEventsFrom: Orchestrator.OrchestratorV2["Service"]["streamStoredEventsFrom"];
473 readonly streamDomainEvents: Orchestrator.OrchestratorV2["Service"]["streamDomainEvents"];
474}
475
476export class ThreadManagementService extends Context.Service<
477 ThreadManagementService,
478 ThreadManagementServiceShape
479>()("t3/orchestration-v2/ThreadManagementService") {}
480
481export function isActiveRun(run: OrchestrationV2Run): boolean {
482 return (
483 run.status === "preparing" ||
484 run.status === "starting" ||
485 run.status === "running" ||
486 run.status === "waiting"
487 );
488}
489
490export function isTerminalRunStatus(
491 status: OrchestrationV2Run["status"],
492): status is ThreadManagementTerminalRunStatus {
493 return (
494 status === "completed" ||
495 status === "failed" ||
496 status === "cancelled" ||
497 status === "interrupted" ||
498 status === "rolled_back"
499 );
500}
501
502export function latestRun(
503 projection: Pick<OrchestrationV2ThreadProjection, "runs">,
504): OrchestrationV2Run | undefined {
505 return projection.runs.toSorted((left, right) => right.ordinal - left.ordinal)[0];
506}
507
508function latestRestartContinuation(
509 runs: ReadonlyArray<OrchestrationV2Run>,
510 run: OrchestrationV2Run,
511): OrchestrationV2Run {
512 let current = run;
513 for (let hops = 0; hops < runs.length; hops++) {
514 const next = runs.find((candidate) => candidate.restartContinuationOfRunId === current.id);
515 if (next === undefined) break;
516 current = next;
517 }
518 return current;
519}
520
521export function latestActiveRun(
522 projection: Pick<OrchestrationV2ThreadProjection, "runs">,
523): OrchestrationV2Run | undefined {
524 return projection.runs
525 .filter(isActiveRun)
526 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
527}
528
529function latestSteerableRun(
530 projection: Pick<OrchestrationV2ThreadProjection, "runs" | "providerTurns">,
531): OrchestrationV2Run | undefined {
532 return projection.runs
533 .filter(
534 (run) =>
535 run.status === "running" &&
536 run.activeAttemptId !== null &&
537 projection.providerTurns.some(
538 (turn) => turn.runAttemptId === run.activeAttemptId && turn.status === "running",
539 ),
540 )
541 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
542}
543
544const SETTLE_AFTER_RUN_WAIT_MS = 24 * 60 * 60 * 1_000;
545
546const make = Effect.gen(function* () {
547 const threadDispatch = yield* ThreadCommandExecutor.ThreadCommandExecutor;
548 const orchestrator = yield* Orchestrator.OrchestratorV2;
549 const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
550 const layerScope = yield* Effect.scope;
551 const legacyImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
552 const serverSettings = yield* ServerSettings.ServerSettingsService;
553 const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
554
555 const assertProviderInstanceEnabled: ThreadManagementServiceShape["assertProviderInstanceEnabled"] =
556 (input) =>
557 receipts.getByCommandId(input.commandId).pipe(
558 Effect.orElseSucceed(() => Option.none()),
559 Effect.flatMap((receipt) =>
560 Option.isSome(receipt)
561 ? Effect.void
562 : serverSettings.getSettings.pipe(
563 Effect.orDie,
564 Effect.flatMap((current) =>
565 resolveProjectProviderInstanceEnabled(current, input.projectId, input.instanceId)
566 ? Effect.void
567 : new ThreadManagementProviderInstanceDisabledError({
568 projectId: input.projectId,
569 instanceId: input.instanceId,
570 }),
571 ),
572 ),
573 ),
574 );
575
576 const isProviderInstanceEnabledForProject: ThreadManagementServiceShape["isProviderInstanceEnabledForProject"] =
577 (input) =>
578 serverSettings.getSettings.pipe(
579 Effect.orDie,
580 Effect.map((current) =>
581 resolveProjectProviderInstanceEnabled(current, input.projectId, input.instanceId),
582 ),
583 );
584
585 const hasReceipt: ThreadManagementServiceShape["hasReceipt"] = (commandId) =>
586 receipts.getByCommandId(commandId).pipe(
587 Effect.orElseSucceed(() => Option.none()),
588 Effect.map(Option.isSome),
589 );
590
591 const ensureLegacyTranscript = Effect.fn(
592 "orchestrationV2.threadManagement.ensureLegacyTranscript",
593 )(function* (threadId: ThreadId) {
594 yield* legacyImporter.ensureTranscript(threadId).pipe(
595 Effect.tapError((cause) =>
596 Effect.logWarning("Unable to hydrate migrated v1 thread transcript", {
597 threadId,
598 cause,
599 }),
600 ),
601 );
602 });
603
604 const ensureProjectionTranscript = (threadId: ThreadId) =>
605 ensureLegacyTranscript(threadId).pipe(
606 Effect.mapError(
607 (cause) =>
608 new Orchestrator.OrchestratorProjectionError({
609 threadId,
610 cause,
611 }),
612 ),
613 );
614
615 const ensureCommandTranscripts = Effect.fn(
616 "orchestrationV2.threadManagement.ensureCommandTranscripts",
617 )(function* (command: OrchestrationV2ServerCommand) {
618 yield* Effect.forEach(
619 existingThreadIdsForCommand(command),
620 (threadId) => ensureLegacyTranscript(threadId),
621 { discard: true },
622 ).pipe(
623 Effect.mapError(
624 (cause) =>
625 new Orchestrator.OrchestratorDispatchError({
626 commandId: command.commandId,
627 commandType: command.type,
628 cause,
629 }),
630 ),
631 );
632 });
633
634 const getThreadProjection: ThreadManagementServiceShape["getThreadProjection"] = (threadId) =>
635 ensureProjectionTranscript(threadId).pipe(
636 Effect.andThen(orchestrator.getThreadProjection(threadId)),
637 );
638
639 const getCheckpointContext: ThreadManagementServiceShape["getCheckpointContext"] = (threadId) =>
640 ensureProjectionTranscript(threadId).pipe(
641 Effect.andThen(orchestrator.getCheckpointContext(threadId)),
642 );
643
644 const getThreadSnapshot: ThreadManagementServiceShape["getThreadSnapshot"] = (threadId) =>
645 ensureProjectionTranscript(threadId).pipe(
646 Effect.andThen(orchestrator.getThreadSnapshot(threadId)),
647 );
648 const getThreadTranscript = Effect.fn("orchestrationV2.threadManagement.getThreadTranscript")(
649 function* (threadId: ThreadId) {
650 const { projection } = yield* getThreadSnapshot(threadId);
651 const environment = yield* ServerEnvironment.ServerEnvironmentIdentity;
652 const transcript = {
653 threadId: projection.thread.id,
654 title: projection.thread.title,
655 updatedAt: projection.updatedAt,
656 items: projection.visibleTurnItems,
657 };
658 let sizeBytes = Buffer.byteLength(
659 threadTranscriptHeader(yield* environment.getEnvironmentId, transcript),
660 "utf8",
661 );
662 if (sizeBytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) {
663 return yield* new ThreadTranscriptTooLargeError({ threadId });
664 }
665 for (const row of transcript.items) {
666 sizeBytes += projectedRowEncodedBytes(row) + 1;
667 if (sizeBytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) {
668 return yield* new ThreadTranscriptTooLargeError({ threadId });
669 }
670 }
671 return transcript;
672 },
673 );
674 const getThreadSnapshotWindow: ThreadManagementServiceShape["getThreadSnapshotWindow"] = (
675 threadId,
676 options,
677 ) =>
678 ensureProjectionTranscript(threadId).pipe(
679 Effect.andThen(orchestrator.getThreadSnapshotWindow(threadId, options)),
680 );
681
682 const assertDispatchTargetEnabled = (command: OrchestrationV2ServerCommand) => {
683 switch (command.type) {
684 case "message.dispatch":
685 return orchestrator.getThreadRecords(command.threadId, []).pipe(
686 Effect.flatMap((projection) =>
687 assertProviderInstanceEnabled({
688 projectId: projection.thread.projectId,
689 commandId: command.commandId,
690 instanceId: (command.modelSelection ?? projection.thread.modelSelection).instanceId,
691 }),
692 ),
693 );
694 case "delegated_task.request":
695 return orchestrator.getThreadRecords(command.parentThreadId, []).pipe(
696 Effect.flatMap((parent) =>
697 assertProviderInstanceEnabled({
698 projectId: parent.thread.projectId,
699 commandId: command.commandId,
700 instanceId: command.modelSelection.instanceId,
701 }),
702 ),
703 );
704 default:
705 return Effect.void;
706 }
707 };
708
709 const dispatch: ThreadManagementServiceShape["dispatch"] = (command) =>
710 ensureCommandTranscripts(command).pipe(
711 Effect.andThen(assertDispatchTargetEnabled(command)),
712 Effect.andThen(orchestrator.dispatch(command)),
713 );
714
715 const getProjectThreadRecords: ThreadManagementServiceShape["getProjectThreadRecords"] = (
716 input,
717 fields,
718 filter,
719 ) =>
720 ensureProjectionTranscript(input.threadId).pipe(
721 Effect.andThen(orchestrator.getThreadRecords(input.threadId, fields, filter)),
722 Effect.mapError(
723 (cause) =>
724 new ThreadManagementProjectionLoadError({
725 projectId: input.projectId,
726 threadId: input.threadId,
727 cause,
728 }),
729 ),
730 Effect.filterOrFail(
731 (projection) =>
732 projection.thread.projectId === input.projectId && projection.thread.deletedAt === null,
733 (_projection) =>
734 new ThreadManagementThreadNotFoundError({
735 projectId: input.projectId,
736 threadId: input.threadId,
737 }),
738 ),
739 );
740
741 const listProjectThreads: ThreadManagementServiceShape["listProjectThreads"] = (input) =>
742 orchestrator
743 .getShellSnapshot({
744 location: "active",
745 ...(input.projectId === undefined ? {} : { projectId: input.projectId }),
746 })
747 .pipe(
748 Effect.mapError(
749 (cause) =>
750 new ThreadManagementProjectThreadsListError({
751 projectId: input.projectId,
752 cause,
753 }),
754 ),
755 Effect.map((snapshot) =>
756 snapshot.threads
757 .filter(
758 (thread) =>
759 input.includeSubagents || thread.lineage.relationshipToParent !== "subagent",
760 )
761 .toSorted(
762 (left, right) =>
763 DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt) ||
764 right.id.localeCompare(left.id),
765 ),
766 ),
767 );
768
769 const sendToThread: ThreadManagementServiceShape["sendToThread"] = Effect.fn(
770 "ThreadManagementService.sendToThread",
771 )(function* (input) {
772 const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
773 if (target.thread.archivedAt !== null) {
774 return yield* new ThreadManagementThreadArchivedError({
775 threadId: input.threadId,
776 });
777 }
778 const steerableRun = latestSteerableRun(target);
779 let dispatchMode: Extract<
780 OrchestrationV2Command,
781 { readonly type: "message.dispatch" }
782 >["dispatchMode"];
783 if (input.mode === "steer" || input.mode === "restart") {
784 if (steerableRun === undefined) {
785 return yield* new ThreadManagementNoSteerableRunError({
786 threadId: input.threadId,
787 mode: input.mode,
788 });
789 }
790 dispatchMode = {
791 type: input.mode === "steer" ? "steer_active" : "restart_active",
792 targetRunId: steerableRun.id,
793 };
794 } else if (input.mode === "auto" && steerableRun !== undefined) {
795 dispatchMode = { type: "steer_active", targetRunId: steerableRun.id };
796 } else {
797 dispatchMode = {
798 type: input.mode === "queue" ? "queue_after_active" : "start_immediately",
799 };
800 }
801
802 const dispatched = yield* dispatch({
803 type: "message.dispatch",
804 commandId: input.commandId,
805 threadId: input.threadId,
806 messageId: input.messageId,
807 ...(input.scheduledTaskId === undefined ? {} : { scheduledTaskId: input.scheduledTaskId }),
808 ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
809 text: input.text,
810 attachments: input.attachments,
811 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
812 dispatchMode,
813 createdBy: input.createdBy,
814 creationSource: input.creationSource,
815 });
816 const projection = yield* getProjectThreadRecords(input, ["runs", "messages", "turnItems"], {
817 messageIds: [input.messageId],
818 turnItemTypes: ["user_message"],
819 });
820 const message = projection.messages.find((candidate) => candidate.id === input.messageId);
821 const run =
822 message?.runId === null || message?.runId === undefined
823 ? undefined
824 : projection.runs.find((candidate) => candidate.id === message.runId);
825 const turnItem =
826 projection.turnItems.find(
827 (
828 candidate,
829 ): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> =>
830 candidate.type === "user_message" && candidate.messageId === input.messageId,
831 ) ?? null;
832 if (
833 message === undefined ||
834 run === undefined ||
835 (turnItem === null && run.status !== "queued")
836 ) {
837 return yield* new ThreadManagementDurableRunProjectionError({
838 threadId: input.threadId,
839 messageId: input.messageId,
840 });
841 }
842 const delivery: ThreadManagementSendResult["delivery"] =
843 turnItem === null || turnItem.inputIntent === "queued_turn"
844 ? "queued"
845 : turnItem.inputIntent === "turn_start"
846 ? "started"
847 : input.mode === "restart"
848 ? "restarted"
849 : "steered";
850 return { dispatch: dispatched, projection, message, run, turnItem, delivery };
851 });
852
853 const waitForThread: ThreadManagementServiceShape["waitForThread"] = Effect.fn(
854 "ThreadManagementService.waitForThread",
855 )(function* (input) {
856 const loadError = (cause: unknown) =>
857 new ThreadManagementProjectionLoadError({
858 projectId: input.projectId,
859 threadId: input.threadId,
860 cause,
861 });
862 // Taken before the first read, so a run update between that read and
863 // the subscription below still replays.
864 const afterSequence = yield* orchestrator
865 .getThreadEventSequence(input.threadId)
866 .pipe(Effect.mapError(loadError));
867 const target = yield* getProjectThreadRecords(input, ["runs"]);
868 const selectedRun =
869 input.runId === undefined
870 ? latestRun(target)
871 : target.runs.find((candidate) => candidate.id === input.runId);
872 if (input.runId !== undefined && selectedRun === undefined) {
873 return yield* new ThreadManagementRunNotFoundError({
874 threadId: input.threadId,
875 runId: input.runId,
876 });
877 }
878 if (selectedRun === undefined) {
879 return { threadId: input.threadId, run: null, timedOut: false };
880 }
881 // A restart cuts a run and continues it as a new run. Follow that chain,
882 // so a cut run is not the answer while its continuation is pending.
883 // Runs per matching event and is already covered by the waitForThread span.
884 const outcome = Effect.fnUntraced(function* (runs: ReadonlyArray<OrchestrationV2Run>) {
885 const current = runs.find((candidate) => candidate.id === selectedRun.id);
886 if (current === undefined) {
887 return yield* new ThreadManagementRunNotFoundError({
888 threadId: input.threadId,
889 runId: selectedRun.id,
890 });
891 }
892 const run = latestRestartContinuation(runs, current);
893 const pending =
894 isTerminalRunStatus(run.status) && (yield* orchestrator.restartContinuationPending(run));
895 return { run, pending, settled: isTerminalRunStatus(run.status) && !pending };
896 });
897 const untilDelegatedWorkSettled = input.untilDelegatedWorkSettled === true;
898 const delegatedWorkResult = Effect.gen(function* () {
899 const records = yield* getProjectThreadRecords(
900 input,
901 ["runs", "messages", "subagents", "providerThreads"],
902 { messageRoles: ["user"] },
903 );
904 const progress = delegatedTaskProgress(records);
905 // A thread rolled back past all its work, with nothing left running, has no answer to wait for.
906 if (
907 progress.resultRun === undefined &&
908 records.runs.every((run) => isTerminalRunStatus(run.status))
909 ) {
910 return latestRun(records);
911 }
912 if (progress.state !== "result_available") return undefined;
913 const pending = yield* orchestrator
914 .delegatedTaskResultPending(input.threadId)
915 .pipe(Effect.mapError(loadError));
916 return pending ? undefined : progress.resultRun;
917 });
918 const evaluate = Effect.fn("orchestrationV2.threadManagement.evaluate")(function* (
919 runs: ReadonlyArray<OrchestrationV2Run>,
920 ) {
921 const current = yield* outcome(runs);
922 if (!current.settled || !untilDelegatedWorkSettled) {
923 return { ...current, resultRun: undefined };
924 }
925 const resultRun = yield* delegatedWorkResult;
926 return { ...current, settled: resultRun !== undefined, resultRun };
927 });
928 const settledResult = (current: Effect.Success<ReturnType<typeof evaluate>>) => ({
929 threadId: input.threadId,
930 run: current.run,
931 timedOut: !current.settled,
932 ...(current.resultRun === undefined ? {} : { resultRun: current.resultRun }),
933 });
934 const initial = yield* evaluate(target.runs);
935 if (initial.settled) return settledResult(initial);
936
937 // A declined continuation records no event, so its effect settling wakes
938 // the wait too.
939 const wait = Stream.merge(
940 Stream.mergeAll(
941 (
942 [
943 "run.updated",
944 "thread.deleted",
945 // What delegated work reads besides runs: tasks and their
946 // deliveries, and a provider thread's background tasks.
947 ...(untilDelegatedWorkSettled
948 ? (["subagent.updated", "provider-thread.updated"] as const)
949 : []),
950 ] as const
951 ).map((eventType) =>
952 orchestrator.streamStoredEventsFrom({
953 threadId: input.threadId,
954 afterSequence,
955 eventType,
956 }),
957 ),
958 { concurrency: "unbounded" },
959 ).pipe(
960 Stream.mapError(loadError),
961 Stream.filter(
962 (stored) =>
963 untilDelegatedWorkSettled ||
964 stored.event.type !== "run.updated" ||
965 stored.event.payload.id === selectedRun.id ||
966 stored.event.payload.restartContinuationOfRunId !== undefined,
967 ),
968 ),
969 initial.pending
970 ? Stream.fromEffect(orchestrator.awaitRestartContinuation(initial.run))
971 : Stream.empty,
972 ).pipe(
973 Stream.mapEffect(() =>
974 getProjectThreadRecords(input, ["runs"]).pipe(
975 Effect.flatMap((current) => evaluate(current.runs)),
976 ),
977 ),
978 Stream.filter((current) => current.settled),
979 Stream.runHead,
980 Effect.timeoutOption(Duration.millis(Math.max(1, input.timeoutMs))),
981 );
982 const waited = Option.flatten(yield* wait);
983 if (Option.isSome(waited)) return settledResult(waited.value);
984 // The run may have reached a terminal status while the timeout was
985 // winning the race; the final projection read decides what actually
986 // happened, so only a still-active run counts as timed out.
987 return settledResult(yield* evaluate((yield* getProjectThreadRecords(input, ["runs"])).runs));
988 });
989
990 const settleAfterRun: ThreadManagementServiceShape["settleAfterRun"] = Effect.fn(
991 "orchestrationV2.threadManagement.settleAfterRun",
992 )(function* (input) {
993 const { run } = yield* waitForThread({ ...input, timeoutMs: SETTLE_AFTER_RUN_WAIT_MS });
994 if (run?.status !== "completed") return;
995 yield* dispatch({
996 type: "thread.settle",
997 commandId: CommandId.make(`server:settle-after-run:${input.runId}`),
998 threadId: input.threadId,
999 });
1000 });
1001
1002 const settleThread: ThreadManagementServiceShape["settleThread"] = Effect.fn(
1003 "orchestrationV2.threadManagement.settleThread",
1004 )(function* (input) {
1005 const shell = input.byOwnAgent ? yield* orchestrator.getThreadShell(input.threadId) : null;
1006 if (shell != null && shell.activeRunId !== null) {
1007 yield* settleAfterRun({
1008 projectId: shell.projectId,
1009 threadId: shell.id,
1010 runId: shell.activeRunId,
1011 }).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(layerScope));
1012 return { settlesWhenTurnEnds: true } as const;
1013 }
1014 const result = yield* dispatch({
1015 type: "thread.settle",
1016 commandId: input.commandId,
1017 threadId: input.threadId,
1018 });
1019 return { sequence: result.sequence };
1020 });
1021
1022 const interruptThread: ThreadManagementServiceShape["interruptThread"] = Effect.fn(
1023 "ThreadManagementService.interruptThread",
1024 )(function* (input) {
1025 const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
1026 const explicitRun =
1027 input.runId === undefined
1028 ? undefined
1029 : target.runs.find((candidate) => candidate.id === input.runId);
1030 if (input.runId !== undefined && explicitRun === undefined) {
1031 return yield* new ThreadManagementRunNotFoundError({
1032 threadId: input.threadId,
1033 runId: input.runId,
1034 });
1035 }
1036 if (explicitRun !== undefined && isTerminalRunStatus(explicitRun.status)) {
1037 return {
1038 type: "already_terminal",
1039 run: explicitRun as OrchestrationV2Run & {
1040 readonly status: ThreadManagementTerminalRunStatus;
1041 },
1042 } as const;
1043 }
1044 const interruptibleRun = latestActiveRun(target);
1045 if (interruptibleRun === undefined) {
1046 if (input.runId === undefined) {
1047 return { type: "no_active_run" } as const;
1048 }
1049 return yield* new ThreadManagementThreadNotInterruptibleError({
1050 threadId: input.threadId,
1051 runId: input.runId,
1052 });
1053 }
1054 if (input.runId !== undefined && interruptibleRun.id !== input.runId) {
1055 return yield* new ThreadManagementThreadNotInterruptibleError({
1056 threadId: input.threadId,
1057 runId: input.runId,
1058 });
1059 }
1060 const dispatch = yield* orchestrator.dispatch({
1061 type: "run.interrupt",
1062 commandId: input.commandId,
1063 threadId: input.threadId,
1064 runId: interruptibleRun.id,
1065 ...(input.reason === undefined ? {} : { reason: input.reason }),
1066 });
1067 return { type: "interrupt_requested", run: interruptibleRun, dispatch } as const;
1068 });
1069
1070 const stopWorkflow: ThreadManagementServiceShape["stopWorkflow"] = Effect.fn(
1071 "ThreadManagementService.stopWorkflow",
1072 )(
1073 function* (input) {
1074 const records = yield* orchestrator
1075 .getThreadRecords(input.threadId, ["subagents", "runs", "providerThreads"])
1076 .pipe(
1077 Effect.mapError(
1078 (cause) =>
1079 new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable", cause }),
1080 ),
1081 );
1082 if (records.thread.deletedAt !== null) {
1083 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable" });
1084 }
1085 // Check mode limits under the lock so users cannot raise modes between validation and Stop.
1086 const limit = yield* DispatchModeLimit;
1087 const exceeded =
1088 limit === undefined ? undefined : exceededDispatchModeLimit(limit, records.thread);
1089 if (limit !== undefined && exceeded !== undefined) {
1090 if (limit.refused !== undefined) {
1091 yield* Ref.set(limit.refused, {
1092 threadId: input.threadId,
1093 runtimeMode: records.thread.runtimeMode,
1094 interactionMode: records.thread.interactionMode,
1095 mode: exceeded,
1096 });
1097 }
1098 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable" });
1099 }
1100 const task = records.subagents.find((candidate) => candidate.id === input.subagentId);
1101 if (
1102 task === undefined ||
1103 task.threadId !== input.threadId ||
1104 task.workflow === undefined ||
1105 task.status !== "running"
1106 ) {
1107 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "not-running" });
1108 }
1109 if (task.origin !== "provider_native" || task.driver !== "claudeAgent") {
1110 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unsupported" });
1111 }
1112 const providerThreadId =
1113 task.providerThreadId ??
1114 records.runs.find((run) => run.id === task.runId)?.providerThreadId;
1115 const providerThread = records.providerThreads.find(
1116 (candidate) =>
1117 candidate.id === providerThreadId &&
1118 candidate.appThreadId === input.threadId &&
1119 candidate.providerInstanceId === task.providerInstanceId &&
1120 candidate.driver === task.driver,
1121 );
1122 const taskId = task.nativeTaskRef?.nativeId;
1123 if (providerThread?.providerSessionId == null || taskId == null || taskId.length === 0) {
1124 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable" });
1125 }
1126 const runtime = yield* sessions
1127 .get(providerThread.providerSessionId)
1128 .pipe(
1129 Effect.mapError(
1130 (cause) =>
1131 new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable", cause }),
1132 ),
1133 );
1134 if (Option.isNone(runtime)) {
1135 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable" });
1136 }
1137 if (runtime.value.stopTask === undefined) {
1138 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unsupported" });
1139 }
1140 // Bounded so a provider that never answers cannot hold the thread lock.
1141 yield* runtime.value.stopTask({ providerThread, taskId }).pipe(
1142 Effect.timeout("15 seconds"),
1143 Effect.mapError(
1144 (cause) =>
1145 new OrchestrationV2StopWorkflowError({
1146 ...input,
1147 reason: "stop-failed",
1148 cause,
1149 }),
1150 ),
1151 );
1152 },
1153 (effect, input) => effect.pipe((effect) => threadDispatch.withLock(input.threadId, effect)),
1154 );
1155
1156 const awaitBackgroundTasks: ThreadManagementServiceShape["awaitBackgroundTasks"] = Effect.fn(
1157 "ThreadManagementService.awaitBackgroundTasks",
1158 )(function* (input) {
1159 const unavailable = (cause?: unknown) =>
1160 new ThreadManagementBackgroundWaitError({
1161 threadId: input.threadId,
1162 reason: "unavailable",
1163 ...(cause === undefined ? {} : { cause }),
1164 });
1165 const records = yield* orchestrator
1166 .getThreadRecords(input.threadId, ["providerThreads"])
1167 .pipe(Effect.mapError(unavailable));
1168 const providerThread = records.providerThreads.find(
1169 (candidate) =>
1170 candidate.id === records.thread.activeProviderThreadId &&
1171 candidate.appThreadId === input.threadId,
1172 );
1173 if (records.thread.deletedAt !== null || providerThread?.providerSessionId == null) {
1174 return yield* unavailable();
1175 }
1176 const runtime = yield* sessions
1177 .get(providerThread.providerSessionId)
1178 .pipe(Effect.mapError(unavailable));
1179 if (Option.isNone(runtime)) {
1180 return yield* unavailable();
1181 }
1182 if (runtime.value.awaitBackgroundTasks === undefined) {
1183 return yield* new ThreadManagementBackgroundWaitError({
1184 threadId: input.threadId,
1185 reason: "unsupported",
1186 });
1187 }
1188 const { matched } = yield* runtime.value
1189 .awaitBackgroundTasks({ providerThread, taskIds: input.taskIds, awaited: input.awaited })
1190 .pipe(
1191 Effect.timeout("15 seconds"),
1192 Effect.mapError(
1193 (cause) =>
1194 new ThreadManagementBackgroundWaitError({
1195 threadId: input.threadId,
1196 reason: "failed",
1197 cause,
1198 }),
1199 ),
1200 );
1201 const matchedIds = new Set(matched);
1202 return { matched, unmatched: input.taskIds.filter((taskId) => !matchedIds.has(taskId)) };
1203 });
1204
1205 const stopDelegatedTasks: ThreadManagementServiceShape["stopDelegatedTasks"] = Effect.fn(
1206 "ThreadManagementService.stopDelegatedTasks",
1207 )(function* (input) {
1208 const { subagents } = yield* orchestrator.getThreadRecords(input.threadId, ["subagents"]);
1209 const failures: Array<
1210 Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
1211 > = [];
1212 const stoppedChildThreadIds = new Set<ThreadId>();
1213 for (const task of subagents) {
1214 if (task.origin !== "app_owned") continue;
1215 if (task.childThreadId === null) {
1216 // A task in a linked environment ends here; its follower then stops it there.
1217 // One with its result keeps it, but its thread there may run follow-up work.
1218 if (task.remoteChild === undefined) continue;
1219 const commandId = CommandId.make(`${input.commandId}:stop:${task.id}`);
1220 yield* dispatch(
1221 task.result === null
1222 ? {
1223 type: "delegated_task.remote.complete",
1224 commandId,
1225 parentThreadId: input.threadId,
1226 taskId: task.id,
1227 status: "interrupted",
1228 result:
1229 input.reason === undefined
1230 ? "Stopped with its parent."
1231 : `Stopped with its parent: ${input.reason}`,
1232 }
1233 : {
1234 type: "delegated_task.remote.stop",
1235 commandId,
1236 parentThreadId: input.threadId,
1237 taskId: task.id,
1238 },
1239 ).pipe(
1240 Effect.catch((error) =>
1241 Effect.logWarning("Unable to stop a delegated task", {
1242 parentThreadId: input.threadId,
1243 taskId: task.id,
1244 error,
1245 }).pipe(Effect.andThen(Effect.sync(() => failures.push(error)))),
1246 ),
1247 );
1248 continue;
1249 }
1250 const threadId = task.childThreadId;
1251 // Follow-up tasks reuse a child thread; walk its subtree only once.
1252 if (stoppedChildThreadIds.has(threadId)) continue;
1253 stoppedChildThreadIds.add(threadId);
1254 yield* dispatch({
1255 type: "thread.stop",
1256 commandId: CommandId.make(`${input.commandId}:stop:${threadId}`),
1257 threadId,
1258 stopDelegatedTasks: false,
1259 ...(input.reason === undefined ? {} : { reason: input.reason }),
1260 }).pipe(
1261 Effect.andThen(stopDelegatedTasks({ ...input, threadId })),
1262 Effect.catch((error) =>
1263 Effect.logWarning("Unable to stop a delegated task", {
1264 parentThreadId: input.threadId,
1265 threadId,
1266 error,
1267 }).pipe(Effect.andThen(Effect.sync(() => failures.push(error)))),
1268 ),
1269 );
1270 }
1271 if (failures[0] !== undefined) return yield* failures[0];
1272 });
1273
1274 return ThreadManagementService.of({
1275 ensureLegacyTranscript,
1276 searchThreadStream: (input) =>
1277 Stream.unwrap(
1278 ensureProjectionTranscript(input.threadId).pipe(
1279 Effect.as(orchestrator.searchThreadStream(input)),
1280 ),
1281 ),
1282 searchThread: Effect.fn("ThreadManagementService.searchThread")(function (input) {
1283 return ensureProjectionTranscript(input.threadId).pipe(
1284 Effect.andThen(orchestrator.searchThread(input)),
1285 );
1286 }),
1287 dispatch,
1288 getThreadHistoryPage: Effect.fn("ThreadManagementService.getThreadHistoryPage")(
1289 function (threadId, cursor, throughEntryId, conversationOnly, workMode) {
1290 return ensureProjectionTranscript(threadId).pipe(
1291 Effect.andThen(
1292 orchestrator.getThreadHistoryPage(
1293 threadId,
1294 cursor,
1295 throughEntryId,
1296 conversationOnly,
1297 workMode,
1298 ),
1299 ),
1300 );
1301 },
1302 ),
1303 getTimelinePage: Effect.fn("ThreadManagementService.getTimelinePage")(
1304 function (threadId, options) {
1305 return ensureProjectionTranscript(threadId).pipe(
1306 Effect.andThen(orchestrator.getTimelinePage(threadId, options)),
1307 );
1308 },
1309 ),
1310 getMessageCount: Effect.fn("ThreadManagementService.getMessageCount")(function (threadId) {
1311 return ensureProjectionTranscript(threadId).pipe(
1312 Effect.andThen(orchestrator.getMessageCount(threadId)),
1313 );
1314 }),
1315 getTurnItem: Effect.fn("ThreadManagementService.getTurnItem")(function (input) {
1316 return ensureProjectionTranscript(input.threadId).pipe(
1317 Effect.andThen(orchestrator.getTurnItem(input)),
1318 Effect.map((item) => ({ item: item === null ? null : projectTurnItemForDetail(item) })),
1319 );
1320 }),
1321 getThreadRecords: Effect.fn("ThreadManagementService.getThreadRecords")(
1322 function (threadId, fields, filter) {
1323 return ensureProjectionTranscript(threadId).pipe(
1324 Effect.andThen(orchestrator.getThreadRecords(threadId, fields, filter)),
1325 );
1326 },
1327 ),
1328 getThreadProjection,
1329 getCheckpointContext,
1330 getThreadSnapshot,
1331 getThreadTranscript,
1332 getThreadSnapshotWindow,
1333 getProjectThreadRecords,
1334 getShellSnapshot: orchestrator.getShellSnapshot,
1335 listActiveSubagentThreadIds: orchestrator.listActiveSubagentThreadIds,
1336 listOlderSettledThreads: orchestrator.listOlderSettledThreads,
1337 readShellSnapshot: orchestrator.readShellSnapshot,
1338 getThreadShell: orchestrator.getThreadShell,
1339 listProjectThreads,
1340 sendToThread,
1341 assertProviderInstanceEnabled,
1342 isProviderInstanceEnabledForProject,
1343 hasReceipt,
1344 waitForThread,
1345 settleAfterRun,
1346 settleThread,
1347 interruptThread,
1348 stopDelegatedTasks,
1349 stopWorkflow,
1350 awaitBackgroundTasks,
1351 getThreadEventSequence: orchestrator.getThreadEventSequence,
1352 recoverDelegatedTask: orchestrator.recoverDelegatedTask,
1353 delegatedTaskResultPending: orchestrator.delegatedTaskResultPending,
1354 streamStoredEvents: orchestrator.streamStoredEvents,
1355 streamStoredEventsFrom: orchestrator.streamStoredEventsFrom,
1356 streamDomainEvents: orchestrator.streamDomainEvents,
1357 });
1358});
1359
1360const layerLegacyV1ThreadImporterNoop = Layer.succeed(
1361 LegacyV1ThreadImporter.LegacyV1ThreadImporter,
1362 LegacyV1ThreadImporter.LegacyV1ThreadImporter.of({
1363 pendingThreadCount: Effect.succeed(0),
1364 reconcileShells: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
1365 ensureTranscript: Effect.fn("LegacyV1ThreadImporter.ensureTranscript")(function () {
1366 return Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 });
1367 }),
1368 importPendingTranscripts: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
1369 }),
1370);
1371
1372export const layer: Layer.Layer<
1373 ThreadManagementService,
1374 never,
1375 | Orchestrator.OrchestratorV2
1376 | ProviderSessionManager.ProviderSessionManagerV2
1377 | ServerSettings.ServerSettingsService
1378 | CommandReceiptStore.CommandReceiptStoreV2
1379> = Layer.effect(ThreadManagementService, make).pipe(
1380 Layer.provide(layerLegacyV1ThreadImporterNoop),
1381 Layer.provide(ThreadCommandExecutor.layer),
1382);
1383
1384export const layerWithLegacyImporter: Layer.Layer<
1385 ThreadManagementService,
1386 never,
1387 | LegacyV1ThreadImporter.LegacyV1ThreadImporter
1388 | Orchestrator.OrchestratorV2
1389 | ProviderSessionManager.ProviderSessionManagerV2
1390 | ServerSettings.ServerSettingsService
1391 | CommandReceiptStore.CommandReceiptStoreV2
1392> = Layer.effect(ThreadManagementService, make).pipe(Layer.provide(ThreadCommandExecutor.layer));