sessiongraph-app-win32-x64 1.0.13 → 1.0.15

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 (29) hide show
  1. package/package.json +2 -2
  2. package/payload/SessionGraph.exe +0 -0
  3. package/payload/resources/node.exe +2 -2
  4. package/payload/resources/server.mjs +643 -325
  5. package/payload/resources/web/assets/external-links-BmBkCsrt.js +1 -0
  6. package/payload/resources/web/assets/index-B1kyvo41.js +175 -0
  7. package/payload/resources/web/assets/index-BLM-0yG6.js +1 -0
  8. package/payload/resources/web/assets/{index-CJb-F0VY.js → index-D4P4hbvc.js} +1 -1
  9. package/payload/resources/web/assets/index-Du0_nVjH.css +1 -0
  10. package/payload/resources/web/assets/{index-HzUuskn3.js → index-Kotmn42s.js} +1 -1
  11. package/payload/resources/web/assets/publishing-CEvQPkO1.css +1 -0
  12. package/payload/resources/web/assets/publishing-D9CqkbeB.js +23 -0
  13. package/payload/resources/web/assets/scene-CTHyYtma.js +139 -0
  14. package/payload/resources/web/assets/share-Cw1E-ED9.js +7 -0
  15. package/payload/resources/web/index.html +2 -2
  16. package/payload/resources/web/sources/NOTICE.txt +4 -4
  17. package/payload/resources/web/assets/external-links-BcKDmn29.js +0 -1
  18. package/payload/resources/web/assets/index-CDA8pT1Q.js +0 -170
  19. package/payload/resources/web/assets/index-DYhIhreE.js +0 -1
  20. package/payload/resources/web/assets/index-cVgPCrFV.css +0 -1
  21. package/payload/resources/web/assets/publishing-CpVLG7_B.js +0 -25
  22. package/payload/resources/web/assets/publishing-VJhUmdPH.css +0 -1
  23. package/payload/resources/web/assets/scene-BkoCsbA8.js +0 -139
  24. package/payload/resources/web/assets/share-CS1dKayZ.js +0 -7
  25. package/payload/resources/web/sources/hindsight.svg +0 -1
  26. package/payload/resources/web/sources/lmstudio.svg +0 -1
  27. package/payload/resources/web/sources/reasonix.svg +0 -1
  28. package/payload/resources/web/sources/trae.svg +0 -1
  29. 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 {
@@ -30654,7 +30810,11 @@ function localFileAdapter(source) {
30654
30810
  let candidate = metadata2.get(path);
30655
30811
  if (!candidate || candidate.revision !== rev) {
30656
30812
  const history = await load(path, rev, before);
30657
- if (!history) continue;
30813
+ if (!history) {
30814
+ const nativeID = source.authoritativeIdentity?.(path);
30815
+ if (nativeID) blocked.add(identity(source.id, nativeID));
30816
+ continue;
30817
+ }
30658
30818
  const session = { ...blankSession(source.id, history.nativeID), ...history.session };
30659
30819
  session.id = identity(source.id, history.nativeID);
30660
30820
  session.nativeID = history.nativeID;
@@ -30714,7 +30874,7 @@ function conversationMessage(raw, fallbackID) {
30714
30874
  const message2 = blankMessage(text(raw.id) || fallbackID, time(raw.timestamp ?? raw.ts), role);
30715
30875
  let content = raw.content;
30716
30876
  if (Array.isArray(content)) content = content.map((part) => {
30717
- const p = object(part);
30877
+ const p = object2(part);
30718
30878
  return p.type === "toolCall" ? { ...p, type: "tool_use", input: p.arguments } : p.type === "reasoning" ? { ...p, type: "thinking", thinking: p.text } : p;
30719
30879
  });
30720
30880
  if (raw.role === "thinking") content = [{ type: "thinking", thinking: raw.content }];
@@ -30735,7 +30895,7 @@ function conversationMessage(raw, fallbackID) {
30735
30895
  else if (event.kind === "reasoning") addText(message2, event.text, "Assistant");
30736
30896
  }
30737
30897
  for (const call of Array.isArray(raw.toolCalls) ? raw.toolCalls : []) {
30738
- const f = object(call.function);
30898
+ const f = object2(call.function);
30739
30899
  if (!text(f.name)) continue;
30740
30900
  message2.tools.push(f.name);
30741
30901
  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 +30909,7 @@ function googleMessage(raw, fallbackID) {
30749
30909
  const parts = Array.isArray(raw.content) ? raw.content : raw.content != null ? [raw.content] : [];
30750
30910
  const content = parts.map((part) => {
30751
30911
  if (typeof part === "string") return { type: "text", text: part };
30752
- const p = object(part);
30912
+ const p = object2(part);
30753
30913
  if (typeof p.text === "string") return p.thought ? { type: "thinking", thinking: p.text } : { type: "text", text: p.text };
30754
30914
  if (p.functionCall) return { type: "tool_use", ...p.functionCall, input: p.functionCall.args };
30755
30915
  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 +30923,7 @@ function successfulEdits(messages, editNames) {
30763
30923
  if (event.kind === "tool_call" && event.callID) {
30764
30924
  let input = {};
30765
30925
  try {
30766
- input = object(JSON.parse(event.input || "{}"));
30926
+ input = object2(JSON.parse(event.input || "{}"));
30767
30927
  } catch {
30768
30928
  }
30769
30929
  calls.set(event.callID, { name: event.name, input });
@@ -30853,7 +31013,7 @@ var piAdapter = localFileAdapter({
30853
31013
  var nativeText = (v3) => typeof v3 === "number" && Number.isSafeInteger(v3) ? String(v3) : text(v3);
30854
31014
  var seconds = (v3) => typeof v3 === "number" && Number.isFinite(v3) && v3 > 0 ? v3 * 1e3 : time(v3);
30855
31015
  var fileID = (path) => basename4(path).replace(/\.jsonl(?:\..*)?$|\.json$/, "");
30856
- var sidecar2 = (files, path) => object(files.has(path) ? json2(files.get(path)) : void 0);
31016
+ var sidecar2 = (files, path) => object2(files.has(path) ? json3(files.get(path)) : void 0);
30857
31017
  var roles = ["user", "assistant", "system", "tool", "toolResult", "model"];
30858
31018
  function message(raw, id2, timestamp) {
30859
31019
  if (!roles.includes(raw.role)) return;
@@ -30874,7 +31034,7 @@ function envelopeHistory(path, value) {
30874
31034
  const header = rows2.find((r) => r.type === "session" || r.type === "session_start" || r.type === "session_startup") || {};
30875
31035
  const nativeID = [...nativeIDs][0] || text(header.id || header.sessionId) || fileID(path);
30876
31036
  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);
31037
+ const body2 = object2(r.message), role = body2.role || r.role || (["user", "assistant", "system"].includes(r.type) ? r.type : void 0);
30878
31038
  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
31039
  return m ? [m] : [];
30880
31040
  });
@@ -30890,7 +31050,7 @@ function envelopeHistory(path, value) {
30890
31050
  };
30891
31051
  }
30892
31052
  function ampHistory(path, files) {
30893
- const raw = object(json2(files.get(path)));
31053
+ const raw = object2(json3(files.get(path)));
30894
31054
  if (!text(raw.id) || !Array.isArray(raw.messages)) throw new Error("Unsupported Amp thread.");
30895
31055
  const messages = raw.messages.flatMap((m, i) => {
30896
31056
  const result = message(m, nativeText(m.messageId) || `message:${i}`, m.timestamp ?? m.usage?.timestamp);
@@ -30899,14 +31059,14 @@ function ampHistory(path, files) {
30899
31059
  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
31060
  }
30901
31061
  function jcodeHistory(path, files) {
30902
- const raw = object(json2(files.get(path)));
31062
+ const raw = object2(json3(files.get(path)));
30903
31063
  if (!text(raw.id) || !Array.isArray(raw.messages)) throw new Error("Unsupported Jcode session.");
30904
31064
  const journal = path.replace(/\.json$/, ".journal.jsonl");
30905
31065
  const appended = files.has(journal) ? jsonLines(files.get(journal)) : { rows: [], partial: false };
30906
31066
  const records = [...raw.messages];
30907
31067
  for (const row of appended.rows) {
30908
31068
  if (Array.isArray(row.append_messages)) records.push(...row.append_messages);
30909
- if (row.meta) Object.assign(raw, object(row.meta));
31069
+ if (row.meta) Object.assign(raw, object2(row.meta));
30910
31070
  }
30911
31071
  const seen = /* @__PURE__ */ new Set();
30912
31072
  const messages = records.flatMap((r, i) => {
@@ -30919,7 +31079,7 @@ function jcodeHistory(path, files) {
30919
31079
  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
31080
  }
30921
31081
  function codebuffHistory(path, files, free) {
30922
- const records = json2(files.get(path));
31082
+ const records = json3(files.get(path));
30923
31083
  if (!Array.isArray(records)) throw new Error("Unsupported Codebuff chat.");
30924
31084
  const isFree = records.some((m) => text(m.metadata?.runState?.sessionState?.mainAgentState?.agentType).startsWith("base2-free"));
30925
31085
  if (isFree !== free) return;
@@ -30932,8 +31092,8 @@ function codebuffHistory(path, files, free) {
30932
31092
  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
31093
  }
30934
31094
  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;
31095
+ const raw = object2(json3(files.get(path))), legacy = basename4(path) !== "meta.json";
31096
+ const meta = legacy ? object2(raw.metadata) : raw;
30937
31097
  const transcript = join6(dirname2(path), "messages.jsonl");
30938
31098
  const parsed = files.has(transcript) ? jsonLines(files.get(transcript)) : { rows: [], partial: false };
30939
31099
  const records = legacy ? raw.messages : parsed.rows;
@@ -30960,7 +31120,7 @@ function acpHistory(path, value) {
30960
31120
  }
30961
31121
  };
30962
31122
  for (const [i, row] of rows2.entries()) {
30963
- const p = object(row.params), u2 = object(p.update), kind = text(u2.sessionUpdate);
31123
+ const p = object2(row.params), u2 = object2(p.update), kind = text(u2.sessionUpdate);
30964
31124
  if (text(p.sessionId)) ids.add(p.sessionId);
30965
31125
  const timestamp = time(p._meta?.agentTimestampMs) || time(row.timestamp);
30966
31126
  const role = kind === "user_message_chunk" ? "user" : kind === "agent_message_chunk" ? "assistant" : "";
@@ -30986,7 +31146,7 @@ function dshHistory(value) {
30986
31146
  if (!text(header?.id)) throw new Error("Unsupported DeepSeek Harness session.");
30987
31147
  const messages = rows2.flatMap((r, i) => {
30988
31148
  if (!["user/message", "assistant/message", "tool/message"].includes(r.type)) return [];
30989
- const body2 = object(r.data?.message);
31149
+ const body2 = object2(r.data?.message);
30990
31150
  const m = message({ ...body2, role: body2.role || r.type.split("/")[0] }, text(body2.id) || `record:${i}`, r.time);
30991
31151
  return m ? [m] : [];
30992
31152
  });
@@ -31038,11 +31198,11 @@ function withSqliteSnapshot(path, read3, expected, pinned = false) {
31038
31198
  if (copy?.revision !== revision2) {
31039
31199
  close(path);
31040
31200
  while (copies.size >= 2) close(copies.keys().next().value);
31041
- const directory2 = mkdtempSync(join7(tmpdir(), "sessiongraph-history-"));
31201
+ const directory3 = mkdtempSync(join7(tmpdir(), "sessiongraph-history-"));
31042
31202
  let db2;
31043
31203
  try {
31044
- chmodSync(directory2, 448);
31045
- const destination = join7(directory2, "history.db");
31204
+ chmodSync(directory3, 448);
31205
+ const destination = join7(directory3, "history.db");
31046
31206
  for (const suffix of ["", "-wal"]) {
31047
31207
  try {
31048
31208
  copyFileSync(path + suffix, destination + suffix, constants4.COPYFILE_FICLONE);
@@ -31055,13 +31215,13 @@ function withSqliteSnapshot(path, read3, expected, pinned = false) {
31055
31215
  if (sqliteRevision(path) !== revision2) throw new SqliteSnapshotChangedError("History database changed while copying; import again.");
31056
31216
  db2 = new DatabaseSync(destination, { readOnly: true, enableDoubleQuotedStringLiterals: false, allowExtension: false });
31057
31217
  db2.exec("PRAGMA query_only=ON; PRAGMA trusted_schema=OFF; PRAGMA busy_timeout=1000; BEGIN;");
31058
- copy = { revision: revision2, directory: directory2, db: db2 };
31218
+ copy = { revision: revision2, directory: directory3, db: db2 };
31059
31219
  copies.set(path, copy);
31060
31220
  } catch (error) {
31061
31221
  try {
31062
31222
  db2?.close();
31063
31223
  } finally {
31064
- rmSync2(directory2, { recursive: true, force: true });
31224
+ rmSync2(directory3, { recursive: true, force: true });
31065
31225
  }
31066
31226
  throw error;
31067
31227
  }
@@ -31270,7 +31430,7 @@ function combineAdapters(parts) {
31270
31430
 
31271
31431
  // server/adapters/claude.ts
31272
31432
  var root = () => join8(sourcePath("claude-code") || process.env.CLAUDE_CONFIG_DIR || join8(homedir4(), ".claude"), "projects");
31273
- function claudeMessages(rows2, candidate, times) {
31433
+ function claudeMessages(rows2, candidate, times, entries2) {
31274
31434
  const calls = /* @__PURE__ */ new Map();
31275
31435
  return rows2.map((row) => {
31276
31436
  const raw = row.message;
@@ -31295,7 +31455,18 @@ function claudeMessages(rows2, candidate, times) {
31295
31455
  }
31296
31456
  }
31297
31457
  }
31298
- msg.events = blockEvents(msg, raw?.content).map((event) => ({ ...event, parentID: row.parent_tool_use_id || void 0 }));
31458
+ const entry = entries2?.get(row.uuid), structured = entry?.tool_use_result ?? entry?.toolUseResult;
31459
+ const results = Array.isArray(raw?.content) ? raw.content.filter((p) => p.type === "tool_result") : [];
31460
+ msg.events = blockEvents(msg, raw?.content).map((event) => {
31461
+ const result = event.kind === "tool_result" && results.length === 1 ? structured : void 0;
31462
+ return {
31463
+ ...event,
31464
+ parentID: row.parent_tool_use_id || void 0,
31465
+ ...executionFields({}, { ...result, cwd: entry?.cwd }),
31466
+ gitCommit: nativeCommit(result?.gitOperation?.commit),
31467
+ partial: Boolean(event.partial || result?.interrupted || result?.backgroundTaskId || result?.backgroundedByUser || result?.timedOutAfterMs || entry?.sessionId && entry.sessionId !== (candidate.locator.parent || candidate.session.nativeID))
31468
+ };
31469
+ });
31299
31470
  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
31471
  return msg;
31301
31472
  });
@@ -31396,7 +31567,7 @@ var sdkClaudeAdapter = {
31396
31567
  const options = { dir: candidate.locator.dir || void 0, offset: start, limit: count + 1, sessionStore: claudeTranscriptStore(transcript, sessionId, candidate.locator.agent) };
31397
31568
  const rows2 = candidate.locator.parent ? await U1t(candidate.locator.parent, candidate.locator.agent, options) : await P1t(candidate.session.nativeID, options);
31398
31569
  const more = rows2.length > count;
31399
- const messages = claudeMessages(rows2.slice(0, count), candidate, transcript.times).slice(offset - start);
31570
+ const messages = claudeMessages(rows2.slice(0, count), candidate, transcript.times, transcript.byID).slice(offset - start);
31400
31571
  if (!offset && !messages.length && transcript.size > 100) throw new Error("SDK returned no readable conversation for this transcript.");
31401
31572
  if (!more && await claudeRevision(candidate.locator.path) !== candidate.revision) throw new Error("Session changed during import; import again to capture the latest messages.");
31402
31573
  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 +31686,7 @@ async function transcriptFiles(root3, max = 2e4, match2 = (name) => name.endsWit
31515
31686
  var root2 = () => sourcePath("codex") || process.env.CODEX_HOME || join10(homedir5(), ".codex");
31516
31687
  var revision = async (path) => {
31517
31688
  const s = await stat2(path);
31518
- return digest([9, s.mtimeMs, s.size]);
31689
+ return digest([10, s.mtimeMs, s.size]);
31519
31690
  };
31520
31691
  function changedPaths(value) {
31521
31692
  if (!value || typeof value !== "object") return [];
@@ -31553,6 +31724,7 @@ async function sessionNames() {
31553
31724
  function codexRecord(raw, offset, candidate) {
31554
31725
  const p = raw.payload;
31555
31726
  if (!p || typeof p !== "object") return;
31727
+ if (raw.type === "session_meta" || raw.type === "turn_context") candidate.locator.executionCwd = typeof p.cwd === "string" ? p.cwd : "";
31556
31728
  if (raw.type === "turn_context" && typeof p.model === "string") candidate.session.model = p.model;
31557
31729
  if (raw.type === "event_msg" && p.type === "item_completed" && ["FileChange", "fileChange"].includes(p.item?.type)) {
31558
31730
  const msg2 = blankMessage(`event:${p.item.id || raw.ordinal || offset}`, p.completed_at_ms || Date.parse(raw.timestamp) || 0, "tool");
@@ -31584,7 +31756,14 @@ function codexRecord(raw, offset, candidate) {
31584
31756
  }
31585
31757
  const role = p.role === "user" ? "user" : p.role === "assistant" ? "assistant" : p.type === "message" ? "system" : "tool";
31586
31758
  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 };
31759
+ let input = p.arguments ?? p.input;
31760
+ if (typeof input === "string") {
31761
+ try {
31762
+ input = JSON.parse(input);
31763
+ } catch {
31764
+ }
31765
+ }
31766
+ const fields2 = { nativeID: p.id, nativeType: p.type, callID: p.call_id, ...executionFields(input, { cwd: candidate.locator.executionCwd }) };
31588
31767
  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
31768
  if (p.type === "message") {
31590
31769
  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 +31838,7 @@ var codexAdapter = {
31659
31838
  })).values()], warnings };
31660
31839
  },
31661
31840
  async read(candidate, cursor) {
31841
+ if (!cursor) candidate.locator.executionCwd = "";
31662
31842
  const page = await readJSONL(candidate.locator.path, Number(cursor || 0));
31663
31843
  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
31844
  return { messages: page.rows.flatMap((r) => {
@@ -31677,7 +31857,8 @@ var PAGE = 100;
31677
31857
  var MAX_THREADS = 2e4;
31678
31858
  var MAX_ITEM_JSON = 256e3;
31679
31859
  var providerSource = { codex: "codex", claudeAgent: "claude-code", opencode: "opencode" };
31680
- var string = (value) => typeof value === "string" ? value : "";
31860
+ var openCodeEditTools = /* @__PURE__ */ new Set(["patch", "apply_patch", "edit", "write", "multiedit"]);
31861
+ var string2 = (value) => typeof value === "string" ? value : "";
31681
31862
  function parsedObject(value) {
31682
31863
  if (typeof value !== "string") return;
31683
31864
  try {
@@ -31692,7 +31873,7 @@ function time2(value) {
31692
31873
  return Number.isFinite(parsed) && parsed > 0 && parsed <= 864e13 ? parsed : 0;
31693
31874
  }
31694
31875
  function status(value) {
31695
- return ["pending", "running", "completed", "failed"].includes(string(value)) ? value : "unknown";
31876
+ return ["pending", "running", "completed", "failed"].includes(string2(value)) ? value : "unknown";
31696
31877
  }
31697
31878
  async function databasePath2() {
31698
31879
  const root3 = sourcePath("t3-code") || process.env.SESSIONGRAPH_T3_CODE_HISTORY_DIR || process.env.T3CODE_HOME || join11(homedir6(), ".t3");
@@ -31721,7 +31902,7 @@ function projectRoots(db2, ids) {
31721
31902
  for (const batch of batches([...new Set(ids.filter(Boolean))])) {
31722
31903
  const placeholders = batch.map(() => "?").join(",");
31723
31904
  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));
31905
+ roots2.set(string2(row.project_id), string2(row.workspace_root));
31725
31906
  }
31726
31907
  return roots2;
31727
31908
  }
@@ -31731,7 +31912,7 @@ function aggregates(db2, table, ids) {
31731
31912
  for (const batch of batches(ids)) {
31732
31913
  const placeholders = batch.map(() => "?").join(",");
31733
31914
  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)]);
31915
+ result.set(string2(row.thread_id), [Number(row.n), string2(row.latest)]);
31735
31916
  }
31736
31917
  return result;
31737
31918
  }
@@ -31745,10 +31926,10 @@ function linkedSessions(db2, ids) {
31745
31926
  CASE WHEN json_valid(payload_json) THEN json_extract(payload_json,'$.nativeThreadRef.strength') END AS strength,
31746
31927
  CASE WHEN json_valid(payload_json) THEN json_extract(payload_json,'$.nativeThreadRef.driver') END AS driver
31747
31928
  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);
31929
+ const source = providerSource[string2(row.provider)];
31930
+ const nativeID = string2(row.native_id);
31750
31931
  if (!source || row.strength !== "strong" || row.driver && row.driver !== row.provider || !nativeID || nativeID.length > 512) continue;
31751
- const id2 = string(row.thread_id);
31932
+ const id2 = string2(row.thread_id);
31752
31933
  links.set(id2, [.../* @__PURE__ */ new Set([...links.get(id2) || [], identity(source, nativeID)])]);
31753
31934
  }
31754
31935
  }
@@ -31763,8 +31944,8 @@ function discoverV2(db2, path, databaseRevision) {
31763
31944
  CASE WHEN json_valid(payload_json) THEN json_extract(payload_json,'$.lineage.relationshipToParent') END AS relationship,
31764
31945
  json_valid(payload_json) AS valid_payload
31765
31946
  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)));
31947
+ const selected = rows2.slice(0, MAX_THREADS), ids = selected.map((row) => string2(row.thread_id));
31948
+ const roots2 = projectRoots(db2, selected.map((row) => string2(row.project_id)));
31768
31949
  const counts = aggregates(db2, "orchestration_v2_projection_messages", ids);
31769
31950
  const items = aggregates(db2, "orchestration_v2_projection_turn_items", ids);
31770
31951
  const links = linkedSessions(db2, ids);
@@ -31772,28 +31953,28 @@ function discoverV2(db2, path, databaseRevision) {
31772
31953
  if (rows2.length > MAX_THREADS) warnings.push(`T3 Code discovery is limited to ${MAX_THREADS.toLocaleString()} threads.`);
31773
31954
  let unreadableMetadata = 0;
31774
31955
  for (const row of selected) {
31775
- const nativeID = string(row.thread_id), created = time2(row.created_at);
31956
+ const nativeID = string2(row.thread_id), created = time2(row.created_at);
31776
31957
  if (!nativeID || nativeID.length > 512 || !created) continue;
31777
31958
  if (!row.valid_payload) unreadableMetadata++;
31778
- const directory2 = string(row.worktree_path) || roots2.get(string(row.project_id)) || "";
31779
- const p = project(SOURCE, directory2);
31959
+ const directory3 = string2(row.worktree_path) || roots2.get(string2(row.project_id)) || "";
31960
+ const p = project(SOURCE, directory3);
31780
31961
  projects.set(p.id, p);
31781
- const session = blankSession(SOURCE, nativeID, directory2);
31782
- const parent2 = string(row.parent_thread_id);
31962
+ const session = blankSession(SOURCE, nativeID, directory3);
31963
+ const parent2 = string2(row.parent_thread_id);
31783
31964
  session.parentID = row.relationship === "subagent" && parent2 ? identity(SOURCE, parent2) : void 0;
31784
31965
  session.forkID = row.relationship === "fork" && parent2 ? identity(SOURCE, parent2) : void 0;
31785
31966
  Object.assign(session, {
31786
- title: string(row.title) || "T3 Code thread",
31967
+ title: string2(row.title) || "T3 Code thread",
31787
31968
  projectID: p.id,
31788
31969
  created,
31789
31970
  updated: time2(row.updated_at) || created,
31790
31971
  archived: Boolean(row.archived_at),
31791
- model: string(row.model) || "Unknown model",
31792
- provider: string(row.default_provider),
31972
+ model: string2(row.model) || "Unknown model",
31973
+ provider: string2(row.default_provider),
31793
31974
  agent: "T3 Code",
31794
31975
  linkedSessionIDs: links.get(nativeID) || []
31795
31976
  });
31796
- const revision2 = digest([row.updated_at, counts.get(nativeID), items.get(nativeID), links.get(nativeID)]);
31977
+ const revision2 = digest([3, row.updated_at, counts.get(nativeID), items.get(nativeID), links.get(nativeID)]);
31797
31978
  sessions.push({ session, revision: revision2, locator: { path, databaseRevision, threadID: nativeID, format: "v2", metadataPartial: row.valid_payload ? "" : "1" } });
31798
31979
  }
31799
31980
  if (unreadableMetadata) warnings.push(`${unreadableMetadata} T3 Code threads had unreadable metadata; model or lineage may be unavailable.`);
@@ -31806,23 +31987,23 @@ function discoverV1(db2, path, databaseRevision) {
31806
31987
  CASE WHEN json_valid(model_selection_json) THEN substr(json_extract(model_selection_json,'$.model'),1,200) END AS model
31807
31988
  FROM projection_threads WHERE deleted_at IS NULL ORDER BY created_at, thread_id LIMIT ?`).all(MAX_THREADS + 1);
31808
31989
  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)));
31990
+ const roots2 = projectRoots(db2, selected.map((row) => string2(row.project_id)));
31991
+ const counts = aggregates(db2, "projection_thread_messages", selected.map((row) => string2(row.thread_id)));
31811
31992
  const sessions = [], projects = /* @__PURE__ */ new Map();
31812
31993
  for (const row of selected) {
31813
- const nativeID = string(row.thread_id), created = time2(row.created_at);
31994
+ const nativeID = string2(row.thread_id), created = time2(row.created_at);
31814
31995
  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);
31996
+ const directory3 = string2(row.worktree_path) || roots2.get(string2(row.project_id)) || "";
31997
+ const p = project(SOURCE, directory3);
31817
31998
  projects.set(p.id, p);
31818
- const session = blankSession(SOURCE, nativeID, directory2);
31999
+ const session = blankSession(SOURCE, nativeID, directory3);
31819
32000
  Object.assign(session, {
31820
- title: string(row.title) || "T3 Code thread",
32001
+ title: string2(row.title) || "T3 Code thread",
31821
32002
  projectID: p.id,
31822
32003
  created,
31823
32004
  updated: time2(row.updated_at) || created,
31824
32005
  archived: Boolean(row.archived_at),
31825
- model: string(row.model) || "Unknown model",
32006
+ model: string2(row.model) || "Unknown model",
31826
32007
  agent: "T3 Code"
31827
32008
  });
31828
32009
  sessions.push({ session, revision: digest([row.updated_at, counts.get(nativeID)]), locator: { path, databaseRevision, threadID: nativeID, format: "v1" } });
@@ -31831,15 +32012,15 @@ function discoverV1(db2, path, databaseRevision) {
31831
32012
  if (rows2.length > MAX_THREADS) warnings.push(`T3 Code discovery is limited to ${MAX_THREADS.toLocaleString()} threads.`);
31832
32013
  return { sessions, projects: [...projects.values()], warnings };
31833
32014
  }
31834
- function v2Message(row, directory2) {
31835
- const parsed = parsedObject(row.payload_json), item = parsed || {}, type = string(row.type), id2 = string(row.turn_item_id);
32015
+ function v2Message(row, directory3) {
32016
+ const parsed = parsedObject(row.payload_json), item = parsed || {}, type = string2(row.type), id2 = string2(row.turn_item_id);
31836
32017
  const role = type === "user_message" ? "user" : type === "assistant_message" ? "assistant" : type === "reasoning" ? "assistant" : "tool";
31837
32018
  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("_", " ");
32019
+ const recorded = Boolean(message2.time), name = string2(item.title || item.toolName) || type.replaceAll("_", " ");
31839
32020
  const fields2 = {
31840
32021
  nativeID: id2,
31841
32022
  nativeType: type,
31842
- parentID: string(item.parentItemId) || void 0,
32023
+ parentID: string2(item.parentItemId) || void 0,
31843
32024
  status: status(row.status),
31844
32025
  endTime: time2(item.completedAt) || null,
31845
32026
  timeSource: recorded ? "recorded" : "unknown"
@@ -31850,34 +32031,42 @@ function v2Message(row, directory2) {
31850
32031
  return message2;
31851
32032
  }
31852
32033
  if (type === "user_message" || type === "assistant_message") {
31853
- const body2 = string(item.text);
32034
+ const body2 = string2(item.text);
31854
32035
  if (body2) addText(message2, body2, role === "user" ? "You" : "Assistant");
31855
32036
  message2.events = [{ ...messageEvent(message2, body2, id2), ...fields2 }];
31856
32037
  if (Array.isArray(item.attachments) && item.attachments.length) message2.partial = true;
31857
32038
  return message2;
31858
32039
  }
31859
32040
  if (type === "reasoning") {
31860
- message2.events = [eventFor(message2, id2, "reasoning", "Recorded reasoning", string(item.text), fields2)];
32041
+ message2.events = [eventFor(message2, id2, "reasoning", "Recorded reasoning", string2(item.text), fields2)];
31861
32042
  return message2;
31862
32043
  }
31863
32044
  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 });
32045
+ const file = string2(item.fileName), completed = status(row.status) === "completed";
32046
+ const native = item.nativeItemRef;
32047
+ if (native?.driver === "opencode" && openCodeEditTools.has(file.toLowerCase())) {
32048
+ message2.tools.push(file);
32049
+ const kind2 = completed || fields2.status === "failed" ? "tool_result" : "tool_call";
32050
+ message2.events = [eventFor(message2, id2, kind2, file, "", { ...fields2, callID: string2(native.nativeId) || void 0 })];
32051
+ return message2;
32052
+ }
32053
+ if (file && completed) message2.files.push({ path: isAbsolute2(file) ? file : join11(directory3, file), source: "file change", steps: 1 });
31866
32054
  message2.events = [eventFor(message2, id2, "file_change", file || name, "", fields2)];
31867
32055
  return message2;
31868
32056
  }
31869
32057
  if (["command_execution", "dynamic_tool", "file_search", "web_search"].includes(type)) {
31870
32058
  const input = eventText(item.input ?? item.pattern ?? item.patterns, 32e3);
31871
- const output = eventText(item.output ?? item.results, 64e3);
32059
+ const output2 = eventText(item.output ?? item.results, 64e3);
31872
32060
  const kind2 = fields2.status === "completed" || fields2.status === "failed" ? "tool_result" : "tool_call";
31873
32061
  message2.tools.push(name);
31874
32062
  if (input) addText(message2, input, "Tool");
31875
- if (output) addText(message2, output, "Tool");
31876
- message2.events = [eventFor(message2, id2, kind2, name, "", { ...fields2, input, output })];
32063
+ if (output2) addText(message2, output2, "Tool");
32064
+ const native = item.nativeItemRef;
32065
+ 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
32066
  return message2;
31878
32067
  }
31879
32068
  const kind = type === "compaction" ? "compaction" : type === "error" ? "error" : "event";
31880
- message2.events = [eventFor(message2, id2, kind, name, string(item.text), fields2)];
32069
+ message2.events = [eventFor(message2, id2, kind, name, string2(item.text), fields2)];
31881
32070
  return message2;
31882
32071
  }
31883
32072
  function readV2(db2, candidate, cursor) {
@@ -31910,9 +32099,9 @@ function readV1(db2, candidate, cursor) {
31910
32099
  const messages = rows2.slice(0, PAGE).map((row) => {
31911
32100
  const role = row.role === "user" ? "user" : row.role === "assistant" ? "assistant" : "system";
31912
32101
  const message2 = blankMessage(`message:${row.message_id}`, time2(row.created_at), role);
31913
- const body2 = string(row.text);
32102
+ const body2 = string2(row.text);
31914
32103
  if (body2) addText(message2, body2, role === "user" ? "You" : "Assistant");
31915
- message2.events = [{ ...messageEvent(message2, body2), nativeID: string(row.message_id), nativeType: "legacy-message" }];
32104
+ message2.events = [{ ...messageEvent(message2, body2), nativeID: string2(row.message_id), nativeType: "legacy-message" }];
31916
32105
  message2.partial = row.text == null;
31917
32106
  return message2;
31918
32107
  });
@@ -32069,11 +32258,11 @@ function withStore(path, read3) {
32069
32258
  throw error;
32070
32259
  }
32071
32260
  });
32072
- const before = stats(), directory2 = mkdtempSync2(join12(tmpdir2(), "sessiongraph-cursor-"));
32261
+ const before = stats(), directory3 = mkdtempSync2(join12(tmpdir2(), "sessiongraph-cursor-"));
32073
32262
  let db2;
32074
32263
  try {
32075
- chmodSync2(directory2, 448);
32076
- const copy = join12(directory2, "store.db");
32264
+ chmodSync2(directory3, 448);
32265
+ const copy = join12(directory3, "store.db");
32077
32266
  files.forEach((file, index) => {
32078
32267
  if (before[index]) {
32079
32268
  const target = index ? `${copy}-wal` : copy;
@@ -32089,7 +32278,7 @@ function withStore(path, read3) {
32089
32278
  try {
32090
32279
  db2?.close();
32091
32280
  } finally {
32092
- rmSync3(directory2, { recursive: true, force: true });
32281
+ rmSync3(directory3, { recursive: true, force: true });
32093
32282
  }
32094
32283
  }
32095
32284
  }
@@ -32162,12 +32351,12 @@ function readCursorStore(path) {
32162
32351
  bytes2 += data.length;
32163
32352
  try {
32164
32353
  if (item.leaf) {
32165
- const json4 = data[0] === 123 ? data : fields(data).find((v3) => v3.field === 4)?.data;
32166
- if (!json4) {
32354
+ const json5 = data[0] === 123 ? data : fields(data).find((v3) => v3.field === 4)?.data;
32355
+ if (!json5) {
32167
32356
  partial = true;
32168
32357
  continue;
32169
32358
  }
32170
- const raw = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(json4));
32359
+ const raw = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(json5));
32171
32360
  const msg = cursorMessage(raw, `blob:${item.id}:${ordinal++}`);
32172
32361
  if (!msg) {
32173
32362
  partial = true;
@@ -32217,9 +32406,9 @@ var MAX_BUBBLE = 8e6;
32217
32406
  var MAX_MESSAGES = 5e4;
32218
32407
  var MAX_BYTES4 = 64e6;
32219
32408
  function decode(value) {
32220
- return object(JSON.parse(typeof value === "string" ? value : value instanceof Uint8Array ? Buffer.from(value).toString("utf8") : "{}"));
32409
+ return object2(JSON.parse(typeof value === "string" ? value : value instanceof Uint8Array ? Buffer.from(value).toString("utf8") : "{}"));
32221
32410
  }
32222
- function directory(raw) {
32411
+ function directory2(raw) {
32223
32412
  const value = text(raw.workspaceIdentifier?.uri?.path) || text(raw.workspaceIdentifier?.uri) || text(raw.cwd);
32224
32413
  try {
32225
32414
  return value.startsWith("file:") ? fileURLToPath(value) : isAbsolute3(value) ? value : "";
@@ -32246,7 +32435,7 @@ function discoverComposers(path, workspace = "") {
32246
32435
  if (!nativeID || row.key !== `composerData:${nativeID}`) throw new Error("Composer identity mismatch.");
32247
32436
  const headers = Array.isArray(data.fullConversationHeadersOnly) ? data.fullConversationHeadersOnly : Array.isArray(data.conversation) ? data.conversation : [];
32248
32437
  if (!headers.length) continue;
32249
- const session = blankSession("cursor", nativeID, directory(data) || workspace);
32438
+ const session = blankSession("cursor", nativeID, directory2(data) || workspace);
32250
32439
  session.created = cursorTime(data.createdAt);
32251
32440
  if (!session.created) continue;
32252
32441
  session.updated = cursorTime(data.lastUpdatedAt) || session.created;
@@ -32297,7 +32486,7 @@ function readComposer(candidate) {
32297
32486
  const id2 = text(header.bubbleId);
32298
32487
  const stored = id2 ? get.get(`bubbleId:${nativeID}:${id2}`, MAX_BUBBLE) : void 0;
32299
32488
  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]) };
32489
+ const raw = stored ? { ...header, ...decode(stored.value) } : { ...header, ...object2(data.conversationMap?.[id2]) };
32301
32490
  if (![1, 2].includes(raw.type)) {
32302
32491
  partial = true;
32303
32492
  continue;
@@ -32343,7 +32532,7 @@ async function stamp(path) {
32343
32532
  async function snapshot(locator) {
32344
32533
  return digest(await Promise.all([stamp(locator.path), locator.kind === "transcript" ? null : stamp(`${locator.path}-wal`), locator.meta ? stamp(locator.meta) : null]));
32345
32534
  }
32346
- async function json3(path) {
32535
+ async function json4(path) {
32347
32536
  const s = await fileStats(path);
32348
32537
  if (!s) return {};
32349
32538
  if (s.size > 128e3) throw new Error("Cursor metadata exceeds the 128 KB limit.");
@@ -32373,7 +32562,7 @@ async function workspacePaths(root3, warnings) {
32373
32562
  const database = join13(storage, entry.name, "state.vscdb");
32374
32563
  stores.set(database, "");
32375
32564
  try {
32376
- const info = await json3(join13(storage, entry.name, "workspace.json"));
32565
+ const info = await json4(join13(storage, entry.name, "workspace.json"));
32377
32566
  if (typeof info.folder === "string" && info.folder.startsWith("file:")) {
32378
32567
  const path = cwd(fileURLToPath2(info.folder));
32379
32568
  if (path) stores.set(database, path);
@@ -32433,7 +32622,7 @@ function createCursorAdapter(options = {}) {
32433
32622
  return matches.length === 1 ? matches[0] : "";
32434
32623
  };
32435
32624
  let unreadable = 0, legacy = 0, scanned = 0;
32436
- const add = async (path, id2, kind, directory2, parent2 = "", workspaceHash = "") => {
32625
+ const add = async (path, id2, kind, directory3, parent2 = "", workspaceHash = "") => {
32437
32626
  if (!validID(id2) || ++scanned > LIMIT) return;
32438
32627
  try {
32439
32628
  const stats = await fileStats(path);
@@ -32442,11 +32631,11 @@ function createCursorAdapter(options = {}) {
32442
32631
  const locator = { path, kind };
32443
32632
  if (kind !== "transcript") locator.meta = join13(path, "..", "meta.json");
32444
32633
  const before = await snapshot(locator);
32445
- const extra2 = locator.meta ? await json3(locator.meta) : {};
32634
+ const extra2 = locator.meta ? await json4(locator.meta) : {};
32446
32635
  const meta = kind === "transcript" ? {} : cursorStoreMetadata(path);
32447
32636
  if (meta.agentId && meta.agentId !== id2) throw new Error("Cursor native identity mismatch.");
32448
32637
  if (kind !== "transcript" && !meta.latestRootBlobId) return;
32449
- const session = blankSession("cursor", native, cwd(meta.cwd) || cwd(extra2.cwd) || directory2);
32638
+ const session = blankSession("cursor", native, cwd(meta.cwd) || cwd(extra2.cwd) || directory3);
32450
32639
  session.agent = kind === "cli" ? "Cursor Agent" : kind === "acp" ? "Cursor ACP" : parent2 ? "Cursor subagent" : "Cursor IDE";
32451
32640
  if (parent2) session.parentID = identity("cursor", parent2);
32452
32641
  session.title = typeof meta.name === "string" && meta.name.trim() ? meta.name : typeof extra2.title === "string" && extra2.title.trim() ? extra2.title : "Cursor session";
@@ -32503,15 +32692,15 @@ function createCursorAdapter(options = {}) {
32503
32692
  const projects = join13(root3(), "projects");
32504
32693
  for (const dir of await entries(projects, warnings)) {
32505
32694
  if (!dir.isDirectory() || scanned >= LIMIT) continue;
32506
- const transcripts = join13(projects, dir.name, "agent-transcripts"), directory2 = match2(dir.name, slug);
32695
+ const transcripts = join13(projects, dir.name, "agent-transcripts"), directory3 = match2(dir.name, slug);
32507
32696
  for (const entry of await entries(transcripts, warnings)) {
32508
32697
  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);
32698
+ if (entry.isFile() && entry.name.endsWith(".jsonl")) await add(join13(transcripts, entry.name), entry.name.slice(0, -6), "transcript", directory3);
32510
32699
  else if (entry.isFile() && entry.name.endsWith(".txt")) legacy++;
32511
32700
  else if (entry.isDirectory() && validID(entry.name)) {
32512
- await add(join13(transcripts, entry.name, `${entry.name}.jsonl`), entry.name, "transcript", directory2);
32701
+ await add(join13(transcripts, entry.name, `${entry.name}.jsonl`), entry.name, "transcript", directory3);
32513
32702
  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);
32703
+ 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
32704
  if (scanned >= LIMIT) break;
32516
32705
  }
32517
32706
  }
@@ -32520,13 +32709,13 @@ function createCursorAdapter(options = {}) {
32520
32709
  const chats = join13(root3(), "chats");
32521
32710
  for (const bucket of await entries(chats, warnings)) {
32522
32711
  if (!bucket.isDirectory() || scanned >= LIMIT) continue;
32523
- const folder = join13(chats, bucket.name), directory2 = match2(bucket.name, hashCwd);
32712
+ const folder = join13(chats, bucket.name), directory3 = match2(bucket.name, hashCwd);
32524
32713
  if (/^[a-f\d]{32}$/i.test(bucket.name) && await fileStats(join13(folder, "store.db"))) {
32525
32714
  const id2 = bucket.name.replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, "$1-$2-$3-$4-$5");
32526
32715
  await add(join13(folder, "store.db"), id2, "cli", "");
32527
32716
  }
32528
32717
  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);
32718
+ if (entry.isDirectory()) await add(join13(folder, entry.name, "store.db"), entry.name, "cli", directory3, "", bucket.name);
32530
32719
  if (scanned >= LIMIT) break;
32531
32720
  }
32532
32721
  }
@@ -32591,7 +32780,7 @@ function projectRootFile(path) {
32591
32780
  return join14(parts.slice(0, parts.lastIndexOf("chats")).join(sep3), ".project_root");
32592
32781
  }
32593
32782
  function geminiConversation(contents, lines) {
32594
- const parsed = lines ? jsonLines(contents) : { rows: [object(json2(contents))], partial: false };
32783
+ const parsed = lines ? jsonLines(contents) : { rows: [object2(json3(contents))], partial: false };
32595
32784
  let metadata2 = {};
32596
32785
  const messages = /* @__PURE__ */ new Map();
32597
32786
  const patch = (p) => {
@@ -32608,9 +32797,9 @@ function geminiConversation(contents, lines) {
32608
32797
  const ids = [...messages.keys()], index = ids.indexOf(row.$rewindTo);
32609
32798
  for (const id2 of index < 0 ? ids : ids.slice(index)) messages.delete(id2);
32610
32799
  } else if (row.$patch) {
32611
- const p = object(row.$patch);
32800
+ const p = object2(row.$patch);
32612
32801
  if (p.id) patch(p);
32613
- for (const update of Array.isArray(p.updates) ? p.updates : []) patch(object(update));
32802
+ for (const update of Array.isArray(p.updates) ? p.updates : []) patch(object2(update));
32614
32803
  for (const id2 of Array.isArray(p.removeIds) ? p.removeIds : []) messages.delete(id2);
32615
32804
  for (const id2 of Array.isArray(p.orderIds) ? p.orderIds : []) {
32616
32805
  const value = messages.get(id2);
@@ -32620,7 +32809,7 @@ function geminiConversation(contents, lines) {
32620
32809
  }
32621
32810
  }
32622
32811
  } else if (row.$set || row.sessionId) {
32623
- const update = row.$set ? object(row.$set) : row;
32812
+ const update = row.$set ? object2(row.$set) : row;
32624
32813
  metadata2 = { ...metadata2, ...update };
32625
32814
  if (Array.isArray(update.messages)) {
32626
32815
  if (row.$set) messages.clear();
@@ -32642,7 +32831,7 @@ var geminiAdapter = localFileAdapter({
32642
32831
  parse(path, files) {
32643
32832
  const { metadata: meta, records, partial } = geminiConversation(files.get(path), path.endsWith(".jsonl"));
32644
32833
  if (!text(meta.sessionId)) throw new Error("Unsupported Gemini history.");
32645
- const directory2 = (files.get(projectRootFile(path)) || "").trim().slice(0, 4096);
32834
+ const directory3 = (files.get(projectRootFile(path)) || "").trim().slice(0, 4096);
32646
32835
  const messages = records.map((raw, index) => {
32647
32836
  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
32837
  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 +32840,9 @@ var geminiAdapter = localFileAdapter({
32651
32840
  message2.tools.push(name);
32652
32841
  message2.events.push(eventFor(message2, `call:${id2}`, "tool_call", name, "", { callID: id2, input: eventText(call.args), status: "unknown" }));
32653
32842
  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");
32843
+ const output2 = eventText(call.result);
32844
+ 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" }));
32845
+ addText(message2, output2, "Tool");
32657
32846
  }
32658
32847
  }
32659
32848
  return message2;
@@ -32665,7 +32854,7 @@ var geminiAdapter = localFileAdapter({
32665
32854
  messages,
32666
32855
  parent: parent2,
32667
32856
  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}`) },
32857
+ 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
32858
  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
32859
  };
32671
32860
  }
@@ -32689,7 +32878,7 @@ var qwenAdapter = localFileAdapter({
32689
32878
  const messages = rows2.map((raw, index) => {
32690
32879
  const id2 = text(raw.uuid) || `record:${index}`;
32691
32880
  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);
32881
+ 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
32882
  for (const event of message3.events || []) if (event.kind === "tool_result") {
32694
32883
  event.status = raw.toolCallResult?.status === "success" ? "completed" : raw.toolCallResult?.status === "error" ? "failed" : "unknown";
32695
32884
  event.nativeType = text(raw.toolCallResult?.status);
@@ -32727,11 +32916,11 @@ var copilotAdapter = localFileAdapter({
32727
32916
  match: (path) => /(?:^|\/)events\.jsonl$/.test(path),
32728
32917
  parse(path, files) {
32729
32918
  const { rows: rows2, partial } = jsonLines(files.get(path));
32730
- const start = rows2.find((r) => r.type === "session.start"), meta = object(start?.data);
32919
+ const start = rows2.find((r) => r.type === "session.start"), meta = object2(start?.data);
32731
32920
  if (!text(meta.sessionId)) throw new Error("Unsupported Copilot event log.");
32732
32921
  const toolNames = new Map(rows2.filter((r) => r.type === "tool.execution_start").map((r) => [r.data?.toolCallId, text(r.data?.toolName)]));
32733
32922
  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;
32923
+ const data = object2(raw.data), kind = text(raw.type), human = kind === "user.message" && !data.isAutopilotContinuation && !data.source;
32735
32924
  const message2 = blankMessage(text(raw.id) || `record:${index}`, time(raw.timestamp), human ? "user" : kind === "assistant.message" ? "assistant" : kind.startsWith("tool.") ? "tool" : "system");
32736
32925
  if (["user.message", "assistant.message"].includes(kind)) {
32737
32926
  const content = text(data.content);
@@ -32771,7 +32960,7 @@ var copilotAdapter = localFileAdapter({
32771
32960
 
32772
32961
  // server/adapters/copilot-chat.ts
32773
32962
  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";
32963
+ import { basename as basename6, dirname as dirname4, join as join17, posix as posix2, win32 as win323 } from "node:path";
32775
32964
  import { fileURLToPath as fileURLToPath3 } from "node:url";
32776
32965
 
32777
32966
  // server/adapters/vscode-chat-log.ts
@@ -32780,7 +32969,7 @@ function vscodeChatLog(content) {
32780
32969
  for (const line of content.split("\n")) {
32781
32970
  if (!line.trim()) continue;
32782
32971
  if (++records > 5e4) throw new Error("Chat log exceeds the 50,000-operation limit.");
32783
- const entry = object(JSON.parse(line));
32972
+ const entry = object2(JSON.parse(line));
32784
32973
  if (entry.kind === 0) {
32785
32974
  if (records !== 1 || !entry.v || typeof entry.v !== "object" || Array.isArray(entry.v)) throw new Error("Invalid chat log initial state.");
32786
32975
  state2 = entry.v;
@@ -32819,14 +33008,14 @@ function vscodeChatLog(content) {
32819
33008
 
32820
33009
  // server/adapters/copilot-chat.ts
32821
33010
  function copilotChatRoots(platform = process.platform, home = homedir11(), env = process.env) {
32822
- const path = platform === "win32" ? win322 : posix;
33011
+ const path = platform === "win32" ? win323 : posix2;
32823
33012
  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
33013
  const override = sourcePath("copilot-chat") || env.SESSIONGRAPH_COPILOT_CHAT_USER_DATA_DIR;
32825
33014
  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
33015
  return users.flatMap((user) => [path.join(user, "workspaceStorage"), path.join(user, "globalStorage", "emptyWindowChatSessions")]);
32827
33016
  }
32828
33017
  function vscodeChatPath(value) {
32829
- const raw = object(value);
33018
+ const raw = object2(value);
32830
33019
  if (raw.scheme) {
32831
33020
  if (raw.scheme !== "file") return `${text(raw.scheme)}://${text(raw.authority)}${text(raw.path)}`;
32832
33021
  const path = text(raw.path);
@@ -32841,10 +33030,10 @@ function vscodeChatPath(value) {
32841
33030
  return "";
32842
33031
  }
32843
33032
  }
32844
- var markdown = (value) => typeof value === "string" ? value : text(object(value).value);
33033
+ var markdown = (value) => typeof value === "string" ? value : text(object2(value).value);
32845
33034
  var recordedTime = (value) => ({ time: time(value) || null, timeSource: time(value) ? "recorded" : "unknown" });
32846
33035
  function responsePart(message2, value, index) {
32847
- const part = object(value), kind = text(part.kind), id2 = `part:${index}`;
33036
+ const part = object2(value), kind = text(part.kind), id2 = `part:${index}`;
32848
33037
  const fields2 = { nativeType: kind || "markdown", nativeID: text(part.id) || void 0 };
32849
33038
  if (typeof value === "string" || !kind && typeof part.value === "string" || kind === "markdownContent" || kind === "markdownVuln") {
32850
33039
  const content = markdown(kind ? part.content : value);
@@ -32855,19 +33044,19 @@ function responsePart(message2, value, index) {
32855
33044
  message2.events.push(eventFor(message2, id2, "reasoning", "Recorded reasoning", content, { ...fields2, ...recordedTime(part.reasoningStartedAt) }));
32856
33045
  addText(message2, content, "Tool");
32857
33046
  } else if (kind === "toolInvocationSerialized") {
32858
- const data = object(part.toolSpecificData), command = object(data.commandLine), details = object(part.resultDetails);
33047
+ const data = object2(part.toolSpecificData), command = object2(data.commandLine), details = object2(part.resultDetails);
32859
33048
  const name = text(part.toolId) || "Tool", callID = text(part.toolCallId) || void 0;
32860
33049
  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);
33050
+ const denied = part.isConfirmed === false || [0, 5].includes(object2(part.isConfirmed).type);
32862
33051
  const status2 = denied || part.resultError ? "failed" : part.isComplete === true ? "completed" : "unknown";
32863
33052
  const correlation = { ...fields2, callID, parentID: text(part.subAgentInvocationId) || void 0 };
32864
33053
  message2.events.push(eventFor(message2, `${id2}:call`, "tool_call", name, markdown(part.invocationMessage), { ...correlation, ...recordedTime(part.startedAt), input, status: "unknown" }));
32865
33054
  message2.tools.push(name);
32866
33055
  addText(message2, input, "Tool");
32867
33056
  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");
33057
+ const output2 = eventText(part.resultError || (denied ? "Tool invocation was denied or skipped." : details.output ?? part.resultDetails ?? markdown(part.pastTenseMessage)));
33058
+ message2.events.push(eventFor(message2, `${id2}:result`, "tool_result", name, markdown(part.pastTenseMessage), { ...correlation, ...recordedTime(part.completedAt), role: "tool", output: output2, status: status2 }));
33059
+ addText(message2, output2, "Tool");
32871
33060
  } else message2.partial = true;
32872
33061
  } else {
32873
33062
  message2.events.push(eventFor(message2, id2, "event", kind || "Unsupported chat content", eventText(part), { ...fields2, partial: true }));
@@ -32880,7 +33069,7 @@ function chatMessages(requests) {
32880
33069
  const requestID = text(request.requestId) || `request:${index}`;
32881
33070
  const injected = Boolean(request.isSystemInitiated || request.hiddenFromTranscript || request.requestHiddenFromTranscript);
32882
33071
  const user = blankMessage(requestID, time(request.timestamp), injected ? "system" : "user");
32883
- const content = typeof request.message === "string" ? request.message : text(object(request.message).text);
33072
+ const content = typeof request.message === "string" ? request.message : text(object2(request.message).text);
32884
33073
  user.events = [eventFor(user, "message", injected ? "event" : "message", injected ? "Injected message" : "User message", content, { nativeID: requestID, ...recordedTime(request.timestamp) })];
32885
33074
  addText(user, content, injected ? "Tool" : "You");
32886
33075
  if (request.variableData?.variables?.length) user.partial = true;
@@ -32923,13 +33112,13 @@ var filesAdapter = localFileAdapter({
32923
33112
  extras: (path) => [...basename6(dirname4(path)) === "chatSessions" ? [join17(dirname4(dirname4(path)), "workspace.json")] : [], ...path.endsWith(".json") ? [`${path}l`] : []],
32924
33113
  parse(path, files) {
32925
33114
  const log = path.endsWith(".jsonl") ? path : `${path}l`;
32926
- const data = files.has(log) ? vscodeChatLog(files.get(log)) : object(JSON.parse(files.get(path)));
33115
+ const data = files.has(log) ? vscodeChatLog(files.get(log)) : object2(JSON.parse(files.get(path)));
32927
33116
  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
33117
  if (data.sessionId !== basename6(path).replace(/\.jsonl?$/, "")) throw new Error("VS Code chat identity mismatch.");
32929
33118
  if (!data.requests.length) return;
32930
33119
  if (data.requests.length > 25e3) throw new Error("Chat exceeds the 50,000-message limit.");
32931
33120
  const workspacePath = join17(dirname4(dirname4(path)), "workspace.json");
32932
- const workspace = files.has(workspacePath) ? object(JSON.parse(files.get(workspacePath))) : {};
33121
+ const workspace = files.has(workspacePath) ? object2(JSON.parse(files.get(workspacePath))) : {};
32933
33122
  const messages = chatMessages(data.requests);
32934
33123
  const model = [...data.requests].reverse().find((r) => text(r.modelId));
32935
33124
  return {
@@ -32964,15 +33153,15 @@ function taskAdapter(id2, name, extension, env) {
32964
33153
  match: (path) => /^[^/]+\/api_conversation_history\.json$/.test(path) || id2 === "cline" && /^[^/]+\/[^/]+\.messages\.json$/.test(path),
32965
33154
  extras: (path) => ["history_item.json", "task_metadata.json", "session.json"].map((file) => join18(dirname5(path), file)),
32966
33155
  parse(path, files) {
32967
- const sdk = path.endsWith(".messages.json"), value = json2(files.get(path));
32968
- const records = sdk ? object(value).messages : value;
33156
+ const sdk = path.endsWith(".messages.json"), value = json3(files.get(path));
33157
+ const records = sdk ? object2(value).messages : value;
32969
33158
  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);
33159
+ const read3 = (name2) => object2(files.has(join18(dirname5(path), name2)) ? json3(files.get(join18(dirname5(path), name2))) : void 0);
32971
33160
  const history = read3("history_item.json"), info = read3("session.json"), task = read3("task_metadata.json");
32972
33161
  const nativeID = sdk ? value.sessionId : basename7(dirname5(path));
32973
33162
  if (history.id && history.id !== nativeID || info.session_id && info.session_id !== nativeID) throw new Error("Task metadata identity mismatch.");
32974
33163
  const messages = records.map((raw, index) => {
32975
- const row = object(raw), message2 = conversationMessage(row, `record:${index}`);
33164
+ const row = object2(raw), message2 = conversationMessage(row, `record:${index}`);
32976
33165
  if (row.isSummary || row.isTruncationMarker || row.type === "reasoning") {
32977
33166
  message2.role = "system";
32978
33167
  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 +33197,17 @@ var continueAdapter = localFileAdapter({
33008
33197
  extras: (path) => [join18(dirname5(path), "sessions.json")],
33009
33198
  revisionExtras: false,
33010
33199
  parse(path, files) {
33011
- const value = object(json2(files.get(path)));
33200
+ const value = object2(json3(files.get(path)));
33012
33201
  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)) : {};
33202
+ const indexPath = join18(dirname5(path), "sessions.json"), index = files.has(indexPath) ? json3(files.get(indexPath)) : [];
33203
+ const meta = Array.isArray(index) ? object2(index.find((r) => r.sessionId === value.sessionId)) : {};
33015
33204
  const messages = value.history.map((item, i) => {
33016
- const row = object(item), raw = object(row.message), message2 = conversationMessage(raw, `record:${i}`);
33205
+ const row = object2(item), raw = object2(row.message), message2 = conversationMessage(raw, `record:${i}`);
33017
33206
  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
33207
  if (row.conversationSummary) message2.events.push(eventFor(message2, "summary", "compaction", "Conversation summary", text(row.conversationSummary)));
33019
33208
  return message2;
33020
33209
  });
33021
- const usage = object(value.usage);
33210
+ const usage = object2(value.usage);
33022
33211
  return {
33023
33212
  nativeID: value.sessionId,
33024
33213
  messages,
@@ -33048,7 +33237,7 @@ var harnessRoots = (id2, defaults) => () => {
33048
33237
  // server/adapters/harness-extra-formats.ts
33049
33238
  import { basename as basename8, dirname as dirname6, join as join20 } from "node:path";
33050
33239
  function kiroHistory(path, files) {
33051
- const header = object(json2(files.get(path)));
33240
+ const header = object2(json3(files.get(path)));
33052
33241
  const ide2 = basename8(path) === "session.json";
33053
33242
  const nativeID = text(header.session_id || header.sessionId || header.id) || (ide2 ? basename8(dirname6(path)) : "");
33054
33243
  if (!nativeID) throw new Error("Unsupported Kiro session header.");
@@ -33057,12 +33246,12 @@ function kiroHistory(path, files) {
33057
33246
  const { rows: rows2 } = jsonLines(files.get(side));
33058
33247
  const messages = rows2.flatMap((r, i) => {
33059
33248
  if (ide2) {
33060
- const p = object(r.payload || r);
33249
+ const p = object2(r.payload || r);
33061
33250
  const role2 = p.type === "human" ? "user" : p.type === "ai" ? "assistant" : p.role || p.type;
33062
33251
  const m3 = message({ ...p, role: role2 }, text(p.id) || `message:${i}`, r.timestamp);
33063
33252
  return m3 ? [m3] : [recordEvent(r, `event:${i}`, text(p.type) || "Kiro event", r.timestamp, p.text)];
33064
33253
  }
33065
- const data = object(r.data), role = r.kind === "Prompt" ? "user" : r.kind === "AssistantMessage" ? "assistant" : r.kind === "ToolResults" ? "tool" : "";
33254
+ const data = object2(r.data), role = r.kind === "Prompt" ? "user" : r.kind === "AssistantMessage" ? "assistant" : r.kind === "ToolResults" ? "tool" : "";
33066
33255
  if (!role) return [];
33067
33256
  const content = Array.isArray(data.content) ? data.content.map((p) => p.kind === "text" ? { type: "text", text: p.data } : { type: "unsupported" }) : void 0;
33068
33257
  const m = message({ role, content }, text(data.message_id) || `message:${i}`, seconds(data.meta?.timestamp));
@@ -33106,7 +33295,7 @@ function muxHistory(path, files) {
33106
33295
  function devinDesktopHistory(path, files) {
33107
33296
  const { rows: rows2 } = jsonLines(files.get(path));
33108
33297
  const normalized = rows2.flatMap((r) => {
33109
- const n = object(r.notification);
33298
+ const n = object2(r.notification);
33110
33299
  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
33300
  });
33112
33301
  const history = acpHistory(path, normalized.map((r) => JSON.stringify(r)).join("\n"));
@@ -33151,7 +33340,7 @@ function museHistory(path, files) {
33151
33340
  if (!meta || ids.size > 1) throw new Error("Unsupported Muse stream.");
33152
33341
  const nativeID = [...ids][0] || basename9(dirname7(path));
33153
33342
  const messages = rows2.flatMap((r, i) => {
33154
- const event = object(r.payload?.event), body2 = object(event.message);
33343
+ const event = object2(r.payload?.event), body2 = object2(event.message);
33155
33344
  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
33345
  const m = message(body2, nativeText(r.sequence) || `record:${i}`, at2);
33157
33346
  if (m) return [m];
@@ -33168,7 +33357,7 @@ function museHistory(path, files) {
33168
33357
  function junieHistory(path, files) {
33169
33358
  const { rows: rows2 } = jsonLines(files.get(path));
33170
33359
  const messages = rows2.flatMap((r, i) => {
33171
- const e10 = object(r.event?.agentEvent || r.event), kind = text(e10.kind);
33360
+ const e10 = object2(r.event?.agentEvent || r.event), kind = text(e10.kind);
33172
33361
  if (!kind || /State|Snapshot/.test(kind)) return [];
33173
33362
  return [recordEvent(r, text(r.id) || `event:${i}`, kind, r.timestampMs, e10.text ?? e10.prompt ?? e10.message)];
33174
33363
  });
@@ -33176,16 +33365,16 @@ function junieHistory(path, files) {
33176
33365
  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
33366
  }
33178
33367
  function augmentHistory(path, files) {
33179
- const r = object(json2(files.get(path)));
33368
+ const r = object2(json3(files.get(path)));
33180
33369
  if (!text(r.sessionId) || !Array.isArray(r.chatHistory)) throw new Error("Unsupported Augment session.");
33181
33370
  const messages = r.chatHistory.flatMap((turn, i) => {
33182
- const exchange = object(turn.exchange), id2 = nativeText(turn.sequenceId) || `turn:${i}`;
33371
+ const exchange = object2(turn.exchange), id2 = nativeText(turn.sequenceId) || `turn:${i}`;
33183
33372
  return [recordEvent(turn, id2, turn.completed === true ? "Completed exchange" : "Incomplete exchange", turn.finishedAt, exchange.response_text)];
33184
33373
  });
33185
33374
  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
33375
  }
33187
33376
  function fxHistory(path, files) {
33188
- const usage = object(json2(files.get(path))), meta = sidecar2(files, join21(dirname7(path), "session.json"));
33377
+ const usage = object2(json3(files.get(path))), meta = sidecar2(files, join21(dirname7(path), "session.json"));
33189
33378
  const id2 = text(usage.session_id) || text(meta.id);
33190
33379
  if (!id2 || !usage.snapshot || meta.id && meta.id !== id2) throw new Error("Unsupported Fx session metadata.");
33191
33380
  return {
@@ -33230,7 +33419,7 @@ var definitions = [
33230
33419
  const value = f.get(p), { rows: rows2 } = jsonLines(value), ids = new Set(rows2.map((r) => text(r.sessionId)).filter(Boolean));
33231
33420
  if (ids.size !== 1) throw new Error("Headless capture needs one explicit session identity.");
33232
33421
  const messages = rows2.flatMap((r, i) => {
33233
- const m = message(object(r.message), text(r.message?.id) || `record:${i}`);
33422
+ const m = message(object2(r.message), text(r.message?.id) || `record:${i}`);
33234
33423
  return m ? [m] : [];
33235
33424
  });
33236
33425
  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 +33514,9 @@ var openclaw = {
33325
33514
  parse(db2, r) {
33326
33515
  const events = rows(db2, "transcript_events", ["seq", "event_json", "event_zstd"], ["session_id", r.session_id], "seq");
33327
33516
  const messages = events.flatMap((e10) => {
33328
- const raw = object(sqliteJSON(e10.event_json ?? e10.event_zstd));
33517
+ const raw = object2(sqliteJSON(e10.event_json ?? e10.event_zstd));
33329
33518
  if (raw.type !== "message") return [];
33330
- const m = message(object(raw.message), text(raw.id) || `event:${e10.seq}`, raw.timestamp ?? raw.message?.timestamp);
33519
+ const m = message(object2(raw.message), text(raw.id) || `event:${e10.seq}`, raw.timestamp ?? raw.message?.timestamp);
33331
33520
  return m ? [m] : [];
33332
33521
  });
33333
33522
  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 +33533,7 @@ function forkStore(id2, name, defaultPath, desktop) {
33344
33533
  parse(db2, r) {
33345
33534
  if (desktop !== void 0 && text(r.version).startsWith("desktop-") !== desktop) return;
33346
33535
  const messages = rows(db2, "message", ["id", "data", "time_created"], ["session_id", r.id], "time_created").map((m) => {
33347
- const body2 = object(sqliteJSON(m.data));
33536
+ const body2 = object2(sqliteJSON(m.data));
33348
33537
  let content = body2.parts ?? body2.content;
33349
33538
  if (hasTable(db2, "part")) content = rows(db2, "part", ["id", "data"], ["message_id", m.id], "id").map((p) => sqliteJSON(p.data));
33350
33539
  if (Array.isArray(content)) content = content.flatMap((p) => {
@@ -33369,11 +33558,11 @@ var zed = {
33369
33558
  fields: ["id", "summary", "created_at", "updated_at", "data_type", "data", "folder_paths"],
33370
33559
  parse(db2, r) {
33371
33560
  if (!["json", "zstd"].includes(r.data_type)) throw new Error("Unsupported Zed encoding.");
33372
- const body2 = object(sqliteJSON(r.data));
33561
+ const body2 = object2(sqliteJSON(r.data));
33373
33562
  if (body2.imported === true) return;
33374
33563
  if (!Array.isArray(body2.messages)) throw new Error("Unsupported Zed thread.");
33375
33564
  const messages = body2.messages.map((raw, i) => {
33376
- const user = object(raw.User), agent = object(raw.Agent), b = raw.User ? user : agent;
33565
+ const user = object2(raw.User), agent = object2(raw.Agent), b = raw.User ? user : agent;
33377
33566
  if (!raw.User && !raw.Agent) return recordEvent(raw, `message:${i}`, "Context checkpoint", 0, raw.Compaction?.Summary);
33378
33567
  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
33568
  return conversationMessage({ role: raw.User ? "user" : "assistant", content }, text(b.id) || `message:${i}`);
@@ -33391,7 +33580,7 @@ var devin = {
33391
33580
  fields: ["id", "working_directory", "model", "title", "created_at", "last_activity_at"],
33392
33581
  parse(db2, r) {
33393
33582
  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));
33583
+ const raw = object2(sqliteJSON(m.chat_message)), result = message(raw, nativeText(m.node_id), millisOrSeconds(m.created_at));
33395
33584
  return result ? [result] : [recordEvent(raw, nativeText(m.node_id), "Devin message node", millisOrSeconds(m.created_at))];
33396
33585
  });
33397
33586
  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 +33643,9 @@ var octofriend = {
33454
33643
  const row = rows(db2, "llm_irs", ["json"], ["id", item.llm_ir_id], void 0, 1)[0];
33455
33644
  bytes2 += text(row?.json).length;
33456
33645
  if (bytes2 > 32e6) throw new Error("Octofriend session exceeds the snapshot limit.");
33457
- const payload = object(sqliteJSON(row?.json));
33646
+ const payload = object2(sqliteJSON(row?.json));
33458
33647
  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;
33648
+ 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
33649
  const m = message({ ...ir, content, role: ir.role === "tool-output" ? "tool" : ir.role }, nativeText(node.id), node.created_at);
33461
33650
  messages.push(m || recordEvent(ir, nativeText(node.id), text(ir.role), node.created_at));
33462
33651
  }
@@ -33490,13 +33679,13 @@ var kiro = {
33490
33679
  key: "conversation_id",
33491
33680
  fields: ["key", "conversation_id", "value"],
33492
33681
  parse(db2, r) {
33493
- const body2 = object(sqliteJSON(r.value));
33682
+ const body2 = object2(sqliteJSON(r.value));
33494
33683
  if (!Array.isArray(body2.history)) throw new Error("Unsupported Kiro conversation.");
33495
33684
  const messages = body2.history.flatMap((turn, i) => {
33496
- const result = [], input = object(turn.user?.content), output = object(turn.assistant?.Response || turn.assistant?.ToolUse);
33685
+ const result = [], input = object2(turn.user?.content), output2 = object2(turn.assistant?.Response || turn.assistant?.ToolUse);
33497
33686
  if (typeof input.Prompt?.prompt === "string") result.push(conversationMessage({ role: "user", content: input.Prompt.prompt }, `turn:${i}:user`));
33498
33687
  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`));
33688
+ 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
33689
  return result;
33501
33690
  });
33502
33691
  const created = body2.history.map((t) => time(t.request_metadata?.request_start_timestamp_ms)).find(Boolean);
@@ -33521,7 +33710,6 @@ var databaseHarnessAdapters = [
33521
33710
  // server/adapters/harness-metadata.ts
33522
33711
  import { basename as basename10 } from "node:path";
33523
33712
  import { fileURLToPath as fileURLToPath4 } from "node:url";
33524
- import { lstat as lstat7 } from "node:fs/promises";
33525
33713
  function protoFields(value) {
33526
33714
  if (value.length > 2e6) throw new Error("Trajectory metadata exceeds 2 MB.");
33527
33715
  const fields2 = /* @__PURE__ */ new Map();
@@ -33568,15 +33756,15 @@ var antigravityDatabaseAdapters = ["antigravity-cli", "antigravity-extension"].m
33568
33756
  const sec = timestamp.get(1), nano = timestamp.get(2);
33569
33757
  const created = typeof sec === "bigint" && sec > 0n && sec < 8640000000000n ? time(Number(sec) * 1e3 + (typeof nano === "bigint" && nano < 1000000000n ? Number(nano) / 1e6 : 0)) : 0;
33570
33758
  const uri = nested(fields2.get(1)).get(1);
33571
- let directory2 = "";
33759
+ let directory3 = "";
33572
33760
  if (uri instanceof Uint8Array) {
33573
33761
  try {
33574
- directory2 = fileURLToPath4(Buffer.from(uri).toString("utf8"));
33762
+ directory3 = fileURLToPath4(Buffer.from(uri).toString("utf8"));
33575
33763
  } catch {
33576
33764
  }
33577
33765
  }
33578
33766
  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." };
33767
+ 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
33768
  }
33581
33769
  }));
33582
33770
  var antigravityCacheAdapter = localFileAdapter({
@@ -33595,31 +33783,9 @@ var antigravityCacheAdapter = localFileAdapter({
33595
33783
  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
33784
  }
33597
33785
  });
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
33786
 
33621
33787
  // server/adapters/index.ts
33622
- var extra = [...databaseHarnessAdapters, ...fileHarnessAdapters, antigravityCacheAdapter, ...antigravityDatabaseAdapters, ...usageOnlyAdapters];
33788
+ var extra = [...databaseHarnessAdapters, ...fileHarnessAdapters, antigravityCacheAdapter, ...antigravityDatabaseAdapters];
33623
33789
  var grouped = /* @__PURE__ */ new Map();
33624
33790
  for (const adapter of extra) grouped.set(adapter.id, [...grouped.get(adapter.id) || [], adapter]);
33625
33791
  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 +33820,160 @@ function validRecord(value, session) {
33654
33820
 
33655
33821
  // server/event-store.ts
33656
33822
  import { randomUUID } from "node:crypto";
33823
+
33824
+ // packages/core/src/commits.ts
33825
+ var abbreviatedSHA = (sha) => sha.length !== 40 && sha.length !== 64;
33826
+
33827
+ // server/library-query.ts
33828
+ import { createHash as createHash4 } from "node:crypto";
33829
+
33830
+ // packages/core/src/layout.ts
33831
+ var directoryPath = (directory3) => (/^(?:[a-z]:[\\/]|\\\\)/i.test(directory3) ? directory3.replace(/\\/g, "/") : directory3).replace(/\/+$/, "") || (directory3.startsWith("/") ? "/" : "");
33832
+ var laneKey = (session) => session.directory ? JSON.stringify(["directory", directoryPath(session.directory)]) : JSON.stringify(["project", session.source || "opencode", session.projectID || session.id]);
33833
+
33834
+ // src/session-links.ts
33835
+ function visibleSessions(sessions) {
33836
+ const owners = /* @__PURE__ */ new Map();
33837
+ for (const session of sessions) {
33838
+ if (session.source !== "t3-code") continue;
33839
+ for (const id2 of new Set(session.linkedSessionIDs || [])) owners.set(id2, [...owners.get(id2) || [], session]);
33840
+ }
33841
+ const unique = new Map([...owners].flatMap(([native, claims]) => {
33842
+ const owner = claims[0];
33843
+ return claims.length === 1 && ["complete", "partial"].includes(owner.coverage?.history || "") && owner.activity?.userMessages ? [[native, owner.id]] : [];
33844
+ }));
33845
+ return sessions.filter((session) => !unique.has(session.id)).map((session) => ({
33846
+ ...session,
33847
+ parentID: session.parentID ? unique.get(session.parentID) || session.parentID : void 0,
33848
+ forkID: session.forkID ? unique.get(session.forkID) || session.forkID : void 0
33849
+ }));
33850
+ }
33851
+
33852
+ // server/library-query.ts
33853
+ var LibraryError = class extends Error {
33854
+ constructor(code, message2, exitCode2 = 1) {
33855
+ super(message2);
33856
+ this.code = code;
33857
+ this.exitCode = exitCode2;
33858
+ }
33859
+ code;
33860
+ exitCode;
33861
+ };
33862
+ function invalid(message2) {
33863
+ throw new LibraryError("INVALID_ARGUMENT", message2, 2);
33864
+ }
33865
+ var fingerprint = (value) => createHash4("sha256").update(JSON.stringify(value)).digest("hex");
33866
+ function pageLimit(value = 50) {
33867
+ if (!Number.isSafeInteger(value) || value < 1 || value > 200) invalid("Limit must be an integer from 1 to 200.");
33868
+ return value;
33869
+ }
33870
+ function pageOffset(cursor, key) {
33871
+ if (!cursor) return 0;
33872
+ let parsed;
33873
+ try {
33874
+ if (cursor.length > 512 || !/^[\w-]+$/.test(cursor)) throw new Error();
33875
+ parsed = JSON.parse(Buffer.from(cursor, "base64url").toString());
33876
+ if (!parsed || !Number.isSafeInteger(parsed.offset) || parsed.offset < 0 || typeof parsed.key !== "string") throw new Error();
33877
+ } catch {
33878
+ return invalid("Invalid cursor. Use nextCursor from the previous response.");
33879
+ }
33880
+ if (parsed.key !== key) throw new LibraryError("STALE_CURSOR", "Saved history or query changed. Restart without --cursor.");
33881
+ return parsed.offset;
33882
+ }
33883
+ var nextCursor = (key, offset) => Buffer.from(JSON.stringify({ key, offset })).toString("base64url");
33884
+
33885
+ // server/commit-store.ts
33886
+ var COMMIT_SCHEMA = `CREATE TABLE IF NOT EXISTS session_commits (
33887
+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
33888
+ sha TEXT NOT NULL, repository_path TEXT NOT NULL, operation TEXT NOT NULL,
33889
+ occurred_at REAL, evidence_event_id TEXT NOT NULL,
33890
+ PRIMARY KEY(session_id,repository_path,sha,operation),
33891
+ FOREIGN KEY(session_id,evidence_event_id) REFERENCES timeline_items(session_id,id) ON DELETE CASCADE);
33892
+ CREATE INDEX IF NOT EXISTS session_commits_time ON session_commits(session_id,occurred_at);`;
33893
+ var supported = /* @__PURE__ */ new Set(["opencode", "t3-code", "codex", "claude-code"]);
33894
+ var pendingCommits = () => ({ version: 0, state: "pending", count: null, note: "Refresh sources to index recorded commit operations." });
33895
+ function writeCommits(db2, session) {
33896
+ db2.prepare("DELETE FROM session_commits WHERE session_id=?").run(session.id);
33897
+ const base = { version: COMMIT_EXTRACTOR_VERSION, indexedAt: Date.now() };
33898
+ if (!supported.has(session.source || "")) return { ...base, state: "unavailable", count: null, note: "Commit attribution is not validated for this source format." };
33899
+ const calls = /* @__PURE__ */ new Map();
33900
+ const results = /* @__PURE__ */ new Map();
33901
+ 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);
33902
+ let tools = 0, partial = session.coverage?.history !== "complete" || Boolean(db2.prepare("SELECT partial FROM timeline_coverage WHERE session_id=?").get(session.id)?.partial);
33903
+ for (const row of rows2()) {
33904
+ const item = JSON.parse(String(row.data));
33905
+ tools++;
33906
+ if (item.kind === "tool_result" && item.callID) {
33907
+ const signature = fingerprint([item.output, item.exitCode, item.status, item.gitCommit]);
33908
+ results.set(item.callID, results.has(item.callID) && results.get(item.callID) !== signature ? null : signature);
33909
+ }
33910
+ if (item.kind !== "tool_call" || !item.callID) continue;
33911
+ calls.set(item.callID, calls.has(item.callID) ? null : item);
33912
+ }
33913
+ const completed = /* @__PURE__ */ new Set();
33914
+ const insert = db2.prepare("INSERT OR IGNORE INTO session_commits VALUES (?,?,?,?,?,?)");
33915
+ for (const row of rows2()) {
33916
+ const item = JSON.parse(String(row.data));
33917
+ if (item.kind !== "tool_result") continue;
33918
+ const call = item.input ? item : item.callID ? calls.get(item.callID) : void 0;
33919
+ if (!call || call !== item && call.ordinal >= item.ordinal || item.callID && results.get(item.callID) === null) {
33920
+ partial = true;
33921
+ continue;
33922
+ }
33923
+ if (item.callID) completed.add(item.callID);
33924
+ const extracted = extractCommit(call, item);
33925
+ if (!extracted.candidate) continue;
33926
+ const time4 = item.endTime ?? item.time;
33927
+ if (time4 !== null && time4 < session.created || session.forkID && (time4 === null || time4 <= session.created || call.time === null || call.time < session.created)) {
33928
+ partial = true;
33929
+ continue;
33930
+ }
33931
+ if (!extracted.commit) {
33932
+ partial = true;
33933
+ continue;
33934
+ }
33935
+ const { sha, repositoryPath, operation: operation2 } = extracted.commit;
33936
+ insert.run(session.id, sha, repositoryPath, operation2, time4, item.id);
33937
+ }
33938
+ 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;
33939
+ const count = Number(db2.prepare("SELECT count(*) AS n FROM session_commits WHERE session_id=?").get(session.id).n);
33940
+ return {
33941
+ ...base,
33942
+ state: !tools ? "unavailable" : partial ? "partial" : "indexed",
33943
+ count: !tools ? null : count,
33944
+ 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.`
33945
+ };
33946
+ }
33947
+ function commit(row) {
33948
+ 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) };
33949
+ }
33950
+ function readCommits(db2, session, options = {}) {
33951
+ let coverage2 = session.commits || pendingCommits();
33952
+ if (session.coverage?.note?.startsWith("Latest import failed:")) coverage2 = { ...coverage2, state: coverage2.count === null ? coverage2.state : "partial", note: `${session.coverage.note} ${coverage2.note}` };
33953
+ const revision2 = String(db2.prepare("SELECT revision FROM timeline_coverage WHERE session_id=?").get(session.id)?.revision || "pending");
33954
+ const key = fingerprint(["commits", session.id, revision2, coverage2]), offset = pageOffset(options.cursor, key), limit = pageLimit(options.limit);
33955
+ const total = Number(db2.prepare("SELECT count(*) AS n FROM session_commits WHERE session_id=?").get(session.id).n);
33956
+ 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);
33957
+ return { sessionID: session.id, revision: revision2, coverage: coverage2, items, total, nextCursor: offset + limit < total ? nextCursor(key, offset + limit) : null };
33958
+ }
33959
+ function commitMarkers(db2, session) {
33960
+ const end = Math.max(session.created, session.activity?.lastMessageAt || session.created);
33961
+ 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) => {
33962
+ const value = commit(row);
33963
+ return {
33964
+ id: value.evidenceEventID,
33965
+ kind: "commit",
33966
+ name: `${value.operation} ${value.sha}`,
33967
+ time: value.occurredAt,
33968
+ timeSource: "recorded",
33969
+ ordinal,
33970
+ preview: `${value.repositoryPath}
33971
+ ${abbreviatedSHA(value.sha) ? "Abbreviated SHA \xB7 " : ""}Open recorded execution evidence`
33972
+ };
33973
+ });
33974
+ }
33975
+
33976
+ // server/event-store.ts
33657
33977
  var EVENT_SCHEMA = `CREATE TABLE IF NOT EXISTS timeline_items (
33658
33978
  session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, id TEXT NOT NULL, message_id TEXT NOT NULL,
33659
33979
  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 +34025,8 @@ function readEventMarkers(db2, session) {
33705
34025
  const end = Math.max(session.created, session.activity?.lastMessageAt || session.created);
33706
34026
  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
34027
  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 };
34028
+ const commits = commitMarkers(db2, session);
34029
+ 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
34030
  }
33710
34031
  function readEvents(db2, session, options = {}) {
33711
34032
  const state2 = coverage(db2, session), filter = options.filter || "all", size = 60;
@@ -33825,64 +34146,6 @@ function normalizeViewState(value) {
33825
34146
  return result;
33826
34147
  }
33827
34148
 
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
34149
  // server/store.ts
33887
34150
  var SessionGraphStore = class {
33888
34151
  constructor(path = databasePath()) {
@@ -33892,7 +34155,7 @@ var SessionGraphStore = class {
33892
34155
  if (path !== ":memory:") chmodSync3(path, 384);
33893
34156
  this.db.exec("PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;");
33894
34157
  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.");
34158
+ if (version > 6) throw new Error("This SessionGraph database requires a newer version of the app.");
33896
34159
  this.db.exec(`
33897
34160
  CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT NOT NULL);
33898
34161
  CREATE TABLE IF NOT EXISTS sources (id TEXT PRIMARY KEY, last_import INTEGER, error TEXT);
@@ -33940,6 +34203,35 @@ var SessionGraphStore = class {
33940
34203
  throw error;
33941
34204
  }
33942
34205
  }
34206
+ if (version < 5) {
34207
+ this.db.exec("BEGIN IMMEDIATE");
34208
+ try {
34209
+ this.db.exec(COMMIT_SCHEMA);
34210
+ this.db.prepare("UPDATE sessions SET metadata=json_set(metadata,'$.commits',json(?))").run(JSON.stringify(pendingCommits()));
34211
+ this.db.exec("PRAGMA user_version=5; COMMIT");
34212
+ } catch (error) {
34213
+ this.db.exec("ROLLBACK");
34214
+ throw error;
34215
+ }
34216
+ }
34217
+ if (version < 6) {
34218
+ this.db.exec("BEGIN IMMEDIATE");
34219
+ try {
34220
+ const retired = /* @__PURE__ */ new Set(["reasonix", "trae", "warp", "lm-studio", "hindsight"]);
34221
+ const selected = this.setting("selected");
34222
+ if (selected) this.setting("selected", selected.filter((id2) => !retired.has(id2)));
34223
+ const paths2 = this.setting("sourcePaths");
34224
+ if (paths2) this.setting("sourcePaths", Object.fromEntries(Object.entries(paths2).filter(([id2]) => !retired.has(id2))));
34225
+ const view = this.setting("viewState");
34226
+ if (view && typeof view.sourceID === "string" && retired.has(view.sourceID)) this.setting("viewState", { ...view, sourceID: "" });
34227
+ const remove = this.db.prepare("DELETE FROM sources WHERE id=?");
34228
+ for (const id2 of retired) remove.run(id2);
34229
+ this.db.exec("PRAGMA user_version=6; COMMIT");
34230
+ } catch (error) {
34231
+ this.db.exec("ROLLBACK");
34232
+ throw error;
34233
+ }
34234
+ }
33943
34235
  if (!this.setting("libraryID")) this.setting("libraryID", randomUUID2());
33944
34236
  }
33945
34237
  path;
@@ -33993,6 +34285,9 @@ var SessionGraphStore = class {
33993
34285
  revision(id2) {
33994
34286
  return this.db.prepare("SELECT imported_revision FROM sessions WHERE id=?").get(id2)?.imported_revision;
33995
34287
  }
34288
+ commitsCurrent(id2) {
34289
+ return this.getSession(id2)?.commits?.version === COMMIT_EXTRACTOR_VERSION;
34290
+ }
33996
34291
  upsert(candidate) {
33997
34292
  const s = candidate.session, previous = this.getSession(s.id);
33998
34293
  const metadata2 = {
@@ -34000,6 +34295,7 @@ var SessionGraphStore = class {
34000
34295
  model: s.model === "Unknown model" ? previous?.model || s.model : s.model,
34001
34296
  parentID: previous?.parentID && candidate.locator.agent ? previous.parentID : s.parentID,
34002
34297
  activity: previous?.activity,
34298
+ commits: previous?.commits || pendingCommits(),
34003
34299
  revision: previous?.revision || "",
34004
34300
  coverage: previous?.coverage || { history: "pending" }
34005
34301
  };
@@ -34014,8 +34310,9 @@ var SessionGraphStore = class {
34014
34310
  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
34311
  messages.forEach((message2, i) => insert.run(s.id, message2.id, i, JSON.stringify(message2), messageTime(message2.time), Number(isUserMessage(message2))));
34016
34312
  writeEvents(this.db, s.id, this.db.prepare("SELECT data FROM messages WHERE session_id=? ORDER BY ordinal").iterate(s.id));
34313
+ const commits = writeCommits(this.db, s);
34017
34314
  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);
34315
+ this.db.prepare("UPDATE sessions SET metadata=?, imported_revision=?, locator=? WHERE id=?").run(JSON.stringify({ ...s, activity, commits }), candidate.revision, JSON.stringify(candidate.locator), s.id);
34019
34316
  this.db.prepare("DELETE FROM search_cache WHERE id=?").run(s.id);
34020
34317
  this.db.exec("COMMIT");
34021
34318
  } catch (error) {
@@ -34104,6 +34401,9 @@ var SessionGraphStore = class {
34104
34401
  eventMarkers(id2) {
34105
34402
  return this.readSnapshot(id2, (session) => readEventMarkers(this.db, session));
34106
34403
  }
34404
+ commits(id2, options = {}) {
34405
+ return this.readSnapshot(id2, (session) => readCommits(this.db, session, options));
34406
+ }
34107
34407
  readSnapshot(id2, read3) {
34108
34408
  this.db.exec("BEGIN");
34109
34409
  try {
@@ -34305,13 +34605,14 @@ var Importer = class {
34305
34605
  this.status.errors.push(...discovery.warnings);
34306
34606
  for (const project2 of discovery.projects) this.store.db.prepare("INSERT INTO projects VALUES (?,?,?) ON CONFLICT(id) DO UPDATE SET data=excluded.data").run(project2.id, adapter.id, JSON.stringify(project2));
34307
34607
  for (const candidate of seen.values()) {
34308
- this.store.upsert(candidate);
34309
34608
  const saved = this.store.getSession(candidate.session.id);
34310
- const retry = !saved?.coverage?.importedAt || saved.coverage.note?.startsWith("Latest import failed:");
34609
+ const retry = !saved?.coverage?.importedAt || saved.coverage.note?.startsWith("Latest import failed:") || !this.store.commitsCurrent(candidate.session.id);
34311
34610
  if (!retry && saved?.revision === candidate.revision && this.store.revision(candidate.session.id) === candidate.revision) {
34611
+ this.store.upsert(candidate);
34312
34612
  this.status.unchanged++;
34313
34613
  continue;
34314
34614
  }
34615
+ if (!saved) this.store.upsert(candidate);
34315
34616
  try {
34316
34617
  const messages = /* @__PURE__ */ new Map();
34317
34618
  const cursors = /* @__PURE__ */ new Set();
@@ -34450,10 +34751,10 @@ function shellQuote(value, platform = process.platform) {
34450
34751
  if (/[\x00-\x1f\x7f]/.test(value)) throw new Error("Paths and launch arguments must not contain control characters.");
34451
34752
  return `'${value.replaceAll("'", platform === "win32" ? "''" : "'\\''")}'`;
34452
34753
  }
34453
- function launchCommand(binary, args, directory2, platform = process.platform) {
34754
+ function launchCommand(binary, args, directory3, platform = process.platform) {
34454
34755
  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}`;
34756
+ const invocation2 = [binary, ...args].map(quote).join(" ");
34757
+ return platform === "win32" ? `Set-Location -LiteralPath ${quote(directory3)}; if ($?) { & ${invocation2} }` : `cd -- ${quote(directory3)} && ${invocation2}`;
34457
34758
  }
34458
34759
 
34459
34760
  // server/handoff.ts
@@ -34522,10 +34823,10 @@ This handoff transfers saved text and file-change evidence, not files, credentia
34522
34823
  ` + chunks.map((c) => c.text).join("\n");
34523
34824
  return { text: text2, messages: chunks.length, totalMessages, partial, note };
34524
34825
  }
34525
- async function saveHandoff(snapshot2, directory2) {
34826
+ async function saveHandoff(snapshot2, directory3) {
34526
34827
  const { text: text2, ...coverage2 } = handoffDocument(snapshot2);
34527
34828
  const digest2 = createHash5("sha256").update(text2).digest("hex");
34528
- const root3 = join24(directory2, "handoffs");
34829
+ const root3 = join24(directory3, "handoffs");
34529
34830
  await mkdir(root3, { recursive: true, mode: 448 });
34530
34831
  const path = join24(root3, `${digest2}.md`), temporary = join24(root3, `.${randomUUID3()}.tmp`);
34531
34832
  try {
@@ -34557,14 +34858,14 @@ async function getLaunchConnection(session) {
34557
34858
  }
34558
34859
  return { webBaseUrl, terminalAvailable: Boolean(terminal), targets };
34559
34860
  }
34560
- async function prepareLaunch(store, session, target, directory2 = session.directory) {
34861
+ async function prepareLaunch(store, session, target, directory3 = session.directory) {
34561
34862
  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.");
34863
+ if (typeof directory3 !== "string" || !isAbsolute7(directory3) || /[\x00-\x1f\x7f]/.test(directory3)) throw new Error("Choose an absolute working directory.");
34864
+ if (!(await stat4(directory3).catch(() => void 0))?.isDirectory()) throw new Error("Working directory is unavailable. Choose an existing directory.");
34564
34865
  const [binary, terminal] = await Promise.all([harnessExecutable(target), terminalExecutable()]);
34565
34866
  let args;
34566
34867
  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);
34868
+ const localHandoff = session.nativeResume === false || ["cursor", "gemini", "qwen-code", "pi", "copilot"].includes(session.source || "") && (!session.nativeResume || directory3 !== session.directory);
34568
34869
  if (target === (session.source || "opencode") && !subagent && !localHandoff) args = resumeArgs(session);
34569
34870
  const mode = args ? "resume" : "handoff";
34570
34871
  if (mode === "handoff" && store.path === ":memory:") throw new Error("Save this library before creating a context handoff.");
@@ -34573,8 +34874,8 @@ async function prepareLaunch(store, session, target, directory2 = session.direct
34573
34874
  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
34875
  args = target === "opencode" ? ["--prompt", prompt] : target === "gemini" || target === "qwen-code" ? ["--prompt-interactive", prompt] : target === "copilot" ? ["--interactive", prompt] : [prompt];
34575
34876
  }
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()) };
34877
+ const command = launchCommand(binary || HARNESSES.find((h3) => h3.id === target).command, args, directory3);
34878
+ return { command, directory: directory3, mode, context, targetAvailable: Boolean(binary), terminalAvailable: Boolean(binary && terminal) && !(target === "opencode" && mode === "resume" && serviceFile()) };
34578
34879
  }
34579
34880
  function macTerminalInvocation(command) {
34580
34881
  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 +34897,17 @@ async function launchTerminal(session, prepared) {
34596
34897
  }
34597
34898
  const terminal = await terminalExecutable();
34598
34899
  if (!terminal) throw new Error("No supported terminal was found. Copy the command instead.");
34599
- const invocation = commandInvocation(prepared.command, terminal);
34900
+ const invocation2 = commandInvocation(prepared.command, terminal);
34600
34901
  if (process.platform === "linux") {
34601
34902
  await new Promise((resolve3, reject) => {
34602
- const child = spawn2(invocation.file, invocation.args, { detached: true, stdio: "ignore" });
34903
+ const child = spawn2(invocation2.file, invocation2.args, { detached: true, stdio: "ignore" });
34603
34904
  child.once("error", reject);
34604
34905
  child.once("spawn", () => {
34605
34906
  child.unref();
34606
34907
  resolve3();
34607
34908
  });
34608
34909
  });
34609
- } else await exec(invocation.file, invocation.args, { timeout: 15e3, maxBuffer: 16384 });
34910
+ } else await exec(invocation2.file, invocation2.args, { timeout: 15e3, maxBuffer: 16384 });
34610
34911
  }
34611
34912
 
34612
34913
  // server/publishing.ts
@@ -34673,20 +34974,19 @@ var sources = {
34673
34974
  mux: { name: "Mux", icon: "mux" },
34674
34975
  antigravity: { name: "Antigravity", icon: "antigravity" },
34675
34976
  "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" }
34977
+ "antigravity-extension": { name: "Antigravity IDE Extension", icon: "antigravity" }
34682
34978
  };
34683
34979
  var isKnownSource = (id2) => typeof id2 === "string" && Object.hasOwn(sources, id2);
34684
34980
 
34981
+ // packages/core/src/anonymous-projects.ts
34982
+ 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(" ");
34983
+ 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(" ");
34984
+
34685
34985
  // packages/core/src/public-graph.ts
34686
34986
  var DEFAULT_PUBLISHING = { tokens: true, timestamps: true, messageCounts: true, messageTimestamps: true, model: true, harness: true };
34687
34987
  function publishingSettings(value) {
34688
34988
  const result = { ...DEFAULT_PUBLISHING };
34689
- if (object2(value)) {
34989
+ if (object3(value)) {
34690
34990
  for (const key of Object.keys(result)) if (typeof value[key] === "boolean") result[key] = value[key];
34691
34991
  }
34692
34992
  if (!result.timestamps || !result.messageCounts) result.messageTimestamps = false;
@@ -34705,7 +35005,7 @@ function publishableGraph(sessions, settings, messages = /* @__PURE__ */ new Map
34705
35005
  const ordered = [...sessions].sort((a, b) => a.created - b.created || a.id.localeCompare(b.id));
34706
35006
  const ids = new Map(ordered.map((session, index) => [session.id, index]));
34707
35007
  const groups = /* @__PURE__ */ new Map();
34708
- return validatePublicGraph({ version: 1, settings: fields2, sessions: ordered.map((session) => {
35008
+ const graph = { version: 1, settings: fields2, sessions: ordered.map((session) => {
34709
35009
  const key = laneKey(session);
34710
35010
  if (!groups.has(key)) groups.set(key, groups.size);
34711
35011
  const result = {
@@ -34714,18 +35014,34 @@ function publishableGraph(sessions, settings, messages = /* @__PURE__ */ new Map
34714
35014
  parent: session.parentID ? ids.get(session.parentID) ?? null : null,
34715
35015
  fork: session.forkID ? ids.get(session.forkID) ?? null : null
34716
35016
  };
34717
- if (fields2.timestamps) result.timestamps = { created: session.created, lastMessageAt: session.activity?.lastMessageAt ?? null };
35017
+ if (fields2.timestamps) result.timestamps = { created: Math.trunc(session.created), lastMessageAt: session.activity?.lastMessageAt == null ? null : Math.trunc(session.activity.lastMessageAt) };
34718
35018
  if (fields2.tokens) result.tokens = session.tokens;
34719
35019
  const stats = messages.get(session.id);
34720
35020
  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 };
35021
+ if (fields2.messageTimestamps) result.messageTimes = { values: [], limited: stats?.timesLimited ?? true };
34722
35022
  if (fields2.model) result.model = publicModel(session.model);
34723
35023
  if (fields2.harness) result.harness = isKnownSource(session.source) ? session.source : null;
34724
35024
  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));
35025
+ }) };
35026
+ if (fields2.messageTimestamps) {
35027
+ let bytes2 = PUBLIC_GRAPH_MAX_BYTES - new TextEncoder().encode(JSON.stringify(graph)).length;
35028
+ let remaining = PUBLIC_GRAPH_MAX_MESSAGE_TIMES;
35029
+ for (let index = 0; index < ordered.length; index++) {
35030
+ const times = messages.get(ordered[index].id)?.times ?? [], output2 = graph.sessions[index].messageTimes;
35031
+ for (const native of times) {
35032
+ const time4 = Math.trunc(native), size = String(time4).length + (output2.values.length ? 1 : 0);
35033
+ if (!remaining || output2.values.length === 2e3 || size > bytes2) break;
35034
+ output2.values.push(time4);
35035
+ bytes2 -= size;
35036
+ remaining--;
35037
+ }
35038
+ if (output2.values.length < times.length) output2.limited = true;
35039
+ }
35040
+ }
35041
+ return validatePublicGraph(graph);
35042
+ }
35043
+ var object3 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
35044
+ var exact = (value, keys) => object3(value) && Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
34729
35045
  var integer = (value, max = Number.MAX_SAFE_INTEGER) => Number.isSafeInteger(value) && value >= 0 && value <= max;
34730
35046
  var time3 = (value) => integer(value, Date.UTC(2100, 0, 1));
34731
35047
  var nullableCount = (value) => value === null || integer(value);
@@ -34984,46 +35300,46 @@ async function sessionGraphMiddleware(req, res, next) {
34984
35300
  res.setHeader("Content-Type", "application/json");
34985
35301
  res.setHeader("Cache-Control", "no-store");
34986
35302
  res.setHeader("X-Content-Type-Options", "nosniff");
34987
- const json4 = (status2, value) => {
35303
+ const json5 = (status2, value) => {
34988
35304
  if (!res.writableEnded) {
34989
35305
  res.statusCode = status2;
34990
35306
  res.end(JSON.stringify(value));
34991
35307
  }
34992
35308
  };
34993
- if (req.headers["sec-fetch-site"] === "cross-site") return json4(403, { error: "Cross-site requests are not allowed." });
35309
+ if (req.headers["sec-fetch-site"] === "cross-site") return json5(403, { error: "Cross-site requests are not allowed." });
34994
35310
  if (req.headers.origin) {
34995
35311
  try {
34996
- if (new URL(req.headers.origin).host !== req.headers.host) return json4(403, { error: "Origin mismatch." });
35312
+ if (new URL(req.headers.origin).host !== req.headers.host) return json5(403, { error: "Origin mismatch." });
34997
35313
  } catch {
34998
- return json4(403, { error: "Invalid origin." });
35314
+ return json5(403, { error: "Invalid origin." });
34999
35315
  }
35000
35316
  }
35001
- if (req.method !== "GET" && typeof req.headers["x-sessiongraph-action"] !== "string") return json4(403, { error: "Use the SessionGraph application." });
35317
+ if (req.method !== "GET" && typeof req.headers["x-sessiongraph-action"] !== "string") return json5(403, { error: "Use the SessionGraph application." });
35002
35318
  try {
35003
35319
  const { store, importer } = library();
35004
35320
  if (url.pathname.startsWith("/api/sessiongraph/publishing")) {
35005
35321
  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());
35322
+ if (action === "/settings" && req.method === "GET") return json5(200, publishingSettings(store.setting("publishing")));
35323
+ if (action === "/status" && req.method === "GET") return json5(200, await publishing.status());
35324
+ if (action === "/login" && req.method === "POST") return json5(200, publishing.login());
35325
+ if (action === "/poll" && req.method === "POST") return json5(200, await publishing.poll());
35326
+ if (action === "/logout" && req.method === "POST") return json5(200, await publishing.logout());
35011
35327
  if (action === "/preview" && req.method === "POST") {
35012
35328
  const value = await body(req);
35013
- return json4(200, publishing.prepare(store, value?.ids, value?.settings));
35329
+ return json5(200, publishing.prepare(store, value?.ids, value?.settings));
35014
35330
  }
35015
35331
  if (action === "/publish" && req.method === "POST") {
35016
35332
  const value = await body(req);
35017
- return json4(200, await publishing.publish(value?.id, value?.confirmed));
35333
+ return json5(200, await publishing.publish(value?.id, value?.confirmed));
35018
35334
  }
35019
- if (action === "/unpublish" && req.method === "POST") return json4(200, await publishing.unpublish());
35020
- return json4(405, { error: "Method not allowed." });
35335
+ if (action === "/unpublish" && req.method === "POST") return json5(200, await publishing.unpublish());
35336
+ return json5(405, { error: "Method not allowed." });
35021
35337
  }
35022
35338
  if (url.pathname === "/api/sessiongraph/settings" && req.method === "POST") {
35023
35339
  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." });
35340
+ if (!value || typeof value !== "object" || Array.isArray(value) || !["autoImport", "preferences", "viewState"].some((key) => value[key] !== void 0)) return json5(400, { error: "Choose valid settings." });
35341
+ if (value.autoImport !== void 0 && typeof value.autoImport !== "boolean") return json5(400, { error: "Choose a valid auto-import setting." });
35342
+ 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
35343
  store.db.exec("BEGIN IMMEDIATE");
35028
35344
  try {
35029
35345
  if (value.autoImport !== void 0) store.setting("autoImport", value.autoImport);
@@ -35034,69 +35350,71 @@ async function sessionGraphMiddleware(req, res, next) {
35034
35350
  store.db.exec("ROLLBACK");
35035
35351
  throw error;
35036
35352
  }
35037
- return json4(200, { saved: true, autoImport: store.autoImportEnabled() });
35353
+ return json5(200, { saved: true, autoImport: store.autoImportEnabled() });
35038
35354
  }
35039
- if (url.pathname === "/api/sessiongraph/sources" && req.method === "GET") return json4(200, { sources: await importer.sources(), onboarding: store.setting("selected") === void 0 });
35355
+ if (url.pathname === "/api/sessiongraph/sources" && req.method === "GET") return json5(200, { sources: await importer.sources(), onboarding: store.setting("selected") === void 0 });
35040
35356
  if (url.pathname === "/api/sessiongraph/import") {
35041
- if (req.method === "GET") return json4(200, importer.status);
35357
+ if (req.method === "GET") return json5(200, importer.status);
35042
35358
  if (req.method === "POST") {
35043
35359
  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));
35360
+ if (!value || typeof value !== "object" || Array.isArray(value)) return json5(400, { error: "Invalid import request." });
35361
+ if (value.sources !== void 0 && (!Array.isArray(value.sources) || value.sources.some((s) => typeof s !== "string"))) return json5(400, { error: "Choose valid sources." });
35362
+ if (value.automatic !== void 0 && (typeof value.automatic !== "boolean" || value.sources !== void 0)) return json5(400, { error: "Automatic imports use saved sources." });
35363
+ if (importer.status.running) return json5(409, { error: "An import is already running." });
35364
+ return json5(202, importer.start(value.sources, value.automatic));
35049
35365
  }
35050
35366
  }
35051
35367
  if (url.pathname === "/api/sessiongraph/index") {
35052
- if (req.method === "GET") return json4(200, store.checkpoints(url.searchParams.get("after") || ""));
35368
+ if (req.method === "GET") return json5(200, store.checkpoints(url.searchParams.get("after") || ""));
35053
35369
  if (req.method === "POST") {
35054
35370
  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." });
35371
+ return value.record && store.saveCheckpoint(value.record, value.epoch) ? json5(200, { saved: true }) : json5(409, { error: "Index snapshot is stale." });
35056
35372
  }
35057
35373
  if (req.method === "DELETE") {
35058
35374
  store.clearIndex();
35059
- return json4(200, { cleared: true });
35375
+ return json5(200, { cleared: true });
35060
35376
  }
35061
35377
  }
35062
35378
  if (url.pathname === "/api/sessiongraph" && req.method === "GET") {
35063
35379
  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));
35380
+ return json5(200, store.library(sources2, importer.status.running));
35065
35381
  }
35066
- const match2 = /^\/api\/sessiongraph\/session\/([^/]+)(?:\/(content|timeline|events|event-markers|connection|prepare-launch|open-terminal))?$/.exec(url.pathname);
35382
+ const match2 = /^\/api\/sessiongraph\/session\/([^/]+)(?:\/(content|timeline|commits|events|event-markers|connection|prepare-launch|open-terminal))?$/.exec(url.pathname);
35067
35383
  if (match2) {
35068
35384
  const id2 = decodeURIComponent(match2[1]);
35069
35385
  const session = store.getSession(id2);
35070
- if (!session) return json4(404, { error: "Session not imported." });
35386
+ if (!session) return json5(404, { error: "Session not imported." });
35071
35387
  if (["prepare-launch", "open-terminal"].includes(match2[2]) && req.method === "POST") {
35072
35388
  const value = await body(req);
35073
- if (!value || typeof value !== "object" || Array.isArray(value)) return json4(400, { error: "Invalid launch request." });
35389
+ if (!value || typeof value !== "object" || Array.isArray(value)) return json5(400, { error: "Invalid launch request." });
35074
35390
  const target = value.target ?? session.source ?? "opencode";
35075
- if (!isHarness(target)) return json4(400, { error: "Choose a supported destination app." });
35391
+ if (!isHarness(target)) return json5(400, { error: "Choose a supported destination app." });
35076
35392
  try {
35077
35393
  const prepared = await prepareLaunch(store, session, target, value.directory);
35078
35394
  if (match2[2] === "open-terminal") await launchTerminal(session, prepared);
35079
- return json4(200, prepared);
35395
+ return json5(200, prepared);
35080
35396
  } catch (error) {
35081
- return json4(400, { error: error instanceof Error ? error.message : "Could not prepare this session." });
35397
+ return json5(400, { error: error instanceof Error ? error.message : "Could not prepare this session." });
35082
35398
  }
35083
35399
  }
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));
35400
+ if (req.method !== "GET") return json5(405, { error: "Method not allowed." });
35401
+ if (["prepare-launch", "open-terminal"].includes(match2[2])) return json5(405, { error: "Method not allowed." });
35402
+ if (match2[2] === "timeline") return json5(200, store.timeline(id2));
35403
+ 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 }));
35404
+ if (match2[2] === "event-markers") return json5(200, store.eventMarkers(id2));
35405
+ 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)]] : []))));
35406
+ if (match2[2] === "connection") return json5(200, await getLaunchConnection(session));
35090
35407
  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));
35408
+ if (cursor && (!/^\d{1,9}$/.test(cursor) || Number(cursor) > 5e4)) return json5(400, { error: "Invalid cursor." });
35409
+ return json5(200, match2[2] === "content" ? store.content(id2, cursor) : store.detail(id2, cursor));
35093
35410
  }
35094
- return json4(404, { error: "Not found." });
35411
+ return json5(404, { error: "Not found." });
35095
35412
  } 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 });
35413
+ if (error instanceof PublishingError) return json5(error.status, { error: error.message });
35414
+ if (error instanceof EventReadError) return json5(error.status, { error: error.message });
35415
+ if (error instanceof LibraryError) return json5(error.code === "STALE_CURSOR" ? 409 : 400, { error: error.message });
35098
35416
  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." });
35417
+ return json5(500, { error: "Local operation failed. Check the import status or retry." });
35100
35418
  }
35101
35419
  }
35102
35420