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