import { lstatSync, readFileSync, realpathSync, statSync } from "node:fs"; import path from "node:path"; import { pathToFileURL } from "node:url"; import { DatabaseSync, type SQLOutputValue } from "node:sqlite"; import type { HistoricalTurnOutcome, HostThreadSnapshot, HostTurnSnapshot, } from "@codexhost/harness-adapter"; import { nativeSessionRefSchema, nativeTurnRefSchema, type NativeSessionRef, type NativeTurnRef, } from "@codexhost/shared-contracts"; import { containedPath } from "./installation.js"; import { HARNESS_ID, MiniMaxError, nativeError, nativeId, record } from "./native.js"; import { fileChangeItem, itemId, toolItems } from "./projection.js"; import { questionnaireRequestId } from "./questionnaire.js"; const LOCATOR_KIND = "mcode-data-root-v1"; const SESSION_ID = /^mvs_[0-9a-f]{32}$/u; const DATED_DIR = /^\d{4}\/(?:0[1-9]|1[0-2])\/(?:0[1-9]|[12]\d|3[01])\/(?:[01]\d|2[0-3])-[0-5]\d-[0-5]\d-\d{3}-session_([A-Za-z0-9_-]+)$/u; const MAX_LEDGER_BYTES = 64 * 1024 * 1024; type SqlRow = Record; export function sessionRef(id: string, root: string): NativeSessionRef { if (!SESSION_ID.test(id)) throw historyError("Invalid MiniMax Code Session ID"); return nativeSessionRefSchema.parse({ harnessId: HARNESS_ID, nativeSessionId: id, locator: { kind: LOCATOR_KIND, dataRoot: root }, formatVersion: 1, }); } export function validateSessionRef(ref: NativeSessionRef, root: string): string { const parsed = nativeSessionRefSchema.safeParse(ref); const locator = record(parsed.data?.locator); if ( !parsed.success || ref.harnessId !== HARNESS_ID || !SESSION_ID.test(ref.nativeSessionId) || locator?.kind !== LOCATOR_KIND || locator.dataRoot !== root || Object.keys(locator).length !== 2 ) { throw new MiniMaxError( "invalidRequest", "MiniMax Code Session ref does not match this data root", ); } return ref.nativeSessionId; } function turnRef(id: string, key: string): NativeTurnRef { return nativeTurnRefSchema.parse({ harnessId: HARNESS_ID, nativeSessionId: id, nativeTurnKey: key, formatVersion: 1, }); } export function validateKnownTurns( snapshot: HostThreadSnapshot, refs: readonly NativeTurnRef[], ): void { let next = 0; for (const ref of refs) { const index = snapshot.turns.findIndex( ({ nativeTurnRef: actual }, i) => i >= next && ref.formatVersion === actual.formatVersion && ref.harnessId === actual.harnessId && ref.nativeSessionId === actual.nativeSessionId && ref.nativeTurnKey === actual.nativeTurnKey, ); if (index < 0) throw new MiniMaxError( "invalidRequest", "Known MiniMax Code Turn refs do not match native history order", ); next = index + 1; } } function historyError(message = "Unrecognized MiniMax Code history schema"): MiniMaxError { return new MiniMaxError("protocolError", message); } function missing(error: unknown): boolean { return (error as NodeJS.ErrnoException | undefined)?.code === "ENOENT"; } function exactPath(root: string, candidate: string): string { const actual = containedPath(root, candidate); if (path.relative(candidate, actual) !== "") throw historyError("MiniMax Code history is not at its expected path"); return actual; } function readJson(text: string): Record { try { const value = record(JSON.parse(text)); if (value) return value; } catch { /* Report a content-free protocol error. */ } throw historyError(); } function validateColumns(db: DatabaseSync, table: string, required: Record): void { const columns = db.prepare(`PRAGMA table_info(${table})`).all(); for (const [name, type] of Object.entries(required)) { if (!columns.some((col) => col.name === name && col.type === type)) throw historyError(); } } function journalSidecars(root: string, dbPath: string): number { return ["-wal", "-shm"].reduce((count, suffix) => { const file = `${dbPath}${suffix}`; try { if (!lstatSync(file).isFile()) throw historyError("Invalid MiniMax Code SQLite sidecar"); exactPath(root, file); return count + 1; } catch (error) { if (!missing(error)) throw error; return count; } }, 0); } function withHistory( root: string, cwd: string, id: string, read: (db: DatabaseSync, ledger: string) => T, ): T { if (!SESSION_ID.test(id)) throw historyError("Invalid MiniMax Code Session ID"); try { const dbPath = exactPath(root, path.join(root, "v2", "sqlite", "runtime-state.sqlite")); const sidecars = journalSidecars(root, dbPath); if (sidecars === 1) throw historyError("MiniMax Code SQLite sidecars are in transition"); const coldUri = pathToFileURL(dbPath); // A normal read-only open of a cold WAL database can create sidecars. coldUri.searchParams.set("immutable", "1"); const db = new DatabaseSync(sidecars === 0 ? coldUri : dbPath, { readOnly: true }); try { validateColumns(db, "local_runtime_sessions", { session_id: "TEXT", workspace_dir: "TEXT", history_relative_dir: "TEXT", }); validateColumns(db, "local_runtime_message_rows", { id: "INTEGER", session_id: "TEXT", msg_id: "TEXT", role: "TEXT", turn_id: "TEXT", data_json: "TEXT", }); validateColumns(db, "local_runtime_turn_ingress", { session_id: "TEXT", turn_id: "TEXT", status: "TEXT", accepted_sequence: "INTEGER", accepted_at_ms: "INTEGER", completed_at_ms: "INTEGER", }); db.exec("BEGIN"); const session = db .prepare( "SELECT workspace_dir, history_relative_dir FROM local_runtime_sessions WHERE session_id = ?", ) .get(id); if (!session) throw new MiniMaxError("sessionNotFound", "MiniMax Code Session is not in native history"); const workspace = session.workspace_dir; if ( typeof workspace !== "string" || !path.isAbsolute(workspace) || path.relative(cwd, realpathSync(workspace)) !== "" ) { throw new MiniMaxError( "invalidRequest", "MiniMax Code Session belongs to another workspace", ); } const relative = session.history_relative_dir; const encoded = typeof relative === "string" && DATED_DIR.exec(relative)?.[1]; if (typeof relative !== "string" || encoded !== Buffer.from(id).toString("base64url")) throw historyError(); const directory = exactPath(root, path.join(root, "v2", "sessions", relative)); const manifest = readFileSync( exactPath(directory, path.join(directory, "manifest.json")), "utf8", ); const value = readJson(manifest); const ledger = path.join(directory, "messages.jsonl"); const paths = record(value.paths); if ( value.schemaVersion !== 1 || value.layout !== "v2-final-dated-session" || value.sessionId !== id || paths?.sessionDir !== directory || paths.messages !== ledger ) throw historyError(); const valueRead = read(db, ledger); if (sidecars === 0 && journalSidecars(root, dbPath) !== 0) { throw historyError("MiniMax Code SQLite sidecars appeared during a cold read"); } return valueRead; } finally { db.close(); } } catch (error) { if (error instanceof MiniMaxError) throw error; if (missing(error)) throw new MiniMaxError( "sessionNotFound", "MiniMax Code durable Session history is not present yet", ); throw historyError(); } } function journalData(row: SqlRow): Record { if (typeof row.data_json !== "string") throw historyError(); const data = readJson(row.data_json); if ( data.msg_id !== row.msg_id || (data.turn_id != null && data.turn_id !== row.turn_id) || (data.turnId != null && data.turnId !== row.turn_id) ) throw historyError(); return data; } function journalRecord(value: unknown) { if (typeof value !== "string") return record(value); try { return record(JSON.parse(value)); } catch { return undefined; } } function questionnaireTurnKeys( db: DatabaseSync, sessionId: string, requestId: string, toolCallId: string, ): Set { const keys = new Set(); const request = db .prepare( "SELECT request_id FROM questionnaire_requests WHERE session_id = ? AND request_id = ?", ) .all(sessionId, requestId); if (request.length > 1) throw historyError(); if (!request.length) return keys; // The request row can have a NULL msg_id. The assistant's journal result carries the join. for (const row of db .prepare( "SELECT msg_id, turn_id, data_json FROM local_runtime_message_rows WHERE session_id = ? AND role = 'assistant' AND instr(data_json, ?) > 0", ) .iterate(sessionId, requestId)) { const { tool_calls: tools } = journalData(row); if (!Array.isArray(tools)) continue; for (const value of tools) { const tool = record(value); if (tool?.tool_name !== "ask_user" || tool.tool_call_id !== toolCallId) continue; if (questionnaireRequestId(journalRecord(tool.tool_call_result_data)) !== requestId) continue; if (!nativeId(row.turn_id)) throw historyError("Invalid MiniMax Code questionnaire identity"); keys.add(row.turn_id); } } return keys; } /** Only IDs observed on this ACP connection can establish a live Turn's identity. */ export function correlatedTurn( root: string, cwd: string, id: string, ids: ReadonlySet, questionnaireCalls: ReadonlyMap, terminal: string, ): NativeTurnRef | undefined { if (!ids.size && !questionnaireCalls.size) return; return withHistory(root, cwd, id, (db, ledger) => { const query = db.prepare( "SELECT msg_id, role, turn_id, data_json FROM local_runtime_message_rows WHERE session_id = ? AND msg_id = ?", ); let key: string | undefined; let pending = false; for (const messageId of ids) { const rows = query.all(id, messageId); if (!rows.length) { pending = true; continue; } const [row] = rows; if (rows.length !== 1 || row?.role !== "assistant" || !nativeId(row.turn_id)) throw historyError("Invalid MiniMax Code ACP message identity"); journalData(row); if (key && key !== row.turn_id) throw historyError("MiniMax Code ACP messages refer to multiple native Turns"); key = row.turn_id; } if (questionnaireCalls.size) { validateColumns(db, "questionnaire_requests", { session_id: "TEXT", request_id: "TEXT" }); for (const [requestId, toolCallId] of questionnaireCalls) { const keys = questionnaireTurnKeys(db, id, requestId, toolCallId); const [matched] = keys; if (keys.size > 1 || (key && matched && key !== matched)) throw historyError("MiniMax Code ACP updates refer to multiple native Turns"); if (!matched) pending = true; else key = matched; } } if (!key || pending) return; const ingress = db .prepare("SELECT status FROM local_runtime_turn_ingress WHERE session_id = ? AND turn_id = ?") .all(id, key); if (ingress.length > 1) throw historyError(); if (ingress[0]?.status !== terminal) return; // The compacted ledger may lack this Turn. Its journal still needs the original user row. const user = db .prepare( "SELECT msg_id, turn_id, data_json FROM local_runtime_message_rows WHERE session_id = ? AND turn_id = ? AND role = 'user'", ) .all(id, key); if (!user.some((row) => typeof journalData(row).msg_content === "string")) return; exactPath(path.dirname(ledger), ledger); return turnRef(id, key); }); } function historicalOutcome(status: SQLOutputValue | undefined): HistoricalTurnOutcome { if (status === "completed") return { status: "succeeded" }; if (status === "aborted") return { status: "cancelled" }; if (status === "failed") return { status: "failed", error: nativeError(undefined) }; return { status: "unknown", reason: "MiniMax Code has no durable terminal outcome for this Turn", }; } function addJournalItems(turn: HostTurnSnapshot, data: Record, cwd: string): void { if (typeof data.msg_id !== "string") throw historyError(); for (const [type, text] of [ ["reasoning", data.thinking_content], ["agentMessage", data.msg_content], ] as const) { if (typeof text === "string" && text !== "") { turn.items.push({ item: { type, text, itemId: itemId(type, data.msg_id) }, outcome: { status: "succeeded" }, }); } } if (!Array.isArray(data.tool_calls)) return; for (const value of data.tool_calls) { const tool = record(value); if (!nativeId(tool?.tool_call_id)) continue; const input = journalRecord(tool.tool_call_args); const rawOutput = journalRecord(tool.tool_call_result_data); const result = record(rawOutput?.result) ?? rawOutput; const status = result?.isError === true ? "failed" : result ? "completed" : undefined; const update = { name: tool.tool_name, kind: tool.tool_name === "bash" ? "execute" : undefined, rawInput: input ?? tool.tool_call_args, rawOutput: result, status, }; const items = toolItems(tool.tool_call_id, update, cwd); const filePath = input?.file_path; const patch = record(result?.details)?.patch; if ( tool.tool_name === "edit" && tool.tool_call_status === 2 && status === "completed" && nativeId(filePath) && !/[\r\n]/u.test(filePath) && typeof patch === "string" && patch.startsWith(`--- ${filePath}\n+++ ${filePath}\n@@ `) ) { items.push( fileChangeItem(tool.tool_call_id, [{ path: filePath, kind: "update", unifiedDiff: patch }]), ); } for (const item of items) { const outcome = status === "completed" ? ({ status: "succeeded" } as const) : status === "failed" ? ({ status: "failed", error: nativeError(undefined) } as const) : ({ status: "cancelled" } as const); const previous = turn.items.findIndex( ({ item: existing }) => existing.itemId === item.itemId, ); if (previous < 0) turn.items.push({ item, outcome }); else turn.items[previous] = { item, outcome }; } } } function addLedgerCompactions(ledger: string, turns: Map): void { const file = exactPath(path.dirname(ledger), ledger); if (statSync(file).size > MAX_LEDGER_BYTES) throw historyError("MiniMax Code history ledger exceeds the supported size"); const contents = readFileSync(file, "utf8"); const lines = contents.split("\n"); // A native process may still be appending the final line. lines.pop(); for (const line of lines) { if (!line.trim()) continue; const row = readJson(line); const data = record(row.message); if (data?.role !== "compactionSummary" || !nativeId(row.turn_id) || !nativeId(row.message_id)) continue; turns.get(row.turn_id)?.items.push({ item: { type: "contextCompaction", itemId: itemId("compaction", row.message_id) }, outcome: { status: "succeeded" }, }); } } export function readHistory(root: string, cwd: string, id: string): HostThreadSnapshot { return withHistory(root, cwd, id, (db, ledger) => { const ingress = db .prepare( "SELECT turn_id, status, accepted_at_ms, completed_at_ms, accepted_sequence FROM local_runtime_turn_ingress WHERE session_id = ?", ) .all(id); const metadata = new Map(ingress.map((row) => [row.turn_id, row])); if (metadata.size !== ingress.length) throw historyError(); const turns = new Map(); for (const row of db .prepare( "SELECT msg_id, role, turn_id, data_json FROM local_runtime_message_rows WHERE session_id = ? ORDER BY id", ) .iterate(id)) { if (!nativeId(row.turn_id) || (row.role !== "user" && row.role !== "assistant")) continue; const data = journalData(row); const key = row.turn_id; let turn = turns.get(key); if (!turn) { const entry = metadata.get(key); turn = { nativeTurnRef: turnRef(id, key), input: [], items: [], outcome: historicalOutcome(entry?.status), ...(typeof entry?.accepted_at_ms === "number" ? { startedAtMs: entry.accepted_at_ms } : {}), ...(typeof entry?.completed_at_ms === "number" ? { completedAtMs: entry.completed_at_ms } : {}), }; turns.set(key, turn); } if (row.role === "user" && typeof data.msg_content === "string") turn.input.push({ type: "text", text: data.msg_content }); if (row.role === "assistant") addJournalItems(turn, data, cwd); } addLedgerCompactions(ledger, turns); return { turns: [...turns.values()] }; }); }