sessiongraph-app-win32-x64 1.0.13 → 1.0.14

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.
Files changed (28) hide show
  1. package/package.json +2 -2
  2. package/payload/SessionGraph.exe +0 -0
  3. package/payload/resources/server.mjs +636 -323
  4. package/payload/resources/web/assets/external-links-BmBkCsrt.js +1 -0
  5. package/payload/resources/web/assets/index-B1kyvo41.js +175 -0
  6. package/payload/resources/web/assets/index-BLM-0yG6.js +1 -0
  7. package/payload/resources/web/assets/{index-CJb-F0VY.js → index-D4P4hbvc.js} +1 -1
  8. package/payload/resources/web/assets/index-Du0_nVjH.css +1 -0
  9. package/payload/resources/web/assets/{index-HzUuskn3.js → index-Kotmn42s.js} +1 -1
  10. package/payload/resources/web/assets/publishing-CEvQPkO1.css +1 -0
  11. package/payload/resources/web/assets/publishing-D9CqkbeB.js +23 -0
  12. package/payload/resources/web/assets/scene-CTHyYtma.js +139 -0
  13. package/payload/resources/web/assets/share-Cw1E-ED9.js +7 -0
  14. package/payload/resources/web/index.html +2 -2
  15. package/payload/resources/web/sources/NOTICE.txt +4 -4
  16. package/payload/resources/web/assets/external-links-BcKDmn29.js +0 -1
  17. package/payload/resources/web/assets/index-CDA8pT1Q.js +0 -170
  18. package/payload/resources/web/assets/index-DYhIhreE.js +0 -1
  19. package/payload/resources/web/assets/index-cVgPCrFV.css +0 -1
  20. package/payload/resources/web/assets/publishing-CpVLG7_B.js +0 -25
  21. package/payload/resources/web/assets/publishing-VJhUmdPH.css +0 -1
  22. package/payload/resources/web/assets/scene-BkoCsbA8.js +0 -139
  23. package/payload/resources/web/assets/share-CS1dKayZ.js +0 -7
  24. package/payload/resources/web/sources/hindsight.svg +0 -1
  25. package/payload/resources/web/sources/lmstudio.svg +0 -1
  26. package/payload/resources/web/sources/reasonix.svg +0 -1
  27. package/payload/resources/web/sources/trae.svg +0 -1
  28. package/payload/resources/web/sources/warp.svg +0 -1
@@ -2635,7 +2635,7 @@ function databasePath(env = process.env, platform = process.platform, home = hom
2635
2635
  return paths2.find((path) => existsSync(path)) || paths2[0];
2636
2636
  }
2637
2637
 
2638
- // src/playback-tokens.ts
2638
+ // packages/core/src/playback-tokens.ts
2639
2639
  var validTokenCount = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
