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} from "./ProjectionStore.ts";
10import {
11 type ChatAttachment,
12 CommandId,
13 MessageId,
14 OrchestrationV2StopWorkflowError,
15 type OrchestrationV2StopWorkflowInput,
16 type ModelSelection,
17 type OrchestrationV2Actor,
18 type OrchestrationV2Command,
19 type OrchestrationV2GetTurnItemResult,
20 type OrchestrationV2ServerCommand,
21 type OrchestrationV2ConversationMessage,
22 type OrchestrationV2CreationSource,
23 type OrchestrationV2Run,
24 type OrchestrationV2ThreadShellSnapshot,
25 type OrchestrationV2ThreadProjection,
26 type OrchestrationV2ThreadShell,
27 type OrchestrationV2TurnItem,
28 ProjectId,
29 RunId,
30 type ScheduledTaskId,
31 ThreadId,
32 type TurnItemId,
33} from "@t3tools/contracts";
34import * as Context from "effect/Context";
35import * as DateTime from "effect/DateTime";
36import * as Duration from "effect/Duration";
37import * as Effect from "effect/Effect";
38import * as Layer from "effect/Layer";
39import * as Option from "effect/Option";
40import * as Ref from "effect/Ref";
41import * as Schema from "effect/Schema";
42import * as Stream from "effect/Stream";
43
44import * as Orchestrator from "./Orchestrator.ts";
45import * as ProviderSessionManager from "./ProviderSessionManager.ts";
46import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
47import { DispatchModeLimit, exceededDispatchModeLimit } from "./DispatchModeLimit.ts";
48import { projectTurnItemForDetail } from "./WireProjection.ts";
49import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts";
50
51export type ThreadManagementSendMode = "auto" | "queue" | "steer" | "restart";
52
53export interface ThreadManagementProvenance {
54 readonly createdBy: OrchestrationV2Actor;
55 readonly creationSource: OrchestrationV2CreationSource;
56}
57
58export function withCreationProvenance(
59 command: OrchestrationV2Command,
60 provenance: ThreadManagementProvenance,
61): OrchestrationV2Command {
62 switch (command.type) {
63 case "thread.create":
64 case "message.dispatch":
65 case "thread.fork":
66 case "thread.merge_back":
67 case "delegated_task.request":
68 return { ...command, ...provenance };
69 default:
70 return command;
71 }
72}
73
74export function existingThreadIdsForCommand(
75 command: OrchestrationV2ServerCommand,
76): ReadonlyArray<ThreadId> {
77 switch (command.type) {
78 case "thread.create":
79 return [];
80 // Read-state commands only rewrite the thread payload's visited/unread
81 // watermark; they never touch messages, so they do not need the imported
82 // v1 transcript hydrated first. Visits fire on every thread-activity bump
83 // while a thread is open, so keeping them off the import path matters.
84 case "thread.visit":
85 case "thread.mark-unread":
86 return [];
87 case "thread.fork":
88 return [command.sourceThreadId];
89 case "thread.merge_back":
90 return command.sourceThreadId === command.targetThreadId
91 ? [command.sourceThreadId]
92 : [command.sourceThreadId, command.targetThreadId];
93 case "delegated_task.request":
94 case "delegated_task.wake-policy":
95 case "delegated_task.completion-delivery.acknowledge":
96 case "delegated_task.completion-delivery.dispose":
97 return [command.parentThreadId];
98 case "thread.created.record":
99 return command.parentThreadId === command.targetThreadId
100 ? [command.parentThreadId]
101 : [command.parentThreadId, command.targetThreadId];
102 default:
103 return [command.threadId];
104 }
105}
106
107export type ThreadManagementTerminalRunStatus = Extract<
108 OrchestrationV2Run["status"],
109 "completed" | "failed" | "cancelled" | "interrupted" | "rolled_back"
110>;
111
112export interface ThreadManagementSendInput {
113 readonly projectId: ProjectId;
114 readonly commandId: CommandId;
115 readonly threadId: ThreadId;
116 readonly messageId: MessageId;
117 readonly scheduledTaskId?: ScheduledTaskId;
118 readonly senderThreadId?: ThreadId;
119 readonly text: string;
120 readonly attachments: ReadonlyArray<ChatAttachment>;
121 readonly modelSelection?: ModelSelection;
122 readonly mode: ThreadManagementSendMode;
123 readonly createdBy: OrchestrationV2Actor;
124 readonly creationSource: OrchestrationV2CreationSource;
125}
126
127export interface ThreadManagementSendResult {
128 readonly dispatch: Orchestrator.OrchestratorV2DispatchResult;
129 readonly projection: Pick<
130 OrchestrationV2ThreadProjection,
131 "thread" | "runs" | "messages" | "turnItems"
132 >;
133 readonly message: OrchestrationV2ConversationMessage;
134 readonly run: OrchestrationV2Run;
135 /** Null for queued sends: the user turn item materializes when the queued turn starts. */
136 readonly turnItem: Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> | null;
137 readonly delivery: "started" | "queued" | "steered" | "restarted";
138}
139
140export interface ThreadManagementWaitInput {
141 readonly projectId: ProjectId;
142 readonly threadId: ThreadId;
143 readonly runId?: RunId;
144 readonly timeoutMs: number;
145}
146
147export interface ThreadManagementWaitResult {
148 readonly threadId: ThreadId;
149 readonly run: OrchestrationV2Run | null;
150 readonly timedOut: boolean;
151}
152
153export interface ThreadManagementInterruptInput {
154 readonly projectId: ProjectId;
155 readonly commandId: CommandId;
156 readonly threadId: ThreadId;
157 readonly runId?: RunId;
158 readonly reason?: string;
159}
160
161export type ThreadManagementInterruptResult =
162 | {
163 readonly type: "interrupt_requested";
164 readonly run: OrchestrationV2Run;
165 readonly dispatch: Orchestrator.OrchestratorV2DispatchResult;
166 }
167 | { readonly type: "no_active_run" }
168 | {
169 readonly type: "already_terminal";
170 readonly run: OrchestrationV2Run & { readonly status: ThreadManagementTerminalRunStatus };
171 };
172
173export class ThreadManagementThreadNotFoundError extends Schema.TaggedError<ThreadManagementThreadNotFoundError>()(
174 "ThreadManagementThreadNotFoundError",
175 {
176 projectId: ProjectId,
177 threadId: ThreadId,
178 },
179) {
180 override get message(): string {
181 return `Thread ${this.threadId} was not found in project ${this.projectId}.`;
182 }
183}
184
185export class ThreadManagementRunNotFoundError extends Schema.TaggedError<ThreadManagementRunNotFoundError>()(
186 "ThreadManagementRunNotFoundError",
187 {
188 threadId: ThreadId,
189 runId: RunId,
190 },
191) {
192 override get message(): string {
193 return `Run ${this.runId} does not belong to thread ${this.threadId}.`;
194 }
195}
196
197export class ThreadManagementThreadArchivedError extends Schema.TaggedError<ThreadManagementThreadArchivedError>()(
198 "ThreadManagementThreadArchivedError",
199 {
200 threadId: ThreadId,
201 },
202) {
203 override get message(): string {
204 return `Thread ${this.threadId} is archived and cannot receive messages.`;
205 }
206}
207
208export class ThreadManagementNoSteerableRunError extends Schema.TaggedError<ThreadManagementNoSteerableRunError>()(
209 "ThreadManagementNoSteerableRunError",
210 {
211 threadId: ThreadId,
212 mode: Schema.Literals(["steer", "restart"]),
213 },
214) {
215 override get message(): string {
216 return `Thread ${this.threadId} has no running turn that can be ${this.mode === "steer" ? "steered" : "restarted"}.`;
217 }
218}
219
220export class ThreadManagementThreadNotInterruptibleError extends Schema.TaggedError<ThreadManagementThreadNotInterruptibleError>()(
221 "ThreadManagementThreadNotInterruptibleError",
222 {
223 threadId: ThreadId,
224 runId: RunId,
225 },
226) {
227 override get message(): string {
228 return `Run ${this.runId} is not currently interruptible.`;
229 }
230}
231
232export class ThreadManagementProjectionLoadError extends Schema.TaggedError<ThreadManagementProjectionLoadError>()(
233 "ThreadManagementProjectionLoadError",
234 {
235 projectId: ProjectId,
236 threadId: ThreadId,
237 cause: Schema.Defect(),
238 },
239) {
240 override get message(): string {
241 return `Unable to load thread ${this.threadId} in project ${this.projectId}.`;
242 }
243}
244
245export class ThreadManagementProjectThreadsListError extends Schema.TaggedError<ThreadManagementProjectThreadsListError>()(
246 "ThreadManagementProjectThreadsListError",
247 {
248 projectId: ProjectId,
249 cause: Schema.Defect(),
250 },
251) {
252 override get message(): string {
253 return `Unable to list threads in project ${this.projectId}.`;
254 }
255}
256
257export class ThreadManagementDurableRunProjectionError extends Schema.TaggedError<ThreadManagementDurableRunProjectionError>()(
258 "ThreadManagementDurableRunProjectionError",
259 {
260 threadId: ThreadId,
261 messageId: MessageId,
262 },
263) {
264 override get message(): string {
265 return `Message ${this.messageId} was accepted on thread ${this.threadId} without a durable run projection.`;
266 }
267}
268
269export const ThreadManagementError = Schema.Union([
270 ThreadManagementThreadNotFoundError,
271 ThreadManagementRunNotFoundError,
272 ThreadManagementThreadArchivedError,
273 ThreadManagementNoSteerableRunError,
274 ThreadManagementThreadNotInterruptibleError,
275 ThreadManagementProjectionLoadError,
276 ThreadManagementProjectThreadsListError,
277 ThreadManagementDurableRunProjectionError,
278]);
279export type ThreadManagementError = typeof ThreadManagementError.Type;
280
281type ThreadManagementFailure = ThreadManagementError | Orchestrator.OrchestratorV2Error;
282
283export interface ThreadManagementServiceShape {
284 readonly searchThreadStream: (
285 input: OrchestrationV2SearchThreadInput,
286 ) => Stream.Stream<OrchestrationV2SearchThreadResult, Orchestrator.OrchestratorV2Error>;
287 readonly searchThread: (
288 input: OrchestrationV2SearchThreadInput,
289 ) => Effect.Effect<OrchestrationV2SearchThreadResult, Orchestrator.OrchestratorV2Error>;
290 readonly ensureLegacyTranscript: (
291 threadId: ThreadId,
292 ) => Effect.Effect<void, LegacyV1ThreadImporter.LegacyV1ThreadImportError>;
293 readonly dispatch: (
294 command: OrchestrationV2ServerCommand,
295 ) => Effect.Effect<Orchestrator.OrchestratorV2DispatchResult, Orchestrator.OrchestratorV2Error>;
296 readonly getThreadHistoryPage: Orchestrator.OrchestratorV2["Service"]["getThreadHistoryPage"];
297 readonly getTimelinePage: Orchestrator.OrchestratorV2["Service"]["getTimelinePage"];
298 readonly getMessageCount: Orchestrator.OrchestratorV2["Service"]["getMessageCount"];
299 /**
300 * One turn item with the input and output the thread stream withholds,
301 * bounded for the wire. Clients fetch it when a tool row is expanded.
302 */
303 readonly getTurnItem: (input: {
304 readonly threadId: ThreadId;
305 readonly itemId: TurnItemId;
306 }) => Effect.Effect<OrchestrationV2GetTurnItemResult, Orchestrator.OrchestratorV2Error>;
307 readonly getThreadRecords: Orchestrator.OrchestratorV2["Service"]["getThreadRecords"];
308 readonly getThreadProjection: (
309 threadId: ThreadId,
310 ) => Effect.Effect<OrchestrationV2ThreadProjection, Orchestrator.OrchestratorV2Error>;
311 readonly getCheckpointContext: Orchestrator.OrchestratorV2["Service"]["getCheckpointContext"];
312 readonly getThreadSnapshot: Orchestrator.OrchestratorV2["Service"]["getThreadSnapshot"];
313 readonly getThreadSnapshotWindow: Orchestrator.OrchestratorV2["Service"]["getThreadSnapshotWindow"];
314 readonly getProjectThreadRecords: <K extends ProjectionRecordField>(
315 input: { readonly projectId: ProjectId; readonly threadId: ThreadId },
316 fields: ReadonlyArray<K>,
317 filter?: ProjectionRecordFilter,
318 ) => Effect.Effect<
319 ProjectionRecords<K>,
320 ThreadManagementProjectionLoadError | ThreadManagementThreadNotFoundError
321 >;
322 readonly getProjectThread: (input: {
323 readonly projectId: ProjectId;
324 readonly threadId: ThreadId;
325 }) => Effect.Effect<OrchestrationV2ThreadProjection, ThreadManagementError>;
326 readonly getShellSnapshot: (options?: {
327 readonly location?: "active" | "archive";
328 }) => Effect.Effect<OrchestrationV2ThreadShellSnapshot, Orchestrator.OrchestratorV2Error>;
329 readonly readShellSnapshot: (options?: {
330 readonly location?: "active" | "archive";
331 }) => Effect.Effect<
332 Effect.Effect<OrchestrationV2ThreadShellSnapshot, Orchestrator.OrchestratorV2Error>,
333 Orchestrator.OrchestratorV2Error
334 >;
335 readonly getThreadShell: Orchestrator.OrchestratorV2["Service"]["getThreadShell"];
336 readonly listProjectThreads: (input: {
337 readonly projectId: ProjectId;
338 readonly includeSubagents: boolean;
339 }) => Effect.Effect<ReadonlyArray<OrchestrationV2ThreadShell>, ThreadManagementError>;
340 readonly sendToThread: (
341 input: ThreadManagementSendInput,
342 ) => Effect.Effect<ThreadManagementSendResult, ThreadManagementFailure>;
343 readonly waitForThread: (
344 input: ThreadManagementWaitInput,
345 ) => Effect.Effect<ThreadManagementWaitResult, ThreadManagementError>;
346 /**
347 * Waits for `runId` to end, then settles the thread if the run completed.
348 * Settling stops the provider session, so an agent that settles its own
349 * thread uses this to wait for its turn to end. A run that ends any other
350 * way leaves the thread active, as does anything `thread.settle` refuses
351 * then, such as a queued message.
352 */
353 readonly settleAfterRun: (input: {
354 readonly projectId: ProjectId;
355 readonly threadId: ThreadId;
356 readonly runId: RunId;
357 }) => Effect.Effect<void, ThreadManagementFailure>;
358 /**
359 * Settles a thread. When the thread's own agent asks, it is mid-turn, so
360 * the thread settles through `settleAfterRun` once that turn ends.
361 */
362 readonly settleThread: (input: {
363 readonly threadId: ThreadId;
364 readonly commandId: CommandId;
365 readonly byOwnAgent: boolean;
366 }) => Effect.Effect<
367 { readonly sequence: number } | { readonly settlesWhenTurnEnds: true },
368 Orchestrator.OrchestratorV2Error
369 >;
370 readonly interruptThread: (
371 input: ThreadManagementInterruptInput,
372 ) => Effect.Effect<ThreadManagementInterruptResult, ThreadManagementFailure>;
373 /**
374 * Asks the provider to stop a running workflow coordinator. The provider's
375 * own terminal notification then settles the coordinator and its members.
376 */
377 readonly stopWorkflow: (
378 input: OrchestrationV2StopWorkflowInput,
379 ) => Effect.Effect<void, OrchestrationV2StopWorkflowError>;
380 /**
381 * Sends `thread.stop` to every delegated task under a thread, depth first. Their command IDs
382 * derive from `commandId`, so a retry repeats nothing that already stopped. A task that
383 * cannot be stopped does not keep the others running: all are tried, then it fails.
384 */
385 readonly stopDelegatedTasks: (input: {
386 readonly threadId: ThreadId;
387 readonly commandId: CommandId;
388 readonly reason?: string | undefined;
389 }) => Effect.Effect<void, Orchestrator.OrchestratorV2Error>;
390 readonly getThreadEventSequence: Orchestrator.OrchestratorV2["Service"]["getThreadEventSequence"];
391 readonly recoverDelegatedTask: Orchestrator.OrchestratorV2["Service"]["recoverDelegatedTask"];
392 readonly delegatedTaskResultPending: Orchestrator.OrchestratorV2["Service"]["delegatedTaskResultPending"];
393 readonly streamStoredEvents: Orchestrator.OrchestratorV2["Service"]["streamStoredEvents"];
394 readonly streamStoredEventsFrom: Orchestrator.OrchestratorV2["Service"]["streamStoredEventsFrom"];
395 readonly streamDomainEvents: Orchestrator.OrchestratorV2["Service"]["streamDomainEvents"];
396}
397
398export class ThreadManagementService extends Context.Service<
399 ThreadManagementService,
400 ThreadManagementServiceShape
401>()("t3/orchestration-v2/ThreadManagementService") {}
402
403export function isActiveRun(run: OrchestrationV2Run): boolean {
404 return (
405 run.status === "preparing" ||
406 run.status === "starting" ||
407 run.status === "running" ||
408 run.status === "waiting"
409 );
410}
411
412export function isTerminalRunStatus(
413 status: OrchestrationV2Run["status"],
414): status is ThreadManagementTerminalRunStatus {
415 return (
416 status === "completed" ||
417 status === "failed" ||
418 status === "cancelled" ||
419 status === "interrupted" ||
420 status === "rolled_back"
421 );
422}
423
424export function latestRun(
425 projection: Pick<OrchestrationV2ThreadProjection, "runs">,
426): OrchestrationV2Run | undefined {
427 return projection.runs.toSorted((left, right) => right.ordinal - left.ordinal)[0];
428}
429
430export function latestActiveRun(
431 projection: Pick<OrchestrationV2ThreadProjection, "runs">,
432): OrchestrationV2Run | undefined {
433 return projection.runs
434 .filter(isActiveRun)
435 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
436}
437
438function latestSteerableRun(
439 projection: Pick<OrchestrationV2ThreadProjection, "runs" | "providerTurns">,
440): OrchestrationV2Run | undefined {
441 return projection.runs
442 .filter(
443 (run) =>
444 run.status === "running" &&
445 run.activeAttemptId !== null &&
446 projection.providerTurns.some(
447 (turn) => turn.runAttemptId === run.activeAttemptId && turn.status === "running",
448 ),
449 )
450 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
451}
452
453const SETTLE_AFTER_RUN_WAIT_MS = 24 * 60 * 60 * 1_000;
454
455const make = Effect.gen(function* () {
456 const threadDispatch = yield* ThreadCommandExecutor.ThreadCommandExecutor;
457 const orchestrator = yield* Orchestrator.OrchestratorV2;
458 const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
459 const layerScope = yield* Effect.scope;
460 const legacyImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
461
462 const ensureLegacyTranscript = Effect.fn(
463 "orchestrationV2.threadManagement.ensureLegacyTranscript",
464 )(function* (threadId: ThreadId) {
465 yield* legacyImporter.ensureTranscript(threadId).pipe(
466 Effect.tapError((cause) =>
467 Effect.logWarning("Unable to hydrate migrated v1 thread transcript", {
468 threadId,
469 cause,
470 }),
471 ),
472 );
473 });
474
475 const ensureProjectionTranscript = (threadId: ThreadId) =>
476 ensureLegacyTranscript(threadId).pipe(
477 Effect.mapError(
478 (cause) =>
479 new Orchestrator.OrchestratorProjectionError({
480 threadId,
481 cause,
482 }),
483 ),
484 );
485
486 const ensureCommandTranscripts = Effect.fn(
487 "orchestrationV2.threadManagement.ensureCommandTranscripts",
488 )(function* (command: OrchestrationV2ServerCommand) {
489 yield* Effect.forEach(
490 existingThreadIdsForCommand(command),
491 (threadId) => ensureLegacyTranscript(threadId),
492 { discard: true },
493 ).pipe(
494 Effect.mapError(
495 (cause) =>
496 new Orchestrator.OrchestratorDispatchError({
497 commandId: command.commandId,
498 commandType: command.type,
499 cause,
500 }),
501 ),
502 );
503 });
504
505 const getThreadProjection: ThreadManagementServiceShape["getThreadProjection"] = (threadId) =>
506 ensureProjectionTranscript(threadId).pipe(
507 Effect.andThen(orchestrator.getThreadProjection(threadId)),
508 );
509
510 const getCheckpointContext: ThreadManagementServiceShape["getCheckpointContext"] = (threadId) =>
511 ensureProjectionTranscript(threadId).pipe(
512 Effect.andThen(orchestrator.getCheckpointContext(threadId)),
513 );
514
515 const getThreadSnapshot: ThreadManagementServiceShape["getThreadSnapshot"] = (threadId) =>
516 ensureProjectionTranscript(threadId).pipe(
517 Effect.andThen(orchestrator.getThreadSnapshot(threadId)),
518 );
519 const getThreadSnapshotWindow: ThreadManagementServiceShape["getThreadSnapshotWindow"] = (
520 threadId,
521 options,
522 ) =>
523 ensureProjectionTranscript(threadId).pipe(
524 Effect.andThen(orchestrator.getThreadSnapshotWindow(threadId, options)),
525 );
526
527 const dispatch: ThreadManagementServiceShape["dispatch"] = (command) =>
528 ensureCommandTranscripts(command).pipe(Effect.andThen(orchestrator.dispatch(command)));
529
530 const getProjectThread: ThreadManagementServiceShape["getProjectThread"] = (input) =>
531 getThreadProjection(input.threadId).pipe(
532 Effect.mapError(
533 (cause) =>
534 new ThreadManagementProjectionLoadError({
535 projectId: input.projectId,
536 threadId: input.threadId,
537 cause,
538 }),
539 ),
540 Effect.flatMap((projection) =>
541 projection.thread.projectId === input.projectId && projection.thread.deletedAt === null
542 ? Effect.succeed(projection)
543 : Effect.fail(
544 new ThreadManagementThreadNotFoundError({
545 projectId: input.projectId,
546 threadId: input.threadId,
547 }),
548 ),
549 ),
550 );
551
552 const getProjectThreadRecords: ThreadManagementServiceShape["getProjectThreadRecords"] = (
553 input,
554 fields,
555 filter,
556 ) =>
557 ensureProjectionTranscript(input.threadId)
558 .pipe(Effect.andThen(orchestrator.getThreadRecords(input.threadId, fields, filter)))
559 .pipe(
560 Effect.mapError(
561 (cause) =>
562 new ThreadManagementProjectionLoadError({
563 projectId: input.projectId,
564 threadId: input.threadId,
565 cause,
566 }),
567 ),
568 Effect.flatMap((projection) =>
569 projection.thread.projectId === input.projectId && projection.thread.deletedAt === null
570 ? Effect.succeed(projection)
571 : Effect.fail(
572 new ThreadManagementThreadNotFoundError({
573 projectId: input.projectId,
574 threadId: input.threadId,
575 }),
576 ),
577 ),
578 );
579
580 const listProjectThreads: ThreadManagementServiceShape["listProjectThreads"] = (input) =>
581 orchestrator.getShellSnapshot({ projectId: input.projectId, location: "active" }).pipe(
582 Effect.mapError(
583 (cause) =>
584 new ThreadManagementProjectThreadsListError({
585 projectId: input.projectId,
586 cause,
587 }),
588 ),
589 Effect.map((snapshot) =>
590 snapshot.threads
591 .filter(
592 (thread) =>
593 input.includeSubagents || thread.lineage.relationshipToParent !== "subagent",
594 )
595 .toSorted(
596 (left, right) =>
597 DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt) ||
598 right.id.localeCompare(left.id),
599 ),
600 ),
601 );
602
603 const sendToThread: ThreadManagementServiceShape["sendToThread"] = (input) =>
604 Effect.gen(function* () {
605 const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
606 if (target.thread.archivedAt !== null) {
607 return yield* new ThreadManagementThreadArchivedError({
608 threadId: input.threadId,
609 });
610 }
611
612 const steerableRun = latestSteerableRun(target);
613 let dispatchMode: Extract<
614 OrchestrationV2Command,
615 { readonly type: "message.dispatch" }
616 >["dispatchMode"];
617 if (input.mode === "steer" || input.mode === "restart") {
618 if (steerableRun === undefined) {
619 return yield* new ThreadManagementNoSteerableRunError({
620 threadId: input.threadId,
621 mode: input.mode,
622 });
623 }
624 dispatchMode = {
625 type: input.mode === "steer" ? "steer_active" : "restart_active",
626 targetRunId: steerableRun.id,
627 };
628 } else if (input.mode === "auto" && steerableRun !== undefined) {
629 dispatchMode = { type: "steer_active", targetRunId: steerableRun.id };
630 } else {
631 dispatchMode = {
632 type: input.mode === "queue" ? "queue_after_active" : "start_immediately",
633 };
634 }
635
636 const dispatch = yield* orchestrator.dispatch({
637 type: "message.dispatch",
638 commandId: input.commandId,
639 threadId: input.threadId,
640 messageId: input.messageId,
641 ...(input.scheduledTaskId === undefined ? {} : { scheduledTaskId: input.scheduledTaskId }),
642 ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
643 text: input.text,
644 attachments: input.attachments,
645 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
646 dispatchMode,
647 createdBy: input.createdBy,
648 creationSource: input.creationSource,
649 });
650 const projection = yield* getProjectThreadRecords(input, ["runs", "messages", "turnItems"], {
651 messageIds: [input.messageId],
652 turnItemTypes: ["user_message"],
653 });
654 const message = projection.messages.find((candidate) => candidate.id === input.messageId);
655 const run =
656 message?.runId === null || message?.runId === undefined
657 ? undefined
658 : projection.runs.find((candidate) => candidate.id === message.runId);
659 const turnItem =
660 projection.turnItems.find(
661 (
662 candidate,
663 ): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> =>
664 candidate.type === "user_message" && candidate.messageId === input.messageId,
665 ) ?? null;
666 // A queued message's user turn item is deliberately not emitted at
667 // dispatch time — it materializes when the queued turn actually starts,
668 // so it can map onto the provider turn. Every other dispatch mode still
669 // produces its turn item transactionally with the run.
670 if (
671 message === undefined ||
672 run === undefined ||
673 (turnItem === null && run.status !== "queued")
674 ) {
675 return yield* new ThreadManagementDurableRunProjectionError({
676 threadId: input.threadId,
677 messageId: input.messageId,
678 });
679 }
680 const delivery: ThreadManagementSendResult["delivery"] =
681 turnItem === null || turnItem.inputIntent === "queued_turn"
682 ? "queued"
683 : turnItem.inputIntent === "turn_start"
684 ? "started"
685 : input.mode === "restart"
686 ? "restarted"
687 : "steered";
688 return { dispatch, projection, message, run, turnItem, delivery };
689 });
690
691 const waitForThread: ThreadManagementServiceShape["waitForThread"] = (input) =>
692 Effect.gen(function* () {
693 const loadError = (cause: unknown) =>
694 new ThreadManagementProjectionLoadError({
695 projectId: input.projectId,
696 threadId: input.threadId,
697 cause,
698 });
699 // Taken before the first read, so a run update between that read and
700 // the subscription below still replays.
701 const afterSequence = yield* orchestrator
702 .getThreadEventSequence(input.threadId)
703 .pipe(Effect.mapError(loadError));
704 const target = yield* getProjectThreadRecords(input, ["runs"]);
705 const selectedRun =
706 input.runId === undefined
707 ? latestRun(target)
708 : target.runs.find((candidate) => candidate.id === input.runId);
709 if (input.runId !== undefined && selectedRun === undefined) {
710 return yield* new ThreadManagementRunNotFoundError({
711 threadId: input.threadId,
712 runId: input.runId,
713 });
714 }
715 if (selectedRun === undefined) {
716 return { threadId: input.threadId, run: null, timedOut: false };
717 }
718 if (isTerminalRunStatus(selectedRun.status)) {
719 return { threadId: input.threadId, run: selectedRun, timedOut: false };
720 }
721
722 // Re-read the run only when the thread records a run update or its
723 // deletion, instead of polling the projection for up to an hour. Each
724 // stream keeps one event type, so transcript events never fill its buffer.
725 const wait = Stream.merge(
726 orchestrator.streamStoredEventsFrom({
727 threadId: input.threadId,
728 afterSequence,
729 eventType: "run.updated",
730 }),
731 orchestrator.streamStoredEventsFrom({
732 threadId: input.threadId,
733 afterSequence,
734 eventType: "thread.deleted",
735 }),
736 ).pipe(
737 Stream.mapError(loadError),
738 Stream.filter(
739 (stored) =>
740 stored.event.type !== "run.updated" || stored.event.payload.id === selectedRun.id,
741 ),
742 Stream.mapEffect(() =>
743 getProjectThreadRecords(input, ["runs"], { runIds: [selectedRun.id] }).pipe(
744 Effect.flatMap((current) => {
745 const run = current.runs.find((candidate) => candidate.id === selectedRun.id);
746 return run === undefined
747 ? Effect.fail(
748 new ThreadManagementRunNotFoundError({
749 threadId: input.threadId,
750 runId: selectedRun.id,
751 }),
752 )
753 : Effect.succeed(run);
754 }),
755 ),
756 ),
757 Stream.filter((run) => isTerminalRunStatus(run.status)),
758 Stream.runHead,
759 Effect.timeoutOption(Duration.millis(Math.max(1, input.timeoutMs))),
760 );
761 const waited = Option.flatten(yield* wait);
762 if (Option.isSome(waited)) {
763 return { threadId: input.threadId, run: waited.value, timedOut: false };
764 }
765 const current = yield* getProjectThreadRecords(input, ["runs"], { runIds: [selectedRun.id] });
766 const run = current.runs.find((candidate) => candidate.id === selectedRun.id);
767 if (run === undefined) {
768 return yield* new ThreadManagementRunNotFoundError({
769 threadId: input.threadId,
770 runId: selectedRun.id,
771 });
772 }
773 // The run may have reached a terminal status while the timeout was
774 // winning the race; the final projection read decides what actually
775 // happened, so only a still-active run counts as timed out.
776 return { threadId: input.threadId, run, timedOut: !isTerminalRunStatus(run.status) };
777 });
778
779 const settleAfterRun: ThreadManagementServiceShape["settleAfterRun"] = Effect.fn(
780 "orchestrationV2.threadManagement.settleAfterRun",
781 )(function* (input) {
782 // A turn that outlives this wait leaves its thread active.
783 const { run } = yield* waitForThread({ ...input, timeoutMs: SETTLE_AFTER_RUN_WAIT_MS });
784 if (run?.status !== "completed") return;
785 yield* dispatch({
786 type: "thread.settle",
787 commandId: CommandId.make(`server:settle-after-run:${input.runId}`),
788 threadId: input.threadId,
789 });
790 });
791
792 const settleThread: ThreadManagementServiceShape["settleThread"] = Effect.fn(
793 "orchestrationV2.threadManagement.settleThread",
794 )(function* (input) {
795 const shell = input.byOwnAgent ? yield* orchestrator.getThreadShell(input.threadId) : null;
796 if (shell != null && shell.activeRunId !== null) {
797 yield* settleAfterRun({
798 projectId: shell.projectId,
799 threadId: shell.id,
800 runId: shell.activeRunId,
801 }).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(layerScope));
802 return { settlesWhenTurnEnds: true } as const;
803 }
804 const result = yield* dispatch({
805 type: "thread.settle",
806 commandId: input.commandId,
807 threadId: input.threadId,
808 });
809 return { sequence: result.sequence };
810 });
811
812 const interruptThread: ThreadManagementServiceShape["interruptThread"] = (input) =>
813 Effect.gen(function* () {
814 const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
815 const explicitRun =
816 input.runId === undefined
817 ? undefined
818 : target.runs.find((candidate) => candidate.id === input.runId);
819 if (input.runId !== undefined && explicitRun === undefined) {
820 return yield* new ThreadManagementRunNotFoundError({
821 threadId: input.threadId,
822 runId: input.runId,
823 });
824 }
825 if (explicitRun !== undefined && isTerminalRunStatus(explicitRun.status)) {
826 return {
827 type: "already_terminal",
828 run: explicitRun as OrchestrationV2Run & {
829 readonly status: ThreadManagementTerminalRunStatus;
830 },
831 } as const;
832 }
833 const interruptibleRun = latestActiveRun(target);
834 if (interruptibleRun === undefined) {
835 if (input.runId === undefined) {
836 return { type: "no_active_run" } as const;
837 }
838 return yield* new ThreadManagementThreadNotInterruptibleError({
839 threadId: input.threadId,
840 runId: input.runId,
841 });
842 }
843 if (input.runId !== undefined && interruptibleRun.id !== input.runId) {
844 return yield* new ThreadManagementThreadNotInterruptibleError({
845 threadId: input.threadId,
846 runId: input.runId,
847 });
848 }
849 const dispatch = yield* orchestrator.dispatch({
850 type: "run.interrupt",
851 commandId: input.commandId,
852 threadId: input.threadId,
853 runId: interruptibleRun.id,
854 ...(input.reason === undefined ? {} : { reason: input.reason }),
855 });
856 return { type: "interrupt_requested", run: interruptibleRun, dispatch } as const;
857 });
858
859 const stopWorkflow: ThreadManagementServiceShape["stopWorkflow"] = (input) =>
860 Effect.gen(function* () {
861 const records = yield* orchestrator
862 .getThreadRecords(input.threadId, ["subagents", "runs", "providerThreads"])
863 .pipe(
864 Effect.mapError(
865 (cause) =>
866 new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable", cause }),
867 ),
868 );
869 if (records.thread.deletedAt !== null) {
870 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable" });
871 }
872 // A limited caller (an agent over MCP) may not stop work on a thread
873 // running above its own modes. Checked under the thread lock, where the
874 // thread's user cannot raise the modes between this read and the stop.
875 const limit = yield* DispatchModeLimit;
876 const exceeded =
877 limit === undefined ? undefined : exceededDispatchModeLimit(limit, records.thread);
878 if (limit !== undefined && exceeded !== undefined) {
879 if (limit.refused !== undefined) {
880 yield* Ref.set(limit.refused, {
881 threadId: input.threadId,
882 runtimeMode: records.thread.runtimeMode,
883 interactionMode: records.thread.interactionMode,
884 mode: exceeded,
885 });
886 }
887 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable" });
888 }
889 const task = records.subagents.find((candidate) => candidate.id === input.subagentId);
890 if (
891 task === undefined ||
892 task.threadId !== input.threadId ||
893 task.workflow === undefined ||
894 task.status !== "running"
895 ) {
896 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "not-running" });
897 }
898 if (task.origin !== "provider_native" || task.driver !== "claudeAgent") {
899 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unsupported" });
900 }
901 const providerThreadId =
902 task.providerThreadId ??
903 records.runs.find((run) => run.id === task.runId)?.providerThreadId;
904 const providerThread = records.providerThreads.find(
905 (candidate) =>
906 candidate.id === providerThreadId &&
907 candidate.appThreadId === input.threadId &&
908 candidate.providerInstanceId === task.providerInstanceId &&
909 candidate.driver === task.driver,
910 );
911 const taskId = task.nativeTaskRef?.nativeId;
912 if (providerThread?.providerSessionId == null || taskId == null || taskId.length === 0) {
913 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable" });
914 }
915 const runtime = yield* sessions
916 .get(providerThread.providerSessionId)
917 .pipe(
918 Effect.mapError(
919 (cause) =>
920 new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable", cause }),
921 ),
922 );
923 if (Option.isNone(runtime)) {
924 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable" });
925 }
926 if (runtime.value.stopTask === undefined) {
927 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unsupported" });
928 }
929 // Bounded so a provider that never answers cannot hold the thread lock.
930 yield* runtime.value.stopTask({ providerThread, taskId }).pipe(
931 Effect.timeout("15 seconds"),
932 Effect.mapError(
933 (cause) =>
934 new OrchestrationV2StopWorkflowError({
935 ...input,
936 reason: "stop-failed",
937 cause,
938 }),
939 ),
940 );
941 }).pipe((effect) => threadDispatch.withLock(input.threadId, effect));
942
943 const stopDelegatedTasks: ThreadManagementServiceShape["stopDelegatedTasks"] = (input) =>
944 Effect.gen(function* () {
945 const { subagents } = yield* orchestrator.getThreadRecords(input.threadId, ["subagents"]);
946 const failures: Array<Orchestrator.OrchestratorV2Error> = [];
947 for (const task of subagents) {
948 if (task.origin !== "app_owned" || task.childThreadId === null) continue;
949 const threadId = task.childThreadId;
950 yield* dispatch({
951 type: "thread.stop",
952 commandId: CommandId.make(`${input.commandId}:stop:${threadId}`),
953 threadId,
954 ...(input.reason === undefined ? {} : { reason: input.reason }),
955 }).pipe(
956 Effect.andThen(stopDelegatedTasks({ ...input, threadId })),
957 Effect.catch((error) =>
958 Effect.logWarning("Unable to stop a delegated task", {
959 parentThreadId: input.threadId,
960 threadId,
961 error,
962 }).pipe(Effect.andThen(Effect.sync(() => failures.push(error)))),
963 ),
964 );
965 }
966 if (failures[0] !== undefined) return yield* Effect.fail(failures[0]);
967 });
968
969 return ThreadManagementService.of({
970 ensureLegacyTranscript,
971 searchThreadStream: (input) =>
972 Stream.unwrap(
973 ensureProjectionTranscript(input.threadId).pipe(
974 Effect.as(orchestrator.searchThreadStream(input)),
975 ),
976 ),
977 searchThread: (input) =>
978 ensureProjectionTranscript(input.threadId).pipe(
979 Effect.andThen(orchestrator.searchThread(input)),
980 ),
981 dispatch,
982 getThreadHistoryPage: (threadId, cursor, throughEntryId, conversationOnly) =>
983 ensureProjectionTranscript(threadId).pipe(
984 Effect.andThen(
985 orchestrator.getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly),
986 ),
987 ),
988 getTimelinePage: (threadId, options) =>
989 ensureProjectionTranscript(threadId).pipe(
990 Effect.andThen(orchestrator.getTimelinePage(threadId, options)),
991 ),
992 getMessageCount: (threadId) =>
993 ensureProjectionTranscript(threadId).pipe(
994 Effect.andThen(orchestrator.getMessageCount(threadId)),
995 ),
996 getTurnItem: (input) =>
997 ensureProjectionTranscript(input.threadId).pipe(
998 Effect.andThen(orchestrator.getTurnItem(input)),
999 Effect.map((item) => ({ item: item === null ? null : projectTurnItemForDetail(item) })),
1000 ),
1001 getThreadRecords: (threadId, fields, filter) =>
1002 ensureProjectionTranscript(threadId).pipe(
1003 Effect.andThen(orchestrator.getThreadRecords(threadId, fields, filter)),
1004 ),
1005 getThreadProjection,
1006 getCheckpointContext,
1007 getThreadSnapshot,
1008 getThreadSnapshotWindow,
1009 getProjectThreadRecords,
1010 getProjectThread,
1011 getShellSnapshot: orchestrator.getShellSnapshot,
1012 readShellSnapshot: orchestrator.readShellSnapshot,
1013 getThreadShell: orchestrator.getThreadShell,
1014 listProjectThreads,
1015 sendToThread,
1016 waitForThread,
1017 settleAfterRun,
1018 settleThread,
1019 interruptThread,
1020 stopDelegatedTasks,
1021 stopWorkflow,
1022 getThreadEventSequence: orchestrator.getThreadEventSequence,
1023 recoverDelegatedTask: orchestrator.recoverDelegatedTask,
1024 delegatedTaskResultPending: orchestrator.delegatedTaskResultPending,
1025 streamStoredEvents: orchestrator.streamStoredEvents,
1026 streamStoredEventsFrom: orchestrator.streamStoredEventsFrom,
1027 streamDomainEvents: orchestrator.streamDomainEvents,
1028 });
1029});
1030
1031const layerLegacyV1ThreadImporterNoop = Layer.succeed(
1032 LegacyV1ThreadImporter.LegacyV1ThreadImporter,
1033 LegacyV1ThreadImporter.LegacyV1ThreadImporter.of({
1034 pendingThreadCount: Effect.succeed(0),
1035 reconcileShells: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
1036 ensureTranscript: () => Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
1037 importPendingTranscripts: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
1038 }),
1039);
1040
1041export const layer: Layer.Layer<
1042 ThreadManagementService,
1043 never,
1044 Orchestrator.OrchestratorV2 | ProviderSessionManager.ProviderSessionManagerV2
1045> = Layer.effect(ThreadManagementService, make).pipe(
1046 Layer.provide(layerLegacyV1ThreadImporterNoop),
1047 Layer.provide(ThreadCommandExecutor.layer),
1048);
1049
1050export const layerWithLegacyImporter: Layer.Layer<
1051 ThreadManagementService,
1052 never,
1053 | LegacyV1ThreadImporter.LegacyV1ThreadImporter
1054 | Orchestrator.OrchestratorV2
1055 | ProviderSessionManager.ProviderSessionManagerV2
1056> = Layer.effect(ThreadManagementService, make).pipe(Layer.provide(ThreadCommandExecutor.layer));