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

ThreadManagementService.ts

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