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