The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
chore: reformat JavaScript files and remove stray blank line
Steven Enamakel4891aa0f0365
diff --git a/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rs b/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rsindex 02357aaa40..39edb1f223 100644--- a/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rs+++ b/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rs@@ -662,7 +662,6 @@ impl ChatModel<()> for OpenHumanBackendModel {}}-/// Connect timeout for the shared managed-inference client; matches the/// adapter's own default.const MANAGED_INFERENCE_CONNECT_TIMEOUT: Duration = Duration::from_secs(30);diff --git a/scripts/__tests__/capture-first-inference.test.mjs b/scripts/__tests__/capture-first-inference.test.mjsindex b2514e8457..a5dac7189a 100644--- a/scripts/__tests__/capture-first-inference.test.mjs+++ b/scripts/__tests__/capture-first-inference.test.mjs@@ -1,35 +1,44 @@-import assert from 'node:assert/strict';-import { spawn, spawnSync } from 'node:child_process';-import fs from 'node:fs';-import http from 'node:http';-import os from 'node:os';-import path, { dirname, resolve } from 'node:path';-import { fileURLToPath } from 'node:url';-import { after, before, test } from 'node:test';+import assert from "node:assert/strict";+import { spawn, spawnSync } from "node:child_process";+import fs from "node:fs";+import http from "node:http";+import os from "node:os";+import path, { dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { after, before, test } from "node:test";const HERE = dirname(fileURLToPath(import.meta.url));-const SCRIPT = resolve(HERE, '..', 'debug', 'capture-first-inference.mjs');+const SCRIPT = resolve(HERE, "..", "debug", "capture-first-inference.mjs");-test('capture proxy --help prints usage without opening a listener', () => {- const result = spawnSync(process.execPath, [SCRIPT, '--help'], { encoding: 'utf8' });+test("capture proxy --help prints usage without opening a listener", () => {+ const result = spawnSync(process.execPath, [SCRIPT, "--help"], {+ encoding: "utf8",+ });assert.equal(result.status, 0, result.stderr);- assert.match(result.stdout, /Usage: node scripts\/debug\/capture-first-inference\.mjs/);+ assert.match(+ result.stdout,+ /Usage: node scripts\/debug\/capture-first-inference\.mjs/,+ );assert.match(result.stdout, /CAPTURE_UPSTREAM/);assert.match(result.stdout, /pnpm debug capture/);- assert.equal(result.stderr, '');+ assert.equal(result.stderr, "");});-test('capture proxy refuses a non-loopback bind and a plaintext remote upstream by default', () => {+test("capture proxy refuses a non-loopback bind and a plaintext remote upstream by default", () => {const bind = spawnSync(process.execPath, [SCRIPT], {- encoding: 'utf8',- env: { ...process.env, CAPTURE_HOST: '0.0.0.0', CAPTURE_PORT: '0' },+ encoding: "utf8",+ env: { ...process.env, CAPTURE_HOST: "0.0.0.0", CAPTURE_PORT: "0" },});assert.notEqual(bind.status, 0);assert.match(bind.stderr, /refusing to bind CAPTURE_HOST=0\.0\.0\.0/);const upstream = spawnSync(process.execPath, [SCRIPT], {- encoding: 'utf8',- env: { ...process.env, CAPTURE_UPSTREAM: 'http://example.com', CAPTURE_PORT: '0' },+ encoding: "utf8",+ env: {+ ...process.env,+ CAPTURE_UPSTREAM: "http://example.com",+ CAPTURE_PORT: "0",+ },});assert.notEqual(upstream.status, 0);assert.match(upstream.stderr, /plaintext http:/);@@ -43,63 +52,75 @@ function startMockUpstream() {const requests = [];const server = http.createServer((req, res) => {const chunks = [];- req.on('data', c => chunks.push(c));- req.on('end', () => {- const body = Buffer.concat(chunks).toString('utf8');- requests.push({ method: req.method, url: req.url, headers: req.headers, body });- if (req.url === '/openai/v1/chat/completions') {+ req.on("data", (c) => chunks.push(c));+ req.on("end", () => {+ const body = Buffer.concat(chunks).toString("utf8");+ requests.push({+ method: req.method,+ url: req.url,+ headers: req.headers,+ body,+ });+ if (req.url === "/openai/v1/chat/completions") {if (body.includes('"model":"boom"')) {- res.writeHead(503, { 'content-type': 'text/html' });- res.end('<html><head><title>503 Service Temporarily Unavailable</title></head></html>');+ res.writeHead(503, { "content-type": "text/html" });+ res.end(+ "<html><head><title>503 Service Temporarily Unavailable</title></head></html>",+ );return;}- res.writeHead(200, { 'content-type': 'text/event-stream' });- const chunk = delta =>+ res.writeHead(200, { "content-type": "text/event-stream" });+ const chunk = (delta) =>`data: ${JSON.stringify({- id: 'gen-1',- provider: 'StreamLake',+ id: "gen-1",+ provider: "StreamLake",choices: [{ index: 0, delta }],})}\n\n`;- res.write(chunk({ role: 'assistant', content: 'Hel' }));+ res.write(chunk({ role: "assistant", content: "Hel" }));setTimeout(() => {- res.write(chunk({ content: 'lo' }));+ res.write(chunk({ content: "lo" }));res.write(`data: ${JSON.stringify({- id: 'gen-1',- provider: 'StreamLake',+ id: "gen-1",+ provider: "StreamLake",choices: [],usage: {prompt_tokens: 12344,completion_tokens: 2,prompt_tokens_details: { cached_tokens: 12288 },},- })}\n\n`+ })}\n\n`,);- res.write('data: [DONE]\n\n');+ res.write("data: [DONE]\n\n");res.end();}, 30);return;}- res.writeHead(200, { 'content-type': 'application/json' });+ res.writeHead(200, { "content-type": "application/json" });res.end(JSON.stringify({ ok: true, path: req.url }));});});- return new Promise(resolveStart => {- server.listen(0, '127.0.0.1', () => resolveStart({ server, port: server.address().port, requests }));+ return new Promise((resolveStart) => {+ server.listen(0, "127.0.0.1", () =>+ resolveStart({ server, port: server.address().port, requests }),+ );});}function startProxy(env) {const child = spawn(process.execPath, [SCRIPT], {env: { ...process.env, ...env },- stdio: ['ignore', 'pipe', 'pipe'],+ stdio: ["ignore", "pipe", "pipe"],});- let stdout = '';- let stderr = '';- child.stdout.on('data', d => (stdout += d));- child.stderr.on('data', d => (stderr += d));+ let stdout = "";+ let stderr = "";+ child.stdout.on("data", (d) => (stdout += d));+ child.stderr.on("data", (d) => (stderr += d));const ready = new Promise((resolveReady, reject) => {- const timer = setTimeout(() => reject(new Error(`proxy did not start:\n${stdout}\n${stderr}`)), 10_000);+ const timer = setTimeout(+ () => reject(new Error(`proxy did not start:\n${stdout}\n${stderr}`)),+ 10_000,+ );const check = () => {const m = stdout.match(/listening on http:\/\/127\.0\.0\.1:(\d+)/);if (m) {@@ -119,8 +140,12 @@ function startProxy(env) {async function post(port, urlPath, body, headers = {}) {const res = await fetch(`http://127.0.0.1:${port}${urlPath}`, {- method: 'POST',- headers: { 'content-type': 'application/json', authorization: 'Bearer secret-token', ...headers },+ method: "POST",+ headers: {+ "content-type": "application/json",+ authorization: "Bearer secret-token",+ ...headers,+ },body: JSON.stringify(body),});return { status: res.status, text: await res.text() };@@ -138,7 +163,7 @@ async function waitForOutput(getOutput, pattern, timeoutMs = 2000) {const output = getOutput();if (pattern.test(output)) return output;if (Date.now() >= deadline) return output;- await new Promise(r => setTimeout(r, 10));+ await new Promise((r) => setTimeout(r, 10));}}@@ -148,79 +173,105 @@ let workDir;before(async () => {upstream = await startMockUpstream();- workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'capture-proxy-'));+ workDir = fs.mkdtempSync(path.join(os.tmpdir(), "capture-proxy-"));proxy = startProxy({- CAPTURE_PORT: '0',+ CAPTURE_PORT: "0",CAPTURE_UPSTREAM: `http://127.0.0.1:${upstream.port}`,- CAPTURE_ALL: '1',- CAPTURE_RESPONSES: '1',- CAPTURE_ALL_DIR: path.join(workDir, 'seq'),- CAPTURE_OUTPUT: path.join(workDir, 'first.json'),- CAPTURE_LOG: path.join(workDir, 'capture.jsonl'),+ CAPTURE_ALL: "1",+ CAPTURE_RESPONSES: "1",+ CAPTURE_ALL_DIR: path.join(workDir, "seq"),+ CAPTURE_OUTPUT: path.join(workDir, "first.json"),+ CAPTURE_LOG: path.join(workDir, "capture.jsonl"),});});after(() => {- proxy?.child.kill('SIGTERM');+ proxy?.child.kill("SIGTERM");upstream?.server.close();if (workDir) fs.rmSync(workDir, { recursive: true, force: true });});-test('capture proxy forwards an inference call, dumps the body, and summarises the response', async () => {+test("capture proxy forwards an inference call, dumps the body, and summarises the response", async () => {const port = await proxy.ready;const request = {- model: 'z-ai/glm-5.3-flash',+ model: "z-ai/glm-5.3-flash",stream: true,- prompt_cache_key: 'tap-25675927a3f2160d',- thread_id: 'thread-1',- tools: [{ type: 'function', function: { name: 'web_search_tool' } }],+ prompt_cache_key: "tap-25675927a3f2160d",+ thread_id: "thread-1",+ tools: [{ type: "function", function: { name: "web_search_tool" } }],messages: [- { role: 'system', content: 'sys' },- { role: 'user', content: 'hi' },+ { role: "system", content: "sys" },+ { role: "user", content: "hi" },],};- const reply = await post(port, '/openai/v1/chat/completions', request);+ const reply = await post(port, "/openai/v1/chat/completions", request);assert.equal(reply.status, 200);- assert.match(reply.text, /"content":"Hel"/, 'the stream reaches the client untouched');+ assert.match(+ reply.text,+ /"content":"Hel"/,+ "the stream reaches the client untouched",+ );assert.match(reply.text, /\[DONE\]/);assert.equal(- fs.readFileSync(path.join(workDir, 'seq', 'res-000.txt'), 'utf8'),+ fs.readFileSync(path.join(workDir, "seq", "res-000.txt"), "utf8"),reply.text,- 'the saved successful response must match the stream forwarded to the core'+ "the saved successful response must match the stream forwarded to the core",);- for (const file of ['first.json', 'seq/req-000.json', 'seq/res-000.txt', 'capture.jsonl']) {- assert.equal(fs.statSync(path.join(workDir, file)).mode & 0o777, 0o600, file);+ for (const file of [+ "first.json",+ "seq/req-000.json",+ "seq/res-000.txt",+ "capture.jsonl",+ ]) {+ assert.equal(+ fs.statSync(path.join(workDir, file)).mode & 0o777,+ 0o600,+ file,+ );}// Forwarded verbatim, bearer included, to the upstream path.- const seen = upstream.requests.find(r => r.url === '/openai/v1/chat/completions');- assert.ok(seen, 'upstream received the inference call');- assert.equal(seen.headers.authorization, 'Bearer secret-token');+ const seen = upstream.requests.find(+ (r) => r.url === "/openai/v1/chat/completions",+ );+ assert.ok(seen, "upstream received the inference call");+ assert.equal(seen.headers.authorization, "Bearer secret-token");assert.deepEqual(JSON.parse(seen.body), request);// Request dumps: first-body file and the numbered sequence.- assert.deepEqual(JSON.parse(fs.readFileSync(path.join(workDir, 'first.json'), 'utf8')), request);- assert.deepEqual(JSON.parse(fs.readFileSync(path.join(workDir, 'seq', 'req-000.json'), 'utf8')), request);+ assert.deepEqual(+ JSON.parse(fs.readFileSync(path.join(workDir, "first.json"), "utf8")),+ request,+ );+ assert.deepEqual(+ JSON.parse(+ fs.readFileSync(path.join(workDir, "seq", "req-000.json"), "utf8"),+ ),+ request,+ );// Summary: one JSONL record and one stdout line with the routing facts.const record = fs- .readFileSync(path.join(workDir, 'capture.jsonl'), 'utf8')+ .readFileSync(path.join(workDir, "capture.jsonl"), "utf8").trim()- .split('\n')- .map(l => JSON.parse(l))- .find(r => r.seq === 0);- assert.ok(record, 'summary record written');+ .split("\n")+ .map((l) => JSON.parse(l))+ .find((r) => r.seq === 0);+ assert.ok(record, "summary record written");assert.equal(record.status, 200);- assert.equal(record.model, 'z-ai/glm-5.3-flash');+ assert.equal(record.model, "z-ai/glm-5.3-flash");assert.equal(record.messages, 2);assert.equal(record.tools, 1);- assert.equal(record.prompt_cache_key, 'tap-25675927a3f2160d');- assert.equal(record.thread_id, 'thread-1');- assert.equal(record.provider, 'StreamLake');+ assert.equal(record.prompt_cache_key, "tap-25675927a3f2160d");+ assert.equal(record.thread_id, "thread-1");+ assert.equal(record.provider, "StreamLake");assert.equal(record.prompt_tokens, 12344);assert.equal(record.cached_tokens, 12288);assert.equal(record.error, null);- assert.ok(record.ttfb_ms >= 0 && record.total_ms >= record.ttfb_ms, JSON.stringify(record));+ assert.ok(+ record.ttfb_ms >= 0 && record.total_ms >= record.ttfb_ms,+ JSON.stringify(record),+ );assert.equal(record.stream, true);// The stub streams visible content straight away, so the first token is the// first content, and both land no earlier than the first byte.@@ -231,97 +282,115 @@ test('capture proxy forwards an inference call, dumps the body, and summarises tassert.match(await waitForOutput(proxy.output, summaryLine), summaryLine);});-test('capture proxy forwards Socket.IO WebSocket upgrades and both socket directions', async () => {+test("capture proxy forwards Socket.IO WebSocket upgrades and both socket directions", async () => {const port = await proxy.ready;let seen;let upstreamSocket;const onUpgrade = (req, socket, head) => {upstreamSocket = socket;- seen = { url: req.url, authorization: req.headers.authorization, host: req.headers.host };- socket.write('HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n');+ seen = {+ url: req.url,+ authorization: req.headers.authorization,+ host: req.headers.host,+ };+ socket.write(+ "HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n",+ );if (head.length) socket.write(head);- socket.on('data', chunk => socket.write(chunk));+ socket.on("data", (chunk) => socket.write(chunk));};- upstream.server.on('upgrade', onUpgrade);+ upstream.server.on("upgrade", onUpgrade);let clientSocket;try {await new Promise((resolve, reject) => {const request = http.request({- hostname: '127.0.0.1',+ hostname: "127.0.0.1",port,- path: '/socket.io/?EIO=4&transport=websocket',+ path: "/socket.io/?EIO=4&transport=websocket",headers: {- connection: 'Upgrade',- upgrade: 'websocket',- authorization: 'Bearer websocket-test',+ connection: "Upgrade",+ upgrade: "websocket",+ authorization: "Bearer websocket-test",},});const timer = setTimeout(- () => request.destroy(new Error('WebSocket upgrade did not complete')),- 1500+ () => request.destroy(new Error("WebSocket upgrade did not complete")),+ 1500,);- request.on('upgrade', (response, socket) => {+ request.on("upgrade", (response, socket) => {clientSocket = socket;if (response.statusCode !== 101) {clearTimeout(timer);reject(new Error(`unexpected upgrade status ${response.statusCode}`));return;}- socket.on('data', chunk => {- if (chunk.toString() === 'socket-ping') {+ socket.on("data", (chunk) => {+ if (chunk.toString() === "socket-ping") {clearTimeout(timer);resolve();}});- socket.write('socket-ping');+ socket.write("socket-ping");});- request.on('response', response => {+ request.on("response", (response) => {clearTimeout(timer);reject(new Error(`upgrade returned HTTP ${response.statusCode}`));});- request.on('error', error => {+ request.on("error", (error) => {clearTimeout(timer);reject(error);});request.end();});assert.deepEqual(seen, {- url: '/socket.io/?EIO=4&transport=websocket',- authorization: 'Bearer websocket-test',+ url: "/socket.io/?EIO=4&transport=websocket",+ authorization: "Bearer websocket-test",host: `127.0.0.1:${upstream.port}`,});} finally {clientSocket?.destroy();upstreamSocket?.destroy();- upstream.server.off('upgrade', onUpgrade);+ upstream.server.off("upgrade", onUpgrade);}});-test('capture proxy records a non-2xx inference response body and names the error', async () => {+test("capture proxy records a non-2xx inference response body and names the error", async () => {const port = await proxy.ready;- const reply = await post(port, '/openai/v1/chat/completions', { model: 'boom', messages: [] });- assert.equal(reply.status, 503, 'status passes through');+ const reply = await post(port, "/openai/v1/chat/completions", {+ model: "boom",+ messages: [],+ });+ assert.equal(reply.status, 503, "status passes through");const records = fs- .readFileSync(path.join(workDir, 'capture.jsonl'), 'utf8')+ .readFileSync(path.join(workDir, "capture.jsonl"), "utf8").trim()- .split('\n')- .map(l => JSON.parse(l));- const record = records.find(r => r.model === 'boom');+ .split("\n")+ .map((l) => JSON.parse(l));+ const record = records.find((r) => r.model === "boom");assert.ok(record);assert.equal(record.status, 503);assert.match(record.error, /503 Service Temporarily Unavailable/);- assert.ok(fs.existsSync(record.response_body), 'error body saved next to the request dumps');- assert.match(fs.readFileSync(record.response_body, 'utf8'), /<html>/);+ assert.ok(+ fs.existsSync(record.response_body),+ "error body saved next to the request dumps",+ );+ assert.match(fs.readFileSync(record.response_body, "utf8"), /<html>/);});-test('capture proxy passes non-inference routes through without summarising them', async () => {+test("capture proxy passes non-inference routes through without summarising them", async () => {const port = await proxy.ready;- const reply = await post(port, '/auth/me', { probe: true });+ const reply = await post(port, "/auth/me", { probe: true });assert.equal(reply.status, 200);- assert.deepEqual(JSON.parse(reply.text), { ok: true, path: '/auth/me' });- const lines = fs.readFileSync(path.join(workDir, 'capture.jsonl'), 'utf8').trim().split('\n');- assert.ok(lines.every(l => !l.includes('/auth/me')), 'no summary record for a non-inference route');+ assert.deepEqual(JSON.parse(reply.text), { ok: true, path: "/auth/me" });+ const lines = fs+ .readFileSync(path.join(workDir, "capture.jsonl"), "utf8")+ .trim()+ .split("\n");+ assert.ok(+ lines.every((l) => !l.includes("/auth/me")),+ "no summary record for a non-inference route",+ );assert.doesNotMatch(proxy.output(), /auth\/me/);});diff --git a/scripts/debug/capture-first-inference.mjs b/scripts/debug/capture-first-inference.mjsindex 9e2ee5b31c..aeedec6ea3 100644--- a/scripts/debug/capture-first-inference.mjs+++ b/scripts/debug/capture-first-inference.mjs@@ -9,12 +9,12 @@// `pnpm debug capture --help`) for the knobs; the tail of this file has the// setup recipe.-import fs from 'node:fs';-import http from 'node:http';-import https from 'node:https';-import path from 'node:path';+import fs from "node:fs";+import http from "node:http";+import https from "node:https";+import path from "node:path";-const LOOPBACK_HOSTS = new Set(['127.0.0.1', '::1', 'localhost']);+const LOOPBACK_HOSTS = new Set(["127.0.0.1", "::1", "localhost"]);function isLoopbackHost(host) {return LOOPBACK_HOSTS.has(host.toLowerCase());@@ -53,19 +53,22 @@ Point the core at it, then drive turns and read the summary lines:BACKEND_URL=http://127.0.0.1:18765 ./target/debug/openhuman-core run --port 7799`;-if (process.argv.includes('--help') || process.argv.includes('-h')) {+if (process.argv.includes("--help") || process.argv.includes("-h")) {process.stdout.write(USAGE);process.exit(0);}-const listenHost = process.env.CAPTURE_HOST || '127.0.0.1';-const listenPort = Number.parseInt(process.env.CAPTURE_PORT || '18765', 10);-const upstream = new URL(process.env.CAPTURE_UPSTREAM || 'https://api.tinyhumans.ai');+const listenHost = process.env.CAPTURE_HOST || "127.0.0.1";+const listenPort = Number.parseInt(process.env.CAPTURE_PORT || "18765", 10);+const upstream = new URL(+ process.env.CAPTURE_UPSTREAM || "https://api.tinyhumans.ai",+);const outputPath = path.resolve(- process.env.CAPTURE_OUTPUT || 'target/debug-logs/first-inference-request.json'+ process.env.CAPTURE_OUTPUT ||+ "target/debug-logs/first-inference-request.json",);const summaryLogPath = path.resolve(- process.env.CAPTURE_LOG || 'target/debug-logs/inference-capture.jsonl'+ process.env.CAPTURE_LOG || "target/debug-logs/inference-capture.jsonl",);// The proxy forwards the inbound `authorization` header verbatim. Binding to a@@ -76,20 +79,20 @@ const summaryLogPath = path.resolve(// non-loopback CAPTURE_UPSTREAM pointed at a local mock server on `http:` is a// normal debugging setup), gated by explicit env vars rather than silently// allowed.-if (!isLoopbackHost(listenHost) && process.env.CAPTURE_ALLOW_REMOTE !== '1') {+if (!isLoopbackHost(listenHost) && process.env.CAPTURE_ALLOW_REMOTE !== "1") {throw new Error(`refusing to bind CAPTURE_HOST=${listenHost}: not loopback. ` +- 'Set CAPTURE_ALLOW_REMOTE=1 to bind a non-loopback interface anyway.'+ "Set CAPTURE_ALLOW_REMOTE=1 to bind a non-loopback interface anyway.",);}if (- upstream.protocol === 'http:' &&+ upstream.protocol === "http:" &&!isLoopbackHost(upstream.hostname) &&- process.env.CAPTURE_ALLOW_PLAINTEXT_UPSTREAM !== '1'+ process.env.CAPTURE_ALLOW_PLAINTEXT_UPSTREAM !== "1") {throw new Error(`refusing to forward the authorization header to CAPTURE_UPSTREAM=${upstream.origin} over plaintext http:. ` +- 'Use an https: upstream, point at a loopback host, or set CAPTURE_ALLOW_PLAINTEXT_UPSTREAM=1 to override.'+ "Use an https: upstream, point at a loopback host, or set CAPTURE_ALLOW_PLAINTEXT_UPSTREAM=1 to override.",);}@@ -97,13 +100,13 @@ if (// `CAPTURE_ALL_DIR`. The single-shot default answers "what does the first turn// cost"; only the sequence answers "does the cacheable prefix survive turn 2",// which is a different question and the one a prefix cache is graded on.-const captureAll = process.env.CAPTURE_ALL === '1';-const captureResponses = process.env.CAPTURE_RESPONSES === '1';+const captureAll = process.env.CAPTURE_ALL === "1";+const captureResponses = process.env.CAPTURE_RESPONSES === "1";const captureAllDir = path.resolve(- process.env.CAPTURE_ALL_DIR || 'target/debug-logs/inference-sequence'+ process.env.CAPTURE_ALL_DIR || "target/debug-logs/inference-sequence",);-if (upstream.protocol !== 'https:' && upstream.protocol !== 'http:') {+if (upstream.protocol !== "https:" && upstream.protocol !== "http:") {throw new Error(`unsupported upstream protocol: ${upstream.protocol}`);}@@ -112,15 +115,15 @@ let sequenceIndex = 0;function isInferenceRequest(req) {return (- req.method === 'POST' &&- (req.url?.includes('/openai/v1/chat/completions') ||- req.url?.includes('/v1/chat/completions'))+ req.method === "POST" &&+ (req.url?.includes("/openai/v1/chat/completions") ||+ req.url?.includes("/v1/chat/completions")));}function upstreamPath(requestUrl) {- const basePath = upstream.pathname.replace(/\/$/, '');- return `${basePath}${requestUrl || '/'}`;+ const basePath = upstream.pathname.replace(/\/$/, "");+ return `${basePath}${requestUrl || "/"}`;}/**@@ -132,7 +135,7 @@ function upstreamPath(requestUrl) {*/function summarizeRequestBody(body) {try {- const json = JSON.parse(body.toString('utf8'));+ const json = JSON.parse(body.toString("utf8"));return {model: json.model ?? null,messages: Array.isArray(json.messages) ? json.messages.length : null,@@ -142,7 +145,13 @@ function summarizeRequestBody(body) {thread_id: json.thread_id ?? json.session_id ?? null,};} catch {- return { model: null, messages: null, tools: 0, stream: false, prompt_cache_key: null };+ return {+ model: null,+ messages: null,+ tools: 0,+ stream: false,+ prompt_cache_key: null,+ };}}@@ -153,35 +162,51 @@ function summarizeRequestBody(body) {* too, so a stream cut off mid-way still reports what arrived.*/function summarizeResponseBody(text) {- const out = { provider: null, prompt_tokens: null, cached_tokens: null, error: null };- const absorb = json => {- if (json && typeof json === 'object') {- if (typeof json.provider === 'string') out.provider = json.provider;- if (json.usage && typeof json.usage === 'object') {+ const out = {+ provider: null,+ prompt_tokens: null,+ cached_tokens: null,+ error: null,+ };+ const absorb = (json) => {+ if (json && typeof json === "object") {+ if (typeof json.provider === "string") out.provider = json.provider;+ if (json.usage && typeof json.usage === "object") {out.prompt_tokens = json.usage.prompt_tokens ?? out.prompt_tokens;- out.cached_tokens = json.usage.prompt_tokens_details?.cached_tokens ?? out.cached_tokens;+ out.cached_tokens =+ json.usage.prompt_tokens_details?.cached_tokens ?? out.cached_tokens;}if (json.error) {out.error =- typeof json.error === 'string'+ typeof json.error === "string"? json.error: (json.error.message ?? JSON.stringify(json.error));}}};- for (const line of text.split('\n')) {+ for (const line of text.split("\n")) {const trimmed = line.trim();if (!trimmed) continue;- const payload = trimmed.startsWith('data:') ? trimmed.slice(5).trim() : trimmed;- if (payload === '[DONE]' || !payload.startsWith('{')) continue;+ const payload = trimmed.startsWith("data:")+ ? trimmed.slice(5).trim()+ : trimmed;+ if (payload === "[DONE]" || !payload.startsWith("{")) continue;try {absorb(JSON.parse(payload));} catch {// partial or non-JSON line — keep scanning}}- if (out.error === null && !text.trimStart().startsWith('data:') && text.includes('<html')) {- out.error = text.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 120);+ if (+ out.error === null &&+ !text.trimStart().startsWith("data:") &&+ text.includes("<html")+ ) {+ out.error = text+ .replace(/<[^>]+>/g, " ")+ .replace(/\s+/g, " ")+ .trim()+ .slice(0, 120);}return out;}@@ -197,12 +222,12 @@ const FIRST_CONTENT_RE = /"content":"[^"]/;* boundaries: each chunk is scanned together with the tail of the previous one.*/function createFirstTokenTracker(startedAt) {- let tail = '';+ let tail = "";const out = { first_token_ms: null, first_content_ms: null };return {observe(chunk, now = Date.now()) {if (out.first_token_ms !== null && out.first_content_ms !== null) return;- const window = tail + chunk.toString('utf8');+ const window = tail + chunk.toString("utf8");tail = window.slice(-256);if (out.first_token_ms === null && FIRST_TOKEN_RE.test(window)) {out.first_token_ms = now - startedAt;@@ -216,22 +241,24 @@ function createFirstTokenTracker(startedAt) {}function formatSummaryLine(record) {- const ms = value => (value == null ? '-' : `${(value / 1000).toFixed(2)}s`);+ const ms = (value) => (value == null ? "-" : `${(value / 1000).toFixed(2)}s`);return (- `[capture] #${String(record.seq).padStart(3, '0')} ${record.status} ` +- `model=${record.model ?? '?'} msgs=${record.messages ?? '?'} tools=${record.tools} ` +- `served_by=${record.provider ?? '?'} ttfb=${ms(record.ttfb_ms)} total=${ms(record.total_ms)} ` +- `prompt=${record.prompt_tokens ?? '?'} cached=${record.cached_tokens ?? '?'} ` +- `cache_key=${record.prompt_cache_key ?? '-'} ` +- `stream=${record.stream ? 'yes' : 'no'} ttft=${ms(record.first_token_ms)} ` +- `ttfc=${ms(record.first_content_ms)} thread=${record.thread_id ?? '-'}` +- (record.error ? ` error=${JSON.stringify(record.error)}` : '')+ `[capture] #${String(record.seq).padStart(3, "0")} ${record.status} ` ++ `model=${record.model ?? "?"} msgs=${record.messages ?? "?"} tools=${record.tools} ` ++ `served_by=${record.provider ?? "?"} ttfb=${ms(record.ttfb_ms)} total=${ms(record.total_ms)} ` ++ `prompt=${record.prompt_tokens ?? "?"} cached=${record.cached_tokens ?? "?"} ` ++ `cache_key=${record.prompt_cache_key ?? "-"} ` ++ `stream=${record.stream ? "yes" : "no"} ttft=${ms(record.first_token_ms)} ` ++ `ttfc=${ms(record.first_content_ms)} thread=${record.thread_id ?? "-"}` ++ (record.error ? ` error=${JSON.stringify(record.error)}` : ""));}function appendSummary(record) {fs.mkdirSync(path.dirname(summaryLogPath), { recursive: true });- fs.appendFileSync(summaryLogPath, `${JSON.stringify(record)}\n`, { mode: 0o600 });+ fs.appendFileSync(summaryLogPath, `${JSON.stringify(record)}\n`, {+ mode: 0o600,+ });fs.chmodSync(summaryLogPath, 0o600);process.stdout.write(`${formatSummaryLine(record)}\n`);}@@ -243,8 +270,8 @@ function writePrivateCapture(file, data) {const server = http.createServer((req, res) => {const chunks = [];- req.on('data', chunk => chunks.push(chunk));- req.on('end', () => {+ req.on("data", (chunk) => chunks.push(chunk));+ req.on("end", () => {const body = Buffer.concat(chunks);const inference = isInferenceRequest(req);const seq = inference ? sequenceIndex++ : null;@@ -254,22 +281,24 @@ const server = http.createServer((req, res) => {fs.mkdirSync(path.dirname(outputPath), { recursive: true });writePrivateCapture(outputPath, body);captured = true;- process.stdout.write(`[capture] wrote first inference body to ${outputPath}\n`);+ process.stdout.write(+ `[capture] wrote first inference body to ${outputPath}\n`,+ );}if (captureAll) {fs.mkdirSync(captureAllDir, { recursive: true });- const name = `req-${String(seq).padStart(3, '0')}.json`;+ const name = `req-${String(seq).padStart(3, "0")}.json`;writePrivateCapture(path.join(captureAllDir, name), body);process.stdout.write(`[capture] wrote ${name} (${body.length} B)\n`);}}const headers = { ...req.headers, host: upstream.host };- delete headers['content-length'];- headers['content-length'] = String(body.length);+ delete headers["content-length"];+ headers["content-length"] = String(body.length);const startedAt = Date.now();- const transport = upstream.protocol === 'https:' ? https : http;+ const transport = upstream.protocol === "https:" ? https : http;const upstreamReq = transport.request({protocol: upstream.protocol,@@ -279,7 +308,7 @@ const server = http.createServer((req, res) => {path: upstreamPath(req.url),headers,},- upstreamRes => {+ (upstreamRes) => {res.writeHead(upstreamRes.statusCode || 502, upstreamRes.headers);if (!inference) {upstreamRes.pipe(res);@@ -291,17 +320,17 @@ const server = http.createServer((req, res) => {let firstByteAt = null;const firstTokens = createFirstTokenTracker(startedAt);const pieces = [];- upstreamRes.on('data', chunk => {+ upstreamRes.on("data", (chunk) => {if (firstByteAt === null) firstByteAt = Date.now();firstTokens.observe(chunk);pieces.push(chunk);res.write(chunk);});- upstreamRes.on('end', () => {+ upstreamRes.on("end", () => {// Summarise before closing the client side, so anything waiting on// the response (a test, a script driving turns) can read the record// as soon as its call returns.- const text = Buffer.concat(pieces).toString('utf8');+ const text = Buffer.concat(pieces).toString("utf8");const status = upstreamRes.statusCode || 502;const record = {seq,@@ -313,8 +342,11 @@ const server = http.createServer((req, res) => {...firstTokens.result(),total_ms: Date.now() - startedAt,};- if (captureResponses || (captureAll && (status < 200 || status >= 300))) {- const name = `res-${String(seq).padStart(3, '0')}.txt`;+ if (+ captureResponses ||+ (captureAll && (status < 200 || status >= 300))+ ) {+ const name = `res-${String(seq).padStart(3, "0")}.txt`;fs.mkdirSync(captureAllDir, { recursive: true });writePrivateCapture(path.join(captureAllDir, name), text);record.response_body = path.join(captureAllDir, name);@@ -322,17 +354,20 @@ const server = http.createServer((req, res) => {appendSummary(record);res.end();});- upstreamRes.on('error', error => {- process.stderr.write(`[capture] upstream stream error: ${error.message}\n`);+ upstreamRes.on("error", (error) => {+ process.stderr.write(+ `[capture] upstream stream error: ${error.message}\n`,+ );res.end();});- }+ },);- upstreamReq.on('error', error => {+ upstreamReq.on("error", (error) => {process.stderr.write(`[capture] upstream error: ${error.message}\n`);- if (!res.headersSent) res.writeHead(502, { 'content-type': 'text/plain' });- res.end('capture proxy upstream error');+ if (!res.headersSent)+ res.writeHead(502, { "content-type": "text/plain" });+ res.end("capture proxy upstream error");if (inference) {appendSummary({seq,@@ -355,8 +390,8 @@ const server = http.createServer((req, res) => {// Socket.IO upgrades never enter the HTTP request callback. Relay the// handshake and then pipe both raw sockets so desktop backend events work.-server.on('upgrade', (req, clientSocket, clientHead) => {- const transport = upstream.protocol === 'https:' ? https : http;+server.on("upgrade", (req, clientSocket, clientHead) => {+ const transport = upstream.protocol === "https:" ? https : http;const upstreamReq = transport.request({protocol: upstream.protocol,hostname: upstream.hostname,@@ -367,38 +402,42 @@ server.on('upgrade', (req, clientSocket, clientHead) => {});let upstreamSocket;- const writeResponseHead = response => {+ const writeResponseHead = (response) => {clientSocket.write(- `HTTP/${response.httpVersion} ${response.statusCode} ${response.statusMessage}\r\n`+ `HTTP/${response.httpVersion} ${response.statusCode} ${response.statusMessage}\r\n`,);for (let i = 0; i < response.rawHeaders.length; i += 2) {- clientSocket.write(`${response.rawHeaders[i]}: ${response.rawHeaders[i + 1]}\r\n`);+ clientSocket.write(+ `${response.rawHeaders[i]}: ${response.rawHeaders[i + 1]}\r\n`,+ );}- clientSocket.write('\r\n');+ clientSocket.write("\r\n");};- upstreamReq.on('upgrade', (response, socket, upstreamHead) => {+ upstreamReq.on("upgrade", (response, socket, upstreamHead) => {upstreamSocket = socket;writeResponseHead(response);if (upstreamHead.length) clientSocket.write(upstreamHead);if (clientHead.length) socket.write(clientHead);socket.pipe(clientSocket);clientSocket.pipe(socket);- socket.on('error', () => clientSocket.destroy());- clientSocket.on('error', () => socket.destroy());+ socket.on("error", () => clientSocket.destroy());+ clientSocket.on("error", () => socket.destroy());});- upstreamReq.on('response', response => {+ upstreamReq.on("response", (response) => {writeResponseHead(response);response.pipe(clientSocket);- response.on('end', () => clientSocket.end());+ response.on("end", () => clientSocket.end());});- upstreamReq.on('error', error => {- process.stderr.write(`[capture] websocket upstream error: ${error.message}\n`);+ upstreamReq.on("error", (error) => {+ process.stderr.write(+ `[capture] websocket upstream error: ${error.message}\n`,+ );if (!clientSocket.destroyed) {- clientSocket.end('HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\n\r\n');+ clientSocket.end("HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\n\r\n");}});- clientSocket.on('close', () => {+ clientSocket.on("close", () => {upstreamReq.destroy();upstreamSocket?.destroy();});@@ -412,11 +451,11 @@ server.listen(listenPort, listenHost, () => {process.stdout.write(`[capture] listening on http://${listenHost}:${boundPort}; forwarding to ${upstream.origin}` +`; summaries → ${summaryLogPath}` +- `${captureAll ? `; recording every request under ${captureAllDir}` : ''}` +- `${captureResponses ? `; recording every response under ${captureAllDir}` : ''}\n`+ `${captureAll ? `; recording every request under ${captureAllDir}` : ""}` ++ `${captureResponses ? `; recording every response under ${captureAllDir}` : ""}\n`,);});-for (const signal of ['SIGINT', 'SIGTERM']) {+for (const signal of ["SIGINT", "SIGTERM"]) {process.on(signal, () => server.close(() => process.exit(0)));}