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

ThreadManagementService.ts

1,301 lines48.3 KB

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;
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 }
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 }
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;
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";
148​
149export interface ThreadManagementWaitInput {
150 readonly projectId: ProjectId;
151 readonly threadId: ThreadId;
152 readonly runId?: RunId;
153 readonly timeoutMs: number;
155​
156export interface ThreadManagementWaitResult {
157 readonly threadId: ThreadId;
158 readonly run: OrchestrationV2Run | null;
159 readonly timedOut: boolean;
161​
162export interface ThreadManagementInterruptInput {
163 readonly projectId: ProjectId;
164 readonly commandId: CommandId;
165 readonly threadId: ThreadId;
166 readonly runId?: RunId;
167 readonly reason?: string;
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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"];
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 );
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 );
486​
487export function latestRun(
488 projection: Pick<OrchestrationV2ThreadProjection, "runs">,
489): OrchestrationV2Run | undefined {
490 return projection.runs.toSorted((left, right) => right.ordinal - left.ordinal)[0];
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;
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];
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];
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)
728 .pipe(Effect.andThen(orchestrator.getThreadRecords(input.threadId, fields, filter)))
729 .pipe(
730 Effect.mapError(
731 (cause) =>
732 new ThreadManagementProjectionLoadError({
733 projectId: input.projectId,
734 threadId: input.threadId,
735 cause,
736 }),
737 ),
738 Effect.flatMap((projection) =>
739 projection.thread.projectId === input.projectId && projection.thread.deletedAt === null
740 ? Effect.succeed(projection)
741 : Effect.fail(
742 new ThreadManagementThreadNotFoundError({
743 projectId: input.projectId,
744 threadId: input.threadId,
745 }),
746 ),
747 ),
748 );
749​
750 const listProjectThreads: ThreadManagementServiceShape["listProjectThreads"] = (input) =>
751 orchestrator.getShellSnapshot({ projectId: input.projectId, location: "active" }).pipe(
752 Effect.mapError(
753 (cause) =>
754 new ThreadManagementProjectThreadsListError({
755 projectId: input.projectId,
756 cause,
757 }),
758 ),
759 Effect.map((snapshot) =>
760 snapshot.threads
761 .filter(
762 (thread) =>
763 input.includeSubagents || thread.lineage.relationshipToParent !== "subagent",
764 )
765 .toSorted(
766 (left, right) =>
767 DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt) ||
768 right.id.localeCompare(left.id),
769 ),
770 ),
771 );
772​
773 const sendToThread: ThreadManagementServiceShape["sendToThread"] = Effect.fn(
774 "ThreadManagementService.sendToThread",
775 )(function* (input) {
776 const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
777 if (target.thread.archivedAt !== null) {
778 return yield* new ThreadManagementThreadArchivedError({
779 threadId: input.threadId,
780 });
781 }
782 const steerableRun = latestSteerableRun(target);
783 let dispatchMode: Extract<
784 OrchestrationV2Command,
785 { readonly type: "message.dispatch" }
786 >["dispatchMode"];
787 if (input.mode === "steer" || input.mode === "restart") {
788 if (steerableRun === undefined) {
789 return yield* new ThreadManagementNoSteerableRunError({
790 threadId: input.threadId,
791 mode: input.mode,
792 });
793 }
794 dispatchMode = {
795 type: input.mode === "steer" ? "steer_active" : "restart_active",
796 targetRunId: steerableRun.id,
797 };
798 } else if (input.mode === "auto" && steerableRun !== undefined) {
799 dispatchMode = { type: "steer_active", targetRunId: steerableRun.id };
800 } else {
801 dispatchMode = {
802 type: input.mode === "queue" ? "queue_after_active" : "start_immediately",
803 };
804 }
805​
806 const dispatched = yield* dispatch({
807 type: "message.dispatch",
808 commandId: input.commandId,
809 threadId: input.threadId,
810 messageId: input.messageId,
811 ...(input.scheduledTaskId === undefined ? {} : { scheduledTaskId: input.scheduledTaskId }),
812 ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
813 text: input.text,
814 attachments: input.attachments,
815 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
816 dispatchMode,
817 createdBy: input.createdBy,
818 creationSource: input.creationSource,
819 });
820 const projection = yield* getProjectThreadRecords(input, ["runs", "messages", "turnItems"], {
821 messageIds: [input.messageId],
822 turnItemTypes: ["user_message"],
823 });
824 const message = projection.messages.find((candidate) => candidate.id === input.messageId);
825 const run =
826 message?.runId === null || message?.runId === undefined
827 ? undefined
828 : projection.runs.find((candidate) => candidate.id === message.runId);
829 const turnItem =
830 projection.turnItems.find(
831 (
832 candidate,
833 ): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> =>
834 candidate.type === "user_message" && candidate.messageId === input.messageId,
835 ) ?? null;
836 if (
837 message === undefined ||
838 run === undefined ||
839 (turnItem === null && run.status !== "queued")
840 ) {
841 return yield* new ThreadManagementDurableRunProjectionError({
842 threadId: input.threadId,
843 messageId: input.messageId,
844 });
845 }
846 const delivery: ThreadManagementSendResult["delivery"] =
847 turnItem === null || turnItem.inputIntent === "queued_turn"
848 ? "queued"
849 : turnItem.inputIntent === "turn_start"
850 ? "started"
851 : input.mode === "restart"
852 ? "restarted"
853 : "steered";
854 return { dispatch: dispatched, projection, message, run, turnItem, delivery };
855 });
856​
857 const waitForThread: ThreadManagementServiceShape["waitForThread"] = Effect.fn(
858 "ThreadManagementService.waitForThread",
859 )(function* (input) {
860 const loadError = (cause: unknown) =>
861 new ThreadManagementProjectionLoadError({
862 projectId: input.projectId,
863 threadId: input.threadId,
864 cause,
865 });
866 // Taken before the first read, so a run update between that read and
867 // the subscription below still replays.
868 const afterSequence = yield* orchestrator
869 .getThreadEventSequence(input.threadId)
870 .pipe(Effect.mapError(loadError));
871 const target = yield* getProjectThreadRecords(input, ["runs"]);
872 const selectedRun =
873 input.runId === undefined
874 ? latestRun(target)
875 : target.runs.find((candidate) => candidate.id === input.runId);
876 if (input.runId !== undefined && selectedRun === undefined) {
877 return yield* new ThreadManagementRunNotFoundError({
878 threadId: input.threadId,
879 runId: input.runId,
880 });
881 }
882 if (selectedRun === undefined) {
883 return { threadId: input.threadId, run: null, timedOut: false };
884 }
885 // A restart cuts a run and continues it as a new run. Follow that chain,
886 // so a cut run is not the answer while its continuation is pending.
887 // Runs per matching event and is already covered by the waitForThread span.
888 const outcome = Effect.fnUntraced(function* (runs: ReadonlyArray<OrchestrationV2Run>) {
889 const current = runs.find((candidate) => candidate.id === selectedRun.id);
890 if (current === undefined) {
891 return yield* new ThreadManagementRunNotFoundError({
892 threadId: input.threadId,
893 runId: selectedRun.id,
894 });
895 }
896 const run = latestRestartContinuation(runs, current);
897 const pending =
898 isTerminalRunStatus(run.status) && (yield* orchestrator.restartContinuationPending(run));
899 return { run, pending, settled: isTerminalRunStatus(run.status) && !pending };
900 });
901 const initial = yield* outcome(target.runs);
902 if (initial.settled) {
903 return { threadId: input.threadId, run: initial.run, timedOut: false };
904 }
905​
906 // A declined continuation records no event, so its effect settling wakes
907 // the wait too.
908 const wait = Stream.merge(
909 Stream.merge(
910 orchestrator.streamStoredEventsFrom({
911 threadId: input.threadId,
912 afterSequence,
913 eventType: "run.updated",
914 }),
915 orchestrator.streamStoredEventsFrom({
916 threadId: input.threadId,
917 afterSequence,
918 eventType: "thread.deleted",
919 }),
920 ).pipe(
921 Stream.mapError(loadError),
922 Stream.filter(
923 (stored) =>
924 stored.event.type !== "run.updated" ||
925 stored.event.payload.id === selectedRun.id ||
926 stored.event.payload.restartContinuationOfRunId !== undefined,
927 ),
928 ),
929 initial.pending
930 ? Stream.fromEffect(orchestrator.awaitRestartContinuation(initial.run))
931 : Stream.empty,
932 ).pipe(
933 Stream.mapEffect(() =>
934 getProjectThreadRecords(input, ["runs"]).pipe(
935 Effect.flatMap((current) => outcome(current.runs)),
936 ),
937 ),
938 Stream.filter((current) => current.settled),
939 Stream.runHead,
940 Effect.timeoutOption(Duration.millis(Math.max(1, input.timeoutMs))),
941 );
942 const waited = Option.flatten(yield* wait);
943 if (Option.isSome(waited)) {
944 return { threadId: input.threadId, run: waited.value.run, timedOut: false };
945 }
946 // The run may have reached a terminal status while the timeout was
947 // winning the race; the final projection read decides what actually
948 // happened, so only a still-active run counts as timed out.
949 const final = yield* outcome((yield* getProjectThreadRecords(input, ["runs"])).runs);
950 return { threadId: input.threadId, run: final.run, timedOut: !final.settled };
951 });
952​
953 const settleAfterRun: ThreadManagementServiceShape["settleAfterRun"] = Effect.fn(
954 "orchestrationV2.threadManagement.settleAfterRun",
955 )(function* (input) {
956 const { run } = yield* waitForThread({ ...input, timeoutMs: SETTLE_AFTER_RUN_WAIT_MS });
957 if (run?.status !== "completed") return;
958 yield* dispatch({
959 type: "thread.settle",
960 commandId: CommandId.make(`server:settle-after-run:${input.runId}`),
961 threadId: input.threadId,
962 });
963 });
964​
965 const settleThread: ThreadManagementServiceShape["settleThread"] = Effect.fn(
966 "orchestrationV2.threadManagement.settleThread",
967 )(function* (input) {
968 const shell = input.byOwnAgent ? yield* orchestrator.getThreadShell(input.threadId) : null;
969 if (shell != null && shell.activeRunId !== null) {
970 yield* settleAfterRun({
971 projectId: shell.projectId,
972 threadId: shell.id,
973 runId: shell.activeRunId,
974 }).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(layerScope));
975 return { settlesWhenTurnEnds: true } as const;
976 }
977 const result = yield* dispatch({
978 type: "thread.settle",
979 commandId: input.commandId,
980 threadId: input.threadId,
981 });
982 return { sequence: result.sequence };
983 });
984​
985 const interruptThread: ThreadManagementServiceShape["interruptThread"] = Effect.fn(
986 "ThreadManagementService.interruptThread",
987 )(function* (input) {
988 const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
989 const explicitRun =
990 input.runId === undefined
991 ? undefined
992 : target.runs.find((candidate) => candidate.id === input.runId);
993 if (input.runId !== undefined && explicitRun === undefined) {
994 return yield* new ThreadManagementRunNotFoundError({
995 threadId: input.threadId,
996 runId: input.runId,
997 });
998 }
999 if (explicitRun !== undefined && isTerminalRunStatus(explicitRun.status)) {
1000 return {
1001 type: "already_terminal",
1002 run: explicitRun as OrchestrationV2Run & {
1003 readonly status: ThreadManagementTerminalRunStatus;
1004 },
1005 } as const;
1007 const interruptibleRun = latestActiveRun(target);
1008 if (interruptibleRun === undefined) {
1009 if (input.runId === undefined) {
1010 return { type: "no_active_run" } as const;
1012 return yield* new ThreadManagementThreadNotInterruptibleError({
1013 threadId: input.threadId,
1014 runId: input.runId,
1015 });
1017 if (input.runId !== undefined && interruptibleRun.id !== input.runId) {
1018 return yield* new ThreadManagementThreadNotInterruptibleError({
1019 threadId: input.threadId,
1020 runId: input.runId,
1021 });
1023 const dispatch = yield* orchestrator.dispatch({
1024 type: "run.interrupt",
1025 commandId: input.commandId,
1026 threadId: input.threadId,
1027 runId: interruptibleRun.id,
1028 ...(input.reason === undefined ? {} : { reason: input.reason }),
1029 });
1030 return { type: "interrupt_requested", run: interruptibleRun, dispatch } as const;
1031 });
1032​
1033 const stopWorkflow: ThreadManagementServiceShape["stopWorkflow"] = Effect.fn(
1034 "ThreadManagementService.stopWorkflow",
1035 )(
1036 function* (input) {
1037 const records = yield* orchestrator
1038 .getThreadRecords(input.threadId, ["subagents", "runs", "providerThreads"])
1039 .pipe(
1040 Effect.mapError(
1041 (cause) =>
1042 new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable", cause }),
1043 ),
1044 );
1045 if (records.thread.deletedAt !== null) {
1046 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable" });
1048 // Check mode limits under the lock so users cannot raise modes between validation and Stop.
1049 const limit = yield* DispatchModeLimit;
1050 const exceeded =
1051 limit === undefined ? undefined : exceededDispatchModeLimit(limit, records.thread);
1052 if (limit !== undefined && exceeded !== undefined) {
1053 if (limit.refused !== undefined) {
1054 yield* Ref.set(limit.refused, {
1055 threadId: input.threadId,
1056 runtimeMode: records.thread.runtimeMode,
1057 interactionMode: records.thread.interactionMode,
1058 mode: exceeded,
1059 });
1061 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable" });
1063 const task = records.subagents.find((candidate) => candidate.id === input.subagentId);
1064 if (
1065 task === undefined ||
1066 task.threadId !== input.threadId ||
1067 task.workflow === undefined ||
1068 task.status !== "running"
1069 ) {
1070 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "not-running" });
1072 if (task.origin !== "provider_native" || task.driver !== "claudeAgent") {
1073 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unsupported" });
1075 const providerThreadId =
1076 task.providerThreadId ??
1077 records.runs.find((run) => run.id === task.runId)?.providerThreadId;
1078 const providerThread = records.providerThreads.find(
1079 (candidate) =>
1080 candidate.id === providerThreadId &&
1081 candidate.appThreadId === input.threadId &&
1082 candidate.providerInstanceId === task.providerInstanceId &&
1083 candidate.driver === task.driver,
1084 );
1085 const taskId = task.nativeTaskRef?.nativeId;
1086 if (providerThread?.providerSessionId == null || taskId == null || taskId.length === 0) {
1087 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable" });
1089 const runtime = yield* sessions
1090 .get(providerThread.providerSessionId)
1091 .pipe(
1092 Effect.mapError(
1093 (cause) =>
1094 new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable", cause }),
1095 ),
1096 );
1097 if (Option.isNone(runtime)) {
1098 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable" });
1100 if (runtime.value.stopTask === undefined) {
1101 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unsupported" });
1103 // Bounded so a provider that never answers cannot hold the thread lock.
1104 yield* runtime.value.stopTask({ providerThread, taskId }).pipe(
1105 Effect.timeout("15 seconds"),
1106 Effect.mapError(
1107 (cause) =>
1108 new OrchestrationV2StopWorkflowError({
1109 ...input,
1110 reason: "stop-failed",
1111 cause,
1112 }),
1113 ),
1114 );
1115 },
1116 (effect, input) => effect.pipe((effect) => threadDispatch.withLock(input.threadId, effect)),
1117 );
1118​
1119 const awaitBackgroundTasks: ThreadManagementServiceShape["awaitBackgroundTasks"] = Effect.fn(
1120 "ThreadManagementService.awaitBackgroundTasks",
1121 )(function* (input) {
1122 const unavailable = (cause?: unknown) =>
1123 new ThreadManagementBackgroundWaitError({
1124 threadId: input.threadId,
1125 reason: "unavailable",
1126 ...(cause === undefined ? {} : { cause }),
1127 });
1128 const records = yield* orchestrator
1129 .getThreadRecords(input.threadId, ["providerThreads"])
1130 .pipe(Effect.mapError(unavailable));
1131 const providerThread = records.providerThreads.find(
1132 (candidate) =>
1133 candidate.id === records.thread.activeProviderThreadId &&
1134 candidate.appThreadId === input.threadId,
1135 );
1136 if (records.thread.deletedAt !== null || providerThread?.providerSessionId == null) {
1137 return yield* unavailable();
1139 const runtime = yield* sessions
1140 .get(providerThread.providerSessionId)
1141 .pipe(Effect.mapError(unavailable));
1142 if (Option.isNone(runtime)) {
1143 return yield* unavailable();
1145 if (runtime.value.awaitBackgroundTasks === undefined) {
1146 return yield* new ThreadManagementBackgroundWaitError({
1147 threadId: input.threadId,
1148 reason: "unsupported",
1149 });
1151 const { matched } = yield* runtime.value
1152 .awaitBackgroundTasks({ providerThread, taskIds: input.taskIds, awaited: input.awaited })
1153 .pipe(
1154 Effect.timeout("15 seconds"),
1155 Effect.mapError(
1156 (cause) =>
1157 new ThreadManagementBackgroundWaitError({
1158 threadId: input.threadId,
1159 reason: "failed",
1160 cause,
1161 }),
1162 ),
1163 );
1164 const matchedIds = new Set(matched);
1165 return { matched, unmatched: input.taskIds.filter((taskId) => !matchedIds.has(taskId)) };
1166 });
1167​
1168 const stopDelegatedTasks: ThreadManagementServiceShape["stopDelegatedTasks"] = Effect.fn(
1169 "ThreadManagementService.stopDelegatedTasks",
1170 )(function* (input) {
1171 const { subagents } = yield* orchestrator.getThreadRecords(input.threadId, ["subagents"]);
1172 const failures: Array<
1173 Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
1174 > = [];
1175 const stoppedChildThreadIds = new Set<ThreadId>();
1176 for (const task of subagents) {
1177 if (task.origin !== "app_owned" || task.childThreadId === null) continue;
1178 const threadId = task.childThreadId;
1179 // Follow-up tasks reuse a child thread; walk its subtree only once.
1180 if (stoppedChildThreadIds.has(threadId)) continue;
1181 stoppedChildThreadIds.add(threadId);
1182 yield* dispatch({
1183 type: "thread.stop",
1184 commandId: CommandId.make(`${input.commandId}:stop:${threadId}`),
1185 threadId,
1186 stopDelegatedTasks: false,
1187 ...(input.reason === undefined ? {} : { reason: input.reason }),
1188 }).pipe(
1189 Effect.andThen(stopDelegatedTasks({ ...input, threadId })),
1190 Effect.catch((error) =>
1191 Effect.logWarning("Unable to stop a delegated task", {
1192 parentThreadId: input.threadId,
1193 threadId,
1194 error,
1195 }).pipe(Effect.andThen(Effect.sync(() => failures.push(error)))),
1196 ),
1197 );
1199 if (failures[0] !== undefined) return yield* Effect.fail(failures[0]);
1200 });
1201​
1202 return ThreadManagementService.of({
1203 ensureLegacyTranscript,
1204 searchThreadStream: (input) =>
1205 Stream.unwrap(
1206 ensureProjectionTranscript(input.threadId).pipe(
1207 Effect.as(orchestrator.searchThreadStream(input)),
1208 ),
1209 ),
1210 searchThread: (input) =>
1211 ensureProjectionTranscript(input.threadId).pipe(
1212 Effect.andThen(orchestrator.searchThread(input)),
1213 ),
1214 dispatch,
1215 getThreadHistoryPage: (threadId, cursor, throughEntryId, conversationOnly) =>
1216 ensureProjectionTranscript(threadId).pipe(
1217 Effect.andThen(
1218 orchestrator.getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly),
1219 ),
1220 ),
1221 getTimelinePage: (threadId, options) =>
1222 ensureProjectionTranscript(threadId).pipe(
1223 Effect.andThen(orchestrator.getTimelinePage(threadId, options)),
1224 ),
1225 getMessageCount: (threadId) =>
1226 ensureProjectionTranscript(threadId).pipe(
1227 Effect.andThen(orchestrator.getMessageCount(threadId)),
1228 ),
1229 getTurnItem: (input) =>
1230 ensureProjectionTranscript(input.threadId).pipe(
1231 Effect.andThen(orchestrator.getTurnItem(input)),
1232 Effect.map((item) => ({ item: item === null ? null : projectTurnItemForDetail(item) })),
1233 ),
1234 getThreadRecords: (threadId, fields, filter) =>
1235 ensureProjectionTranscript(threadId).pipe(
1236 Effect.andThen(orchestrator.getThreadRecords(threadId, fields, filter)),
1237 ),
1238 getThreadProjection,
1239 getCheckpointContext,
1240 getThreadSnapshot,
1241 getThreadTranscript,
1242 getThreadSnapshotWindow,
1243 getProjectThreadRecords,
1244 getProjectThread,
1245 getShellSnapshot: orchestrator.getShellSnapshot,
1246 listActiveSubagentThreadIds: orchestrator.listActiveSubagentThreadIds,
1247 listOlderSettledThreads: orchestrator.listOlderSettledThreads,
1248 readShellSnapshot: orchestrator.readShellSnapshot,
1249 getThreadShell: orchestrator.getThreadShell,
1250 listProjectThreads,
1251 sendToThread,
1252 assertProviderInstanceEnabled,
1253 isProviderInstanceEnabledForProject,
1254 hasReceipt,
1255 waitForThread,
1256 settleAfterRun,
1257 settleThread,
1258 interruptThread,
1259 stopDelegatedTasks,
1260 stopWorkflow,
1261 awaitBackgroundTasks,
1262 getThreadEventSequence: orchestrator.getThreadEventSequence,
1263 recoverDelegatedTask: orchestrator.recoverDelegatedTask,
1264 delegatedTaskResultPending: orchestrator.delegatedTaskResultPending,
1265 streamStoredEvents: orchestrator.streamStoredEvents,
1266 streamStoredEventsFrom: orchestrator.streamStoredEventsFrom,
1267 streamDomainEvents: orchestrator.streamDomainEvents,
1268 });
1269});
1270​
1271const layerLegacyV1ThreadImporterNoop = Layer.succeed(
1272 LegacyV1ThreadImporter.LegacyV1ThreadImporter,
1273 LegacyV1ThreadImporter.LegacyV1ThreadImporter.of({
1274 pendingThreadCount: Effect.succeed(0),
1275 reconcileShells: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
1276 ensureTranscript: () => Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
1277 importPendingTranscripts: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
1278 }),
1280​
1281export const layer: Layer.Layer<
1282 ThreadManagementService,
1283 never,
1284 | Orchestrator.OrchestratorV2
1285 | ProviderSessionManager.ProviderSessionManagerV2
1286 | ServerSettings.ServerSettingsService
1287 | CommandReceiptStore.CommandReceiptStoreV2
1288> = Layer.effect(ThreadManagementService, make).pipe(
1289 Layer.provide(layerLegacyV1ThreadImporterNoop),
1290 Layer.provide(ThreadCommandExecutor.layer),
1292​
1293export const layerWithLegacyImporter: Layer.Layer<
1294 ThreadManagementService,
1295 never,
1296 | LegacyV1ThreadImporter.LegacyV1ThreadImporter
1297 | Orchestrator.OrchestratorV2
1298 | ProviderSessionManager.ProviderSessionManagerV2
1299 | ServerSettings.ServerSettingsService
1300 | CommandReceiptStore.CommandReceiptStoreV2
1301> = Layer.effect(ThreadManagementService, make).pipe(Layer.provide(ThreadCommandExecutor.layer));