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