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

ThreadManagementService.ts

949 lines35.2 KB

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;
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 }
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 }
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;
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";
133​
134export interface ThreadManagementWaitInput {
135 readonly projectId: ProjectId;
136 readonly threadId: ThreadId;
137 readonly runId?: RunId;
138 readonly timeoutMs: number;
140​
141export interface ThreadManagementWaitResult {
142 readonly threadId: ThreadId;
143 readonly run: OrchestrationV2Run | null;
144 readonly timedOut: boolean;
146​
147export interface ThreadManagementInterruptInput {
148 readonly projectId: ProjectId;
149 readonly commandId: CommandId;
150 readonly threadId: ThreadId;
151 readonly runId?: RunId;
152 readonly reason?: string;
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 readShellSnapshot: (options?: {
324 readonly location?: "active" | "archive";
325 }) => Effect.Effect<
326 Effect.Effect<OrchestrationV2ThreadShellSnapshot, Orchestrator.OrchestratorV2Error>,
327 Orchestrator.OrchestratorV2Error
328 >;
329 readonly getThreadShell: Orchestrator.OrchestratorV2["Service"]["getThreadShell"];
330 readonly listProjectThreads: (input: {
331 readonly projectId: ProjectId;
332 readonly includeSubagents: boolean;
333 }) => Effect.Effect<ReadonlyArray<OrchestrationV2ThreadShell>, ThreadManagementError>;
334 readonly sendToThread: (
335 input: ThreadManagementSendInput,
336 ) => Effect.Effect<ThreadManagementSendResult, ThreadManagementFailure>;
337 readonly waitForThread: (
338 input: ThreadManagementWaitInput,
339 ) => Effect.Effect<ThreadManagementWaitResult, ThreadManagementError>;
340 /**
341 * Waits for `runId` to end, then settles the thread if the run completed.
342 * Settling stops the provider session, so an agent that settles its own
343 * thread uses this to wait for its turn to end. A run that ends any other
344 * way leaves the thread active, as does anything `thread.settle` refuses
345 * then, such as a queued message.
346 */
347 readonly settleAfterRun: (input: {
348 readonly projectId: ProjectId;
349 readonly threadId: ThreadId;
350 readonly runId: RunId;
351 }) => Effect.Effect<void, ThreadManagementFailure>;
352 /**
353 * Settles a thread. When the thread's own agent asks, it is mid-turn, so
354 * the thread settles through `settleAfterRun` once that turn ends.
355 */
356 readonly settleThread: (input: {
357 readonly threadId: ThreadId;
358 readonly commandId: CommandId;
359 readonly byOwnAgent: boolean;
360 }) => Effect.Effect<
361 { readonly sequence: number } | { readonly settlesWhenTurnEnds: true },
362 Orchestrator.OrchestratorV2Error
363 >;
364 readonly interruptThread: (
365 input: ThreadManagementInterruptInput,
366 ) => Effect.Effect<ThreadManagementInterruptResult, ThreadManagementFailure>;
367 /**
368 * Sends `thread.stop` to every delegated task under a thread, depth first. Their command IDs
369 * derive from `commandId`, so a retry repeats nothing that already stopped. A task that
370 * cannot be stopped does not keep the others running: all are tried, then it fails.
371 */
372 readonly stopDelegatedTasks: (input: {
373 readonly threadId: ThreadId;
374 readonly commandId: CommandId;
375 readonly reason?: string | undefined;
376 }) => Effect.Effect<void, Orchestrator.OrchestratorV2Error>;
377 readonly getThreadEventSequence: Orchestrator.OrchestratorV2["Service"]["getThreadEventSequence"];
378 readonly recoverDelegatedTask: Orchestrator.OrchestratorV2["Service"]["recoverDelegatedTask"];
379 readonly delegatedTaskResultPending: Orchestrator.OrchestratorV2["Service"]["delegatedTaskResultPending"];
380 readonly streamStoredEvents: Orchestrator.OrchestratorV2["Service"]["streamStoredEvents"];
381 readonly streamStoredEventsFrom: Orchestrator.OrchestratorV2["Service"]["streamStoredEventsFrom"];
382 readonly streamDomainEvents: Orchestrator.OrchestratorV2["Service"]["streamDomainEvents"];
384​
385export class ThreadManagementService extends Context.Service<
386 ThreadManagementService,
387 ThreadManagementServiceShape
388>()("t3/orchestration-v2/ThreadManagementService") {}
389​
390export function isActiveRun(run: OrchestrationV2Run): boolean {
391 return (
392 run.status === "preparing" ||
393 run.status === "starting" ||
394 run.status === "running" ||
395 run.status === "waiting"
396 );
398​
399export function isTerminalRunStatus(
400 status: OrchestrationV2Run["status"],
401): status is ThreadManagementTerminalRunStatus {
402 return (
403 status === "completed" ||
404 status === "failed" ||
405 status === "cancelled" ||
406 status === "interrupted" ||
407 status === "rolled_back"
408 );
410​
411export function latestRun(
412 projection: Pick<OrchestrationV2ThreadProjection, "runs">,
413): OrchestrationV2Run | undefined {
414 return projection.runs.toSorted((left, right) => right.ordinal - left.ordinal)[0];
416​
417export function latestActiveRun(
418 projection: Pick<OrchestrationV2ThreadProjection, "runs">,
419): OrchestrationV2Run | undefined {
420 return projection.runs
421 .filter(isActiveRun)
422 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
424​
425function latestSteerableRun(
426 projection: Pick<OrchestrationV2ThreadProjection, "runs" | "providerTurns">,
427): OrchestrationV2Run | undefined {
428 return projection.runs
429 .filter(
430 (run) =>
431 run.status === "running" &&
432 run.activeAttemptId !== null &&
433 projection.providerTurns.some(
434 (turn) => turn.runAttemptId === run.activeAttemptId && turn.status === "running",
435 ),
436 )
437 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
439​
440const SETTLE_AFTER_RUN_WAIT_MS = 24 * 60 * 60 * 1_000;
441​
442const make = Effect.gen(function* () {
443 const orchestrator = yield* Orchestrator.OrchestratorV2;
444 const layerScope = yield* Effect.scope;
445 const legacyImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
446​
447 const ensureLegacyTranscript = Effect.fn(
448 "orchestrationV2.threadManagement.ensureLegacyTranscript",
449 )(function* (threadId: ThreadId) {
450 yield* legacyImporter.ensureTranscript(threadId).pipe(
451 Effect.tapError((cause) =>
452 Effect.logWarning("Unable to hydrate migrated v1 thread transcript", {
453 threadId,
454 cause,
455 }),
456 ),
457 );
458 });
459​
460 const ensureProjectionTranscript = (threadId: ThreadId) =>
461 ensureLegacyTranscript(threadId).pipe(
462 Effect.mapError(
463 (cause) =>
464 new Orchestrator.OrchestratorProjectionError({
465 threadId,
466 cause,
467 }),
468 ),
469 );
470​
471 const ensureCommandTranscripts = Effect.fn(
472 "orchestrationV2.threadManagement.ensureCommandTranscripts",
473 )(function* (command: OrchestrationV2ServerCommand) {
474 yield* Effect.forEach(
475 existingThreadIdsForCommand(command),
476 (threadId) => ensureLegacyTranscript(threadId),
477 { discard: true },
478 ).pipe(
479 Effect.mapError(
480 (cause) =>
481 new Orchestrator.OrchestratorDispatchError({
482 commandId: command.commandId,
483 commandType: command.type,
484 cause,
485 }),
486 ),
487 );
488 });
489​
490 const getThreadProjection: ThreadManagementServiceShape["getThreadProjection"] = (threadId) =>
491 ensureProjectionTranscript(threadId).pipe(
492 Effect.andThen(orchestrator.getThreadProjection(threadId)),
493 );
494​
495 const getCheckpointContext: ThreadManagementServiceShape["getCheckpointContext"] = (threadId) =>
496 ensureProjectionTranscript(threadId).pipe(
497 Effect.andThen(orchestrator.getCheckpointContext(threadId)),
498 );
499​
500 const getThreadSnapshot: ThreadManagementServiceShape["getThreadSnapshot"] = (threadId) =>
501 ensureProjectionTranscript(threadId).pipe(
502 Effect.andThen(orchestrator.getThreadSnapshot(threadId)),
503 );
504 const getThreadSnapshotWindow: ThreadManagementServiceShape["getThreadSnapshotWindow"] = (
505 threadId,
506 options,
507 ) =>
508 ensureProjectionTranscript(threadId).pipe(
509 Effect.andThen(orchestrator.getThreadSnapshotWindow(threadId, options)),
510 );
511​
512 const dispatch: ThreadManagementServiceShape["dispatch"] = (command) =>
513 ensureCommandTranscripts(command).pipe(Effect.andThen(orchestrator.dispatch(command)));
514​
515 const getProjectThread: ThreadManagementServiceShape["getProjectThread"] = (input) =>
516 getThreadProjection(input.threadId).pipe(
517 Effect.mapError(
518 (cause) =>
519 new ThreadManagementProjectionLoadError({
520 projectId: input.projectId,
521 threadId: input.threadId,
522 cause,
523 }),
524 ),
525 Effect.flatMap((projection) =>
526 projection.thread.projectId === input.projectId && projection.thread.deletedAt === null
527 ? Effect.succeed(projection)
528 : Effect.fail(
529 new ThreadManagementThreadNotFoundError({
530 projectId: input.projectId,
531 threadId: input.threadId,
532 }),
533 ),
534 ),
535 );
536​
537 const getProjectThreadRecords: ThreadManagementServiceShape["getProjectThreadRecords"] = (
538 input,
539 fields,
540 filter,
541 ) =>
542 ensureProjectionTranscript(input.threadId)
543 .pipe(Effect.andThen(orchestrator.getThreadRecords(input.threadId, fields, filter)))
544 .pipe(
545 Effect.mapError(
546 (cause) =>
547 new ThreadManagementProjectionLoadError({
548 projectId: input.projectId,
549 threadId: input.threadId,
550 cause,
551 }),
552 ),
553 Effect.flatMap((projection) =>
554 projection.thread.projectId === input.projectId && projection.thread.deletedAt === null
555 ? Effect.succeed(projection)
556 : Effect.fail(
557 new ThreadManagementThreadNotFoundError({
558 projectId: input.projectId,
559 threadId: input.threadId,
560 }),
561 ),
562 ),
563 );
564​
565 const listProjectThreads: ThreadManagementServiceShape["listProjectThreads"] = (input) =>
566 orchestrator.getShellSnapshot().pipe(
567 Effect.mapError(
568 (cause) =>
569 new ThreadManagementProjectThreadsListError({
570 projectId: input.projectId,
571 cause,
572 }),
573 ),
574 Effect.map((snapshot) =>
575 snapshot.threads
576 .filter((thread) => thread.projectId === input.projectId)
577 .filter(
578 (thread) =>
579 input.includeSubagents || thread.lineage.relationshipToParent !== "subagent",
580 )
581 .toSorted(
582 (left, right) =>
583 DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt) ||
584 right.id.localeCompare(left.id),
585 ),
586 ),
587 );
588​
589 const sendToThread: ThreadManagementServiceShape["sendToThread"] = (input) =>
590 Effect.gen(function* () {
591 const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
592 if (target.thread.archivedAt !== null) {
593 return yield* new ThreadManagementThreadArchivedError({
594 threadId: input.threadId,
595 });
596 }
597​
598 const steerableRun = latestSteerableRun(target);
599 let dispatchMode: Extract<
600 OrchestrationV2Command,
601 { readonly type: "message.dispatch" }
602 >["dispatchMode"];
603 if (input.mode === "steer" || input.mode === "restart") {
604 if (steerableRun === undefined) {
605 return yield* new ThreadManagementNoSteerableRunError({
606 threadId: input.threadId,
607 mode: input.mode,
608 });
609 }
610 dispatchMode = {
611 type: input.mode === "steer" ? "steer_active" : "restart_active",
612 targetRunId: steerableRun.id,
613 };
614 } else if (input.mode === "auto" && steerableRun !== undefined) {
615 dispatchMode = { type: "steer_active", targetRunId: steerableRun.id };
616 } else {
617 dispatchMode = {
618 type: input.mode === "queue" ? "queue_after_active" : "start_immediately",
619 };
620 }
621​
622 const dispatch = yield* orchestrator.dispatch({
623 type: "message.dispatch",
624 commandId: input.commandId,
625 threadId: input.threadId,
626 messageId: input.messageId,
627 ...(input.scheduledTaskId === undefined ? {} : { scheduledTaskId: input.scheduledTaskId }),
628 ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
629 text: input.text,
630 attachments: input.attachments,
631 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
632 dispatchMode,
633 createdBy: input.createdBy,
634 creationSource: input.creationSource,
635 });
636 const projection = yield* getProjectThreadRecords(input, ["runs", "messages", "turnItems"], {
637 messageIds: [input.messageId],
638 turnItemTypes: ["user_message"],
639 });
640 const message = projection.messages.find((candidate) => candidate.id === input.messageId);
641 const run =
642 message?.runId === null || message?.runId === undefined
643 ? undefined
644 : projection.runs.find((candidate) => candidate.id === message.runId);
645 const turnItem =
646 projection.turnItems.find(
647 (
648 candidate,
649 ): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> =>
650 candidate.type === "user_message" && candidate.messageId === input.messageId,
651 ) ?? null;
652 // A queued message's user turn item is deliberately not emitted at
653 // dispatch time — it materializes when the queued turn actually starts,
654 // so it can map onto the provider turn. Every other dispatch mode still
655 // produces its turn item transactionally with the run.
656 if (
657 message === undefined ||
658 run === undefined ||
659 (turnItem === null && run.status !== "queued")
660 ) {
661 return yield* new ThreadManagementDurableRunProjectionError({
662 threadId: input.threadId,
663 messageId: input.messageId,
664 });
665 }
666 const delivery: ThreadManagementSendResult["delivery"] =
667 turnItem === null || turnItem.inputIntent === "queued_turn"
668 ? "queued"
669 : turnItem.inputIntent === "turn_start"
670 ? "started"
671 : input.mode === "restart"
672 ? "restarted"
673 : "steered";
674 return { dispatch, projection, message, run, turnItem, delivery };
675 });
676​
677 const waitForThread: ThreadManagementServiceShape["waitForThread"] = (input) =>
678 Effect.gen(function* () {
679 const loadError = (cause: unknown) =>
680 new ThreadManagementProjectionLoadError({
681 projectId: input.projectId,
682 threadId: input.threadId,
683 cause,
684 });
685 // Taken before the first read, so a run update between that read and
686 // the subscription below still replays.
687 const afterSequence = yield* orchestrator
688 .getThreadEventSequence(input.threadId)
689 .pipe(Effect.mapError(loadError));
690 const target = yield* getProjectThreadRecords(input, ["runs"]);
691 const selectedRun =
692 input.runId === undefined
693 ? latestRun(target)
694 : target.runs.find((candidate) => candidate.id === input.runId);
695 if (input.runId !== undefined && selectedRun === undefined) {
696 return yield* new ThreadManagementRunNotFoundError({
697 threadId: input.threadId,
698 runId: input.runId,
699 });
700 }
701 if (selectedRun === undefined) {
702 return { threadId: input.threadId, run: null, timedOut: false };
703 }
704 if (isTerminalRunStatus(selectedRun.status)) {
705 return { threadId: input.threadId, run: selectedRun, timedOut: false };
706 }
707​
708 // Re-read the run only when the thread records a run update or its
709 // deletion, instead of polling the projection for up to an hour. Each
710 // stream keeps one event type, so transcript events never fill its buffer.
711 const wait = Stream.merge(
712 orchestrator.streamStoredEventsFrom({
713 threadId: input.threadId,
714 afterSequence,
715 eventType: "run.updated",
716 }),
717 orchestrator.streamStoredEventsFrom({
718 threadId: input.threadId,
719 afterSequence,
720 eventType: "thread.deleted",
721 }),
722 ).pipe(
723 Stream.mapError(loadError),
724 Stream.filter(
725 (stored) =>
726 stored.event.type !== "run.updated" || stored.event.payload.id === selectedRun.id,
727 ),
728 Stream.mapEffect(() =>
729 getProjectThreadRecords(input, ["runs"], { runIds: [selectedRun.id] }).pipe(
730 Effect.flatMap((current) => {
731 const run = current.runs.find((candidate) => candidate.id === selectedRun.id);
732 return run === undefined
733 ? Effect.fail(
734 new ThreadManagementRunNotFoundError({
735 threadId: input.threadId,
736 runId: selectedRun.id,
737 }),
738 )
739 : Effect.succeed(run);
740 }),
741 ),
742 ),
743 Stream.filter((run) => isTerminalRunStatus(run.status)),
744 Stream.runHead,
745 Effect.timeoutOption(Duration.millis(Math.max(1, input.timeoutMs))),
746 );
747 const waited = Option.flatten(yield* wait);
748 if (Option.isSome(waited)) {
749 return { threadId: input.threadId, run: waited.value, timedOut: false };
750 }
751 const current = yield* getProjectThreadRecords(input, ["runs"], { runIds: [selectedRun.id] });
752 const run = current.runs.find((candidate) => candidate.id === selectedRun.id);
753 if (run === undefined) {
754 return yield* new ThreadManagementRunNotFoundError({
755 threadId: input.threadId,
756 runId: selectedRun.id,
757 });
758 }
759 // The run may have reached a terminal status while the timeout was
760 // winning the race; the final projection read decides what actually
761 // happened, so only a still-active run counts as timed out.
762 return { threadId: input.threadId, run, timedOut: !isTerminalRunStatus(run.status) };
763 });
764​
765 const settleAfterRun: ThreadManagementServiceShape["settleAfterRun"] = Effect.fn(
766 "orchestrationV2.threadManagement.settleAfterRun",
767 )(function* (input) {
768 // A turn that outlives this wait leaves its thread active.
769 const { run } = yield* waitForThread({ ...input, timeoutMs: SETTLE_AFTER_RUN_WAIT_MS });
770 if (run?.status !== "completed") return;
771 yield* dispatch({
772 type: "thread.settle",
773 commandId: CommandId.make(`server:settle-after-run:${input.runId}`),
774 threadId: input.threadId,
775 });
776 });
777​
778 const settleThread: ThreadManagementServiceShape["settleThread"] = Effect.fn(
779 "orchestrationV2.threadManagement.settleThread",
780 )(function* (input) {
781 const shell = input.byOwnAgent ? yield* orchestrator.getThreadShell(input.threadId) : null;
782 if (shell != null && shell.activeRunId !== null) {
783 yield* settleAfterRun({
784 projectId: shell.projectId,
785 threadId: shell.id,
786 runId: shell.activeRunId,
787 }).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(layerScope));
788 return { settlesWhenTurnEnds: true } as const;
789 }
790 const result = yield* dispatch({
791 type: "thread.settle",
792 commandId: input.commandId,
793 threadId: input.threadId,
794 });
795 return { sequence: result.sequence };
796 });
797​
798 const interruptThread: ThreadManagementServiceShape["interruptThread"] = (input) =>
799 Effect.gen(function* () {
800 const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
801 const explicitRun =
802 input.runId === undefined
803 ? undefined
804 : target.runs.find((candidate) => candidate.id === input.runId);
805 if (input.runId !== undefined && explicitRun === undefined) {
806 return yield* new ThreadManagementRunNotFoundError({
807 threadId: input.threadId,
808 runId: input.runId,
809 });
810 }
811 if (explicitRun !== undefined && isTerminalRunStatus(explicitRun.status)) {
812 return {
813 type: "already_terminal",
814 run: explicitRun as OrchestrationV2Run & {
815 readonly status: ThreadManagementTerminalRunStatus;
816 },
817 } as const;
818 }
819 const interruptibleRun = latestActiveRun(target);
820 if (interruptibleRun === undefined) {
821 if (input.runId === undefined) {
822 return { type: "no_active_run" } as const;
823 }
824 return yield* new ThreadManagementThreadNotInterruptibleError({
825 threadId: input.threadId,
826 runId: input.runId,
827 });
828 }
829 if (input.runId !== undefined && interruptibleRun.id !== input.runId) {
830 return yield* new ThreadManagementThreadNotInterruptibleError({
831 threadId: input.threadId,
832 runId: input.runId,
833 });
834 }
835 const dispatch = yield* orchestrator.dispatch({
836 type: "run.interrupt",
837 commandId: input.commandId,
838 threadId: input.threadId,
839 runId: interruptibleRun.id,
840 ...(input.reason === undefined ? {} : { reason: input.reason }),
841 });
842 return { type: "interrupt_requested", run: interruptibleRun, dispatch } as const;
843 });
844​
845 const stopDelegatedTasks: ThreadManagementServiceShape["stopDelegatedTasks"] = (input) =>
846 Effect.gen(function* () {
847 const { subagents } = yield* orchestrator.getThreadRecords(input.threadId, ["subagents"]);
848 const failures: Array<Orchestrator.OrchestratorV2Error> = [];
849 for (const task of subagents) {
850 if (task.origin !== "app_owned" || task.childThreadId === null) continue;
851 const threadId = task.childThreadId;
852 yield* dispatch({
853 type: "thread.stop",
854 commandId: CommandId.make(`${input.commandId}:stop:${threadId}`),
855 threadId,
856 ...(input.reason === undefined ? {} : { reason: input.reason }),
857 }).pipe(
858 Effect.andThen(stopDelegatedTasks({ ...input, threadId })),
859 Effect.catch((error) =>
860 Effect.logWarning("Unable to stop a delegated task", {
861 parentThreadId: input.threadId,
862 threadId,
863 error,
864 }).pipe(Effect.andThen(Effect.sync(() => failures.push(error)))),
865 ),
866 );
867 }
868 if (failures[0] !== undefined) return yield* Effect.fail(failures[0]);
869 });
870​
871 return ThreadManagementService.of({
872 ensureLegacyTranscript,
873 searchThreadStream: (input) =>
874 Stream.unwrap(
875 ensureProjectionTranscript(input.threadId).pipe(
876 Effect.as(orchestrator.searchThreadStream(input)),
877 ),
878 ),
879 searchThread: (input) =>
880 ensureProjectionTranscript(input.threadId).pipe(
881 Effect.andThen(orchestrator.searchThread(input)),
882 ),
883 dispatch,
884 getThreadHistoryPage: (threadId, cursor, throughEntryId, conversationOnly) =>
885 ensureProjectionTranscript(threadId).pipe(
886 Effect.andThen(
887 orchestrator.getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly),
888 ),
889 ),
890 getTimelinePage: (threadId, options) =>
891 ensureProjectionTranscript(threadId).pipe(
892 Effect.andThen(orchestrator.getTimelinePage(threadId, options)),
893 ),
894 getMessageCount: (threadId) =>
895 ensureProjectionTranscript(threadId).pipe(
896 Effect.andThen(orchestrator.getMessageCount(threadId)),
897 ),
898 getTurnItem: (input) =>
899 ensureProjectionTranscript(input.threadId).pipe(
900 Effect.andThen(orchestrator.getTurnItem(input)),
901 Effect.map((item) => ({ item: item === null ? null : projectTurnItemForDetail(item) })),
902 ),
903 getThreadRecords: (threadId, fields, filter) =>
904 ensureProjectionTranscript(threadId).pipe(
905 Effect.andThen(orchestrator.getThreadRecords(threadId, fields, filter)),
906 ),
907 getThreadProjection,
908 getCheckpointContext,
909 getThreadSnapshot,
910 getThreadSnapshotWindow,
911 getProjectThreadRecords,
912 getProjectThread,
913 getShellSnapshot: orchestrator.getShellSnapshot,
914 readShellSnapshot: orchestrator.readShellSnapshot,
915 getThreadShell: orchestrator.getThreadShell,
916 listProjectThreads,
917 sendToThread,
918 waitForThread,
919 settleAfterRun,
920 settleThread,
921 interruptThread,
922 stopDelegatedTasks,
923 getThreadEventSequence: orchestrator.getThreadEventSequence,
924 recoverDelegatedTask: orchestrator.recoverDelegatedTask,
925 delegatedTaskResultPending: orchestrator.delegatedTaskResultPending,
926 streamStoredEvents: orchestrator.streamStoredEvents,
927 streamStoredEventsFrom: orchestrator.streamStoredEventsFrom,
928 streamDomainEvents: orchestrator.streamDomainEvents,
929 });
930});
931​
932const layerLegacyV1ThreadImporterNoop = Layer.succeed(
933 LegacyV1ThreadImporter.LegacyV1ThreadImporter,
934 LegacyV1ThreadImporter.LegacyV1ThreadImporter.of({
935 pendingThreadCount: Effect.succeed(0),
936 reconcileShells: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
937 ensureTranscript: () => Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
938 importPendingTranscripts: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
939 }),
940);
941​
942export const layer: Layer.Layer<ThreadManagementService, never, Orchestrator.OrchestratorV2> =
943 Layer.effect(ThreadManagementService, make).pipe(Layer.provide(layerLegacyV1ThreadImporterNoop));
944​
945export const layerWithLegacyImporter: Layer.Layer<
946 ThreadManagementService,
947 never,
948 LegacyV1ThreadImporter.LegacyV1ThreadImporter | Orchestrator.OrchestratorV2
949> = Layer.effect(ThreadManagementService, make);