loopcap 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 +110 -2
- package/dist/cli/commands-CWPR6G7K.js +1448 -0
- package/dist/cli/index.js +57 -0
- package/dist/web/assets/index-Dh109ogZ.css +2 -0
- package/dist/web/assets/index-piKH5vJH.js +9 -0
- package/dist/web/index.html +14 -0
- package/loopcap.config.yaml +31 -0
- package/package.json +68 -4
- package/pricing.json +57 -0
|
@@ -0,0 +1,1448 @@
|
|
|
1
|
+
// src/cli/commands.ts
|
|
2
|
+
import { existsSync as existsSync3, readFileSync as readFileSync4, writeFileSync } from "fs";
|
|
3
|
+
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
4
|
+
|
|
5
|
+
// src/dashboard/server.ts
|
|
6
|
+
import { existsSync, readFileSync, statSync } from "fs";
|
|
7
|
+
import { extname, join, normalize, sep } from "path";
|
|
8
|
+
import { fileURLToPath } from "url";
|
|
9
|
+
import { serve } from "@hono/node-server";
|
|
10
|
+
import { Hono } from "hono";
|
|
11
|
+
var SNAPSHOT_MS = 2e3;
|
|
12
|
+
var PING_MS = 15e3;
|
|
13
|
+
var TYPES = {
|
|
14
|
+
".html": "text/html; charset=utf-8",
|
|
15
|
+
".js": "text/javascript; charset=utf-8",
|
|
16
|
+
".mjs": "text/javascript; charset=utf-8",
|
|
17
|
+
".css": "text/css; charset=utf-8",
|
|
18
|
+
".json": "application/json",
|
|
19
|
+
".svg": "image/svg+xml",
|
|
20
|
+
".png": "image/png",
|
|
21
|
+
".ico": "image/x-icon",
|
|
22
|
+
".woff2": "font/woff2",
|
|
23
|
+
".map": "application/json",
|
|
24
|
+
".txt": "text/plain; charset=utf-8"
|
|
25
|
+
};
|
|
26
|
+
var MISSING_PAGE = `<!doctype html><meta charset="utf-8"><title>LoopCap</title>
|
|
27
|
+
<body style="font-family:system-ui;max-width:36rem;margin:4rem auto;padding:0 1rem">
|
|
28
|
+
<h1>LoopCap dashboard not built</h1><p>Run <code>npm run build:web</code>, then reload this page.</p>
|
|
29
|
+
<p>The API is live at <a href="/api/state">/api/state</a>.</p></body>`;
|
|
30
|
+
function findWebDir() {
|
|
31
|
+
for (const rel of ["../../dist/web", "../web"]) {
|
|
32
|
+
const dir = fileURLToPath(new URL(rel, import.meta.url));
|
|
33
|
+
if (existsSync(join(dir, "index.html"))) return dir;
|
|
34
|
+
}
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
function createDashboardApp({ config, engine, webDir }) {
|
|
38
|
+
const port2 = config.server.dashboardPort;
|
|
39
|
+
const allowed = /* @__PURE__ */ new Set([`http://localhost:${port2}`, `http://127.0.0.1:${port2}`]);
|
|
40
|
+
const dir = webDir === void 0 ? findWebDir() : webDir;
|
|
41
|
+
const hosts = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", config.server.host.toLowerCase()]);
|
|
42
|
+
const app = new Hono();
|
|
43
|
+
app.use("*", async (c, next) => {
|
|
44
|
+
if (!hosts.has(new URL(c.req.url).hostname.toLowerCase())) return c.text("Forbidden host", 403);
|
|
45
|
+
await next();
|
|
46
|
+
});
|
|
47
|
+
app.get("/api/state", (c) => c.json(engine.snapshot()));
|
|
48
|
+
app.get("/api/events", (c) => {
|
|
49
|
+
const enc = new TextEncoder();
|
|
50
|
+
let cleanup = () => {
|
|
51
|
+
};
|
|
52
|
+
const body = new ReadableStream({
|
|
53
|
+
start(controller) {
|
|
54
|
+
const write = (text) => {
|
|
55
|
+
try {
|
|
56
|
+
controller.enqueue(enc.encode(text));
|
|
57
|
+
} catch {
|
|
58
|
+
cleanup();
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
const send = (m) => write(`data: ${JSON.stringify(m)}
|
|
62
|
+
|
|
63
|
+
`);
|
|
64
|
+
const snapshot = () => send({ type: "snapshot", snapshot: engine.snapshot() });
|
|
65
|
+
snapshot();
|
|
66
|
+
const unsubscribe = engine.bus.subscribe((event) => {
|
|
67
|
+
send({ type: "event", event });
|
|
68
|
+
if (event.type === "trip" || event.type === "reset") snapshot();
|
|
69
|
+
});
|
|
70
|
+
const snapTimer = setInterval(snapshot, SNAPSHOT_MS);
|
|
71
|
+
const pingTimer = setInterval(() => write(": ping\n\n"), PING_MS);
|
|
72
|
+
snapTimer.unref();
|
|
73
|
+
pingTimer.unref();
|
|
74
|
+
cleanup = () => {
|
|
75
|
+
unsubscribe();
|
|
76
|
+
clearInterval(snapTimer);
|
|
77
|
+
clearInterval(pingTimer);
|
|
78
|
+
};
|
|
79
|
+
c.req.raw.signal.addEventListener("abort", () => {
|
|
80
|
+
cleanup();
|
|
81
|
+
try {
|
|
82
|
+
controller.close();
|
|
83
|
+
} catch {
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
},
|
|
87
|
+
cancel() {
|
|
88
|
+
cleanup();
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
return new Response(body, {
|
|
92
|
+
headers: { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-cache", connection: "keep-alive" }
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
const control = (action) => async (c) => {
|
|
96
|
+
const origin = c.req.header("origin");
|
|
97
|
+
if (!origin || !allowed.has(origin)) return c.json({ error: "Forbidden origin" }, 403);
|
|
98
|
+
if (!(c.req.header("content-type") ?? "").toLowerCase().startsWith("application/json")) {
|
|
99
|
+
return c.json({ error: "Content-Type must be application/json" }, 415);
|
|
100
|
+
}
|
|
101
|
+
let req = {};
|
|
102
|
+
const text = await c.req.text();
|
|
103
|
+
if (text.trim()) {
|
|
104
|
+
try {
|
|
105
|
+
req = JSON.parse(text);
|
|
106
|
+
} catch {
|
|
107
|
+
return c.json({ error: "Invalid JSON" }, 400);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if (req === null || typeof req !== "object" || req.session !== void 0 && typeof req.session !== "string") {
|
|
111
|
+
return c.json({ error: "session must be a string" }, 400);
|
|
112
|
+
}
|
|
113
|
+
const key = req.session ?? null;
|
|
114
|
+
if (action === "trip") engine.trip(key);
|
|
115
|
+
else engine.reset(key);
|
|
116
|
+
return c.json(engine.snapshot());
|
|
117
|
+
};
|
|
118
|
+
app.post("/api/trip", control("trip"));
|
|
119
|
+
app.post("/api/reset", control("reset"));
|
|
120
|
+
app.get("*", (c) => {
|
|
121
|
+
let path;
|
|
122
|
+
try {
|
|
123
|
+
path = decodeURIComponent(new URL(c.req.url).pathname);
|
|
124
|
+
} catch {
|
|
125
|
+
return c.text("Bad request", 400);
|
|
126
|
+
}
|
|
127
|
+
const rel = normalize(path).replace(/^[/\\]+/, "");
|
|
128
|
+
if (!dir) return extname(rel) ? c.text("Not found", 404) : c.html(MISSING_PAGE);
|
|
129
|
+
let file = join(dir, rel);
|
|
130
|
+
const inside = file === dir || file.startsWith(dir + sep);
|
|
131
|
+
if (!inside || !existsSync(file) || !statSync(file).isFile()) {
|
|
132
|
+
if (extname(rel)) return c.text("Not found", 404);
|
|
133
|
+
file = join(dir, "index.html");
|
|
134
|
+
}
|
|
135
|
+
const data = readFileSync(file);
|
|
136
|
+
const type = TYPES[extname(file)] ?? "application/octet-stream";
|
|
137
|
+
return new Response(data, { headers: { "content-type": type, ...file.includes(`${sep}assets${sep}`) ? { "cache-control": "public, max-age=31536000, immutable" } : {} } });
|
|
138
|
+
});
|
|
139
|
+
return app;
|
|
140
|
+
}
|
|
141
|
+
async function startDashboard(config, engine) {
|
|
142
|
+
const app = createDashboardApp({ config, engine });
|
|
143
|
+
const server = await new Promise((resolve, reject) => {
|
|
144
|
+
const s = serve({ fetch: app.fetch, hostname: config.server.host, port: config.server.dashboardPort }, () => resolve(s));
|
|
145
|
+
s.once("error", reject);
|
|
146
|
+
});
|
|
147
|
+
const close = () => new Promise((resolve) => {
|
|
148
|
+
server.close(() => resolve());
|
|
149
|
+
if ("closeAllConnections" in server) server.closeAllConnections();
|
|
150
|
+
});
|
|
151
|
+
return { url: engine.dashboardUrl, server, close };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// src/proxy/config.ts
|
|
155
|
+
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
|
|
156
|
+
import { homedir } from "os";
|
|
157
|
+
import { join as join2 } from "path";
|
|
158
|
+
import { parse } from "yaml";
|
|
159
|
+
import { z } from "zod";
|
|
160
|
+
function expandHome(p) {
|
|
161
|
+
return p === "~" ? homedir() : p.startsWith("~/") ? join2(homedir(), p.slice(2)) : p;
|
|
162
|
+
}
|
|
163
|
+
var port = z.number().int().min(0).max(65535);
|
|
164
|
+
var ConfigSchema = z.object({
|
|
165
|
+
server: z.object({
|
|
166
|
+
host: z.string().default("127.0.0.1"),
|
|
167
|
+
proxyPort: port.default(4e3),
|
|
168
|
+
dashboardPort: port.default(4001)
|
|
169
|
+
}).prefault({}),
|
|
170
|
+
upstreams: z.object({
|
|
171
|
+
anthropic: z.url().default("https://api.anthropic.com"),
|
|
172
|
+
openai: z.url().default("https://api.openai.com")
|
|
173
|
+
}).prefault({}),
|
|
174
|
+
breakers: z.object({
|
|
175
|
+
loop: z.object({
|
|
176
|
+
enabled: z.boolean().default(true),
|
|
177
|
+
windowSize: z.number().int().min(2).default(10),
|
|
178
|
+
identicalLoopThreshold: z.number().int().min(2).default(3),
|
|
179
|
+
ignoreArgKeys: z.array(z.string()).default(["description"])
|
|
180
|
+
}).prefault({}),
|
|
181
|
+
spend: z.object({
|
|
182
|
+
enabled: z.boolean().default(true),
|
|
183
|
+
maxSessionSpendUsd: z.number().positive().default(2),
|
|
184
|
+
maxBurnRatePerMinUsd: z.number().positive().default(0.75),
|
|
185
|
+
warnAtFraction: z.number().gt(0).max(1).default(0.8)
|
|
186
|
+
}).prefault({})
|
|
187
|
+
}).prefault({}),
|
|
188
|
+
sessions: z.object({
|
|
189
|
+
header: z.string().min(1).default("x-loopcap-session"),
|
|
190
|
+
idleTimeoutMinutes: z.number().positive().default(30)
|
|
191
|
+
}).prefault({}),
|
|
192
|
+
storage: z.object({
|
|
193
|
+
// In the home directory by default, so running LoopCap never clutters a project folder.
|
|
194
|
+
path: z.string().min(1).default("~/.loopcap/loopcap.db").transform(expandHome)
|
|
195
|
+
}).prefault({}),
|
|
196
|
+
pricing: z.object({
|
|
197
|
+
file: z.string().nullable().default(null)
|
|
198
|
+
}).prefault({})
|
|
199
|
+
});
|
|
200
|
+
function parseConfig(input, source = "config") {
|
|
201
|
+
const result = ConfigSchema.safeParse(input ?? {});
|
|
202
|
+
if (!result.success) throw new Error(`Invalid ${source}:
|
|
203
|
+
${z.prettifyError(result.error)}`);
|
|
204
|
+
return result.data;
|
|
205
|
+
}
|
|
206
|
+
function loadConfig(path = "loopcap.config.yaml") {
|
|
207
|
+
if (!existsSync2(path)) return parseConfig({});
|
|
208
|
+
return parseConfig(parse(readFileSync2(path, "utf8")), path);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// src/proxy/index.ts
|
|
212
|
+
import { serve as serve2 } from "@hono/node-server";
|
|
213
|
+
|
|
214
|
+
// src/proxy/loop.ts
|
|
215
|
+
import { createHash } from "crypto";
|
|
216
|
+
var PREVIEW_CHARS = 500;
|
|
217
|
+
function fingerprint(turn, ignoreArgKeys = []) {
|
|
218
|
+
let kind;
|
|
219
|
+
let canonical;
|
|
220
|
+
if (turn.toolCalls.length > 0) {
|
|
221
|
+
kind = "tools";
|
|
222
|
+
canonical = turn.toolCalls.map((c) => `${c.name}(${canonicalArgs(c.args, ignoreArgKeys)})`).join("\n");
|
|
223
|
+
} else {
|
|
224
|
+
kind = "text";
|
|
225
|
+
canonical = turn.text.replace(/\s+/g, " ").trim();
|
|
226
|
+
if (!canonical) return null;
|
|
227
|
+
}
|
|
228
|
+
const hash = createHash("sha256").update(`${kind}\0${canonical}`).digest("hex").slice(0, 16);
|
|
229
|
+
const preview = canonical.length > PREVIEW_CHARS ? `${canonical.slice(0, PREVIEW_CHARS - 1)}\u2026` : canonical;
|
|
230
|
+
return { hash, kind, preview };
|
|
231
|
+
}
|
|
232
|
+
function canonicalArgs(args, ignore) {
|
|
233
|
+
if (!args.trim()) return "{}";
|
|
234
|
+
try {
|
|
235
|
+
const v = JSON.parse(args);
|
|
236
|
+
if (ignore.length && v !== null && typeof v === "object" && !Array.isArray(v)) {
|
|
237
|
+
const obj = { ...v };
|
|
238
|
+
for (const k of ignore) delete obj[k];
|
|
239
|
+
return stableStringify(obj);
|
|
240
|
+
}
|
|
241
|
+
return stableStringify(v);
|
|
242
|
+
} catch {
|
|
243
|
+
return args.trim();
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
function stableStringify(v) {
|
|
247
|
+
if (Array.isArray(v)) return `[${v.map(stableStringify).join(",")}]`;
|
|
248
|
+
if (v !== null && typeof v === "object") {
|
|
249
|
+
const obj = v;
|
|
250
|
+
return `{${Object.keys(obj).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(",")}}`;
|
|
251
|
+
}
|
|
252
|
+
return JSON.stringify(v) ?? "null";
|
|
253
|
+
}
|
|
254
|
+
var LoopTracker = class {
|
|
255
|
+
constructor(size) {
|
|
256
|
+
this.size = size;
|
|
257
|
+
}
|
|
258
|
+
size;
|
|
259
|
+
window = [];
|
|
260
|
+
record(hash) {
|
|
261
|
+
this.window.push(hash);
|
|
262
|
+
if (this.window.length > this.size) this.window.shift();
|
|
263
|
+
}
|
|
264
|
+
/** How many of the most recent responses in a row share a fingerprint. */
|
|
265
|
+
streak() {
|
|
266
|
+
const last = this.window.at(-1);
|
|
267
|
+
if (!last) return 0;
|
|
268
|
+
let n = 0;
|
|
269
|
+
for (let i = this.window.length - 1; i >= 0 && this.window[i] === last; i--) n++;
|
|
270
|
+
return n;
|
|
271
|
+
}
|
|
272
|
+
clear() {
|
|
273
|
+
this.window = [];
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
// src/proxy/breaker.ts
|
|
278
|
+
var MINUTE_MS = 6e4;
|
|
279
|
+
var usd = (n) => `$${n !== 0 && Math.abs(n) < 0.01 ? n.toFixed(4) : n.toFixed(2)}`;
|
|
280
|
+
var Breakers = class {
|
|
281
|
+
constructor(cfg, idleMs, now = Date.now) {
|
|
282
|
+
this.cfg = cfg;
|
|
283
|
+
this.idleMs = idleMs;
|
|
284
|
+
this.now = now;
|
|
285
|
+
}
|
|
286
|
+
cfg;
|
|
287
|
+
idleMs;
|
|
288
|
+
now;
|
|
289
|
+
sessions = /* @__PURE__ */ new Map();
|
|
290
|
+
globalTrip = null;
|
|
291
|
+
session(key) {
|
|
292
|
+
const t = this.now();
|
|
293
|
+
const existing = this.sessions.get(key);
|
|
294
|
+
if (existing && t - existing.lastSeenAt <= this.idleMs) return existing;
|
|
295
|
+
const s = {
|
|
296
|
+
key,
|
|
297
|
+
id: `${key}-${t.toString(36)}`,
|
|
298
|
+
startedAt: t,
|
|
299
|
+
lastSeenAt: t,
|
|
300
|
+
spentUsd: 0,
|
|
301
|
+
capSpendUsd: 0,
|
|
302
|
+
savedUsd: 0,
|
|
303
|
+
turns: 0,
|
|
304
|
+
blocked: 0,
|
|
305
|
+
lastTurnCostUsd: 0,
|
|
306
|
+
trip: null,
|
|
307
|
+
costLog: [],
|
|
308
|
+
threads: /* @__PURE__ */ new Map()
|
|
309
|
+
};
|
|
310
|
+
this.sessions.set(key, s);
|
|
311
|
+
return s;
|
|
312
|
+
}
|
|
313
|
+
/** Decides whether a request may go upstream. */
|
|
314
|
+
admit(key, thread = "") {
|
|
315
|
+
const s = this.session(key);
|
|
316
|
+
s.lastSeenAt = this.now();
|
|
317
|
+
let newlyTripped = false;
|
|
318
|
+
if (!this.globalTrip && !s.trip) {
|
|
319
|
+
s.trip = this.evaluate(s, thread);
|
|
320
|
+
newlyTripped = s.trip !== null;
|
|
321
|
+
}
|
|
322
|
+
const trip = this.globalTrip ?? s.trip;
|
|
323
|
+
if (!trip) return { allowed: true, session: s };
|
|
324
|
+
s.blocked++;
|
|
325
|
+
s.savedUsd += s.lastTurnCostUsd;
|
|
326
|
+
return { allowed: false, session: s, trip, newlyTripped };
|
|
327
|
+
}
|
|
328
|
+
/** Records a finished response. Failed or cut-off responses skip the loop window. */
|
|
329
|
+
record(key, costUsd, fp, countForLoop, thread = "") {
|
|
330
|
+
const s = this.session(key);
|
|
331
|
+
const t = this.now();
|
|
332
|
+
s.lastSeenAt = t;
|
|
333
|
+
s.turns++;
|
|
334
|
+
if (costUsd > 0) {
|
|
335
|
+
s.spentUsd += costUsd;
|
|
336
|
+
s.capSpendUsd += costUsd;
|
|
337
|
+
s.lastTurnCostUsd = costUsd;
|
|
338
|
+
s.costLog.push({ at: t, usd: costUsd });
|
|
339
|
+
}
|
|
340
|
+
if (countForLoop) {
|
|
341
|
+
const t2 = this.thread(s, thread);
|
|
342
|
+
t2.loop.record(fp?.hash ?? null);
|
|
343
|
+
t2.last = fp;
|
|
344
|
+
}
|
|
345
|
+
return s;
|
|
346
|
+
}
|
|
347
|
+
/** Spend in the last 60 seconds. */
|
|
348
|
+
burnRate(s) {
|
|
349
|
+
const cutoff = this.now() - MINUTE_MS;
|
|
350
|
+
while (s.costLog[0] && s.costLog[0].at < cutoff) s.costLog.shift();
|
|
351
|
+
return s.costLog.reduce((sum, c) => sum + c.usd, 0);
|
|
352
|
+
}
|
|
353
|
+
health(s) {
|
|
354
|
+
if (this.globalTrip || s.trip) return "TRIPPED";
|
|
355
|
+
const { loop, spend } = this.cfg;
|
|
356
|
+
if (spend.enabled) {
|
|
357
|
+
const w = spend.warnAtFraction;
|
|
358
|
+
if (s.capSpendUsd >= w * spend.maxSessionSpendUsd || this.burnRate(s) >= w * spend.maxBurnRatePerMinUsd) return "WARNING";
|
|
359
|
+
}
|
|
360
|
+
if (loop.enabled && this.streak(s) >= Math.max(2, loop.identicalLoopThreshold - 1)) return "WARNING";
|
|
361
|
+
return "HEALTHY";
|
|
362
|
+
}
|
|
363
|
+
/** Manual kill switch. A null key trips every session. */
|
|
364
|
+
trip(key, detail) {
|
|
365
|
+
const trip = { kind: "manual", detail, at: this.now() };
|
|
366
|
+
if (key === null) this.globalTrip = trip;
|
|
367
|
+
else this.session(key).trip = trip;
|
|
368
|
+
return trip;
|
|
369
|
+
}
|
|
370
|
+
/** Clears trips, loop history and cap spend. A null key resets everything. */
|
|
371
|
+
reset(key) {
|
|
372
|
+
if (key === null) this.globalTrip = null;
|
|
373
|
+
const targets = key === null ? [...this.sessions.values()] : [this.session(key)];
|
|
374
|
+
for (const s of targets) {
|
|
375
|
+
s.trip = null;
|
|
376
|
+
s.capSpendUsd = 0;
|
|
377
|
+
s.costLog = [];
|
|
378
|
+
s.threads.clear();
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
get global() {
|
|
382
|
+
return this.globalTrip;
|
|
383
|
+
}
|
|
384
|
+
list() {
|
|
385
|
+
return [...this.sessions.values()];
|
|
386
|
+
}
|
|
387
|
+
thread(s, id) {
|
|
388
|
+
let t = s.threads.get(id);
|
|
389
|
+
if (!t) {
|
|
390
|
+
t = { loop: new LoopTracker(Math.max(this.cfg.loop.windowSize, this.cfg.loop.identicalLoopThreshold)), last: null };
|
|
391
|
+
s.threads.set(id, t);
|
|
392
|
+
}
|
|
393
|
+
return t;
|
|
394
|
+
}
|
|
395
|
+
/** The longest current streak across the session's threads. */
|
|
396
|
+
streak(s) {
|
|
397
|
+
let max = 0;
|
|
398
|
+
for (const t of s.threads.values()) max = Math.max(max, t.loop.streak());
|
|
399
|
+
return max;
|
|
400
|
+
}
|
|
401
|
+
evaluate(s, thread) {
|
|
402
|
+
const { loop, spend } = this.cfg;
|
|
403
|
+
const at = this.now();
|
|
404
|
+
const t = s.threads.get(thread);
|
|
405
|
+
const streak = t?.loop.streak() ?? 0;
|
|
406
|
+
if (loop.enabled && streak >= loop.identicalLoopThreshold) {
|
|
407
|
+
const what = t?.last?.kind === "text" ? "identical output" : "identical tool call loop";
|
|
408
|
+
return { kind: "loop", detail: `${what} detected ${streak}x`, at };
|
|
409
|
+
}
|
|
410
|
+
if (!spend.enabled) return null;
|
|
411
|
+
if (s.capSpendUsd >= spend.maxSessionSpendUsd) {
|
|
412
|
+
return { kind: "session_cap", detail: `session spend ${usd(s.capSpendUsd)} reached the ${usd(spend.maxSessionSpendUsd)} cap`, at };
|
|
413
|
+
}
|
|
414
|
+
const rate = this.burnRate(s);
|
|
415
|
+
if (rate >= spend.maxBurnRatePerMinUsd) {
|
|
416
|
+
return { kind: "burn_rate", detail: `spend rate ${usd(rate)}/min passed the ${usd(spend.maxBurnRatePerMinUsd)}/min limit`, at };
|
|
417
|
+
}
|
|
418
|
+
return null;
|
|
419
|
+
}
|
|
420
|
+
};
|
|
421
|
+
|
|
422
|
+
// src/proxy/events.ts
|
|
423
|
+
var EventBus = class {
|
|
424
|
+
constructor(keep = 200) {
|
|
425
|
+
this.keep = keep;
|
|
426
|
+
}
|
|
427
|
+
keep;
|
|
428
|
+
subscribers = /* @__PURE__ */ new Set();
|
|
429
|
+
recent = [];
|
|
430
|
+
emit(e) {
|
|
431
|
+
this.recent.push(e);
|
|
432
|
+
if (this.recent.length > this.keep) this.recent.shift();
|
|
433
|
+
for (const fn of this.subscribers) {
|
|
434
|
+
try {
|
|
435
|
+
fn(e);
|
|
436
|
+
} catch {
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
subscribe(fn) {
|
|
441
|
+
this.subscribers.add(fn);
|
|
442
|
+
return () => this.subscribers.delete(fn);
|
|
443
|
+
}
|
|
444
|
+
history() {
|
|
445
|
+
return this.recent;
|
|
446
|
+
}
|
|
447
|
+
};
|
|
448
|
+
|
|
449
|
+
// src/proxy/pricing.ts
|
|
450
|
+
import { readFileSync as readFileSync3 } from "fs";
|
|
451
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
452
|
+
import { z as z2 } from "zod";
|
|
453
|
+
var price = z2.number().nonnegative();
|
|
454
|
+
var Rates = z2.object({
|
|
455
|
+
input: price,
|
|
456
|
+
output: price,
|
|
457
|
+
cacheRead: price.optional(),
|
|
458
|
+
cacheWrite5m: price.optional(),
|
|
459
|
+
cacheWrite1h: price.optional()
|
|
460
|
+
});
|
|
461
|
+
var ModelPrice = Rates.extend({
|
|
462
|
+
provider: z2.enum(["anthropic", "openai"]),
|
|
463
|
+
/** Higher rates for requests whose whole prompt is above the threshold. */
|
|
464
|
+
longContext: Rates.extend({ aboveInputTokens: z2.number().int().positive() }).optional()
|
|
465
|
+
});
|
|
466
|
+
var PricingFile = z2.object({
|
|
467
|
+
unit: z2.literal("USD per million tokens"),
|
|
468
|
+
verifiedAt: z2.string(),
|
|
469
|
+
sources: z2.array(z2.string()),
|
|
470
|
+
anthropicWebSearchPerRequestUsd: price.default(0),
|
|
471
|
+
models: z2.record(z2.string(), ModelPrice)
|
|
472
|
+
});
|
|
473
|
+
var BUNDLED = fileURLToPath2(new URL("../../pricing.json", import.meta.url));
|
|
474
|
+
function readPricing(path) {
|
|
475
|
+
const result = PricingFile.safeParse(JSON.parse(readFileSync3(path, "utf8")));
|
|
476
|
+
if (!result.success) throw new Error(`Invalid pricing file ${path}:
|
|
477
|
+
${z2.prettifyError(result.error)}`);
|
|
478
|
+
return result.data;
|
|
479
|
+
}
|
|
480
|
+
function loadPricing(overrideFile) {
|
|
481
|
+
const pricing = readPricing(BUNDLED);
|
|
482
|
+
if (!overrideFile) return pricing;
|
|
483
|
+
const override = readPricing(overrideFile);
|
|
484
|
+
return { ...override, models: { ...pricing.models, ...override.models } };
|
|
485
|
+
}
|
|
486
|
+
var SNAPSHOT_SUFFIX = /^(.+)-(\d{8}|\d{4}-\d{2}-\d{2})$/;
|
|
487
|
+
function resolveModel(pricing, model) {
|
|
488
|
+
if (pricing.models[model]) return model;
|
|
489
|
+
const base = SNAPSHOT_SUFFIX.exec(model)?.[1];
|
|
490
|
+
return base && pricing.models[base] ? base : null;
|
|
491
|
+
}
|
|
492
|
+
function costOf(pricing, model, u) {
|
|
493
|
+
const key = resolveModel(pricing, model);
|
|
494
|
+
const entry = key ? pricing.models[key] : void 0;
|
|
495
|
+
if (!key || !entry) return { usd: 0, priced: false, pricedAs: null, provider: null };
|
|
496
|
+
const prompt = u.inputTokens + u.cacheReadTokens + u.cacheWrite5mTokens + u.cacheWrite1hTokens;
|
|
497
|
+
const lc = entry.longContext;
|
|
498
|
+
const r = lc && prompt > lc.aboveInputTokens ? lc : entry;
|
|
499
|
+
const perToken = u.inputTokens * r.input + u.outputTokens * r.output + u.cacheReadTokens * (r.cacheRead ?? r.input) + u.cacheWrite5mTokens * (r.cacheWrite5m ?? r.input * 1.25) + u.cacheWrite1hTokens * (r.cacheWrite1h ?? r.input * 2);
|
|
500
|
+
const searches = entry.provider === "anthropic" ? u.webSearchRequests * pricing.anthropicWebSearchPerRequestUsd : 0;
|
|
501
|
+
return { usd: perToken / 1e6 + searches, priced: true, pricedAs: key, provider: entry.provider };
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
// src/proxy/engine.ts
|
|
505
|
+
var MINUTE_MS2 = 6e4;
|
|
506
|
+
var Engine = class {
|
|
507
|
+
constructor(config, pricing, store = null, now = Date.now) {
|
|
508
|
+
this.config = config;
|
|
509
|
+
this.pricing = pricing;
|
|
510
|
+
this.store = store;
|
|
511
|
+
this.now = now;
|
|
512
|
+
this.breakers = new Breakers(config.breakers, config.sessions.idleTimeoutMinutes * 6e4, now);
|
|
513
|
+
}
|
|
514
|
+
config;
|
|
515
|
+
pricing;
|
|
516
|
+
store;
|
|
517
|
+
now;
|
|
518
|
+
breakers;
|
|
519
|
+
bus = new EventBus();
|
|
520
|
+
seq = 0;
|
|
521
|
+
unpricedWarned = /* @__PURE__ */ new Set();
|
|
522
|
+
logs = /* @__PURE__ */ new Map();
|
|
523
|
+
get dashboardUrl() {
|
|
524
|
+
return `http://localhost:${this.config.server.dashboardPort}`;
|
|
525
|
+
}
|
|
526
|
+
admit(key, provider, model, thread = "") {
|
|
527
|
+
const a = this.breakers.admit(key, thread);
|
|
528
|
+
if (a.allowed) return a;
|
|
529
|
+
const at = this.now();
|
|
530
|
+
if (a.newlyTripped) {
|
|
531
|
+
const loop = a.trip.kind === "loop" ? this.loopDiff(a.session.id, thread, this.breakers.thread(a.session, thread).loop.streak()) : null;
|
|
532
|
+
this.bus.emit({ type: "trip", at, session: a.session.id, trip: a.trip, loop });
|
|
533
|
+
this.store?.recordTrip(a.session.id, a.trip);
|
|
534
|
+
}
|
|
535
|
+
this.bus.emit({ type: "blocked", at, id: this.nextId(), session: a.session.id, provider, model, trip: a.trip, savedUsd: a.session.savedUsd });
|
|
536
|
+
return a;
|
|
537
|
+
}
|
|
538
|
+
tripMessage(a) {
|
|
539
|
+
return `[LoopCap] Circuit breaker tripped: ${a.trip.detail} (~${usd(a.session.savedUsd)} saved). Reset it at ${this.dashboardUrl} to continue.`;
|
|
540
|
+
}
|
|
541
|
+
complete(c) {
|
|
542
|
+
const model = c.turn.model ?? c.requestModel;
|
|
543
|
+
const cost = costOf(this.pricing, model, c.turn.usage);
|
|
544
|
+
const u = c.turn.usage;
|
|
545
|
+
if (!cost.priced && u.inputTokens + u.outputTokens > 0 && !this.unpricedWarned.has(model)) {
|
|
546
|
+
this.unpricedWarned.add(model);
|
|
547
|
+
this.bus.emit({ type: "warning", at: this.now(), message: `No price for model "${model}". Its spend counts as $0 until it is added to pricing.json.` });
|
|
548
|
+
}
|
|
549
|
+
const ok = c.status < 400 && c.complete;
|
|
550
|
+
const thread = c.thread ?? "";
|
|
551
|
+
const fp = ok ? fingerprint(c.turn, this.config.breakers.loop.ignoreArgKeys) : null;
|
|
552
|
+
const s = this.breakers.record(c.key, cost.usd, fp, ok, thread);
|
|
553
|
+
const event = {
|
|
554
|
+
type: "turn",
|
|
555
|
+
at: this.now(),
|
|
556
|
+
id: this.nextId(),
|
|
557
|
+
session: s.id,
|
|
558
|
+
provider: c.provider,
|
|
559
|
+
model,
|
|
560
|
+
status: c.status,
|
|
561
|
+
complete: c.complete,
|
|
562
|
+
latencyMs: Math.round(c.latencyMs),
|
|
563
|
+
usage: u,
|
|
564
|
+
costUsd: cost.usd,
|
|
565
|
+
priced: cost.priced,
|
|
566
|
+
fingerprint: fp?.hash ?? null,
|
|
567
|
+
preview: fp?.preview ?? null,
|
|
568
|
+
streak: ok ? this.breakers.thread(s, thread).loop.streak() : 0,
|
|
569
|
+
health: this.breakers.health(s),
|
|
570
|
+
sessionSpentUsd: s.spentUsd
|
|
571
|
+
};
|
|
572
|
+
const log = this.log(s.id);
|
|
573
|
+
const tokens = u.inputTokens + u.outputTokens + u.cacheReadTokens + u.cacheWrite5mTokens + u.cacheWrite1hTokens;
|
|
574
|
+
if (tokens > 0) log.tokens.push({ at: this.now(), n: tokens });
|
|
575
|
+
if (ok) {
|
|
576
|
+
log.turns.push({ id: event.id, at: event.at, thread, hash: fp?.hash ?? null, preview: fp?.preview ?? "" });
|
|
577
|
+
const keep = 4 * (this.config.breakers.loop.identicalLoopThreshold + this.config.breakers.loop.windowSize);
|
|
578
|
+
if (log.turns.length > keep) log.turns.splice(0, log.turns.length - keep);
|
|
579
|
+
}
|
|
580
|
+
this.bus.emit(event);
|
|
581
|
+
this.store?.recordTurn(event);
|
|
582
|
+
return event;
|
|
583
|
+
}
|
|
584
|
+
/** Everything the dashboard needs to draw itself. */
|
|
585
|
+
snapshot() {
|
|
586
|
+
const now = this.now();
|
|
587
|
+
const { loop, spend } = this.config.breakers;
|
|
588
|
+
const sessions = this.breakers.list().map((s) => {
|
|
589
|
+
const log = this.log(s.id);
|
|
590
|
+
while (log.tokens[0] && log.tokens[0].at < now - MINUTE_MS2) log.tokens.shift();
|
|
591
|
+
return {
|
|
592
|
+
key: s.key,
|
|
593
|
+
id: s.id,
|
|
594
|
+
health: this.breakers.health(s),
|
|
595
|
+
trip: s.trip,
|
|
596
|
+
startedAt: s.startedAt,
|
|
597
|
+
lastSeenAt: s.lastSeenAt,
|
|
598
|
+
spentUsd: s.spentUsd,
|
|
599
|
+
capSpendUsd: s.capSpendUsd,
|
|
600
|
+
savedUsd: s.savedUsd,
|
|
601
|
+
burnRateUsdPerMin: this.breakers.burnRate(s),
|
|
602
|
+
tokensPerSec: log.tokens.reduce((sum, t) => sum + t.n, 0) / 60,
|
|
603
|
+
turns: s.turns,
|
|
604
|
+
blocked: s.blocked,
|
|
605
|
+
streak: this.breakers.streak(s)
|
|
606
|
+
};
|
|
607
|
+
});
|
|
608
|
+
return {
|
|
609
|
+
at: now,
|
|
610
|
+
limits: {
|
|
611
|
+
maxSessionSpendUsd: spend.maxSessionSpendUsd,
|
|
612
|
+
maxBurnRatePerMinUsd: spend.maxBurnRatePerMinUsd,
|
|
613
|
+
identicalLoopThreshold: loop.identicalLoopThreshold,
|
|
614
|
+
warnAtFraction: spend.warnAtFraction
|
|
615
|
+
},
|
|
616
|
+
globalTrip: this.breakers.global,
|
|
617
|
+
sessions,
|
|
618
|
+
recent: [...this.bus.history()]
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
log(sessionId) {
|
|
622
|
+
let l = this.logs.get(sessionId);
|
|
623
|
+
if (!l) this.logs.set(sessionId, l = { turns: [], tokens: [] });
|
|
624
|
+
return l;
|
|
625
|
+
}
|
|
626
|
+
loopDiff(sessionId, thread, streak) {
|
|
627
|
+
const turns = this.log(sessionId).turns.filter((t) => t.thread === thread);
|
|
628
|
+
const run = turns.slice(Math.max(0, turns.length - streak));
|
|
629
|
+
const first = run[0];
|
|
630
|
+
if (!first?.hash) return null;
|
|
631
|
+
const before = turns.at(-run.length - 1) ?? null;
|
|
632
|
+
const view = (t) => ({ id: t.id, at: t.at, preview: t.preview });
|
|
633
|
+
return { fingerprint: first.hash, repeats: run.length, turns: run.map(view), before: before ? view(before) : null };
|
|
634
|
+
}
|
|
635
|
+
/** Manual kill switch. A null key trips every session. */
|
|
636
|
+
trip(key, detail = "tripped manually") {
|
|
637
|
+
const trip = this.breakers.trip(key, detail);
|
|
638
|
+
const session = key === null ? null : this.breakers.session(key).id;
|
|
639
|
+
this.bus.emit({ type: "trip", at: trip.at, session, trip, loop: null });
|
|
640
|
+
this.store?.recordTrip(session, trip);
|
|
641
|
+
return trip;
|
|
642
|
+
}
|
|
643
|
+
reset(key) {
|
|
644
|
+
this.breakers.reset(key);
|
|
645
|
+
for (const s of key === null ? this.breakers.list() : [this.breakers.session(key)]) this.log(s.id).turns = [];
|
|
646
|
+
this.bus.emit({ type: "reset", at: this.now(), session: key === null ? null : this.breakers.session(key).id });
|
|
647
|
+
}
|
|
648
|
+
nextId() {
|
|
649
|
+
return `${this.now().toString(36)}-${(++this.seq).toString(36)}`;
|
|
650
|
+
}
|
|
651
|
+
};
|
|
652
|
+
|
|
653
|
+
// src/proxy/server.ts
|
|
654
|
+
import { Hono as Hono2 } from "hono";
|
|
655
|
+
|
|
656
|
+
// src/proxy/sse.ts
|
|
657
|
+
var BOUNDARY = /\r?\n\r?\n/g;
|
|
658
|
+
var SseParser = class {
|
|
659
|
+
buffer = "";
|
|
660
|
+
push(text) {
|
|
661
|
+
this.buffer += text;
|
|
662
|
+
const events = [];
|
|
663
|
+
let start2 = 0;
|
|
664
|
+
BOUNDARY.lastIndex = 0;
|
|
665
|
+
for (let m = BOUNDARY.exec(this.buffer); m; m = BOUNDARY.exec(this.buffer)) {
|
|
666
|
+
events.push(parseEvent(this.buffer.slice(start2, BOUNDARY.lastIndex)));
|
|
667
|
+
start2 = BOUNDARY.lastIndex;
|
|
668
|
+
}
|
|
669
|
+
this.buffer = this.buffer.slice(start2);
|
|
670
|
+
return events;
|
|
671
|
+
}
|
|
672
|
+
/** Returns whatever is left when the stream ends without a final blank line. */
|
|
673
|
+
flush() {
|
|
674
|
+
const rest = this.buffer;
|
|
675
|
+
this.buffer = "";
|
|
676
|
+
return rest ? [parseEvent(rest)] : [];
|
|
677
|
+
}
|
|
678
|
+
};
|
|
679
|
+
function parseEvent(raw) {
|
|
680
|
+
let event = null;
|
|
681
|
+
const data = [];
|
|
682
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
683
|
+
if (!line || line.startsWith(":")) continue;
|
|
684
|
+
const colon = line.indexOf(":");
|
|
685
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
686
|
+
let value = colon === -1 ? "" : line.slice(colon + 1);
|
|
687
|
+
if (value.startsWith(" ")) value = value.slice(1);
|
|
688
|
+
if (field === "event") event = value;
|
|
689
|
+
else if (field === "data") data.push(value);
|
|
690
|
+
}
|
|
691
|
+
return { event, data: data.join("\n"), raw };
|
|
692
|
+
}
|
|
693
|
+
function formatSse(event, data) {
|
|
694
|
+
const payload = typeof data === "string" ? data : JSON.stringify(data);
|
|
695
|
+
return `${event ? `event: ${event}
|
|
696
|
+
` : ""}data: ${payload}
|
|
697
|
+
|
|
698
|
+
`;
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
// src/proxy/interceptor.ts
|
|
702
|
+
function intercept(provider, { strip }, onDone) {
|
|
703
|
+
const parser = new SseParser();
|
|
704
|
+
const acc = provider.accumulator();
|
|
705
|
+
const decoder = new TextDecoder();
|
|
706
|
+
const encoder = new TextEncoder();
|
|
707
|
+
let finished = false;
|
|
708
|
+
const finish = (complete) => {
|
|
709
|
+
if (finished) return;
|
|
710
|
+
finished = true;
|
|
711
|
+
onDone(acc.turn(), complete);
|
|
712
|
+
};
|
|
713
|
+
const handle = (events, ctrl) => {
|
|
714
|
+
for (const e of events) {
|
|
715
|
+
acc.push(e);
|
|
716
|
+
if (strip && !provider.isUsageOnlyChunk(e)) ctrl.enqueue(encoder.encode(e.raw));
|
|
717
|
+
}
|
|
718
|
+
};
|
|
719
|
+
return new TransformStream({
|
|
720
|
+
transform(chunk, ctrl) {
|
|
721
|
+
if (!strip) ctrl.enqueue(chunk);
|
|
722
|
+
handle(parser.push(decoder.decode(chunk, { stream: true })), ctrl);
|
|
723
|
+
},
|
|
724
|
+
flush(ctrl) {
|
|
725
|
+
handle(parser.push(decoder.decode()), ctrl);
|
|
726
|
+
handle(parser.flush(), ctrl);
|
|
727
|
+
finish(true);
|
|
728
|
+
},
|
|
729
|
+
cancel() {
|
|
730
|
+
finish(false);
|
|
731
|
+
}
|
|
732
|
+
});
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
// src/proxy/providers/anthropic.ts
|
|
736
|
+
import { randomUUID } from "crypto";
|
|
737
|
+
|
|
738
|
+
// src/proxy/types.ts
|
|
739
|
+
var emptyUsage = () => ({
|
|
740
|
+
inputTokens: 0,
|
|
741
|
+
outputTokens: 0,
|
|
742
|
+
cacheReadTokens: 0,
|
|
743
|
+
cacheWrite5mTokens: 0,
|
|
744
|
+
cacheWrite1hTokens: 0,
|
|
745
|
+
webSearchRequests: 0
|
|
746
|
+
});
|
|
747
|
+
var emptyTurn = () => ({
|
|
748
|
+
model: null,
|
|
749
|
+
usage: emptyUsage(),
|
|
750
|
+
toolCalls: [],
|
|
751
|
+
text: "",
|
|
752
|
+
stopReason: null
|
|
753
|
+
});
|
|
754
|
+
|
|
755
|
+
// src/proxy/providers/shared.ts
|
|
756
|
+
function parseJson(text) {
|
|
757
|
+
try {
|
|
758
|
+
return JSON.parse(text);
|
|
759
|
+
} catch {
|
|
760
|
+
return null;
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
function respond(body, { stream, status = 200, tripped }) {
|
|
764
|
+
const headers = new Headers({
|
|
765
|
+
"content-type": stream ? "text/event-stream; charset=utf-8" : "application/json",
|
|
766
|
+
"cache-control": "no-cache"
|
|
767
|
+
});
|
|
768
|
+
if (tripped) headers.set("x-loopcap-tripped", tripped);
|
|
769
|
+
return new Response(body, { status, headers });
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
// src/proxy/providers/anthropic.ts
|
|
773
|
+
function applyUsage(target, u) {
|
|
774
|
+
if (u.input_tokens != null) target.inputTokens = u.input_tokens;
|
|
775
|
+
if (u.output_tokens != null) target.outputTokens = u.output_tokens;
|
|
776
|
+
if (u.cache_read_input_tokens != null) target.cacheReadTokens = u.cache_read_input_tokens;
|
|
777
|
+
if (u.cache_creation) {
|
|
778
|
+
target.cacheWrite5mTokens = u.cache_creation.ephemeral_5m_input_tokens ?? 0;
|
|
779
|
+
target.cacheWrite1hTokens = u.cache_creation.ephemeral_1h_input_tokens ?? 0;
|
|
780
|
+
} else if (u.cache_creation_input_tokens != null) {
|
|
781
|
+
target.cacheWrite5mTokens = u.cache_creation_input_tokens;
|
|
782
|
+
target.cacheWrite1hTokens = 0;
|
|
783
|
+
}
|
|
784
|
+
const searches = u.server_tool_use?.web_search_requests;
|
|
785
|
+
if (searches != null) target.webSearchRequests = searches;
|
|
786
|
+
}
|
|
787
|
+
var isTool = (b) => b.type === "tool_use" || b.type === "server_tool_use";
|
|
788
|
+
var StreamAccumulator = class {
|
|
789
|
+
t = emptyTurn();
|
|
790
|
+
tools = /* @__PURE__ */ new Map();
|
|
791
|
+
push(e) {
|
|
792
|
+
const ev = parseJson(e.data);
|
|
793
|
+
if (!ev) return;
|
|
794
|
+
switch (ev.type) {
|
|
795
|
+
case "message_start":
|
|
796
|
+
if (ev.message?.model) this.t.model = ev.message.model;
|
|
797
|
+
if (ev.message?.usage) applyUsage(this.t.usage, ev.message.usage);
|
|
798
|
+
break;
|
|
799
|
+
case "content_block_start": {
|
|
800
|
+
const b = ev.content_block;
|
|
801
|
+
if (!b || ev.index === void 0) break;
|
|
802
|
+
if (isTool(b)) {
|
|
803
|
+
this.tools.set(ev.index, { name: b.name ?? "", args: "", initial: JSON.stringify(b.input ?? {}) });
|
|
804
|
+
} else if (b.type === "text" && b.text) {
|
|
805
|
+
this.t.text += b.text;
|
|
806
|
+
}
|
|
807
|
+
break;
|
|
808
|
+
}
|
|
809
|
+
case "content_block_delta": {
|
|
810
|
+
const d = ev.delta;
|
|
811
|
+
if (d?.type === "text_delta" && d.text) this.t.text += d.text;
|
|
812
|
+
if (d?.type === "input_json_delta" && d.partial_json && ev.index !== void 0) {
|
|
813
|
+
const tool = this.tools.get(ev.index);
|
|
814
|
+
if (tool) tool.args += d.partial_json;
|
|
815
|
+
}
|
|
816
|
+
break;
|
|
817
|
+
}
|
|
818
|
+
case "message_delta":
|
|
819
|
+
if (ev.usage) applyUsage(this.t.usage, ev.usage);
|
|
820
|
+
if (ev.delta?.stop_reason) this.t.stopReason = ev.delta.stop_reason;
|
|
821
|
+
break;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
turn() {
|
|
825
|
+
this.t.toolCalls = [...this.tools.entries()].sort(([a], [b]) => a - b).map(([, c]) => ({ name: c.name, args: c.args || c.initial }));
|
|
826
|
+
return this.t;
|
|
827
|
+
}
|
|
828
|
+
};
|
|
829
|
+
function fromJson(body) {
|
|
830
|
+
const m = body;
|
|
831
|
+
const t = emptyTurn();
|
|
832
|
+
t.model = m.model ?? null;
|
|
833
|
+
t.stopReason = m.stop_reason ?? null;
|
|
834
|
+
if (m.usage) applyUsage(t.usage, m.usage);
|
|
835
|
+
for (const b of m.content ?? []) {
|
|
836
|
+
if (isTool(b)) t.toolCalls.push({ name: b.name ?? "", args: JSON.stringify(b.input ?? {}) });
|
|
837
|
+
else if (b.type === "text" && b.text) t.text += b.text;
|
|
838
|
+
}
|
|
839
|
+
return t;
|
|
840
|
+
}
|
|
841
|
+
function tripResponse({ model, message, stream, kind }) {
|
|
842
|
+
const id = `msg_loopcap_${randomUUID().replaceAll("-", "")}`;
|
|
843
|
+
const usage = { input_tokens: 0, output_tokens: 0 };
|
|
844
|
+
if (!stream) {
|
|
845
|
+
const msg = {
|
|
846
|
+
id,
|
|
847
|
+
type: "message",
|
|
848
|
+
role: "assistant",
|
|
849
|
+
model,
|
|
850
|
+
content: [{ type: "text", text: message }],
|
|
851
|
+
stop_reason: "end_turn",
|
|
852
|
+
stop_sequence: null,
|
|
853
|
+
usage
|
|
854
|
+
};
|
|
855
|
+
return respond(JSON.stringify(msg), { stream, tripped: kind });
|
|
856
|
+
}
|
|
857
|
+
const body = [
|
|
858
|
+
formatSse("message_start", {
|
|
859
|
+
type: "message_start",
|
|
860
|
+
message: { id, type: "message", role: "assistant", model, content: [], stop_reason: null, stop_sequence: null, usage }
|
|
861
|
+
}),
|
|
862
|
+
formatSse("content_block_start", { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } }),
|
|
863
|
+
formatSse("content_block_delta", { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: message } }),
|
|
864
|
+
formatSse("content_block_stop", { type: "content_block_stop", index: 0 }),
|
|
865
|
+
formatSse("message_delta", {
|
|
866
|
+
type: "message_delta",
|
|
867
|
+
delta: { stop_reason: "end_turn", stop_sequence: null },
|
|
868
|
+
usage: { output_tokens: 0 }
|
|
869
|
+
}),
|
|
870
|
+
formatSse("message_stop", { type: "message_stop" })
|
|
871
|
+
].join("");
|
|
872
|
+
return respond(body, { stream, tripped: kind });
|
|
873
|
+
}
|
|
874
|
+
var anthropic = {
|
|
875
|
+
name: "anthropic",
|
|
876
|
+
accumulator: () => new StreamAccumulator(),
|
|
877
|
+
fromJson,
|
|
878
|
+
tripResponse,
|
|
879
|
+
errorResponse: (status, message) => respond(JSON.stringify({ type: "error", error: { type: "api_error", message } }), { stream: false, status }),
|
|
880
|
+
isUsageOnlyChunk: () => false
|
|
881
|
+
};
|
|
882
|
+
|
|
883
|
+
// src/proxy/providers/openai.ts
|
|
884
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
885
|
+
function applyUsage2(target, u) {
|
|
886
|
+
const cached = u.prompt_tokens_details?.cached_tokens ?? 0;
|
|
887
|
+
target.inputTokens = Math.max(0, (u.prompt_tokens ?? 0) - cached);
|
|
888
|
+
target.cacheReadTokens = cached;
|
|
889
|
+
target.outputTokens = u.completion_tokens ?? 0;
|
|
890
|
+
}
|
|
891
|
+
var StreamAccumulator2 = class {
|
|
892
|
+
t = emptyTurn();
|
|
893
|
+
tools = /* @__PURE__ */ new Map();
|
|
894
|
+
push(e) {
|
|
895
|
+
if (e.data === "[DONE]") return;
|
|
896
|
+
const c = parseJson(e.data);
|
|
897
|
+
if (!c) return;
|
|
898
|
+
if (c.model) this.t.model = c.model;
|
|
899
|
+
if (c.usage) applyUsage2(this.t.usage, c.usage);
|
|
900
|
+
const choice = c.choices?.find((ch) => (ch.index ?? 0) === 0);
|
|
901
|
+
if (!choice) return;
|
|
902
|
+
if (choice.delta?.content) this.t.text += choice.delta.content;
|
|
903
|
+
for (const tc of choice.delta?.tool_calls ?? []) {
|
|
904
|
+
const i = tc.index ?? 0;
|
|
905
|
+
const call = this.tools.get(i) ?? { name: "", args: "" };
|
|
906
|
+
call.name += tc.function?.name ?? "";
|
|
907
|
+
call.args += tc.function?.arguments ?? "";
|
|
908
|
+
this.tools.set(i, call);
|
|
909
|
+
}
|
|
910
|
+
if (choice.finish_reason) this.t.stopReason = choice.finish_reason;
|
|
911
|
+
}
|
|
912
|
+
turn() {
|
|
913
|
+
this.t.toolCalls = [...this.tools.entries()].sort(([a], [b]) => a - b).map(([, c]) => c);
|
|
914
|
+
return this.t;
|
|
915
|
+
}
|
|
916
|
+
};
|
|
917
|
+
function fromJson2(body) {
|
|
918
|
+
const c = body;
|
|
919
|
+
const t = emptyTurn();
|
|
920
|
+
t.model = c.model ?? null;
|
|
921
|
+
if (c.usage) applyUsage2(t.usage, c.usage);
|
|
922
|
+
const choice = c.choices?.find((ch) => (ch.index ?? 0) === 0);
|
|
923
|
+
t.text = choice?.message?.content ?? "";
|
|
924
|
+
t.stopReason = choice?.finish_reason ?? null;
|
|
925
|
+
t.toolCalls = (choice?.message?.tool_calls ?? []).map((tc) => ({
|
|
926
|
+
name: tc.function?.name ?? "",
|
|
927
|
+
args: tc.function?.arguments ?? ""
|
|
928
|
+
}));
|
|
929
|
+
return t;
|
|
930
|
+
}
|
|
931
|
+
function tripResponse2({ model, message, stream, includeUsage, kind }) {
|
|
932
|
+
const id = `chatcmpl-loopcap-${randomUUID2()}`;
|
|
933
|
+
const created = Math.floor(Date.now() / 1e3);
|
|
934
|
+
const usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };
|
|
935
|
+
if (!stream) {
|
|
936
|
+
const completion = {
|
|
937
|
+
id,
|
|
938
|
+
object: "chat.completion",
|
|
939
|
+
created,
|
|
940
|
+
model,
|
|
941
|
+
choices: [{ index: 0, message: { role: "assistant", content: message, refusal: null }, logprobs: null, finish_reason: "stop" }],
|
|
942
|
+
usage
|
|
943
|
+
};
|
|
944
|
+
return respond(JSON.stringify(completion), { stream, tripped: kind });
|
|
945
|
+
}
|
|
946
|
+
const base = { id, object: "chat.completion.chunk", created, model };
|
|
947
|
+
const chunks = [
|
|
948
|
+
{ ...base, choices: [{ index: 0, delta: { role: "assistant", content: message }, logprobs: null, finish_reason: null }] },
|
|
949
|
+
{ ...base, choices: [{ index: 0, delta: {}, logprobs: null, finish_reason: "stop" }] }
|
|
950
|
+
];
|
|
951
|
+
if (includeUsage) chunks.push({ ...base, choices: [], usage });
|
|
952
|
+
const body = chunks.map((c) => formatSse(null, c)).join("") + formatSse(null, "[DONE]");
|
|
953
|
+
return respond(body, { stream, tripped: kind });
|
|
954
|
+
}
|
|
955
|
+
var openai = {
|
|
956
|
+
name: "openai",
|
|
957
|
+
accumulator: () => new StreamAccumulator2(),
|
|
958
|
+
fromJson: fromJson2,
|
|
959
|
+
tripResponse: tripResponse2,
|
|
960
|
+
errorResponse: (status, message) => respond(JSON.stringify({ error: { message, type: "loopcap_error", param: null, code: null } }), {
|
|
961
|
+
stream: false,
|
|
962
|
+
status
|
|
963
|
+
}),
|
|
964
|
+
isUsageOnlyChunk(e) {
|
|
965
|
+
if (e.data === "[DONE]") return false;
|
|
966
|
+
const c = parseJson(e.data);
|
|
967
|
+
return !!c && Array.isArray(c.choices) && c.choices.length === 0 && c.usage != null;
|
|
968
|
+
}
|
|
969
|
+
};
|
|
970
|
+
|
|
971
|
+
// src/proxy/providers/index.ts
|
|
972
|
+
var providers = { anthropic, openai };
|
|
973
|
+
|
|
974
|
+
// src/proxy/simulator.ts
|
|
975
|
+
var DEMO_HEADER = "x-loopcap-demo";
|
|
976
|
+
var TOOL_NAME = "bash";
|
|
977
|
+
var TOOL_ARGS = '{"command":"npm test"}';
|
|
978
|
+
var INPUT_TOKENS = 62e3;
|
|
979
|
+
var OUTPUT_TOKENS = 2800;
|
|
980
|
+
var STEP_MS = 90;
|
|
981
|
+
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
982
|
+
function paced(frames, signal) {
|
|
983
|
+
const enc = new TextEncoder();
|
|
984
|
+
let i = 0;
|
|
985
|
+
return new ReadableStream({
|
|
986
|
+
async pull(controller) {
|
|
987
|
+
if (i >= frames.length || signal?.aborted) return controller.close();
|
|
988
|
+
if (i > 0) await sleep(STEP_MS);
|
|
989
|
+
controller.enqueue(enc.encode(frames[i++]));
|
|
990
|
+
}
|
|
991
|
+
});
|
|
992
|
+
}
|
|
993
|
+
var sse = (stream) => new Response(stream, { headers: { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-cache" } });
|
|
994
|
+
function anthropic2(stream, signal) {
|
|
995
|
+
const model = "claude-sonnet-5-5";
|
|
996
|
+
const input = { command: "npm test" };
|
|
997
|
+
if (!stream) {
|
|
998
|
+
return Response.json({
|
|
999
|
+
id: "msg_sim",
|
|
1000
|
+
type: "message",
|
|
1001
|
+
role: "assistant",
|
|
1002
|
+
model,
|
|
1003
|
+
stop_reason: "tool_use",
|
|
1004
|
+
content: [{ type: "tool_use", id: "toolu_sim", name: TOOL_NAME, input }],
|
|
1005
|
+
usage: { input_tokens: INPUT_TOKENS, output_tokens: OUTPUT_TOKENS }
|
|
1006
|
+
});
|
|
1007
|
+
}
|
|
1008
|
+
const ev = (e) => formatSse(e.type, e);
|
|
1009
|
+
const delta = (partial_json) => ev({ type: "content_block_delta", index: 1, delta: { type: "input_json_delta", partial_json } });
|
|
1010
|
+
return sse(paced([
|
|
1011
|
+
ev({ type: "message_start", message: { id: "msg_sim", type: "message", role: "assistant", model, content: [], usage: { input_tokens: INPUT_TOKENS, output_tokens: 1, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 } } }),
|
|
1012
|
+
ev({ type: "content_block_start", index: 0, content_block: { type: "text", text: "" } }),
|
|
1013
|
+
ev({ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "Running the tests again." } }),
|
|
1014
|
+
ev({ type: "content_block_stop", index: 0 }),
|
|
1015
|
+
ev({ type: "content_block_start", index: 1, content_block: { type: "tool_use", id: "toolu_sim", name: TOOL_NAME, input: {} } }),
|
|
1016
|
+
delta('{"command":'),
|
|
1017
|
+
delta(' "npm test"}'),
|
|
1018
|
+
ev({ type: "content_block_stop", index: 1 }),
|
|
1019
|
+
ev({ type: "message_delta", delta: { stop_reason: "tool_use" }, usage: { output_tokens: OUTPUT_TOKENS } }),
|
|
1020
|
+
ev({ type: "message_stop" })
|
|
1021
|
+
], signal));
|
|
1022
|
+
}
|
|
1023
|
+
function openai2(stream, includeUsage, signal) {
|
|
1024
|
+
const model = "gpt-6.1-sol";
|
|
1025
|
+
const usage = { prompt_tokens: INPUT_TOKENS, completion_tokens: OUTPUT_TOKENS, total_tokens: INPUT_TOKENS + OUTPUT_TOKENS, prompt_tokens_details: { cached_tokens: 0 } };
|
|
1026
|
+
if (!stream) {
|
|
1027
|
+
return Response.json({
|
|
1028
|
+
id: "chatcmpl-sim",
|
|
1029
|
+
object: "chat.completion",
|
|
1030
|
+
created: 0,
|
|
1031
|
+
model,
|
|
1032
|
+
choices: [{ index: 0, finish_reason: "tool_calls", message: { role: "assistant", content: null, tool_calls: [{ id: "call_sim", type: "function", function: { name: TOOL_NAME, arguments: TOOL_ARGS } }] } }],
|
|
1033
|
+
usage
|
|
1034
|
+
});
|
|
1035
|
+
}
|
|
1036
|
+
const chunk = (delta, finish = null) => formatSse(null, { id: "chatcmpl-sim", object: "chat.completion.chunk", created: 0, model, choices: [{ index: 0, delta, finish_reason: finish }] });
|
|
1037
|
+
const call = (fn) => ({ tool_calls: [{ index: 0, function: fn }] });
|
|
1038
|
+
const frames = [
|
|
1039
|
+
chunk({ role: "assistant", content: null }),
|
|
1040
|
+
chunk({ tool_calls: [{ index: 0, id: "call_sim", type: "function", function: { name: TOOL_NAME, arguments: "" } }] }),
|
|
1041
|
+
chunk(call({ arguments: '{"command":' })),
|
|
1042
|
+
chunk(call({ arguments: ' "npm test"}' })),
|
|
1043
|
+
chunk({}, "tool_calls")
|
|
1044
|
+
];
|
|
1045
|
+
if (includeUsage) frames.push(formatSse(null, { id: "chatcmpl-sim", object: "chat.completion.chunk", created: 0, model, choices: [], usage }));
|
|
1046
|
+
frames.push(formatSse(null, "[DONE]"));
|
|
1047
|
+
return sse(paced(frames, signal));
|
|
1048
|
+
}
|
|
1049
|
+
function simulateUpstream(name, body, signal) {
|
|
1050
|
+
const stream = body.stream === true;
|
|
1051
|
+
return name === "anthropic" ? anthropic2(stream, signal) : openai2(stream, body.stream_options?.include_usage === true, signal);
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
// src/proxy/server.ts
|
|
1055
|
+
function threadKey(body) {
|
|
1056
|
+
if (!Array.isArray(body.tools)) return "";
|
|
1057
|
+
const names = body.tools.map((t) => {
|
|
1058
|
+
const tool = t;
|
|
1059
|
+
const name = tool?.name ?? tool?.function?.name ?? tool?.type;
|
|
1060
|
+
return typeof name === "string" ? name : "?";
|
|
1061
|
+
});
|
|
1062
|
+
return names.sort().join(",");
|
|
1063
|
+
}
|
|
1064
|
+
var DROP_FROM_REQUEST = /* @__PURE__ */ new Set([
|
|
1065
|
+
"connection",
|
|
1066
|
+
"keep-alive",
|
|
1067
|
+
"proxy-authenticate",
|
|
1068
|
+
"proxy-authorization",
|
|
1069
|
+
"te",
|
|
1070
|
+
"trailer",
|
|
1071
|
+
"transfer-encoding",
|
|
1072
|
+
"upgrade",
|
|
1073
|
+
"host",
|
|
1074
|
+
"content-length",
|
|
1075
|
+
"accept-encoding"
|
|
1076
|
+
]);
|
|
1077
|
+
var DROP_FROM_RESPONSE = /* @__PURE__ */ new Set(["connection", "keep-alive", "transfer-encoding", "content-encoding", "content-length"]);
|
|
1078
|
+
var errorText = (err) => err instanceof Error ? err.message : String(err);
|
|
1079
|
+
function createProxyApp({ config, engine, fetch: send = (input, init2) => fetch(input, init2) }) {
|
|
1080
|
+
const sessionHeader = config.sessions.header.toLowerCase();
|
|
1081
|
+
const upstreamUrl = (name, url) => config.upstreams[name].replace(/\/+$/, "") + url.pathname + url.search;
|
|
1082
|
+
const requestHeaders = (h) => {
|
|
1083
|
+
const out = new Headers();
|
|
1084
|
+
h.forEach((value, key) => {
|
|
1085
|
+
if (!DROP_FROM_REQUEST.has(key) && key !== sessionHeader && !key.startsWith("x-loopcap-")) out.append(key, value);
|
|
1086
|
+
});
|
|
1087
|
+
return out;
|
|
1088
|
+
};
|
|
1089
|
+
const responseHeaders = (h) => {
|
|
1090
|
+
const out = new Headers();
|
|
1091
|
+
h.forEach((value, key) => {
|
|
1092
|
+
if (!DROP_FROM_RESPONSE.has(key)) out.append(key, value);
|
|
1093
|
+
});
|
|
1094
|
+
return out;
|
|
1095
|
+
};
|
|
1096
|
+
const unreachable = (name, err) => providers[name].errorResponse(502, `LoopCap could not reach ${config.upstreams[name]}: ${errorText(err)}`);
|
|
1097
|
+
async function relay(req, name, body) {
|
|
1098
|
+
const payload = body ?? (req.method === "GET" || req.method === "HEAD" ? null : await req.arrayBuffer());
|
|
1099
|
+
try {
|
|
1100
|
+
const res = await send(upstreamUrl(name, new URL(req.url)), {
|
|
1101
|
+
method: req.method,
|
|
1102
|
+
headers: requestHeaders(req.headers),
|
|
1103
|
+
body: payload,
|
|
1104
|
+
signal: req.signal,
|
|
1105
|
+
redirect: "manual"
|
|
1106
|
+
});
|
|
1107
|
+
return new Response(res.body, { status: res.status, headers: responseHeaders(res.headers) });
|
|
1108
|
+
} catch (err) {
|
|
1109
|
+
return unreachable(name, err);
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
async function handle(req, name) {
|
|
1113
|
+
const provider = providers[name];
|
|
1114
|
+
const text = await req.text();
|
|
1115
|
+
const body = parseJson(text);
|
|
1116
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) return relay(req, name, text);
|
|
1117
|
+
const key = req.headers.get(sessionHeader) || "default";
|
|
1118
|
+
const model = typeof body.model === "string" ? body.model : "unknown";
|
|
1119
|
+
const stream = body.stream === true;
|
|
1120
|
+
const clientWantsUsage = body.stream_options?.include_usage === true;
|
|
1121
|
+
const thread = threadKey(body);
|
|
1122
|
+
const admission = engine.admit(key, name, model, thread);
|
|
1123
|
+
if (!admission.allowed) {
|
|
1124
|
+
return provider.tripResponse({
|
|
1125
|
+
model,
|
|
1126
|
+
stream,
|
|
1127
|
+
includeUsage: clientWantsUsage,
|
|
1128
|
+
kind: admission.trip.kind,
|
|
1129
|
+
message: engine.tripMessage(admission)
|
|
1130
|
+
});
|
|
1131
|
+
}
|
|
1132
|
+
const strip = name === "openai" && stream && !clientWantsUsage;
|
|
1133
|
+
const outbound = strip ? JSON.stringify({ ...body, stream_options: { ...body.stream_options ?? {}, include_usage: true } }) : text;
|
|
1134
|
+
const started = performance.now();
|
|
1135
|
+
const demo2 = req.headers.get(DEMO_HEADER) === "1";
|
|
1136
|
+
let res;
|
|
1137
|
+
try {
|
|
1138
|
+
res = demo2 ? simulateUpstream(name, JSON.parse(outbound), req.signal) : await send(upstreamUrl(name, new URL(req.url)), {
|
|
1139
|
+
method: "POST",
|
|
1140
|
+
headers: requestHeaders(req.headers),
|
|
1141
|
+
body: outbound,
|
|
1142
|
+
signal: req.signal,
|
|
1143
|
+
redirect: "manual"
|
|
1144
|
+
});
|
|
1145
|
+
} catch (err) {
|
|
1146
|
+
return unreachable(name, err);
|
|
1147
|
+
}
|
|
1148
|
+
const finish = (turn, complete) => engine.complete({ key, provider: name, requestModel: model, thread, turn, status: res.status, latencyMs: performance.now() - started, complete });
|
|
1149
|
+
const headers = responseHeaders(res.headers);
|
|
1150
|
+
const isSse = res.headers.get("content-type")?.includes("text/event-stream") ?? false;
|
|
1151
|
+
if (res.ok && isSse && res.body) {
|
|
1152
|
+
return new Response(res.body.pipeThrough(intercept(provider, { strip }, finish)), { status: res.status, headers });
|
|
1153
|
+
}
|
|
1154
|
+
const out = await res.text();
|
|
1155
|
+
const parsed = res.ok ? parseJson(out) : null;
|
|
1156
|
+
finish(parsed ? provider.fromJson(parsed) : emptyTurn(), true);
|
|
1157
|
+
return new Response(out, { status: res.status, headers });
|
|
1158
|
+
}
|
|
1159
|
+
const detect = (req) => {
|
|
1160
|
+
const path = new URL(req.url).pathname;
|
|
1161
|
+
const h = req.headers;
|
|
1162
|
+
const anthropic3 = !path.startsWith("/v1/") || path.startsWith("/v1/messages") || h.has("anthropic-version") || h.has("anthropic-beta") || h.has("x-api-key");
|
|
1163
|
+
return anthropic3 ? "anthropic" : "openai";
|
|
1164
|
+
};
|
|
1165
|
+
const app = new Hono2();
|
|
1166
|
+
app.get("/_loopcap/health", (c) => c.json({ ok: true }));
|
|
1167
|
+
app.post("/v1/messages", (c) => handle(c.req.raw, "anthropic"));
|
|
1168
|
+
app.post("/v1/chat/completions", (c) => handle(c.req.raw, "openai"));
|
|
1169
|
+
app.all("*", (c) => relay(c.req.raw, detect(c.req.raw)));
|
|
1170
|
+
return app;
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
// src/proxy/store.ts
|
|
1174
|
+
import { mkdirSync } from "fs";
|
|
1175
|
+
import { dirname } from "path";
|
|
1176
|
+
import { createRequire } from "module";
|
|
1177
|
+
var { DatabaseSync: Database } = createRequire(import.meta.url)("node:sqlite");
|
|
1178
|
+
var Store = class {
|
|
1179
|
+
db;
|
|
1180
|
+
insertTurn;
|
|
1181
|
+
insertTrip;
|
|
1182
|
+
constructor(path) {
|
|
1183
|
+
if (path !== ":memory:") mkdirSync(dirname(path), { recursive: true, mode: 448 });
|
|
1184
|
+
this.db = new Database(path);
|
|
1185
|
+
this.db.exec(`
|
|
1186
|
+
PRAGMA journal_mode = WAL;
|
|
1187
|
+
CREATE TABLE IF NOT EXISTS turns (
|
|
1188
|
+
id TEXT PRIMARY KEY,
|
|
1189
|
+
at INTEGER NOT NULL,
|
|
1190
|
+
session TEXT NOT NULL,
|
|
1191
|
+
provider TEXT NOT NULL,
|
|
1192
|
+
model TEXT NOT NULL,
|
|
1193
|
+
status INTEGER NOT NULL,
|
|
1194
|
+
complete INTEGER NOT NULL,
|
|
1195
|
+
latency_ms REAL NOT NULL,
|
|
1196
|
+
input_tokens INTEGER NOT NULL,
|
|
1197
|
+
output_tokens INTEGER NOT NULL,
|
|
1198
|
+
cache_read_tokens INTEGER NOT NULL,
|
|
1199
|
+
cache_write_tokens INTEGER NOT NULL,
|
|
1200
|
+
cost_usd REAL NOT NULL,
|
|
1201
|
+
priced INTEGER NOT NULL,
|
|
1202
|
+
fingerprint TEXT
|
|
1203
|
+
);
|
|
1204
|
+
CREATE INDEX IF NOT EXISTS turns_by_session ON turns (session, at);
|
|
1205
|
+
CREATE TABLE IF NOT EXISTS trips (
|
|
1206
|
+
at INTEGER NOT NULL,
|
|
1207
|
+
session TEXT,
|
|
1208
|
+
kind TEXT NOT NULL,
|
|
1209
|
+
detail TEXT NOT NULL
|
|
1210
|
+
);
|
|
1211
|
+
`);
|
|
1212
|
+
this.insertTurn = this.db.prepare(
|
|
1213
|
+
"INSERT OR REPLACE INTO turns VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
|
|
1214
|
+
);
|
|
1215
|
+
this.insertTrip = this.db.prepare("INSERT INTO trips VALUES (?, ?, ?, ?)");
|
|
1216
|
+
}
|
|
1217
|
+
recordTurn(e) {
|
|
1218
|
+
const u = e.usage;
|
|
1219
|
+
this.insertTurn.run(
|
|
1220
|
+
e.id,
|
|
1221
|
+
e.at,
|
|
1222
|
+
e.session,
|
|
1223
|
+
e.provider,
|
|
1224
|
+
e.model,
|
|
1225
|
+
e.status,
|
|
1226
|
+
e.complete ? 1 : 0,
|
|
1227
|
+
e.latencyMs,
|
|
1228
|
+
u.inputTokens,
|
|
1229
|
+
u.outputTokens,
|
|
1230
|
+
u.cacheReadTokens,
|
|
1231
|
+
u.cacheWrite5mTokens + u.cacheWrite1hTokens,
|
|
1232
|
+
e.costUsd,
|
|
1233
|
+
e.priced ? 1 : 0,
|
|
1234
|
+
e.fingerprint
|
|
1235
|
+
);
|
|
1236
|
+
}
|
|
1237
|
+
recordTrip(session, trip) {
|
|
1238
|
+
this.insertTrip.run(trip.at, session, trip.kind, trip.detail);
|
|
1239
|
+
}
|
|
1240
|
+
close() {
|
|
1241
|
+
this.db.close();
|
|
1242
|
+
}
|
|
1243
|
+
};
|
|
1244
|
+
|
|
1245
|
+
// src/proxy/index.ts
|
|
1246
|
+
async function startProxy(config) {
|
|
1247
|
+
const pricing = loadPricing(config.pricing.file);
|
|
1248
|
+
const store = new Store(config.storage.path);
|
|
1249
|
+
const engine = new Engine(config, pricing, store);
|
|
1250
|
+
const app = createProxyApp({ config, engine });
|
|
1251
|
+
const server = await new Promise((resolve, reject) => {
|
|
1252
|
+
const s = serve2({ fetch: app.fetch, hostname: config.server.host, port: config.server.proxyPort }, () => resolve(s));
|
|
1253
|
+
s.once("error", reject);
|
|
1254
|
+
});
|
|
1255
|
+
const close = () => new Promise((resolve) => {
|
|
1256
|
+
server.close(() => {
|
|
1257
|
+
store.close();
|
|
1258
|
+
resolve();
|
|
1259
|
+
});
|
|
1260
|
+
if ("closeAllConnections" in server) server.closeAllConnections();
|
|
1261
|
+
});
|
|
1262
|
+
return { engine, app, server, close };
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
// src/cli/commands.ts
|
|
1266
|
+
var TEMPLATE = fileURLToPath3(new URL("../../loopcap.config.yaml", import.meta.url));
|
|
1267
|
+
function init(force) {
|
|
1268
|
+
const target = "loopcap.config.yaml";
|
|
1269
|
+
if (existsSync3(target) && !force) {
|
|
1270
|
+
console.error(`${target} already exists. Use --force to overwrite it.`);
|
|
1271
|
+
return 1;
|
|
1272
|
+
}
|
|
1273
|
+
writeFileSync(target, readFileSync4(TEMPLATE, "utf8"));
|
|
1274
|
+
console.log(`Wrote ${target}.`);
|
|
1275
|
+
return 0;
|
|
1276
|
+
}
|
|
1277
|
+
async function launch(config) {
|
|
1278
|
+
let proxy = null;
|
|
1279
|
+
try {
|
|
1280
|
+
proxy = await startProxy(config);
|
|
1281
|
+
const dashboard = await startDashboard(config, proxy.engine);
|
|
1282
|
+
const p = proxy;
|
|
1283
|
+
return { proxy, dashboard, close: async () => {
|
|
1284
|
+
await dashboard.close();
|
|
1285
|
+
await p.close();
|
|
1286
|
+
} };
|
|
1287
|
+
} catch (err) {
|
|
1288
|
+
await proxy?.close();
|
|
1289
|
+
const e = err;
|
|
1290
|
+
if (e.code === "EADDRINUSE") throw new Error(`A port is already in use (${e.message}). Stop the other process or change server.proxyPort / server.dashboardPort in loopcap.config.yaml.`);
|
|
1291
|
+
throw err;
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
var waitForSignal = () => new Promise((resolve) => {
|
|
1295
|
+
process.once("SIGINT", resolve);
|
|
1296
|
+
process.once("SIGTERM", resolve);
|
|
1297
|
+
});
|
|
1298
|
+
var clock = (at) => new Date(at).toLocaleTimeString("en-GB");
|
|
1299
|
+
function ticker(run) {
|
|
1300
|
+
const engine = run.proxy.engine;
|
|
1301
|
+
const tty = process.stdout.isTTY === true;
|
|
1302
|
+
let last = "no requests yet";
|
|
1303
|
+
const status = () => {
|
|
1304
|
+
const snap = engine.snapshot();
|
|
1305
|
+
const s = [...snap.sessions].sort((a, b) => b.lastSeenAt - a.lastSeenAt)[0];
|
|
1306
|
+
const health = snap.globalTrip ? "TRIPPED" : s?.health ?? "HEALTHY";
|
|
1307
|
+
if (!s) return `${health} waiting for requests`;
|
|
1308
|
+
return `${health} spent ${usd(s.spentUsd)} burn ${usd(s.burnRateUsdPerMin)}/min ${s.tokensPerSec.toFixed(0)} tok/s last: ${last}`;
|
|
1309
|
+
};
|
|
1310
|
+
const draw = () => {
|
|
1311
|
+
if (tty) process.stdout.write(`\r\x1B[K${status()}`);
|
|
1312
|
+
};
|
|
1313
|
+
const line = (text) => {
|
|
1314
|
+
if (tty) process.stdout.write("\r\x1B[K");
|
|
1315
|
+
console.log(text);
|
|
1316
|
+
draw();
|
|
1317
|
+
};
|
|
1318
|
+
const onEvent = (e) => {
|
|
1319
|
+
const t = clock(e.at);
|
|
1320
|
+
switch (e.type) {
|
|
1321
|
+
case "turn":
|
|
1322
|
+
last = `${e.model} ${usd(e.costUsd)}`;
|
|
1323
|
+
if (!tty) line(`${t} turn ${e.model} ${usd(e.costUsd)} streak ${e.streak} session ${usd(e.sessionSpentUsd)} ${e.health}`);
|
|
1324
|
+
break;
|
|
1325
|
+
case "trip":
|
|
1326
|
+
line(`${t} TRIPPED [${e.trip.kind}] ${e.trip.detail}${e.session ? ` (${e.session})` : " (all sessions)"}`);
|
|
1327
|
+
break;
|
|
1328
|
+
case "blocked":
|
|
1329
|
+
if (!tty) line(`${t} blocked ${e.model} (~${usd(e.savedUsd)} saved)`);
|
|
1330
|
+
break;
|
|
1331
|
+
case "reset":
|
|
1332
|
+
line(`${t} reset ${e.session ?? "all sessions"}`);
|
|
1333
|
+
break;
|
|
1334
|
+
case "warning":
|
|
1335
|
+
line(`${t} warning: ${e.message}`);
|
|
1336
|
+
break;
|
|
1337
|
+
}
|
|
1338
|
+
draw();
|
|
1339
|
+
};
|
|
1340
|
+
const unsub = engine.bus.subscribe(onEvent);
|
|
1341
|
+
const timer = tty ? setInterval(draw, 1e3) : null;
|
|
1342
|
+
timer?.unref();
|
|
1343
|
+
return () => {
|
|
1344
|
+
unsub();
|
|
1345
|
+
if (timer) clearInterval(timer);
|
|
1346
|
+
if (tty) process.stdout.write("\n");
|
|
1347
|
+
};
|
|
1348
|
+
}
|
|
1349
|
+
function printEndpoints(config, run) {
|
|
1350
|
+
if (!["127.0.0.1", "localhost", "::1"].includes(config.server.host)) {
|
|
1351
|
+
console.warn(`Warning: listening on ${config.server.host}, not loopback. Other machines on your network may reach the proxy and dashboard.
|
|
1352
|
+
`);
|
|
1353
|
+
}
|
|
1354
|
+
console.log(`LoopCap is running.
|
|
1355
|
+
Dashboard: ${run.dashboard.url}
|
|
1356
|
+
Log: ${config.storage.path}
|
|
1357
|
+
|
|
1358
|
+
Point your agent at the proxy:
|
|
1359
|
+
export ANTHROPIC_BASE_URL=http://localhost:${config.server.proxyPort}
|
|
1360
|
+
export OPENAI_BASE_URL=http://localhost:${config.server.proxyPort}/v1
|
|
1361
|
+
`);
|
|
1362
|
+
}
|
|
1363
|
+
async function start(configPath) {
|
|
1364
|
+
const config = loadConfig(configPath);
|
|
1365
|
+
const run = await launch(config);
|
|
1366
|
+
printEndpoints(config, run);
|
|
1367
|
+
console.log("Press Ctrl-C to stop.\n");
|
|
1368
|
+
const stop = ticker(run);
|
|
1369
|
+
await waitForSignal();
|
|
1370
|
+
stop();
|
|
1371
|
+
console.log("Shutting down.");
|
|
1372
|
+
await run.close();
|
|
1373
|
+
return 0;
|
|
1374
|
+
}
|
|
1375
|
+
async function proxyAnswers(config) {
|
|
1376
|
+
try {
|
|
1377
|
+
const res = await fetch(`http://${config.server.host}:${config.server.proxyPort}/_loopcap/health`, { signal: AbortSignal.timeout(800) });
|
|
1378
|
+
return res.ok && (await res.json()).ok === true;
|
|
1379
|
+
} catch {
|
|
1380
|
+
return false;
|
|
1381
|
+
}
|
|
1382
|
+
}
|
|
1383
|
+
async function demo(configPath, keepOpen) {
|
|
1384
|
+
const config = loadConfig(configPath);
|
|
1385
|
+
let run = null;
|
|
1386
|
+
let base = `http://${config.server.host}:${config.server.proxyPort}`;
|
|
1387
|
+
let dashboardUrl = `http://localhost:${config.server.dashboardPort}`;
|
|
1388
|
+
if (await proxyAnswers(config)) {
|
|
1389
|
+
console.log(`Using the LoopCap already running at ${base}.`);
|
|
1390
|
+
} else {
|
|
1391
|
+
run = await launch({ ...config, storage: { path: ":memory:" } });
|
|
1392
|
+
dashboardUrl = run.dashboard.url;
|
|
1393
|
+
console.log(`Started LoopCap in-process. Dashboard: ${dashboardUrl}`);
|
|
1394
|
+
}
|
|
1395
|
+
const pricing = loadPricing(config.pricing.file);
|
|
1396
|
+
const session = `demo-${Date.now()}`;
|
|
1397
|
+
const deadline = AbortSignal.timeout(1e4);
|
|
1398
|
+
const limit = config.breakers.loop.identicalLoopThreshold;
|
|
1399
|
+
let tripped = false;
|
|
1400
|
+
try {
|
|
1401
|
+
console.log(`
|
|
1402
|
+
Simulated agent (session ${session}) repeating the same tool call:
|
|
1403
|
+
`);
|
|
1404
|
+
for (let n = 1; n <= limit + 3 && !tripped; n++) {
|
|
1405
|
+
const res = await fetch(`${base}/v1/messages`, {
|
|
1406
|
+
method: "POST",
|
|
1407
|
+
signal: deadline,
|
|
1408
|
+
headers: {
|
|
1409
|
+
"content-type": "application/json",
|
|
1410
|
+
"x-api-key": "sk-loopcap-demo",
|
|
1411
|
+
"anthropic-version": "2023-06-01",
|
|
1412
|
+
"x-loopcap-demo": "1",
|
|
1413
|
+
[config.sessions.header]: session
|
|
1414
|
+
},
|
|
1415
|
+
body: JSON.stringify({ model: "claude-sonnet-5-5", max_tokens: 1024, stream: true, messages: [{ role: "user", content: "Run the tests and fix any failures." }] })
|
|
1416
|
+
});
|
|
1417
|
+
const parser = new SseParser();
|
|
1418
|
+
const acc = providers.anthropic.accumulator();
|
|
1419
|
+
for (const e of [...parser.push(await res.text()), ...parser.flush()]) acc.push(e);
|
|
1420
|
+
const turn = acc.turn();
|
|
1421
|
+
if (res.headers.get("x-loopcap-tripped")) {
|
|
1422
|
+
tripped = true;
|
|
1423
|
+
console.log(` request ${n}: BLOCKED by LoopCap (request never sent upstream)
|
|
1424
|
+
|
|
1425
|
+
${turn.text}
|
|
1426
|
+
`);
|
|
1427
|
+
} else {
|
|
1428
|
+
const cost = costOf(pricing, turn.model ?? "", turn.usage).usd;
|
|
1429
|
+
console.log(` request ${n}: ${turn.model} ${turn.toolCalls[0]?.name}(${turn.toolCalls[0]?.args}) cost ${usd(cost)} streak ${n}/${limit}`);
|
|
1430
|
+
}
|
|
1431
|
+
}
|
|
1432
|
+
} catch (err) {
|
|
1433
|
+
console.error(`Demo failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1434
|
+
}
|
|
1435
|
+
if (tripped) console.log(`Breaker tripped as expected. Dashboard: ${dashboardUrl}`);
|
|
1436
|
+
else console.error("The breaker never tripped.");
|
|
1437
|
+
if (keepOpen && run) {
|
|
1438
|
+
console.log("Dashboard kept open. Press Ctrl-C to stop.");
|
|
1439
|
+
await waitForSignal();
|
|
1440
|
+
}
|
|
1441
|
+
await run?.close();
|
|
1442
|
+
return tripped ? 0 : 1;
|
|
1443
|
+
}
|
|
1444
|
+
export {
|
|
1445
|
+
demo,
|
|
1446
|
+
init,
|
|
1447
|
+
start
|
|
1448
|
+
};
|