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