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

AgentSessionImporter.ts

601 lines22.5 KB

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 AgentSessionScanError,
10 AgentSessionSource,
11 EventId,
12 MessageId,
13 ProjectId,
14 ProviderDriverKind,
15 ThreadId,
16 TurnItemId,
17 type AgentSessionImportInput,
18 type AgentSessionImportResult,
19 type OrchestrationV2AppThread,
20 type OrchestrationV2ConversationMessage,
21 type OrchestrationV2DomainEvent,
22 type OrchestrationV2ProviderThread,
23 type OrchestrationV2TurnItem,
24} from "@t3tools/contracts";
25import { normalizeProjectPathForComparison } from "@t3tools/shared/path";
26import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
27import * as Context from "effect/Context";
28import * as DateTime from "effect/DateTime";
29import * as Effect from "effect/Effect";
30import * as Layer from "effect/Layer";
31import * as Option from "effect/Option";
32import * as Schema from "effect/Schema";
33import * as Stream from "effect/Stream";
34​
35import * as EventSink from "../orchestration-v2/EventSink.ts";
36import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
37import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
38import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
39import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts";
40import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
41import * as ServerSettings from "../serverSettings.ts";
42import * as AgentSessionScanner from "./AgentSessionScanner.ts";
43import * as ProjectService from "./ProjectService.ts";
44​
45const IMPORT_EVENT_PREFIX = "agent-session-import:v2";
46const CLAUDE_SESSION_ID_PATTERN =
47 /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
48​
49class AgentSessionUnresumableSessionError extends Schema.TaggedError<AgentSessionUnresumableSessionError>()(
50 "AgentSessionUnresumableSessionError",
51 {
52 source: AgentSessionSource,
53 providerSessionId: Schema.String,
54 },
55) {
56 override get message(): string {
57 return `Session '${this.providerSessionId}' from '${this.source}' cannot be resumed.`;
58 }
60​
61class AgentSessionThreadProjectConflictError extends Schema.TaggedError<AgentSessionThreadProjectConflictError>()(
62 "AgentSessionThreadProjectConflictError",
63 {
64 threadId: ThreadId,
65 expectedProjectId: ProjectId,
66 actualProjectId: ProjectId,
67 },
68) {
69 override get message(): string {
70 return `Imported thread '${this.threadId}' belongs to project '${this.actualProjectId}', not '${this.expectedProjectId}'.`;
71 }
73​
74class AgentSessionThreadModifiedError extends Schema.TaggedError<AgentSessionThreadModifiedError>()(
75 "AgentSessionThreadModifiedError",
76 { threadId: ThreadId },
77) {
78 override get message(): string {
79 return `Imported thread '${this.threadId}' already contains non-imported activity.`;
80 }
82​
83// ACP imports read the history while holding the session-mutation lock, and an agent can
84// leave session/resume or initialize unanswered. Longer than session/load's own deadline.
85const NATIVE_HISTORY_READ_TIMEOUT = "2 minutes";
86​
87/**
88 * Whether a thread bound to a native session still lacks its native history.
89 * Once a turn has run, the native session also holds that turn's messages, so
90 * its history can no longer be imported as run-less items.
91 */
92export function isNativeHistoryPending(input: {
93 readonly historyOrigin: OrchestrationV2AppThread["historyOrigin"];
94 readonly hasRun: boolean;
95}): boolean {
96 return input.historyOrigin !== "v1_import" && !input.hasRun;
98​
99function dateTime(value: string): DateTime.Utc {
100 return DateTime.makeUnsafe(value);
102​
103type HistoryMessage = Omit<AgentSessionScanner.AgentSessionThreadMessage, "role"> & {
104 readonly role: AgentSessionScanner.AgentSessionThreadMessage["role"] | "reasoning";
105};
106​
107function messageEvents(input: {
108 readonly threadId: ThreadId;
109 readonly index: number;
110 readonly message: HistoryMessage;
111}): ReadonlyArray<OrchestrationV2DomainEvent> {
112 const ordinal = input.index + 1;
113 const suffix = String(input.index).padStart(6, "0");
114 const messageId = MessageId.make(`${input.threadId}:${suffix}`);
115 const turnItemId = TurnItemId.make(
116 `${IMPORT_EVENT_PREFIX}:turn-item:${input.threadId}:${suffix}`,
117 );
118 const at = dateTime(input.message.createdAt);
119 const common = {
120 id: turnItemId,
121 threadId: input.threadId,
122 runId: null,
123 nodeId: null,
124 providerThreadId: null,
125 providerTurnId: null,
126 nativeItemRef: null,
127 parentItemId: null,
128 ordinal,
129 status: "completed" as const,
130 title: null,
131 startedAt: at,
132 completedAt: at,
133 updatedAt: at,
134 };
135 const turnItemEvent = (payload: OrchestrationV2TurnItem): OrchestrationV2DomainEvent => ({
136 id: EventId.make(turnItemId),
137 type: "turn-item.updated",
138 threadId: input.threadId,
139 occurredAt: at,
140 payload,
141 });
142 if (input.message.role === "reasoning") {
143 return [
144 turnItemEvent({ ...common, type: "reasoning", text: input.message.text, streaming: false }),
145 ];
146 }
147 const message: OrchestrationV2ConversationMessage = {
148 createdBy: input.message.role === "user" ? "user" : "agent",
149 creationSource: "server",
150 id: messageId,
151 threadId: input.threadId,
152 runId: null,
153 nodeId: null,
154 role: input.message.role,
155 text: input.message.text,
156 attachments: [],
157 streaming: false,
158 createdAt: at,
159 updatedAt: at,
160 };
161 const turnItem: OrchestrationV2TurnItem =
162 input.message.role === "user"
163 ? {
164 ...common,
165 createdBy: "user",
166 creationSource: "server",
167 type: "user_message",
168 messageId,
169 inputIntent: "turn_start",
170 text: input.message.text,
171 attachments: [],
172 }
173 : {
174 ...common,
175 type: "assistant_message",
176 messageId,
177 text: input.message.text,
178 streaming: false,
179 };
180 return [
181 {
182 id: EventId.make(`${IMPORT_EVENT_PREFIX}:message:${input.threadId}:${suffix}`),
183 type: "message.updated",
184 threadId: input.threadId,
185 occurredAt: at,
186 payload: message,
187 },
188 turnItemEvent(turnItem),
189 ];
191​
192const make = Effect.gen(function* () {
193 const scanner = yield* AgentSessionScanner.AgentSessionScanner;
194 const orchestrator = yield* Orchestrator.OrchestratorV2;
195 const projects = yield* ProjectService.ProjectService;
196 const eventSink = yield* EventSink.EventSinkV2;
197 const idAllocator = yield* IdAllocator.IdAllocatorV2;
198 const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
199 const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistryV2;
200 const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor;
201 const settingsService = yield* ServerSettings.ServerSettingsService;
202 const ceiling = settingsService.managedPolicy?.limits?.maxRuntimeMode;
203 const importRecentAgentThreads = Effect.fn("importRecentAgentThreadsV2")(function* (
204 input: AgentSessionImportInput,
205 ) {
206 const project = yield* projects.getById(input.projectId).pipe(
207 Effect.mapError((cause) => new AgentSessionScanError({ operation: "read-projects", cause })),
208 Effect.flatMap(
209 Option.match({
210 onNone: () =>
211 Effect.fail(new AgentSessionImportProjectNotFoundError({ projectId: input.projectId })),
212 onSome: Effect.succeed,
213 }),
214 ),
215 );
216 if (
217 input.expectedWorkspaceRoot !== undefined &&
218 normalizeProjectPathForComparison(project.workspaceRoot) !==
219 normalizeProjectPathForComparison(input.expectedWorkspaceRoot)
220 ) {
221 return yield* new AgentSessionImportProjectChangedError({ projectId: input.projectId });
222 }
223 // Imports run in full access, except under a policy ceiling: then in the project's default,
224 // which the policy keeps under it, so imported threads never sit above the ceiling.
225 const runtimeMode =
226 ceiling === undefined
227 ? DEFAULT_RUNTIME_MODE
228 : yield* settingsService.getSettings.pipe(
229 Effect.mapError(
230 (cause) => new AgentSessionScanError({ operation: "read-settings", cause }),
231 ),
232 Effect.map((settings) => {
233 const mode = resolveProjectSettings(settings, input.projectId, project).settings
234 .defaultRuntimeMode;
235 return isRuntimeModeAbove(mode, ceiling) ? ceiling : mode;
236 }),
237 );
238 const runtimeRows = yield* runtimes
239 .list()
240 .pipe(
241 Effect.mapError(
242 (cause) => new AgentSessionScanError({ operation: "read-projects", cause }),
243 ),
244 );
245 const completedSources = runtimeRows.flatMap((runtime) => {
246 const payload = AgentSessionScanner.decodeImportedTranscriptPayload(runtime.runtimePayload);
247 if (
248 Option.isNone(payload) ||
249 payload.value.cwd === undefined ||
250 normalizeProjectPathForComparison(payload.value.cwd) !==
251 normalizeProjectPathForComparison(project.workspaceRoot)
252 ) {
253 return [];
254 }
255 return payload.value.importedTranscripts ?? [];
256 });
257 const outcomes = scanner.recentThreads(project.workspaceRoot, completedSources);
258 const importedThreadIds = new Set<ThreadId>();
259 let importedCount = 0;
260 let skippedCount = 0;
261​
262 yield* Stream.runForEach(outcomes, (outcome) =>
263 Effect.gen(function* () {
264 if (outcome._tag === "Skipped") {
265 skippedCount += 1;
266 return;
267 }
268 const source = outcome.source;
269 const threadId = ThreadId.make(
270 `import:${source.providerInstanceId}:${source.providerSessionId}`,
271 );
272 if (outcome._tag === "AlreadyImported") {
273 importedThreadIds.add(threadId);
274 importedCount += 1;
275 return;
276 }
277 if (outcome._tag === "Duplicate") {
278 if (importedThreadIds.has(threadId)) {
279 yield* runtimes.recordImportedTranscript({ threadId, source }).pipe(Effect.ignore);
280 }
281 return;
282 }
283​
284 const imported = yield* Effect.gen(function* () {
285 const thread = outcome.thread;
286 if (
287 thread.source === "claudeAgent" &&
288 !CLAUDE_SESSION_ID_PATTERN.test(thread.providerSessionId)
289 ) {
290 return yield* new AgentSessionUnresumableSessionError({
291 source: thread.source,
292 providerSessionId: thread.providerSessionId,
293 });
294 }
295 const driver = ProviderDriverKind.make(thread.source);
296 // Pi resumes by session file path; its session UUID only names the thread.
297 const nativeThreadId =
298 thread.source === "pi" ? source.filePath : thread.providerSessionId;
299 const persistRuntime = runtimes.upsert(
300 {
301 threadId,
302 providerName: driver,
303 providerInstanceId: thread.providerInstanceId,
304 adapterKey: driver,
305 runtimeMode,
306 status: "stopped",
307 lastSeenAt: thread.updatedAt,
308 resumeCursor:
309 thread.source === "claudeAgent"
310 ? { threadId, resume: thread.providerSessionId }
311 : { threadId: nativeThreadId },
312 runtimePayload: { cwd: outcome.worktree?.path ?? project.workspaceRoot },
313 },
314 { onConflict: "ignore" },
315 );
316 const existing = yield* Effect.option(
317 orchestrator.getThreadRecords(threadId, ["messages"]),
318 );
319 if (Option.isSome(existing)) {
320 if (existing.value.thread.projectId !== input.projectId) {
321 return yield* new AgentSessionThreadProjectConflictError({
322 threadId,
323 expectedProjectId: input.projectId,
324 actualProjectId: existing.value.thread.projectId,
325 });
326 }
327 if (existing.value.thread.historyOrigin !== "v1_import") {
328 return yield* new AgentSessionThreadModifiedError({ threadId });
329 }
330 // A transcript can change after the import, so record it only when the
331 // thread already holds exactly its messages.
332 const stored = existing.value.messages;
333 if (
334 stored.length !== thread.messages.length ||
335 stored.some(
336 (message, index) =>
337 message.role !== thread.messages[index]?.role ||
338 message.text !== thread.messages[index]?.text,
339 )
340 ) {
341 return false;
342 }
343 yield* persistRuntime;
344 yield* runtimes.recordImportedTranscript({ threadId, source });
345 return true;
346 }
347​
348 const model = thread.model ?? DEFAULT_MODEL_BY_PROVIDER[driver] ?? DEFAULT_MODEL;
349 const providerThreadId = idAllocator.derive.providerThread({
350 driver,
351 providerInstanceId: thread.providerInstanceId,
352 nativeThreadId,
353 });
354 const createdAt = dateTime(thread.createdAt);
355 const updatedAt = dateTime(thread.updatedAt);
356 const appThread: OrchestrationV2AppThread = {
357 createdBy: "system",
358 creationSource: "server",
359 id: threadId,
360 projectId: input.projectId,
361 title: thread.title.trim() === "" ? "Untitled thread" : thread.title,
362 providerInstanceId: thread.providerInstanceId,
363 modelSelection: { instanceId: thread.providerInstanceId, model },
364 runtimeMode,
365 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
366 branch: outcome.worktree?.branch ?? null,
367 worktreePath: outcome.worktree?.path ?? null,
368 linkedPullRequest: null,
369 branchPullRequest: null,
370 activeProviderThreadId: providerThreadId,
371 historyOrigin: "v1_import",
372 lineage: {
373 parentThreadId: null,
374 relationshipToParent: null,
375 rootThreadId: threadId,
376 },
377 forkedFrom: null,
378 createdAt,
379 updatedAt,
380 archivedAt: null,
381 settledOverride: "settled",
382 settledAt: updatedAt,
383 unsettledAt: null,
384 snoozedUntil: null,
385 snoozedAt: null,
386 pinnedAt: null,
387 pinOrderKey: null,
388 activeOrderKey: null,
389 lastVisitedAt: null,
390 deletedAt: null,
391 };
392 const providerThread: OrchestrationV2ProviderThread = {
393 id: providerThreadId,
394 driver,
395 providerInstanceId: thread.providerInstanceId,
396 providerSessionId: null,
397 appThreadId: threadId,
398 ownerNodeId: null,
399 nativeThreadRef: {
400 driver,
401 nativeId: nativeThreadId,
402 strength: "strong",
403 },
404 nativeConversationHeadRef: null,
405 status: "idle",
406 firstRunOrdinal: null,
407 lastRunOrdinal: null,
408 handoffIds: [],
409 forkedFrom: null,
410 pendingBackgroundTasks: [],
411 createdAt,
412 updatedAt,
413 };
414​
415 const committed = yield* eventSink.write({
416 unlessNativeThreadOwned: providerThread,
417 events: [
418 {
419 id: EventId.make(`${IMPORT_EVENT_PREFIX}:thread:${threadId}:created`),
420 type: "thread.created",
421 threadId,
422 providerInstanceId: thread.providerInstanceId,
423 occurredAt: createdAt,
424 payload: appThread,
425 },
426 ...(thread.omittedMessageCount > 0
427 ? [
428 {
429 id: EventId.make(`${IMPORT_EVENT_PREFIX}:history-truncated:${threadId}`),
430 type: "turn-item.updated" as const,
431 threadId,
432 occurredAt: createdAt,
433 payload: {
434 id: TurnItemId.make(`${IMPORT_EVENT_PREFIX}:history-truncated:${threadId}`),
435 threadId,
436 runId: null,
437 nodeId: null,
438 providerThreadId: null,
439 providerTurnId: null,
440 nativeItemRef: null,
441 parentItemId: null,
442 ordinal: 0,
443 status: "completed" as const,
444 title: null,
445 startedAt: createdAt,
446 completedAt: createdAt,
447 updatedAt: createdAt,
448 type: "system_notice" as const,
449 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.`,
450 },
451 },
452 ]
453 : []),
454 ...thread.messages.flatMap((message, index) =>
455 messageEvents({ threadId, index, message }),
456 ),
457 {
458 id: EventId.make(`${IMPORT_EVENT_PREFIX}:provider-thread:${providerThreadId}`),
459 type: "provider-thread.updated",
460 threadId,
461 driver,
462 providerInstanceId: thread.providerInstanceId,
463 occurredAt: updatedAt,
464 payload: providerThread,
465 },
466 ],
467 });
468 if (committed.length === 0) return null;
469 yield* persistRuntime;
470 yield* runtimes.recordImportedTranscript({ threadId, source });
471 return true;
472 }).pipe(
473 Effect.catch((cause) =>
474 Effect.logWarning("Could not import an agent session", {
475 provider: outcome.thread.source,
476 sessionId: outcome.thread.providerSessionId,
477 cause,
478 }).pipe(Effect.as(false)),
479 ),
480 );
481 if (imported === true) {
482 importedThreadIds.add(threadId);
483 importedCount += 1;
484 } else if (imported === false) {
485 skippedCount += 1;
486 }
487 }),
488 );
489​
490 return { importedCount, skippedCount } satisfies AgentSessionImportResult;
491 });
492​
493 /**
494 * Loading a native session replays its history only into the adapter's own
495 * snapshot, so copy that snapshot into the thread as run-less history. The
496 * `v1_import` origin keeps it in forks and marks the import done, so a call
497 * after a failed read repairs the thread and any later call does nothing.
498 */
499 const importNativeHistory = Effect.fn("importNativeHistoryV2")(function* (input: {
500 readonly threadId: ThreadId;
501 readonly workspaceRoot: string;
502 }) {
503 const pendingThread = Effect.map(
504 orchestrator.getThreadRecords(input.threadId, ["providerThreads", "runs"]),
505 (records) =>
506 isNativeHistoryPending({
507 historyOrigin: records.thread.historyOrigin,
508 hasRun: records.runs.length > 0,
509 })
510 ? records
511 : null,
512 );
513 // Thread commands write whole thread rows, so hold their lock from the
514 // re-read through the write to keep both this marker and their changes.
515 const commit = (messages: ReadonlyArray<HistoryMessage>) =>
516 threadCommands.withLock(
517 input.threadId,
518 Effect.gen(function* () {
519 const current = yield* pendingThread;
520 if (current === null) return 0;
521 yield* eventSink.write({
522 events: [
523 ...messages.flatMap((message, index) =>
524 messageEvents({ threadId: input.threadId, index, message }),
525 ),
526 {
527 id: EventId.make(`${IMPORT_EVENT_PREFIX}:thread:${input.threadId}:native-history`),
528 type: "thread.metadata-updated",
529 threadId: input.threadId,
530 providerInstanceId: current.thread.providerInstanceId,
531 occurredAt: yield* DateTime.now,
532 payload: { ...current.thread, historyOrigin: "v1_import" },
533 },
534 ],
535 });
536 return messages.length;
537 }),
538 );
539 const records = yield* pendingThread;
540 if (records === null) return 0;
541 const { thread, providerThreads } = records;
542 const providerThread = providerThreads.find(
543 (candidate) => candidate.appThreadId === input.threadId && candidate.nativeThreadRef !== null,
544 );
545 const nativeThreadId = providerThread?.nativeThreadRef?.nativeId;
546 if (providerThread === undefined || nativeThreadId == null) return 0;
547 const providerSessionId = yield* idAllocator.allocate.providerSession({
548 providerInstanceId: providerThread.providerInstanceId,
549 threadId: input.threadId,
550 });
551 // The registry admits this open against sign-in changes, like any other open.
552 const adapter = yield* registry.get(thread.modelSelection.instanceId);
553 const snapshot = yield* adapter
554 .openSession({
555 threadId: input.threadId,
556 providerSessionId,
557 modelSelection: thread.modelSelection,
558 runtimePolicy: {
559 runtimeMode: thread.runtimeMode,
560 interactionMode: thread.interactionMode,
561 cwd: thread.worktreePath ?? input.workspaceRoot,
562 },
563 initialNativeThreadId: nativeThreadId,
564 ...(providerThread.nativeMetadata?.itemIdentityVersion === undefined
565 ? {}
566 : {
567 initialProviderItemIdentityVersion: providerThread.nativeMetadata.itemIdentityVersion,
568 }),
569 })
570 .pipe(
571 Effect.flatMap((session) => session.readThreadSnapshot({ providerThread })),
572 Effect.timeout(NATIVE_HISTORY_READ_TIMEOUT),
573 Effect.scoped,
574 );
575 const reasoningIds = new Set(snapshot.reasoningMessageIds);
576 const messages = snapshot.messages.flatMap((message) =>
577 (message.role === "user" || message.role === "assistant") && message.text.trim() !== ""
578 ? [
579 {
580 role: reasoningIds.has(message.id) ? ("reasoning" as const) : message.role,
581 text: message.text,
582 createdAt: DateTime.formatIso(message.createdAt),
583 },
584 ]
585 : [],
586 );
587 // Loading the session can take a while, and the thread is usable meanwhile.
588 return yield* commit(messages);
589 });
590​
591 return { importRecentAgentThreads, importNativeHistory };
592});
593​
594type AgentSessionImporterShape = Effect.Success<typeof make>;
595​
596export class AgentSessionImporter extends Context.Service<
597 AgentSessionImporter,
598 AgentSessionImporterShape
599>()("t3/project/AgentSessionImporter") {}
600​
601export const layer = Layer.effect(AgentSessionImporter, make);