@drakonkat/ai-helper 1.1.1 → 1.2.3
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/ARCHITECTURE.md +14 -3
- package/CHANGELOG.md +9 -0
- package/README.md +483 -26
- package/docs/benchmark.md +373 -0
- package/package.json +17 -5
- package/scripts/bench-proxy.js +111 -0
- package/scripts/build.js +16 -0
- package/src/benchmark/fixtures.js +162 -0
- package/src/benchmark/live.js +207 -0
- package/src/benchmark/measurement.js +180 -0
- package/src/benchmark/quality-fixtures.js +95 -0
- package/src/benchmark/quality.js +206 -0
- package/src/benchmark/report.js +162 -0
- package/src/benchmark/runner.js +287 -0
- package/src/codex-config.js +247 -0
- package/src/codex-routing.js +132 -0
- package/src/config.js +19 -1
- package/src/index.js +158 -26
- package/src/manager.js +233 -15
- package/src/proxy-interceptor.example.mjs +33 -0
- package/src/proxy-presets.js +235 -0
- package/src/proxy-stats.js +64 -0
- package/src/proxy-worker.js +17 -0
- package/src/proxy.js +313 -0
- package/src/request-images.js +69 -0
- package/src/service-updates.js +68 -0
- package/src/tui.js +370 -162
- package/src/update.js +41 -0
- package/src/utils/metrics.js +39 -12
- package/src/utils/process.js +92 -146
- package/src/utils/versions.js +165 -0
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync, renameSync, mkdirSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { getAihDir } from "./utils/path.js";
|
|
4
|
+
|
|
5
|
+
export const getProxyStatsPath = () => join(getAihDir(), "proxy-stats.json");
|
|
6
|
+
|
|
7
|
+
export function readProxyStats(file = getProxyStatsPath()) {
|
|
8
|
+
try {
|
|
9
|
+
const stats = JSON.parse(readFileSync(file, "utf8"));
|
|
10
|
+
return stats.version === 1 && Number.isFinite(stats.requests) && stats.stages && Array.isArray(stats.recent) ? stats : null;
|
|
11
|
+
} catch { return null; }
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function tokenStage(name, before, after, applied, reason, method) {
|
|
15
|
+
const known = Number.isFinite(before) && before >= 0 && Number.isFinite(after) && after >= 0;
|
|
16
|
+
return { name, before: known ? Math.round(before) : null, after: known ? Math.round(after) : null,
|
|
17
|
+
saved: known ? Math.round(before - after) : null, applied, reason, method };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// One managed proxy writes this bounded snapshot. Counters survive worker restarts.
|
|
21
|
+
export function createProxyStatsRecorder(file = getProxyStatsPath()) {
|
|
22
|
+
const stats = readProxyStats(file) || { version: 1, since: new Date().toISOString(), requests: 0,
|
|
23
|
+
changed: 0, errors: 0, estimatedSavedTokens: 0, unmeasuredStages: 0, stages: {}, recent: [] };
|
|
24
|
+
let warned = false;
|
|
25
|
+
return event => {
|
|
26
|
+
try {
|
|
27
|
+
stats.updatedAt = new Date().toISOString();
|
|
28
|
+
stats.requests++;
|
|
29
|
+
if (event.error) stats.errors++;
|
|
30
|
+
else if (event.changed) stats.changed++;
|
|
31
|
+
const stages = event.error ? [] : event.stages;
|
|
32
|
+
let saved = 0;
|
|
33
|
+
for (const stage of stages) {
|
|
34
|
+
const total = stats.stages[stage.name] ||= { requests: 0, applied: 0, before: 0, after: 0, saved: 0, unmeasured: 0 };
|
|
35
|
+
total.requests++;
|
|
36
|
+
if (stage.applied) total.applied++;
|
|
37
|
+
if (stage.saved === null) { total.unmeasured++; stats.unmeasuredStages++; }
|
|
38
|
+
else { total.before += stage.before; total.after += stage.after; total.saved += stage.saved; saved += stage.saved; }
|
|
39
|
+
}
|
|
40
|
+
stats.estimatedSavedTokens += saved;
|
|
41
|
+
const model = String(event.model).replace(/[\r\n]/g, " ").slice(0, 128);
|
|
42
|
+
stats.recent.push({ at: stats.updatedAt, model, preset: event.preset, transport: event.transport,
|
|
43
|
+
changed: event.changed, error: Boolean(event.error), saved: event.error ? null : saved, stages });
|
|
44
|
+
stats.recent = stats.recent.slice(-20);
|
|
45
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
46
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
47
|
+
writeFileSync(temporary, JSON.stringify(stats) + "\n");
|
|
48
|
+
renameSync(temporary, file);
|
|
49
|
+
console.log(`[aih stats] ${event.transport} ${model} ${event.preset}: ${event.error ? "processing failed" : stages.map(s => `${s.name}=${s.saved ?? "?"} (${s.reason})`).join(", ") + `; estimated saved=${saved} tokens`}`);
|
|
50
|
+
} catch (error) {
|
|
51
|
+
if (!warned) console.error(`[aih stats] Cannot save statistics: ${error.message}`);
|
|
52
|
+
warned = true;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function proxyStatsLines(stats) {
|
|
58
|
+
if (!stats) return ["Proxy: nessuna statistica. Invia una richiesta AI con un preset attivo."];
|
|
59
|
+
return [
|
|
60
|
+
`PROXY: risparmio stimato ${stats.estimatedSavedTokens} token${stats.unmeasuredStages ? " (parziale)" : ""} | richieste ${stats.requests} | modificate ${stats.changed} | errori preset ${stats.errors}`,
|
|
61
|
+
...Object.entries(stats.stages).map(([name, s]) => ` ${name}: ${s.saved} token risparmiati | applicato ${s.applied}/${s.requests}${s.unmeasured ? ` | non misurati ${s.unmeasured}` : ""}`),
|
|
62
|
+
" Stime dei preset; esclusi interceptor, cache e fatturazione.",
|
|
63
|
+
];
|
|
64
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { startProxy } from "./proxy.js";
|
|
2
|
+
import { createProxyStatsRecorder } from "./proxy-stats.js";
|
|
3
|
+
|
|
4
|
+
try {
|
|
5
|
+
const options = JSON.parse(process.env.AIH_PROXY_OPTIONS || "{}");
|
|
6
|
+
delete process.env.AIH_PROXY_OPTIONS;
|
|
7
|
+
const proxy = await startProxy({ ...options, onStats: createProxyStatsRecorder() });
|
|
8
|
+
console.log(`[aih proxy] Listening on ${proxy.url} -> ${options.upstream}`);
|
|
9
|
+
process.send?.({ url: proxy.url });
|
|
10
|
+
for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => {
|
|
11
|
+
proxy.close().then(() => process.exit(0), () => process.exit(1));
|
|
12
|
+
});
|
|
13
|
+
} catch (error) {
|
|
14
|
+
console.error(`[aih proxy] ${error.message}`);
|
|
15
|
+
if (process.send) process.send({ error: error.message }, () => process.exit(1));
|
|
16
|
+
else process.exit(1);
|
|
17
|
+
}
|
package/src/proxy.js
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
import http from "node:http";
|
|
2
|
+
import https from "node:https";
|
|
3
|
+
import { resolve } from "node:path";
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
import { Transform } from "node:stream";
|
|
6
|
+
import { pipeline } from "node:stream/promises";
|
|
7
|
+
import WebSocket, { WebSocketServer } from "ws";
|
|
8
|
+
import { normalizePresetOptions, createPresetHooks } from "./proxy-presets.js";
|
|
9
|
+
|
|
10
|
+
const HOP_HEADERS = ["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade"];
|
|
11
|
+
const HOOKS = ["onRequest", "onResponse", "onResponseBody", "onResponseChunk", "onWebSocketMessage"];
|
|
12
|
+
|
|
13
|
+
function parseUrl(value) {
|
|
14
|
+
return new URL(String(value).replace(/^(https?):\/*/i, "$1://"));
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function normalizeProxyOptions(options = {}) {
|
|
18
|
+
if (!options.upstream) throw new Error("Usage: aih start proxy <http(s)://upstream> [--listen http://127.0.0.1:10101] [--interceptor file.mjs]");
|
|
19
|
+
const upstream = parseUrl(options.upstream);
|
|
20
|
+
const listen = parseUrl(options.listen || "http://127.0.0.1:10101");
|
|
21
|
+
if (!["http:", "https:"].includes(upstream.protocol) || upstream.username || upstream.password || upstream.search || upstream.hash) {
|
|
22
|
+
throw new Error("Upstream must be HTTP(S), with no credentials, query or fragment");
|
|
23
|
+
}
|
|
24
|
+
if (listen.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(listen.hostname) || listen.pathname !== "/" || listen.search || listen.hash || listen.username || listen.password) {
|
|
25
|
+
throw new Error("Listen URL must be HTTP on loopback (127.0.0.1, localhost or [::1]), with no path or credentials");
|
|
26
|
+
}
|
|
27
|
+
if (listen.port !== "0" && listen.port === upstream.port && listen.protocol === upstream.protocol &&
|
|
28
|
+
(listen.hostname === upstream.hostname || ["127.0.0.1", "localhost", "[::1]"].includes(upstream.hostname))) {
|
|
29
|
+
throw new Error("Proxy cannot forward to its own listening address");
|
|
30
|
+
}
|
|
31
|
+
const maxBodyBytes = Number(options.maxBodyBytes ?? 64 * 1024 * 1024);
|
|
32
|
+
if (!Number.isSafeInteger(maxBodyBytes) || maxBodyBytes <= 0) throw new Error("maxBodyBytes must be a positive integer");
|
|
33
|
+
return {
|
|
34
|
+
upstream: upstream.href,
|
|
35
|
+
listen: listen.href,
|
|
36
|
+
interceptor: options.interceptor ? resolve(options.interceptor) : undefined,
|
|
37
|
+
maxBodyBytes,
|
|
38
|
+
...normalizePresetOptions(options),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function headersForHop(headers) {
|
|
43
|
+
const result = { ...headers };
|
|
44
|
+
const connection = String(result.connection || "").toLowerCase().split(",").map(s => s.trim());
|
|
45
|
+
for (const name of [...HOP_HEADERS, ...connection]) delete result[name];
|
|
46
|
+
return result;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function bytes(value) {
|
|
50
|
+
if (typeof value === "string" || value instanceof Uint8Array) return Buffer.from(value);
|
|
51
|
+
throw new TypeError("Interceptor body must be a string, Buffer or Uint8Array");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function readBody(request, limit) {
|
|
55
|
+
return new Promise((resolveBody, reject) => {
|
|
56
|
+
const chunks = [];
|
|
57
|
+
let size = 0;
|
|
58
|
+
const finish = (error) => {
|
|
59
|
+
request.off("data", onData).off("end", onEnd).off("error", finish).off("aborted", onAbort);
|
|
60
|
+
if (error) reject(error);
|
|
61
|
+
else resolveBody(Buffer.concat(chunks, size));
|
|
62
|
+
};
|
|
63
|
+
const onData = chunk => {
|
|
64
|
+
size += chunk.length;
|
|
65
|
+
if (size > limit) {
|
|
66
|
+
request.pause();
|
|
67
|
+
finish(Object.assign(new Error("Request body exceeds maxBodyBytes"), { statusCode: 413 }));
|
|
68
|
+
} else chunks.push(chunk);
|
|
69
|
+
};
|
|
70
|
+
const onEnd = () => finish();
|
|
71
|
+
const onAbort = () => finish(new Error("Client aborted request"));
|
|
72
|
+
request.on("data", onData).once("end", onEnd).once("error", finish).once("aborted", onAbort);
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export async function startProxy(options) {
|
|
77
|
+
const config = normalizeProxyOptions(options);
|
|
78
|
+
const target = new URL(config.upstream);
|
|
79
|
+
const listen = new URL(config.listen);
|
|
80
|
+
const hooks = { ...(config.interceptor ? await import(pathToFileURL(config.interceptor).href) : {}) };
|
|
81
|
+
for (const name of HOOKS) {
|
|
82
|
+
if (hooks[name] !== undefined && typeof hooks[name] !== "function") throw new TypeError(`${name} must be a function`);
|
|
83
|
+
}
|
|
84
|
+
const preset = await createPresetHooks(config, options.onStats);
|
|
85
|
+
for (const [name, hook] of Object.entries(preset)) {
|
|
86
|
+
const custom = hooks[name];
|
|
87
|
+
hooks[name] = async context => { await hook(context); await custom?.(context); };
|
|
88
|
+
}
|
|
89
|
+
const connections = new Set();
|
|
90
|
+
const upstreamSockets = new Set();
|
|
91
|
+
const upgrades = new WeakMap();
|
|
92
|
+
const wsServer = new WebSocketServer({
|
|
93
|
+
noServer: true,
|
|
94
|
+
autoPong: false,
|
|
95
|
+
maxPayload: config.maxBodyBytes,
|
|
96
|
+
handleProtocols: (_protocols, request) => upgrades.get(request)?.protocol || false,
|
|
97
|
+
});
|
|
98
|
+
wsServer.on("headers", (headers, request) => {
|
|
99
|
+
const extra = headersForHop(upgrades.get(request)?.headers || {});
|
|
100
|
+
for (const [name, value] of Object.entries(extra)) {
|
|
101
|
+
if (name.startsWith("sec-websocket-") || name === "content-length") continue;
|
|
102
|
+
for (const item of Array.isArray(value) ? value : [value]) headers.push(`${name}: ${item}`);
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
function requestContext(request) {
|
|
107
|
+
if (!request.url?.startsWith("/")) throw Object.assign(new Error("Only reverse proxy origin-form paths are supported"), { statusCode: 400 });
|
|
108
|
+
return { method: request.method, path: request.url, headers: { ...request.headers }, upstream: target.href };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function upstreamPath(path) {
|
|
112
|
+
if (typeof path !== "string" || !path.startsWith("/") || /[\r\n#]/.test(path)) throw new Error("Interceptor path must start with / and contain no fragment or newline");
|
|
113
|
+
return target.pathname.replace(/\/$/, "") + path;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function fail(response, error) {
|
|
117
|
+
if (response.destroyed) return;
|
|
118
|
+
console.error(`[aih proxy] ${error.message}`);
|
|
119
|
+
if (response.headersSent) return response.destroy();
|
|
120
|
+
response.writeHead(error.statusCode || 502, { "content-type": "text/plain", connection: "close" });
|
|
121
|
+
response.end(error.statusCode === 413 ? "Request body too large\n" : "Proxy request failed\n");
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function relayResponse(incoming, response, request) {
|
|
125
|
+
const context = { request, statusCode: incoming.statusCode, headers: { ...incoming.headers } };
|
|
126
|
+
try {
|
|
127
|
+
await hooks.onResponse?.(context);
|
|
128
|
+
const headers = headersForHop(context.headers);
|
|
129
|
+
const hasBody = request.method !== "HEAD" && ![204, 304].includes(context.statusCode);
|
|
130
|
+
const isSse = String(incoming.headers["content-type"] || "").toLowerCase().includes("text/event-stream");
|
|
131
|
+
if (hasBody && hooks.onResponseBody && !isSse) {
|
|
132
|
+
context.body = await readBody(incoming, config.maxBodyBytes).catch(error => {
|
|
133
|
+
error.statusCode = 502;
|
|
134
|
+
throw error;
|
|
135
|
+
});
|
|
136
|
+
await hooks.onResponseBody(context);
|
|
137
|
+
context.body = bytes(context.body);
|
|
138
|
+
if (context.body.length > config.maxBodyBytes) throw new Error("Modified response body exceeds maxBodyBytes");
|
|
139
|
+
// The body hook can also update representation headers (e.g. content-encoding).
|
|
140
|
+
const bufferedHeaders = headersForHop(context.headers);
|
|
141
|
+
bufferedHeaders["content-length"] = String(context.body.length);
|
|
142
|
+
response.writeHead(context.statusCode, bufferedHeaders);
|
|
143
|
+
response.end(context.body);
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
if (hasBody && hooks.onResponseChunk) delete headers["content-length"];
|
|
147
|
+
if (context.headers.trailer) headers.trailer = context.headers.trailer;
|
|
148
|
+
incoming.once("end", () => response.addTrailers(headersForHop(incoming.trailers)));
|
|
149
|
+
response.writeHead(context.statusCode, headers);
|
|
150
|
+
response.flushHeaders();
|
|
151
|
+
if (hasBody && hooks.onResponseChunk) {
|
|
152
|
+
const transform = new Transform({
|
|
153
|
+
transform(chunk, _encoding, callback) {
|
|
154
|
+
const event = { ...context, body: chunk };
|
|
155
|
+
Promise.resolve().then(() => hooks.onResponseChunk(event))
|
|
156
|
+
.then(() => bytes(event.body)).then(body => callback(null, body), callback);
|
|
157
|
+
},
|
|
158
|
+
});
|
|
159
|
+
await pipeline(incoming, transform, response);
|
|
160
|
+
} else {
|
|
161
|
+
await pipeline(incoming, response);
|
|
162
|
+
}
|
|
163
|
+
} catch (error) {
|
|
164
|
+
fail(response, error);
|
|
165
|
+
incoming.destroy();
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const server = http.createServer(async (request, response) => {
|
|
170
|
+
let upstream;
|
|
171
|
+
response.on("close", () => upstream?.destroy());
|
|
172
|
+
request.on("error", error => { upstream?.destroy(); fail(response, error); });
|
|
173
|
+
try {
|
|
174
|
+
const context = requestContext(request);
|
|
175
|
+
if (hooks.onRequest) {
|
|
176
|
+
context.body = await readBody(request, config.maxBodyBytes);
|
|
177
|
+
await hooks.onRequest(context);
|
|
178
|
+
context.body = bytes(context.body);
|
|
179
|
+
if (context.body.length > config.maxBodyBytes) throw Object.assign(new Error("Modified request body exceeds maxBodyBytes"), { statusCode: 413 });
|
|
180
|
+
}
|
|
181
|
+
if (response.destroyed) return;
|
|
182
|
+
const headers = headersForHop(context.headers);
|
|
183
|
+
headers.host = target.host;
|
|
184
|
+
if (context.body !== undefined) headers["content-length"] = String(context.body.length);
|
|
185
|
+
else if (context.headers.trailer) headers.trailer = context.headers.trailer;
|
|
186
|
+
upstream = (target.protocol === "https:" ? https : http).request(target, {
|
|
187
|
+
method: context.method, path: upstreamPath(context.path), headers,
|
|
188
|
+
}, incoming => { void relayResponse(incoming, response, context); });
|
|
189
|
+
upstream.on("error", error => fail(response, error));
|
|
190
|
+
request.on("aborted", () => upstream.destroy());
|
|
191
|
+
if (context.body !== undefined) upstream.end(context.body);
|
|
192
|
+
else {
|
|
193
|
+
request.once("end", () => upstream.addTrailers(headersForHop(request.trailers)));
|
|
194
|
+
request.pipe(upstream);
|
|
195
|
+
}
|
|
196
|
+
} catch (error) {
|
|
197
|
+
upstream?.destroy();
|
|
198
|
+
fail(response, error);
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
// Long-lived SSE streams must not expire between model events.
|
|
202
|
+
server.timeout = 0;
|
|
203
|
+
server.on("connection", socket => {
|
|
204
|
+
connections.add(socket);
|
|
205
|
+
socket.once("close", () => connections.delete(socket));
|
|
206
|
+
});
|
|
207
|
+
server.on("connect", (_request, socket) => socket.end("HTTP/1.1 405 Method Not Allowed\r\nConnection: close\r\nContent-Length: 0\r\n\r\n"));
|
|
208
|
+
|
|
209
|
+
server.on("upgrade", (request, socket, head) => {
|
|
210
|
+
let upstream;
|
|
211
|
+
let client;
|
|
212
|
+
let rejected = false;
|
|
213
|
+
let failed = false;
|
|
214
|
+
const abort = error => {
|
|
215
|
+
if (failed) return;
|
|
216
|
+
failed = true;
|
|
217
|
+
if (rejected) { upstream?.terminate(); return; }
|
|
218
|
+
console.error(`[aih proxy] WebSocket: ${error.message}`);
|
|
219
|
+
if (!client && !socket.destroyed && !socket.writableEnded) socket.end("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
|
|
220
|
+
client?.terminate();
|
|
221
|
+
upstream?.terminate();
|
|
222
|
+
};
|
|
223
|
+
socket.on("error", abort);
|
|
224
|
+
socket.once("close", () => { if (!client) upstream?.terminate(); });
|
|
225
|
+
try {
|
|
226
|
+
const context = requestContext(request);
|
|
227
|
+
const headers = headersForHop(context.headers);
|
|
228
|
+
for (const name of Object.keys(headers)) if (name.startsWith("sec-websocket-")) delete headers[name];
|
|
229
|
+
headers.host = target.host;
|
|
230
|
+
const protocols = request.headers["sec-websocket-protocol"]?.split(",").map(p => p.trim());
|
|
231
|
+
const url = new URL(target.origin);
|
|
232
|
+
url.protocol = target.protocol === "https:" ? "wss:" : "ws:";
|
|
233
|
+
upstream = new WebSocket(url.origin + upstreamPath(context.path), protocols, {
|
|
234
|
+
headers, autoPong: false,
|
|
235
|
+
finishRequest: outgoing => { outgoing.path = upstreamPath(context.path); outgoing.end(); },
|
|
236
|
+
perMessageDeflate: false, maxPayload: config.maxBodyBytes, handshakeTimeout: 30000,
|
|
237
|
+
});
|
|
238
|
+
upstreamSockets.add(upstream);
|
|
239
|
+
upstream.once("close", () => upstreamSockets.delete(upstream));
|
|
240
|
+
upstream.on("error", abort);
|
|
241
|
+
upstream.on("unexpected-response", (_outgoing, incoming) => {
|
|
242
|
+
rejected = true;
|
|
243
|
+
const response = new http.ServerResponse(request);
|
|
244
|
+
response.assignSocket(socket);
|
|
245
|
+
response.shouldKeepAlive = false;
|
|
246
|
+
response.once("finish", () => { socket.end(); upstream.terminate(); });
|
|
247
|
+
void relayResponse(incoming, response, context);
|
|
248
|
+
});
|
|
249
|
+
upstream.once("upgrade", incoming => upgrades.set(request, { headers: incoming.headers }));
|
|
250
|
+
upstream.once("open", () => {
|
|
251
|
+
try {
|
|
252
|
+
upgrades.get(request).protocol = upstream.protocol;
|
|
253
|
+
wsServer.handleUpgrade(request, socket, head, connected => {
|
|
254
|
+
client = connected;
|
|
255
|
+
client.on("error", abort);
|
|
256
|
+
bridge(client, upstream, "request", context, abort);
|
|
257
|
+
bridge(upstream, client, "response", context, abort);
|
|
258
|
+
});
|
|
259
|
+
} catch (error) { abort(error); }
|
|
260
|
+
});
|
|
261
|
+
} catch (error) { abort(error); }
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
function bridge(source, destination, direction, request, abort) {
|
|
265
|
+
let pending = Promise.resolve();
|
|
266
|
+
let queuedBytes = 0;
|
|
267
|
+
source.on("message", (data, isBinary) => {
|
|
268
|
+
queuedBytes += data.length;
|
|
269
|
+
if (queuedBytes > config.maxBodyBytes) return abort(new Error("WebSocket interceptor queue exceeds maxBodyBytes"));
|
|
270
|
+
source.pause();
|
|
271
|
+
pending = pending.then(async () => {
|
|
272
|
+
const event = { direction, request, body: data, isBinary };
|
|
273
|
+
await hooks.onWebSocketMessage?.(event);
|
|
274
|
+
const body = bytes(event.body);
|
|
275
|
+
if (body.length > config.maxBodyBytes) throw new Error("Modified WebSocket message exceeds maxBodyBytes");
|
|
276
|
+
await new Promise((resolveSend, reject) => destination.send(body, { binary: event.isBinary }, error => error ? reject(error) : resolveSend()));
|
|
277
|
+
queuedBytes -= data.length;
|
|
278
|
+
if (queuedBytes === 0) source.resume();
|
|
279
|
+
}).catch(abort);
|
|
280
|
+
});
|
|
281
|
+
for (const type of ["ping", "pong"]) source.on(type, data => {
|
|
282
|
+
if (destination.readyState === WebSocket.OPEN) destination[type](data, undefined, error => { if (error) abort(error); });
|
|
283
|
+
});
|
|
284
|
+
source.once("close", (code, reason) => {
|
|
285
|
+
pending.then(() => {
|
|
286
|
+
if (destination.readyState !== WebSocket.OPEN) return;
|
|
287
|
+
if (code === 1006) destination.terminate();
|
|
288
|
+
else if (code === 1005) destination.close();
|
|
289
|
+
else destination.close(code, reason);
|
|
290
|
+
}).catch(abort);
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
await new Promise((resolveListen, reject) => {
|
|
295
|
+
server.once("error", reject);
|
|
296
|
+
server.listen(Number(listen.port || 80), listen.hostname.replace(/^\[|\]$/g, ""), () => {
|
|
297
|
+
server.off("error", reject);
|
|
298
|
+
resolveListen();
|
|
299
|
+
});
|
|
300
|
+
});
|
|
301
|
+
const address = server.address();
|
|
302
|
+
const url = `http://${address.family === "IPv6" ? `[${address.address}]` : address.address}:${address.port}`;
|
|
303
|
+
return {
|
|
304
|
+
url,
|
|
305
|
+
close: () => new Promise((resolveClose, reject) => {
|
|
306
|
+
for (const ws of upstreamSockets) ws.terminate();
|
|
307
|
+
for (const ws of wsServer.clients) ws.terminate();
|
|
308
|
+
for (const socket of connections) socket.destroy();
|
|
309
|
+
wsServer.close();
|
|
310
|
+
server.close(error => error ? reject(error) : resolveClose());
|
|
311
|
+
}),
|
|
312
|
+
};
|
|
313
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
const TYPES = new Set(["image", "image_url", "input_image", "output_image"]);
|
|
4
|
+
const canonical = value => Array.isArray(value) ? value.map(canonical)
|
|
5
|
+
: value && typeof value === "object" ? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])])) : value;
|
|
6
|
+
const hash = value => createHash("sha256").update(JSON.stringify(canonical(value))).digest("hex");
|
|
7
|
+
const textTypes = new Set(["text", "input_text", "output_text"]);
|
|
8
|
+
|
|
9
|
+
/** Only protocol content slots, never schemas, metadata or strings containing JSON. No URL fetches. */
|
|
10
|
+
export function requestImages(body, { identities = true } = {}) {
|
|
11
|
+
const images = [];
|
|
12
|
+
function content(value, owner, path) {
|
|
13
|
+
if (!Array.isArray(value)) return;
|
|
14
|
+
const nearbyText = identities ? value.filter(part => textTypes.has(part?.type) && typeof part.text === "string").map(part => part.text) : [];
|
|
15
|
+
const associationHash = identities ? hash({ ...owner, nearbyText }) : undefined;
|
|
16
|
+
for (const [index, part] of value.entries()) {
|
|
17
|
+
if (!part || typeof part !== "object") continue;
|
|
18
|
+
const inline = part.inline_data || part.inlineData;
|
|
19
|
+
if (TYPES.has(part.type) || /^image\//.test(inline?.mime_type || inline?.mimeType || "")) {
|
|
20
|
+
// Routing only needs presence: avoid serializing/hashing potentially huge attachments there.
|
|
21
|
+
images.push({ ...(identities ? { fingerprint: hash(part), associationHash } : {}), group: path, position: index });
|
|
22
|
+
} else if (part.type === "tool_result") {
|
|
23
|
+
content(part.content, { ...owner, toolCallId: part.tool_use_id || null }, `${path}/${index}/tool_result`);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
content(body?.system, { scope: "system", role: "system" }, "system");
|
|
28
|
+
content(body?.instructions, { scope: "instructions", role: "system" }, "instructions");
|
|
29
|
+
for (const scope of ["input", "messages"]) {
|
|
30
|
+
for (const [index, item] of (Array.isArray(body?.[scope]) ? body[scope] : []).entries()) {
|
|
31
|
+
if (!item || typeof item !== "object") continue;
|
|
32
|
+
const owner = { scope, role: item.role || null, toolCallId: item.call_id || item.tool_call_id || null };
|
|
33
|
+
content(item.content, owner, `${scope}/${index}/content`);
|
|
34
|
+
if (item.type === "function_call_output") content(item.output, owner, `${scope}/${index}/output`);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return images;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Exact attachment/metadata preservation, relative order, grouping and adjacent native text. */
|
|
41
|
+
export function compareRequestImages(original, transformed) {
|
|
42
|
+
const before = requestImages(original), after = requestImages(transformed);
|
|
43
|
+
const wanted = new Set(before.map(x => x.fingerprint));
|
|
44
|
+
const originalsAfter = after.filter(x => wanted.has(x.fingerprint));
|
|
45
|
+
const counts = list => { const map = new Map(); for (const x of list) map.set(x.fingerprint, (map.get(x.fingerprint) || 0) + 1); return map; };
|
|
46
|
+
const b = counts(before), a = counts(originalsAfter);
|
|
47
|
+
let retained = 0, duplicated = 0;
|
|
48
|
+
for (const [fingerprint, count] of b) { retained += Math.min(count, a.get(fingerprint) || 0); duplicated += Math.max(0, (a.get(fingerprint) || 0) - count); }
|
|
49
|
+
const sequence = list => JSON.stringify(list.map(x => x.fingerprint));
|
|
50
|
+
const groups = list => { const map = new Map(); return list.map(x => { if (!map.has(x.group)) map.set(x.group, map.size); return map.get(x.group); }); };
|
|
51
|
+
const occurrences = new Map(), matches = new Map();
|
|
52
|
+
for (const item of originalsAfter) { if (!matches.has(item.fingerprint)) matches.set(item.fingerprint, []); matches.get(item.fingerprint).push(item); }
|
|
53
|
+
const checks = before.map((item, index) => {
|
|
54
|
+
const occurrence = occurrences.get(item.fingerprint) || 0;
|
|
55
|
+
occurrences.set(item.fingerprint, occurrence + 1);
|
|
56
|
+
const match = matches.get(item.fingerprint)?.[occurrence];
|
|
57
|
+
return { id: `native_image:${index}`, kind: "nativeImage", status: match ? "pass" : "fail", reason: match ? "native_image_unchanged" : "native_image_missing_or_changed" };
|
|
58
|
+
});
|
|
59
|
+
if (before.length) {
|
|
60
|
+
const ordered = sequence(before) === sequence(originalsAfter);
|
|
61
|
+
checks.push({ id: "native_images:order", kind: "nativeImage", status: ordered ? "pass" : "fail", reason: ordered ? "native_image_order_preserved" : "native_image_order_or_count_changed" });
|
|
62
|
+
const associated = ordered && before.every((x, i) => x.associationHash === originalsAfter[i].associationHash)
|
|
63
|
+
&& JSON.stringify(groups(before)) === JSON.stringify(groups(originalsAfter));
|
|
64
|
+
checks.push({ id: "native_images:association", kind: "nativeImage", status: associated ? "pass" : "fail", reason: associated ? "native_image_association_preserved" : "native_image_association_or_adjacent_text_changed" });
|
|
65
|
+
}
|
|
66
|
+
return { status: checks.some(c => c.status === "fail") ? "fail" : before.length ? "pass" : "unscored",
|
|
67
|
+
before: before.length, after: after.length, retained, missingOrChanged: before.length - retained, duplicated,
|
|
68
|
+
addedOrChanged: after.length - originalsAfter.length, checks };
|
|
69
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { closeSync, openSync, writeSync } from "node:fs";
|
|
3
|
+
import { SERVICE_PACKAGES, SERVICES } from "./config.js";
|
|
4
|
+
import { compareVersions } from "./utils/versions.js";
|
|
5
|
+
import { ensureDir, getLogsDir, getServiceLogPath } from "./utils/path.js";
|
|
6
|
+
|
|
7
|
+
/** Only allowlisted services/arguments reach an installer; never execute user input. */
|
|
8
|
+
export function serviceUpdateInvocation(id, platform = process.platform) {
|
|
9
|
+
if (!Object.hasOwn(SERVICE_PACKAGES, id)) throw new Error(`Service '${id}' cannot be updated separately`);
|
|
10
|
+
const pkg = SERVICE_PACKAGES[id];
|
|
11
|
+
// Headroom detects its own Python environment (uv, pipx, pip/venv).
|
|
12
|
+
// Do not run an arbitrary `pip` from PATH against a different interpreter.
|
|
13
|
+
if (pkg.pypi) return { command: "headroom", args: ["update", "--yes"] };
|
|
14
|
+
const args = ["install", "--global", `${pkg.name}@latest`, "--no-audit", "--no-fund"];
|
|
15
|
+
// npm.cmd cannot be spawned directly on Windows. These are fixed arguments,
|
|
16
|
+
// not paths or user-provided shell text; no shell is used on Unix.
|
|
17
|
+
return platform === "win32"
|
|
18
|
+
? { command: "cmd.exe", args: ["/d", "/s", "/c", `npm ${args.join(" ")}`] }
|
|
19
|
+
: { command: "npm", args };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Pin npx after an explicit update, so a project's old dependency/cache cannot win. */
|
|
23
|
+
export function serviceStartCommand(id, state) {
|
|
24
|
+
const pkg = SERVICE_PACKAGES[id];
|
|
25
|
+
const version = state?.launchVersion;
|
|
26
|
+
if (pkg?.npx && typeof version === "string" && compareVersions(version, version) === 0) {
|
|
27
|
+
return `npx --yes ${pkg.name}@${version.trim().replace(/^v/, "")}`;
|
|
28
|
+
}
|
|
29
|
+
return SERVICES[id]?.command;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Capture installer output, keeping --json/TUI clean and full diagnostics in the service log. */
|
|
33
|
+
export function installServiceUpdate(id, { spawnImpl = spawn, platform = process.platform } = {}) {
|
|
34
|
+
const { command, args } = serviceUpdateInvocation(id, platform);
|
|
35
|
+
ensureDir(getLogsDir());
|
|
36
|
+
const logPath = getServiceLogPath(id);
|
|
37
|
+
const fd = openSync(logPath, "a");
|
|
38
|
+
writeSync(fd, `\n[aih] Update ${new Date().toISOString()}: ${command} ${args.join(" ")}\n`);
|
|
39
|
+
return new Promise(resolve => {
|
|
40
|
+
let tail = "";
|
|
41
|
+
let finished = false;
|
|
42
|
+
const finish = (exitCode, message) => {
|
|
43
|
+
if (finished) return;
|
|
44
|
+
finished = true;
|
|
45
|
+
closeSync(fd);
|
|
46
|
+
resolve({ success: exitCode === 0, exitCode, logPath,
|
|
47
|
+
message: message || (exitCode === 0 ? "Installer completed" : `Installer failed (${exitCode}): ${tail.trim() || "no output"}`) });
|
|
48
|
+
};
|
|
49
|
+
const collect = data => {
|
|
50
|
+
// Bound memory, not the log: package managers can produce many megabytes.
|
|
51
|
+
const text = String(data);
|
|
52
|
+
tail = (tail + text).slice(-4000);
|
|
53
|
+
if (!finished) { try { writeSync(fd, text); } catch {} }
|
|
54
|
+
};
|
|
55
|
+
try {
|
|
56
|
+
const child = spawnImpl(command, args, {
|
|
57
|
+
windowsHide: true, stdio: ["ignore", "pipe", "pipe"],
|
|
58
|
+
env: { ...process.env, CI: "1", npm_config_yes: "true", PIP_NO_INPUT: "1", NO_COLOR: "1" },
|
|
59
|
+
});
|
|
60
|
+
child.stdout?.on("data", collect);
|
|
61
|
+
child.stderr?.on("data", collect);
|
|
62
|
+
child.once("error", error => finish(1, `Cannot update '${id}': ${error.message}`));
|
|
63
|
+
// `close`, not `exit`: Headroom on Windows hands pip off to a child that
|
|
64
|
+
// inherits these pipes. Wait for that installer too before restarting.
|
|
65
|
+
child.once("close", (code, signal) => finish(code ?? 1, signal ? `Installer terminated by ${signal}` : undefined));
|
|
66
|
+
} catch (error) { finish(1, error.message); }
|
|
67
|
+
});
|
|
68
|
+
}
|