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

AgentSessionImporter.ts

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