Open History to see the last commit
1import {
2 DEFAULT_MODEL,
3 DEFAULT_MODEL_BY_PROVIDER,
4 DEFAULT_PROVIDER_INTERACTION_MODE,
5 DEFAULT_RUNTIME_MODE,
6 isRuntimeModeAbove,
7 AgentSessionImportProjectChangedError,
8 AgentSessionImportProjectNotFoundError,
9 AgentSessionImportSource,
10 AgentSessionScanError,
11 AgentSessionSource,
12 EventId,
13 MessageId,
14 ProjectId,
15 ProviderDriverKind,
16 ThreadId,
17 TurnItemId,
18 type AgentSessionImportInput,
19 type AgentSessionImportResult,
20 type OrchestrationV2AppThread,
21 type OrchestrationV2ConversationMessage,
22 type OrchestrationV2DomainEvent,
23 type OrchestrationV2ProviderThread,
24 type OrchestrationV2TurnItem,
25} from "@t3tools/contracts";
26import { normalizeProjectPathForComparison } from "@t3tools/shared/path";
27import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
28import * as Context from "effect/Context";
29import * as DateTime from "effect/DateTime";
30import * as Effect from "effect/Effect";
31import * as Layer from "effect/Layer";
32import * as Option from "effect/Option";
33import * as Schema from "effect/Schema";
34import * as Stream from "effect/Stream";
35
36import * as EventSink from "../orchestration-v2/EventSink.ts";
37import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
38import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
39import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
40import * as ServerSettings from "../serverSettings.ts";
41import * as AgentSessionScanner from "./AgentSessionScanner.ts";
42import * as ProjectService from "./ProjectService.ts";
43
44const IMPORT_EVENT_PREFIX = "agent-session-import:v2";
45const CLAUDE_SESSION_ID_PATTERN =
46 /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
47const decodeImportedTranscriptPayload = Schema.decodeUnknownOption(
48 Schema.Struct({
49 cwd: Schema.optional(Schema.String),
50 importedTranscripts: Schema.optional(Schema.Array(AgentSessionImportSource)),
51 }),
52);
53
54class AgentSessionUnresumableSessionError extends Schema.TaggedError<AgentSessionUnresumableSessionError>()(
55 "AgentSessionUnresumableSessionError",
56 {
57 source: AgentSessionSource,
58 providerSessionId: Schema.String,
59 },
60) {
61 override get message(): string {
62 return `Session '${this.providerSessionId}' from '${this.source}' cannot be resumed.`;
63 }
64}
65
66class AgentSessionThreadProjectConflictError extends Schema.TaggedError<AgentSessionThreadProjectConflictError>()(
67 "AgentSessionThreadProjectConflictError",
68 {
69 threadId: ThreadId,
70 expectedProjectId: ProjectId,
71 actualProjectId: ProjectId,
72 },
73) {
74 override get message(): string {
75 return `Imported thread '${this.threadId}' belongs to project '${this.actualProjectId}', not '${this.expectedProjectId}'.`;
76 }
77}
78
79class AgentSessionThreadModifiedError extends Schema.TaggedError<AgentSessionThreadModifiedError>()(
80 "AgentSessionThreadModifiedError",
81 { threadId: ThreadId },
82) {
83 override get message(): string {
84 return `Imported thread '${this.threadId}' already contains non-imported activity.`;
85 }
86}
87
88function dateTime(value: string): DateTime.Utc {
89 return DateTime.makeUnsafe(value);
90}
91
92function messageEvents(input: {
93 readonly threadId: ThreadId;
94 readonly index: number;
95 readonly message: AgentSessionScanner.AgentSessionThreadMessage;
96}): ReadonlyArray<OrchestrationV2DomainEvent> {
97 const ordinal = input.index + 1;
98 const suffix = String(input.index).padStart(6, "0");
99 const messageId = MessageId.make(`${input.threadId}:${suffix}`);
100 const turnItemId = TurnItemId.make(
101 `${IMPORT_EVENT_PREFIX}:turn-item:${input.threadId}:${suffix}`,
102 );
103 const at = dateTime(input.message.createdAt);
104 const message: OrchestrationV2ConversationMessage = {
105 createdBy: input.message.role === "user" ? "user" : "agent",
106 creationSource: "server",
107 id: messageId,
108 threadId: input.threadId,
109 runId: null,
110 nodeId: null,
111 role: input.message.role,
112 text: input.message.text,
113 attachments: [],
114 streaming: false,
115 createdAt: at,
116 updatedAt: at,
117 };
118 const common = {
119 id: turnItemId,
120 threadId: input.threadId,
121 runId: null,
122 nodeId: null,
123 providerThreadId: null,
124 providerTurnId: null,
125 nativeItemRef: null,
126 parentItemId: null,
127 ordinal,
128 status: "completed" as const,
129 title: null,
130 startedAt: at,
131 completedAt: at,
132 updatedAt: at,
133 };
134 const turnItem: OrchestrationV2TurnItem =
135 input.message.role === "user"
136 ? {
137 ...common,
138 createdBy: "user",
139 creationSource: "server",
140 type: "user_message",
141 messageId,
142 inputIntent: "turn_start",
143 text: input.message.text,
144 attachments: [],
145 }
146 : {
147 ...common,
148 type: "assistant_message",
149 messageId,
150 text: input.message.text,
151 streaming: false,
152 };
153 return [
154 {
155 id: EventId.make(`${IMPORT_EVENT_PREFIX}:message:${input.threadId}:${suffix}`),
156 type: "message.updated",
157 threadId: input.threadId,
158 occurredAt: at,
159 payload: message,
160 },
161 {
162 id: EventId.make(`${IMPORT_EVENT_PREFIX}:turn-item:${input.threadId}:${suffix}`),
163 type: "turn-item.updated",
164 threadId: input.threadId,
165 occurredAt: at,
166 payload: turnItem,
167 },
168 ];
169}
170
171const make = Effect.gen(function* () {
172 const scanner = yield* AgentSessionScanner.AgentSessionScanner;
173 const orchestrator = yield* Orchestrator.OrchestratorV2;
174 const projects = yield* ProjectService.ProjectService;
175 const eventSink = yield* EventSink.EventSinkV2;
176 const idAllocator = yield* IdAllocator.IdAllocatorV2;
177 const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
178 const settingsService = yield* ServerSettings.ServerSettingsService;
179 const ceiling = settingsService.managedPolicy?.limits?.maxRuntimeMode;
180 const importRecentAgentThreads = Effect.fn("importRecentAgentThreadsV2")(function* (
181 input: AgentSessionImportInput,
182 ) {
183 const project = yield* projects.getById(input.projectId).pipe(
184 Effect.mapError((cause) => new AgentSessionScanError({ operation: "read-projects", cause })),
185 Effect.flatMap(
186 Option.match({
187 onNone: () =>
188 Effect.fail(new AgentSessionImportProjectNotFoundError({ projectId: input.projectId })),
189 onSome: Effect.succeed,
190 }),
191 ),
192 );
193 if (
194 input.expectedWorkspaceRoot !== undefined &&
195 normalizeProjectPathForComparison(project.workspaceRoot) !==
196 normalizeProjectPathForComparison(input.expectedWorkspaceRoot)
197 ) {
198 return yield* new AgentSessionImportProjectChangedError({ projectId: input.projectId });
199 }
200 // Imports run in full access, except under a policy ceiling: then in the project's default,
201 // which the policy keeps under it, so imported threads never sit above the ceiling.
202 const runtimeMode =
203 ceiling === undefined
204 ? DEFAULT_RUNTIME_MODE
205 : yield* settingsService.getSettings.pipe(
206 Effect.mapError(
207 (cause) => new AgentSessionScanError({ operation: "read-settings", cause }),
208 ),
209 Effect.map((settings) => {
210 const mode = resolveProjectSettings(settings, input.projectId, project).settings
211 .defaultRuntimeMode;
212 return isRuntimeModeAbove(mode, ceiling) ? ceiling : mode;
213 }),
214 );
215 const runtimeRows = yield* runtimes
216 .list()
217 .pipe(
218 Effect.mapError(
219 (cause) => new AgentSessionScanError({ operation: "read-projects", cause }),
220 ),
221 );
222 const completedSources = runtimeRows.flatMap((runtime) => {
223 const payload = decodeImportedTranscriptPayload(runtime.runtimePayload);
224 if (
225 Option.isNone(payload) ||
226 payload.value.cwd === undefined ||
227 normalizeProjectPathForComparison(payload.value.cwd) !==
228 normalizeProjectPathForComparison(project.workspaceRoot)
229 ) {
230 return [];
231 }
232 return payload.value.importedTranscripts ?? [];
233 });
234 const outcomes = scanner.recentThreads(project.workspaceRoot, completedSources);
235 const importedThreadIds = new Set<ThreadId>();
236 let importedCount = 0;
237 let skippedCount = 0;
238
239 yield* Stream.runForEach(outcomes, (outcome) =>
240 Effect.gen(function* () {
241 if (outcome._tag === "Skipped") {
242 skippedCount += 1;
243 return;
244 }
245 const source = outcome.source;
246 const threadId = ThreadId.make(
247 `import:${source.providerInstanceId}:${source.providerSessionId}`,
248 );
249 if (outcome._tag === "AlreadyImported") {
250 importedThreadIds.add(threadId);
251 importedCount += 1;
252 return;
253 }
254 if (outcome._tag === "Duplicate") {
255 if (importedThreadIds.has(threadId)) {
256 yield* runtimes.recordImportedTranscript({ threadId, source }).pipe(Effect.ignore);
257 }
258 return;
259 }
260
261 const imported = yield* Effect.gen(function* () {
262 const thread = outcome.thread;
263 if (
264 thread.source === "claudeAgent" &&
265 !CLAUDE_SESSION_ID_PATTERN.test(thread.providerSessionId)
266 ) {
267 return yield* new AgentSessionUnresumableSessionError({
268 source: thread.source,
269 providerSessionId: thread.providerSessionId,
270 });
271 }
272 const driver = ProviderDriverKind.make(thread.source);
273 // Pi resumes by session file path; its session UUID only names the thread.
274 const nativeThreadId =
275 thread.source === "pi" ? source.filePath : thread.providerSessionId;
276 const persistRuntime = runtimes.upsert(
277 {
278 threadId,
279 providerName: driver,
280 providerInstanceId: thread.providerInstanceId,
281 adapterKey: driver,
282 runtimeMode,
283 status: "stopped",
284 lastSeenAt: thread.updatedAt,
285 resumeCursor:
286 thread.source === "claudeAgent"
287 ? { threadId, resume: thread.providerSessionId }
288 : { threadId: nativeThreadId },
289 runtimePayload: { cwd: project.workspaceRoot },
290 },
291 { onConflict: "ignore" },
292 );
293 const existing = yield* Effect.option(orchestrator.getThreadRecords(threadId, []));
294 if (Option.isSome(existing)) {
295 if (existing.value.thread.projectId !== input.projectId) {
296 return yield* new AgentSessionThreadProjectConflictError({
297 threadId,
298 expectedProjectId: input.projectId,
299 actualProjectId: existing.value.thread.projectId,
300 });
301 }
302 if (existing.value.thread.historyOrigin !== "v1_import") {
303 return yield* new AgentSessionThreadModifiedError({ threadId });
304 }
305 yield* persistRuntime;
306 yield* runtimes.recordImportedTranscript({ threadId, source });
307 return true;
308 }
309
310 const model = thread.model ?? DEFAULT_MODEL_BY_PROVIDER[driver] ?? DEFAULT_MODEL;
311 const providerThreadId = idAllocator.derive.providerThread({
312 driver,
313 providerInstanceId: thread.providerInstanceId,
314 nativeThreadId,
315 });
316 const createdAt = dateTime(thread.createdAt);
317 const updatedAt = dateTime(thread.updatedAt);
318 const appThread: OrchestrationV2AppThread = {
319 createdBy: "system",
320 creationSource: "server",
321 id: threadId,
322 projectId: input.projectId,
323 title: thread.title.trim() === "" ? "Untitled thread" : thread.title,
324 providerInstanceId: thread.providerInstanceId,
325 modelSelection: { instanceId: thread.providerInstanceId, model },
326 runtimeMode,
327 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
328 branch: null,
329 worktreePath: null,
330 linkedPullRequest: null,
331 branchPullRequest: null,
332 activeProviderThreadId: providerThreadId,
333 historyOrigin: "v1_import",
334 lineage: {
335 parentThreadId: null,
336 relationshipToParent: null,
337 rootThreadId: threadId,
338 },
339 forkedFrom: null,
340 createdAt,
341 updatedAt,
342 archivedAt: null,
343 settledOverride: "settled",
344 settledAt: updatedAt,
345 unsettledAt: null,
346 snoozedUntil: null,
347 snoozedAt: null,
348 pinnedAt: null,
349 pinOrderKey: null,
350 activeOrderKey: null,
351 lastVisitedAt: null,
352 deletedAt: null,
353 };
354 const providerThread: OrchestrationV2ProviderThread = {
355 id: providerThreadId,
356 driver,
357 providerInstanceId: thread.providerInstanceId,
358 providerSessionId: null,
359 appThreadId: threadId,
360 ownerNodeId: null,
361 nativeThreadRef: {
362 driver,
363 nativeId: nativeThreadId,
364 strength: "strong",
365 },
366 nativeConversationHeadRef: null,
367 status: "idle",
368 firstRunOrdinal: null,
369 lastRunOrdinal: null,
370 handoffIds: [],
371 forkedFrom: null,
372 pendingBackgroundTasks: [],
373 createdAt,
374 updatedAt,
375 };
376
377 const committed = yield* eventSink.write({
378 unlessNativeThreadOwned: providerThread,
379 events: [
380 {
381 id: EventId.make(`${IMPORT_EVENT_PREFIX}:thread:${threadId}:created`),
382 type: "thread.created",
383 threadId,
384 providerInstanceId: thread.providerInstanceId,
385 occurredAt: createdAt,
386 payload: appThread,
387 },
388 ...(thread.omittedMessageCount > 0
389 ? [
390 {
391 id: EventId.make(`${IMPORT_EVENT_PREFIX}:history-truncated:${threadId}`),
392 type: "turn-item.updated" as const,
393 threadId,
394 occurredAt: createdAt,
395 payload: {
396 id: TurnItemId.make(`${IMPORT_EVENT_PREFIX}:history-truncated:${threadId}`),
397 threadId,
398 runId: null,
399 nodeId: null,
400 providerThreadId: null,
401 providerTurnId: null,
402 nativeItemRef: null,
403 parentItemId: null,
404 ordinal: 0,
405 status: "completed" as const,
406 title: null,
407 startedAt: createdAt,
408 completedAt: createdAt,
409 updatedAt: createdAt,
410 type: "system_notice" as const,
411 message: `${thread.omittedMessageCount} earlier ${thread.omittedMessageCount === 1 ? "message was" : "messages were"} not imported. This thread keeps the first user message and the most recent history. The original session transcript is unchanged.`,
412 },
413 },
414 ]
415 : []),
416 ...thread.messages.flatMap((message, index) =>
417 messageEvents({ threadId, index, message }),
418 ),
419 {
420 id: EventId.make(`${IMPORT_EVENT_PREFIX}:provider-thread:${providerThreadId}`),
421 type: "provider-thread.updated",
422 threadId,
423 driver,
424 providerInstanceId: thread.providerInstanceId,
425 occurredAt: updatedAt,
426 payload: providerThread,
427 },
428 ],
429 });
430 if (committed.length === 0) return null;
431 yield* persistRuntime;
432 yield* runtimes.recordImportedTranscript({ threadId, source });
433 return true;
434 }).pipe(
435 Effect.catch((cause) =>
436 Effect.logWarning("Could not import an agent session", {
437 provider: outcome.thread.source,
438 sessionId: outcome.thread.providerSessionId,
439 cause,
440 }).pipe(Effect.as(false)),
441 ),
442 );
443 if (imported === true) {
444 importedThreadIds.add(threadId);
445 importedCount += 1;
446 } else if (imported === false) {
447 skippedCount += 1;
448 }
449 }),
450 );
451
452 return { importedCount, skippedCount } satisfies AgentSessionImportResult;
453 });
454
455 return { importRecentAgentThreads };
456});
457
458type AgentSessionImporterShape = Effect.Success<typeof make>;
459
460export class AgentSessionImporter extends Context.Service<
461 AgentSessionImporter,
462 AgentSessionImporterShape
463>()("t3/project/AgentSessionImporter") {}
464
465export const layer = Layer.effect(AgentSessionImporter, make);