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

ThreadManagementService.ts

1,404 lines52.6 KB

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