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

ThreadManagementService.ts

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