Open History to see the last commit
1import {
2 CommandId,
3 EventId,
4 threadMoveMessageId,
5 type OrchestrationV2AppThread,
6 type OrchestrationV2DomainEvent,
7 type OrchestrationV2LinkOrigin,
8 type OrchestratorMcpThreadImportInput,
9 type OrchestratorMcpThreadImportResult,
10 type ProviderInteractionMode,
11 ProjectId,
12 type RunId,
13 type RuntimeMode,
14 ThreadId,
15} from "@t3tools/contracts";
16import * as KeyedLock from "@t3tools/shared/KeyedLock";
17import * as Context from "effect/Context";
18import * as Digest from "effect/crypto/Digest";
19import * as DateTime from "effect/DateTime";
20import * as Effect from "effect/Effect";
21import * as Hex from "effect/encoding/Hex";
22import * as Layer from "effect/Layer";
23import * as Schema from "effect/Schema";
24
25import { DispatchModeLimit } from "./DispatchModeLimit.ts";
26import * as EventSink from "./EventSink.ts";
27import * as ImportedHistory from "./importedHistory.ts";
28import * as ThreadManagement from "./ThreadManagementService.ts";
29
30const IMPORT_EVENT_PREFIX = "thread-import:v1";
31
32/** The imported thread's events could not be written. */
33export class ThreadImportWriteError extends Schema.TaggedError<ThreadImportWriteError>()(
34 "ThreadImportWriteError",
35 { threadId: ThreadId, cause: Schema.Defect() },
36) {
37 override get message(): string {
38 return "The thread could not be imported.";
39 }
40}
41
42/** A retried import named another project than the one the thread landed in. */
43export class ThreadImportProjectMismatchError extends Schema.TaggedError<ThreadImportProjectMismatchError>()(
44 "ThreadImportProjectMismatchError",
45 { threadId: ThreadId, existingProjectId: ProjectId },
46) {
47 override get message(): string {
48 return `This handoff was already imported into another project (${this.existingProjectId}).`;
49 }
50}
51
52/** A retried import came over another link than the one that moved the thread here. */
53export class ThreadImportOtherLinkError extends Schema.TaggedError<ThreadImportOtherLinkError>()(
54 "ThreadImportOtherLinkError",
55 { threadId: ThreadId },
56) {
57 override get message(): string {
58 return "This handoff was already imported over another link.";
59 }
60}
61
62export type ThreadImportError =
63 | ThreadImportWriteError
64 | ThreadImportOtherLinkError
65 | ThreadImportProjectMismatchError;
66
67/** A checkout an import prepared for its thread. */
68export interface ImportedWorkspace {
69 readonly worktreePath: string;
70 readonly branch: string | null;
71 readonly undo: Effect.Effect<void>;
72}
73
74/**
75 * Creates a thread here from another environment's conversation. Its history is run-less and
76 * marked imported, so the first run gets it as context whatever the provider. Ids derive from
77 * the source thread and the handoff, so a retried import returns the first one's thread.
78 */
79export class ThreadImportService extends Context.Service<
80 ThreadImportService,
81 {
82 readonly importThread: <E = never>(
83 input: OrchestratorMcpThreadImportInput & {
84 readonly runtimeMode: RuntimeMode;
85 readonly interactionMode: ProviderInteractionMode;
86 readonly linkOrigin: OrchestrationV2LinkOrigin | undefined;
87 /** Prepares the thread's checkout, only when this import creates the thread. */
88 readonly workspace?: Effect.Effect<ImportedWorkspace, E>;
89 },
90 ) => Effect.Effect<OrchestratorMcpThreadImportResult, ThreadImportError | E>;
91 }
92>()("t3/orchestration-v2/ThreadImportService") {}
93
94const make = Effect.gen(function* () {
95 const sink = yield* EventSink.EventSinkV2;
96 const threads = yield* ThreadManagement.ThreadManagementService;
97 const crypto = yield* Digest.Digest;
98 const imports = yield* KeyedLock.make<ThreadId>();
99
100 /** The thread an import of `source` creates here, the same on every retry. */
101 const importedThreadId = (source: OrchestratorMcpThreadImportInput["source"]) =>
102 crypto
103 .digest(
104 Digest.sha256,
105 new TextEncoder().encode(
106 `${source.environmentId}\n${source.threadId}\n${source.handoffId}`,
107 ),
108 )
109 .pipe(
110 Effect.map((digest) => ThreadId.make(`thread:import:${Hex.encode(digest).slice(0, 32)}`)),
111 Effect.orDie,
112 );
113
114 const historyEvents = (
115 threadId: ThreadId,
116 messages: OrchestratorMcpThreadImportInput["messages"],
117 ): ReadonlyArray<OrchestrationV2DomainEvent> =>
118 messages.flatMap((message, index) =>
119 ImportedHistory.importedMessageEvents({
120 prefix: IMPORT_EVENT_PREFIX,
121 threadId,
122 index,
123 message,
124 }),
125 );
126
127 const importThread: ThreadImportService["Service"]["importThread"] = Effect.fn(
128 "ThreadImportService.importThread",
129 )(function* (input) {
130 const threadId = yield* importedThreadId(input.source);
131 const created = yield* imports.withLock(
132 threadId,
133 Effect.gen(function* () {
134 const existing = yield* threads
135 .getThreadShell(threadId)
136 .pipe(Effect.orElseSucceed(() => null));
137 let landed = existing;
138 if (existing === null) {
139 const workspace = input.workspace === undefined ? undefined : yield* input.workspace;
140 const now = yield* DateTime.now;
141 const thread: OrchestrationV2AppThread = {
142 createdBy: "agent",
143 creationSource: "mcp",
144 id: threadId,
145 projectId: input.projectId,
146 title: input.title,
147 providerInstanceId: input.modelSelection.instanceId,
148 modelSelection: input.modelSelection,
149 runtimeMode: input.runtimeMode,
150 interactionMode: input.interactionMode,
151 branch: workspace === undefined ? (input.branch ?? null) : workspace.branch,
152 worktreePath:
153 workspace === undefined ? (input.worktreePath ?? null) : workspace.worktreePath,
154 linkedPullRequest: null,
155 branchPullRequest: null,
156 activeProviderThreadId: null,
157 historyOrigin: "v1_import",
158 ...(input.linkOrigin === undefined ? {} : { linkOrigin: input.linkOrigin }),
159 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
160 forkedFrom: null,
161 createdAt: now,
162 updatedAt: now,
163 archivedAt: null,
164 settledOverride: null,
165 settledAt: null,
166 unsettledAt: null,
167 snoozedUntil: null,
168 snoozedAt: null,
169 pinnedAt: null,
170 pinOrderKey: null,
171 activeOrderKey: null,
172 lastVisitedAt: null,
173 deletedAt: null,
174 };
175 landed = yield* sink
176 .write({
177 events: [
178 {
179 id: EventId.make(`${IMPORT_EVENT_PREFIX}:thread:${threadId}:created`),
180 type: "thread.created",
181 threadId,
182 providerInstanceId: input.modelSelection.instanceId,
183 occurredAt: now,
184 payload: thread,
185 },
186 ...historyEvents(threadId, input.messages),
187 ],
188 })
189 .pipe(
190 Effect.as(null),
191 // A concurrent retry may have written the same events first.
192 Effect.catchCause((cause) =>
193 threads.getThreadShell(threadId).pipe(
194 Effect.orElseSucceed(() => null),
195 Effect.filterOrElse(
196 (raced): raced is NonNullable<typeof raced> => raced !== null,
197 () => Effect.failCause(cause),
198 ),
199 ),
200 ),
201 // The checkout was made for a thread that now does not exist.
202 Effect.tapError(() => workspace?.undo ?? Effect.void),
203 // An interrupt can land after the write committed; the thread then owns the checkout.
204 Effect.onInterrupt(() =>
205 threads.getThreadShell(threadId).pipe(
206 Effect.flatMap((written) =>
207 written === null ? (workspace?.undo ?? Effect.void) : Effect.void,
208 ),
209 // A lookup that fails says nothing about the write: keep the checkout.
210 Effect.ignore,
211 ),
212 ),
213 Effect.mapError((cause) => new ThreadImportWriteError({ threadId, cause })),
214 );
215 }
216 // A retry, or the loser of a race, continues the thread only as the import that made it.
217 if (landed !== null) {
218 if (landed.projectId !== input.projectId) {
219 return yield* new ThreadImportProjectMismatchError({
220 threadId,
221 existingProjectId: landed.projectId,
222 });
223 }
224 if (landed.linkOrigin?.sessionId !== input.linkOrigin?.sessionId) {
225 return yield* new ThreadImportOtherLinkError({ threadId });
226 }
227 }
228 return landed === null;
229 }),
230 );
231 const runId = yield* startContinuation(threadId, input);
232 return { threadId, projectId: input.projectId, created, runId };
233 });
234
235 /** Sends the continuation prompt once; a retry replays the same command. */
236 const startContinuation = (
237 threadId: ThreadId,
238 input: Parameters<ThreadImportService["Service"]["importThread"]>[0],
239 ): Effect.Effect<RunId | null> =>
240 input.continuationPrompt === undefined
241 ? Effect.succeed(null)
242 : threads
243 .dispatch({
244 type: "message.dispatch",
245 commandId: CommandId.make(`command:thread-import:${threadId}:continue`),
246 threadId,
247 messageId: threadMoveMessageId(threadId),
248 // Names where the thread came from; clients draw this message as the move's divider.
249 linkedSender: {
250 environmentId: input.source.environmentId,
251 threadId: input.source.threadId,
252 title: input.title,
253 },
254 text: input.continuationPrompt,
255 attachments: [],
256 modelSelection: input.modelSelection,
257 dispatchMode: { type: "start_immediately" },
258 createdBy: "agent",
259 creationSource: "mcp",
260 })
261 .pipe(
262 // The user there may have raised the thread's modes since it was imported.
263 Effect.provideService(DispatchModeLimit, {
264 runtimeMode: input.runtimeMode,
265 interactionMode: input.interactionMode,
266 }),
267 Effect.flatMap(() => threads.getThreadRecords(threadId, ["runs"])),
268 Effect.map(
269 (records) =>
270 records.runs.find((run) => run.userMessageId === threadMoveMessageId(threadId))
271 ?.id ?? null,
272 ),
273 // The thread already exists. Confirm the import even if its first run could not start.
274 Effect.catch((cause) =>
275 Effect.logWarning("thread-import.continuation-failed", { threadId, cause }).pipe(
276 Effect.as(null),
277 ),
278 ),
279 );
280
281 return ThreadImportService.of({ importThread });
282});
283
284export const layer = Layer.effect(ThreadImportService, make);