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

AgentSessionImporter.ts

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