sessiongraph-app-win32-x64 1.0.11 → 1.0.13

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.
@@ -2627,12 +2627,12 @@ var serviceFile = (env = process.env) => env.SESSIONGRAPH_SERVICE_FILE || env.SE
2627
2627
  function databasePath(env = process.env, platform = process.platform, home = homedir2()) {
2628
2628
  const override = env.SESSIONGRAPH_DATA_DIR || env.SESSION_ATLAS_DATA_DIR || env.ATLAS_DATA_DIR;
2629
2629
  const base = platform === "darwin" ? join2(home, "Library", "Application Support") : platform === "win32" ? env.LOCALAPPDATA || home : env.XDG_DATA_HOME || join2(home, ".local", "share");
2630
- const paths = [
2630
+ const paths2 = [
2631
2631
  join2(override || join2(base, platform === "linux" ? "sessiongraph" : "SessionGraph"), "sessiongraph.sqlite"),
2632
2632
  join2(override || join2(base, platform === "linux" ? "session-atlas" : "Session Atlas"), "session-atlas.sqlite"),
2633
2633
  join2(override || join2(base, platform === "linux" ? "atlas" : "Atlas"), "atlas.sqlite")
2634
2634
  ];
2635
- return paths.find((path) => existsSync(path)) || paths[0];
2635
+ return paths2.find((path) => existsSync(path)) || paths2[0];
2636
2636
  }
2637
2637
 
2638
2638
  // src/playback-tokens.ts
@@ -2738,7 +2738,7 @@ function editedPaths(part) {
2738
2738
  }
2739
2739
  return [];
2740
2740
  }
2741
- function summarizeMessages(id2, messages, nextCursor) {
2741
+ function summarizeMessages(id2, messages, nextCursor2) {
2742
2742
  const files = /* @__PURE__ */ new Map();
2743
2743
  const tools = /* @__PURE__ */ new Map();
2744
2744
  const locations = [];
@@ -2770,8 +2770,8 @@ function summarizeMessages(id2, messages, nextCursor) {
2770
2770
  locations,
2771
2771
  messagesScanned: messages.length,
2772
2772
  snapshotSteps,
2773
- partial: Boolean(nextCursor),
2774
- nextCursor,
2773
+ partial: Boolean(nextCursor2),
2774
+ nextCursor: nextCursor2,
2775
2775
  loadedAt: Date.now()
2776
2776
  };
2777
2777
  }
@@ -2985,6 +2985,14 @@ function blockEvents(message2, content, transform = (v3) => v3) {
2985
2985
  return [eventFor(message2, id2, "event", `${part.type || "Unknown"} content`, "This content type is not represented as text.", { ...fields2, partial: true })];
2986
2986
  });
2987
2987
  }
