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