sessiongraph 1.0.15 → 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.
- package/PRIVACY.md +15 -61
- package/README.md +35 -55
- package/bin/sessiongraph.mjs +14 -8
- package/dist/assets/index-C0jATzD9.css +1 -0
- package/dist/assets/{index-D4P4hbvc.js → index-CFlNwG9H.js} +1 -1
- package/dist/assets/index-D24Hz9MJ.js +180 -0
- package/dist/assets/{index-Kotmn42s.js → index-D7udGrT1.js} +1 -1
- package/dist/assets/{index-BLM-0yG6.js → index-U9QGDl1t.js} +1 -1
- package/dist/assets/katagami-sans-DMv8PCo8.woff2 +0 -0
- package/dist/assets/licenses/hugeicons.txt +21 -0
- package/dist/assets/licenses/katagami.txt +93 -0
- package/dist/assets/public-viewer-CyDoUT6s.css +1 -0
- package/dist/assets/public-viewer-iQBchlbq.js +24 -0
- package/dist/assets/scene-DmT4K5Nj.js +248 -0
- package/dist/assets/share-DrezE0sG.js +7 -0
- package/dist/assets/{three-D_1Qt16u.js → three-DDiuFd7k.js} +21 -21
- package/dist/assets/{worker-C10U_apJ.js → worker-B9mWJfQ6.js} +1 -1
- package/dist/index.html +2 -2
- package/dist-server/cli.mjs +48449 -15768
- package/dist-server/install-cli.mjs +204 -0
- package/dist-server/server.mjs +1081 -376
- package/docs/cli.md +293 -190
- package/docs/guide.md +15 -8
- package/docs/import-coverage.md +73 -5
- package/docs/performance.md +164 -0
- package/docs/releases.md +6 -0
- package/package.json +18 -10
- package/dist/assets/external-links-BmBkCsrt.js +0 -1
- package/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
- package/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
- package/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
- package/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
- package/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
- package/dist/assets/index-B1kyvo41.js +0 -175
- package/dist/assets/index-Du0_nVjH.css +0 -1
- package/dist/assets/publishing-CEvQPkO1.css +0 -1
- package/dist/assets/publishing-D9CqkbeB.js +0 -23
- package/dist/assets/scene-CTHyYtma.js +0 -139
- package/dist/assets/share-Cw1E-ED9.js +0 -7
- package/docs/importer-comparison.md +0 -48
- package/docs/session-artifacts-audit.md +0 -176
package/dist-server/server.mjs
CHANGED
|
@@ -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,
|
|
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, ...
|
|
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,
|
|
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 { ...
|
|
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 = (
|
|
2627
|
-
function databasePath(
|
|
2628
|
-
const override =
|
|
2629
|
-
const base = platform === "darwin" ? join2(home, "Library", "Application Support") : platform === "win32" ?
|
|
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
|
|
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.
|
|
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 = "",
|
|
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), ...
|
|
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
|
|
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, ...
|
|
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", "", { ...
|
|
2983
|
-
if (["tool_result", "tool-result"].includes(part.type)) return [eventFor(message2, id2, "tool_result", part.name || part.toolName || "Tool result", "", { ...
|
|
2984
|
-
if (["thinking", "reasoning"].includes(part.type)) return [eventFor(message2, id2, "reasoning", "Recorded reasoning", eventText(part.thinking ?? part.text),
|
|
2985
|
-
return [eventFor(message2, id2, "event", `${part.type || "Unknown"} content`, "This content type is not represented as text.", { ...
|
|
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
|
|
3034
|
-
var
|
|
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 =
|
|
3038
|
-
return { cwd:
|
|
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 =
|
|
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 =
|
|
3105
|
-
const command = typeof value === "string" ? value :
|
|
3106
|
-
const explicit =
|
|
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 =
|
|
3166
|
-
return { text:
|
|
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
|
|
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)), { ...
|
|
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", "", { ...
|
|
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([
|
|
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
|
|
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,7 +31030,7 @@ 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);
|
|
@@ -30834,19 +31061,23 @@ function localFileAdapter(source) {
|
|
|
30834
31061
|
const preferred = candidate.locator.path.endsWith(".jsonl"), previousPreferred = previous?.locator.path.endsWith(".jsonl");
|
|
30835
31062
|
if (!previous || preferred && !previousPreferred || preferred === previousPreferred && candidate.session.updated > previous.session.updated) found.set(candidate.session.id, candidate);
|
|
30836
31063
|
} catch {
|
|
30837
|
-
failed++;
|
|
30838
31064
|
const nativeID = source.authoritativeIdentity?.(path);
|
|
30839
|
-
if (nativeID)
|
|
31065
|
+
if (nativeID) {
|
|
31066
|
+
const id2 = identity(source.id, nativeID);
|
|
31067
|
+
blocked.add(id2);
|
|
31068
|
+
unreadable.add(id2);
|
|
31069
|
+
} else failed++;
|
|
30840
31070
|
}
|
|
30841
31071
|
}
|
|
30842
31072
|
const listed = new Set(listing.files);
|
|
30843
31073
|
for (const path of metadata2.keys()) if (!listed.has(path)) metadata2.delete(path);
|
|
30844
|
-
if (failed) listing.warnings.push(`${
|
|
31074
|
+
if (failed) listing.warnings.push(`${source.name}: Skipped ${failed} unreadable, changing, unsupported, or oversized ${failed === 1 ? "history file" : "history files"}.`);
|
|
30845
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;
|
|
30846
31077
|
return { sessions, projects: [...new Map(sessions.map((c) => {
|
|
30847
31078
|
const p = project(source.id, c.session.directory);
|
|
30848
31079
|
return [p.id, p];
|
|
30849
|
-
})).values()], warnings: listing.warnings, blocked: [...blocked] };
|
|
31080
|
+
})).values()], warnings: listing.warnings, errors, blocked: [...blocked] };
|
|
30850
31081
|
},
|
|
30851
31082
|
async read(candidate, cursor) {
|
|
30852
31083
|
const offset = cursor === void 0 ? 0 : Number(cursor);
|
|
@@ -30854,12 +31085,11 @@ function localFileAdapter(source) {
|
|
|
30854
31085
|
const history = await load(candidate.locator.path, candidate.revision, await states(candidate.locator.path));
|
|
30855
31086
|
if (!history) throw new Error("History representation is no longer available.");
|
|
30856
31087
|
const messages = history.messages.slice(offset, offset + 100);
|
|
30857
|
-
const untimed = history.messages.some((m) => !time(m.time));
|
|
30858
31088
|
return {
|
|
30859
31089
|
messages,
|
|
30860
31090
|
cursor: offset + messages.length < history.messages.length ? String(offset + messages.length) : void 0,
|
|
30861
31091
|
partial: Boolean(history.partial || messages.some((m) => m.partial)),
|
|
30862
|
-
note:
|
|
31092
|
+
note: history.note
|
|
30863
31093
|
};
|
|
30864
31094
|
}
|
|
30865
31095
|
};
|
|
@@ -30872,9 +31102,11 @@ import { basename as basename4, dirname as dirname2, join as join6 } from "node:
|
|
|
30872
31102
|
function conversationMessage(raw, fallbackID) {
|
|
30873
31103
|
const role = raw.role === "user" ? "user" : ["assistant", "model", "thinking"].includes(raw.role) ? "assistant" : ["tool", "toolResult"].includes(raw.role) ? "tool" : "system";
|
|
30874
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);
|
|
30875
31107
|
let content = raw.content;
|
|
30876
31108
|
if (Array.isArray(content)) content = content.map((part) => {
|
|
30877
|
-
const p =
|
|
31109
|
+
const p = object3(part);
|
|
30878
31110
|
return p.type === "toolCall" ? { ...p, type: "tool_use", input: p.arguments } : p.type === "reasoning" ? { ...p, type: "thinking", thinking: p.text } : p;
|
|
30879
31111
|
});
|
|
30880
31112
|
if (raw.role === "thinking") content = [{ type: "thinking", thinking: raw.content }];
|
|
@@ -30895,7 +31127,7 @@ function conversationMessage(raw, fallbackID) {
|
|
|
30895
31127
|
else if (event.kind === "reasoning") addText(message2, event.text, "Assistant");
|
|
30896
31128
|
}
|
|
30897
31129
|
for (const call of Array.isArray(raw.toolCalls) ? raw.toolCalls : []) {
|
|
30898
|
-
const f =
|
|
31130
|
+
const f = object3(call.function);
|
|
30899
31131
|
if (!text(f.name)) continue;
|
|
30900
31132
|
message2.tools.push(f.name);
|
|
30901
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" }));
|
|
@@ -30909,7 +31141,7 @@ function googleMessage(raw, fallbackID) {
|
|
|
30909
31141
|
const parts = Array.isArray(raw.content) ? raw.content : raw.content != null ? [raw.content] : [];
|
|
30910
31142
|
const content = parts.map((part) => {
|
|
30911
31143
|
if (typeof part === "string") return { type: "text", text: part };
|
|
30912
|
-
const p =
|
|
31144
|
+
const p = object3(part);
|
|
30913
31145
|
if (typeof p.text === "string") return p.thought ? { type: "thinking", thinking: p.text } : { type: "text", text: p.text };
|
|
30914
31146
|
if (p.functionCall) return { type: "tool_use", ...p.functionCall, input: p.functionCall.args };
|
|
30915
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 };
|
|
@@ -30923,7 +31155,7 @@ function successfulEdits(messages, editNames) {
|
|
|
30923
31155
|
if (event.kind === "tool_call" && event.callID) {
|
|
30924
31156
|
let input = {};
|
|
30925
31157
|
try {
|
|
30926
|
-
input =
|
|
31158
|
+
input = object3(JSON.parse(event.input || "{}"));
|
|
30927
31159
|
} catch {
|
|
30928
31160
|
}
|
|
30929
31161
|
calls.set(event.callID, { name: event.name, input });
|
|
@@ -30992,7 +31224,7 @@ function piHistory(value) {
|
|
|
30992
31224
|
messages,
|
|
30993
31225
|
partial,
|
|
30994
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) },
|
|
30995
|
-
note: "
|
|
31227
|
+
note: "Includes all saved branches in this transcript."
|
|
30996
31228
|
};
|
|
30997
31229
|
}
|
|
30998
31230
|
var piAdapter = localFileAdapter({
|
|
@@ -31013,7 +31245,7 @@ var piAdapter = localFileAdapter({
|
|
|
31013
31245
|
var nativeText = (v3) => typeof v3 === "number" && Number.isSafeInteger(v3) ? String(v3) : text(v3);
|
|
31014
31246
|
var seconds = (v3) => typeof v3 === "number" && Number.isFinite(v3) && v3 > 0 ? v3 * 1e3 : time(v3);
|
|
31015
31247
|
var fileID = (path) => basename4(path).replace(/\.jsonl(?:\..*)?$|\.json$/, "");
|
|
31016
|
-
var sidecar2 = (files, path) =>
|
|
31248
|
+
var sidecar2 = (files, path) => object3(files.has(path) ? json3(files.get(path)) : void 0);
|
|
31017
31249
|
var roles = ["user", "assistant", "system", "tool", "toolResult", "model"];
|
|
31018
31250
|
function message(raw, id2, timestamp) {
|
|
31019
31251
|
if (!roles.includes(raw.role)) return;
|
|
@@ -31022,6 +31254,7 @@ function message(raw, id2, timestamp) {
|
|
|
31022
31254
|
}
|
|
31023
31255
|
function recordEvent(raw, id2, kind, timestamp, content) {
|
|
31024
31256
|
const m = blankMessage(id2, time(timestamp), "system");
|
|
31257
|
+
m.eventOnly = true;
|
|
31025
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 })];
|
|
31026
31259
|
m.partial = true;
|
|
31027
31260
|
return m;
|
|
@@ -31034,8 +31267,9 @@ function envelopeHistory(path, value) {
|
|
|
31034
31267
|
const header = rows2.find((r) => r.type === "session" || r.type === "session_start" || r.type === "session_startup") || {};
|
|
31035
31268
|
const nativeID = [...nativeIDs][0] || text(header.id || header.sessionId) || fileID(path);
|
|
31036
31269
|
const messages = rows2.flatMap((r, i) => {
|
|
31037
|
-
const body2 =
|
|
31270
|
+
const body2 = object3(r.message), role = body2.role || r.role || (["user", "assistant", "system"].includes(r.type) ? r.type : void 0);
|
|
31038
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 });
|
|
31039
31273
|
return m ? [m] : [];
|
|
31040
31274
|
});
|
|
31041
31275
|
if (!messages.length) throw new Error("No readable conversation records.");
|
|
@@ -31046,37 +31280,36 @@ function envelopeHistory(path, value) {
|
|
|
31046
31280
|
messages,
|
|
31047
31281
|
partial: true,
|
|
31048
31282
|
session: { directory: text(meta.cwd), created: time(header.timestamp), title: text(header.title), model: text(last?.message?.model || last?.model) || "Unknown model" },
|
|
31049
|
-
note:
|
|
31283
|
+
note: partial ? "Some transcript records could not be imported." : void 0
|
|
31050
31284
|
};
|
|
31051
31285
|
}
|
|
31052
31286
|
function ampHistory(path, files) {
|
|
31053
|
-
const raw =
|
|
31287
|
+
const raw = object3(json3(files.get(path)));
|
|
31054
31288
|
if (!text(raw.id) || !Array.isArray(raw.messages)) throw new Error("Unsupported Amp thread.");
|
|
31055
31289
|
const messages = raw.messages.flatMap((m, i) => {
|
|
31056
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 });
|
|
31057
31292
|
return result ? [result] : [];
|
|
31058
31293
|
});
|
|
31059
|
-
return { nativeID: raw.id, messages, partial: true, session: { created: time(raw.created), title: text(raw.title), directory: text(raw.cwd) }
|
|
31294
|
+
return { nativeID: raw.id, messages, partial: true, session: { created: time(raw.created), title: text(raw.title), directory: text(raw.cwd) } };
|
|
31060
31295
|
}
|
|
31061
31296
|
function jcodeHistory(path, files) {
|
|
31062
|
-
const raw =
|
|
31297
|
+
const raw = object3(json3(files.get(path)));
|
|
31063
31298
|
if (!text(raw.id) || !Array.isArray(raw.messages)) throw new Error("Unsupported Jcode session.");
|
|
31064
31299
|
const journal = path.replace(/\.json$/, ".journal.jsonl");
|
|
31065
31300
|
const appended = files.has(journal) ? jsonLines(files.get(journal)) : { rows: [], partial: false };
|
|
31066
31301
|
const records = [...raw.messages];
|
|
31067
31302
|
for (const row of appended.rows) {
|
|
31068
31303
|
if (Array.isArray(row.append_messages)) records.push(...row.append_messages);
|
|
31069
|
-
if (row.meta) Object.assign(raw,
|
|
31304
|
+
if (row.meta) Object.assign(raw, object3(row.meta));
|
|
31070
31305
|
}
|
|
31071
|
-
const
|
|
31072
|
-
|
|
31073
|
-
|
|
31074
|
-
if (seen.has(id2)) return [];
|
|
31075
|
-
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]) => {
|
|
31076
31309
|
const m = message(r, id2);
|
|
31077
31310
|
return m ? [m] : [];
|
|
31078
31311
|
});
|
|
31079
|
-
return { nativeID: raw.id, messages, partial: appended.partial, session: { title: text(raw.title), directory: text(raw.working_dir), created: time(raw.created_at), model: text(raw.model) || "Unknown model", provider: text(raw.provider_key) }
|
|
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) } };
|
|
31080
31313
|
}
|
|
31081
31314
|
function codebuffHistory(path, files, free) {
|
|
31082
31315
|
const records = json3(files.get(path));
|
|
@@ -31089,11 +31322,11 @@ function codebuffHistory(path, files, free) {
|
|
|
31089
31322
|
return m ? [m] : [];
|
|
31090
31323
|
});
|
|
31091
31324
|
const chat = basename4(dirname2(path)), project2 = basename4(dirname2(dirname2(dirname2(path))));
|
|
31092
|
-
return { nativeID: `${project2}/${chat}`, messages, partial: true
|
|
31325
|
+
return { nativeID: `${project2}/${chat}`, messages, partial: true };
|
|
31093
31326
|
}
|
|
31094
31327
|
function vibeHistory(path, files) {
|
|
31095
|
-
const raw =
|
|
31096
|
-
const meta = legacy ?
|
|
31328
|
+
const raw = object3(json3(files.get(path))), legacy = basename4(path) !== "meta.json";
|
|
31329
|
+
const meta = legacy ? object3(raw.metadata) : raw;
|
|
31097
31330
|
const transcript = join6(dirname2(path), "messages.jsonl");
|
|
31098
31331
|
const parsed = files.has(transcript) ? jsonLines(files.get(transcript)) : { rows: [], partial: false };
|
|
31099
31332
|
const records = legacy ? raw.messages : parsed.rows;
|
|
@@ -31106,8 +31339,20 @@ function vibeHistory(path, files) {
|
|
|
31106
31339
|
nativeID: meta.session_id,
|
|
31107
31340
|
messages,
|
|
31108
31341
|
partial: parsed.partial || !messages.length,
|
|
31109
|
-
session: {
|
|
31110
|
-
|
|
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
|
+
}
|
|
31111
31356
|
};
|
|
31112
31357
|
}
|
|
31113
31358
|
function acpHistory(path, value) {
|
|
@@ -31120,7 +31365,7 @@ function acpHistory(path, value) {
|
|
|
31120
31365
|
}
|
|
31121
31366
|
};
|
|
31122
31367
|
for (const [i, row] of rows2.entries()) {
|
|
31123
|
-
const p =
|
|
31368
|
+
const p = object3(row.params), u2 = object3(p.update), kind = text(u2.sessionUpdate);
|
|
31124
31369
|
if (text(p.sessionId)) ids.add(p.sessionId);
|
|
31125
31370
|
const timestamp = time(p._meta?.agentTimestampMs) || time(row.timestamp);
|
|
31126
31371
|
const role = kind === "user_message_chunk" ? "user" : kind === "agent_message_chunk" ? "assistant" : "";
|
|
@@ -31139,18 +31384,18 @@ function acpHistory(path, value) {
|
|
|
31139
31384
|
flush();
|
|
31140
31385
|
if (ids.size > 1) throw new Error("Multiple sessions in one ACP event log.");
|
|
31141
31386
|
if (!ids.size || !messages.length) throw new Error("No supported ACP session updates.");
|
|
31142
|
-
return { nativeID: [...ids][0], messages, partial: true, note: "
|
|
31387
|
+
return { nativeID: [...ids][0], messages, partial: true, note: "Turn boundaries and tool details may be incomplete." };
|
|
31143
31388
|
}
|
|
31144
31389
|
function dshHistory(value) {
|
|
31145
31390
|
const { rows: rows2, partial } = jsonLines(value), header = rows2.find((r) => r.type === "session");
|
|
31146
31391
|
if (!text(header?.id)) throw new Error("Unsupported DeepSeek Harness session.");
|
|
31147
31392
|
const messages = rows2.flatMap((r, i) => {
|
|
31148
31393
|
if (!["user/message", "assistant/message", "tool/message"].includes(r.type)) return [];
|
|
31149
|
-
const body2 =
|
|
31394
|
+
const body2 = object3(r.data?.message);
|
|
31150
31395
|
const m = message({ ...body2, role: body2.role || r.type.split("/")[0] }, text(body2.id) || `record:${i}`, r.time);
|
|
31151
31396
|
return m ? [m] : [];
|
|
31152
31397
|
});
|
|
31153
|
-
return { nativeID: header.id, messages, partial: true, session: { directory: text(header.cwd), created: time(header.createdAt ?? header.time) }, note:
|
|
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 };
|
|
31154
31399
|
}
|
|
31155
31400
|
|
|
31156
31401
|
// server/adapters/sqlite-histories.ts
|
|
@@ -31159,11 +31404,14 @@ import { lstat as lstat3 } from "node:fs/promises";
|
|
|
31159
31404
|
// server/adapters/sqlite-snapshot.ts
|
|
31160
31405
|
import { DatabaseSync } from "node:sqlite";
|
|
31161
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";
|
|
31162
31408
|
import { tmpdir } from "node:os";
|
|
31163
31409
|
import { join as join7 } from "node:path";
|
|
31164
31410
|
var copies = /* @__PURE__ */ new Map();
|
|
31165
31411
|
var SqliteSnapshotChangedError = class extends Error {
|
|
31166
31412
|
};
|
|
31413
|
+
var SqliteSnapshotFileError = class extends Error {
|
|
31414
|
+
};
|
|
31167
31415
|
var close = (path) => {
|
|
31168
31416
|
const copy = copies.get(path);
|
|
31169
31417
|
if (!copy) return;
|
|
@@ -31177,17 +31425,82 @@ var close = (path) => {
|
|
|
31177
31425
|
process.once("exit", () => {
|
|
31178
31426
|
for (const path of copies.keys()) close(path);
|
|
31179
31427
|
});
|
|
31180
|
-
function
|
|
31181
|
-
return
|
|
31428
|
+
function snapshotFiles(path, large) {
|
|
31429
|
+
return [path, `${path}-wal`].map((file, i) => {
|
|
31182
31430
|
try {
|
|
31183
31431
|
const s = lstatSync2(file);
|
|
31184
|
-
|
|
31185
|
-
|
|
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;
|
|
31186
31436
|
} catch (error) {
|
|
31187
31437
|
if (i && error.code === "ENOENT") return null;
|
|
31188
31438
|
throw error;
|
|
31189
31439
|
}
|
|
31190
|
-
})
|
|
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
|
+
}
|
|
31191
31504
|
}
|
|
31192
31505
|
function withSqliteSnapshot(path, read3, expected, pinned = false) {
|
|
31193
31506
|
const retained = copies.get(path);
|
|
@@ -31213,8 +31526,7 @@ function withSqliteSnapshot(path, read3, expected, pinned = false) {
|
|
|
31213
31526
|
}
|
|
31214
31527
|
}
|
|
31215
31528
|
if (sqliteRevision(path) !== revision2) throw new SqliteSnapshotChangedError("History database changed while copying; import again.");
|
|
31216
|
-
db2 =
|
|
31217
|
-
db2.exec("PRAGMA query_only=ON; PRAGMA trusted_schema=OFF; PRAGMA busy_timeout=1000; BEGIN;");
|
|
31529
|
+
db2 = openSnapshot(destination);
|
|
31218
31530
|
copy = { revision: revision2, directory: directory3, db: db2 };
|
|
31219
31531
|
copies.set(path, copy);
|
|
31220
31532
|
} catch (error) {
|
|
@@ -31260,13 +31572,13 @@ function columns(db2, table) {
|
|
|
31260
31572
|
if (!/^[a-z_][a-z0-9_]*$/.test(table) || !hasTable(db2, table)) throw new Error(`Unsupported history table: ${table}.`);
|
|
31261
31573
|
return new Set(db2.prepare(`PRAGMA table_info("${table}")`).all().map((r) => String(r.name)));
|
|
31262
31574
|
}
|
|
31263
|
-
function rows(db2, table,
|
|
31575
|
+
function rows(db2, table, fields3, filter, order, limit = 5e4) {
|
|
31264
31576
|
const available = columns(db2, table);
|
|
31265
|
-
for (const name of [...
|
|
31577
|
+
for (const name of [...fields3, ...filter ? [filter[0]] : [], ...order ? [order] : []]) if (!/^[a-zA-Z_][\w]*$/.test(name)) throw new Error("Invalid history column.");
|
|
31266
31578
|
if (filter && !available.has(filter[0])) throw new Error("Unsupported history relation.");
|
|
31267
31579
|
const size = (f) => `length(CAST("${f}" AS BLOB))`;
|
|
31268
|
-
const select =
|
|
31269
|
-
const oversized =
|
|
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";
|
|
31270
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}`;
|
|
31271
31583
|
const result = [];
|
|
31272
31584
|
let bytes2 = 0;
|
|
@@ -31298,13 +31610,13 @@ function sqliteHistoryAdapter(source) {
|
|
|
31298
31610
|
return {
|
|
31299
31611
|
id: source.id,
|
|
31300
31612
|
name: source.name,
|
|
31301
|
-
description: source.description || "Local
|
|
31613
|
+
description: source.description || "Local session database",
|
|
31302
31614
|
capabilities: { history: source.history !== false, forks: false, children: false, files: false },
|
|
31303
31615
|
async detect() {
|
|
31304
31616
|
return (await source.paths()).length > 0;
|
|
31305
31617
|
},
|
|
31306
31618
|
async discover() {
|
|
31307
|
-
const sessions = /* @__PURE__ */ new Map(),
|
|
31619
|
+
const sessions = /* @__PURE__ */ new Map(), errors = [], blocked = [];
|
|
31308
31620
|
let unavailable = false;
|
|
31309
31621
|
for (const path of await source.paths()) {
|
|
31310
31622
|
try {
|
|
@@ -31314,15 +31626,14 @@ function sqliteHistoryAdapter(source) {
|
|
|
31314
31626
|
cached2 = withSqliteSnapshot(path, (db2) => {
|
|
31315
31627
|
const table = typeof source.table === "string" ? source.table : source.table(db2);
|
|
31316
31628
|
const values2 = rows(db2, table, source.fields, void 0, source.key, 2e4), found = [];
|
|
31317
|
-
const blocked2 = [],
|
|
31318
|
-
let
|
|
31629
|
+
const blocked2 = [], errors2 = [];
|
|
31630
|
+
let failed = 0;
|
|
31319
31631
|
for (const row of values2) {
|
|
31320
31632
|
try {
|
|
31321
31633
|
const h3 = parseHistory(source, db2, row, path);
|
|
31322
31634
|
if (!h3) continue;
|
|
31323
31635
|
if (source.history !== false && !h3.messages.length) {
|
|
31324
31636
|
blocked2.push(identity(source.id, String(row[source.key])));
|
|
31325
|
-
empty++;
|
|
31326
31637
|
continue;
|
|
31327
31638
|
}
|
|
31328
31639
|
if (!h3.nativeID || h3.nativeID.length > 512) throw new Error("Missing native session identity.");
|
|
@@ -31342,30 +31653,31 @@ function sqliteHistoryAdapter(source) {
|
|
|
31342
31653
|
found.push({ session, revision: rev, locator: { path, snapshot: snapshot2, table, key: String(row[source.key]) } });
|
|
31343
31654
|
} catch {
|
|
31344
31655
|
blocked2.push(identity(source.id, String(row[source.key])));
|
|
31656
|
+
failed++;
|
|
31345
31657
|
}
|
|
31346
31658
|
}
|
|
31347
|
-
if (
|
|
31348
|
-
|
|
31349
|
-
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 };
|
|
31350
31661
|
}, snapshot2);
|
|
31351
31662
|
metadata2.set(path, cached2);
|
|
31352
31663
|
}
|
|
31353
|
-
|
|
31664
|
+
errors.push(...cached2.errors);
|
|
31354
31665
|
blocked.push(...cached2.blocked);
|
|
31355
31666
|
for (const c of cached2.candidates) {
|
|
31356
31667
|
const old = sessions.get(c.session.id);
|
|
31357
31668
|
if (!old || c.session.updated > old.session.updated) sessions.set(c.session.id, c);
|
|
31358
31669
|
}
|
|
31359
|
-
} catch {
|
|
31670
|
+
} catch (error) {
|
|
31360
31671
|
unavailable = true;
|
|
31361
|
-
|
|
31672
|
+
const detail = error instanceof SqliteSnapshotFileError || error instanceof SqliteSnapshotChangedError ? error.message : "Could not read a history database.";
|
|
31673
|
+
errors.push(`${source.name}: ${detail}`);
|
|
31362
31674
|
}
|
|
31363
31675
|
}
|
|
31364
31676
|
const values = [...sessions.values()];
|
|
31365
31677
|
return { sessions: values, projects: [...new Map(values.map((c) => {
|
|
31366
31678
|
const p = project(source.id, c.session.directory);
|
|
31367
31679
|
return [p.id, p];
|
|
31368
|
-
})).values()], warnings, blocked, unavailable };
|
|
31680
|
+
})).values()], warnings: [], errors, blocked, unavailable };
|
|
31369
31681
|
},
|
|
31370
31682
|
async read(candidate, cursor) {
|
|
31371
31683
|
if (cursor) throw new Error("Invalid SQLite history cursor.");
|
|
@@ -31377,7 +31689,7 @@ function sqliteHistoryAdapter(source) {
|
|
|
31377
31689
|
const history = parseHistory(source, db2, row, path);
|
|
31378
31690
|
if (!history || history.nativeID !== candidate.session.nativeID) throw new Error("Session identity changed.");
|
|
31379
31691
|
if (source.history !== false && !history.messages.length) throw new Error("No readable conversation.");
|
|
31380
|
-
return { messages: history.messages, partial: Boolean(history.partial || history.messages.some((m) => m.partial)), note:
|
|
31692
|
+
return { messages: history.messages, partial: Boolean(history.partial || history.messages.some((m) => m.partial)), note: history.note };
|
|
31381
31693
|
}, snapshot2);
|
|
31382
31694
|
}
|
|
31383
31695
|
};
|
|
@@ -31402,23 +31714,25 @@ function combineAdapters(parts) {
|
|
|
31402
31714
|
return false;
|
|
31403
31715
|
},
|
|
31404
31716
|
async discover() {
|
|
31405
|
-
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();
|
|
31406
31718
|
for (const [i, part] of parts.entries()) {
|
|
31407
31719
|
let result;
|
|
31408
31720
|
try {
|
|
31409
31721
|
if (!await part.detect()) continue;
|
|
31410
31722
|
result = await part.discover();
|
|
31411
31723
|
} catch {
|
|
31412
|
-
|
|
31724
|
+
errors.push(`${part.name}: Could not read a history source.`);
|
|
31413
31725
|
break;
|
|
31414
31726
|
}
|
|
31415
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.`);
|
|
31416
31730
|
for (const id2 of result.blocked || []) blocked.add(id2);
|
|
31417
31731
|
for (const p of result.projects) projects.set(p.id, p);
|
|
31418
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 } });
|
|
31419
31733
|
if (result.unavailable) break;
|
|
31420
31734
|
}
|
|
31421
|
-
return { sessions: [...sessions.values()], projects: [...projects.values()], warnings };
|
|
31735
|
+
return { sessions: [...sessions.values()], projects: [...projects.values()], warnings, errors };
|
|
31422
31736
|
},
|
|
31423
31737
|
async read(candidate, cursor) {
|
|
31424
31738
|
const index = Number(candidate.locator.representation);
|
|
@@ -31435,6 +31749,8 @@ function claudeMessages(rows2, candidate, times, entries2) {
|
|
|
31435
31749
|
return rows2.map((row) => {
|
|
31436
31750
|
const raw = row.message;
|
|
31437
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);
|
|
31438
31754
|
if (raw?.model) candidate.session.model = raw.model;
|
|
31439
31755
|
if (row.parent_agent_id && candidate.locator.parent) candidate.session.parentID = identity("claude-code", `${candidate.locator.parent}/agent/${row.parent_agent_id}`);
|
|
31440
31756
|
if (typeof raw?.content === "string") addText(msg, raw.content, row.type === "user" ? "You" : "Assistant");
|
|
@@ -31546,13 +31862,13 @@ var sdkClaudeAdapter = {
|
|
|
31546
31862
|
if (!child.isFile() || !/^agent-[\w-]+\.jsonl$/.test(child.name)) continue;
|
|
31547
31863
|
try {
|
|
31548
31864
|
const agent = child.name.slice(6, -6), path = join8(file.children, child.name), stats = await stat(path);
|
|
31549
|
-
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 } });
|
|
31550
31866
|
} catch {
|
|
31551
31867
|
unreadable++;
|
|
31552
31868
|
}
|
|
31553
31869
|
}
|
|
31554
31870
|
}
|
|
31555
|
-
if (unreadable) warnings.push(
|
|
31871
|
+
if (unreadable) warnings.push(`Claude Code: Skipped ${unreadable} unavailable or oversized transcripts.`);
|
|
31556
31872
|
return { sessions, projects: [...new Map(sessions.map((c) => {
|
|
31557
31873
|
const p = project("claude-code", c.session.directory);
|
|
31558
31874
|
return [p.id, p];
|
|
@@ -31562,6 +31878,21 @@ var sdkClaudeAdapter = {
|
|
|
31562
31878
|
const offset = Number(cursor || 0);
|
|
31563
31879
|
if (!Number.isSafeInteger(offset) || offset < 0) throw new Error("Invalid history cursor.");
|
|
31564
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
|
+
}
|
|
31565
31896
|
const start = Math.max(0, offset - 1), count = 120 + offset - start;
|
|
31566
31897
|
const sessionId = candidate.locator.parent || candidate.session.nativeID;
|
|
31567
31898
|
const options = { dir: candidate.locator.dir || void 0, offset: start, limit: count + 1, sessionStore: claudeTranscriptStore(transcript, sessionId, candidate.locator.agent) };
|
|
@@ -31570,7 +31901,7 @@ var sdkClaudeAdapter = {
|
|
|
31570
31901
|
const messages = claudeMessages(rows2.slice(0, count), candidate, transcript.times, transcript.byID).slice(offset - start);
|
|
31571
31902
|
if (!offset && !messages.length && transcript.size > 100) throw new Error("SDK returned no readable conversation for this transcript.");
|
|
31572
31903
|
if (!more && await claudeRevision(candidate.locator.path) !== candidate.revision) throw new Error("Session changed during import; import again to capture the latest messages.");
|
|
31573
|
-
return { messages, cursor: more ? String(offset + 120) : void 0, partial: transcript.partial, note:
|
|
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 };
|
|
31574
31905
|
}
|
|
31575
31906
|
};
|
|
31576
31907
|
var exportedClaudeAdapter = localFileAdapter({
|
|
@@ -31751,11 +32082,17 @@ function codexRecord(raw, offset, candidate) {
|
|
|
31751
32082
|
if (raw.type !== "response_item") {
|
|
31752
32083
|
if (raw.type === "session_meta" || raw.type === "event_msg" && ["user_message", "agent_message", "agent_reasoning", "agent_reasoning_raw_content"].includes(p.type)) return;
|
|
31753
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
|
+
}
|
|
31754
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 || ""}` })];
|
|
31755
32090
|
return msg2;
|
|
31756
32091
|
}
|
|
31757
32092
|
const role = p.role === "user" ? "user" : p.role === "assistant" ? "assistant" : p.type === "message" ? "system" : "tool";
|
|
31758
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);
|
|
31759
32096
|
let input = p.arguments ?? p.input;
|
|
31760
32097
|
if (typeof input === "string") {
|
|
31761
32098
|
try {
|
|
@@ -31763,8 +32100,8 @@ function codexRecord(raw, offset, candidate) {
|
|
|
31763
32100
|
} catch {
|
|
31764
32101
|
}
|
|
31765
32102
|
}
|
|
31766
|
-
const
|
|
31767
|
-
msg.events = p.type === "message" ? role === "user" ? userBlockEvents(msg, p.content, codexUserText) : blockEvents(msg, p.content) : ["function_call", "custom_tool_call"].includes(p.type) ? [eventFor(msg, "call", "tool_call", p.name || "Tool call", "", { ...
|
|
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" })];
|
|
31768
32105
|
if (p.type === "message") {
|
|
31769
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");
|
|
31770
32107
|
} else if (["function_call", "custom_tool_call"].includes(p.type)) {
|
|
@@ -31783,7 +32120,7 @@ function codexRecord(raw, offset, candidate) {
|
|
|
31783
32120
|
var codexAdapter = {
|
|
31784
32121
|
id: "codex",
|
|
31785
32122
|
name: "Codex",
|
|
31786
|
-
description: "Local active and archived
|
|
32123
|
+
description: "Local active and archived transcripts",
|
|
31787
32124
|
capabilities: { history: true, forks: true, children: true, files: true },
|
|
31788
32125
|
async detect() {
|
|
31789
32126
|
try {
|
|
@@ -31810,6 +32147,7 @@ var codexAdapter = {
|
|
|
31810
32147
|
const stats = await stat2(path), session = blankSession("codex", meta.id, meta.cwd);
|
|
31811
32148
|
session.title = names.get(meta.id) || (typeof meta.name === "string" ? meta.name : "Untitled session");
|
|
31812
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";
|
|
31813
32151
|
const parent2 = meta.parent_thread_id || source?.parent_thread_id;
|
|
31814
32152
|
const fork = meta.forked_from_id || meta.forkedFromId;
|
|
31815
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 });
|
|
@@ -31829,8 +32167,7 @@ var codexAdapter = {
|
|
|
31829
32167
|
unsupported++;
|
|
31830
32168
|
}
|
|
31831
32169
|
}
|
|
31832
|
-
if (unsupported) warnings.push(
|
|
31833
|
-
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.`);
|
|
31834
32171
|
const sessions = [...found.values()];
|
|
31835
32172
|
return { sessions, projects: [...new Map(sessions.map((c) => {
|
|
31836
32173
|
const p = project("codex", c.session.directory);
|
|
@@ -31844,7 +32181,7 @@ var codexAdapter = {
|
|
|
31844
32181
|
return { messages: page.rows.flatMap((r) => {
|
|
31845
32182
|
const msg = codexRecord(r.value, r.offset, candidate);
|
|
31846
32183
|
return msg ? [msg] : [];
|
|
31847
|
-
}), cursor: page.cursor === void 0 ? void 0 : String(page.cursor), partial: page.partial
|
|
32184
|
+
}), cursor: page.cursor === void 0 ? void 0 : String(page.cursor), partial: page.partial };
|
|
31848
32185
|
}
|
|
31849
32186
|
};
|
|
31850
32187
|
|
|
@@ -31854,11 +32191,10 @@ import { homedir as homedir6 } from "node:os";
|
|
|
31854
32191
|
import { isAbsolute as isAbsolute2, join as join11 } from "node:path";
|
|
31855
32192
|
var SOURCE = "t3-code";
|
|
31856
32193
|
var PAGE = 100;
|
|
31857
|
-
var MAX_THREADS = 2e4;
|
|
31858
32194
|
var MAX_ITEM_JSON = 256e3;
|
|
31859
32195
|
var providerSource = { codex: "codex", claudeAgent: "claude-code", opencode: "opencode" };
|
|
31860
32196
|
var openCodeEditTools = /* @__PURE__ */ new Set(["patch", "apply_patch", "edit", "write", "multiedit"]);
|
|
31861
|
-
var
|
|
32197
|
+
var string3 = (value) => typeof value === "string" ? value : "";
|
|
31862
32198
|
function parsedObject(value) {
|
|
31863
32199
|
if (typeof value !== "string") return;
|
|
31864
32200
|
try {
|
|
@@ -31873,7 +32209,7 @@ function time2(value) {
|
|
|
31873
32209
|
return Number.isFinite(parsed) && parsed > 0 && parsed <= 864e13 ? parsed : 0;
|
|
31874
32210
|
}
|
|
31875
32211
|
function status(value) {
|
|
31876
|
-
return ["pending", "running", "completed", "failed"].includes(
|
|
32212
|
+
return ["pending", "running", "completed", "failed"].includes(string3(value)) ? value : "unknown";
|
|
31877
32213
|
}
|
|
31878
32214
|
async function databasePath2() {
|
|
31879
32215
|
const root3 = sourcePath("t3-code") || process.env.SESSIONGRAPH_T3_CODE_HISTORY_DIR || process.env.T3CODE_HOME || join11(homedir6(), ".t3");
|
|
@@ -31902,7 +32238,7 @@ function projectRoots(db2, ids) {
|
|
|
31902
32238
|
for (const batch of batches([...new Set(ids.filter(Boolean))])) {
|
|
31903
32239
|
const placeholders = batch.map(() => "?").join(",");
|
|
31904
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))
|
|
31905
|
-
roots2.set(
|
|
32241
|
+
roots2.set(string3(row.project_id), string3(row.workspace_root));
|
|
31906
32242
|
}
|
|
31907
32243
|
return roots2;
|
|
31908
32244
|
}
|
|
@@ -31912,7 +32248,7 @@ function aggregates(db2, table, ids) {
|
|
|
31912
32248
|
for (const batch of batches(ids)) {
|
|
31913
32249
|
const placeholders = batch.map(() => "?").join(",");
|
|
31914
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))
|
|
31915
|
-
result.set(
|
|
32251
|
+
result.set(string3(row.thread_id), [Number(row.n), string3(row.latest)]);
|
|
31916
32252
|
}
|
|
31917
32253
|
return result;
|
|
31918
32254
|
}
|
|
@@ -31926,147 +32262,174 @@ function linkedSessions(db2, ids) {
|
|
|
31926
32262
|
CASE WHEN json_valid(payload_json) THEN json_extract(payload_json,'$.nativeThreadRef.strength') END AS strength,
|
|
31927
32263
|
CASE WHEN json_valid(payload_json) THEN json_extract(payload_json,'$.nativeThreadRef.driver') END AS driver
|
|
31928
32264
|
FROM orchestration_v2_projection_provider_threads WHERE thread_id IN (${placeholders})`).all(...batch)) {
|
|
31929
|
-
const source = providerSource[
|
|
31930
|
-
const nativeID =
|
|
32265
|
+
const source = providerSource[string3(row.provider)];
|
|
32266
|
+
const nativeID = string3(row.native_id);
|
|
31931
32267
|
if (!source || row.strength !== "strong" || row.driver && row.driver !== row.provider || !nativeID || nativeID.length > 512) continue;
|
|
31932
|
-
const id2 =
|
|
32268
|
+
const id2 = string3(row.thread_id);
|
|
31933
32269
|
links.set(id2, [.../* @__PURE__ */ new Set([...links.get(id2) || [], identity(source, nativeID)])]);
|
|
31934
32270
|
}
|
|
31935
32271
|
}
|
|
31936
32272
|
return links;
|
|
31937
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
|
+
}
|
|
31938
32298
|
function discoverV2(db2, path, databaseRevision) {
|
|
31939
32299
|
if (!hasTable(db2, "orchestration_v2_projection_threads") || !hasTable(db2, "orchestration_v2_projection_turn_items")) throw new Error("Unsupported T3 Code database schema.");
|
|
31940
|
-
const
|
|
32300
|
+
const selected = db2.prepare(`SELECT thread_id, project_id, substr(title,1,300) AS title, default_provider, created_at, updated_at, archived_at,
|
|
31941
32301
|
CASE WHEN json_valid(payload_json) THEN substr(json_extract(payload_json,'$.worktreePath'),1,4096) END AS worktree_path,
|
|
31942
32302
|
CASE WHEN json_valid(payload_json) THEN substr(json_extract(payload_json,'$.modelSelection.model'),1,200) END AS model,
|
|
31943
32303
|
CASE WHEN json_valid(payload_json) THEN json_extract(payload_json,'$.lineage.parentThreadId') END AS parent_thread_id,
|
|
31944
32304
|
CASE WHEN json_valid(payload_json) THEN json_extract(payload_json,'$.lineage.relationshipToParent') END AS relationship,
|
|
31945
32305
|
json_valid(payload_json) AS valid_payload
|
|
31946
|
-
FROM orchestration_v2_projection_threads WHERE deleted_at IS NULL ORDER BY created_at, thread_id
|
|
31947
|
-
const
|
|
31948
|
-
const roots2 = projectRoots(db2, selected.map((row) =>
|
|
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)));
|
|
31949
32309
|
const counts = aggregates(db2, "orchestration_v2_projection_messages", ids);
|
|
31950
32310
|
const items = aggregates(db2, "orchestration_v2_projection_turn_items", ids);
|
|
31951
32311
|
const links = linkedSessions(db2, ids);
|
|
31952
32312
|
const sessions = [], projects = /* @__PURE__ */ new Map(), warnings = [];
|
|
31953
|
-
|
|
32313
|
+
const readPullRequests = pullRequests(db2, warnings);
|
|
31954
32314
|
let unreadableMetadata = 0;
|
|
31955
32315
|
for (const row of selected) {
|
|
31956
|
-
const nativeID =
|
|
32316
|
+
const nativeID = string3(row.thread_id), created = time2(row.created_at);
|
|
31957
32317
|
if (!nativeID || nativeID.length > 512 || !created) continue;
|
|
31958
32318
|
if (!row.valid_payload) unreadableMetadata++;
|
|
31959
|
-
const directory3 =
|
|
32319
|
+
const directory3 = string3(row.worktree_path) || roots2.get(string3(row.project_id)) || "";
|
|
31960
32320
|
const p = project(SOURCE, directory3);
|
|
31961
32321
|
projects.set(p.id, p);
|
|
31962
32322
|
const session = blankSession(SOURCE, nativeID, directory3);
|
|
31963
|
-
const parent2 =
|
|
32323
|
+
const parent2 = string3(row.parent_thread_id);
|
|
31964
32324
|
session.parentID = row.relationship === "subagent" && parent2 ? identity(SOURCE, parent2) : void 0;
|
|
32325
|
+
if (row.relationship === "subagent") session.origin = "automated";
|
|
31965
32326
|
session.forkID = row.relationship === "fork" && parent2 ? identity(SOURCE, parent2) : void 0;
|
|
31966
32327
|
Object.assign(session, {
|
|
31967
|
-
title:
|
|
32328
|
+
title: string3(row.title) || "T3 Code thread",
|
|
31968
32329
|
projectID: p.id,
|
|
31969
32330
|
created,
|
|
31970
32331
|
updated: time2(row.updated_at) || created,
|
|
31971
32332
|
archived: Boolean(row.archived_at),
|
|
31972
|
-
model:
|
|
31973
|
-
provider:
|
|
32333
|
+
model: string3(row.model) || "Unknown model",
|
|
32334
|
+
provider: string3(row.default_provider),
|
|
31974
32335
|
agent: "T3 Code",
|
|
31975
32336
|
linkedSessionIDs: links.get(nativeID) || []
|
|
31976
32337
|
});
|
|
31977
|
-
const
|
|
31978
|
-
|
|
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" } });
|
|
31979
32342
|
}
|
|
31980
32343
|
if (unreadableMetadata) warnings.push(`${unreadableMetadata} T3 Code threads had unreadable metadata; model or lineage may be unavailable.`);
|
|
31981
32344
|
return { sessions, projects: [...projects.values()], warnings };
|
|
31982
32345
|
}
|
|
31983
32346
|
function discoverV1(db2, path, databaseRevision) {
|
|
31984
32347
|
if (!hasTable(db2, "projection_threads") || !hasTable(db2, "projection_thread_messages")) throw new Error("Unsupported T3 Code database schema.");
|
|
31985
|
-
const
|
|
32348
|
+
const selected = db2.prepare(`SELECT thread_id, project_id, substr(title,1,300) AS title, substr(worktree_path,1,4096) AS worktree_path,
|
|
31986
32349
|
created_at, updated_at, archived_at,
|
|
31987
32350
|
CASE WHEN json_valid(model_selection_json) THEN substr(json_extract(model_selection_json,'$.model'),1,200) END AS model
|
|
31988
|
-
FROM projection_threads WHERE deleted_at IS NULL ORDER BY created_at, thread_id
|
|
31989
|
-
const
|
|
31990
|
-
const
|
|
31991
|
-
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)));
|
|
31992
32354
|
const sessions = [], projects = /* @__PURE__ */ new Map();
|
|
31993
32355
|
for (const row of selected) {
|
|
31994
|
-
const nativeID =
|
|
32356
|
+
const nativeID = string3(row.thread_id), created = time2(row.created_at);
|
|
31995
32357
|
if (!nativeID || nativeID.length > 512 || !created) continue;
|
|
31996
|
-
const directory3 =
|
|
32358
|
+
const directory3 = string3(row.worktree_path) || roots2.get(string3(row.project_id)) || "";
|
|
31997
32359
|
const p = project(SOURCE, directory3);
|
|
31998
32360
|
projects.set(p.id, p);
|
|
31999
32361
|
const session = blankSession(SOURCE, nativeID, directory3);
|
|
32000
32362
|
Object.assign(session, {
|
|
32001
|
-
title:
|
|
32363
|
+
title: string3(row.title) || "T3 Code thread",
|
|
32002
32364
|
projectID: p.id,
|
|
32003
32365
|
created,
|
|
32004
32366
|
updated: time2(row.updated_at) || created,
|
|
32005
32367
|
archived: Boolean(row.archived_at),
|
|
32006
|
-
model:
|
|
32368
|
+
model: string3(row.model) || "Unknown model",
|
|
32007
32369
|
agent: "T3 Code"
|
|
32008
32370
|
});
|
|
32009
32371
|
sessions.push({ session, revision: digest([row.updated_at, counts.get(nativeID)]), locator: { path, databaseRevision, threadID: nativeID, format: "v1" } });
|
|
32010
32372
|
}
|
|
32011
32373
|
const warnings = ["Legacy T3 Code V1 stores text conversations but has limited event and provider-link coverage."];
|
|
32012
|
-
if (rows2.length > MAX_THREADS) warnings.push(`T3 Code discovery is limited to ${MAX_THREADS.toLocaleString()} threads.`);
|
|
32013
32374
|
return { sessions, projects: [...projects.values()], warnings };
|
|
32014
32375
|
}
|
|
32015
32376
|
function v2Message(row, directory3) {
|
|
32016
|
-
const parsed = parsedObject(row.payload_json), item = parsed || {}, type =
|
|
32377
|
+
const parsed = parsedObject(row.payload_json), item = parsed || {}, type = string3(row.type), id2 = string3(row.turn_item_id);
|
|
32017
32378
|
const role = type === "user_message" ? "user" : type === "assistant_message" ? "assistant" : type === "reasoning" ? "assistant" : "tool";
|
|
32018
32379
|
const message2 = blankMessage(`item:${id2}`, time2(item.startedAt || item.createdAt), role);
|
|
32019
|
-
|
|
32020
|
-
|
|
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 = {
|
|
32021
32384
|
nativeID: id2,
|
|
32022
32385
|
nativeType: type,
|
|
32023
|
-
parentID:
|
|
32386
|
+
parentID: string3(item.parentItemId) || void 0,
|
|
32024
32387
|
status: status(row.status),
|
|
32025
32388
|
endTime: time2(item.completedAt) || null,
|
|
32026
32389
|
timeSource: recorded ? "recorded" : "unknown"
|
|
32027
32390
|
};
|
|
32028
32391
|
if (!parsed) {
|
|
32029
32392
|
message2.partial = true;
|
|
32030
|
-
message2.events = [eventFor(message2, id2, "event", name, "Oversized or unreadable T3 item omitted.", { ...
|
|
32393
|
+
message2.events = [eventFor(message2, id2, "event", name, "Oversized or unreadable T3 item omitted.", { ...fields3, partial: true })];
|
|
32031
32394
|
return message2;
|
|
32032
32395
|
}
|
|
32033
32396
|
if (type === "user_message" || type === "assistant_message") {
|
|
32034
|
-
const body2 =
|
|
32397
|
+
const body2 = string3(item.text);
|
|
32035
32398
|
if (body2) addText(message2, body2, role === "user" ? "You" : "Assistant");
|
|
32036
|
-
message2.events = [{ ...messageEvent(message2, body2, id2), ...
|
|
32399
|
+
message2.events = [{ ...messageEvent(message2, body2, id2), ...fields3 }];
|
|
32037
32400
|
if (Array.isArray(item.attachments) && item.attachments.length) message2.partial = true;
|
|
32038
32401
|
return message2;
|
|
32039
32402
|
}
|
|
32040
32403
|
if (type === "reasoning") {
|
|
32041
|
-
message2.events = [eventFor(message2, id2, "reasoning", "Recorded reasoning",
|
|
32404
|
+
message2.events = [eventFor(message2, id2, "reasoning", "Recorded reasoning", string3(item.text), fields3)];
|
|
32042
32405
|
return message2;
|
|
32043
32406
|
}
|
|
32044
32407
|
if (type === "file_change") {
|
|
32045
|
-
const file =
|
|
32408
|
+
const file = string3(item.fileName), completed = status(row.status) === "completed";
|
|
32046
32409
|
const native = item.nativeItemRef;
|
|
32047
32410
|
if (native?.driver === "opencode" && openCodeEditTools.has(file.toLowerCase())) {
|
|
32048
32411
|
message2.tools.push(file);
|
|
32049
|
-
const kind2 = completed ||
|
|
32050
|
-
message2.events = [eventFor(message2, id2, kind2, file, "", { ...
|
|
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 })];
|
|
32051
32414
|
return message2;
|
|
32052
32415
|
}
|
|
32053
32416
|
if (file && completed) message2.files.push({ path: isAbsolute2(file) ? file : join11(directory3, file), source: "file change", steps: 1 });
|
|
32054
|
-
message2.events = [eventFor(message2, id2, "file_change", file || name, "",
|
|
32417
|
+
message2.events = [eventFor(message2, id2, "file_change", file || name, "", fields3)];
|
|
32055
32418
|
return message2;
|
|
32056
32419
|
}
|
|
32057
32420
|
if (["command_execution", "dynamic_tool", "file_search", "web_search"].includes(type)) {
|
|
32058
32421
|
const input = eventText(item.input ?? item.pattern ?? item.patterns, 32e3);
|
|
32059
32422
|
const output2 = eventText(item.output ?? item.results, 64e3);
|
|
32060
|
-
const kind2 =
|
|
32423
|
+
const kind2 = fields3.status === "completed" || fields3.status === "failed" ? "tool_result" : "tool_call";
|
|
32061
32424
|
message2.tools.push(name);
|
|
32062
32425
|
if (input) addText(message2, input, "Tool");
|
|
32063
32426
|
if (output2) addText(message2, output2, "Tool");
|
|
32064
32427
|
const native = item.nativeItemRef;
|
|
32065
|
-
message2.events = [eventFor(message2, id2, kind2, name, "", { ...
|
|
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 })];
|
|
32066
32429
|
return message2;
|
|
32067
32430
|
}
|
|
32068
32431
|
const kind = type === "compaction" ? "compaction" : type === "error" ? "error" : "event";
|
|
32069
|
-
message2.events = [eventFor(message2, id2, kind, name,
|
|
32432
|
+
message2.events = [eventFor(message2, id2, kind, name, string3(item.text), fields3)];
|
|
32070
32433
|
return message2;
|
|
32071
32434
|
}
|
|
32072
32435
|
function readV2(db2, candidate, cursor) {
|
|
@@ -32086,8 +32449,7 @@ function readV2(db2, candidate, cursor) {
|
|
|
32086
32449
|
return {
|
|
32087
32450
|
messages: page.map((row) => v2Message(row, candidate.session.directory)),
|
|
32088
32451
|
cursor: rows2.length > PAGE && last ? `${last.ordinal}:${last.turn_item_id}` : void 0,
|
|
32089
|
-
partial: candidate.locator.metadataPartial === "1" || page.some((row) => !parsedObject(row.payload_json))
|
|
32090
|
-
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))
|
|
32091
32453
|
};
|
|
32092
32454
|
}
|
|
32093
32455
|
function readV1(db2, candidate, cursor) {
|
|
@@ -32099,9 +32461,9 @@ function readV1(db2, candidate, cursor) {
|
|
|
32099
32461
|
const messages = rows2.slice(0, PAGE).map((row) => {
|
|
32100
32462
|
const role = row.role === "user" ? "user" : row.role === "assistant" ? "assistant" : "system";
|
|
32101
32463
|
const message2 = blankMessage(`message:${row.message_id}`, time2(row.created_at), role);
|
|
32102
|
-
const body2 =
|
|
32464
|
+
const body2 = string3(row.text);
|
|
32103
32465
|
if (body2) addText(message2, body2, role === "user" ? "You" : "Assistant");
|
|
32104
|
-
message2.events = [{ ...messageEvent(message2, body2), nativeID:
|
|
32466
|
+
message2.events = [{ ...messageEvent(message2, body2), nativeID: string3(row.message_id), nativeType: "legacy-message" }];
|
|
32105
32467
|
message2.partial = row.text == null;
|
|
32106
32468
|
return message2;
|
|
32107
32469
|
});
|
|
@@ -32109,31 +32471,30 @@ function readV1(db2, candidate, cursor) {
|
|
|
32109
32471
|
messages,
|
|
32110
32472
|
cursor: rows2.length > PAGE ? String(offset + PAGE) : void 0,
|
|
32111
32473
|
partial: true,
|
|
32112
|
-
note: "Legacy T3 Code text
|
|
32474
|
+
note: "Legacy T3 Code: conversation text only."
|
|
32113
32475
|
};
|
|
32114
32476
|
}
|
|
32115
32477
|
var t3CodeAdapter = {
|
|
32116
32478
|
id: SOURCE,
|
|
32117
32479
|
name: "T3 Code",
|
|
32118
|
-
description: "Local T3
|
|
32480
|
+
description: "Local T3 threads and activity",
|
|
32119
32481
|
capabilities: { history: true, forks: true, children: true, files: true },
|
|
32120
32482
|
async detect() {
|
|
32121
32483
|
return Boolean(await databasePath2());
|
|
32122
32484
|
},
|
|
32123
32485
|
async discover() {
|
|
32124
32486
|
const path = await databasePath2();
|
|
32125
|
-
if (!path) return { sessions: [], projects: [], warnings: ["T3 Code database
|
|
32487
|
+
if (!path) return { sessions: [], projects: [], warnings: [], errors: ["T3 Code: History database unavailable."] };
|
|
32126
32488
|
for (let attempt = 0; ; attempt++) {
|
|
32127
|
-
const databaseRevision = sqliteRevision(path);
|
|
32128
32489
|
try {
|
|
32129
|
-
return
|
|
32490
|
+
return await withLargeSqliteSnapshot(path, (db2, databaseRevision) => hasTable(db2, "orchestration_v2_projection_threads") ? discoverV2(db2, path, databaseRevision) : discoverV1(db2, path, databaseRevision));
|
|
32130
32491
|
} catch (error) {
|
|
32131
32492
|
if (!(error instanceof SqliteSnapshotChangedError) || attempt >= 2) throw error;
|
|
32132
32493
|
}
|
|
32133
32494
|
}
|
|
32134
32495
|
},
|
|
32135
32496
|
async read(candidate, cursor) {
|
|
32136
|
-
return
|
|
32497
|
+
return withLargeSqliteSnapshot(candidate.locator.path, (db2) => candidate.locator.format === "v2" ? readV2(db2, candidate, cursor) : readV1(db2, candidate, cursor), candidate.locator.databaseRevision);
|
|
32137
32498
|
}
|
|
32138
32499
|
};
|
|
32139
32500
|
|
|
@@ -32200,6 +32561,8 @@ function cursorMessage(raw, fallbackID) {
|
|
|
32200
32561
|
const time4 = cursorTime(raw.timestamp) || cursorTime(body2.timestamp) || cursorTime(body2.createdAt) || (role === "user" && typeof firstText === "string" ? cursorEnvelopeTime(firstText) : 0);
|
|
32201
32562
|
const native = [raw.uuid, raw.id, body2.uuid, body2.id].find((id2) => typeof id2 === "string" && id2.length && id2.length <= 512);
|
|
32202
32563
|
const msg = blankMessage(native || fallbackID, time4, role);
|
|
32564
|
+
msg.metadata = messageMetadata(body2);
|
|
32565
|
+
if (role === "assistant") msg.usage = messageUsage(body2);
|
|
32203
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);
|
|
32204
32567
|
const kind = role === "user" ? "You" : role === "assistant" ? "Assistant" : "Tool";
|
|
32205
32568
|
const text2 = (value) => addText(msg, role === "user" && typeof value === "string" ? cursorUserText(value) : value, kind);
|
|
@@ -32290,7 +32653,7 @@ function metadata(db2) {
|
|
|
32290
32653
|
return value;
|
|
32291
32654
|
}
|
|
32292
32655
|
var cursorStoreMetadata = (path) => withStore(path, metadata);
|
|
32293
|
-
function
|
|
32656
|
+
function fields2(data) {
|
|
32294
32657
|
let at2 = 0;
|
|
32295
32658
|
const values = [];
|
|
32296
32659
|
const uint = () => {
|
|
@@ -32351,7 +32714,7 @@ function readCursorStore(path) {
|
|
|
32351
32714
|
bytes2 += data.length;
|
|
32352
32715
|
try {
|
|
32353
32716
|
if (item.leaf) {
|
|
32354
|
-
const json5 = data[0] === 123 ? data :
|
|
32717
|
+
const json5 = data[0] === 123 ? data : fields2(data).find((v3) => v3.field === 4)?.data;
|
|
32355
32718
|
if (!json5) {
|
|
32356
32719
|
partial = true;
|
|
32357
32720
|
continue;
|
|
@@ -32375,7 +32738,7 @@ function readCursorStore(path) {
|
|
|
32375
32738
|
partial ||= Boolean(msg.partial);
|
|
32376
32739
|
messages.push(msg);
|
|
32377
32740
|
} else {
|
|
32378
|
-
const refs =
|
|
32741
|
+
const refs = fields2(data).filter((v3) => v3.field === 1 || v3.field === 2);
|
|
32379
32742
|
if (!refs.length) partial = true;
|
|
32380
32743
|
if (stack.length + refs.length > MAX_NODES) {
|
|
32381
32744
|
partial = true;
|
|
@@ -32393,7 +32756,7 @@ function readCursorStore(path) {
|
|
|
32393
32756
|
partial = true;
|
|
32394
32757
|
}
|
|
32395
32758
|
}
|
|
32396
|
-
if (!messages.length) throw new Error("Cursor store has no readable conversation
|
|
32759
|
+
if (!messages.length) throw new Error("Cursor store has no readable conversation.");
|
|
32397
32760
|
return { meta, messages, partial };
|
|
32398
32761
|
});
|
|
32399
32762
|
}
|
|
@@ -32406,7 +32769,7 @@ var MAX_BUBBLE = 8e6;
|
|
|
32406
32769
|
var MAX_MESSAGES = 5e4;
|
|
32407
32770
|
var MAX_BYTES4 = 64e6;
|
|
32408
32771
|
function decode(value) {
|
|
32409
|
-
return
|
|
32772
|
+
return object3(JSON.parse(typeof value === "string" ? value : value instanceof Uint8Array ? Buffer.from(value).toString("utf8") : "{}"));
|
|
32410
32773
|
}
|
|
32411
32774
|
function directory2(raw) {
|
|
32412
32775
|
const value = text(raw.workspaceIdentifier?.uri?.path) || text(raw.workspaceIdentifier?.uri) || text(raw.cwd);
|
|
@@ -32449,7 +32812,7 @@ function discoverComposers(path, workspace = "") {
|
|
|
32449
32812
|
failed++;
|
|
32450
32813
|
}
|
|
32451
32814
|
}
|
|
32452
|
-
if (failed) warnings.push(
|
|
32815
|
+
if (failed) warnings.push(`Cursor Composer: Skipped ${failed} unreadable or oversized ${failed === 1 ? "record" : "records"}.`);
|
|
32453
32816
|
}
|
|
32454
32817
|
const parents = /* @__PURE__ */ new Map();
|
|
32455
32818
|
for (const c of sessions) for (const id2 of JSON.parse(c.locator.children)) {
|
|
@@ -32459,7 +32822,10 @@ function discoverComposers(path, workspace = "") {
|
|
|
32459
32822
|
}
|
|
32460
32823
|
for (const c of sessions) {
|
|
32461
32824
|
const found = parents.get(c.session.nativeID);
|
|
32462
|
-
if (found?.size === 1 && !found.has(c.session.nativeID))
|
|
32825
|
+
if (found?.size === 1 && !found.has(c.session.nativeID)) {
|
|
32826
|
+
c.session.parentID = identity("cursor", [...found][0]);
|
|
32827
|
+
c.session.origin = "automated";
|
|
32828
|
+
}
|
|
32463
32829
|
c.session.projectID = project("cursor", c.session.directory).id;
|
|
32464
32830
|
c.revision = digest([c.revision, c.session.directory, c.session.parentID]);
|
|
32465
32831
|
}
|
|
@@ -32486,7 +32852,7 @@ function readComposer(candidate) {
|
|
|
32486
32852
|
const id2 = text(header.bubbleId);
|
|
32487
32853
|
const stored = id2 ? get.get(`bubbleId:${nativeID}:${id2}`, MAX_BUBBLE) : void 0;
|
|
32488
32854
|
if (stored) bytes2 += typeof stored.value === "string" ? Buffer.byteLength(stored.value) : stored.value.byteLength;
|
|
32489
|
-
const raw = stored ? { ...header, ...decode(stored.value) } : { ...header, ...
|
|
32855
|
+
const raw = stored ? { ...header, ...decode(stored.value) } : { ...header, ...object3(data.conversationMap?.[id2]) };
|
|
32490
32856
|
if (![1, 2].includes(raw.type)) {
|
|
32491
32857
|
partial = true;
|
|
32492
32858
|
continue;
|
|
@@ -32503,8 +32869,8 @@ function readComposer(candidate) {
|
|
|
32503
32869
|
partial = true;
|
|
32504
32870
|
}
|
|
32505
32871
|
}
|
|
32506
|
-
if (!messages.length) throw new Error("Composer has no readable
|
|
32507
|
-
return { messages, partial: true, note:
|
|
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." };
|
|
32508
32874
|
}, snapshot2);
|
|
32509
32875
|
}
|
|
32510
32876
|
|
|
@@ -32551,7 +32917,7 @@ async function entries(path, warnings) {
|
|
|
32551
32917
|
}
|
|
32552
32918
|
}
|
|
32553
32919
|
} catch (error) {
|
|
32554
|
-
if (error.code !== "ENOENT") warnings.push("
|
|
32920
|
+
if (error.code !== "ENOENT") warnings.push("Cursor: Could not list a history directory.");
|
|
32555
32921
|
}
|
|
32556
32922
|
return result.sort((a, b) => a.name.localeCompare(b.name));
|
|
32557
32923
|
}
|
|
@@ -32579,7 +32945,7 @@ function createCursorAdapter(options = {}) {
|
|
|
32579
32945
|
return {
|
|
32580
32946
|
id: "cursor",
|
|
32581
32947
|
name: "Cursor",
|
|
32582
|
-
description: "Local IDE
|
|
32948
|
+
description: "Local IDE, Composer, and CLI sessions",
|
|
32583
32949
|
capabilities: { history: true, forks: false, children: true, files: false },
|
|
32584
32950
|
async detect() {
|
|
32585
32951
|
if (await fileStats(join13(editor(), "User/globalStorage/state.vscdb"))) return true;
|
|
@@ -32595,7 +32961,7 @@ function createCursorAdapter(options = {}) {
|
|
|
32595
32961
|
return false;
|
|
32596
32962
|
},
|
|
32597
32963
|
async discover() {
|
|
32598
|
-
const warnings = [], found = /* @__PURE__ */ new Map(), blocked = /* @__PURE__ */ new Set();
|
|
32964
|
+
const warnings = [], errors = [], found = /* @__PURE__ */ new Map(), blocked = /* @__PURE__ */ new Set();
|
|
32599
32965
|
const workspaceStores = await workspacePaths(editor(), warnings);
|
|
32600
32966
|
const paths2 = [...new Set([...workspaceStores.values()].filter(Boolean))];
|
|
32601
32967
|
const legacyStores = new Map([[join13(editor(), "User/globalStorage/state.vscdb"), ""], ...workspaceStores]);
|
|
@@ -32612,8 +32978,8 @@ function createCursorAdapter(options = {}) {
|
|
|
32612
32978
|
selected.revision = digest([selected.revision, selected.session.directory]);
|
|
32613
32979
|
found.set(candidate.session.id, selected);
|
|
32614
32980
|
}
|
|
32615
|
-
} catch {
|
|
32616
|
-
|
|
32981
|
+
} catch (error) {
|
|
32982
|
+
errors.push(`Cursor Composer: ${error instanceof SqliteSnapshotFileError ? error.message : "Could not read a history database."}`);
|
|
32617
32983
|
}
|
|
32618
32984
|
}
|
|
32619
32985
|
const composers = new Map(found);
|
|
@@ -32621,7 +32987,7 @@ function createCursorAdapter(options = {}) {
|
|
|
32621
32987
|
const matches = paths2.filter((path) => encode(path) === key);
|
|
32622
32988
|
return matches.length === 1 ? matches[0] : "";
|
|
32623
32989
|
};
|
|
32624
|
-
let unreadable = 0, legacy = 0, scanned = 0;
|
|
32990
|
+
let unreadable = 0, unreadableStores = 0, legacy = 0, scanned = 0;
|
|
32625
32991
|
const add = async (path, id2, kind, directory3, parent2 = "", workspaceHash = "") => {
|
|
32626
32992
|
if (!validID(id2) || ++scanned > LIMIT) return;
|
|
32627
32993
|
try {
|
|
@@ -32637,7 +33003,10 @@ function createCursorAdapter(options = {}) {
|
|
|
32637
33003
|
if (kind !== "transcript" && !meta.latestRootBlobId) return;
|
|
32638
33004
|
const session = blankSession("cursor", native, cwd(meta.cwd) || cwd(extra2.cwd) || directory3);
|
|
32639
33005
|
session.agent = kind === "cli" ? "Cursor Agent" : kind === "acp" ? "Cursor ACP" : parent2 ? "Cursor subagent" : "Cursor IDE";
|
|
32640
|
-
if (parent2)
|
|
33006
|
+
if (parent2) {
|
|
33007
|
+
session.parentID = identity("cursor", parent2);
|
|
33008
|
+
session.origin = "automated";
|
|
33009
|
+
}
|
|
32641
33010
|
session.title = typeof meta.name === "string" && meta.name.trim() ? meta.name : typeof extra2.title === "string" && extra2.title.trim() ? extra2.title : "Cursor session";
|
|
32642
33011
|
session.title = session.title.slice(0, 300);
|
|
32643
33012
|
session.created = cursorTime(meta.createdAt) || cursorTime(extra2.createdAtMs);
|
|
@@ -32664,7 +33033,7 @@ function createCursorAdapter(options = {}) {
|
|
|
32664
33033
|
}
|
|
32665
33034
|
if (!session.created) {
|
|
32666
33035
|
session.created = stats.birthtimeMs > 0 ? stats.birthtimeMs : stats.mtimeMs;
|
|
32667
|
-
locator.timeNote = "Session
|
|
33036
|
+
locator.timeNote = "Session start estimated from file time.";
|
|
32668
33037
|
}
|
|
32669
33038
|
if (!session.directory) locator.directoryNote = "Working directory is unknown; choose one when continuing.";
|
|
32670
33039
|
session.projectID = project("cursor", session.directory).id;
|
|
@@ -32684,8 +33053,10 @@ function createCursorAdapter(options = {}) {
|
|
|
32684
33053
|
}
|
|
32685
33054
|
const candidate = { session, locator, revision: digest([5, kind, path, before, session.created, session.directory, session.parentID]) };
|
|
32686
33055
|
if (!previous || rank(candidate) > rank(previous) || rank(candidate) === rank(previous) && session.updated > previous.session.updated) found.set(session.id, candidate);
|
|
32687
|
-
} catch {
|
|
32688
|
-
|
|
33056
|
+
} catch (error) {
|
|
33057
|
+
if (error instanceof SqliteSnapshotFileError) errors.push(`Cursor: ${error.message}`);
|
|
33058
|
+
else if (kind !== "transcript") unreadableStores++;
|
|
33059
|
+
else unreadable++;
|
|
32689
33060
|
if (kind !== "transcript") blocked.add(identity("cursor", id2));
|
|
32690
33061
|
}
|
|
32691
33062
|
};
|
|
@@ -32725,14 +33096,14 @@ function createCursorAdapter(options = {}) {
|
|
|
32725
33096
|
if (scanned >= LIMIT) break;
|
|
32726
33097
|
}
|
|
32727
33098
|
if (scanned >= LIMIT) warnings.push("Cursor discovery limited to 20,000 history files.");
|
|
32728
|
-
if (unreadable) warnings.push(
|
|
32729
|
-
if (
|
|
32730
|
-
warnings.push(
|
|
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.`);
|
|
32731
33102
|
const sessions = [...found.values()].filter((c) => !blocked.has(c.session.id));
|
|
32732
33103
|
return { sessions, projects: [...new Map(sessions.map((c) => {
|
|
32733
33104
|
const p = project("cursor", c.session.directory);
|
|
32734
33105
|
return [p.id, p];
|
|
32735
|
-
})).values()], warnings: [...new Set(warnings)] };
|
|
33106
|
+
})).values()], warnings: [...new Set(warnings)], errors: [...new Set(errors)] };
|
|
32736
33107
|
},
|
|
32737
33108
|
async read(candidate, cursor) {
|
|
32738
33109
|
const { locator } = candidate;
|
|
@@ -32744,17 +33115,12 @@ function createCursorAdapter(options = {}) {
|
|
|
32744
33115
|
if (await snapshot(locator) !== locator.snapshot) throw new Error("Cursor session changed during import; re-import to capture the latest history.");
|
|
32745
33116
|
};
|
|
32746
33117
|
await verify();
|
|
32747
|
-
const
|
|
32748
|
-
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.",
|
|
32749
|
-
"No file snapshots or inferred edit evidence. Missing message timestamps stay unknown.",
|
|
32750
|
-
locator.timeNote,
|
|
32751
|
-
locator.directoryNote
|
|
32752
|
-
].filter(Boolean).join(" ");
|
|
33118
|
+
const notes = [locator.kind === "transcript" ? "Tool results and earlier messages may be missing." : void 0, locator.timeNote, locator.directoryNote];
|
|
32753
33119
|
if (locator.kind !== "transcript") {
|
|
32754
33120
|
if (cursor) throw new Error("Invalid Cursor store cursor.");
|
|
32755
33121
|
const result = readCursorStore(locator.path);
|
|
32756
33122
|
await verify();
|
|
32757
|
-
return { messages: result.messages, partial: result.partial, note:
|
|
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 };
|
|
32758
33124
|
}
|
|
32759
33125
|
const offset = Number(cursor || 0);
|
|
32760
33126
|
if (!Number.isSafeInteger(offset) || offset < 0) throw new Error("Invalid Cursor transcript cursor.");
|
|
@@ -32765,8 +33131,8 @@ function createCursorAdapter(options = {}) {
|
|
|
32765
33131
|
return message2 && (message2.role !== "system" || row.value?.type === "turn_ended") ? [message2] : [];
|
|
32766
33132
|
});
|
|
32767
33133
|
await verify();
|
|
32768
|
-
if (!offset && page.cursor === void 0 && !messages.length) throw new Error("
|
|
32769
|
-
return { messages, cursor: page.cursor === void 0 ? void 0 : String(page.cursor), partial: true, note:
|
|
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(" ") };
|
|
32770
33136
|
}
|
|
32771
33137
|
};
|
|
32772
33138
|
}
|
|
@@ -32780,16 +33146,19 @@ function projectRootFile(path) {
|
|
|
32780
33146
|
return join14(parts.slice(0, parts.lastIndexOf("chats")).join(sep3), ".project_root");
|
|
32781
33147
|
}
|
|
32782
33148
|
function geminiConversation(contents, lines) {
|
|
32783
|
-
const parsed = lines ? jsonLines(contents) : { rows: [
|
|
33149
|
+
const parsed = lines ? jsonLines(contents) : { rows: [object3(json3(contents))], partial: false };
|
|
32784
33150
|
let metadata2 = {};
|
|
32785
33151
|
const messages = /* @__PURE__ */ new Map();
|
|
32786
33152
|
const patch = (p) => {
|
|
32787
33153
|
const existing = messages.get(text(p.id));
|
|
32788
33154
|
if (!existing) return;
|
|
32789
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];
|
|
32790
33157
|
for (const update of Array.isArray(p.toolCalls) ? p.toolCalls : []) {
|
|
32791
33158
|
const call = existing.toolCalls?.find((t) => t.id === update.id);
|
|
32792
|
-
if (call
|
|
33159
|
+
if (call) {
|
|
33160
|
+
for (const key of ["result", "status", "timestamp", "args", "name"]) if (key in update) call[key] = update[key];
|
|
33161
|
+
}
|
|
32793
33162
|
}
|
|
32794
33163
|
};
|
|
32795
33164
|
for (const row of parsed.rows) {
|
|
@@ -32797,9 +33166,9 @@ function geminiConversation(contents, lines) {
|
|
|
32797
33166
|
const ids = [...messages.keys()], index = ids.indexOf(row.$rewindTo);
|
|
32798
33167
|
for (const id2 of index < 0 ? ids : ids.slice(index)) messages.delete(id2);
|
|
32799
33168
|
} else if (row.$patch) {
|
|
32800
|
-
const p =
|
|
33169
|
+
const p = object3(row.$patch);
|
|
32801
33170
|
if (p.id) patch(p);
|
|
32802
|
-
for (const update of Array.isArray(p.updates) ? p.updates : []) patch(
|
|
33171
|
+
for (const update of Array.isArray(p.updates) ? p.updates : []) patch(object3(update));
|
|
32803
33172
|
for (const id2 of Array.isArray(p.removeIds) ? p.removeIds : []) messages.delete(id2);
|
|
32804
33173
|
for (const id2 of Array.isArray(p.orderIds) ? p.orderIds : []) {
|
|
32805
33174
|
const value = messages.get(id2);
|
|
@@ -32809,7 +33178,7 @@ function geminiConversation(contents, lines) {
|
|
|
32809
33178
|
}
|
|
32810
33179
|
}
|
|
32811
33180
|
} else if (row.$set || row.sessionId) {
|
|
32812
|
-
const update = row.$set ?
|
|
33181
|
+
const update = row.$set ? object3(row.$set) : row;
|
|
32813
33182
|
metadata2 = { ...metadata2, ...update };
|
|
32814
33183
|
if (Array.isArray(update.messages)) {
|
|
32815
33184
|
if (row.$set) messages.clear();
|
|
@@ -32834,6 +33203,8 @@ var geminiAdapter = localFileAdapter({
|
|
|
32834
33203
|
const directory3 = (files.get(projectRootFile(path)) || "").trim().slice(0, 4096);
|
|
32835
33204
|
const messages = records.map((raw, index) => {
|
|
32836
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);
|
|
32837
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" }));
|
|
32838
33209
|
for (const [i, call] of (Array.isArray(raw.toolCalls) ? raw.toolCalls : []).entries()) {
|
|
32839
33210
|
const id2 = text(call.id) || `tool:${i}`, name = text(call.name) || "Tool";
|
|
@@ -32854,8 +33225,7 @@ var geminiAdapter = localFileAdapter({
|
|
|
32854
33225
|
messages,
|
|
32855
33226
|
parent: parent2,
|
|
32856
33227
|
partial,
|
|
32857
|
-
session: { directory: directory3, created: time(meta.startTime), title: text(meta.summary), model: text([...records].reverse().find((r) => r.model)?.model) || "Unknown model", provider: "Google", nativeResume: !parent2 && Boolean(directory3) && !sourcePath("gemini") && !process.env.SESSIONGRAPH_GEMINI_HOME && !path.includes(`${sep3}.cache${sep3}`) }
|
|
32858
|
-
note: "Local Gemini chat records with rewind and patch reconstruction. Only explicit subagent directories form parent links; workspace paths come from the project-root marker. Binary content is omitted."
|
|
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}`) }
|
|
32859
33229
|
};
|
|
32860
33230
|
}
|
|
32861
33231
|
});
|
|
@@ -32878,7 +33248,9 @@ var qwenAdapter = localFileAdapter({
|
|
|
32878
33248
|
const messages = rows2.map((raw, index) => {
|
|
32879
33249
|
const id2 = text(raw.uuid) || `record:${index}`;
|
|
32880
33250
|
if (raw.message && !["agent_message", "agent_mention", "notification"].includes(raw.subtype)) {
|
|
32881
|
-
const message3 = googleMessage({ id: id2, timestamp: raw.timestamp, role: raw.type === "assistant" ? "assistant" : raw.type === "user" ? "user" : "tool", toolCallId: raw.toolCallResult?.callId, content:
|
|
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);
|
|
32882
33254
|
for (const event of message3.events || []) if (event.kind === "tool_result") {
|
|
32883
33255
|
event.status = raw.toolCallResult?.status === "success" ? "completed" : raw.toolCallResult?.status === "error" ? "failed" : "unknown";
|
|
32884
33256
|
event.nativeType = text(raw.toolCallResult?.status);
|
|
@@ -32898,8 +33270,7 @@ var qwenAdapter = localFileAdapter({
|
|
|
32898
33270
|
partial,
|
|
32899
33271
|
parent: text(parent2) || void 0,
|
|
32900
33272
|
fork: text(rows2.find((r) => r.forkedFrom?.sessionId)?.forkedFrom?.sessionId) || void 0,
|
|
32901
|
-
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 }
|
|
32902
|
-
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 }
|
|
32903
33274
|
};
|
|
32904
33275
|
}
|
|
32905
33276
|
});
|
|
@@ -32916,11 +33287,11 @@ var copilotAdapter = localFileAdapter({
|
|
|
32916
33287
|
match: (path) => /(?:^|\/)events\.jsonl$/.test(path),
|
|
32917
33288
|
parse(path, files) {
|
|
32918
33289
|
const { rows: rows2, partial } = jsonLines(files.get(path));
|
|
32919
|
-
const start = rows2.find((r) => r.type === "session.start"), meta =
|
|
33290
|
+
const start = rows2.find((r) => r.type === "session.start"), meta = object3(start?.data);
|
|
32920
33291
|
if (!text(meta.sessionId)) throw new Error("Unsupported Copilot event log.");
|
|
32921
33292
|
const toolNames = new Map(rows2.filter((r) => r.type === "tool.execution_start").map((r) => [r.data?.toolCallId, text(r.data?.toolName)]));
|
|
32922
33293
|
const messages = rows2.filter((r) => !r.ephemeral && !["assistant.message_delta", "assistant.reasoning_delta"].includes(r.type)).map((raw, index) => {
|
|
32923
|
-
const data =
|
|
33294
|
+
const data = object3(raw.data), kind = text(raw.type), human = kind === "user.message" && !data.isAutopilotContinuation && !data.source;
|
|
32924
33295
|
const message2 = blankMessage(text(raw.id) || `record:${index}`, time(raw.timestamp), human ? "user" : kind === "assistant.message" ? "assistant" : kind.startsWith("tool.") ? "tool" : "system");
|
|
32925
33296
|
if (["user.message", "assistant.message"].includes(kind)) {
|
|
32926
33297
|
const content = text(data.content);
|
|
@@ -32952,8 +33323,7 @@ var copilotAdapter = localFileAdapter({
|
|
|
32952
33323
|
messages,
|
|
32953
33324
|
partial,
|
|
32954
33325
|
parent: text(meta.detachedFromSpawningParentSessionId) || void 0,
|
|
32955
|
-
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 }
|
|
32956
|
-
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 }
|
|
32957
33327
|
};
|
|
32958
33328
|
}
|
|
32959
33329
|
});
|
|
@@ -32969,7 +33339,7 @@ function vscodeChatLog(content) {
|
|
|
32969
33339
|
for (const line of content.split("\n")) {
|
|
32970
33340
|
if (!line.trim()) continue;
|
|
32971
33341
|
if (++records > 5e4) throw new Error("Chat log exceeds the 50,000-operation limit.");
|
|
32972
|
-
const entry =
|
|
33342
|
+
const entry = object3(JSON.parse(line));
|
|
32973
33343
|
if (entry.kind === 0) {
|
|
32974
33344
|
if (records !== 1 || !entry.v || typeof entry.v !== "object" || Array.isArray(entry.v)) throw new Error("Invalid chat log initial state.");
|
|
32975
33345
|
state2 = entry.v;
|
|
@@ -33007,15 +33377,15 @@ function vscodeChatLog(content) {
|
|
|
33007
33377
|
}
|
|
33008
33378
|
|
|
33009
33379
|
// server/adapters/copilot-chat.ts
|
|
33010
|
-
function copilotChatRoots(platform = process.platform, home = homedir11(),
|
|
33380
|
+
function copilotChatRoots(platform = process.platform, home = homedir11(), env2 = process.env) {
|
|
33011
33381
|
const path = platform === "win32" ? win323 : posix2;
|
|
33012
|
-
const base = platform === "darwin" ? path.join(home, "Library", "Application Support") : platform === "win32" ?
|
|
33013
|
-
const override = sourcePath("copilot-chat") ||
|
|
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;
|
|
33014
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"))];
|
|
33015
33385
|
return users.flatMap((user) => [path.join(user, "workspaceStorage"), path.join(user, "globalStorage", "emptyWindowChatSessions")]);
|
|
33016
33386
|
}
|
|
33017
33387
|
function vscodeChatPath(value) {
|
|
33018
|
-
const raw =
|
|
33388
|
+
const raw = object3(value);
|
|
33019
33389
|
if (raw.scheme) {
|
|
33020
33390
|
if (raw.scheme !== "file") return `${text(raw.scheme)}://${text(raw.authority)}${text(raw.path)}`;
|
|
33021
33391
|
const path = text(raw.path);
|
|
@@ -33030,26 +33400,26 @@ function vscodeChatPath(value) {
|
|
|
33030
33400
|
return "";
|
|
33031
33401
|
}
|
|
33032
33402
|
}
|
|
33033
|
-
var markdown = (value) => typeof value === "string" ? value : text(
|
|
33403
|
+
var markdown = (value) => typeof value === "string" ? value : text(object3(value).value);
|
|
33034
33404
|
var recordedTime = (value) => ({ time: time(value) || null, timeSource: time(value) ? "recorded" : "unknown" });
|
|
33035
33405
|
function responsePart(message2, value, index) {
|
|
33036
|
-
const part =
|
|
33037
|
-
const
|
|
33406
|
+
const part = object3(value), kind = text(part.kind), id2 = `part:${index}`;
|
|
33407
|
+
const fields3 = { nativeType: kind || "markdown", nativeID: text(part.id) || void 0 };
|
|
33038
33408
|
if (typeof value === "string" || !kind && typeof part.value === "string" || kind === "markdownContent" || kind === "markdownVuln") {
|
|
33039
33409
|
const content = markdown(kind ? part.content : value);
|
|
33040
|
-
message2.events.push(eventFor(message2, id2, "message", "Assistant message", content,
|
|
33410
|
+
message2.events.push(eventFor(message2, id2, "message", "Assistant message", content, fields3));
|
|
33041
33411
|
addText(message2, content, "Assistant");
|
|
33042
33412
|
} else if (kind === "thinking") {
|
|
33043
33413
|
const content = Array.isArray(part.value) ? part.value.filter((v3) => typeof v3 === "string").join("\n") : markdown(part.value);
|
|
33044
|
-
message2.events.push(eventFor(message2, id2, "reasoning", "Recorded reasoning", content, { ...
|
|
33414
|
+
message2.events.push(eventFor(message2, id2, "reasoning", "Recorded reasoning", content, { ...fields3, ...recordedTime(part.reasoningStartedAt) }));
|
|
33045
33415
|
addText(message2, content, "Tool");
|
|
33046
33416
|
} else if (kind === "toolInvocationSerialized") {
|
|
33047
|
-
const data =
|
|
33417
|
+
const data = object3(part.toolSpecificData), command = object3(data.commandLine), details = object3(part.resultDetails);
|
|
33048
33418
|
const name = text(part.toolId) || "Tool", callID = text(part.toolCallId) || void 0;
|
|
33049
33419
|
const input = eventText(data.rawInput ?? command.userEdited ?? command.toolEdited ?? command.original ?? details.input);
|
|
33050
|
-
const denied = part.isConfirmed === false || [0, 5].includes(
|
|
33420
|
+
const denied = part.isConfirmed === false || [0, 5].includes(object3(part.isConfirmed).type);
|
|
33051
33421
|
const status2 = denied || part.resultError ? "failed" : part.isComplete === true ? "completed" : "unknown";
|
|
33052
|
-
const correlation = { ...
|
|
33422
|
+
const correlation = { ...fields3, callID, parentID: text(part.subAgentInvocationId) || void 0 };
|
|
33053
33423
|
message2.events.push(eventFor(message2, `${id2}:call`, "tool_call", name, markdown(part.invocationMessage), { ...correlation, ...recordedTime(part.startedAt), input, status: "unknown" }));
|
|
33054
33424
|
message2.tools.push(name);
|
|
33055
33425
|
addText(message2, input, "Tool");
|
|
@@ -33059,7 +33429,7 @@ function responsePart(message2, value, index) {
|
|
|
33059
33429
|
addText(message2, output2, "Tool");
|
|
33060
33430
|
} else message2.partial = true;
|
|
33061
33431
|
} else {
|
|
33062
|
-
message2.events.push(eventFor(message2, id2, "event", kind || "Unsupported chat content", eventText(part), { ...
|
|
33432
|
+
message2.events.push(eventFor(message2, id2, "event", kind || "Unsupported chat content", eventText(part), { ...fields3, partial: true }));
|
|
33063
33433
|
message2.partial = true;
|
|
33064
33434
|
}
|
|
33065
33435
|
}
|
|
@@ -33069,13 +33439,17 @@ function chatMessages(requests) {
|
|
|
33069
33439
|
const requestID = text(request.requestId) || `request:${index}`;
|
|
33070
33440
|
const injected = Boolean(request.isSystemInitiated || request.hiddenFromTranscript || request.requestHiddenFromTranscript);
|
|
33071
33441
|
const user = blankMessage(requestID, time(request.timestamp), injected ? "system" : "user");
|
|
33072
|
-
const content = typeof request.message === "string" ? request.message : text(
|
|
33442
|
+
const content = typeof request.message === "string" ? request.message : text(object3(request.message).text);
|
|
33073
33443
|
user.events = [eventFor(user, "message", injected ? "event" : "message", injected ? "Injected message" : "User message", content, { nativeID: requestID, ...recordedTime(request.timestamp) })];
|
|
33074
33444
|
addText(user, content, injected ? "Tool" : "You");
|
|
33075
33445
|
if (request.variableData?.variables?.length) user.partial = true;
|
|
33076
33446
|
const messages = [user];
|
|
33077
33447
|
if (request.response !== void 0 || request.result?.errorDetails || request.responseErrorDetails || request.editedFileEvents?.length) {
|
|
33078
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 });
|
|
33079
33453
|
assistant.events = [];
|
|
33080
33454
|
const parts = Array.isArray(request.response) ? request.response : request.response == null ? [] : [request.response];
|
|
33081
33455
|
if (parts.length > 200) assistant.partial = true;
|
|
@@ -33112,20 +33486,20 @@ var filesAdapter = localFileAdapter({
|
|
|
33112
33486
|
extras: (path) => [...basename6(dirname4(path)) === "chatSessions" ? [join17(dirname4(dirname4(path)), "workspace.json")] : [], ...path.endsWith(".json") ? [`${path}l`] : []],
|
|
33113
33487
|
parse(path, files) {
|
|
33114
33488
|
const log = path.endsWith(".jsonl") ? path : `${path}l`;
|
|
33115
|
-
const data = files.has(log) ? vscodeChatLog(files.get(log)) :
|
|
33489
|
+
const data = files.has(log) ? vscodeChatLog(files.get(log)) : object3(JSON.parse(files.get(path)));
|
|
33116
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.");
|
|
33117
33491
|
if (data.sessionId !== basename6(path).replace(/\.jsonl?$/, "")) throw new Error("VS Code chat identity mismatch.");
|
|
33118
33492
|
if (!data.requests.length) return;
|
|
33119
33493
|
if (data.requests.length > 25e3) throw new Error("Chat exceeds the 50,000-message limit.");
|
|
33120
33494
|
const workspacePath = join17(dirname4(dirname4(path)), "workspace.json");
|
|
33121
|
-
const workspace = files.has(workspacePath) ?
|
|
33495
|
+
const workspace = files.has(workspacePath) ? object3(JSON.parse(files.get(workspacePath))) : {};
|
|
33122
33496
|
const messages = chatMessages(data.requests);
|
|
33123
33497
|
const model = [...data.requests].reverse().find((r) => text(r.modelId));
|
|
33124
33498
|
return {
|
|
33125
33499
|
nativeID: data.sessionId,
|
|
33126
33500
|
messages,
|
|
33127
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" },
|
|
33128
|
-
note: "
|
|
33502
|
+
note: "Earlier messages may be missing."
|
|
33129
33503
|
};
|
|
33130
33504
|
}
|
|
33131
33505
|
});
|
|
@@ -33136,13 +33510,41 @@ var copilotChatAdapter = { ...filesAdapter, async detect() {
|
|
|
33136
33510
|
// server/adapters/extensions.ts
|
|
33137
33511
|
import { homedir as homedir12 } from "node:os";
|
|
33138
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
|
+
}
|
|
33139
33541
|
function editorTaskRoots(extension) {
|
|
33140
33542
|
const home = homedir12();
|
|
33141
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");
|
|
33142
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")));
|
|
33143
33545
|
}
|
|
33144
|
-
function taskAdapter(id2, name, extension,
|
|
33145
|
-
const home = () => sourcePath(id2) || process.env[
|
|
33546
|
+
function taskAdapter(id2, name, extension, env2) {
|
|
33547
|
+
const home = () => sourcePath(id2) || process.env[env2];
|
|
33146
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")] : []];
|
|
33147
33549
|
return localFileAdapter({
|
|
33148
33550
|
id: id2,
|
|
@@ -33151,17 +33553,31 @@ function taskAdapter(id2, name, extension, env) {
|
|
|
33151
33553
|
capabilities: { history: true, forks: id2 === "cline", children: true, files: true },
|
|
33152
33554
|
roots: roots2,
|
|
33153
33555
|
match: (path) => /^[^/]+\/api_conversation_history\.json$/.test(path) || id2 === "cline" && /^[^/]+\/[^/]+\.messages\.json$/.test(path),
|
|
33154
|
-
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)),
|
|
33155
33557
|
parse(path, files) {
|
|
33156
33558
|
const sdk = path.endsWith(".messages.json"), value = json3(files.get(path));
|
|
33157
|
-
const records = sdk ?
|
|
33559
|
+
const records = sdk ? object3(value).messages : value;
|
|
33158
33560
|
if (!Array.isArray(records) || sdk && !text(value.sessionId)) throw new Error("Unsupported task history.");
|
|
33159
|
-
const read3 = (name2) =>
|
|
33561
|
+
const read3 = (name2) => object3(files.has(join18(dirname5(path), name2)) ? json3(files.get(join18(dirname5(path), name2))) : void 0);
|
|
33160
33562
|
const history = read3("history_item.json"), info = read3("session.json"), task = read3("task_metadata.json");
|
|
33161
33563
|
const nativeID = sdk ? value.sessionId : basename7(dirname5(path));
|
|
33162
33564
|
if (history.id && history.id !== nativeID || info.session_id && info.session_id !== nativeID) throw new Error("Task metadata identity mismatch.");
|
|
33163
33565
|
const messages = records.map((raw, index) => {
|
|
33164
|
-
const row =
|
|
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
|
+
}
|
|
33165
33581
|
if (row.isSummary || row.isTruncationMarker || row.type === "reasoning") {
|
|
33166
33582
|
message2.role = "system";
|
|
33167
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" })];
|
|
@@ -33178,8 +33594,15 @@ function taskAdapter(id2, name, extension, env) {
|
|
|
33178
33594
|
partial: !sdk,
|
|
33179
33595
|
parent: text(history.parentTaskId || info.parent_session_id) || void 0,
|
|
33180
33596
|
fork: text(info.metadata?.fork?.forkedFromSessionId) || void 0,
|
|
33181
|
-
session: {
|
|
33182
|
-
|
|
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."
|
|
33183
33606
|
};
|
|
33184
33607
|
}
|
|
33185
33608
|
});
|
|
@@ -33197,22 +33620,36 @@ var continueAdapter = localFileAdapter({
|
|
|
33197
33620
|
extras: (path) => [join18(dirname5(path), "sessions.json")],
|
|
33198
33621
|
revisionExtras: false,
|
|
33199
33622
|
parse(path, files) {
|
|
33200
|
-
const value =
|
|
33623
|
+
const value = object3(json3(files.get(path)));
|
|
33201
33624
|
if (!text(value.sessionId) || !Array.isArray(value.history)) throw new Error("Unsupported Continue session.");
|
|
33202
33625
|
const indexPath = join18(dirname5(path), "sessions.json"), index = files.has(indexPath) ? json3(files.get(indexPath)) : [];
|
|
33203
|
-
const meta = Array.isArray(index) ?
|
|
33626
|
+
const meta = Array.isArray(index) ? object3(index.find((r) => r.sessionId === value.sessionId)) : {};
|
|
33204
33627
|
const messages = value.history.map((item, i) => {
|
|
33205
|
-
const row =
|
|
33628
|
+
const row = object3(item), raw = object3(row.message), message2 = conversationMessage(raw, `record:${i}`);
|
|
33206
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" }));
|
|
33207
33630
|
if (row.conversationSummary) message2.events.push(eventFor(message2, "summary", "compaction", "Conversation summary", text(row.conversationSummary)));
|
|
33208
33631
|
return message2;
|
|
33209
33632
|
});
|
|
33210
|
-
const usage =
|
|
33633
|
+
const usage = object3(value.usage);
|
|
33211
33634
|
return {
|
|
33212
33635
|
nativeID: value.sessionId,
|
|
33213
33636
|
messages,
|
|
33214
|
-
session: {
|
|
33215
|
-
|
|
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
|
+
}
|
|
33216
33653
|
};
|
|
33217
33654
|
}
|
|
33218
33655
|
});
|
|
@@ -33228,7 +33665,7 @@ var dataPath = (...parts) => join19(process.env.XDG_DATA_HOME || homePath(".loca
|
|
|
33228
33665
|
var configPath = (...parts) => join19(process.env.XDG_CONFIG_HOME || homePath(".config"), ...parts);
|
|
33229
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);
|
|
33230
33667
|
var tokscalePath = (...parts) => join19(process.env.TOKSCALE_CONFIG_DIR || (process.platform === "win32" ? appPath("tokscale") : configPath("tokscale")), ...parts);
|
|
33231
|
-
var envHome = (
|
|
33668
|
+
var envHome = (env2, fallback, ...parts) => join19(process.env[env2]?.trim() || homePath(fallback), ...parts);
|
|
33232
33669
|
var harnessRoots = (id2, defaults) => () => {
|
|
33233
33670
|
const override = sourcePath(id2) || process.env[`SESSIONGRAPH_${id2.replace(/-/g, "_").toUpperCase()}_HISTORY_DIR`]?.trim();
|
|
33234
33671
|
return override ? [override] : defaults();
|
|
@@ -33237,7 +33674,7 @@ var harnessRoots = (id2, defaults) => () => {
|
|
|
33237
33674
|
// server/adapters/harness-extra-formats.ts
|
|
33238
33675
|
import { basename as basename8, dirname as dirname6, join as join20 } from "node:path";
|
|
33239
33676
|
function kiroHistory(path, files) {
|
|
33240
|
-
const header =
|
|
33677
|
+
const header = object3(json3(files.get(path)));
|
|
33241
33678
|
const ide2 = basename8(path) === "session.json";
|
|
33242
33679
|
const nativeID = text(header.session_id || header.sessionId || header.id) || (ide2 ? basename8(dirname6(path)) : "");
|
|
33243
33680
|
if (!nativeID) throw new Error("Unsupported Kiro session header.");
|
|
@@ -33246,12 +33683,12 @@ function kiroHistory(path, files) {
|
|
|
33246
33683
|
const { rows: rows2 } = jsonLines(files.get(side));
|
|
33247
33684
|
const messages = rows2.flatMap((r, i) => {
|
|
33248
33685
|
if (ide2) {
|
|
33249
|
-
const p =
|
|
33686
|
+
const p = object3(r.payload || r);
|
|
33250
33687
|
const role2 = p.type === "human" ? "user" : p.type === "ai" ? "assistant" : p.role || p.type;
|
|
33251
33688
|
const m3 = message({ ...p, role: role2 }, text(p.id) || `message:${i}`, r.timestamp);
|
|
33252
33689
|
return m3 ? [m3] : [recordEvent(r, `event:${i}`, text(p.type) || "Kiro event", r.timestamp, p.text)];
|
|
33253
33690
|
}
|
|
33254
|
-
const data =
|
|
33691
|
+
const data = object3(r.data), role = r.kind === "Prompt" ? "user" : r.kind === "AssistantMessage" ? "assistant" : r.kind === "ToolResults" ? "tool" : "";
|
|
33255
33692
|
if (!role) return [];
|
|
33256
33693
|
const content = Array.isArray(data.content) ? data.content.map((p) => p.kind === "text" ? { type: "text", text: p.data } : { type: "unsupported" }) : void 0;
|
|
33257
33694
|
const m = message({ role, content }, text(data.message_id) || `message:${i}`, seconds(data.meta?.timestamp));
|
|
@@ -33263,7 +33700,7 @@ function kiroHistory(path, files) {
|
|
|
33263
33700
|
messages,
|
|
33264
33701
|
partial: true,
|
|
33265
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" },
|
|
33266
|
-
note: "
|
|
33703
|
+
note: "Earlier messages and some tool details may be missing."
|
|
33267
33704
|
};
|
|
33268
33705
|
}
|
|
33269
33706
|
function muxHistory(path, files) {
|
|
@@ -33285,22 +33722,31 @@ function muxHistory(path, files) {
|
|
|
33285
33722
|
return m ? [m] : [];
|
|
33286
33723
|
});
|
|
33287
33724
|
if (!messages.length) throw new Error("No readable Mux conversation.");
|
|
33288
|
-
|
|
33289
|
-
|
|
33290
|
-
|
|
33291
|
-
|
|
33292
|
-
|
|
33293
|
-
|
|
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)) } };
|
|
33294
33742
|
}
|
|
33295
33743
|
function devinDesktopHistory(path, files) {
|
|
33296
33744
|
const { rows: rows2 } = jsonLines(files.get(path));
|
|
33297
33745
|
const normalized = rows2.flatMap((r) => {
|
|
33298
|
-
const n =
|
|
33746
|
+
const n = object3(r.notification);
|
|
33299
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 }] : [];
|
|
33300
33748
|
});
|
|
33301
|
-
|
|
33302
|
-
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.";
|
|
33303
|
-
return history;
|
|
33749
|
+
return acpHistory(path, normalized.map((r) => JSON.stringify(r)).join("\n"));
|
|
33304
33750
|
}
|
|
33305
33751
|
|
|
33306
33752
|
// server/adapters/harness-files.ts
|
|
@@ -33330,7 +33776,7 @@ function kimiHistory(path, files) {
|
|
|
33330
33776
|
messages,
|
|
33331
33777
|
partial: true,
|
|
33332
33778
|
session: { created: seconds(wireRows.find((r) => r.timestamp)?.timestamp) },
|
|
33333
|
-
note: "
|
|
33779
|
+
note: "Message times unavailable. Earlier messages may be missing."
|
|
33334
33780
|
};
|
|
33335
33781
|
}
|
|
33336
33782
|
function museHistory(path, files) {
|
|
@@ -33340,55 +33786,65 @@ function museHistory(path, files) {
|
|
|
33340
33786
|
if (!meta || ids.size > 1) throw new Error("Unsupported Muse stream.");
|
|
33341
33787
|
const nativeID = [...ids][0] || basename9(dirname7(path));
|
|
33342
33788
|
const messages = rows2.flatMap((r, i) => {
|
|
33343
|
-
const event =
|
|
33789
|
+
const event = object3(r.payload?.event), body2 = object3(event.message);
|
|
33344
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);
|
|
33345
33791
|
const m = message(body2, nativeText(r.sequence) || `record:${i}`, at2);
|
|
33346
33792
|
if (m) return [m];
|
|
33347
33793
|
return text(event.kind) ? [recordEvent(r, nativeText(r.sequence) || `record:${i}`, event.kind, at2, event.text)] : [];
|
|
33348
33794
|
});
|
|
33349
|
-
return {
|
|
33350
|
-
nativeID,
|
|
33351
|
-
messages,
|
|
33352
|
-
partial: true,
|
|
33353
|
-
session: { directory: text(meta.payload?.record?.workspace_root), model: text(meta.payload?.record?.model_id) || "Unknown model", provider: text(meta.payload?.record?.provider_id) },
|
|
33354
|
-
note: "Muse runtime session events and recognized message payloads. Unsupported event content remains partial; no session ancestry is inferred from timestamps."
|
|
33355
|
-
};
|
|
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) } };
|
|
33356
33796
|
}
|
|
33357
33797
|
function junieHistory(path, files) {
|
|
33358
33798
|
const { rows: rows2 } = jsonLines(files.get(path));
|
|
33359
33799
|
const messages = rows2.flatMap((r, i) => {
|
|
33360
|
-
const e10 =
|
|
33800
|
+
const e10 = object3(r.event?.agentEvent || r.event), kind = text(e10.kind);
|
|
33361
33801
|
if (!kind || /State|Snapshot/.test(kind)) return [];
|
|
33362
33802
|
return [recordEvent(r, text(r.id) || `event:${i}`, kind, r.timestampMs, e10.text ?? e10.prompt ?? e10.message)];
|
|
33363
33803
|
});
|
|
33364
33804
|
if (!messages.length) throw new Error("No supported Junie events.");
|
|
33365
|
-
return { nativeID: basename9(dirname7(path)), messages, partial: true, note: "
|
|
33805
|
+
return { nativeID: basename9(dirname7(path)), messages, partial: true, note: "Recorded events only." };
|
|
33366
33806
|
}
|
|
33367
33807
|
function augmentHistory(path, files) {
|
|
33368
|
-
const r =
|
|
33808
|
+
const r = object3(json3(files.get(path)));
|
|
33369
33809
|
if (!text(r.sessionId) || !Array.isArray(r.chatHistory)) throw new Error("Unsupported Augment session.");
|
|
33370
33810
|
const messages = r.chatHistory.flatMap((turn, i) => {
|
|
33371
|
-
const exchange =
|
|
33811
|
+
const exchange = object3(turn.exchange), id2 = nativeText(turn.sequenceId) || `turn:${i}`;
|
|
33372
33812
|
return [recordEvent(turn, id2, turn.completed === true ? "Completed exchange" : "Incomplete exchange", turn.finishedAt, exchange.response_text)];
|
|
33373
33813
|
});
|
|
33374
|
-
return { nativeID: r.sessionId, messages, partial: true, session: { title: text(r.title), created: time(r.created), model: text(r.agentState?.modelId) || "Unknown model" }, note: "
|
|
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." };
|
|
33375
33815
|
}
|
|
33376
33816
|
function fxHistory(path, files) {
|
|
33377
|
-
const usage =
|
|
33817
|
+
const usage = object3(json3(files.get(path))), meta = sidecar2(files, join21(dirname7(path), "session.json"));
|
|
33378
33818
|
const id2 = text(usage.session_id) || text(meta.id);
|
|
33379
33819
|
if (!id2 || !usage.snapshot || meta.id && meta.id !== id2) throw new Error("Unsupported Fx session metadata.");
|
|
33820
|
+
const snapshot2 = object3(usage.snapshot);
|
|
33380
33821
|
return {
|
|
33381
33822
|
nativeID: id2,
|
|
33382
33823
|
messages: [],
|
|
33383
33824
|
partial: true,
|
|
33384
|
-
session: {
|
|
33385
|
-
|
|
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."
|
|
33386
33842
|
};
|
|
33387
33843
|
}
|
|
33388
33844
|
var definitions = [
|
|
33389
33845
|
...piSources,
|
|
33390
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 },
|
|
33391
|
-
{ 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 },
|
|
33392
33848
|
{ id: "devin-desktop", name: "Devin Desktop", roots: () => [appPath("Devin/User/acp-events")], match: (p) => /\.(ndjson|jsonl)$/.test(p), parse: devinDesktopHistory },
|
|
33393
33849
|
{ id: "openclaw", name: "OpenClaw", roots: openclawRoots, match: (p) => /(?:^|\/)sessions\/.*\.jsonl(?:\.[\w.-]+)?$/.test(p) || /session-sqlite-import-archive\/.*\.jsonl\./.test(p), parse: piParse },
|
|
33394
33850
|
{ id: "amp", name: "Amp", roots: () => [dataPath("amp/threads"), tokscalePath("amp-cache/threads")], match: (p) => p.endsWith(".json"), parse: ampHistory },
|
|
@@ -33414,27 +33870,27 @@ var definitions = [
|
|
|
33414
33870
|
{ id: "muse", name: "Muse Code", roots: () => [dataPath("muse/sessions")], match: (p) => p.endsWith("/session.jsonl"), parse: museHistory },
|
|
33415
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" },
|
|
33416
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" },
|
|
33417
|
-
{ 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: "
|
|
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" },
|
|
33418
33874
|
{ id: "minimax-code", name: "MiniMax Code", roots: () => [join21(process.env.TOKSCALE_HEADLESS_DIR || tokscalePath("headless"), "mcode")], parse(p, f) {
|
|
33419
33875
|
const value = f.get(p), { rows: rows2 } = jsonLines(value), ids = new Set(rows2.map((r) => text(r.sessionId)).filter(Boolean));
|
|
33420
33876
|
if (ids.size !== 1) throw new Error("Headless capture needs one explicit session identity.");
|
|
33421
33877
|
const messages = rows2.flatMap((r, i) => {
|
|
33422
|
-
const m = message(
|
|
33878
|
+
const m = message(object3(r.message), text(r.message?.id) || `record:${i}`);
|
|
33423
33879
|
return m ? [m] : [];
|
|
33424
33880
|
});
|
|
33425
|
-
return { nativeID: [...ids][0], messages, partial: true, note: "
|
|
33881
|
+
return { nativeID: [...ids][0], messages, partial: true, note: "Captured messages only; prompts may be missing." };
|
|
33426
33882
|
} },
|
|
33427
33883
|
{ id: "opencodereview", name: "OpenCodeReview", roots: () => [homePath(".opencodereview/sessions")], parse(p, f) {
|
|
33428
33884
|
const { rows: rows2 } = jsonLines(f.get(p)), header = rows2.find((r) => r.type === "session_start");
|
|
33429
33885
|
if (!header) throw new Error("Unsupported review session.");
|
|
33430
|
-
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: "
|
|
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." };
|
|
33431
33887
|
} }
|
|
33432
33888
|
];
|
|
33433
33889
|
var fileHarnessAdapters = definitions.map((source) => localFileAdapter({
|
|
33434
33890
|
...source,
|
|
33435
33891
|
roots: harnessRoots(source.id, source.roots),
|
|
33436
33892
|
match: source.match || jsonl,
|
|
33437
|
-
description: source.description || "Local
|
|
33893
|
+
description: source.description || "Local session transcripts",
|
|
33438
33894
|
capabilities: { history: source.history !== false, forks: false, children: false, files: false },
|
|
33439
33895
|
parse: source.parse || ((p, f) => envelopeHistory(p, f.get(p)))
|
|
33440
33896
|
}));
|
|
@@ -33451,6 +33907,29 @@ function hermesContent(value) {
|
|
|
33451
33907
|
}
|
|
33452
33908
|
}
|
|
33453
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
|
+
}
|
|
33454
33933
|
function dbPaths(id2, defaults, match2) {
|
|
33455
33934
|
return async () => {
|
|
33456
33935
|
const override = sourcePath(id2) || process.env[`SESSIONGRAPH_${id2.replace(/-/g, "_").toUpperCase()}_HISTORY_DIR`];
|
|
@@ -33473,14 +33952,23 @@ var hermes = {
|
|
|
33473
33952
|
paths: async () => (await historyFiles(harnessRoots("hermes", () => [envHome("HERMES_HOME", ".hermes")])(), (p) => p === "state.db" || /^profiles\/[^/]+\/state\.db$/.test(p))).files,
|
|
33474
33953
|
table: "sessions",
|
|
33475
33954
|
key: "id",
|
|
33476
|
-
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],
|
|
33477
33956
|
parse(db2, r) {
|
|
33478
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) => {
|
|
33479
33958
|
if (m._compressed_summary) return recordEvent(m, text(m.message_uid) || nativeText(m.id), "Context summary", seconds(m.timestamp), m.content);
|
|
33480
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));
|
|
33481
33960
|
});
|
|
33482
|
-
const h3 = sessionHistory({ ...r, created_at: seconds(r.started_at), updated_at: seconds(r.last_activity_at), provider: r.billing_provider }, messages
|
|
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);
|
|
33483
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";
|
|
33484
33972
|
h3.fork = text(optionalJSON(r.model_config)._branched_from) || void 0;
|
|
33485
33973
|
h3.session.archived = r.archived === 1;
|
|
33486
33974
|
return h3;
|
|
@@ -33492,14 +33980,41 @@ var goose = {
|
|
|
33492
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")),
|
|
33493
33981
|
table: "sessions",
|
|
33494
33982
|
key: "id",
|
|
33495
|
-
fields: [
|
|
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
|
+
],
|
|
33496
34002
|
parse(db2, r) {
|
|
33497
34003
|
const messages = rows(db2, "messages", ["id", "message_id", "role", "content_json", "created_timestamp"], ["session_id", r.id], "id").map((m) => {
|
|
33498
34004
|
const content = sqliteJSON(m.content_json);
|
|
33499
34005
|
return conversationMessage({ role: m.role, content, timestamp: millisOrSeconds(m.created_timestamp) }, text(m.message_id) || nativeText(m.id));
|
|
33500
34006
|
});
|
|
33501
|
-
const h3 = sessionHistory({ ...r, name: r.name || r.description, model: optionalJSON(r.model_config_json).model_name }, messages
|
|
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);
|
|
33502
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";
|
|
33503
34018
|
h3.session.archived = Boolean(r.archived_at);
|
|
33504
34019
|
return h3;
|
|
33505
34020
|
}
|
|
@@ -33514,12 +34029,16 @@ var openclaw = {
|
|
|
33514
34029
|
parse(db2, r) {
|
|
33515
34030
|
const events = rows(db2, "transcript_events", ["seq", "event_json", "event_zstd"], ["session_id", r.session_id], "seq");
|
|
33516
34031
|
const messages = events.flatMap((e10) => {
|
|
33517
|
-
const raw =
|
|
33518
|
-
if (raw.type !== "message")
|
|
33519
|
-
|
|
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);
|
|
33520
34039
|
return m ? [m] : [];
|
|
33521
34040
|
});
|
|
33522
|
-
return sessionHistory({ ...r, id: r.session_id, provider: r.model_provider }, messages
|
|
34041
|
+
return sessionHistory({ ...r, id: r.session_id, provider: r.model_provider }, messages);
|
|
33523
34042
|
}
|
|
33524
34043
|
};
|
|
33525
34044
|
function forkStore(id2, name, defaultPath, desktop) {
|
|
@@ -33533,7 +34052,7 @@ function forkStore(id2, name, defaultPath, desktop) {
|
|
|
33533
34052
|
parse(db2, r) {
|
|
33534
34053
|
if (desktop !== void 0 && text(r.version).startsWith("desktop-") !== desktop) return;
|
|
33535
34054
|
const messages = rows(db2, "message", ["id", "data", "time_created"], ["session_id", r.id], "time_created").map((m) => {
|
|
33536
|
-
const body2 =
|
|
34055
|
+
const body2 = object3(sqliteJSON(m.data));
|
|
33537
34056
|
let content = body2.parts ?? body2.content;
|
|
33538
34057
|
if (hasTable(db2, "part")) content = rows(db2, "part", ["id", "data"], ["message_id", m.id], "id").map((p) => sqliteJSON(p.data));
|
|
33539
34058
|
if (Array.isArray(content)) content = content.flatMap((p) => {
|
|
@@ -33545,7 +34064,7 @@ function forkStore(id2, name, defaultPath, desktop) {
|
|
|
33545
34064
|
});
|
|
33546
34065
|
return conversationMessage({ ...body2, content, timestamp: body2.time?.created ?? m.time_created }, text(m.id));
|
|
33547
34066
|
});
|
|
33548
|
-
return sessionHistory({ ...r, created_at: r.time_created, updated_at: r.time_updated }, messages
|
|
34067
|
+
return sessionHistory({ ...r, created_at: r.time_created, updated_at: r.time_updated }, messages);
|
|
33549
34068
|
}
|
|
33550
34069
|
};
|
|
33551
34070
|
}
|
|
@@ -33558,17 +34077,22 @@ var zed = {
|
|
|
33558
34077
|
fields: ["id", "summary", "created_at", "updated_at", "data_type", "data", "folder_paths"],
|
|
33559
34078
|
parse(db2, r) {
|
|
33560
34079
|
if (!["json", "zstd"].includes(r.data_type)) throw new Error("Unsupported Zed encoding.");
|
|
33561
|
-
const body2 =
|
|
34080
|
+
const body2 = object3(sqliteJSON(r.data));
|
|
33562
34081
|
if (body2.imported === true) return;
|
|
33563
34082
|
if (!Array.isArray(body2.messages)) throw new Error("Unsupported Zed thread.");
|
|
33564
34083
|
const messages = body2.messages.map((raw, i) => {
|
|
33565
|
-
const user =
|
|
34084
|
+
const user = object3(raw.User), agent = object3(raw.Agent), b = raw.User ? user : agent;
|
|
33566
34085
|
if (!raw.User && !raw.Agent) return recordEvent(raw, `message:${i}`, "Context checkpoint", 0, raw.Compaction?.Summary);
|
|
33567
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" });
|
|
33568
34087
|
return conversationMessage({ role: raw.User ? "user" : "assistant", content }, text(b.id) || `message:${i}`);
|
|
33569
34088
|
});
|
|
33570
34089
|
const folders = optionalJSON(r.folder_paths);
|
|
33571
|
-
|
|
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;
|
|
33572
34096
|
}
|
|
33573
34097
|
};
|
|
33574
34098
|
var devin = {
|
|
@@ -33580,10 +34104,10 @@ var devin = {
|
|
|
33580
34104
|
fields: ["id", "working_directory", "model", "title", "created_at", "last_activity_at"],
|
|
33581
34105
|
parse(db2, r) {
|
|
33582
34106
|
const messages = rows(db2, "message_nodes", ["node_id", "chat_message", "created_at"], ["session_id", r.id], "row_id").flatMap((m) => {
|
|
33583
|
-
const raw =
|
|
34107
|
+
const raw = object3(sqliteJSON(m.chat_message)), result = message(raw, nativeText(m.node_id), millisOrSeconds(m.created_at));
|
|
33584
34108
|
return result ? [result] : [recordEvent(raw, nativeText(m.node_id), "Devin message node", millisOrSeconds(m.created_at))];
|
|
33585
34109
|
});
|
|
33586
|
-
return sessionHistory({ ...r, created_at: millisOrSeconds(r.created_at), updated_at: millisOrSeconds(r.last_activity_at) }, messages
|
|
34110
|
+
return sessionHistory({ ...r, created_at: millisOrSeconds(r.created_at), updated_at: millisOrSeconds(r.last_activity_at) }, messages);
|
|
33587
34111
|
}
|
|
33588
34112
|
};
|
|
33589
34113
|
var crushDirectories = /* @__PURE__ */ new Map();
|
|
@@ -33621,7 +34145,7 @@ var crush = {
|
|
|
33621
34145
|
if (m.is_summary_message) return recordEvent(m, text(m.id), "Context summary", millisOrSeconds(m.created_at), content);
|
|
33622
34146
|
return conversationMessage({ role: m.role, content, timestamp: millisOrSeconds(m.created_at) }, text(m.id));
|
|
33623
34147
|
});
|
|
33624
|
-
const h3 = sessionHistory({ ...r, directory: crushDirectories.get(path) || "", created_at: millisOrSeconds(r.created_at), updated_at: millisOrSeconds(r.updated_at) }, messages
|
|
34148
|
+
const h3 = sessionHistory({ ...r, directory: crushDirectories.get(path) || "", created_at: millisOrSeconds(r.created_at), updated_at: millisOrSeconds(r.updated_at) }, messages);
|
|
33625
34149
|
h3.session.cost = typeof r.cost === "number" && r.cost >= 0 ? r.cost : null;
|
|
33626
34150
|
return h3;
|
|
33627
34151
|
}
|
|
@@ -33643,13 +34167,13 @@ var octofriend = {
|
|
|
33643
34167
|
const row = rows(db2, "llm_irs", ["json"], ["id", item.llm_ir_id], void 0, 1)[0];
|
|
33644
34168
|
bytes2 += text(row?.json).length;
|
|
33645
34169
|
if (bytes2 > 32e6) throw new Error("Octofriend session exceeds the snapshot limit.");
|
|
33646
|
-
const payload =
|
|
34170
|
+
const payload = object3(sqliteJSON(row?.json));
|
|
33647
34171
|
if (payload.version !== "octo-llm-ir/v1") throw new Error("Unsupported Octofriend IR version.");
|
|
33648
|
-
const ir =
|
|
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;
|
|
33649
34173
|
const m = message({ ...ir, content, role: ir.role === "tool-output" ? "tool" : ir.role }, nativeText(node.id), node.created_at);
|
|
33650
34174
|
messages.push(m || recordEvent(ir, nativeText(node.id), text(ir.role), node.created_at));
|
|
33651
34175
|
}
|
|
33652
|
-
const h3 = sessionHistory({ ...r, created_at: nodes[0]?.created_at }, messages, "
|
|
34176
|
+
const h3 = sessionHistory({ ...r, created_at: nodes[0]?.created_at }, messages, "Some subagent history may be missing.");
|
|
33653
34177
|
return h3;
|
|
33654
34178
|
}
|
|
33655
34179
|
};
|
|
@@ -33661,11 +34185,25 @@ var unsloth = {
|
|
|
33661
34185
|
key: "id",
|
|
33662
34186
|
fields: ["id", "title", "model_id", "created_at", "updated_at", "archived", "forked_from_thread_id"],
|
|
33663
34187
|
parse(db2, r) {
|
|
33664
|
-
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);
|
|
33665
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
|
+
}
|
|
33666
34204
|
return m ? [m] : [];
|
|
33667
34205
|
});
|
|
33668
|
-
const h3 = sessionHistory({ ...r, model: r.model_id, created_at: seconds(r.created_at), updated_at: seconds(r.updated_at) }, messages
|
|
34206
|
+
const h3 = sessionHistory({ ...r, model: r.model_id, created_at: seconds(r.created_at), updated_at: seconds(r.updated_at) }, messages);
|
|
33669
34207
|
h3.fork = text(r.forked_from_thread_id) || void 0;
|
|
33670
34208
|
h3.session.archived = r.archived === 1;
|
|
33671
34209
|
return h3;
|
|
@@ -33679,17 +34217,17 @@ var kiro = {
|
|
|
33679
34217
|
key: "conversation_id",
|
|
33680
34218
|
fields: ["key", "conversation_id", "value"],
|
|
33681
34219
|
parse(db2, r) {
|
|
33682
|
-
const body2 =
|
|
34220
|
+
const body2 = object3(sqliteJSON(r.value));
|
|
33683
34221
|
if (!Array.isArray(body2.history)) throw new Error("Unsupported Kiro conversation.");
|
|
33684
34222
|
const messages = body2.history.flatMap((turn, i) => {
|
|
33685
|
-
const result = [], input =
|
|
34223
|
+
const result = [], input = object3(turn.user?.content), output2 = object3(turn.assistant?.Response || turn.assistant?.ToolUse);
|
|
33686
34224
|
if (typeof input.Prompt?.prompt === "string") result.push(conversationMessage({ role: "user", content: input.Prompt.prompt }, `turn:${i}:user`));
|
|
33687
34225
|
if (input.ToolUseResults) result.push(conversationMessage({ role: "tool", content: input.ToolUseResults }, `turn:${i}:tool`));
|
|
33688
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`));
|
|
33689
34227
|
return result;
|
|
33690
34228
|
});
|
|
33691
34229
|
const created = body2.history.map((t) => time(t.request_metadata?.request_start_timestamp_ms)).find(Boolean);
|
|
33692
|
-
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: "
|
|
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." };
|
|
33693
34231
|
}
|
|
33694
34232
|
};
|
|
33695
34233
|
var databaseHarnessAdapters = [
|
|
@@ -33712,7 +34250,7 @@ import { basename as basename10 } from "node:path";
|
|
|
33712
34250
|
import { fileURLToPath as fileURLToPath4 } from "node:url";
|
|
33713
34251
|
function protoFields(value) {
|
|
33714
34252
|
if (value.length > 2e6) throw new Error("Trajectory metadata exceeds 2 MB.");
|
|
33715
|
-
const
|
|
34253
|
+
const fields3 = /* @__PURE__ */ new Map();
|
|
33716
34254
|
let at2 = 0, count = 0;
|
|
33717
34255
|
const varint = () => {
|
|
33718
34256
|
let n = 0n;
|
|
@@ -33727,35 +34265,35 @@ function protoFields(value) {
|
|
|
33727
34265
|
if (++count > 1e4) throw new Error("Too many protobuf fields.");
|
|
33728
34266
|
const key = Number(varint()), field = key >>> 3, wire = key & 7;
|
|
33729
34267
|
if (!field) throw new Error("Invalid protobuf field.");
|
|
33730
|
-
if (wire === 0)
|
|
34268
|
+
if (wire === 0) fields3.set(field, varint());
|
|
33731
34269
|
else if (wire === 2) {
|
|
33732
34270
|
const length = Number(varint());
|
|
33733
34271
|
if (!Number.isSafeInteger(length) || length > value.length - at2) throw new Error("Invalid protobuf length.");
|
|
33734
|
-
|
|
34272
|
+
fields3.set(field, value.subarray(at2, at2 + length));
|
|
33735
34273
|
at2 += length;
|
|
33736
34274
|
} else if (wire === 1 || wire === 5) {
|
|
33737
34275
|
at2 += wire === 1 ? 8 : 4;
|
|
33738
34276
|
if (at2 > value.length) throw new Error("Truncated protobuf field.");
|
|
33739
34277
|
} else throw new Error("Unsupported protobuf wire type.");
|
|
33740
34278
|
}
|
|
33741
|
-
return
|
|
34279
|
+
return fields3;
|
|
33742
34280
|
}
|
|
33743
34281
|
var nested = (v3) => v3 instanceof Uint8Array ? protoFields(v3) : /* @__PURE__ */ new Map();
|
|
33744
34282
|
var antigravityDatabaseAdapters = ["antigravity-cli", "antigravity-extension"].map((id2) => sqliteHistoryAdapter({
|
|
33745
34283
|
id: id2,
|
|
33746
34284
|
name: id2 === "antigravity-cli" ? "Antigravity CLI" : "Antigravity IDE Extension",
|
|
33747
34285
|
history: false,
|
|
33748
|
-
description: "
|
|
34286
|
+
description: "Session metadata only",
|
|
33749
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,
|
|
33750
34288
|
table: "trajectory_metadata_blob",
|
|
33751
34289
|
key: "id",
|
|
33752
34290
|
fields: ["id", "data"],
|
|
33753
34291
|
parse(db2, row, path) {
|
|
33754
34292
|
if (!(row.data instanceof Uint8Array)) throw new Error("Unsupported trajectory metadata.");
|
|
33755
|
-
const
|
|
34293
|
+
const fields3 = protoFields(row.data), timestamp = nested(fields3.get(2));
|
|
33756
34294
|
const sec = timestamp.get(1), nano = timestamp.get(2);
|
|
33757
34295
|
const created = typeof sec === "bigint" && sec > 0n && sec < 8640000000000n ? time(Number(sec) * 1e3 + (typeof nano === "bigint" && nano < 1000000000n ? Number(nano) / 1e6 : 0)) : 0;
|
|
33758
|
-
const uri = nested(
|
|
34296
|
+
const uri = nested(fields3.get(1)).get(1);
|
|
33759
34297
|
let directory3 = "";
|
|
33760
34298
|
if (uri instanceof Uint8Array) {
|
|
33761
34299
|
try {
|
|
@@ -33764,13 +34302,13 @@ var antigravityDatabaseAdapters = ["antigravity-cli", "antigravity-extension"].m
|
|
|
33764
34302
|
}
|
|
33765
34303
|
}
|
|
33766
34304
|
if (!created) throw new Error("Trajectory creation time is unavailable.");
|
|
33767
|
-
return { nativeID: basename10(path, ".db"), messages: [], partial: true, session: { created, directory: directory3 }, note: "
|
|
34305
|
+
return { nativeID: basename10(path, ".db"), messages: [], partial: true, session: { created, directory: directory3 }, note: "Session metadata only." };
|
|
33768
34306
|
}
|
|
33769
34307
|
}));
|
|
33770
34308
|
var antigravityCacheAdapter = localFileAdapter({
|
|
33771
34309
|
id: "antigravity",
|
|
33772
34310
|
name: "Antigravity",
|
|
33773
|
-
description: "
|
|
34311
|
+
description: "Cached session metadata only",
|
|
33774
34312
|
capabilities: { history: false, forks: false, children: false, files: false },
|
|
33775
34313
|
roots: harnessRoots("antigravity", () => [tokscalePath("antigravity-cache/sessions")]),
|
|
33776
34314
|
match: (p) => p.endsWith(".jsonl"),
|
|
@@ -33780,7 +34318,7 @@ var antigravityCacheAdapter = localFileAdapter({
|
|
|
33780
34318
|
if (ids.size !== 1) throw new Error("Unsupported Antigravity cache identity.");
|
|
33781
34319
|
const created = rows2.map((r) => time(r.timestamp)).filter(Boolean).sort((a, b) => a - b)[0];
|
|
33782
34320
|
if (!created) throw new Error("Antigravity cache has no recorded date.");
|
|
33783
|
-
return { nativeID: [...ids][0], messages: [], partial: true, session: { created, model: text(rows2.find((r) => r.modelId)?.modelId) || "Unknown model" }, note: "
|
|
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." };
|
|
33784
34322
|
}
|
|
33785
34323
|
});
|
|
33786
34324
|
|
|
@@ -33800,7 +34338,7 @@ import { randomUUID as randomUUID2 } from "node:crypto";
|
|
|
33800
34338
|
var MAX_CHARACTERS = 24e6;
|
|
33801
34339
|
var SESSION_CHARACTERS = 48e3;
|
|
33802
34340
|
var CACHE_VERSION = 2;
|
|
33803
|
-
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]);
|
|
33804
34342
|
function validRecord(value, session) {
|
|
33805
34343
|
if (!value || !session || value.id !== session.id || value.version !== contentVersion(session)) return false;
|
|
33806
34344
|
if (!Number.isInteger(value.pages) || value.pages < 1 || value.pages > 8) return false;
|
|
@@ -33862,7 +34400,7 @@ var LibraryError = class extends Error {
|
|
|
33862
34400
|
function invalid(message2) {
|
|
33863
34401
|
throw new LibraryError("INVALID_ARGUMENT", message2, 2);
|
|
33864
34402
|
}
|
|
33865
|
-
var
|
|
34403
|
+
var fingerprint2 = (value) => createHash4("sha256").update(JSON.stringify(value)).digest("hex");
|
|
33866
34404
|
function pageLimit(value = 50) {
|
|
33867
34405
|
if (!Number.isSafeInteger(value) || value < 1 || value > 200) invalid("Limit must be an integer from 1 to 200.");
|
|
33868
34406
|
return value;
|
|
@@ -33895,7 +34433,7 @@ var pendingCommits = () => ({ version: 0, state: "pending", count: null, note: "
|
|
|
33895
34433
|
function writeCommits(db2, session) {
|
|
33896
34434
|
db2.prepare("DELETE FROM session_commits WHERE session_id=?").run(session.id);
|
|
33897
34435
|
const base = { version: COMMIT_EXTRACTOR_VERSION, indexedAt: Date.now() };
|
|
33898
|
-
if (!supported.has(session.source || "")) return { ...base, state: "unavailable", count: null, note: "Commit
|
|
34436
|
+
if (!supported.has(session.source || "")) return { ...base, state: "unavailable", count: null, note: "Commit history unavailable for this source." };
|
|
33899
34437
|
const calls = /* @__PURE__ */ new Map();
|
|
33900
34438
|
const results = /* @__PURE__ */ new Map();
|
|
33901
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);
|
|
@@ -33904,7 +34442,7 @@ function writeCommits(db2, session) {
|
|
|
33904
34442
|
const item = JSON.parse(String(row.data));
|
|
33905
34443
|
tools++;
|
|
33906
34444
|
if (item.kind === "tool_result" && item.callID) {
|
|
33907
|
-
const signature =
|
|
34445
|
+
const signature = fingerprint2([item.output, item.exitCode, item.status, item.gitCommit]);
|
|
33908
34446
|
results.set(item.callID, results.has(item.callID) && results.get(item.callID) !== signature ? null : signature);
|
|
33909
34447
|
}
|
|
33910
34448
|
if (item.kind !== "tool_call" || !item.callID) continue;
|
|
@@ -33941,7 +34479,7 @@ function writeCommits(db2, session) {
|
|
|
33941
34479
|
...base,
|
|
33942
34480
|
state: !tools ? "unavailable" : partial ? "partial" : "indexed",
|
|
33943
34481
|
count: !tools ? null : count,
|
|
33944
|
-
note: !tools ? "No
|
|
34482
|
+
note: !tools ? "No tool executions recorded." : partial ? "Some commits may be missing." : count ? "Confirmed commits from saved tool results." : "No recorded commits found."
|
|
33945
34483
|
};
|
|
33946
34484
|
}
|
|
33947
34485
|
function commit(row) {
|
|
@@ -33951,7 +34489,7 @@ function readCommits(db2, session, options = {}) {
|
|
|
33951
34489
|
let coverage2 = session.commits || pendingCommits();
|
|
33952
34490
|
if (session.coverage?.note?.startsWith("Latest import failed:")) coverage2 = { ...coverage2, state: coverage2.count === null ? coverage2.state : "partial", note: `${session.coverage.note} ${coverage2.note}` };
|
|
33953
34491
|
const revision2 = String(db2.prepare("SELECT revision FROM timeline_coverage WHERE session_id=?").get(session.id)?.revision || "pending");
|
|
33954
|
-
const key =
|
|
34492
|
+
const key = fingerprint2(["commits", session.id, revision2, coverage2]), offset = pageOffset(options.cursor, key), limit = pageLimit(options.limit);
|
|
33955
34493
|
const total = Number(db2.prepare("SELECT count(*) AS n FROM session_commits WHERE session_id=?").get(session.id).n);
|
|
33956
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);
|
|
33957
34495
|
return { sessionID: session.id, revision: revision2, coverage: coverage2, items, total, nextCursor: offset + limit < total ? nextCursor(key, offset + limit) : null };
|
|
@@ -33973,7 +34511,19 @@ ${abbreviatedSHA(value.sha) ? "Abbreviated SHA \xB7 " : ""}Open recorded executi
|
|
|
33973
34511
|
});
|
|
33974
34512
|
}
|
|
33975
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
|
+
|
|
33976
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');`;
|
|
33977
34527
|
var EVENT_SCHEMA = `CREATE TABLE IF NOT EXISTS timeline_items (
|
|
33978
34528
|
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, id TEXT NOT NULL, message_id TEXT NOT NULL,
|
|
33979
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,
|
|
@@ -33992,7 +34542,7 @@ function writeEvents(db2, id2, rows2) {
|
|
|
33992
34542
|
for (const event of normalizedEvents(message2, id2)) {
|
|
33993
34543
|
const item = { ...event, ordinal: ordinal++ }, data = JSON.stringify(item);
|
|
33994
34544
|
bytes2 += Buffer.byteLength(data);
|
|
33995
|
-
if (ordinal >
|
|
34545
|
+
if (ordinal > MAX_TIMELINE_EVENTS || bytes2 > MAX_TIMELINE_BYTES) {
|
|
33996
34546
|
limited = true;
|
|
33997
34547
|
break;
|
|
33998
34548
|
}
|
|
@@ -34002,7 +34552,7 @@ function writeEvents(db2, id2, rows2) {
|
|
|
34002
34552
|
}
|
|
34003
34553
|
if (limited) break;
|
|
34004
34554
|
}
|
|
34005
|
-
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 ?
|
|
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(" ");
|
|
34006
34556
|
db2.prepare("INSERT OR REPLACE INTO timeline_coverage VALUES (?,?,?,?)").run(id2, Number(partial || legacy || limited), note || null, randomUUID());
|
|
34007
34557
|
}
|
|
34008
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";
|
|
@@ -34038,7 +34588,7 @@ function readEvents(db2, session, options = {}) {
|
|
|
34038
34588
|
try {
|
|
34039
34589
|
if (options.cursor.length > 512) throw new Error();
|
|
34040
34590
|
const cursor2 = JSON.parse(Buffer.from(options.cursor, "base64url").toString());
|
|
34041
|
-
if (!Number.isSafeInteger(cursor2.offset) || cursor2.offset < 0 || cursor2.offset >
|
|
34591
|
+
if (!Number.isSafeInteger(cursor2.offset) || cursor2.offset < 0 || cursor2.offset > MAX_TIMELINE_EVENTS || cursor2.filter !== filter || typeof cursor2.revision !== "string") throw new Error();
|
|
34042
34592
|
if (cursor2.revision !== state2.revision) throw new EventReadError("Saved history changed. Reload the event explorer.", 409);
|
|
34043
34593
|
offset = cursor2.offset;
|
|
34044
34594
|
} catch (error) {
|
|
@@ -34079,12 +34629,12 @@ function readEvents(db2, session, options = {}) {
|
|
|
34079
34629
|
|
|
34080
34630
|
// packages/core/src/preferences.ts
|
|
34081
34631
|
var DEFAULT_PREFERENCES = Object.freeze({
|
|
34082
|
-
autoImport:
|
|
34632
|
+
autoImport: false,
|
|
34083
34633
|
muted: false,
|
|
34084
34634
|
clickSounds: true,
|
|
34085
34635
|
clickVolume: 35,
|
|
34086
34636
|
motion: "system",
|
|
34087
|
-
|
|
34637
|
+
grouping: "worktree",
|
|
34088
34638
|
density: "comfortable",
|
|
34089
34639
|
panelOpacity: 90,
|
|
34090
34640
|
quality: "balanced",
|
|
@@ -34101,7 +34651,7 @@ var DEFAULT_PREFERENCES = Object.freeze({
|
|
|
34101
34651
|
messageDots: true,
|
|
34102
34652
|
playbackSpeed: 1
|
|
34103
34653
|
});
|
|
34104
|
-
var choices = { motion: ["system", "on", "off"],
|
|
34654
|
+
var choices = { motion: ["system", "on", "off"], grouping: ["repository", "worktree"], density: ["comfortable", "compact"], quality: ["performance", "balanced", "high"], trails: ["all", "selected", "off"] };
|
|
34105
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] };
|
|
34106
34656
|
function normalizePreferences(value) {
|
|
34107
34657
|
const result = { ...DEFAULT_PREFERENCES };
|
|
@@ -34124,7 +34674,7 @@ var DEFAULT_VIEW_STATE = Object.freeze({
|
|
|
34124
34674
|
sourceID: "",
|
|
34125
34675
|
projectID: "",
|
|
34126
34676
|
directory: "",
|
|
34127
|
-
days:
|
|
34677
|
+
days: "ytd",
|
|
34128
34678
|
fromDate: "",
|
|
34129
34679
|
toDate: "",
|
|
34130
34680
|
includeChildren: true,
|
|
@@ -34136,7 +34686,7 @@ function normalizeViewState(value) {
|
|
|
34136
34686
|
if (!value || typeof value !== "object" || Array.isArray(value)) return result;
|
|
34137
34687
|
const input = value;
|
|
34138
34688
|
for (const key of ["sourceID", "projectID", "directory"]) if (typeof input[key] === "string" && input[key].length <= 4096) result[key] = input[key];
|
|
34139
|
-
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;
|
|
34140
34690
|
for (const key of ["includeChildren", "includeArchived"]) if (typeof input[key] === "boolean") result[key] = input[key];
|
|
34141
34691
|
for (const key of ["fromDate", "toDate"]) if (validDate(input[key])) result[key] = input[key];
|
|
34142
34692
|
if (result.fromDate && result.toDate && result.fromDate > result.toDate) {
|
|
@@ -34155,7 +34705,7 @@ var SessionGraphStore = class {
|
|
|
34155
34705
|
if (path !== ":memory:") chmodSync3(path, 384);
|
|
34156
34706
|
this.db.exec("PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;");
|
|
34157
34707
|
const version = Number(this.db.prepare("PRAGMA user_version").get().user_version);
|
|
34158
|
-
if (version >
|
|
34708
|
+
if (version > 8) throw new Error("This SessionGraph database requires a newer version of the app.");
|
|
34159
34709
|
this.db.exec(`
|
|
34160
34710
|
CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
34161
34711
|
CREATE TABLE IF NOT EXISTS sources (id TEXT PRIMARY KEY, last_import INTEGER, error TEXT);
|
|
@@ -34232,6 +34782,29 @@ var SessionGraphStore = class {
|
|
|
34232
34782
|
throw error;
|
|
34233
34783
|
}
|
|
34234
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
|
+
}
|
|
34235
34808
|
if (!this.setting("libraryID")) this.setting("libraryID", randomUUID2());
|
|
34236
34809
|
}
|
|
34237
34810
|
path;
|
|
@@ -34246,7 +34819,7 @@ var SessionGraphStore = class {
|
|
|
34246
34819
|
return this.setting("selected") || [];
|
|
34247
34820
|
}
|
|
34248
34821
|
autoImportEnabled() {
|
|
34249
|
-
return this.setting("autoImport")
|
|
34822
|
+
return this.setting("autoImport") === true;
|
|
34250
34823
|
}
|
|
34251
34824
|
acquireImport() {
|
|
34252
34825
|
this.db.exec("BEGIN IMMEDIATE");
|
|
@@ -34288,11 +34861,20 @@ var SessionGraphStore = class {
|
|
|
34288
34861
|
commitsCurrent(id2) {
|
|
34289
34862
|
return this.getSession(id2)?.commits?.version === COMMIT_EXTRACTOR_VERSION;
|
|
34290
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
|
+
}
|
|
34291
34869
|
upsert(candidate) {
|
|
34292
34870
|
const s = candidate.session, previous = this.getSession(s.id);
|
|
34293
34871
|
const metadata2 = {
|
|
34294
34872
|
...s,
|
|
34295
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,
|
|
34296
34878
|
parentID: previous?.parentID && candidate.locator.agent ? previous.parentID : s.parentID,
|
|
34297
34879
|
activity: previous?.activity,
|
|
34298
34880
|
commits: previous?.commits || pendingCommits(),
|
|
@@ -34303,14 +34885,28 @@ var SessionGraphStore = class {
|
|
|
34303
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));
|
|
34304
34886
|
}
|
|
34305
34887
|
replace(candidate, messages, partial, note) {
|
|
34306
|
-
const
|
|
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
|
+
};
|
|
34307
34898
|
this.db.exec("BEGIN IMMEDIATE");
|
|
34308
34899
|
try {
|
|
34309
34900
|
this.db.prepare("DELETE FROM messages WHERE session_id=?").run(s.id);
|
|
34310
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");
|
|
34311
|
-
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))));
|
|
34312
34903
|
writeEvents(this.db, s.id, this.db.prepare("SELECT data FROM messages WHERE session_id=? ORDER BY ordinal").iterate(s.id));
|
|
34313
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
|
+
}
|
|
34314
34910
|
const activity = this.db.prepare(activitySQL).get(s.id);
|
|
34315
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);
|
|
34316
34912
|
this.db.prepare("DELETE FROM search_cache WHERE id=?").run(s.id);
|
|
@@ -34434,7 +35030,7 @@ var SessionGraphStore = class {
|
|
|
34434
35030
|
}
|
|
34435
35031
|
messages(id2, options = {}) {
|
|
34436
35032
|
return this.readSnapshot(id2, (session) => {
|
|
34437
|
-
const key =
|
|
35033
|
+
const key = fingerprint2(["messages", id2, session.revision, session.coverage]);
|
|
34438
35034
|
const offset = pageOffset(options.cursor, key), limit = pageLimit(options.limit);
|
|
34439
35035
|
const rows2 = this.messagePage(id2, offset, limit);
|
|
34440
35036
|
let remaining = 64e3, truncated = false;
|
|
@@ -34451,6 +35047,9 @@ var SessionGraphStore = class {
|
|
|
34451
35047
|
time: messageTime(message2.time),
|
|
34452
35048
|
role: message2.role,
|
|
34453
35049
|
fragments,
|
|
35050
|
+
metadata: message2.metadata,
|
|
35051
|
+
usage: message2.usage,
|
|
35052
|
+
locations: message2.locations,
|
|
34454
35053
|
files: message2.files.slice(0, 200),
|
|
34455
35054
|
tools: message2.tools.slice(0, 200),
|
|
34456
35055
|
partial: !!message2.partial || message2.fragments.length > 200 || message2.files.length > 200 || message2.tools.length > 200 || fragments.some((f) => f.truncated)
|
|
@@ -34471,19 +35070,29 @@ var SessionGraphStore = class {
|
|
|
34471
35070
|
return this.readSnapshot(id2, (session) => {
|
|
34472
35071
|
const page = this.messagePage(id2, Number(cursor || 0), 120);
|
|
34473
35072
|
const files = /* @__PURE__ */ new Map(), tools = /* @__PURE__ */ new Map();
|
|
35073
|
+
const locations = [];
|
|
34474
35074
|
for (const message2 of page.messages) {
|
|
34475
35075
|
for (const file of message2.files) {
|
|
34476
35076
|
const previous = files.get(file.path);
|
|
34477
35077
|
files.set(file.path, { ...file, source: previous?.source === "snapshot" ? "snapshot" : file.source, steps: (previous?.steps || 0) + file.steps });
|
|
34478
35078
|
}
|
|
34479
35079
|
message2.tools.forEach((tool) => tools.set(tool, (tools.get(tool) || 0) + 1));
|
|
34480
|
-
|
|
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;
|
|
34481
35089
|
return {
|
|
34482
35090
|
id: id2,
|
|
34483
35091
|
revision: session.revision,
|
|
35092
|
+
pullRequests: pullRequests2?.length ? pullRequests2 : void 0,
|
|
34484
35093
|
files: [...files.values()].sort((a, b) => b.steps - a.steps),
|
|
34485
35094
|
tools: [...tools].map(([name, count]) => ({ name, count })),
|
|
34486
|
-
locations
|
|
35095
|
+
locations,
|
|
34487
35096
|
messagesScanned: page.messages.length,
|
|
34488
35097
|
snapshotSteps: page.messages.reduce((n, m) => n + (m.snapshots || 0), 0),
|
|
34489
35098
|
nextCursor: page.next,
|
|
@@ -34555,7 +35164,7 @@ var Importer = class {
|
|
|
34555
35164
|
this.adapters = adapters2.map((adapter) => withSourcePaths(adapter, () => this.store.setting("sourcePaths") || {}));
|
|
34556
35165
|
}
|
|
34557
35166
|
store;
|
|
34558
|
-
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: [] };
|
|
34559
35168
|
job;
|
|
34560
35169
|
adapters;
|
|
34561
35170
|
async sources() {
|
|
@@ -34576,7 +35185,7 @@ var Importer = class {
|
|
|
34576
35185
|
if (ids && save) {
|
|
34577
35186
|
this.store.setting("selected", [...new Set(ids)]);
|
|
34578
35187
|
}
|
|
34579
|
-
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: [] };
|
|
34580
35189
|
const heartbeat = setInterval(() => this.store.heartbeat(), 5e3);
|
|
34581
35190
|
this.job = this.run(ids || this.store.selected()).catch(() => {
|
|
34582
35191
|
this.status.failed++;
|
|
@@ -34593,20 +35202,30 @@ var Importer = class {
|
|
|
34593
35202
|
async settled() {
|
|
34594
35203
|
await this.job;
|
|
34595
35204
|
}
|
|
35205
|
+
report(kind, message2) {
|
|
35206
|
+
const messages = this.status[kind] ??= [];
|
|
35207
|
+
if (!messages.includes(message2)) messages.push(message2);
|
|
35208
|
+
}
|
|
34596
35209
|
async run(ids) {
|
|
34597
35210
|
for (const adapter of this.adapters.filter((a) => ids.includes(a.id))) {
|
|
34598
35211
|
this.status.source = adapter.id;
|
|
34599
35212
|
try {
|
|
34600
|
-
if (!await adapter.detect()) throw new Error(
|
|
35213
|
+
if (!await adapter.detect()) throw new Error("Source unavailable.");
|
|
34601
35214
|
const discovery = await adapter.discover();
|
|
34602
35215
|
const failedBefore = this.status.failed;
|
|
35216
|
+
const discoveryErrors = [...new Set(discovery.errors)];
|
|
34603
35217
|
const seen = new Map(discovery.sessions.map((candidate) => [candidate.session.id, candidate]));
|
|
34604
35218
|
this.status.discovered += seen.size;
|
|
34605
|
-
|
|
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
|
+
}
|
|
34606
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));
|
|
34607
35226
|
for (const candidate of seen.values()) {
|
|
34608
35227
|
const saved = this.store.getSession(candidate.session.id);
|
|
34609
|
-
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);
|
|
34610
35229
|
if (!retry && saved?.revision === candidate.revision && this.store.revision(candidate.session.id) === candidate.revision) {
|
|
34611
35230
|
this.store.upsert(candidate);
|
|
34612
35231
|
this.status.unchanged++;
|
|
@@ -34621,16 +35240,26 @@ var Importer = class {
|
|
|
34621
35240
|
const page = await adapter.read(candidate, cursor);
|
|
34622
35241
|
partial ||= Boolean(page.partial);
|
|
34623
35242
|
note = page.note || note;
|
|
35243
|
+
let limited = false;
|
|
34624
35244
|
for (const message2 of page.messages) {
|
|
34625
|
-
if (!message2.id
|
|
34626
|
-
|
|
34627
|
-
|
|
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;
|
|
34628
35254
|
break;
|
|
34629
35255
|
}
|
|
34630
|
-
let remaining =
|
|
35256
|
+
let remaining = MAX_SESSION_CHARACTERS - characters;
|
|
34631
35257
|
message2.fragments = message2.fragments.flatMap((fragment) => {
|
|
34632
35258
|
const text2 = fragment.text.slice(0, remaining);
|
|
34633
|
-
if (text2.length < fragment.text.length)
|
|
35259
|
+
if (text2.length < fragment.text.length) {
|
|
35260
|
+
message2.partial = true;
|
|
35261
|
+
limited = true;
|
|
35262
|
+
}
|
|
34634
35263
|
remaining -= text2.length;
|
|
34635
35264
|
return text2 ? [{ ...fragment, text: text2 }] : [];
|
|
34636
35265
|
});
|
|
@@ -34643,29 +35272,31 @@ var Importer = class {
|
|
|
34643
35272
|
pages++;
|
|
34644
35273
|
if (cursor && cursors.has(cursor)) throw new Error("Source returned a repeated history cursor.");
|
|
34645
35274
|
if (cursor) cursors.add(cursor);
|
|
34646
|
-
if (pages >=
|
|
35275
|
+
if (limited || cursor && (pages >= MAX_SESSION_PAGES || messages.size >= MAX_SESSION_RECORDS || characters >= MAX_SESSION_CHARACTERS)) {
|
|
34647
35276
|
partial = true;
|
|
34648
|
-
note =
|
|
35277
|
+
note = [note, SESSION_LIMIT_NOTE].filter(Boolean).join(" ");
|
|
34649
35278
|
break;
|
|
34650
35279
|
}
|
|
34651
35280
|
await yieldToIO();
|
|
34652
35281
|
} while (cursor);
|
|
34653
35282
|
const values = [...messages.values()];
|
|
34654
35283
|
if (adapter.id === "opencode") values.reverse();
|
|
34655
|
-
if (saved?.activity?.userMessages && values.every((message2) => message2.role === "system")) throw new Error("
|
|
35284
|
+
if (saved?.activity?.userMessages && values.every((message2) => message2.role === "system")) throw new Error("No readable conversation.");
|
|
34656
35285
|
this.store.replace(candidate, values, partial, note);
|
|
34657
35286
|
this.status.imported++;
|
|
34658
35287
|
} catch (error) {
|
|
34659
35288
|
this.status.failed++;
|
|
34660
35289
|
this.store.failed(candidate.session.id, error instanceof Error ? error.message : "Unavailable");
|
|
34661
|
-
if (this.status.errors.length < 30) this.
|
|
35290
|
+
if (this.status.errors.length < 30) this.report("errors", `${adapter.name}: ${error instanceof Error ? error.message : "Session import failed."}`);
|
|
34662
35291
|
}
|
|
34663
35292
|
await yieldToIO();
|
|
34664
35293
|
}
|
|
34665
|
-
|
|
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);
|
|
34666
35297
|
} catch (error) {
|
|
34667
|
-
const message2 = error instanceof Error ? error.message :
|
|
34668
|
-
this.
|
|
35298
|
+
const message2 = `${adapter.name}: ${error instanceof Error ? error.message : "Import failed."}`;
|
|
35299
|
+
this.report("errors", message2);
|
|
34669
35300
|
this.store.recordSource(adapter.id, message2);
|
|
34670
35301
|
this.status.failed++;
|
|
34671
35302
|
}
|
|
@@ -34986,7 +35617,7 @@ var nouns = "Wombat Pickle Pancake Badger Potato Narwhal Noodle Goblin Otter Tur
|
|
|
34986
35617
|
var DEFAULT_PUBLISHING = { tokens: true, timestamps: true, messageCounts: true, messageTimestamps: true, model: true, harness: true };
|
|
34987
35618
|
function publishingSettings(value) {
|
|
34988
35619
|
const result = { ...DEFAULT_PUBLISHING };
|
|
34989
|
-
if (
|
|
35620
|
+
if (object4(value)) {
|
|
34990
35621
|
for (const key of Object.keys(result)) if (typeof value[key] === "boolean") result[key] = value[key];
|
|
34991
35622
|
}
|
|
34992
35623
|
if (!result.timestamps || !result.messageCounts) result.messageTimestamps = false;
|
|
@@ -35001,11 +35632,11 @@ var publicModel = (value) => {
|
|
|
35001
35632
|
return name.length <= 100 && modelPattern.test(name) ? name.toLowerCase() : null;
|
|
35002
35633
|
};
|
|
35003
35634
|
function publishableGraph(sessions, settings, messages = /* @__PURE__ */ new Map()) {
|
|
35004
|
-
const
|
|
35635
|
+
const fields3 = publishingSettings(settings);
|
|
35005
35636
|
const ordered = [...sessions].sort((a, b) => a.created - b.created || a.id.localeCompare(b.id));
|
|
35006
35637
|
const ids = new Map(ordered.map((session, index) => [session.id, index]));
|
|
35007
35638
|
const groups = /* @__PURE__ */ new Map();
|
|
35008
|
-
const graph = { version: 1, settings:
|
|
35639
|
+
const graph = { version: 1, settings: fields3, sessions: ordered.map((session) => {
|
|
35009
35640
|
const key = laneKey(session);
|
|
35010
35641
|
if (!groups.has(key)) groups.set(key, groups.size);
|
|
35011
35642
|
const result = {
|
|
@@ -35014,16 +35645,16 @@ function publishableGraph(sessions, settings, messages = /* @__PURE__ */ new Map
|
|
|
35014
35645
|
parent: session.parentID ? ids.get(session.parentID) ?? null : null,
|
|
35015
35646
|
fork: session.forkID ? ids.get(session.forkID) ?? null : null
|
|
35016
35647
|
};
|
|
35017
|
-
if (
|
|
35018
|
-
if (
|
|
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;
|
|
35019
35650
|
const stats = messages.get(session.id);
|
|
35020
|
-
if (
|
|
35021
|
-
if (
|
|
35022
|
-
if (
|
|
35023
|
-
if (
|
|
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;
|
|
35024
35655
|
return result;
|
|
35025
35656
|
}) };
|
|
35026
|
-
if (
|
|
35657
|
+
if (fields3.messageTimestamps) {
|
|
35027
35658
|
let bytes2 = PUBLIC_GRAPH_MAX_BYTES - new TextEncoder().encode(JSON.stringify(graph)).length;
|
|
35028
35659
|
let remaining = PUBLIC_GRAPH_MAX_MESSAGE_TIMES;
|
|
35029
35660
|
for (let index = 0; index < ordered.length; index++) {
|
|
@@ -35040,8 +35671,8 @@ function publishableGraph(sessions, settings, messages = /* @__PURE__ */ new Map
|
|
|
35040
35671
|
}
|
|
35041
35672
|
return validatePublicGraph(graph);
|
|
35042
35673
|
}
|
|
35043
|
-
var
|
|
35044
|
-
var exact = (value, keys) =>
|
|
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));
|
|
35045
35676
|
var integer = (value, max = Number.MAX_SAFE_INTEGER) => Number.isSafeInteger(value) && value >= 0 && value <= max;
|
|
35046
35677
|
var time3 = (value) => integer(value, Date.UTC(2100, 0, 1));
|
|
35047
35678
|
var nullableCount = (value) => value === null || integer(value);
|
|
@@ -35110,23 +35741,24 @@ function preparePublicGraph(store, ids, inputSettings) {
|
|
|
35110
35741
|
const stats = /* @__PURE__ */ new Map();
|
|
35111
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')");
|
|
35112
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 ?");
|
|
35113
|
-
const
|
|
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=?");
|
|
35114
35745
|
let remaining = PUBLIC_GRAPH_MAX_MESSAGE_TIMES;
|
|
35115
35746
|
store.db.exec("BEGIN");
|
|
35116
35747
|
try {
|
|
35117
35748
|
const sessions = ids.map((id2) => {
|
|
35118
|
-
const
|
|
35119
|
-
if (!
|
|
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));
|
|
35120
35752
|
if (settings.messageCounts) {
|
|
35121
|
-
const known = session.coverage?.history !== "pending" &&
|
|
35753
|
+
const known = session.coverage?.history !== "pending" && row.partial !== null;
|
|
35122
35754
|
const totals = count.get(id2);
|
|
35123
|
-
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)) : [];
|
|
35124
35756
|
remaining -= rows2.length;
|
|
35125
|
-
const values = rows2.map((
|
|
35757
|
+
const values = rows2.map((row2) => Number(row2.time));
|
|
35126
35758
|
stats.set(id2, {
|
|
35127
35759
|
count: known ? Number(totals.count) : null,
|
|
35128
35760
|
untimed: known ? Number(totals.untimed) : null,
|
|
35129
|
-
partial: !known || session.coverage?.history !== "complete" || Boolean(
|
|
35761
|
+
partial: !known || session.coverage?.history !== "complete" || Boolean(row.partial),
|
|
35130
35762
|
times: values,
|
|
35131
35763
|
timesLimited: !known || Number(totals.count) - Number(totals.untimed) > values.length
|
|
35132
35764
|
});
|
|
@@ -35263,6 +35895,77 @@ var PublishingClient = class {
|
|
|
35263
35895
|
}
|
|
35264
35896
|
};
|
|
35265
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
|
+
|
|
35266
35969
|
// server/middleware.ts
|
|
35267
35970
|
var publishing = new PublishingClient();
|
|
35268
35971
|
var generation = /* @__PURE__ */ Symbol("sessiongraph-backend");
|
|
@@ -35377,7 +36080,9 @@ async function sessionGraphMiddleware(req, res, next) {
|
|
|
35377
36080
|
}
|
|
35378
36081
|
if (url.pathname === "/api/sessiongraph" && req.method === "GET") {
|
|
35379
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) }));
|
|
35380
|
-
|
|
36083
|
+
const data = store.library(sources2, importer.status.running);
|
|
36084
|
+
data.sessions = await annotateGitCheckouts(data.sessions);
|
|
36085
|
+
return json5(200, data);
|
|
35381
36086
|
}
|
|
35382
36087
|
const match2 = /^\/api\/sessiongraph\/session\/([^/]+)(?:\/(content|timeline|commits|events|event-markers|connection|prepare-launch|open-terminal))?$/.exec(url.pathname);
|
|
35383
36088
|
if (match2) {
|
|
@@ -35405,7 +36110,7 @@ async function sessionGraphMiddleware(req, res, next) {
|
|
|
35405
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)]] : []))));
|
|
35406
36111
|
if (match2[2] === "connection") return json5(200, await getLaunchConnection(session));
|
|
35407
36112
|
const cursor = url.searchParams.get("cursor") || void 0;
|
|
35408
|
-
if (cursor && (!/^\d{1,9}$/.test(cursor) || Number(cursor) >
|
|
36113
|
+
if (cursor && (!/^\d{1,9}$/.test(cursor) || Number(cursor) > MAX_SESSION_RECORDS)) return json5(400, { error: "Invalid cursor." });
|
|
35409
36114
|
return json5(200, match2[2] === "content" ? store.content(id2, cursor) : store.detail(id2, cursor));
|
|
35410
36115
|
}
|
|
35411
36116
|
return json5(404, { error: "Not found." });
|