sessiongraph-app-darwin-arm64 1.0.18 → 1.0.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/payload/SessionGraph.app/Contents/Info.plist +2 -2
- package/payload/SessionGraph.app/Contents/MacOS/sessiongraph +0 -0
- package/payload/SessionGraph.app/Contents/Resources/resources/cli-package.json +1 -1
- package/payload/SessionGraph.app/Contents/Resources/resources/cli.mjs +1073 -1265
- package/payload/SessionGraph.app/Contents/Resources/resources/server.mjs +1050 -880
- package/payload/SessionGraph.app/Contents/_CodeSignature/CodeResources +6 -6
|
@@ -79,7 +79,7 @@ function make7(connect) {
|
|
|
79
79
|
subscribe(options) {
|
|
80
80
|
return {
|
|
81
81
|
[Symbol.asyncIterator]() {
|
|
82
|
-
const
|
|
82
|
+
const pending = [];
|
|
83
83
|
const queued = [];
|
|
84
84
|
let started = false;
|
|
85
85
|
let completion;
|
|
@@ -93,7 +93,7 @@ function make7(connect) {
|
|
|
93
93
|
options?.signal?.removeEventListener("abort", abort);
|
|
94
94
|
if (connection?.subscribers.delete(subscriber) && !connection.subscribers.size)
|
|
95
95
|
stop2(connection);
|
|
96
|
-
|
|
96
|
+
pending.splice(0).forEach((request) => {
|
|
97
97
|
if ("error" in result)
|
|
98
98
|
request.reject(result.error);
|
|
99
99
|
else
|
|
@@ -113,7 +113,7 @@ function make7(connect) {
|
|
|
113
113
|
return;
|
|
114
114
|
if (!selected(value))
|
|
115
115
|
return;
|
|
116
|
-
const request =
|
|
116
|
+
const request = pending.shift();
|
|
117
117
|
if (request) {
|
|
118
118
|
request.resolve({ done: false, value });
|
|
119
119
|
return;
|
|
@@ -155,7 +155,7 @@ function make7(connect) {
|
|
|
155
155
|
return Promise.resolve({ done: true, value: void 0 });
|
|
156
156
|
}
|
|
157
157
|
const request = Promise.withResolvers();
|
|
158
|
-
|
|
158
|
+
pending.push(request);
|
|
159
159
|
if (!started) {
|
|
160
160
|
started = true;
|
|
161
161
|
options?.signal?.addEventListener("abort", abort, { once: true });
|
|
@@ -2142,6 +2142,10 @@ import { fileURLToPath as fileURLToPath5 } from "node:url";
|
|
|
2142
2142
|
import { resolve as resolve2, extname, sep as sep4 } from "node:path";
|
|
2143
2143
|
import { randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
|
|
2144
2144
|
|
|
2145
|
+
// server/adapters/opencode.ts
|
|
2146
|
+
import { lstat as lstat3, readdir as readdir2 } from "node:fs/promises";
|
|
2147
|
+
import { join as join6 } from "node:path";
|
|
2148
|
+
|
|
2145
2149
|
// node_modules/.pnpm/@opencode+client@2.2.1_effect@4.0.1/node_modules/@opencode/client/dist/chunks/mcp-ve4aws36.js
|
|
2146
2150
|
import { spawn } from "node:child_process";
|
|
2147
2151
|
var stderrLimit = 8 * 1024;
|
|
@@ -2615,10 +2619,6 @@ function delay(milliseconds) {
|
|
|
2615
2619
|
}
|
|
2616
2620
|
var Service = { discover, ensure, stop, headers: headers2 };
|
|
2617
2621
|
|
|
2618
|
-
// server/opencode.ts
|
|
2619
|
-
import { basename } from "node:path";
|
|
2620
|
-
import { createHash } from "node:crypto";
|
|
2621
|
-
|
|
2622
2622
|
// server/config.ts
|
|
2623
2623
|
import { existsSync } from "node:fs";
|
|
2624
2624
|
import { homedir as homedir2 } from "node:os";
|
|
@@ -2879,65 +2879,6 @@ function sessionFromResponse(value, id2) {
|
|
|
2879
2879
|
async function getSessionInfo(id2) {
|
|
2880
2880
|
return sessionFromResponse(await api(`/api/session/${encodeURIComponent(id2)}`), id2);
|
|
2881
2881
|
}
|
|
2882
|
-
var cache;
|
|
2883
|
-
var pending;
|
|
2884
|
-
async function getSessionGraph(force = false) {
|
|
2885
|
-
if (!force && cache && Date.now() - cache.loadedAt < 3e4) return cache;
|
|
2886
|
-
if (pending) return pending;
|
|
2887
|
-
pending = loadSessionGraph().then((data) => cache = data).finally(() => {
|
|
2888
|
-
pending = void 0;
|
|
2889
|
-
});
|
|
2890
|
-
return pending;
|
|
2891
|
-
}
|
|
2892
|
-
async function loadSessionGraph() {
|
|
2893
|
-
const endpoint = await Service.discover({ file: serviceFile() });
|
|
2894
|
-
if (!endpoint) throw new Error("No healthy OpenCode service was found.");
|
|
2895
|
-
const sourceID = createHash("sha256").update(JSON.stringify([endpoint.url, serviceFile() || "default"])).digest("hex");
|
|
2896
|
-
const rawProjects = await api("/api/project");
|
|
2897
|
-
const sessions = /* @__PURE__ */ new Map();
|
|
2898
|
-
const warnings = [];
|
|
2899
|
-
let cursor;
|
|
2900
|
-
const seenCursors = /* @__PURE__ */ new Set();
|
|
2901
|
-
do {
|
|
2902
|
-
const params = new URLSearchParams({ limit: "500" });
|
|
2903
|
-
if (cursor) params.set("cursor", cursor);
|
|
2904
|
-
const page = await api(`/api/session?${params}`);
|
|
2905
|
-
if (!Array.isArray(page.data)) throw new Error("Unexpected OpenCode session response. OpenCode V2 is required.");
|
|
2906
|
-
for (const raw of page.data) {
|
|
2907
|
-
const t = raw.tokens;
|
|
2908
|
-
sessions.set(raw.id, {
|
|
2909
|
-
id: raw.id,
|
|
2910
|
-
title: raw.title || "Untitled session",
|
|
2911
|
-
projectID: raw.projectID,
|
|
2912
|
-
parentID: raw.parentID,
|
|
2913
|
-
forkID: raw.fork?.sessionID,
|
|
2914
|
-
directory: raw.location?.directory || "",
|
|
2915
|
-
created: raw.time.created,
|
|
2916
|
-
updated: raw.time.updated,
|
|
2917
|
-
archived: Boolean(raw.time.archived),
|
|
2918
|
-
model: raw.model?.id || "Unknown model",
|
|
2919
|
-
provider: raw.model?.providerID || "",
|
|
2920
|
-
agent: raw.agent || "build",
|
|
2921
|
-
cost: recordedCost(raw.cost),
|
|
2922
|
-
// Input + output + cache tokens; reasoning is generally part of output.
|
|
2923
|
-
tokens: sumRecordedTokens([t?.input, t?.output, t?.cache?.read, t?.cache?.write]),
|
|
2924
|
-
usage: sessionUsage(openCodeUsage(t, raw.cost)),
|
|
2925
|
-
outcome: raw.outcome
|
|
2926
|
-
});
|
|
2927
|
-
}
|
|
2928
|
-
cursor = page.cursor?.next;
|
|
2929
|
-
if (cursor && seenCursors.has(cursor)) throw new Error("OpenCode returned a repeated session cursor.");
|
|
2930
|
-
if (cursor) seenCursors.add(cursor);
|
|
2931
|
-
} while (cursor && sessions.size < 2e4);
|
|
2932
|
-
if (cursor) warnings.push("OpenCode: Showing the newest 20,000 sessions.");
|
|
2933
|
-
const projects = rawProjects.map((p) => ({
|
|
2934
|
-
id: p.id,
|
|
2935
|
-
name: p.name || basename(p.canonical) || "Global",
|
|
2936
|
-
directory: p.canonical,
|
|
2937
|
-
worktrees: p.sandboxes || []
|
|
2938
|
-
}));
|
|
2939
|
-
return { sourceID, sessions: [...sessions.values()], projects, loadedAt: Date.now(), warnings };
|
|
2940
|
-
}
|
|
2941
2882
|
function editedPaths(part) {
|
|
2942
2883
|
if (part.state?.status !== "completed") return [];
|
|
2943
2884
|
const name = (part.name || "").split(/[./]/).at(-1) || "";
|
|
@@ -3067,11 +3008,11 @@ function extractContent(messages) {
|
|
|
3067
3008
|
}
|
|
3068
3009
|
|
|
3069
3010
|
// server/adapters/common.ts
|
|
3070
|
-
import { createHash
|
|
3071
|
-
import { basename
|
|
3072
|
-
var digest = (value) =>
|
|
3011
|
+
import { createHash } from "node:crypto";
|
|
3012
|
+
import { basename } from "node:path";
|
|
3013
|
+
var digest = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
3073
3014
|
var identity = (source, native) => `${source}:${native}`;
|
|
3074
|
-
var project = (source, directory3) => ({ id: identity(source, digest(directory3).slice(0, 24)), name:
|
|
3015
|
+
var project = (source, directory3) => ({ id: identity(source, digest(directory3).slice(0, 24)), name: basename(directory3) || "Global", directory: directory3, worktrees: [] });
|
|
3075
3016
|
var blankSession = (source, nativeID, directory3 = "") => ({
|
|
3076
3017
|
source,
|
|
3077
3018
|
nativeID,
|
|
@@ -3416,7 +3357,7 @@ function opencodeEvents(raw, message2) {
|
|
|
3416
3357
|
else if (part.type === "tool") {
|
|
3417
3358
|
const state2 = part.state || {}, endTime = messageTime(part.time?.completed);
|
|
3418
3359
|
const status2 = state2.status === "error" ? "failed" : state2.status === "streaming" ? "pending" : ["running", "completed"].includes(state2.status) ? state2.status : "unknown";
|
|
3419
|
-
const common = { ...native, callID: part.id, status: status2, endTime, ...executionFields(state2.input, state2.metadata), partial: Boolean(state2.metadata?.truncated) };
|
|
3360
|
+
const common = { ...native, callID: part.callID || part.id, status: status2, endTime, ...executionFields(state2.input, state2.metadata), partial: Boolean(state2.metadata?.truncated) };
|
|
3420
3361
|
events.push(eventFor(message2, `${id2}:call`, "tool_call", part.name || "Tool call", "", { ...common, ...timing, input: eventText(state2.input) }));
|
|
3421
3362
|
if (["completed", "error"].includes(state2.status)) events.push(eventFor(message2, `${id2}:result`, "tool_result", part.name || "Tool result", "", { ...common, role: "tool", ...endTime ? { time: endTime, timeSource: "recorded" } : {}, output: eventText(state2.error ?? state2.content, 64e3) }));
|
|
3422
3363
|
} else events.push(eventFor(message2, id2, "event", `${part.type || "Unknown"} content`, "Unsupported content.", { ...native, ...timing, partial: true }));
|
|
@@ -3427,6 +3368,639 @@ function opencodeEvents(raw, message2) {
|
|
|
3427
3368
|
return events;
|
|
3428
3369
|
}
|
|
3429
3370
|
|
|
3371
|
+
// server/adapters/harness-paths.ts
|
|
3372
|
+
import { homedir as homedir3 } from "node:os";
|
|
3373
|
+
import { join as join3 } from "node:path";
|
|
3374
|
+
|
|
3375
|
+
// server/source-paths.ts
|
|
3376
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3377
|
+
var paths = new AsyncLocalStorage();
|
|
3378
|
+
var sourcePath = (id2) => paths.getStore()?.[id2];
|
|
3379
|
+
function withSourcePaths(adapter, configured) {
|
|
3380
|
+
return {
|
|
3381
|
+
...adapter,
|
|
3382
|
+
detect: () => paths.run(configured(), () => adapter.detect()),
|
|
3383
|
+
discover: () => paths.run(configured(), async () => {
|
|
3384
|
+
const result = await adapter.discover();
|
|
3385
|
+
if (!sourcePath(adapter.id)) return result;
|
|
3386
|
+
return { ...result, sessions: result.sessions.map((candidate) => ({ ...candidate, session: { ...candidate.session, nativeResume: false } })) };
|
|
3387
|
+
}),
|
|
3388
|
+
read: (candidate, cursor) => paths.run(configured(), async () => {
|
|
3389
|
+
const result = await adapter.read(candidate, cursor);
|
|
3390
|
+
if (sourcePath(adapter.id)) candidate.session.nativeResume = false;
|
|
3391
|
+
return result;
|
|
3392
|
+
})
|
|
3393
|
+
};
|
|
3394
|
+
}
|
|
3395
|
+
|
|
3396
|
+
// server/adapters/harness-paths.ts
|
|
3397
|
+
var homePath = (...parts) => join3(homedir3(), ...parts);
|
|
3398
|
+
var dataPath = (...parts) => join3(process.env.XDG_DATA_HOME || homePath(".local/share"), ...parts);
|
|
3399
|
+
var configPath = (...parts) => join3(process.env.XDG_CONFIG_HOME || homePath(".config"), ...parts);
|
|
3400
|
+
var appPath = (...parts) => join3(process.platform === "darwin" ? homePath("Library/Application Support") : process.platform === "win32" ? process.env.APPDATA || homePath("AppData/Roaming") : process.env.XDG_CONFIG_HOME || homePath(".config"), ...parts);
|
|
3401
|
+
var tokscalePath = (...parts) => join3(process.env.TOKSCALE_CONFIG_DIR || (process.platform === "win32" ? appPath("tokscale") : configPath("tokscale")), ...parts);
|
|
3402
|
+
var envHome = (env2, fallback, ...parts) => join3(process.env[env2]?.trim() || homePath(fallback), ...parts);
|
|
3403
|
+
var harnessRoots = (id2, defaults) => () => {
|
|
3404
|
+
const override = sourcePath(id2) || process.env[`SESSIONGRAPH_${id2.replace(/-/g, "_").toUpperCase()}_HISTORY_DIR`]?.trim();
|
|
3405
|
+
return override ? [override] : defaults();
|
|
3406
|
+
};
|
|
3407
|
+
|
|
3408
|
+
// server/adapters/sqlite-histories.ts
|
|
3409
|
+
import { lstat as lstat2 } from "node:fs/promises";
|
|
3410
|
+
|
|
3411
|
+
// server/adapters/local-files.ts
|
|
3412
|
+
import { constants } from "node:fs";
|
|
3413
|
+
import { lstat, open, readdir } from "node:fs/promises";
|
|
3414
|
+
import { join as join4, relative } from "node:path";
|
|
3415
|
+
|
|
3416
|
+
// server/adapters/compressed.ts
|
|
3417
|
+
import { gunzipSync, zstdDecompressSync } from "node:zlib";
|
|
3418
|
+
function expandHistory(buffer, maxOutputLength) {
|
|
3419
|
+
if (buffer.length >= 4 && buffer.readUInt32LE(0) === 4247762216) return zstdDecompressSync(buffer, { maxOutputLength });
|
|
3420
|
+
if (buffer[0] === 31 && buffer[1] === 139) return gunzipSync(buffer, { maxOutputLength });
|
|
3421
|
+
if (buffer.length > maxOutputLength) throw new Error("Expanded history exceeds the snapshot limit.");
|
|
3422
|
+
return buffer;
|
|
3423
|
+
}
|
|
3424
|
+
|
|
3425
|
+
// server/adapters/local-files.ts
|
|
3426
|
+
var object3 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
3427
|
+
var text = (value) => typeof value === "string" ? value : "";
|
|
3428
|
+
var time = (value) => {
|
|
3429
|
+
const n = typeof value === "number" ? value : typeof value === "string" ? /^\d{13}$/.test(value) ? Number(value) : Date.parse(value) : 0;
|
|
3430
|
+
return Number.isFinite(n) && n > 0 && n <= 864e13 ? n : 0;
|
|
3431
|
+
};
|
|
3432
|
+
var MAX_BYTES = 32e6;
|
|
3433
|
+
var MAX_RECORDS = 5e4;
|
|
3434
|
+
var MAX_FILES = 2e4;
|
|
3435
|
+
async function fileState(path) {
|
|
3436
|
+
try {
|
|
3437
|
+
const s = await lstat(path);
|
|
3438
|
+
if (!s.isFile()) throw new Error("History must be a regular file, not a symlink.");
|
|
3439
|
+
if (s.size > MAX_BYTES) throw new Error("History exceeds the 32 MB per-file limit.");
|
|
3440
|
+
return { path, signature: digest([s.size, s.mtimeMs, s.ctimeMs, s.ino]), created: s.birthtimeMs || s.mtimeMs, updated: s.mtimeMs, size: s.size };
|
|
3441
|
+
} catch (error) {
|
|
3442
|
+
if (error.code === "ENOENT") return { path, signature: "missing", created: 0, updated: 0, size: 0 };
|
|
3443
|
+
throw error;
|
|
3444
|
+
}
|
|
3445
|
+
}
|
|
3446
|
+
async function historyFiles(roots2, match2) {
|
|
3447
|
+
const files = [], queue = [];
|
|
3448
|
+
const warnings = [];
|
|
3449
|
+
for (const root3 of new Set(roots2)) {
|
|
3450
|
+
try {
|
|
3451
|
+
if ((await lstat(root3)).isDirectory()) queue.push({ root: root3, path: root3, depth: 0 });
|
|
3452
|
+
} catch (error) {
|
|
3453
|
+
if (error.code !== "ENOENT") warnings.push("A history directory could not be read.");
|
|
3454
|
+
}
|
|
3455
|
+
}
|
|
3456
|
+
let entriesSeen = 0, limited = false;
|
|
3457
|
+
for (let i = 0; i < queue.length && files.length < MAX_FILES && entriesSeen < 1e5; i++) {
|
|
3458
|
+
const { root: root3, path, depth } = queue[i];
|
|
3459
|
+
let entries2;
|
|
3460
|
+
try {
|
|
3461
|
+
entries2 = await readdir(path, { withFileTypes: true });
|
|
3462
|
+
} catch {
|
|
3463
|
+
warnings.push("A history directory could not be read.");
|
|
3464
|
+
continue;
|
|
3465
|
+
}
|
|
3466
|
+
for (const entry of entries2) {
|
|
3467
|
+
if (++entriesSeen > 1e5 || files.length >= MAX_FILES) {
|
|
3468
|
+
limited = true;
|
|
3469
|
+
break;
|
|
3470
|
+
}
|
|
3471
|
+
const file = join4(path, entry.name);
|
|
3472
|
+
if (entry.isDirectory()) {
|
|
3473
|
+
if (depth < 6 && queue.length < MAX_FILES) queue.push({ root: root3, path: file, depth: depth + 1 });
|
|
3474
|
+
else limited = true;
|
|
3475
|
+
}
|
|
3476
|
+
if (entry.isFile() && match2(relative(root3, file).split("\\").join("/"))) files.push(file);
|
|
3477
|
+
}
|
|
3478
|
+
}
|
|
3479
|
+
if (limited) warnings.push("History discovery reached its file, directory, or depth limit.");
|
|
3480
|
+
return { files: [...new Set(files)].sort(), warnings };
|
|
3481
|
+
}
|
|
3482
|
+
function json3(value) {
|
|
3483
|
+
return JSON.parse(value);
|
|
3484
|
+
}
|
|
3485
|
+
function jsonLines(value) {
|
|
3486
|
+
const rows2 = [];
|
|
3487
|
+
let partial = false;
|
|
3488
|
+
for (const line of value.split("\n")) {
|
|
3489
|
+
if (!line.trim()) continue;
|
|
3490
|
+
if (rows2.length >= MAX_RECORDS) throw new Error("History exceeds the 50,000-record limit.");
|
|
3491
|
+
if (line.length > 2e6) throw new Error("History contains a record larger than 2 MB.");
|
|
3492
|
+
try {
|
|
3493
|
+
const row = json3(line);
|
|
3494
|
+
if (!row || typeof row !== "object" || Array.isArray(row)) partial = true;
|
|
3495
|
+
else rows2.push(row);
|
|
3496
|
+
} catch {
|
|
3497
|
+
partial = true;
|
|
3498
|
+
}
|
|
3499
|
+
}
|
|
3500
|
+
return { rows: rows2, partial };
|
|
3501
|
+
}
|
|
3502
|
+
function localFileAdapter(source) {
|
|
3503
|
+
const metadata2 = /* @__PURE__ */ new Map();
|
|
3504
|
+
let cached2;
|
|
3505
|
+
const states = (path) => Promise.all([path, ...source.extras?.(path) || []].map(fileState));
|
|
3506
|
+
const revision2 = (values) => digest([1, ...values.filter((_, i) => i === 0 || source.revisionExtras !== false).map((s) => [s.path, s.signature])]);
|
|
3507
|
+
async function load(path, expected, before) {
|
|
3508
|
+
if (revision2(before) !== expected) throw new Error("Session changed during import; import again.");
|
|
3509
|
+
if (cached2?.path === path && cached2.revision === expected) return cached2.history;
|
|
3510
|
+
if (before[0].signature === "missing") throw new Error("History file is unavailable.");
|
|
3511
|
+
if (before.reduce((n, s) => n + s.size, 0) > MAX_BYTES) throw new Error("Combined history exceeds the 32 MB snapshot limit.");
|
|
3512
|
+
const files = /* @__PURE__ */ new Map();
|
|
3513
|
+
let expanded = 0;
|
|
3514
|
+
for (const s of before.filter((s2) => s2.signature !== "missing")) {
|
|
3515
|
+
const handle = await open(s.path, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
|
|
3516
|
+
try {
|
|
3517
|
+
const buffer = Buffer.alloc(s.size + 1);
|
|
3518
|
+
let bytes2 = 0;
|
|
3519
|
+
while (bytes2 < buffer.length) {
|
|
3520
|
+
const part = await handle.read(buffer, bytes2, buffer.length - bytes2, bytes2);
|
|
3521
|
+
if (!part.bytesRead) break;
|
|
3522
|
+
bytes2 += part.bytesRead;
|
|
3523
|
+
}
|
|
3524
|
+
if (bytes2 !== s.size) throw new Error("History changed while reading; import again.");
|
|
3525
|
+
const data = expandHistory(buffer.subarray(0, bytes2), MAX_BYTES);
|
|
3526
|
+
expanded += data.length;
|
|
3527
|
+
if (expanded > MAX_BYTES) throw new Error("Expanded history exceeds the 32 MB snapshot limit.");
|
|
3528
|
+
files.set(s.path, data.toString("utf8"));
|
|
3529
|
+
} finally {
|
|
3530
|
+
await handle.close();
|
|
3531
|
+
}
|
|
3532
|
+
}
|
|
3533
|
+
if (digest(await states(path)) !== digest(before)) throw new Error("History changed while reading; import again.");
|
|
3534
|
+
const history = source.parse(path, files);
|
|
3535
|
+
if (!history) return;
|
|
3536
|
+
if (source.capabilities.history && !history.messages.length) throw new Error("No readable conversation.");
|
|
3537
|
+
if (!history.nativeID || history.nativeID.length > 512) throw new Error("History has no supported native session identity.");
|
|
3538
|
+
if (history.messages.length > MAX_RECORDS) throw new Error("History exceeds the 50,000-message limit.");
|
|
3539
|
+
cached2 = { path, revision: expected, history };
|
|
3540
|
+
return history;
|
|
3541
|
+
}
|
|
3542
|
+
return {
|
|
3543
|
+
id: source.id,
|
|
3544
|
+
name: source.name,
|
|
3545
|
+
description: source.description,
|
|
3546
|
+
capabilities: source.capabilities,
|
|
3547
|
+
async detect() {
|
|
3548
|
+
for (const root3 of source.roots()) if ((await lstat(root3).catch(() => void 0))?.isDirectory()) return true;
|
|
3549
|
+
return false;
|
|
3550
|
+
},
|
|
3551
|
+
async discover() {
|
|
3552
|
+
const listing = await historyFiles(source.roots(), source.match), found = /* @__PURE__ */ new Map();
|
|
3553
|
+
let failed = 0;
|
|
3554
|
+
const blocked = /* @__PURE__ */ new Set(), unreadable = /* @__PURE__ */ new Set();
|
|
3555
|
+
for (const path of listing.files) {
|
|
3556
|
+
try {
|
|
3557
|
+
const before = await states(path), rev = revision2(before);
|
|
3558
|
+
let candidate = metadata2.get(path);
|
|
3559
|
+
if (!candidate || candidate.revision !== rev) {
|
|
3560
|
+
const history = await load(path, rev, before);
|
|
3561
|
+
if (!history) {
|
|
3562
|
+
const nativeID = source.authoritativeIdentity?.(path);
|
|
3563
|
+
if (nativeID) blocked.add(identity(source.id, nativeID));
|
|
3564
|
+
continue;
|
|
3565
|
+
}
|
|
3566
|
+
const session = { ...blankSession(source.id, history.nativeID), ...history.session };
|
|
3567
|
+
session.id = identity(source.id, history.nativeID);
|
|
3568
|
+
session.nativeID = history.nativeID;
|
|
3569
|
+
session.source = source.id;
|
|
3570
|
+
session.directory = text(session.directory);
|
|
3571
|
+
session.projectID = project(source.id, session.directory).id;
|
|
3572
|
+
session.created = time(session.created) || history.messages.map((m) => time(m.time)).find(Boolean) || before[0].created;
|
|
3573
|
+
session.updated = before[0].updated;
|
|
3574
|
+
session.agent ||= source.name;
|
|
3575
|
+
session.parentID = history.parent ? identity(source.id, history.parent) : void 0;
|
|
3576
|
+
session.forkID = history.fork ? identity(source.id, history.fork) : void 0;
|
|
3577
|
+
if (session.title === "Untitled session" || !session.title) session.title = history.messages.flatMap((m) => m.role === "user" ? m.fragments.filter((f) => f.kind === "You").map((f) => f.text) : []).find(Boolean)?.replace(/\s+/g, " ").slice(0, 180) || `${source.name} session`;
|
|
3578
|
+
candidate = { session, revision: rev, locator: { path } };
|
|
3579
|
+
metadata2.set(path, candidate);
|
|
3580
|
+
}
|
|
3581
|
+
const previous = found.get(candidate.session.id);
|
|
3582
|
+
const preferred = candidate.locator.path.endsWith(".jsonl"), previousPreferred = previous?.locator.path.endsWith(".jsonl");
|
|
3583
|
+
if (!previous || preferred && !previousPreferred || preferred === previousPreferred && candidate.session.updated > previous.session.updated) found.set(candidate.session.id, candidate);
|
|
3584
|
+
} catch {
|
|
3585
|
+
const nativeID = source.authoritativeIdentity?.(path);
|
|
3586
|
+
if (nativeID) {
|
|
3587
|
+
const id2 = identity(source.id, nativeID);
|
|
3588
|
+
blocked.add(id2);
|
|
3589
|
+
unreadable.add(id2);
|
|
3590
|
+
} else failed++;
|
|
3591
|
+
}
|
|
3592
|
+
}
|
|
3593
|
+
const listed = new Set(listing.files);
|
|
3594
|
+
for (const path of metadata2.keys()) if (!listed.has(path)) metadata2.delete(path);
|
|
3595
|
+
if (failed) listing.warnings.push(`${source.name}: Skipped ${failed} unreadable, changing, unsupported, or oversized ${failed === 1 ? "history file" : "history files"}.`);
|
|
3596
|
+
const sessions = [...found.values()].filter((c) => !blocked.has(c.session.id));
|
|
3597
|
+
const errors = unreadable.size ? [`${source.name}: Could not read history for ${unreadable.size} ${unreadable.size === 1 ? "session" : "sessions"}.`] : void 0;
|
|
3598
|
+
return { sessions, projects: [...new Map(sessions.map((c) => {
|
|
3599
|
+
const p = project(source.id, c.session.directory);
|
|
3600
|
+
return [p.id, p];
|
|
3601
|
+
})).values()], warnings: listing.warnings, errors, blocked: [...blocked] };
|
|
3602
|
+
},
|
|
3603
|
+
async read(candidate, cursor) {
|
|
3604
|
+
const offset = cursor === void 0 ? 0 : Number(cursor);
|
|
3605
|
+
if (!Number.isSafeInteger(offset) || offset < 0) throw new Error("Invalid history cursor.");
|
|
3606
|
+
const history = await load(candidate.locator.path, candidate.revision, await states(candidate.locator.path));
|
|
3607
|
+
if (!history) throw new Error("History representation is no longer available.");
|
|
3608
|
+
const messages = history.messages.slice(offset, offset + 100);
|
|
3609
|
+
return {
|
|
3610
|
+
messages,
|
|
3611
|
+
cursor: offset + messages.length < history.messages.length ? String(offset + messages.length) : void 0,
|
|
3612
|
+
partial: Boolean(history.partial || messages.some((m) => m.partial)),
|
|
3613
|
+
note: history.note
|
|
3614
|
+
};
|
|
3615
|
+
}
|
|
3616
|
+
};
|
|
3617
|
+
}
|
|
3618
|
+
|
|
3619
|
+
// server/adapters/sqlite-snapshot.ts
|
|
3620
|
+
import { DatabaseSync } from "node:sqlite";
|
|
3621
|
+
import { chmodSync, constants as constants2, copyFileSync, lstatSync, mkdtempSync, rmSync } from "node:fs";
|
|
3622
|
+
import { copyFile, statfs } from "node:fs/promises";
|
|
3623
|
+
import { tmpdir } from "node:os";
|
|
3624
|
+
import { join as join5 } from "node:path";
|
|
3625
|
+
var copies = /* @__PURE__ */ new Map();
|
|
3626
|
+
var SqliteSnapshotChangedError = class extends Error {
|
|
3627
|
+
};
|
|
3628
|
+
var SqliteSnapshotFileError = class extends Error {
|
|
3629
|
+
};
|
|
3630
|
+
var close = (path) => {
|
|
3631
|
+
const copy = copies.get(path);
|
|
3632
|
+
if (!copy) return;
|
|
3633
|
+
copies.delete(path);
|
|
3634
|
+
try {
|
|
3635
|
+
copy.db.close();
|
|
3636
|
+
} finally {
|
|
3637
|
+
rmSync(copy.directory, { recursive: true, force: true });
|
|
3638
|
+
}
|
|
3639
|
+
};
|
|
3640
|
+
process.once("exit", () => {
|
|
3641
|
+
for (const path of copies.keys()) close(path);
|
|
3642
|
+
});
|
|
3643
|
+
function snapshotFiles(path, large) {
|
|
3644
|
+
return [path, `${path}-wal`].map((file, i) => {
|
|
3645
|
+
try {
|
|
3646
|
+
const s = lstatSync(file);
|
|
3647
|
+
const kind = i ? "History database WAL" : "History database";
|
|
3648
|
+
if (!s.isFile()) throw new SqliteSnapshotFileError(`${kind} is not a regular file.`);
|
|
3649
|
+
if (!large && s.size > 8e9) throw new SqliteSnapshotFileError(`${kind} exceeds 8 GB.`);
|
|
3650
|
+
return s;
|
|
3651
|
+
} catch (error) {
|
|
3652
|
+
if (i && error.code === "ENOENT") return null;
|
|
3653
|
+
throw error;
|
|
3654
|
+
}
|
|
3655
|
+
});
|
|
3656
|
+
}
|
|
3657
|
+
var fingerprint = (path, files) => digest([path, ...files.map((s) => s && [s.dev, s.ino, s.size, s.mtimeMs, s.ctimeMs])]);
|
|
3658
|
+
function sqliteRevision(path) {
|
|
3659
|
+
return fingerprint(path, snapshotFiles(path, false));
|
|
3660
|
+
}
|
|
3661
|
+
function openSnapshot(destination) {
|
|
3662
|
+
const db2 = new DatabaseSync(destination, { readOnly: true, enableDoubleQuotedStringLiterals: false, allowExtension: false });
|
|
3663
|
+
try {
|
|
3664
|
+
db2.exec("PRAGMA query_only=ON; PRAGMA trusted_schema=OFF; PRAGMA busy_timeout=1000; BEGIN;");
|
|
3665
|
+
return db2;
|
|
3666
|
+
} catch (error) {
|
|
3667
|
+
db2.close();
|
|
3668
|
+
throw error;
|
|
3669
|
+
}
|
|
3670
|
+
}
|
|
3671
|
+
async function withLargeSqliteSnapshot(path, read3, expected) {
|
|
3672
|
+
const retained = copies.get(path);
|
|
3673
|
+
if (expected && retained?.revision === expected) return read3(retained.db, expected);
|
|
3674
|
+
const files = snapshotFiles(path, true), revision2 = fingerprint(path, files);
|
|
3675
|
+
if (expected && revision2 !== expected) throw new SqliteSnapshotChangedError("History database changed during import; import again.");
|
|
3676
|
+
if (retained?.revision === revision2) {
|
|
3677
|
+
const result = read3(retained.db, revision2);
|
|
3678
|
+
if (fingerprint(path, snapshotFiles(path, true)) !== revision2) throw new SqliteSnapshotChangedError("History database changed during reading; import again.");
|
|
3679
|
+
return result;
|
|
3680
|
+
}
|
|
3681
|
+
close(path);
|
|
3682
|
+
while (copies.size >= 2) close(copies.keys().next().value);
|
|
3683
|
+
const directory3 = mkdtempSync(join5(tmpdir(), "sessiongraph-history-"));
|
|
3684
|
+
const destination = join5(directory3, "history.db");
|
|
3685
|
+
let db2;
|
|
3686
|
+
try {
|
|
3687
|
+
for (const [index, suffix] of ["", "-wal"].entries()) {
|
|
3688
|
+
const file = files[index];
|
|
3689
|
+
if (!file) continue;
|
|
3690
|
+
try {
|
|
3691
|
+
await copyFile(path + suffix, destination + suffix, constants2.COPYFILE_FICLONE_FORCE);
|
|
3692
|
+
} catch (error) {
|
|
3693
|
+
if (!["ENOSYS", "ENOTSUP", "EOPNOTSUPP", "EXDEV", "EINVAL"].includes(error.code || "")) throw error;
|
|
3694
|
+
const { bavail, bsize } = await statfs(directory3);
|
|
3695
|
+
const reserve = 512 * 1024 * 1024;
|
|
3696
|
+
if (bavail * bsize < file.size + reserve) throw new Error("Not enough free space for the T3 history snapshot. Free space on the temporary drive and retry.");
|
|
3697
|
+
await copyFile(path + suffix, destination + suffix);
|
|
3698
|
+
}
|
|
3699
|
+
chmodSync(destination + suffix, 384);
|
|
3700
|
+
}
|
|
3701
|
+
if (fingerprint(path, snapshotFiles(path, true)) !== revision2) throw new SqliteSnapshotChangedError("History database changed while copying; import again.");
|
|
3702
|
+
db2 = openSnapshot(destination);
|
|
3703
|
+
const result = read3(db2, revision2);
|
|
3704
|
+
if (!expected && fingerprint(path, snapshotFiles(path, true)) !== revision2) throw new SqliteSnapshotChangedError("History database changed during reading; import again.");
|
|
3705
|
+
close(path);
|
|
3706
|
+
while (copies.size >= 2) close(copies.keys().next().value);
|
|
3707
|
+
copies.set(path, { revision: revision2, directory: directory3, db: db2 });
|
|
3708
|
+
return result;
|
|
3709
|
+
} catch (error) {
|
|
3710
|
+
try {
|
|
3711
|
+
db2?.close();
|
|
3712
|
+
} finally {
|
|
3713
|
+
rmSync(directory3, { recursive: true, force: true });
|
|
3714
|
+
}
|
|
3715
|
+
if (error.code === "ENOENT" && fingerprint(path, snapshotFiles(path, true)) !== revision2)
|
|
3716
|
+
throw new SqliteSnapshotChangedError("History database changed while copying; import again.");
|
|
3717
|
+
throw error;
|
|
3718
|
+
}
|
|
3719
|
+
}
|
|
3720
|
+
function withSqliteSnapshot(path, read3, expected, pinned = false) {
|
|
3721
|
+
const retained = copies.get(path);
|
|
3722
|
+
if (pinned && expected && retained?.revision === expected) return read3(retained.db);
|
|
3723
|
+
const revision2 = sqliteRevision(path);
|
|
3724
|
+
if (expected && revision2 !== expected) throw new SqliteSnapshotChangedError("History database changed during import; import again.");
|
|
3725
|
+
let copy = copies.get(path);
|
|
3726
|
+
if (copy?.revision !== revision2) {
|
|
3727
|
+
close(path);
|
|
3728
|
+
while (copies.size >= 2) close(copies.keys().next().value);
|
|
3729
|
+
const directory3 = mkdtempSync(join5(tmpdir(), "sessiongraph-history-"));
|
|
3730
|
+
let db2;
|
|
3731
|
+
try {
|
|
3732
|
+
chmodSync(directory3, 448);
|
|
3733
|
+
const destination = join5(directory3, "history.db");
|
|
3734
|
+
for (const suffix of ["", "-wal"]) {
|
|
3735
|
+
try {
|
|
3736
|
+
copyFileSync(path + suffix, destination + suffix, constants2.COPYFILE_FICLONE);
|
|
3737
|
+
chmodSync(destination + suffix, 384);
|
|
3738
|
+
} catch (error) {
|
|
3739
|
+
if (suffix && error.code === "ENOENT") continue;
|
|
3740
|
+
throw error;
|
|
3741
|
+
}
|
|
3742
|
+
}
|
|
3743
|
+
if (sqliteRevision(path) !== revision2) throw new SqliteSnapshotChangedError("History database changed while copying; import again.");
|
|
3744
|
+
db2 = openSnapshot(destination);
|
|
3745
|
+
copy = { revision: revision2, directory: directory3, db: db2 };
|
|
3746
|
+
copies.set(path, copy);
|
|
3747
|
+
} catch (error) {
|
|
3748
|
+
try {
|
|
3749
|
+
db2?.close();
|
|
3750
|
+
} finally {
|
|
3751
|
+
rmSync(directory3, { recursive: true, force: true });
|
|
3752
|
+
}
|
|
3753
|
+
throw error;
|
|
3754
|
+
}
|
|
3755
|
+
}
|
|
3756
|
+
const result = read3(copy.db);
|
|
3757
|
+
if (!pinned && sqliteRevision(path) !== revision2) throw new SqliteSnapshotChangedError("History database changed during reading; import again.");
|
|
3758
|
+
return result;
|
|
3759
|
+
}
|
|
3760
|
+
function hasTable(db2, name) {
|
|
3761
|
+
const row = db2.prepare("SELECT sql FROM sqlite_master WHERE type='table' AND name=?").get(name);
|
|
3762
|
+
return typeof row?.sql === "string" && !/CREATE\s+VIRTUAL/i.test(row.sql);
|
|
3763
|
+
}
|
|
3764
|
+
|
|
3765
|
+
// server/adapters/sqlite-histories.ts
|
|
3766
|
+
var budget;
|
|
3767
|
+
var rowBytes = (row) => Object.values(row).reduce((n, v3) => n + (typeof v3 === "string" ? Buffer.byteLength(v3) : v3 instanceof Uint8Array ? v3.byteLength : 8), 0);
|
|
3768
|
+
function consume(bytes2, records = 0) {
|
|
3769
|
+
if (!budget) return;
|
|
3770
|
+
budget.bytes += bytes2;
|
|
3771
|
+
budget.records += records;
|
|
3772
|
+
if (budget.bytes > 64e6 || budget.records > 5e4) throw new Error("Session exceeds the 64 MB / 50,000-record snapshot limit.");
|
|
3773
|
+
}
|
|
3774
|
+
function parseHistory(source, db2, row, path) {
|
|
3775
|
+
const previous = budget;
|
|
3776
|
+
budget = { bytes: 0, records: 0 };
|
|
3777
|
+
try {
|
|
3778
|
+
consume(rowBytes(row), 1);
|
|
3779
|
+
const history = source.parse(db2, row, path);
|
|
3780
|
+
if (history && history.messages.length > 5e4) throw new Error("Session exceeds the 50,000-message limit.");
|
|
3781
|
+
return history;
|
|
3782
|
+
} finally {
|
|
3783
|
+
budget = previous;
|
|
3784
|
+
}
|
|
3785
|
+
}
|
|
3786
|
+
function columns(db2, table) {
|
|
3787
|
+
if (!/^[a-z_][a-z0-9_]*$/.test(table) || !hasTable(db2, table)) throw new Error(`Unsupported history table: ${table}.`);
|
|
3788
|
+
return new Set(db2.prepare(`PRAGMA table_info("${table}")`).all().map((r) => String(r.name)));
|
|
3789
|
+
}
|
|
3790
|
+
function rows(db2, table, fields3, filter, order, limit = 5e4) {
|
|
3791
|
+
const available = columns(db2, table);
|
|
3792
|
+
for (const name of [...fields3, ...filter ? [filter[0]] : [], ...order ? [order] : []]) if (!/^[a-zA-Z_][\w]*$/.test(name)) throw new Error("Invalid history column.");
|
|
3793
|
+
if (filter && !available.has(filter[0])) throw new Error("Unsupported history relation.");
|
|
3794
|
+
const size = (f) => `length(CAST("${f}" AS BLOB))`;
|
|
3795
|
+
const select = fields3.map((f) => available.has(f) ? `CASE WHEN ${size(f)}<=32000000 THEN "${f}" END AS "${f}"` : `NULL AS "${f}"`).join(",");
|
|
3796
|
+
const oversized = fields3.filter((f) => available.has(f)).map((f) => `COALESCE(${size(f)},0)>32000000`).join(" OR ") || "0";
|
|
3797
|
+
const query = `SELECT ${select}, (${oversized}) AS __sessiongraph_oversized FROM "${table}"${filter ? ` WHERE "${filter[0]}"=?` : ""}${order && available.has(order) ? ` ORDER BY "${order}"` : ""} LIMIT ${limit + 1}`;
|
|
3798
|
+
const result = [];
|
|
3799
|
+
let bytes2 = 0;
|
|
3800
|
+
for (const row of db2.prepare(query).iterate(...filter ? [filter[1]] : [])) {
|
|
3801
|
+
if (row.__sessiongraph_oversized) throw new Error("History field exceeds the 32 MB snapshot limit.");
|
|
3802
|
+
delete row.__sessiongraph_oversized;
|
|
3803
|
+
const size2 = rowBytes(row);
|
|
3804
|
+
bytes2 += size2;
|
|
3805
|
+
consume(size2, 1);
|
|
3806
|
+
if (bytes2 > 64e6 || result.length >= limit) throw new Error("History exceeds the 64 MB / record-count query limit.");
|
|
3807
|
+
result.push(row);
|
|
3808
|
+
}
|
|
3809
|
+
return result;
|
|
3810
|
+
}
|
|
3811
|
+
function sqliteJSON(value) {
|
|
3812
|
+
if (value instanceof Uint8Array) {
|
|
3813
|
+
const expanded = expandHistory(Buffer.from(value), Math.max(1, Math.min(32e6, 64e6 - (budget?.bytes || 0))));
|
|
3814
|
+
consume(expanded.byteLength);
|
|
3815
|
+
return JSON.parse(expanded.toString("utf8"));
|
|
3816
|
+
}
|
|
3817
|
+
if (typeof value === "string") return JSON.parse(value);
|
|
3818
|
+
throw new Error("Missing or oversized history payload.");
|
|
3819
|
+
}
|
|
3820
|
+
function optionalJSON(value) {
|
|
3821
|
+
return value == null || value === "" ? {} : sqliteJSON(value);
|
|
3822
|
+
}
|
|
3823
|
+
function sqliteHistoryAdapter(source) {
|
|
3824
|
+
const metadata2 = /* @__PURE__ */ new Map();
|
|
3825
|
+
return {
|
|
3826
|
+
id: source.id,
|
|
3827
|
+
name: source.name,
|
|
3828
|
+
description: source.description || "Local session database",
|
|
3829
|
+
capabilities: { history: source.history !== false, forks: false, children: false, files: false },
|
|
3830
|
+
async detect() {
|
|
3831
|
+
return (await source.paths()).length > 0;
|
|
3832
|
+
},
|
|
3833
|
+
async discover() {
|
|
3834
|
+
const sessions = /* @__PURE__ */ new Map(), errors = [], blocked = [];
|
|
3835
|
+
let unavailable = false;
|
|
3836
|
+
for (const path of await source.paths()) {
|
|
3837
|
+
try {
|
|
3838
|
+
const snapshot2 = sqliteRevision(path), rev = digest([source.version || 2, source.id, snapshot2]);
|
|
3839
|
+
let cached2 = metadata2.get(path);
|
|
3840
|
+
if (!cached2 || cached2.revision !== rev) {
|
|
3841
|
+
cached2 = withSqliteSnapshot(path, (db2) => {
|
|
3842
|
+
const table = typeof source.table === "string" ? source.table : source.table(db2);
|
|
3843
|
+
const values2 = rows(db2, table, source.fields, void 0, source.key, 2e4), found = [];
|
|
3844
|
+
const blocked2 = [], errors2 = [];
|
|
3845
|
+
let failed = 0;
|
|
3846
|
+
for (const row of values2) {
|
|
3847
|
+
try {
|
|
3848
|
+
const h3 = parseHistory(source, db2, row, path);
|
|
3849
|
+
if (!h3) continue;
|
|
3850
|
+
if (source.history !== false && !h3.messages.length) {
|
|
3851
|
+
blocked2.push(identity(source.id, String(row[source.key])));
|
|
3852
|
+
continue;
|
|
3853
|
+
}
|
|
3854
|
+
if (!h3.nativeID || h3.nativeID.length > 512) throw new Error("Missing native session identity.");
|
|
3855
|
+
const created = time(h3.session?.created) || h3.messages.map((m) => time(m.time)).find(Boolean);
|
|
3856
|
+
if (!created) throw new Error("Session has no recorded creation or message date.");
|
|
3857
|
+
const session = { ...blankSession(source.id, h3.nativeID), ...h3.session, created };
|
|
3858
|
+
session.id = identity(source.id, h3.nativeID);
|
|
3859
|
+
session.nativeID = h3.nativeID;
|
|
3860
|
+
session.source = source.id;
|
|
3861
|
+
session.directory = text(session.directory);
|
|
3862
|
+
session.projectID = project(source.id, session.directory).id;
|
|
3863
|
+
session.agent ||= source.name;
|
|
3864
|
+
session.updated ||= created;
|
|
3865
|
+
session.parentID = h3.parent ? identity(source.id, h3.parent) : void 0;
|
|
3866
|
+
session.forkID = h3.fork ? identity(source.id, h3.fork) : void 0;
|
|
3867
|
+
if (!session.title || session.title === "Untitled session") session.title = h3.messages.flatMap((m) => m.role === "user" ? m.fragments.filter((f) => f.kind === "You").map((f) => f.text) : []).find(Boolean)?.replace(/\s+/g, " ").slice(0, 180) || `${source.name} session`;
|
|
3868
|
+
found.push({ session, revision: rev, locator: { path, snapshot: snapshot2, table, key: String(row[source.key]) } });
|
|
3869
|
+
} catch {
|
|
3870
|
+
blocked2.push(identity(source.id, String(row[source.key])));
|
|
3871
|
+
failed++;
|
|
3872
|
+
}
|
|
3873
|
+
}
|
|
3874
|
+
if (failed) errors2.push(`${source.name}: Skipped ${failed} unreadable, undated, unsupported, or oversized ${failed === 1 ? "session" : "sessions"}.`);
|
|
3875
|
+
return { revision: rev, candidates: found, blocked: blocked2, errors: errors2 };
|
|
3876
|
+
}, snapshot2);
|
|
3877
|
+
metadata2.set(path, cached2);
|
|
3878
|
+
}
|
|
3879
|
+
errors.push(...cached2.errors);
|
|
3880
|
+
blocked.push(...cached2.blocked);
|
|
3881
|
+
for (const c of cached2.candidates) {
|
|
3882
|
+
const old = sessions.get(c.session.id);
|
|
3883
|
+
if (!old || c.session.updated > old.session.updated) sessions.set(c.session.id, c);
|
|
3884
|
+
}
|
|
3885
|
+
} catch (error) {
|
|
3886
|
+
unavailable = true;
|
|
3887
|
+
const detail = error instanceof SqliteSnapshotFileError || error instanceof SqliteSnapshotChangedError ? error.message : "Could not read a history database.";
|
|
3888
|
+
errors.push(`${source.name}: ${detail}`);
|
|
3889
|
+
}
|
|
3890
|
+
}
|
|
3891
|
+
const values = [...sessions.values()];
|
|
3892
|
+
return { sessions: values, projects: [...new Map(values.map((c) => {
|
|
3893
|
+
const p = project(source.id, c.session.directory);
|
|
3894
|
+
return [p.id, p];
|
|
3895
|
+
})).values()], warnings: [], errors, blocked, unavailable };
|
|
3896
|
+
},
|
|
3897
|
+
async read(candidate, cursor) {
|
|
3898
|
+
if (cursor) throw new Error("Invalid SQLite history cursor.");
|
|
3899
|
+
const { path, snapshot: snapshot2, key } = candidate.locator;
|
|
3900
|
+
return withSqliteSnapshot(path, (db2) => {
|
|
3901
|
+
const table = typeof source.table === "string" ? source.table : source.table(db2);
|
|
3902
|
+
const row = rows(db2, table, source.fields, [source.key, key], void 0, 1)[0];
|
|
3903
|
+
if (!row) throw new Error("Session metadata is unavailable.");
|
|
3904
|
+
const history = parseHistory(source, db2, row, path);
|
|
3905
|
+
if (!history || history.nativeID !== candidate.session.nativeID) throw new Error("Session identity changed.");
|
|
3906
|
+
if (source.history !== false && !history.messages.length) throw new Error("No readable conversation.");
|
|
3907
|
+
return { messages: history.messages, partial: Boolean(history.partial || history.messages.some((m) => m.partial)), note: history.note };
|
|
3908
|
+
}, snapshot2);
|
|
3909
|
+
}
|
|
3910
|
+
};
|
|
3911
|
+
}
|
|
3912
|
+
async function existingDatabases(paths2) {
|
|
3913
|
+
const found = [];
|
|
3914
|
+
for (const path of new Set(paths2)) {
|
|
3915
|
+
try {
|
|
3916
|
+
if ((await lstat2(path)).isFile()) found.push(path);
|
|
3917
|
+
} catch (e10) {
|
|
3918
|
+
if (e10.code !== "ENOENT") throw e10;
|
|
3919
|
+
}
|
|
3920
|
+
}
|
|
3921
|
+
return found;
|
|
3922
|
+
}
|
|
3923
|
+
function combineAdapters(parts) {
|
|
3924
|
+
const first = parts[0];
|
|
3925
|
+
return {
|
|
3926
|
+
...first,
|
|
3927
|
+
async detect() {
|
|
3928
|
+
for (const p of parts) if (await p.detect().catch(() => false)) return true;
|
|
3929
|
+
return false;
|
|
3930
|
+
},
|
|
3931
|
+
async discover() {
|
|
3932
|
+
const sessions = /* @__PURE__ */ new Map(), projects = /* @__PURE__ */ new Map(), warnings = [], errors = [], blocked = /* @__PURE__ */ new Set();
|
|
3933
|
+
for (const [i, part] of parts.entries()) {
|
|
3934
|
+
let result;
|
|
3935
|
+
try {
|
|
3936
|
+
if (!await part.detect()) continue;
|
|
3937
|
+
result = await part.discover();
|
|
3938
|
+
} catch {
|
|
3939
|
+
errors.push(`${part.name}: Could not read a history source.`);
|
|
3940
|
+
break;
|
|
3941
|
+
}
|
|
3942
|
+
warnings.push(...result.warnings);
|
|
3943
|
+
if (result.errors?.length) errors.push(...result.errors);
|
|
3944
|
+
else if (result.unavailable) errors.push(`${part.name}: History unavailable.`);
|
|
3945
|
+
for (const id2 of result.blocked || []) blocked.add(id2);
|
|
3946
|
+
for (const p of result.projects) projects.set(p.id, p);
|
|
3947
|
+
for (const c of result.sessions) if (!blocked.has(c.session.id) && !sessions.has(c.session.id)) sessions.set(c.session.id, { ...c, revision: digest([i, c.revision]), locator: { ...c.locator, representation: String(i), originalRevision: c.revision } });
|
|
3948
|
+
if (result.unavailable) break;
|
|
3949
|
+
}
|
|
3950
|
+
return { sessions: [...sessions.values()], projects: [...projects.values()], warnings, errors };
|
|
3951
|
+
},
|
|
3952
|
+
async read(candidate, cursor) {
|
|
3953
|
+
const index = Number(candidate.locator.representation);
|
|
3954
|
+
if (!Number.isInteger(index) || !parts[index]) throw new Error("Invalid history representation.");
|
|
3955
|
+
return parts[index].read({ ...candidate, revision: candidate.locator.originalRevision }, cursor);
|
|
3956
|
+
}
|
|
3957
|
+
};
|
|
3958
|
+
}
|
|
3959
|
+
|
|
3960
|
+
// server/adapters/opencode-v1.ts
|
|
3961
|
+
function openCodeV1Message(body2, parts) {
|
|
3962
|
+
const content = [], files = [];
|
|
3963
|
+
let start, end;
|
|
3964
|
+
for (const part of parts) {
|
|
3965
|
+
if (part.type === "step-start") {
|
|
3966
|
+
start = text(part.snapshot) || void 0;
|
|
3967
|
+
continue;
|
|
3968
|
+
}
|
|
3969
|
+
if (part.type === "step-finish") {
|
|
3970
|
+
end = text(part.snapshot) || void 0;
|
|
3971
|
+
continue;
|
|
3972
|
+
}
|
|
3973
|
+
if (part.type === "patch") {
|
|
3974
|
+
files.push(...Array.isArray(part.files) ? part.files.filter((value) => typeof value === "string") : []);
|
|
3975
|
+
continue;
|
|
3976
|
+
}
|
|
3977
|
+
if (part.type === "snapshot") continue;
|
|
3978
|
+
const timing = object3(part.time), state2 = object3(part.state), toolTime = object3(state2.time);
|
|
3979
|
+
content.push(part.type === "tool" ? {
|
|
3980
|
+
...part,
|
|
3981
|
+
name: part.tool,
|
|
3982
|
+
time: { created: toolTime.start, completed: toolTime.end },
|
|
3983
|
+
state: {
|
|
3984
|
+
...state2,
|
|
3985
|
+
content: typeof state2.output === "string" ? [{ type: "text", text: state2.output }] : [],
|
|
3986
|
+
metadata: { ...object3(state2.metadata), cwd: state2.metadata?.cwd || body2.path?.cwd }
|
|
3987
|
+
}
|
|
3988
|
+
} : { ...part, time: { created: timing.start, completed: timing.end } });
|
|
3989
|
+
}
|
|
3990
|
+
const prompt = parts.filter((part) => part.type === "text").map((part) => text(part.text)).join("\n");
|
|
3991
|
+
const type = body2.role === "user" && !prompt && parts.some((part) => part.type === "compaction") ? "compaction" : body2.role;
|
|
3992
|
+
return {
|
|
3993
|
+
...body2,
|
|
3994
|
+
type,
|
|
3995
|
+
cwd: body2.path?.cwd,
|
|
3996
|
+
model: body2.role === "assistant" ? { id: body2.modelID, providerID: body2.providerID } : { ...object3(body2.model), id: body2.model?.modelID },
|
|
3997
|
+
text: body2.role === "user" ? prompt : void 0,
|
|
3998
|
+
files: parts.filter((part) => part.type === "file").map((part) => ({ name: part.filename, uri: part.url })),
|
|
3999
|
+
content: body2.role === "user" ? [] : content,
|
|
4000
|
+
snapshot: files.length || start || end ? { files, start, end } : void 0
|
|
4001
|
+
};
|
|
4002
|
+
}
|
|
4003
|
+
|
|
3430
4004
|
// server/adapters/opencode.ts
|
|
3431
4005
|
function openCodeMessage(raw, sessionID) {
|
|
3432
4006
|
const content = extractContent([raw]), detail = summarizeMessages(sessionID, [raw], null);
|
|
@@ -3446,46 +4020,231 @@ function openCodeMessage(raw, sessionID) {
|
|
|
3446
4020
|
message2.events = opencodeEvents(raw, message2);
|
|
3447
4021
|
return message2;
|
|
3448
4022
|
}
|
|
4023
|
+
var PAGE = 60;
|
|
4024
|
+
var MAX_JSON = 4e6;
|
|
4025
|
+
var sessionFields = [
|
|
4026
|
+
"id",
|
|
4027
|
+
"project_id",
|
|
4028
|
+
"parent_id",
|
|
4029
|
+
"fork_session_id",
|
|
4030
|
+
"directory",
|
|
4031
|
+
"title",
|
|
4032
|
+
"time_created",
|
|
4033
|
+
"time_updated",
|
|
4034
|
+
"time_archived",
|
|
4035
|
+
"model",
|
|
4036
|
+
"agent",
|
|
4037
|
+
"cost",
|
|
4038
|
+
"tokens_input",
|
|
4039
|
+
"tokens_output",
|
|
4040
|
+
"tokens_reasoning",
|
|
4041
|
+
"tokens_cache_read",
|
|
4042
|
+
"tokens_cache_write",
|
|
4043
|
+
"idle_outcome"
|
|
4044
|
+
];
|
|
4045
|
+
async function openCodeDatabases() {
|
|
4046
|
+
const override = sourcePath("opencode") || process.env.SESSIONGRAPH_OPENCODE_HISTORY_DIR || process.env.OPENCODE_DB;
|
|
4047
|
+
const root3 = override || dataPath("opencode");
|
|
4048
|
+
try {
|
|
4049
|
+
const info = await lstat3(root3);
|
|
4050
|
+
if (info.isFile()) return [root3];
|
|
4051
|
+
if (!info.isDirectory()) return [];
|
|
4052
|
+
const files = (await readdir2(root3)).filter((name) => /^opencode(?:[-.][\w.-]+)?\.db$/.test(name)).sort((a, b) => a === "opencode.db" ? -1 : b === "opencode.db" ? 1 : a.localeCompare(b));
|
|
4053
|
+
if (files.length > 20) throw new Error("Too many OpenCode databases. Choose a database file with a source path override.");
|
|
4054
|
+
const paths2 = [];
|
|
4055
|
+
for (const file of files) {
|
|
4056
|
+
const path = join6(root3, file);
|
|
4057
|
+
if ((await lstat3(path)).isFile()) paths2.push(path);
|
|
4058
|
+
}
|
|
4059
|
+
return paths2;
|
|
4060
|
+
} catch (error) {
|
|
4061
|
+
if (error.code === "ENOENT") return [];
|
|
4062
|
+
throw error;
|
|
4063
|
+
}
|
|
4064
|
+
}
|
|
4065
|
+
function schemas(db2) {
|
|
4066
|
+
const result = [];
|
|
4067
|
+
for (const version of ["2", "1"]) {
|
|
4068
|
+
const session = version === "2" ? "session_v2" : "session", message2 = version === "2" ? "session_message" : "message", part = version === "2" ? "session_part" : "part";
|
|
4069
|
+
if (!hasTable(db2, session)) continue;
|
|
4070
|
+
for (const [table, required] of [[session, ["id", "time_created", "time_updated"]], [message2, ["id", "session_id", "data", "time_created", ...version === "2" ? ["type", "seq"] : []]]]) {
|
|
4071
|
+
const names = columns(db2, table);
|
|
4072
|
+
if (required.some((name) => !names.has(name))) throw new Error("Unsupported OpenCode database schema.");
|
|
4073
|
+
}
|
|
4074
|
+
if (hasTable(db2, part)) {
|
|
4075
|
+
const names = columns(db2, part);
|
|
4076
|
+
if (["message_id", "data", version === "2" ? "ordinal" : "id"].some((name) => !names.has(name))) throw new Error("Unsupported OpenCode part schema.");
|
|
4077
|
+
} else if (version === "1") throw new Error("OpenCode V1 parts are unavailable.");
|
|
4078
|
+
result.push({ version, session, message: message2, part: hasTable(db2, part) ? part : void 0 });
|
|
4079
|
+
}
|
|
4080
|
+
if (!result.length) throw new Error("Unsupported OpenCode database schema.");
|
|
4081
|
+
return result;
|
|
4082
|
+
}
|
|
4083
|
+
function historyRevisions(db2, schema) {
|
|
4084
|
+
const result = /* @__PURE__ */ new Map();
|
|
4085
|
+
for (const table of [schema.message, schema.part].filter((value) => Boolean(value))) {
|
|
4086
|
+
const names = columns(db2, table);
|
|
4087
|
+
if (!names.has("session_id")) continue;
|
|
4088
|
+
const updated = names.has("time_updated") ? "MAX(time_updated)" : "NULL";
|
|
4089
|
+
for (const row of db2.prepare(`SELECT session_id, COUNT(*) AS count, ${updated} AS updated FROM "${table}" GROUP BY session_id`).iterate()) {
|
|
4090
|
+
const id2 = text(row.session_id);
|
|
4091
|
+
result.set(id2, [...result.get(id2) || [], row.count, row.updated]);
|
|
4092
|
+
}
|
|
4093
|
+
}
|
|
4094
|
+
return result;
|
|
4095
|
+
}
|
|
4096
|
+
function discoverDatabase(db2, path, snapshot2) {
|
|
4097
|
+
const sessions = /* @__PURE__ */ new Map(), projects = /* @__PURE__ */ new Map(), errors = [];
|
|
4098
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4099
|
+
if (hasTable(db2, "project")) {
|
|
4100
|
+
for (const row of rows(db2, "project", ["id", "name", "worktree", "sandboxes"], void 0, "id", 2e4)) {
|
|
4101
|
+
try {
|
|
4102
|
+
const p = project("opencode", text(row.worktree)), sandboxes = optionalJSON(row.sandboxes);
|
|
4103
|
+
p.id = identity("opencode", text(row.id));
|
|
4104
|
+
p.name = text(row.name) || p.name;
|
|
4105
|
+
p.worktrees = Array.isArray(sandboxes) ? sandboxes.filter((value) => typeof value === "string") : [];
|
|
4106
|
+
projects.set(p.id, p);
|
|
4107
|
+
} catch {
|
|
4108
|
+
errors.push("OpenCode: Skipped unreadable project metadata.");
|
|
4109
|
+
}
|
|
4110
|
+
}
|
|
4111
|
+
}
|
|
4112
|
+
for (const schema of schemas(db2)) {
|
|
4113
|
+
const revisions = historyRevisions(db2, schema);
|
|
4114
|
+
for (const row of rows(db2, schema.session, sessionFields, void 0, "id", 2e4)) {
|
|
4115
|
+
const nativeID = text(row.id), id2 = identity("opencode", nativeID);
|
|
4116
|
+
if (seen.has(id2)) continue;
|
|
4117
|
+
seen.add(id2);
|
|
4118
|
+
if (!nativeID || nativeID.length > 512 || !time(row.time_created)) {
|
|
4119
|
+
errors.push("OpenCode: Skipped invalid session metadata.");
|
|
4120
|
+
continue;
|
|
4121
|
+
}
|
|
4122
|
+
const session = {
|
|
4123
|
+
...blankSession("opencode", nativeID, text(row.directory)),
|
|
4124
|
+
title: text(row.title) || "Untitled session",
|
|
4125
|
+
created: time(row.time_created),
|
|
4126
|
+
updated: time(row.time_updated) || time(row.time_created),
|
|
4127
|
+
archived: Boolean(row.time_archived),
|
|
4128
|
+
parentID: text(row.parent_id) ? identity("opencode", text(row.parent_id)) : void 0,
|
|
4129
|
+
forkID: text(row.fork_session_id) ? identity("opencode", text(row.fork_session_id)) : void 0
|
|
4130
|
+
};
|
|
4131
|
+
try {
|
|
4132
|
+
const model = object3(optionalJSON(row.model));
|
|
4133
|
+
session.model = text(model.id) || "Unknown model";
|
|
4134
|
+
session.provider = text(model.providerID);
|
|
4135
|
+
session.agent = text(row.agent) || "build";
|
|
4136
|
+
session.outcome = text(row.idle_outcome) || void 0;
|
|
4137
|
+
if (schema.version === "1") {
|
|
4138
|
+
const valid = `length(CAST(data AS BLOB))<=${MAX_JSON} AND json_valid(data)`;
|
|
4139
|
+
const latest = db2.prepare(`SELECT
|
|
4140
|
+
CASE WHEN ${valid} THEN substr(json_extract(data,'$.modelID'),1,256) END AS model,
|
|
4141
|
+
CASE WHEN ${valid} THEN substr(json_extract(data,'$.providerID'),1,256) END AS provider,
|
|
4142
|
+
CASE WHEN ${valid} THEN substr(json_extract(data,'$.model.modelID'),1,256) END AS user_model,
|
|
4143
|
+
CASE WHEN ${valid} THEN substr(json_extract(data,'$.model.providerID'),1,256) END AS user_provider,
|
|
4144
|
+
CASE WHEN ${valid} THEN substr(json_extract(data,'$.agent'),1,256) END AS agent
|
|
4145
|
+
FROM message WHERE session_id=? ORDER BY time_created DESC, id DESC LIMIT 1`).get(nativeID);
|
|
4146
|
+
session.model = text(latest?.model || latest?.user_model) || session.model;
|
|
4147
|
+
session.provider = text(latest?.provider || latest?.user_provider);
|
|
4148
|
+
session.agent = text(latest?.agent) || session.agent;
|
|
4149
|
+
}
|
|
4150
|
+
if (schema.version === "2") {
|
|
4151
|
+
session.usage = sessionUsage(openCodeUsage({
|
|
4152
|
+
input: row.tokens_input,
|
|
4153
|
+
output: row.tokens_output,
|
|
4154
|
+
reasoning: row.tokens_reasoning,
|
|
4155
|
+
cache: { read: row.tokens_cache_read, write: row.tokens_cache_write }
|
|
4156
|
+
}, row.cost));
|
|
4157
|
+
session.tokens = session.usage?.total ?? null;
|
|
4158
|
+
session.cost = session.usage?.cost ?? null;
|
|
4159
|
+
}
|
|
4160
|
+
const nativeProject = identity("opencode", text(row.project_id));
|
|
4161
|
+
const p = projects.get(nativeProject) || project("opencode", session.directory);
|
|
4162
|
+
session.projectID = p.id;
|
|
4163
|
+
projects.set(p.id, p);
|
|
4164
|
+
sessions.set(id2, {
|
|
4165
|
+
session,
|
|
4166
|
+
revision: digest([6, schema.version, row, revisions.get(nativeID)]),
|
|
4167
|
+
locator: { path, snapshot: snapshot2, version: schema.version }
|
|
4168
|
+
});
|
|
4169
|
+
} catch {
|
|
4170
|
+
errors.push("OpenCode: Skipped unreadable session metadata.");
|
|
4171
|
+
}
|
|
4172
|
+
}
|
|
4173
|
+
}
|
|
4174
|
+
return { sessions: [...sessions.values()], projects: [...projects.values()], warnings: [], errors };
|
|
4175
|
+
}
|
|
4176
|
+
function payloadRows(db2, query, values, budget2) {
|
|
4177
|
+
const result = [];
|
|
4178
|
+
for (const row of db2.prepare(query).iterate(...values)) {
|
|
4179
|
+
if (typeof row.data !== "string") throw new Error("OpenCode history contains a missing or oversized JSON field (4 MB limit).");
|
|
4180
|
+
budget2.bytes += Buffer.byteLength(row.data);
|
|
4181
|
+
budget2.records++;
|
|
4182
|
+
if (budget2.bytes > 32e6 || budget2.records > 5e4) throw new Error("OpenCode history page exceeds the 32 MB / 50,000-record limit.");
|
|
4183
|
+
result.push(row);
|
|
4184
|
+
}
|
|
4185
|
+
return result;
|
|
4186
|
+
}
|
|
3449
4187
|
var opencodeAdapter = {
|
|
3450
4188
|
id: "opencode",
|
|
3451
4189
|
name: "OpenCode",
|
|
3452
|
-
description: "Local
|
|
4190
|
+
description: "Local SQLite history \xB7 V1 and V2 \xB7 no running service needed",
|
|
3453
4191
|
capabilities: { history: true, forks: true, children: true, files: true },
|
|
3454
4192
|
async detect() {
|
|
3455
|
-
|
|
3456
|
-
await api("/api/info", AbortSignal.timeout(3e3));
|
|
3457
|
-
return true;
|
|
3458
|
-
} catch {
|
|
3459
|
-
return false;
|
|
3460
|
-
}
|
|
4193
|
+
return (await openCodeDatabases()).length > 0;
|
|
3461
4194
|
},
|
|
3462
4195
|
async discover() {
|
|
3463
|
-
const
|
|
3464
|
-
|
|
3465
|
-
|
|
3466
|
-
|
|
3467
|
-
|
|
3468
|
-
|
|
3469
|
-
|
|
3470
|
-
|
|
3471
|
-
|
|
3472
|
-
|
|
3473
|
-
|
|
3474
|
-
|
|
3475
|
-
|
|
3476
|
-
|
|
4196
|
+
const sessions = /* @__PURE__ */ new Map(), projects = /* @__PURE__ */ new Map(), errors = [];
|
|
4197
|
+
for (const path of await openCodeDatabases()) {
|
|
4198
|
+
try {
|
|
4199
|
+
const snapshot2 = sqliteRevision(path);
|
|
4200
|
+
const found = withSqliteSnapshot(path, (db2) => discoverDatabase(db2, path, snapshot2), snapshot2);
|
|
4201
|
+
for (const candidate of found.sessions) {
|
|
4202
|
+
const previous = sessions.get(candidate.session.id);
|
|
4203
|
+
if (!previous || candidate.locator.version > previous.locator.version || candidate.locator.version === previous.locator.version && candidate.session.updated > previous.session.updated) sessions.set(candidate.session.id, candidate);
|
|
4204
|
+
}
|
|
4205
|
+
for (const p of found.projects) projects.set(p.id, p);
|
|
4206
|
+
errors.push(...found.errors);
|
|
4207
|
+
} catch (error) {
|
|
4208
|
+
errors.push(`OpenCode: ${error instanceof Error ? error.message : "Could not read a history database."}`);
|
|
4209
|
+
}
|
|
4210
|
+
}
|
|
4211
|
+
return { sessions: [...sessions.values()], projects: [...projects.values()], warnings: [], errors: [...new Set(errors)] };
|
|
3477
4212
|
},
|
|
3478
4213
|
async read(candidate, cursor) {
|
|
3479
|
-
|
|
3480
|
-
|
|
3481
|
-
|
|
3482
|
-
|
|
3483
|
-
|
|
3484
|
-
|
|
3485
|
-
const
|
|
3486
|
-
|
|
3487
|
-
|
|
3488
|
-
|
|
4214
|
+
if (cursor && !/^[1-9]\d{0,5}$/.test(cursor)) throw new Error("Invalid OpenCode history cursor.");
|
|
4215
|
+
const offset = Number(cursor || 0);
|
|
4216
|
+
return withSqliteSnapshot(candidate.locator.path, (db2) => {
|
|
4217
|
+
const schema = schemas(db2).find((value) => value.version === candidate.locator.version);
|
|
4218
|
+
if (!schema) throw new Error("OpenCode history schema changed.");
|
|
4219
|
+
const budget2 = { bytes: 0, records: 0 };
|
|
4220
|
+
const data = `CASE WHEN length(CAST(data AS BLOB))<=${MAX_JSON} THEN data END AS data`;
|
|
4221
|
+
const page = payloadRows(
|
|
4222
|
+
db2,
|
|
4223
|
+
`SELECT id, time_created, ${schema.version === "2" ? "type" : "NULL AS type"}, ${data}
|
|
4224
|
+
FROM "${schema.message}" WHERE session_id=? ORDER BY ${schema.version === "2" ? "seq DESC" : "time_created DESC, id DESC"} LIMIT ${PAGE + 1} OFFSET ?`,
|
|
4225
|
+
[candidate.session.nativeID, offset],
|
|
4226
|
+
budget2
|
|
4227
|
+
);
|
|
4228
|
+
const messages = page.slice(0, PAGE).map((row) => {
|
|
4229
|
+
const body2 = object3(sqliteJSON(row.data));
|
|
4230
|
+
if (schema.version === "1" && !["user", "assistant"].includes(body2.role)) throw new Error("Unsupported OpenCode V1 message.");
|
|
4231
|
+
if (schema.version === "2" && !text(row.type)) throw new Error("Missing OpenCode message type.");
|
|
4232
|
+
const parts = schema.part ? payloadRows(
|
|
4233
|
+
db2,
|
|
4234
|
+
`SELECT ${schema.version === "2" ? "ordinal" : "id"}, ${data} FROM "${schema.part}" WHERE message_id=? ORDER BY ${schema.version === "2" ? "ordinal" : "id"}`,
|
|
4235
|
+
[text(row.id)],
|
|
4236
|
+
budget2
|
|
4237
|
+
).map((part) => ({ ...object3(sqliteJSON(part.data)), ...schema.version === "1" ? { id: part.id } : {} })) : [];
|
|
4238
|
+
const raw = schema.version === "1" ? openCodeV1Message(body2, parts) : { ...body2, type: row.type, content: [...parts, ...Array.isArray(body2.content) ? body2.content : []] };
|
|
4239
|
+
const message2 = openCodeMessage({ ...raw, id: text(row.id), time: { ...object3(raw.time), created: time(raw.time?.created) || time(row.time_created) } }, candidate.session.id);
|
|
4240
|
+
if (schema.version === "1" && candidate.session.model === "Unknown model" && message2.metadata?.model) {
|
|
4241
|
+
candidate.session.model = message2.metadata?.model || candidate.session.model;
|
|
4242
|
+
candidate.session.provider = message2.metadata?.provider || candidate.session.provider;
|
|
4243
|
+
}
|
|
4244
|
+
return message2;
|
|
4245
|
+
});
|
|
4246
|
+
return { messages, cursor: page.length > PAGE ? String(offset + PAGE) : void 0 };
|
|
4247
|
+
}, candidate.locator.snapshot, true);
|
|
3489
4248
|
}
|
|
3490
4249
|
};
|
|
3491
4250
|
|
|
@@ -30775,19 +31534,19 @@ async function f3e(e10, t, n, r) {
|
|
|
30775
31534
|
}
|
|
30776
31535
|
|
|
30777
31536
|
// server/adapters/claude.ts
|
|
30778
|
-
import { readdir as
|
|
30779
|
-
import { homedir as
|
|
30780
|
-
import { join as
|
|
31537
|
+
import { readdir as readdir3, stat } from "node:fs/promises";
|
|
31538
|
+
import { homedir as homedir5 } from "node:os";
|
|
31539
|
+
import { join as join10 } from "node:path";
|
|
30781
31540
|
|
|
30782
31541
|
// server/adapters/claude-transcripts.ts
|
|
30783
|
-
import { constants as
|
|
30784
|
-
import { lstat, open } from "node:fs/promises";
|
|
30785
|
-
import { basename as
|
|
31542
|
+
import { constants as constants4 } from "node:fs";
|
|
31543
|
+
import { lstat as lstat4, open as open2 } from "node:fs/promises";
|
|
31544
|
+
import { basename as basename2 } from "node:path";
|
|
30786
31545
|
var claudeSessionID = (value) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
|
|
30787
|
-
var
|
|
30788
|
-
var sidecar = (path) =>
|
|
31546
|
+
var MAX_BYTES2 = 128e6;
|
|
31547
|
+
var sidecar = (path) => basename2(path).startsWith("agent-") ? path.replace(/\.jsonl$/, ".meta.json") : void 0;
|
|
30789
31548
|
async function state(path) {
|
|
30790
|
-
const s = await
|
|
31549
|
+
const s = await lstat4(path);
|
|
30791
31550
|
if (!s.isFile()) throw new Error("Claude transcript must be a regular file.");
|
|
30792
31551
|
return { size: s.size, modified: s.mtimeMs, signature: [s.dev, s.ino, s.size, s.mtimeMs] };
|
|
30793
31552
|
}
|
|
@@ -30805,8 +31564,8 @@ async function claudeRevision(path) {
|
|
|
30805
31564
|
}
|
|
30806
31565
|
async function bytes(path, max) {
|
|
30807
31566
|
const before = await state(path);
|
|
30808
|
-
if (before.size > max) throw new Error(`Claude transcript exceeds the ${max ===
|
|
30809
|
-
const file = await
|
|
31567
|
+
if (before.size > max) throw new Error(`Claude transcript exceeds the ${max === MAX_BYTES2 ? "128 MB import" : "metadata size"} limit.`);
|
|
31568
|
+
const file = await open2(path, constants4.O_RDONLY | (constants4.O_NOFOLLOW || 0) | (constants4.O_NONBLOCK || 0));
|
|
30810
31569
|
try {
|
|
30811
31570
|
const opened = await file.stat();
|
|
30812
31571
|
if (!opened.isFile() || opened.dev !== before.signature[0] || opened.ino !== before.signature[1]) throw new Error("Claude transcript changed during import; import again.");
|
|
@@ -30827,7 +31586,7 @@ var cached;
|
|
|
30827
31586
|
async function claudeTranscript(path, revision2) {
|
|
30828
31587
|
if (await claudeRevision(path) !== revision2) throw new Error("Claude transcript changed during import; import again.");
|
|
30829
31588
|
if (cached?.path === path && cached.revision === revision2) return cached.transcript;
|
|
30830
|
-
const source = await bytes(path,
|
|
31589
|
+
const source = await bytes(path, MAX_BYTES2), entries2 = [], times = /* @__PURE__ */ new Map();
|
|
30831
31590
|
let partial = false;
|
|
30832
31591
|
for (const line of source.split("\n")) {
|
|
30833
31592
|
if (!line.trim()) continue;
|
|
@@ -30887,216 +31646,8 @@ function claudeTranscriptStore(transcript, sessionId, agent) {
|
|
|
30887
31646
|
};
|
|
30888
31647
|
}
|
|
30889
31648
|
|
|
30890
|
-
// server/adapters/local-files.ts
|
|
30891
|
-
import { constants as constants3 } from "node:fs";
|
|
30892
|
-
import { lstat as lstat2, open as open2, readdir } from "node:fs/promises";
|
|
30893
|
-
import { join as join4, relative } from "node:path";
|
|
30894
|
-
|
|
30895
|
-
// server/adapters/compressed.ts
|
|
30896
|
-
import { gunzipSync, zstdDecompressSync } from "node:zlib";
|
|
30897
|
-
function expandHistory(buffer, maxOutputLength) {
|
|
30898
|
-
if (buffer.length >= 4 && buffer.readUInt32LE(0) === 4247762216) return zstdDecompressSync(buffer, { maxOutputLength });
|
|
30899
|
-
if (buffer[0] === 31 && buffer[1] === 139) return gunzipSync(buffer, { maxOutputLength });
|
|
30900
|
-
if (buffer.length > maxOutputLength) throw new Error("Expanded history exceeds the snapshot limit.");
|
|
30901
|
-
return buffer;
|
|
30902
|
-
}
|
|
30903
|
-
|
|
30904
|
-
// server/adapters/local-files.ts
|
|
30905
|
-
var object3 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
30906
|
-
var text = (value) => typeof value === "string" ? value : "";
|
|
30907
|
-
var time = (value) => {
|
|
30908
|
-
const n = typeof value === "number" ? value : typeof value === "string" ? /^\d{13}$/.test(value) ? Number(value) : Date.parse(value) : 0;
|
|
30909
|
-
return Number.isFinite(n) && n > 0 && n <= 864e13 ? n : 0;
|
|
30910
|
-
};
|
|
30911
|
-
var MAX_BYTES2 = 32e6;
|
|
30912
|
-
var MAX_RECORDS = 5e4;
|
|
30913
|
-
var MAX_FILES = 2e4;
|
|
30914
|
-
async function fileState(path) {
|
|
30915
|
-
try {
|
|
30916
|
-
const s = await lstat2(path);
|
|
30917
|
-
if (!s.isFile()) throw new Error("History must be a regular file, not a symlink.");
|
|
30918
|
-
if (s.size > MAX_BYTES2) throw new Error("History exceeds the 32 MB per-file limit.");
|
|
30919
|
-
return { path, signature: digest([s.size, s.mtimeMs, s.ctimeMs, s.ino]), created: s.birthtimeMs || s.mtimeMs, updated: s.mtimeMs, size: s.size };
|
|
30920
|
-
} catch (error) {
|
|
30921
|
-
if (error.code === "ENOENT") return { path, signature: "missing", created: 0, updated: 0, size: 0 };
|
|
30922
|
-
throw error;
|
|
30923
|
-
}
|
|
30924
|
-
}
|
|
30925
|
-
async function historyFiles(roots2, match2) {
|
|
30926
|
-
const files = [], queue = [];
|
|
30927
|
-
const warnings = [];
|
|
30928
|
-
for (const root3 of new Set(roots2)) {
|
|
30929
|
-
try {
|
|
30930
|
-
if ((await lstat2(root3)).isDirectory()) queue.push({ root: root3, path: root3, depth: 0 });
|
|
30931
|
-
} catch (error) {
|
|
30932
|
-
if (error.code !== "ENOENT") warnings.push("A history directory could not be read.");
|
|
30933
|
-
}
|
|
30934
|
-
}
|
|
30935
|
-
let entriesSeen = 0, limited = false;
|
|
30936
|
-
for (let i = 0; i < queue.length && files.length < MAX_FILES && entriesSeen < 1e5; i++) {
|
|
30937
|
-
const { root: root3, path, depth } = queue[i];
|
|
30938
|
-
let entries2;
|
|
30939
|
-
try {
|
|
30940
|
-
entries2 = await readdir(path, { withFileTypes: true });
|
|
30941
|
-
} catch {
|
|
30942
|
-
warnings.push("A history directory could not be read.");
|
|
30943
|
-
continue;
|
|
30944
|
-
}
|
|
30945
|
-
for (const entry of entries2) {
|
|
30946
|
-
if (++entriesSeen > 1e5 || files.length >= MAX_FILES) {
|
|
30947
|
-
limited = true;
|
|
30948
|
-
break;
|
|
30949
|
-
}
|
|
30950
|
-
const file = join4(path, entry.name);
|
|
30951
|
-
if (entry.isDirectory()) {
|
|
30952
|
-
if (depth < 6 && queue.length < MAX_FILES) queue.push({ root: root3, path: file, depth: depth + 1 });
|
|
30953
|
-
else limited = true;
|
|
30954
|
-
}
|
|
30955
|
-
if (entry.isFile() && match2(relative(root3, file).split("\\").join("/"))) files.push(file);
|
|
30956
|
-
}
|
|
30957
|
-
}
|
|
30958
|
-
if (limited) warnings.push("History discovery reached its file, directory, or depth limit.");
|
|
30959
|
-
return { files: [...new Set(files)].sort(), warnings };
|
|
30960
|
-
}
|
|
30961
|
-
function json3(value) {
|
|
30962
|
-
return JSON.parse(value);
|
|
30963
|
-
}
|
|
30964
|
-
function jsonLines(value) {
|
|
30965
|
-
const rows2 = [];
|
|
30966
|
-
let partial = false;
|
|
30967
|
-
for (const line of value.split("\n")) {
|
|
30968
|
-
if (!line.trim()) continue;
|
|
30969
|
-
if (rows2.length >= MAX_RECORDS) throw new Error("History exceeds the 50,000-record limit.");
|
|
30970
|
-
if (line.length > 2e6) throw new Error("History contains a record larger than 2 MB.");
|
|
30971
|
-
try {
|
|
30972
|
-
const row = json3(line);
|
|
30973
|
-
if (!row || typeof row !== "object" || Array.isArray(row)) partial = true;
|
|
30974
|
-
else rows2.push(row);
|
|
30975
|
-
} catch {
|
|
30976
|
-
partial = true;
|
|
30977
|
-
}
|
|
30978
|
-
}
|
|
30979
|
-
return { rows: rows2, partial };
|
|
30980
|
-
}
|
|
30981
|
-
function localFileAdapter(source) {
|
|
30982
|
-
const metadata2 = /* @__PURE__ */ new Map();
|
|
30983
|
-
let cached2;
|
|
30984
|
-
const states = (path) => Promise.all([path, ...source.extras?.(path) || []].map(fileState));
|
|
30985
|
-
const revision2 = (values) => digest([1, ...values.filter((_, i) => i === 0 || source.revisionExtras !== false).map((s) => [s.path, s.signature])]);
|
|
30986
|
-
async function load(path, expected, before) {
|
|
30987
|
-
if (revision2(before) !== expected) throw new Error("Session changed during import; import again.");
|
|
30988
|
-
if (cached2?.path === path && cached2.revision === expected) return cached2.history;
|
|
30989
|
-
if (before[0].signature === "missing") throw new Error("History file is unavailable.");
|
|
30990
|
-
if (before.reduce((n, s) => n + s.size, 0) > MAX_BYTES2) throw new Error("Combined history exceeds the 32 MB snapshot limit.");
|
|
30991
|
-
const files = /* @__PURE__ */ new Map();
|
|
30992
|
-
let expanded = 0;
|
|
30993
|
-
for (const s of before.filter((s2) => s2.signature !== "missing")) {
|
|
30994
|
-
const handle = await open2(s.path, constants3.O_RDONLY | (constants3.O_NOFOLLOW || 0));
|
|
30995
|
-
try {
|
|
30996
|
-
const buffer = Buffer.alloc(s.size + 1);
|
|
30997
|
-
let bytes2 = 0;
|
|
30998
|
-
while (bytes2 < buffer.length) {
|
|
30999
|
-
const part = await handle.read(buffer, bytes2, buffer.length - bytes2, bytes2);
|
|
31000
|
-
if (!part.bytesRead) break;
|
|
31001
|
-
bytes2 += part.bytesRead;
|
|
31002
|
-
}
|
|
31003
|
-
if (bytes2 !== s.size) throw new Error("History changed while reading; import again.");
|
|
31004
|
-
const data = expandHistory(buffer.subarray(0, bytes2), MAX_BYTES2);
|
|
31005
|
-
expanded += data.length;
|
|
31006
|
-
if (expanded > MAX_BYTES2) throw new Error("Expanded history exceeds the 32 MB snapshot limit.");
|
|
31007
|
-
files.set(s.path, data.toString("utf8"));
|
|
31008
|
-
} finally {
|
|
31009
|
-
await handle.close();
|
|
31010
|
-
}
|
|
31011
|
-
}
|
|
31012
|
-
if (digest(await states(path)) !== digest(before)) throw new Error("History changed while reading; import again.");
|
|
31013
|
-
const history = source.parse(path, files);
|
|
31014
|
-
if (!history) return;
|
|
31015
|
-
if (source.capabilities.history && !history.messages.length) throw new Error("No readable conversation.");
|
|
31016
|
-
if (!history.nativeID || history.nativeID.length > 512) throw new Error("History has no supported native session identity.");
|
|
31017
|
-
if (history.messages.length > MAX_RECORDS) throw new Error("History exceeds the 50,000-message limit.");
|
|
31018
|
-
cached2 = { path, revision: expected, history };
|
|
31019
|
-
return history;
|
|
31020
|
-
}
|
|
31021
|
-
return {
|
|
31022
|
-
id: source.id,
|
|
31023
|
-
name: source.name,
|
|
31024
|
-
description: source.description,
|
|
31025
|
-
capabilities: source.capabilities,
|
|
31026
|
-
async detect() {
|
|
31027
|
-
for (const root3 of source.roots()) if ((await lstat2(root3).catch(() => void 0))?.isDirectory()) return true;
|
|
31028
|
-
return false;
|
|
31029
|
-
},
|
|
31030
|
-
async discover() {
|
|
31031
|
-
const listing = await historyFiles(source.roots(), source.match), found = /* @__PURE__ */ new Map();
|
|
31032
|
-
let failed = 0;
|
|
31033
|
-
const blocked = /* @__PURE__ */ new Set(), unreadable = /* @__PURE__ */ new Set();
|
|
31034
|
-
for (const path of listing.files) {
|
|
31035
|
-
try {
|
|
31036
|
-
const before = await states(path), rev = revision2(before);
|
|
31037
|
-
let candidate = metadata2.get(path);
|
|
31038
|
-
if (!candidate || candidate.revision !== rev) {
|
|
31039
|
-
const history = await load(path, rev, before);
|
|
31040
|
-
if (!history) {
|
|
31041
|
-
const nativeID = source.authoritativeIdentity?.(path);
|
|
31042
|
-
if (nativeID) blocked.add(identity(source.id, nativeID));
|
|
31043
|
-
continue;
|
|
31044
|
-
}
|
|
31045
|
-
const session = { ...blankSession(source.id, history.nativeID), ...history.session };
|
|
31046
|
-
session.id = identity(source.id, history.nativeID);
|
|
31047
|
-
session.nativeID = history.nativeID;
|
|
31048
|
-
session.source = source.id;
|
|
31049
|
-
session.directory = text(session.directory);
|
|
31050
|
-
session.projectID = project(source.id, session.directory).id;
|
|
31051
|
-
session.created = time(session.created) || history.messages.map((m) => time(m.time)).find(Boolean) || before[0].created;
|
|
31052
|
-
session.updated = before[0].updated;
|
|
31053
|
-
session.agent ||= source.name;
|
|
31054
|
-
session.parentID = history.parent ? identity(source.id, history.parent) : void 0;
|
|
31055
|
-
session.forkID = history.fork ? identity(source.id, history.fork) : void 0;
|
|
31056
|
-
if (session.title === "Untitled session" || !session.title) session.title = history.messages.flatMap((m) => m.role === "user" ? m.fragments.filter((f) => f.kind === "You").map((f) => f.text) : []).find(Boolean)?.replace(/\s+/g, " ").slice(0, 180) || `${source.name} session`;
|
|
31057
|
-
candidate = { session, revision: rev, locator: { path } };
|
|
31058
|
-
metadata2.set(path, candidate);
|
|
31059
|
-
}
|
|
31060
|
-
const previous = found.get(candidate.session.id);
|
|
31061
|
-
const preferred = candidate.locator.path.endsWith(".jsonl"), previousPreferred = previous?.locator.path.endsWith(".jsonl");
|
|
31062
|
-
if (!previous || preferred && !previousPreferred || preferred === previousPreferred && candidate.session.updated > previous.session.updated) found.set(candidate.session.id, candidate);
|
|
31063
|
-
} catch {
|
|
31064
|
-
const nativeID = source.authoritativeIdentity?.(path);
|
|
31065
|
-
if (nativeID) {
|
|
31066
|
-
const id2 = identity(source.id, nativeID);
|
|
31067
|
-
blocked.add(id2);
|
|
31068
|
-
unreadable.add(id2);
|
|
31069
|
-
} else failed++;
|
|
31070
|
-
}
|
|
31071
|
-
}
|
|
31072
|
-
const listed = new Set(listing.files);
|
|
31073
|
-
for (const path of metadata2.keys()) if (!listed.has(path)) metadata2.delete(path);
|
|
31074
|
-
if (failed) listing.warnings.push(`${source.name}: Skipped ${failed} unreadable, changing, unsupported, or oversized ${failed === 1 ? "history file" : "history files"}.`);
|
|
31075
|
-
const sessions = [...found.values()].filter((c) => !blocked.has(c.session.id));
|
|
31076
|
-
const errors = unreadable.size ? [`${source.name}: Could not read history for ${unreadable.size} ${unreadable.size === 1 ? "session" : "sessions"}.`] : void 0;
|
|
31077
|
-
return { sessions, projects: [...new Map(sessions.map((c) => {
|
|
31078
|
-
const p = project(source.id, c.session.directory);
|
|
31079
|
-
return [p.id, p];
|
|
31080
|
-
})).values()], warnings: listing.warnings, errors, blocked: [...blocked] };
|
|
31081
|
-
},
|
|
31082
|
-
async read(candidate, cursor) {
|
|
31083
|
-
const offset = cursor === void 0 ? 0 : Number(cursor);
|
|
31084
|
-
if (!Number.isSafeInteger(offset) || offset < 0) throw new Error("Invalid history cursor.");
|
|
31085
|
-
const history = await load(candidate.locator.path, candidate.revision, await states(candidate.locator.path));
|
|
31086
|
-
if (!history) throw new Error("History representation is no longer available.");
|
|
31087
|
-
const messages = history.messages.slice(offset, offset + 100);
|
|
31088
|
-
return {
|
|
31089
|
-
messages,
|
|
31090
|
-
cursor: offset + messages.length < history.messages.length ? String(offset + messages.length) : void 0,
|
|
31091
|
-
partial: Boolean(history.partial || messages.some((m) => m.partial)),
|
|
31092
|
-
note: history.note
|
|
31093
|
-
};
|
|
31094
|
-
}
|
|
31095
|
-
};
|
|
31096
|
-
}
|
|
31097
|
-
|
|
31098
31649
|
// server/adapters/harness-formats.ts
|
|
31099
|
-
import { basename as
|
|
31650
|
+
import { basename as basename3, dirname as dirname2, join as join9 } from "node:path";
|
|
31100
31651
|
|
|
31101
31652
|
// server/adapters/local-messages.ts
|
|
31102
31653
|
function conversationMessage(raw, fallbackID) {
|
|
@@ -31177,31 +31728,8 @@ function successfulEdits(messages, editNames) {
|
|
|
31177
31728
|
}
|
|
31178
31729
|
|
|
31179
31730
|
// server/adapters/pi.ts
|
|
31180
|
-
import { homedir as
|
|
31181
|
-
|
|
31182
|
-
// server/source-paths.ts
|
|
31183
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
31184
|
-
var paths = new AsyncLocalStorage();
|
|
31185
|
-
var sourcePath = (id2) => paths.getStore()?.[id2];
|
|
31186
|
-
function withSourcePaths(adapter, configured) {
|
|
31187
|
-
return {
|
|
31188
|
-
...adapter,
|
|
31189
|
-
detect: () => paths.run(configured(), () => adapter.detect()),
|
|
31190
|
-
discover: () => paths.run(configured(), async () => {
|
|
31191
|
-
const result = await adapter.discover();
|
|
31192
|
-
if (!sourcePath(adapter.id)) return result;
|
|
31193
|
-
return { ...result, sessions: result.sessions.map((candidate) => ({ ...candidate, session: { ...candidate.session, nativeResume: false } })) };
|
|
31194
|
-
}),
|
|
31195
|
-
read: (candidate, cursor) => paths.run(configured(), async () => {
|
|
31196
|
-
const result = await adapter.read(candidate, cursor);
|
|
31197
|
-
if (sourcePath(adapter.id)) candidate.session.nativeResume = false;
|
|
31198
|
-
return result;
|
|
31199
|
-
})
|
|
31200
|
-
};
|
|
31201
|
-
}
|
|
31202
|
-
|
|
31203
|
-
// server/adapters/pi.ts
|
|
31204
|
-
import { join as join5 } from "node:path";
|
|
31731
|
+
import { homedir as homedir4 } from "node:os";
|
|
31732
|
+
import { join as join8 } from "node:path";
|
|
31205
31733
|
function piHistory(value) {
|
|
31206
31734
|
const { rows: rows2, partial } = jsonLines(value);
|
|
31207
31735
|
const header = rows2[0];
|
|
@@ -31232,7 +31760,7 @@ var piAdapter = localFileAdapter({
|
|
|
31232
31760
|
name: "Pi",
|
|
31233
31761
|
description: "Local JSONL sessions \xB7 messages, tools, compaction, and branch entries",
|
|
31234
31762
|
capabilities: { history: true, forks: false, children: false, files: true },
|
|
31235
|
-
roots: () => [sourcePath("pi") || process.env.SESSIONGRAPH_PI_SESSIONS_DIR ||
|
|
31763
|
+
roots: () => [sourcePath("pi") || process.env.SESSIONGRAPH_PI_SESSIONS_DIR || join8(process.env.PI_CODING_AGENT_DIR || join8(homedir4(), ".pi", "agent"), "sessions")],
|
|
31236
31764
|
match: (path) => path.endsWith(".jsonl"),
|
|
31237
31765
|
parse(path, files) {
|
|
31238
31766
|
const history = piHistory(files.get(path));
|
|
@@ -31244,7 +31772,7 @@ var piAdapter = localFileAdapter({
|
|
|
31244
31772
|
// server/adapters/harness-formats.ts
|
|
31245
31773
|
var nativeText = (v3) => typeof v3 === "number" && Number.isSafeInteger(v3) ? String(v3) : text(v3);
|
|
31246
31774
|
var seconds = (v3) => typeof v3 === "number" && Number.isFinite(v3) && v3 > 0 ? v3 * 1e3 : time(v3);
|
|
31247
|
-
var fileID = (path) =>
|
|
31775
|
+
var fileID = (path) => basename3(path).replace(/\.jsonl(?:\..*)?$|\.json$/, "");
|
|
31248
31776
|
var sidecar2 = (files, path) => object3(files.has(path) ? json3(files.get(path)) : void 0);
|
|
31249
31777
|
var roles = ["user", "assistant", "system", "tool", "toolResult", "model"];
|
|
31250
31778
|
function message(raw, id2, timestamp) {
|
|
@@ -31321,13 +31849,13 @@ function codebuffHistory(path, files, free) {
|
|
|
31321
31849
|
const m = message({ ...r, role: r.role || r.type, content }, text(r.id) || `message:${i}`);
|
|
31322
31850
|
return m ? [m] : [];
|
|
31323
31851
|
});
|
|
31324
|
-
const chat =
|
|
31852
|
+
const chat = basename3(dirname2(path)), project2 = basename3(dirname2(dirname2(dirname2(path))));
|
|
31325
31853
|
return { nativeID: `${project2}/${chat}`, messages, partial: true };
|
|
31326
31854
|
}
|
|
31327
31855
|
function vibeHistory(path, files) {
|
|
31328
|
-
const raw = object3(json3(files.get(path))), legacy =
|
|
31856
|
+
const raw = object3(json3(files.get(path))), legacy = basename3(path) !== "meta.json";
|
|
31329
31857
|
const meta = legacy ? object3(raw.metadata) : raw;
|
|
31330
|
-
const transcript =
|
|
31858
|
+
const transcript = join9(dirname2(path), "messages.jsonl");
|
|
31331
31859
|
const parsed = files.has(transcript) ? jsonLines(files.get(transcript)) : { rows: [], partial: false };
|
|
31332
31860
|
const records = legacy ? raw.messages : parsed.rows;
|
|
31333
31861
|
if (!text(meta.session_id) || !Array.isArray(records)) throw new Error("Unsupported Vibe session.");
|
|
@@ -31398,352 +31926,8 @@ function dshHistory(value) {
|
|
|
31398
31926
|
return { nativeID: header.id, messages, partial: true, session: { directory: text(header.cwd), created: time(header.createdAt ?? header.time) }, note: partial ? "Some transcript records could not be imported." : void 0 };
|
|
31399
31927
|
}
|
|
31400
31928
|
|
|
31401
|
-
// server/adapters/sqlite-histories.ts
|
|
31402
|
-
import { lstat as lstat3 } from "node:fs/promises";
|
|
31403
|
-
|
|
31404
|
-
// server/adapters/sqlite-snapshot.ts
|
|
31405
|
-
import { DatabaseSync } from "node:sqlite";
|
|
31406
|
-
import { chmodSync, constants as constants4, copyFileSync, lstatSync as lstatSync2, mkdtempSync, rmSync as rmSync2 } from "node:fs";
|
|
31407
|
-
import { copyFile, statfs } from "node:fs/promises";
|
|
31408
|
-
import { tmpdir } from "node:os";
|
|
31409
|
-
import { join as join7 } from "node:path";
|
|
31410
|
-
var copies = /* @__PURE__ */ new Map();
|
|
31411
|
-
var SqliteSnapshotChangedError = class extends Error {
|
|
31412
|
-
};
|
|
31413
|
-
var SqliteSnapshotFileError = class extends Error {
|
|
31414
|
-
};
|
|
31415
|
-
var close = (path) => {
|
|
31416
|
-
const copy = copies.get(path);
|
|
31417
|
-
if (!copy) return;
|
|
31418
|
-
copies.delete(path);
|
|
31419
|
-
try {
|
|
31420
|
-
copy.db.close();
|
|
31421
|
-
} finally {
|
|
31422
|
-
rmSync2(copy.directory, { recursive: true, force: true });
|
|
31423
|
-
}
|
|
31424
|
-
};
|
|
31425
|
-
process.once("exit", () => {
|
|
31426
|
-
for (const path of copies.keys()) close(path);
|
|
31427
|
-
});
|
|
31428
|
-
function snapshotFiles(path, large) {
|
|
31429
|
-
return [path, `${path}-wal`].map((file, i) => {
|
|
31430
|
-
try {
|
|
31431
|
-
const s = lstatSync2(file);
|
|
31432
|
-
const kind = i ? "History database WAL" : "History database";
|
|
31433
|
-
if (!s.isFile()) throw new SqliteSnapshotFileError(`${kind} is not a regular file.`);
|
|
31434
|
-
if (!large && s.size > 8e9) throw new SqliteSnapshotFileError(`${kind} exceeds 8 GB.`);
|
|
31435
|
-
return s;
|
|
31436
|
-
} catch (error) {
|
|
31437
|
-
if (i && error.code === "ENOENT") return null;
|
|
31438
|
-
throw error;
|
|
31439
|
-
}
|
|
31440
|
-
});
|
|
31441
|
-
}
|
|
31442
|
-
var fingerprint = (path, files) => digest([path, ...files.map((s) => s && [s.dev, s.ino, s.size, s.mtimeMs, s.ctimeMs])]);
|
|
31443
|
-
function sqliteRevision(path) {
|
|
31444
|
-
return fingerprint(path, snapshotFiles(path, false));
|
|
31445
|
-
}
|
|
31446
|
-
function openSnapshot(destination) {
|
|
31447
|
-
const db2 = new DatabaseSync(destination, { readOnly: true, enableDoubleQuotedStringLiterals: false, allowExtension: false });
|
|
31448
|
-
try {
|
|
31449
|
-
db2.exec("PRAGMA query_only=ON; PRAGMA trusted_schema=OFF; PRAGMA busy_timeout=1000; BEGIN;");
|
|
31450
|
-
return db2;
|
|
31451
|
-
} catch (error) {
|
|
31452
|
-
db2.close();
|
|
31453
|
-
throw error;
|
|
31454
|
-
}
|
|
31455
|
-
}
|
|
31456
|
-
async function withLargeSqliteSnapshot(path, read3, expected) {
|
|
31457
|
-
const retained = copies.get(path);
|
|
31458
|
-
if (expected && retained?.revision === expected) return read3(retained.db, expected);
|
|
31459
|
-
const files = snapshotFiles(path, true), revision2 = fingerprint(path, files);
|
|
31460
|
-
if (expected && revision2 !== expected) throw new SqliteSnapshotChangedError("History database changed during import; import again.");
|
|
31461
|
-
if (retained?.revision === revision2) {
|
|
31462
|
-
const result = read3(retained.db, revision2);
|
|
31463
|
-
if (fingerprint(path, snapshotFiles(path, true)) !== revision2) throw new SqliteSnapshotChangedError("History database changed during reading; import again.");
|
|
31464
|
-
return result;
|
|
31465
|
-
}
|
|
31466
|
-
close(path);
|
|
31467
|
-
while (copies.size >= 2) close(copies.keys().next().value);
|
|
31468
|
-
const directory3 = mkdtempSync(join7(tmpdir(), "sessiongraph-history-"));
|
|
31469
|
-
const destination = join7(directory3, "history.db");
|
|
31470
|
-
let db2;
|
|
31471
|
-
try {
|
|
31472
|
-
for (const [index, suffix] of ["", "-wal"].entries()) {
|
|
31473
|
-
const file = files[index];
|
|
31474
|
-
if (!file) continue;
|
|
31475
|
-
try {
|
|
31476
|
-
await copyFile(path + suffix, destination + suffix, constants4.COPYFILE_FICLONE_FORCE);
|
|
31477
|
-
} catch (error) {
|
|
31478
|
-
if (!["ENOSYS", "ENOTSUP", "EOPNOTSUPP", "EXDEV", "EINVAL"].includes(error.code || "")) throw error;
|
|
31479
|
-
const { bavail, bsize } = await statfs(directory3);
|
|
31480
|
-
const reserve = 512 * 1024 * 1024;
|
|
31481
|
-
if (bavail * bsize < file.size + reserve) throw new Error("Not enough free space for the T3 history snapshot. Free space on the temporary drive and retry.");
|
|
31482
|
-
await copyFile(path + suffix, destination + suffix);
|
|
31483
|
-
}
|
|
31484
|
-
chmodSync(destination + suffix, 384);
|
|
31485
|
-
}
|
|
31486
|
-
if (fingerprint(path, snapshotFiles(path, true)) !== revision2) throw new SqliteSnapshotChangedError("History database changed while copying; import again.");
|
|
31487
|
-
db2 = openSnapshot(destination);
|
|
31488
|
-
const result = read3(db2, revision2);
|
|
31489
|
-
if (!expected && fingerprint(path, snapshotFiles(path, true)) !== revision2) throw new SqliteSnapshotChangedError("History database changed during reading; import again.");
|
|
31490
|
-
close(path);
|
|
31491
|
-
while (copies.size >= 2) close(copies.keys().next().value);
|
|
31492
|
-
copies.set(path, { revision: revision2, directory: directory3, db: db2 });
|
|
31493
|
-
return result;
|
|
31494
|
-
} catch (error) {
|
|
31495
|
-
try {
|
|
31496
|
-
db2?.close();
|
|
31497
|
-
} finally {
|
|
31498
|
-
rmSync2(directory3, { recursive: true, force: true });
|
|
31499
|
-
}
|
|
31500
|
-
if (error.code === "ENOENT" && fingerprint(path, snapshotFiles(path, true)) !== revision2)
|
|
31501
|
-
throw new SqliteSnapshotChangedError("History database changed while copying; import again.");
|
|
31502
|
-
throw error;
|
|
31503
|
-
}
|
|
31504
|
-
}
|
|
31505
|
-
function withSqliteSnapshot(path, read3, expected, pinned = false) {
|
|
31506
|
-
const retained = copies.get(path);
|
|
31507
|
-
if (pinned && expected && retained?.revision === expected) return read3(retained.db);
|
|
31508
|
-
const revision2 = sqliteRevision(path);
|
|
31509
|
-
if (expected && revision2 !== expected) throw new SqliteSnapshotChangedError("History database changed during import; import again.");
|
|
31510
|
-
let copy = copies.get(path);
|
|
31511
|
-
if (copy?.revision !== revision2) {
|
|
31512
|
-
close(path);
|
|
31513
|
-
while (copies.size >= 2) close(copies.keys().next().value);
|
|
31514
|
-
const directory3 = mkdtempSync(join7(tmpdir(), "sessiongraph-history-"));
|
|
31515
|
-
let db2;
|
|
31516
|
-
try {
|
|
31517
|
-
chmodSync(directory3, 448);
|
|
31518
|
-
const destination = join7(directory3, "history.db");
|
|
31519
|
-
for (const suffix of ["", "-wal"]) {
|
|
31520
|
-
try {
|
|
31521
|
-
copyFileSync(path + suffix, destination + suffix, constants4.COPYFILE_FICLONE);
|
|
31522
|
-
chmodSync(destination + suffix, 384);
|
|
31523
|
-
} catch (error) {
|
|
31524
|
-
if (suffix && error.code === "ENOENT") continue;
|
|
31525
|
-
throw error;
|
|
31526
|
-
}
|
|
31527
|
-
}
|
|
31528
|
-
if (sqliteRevision(path) !== revision2) throw new SqliteSnapshotChangedError("History database changed while copying; import again.");
|
|
31529
|
-
db2 = openSnapshot(destination);
|
|
31530
|
-
copy = { revision: revision2, directory: directory3, db: db2 };
|
|
31531
|
-
copies.set(path, copy);
|
|
31532
|
-
} catch (error) {
|
|
31533
|
-
try {
|
|
31534
|
-
db2?.close();
|
|
31535
|
-
} finally {
|
|
31536
|
-
rmSync2(directory3, { recursive: true, force: true });
|
|
31537
|
-
}
|
|
31538
|
-
throw error;
|
|
31539
|
-
}
|
|
31540
|
-
}
|
|
31541
|
-
const result = read3(copy.db);
|
|
31542
|
-
if (!pinned && sqliteRevision(path) !== revision2) throw new SqliteSnapshotChangedError("History database changed during reading; import again.");
|
|
31543
|
-
return result;
|
|
31544
|
-
}
|
|
31545
|
-
function hasTable(db2, name) {
|
|
31546
|
-
const row = db2.prepare("SELECT sql FROM sqlite_master WHERE type='table' AND name=?").get(name);
|
|
31547
|
-
return typeof row?.sql === "string" && !/CREATE\s+VIRTUAL/i.test(row.sql);
|
|
31548
|
-
}
|
|
31549
|
-
|
|
31550
|
-
// server/adapters/sqlite-histories.ts
|
|
31551
|
-
var budget;
|
|
31552
|
-
var rowBytes = (row) => Object.values(row).reduce((n, v3) => n + (typeof v3 === "string" ? Buffer.byteLength(v3) : v3 instanceof Uint8Array ? v3.byteLength : 8), 0);
|
|
31553
|
-
function consume(bytes2, records = 0) {
|
|
31554
|
-
if (!budget) return;
|
|
31555
|
-
budget.bytes += bytes2;
|
|
31556
|
-
budget.records += records;
|
|
31557
|
-
if (budget.bytes > 64e6 || budget.records > 5e4) throw new Error("Session exceeds the 64 MB / 50,000-record snapshot limit.");
|
|
31558
|
-
}
|
|
31559
|
-
function parseHistory(source, db2, row, path) {
|
|
31560
|
-
const previous = budget;
|
|
31561
|
-
budget = { bytes: 0, records: 0 };
|
|
31562
|
-
try {
|
|
31563
|
-
consume(rowBytes(row), 1);
|
|
31564
|
-
const history = source.parse(db2, row, path);
|
|
31565
|
-
if (history && history.messages.length > 5e4) throw new Error("Session exceeds the 50,000-message limit.");
|
|
31566
|
-
return history;
|
|
31567
|
-
} finally {
|
|
31568
|
-
budget = previous;
|
|
31569
|
-
}
|
|
31570
|
-
}
|
|
31571
|
-
function columns(db2, table) {
|
|
31572
|
-
if (!/^[a-z_][a-z0-9_]*$/.test(table) || !hasTable(db2, table)) throw new Error(`Unsupported history table: ${table}.`);
|
|
31573
|
-
return new Set(db2.prepare(`PRAGMA table_info("${table}")`).all().map((r) => String(r.name)));
|
|
31574
|
-
}
|
|
31575
|
-
function rows(db2, table, fields3, filter, order, limit = 5e4) {
|
|
31576
|
-
const available = columns(db2, table);
|
|
31577
|
-
for (const name of [...fields3, ...filter ? [filter[0]] : [], ...order ? [order] : []]) if (!/^[a-zA-Z_][\w]*$/.test(name)) throw new Error("Invalid history column.");
|
|
31578
|
-
if (filter && !available.has(filter[0])) throw new Error("Unsupported history relation.");
|
|
31579
|
-
const size = (f) => `length(CAST("${f}" AS BLOB))`;
|
|
31580
|
-
const select = fields3.map((f) => available.has(f) ? `CASE WHEN ${size(f)}<=32000000 THEN "${f}" END AS "${f}"` : `NULL AS "${f}"`).join(",");
|
|
31581
|
-
const oversized = fields3.filter((f) => available.has(f)).map((f) => `COALESCE(${size(f)},0)>32000000`).join(" OR ") || "0";
|
|
31582
|
-
const query = `SELECT ${select}, (${oversized}) AS __sessiongraph_oversized FROM "${table}"${filter ? ` WHERE "${filter[0]}"=?` : ""}${order && available.has(order) ? ` ORDER BY "${order}"` : ""} LIMIT ${limit + 1}`;
|
|
31583
|
-
const result = [];
|
|
31584
|
-
let bytes2 = 0;
|
|
31585
|
-
for (const row of db2.prepare(query).iterate(...filter ? [filter[1]] : [])) {
|
|
31586
|
-
if (row.__sessiongraph_oversized) throw new Error("History field exceeds the 32 MB snapshot limit.");
|
|
31587
|
-
delete row.__sessiongraph_oversized;
|
|
31588
|
-
const size2 = rowBytes(row);
|
|
31589
|
-
bytes2 += size2;
|
|
31590
|
-
consume(size2, 1);
|
|
31591
|
-
if (bytes2 > 64e6 || result.length >= limit) throw new Error("History exceeds the 64 MB / record-count query limit.");
|
|
31592
|
-
result.push(row);
|
|
31593
|
-
}
|
|
31594
|
-
return result;
|
|
31595
|
-
}
|
|
31596
|
-
function sqliteJSON(value) {
|
|
31597
|
-
if (value instanceof Uint8Array) {
|
|
31598
|
-
const expanded = expandHistory(Buffer.from(value), Math.max(1, Math.min(32e6, 64e6 - (budget?.bytes || 0))));
|
|
31599
|
-
consume(expanded.byteLength);
|
|
31600
|
-
return JSON.parse(expanded.toString("utf8"));
|
|
31601
|
-
}
|
|
31602
|
-
if (typeof value === "string") return JSON.parse(value);
|
|
31603
|
-
throw new Error("Missing or oversized history payload.");
|
|
31604
|
-
}
|
|
31605
|
-
function optionalJSON(value) {
|
|
31606
|
-
return value == null || value === "" ? {} : sqliteJSON(value);
|
|
31607
|
-
}
|
|
31608
|
-
function sqliteHistoryAdapter(source) {
|
|
31609
|
-
const metadata2 = /* @__PURE__ */ new Map();
|
|
31610
|
-
return {
|
|
31611
|
-
id: source.id,
|
|
31612
|
-
name: source.name,
|
|
31613
|
-
description: source.description || "Local session database",
|
|
31614
|
-
capabilities: { history: source.history !== false, forks: false, children: false, files: false },
|
|
31615
|
-
async detect() {
|
|
31616
|
-
return (await source.paths()).length > 0;
|
|
31617
|
-
},
|
|
31618
|
-
async discover() {
|
|
31619
|
-
const sessions = /* @__PURE__ */ new Map(), errors = [], blocked = [];
|
|
31620
|
-
let unavailable = false;
|
|
31621
|
-
for (const path of await source.paths()) {
|
|
31622
|
-
try {
|
|
31623
|
-
const snapshot2 = sqliteRevision(path), rev = digest([source.version || 2, source.id, snapshot2]);
|
|
31624
|
-
let cached2 = metadata2.get(path);
|
|
31625
|
-
if (!cached2 || cached2.revision !== rev) {
|
|
31626
|
-
cached2 = withSqliteSnapshot(path, (db2) => {
|
|
31627
|
-
const table = typeof source.table === "string" ? source.table : source.table(db2);
|
|
31628
|
-
const values2 = rows(db2, table, source.fields, void 0, source.key, 2e4), found = [];
|
|
31629
|
-
const blocked2 = [], errors2 = [];
|
|
31630
|
-
let failed = 0;
|
|
31631
|
-
for (const row of values2) {
|
|
31632
|
-
try {
|
|
31633
|
-
const h3 = parseHistory(source, db2, row, path);
|
|
31634
|
-
if (!h3) continue;
|
|
31635
|
-
if (source.history !== false && !h3.messages.length) {
|
|
31636
|
-
blocked2.push(identity(source.id, String(row[source.key])));
|
|
31637
|
-
continue;
|
|
31638
|
-
}
|
|
31639
|
-
if (!h3.nativeID || h3.nativeID.length > 512) throw new Error("Missing native session identity.");
|
|
31640
|
-
const created = time(h3.session?.created) || h3.messages.map((m) => time(m.time)).find(Boolean);
|
|
31641
|
-
if (!created) throw new Error("Session has no recorded creation or message date.");
|
|
31642
|
-
const session = { ...blankSession(source.id, h3.nativeID), ...h3.session, created };
|
|
31643
|
-
session.id = identity(source.id, h3.nativeID);
|
|
31644
|
-
session.nativeID = h3.nativeID;
|
|
31645
|
-
session.source = source.id;
|
|
31646
|
-
session.directory = text(session.directory);
|
|
31647
|
-
session.projectID = project(source.id, session.directory).id;
|
|
31648
|
-
session.agent ||= source.name;
|
|
31649
|
-
session.updated ||= created;
|
|
31650
|
-
session.parentID = h3.parent ? identity(source.id, h3.parent) : void 0;
|
|
31651
|
-
session.forkID = h3.fork ? identity(source.id, h3.fork) : void 0;
|
|
31652
|
-
if (!session.title || session.title === "Untitled session") session.title = h3.messages.flatMap((m) => m.role === "user" ? m.fragments.filter((f) => f.kind === "You").map((f) => f.text) : []).find(Boolean)?.replace(/\s+/g, " ").slice(0, 180) || `${source.name} session`;
|
|
31653
|
-
found.push({ session, revision: rev, locator: { path, snapshot: snapshot2, table, key: String(row[source.key]) } });
|
|
31654
|
-
} catch {
|
|
31655
|
-
blocked2.push(identity(source.id, String(row[source.key])));
|
|
31656
|
-
failed++;
|
|
31657
|
-
}
|
|
31658
|
-
}
|
|
31659
|
-
if (failed) errors2.push(`${source.name}: Skipped ${failed} unreadable, undated, unsupported, or oversized ${failed === 1 ? "session" : "sessions"}.`);
|
|
31660
|
-
return { revision: rev, candidates: found, blocked: blocked2, errors: errors2 };
|
|
31661
|
-
}, snapshot2);
|
|
31662
|
-
metadata2.set(path, cached2);
|
|
31663
|
-
}
|
|
31664
|
-
errors.push(...cached2.errors);
|
|
31665
|
-
blocked.push(...cached2.blocked);
|
|
31666
|
-
for (const c of cached2.candidates) {
|
|
31667
|
-
const old = sessions.get(c.session.id);
|
|
31668
|
-
if (!old || c.session.updated > old.session.updated) sessions.set(c.session.id, c);
|
|
31669
|
-
}
|
|
31670
|
-
} catch (error) {
|
|
31671
|
-
unavailable = true;
|
|
31672
|
-
const detail = error instanceof SqliteSnapshotFileError || error instanceof SqliteSnapshotChangedError ? error.message : "Could not read a history database.";
|
|
31673
|
-
errors.push(`${source.name}: ${detail}`);
|
|
31674
|
-
}
|
|
31675
|
-
}
|
|
31676
|
-
const values = [...sessions.values()];
|
|
31677
|
-
return { sessions: values, projects: [...new Map(values.map((c) => {
|
|
31678
|
-
const p = project(source.id, c.session.directory);
|
|
31679
|
-
return [p.id, p];
|
|
31680
|
-
})).values()], warnings: [], errors, blocked, unavailable };
|
|
31681
|
-
},
|
|
31682
|
-
async read(candidate, cursor) {
|
|
31683
|
-
if (cursor) throw new Error("Invalid SQLite history cursor.");
|
|
31684
|
-
const { path, snapshot: snapshot2, key } = candidate.locator;
|
|
31685
|
-
return withSqliteSnapshot(path, (db2) => {
|
|
31686
|
-
const table = typeof source.table === "string" ? source.table : source.table(db2);
|
|
31687
|
-
const row = rows(db2, table, source.fields, [source.key, key], void 0, 1)[0];
|
|
31688
|
-
if (!row) throw new Error("Session metadata is unavailable.");
|
|
31689
|
-
const history = parseHistory(source, db2, row, path);
|
|
31690
|
-
if (!history || history.nativeID !== candidate.session.nativeID) throw new Error("Session identity changed.");
|
|
31691
|
-
if (source.history !== false && !history.messages.length) throw new Error("No readable conversation.");
|
|
31692
|
-
return { messages: history.messages, partial: Boolean(history.partial || history.messages.some((m) => m.partial)), note: history.note };
|
|
31693
|
-
}, snapshot2);
|
|
31694
|
-
}
|
|
31695
|
-
};
|
|
31696
|
-
}
|
|
31697
|
-
async function existingDatabases(paths2) {
|
|
31698
|
-
const found = [];
|
|
31699
|
-
for (const path of new Set(paths2)) {
|
|
31700
|
-
try {
|
|
31701
|
-
if ((await lstat3(path)).isFile()) found.push(path);
|
|
31702
|
-
} catch (e10) {
|
|
31703
|
-
if (e10.code !== "ENOENT") throw e10;
|
|
31704
|
-
}
|
|
31705
|
-
}
|
|
31706
|
-
return found;
|
|
31707
|
-
}
|
|
31708
|
-
function combineAdapters(parts) {
|
|
31709
|
-
const first = parts[0];
|
|
31710
|
-
return {
|
|
31711
|
-
...first,
|
|
31712
|
-
async detect() {
|
|
31713
|
-
for (const p of parts) if (await p.detect().catch(() => false)) return true;
|
|
31714
|
-
return false;
|
|
31715
|
-
},
|
|
31716
|
-
async discover() {
|
|
31717
|
-
const sessions = /* @__PURE__ */ new Map(), projects = /* @__PURE__ */ new Map(), warnings = [], errors = [], blocked = /* @__PURE__ */ new Set();
|
|
31718
|
-
for (const [i, part] of parts.entries()) {
|
|
31719
|
-
let result;
|
|
31720
|
-
try {
|
|
31721
|
-
if (!await part.detect()) continue;
|
|
31722
|
-
result = await part.discover();
|
|
31723
|
-
} catch {
|
|
31724
|
-
errors.push(`${part.name}: Could not read a history source.`);
|
|
31725
|
-
break;
|
|
31726
|
-
}
|
|
31727
|
-
warnings.push(...result.warnings);
|
|
31728
|
-
if (result.errors?.length) errors.push(...result.errors);
|
|
31729
|
-
else if (result.unavailable) errors.push(`${part.name}: History unavailable.`);
|
|
31730
|
-
for (const id2 of result.blocked || []) blocked.add(id2);
|
|
31731
|
-
for (const p of result.projects) projects.set(p.id, p);
|
|
31732
|
-
for (const c of result.sessions) if (!blocked.has(c.session.id) && !sessions.has(c.session.id)) sessions.set(c.session.id, { ...c, revision: digest([i, c.revision]), locator: { ...c.locator, representation: String(i), originalRevision: c.revision } });
|
|
31733
|
-
if (result.unavailable) break;
|
|
31734
|
-
}
|
|
31735
|
-
return { sessions: [...sessions.values()], projects: [...projects.values()], warnings, errors };
|
|
31736
|
-
},
|
|
31737
|
-
async read(candidate, cursor) {
|
|
31738
|
-
const index = Number(candidate.locator.representation);
|
|
31739
|
-
if (!Number.isInteger(index) || !parts[index]) throw new Error("Invalid history representation.");
|
|
31740
|
-
return parts[index].read({ ...candidate, revision: candidate.locator.originalRevision }, cursor);
|
|
31741
|
-
}
|
|
31742
|
-
};
|
|
31743
|
-
}
|
|
31744
|
-
|
|
31745
31929
|
// server/adapters/claude.ts
|
|
31746
|
-
var root = () =>
|
|
31930
|
+
var root = () => join10(sourcePath("claude-code") || process.env.CLAUDE_CONFIG_DIR || join10(homedir5(), ".claude"), "projects");
|
|
31747
31931
|
function claudeMessages(rows2, candidate, times, entries2) {
|
|
31748
31932
|
const calls = /* @__PURE__ */ new Map();
|
|
31749
31933
|
return rows2.map((row) => {
|
|
@@ -31805,21 +31989,21 @@ var sdkClaudeAdapter = {
|
|
|
31805
31989
|
if (infos.length === 2e4) warnings.push("Claude Code listing is limited to 20,000 sessions.");
|
|
31806
31990
|
const files = /* @__PURE__ */ new Map();
|
|
31807
31991
|
let unreadable = 0;
|
|
31808
|
-
for (const dir of await
|
|
31992
|
+
for (const dir of await readdir3(root(), { withFileTypes: true })) {
|
|
31809
31993
|
if (!dir.isDirectory()) continue;
|
|
31810
|
-
const parent2 =
|
|
31994
|
+
const parent2 = join10(root(), dir.name);
|
|
31811
31995
|
let entries2;
|
|
31812
31996
|
try {
|
|
31813
|
-
entries2 = await
|
|
31997
|
+
entries2 = await readdir3(parent2, { withFileTypes: true });
|
|
31814
31998
|
} catch {
|
|
31815
31999
|
unreadable++;
|
|
31816
32000
|
continue;
|
|
31817
32001
|
}
|
|
31818
32002
|
for (const file of entries2) if (file.isFile() && file.name.endsWith(".jsonl") && claudeSessionID(file.name.slice(0, -6))) {
|
|
31819
|
-
const id2 = file.name.slice(0, -6), path =
|
|
32003
|
+
const id2 = file.name.slice(0, -6), path = join10(parent2, file.name);
|
|
31820
32004
|
try {
|
|
31821
32005
|
const old = files.get(id2);
|
|
31822
|
-
if (!old || (await stat(path)).mtimeMs > (await stat(old.path)).mtimeMs) files.set(id2, { path, children:
|
|
32006
|
+
if (!old || (await stat(path)).mtimeMs > (await stat(old.path)).mtimeMs) files.set(id2, { path, children: join10(parent2, id2, "subagents") });
|
|
31823
32007
|
} catch {
|
|
31824
32008
|
unreadable++;
|
|
31825
32009
|
}
|
|
@@ -31853,7 +32037,7 @@ var sdkClaudeAdapter = {
|
|
|
31853
32037
|
}
|
|
31854
32038
|
let children;
|
|
31855
32039
|
try {
|
|
31856
|
-
children = await
|
|
32040
|
+
children = await readdir3(file.children, { withFileTypes: true });
|
|
31857
32041
|
} catch (error) {
|
|
31858
32042
|
if (error.code !== "ENOENT") unreadable++;
|
|
31859
32043
|
continue;
|
|
@@ -31861,7 +32045,7 @@ var sdkClaudeAdapter = {
|
|
|
31861
32045
|
for (const child of children) {
|
|
31862
32046
|
if (!child.isFile() || !/^agent-[\w-]+\.jsonl$/.test(child.name)) continue;
|
|
31863
32047
|
try {
|
|
31864
|
-
const agent = child.name.slice(6, -6), path =
|
|
32048
|
+
const agent = child.name.slice(6, -6), path = join10(file.children, child.name), stats = await stat(path);
|
|
31865
32049
|
sessions.push({ session: { ...s, id: identity("claude-code", `${info.sessionId}/agent/${agent}`), nativeID: `${info.sessionId}/agent/${agent}`, title: `Subagent ${agent}`, created: stats.birthtimeMs || s.created, updated: stats.mtimeMs, parentID: s.id, origin: "automated", agent }, revision: await claudeRevision(path), locator: { path, dir: info.cwd || "", parent: info.sessionId, agent } });
|
|
31866
32050
|
} catch {
|
|
31867
32051
|
unreadable++;
|
|
@@ -31909,7 +32093,7 @@ var exportedClaudeAdapter = localFileAdapter({
|
|
|
31909
32093
|
name: "Claude Code",
|
|
31910
32094
|
description: "Legacy local transcript exports",
|
|
31911
32095
|
capabilities: { history: true, forks: false, children: false, files: false },
|
|
31912
|
-
roots: () => [
|
|
32096
|
+
roots: () => [join10(sourcePath("claude-code") || process.env.CLAUDE_CONFIG_DIR || join10(homedir5(), ".claude"), "transcripts")],
|
|
31913
32097
|
match: (p) => p.endsWith(".jsonl"),
|
|
31914
32098
|
parse: (path, files) => envelopeHistory(path, files.get(path))
|
|
31915
32099
|
});
|
|
@@ -31917,12 +32101,12 @@ var claudeAdapter = combineAdapters([sdkClaudeAdapter, exportedClaudeAdapter]);
|
|
|
31917
32101
|
|
|
31918
32102
|
// server/adapters/codex.ts
|
|
31919
32103
|
import { stat as stat2 } from "node:fs/promises";
|
|
31920
|
-
import { homedir as
|
|
31921
|
-
import { join as
|
|
32104
|
+
import { homedir as homedir6 } from "node:os";
|
|
32105
|
+
import { join as join12, sep as sep2 } from "node:path";
|
|
31922
32106
|
|
|
31923
32107
|
// server/adapters/jsonl.ts
|
|
31924
|
-
import { open as open3, readdir as
|
|
31925
|
-
import { join as
|
|
32108
|
+
import { open as open3, readdir as readdir4 } from "node:fs/promises";
|
|
32109
|
+
import { join as join11 } from "node:path";
|
|
31926
32110
|
import { constants as constants5 } from "node:fs";
|
|
31927
32111
|
var compressed;
|
|
31928
32112
|
async function readJSONL(path, offset = 0, budget2 = 2e6, limit = 200) {
|
|
@@ -31999,14 +32183,14 @@ async function transcriptFiles(root3, max = 2e4, match2 = (name) => name.endsWit
|
|
|
31999
32183
|
for (let i = 0; i < queue.length && files.length < max; i++) {
|
|
32000
32184
|
let entries2;
|
|
32001
32185
|
try {
|
|
32002
|
-
entries2 = await
|
|
32186
|
+
entries2 = await readdir4(queue[i], { withFileTypes: true });
|
|
32003
32187
|
} catch (error) {
|
|
32004
32188
|
if (error.code === "ENOENT") continue;
|
|
32005
32189
|
throw error;
|
|
32006
32190
|
}
|
|
32007
32191
|
for (const entry of entries2) {
|
|
32008
|
-
if (entry.isDirectory() && queue.length < 2e4) queue.push(
|
|
32009
|
-
if (entry.isFile() && match2(entry.name)) files.push(
|
|
32192
|
+
if (entry.isDirectory() && queue.length < 2e4) queue.push(join11(queue[i], entry.name));
|
|
32193
|
+
if (entry.isFile() && match2(entry.name)) files.push(join11(queue[i], entry.name));
|
|
32010
32194
|
if (files.length >= max) break;
|
|
32011
32195
|
}
|
|
32012
32196
|
}
|
|
@@ -32014,7 +32198,7 @@ async function transcriptFiles(root3, max = 2e4, match2 = (name) => name.endsWit
|
|
|
32014
32198
|
}
|
|
32015
32199
|
|
|
32016
32200
|
// server/adapters/codex.ts
|
|
32017
|
-
var root2 = () => sourcePath("codex") || process.env.CODEX_HOME ||
|
|
32201
|
+
var root2 = () => sourcePath("codex") || process.env.CODEX_HOME || join12(homedir6(), ".codex");
|
|
32018
32202
|
var revision = async (path) => {
|
|
32019
32203
|
const s = await stat2(path);
|
|
32020
32204
|
return digest([10, s.mtimeMs, s.size]);
|
|
@@ -32042,7 +32226,7 @@ async function sessionNames() {
|
|
|
32042
32226
|
let cursor, count = 0;
|
|
32043
32227
|
try {
|
|
32044
32228
|
do {
|
|
32045
|
-
const page = await readJSONL(
|
|
32229
|
+
const page = await readJSONL(join12(root2(), "session_index.jsonl"), cursor, 2e6, 1e3);
|
|
32046
32230
|
for (const { value } of page.rows) if (typeof value.id === "string" && typeof value.thread_name === "string" && value.thread_name.trim()) names.set(value.id, value.thread_name.trim().slice(0, 300));
|
|
32047
32231
|
cursor = page.cursor;
|
|
32048
32232
|
count += page.rows.length;
|
|
@@ -32133,7 +32317,7 @@ var codexAdapter = {
|
|
|
32133
32317
|
const found = /* @__PURE__ */ new Map(), warnings = [];
|
|
32134
32318
|
const names = await sessionNames();
|
|
32135
32319
|
const match2 = (name) => /\.jsonl(?:\.[\w.-]+)?$/.test(name);
|
|
32136
|
-
const paths2 = [...await transcriptFiles(
|
|
32320
|
+
const paths2 = [...await transcriptFiles(join12(root2(), "sessions"), 2e4, match2), ...await transcriptFiles(join12(root2(), "archived_sessions"), 2e4, match2)];
|
|
32137
32321
|
if (paths2.length >= 2e4) warnings.push("Codex transcript listing may be partial (20,000 files per history folder).");
|
|
32138
32322
|
let unsupported = 0;
|
|
32139
32323
|
for (const path of paths2) {
|
|
@@ -32186,11 +32370,11 @@ var codexAdapter = {
|
|
|
32186
32370
|
};
|
|
32187
32371
|
|
|
32188
32372
|
// server/adapters/t3-code.ts
|
|
32189
|
-
import { lstat as
|
|
32190
|
-
import { homedir as
|
|
32191
|
-
import { isAbsolute as isAbsolute2, join as
|
|
32373
|
+
import { lstat as lstat5 } from "node:fs/promises";
|
|
32374
|
+
import { homedir as homedir7 } from "node:os";
|
|
32375
|
+
import { isAbsolute as isAbsolute2, join as join13 } from "node:path";
|
|
32192
32376
|
var SOURCE = "t3-code";
|
|
32193
|
-
var
|
|
32377
|
+
var PAGE2 = 100;
|
|
32194
32378
|
var MAX_ITEM_JSON = 256e3;
|
|
32195
32379
|
var providerSource = { codex: "codex", claudeAgent: "claude-code", opencode: "opencode" };
|
|
32196
32380
|
var openCodeEditTools = /* @__PURE__ */ new Set(["patch", "apply_patch", "edit", "write", "multiedit"]);
|
|
@@ -32212,16 +32396,16 @@ function status(value) {
|
|
|
32212
32396
|
return ["pending", "running", "completed", "failed"].includes(string3(value)) ? value : "unknown";
|
|
32213
32397
|
}
|
|
32214
32398
|
async function databasePath2() {
|
|
32215
|
-
const root3 = sourcePath("t3-code") || process.env.SESSIONGRAPH_T3_CODE_HISTORY_DIR || process.env.T3CODE_HOME ||
|
|
32399
|
+
const root3 = sourcePath("t3-code") || process.env.SESSIONGRAPH_T3_CODE_HISTORY_DIR || process.env.T3CODE_HOME || join13(homedir7(), ".t3");
|
|
32216
32400
|
const paths2 = /\.sqlite$/.test(root3) ? [root3] : [
|
|
32217
|
-
|
|
32218
|
-
|
|
32219
|
-
|
|
32220
|
-
|
|
32401
|
+
join13(root3, "userdata", "statev2.sqlite"),
|
|
32402
|
+
join13(root3, "statev2.sqlite"),
|
|
32403
|
+
join13(root3, "userdata", "state.sqlite"),
|
|
32404
|
+
join13(root3, "state.sqlite")
|
|
32221
32405
|
];
|
|
32222
32406
|
for (const path of paths2) {
|
|
32223
32407
|
try {
|
|
32224
|
-
if ((await
|
|
32408
|
+
if ((await lstat5(path)).isFile()) return path;
|
|
32225
32409
|
} catch (error) {
|
|
32226
32410
|
if (error.code !== "ENOENT") throw error;
|
|
32227
32411
|
}
|
|
@@ -32413,7 +32597,7 @@ function v2Message(row, directory3) {
|
|
|
32413
32597
|
message2.events = [eventFor(message2, id2, kind2, file, "", { ...fields3, callID: string3(native.nativeId) || void 0 })];
|
|
32414
32598
|
return message2;
|
|
32415
32599
|
}
|
|
32416
|
-
if (file && completed) message2.files.push({ path: isAbsolute2(file) ? file :
|
|
32600
|
+
if (file && completed) message2.files.push({ path: isAbsolute2(file) ? file : join13(directory3, file), source: "file change", steps: 1 });
|
|
32417
32601
|
message2.events = [eventFor(message2, id2, "file_change", file || name, "", fields3)];
|
|
32418
32602
|
return message2;
|
|
32419
32603
|
}
|
|
@@ -32444,11 +32628,11 @@ function readV2(db2, candidate, cursor) {
|
|
|
32444
32628
|
CASE WHEN length(payload_json)<=? THEN payload_json END AS payload_json
|
|
32445
32629
|
FROM orchestration_v2_projection_turn_items
|
|
32446
32630
|
WHERE thread_id=? AND (ordinal>? OR (ordinal=? AND turn_item_id>?))
|
|
32447
|
-
ORDER BY ordinal, turn_item_id LIMIT ?`).all(MAX_ITEM_JSON, candidate.locator.threadID, ordinal, ordinal, id2,
|
|
32448
|
-
const page = rows2.slice(0,
|
|
32631
|
+
ORDER BY ordinal, turn_item_id LIMIT ?`).all(MAX_ITEM_JSON, candidate.locator.threadID, ordinal, ordinal, id2, PAGE2 + 1);
|
|
32632
|
+
const page = rows2.slice(0, PAGE2), last = page.at(-1);
|
|
32449
32633
|
return {
|
|
32450
32634
|
messages: page.map((row) => v2Message(row, candidate.session.directory)),
|
|
32451
|
-
cursor: rows2.length >
|
|
32635
|
+
cursor: rows2.length > PAGE2 && last ? `${last.ordinal}:${last.turn_item_id}` : void 0,
|
|
32452
32636
|
partial: candidate.locator.metadataPartial === "1" || page.some((row) => !parsedObject(row.payload_json))
|
|
32453
32637
|
};
|
|
32454
32638
|
}
|
|
@@ -32457,8 +32641,8 @@ function readV1(db2, candidate, cursor) {
|
|
|
32457
32641
|
if (!Number.isSafeInteger(offset) || offset < 0) throw new Error("Invalid T3 Code history cursor.");
|
|
32458
32642
|
const rows2 = db2.prepare(`SELECT message_id, role, created_at,
|
|
32459
32643
|
CASE WHEN length(text)<=? THEN text END AS text FROM projection_thread_messages
|
|
32460
|
-
WHERE thread_id=? ORDER BY created_at, message_id LIMIT ? OFFSET ?`).all(MAX_ITEM_JSON, candidate.locator.threadID,
|
|
32461
|
-
const messages = rows2.slice(0,
|
|
32644
|
+
WHERE thread_id=? ORDER BY created_at, message_id LIMIT ? OFFSET ?`).all(MAX_ITEM_JSON, candidate.locator.threadID, PAGE2 + 1, offset);
|
|
32645
|
+
const messages = rows2.slice(0, PAGE2).map((row) => {
|
|
32462
32646
|
const role = row.role === "user" ? "user" : row.role === "assistant" ? "assistant" : "system";
|
|
32463
32647
|
const message2 = blankMessage(`message:${row.message_id}`, time2(row.created_at), role);
|
|
32464
32648
|
const body2 = string3(row.text);
|
|
@@ -32469,7 +32653,7 @@ function readV1(db2, candidate, cursor) {
|
|
|
32469
32653
|
});
|
|
32470
32654
|
return {
|
|
32471
32655
|
messages,
|
|
32472
|
-
cursor: rows2.length >
|
|
32656
|
+
cursor: rows2.length > PAGE2 ? String(offset + PAGE2) : void 0,
|
|
32473
32657
|
partial: true,
|
|
32474
32658
|
note: "Legacy T3 Code: conversation text only."
|
|
32475
32659
|
};
|
|
@@ -32499,10 +32683,10 @@ var t3CodeAdapter = {
|
|
|
32499
32683
|
};
|
|
32500
32684
|
|
|
32501
32685
|
// server/adapters/cursor.ts
|
|
32502
|
-
import { createHash as
|
|
32503
|
-
import { lstat as
|
|
32504
|
-
import { homedir as
|
|
32505
|
-
import { isAbsolute as isAbsolute4, join as
|
|
32686
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
32687
|
+
import { lstat as lstat6, opendir, readFile as readFile3 } from "node:fs/promises";
|
|
32688
|
+
import { homedir as homedir8 } from "node:os";
|
|
32689
|
+
import { isAbsolute as isAbsolute4, join as join15 } from "node:path";
|
|
32506
32690
|
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
32507
32691
|
|
|
32508
32692
|
// server/adapters/cursor-message.ts
|
|
@@ -32604,7 +32788,7 @@ function cursorMessage(raw, fallbackID) {
|
|
|
32604
32788
|
import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
|
|
32605
32789
|
import { chmodSync as chmodSync2, copyFileSync as copyFileSync2, lstatSync as lstatSync3, mkdtempSync as mkdtempSync2, rmSync as rmSync3 } from "node:fs";
|
|
32606
32790
|
import { tmpdir as tmpdir2 } from "node:os";
|
|
32607
|
-
import { join as
|
|
32791
|
+
import { join as join14 } from "node:path";
|
|
32608
32792
|
var MAX_VALUE = 2e6;
|
|
32609
32793
|
var MAX_BYTES3 = 64e6;
|
|
32610
32794
|
var MAX_NODES = 5e4;
|
|
@@ -32621,11 +32805,11 @@ function withStore(path, read3) {
|
|
|
32621
32805
|
throw error;
|
|
32622
32806
|
}
|
|
32623
32807
|
});
|
|
32624
|
-
const before = stats(), directory3 = mkdtempSync2(
|
|
32808
|
+
const before = stats(), directory3 = mkdtempSync2(join14(tmpdir2(), "sessiongraph-cursor-"));
|
|
32625
32809
|
let db2;
|
|
32626
32810
|
try {
|
|
32627
32811
|
chmodSync2(directory3, 448);
|
|
32628
|
-
const copy =
|
|
32812
|
+
const copy = join14(directory3, "store.db");
|
|
32629
32813
|
files.forEach((file, index) => {
|
|
32630
32814
|
if (before[index]) {
|
|
32631
32815
|
const target = index ? `${copy}-wal` : copy;
|
|
@@ -32879,11 +33063,11 @@ var LIMIT = 2e4;
|
|
|
32879
33063
|
var validID = (id2) => /^[a-z\d][\w-]{0,159}$/i.test(id2);
|
|
32880
33064
|
var cwd = (value) => typeof value === "string" && isAbsolute4(value) && !/[\x00-\x1f\x7f]/.test(value) ? value : "";
|
|
32881
33065
|
var slug = (path) => path.replace(/\\/g, "/").replace(/^([A-Z]):/i, (_, drive) => drive.toLowerCase()).replace(/^\/+|\/+$/g, "").replace(/[/:]+/g, "-");
|
|
32882
|
-
var hashCwd = (path) =>
|
|
32883
|
-
var userData = () => process.platform === "darwin" ?
|
|
33066
|
+
var hashCwd = (path) => createHash2("md5").update(path).digest("hex");
|
|
33067
|
+
var userData = () => process.platform === "darwin" ? join15(homedir8(), "Library/Application Support/Cursor") : process.platform === "win32" ? join15(process.env.APPDATA || join15(homedir8(), "AppData/Roaming"), "Cursor") : join15(process.env.XDG_CONFIG_HOME || join15(homedir8(), ".config"), "Cursor");
|
|
32884
33068
|
async function fileStats(path) {
|
|
32885
33069
|
try {
|
|
32886
|
-
const s = await
|
|
33070
|
+
const s = await lstat6(path);
|
|
32887
33071
|
if (s.isSymbolicLink()) throw new Error("Cursor history symlinks are not followed.");
|
|
32888
33072
|
return s.isFile() ? s : void 0;
|
|
32889
33073
|
} catch (error) {
|
|
@@ -32908,7 +33092,7 @@ async function json4(path) {
|
|
|
32908
33092
|
async function entries(path, warnings) {
|
|
32909
33093
|
const result = [];
|
|
32910
33094
|
try {
|
|
32911
|
-
if (!(await
|
|
33095
|
+
if (!(await lstat6(path)).isDirectory()) return result;
|
|
32912
33096
|
for await (const entry of await opendir(path)) {
|
|
32913
33097
|
if (!entry.isSymbolicLink()) result.push(entry);
|
|
32914
33098
|
if (result.length === LIMIT) {
|
|
@@ -32923,12 +33107,12 @@ async function entries(path, warnings) {
|
|
|
32923
33107
|
}
|
|
32924
33108
|
async function workspacePaths(root3, warnings) {
|
|
32925
33109
|
const stores = /* @__PURE__ */ new Map();
|
|
32926
|
-
const storage =
|
|
33110
|
+
const storage = join15(root3, "User/workspaceStorage");
|
|
32927
33111
|
for (const entry of await entries(storage, warnings)) if (entry.isDirectory()) {
|
|
32928
|
-
const database =
|
|
33112
|
+
const database = join15(storage, entry.name, "state.vscdb");
|
|
32929
33113
|
stores.set(database, "");
|
|
32930
33114
|
try {
|
|
32931
|
-
const info = await json4(
|
|
33115
|
+
const info = await json4(join15(storage, entry.name, "workspace.json"));
|
|
32932
33116
|
if (typeof info.folder === "string" && info.folder.startsWith("file:")) {
|
|
32933
33117
|
const path = cwd(fileURLToPath2(info.folder));
|
|
32934
33118
|
if (path) stores.set(database, path);
|
|
@@ -32940,7 +33124,7 @@ async function workspacePaths(root3, warnings) {
|
|
|
32940
33124
|
return stores;
|
|
32941
33125
|
}
|
|
32942
33126
|
function createCursorAdapter(options = {}) {
|
|
32943
|
-
const root3 = () => options.home || sourcePath("cursor") || process.env.SESSIONGRAPH_CURSOR_HOME || process.env.SESSION_ATLAS_CURSOR_HOME ||
|
|
33127
|
+
const root3 = () => options.home || sourcePath("cursor") || process.env.SESSIONGRAPH_CURSOR_HOME || process.env.SESSION_ATLAS_CURSOR_HOME || join15(homedir8(), ".cursor");
|
|
32944
33128
|
const editor = () => options.userData || process.env.SESSIONGRAPH_CURSOR_USER_DATA_DIR || process.env.SESSION_ATLAS_CURSOR_USER_DATA_DIR || userData();
|
|
32945
33129
|
return {
|
|
32946
33130
|
id: "cursor",
|
|
@@ -32948,13 +33132,13 @@ function createCursorAdapter(options = {}) {
|
|
|
32948
33132
|
description: "Local IDE, Composer, and CLI sessions",
|
|
32949
33133
|
capabilities: { history: true, forks: false, children: true, files: false },
|
|
32950
33134
|
async detect() {
|
|
32951
|
-
if (await fileStats(
|
|
32952
|
-
for (const entry of await entries(
|
|
32953
|
-
if (entry.isDirectory() && await fileStats(
|
|
33135
|
+
if (await fileStats(join15(editor(), "User/globalStorage/state.vscdb"))) return true;
|
|
33136
|
+
for (const entry of await entries(join15(editor(), "User/workspaceStorage"), [])) {
|
|
33137
|
+
if (entry.isDirectory() && await fileStats(join15(editor(), "User/workspaceStorage", entry.name, "state.vscdb"))) return true;
|
|
32954
33138
|
}
|
|
32955
33139
|
for (const name of ["projects", "chats", "acp-sessions"]) {
|
|
32956
33140
|
try {
|
|
32957
|
-
if ((await
|
|
33141
|
+
if ((await lstat6(join15(root3(), name))).isDirectory()) return true;
|
|
32958
33142
|
} catch {
|
|
32959
33143
|
}
|
|
32960
33144
|
}
|
|
@@ -32964,7 +33148,7 @@ function createCursorAdapter(options = {}) {
|
|
|
32964
33148
|
const warnings = [], errors = [], found = /* @__PURE__ */ new Map(), blocked = /* @__PURE__ */ new Set();
|
|
32965
33149
|
const workspaceStores = await workspacePaths(editor(), warnings);
|
|
32966
33150
|
const paths2 = [...new Set([...workspaceStores.values()].filter(Boolean))];
|
|
32967
|
-
const legacyStores = new Map([[
|
|
33151
|
+
const legacyStores = new Map([[join15(editor(), "User/globalStorage/state.vscdb"), ""], ...workspaceStores]);
|
|
32968
33152
|
for (const [path, workspace] of legacyStores) {
|
|
32969
33153
|
try {
|
|
32970
33154
|
if (!await fileStats(path)) continue;
|
|
@@ -32995,7 +33179,7 @@ function createCursorAdapter(options = {}) {
|
|
|
32995
33179
|
if (!stats) return;
|
|
32996
33180
|
const native = parent2 ? `${parent2}/agent/${id2}` : id2;
|
|
32997
33181
|
const locator = { path, kind };
|
|
32998
|
-
if (kind !== "transcript") locator.meta =
|
|
33182
|
+
if (kind !== "transcript") locator.meta = join15(path, "..", "meta.json");
|
|
32999
33183
|
const before = await snapshot(locator);
|
|
33000
33184
|
const extra2 = locator.meta ? await json4(locator.meta) : {};
|
|
33001
33185
|
const meta = kind === "transcript" ? {} : cursorStoreMetadata(path);
|
|
@@ -33037,7 +33221,7 @@ function createCursorAdapter(options = {}) {
|
|
|
33037
33221
|
}
|
|
33038
33222
|
if (!session.directory) locator.directoryNote = "Working directory is unknown; choose one when continuing.";
|
|
33039
33223
|
session.projectID = project("cursor", session.directory).id;
|
|
33040
|
-
session.nativeResume = kind === "cli" && Boolean(session.directory) && hashCwd(session.directory) === workspaceHash && root3() ===
|
|
33224
|
+
session.nativeResume = kind === "cli" && Boolean(session.directory) && hashCwd(session.directory) === workspaceHash && root3() === join15(homedir8(), ".cursor");
|
|
33041
33225
|
locator.snapshot = before;
|
|
33042
33226
|
if (await snapshot(locator) !== before) throw new Error("Cursor session changed during discovery.");
|
|
33043
33227
|
const previous = found.get(session.id);
|
|
@@ -33060,39 +33244,39 @@ function createCursorAdapter(options = {}) {
|
|
|
33060
33244
|
if (kind !== "transcript") blocked.add(identity("cursor", id2));
|
|
33061
33245
|
}
|
|
33062
33246
|
};
|
|
33063
|
-
const projects =
|
|
33247
|
+
const projects = join15(root3(), "projects");
|
|
33064
33248
|
for (const dir of await entries(projects, warnings)) {
|
|
33065
33249
|
if (!dir.isDirectory() || scanned >= LIMIT) continue;
|
|
33066
|
-
const transcripts =
|
|
33250
|
+
const transcripts = join15(projects, dir.name, "agent-transcripts"), directory3 = match2(dir.name, slug);
|
|
33067
33251
|
for (const entry of await entries(transcripts, warnings)) {
|
|
33068
33252
|
if (scanned >= LIMIT) break;
|
|
33069
|
-
if (entry.isFile() && entry.name.endsWith(".jsonl")) await add(
|
|
33253
|
+
if (entry.isFile() && entry.name.endsWith(".jsonl")) await add(join15(transcripts, entry.name), entry.name.slice(0, -6), "transcript", directory3);
|
|
33070
33254
|
else if (entry.isFile() && entry.name.endsWith(".txt")) legacy++;
|
|
33071
33255
|
else if (entry.isDirectory() && validID(entry.name)) {
|
|
33072
|
-
await add(
|
|
33073
|
-
for (const child of await entries(
|
|
33074
|
-
if (child.isFile() && child.name.endsWith(".jsonl")) await add(
|
|
33256
|
+
await add(join15(transcripts, entry.name, `${entry.name}.jsonl`), entry.name, "transcript", directory3);
|
|
33257
|
+
for (const child of await entries(join15(transcripts, entry.name, "subagents"), warnings)) {
|
|
33258
|
+
if (child.isFile() && child.name.endsWith(".jsonl")) await add(join15(transcripts, entry.name, "subagents", child.name), child.name.slice(0, -6), "transcript", directory3, entry.name);
|
|
33075
33259
|
if (scanned >= LIMIT) break;
|
|
33076
33260
|
}
|
|
33077
33261
|
}
|
|
33078
33262
|
}
|
|
33079
33263
|
}
|
|
33080
|
-
const chats =
|
|
33264
|
+
const chats = join15(root3(), "chats");
|
|
33081
33265
|
for (const bucket of await entries(chats, warnings)) {
|
|
33082
33266
|
if (!bucket.isDirectory() || scanned >= LIMIT) continue;
|
|
33083
|
-
const folder =
|
|
33084
|
-
if (/^[a-f\d]{32}$/i.test(bucket.name) && await fileStats(
|
|
33267
|
+
const folder = join15(chats, bucket.name), directory3 = match2(bucket.name, hashCwd);
|
|
33268
|
+
if (/^[a-f\d]{32}$/i.test(bucket.name) && await fileStats(join15(folder, "store.db"))) {
|
|
33085
33269
|
const id2 = bucket.name.replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, "$1-$2-$3-$4-$5");
|
|
33086
|
-
await add(
|
|
33270
|
+
await add(join15(folder, "store.db"), id2, "cli", "");
|
|
33087
33271
|
}
|
|
33088
33272
|
for (const entry of await entries(folder, warnings)) {
|
|
33089
|
-
if (entry.isDirectory()) await add(
|
|
33273
|
+
if (entry.isDirectory()) await add(join15(folder, entry.name, "store.db"), entry.name, "cli", directory3, "", bucket.name);
|
|
33090
33274
|
if (scanned >= LIMIT) break;
|
|
33091
33275
|
}
|
|
33092
33276
|
}
|
|
33093
|
-
const acp =
|
|
33277
|
+
const acp = join15(root3(), "acp-sessions");
|
|
33094
33278
|
for (const entry of await entries(acp, warnings)) {
|
|
33095
|
-
if (entry.isDirectory()) await add(
|
|
33279
|
+
if (entry.isDirectory()) await add(join15(acp, entry.name, "store.db"), entry.name, "acp", "");
|
|
33096
33280
|
if (scanned >= LIMIT) break;
|
|
33097
33281
|
}
|
|
33098
33282
|
if (scanned >= LIMIT) warnings.push("Cursor discovery limited to 20,000 history files.");
|
|
@@ -33139,11 +33323,11 @@ function createCursorAdapter(options = {}) {
|
|
|
33139
33323
|
var cursorAdapter = createCursorAdapter();
|
|
33140
33324
|
|
|
33141
33325
|
// server/adapters/gemini.ts
|
|
33142
|
-
import { homedir as
|
|
33143
|
-
import { basename as
|
|
33326
|
+
import { homedir as homedir9 } from "node:os";
|
|
33327
|
+
import { basename as basename4, dirname as dirname3, join as join16, sep as sep3 } from "node:path";
|
|
33144
33328
|
function projectRootFile(path) {
|
|
33145
33329
|
const parts = path.split(sep3);
|
|
33146
|
-
return
|
|
33330
|
+
return join16(parts.slice(0, parts.lastIndexOf("chats")).join(sep3), ".project_root");
|
|
33147
33331
|
}
|
|
33148
33332
|
function geminiConversation(contents, lines) {
|
|
33149
33333
|
const parsed = lines ? jsonLines(contents) : { rows: [object3(json3(contents))], partial: false };
|
|
@@ -33194,7 +33378,7 @@ var geminiAdapter = localFileAdapter({
|
|
|
33194
33378
|
name: "Gemini CLI",
|
|
33195
33379
|
description: "Local JSON and JSONL chats, including recorded subagent histories",
|
|
33196
33380
|
capabilities: { history: true, forks: false, children: true, files: true },
|
|
33197
|
-
roots: () => sourcePath("gemini") || process.env.SESSIONGRAPH_GEMINI_HOME ? [
|
|
33381
|
+
roots: () => sourcePath("gemini") || process.env.SESSIONGRAPH_GEMINI_HOME ? [join16(sourcePath("gemini") || process.env.SESSIONGRAPH_GEMINI_HOME, "tmp")] : [join16(process.env.GEMINI_CLI_HOME || homedir9(), ".gemini", "tmp"), join16(process.env.GEMINI_CLI_HOME || homedir9(), ".cache", ".gemini", "tmp")],
|
|
33198
33382
|
match: (path) => /^[^/]+\/chats\/(?:[^/]+\/)?[^/]+\.jsonl?$/.test(path),
|
|
33199
33383
|
extras: (path) => [projectRootFile(path)],
|
|
33200
33384
|
parse(path, files) {
|
|
@@ -33219,7 +33403,7 @@ var geminiAdapter = localFileAdapter({
|
|
|
33219
33403
|
return message2;
|
|
33220
33404
|
});
|
|
33221
33405
|
successfulEdits(messages, ["write_file", "replace"]);
|
|
33222
|
-
const parent2 = meta.kind === "subagent" &&
|
|
33406
|
+
const parent2 = meta.kind === "subagent" && basename4(dirname3(dirname3(path))) === "chats" ? basename4(dirname3(path)) : void 0;
|
|
33223
33407
|
return {
|
|
33224
33408
|
nativeID: meta.sessionId,
|
|
33225
33409
|
messages,
|
|
@@ -33231,14 +33415,14 @@ var geminiAdapter = localFileAdapter({
|
|
|
33231
33415
|
});
|
|
33232
33416
|
|
|
33233
33417
|
// server/adapters/qwen.ts
|
|
33234
|
-
import { homedir as
|
|
33235
|
-
import { join as
|
|
33418
|
+
import { homedir as homedir10 } from "node:os";
|
|
33419
|
+
import { join as join17 } from "node:path";
|
|
33236
33420
|
var qwenAdapter = localFileAdapter({
|
|
33237
33421
|
id: "qwen-code",
|
|
33238
33422
|
name: "Qwen Code",
|
|
33239
33423
|
description: "Local project chat records \xB7 tool results, forks, and child sessions",
|
|
33240
33424
|
capabilities: { history: true, forks: true, children: true, files: true },
|
|
33241
|
-
roots: () => [
|
|
33425
|
+
roots: () => [join17(sourcePath("qwen-code") || process.env.SESSIONGRAPH_QWEN_HOME || process.env.QWEN_RUNTIME_DIR || process.env.QWEN_HOME || join17(homedir10(), ".qwen"), "projects")],
|
|
33242
33426
|
match: (path) => /^[^/]+\/chats\/[^/]+\.jsonl$/.test(path),
|
|
33243
33427
|
parse(path, files) {
|
|
33244
33428
|
const { rows: rows2, partial } = jsonLines(files.get(path));
|
|
@@ -33276,14 +33460,14 @@ var qwenAdapter = localFileAdapter({
|
|
|
33276
33460
|
});
|
|
33277
33461
|
|
|
33278
33462
|
// server/adapters/copilot.ts
|
|
33279
|
-
import { homedir as
|
|
33280
|
-
import { join as
|
|
33463
|
+
import { homedir as homedir11 } from "node:os";
|
|
33464
|
+
import { join as join18 } from "node:path";
|
|
33281
33465
|
var copilotAdapter = localFileAdapter({
|
|
33282
33466
|
id: "copilot",
|
|
33283
33467
|
name: "GitHub Copilot CLI",
|
|
33284
33468
|
description: "Local session event logs \xB7 conversations and completed file edits",
|
|
33285
33469
|
capabilities: { history: true, forks: false, children: true, files: true },
|
|
33286
|
-
roots: () => [
|
|
33470
|
+
roots: () => [join18(sourcePath("copilot") || process.env.SESSIONGRAPH_COPILOT_HOME || join18(homedir11(), ".copilot"), "session-state")],
|
|
33287
33471
|
match: (path) => /(?:^|\/)events\.jsonl$/.test(path),
|
|
33288
33472
|
parse(path, files) {
|
|
33289
33473
|
const { rows: rows2, partial } = jsonLines(files.get(path));
|
|
@@ -33329,8 +33513,8 @@ var copilotAdapter = localFileAdapter({
|
|
|
33329
33513
|
});
|
|
33330
33514
|
|
|
33331
33515
|
// server/adapters/copilot-chat.ts
|
|
33332
|
-
import { homedir as
|
|
33333
|
-
import { basename as
|
|
33516
|
+
import { homedir as homedir12 } from "node:os";
|
|
33517
|
+
import { basename as basename5, dirname as dirname4, join as join19, posix as posix2, win32 as win323 } from "node:path";
|
|
33334
33518
|
import { fileURLToPath as fileURLToPath3 } from "node:url";
|
|
33335
33519
|
|
|
33336
33520
|
// server/adapters/vscode-chat-log.ts
|
|
@@ -33377,7 +33561,7 @@ function vscodeChatLog(content) {
|
|
|
33377
33561
|
}
|
|
33378
33562
|
|
|
33379
33563
|
// server/adapters/copilot-chat.ts
|
|
33380
|
-
function copilotChatRoots(platform = process.platform, home =
|
|
33564
|
+
function copilotChatRoots(platform = process.platform, home = homedir12(), env2 = process.env) {
|
|
33381
33565
|
const path = platform === "win32" ? win323 : posix2;
|
|
33382
33566
|
const base = platform === "darwin" ? path.join(home, "Library", "Application Support") : platform === "win32" ? env2.APPDATA || path.join(home, "AppData", "Roaming") : env2.XDG_CONFIG_HOME || path.join(home, ".config");
|
|
33383
33567
|
const override = sourcePath("copilot-chat") || env2.SESSIONGRAPH_COPILOT_CHAT_USER_DATA_DIR;
|
|
@@ -33482,16 +33666,16 @@ var filesAdapter = localFileAdapter({
|
|
|
33482
33666
|
capabilities: { history: true, forks: false, children: false, files: true },
|
|
33483
33667
|
roots,
|
|
33484
33668
|
match,
|
|
33485
|
-
authoritativeIdentity: (path) => path.endsWith(".jsonl") ?
|
|
33486
|
-
extras: (path) => [...
|
|
33669
|
+
authoritativeIdentity: (path) => path.endsWith(".jsonl") ? basename5(path, ".jsonl") : void 0,
|
|
33670
|
+
extras: (path) => [...basename5(dirname4(path)) === "chatSessions" ? [join19(dirname4(dirname4(path)), "workspace.json")] : [], ...path.endsWith(".json") ? [`${path}l`] : []],
|
|
33487
33671
|
parse(path, files) {
|
|
33488
33672
|
const log = path.endsWith(".jsonl") ? path : `${path}l`;
|
|
33489
33673
|
const data = files.has(log) ? vscodeChatLog(files.get(log)) : object3(JSON.parse(files.get(path)));
|
|
33490
33674
|
if (!text(data.sessionId) || !Array.isArray(data.requests) || data.version !== void 0 && ![1, 2, 3].includes(data.version)) throw new Error("Unsupported VS Code chat history.");
|
|
33491
|
-
if (data.sessionId !==
|
|
33675
|
+
if (data.sessionId !== basename5(path).replace(/\.jsonl?$/, "")) throw new Error("VS Code chat identity mismatch.");
|
|
33492
33676
|
if (!data.requests.length) return;
|
|
33493
33677
|
if (data.requests.length > 25e3) throw new Error("Chat exceeds the 50,000-message limit.");
|
|
33494
|
-
const workspacePath =
|
|
33678
|
+
const workspacePath = join19(dirname4(dirname4(path)), "workspace.json");
|
|
33495
33679
|
const workspace = files.has(workspacePath) ? object3(JSON.parse(files.get(workspacePath))) : {};
|
|
33496
33680
|
const messages = chatMessages(data.requests);
|
|
33497
33681
|
const model = [...data.requests].reverse().find((r) => text(r.modelId));
|
|
@@ -33508,8 +33692,8 @@ var copilotChatAdapter = { ...filesAdapter, async detect() {
|
|
|
33508
33692
|
} };
|
|
33509
33693
|
|
|
33510
33694
|
// server/adapters/extensions.ts
|
|
33511
|
-
import { homedir as
|
|
33512
|
-
import { basename as
|
|
33695
|
+
import { homedir as homedir13 } from "node:os";
|
|
33696
|
+
import { basename as basename6, dirname as dirname5, join as join20 } from "node:path";
|
|
33513
33697
|
function taskUsage(value, source) {
|
|
33514
33698
|
if (!Array.isArray(value)) return;
|
|
33515
33699
|
const records = /* @__PURE__ */ new Map();
|
|
@@ -33539,13 +33723,13 @@ function taskUsage(value, source) {
|
|
|
33539
33723
|
return sessionUsage(sumUsage([...records.values()]));
|
|
33540
33724
|
}
|
|
33541
33725
|
function editorTaskRoots(extension) {
|
|
33542
|
-
const home =
|
|
33543
|
-
const base = process.platform === "darwin" ?
|
|
33544
|
-
return ["Code", "Code - Insiders", "VSCodium", "Cursor", "Windsurf"].map((app) =>
|
|
33726
|
+
const home = homedir13();
|
|
33727
|
+
const base = process.platform === "darwin" ? join20(home, "Library", "Application Support") : process.platform === "win32" ? process.env.APPDATA || join20(home, "AppData", "Roaming") : process.env.XDG_CONFIG_HOME || join20(home, ".config");
|
|
33728
|
+
return ["Code", "Code - Insiders", "VSCodium", "Cursor", "Windsurf"].map((app) => join20(base, app, "User", "globalStorage", extension, "tasks")).concat([".vscode-server", ".vscode-server-insiders"].map((app) => join20(home, app, "data", "User", "globalStorage", extension, "tasks")));
|
|
33545
33729
|
}
|
|
33546
33730
|
function taskAdapter(id2, name, extension, env2) {
|
|
33547
33731
|
const home = () => sourcePath(id2) || process.env[env2];
|
|
33548
|
-
const roots2 = () => home() ? [
|
|
33732
|
+
const roots2 = () => home() ? [join20(home(), "tasks"), ...id2 === "cline" ? [join20(home(), "data", "sessions")] : []] : [...editorTaskRoots(extension), ...id2 === "cline" ? [process.env.CLINE_SESSION_DATA_DIR || join20(process.env.CLINE_DATA_DIR || join20(process.env.CLINE_DIR || join20(homedir13(), ".cline"), "data"), "sessions")] : []];
|
|
33549
33733
|
return localFileAdapter({
|
|
33550
33734
|
id: id2,
|
|
33551
33735
|
name,
|
|
@@ -33553,14 +33737,14 @@ function taskAdapter(id2, name, extension, env2) {
|
|
|
33553
33737
|
capabilities: { history: true, forks: id2 === "cline", children: true, files: true },
|
|
33554
33738
|
roots: roots2,
|
|
33555
33739
|
match: (path) => /^[^/]+\/api_conversation_history\.json$/.test(path) || id2 === "cline" && /^[^/]+\/[^/]+\.messages\.json$/.test(path),
|
|
33556
|
-
extras: (path) => ["history_item.json", "task_metadata.json", "session.json", "ui_messages.json"].map((file) =>
|
|
33740
|
+
extras: (path) => ["history_item.json", "task_metadata.json", "session.json", "ui_messages.json"].map((file) => join20(dirname5(path), file)),
|
|
33557
33741
|
parse(path, files) {
|
|
33558
33742
|
const sdk = path.endsWith(".messages.json"), value = json3(files.get(path));
|
|
33559
33743
|
const records = sdk ? object3(value).messages : value;
|
|
33560
33744
|
if (!Array.isArray(records) || sdk && !text(value.sessionId)) throw new Error("Unsupported task history.");
|
|
33561
|
-
const read3 = (name2) => object3(files.has(
|
|
33745
|
+
const read3 = (name2) => object3(files.has(join20(dirname5(path), name2)) ? json3(files.get(join20(dirname5(path), name2))) : void 0);
|
|
33562
33746
|
const history = read3("history_item.json"), info = read3("session.json"), task = read3("task_metadata.json");
|
|
33563
|
-
const nativeID = sdk ? value.sessionId :
|
|
33747
|
+
const nativeID = sdk ? value.sessionId : basename6(dirname5(path));
|
|
33564
33748
|
if (history.id && history.id !== nativeID || info.session_id && info.session_id !== nativeID) throw new Error("Task metadata identity mismatch.");
|
|
33565
33749
|
const messages = records.map((raw, index) => {
|
|
33566
33750
|
const row = object3(raw), message2 = conversationMessage(row, `record:${index}`);
|
|
@@ -33600,7 +33784,7 @@ function taskAdapter(id2, name, extension, env2) {
|
|
|
33600
33784
|
title: text(history.task || info.metadata?.title),
|
|
33601
33785
|
model: text(lastModel?.modelInfo?.id || lastModel?.model || info.model) || "Unknown model",
|
|
33602
33786
|
provider: text(lastModel?.modelInfo?.provider || info.provider),
|
|
33603
|
-
usage: !sdk && files.has(
|
|
33787
|
+
usage: !sdk && files.has(join20(dirname5(path), "ui_messages.json")) ? taskUsage(json3(files.get(join20(dirname5(path), "ui_messages.json"))), id2) : void 0
|
|
33604
33788
|
},
|
|
33605
33789
|
note: sdk ? void 0 : "Earlier and editor-only messages may be missing."
|
|
33606
33790
|
};
|
|
@@ -33615,14 +33799,14 @@ var continueAdapter = localFileAdapter({
|
|
|
33615
33799
|
name: "Continue",
|
|
33616
33800
|
description: "Local IDE and CLI session JSON \xB7 recorded conversation and tool history",
|
|
33617
33801
|
capabilities: { history: true, forks: false, children: false, files: false },
|
|
33618
|
-
roots: () => [
|
|
33802
|
+
roots: () => [join20(sourcePath("continue") || process.env.SESSIONGRAPH_CONTINUE_HOME || process.env.CONTINUE_GLOBAL_DIR || join20(homedir13(), ".continue"), "sessions")],
|
|
33619
33803
|
match: (path) => /^[^/]+\.json$/.test(path) && path !== "sessions.json",
|
|
33620
|
-
extras: (path) => [
|
|
33804
|
+
extras: (path) => [join20(dirname5(path), "sessions.json")],
|
|
33621
33805
|
revisionExtras: false,
|
|
33622
33806
|
parse(path, files) {
|
|
33623
33807
|
const value = object3(json3(files.get(path)));
|
|
33624
33808
|
if (!text(value.sessionId) || !Array.isArray(value.history)) throw new Error("Unsupported Continue session.");
|
|
33625
|
-
const indexPath =
|
|
33809
|
+
const indexPath = join20(dirname5(path), "sessions.json"), index = files.has(indexPath) ? json3(files.get(indexPath)) : [];
|
|
33626
33810
|
const meta = Array.isArray(index) ? object3(index.find((r) => r.sessionId === value.sessionId)) : {};
|
|
33627
33811
|
const messages = value.history.map((item, i) => {
|
|
33628
33812
|
const row = object3(item), raw = object3(row.message), message2 = conversationMessage(raw, `record:${i}`);
|
|
@@ -33655,30 +33839,16 @@ var continueAdapter = localFileAdapter({
|
|
|
33655
33839
|
});
|
|
33656
33840
|
|
|
33657
33841
|
// server/adapters/harness-files.ts
|
|
33658
|
-
import { basename as
|
|
33659
|
-
|
|
33660
|
-
// server/adapters/harness-paths.ts
|
|
33661
|
-
import { homedir as homedir13 } from "node:os";
|
|
33662
|
-
import { join as join19 } from "node:path";
|
|
33663
|
-
var homePath = (...parts) => join19(homedir13(), ...parts);
|
|
33664
|
-
var dataPath = (...parts) => join19(process.env.XDG_DATA_HOME || homePath(".local/share"), ...parts);
|
|
33665
|
-
var configPath = (...parts) => join19(process.env.XDG_CONFIG_HOME || homePath(".config"), ...parts);
|
|
33666
|
-
var appPath = (...parts) => join19(process.platform === "darwin" ? homePath("Library/Application Support") : process.platform === "win32" ? process.env.APPDATA || homePath("AppData/Roaming") : process.env.XDG_CONFIG_HOME || homePath(".config"), ...parts);
|
|
33667
|
-
var tokscalePath = (...parts) => join19(process.env.TOKSCALE_CONFIG_DIR || (process.platform === "win32" ? appPath("tokscale") : configPath("tokscale")), ...parts);
|
|
33668
|
-
var envHome = (env2, fallback, ...parts) => join19(process.env[env2]?.trim() || homePath(fallback), ...parts);
|
|
33669
|
-
var harnessRoots = (id2, defaults) => () => {
|
|
33670
|
-
const override = sourcePath(id2) || process.env[`SESSIONGRAPH_${id2.replace(/-/g, "_").toUpperCase()}_HISTORY_DIR`]?.trim();
|
|
33671
|
-
return override ? [override] : defaults();
|
|
33672
|
-
};
|
|
33842
|
+
import { basename as basename8, dirname as dirname7, join as join22 } from "node:path";
|
|
33673
33843
|
|
|
33674
33844
|
// server/adapters/harness-extra-formats.ts
|
|
33675
|
-
import { basename as
|
|
33845
|
+
import { basename as basename7, dirname as dirname6, join as join21 } from "node:path";
|
|
33676
33846
|
function kiroHistory(path, files) {
|
|
33677
33847
|
const header = object3(json3(files.get(path)));
|
|
33678
|
-
const ide2 =
|
|
33679
|
-
const nativeID = text(header.session_id || header.sessionId || header.id) || (ide2 ?
|
|
33848
|
+
const ide2 = basename7(path) === "session.json";
|
|
33849
|
+
const nativeID = text(header.session_id || header.sessionId || header.id) || (ide2 ? basename7(dirname6(path)) : "");
|
|
33680
33850
|
if (!nativeID) throw new Error("Unsupported Kiro session header.");
|
|
33681
|
-
const side = ide2 ?
|
|
33851
|
+
const side = ide2 ? join21(dirname6(path), "messages.jsonl") : path.replace(/\.json$/, ".jsonl");
|
|
33682
33852
|
if (!files.has(side)) throw new Error("Kiro conversation sidecar is unavailable.");
|
|
33683
33853
|
const { rows: rows2 } = jsonLines(files.get(side));
|
|
33684
33854
|
const messages = rows2.flatMap((r, i) => {
|
|
@@ -33704,7 +33874,7 @@ function kiroHistory(path, files) {
|
|
|
33704
33874
|
};
|
|
33705
33875
|
}
|
|
33706
33876
|
function muxHistory(path, files) {
|
|
33707
|
-
const archive = files.get(
|
|
33877
|
+
const archive = files.get(join21(dirname6(path), "chat-archive.jsonl"));
|
|
33708
33878
|
const records = [...archive ? jsonLines(archive).rows : [], ...jsonLines(files.get(path)).rows];
|
|
33709
33879
|
const unique = /* @__PURE__ */ new Map();
|
|
33710
33880
|
for (const r of records) {
|
|
@@ -33722,7 +33892,7 @@ function muxHistory(path, files) {
|
|
|
33722
33892
|
return m ? [m] : [];
|
|
33723
33893
|
});
|
|
33724
33894
|
if (!messages.length) throw new Error("No readable Mux conversation.");
|
|
33725
|
-
const usagePath =
|
|
33895
|
+
const usagePath = join21(dirname6(path), "session-usage.json");
|
|
33726
33896
|
const usage = files.has(usagePath) ? object3(json3(files.get(usagePath))) : {};
|
|
33727
33897
|
const models = Object.values(object3(usage.byModel)).slice(0, 5e4).map((value) => {
|
|
33728
33898
|
const row = object3(value), buckets = [row.input, row.cached, row.cacheCreate, row.output, row.reasoning].map(object3);
|
|
@@ -33738,7 +33908,7 @@ function muxHistory(path, files) {
|
|
|
33738
33908
|
cost: buckets.every((bucket) => recordedCost(bucket.cost_usd) !== null) ? buckets.reduce((sum, bucket) => sum + bucket.cost_usd, 0) : null
|
|
33739
33909
|
});
|
|
33740
33910
|
}).filter((value) => value !== void 0);
|
|
33741
|
-
return { nativeID:
|
|
33911
|
+
return { nativeID: basename7(dirname6(path)), messages, partial: true, session: { usage: sessionUsage(sumUsage(models), models.some((value) => value.total === null)) } };
|
|
33742
33912
|
}
|
|
33743
33913
|
function devinDesktopHistory(path, files) {
|
|
33744
33914
|
const { rows: rows2 } = jsonLines(files.get(path));
|
|
@@ -33756,16 +33926,16 @@ var piSources = [
|
|
|
33756
33926
|
{ id: "prime-agent", name: "Prime Agent", roots: () => [process.env.PRIME_AGENT_SESSION_DIR || process.env.PRIME_AGENT_CODING_AGENT_SESSION_DIR || envHome("PRIME_AGENT_CODING_AGENT_DIR", ".prime/agent", "sessions"), envHome("PRIME_AGENT_CODING_AGENT_DIR", ".prime/agent", "session-artifacts")] },
|
|
33757
33927
|
{ id: "omp", name: "Oh My Pi", roots: () => [envHome("PI_CODING_AGENT_DIR_OMP", ".omp/agent", "sessions")] },
|
|
33758
33928
|
{ id: "senpi", name: "Senpi / OmO Native", roots: () => [envHome("SENPI_CODING_AGENT_DIR", ".senpi/agent", "sessions"), homePath(".omo/agent/sessions")] },
|
|
33759
|
-
{ id: "kimchi", name: "Kimchi", roots: () => [
|
|
33760
|
-
{ id: "gajae", name: "Gajae-Code", roots: () => [
|
|
33929
|
+
{ id: "kimchi", name: "Kimchi", roots: () => [join22(process.env.KIMCHI_CODING_AGENT_DIR || configPath("kimchi/harness"), "sessions")] },
|
|
33930
|
+
{ id: "gajae", name: "Gajae-Code", roots: () => [join22(process.env.GJC_CODING_AGENT_DIR || (process.env.GJC_CONFIG_DIR || process.env.PI_CONFIG_DIR ? join22(process.env.GJC_CONFIG_DIR || process.env.PI_CONFIG_DIR, "agent") : homePath(".gjc/agent")), "sessions"), dataPath("gjc/sessions")] }
|
|
33761
33931
|
].map((s) => ({ ...s, parse: piParse }));
|
|
33762
33932
|
var openclawRoots = () => [envHome("OPENCLAW_STATE_DIR", ".openclaw", "agents"), ...[".clawdbot", ".moltbot", ".moldbot"].map((p) => homePath(p, "agents"))];
|
|
33763
33933
|
var promaRoots = () => [".proma", ".proma-dev"].flatMap((p) => ["agent-sessions", "sdk-config/sessions", "sdk-config/projects"].map((s) => homePath(p, s)));
|
|
33764
33934
|
function kimiHistory(path, files) {
|
|
33765
33935
|
const { rows: rows2 } = jsonLines(files.get(path));
|
|
33766
|
-
const folder = dirname7(path), id2 =
|
|
33767
|
-
const nativeID = agent ? `${
|
|
33768
|
-
const wire =
|
|
33936
|
+
const folder = dirname7(path), id2 = basename8(folder), agent = basename8(dirname7(folder)) === "agents";
|
|
33937
|
+
const nativeID = agent ? `${basename8(dirname7(dirname7(folder)))}/agent/${id2}` : id2;
|
|
33938
|
+
const wire = join22(folder, "wire.jsonl"), wireRows = files.has(wire) ? jsonLines(files.get(wire)).rows : [];
|
|
33769
33939
|
const messages = rows2.flatMap((r, i) => {
|
|
33770
33940
|
const m = message(r, nativeText(r.id) || `context:${i}`);
|
|
33771
33941
|
return m ? [m] : [];
|
|
@@ -33784,7 +33954,7 @@ function museHistory(path, files) {
|
|
|
33784
33954
|
const meta = rows2.find((r) => r.payload_type === "runtime.session.metadata");
|
|
33785
33955
|
const ids = new Set(rows2.map((r) => text(r.stream?.id)).filter(Boolean));
|
|
33786
33956
|
if (!meta || ids.size > 1) throw new Error("Unsupported Muse stream.");
|
|
33787
|
-
const nativeID = [...ids][0] ||
|
|
33957
|
+
const nativeID = [...ids][0] || basename8(dirname7(path));
|
|
33788
33958
|
const messages = rows2.flatMap((r, i) => {
|
|
33789
33959
|
const event = object3(r.payload?.event), body2 = object3(event.message);
|
|
33790
33960
|
const at2 = typeof r.recorded_at === "number" && r.recorded_at >= 1e15 ? r.recorded_at / 1e3 : typeof r.recorded_at === "number" && r.recorded_at < 1e12 ? seconds(r.recorded_at) : time(r.recorded_at);
|
|
@@ -33802,7 +33972,7 @@ function junieHistory(path, files) {
|
|
|
33802
33972
|
return [recordEvent(r, text(r.id) || `event:${i}`, kind, r.timestampMs, e10.text ?? e10.prompt ?? e10.message)];
|
|
33803
33973
|
});
|
|
33804
33974
|
if (!messages.length) throw new Error("No supported Junie events.");
|
|
33805
|
-
return { nativeID:
|
|
33975
|
+
return { nativeID: basename8(dirname7(path)), messages, partial: true, note: "Recorded events only." };
|
|
33806
33976
|
}
|
|
33807
33977
|
function augmentHistory(path, files) {
|
|
33808
33978
|
const r = object3(json3(files.get(path)));
|
|
@@ -33814,7 +33984,7 @@ function augmentHistory(path, files) {
|
|
|
33814
33984
|
return { nativeID: r.sessionId, messages, partial: true, session: { title: text(r.title), created: time(r.created), model: text(r.agentState?.modelId) || "Unknown model" }, note: "Recorded exchanges only." };
|
|
33815
33985
|
}
|
|
33816
33986
|
function fxHistory(path, files) {
|
|
33817
|
-
const usage = object3(json3(files.get(path))), meta = sidecar2(files,
|
|
33987
|
+
const usage = object3(json3(files.get(path))), meta = sidecar2(files, join22(dirname7(path), "session.json"));
|
|
33818
33988
|
const id2 = text(usage.session_id) || text(meta.id);
|
|
33819
33989
|
if (!id2 || !usage.snapshot || meta.id && meta.id !== id2) throw new Error("Unsupported Fx session metadata.");
|
|
33820
33990
|
const snapshot2 = object3(usage.snapshot);
|
|
@@ -33843,15 +34013,15 @@ function fxHistory(path, files) {
|
|
|
33843
34013
|
}
|
|
33844
34014
|
var definitions = [
|
|
33845
34015
|
...piSources,
|
|
33846
|
-
{ id: "kiro", name: "Kiro", roots: () => [homePath(".kiro/sessions"), appPath("Kiro/User/globalStorage/kiro.kiroagent")], match: (p) => p.endsWith("/session.json") || /^cli\/[^/]+\.json$/.test(p), extras: (p) => [
|
|
33847
|
-
{ id: "mux", name: "Mux", roots: () => [envHome("MUX_ROOT", ".mux", "sessions")], match: (p) => p.endsWith("/chat.jsonl"), extras: (p) => [
|
|
34016
|
+
{ id: "kiro", name: "Kiro", roots: () => [homePath(".kiro/sessions"), appPath("Kiro/User/globalStorage/kiro.kiroagent")], match: (p) => p.endsWith("/session.json") || /^cli\/[^/]+\.json$/.test(p), extras: (p) => [basename8(p) === "session.json" ? join22(dirname7(p), "messages.jsonl") : p.replace(/\.json$/, ".jsonl")], parse: kiroHistory },
|
|
34017
|
+
{ id: "mux", name: "Mux", roots: () => [envHome("MUX_ROOT", ".mux", "sessions")], match: (p) => p.endsWith("/chat.jsonl"), extras: (p) => [join22(dirname7(p), "chat-archive.jsonl"), join22(dirname7(p), "session-usage.json")], parse: muxHistory },
|
|
33848
34018
|
{ id: "devin-desktop", name: "Devin Desktop", roots: () => [appPath("Devin/User/acp-events")], match: (p) => /\.(ndjson|jsonl)$/.test(p), parse: devinDesktopHistory },
|
|
33849
34019
|
{ id: "openclaw", name: "OpenClaw", roots: openclawRoots, match: (p) => /(?:^|\/)sessions\/.*\.jsonl(?:\.[\w.-]+)?$/.test(p) || /session-sqlite-import-archive\/.*\.jsonl\./.test(p), parse: piParse },
|
|
33850
34020
|
{ id: "amp", name: "Amp", roots: () => [dataPath("amp/threads"), tokscalePath("amp-cache/threads")], match: (p) => p.endsWith(".json"), parse: ampHistory },
|
|
33851
34021
|
{ id: "droid", name: "Factory Droid", roots: () => [envHome("FACTORY_HOME", ".factory", "sessions")] },
|
|
33852
34022
|
{ id: "codebuff", name: "Codebuff", roots: () => process.env.CODEBUFF_DATA_DIR ? [process.env.CODEBUFF_DATA_DIR] : ["manicode", "manicode-dev", "manicode-staging"].map((p) => configPath(p)), match: (p) => p.endsWith("/chat-messages.json"), parse: (p, f) => codebuffHistory(p, f, false) },
|
|
33853
34023
|
{ id: "freebuff", name: "Freebuff", roots: () => process.env.FREEBUFF_DATA_DIR ? [process.env.FREEBUFF_DATA_DIR] : process.env.CODEBUFF_DATA_DIR ? [process.env.CODEBUFF_DATA_DIR] : ["manicode", "manicode-dev", "manicode-staging"].map((p) => configPath(p)), match: (p) => p.endsWith("/chat-messages.json"), parse: (p, f) => codebuffHistory(p, f, true) },
|
|
33854
|
-
{ id: "kimi", name: "Kimi CLI / Code", roots: () => [envHome("KIMI_HOME", ".kimi", "sessions"), envHome("KIMI_CODE_HOME", ".kimi-code", "sessions")], match: (p) => p.endsWith("/context.jsonl"), extras: (p) => [
|
|
34024
|
+
{ id: "kimi", name: "Kimi CLI / Code", roots: () => [envHome("KIMI_HOME", ".kimi", "sessions"), envHome("KIMI_CODE_HOME", ".kimi-code", "sessions")], match: (p) => p.endsWith("/context.jsonl"), extras: (p) => [join22(dirname7(p), "wire.jsonl")], parse: kimiHistory },
|
|
33855
34025
|
{ id: "grok", name: "Grok Build", roots: () => [envHome("GROK_HOME", ".grok", "sessions")], match: (p) => p.endsWith("/updates.jsonl"), parse: (p, f) => acpHistory(p, f.get(p)) },
|
|
33856
34026
|
{ id: "jcode", name: "Jcode", roots: () => [envHome("JCODE_HOME", ".jcode", "sessions")], match: (p) => /(?:^|\/)session_[^/]+\.json$/.test(p), extras: (p) => [p.replace(/\.json$/, ".journal.jsonl")], parse: jcodeHistory },
|
|
33857
34027
|
{ id: "cherry-studio", name: "Cherry Studio", roots: () => [appPath("CherryStudio/Data/Agents/.claude/projects"), appPath("CherryStudio/.claude/projects")] },
|
|
@@ -33863,15 +34033,15 @@ var definitions = [
|
|
|
33863
34033
|
{ id: "deepseek-harness", name: "DeepSeek Harness", roots: () => [envHome("DSH_HOME", ".dsh", "sessions")], match: (p) => /(?:^|\/)session(?:\.v\d+)?\.jsonl(?:\.zstd)?$/.test(p), parse: (p, f) => dshHistory(f.get(p)) },
|
|
33864
34034
|
{ id: "aside", name: "Aside", roots: () => [homePath(".aside/u")], match: (p) => /^[^/]+\/sessions\/[^/]+\/messages\.jsonl$/.test(p), parse(p, f) {
|
|
33865
34035
|
const h3 = envelopeHistory(p, f.get(p));
|
|
33866
|
-
h3.nativeID = `${
|
|
34036
|
+
h3.nativeID = `${basename8(dirname7(dirname7(dirname7(p))))}/${basename8(dirname7(p))}`;
|
|
33867
34037
|
return h3;
|
|
33868
34038
|
} },
|
|
33869
|
-
{ id: "vibe", name: "Mistral Vibe", roots: () => [envHome("VIBE_HOME", ".vibe", "logs/session")], match: (p) => p.endsWith("/meta.json") || /^[^/]+\.json$/.test(p), extras: (p) =>
|
|
34039
|
+
{ id: "vibe", name: "Mistral Vibe", roots: () => [envHome("VIBE_HOME", ".vibe", "logs/session")], match: (p) => p.endsWith("/meta.json") || /^[^/]+\.json$/.test(p), extras: (p) => basename8(p) === "meta.json" ? [join22(dirname7(p), "messages.jsonl")] : [], parse: vibeHistory },
|
|
33870
34040
|
{ id: "muse", name: "Muse Code", roots: () => [dataPath("muse/sessions")], match: (p) => p.endsWith("/session.jsonl"), parse: museHistory },
|
|
33871
34041
|
{ id: "junie", name: "Junie", roots: () => [homePath(".junie/sessions")], match: (p) => p.endsWith("/events.jsonl"), parse: junieHistory, description: "Local agent event history \xB7 partial conversation coverage" },
|
|
33872
34042
|
{ id: "augment", name: "Augment Code", roots: () => [homePath(".augment/sessions")], match: (p) => p.endsWith(".json"), parse: augmentHistory, description: "Local exchange records \xB7 partial conversation coverage" },
|
|
33873
|
-
{ id: "fx", name: "Fx", roots: () => [homePath(".fx/sessions")], match: (p) => p.endsWith("/usage-v2.json"), extras: (p) => [
|
|
33874
|
-
{ id: "minimax-code", name: "MiniMax Code", roots: () => [
|
|
34043
|
+
{ id: "fx", name: "Fx", roots: () => [homePath(".fx/sessions")], match: (p) => p.endsWith("/usage-v2.json"), extras: (p) => [join22(dirname7(p), "session.json")], parse: fxHistory, history: false, description: "Session metadata only" },
|
|
34044
|
+
{ id: "minimax-code", name: "MiniMax Code", roots: () => [join22(process.env.TOKSCALE_HEADLESS_DIR || tokscalePath("headless"), "mcode")], parse(p, f) {
|
|
33875
34045
|
const value = f.get(p), { rows: rows2 } = jsonLines(value), ids = new Set(rows2.map((r) => text(r.sessionId)).filter(Boolean));
|
|
33876
34046
|
if (ids.size !== 1) throw new Error("Headless capture needs one explicit session identity.");
|
|
33877
34047
|
const messages = rows2.flatMap((r, i) => {
|
|
@@ -33896,8 +34066,8 @@ var fileHarnessAdapters = definitions.map((source) => localFileAdapter({
|
|
|
33896
34066
|
}));
|
|
33897
34067
|
|
|
33898
34068
|
// server/adapters/harness-databases.ts
|
|
33899
|
-
import { lstat as
|
|
33900
|
-
import { isAbsolute as isAbsolute5, join as
|
|
34069
|
+
import { lstat as lstat7, readFile as readFile4 } from "node:fs/promises";
|
|
34070
|
+
import { isAbsolute as isAbsolute5, join as join23 } from "node:path";
|
|
33901
34071
|
function hermesContent(value) {
|
|
33902
34072
|
if (typeof value !== "string" || !value.startsWith("\0json:")) return value;
|
|
33903
34073
|
try {
|
|
@@ -33977,7 +34147,7 @@ var hermes = {
|
|
|
33977
34147
|
var goose = {
|
|
33978
34148
|
id: "goose",
|
|
33979
34149
|
name: "Goose",
|
|
33980
|
-
paths: dbPaths("goose", () => process.env.GOOSE_PATH_ROOT && isAbsolute5(process.env.GOOSE_PATH_ROOT) ? [
|
|
34150
|
+
paths: dbPaths("goose", () => process.env.GOOSE_PATH_ROOT && isAbsolute5(process.env.GOOSE_PATH_ROOT) ? [join23(process.env.GOOSE_PATH_ROOT, "data/sessions/sessions.db")] : [dataPath("goose/sessions/sessions.db"), dataPath("Block/goose/sessions/sessions.db"), appPath("goose/sessions/sessions.db"), appPath("Block/goose/sessions/sessions.db"), appPath("Block/goose/data/sessions/sessions.db")], (p) => p.endsWith("sessions.db")),
|
|
33981
34151
|
table: "sessions",
|
|
33982
34152
|
key: "id",
|
|
33983
34153
|
fields: [
|
|
@@ -34071,7 +34241,7 @@ function forkStore(id2, name, defaultPath, desktop) {
|
|
|
34071
34241
|
var zed = {
|
|
34072
34242
|
id: "zed",
|
|
34073
34243
|
name: "Zed Agent",
|
|
34074
|
-
paths: dbPaths("zed", () => [process.platform === "darwin" ? appPath("Zed/threads/threads.db") : process.platform === "win32" ?
|
|
34244
|
+
paths: dbPaths("zed", () => [process.platform === "darwin" ? appPath("Zed/threads/threads.db") : process.platform === "win32" ? join23(process.env.LOCALAPPDATA || homePath("AppData/Local"), "Zed/threads/threads.db") : dataPath("zed/threads/threads.db")], (p) => p.endsWith("threads.db")),
|
|
34075
34245
|
table: "threads",
|
|
34076
34246
|
key: "id",
|
|
34077
34247
|
fields: ["id", "summary", "created_at", "updated_at", "data_type", "data", "folder_paths"],
|
|
@@ -34120,15 +34290,15 @@ var crush = {
|
|
|
34120
34290
|
paths: async () => {
|
|
34121
34291
|
const override = sourcePath("crush") || process.env.SESSIONGRAPH_CRUSH_HISTORY_DIR;
|
|
34122
34292
|
if (override) return (await historyFiles([override], (p) => p.endsWith("crush.db"))).files;
|
|
34123
|
-
const registry =
|
|
34293
|
+
const registry = join23(process.env.CRUSH_GLOBAL_DATA || dataPath("crush"), "projects.json");
|
|
34124
34294
|
try {
|
|
34125
|
-
const stat6 = await
|
|
34295
|
+
const stat6 = await lstat7(registry);
|
|
34126
34296
|
if (!stat6.isFile() || stat6.size > 2e6) throw new Error("Unsupported Crush registry.");
|
|
34127
34297
|
const raw = JSON.parse(await readFile4(registry, "utf8"));
|
|
34128
34298
|
const paths2 = [];
|
|
34129
34299
|
for (const p of Array.isArray(raw.projects) ? raw.projects.slice(0, 2e4) : []) {
|
|
34130
34300
|
if (!isAbsolute5(text(p.path)) || !text(p.data_dir)) continue;
|
|
34131
|
-
const path =
|
|
34301
|
+
const path = join23(isAbsolute5(p.data_dir) ? p.data_dir : join23(p.path, p.data_dir), "crush.db");
|
|
34132
34302
|
paths2.push(path);
|
|
34133
34303
|
crushDirectories.set(path, p.path);
|
|
34134
34304
|
}
|
|
@@ -34246,7 +34416,7 @@ var databaseHarnessAdapters = [
|
|
|
34246
34416
|
].map(sqliteHistoryAdapter);
|
|
34247
34417
|
|
|
34248
34418
|
// server/adapters/harness-metadata.ts
|
|
34249
|
-
import { basename as
|
|
34419
|
+
import { basename as basename9 } from "node:path";
|
|
34250
34420
|
import { fileURLToPath as fileURLToPath4 } from "node:url";
|
|
34251
34421
|
function protoFields(value) {
|
|
34252
34422
|
if (value.length > 2e6) throw new Error("Trajectory metadata exceeds 2 MB.");
|
|
@@ -34302,7 +34472,7 @@ var antigravityDatabaseAdapters = ["antigravity-cli", "antigravity-extension"].m
|
|
|
34302
34472
|
}
|
|
34303
34473
|
}
|
|
34304
34474
|
if (!created) throw new Error("Trajectory creation time is unavailable.");
|
|
34305
|
-
return { nativeID:
|
|
34475
|
+
return { nativeID: basename9(path, ".db"), messages: [], partial: true, session: { created, directory: directory3 }, note: "Session metadata only." };
|
|
34306
34476
|
}
|
|
34307
34477
|
}));
|
|
34308
34478
|
var antigravityCacheAdapter = localFileAdapter({
|
|
@@ -34363,7 +34533,7 @@ import { randomUUID } from "node:crypto";
|
|
|
34363
34533
|
var abbreviatedSHA = (sha) => sha.length !== 40 && sha.length !== 64;
|
|
34364
34534
|
|
|
34365
34535
|
// server/library-query.ts
|
|
34366
|
-
import { createHash as
|
|
34536
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
34367
34537
|
|
|
34368
34538
|
// packages/core/src/layout.ts
|
|
34369
34539
|
var directoryPath = (directory3) => (/^(?:[a-z]:[\\/]|\\\\)/i.test(directory3) ? directory3.replace(/\\/g, "/") : directory3).replace(/\/+$/, "") || (directory3.startsWith("/") ? "/" : "");
|
|
@@ -34400,7 +34570,7 @@ var LibraryError = class extends Error {
|
|
|
34400
34570
|
function invalid(message2) {
|
|
34401
34571
|
throw new LibraryError("INVALID_ARGUMENT", message2, 2);
|
|
34402
34572
|
}
|
|
34403
|
-
var fingerprint2 = (value) =>
|
|
34573
|
+
var fingerprint2 = (value) => createHash3("sha256").update(JSON.stringify(value)).digest("hex");
|
|
34404
34574
|
function pageLimit(value = 50) {
|
|
34405
34575
|
if (!Number.isSafeInteger(value) || value < 1 || value > 200) invalid("Limit must be an integer from 1 to 200.");
|
|
34406
34576
|
return value;
|
|
@@ -35358,7 +35528,7 @@ var Importer = class {
|
|
|
35358
35528
|
import { execFile, spawn as spawn2 } from "node:child_process";
|
|
35359
35529
|
import { promisify } from "node:util";
|
|
35360
35530
|
import { stat as stat4 } from "node:fs/promises";
|
|
35361
|
-
import { basename as
|
|
35531
|
+
import { basename as basename10, dirname as dirname9, isAbsolute as isAbsolute7 } from "node:path";
|
|
35362
35532
|
|
|
35363
35533
|
// src/launch-links.ts
|
|
35364
35534
|
var HARNESSES = [
|
|
@@ -35394,13 +35564,13 @@ function resumeArgs(value) {
|
|
|
35394
35564
|
import { access, stat as stat3 } from "node:fs/promises";
|
|
35395
35565
|
import { constants as constants6 } from "node:fs";
|
|
35396
35566
|
import { homedir as homedir14 } from "node:os";
|
|
35397
|
-
import { delimiter, isAbsolute as isAbsolute6, join as
|
|
35567
|
+
import { delimiter, isAbsolute as isAbsolute6, join as join24 } from "node:path";
|
|
35398
35568
|
async function executable(name) {
|
|
35399
35569
|
const home = homedir14();
|
|
35400
|
-
const directories = [...(process.env.PATH || "").split(delimiter),
|
|
35401
|
-
if (process.platform === "win32" && process.env.APPDATA) directories.push(
|
|
35402
|
-
if (process.platform === "win32" && process.env.SystemRoot) directories.push(
|
|
35403
|
-
const candidates = isAbsolute6(name) ? [name] : directories.filter((dir) => isAbsolute6(dir)).flatMap((dir) => (process.platform === "win32" ? [".exe", ".cmd", ".bat", ""] : [""]).map((extension) =>
|
|
35570
|
+
const directories = [...(process.env.PATH || "").split(delimiter), join24(home, ".local", "bin"), join24(home, ".opencode", "bin"), join24(home, ".bun", "bin"), join24(home, "Library", "pnpm"), "/opt/homebrew/bin", "/usr/local/bin"];
|
|
35571
|
+
if (process.platform === "win32" && process.env.APPDATA) directories.push(join24(process.env.APPDATA, "npm"));
|
|
35572
|
+
if (process.platform === "win32" && process.env.SystemRoot) directories.push(join24(process.env.SystemRoot, "System32", "WindowsPowerShell", "v1.0"));
|
|
35573
|
+
const candidates = isAbsolute6(name) ? [name] : directories.filter((dir) => isAbsolute6(dir)).flatMap((dir) => (process.platform === "win32" ? [".exe", ".cmd", ".bat", ""] : [""]).map((extension) => join24(dir, name + extension)));
|
|
35404
35574
|
for (const path of candidates) {
|
|
35405
35575
|
try {
|
|
35406
35576
|
if ((await stat3(path)).isFile()) {
|
|
@@ -35416,7 +35586,7 @@ async function harnessExecutable(target) {
|
|
|
35416
35586
|
const path = await executable(name);
|
|
35417
35587
|
if (path) return path;
|
|
35418
35588
|
if (target === "codex" && process.platform === "darwin") {
|
|
35419
|
-
return await executable("/Applications/Codex.app/Contents/Resources/codex") || await executable(
|
|
35589
|
+
return await executable("/Applications/Codex.app/Contents/Resources/codex") || await executable(join24(homedir14(), "Applications/Codex.app/Contents/Resources/codex"));
|
|
35420
35590
|
}
|
|
35421
35591
|
}
|
|
35422
35592
|
async function terminalExecutable() {
|
|
@@ -35439,9 +35609,9 @@ function launchCommand(binary, args, directory3, platform = process.platform) {
|
|
|
35439
35609
|
}
|
|
35440
35610
|
|
|
35441
35611
|
// server/handoff.ts
|
|
35442
|
-
import { createHash as
|
|
35612
|
+
import { createHash as createHash4, randomUUID as randomUUID3 } from "node:crypto";
|
|
35443
35613
|
import { mkdir, writeFile as writeFile2, rename as rename2, rm as rm4 } from "node:fs/promises";
|
|
35444
|
-
import { join as
|
|
35614
|
+
import { join as join25 } from "node:path";
|
|
35445
35615
|
function handoffDocument(snapshot2) {
|
|
35446
35616
|
const { session, messages, firstUser, totalMessages } = snapshot2;
|
|
35447
35617
|
if (!messages.length) invalid("Import the conversation before continuing.");
|
|
@@ -35506,10 +35676,10 @@ This handoff transfers saved text and file-change evidence, not files, credentia
|
|
|
35506
35676
|
}
|
|
35507
35677
|
async function saveHandoff(snapshot2, directory3) {
|
|
35508
35678
|
const { text: text2, ...coverage2 } = handoffDocument(snapshot2);
|
|
35509
|
-
const digest2 =
|
|
35510
|
-
const root3 =
|
|
35679
|
+
const digest2 = createHash4("sha256").update(text2).digest("hex");
|
|
35680
|
+
const root3 = join25(directory3, "handoffs");
|
|
35511
35681
|
await mkdir(root3, { recursive: true, mode: 448 });
|
|
35512
|
-
const path =
|
|
35682
|
+
const path = join25(root3, `${digest2}.md`), temporary = join25(root3, `.${randomUUID3()}.tmp`);
|
|
35513
35683
|
try {
|
|
35514
35684
|
await writeFile2(temporary, text2, { mode: 384, flag: "wx" });
|
|
35515
35685
|
await rename2(temporary, path);
|
|
@@ -35575,7 +35745,7 @@ function commandInvocation(command, terminal, platform = process.platform) {
|
|
|
35575
35745
|
const encoded = Buffer.from(command, "utf16le").toString("base64");
|
|
35576
35746
|
return { file: terminal, args: ["-NoProfile", "-NonInteractive", "-Command", `Start-Process powershell.exe -ArgumentList '-NoExit','-NoProfile','-EncodedCommand','${encoded}'`] };
|
|
35577
35747
|
}
|
|
35578
|
-
return { file: terminal, args: [
|
|
35748
|
+
return { file: terminal, args: [basename10(terminal) === "gnome-terminal" ? "--" : "-e", "sh", "-lc", command] };
|
|
35579
35749
|
}
|
|
35580
35750
|
async function launchTerminal(session, prepared) {
|
|
35581
35751
|
if (!prepared.terminalAvailable) invalid("Copy the command and run it in your terminal.");
|
|
@@ -35604,9 +35774,9 @@ async function launchTerminal(session, prepared) {
|
|
|
35604
35774
|
}
|
|
35605
35775
|
|
|
35606
35776
|
// server/publishing.ts
|
|
35607
|
-
import { createHash as
|
|
35777
|
+
import { createHash as createHash5, randomBytes } from "node:crypto";
|
|
35608
35778
|
import { chmod, mkdir as mkdir2, readFile as readFile5, rename as rename3, rm as rm5, writeFile as writeFile3 } from "node:fs/promises";
|
|
35609
|
-
import { dirname as dirname10, join as
|
|
35779
|
+
import { dirname as dirname10, join as join26 } from "node:path";
|
|
35610
35780
|
|
|
35611
35781
|
// packages/core/src/sources.ts
|
|
35612
35782
|
var sources = {
|
|
@@ -35795,7 +35965,7 @@ var PublishingError = class extends Error {
|
|
|
35795
35965
|
status;
|
|
35796
35966
|
};
|
|
35797
35967
|
var SITE = "https://sessiongraph.ai";
|
|
35798
|
-
var hash = (value) =>
|
|
35968
|
+
var hash = (value) => createHash5("sha256").update(value).digest("hex");
|
|
35799
35969
|
var token = () => randomBytes(32).toString("base64url");
|
|
35800
35970
|
function preparePublicGraph(store, ids, inputSettings) {
|
|
35801
35971
|
if (!Array.isArray(ids) || !ids.length || ids.length > PUBLIC_GRAPH_MAX_SESSIONS || ids.some((id2) => typeof id2 !== "string") || new Set(ids).size !== ids.length) throw new PublishingError("Choose a valid set of sessions.");
|
|
@@ -35836,7 +36006,7 @@ function preparePublicGraph(store, ids, inputSettings) {
|
|
|
35836
36006
|
}
|
|
35837
36007
|
}
|
|
35838
36008
|
var PublishingClient = class {
|
|
35839
|
-
constructor(credentialPath =
|
|
36009
|
+
constructor(credentialPath = join26(dirname10(databasePath()), "account.json"), fetcher = fetch) {
|
|
35840
36010
|
this.credentialPath = credentialPath;
|
|
35841
36011
|
this.fetcher = fetcher;
|
|
35842
36012
|
}
|
|
@@ -35897,16 +36067,16 @@ var PublishingClient = class {
|
|
|
35897
36067
|
return { url: `${SITE}/api/auth/github?device=${challenge}`, code: challenge.slice(0, 8).toUpperCase() };
|
|
35898
36068
|
}
|
|
35899
36069
|
async poll() {
|
|
35900
|
-
const
|
|
35901
|
-
if (!
|
|
36070
|
+
const pending = this.pending;
|
|
36071
|
+
if (!pending || pending.expires <= Date.now()) {
|
|
35902
36072
|
this.pending = void 0;
|
|
35903
36073
|
throw new PublishingError("Login expired. Start again.");
|
|
35904
36074
|
}
|
|
35905
|
-
if (this.busy ||
|
|
35906
|
-
|
|
36075
|
+
if (this.busy || pending.nextPoll > Date.now()) return { pending: true };
|
|
36076
|
+
pending.nextPoll = Date.now() + 3e3;
|
|
35907
36077
|
return this.exclusive(async () => {
|
|
35908
|
-
const result = await this.call("auth/device", "POST", { verifier:
|
|
35909
|
-
if (this.pending !==
|
|
36078
|
+
const result = await this.call("auth/device", "POST", { verifier: pending.verifier });
|
|
36079
|
+
if (this.pending !== pending || result.pending === true) return { pending: true };
|
|
35910
36080
|
if (typeof result.token !== "string" || !/^[\w-]{43}$/.test(result.token) || typeof result.username !== "string" || !Number.isFinite(Date.parse(result.expiresAt)) || Date.parse(result.expiresAt) <= Date.now()) throw new PublishingError("The publishing service returned an invalid login response. Please try again.", 502);
|
|
35911
36081
|
await this.save(result);
|
|
35912
36082
|
this.pending = void 0;
|
|
@@ -35959,11 +36129,11 @@ var PublishingClient = class {
|
|
|
35959
36129
|
|
|
35960
36130
|
// server/git-checkouts.ts
|
|
35961
36131
|
import { execFile as execFile2 } from "node:child_process";
|
|
35962
|
-
import { createHash as
|
|
35963
|
-
import { basename as
|
|
36132
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
36133
|
+
import { basename as basename11, isAbsolute as isAbsolute8 } from "node:path";
|
|
35964
36134
|
import { promisify as promisify2 } from "node:util";
|
|
35965
36135
|
var exec2 = promisify2(execFile2);
|
|
35966
|
-
var
|
|
36136
|
+
var cache = /* @__PURE__ */ new Map();
|
|
35967
36137
|
var env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^GIT_/i.test(key)));
|
|
35968
36138
|
async function git(cwd2, ...args) {
|
|
35969
36139
|
const { stdout } = await exec2("git", args, { cwd: cwd2, env: { ...env, GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: process.platform === "win32" ? "NUL" : "/dev/null", GIT_OPTIONAL_LOCKS: "0" }, timeout: 1500, maxBuffer: 8192, windowsHide: true });
|
|
@@ -36000,8 +36170,8 @@ async function inspect(directory3) {
|
|
|
36000
36170
|
const key = remote ? `remote:${remote.key}` : `local:${common}`;
|
|
36001
36171
|
return {
|
|
36002
36172
|
worktree,
|
|
36003
|
-
repository:
|
|
36004
|
-
repositoryLabel: remote?.label || (
|
|
36173
|
+
repository: createHash6("sha256").update(key).digest("hex"),
|
|
36174
|
+
repositoryLabel: remote?.label || (basename11(common) === ".git" ? basename11(common.slice(0, -5)) : basename11(common))
|
|
36005
36175
|
};
|
|
36006
36176
|
} catch {
|
|
36007
36177
|
return;
|
|
@@ -36014,12 +36184,12 @@ async function annotateGitCheckouts(sessions) {
|
|
|
36014
36184
|
await Promise.all(Array.from({ length: Math.min(8, directories.length) }, async () => {
|
|
36015
36185
|
while (index < directories.length) {
|
|
36016
36186
|
const directory3 = directories[index++];
|
|
36017
|
-
let entry =
|
|
36187
|
+
let entry = cache.get(directory3);
|
|
36018
36188
|
if (!entry || entry.expires <= Date.now()) {
|
|
36019
|
-
|
|
36020
|
-
if (
|
|
36189
|
+
cache.delete(directory3);
|
|
36190
|
+
if (cache.size >= 4096) cache.delete(cache.keys().next().value);
|
|
36021
36191
|
entry = { expires: Date.now() + 12e4, value: inspect(directory3) };
|
|
36022
|
-
|
|
36192
|
+
cache.set(directory3, entry);
|
|
36023
36193
|
}
|
|
36024
36194
|
const checkout = await entry.value;
|
|
36025
36195
|
if (checkout) results.set(directory3, checkout);
|