Open History to see the last commit
1import type {
2 ProjectionRecordField,
3 ProjectionRecordFilter,
4 ProjectionRecords,
5} from "./ProjectionStore.ts";
6import {
7 type ChatAttachment,
8 CommandId,
9 MessageId,
10 type ModelSelection,
11 type OrchestrationV2Actor,
12 type OrchestrationV2Command,
13 type OrchestrationV2GetTurnItemResult,
14 type OrchestrationV2ServerCommand,
15 type OrchestrationV2ConversationMessage,
16 type OrchestrationV2CreationSource,
17 type OrchestrationV2Run,
18 type OrchestrationV2ThreadShellSnapshot,
19 type OrchestrationV2ThreadProjection,
20 type OrchestrationV2ThreadShell,
21 type OrchestrationV2TurnItem,
22 ProjectId,
23 RunId,
24 type ScheduledTaskId,
25 ThreadId,
26 type TurnItemId,
27} from "@t3tools/contracts";
28import * as Context from "effect/Context";
29import * as DateTime from "effect/DateTime";
30import * as Duration from "effect/Duration";
31import * as Effect from "effect/Effect";
32import * as Layer from "effect/Layer";
33import * as Option from "effect/Option";
34import * as Schema from "effect/Schema";
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;
45}
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 }
61}
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 }
94}
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;
114}
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";
127}
128
129export interface ThreadManagementWaitInput {
130 readonly projectId: ProjectId;
131 readonly threadId: ThreadId;
132 readonly runId?: RunId;
133 readonly timeoutMs: number;
134 readonly pollIntervalMs?: number;
135}
136
137export interface ThreadManagementWaitResult {
138 readonly threadId: ThreadId;
139 readonly run: OrchestrationV2Run | null;
140 readonly timedOut: boolean;
141}
142
143export interface ThreadManagementInterruptInput {
144 readonly projectId: ProjectId;
145 readonly commandId: CommandId;
146 readonly threadId: ThreadId;
147 readonly runId?: RunId;
148 readonly reason?: string;
149}
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 }
173}
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 }
185}
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 }
196}
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 }
208}
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 }
220}
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 }
233}
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 }
245}
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 }
257}
258
259export const ThreadManagementError = Schema.Union([
260 ThreadManagementThreadNotFoundError,
261 ThreadManagementRunNotFoundError,
262 ThreadManagementThreadArchivedError,
263 ThreadManagementNoSteerableRunError,
264 ThreadManagementThreadNotInterruptibleError,
265 ThreadManagementProjectionLoadError,
266 ThreadManagementProjectThreadsListError,
267 ThreadManagementDurableRunProjectionError,
268]);
269export type ThreadManagementError = typeof ThreadManagementError.Type;
270
271type ThreadManagementFailure = ThreadManagementError | Orchestrator.OrchestratorV2Error;
272
273export interface ThreadManagementServiceShape {
274 readonly ensureLegacyTranscript: (
275 threadId: ThreadId,
276 ) => Effect.Effect<void, LegacyV1ThreadImporter.LegacyV1ThreadImportError>;
277 readonly dispatch: (
278 command: OrchestrationV2ServerCommand,
279 ) => Effect.Effect<Orchestrator.OrchestratorV2DispatchResult, Orchestrator.OrchestratorV2Error>;
280 readonly getTimelinePage: Orchestrator.OrchestratorV2["Service"]["getTimelinePage"];
281 readonly getMessageCount: Orchestrator.OrchestratorV2["Service"]["getMessageCount"];
282 /**
283 * One turn item with the input and output the thread stream withholds,
284 * bounded for the wire. Clients fetch it when a tool row is expanded.
285 */
286 readonly getTurnItem: (input: {
287 readonly threadId: ThreadId;
288 readonly itemId: TurnItemId;
289 }) => Effect.Effect<OrchestrationV2GetTurnItemResult, Orchestrator.OrchestratorV2Error>;
290 readonly getThreadRecords: Orchestrator.OrchestratorV2["Service"]["getThreadRecords"];
291 readonly getThreadProjection: (
292 threadId: ThreadId,
293 ) => Effect.Effect<OrchestrationV2ThreadProjection, Orchestrator.OrchestratorV2Error>;
294 readonly getCheckpointContext: Orchestrator.OrchestratorV2["Service"]["getCheckpointContext"];
295 readonly getThreadSnapshot: Orchestrator.OrchestratorV2["Service"]["getThreadSnapshot"];
296 readonly getThreadSnapshotWindow: Orchestrator.OrchestratorV2["Service"]["getThreadSnapshotWindow"];
297 readonly getProjectThreadRecords: <K extends ProjectionRecordField>(
298 input: { readonly projectId: ProjectId; readonly threadId: ThreadId },
299 fields: ReadonlyArray<K>,
300 filter?: ProjectionRecordFilter,
301 ) => Effect.Effect<
302 ProjectionRecords<K>,
303 ThreadManagementProjectionLoadError | ThreadManagementThreadNotFoundError
304 >;
305 readonly getProjectThread: (input: {
306 readonly projectId: ProjectId;
307 readonly threadId: ThreadId;
308 }) => Effect.Effect<OrchestrationV2ThreadProjection, ThreadManagementError>;
309 readonly getShellSnapshot: (options?: {
310 readonly location?: "active" | "archive";
311 }) => Effect.Effect<OrchestrationV2ThreadShellSnapshot, Orchestrator.OrchestratorV2Error>;
312 readonly getThreadShell: Orchestrator.OrchestratorV2["Service"]["getThreadShell"];
313 readonly listProjectThreads: (input: {
314 readonly projectId: ProjectId;
315 readonly includeSubagents: boolean;
316 }) => Effect.Effect<ReadonlyArray<OrchestrationV2ThreadShell>, ThreadManagementError>;
317 readonly sendToThread: (
318 input: ThreadManagementSendInput,
319 ) => Effect.Effect<ThreadManagementSendResult, ThreadManagementFailure>;
320 readonly waitForThread: (
321 input: ThreadManagementWaitInput,
322 ) => Effect.Effect<ThreadManagementWaitResult, ThreadManagementError>;
323 readonly interruptThread: (
324 input: ThreadManagementInterruptInput,
325 ) => Effect.Effect<ThreadManagementInterruptResult, ThreadManagementFailure>;
326 /**
327 * Sends `thread.stop` to every delegated task under a thread, depth first. Their command IDs
328 * derive from `commandId`, so a retry repeats nothing that already stopped. A task that
329 * cannot be stopped does not keep the others running: all are tried, then it fails.
330 */
331 readonly stopDelegatedTasks: (input: {
332 readonly threadId: ThreadId;
333 readonly commandId: CommandId;
334 readonly reason?: string | undefined;
335 }) => Effect.Effect<void, Orchestrator.OrchestratorV2Error>;
336 readonly getThreadEventSequence: Orchestrator.OrchestratorV2["Service"]["getThreadEventSequence"];
337 readonly recoverDelegatedTask: Orchestrator.OrchestratorV2["Service"]["recoverDelegatedTask"];
338 readonly delegatedTaskResultPending: Orchestrator.OrchestratorV2["Service"]["delegatedTaskResultPending"];
339 readonly streamStoredEvents: Orchestrator.OrchestratorV2["Service"]["streamStoredEvents"];
340 readonly streamStoredEventsFrom: Orchestrator.OrchestratorV2["Service"]["streamStoredEventsFrom"];
341 readonly streamDomainEvents: Orchestrator.OrchestratorV2["Service"]["streamDomainEvents"];
342}
343
344export class ThreadManagementService extends Context.Service<
345 ThreadManagementService,
346 ThreadManagementServiceShape
347>()("t3/orchestration-v2/ThreadManagementService") {}
348
349export function isActiveRun(run: OrchestrationV2Run): boolean {
350 return (
351 run.status === "preparing" ||
352 run.status === "starting" ||
353 run.status === "running" ||
354 run.status === "waiting"
355 );
356}
357
358export function isTerminalRunStatus(
359 status: OrchestrationV2Run["status"],
360): status is ThreadManagementTerminalRunStatus {
361 return (
362 status === "completed" ||
363 status === "failed" ||
364 status === "cancelled" ||
365 status === "interrupted" ||
366 status === "rolled_back"
367 );
368}
369
370export function latestRun(
371 projection: Pick<OrchestrationV2ThreadProjection, "runs">,
372): OrchestrationV2Run | undefined {
373 return projection.runs.toSorted((left, right) => right.ordinal - left.ordinal)[0];
374}
375
376export function latestActiveRun(
377 projection: Pick<OrchestrationV2ThreadProjection, "runs">,
378): OrchestrationV2Run | undefined {
379 return projection.runs
380 .filter(isActiveRun)
381 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
382}
383
384function latestSteerableRun(
385 projection: Pick<OrchestrationV2ThreadProjection, "runs" | "providerTurns">,
386): OrchestrationV2Run | undefined {
387 return projection.runs
388 .filter(
389 (run) =>
390 run.status === "running" &&
391 run.activeAttemptId !== null &&
392 projection.providerTurns.some(
393 (turn) => turn.runAttemptId === run.activeAttemptId && turn.status === "running",
394 ),
395 )
396 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
397}
398
399const make = Effect.gen(function* () {
400 const orchestrator = yield* Orchestrator.OrchestratorV2;
401 const legacyImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
402
403 const ensureLegacyTranscript = Effect.fn(
404 "orchestrationV2.threadManagement.ensureLegacyTranscript",
405 )(function* (threadId: ThreadId) {
406 yield* legacyImporter.ensureTranscript(threadId).pipe(
407 Effect.tapError((cause) =>
408 Effect.logWarning("Unable to hydrate migrated v1 thread transcript", {
409 threadId,
410 cause,
411 }),
412 ),
413 );
414 });
415
416 const ensureProjectionTranscript = (threadId: ThreadId) =>
417 ensureLegacyTranscript(threadId).pipe(
418 Effect.mapError(
419 (cause) =>
420 new Orchestrator.OrchestratorProjectionError({
421 threadId,
422 cause,
423 }),
424 ),
425 );
426
427 const ensureCommandTranscripts = Effect.fn(
428 "orchestrationV2.threadManagement.ensureCommandTranscripts",
429 )(function* (command: OrchestrationV2ServerCommand) {
430 yield* Effect.forEach(
431 existingThreadIdsForCommand(command),
432 (threadId) => ensureLegacyTranscript(threadId),
433 { discard: true },
434 ).pipe(
435 Effect.mapError(
436 (cause) =>
437 new Orchestrator.OrchestratorDispatchError({
438 commandId: command.commandId,
439 commandType: command.type,
440 cause,
441 }),
442 ),
443 );
444 });
445
446 const getThreadProjection: ThreadManagementServiceShape["getThreadProjection"] = (threadId) =>
447 ensureProjectionTranscript(threadId).pipe(
448 Effect.andThen(orchestrator.getThreadProjection(threadId)),
449 );
450
451 const getCheckpointContext: ThreadManagementServiceShape["getCheckpointContext"] = (threadId) =>
452 ensureProjectionTranscript(threadId).pipe(
453 Effect.andThen(orchestrator.getCheckpointContext(threadId)),
454 );
455
456 const getThreadSnapshot: ThreadManagementServiceShape["getThreadSnapshot"] = (threadId) =>
457 ensureProjectionTranscript(threadId).pipe(
458 Effect.andThen(orchestrator.getThreadSnapshot(threadId)),
459 );
460 const getThreadSnapshotWindow: ThreadManagementServiceShape["getThreadSnapshotWindow"] = (
461 threadId,
462 options,
463 ) =>
464 ensureProjectionTranscript(threadId).pipe(
465 Effect.andThen(orchestrator.getThreadSnapshotWindow(threadId, options)),
466 );
467
468 const dispatch: ThreadManagementServiceShape["dispatch"] = (command) =>
469 ensureCommandTranscripts(command).pipe(Effect.andThen(orchestrator.dispatch(command)));
470
471 const getProjectThread: ThreadManagementServiceShape["getProjectThread"] = (input) =>
472 getThreadProjection(input.threadId).pipe(
473 Effect.mapError(
474 (cause) =>
475 new ThreadManagementProjectionLoadError({
476 projectId: input.projectId,
477 threadId: input.threadId,
478 cause,
479 }),
480 ),
481 Effect.flatMap((projection) =>
482 projection.thread.projectId === input.projectId && projection.thread.deletedAt === null
483 ? Effect.succeed(projection)
484 : Effect.fail(
485 new ThreadManagementThreadNotFoundError({
486 projectId: input.projectId,
487 threadId: input.threadId,
488 }),
489 ),
490 ),
491 );
492
493 const getProjectThreadRecords: ThreadManagementServiceShape["getProjectThreadRecords"] = (
494 input,
495 fields,
496 filter,
497 ) =>
498 ensureProjectionTranscript(input.threadId)
499 .pipe(Effect.andThen(orchestrator.getThreadRecords(input.threadId, fields, filter)))
500 .pipe(
501 Effect.mapError(
502 (cause) =>
503 new ThreadManagementProjectionLoadError({
504 projectId: input.projectId,
505 threadId: input.threadId,
506 cause,
507 }),
508 ),
509 Effect.flatMap((projection) =>
510 projection.thread.projectId === input.projectId && projection.thread.deletedAt === null
511 ? Effect.succeed(projection)
512 : Effect.fail(
513 new ThreadManagementThreadNotFoundError({
514 projectId: input.projectId,
515 threadId: input.threadId,
516 }),
517 ),
518 ),
519 );
520
521 const listProjectThreads: ThreadManagementServiceShape["listProjectThreads"] = (input) =>
522 orchestrator.getShellSnapshot().pipe(
523 Effect.mapError(
524 (cause) =>
525 new ThreadManagementProjectThreadsListError({
526 projectId: input.projectId,
527 cause,
528 }),
529 ),
530 Effect.map((snapshot) =>
531 snapshot.threads
532 .filter((thread) => thread.projectId === input.projectId)
533 .filter(
534 (thread) =>
535 input.includeSubagents || thread.lineage.relationshipToParent !== "subagent",
536 )
537 .toSorted(
538 (left, right) =>
539 DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt) ||
540 right.id.localeCompare(left.id),
541 ),
542 ),
543 );
544
545 const sendToThread: ThreadManagementServiceShape["sendToThread"] = (input) =>
546 Effect.gen(function* () {
547 const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
548 if (target.thread.archivedAt !== null) {
549 return yield* new ThreadManagementThreadArchivedError({
550 threadId: input.threadId,
551 });
552 }
553
554 const steerableRun = latestSteerableRun(target);
555 let dispatchMode: Extract<
556 OrchestrationV2Command,
557 { readonly type: "message.dispatch" }
558 >["dispatchMode"];
559 if (input.mode === "steer" || input.mode === "restart") {
560 if (steerableRun === undefined) {
561 return yield* new ThreadManagementNoSteerableRunError({
562 threadId: input.threadId,
563 mode: input.mode,
564 });
565 }
566 dispatchMode = {
567 type: input.mode === "steer" ? "steer_active" : "restart_active",
568 targetRunId: steerableRun.id,
569 };
570 } else if (input.mode === "auto" && steerableRun !== undefined) {
571 dispatchMode = { type: "steer_active", targetRunId: steerableRun.id };
572 } else {
573 dispatchMode = {
574 type: input.mode === "queue" ? "queue_after_active" : "start_immediately",
575 };
576 }
577
578 const dispatch = yield* orchestrator.dispatch({
579 type: "message.dispatch",
580 commandId: input.commandId,
581 threadId: input.threadId,
582 messageId: input.messageId,
583 ...(input.scheduledTaskId === undefined ? {} : { scheduledTaskId: input.scheduledTaskId }),
584 ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
585 text: input.text,
586 attachments: input.attachments,
587 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
588 dispatchMode,
589 createdBy: input.createdBy,
590 creationSource: input.creationSource,
591 });
592 const projection = yield* getProjectThreadRecords(input, ["runs", "messages", "turnItems"], {
593 messageIds: [input.messageId],
594 turnItemTypes: ["user_message"],
595 });
596 const message = projection.messages.find((candidate) => candidate.id === input.messageId);
597 const run =
598 message?.runId === null || message?.runId === undefined
599 ? undefined
600 : projection.runs.find((candidate) => candidate.id === message.runId);
601 const turnItem =
602 projection.turnItems.find(
603 (
604 candidate,
605 ): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> =>
606 candidate.type === "user_message" && candidate.messageId === input.messageId,
607 ) ?? null;
608 // A queued message's user turn item is deliberately not emitted at
609 // dispatch time — it materializes when the queued turn actually starts,
610 // so it can map onto the provider turn. Every other dispatch mode still
611 // produces its turn item transactionally with the run.
612 if (
613 message === undefined ||
614 run === undefined ||
615 (turnItem === null && run.status !== "queued")
616 ) {
617 return yield* new ThreadManagementDurableRunProjectionError({
618 threadId: input.threadId,
619 messageId: input.messageId,
620 });
621 }
622 const delivery: ThreadManagementSendResult["delivery"] =
623 turnItem === null || turnItem.inputIntent === "queued_turn"
624 ? "queued"
625 : turnItem.inputIntent === "turn_start"
626 ? "started"
627 : input.mode === "restart"
628 ? "restarted"
629 : "steered";
630 return { dispatch, projection, message, run, turnItem, delivery };
631 });
632
633 const waitForThread: ThreadManagementServiceShape["waitForThread"] = (input) =>
634 Effect.gen(function* () {
635 const target = yield* getProjectThreadRecords(input, ["runs"]);
636 const selectedRun =
637 input.runId === undefined
638 ? latestRun(target)
639 : target.runs.find((candidate) => candidate.id === input.runId);
640 if (input.runId !== undefined && selectedRun === undefined) {
641 return yield* new ThreadManagementRunNotFoundError({
642 threadId: input.threadId,
643 runId: input.runId,
644 });
645 }
646 if (selectedRun === undefined) {
647 return { threadId: input.threadId, run: null, timedOut: false };
648 }
649 if (isTerminalRunStatus(selectedRun.status)) {
650 return { threadId: input.threadId, run: selectedRun, timedOut: false };
651 }
652
653 const wait = Effect.gen(function* () {
654 while (true) {
655 const current = yield* getProjectThreadRecords(input, ["runs"], {
656 runIds: [selectedRun.id],
657 });
658 const run = current.runs.find((candidate) => candidate.id === selectedRun.id);
659 if (run === undefined) {
660 return yield* new ThreadManagementRunNotFoundError({
661 threadId: input.threadId,
662 runId: selectedRun.id,
663 });
664 }
665 if (isTerminalRunStatus(run.status)) return run;
666 yield* Effect.sleep(Duration.millis(Math.max(1, input.pollIntervalMs ?? 250)));
667 }
668 }).pipe(Effect.timeoutOption(Duration.millis(Math.max(1, input.timeoutMs))));
669 const waited = yield* wait;
670 if (Option.isSome(waited)) {
671 return { threadId: input.threadId, run: waited.value, timedOut: false };
672 }
673 const current = yield* getProjectThreadRecords(input, ["runs"], { runIds: [selectedRun.id] });
674 const run = current.runs.find((candidate) => candidate.id === selectedRun.id);
675 if (run === undefined) {
676 return yield* new ThreadManagementRunNotFoundError({
677 threadId: input.threadId,
678 runId: selectedRun.id,
679 });
680 }
681 // The run may have reached a terminal status while the timeout was
682 // winning the race; the final projection read decides what actually
683 // happened, so only a still-active run counts as timed out.
684 return { threadId: input.threadId, run, timedOut: !isTerminalRunStatus(run.status) };
685 });
686
687 const interruptThread: ThreadManagementServiceShape["interruptThread"] = (input) =>
688 Effect.gen(function* () {
689 const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
690 const explicitRun =
691 input.runId === undefined
692 ? undefined
693 : target.runs.find((candidate) => candidate.id === input.runId);
694 if (input.runId !== undefined && explicitRun === undefined) {
695 return yield* new ThreadManagementRunNotFoundError({
696 threadId: input.threadId,
697 runId: input.runId,
698 });
699 }
700 if (explicitRun !== undefined && isTerminalRunStatus(explicitRun.status)) {
701 return {
702 type: "already_terminal",
703 run: explicitRun as OrchestrationV2Run & {
704 readonly status: ThreadManagementTerminalRunStatus;
705 },
706 } as const;
707 }
708 const interruptibleRun = latestActiveRun(target);
709 if (interruptibleRun === undefined) {
710 if (input.runId === undefined) {
711 return { type: "no_active_run" } as const;
712 }
713 return yield* new ThreadManagementThreadNotInterruptibleError({
714 threadId: input.threadId,
715 runId: input.runId,
716 });
717 }
718 if (input.runId !== undefined && interruptibleRun.id !== input.runId) {
719 return yield* new ThreadManagementThreadNotInterruptibleError({
720 threadId: input.threadId,
721 runId: input.runId,
722 });
723 }
724 const dispatch = yield* orchestrator.dispatch({
725 type: "run.interrupt",
726 commandId: input.commandId,
727 threadId: input.threadId,
728 runId: interruptibleRun.id,
729 ...(input.reason === undefined ? {} : { reason: input.reason }),
730 });
731 return { type: "interrupt_requested", run: interruptibleRun, dispatch } as const;
732 });
733
734 const stopDelegatedTasks: ThreadManagementServiceShape["stopDelegatedTasks"] = (input) =>
735 Effect.gen(function* () {
736 const { subagents } = yield* orchestrator.getThreadRecords(input.threadId, ["subagents"]);
737 const failures: Array<Orchestrator.OrchestratorV2Error> = [];
738 for (const task of subagents) {
739 if (task.origin !== "app_owned" || task.childThreadId === null) continue;
740 const threadId = task.childThreadId;
741 yield* dispatch({
742 type: "thread.stop",
743 commandId: CommandId.make(`${input.commandId}:stop:${threadId}`),
744 threadId,
745 ...(input.reason === undefined ? {} : { reason: input.reason }),
746 }).pipe(
747 Effect.andThen(stopDelegatedTasks({ ...input, threadId })),
748 Effect.catch((error) =>
749 Effect.logWarning("Unable to stop a delegated task", {
750 parentThreadId: input.threadId,
751 threadId,
752 error,
753 }).pipe(Effect.andThen(Effect.sync(() => failures.push(error)))),
754 ),
755 );
756 }
757 if (failures[0] !== undefined) return yield* Effect.fail(failures[0]);
758 });
759
760 return ThreadManagementService.of({
761 ensureLegacyTranscript,
762 dispatch,
763 getTimelinePage: (threadId, options) =>
764 ensureProjectionTranscript(threadId).pipe(
765 Effect.andThen(orchestrator.getTimelinePage(threadId, options)),
766 ),
767 getMessageCount: (threadId) =>
768 ensureProjectionTranscript(threadId).pipe(
769 Effect.andThen(orchestrator.getMessageCount(threadId)),
770 ),
771 getTurnItem: (input) =>
772 ensureProjectionTranscript(input.threadId).pipe(
773 Effect.andThen(orchestrator.getTurnItem(input)),
774 Effect.map((item) => ({ item: item === null ? null : projectTurnItemForDetail(item) })),
775 ),
776 getThreadRecords: (threadId, fields, filter) =>
777 ensureProjectionTranscript(threadId).pipe(
778 Effect.andThen(orchestrator.getThreadRecords(threadId, fields, filter)),
779 ),
780 getThreadProjection,
781 getCheckpointContext,
782 getThreadSnapshot,
783 getThreadSnapshotWindow,
784 getProjectThreadRecords,
785 getProjectThread,
786 getShellSnapshot: orchestrator.getShellSnapshot,
787 getThreadShell: orchestrator.getThreadShell,
788 listProjectThreads,
789 sendToThread,
790 waitForThread,
791 interruptThread,
792 stopDelegatedTasks,
793 getThreadEventSequence: orchestrator.getThreadEventSequence,
794 recoverDelegatedTask: orchestrator.recoverDelegatedTask,
795 delegatedTaskResultPending: orchestrator.delegatedTaskResultPending,
796 streamStoredEvents: orchestrator.streamStoredEvents,
797 streamStoredEventsFrom: orchestrator.streamStoredEventsFrom,
798 streamDomainEvents: orchestrator.streamDomainEvents,
799 });
800});
801
802const legacyV1ThreadImporterNoopLayer = Layer.succeed(
803 LegacyV1ThreadImporter.LegacyV1ThreadImporter,
804 LegacyV1ThreadImporter.LegacyV1ThreadImporter.of({
805 pendingThreadCount: Effect.succeed(0),
806 reconcileShells: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
807 ensureTranscript: () => Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
808 importPendingTranscripts: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
809 }),
810);
811
812export const layer: Layer.Layer<ThreadManagementService, never, Orchestrator.OrchestratorV2> =
813 Layer.effect(ThreadManagementService, make).pipe(Layer.provide(legacyV1ThreadImporterNoopLayer));
814
815export const layerWithLegacyImporter: Layer.Layer<
816 ThreadManagementService,
817 never,
818 LegacyV1ThreadImporter.LegacyV1ThreadImporter | Orchestrator.OrchestratorV2
819> = Layer.effect(ThreadManagementService, make);