@drakonkat/ai-helper 1.1.1 → 1.2.2

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.
@@ -0,0 +1,226 @@
1
+ import { spawn } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import zlib from "node:zlib";
4
+ import { tokenStage } from "./proxy-stats.js";
5
+
6
+ // Fixed recipes; the user's --interceptor runs afterwards and can inspect/edit the result.
7
+ const PRESETS = ["none", "pxpipe", "headroom", "rtk", "headroom-pxpipe", "rtk-pxpipe"];
8
+ const DECODERS = { gzip: promisify(zlib.gunzip), deflate: promisify(zlib.inflate), br: promisify(zlib.brotliDecompress),
9
+ ...(typeof zlib.zstdDecompress === "function" ? { zstd: promisify(zlib.zstdDecompress) } : {}) };
10
+
11
+ export function normalizePresetOptions(options) {
12
+ const preset = options.preset || "none";
13
+ if (!PRESETS.includes(preset)) throw new Error(`Unknown preset. Choose: ${PRESETS.join(", ")}`);
14
+ const models = options.models ? String(options.models).split(",").map(s => s.trim()) : undefined;
15
+ if (models?.some(s => !s || !/^[\w./:-]+\*?$/.test(s))) throw new Error("models must be comma-separated model names, optionally ending in *");
16
+ const headroom = new URL(options.headroomUrl || "http://127.0.0.1:8787");
17
+ if (!["http:", "https:"].includes(headroom.protocol) || headroom.username || headroom.password || headroom.search || headroom.hash) {
18
+ throw new Error("headroomUrl must be HTTP(S) without credentials, query or fragment");
19
+ }
20
+ const rtkFilter = options.rtkFilter || undefined;
21
+ if (rtkFilter && !/^[a-z][a-z0-9-]*$/.test(rtkFilter)) throw new Error("Invalid rtk filter name");
22
+ return { preset, models: models?.join(","), headroomUrl: headroom.href, rtkFilter };
23
+ }
24
+
25
+ function toolTexts(body) {
26
+ const slots = [];
27
+ const add = (object, key) => { if (typeof object[key] === "string" && object[key]) slots.push([object, key]); };
28
+ for (const item of Array.isArray(body.input) ? body.input : []) {
29
+ if (item?.type !== "function_call_output") continue;
30
+ if (Array.isArray(item.output)) {
31
+ for (const part of item.output) if (part?.type === "input_text") add(part, "text");
32
+ } else add(item, "output");
33
+ }
34
+ for (const message of Array.isArray(body.messages) ? body.messages : []) {
35
+ if (message?.role === "tool") {
36
+ if (Array.isArray(message.content)) {
37
+ for (const part of message.content) if (part?.type === "text") add(part, "text");
38
+ } else add(message, "content");
39
+ }
40
+ if (!Array.isArray(message?.content)) continue;
41
+ for (const part of message.content) {
42
+ if (part?.type !== "tool_result") continue;
43
+ if (Array.isArray(part.content)) {
44
+ for (const block of part.content) if (block?.type === "text") add(block, "text");
45
+ } else add(part, "content");
46
+ }
47
+ }
48
+ return slots;
49
+ }
50
+
51
+ function rtkPipe(text, filter, limit) {
52
+ return new Promise((resolve, reject) => {
53
+ // Never execute a command from a tool call: RTK receives only stdin and fixed CLI flags.
54
+ const child = spawn("rtk", ["pipe", ...(filter ? ["--filter", filter] : [])], { windowsHide: true, shell: false, stdio: ["pipe", "pipe", "pipe"] });
55
+ const chunks = [];
56
+ let size = 0;
57
+ const fail = error => { child.kill(); reject(error); };
58
+ const timeout = setTimeout(() => fail(new Error("rtk pipe timed out")), 30000);
59
+ child.once("error", error => { clearTimeout(timeout); reject(error); });
60
+ child.stdin.on("error", fail);
61
+ child.stderr.resume();
62
+ child.stdout.on("data", chunk => {
63
+ size += chunk.length;
64
+ if (size > limit) fail(new Error("rtk output exceeds maxBodyBytes"));
65
+ else chunks.push(chunk);
66
+ });
67
+ child.once("close", code => {
68
+ clearTimeout(timeout);
69
+ if (code !== 0) reject(new Error(`rtk pipe exited with code ${code}`));
70
+ else resolve(Buffer.concat(chunks).toString("utf8"));
71
+ });
72
+ child.stdin.end(text);
73
+ });
74
+ }
75
+
76
+ export async function createPresetHooks(config, onStats = () => {}) {
77
+ if (!config.preset || config.preset === "none") return {};
78
+ const { countTokens: tokenize } = await import("gpt-tokenizer/encoding/o200k_base");
79
+ function countTokens(text) {
80
+ try { return tokenize(text, { disallowedSpecial: new Set() }); }
81
+ catch { return NaN; } // Observability must not reject an otherwise valid request.
82
+ }
83
+ const px = config.preset.includes("pxpipe") ? await import("pxpipe-proxy") : null;
84
+ const models = config.models?.split(",");
85
+ const wsModels = new WeakMap();
86
+ const warnedEncodings = new Set();
87
+
88
+ async function headroom(body, model) {
89
+ // Responses items (reasoning, calls, IDs, images) stay native. Compress only their tool text.
90
+ const slots = Array.isArray(body.input) ? toolTexts(body) : null;
91
+ const messages = slots ? slots.map(([object, key], i) => ({ role: "tool", tool_call_id: String(i), content: object[key] })) : body.messages;
92
+ if (!messages?.length) return tokenStage("headroom", 0, 0, false, "no_messages", "headroom");
93
+ const response = await fetch(config.headroomUrl.replace(/\/$/, "") + "/v1/compress", {
94
+ method: "POST", redirect: "error", signal: AbortSignal.timeout(30000),
95
+ headers: { "content-type": "application/json", ...(process.env.HEADROOM_PROXY_TOKEN ? { "x-headroom-proxy-token": process.env.HEADROOM_PROXY_TOKEN } : {}) },
96
+ // Inline mode needs no Headroom retrieval tool injected into the client.
97
+ body: JSON.stringify({ model, messages, config: { mode: "lossy_inline" } }),
98
+ });
99
+ if (!response.ok) throw new Error(`Headroom compression returned HTTP ${response.status}`);
100
+ const chunks = [];
101
+ let size = 0;
102
+ for await (const chunk of response.body) {
103
+ size += chunk.length;
104
+ if (size > config.maxBodyBytes) throw new Error("Headroom response exceeds maxBodyBytes");
105
+ chunks.push(chunk);
106
+ }
107
+ const result = JSON.parse(Buffer.concat(chunks).toString("utf8"));
108
+ if (!Array.isArray(result.messages)) throw new Error("Invalid Headroom response: missing messages");
109
+ if (slots) {
110
+ if (result.messages.length !== slots.length || result.messages.some((m, i) => m?.tool_call_id !== String(i) || typeof m.content !== "string")) {
111
+ throw new Error("Headroom changed the Responses tool output structure");
112
+ }
113
+ slots.forEach(([object, key], i) => { object[key] = result.messages[i].content; });
114
+ } else body.messages = result.messages;
115
+ return tokenStage("headroom", result.tokens_before, result.tokens_after,
116
+ JSON.stringify(result.messages) !== JSON.stringify(messages), result.compression_skipped ? "compression_skipped" : "processed", "headroom");
117
+ }
118
+
119
+ async function transform(raw, context, websocket = false) {
120
+ const path = new URL(context.path, "http://localhost").pathname;
121
+ const format = /\/(?:v1\/|anthropic\/)?messages$/.test(path) ? "anthropic"
122
+ : /\/chat\/completions$/.test(path) ? "chat" : /\/responses$/.test(path) ? "responses" : null;
123
+ if (!format) return raw;
124
+ let envelope;
125
+ try { envelope = JSON.parse(raw.toString("utf8")); } catch { return raw; }
126
+ if (!envelope || typeof envelope !== "object" || Array.isArray(envelope)) return raw;
127
+ if (websocket && envelope.type !== "response.create") return raw;
128
+ const body = websocket && envelope.response ? envelope.response : envelope;
129
+ if (!body || typeof body !== "object" || Array.isArray(body)) return raw;
130
+ const model = body.model || (websocket && (wsModels.get(context) || new URL(context.path, "http://localhost").searchParams.get("model")));
131
+ if (typeof model !== "string" || !model) return raw;
132
+ if (websocket) wsModels.set(context, model);
133
+ if (format === "responses" ? !(typeof body.input === "string" || Array.isArray(body.input)) : !Array.isArray(body.messages)) return raw;
134
+ let changed = false;
135
+ const stages = [];
136
+ const report = error => {
137
+ // Observability must never interrupt proxy traffic; no request bodies are passed to the recorder.
138
+ // Optional correlation only; never pass headers or bodies to the recorder.
139
+ const requestId = typeof context.headers?.["x-request-id"] === "string" ? context.headers["x-request-id"].slice(0, 128) : undefined;
140
+ try { onStats({ model, preset: config.preset, transport: websocket ? "WS" : "HTTP", changed, stages, error, ...(requestId ? { requestId } : {}) }); } catch {}
141
+ };
142
+ try {
143
+ if (config.preset.startsWith("headroom")) {
144
+ const before = JSON.stringify(body);
145
+ stages.push(await headroom(body, model));
146
+ changed = JSON.stringify(body) !== before;
147
+ }
148
+ if (config.preset === "rtk" || config.preset === "rtk-pxpipe") {
149
+ let before = 0, after = 0, applied = false;
150
+ for (const [object, key] of toolTexts(body)) {
151
+ before += countTokens(object[key]);
152
+ const output = await rtkPipe(object[key], config.rtkFilter, config.maxBodyBytes);
153
+ // RTK may add framing or not recognize this output; only keep actual compression.
154
+ if (output.trim() && Buffer.byteLength(output) < Buffer.byteLength(object[key])) {
155
+ object[key] = output;
156
+ changed = true;
157
+ applied = true;
158
+ }
159
+ after += countTokens(object[key]);
160
+ }
161
+ stages.push(tokenStage("rtk", before, after, applied, applied ? "applied" : "unchanged", "o200k_estimate"));
162
+ }
163
+ if (px && (models ? models.some(m => m.endsWith("*") ? model.startsWith(m.slice(0, -1)) : model === m) : px.isPxpipeSupportedModel(model) || px.isPxpipeSupportedGptModel(model))) {
164
+ const bytes = Buffer.from(JSON.stringify({ ...body, model }));
165
+ const options = { model };
166
+ const result = await (format === "anthropic" ? px.transformRequest(bytes, options)
167
+ : format === "chat" ? px.transformOpenAIChatCompletions(bytes, options) : px.transformOpenAIResponses(bytes, options));
168
+ const info = result.info || {};
169
+ let before = 0, after = 0, method = "pxpipe_estimate";
170
+ if (info.compressed) {
171
+ before = info.baselineImagedTokens;
172
+ after = Number.isFinite(info.imageTokens) ? info.imageTokens + (info.nativeInjectedTokens ?? 0) : undefined;
173
+ if (!Number.isFinite(before) || !Number.isFinite(after)) {
174
+ // Anthropic's transformer lacks token totals: count text locally and include newly rendered images.
175
+ const textTokens = value => countTokens(JSON.stringify(value, (key, item) =>
176
+ ["image", "input_image", "image_url"].includes(item?.type) || key === "encrypted_content" ? undefined : item));
177
+ before = textTokens(JSON.parse(bytes));
178
+ let imageTokens;
179
+ try { imageTokens = info.imageDims?.reduce((sum, d) => sum + px.openAIVisionTokens(model, d.width, d.height), 0); } catch {}
180
+ after = Number.isFinite(imageTokens) ? textTokens(JSON.parse(Buffer.from(result.body))) + imageTokens : undefined;
181
+ method = "o200k_and_vision_estimate";
182
+ }
183
+ }
184
+ stages.push(tokenStage("pxpipe", before, after, Boolean(info.compressed),
185
+ info.compressed ? "applied" : String(info.reason || "unchanged").split(/[^a-z_]/i)[0].slice(0, 40), method));
186
+ if (result.info?.compressed) {
187
+ const transformed = JSON.parse(Buffer.from(result.body).toString("utf8"));
188
+ if (!Object.hasOwn(body, "model")) delete transformed.model;
189
+ // Only replace the AI request, preserving a WebSocket event's outer fields.
190
+ if (body !== envelope) envelope.response = transformed;
191
+ else { for (const key of Object.keys(body)) delete body[key]; Object.assign(body, transformed); }
192
+ changed = true;
193
+ }
194
+ } else if (px) {
195
+ stages.push(tokenStage("pxpipe", 0, 0, false, "model_excluded", "pxpipe_estimate"));
196
+ }
197
+ report(false);
198
+ return changed ? Buffer.from(JSON.stringify(envelope)) : raw;
199
+ } catch (error) { report(true); throw error; }
200
+ }
201
+
202
+ return {
203
+ async onRequest(context) {
204
+ if (context.method !== "POST" || !/\bapplication\/(?:[\w.-]+\+)?json\b/i.test(String(context.headers["content-type"] || ""))) return;
205
+ const encoding = String(context.headers["content-encoding"] || "identity").toLowerCase();
206
+ if (encoding !== "identity" && !DECODERS[encoding]) {
207
+ if (!warnedEncodings.has(encoding)) {
208
+ console.warn(`[aih preset] Skipped unsupported content-encoding=${encoding} on ${process.version}${encoding === "zstd" ? "; use Node.js 22.15+ for Zstandard requests" : ""}`);
209
+ warnedEncodings.add(encoding);
210
+ }
211
+ return;
212
+ }
213
+ const raw = encoding === "identity" ? context.body : await DECODERS[encoding](context.body, { maxOutputLength: config.maxBodyBytes });
214
+ const body = await transform(raw, context);
215
+ if (body !== raw) {
216
+ context.body = body;
217
+ delete context.headers["content-encoding"];
218
+ delete context.headers["content-md5"];
219
+ delete context.headers.digest;
220
+ }
221
+ },
222
+ async onWebSocketMessage(event) {
223
+ if (event.direction === "request" && !event.isBinary) event.body = await transform(event.body, event.request, true);
224
+ },
225
+ };
226
+ }
@@ -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
+ }