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

ThreadManagementService.ts

948 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({ projectId: input.projectId, location: "active" }).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(
577 (thread) =>
578 input.includeSubagents || thread.lineage.relationshipToParent !== "subagent",
579 )
580 .toSorted(
581 (left, right) =>
582 DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt) ||
583 right.id.localeCompare(left.id),
584 ),
585 ),
586 );
587​
588 const sendToThread: ThreadManagementServiceShape["sendToThread"] = (input) =>
589 Effect.gen(function* () {
590 const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
591 if (target.thread.archivedAt !== null) {
592 return yield* new ThreadManagementThreadArchivedError({
593 threadId: input.threadId,
594 });
595 }
596​
597 const steerableRun = latestSteerableRun(target);
598 let dispatchMode: Extract<
599 OrchestrationV2Command,
600 { readonly type: "message.dispatch" }
601 >["dispatchMode"];
602 if (input.mode === "steer" || input.mode === "restart") {
603 if (steerableRun === undefined) {
604 return yield* new ThreadManagementNoSteerableRunError({
605 threadId: input.threadId,
606 mode: input.mode,
607 });
608 }
609 dispatchMode = {
610 type: input.mode === "steer" ? "steer_active" : "restart_active",
611 targetRunId: steerableRun.id,
612 };
613 } else if (input.mode === "auto" && steerableRun !== undefined) {
614 dispatchMode = { type: "steer_active", targetRunId: steerableRun.id };
615 } else {
616 dispatchMode = {
617 type: input.mode === "queue" ? "queue_after_active" : "start_immediately",
618 };
619 }
620​
621 const dispatch = yield* orchestrator.dispatch({
622 type: "message.dispatch",
623 commandId: input.commandId,
624 threadId: input.threadId,
625 messageId: input.messageId,
626 ...(input.scheduledTaskId === undefined ? {} : { scheduledTaskId: input.scheduledTaskId }),
627 ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
628 text: input.text,
629 attachments: input.attachments,
630 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
631 dispatchMode,
632 createdBy: input.createdBy,
633 creationSource: input.creationSource,
634 });
635 const projection = yield* getProjectThreadRecords(input, ["runs", "messages", "turnItems"], {
636 messageIds: [input.messageId],
637 turnItemTypes: ["user_message"],
638 });
639 const message = projection.messages.find((candidate) => candidate.id === input.messageId);
640 const run =
641 message?.runId === null || message?.runId === undefined
642 ? undefined
643 : projection.runs.find((candidate) => candidate.id === message.runId);
644 const turnItem =
645 projection.turnItems.find(
646 (
647 candidate,
648 ): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> =>
649 candidate.type === "user_message" && candidate.messageId === input.messageId,
650 ) ?? null;
651 // A queued message's user turn item is deliberately not emitted at
652 // dispatch time — it materializes when the queued turn actually starts,
653 // so it can map onto the provider turn. Every other dispatch mode still
654 // produces its turn item transactionally with the run.
655 if (
656 message === undefined ||
657 run === undefined ||
658 (turnItem === null && run.status !== "queued")
659 ) {
660 return yield* new ThreadManagementDurableRunProjectionError({
661 threadId: input.threadId,
662 messageId: input.messageId,
663 });
664 }
665 const delivery: ThreadManagementSendResult["delivery"] =
666 turnItem === null || turnItem.inputIntent === "queued_turn"
667 ? "queued"
668 : turnItem.inputIntent === "turn_start"
669 ? "started"
670 : input.mode === "restart"
671 ? "restarted"
672 : "steered";
673 return { dispatch, projection, message, run, turnItem, delivery };
674 });
675​
676 const waitForThread: ThreadManagementServiceShape["waitForThread"] = (input) =>
677 Effect.gen(function* () {
678 const loadError = (cause: unknown) =>
679 new ThreadManagementProjectionLoadError({
680 projectId: input.projectId,
681 threadId: input.threadId,
682 cause,
683 });
684 // Taken before the first read, so a run update between that read and
685 // the subscription below still replays.
686 const afterSequence = yield* orchestrator
687 .getThreadEventSequence(input.threadId)
688 .pipe(Effect.mapError(loadError));
689 const target = yield* getProjectThreadRecords(input, ["runs"]);
690 const selectedRun =
691 input.runId === undefined
692 ? latestRun(target)
693 : target.runs.find((candidate) => candidate.id === input.runId);
694 if (input.runId !== undefined && selectedRun === undefined) {
695 return yield* new ThreadManagementRunNotFoundError({
696 threadId: input.threadId,
697 runId: input.runId,
698 });
699 }
700 if (selectedRun === undefined) {
701 return { threadId: input.threadId, run: null, timedOut: false };
702 }
703 if (isTerminalRunStatus(selectedRun.status)) {
704 return { threadId: input.threadId, run: selectedRun, timedOut: false };
705 }
706​
707 // Re-read the run only when the thread records a run update or its
708 // deletion, instead of polling the projection for up to an hour. Each
709 // stream keeps one event type, so transcript events never fill its buffer.
710 const wait = Stream.merge(
711 orchestrator.streamStoredEventsFrom({
712 threadId: input.threadId,
713 afterSequence,
714 eventType: "run.updated",
715 }),
716 orchestrator.streamStoredEventsFrom({
717 threadId: input.threadId,
718 afterSequence,
719 eventType: "thread.deleted",
720 }),
721 ).pipe(
722 Stream.mapError(loadError),
723 Stream.filter(
724 (stored) =>
725 stored.event.type !== "run.updated" || stored.event.payload.id === selectedRun.id,
726 ),
727 Stream.mapEffect(() =>
728 getProjectThreadRecords(input, ["runs"], { runIds: [selectedRun.id] }).pipe(
729 Effect.flatMap((current) => {
730 const run = current.runs.find((candidate) => candidate.id === selectedRun.id);
731 return run === undefined
732 ? Effect.fail(
733 new ThreadManagementRunNotFoundError({
734 threadId: input.threadId,
735 runId: selectedRun.id,
736 }),
737 )
738 : Effect.succeed(run);
739 }),
740 ),
741 ),
742 Stream.filter((run) => isTerminalRunStatus(run.status)),
743 Stream.runHead,
744 Effect.timeoutOption(Duration.millis(Math.max(1, input.timeoutMs))),
745 );
746 const waited = Option.flatten(yield* wait);
747 if (Option.isSome(waited)) {
748 return { threadId: input.threadId, run: waited.value, timedOut: false };
749 }
750 const current = yield* getProjectThreadRecords(input, ["runs"], { runIds: [selectedRun.id] });
751 const run = current.runs.find((candidate) => candidate.id === selectedRun.id);
752 if (run === undefined) {
753 return yield* new ThreadManagementRunNotFoundError({
754 threadId: input.threadId,
755 runId: selectedRun.id,
756 });
757 }
758 // The run may have reached a terminal status while the timeout was
759 // winning the race; the final projection read decides what actually
760 // happened, so only a still-active run counts as timed out.
761 return { threadId: input.threadId, run, timedOut: !isTerminalRunStatus(run.status) };
762 });
763​
764 const settleAfterRun: ThreadManagementServiceShape["settleAfterRun"] = Effect.fn(
765 "orchestrationV2.threadManagement.settleAfterRun",
766 )(function* (input) {
767 // A turn that outlives this wait leaves its thread active.
768 const { run } = yield* waitForThread({ ...input, timeoutMs: SETTLE_AFTER_RUN_WAIT_MS });
769 if (run?.status !== "completed") return;
770 yield* dispatch({
771 type: "thread.settle",
772 commandId: CommandId.make(`server:settle-after-run:${input.runId}`),
773 threadId: input.threadId,
774 });
775 });
776​
777 const settleThread: ThreadManagementServiceShape["settleThread"] = Effect.fn(
778 "orchestrationV2.threadManagement.settleThread",
779 )(function* (input) {
780 const shell = input.byOwnAgent ? yield* orchestrator.getThreadShell(input.threadId) : null;
781 if (shell != null && shell.activeRunId !== null) {
782 yield* settleAfterRun({
783 projectId: shell.projectId,
784 threadId: shell.id,
785 runId: shell.activeRunId,
786 }).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(layerScope));
787 return { settlesWhenTurnEnds: true } as const;
788 }
789 const result = yield* dispatch({
790 type: "thread.settle",
791 commandId: input.commandId,
792 threadId: input.threadId,
793 });
794 return { sequence: result.sequence };
795 });
796​
797 const interruptThread: ThreadManagementServiceShape["interruptThread"] = (input) =>
798 Effect.gen(function* () {
799 const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
800 const explicitRun =
801 input.runId === undefined
802 ? undefined
803 : target.runs.find((candidate) => candidate.id === input.runId);
804 if (input.runId !== undefined && explicitRun === undefined) {
805 return yield* new ThreadManagementRunNotFoundError({
806 threadId: input.threadId,
807 runId: input.runId,
808 });
809 }
810 if (explicitRun !== undefined && isTerminalRunStatus(explicitRun.status)) {
811 return {
812 type: "already_terminal",
813 run: explicitRun as OrchestrationV2Run & {
814 readonly status: ThreadManagementTerminalRunStatus;
815 },
816 } as const;
817 }
818 const interruptibleRun = latestActiveRun(target);
819 if (interruptibleRun === undefined) {
820 if (input.runId === undefined) {
821 return { type: "no_active_run" } as const;
822 }
823 return yield* new ThreadManagementThreadNotInterruptibleError({
824 threadId: input.threadId,
825 runId: input.runId,
826 });
827 }
828 if (input.runId !== undefined && interruptibleRun.id !== input.runId) {
829 return yield* new ThreadManagementThreadNotInterruptibleError({
830 threadId: input.threadId,
831 runId: input.runId,
832 });
833 }
834 const dispatch = yield* orchestrator.dispatch({
835 type: "run.interrupt",
836 commandId: input.commandId,
837 threadId: input.threadId,
838 runId: interruptibleRun.id,
839 ...(input.reason === undefined ? {} : { reason: input.reason }),
840 });
841 return { type: "interrupt_requested", run: interruptibleRun, dispatch } as const;
842 });
843​
844 const stopDelegatedTasks: ThreadManagementServiceShape["stopDelegatedTasks"] = (input) =>
845 Effect.gen(function* () {
846 const { subagents } = yield* orchestrator.getThreadRecords(input.threadId, ["subagents"]);
847 const failures: Array<Orchestrator.OrchestratorV2Error> = [];
848 for (const task of subagents) {
849 if (task.origin !== "app_owned" || task.childThreadId === null) continue;
850 const threadId = task.childThreadId;
851 yield* dispatch({
852 type: "thread.stop",
853 commandId: CommandId.make(`${input.commandId}:stop:${threadId}`),
854 threadId,
855 ...(input.reason === undefined ? {} : { reason: input.reason }),
856 }).pipe(
857 Effect.andThen(stopDelegatedTasks({ ...input, threadId })),
858 Effect.catch((error) =>
859 Effect.logWarning("Unable to stop a delegated task", {
860 parentThreadId: input.threadId,
861 threadId,
862 error,
863 }).pipe(Effect.andThen(Effect.sync(() => failures.push(error)))),
864 ),
865 );
866 }
867 if (failures[0] !== undefined) return yield* Effect.fail(failures[0]);
868 });
869​
870 return ThreadManagementService.of({
871 ensureLegacyTranscript,
872 searchThreadStream: (input) =>
873 Stream.unwrap(
874 ensureProjectionTranscript(input.threadId).pipe(
875 Effect.as(orchestrator.searchThreadStream(input)),
876 ),
877 ),
878 searchThread: (input) =>
879 ensureProjectionTranscript(input.threadId).pipe(
880 Effect.andThen(orchestrator.searchThread(input)),
881 ),
882 dispatch,
883 getThreadHistoryPage: (threadId, cursor, throughEntryId, conversationOnly) =>
884 ensureProjectionTranscript(threadId).pipe(
885 Effect.andThen(
886 orchestrator.getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly),
887 ),
888 ),
889 getTimelinePage: (threadId, options) =>
890 ensureProjectionTranscript(threadId).pipe(
891 Effect.andThen(orchestrator.getTimelinePage(threadId, options)),
892 ),
893 getMessageCount: (threadId) =>
894 ensureProjectionTranscript(threadId).pipe(
895 Effect.andThen(orchestrator.getMessageCount(threadId)),
896 ),
897 getTurnItem: (input) =>
898 ensureProjectionTranscript(input.threadId).pipe(
899 Effect.andThen(orchestrator.getTurnItem(input)),
900 Effect.map((item) => ({ item: item === null ? null : projectTurnItemForDetail(item) })),
901 ),
902 getThreadRecords: (threadId, fields, filter) =>
903 ensureProjectionTranscript(threadId).pipe(
904 Effect.andThen(orchestrator.getThreadRecords(threadId, fields, filter)),
905 ),
906 getThreadProjection,
907 getCheckpointContext,
908 getThreadSnapshot,
909 getThreadSnapshotWindow,
910 getProjectThreadRecords,
911 getProjectThread,
912 getShellSnapshot: orchestrator.getShellSnapshot,
913 readShellSnapshot: orchestrator.readShellSnapshot,
914 getThreadShell: orchestrator.getThreadShell,
915 listProjectThreads,
916 sendToThread,
917 waitForThread,
918 settleAfterRun,
919 settleThread,
920 interruptThread,
921 stopDelegatedTasks,
922 getThreadEventSequence: orchestrator.getThreadEventSequence,
923 recoverDelegatedTask: orchestrator.recoverDelegatedTask,
924 delegatedTaskResultPending: orchestrator.delegatedTaskResultPending,
925 streamStoredEvents: orchestrator.streamStoredEvents,
926 streamStoredEventsFrom: orchestrator.streamStoredEventsFrom,
927 streamDomainEvents: orchestrator.streamDomainEvents,
928 });
929});
930​
931const layerLegacyV1ThreadImporterNoop = Layer.succeed(
932 LegacyV1ThreadImporter.LegacyV1ThreadImporter,
933 LegacyV1ThreadImporter.LegacyV1ThreadImporter.of({
934 pendingThreadCount: Effect.succeed(0),
935 reconcileShells: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
936 ensureTranscript: () => Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
937 importPendingTranscripts: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
938 }),
939);
940​
941export const layer: Layer.Layer<ThreadManagementService, never, Orchestrator.OrchestratorV2> =
942 Layer.effect(ThreadManagementService, make).pipe(Layer.provide(layerLegacyV1ThreadImporterNoop));
943​
944export const layerWithLegacyImporter: Layer.Layer<
945 ThreadManagementService,
946 never,
947 LegacyV1ThreadImporter.LegacyV1ThreadImporter | Orchestrator.OrchestratorV2
948> = Layer.effect(ThreadManagementService, make);