sessiongraph 1.0.14 → 1.0.16

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 (41) hide show
  1. package/PRIVACY.md +15 -61
  2. package/README.md +35 -55
  3. package/bin/sessiongraph.mjs +14 -8
  4. package/dist/assets/index-C0jATzD9.css +1 -0
  5. package/dist/assets/{index-D4P4hbvc.js → index-CFlNwG9H.js} +1 -1
  6. package/dist/assets/index-D24Hz9MJ.js +180 -0
  7. package/dist/assets/{index-Kotmn42s.js → index-D7udGrT1.js} +1 -1
  8. package/dist/assets/{index-BLM-0yG6.js → index-U9QGDl1t.js} +1 -1
  9. package/dist/assets/katagami-sans-DMv8PCo8.woff2 +0 -0
  10. package/dist/assets/licenses/hugeicons.txt +21 -0
  11. package/dist/assets/licenses/katagami.txt +93 -0
  12. package/dist/assets/public-viewer-CyDoUT6s.css +1 -0
  13. package/dist/assets/public-viewer-iQBchlbq.js +24 -0
  14. package/dist/assets/scene-DmT4K5Nj.js +248 -0
  15. package/dist/assets/share-DrezE0sG.js +7 -0
  16. package/dist/assets/{three-D_1Qt16u.js → three-DDiuFd7k.js} +21 -21
  17. package/dist/assets/{worker-C10U_apJ.js → worker-B9mWJfQ6.js} +1 -1
  18. package/dist/index.html +2 -2
  19. package/dist-server/cli.mjs +50326 -17640
  20. package/dist-server/install-cli.mjs +204 -0
  21. package/dist-server/server.mjs +1089 -379
  22. package/docs/cli.md +293 -190
  23. package/docs/guide.md +16 -9
  24. package/docs/import-coverage.md +73 -5
  25. package/docs/performance.md +164 -0
  26. package/docs/releases.md +6 -0
  27. package/package.json +18 -10
  28. package/dist/assets/external-links-BmBkCsrt.js +0 -1
  29. package/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  30. package/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  31. package/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  32. package/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  33. package/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  34. package/dist/assets/index-B1kyvo41.js +0 -175
  35. package/dist/assets/index-Du0_nVjH.css +0 -1
  36. package/dist/assets/publishing-CEvQPkO1.css +0 -1
  37. package/dist/assets/publishing-D9CqkbeB.js +0 -23
  38. package/dist/assets/scene-CTHyYtma.js +0 -139
  39. package/dist/assets/share-Cw1E-ED9.js +0 -7
  40. package/docs/importer-comparison.md +0 -48
  41. package/docs/session-artifacts-audit.md +0 -176
@@ -2145,12 +2145,12 @@ import { randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
2145
2145
  // node_modules/.pnpm/@opencode+client@2.2.1_effect@4.0.1/node_modules/@opencode/client/dist/chunks/mcp-ve4aws36.js
2146
2146
  import { spawn } from "node:child_process";
2147
2147
  var stderrLimit = 8 * 1024;
2148
- function spawnServiceContender2(command, args, env) {
2148
+ function spawnServiceContender2(command, args, env2) {
2149
2149
  const child = spawn(command, args, {
2150
2150
  detached: true,
2151
2151
  windowsHide: true,
2152
2152
  stdio: ["ignore", "ignore", "pipe"],
2153
- env: { ...process.env, ...env }
2153
+ env: { ...process.env, ...env2 }
2154
2154
  });
2155
2155
  let error;
2156
2156
  let closed = false;
@@ -2408,13 +2408,13 @@ async function publish(file, info, handoff) {
2408
2408
  }), { mode: 384, flag: "wx" });
2409
2409
  await rename(temporary, file + ".pty-handoff").finally(() => rm(temporary, { force: true }));
2410
2410
  }