2988
+ function userBlockEvents(message2, content, normalize) {
2989
+ const context = [];
2990
+ return blockEvents(message2, content, (value) => {
2991
+ const text2 = normalize(value);
2992
+ context.push(Boolean(value && !text2));
2993
+ return text2 || value;
2994
+ }).map((event) => event.kind === "message" && context.shift() ? { ...event, kind: "event", role: "system", name: "Session context", nativeType: "user-context" } : event);
2995
+ }
2988
2996
  function normalizedEvents(message2, sessionID) {
2989
2997
  let events = message2.events;
2990
2998
  if (!events) {
@@ -30778,6 +30786,29 @@ function successfulEdits(messages, editNames) {
30778
30786
 
30779
30787
  // server/adapters/pi.ts
30780
30788
  import { homedir as homedir3 } from "node:os";
30789
+
30790
+ // server/source-paths.ts
30791
+ import { AsyncLocalStorage } from "node:async_hooks";
30792
+ var paths = new AsyncLocalStorage();
30793
+ var sourcePath = (id2) => paths.getStore()?.[id2];
30794
+ function withSourcePaths(adapter, configured) {
30795
+ return {
30796
+ ...adapter,
30797
+ detect: () => paths.run(configured(), () => adapter.detect()),
30798
+ discover: () => paths.run(configured(), async () => {
30799
+ const result = await adapter.discover();
30800
+ if (!sourcePath(adapter.id)) return result;
30801
+ return { ...result, sessions: result.sessions.map((candidate) => ({ ...candidate, session: { ...candidate.session, nativeResume: false } })) };
30802
+ }),
30803
+ read: (candidate, cursor) => paths.run(configured(), async () => {
30804
+ const result = await adapter.read(candidate, cursor);
30805
+ if (sourcePath(adapter.id)) candidate.session.nativeResume = false;
30806
+ return result;
30807
+ })
30808
+ };
30809
+ }
30810
+
30811
+ // server/adapters/pi.ts
30781
30812
  import { join as join5 } from "node:path";
30782
30813
  function piHistory(value) {
30783
30814
  const { rows: rows2, partial } = jsonLines(value);
@@ -30809,11 +30840,11 @@ var piAdapter = localFileAdapter({
30809
30840
  name: "Pi",
30810
30841
  description: "Local JSONL sessions \xB7 messages, tools, compaction, and branch entries",
30811
30842
  capabilities: { history: true, forks: false, children: false, files: true },
30812
- roots: () => [process.env.SESSIONGRAPH_PI_SESSIONS_DIR || join5(process.env.PI_CODING_AGENT_DIR || join5(homedir3(), ".pi", "agent"), "sessions")],
30843
+ roots: () => [sourcePath("pi") || process.env.SESSIONGRAPH_PI_SESSIONS_DIR || join5(process.env.PI_CODING_AGENT_DIR || join5(homedir3(), ".pi", "agent"), "sessions")],
30813
30844
  match: (path) => path.endsWith(".jsonl"),
30814
30845
  parse(path, files) {
30815
30846
  const history = piHistory(files.get(path));
30816
- history.session.nativeResume = Boolean(history.session.directory) && !process.env.SESSIONGRAPH_PI_SESSIONS_DIR;
30847
+ history.session.nativeResume = Boolean(history.session.directory) && !sourcePath("pi") && !process.env.SESSIONGRAPH_PI_SESSIONS_DIR;
30817
30848
  return history;
30818
30849
  }
30819
30850
  });
@@ -30971,6 +31002,8 @@ import { chmodSync, constants as constants4, copyFileSync, lstatSync as lstatSyn
30971
31002
  import { tmpdir } from "node:os";
30972
31003
  import { join as join7 } from "node:path";
30973
31004
  var copies = /* @__PURE__ */ new Map();
31005
+ var SqliteSnapshotChangedError = class extends Error {
31006
+ };
30974
31007
  var close = (path) => {
30975
31008
  const copy = copies.get(path);
30976
31009
  if (!copy) return;
@@ -31000,7 +31033,7 @@ function withSqliteSnapshot(path, read3, expected, pinned = false) {
31000
31033
  const retained = copies.get(path);
31001
31034
  if (pinned && expected && retained?.revision === expected) return read3(retained.db);
31002
31035
  const revision2 = sqliteRevision(path);
31003
- if (expected && revision2 !== expected) throw new Error("History database changed during import; import again.");
31036
+ if (expected && revision2 !== expected) throw new SqliteSnapshotChangedError("History database changed during import; import again.");
31004
31037
  let copy = copies.get(path);
31005
31038
  if (copy?.revision !== revision2) {
31006
31039
  close(path);
@@ -31019,7 +31052,7 @@ function withSqliteSnapshot(path, read3, expected, pinned = false) {
31019
31052
  throw error;
31020
31053
  }
31021
31054
  }
31022
- if (sqliteRevision(path) !== revision2) throw new Error("History database changed while copying; import again.");
31055
+ if (sqliteRevision(path) !== revision2) throw new SqliteSnapshotChangedError("History database changed while copying; import again.");
31023
31056
  db2 = new DatabaseSync(destination, { readOnly: true, enableDoubleQuotedStringLiterals: false, allowExtension: false });
31024
31057
  db2.exec("PRAGMA query_only=ON; PRAGMA trusted_schema=OFF; PRAGMA busy_timeout=1000; BEGIN;");
31025
31058
  copy = { revision: revision2, directory: directory2, db: db2 };
@@ -31034,7 +31067,7 @@ function withSqliteSnapshot(path, read3, expected, pinned = false) {
31034
31067
  }
31035
31068
  }
31036
31069
  const result = read3(copy.db);
31037
- if (!pinned && sqliteRevision(path) !== revision2) throw new Error("History database changed during reading; import again.");
31070
+ if (!pinned && sqliteRevision(path) !== revision2) throw new SqliteSnapshotChangedError("History database changed during reading; import again.");
31038
31071
  return result;
31039
31072
  }
31040
31073
  function hasTable(db2, name) {
@@ -31115,18 +31148,23 @@ function sqliteHistoryAdapter(source) {
31115
31148
  let unavailable = false;
31116
31149
  for (const path of await source.paths()) {
31117
31150
  try {
31118
- const snapshot2 = sqliteRevision(path), rev = digest([2, source.id, snapshot2]);
31151
+ const snapshot2 = sqliteRevision(path), rev = digest([source.version || 2, source.id, snapshot2]);
31119
31152
  let cached2 = metadata2.get(path);
31120
31153
  if (!cached2 || cached2.revision !== rev) {
31121
31154
  cached2 = withSqliteSnapshot(path, (db2) => {
31122
31155
  const table = typeof source.table === "string" ? source.table : source.table(db2);
31123
31156
  const values2 = rows(db2, table, source.fields, void 0, source.key, 2e4), found = [];
31124
31157
  const blocked2 = [], warnings2 = [];
31158
+ let empty = 0;
31125
31159
  for (const row of values2) {
31126
31160
  try {
31127
31161
  const h3 = parseHistory(source, db2, row, path);
31128
31162
  if (!h3) continue;
31129
- if (source.history !== false && !h3.messages.length) throw new Error("No readable conversation.");
31163
+ if (source.history !== false && !h3.messages.length) {
31164
+ blocked2.push(identity(source.id, String(row[source.key])));
31165
+ empty++;
31166
+ continue;
31167
+ }
31130
31168
  if (!h3.nativeID || h3.nativeID.length > 512) throw new Error("Missing native session identity.");
31131
31169
  const created = time(h3.session?.created) || h3.messages.map((m) => time(m.time)).find(Boolean);
31132
31170
  if (!created) throw new Error("Session has no recorded creation or message date.");
@@ -31146,7 +31184,8 @@ function sqliteHistoryAdapter(source) {
31146
31184
  blocked2.push(identity(source.id, String(row[source.key])));
31147
31185
  }
31148
31186
  }
31149
- if (blocked2.length) warnings2.push(`${blocked2.length} ${source.name} sessions had unsupported, undated, missing, or oversized history; saved imports are kept.`);
31187
+ if (blocked2.length > empty) warnings2.push(`${blocked2.length - empty} ${source.name} sessions had unsupported, undated, missing, or oversized history; saved imports are kept.`);
31188
+ if (empty) warnings2.push(`${empty} empty ${source.name} sessions had no saved messages; previous imports are kept.`);
31150
31189
  return { revision: rev, candidates: found, blocked: blocked2, warnings: warnings2 };
31151
31190
  }, snapshot2);
31152
31191
  metadata2.set(path, cached2);
@@ -31183,9 +31222,9 @@ function sqliteHistoryAdapter(source) {
31183
31222
  }
31184
31223
  };
31185
31224
  }
31186
- async function existingDatabases(paths) {
31225
+ async function existingDatabases(paths2) {
31187
31226
  const found = [];
31188
- for (const path of new Set(paths)) {
31227
+ for (const path of new Set(paths2)) {
31189
31228
  try {
31190
31229
  if ((await lstat3(path)).isFile()) found.push(path);
31191
31230
  } catch (e10) {
@@ -31230,7 +31269,7 @@ function combineAdapters(parts) {
31230
31269
  }
31231
31270
 
31232
31271
  // server/adapters/claude.ts
31233
- var root = () => join8(process.env.CLAUDE_CONFIG_DIR || join8(homedir4(), ".claude"), "projects");
31272
+ var root = () => join8(sourcePath("claude-code") || process.env.CLAUDE_CONFIG_DIR || join8(homedir4(), ".claude"), "projects");
31234
31273
  function claudeMessages(rows2, candidate, times) {
31235
31274
  const calls = /* @__PURE__ */ new Map();
31236
31275
  return rows2.map((row) => {
@@ -31275,7 +31314,7 @@ var sdkClaudeAdapter = {
31275
31314
  },
31276
31315
  async discover() {
31277
31316
  const sessions = [], warnings = [];
31278
- const infos = await I1t({ limit: 2e4, includeProgrammatic: true });
31317
+ const infos = sourcePath("claude-code") ? [] : await I1t({ limit: 2e4, includeProgrammatic: true });
31279
31318
  if (infos.length === 2e4) warnings.push("Claude Code listing is limited to 20,000 sessions.");
31280
31319
  const files = /* @__PURE__ */ new Map();
31281
31320
  let unreadable = 0;
@@ -31368,7 +31407,7 @@ var exportedClaudeAdapter = localFileAdapter({
31368
31407
  name: "Claude Code",
31369
31408
  description: "Legacy local transcript exports",
31370
31409
  capabilities: { history: true, forks: false, children: false, files: false },
31371
- roots: () => [join8(process.env.CLAUDE_CONFIG_DIR || join8(homedir4(), ".claude"), "transcripts")],
31410
+ roots: () => [join8(sourcePath("claude-code") || process.env.CLAUDE_CONFIG_DIR || join8(homedir4(), ".claude"), "transcripts")],
31372
31411
  match: (p) => p.endsWith(".jsonl"),
31373
31412
  parse: (path, files) => envelopeHistory(path, files.get(path))
31374
31413
  });
@@ -31473,10 +31512,10 @@ async function transcriptFiles(root3, max = 2e4, match2 = (name) => name.endsWit
31473
31512
  }
31474
31513
 
31475
31514
  // server/adapters/codex.ts
31476
- var root2 = () => process.env.CODEX_HOME || join10(homedir5(), ".codex");
31515
+ var root2 = () => sourcePath("codex") || process.env.CODEX_HOME || join10(homedir5(), ".codex");
31477
31516
  var revision = async (path) => {
31478
31517
  const s = await stat2(path);
31479
- return digest([8, s.mtimeMs, s.size]);
31518
+ return digest([9, s.mtimeMs, s.size]);
31480
31519
  };
31481
31520
  function changedPaths(value) {
31482
31521
  if (!value || typeof value !== "object") return [];
@@ -31486,9 +31525,14 @@ function changedPaths(value) {
31486
31525
  function codexUserText(value) {
31487
31526
  if (typeof value !== "string") return "";
31488
31527
  let text2 = value.trim();
31528
+ for (; ; ) {
31529
+ const context = text2.match(/^<(environment_context|permissions|user_instructions|turn_aborted|system_instruction|recommended_plugins|external_codex_[\w-]+)(?:\s[^>]*)?>/i);
31530
+ if (!context) break;
31531
+ const end = text2.toLowerCase().indexOf(`</${context[1].toLowerCase()}>`, context[0].length);
31532
+ if (end < 0) return "";
31533
+ text2 = text2.slice(end + context[1].length + 3).trim();
31534
+ }
31489
31535
  if (/^# (?:AGENTS\.md|Instructions for)/i.test(text2)) return "";
31490
- text2 = text2.replace(/<(environment_context|permissions|user_instructions|turn_aborted|external_codex_[\w-]+)>[\s\S]*?<\/\1>/g, "").trim();
31491
- if (/^<(?:environment_context|permissions|user_instructions|turn_aborted|external_codex_[\w-]+)(?:>|\s)/.test(text2)) return "";
31492
31536
  return text2;
31493
31537
  }
31494
31538
  async function sessionNames() {
@@ -31541,8 +31585,7 @@ function codexRecord(raw, offset, candidate) {
31541
31585
  const role = p.role === "user" ? "user" : p.role === "assistant" ? "assistant" : p.type === "message" ? "system" : "tool";
31542
31586
  const msg = blankMessage(`item:${raw.ordinal ?? offset}`, Date.parse(raw.timestamp) || 0, role);
31543
31587
  const fields2 = { nativeID: p.id, nativeType: p.type, callID: p.call_id };
31544
- msg.events = p.type === "message" ? blockEvents(msg, p.content) : ["function_call", "custom_tool_call"].includes(p.type) ? [eventFor(msg, "call", "tool_call", p.name || "Tool call", "", { ...fields2, role: "assistant", input: eventText(p.arguments ?? p.input), status: "unknown" })] : ["function_call_output", "custom_tool_call_output"].includes(p.type) ? [eventFor(msg, "result", "tool_result", "Tool result", "", { ...fields2, output: eventText(p.output, 64e3), status: "unknown" })] : [eventFor(msg, "event", p.type === "reasoning" ? "reasoning" : "event", p.type === "reasoning" ? "Recorded reasoning summary" : p.type || "Unknown event", eventText(p.type === "reasoning" ? p.summary : p), { ...fields2, partial: p.type === "reasoning" })];
31545
- if (role === "user") msg.events = msg.events.map((event) => event.kind === "message" && event.text && !codexUserText(event.text) ? { ...event, kind: "event", role: "system", name: "Session context", nativeType: "user-context" } : event);
31588
+ msg.events = p.type === "message" ? role === "user" ? userBlockEvents(msg, p.content, codexUserText) : blockEvents(msg, p.content) : ["function_call", "custom_tool_call"].includes(p.type) ? [eventFor(msg, "call", "tool_call", p.name || "Tool call", "", { ...fields2, role: "assistant", input: eventText(p.arguments ?? p.input), status: "unknown" })] : ["function_call_output", "custom_tool_call_output"].includes(p.type) ? [eventFor(msg, "result", "tool_result", "Tool result", "", { ...fields2, output: eventText(p.output, 64e3), status: "unknown" })] : [eventFor(msg, "event", p.type === "reasoning" ? "reasoning" : "event", p.type === "reasoning" ? "Recorded reasoning summary" : p.type || "Unknown event", eventText(p.type === "reasoning" ? p.summary : p), { ...fields2, partial: p.type === "reasoning" })];
31546
31589
  if (p.type === "message") {
31547
31590
  for (const part of Array.isArray(p.content) ? p.content : []) if (["input_text", "output_text", "text"].includes(part.type)) addText(msg, role === "user" ? codexUserText(part.text) : part.text, role === "user" ? "You" : "Assistant");
31548
31591
  } else if (["function_call", "custom_tool_call"].includes(p.type)) {
@@ -31574,10 +31617,10 @@ var codexAdapter = {
31574
31617
  const found = /* @__PURE__ */ new Map(), warnings = [];
31575
31618
  const names = await sessionNames();
31576
31619
  const match2 = (name) => /\.jsonl(?:\.[\w.-]+)?$/.test(name);
31577
- const paths = [...await transcriptFiles(join10(root2(), "sessions"), 2e4, match2), ...await transcriptFiles(join10(root2(), "archived_sessions"), 2e4, match2)];
31578
- if (paths.length >= 2e4) warnings.push("Codex transcript listing may be partial (20,000 files per history folder).");
31620
+ const paths2 = [...await transcriptFiles(join10(root2(), "sessions"), 2e4, match2), ...await transcriptFiles(join10(root2(), "archived_sessions"), 2e4, match2)];
31621
+ if (paths2.length >= 2e4) warnings.push("Codex transcript listing may be partial (20,000 files per history folder).");
31579
31622
  let unsupported = 0;
31580
- for (const path of paths) {
31623
+ for (const path of paths2) {
31581
31624
  try {
31582
31625
  const first = await readJSONL(path, 0, 2e6, 100);
31583
31626
  const meta = first.rows.find((r) => r.value.type === "session_meta")?.value.payload;
@@ -31652,14 +31695,14 @@ function status(value) {
31652
31695
  return ["pending", "running", "completed", "failed"].includes(string(value)) ? value : "unknown";
31653
31696
  }
31654
31697
  async function databasePath2() {
31655
- const root3 = process.env.SESSIONGRAPH_T3_CODE_HISTORY_DIR || process.env.T3CODE_HOME || join11(homedir6(), ".t3");
31656
- const paths = /\.sqlite$/.test(root3) ? [root3] : [
31698
+ const root3 = sourcePath("t3-code") || process.env.SESSIONGRAPH_T3_CODE_HISTORY_DIR || process.env.T3CODE_HOME || join11(homedir6(), ".t3");
31699
+ const paths2 = /\.sqlite$/.test(root3) ? [root3] : [
31657
31700
  join11(root3, "userdata", "statev2.sqlite"),
31658
31701
  join11(root3, "statev2.sqlite"),
31659
31702
  join11(root3, "userdata", "state.sqlite"),
31660
31703
  join11(root3, "state.sqlite")
31661
31704
  ];
31662
- for (const path of paths) {
31705
+ for (const path of paths2) {
31663
31706
  try {
31664
31707
  if ((await lstat4(path)).isFile()) return path;
31665
31708
  } catch (error) {
@@ -31891,8 +31934,14 @@ var t3CodeAdapter = {
31891
31934
  async discover() {
31892
31935
  const path = await databasePath2();
31893
31936
  if (!path) return { sessions: [], projects: [], warnings: ["T3 Code database is unavailable. Saved history is retained."] };
31894
- const databaseRevision = sqliteRevision(path);
31895
- return withSqliteSnapshot(path, (db2) => hasTable(db2, "orchestration_v2_projection_threads") ? discoverV2(db2, path, databaseRevision) : discoverV1(db2, path, databaseRevision), databaseRevision);
31937
+ for (let attempt = 0; ; attempt++) {
31938
+ const databaseRevision = sqliteRevision(path);
31939
+ try {
31940
+ return withSqliteSnapshot(path, (db2) => hasTable(db2, "orchestration_v2_projection_threads") ? discoverV2(db2, path, databaseRevision) : discoverV1(db2, path, databaseRevision), databaseRevision);
31941
+ } catch (error) {
31942
+ if (!(error instanceof SqliteSnapshotChangedError) || attempt >= 2) throw error;
31943
+ }
31944
+ }
31896
31945
  },
31897
31946
  async read(candidate, cursor) {
31898
31947
  return withSqliteSnapshot(candidate.locator.path, (db2) => candidate.locator.format === "v2" ? readV2(db2, candidate, cursor) : readV1(db2, candidate, cursor), candidate.locator.databaseRevision, true);
@@ -31911,8 +31960,26 @@ function cursorTime(value) {
31911
31960
  const time4 = typeof value === "number" ? value : typeof value === "string" && /(?:Z|[+-]\d\d:\d\d)$/.test(value) ? Date.parse(value) : 0;
31912
31961
  return Number.isFinite(time4) && time4 > 0 && time4 <= 864e13 ? time4 : 0;
31913
31962
  }
31963
+ function cursorEnvelope(text2) {
31964
+ let value = text2.trim(), timestamp;
31965
+ for (; ; ) {
31966
+ value = value.replace(/^(?:\[Image\]\s*)+(?=<image_files>)/, "");
31967
+ const clock = value.match(/^<timestamp>([^<]+)<\/timestamp>\s*/);
31968
+ if (clock) {
31969
+ timestamp ??= clock[1];
31970
+ value = value.slice(clock[0].length);
31971
+ continue;
31972
+ }
31973
+ const context = value.match(/^<(user_info|environment_context|system_reminder|external_links|attached_files|image_files)(?:\s[^>]*)?>/);
31974
+ if (!context) break;
31975
+ const end = value.indexOf(`</${context[1]}>`, context[0].length);
31976
+ if (end < 0) return { text: "", timestamp };
31977
+ value = value.slice(end + context[1].length + 3).trim();
31978
+ }
31979
+ return { text: value, timestamp };
31980
+ }
31914
31981
  function cursorEnvelopeTime(text2) {
31915
- const value = text2.match(/^\s*<timestamp>([^<]+)<\/timestamp>/)?.[1];
31982
+ const value = cursorEnvelope(text2).timestamp;
31916
31983
  if (!value) return 0;
31917
31984
  const iso = cursorTime(value);
31918
31985
  if (iso) return iso;
@@ -31921,17 +31988,21 @@ function cursorEnvelopeTime(text2) {
31921
31988
  return cursorTime(Date.parse(`${match2[1]} ${match2[2]} GMT${match2[3]}${match2[4].padStart(2, "0")}${match2[5] || "00"}`));
31922
31989
  }
31923
31990
  function cursorUserText(text2) {
31924
- let value = text2.trim().replace(/^<timestamp>[^<]+<\/timestamp>\s*/, "");
31925
- for (; ; ) {
31926
- const stripped = value.replace(/^<(user_info|environment_context|system_reminder)>[\s\S]*?<\/\1>\s*/, "");
31927
- if (stripped === value) break;
31928
- value = stripped;
31929
- }
31991
+ const value = cursorEnvelope(text2).text;
31930
31992
  const query = value.match(/^<user_query>([\s\S]*?)<\/user_query>(?:\s*<system_reminder>[\s\S]*?<\/system_reminder>)*\s*$/);
31931
31993
  return (query ? query[1] : value).trim();
31932
31994
  }
31933
31995
  function cursorMessage(raw, fallbackID) {
31934
31996
  if (!raw || typeof raw !== "object") return;
31997
+ if (raw.type === "turn_ended") {
31998
+ const message2 = blankMessage(typeof raw.id === "string" && raw.id.length <= 512 ? raw.id : fallbackID, cursorTime(raw.timestamp), "system");
31999
+ const failed = raw.status === "error" || raw.status === "failed";
32000
+ message2.events = [eventFor(message2, "turn-ended", failed ? "error" : "event", failed ? "Cursor turn failed" : "Cursor turn ended", eventText(raw.error), {
32001
+ nativeType: "turn_ended",
32002
+ status: failed ? "failed" : raw.status === "completed" || raw.status === "success" ? "completed" : "unknown"
32003
+ })];
32004
+ return message2;
32005
+ }
31935
32006
  const body2 = raw.message && typeof raw.message === "object" ? raw.message : raw;
31936
32007
  const role = raw.role || body2.role;
31937
32008
  if (!["user", "assistant", "tool", "system"].includes(role)) return;
@@ -31940,7 +32011,7 @@ function cursorMessage(raw, fallbackID) {
31940
32011
  const time4 = cursorTime(raw.timestamp) || cursorTime(body2.timestamp) || cursorTime(body2.createdAt) || (role === "user" && typeof firstText === "string" ? cursorEnvelopeTime(firstText) : 0);
31941
32012
  const native = [raw.uuid, raw.id, body2.uuid, body2.id].find((id2) => typeof id2 === "string" && id2.length && id2.length <= 512);
31942
32013
  const msg = blankMessage(native || fallbackID, time4, role);
31943
- msg.events = role === "tool" ? [eventFor(msg, "result", "tool_result", body2.name || "Tool result", "", { callID: body2.tool_call_id, output: eventText(content, 64e3), status: "unknown" })] : blockEvents(msg, content);
32014
+ msg.events = role === "tool" ? [eventFor(msg, "result", "tool_result", body2.name || "Tool result", "", { callID: body2.tool_call_id, output: eventText(content, 64e3), status: "unknown" })] : role === "user" ? userBlockEvents(msg, content, cursorUserText) : blockEvents(msg, content);
31944
32015
  const kind = role === "user" ? "You" : role === "assistant" ? "Assistant" : "Tool";
31945
32016
  const text2 = (value) => addText(msg, role === "user" && typeof value === "string" ? cursorUserText(value) : value, kind);
31946
32017
  if (typeof content === "string") text2(content);
@@ -32163,7 +32234,7 @@ function discoverComposers(path, workspace = "") {
32163
32234
  for (const table of ["cursorDiskKV", "ItemTable"]) {
32164
32235
  if (!hasTable(db2, table)) continue;
32165
32236
  let failed = 0, count = 0;
32166
- const rows2 = db2.prepare(`SELECT key, CASE WHEN length(value)<=? THEN value END AS value FROM ${table} WHERE key LIKE 'composerData:%' ORDER BY key LIMIT 20001`).iterate(MAX_VALUE2);
32237
+ const rows2 = db2.prepare(`SELECT key, CASE WHEN length(value)<=? THEN value END AS value FROM ${table} WHERE key LIKE 'composerData:%' AND value IS NOT NULL ORDER BY key LIMIT 20001`).iterate(MAX_VALUE2);
32167
32238
  for (const row of rows2) {
32168
32239
  if (++count > 2e4) {
32169
32240
  warnings.push("Cursor Composer listing reached its 20,000-session limit.");
@@ -32184,7 +32255,7 @@ function discoverComposers(path, workspace = "") {
32184
32255
  session.model = text(data.modelConfig?.modelName) || "Unknown model";
32185
32256
  session.archived = data.isArchived === true;
32186
32257
  const children = Array.isArray(data.subagentComposerIds) ? data.subagentComposerIds.filter((id2) => typeof id2 === "string") : [];
32187
- sessions.push({ session, revision: digest([1, snapshot2, table, nativeID]), locator: { path, kind: "composer", table, snapshot: snapshot2, nativeID, children: JSON.stringify(children) } });
32258
+ sessions.push({ session, revision: digest([2, snapshot2, table, nativeID]), locator: { path, kind: "composer", table, snapshot: snapshot2, nativeID, children: JSON.stringify(children) } });
32188
32259
  } catch {
32189
32260
  failed++;
32190
32261
  }
@@ -32314,7 +32385,7 @@ async function workspacePaths(root3, warnings) {
32314
32385
  return stores;
32315
32386
  }
32316
32387
  function createCursorAdapter(options = {}) {
32317
- const root3 = () => options.home || process.env.SESSIONGRAPH_CURSOR_HOME || process.env.SESSION_ATLAS_CURSOR_HOME || join13(homedir7(), ".cursor");
32388
+ const root3 = () => options.home || sourcePath("cursor") || process.env.SESSIONGRAPH_CURSOR_HOME || process.env.SESSION_ATLAS_CURSOR_HOME || join13(homedir7(), ".cursor");
32318
32389
  const editor = () => options.userData || process.env.SESSIONGRAPH_CURSOR_USER_DATA_DIR || process.env.SESSION_ATLAS_CURSOR_USER_DATA_DIR || userData();
32319
32390
  return {
32320
32391
  id: "cursor",
@@ -32337,7 +32408,7 @@ function createCursorAdapter(options = {}) {
32337
32408
  async discover() {
32338
32409
  const warnings = [], found = /* @__PURE__ */ new Map(), blocked = /* @__PURE__ */ new Set();
32339
32410
  const workspaceStores = await workspacePaths(editor(), warnings);
32340
- const paths = [...new Set([...workspaceStores.values()].filter(Boolean))];
32411
+ const paths2 = [...new Set([...workspaceStores.values()].filter(Boolean))];
32341
32412
  const legacyStores = new Map([[join13(editor(), "User/globalStorage/state.vscdb"), ""], ...workspaceStores]);
32342
32413
  for (const [path, workspace] of legacyStores) {
32343
32414
  try {
@@ -32358,7 +32429,7 @@ function createCursorAdapter(options = {}) {
32358
32429
  }
32359
32430
  const composers = new Map(found);
32360
32431
  const match2 = (key, encode) => {
32361
- const matches = paths.filter((path) => encode(path) === key);
32432
+ const matches = paths2.filter((path) => encode(path) === key);
32362
32433
  return matches.length === 1 ? matches[0] : "";
32363
32434
  };
32364
32435
  let unreadable = 0, legacy = 0, scanned = 0;
@@ -32422,7 +32493,7 @@ function createCursorAdapter(options = {}) {
32422
32493
  session.projectID = project("cursor", session.directory).id;
32423
32494
  if (session.directory) delete locator.directoryNote;
32424
32495
  }
32425
- const candidate = { session, locator, revision: digest([4, kind, path, before, session.created, session.directory, session.parentID]) };
32496
+ const candidate = { session, locator, revision: digest([5, kind, path, before, session.created, session.directory, session.parentID]) };
32426
32497
  if (!previous || rank(candidate) > rank(previous) || rank(candidate) === rank(previous) && session.updated > previous.session.updated) found.set(session.id, candidate);
32427
32498
  } catch {
32428
32499
  unreadable++;
@@ -32502,7 +32573,7 @@ function createCursorAdapter(options = {}) {
32502
32573
  const messages = page.rows.flatMap((row) => {
32503
32574
  const message2 = cursorMessage(row.value, `offset:${row.offset}`);
32504
32575
  if (!message2) page.partial = true;
32505
- return message2 && message2.role !== "system" ? [message2] : [];
32576
+ return message2 && (message2.role !== "system" || row.value?.type === "turn_ended") ? [message2] : [];
32506
32577
  });
32507
32578
  await verify();
32508
32579
  if (!offset && page.cursor === void 0 && !messages.length) throw new Error("Cursor transcript has no readable conversation. Previous imports are retained.");
@@ -32565,7 +32636,7 @@ var geminiAdapter = localFileAdapter({
32565
32636
  name: "Gemini CLI",
32566
32637
  description: "Local JSON and JSONL chats, including recorded subagent histories",
32567
32638
  capabilities: { history: true, forks: false, children: true, files: true },
32568
- roots: () => process.env.SESSIONGRAPH_GEMINI_HOME ? [join14(process.env.SESSIONGRAPH_GEMINI_HOME, "tmp")] : [join14(process.env.GEMINI_CLI_HOME || homedir8(), ".gemini", "tmp"), join14(process.env.GEMINI_CLI_HOME || homedir8(), ".cache", ".gemini", "tmp")],
32639
+ roots: () => sourcePath("gemini") || process.env.SESSIONGRAPH_GEMINI_HOME ? [join14(sourcePath("gemini") || process.env.SESSIONGRAPH_GEMINI_HOME, "tmp")] : [join14(process.env.GEMINI_CLI_HOME || homedir8(), ".gemini", "tmp"), join14(process.env.GEMINI_CLI_HOME || homedir8(), ".cache", ".gemini", "tmp")],
32569
32640
  match: (path) => /^[^/]+\/chats\/(?:[^/]+\/)?[^/]+\.jsonl?$/.test(path),
32570
32641
  extras: (path) => [projectRootFile(path)],
32571
32642
  parse(path, files) {
@@ -32594,7 +32665,7 @@ var geminiAdapter = localFileAdapter({
32594
32665
  messages,
32595
32666
  parent: parent2,
32596
32667
  partial,
32597
- session: { directory: directory2, created: time(meta.startTime), title: text(meta.summary), model: text([...records].reverse().find((r) => r.model)?.model) || "Unknown model", provider: "Google", nativeResume: !parent2 && Boolean(directory2) && !process.env.SESSIONGRAPH_GEMINI_HOME && !path.includes(`${sep3}.cache${sep3}`) },
32668
+ session: { directory: directory2, created: time(meta.startTime), title: text(meta.summary), model: text([...records].reverse().find((r) => r.model)?.model) || "Unknown model", provider: "Google", nativeResume: !parent2 && Boolean(directory2) && !sourcePath("gemini") && !process.env.SESSIONGRAPH_GEMINI_HOME && !path.includes(`${sep3}.cache${sep3}`) },
32598
32669
  note: "Local Gemini chat records with rewind and patch reconstruction. Only explicit subagent directories form parent links; workspace paths come from the project-root marker. Binary content is omitted."
32599
32670
  };
32600
32671
  }
@@ -32608,7 +32679,7 @@ var qwenAdapter = localFileAdapter({
32608
32679
  name: "Qwen Code",
32609
32680
  description: "Local project chat records \xB7 tool results, forks, and child sessions",
32610
32681
  capabilities: { history: true, forks: true, children: true, files: true },
32611
- roots: () => [join15(process.env.SESSIONGRAPH_QWEN_HOME || process.env.QWEN_RUNTIME_DIR || process.env.QWEN_HOME || join15(homedir9(), ".qwen"), "projects")],
32682
+ roots: () => [join15(sourcePath("qwen-code") || process.env.SESSIONGRAPH_QWEN_HOME || process.env.QWEN_RUNTIME_DIR || process.env.QWEN_HOME || join15(homedir9(), ".qwen"), "projects")],
32612
32683
  match: (path) => /^[^/]+\/chats\/[^/]+\.jsonl$/.test(path),
32613
32684
  parse(path, files) {
32614
32685
  const { rows: rows2, partial } = jsonLines(files.get(path));
@@ -32638,7 +32709,7 @@ var qwenAdapter = localFileAdapter({
32638
32709
  partial,
32639
32710
  parent: text(parent2) || void 0,
32640
32711
  fork: text(rows2.find((r) => r.forkedFrom?.sessionId)?.forkedFrom?.sessionId) || void 0,
32641
- session: { directory: text(first.cwd), created: time(first.timestamp), title: text(title), model: text(latest.find((r) => r.model)?.model) || text(latest.find((r) => r.subtype === "session_model")?.systemPayload?.modelId) || "Unknown model", nativeResume: Boolean(first.cwd) && !process.env.SESSIONGRAPH_QWEN_HOME },
32712
+ session: { directory: text(first.cwd), created: time(first.timestamp), title: text(title), model: text(latest.find((r) => r.model)?.model) || text(latest.find((r) => r.subtype === "session_model")?.systemPayload?.modelId) || "Unknown model", nativeResume: Boolean(first.cwd) && !sourcePath("qwen-code") && !process.env.SESSIONGRAPH_QWEN_HOME },
32642
32713
  note: "Local Qwen chat records, including compaction and branch events in source order. Parent and fork links use recorded session IDs. Managed-daemon-only and binary history may be unavailable."
32643
32714
  };
32644
32715
  }
@@ -32652,7 +32723,7 @@ var copilotAdapter = localFileAdapter({
32652
32723
  name: "GitHub Copilot CLI",
32653
32724
  description: "Local session event logs \xB7 conversations and completed file edits",
32654
32725
  capabilities: { history: true, forks: false, children: true, files: true },
32655
- roots: () => [join16(process.env.SESSIONGRAPH_COPILOT_HOME || join16(homedir10(), ".copilot"), "session-state")],
32726
+ roots: () => [join16(sourcePath("copilot") || process.env.SESSIONGRAPH_COPILOT_HOME || join16(homedir10(), ".copilot"), "session-state")],
32656
32727
  match: (path) => /(?:^|\/)events\.jsonl$/.test(path),
32657
32728
  parse(path, files) {
32658
32729
  const { rows: rows2, partial } = jsonLines(files.get(path));
@@ -32692,7 +32763,7 @@ var copilotAdapter = localFileAdapter({
32692
32763
  messages,
32693
32764
  partial,
32694
32765
  parent: text(meta.detachedFromSpawningParentSessionId) || void 0,
32695
- session: { directory: text(meta.context?.cwd), created: time(meta.startTime || start?.timestamp), title: text(latest.find((r) => r.type === "session.title_changed")?.data?.title), model: text(latest.find((r) => r.type === "session.model_change")?.data?.newModel) || text(meta.selectedModel) || "Unknown model", provider: text(meta.providerId), nativeResume: Boolean(meta.context?.cwd) && !process.env.SESSIONGRAPH_COPILOT_HOME },
32766
+ session: { directory: text(meta.context?.cwd), created: time(meta.startTime || start?.timestamp), title: text(latest.find((r) => r.type === "session.title_changed")?.data?.title), model: text(latest.find((r) => r.type === "session.model_change")?.data?.newModel) || text(meta.selectedModel) || "Unknown model", provider: text(meta.providerId), nativeResume: Boolean(meta.context?.cwd) && !sourcePath("copilot") && !process.env.SESSIONGRAPH_COPILOT_HOME },
32696
32767
  note: "Persisted Copilot CLI events only. Streaming deltas are excluded in favor of final messages. Tool-call parents are event correlations, not session ancestry. Cloud-only sessions and binary assets are unavailable."
32697
32768
  };
32698
32769
  }
@@ -32750,7 +32821,8 @@ function vscodeChatLog(content) {
32750
32821
  function copilotChatRoots(platform = process.platform, home = homedir11(), env = process.env) {
32751
32822
  const path = platform === "win32" ? win322 : posix;
32752
32823
  const base = platform === "darwin" ? path.join(home, "Library", "Application Support") : platform === "win32" ? env.APPDATA || path.join(home, "AppData", "Roaming") : env.XDG_CONFIG_HOME || path.join(home, ".config");
32753
- const users = env.SESSIONGRAPH_COPILOT_CHAT_USER_DATA_DIR ? [path.join(env.SESSIONGRAPH_COPILOT_CHAT_USER_DATA_DIR, "User")] : [...["Code", "Code - Insiders"].map((app) => path.join(base, app, "User")), ...[".vscode-server", ".vscode-server-insiders"].map((app) => path.join(home, app, "data", "User"))];
32824
+ const override = sourcePath("copilot-chat") || env.SESSIONGRAPH_COPILOT_CHAT_USER_DATA_DIR;
32825
+ const users = override ? [path.join(override, "User")] : [...["Code", "Code - Insiders"].map((app) => path.join(base, app, "User")), ...[".vscode-server", ".vscode-server-insiders"].map((app) => path.join(home, app, "data", "User"))];
32754
32826
  return users.flatMap((user) => [path.join(user, "workspaceStorage"), path.join(user, "globalStorage", "emptyWindowChatSessions")]);
32755
32827
  }
32756
32828
  function vscodeChatPath(value) {
@@ -32881,7 +32953,8 @@ function editorTaskRoots(extension) {
32881
32953
  return ["Code", "Code - Insiders", "VSCodium", "Cursor", "Windsurf"].map((app) => join18(base, app, "User", "globalStorage", extension, "tasks")).concat([".vscode-server", ".vscode-server-insiders"].map((app) => join18(home, app, "data", "User", "globalStorage", extension, "tasks")));
32882
32954
  }
32883
32955
  function taskAdapter(id2, name, extension, env) {
32884
- const roots2 = () => process.env[env] ? [join18(process.env[env], "tasks"), ...id2 === "cline" ? [join18(process.env[env], "data", "sessions")] : []] : [...editorTaskRoots(extension), ...id2 === "cline" ? [process.env.CLINE_SESSION_DATA_DIR || join18(process.env.CLINE_DATA_DIR || join18(process.env.CLINE_DIR || join18(homedir12(), ".cline"), "data"), "sessions")] : []];
32956
+ const home = () => sourcePath(id2) || process.env[env];
32957
+ const roots2 = () => home() ? [join18(home(), "tasks"), ...id2 === "cline" ? [join18(home(), "data", "sessions")] : []] : [...editorTaskRoots(extension), ...id2 === "cline" ? [process.env.CLINE_SESSION_DATA_DIR || join18(process.env.CLINE_DATA_DIR || join18(process.env.CLINE_DIR || join18(homedir12(), ".cline"), "data"), "sessions")] : []];
32885
32958
  return localFileAdapter({
32886
32959
  id: id2,
32887
32960
  name,
@@ -32930,7 +33003,7 @@ var continueAdapter = localFileAdapter({
32930
33003
  name: "Continue",
32931
33004
  description: "Local IDE and CLI session JSON \xB7 recorded conversation and tool history",
32932
33005
  capabilities: { history: true, forks: false, children: false, files: false },
32933
- roots: () => [join18(process.env.SESSIONGRAPH_CONTINUE_HOME || process.env.CONTINUE_GLOBAL_DIR || join18(homedir12(), ".continue"), "sessions")],
33006
+ roots: () => [join18(sourcePath("continue") || process.env.SESSIONGRAPH_CONTINUE_HOME || process.env.CONTINUE_GLOBAL_DIR || join18(homedir12(), ".continue"), "sessions")],
32934
33007
  match: (path) => /^[^/]+\.json$/.test(path) && path !== "sessions.json",
32935
33008
  extras: (path) => [join18(dirname5(path), "sessions.json")],
32936
33009
  revisionExtras: false,
@@ -32968,7 +33041,7 @@ var appPath = (...parts) => join19(process.platform === "darwin" ? homePath("Lib
32968
33041
  var tokscalePath = (...parts) => join19(process.env.TOKSCALE_CONFIG_DIR || (process.platform === "win32" ? appPath("tokscale") : configPath("tokscale")), ...parts);
32969
33042
  var envHome = (env, fallback, ...parts) => join19(process.env[env]?.trim() || homePath(fallback), ...parts);
32970
33043
  var harnessRoots = (id2, defaults) => () => {
32971
- const override = process.env[`SESSIONGRAPH_${id2.replace(/-/g, "_").toUpperCase()}_HISTORY_DIR`]?.trim();
33044
+ const override = sourcePath(id2) || process.env[`SESSIONGRAPH_${id2.replace(/-/g, "_").toUpperCase()}_HISTORY_DIR`]?.trim();
32972
33045
  return override ? [override] : defaults();
32973
33046
  };
32974
33047
 
@@ -33180,11 +33253,18 @@ var fileHarnessAdapters = definitions.map((source) => localFileAdapter({
33180
33253
  // server/adapters/harness-databases.ts
33181
33254
  import { lstat as lstat6, readFile as readFile4 } from "node:fs/promises";
33182
33255
  import { isAbsolute as isAbsolute5, join as join22 } from "node:path";
33183
- var parsedContent = (v3) => typeof v3 === "string" && /^[\[{]/.test(v3.trim()) ? optionalJSON(v3) : v3;
33256
+ function hermesContent(value) {
33257
+ if (typeof value !== "string" || !value.startsWith("\0json:")) return value;
33258
+ try {
33259
+ return JSON.parse(value.slice(6));
33260
+ } catch {
33261
+ return value;
33262
+ }
33263
+ }
33184
33264
  var millisOrSeconds = (v3) => typeof v3 === "number" && v3 > 0 && v3 < 1e10 ? seconds(v3) : time(v3);
33185
33265
  function dbPaths(id2, defaults, match2) {
33186
33266
  return async () => {
33187
- const override = process.env[`SESSIONGRAPH_${id2.replace(/-/g, "_").toUpperCase()}_HISTORY_DIR`];
33267
+ const override = sourcePath(id2) || process.env[`SESSIONGRAPH_${id2.replace(/-/g, "_").toUpperCase()}_HISTORY_DIR`];
33188
33268
  return override ? (await historyFiles([override], match2)).files : existingDatabases(defaults());
33189
33269
  };
33190
33270
  }
@@ -33200,6 +33280,7 @@ function sessionHistory(r, messages, note) {
33200
33280
  var hermes = {
33201
33281
  id: "hermes",
33202
33282
  name: "Hermes Agent",
33283
+ version: 3,
33203
33284
  paths: async () => (await historyFiles(harnessRoots("hermes", () => [envHome("HERMES_HOME", ".hermes")])(), (p) => p === "state.db" || /^profiles\/[^/]+\/state\.db$/.test(p))).files,
33204
33285
  table: "sessions",
33205
33286
  key: "id",
@@ -33207,7 +33288,7 @@ var hermes = {
33207
33288
  parse(db2, r) {
33208
33289
  const messages = rows(db2, "messages", ["id", "message_uid", "role", "content", "timestamp", "tool_call_id", "tool_calls", "tool_name", "_compressed_summary"], ["session_id", r.id], "id").map((m) => {
33209
33290
  if (m._compressed_summary) return recordEvent(m, text(m.message_uid) || nativeText(m.id), "Context summary", seconds(m.timestamp), m.content);
33210
- return conversationMessage({ role: m.role, content: parsedContent(m.content), timestamp: seconds(m.timestamp), tool_call_id: m.tool_call_id, toolCalls: optionalJSON(m.tool_calls), toolName: m.tool_name }, text(m.message_uid) || nativeText(m.id));
33291
+ return conversationMessage({ role: m.role, content: hermesContent(m.content), timestamp: seconds(m.timestamp), tool_call_id: m.tool_call_id, toolCalls: optionalJSON(m.tool_calls), toolName: m.tool_name }, text(m.message_uid) || nativeText(m.id));
33211
33292
  });
33212
33293
  const h3 = sessionHistory({ ...r, created_at: seconds(r.started_at), updated_at: seconds(r.last_activity_at), provider: r.billing_provider }, messages, "Hermes saved message rows, including retained summaries. Compression/reset parent links are not subagent ancestry. Session usage aggregates are not used as message times.");
33213
33294
  if (r.source === "subagent") h3.parent = text(r.parent_session_id) || void 0;
@@ -33324,21 +33405,21 @@ var crush = {
33324
33405
  key: "id",
33325
33406
  fields: ["id", "title", "created_at", "updated_at", "cost"],
33326
33407
  paths: async () => {
33327
- const override = process.env.SESSIONGRAPH_CRUSH_HISTORY_DIR;
33408
+ const override = sourcePath("crush") || process.env.SESSIONGRAPH_CRUSH_HISTORY_DIR;
33328
33409
  if (override) return (await historyFiles([override], (p) => p.endsWith("crush.db"))).files;
33329
33410
  const registry = join22(process.env.CRUSH_GLOBAL_DATA || dataPath("crush"), "projects.json");
33330
33411
  try {
33331
33412
  const stat6 = await lstat6(registry);
33332
33413
  if (!stat6.isFile() || stat6.size > 2e6) throw new Error("Unsupported Crush registry.");
33333
33414
  const raw = JSON.parse(await readFile4(registry, "utf8"));
33334
- const paths = [];
33415
+ const paths2 = [];
33335
33416
  for (const p of Array.isArray(raw.projects) ? raw.projects.slice(0, 2e4) : []) {
33336
33417
  if (!isAbsolute5(text(p.path)) || !text(p.data_dir)) continue;
33337
33418
  const path = join22(isAbsolute5(p.data_dir) ? p.data_dir : join22(p.path, p.data_dir), "crush.db");
33338
- paths.push(path);
33419
+ paths2.push(path);
33339
33420
  crushDirectories.set(path, p.path);
33340
33421
  }
33341
- return existingDatabases(paths);
33422
+ return existingDatabases(paths2);
33342
33423
  } catch (e10) {
33343
33424
  if (e10.code === "ENOENT") return [];
33344
33425
  throw e10;
@@ -33748,10 +33829,13 @@ function normalizeViewState(value) {
33748
33829
  function visibleSessions(sessions) {
33749
33830
  const owners = /* @__PURE__ */ new Map();
33750
33831
  for (const session of sessions) {
33751
- if (session.source !== "t3-code" || session.coverage?.history !== "complete" || !session.activity?.userMessages) continue;
33752
- for (const id2 of session.linkedSessionIDs || []) owners.set(id2, [...owners.get(id2) || [], session.id]);
33832
+ if (session.source !== "t3-code") continue;
33833
+ for (const id2 of new Set(session.linkedSessionIDs || [])) owners.set(id2, [...owners.get(id2) || [], session]);
33753
33834
  }
33754
- const unique = new Map([...owners].flatMap(([native, ids]) => ids.length === 1 ? [[native, ids[0]]] : []));
33835
+ const unique = new Map([...owners].flatMap(([native, claims]) => {
33836
+ const owner = claims[0];
33837
+ return claims.length === 1 && ["complete", "partial"].includes(owner.coverage?.history || "") && owner.activity?.userMessages ? [[native, owner.id]] : [];
33838
+ }));
33755
33839
  return sessions.filter((session) => !unique.has(session.id)).map((session) => ({
33756
33840
  ...session,
33757
33841
  parentID: session.parentID ? unique.get(session.parentID) || session.parentID : void 0,
@@ -33759,6 +33843,46 @@ function visibleSessions(sessions) {
33759
33843
  }));
33760
33844
  }
33761
33845
 
33846
+ // server/library-query.ts
33847
+ import { createHash as createHash4 } from "node:crypto";
33848
+
33849
+ // packages/core/src/layout.ts
33850
+ var directoryPath = (directory2) => (/^(?:[a-z]:[\\/]|\\\\)/i.test(directory2) ? directory2.replace(/\\/g, "/") : directory2).replace(/\/+$/, "") || (directory2.startsWith("/") ? "/" : "");
33851
+ var laneKey = (session) => session.directory ? JSON.stringify(["directory", directoryPath(session.directory)]) : JSON.stringify(["project", session.source || "opencode", session.projectID || session.id]);
33852
+
33853
+ // server/library-query.ts
33854
+ var LibraryError = class extends Error {
33855
+ constructor(code, message2, exitCode = 1) {
33856
+ super(message2);
33857
+ this.code = code;
33858
+ this.exitCode = exitCode;
33859
+ }
33860
+ code;
33861
+ exitCode;
33862
+ };
33863
+ function invalid(message2) {
33864
+ throw new LibraryError("INVALID_ARGUMENT", message2, 2);
33865
+ }
33866
+ var fingerprint = (value) => createHash4("sha256").update(JSON.stringify(value)).digest("hex");
33867
+ function pageLimit(value = 50) {
33868
+ if (!Number.isSafeInteger(value) || value < 1 || value > 200) invalid("Limit must be an integer from 1 to 200.");
33869
+ return value;
33870
+ }
33871
+ function pageOffset(cursor, key) {
33872
+ if (!cursor) return 0;
33873
+ let parsed;
33874
+ try {
33875
+ if (cursor.length > 512 || !/^[\w-]+$/.test(cursor)) throw new Error();
33876
+ parsed = JSON.parse(Buffer.from(cursor, "base64url").toString());
33877
+ if (!parsed || !Number.isSafeInteger(parsed.offset) || parsed.offset < 0 || typeof parsed.key !== "string") throw new Error();
33878
+ } catch {
33879
+ return invalid("Invalid cursor. Use nextCursor from the previous response.");
33880
+ }
33881
+ if (parsed.key !== key) throw new LibraryError("STALE_CURSOR", "Saved history or query changed. Restart without --cursor.");
33882
+ return parsed.offset;
33883
+ }
33884
+ var nextCursor = (key, offset) => Buffer.from(JSON.stringify({ key, offset })).toString("base64url");
33885
+
33762
33886
  // server/store.ts
33763
33887
  var SessionGraphStore = class {
33764
33888
  constructor(path = databasePath()) {
@@ -34008,6 +34132,41 @@ var SessionGraphStore = class {
34008
34132
  truncated ||= this.getSession(id2)?.coverage?.history !== "complete";
34009
34133
  return { id: id2, fragments, messages: page.messages.length, nextCursor: page.next, truncated };
34010
34134
  }
34135
+ messages(id2, options = {}) {
34136
+ return this.readSnapshot(id2, (session) => {
34137
+ const key = fingerprint(["messages", id2, session.revision, session.coverage]);
34138
+ const offset = pageOffset(options.cursor, key), limit = pageLimit(options.limit);
34139
+ const rows2 = this.messagePage(id2, offset, limit);
34140
+ let remaining = 64e3, truncated = false;
34141
+ const messages = rows2.messages.map((message2) => {
34142
+ const fragments = message2.fragments.slice(0, 200).map((fragment) => {
34143
+ const text2 = fragment.text.slice(0, remaining);
34144
+ remaining -= text2.length;
34145
+ truncated ||= text2.length < fragment.text.length;
34146
+ return { ...fragment, text: text2, truncated: text2.length < fragment.text.length };
34147
+ });
34148
+ truncated ||= !!message2.partial;
34149
+ return {
34150
+ id: message2.id,
34151
+ time: messageTime(message2.time),
34152
+ role: message2.role,
34153
+ fragments,
34154
+ files: message2.files.slice(0, 200),
34155
+ tools: message2.tools.slice(0, 200),
34156
+ partial: !!message2.partial || message2.fragments.length > 200 || message2.files.length > 200 || message2.tools.length > 200 || fragments.some((f) => f.truncated)
34157
+ };
34158
+ });
34159
+ return {
34160
+ sessionID: id2,
34161
+ revision: session.revision,
34162
+ messages,
34163
+ order: "newest-first",
34164
+ nextCursor: rows2.next ? nextCursor(key, Number(rows2.next)) : null,
34165
+ partial: truncated || messages.some((m) => m.partial) || session.coverage?.history !== "complete",
34166
+ coverage: session.coverage
34167
+ };
34168
+ });
34169
+ }
34011
34170
  detail(id2, cursor) {
34012
34171
  return this.readSnapshot(id2, (session) => {
34013
34172
  const page = this.messagePage(id2, Number(cursor || 0), 120);
@@ -34093,26 +34252,33 @@ import { setImmediate as yieldToIO } from "node:timers/promises";
34093
34252
  var Importer = class {
34094
34253
  constructor(store, adapters2) {
34095
34254
  this.store = store;
34096
- this.adapters = adapters2;
34255
+ this.adapters = adapters2.map((adapter) => withSourcePaths(adapter, () => this.store.setting("sourcePaths") || {}));
34097
34256
  }
34098
34257
  store;
34099
- adapters;
34100
34258
  status = { running: false, discovered: 0, imported: 0, unchanged: 0, failed: 0, errors: [] };
34101
34259
  job;
34260
+ adapters;
34102
34261
  async sources() {
34103
34262
  return Promise.all(this.adapters.map(async (adapter) => ({ id: adapter.id, name: adapter.name, description: adapter.description, capabilities: adapter.capabilities, available: await adapter.detect().catch(() => false), selected: this.store.selected().includes(adapter.id), ...this.store.sourceInfo(adapter.id) })));
34104
34263
  }
34105
34264
  start(ids, automatic = false) {
34265
+ return this.begin(ids, automatic, true);
34266
+ }
34267
+ /** A one-off subset refresh never replaces the saved source selection. */
34268
+ sync(ids) {
34269
+ return this.begin(ids, false, false);
34270
+ }
34271
+ begin(ids, automatic, save) {
34106
34272
  if (this.job) return this.status;
34107
34273
  if (automatic && (!this.store.autoImportEnabled() || !this.store.selected().length)) return this.status;
34108
34274
  if (ids?.some((id2) => !this.adapters.some((a) => a.id === id2))) throw new Error("Unknown session source.");
34109
34275
  if (!this.store.acquireImport()) throw new Error("Another SessionGraph window is importing this library.");
34110
- if (ids) {
34276
+ if (ids && save) {
34111
34277
  this.store.setting("selected", [...new Set(ids)]);
34112
34278
  }
34113
34279
  this.status = { running: true, discovered: 0, imported: 0, unchanged: 0, failed: 0, errors: [] };
34114
34280
  const heartbeat = setInterval(() => this.store.heartbeat(), 5e3);
34115
- this.job = this.run().catch(() => {
34281
+ this.job = this.run(ids || this.store.selected()).catch(() => {
34116
34282
  this.status.failed++;
34117
34283
  this.status.errors.push("Import interrupted. Re-import to resume remaining sessions.");
34118
34284
  }).finally(() => {
@@ -34127,8 +34293,8 @@ var Importer = class {
34127
34293
  async settled() {
34128
34294
  await this.job;
34129
34295
  }
34130
- async run() {
34131
- for (const adapter of this.adapters.filter((a) => this.store.selected().includes(a.id))) {
34296
+ async run(ids) {
34297
+ for (const adapter of this.adapters.filter((a) => ids.includes(a.id))) {
34132
34298
  this.status.source = adapter.id;
34133
34299
  try {
34134
34300
  if (!await adapter.detect()) throw new Error(`${adapter.name} is unavailable. Saved imports remain available.`);
@@ -34185,6 +34351,7 @@ var Importer = class {
34185
34351
  } while (cursor);
34186
34352
  const values = [...messages.values()];
34187
34353
  if (adapter.id === "opencode") values.reverse();
34354
+ if (saved?.activity?.userMessages && values.every((message2) => message2.role === "system")) throw new Error("Source has no readable conversation. Previous imports are retained.");
34188
34355
  this.store.replace(candidate, values, partial, note);
34189
34356
  this.status.imported++;
34190
34357
  } catch (error) {
@@ -34225,6 +34392,7 @@ var HARNESSES = [
34225
34392
  var isHarness = (value) => HARNESSES.some((h3) => h3.id === value);
34226
34393
  var validSessionID = (id2) => /^ses[a-zA-Z0-9_-]+$/.test(id2);
34227
34394
  function resumeArgs(value) {
34395
+ if (typeof value !== "string" && value.nativeResume === false) throw new Error("This saved history requires a context handoff.");
34228
34396
  const source = typeof value === "string" ? "opencode" : value.source || "opencode";
34229
34397
  const id2 = typeof value === "string" ? value : value.nativeID || value.id;
34230
34398
  if (source !== "opencode") {
@@ -34289,7 +34457,7 @@ function launchCommand(binary, args, directory2, platform = process.platform) {
34289
34457
  }
34290
34458
 
34291
34459
  // server/handoff.ts
34292
- import { createHash as createHash4, randomUUID as randomUUID3 } from "node:crypto";
34460
+ import { createHash as createHash5, randomUUID as randomUUID3 } from "node:crypto";
34293
34461
  import { mkdir, writeFile as writeFile2, rename as rename2, rm as rm4 } from "node:fs/promises";
34294
34462
  import { join as join24 } from "node:path";
34295
34463
  function handoffDocument(snapshot2) {
@@ -34356,7 +34524,7 @@ This handoff transfers saved text and file-change evidence, not files, credentia
34356
34524
  }
34357
34525
  async function saveHandoff(snapshot2, directory2) {
34358
34526
  const { text: text2, ...coverage2 } = handoffDocument(snapshot2);
34359
- const digest2 = createHash4("sha256").update(text2).digest("hex");
34527
+ const digest2 = createHash5("sha256").update(text2).digest("hex");
34360
34528
  const root3 = join24(directory2, "handoffs");
34361
34529
  await mkdir(root3, { recursive: true, mode: 448 });
34362
34530
  const path = join24(root3, `${digest2}.md`), temporary = join24(root3, `.${randomUUID3()}.tmp`);
@@ -34396,7 +34564,7 @@ async function prepareLaunch(store, session, target, directory2 = session.direct
34396
34564
  const [binary, terminal] = await Promise.all([harnessExecutable(target), terminalExecutable()]);
34397
34565
  let args;
34398
34566
  const subagent = session.source === "claude-code" && Boolean(session.parentID) && /^[\w-]+\/agent\/[\w-]+$/.test(session.nativeID || "");
34399
- const localHandoff = ["cursor", "gemini", "qwen-code", "pi", "copilot"].includes(session.source || "") && (!session.nativeResume || directory2 !== session.directory);
34567
+ const localHandoff = session.nativeResume === false || ["cursor", "gemini", "qwen-code", "pi", "copilot"].includes(session.source || "") && (!session.nativeResume || directory2 !== session.directory);
34400
34568
  if (target === (session.source || "opencode") && !subagent && !localHandoff) args = resumeArgs(session);
34401
34569
  const mode = args ? "resume" : "handoff";
34402
34570
  if (mode === "handoff" && store.path === ":memory:") throw new Error("Save this library before creating a context handoff.");
@@ -34442,14 +34610,10 @@ async function launchTerminal(session, prepared) {
34442
34610
  }
34443
34611
 
34444
34612
  // server/publishing.ts
34445
- import { createHash as createHash5, randomBytes } from "node:crypto";
34613
+ import { createHash as createHash6, randomBytes } from "node:crypto";
34446
34614
  import { chmod, mkdir as mkdir2, readFile as readFile5, rename as rename3, rm as rm5, writeFile as writeFile3 } from "node:fs/promises";
34447
34615
  import { dirname as dirname10, join as join25 } from "node:path";
34448
34616
 
34449
- // packages/core/src/layout.ts
34450
- var directoryPath = (directory2) => (/^(?:[a-z]:[\\/]|\\\\)/i.test(directory2) ? directory2.replace(/\\/g, "/") : directory2).replace(/\/+$/, "") || (directory2.startsWith("/") ? "/" : "");
34451
- var laneKey = (session) => session.directory ? JSON.stringify(["directory", directoryPath(session.directory)]) : JSON.stringify(["project", session.source || "opencode", session.projectID || session.id]);
34452
-
34453
34617
  // packages/core/src/sources.ts
34454
34618
  var sources = {
34455
34619
  opencode: { name: "OpenCode", icon: "opencode" },
@@ -34622,7 +34786,7 @@ var PublishingError = class extends Error {
34622
34786
  status;
34623
34787
  };
34624
34788
  var SITE = "https://sessiongraph.ai";
34625
- var hash = (value) => createHash5("sha256").update(value).digest("hex");
34789
+ var hash = (value) => createHash6("sha256").update(value).digest("hex");
34626
34790
  var token = () => randomBytes(32).toString("base64url");
34627
34791
  function preparePublicGraph(store, ids, inputSettings) {
34628
34792
  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.");
@@ -34791,7 +34955,7 @@ function library() {
34791
34955
  if (runtime.sessionGraphRuntime?.importer.status.running && runtime.sessionGraphRuntime.generation !== generation) {
34792
34956
  for (const live of runtime.sessionGraphRuntime.importer.adapters) {
34793
34957
  const updated = adapters.find((adapter) => adapter.id === live.id);
34794
- if (updated) Object.assign(live, updated);
34958
+ if (updated) Object.assign(live, withSourcePaths(updated, () => runtime.sessionGraphRuntime.store.setting("sourcePaths") || {}));
34795
34959
  }
34796
34960
  }
34797
34961
  if (runtime.sessionGraphRuntime && runtime.sessionGraphRuntime.generation !== generation && !runtime.sessionGraphRuntime.importer.status.running) {