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

ThreadManagementService.ts

853 lines31.4 KB

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