Open History to see the last commit
1import type {
2 OrchestrationV2SearchThreadInput,
3 OrchestrationV2SearchThreadResult,
4} from "@t3tools/contracts";
5import type {
6 ProjectionRecordField,
7 ProjectionRecordFilter,
8 ProjectionRecords,
9 ShellSnapshotOptions,
10} from "./ProjectionStore.ts";
11import {
12 type ChatAttachment,
13 CommandId,
14 MessageId,
15 OrchestrationV2StopWorkflowError,
16 type OrchestrationV2StopWorkflowInput,
17 type ModelSelection,
18 type OrchestrationV2Actor,
19 type OrchestrationV2Command,
20 type OrchestrationV2GetTurnItemResult,
21 type OrchestrationV2ServerCommand,
22 type OrchestrationV2ConversationMessage,
23 type OrchestrationV2CreationSource,
24 type OrchestrationV2Run,
25 type OrchestrationV2ThreadShellSnapshot,
26 type OrchestrationV2ThreadProjection,
27 type OrchestrationV2ThreadTranscript,
28 type OrchestrationV2ThreadShell,
29 type OrchestrationV2TurnItem,
30 ProjectId,
31 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
32 ProviderInstanceId,
33 resolveProjectProviderInstanceEnabled,
34 RunId,
35 type ScheduledTaskId,
36 ThreadId,
37 type TurnItemId,
38} from "@t3tools/contracts";
39import { threadTranscriptHeader } from "@t3tools/shared/threadTranscript";
40import * as Context from "effect/Context";
41import * as DateTime from "effect/DateTime";
42import * as Duration from "effect/Duration";
43import * as Effect from "effect/Effect";
44import * as Layer from "effect/Layer";
45import * as Option from "effect/Option";
46import * as Ref from "effect/Ref";
47import * as Schema from "effect/Schema";
48import * as Stream from "effect/Stream";
49
50import * as CommandReceiptStore from "./CommandReceiptStore.ts";
51import * as Orchestrator from "./Orchestrator.ts";
52import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
53import { projectedRowEncodedBytes } from "./threadHistoryPaging.ts";
54import * as ProviderSessionManager from "./ProviderSessionManager.ts";
55import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
56import { DispatchModeLimit, exceededDispatchModeLimit } from "./DispatchModeLimit.ts";
57import { projectTurnItemForDetail } from "./WireProjection.ts";
58import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts";
59import * as ServerSettings from "../serverSettings.ts";
60
61export type ThreadManagementSendMode = "auto" | "queue" | "steer" | "restart";
62
63export interface ThreadManagementProvenance {
64 readonly createdBy: OrchestrationV2Actor;
65 readonly creationSource: OrchestrationV2CreationSource;
66}
67
68export function withCreationProvenance(
69 command: OrchestrationV2Command,
70 provenance: ThreadManagementProvenance,
71): OrchestrationV2Command {
72 switch (command.type) {
73 case "thread.create":
74 case "message.dispatch":
75 case "thread.fork":
76 case "thread.merge_back":
77 case "delegated_task.request":
78 return { ...command, ...provenance };
79 default:
80 return command;
81 }
82}
83
84function existingThreadIdsForCommand(
85 command: OrchestrationV2ServerCommand,
86): ReadonlyArray<ThreadId> {
87 switch (command.type) {
88 case "thread.create":
89 return [];
90 // Read-state commands only rewrite the thread payload's visited/unread
91 // watermark and open stats; they never touch messages, so they do not need the imported
92 // v1 transcript hydrated first. Visits fire on every thread-activity bump
93 // while a thread is open, so keeping them off the import path matters.
94 case "thread.visit":
95 case "thread.mark-unread":
96 return [];
97 case "thread.fork":
98 return [command.sourceThreadId];
99 case "thread.merge_back":
100 return command.sourceThreadId === command.targetThreadId
101 ? [command.sourceThreadId]
102 : [command.sourceThreadId, command.targetThreadId];
103 case "delegated_task.request":
104 case "delegated_task.wake-policy":
105 case "delegated_task.completion-delivery.acknowledge":
106 case "delegated_task.completion-delivery.dispose":
107 return [command.parentThreadId];
108 case "thread.created.record":
109 return command.parentThreadId === command.targetThreadId
110 ? [command.parentThreadId]
111 : [command.parentThreadId, command.targetThreadId];
112 default:
113 return [command.threadId];
114 }
115}
116
117export type ThreadManagementTerminalRunStatus = Extract<
118 OrchestrationV2Run["status"],
119 "completed" | "failed" | "cancelled" | "interrupted" | "rolled_back"
120>;
121
122export interface ThreadManagementSendInput {
123 readonly projectId: ProjectId;
124 readonly commandId: CommandId;
125 readonly threadId: ThreadId;
126 readonly messageId: MessageId;
127 readonly scheduledTaskId?: ScheduledTaskId;
128 readonly senderThreadId?: ThreadId;
129 readonly text: string;
130 readonly attachments: ReadonlyArray<ChatAttachment>;
131 readonly modelSelection?: ModelSelection;
132 readonly mode: ThreadManagementSendMode;
133 readonly createdBy: OrchestrationV2Actor;
134 readonly creationSource: OrchestrationV2CreationSource;
135}
136
137export interface ThreadManagementSendResult {
138 readonly dispatch: Orchestrator.OrchestratorV2DispatchResult;
139 readonly projection: Pick<
140 OrchestrationV2ThreadProjection,
141 "thread" | "runs" | "messages" | "turnItems"
142 >;
143 readonly message: OrchestrationV2ConversationMessage;
144 readonly run: OrchestrationV2Run;
145 readonly turnItem: Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> | null;
146 readonly delivery: "started" | "queued" | "steered" | "restarted";
147}
148
149export interface ThreadManagementWaitInput {
150 readonly projectId: ProjectId;
151 readonly threadId: ThreadId;
152 readonly runId?: RunId;
153 readonly timeoutMs: number;
154}
155
156export interface ThreadManagementWaitResult {
157 readonly threadId: ThreadId;
158 readonly run: OrchestrationV2Run | null;
159 readonly timedOut: boolean;
160}
161
162export interface ThreadManagementInterruptInput {
163 readonly projectId: ProjectId;
164 readonly commandId: CommandId;
165 readonly threadId: ThreadId;
166 readonly runId?: RunId;
167 readonly reason?: string;
168}
169
170export type ThreadManagementInterruptResult =
171 | {
172 readonly type: "interrupt_requested";
173 readonly run: OrchestrationV2Run;
174 readonly dispatch: Orchestrator.OrchestratorV2DispatchResult;
175 }
176 | { readonly type: "no_active_run" }
177 | {
178 readonly type: "already_terminal";
179 readonly run: OrchestrationV2Run & { readonly status: ThreadManagementTerminalRunStatus };
180 };
181
182export class ThreadManagementThreadNotFoundError extends Schema.TaggedError<ThreadManagementThreadNotFoundError>()(
183 "ThreadManagementThreadNotFoundError",
184 {
185 projectId: ProjectId,
186 threadId: ThreadId,
187 },
188) {
189 override get message(): string {
190 return `Thread ${this.threadId} was not found in project ${this.projectId}.`;
191 }
192}
193
194export class ThreadTranscriptTooLargeError extends Schema.TaggedError<ThreadTranscriptTooLargeError>()(
195 "ThreadTranscriptTooLargeError",
196 { threadId: ThreadId },
197) {
198 override get message(): string {
199 return "The thread transcript exceeds the file attachment limit.";
200 }
201}
202
203export class ThreadManagementRunNotFoundError extends Schema.TaggedError<ThreadManagementRunNotFoundError>()(
204 "ThreadManagementRunNotFoundError",
205 {
206 threadId: ThreadId,
207 runId: RunId,
208 },
209) {
210 override get message(): string {
211 return `Run ${this.runId} does not belong to thread ${this.threadId}.`;
212 }
213}
214
215export class ThreadManagementThreadArchivedError extends Schema.TaggedError<ThreadManagementThreadArchivedError>()(
216 "ThreadManagementThreadArchivedError",
217 {
218 threadId: ThreadId,
219 },
220) {
221 override get message(): string {
222 return `Thread ${this.threadId} is archived and cannot receive messages.`;
223 }
224}
225
226export class ThreadManagementNoSteerableRunError extends Schema.TaggedError<ThreadManagementNoSteerableRunError>()(
227 "ThreadManagementNoSteerableRunError",
228 {
229 threadId: ThreadId,
230 mode: Schema.Literals(["steer", "restart"]),
231 },
232) {
233 override get message(): string {
234 return `Thread ${this.threadId} has no running turn that can be ${this.mode === "steer" ? "steered" : "restarted"}.`;
235 }
236}
237
238export class ThreadManagementThreadNotInterruptibleError extends Schema.TaggedError<ThreadManagementThreadNotInterruptibleError>()(
239 "ThreadManagementThreadNotInterruptibleError",
240 {
241 threadId: ThreadId,
242 runId: RunId,
243 },
244) {
245 override get message(): string {
246 return `Run ${this.runId} is not currently interruptible.`;
247 }
248}
249
250export class ThreadManagementProjectionLoadError extends Schema.TaggedError<ThreadManagementProjectionLoadError>()(
251 "ThreadManagementProjectionLoadError",
252 {
253 projectId: ProjectId,
254 threadId: ThreadId,
255 cause: Schema.Defect(),
256 },
257) {
258 override get message(): string {
259 return `Unable to load thread ${this.threadId} in project ${this.projectId}.`;
260 }
261}
262
263export class ThreadManagementProjectThreadsListError extends Schema.TaggedError<ThreadManagementProjectThreadsListError>()(
264 "ThreadManagementProjectThreadsListError",
265 {
266 projectId: ProjectId,
267 cause: Schema.Defect(),
268 },
269) {
270 override get message(): string {
271 return `Unable to list threads in project ${this.projectId}.`;
272 }
273}
274
275export class ThreadManagementDurableRunProjectionError extends Schema.TaggedError<ThreadManagementDurableRunProjectionError>()(
276 "ThreadManagementDurableRunProjectionError",
277 {
278 threadId: ThreadId,
279 messageId: MessageId,
280 },
281) {
282 override get message(): string {
283 return `Message ${this.messageId} was accepted on thread ${this.threadId} without a durable run projection.`;
284 }
285}
286
287export class ThreadManagementProviderInstanceDisabledError extends Schema.TaggedError<ThreadManagementProviderInstanceDisabledError>()(
288 "ThreadManagementProviderInstanceDisabledError",
289 {
290 projectId: ProjectId,
291 instanceId: ProviderInstanceId,
292 },
293) {
294 override get message(): string {
295 return `Provider instance "${this.instanceId}" is disabled for project ${this.projectId}.`;
296 }
297}
298
299export class ThreadManagementBackgroundWaitError extends Schema.TaggedError<ThreadManagementBackgroundWaitError>()(
300 "ThreadManagementBackgroundWaitError",
301 {
302 threadId: ThreadId,
303 reason: Schema.Literals(["unsupported", "unavailable", "failed"]),
304 cause: Schema.optional(Schema.Defect()),
305 },
306) {
307 override get message(): string {
308 switch (this.reason) {
309 case "unsupported":
310 return "This provider cannot mark background work as awaited.";
311 case "unavailable":
312 return "This thread has no live provider session.";
313 case "failed":
314 return "Failed to update the awaited background work.";
315 }
316 }
317}
318
319export const ThreadManagementError = Schema.Union([
320 ThreadManagementThreadNotFoundError,
321 ThreadManagementRunNotFoundError,
322 ThreadManagementThreadArchivedError,
323 ThreadManagementNoSteerableRunError,
324 ThreadManagementThreadNotInterruptibleError,
325 ThreadManagementProjectionLoadError,
326 ThreadManagementProjectThreadsListError,
327 ThreadManagementDurableRunProjectionError,
328 ThreadManagementProviderInstanceDisabledError,
329]);
330export type ThreadManagementError = typeof ThreadManagementError.Type;
331
332type ThreadManagementFailure = ThreadManagementError | Orchestrator.OrchestratorV2Error;
333
334export interface ThreadManagementServiceShape {
335 readonly searchThreadStream: (
336 input: OrchestrationV2SearchThreadInput,
337 ) => Stream.Stream<OrchestrationV2SearchThreadResult, Orchestrator.OrchestratorV2Error>;
338 readonly searchThread: (
339 input: OrchestrationV2SearchThreadInput,
340 ) => Effect.Effect<OrchestrationV2SearchThreadResult, Orchestrator.OrchestratorV2Error>;
341 readonly ensureLegacyTranscript: (
342 threadId: ThreadId,
343 ) => Effect.Effect<void, LegacyV1ThreadImporter.LegacyV1ThreadImportError>;
344 readonly dispatch: (
345 command: OrchestrationV2ServerCommand,
346 ) => Effect.Effect<
347 Orchestrator.OrchestratorV2DispatchResult,
348 Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
349 >;
350 readonly getThreadHistoryPage: Orchestrator.OrchestratorV2["Service"]["getThreadHistoryPage"];
351 readonly getTimelinePage: Orchestrator.OrchestratorV2["Service"]["getTimelinePage"];
352 readonly getMessageCount: Orchestrator.OrchestratorV2["Service"]["getMessageCount"];
353 readonly getTurnItem: (input: {
354 readonly threadId: ThreadId;
355 readonly itemId: TurnItemId;
356 }) => Effect.Effect<OrchestrationV2GetTurnItemResult, Orchestrator.OrchestratorV2Error>;
357 readonly getThreadRecords: Orchestrator.OrchestratorV2["Service"]["getThreadRecords"];
358 readonly getThreadProjection: (
359 threadId: ThreadId,
360 ) => Effect.Effect<OrchestrationV2ThreadProjection, Orchestrator.OrchestratorV2Error>;
361 readonly getCheckpointContext: Orchestrator.OrchestratorV2["Service"]["getCheckpointContext"];
362 readonly getThreadSnapshot: Orchestrator.OrchestratorV2["Service"]["getThreadSnapshot"];
363 readonly getThreadTranscript: (
364 threadId: ThreadId,
365 ) => Effect.Effect<
366 OrchestrationV2ThreadTranscript,
367 Orchestrator.OrchestratorV2Error | ThreadTranscriptTooLargeError,
368 ServerEnvironment.ServerEnvironmentIdentity
369 >;
370 readonly getThreadSnapshotWindow: Orchestrator.OrchestratorV2["Service"]["getThreadSnapshotWindow"];
371 readonly getProjectThreadRecords: <K extends ProjectionRecordField>(
372 input: { readonly projectId: ProjectId; readonly threadId: ThreadId },
373 fields: ReadonlyArray<K>,
374 filter?: ProjectionRecordFilter,
375 ) => Effect.Effect<
376 ProjectionRecords<K>,
377 ThreadManagementProjectionLoadError | ThreadManagementThreadNotFoundError
378 >;
379 readonly getProjectThread: (input: {
380 readonly projectId: ProjectId;
381 readonly threadId: ThreadId;
382 }) => Effect.Effect<OrchestrationV2ThreadProjection, ThreadManagementError>;
383 readonly getShellSnapshot: (options?: {
384 readonly location?: "active" | "archive";
385 }) => Effect.Effect<OrchestrationV2ThreadShellSnapshot, Orchestrator.OrchestratorV2Error>;
386 readonly listActiveSubagentThreadIds: Orchestrator.OrchestratorV2["Service"]["listActiveSubagentThreadIds"];
387 readonly listOlderSettledThreads: Orchestrator.OrchestratorV2["Service"]["listOlderSettledThreads"];
388 readonly readShellSnapshot: (
389 options?: Pick<ShellSnapshotOptions, "location" | "familyOf" | "worktreePath" | "threadIds">,
390 ) => Effect.Effect<
391 Effect.Effect<OrchestrationV2ThreadShellSnapshot, Orchestrator.OrchestratorV2Error>,
392 Orchestrator.OrchestratorV2Error
393 >;
394 readonly getThreadShell: Orchestrator.OrchestratorV2["Service"]["getThreadShell"];
395 readonly listProjectThreads: (input: {
396 readonly projectId: ProjectId;
397 readonly includeSubagents: boolean;
398 }) => Effect.Effect<ReadonlyArray<OrchestrationV2ThreadShell>, ThreadManagementError>;
399 readonly sendToThread: (
400 input: ThreadManagementSendInput,
401 ) => Effect.Effect<ThreadManagementSendResult, ThreadManagementFailure>;
402 readonly assertProviderInstanceEnabled: (input: {
403 readonly projectId: ProjectId;
404 readonly commandId: CommandId;
405 readonly instanceId: ProviderInstanceId;
406 }) => Effect.Effect<void, ThreadManagementProviderInstanceDisabledError>;
407 readonly isProviderInstanceEnabledForProject: (input: {
408 readonly projectId: ProjectId;
409 readonly instanceId: ProviderInstanceId;
410 }) => Effect.Effect<boolean>;
411 /** Receipt replays start no work; skip enablement checks with the same command id so settings cannot reject accepted retries. */
412 readonly hasReceipt: (commandId: CommandId) => Effect.Effect<boolean>;
413 readonly waitForThread: (
414 input: ThreadManagementWaitInput,
415 ) => Effect.Effect<ThreadManagementWaitResult, ThreadManagementError>;
416 /** Waits for the agent's run to end before settling its thread and stopping the session.
417 * Other endings or settle refusals leave the thread active. */
418 readonly settleAfterRun: (input: {
419 readonly projectId: ProjectId;
420 readonly threadId: ThreadId;
421 readonly runId: RunId;
422 }) => Effect.Effect<void, ThreadManagementFailure>;
423 readonly settleThread: (input: {
424 readonly threadId: ThreadId;
425 readonly commandId: CommandId;
426 readonly byOwnAgent: boolean;
427 }) => Effect.Effect<
428 { readonly sequence: number } | { readonly settlesWhenTurnEnds: true },
429 Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
430 >;
431 readonly interruptThread: (
432 input: ThreadManagementInterruptInput,
433 ) => Effect.Effect<ThreadManagementInterruptResult, ThreadManagementFailure>;
434 readonly stopWorkflow: (
435 input: OrchestrationV2StopWorkflowInput,
436 ) => Effect.Effect<void, OrchestrationV2StopWorkflowError>;
437 readonly awaitBackgroundTasks: (input: {
438 readonly threadId: ThreadId;
439 readonly taskIds: ReadonlyArray<string>;
440 readonly awaited: boolean;
441 }) => Effect.Effect<
442 { readonly matched: ReadonlyArray<string>; readonly unmatched: ReadonlyArray<string> },
443 ThreadManagementBackgroundWaitError
444 >;
445 readonly stopDelegatedTasks: (input: {
446 readonly threadId: ThreadId;
447 readonly commandId: CommandId;
448 readonly reason?: string | undefined;
449 }) => Effect.Effect<
450 void,
451 Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
452 >;
453 readonly getThreadEventSequence: Orchestrator.OrchestratorV2["Service"]["getThreadEventSequence"];
454 readonly recoverDelegatedTask: Orchestrator.OrchestratorV2["Service"]["recoverDelegatedTask"];
455 readonly delegatedTaskResultPending: Orchestrator.OrchestratorV2["Service"]["delegatedTaskResultPending"];
456 readonly streamStoredEvents: Orchestrator.OrchestratorV2["Service"]["streamStoredEvents"];
457 readonly streamStoredEventsFrom: Orchestrator.OrchestratorV2["Service"]["streamStoredEventsFrom"];
458 readonly streamDomainEvents: Orchestrator.OrchestratorV2["Service"]["streamDomainEvents"];
459}
460
461export class ThreadManagementService extends Context.Service<
462 ThreadManagementService,
463 ThreadManagementServiceShape
464>()("t3/orchestration-v2/ThreadManagementService") {}
465
466export function isActiveRun(run: OrchestrationV2Run): boolean {
467 return (
468 run.status === "preparing" ||
469 run.status === "starting" ||
470 run.status === "running" ||
471 run.status === "waiting"
472 );
473}
474
475export function isTerminalRunStatus(
476 status: OrchestrationV2Run["status"],
477): status is ThreadManagementTerminalRunStatus {
478 return (
479 status === "completed" ||
480 status === "failed" ||
481 status === "cancelled" ||
482 status === "interrupted" ||
483 status === "rolled_back"
484 );
485}
486
487export function latestRun(
488 projection: Pick<OrchestrationV2ThreadProjection, "runs">,
489): OrchestrationV2Run | undefined {
490 return projection.runs.toSorted((left, right) => right.ordinal - left.ordinal)[0];
491}
492
493function latestRestartContinuation(
494 runs: ReadonlyArray<OrchestrationV2Run>,
495 run: OrchestrationV2Run,
496): OrchestrationV2Run {
497 let current = run;
498 for (let hops = 0; hops < runs.length; hops++) {
499 const next = runs.find((candidate) => candidate.restartContinuationOfRunId === current.id);
500 if (next === undefined) break;
501 current = next;
502 }
503 return current;
504}
505
506export function latestActiveRun(
507 projection: Pick<OrchestrationV2ThreadProjection, "runs">,
508): OrchestrationV2Run | undefined {
509 return projection.runs
510 .filter(isActiveRun)
511 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
512}
513
514function latestSteerableRun(
515 projection: Pick<OrchestrationV2ThreadProjection, "runs" | "providerTurns">,
516): OrchestrationV2Run | undefined {
517 return projection.runs
518 .filter(
519 (run) =>
520 run.status === "running" &&
521 run.activeAttemptId !== null &&
522 projection.providerTurns.some(
523 (turn) => turn.runAttemptId === run.activeAttemptId && turn.status === "running",
524 ),
525 )
526 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
527}
528
529const SETTLE_AFTER_RUN_WAIT_MS = 24 * 60 * 60 * 1_000;
530
531const make = Effect.gen(function* () {
532 const threadDispatch = yield* ThreadCommandExecutor.ThreadCommandExecutor;
533 const orchestrator = yield* Orchestrator.OrchestratorV2;
534 const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
535 const layerScope = yield* Effect.scope;
536 const legacyImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
537 const serverSettings = yield* ServerSettings.ServerSettingsService;
538 const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
539
540 const assertProviderInstanceEnabled: ThreadManagementServiceShape["assertProviderInstanceEnabled"] =
541 (input) =>
542 receipts.getByCommandId(input.commandId).pipe(
543 Effect.orElseSucceed(() => Option.none()),
544 Effect.flatMap((receipt) =>
545 Option.isSome(receipt)
546 ? Effect.void
547 : serverSettings.getSettings.pipe(
548 Effect.orDie,
549 Effect.flatMap((current) =>
550 resolveProjectProviderInstanceEnabled(current, input.projectId, input.instanceId)
551 ? Effect.void
552 : new ThreadManagementProviderInstanceDisabledError({
553 projectId: input.projectId,
554 instanceId: input.instanceId,
555 }),
556 ),
557 ),
558 ),
559 );
560
561 const isProviderInstanceEnabledForProject: ThreadManagementServiceShape["isProviderInstanceEnabledForProject"] =
562 (input) =>
563 serverSettings.getSettings.pipe(
564 Effect.orDie,
565 Effect.map((current) =>
566 resolveProjectProviderInstanceEnabled(current, input.projectId, input.instanceId),
567 ),
568 );
569
570 const hasReceipt: ThreadManagementServiceShape["hasReceipt"] = (commandId) =>
571 receipts.getByCommandId(commandId).pipe(
572 Effect.orElseSucceed(() => Option.none()),
573 Effect.map(Option.isSome),
574 );
575
576 const ensureLegacyTranscript = Effect.fn(
577 "orchestrationV2.threadManagement.ensureLegacyTranscript",
578 )(function* (threadId: ThreadId) {
579 yield* legacyImporter.ensureTranscript(threadId).pipe(
580 Effect.tapError((cause) =>
581 Effect.logWarning("Unable to hydrate migrated v1 thread transcript", {
582 threadId,
583 cause,
584 }),
585 ),
586 );
587 });
588
589 const ensureProjectionTranscript = (threadId: ThreadId) =>
590 ensureLegacyTranscript(threadId).pipe(
591 Effect.mapError(
592 (cause) =>
593 new Orchestrator.OrchestratorProjectionError({
594 threadId,
595 cause,
596 }),
597 ),
598 );
599
600 const ensureCommandTranscripts = Effect.fn(
601 "orchestrationV2.threadManagement.ensureCommandTranscripts",
602 )(function* (command: OrchestrationV2ServerCommand) {
603 yield* Effect.forEach(
604 existingThreadIdsForCommand(command),
605 (threadId) => ensureLegacyTranscript(threadId),
606 { discard: true },
607 ).pipe(
608 Effect.mapError(
609 (cause) =>
610 new Orchestrator.OrchestratorDispatchError({
611 commandId: command.commandId,
612 commandType: command.type,
613 cause,
614 }),
615 ),
616 );
617 });
618
619 const getThreadProjection: ThreadManagementServiceShape["getThreadProjection"] = (threadId) =>
620 ensureProjectionTranscript(threadId).pipe(
621 Effect.andThen(orchestrator.getThreadProjection(threadId)),
622 );
623
624 const getCheckpointContext: ThreadManagementServiceShape["getCheckpointContext"] = (threadId) =>
625 ensureProjectionTranscript(threadId).pipe(
626 Effect.andThen(orchestrator.getCheckpointContext(threadId)),
627 );
628
629 const getThreadSnapshot: ThreadManagementServiceShape["getThreadSnapshot"] = (threadId) =>
630 ensureProjectionTranscript(threadId).pipe(
631 Effect.andThen(orchestrator.getThreadSnapshot(threadId)),
632 );
633 const getThreadTranscript = Effect.fn("orchestrationV2.threadManagement.getThreadTranscript")(
634 function* (threadId: ThreadId) {
635 const { projection } = yield* getThreadSnapshot(threadId);
636 const environment = yield* ServerEnvironment.ServerEnvironmentIdentity;
637 const transcript = {
638 threadId: projection.thread.id,
639 title: projection.thread.title,
640 updatedAt: projection.updatedAt,
641 items: projection.visibleTurnItems,
642 };
643 let sizeBytes = Buffer.byteLength(
644 threadTranscriptHeader(yield* environment.getEnvironmentId, transcript),
645 "utf8",
646 );
647 if (sizeBytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) {
648 return yield* new ThreadTranscriptTooLargeError({ threadId });
649 }
650 for (const row of transcript.items) {
651 sizeBytes += projectedRowEncodedBytes(row) + 1;
652 if (sizeBytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) {
653 return yield* new ThreadTranscriptTooLargeError({ threadId });
654 }
655 }
656 return transcript;
657 },
658 );
659 const getThreadSnapshotWindow: ThreadManagementServiceShape["getThreadSnapshotWindow"] = (
660 threadId,
661 options,
662 ) =>
663 ensureProjectionTranscript(threadId).pipe(
664 Effect.andThen(orchestrator.getThreadSnapshotWindow(threadId, options)),
665 );
666
667 const assertDispatchTargetEnabled = (command: OrchestrationV2ServerCommand) => {
668 switch (command.type) {
669 case "message.dispatch":
670 return orchestrator.getThreadRecords(command.threadId, []).pipe(
671 Effect.flatMap((projection) =>
672 assertProviderInstanceEnabled({
673 projectId: projection.thread.projectId,
674 commandId: command.commandId,
675 instanceId: (command.modelSelection ?? projection.thread.modelSelection).instanceId,
676 }),
677 ),
678 );
679 case "delegated_task.request":
680 return orchestrator.getThreadRecords(command.parentThreadId, []).pipe(
681 Effect.flatMap((parent) =>
682 assertProviderInstanceEnabled({
683 projectId: parent.thread.projectId,
684 commandId: command.commandId,
685 instanceId: command.modelSelection.instanceId,
686 }),
687 ),
688 );
689 default:
690 return Effect.void;
691 }
692 };
693
694 const dispatch: ThreadManagementServiceShape["dispatch"] = (command) =>
695 ensureCommandTranscripts(command).pipe(
696 Effect.andThen(assertDispatchTargetEnabled(command)),
697 Effect.andThen(orchestrator.dispatch(command)),
698 );
699
700 const getProjectThread: ThreadManagementServiceShape["getProjectThread"] = (input) =>
701 getThreadProjection(input.threadId).pipe(
702 Effect.mapError(
703 (cause) =>
704 new ThreadManagementProjectionLoadError({
705 projectId: input.projectId,
706 threadId: input.threadId,
707 cause,
708 }),
709 ),
710 Effect.flatMap((projection) =>
711 projection.thread.projectId === input.projectId && projection.thread.deletedAt === null
712 ? Effect.succeed(projection)
713 : Effect.fail(
714 new ThreadManagementThreadNotFoundError({
715 projectId: input.projectId,
716 threadId: input.threadId,
717 }),
718 ),
719 ),
720 );
721
722 const getProjectThreadRecords: ThreadManagementServiceShape["getProjectThreadRecords"] = (
723 input,
724 fields,
725 filter,
726 ) =>
727 ensureProjectionTranscript(input.threadId).pipe(
728 Effect.andThen(orchestrator.getThreadRecords(input.threadId, fields, filter)),
729 Effect.mapError(
730 (cause) =>
731 new ThreadManagementProjectionLoadError({
732 projectId: input.projectId,
733 threadId: input.threadId,
734 cause,
735 }),
736 ),
737 Effect.flatMap((projection) =>
738 projection.thread.projectId === input.projectId && projection.thread.deletedAt === null
739 ? Effect.succeed(projection)
740 : Effect.fail(
741 new ThreadManagementThreadNotFoundError({
742 projectId: input.projectId,
743 threadId: input.threadId,
744 }),
745 ),
746 ),
747 );
748
749 const listProjectThreads: ThreadManagementServiceShape["listProjectThreads"] = (input) =>
750 orchestrator.getShellSnapshot({ projectId: input.projectId, location: "active" }).pipe(
751 Effect.mapError(
752 (cause) =>
753 new ThreadManagementProjectThreadsListError({
754 projectId: input.projectId,
755 cause,
756 }),
757 ),
758 Effect.map((snapshot) =>
759 snapshot.threads
760 .filter(
761 (thread) =>
762 input.includeSubagents || thread.lineage.relationshipToParent !== "subagent",
763 )
764 .toSorted(
765 (left, right) =>
766 DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt) ||
767 right.id.localeCompare(left.id),
768 ),
769 ),
770 );
771
772 const sendToThread: ThreadManagementServiceShape["sendToThread"] = Effect.fn(
773 "ThreadManagementService.sendToThread",
774 )(function* (input) {
775 const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
776 if (target.thread.archivedAt !== null) {
777 return yield* new ThreadManagementThreadArchivedError({
778 threadId: input.threadId,
779 });
780 }
781 const steerableRun = latestSteerableRun(target);
782 let dispatchMode: Extract<
783 OrchestrationV2Command,
784 { readonly type: "message.dispatch" }
785 >["dispatchMode"];
786 if (input.mode === "steer" || input.mode === "restart") {
787 if (steerableRun === undefined) {
788 return yield* new ThreadManagementNoSteerableRunError({
789 threadId: input.threadId,
790 mode: input.mode,
791 });
792 }
793 dispatchMode = {
794 type: input.mode === "steer" ? "steer_active" : "restart_active",
795 targetRunId: steerableRun.id,
796 };
797 } else if (input.mode === "auto" && steerableRun !== undefined) {
798 dispatchMode = { type: "steer_active", targetRunId: steerableRun.id };
799 } else {
800 dispatchMode = {
801 type: input.mode === "queue" ? "queue_after_active" : "start_immediately",
802 };
803 }
804
805 const dispatched = yield* dispatch({
806 type: "message.dispatch",
807 commandId: input.commandId,
808 threadId: input.threadId,
809 messageId: input.messageId,
810 ...(input.scheduledTaskId === undefined ? {} : { scheduledTaskId: input.scheduledTaskId }),
811 ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
812 text: input.text,
813 attachments: input.attachments,
814 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
815 dispatchMode,
816 createdBy: input.createdBy,
817 creationSource: input.creationSource,
818 });
819 const projection = yield* getProjectThreadRecords(input, ["runs", "messages", "turnItems"], {
820 messageIds: [input.messageId],
821 turnItemTypes: ["user_message"],
822 });
823 const message = projection.messages.find((candidate) => candidate.id === input.messageId);
824 const run =
825 message?.runId === null || message?.runId === undefined
826 ? undefined
827 : projection.runs.find((candidate) => candidate.id === message.runId);
828 const turnItem =
829 projection.turnItems.find(
830 (
831 candidate,
832 ): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> =>
833 candidate.type === "user_message" && candidate.messageId === input.messageId,
834 ) ?? null;
835 if (
836 message === undefined ||
837 run === undefined ||
838 (turnItem === null && run.status !== "queued")
839 ) {
840 return yield* new ThreadManagementDurableRunProjectionError({
841 threadId: input.threadId,
842 messageId: input.messageId,
843 });
844 }
845 const delivery: ThreadManagementSendResult["delivery"] =
846 turnItem === null || turnItem.inputIntent === "queued_turn"
847 ? "queued"
848 : turnItem.inputIntent === "turn_start"
849 ? "started"
850 : input.mode === "restart"
851 ? "restarted"
852 : "steered";
853 return { dispatch: dispatched, projection, message, run, turnItem, delivery };
854 });
855
856 const waitForThread: ThreadManagementServiceShape["waitForThread"] = Effect.fn(
857 "ThreadManagementService.waitForThread",
858 )(function* (input) {
859 const loadError = (cause: unknown) =>
860 new ThreadManagementProjectionLoadError({
861 projectId: input.projectId,
862 threadId: input.threadId,
863 cause,
864 });
865 // Taken before the first read, so a run update between that read and
866 // the subscription below still replays.
867 const afterSequence = yield* orchestrator
868 .getThreadEventSequence(input.threadId)
869 .pipe(Effect.mapError(loadError));
870 const target = yield* getProjectThreadRecords(input, ["runs"]);
871 const selectedRun =
872 input.runId === undefined
873 ? latestRun(target)
874 : target.runs.find((candidate) => candidate.id === input.runId);
875 if (input.runId !== undefined && selectedRun === undefined) {
876 return yield* new ThreadManagementRunNotFoundError({
877 threadId: input.threadId,
878 runId: input.runId,
879 });
880 }
881 if (selectedRun === undefined) {
882 return { threadId: input.threadId, run: null, timedOut: false };
883 }
884 // A restart cuts a run and continues it as a new run. Follow that chain,
885 // so a cut run is not the answer while its continuation is pending.
886 // Runs per matching event and is already covered by the waitForThread span.
887 const outcome = Effect.fnUntraced(function* (runs: ReadonlyArray<OrchestrationV2Run>) {
888 const current = runs.find((candidate) => candidate.id === selectedRun.id);
889 if (current === undefined) {
890 return yield* new ThreadManagementRunNotFoundError({
891 threadId: input.threadId,
892 runId: selectedRun.id,
893 });
894 }
895 const run = latestRestartContinuation(runs, current);
896 const pending =
897 isTerminalRunStatus(run.status) && (yield* orchestrator.restartContinuationPending(run));
898 return { run, pending, settled: isTerminalRunStatus(run.status) && !pending };
899 });
900 const initial = yield* outcome(target.runs);
901 if (initial.settled) {
902 return { threadId: input.threadId, run: initial.run, timedOut: false };
903 }
904
905 // A declined continuation records no event, so its effect settling wakes
906 // the wait too.
907 const wait = Stream.merge(
908 Stream.merge(
909 orchestrator.streamStoredEventsFrom({
910 threadId: input.threadId,
911 afterSequence,
912 eventType: "run.updated",
913 }),
914 orchestrator.streamStoredEventsFrom({
915 threadId: input.threadId,
916 afterSequence,
917 eventType: "thread.deleted",
918 }),
919 ).pipe(
920 Stream.mapError(loadError),
921 Stream.filter(
922 (stored) =>
923 stored.event.type !== "run.updated" ||
924 stored.event.payload.id === selectedRun.id ||
925 stored.event.payload.restartContinuationOfRunId !== undefined,
926 ),
927 ),
928 initial.pending
929 ? Stream.fromEffect(orchestrator.awaitRestartContinuation(initial.run))
930 : Stream.empty,
931 ).pipe(
932 Stream.mapEffect(() =>
933 getProjectThreadRecords(input, ["runs"]).pipe(
934 Effect.flatMap((current) => outcome(current.runs)),
935 ),
936 ),
937 Stream.filter((current) => current.settled),
938 Stream.runHead,
939 Effect.timeoutOption(Duration.millis(Math.max(1, input.timeoutMs))),
940 );
941 const waited = Option.flatten(yield* wait);
942 if (Option.isSome(waited)) {
943 return { threadId: input.threadId, run: waited.value.run, timedOut: false };
944 }
945 // The run may have reached a terminal status while the timeout was
946 // winning the race; the final projection read decides what actually
947 // happened, so only a still-active run counts as timed out.
948 const final = yield* outcome((yield* getProjectThreadRecords(input, ["runs"])).runs);
949 return { threadId: input.threadId, run: final.run, timedOut: !final.settled };
950 });
951
952 const settleAfterRun: ThreadManagementServiceShape["settleAfterRun"] = Effect.fn(
953 "orchestrationV2.threadManagement.settleAfterRun",
954 )(function* (input) {
955 const { run } = yield* waitForThread({ ...input, timeoutMs: SETTLE_AFTER_RUN_WAIT_MS });
956 if (run?.status !== "completed") return;
957 yield* dispatch({
958 type: "thread.settle",
959 commandId: CommandId.make(`server:settle-after-run:${input.runId}`),
960 threadId: input.threadId,
961 });
962 });
963
964 const settleThread: ThreadManagementServiceShape["settleThread"] = Effect.fn(
965 "orchestrationV2.threadManagement.settleThread",
966 )(function* (input) {
967 const shell = input.byOwnAgent ? yield* orchestrator.getThreadShell(input.threadId) : null;
968 if (shell != null && shell.activeRunId !== null) {
969 yield* settleAfterRun({
970 projectId: shell.projectId,
971 threadId: shell.id,
972 runId: shell.activeRunId,
973 }).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(layerScope));
974 return { settlesWhenTurnEnds: true } as const;
975 }
976 const result = yield* dispatch({
977 type: "thread.settle",
978 commandId: input.commandId,
979 threadId: input.threadId,
980 });
981 return { sequence: result.sequence };
982 });
983
984 const interruptThread: ThreadManagementServiceShape["interruptThread"] = Effect.fn(
985 "ThreadManagementService.interruptThread",
986 )(function* (input) {
987 const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
988 const explicitRun =
989 input.runId === undefined
990 ? undefined
991 : target.runs.find((candidate) => candidate.id === input.runId);
992 if (input.runId !== undefined && explicitRun === undefined) {
993 return yield* new ThreadManagementRunNotFoundError({
994 threadId: input.threadId,
995 runId: input.runId,
996 });
997 }
998 if (explicitRun !== undefined && isTerminalRunStatus(explicitRun.status)) {
999 return {
1000 type: "already_terminal",
1001 run: explicitRun as OrchestrationV2Run & {
1002 readonly status: ThreadManagementTerminalRunStatus;
1003 },
1004 } as const;
1005 }
1006 const interruptibleRun = latestActiveRun(target);
1007 if (interruptibleRun === undefined) {
1008 if (input.runId === undefined) {
1009 return { type: "no_active_run" } as const;
1010 }
1011 return yield* new ThreadManagementThreadNotInterruptibleError({
1012 threadId: input.threadId,
1013 runId: input.runId,
1014 });
1015 }
1016 if (input.runId !== undefined && interruptibleRun.id !== input.runId) {
1017 return yield* new ThreadManagementThreadNotInterruptibleError({
1018 threadId: input.threadId,
1019 runId: input.runId,
1020 });
1021 }
1022 const dispatch = yield* orchestrator.dispatch({
1023 type: "run.interrupt",
1024 commandId: input.commandId,
1025 threadId: input.threadId,
1026 runId: interruptibleRun.id,
1027 ...(input.reason === undefined ? {} : { reason: input.reason }),
1028 });
1029 return { type: "interrupt_requested", run: interruptibleRun, dispatch } as const;
1030 });
1031
1032 const stopWorkflow: ThreadManagementServiceShape["stopWorkflow"] = Effect.fn(
1033 "ThreadManagementService.stopWorkflow",
1034 )(
1035 function* (input) {
1036 const records = yield* orchestrator
1037 .getThreadRecords(input.threadId, ["subagents", "runs", "providerThreads"])
1038 .pipe(
1039 Effect.mapError(
1040 (cause) =>
1041 new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable", cause }),
1042 ),
1043 );
1044 if (records.thread.deletedAt !== null) {
1045 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable" });
1046 }
1047 // Check mode limits under the lock so users cannot raise modes between validation and Stop.
1048 const limit = yield* DispatchModeLimit;
1049 const exceeded =
1050 limit === undefined ? undefined : exceededDispatchModeLimit(limit, records.thread);
1051 if (limit !== undefined && exceeded !== undefined) {
1052 if (limit.refused !== undefined) {
1053 yield* Ref.set(limit.refused, {
1054 threadId: input.threadId,
1055 runtimeMode: records.thread.runtimeMode,
1056 interactionMode: records.thread.interactionMode,
1057 mode: exceeded,
1058 });
1059 }
1060 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable" });
1061 }
1062 const task = records.subagents.find((candidate) => candidate.id === input.subagentId);
1063 if (
1064 task === undefined ||
1065 task.threadId !== input.threadId ||
1066 task.workflow === undefined ||
1067 task.status !== "running"
1068 ) {
1069 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "not-running" });
1070 }
1071 if (task.origin !== "provider_native" || task.driver !== "claudeAgent") {
1072 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unsupported" });
1073 }
1074 const providerThreadId =
1075 task.providerThreadId ??
1076 records.runs.find((run) => run.id === task.runId)?.providerThreadId;
1077 const providerThread = records.providerThreads.find(
1078 (candidate) =>
1079 candidate.id === providerThreadId &&
1080 candidate.appThreadId === input.threadId &&
1081 candidate.providerInstanceId === task.providerInstanceId &&
1082 candidate.driver === task.driver,
1083 );
1084 const taskId = task.nativeTaskRef?.nativeId;
1085 if (providerThread?.providerSessionId == null || taskId == null || taskId.length === 0) {
1086 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable" });
1087 }
1088 const runtime = yield* sessions
1089 .get(providerThread.providerSessionId)
1090 .pipe(
1091 Effect.mapError(
1092 (cause) =>
1093 new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable", cause }),
1094 ),
1095 );
1096 if (Option.isNone(runtime)) {
1097 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable" });
1098 }
1099 if (runtime.value.stopTask === undefined) {
1100 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unsupported" });
1101 }
1102 // Bounded so a provider that never answers cannot hold the thread lock.
1103 yield* runtime.value.stopTask({ providerThread, taskId }).pipe(
1104 Effect.timeout("15 seconds"),
1105 Effect.mapError(
1106 (cause) =>
1107 new OrchestrationV2StopWorkflowError({
1108 ...input,
1109 reason: "stop-failed",
1110 cause,
1111 }),
1112 ),
1113 );
1114 },
1115 (effect, input) => effect.pipe((effect) => threadDispatch.withLock(input.threadId, effect)),
1116 );
1117
1118 const awaitBackgroundTasks: ThreadManagementServiceShape["awaitBackgroundTasks"] = Effect.fn(
1119 "ThreadManagementService.awaitBackgroundTasks",
1120 )(function* (input) {
1121 const unavailable = (cause?: unknown) =>
1122 new ThreadManagementBackgroundWaitError({
1123 threadId: input.threadId,
1124 reason: "unavailable",
1125 ...(cause === undefined ? {} : { cause }),
1126 });
1127 const records = yield* orchestrator
1128 .getThreadRecords(input.threadId, ["providerThreads"])
1129 .pipe(Effect.mapError(unavailable));
1130 const providerThread = records.providerThreads.find(
1131 (candidate) =>
1132 candidate.id === records.thread.activeProviderThreadId &&
1133 candidate.appThreadId === input.threadId,
1134 );
1135 if (records.thread.deletedAt !== null || providerThread?.providerSessionId == null) {
1136 return yield* unavailable();
1137 }
1138 const runtime = yield* sessions
1139 .get(providerThread.providerSessionId)
1140 .pipe(Effect.mapError(unavailable));
1141 if (Option.isNone(runtime)) {
1142 return yield* unavailable();
1143 }
1144 if (runtime.value.awaitBackgroundTasks === undefined) {
1145 return yield* new ThreadManagementBackgroundWaitError({
1146 threadId: input.threadId,
1147 reason: "unsupported",
1148 });
1149 }
1150 const { matched } = yield* runtime.value
1151 .awaitBackgroundTasks({ providerThread, taskIds: input.taskIds, awaited: input.awaited })
1152 .pipe(
1153 Effect.timeout("15 seconds"),
1154 Effect.mapError(
1155 (cause) =>
1156 new ThreadManagementBackgroundWaitError({
1157 threadId: input.threadId,
1158 reason: "failed",
1159 cause,
1160 }),
1161 ),
1162 );
1163 const matchedIds = new Set(matched);
1164 return { matched, unmatched: input.taskIds.filter((taskId) => !matchedIds.has(taskId)) };
1165 });
1166
1167 const stopDelegatedTasks: ThreadManagementServiceShape["stopDelegatedTasks"] = Effect.fn(
1168 "ThreadManagementService.stopDelegatedTasks",
1169 )(function* (input) {
1170 const { subagents } = yield* orchestrator.getThreadRecords(input.threadId, ["subagents"]);
1171 const failures: Array<
1172 Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
1173 > = [];
1174 const stoppedChildThreadIds = new Set<ThreadId>();
1175 for (const task of subagents) {
1176 if (task.origin !== "app_owned" || task.childThreadId === null) continue;
1177 const threadId = task.childThreadId;
1178 // Follow-up tasks reuse a child thread; walk its subtree only once.
1179 if (stoppedChildThreadIds.has(threadId)) continue;
1180 stoppedChildThreadIds.add(threadId);
1181 yield* dispatch({
1182 type: "thread.stop",
1183 commandId: CommandId.make(`${input.commandId}:stop:${threadId}`),
1184 threadId,
1185 stopDelegatedTasks: false,
1186 ...(input.reason === undefined ? {} : { reason: input.reason }),
1187 }).pipe(
1188 Effect.andThen(stopDelegatedTasks({ ...input, threadId })),
1189 Effect.catch((error) =>
1190 Effect.logWarning("Unable to stop a delegated task", {
1191 parentThreadId: input.threadId,
1192 threadId,
1193 error,
1194 }).pipe(Effect.andThen(Effect.sync(() => failures.push(error)))),
1195 ),
1196 );
1197 }
1198 if (failures[0] !== undefined) return yield* failures[0];
1199 });
1200
1201 return ThreadManagementService.of({
1202 ensureLegacyTranscript,
1203 searchThreadStream: (input) =>
1204 Stream.unwrap(
1205 ensureProjectionTranscript(input.threadId).pipe(
1206 Effect.as(orchestrator.searchThreadStream(input)),
1207 ),
1208 ),
1209 searchThread: (input) =>
1210 ensureProjectionTranscript(input.threadId).pipe(
1211 Effect.andThen(orchestrator.searchThread(input)),
1212 ),
1213 dispatch,
1214 getThreadHistoryPage: (threadId, cursor, throughEntryId, conversationOnly) =>
1215 ensureProjectionTranscript(threadId).pipe(
1216 Effect.andThen(
1217 orchestrator.getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly),
1218 ),
1219 ),
1220 getTimelinePage: (threadId, options) =>
1221 ensureProjectionTranscript(threadId).pipe(
1222 Effect.andThen(orchestrator.getTimelinePage(threadId, options)),
1223 ),
1224 getMessageCount: (threadId) =>
1225 ensureProjectionTranscript(threadId).pipe(
1226 Effect.andThen(orchestrator.getMessageCount(threadId)),
1227 ),
1228 getTurnItem: (input) =>
1229 ensureProjectionTranscript(input.threadId).pipe(
1230 Effect.andThen(orchestrator.getTurnItem(input)),
1231 Effect.map((item) => ({ item: item === null ? null : projectTurnItemForDetail(item) })),
1232 ),
1233 getThreadRecords: (threadId, fields, filter) =>
1234 ensureProjectionTranscript(threadId).pipe(
1235 Effect.andThen(orchestrator.getThreadRecords(threadId, fields, filter)),
1236 ),
1237 getThreadProjection,
1238 getCheckpointContext,
1239 getThreadSnapshot,
1240 getThreadTranscript,
1241 getThreadSnapshotWindow,
1242 getProjectThreadRecords,
1243 getProjectThread,
1244 getShellSnapshot: orchestrator.getShellSnapshot,
1245 listActiveSubagentThreadIds: orchestrator.listActiveSubagentThreadIds,
1246 listOlderSettledThreads: orchestrator.listOlderSettledThreads,
1247 readShellSnapshot: orchestrator.readShellSnapshot,
1248 getThreadShell: orchestrator.getThreadShell,
1249 listProjectThreads,
1250 sendToThread,
1251 assertProviderInstanceEnabled,
1252 isProviderInstanceEnabledForProject,
1253 hasReceipt,
1254 waitForThread,
1255 settleAfterRun,
1256 settleThread,
1257 interruptThread,
1258 stopDelegatedTasks,
1259 stopWorkflow,
1260 awaitBackgroundTasks,
1261 getThreadEventSequence: orchestrator.getThreadEventSequence,
1262 recoverDelegatedTask: orchestrator.recoverDelegatedTask,
1263 delegatedTaskResultPending: orchestrator.delegatedTaskResultPending,
1264 streamStoredEvents: orchestrator.streamStoredEvents,
1265 streamStoredEventsFrom: orchestrator.streamStoredEventsFrom,
1266 streamDomainEvents: orchestrator.streamDomainEvents,
1267 });
1268});
1269
1270const layerLegacyV1ThreadImporterNoop = Layer.succeed(
1271 LegacyV1ThreadImporter.LegacyV1ThreadImporter,
1272 LegacyV1ThreadImporter.LegacyV1ThreadImporter.of({
1273 pendingThreadCount: Effect.succeed(0),
1274 reconcileShells: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
1275 ensureTranscript: () => Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
1276 importPendingTranscripts: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
1277 }),
1278);
1279
1280export const layer: Layer.Layer<
1281 ThreadManagementService,
1282 never,
1283 | Orchestrator.OrchestratorV2
1284 | ProviderSessionManager.ProviderSessionManagerV2
1285 | ServerSettings.ServerSettingsService
1286 | CommandReceiptStore.CommandReceiptStoreV2
1287> = Layer.effect(ThreadManagementService, make).pipe(
1288 Layer.provide(layerLegacyV1ThreadImporterNoop),
1289 Layer.provide(ThreadCommandExecutor.layer),
1290);
1291
1292export const layerWithLegacyImporter: Layer.Layer<
1293 ThreadManagementService,
1294 never,
1295 | LegacyV1ThreadImporter.LegacyV1ThreadImporter
1296 | Orchestrator.OrchestratorV2
1297 | ProviderSessionManager.ProviderSessionManagerV2
1298 | ServerSettings.ServerSettingsService
1299 | CommandReceiptStore.CommandReceiptStoreV2
1300> = Layer.effect(ThreadManagementService, make).pipe(Layer.provide(ThreadCommandExecutor.layer));