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