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

ThreadManagementService.ts

762 lines27.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 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;
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 }
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 }
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;
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";
125​
126export interface ThreadManagementWaitInput {
127 readonly projectId: ProjectId;
128 readonly threadId: ThreadId;
129 readonly runId?: RunId;
130 readonly timeoutMs: number;
131 readonly pollIntervalMs?: number;
133​
134export interface ThreadManagementWaitResult {
135 readonly threadId: ThreadId;
136 readonly run: OrchestrationV2Run | null;
137 readonly timedOut: boolean;
139​
140export interface ThreadManagementInterruptInput {
141 readonly projectId: ProjectId;
142 readonly commandId: CommandId;
143 readonly threadId: ThreadId;
144 readonly runId?: RunId;
145 readonly reason?: string;
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 streamStoredEvents: Orchestrator.OrchestratorV2["Service"]["streamStoredEvents"];
317 readonly streamStoredEventsFrom: Orchestrator.OrchestratorV2["Service"]["streamStoredEventsFrom"];
318 readonly streamDomainEvents: Orchestrator.OrchestratorV2["Service"]["streamDomainEvents"];
320​
321export class ThreadManagementService extends Context.Service<
322 ThreadManagementService,
323 ThreadManagementServiceShape
324>()("t3/orchestration-v2/ThreadManagementService") {}
325​
326export function isActiveRun(run: OrchestrationV2Run): boolean {
327 return (
328 run.status === "preparing" ||
329 run.status === "starting" ||
330 run.status === "running" ||
331 run.status === "waiting"
332 );
334​
335export function isTerminalRunStatus(
336 status: OrchestrationV2Run["status"],
337): status is ThreadManagementTerminalRunStatus {
338 return (
339 status === "completed" ||
340 status === "failed" ||
341 status === "cancelled" ||
342 status === "interrupted" ||
343 status === "rolled_back"
344 );
346​
347export function latestRun(
348 projection: Pick<OrchestrationV2ThreadProjection, "runs">,
349): OrchestrationV2Run | undefined {
350 return projection.runs.toSorted((left, right) => right.ordinal - left.ordinal)[0];
352​
353export function latestActiveRun(
354 projection: Pick<OrchestrationV2ThreadProjection, "runs">,
355): OrchestrationV2Run | undefined {
356 return projection.runs
357 .filter(isActiveRun)
358 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
360​
361function latestSteerableRun(
362 projection: Pick<OrchestrationV2ThreadProjection, "runs" | "providerTurns">,
363): OrchestrationV2Run | undefined {
364 return projection.runs
365 .filter(
366 (run) =>
367 run.status === "running" &&
368 run.activeAttemptId !== null &&
369 projection.providerTurns.some(
370 (turn) => turn.runAttemptId === run.activeAttemptId && turn.status === "running",
371 ),
372 )
373 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
375​
376const make = Effect.gen(function* () {
377 const orchestrator = yield* Orchestrator.OrchestratorV2;
378 const legacyImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
379​
380 const ensureLegacyTranscript = Effect.fn(
381 "orchestrationV2.threadManagement.ensureLegacyTranscript",
382 )(function* (threadId: ThreadId) {
383 yield* legacyImporter.ensureTranscript(threadId).pipe(
384 Effect.tapError((cause) =>
385 Effect.logWarning("Unable to hydrate migrated v1 thread transcript", {
386 threadId,
387 cause,
388 }),
389 ),
390 );
391 });
392​
393 const ensureProjectionTranscript = (threadId: ThreadId) =>
394 ensureLegacyTranscript(threadId).pipe(
395 Effect.mapError(
396 (cause) =>
397 new Orchestrator.OrchestratorProjectionError({
398 threadId,
399 cause,
400 }),
401 ),
402 );
403​
404 const ensureCommandTranscripts = Effect.fn(
405 "orchestrationV2.threadManagement.ensureCommandTranscripts",
406 )(function* (command: OrchestrationV2ServerCommand) {
407 yield* Effect.forEach(
408 existingThreadIdsForCommand(command),
409 (threadId) => ensureLegacyTranscript(threadId),
410 { discard: true },
411 ).pipe(
412 Effect.mapError(
413 (cause) =>
414 new Orchestrator.OrchestratorDispatchError({
415 commandId: command.commandId,
416 commandType: command.type,
417 cause,
418 }),
419 ),
420 );
421 });
422​
423 const getThreadProjection: ThreadManagementServiceShape["getThreadProjection"] = (threadId) =>
424 ensureProjectionTranscript(threadId).pipe(
425 Effect.andThen(orchestrator.getThreadProjection(threadId)),
426 );
427​
428 const getCheckpointContext: ThreadManagementServiceShape["getCheckpointContext"] = (threadId) =>
429 ensureProjectionTranscript(threadId).pipe(
430 Effect.andThen(orchestrator.getCheckpointContext(threadId)),
431 );
432​
433 const getThreadSnapshot: ThreadManagementServiceShape["getThreadSnapshot"] = (threadId) =>
434 ensureProjectionTranscript(threadId).pipe(
435 Effect.andThen(orchestrator.getThreadSnapshot(threadId)),
436 );
437 const getThreadSnapshotWindow: ThreadManagementServiceShape["getThreadSnapshotWindow"] = (
438 threadId,
439 options,
440 ) =>
441 ensureProjectionTranscript(threadId).pipe(
442 Effect.andThen(orchestrator.getThreadSnapshotWindow(threadId, options)),
443 );
444​
445 const dispatch: ThreadManagementServiceShape["dispatch"] = (command) =>
446 ensureCommandTranscripts(command).pipe(Effect.andThen(orchestrator.dispatch(command)));
447​
448 const getProjectThread: ThreadManagementServiceShape["getProjectThread"] = (input) =>
449 getThreadProjection(input.threadId).pipe(
450 Effect.mapError(
451 (cause) =>
452 new ThreadManagementProjectionLoadError({
453 projectId: input.projectId,
454 threadId: input.threadId,
455 cause,
456 }),
457 ),
458 Effect.flatMap((projection) =>
459 projection.thread.projectId === input.projectId && projection.thread.deletedAt === null
460 ? Effect.succeed(projection)
461 : Effect.fail(
462 new ThreadManagementThreadNotFoundError({
463 projectId: input.projectId,
464 threadId: input.threadId,
465 }),
466 ),
467 ),
468 );
469​
470 const getProjectThreadRecords: ThreadManagementServiceShape["getProjectThreadRecords"] = (
471 input,
472 fields,
473 filter,
474 ) =>
475 ensureProjectionTranscript(input.threadId)
476 .pipe(Effect.andThen(orchestrator.getThreadRecords(input.threadId, fields, filter)))
477 .pipe(
478 Effect.mapError(
479 (cause) =>
480 new ThreadManagementProjectionLoadError({
481 projectId: input.projectId,
482 threadId: input.threadId,
483 cause,
484 }),
485 ),
486 Effect.flatMap((projection) =>
487 projection.thread.projectId === input.projectId && projection.thread.deletedAt === null
488 ? Effect.succeed(projection)
489 : Effect.fail(
490 new ThreadManagementThreadNotFoundError({
491 projectId: input.projectId,
492 threadId: input.threadId,
493 }),
494 ),
495 ),
496 );
497​
498 const listProjectThreads: ThreadManagementServiceShape["listProjectThreads"] = (input) =>
499 orchestrator.getShellSnapshot().pipe(
500 Effect.mapError(
501 (cause) =>
502 new ThreadManagementProjectThreadsListError({
503 projectId: input.projectId,
504 cause,
505 }),
506 ),
507 Effect.map((snapshot) =>
508 snapshot.threads
509 .filter((thread) => thread.projectId === input.projectId)
510 .filter(
511 (thread) =>
512 input.includeSubagents || thread.lineage.relationshipToParent !== "subagent",
513 )
514 .toSorted(
515 (left, right) =>
516 DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt) ||
517 right.id.localeCompare(left.id),
518 ),
519 ),
520 );
521​
522 const sendToThread: ThreadManagementServiceShape["sendToThread"] = (input) =>
523 Effect.gen(function* () {
524 const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
525 if (target.thread.archivedAt !== null) {
526 return yield* new ThreadManagementThreadArchivedError({
527 threadId: input.threadId,
528 });
529 }
530​
531 const steerableRun = latestSteerableRun(target);
532 let dispatchMode: Extract<
533 OrchestrationV2Command,
534 { readonly type: "message.dispatch" }
535 >["dispatchMode"];
536 if (input.mode === "steer" || input.mode === "restart") {
537 if (steerableRun === undefined) {
538 return yield* new ThreadManagementNoSteerableRunError({
539 threadId: input.threadId,
540 mode: input.mode,
541 });
542 }
543 dispatchMode = {
544 type: input.mode === "steer" ? "steer_active" : "restart_active",
545 targetRunId: steerableRun.id,
546 };
547 } else if (input.mode === "auto" && steerableRun !== undefined) {
548 dispatchMode = { type: "steer_active", targetRunId: steerableRun.id };
549 } else {
550 dispatchMode = {
551 type: input.mode === "queue" ? "queue_after_active" : "start_immediately",
552 };
553 }
554​
555 const dispatch = yield* orchestrator.dispatch({
556 type: "message.dispatch",
557 commandId: input.commandId,
558 threadId: input.threadId,
559 messageId: input.messageId,
560 ...(input.scheduledTaskId === undefined ? {} : { scheduledTaskId: input.scheduledTaskId }),
561 ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
562 text: input.text,
563 attachments: input.attachments,
564 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
565 dispatchMode,
566 createdBy: input.createdBy,
567 creationSource: input.creationSource,
568 });
569 const projection = yield* getProjectThreadRecords(input, ["runs", "messages", "turnItems"], {
570 messageIds: [input.messageId],
571 turnItemTypes: ["user_message"],
572 });
573 const message = projection.messages.find((candidate) => candidate.id === input.messageId);
574 const run =
575 message?.runId === null || message?.runId === undefined
576 ? undefined
577 : projection.runs.find((candidate) => candidate.id === message.runId);
578 const turnItem =
579 projection.turnItems.find(
580 (
581 candidate,
582 ): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> =>
583 candidate.type === "user_message" && candidate.messageId === input.messageId,
584 ) ?? null;
585 // A queued message's user turn item is deliberately not emitted at
586 // dispatch time — it materializes when the queued turn actually starts,
587 // so it can map onto the provider turn. Every other dispatch mode still
588 // produces its turn item transactionally with the run.
589 if (
590 message === undefined ||
591 run === undefined ||
592 (turnItem === null && run.status !== "queued")
593 ) {
594 return yield* new ThreadManagementDurableRunProjectionError({
595 threadId: input.threadId,
596 messageId: input.messageId,
597 });
598 }
599 const delivery: ThreadManagementSendResult["delivery"] =
600 turnItem === null || turnItem.inputIntent === "queued_turn"
601 ? "queued"
602 : turnItem.inputIntent === "turn_start"
603 ? "started"
604 : input.mode === "restart"
605 ? "restarted"
606 : "steered";
607 return { dispatch, projection, message, run, turnItem, delivery };
608 });
609​
610 const waitForThread: ThreadManagementServiceShape["waitForThread"] = (input) =>
611 Effect.gen(function* () {
612 const target = yield* getProjectThreadRecords(input, ["runs"]);
613 const selectedRun =
614 input.runId === undefined
615 ? latestRun(target)
616 : target.runs.find((candidate) => candidate.id === input.runId);
617 if (input.runId !== undefined && selectedRun === undefined) {
618 return yield* new ThreadManagementRunNotFoundError({
619 threadId: input.threadId,
620 runId: input.runId,
621 });
622 }
623 if (selectedRun === undefined) {
624 return { threadId: input.threadId, run: null, timedOut: false };
625 }
626 if (isTerminalRunStatus(selectedRun.status)) {
627 return { threadId: input.threadId, run: selectedRun, timedOut: false };
628 }
629​
630 const wait = Effect.gen(function* () {
631 while (true) {
632 const current = yield* getProjectThreadRecords(input, ["runs"], {
633 runIds: [selectedRun.id],
634 });
635 const run = current.runs.find((candidate) => candidate.id === selectedRun.id);
636 if (run === undefined) {
637 return yield* new ThreadManagementRunNotFoundError({
638 threadId: input.threadId,
639 runId: selectedRun.id,
640 });
641 }
642 if (isTerminalRunStatus(run.status)) return run;
643 yield* Effect.sleep(Duration.millis(Math.max(1, input.pollIntervalMs ?? 250)));
644 }
645 }).pipe(Effect.timeoutOption(Duration.millis(Math.max(1, input.timeoutMs))));
646 const waited = yield* wait;
647 if (Option.isSome(waited)) {
648 return { threadId: input.threadId, run: waited.value, timedOut: false };
649 }
650 const current = yield* getProjectThreadRecords(input, ["runs"], { runIds: [selectedRun.id] });
651 const run = current.runs.find((candidate) => candidate.id === selectedRun.id);
652 if (run === undefined) {
653 return yield* new ThreadManagementRunNotFoundError({
654 threadId: input.threadId,
655 runId: selectedRun.id,
656 });
657 }
658 // The run may have reached a terminal status while the timeout was
659 // winning the race; the final projection read decides what actually
660 // happened, so only a still-active run counts as timed out.
661 return { threadId: input.threadId, run, timedOut: !isTerminalRunStatus(run.status) };
662 });
663​
664 const interruptThread: ThreadManagementServiceShape["interruptThread"] = (input) =>
665 Effect.gen(function* () {
666 const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
667 const explicitRun =
668 input.runId === undefined
669 ? undefined
670 : target.runs.find((candidate) => candidate.id === input.runId);
671 if (input.runId !== undefined && explicitRun === undefined) {
672 return yield* new ThreadManagementRunNotFoundError({
673 threadId: input.threadId,
674 runId: input.runId,
675 });
676 }
677 if (explicitRun !== undefined && isTerminalRunStatus(explicitRun.status)) {
678 return {
679 type: "already_terminal",
680 run: explicitRun as OrchestrationV2Run & {
681 readonly status: ThreadManagementTerminalRunStatus;
682 },
683 } as const;
684 }
685 const interruptibleRun = latestActiveRun(target);
686 if (interruptibleRun === undefined) {
687 if (input.runId === undefined) {
688 return { type: "no_active_run" } as const;
689 }
690 return yield* new ThreadManagementThreadNotInterruptibleError({
691 threadId: input.threadId,
692 runId: input.runId,
693 });
694 }
695 if (input.runId !== undefined && interruptibleRun.id !== input.runId) {
696 return yield* new ThreadManagementThreadNotInterruptibleError({
697 threadId: input.threadId,
698 runId: input.runId,
699 });
700 }
701 const dispatch = yield* orchestrator.dispatch({
702 type: "run.interrupt",
703 commandId: input.commandId,
704 threadId: input.threadId,
705 runId: interruptibleRun.id,
706 ...(input.reason === undefined ? {} : { reason: input.reason }),
707 });
708 return { type: "interrupt_requested", run: interruptibleRun, dispatch } as const;
709 });
710​
711 return ThreadManagementService.of({
712 ensureLegacyTranscript,
713 dispatch,
714 getTimelinePage: (threadId, options) =>
715 ensureProjectionTranscript(threadId).pipe(
716 Effect.andThen(orchestrator.getTimelinePage(threadId, options)),
717 ),
718 getMessageCount: (threadId) =>
719 ensureProjectionTranscript(threadId).pipe(
720 Effect.andThen(orchestrator.getMessageCount(threadId)),
721 ),
722 getThreadRecords: (threadId, fields, filter) =>
723 ensureProjectionTranscript(threadId).pipe(
724 Effect.andThen(orchestrator.getThreadRecords(threadId, fields, filter)),
725 ),
726 getThreadProjection,
727 getCheckpointContext,
728 getThreadSnapshot,
729 getThreadSnapshotWindow,
730 getProjectThreadRecords,
731 getProjectThread,
732 getShellSnapshot: orchestrator.getShellSnapshot,
733 getThreadShell: orchestrator.getThreadShell,
734 listProjectThreads,
735 sendToThread,
736 waitForThread,
737 interruptThread,
738 getThreadEventSequence: orchestrator.getThreadEventSequence,
739 streamStoredEvents: orchestrator.streamStoredEvents,
740 streamStoredEventsFrom: orchestrator.streamStoredEventsFrom,
741 streamDomainEvents: orchestrator.streamDomainEvents,
742 });
743});
744​
745const legacyV1ThreadImporterNoopLayer = Layer.succeed(
746 LegacyV1ThreadImporter.LegacyV1ThreadImporter,
747 LegacyV1ThreadImporter.LegacyV1ThreadImporter.of({
748 pendingThreadCount: Effect.succeed(0),
749 reconcileShells: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
750 ensureTranscript: () => Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
751 importPendingTranscripts: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
752 }),
753);
754​
755export const layer: Layer.Layer<ThreadManagementService, never, Orchestrator.OrchestratorV2> =
756 Layer.effect(ThreadManagementService, make).pipe(Layer.provide(legacyV1ThreadImporterNoopLayer));
757​
758export const layerWithLegacyImporter: Layer.Layer<
759 ThreadManagementService,
760 never,
761 LegacyV1ThreadImporter.LegacyV1ThreadImporter | Orchestrator.OrchestratorV2
762> = Layer.effect(ThreadManagementService, make);