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

AgentSessionImporter.ts

414 lines14.2 KB

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