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

ThreadManagementService.ts

772 lines27.2 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 OrchestrationV2ConversationMessage,
14 type OrchestrationV2CreationSource,
15 type OrchestrationV2Run,
16 type OrchestrationV2ThreadShellSnapshot,
17 type OrchestrationV2ThreadProjection,
18 type OrchestrationV2ThreadShell,
19 type OrchestrationV2TurnItem,
20 ProjectId,
21 RunId,
22 type ScheduledTaskId,
23 ThreadId,
24} from "@t3tools/contracts";
25import * as Context from "effect/Context";
26import * as DateTime from "effect/DateTime";
27import * as Duration from "effect/Duration";
28import * as Effect from "effect/Effect";
29import * as Layer from "effect/Layer";
30import * as Option from "effect/Option";
31import * as Schema from "effect/Schema";
32​
33import {
34 OrchestratorDispatchError,
35 OrchestratorProjectionError,
36 OrchestratorV2,
37 type OrchestratorV2DispatchResult,
38 type OrchestratorV2Error,
39} from "./Orchestrator.ts";
40import {
41 LegacyV1ThreadImporter,
42 type LegacyV1ThreadImportError,
43} from "./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: OrchestrationV2Command,
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: 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;
139 readonly pollIntervalMs?: number;
141​
142export interface ThreadManagementWaitResult {
143 readonly threadId: ThreadId;
144 readonly run: OrchestrationV2Run | null;
145 readonly timedOut: boolean;
147​
148export interface ThreadManagementInterruptInput {
149 readonly projectId: ProjectId;
150 readonly commandId: CommandId;
151 readonly threadId: ThreadId;
152 readonly runId?: RunId;
153 readonly reason?: string;
155​
156export type ThreadManagementInterruptResult =
157 | {
158 readonly type: "interrupt_requested";
159 readonly run: OrchestrationV2Run;
160 readonly dispatch: OrchestratorV2DispatchResult;
161 }
162 | { readonly type: "no_active_run" }
163 | {
164 readonly type: "already_terminal";
165 readonly run: OrchestrationV2Run & { readonly status: ThreadManagementTerminalRunStatus };
166 };
167​
168export class ThreadManagementThreadNotFoundError extends Schema.TaggedError<ThreadManagementThreadNotFoundError>()(
169 "ThreadManagementThreadNotFoundError",
170 {
171 projectId: ProjectId,
172 threadId: ThreadId,
173 },
174) {
175 override get message(): string {
176 return `Thread ${this.threadId} was not found in project ${this.projectId}.`;
177 }
179​
180export class ThreadManagementRunNotFoundError extends Schema.TaggedError<ThreadManagementRunNotFoundError>()(
181 "ThreadManagementRunNotFoundError",
182 {
183 threadId: ThreadId,
184 runId: RunId,
185 },
186) {
187 override get message(): string {
188 return `Run ${this.runId} does not belong to thread ${this.threadId}.`;
189 }
191​
192export class ThreadManagementThreadArchivedError extends Schema.TaggedError<ThreadManagementThreadArchivedError>()(
193 "ThreadManagementThreadArchivedError",
194 {
195 threadId: ThreadId,
196 },
197) {
198 override get message(): string {
199 return `Thread ${this.threadId} is archived and cannot receive messages.`;
200 }
202​
203export class ThreadManagementNoSteerableRunError extends Schema.TaggedError<ThreadManagementNoSteerableRunError>()(
204 "ThreadManagementNoSteerableRunError",
205 {
206 threadId: ThreadId,
207 mode: Schema.Literals(["steer", "restart"]),
208 },
209) {
210 override get message(): string {
211 return `Thread ${this.threadId} has no running turn that can be ${this.mode === "steer" ? "steered" : "restarted"}.`;
212 }
214​
215export class ThreadManagementThreadNotInterruptibleError extends Schema.TaggedError<ThreadManagementThreadNotInterruptibleError>()(
216 "ThreadManagementThreadNotInterruptibleError",
217 {
218 threadId: ThreadId,
219 runId: RunId,
220 },
221) {
222 override get message(): string {
223 return `Run ${this.runId} is not currently interruptible.`;
224 }
226​
227export class ThreadManagementProjectionLoadError extends Schema.TaggedError<ThreadManagementProjectionLoadError>()(
228 "ThreadManagementProjectionLoadError",
229 {
230 projectId: ProjectId,
231 threadId: ThreadId,
232 cause: Schema.Defect(),
233 },
234) {
235 override get message(): string {
236 return `Unable to load thread ${this.threadId} in project ${this.projectId}.`;
237 }
239​
240export class ThreadManagementProjectThreadsListError extends Schema.TaggedError<ThreadManagementProjectThreadsListError>()(
241 "ThreadManagementProjectThreadsListError",
242 {
243 projectId: ProjectId,
244 cause: Schema.Defect(),
245 },
246) {
247 override get message(): string {
248 return `Unable to list threads in project ${this.projectId}.`;
249 }
251​
252export class ThreadManagementDurableRunProjectionError extends Schema.TaggedError<ThreadManagementDurableRunProjectionError>()(
253 "ThreadManagementDurableRunProjectionError",
254 {
255 threadId: ThreadId,
256 messageId: MessageId,
257 },
258) {
259 override get message(): string {
260 return `Message ${this.messageId} was accepted on thread ${this.threadId} without a durable run projection.`;
261 }
263​
264export const ThreadManagementError = Schema.Union([
265 ThreadManagementThreadNotFoundError,
266 ThreadManagementRunNotFoundError,
267 ThreadManagementThreadArchivedError,
268 ThreadManagementNoSteerableRunError,
269 ThreadManagementThreadNotInterruptibleError,
270 ThreadManagementProjectionLoadError,
271 ThreadManagementProjectThreadsListError,
272 ThreadManagementDurableRunProjectionError,
273]);
274export type ThreadManagementError = typeof ThreadManagementError.Type;
275​
276type ThreadManagementFailure = ThreadManagementError | OrchestratorV2Error;
277​
278export interface ThreadManagementServiceShape {
279 readonly ensureLegacyTranscript: (
280 threadId: ThreadId,
281 ) => Effect.Effect<void, LegacyV1ThreadImportError>;
282 readonly dispatch: (
283 command: OrchestrationV2Command,
284 ) => Effect.Effect<OrchestratorV2DispatchResult, OrchestratorV2Error>;
285 readonly getTimelinePage: OrchestratorV2["Service"]["getTimelinePage"];
286 readonly getMessageCount: OrchestratorV2["Service"]["getMessageCount"];
287 readonly getThreadRecords: OrchestratorV2["Service"]["getThreadRecords"];
288 readonly getThreadProjection: (
289 threadId: ThreadId,
290 ) => Effect.Effect<OrchestrationV2ThreadProjection, OrchestratorV2Error>;
291 readonly getCheckpointContext: OrchestratorV2["Service"]["getCheckpointContext"];
292 readonly getThreadSnapshot: OrchestratorV2["Service"]["getThreadSnapshot"];
293 readonly getThreadSnapshotWindow: OrchestratorV2["Service"]["getThreadSnapshotWindow"];
294 readonly getProjectThreadRecords: <K extends ProjectionRecordField>(
295 input: { readonly projectId: ProjectId; readonly threadId: ThreadId },
296 fields: ReadonlyArray<K>,
297 filter?: ProjectionRecordFilter,
298 ) => Effect.Effect<
299 ProjectionRecords<K>,
300 ThreadManagementProjectionLoadError | ThreadManagementThreadNotFoundError
301 >;
302 readonly getProjectThread: (input: {
303 readonly projectId: ProjectId;
304 readonly threadId: ThreadId;
305 }) => Effect.Effect<OrchestrationV2ThreadProjection, ThreadManagementError>;
306 readonly getShellSnapshot: (options?: {
307 readonly location?: "active" | "archive";
308 }) => Effect.Effect<OrchestrationV2ThreadShellSnapshot, OrchestratorV2Error>;
309 readonly getThreadShell: OrchestratorV2["Service"]["getThreadShell"];
310 readonly listProjectThreads: (input: {
311 readonly projectId: ProjectId;
312 readonly includeSubagents: boolean;
313 }) => Effect.Effect<ReadonlyArray<OrchestrationV2ThreadShell>, ThreadManagementError>;
314 readonly sendToThread: (
315 input: ThreadManagementSendInput,
316 ) => Effect.Effect<ThreadManagementSendResult, ThreadManagementFailure>;
317 readonly waitForThread: (
318 input: ThreadManagementWaitInput,
319 ) => Effect.Effect<ThreadManagementWaitResult, ThreadManagementError>;
320 readonly interruptThread: (
321 input: ThreadManagementInterruptInput,
322 ) => Effect.Effect<ThreadManagementInterruptResult, ThreadManagementFailure>;
323 readonly getThreadEventSequence: OrchestratorV2["Service"]["getThreadEventSequence"];
324 readonly streamStoredEvents: OrchestratorV2["Service"]["streamStoredEvents"];
325 readonly streamStoredEventsFrom: OrchestratorV2["Service"]["streamStoredEventsFrom"];
326 readonly streamDomainEvents: OrchestratorV2["Service"]["streamDomainEvents"];
328​
329export class ThreadManagementService extends Context.Service<
330 ThreadManagementService,
331 ThreadManagementServiceShape
332>()("t3/orchestration-v2/ThreadManagementService") {}
333​
334export function isActiveRun(run: OrchestrationV2Run): boolean {
335 return (
336 run.status === "preparing" ||
337 run.status === "starting" ||
338 run.status === "running" ||
339 run.status === "waiting"
340 );
342​
343export function isTerminalRunStatus(
344 status: OrchestrationV2Run["status"],
345): status is ThreadManagementTerminalRunStatus {
346 return (
347 status === "completed" ||
348 status === "failed" ||
349 status === "cancelled" ||
350 status === "interrupted" ||
351 status === "rolled_back"
352 );
354​
355export function latestRun(
356 projection: Pick<OrchestrationV2ThreadProjection, "runs">,
357): OrchestrationV2Run | undefined {
358 return projection.runs.toSorted((left, right) => right.ordinal - left.ordinal)[0];
360​
361export function latestActiveRun(
362 projection: Pick<OrchestrationV2ThreadProjection, "runs">,
363): OrchestrationV2Run | undefined {
364 return projection.runs
365 .filter(isActiveRun)
366 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
368​
369function latestSteerableRun(
370 projection: Pick<OrchestrationV2ThreadProjection, "runs" | "providerTurns">,
371): OrchestrationV2Run | undefined {
372 return projection.runs
373 .filter(
374 (run) =>
375 run.status === "running" &&
376 run.activeAttemptId !== null &&
377 projection.providerTurns.some(
378 (turn) => turn.runAttemptId === run.activeAttemptId && turn.status === "running",
379 ),
380 )
381 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
383​
384const make = Effect.gen(function* () {
385 const orchestrator = yield* OrchestratorV2;
386 const legacyImporter = yield* LegacyV1ThreadImporter;
387​
388 const ensureLegacyTranscript = Effect.fn(
389 "orchestrationV2.threadManagement.ensureLegacyTranscript",
390 )(function* (threadId: ThreadId) {
391 yield* legacyImporter.ensureTranscript(threadId).pipe(
392 Effect.tapError((cause) =>
393 Effect.logWarning("Unable to hydrate migrated v1 thread transcript", {
394 threadId,
395 cause,
396 }),
397 ),
398 );
399 });
400​
401 const ensureProjectionTranscript = (threadId: ThreadId) =>
402 ensureLegacyTranscript(threadId).pipe(
403 Effect.mapError(
404 (cause) =>
405 new OrchestratorProjectionError({
406 threadId,
407 cause,
408 }),
409 ),
410 );
411​
412 const ensureCommandTranscripts = Effect.fn(
413 "orchestrationV2.threadManagement.ensureCommandTranscripts",
414 )(function* (command: OrchestrationV2Command) {
415 yield* Effect.forEach(
416 existingThreadIdsForCommand(command),
417 (threadId) => ensureLegacyTranscript(threadId),
418 { discard: true },
419 ).pipe(
420 Effect.mapError(
421 (cause) =>
422 new OrchestratorDispatchError({
423 commandId: command.commandId,
424 commandType: command.type,
425 cause,
426 }),
427 ),
428 );
429 });
430​
431 const getThreadProjection: ThreadManagementServiceShape["getThreadProjection"] = (threadId) =>
432 ensureProjectionTranscript(threadId).pipe(
433 Effect.andThen(orchestrator.getThreadProjection(threadId)),
434 );
435​
436 const getCheckpointContext: ThreadManagementServiceShape["getCheckpointContext"] = (threadId) =>
437 ensureProjectionTranscript(threadId).pipe(
438 Effect.andThen(orchestrator.getCheckpointContext(threadId)),
439 );
440​
441 const getThreadSnapshot: ThreadManagementServiceShape["getThreadSnapshot"] = (threadId) =>
442 ensureProjectionTranscript(threadId).pipe(
443 Effect.andThen(orchestrator.getThreadSnapshot(threadId)),
444 );
445 const getThreadSnapshotWindow: ThreadManagementServiceShape["getThreadSnapshotWindow"] = (
446 threadId,
447 options,
448 ) =>
449 ensureProjectionTranscript(threadId).pipe(
450 Effect.andThen(orchestrator.getThreadSnapshotWindow(threadId, options)),
451 );
452​
453 const dispatch: ThreadManagementServiceShape["dispatch"] = (command) =>
454 ensureCommandTranscripts(command).pipe(Effect.andThen(orchestrator.dispatch(command)));
455​
456 const getProjectThread: ThreadManagementServiceShape["getProjectThread"] = (input) =>
457 getThreadProjection(input.threadId).pipe(
458 Effect.mapError(
459 (cause) =>
460 new ThreadManagementProjectionLoadError({
461 projectId: input.projectId,
462 threadId: input.threadId,
463 cause,
464 }),
465 ),
466 Effect.flatMap((projection) =>
467 projection.thread.projectId === input.projectId && projection.thread.deletedAt === null
468 ? Effect.succeed(projection)
469 : Effect.fail(
470 new ThreadManagementThreadNotFoundError({
471 projectId: input.projectId,
472 threadId: input.threadId,
473 }),
474 ),
475 ),
476 );
477​
478 const getProjectThreadRecords: ThreadManagementServiceShape["getProjectThreadRecords"] = (
479 input,
480 fields,
481 filter,
482 ) =>
483 ensureProjectionTranscript(input.threadId)
484 .pipe(Effect.andThen(orchestrator.getThreadRecords(input.threadId, fields, filter)))
485 .pipe(
486 Effect.mapError(
487 (cause) =>
488 new ThreadManagementProjectionLoadError({
489 projectId: input.projectId,
490 threadId: input.threadId,
491 cause,
492 }),
493 ),
494 Effect.flatMap((projection) =>
495 projection.thread.projectId === input.projectId && projection.thread.deletedAt === null
496 ? Effect.succeed(projection)
497 : Effect.fail(
498 new ThreadManagementThreadNotFoundError({
499 projectId: input.projectId,
500 threadId: input.threadId,
501 }),
502 ),
503 ),
504 );
505​
506 const listProjectThreads: ThreadManagementServiceShape["listProjectThreads"] = (input) =>
507 orchestrator.getShellSnapshot().pipe(
508 Effect.mapError(
509 (cause) =>
510 new ThreadManagementProjectThreadsListError({
511 projectId: input.projectId,
512 cause,
513 }),
514 ),
515 Effect.map((snapshot) =>
516 snapshot.threads
517 .filter((thread) => thread.projectId === input.projectId)
518 .filter(
519 (thread) =>
520 input.includeSubagents || thread.lineage.relationshipToParent !== "subagent",
521 )
522 .toSorted(
523 (left, right) =>
524 DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt) ||
525 right.id.localeCompare(left.id),
526 ),
527 ),
528 );
529​
530 const sendToThread: ThreadManagementServiceShape["sendToThread"] = (input) =>
531 Effect.gen(function* () {
532 const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
533 if (target.thread.archivedAt !== null) {
534 return yield* new ThreadManagementThreadArchivedError({
535 threadId: input.threadId,
536 });
537 }
538​
539 const steerableRun = latestSteerableRun(target);
540 let dispatchMode: Extract<
541 OrchestrationV2Command,
542 { readonly type: "message.dispatch" }
543 >["dispatchMode"];
544 if (input.mode === "steer" || input.mode === "restart") {
545 if (steerableRun === undefined) {
546 return yield* new ThreadManagementNoSteerableRunError({
547 threadId: input.threadId,
548 mode: input.mode,
549 });
550 }
551 dispatchMode = {
552 type: input.mode === "steer" ? "steer_active" : "restart_active",
553 targetRunId: steerableRun.id,
554 };
555 } else if (input.mode === "auto" && steerableRun !== undefined) {
556 dispatchMode = { type: "steer_active", targetRunId: steerableRun.id };
557 } else {
558 dispatchMode = {
559 type: input.mode === "queue" ? "queue_after_active" : "start_immediately",
560 };
561 }
562​
563 const dispatch = yield* orchestrator.dispatch({
564 type: "message.dispatch",
565 commandId: input.commandId,
566 threadId: input.threadId,
567 messageId: input.messageId,
568 ...(input.scheduledTaskId === undefined ? {} : { scheduledTaskId: input.scheduledTaskId }),
569 ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
570 text: input.text,
571 attachments: input.attachments,
572 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
573 dispatchMode,
574 createdBy: input.createdBy,
575 creationSource: input.creationSource,
576 });
577 const projection = yield* getProjectThreadRecords(input, ["runs", "messages", "turnItems"], {
578 messageIds: [input.messageId],
579 turnItemTypes: ["user_message"],
580 });
581 const message = projection.messages.find((candidate) => candidate.id === input.messageId);
582 const run =
583 message?.runId === null || message?.runId === undefined
584 ? undefined
585 : projection.runs.find((candidate) => candidate.id === message.runId);
586 const turnItem =
587 projection.turnItems.find(
588 (
589 candidate,
590 ): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> =>
591 candidate.type === "user_message" && candidate.messageId === input.messageId,
592 ) ?? null;
593 // A queued message's user turn item is deliberately not emitted at
594 // dispatch time — it materializes when the queued turn actually starts,
595 // so it can map onto the provider turn. Every other dispatch mode still
596 // produces its turn item transactionally with the run.
597 if (
598 message === undefined ||
599 run === undefined ||
600 (turnItem === null && run.status !== "queued")
601 ) {
602 return yield* new ThreadManagementDurableRunProjectionError({
603 threadId: input.threadId,
604 messageId: input.messageId,
605 });
606 }
607 const delivery: ThreadManagementSendResult["delivery"] =
608 turnItem === null || turnItem.inputIntent === "queued_turn"
609 ? "queued"
610 : turnItem.inputIntent === "turn_start"
611 ? "started"
612 : input.mode === "restart"
613 ? "restarted"
614 : "steered";
615 return { dispatch, projection, message, run, turnItem, delivery };
616 });
617​
618 const waitForThread: ThreadManagementServiceShape["waitForThread"] = (input) =>
619 Effect.gen(function* () {
620 const target = yield* getProjectThreadRecords(input, ["runs"]);
621 const selectedRun =
622 input.runId === undefined
623 ? latestRun(target)
624 : target.runs.find((candidate) => candidate.id === input.runId);
625 if (input.runId !== undefined && selectedRun === undefined) {
626 return yield* new ThreadManagementRunNotFoundError({
627 threadId: input.threadId,
628 runId: input.runId,
629 });
630 }
631 if (selectedRun === undefined) {
632 return { threadId: input.threadId, run: null, timedOut: false };
633 }
634 if (isTerminalRunStatus(selectedRun.status)) {
635 return { threadId: input.threadId, run: selectedRun, timedOut: false };
636 }
637​
638 const wait = Effect.gen(function* () {
639 while (true) {
640 const current = yield* getProjectThreadRecords(input, ["runs"], {
641 runIds: [selectedRun.id],
642 });
643 const run = current.runs.find((candidate) => candidate.id === selectedRun.id);
644 if (run === undefined) {
645 return yield* new ThreadManagementRunNotFoundError({
646 threadId: input.threadId,
647 runId: selectedRun.id,
648 });
649 }
650 if (isTerminalRunStatus(run.status)) return run;
651 yield* Effect.sleep(Duration.millis(Math.max(1, input.pollIntervalMs ?? 250)));
652 }
653 }).pipe(Effect.timeoutOption(Duration.millis(Math.max(1, input.timeoutMs))));
654 const waited = yield* wait;
655 if (Option.isSome(waited)) {
656 return { threadId: input.threadId, run: waited.value, timedOut: false };
657 }
658 const current = yield* getProjectThreadRecords(input, ["runs"], { runIds: [selectedRun.id] });
659 const run = current.runs.find((candidate) => candidate.id === selectedRun.id);
660 if (run === undefined) {
661 return yield* new ThreadManagementRunNotFoundError({
662 threadId: input.threadId,
663 runId: selectedRun.id,
664 });
665 }
666 // The run may have reached a terminal status while the timeout was
667 // winning the race; the final projection read decides what actually
668 // happened, so only a still-active run counts as timed out.
669 return { threadId: input.threadId, run, timedOut: !isTerminalRunStatus(run.status) };
670 });
671​
672 const interruptThread: ThreadManagementServiceShape["interruptThread"] = (input) =>
673 Effect.gen(function* () {
674 const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
675 const explicitRun =
676 input.runId === undefined
677 ? undefined
678 : target.runs.find((candidate) => candidate.id === input.runId);
679 if (input.runId !== undefined && explicitRun === undefined) {
680 return yield* new ThreadManagementRunNotFoundError({
681 threadId: input.threadId,
682 runId: input.runId,
683 });
684 }
685 if (explicitRun !== undefined && isTerminalRunStatus(explicitRun.status)) {
686 return {
687 type: "already_terminal",
688 run: explicitRun as OrchestrationV2Run & {
689 readonly status: ThreadManagementTerminalRunStatus;
690 },
691 } as const;
692 }
693 const interruptibleRun = latestActiveRun(target);
694 if (interruptibleRun === undefined) {
695 if (input.runId === undefined) {
696 return { type: "no_active_run" } as const;
697 }
698 return yield* new ThreadManagementThreadNotInterruptibleError({
699 threadId: input.threadId,
700 runId: input.runId,
701 });
702 }
703 if (input.runId !== undefined && interruptibleRun.id !== input.runId) {
704 return yield* new ThreadManagementThreadNotInterruptibleError({
705 threadId: input.threadId,
706 runId: input.runId,
707 });
708 }
709 const dispatch = yield* orchestrator.dispatch({
710 type: "run.interrupt",
711 commandId: input.commandId,
712 threadId: input.threadId,
713 runId: interruptibleRun.id,
714 ...(input.reason === undefined ? {} : { reason: input.reason }),
715 });
716 return { type: "interrupt_requested", run: interruptibleRun, dispatch } as const;
717 });
718​
719 return ThreadManagementService.of({
720 ensureLegacyTranscript,
721 dispatch,
722 getTimelinePage: (threadId, options) =>
723 ensureProjectionTranscript(threadId).pipe(
724 Effect.andThen(orchestrator.getTimelinePage(threadId, options)),
725 ),
726 getMessageCount: (threadId) =>
727 ensureProjectionTranscript(threadId).pipe(
728 Effect.andThen(orchestrator.getMessageCount(threadId)),
729 ),
730 getThreadRecords: (threadId, fields, filter) =>
731 ensureProjectionTranscript(threadId).pipe(
732 Effect.andThen(orchestrator.getThreadRecords(threadId, fields, filter)),
733 ),
734 getThreadProjection,
735 getCheckpointContext,
736 getThreadSnapshot,
737 getThreadSnapshotWindow,
738 getProjectThreadRecords,
739 getProjectThread,
740 getShellSnapshot: orchestrator.getShellSnapshot,
741 getThreadShell: orchestrator.getThreadShell,
742 listProjectThreads,
743 sendToThread,
744 waitForThread,
745 interruptThread,
746 getThreadEventSequence: orchestrator.getThreadEventSequence,
747 streamStoredEvents: orchestrator.streamStoredEvents,
748 streamStoredEventsFrom: orchestrator.streamStoredEventsFrom,
749 streamDomainEvents: orchestrator.streamDomainEvents,
750 });
751});
752​
753const legacyV1ThreadImporterNoopLayer = Layer.succeed(
754 LegacyV1ThreadImporter,
755 LegacyV1ThreadImporter.of({
756 pendingThreadCount: Effect.succeed(0),
757 reconcileShells: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
758 ensureTranscript: () => Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
759 importPendingTranscripts: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
760 }),
761);
762​
763export const layer: Layer.Layer<ThreadManagementService, never, OrchestratorV2> = Layer.effect(
764 ThreadManagementService,
765 make,
766).pipe(Layer.provide(legacyV1ThreadImporterNoopLayer));
767​
768export const layerWithLegacyImporter: Layer.Layer<
769 ThreadManagementService,
770 never,
771 LegacyV1ThreadImporter | OrchestratorV2
772> = Layer.effect(ThreadManagementService, make);