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

AgentSessionImporter.ts

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