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

AgentSessionImporter.ts

297 lines10.6 KB

1import {
2 CommandId,
3 DEFAULT_MODEL,
4 DEFAULT_MODEL_BY_PROVIDER,
5 DEFAULT_PROVIDER_INTERACTION_MODE,
6 DEFAULT_RUNTIME_MODE,
7 AgentSessionImportProjectChangedError,
8 AgentSessionImportProjectNotFoundError,
9 AgentSessionSource,
10 AgentSessionScanError,
11 isImportedAgentSessionMessageId,
12 MessageId,
13 ProjectId,
14 ProviderDriverKind,
15 ThreadId,
16 type AgentSessionImportInput,
17 type AgentSessionImportResult,
18 type OrchestrationThread,
19} from "@t3tools/contracts";
20import { normalizeProjectPathForComparison } from "@t3tools/shared/path";
21import * as Crypto from "effect/Crypto";
22import * as Effect from "effect/Effect";
23import * as Option from "effect/Option";
24import * as Schema from "effect/Schema";
25import * as Stream from "effect/Stream";
26​
27import * as OrchestrationEngine from "../orchestration/Services/OrchestrationEngine.ts";
28import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
29import * as ProviderSessionDirectory from "../provider/Services/ProviderSessionDirectory.ts";
30import * as AgentSessionScanner from "./AgentSessionScanner.ts";
31​
32const CLAUDE_SESSION_ID_PATTERN =
33 /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
34​
35class AgentSessionUnresumableSessionError extends Schema.TaggedErrorClass<AgentSessionUnresumableSessionError>()(
36 "AgentSessionUnresumableSessionError",
37 {
38 source: AgentSessionSource,
39 providerSessionId: Schema.String,
40 },
41) {
42 override get message(): string {
43 return `Session '${this.providerSessionId}' from '${this.source}' cannot be resumed.`;
44 }
46​
47class AgentSessionThreadProjectConflictError extends Schema.TaggedErrorClass<AgentSessionThreadProjectConflictError>()(
48 "AgentSessionThreadProjectConflictError",
49 {
50 threadId: ThreadId,
51 expectedProjectId: ProjectId,
52 actualProjectId: ProjectId,
53 },
54) {
55 override get message(): string {
56 return `Imported thread '${this.threadId}' belongs to project '${this.actualProjectId}', not '${this.expectedProjectId}'.`;
57 }
59​
60class AgentSessionThreadModifiedError extends Schema.TaggedErrorClass<AgentSessionThreadModifiedError>()(
61 "AgentSessionThreadModifiedError",
62 { threadId: ThreadId },
63) {
64 override get message(): string {
65 return `Imported thread '${this.threadId}' changed before its history import completed.`;
66 }
68​
69function hasImportedHistory(thread: OrchestrationThread): boolean {
70 return thread.messages.some((message) => isImportedAgentSessionMessageId(message.id));
72​
73function hasImportBlockingActivity(
74 thread: OrchestrationThread,
75 importedHistoryPresent: boolean,
76): boolean {
77 return (
78 thread.archivedAt !== null ||
79 thread.deletedAt !== null ||
80 thread.latestTurn !== null ||
81 thread.session !== null ||
82 thread.messages.some((message) => !isImportedAgentSessionMessageId(message.id)) ||
83 thread.proposedPlans.length > 0 ||
84 thread.activities.length > 0 ||
85 thread.checkpoints.length > 0 ||
86 thread.snoozedUntil != null ||
87 thread.snoozedAt != null ||
88 thread.pinnedAt != null ||
89 thread.pinOrderKey != null ||
90 thread.titleRegeneration != null ||
91 thread.linkedPullRequest != null ||
92 thread.unsettledAt != null ||
93 (importedHistoryPresent
94 ? thread.settledOverride !== "settled"
95 : thread.settledOverride !== null || thread.settledAt !== null)
96 );
98​
99/** Import recent transcript text and persist the cursor needed to resume its provider session. */
100export const importRecentAgentThreads = Effect.fn("importRecentAgentThreads")(function* (
101 input: AgentSessionImportInput,
102) {
103 const scanner = yield* AgentSessionScanner.AgentSessionScanner;
104 const engine = yield* OrchestrationEngine.OrchestrationEngineService;
105 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
106 const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
107 const crypto = yield* Crypto.Crypto;
108 const project = yield* snapshots.getProjectShellById(input.projectId).pipe(
109 Effect.mapError((cause) => new AgentSessionScanError({ operation: "read-projects", cause })),
110 Effect.flatMap(
111 Option.match({
112 onNone: () =>
113 Effect.fail(new AgentSessionImportProjectNotFoundError({ projectId: input.projectId })),
114 onSome: Effect.succeed,
115 }),
116 ),
117 );
118 const workspaceRoot = project.workspaceRoot;
119 if (
120 input.expectedWorkspaceRoot !== undefined &&
121 normalizeProjectPathForComparison(workspaceRoot) !==
122 normalizeProjectPathForComparison(input.expectedWorkspaceRoot)
123 ) {
124 return yield* new AgentSessionImportProjectChangedError({ projectId: input.projectId });
125 }
126 const completedSources = yield* snapshots
127 .getImportedAgentSessionSources(input.projectId)
128 .pipe(
129 Effect.mapError((cause) => new AgentSessionScanError({ operation: "read-projects", cause })),
130 );
131 const threads = scanner.recentThreads(
132 workspaceRoot,
133 completedSources.map((entry) => entry.source),
134 );
135 const importedThreadIds = new Set<ThreadId>();
136 let importedCount = 0;
137 let skippedCount = 0;
138​
139 yield* Stream.runForEach(threads, (outcome) =>
140 Effect.gen(function* () {
141 if (outcome._tag === "Skipped") {
142 skippedCount += 1;
143 return;
144 }
145 if (outcome._tag === "AlreadyImported" || outcome._tag === "Duplicate") {
146 const threadId = ThreadId.make(
147 `import:${outcome.source.providerInstanceId}:${outcome.source.providerSessionId}`,
148 );
149 if (outcome._tag === "AlreadyImported") {
150 importedThreadIds.add(threadId);
151 importedCount += 1;
152 } else if (importedThreadIds.has(threadId)) {
153 const recorded = yield* directory
154 .recordImportedTranscript({ threadId, source: outcome.source })
155 .pipe(Effect.result);
156 if (recorded._tag === "Failure") {
157 skippedCount += 1;
158 yield* Effect.logWarning("Could not record an imported transcript copy", {
159 threadId,
160 cause: recorded.failure,
161 });
162 }
163 }
164 return;
165 }
166 const thread = outcome.thread;
167 const threadId = ThreadId.make(
168 `import:${thread.providerInstanceId}:${thread.providerSessionId}`,
169 );
170 const imported = yield* Effect.gen(function* () {
171 const provider = ProviderDriverKind.make(thread.source);
172 const model = thread.model ?? DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL;
173 const existingThread = yield* snapshots.getThreadDetailById(threadId);
174 const existingBinding = yield* directory.getBinding(threadId);
175​
176 if (
177 thread.source === "claudeAgent" &&
178 !CLAUDE_SESSION_ID_PATTERN.test(thread.providerSessionId)
179 ) {
180 return yield* new AgentSessionUnresumableSessionError({
181 source: thread.source,
182 providerSessionId: thread.providerSessionId,
183 });
184 }
185​
186 if (Option.isSome(existingThread) && existingThread.value.projectId !== input.projectId) {
187 return yield* new AgentSessionThreadProjectConflictError({
188 threadId,
189 expectedProjectId: input.projectId,
190 actualProjectId: existingThread.value.projectId,
191 });
192 }
193​
194 const importedHistoryPresent = Option.isSome(existingThread)
195 ? hasImportedHistory(existingThread.value)
196 : false;
197 if (
198 Option.isSome(existingThread) &&
199 importedHistoryPresent &&
200 Option.isSome(existingBinding)
201 ) {
202 yield* directory.recordImportedTranscript({ threadId, source: outcome.source });
203 return true;
204 }
205​
206 if (
207 Option.isSome(existingThread) &&
208 hasImportBlockingActivity(existingThread.value, importedHistoryPresent)
209 ) {
210 return yield* new AgentSessionThreadModifiedError({ threadId });
211 }
212​
213 if (
214 Option.isSome(existingBinding) &&
215 (existingBinding.value.provider !== provider ||
216 existingBinding.value.providerInstanceId !== thread.providerInstanceId ||
217 existingBinding.value.status !== "stopped")
218 ) {
219 return yield* new AgentSessionThreadModifiedError({ threadId });
220 }
221​
222 // Install the cursor before the thread becomes visible. A concurrent
223 // real session can replace it, while insert-ignore keeps this import
224 // from replacing that newer binding.
225 if (Option.isNone(existingBinding)) {
226 yield* directory.upsert(
227 {
228 threadId,
229 provider,
230 providerInstanceId: thread.providerInstanceId,
231 status: "stopped",
232 runtimeMode: DEFAULT_RUNTIME_MODE,
233 resumeCursor:
234 thread.source === "codex"
235 ? { threadId: thread.providerSessionId }
236 : { threadId, resume: thread.providerSessionId },
237 runtimePayload: { cwd: workspaceRoot },
238 },
239 { onConflict: "ignore" },
240 );
241 }
242​
243 if (Option.isNone(existingThread)) {
244 yield* engine.dispatch({
245 type: "thread.create",
246 commandId: CommandId.make(yield* crypto.randomUUIDv4),
247 threadId,
248 projectId: input.projectId,
249 title: thread.title,
250 modelSelection: { instanceId: thread.providerInstanceId, model },
251 runtimeMode: DEFAULT_RUNTIME_MODE,
252 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
253 branch: null,
254 worktreePath: null,
255 createdAt: thread.createdAt,
256 historyImport: true,
257 });
258 }
259​
260 if (!importedHistoryPresent) {
261 yield* engine.dispatch({
262 type: "thread.history.import",
263 commandId: CommandId.make(yield* crypto.randomUUIDv4),
264 threadId,
265 messages: thread.messages.map((message, index) => ({
266 messageId: MessageId.make(`${threadId}:${String(index).padStart(6, "0")}`),
267 role: message.role,
268 text: message.text,
269 createdAt: message.createdAt,
270 })),
271 });
272 }
273​
274 yield* directory.recordImportedTranscript({ threadId, source: outcome.source });
275​
276 return true;
277 }).pipe(
278 Effect.catch((cause) =>
279 Effect.logWarning("Could not import an agent session", {
280 provider: thread.source,
281 sessionId: thread.providerSessionId,
282 cause,
283 }).pipe(Effect.as(false)),
284 ),
285 );
286​
287 if (imported) {
288 importedThreadIds.add(threadId);
289 importedCount += 1;
290 } else {
291 skippedCount += 1;
292 }
293 }),
294 );
295​
296 return { importedCount, skippedCount } satisfies AgentSessionImportResult;
297});