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

ThreadManagementService.ts

1,218 lines45.5 KB

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;
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 }
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 }
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;
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";
147​
148export interface ThreadManagementWaitInput {
149 readonly projectId: ProjectId;
150 readonly threadId: ThreadId;
151 readonly runId?: RunId;
152 readonly timeoutMs: number;
154​
155export interface ThreadManagementWaitResult {
156 readonly threadId: ThreadId;
157 readonly run: OrchestrationV2Run | null;
158 readonly timedOut: boolean;
160​
161export interface ThreadManagementInterruptInput {
162 readonly projectId: ProjectId;
163 readonly commandId: CommandId;
164 readonly threadId: ThreadId;
165 readonly runId?: RunId;
166 readonly reason?: string;
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 readonly compactPullRequests?: boolean;
368 }) => Effect.Effect<
369 Effect.Effect<OrchestrationV2ThreadShellSnapshot, Orchestrator.OrchestratorV2Error>,
370 Orchestrator.OrchestratorV2Error
371 >;
372 readonly getThreadShell: Orchestrator.OrchestratorV2["Service"]["getThreadShell"];
373 readonly listProjectThreads: (input: {
374 readonly projectId: ProjectId;
375 readonly includeSubagents: boolean;
376 }) => Effect.Effect<ReadonlyArray<OrchestrationV2ThreadShell>, ThreadManagementError>;
377 readonly sendToThread: (
378 input: ThreadManagementSendInput,
379 ) => Effect.Effect<ThreadManagementSendResult, ThreadManagementFailure>;
380 readonly assertProviderInstanceEnabled: (input: {
381 readonly projectId: ProjectId;
382 readonly commandId: CommandId;
383 readonly instanceId: ProviderInstanceId;
384 }) => Effect.Effect<void, ThreadManagementProviderInstanceDisabledError>;
385 readonly isProviderInstanceEnabledForProject: (input: {
386 readonly projectId: ProjectId;
387 readonly instanceId: ProviderInstanceId;
388 }) => Effect.Effect<boolean>;
389 /**
390 * A caller resolving a target ahead of a dispatch under this same command id
391 * can use it to skip project-enablement filtering: the dispatch will only
392 * replay the recorded result, never start anything new, so the filter would
393 * just refuse a retry the project's settings no longer allow fresh.
394 */
395 readonly hasReceipt: (commandId: CommandId) => Effect.Effect<boolean>;
396 readonly waitForThread: (
397 input: ThreadManagementWaitInput,
398 ) => Effect.Effect<ThreadManagementWaitResult, ThreadManagementError>;
399 /**
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 readonly settleThread: (input: {
411 readonly threadId: ThreadId;
412 readonly commandId: CommandId;
413 readonly byOwnAgent: boolean;
414 }) => Effect.Effect<
415 { readonly sequence: number } | { readonly settlesWhenTurnEnds: true },
416 Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
417 >;
418 readonly interruptThread: (
419 input: ThreadManagementInterruptInput,
420 ) => Effect.Effect<ThreadManagementInterruptResult, ThreadManagementFailure>;
421 readonly stopWorkflow: (
422 input: OrchestrationV2StopWorkflowInput,
423 ) => Effect.Effect<void, OrchestrationV2StopWorkflowError>;
424 readonly stopDelegatedTasks: (input: {
425 readonly threadId: ThreadId;
426 readonly commandId: CommandId;
427 readonly reason?: string | undefined;
428 }) => Effect.Effect<
429 void,
430 Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
431 >;
432 readonly getThreadEventSequence: Orchestrator.OrchestratorV2["Service"]["getThreadEventSequence"];
433 readonly recoverDelegatedTask: Orchestrator.OrchestratorV2["Service"]["recoverDelegatedTask"];
434 readonly delegatedTaskResultPending: Orchestrator.OrchestratorV2["Service"]["delegatedTaskResultPending"];
435 readonly streamStoredEvents: Orchestrator.OrchestratorV2["Service"]["streamStoredEvents"];
436 readonly streamStoredEventsFrom: Orchestrator.OrchestratorV2["Service"]["streamStoredEventsFrom"];
437 readonly streamDomainEvents: Orchestrator.OrchestratorV2["Service"]["streamDomainEvents"];
439​
440export class ThreadManagementService extends Context.Service<
441 ThreadManagementService,
442 ThreadManagementServiceShape
443>()("t3/orchestration-v2/ThreadManagementService") {}
444​
445export function isActiveRun(run: OrchestrationV2Run): boolean {
446 return (
447 run.status === "preparing" ||
448 run.status === "starting" ||
449 run.status === "running" ||
450 run.status === "waiting"
451 );
453​
454export function isTerminalRunStatus(
455 status: OrchestrationV2Run["status"],
456): status is ThreadManagementTerminalRunStatus {
457 return (
458 status === "completed" ||
459 status === "failed" ||
460 status === "cancelled" ||
461 status === "interrupted" ||
462 status === "rolled_back"
463 );
465​
466export function latestRun(
467 projection: Pick<OrchestrationV2ThreadProjection, "runs">,
468): OrchestrationV2Run | undefined {
469 return projection.runs.toSorted((left, right) => right.ordinal - left.ordinal)[0];
471​
472function latestRestartContinuation(
473 runs: ReadonlyArray<OrchestrationV2Run>,
474 run: OrchestrationV2Run,
475): OrchestrationV2Run {
476 let current = run;
477 for (let hops = 0; hops < runs.length; hops++) {
478 const next = runs.find((candidate) => candidate.restartContinuationOfRunId === current.id);
479 if (next === undefined) break;
480 current = next;
481 }
482 return current;
484​
485export function latestActiveRun(
486 projection: Pick<OrchestrationV2ThreadProjection, "runs">,
487): OrchestrationV2Run | undefined {
488 return projection.runs
489 .filter(isActiveRun)
490 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
492​
493function latestSteerableRun(
494 projection: Pick<OrchestrationV2ThreadProjection, "runs" | "providerTurns">,
495): OrchestrationV2Run | undefined {
496 return projection.runs
497 .filter(
498 (run) =>
499 run.status === "running" &&
500 run.activeAttemptId !== null &&
501 projection.providerTurns.some(
502 (turn) => turn.runAttemptId === run.activeAttemptId && turn.status === "running",
503 ),
504 )
505 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
507​
508const SETTLE_AFTER_RUN_WAIT_MS = 24 * 60 * 60 * 1_000;
509​
510const make = Effect.gen(function* () {
511 const threadDispatch = yield* ThreadCommandExecutor.ThreadCommandExecutor;
512 const orchestrator = yield* Orchestrator.OrchestratorV2;
513 const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
514 const layerScope = yield* Effect.scope;
515 const legacyImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
516 const serverSettings = yield* ServerSettings.ServerSettingsService;
517 const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
518​
519 const assertProviderInstanceEnabled: ThreadManagementServiceShape["assertProviderInstanceEnabled"] =
520 (input) =>
521 receipts.getByCommandId(input.commandId).pipe(
522 Effect.orElseSucceed(() => Option.none()),
523 Effect.flatMap((receipt) =>
524 Option.isSome(receipt)
525 ? Effect.void
526 : serverSettings.getSettings.pipe(
527 Effect.orDie,
528 Effect.flatMap((current) =>
529 resolveProjectProviderInstanceEnabled(current, input.projectId, input.instanceId)
530 ? Effect.void
531 : new ThreadManagementProviderInstanceDisabledError({
532 projectId: input.projectId,
533 instanceId: input.instanceId,
534 }),
535 ),
536 ),
537 ),
538 );
539​
540 const isProviderInstanceEnabledForProject: ThreadManagementServiceShape["isProviderInstanceEnabledForProject"] =
541 (input) =>
542 serverSettings.getSettings.pipe(
543 Effect.orDie,
544 Effect.map((current) =>
545 resolveProjectProviderInstanceEnabled(current, input.projectId, input.instanceId),
546 ),
547 );
548​
549 const hasReceipt: ThreadManagementServiceShape["hasReceipt"] = (commandId) =>
550 receipts.getByCommandId(commandId).pipe(
551 Effect.orElseSucceed(() => Option.none()),
552 Effect.map(Option.isSome),
553 );
554​
555 const ensureLegacyTranscript = Effect.fn(
556 "orchestrationV2.threadManagement.ensureLegacyTranscript",
557 )(function* (threadId: ThreadId) {
558 yield* legacyImporter.ensureTranscript(threadId).pipe(
559 Effect.tapError((cause) =>
560 Effect.logWarning("Unable to hydrate migrated v1 thread transcript", {
561 threadId,
562 cause,
563 }),
564 ),
565 );
566 });
567​
568 const ensureProjectionTranscript = (threadId: ThreadId) =>
569 ensureLegacyTranscript(threadId).pipe(
570 Effect.mapError(
571 (cause) =>
572 new Orchestrator.OrchestratorProjectionError({
573 threadId,
574 cause,
575 }),
576 ),
577 );
578​
579 const ensureCommandTranscripts = Effect.fn(
580 "orchestrationV2.threadManagement.ensureCommandTranscripts",
581 )(function* (command: OrchestrationV2ServerCommand) {
582 yield* Effect.forEach(
583 existingThreadIdsForCommand(command),
584 (threadId) => ensureLegacyTranscript(threadId),
585 { discard: true },
586 ).pipe(
587 Effect.mapError(
588 (cause) =>
589 new Orchestrator.OrchestratorDispatchError({
590 commandId: command.commandId,
591 commandType: command.type,
592 cause,
593 }),
594 ),
595 );
596 });
597​
598 const getThreadProjection: ThreadManagementServiceShape["getThreadProjection"] = (threadId) =>
599 ensureProjectionTranscript(threadId).pipe(
600 Effect.andThen(orchestrator.getThreadProjection(threadId)),
601 );
602​
603 const getCheckpointContext: ThreadManagementServiceShape["getCheckpointContext"] = (threadId) =>
604 ensureProjectionTranscript(threadId).pipe(
605 Effect.andThen(orchestrator.getCheckpointContext(threadId)),
606 );
607​
608 const getThreadSnapshot: ThreadManagementServiceShape["getThreadSnapshot"] = (threadId) =>
609 ensureProjectionTranscript(threadId).pipe(
610 Effect.andThen(orchestrator.getThreadSnapshot(threadId)),
611 );
612 const getThreadTranscript = Effect.fn("orchestrationV2.threadManagement.getThreadTranscript")(
613 function* (threadId: ThreadId) {
614 const { projection } = yield* getThreadSnapshot(threadId);
615 const environment = yield* ServerEnvironment.ServerEnvironmentIdentity;
616 const transcript = {
617 threadId: projection.thread.id,
618 title: projection.thread.title,
619 updatedAt: projection.updatedAt,
620 items: projection.visibleTurnItems,
621 };
622 let sizeBytes = Buffer.byteLength(
623 threadTranscriptHeader(yield* environment.getEnvironmentId, transcript),
624 "utf8",
625 );
626 if (sizeBytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) {
627 return yield* new ThreadTranscriptTooLargeError({ threadId });
628 }
629 for (const row of transcript.items) {
630 sizeBytes += projectedRowEncodedBytes(row) + 1;
631 if (sizeBytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) {
632 return yield* new ThreadTranscriptTooLargeError({ threadId });
633 }
634 }
635 return transcript;
636 },
637 );
638 const getThreadSnapshotWindow: ThreadManagementServiceShape["getThreadSnapshotWindow"] = (
639 threadId,
640 options,
641 ) =>
642 ensureProjectionTranscript(threadId).pipe(
643 Effect.andThen(orchestrator.getThreadSnapshotWindow(threadId, options)),
644 );
645​
646 const assertDispatchTargetEnabled = (command: OrchestrationV2ServerCommand) => {
647 switch (command.type) {
648 case "message.dispatch":
649 return orchestrator.getThreadRecords(command.threadId, []).pipe(
650 Effect.flatMap((projection) =>
651 assertProviderInstanceEnabled({
652 projectId: projection.thread.projectId,
653 commandId: command.commandId,
654 instanceId: (command.modelSelection ?? projection.thread.modelSelection).instanceId,
655 }),
656 ),
657 );
658 case "delegated_task.request":
659 return orchestrator.getThreadRecords(command.parentThreadId, []).pipe(
660 Effect.flatMap((parent) =>
661 assertProviderInstanceEnabled({
662 projectId: parent.thread.projectId,
663 commandId: command.commandId,
664 instanceId: command.modelSelection.instanceId,
665 }),
666 ),
667 );
668 default:
669 return Effect.void;
670 }
671 };
672​
673 const dispatch: ThreadManagementServiceShape["dispatch"] = (command) =>
674 ensureCommandTranscripts(command).pipe(
675 Effect.andThen(assertDispatchTargetEnabled(command)),
676 Effect.andThen(orchestrator.dispatch(command)),
677 );
678​
679 const getProjectThread: ThreadManagementServiceShape["getProjectThread"] = (input) =>
680 getThreadProjection(input.threadId).pipe(
681 Effect.mapError(
682 (cause) =>
683 new ThreadManagementProjectionLoadError({
684 projectId: input.projectId,
685 threadId: input.threadId,
686 cause,
687 }),
688 ),
689 Effect.flatMap((projection) =>
690 projection.thread.projectId === input.projectId && projection.thread.deletedAt === null
691 ? Effect.succeed(projection)
692 : Effect.fail(
693 new ThreadManagementThreadNotFoundError({
694 projectId: input.projectId,
695 threadId: input.threadId,
696 }),
697 ),
698 ),
699 );
700​
701 const getProjectThreadRecords: ThreadManagementServiceShape["getProjectThreadRecords"] = (
702 input,
703 fields,
704 filter,
705 ) =>
706 ensureProjectionTranscript(input.threadId)
707 .pipe(Effect.andThen(orchestrator.getThreadRecords(input.threadId, fields, filter)))
708 .pipe(
709 Effect.mapError(
710 (cause) =>
711 new ThreadManagementProjectionLoadError({
712 projectId: input.projectId,
713 threadId: input.threadId,
714 cause,
715 }),
716 ),
717 Effect.flatMap((projection) =>
718 projection.thread.projectId === input.projectId && projection.thread.deletedAt === null
719 ? Effect.succeed(projection)
720 : Effect.fail(
721 new ThreadManagementThreadNotFoundError({
722 projectId: input.projectId,
723 threadId: input.threadId,
724 }),
725 ),
726 ),
727 );
728​
729 const listProjectThreads: ThreadManagementServiceShape["listProjectThreads"] = (input) =>
730 orchestrator.getShellSnapshot({ projectId: input.projectId, location: "active" }).pipe(
731 Effect.mapError(
732 (cause) =>
733 new ThreadManagementProjectThreadsListError({
734 projectId: input.projectId,
735 cause,
736 }),
737 ),
738 Effect.map((snapshot) =>
739 snapshot.threads
740 .filter(
741 (thread) =>
742 input.includeSubagents || thread.lineage.relationshipToParent !== "subagent",
743 )
744 .toSorted(
745 (left, right) =>
746 DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt) ||
747 right.id.localeCompare(left.id),
748 ),
749 ),
750 );
751​
752 const sendToThread: ThreadManagementServiceShape["sendToThread"] = (input) =>
753 Effect.gen(function* () {
754 const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
755 if (target.thread.archivedAt !== null) {
756 return yield* new ThreadManagementThreadArchivedError({
757 threadId: input.threadId,
758 });
759 }
760 const steerableRun = latestSteerableRun(target);
761 let dispatchMode: Extract<
762 OrchestrationV2Command,
763 { readonly type: "message.dispatch" }
764 >["dispatchMode"];
765 if (input.mode === "steer" || input.mode === "restart") {
766 if (steerableRun === undefined) {
767 return yield* new ThreadManagementNoSteerableRunError({
768 threadId: input.threadId,
769 mode: input.mode,
770 });
771 }
772 dispatchMode = {
773 type: input.mode === "steer" ? "steer_active" : "restart_active",
774 targetRunId: steerableRun.id,
775 };
776 } else if (input.mode === "auto" && steerableRun !== undefined) {
777 dispatchMode = { type: "steer_active", targetRunId: steerableRun.id };
778 } else {
779 dispatchMode = {
780 type: input.mode === "queue" ? "queue_after_active" : "start_immediately",
781 };
782 }
783​
784 const dispatched = yield* dispatch({
785 type: "message.dispatch",
786 commandId: input.commandId,
787 threadId: input.threadId,
788 messageId: input.messageId,
789 ...(input.scheduledTaskId === undefined ? {} : { scheduledTaskId: input.scheduledTaskId }),
790 ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
791 text: input.text,
792 attachments: input.attachments,
793 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
794 dispatchMode,
795 createdBy: input.createdBy,
796 creationSource: input.creationSource,
797 });
798 const projection = yield* getProjectThreadRecords(input, ["runs", "messages", "turnItems"], {
799 messageIds: [input.messageId],
800 turnItemTypes: ["user_message"],
801 });
802 const message = projection.messages.find((candidate) => candidate.id === input.messageId);
803 const run =
804 message?.runId === null || message?.runId === undefined
805 ? undefined
806 : projection.runs.find((candidate) => candidate.id === message.runId);
807 const turnItem =
808 projection.turnItems.find(
809 (
810 candidate,
811 ): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> =>
812 candidate.type === "user_message" && candidate.messageId === input.messageId,
813 ) ?? null;
814 if (
815 message === undefined ||
816 run === undefined ||
817 (turnItem === null && run.status !== "queued")
818 ) {
819 return yield* new ThreadManagementDurableRunProjectionError({
820 threadId: input.threadId,
821 messageId: input.messageId,
822 });
823 }
824 const delivery: ThreadManagementSendResult["delivery"] =
825 turnItem === null || turnItem.inputIntent === "queued_turn"
826 ? "queued"
827 : turnItem.inputIntent === "turn_start"
828 ? "started"
829 : input.mode === "restart"
830 ? "restarted"
831 : "steered";
832 return { dispatch: dispatched, projection, message, run, turnItem, delivery };
833 });
834​
835 const waitForThread: ThreadManagementServiceShape["waitForThread"] = (input) =>
836 Effect.gen(function* () {
837 const loadError = (cause: unknown) =>
838 new ThreadManagementProjectionLoadError({
839 projectId: input.projectId,
840 threadId: input.threadId,
841 cause,
842 });
843 // Taken before the first read, so a run update between that read and
844 // the subscription below still replays.
845 const afterSequence = yield* orchestrator
846 .getThreadEventSequence(input.threadId)
847 .pipe(Effect.mapError(loadError));
848 const target = yield* getProjectThreadRecords(input, ["runs"]);
849 const selectedRun =
850 input.runId === undefined
851 ? latestRun(target)
852 : target.runs.find((candidate) => candidate.id === input.runId);
853 if (input.runId !== undefined && selectedRun === undefined) {
854 return yield* new ThreadManagementRunNotFoundError({
855 threadId: input.threadId,
856 runId: input.runId,
857 });
858 }
859 if (selectedRun === undefined) {
860 return { threadId: input.threadId, run: null, timedOut: false };
861 }
862 // A restart cuts a run and continues it as a new run. Follow that chain,
863 // so a cut run is not the answer while its continuation is pending.
864 const outcome = (runs: ReadonlyArray<OrchestrationV2Run>) =>
865 Effect.gen(function* () {
866 const current = runs.find((candidate) => candidate.id === selectedRun.id);
867 if (current === undefined) {
868 return yield* new ThreadManagementRunNotFoundError({
869 threadId: input.threadId,
870 runId: selectedRun.id,
871 });
872 }
873 const run = latestRestartContinuation(runs, current);
874 const pending =
875 isTerminalRunStatus(run.status) &&
876 (yield* orchestrator.restartContinuationPending(run));
877 return { run, pending, settled: isTerminalRunStatus(run.status) && !pending };
878 });
879 const initial = yield* outcome(target.runs);
880 if (initial.settled) {
881 return { threadId: input.threadId, run: initial.run, timedOut: false };
882 }
883​
884 // A declined continuation records no event, so its effect settling wakes
885 // the wait too.
886 const wait = Stream.merge(
887 Stream.merge(
888 orchestrator.streamStoredEventsFrom({
889 threadId: input.threadId,
890 afterSequence,
891 eventType: "run.updated",
892 }),
893 orchestrator.streamStoredEventsFrom({
894 threadId: input.threadId,
895 afterSequence,
896 eventType: "thread.deleted",
897 }),
898 ).pipe(
899 Stream.mapError(loadError),
900 Stream.filter(
901 (stored) =>
902 stored.event.type !== "run.updated" ||
903 stored.event.payload.id === selectedRun.id ||
904 stored.event.payload.restartContinuationOfRunId !== undefined,
905 ),
906 ),
907 initial.pending
908 ? Stream.fromEffect(orchestrator.awaitRestartContinuation(initial.run))
909 : Stream.empty,
910 ).pipe(
911 Stream.mapEffect(() =>
912 getProjectThreadRecords(input, ["runs"]).pipe(
913 Effect.flatMap((current) => outcome(current.runs)),
914 ),
915 ),
916 Stream.filter((current) => current.settled),
917 Stream.runHead,
918 Effect.timeoutOption(Duration.millis(Math.max(1, input.timeoutMs))),
919 );
920 const waited = Option.flatten(yield* wait);
921 if (Option.isSome(waited)) {
922 return { threadId: input.threadId, run: waited.value.run, timedOut: false };
923 }
924 // The run may have reached a terminal status while the timeout was
925 // winning the race; the final projection read decides what actually
926 // happened, so only a still-active run counts as timed out.
927 const final = yield* outcome((yield* getProjectThreadRecords(input, ["runs"])).runs);
928 return { threadId: input.threadId, run: final.run, timedOut: !final.settled };
929 });
930​
931 const settleAfterRun: ThreadManagementServiceShape["settleAfterRun"] = Effect.fn(
932 "orchestrationV2.threadManagement.settleAfterRun",
933 )(function* (input) {
934 const { run } = yield* waitForThread({ ...input, timeoutMs: SETTLE_AFTER_RUN_WAIT_MS });
935 if (run?.status !== "completed") return;
936 yield* dispatch({
937 type: "thread.settle",
938 commandId: CommandId.make(`server:settle-after-run:${input.runId}`),
939 threadId: input.threadId,
940 });
941 });
942​
943 const settleThread: ThreadManagementServiceShape["settleThread"] = Effect.fn(
944 "orchestrationV2.threadManagement.settleThread",
945 )(function* (input) {
946 const shell = input.byOwnAgent ? yield* orchestrator.getThreadShell(input.threadId) : null;
947 if (shell != null && shell.activeRunId !== null) {
948 yield* settleAfterRun({
949 projectId: shell.projectId,
950 threadId: shell.id,
951 runId: shell.activeRunId,
952 }).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(layerScope));
953 return { settlesWhenTurnEnds: true } as const;
954 }
955 const result = yield* dispatch({
956 type: "thread.settle",
957 commandId: input.commandId,
958 threadId: input.threadId,
959 });
960 return { sequence: result.sequence };
961 });
962​
963 const interruptThread: ThreadManagementServiceShape["interruptThread"] = (input) =>
964 Effect.gen(function* () {
965 const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
966 const explicitRun =
967 input.runId === undefined
968 ? undefined
969 : target.runs.find((candidate) => candidate.id === input.runId);
970 if (input.runId !== undefined && explicitRun === undefined) {
971 return yield* new ThreadManagementRunNotFoundError({
972 threadId: input.threadId,
973 runId: input.runId,
974 });
975 }
976 if (explicitRun !== undefined && isTerminalRunStatus(explicitRun.status)) {
977 return {
978 type: "already_terminal",
979 run: explicitRun as OrchestrationV2Run & {
980 readonly status: ThreadManagementTerminalRunStatus;
981 },
982 } as const;
983 }
984 const interruptibleRun = latestActiveRun(target);
985 if (interruptibleRun === undefined) {
986 if (input.runId === undefined) {
987 return { type: "no_active_run" } as const;
988 }
989 return yield* new ThreadManagementThreadNotInterruptibleError({
990 threadId: input.threadId,
991 runId: input.runId,
992 });
993 }
994 if (input.runId !== undefined && interruptibleRun.id !== input.runId) {
995 return yield* new ThreadManagementThreadNotInterruptibleError({
996 threadId: input.threadId,
997 runId: input.runId,
998 });
999 }
1000 const dispatch = yield* orchestrator.dispatch({
1001 type: "run.interrupt",
1002 commandId: input.commandId,
1003 threadId: input.threadId,
1004 runId: interruptibleRun.id,
1005 ...(input.reason === undefined ? {} : { reason: input.reason }),
1006 });
1007 return { type: "interrupt_requested", run: interruptibleRun, dispatch } as const;
1008 });
1009​
1010 const stopWorkflow: ThreadManagementServiceShape["stopWorkflow"] = (input) =>
1011 Effect.gen(function* () {
1012 const records = yield* orchestrator
1013 .getThreadRecords(input.threadId, ["subagents", "runs", "providerThreads"])
1014 .pipe(
1015 Effect.mapError(
1016 (cause) =>
1017 new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable", cause }),
1018 ),
1019 );
1020 if (records.thread.deletedAt !== null) {
1021 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable" });
1023 // A limited caller (an agent over MCP) may not stop work on a thread
1024 // running above its own modes. Checked under the thread lock, where the
1025 // thread's user cannot raise the modes between this read and the stop.
1026 const limit = yield* DispatchModeLimit;
1027 const exceeded =
1028 limit === undefined ? undefined : exceededDispatchModeLimit(limit, records.thread);
1029 if (limit !== undefined && exceeded !== undefined) {
1030 if (limit.refused !== undefined) {
1031 yield* Ref.set(limit.refused, {
1032 threadId: input.threadId,
1033 runtimeMode: records.thread.runtimeMode,
1034 interactionMode: records.thread.interactionMode,
1035 mode: exceeded,
1036 });
1038 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable" });
1040 const task = records.subagents.find((candidate) => candidate.id === input.subagentId);
1041 if (
1042 task === undefined ||
1043 task.threadId !== input.threadId ||
1044 task.workflow === undefined ||
1045 task.status !== "running"
1046 ) {
1047 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "not-running" });
1049 if (task.origin !== "provider_native" || task.driver !== "claudeAgent") {
1050 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unsupported" });
1052 const providerThreadId =
1053 task.providerThreadId ??
1054 records.runs.find((run) => run.id === task.runId)?.providerThreadId;
1055 const providerThread = records.providerThreads.find(
1056 (candidate) =>
1057 candidate.id === providerThreadId &&
1058 candidate.appThreadId === input.threadId &&
1059 candidate.providerInstanceId === task.providerInstanceId &&
1060 candidate.driver === task.driver,
1061 );
1062 const taskId = task.nativeTaskRef?.nativeId;
1063 if (providerThread?.providerSessionId == null || taskId == null || taskId.length === 0) {
1064 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable" });
1066 const runtime = yield* sessions
1067 .get(providerThread.providerSessionId)
1068 .pipe(
1069 Effect.mapError(
1070 (cause) =>
1071 new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable", cause }),
1072 ),
1073 );
1074 if (Option.isNone(runtime)) {
1075 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unavailable" });
1077 if (runtime.value.stopTask === undefined) {
1078 return yield* new OrchestrationV2StopWorkflowError({ ...input, reason: "unsupported" });
1080 // Bounded so a provider that never answers cannot hold the thread lock.
1081 yield* runtime.value.stopTask({ providerThread, taskId }).pipe(
1082 Effect.timeout("15 seconds"),
1083 Effect.mapError(
1084 (cause) =>
1085 new OrchestrationV2StopWorkflowError({
1086 ...input,
1087 reason: "stop-failed",
1088 cause,
1089 }),
1090 ),
1091 );
1092 }).pipe((effect) => threadDispatch.withLock(input.threadId, effect));
1093​
1094 const stopDelegatedTasks: ThreadManagementServiceShape["stopDelegatedTasks"] = (input) =>
1095 Effect.gen(function* () {
1096 const { subagents } = yield* orchestrator.getThreadRecords(input.threadId, ["subagents"]);
1097 const failures: Array<
1098 Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
1099 > = [];
1100 for (const task of subagents) {
1101 if (task.origin !== "app_owned" || task.childThreadId === null) continue;
1102 const threadId = task.childThreadId;
1103 yield* dispatch({
1104 type: "thread.stop",
1105 commandId: CommandId.make(`${input.commandId}:stop:${threadId}`),
1106 threadId,
1107 ...(input.reason === undefined ? {} : { reason: input.reason }),
1108 }).pipe(
1109 Effect.andThen(stopDelegatedTasks({ ...input, threadId })),
1110 Effect.catch((error) =>
1111 Effect.logWarning("Unable to stop a delegated task", {
1112 parentThreadId: input.threadId,
1113 threadId,
1114 error,
1115 }).pipe(Effect.andThen(Effect.sync(() => failures.push(error)))),
1116 ),
1117 );
1119 if (failures[0] !== undefined) return yield* Effect.fail(failures[0]);
1120 });
1121​
1122 return ThreadManagementService.of({
1123 ensureLegacyTranscript,
1124 searchThreadStream: (input) =>
1125 Stream.unwrap(
1126 ensureProjectionTranscript(input.threadId).pipe(
1127 Effect.as(orchestrator.searchThreadStream(input)),
1128 ),
1129 ),
1130 searchThread: (input) =>
1131 ensureProjectionTranscript(input.threadId).pipe(
1132 Effect.andThen(orchestrator.searchThread(input)),
1133 ),
1134 dispatch,
1135 getThreadHistoryPage: (threadId, cursor, throughEntryId, conversationOnly) =>
1136 ensureProjectionTranscript(threadId).pipe(
1137 Effect.andThen(
1138 orchestrator.getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly),
1139 ),
1140 ),
1141 getTimelinePage: (threadId, options) =>
1142 ensureProjectionTranscript(threadId).pipe(
1143 Effect.andThen(orchestrator.getTimelinePage(threadId, options)),
1144 ),
1145 getMessageCount: (threadId) =>
1146 ensureProjectionTranscript(threadId).pipe(
1147 Effect.andThen(orchestrator.getMessageCount(threadId)),
1148 ),
1149 getTurnItem: (input) =>
1150 ensureProjectionTranscript(input.threadId).pipe(
1151 Effect.andThen(orchestrator.getTurnItem(input)),
1152 Effect.map((item) => ({ item: item === null ? null : projectTurnItemForDetail(item) })),
1153 ),
1154 getThreadRecords: (threadId, fields, filter) =>
1155 ensureProjectionTranscript(threadId).pipe(
1156 Effect.andThen(orchestrator.getThreadRecords(threadId, fields, filter)),
1157 ),
1158 getThreadProjection,
1159 getCheckpointContext,
1160 getThreadSnapshot,
1161 getThreadTranscript,
1162 getThreadSnapshotWindow,
1163 getProjectThreadRecords,
1164 getProjectThread,
1165 getShellSnapshot: orchestrator.getShellSnapshot,
1166 readShellSnapshot: orchestrator.readShellSnapshot,
1167 getThreadShell: orchestrator.getThreadShell,
1168 listProjectThreads,
1169 sendToThread,
1170 assertProviderInstanceEnabled,
1171 isProviderInstanceEnabledForProject,
1172 hasReceipt,
1173 waitForThread,
1174 settleAfterRun,
1175 settleThread,
1176 interruptThread,
1177 stopDelegatedTasks,
1178 stopWorkflow,
1179 getThreadEventSequence: orchestrator.getThreadEventSequence,
1180 recoverDelegatedTask: orchestrator.recoverDelegatedTask,
1181 delegatedTaskResultPending: orchestrator.delegatedTaskResultPending,
1182 streamStoredEvents: orchestrator.streamStoredEvents,
1183 streamStoredEventsFrom: orchestrator.streamStoredEventsFrom,
1184 streamDomainEvents: orchestrator.streamDomainEvents,
1185 });
1186});
1187​
1188const layerLegacyV1ThreadImporterNoop = Layer.succeed(
1189 LegacyV1ThreadImporter.LegacyV1ThreadImporter,
1190 LegacyV1ThreadImporter.LegacyV1ThreadImporter.of({
1191 pendingThreadCount: Effect.succeed(0),
1192 reconcileShells: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
1193 ensureTranscript: () => Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
1194 importPendingTranscripts: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
1195 }),
1197​
1198export const layer: Layer.Layer<
1199 ThreadManagementService,
1200 never,
1201 | Orchestrator.OrchestratorV2
1202 | ProviderSessionManager.ProviderSessionManagerV2
1203 | ServerSettings.ServerSettingsService
1204 | CommandReceiptStore.CommandReceiptStoreV2
1205> = Layer.effect(ThreadManagementService, make).pipe(
1206 Layer.provide(layerLegacyV1ThreadImporterNoop),
1207 Layer.provide(ThreadCommandExecutor.layer),
1209​
1210export const layerWithLegacyImporter: Layer.Layer<
1211 ThreadManagementService,
1212 never,
1213 | LegacyV1ThreadImporter.LegacyV1ThreadImporter
1214 | Orchestrator.OrchestratorV2
1215 | ProviderSessionManager.ProviderSessionManagerV2
1216 | ServerSettings.ServerSettingsService
1217 | CommandReceiptStore.CommandReceiptStoreV2
1218> = Layer.effect(ThreadManagementService, make).pipe(Layer.provide(ThreadCommandExecutor.layer));