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