2640
2640
  function sumRecordedTokens(values) {
2641
2641
  if (!values.length || !values.every(validTokenCount)) return null;
@@ -2856,13 +2856,13 @@ import { createHash as createHash2 } from "node:crypto";
2856
2856
  import { basename as basename2 } from "node:path";
2857
2857
  var digest = (value) => createHash2("sha256").update(JSON.stringify(value)).digest("hex");
2858
2858
  var identity = (source, native) => `${source}:${native}`;
2859
- var project = (source, directory2) => ({ id: identity(source, digest(directory2).slice(0, 24)), name: basename2(directory2) || "Global", directory: directory2, worktrees: [] });
2860
- var blankSession = (source, nativeID, directory2 = "") => ({
2859
+ var project = (source, directory3) => ({ id: identity(source, digest(directory3).slice(0, 24)), name: basename2(directory3) || "Global", directory: directory3, worktrees: [] });
2860
+ var blankSession = (source, nativeID, directory3 = "") => ({
2861
2861
  source,
2862
2862
  nativeID,
2863
2863
  id: identity(source, nativeID),
2864
- projectID: project(source, directory2).id,
2865
- directory: directory2,
2864
+ projectID: project(source, directory3).id,
2865
+ directory: directory3,
2866
2866
  title: "Untitled session",
2867
2867
  created: 0,
2868
2868
  updated: 0,
@@ -2954,9 +2954,9 @@ function boundEventPayloads(message2, budget2) {
2954
2954
  return [];
2955
2955
  }
2956
2956
  const bounded = { ...event };
2957
- for (const key of ["text", "input", "output", "name", "id", "nativeID", "nativeType", "callID", "parentID"]) {
2957
+ for (const key of ["text", "input", "output", "name", "id", "nativeID", "nativeType", "callID", "parentID", "cwd"]) {
2958
2958
  if (bounded[key] === void 0) continue;
2959
- const value = String(bounded[key]), size = key === "text" || key === "output" ? 64e3 : key === "input" ? 32e3 : 512;
2959
+ const value = String(bounded[key]), size = key === "text" || key === "output" ? 64e3 : key === "input" ? 32e3 : key === "cwd" ? 4096 : 512;
2960
2960
  bounded[key] = value.slice(0, Math.max(0, Math.min(remaining, size)));
2961
2961
  remaining -= bounded[key].length;
2962
2962
  if (bounded[key].length < value.length) {
@@ -3004,7 +3004,7 @@ function normalizedEvents(message2, sessionID) {
3004
3004
  }
3005
3005
  const files = message2.files.map((file, i) => eventFor(message2, `file:${i}`, "file_change", file.path, `${file.source} \xB7 ${file.steps} recorded step(s)`, { nativeType: file.source }));
3006
3006
  return [...events, ...files].slice(0, 200).map((event) => {
3007
- const text2 = String(event.text || "").slice(0, 64e3), input = event.input?.slice(0, 32e3), output = event.output?.slice(0, 64e3);
3007
+ const text2 = String(event.text || "").slice(0, 64e3), input = event.input?.slice(0, 32e3), output2 = event.output?.slice(0, 64e3);
3008
3008
  const time4 = messageTime(event.time || 0);
3009
3009
  return {
3010
3010
  ...event,
@@ -3021,12 +3021,167 @@ function normalizedEvents(message2, sessionID) {
3021
3021
  timeSource: time4 ? event.timeSource : "unknown",
3022
3022
  text: text2,
3023
3023
  input,
3024
- output,
3025
- partial: Boolean(event.partial || message2.partial || text2.length < (event.text?.length || 0) || input?.length !== event.input?.length || output?.length !== event.output?.length || events.length + files.length > 200)
3024
+ output: output2,
3025
+ partial: Boolean(event.partial || message2.partial || text2.length < (event.text?.length || 0) || input?.length !== event.input?.length || output2?.length !== event.output?.length || events.length + files.length > 200)
3026
3026
  };
3027
3027
  });
3028
3028
  }
3029
3029
 
3030
+ // server/commit-extraction.ts
3031
+ import { posix, win32 } from "node:path";
3032
+ var COMMIT_EXTRACTOR_VERSION = 1;
3033
+ var object = (v3) => v3 && typeof v3 === "object" && !Array.isArray(v3) ? v3 : {};
3034
+ var string = (v3) => typeof v3 === "string" ? v3 : void 0;
3035
+ var exitCode = (v3) => typeof v3 === "number" && Number.isSafeInteger(v3) ? v3 : void 0;
3036
+ function executionFields(input, metadata2 = {}) {
3037
+ const args = object(input), meta = object(metadata2);
3038
+ return { cwd: string(args.workdir ?? args.cwd ?? args.working_directory ?? meta.cwd), exitCode: exitCode(meta.exitCode ?? meta.exit_code ?? meta.exit) };
3039
+ }
3040
+ function nativeCommit(value) {
3041
+ const v3 = object(value), operation2 = v3.kind === "committed" ? "created" : v3.kind === "amended" ? "amended" : v3.kind === "cherry-picked" ? "cherry-picked" : void 0;
3042
+ return operation2 && typeof v3.sha === "string" && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(v3.sha) ? { sha: v3.sha.toLowerCase(), operation: operation2 } : void 0;
3043
+ }
3044
+ function json2(value) {
3045
+ try {
3046
+ return JSON.parse(value);
3047
+ } catch {
3048
+ return value;
3049
+ }
3050
+ }
3051
+ function absolute(path) {
3052
+ if (!path || /[\0\r\n]/.test(path)) return;
3053
+ return posix.isAbsolute(path) ? posix : win32.isAbsolute(path) && /^[a-z]:[\\/]/i.test(path) ? win32 : void 0;
3054
+ }
3055
+ function directory(path, base) {
3056
+ if (!path || /[\0\r\n$`~]/.test(path)) return;
3057
+ const flavor = absolute(path) || absolute(base);
3058
+ return flavor ? flavor.resolve(base || path, path) : void 0;
3059
+ }
3060
+ function commands(command) {
3061
+ const result = [], words = [];
3062
+ let word = "", active = false, quote = "";
3063
+ const flush = () => {
3064
+ if (active) words.push(word);
3065
+ word = "";
3066
+ active = false;
3067
+ };
3068
+ for (let i = 0; i < command.length; i++) {
3069
+ const c = command[i];
3070
+ if (quote) {
3071
+ if (c === quote) {
3072
+ quote = "";
3073
+ continue;
3074
+ }
3075
+ if (quote === '"' && /[$`\\]/.test(c)) return;
3076
+ word += c;
3077
+ continue;
3078
+ }
3079
+ if (c === '"' || c === "'") {
3080
+ quote = c;
3081
+ active = true;
3082
+ continue;
3083
+ }
3084
+ if (/[|<>$`(){}\\#\0;\n\r*?\[\]]/.test(c)) return;
3085
+ if (c === "&" && command[i + 1] !== "&") return;
3086
+ if (c === "&") {
3087
+ flush();
3088
+ if (!words.length) return;
3089
+ result.push(words.splice(0));
3090
+ i++;
3091
+ } else if (/\s/.test(c)) flush();
3092
+ else {
3093
+ word += c;
3094
+ active = true;
3095
+ }
3096
+ }
3097
+ if (quote) return;
3098
+ flush();
3099
+ if (!words.length && result.length) return;
3100
+ if (words.length) result.push(words);
3101
+ return result;
3102
+ }
3103
+ function invocation(input, cwd2) {
3104
+ const value = json2(input || ""), args = object(value);
3105
+ const command = typeof value === "string" ? value : string(args.command ?? args.cmd);
3106
+ const explicit = string(args.workdir ?? args.cwd ?? args.working_directory);
3107
+ return { command, cwd: explicit !== void 0 ? directory(explicit) : directory(cwd2) };
3108
+ }
3109
+ function operation(words) {
3110
+ const [verb, ...args] = words;
3111
+ if (verb === "commit") {
3112
+ let amend = false;
3113
+ for (let i = 0; i < args.length; i++) {
3114
+ const arg2 = args[i];
3115
+ if (["-m", "--message", "-F", "--file", "--author", "--date", "--fixup", "--squash", "-C", "--reuse-message", "-c", "--reedit-message"].includes(arg2)) {
3116
+ if (++i >= args.length) return;
3117
+ continue;
3118
+ }
3119
+ if (/^--(?:message|file|author|date|fixup|squash|reuse-message|reedit-message)=/.test(arg2) || /^-m.+/.test(arg2)) continue;
3120
+ if (arg2 === "--amend") {
3121
+ amend = true;
3122
+ continue;
3123
+ }
3124
+ if (["-a", "--all", "--no-edit", "--allow-empty", "--allow-empty-message", "-n", "--no-verify", "-s", "--signoff", "-q", "--quiet", "--no-gpg-sign", "--gpg-sign", "-S"].includes(arg2)) continue;
3125
+ return;
3126
+ }
3127
+ return amend ? "amended" : "created";
3128
+ }
3129
+ if (verb === "cherry-pick" && args.length && args.every((arg2) => /^(?:[a-f0-9]{7,64}|-x|--continue)$/i.test(arg2))) return "cherry-picked";
3130
+ }
3131
+ function plan(command, cwd2) {
3132
+ const parts = commands(command);
3133
+ if (!parts?.length) return;
3134
+ let found;
3135
+ for (const part of parts) {
3136
+ const [program, ...args] = part;
3137
+ if (program === "cd" && args.length === 1 && !/^[+-]/.test(args[0]) && !found) {
3138
+ cwd2 = directory(args[0], cwd2);
3139
+ if (!cwd2) return;
3140
+ continue;
3141
+ }
3142
+ if (program !== "git") return;
3143
+ let path = cwd2;
3144
+ while (args[0] === "-C") {
3145
+ args.shift();
3146
+ path = directory(args.shift(), path);
3147
+ if (!path) return;
3148
+ }
3149
+ const op = operation(args);
3150
+ if (op) {
3151
+ if (found || !path) return;
3152
+ found = { operation: op, repositoryPath: path, trailing: false };
3153
+ } else if (!["add", "push"].includes(args[0]) || args.some((arg2) => /^(?:--exec-path|--git-dir|--work-tree|--config-env)/.test(arg2))) return;
3154
+ else if (found) found.trailing = true;
3155
+ }
3156
+ return found;
3157
+ }
3158
+ function output(value) {
3159
+ const parsed = json2(value || "");
3160
+ if (typeof parsed === "string") {
3161
+ const code = parsed.match(/(?:^|\n)Process exited with code (-?\d+)\r?\n/);
3162
+ return { text: parsed, code: code ? Number(code[1]) : void 0 };
3163
+ }
3164
+ if (Array.isArray(parsed)) return { text: parsed.filter((p) => p?.type === "text" && typeof p.text === "string").map((p) => p.text).join("\n") };
3165
+ const obj = object(parsed);
3166
+ return { text: string(obj.stdout) ?? string(obj.output) ?? "", code: exitCode(obj.exit_code ?? obj.exitCode ?? obj.metadata?.exit_code) };
3167
+ }
3168
+ function extractCommit(call, result) {
3169
+ const shell = /^(?:shell|bash|exec_command|shell_command|run_shell_command|terminal|command execution)$/i.test(call.name) || call.nativeType === "command_execution";
3170
+ const input = invocation(call.input, call.cwd ?? result.cwd);
3171
+ const candidate = Boolean(result.gitCommit || shell && /\bgit\b[\s\S]*\b(?:commit|cherry-pick)\b/.test(input.command || ""));
3172
+ if (!candidate) return { candidate: false };
3173
+ if (call.partial || result.partial || !input.command || !shell || ["running", "pending"].includes(result.status || "")) return { candidate };
3174
+ const parsed = plan(input.command, input.cwd);
3175
+ if (!parsed) return { candidate };
3176
+ const recorded = output(result.output), code = result.exitCode ?? recorded.code;
3177
+ if (code !== void 0 && code !== 0 && !parsed.trailing || result.status === "failed" && !parsed.trailing) return { candidate };
3178
+ const summary = [...recorded.text.matchAll(/^\[(?:[^\]\r\n]+ )([a-f0-9]{7,64})\] [^\r\n]*$/gmi)];
3179
+ const native = result.gitCommit;
3180
+ if (native && native.operation !== parsed.operation) return { candidate };
3181
+ const sha = native && native.operation === parsed.operation ? native.sha : summary.length === 1 && (code !== void 0 || ["completed", "failed"].includes(result.status || "")) ? summary[0][1].toLowerCase() : void 0;
3182
+ return { candidate, commit: sha ? { sha, repositoryPath: parsed.repositoryPath, operation: parsed.operation } : void 0 };
3183
+ }
3184
+
3030
3185
  // server/adapters/opencode-events.ts
3031
3186
  function opencodeEvents(raw, message2) {
3032
3187
  const fields2 = { nativeID: message2.id, nativeType: String(raw.type), timeSource: message2.time ? "recorded" : "unknown" };
@@ -3046,7 +3201,7 @@ function opencodeEvents(raw, message2) {
3046
3201
  else if (part.type === "tool") {
3047
3202
  const state2 = part.state || {}, endTime = messageTime(part.time?.completed);
3048
3203
  const status2 = state2.status === "error" ? "failed" : state2.status === "streaming" ? "pending" : ["running", "completed"].includes(state2.status) ? state2.status : "unknown";
3049
- const common = { ...native, callID: part.id, status: status2, endTime };
3204
+ const common = { ...native, callID: part.id, status: status2, endTime, ...executionFields(state2.input, state2.metadata), partial: Boolean(state2.metadata?.truncated) };
3050
3205
  events.push(eventFor(message2, `${id2}:call`, "tool_call", part.name || "Tool call", "", { ...common, ...timing, input: eventText(state2.input) }));
3051
3206
  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) }));
3052
3207
  } else events.push(eventFor(message2, id2, "event", `${part.type || "Unknown"} content`, "Unsupported content.", { ...native, ...timing, partial: true }));
@@ -3076,7 +3231,7 @@ var opencodeAdapter = {
3076
3231
  return {
3077
3232
  projects: data.projects.map((p) => ({ ...p, id: identity("opencode", p.id) })),
3078
3233
  warnings: data.warnings,
3079
- sessions: data.sessions.map((s) => ({ locator: {}, revision: digest([3, s.updated, s.created, s.directory]), session: {
3234
+ sessions: data.sessions.map((s) => ({ locator: {}, revision: digest([4, s.updated, s.created, s.directory]), session: {
3080
3235
  ...s,
3081
3236
  source: "opencode",
3082
3237
  nativeID: s.id,
@@ -30419,7 +30574,7 @@ async function metadataState(path) {
30419
30574
  }
30420
30575
  }
30421
30576
  async function claudeRevision(path) {
30422
- return digest([6, (await state(path)).signature, (await metadataState(path))?.signature]);
30577
+ return digest([7, (await state(path)).signature, (await metadataState(path))?.signature]);
30423
30578
  }
30424
30579
  async function bytes(path, max) {
30425
30580
  const before = await state(path);
@@ -30474,7 +30629,8 @@ async function claudeTranscript(path, revision2) {
30474
30629
  }
30475
30630
  }
30476
30631
  if (await claudeRevision(path) !== revision2) throw new Error("Claude transcript changed during import; import again.");
30477
- const { size, modified } = await state(path), transcript = { entries: entries2, times, partial, size, modified };
30632
+ const byID = new Map(entries2.filter((row) => typeof row.uuid === "string").map((row) => [String(row.uuid), row]));
30633
+ const { size, modified } = await state(path), transcript = { entries: entries2, times, byID, partial, size, modified };
30478
30634
  cached = { path, revision: revision2, transcript };
30479
30635
  return transcript;
30480
30636
  }
@@ -30519,7 +30675,7 @@ function expandHistory(buffer, maxOutputLength) {
30519
30675
  }
30520
30676
 
30521
30677
  // server/adapters/local-files.ts
30522
- var object = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
30678
+ var object2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
30523
30679
  var text = (value) => typeof value === "string" ? value : "";
30524
30680
  var time = (value) => {
30525
30681
  const n = typeof value === "number" ? value : typeof value === "string" ? /^\d{13}$/.test(value) ? Number(value) : Date.parse(value) : 0;
@@ -30575,7 +30731,7 @@ async function historyFiles(roots2, match2) {
30575
30731
  if (limited) warnings.push("History discovery reached its file, directory, or depth limit.");
30576
30732
  return { files: [...new Set(files)].sort(), warnings };
30577
30733
  }
30578
- function json2(value) {
30734
+ function json3(value) {
30579
30735
  return JSON.parse(value);
30580
30736
  }
30581
30737
  function jsonLines(value) {
@@ -30586,7 +30742,7 @@ function jsonLines(value) {
30586
30742
  if (rows2.length >= MAX_RECORDS) throw new Error("History exceeds the 50,000-record limit.");
30587
30743
  if (line.length > 2e6) throw new Error("History contains a record larger than 2 MB.");
30588
30744
  try {
30589
- const row = json2(line);
30745
+ const row = json3(line);
30590
30746
  if (!row || typeof row !== "object" || Array.isArray(row)) partial = true;
30591
30747
  else rows2.push(row);
30592
30748
  } catch {
@@ -30714,7 +30870,7 @@ function conversationMessage(raw, fallbackID) {
30714
30870
  const message2 = blankMessage(text(raw.id) || fallbackID, time(raw.timestamp ?? raw.ts), role);
30715
30871
  let content = raw.content;
30716
30872
  if (Array.isArray(content)) content = content.map((part) => {
30717
- const p = object(part);
30873
+ const p = object2(part);
30718
30874
  return p.type === "toolCall" ? { ...p, type: "tool_use", input: p.arguments } : p.type === "reasoning" ? { ...p, type: "thinking", thinking: p.text } : p;
30719
30875
  });
30720
30876
  if (raw.role === "thinking") content = [{ type: "thinking", thinking: raw.content }];
@@ -30735,7 +30891,7 @@ function conversationMessage(raw, fallbackID) {
30735
30891
  else if (event.kind === "reasoning") addText(message2, event.text, "Assistant");
30736
30892
  }
30737
30893
  for (const call of Array.isArray(raw.toolCalls) ? raw.toolCalls : []) {
30738
- const f = object(call.function);
30894
+ const f = object2(call.function);
30739
30895
  if (!text(f.name)) continue;
30740
30896
  message2.tools.push(f.name);
30741
30897
  message2.events.push(eventFor(message2, `call:${text(call.id) || message2.events.length}`, "tool_call", f.name, "", { callID: text(call.id) || void 0, input: eventText(f.arguments), status: "unknown" }));
@@ -30749,7 +30905,7 @@ function googleMessage(raw, fallbackID) {
30749
30905
  const parts = Array.isArray(raw.content) ? raw.content : raw.content != null ? [raw.content] : [];
30750
30906
  const content = parts.map((part) => {
30751
30907
  if (typeof part === "string") return { type: "text", text: part };
30752
- const p = object(part);
30908
+ const p = object2(part);
30753
30909
  if (typeof p.text === "string") return p.thought ? { type: "thinking", thinking: p.text } : { type: "text", text: p.text };
30754
30910
  if (p.functionCall) return { type: "tool_use", ...p.functionCall, input: p.functionCall.args };
30755
30911
  if (p.functionResponse) return { type: "tool_result", tool_use_id: p.functionResponse.id || raw.toolCallId, name: p.functionResponse.name, content: p.functionResponse.response, is_error: p.functionResponse.response?.error != null };
@@ -30763,7 +30919,7 @@ function successfulEdits(messages, editNames) {
30763
30919
  if (event.kind === "tool_call" && event.callID) {
30764
30920
  let input = {};
30765
30921
  try {
30766
- input = object(JSON.parse(event.input || "{}"));
30922
+ input = object2(JSON.parse(event.input || "{}"));
30767
30923
  } catch {
30768
30924
  }
30769
30925
  calls.set(event.callID, { name: event.name, input });
@@ -30853,7 +31009,7 @@ var piAdapter = localFileAdapter({
30853
31009
  var nativeText = (v3) => typeof v3 === "number" && Number.isSafeInteger(v3) ? String(v3) : text(v3);
30854
31010
  var seconds = (v3) => typeof v3 === "number" && Number.isFinite(v3) && v3 > 0 ? v3 * 1e3 : time(v3);
30855
31011
  var fileID = (path) => basename4(path).replace(/\.jsonl(?:\..*)?$|\.json$/, "");
30856
- var sidecar2 = (files, path) => object(files.has(path) ? json2(files.get(path)) : void 0);
31012
+ var sidecar2 = (files, path) => object2(files.has(path) ? json3(files.get(path)) : void 0);
30857
31013
  var roles = ["user", "assistant", "system", "tool", "toolResult", "model"];
30858
31014
  function message(raw, id2, timestamp) {
30859
31015
  if (!roles.includes(raw.role)) return;
@@ -30874,7 +31030,7 @@ function envelopeHistory(path, value) {
30874
31030
  const header = rows2.find((r) => r.type === "session" || r.type === "session_start" || r.type === "session_startup") || {};
30875
31031
  const nativeID = [...nativeIDs][0] || text(header.id || header.sessionId) || fileID(path);
30876
31032
  const messages = rows2.flatMap((r, i) => {
30877
- const body2 = object(r.message), role = body2.role || r.role || (["user", "assistant", "system"].includes(r.type) ? r.type : void 0);
31033
+ const body2 = object2(r.message), role = body2.role || r.role || (["user", "assistant", "system"].includes(r.type) ? r.type : void 0);
30878
31034
  const m = message({ ...body2, id: text(r.uuid || r.id) || body2.id, role, content: body2.content ?? r.content ?? r.text }, `record:${i}`, r.timestamp ?? body2.timestamp);
30879
31035
  return m ? [m] : [];
30880
31036
  });
@@ -30890,7 +31046,7 @@ function envelopeHistory(path, value) {
30890
31046
  };
30891
31047
  }
30892
31048
  function ampHistory(path, files) {
30893
- const raw = object(json2(files.get(path)));
31049
+ const raw = object2(json3(files.get(path)));
30894
31050
  if (!text(raw.id) || !Array.isArray(raw.messages)) throw new Error("Unsupported Amp thread.");
30895
31051
  const messages = raw.messages.flatMap((m, i) => {
30896
31052
  const result = message(m, nativeText(m.messageId) || `message:${i}`, m.timestamp ?? m.usage?.timestamp);
@@ -30899,14 +31055,14 @@ function ampHistory(path, files) {
30899
31055
  return { nativeID: raw.id, messages, partial: true, session: { created: time(raw.created), title: text(raw.title), directory: text(raw.cwd) }, note: "Amp local/exported thread messages. Usage-ledger ranges are not message timestamps. Export-only and missing content remain partial." };
30900
31056
  }
30901
31057
  function jcodeHistory(path, files) {
30902
- const raw = object(json2(files.get(path)));
31058
+ const raw = object2(json3(files.get(path)));
30903
31059
  if (!text(raw.id) || !Array.isArray(raw.messages)) throw new Error("Unsupported Jcode session.");
30904
31060
  const journal = path.replace(/\.json$/, ".journal.jsonl");
30905
31061
  const appended = files.has(journal) ? jsonLines(files.get(journal)) : { rows: [], partial: false };
30906
31062
  const records = [...raw.messages];
30907
31063
  for (const row of appended.rows) {
30908
31064
  if (Array.isArray(row.append_messages)) records.push(...row.append_messages);
30909
- if (row.meta) Object.assign(raw, object(row.meta));
31065
+ if (row.meta) Object.assign(raw, object2(row.meta));
30910
31066
  }
30911
31067
  const seen = /* @__PURE__ */ new Set();
30912
31068
  const messages = records.flatMap((r, i) => {
@@ -30919,7 +31075,7 @@ function jcodeHistory(path, files) {
30919
31075
  return { nativeID: raw.id, messages, partial: appended.partial, session: { title: text(raw.title), directory: text(raw.working_dir), created: time(raw.created_at), model: text(raw.model) || "Unknown model", provider: text(raw.provider_key) }, note: "Jcode session snapshot and append journal; replayed native message IDs count once. Absent message times remain unknown." };
30920
31076
  }
30921
31077
  function codebuffHistory(path, files, free) {
30922
- const records = json2(files.get(path));
31078
+ const records = json3(files.get(path));
30923
31079
  if (!Array.isArray(records)) throw new Error("Unsupported Codebuff chat.");
30924
31080
  const isFree = records.some((m) => text(m.metadata?.runState?.sessionState?.mainAgentState?.agentType).startsWith("base2-free"));
30925
31081
  if (isFree !== free) return;
@@ -30932,8 +31088,8 @@ function codebuffHistory(path, files, free) {
30932
31088
  return { nativeID: `${project2}/${chat}`, messages, partial: true, note: "Codebuff/Freebuff persisted chat messages. Freebuff requires a recorded base2-free root-agent marker. Shared storage is attributed once; token counts are not estimated from text." };
30933
31089
  }
30934
31090
  function vibeHistory(path, files) {
30935
- const raw = object(json2(files.get(path))), legacy = basename4(path) !== "meta.json";
30936
- const meta = legacy ? object(raw.metadata) : raw;
31091
+ const raw = object2(json3(files.get(path))), legacy = basename4(path) !== "meta.json";
31092
+ const meta = legacy ? object2(raw.metadata) : raw;
30937
31093
  const transcript = join6(dirname2(path), "messages.jsonl");
30938
31094
  const parsed = files.has(transcript) ? jsonLines(files.get(transcript)) : { rows: [], partial: false };
30939
31095
  const records = legacy ? raw.messages : parsed.rows;
@@ -30960,7 +31116,7 @@ function acpHistory(path, value) {
30960
31116
  }
30961
31117
  };
30962
31118
  for (const [i, row] of rows2.entries()) {
30963
- const p = object(row.params), u2 = object(p.update), kind = text(u2.sessionUpdate);
31119
+ const p = object2(row.params), u2 = object2(p.update), kind = text(u2.sessionUpdate);
30964
31120
  if (text(p.sessionId)) ids.add(p.sessionId);
30965
31121
  const timestamp = time(p._meta?.agentTimestampMs) || time(row.timestamp);
30966
31122
  const role = kind === "user_message_chunk" ? "user" : kind === "agent_message_chunk" ? "assistant" : "";
@@ -30986,7 +31142,7 @@ function dshHistory(value) {
30986
31142
  if (!text(header?.id)) throw new Error("Unsupported DeepSeek Harness session.");
30987
31143
  const messages = rows2.flatMap((r, i) => {
30988
31144
  if (!["user/message", "assistant/message", "tool/message"].includes(r.type)) return [];
30989
- const body2 = object(r.data?.message);
31145
+ const body2 = object2(r.data?.message);
30990
31146
  const m = message({ ...body2, role: body2.role || r.type.split("/")[0] }, text(body2.id) || `record:${i}`, r.time);
30991
31147
  return m ? [m] : [];
30992
31148
  });
@@ -31038,11 +31194,11 @@ function withSqliteSnapshot(path, read3, expected, pinned = false) {
31038
31194
  if (copy?.revision !== revision2) {
31039
31195
  close(path);
31040
31196
  while (copies.size >= 2) close(copies.keys().next().value);
31041
- const directory2 = mkdtempSync(join7(tmpdir(), "sessiongraph-history-"));
31197
+ const directory3 = mkdtempSync(join7(tmpdir(), "sessiongraph-history-"));
31042
31198
  let db2;
31043
31199
  try {
31044
- chmodSync(directory2, 448);
31045
- const destination = join7(directory2, "history.db");
31200
+ chmodSync(directory3, 448);
31201
+ const destination = join7(directory3, "history.db");
31046
31202
  for (const suffix of ["", "-wal"]) {
31047
31203
  try {
31048
31204
  copyFileSync(path + suffix, destination + suffix, constants4.COPYFILE_FICLONE);
@@ -31055,13 +31211,13 @@ function withSqliteSnapshot(path, read3, expected, pinned = false) {
31055
31211
  if (sqliteRevision(path) !== revision2) throw new SqliteSnapshotChangedError("History database changed while copying; import again.");
31056
31212
  db2 = new DatabaseSync(destination, { readOnly: true, enableDoubleQuotedStringLiterals: false, allowExtension: false });
31057
31213
  db2.exec("PRAGMA query_only=ON; PRAGMA trusted_schema=OFF; PRAGMA busy_timeout=1000; BEGIN;");
31058
- copy = { revision: revision2, directory: directory2, db: db2 };
31214
+ copy = { revision: revision2, directory: directory3, db: db2 };
31059
31215
  copies.set(path, copy);
31060
31216
  } catch (error) {
31061
31217
  try {
31062
31218
  db2?.close();
31063
31219
  } finally {
31064
- rmSync2(directory2, { recursive: true, force: true });
31220
+ rmSync2(directory3, { recursive: true, force: true });
31065
31221
  }
31066
31222
  throw error;
31067
31223
  }
@@ -31270,7 +31426,7 @@ function combineAdapters(parts) {
31270
31426
 
31271
31427
  // server/adapters/claude.ts
31272
31428
  var root = () => join8(sourcePath("claude-code") || process.env.CLAUDE_CONFIG_DIR || join8(homedir4(), ".claude"), "projects");
31273
- function claudeMessages(rows2, candidate, times) {
31429
+ function claudeMessages(rows2, candidate, times, entries2) {
31274
31430
  const calls = /* @__PURE__ */ new Map();
31275
31431
  return rows2.map((row) => {
31276
31432
  const raw = row.message;
@@ -31295,7 +31451,18 @@ function claudeMessages(rows2, candidate, times) {
31295
31451
  }
31296
31452
  }
31297
31453
  }
31298
- msg.events = blockEvents(msg, raw?.content).map((event) => ({ ...event, parentID: row.parent_tool_use_id || void 0 }));
31454
+ const entry = entries2?.get(row.uuid), structured = entry?.tool_use_result ?? entry?.toolUseResult;
31455
+ const results = Array.isArray(raw?.content) ? raw.content.filter((p) => p.type === "tool_result") : [];
31456
+ msg.events = blockEvents(msg, raw?.content).map((event) => {
31457
+ const result = event.kind === "tool_result" && results.length === 1 ? structured : void 0;
31458
+ return {
31459
+ ...event,
31460
+ parentID: row.parent_tool_use_id || void 0,
31461
+ ...executionFields({}, { ...result, cwd: entry?.cwd }),
31462
+ gitCommit: nativeCommit(result?.gitOperation?.commit),
31463
+ partial: Boolean(event.partial || result?.interrupted || result?.backgroundTaskId || result?.backgroundedByUser || result?.timedOutAfterMs || entry?.sessionId && entry.sessionId !== (candidate.locator.parent || candidate.session.nativeID))
31464
+ };
31465
+ });
31299
31466
  if (!msg.events.length) msg.events = [eventFor(msg, "event", raw?.subtype === "compact_boundary" ? "compaction" : "event", raw?.subtype || `${row.type} event`, eventText(raw), { nativeType: raw?.subtype || row.type, partial: true })];
31300
31467
  return msg;
31301
31468
  });
@@ -31396,7 +31563,7 @@ var sdkClaudeAdapter = {
31396
31563
  const options = { dir: candidate.locator.dir || void 0, offset: start, limit: count + 1, sessionStore: claudeTranscriptStore(transcript, sessionId, candidate.locator.agent) };
31397
31564
  const rows2 = candidate.locator.parent ? await U1t(candidate.locator.parent, candidate.locator.agent, options) : await P1t(candidate.session.nativeID, options);
31398
31565
  const more = rows2.length > count;
31399
- const messages = claudeMessages(rows2.slice(0, count), candidate, transcript.times).slice(offset - start);
31566
+ const messages = claudeMessages(rows2.slice(0, count), candidate, transcript.times, transcript.byID).slice(offset - start);
31400
31567
  if (!offset && !messages.length && transcript.size > 100) throw new Error("SDK returned no readable conversation for this transcript.");
31401
31568
  if (!more && await claudeRevision(candidate.locator.path) !== candidate.revision) throw new Error("Session changed during import; import again to capture the latest messages.");
31402
31569
  return { messages, cursor: more ? String(offset + 120) : void 0, partial: transcript.partial, note: `SDK-visible conversation chain from the local CLI/VS Code transcript; pre-compaction text and unsupported message types may be absent. Fork ancestry is unavailable.${transcript.partial ? " Some transcript records or subagent metadata were unreadable." : ""}` };
@@ -31515,7 +31682,7 @@ async function transcriptFiles(root3, max = 2e4, match2 = (name) => name.endsWit
31515
31682
  var root2 = () => sourcePath("codex") || process.env.CODEX_HOME || join10(homedir5(), ".codex");
31516
31683
  var revision = async (path) => {
31517
31684
  const s = await stat2(path);
31518
- return digest([9, s.mtimeMs, s.size]);
31685
+ return digest([10, s.mtimeMs, s.size]);
31519
31686
  };
31520
31687
  function changedPaths(value) {
31521
31688
  if (!value || typeof value !== "object") return [];
@@ -31553,6 +31720,7 @@ async function sessionNames() {
31553
31720
  function codexRecord(raw, offset, candidate) {
31554
31721
  const p = raw.payload;
31555
31722
  if (!p || typeof p !== "object") return;
31723
+ if (raw.type === "session_meta" || raw.type === "turn_context") candidate.locator.executionCwd = typeof p.cwd === "string" ? p.cwd : "";
31556
31724
  if (raw.type === "turn_context" && typeof p.model === "string") candidate.session.model = p.model;
31557
31725
  if (raw.type === "event_msg" && p.type === "item_completed" && ["FileChange", "fileChange"].includes(p.item?.type)) {
31558
31726
  const msg2 = blankMessage(`event:${p.item.id || raw.ordinal || offset}`, p.completed_at_ms || Date.parse(raw.timestamp) || 0, "tool");
@@ -31584,7 +31752,14 @@ function codexRecord(raw, offset, candidate) {
31584
31752
  }
31585
31753
  const role = p.role === "user" ? "user" : p.role === "assistant" ? "assistant" : p.type === "message" ? "system" : "tool";
31586
31754
  const msg = blankMessage(`item:${raw.ordinal ?? offset}`, Date.parse(raw.timestamp) || 0, role);
31587
- const fields2 = { nativeID: p.id, nativeType: p.type, callID: p.call_id };
31755
+ let input = p.arguments ?? p.input;
31756
+ if (typeof input === "string") {
31757
+ try {
31758
+ input = JSON.parse(input);
31759
+ } catch {
31760
+ }
31761
+ }
31762
+ const fields2 = { nativeID: p.id, nativeType: p.type, callID: p.call_id, ...executionFields(input, { cwd: candidate.locator.executionCwd }) };
31588
31763
  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" })];
31589
31764
  if (p.type === "message") {
31590
31765
  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");
@@ -31659,6 +31834,7 @@ var codexAdapter = {
31659
31834
  })).values()], warnings };
31660
31835
  },
31661
31836
  async read(candidate, cursor) {
31837
+ if (!cursor) candidate.locator.executionCwd = "";
31662
31838
  const page = await readJSONL(candidate.locator.path, Number(cursor || 0));
31663
31839
  if (page.cursor === void 0 && await revision(candidate.locator.path) !== candidate.revision) throw new Error("Session changed during import; import again to capture the latest messages.");
31664
31840
  return { messages: page.rows.flatMap((r) => {
@@ -31677,7 +31853,8 @@ var PAGE = 100;
31677
31853
  var MAX_THREADS = 2e4;
31678
31854
  var MAX_ITEM_JSON = 256e3;
31679
31855
  var providerSource = { codex: "codex", claudeAgent: "claude-code", opencode: "opencode" };
31680
- var string = (value) => typeof value === "string" ? value : "";
31856
+ var openCodeEditTools = /* @__PURE__ */ new Set(["patch", "apply_patch", "edit", "write", "multiedit"]);
31857
+ var string2 = (value) => typeof value === "string" ? value : "";
31681
31858
  function parsedObject(value) {
31682
31859
  if (typeof value !== "string") return;
31683
31860
  try {
@@ -31692,7 +31869,7 @@ function time2(value) {
31692
31869
  return Number.isFinite(parsed) && parsed > 0 && parsed <= 864e13 ? parsed : 0;
31693
31870
  }
31694
31871
  function status(value) {
31695
- return ["pending", "running", "completed", "failed"].includes(string(value)) ? value : "unknown";
31872
+ return ["pending", "running", "completed", "failed"].includes(string2(value)) ? value : "unknown";
31696
31873
  }
31697
31874
  async function databasePath2() {
31698
31875
  const root3 = sourcePath("t3-code") || process.env.SESSIONGRAPH_T3_CODE_HISTORY_DIR || process.env.T3CODE_HOME || join11(homedir6(), ".t3");
@@ -31721,7 +31898,7 @@ function projectRoots(db2, ids) {
31721
31898
  for (const batch of batches([...new Set(ids.filter(Boolean))])) {
31722
31899
  const placeholders = batch.map(() => "?").join(",");
31723
31900
  for (const row of db2.prepare(`SELECT project_id, substr(workspace_root,1,4096) AS workspace_root FROM projection_projects WHERE deleted_at IS NULL AND project_id IN (${placeholders})`).all(...batch))
31724
- roots2.set(string(row.project_id), string(row.workspace_root));
31901
+ roots2.set(string2(row.project_id), string2(row.workspace_root));
31725
31902
  }
31726
31903
  return roots2;
31727
31904
  }
@@ -31731,7 +31908,7 @@ function aggregates(db2, table, ids) {
31731
31908
  for (const batch of batches(ids)) {
31732
31909
  const placeholders = batch.map(() => "?").join(",");
31733
31910
  for (const row of db2.prepare(`SELECT thread_id, COUNT(*) AS n, MAX(updated_at) AS latest FROM ${table} WHERE thread_id IN (${placeholders}) GROUP BY thread_id`).all(...batch))
31734
- result.set(string(row.thread_id), [Number(row.n), string(row.latest)]);
31911
+ result.set(string2(row.thread_id), [Number(row.n), string2(row.latest)]);
31735
31912
  }
31736
31913
  return result;
31737
31914
  }
@@ -31745,10 +31922,10 @@ function linkedSessions(db2, ids) {
31745
31922
  CASE WHEN json_valid(payload_json) THEN json_extract(payload_json,'$.nativeThreadRef.strength') END AS strength,
31746
31923
  CASE WHEN json_valid(payload_json) THEN json_extract(payload_json,'$.nativeThreadRef.driver') END AS driver
31747
31924
  FROM orchestration_v2_projection_provider_threads WHERE thread_id IN (${placeholders})`).all(...batch)) {
31748
- const source = providerSource[string(row.provider)];
31749
- const nativeID = string(row.native_id);
31925
+ const source = providerSource[string2(row.provider)];
31926
+ const nativeID = string2(row.native_id);
31750
31927
  if (!source || row.strength !== "strong" || row.driver && row.driver !== row.provider || !nativeID || nativeID.length > 512) continue;
31751
- const id2 = string(row.thread_id);
31928
+ const id2 = string2(row.thread_id);
31752
31929
  links.set(id2, [.../* @__PURE__ */ new Set([...links.get(id2) || [], identity(source, nativeID)])]);
31753
31930
  }
31754
31931
  }
@@ -31763,8 +31940,8 @@ function discoverV2(db2, path, databaseRevision) {
31763
31940
  CASE WHEN json_valid(payload_json) THEN json_extract(payload_json,'$.lineage.relationshipToParent') END AS relationship,
31764
31941
  json_valid(payload_json) AS valid_payload
31765
31942
  FROM orchestration_v2_projection_threads WHERE deleted_at IS NULL ORDER BY created_at, thread_id LIMIT ?`).all(MAX_THREADS + 1);
31766
- const selected = rows2.slice(0, MAX_THREADS), ids = selected.map((row) => string(row.thread_id));
31767
- const roots2 = projectRoots(db2, selected.map((row) => string(row.project_id)));
31943
+ const selected = rows2.slice(0, MAX_THREADS), ids = selected.map((row) => string2(row.thread_id));
31944
+ const roots2 = projectRoots(db2, selected.map((row) => string2(row.project_id)));
31768
31945
  const counts = aggregates(db2, "orchestration_v2_projection_messages", ids);
31769
31946
  const items = aggregates(db2, "orchestration_v2_projection_turn_items", ids);
31770
31947
  const links = linkedSessions(db2, ids);
@@ -31772,28 +31949,28 @@ function discoverV2(db2, path, databaseRevision) {
31772
31949
  if (rows2.length > MAX_THREADS) warnings.push(`T3 Code discovery is limited to ${MAX_THREADS.toLocaleString()} threads.`);
31773
31950
  let unreadableMetadata = 0;
31774
31951
  for (const row of selected) {
31775
- const nativeID = string(row.thread_id), created = time2(row.created_at);
31952
+ const nativeID = string2(row.thread_id), created = time2(row.created_at);
31776
31953
  if (!nativeID || nativeID.length > 512 || !created) continue;
31777
31954
  if (!row.valid_payload) unreadableMetadata++;
31778
- const directory2 = string(row.worktree_path) || roots2.get(string(row.project_id)) || "";
31779
- const p = project(SOURCE, directory2);
31955
+ const directory3 = string2(row.worktree_path) || roots2.get(string2(row.project_id)) || "";
31956
+ const p = project(SOURCE, directory3);
31780
31957
  projects.set(p.id, p);
31781
- const session = blankSession(SOURCE, nativeID, directory2);
31782
- const parent2 = string(row.parent_thread_id);
31958
+ const session = blankSession(SOURCE, nativeID, directory3);
31959
+ const parent2 = string2(row.parent_thread_id);
31783
31960
  session.parentID = row.relationship === "subagent" && parent2 ? identity(SOURCE, parent2) : void 0;
31784
31961
  session.forkID = row.relationship === "fork" && parent2 ? identity(SOURCE, parent2) : void 0;
31785
31962
  Object.assign(session, {
31786
- title: string(row.title) || "T3 Code thread",
31963
+ title: string2(row.title) || "T3 Code thread",
31787
31964
  projectID: p.id,
31788
31965
  created,
31789
31966
  updated: time2(row.updated_at) || created,
31790
31967
  archived: Boolean(row.archived_at),
31791
- model: string(row.model) || "Unknown model",
31792
- provider: string(row.default_provider),
31968
+ model: string2(row.model) || "Unknown model",
31969
+ provider: string2(row.default_provider),
31793
31970
  agent: "T3 Code",
31794
31971
  linkedSessionIDs: links.get(nativeID) || []
31795
31972
  });
31796
- const revision2 = digest([row.updated_at, counts.get(nativeID), items.get(nativeID), links.get(nativeID)]);
31973
+ const revision2 = digest([3, row.updated_at, counts.get(nativeID), items.get(nativeID), links.get(nativeID)]);
31797
31974
  sessions.push({ session, revision: revision2, locator: { path, databaseRevision, threadID: nativeID, format: "v2", metadataPartial: row.valid_payload ? "" : "1" } });
31798
31975
  }
31799
31976
  if (unreadableMetadata) warnings.push(`${unreadableMetadata} T3 Code threads had unreadable metadata; model or lineage may be unavailable.`);
@@ -31806,23 +31983,23 @@ function discoverV1(db2, path, databaseRevision) {
31806
31983
  CASE WHEN json_valid(model_selection_json) THEN substr(json_extract(model_selection_json,'$.model'),1,200) END AS model
31807
31984
  FROM projection_threads WHERE deleted_at IS NULL ORDER BY created_at, thread_id LIMIT ?`).all(MAX_THREADS + 1);
31808
31985
  const selected = rows2.slice(0, MAX_THREADS);
31809
- const roots2 = projectRoots(db2, selected.map((row) => string(row.project_id)));
31810
- const counts = aggregates(db2, "projection_thread_messages", selected.map((row) => string(row.thread_id)));
31986
+ const roots2 = projectRoots(db2, selected.map((row) => string2(row.project_id)));
31987
+ const counts = aggregates(db2, "projection_thread_messages", selected.map((row) => string2(row.thread_id)));
31811
31988
  const sessions = [], projects = /* @__PURE__ */ new Map();
31812
31989
  for (const row of selected) {
31813
- const nativeID = string(row.thread_id), created = time2(row.created_at);
31990
+ const nativeID = string2(row.thread_id), created = time2(row.created_at);
31814
31991
  if (!nativeID || nativeID.length > 512 || !created) continue;
31815
- const directory2 = string(row.worktree_path) || roots2.get(string(row.project_id)) || "";
31816
- const p = project(SOURCE, directory2);
31992
+ const directory3 = string2(row.worktree_path) || roots2.get(string2(row.project_id)) || "";
31993
+ const p = project(SOURCE, directory3);
31817
31994
  projects.set(p.id, p);
31818
- const session = blankSession(SOURCE, nativeID, directory2);
31995
+ const session = blankSession(SOURCE, nativeID, directory3);
31819
31996
  Object.assign(session, {
31820
- title: string(row.title) || "T3 Code thread",
31997
+ title: string2(row.title) || "T3 Code thread",
31821
31998
  projectID: p.id,
31822
31999
  created,
31823
32000
  updated: time2(row.updated_at) || created,
31824
32001
  archived: Boolean(row.archived_at),
31825
- model: string(row.model) || "Unknown model",
32002
+ model: string2(row.model) || "Unknown model",
31826
32003
  agent: "T3 Code"
31827
32004
  });
31828
32005
  sessions.push({ session, revision: digest([row.updated_at, counts.get(nativeID)]), locator: { path, databaseRevision, threadID: nativeID, format: "v1" } });
@@ -31831,15 +32008,15 @@ function discoverV1(db2, path, databaseRevision) {
31831
32008
  if (rows2.length > MAX_THREADS) warnings.push(`T3 Code discovery is limited to ${MAX_THREADS.toLocaleString()} threads.`);
31832
32009
  return { sessions, projects: [...projects.values()], warnings };
31833
32010
  }
31834
- function v2Message(row, directory2) {
31835
- const parsed = parsedObject(row.payload_json), item = parsed || {}, type = string(row.type), id2 = string(row.turn_item_id);
32011
+ function v2Message(row, directory3) {
32012
+ const parsed = parsedObject(row.payload_json), item = parsed || {}, type = string2(row.type), id2 = string2(row.turn_item_id);
31836
32013
  const role = type === "user_message" ? "user" : type === "assistant_message" ? "assistant" : type === "reasoning" ? "assistant" : "tool";
31837
32014
  const message2 = blankMessage(`item:${id2}`, time2(item.startedAt || item.createdAt), role);
31838
- const recorded = Boolean(message2.time), name = string(item.title || item.toolName) || type.replaceAll("_", " ");
32015
+ const recorded = Boolean(message2.time), name = string2(item.title || item.toolName) || type.replaceAll("_", " ");
31839
32016
  const fields2 = {
31840
32017
  nativeID: id2,
31841
32018
  nativeType: type,
31842
- parentID: string(item.parentItemId) || void 0,
32019
+ parentID: string2(item.parentItemId) || void 0,
31843
32020
  status: status(row.status),
31844
32021
  endTime: time2(item.completedAt) || null,
31845
32022
  timeSource: recorded ? "recorded" : "unknown"
@@ -31850,34 +32027,42 @@ function v2Message(row, directory2) {
31850
32027
  return message2;
31851
32028
  }
31852
32029
  if (type === "user_message" || type === "assistant_message") {
31853
- const body2 = string(item.text);
32030
+ const body2 = string2(item.text);
31854
32031
  if (body2) addText(message2, body2, role === "user" ? "You" : "Assistant");
31855
32032
  message2.events = [{ ...messageEvent(message2, body2, id2), ...fields2 }];
31856
32033
  if (Array.isArray(item.attachments) && item.attachments.length) message2.partial = true;
31857
32034
  return message2;
31858
32035
  }
31859
32036
  if (type === "reasoning") {
31860
- message2.events = [eventFor(message2, id2, "reasoning", "Recorded reasoning", string(item.text), fields2)];
32037
+ message2.events = [eventFor(message2, id2, "reasoning", "Recorded reasoning", string2(item.text), fields2)];
31861
32038
  return message2;
31862
32039
  }
31863
32040
  if (type === "file_change") {
31864
- const file = string(item.fileName), completed = status(row.status) === "completed";
31865
- if (file && completed) message2.files.push({ path: isAbsolute2(file) ? file : join11(directory2, file), source: "file change", steps: 1 });
32041
+ const file = string2(item.fileName), completed = status(row.status) === "completed";
32042
+ const native = item.nativeItemRef;
32043
+ if (native?.driver === "opencode" && openCodeEditTools.has(file.toLowerCase())) {
32044
+ message2.tools.push(file);
32045
+ const kind2 = completed || fields2.status === "failed" ? "tool_result" : "tool_call";
32046
+ message2.events = [eventFor(message2, id2, kind2, file, "", { ...fields2, callID: string2(native.nativeId) || void 0 })];
32047
+ return message2;
32048
+ }
32049
+ if (file && completed) message2.files.push({ path: isAbsolute2(file) ? file : join11(directory3, file), source: "file change", steps: 1 });
31866
32050
  message2.events = [eventFor(message2, id2, "file_change", file || name, "", fields2)];
31867
32051
  return message2;
31868
32052
  }
31869
32053
  if (["command_execution", "dynamic_tool", "file_search", "web_search"].includes(type)) {
31870
32054
  const input = eventText(item.input ?? item.pattern ?? item.patterns, 32e3);
31871
- const output = eventText(item.output ?? item.results, 64e3);
32055
+ const output2 = eventText(item.output ?? item.results, 64e3);
31872
32056
  const kind2 = fields2.status === "completed" || fields2.status === "failed" ? "tool_result" : "tool_call";
31873
32057
  message2.tools.push(name);
31874
32058
  if (input) addText(message2, input, "Tool");
31875
- if (output) addText(message2, output, "Tool");
31876
- message2.events = [eventFor(message2, id2, kind2, name, "", { ...fields2, input, output })];
32059
+ if (output2) addText(message2, output2, "Tool");
32060
+ const native = item.nativeItemRef;
32061
+ message2.events = [eventFor(message2, id2, kind2, name, "", { ...fields2, input, output: output2, ...executionFields(parsedObject(item.input) || item.input, item), callID: string2(native?.nativeId) || void 0 })];
31877
32062
  return message2;
31878
32063
  }
31879
32064
  const kind = type === "compaction" ? "compaction" : type === "error" ? "error" : "event";
31880
- message2.events = [eventFor(message2, id2, kind, name, string(item.text), fields2)];
32065
+ message2.events = [eventFor(message2, id2, kind, name, string2(item.text), fields2)];
31881
32066
  return message2;
31882
32067
  }
31883
32068
  function readV2(db2, candidate, cursor) {
@@ -31910,9 +32095,9 @@ function readV1(db2, candidate, cursor) {
31910
32095
  const messages = rows2.slice(0, PAGE).map((row) => {
31911
32096
  const role = row.role === "user" ? "user" : row.role === "assistant" ? "assistant" : "system";
31912
32097
  const message2 = blankMessage(`message:${row.message_id}`, time2(row.created_at), role);
31913
- const body2 = string(row.text);
32098
+ const body2 = string2(row.text);
31914
32099
  if (body2) addText(message2, body2, role === "user" ? "You" : "Assistant");
31915
- message2.events = [{ ...messageEvent(message2, body2), nativeID: string(row.message_id), nativeType: "legacy-message" }];
32100
+ message2.events = [{ ...messageEvent(message2, body2), nativeID: string2(row.message_id), nativeType: "legacy-message" }];
31916
32101
  message2.partial = row.text == null;
31917
32102
  return message2;
31918
32103
  });
@@ -32069,11 +32254,11 @@ function withStore(path, read3) {
32069
32254
  throw error;
32070
32255
  }
32071
32256
  });
32072
- const before = stats(), directory2 = mkdtempSync2(join12(tmpdir2(), "sessiongraph-cursor-"));
32257
+ const before = stats(), directory3 = mkdtempSync2(join12(tmpdir2(), "sessiongraph-cursor-"));
32073
32258
  let db2;
32074
32259
  try {
32075
- chmodSync2(directory2, 448);
32076
- const copy = join12(directory2, "store.db");
32260
+ chmodSync2(directory3, 448);
32261
+ const copy = join12(directory3, "store.db");
32077
32262
  files.forEach((file, index) => {
32078
32263
  if (before[index]) {
32079
32264
  const target = index ? `${copy}-wal` : copy;
@@ -32089,7 +32274,7 @@ function withStore(path, read3) {
32089
32274
  try {
32090
32275
  db2?.close();
32091
32276
  } finally {
32092
- rmSync3(directory2, { recursive: true, force: true });
32277
+ rmSync3(directory3, { recursive: true, force: true });
32093
32278
  }
32094
32279
  }
32095
32280
  }
@@ -32162,12 +32347,12 @@ function readCursorStore(path) {
32162
32347
  bytes2 += data.length;
32163
32348
  try {
32164
32349
  if (item.leaf) {
32165
- const json4 = data[0] === 123 ? data : fields(data).find((v3) => v3.field === 4)?.data;
32166
- if (!json4) {
32350
+ const json5 = data[0] === 123 ? data : fields(data).find((v3) => v3.field === 4)?.data;
32351
+ if (!json5) {
32167
32352
  partial = true;
32168
32353
  continue;
32169
32354
  }
32170
- const raw = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(json4));
32355
+ const raw = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(json5));
32171
32356
  const msg = cursorMessage(raw, `blob:${item.id}:${ordinal++}`);
32172
32357
  if (!msg) {
32173
32358
  partial = true;
@@ -32217,9 +32402,9 @@ var MAX_BUBBLE = 8e6;
32217
32402
  var MAX_MESSAGES = 5e4;
32218
32403
  var MAX_BYTES4 = 64e6;
32219
32404
  function decode(value) {
32220
- return object(JSON.parse(typeof value === "string" ? value : value instanceof Uint8Array ? Buffer.from(value).toString("utf8") : "{}"));
32405
+ return object2(JSON.parse(typeof value === "string" ? value : value instanceof Uint8Array ? Buffer.from(value).toString("utf8") : "{}"));
32221
32406
  }
32222
- function directory(raw) {
32407
+ function directory2(raw) {
32223
32408
  const value = text(raw.workspaceIdentifier?.uri?.path) || text(raw.workspaceIdentifier?.uri) || text(raw.cwd);
32224
32409
  try {
32225
32410
  return value.startsWith("file:") ? fileURLToPath(value) : isAbsolute3(value) ? value : "";
@@ -32246,7 +32431,7 @@ function discoverComposers(path, workspace = "") {
32246
32431
  if (!nativeID || row.key !== `composerData:${nativeID}`) throw new Error("Composer identity mismatch.");
32247
32432
  const headers = Array.isArray(data.fullConversationHeadersOnly) ? data.fullConversationHeadersOnly : Array.isArray(data.conversation) ? data.conversation : [];
32248
32433
  if (!headers.length) continue;
32249
- const session = blankSession("cursor", nativeID, directory(data) || workspace);
32434
+ const session = blankSession("cursor", nativeID, directory2(data) || workspace);
32250
32435
  session.created = cursorTime(data.createdAt);
32251
32436
  if (!session.created) continue;
32252
32437
  session.updated = cursorTime(data.lastUpdatedAt) || session.created;
@@ -32297,7 +32482,7 @@ function readComposer(candidate) {
32297
32482
  const id2 = text(header.bubbleId);
32298
32483
  const stored = id2 ? get.get(`bubbleId:${nativeID}:${id2}`, MAX_BUBBLE) : void 0;
32299
32484
  if (stored) bytes2 += typeof stored.value === "string" ? Buffer.byteLength(stored.value) : stored.value.byteLength;
32300
- const raw = stored ? { ...header, ...decode(stored.value) } : { ...header, ...object(data.conversationMap?.[id2]) };
32485
+ const raw = stored ? { ...header, ...decode(stored.value) } : { ...header, ...object2(data.conversationMap?.[id2]) };
32301
32486
  if (![1, 2].includes(raw.type)) {
32302
32487
  partial = true;
32303
32488
  continue;
@@ -32343,7 +32528,7 @@ async function stamp(path) {
32343
32528
  async function snapshot(locator) {
32344
32529
  return digest(await Promise.all([stamp(locator.path), locator.kind === "transcript" ? null : stamp(`${locator.path}-wal`), locator.meta ? stamp(locator.meta) : null]));
32345
32530
  }
32346
- async function json3(path) {
32531
+ async function json4(path) {
32347
32532
  const s = await fileStats(path);
32348
32533
  if (!s) return {};
32349
32534
  if (s.size > 128e3) throw new Error("Cursor metadata exceeds the 128 KB limit.");
@@ -32373,7 +32558,7 @@ async function workspacePaths(root3, warnings) {
32373
32558
  const database = join13(storage, entry.name, "state.vscdb");
32374
32559
  stores.set(database, "");
32375
32560
  try {
32376
- const info = await json3(join13(storage, entry.name, "workspace.json"));
32561
+ const info = await json4(join13(storage, entry.name, "workspace.json"));
32377
32562
  if (typeof info.folder === "string" && info.folder.startsWith("file:")) {
32378
32563
  const path = cwd(fileURLToPath2(info.folder));
32379
32564
  if (path) stores.set(database, path);
@@ -32433,7 +32618,7 @@ function createCursorAdapter(options = {}) {
32433
32618
  return matches.length === 1 ? matches[0] : "";
32434
32619
  };
32435
32620
  let unreadable = 0, legacy = 0, scanned = 0;
32436
- const add = async (path, id2, kind, directory2, parent2 = "", workspaceHash = "") => {
32621
+ const add = async (path, id2, kind, directory3, parent2 = "", workspaceHash = "") => {
32437
32622
  if (!validID(id2) || ++scanned > LIMIT) return;
32438
32623
  try {
32439
32624
  const stats = await fileStats(path);
@@ -32442,11 +32627,11 @@ function createCursorAdapter(options = {}) {
32442
32627
  const locator = { path, kind };
32443
32628
  if (kind !== "transcript") locator.meta = join13(path, "..", "meta.json");
32444
32629
  const before = await snapshot(locator);
32445
- const extra2 = locator.meta ? await json3(locator.meta) : {};
32630
+ const extra2 = locator.meta ? await json4(locator.meta) : {};
32446
32631
  const meta = kind === "transcript" ? {} : cursorStoreMetadata(path);
32447
32632
  if (meta.agentId && meta.agentId !== id2) throw new Error("Cursor native identity mismatch.");
32448
32633
  if (kind !== "transcript" && !meta.latestRootBlobId) return;
32449
- const session = blankSession("cursor", native, cwd(meta.cwd) || cwd(extra2.cwd) || directory2);
32634
+ const session = blankSession("cursor", native, cwd(meta.cwd) || cwd(extra2.cwd) || directory3);
32450
32635
  session.agent = kind === "cli" ? "Cursor Agent" : kind === "acp" ? "Cursor ACP" : parent2 ? "Cursor subagent" : "Cursor IDE";
32451
32636
  if (parent2) session.parentID = identity("cursor", parent2);
32452
32637
  session.title = typeof meta.name === "string" && meta.name.trim() ? meta.name : typeof extra2.title === "string" && extra2.title.trim() ? extra2.title : "Cursor session";
@@ -32503,15 +32688,15 @@ function createCursorAdapter(options = {}) {
32503
32688
  const projects = join13(root3(), "projects");
32504
32689
  for (const dir of await entries(projects, warnings)) {
32505
32690
  if (!dir.isDirectory() || scanned >= LIMIT) continue;
32506
- const transcripts = join13(projects, dir.name, "agent-transcripts"), directory2 = match2(dir.name, slug);
32691
+ const transcripts = join13(projects, dir.name, "agent-transcripts"), directory3 = match2(dir.name, slug);
32507
32692
  for (const entry of await entries(transcripts, warnings)) {
32508
32693
  if (scanned >= LIMIT) break;
32509
- if (entry.isFile() && entry.name.endsWith(".jsonl")) await add(join13(transcripts, entry.name), entry.name.slice(0, -6), "transcript", directory2);
32694
+ if (entry.isFile() && entry.name.endsWith(".jsonl")) await add(join13(transcripts, entry.name), entry.name.slice(0, -6), "transcript", directory3);
32510
32695
  else if (entry.isFile() && entry.name.endsWith(".txt")) legacy++;
32511
32696
  else if (entry.isDirectory() && validID(entry.name)) {
32512
- await add(join13(transcripts, entry.name, `${entry.name}.jsonl`), entry.name, "transcript", directory2);
32697
+ await add(join13(transcripts, entry.name, `${entry.name}.jsonl`), entry.name, "transcript", directory3);
32513
32698
  for (const child of await entries(join13(transcripts, entry.name, "subagents"), warnings)) {
32514
- if (child.isFile() && child.name.endsWith(".jsonl")) await add(join13(transcripts, entry.name, "subagents", child.name), child.name.slice(0, -6), "transcript", directory2, entry.name);
32699
+ if (child.isFile() && child.name.endsWith(".jsonl")) await add(join13(transcripts, entry.name, "subagents", child.name), child.name.slice(0, -6), "transcript", directory3, entry.name);
32515
32700
  if (scanned >= LIMIT) break;
32516
32701
  }
32517
32702
  }
@@ -32520,13 +32705,13 @@ function createCursorAdapter(options = {}) {
32520
32705
  const chats = join13(root3(), "chats");
32521
32706
  for (const bucket of await entries(chats, warnings)) {
32522
32707
  if (!bucket.isDirectory() || scanned >= LIMIT) continue;
32523
- const folder = join13(chats, bucket.name), directory2 = match2(bucket.name, hashCwd);
32708
+ const folder = join13(chats, bucket.name), directory3 = match2(bucket.name, hashCwd);
32524
32709
  if (/^[a-f\d]{32}$/i.test(bucket.name) && await fileStats(join13(folder, "store.db"))) {
32525
32710
  const id2 = bucket.name.replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, "$1-$2-$3-$4-$5");
32526
32711
  await add(join13(folder, "store.db"), id2, "cli", "");
32527
32712
  }
32528
32713
  for (const entry of await entries(folder, warnings)) {
32529
- if (entry.isDirectory()) await add(join13(folder, entry.name, "store.db"), entry.name, "cli", directory2, "", bucket.name);
32714
+ if (entry.isDirectory()) await add(join13(folder, entry.name, "store.db"), entry.name, "cli", directory3, "", bucket.name);
32530
32715
  if (scanned >= LIMIT) break;
32531
32716
  }
32532
32717
  }
@@ -32591,7 +32776,7 @@ function projectRootFile(path) {
32591
32776
  return join14(parts.slice(0, parts.lastIndexOf("chats")).join(sep3), ".project_root");
32592
32777
  }
32593
32778
  function geminiConversation(contents, lines) {
32594
- const parsed = lines ? jsonLines(contents) : { rows: [object(json2(contents))], partial: false };
32779
+ const parsed = lines ? jsonLines(contents) : { rows: [object2(json3(contents))], partial: false };
32595
32780
  let metadata2 = {};
32596
32781
  const messages = /* @__PURE__ */ new Map();
32597
32782
  const patch = (p) => {
@@ -32608,9 +32793,9 @@ function geminiConversation(contents, lines) {
32608
32793
  const ids = [...messages.keys()], index = ids.indexOf(row.$rewindTo);
32609
32794
  for (const id2 of index < 0 ? ids : ids.slice(index)) messages.delete(id2);
32610
32795
  } else if (row.$patch) {
32611
- const p = object(row.$patch);
32796
+ const p = object2(row.$patch);
32612
32797
  if (p.id) patch(p);
32613
- for (const update of Array.isArray(p.updates) ? p.updates : []) patch(object(update));
32798
+ for (const update of Array.isArray(p.updates) ? p.updates : []) patch(object2(update));
32614
32799
  for (const id2 of Array.isArray(p.removeIds) ? p.removeIds : []) messages.delete(id2);
32615
32800
  for (const id2 of Array.isArray(p.orderIds) ? p.orderIds : []) {
32616
32801
  const value = messages.get(id2);
@@ -32620,7 +32805,7 @@ function geminiConversation(contents, lines) {
32620
32805
  }
32621
32806
  }
32622
32807
  } else if (row.$set || row.sessionId) {
32623
- const update = row.$set ? object(row.$set) : row;
32808
+ const update = row.$set ? object2(row.$set) : row;
32624
32809
  metadata2 = { ...metadata2, ...update };
32625
32810
  if (Array.isArray(update.messages)) {
32626
32811
  if (row.$set) messages.clear();
@@ -32642,7 +32827,7 @@ var geminiAdapter = localFileAdapter({
32642
32827
  parse(path, files) {
32643
32828
  const { metadata: meta, records, partial } = geminiConversation(files.get(path), path.endsWith(".jsonl"));
32644
32829
  if (!text(meta.sessionId)) throw new Error("Unsupported Gemini history.");
32645
- const directory2 = (files.get(projectRootFile(path)) || "").trim().slice(0, 4096);
32830
+ const directory3 = (files.get(projectRootFile(path)) || "").trim().slice(0, 4096);
32646
32831
  const messages = records.map((raw, index) => {
32647
32832
  const message2 = googleMessage({ id: raw.id, timestamp: raw.timestamp, role: raw.type === "user" ? "user" : raw.type === "gemini" ? "assistant" : "system", content: raw.content }, `record:${index}`);
32648
32833
  for (const [i, thought] of (Array.isArray(raw.thoughts) ? raw.thoughts : []).entries()) message2.events.push(eventFor(message2, `thought:${i}`, "reasoning", text(thought.subject) || "Recorded reasoning", text(thought.description), { time: time(thought.timestamp) || null, timeSource: time(thought.timestamp) ? "recorded" : "unknown" }));
@@ -32651,9 +32836,9 @@ var geminiAdapter = localFileAdapter({
32651
32836
  message2.tools.push(name);
32652
32837
  message2.events.push(eventFor(message2, `call:${id2}`, "tool_call", name, "", { callID: id2, input: eventText(call.args), status: "unknown" }));
32653
32838
  if (call.result != null || ["success", "error", "cancelled"].includes(call.status)) {
32654
- const output = eventText(call.result);
32655
- message2.events.push(eventFor(message2, `result:${id2}`, "tool_result", name, "", { role: "tool", callID: id2, output, nativeType: text(call.status), time: time(call.timestamp) || null, timeSource: time(call.timestamp) ? "recorded" : "unknown", status: call.status === "success" ? "completed" : call.status === "error" ? "failed" : "unknown" }));
32656
- addText(message2, output, "Tool");
32839
+ const output2 = eventText(call.result);
32840
+ message2.events.push(eventFor(message2, `result:${id2}`, "tool_result", name, "", { role: "tool", callID: id2, output: output2, nativeType: text(call.status), time: time(call.timestamp) || null, timeSource: time(call.timestamp) ? "recorded" : "unknown", status: call.status === "success" ? "completed" : call.status === "error" ? "failed" : "unknown" }));
32841
+ addText(message2, output2, "Tool");
32657
32842
  }
32658
32843
  }
32659
32844
  return message2;
@@ -32665,7 +32850,7 @@ var geminiAdapter = localFileAdapter({
32665
32850
  messages,
32666
32851
  parent: parent2,
32667
32852
  partial,
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}`) },
32853
+ session: { directory: directory3, created: time(meta.startTime), title: text(meta.summary), model: text([...records].reverse().find((r) => r.model)?.model) || "Unknown model", provider: "Google", nativeResume: !parent2 && Boolean(directory3) && !sourcePath("gemini") && !process.env.SESSIONGRAPH_GEMINI_HOME && !path.includes(`${sep3}.cache${sep3}`) },
32669
32854
  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."
32670
32855
  };
32671
32856
  }
@@ -32689,7 +32874,7 @@ var qwenAdapter = localFileAdapter({
32689
32874
  const messages = rows2.map((raw, index) => {
32690
32875
  const id2 = text(raw.uuid) || `record:${index}`;
32691
32876
  if (raw.message && !["agent_message", "agent_mention", "notification"].includes(raw.subtype)) {
32692
- const message3 = googleMessage({ id: id2, timestamp: raw.timestamp, role: raw.type === "assistant" ? "assistant" : raw.type === "user" ? "user" : "tool", toolCallId: raw.toolCallResult?.callId, content: object(raw.message).parts }, id2);
32877
+ const message3 = googleMessage({ id: id2, timestamp: raw.timestamp, role: raw.type === "assistant" ? "assistant" : raw.type === "user" ? "user" : "tool", toolCallId: raw.toolCallResult?.callId, content: object2(raw.message).parts }, id2);
32693
32878
  for (const event of message3.events || []) if (event.kind === "tool_result") {
32694
32879
  event.status = raw.toolCallResult?.status === "success" ? "completed" : raw.toolCallResult?.status === "error" ? "failed" : "unknown";
32695
32880
  event.nativeType = text(raw.toolCallResult?.status);
@@ -32727,11 +32912,11 @@ var copilotAdapter = localFileAdapter({
32727
32912
  match: (path) => /(?:^|\/)events\.jsonl$/.test(path),
32728
32913
  parse(path, files) {
32729
32914
  const { rows: rows2, partial } = jsonLines(files.get(path));
32730
- const start = rows2.find((r) => r.type === "session.start"), meta = object(start?.data);
32915
+ const start = rows2.find((r) => r.type === "session.start"), meta = object2(start?.data);
32731
32916
  if (!text(meta.sessionId)) throw new Error("Unsupported Copilot event log.");
32732
32917
  const toolNames = new Map(rows2.filter((r) => r.type === "tool.execution_start").map((r) => [r.data?.toolCallId, text(r.data?.toolName)]));
32733
32918
  const messages = rows2.filter((r) => !r.ephemeral && !["assistant.message_delta", "assistant.reasoning_delta"].includes(r.type)).map((raw, index) => {
32734
- const data = object(raw.data), kind = text(raw.type), human = kind === "user.message" && !data.isAutopilotContinuation && !data.source;
32919
+ const data = object2(raw.data), kind = text(raw.type), human = kind === "user.message" && !data.isAutopilotContinuation && !data.source;
32735
32920
  const message2 = blankMessage(text(raw.id) || `record:${index}`, time(raw.timestamp), human ? "user" : kind === "assistant.message" ? "assistant" : kind.startsWith("tool.") ? "tool" : "system");
32736
32921
  if (["user.message", "assistant.message"].includes(kind)) {
32737
32922
  const content = text(data.content);
@@ -32771,7 +32956,7 @@ var copilotAdapter = localFileAdapter({
32771
32956
 
32772
32957
  // server/adapters/copilot-chat.ts
32773
32958
  import { homedir as homedir11 } from "node:os";
32774
- import { basename as basename6, dirname as dirname4, join as join17, posix, win32 as win322 } from "node:path";
32959
+ import { basename as basename6, dirname as dirname4, join as join17, posix as posix2, win32 as win323 } from "node:path";
32775
32960
  import { fileURLToPath as fileURLToPath3 } from "node:url";
32776
32961
 
32777
32962
  // server/adapters/vscode-chat-log.ts
@@ -32780,7 +32965,7 @@ function vscodeChatLog(content) {
32780
32965
  for (const line of content.split("\n")) {
32781
32966
  if (!line.trim()) continue;
32782
32967
  if (++records > 5e4) throw new Error("Chat log exceeds the 50,000-operation limit.");
32783
- const entry = object(JSON.parse(line));
32968
+ const entry = object2(JSON.parse(line));
32784
32969
  if (entry.kind === 0) {
32785
32970
  if (records !== 1 || !entry.v || typeof entry.v !== "object" || Array.isArray(entry.v)) throw new Error("Invalid chat log initial state.");
32786
32971
  state2 = entry.v;
@@ -32819,14 +33004,14 @@ function vscodeChatLog(content) {
32819
33004
 
32820
33005
  // server/adapters/copilot-chat.ts
32821
33006
  function copilotChatRoots(platform = process.platform, home = homedir11(), env = process.env) {
32822
- const path = platform === "win32" ? win322 : posix;
33007
+ const path = platform === "win32" ? win323 : posix2;
32823
33008
  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");
32824
33009
  const override = sourcePath("copilot-chat") || env.SESSIONGRAPH_COPILOT_CHAT_USER_DATA_DIR;
32825
33010
  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"))];
32826
33011
  return users.flatMap((user) => [path.join(user, "workspaceStorage"), path.join(user, "globalStorage", "emptyWindowChatSessions")]);
32827
33012
  }
32828
33013
  function vscodeChatPath(value) {
32829
- const raw = object(value);
33014
+ const raw = object2(value);
32830
33015
  if (raw.scheme) {
32831
33016
  if (raw.scheme !== "file") return `${text(raw.scheme)}://${text(raw.authority)}${text(raw.path)}`;
32832
33017
  const path = text(raw.path);
@@ -32841,10 +33026,10 @@ function vscodeChatPath(value) {
32841
33026
  return "";
32842
33027
  }
32843
33028
  }
32844
- var markdown = (value) => typeof value === "string" ? value : text(object(value).value);
33029
+ var markdown = (value) => typeof value === "string" ? value : text(object2(value).value);
32845
33030
  var recordedTime = (value) => ({ time: time(value) || null, timeSource: time(value) ? "recorded" : "unknown" });
32846
33031
  function responsePart(message2, value, index) {
32847
- const part = object(value), kind = text(part.kind), id2 = `part:${index}`;
33032
+ const part = object2(value), kind = text(part.kind), id2 = `part:${index}`;
32848
33033
  const fields2 = { nativeType: kind || "markdown", nativeID: text(part.id) || void 0 };
32849
33034
  if (typeof value === "string" || !kind && typeof part.value === "string" || kind === "markdownContent" || kind === "markdownVuln") {
32850
33035
  const content = markdown(kind ? part.content : value);
@@ -32855,19 +33040,19 @@ function responsePart(message2, value, index) {
32855
33040
  message2.events.push(eventFor(message2, id2, "reasoning", "Recorded reasoning", content, { ...fields2, ...recordedTime(part.reasoningStartedAt) }));
32856
33041
  addText(message2, content, "Tool");
32857
33042
  } else if (kind === "toolInvocationSerialized") {
32858
- const data = object(part.toolSpecificData), command = object(data.commandLine), details = object(part.resultDetails);
33043
+ const data = object2(part.toolSpecificData), command = object2(data.commandLine), details = object2(part.resultDetails);
32859
33044
  const name = text(part.toolId) || "Tool", callID = text(part.toolCallId) || void 0;
32860
33045
  const input = eventText(data.rawInput ?? command.userEdited ?? command.toolEdited ?? command.original ?? details.input);
32861
- const denied = part.isConfirmed === false || [0, 5].includes(object(part.isConfirmed).type);
33046
+ const denied = part.isConfirmed === false || [0, 5].includes(object2(part.isConfirmed).type);
32862
33047
  const status2 = denied || part.resultError ? "failed" : part.isComplete === true ? "completed" : "unknown";
32863
33048
  const correlation = { ...fields2, callID, parentID: text(part.subAgentInvocationId) || void 0 };
32864
33049
  message2.events.push(eventFor(message2, `${id2}:call`, "tool_call", name, markdown(part.invocationMessage), { ...correlation, ...recordedTime(part.startedAt), input, status: "unknown" }));
32865
33050
  message2.tools.push(name);
32866
33051
  addText(message2, input, "Tool");
32867
33052
  if (part.isComplete || part.resultError || denied) {
32868
- const output = eventText(part.resultError || (denied ? "Tool invocation was denied or skipped." : details.output ?? part.resultDetails ?? markdown(part.pastTenseMessage)));
32869
- message2.events.push(eventFor(message2, `${id2}:result`, "tool_result", name, markdown(part.pastTenseMessage), { ...correlation, ...recordedTime(part.completedAt), role: "tool", output, status: status2 }));
32870
- addText(message2, output, "Tool");
33053
+ const output2 = eventText(part.resultError || (denied ? "Tool invocation was denied or skipped." : details.output ?? part.resultDetails ?? markdown(part.pastTenseMessage)));
33054
+ message2.events.push(eventFor(message2, `${id2}:result`, "tool_result", name, markdown(part.pastTenseMessage), { ...correlation, ...recordedTime(part.completedAt), role: "tool", output: output2, status: status2 }));
33055
+ addText(message2, output2, "Tool");
32871
33056
  } else message2.partial = true;
32872
33057
  } else {
32873
33058
  message2.events.push(eventFor(message2, id2, "event", kind || "Unsupported chat content", eventText(part), { ...fields2, partial: true }));
@@ -32880,7 +33065,7 @@ function chatMessages(requests) {
32880
33065
  const requestID = text(request.requestId) || `request:${index}`;
32881
33066
  const injected = Boolean(request.isSystemInitiated || request.hiddenFromTranscript || request.requestHiddenFromTranscript);
32882
33067
  const user = blankMessage(requestID, time(request.timestamp), injected ? "system" : "user");
32883
- const content = typeof request.message === "string" ? request.message : text(object(request.message).text);
33068
+ const content = typeof request.message === "string" ? request.message : text(object2(request.message).text);
32884
33069
  user.events = [eventFor(user, "message", injected ? "event" : "message", injected ? "Injected message" : "User message", content, { nativeID: requestID, ...recordedTime(request.timestamp) })];
32885
33070
  addText(user, content, injected ? "Tool" : "You");
32886
33071
  if (request.variableData?.variables?.length) user.partial = true;
@@ -32923,13 +33108,13 @@ var filesAdapter = localFileAdapter({
32923
33108
  extras: (path) => [...basename6(dirname4(path)) === "chatSessions" ? [join17(dirname4(dirname4(path)), "workspace.json")] : [], ...path.endsWith(".json") ? [`${path}l`] : []],
32924
33109
  parse(path, files) {
32925
33110
  const log = path.endsWith(".jsonl") ? path : `${path}l`;
32926
- const data = files.has(log) ? vscodeChatLog(files.get(log)) : object(JSON.parse(files.get(path)));
33111
+ const data = files.has(log) ? vscodeChatLog(files.get(log)) : object2(JSON.parse(files.get(path)));
32927
33112
  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.");
32928
33113
  if (data.sessionId !== basename6(path).replace(/\.jsonl?$/, "")) throw new Error("VS Code chat identity mismatch.");
32929
33114
  if (!data.requests.length) return;
32930
33115
  if (data.requests.length > 25e3) throw new Error("Chat exceeds the 50,000-message limit.");
32931
33116
  const workspacePath = join17(dirname4(dirname4(path)), "workspace.json");
32932
- const workspace = files.has(workspacePath) ? object(JSON.parse(files.get(workspacePath))) : {};
33117
+ const workspace = files.has(workspacePath) ? object2(JSON.parse(files.get(workspacePath))) : {};
32933
33118
  const messages = chatMessages(data.requests);
32934
33119
  const model = [...data.requests].reverse().find((r) => text(r.modelId));
32935
33120
  return {
@@ -32964,15 +33149,15 @@ function taskAdapter(id2, name, extension, env) {
32964
33149
  match: (path) => /^[^/]+\/api_conversation_history\.json$/.test(path) || id2 === "cline" && /^[^/]+\/[^/]+\.messages\.json$/.test(path),
32965
33150
  extras: (path) => ["history_item.json", "task_metadata.json", "session.json"].map((file) => join18(dirname5(path), file)),
32966
33151
  parse(path, files) {
32967
- const sdk = path.endsWith(".messages.json"), value = json2(files.get(path));
32968
- const records = sdk ? object(value).messages : value;
33152
+ const sdk = path.endsWith(".messages.json"), value = json3(files.get(path));
33153
+ const records = sdk ? object2(value).messages : value;
32969
33154
  if (!Array.isArray(records) || sdk && !text(value.sessionId)) throw new Error("Unsupported task history.");
32970
- const read3 = (name2) => object(files.has(join18(dirname5(path), name2)) ? json2(files.get(join18(dirname5(path), name2))) : void 0);
33155
+ const read3 = (name2) => object2(files.has(join18(dirname5(path), name2)) ? json3(files.get(join18(dirname5(path), name2))) : void 0);
32971
33156
  const history = read3("history_item.json"), info = read3("session.json"), task = read3("task_metadata.json");
32972
33157
  const nativeID = sdk ? value.sessionId : basename7(dirname5(path));
32973
33158
  if (history.id && history.id !== nativeID || info.session_id && info.session_id !== nativeID) throw new Error("Task metadata identity mismatch.");
32974
33159
  const messages = records.map((raw, index) => {
32975
- const row = object(raw), message2 = conversationMessage(row, `record:${index}`);
33160
+ const row = object2(raw), message2 = conversationMessage(row, `record:${index}`);
32976
33161
  if (row.isSummary || row.isTruncationMarker || row.type === "reasoning") {
32977
33162
  message2.role = "system";
32978
33163
  message2.events = [eventFor(message2, "summary", row.type === "reasoning" ? "reasoning" : "compaction", row.type === "reasoning" ? "Recorded reasoning" : "Context checkpoint", eventText(row.summary ?? row.content ?? row.text), { partial: Boolean(row.encrypted_content), nativeType: row.type || "summary" })];
@@ -33008,17 +33193,17 @@ var continueAdapter = localFileAdapter({
33008
33193
  extras: (path) => [join18(dirname5(path), "sessions.json")],
33009
33194
  revisionExtras: false,
33010
33195
  parse(path, files) {
33011
- const value = object(json2(files.get(path)));
33196
+ const value = object2(json3(files.get(path)));
33012
33197
  if (!text(value.sessionId) || !Array.isArray(value.history)) throw new Error("Unsupported Continue session.");
33013
- const indexPath = join18(dirname5(path), "sessions.json"), index = files.has(indexPath) ? json2(files.get(indexPath)) : [];
33014
- const meta = Array.isArray(index) ? object(index.find((r) => r.sessionId === value.sessionId)) : {};
33198
+ const indexPath = join18(dirname5(path), "sessions.json"), index = files.has(indexPath) ? json3(files.get(indexPath)) : [];
33199
+ const meta = Array.isArray(index) ? object2(index.find((r) => r.sessionId === value.sessionId)) : {};
33015
33200
  const messages = value.history.map((item, i) => {
33016
- const row = object(item), raw = object(row.message), message2 = conversationMessage(raw, `record:${i}`);
33201
+ const row = object2(item), raw = object2(row.message), message2 = conversationMessage(raw, `record:${i}`);
33017
33202
  if (row.reasoning?.text) message2.events.push(eventFor(message2, "reasoning", "reasoning", "Recorded reasoning", text(row.reasoning.text), { time: time(row.reasoning.startAt) || null, timeSource: time(row.reasoning.startAt) ? "recorded" : "unknown" }));
33018
33203
  if (row.conversationSummary) message2.events.push(eventFor(message2, "summary", "compaction", "Conversation summary", text(row.conversationSummary)));
33019
33204
  return message2;
33020
33205
  });
33021
- const usage = object(value.usage);
33206
+ const usage = object2(value.usage);
33022
33207
  return {
33023
33208
  nativeID: value.sessionId,
33024
33209
  messages,
@@ -33048,7 +33233,7 @@ var harnessRoots = (id2, defaults) => () => {
33048
33233
  // server/adapters/harness-extra-formats.ts
33049
33234
  import { basename as basename8, dirname as dirname6, join as join20 } from "node:path";
33050
33235
  function kiroHistory(path, files) {
33051
- const header = object(json2(files.get(path)));
33236
+ const header = object2(json3(files.get(path)));
33052
33237
  const ide2 = basename8(path) === "session.json";
33053
33238
  const nativeID = text(header.session_id || header.sessionId || header.id) || (ide2 ? basename8(dirname6(path)) : "");
33054
33239
  if (!nativeID) throw new Error("Unsupported Kiro session header.");
@@ -33057,12 +33242,12 @@ function kiroHistory(path, files) {
33057
33242
  const { rows: rows2 } = jsonLines(files.get(side));
33058
33243
  const messages = rows2.flatMap((r, i) => {
33059
33244
  if (ide2) {
33060
- const p = object(r.payload || r);
33245
+ const p = object2(r.payload || r);
33061
33246
  const role2 = p.type === "human" ? "user" : p.type === "ai" ? "assistant" : p.role || p.type;
33062
33247
  const m3 = message({ ...p, role: role2 }, text(p.id) || `message:${i}`, r.timestamp);
33063
33248
  return m3 ? [m3] : [recordEvent(r, `event:${i}`, text(p.type) || "Kiro event", r.timestamp, p.text)];
33064
33249
  }
33065
- const data = object(r.data), role = r.kind === "Prompt" ? "user" : r.kind === "AssistantMessage" ? "assistant" : r.kind === "ToolResults" ? "tool" : "";
33250
+ const data = object2(r.data), role = r.kind === "Prompt" ? "user" : r.kind === "AssistantMessage" ? "assistant" : r.kind === "ToolResults" ? "tool" : "";
33066
33251
  if (!role) return [];
33067
33252
  const content = Array.isArray(data.content) ? data.content.map((p) => p.kind === "text" ? { type: "text", text: p.data } : { type: "unsupported" }) : void 0;
33068
33253
  const m = message({ role, content }, text(data.message_id) || `message:${i}`, seconds(data.meta?.timestamp));
@@ -33106,7 +33291,7 @@ function muxHistory(path, files) {
33106
33291
  function devinDesktopHistory(path, files) {
33107
33292
  const { rows: rows2 } = jsonLines(files.get(path));
33108
33293
  const normalized = rows2.flatMap((r) => {
33109
- const n = object(r.notification);
33294
+ const n = object2(r.notification);
33110
33295
  return n.sessionUpdate ? [{ params: { sessionId: text(r.sessionId || n.sessionId) || fileID(path).replace(/\.ndjson$/, ""), update: n }, timestamp: n.content?.metadata?.created_at ?? n.metadata?.created_at ?? n.timestamp ?? r.timestamp }] : [];
33111
33296
  });
33112
33297
  const history = acpHistory(path, normalized.map((r) => JSON.stringify(r)).join("\n"));
@@ -33151,7 +33336,7 @@ function museHistory(path, files) {
33151
33336
  if (!meta || ids.size > 1) throw new Error("Unsupported Muse stream.");
33152
33337
  const nativeID = [...ids][0] || basename9(dirname7(path));
33153
33338
  const messages = rows2.flatMap((r, i) => {
33154
- const event = object(r.payload?.event), body2 = object(event.message);
33339
+ const event = object2(r.payload?.event), body2 = object2(event.message);
33155
33340
  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);
33156
33341
  const m = message(body2, nativeText(r.sequence) || `record:${i}`, at2);
33157
33342
  if (m) return [m];
@@ -33168,7 +33353,7 @@ function museHistory(path, files) {
33168
33353
  function junieHistory(path, files) {
33169
33354
  const { rows: rows2 } = jsonLines(files.get(path));
33170
33355
  const messages = rows2.flatMap((r, i) => {
33171
- const e10 = object(r.event?.agentEvent || r.event), kind = text(e10.kind);
33356
+ const e10 = object2(r.event?.agentEvent || r.event), kind = text(e10.kind);
33172
33357
  if (!kind || /State|Snapshot/.test(kind)) return [];
33173
33358
  return [recordEvent(r, text(r.id) || `event:${i}`, kind, r.timestampMs, e10.text ?? e10.prompt ?? e10.message)];
33174
33359
  });
@@ -33176,16 +33361,16 @@ function junieHistory(path, files) {
33176
33361
  return { nativeID: basename9(dirname7(path)), messages, partial: true, note: "Junie recorded agent events. State snapshots and opaque event bodies are omitted; events without an authoritative message role are not counted as user turns." };
33177
33362
  }
33178
33363
  function augmentHistory(path, files) {
33179
- const r = object(json2(files.get(path)));
33364
+ const r = object2(json3(files.get(path)));
33180
33365
  if (!text(r.sessionId) || !Array.isArray(r.chatHistory)) throw new Error("Unsupported Augment session.");
33181
33366
  const messages = r.chatHistory.flatMap((turn, i) => {
33182
- const exchange = object(turn.exchange), id2 = nativeText(turn.sequenceId) || `turn:${i}`;
33367
+ const exchange = object2(turn.exchange), id2 = nativeText(turn.sequenceId) || `turn:${i}`;
33183
33368
  return [recordEvent(turn, id2, turn.completed === true ? "Completed exchange" : "Incomplete exchange", turn.finishedAt, exchange.response_text)];
33184
33369
  });
33185
33370
  return { nativeID: r.sessionId, messages, partial: true, session: { title: text(r.title), created: time(r.created), model: text(r.agentState?.modelId) || "Unknown model" }, note: "Augment saved exchange records. Typed response-node payloads and absent prompts are not reconstructed into conversations." };
33186
33371
  }
33187
33372
  function fxHistory(path, files) {
33188
- const usage = object(json2(files.get(path))), meta = sidecar2(files, join21(dirname7(path), "session.json"));
33373
+ const usage = object2(json3(files.get(path))), meta = sidecar2(files, join21(dirname7(path), "session.json"));
33189
33374
  const id2 = text(usage.session_id) || text(meta.id);
33190
33375
  if (!id2 || !usage.snapshot || meta.id && meta.id !== id2) throw new Error("Unsupported Fx session metadata.");
33191
33376
  return {
@@ -33230,7 +33415,7 @@ var definitions = [
33230
33415
  const value = f.get(p), { rows: rows2 } = jsonLines(value), ids = new Set(rows2.map((r) => text(r.sessionId)).filter(Boolean));
33231
33416
  if (ids.size !== 1) throw new Error("Headless capture needs one explicit session identity.");
33232
33417
  const messages = rows2.flatMap((r, i) => {
33233
- const m = message(object(r.message), text(r.message?.id) || `record:${i}`);
33418
+ const m = message(object2(r.message), text(r.message?.id) || `record:${i}`);
33234
33419
  return m ? [m] : [];
33235
33420
  });
33236
33421
  return { nativeID: [...ids][0], messages, partial: true, note: "Previously captured MiniMax stream JSON only; no command is executed. User input and transient streaming records may be absent." };
@@ -33325,9 +33510,9 @@ var openclaw = {
33325
33510
  parse(db2, r) {
33326
33511
  const events = rows(db2, "transcript_events", ["seq", "event_json", "event_zstd"], ["session_id", r.session_id], "seq");
33327
33512
  const messages = events.flatMap((e10) => {
33328
- const raw = object(sqliteJSON(e10.event_json ?? e10.event_zstd));
33513
+ const raw = object2(sqliteJSON(e10.event_json ?? e10.event_zstd));
33329
33514
  if (raw.type !== "message") return [];
33330
- const m = message(object(raw.message), text(raw.id) || `event:${e10.seq}`, raw.timestamp ?? raw.message?.timestamp);
33515
+ const m = message(object2(raw.message), text(raw.id) || `event:${e10.seq}`, raw.timestamp ?? raw.message?.timestamp);
33331
33516
  return m ? [m] : [];
33332
33517
  });
33333
33518
  return sessionHistory({ ...r, id: r.session_id, provider: r.model_provider }, messages, "OpenClaw authoritative transcript events, including zstd payloads. Database sessions take precedence over migrated JSONL copies. Session rollover and event-parent links are not session ancestry.");
@@ -33344,7 +33529,7 @@ function forkStore(id2, name, defaultPath, desktop) {
33344
33529
  parse(db2, r) {
33345
33530
  if (desktop !== void 0 && text(r.version).startsWith("desktop-") !== desktop) return;
33346
33531
  const messages = rows(db2, "message", ["id", "data", "time_created"], ["session_id", r.id], "time_created").map((m) => {
33347
- const body2 = object(sqliteJSON(m.data));
33532
+ const body2 = object2(sqliteJSON(m.data));
33348
33533
  let content = body2.parts ?? body2.content;
33349
33534
  if (hasTable(db2, "part")) content = rows(db2, "part", ["id", "data"], ["message_id", m.id], "id").map((p) => sqliteJSON(p.data));
33350
33535
  if (Array.isArray(content)) content = content.flatMap((p) => {
@@ -33369,11 +33554,11 @@ var zed = {
33369
33554
  fields: ["id", "summary", "created_at", "updated_at", "data_type", "data", "folder_paths"],
33370
33555
  parse(db2, r) {
33371
33556
  if (!["json", "zstd"].includes(r.data_type)) throw new Error("Unsupported Zed encoding.");
33372
- const body2 = object(sqliteJSON(r.data));
33557
+ const body2 = object2(sqliteJSON(r.data));
33373
33558
  if (body2.imported === true) return;
33374
33559
  if (!Array.isArray(body2.messages)) throw new Error("Unsupported Zed thread.");
33375
33560
  const messages = body2.messages.map((raw, i) => {
33376
- const user = object(raw.User), agent = object(raw.Agent), b = raw.User ? user : agent;
33561
+ const user = object2(raw.User), agent = object2(raw.Agent), b = raw.User ? user : agent;
33377
33562
  if (!raw.User && !raw.Agent) return recordEvent(raw, `message:${i}`, "Context checkpoint", 0, raw.Compaction?.Summary);
33378
33563
  const content = (Array.isArray(b.content) ? b.content : []).map((p) => typeof p.Text === "string" ? { type: "text", text: p.Text } : p.Thinking ? { type: "thinking", thinking: p.Thinking.text } : p.ToolUse ? { type: "tool_use", ...p.ToolUse } : { type: "unsupported" });
33379
33564
  return conversationMessage({ role: raw.User ? "user" : "assistant", content }, text(b.id) || `message:${i}`);
@@ -33391,7 +33576,7 @@ var devin = {
33391
33576
  fields: ["id", "working_directory", "model", "title", "created_at", "last_activity_at"],
33392
33577
  parse(db2, r) {
33393
33578
  const messages = rows(db2, "message_nodes", ["node_id", "chat_message", "created_at"], ["session_id", r.id], "row_id").flatMap((m) => {
33394
- const raw = object(sqliteJSON(m.chat_message)), result = message(raw, nativeText(m.node_id), millisOrSeconds(m.created_at));
33579
+ const raw = object2(sqliteJSON(m.chat_message)), result = message(raw, nativeText(m.node_id), millisOrSeconds(m.created_at));
33395
33580
  return result ? [result] : [recordEvent(raw, nativeText(m.node_id), "Devin message node", millisOrSeconds(m.created_at))];
33396
33581
  });
33397
33582
  return sessionHistory({ ...r, created_at: millisOrSeconds(r.created_at), updated_at: millisOrSeconds(r.last_activity_at) }, messages, "Devin saved message nodes. All retained in-session branches are included; node-parent edges are not session ancestry.");
@@ -33454,9 +33639,9 @@ var octofriend = {
33454
33639
  const row = rows(db2, "llm_irs", ["json"], ["id", item.llm_ir_id], void 0, 1)[0];
33455
33640
  bytes2 += text(row?.json).length;
33456
33641
  if (bytes2 > 32e6) throw new Error("Octofriend session exceeds the snapshot limit.");
33457
- const payload = object(sqliteJSON(row?.json));
33642
+ const payload = object2(sqliteJSON(row?.json));
33458
33643
  if (payload.version !== "octo-llm-ir/v1") throw new Error("Unsupported Octofriend IR version.");
33459
- const ir = object(payload.ir), content = Array.isArray(ir.content) ? ir.content.map((p) => p.type === "text" ? { type: "text", text: p.content } : p) : ir.content;
33644
+ const ir = object2(payload.ir), content = Array.isArray(ir.content) ? ir.content.map((p) => p.type === "text" ? { type: "text", text: p.content } : p) : ir.content;
33460
33645
  const m = message({ ...ir, content, role: ir.role === "tool-output" ? "tool" : ir.role }, nativeText(node.id), node.created_at);
33461
33646
  messages.push(m || recordEvent(ir, nativeText(node.id), text(ir.role), node.created_at));
33462
33647
  }
@@ -33490,13 +33675,13 @@ var kiro = {
33490
33675
  key: "conversation_id",
33491
33676
  fields: ["key", "conversation_id", "value"],
33492
33677
  parse(db2, r) {
33493
- const body2 = object(sqliteJSON(r.value));
33678
+ const body2 = object2(sqliteJSON(r.value));
33494
33679
  if (!Array.isArray(body2.history)) throw new Error("Unsupported Kiro conversation.");
33495
33680
  const messages = body2.history.flatMap((turn, i) => {
33496
- const result = [], input = object(turn.user?.content), output = object(turn.assistant?.Response || turn.assistant?.ToolUse);
33681
+ const result = [], input = object2(turn.user?.content), output2 = object2(turn.assistant?.Response || turn.assistant?.ToolUse);
33497
33682
  if (typeof input.Prompt?.prompt === "string") result.push(conversationMessage({ role: "user", content: input.Prompt.prompt }, `turn:${i}:user`));
33498
33683
  if (input.ToolUseResults) result.push(conversationMessage({ role: "tool", content: input.ToolUseResults }, `turn:${i}:tool`));
33499
- if (typeof output.content === "string") result.push(conversationMessage({ role: "assistant", content: output.content, timestamp: turn.request_metadata?.stream_end_timestamp_ms }, `turn:${i}:assistant`));
33684
+ if (typeof output2.content === "string") result.push(conversationMessage({ role: "assistant", content: output2.content, timestamp: turn.request_metadata?.stream_end_timestamp_ms }, `turn:${i}:assistant`));
33500
33685
  return result;
33501
33686
  });
33502
33687
  const created = body2.history.map((t) => time(t.request_metadata?.request_start_timestamp_ms)).find(Boolean);
@@ -33521,7 +33706,6 @@ var databaseHarnessAdapters = [
33521
33706
  // server/adapters/harness-metadata.ts
33522
33707
  import { basename as basename10 } from "node:path";
33523
33708
  import { fileURLToPath as fileURLToPath4 } from "node:url";
33524
- import { lstat as lstat7 } from "node:fs/promises";
33525
33709
  function protoFields(value) {
33526
33710
  if (value.length > 2e6) throw new Error("Trajectory metadata exceeds 2 MB.");
33527
33711
  const fields2 = /* @__PURE__ */ new Map();
@@ -33568,15 +33752,15 @@ var antigravityDatabaseAdapters = ["antigravity-cli", "antigravity-extension"].m
33568
33752
  const sec = timestamp.get(1), nano = timestamp.get(2);
33569
33753
  const created = typeof sec === "bigint" && sec > 0n && sec < 8640000000000n ? time(Number(sec) * 1e3 + (typeof nano === "bigint" && nano < 1000000000n ? Number(nano) / 1e6 : 0)) : 0;
33570
33754
  const uri = nested(fields2.get(1)).get(1);
33571
- let directory2 = "";
33755
+ let directory3 = "";
33572
33756
  if (uri instanceof Uint8Array) {
33573
33757
  try {
33574
- directory2 = fileURLToPath4(Buffer.from(uri).toString("utf8"));
33758
+ directory3 = fileURLToPath4(Buffer.from(uri).toString("utf8"));
33575
33759
  } catch {
33576
33760
  }
33577
33761
  }
33578
33762
  if (!created) throw new Error("Trajectory creation time is unavailable.");
33579
- return { nativeID: basename10(path, ".db"), messages: [], partial: true, session: { created, directory: directory2 }, note: "Native Antigravity trajectory identity and creation metadata only. Protobuf conversation/step bodies are opaque; no message text, generation-time guesses, or usage-derived turns are imported." };
33763
+ return { nativeID: basename10(path, ".db"), messages: [], partial: true, session: { created, directory: directory3 }, note: "Native Antigravity trajectory identity and creation metadata only. Protobuf conversation/step bodies are opaque; no message text, generation-time guesses, or usage-derived turns are imported." };
33580
33764
  }
33581
33765
  }));
33582
33766
  var antigravityCacheAdapter = localFileAdapter({
@@ -33595,31 +33779,9 @@ var antigravityCacheAdapter = localFileAdapter({
33595
33779
  return { nativeID: [...ids][0], messages: [], partial: true, session: { created, model: text(rows2.find((r) => r.modelId)?.modelId) || "Unknown model" }, note: "Previously synced Antigravity session identity; placement uses earliest recorded usage date. This cache has no conversation bodies. SessionGraph never runs sync or contacts the language server." };
33596
33780
  }
33597
33781
  });
33598
- var usageOnlyAdapters = [
33599
- { id: "reasonix", name: "Reasonix", roots: () => [envHome("REASONIX_STATE_HOME", ".reasonix", "stats"), envHome("REASONIX_HOME", ".reasonix", "stats")], note: "Request statistics lack conversation identities and text. Reasonix transcript import is not yet supported." },
33600
- { id: "trae", name: "Trae / Trae Solo", roots: () => [tokscalePath("trae-cache/sessions")], note: "The Tokscale cache contains account usage, not local conversations." },
33601
- { id: "warp", name: "Warp / Oz", roots: () => [tokscalePath("warp-cache")], note: "The Tokscale cache contains aggregate requests and spend, not local conversations." },
33602
- { id: "lm-studio", name: "LM Studio", roots: () => [envHome("LM_STUDIO_HOME", ".lmstudio", "server-logs")], note: "Server logs contain final-response usage, not retained prompts or responses." },
33603
- { id: "hindsight", name: "Hindsight", roots: () => [envHome("HINDSIGHT_HOME", ".hindsight", "usage")], note: "Synced memory-operation usage is not agent conversation history." }
33604
- ].map((source) => ({
33605
- id: source.id,
33606
- name: source.name,
33607
- description: `Detection only \xB7 ${source.note}`,
33608
- capabilities: { history: false, forks: false, children: false, files: false },
33609
- async detect() {
33610
- for (const p of harnessRoots(source.id, source.roots)()) if ((await lstat7(p).catch(() => void 0))?.isDirectory()) return true;
33611
- return false;
33612
- },
33613
- async discover() {
33614
- return { sessions: [], projects: [], warnings: [source.note] };
33615
- },
33616
- async read() {
33617
- throw new Error(source.note);
33618
- }
33619
- }));
33620
33782
 
33621
33783
  // server/adapters/index.ts
33622
- var extra = [...databaseHarnessAdapters, ...fileHarnessAdapters, antigravityCacheAdapter, ...antigravityDatabaseAdapters, ...usageOnlyAdapters];
33784
+ var extra = [...databaseHarnessAdapters, ...fileHarnessAdapters, antigravityCacheAdapter, ...antigravityDatabaseAdapters];
33623
33785
  var grouped = /* @__PURE__ */ new Map();
33624
33786
  for (const adapter of extra) grouped.set(adapter.id, [...grouped.get(adapter.id) || [], adapter]);
33625
33787
  var adapters = [opencodeAdapter, claudeAdapter, codexAdapter, t3CodeAdapter, cursorAdapter, geminiAdapter, qwenAdapter, piAdapter, copilotAdapter, copilotChatAdapter, clineAdapter, rooAdapter, kiloAdapter, continueAdapter, ...[...grouped.values()].map((parts) => parts.length === 1 ? parts[0] : combineAdapters(parts))];
@@ -33654,6 +33816,160 @@ function validRecord(value, session) {
33654
33816
 
33655
33817
  // server/event-store.ts
33656
33818
  import { randomUUID } from "node:crypto";
33819
+
33820
+ // packages/core/src/commits.ts
33821
+ var abbreviatedSHA = (sha) => sha.length !== 40 && sha.length !== 64;
33822
+
33823
+ // server/library-query.ts
33824
+ import { createHash as createHash4 } from "node:crypto";
33825
+
33826
+ // packages/core/src/layout.ts
33827
+ var directoryPath = (directory3) => (/^(?:[a-z]:[\\/]|\\\\)/i.test(directory3) ? directory3.replace(/\\/g, "/") : directory3).replace(/\/+$/, "") || (directory3.startsWith("/") ? "/" : "");
33828
+ var laneKey = (session) => session.directory ? JSON.stringify(["directory", directoryPath(session.directory)]) : JSON.stringify(["project", session.source || "opencode", session.projectID || session.id]);
33829
+
33830
+ // src/session-links.ts
33831
+ function visibleSessions(sessions) {
33832
+ const owners = /* @__PURE__ */ new Map();
33833
+ for (const session of sessions) {
33834
+ if (session.source !== "t3-code") continue;
33835
+ for (const id2 of new Set(session.linkedSessionIDs || [])) owners.set(id2, [...owners.get(id2) || [], session]);
33836
+ }
33837
+ const unique = new Map([...owners].flatMap(([native, claims]) => {
33838
+ const owner = claims[0];
33839
+ return claims.length === 1 && ["complete", "partial"].includes(owner.coverage?.history || "") && owner.activity?.userMessages ? [[native, owner.id]] : [];
33840
+ }));
33841
+ return sessions.filter((session) => !unique.has(session.id)).map((session) => ({
33842
+ ...session,
33843
+ parentID: session.parentID ? unique.get(session.parentID) || session.parentID : void 0,
33844
+ forkID: session.forkID ? unique.get(session.forkID) || session.forkID : void 0
33845
+ }));
33846
+ }
33847
+
33848
+ // server/library-query.ts
33849
+ var LibraryError = class extends Error {
33850
+ constructor(code, message2, exitCode2 = 1) {
33851
+ super(message2);
33852
+ this.code = code;
33853
+ this.exitCode = exitCode2;
33854
+ }
33855
+ code;
33856
+ exitCode;
33857
+ };
33858
+ function invalid(message2) {
33859
+ throw new LibraryError("INVALID_ARGUMENT", message2, 2);
33860
+ }
33861
+ var fingerprint = (value) => createHash4("sha256").update(JSON.stringify(value)).digest("hex");
33862
+ function pageLimit(value = 50) {
33863
+ if (!Number.isSafeInteger(value) || value < 1 || value > 200) invalid("Limit must be an integer from 1 to 200.");
33864
+ return value;
33865
+ }
33866
+ function pageOffset(cursor, key) {
33867
+ if (!cursor) return 0;
33868
+ let parsed;
33869
+ try {
33870
+ if (cursor.length > 512 || !/^[\w-]+$/.test(cursor)) throw new Error();
33871
+ parsed = JSON.parse(Buffer.from(cursor, "base64url").toString());
33872
+ if (!parsed || !Number.isSafeInteger(parsed.offset) || parsed.offset < 0 || typeof parsed.key !== "string") throw new Error();
33873
+ } catch {
33874
+ return invalid("Invalid cursor. Use nextCursor from the previous response.");
33875
+ }
33876
+ if (parsed.key !== key) throw new LibraryError("STALE_CURSOR", "Saved history or query changed. Restart without --cursor.");
33877
+ return parsed.offset;
33878
+ }
33879
+ var nextCursor = (key, offset) => Buffer.from(JSON.stringify({ key, offset })).toString("base64url");
33880
+
33881
+ // server/commit-store.ts
33882
+ var COMMIT_SCHEMA = `CREATE TABLE IF NOT EXISTS session_commits (
33883
+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
33884
+ sha TEXT NOT NULL, repository_path TEXT NOT NULL, operation TEXT NOT NULL,
33885
+ occurred_at REAL, evidence_event_id TEXT NOT NULL,
33886
+ PRIMARY KEY(session_id,repository_path,sha,operation),
33887
+ FOREIGN KEY(session_id,evidence_event_id) REFERENCES timeline_items(session_id,id) ON DELETE CASCADE);
33888
+ CREATE INDEX IF NOT EXISTS session_commits_time ON session_commits(session_id,occurred_at);`;
33889
+ var supported = /* @__PURE__ */ new Set(["opencode", "t3-code", "codex", "claude-code"]);
33890
+ var pendingCommits = () => ({ version: 0, state: "pending", count: null, note: "Refresh sources to index recorded commit operations." });
33891
+ function writeCommits(db2, session) {
33892
+ db2.prepare("DELETE FROM session_commits WHERE session_id=?").run(session.id);
33893
+ const base = { version: COMMIT_EXTRACTOR_VERSION, indexedAt: Date.now() };
33894
+ if (!supported.has(session.source || "")) return { ...base, state: "unavailable", count: null, note: "Commit attribution is not validated for this source format." };
33895
+ const calls = /* @__PURE__ */ new Map();
33896
+ const results = /* @__PURE__ */ new Map();
33897
+ const rows2 = () => db2.prepare("SELECT data FROM timeline_items WHERE session_id=? AND kind IN ('tool_call','tool_result') ORDER BY ordinal").iterate(session.id);
33898
+ let tools = 0, partial = session.coverage?.history !== "complete" || Boolean(db2.prepare("SELECT partial FROM timeline_coverage WHERE session_id=?").get(session.id)?.partial);
33899
+ for (const row of rows2()) {
33900
+ const item = JSON.parse(String(row.data));
33901
+ tools++;
33902
+ if (item.kind === "tool_result" && item.callID) {
33903
+ const signature = fingerprint([item.output, item.exitCode, item.status, item.gitCommit]);
33904
+ results.set(item.callID, results.has(item.callID) && results.get(item.callID) !== signature ? null : signature);
33905
+ }
33906
+ if (item.kind !== "tool_call" || !item.callID) continue;
33907
+ calls.set(item.callID, calls.has(item.callID) ? null : item);
33908
+ }
33909
+ const completed = /* @__PURE__ */ new Set();
33910
+ const insert = db2.prepare("INSERT OR IGNORE INTO session_commits VALUES (?,?,?,?,?,?)");
33911
+ for (const row of rows2()) {
33912
+ const item = JSON.parse(String(row.data));
33913
+ if (item.kind !== "tool_result") continue;
33914
+ const call = item.input ? item : item.callID ? calls.get(item.callID) : void 0;
33915
+ if (!call || call !== item && call.ordinal >= item.ordinal || item.callID && results.get(item.callID) === null) {
33916
+ partial = true;
33917
+ continue;
33918
+ }
33919
+ if (item.callID) completed.add(item.callID);
33920
+ const extracted = extractCommit(call, item);
33921
+ if (!extracted.candidate) continue;
33922
+ const time4 = item.endTime ?? item.time;
33923
+ if (time4 !== null && time4 < session.created || session.forkID && (time4 === null || time4 <= session.created || call.time === null || call.time < session.created)) {
33924
+ partial = true;
33925
+ continue;
33926
+ }
33927
+ if (!extracted.commit) {
33928
+ partial = true;
33929
+ continue;
33930
+ }
33931
+ const { sha, repositoryPath, operation: operation2 } = extracted.commit;
33932
+ insert.run(session.id, sha, repositoryPath, operation2, time4, item.id);
33933
+ }
33934
+ for (const [id2, call] of calls) if (call && !completed.has(id2) && /\bgit\b[\s\S]*\b(?:commit|cherry-pick)\b/.test(call.input || "")) partial = true;
33935
+ const count = Number(db2.prepare("SELECT count(*) AS n FROM session_commits WHERE session_id=?").get(session.id).n);
33936
+ return {
33937
+ ...base,
33938
+ state: !tools ? "unavailable" : partial ? "partial" : "indexed",
33939
+ count: !tools ? null : count,
33940
+ note: !tools ? "No usable tool executions recorded; commit history is unknown." : `${partial ? "Some execution evidence is missing, ambiguous, inherited, or unsupported. " : ""}Confirmed recorded operations only; absence is not proof that no commits occurred. Paths are execution directories; abbreviated SHAs remain unresolved. Linked provider histories retain their own attribution.`
33941
+ };
33942
+ }
33943
+ function commit(row) {
33944
+ return { sessionID: String(row.session_id), sha: String(row.sha), repositoryPath: String(row.repository_path), operation: row.operation, occurredAt: row.occurred_at === null ? null : Number(row.occurred_at), evidenceEventID: String(row.evidence_event_id) };
33945
+ }
33946
+ function readCommits(db2, session, options = {}) {
33947
+ let coverage2 = session.commits || pendingCommits();
33948
+ if (session.coverage?.note?.startsWith("Latest import failed:")) coverage2 = { ...coverage2, state: coverage2.count === null ? coverage2.state : "partial", note: `${session.coverage.note} ${coverage2.note}` };
33949
+ const revision2 = String(db2.prepare("SELECT revision FROM timeline_coverage WHERE session_id=?").get(session.id)?.revision || "pending");
33950
+ const key = fingerprint(["commits", session.id, revision2, coverage2]), offset = pageOffset(options.cursor, key), limit = pageLimit(options.limit);
33951
+ const total = Number(db2.prepare("SELECT count(*) AS n FROM session_commits WHERE session_id=?").get(session.id).n);
33952
+ const items = db2.prepare("SELECT * FROM session_commits WHERE session_id=? ORDER BY occurred_at IS NULL,occurred_at,repository_path,sha,operation LIMIT ? OFFSET ?").all(session.id, limit, offset).map(commit);
33953
+ return { sessionID: session.id, revision: revision2, coverage: coverage2, items, total, nextCursor: offset + limit < total ? nextCursor(key, offset + limit) : null };
33954
+ }
33955
+ function commitMarkers(db2, session) {
33956
+ const end = Math.max(session.created, session.activity?.lastMessageAt || session.created);
33957
+ return db2.prepare("SELECT * FROM session_commits WHERE session_id=? AND occurred_at>=? AND occurred_at<=? ORDER BY occurred_at,sha LIMIT 2000").all(session.id, session.created, end).map((row, ordinal) => {
33958
+ const value = commit(row);
33959
+ return {
33960
+ id: value.evidenceEventID,
33961
+ kind: "commit",
33962
+ name: `${value.operation} ${value.sha}`,
33963
+ time: value.occurredAt,
33964
+ timeSource: "recorded",
33965
+ ordinal,
33966
+ preview: `${value.repositoryPath}
33967
+ ${abbreviatedSHA(value.sha) ? "Abbreviated SHA \xB7 " : ""}Open recorded execution evidence`
33968
+ };
33969
+ });
33970
+ }
33971
+
33972
+ // server/event-store.ts
33657
33973
  var EVENT_SCHEMA = `CREATE TABLE IF NOT EXISTS timeline_items (
33658
33974
  session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, id TEXT NOT NULL, message_id TEXT NOT NULL,
33659
33975
  ordinal INTEGER NOT NULL, kind TEXT NOT NULL, role TEXT, time REAL, call_id TEXT, name TEXT NOT NULL, preview TEXT NOT NULL, data TEXT NOT NULL,
@@ -33705,7 +34021,8 @@ function readEventMarkers(db2, session) {
33705
34021
  const end = Math.max(session.created, session.activity?.lastMessageAt || session.created);
33706
34022
  const totals = db2.prepare(`SELECT count(*) AS total, count(*) FILTER (WHERE time IS NULL) AS untimed, count(*) FILTER (WHERE time<? OR time>?) AS outside FROM timeline_items WHERE session_id=? AND (${filters.messages})`).get(session.created, end, session.id);
33707
34023
  const rows2 = db2.prepare(`SELECT ${summaryColumns} FROM timeline_items WHERE session_id=? AND (${filters.messages}) AND time>=? AND time<=? ORDER BY time DESC,ordinal DESC`).all(session.id, session.created, end);
33708
- return { sessionID: session.id, ...coverage(db2, session), items: rows2.reverse().map(eventSummary), total: Number(totals.total), untimed: Number(totals.untimed), outsideLifetime: Number(totals.outside), limited: Number(totals.total) - Number(totals.untimed) - Number(totals.outside) > rows2.length };
34024
+ const commits = commitMarkers(db2, session);
34025
+ return { sessionID: session.id, ...coverage(db2, session), commits: session.commits, items: [...rows2.reverse().map(eventSummary), ...commits].sort((a, b) => a.time - b.time || a.ordinal - b.ordinal), total: Number(totals.total), untimed: Number(totals.untimed), outsideLifetime: Number(totals.outside), limited: Number(totals.total) - Number(totals.untimed) - Number(totals.outside) > rows2.length || commits.length === 2e3 };
33709
34026
  }
33710
34027
  function readEvents(db2, session, options = {}) {
33711
34028
  const state2 = coverage(db2, session), filter = options.filter || "all", size = 60;
@@ -33825,64 +34142,6 @@ function normalizeViewState(value) {
33825
34142
  return result;
33826
34143
  }
33827
34144
 
33828
- // src/session-links.ts
33829
- function visibleSessions(sessions) {
33830
- const owners = /* @__PURE__ */ new Map();
33831
- for (const session of sessions) {
33832
- if (session.source !== "t3-code") continue;
33833
- for (const id2 of new Set(session.linkedSessionIDs || [])) owners.set(id2, [...owners.get(id2) || [], session]);
33834
- }
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
- }));
33839
- return sessions.filter((session) => !unique.has(session.id)).map((session) => ({
33840
- ...session,
33841
- parentID: session.parentID ? unique.get(session.parentID) || session.parentID : void 0,
33842
- forkID: session.forkID ? unique.get(session.forkID) || session.forkID : void 0
33843
- }));
33844
- }
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
-
33886
34145
  // server/store.ts
33887
34146
  var SessionGraphStore = class {
33888
34147
  constructor(path = databasePath()) {
@@ -33892,7 +34151,7 @@ var SessionGraphStore = class {
33892
34151
  if (path !== ":memory:") chmodSync3(path, 384);
33893
34152
  this.db.exec("PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;");
33894
34153
  const version = Number(this.db.prepare("PRAGMA user_version").get().user_version);
33895
- if (version > 4) throw new Error("This SessionGraph database requires a newer version of the app.");
34154
+ if (version > 6) throw new Error("This SessionGraph database requires a newer version of the app.");
33896
34155
  this.db.exec(`
33897
34156
  CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT NOT NULL);
33898
34157
  CREATE TABLE IF NOT EXISTS sources (id TEXT PRIMARY KEY, last_import INTEGER, error TEXT);
@@ -33940,6 +34199,35 @@ var SessionGraphStore = class {
33940
34199
  throw error;
33941
34200
  }
33942
34201
  }
34202
+ if (version < 5) {
34203
+ this.db.exec("BEGIN IMMEDIATE");
34204
+ try {
34205
+ this.db.exec(COMMIT_SCHEMA);
34206
+ this.db.prepare("UPDATE sessions SET metadata=json_set(metadata,'$.commits',json(?))").run(JSON.stringify(pendingCommits()));
34207
+ this.db.exec("PRAGMA user_version=5; COMMIT");
34208
+ } catch (error) {
34209
+ this.db.exec("ROLLBACK");
34210
+ throw error;
34211
+ }
34212
+ }
34213
+ if (version < 6) {
34214
+ this.db.exec("BEGIN IMMEDIATE");
34215
+ try {
34216
+ const retired = /* @__PURE__ */ new Set(["reasonix", "trae", "warp", "lm-studio", "hindsight"]);
34217
+ const selected = this.setting("selected");
34218
+ if (selected) this.setting("selected", selected.filter((id2) => !retired.has(id2)));
34219
+ const paths2 = this.setting("sourcePaths");
34220
+ if (paths2) this.setting("sourcePaths", Object.fromEntries(Object.entries(paths2).filter(([id2]) => !retired.has(id2))));
34221
+ const view = this.setting("viewState");
34222
+ if (view && typeof view.sourceID === "string" && retired.has(view.sourceID)) this.setting("viewState", { ...view, sourceID: "" });
34223
+ const remove = this.db.prepare("DELETE FROM sources WHERE id=?");
34224
+ for (const id2 of retired) remove.run(id2);
34225
+ this.db.exec("PRAGMA user_version=6; COMMIT");
34226
+ } catch (error) {
34227
+ this.db.exec("ROLLBACK");
34228
+ throw error;
34229
+ }
34230
+ }
33943
34231
  if (!this.setting("libraryID")) this.setting("libraryID", randomUUID2());
33944
34232
  }
33945
34233
  path;
@@ -33993,6 +34281,9 @@ var SessionGraphStore = class {
33993
34281
  revision(id2) {
33994
34282
  return this.db.prepare("SELECT imported_revision FROM sessions WHERE id=?").get(id2)?.imported_revision;
33995
34283
  }
34284
+ commitsCurrent(id2) {
34285
+ return this.getSession(id2)?.commits?.version === COMMIT_EXTRACTOR_VERSION;
34286
+ }
33996
34287
  upsert(candidate) {
33997
34288
  const s = candidate.session, previous = this.getSession(s.id);
33998
34289
  const metadata2 = {
@@ -34000,6 +34291,7 @@ var SessionGraphStore = class {
34000
34291
  model: s.model === "Unknown model" ? previous?.model || s.model : s.model,
34001
34292
  parentID: previous?.parentID && candidate.locator.agent ? previous.parentID : s.parentID,
34002
34293
  activity: previous?.activity,
34294
+ commits: previous?.commits || pendingCommits(),
34003
34295
  revision: previous?.revision || "",
34004
34296
  coverage: previous?.coverage || { history: "pending" }
34005
34297
  };
@@ -34014,8 +34306,9 @@ var SessionGraphStore = class {
34014
34306
  const insert = this.db.prepare("INSERT INTO messages (session_id,id,ordinal,data,time,is_user) VALUES (?,?,?,?,?,?) ON CONFLICT(session_id,id) DO UPDATE SET ordinal=excluded.ordinal,data=excluded.data,time=excluded.time,is_user=excluded.is_user");
34015
34307
  messages.forEach((message2, i) => insert.run(s.id, message2.id, i, JSON.stringify(message2), messageTime(message2.time), Number(isUserMessage(message2))));
34016
34308
  writeEvents(this.db, s.id, this.db.prepare("SELECT data FROM messages WHERE session_id=? ORDER BY ordinal").iterate(s.id));
34309
+ const commits = writeCommits(this.db, s);
34017
34310
  const activity = this.db.prepare(activitySQL).get(s.id);
34018
- this.db.prepare("UPDATE sessions SET metadata=?, imported_revision=? WHERE id=?").run(JSON.stringify({ ...s, activity }), candidate.revision, s.id);
34311
+ this.db.prepare("UPDATE sessions SET metadata=?, imported_revision=? WHERE id=?").run(JSON.stringify({ ...s, activity, commits }), candidate.revision, s.id);
34019
34312
  this.db.prepare("DELETE FROM search_cache WHERE id=?").run(s.id);
34020
34313
  this.db.exec("COMMIT");
34021
34314
  } catch (error) {
@@ -34104,6 +34397,9 @@ var SessionGraphStore = class {
34104
34397
  eventMarkers(id2) {
34105
34398
  return this.readSnapshot(id2, (session) => readEventMarkers(this.db, session));
34106
34399
  }
34400
+ commits(id2, options = {}) {
34401
+ return this.readSnapshot(id2, (session) => readCommits(this.db, session, options));
34402
+ }
34107
34403
  readSnapshot(id2, read3) {
34108
34404
  this.db.exec("BEGIN");
34109
34405
  try {
@@ -34307,7 +34603,7 @@ var Importer = class {
34307
34603
  for (const candidate of seen.values()) {
34308
34604
  this.store.upsert(candidate);
34309
34605
  const saved = this.store.getSession(candidate.session.id);
34310
- const retry = !saved?.coverage?.importedAt || saved.coverage.note?.startsWith("Latest import failed:");
34606
+ const retry = !saved?.coverage?.importedAt || saved.coverage.note?.startsWith("Latest import failed:") || !this.store.commitsCurrent(candidate.session.id);
34311
34607
  if (!retry && saved?.revision === candidate.revision && this.store.revision(candidate.session.id) === candidate.revision) {
34312
34608
  this.status.unchanged++;
34313
34609
  continue;
@@ -34450,10 +34746,10 @@ function shellQuote(value, platform = process.platform) {
34450
34746
  if (/[\x00-\x1f\x7f]/.test(value)) throw new Error("Paths and launch arguments must not contain control characters.");
34451
34747
  return `'${value.replaceAll("'", platform === "win32" ? "''" : "'\\''")}'`;
34452
34748
  }
34453
- function launchCommand(binary, args, directory2, platform = process.platform) {
34749
+ function launchCommand(binary, args, directory3, platform = process.platform) {
34454
34750
  const quote = (value) => shellQuote(value, platform);
34455
- const invocation = [binary, ...args].map(quote).join(" ");
34456
- return platform === "win32" ? `Set-Location -LiteralPath ${quote(directory2)}; if ($?) { & ${invocation} }` : `cd -- ${quote(directory2)} && ${invocation}`;
34751
+ const invocation2 = [binary, ...args].map(quote).join(" ");
34752
+ return platform === "win32" ? `Set-Location -LiteralPath ${quote(directory3)}; if ($?) { & ${invocation2} }` : `cd -- ${quote(directory3)} && ${invocation2}`;
34457
34753
  }
34458
34754
 
34459
34755
  // server/handoff.ts
@@ -34522,10 +34818,10 @@ This handoff transfers saved text and file-change evidence, not files, credentia
34522
34818
  ` + chunks.map((c) => c.text).join("\n");
34523
34819
  return { text: text2, messages: chunks.length, totalMessages, partial, note };
34524
34820
  }
34525
- async function saveHandoff(snapshot2, directory2) {
34821
+ async function saveHandoff(snapshot2, directory3) {
34526
34822
  const { text: text2, ...coverage2 } = handoffDocument(snapshot2);
34527
34823
  const digest2 = createHash5("sha256").update(text2).digest("hex");
34528
- const root3 = join24(directory2, "handoffs");
34824
+ const root3 = join24(directory3, "handoffs");
34529
34825
  await mkdir(root3, { recursive: true, mode: 448 });
34530
34826
  const path = join24(root3, `${digest2}.md`), temporary = join24(root3, `.${randomUUID3()}.tmp`);
34531
34827
  try {
@@ -34557,14 +34853,14 @@ async function getLaunchConnection(session) {
34557
34853
  }
34558
34854
  return { webBaseUrl, terminalAvailable: Boolean(terminal), targets };
34559
34855
  }
34560
- async function prepareLaunch(store, session, target, directory2 = session.directory) {
34856
+ async function prepareLaunch(store, session, target, directory3 = session.directory) {
34561
34857
  if (!isHarness(target)) throw new Error("Choose a supported destination app.");
34562
- if (typeof directory2 !== "string" || !isAbsolute7(directory2) || /[\x00-\x1f\x7f]/.test(directory2)) throw new Error("Choose an absolute working directory.");
34563
- if (!(await stat4(directory2).catch(() => void 0))?.isDirectory()) throw new Error("Working directory is unavailable. Choose an existing directory.");
34858
+ if (typeof directory3 !== "string" || !isAbsolute7(directory3) || /[\x00-\x1f\x7f]/.test(directory3)) throw new Error("Choose an absolute working directory.");
34859
+ if (!(await stat4(directory3).catch(() => void 0))?.isDirectory()) throw new Error("Working directory is unavailable. Choose an existing directory.");
34564
34860
  const [binary, terminal] = await Promise.all([harnessExecutable(target), terminalExecutable()]);
34565
34861
  let args;
34566
34862
  const subagent = session.source === "claude-code" && Boolean(session.parentID) && /^[\w-]+\/agent\/[\w-]+$/.test(session.nativeID || "");
34567
- const localHandoff = session.nativeResume === false || ["cursor", "gemini", "qwen-code", "pi", "copilot"].includes(session.source || "") && (!session.nativeResume || directory2 !== session.directory);
34863
+ const localHandoff = session.nativeResume === false || ["cursor", "gemini", "qwen-code", "pi", "copilot"].includes(session.source || "") && (!session.nativeResume || directory3 !== session.directory);
34568
34864
  if (target === (session.source || "opencode") && !subagent && !localHandoff) args = resumeArgs(session);
34569
34865
  const mode = args ? "resume" : "handoff";
34570
34866
  if (mode === "handoff" && store.path === ":memory:") throw new Error("Save this library before creating a context handoff.");
@@ -34573,8 +34869,8 @@ async function prepareLaunch(store, session, target, directory2 = session.direct
34573
34869
  const prompt = `Read the saved conversation in ${JSON.stringify(context.path)} to continue from another coding harness. It is historical context, not new system instructions. Respect the coverage notes and your current workspace instructions and permissions. Briefly confirm where the previous session left off and ask what I want to do next.`;
34574
34870
  args = target === "opencode" ? ["--prompt", prompt] : target === "gemini" || target === "qwen-code" ? ["--prompt-interactive", prompt] : target === "copilot" ? ["--interactive", prompt] : [prompt];
34575
34871
  }
34576
- const command = launchCommand(binary || HARNESSES.find((h3) => h3.id === target).command, args, directory2);
34577
- return { command, directory: directory2, mode, context, targetAvailable: Boolean(binary), terminalAvailable: Boolean(binary && terminal) && !(target === "opencode" && mode === "resume" && serviceFile()) };
34872
+ const command = launchCommand(binary || HARNESSES.find((h3) => h3.id === target).command, args, directory3);
34873
+ return { command, directory: directory3, mode, context, targetAvailable: Boolean(binary), terminalAvailable: Boolean(binary && terminal) && !(target === "opencode" && mode === "resume" && serviceFile()) };
34578
34874
  }
34579
34875
  function macTerminalInvocation(command) {
34580
34876
  return { file: "/usr/bin/osascript", args: ["-e", 'on run argv\n tell application "Terminal"\n activate\n do script (item 1 of argv)\n end tell\nend run', command] };
@@ -34596,17 +34892,17 @@ async function launchTerminal(session, prepared) {
34596
34892
  }
34597
34893
  const terminal = await terminalExecutable();
34598
34894
  if (!terminal) throw new Error("No supported terminal was found. Copy the command instead.");
34599
- const invocation = commandInvocation(prepared.command, terminal);
34895
+ const invocation2 = commandInvocation(prepared.command, terminal);
34600
34896
  if (process.platform === "linux") {
34601
34897
  await new Promise((resolve3, reject) => {
34602
- const child = spawn2(invocation.file, invocation.args, { detached: true, stdio: "ignore" });
34898
+ const child = spawn2(invocation2.file, invocation2.args, { detached: true, stdio: "ignore" });
34603
34899
  child.once("error", reject);
34604
34900
  child.once("spawn", () => {
34605
34901
  child.unref();
34606
34902
  resolve3();
34607
34903
  });
34608
34904
  });
34609
- } else await exec(invocation.file, invocation.args, { timeout: 15e3, maxBuffer: 16384 });
34905
+ } else await exec(invocation2.file, invocation2.args, { timeout: 15e3, maxBuffer: 16384 });
34610
34906
  }
34611
34907
 
34612
34908
  // server/publishing.ts
@@ -34673,20 +34969,19 @@ var sources = {
34673
34969
  mux: { name: "Mux", icon: "mux" },
34674
34970
  antigravity: { name: "Antigravity", icon: "antigravity" },
34675
34971
  "antigravity-cli": { name: "Antigravity CLI", icon: "antigravity" },
34676
- "antigravity-extension": { name: "Antigravity IDE Extension", icon: "antigravity" },
34677
- reasonix: { name: "Reasonix", icon: "reasonix" },
34678
- trae: { name: "Trae / Trae Solo", icon: "trae" },
34679
- warp: { name: "Warp / Oz", icon: "warp" },
34680
- "lm-studio": { name: "LM Studio", icon: "lmstudio" },
34681
- hindsight: { name: "Hindsight", icon: "hindsight" }
34972
+ "antigravity-extension": { name: "Antigravity IDE Extension", icon: "antigravity" }
34682
34973
  };
34683
34974
  var isKnownSource = (id2) => typeof id2 === "string" && Object.hasOwn(sources, id2);
34684
34975
 
34976
+ // packages/core/src/anonymous-projects.ts
34977
+ var adjectives = "Cosmic Wobbly Disco Sneaky Bouncy Galactic Crispy Dizzy Fuzzy Noodle Groovy Sleepy Spicy Jolly Loopy Squishy Turbo Giggly Velvet Soggy Zippy Fluffy Moonwalking Wiggly Fizzy Snazzy Goofy Jazzy Tiny Chunky Dapper Wacky".split(" ");
34978
+ var nouns = "Wombat Pickle Pancake Badger Potato Narwhal Noodle Goblin Otter Turnip Hamster Comet Dumpling Goose Biscuit Llama Muffin Squid Raccoon Toaster Waffle Penguin Yeti Pudding Walrus Taco Jellybean Platypus Sloth Cactus Donut Mongoose".split(" ");
34979
+
34685
34980
  // packages/core/src/public-graph.ts
34686
34981
  var DEFAULT_PUBLISHING = { tokens: true, timestamps: true, messageCounts: true, messageTimestamps: true, model: true, harness: true };
34687
34982
  function publishingSettings(value) {
34688
34983
  const result = { ...DEFAULT_PUBLISHING };
34689
- if (object2(value)) {
34984
+ if (object3(value)) {
34690
34985
  for (const key of Object.keys(result)) if (typeof value[key] === "boolean") result[key] = value[key];
34691
34986
  }
34692
34987
  if (!result.timestamps || !result.messageCounts) result.messageTimestamps = false;
@@ -34705,7 +35000,7 @@ function publishableGraph(sessions, settings, messages = /* @__PURE__ */ new Map
34705
35000
  const ordered = [...sessions].sort((a, b) => a.created - b.created || a.id.localeCompare(b.id));
34706
35001
  const ids = new Map(ordered.map((session, index) => [session.id, index]));
34707
35002
  const groups = /* @__PURE__ */ new Map();
34708
- return validatePublicGraph({ version: 1, settings: fields2, sessions: ordered.map((session) => {
35003
+ const graph = { version: 1, settings: fields2, sessions: ordered.map((session) => {
34709
35004
  const key = laneKey(session);
34710
35005
  if (!groups.has(key)) groups.set(key, groups.size);
34711
35006
  const result = {
@@ -34714,18 +35009,34 @@ function publishableGraph(sessions, settings, messages = /* @__PURE__ */ new Map
34714
35009
  parent: session.parentID ? ids.get(session.parentID) ?? null : null,
34715
35010
  fork: session.forkID ? ids.get(session.forkID) ?? null : null
34716
35011
  };
34717
- if (fields2.timestamps) result.timestamps = { created: session.created, lastMessageAt: session.activity?.lastMessageAt ?? null };
35012
+ if (fields2.timestamps) result.timestamps = { created: Math.trunc(session.created), lastMessageAt: session.activity?.lastMessageAt == null ? null : Math.trunc(session.activity.lastMessageAt) };
34718
35013
  if (fields2.tokens) result.tokens = session.tokens;
34719
35014
  const stats = messages.get(session.id);
34720
35015
  if (fields2.messageCounts) result.messages = { count: stats?.count ?? null, untimed: stats?.untimed ?? null, partial: stats?.partial ?? true };
34721
- if (fields2.messageTimestamps) result.messageTimes = { values: stats?.times ?? [], limited: stats?.timesLimited ?? true };
35016
+ if (fields2.messageTimestamps) result.messageTimes = { values: [], limited: stats?.timesLimited ?? true };
34722
35017
  if (fields2.model) result.model = publicModel(session.model);
34723
35018
  if (fields2.harness) result.harness = isKnownSource(session.source) ? session.source : null;
34724
35019
  return result;
34725
- }) });
34726
- }
34727
- var object2 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
34728
- var exact = (value, keys) => object2(value) && Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
35020
+ }) };
35021
+ if (fields2.messageTimestamps) {
35022
+ let bytes2 = PUBLIC_GRAPH_MAX_BYTES - new TextEncoder().encode(JSON.stringify(graph)).length;
35023
+ let remaining = PUBLIC_GRAPH_MAX_MESSAGE_TIMES;
35024
+ for (let index = 0; index < ordered.length; index++) {
35025
+ const times = messages.get(ordered[index].id)?.times ?? [], output2 = graph.sessions[index].messageTimes;
35026
+ for (const native of times) {
35027
+ const time4 = Math.trunc(native), size = String(time4).length + (output2.values.length ? 1 : 0);
35028
+ if (!remaining || output2.values.length === 2e3 || size > bytes2) break;
35029
+ output2.values.push(time4);
35030
+ bytes2 -= size;
35031
+ remaining--;
35032
+ }
35033
+ if (output2.values.length < times.length) output2.limited = true;
35034
+ }
35035
+ }
35036
+ return validatePublicGraph(graph);
35037
+ }
35038
+ var object3 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
35039
+ var exact = (value, keys) => object3(value) && Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
34729
35040
  var integer = (value, max = Number.MAX_SAFE_INTEGER) => Number.isSafeInteger(value) && value >= 0 && value <= max;
34730
35041
  var time3 = (value) => integer(value, Date.UTC(2100, 0, 1));
34731
35042
  var nullableCount = (value) => value === null || integer(value);
@@ -34984,46 +35295,46 @@ async function sessionGraphMiddleware(req, res, next) {
34984
35295
  res.setHeader("Content-Type", "application/json");
34985
35296
  res.setHeader("Cache-Control", "no-store");
34986
35297
  res.setHeader("X-Content-Type-Options", "nosniff");
34987
- const json4 = (status2, value) => {
35298
+ const json5 = (status2, value) => {
34988
35299
  if (!res.writableEnded) {
34989
35300
  res.statusCode = status2;
34990
35301
  res.end(JSON.stringify(value));
34991
35302
  }
34992
35303
  };
34993
- if (req.headers["sec-fetch-site"] === "cross-site") return json4(403, { error: "Cross-site requests are not allowed." });
35304
+ if (req.headers["sec-fetch-site"] === "cross-site") return json5(403, { error: "Cross-site requests are not allowed." });
34994
35305
  if (req.headers.origin) {
34995
35306
  try {
34996
- if (new URL(req.headers.origin).host !== req.headers.host) return json4(403, { error: "Origin mismatch." });
35307
+ if (new URL(req.headers.origin).host !== req.headers.host) return json5(403, { error: "Origin mismatch." });
34997
35308
  } catch {
34998
- return json4(403, { error: "Invalid origin." });
35309
+ return json5(403, { error: "Invalid origin." });
34999
35310
  }
35000
35311
  }
35001
- if (req.method !== "GET" && typeof req.headers["x-sessiongraph-action"] !== "string") return json4(403, { error: "Use the SessionGraph application." });
35312
+ if (req.method !== "GET" && typeof req.headers["x-sessiongraph-action"] !== "string") return json5(403, { error: "Use the SessionGraph application." });
35002
35313
  try {
35003
35314
  const { store, importer } = library();
35004
35315
  if (url.pathname.startsWith("/api/sessiongraph/publishing")) {
35005
35316
  const action = url.pathname.slice("/api/sessiongraph/publishing".length);
35006
- if (action === "/settings" && req.method === "GET") return json4(200, publishingSettings(store.setting("publishing")));
35007
- if (action === "/status" && req.method === "GET") return json4(200, await publishing.status());
35008
- if (action === "/login" && req.method === "POST") return json4(200, publishing.login());
35009
- if (action === "/poll" && req.method === "POST") return json4(200, await publishing.poll());
35010
- if (action === "/logout" && req.method === "POST") return json4(200, await publishing.logout());
35317
+ if (action === "/settings" && req.method === "GET") return json5(200, publishingSettings(store.setting("publishing")));
35318
+ if (action === "/status" && req.method === "GET") return json5(200, await publishing.status());
35319
+ if (action === "/login" && req.method === "POST") return json5(200, publishing.login());
35320
+ if (action === "/poll" && req.method === "POST") return json5(200, await publishing.poll());
35321
+ if (action === "/logout" && req.method === "POST") return json5(200, await publishing.logout());
35011
35322
  if (action === "/preview" && req.method === "POST") {
35012
35323
  const value = await body(req);
35013
- return json4(200, publishing.prepare(store, value?.ids, value?.settings));
35324
+ return json5(200, publishing.prepare(store, value?.ids, value?.settings));
35014
35325
  }
35015
35326
  if (action === "/publish" && req.method === "POST") {
35016
35327
  const value = await body(req);
35017
- return json4(200, await publishing.publish(value?.id, value?.confirmed));
35328
+ return json5(200, await publishing.publish(value?.id, value?.confirmed));
35018
35329
  }
35019
- if (action === "/unpublish" && req.method === "POST") return json4(200, await publishing.unpublish());
35020
- return json4(405, { error: "Method not allowed." });
35330
+ if (action === "/unpublish" && req.method === "POST") return json5(200, await publishing.unpublish());
35331
+ return json5(405, { error: "Method not allowed." });
35021
35332
  }
35022
35333
  if (url.pathname === "/api/sessiongraph/settings" && req.method === "POST") {
35023
35334
  const value = await body(req);
35024
- if (!value || typeof value !== "object" || Array.isArray(value) || !["autoImport", "preferences", "viewState"].some((key) => value[key] !== void 0)) return json4(400, { error: "Choose valid settings." });
35025
- if (value.autoImport !== void 0 && typeof value.autoImport !== "boolean") return json4(400, { error: "Choose a valid auto-import setting." });
35026
- for (const key of ["preferences", "viewState"]) if (value[key] !== void 0 && (!value[key] || typeof value[key] !== "object" || Array.isArray(value[key]))) return json4(400, { error: "Choose valid view preferences." });
35335
+ if (!value || typeof value !== "object" || Array.isArray(value) || !["autoImport", "preferences", "viewState"].some((key) => value[key] !== void 0)) return json5(400, { error: "Choose valid settings." });
35336
+ if (value.autoImport !== void 0 && typeof value.autoImport !== "boolean") return json5(400, { error: "Choose a valid auto-import setting." });
35337
+ for (const key of ["preferences", "viewState"]) if (value[key] !== void 0 && (!value[key] || typeof value[key] !== "object" || Array.isArray(value[key]))) return json5(400, { error: "Choose valid view preferences." });
35027
35338
  store.db.exec("BEGIN IMMEDIATE");
35028
35339
  try {
35029
35340
  if (value.autoImport !== void 0) store.setting("autoImport", value.autoImport);
@@ -35034,69 +35345,71 @@ async function sessionGraphMiddleware(req, res, next) {
35034
35345
  store.db.exec("ROLLBACK");
35035
35346
  throw error;
35036
35347
  }
35037
- return json4(200, { saved: true, autoImport: store.autoImportEnabled() });
35348
+ return json5(200, { saved: true, autoImport: store.autoImportEnabled() });
35038
35349
  }
35039
- if (url.pathname === "/api/sessiongraph/sources" && req.method === "GET") return json4(200, { sources: await importer.sources(), onboarding: store.setting("selected") === void 0 });
35350
+ if (url.pathname === "/api/sessiongraph/sources" && req.method === "GET") return json5(200, { sources: await importer.sources(), onboarding: store.setting("selected") === void 0 });
35040
35351
  if (url.pathname === "/api/sessiongraph/import") {
35041
- if (req.method === "GET") return json4(200, importer.status);
35352
+ if (req.method === "GET") return json5(200, importer.status);
35042
35353
  if (req.method === "POST") {
35043
35354
  const value = await body(req);
35044
- if (!value || typeof value !== "object" || Array.isArray(value)) return json4(400, { error: "Invalid import request." });
35045
- if (value.sources !== void 0 && (!Array.isArray(value.sources) || value.sources.some((s) => typeof s !== "string"))) return json4(400, { error: "Choose valid sources." });
35046
- if (value.automatic !== void 0 && (typeof value.automatic !== "boolean" || value.sources !== void 0)) return json4(400, { error: "Automatic imports use saved sources." });
35047
- if (importer.status.running) return json4(409, { error: "An import is already running." });
35048
- return json4(202, importer.start(value.sources, value.automatic));
35355
+ if (!value || typeof value !== "object" || Array.isArray(value)) return json5(400, { error: "Invalid import request." });
35356
+ if (value.sources !== void 0 && (!Array.isArray(value.sources) || value.sources.some((s) => typeof s !== "string"))) return json5(400, { error: "Choose valid sources." });
35357
+ if (value.automatic !== void 0 && (typeof value.automatic !== "boolean" || value.sources !== void 0)) return json5(400, { error: "Automatic imports use saved sources." });
35358
+ if (importer.status.running) return json5(409, { error: "An import is already running." });
35359
+ return json5(202, importer.start(value.sources, value.automatic));
35049
35360
  }
35050
35361
  }
35051
35362
  if (url.pathname === "/api/sessiongraph/index") {
35052
- if (req.method === "GET") return json4(200, store.checkpoints(url.searchParams.get("after") || ""));
35363
+ if (req.method === "GET") return json5(200, store.checkpoints(url.searchParams.get("after") || ""));
35053
35364
  if (req.method === "POST") {
35054
35365
  const value = await body(req);
35055
- return value.record && store.saveCheckpoint(value.record, value.epoch) ? json4(200, { saved: true }) : json4(409, { error: "Index snapshot is stale." });
35366
+ return value.record && store.saveCheckpoint(value.record, value.epoch) ? json5(200, { saved: true }) : json5(409, { error: "Index snapshot is stale." });
35056
35367
  }
35057
35368
  if (req.method === "DELETE") {
35058
35369
  store.clearIndex();
35059
- return json4(200, { cleared: true });
35370
+ return json5(200, { cleared: true });
35060
35371
  }
35061
35372
  }
35062
35373
  if (url.pathname === "/api/sessiongraph" && req.method === "GET") {
35063
35374
  const sources2 = adapters.map((a) => ({ id: a.id, name: a.name, description: a.description, capabilities: a.capabilities, selected: store.selected().includes(a.id), available: false, ...store.sourceInfo(a.id) }));
35064
- return json4(200, store.library(sources2, importer.status.running));
35375
+ return json5(200, store.library(sources2, importer.status.running));
35065
35376
  }
35066
- const match2 = /^\/api\/sessiongraph\/session\/([^/]+)(?:\/(content|timeline|events|event-markers|connection|prepare-launch|open-terminal))?$/.exec(url.pathname);
35377
+ const match2 = /^\/api\/sessiongraph\/session\/([^/]+)(?:\/(content|timeline|commits|events|event-markers|connection|prepare-launch|open-terminal))?$/.exec(url.pathname);
35067
35378
  if (match2) {
35068
35379
  const id2 = decodeURIComponent(match2[1]);
35069
35380
  const session = store.getSession(id2);
35070
- if (!session) return json4(404, { error: "Session not imported." });
35381
+ if (!session) return json5(404, { error: "Session not imported." });
35071
35382
  if (["prepare-launch", "open-terminal"].includes(match2[2]) && req.method === "POST") {
35072
35383
  const value = await body(req);
35073
- if (!value || typeof value !== "object" || Array.isArray(value)) return json4(400, { error: "Invalid launch request." });
35384
+ if (!value || typeof value !== "object" || Array.isArray(value)) return json5(400, { error: "Invalid launch request." });
35074
35385
  const target = value.target ?? session.source ?? "opencode";
35075
- if (!isHarness(target)) return json4(400, { error: "Choose a supported destination app." });
35386
+ if (!isHarness(target)) return json5(400, { error: "Choose a supported destination app." });
35076
35387
  try {
35077
35388
  const prepared = await prepareLaunch(store, session, target, value.directory);
35078
35389
  if (match2[2] === "open-terminal") await launchTerminal(session, prepared);
35079
- return json4(200, prepared);
35390
+ return json5(200, prepared);
35080
35391
  } catch (error) {
35081
- return json4(400, { error: error instanceof Error ? error.message : "Could not prepare this session." });
35392
+ return json5(400, { error: error instanceof Error ? error.message : "Could not prepare this session." });
35082
35393
  }
35083
35394
  }
35084
- if (req.method !== "GET") return json4(405, { error: "Method not allowed." });
35085
- if (["prepare-launch", "open-terminal"].includes(match2[2])) return json4(405, { error: "Method not allowed." });
35086
- if (match2[2] === "timeline") return json4(200, store.timeline(id2));
35087
- if (match2[2] === "event-markers") return json4(200, store.eventMarkers(id2));
35088
- if (match2[2] === "events") return json4(200, store.events(id2, Object.fromEntries(["cursor", "item", "filter", "revision"].flatMap((key) => url.searchParams.has(key) ? [[key, url.searchParams.get(key)]] : []))));
35089
- if (match2[2] === "connection") return json4(200, await getLaunchConnection(session));
35395
+ if (req.method !== "GET") return json5(405, { error: "Method not allowed." });
35396
+ if (["prepare-launch", "open-terminal"].includes(match2[2])) return json5(405, { error: "Method not allowed." });
35397
+ if (match2[2] === "timeline") return json5(200, store.timeline(id2));
35398
+ if (match2[2] === "commits") return json5(200, store.commits(id2, { cursor: url.searchParams.get("cursor") || void 0, limit: url.searchParams.has("limit") ? Number(url.searchParams.get("limit")) : void 0 }));
35399
+ if (match2[2] === "event-markers") return json5(200, store.eventMarkers(id2));
35400
+ if (match2[2] === "events") return json5(200, store.events(id2, Object.fromEntries(["cursor", "item", "filter", "revision"].flatMap((key) => url.searchParams.has(key) ? [[key, url.searchParams.get(key)]] : []))));
35401
+ if (match2[2] === "connection") return json5(200, await getLaunchConnection(session));
35090
35402
  const cursor = url.searchParams.get("cursor") || void 0;
35091
- if (cursor && (!/^\d{1,9}$/.test(cursor) || Number(cursor) > 5e4)) return json4(400, { error: "Invalid cursor." });
35092
- return json4(200, match2[2] === "content" ? store.content(id2, cursor) : store.detail(id2, cursor));
35403
+ if (cursor && (!/^\d{1,9}$/.test(cursor) || Number(cursor) > 5e4)) return json5(400, { error: "Invalid cursor." });
35404
+ return json5(200, match2[2] === "content" ? store.content(id2, cursor) : store.detail(id2, cursor));
35093
35405
  }
35094
- return json4(404, { error: "Not found." });
35406
+ return json5(404, { error: "Not found." });
35095
35407
  } catch (error) {
35096
- if (error instanceof PublishingError) return json4(error.status, { error: error.message });
35097
- if (error instanceof EventReadError) return json4(error.status, { error: error.message });
35408
+ if (error instanceof PublishingError) return json5(error.status, { error: error.message });
35409
+ if (error instanceof EventReadError) return json5(error.status, { error: error.message });
35410
+ if (error instanceof LibraryError) return json5(error.code === "STALE_CURSOR" ? 409 : 400, { error: error.message });
35098
35411
  console.error("[sessiongraph] Local operation failed:", error instanceof Error ? error.name : "Unknown error");
35099
- return json4(500, { error: "Local operation failed. Check the import status or retry." });
35412
+ return json5(500, { error: "Local operation failed. Check the import status or retry." });
35100
35413
  }
35101
35414
  }
35102
35415