@drod915/kvdiff 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +126 -3
- package/dist/cli.js +1849 -0
- package/dist/cli.js.map +1 -0
- package/dist/ui/assets/index-6zpHKv0K.css +1 -0
- package/dist/ui/assets/index-B2iXBreS.js +1 -0
- package/dist/ui/index.html +13 -0
- package/package.json +57 -6
package/dist/cli.js
ADDED
|
@@ -0,0 +1,1849 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { realpathSync } from "node:fs";
|
|
6
|
+
import { join as join3, resolve as resolve2 } from "node:path";
|
|
7
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
8
|
+
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
9
|
+
|
|
10
|
+
// src/store.ts
|
|
11
|
+
import { DatabaseSync } from "node:sqlite";
|
|
12
|
+
import { mkdirSync } from "node:fs";
|
|
13
|
+
import { dirname } from "node:path";
|
|
14
|
+
import { randomUUID } from "node:crypto";
|
|
15
|
+
var KvStore = class {
|
|
16
|
+
db;
|
|
17
|
+
constructor(dbPath) {
|
|
18
|
+
if (dbPath !== ":memory:") {
|
|
19
|
+
mkdirSync(dirname(dbPath), { recursive: true });
|
|
20
|
+
}
|
|
21
|
+
this.db = new DatabaseSync(dbPath);
|
|
22
|
+
if (dbPath !== ":memory:") {
|
|
23
|
+
this.db.exec("PRAGMA journal_mode = WAL;");
|
|
24
|
+
}
|
|
25
|
+
this.db.exec("PRAGMA busy_timeout = 5000;");
|
|
26
|
+
this.db.exec("PRAGMA synchronous = NORMAL;");
|
|
27
|
+
this.db.exec(`
|
|
28
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
29
|
+
id TEXT PRIMARY KEY,
|
|
30
|
+
label TEXT NOT NULL,
|
|
31
|
+
command TEXT,
|
|
32
|
+
healed INTEGER NOT NULL DEFAULT 0,
|
|
33
|
+
created_at_ms INTEGER NOT NULL
|
|
34
|
+
);
|
|
35
|
+
|
|
36
|
+
CREATE TABLE IF NOT EXISTS turns (
|
|
37
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
38
|
+
session_id TEXT NOT NULL,
|
|
39
|
+
turn_index INTEGER NOT NULL,
|
|
40
|
+
timestamp_ms INTEGER NOT NULL,
|
|
41
|
+
provider TEXT NOT NULL,
|
|
42
|
+
endpoint TEXT NOT NULL,
|
|
43
|
+
model TEXT NOT NULL,
|
|
44
|
+
status_code INTEGER NOT NULL,
|
|
45
|
+
latency_ms INTEGER NOT NULL,
|
|
46
|
+
healed INTEGER NOT NULL DEFAULT 0,
|
|
47
|
+
heal_changes_json TEXT NOT NULL,
|
|
48
|
+
usage_json TEXT NOT NULL,
|
|
49
|
+
cost_usd REAL NOT NULL,
|
|
50
|
+
cache_hit_rate REAL NOT NULL,
|
|
51
|
+
wasted_usd REAL NOT NULL,
|
|
52
|
+
break_kind TEXT NOT NULL,
|
|
53
|
+
diagnosis_json TEXT NOT NULL,
|
|
54
|
+
raw_request_body TEXT NOT NULL,
|
|
55
|
+
FOREIGN KEY (session_id) REFERENCES sessions(id)
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
CREATE INDEX IF NOT EXISTS idx_turns_session_turn
|
|
59
|
+
ON turns (session_id, turn_index);
|
|
60
|
+
`);
|
|
61
|
+
}
|
|
62
|
+
createSession(meta) {
|
|
63
|
+
const id = meta.id ?? randomUUID().slice(0, 12);
|
|
64
|
+
const createdAtMs = meta.createdAtMs ?? Date.now();
|
|
65
|
+
this.db.prepare("INSERT OR IGNORE INTO sessions (id, label, command, healed, created_at_ms) VALUES (?, ?, ?, ?, ?)").run(id, meta.label, meta.command ?? null, meta.healed ? 1 : 0, createdAtMs);
|
|
66
|
+
return {
|
|
67
|
+
id,
|
|
68
|
+
label: meta.label,
|
|
69
|
+
command: meta.command ?? null,
|
|
70
|
+
healed: meta.healed,
|
|
71
|
+
createdAtMs,
|
|
72
|
+
turnCount: 0,
|
|
73
|
+
avgCacheHitRate: 0,
|
|
74
|
+
totalCostUsd: 0,
|
|
75
|
+
totalWastedUsd: 0,
|
|
76
|
+
breakCount: 0
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
ensureSession(id, label, healed = false) {
|
|
80
|
+
this.db.prepare("INSERT OR IGNORE INTO sessions (id, label, command, healed, created_at_ms) VALUES (?, ?, NULL, ?, ?)").run(id, label, healed ? 1 : 0, Date.now());
|
|
81
|
+
}
|
|
82
|
+
recordTurn(turn) {
|
|
83
|
+
this.ensureSession(turn.sessionId, turn.sessionId, turn.healed);
|
|
84
|
+
const stmt = this.db.prepare(`
|
|
85
|
+
INSERT INTO turns (
|
|
86
|
+
session_id, turn_index, timestamp_ms, provider, endpoint, model,
|
|
87
|
+
status_code, latency_ms, healed, heal_changes_json, usage_json,
|
|
88
|
+
cost_usd, cache_hit_rate, wasted_usd, break_kind, diagnosis_json, raw_request_body
|
|
89
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
90
|
+
`);
|
|
91
|
+
const res = stmt.run(
|
|
92
|
+
turn.sessionId,
|
|
93
|
+
turn.turnIndex,
|
|
94
|
+
turn.timestampMs,
|
|
95
|
+
turn.provider,
|
|
96
|
+
turn.endpoint,
|
|
97
|
+
turn.model,
|
|
98
|
+
turn.statusCode,
|
|
99
|
+
turn.latencyMs,
|
|
100
|
+
turn.healed ? 1 : 0,
|
|
101
|
+
JSON.stringify(turn.healChanges),
|
|
102
|
+
JSON.stringify(turn.usage),
|
|
103
|
+
turn.costUsd,
|
|
104
|
+
turn.diagnosis.cacheHitRate,
|
|
105
|
+
turn.diagnosis.wastedUsd,
|
|
106
|
+
turn.diagnosis.kind,
|
|
107
|
+
JSON.stringify(turn.diagnosis),
|
|
108
|
+
turn.rawRequestBody
|
|
109
|
+
);
|
|
110
|
+
return {
|
|
111
|
+
id: Number(res.lastInsertRowid),
|
|
112
|
+
...turn
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
listSessions() {
|
|
116
|
+
const rows = this.db.prepare(`
|
|
117
|
+
SELECT
|
|
118
|
+
s.id,
|
|
119
|
+
s.label,
|
|
120
|
+
s.command,
|
|
121
|
+
s.healed,
|
|
122
|
+
s.created_at_ms,
|
|
123
|
+
COUNT(t.id) AS turn_count,
|
|
124
|
+
AVG(CASE WHEN t.turn_index > 1 THEN t.cache_hit_rate END) AS avg_cache_hit_rate,
|
|
125
|
+
SUM(t.cost_usd) AS total_cost_usd,
|
|
126
|
+
SUM(t.wasted_usd) AS total_wasted_usd,
|
|
127
|
+
SUM(CASE WHEN t.break_kind NOT IN ('NONE', 'FIRST_TURN') THEN 1 ELSE 0 END) AS break_count
|
|
128
|
+
FROM sessions s
|
|
129
|
+
LEFT JOIN turns t ON t.session_id = s.id
|
|
130
|
+
GROUP BY s.id
|
|
131
|
+
ORDER BY s.created_at_ms DESC
|
|
132
|
+
`).all();
|
|
133
|
+
return rows.map((r) => ({
|
|
134
|
+
id: r.id,
|
|
135
|
+
label: r.label,
|
|
136
|
+
command: r.command,
|
|
137
|
+
healed: r.healed === 1,
|
|
138
|
+
createdAtMs: r.created_at_ms,
|
|
139
|
+
turnCount: Number(r.turn_count ?? 0),
|
|
140
|
+
avgCacheHitRate: Number(r.avg_cache_hit_rate ?? 0),
|
|
141
|
+
totalCostUsd: Number(r.total_cost_usd ?? 0),
|
|
142
|
+
totalWastedUsd: Number(r.total_wasted_usd ?? 0),
|
|
143
|
+
breakCount: Number(r.break_count ?? 0)
|
|
144
|
+
}));
|
|
145
|
+
}
|
|
146
|
+
getSessionTurns(sessionId) {
|
|
147
|
+
const rows = this.db.prepare(`
|
|
148
|
+
SELECT
|
|
149
|
+
id, session_id, turn_index, timestamp_ms, provider, endpoint, model,
|
|
150
|
+
status_code, latency_ms, healed, heal_changes_json, usage_json,
|
|
151
|
+
cost_usd, diagnosis_json, raw_request_body
|
|
152
|
+
FROM turns
|
|
153
|
+
WHERE session_id = ?
|
|
154
|
+
ORDER BY turn_index ASC, id ASC
|
|
155
|
+
`).all(sessionId);
|
|
156
|
+
return rows.map(hydrateTurn);
|
|
157
|
+
}
|
|
158
|
+
getLastTurn(sessionId, model) {
|
|
159
|
+
const row = model ? this.db.prepare(`
|
|
160
|
+
SELECT
|
|
161
|
+
id, session_id, turn_index, timestamp_ms, provider, endpoint, model,
|
|
162
|
+
status_code, latency_ms, healed, heal_changes_json, usage_json,
|
|
163
|
+
cost_usd, diagnosis_json, raw_request_body
|
|
164
|
+
FROM turns
|
|
165
|
+
WHERE session_id = ? AND model = ? AND status_code >= 200 AND status_code < 300
|
|
166
|
+
ORDER BY turn_index DESC, id DESC
|
|
167
|
+
LIMIT 1
|
|
168
|
+
`).get(sessionId, model) : this.db.prepare(`
|
|
169
|
+
SELECT
|
|
170
|
+
id, session_id, turn_index, timestamp_ms, provider, endpoint, model,
|
|
171
|
+
status_code, latency_ms, healed, heal_changes_json, usage_json,
|
|
172
|
+
cost_usd, diagnosis_json, raw_request_body
|
|
173
|
+
FROM turns
|
|
174
|
+
WHERE session_id = ?
|
|
175
|
+
ORDER BY turn_index DESC, id DESC
|
|
176
|
+
LIMIT 1
|
|
177
|
+
`).get(sessionId);
|
|
178
|
+
return row ? hydrateTurn(row) : null;
|
|
179
|
+
}
|
|
180
|
+
getNextTurnIndex(sessionId) {
|
|
181
|
+
const row = this.db.prepare("SELECT MAX(turn_index) AS max_turn FROM turns WHERE session_id = ?").get(sessionId);
|
|
182
|
+
return Number(row?.max_turn ?? 0) + 1;
|
|
183
|
+
}
|
|
184
|
+
close() {
|
|
185
|
+
this.db.close();
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
function hydrateTurn(row) {
|
|
189
|
+
return {
|
|
190
|
+
id: Number(row.id),
|
|
191
|
+
sessionId: row.session_id,
|
|
192
|
+
turnIndex: Number(row.turn_index),
|
|
193
|
+
timestampMs: Number(row.timestamp_ms),
|
|
194
|
+
provider: row.provider,
|
|
195
|
+
endpoint: row.endpoint,
|
|
196
|
+
model: row.model,
|
|
197
|
+
statusCode: Number(row.status_code),
|
|
198
|
+
latencyMs: Number(row.latency_ms),
|
|
199
|
+
healed: row.healed === 1,
|
|
200
|
+
healChanges: JSON.parse(row.heal_changes_json),
|
|
201
|
+
usage: JSON.parse(row.usage_json),
|
|
202
|
+
costUsd: Number(row.cost_usd),
|
|
203
|
+
diagnosis: JSON.parse(row.diagnosis_json),
|
|
204
|
+
rawRequestBody: row.raw_request_body
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// src/proxy/server.ts
|
|
209
|
+
import http from "node:http";
|
|
210
|
+
import https from "node:https";
|
|
211
|
+
import {
|
|
212
|
+
brotliDecompressSync,
|
|
213
|
+
createBrotliDecompress,
|
|
214
|
+
createGunzip,
|
|
215
|
+
createInflate,
|
|
216
|
+
gunzipSync,
|
|
217
|
+
inflateSync
|
|
218
|
+
} from "node:zlib";
|
|
219
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
220
|
+
import { extname, join, resolve, sep } from "node:path";
|
|
221
|
+
import { fileURLToPath } from "node:url";
|
|
222
|
+
|
|
223
|
+
// src/providers/detect.ts
|
|
224
|
+
function detectProvider(urlPath, headers, isLocalUpstream) {
|
|
225
|
+
const cleanPath = urlPath.split("?")[0] || "/";
|
|
226
|
+
if (cleanPath.startsWith("/v1/messages") || headers["anthropic-version"] !== void 0) {
|
|
227
|
+
return "anthropic";
|
|
228
|
+
}
|
|
229
|
+
if (/^\/v1(?:beta)?\/models\/[^/]+:(?:streamGenerateContent|generateContent)/i.test(cleanPath) || headers["x-goog-api-key"] !== void 0) {
|
|
230
|
+
return "gemini";
|
|
231
|
+
}
|
|
232
|
+
if (isLocalUpstream) {
|
|
233
|
+
return "local-openai";
|
|
234
|
+
}
|
|
235
|
+
return "openai";
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// src/providers/anthropic.ts
|
|
239
|
+
function asRecord(v) {
|
|
240
|
+
return v !== null && typeof v === "object" && !Array.isArray(v) ? v : null;
|
|
241
|
+
}
|
|
242
|
+
function parseAnthropicUsage(bodyOrSseEvents) {
|
|
243
|
+
let inputTokens = 0;
|
|
244
|
+
let cacheReadTokens = 0;
|
|
245
|
+
let cacheWriteTokens = 0;
|
|
246
|
+
let outputTokens = 0;
|
|
247
|
+
const applyUsage = (u) => {
|
|
248
|
+
if (!u) return;
|
|
249
|
+
if (typeof u.input_tokens === "number") inputTokens = u.input_tokens;
|
|
250
|
+
if (typeof u.cache_read_input_tokens === "number") cacheReadTokens = u.cache_read_input_tokens;
|
|
251
|
+
if (typeof u.cache_creation_input_tokens === "number") cacheWriteTokens = u.cache_creation_input_tokens;
|
|
252
|
+
if (typeof u.output_tokens === "number") outputTokens = Math.max(outputTokens, u.output_tokens);
|
|
253
|
+
};
|
|
254
|
+
if (Array.isArray(bodyOrSseEvents)) {
|
|
255
|
+
for (const ev of bodyOrSseEvents) {
|
|
256
|
+
const rec = asRecord(ev);
|
|
257
|
+
if (!rec) continue;
|
|
258
|
+
if (rec.type === "message_start") {
|
|
259
|
+
const msg = asRecord(rec.message);
|
|
260
|
+
applyUsage(asRecord(msg?.usage));
|
|
261
|
+
} else if (rec.type === "message_delta") {
|
|
262
|
+
applyUsage(asRecord(rec.usage));
|
|
263
|
+
} else if (rec.usage) {
|
|
264
|
+
applyUsage(asRecord(rec.usage));
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
} else {
|
|
268
|
+
const rec = asRecord(bodyOrSseEvents);
|
|
269
|
+
if (rec?.usage) {
|
|
270
|
+
applyUsage(asRecord(rec.usage));
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return {
|
|
274
|
+
inputTokens,
|
|
275
|
+
cacheReadTokens,
|
|
276
|
+
cacheWriteTokens,
|
|
277
|
+
outputTokens,
|
|
278
|
+
totalPromptTokens: inputTokens + cacheReadTokens + cacheWriteTokens
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// src/providers/openai.ts
|
|
283
|
+
function asRecord2(v) {
|
|
284
|
+
return v !== null && typeof v === "object" && !Array.isArray(v) ? v : null;
|
|
285
|
+
}
|
|
286
|
+
function num(v) {
|
|
287
|
+
return typeof v === "number" && Number.isFinite(v) ? v : 0;
|
|
288
|
+
}
|
|
289
|
+
function parseOpenAiUsage(bodyOrSseEvents) {
|
|
290
|
+
let totalPrompt = 0;
|
|
291
|
+
let cacheRead = 0;
|
|
292
|
+
let outputTokens = 0;
|
|
293
|
+
const inspectObject = (obj) => {
|
|
294
|
+
if (!obj) return;
|
|
295
|
+
const responseObj = asRecord2(obj.response);
|
|
296
|
+
const usage = asRecord2(obj.usage) ?? asRecord2(responseObj?.usage);
|
|
297
|
+
const timings = asRecord2(obj.timings);
|
|
298
|
+
if (usage) {
|
|
299
|
+
const prompt = num(usage.prompt_tokens) || num(usage.input_tokens);
|
|
300
|
+
if (prompt > 0) totalPrompt = prompt;
|
|
301
|
+
const out = num(usage.completion_tokens) || num(usage.output_tokens);
|
|
302
|
+
if (out > 0) outputTokens = Math.max(outputTokens, out);
|
|
303
|
+
const promptDetails = asRecord2(usage.prompt_tokens_details) ?? asRecord2(usage.input_tokens_details);
|
|
304
|
+
const cached = num(promptDetails?.cached_tokens);
|
|
305
|
+
if (cached > 0) cacheRead = cached;
|
|
306
|
+
}
|
|
307
|
+
if (timings && typeof timings.cache_n === "number") {
|
|
308
|
+
cacheRead = Math.max(cacheRead, num(timings.cache_n));
|
|
309
|
+
if (totalPrompt === 0 && typeof timings.prompt_n === "number") {
|
|
310
|
+
totalPrompt = cacheRead + num(timings.prompt_n);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
if (Array.isArray(bodyOrSseEvents)) {
|
|
315
|
+
for (const ev of bodyOrSseEvents) {
|
|
316
|
+
inspectObject(asRecord2(ev));
|
|
317
|
+
}
|
|
318
|
+
} else {
|
|
319
|
+
inspectObject(asRecord2(bodyOrSseEvents));
|
|
320
|
+
}
|
|
321
|
+
const inputTokens = Math.max(0, totalPrompt - cacheRead);
|
|
322
|
+
return {
|
|
323
|
+
inputTokens,
|
|
324
|
+
cacheReadTokens: cacheRead,
|
|
325
|
+
cacheWriteTokens: 0,
|
|
326
|
+
outputTokens,
|
|
327
|
+
totalPromptTokens: totalPrompt
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// src/providers/gemini.ts
|
|
332
|
+
function asRecord3(v) {
|
|
333
|
+
return v !== null && typeof v === "object" && !Array.isArray(v) ? v : null;
|
|
334
|
+
}
|
|
335
|
+
function num2(v) {
|
|
336
|
+
return typeof v === "number" && Number.isFinite(v) ? v : 0;
|
|
337
|
+
}
|
|
338
|
+
function extractGeminiModel(urlPath) {
|
|
339
|
+
const cleanPath = urlPath.split("?")[0] || "";
|
|
340
|
+
const match = /\/v1(?:beta)?\/models\/([^/:]+)/i.exec(cleanPath);
|
|
341
|
+
return match?.[1] ?? "gemini-unknown";
|
|
342
|
+
}
|
|
343
|
+
function parseGeminiUsage(bodyOrSseEvents) {
|
|
344
|
+
let totalPrompt = 0;
|
|
345
|
+
let cacheRead = 0;
|
|
346
|
+
let outputTokens = 0;
|
|
347
|
+
const inspectObject = (obj) => {
|
|
348
|
+
if (!obj) return;
|
|
349
|
+
const meta = asRecord3(obj.usageMetadata);
|
|
350
|
+
if (!meta) return;
|
|
351
|
+
const p = num2(meta.promptTokenCount);
|
|
352
|
+
const c = num2(meta.cachedContentTokenCount);
|
|
353
|
+
const o = num2(meta.candidatesTokenCount);
|
|
354
|
+
if (p > 0) totalPrompt = Math.max(totalPrompt, p);
|
|
355
|
+
if (c > 0) cacheRead = Math.max(cacheRead, c);
|
|
356
|
+
if (o > 0) outputTokens = Math.max(outputTokens, o);
|
|
357
|
+
};
|
|
358
|
+
if (Array.isArray(bodyOrSseEvents)) {
|
|
359
|
+
for (const ev of bodyOrSseEvents) {
|
|
360
|
+
inspectObject(asRecord3(ev));
|
|
361
|
+
}
|
|
362
|
+
} else {
|
|
363
|
+
inspectObject(asRecord3(bodyOrSseEvents));
|
|
364
|
+
}
|
|
365
|
+
const inputTokens = Math.max(0, totalPrompt - cacheRead);
|
|
366
|
+
return {
|
|
367
|
+
inputTokens,
|
|
368
|
+
cacheReadTokens: cacheRead,
|
|
369
|
+
cacheWriteTokens: 0,
|
|
370
|
+
outputTokens,
|
|
371
|
+
totalPromptTokens: totalPrompt
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// src/diff/lcp.ts
|
|
376
|
+
var CONTEXT_BEFORE = 48;
|
|
377
|
+
var CONTEXT_AFTER = 96;
|
|
378
|
+
function sliceUtf8Safe(buf, center) {
|
|
379
|
+
let start = Math.max(0, center - CONTEXT_BEFORE);
|
|
380
|
+
let end = Math.min(buf.length, center + CONTEXT_AFTER);
|
|
381
|
+
while (start < end && (buf[start] & 192) === 128) {
|
|
382
|
+
start++;
|
|
383
|
+
}
|
|
384
|
+
while (end > start && end < buf.length && (buf[end] & 192) === 128) {
|
|
385
|
+
end--;
|
|
386
|
+
}
|
|
387
|
+
return buf.subarray(start, end).toString("utf8");
|
|
388
|
+
}
|
|
389
|
+
function findByteLcp(prev, curr) {
|
|
390
|
+
const minLen = Math.min(prev.length, curr.length);
|
|
391
|
+
let diffOffset = -1;
|
|
392
|
+
for (let i = 0; i < minLen; i++) {
|
|
393
|
+
if (prev[i] !== curr[i]) {
|
|
394
|
+
diffOffset = i;
|
|
395
|
+
break;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
if (diffOffset === -1) {
|
|
399
|
+
if (prev.length === curr.length) {
|
|
400
|
+
return { byteOffset: null, prevSnippet: "", currSnippet: "" };
|
|
401
|
+
}
|
|
402
|
+
diffOffset = minLen;
|
|
403
|
+
}
|
|
404
|
+
return {
|
|
405
|
+
byteOffset: diffOffset,
|
|
406
|
+
prevSnippet: sliceUtf8Safe(prev, diffOffset),
|
|
407
|
+
currSnippet: sliceUtf8Safe(curr, diffOffset)
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// src/diff/jsonpath.ts
|
|
412
|
+
var BYTE_SPACE = 32;
|
|
413
|
+
var BYTE_TAB = 9;
|
|
414
|
+
var BYTE_LF = 10;
|
|
415
|
+
var BYTE_CR = 13;
|
|
416
|
+
var BYTE_QUOTE = 34;
|
|
417
|
+
var BYTE_BACKSLASH = 92;
|
|
418
|
+
var BYTE_LBRACE = 123;
|
|
419
|
+
var BYTE_RBRACE = 125;
|
|
420
|
+
var BYTE_LBRACKET = 91;
|
|
421
|
+
var BYTE_RBRACKET = 93;
|
|
422
|
+
var BYTE_COLON = 58;
|
|
423
|
+
var BYTE_COMMA = 44;
|
|
424
|
+
function isWhitespace(b) {
|
|
425
|
+
return b === BYTE_SPACE || b === BYTE_TAB || b === BYTE_LF || b === BYTE_CR;
|
|
426
|
+
}
|
|
427
|
+
function formatStack(stack) {
|
|
428
|
+
let out = "$";
|
|
429
|
+
for (const frame of stack) {
|
|
430
|
+
if (frame.kind === "object") {
|
|
431
|
+
if (frame.currentKey !== null) {
|
|
432
|
+
if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(frame.currentKey)) {
|
|
433
|
+
out += `.${frame.currentKey}`;
|
|
434
|
+
} else {
|
|
435
|
+
out += `[${JSON.stringify(frame.currentKey)}]`;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
} else {
|
|
439
|
+
out += `[${frame.index}]`;
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
return out;
|
|
443
|
+
}
|
|
444
|
+
function readJsonString(buf, startQuoteIdx) {
|
|
445
|
+
let i = startQuoteIdx + 1;
|
|
446
|
+
while (i < buf.length) {
|
|
447
|
+
const b = buf[i];
|
|
448
|
+
if (b === BYTE_BACKSLASH) {
|
|
449
|
+
i += 2;
|
|
450
|
+
continue;
|
|
451
|
+
}
|
|
452
|
+
if (b === BYTE_QUOTE) {
|
|
453
|
+
const raw = buf.subarray(startQuoteIdx, i + 1).toString("utf8");
|
|
454
|
+
try {
|
|
455
|
+
return { value: JSON.parse(raw), endIdx: i };
|
|
456
|
+
} catch {
|
|
457
|
+
return { value: buf.subarray(startQuoteIdx + 1, i).toString("utf8"), endIdx: i };
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
i++;
|
|
461
|
+
}
|
|
462
|
+
return { value: buf.subarray(startQuoteIdx + 1).toString("utf8"), endIdx: buf.length - 1 };
|
|
463
|
+
}
|
|
464
|
+
function byteOffsetToJsonPath(buf, targetByteOffset) {
|
|
465
|
+
if (buf.length === 0 || targetByteOffset < 0) return null;
|
|
466
|
+
const clampedTarget = Math.min(targetByteOffset, buf.length - 1);
|
|
467
|
+
const stack = [];
|
|
468
|
+
let i = 0;
|
|
469
|
+
if (buf.length >= 3 && buf[0] === 239 && buf[1] === 187 && buf[2] === 191) {
|
|
470
|
+
i = 3;
|
|
471
|
+
}
|
|
472
|
+
while (i < buf.length) {
|
|
473
|
+
while (i < buf.length && isWhitespace(buf[i])) {
|
|
474
|
+
i++;
|
|
475
|
+
}
|
|
476
|
+
if (i >= buf.length) break;
|
|
477
|
+
const b = buf[i];
|
|
478
|
+
const top = stack[stack.length - 1];
|
|
479
|
+
if (b === BYTE_LBRACE) {
|
|
480
|
+
if (i >= clampedTarget) return formatStack(stack);
|
|
481
|
+
stack.push({ kind: "object", expect: "key", currentKey: null });
|
|
482
|
+
i++;
|
|
483
|
+
continue;
|
|
484
|
+
}
|
|
485
|
+
if (b === BYTE_RBRACE) {
|
|
486
|
+
if (i >= clampedTarget) return formatStack(stack);
|
|
487
|
+
stack.pop();
|
|
488
|
+
const parent = stack[stack.length - 1];
|
|
489
|
+
if (parent?.kind === "object" && parent.expect === "value") parent.expect = "comma";
|
|
490
|
+
else if (parent?.kind === "array" && parent.expect === "value") parent.expect = "comma";
|
|
491
|
+
i++;
|
|
492
|
+
continue;
|
|
493
|
+
}
|
|
494
|
+
if (b === BYTE_LBRACKET) {
|
|
495
|
+
if (i >= clampedTarget) return formatStack(stack);
|
|
496
|
+
stack.push({ kind: "array", expect: "value", index: 0 });
|
|
497
|
+
i++;
|
|
498
|
+
continue;
|
|
499
|
+
}
|
|
500
|
+
if (b === BYTE_RBRACKET) {
|
|
501
|
+
if (i >= clampedTarget) return formatStack(stack);
|
|
502
|
+
stack.pop();
|
|
503
|
+
const parent = stack[stack.length - 1];
|
|
504
|
+
if (parent?.kind === "object" && parent.expect === "value") parent.expect = "comma";
|
|
505
|
+
else if (parent?.kind === "array" && parent.expect === "value") parent.expect = "comma";
|
|
506
|
+
i++;
|
|
507
|
+
continue;
|
|
508
|
+
}
|
|
509
|
+
if (b === BYTE_COLON) {
|
|
510
|
+
if (top?.kind === "object") {
|
|
511
|
+
top.expect = "value";
|
|
512
|
+
}
|
|
513
|
+
if (i >= clampedTarget) return formatStack(stack);
|
|
514
|
+
i++;
|
|
515
|
+
continue;
|
|
516
|
+
}
|
|
517
|
+
if (b === BYTE_COMMA) {
|
|
518
|
+
if (top?.kind === "object") {
|
|
519
|
+
top.expect = "key";
|
|
520
|
+
top.currentKey = null;
|
|
521
|
+
} else if (top?.kind === "array") {
|
|
522
|
+
top.index += 1;
|
|
523
|
+
top.expect = "value";
|
|
524
|
+
}
|
|
525
|
+
if (i >= clampedTarget) return formatStack(stack);
|
|
526
|
+
i++;
|
|
527
|
+
continue;
|
|
528
|
+
}
|
|
529
|
+
if (b === BYTE_QUOTE) {
|
|
530
|
+
const { value, endIdx } = readJsonString(buf, i);
|
|
531
|
+
if (top?.kind === "object" && top.expect === "key") {
|
|
532
|
+
top.currentKey = value;
|
|
533
|
+
top.expect = "colon";
|
|
534
|
+
if (clampedTarget >= i && clampedTarget <= endIdx) {
|
|
535
|
+
return formatStack(stack);
|
|
536
|
+
}
|
|
537
|
+
} else {
|
|
538
|
+
if (clampedTarget >= i && clampedTarget <= endIdx) {
|
|
539
|
+
return formatStack(stack);
|
|
540
|
+
}
|
|
541
|
+
if (top?.kind === "object" && top.expect === "value") top.expect = "comma";
|
|
542
|
+
else if (top?.kind === "array" && top.expect === "value") top.expect = "comma";
|
|
543
|
+
}
|
|
544
|
+
i = endIdx + 1;
|
|
545
|
+
continue;
|
|
546
|
+
}
|
|
547
|
+
const primStart = i;
|
|
548
|
+
while (i < buf.length && !isWhitespace(buf[i]) && buf[i] !== BYTE_COMMA && buf[i] !== BYTE_RBRACE && buf[i] !== BYTE_RBRACKET) {
|
|
549
|
+
i++;
|
|
550
|
+
}
|
|
551
|
+
const primEnd = i - 1;
|
|
552
|
+
if (clampedTarget >= primStart && clampedTarget <= primEnd) {
|
|
553
|
+
return formatStack(stack);
|
|
554
|
+
}
|
|
555
|
+
if (top?.kind === "object" && top.expect === "value") top.expect = "comma";
|
|
556
|
+
else if (top?.kind === "array" && top.expect === "value") top.expect = "comma";
|
|
557
|
+
}
|
|
558
|
+
return stack.length > 0 ? formatStack(stack) : "$";
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
// src/pricing.ts
|
|
562
|
+
var ZERO_RATES = {
|
|
563
|
+
inputPer1M: 0,
|
|
564
|
+
cacheReadPer1M: 0,
|
|
565
|
+
cacheWritePer1M: 0,
|
|
566
|
+
outputPer1M: 0
|
|
567
|
+
};
|
|
568
|
+
var MODEL_PRICING_TABLE = [
|
|
569
|
+
// Local / self-hosted provider prefixes always $0 even when proxying cloud-like names
|
|
570
|
+
{
|
|
571
|
+
match: /^(?:local\/|ollama\/|vllm\/)/i,
|
|
572
|
+
rates: ZERO_RATES
|
|
573
|
+
},
|
|
574
|
+
// Anthropic Claude
|
|
575
|
+
{
|
|
576
|
+
match: /claude-(?:opus-4|4-opus|3-opus)/i,
|
|
577
|
+
rates: { inputPer1M: 15, cacheReadPer1M: 1.5, cacheWritePer1M: 18.75, outputPer1M: 75 }
|
|
578
|
+
},
|
|
579
|
+
{
|
|
580
|
+
match: /claude-(?:sonnet-4|4-sonnet|3-[57]-sonnet)/i,
|
|
581
|
+
rates: { inputPer1M: 3, cacheReadPer1M: 0.3, cacheWritePer1M: 3.75, outputPer1M: 15 }
|
|
582
|
+
},
|
|
583
|
+
{
|
|
584
|
+
match: /claude-(?:haiku-4|4-haiku|3-5-haiku|3-haiku)/i,
|
|
585
|
+
rates: { inputPer1M: 0.8, cacheReadPer1M: 0.08, cacheWritePer1M: 1, outputPer1M: 4 }
|
|
586
|
+
},
|
|
587
|
+
// OpenAI GPT / o-series / Codex (check mini and codex variants before flagship gpt-5)
|
|
588
|
+
{
|
|
589
|
+
match: /(?:^|\/)(?:gpt-5(?:\.\d+)?(?:-[a-z0-9]+)*-mini|gpt-4\.1-mini|gpt-4o-mini|o4-mini|o3-mini|codex-mini)/i,
|
|
590
|
+
rates: { inputPer1M: 0.4, cacheReadPer1M: 0.1, cacheWritePer1M: 0.4, outputPer1M: 1.6 }
|
|
591
|
+
},
|
|
592
|
+
{
|
|
593
|
+
match: /(?:^|\/)(?:gpt-5(?:\.\d+)?-codex|o3|codex)/i,
|
|
594
|
+
rates: { inputPer1M: 2, cacheReadPer1M: 0.5, cacheWritePer1M: 2, outputPer1M: 8 }
|
|
595
|
+
},
|
|
596
|
+
{
|
|
597
|
+
match: /(?:^|\/)(?:gpt-5|gpt-4\.1|gpt-4o)(?!.*mini)/i,
|
|
598
|
+
rates: { inputPer1M: 2.5, cacheReadPer1M: 0.625, cacheWritePer1M: 2.5, outputPer1M: 10 }
|
|
599
|
+
},
|
|
600
|
+
// Google Gemini / Antigravity
|
|
601
|
+
{
|
|
602
|
+
match: /gemini-(?:4|3|2\.5)-pro|gemini-4-neon/i,
|
|
603
|
+
rates: { inputPer1M: 1.25, cacheReadPer1M: 0.3125, cacheWritePer1M: 1.25, outputPer1M: 10 }
|
|
604
|
+
},
|
|
605
|
+
{
|
|
606
|
+
match: /gemini-(?:4|3|2\.5|2\.0)-flash/i,
|
|
607
|
+
rates: { inputPer1M: 0.15, cacheReadPer1M: 0.0375, cacheWritePer1M: 0.15, outputPer1M: 0.6 }
|
|
608
|
+
},
|
|
609
|
+
// OSS self-hosted weights (llama.cpp, vLLM, Ollama, mlx-lm)
|
|
610
|
+
{
|
|
611
|
+
match: /(?:qwen|llama|deepseek|mistral|gemma|phi-|codestral)/i,
|
|
612
|
+
rates: ZERO_RATES
|
|
613
|
+
}
|
|
614
|
+
];
|
|
615
|
+
function lookupModelPricing(model) {
|
|
616
|
+
const normalized = (model || "").trim();
|
|
617
|
+
if (!normalized) return ZERO_RATES;
|
|
618
|
+
for (const entry of MODEL_PRICING_TABLE) {
|
|
619
|
+
if (entry.match.test(normalized)) {
|
|
620
|
+
return entry.rates;
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
return ZERO_RATES;
|
|
624
|
+
}
|
|
625
|
+
function estimateCost(model, usage, expectedCacheableTokens = 0) {
|
|
626
|
+
const rates = lookupModelPricing(model);
|
|
627
|
+
const totalPrompt = usage.totalPromptTokens > 0 ? usage.totalPromptTokens : usage.inputTokens + usage.cacheReadTokens + usage.cacheWriteTokens;
|
|
628
|
+
const cacheHitRate = totalPrompt > 0 ? Math.min(1, Math.max(0, usage.cacheReadTokens / totalPrompt)) : 0;
|
|
629
|
+
const costUsd = (usage.inputTokens * rates.inputPer1M + usage.cacheReadTokens * rates.cacheReadPer1M + usage.cacheWriteTokens * rates.cacheWritePer1M + usage.outputTokens * rates.outputPer1M) / 1e6;
|
|
630
|
+
let wastedUsd = 0;
|
|
631
|
+
if (expectedCacheableTokens > 0 && rates.inputPer1M > rates.cacheReadPer1M) {
|
|
632
|
+
const missedTokens = Math.max(0, Math.min(expectedCacheableTokens, totalPrompt) - usage.cacheReadTokens);
|
|
633
|
+
const rewroteTokens = Math.min(missedTokens, usage.cacheWriteTokens);
|
|
634
|
+
const plainUncachedTokens = Math.max(0, missedTokens - rewroteTokens);
|
|
635
|
+
wastedUsd = (rewroteTokens * Math.max(0, rates.cacheWritePer1M - rates.cacheReadPer1M) + plainUncachedTokens * Math.max(0, rates.inputPer1M - rates.cacheReadPer1M)) / 1e6;
|
|
636
|
+
}
|
|
637
|
+
return {
|
|
638
|
+
costUsd: Number.isFinite(costUsd) ? costUsd : 0,
|
|
639
|
+
wastedUsd: Number.isFinite(wastedUsd) ? wastedUsd : 0,
|
|
640
|
+
cacheHitRate: Number.isFinite(cacheHitRate) ? cacheHitRate : 0
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
// src/diff/diagnose.ts
|
|
645
|
+
var ANTHROPIC_DEFAULT_TTL_MS = 3e5;
|
|
646
|
+
var OPENAI_MIN_CACHE_TOKENS = 1024;
|
|
647
|
+
var GEMINI_FLASH_MIN_CACHE_TOKENS = 1024;
|
|
648
|
+
var GEMINI_PRO_MIN_CACHE_TOKENS = 2048;
|
|
649
|
+
function safeJsonParse(raw) {
|
|
650
|
+
try {
|
|
651
|
+
const parsed = JSON.parse(raw);
|
|
652
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
|
|
653
|
+
} catch {
|
|
654
|
+
return null;
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
function extractToolNames(provider, obj) {
|
|
658
|
+
if (!obj || !Array.isArray(obj.tools)) return [];
|
|
659
|
+
if (provider === "gemini") {
|
|
660
|
+
const names2 = [];
|
|
661
|
+
for (const block of obj.tools) {
|
|
662
|
+
if (block && typeof block === "object" && Array.isArray(block.functionDeclarations)) {
|
|
663
|
+
for (const decl of block.functionDeclarations) {
|
|
664
|
+
if (decl && typeof decl === "object" && typeof decl.name === "string") {
|
|
665
|
+
names2.push(decl.name);
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
return names2;
|
|
671
|
+
}
|
|
672
|
+
const names = [];
|
|
673
|
+
for (const tool of obj.tools) {
|
|
674
|
+
if (!tool || typeof tool !== "object") continue;
|
|
675
|
+
const rec = tool;
|
|
676
|
+
if (typeof rec.name === "string") {
|
|
677
|
+
names.push(rec.name);
|
|
678
|
+
} else if (rec.function && typeof rec.function === "object" && typeof rec.function.name === "string") {
|
|
679
|
+
names.push(rec.function.name);
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
return names;
|
|
683
|
+
}
|
|
684
|
+
function sameMultisetDifferentOrder(a, b) {
|
|
685
|
+
if (a.length === 0 || a.length !== b.length) return false;
|
|
686
|
+
let different = false;
|
|
687
|
+
for (let i = 0; i < a.length; i++) {
|
|
688
|
+
if (a[i] !== b[i]) {
|
|
689
|
+
different = true;
|
|
690
|
+
break;
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
if (!different) return false;
|
|
694
|
+
const sortedA = [...a].sort();
|
|
695
|
+
const sortedB = [...b].sort();
|
|
696
|
+
return sortedA.every((v, idx) => v === sortedB[idx]);
|
|
697
|
+
}
|
|
698
|
+
function isOnlyAppendedTurn(prevObj, currObj, jsonPath) {
|
|
699
|
+
if (!prevObj || !currObj || !jsonPath) return false;
|
|
700
|
+
const key = Array.isArray(prevObj.messages) ? "messages" : Array.isArray(prevObj.contents) ? "contents" : Array.isArray(prevObj.input) ? "input" : null;
|
|
701
|
+
if (!key) return false;
|
|
702
|
+
const prevLen = prevObj[key].length;
|
|
703
|
+
const match = new RegExp(`^\\$\\.${key}\\[(\\d+)\\]`).exec(jsonPath);
|
|
704
|
+
if (!match) {
|
|
705
|
+
return jsonPath === `$.${key}` && Array.isArray(currObj[key]) && currObj[key].length > prevLen;
|
|
706
|
+
}
|
|
707
|
+
return Number(match[1]) >= prevLen;
|
|
708
|
+
}
|
|
709
|
+
function diagnoseCacheBreak(params) {
|
|
710
|
+
const { provider, prevTurn, currBody, currModel, currTimestampMs, currUsage } = params;
|
|
711
|
+
const expectedCacheable = prevTurn ? prevTurn.usage.totalPromptTokens : 0;
|
|
712
|
+
const { cacheHitRate, wastedUsd } = estimateCost(currModel, currUsage, expectedCacheable);
|
|
713
|
+
if (!prevTurn) {
|
|
714
|
+
return {
|
|
715
|
+
kind: "FIRST_TURN",
|
|
716
|
+
byteOffset: null,
|
|
717
|
+
jsonPath: null,
|
|
718
|
+
prevSnippet: "",
|
|
719
|
+
currSnippet: "",
|
|
720
|
+
summary: "Initial turn \u2014 warming prompt cache prefix.",
|
|
721
|
+
wastedUsd: 0,
|
|
722
|
+
cacheHitRate
|
|
723
|
+
};
|
|
724
|
+
}
|
|
725
|
+
const prevBuf = Buffer.from(prevTurn.rawRequestBody, "utf8");
|
|
726
|
+
const lcp = findByteLcp(prevBuf, currBody);
|
|
727
|
+
const jsonPath = lcp.byteOffset !== null ? byteOffsetToJsonPath(currBody, lcp.byteOffset) : null;
|
|
728
|
+
const prevObj = safeJsonParse(prevTurn.rawRequestBody);
|
|
729
|
+
const currObj = safeJsonParse(currBody.toString("utf8"));
|
|
730
|
+
const isHealthyHit = currUsage.cacheReadTokens > 0 && (expectedCacheable === 0 || currUsage.cacheReadTokens >= expectedCacheable * 0.6);
|
|
731
|
+
if (isHealthyHit) {
|
|
732
|
+
return {
|
|
733
|
+
kind: "NONE",
|
|
734
|
+
byteOffset: lcp.byteOffset,
|
|
735
|
+
jsonPath,
|
|
736
|
+
prevSnippet: lcp.prevSnippet,
|
|
737
|
+
currSnippet: lcp.currSnippet,
|
|
738
|
+
summary: `Cache hit (${Math.round(cacheHitRate * 100)}%) \u2014 prefix stayed stable.`,
|
|
739
|
+
wastedUsd: 0,
|
|
740
|
+
cacheHitRate
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
let kind = "UNKNOWN";
|
|
744
|
+
let summary = `Cache miss at byte ${lcp.byteOffset ?? 0} (${jsonPath ?? "$"}).`;
|
|
745
|
+
if (currModel !== prevTurn.model) {
|
|
746
|
+
kind = "MODEL_CHANGED";
|
|
747
|
+
summary = `Model switched from ${prevTurn.model} to ${currModel}, invalidating KV prefix.`;
|
|
748
|
+
} else if (provider === "openai" && currUsage.totalPromptTokens > 0 && currUsage.totalPromptTokens < OPENAI_MIN_CACHE_TOKENS || provider === "gemini" && currUsage.totalPromptTokens > 0 && currUsage.totalPromptTokens < (/flash/i.test(currModel) ? GEMINI_FLASH_MIN_CACHE_TOKENS : GEMINI_PRO_MIN_CACHE_TOKENS)) {
|
|
749
|
+
kind = "PREFIX_TOO_SHORT";
|
|
750
|
+
summary = `Prompt (${currUsage.totalPromptTokens} tokens) is below ${provider} minimum implicit-cache prefix threshold.`;
|
|
751
|
+
} else if (jsonPath?.startsWith("$.tools")) {
|
|
752
|
+
const prevTools = extractToolNames(provider, prevObj);
|
|
753
|
+
const currTools = extractToolNames(provider, currObj);
|
|
754
|
+
if (sameMultisetDifferentOrder(prevTools, currTools)) {
|
|
755
|
+
kind = "TOOL_REORDER";
|
|
756
|
+
summary = `Tool definitions reordered at ${jsonPath} (byte ${lcp.byteOffset}). Enable --heal to sort tools deterministically.`;
|
|
757
|
+
} else {
|
|
758
|
+
kind = "TOOL_MUTATED";
|
|
759
|
+
summary = `Tool schema or description mutated at ${jsonPath} (byte ${lcp.byteOffset}).`;
|
|
760
|
+
}
|
|
761
|
+
} else if (jsonPath?.startsWith("$.system") || jsonPath?.startsWith("$.systemInstruction") || jsonPath?.startsWith("$.instructions") || jsonPath === "$.messages[0]" || jsonPath?.startsWith("$.messages[0].") || jsonPath === "$.input[0]" || jsonPath?.startsWith("$.input[0].")) {
|
|
762
|
+
kind = "VOLATILE_SYSTEM";
|
|
763
|
+
summary = `System prompt changed at ${jsonPath} (byte ${lcp.byteOffset}) \u2014 check for timestamps, UUIDs, or dynamic state.`;
|
|
764
|
+
} else if ((lcp.byteOffset === null || isOnlyAppendedTurn(prevObj, currObj, jsonPath)) && currUsage.cacheReadTokens === 0 && currTimestampMs - prevTurn.timestampMs > ANTHROPIC_DEFAULT_TTL_MS) {
|
|
765
|
+
kind = "TTL_EXPIRED";
|
|
766
|
+
const gapSec = Math.round((currTimestampMs - prevTurn.timestampMs) / 1e3);
|
|
767
|
+
summary = `Prefix bytes matched, but ${gapSec}s elapsed since previous turn (>5m cache TTL).`;
|
|
768
|
+
} else if (!isOnlyAppendedTurn(prevObj, currObj, jsonPath) && (jsonPath?.startsWith("$.messages[") || jsonPath?.startsWith("$.contents[") || jsonPath?.startsWith("$.input["))) {
|
|
769
|
+
kind = "HISTORY_MUTATED";
|
|
770
|
+
summary = `Earlier conversation history mutated at ${jsonPath} (byte ${lcp.byteOffset}).`;
|
|
771
|
+
}
|
|
772
|
+
return {
|
|
773
|
+
kind,
|
|
774
|
+
byteOffset: lcp.byteOffset,
|
|
775
|
+
jsonPath,
|
|
776
|
+
prevSnippet: lcp.prevSnippet,
|
|
777
|
+
currSnippet: lcp.currSnippet,
|
|
778
|
+
summary,
|
|
779
|
+
wastedUsd: kind === "PREFIX_TOO_SHORT" ? 0 : wastedUsd,
|
|
780
|
+
cacheHitRate
|
|
781
|
+
};
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
// src/heal/canonicalize.ts
|
|
785
|
+
function compareCodeUnit(a, b) {
|
|
786
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
787
|
+
}
|
|
788
|
+
function compareCanonicalKey(a, b) {
|
|
789
|
+
if (a === b) return 0;
|
|
790
|
+
if (a === "name") return -1;
|
|
791
|
+
if (b === "name") return 1;
|
|
792
|
+
return a < b ? -1 : 1;
|
|
793
|
+
}
|
|
794
|
+
function sortObjectKeysDeep(value) {
|
|
795
|
+
if (Array.isArray(value)) {
|
|
796
|
+
return value.map(sortObjectKeysDeep);
|
|
797
|
+
}
|
|
798
|
+
if (value !== null && typeof value === "object") {
|
|
799
|
+
const record = value;
|
|
800
|
+
const sorted = {};
|
|
801
|
+
for (const key of Object.keys(record).sort(compareCanonicalKey)) {
|
|
802
|
+
sorted[key] = sortObjectKeysDeep(record[key]);
|
|
803
|
+
}
|
|
804
|
+
return sorted;
|
|
805
|
+
}
|
|
806
|
+
return value;
|
|
807
|
+
}
|
|
808
|
+
function getToolSortKey(tool) {
|
|
809
|
+
if (!tool || typeof tool !== "object") return "";
|
|
810
|
+
const rec = tool;
|
|
811
|
+
if (typeof rec.name === "string") return rec.name;
|
|
812
|
+
if (rec.function && typeof rec.function === "object" && typeof rec.function.name === "string") {
|
|
813
|
+
return rec.function.name;
|
|
814
|
+
}
|
|
815
|
+
return "";
|
|
816
|
+
}
|
|
817
|
+
function healRequestPayload(provider, rawBody) {
|
|
818
|
+
let parsed;
|
|
819
|
+
try {
|
|
820
|
+
parsed = JSON.parse(rawBody.toString("utf8"));
|
|
821
|
+
} catch {
|
|
822
|
+
return { body: rawBody, changes: [] };
|
|
823
|
+
}
|
|
824
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
825
|
+
return { body: rawBody, changes: [] };
|
|
826
|
+
}
|
|
827
|
+
const root = parsed;
|
|
828
|
+
const changes = [];
|
|
829
|
+
if (Array.isArray(root.tools) && root.tools.length > 0) {
|
|
830
|
+
const toolsArr = root.tools;
|
|
831
|
+
if (provider === "gemini") {
|
|
832
|
+
const beforeTools = JSON.stringify(toolsArr);
|
|
833
|
+
let declCount = 0;
|
|
834
|
+
root.tools = toolsArr.map((entry) => {
|
|
835
|
+
if (!entry || typeof entry !== "object") return entry;
|
|
836
|
+
const block = { ...entry };
|
|
837
|
+
if (Array.isArray(block.functionDeclarations)) {
|
|
838
|
+
const canonicalDecls = [...block.functionDeclarations].map(sortObjectKeysDeep).sort((a, b) => compareCodeUnit(getToolSortKey(a), getToolSortKey(b)));
|
|
839
|
+
declCount += canonicalDecls.length;
|
|
840
|
+
block.functionDeclarations = canonicalDecls;
|
|
841
|
+
}
|
|
842
|
+
return sortObjectKeysDeep(block);
|
|
843
|
+
});
|
|
844
|
+
if (JSON.stringify(root.tools) !== beforeTools) {
|
|
845
|
+
changes.push(`canonicalized ${declCount || toolsArr.length} Gemini tool definitions`);
|
|
846
|
+
}
|
|
847
|
+
} else {
|
|
848
|
+
const beforeTools = JSON.stringify(toolsArr);
|
|
849
|
+
let trailingCacheControl = void 0;
|
|
850
|
+
const strippedTools = toolsArr.map((t, idx) => {
|
|
851
|
+
if (provider === "anthropic" && idx === toolsArr.length - 1 && t && typeof t === "object" && "cache_control" in t) {
|
|
852
|
+
const copy = { ...t };
|
|
853
|
+
trailingCacheControl = copy.cache_control;
|
|
854
|
+
delete copy.cache_control;
|
|
855
|
+
return copy;
|
|
856
|
+
}
|
|
857
|
+
return t;
|
|
858
|
+
});
|
|
859
|
+
const canonicalTools = strippedTools.map(sortObjectKeysDeep).sort((a, b) => compareCodeUnit(getToolSortKey(a), getToolSortKey(b)));
|
|
860
|
+
if (trailingCacheControl !== void 0 && canonicalTools.length > 0) {
|
|
861
|
+
const lastIdx = canonicalTools.length - 1;
|
|
862
|
+
const lastTool = canonicalTools[lastIdx];
|
|
863
|
+
if (lastTool && typeof lastTool === "object" && !Array.isArray(lastTool)) {
|
|
864
|
+
canonicalTools[lastIdx] = sortObjectKeysDeep({
|
|
865
|
+
...lastTool,
|
|
866
|
+
cache_control: trailingCacheControl
|
|
867
|
+
});
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
root.tools = canonicalTools;
|
|
871
|
+
if (JSON.stringify(canonicalTools) !== beforeTools) {
|
|
872
|
+
changes.push(`canonicalized ${canonicalTools.length} tools and schema keys`);
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
const serialized = Buffer.from(JSON.stringify(root), "utf8");
|
|
877
|
+
if (!serialized.equals(rawBody)) {
|
|
878
|
+
if (changes.length === 0) {
|
|
879
|
+
changes.push("normalized JSON whitespace for deterministic prefix");
|
|
880
|
+
}
|
|
881
|
+
return { body: serialized, changes };
|
|
882
|
+
}
|
|
883
|
+
return { body: rawBody, changes: [] };
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
// src/proxy/sse.ts
|
|
887
|
+
import { StringDecoder } from "node:string_decoder";
|
|
888
|
+
var SseTeeParser = class {
|
|
889
|
+
decoder = new StringDecoder("utf8");
|
|
890
|
+
buffer = "";
|
|
891
|
+
events = [];
|
|
892
|
+
push(chunk) {
|
|
893
|
+
this.buffer += this.decoder.write(chunk);
|
|
894
|
+
this.drainCompleteFrames();
|
|
895
|
+
}
|
|
896
|
+
finish() {
|
|
897
|
+
this.buffer += this.decoder.end();
|
|
898
|
+
this.drainCompleteFrames();
|
|
899
|
+
if (this.buffer.trim().length > 0) {
|
|
900
|
+
this.parseFrame(this.buffer);
|
|
901
|
+
this.buffer = "";
|
|
902
|
+
}
|
|
903
|
+
return this.events;
|
|
904
|
+
}
|
|
905
|
+
drainCompleteFrames() {
|
|
906
|
+
let match;
|
|
907
|
+
const sep2 = /\r?\n\r?\n/;
|
|
908
|
+
while ((match = sep2.exec(this.buffer)) !== null) {
|
|
909
|
+
const frame = this.buffer.slice(0, match.index);
|
|
910
|
+
this.buffer = this.buffer.slice(match.index + match[0].length);
|
|
911
|
+
this.parseFrame(frame);
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
parseFrame(frame) {
|
|
915
|
+
const dataLines = [];
|
|
916
|
+
for (const line of frame.split(/\r?\n/)) {
|
|
917
|
+
if (line.startsWith("data:")) {
|
|
918
|
+
dataLines.push(line.slice(5).trimStart());
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
if (dataLines.length === 0) return;
|
|
922
|
+
const joined = dataLines.join("\n").trim();
|
|
923
|
+
if (!joined || joined === "[DONE]") return;
|
|
924
|
+
try {
|
|
925
|
+
this.events.push(JSON.parse(joined));
|
|
926
|
+
} catch {
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
};
|
|
930
|
+
|
|
931
|
+
// src/proxy/server.ts
|
|
932
|
+
var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
|
|
933
|
+
"connection",
|
|
934
|
+
"keep-alive",
|
|
935
|
+
"proxy-authenticate",
|
|
936
|
+
"proxy-authorization",
|
|
937
|
+
"te",
|
|
938
|
+
"trailer",
|
|
939
|
+
"transfer-encoding",
|
|
940
|
+
"upgrade",
|
|
941
|
+
"host"
|
|
942
|
+
]);
|
|
943
|
+
var MIME_TYPES = {
|
|
944
|
+
".html": "text/html; charset=utf-8",
|
|
945
|
+
".js": "application/javascript; charset=utf-8",
|
|
946
|
+
".css": "text/css; charset=utf-8",
|
|
947
|
+
".svg": "image/svg+xml",
|
|
948
|
+
".json": "application/json; charset=utf-8",
|
|
949
|
+
".png": "image/png",
|
|
950
|
+
".ico": "image/x-icon"
|
|
951
|
+
};
|
|
952
|
+
var NON_GENERATION_PATH_RE = /(?:\/count_tokens|:countTokens|\/embeddings)\b/i;
|
|
953
|
+
function normalizeIncomingUrl(rawUrl) {
|
|
954
|
+
const qIdx = rawUrl.indexOf("?");
|
|
955
|
+
const rawPath = qIdx >= 0 ? rawUrl.slice(0, qIdx) : rawUrl;
|
|
956
|
+
const search = qIdx >= 0 ? rawUrl.slice(qIdx) : "";
|
|
957
|
+
let pathname = rawPath.replace(/^\/+/, "/");
|
|
958
|
+
pathname = pathname.replace(/^\/v1\/v1(\/|$)/, "/v1$1");
|
|
959
|
+
return { pathname, search, normalized: `${pathname}${search}` };
|
|
960
|
+
}
|
|
961
|
+
function buildUpstreamUrl(upstreamBase, pathname, search) {
|
|
962
|
+
const base = new URL(upstreamBase);
|
|
963
|
+
const basePath = base.pathname.replace(/\/+$/, "");
|
|
964
|
+
let reqPath = pathname;
|
|
965
|
+
if (basePath.endsWith("/v1") && (reqPath === "/v1" || reqPath.startsWith("/v1/"))) {
|
|
966
|
+
reqPath = reqPath.slice(3) || "/";
|
|
967
|
+
}
|
|
968
|
+
const joinedPath = `${basePath}${reqPath.startsWith("/") ? reqPath : `/${reqPath}`}`.replace(/\/{2,}/g, "/");
|
|
969
|
+
base.pathname = joinedPath;
|
|
970
|
+
base.search = search;
|
|
971
|
+
return base;
|
|
972
|
+
}
|
|
973
|
+
function decompressIfNeeded(buf, encodingHeader) {
|
|
974
|
+
const enc = (Array.isArray(encodingHeader) ? encodingHeader[0] : encodingHeader ?? "").toLowerCase().trim();
|
|
975
|
+
if (!enc || buf.length === 0) return buf;
|
|
976
|
+
try {
|
|
977
|
+
if (enc.includes("gzip")) return gunzipSync(buf);
|
|
978
|
+
if (enc.includes("br")) return brotliDecompressSync(buf);
|
|
979
|
+
if (enc.includes("deflate")) return inflateSync(buf);
|
|
980
|
+
} catch {
|
|
981
|
+
return buf;
|
|
982
|
+
}
|
|
983
|
+
return buf;
|
|
984
|
+
}
|
|
985
|
+
function createStreamingDecompressor(encodingHeader) {
|
|
986
|
+
const enc = (Array.isArray(encodingHeader) ? encodingHeader[0] : encodingHeader ?? "").toLowerCase().trim();
|
|
987
|
+
if (!enc) return null;
|
|
988
|
+
if (enc.includes("gzip")) return createGunzip();
|
|
989
|
+
if (enc.includes("br")) return createBrotliDecompress();
|
|
990
|
+
if (enc.includes("deflate")) return createInflate();
|
|
991
|
+
return null;
|
|
992
|
+
}
|
|
993
|
+
function readStreamToBuffer(req) {
|
|
994
|
+
return new Promise((resolveBuf, reject) => {
|
|
995
|
+
const chunks = [];
|
|
996
|
+
req.on("data", (c) => chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c)));
|
|
997
|
+
req.on("end", () => resolveBuf(Buffer.concat(chunks)));
|
|
998
|
+
req.on("error", reject);
|
|
999
|
+
});
|
|
1000
|
+
}
|
|
1001
|
+
function extractModelFromRequest(provider, urlPath, bodyBuf) {
|
|
1002
|
+
if (provider === "gemini") {
|
|
1003
|
+
return extractGeminiModel(urlPath);
|
|
1004
|
+
}
|
|
1005
|
+
try {
|
|
1006
|
+
const parsed = JSON.parse(bodyBuf.toString("utf8"));
|
|
1007
|
+
if (typeof parsed.model === "string" && parsed.model.trim()) {
|
|
1008
|
+
return parsed.model.trim();
|
|
1009
|
+
}
|
|
1010
|
+
} catch {
|
|
1011
|
+
}
|
|
1012
|
+
return `${provider}-unknown`;
|
|
1013
|
+
}
|
|
1014
|
+
function parseProviderUsage(provider, payload) {
|
|
1015
|
+
if (provider === "anthropic") return parseAnthropicUsage(payload);
|
|
1016
|
+
if (provider === "gemini") return parseGeminiUsage(payload);
|
|
1017
|
+
return parseOpenAiUsage(payload);
|
|
1018
|
+
}
|
|
1019
|
+
function resolveDefaultUiDir() {
|
|
1020
|
+
const here = fileURLToPath(new URL(".", import.meta.url));
|
|
1021
|
+
const candidateA = join(here, "ui");
|
|
1022
|
+
if (existsSync(candidateA)) return candidateA;
|
|
1023
|
+
return join(here, "..", "..", "dist", "ui");
|
|
1024
|
+
}
|
|
1025
|
+
function resolveUpstreamBase(provider, opts) {
|
|
1026
|
+
if (provider === "anthropic") return opts.upstreamAnthropic ?? "https://api.anthropic.com";
|
|
1027
|
+
if (provider === "gemini") return opts.upstreamGemini ?? "https://generativelanguage.googleapis.com";
|
|
1028
|
+
if (provider === "local-openai" && opts.upstreamLocal) return opts.upstreamLocal;
|
|
1029
|
+
return opts.upstreamOpenAi ?? "https://api.openai.com";
|
|
1030
|
+
}
|
|
1031
|
+
async function createProxyServer(opts) {
|
|
1032
|
+
const host = opts.host ?? "127.0.0.1";
|
|
1033
|
+
const resolvedUiDir = resolve(opts.uiDir ?? resolveDefaultUiDir());
|
|
1034
|
+
const uiDirPrefix = resolvedUiDir.endsWith(sep) ? resolvedUiDir : `${resolvedUiDir}${sep}`;
|
|
1035
|
+
const sseClients = /* @__PURE__ */ new Set();
|
|
1036
|
+
const broadcastEvent = (payload) => {
|
|
1037
|
+
const msg = `data: ${JSON.stringify(payload)}
|
|
1038
|
+
|
|
1039
|
+
`;
|
|
1040
|
+
for (const client of sseClients) {
|
|
1041
|
+
if (client.writableEnded || client.destroyed) {
|
|
1042
|
+
sseClients.delete(client);
|
|
1043
|
+
continue;
|
|
1044
|
+
}
|
|
1045
|
+
client.write(msg);
|
|
1046
|
+
}
|
|
1047
|
+
};
|
|
1048
|
+
const serveUiAsset = (reqPath, res) => {
|
|
1049
|
+
let decodedPath;
|
|
1050
|
+
try {
|
|
1051
|
+
decodedPath = decodeURIComponent(reqPath);
|
|
1052
|
+
} catch {
|
|
1053
|
+
res.writeHead(400);
|
|
1054
|
+
res.end("Bad Request");
|
|
1055
|
+
return;
|
|
1056
|
+
}
|
|
1057
|
+
const stripped = decodedPath.replace(/^\/__kvdiff\/?/, "/");
|
|
1058
|
+
const rel = stripped === "/" || stripped === "" ? "index.html" : stripped.replace(/^\/+/, "");
|
|
1059
|
+
const safePath = resolve(resolvedUiDir, rel);
|
|
1060
|
+
if (safePath !== resolvedUiDir && !safePath.startsWith(uiDirPrefix)) {
|
|
1061
|
+
res.writeHead(403);
|
|
1062
|
+
res.end("Forbidden");
|
|
1063
|
+
return;
|
|
1064
|
+
}
|
|
1065
|
+
const target = existsSync(safePath) && statSync(safePath).isFile() ? safePath : join(resolvedUiDir, "index.html");
|
|
1066
|
+
if (!existsSync(target)) {
|
|
1067
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
1068
|
+
res.end(
|
|
1069
|
+
`<!doctype html><html><body style="font-family:monospace;background:#0d1117;color:#c9d1d9;padding:24px"><h2>kvdiff proxy running</h2><p>UI bundle not built yet. Run <code>npm run build</code>.</p></body></html>`
|
|
1070
|
+
);
|
|
1071
|
+
return;
|
|
1072
|
+
}
|
|
1073
|
+
const ext = extname(target).toLowerCase();
|
|
1074
|
+
res.writeHead(200, { "content-type": MIME_TYPES[ext] ?? "application/octet-stream" });
|
|
1075
|
+
res.end(readFileSync(target));
|
|
1076
|
+
};
|
|
1077
|
+
const server = http.createServer(async (req, res) => {
|
|
1078
|
+
res.on("error", () => {
|
|
1079
|
+
});
|
|
1080
|
+
try {
|
|
1081
|
+
const { pathname, search, normalized } = normalizeIncomingUrl(req.url ?? "/");
|
|
1082
|
+
if (pathname === "/__kvdiff/api/sessions" && req.method === "GET") {
|
|
1083
|
+
res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
|
|
1084
|
+
res.end(JSON.stringify(opts.store.listSessions()));
|
|
1085
|
+
return;
|
|
1086
|
+
}
|
|
1087
|
+
const turnsMatch = /^\/__kvdiff\/api\/sessions\/([^/]+)\/turns$/.exec(pathname);
|
|
1088
|
+
if (turnsMatch && req.method === "GET") {
|
|
1089
|
+
let sessionId2;
|
|
1090
|
+
try {
|
|
1091
|
+
sessionId2 = decodeURIComponent(turnsMatch[1]);
|
|
1092
|
+
} catch {
|
|
1093
|
+
res.writeHead(400, { "content-type": "application/json; charset=utf-8" });
|
|
1094
|
+
res.end(JSON.stringify({ error: "invalid_session_id" }));
|
|
1095
|
+
return;
|
|
1096
|
+
}
|
|
1097
|
+
res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
|
|
1098
|
+
res.end(JSON.stringify(opts.store.getSessionTurns(sessionId2)));
|
|
1099
|
+
return;
|
|
1100
|
+
}
|
|
1101
|
+
if (pathname === "/__kvdiff/api/events" && req.method === "GET") {
|
|
1102
|
+
res.writeHead(200, {
|
|
1103
|
+
"content-type": "text/event-stream",
|
|
1104
|
+
"cache-control": "no-cache",
|
|
1105
|
+
connection: "keep-alive"
|
|
1106
|
+
});
|
|
1107
|
+
res.write(`data: ${JSON.stringify({ type: "connected" })}
|
|
1108
|
+
|
|
1109
|
+
`);
|
|
1110
|
+
sseClients.add(res);
|
|
1111
|
+
const dropClient = () => sseClients.delete(res);
|
|
1112
|
+
req.on("close", dropClient);
|
|
1113
|
+
res.on("close", dropClient);
|
|
1114
|
+
res.on("error", dropClient);
|
|
1115
|
+
return;
|
|
1116
|
+
}
|
|
1117
|
+
if (req.method === "GET" && (pathname === "/" || pathname.startsWith("/__kvdiff") || pathname.startsWith("/assets/"))) {
|
|
1118
|
+
serveUiAsset(pathname, res);
|
|
1119
|
+
return;
|
|
1120
|
+
}
|
|
1121
|
+
const startedAt = Date.now();
|
|
1122
|
+
const rawReqBuf = await readStreamToBuffer(req);
|
|
1123
|
+
const inspectReqBuf = decompressIfNeeded(rawReqBuf, req.headers["content-encoding"]);
|
|
1124
|
+
const provider = detectProvider(normalized, req.headers, Boolean(opts.upstreamLocal));
|
|
1125
|
+
const upstreamBase = resolveUpstreamBase(provider, opts);
|
|
1126
|
+
const upstreamUrl = buildUpstreamUrl(upstreamBase, pathname, search);
|
|
1127
|
+
let forwardReqBuf = rawReqBuf;
|
|
1128
|
+
let healed = false;
|
|
1129
|
+
let healChanges = [];
|
|
1130
|
+
let recordedReqBuf = inspectReqBuf;
|
|
1131
|
+
if (opts.heal && inspectReqBuf.length > 0 && req.method === "POST") {
|
|
1132
|
+
const healRes = healRequestPayload(provider, inspectReqBuf);
|
|
1133
|
+
if (healRes.changes.length > 0) {
|
|
1134
|
+
forwardReqBuf = healRes.body;
|
|
1135
|
+
recordedReqBuf = healRes.body;
|
|
1136
|
+
healed = true;
|
|
1137
|
+
healChanges = healRes.changes;
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
const forwardHeaders = {};
|
|
1141
|
+
for (const [k, v] of Object.entries(req.headers)) {
|
|
1142
|
+
if (v === void 0) continue;
|
|
1143
|
+
const lower = k.toLowerCase();
|
|
1144
|
+
if (HOP_BY_HOP_HEADERS.has(lower)) continue;
|
|
1145
|
+
if (lower === "x-kvdiff-session") continue;
|
|
1146
|
+
if (healed && (lower === "content-encoding" || lower === "content-length")) continue;
|
|
1147
|
+
forwardHeaders[k] = v;
|
|
1148
|
+
}
|
|
1149
|
+
forwardHeaders["host"] = upstreamUrl.host;
|
|
1150
|
+
if (healed) {
|
|
1151
|
+
forwardHeaders["content-length"] = String(forwardReqBuf.length);
|
|
1152
|
+
}
|
|
1153
|
+
const sessionHeader = req.headers["x-kvdiff-session"];
|
|
1154
|
+
const sessionId = typeof sessionHeader === "string" && sessionHeader.trim() || opts.defaultSessionId;
|
|
1155
|
+
const transport = upstreamUrl.protocol === "https:" ? https : http;
|
|
1156
|
+
const upstreamReq = transport.request(
|
|
1157
|
+
upstreamUrl,
|
|
1158
|
+
{
|
|
1159
|
+
method: req.method,
|
|
1160
|
+
headers: forwardHeaders
|
|
1161
|
+
},
|
|
1162
|
+
(upstreamRes) => {
|
|
1163
|
+
const respHeaders = {};
|
|
1164
|
+
for (const [k, v] of Object.entries(upstreamRes.headers)) {
|
|
1165
|
+
if (v === void 0) continue;
|
|
1166
|
+
if (HOP_BY_HOP_HEADERS.has(k.toLowerCase())) continue;
|
|
1167
|
+
respHeaders[k] = v;
|
|
1168
|
+
}
|
|
1169
|
+
const statusCode = upstreamRes.statusCode ?? 502;
|
|
1170
|
+
res.writeHead(statusCode, respHeaders);
|
|
1171
|
+
const contentType = String(upstreamRes.headers["content-type"] ?? "").toLowerCase();
|
|
1172
|
+
const isSse = contentType.includes("text/event-stream");
|
|
1173
|
+
const sseParser = isSse ? new SseTeeParser() : null;
|
|
1174
|
+
const sseDecompressor = isSse ? createStreamingDecompressor(upstreamRes.headers["content-encoding"]) : null;
|
|
1175
|
+
let sseDecompressDone = null;
|
|
1176
|
+
if (sseParser && sseDecompressor) {
|
|
1177
|
+
sseDecompressDone = new Promise((resolveDone) => {
|
|
1178
|
+
sseDecompressor.on("data", (decChunk) => sseParser.push(decChunk));
|
|
1179
|
+
sseDecompressor.on("end", () => resolveDone());
|
|
1180
|
+
sseDecompressor.on("error", () => resolveDone());
|
|
1181
|
+
});
|
|
1182
|
+
}
|
|
1183
|
+
const respChunks = [];
|
|
1184
|
+
const maxBufferedBytes = 8 * 1024 * 1024;
|
|
1185
|
+
let respBytes = 0;
|
|
1186
|
+
upstreamRes.on("data", (chunk) => {
|
|
1187
|
+
if (!res.writableEnded && !res.destroyed) {
|
|
1188
|
+
res.write(chunk);
|
|
1189
|
+
}
|
|
1190
|
+
if (sseParser) {
|
|
1191
|
+
if (sseDecompressor) {
|
|
1192
|
+
sseDecompressor.write(chunk);
|
|
1193
|
+
} else {
|
|
1194
|
+
sseParser.push(chunk);
|
|
1195
|
+
}
|
|
1196
|
+
} else if (respBytes < maxBufferedBytes) {
|
|
1197
|
+
respChunks.push(chunk);
|
|
1198
|
+
respBytes += chunk.length;
|
|
1199
|
+
}
|
|
1200
|
+
});
|
|
1201
|
+
upstreamRes.on("end", async () => {
|
|
1202
|
+
if (!res.writableEnded) res.end();
|
|
1203
|
+
try {
|
|
1204
|
+
if (sseDecompressor) {
|
|
1205
|
+
sseDecompressor.end();
|
|
1206
|
+
await sseDecompressDone;
|
|
1207
|
+
}
|
|
1208
|
+
if (req.method !== "POST" || recordedReqBuf.length === 0 || NON_GENERATION_PATH_RE.test(pathname)) {
|
|
1209
|
+
return;
|
|
1210
|
+
}
|
|
1211
|
+
if (statusCode < 200 || statusCode >= 300) {
|
|
1212
|
+
return;
|
|
1213
|
+
}
|
|
1214
|
+
let parsedPayload = null;
|
|
1215
|
+
if (sseParser) {
|
|
1216
|
+
parsedPayload = sseParser.finish();
|
|
1217
|
+
} else {
|
|
1218
|
+
const rawResp = decompressIfNeeded(
|
|
1219
|
+
Buffer.concat(respChunks),
|
|
1220
|
+
upstreamRes.headers["content-encoding"]
|
|
1221
|
+
);
|
|
1222
|
+
try {
|
|
1223
|
+
parsedPayload = JSON.parse(rawResp.toString("utf8"));
|
|
1224
|
+
} catch {
|
|
1225
|
+
parsedPayload = null;
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
const model = extractModelFromRequest(provider, normalized, recordedReqBuf);
|
|
1229
|
+
const usage = parseProviderUsage(provider, parsedPayload);
|
|
1230
|
+
const prevTurn = opts.store.getLastTurn(sessionId, model);
|
|
1231
|
+
const turnIndex = opts.store.getNextTurnIndex(sessionId);
|
|
1232
|
+
const nowMs = Date.now();
|
|
1233
|
+
const diagnosis = diagnoseCacheBreak({
|
|
1234
|
+
provider,
|
|
1235
|
+
prevTurn,
|
|
1236
|
+
currBody: recordedReqBuf,
|
|
1237
|
+
currModel: model,
|
|
1238
|
+
currTimestampMs: nowMs,
|
|
1239
|
+
currUsage: usage
|
|
1240
|
+
});
|
|
1241
|
+
const { costUsd } = estimateCost(model, usage, prevTurn?.usage.totalPromptTokens ?? 0);
|
|
1242
|
+
const turn = opts.store.recordTurn({
|
|
1243
|
+
sessionId,
|
|
1244
|
+
turnIndex,
|
|
1245
|
+
timestampMs: nowMs,
|
|
1246
|
+
provider,
|
|
1247
|
+
endpoint: pathname,
|
|
1248
|
+
model,
|
|
1249
|
+
statusCode,
|
|
1250
|
+
latencyMs: nowMs - startedAt,
|
|
1251
|
+
healed,
|
|
1252
|
+
healChanges,
|
|
1253
|
+
usage,
|
|
1254
|
+
costUsd,
|
|
1255
|
+
diagnosis,
|
|
1256
|
+
rawRequestBody: recordedReqBuf.toString("utf8")
|
|
1257
|
+
});
|
|
1258
|
+
opts.onTurnRecorded?.(turn);
|
|
1259
|
+
broadcastEvent({ type: "turn", sessionId, turnId: turn.id, turnIndex: turn.turnIndex });
|
|
1260
|
+
} catch (persistErr) {
|
|
1261
|
+
process.stderr.write(`[kvdiff] warning: failed to record turn: ${persistErr.message}
|
|
1262
|
+
`);
|
|
1263
|
+
}
|
|
1264
|
+
});
|
|
1265
|
+
upstreamRes.on("error", () => {
|
|
1266
|
+
if (!res.writableEnded) res.end();
|
|
1267
|
+
});
|
|
1268
|
+
}
|
|
1269
|
+
);
|
|
1270
|
+
res.on("close", () => {
|
|
1271
|
+
if (!res.writableFinished) {
|
|
1272
|
+
upstreamReq.destroy();
|
|
1273
|
+
}
|
|
1274
|
+
});
|
|
1275
|
+
upstreamReq.on("error", (err) => {
|
|
1276
|
+
if (!res.headersSent) {
|
|
1277
|
+
res.writeHead(502, { "content-type": "application/json" });
|
|
1278
|
+
}
|
|
1279
|
+
if (!res.writableEnded) {
|
|
1280
|
+
res.end(JSON.stringify({ error: "kvdiff_upstream_error", message: err.message }));
|
|
1281
|
+
}
|
|
1282
|
+
});
|
|
1283
|
+
if (forwardReqBuf.length > 0) {
|
|
1284
|
+
upstreamReq.write(forwardReqBuf);
|
|
1285
|
+
}
|
|
1286
|
+
upstreamReq.end();
|
|
1287
|
+
} catch (err) {
|
|
1288
|
+
if (!res.headersSent) {
|
|
1289
|
+
res.writeHead(500, { "content-type": "application/json" });
|
|
1290
|
+
}
|
|
1291
|
+
if (!res.writableEnded) {
|
|
1292
|
+
res.end(JSON.stringify({ error: "kvdiff_proxy_error", message: err.message }));
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
});
|
|
1296
|
+
await new Promise((resolveListen, reject) => {
|
|
1297
|
+
server.once("error", reject);
|
|
1298
|
+
server.listen(opts.port, host, () => resolveListen());
|
|
1299
|
+
});
|
|
1300
|
+
const addr = server.address();
|
|
1301
|
+
if (!addr || typeof addr === "string") {
|
|
1302
|
+
throw new Error("Failed to resolve listening port");
|
|
1303
|
+
}
|
|
1304
|
+
return {
|
|
1305
|
+
server,
|
|
1306
|
+
port: addr.port,
|
|
1307
|
+
url: `http://${host}:${addr.port}`,
|
|
1308
|
+
close: async () => {
|
|
1309
|
+
for (const client of sseClients) {
|
|
1310
|
+
client.end();
|
|
1311
|
+
}
|
|
1312
|
+
sseClients.clear();
|
|
1313
|
+
server.closeIdleConnections?.();
|
|
1314
|
+
await new Promise((resolveClose) => server.close(() => resolveClose()));
|
|
1315
|
+
}
|
|
1316
|
+
};
|
|
1317
|
+
}
|
|
1318
|
+
|
|
1319
|
+
// src/demo/fixture.ts
|
|
1320
|
+
function buildMcpTools(shuffled) {
|
|
1321
|
+
const baseTools = [
|
|
1322
|
+
{ name: "bash_exec", description: "Execute a shell command in the workspace.", input_schema: { properties: { cmd: { type: "string" } }, type: "object" } },
|
|
1323
|
+
{ name: "edit_file", description: "Apply a surgical replacement edit to a file.", input_schema: { properties: { path: { type: "string" }, target: { type: "string" } }, type: "object" } },
|
|
1324
|
+
{ name: "git_diff", description: "Inspect unstaged and staged git hunks.", input_schema: { properties: { base: { type: "string" } }, type: "object" } },
|
|
1325
|
+
{ name: "git_status", description: "Check branch state and modified files.", input_schema: { properties: { short: { type: "boolean" } }, type: "object" } },
|
|
1326
|
+
{ name: "grep_search", description: "Search files with ripgrep regex.", input_schema: { properties: { query: { type: "string" } }, type: "object" } },
|
|
1327
|
+
{ name: "list_dir", description: "List directory contents and file sizes.", input_schema: { properties: { dir: { type: "string" } }, type: "object" } },
|
|
1328
|
+
{ name: "mcp_db_query", description: "Run read-only SQL query against staging Postgres.", input_schema: { properties: { sql: { type: "string" } }, type: "object" } },
|
|
1329
|
+
{ name: "mcp_db_schema", description: "Inspect table schemas and indexes.", input_schema: { properties: { table: { type: "string" } }, type: "object" } },
|
|
1330
|
+
{ name: "mcp_docker_logs", description: "Tail container logs from local Docker Compose.", input_schema: { properties: { service: { type: "string" } }, type: "object" } },
|
|
1331
|
+
{ name: "mcp_github_get_pr", description: "Fetch GitHub pull request metadata and diff.", input_schema: { properties: { pr: { type: "number" } }, type: "object" } },
|
|
1332
|
+
{ name: "mcp_github_list_issues", description: "List open issues in the repository.", input_schema: { properties: { label: { type: "string" } }, type: "object" } },
|
|
1333
|
+
{ name: "mcp_github_review", description: "Post inline review comments on a GitHub PR.", input_schema: { properties: { body: { type: "string" } }, type: "object" } },
|
|
1334
|
+
{ name: "mcp_linear_issue", description: "Read or update a Linear ticket status.", input_schema: { properties: { id: { type: "string" } }, type: "object" } },
|
|
1335
|
+
{ name: "mcp_playwright_snap", description: "Capture DOM snapshot from local dev server.", input_schema: { properties: { url: { type: "string" } }, type: "object" } },
|
|
1336
|
+
{ name: "mcp_sentry_errors", description: "Query recent production stack traces.", input_schema: { properties: { env: { type: "string" } }, type: "object" } }
|
|
1337
|
+
];
|
|
1338
|
+
if (!shuffled) return baseTools;
|
|
1339
|
+
const copy = [...baseTools];
|
|
1340
|
+
const [ghReview] = copy.splice(11, 1);
|
|
1341
|
+
const [ghPr] = copy.splice(9, 1);
|
|
1342
|
+
copy.splice(14, 0, ghReview);
|
|
1343
|
+
copy.splice(13, 0, ghPr);
|
|
1344
|
+
return copy;
|
|
1345
|
+
}
|
|
1346
|
+
function seedDemoSession(store) {
|
|
1347
|
+
const now = Date.now();
|
|
1348
|
+
const baseTs = now - 16 * 22e3;
|
|
1349
|
+
const sessionId = "demo-claude-mcp";
|
|
1350
|
+
store.createSession({
|
|
1351
|
+
id: sessionId,
|
|
1352
|
+
label: "claude-code \xB7 checkout-refactor (15 MCP tools)",
|
|
1353
|
+
command: "kvdiff -- claude",
|
|
1354
|
+
healed: false,
|
|
1355
|
+
createdAtMs: baseTs
|
|
1356
|
+
});
|
|
1357
|
+
const model = "claude-sonnet-4-5";
|
|
1358
|
+
const systemPrompt = "You are an expert TypeScript systems engineer working on the checkout-service monorepo. Follow strict TDD, avoid unverified assumptions, and keep database migrations reversible.";
|
|
1359
|
+
const messages = [];
|
|
1360
|
+
for (let turn = 1; turn <= 16; turn++) {
|
|
1361
|
+
messages.push({
|
|
1362
|
+
role: turn % 2 === 1 ? "user" : "assistant",
|
|
1363
|
+
content: turn === 1 ? "Audit checkout webhook idempotency and fix duplicate charge race condition." : `Turn ${turn}: inspected src/webhooks/stripe.ts and verified lock-key isolation.`
|
|
1364
|
+
});
|
|
1365
|
+
const isTurn14Bust = turn === 14;
|
|
1366
|
+
const isHealedTurn = turn >= 15;
|
|
1367
|
+
const rawPayload = Buffer.from(
|
|
1368
|
+
JSON.stringify({
|
|
1369
|
+
model,
|
|
1370
|
+
max_tokens: 4096,
|
|
1371
|
+
system: systemPrompt,
|
|
1372
|
+
tools: buildMcpTools(isTurn14Bust || isHealedTurn),
|
|
1373
|
+
messages: [...messages]
|
|
1374
|
+
}),
|
|
1375
|
+
"utf8"
|
|
1376
|
+
);
|
|
1377
|
+
let effectiveBody = rawPayload;
|
|
1378
|
+
let healed = false;
|
|
1379
|
+
let healChanges = [];
|
|
1380
|
+
if (isHealedTurn) {
|
|
1381
|
+
const res = healRequestPayload("anthropic", rawPayload);
|
|
1382
|
+
effectiveBody = res.body;
|
|
1383
|
+
healed = res.changes.length > 0;
|
|
1384
|
+
healChanges = res.changes;
|
|
1385
|
+
}
|
|
1386
|
+
const totalPrompt = 78e3 + turn * 2400;
|
|
1387
|
+
let usage;
|
|
1388
|
+
if (turn === 1) {
|
|
1389
|
+
usage = {
|
|
1390
|
+
inputTokens: 1200,
|
|
1391
|
+
cacheReadTokens: 0,
|
|
1392
|
+
cacheWriteTokens: totalPrompt - 1200,
|
|
1393
|
+
outputTokens: 640,
|
|
1394
|
+
totalPromptTokens: totalPrompt
|
|
1395
|
+
};
|
|
1396
|
+
} else if (isTurn14Bust) {
|
|
1397
|
+
usage = {
|
|
1398
|
+
inputTokens: 2100,
|
|
1399
|
+
cacheReadTokens: 0,
|
|
1400
|
+
cacheWriteTokens: totalPrompt - 2100,
|
|
1401
|
+
outputTokens: 520,
|
|
1402
|
+
totalPromptTokens: totalPrompt
|
|
1403
|
+
};
|
|
1404
|
+
} else if (turn === 15) {
|
|
1405
|
+
const cacheRead = Math.round(totalPrompt * 0.97);
|
|
1406
|
+
usage = {
|
|
1407
|
+
inputTokens: totalPrompt - cacheRead,
|
|
1408
|
+
cacheReadTokens: cacheRead,
|
|
1409
|
+
cacheWriteTokens: 0,
|
|
1410
|
+
outputTokens: 480,
|
|
1411
|
+
totalPromptTokens: totalPrompt
|
|
1412
|
+
};
|
|
1413
|
+
} else {
|
|
1414
|
+
const cacheRead = Math.round(totalPrompt * 0.94);
|
|
1415
|
+
const cacheWrite = Math.round(totalPrompt * 0.04);
|
|
1416
|
+
usage = {
|
|
1417
|
+
inputTokens: totalPrompt - cacheRead - cacheWrite,
|
|
1418
|
+
cacheReadTokens: cacheRead,
|
|
1419
|
+
cacheWriteTokens: cacheWrite,
|
|
1420
|
+
outputTokens: 410 + turn * 15,
|
|
1421
|
+
totalPromptTokens: totalPrompt
|
|
1422
|
+
};
|
|
1423
|
+
}
|
|
1424
|
+
const prevTurn = store.getLastTurn(sessionId);
|
|
1425
|
+
const ts = baseTs + turn * 2e4;
|
|
1426
|
+
const diagnosis = diagnoseCacheBreak({
|
|
1427
|
+
provider: "anthropic",
|
|
1428
|
+
prevTurn,
|
|
1429
|
+
currBody: effectiveBody,
|
|
1430
|
+
currModel: model,
|
|
1431
|
+
currTimestampMs: ts,
|
|
1432
|
+
currUsage: usage
|
|
1433
|
+
});
|
|
1434
|
+
const { costUsd } = estimateCost(model, usage, prevTurn?.usage.totalPromptTokens ?? 0);
|
|
1435
|
+
store.recordTurn({
|
|
1436
|
+
sessionId,
|
|
1437
|
+
turnIndex: turn,
|
|
1438
|
+
timestampMs: ts,
|
|
1439
|
+
provider: "anthropic",
|
|
1440
|
+
endpoint: "/v1/messages",
|
|
1441
|
+
model,
|
|
1442
|
+
statusCode: 200,
|
|
1443
|
+
latencyMs: isTurn14Bust ? 2480 : 620 + turn % 5 * 90,
|
|
1444
|
+
healed,
|
|
1445
|
+
healChanges,
|
|
1446
|
+
usage,
|
|
1447
|
+
costUsd,
|
|
1448
|
+
diagnosis,
|
|
1449
|
+
rawRequestBody: effectiveBody.toString("utf8")
|
|
1450
|
+
});
|
|
1451
|
+
}
|
|
1452
|
+
const geminiSessionId = "demo-antigravity-gemini";
|
|
1453
|
+
store.createSession({
|
|
1454
|
+
id: geminiSessionId,
|
|
1455
|
+
label: "antigravity \xB7 gemini-2.5-pro (volatile systemInstruction)",
|
|
1456
|
+
command: "kvdiff serve --port 4318",
|
|
1457
|
+
healed: false,
|
|
1458
|
+
createdAtMs: baseTs - 6e4
|
|
1459
|
+
});
|
|
1460
|
+
const gModel = "gemini-2.5-pro";
|
|
1461
|
+
for (let t = 1; t <= 5; t++) {
|
|
1462
|
+
const volatile = t === 4;
|
|
1463
|
+
const gBody = Buffer.from(
|
|
1464
|
+
JSON.stringify({
|
|
1465
|
+
systemInstruction: {
|
|
1466
|
+
parts: [
|
|
1467
|
+
{
|
|
1468
|
+
text: volatile ? "Antigravity agent context | local_time=2026-11-21T03:24:11Z" : "Antigravity agent context | local_time=2026-11-21T03:20:00Z"
|
|
1469
|
+
}
|
|
1470
|
+
]
|
|
1471
|
+
},
|
|
1472
|
+
contents: Array.from({ length: t }, (_, idx) => ({
|
|
1473
|
+
role: idx % 2 === 0 ? "user" : "model",
|
|
1474
|
+
parts: [{ text: `Step ${idx + 1}: verify cache behavior` }]
|
|
1475
|
+
}))
|
|
1476
|
+
}),
|
|
1477
|
+
"utf8"
|
|
1478
|
+
);
|
|
1479
|
+
const totalPrompt = 52e3 + t * 3e3;
|
|
1480
|
+
const cacheRead = t === 1 || volatile ? 0 : Math.round(totalPrompt * 0.92);
|
|
1481
|
+
const usage = {
|
|
1482
|
+
inputTokens: totalPrompt - cacheRead,
|
|
1483
|
+
cacheReadTokens: cacheRead,
|
|
1484
|
+
cacheWriteTokens: 0,
|
|
1485
|
+
outputTokens: 380,
|
|
1486
|
+
totalPromptTokens: totalPrompt
|
|
1487
|
+
};
|
|
1488
|
+
const prevTurn = store.getLastTurn(geminiSessionId);
|
|
1489
|
+
const ts = baseTs - 6e4 + t * 18e3;
|
|
1490
|
+
const diagnosis = diagnoseCacheBreak({
|
|
1491
|
+
provider: "gemini",
|
|
1492
|
+
prevTurn,
|
|
1493
|
+
currBody: gBody,
|
|
1494
|
+
currModel: gModel,
|
|
1495
|
+
currTimestampMs: ts,
|
|
1496
|
+
currUsage: usage
|
|
1497
|
+
});
|
|
1498
|
+
const { costUsd } = estimateCost(gModel, usage, prevTurn?.usage.totalPromptTokens ?? 0);
|
|
1499
|
+
store.recordTurn({
|
|
1500
|
+
sessionId: geminiSessionId,
|
|
1501
|
+
turnIndex: t,
|
|
1502
|
+
timestampMs: ts,
|
|
1503
|
+
provider: "gemini",
|
|
1504
|
+
endpoint: "/v1beta/models/gemini-2.5-pro:streamGenerateContent",
|
|
1505
|
+
model: gModel,
|
|
1506
|
+
statusCode: 200,
|
|
1507
|
+
latencyMs: volatile ? 1920 : 540,
|
|
1508
|
+
healed: false,
|
|
1509
|
+
healChanges: [],
|
|
1510
|
+
usage,
|
|
1511
|
+
costUsd,
|
|
1512
|
+
diagnosis,
|
|
1513
|
+
rawRequestBody: gBody.toString("utf8")
|
|
1514
|
+
});
|
|
1515
|
+
}
|
|
1516
|
+
return sessionId;
|
|
1517
|
+
}
|
|
1518
|
+
|
|
1519
|
+
// src/launcher/spawn.ts
|
|
1520
|
+
import { spawn } from "node:child_process";
|
|
1521
|
+
import { existsSync as existsSync2, statSync as statSync2 } from "node:fs";
|
|
1522
|
+
import { extname as extname2, join as join2 } from "node:path";
|
|
1523
|
+
function buildProxyEnv(proxyUrl, sessionId, baseEnv = process.env) {
|
|
1524
|
+
const cleanUrl = proxyUrl.replace(/\/+$/, "");
|
|
1525
|
+
return {
|
|
1526
|
+
...baseEnv,
|
|
1527
|
+
ANTHROPIC_BASE_URL: cleanUrl,
|
|
1528
|
+
OPENAI_BASE_URL: `${cleanUrl}/v1`,
|
|
1529
|
+
OPENAI_API_BASE: `${cleanUrl}/v1`,
|
|
1530
|
+
GOOGLE_GEMINI_BASE_URL: cleanUrl,
|
|
1531
|
+
GEMINI_API_BASE_URL: cleanUrl,
|
|
1532
|
+
KVDIFF_SESSION_ID: sessionId
|
|
1533
|
+
};
|
|
1534
|
+
}
|
|
1535
|
+
function isFile(p) {
|
|
1536
|
+
try {
|
|
1537
|
+
return existsSync2(p) && statSync2(p).isFile();
|
|
1538
|
+
} catch {
|
|
1539
|
+
return false;
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
function resolveWindowsBinary(bin, env) {
|
|
1543
|
+
const pathExts = (env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";").map((e) => e.trim()).filter(Boolean);
|
|
1544
|
+
if (bin.includes("\\") || bin.includes("/")) {
|
|
1545
|
+
if (isFile(bin)) return bin;
|
|
1546
|
+
for (const ext of pathExts) {
|
|
1547
|
+
if (isFile(`${bin}${ext}`)) return `${bin}${ext}`;
|
|
1548
|
+
}
|
|
1549
|
+
return bin;
|
|
1550
|
+
}
|
|
1551
|
+
const pathDirs = (env.PATH || env.Path || "").split(";").filter(Boolean);
|
|
1552
|
+
const hasExt = extname2(bin) !== "";
|
|
1553
|
+
for (const dir of pathDirs) {
|
|
1554
|
+
if (hasExt) {
|
|
1555
|
+
const candidate = join2(dir, bin);
|
|
1556
|
+
if (isFile(candidate)) return candidate;
|
|
1557
|
+
} else {
|
|
1558
|
+
for (const ext of pathExts) {
|
|
1559
|
+
const candidate = join2(dir, `${bin}${ext}`);
|
|
1560
|
+
if (isFile(candidate)) return candidate;
|
|
1561
|
+
}
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1564
|
+
return bin;
|
|
1565
|
+
}
|
|
1566
|
+
function quoteCmdArg(arg) {
|
|
1567
|
+
if (!/[\s"&|<>^%!]/.test(arg) && arg.length > 0) return arg;
|
|
1568
|
+
return `"${arg.replace(/"/g, '""')}"`;
|
|
1569
|
+
}
|
|
1570
|
+
function runWrappedCommand(opts) {
|
|
1571
|
+
if (opts.command.length === 0) {
|
|
1572
|
+
return Promise.resolve(1);
|
|
1573
|
+
}
|
|
1574
|
+
const [rawBin, ...args] = opts.command;
|
|
1575
|
+
const env = buildProxyEnv(opts.proxyUrl, opts.sessionId, opts.env);
|
|
1576
|
+
let spawnBin = rawBin;
|
|
1577
|
+
let spawnArgs = args;
|
|
1578
|
+
let windowsVerbatimArguments = false;
|
|
1579
|
+
if (process.platform === "win32") {
|
|
1580
|
+
const resolved = resolveWindowsBinary(rawBin, env);
|
|
1581
|
+
if (/\.(?:cmd|bat)$/i.test(resolved)) {
|
|
1582
|
+
spawnBin = env.ComSpec || "cmd.exe";
|
|
1583
|
+
const cmdLine = [quoteCmdArg(resolved), ...args.map(quoteCmdArg)].join(" ");
|
|
1584
|
+
spawnArgs = ["/d", "/s", "/c", `"${cmdLine}"`];
|
|
1585
|
+
windowsVerbatimArguments = true;
|
|
1586
|
+
} else {
|
|
1587
|
+
spawnBin = resolved;
|
|
1588
|
+
}
|
|
1589
|
+
}
|
|
1590
|
+
return new Promise((resolveExit, reject) => {
|
|
1591
|
+
const child = spawn(spawnBin, spawnArgs, {
|
|
1592
|
+
stdio: "inherit",
|
|
1593
|
+
env,
|
|
1594
|
+
shell: false,
|
|
1595
|
+
windowsVerbatimArguments
|
|
1596
|
+
});
|
|
1597
|
+
const forwardSigInt = () => child.kill("SIGINT");
|
|
1598
|
+
const forwardSigTerm = () => child.kill("SIGTERM");
|
|
1599
|
+
process.on("SIGINT", forwardSigInt);
|
|
1600
|
+
process.on("SIGTERM", forwardSigTerm);
|
|
1601
|
+
const cleanup = () => {
|
|
1602
|
+
process.off("SIGINT", forwardSigInt);
|
|
1603
|
+
process.off("SIGTERM", forwardSigTerm);
|
|
1604
|
+
};
|
|
1605
|
+
child.on("error", (err) => {
|
|
1606
|
+
cleanup();
|
|
1607
|
+
reject(err);
|
|
1608
|
+
});
|
|
1609
|
+
child.on("exit", (code, signal) => {
|
|
1610
|
+
cleanup();
|
|
1611
|
+
if (typeof code === "number") {
|
|
1612
|
+
resolveExit(code);
|
|
1613
|
+
} else if (signal) {
|
|
1614
|
+
resolveExit(130);
|
|
1615
|
+
} else {
|
|
1616
|
+
resolveExit(0);
|
|
1617
|
+
}
|
|
1618
|
+
});
|
|
1619
|
+
});
|
|
1620
|
+
}
|
|
1621
|
+
|
|
1622
|
+
// src/launcher/hud.ts
|
|
1623
|
+
function formatExitSummary(turns, uiUrl) {
|
|
1624
|
+
const count = turns.length;
|
|
1625
|
+
if (count === 0) {
|
|
1626
|
+
return [
|
|
1627
|
+
"",
|
|
1628
|
+
`[kvdiff] Session complete \u2014 0 turns captured.`,
|
|
1629
|
+
`[kvdiff] UI: ${uiUrl}`
|
|
1630
|
+
].join("\n");
|
|
1631
|
+
}
|
|
1632
|
+
const nonFirst = turns.filter((t) => t.turnIndex > 1);
|
|
1633
|
+
const avgHit = nonFirst.length > 0 ? nonFirst.reduce((acc, t) => acc + t.diagnosis.cacheHitRate, 0) / nonFirst.length : turns[0].diagnosis.cacheHitRate;
|
|
1634
|
+
const totalCost = turns.reduce((acc, t) => acc + t.costUsd, 0);
|
|
1635
|
+
const totalWasted = turns.reduce((acc, t) => acc + t.diagnosis.wastedUsd, 0);
|
|
1636
|
+
const breaks = turns.filter((t) => t.diagnosis.kind !== "NONE" && t.diagnosis.kind !== "FIRST_TURN");
|
|
1637
|
+
const worst = [...breaks].sort((a, b) => b.diagnosis.wastedUsd - a.diagnosis.wastedUsd)[0];
|
|
1638
|
+
const lines = [
|
|
1639
|
+
"",
|
|
1640
|
+
`[kvdiff] Session complete \u2014 ${count} turns | Avg Cache Hit: ${Math.round(avgHit * 100)}% | Spend: $${totalCost.toFixed(4)} | Wasted: $${totalWasted.toFixed(2)}`
|
|
1641
|
+
];
|
|
1642
|
+
if (worst) {
|
|
1643
|
+
lines.push(
|
|
1644
|
+
`[kvdiff] Worst break: Turn #${worst.turnIndex} (${worst.diagnosis.kind}) at ${worst.diagnosis.jsonPath ?? "$"} (byte ${worst.diagnosis.byteOffset ?? 0}) -> -$${worst.diagnosis.wastedUsd.toFixed(2)}`
|
|
1645
|
+
);
|
|
1646
|
+
}
|
|
1647
|
+
lines.push(`[kvdiff] Inspect waterfall: ${uiUrl}`);
|
|
1648
|
+
return lines.join("\n");
|
|
1649
|
+
}
|
|
1650
|
+
|
|
1651
|
+
// src/cli.ts
|
|
1652
|
+
var DEFAULT_DB = join3(homedir(), ".kvdiff", "kvdiff.db");
|
|
1653
|
+
function printHelp() {
|
|
1654
|
+
console.log(`kvdiff v0.1.0 \u2014 Local prompt-cache byte-diff proxy & prefix healer
|
|
1655
|
+
|
|
1656
|
+
Usage:
|
|
1657
|
+
kvdiff -- <command...> Wrap an agent CLI (claude, codex, gemini, opencode)
|
|
1658
|
+
kvdiff serve [options] Run standalone local proxy + waterfall UI
|
|
1659
|
+
kvdiff ui [options] Open waterfall UI for existing ~/.kvdiff/kvdiff.db
|
|
1660
|
+
kvdiff --demo [options] Launch pre-baked 16-turn Claude+MCP & Antigravity/Gemini demo
|
|
1661
|
+
|
|
1662
|
+
Options:
|
|
1663
|
+
--port <n> Local port (default: 4318)
|
|
1664
|
+
--host <addr> Bind host (default: 127.0.0.1)
|
|
1665
|
+
--heal Opt-in deterministic tool/schema canonicalizer
|
|
1666
|
+
--db <path> SQLite DB path (default: ~/.kvdiff/kvdiff.db)
|
|
1667
|
+
--upstream-anthropic <url> Override Anthropic API base URL
|
|
1668
|
+
--upstream-openai <url> Override OpenAI API base URL
|
|
1669
|
+
--upstream-gemini <url> Override Google Gemini / Antigravity API base URL
|
|
1670
|
+
--upstream-local <url> Route OpenAI-compatible traffic to local llama.cpp/vLLM
|
|
1671
|
+
-h, --help Show this help`);
|
|
1672
|
+
}
|
|
1673
|
+
function parseArgs(argv) {
|
|
1674
|
+
const sepIdx = argv.indexOf("--");
|
|
1675
|
+
const kvArgs = sepIdx >= 0 ? argv.slice(0, sepIdx) : argv;
|
|
1676
|
+
const wrappedCommand = sepIdx >= 0 ? argv.slice(sepIdx + 1) : [];
|
|
1677
|
+
const parsed = {
|
|
1678
|
+
mode: wrappedCommand.length > 0 ? "wrap" : "help",
|
|
1679
|
+
port: 4318,
|
|
1680
|
+
portProvided: false,
|
|
1681
|
+
host: "127.0.0.1",
|
|
1682
|
+
heal: false,
|
|
1683
|
+
dbPath: DEFAULT_DB,
|
|
1684
|
+
wrappedCommand
|
|
1685
|
+
};
|
|
1686
|
+
const requireValue = (flag, nextIdx) => {
|
|
1687
|
+
if (nextIdx >= kvArgs.length) {
|
|
1688
|
+
throw new Error(`Missing value for ${flag}`);
|
|
1689
|
+
}
|
|
1690
|
+
return kvArgs[nextIdx];
|
|
1691
|
+
};
|
|
1692
|
+
for (let i = 0; i < kvArgs.length; i++) {
|
|
1693
|
+
const arg = kvArgs[i];
|
|
1694
|
+
if (arg === "-h" || arg === "--help") {
|
|
1695
|
+
parsed.mode = "help";
|
|
1696
|
+
return parsed;
|
|
1697
|
+
} else if (arg === "--demo") {
|
|
1698
|
+
parsed.mode = "demo";
|
|
1699
|
+
} else if (arg === "serve") {
|
|
1700
|
+
parsed.mode = "serve";
|
|
1701
|
+
} else if (arg === "ui") {
|
|
1702
|
+
parsed.mode = "ui";
|
|
1703
|
+
} else if (arg === "--heal") {
|
|
1704
|
+
parsed.heal = true;
|
|
1705
|
+
} else if (arg === "--port") {
|
|
1706
|
+
const raw = requireValue("--port", ++i);
|
|
1707
|
+
const port = Number(raw);
|
|
1708
|
+
if (raw.trim() === "" || !Number.isInteger(port) || port < 0 || port > 65535) {
|
|
1709
|
+
throw new Error(`Invalid --port "${raw}": expected an integer between 0 and 65535`);
|
|
1710
|
+
}
|
|
1711
|
+
parsed.port = port;
|
|
1712
|
+
parsed.portProvided = true;
|
|
1713
|
+
} else if (arg === "--host") {
|
|
1714
|
+
parsed.host = requireValue("--host", ++i);
|
|
1715
|
+
} else if (arg === "--db") {
|
|
1716
|
+
parsed.dbPath = requireValue("--db", ++i);
|
|
1717
|
+
} else if (arg === "--upstream-anthropic") {
|
|
1718
|
+
parsed.upstreamAnthropic = requireValue("--upstream-anthropic", ++i);
|
|
1719
|
+
} else if (arg === "--upstream-openai") {
|
|
1720
|
+
parsed.upstreamOpenAi = requireValue("--upstream-openai", ++i);
|
|
1721
|
+
} else if (arg === "--upstream-gemini") {
|
|
1722
|
+
parsed.upstreamGemini = requireValue("--upstream-gemini", ++i);
|
|
1723
|
+
} else if (arg === "--upstream-local") {
|
|
1724
|
+
parsed.upstreamLocal = requireValue("--upstream-local", ++i);
|
|
1725
|
+
} else if (arg.startsWith("-")) {
|
|
1726
|
+
throw new Error(`Unknown option: ${arg}. Run "kvdiff --help" for usage.`);
|
|
1727
|
+
}
|
|
1728
|
+
}
|
|
1729
|
+
return parsed;
|
|
1730
|
+
}
|
|
1731
|
+
async function main() {
|
|
1732
|
+
const args = parseArgs(process.argv.slice(2));
|
|
1733
|
+
if (args.mode === "help") {
|
|
1734
|
+
printHelp();
|
|
1735
|
+
return;
|
|
1736
|
+
}
|
|
1737
|
+
if (args.mode === "demo") {
|
|
1738
|
+
const store2 = new KvStore(":memory:");
|
|
1739
|
+
seedDemoSession(store2);
|
|
1740
|
+
const proxy2 = await createProxyServer({
|
|
1741
|
+
store: store2,
|
|
1742
|
+
port: args.port,
|
|
1743
|
+
host: args.host,
|
|
1744
|
+
heal: args.heal,
|
|
1745
|
+
defaultSessionId: "demo-claude-mcp"
|
|
1746
|
+
});
|
|
1747
|
+
console.log(`[kvdiff] Demo mode ready -> ${proxy2.url}`);
|
|
1748
|
+
console.log(`[kvdiff] Seeded 16-turn Claude Code + MCP session (Turn 14 cache bust + Turn 15 --heal) & Antigravity/Gemini session.`);
|
|
1749
|
+
console.log(`[kvdiff] Press Ctrl+C to stop.`);
|
|
1750
|
+
await new Promise((resolve3) => {
|
|
1751
|
+
process.once("SIGINT", resolve3);
|
|
1752
|
+
process.once("SIGTERM", resolve3);
|
|
1753
|
+
});
|
|
1754
|
+
await proxy2.close();
|
|
1755
|
+
store2.close();
|
|
1756
|
+
return;
|
|
1757
|
+
}
|
|
1758
|
+
const store = new KvStore(args.dbPath);
|
|
1759
|
+
if (args.mode === "serve" || args.mode === "ui") {
|
|
1760
|
+
const sessionId2 = `serve-${randomUUID2().slice(0, 8)}`;
|
|
1761
|
+
const proxy2 = await createProxyServer({
|
|
1762
|
+
store,
|
|
1763
|
+
port: args.port,
|
|
1764
|
+
host: args.host,
|
|
1765
|
+
heal: args.heal,
|
|
1766
|
+
defaultSessionId: sessionId2,
|
|
1767
|
+
upstreamAnthropic: args.upstreamAnthropic,
|
|
1768
|
+
upstreamOpenAi: args.upstreamOpenAi,
|
|
1769
|
+
upstreamGemini: args.upstreamGemini,
|
|
1770
|
+
upstreamLocal: args.upstreamLocal,
|
|
1771
|
+
onTurnRecorded: (turn) => {
|
|
1772
|
+
const hitPct = Math.round(turn.diagnosis.cacheHitRate * 100);
|
|
1773
|
+
const tag = turn.diagnosis.kind !== "NONE" && turn.diagnosis.kind !== "FIRST_TURN" ? ` \u26A0 ${turn.diagnosis.kind}` : "";
|
|
1774
|
+
process.stderr.write(
|
|
1775
|
+
`[kvdiff] Turn #${turn.turnIndex} (${turn.provider}/${turn.model}) | Hit ${hitPct}% | $${turn.costUsd.toFixed(4)}${tag}
|
|
1776
|
+
`
|
|
1777
|
+
);
|
|
1778
|
+
}
|
|
1779
|
+
});
|
|
1780
|
+
console.log(`[kvdiff] Listening on ${proxy2.url} (${args.heal ? "HEAL ON" : "strict passthrough"})`);
|
|
1781
|
+
console.log(`[kvdiff] Waterfall UI: ${proxy2.url}`);
|
|
1782
|
+
if (args.mode === "serve") {
|
|
1783
|
+
console.log(`[kvdiff] Point clients via ANTHROPIC_BASE_URL=${proxy2.url} | OPENAI_BASE_URL=${proxy2.url}/v1 | GOOGLE_GEMINI_BASE_URL=${proxy2.url}`);
|
|
1784
|
+
}
|
|
1785
|
+
await new Promise((resolve3) => {
|
|
1786
|
+
process.once("SIGINT", resolve3);
|
|
1787
|
+
process.once("SIGTERM", resolve3);
|
|
1788
|
+
});
|
|
1789
|
+
await proxy2.close();
|
|
1790
|
+
store.close();
|
|
1791
|
+
return;
|
|
1792
|
+
}
|
|
1793
|
+
const sessionId = `run-${randomUUID2().slice(0, 8)}`;
|
|
1794
|
+
const cmdLabel = args.wrappedCommand.join(" ");
|
|
1795
|
+
store.createSession({
|
|
1796
|
+
id: sessionId,
|
|
1797
|
+
label: cmdLabel,
|
|
1798
|
+
command: cmdLabel,
|
|
1799
|
+
healed: args.heal
|
|
1800
|
+
});
|
|
1801
|
+
const proxy = await createProxyServer({
|
|
1802
|
+
store,
|
|
1803
|
+
port: args.portProvided ? args.port : 0,
|
|
1804
|
+
host: args.host,
|
|
1805
|
+
heal: args.heal,
|
|
1806
|
+
defaultSessionId: sessionId,
|
|
1807
|
+
upstreamAnthropic: args.upstreamAnthropic,
|
|
1808
|
+
upstreamOpenAi: args.upstreamOpenAi,
|
|
1809
|
+
upstreamGemini: args.upstreamGemini,
|
|
1810
|
+
upstreamLocal: args.upstreamLocal
|
|
1811
|
+
});
|
|
1812
|
+
process.stderr.write(
|
|
1813
|
+
`[kvdiff] Wrapping \`${cmdLabel}\` via ${proxy.url} (${args.heal ? "HEAL ON" : "passthrough"})
|
|
1814
|
+
`
|
|
1815
|
+
);
|
|
1816
|
+
let exitCode = 0;
|
|
1817
|
+
try {
|
|
1818
|
+
exitCode = await runWrappedCommand({
|
|
1819
|
+
command: args.wrappedCommand,
|
|
1820
|
+
proxyUrl: proxy.url,
|
|
1821
|
+
sessionId
|
|
1822
|
+
});
|
|
1823
|
+
} finally {
|
|
1824
|
+
const turns = store.getSessionTurns(sessionId);
|
|
1825
|
+
process.stderr.write(`${formatExitSummary(turns, `kvdiff ui --db "${args.dbPath}"`)}
|
|
1826
|
+
`);
|
|
1827
|
+
await proxy.close();
|
|
1828
|
+
store.close();
|
|
1829
|
+
}
|
|
1830
|
+
process.exitCode = exitCode;
|
|
1831
|
+
}
|
|
1832
|
+
function isDirectEntry() {
|
|
1833
|
+
if (!process.argv[1]) return false;
|
|
1834
|
+
try {
|
|
1835
|
+
return realpathSync(fileURLToPath2(import.meta.url)).toLowerCase() === realpathSync(resolve2(process.argv[1])).toLowerCase();
|
|
1836
|
+
} catch {
|
|
1837
|
+
return resolve2(fileURLToPath2(import.meta.url)).toLowerCase() === resolve2(process.argv[1]).toLowerCase();
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1840
|
+
if (isDirectEntry()) {
|
|
1841
|
+
main().catch((err) => {
|
|
1842
|
+
console.error(`[kvdiff] Fatal error: ${err.message}`);
|
|
1843
|
+
process.exitCode = 1;
|
|
1844
|
+
});
|
|
1845
|
+
}
|
|
1846
|
+
export {
|
|
1847
|
+
parseArgs
|
|
1848
|
+
};
|
|
1849
|
+
//# sourceMappingURL=cli.js.map
|