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

AgentSessionImporter.ts

298 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.TaggedError<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.TaggedError<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.TaggedError<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.autoSettleDisabledAt != null ||
91 thread.titleRegeneration != null ||
92 thread.linkedPullRequest != null ||
93 thread.unsettledAt != null ||
94 (importedHistoryPresent
95 ? thread.settledOverride !== "settled"
96 : thread.settledOverride !== null || thread.settledAt !== null)
97 );
99​
100/** Import recent transcript text and persist the cursor needed to resume its provider session. */
101export const importRecentAgentThreads = Effect.fn("importRecentAgentThreads")(function* (
102 input: AgentSessionImportInput,
103) {
104 const scanner = yield* AgentSessionScanner.AgentSessionScanner;
105 const engine = yield* OrchestrationEngine.OrchestrationEngineService;
106 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
107 const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
108 const crypto = yield* Crypto.Crypto;
109 const project = yield* snapshots.getProjectShellById(input.projectId).pipe(
110 Effect.mapError((cause) => new AgentSessionScanError({ operation: "read-projects", cause })),
111 Effect.flatMap(
112 Option.match({
113 onNone: () =>
114 Effect.fail(new AgentSessionImportProjectNotFoundError({ projectId: input.projectId })),
115 onSome: Effect.succeed,
116 }),
117 ),
118 );
119 const workspaceRoot = project.workspaceRoot;
120 if (
121 input.expectedWorkspaceRoot !== undefined &&
122 normalizeProjectPathForComparison(workspaceRoot) !==
123 normalizeProjectPathForComparison(input.expectedWorkspaceRoot)
124 ) {
125 return yield* new AgentSessionImportProjectChangedError({ projectId: input.projectId });
126 }
127 const completedSources = yield* snapshots
128 .getImportedAgentSessionSources(input.projectId)
129 .pipe(
130 Effect.mapError((cause) => new AgentSessionScanError({ operation: "read-projects", cause })),
131 );
132 const threads = scanner.recentThreads(
133 workspaceRoot,
134 completedSources.map((entry) => entry.source),
135 );
136 const importedThreadIds = new Set<ThreadId>();
137 let importedCount = 0;
138 let skippedCount = 0;
139​
140 yield* Stream.runForEach(threads, (outcome) =>
141 Effect.gen(function* () {
142 if (outcome._tag === "Skipped") {
143 skippedCount += 1;
144 return;
145 }
146 if (outcome._tag === "AlreadyImported" || outcome._tag === "Duplicate") {
147 const threadId = ThreadId.make(
148 `import:${outcome.source.providerInstanceId}:${outcome.source.providerSessionId}`,
149 );
150 if (outcome._tag === "AlreadyImported") {
151 importedThreadIds.add(threadId);
152 importedCount += 1;
153 } else if (importedThreadIds.has(threadId)) {
154 const recorded = yield* directory
155 .recordImportedTranscript({ threadId, source: outcome.source })
156 .pipe(Effect.result);
157 if (recorded._tag === "Failure") {
158 skippedCount += 1;
159 yield* Effect.logWarning("Could not record an imported transcript copy", {
160 threadId,
161 cause: recorded.failure,
162 });
163 }
164 }
165 return;
166 }
167 const thread = outcome.thread;
168 const threadId = ThreadId.make(
169 `import:${thread.providerInstanceId}:${thread.providerSessionId}`,
170 );
171 const imported = yield* Effect.gen(function* () {
172 const provider = ProviderDriverKind.make(thread.source);
173 const model = thread.model ?? DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL;
174 const existingThread = yield* snapshots.getThreadDetailById(threadId);
175 const existingBinding = yield* directory.getBinding(threadId);
176​
177 if (
178 thread.source === "claudeAgent" &&
179 !CLAUDE_SESSION_ID_PATTERN.test(thread.providerSessionId)
180 ) {
181 return yield* new AgentSessionUnresumableSessionError({
182 source: thread.source,
183 providerSessionId: thread.providerSessionId,
184 });
185 }
186​
187 if (Option.isSome(existingThread) && existingThread.value.projectId !== input.projectId) {
188 return yield* new AgentSessionThreadProjectConflictError({
189 threadId,
190 expectedProjectId: input.projectId,
191 actualProjectId: existingThread.value.projectId,
192 });
193 }
194​
195 const importedHistoryPresent = Option.isSome(existingThread)
196 ? hasImportedHistory(existingThread.value)
197 : false;
198 if (
199 Option.isSome(existingThread) &&
200 importedHistoryPresent &&
201 Option.isSome(existingBinding)
202 ) {
203 yield* directory.recordImportedTranscript({ threadId, source: outcome.source });
204 return true;
205 }
206​
207 if (
208 Option.isSome(existingThread) &&
209 hasImportBlockingActivity(existingThread.value, importedHistoryPresent)
210 ) {
211 return yield* new AgentSessionThreadModifiedError({ threadId });
212 }
213​
214 if (
215 Option.isSome(existingBinding) &&
216 (existingBinding.value.provider !== provider ||
217 existingBinding.value.providerInstanceId !== thread.providerInstanceId ||
218 existingBinding.value.status !== "stopped")
219 ) {
220 return yield* new AgentSessionThreadModifiedError({ threadId });
221 }
222​
223 // Install the cursor before the thread becomes visible. A concurrent
224 // real session can replace it, while insert-ignore keeps this import
225 // from replacing that newer binding.
226 if (Option.isNone(existingBinding)) {
227 yield* directory.upsert(
228 {
229 threadId,
230 provider,
231 providerInstanceId: thread.providerInstanceId,
232 status: "stopped",
233 runtimeMode: DEFAULT_RUNTIME_MODE,
234 resumeCursor:
235 thread.source === "codex"
236 ? { threadId: thread.providerSessionId }
237 : { threadId, resume: thread.providerSessionId },
238 runtimePayload: { cwd: workspaceRoot },
239 },
240 { onConflict: "ignore" },
241 );
242 }
243​
244 if (Option.isNone(existingThread)) {
245 yield* engine.dispatch({
246 type: "thread.create",
247 commandId: CommandId.make(yield* crypto.randomUUIDv4),
248 threadId,
249 projectId: input.projectId,
250 title: thread.title,
251 modelSelection: { instanceId: thread.providerInstanceId, model },
252 runtimeMode: DEFAULT_RUNTIME_MODE,
253 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
254 branch: null,
255 worktreePath: null,
256 createdAt: thread.createdAt,
257 historyImport: true,
258 });
259 }
260​
261 if (!importedHistoryPresent) {
262 yield* engine.dispatch({
263 type: "thread.history.import",
264 commandId: CommandId.make(yield* crypto.randomUUIDv4),
265 threadId,
266 messages: thread.messages.map((message, index) => ({
267 messageId: MessageId.make(`${threadId}:${String(index).padStart(6, "0")}`),
268 role: message.role,
269 text: message.text,
270 createdAt: message.createdAt,
271 })),
272 });
273 }
274​
275 yield* directory.recordImportedTranscript({ threadId, source: outcome.source });
276​
277 return true;
278 }).pipe(
279 Effect.catch((cause) =>
280 Effect.logWarning("Could not import an agent session", {
281 provider: thread.source,
282 sessionId: thread.providerSessionId,
283 cause,
284 }).pipe(Effect.as(false)),
285 ),
286 );
287​
288 if (imported) {
289 importedThreadIds.add(threadId);
290 importedCount += 1;
291 } else {
292 skippedCount += 1;
293 }
294 }),
295 );
296​
297 return { importedCount, skippedCount } satisfies AgentSessionImportResult;
298});