2411
- async function environment2(file, env) {
2411
+ async function environment2(file, env2) {
2412
2412
  const record = await read(file);
2413
2413
  const current = await readFile(file, "utf8").then((text2) => JSON.parse(text2)).catch(() => {
2414
2414
  return;
2415
2415
  });
2416
2416
  const handoff = record !== void 0 && record.expiresAt > Date.now() && (current === void 0 || same(record.source, current)) ? record.handoff : void 0;
2417
- return { ...env, OPENCODE_PTY_HANDOFF: handoff == null ? void 0 : JSON.stringify(handoff) };
2417
+ return { ...env2, OPENCODE_PTY_HANDOFF: handoff == null ? void 0 : JSON.stringify(handoff) };
2418
2418
  }
2419
2419
  async function complete2(file, info) {
2420
2420
  const record = await read(file);
@@ -2623,10 +2623,10 @@ import { createHash } from "node:crypto";
2623
2623
  import { existsSync } from "node:fs";
2624
2624
  import { homedir as homedir2 } from "node:os";
2625
2625
  import { join as join2 } from "node:path";
2626
- var serviceFile = (env = process.env) => env.SESSIONGRAPH_SERVICE_FILE || env.SESSION_ATLAS_SERVICE_FILE || env.ATLAS_SERVICE_FILE;
2627
- function databasePath(env = process.env, platform = process.platform, home = homedir2()) {
2628
- const override = env.SESSIONGRAPH_DATA_DIR || env.SESSION_ATLAS_DATA_DIR || env.ATLAS_DATA_DIR;
2629
- const base = platform === "darwin" ? join2(home, "Library", "Application Support") : platform === "win32" ? env.LOCALAPPDATA || home : env.XDG_DATA_HOME || join2(home, ".local", "share");
2626
+ var serviceFile = (env2 = process.env) => env2.SESSIONGRAPH_SERVICE_FILE || env2.SESSION_ATLAS_SERVICE_FILE || env2.ATLAS_SERVICE_FILE;
2627
+ function databasePath(env2 = process.env, platform = process.platform, home = homedir2()) {
2628
+ const override = env2.SESSIONGRAPH_DATA_DIR || env2.SESSION_ATLAS_DATA_DIR || env2.ATLAS_DATA_DIR;
2629
+ const base = platform === "darwin" ? join2(home, "Library", "Application Support") : platform === "win32" ? env2.LOCALAPPDATA || home : env2.XDG_DATA_HOME || join2(home, ".local", "share");
2630
2630
  const paths2 = [
2631
2631
  join2(override || join2(base, platform === "linux" ? "sessiongraph" : "SessionGraph"), "sessiongraph.sqlite"),
2632
2632
  join2(override || join2(base, platform === "linux" ? "session-atlas" : "Session Atlas"), "session-atlas.sqlite"),
@@ -2643,6 +2643,220 @@ function sumRecordedTokens(values) {
2643
2643
  return validTokenCount(total) ? total : null;
2644
2644
  }
2645
2645
 
2646
+ // server/usage.ts
2647
+ var IMPORT_METADATA_VERSION = 1;
2648
+ var object = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
2649
+ var string = (value, max = 256) => typeof value === "string" && value.trim() ? value.slice(0, max) : void 0;
2650
+ var tokenCount = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
2651
+ var recordedCost = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
2652
+ var fields = ["total", "input", "output", "cacheRead", "cacheWrite", "reasoning", "tool"];
2653
+ function sumTokens(values) {
2654
+ if (!values.length || values.some((value) => tokenCount(value) === null)) return null;
2655
+ return tokenCount(values.reduce((sum, value) => sum + value, 0));
2656
+ }
2657
+ function recordedUsage(values, scope = "message", id2) {
2658
+ const usage = {
2659
+ total: null,
2660
+ input: null,
2661
+ output: null,
2662
+ cacheRead: null,
2663
+ cacheWrite: null,
2664
+ reasoning: null,
2665
+ tool: null,
2666
+ inputIncludesCache: typeof values.inputIncludesCache === "boolean" ? values.inputIncludesCache : null,
2667
+ outputIncludesReasoning: typeof values.outputIncludesReasoning === "boolean" ? values.outputIncludesReasoning : null,
2668
+ cost: recordedCost(values.cost),
2669
+ scope
2670
+ };
2671
+ for (const field of fields) usage[field] = tokenCount(values[field]);
2672
+ if (values.costEstimated !== void 0 && typeof values.costEstimated === "boolean") usage.costEstimated = values.costEstimated;
2673
+ const identity2 = string(id2, 512);
2674
+ if (identity2) usage.id = identity2;
2675
+ return fields.some((field) => usage[field] !== null) || usage.cost !== null ? usage : void 0;
2676
+ }
2677
+ function anthropicUsage(value, id2) {
2678
+ const u2 = object(value), split = "cache_read_input_tokens" in u2 || "cache_creation_input_tokens" in u2;
2679
+ return recordedUsage({
2680
+ input: u2.input_tokens,
2681
+ output: u2.output_tokens,
2682
+ cacheRead: u2.cache_read_input_tokens,
2683
+ cacheWrite: u2.cache_creation_input_tokens,
2684
+ reasoning: u2.reasoning_output_tokens,
2685
+ total: tokenCount(u2.total_tokens) ?? sumTokens(split ? [u2.input_tokens, u2.output_tokens, u2.cache_read_input_tokens, u2.cache_creation_input_tokens] : [u2.input_tokens, u2.output_tokens]),
2686
+ inputIncludesCache: split ? false : null,
2687
+ outputIncludesReasoning: true
2688
+ }, "message", id2);
2689
+ }
2690
+ function openAIUsage(value, id2, scope = "message") {
2691
+ const u2 = object(value), input = u2.input_tokens ?? u2.prompt_tokens, output2 = u2.output_tokens ?? u2.completion_tokens;
2692
+ return recordedUsage({
2693
+ input,
2694
+ output: output2,
2695
+ total: tokenCount(u2.total_tokens) ?? sumTokens([input, output2]),
2696
+ cacheRead: u2.cached_input_tokens ?? u2.cache_read_input_tokens ?? u2.input_tokens_details?.cached_tokens ?? u2.prompt_tokens_details?.cached_tokens,
2697
+ cacheWrite: u2.cache_write_input_tokens,
2698
+ reasoning: u2.reasoning_output_tokens ?? u2.output_tokens_details?.reasoning_tokens ?? u2.completion_tokens_details?.reasoning_tokens,
2699
+ inputIncludesCache: true,
2700
+ outputIncludesReasoning: true
2701
+ }, scope, id2);
2702
+ }
2703
+ function piUsage(value, id2) {
2704
+ const u2 = object(value);
2705
+ return recordedUsage({
2706
+ input: u2.input,
2707
+ output: u2.output,
2708
+ cacheRead: u2.cacheRead,
2709
+ cacheWrite: u2.cacheWrite,
2710
+ reasoning: u2.reasoning,
2711
+ total: tokenCount(u2.totalTokens) ?? sumTokens([u2.input, u2.output, u2.cacheRead, u2.cacheWrite]),
2712
+ inputIncludesCache: false,
2713
+ outputIncludesReasoning: true,
2714
+ cost: object(u2.cost).total,
2715
+ costEstimated: typeof u2.cost?.total === "number" ? u2.cost.totalFromProvider !== true : void 0
2716
+ }, "message", id2);
2717
+ }
2718
+ function googleUsage(value, id2) {
2719
+ const u2 = object(value);
2720
+ const input = u2.promptTokenCount ?? u2.input, output2 = u2.candidatesTokenCount ?? u2.output;
2721
+ const reasoning = u2.thoughtsTokenCount ?? u2.thoughts, total = u2.totalTokenCount ?? u2.total;
2722
+ const placeholder = total === 0 && [input, output2, reasoning, u2.toolUsePromptTokenCount ?? u2.tool].some((value2) => (tokenCount(value2) ?? 0) > 0);
2723
+ const base = sumTokens([input, output2]), withReasoning = sumTokens([input, output2, reasoning]);
2724
+ const comparable = !placeholder && tokenCount(total) !== null && base !== null && tokenCount(reasoning) !== null && (u2.toolUsePromptTokenCount ?? u2.tool ?? 0) === 0;
2725
+ return recordedUsage({
2726
+ input,
2727
+ output: output2,
2728
+ cacheRead: u2.cachedContentTokenCount ?? u2.cached,
2729
+ reasoning,
2730
+ tool: u2.toolUsePromptTokenCount ?? u2.tool,
2731
+ total: placeholder ? null : total,
2732
+ inputIncludesCache: true,
2733
+ outputIncludesReasoning: comparable && total === base ? true : comparable && total === withReasoning ? false : null
2734
+ }, "message", id2);
2735
+ }
2736
+ function openCodeUsage(value, cost, id2) {
2737
+ const u2 = object(value);
2738
+ return recordedUsage({
2739
+ input: u2.input,
2740
+ output: u2.output,
2741
+ cacheRead: u2.cache?.read,
2742
+ cacheWrite: u2.cache?.write,
2743
+ reasoning: u2.reasoning,
2744
+ total: sumTokens([u2.input, u2.output, u2.cache?.read, u2.cache?.write]),
2745
+ inputIncludesCache: false,
2746
+ outputIncludesReasoning: true,
2747
+ cost: recordedCost(cost)
2748
+ }, "message", id2);
2749
+ }
2750
+ function messageUsage(raw) {
2751
+ const id2 = raw.responseId || raw.response_id || raw.id;
2752
+ if (raw.usageMetadata) return googleUsage(raw.usageMetadata, id2);
2753
+ if (raw.tokens?.cache) return openCodeUsage(raw.tokens, raw.cost, id2);
2754
+ if (raw.token_usage) {
2755
+ const u3 = object(raw.token_usage);
2756
+ const split = "cache_creation_input_tokens" in u3 || tokenCount(u3.cache_read_input_tokens) !== null && tokenCount(u3.input_tokens) !== null && u3.cache_read_input_tokens > u3.input_tokens;
2757
+ return split ? anthropicUsage(u3, id2) : openAIUsage(u3, id2);
2758
+ }
2759
+ const u2 = object(raw.usage);
2760
+ if ("cacheRead" in u2 || "cacheWrite" in u2 || "totalTokens" in u2 && "input" in u2) return piUsage(u2, id2);
2761
+ if ("cache_read_input_tokens" in u2 || "cache_creation_input_tokens" in u2) return anthropicUsage(u2, id2);
2762
+ if ("input_tokens" in u2 || "prompt_tokens" in u2 || "output_tokens" in u2 || "completion_tokens" in u2 || "total_tokens" in u2) return openAIUsage(u2, id2);
2763
+ if ("inputTokens" in u2 || "outputTokens" in u2 || "totalTokens" in u2) {
2764
+ const split = "cacheReadInputTokens" in u2 || "cacheCreationInputTokens" in u2;
2765
+ return recordedUsage({
2766
+ input: u2.inputTokens,
2767
+ output: u2.outputTokens,
2768
+ cacheRead: u2.cacheReadInputTokens ?? u2.cachedInputTokens,
2769
+ cacheWrite: u2.cacheCreationInputTokens,
2770
+ reasoning: u2.reasoningTokens,
2771
+ total: tokenCount(u2.totalTokens) ?? sumTokens(split ? [u2.inputTokens, u2.outputTokens, u2.cacheReadInputTokens, u2.cacheCreationInputTokens] : [u2.inputTokens, u2.outputTokens]),
2772
+ inputIncludesCache: split ? false : null,
2773
+ outputIncludesReasoning: true
2774
+ }, "message", id2);
2775
+ }
2776
+ }
2777
+ function messageMetadata(raw) {
2778
+ const result = {};
2779
+ const values = {
2780
+ model: (typeof raw.model === "object" ? raw.model?.id || raw.model?.modelID : raw.model || raw.modelId || raw.modelID) || raw.modelInfo?.id,
2781
+ provider: raw.provider || raw.providerId || raw.providerID || (typeof raw.model === "object" ? raw.model?.providerID : void 0) || raw.modelInfo?.provider,
2782
+ agent: raw.agent,
2783
+ stopReason: raw.stopReason || raw.stop_reason || raw.finishReason || raw.finish_reason || raw.finish,
2784
+ nativeStopReason: raw.rawFinish,
2785
+ cwd: raw.cwd
2786
+ };
2787
+ for (const [key, value] of Object.entries(values)) {
2788
+ const bounded = string(value, key === "cwd" ? 4096 : 256);
2789
+ if (bounded) result[key] = bounded;
2790
+ }
2791
+ const elapsed = (end, start) => typeof end === "number" && typeof start === "number" && end >= start ? recordedCost(end - start) : null;
2792
+ const duration = recordedCost(raw.durationMs ?? raw.duration_ms ?? raw.tool_duration_ms) ?? elapsed(raw.time?.completed, raw.time?.created);
2793
+ if (duration !== null) result.durationMs = duration;
2794
+ const firstToken = elapsed(raw.time?.firstToken, raw.time?.created);
2795
+ if (firstToken !== null) result.firstTokenMs = firstToken;
2796
+ return Object.keys(result).length ? result : void 0;
2797
+ }
2798
+ function sessionUsage(usage, partial = false) {
2799
+ if (!usage) return;
2800
+ const { scope: _scope, id: _id, ...values } = usage;
2801
+ return { ...values, source: "session", partial: partial || usage.total === null, reportedMessages: 0, missingMessages: 0 };
2802
+ }
2803
+ function mergeUsage(a, b) {
2804
+ const merged = { ...a };
2805
+ for (const field of fields) merged[field] = a[field] === null ? b[field] : b[field] === null ? a[field] : Math.max(a[field], b[field]);
2806
+ if (b.inputIncludesCache === false && a.inputIncludesCache !== false) merged.input = b.input;
2807
+ if (a.inputIncludesCache === false && b.inputIncludesCache !== false) merged.input = a.input;
2808
+ merged.inputIncludesCache = a.inputIncludesCache ?? b.inputIncludesCache;
2809
+ if (a.inputIncludesCache === false || b.inputIncludesCache === false) merged.inputIncludesCache = false;
2810
+ merged.outputIncludesReasoning = a.outputIncludesReasoning ?? b.outputIncludesReasoning;
2811
+ merged.cost = a.cost === null ? b.cost : b.cost === null ? a.cost : Math.max(a.cost, b.cost);
2812
+ merged.costEstimated = a.costEstimated || b.costEstimated || void 0;
2813
+ return merged;
2814
+ }
2815
+ function sumUsage(values) {
2816
+ if (!values.length) return;
2817
+ const result = recordedUsage({ total: 0 });
2818
+ for (const field of fields) result[field] = sumTokens(values.map((value) => value[field]));
2819
+ const costs = values.map((value) => value.cost);
2820
+ result.cost = costs.every((value) => recordedCost(value) !== null) ? recordedCost(costs.reduce((sum, value) => sum + value, 0)) : null;
2821
+ for (const flag of ["inputIncludesCache", "outputIncludesReasoning"]) result[flag] = values.every((value) => value[flag] === values[0][flag]) ? values[0][flag] : null;
2822
+ if (values.some((value) => value.costEstimated)) result.costEstimated = true;
2823
+ const { scope: _scope, ...summary } = result;
2824
+ return summary;
2825
+ }
2826
+ function summarizeUsage(session, messages, historyPartial) {
2827
+ const native = session.usage?.source === "session" ? session.usage : void 0;
2828
+ if (native && native.total !== null) return { ...native };
2829
+ if (tokenCount(session.tokens) !== null) return sessionUsage(recordedUsage({ total: session.tokens, cost: session.cost }));
2830
+ const cumulative = messages.filter((message2) => message2.usage?.scope === "session");
2831
+ const latest = [...cumulative].reverse().find((message2) => message2.usage?.total !== null);
2832
+ if (latest?.usage) return sessionUsage(latest.usage, cumulative.at(-1) !== latest);
2833
+ const lastSnapshot = cumulative.at(-1);
2834
+ if (lastSnapshot?.usage) return sessionUsage(lastSnapshot.usage, true);
2835
+ const unique = /* @__PURE__ */ new Map();
2836
+ let missing = 0;
2837
+ for (const message2 of messages) {
2838
+ if (message2.usage?.scope === "message") {
2839
+ const key = message2.usage.id || message2.id, previous = unique.get(key);
2840
+ unique.set(key, previous ? mergeUsage(previous, message2.usage) : message2.usage);
2841
+ } else if (message2.role === "assistant") missing++;
2842
+ }
2843
+ const records = [...unique.values()], known = records.filter((value) => value.total !== null);
2844
+ if (!known.length && native) return { ...native, partial: true };
2845
+ const totals = sumUsage(records) || recordedUsage({ cost: session.cost }) || recordedUsage({ total: 0 });
2846
+ const { scope: _scope, id: _id, ...values } = totals;
2847
+ const total = known.length ? sumTokens(known.map((value) => value.total)) : null;
2848
+ return {
2849
+ ...values,
2850
+ total,
2851
+ cost: totals.cost ?? native?.cost ?? recordedCost(session.cost),
2852
+ costEstimated: totals.cost !== null ? totals.costEstimated : native?.cost != null ? native.costEstimated : void 0,
2853
+ source: records.length ? "messages" : "unavailable",
2854
+ reportedMessages: known.length,
2855
+ missingMessages: missing + records.length - known.length,
2856
+ partial: historyPartial || total === null || missing > 0 || known.length !== records.length || !records.length
2857
+ };
2858
+ }
2859
+
2646
2860
  // server/opencode.ts
2647
2861
  async function api(path, signal2) {
2648
2862
  const endpoint = await Service.discover({ file: serviceFile() });
@@ -2704,9 +2918,10 @@ async function loadSessionGraph() {
2704
2918
  model: raw.model?.id || "Unknown model",
2705
2919
  provider: raw.model?.providerID || "",
2706
2920
  agent: raw.agent || "build",
2707
- cost: raw.cost || 0,
2921
+ cost: recordedCost(raw.cost),
2708
2922
  // Input + output + cache tokens; reasoning is generally part of output.
2709
2923
  tokens: sumRecordedTokens([t?.input, t?.output, t?.cache?.read, t?.cache?.write]),
2924
+ usage: sessionUsage(openCodeUsage(t, raw.cost)),
2710
2925
  outcome: raw.outcome
2711
2926
  });
2712
2927
  }
@@ -2714,7 +2929,7 @@ async function loadSessionGraph() {
2714
2929
  if (cursor && seenCursors.has(cursor)) throw new Error("OpenCode returned a repeated session cursor.");
2715
2930
  if (cursor) seenCursors.add(cursor);
2716
2931
  } while (cursor && sessions.size < 2e4);
2717
- if (cursor) warnings.push("Showing the newest 20,000 sessions. Older sessions are not loaded.");
2932
+ if (cursor) warnings.push("OpenCode: Showing the newest 20,000 sessions.");
2718
2933
  const projects = rawProjects.map((p) => ({
2719
2934
  id: p.id,
2720
2935
  name: p.name || basename(p.canonical) || "Global",
@@ -2927,9 +3142,9 @@ function eventText(value, limit = 32e3) {
2927
3142
  return "[unavailable]";
2928
3143
  }
2929
3144
  }
2930
- function eventFor(message2, id2, kind, name, text2 = "", fields2 = {}) {
3145
+ function eventFor(message2, id2, kind, name, text2 = "", fields3 = {}) {
2931
3146
  const time4 = messageTime(message2.time);
2932
- const event = { id: id2, kind, name, role: message2.role, time: time4, timeSource: time4 ? "message" : "unknown", text: eventText(text2, 64e3), ...fields2 };
3147
+ const event = { id: id2, kind, name, role: message2.role, time: time4, timeSource: time4 ? "message" : "unknown", text: eventText(text2, 64e3), ...fields3 };
2933
3148
  event.partial ||= [event.text, event.input, event.output].some((value) => /\[(shortened|omitted|unavailable)\]/.test(value || "")) || text2.length > 64e3;
2934
3149
  return event;
2935
3150
  }
@@ -2974,15 +3189,15 @@ function blockEvents(message2, content, transform = (v3) => v3) {
2974
3189
  return content.slice(0, 200).flatMap((part, i) => {
2975
3190
  if (!part || typeof part !== "object") return [eventFor(message2, `unknown:${i}`, "event", "Unsupported content", "", { partial: true })];
2976
3191
  const nativeID = typeof part.id === "string" ? part.id : void 0, id2 = `${part.type || "part"}:${nativeID || i}`;
2977
- const fields2 = { nativeID, nativeType: String(part.type || "unknown"), partial: content.length > 200 };
3192
+ const fields3 = { nativeID, nativeType: String(part.type || "unknown"), partial: content.length > 200 };
2978
3193
  if (["text", "input_text", "output_text"].includes(part.type)) {
2979
3194
  const event = messageEvent(message2, transform(typeof part.text === "string" ? part.text : ""), id2);
2980
- return [{ ...event, ...fields2, partial: Boolean(event.partial || fields2.partial) }];
3195
+ return [{ ...event, ...fields3, partial: Boolean(event.partial || fields3.partial) }];
2981
3196
  }
2982
- if (["tool_use", "tool-call", "tool_call"].includes(part.type)) return [eventFor(message2, id2, "tool_call", part.name || part.toolName || "Tool call", "", { ...fields2, callID: part.id || part.toolCallId, input: eventText(part.input ?? part.args ?? part.arguments), status: "unknown" })];
2983
- if (["tool_result", "tool-result"].includes(part.type)) return [eventFor(message2, id2, "tool_result", part.name || part.toolName || "Tool result", "", { ...fields2, role: "tool", callID: part.tool_use_id || part.toolCallId || part.tool_call_id, output: eventText(part.content ?? part.result ?? part.output), status: part.is_error === true || part.isError === true || part.error != null ? "failed" : "completed" })];
2984
- if (["thinking", "reasoning"].includes(part.type)) return [eventFor(message2, id2, "reasoning", "Recorded reasoning", eventText(part.thinking ?? part.text), fields2)];
2985
- return [eventFor(message2, id2, "event", `${part.type || "Unknown"} content`, "This content type is not represented as text.", { ...fields2, partial: true })];
3197
+ if (["tool_use", "tool-call", "tool_call"].includes(part.type)) return [eventFor(message2, id2, "tool_call", part.name || part.toolName || "Tool call", "", { ...fields3, callID: part.id || part.toolCallId, input: eventText(part.input ?? part.args ?? part.arguments), status: "unknown" })];
3198
+ if (["tool_result", "tool-result"].includes(part.type)) return [eventFor(message2, id2, "tool_result", part.name || part.toolName || "Tool result", "", { ...fields3, role: "tool", callID: part.tool_use_id || part.toolCallId || part.tool_call_id, output: eventText(part.content ?? part.result ?? part.output), status: part.is_error === true || part.isError === true || part.error != null ? "failed" : "completed" })];
3199
+ if (["thinking", "reasoning"].includes(part.type)) return [eventFor(message2, id2, "reasoning", "Recorded reasoning", eventText(part.thinking ?? part.text), fields3)];
3200
+ return [eventFor(message2, id2, "event", `${part.type || "Unknown"} content`, "This content type is not represented as text.", { ...fields3, partial: true })];
2986
3201
  });
2987
3202
  }
2988
3203
  function userBlockEvents(message2, content, normalize) {
@@ -3030,15 +3245,15 @@ function normalizedEvents(message2, sessionID) {
3030
3245
  // server/commit-extraction.ts
3031
3246
  import { posix, win32 } from "node:path";
3032
3247
  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;
3248
+ var object2 = (v3) => v3 && typeof v3 === "object" && !Array.isArray(v3) ? v3 : {};
3249
+ var string2 = (v3) => typeof v3 === "string" ? v3 : void 0;
3035
3250
  var exitCode = (v3) => typeof v3 === "number" && Number.isSafeInteger(v3) ? v3 : void 0;
3036
3251
  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) };
3252
+ const args = object2(input), meta = object2(metadata2);
3253
+ return { cwd: string2(args.workdir ?? args.cwd ?? args.working_directory ?? meta.cwd), exitCode: exitCode(meta.exitCode ?? meta.exit_code ?? meta.exit) };
3039
3254
  }
3040
3255
  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;
3256
+ const v3 = object2(value), operation2 = v3.kind === "committed" ? "created" : v3.kind === "amended" ? "amended" : v3.kind === "cherry-picked" ? "cherry-picked" : void 0;
3042
3257
  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
3258
  }
3044
3259
  function json2(value) {
@@ -3101,9 +3316,9 @@ function commands(command) {
3101
3316
  return result;
3102
3317
  }
3103
3318
  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);
3319
+ const value = json2(input || ""), args = object2(value);
3320
+ const command = typeof value === "string" ? value : string2(args.command ?? args.cmd);
3321
+ const explicit = string2(args.workdir ?? args.cwd ?? args.working_directory);
3107
3322
  return { command, cwd: explicit !== void 0 ? directory(explicit) : directory(cwd2) };
3108
3323
  }
3109
3324
  function operation(words) {
@@ -3162,8 +3377,8 @@ function output(value) {
3162
3377
  return { text: parsed, code: code ? Number(code[1]) : void 0 };
3163
3378
  }
3164
3379
  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) };
3380
+ const obj = object2(parsed);
3381
+ return { text: string2(obj.stdout) ?? string2(obj.output) ?? "", code: exitCode(obj.exit_code ?? obj.exitCode ?? obj.metadata?.exit_code) };
3167
3382
  }
3168
3383
  function extractCommit(call, result) {
3169
3384
  const shell = /^(?:shell|bash|exec_command|shell_command|run_shell_command|terminal|command execution)$/i.test(call.name) || call.nativeType === "command_execution";
@@ -3184,12 +3399,12 @@ function extractCommit(call, result) {
3184
3399
 
3185
3400
  // server/adapters/opencode-events.ts
3186
3401
  function opencodeEvents(raw, message2) {
3187
- const fields2 = { nativeID: message2.id, nativeType: String(raw.type), timeSource: message2.time ? "recorded" : "unknown" };
3402
+ const fields3 = { nativeID: message2.id, nativeType: String(raw.type), timeSource: message2.time ? "recorded" : "unknown" };
3188
3403
  if (raw.type === "user") return [messageEvent(message2, typeof raw.text === "string" ? raw.text : ""), ...raw.files?.length ? [eventFor(message2, "attachments", "event", "Attachments", "Non-text attachments are not included.", { partial: true })] : []];
3189
3404
  if (raw.type !== "assistant") {
3190
3405
  const status2 = ["pending", "running", "completed", "failed"].includes(raw.status) ? raw.status : "unknown";
3191
3406
  const known = ["compaction", "system", "synthetic", "shell", "model-switched", "agent-switched", "location-switched", "skill", "idle"].includes(raw.type);
3192
- return [eventFor(message2, "event", raw.type === "compaction" ? "compaction" : "event", raw.description || raw.type, eventText(raw.summary ?? raw.text ?? raw.error ?? (raw.type === "shell" ? raw.command : raw)), { ...fields2, role: "system", status: status2, output: raw.type === "shell" ? eventText(raw.output?.output) : void 0, partial: !known || Boolean(raw.output?.truncated) })];
3407
+ return [eventFor(message2, "event", raw.type === "compaction" ? "compaction" : "event", raw.description || raw.type, eventText(raw.summary ?? raw.text ?? raw.error ?? (raw.type === "shell" ? raw.command : raw)), { ...fields3, role: "system", status: status2, output: raw.type === "shell" ? eventText(raw.output?.output) : void 0, partial: !known || Boolean(raw.output?.truncated) })];
3193
3408
  }
3194
3409
  const events = [];
3195
3410
  for (const [i, part] of (Array.isArray(raw.content) ? raw.content.slice(0, 200) : []).entries()) {
@@ -3207,12 +3422,30 @@ function opencodeEvents(raw, message2) {
3207
3422
  } else events.push(eventFor(message2, id2, "event", `${part.type || "Unknown"} content`, "Unsupported content.", { ...native, ...timing, partial: true }));
3208
3423
  }
3209
3424
  if (raw.error) events.push(eventFor(message2, "error", "error", "Assistant error", eventText(raw.error), { status: "failed" }));
3210
- if (!events.length) events.push(eventFor(message2, "empty", "message", "Assistant message", "", { ...fields2, partial: true }));
3425
+ if (!events.length) events.push(eventFor(message2, "empty", "message", "Assistant message", "", { ...fields3, partial: true }));
3211
3426
  if (raw.content?.length > 200) events[0].partial = true;
3212
3427
  return events;
3213
3428
  }
3214
3429
 
3215
3430
  // server/adapters/opencode.ts
3431
+ function openCodeMessage(raw, sessionID) {
3432
+ const content = extractContent([raw]), detail = summarizeMessages(sessionID, [raw], null);
3433
+ const message2 = {
3434
+ id: raw.id,
3435
+ time: raw.time?.created || 0,
3436
+ role: raw.type === "user" ? "user" : raw.type === "assistant" ? "assistant" : "system",
3437
+ fragments: content.fragments,
3438
+ files: detail.files,
3439
+ tools: detail.tools.map((tool) => tool.name),
3440
+ snapshots: detail.snapshotSteps,
3441
+ partial: content.truncated
3442
+ };
3443
+ message2.metadata = messageMetadata({ ...raw, stopReason: raw.finish });
3444
+ if (raw.type === "assistant") message2.usage = openCodeUsage(raw.tokens, raw.cost, raw.id);
3445
+ if (detail.locations.length) message2.locations = detail.locations;
3446
+ message2.events = opencodeEvents(raw, message2);
3447
+ return message2;
3448
+ }
3216
3449
  var opencodeAdapter = {
3217
3450
  id: "opencode",
3218
3451
  name: "OpenCode",
@@ -3231,7 +3464,7 @@ var opencodeAdapter = {
3231
3464
  return {
3232
3465
  projects: data.projects.map((p) => ({ ...p, id: identity("opencode", p.id) })),
3233
3466
  warnings: data.warnings,
3234
- sessions: data.sessions.map((s) => ({ locator: {}, revision: digest([4, s.updated, s.created, s.directory]), session: {
3467
+ sessions: data.sessions.map((s) => ({ locator: {}, revision: digest([5, s.updated, s.created, s.directory, s.tokens, s.cost, s.usage]), session: {
3235
3468
  ...s,
3236
3469
  source: "opencode",
3237
3470
  nativeID: s.id,
@@ -3252,13 +3485,7 @@ var opencodeAdapter = {
3252
3485
  const current = await getSessionInfo(candidate.session.nativeID);
3253
3486
  if (current.time.updated !== candidate.session.updated) throw new Error("Session changed during import; import again to capture its latest messages.");
3254
3487
  }
3255
- return { cursor: page.cursor?.next || void 0, messages: page.data.map((raw) => {
3256
- const content = extractContent([raw]);
3257
- const detail = summarizeMessages(candidate.session.id, [raw], null);
3258
- const message2 = { id: raw.id, time: raw.time?.created || 0, role: raw.type === "user" ? "user" : raw.type === "assistant" ? "assistant" : "system", fragments: content.fragments, files: detail.files, tools: detail.tools.map((t) => t.name), snapshots: detail.snapshotSteps, partial: content.truncated };
3259
- message2.events = opencodeEvents(raw, message2);
3260
- return message2;
3261
- }) };
3488
+ return { cursor: page.cursor?.next || void 0, messages: page.data.map((raw) => openCodeMessage(raw, candidate.session.id)) };
3262
3489
  }
3263
3490
  };
3264
3491
 
@@ -30675,7 +30902,7 @@ function expandHistory(buffer, maxOutputLength) {
30675
30902
  }
30676
30903
 
30677
30904
  // server/adapters/local-files.ts
30678
- var object2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
30905
+ var object3 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
30679
30906
  var text = (value) => typeof value === "string" ? value : "";
30680
30907
  var time = (value) => {
30681
30908
  const n = typeof value === "number" ? value : typeof value === "string" ? /^\d{13}$/.test(value) ? Number(value) : Date.parse(value) : 0;
@@ -30803,14 +31030,18 @@ function localFileAdapter(source) {
30803
31030
  async discover() {
30804
31031
  const listing = await historyFiles(source.roots(), source.match), found = /* @__PURE__ */ new Map();
30805
31032
  let failed = 0;
30806
- const blocked = /* @__PURE__ */ new Set();
31033
+ const blocked = /* @__PURE__ */ new Set(), unreadable = /* @__PURE__ */ new Set();
30807
31034
  for (const path of listing.files) {
30808
31035
  try {
30809
31036
  const before = await states(path), rev = revision2(before);
30810
31037
  let candidate = metadata2.get(path);
30811
31038
  if (!candidate || candidate.revision !== rev) {
30812
31039
  const history = await load(path, rev, before);
30813
- if (!history) continue;
31040
+ if (!history) {
31041
+ const nativeID = source.authoritativeIdentity?.(path);
31042
+ if (nativeID) blocked.add(identity(source.id, nativeID));
31043
+ continue;
31044
+ }
30814
31045
  const session = { ...blankSession(source.id, history.nativeID), ...history.session };
30815
31046
  session.id = identity(source.id, history.nativeID);
30816
31047
  session.nativeID = history.nativeID;
@@ -30830,19 +31061,23 @@ function localFileAdapter(source) {
30830
31061
  const preferred = candidate.locator.path.endsWith(".jsonl"), previousPreferred = previous?.locator.path.endsWith(".jsonl");
30831
31062
  if (!previous || preferred && !previousPreferred || preferred === previousPreferred && candidate.session.updated > previous.session.updated) found.set(candidate.session.id, candidate);
30832
31063
  } catch {
30833
- failed++;
30834
31064
  const nativeID = source.authoritativeIdentity?.(path);
30835
- if (nativeID) blocked.add(identity(source.id, nativeID));
31065
+ if (nativeID) {
31066
+ const id2 = identity(source.id, nativeID);
31067
+ blocked.add(id2);
31068
+ unreadable.add(id2);
31069
+ } else failed++;
30836
31070
  }
30837
31071
  }
30838
31072
  const listed = new Set(listing.files);
30839
31073
  for (const path of metadata2.keys()) if (!listed.has(path)) metadata2.delete(path);
30840
- if (failed) listing.warnings.push(`${failed} ${source.name} histories were unreadable, changing, unsupported, or over the size limit. Saved imports are kept.`);
31074
+ if (failed) listing.warnings.push(`${source.name}: Skipped ${failed} unreadable, changing, unsupported, or oversized ${failed === 1 ? "history file" : "history files"}.`);
30841
31075
  const sessions = [...found.values()].filter((c) => !blocked.has(c.session.id));
31076
+ const errors = unreadable.size ? [`${source.name}: Could not read history for ${unreadable.size} ${unreadable.size === 1 ? "session" : "sessions"}.`] : void 0;
30842
31077
  return { sessions, projects: [...new Map(sessions.map((c) => {
30843
31078
  const p = project(source.id, c.session.directory);
30844
31079
  return [p.id, p];
30845
- })).values()], warnings: listing.warnings, blocked: [...blocked] };
31080
+ })).values()], warnings: listing.warnings, errors, blocked: [...blocked] };
30846
31081
  },
30847
31082
  async read(candidate, cursor) {
30848
31083
  const offset = cursor === void 0 ? 0 : Number(cursor);
@@ -30850,12 +31085,11 @@ function localFileAdapter(source) {
30850
31085
  const history = await load(candidate.locator.path, candidate.revision, await states(candidate.locator.path));
30851
31086
  if (!history) throw new Error("History representation is no longer available.");
30852
31087
  const messages = history.messages.slice(offset, offset + 100);
30853
- const untimed = history.messages.some((m) => !time(m.time));
30854
31088
  return {
30855
31089
  messages,
30856
31090
  cursor: offset + messages.length < history.messages.length ? String(offset + messages.length) : void 0,
30857
31091
  partial: Boolean(history.partial || messages.some((m) => m.partial)),
30858
- note: `${history.note}${untimed ? " Missing message timestamps remain unknown; session placement falls back to recorded metadata or file time." : ""} File snapshots are unavailable.`
31092
+ note: history.note
30859
31093
  };
30860
31094
  }
30861
31095
  };
@@ -30868,9 +31102,11 @@ import { basename as basename4, dirname as dirname2, join as join6 } from "node:
30868
31102
  function conversationMessage(raw, fallbackID) {
30869
31103
  const role = raw.role === "user" ? "user" : ["assistant", "model", "thinking"].includes(raw.role) ? "assistant" : ["tool", "toolResult"].includes(raw.role) ? "tool" : "system";
30870
31104
  const message2 = blankMessage(text(raw.id) || fallbackID, time(raw.timestamp ?? raw.ts), role);
31105
+ message2.metadata = messageMetadata(raw);
31106
+ if (role === "assistant") message2.usage = messageUsage(raw);
30871
31107
  let content = raw.content;
30872
31108
  if (Array.isArray(content)) content = content.map((part) => {
30873
- const p = object2(part);
31109
+ const p = object3(part);
30874
31110
  return p.type === "toolCall" ? { ...p, type: "tool_use", input: p.arguments } : p.type === "reasoning" ? { ...p, type: "thinking", thinking: p.text } : p;
30875
31111
  });
30876
31112
  if (raw.role === "thinking") content = [{ type: "thinking", thinking: raw.content }];
@@ -30891,7 +31127,7 @@ function conversationMessage(raw, fallbackID) {
30891
31127
  else if (event.kind === "reasoning") addText(message2, event.text, "Assistant");
30892
31128
  }
30893
31129
  for (const call of Array.isArray(raw.toolCalls) ? raw.toolCalls : []) {
30894
- const f = object2(call.function);
31130
+ const f = object3(call.function);
30895
31131
  if (!text(f.name)) continue;
30896
31132
  message2.tools.push(f.name);
30897
31133
  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" }));
@@ -30905,7 +31141,7 @@ function googleMessage(raw, fallbackID) {
30905
31141
  const parts = Array.isArray(raw.content) ? raw.content : raw.content != null ? [raw.content] : [];
30906
31142
  const content = parts.map((part) => {
30907
31143
  if (typeof part === "string") return { type: "text", text: part };
30908
- const p = object2(part);
31144
+ const p = object3(part);
30909
31145
  if (typeof p.text === "string") return p.thought ? { type: "thinking", thinking: p.text } : { type: "text", text: p.text };
30910
31146
  if (p.functionCall) return { type: "tool_use", ...p.functionCall, input: p.functionCall.args };
30911
31147
  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 };
@@ -30919,7 +31155,7 @@ function successfulEdits(messages, editNames) {
30919
31155
  if (event.kind === "tool_call" && event.callID) {
30920
31156
  let input = {};
30921
31157
  try {
30922
- input = object2(JSON.parse(event.input || "{}"));
31158
+ input = object3(JSON.parse(event.input || "{}"));
30923
31159
  } catch {
30924
31160
  }
30925
31161
  calls.set(event.callID, { name: event.name, input });
@@ -30988,7 +31224,7 @@ function piHistory(value) {
30988
31224
  messages,
30989
31225
  partial,
30990
31226
  session: { directory: text(header.cwd), created: time(header.timestamp), title: text([...rows2].reverse().find((r) => r.type === "session_info")?.name), model: text(lastModel?.modelId || lastModel?.message?.model) || "Unknown model", provider: text(lastModel?.provider || lastModel?.message?.provider) },
30991
- note: "Raw Pi session history includes all recorded in-file branches, not just the active model context. Entry parent IDs are preserved as event links, not session ancestry. Parent-session file paths do not establish whether a session is a fork or a child. Binary content is omitted."
31227
+ note: "Includes all saved branches in this transcript."
30992
31228
  };
30993
31229
  }
30994
31230
  var piAdapter = localFileAdapter({
@@ -31009,7 +31245,7 @@ var piAdapter = localFileAdapter({
31009
31245
  var nativeText = (v3) => typeof v3 === "number" && Number.isSafeInteger(v3) ? String(v3) : text(v3);
31010
31246
  var seconds = (v3) => typeof v3 === "number" && Number.isFinite(v3) && v3 > 0 ? v3 * 1e3 : time(v3);
31011
31247
  var fileID = (path) => basename4(path).replace(/\.jsonl(?:\..*)?$|\.json$/, "");
31012
- var sidecar2 = (files, path) => object2(files.has(path) ? json3(files.get(path)) : void 0);
31248
+ var sidecar2 = (files, path) => object3(files.has(path) ? json3(files.get(path)) : void 0);
31013
31249
  var roles = ["user", "assistant", "system", "tool", "toolResult", "model"];
31014
31250
  function message(raw, id2, timestamp) {
31015
31251
  if (!roles.includes(raw.role)) return;
@@ -31018,6 +31254,7 @@ function message(raw, id2, timestamp) {
31018
31254
  }
31019
31255
  function recordEvent(raw, id2, kind, timestamp, content) {
31020
31256
  const m = blankMessage(id2, time(timestamp), "system");
31257
+ m.eventOnly = true;
31021
31258
  m.events = [eventFor(m, "record", /compact|summary/i.test(kind) ? "compaction" : /error/i.test(kind) ? "error" : "event", kind || "Source event", eventText(content), { nativeType: kind, partial: true })];
31022
31259
  m.partial = true;
31023
31260
  return m;
@@ -31030,8 +31267,9 @@ function envelopeHistory(path, value) {
31030
31267
  const header = rows2.find((r) => r.type === "session" || r.type === "session_start" || r.type === "session_startup") || {};
31031
31268
  const nativeID = [...nativeIDs][0] || text(header.id || header.sessionId) || fileID(path);
31032
31269
  const messages = rows2.flatMap((r, i) => {
31033
- const body2 = object2(r.message), role = body2.role || r.role || (["user", "assistant", "system"].includes(r.type) ? r.type : void 0);
31270
+ const body2 = object3(r.message), role = body2.role || r.role || (["user", "assistant", "system"].includes(r.type) ? r.type : void 0);
31034
31271
  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);
31272
+ if (m?.role === "assistant") m.usage = messageUsage({ ...body2, id: body2.id || r.uuid || r.id, usage: body2.usage ?? r.usage });
31035
31273
  return m ? [m] : [];
31036
31274
  });
31037
31275
  if (!messages.length) throw new Error("No readable conversation records.");
@@ -31042,37 +31280,36 @@ function envelopeHistory(path, value) {
31042
31280
  messages,
31043
31281
  partial: true,
31044
31282
  session: { directory: text(meta.cwd), created: time(header.timestamp), title: text(header.title), model: text(last?.message?.model || last?.model) || "Unknown model" },
31045
- note: `Local conversation envelopes; source-native message IDs are retained. Context-only records, opaque attachments, and unsupported branches may be absent.${partial ? " Malformed records were skipped." : ""}`
31283
+ note: partial ? "Some transcript records could not be imported." : void 0
31046
31284
  };
31047
31285
  }
31048
31286
  function ampHistory(path, files) {
31049
- const raw = object2(json3(files.get(path)));
31287
+ const raw = object3(json3(files.get(path)));
31050
31288
  if (!text(raw.id) || !Array.isArray(raw.messages)) throw new Error("Unsupported Amp thread.");
31051
31289
  const messages = raw.messages.flatMap((m, i) => {
31052
31290
  const result = message(m, nativeText(m.messageId) || `message:${i}`, m.timestamp ?? m.usage?.timestamp);
31291
+ if (result) result.metadata = messageMetadata({ model: m.usage?.model, ...m });
31053
31292
  return result ? [result] : [];
31054
31293
  });
31055
- return { nativeID: raw.id, messages, partial: true, session: { created: time(raw.created), title: text(raw.title), directory: text(raw.cwd) }, note: "Amp local/exported thread messages. Usage-ledger ranges are not message timestamps. Export-only and missing content remain partial." };
31294
+ return { nativeID: raw.id, messages, partial: true, session: { created: time(raw.created), title: text(raw.title), directory: text(raw.cwd) } };
31056
31295
  }
31057
31296
  function jcodeHistory(path, files) {
31058
- const raw = object2(json3(files.get(path)));
31297
+ const raw = object3(json3(files.get(path)));
31059
31298
  if (!text(raw.id) || !Array.isArray(raw.messages)) throw new Error("Unsupported Jcode session.");
31060
31299
  const journal = path.replace(/\.json$/, ".journal.jsonl");
31061
31300
  const appended = files.has(journal) ? jsonLines(files.get(journal)) : { rows: [], partial: false };
31062
31301
  const records = [...raw.messages];
31063
31302
  for (const row of appended.rows) {
31064
31303
  if (Array.isArray(row.append_messages)) records.push(...row.append_messages);
31065
- if (row.meta) Object.assign(raw, object2(row.meta));
31304
+ if (row.meta) Object.assign(raw, object3(row.meta));
31066
31305
  }
31067
- const seen = /* @__PURE__ */ new Set();
31068
- const messages = records.flatMap((r, i) => {
31069
- const id2 = text(r.id) || `message:${i}`;
31070
- if (seen.has(id2)) return [];
31071
- seen.add(id2);
31306
+ const unique = /* @__PURE__ */ new Map();
31307
+ records.forEach((r, i) => unique.set(text(r.id) || `message:${i}`, r));
31308
+ const messages = [...unique].flatMap(([id2, r]) => {
31072
31309
  const m = message(r, id2);
31073
31310
  return m ? [m] : [];
31074
31311
  });
31075
- return { nativeID: raw.id, messages, partial: appended.partial, session: { title: text(raw.title), directory: text(raw.working_dir), created: time(raw.created_at), model: text(raw.model) || "Unknown model", provider: text(raw.provider_key) }, note: "Jcode session snapshot and append journal; replayed native message IDs count once. Absent message times remain unknown." };
31312
+ 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) } };
31076
31313
  }
31077
31314
  function codebuffHistory(path, files, free) {
31078
31315
  const records = json3(files.get(path));
@@ -31085,11 +31322,11 @@ function codebuffHistory(path, files, free) {
31085
31322
  return m ? [m] : [];
31086
31323
  });
31087
31324
  const chat = basename4(dirname2(path)), project2 = basename4(dirname2(dirname2(dirname2(path))));
31088
- return { nativeID: `${project2}/${chat}`, messages, partial: true, note: "Codebuff/Freebuff persisted chat messages. Freebuff requires a recorded base2-free root-agent marker. Shared storage is attributed once; token counts are not estimated from text." };
31325
+ return { nativeID: `${project2}/${chat}`, messages, partial: true };
31089
31326
  }
31090
31327
  function vibeHistory(path, files) {
31091
- const raw = object2(json3(files.get(path))), legacy = basename4(path) !== "meta.json";
31092
- const meta = legacy ? object2(raw.metadata) : raw;
31328
+ const raw = object3(json3(files.get(path))), legacy = basename4(path) !== "meta.json";
31329
+ const meta = legacy ? object3(raw.metadata) : raw;
31093
31330
  const transcript = join6(dirname2(path), "messages.jsonl");
31094
31331
  const parsed = files.has(transcript) ? jsonLines(files.get(transcript)) : { rows: [], partial: false };
31095
31332
  const records = legacy ? raw.messages : parsed.rows;
@@ -31102,8 +31339,20 @@ function vibeHistory(path, files) {
31102
31339
  nativeID: meta.session_id,
31103
31340
  messages,
31104
31341
  partial: parsed.partial || !messages.length,
31105
- session: { directory: text(meta.environment?.working_directory), created: time(meta.start_time), model: text(meta.config?.active_model) || "Unknown model", title: text(meta.title) },
31106
- note: "Vibe session metadata and conversation snapshot. Untimed transcript messages remain untimed; cumulative session usage is not spread across turns."
31342
+ session: {
31343
+ directory: text(meta.environment?.working_directory),
31344
+ created: time(meta.start_time),
31345
+ model: text(meta.config?.active_model) || "Unknown model",
31346
+ title: text(meta.title),
31347
+ usage: sessionUsage(recordedUsage({
31348
+ input: meta.stats?.session_prompt_tokens,
31349
+ output: meta.stats?.session_completion_tokens,
31350
+ cacheRead: meta.stats?.session_cached_tokens,
31351
+ total: sumTokens([meta.stats?.session_prompt_tokens, meta.stats?.session_completion_tokens]),
31352
+ inputIncludesCache: true,
31353
+ outputIncludesReasoning: true
31354
+ }))
31355
+ }
31107
31356
  };
31108
31357
  }
31109
31358
  function acpHistory(path, value) {
@@ -31116,7 +31365,7 @@ function acpHistory(path, value) {
31116
31365
  }
31117
31366
  };
31118
31367
  for (const [i, row] of rows2.entries()) {
31119
- const p = object2(row.params), u2 = object2(p.update), kind = text(u2.sessionUpdate);
31368
+ const p = object3(row.params), u2 = object3(p.update), kind = text(u2.sessionUpdate);
31120
31369
  if (text(p.sessionId)) ids.add(p.sessionId);
31121
31370
  const timestamp = time(p._meta?.agentTimestampMs) || time(row.timestamp);
31122
31371
  const role = kind === "user_message_chunk" ? "user" : kind === "agent_message_chunk" ? "assistant" : "";
@@ -31135,18 +31384,18 @@ function acpHistory(path, value) {
31135
31384
  flush();
31136
31385
  if (ids.size > 1) throw new Error("Multiple sessions in one ACP event log.");
31137
31386
  if (!ids.size || !messages.length) throw new Error("No supported ACP session updates.");
31138
- return { nativeID: [...ids][0], messages, partial: true, note: "Saved ACP updates. Adjacent text chunks are grouped; missing turn boundaries, tool payloads, and metadata remain partial." };
31387
+ return { nativeID: [...ids][0], messages, partial: true, note: "Turn boundaries and tool details may be incomplete." };
31139
31388
  }
31140
31389
  function dshHistory(value) {
31141
31390
  const { rows: rows2, partial } = jsonLines(value), header = rows2.find((r) => r.type === "session");
31142
31391
  if (!text(header?.id)) throw new Error("Unsupported DeepSeek Harness session.");
31143
31392
  const messages = rows2.flatMap((r, i) => {
31144
31393
  if (!["user/message", "assistant/message", "tool/message"].includes(r.type)) return [];
31145
- const body2 = object2(r.data?.message);
31394
+ const body2 = object3(r.data?.message);
31146
31395
  const m = message({ ...body2, role: body2.role || r.type.split("/")[0] }, text(body2.id) || `record:${i}`, r.time);
31147
31396
  return m ? [m] : [];
31148
31397
  });
31149
- return { nativeID: header.id, messages, partial: true, session: { directory: text(header.cwd), created: time(header.createdAt ?? header.time) }, note: `DeepSeek Harness final message records; streaming/retry bookkeeping is excluded. Context seeds and unsupported event payloads may be absent.${partial ? " Malformed records were skipped." : ""}` };
31398
+ return { nativeID: header.id, messages, partial: true, session: { directory: text(header.cwd), created: time(header.createdAt ?? header.time) }, note: partial ? "Some transcript records could not be imported." : void 0 };
31150
31399
  }
31151
31400
 
31152
31401
  // server/adapters/sqlite-histories.ts
@@ -31155,11 +31404,14 @@ import { lstat as lstat3 } from "node:fs/promises";
31155
31404
  // server/adapters/sqlite-snapshot.ts
31156
31405
  import { DatabaseSync } from "node:sqlite";
31157
31406
  import { chmodSync, constants as constants4, copyFileSync, lstatSync as lstatSync2, mkdtempSync, rmSync as rmSync2 } from "node:fs";
31407
+ import { copyFile, statfs } from "node:fs/promises";
31158
31408
  import { tmpdir } from "node:os";
31159
31409
  import { join as join7 } from "node:path";
31160
31410
  var copies = /* @__PURE__ */ new Map();
31161
31411
  var SqliteSnapshotChangedError = class extends Error {
31162
31412
  };
31413
+ var SqliteSnapshotFileError = class extends Error {
31414
+ };
31163
31415
  var close = (path) => {
31164
31416
  const copy = copies.get(path);
31165
31417
  if (!copy) return;
@@ -31173,17 +31425,82 @@ var close = (path) => {
31173
31425
  process.once("exit", () => {
31174
31426
  for (const path of copies.keys()) close(path);
31175
31427
  });
31176
- function sqliteRevision(path) {
31177
- return digest([path, ...[path, `${path}-wal`].map((file, i) => {
31428
+ function snapshotFiles(path, large) {
31429
+ return [path, `${path}-wal`].map((file, i) => {
31178
31430
  try {
31179
31431
  const s = lstatSync2(file);
31180
- if (!s.isFile() || s.size > 8e9) throw new Error("History database must be a regular file below 8 GB.");
31181
- return [s.dev, s.ino, s.size, s.mtimeMs, s.ctimeMs];
31432
+ const kind = i ? "History database WAL" : "History database";
31433
+ if (!s.isFile()) throw new SqliteSnapshotFileError(`${kind} is not a regular file.`);
31434
+ if (!large && s.size > 8e9) throw new SqliteSnapshotFileError(`${kind} exceeds 8 GB.`);
31435
+ return s;
31182
31436
  } catch (error) {
31183
31437
  if (i && error.code === "ENOENT") return null;
31184
31438
  throw error;
31185
31439
  }
31186
- })]);
31440
+ });
31441
+ }
31442
+ var fingerprint = (path, files) => digest([path, ...files.map((s) => s && [s.dev, s.ino, s.size, s.mtimeMs, s.ctimeMs])]);
31443
+ function sqliteRevision(path) {
31444
+ return fingerprint(path, snapshotFiles(path, false));
31445
+ }
31446
+ function openSnapshot(destination) {
31447
+ const db2 = new DatabaseSync(destination, { readOnly: true, enableDoubleQuotedStringLiterals: false, allowExtension: false });
31448
+ try {
31449
+ db2.exec("PRAGMA query_only=ON; PRAGMA trusted_schema=OFF; PRAGMA busy_timeout=1000; BEGIN;");
31450
+ return db2;
31451
+ } catch (error) {
31452
+ db2.close();
31453
+ throw error;
31454
+ }
31455
+ }
31456
+ async function withLargeSqliteSnapshot(path, read3, expected) {
31457
+ const retained = copies.get(path);
31458
+ if (expected && retained?.revision === expected) return read3(retained.db, expected);
31459
+ const files = snapshotFiles(path, true), revision2 = fingerprint(path, files);
31460
+ if (expected && revision2 !== expected) throw new SqliteSnapshotChangedError("History database changed during import; import again.");
31461
+ if (retained?.revision === revision2) {
31462
+ const result = read3(retained.db, revision2);
31463
+ if (fingerprint(path, snapshotFiles(path, true)) !== revision2) throw new SqliteSnapshotChangedError("History database changed during reading; import again.");
31464
+ return result;
31465
+ }
31466
+ close(path);
31467
+ while (copies.size >= 2) close(copies.keys().next().value);
31468
+ const directory3 = mkdtempSync(join7(tmpdir(), "sessiongraph-history-"));
31469
+ const destination = join7(directory3, "history.db");
31470
+ let db2;
31471
+ try {
31472
+ for (const [index, suffix] of ["", "-wal"].entries()) {
31473
+ const file = files[index];
31474
+ if (!file) continue;
31475
+ try {
31476
+ await copyFile(path + suffix, destination + suffix, constants4.COPYFILE_FICLONE_FORCE);
31477
+ } catch (error) {
31478
+ if (!["ENOSYS", "ENOTSUP", "EOPNOTSUPP", "EXDEV", "EINVAL"].includes(error.code || "")) throw error;
31479
+ const { bavail, bsize } = await statfs(directory3);
31480
+ const reserve = 512 * 1024 * 1024;
31481
+ if (bavail * bsize < file.size + reserve) throw new Error("Not enough free space for the T3 history snapshot. Free space on the temporary drive and retry.");
31482
+ await copyFile(path + suffix, destination + suffix);
31483
+ }
31484
+ chmodSync(destination + suffix, 384);
31485
+ }
31486
+ if (fingerprint(path, snapshotFiles(path, true)) !== revision2) throw new SqliteSnapshotChangedError("History database changed while copying; import again.");
31487
+ db2 = openSnapshot(destination);
31488
+ const result = read3(db2, revision2);
31489
+ if (!expected && fingerprint(path, snapshotFiles(path, true)) !== revision2) throw new SqliteSnapshotChangedError("History database changed during reading; import again.");
31490
+ close(path);
31491
+ while (copies.size >= 2) close(copies.keys().next().value);
31492
+ copies.set(path, { revision: revision2, directory: directory3, db: db2 });
31493
+ return result;
31494
+ } catch (error) {
31495
+ try {
31496
+ db2?.close();
31497
+ } finally {
31498
+ rmSync2(directory3, { recursive: true, force: true });
31499
+ }
31500
+ if (error.code === "ENOENT" && fingerprint(path, snapshotFiles(path, true)) !== revision2)
31501
+ throw new SqliteSnapshotChangedError("History database changed while copying; import again.");
31502
+ throw error;
31503
+ }
31187
31504
  }
31188
31505
  function withSqliteSnapshot(path, read3, expected, pinned = false) {
31189
31506
  const retained = copies.get(path);
@@ -31209,8 +31526,7 @@ function withSqliteSnapshot(path, read3, expected, pinned = false) {
31209
31526
  }
31210
31527
  }
31211
31528
  if (sqliteRevision(path) !== revision2) throw new SqliteSnapshotChangedError("History database changed while copying; import again.");
31212
- db2 = new DatabaseSync(destination, { readOnly: true, enableDoubleQuotedStringLiterals: false, allowExtension: false });
31213
- db2.exec("PRAGMA query_only=ON; PRAGMA trusted_schema=OFF; PRAGMA busy_timeout=1000; BEGIN;");
31529
+ db2 = openSnapshot(destination);
31214
31530
  copy = { revision: revision2, directory: directory3, db: db2 };
31215
31531
  copies.set(path, copy);
31216
31532
  } catch (error) {
@@ -31256,13 +31572,13 @@ function columns(db2, table) {
31256
31572
  if (!/^[a-z_][a-z0-9_]*$/.test(table) || !hasTable(db2, table)) throw new Error(`Unsupported history table: ${table}.`);
31257
31573
  return new Set(db2.prepare(`PRAGMA table_info("${table}")`).all().map((r) => String(r.name)));
31258
31574
  }
31259
- function rows(db2, table, fields2, filter, order, limit = 5e4) {
31575
+ function rows(db2, table, fields3, filter, order, limit = 5e4) {
31260
31576
  const available = columns(db2, table);
31261
- for (const name of [...fields2, ...filter ? [filter[0]] : [], ...order ? [order] : []]) if (!/^[a-zA-Z_][\w]*$/.test(name)) throw new Error("Invalid history column.");
31577
+ for (const name of [...fields3, ...filter ? [filter[0]] : [], ...order ? [order] : []]) if (!/^[a-zA-Z_][\w]*$/.test(name)) throw new Error("Invalid history column.");
31262
31578
  if (filter && !available.has(filter[0])) throw new Error("Unsupported history relation.");
31263
31579
  const size = (f) => `length(CAST("${f}" AS BLOB))`;
31264
- const select = fields2.map((f) => available.has(f) ? `CASE WHEN ${size(f)}<=32000000 THEN "${f}" END AS "${f}"` : `NULL AS "${f}"`).join(",");
31265
- const oversized = fields2.filter((f) => available.has(f)).map((f) => `COALESCE(${size(f)},0)>32000000`).join(" OR ") || "0";
31580
+ const select = fields3.map((f) => available.has(f) ? `CASE WHEN ${size(f)}<=32000000 THEN "${f}" END AS "${f}"` : `NULL AS "${f}"`).join(",");
31581
+ const oversized = fields3.filter((f) => available.has(f)).map((f) => `COALESCE(${size(f)},0)>32000000`).join(" OR ") || "0";
31266
31582
  const query = `SELECT ${select}, (${oversized}) AS __sessiongraph_oversized FROM "${table}"${filter ? ` WHERE "${filter[0]}"=?` : ""}${order && available.has(order) ? ` ORDER BY "${order}"` : ""} LIMIT ${limit + 1}`;
31267
31583
  const result = [];
31268
31584
  let bytes2 = 0;
@@ -31294,13 +31610,13 @@ function sqliteHistoryAdapter(source) {
31294
31610
  return {
31295
31611
  id: source.id,
31296
31612
  name: source.name,
31297
- description: source.description || "Local SQLite session history \xB7 isolated read-only snapshots",
31613
+ description: source.description || "Local session database",
31298
31614
  capabilities: { history: source.history !== false, forks: false, children: false, files: false },
31299
31615
  async detect() {
31300
31616
  return (await source.paths()).length > 0;
31301
31617
  },
31302
31618
  async discover() {
31303
- const sessions = /* @__PURE__ */ new Map(), warnings = [], blocked = [];
31619
+ const sessions = /* @__PURE__ */ new Map(), errors = [], blocked = [];
31304
31620
  let unavailable = false;
31305
31621
  for (const path of await source.paths()) {
31306
31622
  try {
@@ -31310,15 +31626,14 @@ function sqliteHistoryAdapter(source) {
31310
31626
  cached2 = withSqliteSnapshot(path, (db2) => {
31311
31627
  const table = typeof source.table === "string" ? source.table : source.table(db2);
31312
31628
  const values2 = rows(db2, table, source.fields, void 0, source.key, 2e4), found = [];
31313
- const blocked2 = [], warnings2 = [];
31314
- let empty = 0;
31629
+ const blocked2 = [], errors2 = [];
31630
+ let failed = 0;
31315
31631
  for (const row of values2) {
31316
31632
  try {
31317
31633
  const h3 = parseHistory(source, db2, row, path);
31318
31634
  if (!h3) continue;
31319
31635
  if (source.history !== false && !h3.messages.length) {
31320
31636
  blocked2.push(identity(source.id, String(row[source.key])));
31321
- empty++;
31322
31637
  continue;
31323
31638
  }
31324
31639
  if (!h3.nativeID || h3.nativeID.length > 512) throw new Error("Missing native session identity.");
@@ -31338,30 +31653,31 @@ function sqliteHistoryAdapter(source) {
31338
31653
  found.push({ session, revision: rev, locator: { path, snapshot: snapshot2, table, key: String(row[source.key]) } });
31339
31654
  } catch {
31340
31655
  blocked2.push(identity(source.id, String(row[source.key])));
31656
+ failed++;
31341
31657
  }
31342
31658
  }
31343
- if (blocked2.length > empty) warnings2.push(`${blocked2.length - empty} ${source.name} sessions had unsupported, undated, missing, or oversized history; saved imports are kept.`);
31344
- if (empty) warnings2.push(`${empty} empty ${source.name} sessions had no saved messages; previous imports are kept.`);
31345
- return { revision: rev, candidates: found, blocked: blocked2, warnings: warnings2 };
31659
+ if (failed) errors2.push(`${source.name}: Skipped ${failed} unreadable, undated, unsupported, or oversized ${failed === 1 ? "session" : "sessions"}.`);
31660
+ return { revision: rev, candidates: found, blocked: blocked2, errors: errors2 };
31346
31661
  }, snapshot2);
31347
31662
  metadata2.set(path, cached2);
31348
31663
  }
31349
- warnings.push(...cached2.warnings);
31664
+ errors.push(...cached2.errors);
31350
31665
  blocked.push(...cached2.blocked);
31351
31666
  for (const c of cached2.candidates) {
31352
31667
  const old = sessions.get(c.session.id);
31353
31668
  if (!old || c.session.updated > old.session.updated) sessions.set(c.session.id, c);
31354
31669
  }
31355
- } catch {
31670
+ } catch (error) {
31356
31671
  unavailable = true;
31357
- warnings.push(`A ${source.name} database could not be read consistently; saved imports are kept.`);
31672
+ const detail = error instanceof SqliteSnapshotFileError || error instanceof SqliteSnapshotChangedError ? error.message : "Could not read a history database.";
31673
+ errors.push(`${source.name}: ${detail}`);
31358
31674
  }
31359
31675
  }
31360
31676
  const values = [...sessions.values()];
31361
31677
  return { sessions: values, projects: [...new Map(values.map((c) => {
31362
31678
  const p = project(source.id, c.session.directory);
31363
31679
  return [p.id, p];
31364
- })).values()], warnings, blocked, unavailable };
31680
+ })).values()], warnings: [], errors, blocked, unavailable };
31365
31681
  },
31366
31682
  async read(candidate, cursor) {
31367
31683
  if (cursor) throw new Error("Invalid SQLite history cursor.");
@@ -31373,7 +31689,7 @@ function sqliteHistoryAdapter(source) {
31373
31689
  const history = parseHistory(source, db2, row, path);
31374
31690
  if (!history || history.nativeID !== candidate.session.nativeID) throw new Error("Session identity changed.");
31375
31691
  if (source.history !== false && !history.messages.length) throw new Error("No readable conversation.");
31376
- return { messages: history.messages, partial: Boolean(history.partial || history.messages.some((m) => m.partial)), note: `${history.note} File snapshots are unavailable. Missing message timestamps remain unknown.` };
31692
+ return { messages: history.messages, partial: Boolean(history.partial || history.messages.some((m) => m.partial)), note: history.note };
31377
31693
  }, snapshot2);
31378
31694
  }
31379
31695
  };
@@ -31398,23 +31714,25 @@ function combineAdapters(parts) {
31398
31714
  return false;
31399
31715
  },
31400
31716
  async discover() {
31401
- const sessions = /* @__PURE__ */ new Map(), projects = /* @__PURE__ */ new Map(), warnings = [], blocked = /* @__PURE__ */ new Set();
31717
+ const sessions = /* @__PURE__ */ new Map(), projects = /* @__PURE__ */ new Map(), warnings = [], errors = [], blocked = /* @__PURE__ */ new Set();
31402
31718
  for (const [i, part] of parts.entries()) {
31403
31719
  let result;
31404
31720
  try {
31405
31721
  if (!await part.detect()) continue;
31406
31722
  result = await part.discover();
31407
31723
  } catch {
31408
- warnings.push(`A ${part.name} representation could not be read; saved imports are retained.`);
31724
+ errors.push(`${part.name}: Could not read a history source.`);
31409
31725
  break;
31410
31726
  }
31411
31727
  warnings.push(...result.warnings);
31728
+ if (result.errors?.length) errors.push(...result.errors);
31729
+ else if (result.unavailable) errors.push(`${part.name}: History unavailable.`);
31412
31730
  for (const id2 of result.blocked || []) blocked.add(id2);
31413
31731
  for (const p of result.projects) projects.set(p.id, p);
31414
31732
  for (const c of result.sessions) if (!blocked.has(c.session.id) && !sessions.has(c.session.id)) sessions.set(c.session.id, { ...c, revision: digest([i, c.revision]), locator: { ...c.locator, representation: String(i), originalRevision: c.revision } });
31415
31733
  if (result.unavailable) break;
31416
31734
  }
31417
- return { sessions: [...sessions.values()], projects: [...projects.values()], warnings };
31735
+ return { sessions: [...sessions.values()], projects: [...projects.values()], warnings, errors };
31418
31736
  },
31419
31737
  async read(candidate, cursor) {
31420
31738
  const index = Number(candidate.locator.representation);
@@ -31431,6 +31749,8 @@ function claudeMessages(rows2, candidate, times, entries2) {
31431
31749
  return rows2.map((row) => {
31432
31750
  const raw = row.message;
31433
31751
  const msg = blankMessage(row.uuid, times?.get(row.uuid) ?? (Number.isFinite(Date.parse(raw?.timestamp)) ? Date.parse(raw.timestamp) : 0), row.type);
31752
+ msg.metadata = messageMetadata({ ...raw, cwd: entries2?.get(row.uuid)?.cwd });
31753
+ if (row.type === "assistant") msg.usage = anthropicUsage(raw?.usage, raw?.id);
31434
31754
  if (raw?.model) candidate.session.model = raw.model;
31435
31755
  if (row.parent_agent_id && candidate.locator.parent) candidate.session.parentID = identity("claude-code", `${candidate.locator.parent}/agent/${row.parent_agent_id}`);
31436
31756
  if (typeof raw?.content === "string") addText(msg, raw.content, row.type === "user" ? "You" : "Assistant");
@@ -31542,13 +31862,13 @@ var sdkClaudeAdapter = {
31542
31862
  if (!child.isFile() || !/^agent-[\w-]+\.jsonl$/.test(child.name)) continue;
31543
31863
  try {
31544
31864
  const agent = child.name.slice(6, -6), path = join8(file.children, child.name), stats = await stat(path);
31545
- sessions.push({ session: { ...s, id: identity("claude-code", `${info.sessionId}/agent/${agent}`), nativeID: `${info.sessionId}/agent/${agent}`, title: `Subagent ${agent}`, created: stats.birthtimeMs || s.created, updated: stats.mtimeMs, parentID: s.id, agent }, revision: await claudeRevision(path), locator: { path, dir: info.cwd || "", parent: info.sessionId, agent } });
31865
+ sessions.push({ session: { ...s, id: identity("claude-code", `${info.sessionId}/agent/${agent}`), nativeID: `${info.sessionId}/agent/${agent}`, title: `Subagent ${agent}`, created: stats.birthtimeMs || s.created, updated: stats.mtimeMs, parentID: s.id, origin: "automated", agent }, revision: await claudeRevision(path), locator: { path, dir: info.cwd || "", parent: info.sessionId, agent } });
31546
31866
  } catch {
31547
31867
  unreadable++;
31548
31868
  }
31549
31869
  }
31550
31870
  }
31551
- if (unreadable) warnings.push(`${unreadable} Claude Code histories unavailable or too large. Saved imports are kept.`);
31871
+ if (unreadable) warnings.push(`Claude Code: Skipped ${unreadable} unavailable or oversized transcripts.`);
31552
31872
  return { sessions, projects: [...new Map(sessions.map((c) => {
31553
31873
  const p = project("claude-code", c.session.directory);
31554
31874
  return [p.id, p];
@@ -31558,6 +31878,21 @@ var sdkClaudeAdapter = {
31558
31878
  const offset = Number(cursor || 0);
31559
31879
  if (!Number.isSafeInteger(offset) || offset < 0) throw new Error("Invalid history cursor.");
31560
31880
  const transcript = await claudeTranscript(candidate.locator.path, candidate.revision);
31881
+ if (!offset) {
31882
+ const owner = candidate.locator.parent || candidate.session.nativeID;
31883
+ const usageMessages = transcript.entries.flatMap((entry) => {
31884
+ if (entry.type !== "assistant" || entry.sessionId !== owner || !candidate.locator.agent && entry.isSidechain === true) return [];
31885
+ if (candidate.locator.agent && entry.agentId && entry.agentId !== candidate.locator.agent) return [];
31886
+ const raw = entry.message;
31887
+ const message2 = blankMessage(String(entry.uuid || ""), 0, "assistant");
31888
+ message2.usage = anthropicUsage(raw?.usage, raw?.id || entry.uuid);
31889
+ return [message2];
31890
+ });
31891
+ if (usageMessages.some((message2) => message2.usage)) {
31892
+ const usage = summarizeUsage({ ...candidate.session, usage: void 0, tokens: null, cost: null }, usageMessages, transcript.partial);
31893
+ candidate.session.usage = { ...usage, source: "session" };
31894
+ }
31895
+ }
31561
31896
  const start = Math.max(0, offset - 1), count = 120 + offset - start;
31562
31897
  const sessionId = candidate.locator.parent || candidate.session.nativeID;
31563
31898
  const options = { dir: candidate.locator.dir || void 0, offset: start, limit: count + 1, sessionStore: claudeTranscriptStore(transcript, sessionId, candidate.locator.agent) };
@@ -31566,7 +31901,7 @@ var sdkClaudeAdapter = {
31566
31901
  const messages = claudeMessages(rows2.slice(0, count), candidate, transcript.times, transcript.byID).slice(offset - start);
31567
31902
  if (!offset && !messages.length && transcript.size > 100) throw new Error("SDK returned no readable conversation for this transcript.");
31568
31903
  if (!more && await claudeRevision(candidate.locator.path) !== candidate.revision) throw new Error("Session changed during import; import again to capture the latest messages.");
31569
- return { messages, cursor: more ? String(offset + 120) : void 0, partial: transcript.partial, note: `SDK-visible conversation chain from the local CLI/VS Code transcript; pre-compaction text and unsupported message types may be absent. Fork ancestry is unavailable.${transcript.partial ? " Some transcript records or subagent metadata were unreadable." : ""}` };
31904
+ return { messages, cursor: more ? String(offset + 120) : void 0, partial: transcript.partial, note: transcript.partial ? "Some transcript or subagent records could not be read." : void 0 };
31570
31905
  }
31571
31906
  };
31572
31907
  var exportedClaudeAdapter = localFileAdapter({
@@ -31747,11 +32082,17 @@ function codexRecord(raw, offset, candidate) {
31747
32082
  if (raw.type !== "response_item") {
31748
32083
  if (raw.type === "session_meta" || raw.type === "event_msg" && ["user_message", "agent_message", "agent_reasoning", "agent_reasoning_raw_content"].includes(p.type)) return;
31749
32084
  const msg2 = blankMessage(`event:${raw.ordinal ?? offset}`, Date.parse(raw.timestamp) || 0, "system");
32085
+ if (raw.type === "event_msg" && p.type === "token_count") {
32086
+ msg2.usage = openAIUsage(p.info?.total_token_usage, void 0, "session");
32087
+ msg2.eventOnly = true;
32088
+ }
31750
32089
  msg2.events = [eventFor(msg2, "event", /compact/.test(p.type || raw.type) ? "compaction" : p.type === "error" ? "error" : "event", p.type || raw.type, eventText(p), { nativeType: `${raw.type}:${p.type || ""}` })];
31751
32090
  return msg2;
31752
32091
  }
31753
32092
  const role = p.role === "user" ? "user" : p.role === "assistant" ? "assistant" : p.type === "message" ? "system" : "tool";
31754
32093
  const msg = blankMessage(`item:${raw.ordinal ?? offset}`, Date.parse(raw.timestamp) || 0, role);
32094
+ msg.metadata = messageMetadata(p);
32095
+ if (role === "assistant") msg.usage = openAIUsage(p.usage, p.id);
31755
32096
  let input = p.arguments ?? p.input;
31756
32097
  if (typeof input === "string") {
31757
32098
  try {
@@ -31759,8 +32100,8 @@ function codexRecord(raw, offset, candidate) {
31759
32100
  } catch {
31760
32101
  }
31761
32102
  }
31762
- const fields2 = { nativeID: p.id, nativeType: p.type, callID: p.call_id, ...executionFields(input, { cwd: candidate.locator.executionCwd }) };
31763
- msg.events = p.type === "message" ? role === "user" ? userBlockEvents(msg, p.content, codexUserText) : blockEvents(msg, p.content) : ["function_call", "custom_tool_call"].includes(p.type) ? [eventFor(msg, "call", "tool_call", p.name || "Tool call", "", { ...fields2, role: "assistant", input: eventText(p.arguments ?? p.input), status: "unknown" })] : ["function_call_output", "custom_tool_call_output"].includes(p.type) ? [eventFor(msg, "result", "tool_result", "Tool result", "", { ...fields2, output: eventText(p.output, 64e3), status: "unknown" })] : [eventFor(msg, "event", p.type === "reasoning" ? "reasoning" : "event", p.type === "reasoning" ? "Recorded reasoning summary" : p.type || "Unknown event", eventText(p.type === "reasoning" ? p.summary : p), { ...fields2, partial: p.type === "reasoning" })];
32103
+ const fields3 = { nativeID: p.id, nativeType: p.type, callID: p.call_id, ...executionFields(input, { cwd: candidate.locator.executionCwd }) };
32104
+ 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", "", { ...fields3, 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", "", { ...fields3, 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), { ...fields3, partial: p.type === "reasoning" })];
31764
32105
  if (p.type === "message") {
31765
32106
  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");
31766
32107
  } else if (["function_call", "custom_tool_call"].includes(p.type)) {
@@ -31779,7 +32120,7 @@ function codexRecord(raw, offset, candidate) {
31779
32120
  var codexAdapter = {
31780
32121
  id: "codex",
31781
32122
  name: "Codex",
31782
- description: "Local active and archived rollouts \xB7 no running agent required",
32123
+ description: "Local active and archived transcripts",
31783
32124
  capabilities: { history: true, forks: true, children: true, files: true },
31784
32125
  async detect() {
31785
32126
  try {
@@ -31806,6 +32147,7 @@ var codexAdapter = {
31806
32147
  const stats = await stat2(path), session = blankSession("codex", meta.id, meta.cwd);
31807
32148
  session.title = names.get(meta.id) || (typeof meta.name === "string" ? meta.name : "Untitled session");
31808
32149
  const source = meta.source?.subagent?.thread_spawn || meta.source?.sub_agent?.thread_spawn;
32150
+ if (meta.source?.subagent || meta.source?.sub_agent) session.origin = "automated";
31809
32151
  const parent2 = meta.parent_thread_id || source?.parent_thread_id;
31810
32152
  const fork = meta.forked_from_id || meta.forkedFromId;
31811
32153
  Object.assign(session, { created: Date.parse(meta.timestamp) || stats.birthtimeMs || stats.mtimeMs, updated: stats.mtimeMs, archived: path.includes(`${sep2}archived_sessions${sep2}`), provider: meta.model_provider || "", agent: "Codex", parentID: parent2 ? identity("codex", parent2) : void 0, forkID: fork ? identity("codex", fork) : void 0 });
@@ -31825,8 +32167,7 @@ var codexAdapter = {
31825
32167
  unsupported++;
31826
32168
  }
31827
32169
  }
31828
- if (unsupported) warnings.push(`${unsupported} Codex files were unreadable, oversized, or had no supported rollout metadata; saved history is retained.`);
31829
- warnings.push("Codex imports local JSONL rollouts and bounded zstd/gzip archive copies. Cloud-only and store-only history are not imported.");
32170
+ if (unsupported) warnings.push(`Codex: Skipped ${unsupported} unreadable, oversized, or unsupported transcript files.`);
31830
32171
  const sessions = [...found.values()];
31831
32172
  return { sessions, projects: [...new Map(sessions.map((c) => {
31832
32173
  const p = project("codex", c.session.directory);
@@ -31840,7 +32181,7 @@ var codexAdapter = {
31840
32181
  return { messages: page.rows.flatMap((r) => {
31841
32182
  const msg = codexRecord(r.value, r.offset, candidate);
31842
32183
  return msg ? [msg] : [];
31843
- }), cursor: page.cursor === void 0 ? void 0 : String(page.cursor), partial: page.partial, note: "Local rollout messages, tools, and lifecycle events. Mirrored conversation events are deduplicated. Images, encrypted reasoning, and store-only history are unavailable." };
32184
+ }), cursor: page.cursor === void 0 ? void 0 : String(page.cursor), partial: page.partial };
31844
32185
  }
31845
32186
  };
31846
32187
 
@@ -31850,11 +32191,10 @@ import { homedir as homedir6 } from "node:os";
31850
32191
  import { isAbsolute as isAbsolute2, join as join11 } from "node:path";
31851
32192
  var SOURCE = "t3-code";
31852
32193
  var PAGE = 100;
31853
- var MAX_THREADS = 2e4;
31854
32194
  var MAX_ITEM_JSON = 256e3;
31855
32195
  var providerSource = { codex: "codex", claudeAgent: "claude-code", opencode: "opencode" };
31856
32196
  var openCodeEditTools = /* @__PURE__ */ new Set(["patch", "apply_patch", "edit", "write", "multiedit"]);
31857
- var string2 = (value) => typeof value === "string" ? value : "";
32197
+ var string3 = (value) => typeof value === "string" ? value : "";
31858
32198
  function parsedObject(value) {
31859
32199
  if (typeof value !== "string") return;
31860
32200
  try {
@@ -31869,7 +32209,7 @@ function time2(value) {
31869
32209
  return Number.isFinite(parsed) && parsed > 0 && parsed <= 864e13 ? parsed : 0;
31870
32210
  }
31871
32211
  function status(value) {
31872
- return ["pending", "running", "completed", "failed"].includes(string2(value)) ? value : "unknown";
32212
+ return ["pending", "running", "completed", "failed"].includes(string3(value)) ? value : "unknown";
31873
32213
  }
31874
32214
  async function databasePath2() {
31875
32215
  const root3 = sourcePath("t3-code") || process.env.SESSIONGRAPH_T3_CODE_HISTORY_DIR || process.env.T3CODE_HOME || join11(homedir6(), ".t3");
@@ -31898,7 +32238,7 @@ function projectRoots(db2, ids) {
31898
32238
  for (const batch of batches([...new Set(ids.filter(Boolean))])) {
31899
32239
  const placeholders = batch.map(() => "?").join(",");
31900
32240
  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))
31901
- roots2.set(string2(row.project_id), string2(row.workspace_root));
32241
+ roots2.set(string3(row.project_id), string3(row.workspace_root));
31902
32242
  }
31903
32243
  return roots2;
31904
32244
  }
@@ -31908,7 +32248,7 @@ function aggregates(db2, table, ids) {
31908
32248
  for (const batch of batches(ids)) {
31909
32249
  const placeholders = batch.map(() => "?").join(",");
31910
32250
  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))
31911
- result.set(string2(row.thread_id), [Number(row.n), string2(row.latest)]);
32251
+ result.set(string3(row.thread_id), [Number(row.n), string3(row.latest)]);
31912
32252
  }
31913
32253
  return result;
31914
32254
  }
@@ -31922,147 +32262,174 @@ function linkedSessions(db2, ids) {
31922
32262
  CASE WHEN json_valid(payload_json) THEN json_extract(payload_json,'$.nativeThreadRef.strength') END AS strength,
31923
32263
  CASE WHEN json_valid(payload_json) THEN json_extract(payload_json,'$.nativeThreadRef.driver') END AS driver
31924
32264
  FROM orchestration_v2_projection_provider_threads WHERE thread_id IN (${placeholders})`).all(...batch)) {
31925
- const source = providerSource[string2(row.provider)];
31926
- const nativeID = string2(row.native_id);
32265
+ const source = providerSource[string3(row.provider)];
32266
+ const nativeID = string3(row.native_id);
31927
32267
  if (!source || row.strength !== "strong" || row.driver && row.driver !== row.provider || !nativeID || nativeID.length > 512) continue;
31928
- const id2 = string2(row.thread_id);
32268
+ const id2 = string3(row.thread_id);
31929
32269
  links.set(id2, [.../* @__PURE__ */ new Set([...links.get(id2) || [], identity(source, nativeID)])]);
31930
32270
  }
31931
32271
  }
31932
32272
  return links;
31933
32273
  }
32274
+ function pullRequests(db2, warnings) {
32275
+ if (!hasTable(db2, "projection_thread_pull_requests")) return void 0;
32276
+ const query = db2.prepare(`SELECT substr(host,1,254) AS host, substr(repository,1,301) AS repository,
32277
+ number, substr(url,1,1025) AS url, substr(source,1,32) AS source
32278
+ FROM projection_thread_pull_requests WHERE thread_id=? AND source<>'stack-dismissed'
32279
+ ORDER BY host, repository, number LIMIT 101`);
32280
+ let warned = false;
32281
+ return (id2) => {
32282
+ const rows2 = query.all(id2), links = /* @__PURE__ */ new Map();
32283
+ for (const row of rows2.slice(0, 100)) {
32284
+ const host = string3(row.host).toLowerCase(), repository = string3(row.repository).toLowerCase();
32285
+ const number = Number(row.number), source = string3(row.source);
32286
+ if (host.length > 253 || !/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(host) || !/^[a-z0-9-]{1,100}\/[a-z0-9_.-]{1,200}$/.test(repository) || /\/\.{1,2}$/.test(repository) || !Number.isSafeInteger(number) || number < 1 || !["manual", "created", "agent", "stack"].includes(source)) continue;
32287
+ const url = `https://${host}/${repository}/pull/${number}`;
32288
+ if (string3(row.url).replace(/\/$/, "").toLowerCase() !== url) continue;
32289
+ if (!links.has(url)) links.set(url, { host, repository, number, url, source });
32290
+ }
32291
+ if (!warned && rows2.length > 100) {
32292
+ warnings.push("T3 Code pull request discovery is limited to 100 links per thread.");
32293
+ warned = true;
32294
+ }
32295
+ return [...links.values()];
32296
+ };
32297
+ }
31934
32298
  function discoverV2(db2, path, databaseRevision) {
31935
32299
  if (!hasTable(db2, "orchestration_v2_projection_threads") || !hasTable(db2, "orchestration_v2_projection_turn_items")) throw new Error("Unsupported T3 Code database schema.");
31936
- const rows2 = db2.prepare(`SELECT thread_id, project_id, substr(title,1,300) AS title, default_provider, created_at, updated_at, archived_at,
32300
+ const selected = db2.prepare(`SELECT thread_id, project_id, substr(title,1,300) AS title, default_provider, created_at, updated_at, archived_at,
31937
32301
  CASE WHEN json_valid(payload_json) THEN substr(json_extract(payload_json,'$.worktreePath'),1,4096) END AS worktree_path,
31938
32302
  CASE WHEN json_valid(payload_json) THEN substr(json_extract(payload_json,'$.modelSelection.model'),1,200) END AS model,
31939
32303
  CASE WHEN json_valid(payload_json) THEN json_extract(payload_json,'$.lineage.parentThreadId') END AS parent_thread_id,
31940
32304
  CASE WHEN json_valid(payload_json) THEN json_extract(payload_json,'$.lineage.relationshipToParent') END AS relationship,
31941
32305
  json_valid(payload_json) AS valid_payload
31942
- FROM orchestration_v2_projection_threads WHERE deleted_at IS NULL ORDER BY created_at, thread_id LIMIT ?`).all(MAX_THREADS + 1);
31943
- const selected = rows2.slice(0, MAX_THREADS), ids = selected.map((row) => string2(row.thread_id));
31944
- const roots2 = projectRoots(db2, selected.map((row) => string2(row.project_id)));
32306
+ FROM orchestration_v2_projection_threads WHERE deleted_at IS NULL ORDER BY created_at, thread_id`).all();
32307
+ const ids = selected.map((row) => string3(row.thread_id));
32308
+ const roots2 = projectRoots(db2, selected.map((row) => string3(row.project_id)));
31945
32309
  const counts = aggregates(db2, "orchestration_v2_projection_messages", ids);
31946
32310
  const items = aggregates(db2, "orchestration_v2_projection_turn_items", ids);
31947
32311
  const links = linkedSessions(db2, ids);
31948
32312
  const sessions = [], projects = /* @__PURE__ */ new Map(), warnings = [];
31949
- if (rows2.length > MAX_THREADS) warnings.push(`T3 Code discovery is limited to ${MAX_THREADS.toLocaleString()} threads.`);
32313
+ const readPullRequests = pullRequests(db2, warnings);
31950
32314
  let unreadableMetadata = 0;
31951
32315
  for (const row of selected) {
31952
- const nativeID = string2(row.thread_id), created = time2(row.created_at);
32316
+ const nativeID = string3(row.thread_id), created = time2(row.created_at);
31953
32317
  if (!nativeID || nativeID.length > 512 || !created) continue;
31954
32318
  if (!row.valid_payload) unreadableMetadata++;
31955
- const directory3 = string2(row.worktree_path) || roots2.get(string2(row.project_id)) || "";
32319
+ const directory3 = string3(row.worktree_path) || roots2.get(string3(row.project_id)) || "";
31956
32320
  const p = project(SOURCE, directory3);
31957
32321
  projects.set(p.id, p);
31958
32322
  const session = blankSession(SOURCE, nativeID, directory3);
31959
- const parent2 = string2(row.parent_thread_id);
32323
+ const parent2 = string3(row.parent_thread_id);
31960
32324
  session.parentID = row.relationship === "subagent" && parent2 ? identity(SOURCE, parent2) : void 0;
32325
+ if (row.relationship === "subagent") session.origin = "automated";
31961
32326
  session.forkID = row.relationship === "fork" && parent2 ? identity(SOURCE, parent2) : void 0;
31962
32327
  Object.assign(session, {
31963
- title: string2(row.title) || "T3 Code thread",
32328
+ title: string3(row.title) || "T3 Code thread",
31964
32329
  projectID: p.id,
31965
32330
  created,
31966
32331
  updated: time2(row.updated_at) || created,
31967
32332
  archived: Boolean(row.archived_at),
31968
- model: string2(row.model) || "Unknown model",
31969
- provider: string2(row.default_provider),
32333
+ model: string3(row.model) || "Unknown model",
32334
+ provider: string3(row.default_provider),
31970
32335
  agent: "T3 Code",
31971
32336
  linkedSessionIDs: links.get(nativeID) || []
31972
32337
  });
31973
- const revision2 = digest([3, row.updated_at, counts.get(nativeID), items.get(nativeID), links.get(nativeID)]);
31974
- sessions.push({ session, revision: revision2, locator: { path, databaseRevision, threadID: nativeID, format: "v2", metadataPartial: row.valid_payload ? "" : "1" } });
32338
+ const prs = readPullRequests?.(nativeID);
32339
+ const revisionParts = [3, row.updated_at, counts.get(nativeID), items.get(nativeID), links.get(nativeID)];
32340
+ const revision2 = digest(prs ? [...revisionParts, prs] : revisionParts);
32341
+ sessions.push({ session, revision: revision2, pullRequests: prs, locator: { path, databaseRevision, threadID: nativeID, format: "v2", metadataPartial: row.valid_payload ? "" : "1" } });
31975
32342
  }
31976
32343
  if (unreadableMetadata) warnings.push(`${unreadableMetadata} T3 Code threads had unreadable metadata; model or lineage may be unavailable.`);
31977
32344
  return { sessions, projects: [...projects.values()], warnings };
31978
32345
  }
31979
32346
  function discoverV1(db2, path, databaseRevision) {
31980
32347
  if (!hasTable(db2, "projection_threads") || !hasTable(db2, "projection_thread_messages")) throw new Error("Unsupported T3 Code database schema.");
31981
- const rows2 = db2.prepare(`SELECT thread_id, project_id, substr(title,1,300) AS title, substr(worktree_path,1,4096) AS worktree_path,
32348
+ const selected = db2.prepare(`SELECT thread_id, project_id, substr(title,1,300) AS title, substr(worktree_path,1,4096) AS worktree_path,
31982
32349
  created_at, updated_at, archived_at,
31983
32350
  CASE WHEN json_valid(model_selection_json) THEN substr(json_extract(model_selection_json,'$.model'),1,200) END AS model
31984
- FROM projection_threads WHERE deleted_at IS NULL ORDER BY created_at, thread_id LIMIT ?`).all(MAX_THREADS + 1);
31985
- const selected = rows2.slice(0, MAX_THREADS);
31986
- const roots2 = projectRoots(db2, selected.map((row) => string2(row.project_id)));
31987
- const counts = aggregates(db2, "projection_thread_messages", selected.map((row) => string2(row.thread_id)));
32351
+ FROM projection_threads WHERE deleted_at IS NULL ORDER BY created_at, thread_id`).all();
32352
+ const roots2 = projectRoots(db2, selected.map((row) => string3(row.project_id)));
32353
+ const counts = aggregates(db2, "projection_thread_messages", selected.map((row) => string3(row.thread_id)));
31988
32354
  const sessions = [], projects = /* @__PURE__ */ new Map();
31989
32355
  for (const row of selected) {
31990
- const nativeID = string2(row.thread_id), created = time2(row.created_at);
32356
+ const nativeID = string3(row.thread_id), created = time2(row.created_at);
31991
32357
  if (!nativeID || nativeID.length > 512 || !created) continue;
31992
- const directory3 = string2(row.worktree_path) || roots2.get(string2(row.project_id)) || "";
32358
+ const directory3 = string3(row.worktree_path) || roots2.get(string3(row.project_id)) || "";
31993
32359
  const p = project(SOURCE, directory3);
31994
32360
  projects.set(p.id, p);
31995
32361
  const session = blankSession(SOURCE, nativeID, directory3);
31996
32362
  Object.assign(session, {
31997
- title: string2(row.title) || "T3 Code thread",
32363
+ title: string3(row.title) || "T3 Code thread",
31998
32364
  projectID: p.id,
31999
32365
  created,
32000
32366
  updated: time2(row.updated_at) || created,
32001
32367
  archived: Boolean(row.archived_at),
32002
- model: string2(row.model) || "Unknown model",
32368
+ model: string3(row.model) || "Unknown model",
32003
32369
  agent: "T3 Code"
32004
32370
  });
32005
32371
  sessions.push({ session, revision: digest([row.updated_at, counts.get(nativeID)]), locator: { path, databaseRevision, threadID: nativeID, format: "v1" } });
32006
32372
  }
32007
32373
  const warnings = ["Legacy T3 Code V1 stores text conversations but has limited event and provider-link coverage."];
32008
- if (rows2.length > MAX_THREADS) warnings.push(`T3 Code discovery is limited to ${MAX_THREADS.toLocaleString()} threads.`);
32009
32374
  return { sessions, projects: [...projects.values()], warnings };
32010
32375
  }
32011
32376
  function v2Message(row, directory3) {
32012
- const parsed = parsedObject(row.payload_json), item = parsed || {}, type = string2(row.type), id2 = string2(row.turn_item_id);
32377
+ const parsed = parsedObject(row.payload_json), item = parsed || {}, type = string3(row.type), id2 = string3(row.turn_item_id);
32013
32378
  const role = type === "user_message" ? "user" : type === "assistant_message" ? "assistant" : type === "reasoning" ? "assistant" : "tool";
32014
32379
  const message2 = blankMessage(`item:${id2}`, time2(item.startedAt || item.createdAt), role);
32015
- const recorded = Boolean(message2.time), name = string2(item.title || item.toolName) || type.replaceAll("_", " ");
32016
- const fields2 = {
32380
+ message2.metadata = messageMetadata(item);
32381
+ if (type === "assistant_message") message2.usage = messageUsage(item);
32382
+ const recorded = Boolean(message2.time), name = string3(item.title || item.toolName) || type.replaceAll("_", " ");
32383
+ const fields3 = {
32017
32384
  nativeID: id2,
32018
32385
  nativeType: type,
32019
- parentID: string2(item.parentItemId) || void 0,
32386
+ parentID: string3(item.parentItemId) || void 0,
32020
32387
  status: status(row.status),
32021
32388
  endTime: time2(item.completedAt) || null,
32022
32389
  timeSource: recorded ? "recorded" : "unknown"
32023
32390
  };
32024
32391
  if (!parsed) {
32025
32392
  message2.partial = true;
32026
- message2.events = [eventFor(message2, id2, "event", name, "Oversized or unreadable T3 item omitted.", { ...fields2, partial: true })];
32393
+ message2.events = [eventFor(message2, id2, "event", name, "Oversized or unreadable T3 item omitted.", { ...fields3, partial: true })];
32027
32394
  return message2;
32028
32395
  }
32029
32396
  if (type === "user_message" || type === "assistant_message") {
32030
- const body2 = string2(item.text);
32397
+ const body2 = string3(item.text);
32031
32398
  if (body2) addText(message2, body2, role === "user" ? "You" : "Assistant");
32032
- message2.events = [{ ...messageEvent(message2, body2, id2), ...fields2 }];
32399
+ message2.events = [{ ...messageEvent(message2, body2, id2), ...fields3 }];
32033
32400
  if (Array.isArray(item.attachments) && item.attachments.length) message2.partial = true;
32034
32401
  return message2;
32035
32402
  }
32036
32403
  if (type === "reasoning") {
32037
- message2.events = [eventFor(message2, id2, "reasoning", "Recorded reasoning", string2(item.text), fields2)];
32404
+ message2.events = [eventFor(message2, id2, "reasoning", "Recorded reasoning", string3(item.text), fields3)];
32038
32405
  return message2;
32039
32406
  }
32040
32407
  if (type === "file_change") {
32041
- const file = string2(item.fileName), completed = status(row.status) === "completed";
32408
+ const file = string3(item.fileName), completed = status(row.status) === "completed";
32042
32409
  const native = item.nativeItemRef;
32043
32410
  if (native?.driver === "opencode" && openCodeEditTools.has(file.toLowerCase())) {
32044
32411
  message2.tools.push(file);
32045
- const kind2 = completed || fields2.status === "failed" ? "tool_result" : "tool_call";
32046
- message2.events = [eventFor(message2, id2, kind2, file, "", { ...fields2, callID: string2(native.nativeId) || void 0 })];
32412
+ const kind2 = completed || fields3.status === "failed" ? "tool_result" : "tool_call";
32413
+ message2.events = [eventFor(message2, id2, kind2, file, "", { ...fields3, callID: string3(native.nativeId) || void 0 })];
32047
32414
  return message2;
32048
32415
  }
32049
32416
  if (file && completed) message2.files.push({ path: isAbsolute2(file) ? file : join11(directory3, file), source: "file change", steps: 1 });
32050
- message2.events = [eventFor(message2, id2, "file_change", file || name, "", fields2)];
32417
+ message2.events = [eventFor(message2, id2, "file_change", file || name, "", fields3)];
32051
32418
  return message2;
32052
32419
  }
32053
32420
  if (["command_execution", "dynamic_tool", "file_search", "web_search"].includes(type)) {
32054
32421
  const input = eventText(item.input ?? item.pattern ?? item.patterns, 32e3);
32055
32422
  const output2 = eventText(item.output ?? item.results, 64e3);
32056
- const kind2 = fields2.status === "completed" || fields2.status === "failed" ? "tool_result" : "tool_call";
32423
+ const kind2 = fields3.status === "completed" || fields3.status === "failed" ? "tool_result" : "tool_call";
32057
32424
  message2.tools.push(name);
32058
32425
  if (input) addText(message2, input, "Tool");
32059
32426
  if (output2) addText(message2, output2, "Tool");
32060
32427
  const native = item.nativeItemRef;
32061
- message2.events = [eventFor(message2, id2, kind2, name, "", { ...fields2, input, output: output2, ...executionFields(parsedObject(item.input) || item.input, item), callID: string2(native?.nativeId) || void 0 })];
32428
+ message2.events = [eventFor(message2, id2, kind2, name, "", { ...fields3, input, output: output2, ...executionFields(parsedObject(item.input) || item.input, item), callID: string3(native?.nativeId) || void 0 })];
32062
32429
  return message2;
32063
32430
  }
32064
32431
  const kind = type === "compaction" ? "compaction" : type === "error" ? "error" : "event";
32065
- message2.events = [eventFor(message2, id2, kind, name, string2(item.text), fields2)];
32432
+ message2.events = [eventFor(message2, id2, kind, name, string3(item.text), fields3)];
32066
32433
  return message2;
32067
32434
  }
32068
32435
  function readV2(db2, candidate, cursor) {
@@ -32082,8 +32449,7 @@ function readV2(db2, candidate, cursor) {
32082
32449
  return {
32083
32450
  messages: page.map((row) => v2Message(row, candidate.session.directory)),
32084
32451
  cursor: rows2.length > PAGE && last ? `${last.ordinal}:${last.turn_item_id}` : void 0,
32085
- partial: candidate.locator.metadataPartial === "1" || page.some((row) => !parsedObject(row.payload_json)),
32086
- note: "T3 Code app-owned messages and activity. Attachments and checkpoint file snapshots are not imported; provider-native histories may contain additional detail."
32452
+ partial: candidate.locator.metadataPartial === "1" || page.some((row) => !parsedObject(row.payload_json))
32087
32453
  };
32088
32454
  }
32089
32455
  function readV1(db2, candidate, cursor) {
@@ -32095,9 +32461,9 @@ function readV1(db2, candidate, cursor) {
32095
32461
  const messages = rows2.slice(0, PAGE).map((row) => {
32096
32462
  const role = row.role === "user" ? "user" : row.role === "assistant" ? "assistant" : "system";
32097
32463
  const message2 = blankMessage(`message:${row.message_id}`, time2(row.created_at), role);
32098
- const body2 = string2(row.text);
32464
+ const body2 = string3(row.text);
32099
32465
  if (body2) addText(message2, body2, role === "user" ? "You" : "Assistant");
32100
- message2.events = [{ ...messageEvent(message2, body2), nativeID: string2(row.message_id), nativeType: "legacy-message" }];
32466
+ message2.events = [{ ...messageEvent(message2, body2), nativeID: string3(row.message_id), nativeType: "legacy-message" }];
32101
32467
  message2.partial = row.text == null;
32102
32468
  return message2;
32103
32469
  });
@@ -32105,31 +32471,30 @@ function readV1(db2, candidate, cursor) {
32105
32471
  messages,
32106
32472
  cursor: rows2.length > PAGE ? String(offset + PAGE) : void 0,
32107
32473
  partial: true,
32108
- note: "Legacy T3 Code text messages only. Tool activity, attachments, and provider links are unavailable."
32474
+ note: "Legacy T3 Code: conversation text only."
32109
32475
  };
32110
32476
  }
32111
32477
  var t3CodeAdapter = {
32112
32478
  id: SOURCE,
32113
32479
  name: "T3 Code",
32114
- description: "Local T3 server threads and saved activity \xB7 no running agent required",
32480
+ description: "Local T3 threads and activity",
32115
32481
  capabilities: { history: true, forks: true, children: true, files: true },
32116
32482
  async detect() {
32117
32483
  return Boolean(await databasePath2());
32118
32484
  },
32119
32485
  async discover() {
32120
32486
  const path = await databasePath2();
32121
- if (!path) return { sessions: [], projects: [], warnings: ["T3 Code database is unavailable. Saved history is retained."] };
32487
+ if (!path) return { sessions: [], projects: [], warnings: [], errors: ["T3 Code: History database unavailable."] };
32122
32488
  for (let attempt = 0; ; attempt++) {
32123
- const databaseRevision = sqliteRevision(path);
32124
32489
  try {
32125
- return withSqliteSnapshot(path, (db2) => hasTable(db2, "orchestration_v2_projection_threads") ? discoverV2(db2, path, databaseRevision) : discoverV1(db2, path, databaseRevision), databaseRevision);
32490
+ return await withLargeSqliteSnapshot(path, (db2, databaseRevision) => hasTable(db2, "orchestration_v2_projection_threads") ? discoverV2(db2, path, databaseRevision) : discoverV1(db2, path, databaseRevision));
32126
32491
  } catch (error) {
32127
32492
  if (!(error instanceof SqliteSnapshotChangedError) || attempt >= 2) throw error;
32128
32493
  }
32129
32494
  }
32130
32495
  },
32131
32496
  async read(candidate, cursor) {
32132
- return withSqliteSnapshot(candidate.locator.path, (db2) => candidate.locator.format === "v2" ? readV2(db2, candidate, cursor) : readV1(db2, candidate, cursor), candidate.locator.databaseRevision, true);
32497
+ return withLargeSqliteSnapshot(candidate.locator.path, (db2) => candidate.locator.format === "v2" ? readV2(db2, candidate, cursor) : readV1(db2, candidate, cursor), candidate.locator.databaseRevision);
32133
32498
  }
32134
32499
  };
32135
32500
 
@@ -32196,6 +32561,8 @@ function cursorMessage(raw, fallbackID) {
32196
32561
  const time4 = cursorTime(raw.timestamp) || cursorTime(body2.timestamp) || cursorTime(body2.createdAt) || (role === "user" && typeof firstText === "string" ? cursorEnvelopeTime(firstText) : 0);
32197
32562
  const native = [raw.uuid, raw.id, body2.uuid, body2.id].find((id2) => typeof id2 === "string" && id2.length && id2.length <= 512);
32198
32563
  const msg = blankMessage(native || fallbackID, time4, role);
32564
+ msg.metadata = messageMetadata(body2);
32565
+ if (role === "assistant") msg.usage = messageUsage(body2);
32199
32566
  msg.events = role === "tool" ? [eventFor(msg, "result", "tool_result", body2.name || "Tool result", "", { callID: body2.tool_call_id, output: eventText(content, 64e3), status: "unknown" })] : role === "user" ? userBlockEvents(msg, content, cursorUserText) : blockEvents(msg, content);
32200
32567
  const kind = role === "user" ? "You" : role === "assistant" ? "Assistant" : "Tool";
32201
32568
  const text2 = (value) => addText(msg, role === "user" && typeof value === "string" ? cursorUserText(value) : value, kind);
@@ -32286,7 +32653,7 @@ function metadata(db2) {
32286
32653
  return value;
32287
32654
  }
32288
32655
  var cursorStoreMetadata = (path) => withStore(path, metadata);
32289
- function fields(data) {
32656
+ function fields2(data) {
32290
32657
  let at2 = 0;
32291
32658
  const values = [];
32292
32659
  const uint = () => {
@@ -32347,7 +32714,7 @@ function readCursorStore(path) {
32347
32714
  bytes2 += data.length;
32348
32715
  try {
32349
32716
  if (item.leaf) {
32350
- const json5 = data[0] === 123 ? data : fields(data).find((v3) => v3.field === 4)?.data;
32717
+ const json5 = data[0] === 123 ? data : fields2(data).find((v3) => v3.field === 4)?.data;
32351
32718
  if (!json5) {
32352
32719
  partial = true;
32353
32720
  continue;
@@ -32371,7 +32738,7 @@ function readCursorStore(path) {
32371
32738
  partial ||= Boolean(msg.partial);
32372
32739
  messages.push(msg);
32373
32740
  } else {
32374
- const refs = fields(data).filter((v3) => v3.field === 1 || v3.field === 2);
32741
+ const refs = fields2(data).filter((v3) => v3.field === 1 || v3.field === 2);
32375
32742
  if (!refs.length) partial = true;
32376
32743
  if (stack.length + refs.length > MAX_NODES) {
32377
32744
  partial = true;
@@ -32389,7 +32756,7 @@ function readCursorStore(path) {
32389
32756
  partial = true;
32390
32757
  }
32391
32758
  }
32392
- if (!messages.length) throw new Error("Cursor store has no readable conversation at its saved root. Previous imports are retained.");
32759
+ if (!messages.length) throw new Error("Cursor store has no readable conversation.");
32393
32760
  return { meta, messages, partial };
32394
32761
  });
32395
32762
  }
@@ -32402,7 +32769,7 @@ var MAX_BUBBLE = 8e6;
32402
32769
  var MAX_MESSAGES = 5e4;
32403
32770
  var MAX_BYTES4 = 64e6;
32404
32771
  function decode(value) {
32405
- return object2(JSON.parse(typeof value === "string" ? value : value instanceof Uint8Array ? Buffer.from(value).toString("utf8") : "{}"));
32772
+ return object3(JSON.parse(typeof value === "string" ? value : value instanceof Uint8Array ? Buffer.from(value).toString("utf8") : "{}"));
32406
32773
  }
32407
32774
  function directory2(raw) {
32408
32775
  const value = text(raw.workspaceIdentifier?.uri?.path) || text(raw.workspaceIdentifier?.uri) || text(raw.cwd);
@@ -32445,7 +32812,7 @@ function discoverComposers(path, workspace = "") {
32445
32812
  failed++;
32446
32813
  }
32447
32814
  }
32448
- if (failed) warnings.push(`${failed} legacy Cursor Composer records were unreadable or oversized; saved imports are retained.`);
32815
+ if (failed) warnings.push(`Cursor Composer: Skipped ${failed} unreadable or oversized ${failed === 1 ? "record" : "records"}.`);
32449
32816
  }
32450
32817
  const parents = /* @__PURE__ */ new Map();
32451
32818
  for (const c of sessions) for (const id2 of JSON.parse(c.locator.children)) {
@@ -32455,7 +32822,10 @@ function discoverComposers(path, workspace = "") {
32455
32822
  }
32456
32823
  for (const c of sessions) {
32457
32824
  const found = parents.get(c.session.nativeID);
32458
- if (found?.size === 1 && !found.has(c.session.nativeID)) c.session.parentID = identity("cursor", [...found][0]);
32825
+ if (found?.size === 1 && !found.has(c.session.nativeID)) {
32826
+ c.session.parentID = identity("cursor", [...found][0]);
32827
+ c.session.origin = "automated";
32828
+ }
32459
32829
  c.session.projectID = project("cursor", c.session.directory).id;
32460
32830
  c.revision = digest([c.revision, c.session.directory, c.session.parentID]);
32461
32831
  }
@@ -32482,7 +32852,7 @@ function readComposer(candidate) {
32482
32852
  const id2 = text(header.bubbleId);
32483
32853
  const stored = id2 ? get.get(`bubbleId:${nativeID}:${id2}`, MAX_BUBBLE) : void 0;
32484
32854
  if (stored) bytes2 += typeof stored.value === "string" ? Buffer.byteLength(stored.value) : stored.value.byteLength;
32485
- const raw = stored ? { ...header, ...decode(stored.value) } : { ...header, ...object2(data.conversationMap?.[id2]) };
32855
+ const raw = stored ? { ...header, ...decode(stored.value) } : { ...header, ...object3(data.conversationMap?.[id2]) };
32486
32856
  if (![1, 2].includes(raw.type)) {
32487
32857
  partial = true;
32488
32858
  continue;
@@ -32499,8 +32869,8 @@ function readComposer(candidate) {
32499
32869
  partial = true;
32500
32870
  }
32501
32871
  }
32502
- if (!messages.length) throw new Error("Composer has no readable message bodies; saved imports are retained.");
32503
- return { messages, partial: true, note: `Legacy Cursor Composer conversation order and native bubble IDs. Original creation dates are preserved; absent message timestamps remain unknown. Tool internals, attachments, encrypted bodies, and file snapshots are unavailable.${partial ? " Some missing, unsupported, or bounded bubbles were omitted." : ""}` };
32872
+ if (!messages.length) throw new Error("Composer has no readable messages.");
32873
+ return { messages, partial: true, note: partial ? "Some Composer messages were skipped." : "Composer conversation text only." };
32504
32874
  }, snapshot2);
32505
32875
  }
32506
32876
 
@@ -32547,7 +32917,7 @@ async function entries(path, warnings) {
32547
32917
  }
32548
32918
  }
32549
32919
  } catch (error) {
32550
- if (error.code !== "ENOENT") warnings.push("A Cursor history directory could not be listed. Saved imports are retained.");
32920
+ if (error.code !== "ENOENT") warnings.push("Cursor: Could not list a history directory.");
32551
32921
  }
32552
32922
  return result.sort((a, b) => a.name.localeCompare(b.name));
32553
32923
  }
@@ -32575,7 +32945,7 @@ function createCursorAdapter(options = {}) {
32575
32945
  return {
32576
32946
  id: "cursor",
32577
32947
  name: "Cursor",
32578
- description: "Local IDE transcripts, legacy Composer, subagents, and CLI / ACP stores \xB7 read-only",
32948
+ description: "Local IDE, Composer, and CLI sessions",
32579
32949
  capabilities: { history: true, forks: false, children: true, files: false },
32580
32950
  async detect() {
32581
32951
  if (await fileStats(join13(editor(), "User/globalStorage/state.vscdb"))) return true;
@@ -32591,7 +32961,7 @@ function createCursorAdapter(options = {}) {
32591
32961
  return false;
32592
32962
  },
32593
32963
  async discover() {
32594
- const warnings = [], found = /* @__PURE__ */ new Map(), blocked = /* @__PURE__ */ new Set();
32964
+ const warnings = [], errors = [], found = /* @__PURE__ */ new Map(), blocked = /* @__PURE__ */ new Set();
32595
32965
  const workspaceStores = await workspacePaths(editor(), warnings);
32596
32966
  const paths2 = [...new Set([...workspaceStores.values()].filter(Boolean))];
32597
32967
  const legacyStores = new Map([[join13(editor(), "User/globalStorage/state.vscdb"), ""], ...workspaceStores]);
@@ -32608,8 +32978,8 @@ function createCursorAdapter(options = {}) {
32608
32978
  selected.revision = digest([selected.revision, selected.session.directory]);
32609
32979
  found.set(candidate.session.id, selected);
32610
32980
  }
32611
- } catch {
32612
- warnings.push("A legacy Cursor database could not be read consistently; saved imports are retained.");
32981
+ } catch (error) {
32982
+ errors.push(`Cursor Composer: ${error instanceof SqliteSnapshotFileError ? error.message : "Could not read a history database."}`);
32613
32983
  }
32614
32984
  }
32615
32985
  const composers = new Map(found);
@@ -32617,7 +32987,7 @@ function createCursorAdapter(options = {}) {
32617
32987
  const matches = paths2.filter((path) => encode(path) === key);
32618
32988
  return matches.length === 1 ? matches[0] : "";
32619
32989
  };
32620
- let unreadable = 0, legacy = 0, scanned = 0;
32990
+ let unreadable = 0, unreadableStores = 0, legacy = 0, scanned = 0;
32621
32991
  const add = async (path, id2, kind, directory3, parent2 = "", workspaceHash = "") => {
32622
32992
  if (!validID(id2) || ++scanned > LIMIT) return;
32623
32993
  try {
@@ -32633,7 +33003,10 @@ function createCursorAdapter(options = {}) {
32633
33003
  if (kind !== "transcript" && !meta.latestRootBlobId) return;
32634
33004
  const session = blankSession("cursor", native, cwd(meta.cwd) || cwd(extra2.cwd) || directory3);
32635
33005
  session.agent = kind === "cli" ? "Cursor Agent" : kind === "acp" ? "Cursor ACP" : parent2 ? "Cursor subagent" : "Cursor IDE";
32636
- if (parent2) session.parentID = identity("cursor", parent2);
33006
+ if (parent2) {
33007
+ session.parentID = identity("cursor", parent2);
33008
+ session.origin = "automated";
33009
+ }
32637
33010
  session.title = typeof meta.name === "string" && meta.name.trim() ? meta.name : typeof extra2.title === "string" && extra2.title.trim() ? extra2.title : "Cursor session";
32638
33011
  session.title = session.title.slice(0, 300);
32639
33012
  session.created = cursorTime(meta.createdAt) || cursorTime(extra2.createdAtMs);
@@ -32660,7 +33033,7 @@ function createCursorAdapter(options = {}) {
32660
33033
  }
32661
33034
  if (!session.created) {
32662
33035
  session.created = stats.birthtimeMs > 0 ? stats.birthtimeMs : stats.mtimeMs;
32663
- locator.timeNote = "Session creation time unavailable; file creation/modification time is used for placement.";
33036
+ locator.timeNote = "Session start estimated from file time.";
32664
33037
  }
32665
33038
  if (!session.directory) locator.directoryNote = "Working directory is unknown; choose one when continuing.";
32666
33039
  session.projectID = project("cursor", session.directory).id;
@@ -32680,8 +33053,10 @@ function createCursorAdapter(options = {}) {
32680
33053
  }
32681
33054
  const candidate = { session, locator, revision: digest([5, kind, path, before, session.created, session.directory, session.parentID]) };
32682
33055
  if (!previous || rank(candidate) > rank(previous) || rank(candidate) === rank(previous) && session.updated > previous.session.updated) found.set(session.id, candidate);
32683
- } catch {
32684
- unreadable++;
33056
+ } catch (error) {
33057
+ if (error instanceof SqliteSnapshotFileError) errors.push(`Cursor: ${error.message}`);
33058
+ else if (kind !== "transcript") unreadableStores++;
33059
+ else unreadable++;
32685
33060
  if (kind !== "transcript") blocked.add(identity("cursor", id2));
32686
33061
  }
32687
33062
  };
@@ -32721,14 +33096,14 @@ function createCursorAdapter(options = {}) {
32721
33096
  if (scanned >= LIMIT) break;
32722
33097
  }
32723
33098
  if (scanned >= LIMIT) warnings.push("Cursor discovery limited to 20,000 history files.");
32724
- if (unreadable) warnings.push(`${unreadable} Cursor histories were unreadable or changed during discovery; saved imports are retained. Re-import to retry.`);
32725
- if (legacy) warnings.push(`${legacy} older plain-text Cursor transcripts are not supported.`);
32726
- warnings.push("Cursor imports local IDE JSONL, legacy Composer databases, and CLI/ACP stores. Plain-text exports, cloud-only and SDK-only history are not imported. Formats are not a stable public API.");
33099
+ if (unreadable) warnings.push(`Cursor: Skipped ${unreadable} unreadable or changing histories.`);
33100
+ if (unreadableStores) errors.push(`Cursor: Skipped ${unreadableStores} unreadable or changing ${unreadableStores === 1 ? "session store" : "session stores"}.`);
33101
+ if (legacy) warnings.push(`Cursor: Skipped ${legacy} plain-text transcripts.`);
32727
33102
  const sessions = [...found.values()].filter((c) => !blocked.has(c.session.id));
32728
33103
  return { sessions, projects: [...new Map(sessions.map((c) => {
32729
33104
  const p = project("cursor", c.session.directory);
32730
33105
  return [p.id, p];
32731
- })).values()], warnings: [...new Set(warnings)] };
33106
+ })).values()], warnings: [...new Set(warnings)], errors: [...new Set(errors)] };
32732
33107
  },
32733
33108
  async read(candidate, cursor) {
32734
33109
  const { locator } = candidate;
@@ -32740,17 +33115,12 @@ function createCursorAdapter(options = {}) {
32740
33115
  if (await snapshot(locator) !== locator.snapshot) throw new Error("Cursor session changed during import; re-import to capture the latest history.");
32741
33116
  };
32742
33117
  await verify();
32743
- const note = [
32744
- locator.kind === "transcript" ? "Cursor IDE JSONL export; tool results and pre-compaction history may be absent." : "Cursor committed conversation root; abandoned branches and system prompts are excluded.",
32745
- "No file snapshots or inferred edit evidence. Missing message timestamps stay unknown.",
32746
- locator.timeNote,
32747
- locator.directoryNote
32748
- ].filter(Boolean).join(" ");
33118
+ const notes = [locator.kind === "transcript" ? "Tool results and earlier messages may be missing." : void 0, locator.timeNote, locator.directoryNote];
32749
33119
  if (locator.kind !== "transcript") {
32750
33120
  if (cursor) throw new Error("Invalid Cursor store cursor.");
32751
33121
  const result = readCursorStore(locator.path);
32752
33122
  await verify();
32753
- return { messages: result.messages, partial: result.partial, note: `${note}${result.partial ? " Unsupported, missing, or bounded store records were omitted (2 MB per blob, 64 MB / 50,000 nodes / 16 million text characters per session)." : ""}` };
33123
+ return { messages: result.messages, partial: result.partial, note: [...notes, result.partial ? "Some messages or tool records could not be imported." : void 0].filter(Boolean).join(" ") || void 0 };
32754
33124
  }
32755
33125
  const offset = Number(cursor || 0);
32756
33126
  if (!Number.isSafeInteger(offset) || offset < 0) throw new Error("Invalid Cursor transcript cursor.");
@@ -32761,8 +33131,8 @@ function createCursorAdapter(options = {}) {
32761
33131
  return message2 && (message2.role !== "system" || row.value?.type === "turn_ended") ? [message2] : [];
32762
33132
  });
32763
33133
  await verify();
32764
- if (!offset && page.cursor === void 0 && !messages.length) throw new Error("Cursor transcript has no readable conversation. Previous imports are retained.");
32765
- return { messages, cursor: page.cursor === void 0 ? void 0 : String(page.cursor), partial: true, note: `${note}${page.partial ? " Malformed or unsupported transcript records were skipped." : ""}` };
33134
+ if (!offset && page.cursor === void 0 && !messages.length) throw new Error("Transcript has no readable messages.");
33135
+ return { messages, cursor: page.cursor === void 0 ? void 0 : String(page.cursor), partial: true, note: [...notes, page.partial ? "Some transcript records could not be imported." : void 0].filter(Boolean).join(" ") };
32766
33136
  }
32767
33137
  };
32768
33138
  }
@@ -32776,16 +33146,19 @@ function projectRootFile(path) {
32776
33146
  return join14(parts.slice(0, parts.lastIndexOf("chats")).join(sep3), ".project_root");
32777
33147
  }
32778
33148
  function geminiConversation(contents, lines) {
32779
- const parsed = lines ? jsonLines(contents) : { rows: [object2(json3(contents))], partial: false };
33149
+ const parsed = lines ? jsonLines(contents) : { rows: [object3(json3(contents))], partial: false };
32780
33150
  let metadata2 = {};
32781
33151
  const messages = /* @__PURE__ */ new Map();
32782
33152
  const patch = (p) => {
32783
33153
  const existing = messages.get(text(p.id));
32784
33154
  if (!existing) return;
32785
33155
  if (p.content !== void 0) existing.content = p.content;
33156
+ for (const key of ["tokens", "model", "thoughts", "timestamp"]) if (key in p) existing[key] = p[key];
32786
33157
  for (const update of Array.isArray(p.toolCalls) ? p.toolCalls : []) {
32787
33158
  const call = existing.toolCalls?.find((t) => t.id === update.id);
32788
- if (call && "result" in update) call.result = update.result;
33159
+ if (call) {
33160
+ for (const key of ["result", "status", "timestamp", "args", "name"]) if (key in update) call[key] = update[key];
33161
+ }
32789
33162
  }
32790
33163
  };
32791
33164
  for (const row of parsed.rows) {
@@ -32793,9 +33166,9 @@ function geminiConversation(contents, lines) {
32793
33166
  const ids = [...messages.keys()], index = ids.indexOf(row.$rewindTo);
32794
33167
  for (const id2 of index < 0 ? ids : ids.slice(index)) messages.delete(id2);
32795
33168
  } else if (row.$patch) {
32796
- const p = object2(row.$patch);
33169
+ const p = object3(row.$patch);
32797
33170
  if (p.id) patch(p);
32798
- for (const update of Array.isArray(p.updates) ? p.updates : []) patch(object2(update));
33171
+ for (const update of Array.isArray(p.updates) ? p.updates : []) patch(object3(update));
32799
33172
  for (const id2 of Array.isArray(p.removeIds) ? p.removeIds : []) messages.delete(id2);
32800
33173
  for (const id2 of Array.isArray(p.orderIds) ? p.orderIds : []) {
32801
33174
  const value = messages.get(id2);
@@ -32805,7 +33178,7 @@ function geminiConversation(contents, lines) {
32805
33178
  }
32806
33179
  }
32807
33180
  } else if (row.$set || row.sessionId) {
32808
- const update = row.$set ? object2(row.$set) : row;
33181
+ const update = row.$set ? object3(row.$set) : row;
32809
33182
  metadata2 = { ...metadata2, ...update };
32810
33183
  if (Array.isArray(update.messages)) {
32811
33184
  if (row.$set) messages.clear();
@@ -32830,6 +33203,8 @@ var geminiAdapter = localFileAdapter({
32830
33203
  const directory3 = (files.get(projectRootFile(path)) || "").trim().slice(0, 4096);
32831
33204
  const messages = records.map((raw, index) => {
32832
33205
  const message2 = googleMessage({ id: raw.id, timestamp: raw.timestamp, role: raw.type === "user" ? "user" : raw.type === "gemini" ? "assistant" : "system", content: raw.content }, `record:${index}`);
33206
+ message2.metadata = messageMetadata(raw);
33207
+ if (raw.type === "gemini") message2.usage = googleUsage(raw.tokens, raw.id);
32833
33208
  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" }));
32834
33209
  for (const [i, call] of (Array.isArray(raw.toolCalls) ? raw.toolCalls : []).entries()) {
32835
33210
  const id2 = text(call.id) || `tool:${i}`, name = text(call.name) || "Tool";
@@ -32850,8 +33225,7 @@ var geminiAdapter = localFileAdapter({
32850
33225
  messages,
32851
33226
  parent: parent2,
32852
33227
  partial,
32853
- session: { directory: directory3, created: time(meta.startTime), title: text(meta.summary), model: text([...records].reverse().find((r) => r.model)?.model) || "Unknown model", provider: "Google", nativeResume: !parent2 && Boolean(directory3) && !sourcePath("gemini") && !process.env.SESSIONGRAPH_GEMINI_HOME && !path.includes(`${sep3}.cache${sep3}`) },
32854
- note: "Local Gemini chat records with rewind and patch reconstruction. Only explicit subagent directories form parent links; workspace paths come from the project-root marker. Binary content is omitted."
33228
+ session: { directory: directory3, origin: meta.kind === "subagent" ? "automated" : void 0, 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}`) }
32855
33229
  };
32856
33230
  }
32857
33231
  });
@@ -32874,7 +33248,9 @@ var qwenAdapter = localFileAdapter({
32874
33248
  const messages = rows2.map((raw, index) => {
32875
33249
  const id2 = text(raw.uuid) || `record:${index}`;
32876
33250
  if (raw.message && !["agent_message", "agent_mention", "notification"].includes(raw.subtype)) {
32877
- const message3 = googleMessage({ id: id2, timestamp: raw.timestamp, role: raw.type === "assistant" ? "assistant" : raw.type === "user" ? "user" : "tool", toolCallId: raw.toolCallResult?.callId, content: object2(raw.message).parts }, id2);
33251
+ const message3 = googleMessage({ id: id2, timestamp: raw.timestamp, role: raw.type === "assistant" ? "assistant" : raw.type === "user" ? "user" : "tool", toolCallId: raw.toolCallResult?.callId, content: object3(raw.message).parts }, id2);
33252
+ message3.metadata = messageMetadata(raw);
33253
+ if (raw.type === "assistant") message3.usage = googleUsage(raw.usageMetadata ?? raw.message?.usageMetadata, id2);
32878
33254
  for (const event of message3.events || []) if (event.kind === "tool_result") {
32879
33255
  event.status = raw.toolCallResult?.status === "success" ? "completed" : raw.toolCallResult?.status === "error" ? "failed" : "unknown";
32880
33256
  event.nativeType = text(raw.toolCallResult?.status);
@@ -32894,8 +33270,7 @@ var qwenAdapter = localFileAdapter({
32894
33270
  partial,
32895
33271
  parent: text(parent2) || void 0,
32896
33272
  fork: text(rows2.find((r) => r.forkedFrom?.sessionId)?.forkedFrom?.sessionId) || void 0,
32897
- session: { directory: text(first.cwd), created: time(first.timestamp), title: text(title), model: text(latest.find((r) => r.model)?.model) || text(latest.find((r) => r.subtype === "session_model")?.systemPayload?.modelId) || "Unknown model", nativeResume: Boolean(first.cwd) && !sourcePath("qwen-code") && !process.env.SESSIONGRAPH_QWEN_HOME },
32898
- note: "Local Qwen chat records, including compaction and branch events in source order. Parent and fork links use recorded session IDs. Managed-daemon-only and binary history may be unavailable."
33273
+ session: { directory: text(first.cwd), created: time(first.timestamp), title: text(title), model: text(latest.find((r) => r.model)?.model) || text(latest.find((r) => r.subtype === "session_model")?.systemPayload?.modelId) || "Unknown model", nativeResume: Boolean(first.cwd) && !sourcePath("qwen-code") && !process.env.SESSIONGRAPH_QWEN_HOME }
32899
33274
  };
32900
33275
  }
32901
33276
  });
@@ -32912,11 +33287,11 @@ var copilotAdapter = localFileAdapter({
32912
33287
  match: (path) => /(?:^|\/)events\.jsonl$/.test(path),
32913
33288
  parse(path, files) {
32914
33289
  const { rows: rows2, partial } = jsonLines(files.get(path));
32915
- const start = rows2.find((r) => r.type === "session.start"), meta = object2(start?.data);
33290
+ const start = rows2.find((r) => r.type === "session.start"), meta = object3(start?.data);
32916
33291
  if (!text(meta.sessionId)) throw new Error("Unsupported Copilot event log.");
32917
33292
  const toolNames = new Map(rows2.filter((r) => r.type === "tool.execution_start").map((r) => [r.data?.toolCallId, text(r.data?.toolName)]));
32918
33293
  const messages = rows2.filter((r) => !r.ephemeral && !["assistant.message_delta", "assistant.reasoning_delta"].includes(r.type)).map((raw, index) => {
32919
- const data = object2(raw.data), kind = text(raw.type), human = kind === "user.message" && !data.isAutopilotContinuation && !data.source;
33294
+ const data = object3(raw.data), kind = text(raw.type), human = kind === "user.message" && !data.isAutopilotContinuation && !data.source;
32920
33295
  const message2 = blankMessage(text(raw.id) || `record:${index}`, time(raw.timestamp), human ? "user" : kind === "assistant.message" ? "assistant" : kind.startsWith("tool.") ? "tool" : "system");
32921
33296
  if (["user.message", "assistant.message"].includes(kind)) {
32922
33297
  const content = text(data.content);
@@ -32948,8 +33323,7 @@ var copilotAdapter = localFileAdapter({
32948
33323
  messages,
32949
33324
  partial,
32950
33325
  parent: text(meta.detachedFromSpawningParentSessionId) || void 0,
32951
- session: { directory: text(meta.context?.cwd), created: time(meta.startTime || start?.timestamp), title: text(latest.find((r) => r.type === "session.title_changed")?.data?.title), model: text(latest.find((r) => r.type === "session.model_change")?.data?.newModel) || text(meta.selectedModel) || "Unknown model", provider: text(meta.providerId), nativeResume: Boolean(meta.context?.cwd) && !sourcePath("copilot") && !process.env.SESSIONGRAPH_COPILOT_HOME },
32952
- note: "Persisted Copilot CLI events only. Streaming deltas are excluded in favor of final messages. Tool-call parents are event correlations, not session ancestry. Cloud-only sessions and binary assets are unavailable."
33326
+ session: { directory: text(meta.context?.cwd), created: time(meta.startTime || start?.timestamp), title: text(latest.find((r) => r.type === "session.title_changed")?.data?.title), model: text(latest.find((r) => r.type === "session.model_change")?.data?.newModel) || text(meta.selectedModel) || "Unknown model", provider: text(meta.providerId), nativeResume: Boolean(meta.context?.cwd) && !sourcePath("copilot") && !process.env.SESSIONGRAPH_COPILOT_HOME }
32953
33327
  };
32954
33328
  }
32955
33329
  });
@@ -32965,7 +33339,7 @@ function vscodeChatLog(content) {
32965
33339
  for (const line of content.split("\n")) {
32966
33340
  if (!line.trim()) continue;
32967
33341
  if (++records > 5e4) throw new Error("Chat log exceeds the 50,000-operation limit.");
32968
- const entry = object2(JSON.parse(line));
33342
+ const entry = object3(JSON.parse(line));
32969
33343
  if (entry.kind === 0) {
32970
33344
  if (records !== 1 || !entry.v || typeof entry.v !== "object" || Array.isArray(entry.v)) throw new Error("Invalid chat log initial state.");
32971
33345
  state2 = entry.v;
@@ -33003,15 +33377,15 @@ function vscodeChatLog(content) {
33003
33377
  }
33004
33378
 
33005
33379
  // server/adapters/copilot-chat.ts
33006
- function copilotChatRoots(platform = process.platform, home = homedir11(), env = process.env) {
33380
+ function copilotChatRoots(platform = process.platform, home = homedir11(), env2 = process.env) {
33007
33381
  const path = platform === "win32" ? win323 : posix2;
33008
- const base = platform === "darwin" ? path.join(home, "Library", "Application Support") : platform === "win32" ? env.APPDATA || path.join(home, "AppData", "Roaming") : env.XDG_CONFIG_HOME || path.join(home, ".config");
33009
- const override = sourcePath("copilot-chat") || env.SESSIONGRAPH_COPILOT_CHAT_USER_DATA_DIR;
33382
+ const base = platform === "darwin" ? path.join(home, "Library", "Application Support") : platform === "win32" ? env2.APPDATA || path.join(home, "AppData", "Roaming") : env2.XDG_CONFIG_HOME || path.join(home, ".config");
33383
+ const override = sourcePath("copilot-chat") || env2.SESSIONGRAPH_COPILOT_CHAT_USER_DATA_DIR;
33010
33384
  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"))];
33011
33385
  return users.flatMap((user) => [path.join(user, "workspaceStorage"), path.join(user, "globalStorage", "emptyWindowChatSessions")]);
33012
33386
  }
33013
33387
  function vscodeChatPath(value) {
33014
- const raw = object2(value);
33388
+ const raw = object3(value);
33015
33389
  if (raw.scheme) {
33016
33390
  if (raw.scheme !== "file") return `${text(raw.scheme)}://${text(raw.authority)}${text(raw.path)}`;
33017
33391
  const path = text(raw.path);
@@ -33026,26 +33400,26 @@ function vscodeChatPath(value) {
33026
33400
  return "";
33027
33401
  }
33028
33402
  }
33029
- var markdown = (value) => typeof value === "string" ? value : text(object2(value).value);
33403
+ var markdown = (value) => typeof value === "string" ? value : text(object3(value).value);
33030
33404
  var recordedTime = (value) => ({ time: time(value) || null, timeSource: time(value) ? "recorded" : "unknown" });
33031
33405
  function responsePart(message2, value, index) {
33032
- const part = object2(value), kind = text(part.kind), id2 = `part:${index}`;
33033
- const fields2 = { nativeType: kind || "markdown", nativeID: text(part.id) || void 0 };
33406
+ const part = object3(value), kind = text(part.kind), id2 = `part:${index}`;
33407
+ const fields3 = { nativeType: kind || "markdown", nativeID: text(part.id) || void 0 };
33034
33408
  if (typeof value === "string" || !kind && typeof part.value === "string" || kind === "markdownContent" || kind === "markdownVuln") {
33035
33409
  const content = markdown(kind ? part.content : value);
33036
- message2.events.push(eventFor(message2, id2, "message", "Assistant message", content, fields2));
33410
+ message2.events.push(eventFor(message2, id2, "message", "Assistant message", content, fields3));
33037
33411
  addText(message2, content, "Assistant");
33038
33412
  } else if (kind === "thinking") {
33039
33413
  const content = Array.isArray(part.value) ? part.value.filter((v3) => typeof v3 === "string").join("\n") : markdown(part.value);
33040
- message2.events.push(eventFor(message2, id2, "reasoning", "Recorded reasoning", content, { ...fields2, ...recordedTime(part.reasoningStartedAt) }));
33414
+ message2.events.push(eventFor(message2, id2, "reasoning", "Recorded reasoning", content, { ...fields3, ...recordedTime(part.reasoningStartedAt) }));
33041
33415
  addText(message2, content, "Tool");
33042
33416
  } else if (kind === "toolInvocationSerialized") {
33043
- const data = object2(part.toolSpecificData), command = object2(data.commandLine), details = object2(part.resultDetails);
33417
+ const data = object3(part.toolSpecificData), command = object3(data.commandLine), details = object3(part.resultDetails);
33044
33418
  const name = text(part.toolId) || "Tool", callID = text(part.toolCallId) || void 0;
33045
33419
  const input = eventText(data.rawInput ?? command.userEdited ?? command.toolEdited ?? command.original ?? details.input);
33046
- const denied = part.isConfirmed === false || [0, 5].includes(object2(part.isConfirmed).type);
33420
+ const denied = part.isConfirmed === false || [0, 5].includes(object3(part.isConfirmed).type);
33047
33421
  const status2 = denied || part.resultError ? "failed" : part.isComplete === true ? "completed" : "unknown";
33048
- const correlation = { ...fields2, callID, parentID: text(part.subAgentInvocationId) || void 0 };
33422
+ const correlation = { ...fields3, callID, parentID: text(part.subAgentInvocationId) || void 0 };
33049
33423
  message2.events.push(eventFor(message2, `${id2}:call`, "tool_call", name, markdown(part.invocationMessage), { ...correlation, ...recordedTime(part.startedAt), input, status: "unknown" }));
33050
33424
  message2.tools.push(name);
33051
33425
  addText(message2, input, "Tool");
@@ -33055,7 +33429,7 @@ function responsePart(message2, value, index) {
33055
33429
  addText(message2, output2, "Tool");
33056
33430
  } else message2.partial = true;
33057
33431
  } else {
33058
- message2.events.push(eventFor(message2, id2, "event", kind || "Unsupported chat content", eventText(part), { ...fields2, partial: true }));
33432
+ message2.events.push(eventFor(message2, id2, "event", kind || "Unsupported chat content", eventText(part), { ...fields3, partial: true }));
33059
33433
  message2.partial = true;
33060
33434
  }
33061
33435
  }
@@ -33065,13 +33439,17 @@ function chatMessages(requests) {
33065
33439
  const requestID = text(request.requestId) || `request:${index}`;
33066
33440
  const injected = Boolean(request.isSystemInitiated || request.hiddenFromTranscript || request.requestHiddenFromTranscript);
33067
33441
  const user = blankMessage(requestID, time(request.timestamp), injected ? "system" : "user");
33068
- const content = typeof request.message === "string" ? request.message : text(object2(request.message).text);
33442
+ const content = typeof request.message === "string" ? request.message : text(object3(request.message).text);
33069
33443
  user.events = [eventFor(user, "message", injected ? "event" : "message", injected ? "Injected message" : "User message", content, { nativeID: requestID, ...recordedTime(request.timestamp) })];
33070
33444
  addText(user, content, injected ? "Tool" : "You");
33071
33445
  if (request.variableData?.variables?.length) user.partial = true;
33072
33446
  const messages = [user];
33073
33447
  if (request.response !== void 0 || request.result?.errorDetails || request.responseErrorDetails || request.editedFileEvents?.length) {
33074
33448
  const assistant = blankMessage(text(request.responseId) || `response:${requestID}`, time(request.responseTimestamp), "assistant");
33449
+ const metadata2 = object3(request.result?.metadata);
33450
+ const input = request.promptTokens ?? metadata2.promptTokens, output2 = request.completionTokens ?? metadata2.outputTokens;
33451
+ assistant.usage = recordedUsage({ input, output: output2, total: sumTokens([input, output2]), inputIncludesCache: true, outputIncludesReasoning: true }, "message", request.responseId || requestID);
33452
+ assistant.metadata = messageMetadata({ model: metadata2.resolvedModel || request.modelId });
33075
33453
  assistant.events = [];
33076
33454
  const parts = Array.isArray(request.response) ? request.response : request.response == null ? [] : [request.response];
33077
33455
  if (parts.length > 200) assistant.partial = true;
@@ -33108,20 +33486,20 @@ var filesAdapter = localFileAdapter({
33108
33486
  extras: (path) => [...basename6(dirname4(path)) === "chatSessions" ? [join17(dirname4(dirname4(path)), "workspace.json")] : [], ...path.endsWith(".json") ? [`${path}l`] : []],
33109
33487
  parse(path, files) {
33110
33488
  const log = path.endsWith(".jsonl") ? path : `${path}l`;
33111
- const data = files.has(log) ? vscodeChatLog(files.get(log)) : object2(JSON.parse(files.get(path)));
33489
+ const data = files.has(log) ? vscodeChatLog(files.get(log)) : object3(JSON.parse(files.get(path)));
33112
33490
  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.");
33113
33491
  if (data.sessionId !== basename6(path).replace(/\.jsonl?$/, "")) throw new Error("VS Code chat identity mismatch.");
33114
33492
  if (!data.requests.length) return;
33115
33493
  if (data.requests.length > 25e3) throw new Error("Chat exceeds the 50,000-message limit.");
33116
33494
  const workspacePath = join17(dirname4(dirname4(path)), "workspace.json");
33117
- const workspace = files.has(workspacePath) ? object2(JSON.parse(files.get(workspacePath))) : {};
33495
+ const workspace = files.has(workspacePath) ? object3(JSON.parse(files.get(workspacePath))) : {};
33118
33496
  const messages = chatMessages(data.requests);
33119
33497
  const model = [...data.requests].reverse().find((r) => text(r.modelId));
33120
33498
  return {
33121
33499
  nativeID: data.sessionId,
33122
33500
  messages,
33123
33501
  session: { title: text(data.customTitle) || text(data.computedTitle), created: time(data.creationDate), directory: vscodeChatPath(data.workingDirectory || workspace.folder), model: text(model?.modelId) || "Unknown model" },
33124
- note: "Persisted VS Code Chat UI history, including Copilot participants. Attachments, pre-compaction content, and transient UI state may be absent. Accepted-edit records provide file evidence; proposed edits and references do not. Multi-root workspaces without an explicit working directory remain unassigned. Tool subagent IDs are event correlations, not session ancestry."
33502
+ note: "Earlier messages may be missing."
33125
33503
  };
33126
33504
  }
33127
33505
  });
@@ -33132,13 +33510,41 @@ var copilotChatAdapter = { ...filesAdapter, async detect() {
33132
33510
  // server/adapters/extensions.ts
33133
33511
  import { homedir as homedir12 } from "node:os";
33134
33512
  import { basename as basename7, dirname as dirname5, join as join18 } from "node:path";
33513
+ function taskUsage(value, source) {
33514
+ if (!Array.isArray(value)) return;
33515
+ const records = /* @__PURE__ */ new Map();
33516
+ value.forEach((row, index) => {
33517
+ if (row?.type !== "say" || row.say !== "api_req_started" || typeof row.text !== "string") return;
33518
+ let payload;
33519
+ try {
33520
+ payload = object3(JSON.parse(row.text));
33521
+ } catch {
33522
+ return;
33523
+ }
33524
+ const caches = [payload.cacheReads, payload.cacheWrites];
33525
+ const includesCache = source === "cline" ? false : caches.every((value2) => tokenCount(value2) === 0) ? true : null;
33526
+ const usage = recordedUsage({
33527
+ input: payload.tokensIn,
33528
+ output: payload.tokensOut,
33529
+ cacheRead: payload.cacheReads,
33530
+ cacheWrite: payload.cacheWrites,
33531
+ total: tokenCount(payload.totalTokens) ?? (includesCache === false ? sumTokens([payload.tokensIn, payload.tokensOut, ...caches]) : includesCache === true ? sumTokens([payload.tokensIn, payload.tokensOut]) : null),
33532
+ inputIncludesCache: includesCache,
33533
+ outputIncludesReasoning: true,
33534
+ cost: recordedCost(payload.cost),
33535
+ costEstimated: true
33536
+ });
33537
+ if (usage) records.set(typeof row.id === "string" ? row.id : row.ts != null ? String(row.ts) : `row:${index}`, usage);
33538
+ });
33539
+ return sessionUsage(sumUsage([...records.values()]));
33540
+ }
33135
33541
  function editorTaskRoots(extension) {
33136
33542
  const home = homedir12();
33137
33543
  const base = process.platform === "darwin" ? join18(home, "Library", "Application Support") : process.platform === "win32" ? process.env.APPDATA || join18(home, "AppData", "Roaming") : process.env.XDG_CONFIG_HOME || join18(home, ".config");
33138
33544
  return ["Code", "Code - Insiders", "VSCodium", "Cursor", "Windsurf"].map((app) => join18(base, app, "User", "globalStorage", extension, "tasks")).concat([".vscode-server", ".vscode-server-insiders"].map((app) => join18(home, app, "data", "User", "globalStorage", extension, "tasks")));
33139
33545
  }
33140
- function taskAdapter(id2, name, extension, env) {
33141
- const home = () => sourcePath(id2) || process.env[env];
33546
+ function taskAdapter(id2, name, extension, env2) {
33547
+ const home = () => sourcePath(id2) || process.env[env2];
33142
33548
  const roots2 = () => home() ? [join18(home(), "tasks"), ...id2 === "cline" ? [join18(home(), "data", "sessions")] : []] : [...editorTaskRoots(extension), ...id2 === "cline" ? [process.env.CLINE_SESSION_DATA_DIR || join18(process.env.CLINE_DATA_DIR || join18(process.env.CLINE_DIR || join18(homedir12(), ".cline"), "data"), "sessions")] : []];
33143
33549
  return localFileAdapter({
33144
33550
  id: id2,
@@ -33147,17 +33553,31 @@ function taskAdapter(id2, name, extension, env) {
33147
33553
  capabilities: { history: true, forks: id2 === "cline", children: true, files: true },
33148
33554
  roots: roots2,
33149
33555
  match: (path) => /^[^/]+\/api_conversation_history\.json$/.test(path) || id2 === "cline" && /^[^/]+\/[^/]+\.messages\.json$/.test(path),
33150
- extras: (path) => ["history_item.json", "task_metadata.json", "session.json"].map((file) => join18(dirname5(path), file)),
33556
+ extras: (path) => ["history_item.json", "task_metadata.json", "session.json", "ui_messages.json"].map((file) => join18(dirname5(path), file)),
33151
33557
  parse(path, files) {
33152
33558
  const sdk = path.endsWith(".messages.json"), value = json3(files.get(path));
33153
- const records = sdk ? object2(value).messages : value;
33559
+ const records = sdk ? object3(value).messages : value;
33154
33560
  if (!Array.isArray(records) || sdk && !text(value.sessionId)) throw new Error("Unsupported task history.");
33155
- const read3 = (name2) => object2(files.has(join18(dirname5(path), name2)) ? json3(files.get(join18(dirname5(path), name2))) : void 0);
33561
+ const read3 = (name2) => object3(files.has(join18(dirname5(path), name2)) ? json3(files.get(join18(dirname5(path), name2))) : void 0);
33156
33562
  const history = read3("history_item.json"), info = read3("session.json"), task = read3("task_metadata.json");
33157
33563
  const nativeID = sdk ? value.sessionId : basename7(dirname5(path));
33158
33564
  if (history.id && history.id !== nativeID || info.session_id && info.session_id !== nativeID) throw new Error("Task metadata identity mismatch.");
33159
33565
  const messages = records.map((raw, index) => {
33160
- const row = object2(raw), message2 = conversationMessage(row, `record:${index}`);
33566
+ const row = object3(raw), message2 = conversationMessage(row, `record:${index}`);
33567
+ if (sdk && message2.role === "assistant" && row.metrics) {
33568
+ const metrics = object3(row.metrics);
33569
+ message2.usage = recordedUsage({
33570
+ input: metrics.inputTokens,
33571
+ output: metrics.outputTokens,
33572
+ cacheRead: metrics.cacheReadTokens,
33573
+ cacheWrite: metrics.cacheWriteTokens,
33574
+ total: sumTokens([metrics.inputTokens, metrics.outputTokens]),
33575
+ inputIncludesCache: true,
33576
+ outputIncludesReasoning: true,
33577
+ cost: recordedCost(metrics.cost),
33578
+ costEstimated: true
33579
+ }, "message", row.id);
33580
+ }
33161
33581
  if (row.isSummary || row.isTruncationMarker || row.type === "reasoning") {
33162
33582
  message2.role = "system";
33163
33583
  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" })];
@@ -33174,8 +33594,15 @@ function taskAdapter(id2, name, extension, env) {
33174
33594
  partial: !sdk,
33175
33595
  parent: text(history.parentTaskId || info.parent_session_id) || void 0,
33176
33596
  fork: text(info.metadata?.fork?.forkedFromSessionId) || void 0,
33177
- session: { directory: text(history.workspace || info.cwd || info.workspace_root || task.workspace), created: time(info.started_at), title: text(history.task || info.metadata?.title), model: text(lastModel?.modelInfo?.id || lastModel?.model || info.model) || "Unknown model", provider: text(lastModel?.modelInfo?.provider || info.provider) },
33178
- note: sdk ? "Cline CLI/SDK message snapshots. Metadata is used when a matching session.json exists; database-only workspace, title, and lineage fields remain unknown. Binary attachments are omitted." : `${name} API-conversation snapshots; UI-only messages, older compacted content, and binary attachments can be absent. XML tool requests alone are not successful edit evidence.${id2 === "kilo-code" ? " Select the separate Kilo CLI source for its SQLite history." : ""}`
33597
+ session: {
33598
+ directory: text(history.workspace || info.cwd || info.workspace_root || task.workspace),
33599
+ created: time(info.started_at),
33600
+ title: text(history.task || info.metadata?.title),
33601
+ model: text(lastModel?.modelInfo?.id || lastModel?.model || info.model) || "Unknown model",
33602
+ provider: text(lastModel?.modelInfo?.provider || info.provider),
33603
+ usage: !sdk && files.has(join18(dirname5(path), "ui_messages.json")) ? taskUsage(json3(files.get(join18(dirname5(path), "ui_messages.json"))), id2) : void 0
33604
+ },
33605
+ note: sdk ? void 0 : "Earlier and editor-only messages may be missing."
33179
33606
  };
33180
33607
  }
33181
33608
  });
@@ -33193,22 +33620,36 @@ var continueAdapter = localFileAdapter({
33193
33620
  extras: (path) => [join18(dirname5(path), "sessions.json")],
33194
33621
  revisionExtras: false,
33195
33622
  parse(path, files) {
33196
- const value = object2(json3(files.get(path)));
33623
+ const value = object3(json3(files.get(path)));
33197
33624
  if (!text(value.sessionId) || !Array.isArray(value.history)) throw new Error("Unsupported Continue session.");
33198
33625
  const indexPath = join18(dirname5(path), "sessions.json"), index = files.has(indexPath) ? json3(files.get(indexPath)) : [];
33199
- const meta = Array.isArray(index) ? object2(index.find((r) => r.sessionId === value.sessionId)) : {};
33626
+ const meta = Array.isArray(index) ? object3(index.find((r) => r.sessionId === value.sessionId)) : {};
33200
33627
  const messages = value.history.map((item, i) => {
33201
- const row = object2(item), raw = object2(row.message), message2 = conversationMessage(raw, `record:${i}`);
33628
+ const row = object3(item), raw = object3(row.message), message2 = conversationMessage(raw, `record:${i}`);
33202
33629
  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" }));
33203
33630
  if (row.conversationSummary) message2.events.push(eventFor(message2, "summary", "compaction", "Conversation summary", text(row.conversationSummary)));
33204
33631
  return message2;
33205
33632
  });
33206
- const usage = object2(value.usage);
33633
+ const usage = object3(value.usage);
33207
33634
  return {
33208
33635
  nativeID: value.sessionId,
33209
33636
  messages,
33210
- session: { directory: text(value.workspaceDirectory), title: text(value.title), created: time(meta.dateCreated), model: text(value.chatModelTitle) || "Unknown model", cost: typeof usage.totalCost === "number" ? usage.totalCost : null, tokens: sumRecordedTokens([usage.promptTokens, usage.completionTokens]) },
33211
- note: "Local Continue conversation snapshots. Missing message times remain unknown. Context attachments and transient tool UI state are not imported; tool outputs are retained when recorded as messages."
33637
+ session: {
33638
+ directory: text(value.workspaceDirectory),
33639
+ title: text(value.title),
33640
+ created: time(meta.dateCreated),
33641
+ model: text(value.chatModelTitle) || "Unknown model",
33642
+ cost: recordedCost(usage.totalCost),
33643
+ tokens: sumRecordedTokens([usage.promptTokens, usage.completionTokens]),
33644
+ usage: sessionUsage(recordedUsage({
33645
+ input: usage.promptTokens,
33646
+ output: usage.completionTokens,
33647
+ total: sumTokens([usage.promptTokens, usage.completionTokens]),
33648
+ inputIncludesCache: true,
33649
+ outputIncludesReasoning: true,
33650
+ cost: recordedCost(usage.totalCost)
33651
+ }))
33652
+ }
33212
33653
  };
33213
33654
  }
33214
33655
  });
@@ -33224,7 +33665,7 @@ var dataPath = (...parts) => join19(process.env.XDG_DATA_HOME || homePath(".loca
33224
33665
  var configPath = (...parts) => join19(process.env.XDG_CONFIG_HOME || homePath(".config"), ...parts);
33225
33666
  var appPath = (...parts) => join19(process.platform === "darwin" ? homePath("Library/Application Support") : process.platform === "win32" ? process.env.APPDATA || homePath("AppData/Roaming") : process.env.XDG_CONFIG_HOME || homePath(".config"), ...parts);
33226
33667
  var tokscalePath = (...parts) => join19(process.env.TOKSCALE_CONFIG_DIR || (process.platform === "win32" ? appPath("tokscale") : configPath("tokscale")), ...parts);
33227
- var envHome = (env, fallback, ...parts) => join19(process.env[env]?.trim() || homePath(fallback), ...parts);
33668
+ var envHome = (env2, fallback, ...parts) => join19(process.env[env2]?.trim() || homePath(fallback), ...parts);
33228
33669
  var harnessRoots = (id2, defaults) => () => {
33229
33670
  const override = sourcePath(id2) || process.env[`SESSIONGRAPH_${id2.replace(/-/g, "_").toUpperCase()}_HISTORY_DIR`]?.trim();
33230
33671
  return override ? [override] : defaults();
@@ -33233,7 +33674,7 @@ var harnessRoots = (id2, defaults) => () => {
33233
33674
  // server/adapters/harness-extra-formats.ts
33234
33675
  import { basename as basename8, dirname as dirname6, join as join20 } from "node:path";
33235
33676
  function kiroHistory(path, files) {
33236
- const header = object2(json3(files.get(path)));
33677
+ const header = object3(json3(files.get(path)));
33237
33678
  const ide2 = basename8(path) === "session.json";
33238
33679
  const nativeID = text(header.session_id || header.sessionId || header.id) || (ide2 ? basename8(dirname6(path)) : "");
33239
33680
  if (!nativeID) throw new Error("Unsupported Kiro session header.");
@@ -33242,12 +33683,12 @@ function kiroHistory(path, files) {
33242
33683
  const { rows: rows2 } = jsonLines(files.get(side));
33243
33684
  const messages = rows2.flatMap((r, i) => {
33244
33685
  if (ide2) {
33245
- const p = object2(r.payload || r);
33686
+ const p = object3(r.payload || r);
33246
33687
  const role2 = p.type === "human" ? "user" : p.type === "ai" ? "assistant" : p.role || p.type;
33247
33688
  const m3 = message({ ...p, role: role2 }, text(p.id) || `message:${i}`, r.timestamp);
33248
33689
  return m3 ? [m3] : [recordEvent(r, `event:${i}`, text(p.type) || "Kiro event", r.timestamp, p.text)];
33249
33690
  }
33250
- const data = object2(r.data), role = r.kind === "Prompt" ? "user" : r.kind === "AssistantMessage" ? "assistant" : r.kind === "ToolResults" ? "tool" : "";
33691
+ const data = object3(r.data), role = r.kind === "Prompt" ? "user" : r.kind === "AssistantMessage" ? "assistant" : r.kind === "ToolResults" ? "tool" : "";
33251
33692
  if (!role) return [];
33252
33693
  const content = Array.isArray(data.content) ? data.content.map((p) => p.kind === "text" ? { type: "text", text: p.data } : { type: "unsupported" }) : void 0;
33253
33694
  const m = message({ role, content }, text(data.message_id) || `message:${i}`, seconds(data.meta?.timestamp));
@@ -33259,7 +33700,7 @@ function kiroHistory(path, files) {
33259
33700
  messages,
33260
33701
  partial: true,
33261
33702
  session: { directory: text(header.cwd) || (header.workspacePaths?.length === 1 ? text(header.workspacePaths[0]) : ""), created: time(header.createdAt), title: text(header.title), model: text(header.modelId || header.session_state?.rts_model_state?.model_info?.model_id) || "Unknown model" },
33262
- note: "Kiro CLI header/JSONL and IDE session snapshots. Unsupported payload variants and compacted context may be absent. Token estimates and credit conversions are not imported."
33703
+ note: "Earlier messages and some tool details may be missing."
33263
33704
  };
33264
33705
  }
33265
33706
  function muxHistory(path, files) {
@@ -33281,22 +33722,31 @@ function muxHistory(path, files) {
33281
33722
  return m ? [m] : [];
33282
33723
  });
33283
33724
  if (!messages.length) throw new Error("No readable Mux conversation.");
33284
- return {
33285
- nativeID: basename8(dirname6(path)),
33286
- messages,
33287
- partial: true,
33288
- note: "Mux durable chat archive followed by active chat, deduplicated by native message ID. In-flight partial.json and workspace ancestry are unavailable. Cumulative usage snapshots are not turns."
33289
- };
33725
+ const usagePath = join20(dirname6(path), "session-usage.json");
33726
+ const usage = files.has(usagePath) ? object3(json3(files.get(usagePath))) : {};
33727
+ const models = Object.values(object3(usage.byModel)).slice(0, 5e4).map((value) => {
33728
+ const row = object3(value), buckets = [row.input, row.cached, row.cacheCreate, row.output, row.reasoning].map(object3);
33729
+ return recordedUsage({
33730
+ input: row.input?.tokens,
33731
+ output: row.output?.tokens,
33732
+ cacheRead: row.cached?.tokens,
33733
+ cacheWrite: row.cacheCreate?.tokens,
33734
+ reasoning: row.reasoning?.tokens,
33735
+ total: sumTokens(buckets.map((bucket) => bucket.tokens)),
33736
+ inputIncludesCache: false,
33737
+ outputIncludesReasoning: false,
33738
+ cost: buckets.every((bucket) => recordedCost(bucket.cost_usd) !== null) ? buckets.reduce((sum, bucket) => sum + bucket.cost_usd, 0) : null
33739
+ });
33740
+ }).filter((value) => value !== void 0);
33741
+ return { nativeID: basename8(dirname6(path)), messages, partial: true, session: { usage: sessionUsage(sumUsage(models), models.some((value) => value.total === null)) } };
33290
33742
  }
33291
33743
  function devinDesktopHistory(path, files) {
33292
33744
  const { rows: rows2 } = jsonLines(files.get(path));
33293
33745
  const normalized = rows2.flatMap((r) => {
33294
- const n = object2(r.notification);
33746
+ const n = object3(r.notification);
33295
33747
  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 }] : [];
33296
33748
  });
33297
- const history = acpHistory(path, normalized.map((r) => JSON.stringify(r)).join("\n"));
33298
- history.note = "Devin Desktop saved ACP notification chunks. File/native identity is preserved; titles are never used to merge desktop and CLI sessions. Tool internals and turn boundaries may be incomplete.";
33299
- return history;
33749
+ return acpHistory(path, normalized.map((r) => JSON.stringify(r)).join("\n"));
33300
33750
  }
33301
33751
 
33302
33752
  // server/adapters/harness-files.ts
@@ -33326,7 +33776,7 @@ function kimiHistory(path, files) {
33326
33776
  messages,
33327
33777
  partial: true,
33328
33778
  session: { created: seconds(wireRows.find((r) => r.timestamp)?.timestamp) },
33329
- note: "Kimi persisted context, including tool messages. Earlier compacted context and wire-only activity may be absent. Context messages carry no reliable turn times; wire times are used only for session placement."
33779
+ note: "Message times unavailable. Earlier messages may be missing."
33330
33780
  };
33331
33781
  }
33332
33782
  function museHistory(path, files) {
@@ -33336,55 +33786,65 @@ function museHistory(path, files) {
33336
33786
  if (!meta || ids.size > 1) throw new Error("Unsupported Muse stream.");
33337
33787
  const nativeID = [...ids][0] || basename9(dirname7(path));
33338
33788
  const messages = rows2.flatMap((r, i) => {
33339
- const event = object2(r.payload?.event), body2 = object2(event.message);
33789
+ const event = object3(r.payload?.event), body2 = object3(event.message);
33340
33790
  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);
33341
33791
  const m = message(body2, nativeText(r.sequence) || `record:${i}`, at2);
33342
33792
  if (m) return [m];
33343
33793
  return text(event.kind) ? [recordEvent(r, nativeText(r.sequence) || `record:${i}`, event.kind, at2, event.text)] : [];
33344
33794
  });
33345
- return {
33346
- nativeID,
33347
- messages,
33348
- partial: true,
33349
- session: { directory: text(meta.payload?.record?.workspace_root), model: text(meta.payload?.record?.model_id) || "Unknown model", provider: text(meta.payload?.record?.provider_id) },
33350
- note: "Muse runtime session events and recognized message payloads. Unsupported event content remains partial; no session ancestry is inferred from timestamps."
33351
- };
33795
+ return { nativeID, messages, partial: true, session: { directory: text(meta.payload?.record?.workspace_root), model: text(meta.payload?.record?.model_id) || "Unknown model", provider: text(meta.payload?.record?.provider_id) } };
33352
33796
  }
33353
33797
  function junieHistory(path, files) {
33354
33798
  const { rows: rows2 } = jsonLines(files.get(path));
33355
33799
  const messages = rows2.flatMap((r, i) => {
33356
- const e10 = object2(r.event?.agentEvent || r.event), kind = text(e10.kind);
33800
+ const e10 = object3(r.event?.agentEvent || r.event), kind = text(e10.kind);
33357
33801
  if (!kind || /State|Snapshot/.test(kind)) return [];
33358
33802
  return [recordEvent(r, text(r.id) || `event:${i}`, kind, r.timestampMs, e10.text ?? e10.prompt ?? e10.message)];
33359
33803
  });
33360
33804
  if (!messages.length) throw new Error("No supported Junie events.");
33361
- return { nativeID: basename9(dirname7(path)), messages, partial: true, note: "Junie recorded agent events. State snapshots and opaque event bodies are omitted; events without an authoritative message role are not counted as user turns." };
33805
+ return { nativeID: basename9(dirname7(path)), messages, partial: true, note: "Recorded events only." };
33362
33806
  }
33363
33807
  function augmentHistory(path, files) {
33364
- const r = object2(json3(files.get(path)));
33808
+ const r = object3(json3(files.get(path)));
33365
33809
  if (!text(r.sessionId) || !Array.isArray(r.chatHistory)) throw new Error("Unsupported Augment session.");
33366
33810
  const messages = r.chatHistory.flatMap((turn, i) => {
33367
- const exchange = object2(turn.exchange), id2 = nativeText(turn.sequenceId) || `turn:${i}`;
33811
+ const exchange = object3(turn.exchange), id2 = nativeText(turn.sequenceId) || `turn:${i}`;
33368
33812
  return [recordEvent(turn, id2, turn.completed === true ? "Completed exchange" : "Incomplete exchange", turn.finishedAt, exchange.response_text)];
33369
33813
  });
33370
- return { nativeID: r.sessionId, messages, partial: true, session: { title: text(r.title), created: time(r.created), model: text(r.agentState?.modelId) || "Unknown model" }, note: "Augment saved exchange records. Typed response-node payloads and absent prompts are not reconstructed into conversations." };
33814
+ return { nativeID: r.sessionId, messages, partial: true, session: { title: text(r.title), created: time(r.created), model: text(r.agentState?.modelId) || "Unknown model" }, note: "Recorded exchanges only." };
33371
33815
  }
33372
33816
  function fxHistory(path, files) {
33373
- const usage = object2(json3(files.get(path))), meta = sidecar2(files, join21(dirname7(path), "session.json"));
33817
+ const usage = object3(json3(files.get(path))), meta = sidecar2(files, join21(dirname7(path), "session.json"));
33374
33818
  const id2 = text(usage.session_id) || text(meta.id);
33375
33819
  if (!id2 || !usage.snapshot || meta.id && meta.id !== id2) throw new Error("Unsupported Fx session metadata.");
33820
+ const snapshot2 = object3(usage.snapshot);
33376
33821
  return {
33377
33822
  nativeID: id2,
33378
33823
  messages: [],
33379
33824
  partial: true,
33380
- session: { created: time(meta.created_at_ms), directory: text(meta.workspace_root), title: text(meta.title) },
33381
- note: "Fx session metadata only. The usage snapshot is cumulative; it contains no conversation or message timestamps."
33825
+ session: {
33826
+ created: time(meta.created_at_ms),
33827
+ directory: text(meta.workspace_root),
33828
+ title: text(meta.title),
33829
+ usage: sessionUsage(recordedUsage({
33830
+ input: snapshot2.input_tokens,
33831
+ output: snapshot2.output_tokens,
33832
+ cacheRead: snapshot2.cache_read_tokens,
33833
+ cacheWrite: snapshot2.cache_write_tokens,
33834
+ reasoning: snapshot2.reasoning_tokens,
33835
+ total: sumTokens([snapshot2.input_tokens, snapshot2.output_tokens, snapshot2.cache_read_tokens, snapshot2.cache_write_tokens, ...snapshot2.reasoning_tokens == null ? [] : [snapshot2.reasoning_tokens]]),
33836
+ inputIncludesCache: false,
33837
+ outputIncludesReasoning: false,
33838
+ cost: snapshot2.total_cost
33839
+ }))
33840
+ },
33841
+ note: "Session metadata only."
33382
33842
  };
33383
33843
  }
33384
33844
  var definitions = [
33385
33845
  ...piSources,
33386
33846
  { id: "kiro", name: "Kiro", roots: () => [homePath(".kiro/sessions"), appPath("Kiro/User/globalStorage/kiro.kiroagent")], match: (p) => p.endsWith("/session.json") || /^cli\/[^/]+\.json$/.test(p), extras: (p) => [basename9(p) === "session.json" ? join21(dirname7(p), "messages.jsonl") : p.replace(/\.json$/, ".jsonl")], parse: kiroHistory },
33387
- { id: "mux", name: "Mux", roots: () => [envHome("MUX_ROOT", ".mux", "sessions")], match: (p) => p.endsWith("/chat.jsonl"), extras: (p) => [join21(dirname7(p), "chat-archive.jsonl")], parse: muxHistory },
33847
+ { id: "mux", name: "Mux", roots: () => [envHome("MUX_ROOT", ".mux", "sessions")], match: (p) => p.endsWith("/chat.jsonl"), extras: (p) => [join21(dirname7(p), "chat-archive.jsonl"), join21(dirname7(p), "session-usage.json")], parse: muxHistory },
33388
33848
  { id: "devin-desktop", name: "Devin Desktop", roots: () => [appPath("Devin/User/acp-events")], match: (p) => /\.(ndjson|jsonl)$/.test(p), parse: devinDesktopHistory },
33389
33849
  { id: "openclaw", name: "OpenClaw", roots: openclawRoots, match: (p) => /(?:^|\/)sessions\/.*\.jsonl(?:\.[\w.-]+)?$/.test(p) || /session-sqlite-import-archive\/.*\.jsonl\./.test(p), parse: piParse },
33390
33850
  { id: "amp", name: "Amp", roots: () => [dataPath("amp/threads"), tokscalePath("amp-cache/threads")], match: (p) => p.endsWith(".json"), parse: ampHistory },
@@ -33410,27 +33870,27 @@ var definitions = [
33410
33870
  { id: "muse", name: "Muse Code", roots: () => [dataPath("muse/sessions")], match: (p) => p.endsWith("/session.jsonl"), parse: museHistory },
33411
33871
  { id: "junie", name: "Junie", roots: () => [homePath(".junie/sessions")], match: (p) => p.endsWith("/events.jsonl"), parse: junieHistory, description: "Local agent event history \xB7 partial conversation coverage" },
33412
33872
  { id: "augment", name: "Augment Code", roots: () => [homePath(".augment/sessions")], match: (p) => p.endsWith(".json"), parse: augmentHistory, description: "Local exchange records \xB7 partial conversation coverage" },
33413
- { id: "fx", name: "Fx", roots: () => [homePath(".fx/sessions")], match: (p) => p.endsWith("/usage-v2.json"), extras: (p) => [join21(dirname7(p), "session.json")], parse: fxHistory, history: false, description: "Local native session metadata \xB7 conversation unavailable in usage snapshots" },
33873
+ { id: "fx", name: "Fx", roots: () => [homePath(".fx/sessions")], match: (p) => p.endsWith("/usage-v2.json"), extras: (p) => [join21(dirname7(p), "session.json")], parse: fxHistory, history: false, description: "Session metadata only" },
33414
33874
  { id: "minimax-code", name: "MiniMax Code", roots: () => [join21(process.env.TOKSCALE_HEADLESS_DIR || tokscalePath("headless"), "mcode")], parse(p, f) {
33415
33875
  const value = f.get(p), { rows: rows2 } = jsonLines(value), ids = new Set(rows2.map((r) => text(r.sessionId)).filter(Boolean));
33416
33876
  if (ids.size !== 1) throw new Error("Headless capture needs one explicit session identity.");
33417
33877
  const messages = rows2.flatMap((r, i) => {
33418
- const m = message(object2(r.message), text(r.message?.id) || `record:${i}`);
33878
+ const m = message(object3(r.message), text(r.message?.id) || `record:${i}`);
33419
33879
  return m ? [m] : [];
33420
33880
  });
33421
- return { nativeID: [...ids][0], messages, partial: true, note: "Previously captured MiniMax stream JSON only; no command is executed. User input and transient streaming records may be absent." };
33881
+ return { nativeID: [...ids][0], messages, partial: true, note: "Captured messages only; prompts may be missing." };
33422
33882
  } },
33423
33883
  { id: "opencodereview", name: "OpenCodeReview", roots: () => [homePath(".opencodereview/sessions")], parse(p, f) {
33424
33884
  const { rows: rows2 } = jsonLines(f.get(p)), header = rows2.find((r) => r.type === "session_start");
33425
33885
  if (!header) throw new Error("Unsupported review session.");
33426
- return { nativeID: text(header.session_id || header.sessionId) || fileID(p), messages: rows2.filter((r) => r.type === "llm_response").map((r, i) => recordEvent(r, text(r.id) || `response:${i}`, "Review response", r.timestamp, r.content ?? r.response)), partial: true, session: { directory: text(header.cwd), created: time(header.timestamp) }, note: "OpenCodeReview saved response events. Usage-only records do not establish conversation text or user prompts." };
33886
+ return { nativeID: text(header.session_id || header.sessionId) || fileID(p), messages: rows2.filter((r) => r.type === "llm_response").map((r, i) => recordEvent(r, text(r.id) || `response:${i}`, "Review response", r.timestamp, r.content ?? r.response)), partial: true, session: { directory: text(header.cwd), created: time(header.timestamp) }, note: "Recorded review responses only." };
33427
33887
  } }
33428
33888
  ];
33429
33889
  var fileHarnessAdapters = definitions.map((source) => localFileAdapter({
33430
33890
  ...source,
33431
33891
  roots: harnessRoots(source.id, source.roots),
33432
33892
  match: source.match || jsonl,
33433
- description: source.description || "Local transcript snapshots \xB7 bounded, read-only import",
33893
+ description: source.description || "Local session transcripts",
33434
33894
  capabilities: { history: source.history !== false, forks: false, children: false, files: false },
33435
33895
  parse: source.parse || ((p, f) => envelopeHistory(p, f.get(p)))
33436
33896
  }));
@@ -33447,6 +33907,29 @@ function hermesContent(value) {
33447
33907
  }
33448
33908
  }
33449
33909
  var millisOrSeconds = (v3) => typeof v3 === "number" && v3 > 0 && v3 < 1e10 ? seconds(v3) : time(v3);
33910
+ var usageColumns = ["input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens", "reasoning_tokens", "actual_cost_usd", "estimated_cost_usd"];
33911
+ function hermesUsage(row) {
33912
+ const actual = recordedCost(row.actual_cost_usd);
33913
+ return recordedUsage({
33914
+ input: row.input_tokens,
33915
+ output: row.output_tokens,
33916
+ cacheRead: row.cache_read_tokens,
33917
+ cacheWrite: row.cache_write_tokens,
33918
+ reasoning: row.reasoning_tokens,
33919
+ total: sumTokens([row.input_tokens, row.output_tokens, row.cache_read_tokens, row.cache_write_tokens]),
33920
+ inputIncludesCache: false,
33921
+ outputIncludesReasoning: true,
33922
+ cost: actual ?? recordedCost(row.estimated_cost_usd),
33923
+ costEstimated: actual === null && recordedCost(row.estimated_cost_usd) !== null
33924
+ });
33925
+ }
33926
+ function usageJSON(value) {
33927
+ try {
33928
+ return object3(optionalJSON(value));
33929
+ } catch {
33930
+ return {};
33931
+ }
33932
+ }
33450
33933
  function dbPaths(id2, defaults, match2) {
33451
33934
  return async () => {
33452
33935
  const override = sourcePath(id2) || process.env[`SESSIONGRAPH_${id2.replace(/-/g, "_").toUpperCase()}_HISTORY_DIR`];
@@ -33469,14 +33952,23 @@ var hermes = {
33469
33952
  paths: async () => (await historyFiles(harnessRoots("hermes", () => [envHome("HERMES_HOME", ".hermes")])(), (p) => p === "state.db" || /^profiles\/[^/]+\/state\.db$/.test(p))).files,
33470
33953
  table: "sessions",
33471
33954
  key: "id",
33472
- fields: ["id", "title", "cwd", "model", "billing_provider", "started_at", "last_activity_at", "parent_session_id", "source", "model_config", "archived"],
33955
+ fields: ["id", "title", "cwd", "model", "billing_provider", "started_at", "last_activity_at", "parent_session_id", "source", "model_config", "archived", ...usageColumns],
33473
33956
  parse(db2, r) {
33474
33957
  const messages = rows(db2, "messages", ["id", "message_uid", "role", "content", "timestamp", "tool_call_id", "tool_calls", "tool_name", "_compressed_summary"], ["session_id", r.id], "id").map((m) => {
33475
33958
  if (m._compressed_summary) return recordEvent(m, text(m.message_uid) || nativeText(m.id), "Context summary", seconds(m.timestamp), m.content);
33476
33959
  return conversationMessage({ role: m.role, content: hermesContent(m.content), timestamp: seconds(m.timestamp), tool_call_id: m.tool_call_id, toolCalls: optionalJSON(m.tool_calls), toolName: m.tool_name }, text(m.message_uid) || nativeText(m.id));
33477
33960
  });
33478
- const h3 = sessionHistory({ ...r, created_at: seconds(r.started_at), updated_at: seconds(r.last_activity_at), provider: r.billing_provider }, messages, "Hermes saved message rows, including retained summaries. Compression/reset parent links are not subagent ancestry. Session usage aggregates are not used as message times.");
33961
+ const h3 = sessionHistory({ ...r, created_at: seconds(r.started_at), updated_at: seconds(r.last_activity_at), provider: r.billing_provider }, messages);
33962
+ const perModel = hasTable(db2, "session_model_usage") ? rows(db2, "session_model_usage", usageColumns, ["session_id", r.id]).map(hermesUsage).filter((value) => value !== void 0) : [];
33963
+ const aggregate = hermesUsage(r), modelTotals = sumUsage(perModel);
33964
+ const usage = modelTotals?.total != null ? modelTotals : aggregate ?? modelTotals;
33965
+ if (usage && usage.cost === null && aggregate?.cost != null) {
33966
+ usage.cost = aggregate.cost;
33967
+ usage.costEstimated = aggregate.costEstimated;
33968
+ }
33969
+ h3.session.usage = sessionUsage(usage);
33479
33970
  if (r.source === "subagent") h3.parent = text(r.parent_session_id) || void 0;
33971
+ if (r.source === "cron" || r.source === "subagent") h3.session.origin = "automated";
33480
33972
  h3.fork = text(optionalJSON(r.model_config)._branched_from) || void 0;
33481
33973
  h3.session.archived = r.archived === 1;
33482
33974
  return h3;
@@ -33488,14 +33980,41 @@ var goose = {
33488
33980
  paths: dbPaths("goose", () => process.env.GOOSE_PATH_ROOT && isAbsolute5(process.env.GOOSE_PATH_ROOT) ? [join22(process.env.GOOSE_PATH_ROOT, "data/sessions/sessions.db")] : [dataPath("goose/sessions/sessions.db"), dataPath("Block/goose/sessions/sessions.db"), appPath("goose/sessions/sessions.db"), appPath("Block/goose/sessions/sessions.db"), appPath("Block/goose/data/sessions/sessions.db")], (p) => p.endsWith("sessions.db")),
33489
33981
  table: "sessions",
33490
33982
  key: "id",
33491
- fields: ["id", "name", "description", "working_dir", "created_at", "updated_at", "model_config_json", "provider_name", "session_type", "parent_session_id", "archived_at"],
33983
+ fields: [
33984
+ "id",
33985
+ "name",
33986
+ "description",
33987
+ "working_dir",
33988
+ "created_at",
33989
+ "updated_at",
33990
+ "model_config_json",
33991
+ "provider_name",
33992
+ "session_type",
33993
+ "parent_session_id",
33994
+ "archived_at",
33995
+ "total_tokens",
33996
+ "input_tokens",
33997
+ "output_tokens",
33998
+ "accumulated_total_tokens",
33999
+ "accumulated_input_tokens",
34000
+ "accumulated_output_tokens"
34001
+ ],
33492
34002
  parse(db2, r) {
33493
34003
  const messages = rows(db2, "messages", ["id", "message_id", "role", "content_json", "created_timestamp"], ["session_id", r.id], "id").map((m) => {
33494
34004
  const content = sqliteJSON(m.content_json);
33495
34005
  return conversationMessage({ role: m.role, content, timestamp: millisOrSeconds(m.created_timestamp) }, text(m.message_id) || nativeText(m.id));
33496
34006
  });
33497
- const h3 = sessionHistory({ ...r, name: r.name || r.description, model: optionalJSON(r.model_config_json).model_name }, messages, "Goose saved conversation rows. Tool/content variants not represented as text are marked partial.");
34007
+ const h3 = sessionHistory({ ...r, name: r.name || r.description, model: optionalJSON(r.model_config_json).model_name }, messages);
34008
+ const input = r.accumulated_input_tokens ?? r.input_tokens, output2 = r.accumulated_output_tokens ?? r.output_tokens;
34009
+ h3.session.usage = sessionUsage(recordedUsage({
34010
+ input,
34011
+ output: output2,
34012
+ total: r.accumulated_total_tokens ?? r.total_tokens ?? sumTokens([input, output2]),
34013
+ inputIncludesCache: true,
34014
+ outputIncludesReasoning: true
34015
+ }), r.accumulated_total_tokens == null);
33498
34016
  if (r.session_type === "sub_agent") h3.parent = text(r.parent_session_id) || void 0;
34017
+ if (r.session_type === "sub_agent") h3.session.origin = "automated";
33499
34018
  h3.session.archived = Boolean(r.archived_at);
33500
34019
  return h3;
33501
34020
  }
@@ -33510,12 +34029,16 @@ var openclaw = {
33510
34029
  parse(db2, r) {
33511
34030
  const events = rows(db2, "transcript_events", ["seq", "event_json", "event_zstd"], ["session_id", r.session_id], "seq");
33512
34031
  const messages = events.flatMap((e10) => {
33513
- const raw = object2(sqliteJSON(e10.event_json ?? e10.event_zstd));
33514
- if (raw.type !== "message") return [];
33515
- const m = message(object2(raw.message), text(raw.id) || `event:${e10.seq}`, raw.timestamp ?? raw.message?.timestamp);
34032
+ const raw = object3(sqliteJSON(e10.event_json ?? e10.event_zstd));
34033
+ if (raw.type !== "message") {
34034
+ const event = recordEvent(raw, text(raw.id) || `event:${e10.seq}`, text(raw.type) || "OpenClaw event", raw.timestamp, raw.summary ?? raw);
34035
+ for (const item of event.events || []) item.parentID = text(raw.parentId) || void 0;
34036
+ return [event];
34037
+ }
34038
+ const m = message(object3(raw.message), text(raw.id) || `event:${e10.seq}`, raw.timestamp ?? raw.message?.timestamp);
33516
34039
  return m ? [m] : [];
33517
34040
  });
33518
- return sessionHistory({ ...r, id: r.session_id, provider: r.model_provider }, messages, "OpenClaw authoritative transcript events, including zstd payloads. Database sessions take precedence over migrated JSONL copies. Session rollover and event-parent links are not session ancestry.");
34041
+ return sessionHistory({ ...r, id: r.session_id, provider: r.model_provider }, messages);
33519
34042
  }
33520
34043
  };
33521
34044
  function forkStore(id2, name, defaultPath, desktop) {
@@ -33529,7 +34052,7 @@ function forkStore(id2, name, defaultPath, desktop) {
33529
34052
  parse(db2, r) {
33530
34053
  if (desktop !== void 0 && text(r.version).startsWith("desktop-") !== desktop) return;
33531
34054
  const messages = rows(db2, "message", ["id", "data", "time_created"], ["session_id", r.id], "time_created").map((m) => {
33532
- const body2 = object2(sqliteJSON(m.data));
34055
+ const body2 = object3(sqliteJSON(m.data));
33533
34056
  let content = body2.parts ?? body2.content;
33534
34057
  if (hasTable(db2, "part")) content = rows(db2, "part", ["id", "data"], ["message_id", m.id], "id").map((p) => sqliteJSON(p.data));
33535
34058
  if (Array.isArray(content)) content = content.flatMap((p) => {
@@ -33541,7 +34064,7 @@ function forkStore(id2, name, defaultPath, desktop) {
33541
34064
  });
33542
34065
  return conversationMessage({ ...body2, content, timestamp: body2.time?.created ?? m.time_created }, text(m.id));
33543
34066
  });
33544
- return sessionHistory({ ...r, created_at: r.time_created, updated_at: r.time_updated }, messages, `${name} native session/message/part tables. Only this harness's database is read; ancestry semantics not explicitly exposed by this format remain unknown.`);
34067
+ return sessionHistory({ ...r, created_at: r.time_created, updated_at: r.time_updated }, messages);
33545
34068
  }
33546
34069
  };
33547
34070
  }
@@ -33554,17 +34077,22 @@ var zed = {
33554
34077
  fields: ["id", "summary", "created_at", "updated_at", "data_type", "data", "folder_paths"],
33555
34078
  parse(db2, r) {
33556
34079
  if (!["json", "zstd"].includes(r.data_type)) throw new Error("Unsupported Zed encoding.");
33557
- const body2 = object2(sqliteJSON(r.data));
34080
+ const body2 = object3(sqliteJSON(r.data));
33558
34081
  if (body2.imported === true) return;
33559
34082
  if (!Array.isArray(body2.messages)) throw new Error("Unsupported Zed thread.");
33560
34083
  const messages = body2.messages.map((raw, i) => {
33561
- const user = object2(raw.User), agent = object2(raw.Agent), b = raw.User ? user : agent;
34084
+ const user = object3(raw.User), agent = object3(raw.Agent), b = raw.User ? user : agent;
33562
34085
  if (!raw.User && !raw.Agent) return recordEvent(raw, `message:${i}`, "Context checkpoint", 0, raw.Compaction?.Summary);
33563
34086
  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" });
33564
34087
  return conversationMessage({ role: raw.User ? "user" : "assistant", content }, text(b.id) || `message:${i}`);
33565
34088
  });
33566
34089
  const folders = optionalJSON(r.folder_paths);
33567
- return sessionHistory({ ...r, title: r.summary || body2.title, directory: Array.isArray(folders) && folders.length === 1 ? folders[0] : "", model: body2.model?.model, provider: body2.model?.provider }, messages, "Zed native thread messages, JSON or zstd. Native message times are absent in this format; no timing is invented. Imported/shared copies and external ACP histories are excluded from this native-thread store.");
34090
+ const h3 = sessionHistory({ ...r, title: r.summary || body2.title, directory: Array.isArray(folders) && folders.length === 1 ? folders[0] : "", model: body2.model?.model, provider: body2.model?.provider }, messages, "Message times unavailable.");
34091
+ const requests = body2.request_token_usage;
34092
+ const values = Array.isArray(requests) ? requests : Object.values(object3(requests));
34093
+ const recorded = values.slice(0, 5e4).map((value) => anthropicUsage(value)).filter((value) => value !== void 0);
34094
+ h3.session.usage = sessionUsage(anthropicUsage(body2.cumulative_token_usage) ?? sumUsage(recorded), recorded.length < values.length && !body2.cumulative_token_usage);
34095
+ return h3;
33568
34096
  }
33569
34097
  };
33570
34098
  var devin = {
@@ -33576,10 +34104,10 @@ var devin = {
33576
34104
  fields: ["id", "working_directory", "model", "title", "created_at", "last_activity_at"],
33577
34105
  parse(db2, r) {
33578
34106
  const messages = rows(db2, "message_nodes", ["node_id", "chat_message", "created_at"], ["session_id", r.id], "row_id").flatMap((m) => {
33579
- const raw = object2(sqliteJSON(m.chat_message)), result = message(raw, nativeText(m.node_id), millisOrSeconds(m.created_at));
34107
+ const raw = object3(sqliteJSON(m.chat_message)), result = message(raw, nativeText(m.node_id), millisOrSeconds(m.created_at));
33580
34108
  return result ? [result] : [recordEvent(raw, nativeText(m.node_id), "Devin message node", millisOrSeconds(m.created_at))];
33581
34109
  });
33582
- return sessionHistory({ ...r, created_at: millisOrSeconds(r.created_at), updated_at: millisOrSeconds(r.last_activity_at) }, messages, "Devin saved message nodes. All retained in-session branches are included; node-parent edges are not session ancestry.");
34110
+ return sessionHistory({ ...r, created_at: millisOrSeconds(r.created_at), updated_at: millisOrSeconds(r.last_activity_at) }, messages);
33583
34111
  }
33584
34112
  };
33585
34113
  var crushDirectories = /* @__PURE__ */ new Map();
@@ -33617,7 +34145,7 @@ var crush = {
33617
34145
  if (m.is_summary_message) return recordEvent(m, text(m.id), "Context summary", millisOrSeconds(m.created_at), content);
33618
34146
  return conversationMessage({ role: m.role, content, timestamp: millisOrSeconds(m.created_at) }, text(m.id));
33619
34147
  });
33620
- const h3 = sessionHistory({ ...r, directory: crushDirectories.get(path) || "", created_at: millisOrSeconds(r.created_at), updated_at: millisOrSeconds(r.updated_at) }, messages, "Crush per-project saved message parts. Session cost is retained when recorded; unreliable token counters remain unknown.");
34148
+ const h3 = sessionHistory({ ...r, directory: crushDirectories.get(path) || "", created_at: millisOrSeconds(r.created_at), updated_at: millisOrSeconds(r.updated_at) }, messages);
33621
34149
  h3.session.cost = typeof r.cost === "number" && r.cost >= 0 ? r.cost : null;
33622
34150
  return h3;
33623
34151
  }
@@ -33639,13 +34167,13 @@ var octofriend = {
33639
34167
  const row = rows(db2, "llm_irs", ["json"], ["id", item.llm_ir_id], void 0, 1)[0];
33640
34168
  bytes2 += text(row?.json).length;
33641
34169
  if (bytes2 > 32e6) throw new Error("Octofriend session exceeds the snapshot limit.");
33642
- const payload = object2(sqliteJSON(row?.json));
34170
+ const payload = object3(sqliteJSON(row?.json));
33643
34171
  if (payload.version !== "octo-llm-ir/v1") throw new Error("Unsupported Octofriend IR version.");
33644
- const ir = object2(payload.ir), content = Array.isArray(ir.content) ? ir.content.map((p) => p.type === "text" ? { type: "text", text: p.content } : p) : ir.content;
34172
+ const ir = object3(payload.ir), content = Array.isArray(ir.content) ? ir.content.map((p) => p.type === "text" ? { type: "text", text: p.content } : p) : ir.content;
33645
34173
  const m = message({ ...ir, content, role: ir.role === "tool-output" ? "tool" : ir.role }, nativeText(node.id), node.created_at);
33646
34174
  messages.push(m || recordEvent(ir, nativeText(node.id), text(ir.role), node.created_at));
33647
34175
  }
33648
- const h3 = sessionHistory({ ...r, created_at: nodes[0]?.created_at }, messages, "Octofriend native history trees and versioned IR. Retained branches are preserved; nested subagent trajectories and unsupported IR variants are partial. Provider attribution remains with the harness.");
34176
+ const h3 = sessionHistory({ ...r, created_at: nodes[0]?.created_at }, messages, "Some subagent history may be missing.");
33649
34177
  return h3;
33650
34178
  }
33651
34179
  };
@@ -33657,11 +34185,25 @@ var unsloth = {
33657
34185
  key: "id",
33658
34186
  fields: ["id", "title", "model_id", "created_at", "updated_at", "archived", "forked_from_thread_id"],
33659
34187
  parse(db2, r) {
33660
- const messages = rows(db2, "chat_messages", ["id", "role", "content_json", "created_at"], ["thread_id", r.id], "created_at").flatMap((row) => {
34188
+ const messages = rows(db2, "chat_messages", ["id", "role", "content_json", "created_at", "metadata_json"], ["thread_id", r.id], "created_at").flatMap((row) => {
34189
+ const metadata2 = usageJSON(row.metadata_json), usage = object3(metadata2.contextUsage);
33661
34190
  const m = message({ role: row.role, content: sqliteJSON(row.content_json) }, text(row.id), seconds(row.created_at));
34191
+ if (m?.role === "assistant") {
34192
+ m.usage = recordedUsage({
34193
+ input: usage.promptTokens,
34194
+ output: usage.completionTokens,
34195
+ total: usage.totalTokens ?? sumTokens([usage.promptTokens, usage.completionTokens]),
34196
+ cacheRead: usage.cachedTokens,
34197
+ cacheWrite: usage.cacheWriteTokens,
34198
+ reasoning: usage.reasoningTokens,
34199
+ inputIncludesCache: true,
34200
+ outputIncludesReasoning: true
34201
+ }, "message", row.id);
34202
+ m.metadata = messageMetadata({ model: metadata2.responseDetails?.responseModelId || usage.modelId, provider: metadata2.responseDetails?.providerType });
34203
+ }
33662
34204
  return m ? [m] : [];
33663
34205
  });
33664
- const h3 = sessionHistory({ ...r, model: r.model_id, created_at: seconds(r.created_at), updated_at: seconds(r.updated_at) }, messages, "Unsloth Studio native chat threads and message content. Content-free API usage, training runs, attachments, and unsupported tool blocks are excluded.");
34206
+ const h3 = sessionHistory({ ...r, model: r.model_id, created_at: seconds(r.created_at), updated_at: seconds(r.updated_at) }, messages);
33665
34207
  h3.fork = text(r.forked_from_thread_id) || void 0;
33666
34208
  h3.session.archived = r.archived === 1;
33667
34209
  return h3;
@@ -33675,17 +34217,17 @@ var kiro = {
33675
34217
  key: "conversation_id",
33676
34218
  fields: ["key", "conversation_id", "value"],
33677
34219
  parse(db2, r) {
33678
- const body2 = object2(sqliteJSON(r.value));
34220
+ const body2 = object3(sqliteJSON(r.value));
33679
34221
  if (!Array.isArray(body2.history)) throw new Error("Unsupported Kiro conversation.");
33680
34222
  const messages = body2.history.flatMap((turn, i) => {
33681
- const result = [], input = object2(turn.user?.content), output2 = object2(turn.assistant?.Response || turn.assistant?.ToolUse);
34223
+ const result = [], input = object3(turn.user?.content), output2 = object3(turn.assistant?.Response || turn.assistant?.ToolUse);
33682
34224
  if (typeof input.Prompt?.prompt === "string") result.push(conversationMessage({ role: "user", content: input.Prompt.prompt }, `turn:${i}:user`));
33683
34225
  if (input.ToolUseResults) result.push(conversationMessage({ role: "tool", content: input.ToolUseResults }, `turn:${i}:tool`));
33684
34226
  if (typeof output2.content === "string") result.push(conversationMessage({ role: "assistant", content: output2.content, timestamp: turn.request_metadata?.stream_end_timestamp_ms }, `turn:${i}:assistant`));
33685
34227
  return result;
33686
34228
  });
33687
34229
  const created = body2.history.map((t) => time(t.request_metadata?.request_start_timestamp_ms)).find(Boolean);
33688
- return { nativeID: text(r.conversation_id), messages, partial: true, session: { directory: text(r.key), created, model: text(body2.model_info?.model_id) || "Unknown model" }, note: "Kiro retained SQLite conversation turns. Request-start metadata places the session; untimed user prompts remain untimed. Tool-use variants and compacted context are partial." };
34230
+ return { nativeID: text(r.conversation_id), messages, partial: true, session: { directory: text(r.key), created, model: text(body2.model_info?.model_id) || "Unknown model" }, note: "Earlier messages and some tool details may be missing." };
33689
34231
  }
33690
34232
  };
33691
34233
  var databaseHarnessAdapters = [
@@ -33708,7 +34250,7 @@ import { basename as basename10 } from "node:path";
33708
34250
  import { fileURLToPath as fileURLToPath4 } from "node:url";
33709
34251
  function protoFields(value) {
33710
34252
  if (value.length > 2e6) throw new Error("Trajectory metadata exceeds 2 MB.");
33711
- const fields2 = /* @__PURE__ */ new Map();
34253
+ const fields3 = /* @__PURE__ */ new Map();
33712
34254
  let at2 = 0, count = 0;
33713
34255
  const varint = () => {
33714
34256
  let n = 0n;
@@ -33723,35 +34265,35 @@ function protoFields(value) {
33723
34265
  if (++count > 1e4) throw new Error("Too many protobuf fields.");
33724
34266
  const key = Number(varint()), field = key >>> 3, wire = key & 7;
33725
34267
  if (!field) throw new Error("Invalid protobuf field.");
33726
- if (wire === 0) fields2.set(field, varint());
34268
+ if (wire === 0) fields3.set(field, varint());
33727
34269
  else if (wire === 2) {
33728
34270
  const length = Number(varint());
33729
34271
  if (!Number.isSafeInteger(length) || length > value.length - at2) throw new Error("Invalid protobuf length.");
33730
- fields2.set(field, value.subarray(at2, at2 + length));
34272
+ fields3.set(field, value.subarray(at2, at2 + length));
33731
34273
  at2 += length;
33732
34274
  } else if (wire === 1 || wire === 5) {
33733
34275
  at2 += wire === 1 ? 8 : 4;
33734
34276
  if (at2 > value.length) throw new Error("Truncated protobuf field.");
33735
34277
  } else throw new Error("Unsupported protobuf wire type.");
33736
34278
  }
33737
- return fields2;
34279
+ return fields3;
33738
34280
  }
33739
34281
  var nested = (v3) => v3 instanceof Uint8Array ? protoFields(v3) : /* @__PURE__ */ new Map();
33740
34282
  var antigravityDatabaseAdapters = ["antigravity-cli", "antigravity-extension"].map((id2) => sqliteHistoryAdapter({
33741
34283
  id: id2,
33742
34284
  name: id2 === "antigravity-cli" ? "Antigravity CLI" : "Antigravity IDE Extension",
33743
34285
  history: false,
33744
- description: "Native session metadata only \xB7 opaque protobuf conversations",
34286
+ description: "Session metadata only",
33745
34287
  paths: async () => (await historyFiles(harnessRoots(id2, () => [envHome("GEMINI_CLI_HOME", ".gemini", id2 === "antigravity-cli" ? "antigravity-cli/conversations" : "antigravity/conversations")])(), (p) => p.endsWith(".db"))).files,
33746
34288
  table: "trajectory_metadata_blob",
33747
34289
  key: "id",
33748
34290
  fields: ["id", "data"],
33749
34291
  parse(db2, row, path) {
33750
34292
  if (!(row.data instanceof Uint8Array)) throw new Error("Unsupported trajectory metadata.");
33751
- const fields2 = protoFields(row.data), timestamp = nested(fields2.get(2));
34293
+ const fields3 = protoFields(row.data), timestamp = nested(fields3.get(2));
33752
34294
  const sec = timestamp.get(1), nano = timestamp.get(2);
33753
34295
  const created = typeof sec === "bigint" && sec > 0n && sec < 8640000000000n ? time(Number(sec) * 1e3 + (typeof nano === "bigint" && nano < 1000000000n ? Number(nano) / 1e6 : 0)) : 0;
33754
- const uri = nested(fields2.get(1)).get(1);
34296
+ const uri = nested(fields3.get(1)).get(1);
33755
34297
  let directory3 = "";
33756
34298
  if (uri instanceof Uint8Array) {
33757
34299
  try {
@@ -33760,13 +34302,13 @@ var antigravityDatabaseAdapters = ["antigravity-cli", "antigravity-extension"].m
33760
34302
  }
33761
34303
  }
33762
34304
  if (!created) throw new Error("Trajectory creation time is unavailable.");
33763
- return { nativeID: basename10(path, ".db"), messages: [], partial: true, session: { created, directory: directory3 }, note: "Native Antigravity trajectory identity and creation metadata only. Protobuf conversation/step bodies are opaque; no message text, generation-time guesses, or usage-derived turns are imported." };
34305
+ return { nativeID: basename10(path, ".db"), messages: [], partial: true, session: { created, directory: directory3 }, note: "Session metadata only." };
33764
34306
  }
33765
34307
  }));
33766
34308
  var antigravityCacheAdapter = localFileAdapter({
33767
34309
  id: "antigravity",
33768
34310
  name: "Antigravity",
33769
- description: "Previously synced session metadata only \xB7 cache contains no conversations",
34311
+ description: "Cached session metadata only",
33770
34312
  capabilities: { history: false, forks: false, children: false, files: false },
33771
34313
  roots: harnessRoots("antigravity", () => [tokscalePath("antigravity-cache/sessions")]),
33772
34314
  match: (p) => p.endsWith(".jsonl"),
@@ -33776,7 +34318,7 @@ var antigravityCacheAdapter = localFileAdapter({
33776
34318
  if (ids.size !== 1) throw new Error("Unsupported Antigravity cache identity.");
33777
34319
  const created = rows2.map((r) => time(r.timestamp)).filter(Boolean).sort((a, b) => a - b)[0];
33778
34320
  if (!created) throw new Error("Antigravity cache has no recorded date.");
33779
- return { nativeID: [...ids][0], messages: [], partial: true, session: { created, model: text(rows2.find((r) => r.modelId)?.modelId) || "Unknown model" }, note: "Previously synced Antigravity session identity; placement uses earliest recorded usage date. This cache has no conversation bodies. SessionGraph never runs sync or contacts the language server." };
34321
+ return { nativeID: [...ids][0], messages: [], partial: true, session: { created, model: text(rows2.find((r) => r.modelId)?.modelId) || "Unknown model" }, note: "Session metadata only. Date based on first recorded usage." };
33780
34322
  }
33781
34323
  });
33782
34324
 
@@ -33796,7 +34338,7 @@ import { randomUUID as randomUUID2 } from "node:crypto";
33796
34338
  var MAX_CHARACTERS = 24e6;
33797
34339
  var SESSION_CHARACTERS = 48e3;
33798
34340
  var CACHE_VERSION = 2;
33799
- var contentVersion = (session) => JSON.stringify([CACHE_VERSION, session.revision, session.updated, session.created, session.projectID, session.directory]);
34341
+ var contentVersion = (session) => JSON.stringify([CACHE_VERSION, session.importVersion, session.revision, session.updated, session.created, session.projectID, session.directory]);
33800
34342
  function validRecord(value, session) {
33801
34343
  if (!value || !session || value.id !== session.id || value.version !== contentVersion(session)) return false;
33802
34344
  if (!Number.isInteger(value.pages) || value.pages < 1 || value.pages > 8) return false;
@@ -33858,7 +34400,7 @@ var LibraryError = class extends Error {
33858
34400
  function invalid(message2) {
33859
34401
  throw new LibraryError("INVALID_ARGUMENT", message2, 2);
33860
34402
  }
33861
- var fingerprint = (value) => createHash4("sha256").update(JSON.stringify(value)).digest("hex");
34403
+ var fingerprint2 = (value) => createHash4("sha256").update(JSON.stringify(value)).digest("hex");
33862
34404
  function pageLimit(value = 50) {
33863
34405
  if (!Number.isSafeInteger(value) || value < 1 || value > 200) invalid("Limit must be an integer from 1 to 200.");
33864
34406
  return value;
@@ -33891,7 +34433,7 @@ var pendingCommits = () => ({ version: 0, state: "pending", count: null, note: "
33891
34433
  function writeCommits(db2, session) {
33892
34434
  db2.prepare("DELETE FROM session_commits WHERE session_id=?").run(session.id);
33893
34435
  const base = { version: COMMIT_EXTRACTOR_VERSION, indexedAt: Date.now() };
33894
- if (!supported.has(session.source || "")) return { ...base, state: "unavailable", count: null, note: "Commit attribution is not validated for this source format." };
34436
+ if (!supported.has(session.source || "")) return { ...base, state: "unavailable", count: null, note: "Commit history unavailable for this source." };
33895
34437
  const calls = /* @__PURE__ */ new Map();
33896
34438
  const results = /* @__PURE__ */ new Map();
33897
34439
  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);
@@ -33900,7 +34442,7 @@ function writeCommits(db2, session) {
33900
34442
  const item = JSON.parse(String(row.data));
33901
34443
  tools++;
33902
34444
  if (item.kind === "tool_result" && item.callID) {
33903
- const signature = fingerprint([item.output, item.exitCode, item.status, item.gitCommit]);
34445
+ const signature = fingerprint2([item.output, item.exitCode, item.status, item.gitCommit]);
33904
34446
  results.set(item.callID, results.has(item.callID) && results.get(item.callID) !== signature ? null : signature);
33905
34447
  }
33906
34448
  if (item.kind !== "tool_call" || !item.callID) continue;
@@ -33937,7 +34479,7 @@ function writeCommits(db2, session) {
33937
34479
  ...base,
33938
34480
  state: !tools ? "unavailable" : partial ? "partial" : "indexed",
33939
34481
  count: !tools ? null : count,
33940
- note: !tools ? "No usable tool executions recorded; commit history is unknown." : `${partial ? "Some execution evidence is missing, ambiguous, inherited, or unsupported. " : ""}Confirmed recorded operations only; absence is not proof that no commits occurred. Paths are execution directories; abbreviated SHAs remain unresolved. Linked provider histories retain their own attribution.`
34482
+ note: !tools ? "No tool executions recorded." : partial ? "Some commits may be missing." : count ? "Confirmed commits from saved tool results." : "No recorded commits found."
33941
34483
  };
33942
34484
  }
33943
34485
  function commit(row) {
@@ -33947,7 +34489,7 @@ function readCommits(db2, session, options = {}) {
33947
34489
  let coverage2 = session.commits || pendingCommits();
33948
34490
  if (session.coverage?.note?.startsWith("Latest import failed:")) coverage2 = { ...coverage2, state: coverage2.count === null ? coverage2.state : "partial", note: `${session.coverage.note} ${coverage2.note}` };
33949
34491
  const revision2 = String(db2.prepare("SELECT revision FROM timeline_coverage WHERE session_id=?").get(session.id)?.revision || "pending");
33950
- const key = fingerprint(["commits", session.id, revision2, coverage2]), offset = pageOffset(options.cursor, key), limit = pageLimit(options.limit);
34492
+ const key = fingerprint2(["commits", session.id, revision2, coverage2]), offset = pageOffset(options.cursor, key), limit = pageLimit(options.limit);
33951
34493
  const total = Number(db2.prepare("SELECT count(*) AS n FROM session_commits WHERE session_id=?").get(session.id).n);
33952
34494
  const items = db2.prepare("SELECT * FROM session_commits WHERE session_id=? ORDER BY occurred_at IS NULL,occurred_at,repository_path,sha,operation LIMIT ? OFFSET ?").all(session.id, limit, offset).map(commit);
33953
34495
  return { sessionID: session.id, revision: revision2, coverage: coverage2, items, total, nextCursor: offset + limit < total ? nextCursor(key, offset + limit) : null };
@@ -33969,7 +34511,19 @@ ${abbreviatedSHA(value.sha) ? "Abbreviated SHA \xB7 " : ""}Open recorded executi
33969
34511
  });
33970
34512
  }
33971
34513
 
34514
+ // server/history-limits.ts
34515
+ var MAX_SESSION_RECORDS = 75e3;
34516
+ var MAX_SESSION_CHARACTERS = 24e6;
34517
+ var MAX_SESSION_PAGES = 3e3;
34518
+ var MAX_TIMELINE_EVENTS = 3e5;
34519
+ var MAX_TIMELINE_BYTES = 48e6;
34520
+ var SESSION_LIMIT_NOTE = "Import limited to 75,000 messages / 24 million text characters / 3,000 pages.";
34521
+ var TIMELINE_LIMIT_NOTE = "Event history limited to 300,000 items / 48 MB per session.";
34522
+
33972
34523
  // server/event-store.ts
34524
+ var MESSAGE_TIME_INDEX = `CREATE INDEX IF NOT EXISTS timeline_messages_time
34525
+ ON timeline_items(session_id,time,ordinal)
34526
+ WHERE kind='message' AND role IN ('user','assistant');`;
33973
34527
  var EVENT_SCHEMA = `CREATE TABLE IF NOT EXISTS timeline_items (
33974
34528
  session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, id TEXT NOT NULL, message_id TEXT NOT NULL,
33975
34529
  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,
@@ -33988,7 +34542,7 @@ function writeEvents(db2, id2, rows2) {
33988
34542
  for (const event of normalizedEvents(message2, id2)) {
33989
34543
  const item = { ...event, ordinal: ordinal++ }, data = JSON.stringify(item);
33990
34544
  bytes2 += Buffer.byteLength(data);
33991
- if (ordinal > 2e5 || bytes2 > 32e6) {
34545
+ if (ordinal > MAX_TIMELINE_EVENTS || bytes2 > MAX_TIMELINE_BYTES) {
33992
34546
  limited = true;
33993
34547
  break;
33994
34548
  }
@@ -33998,7 +34552,7 @@ function writeEvents(db2, id2, rows2) {
33998
34552
  }
33999
34553
  if (limited) break;
34000
34554
  }
34001
- const note = [legacy ? "Some items were reconstructed from an older flattened import; tool inputs/results cannot be paired there. Refresh sources to import structured events." : "", limited ? "Event history limited to 200,000 items / 32 MB per session." : "", partial ? "Some event content is missing, unsupported, or shortened." : ""].filter(Boolean).join(" ");
34555
+ const note = [legacy ? "Some items were reconstructed from an older flattened import; tool inputs/results cannot be paired there. Refresh sources to import structured events." : "", limited ? TIMELINE_LIMIT_NOTE : "", partial ? "Some event content is missing, unsupported, or shortened." : ""].filter(Boolean).join(" ");
34002
34556
  db2.prepare("INSERT OR REPLACE INTO timeline_coverage VALUES (?,?,?,?)").run(id2, Number(partial || legacy || limited), note || null, randomUUID());
34003
34557
  }
34004
34558
  var summaryColumns = "id,kind,role,name,time,ordinal,preview,json_extract(data,'$.timeSource') AS timeSource,json_extract(data,'$.status') AS status,json_extract(data,'$.partial') AS partial";
@@ -34034,7 +34588,7 @@ function readEvents(db2, session, options = {}) {
34034
34588
  try {
34035
34589
  if (options.cursor.length > 512) throw new Error();
34036
34590
  const cursor2 = JSON.parse(Buffer.from(options.cursor, "base64url").toString());
34037
- if (!Number.isSafeInteger(cursor2.offset) || cursor2.offset < 0 || cursor2.offset > 2e5 || cursor2.filter !== filter || typeof cursor2.revision !== "string") throw new Error();
34591
+ if (!Number.isSafeInteger(cursor2.offset) || cursor2.offset < 0 || cursor2.offset > MAX_TIMELINE_EVENTS || cursor2.filter !== filter || typeof cursor2.revision !== "string") throw new Error();
34038
34592
  if (cursor2.revision !== state2.revision) throw new EventReadError("Saved history changed. Reload the event explorer.", 409);
34039
34593
  offset = cursor2.offset;
34040
34594
  } catch (error) {
@@ -34075,12 +34629,12 @@ function readEvents(db2, session, options = {}) {
34075
34629
 
34076
34630
  // packages/core/src/preferences.ts
34077
34631
  var DEFAULT_PREFERENCES = Object.freeze({
34078
- autoImport: true,
34632
+ autoImport: false,
34079
34633
  muted: false,
34080
34634
  clickSounds: true,
34081
34635
  clickVolume: 35,
34082
34636
  motion: "system",
34083
- view: "3d",
34637
+ grouping: "worktree",
34084
34638
  density: "comfortable",
34085
34639
  panelOpacity: 90,
34086
34640
  quality: "balanced",
@@ -34097,7 +34651,7 @@ var DEFAULT_PREFERENCES = Object.freeze({
34097
34651
  messageDots: true,
34098
34652
  playbackSpeed: 1
34099
34653
  });
34100
- var choices = { motion: ["system", "on", "off"], view: ["3d", "2d"], density: ["comfortable", "compact"], quality: ["performance", "balanced", "high"], trails: ["all", "selected", "off"] };
34654
+ var choices = { motion: ["system", "on", "off"], grouping: ["repository", "worktree"], density: ["comfortable", "compact"], quality: ["performance", "balanced", "high"], trails: ["all", "selected", "off"] };
34101
34655
  var ranges = { clickVolume: [0, 100], panelOpacity: [55, 100], bloom: [0, 75], nodeScale: [60, 180], trailOpacity: [0, 100], trailSpeed: [10, 100], playbackSpeed: [0.25, 3] };
34102
34656
  function normalizePreferences(value) {
34103
34657
  const result = { ...DEFAULT_PREFERENCES };
@@ -34120,7 +34674,7 @@ var DEFAULT_VIEW_STATE = Object.freeze({
34120
34674
  sourceID: "",
34121
34675
  projectID: "",
34122
34676
  directory: "",
34123
- days: 0,
34677
+ days: "ytd",
34124
34678
  fromDate: "",
34125
34679
  toDate: "",
34126
34680
  includeChildren: true,
@@ -34132,7 +34686,7 @@ function normalizeViewState(value) {
34132
34686
  if (!value || typeof value !== "object" || Array.isArray(value)) return result;
34133
34687
  const input = value;
34134
34688
  for (const key of ["sourceID", "projectID", "directory"]) if (typeof input[key] === "string" && input[key].length <= 4096) result[key] = input[key];
34135
- if ([0, 7, 30, 90].includes(input.days)) result.days = input.days;
34689
+ if (input.days === "ytd" || [0, 7, 30, 90].includes(input.days)) result.days = input.days;
34136
34690
  for (const key of ["includeChildren", "includeArchived"]) if (typeof input[key] === "boolean") result[key] = input[key];
34137
34691
  for (const key of ["fromDate", "toDate"]) if (validDate(input[key])) result[key] = input[key];
34138
34692
  if (result.fromDate && result.toDate && result.fromDate > result.toDate) {
@@ -34151,7 +34705,7 @@ var SessionGraphStore = class {
34151
34705
  if (path !== ":memory:") chmodSync3(path, 384);
34152
34706
  this.db.exec("PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;");
34153
34707
  const version = Number(this.db.prepare("PRAGMA user_version").get().user_version);
34154
- if (version > 6) throw new Error("This SessionGraph database requires a newer version of the app.");
34708
+ if (version > 8) throw new Error("This SessionGraph database requires a newer version of the app.");
34155
34709
  this.db.exec(`
34156
34710
  CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT NOT NULL);
34157
34711
  CREATE TABLE IF NOT EXISTS sources (id TEXT PRIMARY KEY, last_import INTEGER, error TEXT);
@@ -34228,6 +34782,29 @@ var SessionGraphStore = class {
34228
34782
  throw error;
34229
34783
  }
34230
34784
  }
34785
+ if (version < 7) {
34786
+ this.db.exec("BEGIN IMMEDIATE");
34787
+ try {
34788
+ this.db.exec(`${MESSAGE_TIME_INDEX} PRAGMA user_version=7; COMMIT;`);
34789
+ } catch (error) {
34790
+ this.db.exec("ROLLBACK");
34791
+ throw error;
34792
+ }
34793
+ }
34794
+ if (version < 8) {
34795
+ this.db.exec("BEGIN IMMEDIATE");
34796
+ try {
34797
+ this.db.exec(`${MESSAGE_TIME_INDEX} CREATE TABLE IF NOT EXISTS session_pull_requests (
34798
+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
34799
+ host TEXT NOT NULL, repository TEXT NOT NULL, number INTEGER NOT NULL CHECK(number > 0),
34800
+ url TEXT NOT NULL, source TEXT NOT NULL CHECK(source IN ('manual', 'created', 'agent', 'stack')),
34801
+ PRIMARY KEY(session_id, host, repository, number)
34802
+ ) STRICT; PRAGMA user_version=8; COMMIT;`);
34803
+ } catch (error) {
34804
+ this.db.exec("ROLLBACK");
34805
+ throw error;
34806
+ }
34807
+ }
34231
34808
  if (!this.setting("libraryID")) this.setting("libraryID", randomUUID2());
34232
34809
  }
34233
34810
  path;
@@ -34242,7 +34819,7 @@ var SessionGraphStore = class {
34242
34819
  return this.setting("selected") || [];
34243
34820
  }
34244
34821
  autoImportEnabled() {
34245
- return this.setting("autoImport") !== false;
34822
+ return this.setting("autoImport") === true;
34246
34823
  }
34247
34824
  acquireImport() {
34248
34825
  this.db.exec("BEGIN IMMEDIATE");
@@ -34284,11 +34861,20 @@ var SessionGraphStore = class {
34284
34861
  commitsCurrent(id2) {
34285
34862
  return this.getSession(id2)?.commits?.version === COMMIT_EXTRACTOR_VERSION;
34286
34863
  }
34864
+ historyLimitedByOldBudget(session) {
34865
+ if (session.coverage?.note?.match(/Import limited to 50,000 messages \/ 16 million text characters \/ 2,000 pages\.|Session import limit reached\./)) return true;
34866
+ const timeline = this.db.prepare("SELECT note FROM timeline_coverage WHERE session_id=?").get(session.id);
34867
+ return String(timeline?.note || "").includes("Event history limited to 200,000 items / 32 MB per session.");
34868
+ }
34287
34869
  upsert(candidate) {
34288
34870
  const s = candidate.session, previous = this.getSession(s.id);
34289
34871
  const metadata2 = {
34290
34872
  ...s,
34291
34873
  model: s.model === "Unknown model" ? previous?.model || s.model : s.model,
34874
+ tokens: previous?.revision === candidate.revision ? previous.tokens : s.tokens,
34875
+ cost: previous?.revision === candidate.revision ? previous.cost : s.cost,
34876
+ usage: previous?.revision === candidate.revision ? previous.usage : s.usage,
34877
+ importVersion: previous?.importVersion,
34292
34878
  parentID: previous?.parentID && candidate.locator.agent ? previous.parentID : s.parentID,
34293
34879
  activity: previous?.activity,
34294
34880
  commits: previous?.commits || pendingCommits(),
@@ -34299,16 +34885,30 @@ var SessionGraphStore = class {
34299
34885
  ON CONFLICT(id) DO UPDATE SET metadata=excluded.metadata,locator=excluded.locator`).run(s.id, s.source, s.nativeID, JSON.stringify(metadata2), JSON.stringify(candidate.locator));
34300
34886
  }
34301
34887
  replace(candidate, messages, partial, note) {
34302
- const s = { ...candidate.session, revision: candidate.revision, coverage: { history: partial ? "partial" : "complete", note, importedAt: Date.now() } };
34888
+ const usage = summarizeUsage(candidate.session, messages, partial);
34889
+ const s = {
34890
+ ...candidate.session,
34891
+ tokens: usage.total,
34892
+ cost: usage.cost,
34893
+ usage,
34894
+ importVersion: IMPORT_METADATA_VERSION,
34895
+ revision: candidate.revision,
34896
+ coverage: { history: partial ? "partial" : "complete", note, importedAt: Date.now() }
34897
+ };
34303
34898
  this.db.exec("BEGIN IMMEDIATE");
34304
34899
  try {
34305
34900
  this.db.prepare("DELETE FROM messages WHERE session_id=?").run(s.id);
34306
34901
  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");
34307
- messages.forEach((message2, i) => insert.run(s.id, message2.id, i, JSON.stringify(message2), messageTime(message2.time), Number(isUserMessage(message2))));
34902
+ messages.forEach((message2, i) => insert.run(s.id, message2.id, i, JSON.stringify(message2), message2.eventOnly ? null : messageTime(message2.time), Number(isUserMessage(message2))));
34308
34903
  writeEvents(this.db, s.id, this.db.prepare("SELECT data FROM messages WHERE session_id=? ORDER BY ordinal").iterate(s.id));
34309
34904
  const commits = writeCommits(this.db, s);
34905
+ if (candidate.pullRequests !== void 0) {
34906
+ this.db.prepare("DELETE FROM session_pull_requests WHERE session_id=?").run(s.id);
34907
+ const insertPR = this.db.prepare("INSERT INTO session_pull_requests VALUES (?,?,?,?,?,?)");
34908
+ for (const pr2 of candidate.pullRequests) insertPR.run(s.id, pr2.host, pr2.repository, pr2.number, pr2.url, pr2.source);
34909
+ }
34310
34910
  const activity = this.db.prepare(activitySQL).get(s.id);
34311
- this.db.prepare("UPDATE sessions SET metadata=?, imported_revision=? WHERE id=?").run(JSON.stringify({ ...s, activity, commits }), candidate.revision, s.id);
34911
+ 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);
34312
34912
  this.db.prepare("DELETE FROM search_cache WHERE id=?").run(s.id);
34313
34913
  this.db.exec("COMMIT");
34314
34914
  } catch (error) {
@@ -34430,7 +35030,7 @@ var SessionGraphStore = class {
34430
35030
  }
34431
35031
  messages(id2, options = {}) {
34432
35032
  return this.readSnapshot(id2, (session) => {
34433
- const key = fingerprint(["messages", id2, session.revision, session.coverage]);
35033
+ const key = fingerprint2(["messages", id2, session.revision, session.coverage]);
34434
35034
  const offset = pageOffset(options.cursor, key), limit = pageLimit(options.limit);
34435
35035
  const rows2 = this.messagePage(id2, offset, limit);
34436
35036
  let remaining = 64e3, truncated = false;
@@ -34447,6 +35047,9 @@ var SessionGraphStore = class {
34447
35047
  time: messageTime(message2.time),
34448
35048
  role: message2.role,
34449
35049
  fragments,
35050
+ metadata: message2.metadata,
35051
+ usage: message2.usage,
35052
+ locations: message2.locations,
34450
35053
  files: message2.files.slice(0, 200),
34451
35054
  tools: message2.tools.slice(0, 200),
34452
35055
  partial: !!message2.partial || message2.fragments.length > 200 || message2.files.length > 200 || message2.tools.length > 200 || fragments.some((f) => f.truncated)
@@ -34467,19 +35070,29 @@ var SessionGraphStore = class {
34467
35070
  return this.readSnapshot(id2, (session) => {
34468
35071
  const page = this.messagePage(id2, Number(cursor || 0), 120);
34469
35072
  const files = /* @__PURE__ */ new Map(), tools = /* @__PURE__ */ new Map();
35073
+ const locations = [];
34470
35074
  for (const message2 of page.messages) {
34471
35075
  for (const file of message2.files) {
34472
35076
  const previous = files.get(file.path);
34473
35077
  files.set(file.path, { ...file, source: previous?.source === "snapshot" ? "snapshot" : file.source, steps: (previous?.steps || 0) + file.steps });
34474
35078
  }
34475
35079
  message2.tools.forEach((tool) => tools.set(tool, (tools.get(tool) || 0) + 1));
34476
- }
35080
+ for (const location of message2.locations || []) if (locations.length < 200 && messageTime(location.time) !== null) locations.push(location);
35081
+ }
35082
+ const pullRequests2 = !cursor ? this.db.prepare("SELECT host, repository, number, url, source FROM session_pull_requests WHERE session_id=? ORDER BY host, repository, number").all(id2).map(({ host, repository, number, url, source }) => ({
35083
+ host: String(host),
35084
+ repository: String(repository),
35085
+ number: Number(number),
35086
+ url: String(url),
35087
+ source
35088
+ })) : void 0;
34477
35089
  return {
34478
35090
  id: id2,
34479
35091
  revision: session.revision,
35092
+ pullRequests: pullRequests2?.length ? pullRequests2 : void 0,
34480
35093
  files: [...files.values()].sort((a, b) => b.steps - a.steps),
34481
35094
  tools: [...tools].map(([name, count]) => ({ name, count })),
34482
- locations: [],
35095
+ locations,
34483
35096
  messagesScanned: page.messages.length,
34484
35097
  snapshotSteps: page.messages.reduce((n, m) => n + (m.snapshots || 0), 0),
34485
35098
  nextCursor: page.next,
@@ -34551,7 +35164,7 @@ var Importer = class {
34551
35164
  this.adapters = adapters2.map((adapter) => withSourcePaths(adapter, () => this.store.setting("sourcePaths") || {}));
34552
35165
  }
34553
35166
  store;
34554
- status = { running: false, discovered: 0, imported: 0, unchanged: 0, failed: 0, errors: [] };
35167
+ status = { running: false, discovered: 0, imported: 0, unchanged: 0, failed: 0, errors: [], warnings: [] };
34555
35168
  job;
34556
35169
  adapters;
34557
35170
  async sources() {
@@ -34572,7 +35185,7 @@ var Importer = class {
34572
35185
  if (ids && save) {
34573
35186
  this.store.setting("selected", [...new Set(ids)]);
34574
35187
  }
34575
- this.status = { running: true, discovered: 0, imported: 0, unchanged: 0, failed: 0, errors: [] };
35188
+ this.status = { running: true, discovered: 0, imported: 0, unchanged: 0, failed: 0, errors: [], warnings: [] };
34576
35189
  const heartbeat = setInterval(() => this.store.heartbeat(), 5e3);
34577
35190
  this.job = this.run(ids || this.store.selected()).catch(() => {
34578
35191
  this.status.failed++;
@@ -34589,25 +35202,36 @@ var Importer = class {
34589
35202
  async settled() {
34590
35203
  await this.job;
34591
35204
  }
35205
+ report(kind, message2) {
35206
+ const messages = this.status[kind] ??= [];
35207
+ if (!messages.includes(message2)) messages.push(message2);
35208
+ }
34592
35209
  async run(ids) {
34593
35210
  for (const adapter of this.adapters.filter((a) => ids.includes(a.id))) {
34594
35211
  this.status.source = adapter.id;
34595
35212
  try {
34596
- if (!await adapter.detect()) throw new Error(`${adapter.name} is unavailable. Saved imports remain available.`);
35213
+ if (!await adapter.detect()) throw new Error("Source unavailable.");
34597
35214
  const discovery = await adapter.discover();
34598
35215
  const failedBefore = this.status.failed;
35216
+ const discoveryErrors = [...new Set(discovery.errors)];
34599
35217
  const seen = new Map(discovery.sessions.map((candidate) => [candidate.session.id, candidate]));
34600
35218
  this.status.discovered += seen.size;
34601
- this.status.errors.push(...discovery.warnings);
35219
+ for (const warning of discovery.warnings) this.report("warnings", warning);
35220
+ for (const error of discoveryErrors) this.report("errors", error);
35221
+ if (discovery.unavailable && !discoveryErrors.length) {
35222
+ discoveryErrors.push(`${adapter.name}: History unavailable.`);
35223
+ this.report("errors", discoveryErrors[0]);
35224
+ }
34602
35225
  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));
34603
35226
  for (const candidate of seen.values()) {
34604
- this.store.upsert(candidate);
34605
35227
  const saved = this.store.getSession(candidate.session.id);
34606
- const retry = !saved?.coverage?.importedAt || saved.coverage.note?.startsWith("Latest import failed:") || !this.store.commitsCurrent(candidate.session.id);
35228
+ const retry = !saved?.coverage?.importedAt || saved.importVersion !== IMPORT_METADATA_VERSION || saved.coverage.note?.startsWith("Latest import failed:") || !this.store.commitsCurrent(candidate.session.id) || this.store.historyLimitedByOldBudget(saved);
34607
35229
  if (!retry && saved?.revision === candidate.revision && this.store.revision(candidate.session.id) === candidate.revision) {
35230
+ this.store.upsert(candidate);
34608
35231
  this.status.unchanged++;
34609
35232
  continue;
34610
35233
  }
35234
+ if (!saved) this.store.upsert(candidate);
34611
35235
  try {
34612
35236
  const messages = /* @__PURE__ */ new Map();
34613
35237
  const cursors = /* @__PURE__ */ new Set();
@@ -34616,16 +35240,26 @@ var Importer = class {
34616
35240
  const page = await adapter.read(candidate, cursor);
34617
35241
  partial ||= Boolean(page.partial);
34618
35242
  note = page.note || note;
35243
+ let limited = false;
34619
35244
  for (const message2 of page.messages) {
34620
- if (!message2.id || messages.has(message2.id)) continue;
34621
- if (messages.size >= 5e4 || characters >= 16e6) {
34622
- partial = true;
35245
+ if (!message2.id) continue;
35246
+ const previous = messages.get(message2.id);
35247
+ if (previous) {
35248
+ if (message2.usage) previous.usage = previous.usage ? mergeUsage(previous.usage, message2.usage) : message2.usage;
35249
+ if (message2.metadata) previous.metadata = { ...previous.metadata, ...message2.metadata };
35250
+ continue;
35251
+ }
35252
+ if (messages.size >= MAX_SESSION_RECORDS || characters >= MAX_SESSION_CHARACTERS) {
35253
+ limited = true;
34623
35254
  break;
34624
35255
  }
34625
- let remaining = 16e6 - characters;
35256
+ let remaining = MAX_SESSION_CHARACTERS - characters;
34626
35257
  message2.fragments = message2.fragments.flatMap((fragment) => {
34627
35258
  const text2 = fragment.text.slice(0, remaining);
34628
- if (text2.length < fragment.text.length) message2.partial = true;
35259
+ if (text2.length < fragment.text.length) {
35260
+ message2.partial = true;
35261
+ limited = true;
35262
+ }
34629
35263
  remaining -= text2.length;
34630
35264
  return text2 ? [{ ...fragment, text: text2 }] : [];
34631
35265
  });
@@ -34638,29 +35272,31 @@ var Importer = class {
34638
35272
  pages++;
34639
35273
  if (cursor && cursors.has(cursor)) throw new Error("Source returned a repeated history cursor.");
34640
35274
  if (cursor) cursors.add(cursor);
34641
- if (pages >= 2e3 || messages.size >= 5e4 || characters >= 16e6) {
35275
+ if (limited || cursor && (pages >= MAX_SESSION_PAGES || messages.size >= MAX_SESSION_RECORDS || characters >= MAX_SESSION_CHARACTERS)) {
34642
35276
  partial = true;
34643
- note = `${note || ""} Import limited to 50,000 messages / 16 million text characters / 2,000 pages.`;
35277
+ note = [note, SESSION_LIMIT_NOTE].filter(Boolean).join(" ");
34644
35278
  break;
34645
35279
  }
34646
35280
  await yieldToIO();
34647
35281
  } while (cursor);
34648
35282
  const values = [...messages.values()];
34649
35283
  if (adapter.id === "opencode") values.reverse();
34650
- if (saved?.activity?.userMessages && values.every((message2) => message2.role === "system")) throw new Error("Source has no readable conversation. Previous imports are retained.");
35284
+ if (saved?.activity?.userMessages && values.every((message2) => message2.role === "system")) throw new Error("No readable conversation.");
34651
35285
  this.store.replace(candidate, values, partial, note);
34652
35286
  this.status.imported++;
34653
35287
  } catch (error) {
34654
35288
  this.status.failed++;
34655
35289
  this.store.failed(candidate.session.id, error instanceof Error ? error.message : "Unavailable");
34656
- if (this.status.errors.length < 30) this.status.errors.push(`${adapter.name}: ${error instanceof Error ? error.message : "Session import failed."}`);
35290
+ if (this.status.errors.length < 30) this.report("errors", `${adapter.name}: ${error instanceof Error ? error.message : "Session import failed."}`);
34657
35291
  }
34658
35292
  await yieldToIO();
34659
35293
  }
34660
- this.store.recordSource(adapter.id, [this.status.failed > failedBefore ? `${this.status.failed - failedBefore} sessions could not be updated; import again to retry.` : "", ...discovery.warnings].filter(Boolean).join(" ") || void 0);
35294
+ const failed = this.status.failed - failedBefore;
35295
+ if (discoveryErrors.length) this.status.failed++;
35296
+ this.store.recordSource(adapter.id, [...discoveryErrors, failed ? `${failed} ${failed === 1 ? "session" : "sessions"} failed to import. Run sync to retry.` : ""].filter(Boolean).join(" ") || void 0);
34661
35297
  } catch (error) {
34662
- const message2 = error instanceof Error ? error.message : `${adapter.name} import failed.`;
34663
- this.status.errors.push(message2);
35298
+ const message2 = `${adapter.name}: ${error instanceof Error ? error.message : "Import failed."}`;
35299
+ this.report("errors", message2);
34664
35300
  this.store.recordSource(adapter.id, message2);
34665
35301
  this.status.failed++;
34666
35302
  }
@@ -34981,7 +35617,7 @@ var nouns = "Wombat Pickle Pancake Badger Potato Narwhal Noodle Goblin Otter Tur
34981
35617
  var DEFAULT_PUBLISHING = { tokens: true, timestamps: true, messageCounts: true, messageTimestamps: true, model: true, harness: true };
34982
35618
  function publishingSettings(value) {
34983
35619
  const result = { ...DEFAULT_PUBLISHING };
34984
- if (object3(value)) {
35620
+ if (object4(value)) {
34985
35621
  for (const key of Object.keys(result)) if (typeof value[key] === "boolean") result[key] = value[key];
34986
35622
  }
34987
35623
  if (!result.timestamps || !result.messageCounts) result.messageTimestamps = false;
@@ -34996,11 +35632,11 @@ var publicModel = (value) => {
34996
35632
  return name.length <= 100 && modelPattern.test(name) ? name.toLowerCase() : null;
34997
35633
  };
34998
35634
  function publishableGraph(sessions, settings, messages = /* @__PURE__ */ new Map()) {
34999
- const fields2 = publishingSettings(settings);
35635
+ const fields3 = publishingSettings(settings);
35000
35636
  const ordered = [...sessions].sort((a, b) => a.created - b.created || a.id.localeCompare(b.id));
35001
35637
  const ids = new Map(ordered.map((session, index) => [session.id, index]));
35002
35638
  const groups = /* @__PURE__ */ new Map();
35003
- const graph = { version: 1, settings: fields2, sessions: ordered.map((session) => {
35639
+ const graph = { version: 1, settings: fields3, sessions: ordered.map((session) => {
35004
35640
  const key = laneKey(session);
35005
35641
  if (!groups.has(key)) groups.set(key, groups.size);
35006
35642
  const result = {
@@ -35009,16 +35645,16 @@ function publishableGraph(sessions, settings, messages = /* @__PURE__ */ new Map
35009
35645
  parent: session.parentID ? ids.get(session.parentID) ?? null : null,
35010
35646
  fork: session.forkID ? ids.get(session.forkID) ?? null : null
35011
35647
  };
35012
- if (fields2.timestamps) result.timestamps = { created: Math.trunc(session.created), lastMessageAt: session.activity?.lastMessageAt == null ? null : Math.trunc(session.activity.lastMessageAt) };
35013
- if (fields2.tokens) result.tokens = session.tokens;
35648
+ if (fields3.timestamps) result.timestamps = { created: Math.trunc(session.created), lastMessageAt: session.activity?.lastMessageAt == null ? null : Math.trunc(session.activity.lastMessageAt) };
35649
+ if (fields3.tokens) result.tokens = session.tokens;
35014
35650
  const stats = messages.get(session.id);
35015
- if (fields2.messageCounts) result.messages = { count: stats?.count ?? null, untimed: stats?.untimed ?? null, partial: stats?.partial ?? true };
35016
- if (fields2.messageTimestamps) result.messageTimes = { values: [], limited: stats?.timesLimited ?? true };
35017
- if (fields2.model) result.model = publicModel(session.model);
35018
- if (fields2.harness) result.harness = isKnownSource(session.source) ? session.source : null;
35651
+ if (fields3.messageCounts) result.messages = { count: stats?.count ?? null, untimed: stats?.untimed ?? null, partial: stats?.partial ?? true };
35652
+ if (fields3.messageTimestamps) result.messageTimes = { values: [], limited: stats?.timesLimited ?? true };
35653
+ if (fields3.model) result.model = publicModel(session.model);
35654
+ if (fields3.harness) result.harness = isKnownSource(session.source) ? session.source : null;
35019
35655
  return result;
35020
35656
  }) };
35021
- if (fields2.messageTimestamps) {
35657
+ if (fields3.messageTimestamps) {
35022
35658
  let bytes2 = PUBLIC_GRAPH_MAX_BYTES - new TextEncoder().encode(JSON.stringify(graph)).length;
35023
35659
  let remaining = PUBLIC_GRAPH_MAX_MESSAGE_TIMES;
35024
35660
  for (let index = 0; index < ordered.length; index++) {
@@ -35035,8 +35671,8 @@ function publishableGraph(sessions, settings, messages = /* @__PURE__ */ new Map
35035
35671
  }
35036
35672
  return validatePublicGraph(graph);
35037
35673
  }
35038
- var object3 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
35039
- var exact = (value, keys) => object3(value) && Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
35674
+ var object4 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
35675
+ var exact = (value, keys) => object4(value) && Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
35040
35676
  var integer = (value, max = Number.MAX_SAFE_INTEGER) => Number.isSafeInteger(value) && value >= 0 && value <= max;
35041
35677
  var time3 = (value) => integer(value, Date.UTC(2100, 0, 1));
35042
35678
  var nullableCount = (value) => value === null || integer(value);
@@ -35105,23 +35741,24 @@ function preparePublicGraph(store, ids, inputSettings) {
35105
35741
  const stats = /* @__PURE__ */ new Map();
35106
35742
  const count = store.db.prepare("SELECT count(*) AS count, count(*) FILTER (WHERE time IS NULL) AS untimed FROM timeline_items WHERE session_id=? AND kind='message' AND role IN ('user','assistant')");
35107
35743
  const times = store.db.prepare("SELECT time FROM timeline_items WHERE session_id=? AND kind='message' AND role IN ('user','assistant') AND time IS NOT NULL ORDER BY time,ordinal LIMIT ?");
35108
- const coverage2 = store.db.prepare("SELECT partial FROM timeline_coverage WHERE session_id=?");
35744
+ const metadata2 = store.db.prepare("SELECT metadata,partial FROM sessions LEFT JOIN timeline_coverage ON timeline_coverage.session_id=sessions.id WHERE sessions.id=?");
35109
35745
  let remaining = PUBLIC_GRAPH_MAX_MESSAGE_TIMES;
35110
35746
  store.db.exec("BEGIN");
35111
35747
  try {
35112
35748
  const sessions = ids.map((id2) => {
35113
- const session = store.getSession(id2);
35114
- if (!session) throw new PublishingError("Your session selection changed. Reopen publishing.");
35749
+ const row = metadata2.get(id2);
35750
+ if (!row) throw new PublishingError("Your session selection changed. Reopen publishing.");
35751
+ const session = JSON.parse(String(row.metadata));
35115
35752
  if (settings.messageCounts) {
35116
- const known = session.coverage?.history !== "pending" && !!coverage2.get(id2);
35753
+ const known = session.coverage?.history !== "pending" && row.partial !== null;
35117
35754
  const totals = count.get(id2);
35118
- const rows2 = settings.messageTimestamps ? times.all(id2, Math.min(remaining, 2e3)) : [];
35755
+ const rows2 = settings.messageTimestamps && remaining > 0 ? times.all(id2, Math.min(remaining, 2e3)) : [];
35119
35756
  remaining -= rows2.length;
35120
- const values = rows2.map((row) => Number(row.time));
35757
+ const values = rows2.map((row2) => Number(row2.time));
35121
35758
  stats.set(id2, {
35122
35759
  count: known ? Number(totals.count) : null,
35123
35760
  untimed: known ? Number(totals.untimed) : null,
35124
- partial: !known || session.coverage?.history !== "complete" || Boolean(coverage2.get(id2)?.partial),
35761
+ partial: !known || session.coverage?.history !== "complete" || Boolean(row.partial),
35125
35762
  times: values,
35126
35763
  timesLimited: !known || Number(totals.count) - Number(totals.untimed) > values.length
35127
35764
  });
@@ -35258,6 +35895,77 @@ var PublishingClient = class {
35258
35895
  }
35259
35896
  };
35260
35897
 
35898
+ // server/git-checkouts.ts
35899
+ import { execFile as execFile2 } from "node:child_process";
35900
+ import { createHash as createHash7 } from "node:crypto";
35901
+ import { basename as basename12, isAbsolute as isAbsolute8 } from "node:path";
35902
+ import { promisify as promisify2 } from "node:util";
35903
+ var exec2 = promisify2(execFile2);
35904
+ var cache2 = /* @__PURE__ */ new Map();
35905
+ var env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^GIT_/i.test(key)));
35906
+ async function git(cwd2, ...args) {
35907
+ const { stdout } = await exec2("git", args, { cwd: cwd2, env: { ...env, GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: process.platform === "win32" ? "NUL" : "/dev/null", GIT_OPTIONAL_LOCKS: "0" }, timeout: 1500, maxBuffer: 8192, windowsHide: true });
35908
+ return stdout.replace(/\r?\n$/, "");
35909
+ }
35910
+ function remoteIdentity(remote) {
35911
+ const scp = !remote.includes("://") && /^(?:[^@/\s]+@)?([\w.-]+):([^\\\s]+)$/.exec(remote);
35912
+ let host, path;
35913
+ if (scp) {
35914
+ [, host, path] = scp;
35915
+ if (/^[a-z]:[\\/]/i.test(remote)) return;
35916
+ } else {
35917
+ try {
35918
+ const url = new URL(remote);
35919
+ if (!["https:", "http:", "ssh:", "git:"].includes(url.protocol)) return;
35920
+ host = url.host;
35921
+ path = url.pathname;
35922
+ } catch {
35923
+ return;
35924
+ }
35925
+ }
35926
+ path = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
35927
+ if (!host || !/^[\w.-]+(?:\/[\w.-]+)+$/.test(path)) return;
35928
+ host = host.toLowerCase();
35929
+ if (host === "github.com") path = path.toLowerCase();
35930
+ return { key: `${host}/${path}`, label: path.split("/").at(-1) };
35931
+ }
35932
+ async function inspect(directory3) {
35933
+ try {
35934
+ const [worktree, common, ...extra2] = (await git(directory3, "rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir")).split(/\r?\n/);
35935
+ if (extra2.length || !isAbsolute8(worktree) || !isAbsolute8(common)) return;
35936
+ const origin = await git(worktree, "config", "--local", "--no-includes", "--get", "remote.origin.url").catch(() => "");
35937
+ const remote = remoteIdentity(origin);
35938
+ const key = remote ? `remote:${remote.key}` : `local:${common}`;
35939
+ return {
35940
+ worktree,
35941
+ repository: createHash7("sha256").update(key).digest("hex"),
35942
+ repositoryLabel: remote?.label || (basename12(common) === ".git" ? basename12(common.slice(0, -5)) : basename12(common))
35943
+ };
35944
+ } catch {
35945
+ return;
35946
+ }
35947
+ }
35948
+ async function annotateGitCheckouts(sessions) {
35949
+ const directories = [...new Set(sessions.map((session) => session.directory))].filter((path) => isAbsolute8(path) && !/^[\\/]{2}/.test(path));
35950
+ const results = /* @__PURE__ */ new Map();
35951
+ let index = 0;
35952
+ await Promise.all(Array.from({ length: Math.min(8, directories.length) }, async () => {
35953
+ while (index < directories.length) {
35954
+ const directory3 = directories[index++];
35955
+ let entry = cache2.get(directory3);
35956
+ if (!entry || entry.expires <= Date.now()) {
35957
+ cache2.delete(directory3);
35958
+ if (cache2.size >= 4096) cache2.delete(cache2.keys().next().value);
35959
+ entry = { expires: Date.now() + 12e4, value: inspect(directory3) };
35960
+ cache2.set(directory3, entry);
35961
+ }
35962
+ const checkout = await entry.value;
35963
+ if (checkout) results.set(directory3, checkout);
35964
+ }
35965
+ }));
35966
+ return sessions.map((session) => ({ ...session, checkout: results.get(session.directory) }));
35967
+ }
35968
+
35261
35969
  // server/middleware.ts
35262
35970
  var publishing = new PublishingClient();
35263
35971
  var generation = /* @__PURE__ */ Symbol("sessiongraph-backend");
@@ -35372,7 +36080,9 @@ async function sessionGraphMiddleware(req, res, next) {
35372
36080
  }
35373
36081
  if (url.pathname === "/api/sessiongraph" && req.method === "GET") {
35374
36082
  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) }));
35375
- return json5(200, store.library(sources2, importer.status.running));
36083
+ const data = store.library(sources2, importer.status.running);
36084
+ data.sessions = await annotateGitCheckouts(data.sessions);
36085
+ return json5(200, data);
35376
36086
  }
35377
36087
  const match2 = /^\/api\/sessiongraph\/session\/([^/]+)(?:\/(content|timeline|commits|events|event-markers|connection|prepare-launch|open-terminal))?$/.exec(url.pathname);
35378
36088
  if (match2) {
@@ -35400,7 +36110,7 @@ async function sessionGraphMiddleware(req, res, next) {
35400
36110
  if (match2[2] === "events") return json5(200, store.events(id2, Object.fromEntries(["cursor", "item", "filter", "revision"].flatMap((key) => url.searchParams.has(key) ? [[key, url.searchParams.get(key)]] : []))));
35401
36111
  if (match2[2] === "connection") return json5(200, await getLaunchConnection(session));
35402
36112
  const cursor = url.searchParams.get("cursor") || void 0;
35403
- if (cursor && (!/^\d{1,9}$/.test(cursor) || Number(cursor) > 5e4)) return json5(400, { error: "Invalid cursor." });
36113
+ if (cursor && (!/^\d{1,9}$/.test(cursor) || Number(cursor) > MAX_SESSION_RECORDS)) return json5(400, { error: "Invalid cursor." });
35404
36114
  return json5(200, match2[2] === "content" ? store.content(id2, cursor) : store.detail(id2, cursor));
35405
36115
  }
35406
36116
  return json5(404, { error: "Not found." });