Open History to see the last commit
1import {
2 type ChatAttachment,
3 type CommandId,
4 MessageId,
5 type ModelSelection,
6 type OrchestrationV2Actor,
7 type OrchestrationV2Command,
8 type OrchestrationV2ConversationMessage,
9 type OrchestrationV2CreationSource,
10 type OrchestrationV2Run,
11 type OrchestrationV2ThreadShellSnapshot,
12 type OrchestrationV2ThreadProjection,
13 type OrchestrationV2ThreadShell,
14 type OrchestrationV2TurnItem,
15 ProjectId,
16 RunId,
17 type ScheduledTaskId,
18 ThreadId,
19} from "@t3tools/contracts";
20import * as Context from "effect/Context";
21import * as DateTime from "effect/DateTime";
22import * as Duration from "effect/Duration";
23import * as Effect from "effect/Effect";
24import * as Layer from "effect/Layer";
25import * as Option from "effect/Option";
26import * as Schema from "effect/Schema";
27
28import {
29 OrchestratorDispatchError,
30 OrchestratorProjectionError,
31 OrchestratorV2,
32 type OrchestratorV2DispatchResult,
33 type OrchestratorV2Error,
34} from "./Orchestrator.ts";
35import {
36 LegacyV1ThreadImporter,
37 type LegacyV1ThreadImportError,
38} from "./LegacyV1ThreadImporter.ts";
39
40export type ThreadManagementSendMode = "auto" | "queue" | "steer" | "restart";
41
42export interface ThreadManagementProvenance {
43 readonly createdBy: OrchestrationV2Actor;
44 readonly creationSource: OrchestrationV2CreationSource;
45}
46
47export function withCreationProvenance(
48 command: OrchestrationV2Command,
49 provenance: ThreadManagementProvenance,
50): OrchestrationV2Command {
51 switch (command.type) {
52 case "thread.create":
53 case "message.dispatch":
54 case "thread.fork":
55 case "thread.merge_back":
56 case "delegated_task.request":
57 return { ...command, ...provenance };
58 default:
59 return command;
60 }
61}
62
63export function existingThreadIdsForCommand(
64 command: OrchestrationV2Command,
65): ReadonlyArray<ThreadId> {
66 switch (command.type) {
67 case "thread.create":
68 return [];
69 // Read-state commands only rewrite the thread payload's visited/unread
70 // watermark; they never touch messages, so they do not need the imported
71 // v1 transcript hydrated first. Visits fire on every thread-activity bump
72 // while a thread is open, so keeping them off the import path matters.
73 case "thread.visit":
74 case "thread.mark-unread":
75 return [];
76 case "thread.fork":
77 return [command.sourceThreadId];
78 case "thread.merge_back":
79 return command.sourceThreadId === command.targetThreadId
80 ? [command.sourceThreadId]
81 : [command.sourceThreadId, command.targetThreadId];
82 case "delegated_task.request":
83 case "delegated_task.wake-policy":
84 case "delegated_task.completion-delivery.acknowledge":
85 case "delegated_task.completion-delivery.dispose":
86 return [command.parentThreadId];
87 case "thread.created.record":
88 return command.parentThreadId === command.targetThreadId
89 ? [command.parentThreadId]
90 : [command.parentThreadId, command.targetThreadId];
91 default:
92 return [command.threadId];
93 }
94}
95
96export type ThreadManagementTerminalRunStatus = Extract<
97 OrchestrationV2Run["status"],
98 "completed" | "failed" | "cancelled" | "interrupted" | "rolled_back"
99>;
100
101export interface ThreadManagementSendInput {
102 readonly projectId: ProjectId;
103 readonly commandId: CommandId;
104 readonly threadId: ThreadId;
105 readonly messageId: MessageId;
106 readonly scheduledTaskId?: ScheduledTaskId;
107 readonly text: string;
108 readonly attachments: ReadonlyArray<ChatAttachment>;
109 readonly modelSelection?: ModelSelection;
110 readonly mode: ThreadManagementSendMode;
111 readonly createdBy: OrchestrationV2Actor;
112 readonly creationSource: OrchestrationV2CreationSource;
113}
114
115export interface ThreadManagementSendResult {
116 readonly dispatch: OrchestratorV2DispatchResult;
117 readonly projection: OrchestrationV2ThreadProjection;
118 readonly message: OrchestrationV2ConversationMessage;
119 readonly run: OrchestrationV2Run;
120 /** Null for queued sends: the user turn item materializes when the queued turn starts. */
121 readonly turnItem: Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> | null;
122 readonly delivery: "started" | "queued" | "steered" | "restarted";
123}
124
125export interface ThreadManagementWaitInput {
126 readonly projectId: ProjectId;
127 readonly threadId: ThreadId;
128 readonly runId?: RunId;
129 readonly timeoutMs: number;
130 readonly pollIntervalMs?: number;
131}
132
133export interface ThreadManagementWaitResult {
134 readonly threadId: ThreadId;
135 readonly run: OrchestrationV2Run | null;
136 readonly timedOut: boolean;
137}
138
139export interface ThreadManagementInterruptInput {
140 readonly projectId: ProjectId;
141 readonly commandId: CommandId;
142 readonly threadId: ThreadId;
143 readonly runId?: RunId;
144 readonly reason?: string;
145}
146
147export type ThreadManagementInterruptResult =
148 | {
149 readonly type: "interrupt_requested";
150 readonly run: OrchestrationV2Run;
151 readonly dispatch: OrchestratorV2DispatchResult;
152 }
153 | { readonly type: "no_active_run" }
154 | {
155 readonly type: "already_terminal";
156 readonly run: OrchestrationV2Run & { readonly status: ThreadManagementTerminalRunStatus };
157 };
158
159export class ThreadManagementThreadNotFoundError extends Schema.TaggedError<ThreadManagementThreadNotFoundError>()(
160 "ThreadManagementThreadNotFoundError",
161 {
162 projectId: ProjectId,
163 threadId: ThreadId,
164 },
165) {
166 override get message(): string {
167 return `Thread ${this.threadId} was not found in project ${this.projectId}.`;
168 }
169}
170
171export class ThreadManagementRunNotFoundError extends Schema.TaggedError<ThreadManagementRunNotFoundError>()(
172 "ThreadManagementRunNotFoundError",
173 {
174 threadId: ThreadId,
175 runId: RunId,
176 },
177) {
178 override get message(): string {
179 return `Run ${this.runId} does not belong to thread ${this.threadId}.`;
180 }
181}
182
183export class ThreadManagementThreadArchivedError extends Schema.TaggedError<ThreadManagementThreadArchivedError>()(
184 "ThreadManagementThreadArchivedError",
185 {
186 threadId: ThreadId,
187 },
188) {
189 override get message(): string {
190 return `Thread ${this.threadId} is archived and cannot receive messages.`;
191 }
192}
193
194export class ThreadManagementNoSteerableRunError extends Schema.TaggedError<ThreadManagementNoSteerableRunError>()(
195 "ThreadManagementNoSteerableRunError",
196 {
197 threadId: ThreadId,
198 mode: Schema.Literals(["steer", "restart"]),
199 },
200) {
201 override get message(): string {
202 return `Thread ${this.threadId} has no running turn that can be ${this.mode === "steer" ? "steered" : "restarted"}.`;
203 }
204}
205
206export class ThreadManagementThreadNotInterruptibleError extends Schema.TaggedError<ThreadManagementThreadNotInterruptibleError>()(
207 "ThreadManagementThreadNotInterruptibleError",
208 {
209 threadId: ThreadId,
210 runId: RunId,
211 },
212) {
213 override get message(): string {
214 return `Run ${this.runId} is not currently interruptible.`;
215 }
216}
217
218export class ThreadManagementProjectionLoadError extends Schema.TaggedError<ThreadManagementProjectionLoadError>()(
219 "ThreadManagementProjectionLoadError",
220 {
221 projectId: ProjectId,
222 threadId: ThreadId,
223 cause: Schema.Defect(),
224 },
225) {
226 override get message(): string {
227 return `Unable to load thread ${this.threadId} in project ${this.projectId}.`;
228 }
229}
230
231export class ThreadManagementProjectThreadsListError extends Schema.TaggedError<ThreadManagementProjectThreadsListError>()(
232 "ThreadManagementProjectThreadsListError",
233 {
234 projectId: ProjectId,
235 cause: Schema.Defect(),
236 },
237) {
238 override get message(): string {
239 return `Unable to list threads in project ${this.projectId}.`;
240 }
241}
242
243export class ThreadManagementDurableRunProjectionError extends Schema.TaggedError<ThreadManagementDurableRunProjectionError>()(
244 "ThreadManagementDurableRunProjectionError",
245 {
246 threadId: ThreadId,
247 messageId: MessageId,
248 },
249) {
250 override get message(): string {
251 return `Message ${this.messageId} was accepted on thread ${this.threadId} without a durable run projection.`;
252 }
253}
254
255export const ThreadManagementError = Schema.Union([
256 ThreadManagementThreadNotFoundError,
257 ThreadManagementRunNotFoundError,
258 ThreadManagementThreadArchivedError,
259 ThreadManagementNoSteerableRunError,
260 ThreadManagementThreadNotInterruptibleError,
261 ThreadManagementProjectionLoadError,
262 ThreadManagementProjectThreadsListError,
263 ThreadManagementDurableRunProjectionError,
264]);
265export type ThreadManagementError = typeof ThreadManagementError.Type;
266
267type ThreadManagementFailure = ThreadManagementError | OrchestratorV2Error;
268
269export interface ThreadManagementServiceShape {
270 readonly ensureLegacyTranscript: (
271 threadId: ThreadId,
272 ) => Effect.Effect<void, LegacyV1ThreadImportError>;
273 readonly dispatch: (
274 command: OrchestrationV2Command,
275 ) => Effect.Effect<OrchestratorV2DispatchResult, OrchestratorV2Error>;
276 readonly getThreadProjection: (
277 threadId: ThreadId,
278 ) => Effect.Effect<OrchestrationV2ThreadProjection, OrchestratorV2Error>;
279 readonly getCheckpointContext: OrchestratorV2["Service"]["getCheckpointContext"];
280 readonly getThreadSnapshot: OrchestratorV2["Service"]["getThreadSnapshot"];
281 readonly getThreadSnapshotWindow: OrchestratorV2["Service"]["getThreadSnapshotWindow"];
282 readonly getProjectThread: (input: {
283 readonly projectId: ProjectId;
284 readonly threadId: ThreadId;
285 }) => Effect.Effect<OrchestrationV2ThreadProjection, ThreadManagementError>;
286 readonly getShellSnapshot: (options?: {
287 readonly location?: "active" | "archive";
288 }) => Effect.Effect<OrchestrationV2ThreadShellSnapshot, OrchestratorV2Error>;
289 readonly getThreadShell: OrchestratorV2["Service"]["getThreadShell"];
290 readonly listProjectThreads: (input: {
291 readonly projectId: ProjectId;
292 readonly includeSubagents: boolean;
293 }) => Effect.Effect<ReadonlyArray<OrchestrationV2ThreadShell>, ThreadManagementError>;
294 readonly sendToThread: (
295 input: ThreadManagementSendInput,
296 ) => Effect.Effect<ThreadManagementSendResult, ThreadManagementFailure>;
297 readonly waitForThread: (
298 input: ThreadManagementWaitInput,
299 ) => Effect.Effect<ThreadManagementWaitResult, ThreadManagementError>;
300 readonly interruptThread: (
301 input: ThreadManagementInterruptInput,
302 ) => Effect.Effect<ThreadManagementInterruptResult, ThreadManagementFailure>;
303 readonly getThreadEventSequence: OrchestratorV2["Service"]["getThreadEventSequence"];
304 readonly streamStoredEvents: OrchestratorV2["Service"]["streamStoredEvents"];
305 readonly streamStoredEventsFrom: OrchestratorV2["Service"]["streamStoredEventsFrom"];
306 readonly streamDomainEvents: OrchestratorV2["Service"]["streamDomainEvents"];
307}
308
309export class ThreadManagementService extends Context.Service<
310 ThreadManagementService,
311 ThreadManagementServiceShape
312>()("t3/orchestration-v2/ThreadManagementService") {}
313
314export function isActiveRun(run: OrchestrationV2Run): boolean {
315 return (
316 run.status === "preparing" ||
317 run.status === "starting" ||
318 run.status === "running" ||
319 run.status === "waiting"
320 );
321}
322
323export function isTerminalRunStatus(
324 status: OrchestrationV2Run["status"],
325): status is ThreadManagementTerminalRunStatus {
326 return (
327 status === "completed" ||
328 status === "failed" ||
329 status === "cancelled" ||
330 status === "interrupted" ||
331 status === "rolled_back"
332 );
333}
334
335export function latestRun(
336 projection: OrchestrationV2ThreadProjection,
337): OrchestrationV2Run | undefined {
338 return projection.runs.toSorted((left, right) => right.ordinal - left.ordinal)[0];
339}
340
341export function latestActiveRun(
342 projection: OrchestrationV2ThreadProjection,
343): OrchestrationV2Run | undefined {
344 return projection.runs
345 .filter(isActiveRun)
346 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
347}
348
349function latestSteerableRun(
350 projection: OrchestrationV2ThreadProjection,
351): OrchestrationV2Run | undefined {
352 return projection.runs
353 .filter(
354 (run) =>
355 run.status === "running" &&
356 run.activeAttemptId !== null &&
357 projection.providerTurns.some(
358 (turn) => turn.runAttemptId === run.activeAttemptId && turn.status === "running",
359 ),
360 )
361 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
362}
363
364const make = Effect.gen(function* () {
365 const orchestrator = yield* OrchestratorV2;
366 const legacyImporter = yield* LegacyV1ThreadImporter;
367
368 const ensureLegacyTranscript = Effect.fn(
369 "orchestrationV2.threadManagement.ensureLegacyTranscript",
370 )(function* (threadId: ThreadId) {
371 yield* legacyImporter.ensureTranscript(threadId).pipe(
372 Effect.tapError((cause) =>
373 Effect.logWarning("Unable to hydrate migrated v1 thread transcript", {
374 threadId,
375 cause,
376 }),
377 ),
378 );
379 });
380
381 const ensureProjectionTranscript = (threadId: ThreadId) =>
382 ensureLegacyTranscript(threadId).pipe(
383 Effect.mapError(
384 (cause) =>
385 new OrchestratorProjectionError({
386 threadId,
387 cause,
388 }),
389 ),
390 );
391
392 const ensureCommandTranscripts = Effect.fn(
393 "orchestrationV2.threadManagement.ensureCommandTranscripts",
394 )(function* (command: OrchestrationV2Command) {
395 yield* Effect.forEach(
396 existingThreadIdsForCommand(command),
397 (threadId) => ensureLegacyTranscript(threadId),
398 { discard: true },
399 ).pipe(
400 Effect.mapError(
401 (cause) =>
402 new OrchestratorDispatchError({
403 commandId: command.commandId,
404 commandType: command.type,
405 cause,
406 }),
407 ),
408 );
409 });
410
411 const getThreadProjection: ThreadManagementServiceShape["getThreadProjection"] = (threadId) =>
412 ensureProjectionTranscript(threadId).pipe(
413 Effect.andThen(orchestrator.getThreadProjection(threadId)),
414 );
415
416 const getCheckpointContext: ThreadManagementServiceShape["getCheckpointContext"] = (threadId) =>
417 ensureProjectionTranscript(threadId).pipe(
418 Effect.andThen(orchestrator.getCheckpointContext(threadId)),
419 );
420
421 const getThreadSnapshot: ThreadManagementServiceShape["getThreadSnapshot"] = (threadId) =>
422 ensureProjectionTranscript(threadId).pipe(
423 Effect.andThen(orchestrator.getThreadSnapshot(threadId)),
424 );
425 const getThreadSnapshotWindow: ThreadManagementServiceShape["getThreadSnapshotWindow"] = (
426 threadId,
427 options,
428 ) =>
429 ensureProjectionTranscript(threadId).pipe(
430 Effect.andThen(orchestrator.getThreadSnapshotWindow(threadId, options)),
431 );
432
433 const dispatch: ThreadManagementServiceShape["dispatch"] = (command) =>
434 ensureCommandTranscripts(command).pipe(Effect.andThen(orchestrator.dispatch(command)));
435
436 const getProjectThread: ThreadManagementServiceShape["getProjectThread"] = (input) =>
437 getThreadProjection(input.threadId).pipe(
438 Effect.mapError(
439 (cause) =>
440 new ThreadManagementProjectionLoadError({
441 projectId: input.projectId,
442 threadId: input.threadId,
443 cause,
444 }),
445 ),
446 Effect.flatMap((projection) =>
447 projection.thread.projectId === input.projectId && projection.thread.deletedAt === null
448 ? Effect.succeed(projection)
449 : Effect.fail(
450 new ThreadManagementThreadNotFoundError({
451 projectId: input.projectId,
452 threadId: input.threadId,
453 }),
454 ),
455 ),
456 );
457
458 const listProjectThreads: ThreadManagementServiceShape["listProjectThreads"] = (input) =>
459 orchestrator.getShellSnapshot().pipe(
460 Effect.mapError(
461 (cause) =>
462 new ThreadManagementProjectThreadsListError({
463 projectId: input.projectId,
464 cause,
465 }),
466 ),
467 Effect.map((snapshot) =>
468 snapshot.threads
469 .filter((thread) => thread.projectId === input.projectId)
470 .filter(
471 (thread) =>
472 input.includeSubagents || thread.lineage.relationshipToParent !== "subagent",
473 )
474 .toSorted(
475 (left, right) =>
476 DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt) ||
477 right.id.localeCompare(left.id),
478 ),
479 ),
480 );
481
482 const sendToThread: ThreadManagementServiceShape["sendToThread"] = (input) =>
483 Effect.gen(function* () {
484 const target = yield* getProjectThread(input);
485 if (target.thread.archivedAt !== null) {
486 return yield* new ThreadManagementThreadArchivedError({
487 threadId: input.threadId,
488 });
489 }
490
491 const steerableRun = latestSteerableRun(target);
492 let dispatchMode: Extract<
493 OrchestrationV2Command,
494 { readonly type: "message.dispatch" }
495 >["dispatchMode"];
496 if (input.mode === "steer" || input.mode === "restart") {
497 if (steerableRun === undefined) {
498 return yield* new ThreadManagementNoSteerableRunError({
499 threadId: input.threadId,
500 mode: input.mode,
501 });
502 }
503 dispatchMode = {
504 type: input.mode === "steer" ? "steer_active" : "restart_active",
505 targetRunId: steerableRun.id,
506 };
507 } else if (input.mode === "auto" && steerableRun !== undefined) {
508 dispatchMode = { type: "steer_active", targetRunId: steerableRun.id };
509 } else {
510 dispatchMode = {
511 type: input.mode === "queue" ? "queue_after_active" : "start_immediately",
512 };
513 }
514
515 const dispatch = yield* orchestrator.dispatch({
516 type: "message.dispatch",
517 commandId: input.commandId,
518 threadId: input.threadId,
519 messageId: input.messageId,
520 ...(input.scheduledTaskId === undefined ? {} : { scheduledTaskId: input.scheduledTaskId }),
521 text: input.text,
522 attachments: input.attachments,
523 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
524 dispatchMode,
525 createdBy: input.createdBy,
526 creationSource: input.creationSource,
527 });
528 const projection = yield* getProjectThread(input);
529 const message = projection.messages.find((candidate) => candidate.id === input.messageId);
530 const run =
531 message?.runId === null || message?.runId === undefined
532 ? undefined
533 : projection.runs.find((candidate) => candidate.id === message.runId);
534 const turnItem =
535 projection.turnItems.find(
536 (
537 candidate,
538 ): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> =>
539 candidate.type === "user_message" && candidate.messageId === input.messageId,
540 ) ?? null;
541 // A queued message's user turn item is deliberately not emitted at
542 // dispatch time — it materializes when the queued turn actually starts,
543 // so it can map onto the provider turn. Every other dispatch mode still
544 // produces its turn item transactionally with the run.
545 if (
546 message === undefined ||
547 run === undefined ||
548 (turnItem === null && run.status !== "queued")
549 ) {
550 return yield* new ThreadManagementDurableRunProjectionError({
551 threadId: input.threadId,
552 messageId: input.messageId,
553 });
554 }
555 const delivery: ThreadManagementSendResult["delivery"] =
556 turnItem === null || turnItem.inputIntent === "queued_turn"
557 ? "queued"
558 : turnItem.inputIntent === "turn_start"
559 ? "started"
560 : input.mode === "restart"
561 ? "restarted"
562 : "steered";
563 return { dispatch, projection, message, run, turnItem, delivery };
564 });
565
566 const waitForThread: ThreadManagementServiceShape["waitForThread"] = (input) =>
567 Effect.gen(function* () {
568 const target = yield* getProjectThread(input);
569 const selectedRun =
570 input.runId === undefined
571 ? latestRun(target)
572 : target.runs.find((candidate) => candidate.id === input.runId);
573 if (input.runId !== undefined && selectedRun === undefined) {
574 return yield* new ThreadManagementRunNotFoundError({
575 threadId: input.threadId,
576 runId: input.runId,
577 });
578 }
579 if (selectedRun === undefined) {
580 return { threadId: input.threadId, run: null, timedOut: false };
581 }
582 if (isTerminalRunStatus(selectedRun.status)) {
583 return { threadId: input.threadId, run: selectedRun, timedOut: false };
584 }
585
586 const wait = Effect.gen(function* () {
587 while (true) {
588 const current = yield* getProjectThread(input);
589 const run = current.runs.find((candidate) => candidate.id === selectedRun.id);
590 if (run === undefined) {
591 return yield* new ThreadManagementRunNotFoundError({
592 threadId: input.threadId,
593 runId: selectedRun.id,
594 });
595 }
596 if (isTerminalRunStatus(run.status)) return run;
597 yield* Effect.sleep(Duration.millis(Math.max(1, input.pollIntervalMs ?? 250)));
598 }
599 }).pipe(Effect.timeoutOption(Duration.millis(Math.max(1, input.timeoutMs))));
600 const waited = yield* wait;
601 if (Option.isSome(waited)) {
602 return { threadId: input.threadId, run: waited.value, timedOut: false };
603 }
604 const current = yield* getProjectThread(input);
605 const run = current.runs.find((candidate) => candidate.id === selectedRun.id);
606 if (run === undefined) {
607 return yield* new ThreadManagementRunNotFoundError({
608 threadId: input.threadId,
609 runId: selectedRun.id,
610 });
611 }
612 // The run may have reached a terminal status while the timeout was
613 // winning the race; the final projection read decides what actually
614 // happened, so only a still-active run counts as timed out.
615 return { threadId: input.threadId, run, timedOut: !isTerminalRunStatus(run.status) };
616 });
617
618 const interruptThread: ThreadManagementServiceShape["interruptThread"] = (input) =>
619 Effect.gen(function* () {
620 const target = yield* getProjectThread(input);
621 const explicitRun =
622 input.runId === undefined
623 ? undefined
624 : target.runs.find((candidate) => candidate.id === input.runId);
625 if (input.runId !== undefined && explicitRun === undefined) {
626 return yield* new ThreadManagementRunNotFoundError({
627 threadId: input.threadId,
628 runId: input.runId,
629 });
630 }
631 if (explicitRun !== undefined && isTerminalRunStatus(explicitRun.status)) {
632 return {
633 type: "already_terminal",
634 run: explicitRun as OrchestrationV2Run & {
635 readonly status: ThreadManagementTerminalRunStatus;
636 },
637 } as const;
638 }
639 const interruptibleRun = latestActiveRun(target);
640 if (interruptibleRun === undefined) {
641 if (input.runId === undefined) {
642 return { type: "no_active_run" } as const;
643 }
644 return yield* new ThreadManagementThreadNotInterruptibleError({
645 threadId: input.threadId,
646 runId: input.runId,
647 });
648 }
649 if (input.runId !== undefined && interruptibleRun.id !== input.runId) {
650 return yield* new ThreadManagementThreadNotInterruptibleError({
651 threadId: input.threadId,
652 runId: input.runId,
653 });
654 }
655 const dispatch = yield* orchestrator.dispatch({
656 type: "run.interrupt",
657 commandId: input.commandId,
658 threadId: input.threadId,
659 runId: interruptibleRun.id,
660 ...(input.reason === undefined ? {} : { reason: input.reason }),
661 });
662 return { type: "interrupt_requested", run: interruptibleRun, dispatch } as const;
663 });
664
665 return ThreadManagementService.of({
666 ensureLegacyTranscript,
667 dispatch,
668 getThreadProjection,
669 getCheckpointContext,
670 getThreadSnapshot,
671 getThreadSnapshotWindow,
672 getProjectThread,
673 getShellSnapshot: orchestrator.getShellSnapshot,
674 getThreadShell: orchestrator.getThreadShell,
675 listProjectThreads,
676 sendToThread,
677 waitForThread,
678 interruptThread,
679 getThreadEventSequence: orchestrator.getThreadEventSequence,
680 streamStoredEvents: orchestrator.streamStoredEvents,
681 streamStoredEventsFrom: orchestrator.streamStoredEventsFrom,
682 streamDomainEvents: orchestrator.streamDomainEvents,
683 });
684});
685
686const legacyV1ThreadImporterNoopLayer = Layer.succeed(
687 LegacyV1ThreadImporter,
688 LegacyV1ThreadImporter.of({
689 pendingThreadCount: Effect.succeed(0),
690 reconcileShells: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
691 ensureTranscript: () => Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
692 importPendingTranscripts: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
693 }),
694);
695
696export const layer: Layer.Layer<ThreadManagementService, never, OrchestratorV2> = Layer.effect(
697 ThreadManagementService,
698 make,
699).pipe(Layer.provide(legacyV1ThreadImporterNoopLayer));
700
701export const layerWithLegacyImporter: Layer.Layer<
702 ThreadManagementService,
703 never,
704 LegacyV1ThreadImporter | OrchestratorV2
705> = Layer.effect(ThreadManagementService, make);