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

ThreadManagementService.ts

782 lines28.5 KB

1import type {
2 ProjectionRecordField,
3 ProjectionRecordFilter,
4 ProjectionRecords,
5} from "./ProjectionStore.ts";
6import {
7 type ChatAttachment,
8 type 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";
35​
36import * as Orchestrator from "./Orchestrator.ts";
37import { projectTurnItemForDetail } from "./WireProjection.ts";
38import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts";
39​
40export type ThreadManagementSendMode = "auto" | "queue" | "steer" | "restart";
41​
42export interface ThreadManagementProvenance {
43 readonly createdBy: OrchestrationV2Actor;
44 readonly creationSource: OrchestrationV2CreationSource;
46​
47export function withCreationProvenance(
48 command: OrchestrationV2Command,
49 provenance: ThreadManagementProvenance,
50): OrchestrationV2Command {
51 switch (command.type) {
52 case "thread.create":
53 case "message.dispatch":
54 case "thread.fork":
55 case "thread.merge_back":
56 case "delegated_task.request":
57 return { ...command, ...provenance };
58 default:
59 return command;
60 }
62​
63export function existingThreadIdsForCommand(
64 command: OrchestrationV2ServerCommand,
65): ReadonlyArray<ThreadId> {
66 switch (command.type) {
67 case "thread.create":
68 return [];
69 // Read-state commands only rewrite the thread payload's visited/unread
70 // watermark; they never touch messages, so they do not need the imported
71 // v1 transcript hydrated first. Visits fire on every thread-activity bump
72 // while a thread is open, so keeping them off the import path matters.
73 case "thread.visit":
74 case "thread.mark-unread":
75 return [];
76 case "thread.fork":
77 return [command.sourceThreadId];
78 case "thread.merge_back":
79 return command.sourceThreadId === command.targetThreadId
80 ? [command.sourceThreadId]
81 : [command.sourceThreadId, command.targetThreadId];
82 case "delegated_task.request":
83 case "delegated_task.wake-policy":
84 case "delegated_task.completion-delivery.acknowledge":
85 case "delegated_task.completion-delivery.dispose":
86 return [command.parentThreadId];
87 case "thread.created.record":
88 return command.parentThreadId === command.targetThreadId
89 ? [command.parentThreadId]
90 : [command.parentThreadId, command.targetThreadId];
91 default:
92 return [command.threadId];
93 }
95​
96export type ThreadManagementTerminalRunStatus = Extract<
97 OrchestrationV2Run["status"],
98 "completed" | "failed" | "cancelled" | "interrupted" | "rolled_back"
99>;
100​
101export interface ThreadManagementSendInput {
102 readonly projectId: ProjectId;
103 readonly commandId: CommandId;
104 readonly threadId: ThreadId;
105 readonly messageId: MessageId;
106 readonly scheduledTaskId?: ScheduledTaskId;
107 readonly senderThreadId?: ThreadId;
108 readonly text: string;
109 readonly attachments: ReadonlyArray<ChatAttachment>;
110 readonly modelSelection?: ModelSelection;
111 readonly mode: ThreadManagementSendMode;
112 readonly createdBy: OrchestrationV2Actor;
113 readonly creationSource: OrchestrationV2CreationSource;
115​
116export interface ThreadManagementSendResult {
117 readonly dispatch: Orchestrator.OrchestratorV2DispatchResult;
118 readonly projection: Pick<
119 OrchestrationV2ThreadProjection,
120 "thread" | "runs" | "messages" | "turnItems"
121 >;
122 readonly message: OrchestrationV2ConversationMessage;
123 readonly run: OrchestrationV2Run;
124 /** Null for queued sends: the user turn item materializes when the queued turn starts. */
125 readonly turnItem: Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> | null;
126 readonly delivery: "started" | "queued" | "steered" | "restarted";
128​
129export interface ThreadManagementWaitInput {
130 readonly projectId: ProjectId;
131 readonly threadId: ThreadId;
132 readonly runId?: RunId;
133 readonly timeoutMs: number;
134 readonly pollIntervalMs?: 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 readonly getThreadEventSequence: Orchestrator.OrchestratorV2["Service"]["getThreadEventSequence"];
327 readonly recoverDelegatedTask: Orchestrator.OrchestratorV2["Service"]["recoverDelegatedTask"];
328 readonly delegatedTaskResultPending: Orchestrator.OrchestratorV2["Service"]["delegatedTaskResultPending"];
329 readonly streamStoredEvents: Orchestrator.OrchestratorV2["Service"]["streamStoredEvents"];
330 readonly streamStoredEventsFrom: Orchestrator.OrchestratorV2["Service"]["streamStoredEventsFrom"];
331 readonly streamDomainEvents: Orchestrator.OrchestratorV2["Service"]["streamDomainEvents"];
333​
334export class ThreadManagementService extends Context.Service<
335 ThreadManagementService,
336 ThreadManagementServiceShape
337>()("t3/orchestration-v2/ThreadManagementService") {}
338​
339export function isActiveRun(run: OrchestrationV2Run): boolean {
340 return (
341 run.status === "preparing" ||
342 run.status === "starting" ||
343 run.status === "running" ||
344 run.status === "waiting"
345 );
347​
348export function isTerminalRunStatus(
349 status: OrchestrationV2Run["status"],
350): status is ThreadManagementTerminalRunStatus {
351 return (
352 status === "completed" ||
353 status === "failed" ||
354 status === "cancelled" ||
355 status === "interrupted" ||
356 status === "rolled_back"
357 );
359​
360export function latestRun(
361 projection: Pick<OrchestrationV2ThreadProjection, "runs">,
362): OrchestrationV2Run | undefined {
363 return projection.runs.toSorted((left, right) => right.ordinal - left.ordinal)[0];
365​
366export function latestActiveRun(
367 projection: Pick<OrchestrationV2ThreadProjection, "runs">,
368): OrchestrationV2Run | undefined {
369 return projection.runs
370 .filter(isActiveRun)
371 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
373​
374function latestSteerableRun(
375 projection: Pick<OrchestrationV2ThreadProjection, "runs" | "providerTurns">,
376): OrchestrationV2Run | undefined {
377 return projection.runs
378 .filter(
379 (run) =>
380 run.status === "running" &&
381 run.activeAttemptId !== null &&
382 projection.providerTurns.some(
383 (turn) => turn.runAttemptId === run.activeAttemptId && turn.status === "running",
384 ),
385 )
386 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
388​
389const make = Effect.gen(function* () {
390 const orchestrator = yield* Orchestrator.OrchestratorV2;
391 const legacyImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
392​
393 const ensureLegacyTranscript = Effect.fn(
394 "orchestrationV2.threadManagement.ensureLegacyTranscript",
395 )(function* (threadId: ThreadId) {
396 yield* legacyImporter.ensureTranscript(threadId).pipe(
397 Effect.tapError((cause) =>
398 Effect.logWarning("Unable to hydrate migrated v1 thread transcript", {
399 threadId,
400 cause,
401 }),
402 ),
403 );
404 });
405​
406 const ensureProjectionTranscript = (threadId: ThreadId) =>
407 ensureLegacyTranscript(threadId).pipe(
408 Effect.mapError(
409 (cause) =>
410 new Orchestrator.OrchestratorProjectionError({
411 threadId,
412 cause,
413 }),
414 ),
415 );
416​
417 const ensureCommandTranscripts = Effect.fn(
418 "orchestrationV2.threadManagement.ensureCommandTranscripts",
419 )(function* (command: OrchestrationV2ServerCommand) {
420 yield* Effect.forEach(
421 existingThreadIdsForCommand(command),
422 (threadId) => ensureLegacyTranscript(threadId),
423 { discard: true },
424 ).pipe(
425 Effect.mapError(
426 (cause) =>
427 new Orchestrator.OrchestratorDispatchError({
428 commandId: command.commandId,
429 commandType: command.type,
430 cause,
431 }),
432 ),
433 );
434 });
435​
436 const getThreadProjection: ThreadManagementServiceShape["getThreadProjection"] = (threadId) =>
437 ensureProjectionTranscript(threadId).pipe(
438 Effect.andThen(orchestrator.getThreadProjection(threadId)),
439 );
440​
441 const getCheckpointContext: ThreadManagementServiceShape["getCheckpointContext"] = (threadId) =>
442 ensureProjectionTranscript(threadId).pipe(
443 Effect.andThen(orchestrator.getCheckpointContext(threadId)),
444 );
445​
446 const getThreadSnapshot: ThreadManagementServiceShape["getThreadSnapshot"] = (threadId) =>
447 ensureProjectionTranscript(threadId).pipe(
448 Effect.andThen(orchestrator.getThreadSnapshot(threadId)),
449 );
450 const getThreadSnapshotWindow: ThreadManagementServiceShape["getThreadSnapshotWindow"] = (
451 threadId,
452 options,
453 ) =>
454 ensureProjectionTranscript(threadId).pipe(
455 Effect.andThen(orchestrator.getThreadSnapshotWindow(threadId, options)),
456 );
457​
458 const dispatch: ThreadManagementServiceShape["dispatch"] = (command) =>
459 ensureCommandTranscripts(command).pipe(Effect.andThen(orchestrator.dispatch(command)));
460​
461 const getProjectThread: ThreadManagementServiceShape["getProjectThread"] = (input) =>
462 getThreadProjection(input.threadId).pipe(
463 Effect.mapError(
464 (cause) =>
465 new ThreadManagementProjectionLoadError({
466 projectId: input.projectId,
467 threadId: input.threadId,
468 cause,
469 }),
470 ),
471 Effect.flatMap((projection) =>
472 projection.thread.projectId === input.projectId && projection.thread.deletedAt === null
473 ? Effect.succeed(projection)
474 : Effect.fail(
475 new ThreadManagementThreadNotFoundError({
476 projectId: input.projectId,
477 threadId: input.threadId,
478 }),
479 ),
480 ),
481 );
482​
483 const getProjectThreadRecords: ThreadManagementServiceShape["getProjectThreadRecords"] = (
484 input,
485 fields,
486 filter,
487 ) =>
488 ensureProjectionTranscript(input.threadId)
489 .pipe(Effect.andThen(orchestrator.getThreadRecords(input.threadId, fields, filter)))
490 .pipe(
491 Effect.mapError(
492 (cause) =>
493 new ThreadManagementProjectionLoadError({
494 projectId: input.projectId,
495 threadId: input.threadId,
496 cause,
497 }),
498 ),
499 Effect.flatMap((projection) =>
500 projection.thread.projectId === input.projectId && projection.thread.deletedAt === null
501 ? Effect.succeed(projection)
502 : Effect.fail(
503 new ThreadManagementThreadNotFoundError({
504 projectId: input.projectId,
505 threadId: input.threadId,
506 }),
507 ),
508 ),
509 );
510​
511 const listProjectThreads: ThreadManagementServiceShape["listProjectThreads"] = (input) =>
512 orchestrator.getShellSnapshot().pipe(
513 Effect.mapError(
514 (cause) =>
515 new ThreadManagementProjectThreadsListError({
516 projectId: input.projectId,
517 cause,
518 }),
519 ),
520 Effect.map((snapshot) =>
521 snapshot.threads
522 .filter((thread) => thread.projectId === input.projectId)
523 .filter(
524 (thread) =>
525 input.includeSubagents || thread.lineage.relationshipToParent !== "subagent",
526 )
527 .toSorted(
528 (left, right) =>
529 DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt) ||
530 right.id.localeCompare(left.id),
531 ),
532 ),
533 );
534​
535 const sendToThread: ThreadManagementServiceShape["sendToThread"] = (input) =>
536 Effect.gen(function* () {
537 const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
538 if (target.thread.archivedAt !== null) {
539 return yield* new ThreadManagementThreadArchivedError({
540 threadId: input.threadId,
541 });
542 }
543​
544 const steerableRun = latestSteerableRun(target);
545 let dispatchMode: Extract<
546 OrchestrationV2Command,
547 { readonly type: "message.dispatch" }
548 >["dispatchMode"];
549 if (input.mode === "steer" || input.mode === "restart") {
550 if (steerableRun === undefined) {
551 return yield* new ThreadManagementNoSteerableRunError({
552 threadId: input.threadId,
553 mode: input.mode,
554 });
555 }
556 dispatchMode = {
557 type: input.mode === "steer" ? "steer_active" : "restart_active",
558 targetRunId: steerableRun.id,
559 };
560 } else if (input.mode === "auto" && steerableRun !== undefined) {
561 dispatchMode = { type: "steer_active", targetRunId: steerableRun.id };
562 } else {
563 dispatchMode = {
564 type: input.mode === "queue" ? "queue_after_active" : "start_immediately",
565 };
566 }
567​
568 const dispatch = yield* orchestrator.dispatch({
569 type: "message.dispatch",
570 commandId: input.commandId,
571 threadId: input.threadId,
572 messageId: input.messageId,
573 ...(input.scheduledTaskId === undefined ? {} : { scheduledTaskId: input.scheduledTaskId }),
574 ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
575 text: input.text,
576 attachments: input.attachments,
577 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
578 dispatchMode,
579 createdBy: input.createdBy,
580 creationSource: input.creationSource,
581 });
582 const projection = yield* getProjectThreadRecords(input, ["runs", "messages", "turnItems"], {
583 messageIds: [input.messageId],
584 turnItemTypes: ["user_message"],
585 });
586 const message = projection.messages.find((candidate) => candidate.id === input.messageId);
587 const run =
588 message?.runId === null || message?.runId === undefined
589 ? undefined
590 : projection.runs.find((candidate) => candidate.id === message.runId);
591 const turnItem =
592 projection.turnItems.find(
593 (
594 candidate,
595 ): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> =>
596 candidate.type === "user_message" && candidate.messageId === input.messageId,
597 ) ?? null;
598 // A queued message's user turn item is deliberately not emitted at
599 // dispatch time — it materializes when the queued turn actually starts,
600 // so it can map onto the provider turn. Every other dispatch mode still
601 // produces its turn item transactionally with the run.
602 if (
603 message === undefined ||
604 run === undefined ||
605 (turnItem === null && run.status !== "queued")
606 ) {
607 return yield* new ThreadManagementDurableRunProjectionError({
608 threadId: input.threadId,
609 messageId: input.messageId,
610 });
611 }
612 const delivery: ThreadManagementSendResult["delivery"] =
613 turnItem === null || turnItem.inputIntent === "queued_turn"
614 ? "queued"
615 : turnItem.inputIntent === "turn_start"
616 ? "started"
617 : input.mode === "restart"
618 ? "restarted"
619 : "steered";
620 return { dispatch, projection, message, run, turnItem, delivery };
621 });
622​
623 const waitForThread: ThreadManagementServiceShape["waitForThread"] = (input) =>
624 Effect.gen(function* () {
625 const target = yield* getProjectThreadRecords(input, ["runs"]);
626 const selectedRun =
627 input.runId === undefined
628 ? latestRun(target)
629 : target.runs.find((candidate) => candidate.id === input.runId);
630 if (input.runId !== undefined && selectedRun === undefined) {
631 return yield* new ThreadManagementRunNotFoundError({
632 threadId: input.threadId,
633 runId: input.runId,
634 });
635 }
636 if (selectedRun === undefined) {
637 return { threadId: input.threadId, run: null, timedOut: false };
638 }
639 if (isTerminalRunStatus(selectedRun.status)) {
640 return { threadId: input.threadId, run: selectedRun, timedOut: false };
641 }
642​
643 const wait = Effect.gen(function* () {
644 while (true) {
645 const current = yield* getProjectThreadRecords(input, ["runs"], {
646 runIds: [selectedRun.id],
647 });
648 const run = current.runs.find((candidate) => candidate.id === selectedRun.id);
649 if (run === undefined) {
650 return yield* new ThreadManagementRunNotFoundError({
651 threadId: input.threadId,
652 runId: selectedRun.id,
653 });
654 }
655 if (isTerminalRunStatus(run.status)) return run;
656 yield* Effect.sleep(Duration.millis(Math.max(1, input.pollIntervalMs ?? 250)));
657 }
658 }).pipe(Effect.timeoutOption(Duration.millis(Math.max(1, input.timeoutMs))));
659 const waited = yield* wait;
660 if (Option.isSome(waited)) {
661 return { threadId: input.threadId, run: waited.value, timedOut: false };
662 }
663 const current = yield* getProjectThreadRecords(input, ["runs"], { runIds: [selectedRun.id] });
664 const run = current.runs.find((candidate) => candidate.id === selectedRun.id);
665 if (run === undefined) {
666 return yield* new ThreadManagementRunNotFoundError({
667 threadId: input.threadId,
668 runId: selectedRun.id,
669 });
670 }
671 // The run may have reached a terminal status while the timeout was
672 // winning the race; the final projection read decides what actually
673 // happened, so only a still-active run counts as timed out.
674 return { threadId: input.threadId, run, timedOut: !isTerminalRunStatus(run.status) };
675 });
676​
677 const interruptThread: ThreadManagementServiceShape["interruptThread"] = (input) =>
678 Effect.gen(function* () {
679 const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
680 const explicitRun =
681 input.runId === undefined
682 ? undefined
683 : target.runs.find((candidate) => candidate.id === input.runId);
684 if (input.runId !== undefined && explicitRun === undefined) {
685 return yield* new ThreadManagementRunNotFoundError({
686 threadId: input.threadId,
687 runId: input.runId,
688 });
689 }
690 if (explicitRun !== undefined && isTerminalRunStatus(explicitRun.status)) {
691 return {
692 type: "already_terminal",
693 run: explicitRun as OrchestrationV2Run & {
694 readonly status: ThreadManagementTerminalRunStatus;
695 },
696 } as const;
697 }
698 const interruptibleRun = latestActiveRun(target);
699 if (interruptibleRun === undefined) {
700 if (input.runId === undefined) {
701 return { type: "no_active_run" } as const;
702 }
703 return yield* new ThreadManagementThreadNotInterruptibleError({
704 threadId: input.threadId,
705 runId: input.runId,
706 });
707 }
708 if (input.runId !== undefined && interruptibleRun.id !== input.runId) {
709 return yield* new ThreadManagementThreadNotInterruptibleError({
710 threadId: input.threadId,
711 runId: input.runId,
712 });
713 }
714 const dispatch = yield* orchestrator.dispatch({
715 type: "run.interrupt",
716 commandId: input.commandId,
717 threadId: input.threadId,
718 runId: interruptibleRun.id,
719 ...(input.reason === undefined ? {} : { reason: input.reason }),
720 });
721 return { type: "interrupt_requested", run: interruptibleRun, dispatch } as const;
722 });
723​
724 return ThreadManagementService.of({
725 ensureLegacyTranscript,
726 dispatch,
727 getTimelinePage: (threadId, options) =>
728 ensureProjectionTranscript(threadId).pipe(
729 Effect.andThen(orchestrator.getTimelinePage(threadId, options)),
730 ),
731 getMessageCount: (threadId) =>
732 ensureProjectionTranscript(threadId).pipe(
733 Effect.andThen(orchestrator.getMessageCount(threadId)),
734 ),
735 getTurnItem: (input) =>
736 ensureProjectionTranscript(input.threadId).pipe(
737 Effect.andThen(orchestrator.getTurnItem(input)),
738 Effect.map((item) => ({ item: item === null ? null : projectTurnItemForDetail(item) })),
739 ),
740 getThreadRecords: (threadId, fields, filter) =>
741 ensureProjectionTranscript(threadId).pipe(
742 Effect.andThen(orchestrator.getThreadRecords(threadId, fields, filter)),
743 ),
744 getThreadProjection,
745 getCheckpointContext,
746 getThreadSnapshot,
747 getThreadSnapshotWindow,
748 getProjectThreadRecords,
749 getProjectThread,
750 getShellSnapshot: orchestrator.getShellSnapshot,
751 getThreadShell: orchestrator.getThreadShell,
752 listProjectThreads,
753 sendToThread,
754 waitForThread,
755 interruptThread,
756 getThreadEventSequence: orchestrator.getThreadEventSequence,
757 recoverDelegatedTask: orchestrator.recoverDelegatedTask,
758 delegatedTaskResultPending: orchestrator.delegatedTaskResultPending,
759 streamStoredEvents: orchestrator.streamStoredEvents,
760 streamStoredEventsFrom: orchestrator.streamStoredEventsFrom,
761 streamDomainEvents: orchestrator.streamDomainEvents,
762 });
763});
764​
765const legacyV1ThreadImporterNoopLayer = Layer.succeed(
766 LegacyV1ThreadImporter.LegacyV1ThreadImporter,
767 LegacyV1ThreadImporter.LegacyV1ThreadImporter.of({
768 pendingThreadCount: Effect.succeed(0),
769 reconcileShells: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
770 ensureTranscript: () => Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
771 importPendingTranscripts: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
772 }),
773);
774​
775export const layer: Layer.Layer<ThreadManagementService, never, Orchestrator.OrchestratorV2> =
776 Layer.effect(ThreadManagementService, make).pipe(Layer.provide(legacyV1ThreadImporterNoopLayer));
777​
778export const layerWithLegacyImporter: Layer.Layer<
779 ThreadManagementService,
780 never,
781 LegacyV1ThreadImporter.LegacyV1ThreadImporter | Orchestrator.OrchestratorV2
782> = Layer.effect(ThreadManagementService, make);