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