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 readShellSnapshot: (
388 options?: Pick<ShellSnapshotOptions, "location" | "subagentFamilyOf" | "worktreePath">,
389 ) => Effect.Effect<
390 Effect.Effect<OrchestrationV2ThreadShellSnapshot, Orchestrator.OrchestratorV2Error>,
391 Orchestrator.OrchestratorV2Error
392 >;
393 readonly getThreadShell: Orchestrator.OrchestratorV2["Service"]["getThreadShell"];
394 readonly listProjectThreads: (input: {
395 readonly projectId: ProjectId;
396 readonly includeSubagents: boolean;
397 }) => Effect.Effect<ReadonlyArray<OrchestrationV2ThreadShell>, ThreadManagementError>;
398 readonly sendToThread: (
399 input: ThreadManagementSendInput,
400 ) => Effect.Effect<ThreadManagementSendResult, ThreadManagementFailure>;
401 readonly assertProviderInstanceEnabled: (input: {
402 readonly projectId: ProjectId;
403 readonly commandId: CommandId;
404 readonly instanceId: ProviderInstanceId;
405 }) => Effect.Effect<void, ThreadManagementProviderInstanceDisabledError>;
406 readonly isProviderInstanceEnabledForProject: (input: {
407 readonly projectId: ProjectId;
408 readonly instanceId: ProviderInstanceId;
409 }) => Effect.Effect<boolean>;
410 /** Receipt replays start no work; skip enablement checks with the same command id so settings cannot reject accepted retries. */
411 readonly hasReceipt: (commandId: CommandId) => Effect.Effect<boolean>;
412 readonly waitForThread: (
413 input: ThreadManagementWaitInput,
414 ) => Effect.Effect<ThreadManagementWaitResult, ThreadManagementError>;
415 /** Waits for the agent's run to end before settling its thread and stopping the session.
416 * Other endings or settle refusals leave the thread active. */
417 readonly settleAfterRun: (input: {
418 readonly projectId: ProjectId;
419 readonly threadId: ThreadId;
420 readonly runId: RunId;
421 }) => Effect.Effect<void, ThreadManagementFailure>;
422 readonly settleThread: (input: {
423 readonly threadId: ThreadId;
424 readonly commandId: CommandId;
425 readonly byOwnAgent: boolean;
426 }) => Effect.Effect<
427 { readonly sequence: number } | { readonly settlesWhenTurnEnds: true },
428 Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
429 >;
430 readonly interruptThread: (
431 input: ThreadManagementInterruptInput,
432 ) => Effect.Effect<ThreadManagementInterruptResult, ThreadManagementFailure>;
433 readonly stopWorkflow: (
434 input: OrchestrationV2StopWorkflowInput,
435 ) => Effect.Effect<void, OrchestrationV2StopWorkflowError>;
436 readonly awaitBackgroundTasks: (input: {
437 readonly threadId: ThreadId;
438 readonly taskIds: ReadonlyArray<string>;
439 readonly awaited: boolean;
440 }) => Effect.Effect<
441 { readonly matched: ReadonlyArray<string>; readonly unmatched: ReadonlyArray<string> },
442 ThreadManagementBackgroundWaitError
443 >;
444 readonly stopDelegatedTasks: (input: {
445 readonly threadId: ThreadId;
446 readonly commandId: CommandId;
447 readonly reason?: string | undefined;
448 }) => Effect.Effect<
449 void,
450 Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
451 >;
452 readonly getThreadEventSequence: Orchestrator.OrchestratorV2["Service"]["getThreadEventSequence"];
453 readonly recoverDelegatedTask: Orchestrator.OrchestratorV2["Service"]["recoverDelegatedTask"];
454 readonly delegatedTaskResultPending: Orchestrator.OrchestratorV2["Service"]["delegatedTaskResultPending"];
455 readonly streamStoredEvents: Orchestrator.OrchestratorV2["Service"]["streamStoredEvents"];
456 readonly streamStoredEventsFrom: Orchestrator.OrchestratorV2["Service"]["streamStoredEventsFrom"];
457 readonly streamDomainEvents: Orchestrator.OrchestratorV2["Service"]["streamDomainEvents"];
458}
459
460export class ThreadManagementService extends Context.Service<
461 ThreadManagementService,
462 ThreadManagementServiceShape
463>()("t3/orchestration-v2/ThreadManagementService") {}
464
465export function isActiveRun(run: OrchestrationV2Run): boolean {
466 return (
467 run.status === "preparing" ||
468 run.status === "starting" ||
469 run.status === "running" ||
470 run.status === "waiting"
471 );
472}
473
474export function isTerminalRunStatus(
475 status: OrchestrationV2Run["status"],
476): status is ThreadManagementTerminalRunStatus {
477 return (
478 status === "completed" ||
479 status === "failed" ||
480 status === "cancelled" ||
481 status === "interrupted" ||
482 status === "rolled_back"
483 );
484}
485
486export function latestRun(
487 projection: Pick<OrchestrationV2ThreadProjection, "runs">,
488): OrchestrationV2Run | undefined {
489 return projection.runs.toSorted((left, right) => right.ordinal - left.ordinal)[0];
490}
491
492function latestRestartContinuation(
493 runs: ReadonlyArray<OrchestrationV2Run>,
494 run: OrchestrationV2Run,
495): OrchestrationV2Run {
496 let current = run;
497 for (let hops = 0; hops < runs.length; hops++) {
498 const next = runs.find((candidate) => candidate.restartContinuationOfRunId === current.id);
499 if (next === undefined) break;
500 current = next;
501 }
502 return current;
503}
504
505export function latestActiveRun(
506 projection: Pick<OrchestrationV2ThreadProjection, "runs">,
507): OrchestrationV2Run | undefined {
508 return projection.runs
509 .filter(isActiveRun)
510 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
511}
512
513function latestSteerableRun(
514 projection: Pick<OrchestrationV2ThreadProjection, "runs" | "providerTurns">,
515): OrchestrationV2Run | undefined {
516 return projection.runs
517 .filter(
518 (run) =>
519 run.status === "running" &&
520 run.activeAttemptId !== null &&
521 projection.providerTurns.some(
522 (turn) => turn.runAttemptId === run.activeAttemptId && turn.status === "running",
523 ),
524 )
525 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
526}
527
528const SETTLE_AFTER_RUN_WAIT_MS = 24 * 60 * 60 * 1_000;
529
530const make = Effect.gen(function* () {
531 const threadDispatch = yield* ThreadCommandExecutor.ThreadCommandExecutor;
532 const orchestrator = yield* Orchestrator.OrchestratorV2;
533 const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
534 const layerScope = yield* Effect.scope;
535 const legacyImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
536 const serverSettings = yield* ServerSettings.ServerSettingsService;
537 const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
538
539 const assertProviderInstanceEnabled: ThreadManagementServiceShape["assertProviderInstanceEnabled"] =
540 (input) =>
541 receipts.getByCommandId(input.commandId).pipe(
542 Effect.orElseSucceed(() => Option.none()),
543 Effect.flatMap((receipt) =>
544 Option.isSome(receipt)
545 ? Effect.void
546 : serverSettings.getSettings.pipe(
547 Effect.orDie,
548 Effect.flatMap((current) =>
549 resolveProjectProviderInstanceEnabled(current, input.projectId, input.instanceId)
550 ? Effect.void
551 : new ThreadManagementProviderInstanceDisabledError({
552 projectId: input.projectId,
553 instanceId: input.instanceId,
554 }),
555 ),
556 ),
557 ),
558 );
559
560 const isProviderInstanceEnabledForProject: ThreadManagementServiceShape["isProviderInstanceEnabledForProject"] =
561 (input) =>
562 serverSettings.getSettings.pipe(
563 Effect.orDie,
564 Effect.map((current) =>
565 resolveProjectProviderInstanceEnabled(current, input.projectId, input.instanceId),
566 ),
567 );
568
569 const hasReceipt: ThreadManagementServiceShape["hasReceipt"] = (commandId) =>
570 receipts.getByCommandId(commandId).pipe(
571 Effect.orElseSucceed(() => Option.none()),
572 Effect.map(Option.isSome),
573 );
574
575 const ensureLegacyTranscript = Effect.fn(
576 "orchestrationV2.threadManagement.ensureLegacyTranscript",
577 )(function* (threadId: ThreadId) {
578 yield* legacyImporter.ensureTranscript(threadId).pipe(
579 Effect.tapError((cause) =>
580 Effect.logWarning("Unable to hydrate migrated v1 thread transcript", {
581 threadId,
582 cause,
583 }),
584 ),
585 );
586 });
587
588 const ensureProjectionTranscript = (threadId: ThreadId) =>
589 ensureLegacyTranscript(threadId).pipe(
590 Effect.mapError(
591 (cause) =>
592 new Orchestrator.OrchestratorProjectionError({
593 threadId,
594 cause,
595 }),
596 ),
597 );
598
599 const ensureCommandTranscripts = Effect.fn(
600 "orchestrationV2.threadManagement.ensureCommandTranscripts",
601 )(function* (command: OrchestrationV2ServerCommand) {
602 yield* Effect.forEach(
603 existingThreadIdsForCommand(command),
604 (threadId) => ensureLegacyTranscript(threadId),
605 { discard: true },
606 ).pipe(
607 Effect.mapError(
608 (cause) =>
609 new Orchestrator.OrchestratorDispatchError({
610 commandId: command.commandId,
611 commandType: command.type,
612 cause,
613 }),
614 ),
615 );
616 });
617
618 const getThreadProjection: ThreadManagementServiceShape["getThreadProjection"] = (threadId) =>
619 ensureProjectionTranscript(threadId).pipe(
620 Effect.andThen(orchestrator.getThreadProjection(threadId)),
621 );
622
623 const getCheckpointContext: ThreadManagementServiceShape["getCheckpointContext"] = (threadId) =>
624 ensureProjectionTranscript(threadId).pipe(
625 Effect.andThen(orchestrator.getCheckpointContext(threadId)),
626 );
627
628 const getThreadSnapshot: ThreadManagementServiceShape["getThreadSnapshot"] = (threadId) =>
629 ensureProjectionTranscript(threadId).pipe(
630 Effect.andThen(orchestrator.getThreadSnapshot(threadId)),
631 );
632 const getThreadTranscript = Effect.fn("orchestrationV2.threadManagement.getThreadTranscript")(
633 function* (threadId: ThreadId) {
634 const { projection } = yield* getThreadSnapshot(threadId);
635 const environment = yield* ServerEnvironment.ServerEnvironmentIdentity;
636 const transcript = {
637 threadId: projection.thread.id,
638 title: projection.thread.title,
639 updatedAt: projection.updatedAt,
640 items: projection.visibleTurnItems,
641 };
642 let sizeBytes = Buffer.byteLength(
643 threadTranscriptHeader(yield* environment.getEnvironmentId, transcript),
644 "utf8",
645 );
646 if (sizeBytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) {
647 return yield* new ThreadTranscriptTooLargeError({ threadId });
648 }
649 for (const row of transcript.items) {
650 sizeBytes += projectedRowEncodedBytes(row) + 1;
651 if (sizeBytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) {
652 return yield* new ThreadTranscriptTooLargeError({ threadId });
653 }
654 }
655 return transcript;
656 },
657 );
658 const getThreadSnapshotWindow: ThreadManagementServiceShape["getThreadSnapshotWindow"] = (
659 threadId,
660 options,
661 ) =>
662 ensureProjectionTranscript(threadId).pipe(
663 Effect.andThen(orchestrator.getThreadSnapshotWindow(threadId, options)),
664 );
665
666 const assertDispatchTargetEnabled = (command: OrchestrationV2ServerCommand) => {
667 switch (command.type) {
668 case "message.dispatch":
669 return orchestrator.getThreadRecords(command.threadId, []).pipe(
670 Effect.flatMap((projection) =>
671 assertProviderInstanceEnabled({
672 projectId: projection.thread.projectId,
673 commandId: command.commandId,
674 instanceId: (command.modelSelection ?? projection.thread.modelSelection).instanceId,
675 }),
676 ),
677 );
678 case "delegated_task.request":
679 return orchestrator.getThreadRecords(command.parentThreadId, []).pipe(
680 Effect.flatMap((parent) =>
681 assertProviderInstanceEnabled({
682 projectId: parent.thread.projectId,
683 commandId: command.commandId,
684 instanceId: command.modelSelection.instanceId,
685 }),
686 ),
687 );
688 default:
689 return Effect.void;
690 }
691 };
692
693 const dispatch: ThreadManagementServiceShape["dispatch"] = (command) =>
694 ensureCommandTranscripts(command).pipe(
695 Effect.andThen(assertDispatchTargetEnabled(command)),
696 Effect.andThen(orchestrator.dispatch(command)),
697 );
698
699 const getProjectThread: ThreadManagementServiceShape["getProjectThread"] = (input) =>
700 getThreadProjection(input.threadId).pipe(
701 Effect.mapError(
702 (cause) =>
703 new ThreadManagementProjectionLoadError({
704 projectId: input.projectId,
705 threadId: input.threadId,
706 cause,
707 }),
708 ),
709 Effect.flatMap((projection) =>
710 projection.thread.projectId === input.projectId && projection.thread.deletedAt === null
711 ? Effect.succeed(projection)
712 : Effect.fail(
713 new ThreadManagementThreadNotFoundError({
714 projectId: input.projectId,
715 threadId: input.threadId,
716 }),
717 ),
718 ),
719 );
720
721 const getProjectThreadRecords: ThreadManagementServiceShape["getProjectThreadRecords"] = (
722 input,
723 fields,
724 filter,
725 ) =>
726 ensureProjectionTranscript(input.threadId)
727 .pipe(Effect.andThen(orchestrator.getThreadRecords(input.threadId, fields, filter)))
728 .pipe(
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* Effect.fail(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 readShellSnapshot: orchestrator.readShellSnapshot,
1247 getThreadShell: orchestrator.getThreadShell,
1248 listProjectThreads,
1249 sendToThread,
1250 assertProviderInstanceEnabled,
1251 isProviderInstanceEnabledForProject,
1252 hasReceipt,
1253 waitForThread,
1254 settleAfterRun,
1255 settleThread,
1256 interruptThread,
1257 stopDelegatedTasks,
1258 stopWorkflow,
1259 awaitBackgroundTasks,
1260 getThreadEventSequence: orchestrator.getThreadEventSequence,
1261 recoverDelegatedTask: orchestrator.recoverDelegatedTask,
1262 delegatedTaskResultPending: orchestrator.delegatedTaskResultPending,
1263 streamStoredEvents: orchestrator.streamStoredEvents,
1264 streamStoredEventsFrom: orchestrator.streamStoredEventsFrom,
1265 streamDomainEvents: orchestrator.streamDomainEvents,
1266 });
1267});
1268
1269const layerLegacyV1ThreadImporterNoop = Layer.succeed(
1270 LegacyV1ThreadImporter.LegacyV1ThreadImporter,
1271 LegacyV1ThreadImporter.LegacyV1ThreadImporter.of({
1272 pendingThreadCount: Effect.succeed(0),
1273 reconcileShells: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
1274 ensureTranscript: () => Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
1275 importPendingTranscripts: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
1276 }),
1277);
1278
1279export const layer: Layer.Layer<
1280 ThreadManagementService,
1281 never,
1282 | Orchestrator.OrchestratorV2
1283 | ProviderSessionManager.ProviderSessionManagerV2
1284 | ServerSettings.ServerSettingsService
1285 | CommandReceiptStore.CommandReceiptStoreV2
1286> = Layer.effect(ThreadManagementService, make).pipe(
1287 Layer.provide(layerLegacyV1ThreadImporterNoop),
1288 Layer.provide(ThreadCommandExecutor.layer),
1289);
1290
1291export const layerWithLegacyImporter: Layer.Layer<
1292 ThreadManagementService,
1293 never,
1294 | LegacyV1ThreadImporter.LegacyV1ThreadImporter
1295 | Orchestrator.OrchestratorV2
1296 | ProviderSessionManager.ProviderSessionManagerV2
1297 | ServerSettings.ServerSettingsService
1298 | CommandReceiptStore.CommandReceiptStoreV2
1299> = Layer.effect(ThreadManagementService, make).pipe(Layer.provide(ThreadCommandExecutor.layer));