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"] = Effect.fn(
752 "ThreadManagementService.sendToThread",
753 )(function* (input) {
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"] = Effect.fn(
836 "ThreadManagementService.waitForThread",
837 )(function* (input) {
838 const loadError = (cause: unknown) =>
839 new ThreadManagementProjectionLoadError({
840 projectId: input.projectId,
841 threadId: input.threadId,
842 cause,
843 });
844 // Taken before the first read, so a run update between that read and
845 // the subscription below still replays.
846 const afterSequence = yield* orchestrator
847 .getThreadEventSequence(input.threadId)
848 .pipe(Effect.mapError(loadError));
849 const target = yield* getProjectThreadRecords(input, ["runs"]);
850 const selectedRun =
851 input.runId === undefined
852 ? latestRun(target)
853 : target.runs.find((candidate) => candidate.id === input.runId);
854 if (input.runId !== undefined && selectedRun === undefined) {
855 return yield* new ThreadManagementRunNotFoundError({
856 threadId: input.threadId,
857 runId: input.runId,
858 });
859 }
860 if (selectedRun === undefined) {
861 return { threadId: input.threadId, run: null, timedOut: false };
862 }
863 // A restart cuts a run and continues it as a new run. Follow that chain,
864 // so a cut run is not the answer while its continuation is pending.
865 // Runs per matching event and is already covered by the waitForThread span.
866 const outcome = Effect.fnUntraced(function* (runs: ReadonlyArray<OrchestrationV2Run>) {
867 const current = runs.find((candidate) => candidate.id === selectedRun.id);
868 if (current === undefined) {
869 return yield* new ThreadManagementRunNotFoundError({
870 threadId: input.threadId,
871 runId: selectedRun.id,
872 });
873 }
874 const run = latestRestartContinuation(runs, current);
875 const pending =
876 isTerminalRunStatus(run.status) && (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"] = Effect.fn(
964 "ThreadManagementService.interruptThread",
965 )(function* (input) {
966 const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
967 const explicitRun =
968 input.runId === undefined
969 ? undefined
970 : target.runs.find((candidate) => candidate.id === input.runId);
971 if (input.runId !== undefined && explicitRun === undefined) {
972 return yield* new ThreadManagementRunNotFoundError({
973 threadId: input.threadId,
974 runId: input.runId,
975 });
976 }
977 if (explicitRun !== undefined && isTerminalRunStatus(explicitRun.status)) {
978 return {
979 type: "already_terminal",
980 run: explicitRun as OrchestrationV2Run & {
981 readonly status: ThreadManagementTerminalRunStatus;
982 },
983 } as const;
984 }
985 const interruptibleRun = latestActiveRun(target);
986 if (interruptibleRun === undefined) {
987 if (input.runId === undefined) {
988 return { type: "no_active_run" } as const;
989 }
990 return yield* new ThreadManagementThreadNotInterruptibleError({
991 threadId: input.threadId,
992 runId: input.runId,
993 });
994 }
995 if (input.runId !== undefined && interruptibleRun.id !== input.runId) {
996 return yield* new ThreadManagementThreadNotInterruptibleError({
997 threadId: input.threadId,
998 runId: input.runId,
999 });
1000 }
1001 const dispatch = yield* orchestrator.dispatch({
1002 type: "run.interrupt",
1003 commandId: input.commandId,
1004 threadId: input.threadId,
1005 runId: interruptibleRun.id,
1006 ...(input.reason === undefined ? {} : { reason: input.reason }),
1007 });
1008 return { type: "interrupt_requested", run: interruptibleRun, dispatch } as const;
1009 });
1010
1011 const stopWorkflow: ThreadManagementServiceShape["stopWorkflow"] = Effect.fn(
1012 "ThreadManagementService.stopWorkflow",
1013 )(
1014 function* (input) {
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 },
1096 (effect, input) => effect.pipe((effect) => threadDispatch.withLock(input.threadId, effect)),
1097 );
1098
1099 const stopDelegatedTasks: ThreadManagementServiceShape["stopDelegatedTasks"] = Effect.fn(
1100 "ThreadManagementService.stopDelegatedTasks",
1101 )(function* (input) {
1102 const { subagents } = yield* orchestrator.getThreadRecords(input.threadId, ["subagents"]);
1103 const failures: Array<
1104 Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
1105 > = [];
1106 const stoppedChildThreadIds = new Set<ThreadId>();
1107 for (const task of subagents) {
1108 if (task.origin !== "app_owned" || task.childThreadId === null) continue;
1109 const threadId = task.childThreadId;
1110 // Follow-up tasks reuse a child thread; walk its subtree only once.
1111 if (stoppedChildThreadIds.has(threadId)) continue;
1112 stoppedChildThreadIds.add(threadId);
1113 yield* dispatch({
1114 type: "thread.stop",
1115 commandId: CommandId.make(`${input.commandId}:stop:${threadId}`),
1116 threadId,
1117 ...(input.reason === undefined ? {} : { reason: input.reason }),
1118 }).pipe(
1119 Effect.andThen(stopDelegatedTasks({ ...input, threadId })),
1120 Effect.catch((error) =>
1121 Effect.logWarning("Unable to stop a delegated task", {
1122 parentThreadId: input.threadId,
1123 threadId,
1124 error,
1125 }).pipe(Effect.andThen(Effect.sync(() => failures.push(error)))),
1126 ),
1127 );
1128 }
1129 if (failures[0] !== undefined) return yield* Effect.fail(failures[0]);
1130 });
1131
1132 return ThreadManagementService.of({
1133 ensureLegacyTranscript,
1134 searchThreadStream: (input) =>
1135 Stream.unwrap(
1136 ensureProjectionTranscript(input.threadId).pipe(
1137 Effect.as(orchestrator.searchThreadStream(input)),
1138 ),
1139 ),
1140 searchThread: (input) =>
1141 ensureProjectionTranscript(input.threadId).pipe(
1142 Effect.andThen(orchestrator.searchThread(input)),
1143 ),
1144 dispatch,
1145 getThreadHistoryPage: (threadId, cursor, throughEntryId, conversationOnly) =>
1146 ensureProjectionTranscript(threadId).pipe(
1147 Effect.andThen(
1148 orchestrator.getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly),
1149 ),
1150 ),
1151 getTimelinePage: (threadId, options) =>
1152 ensureProjectionTranscript(threadId).pipe(
1153 Effect.andThen(orchestrator.getTimelinePage(threadId, options)),
1154 ),
1155 getMessageCount: (threadId) =>
1156 ensureProjectionTranscript(threadId).pipe(
1157 Effect.andThen(orchestrator.getMessageCount(threadId)),
1158 ),
1159 getTurnItem: (input) =>
1160 ensureProjectionTranscript(input.threadId).pipe(
1161 Effect.andThen(orchestrator.getTurnItem(input)),
1162 Effect.map((item) => ({ item: item === null ? null : projectTurnItemForDetail(item) })),
1163 ),
1164 getThreadRecords: (threadId, fields, filter) =>
1165 ensureProjectionTranscript(threadId).pipe(
1166 Effect.andThen(orchestrator.getThreadRecords(threadId, fields, filter)),
1167 ),
1168 getThreadProjection,
1169 getCheckpointContext,
1170 getThreadSnapshot,
1171 getThreadTranscript,
1172 getThreadSnapshotWindow,
1173 getProjectThreadRecords,
1174 getProjectThread,
1175 getShellSnapshot: orchestrator.getShellSnapshot,
1176 readShellSnapshot: orchestrator.readShellSnapshot,
1177 getThreadShell: orchestrator.getThreadShell,
1178 listProjectThreads,
1179 sendToThread,
1180 assertProviderInstanceEnabled,
1181 isProviderInstanceEnabledForProject,
1182 hasReceipt,
1183 waitForThread,
1184 settleAfterRun,
1185 settleThread,
1186 interruptThread,
1187 stopDelegatedTasks,
1188 stopWorkflow,
1189 getThreadEventSequence: orchestrator.getThreadEventSequence,
1190 recoverDelegatedTask: orchestrator.recoverDelegatedTask,
1191 delegatedTaskResultPending: orchestrator.delegatedTaskResultPending,
1192 streamStoredEvents: orchestrator.streamStoredEvents,
1193 streamStoredEventsFrom: orchestrator.streamStoredEventsFrom,
1194 streamDomainEvents: orchestrator.streamDomainEvents,
1195 });
1196});
1197
1198const layerLegacyV1ThreadImporterNoop = Layer.succeed(
1199 LegacyV1ThreadImporter.LegacyV1ThreadImporter,
1200 LegacyV1ThreadImporter.LegacyV1ThreadImporter.of({
1201 pendingThreadCount: Effect.succeed(0),
1202 reconcileShells: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
1203 ensureTranscript: () => Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
1204 importPendingTranscripts: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
1205 }),
1206);
1207
1208export const layer: Layer.Layer<
1209 ThreadManagementService,
1210 never,
1211 | Orchestrator.OrchestratorV2
1212 | ProviderSessionManager.ProviderSessionManagerV2
1213 | ServerSettings.ServerSettingsService
1214 | CommandReceiptStore.CommandReceiptStoreV2
1215> = Layer.effect(ThreadManagementService, make).pipe(
1216 Layer.provide(layerLegacyV1ThreadImporterNoop),
1217 Layer.provide(ThreadCommandExecutor.layer),
1218);
1219
1220export const layerWithLegacyImporter: Layer.Layer<
1221 ThreadManagementService,
1222 never,
1223 | LegacyV1ThreadImporter.LegacyV1ThreadImporter
1224 | Orchestrator.OrchestratorV2
1225 | ProviderSessionManager.ProviderSessionManagerV2
1226 | ServerSettings.ServerSettingsService
1227 | CommandReceiptStore.CommandReceiptStoreV2
1228> = Layer.effect(ThreadManagementService, make).pipe(Layer.provide(ThreadCommandExecutor.layer));