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