@drakonkat/ai-helper 1.2.11 → 1.2.12
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/CHANGELOG.md +12 -0
- package/README.md +22 -0
- package/docs/pxpipe-performance-2026-09-30.md +45 -0
- package/package.json +4 -2
- package/scripts/build.js +7 -0
- package/scripts/patch-pxpipe.js +46 -0
- package/src/index.js +1 -0
- package/src/proxy-presets.js +16 -26
- package/src/proxy.js +23 -5
- package/src/pxpipe-pool.js +91 -0
- package/src/pxpipe-thread.js +46 -0
- package/src/tui.js +5 -0
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,18 @@ All notable changes to **`ai-helper` (`aih`)** are documented in this file.
|
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
+
## [1.2.12] - 2026-09-30
|
|
8
|
+
|
|
9
|
+
### Fixed
|
|
10
|
+
- Exclude opaque reasoning, compaction and media from pxpipe's diagnostic token counts, retaining forwarded payloads and reporting partial counts explicitly. Apply the version-checked correction on installation and standalone builds.
|
|
11
|
+
- Run pxpipe transformations and token estimates in up to two persistent CPU workers so heavy requests cannot block HTTP/SSE or excluded models. Bound waiting work, cancel disconnected requests, recover from worker crashes and close workers on shutdown.
|
|
12
|
+
|
|
13
|
+
### Added
|
|
14
|
+
- Show worker queue, processing, supported thread CPU and sampled event-loop delay separately in the request stream.
|
|
15
|
+
- Regression checks for opaque payload preservation, excluded-model responsiveness, bounded queues, cancellation, crash recovery and shutdown.
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
7
19
|
## [1.2.11] - 2026-09-30
|
|
8
20
|
|
|
9
21
|
### Changed
|
package/README.md
CHANGED
|
@@ -324,6 +324,28 @@ does not update an older aih installation or standalone binary. See the
|
|
|
324
324
|
[offline CPU profiling report](docs/pxpipe-performance-2026-09-30.md) for measured
|
|
325
325
|
tokenization costs and worker-thread experiments.
|
|
326
326
|
|
|
327
|
+
Pxpipe transformations and their token estimates run in up to **two persistent
|
|
328
|
+
CPU workers**. Excluded models bypass the worker queue; HTTP and SSE streaming
|
|
329
|
+
remain on the main thread. Sessions have stable worker affinity to reuse caches.
|
|
330
|
+
The queue is limited to 32 waiting requests and `--max-body-bytes` of waiting
|
|
331
|
+
input; overload returns HTTP 503. Disconnecting cancels queued work or terminates
|
|
332
|
+
and replaces the active worker. Shutdown closes both workers.
|
|
333
|
+
|
|
334
|
+
Installation applies a version-checked correction to pxpipe 0.14.0: diagnostic
|
|
335
|
+
composition counts exclude encrypted reasoning, opaque compaction and media data,
|
|
336
|
+
including JSON-serialized tool media. Forwarded payloads keep these values intact.
|
|
337
|
+
`responsesComposition.partial` and `excludedBytes` identify incomplete diagnostic
|
|
338
|
+
counts. Lifecycle scripts must be enabled for this correction; standalone builds
|
|
339
|
+
include it automatically. Dependency upgrades require reviewing the correction.
|
|
340
|
+
|
|
341
|
+
The request stream separates total preset time (`proxy`), worker queue time
|
|
342
|
+
(`coda`), transformation time (`pxpipe`) and, on supporting Node versions, worker
|
|
343
|
+
CPU time (`CPU`). Header and total response times retain their existing meaning;
|
|
344
|
+
worker isolation does not shorten provider generation time.
|
|
345
|
+
`loop max` is the maximum sampled main-thread scheduling delay since the preceding
|
|
346
|
+
preset event beyond the 20 ms sampling interval, shared across requests. Queue
|
|
347
|
+
time includes cold worker startup.
|
|
348
|
+
|
|
327
349
|
Pass `--models` to `aih start` (or `aih up`) to override the proxy's model list:
|
|
328
350
|
|
|
329
351
|
```bash
|
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
# Profilazione pxpipe — 30 settembre 2026
|
|
2
2
|
|
|
3
|
+
**Aggiornamento aih 1.2.12:** gli interventi sul conteggio diagnostico e sui worker
|
|
4
|
+
sono ora integrati. Le sezioni sperimentali sotto conservano le misure originali;
|
|
5
|
+
il nuovo controllo di produzione è descritto in fondo.
|
|
6
|
+
|
|
3
7
|
Il progetto usava `pxpipe-proxy` **0.13.2**. È stato aggiornato a **0.14.0** in
|
|
4
8
|
`package.json`, `package-lock.json`, `bun.lock` e nell'installazione locale.
|
|
5
9
|
La build standalone è stata ricompilata con la nuova dipendenza.
|
|
@@ -203,3 +207,44 @@ privilegi; nel controllo locale la terminazione è stata negata con `Access is d
|
|
|
203
207
|
Fonti primarie: [release pxpipe 0.14.0](https://github.com/teamchong/pxpipe/releases/tag/v0.14.0),
|
|
204
208
|
[Node.js 22: worker thread e pool persistenti](https://nodejs.org/docs/latest-v22.x/api/worker_threads.html).
|
|
205
209
|
Le misure e le conclusioni prestazionali sopra derivano dai profili locali.
|
|
210
|
+
|
|
211
|
+
## Integrazione in aih 1.2.12
|
|
212
|
+
|
|
213
|
+
L'installazione e la build applicano automaticamente una correzione controllata
|
|
214
|
+
per pxpipe 0.14.0. La sola copia diagnostica esclude reasoning cifrato, compaction
|
|
215
|
+
opaca e media, anche serializzati nel JSON di un output tool. Le metriche espongono
|
|
216
|
+
`responsesComposition.partial` e `excludedBytes`; la richiesta trasformata non
|
|
217
|
+
viene privata di questi dati. La correzione è idempotente e rifiuta versioni o
|
|
218
|
+
target diversi, così un aggiornamento della dipendenza richiede una revisione.
|
|
219
|
+
|
|
220
|
+
Il proxy usa al massimo due worker persistenti, avviati al primo lavoro e
|
|
221
|
+
assegnati stabilmente per sessione. I modelli esclusi evitano la coda. Al massimo
|
|
222
|
+
32 richieste e `maxBodyBytes` di input possono attendere; oltre il limite viene
|
|
223
|
+
restituito HTTP 503. Una disconnessione elimina il lavoro in coda oppure termina
|
|
224
|
+
e sostituisce il worker attivo. La chiusura del proxy termina tutti i worker.
|
|
225
|
+
La build standalone incorpora separatamente anche il codice dei thread.
|
|
226
|
+
|
|
227
|
+
Il nuovo probe usa la medesima fixture Responses con 256 KiB ripetitivi e confronta
|
|
228
|
+
gli SHA-256 con il risultato 0.14.0 originale già registrato:
|
|
229
|
+
|
|
230
|
+
| Modello / stato | Tempo totale preset | Tempo nel worker | Coda / avvio worker |
|
|
231
|
+
|---|---:|---:|---:|
|
|
232
|
+
| Claude / primo uso | 1.026 ms | 406 ms | 612 ms |
|
|
233
|
+
| Astra / primo uso | 1.016 ms | 418 ms | 591 ms |
|
|
234
|
+
| Claude / cache calda | 171 ms | 167 ms | 0 ms |
|
|
235
|
+
| Astra / cache calda | 186 ms | 181 ms | 0 ms |
|
|
236
|
+
|
|
237
|
+
I due primi usi sono concorrenti, con cache indipendenti. Gli output coincidono
|
|
238
|
+
con quelli originali in tutti e quattro i confronti. Sol escluso passa in 0,6 ms;
|
|
239
|
+
il ritardo massimo del timer principale è 11,1 ms. Queste misure singole e
|
|
240
|
+
sintetiche non garantiscono la latenza del traffico reale né quella del provider.
|
|
241
|
+
|
|
242
|
+
Il dashboard mostra separatamente `coda`, `pxpipe`, CPU del thread quando
|
|
243
|
+
supportata da Node e `loop max`: quest'ultimo è il massimo ritardo campionato del
|
|
244
|
+
thread principale dall'evento preset precedente, condiviso tra le richieste.
|
|
245
|
+
|
|
246
|
+
Verifica ripetibile nel repository: `node --test test/pxpipe-performance.test.js`.
|
|
247
|
+
I nuovi test controllano anche output identici prima/dopo la correzione, media
|
|
248
|
+
nativi, compaction, Sol escluso durante due lavori CPU, coda limitata, cancellazione,
|
|
249
|
+
crash e chiusura. La suite completa e il test CLI standalone sono passati.
|
|
250
|
+
Il probe e `optimized-production.json` rimangono negli artefatti locali ignorati.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@drakonkat/ai-helper",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.12",
|
|
4
4
|
"description": "Zero-config background service manager, auto-discovery daemon & dashboard launcher for AI agent ecosystems (pxpipe, ocx, agentmemory, headroom)",
|
|
5
5
|
"main": "src/index.js",
|
|
6
6
|
"module": "src/index.js",
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
"bin",
|
|
14
14
|
"src",
|
|
15
15
|
"scripts/build.js",
|
|
16
|
+
"scripts/patch-pxpipe.js",
|
|
16
17
|
"scripts/bench-proxy.js",
|
|
17
18
|
"docs/benchmark.md",
|
|
18
19
|
"docs/pxpipe-performance-2026-09-30.md",
|
|
@@ -36,9 +37,10 @@
|
|
|
36
37
|
},
|
|
37
38
|
"homepage": "https://github.com/drakonkat/ai-helper#readme",
|
|
38
39
|
"scripts": {
|
|
40
|
+
"postinstall": "node scripts/patch-pxpipe.js",
|
|
39
41
|
"start": "node ./bin/cli.js",
|
|
40
42
|
"dev": "node ./bin/cli.js",
|
|
41
|
-
"test": "bun test test/aih.test.js test/metrics.test.js test/discovery.test.js test/tui-pipeline.test.js test/tui-versions.test.js test/versions.test.js test/repositories.test.js test/service-updates.test.js && node --test test/proxy.test.js test/codex-config.test.js test/codex-routing.test.js test/codex-manager.test.js test/benchmark-live.test.js test/benchmark-measurement.test.js test/benchmark-quality.test.js test/benchmark-report.test.js test/benchmark-runner.test.js test/benchmark-multimodal.test.js",
|
|
43
|
+
"test": "bun test test/aih.test.js test/metrics.test.js test/discovery.test.js test/tui-pipeline.test.js test/tui-versions.test.js test/versions.test.js test/repositories.test.js test/service-updates.test.js && node --test test/proxy.test.js test/pxpipe-performance.test.js test/codex-config.test.js test/codex-routing.test.js test/codex-manager.test.js test/benchmark-live.test.js test/benchmark-measurement.test.js test/benchmark-quality.test.js test/benchmark-report.test.js test/benchmark-runner.test.js test/benchmark-multimodal.test.js",
|
|
42
44
|
"bench:proxy": "node scripts/bench-proxy.js",
|
|
43
45
|
"bench:models": "node scripts/bench-proxy.js --compare-models gpt-6-astra,anthropic/claude-fable-5-1 --formats responses",
|
|
44
46
|
"test:benchmark": "node --test test/benchmark-live.test.js test/benchmark-measurement.test.js test/benchmark-quality.test.js test/benchmark-report.test.js test/benchmark-runner.test.js test/benchmark-multimodal.test.js",
|
package/scripts/build.js
CHANGED
|
@@ -1,10 +1,17 @@
|
|
|
1
1
|
import { resolve } from "node:path";
|
|
2
|
+
import { patchPxpipe } from "./patch-pxpipe.js";
|
|
2
3
|
|
|
3
4
|
// Embed a Node worker so the compiled CLI uses the same proxy transport as npm.
|
|
4
5
|
const root = resolve(import.meta.dir, "..");
|
|
5
6
|
const outfile = process.argv[2] || resolve(root, "dist", process.platform === "win32" ? "aih.exe" : "aih");
|
|
7
|
+
patchPxpipe();
|
|
8
|
+
const thread = await Bun.build({
|
|
9
|
+
entrypoints: [resolve(root, "src/pxpipe-thread.js")], target: "node", format: "esm", minify: true,
|
|
10
|
+
});
|
|
11
|
+
if (!thread.success) throw new AggregateError(thread.logs, "Pxpipe thread build failed");
|
|
6
12
|
const worker = await Bun.build({
|
|
7
13
|
entrypoints: [resolve(root, "src/proxy-worker.js")], target: "node", format: "esm", minify: true,
|
|
14
|
+
define: { AIH_PXPIPE_THREAD_SOURCE: JSON.stringify(await thread.outputs[0].text()) },
|
|
8
15
|
});
|
|
9
16
|
if (!worker.success) throw new AggregateError(worker.logs, "Proxy worker build failed");
|
|
10
17
|
const result = await Bun.build({
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync, renameSync, rmSync } from "node:fs";
|
|
2
|
+
import { dirname, resolve } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
|
|
5
|
+
const original = "info.responsesComposition = measureResponsesComposition(req, inputWasString, originalInputString, inputItems);";
|
|
6
|
+
// Only the diagnostic copy is filtered. The transformer continues using req/inputItems unchanged.
|
|
7
|
+
const replacement = `// aih: partial diagnostics exclude opaque payloads (pxpipe 0.14.0).
|
|
8
|
+
const diagnosticOriginal = JSON.stringify(req);
|
|
9
|
+
const diagnosticJson = JSON.stringify(req, (key, value) => {
|
|
10
|
+
if (key === 'encrypted_content') return undefined;
|
|
11
|
+
if (['image', 'input_image', 'output_image', 'image_url', 'input_audio', 'audio', 'audio_url', 'input_video', 'video', 'video_url'].includes(value?.type) || value?.inline_data || value?.inlineData)
|
|
12
|
+
return { type: value.type || 'opaque_media' };
|
|
13
|
+
if (['compaction', 'compaction_trigger', 'context_compaction'].includes(value?.type))
|
|
14
|
+
return { type: value.type, id: value.id };
|
|
15
|
+
// Tool outputs may contain JSON-serialized media instead of a content array.
|
|
16
|
+
if (key === 'output' && typeof value === 'string' && /"(?:encrypted_content|inline_data|inlineData)"|"type"\\s*:\\s*"(?:image|input_image|output_image|image_url|input_audio|audio|audio_url|input_video|video|video_url)"/.test(value)) {
|
|
17
|
+
try { const parsed = JSON.parse(value); if (parsed && typeof parsed === 'object') return parsed; } catch {}
|
|
18
|
+
}
|
|
19
|
+
return value;
|
|
20
|
+
});
|
|
21
|
+
const diagnosticRequest = JSON.parse(diagnosticJson);
|
|
22
|
+
info.responsesComposition = measureResponsesComposition(diagnosticRequest, inputWasString, originalInputString, inputWasString ? [] : diagnosticRequest.input);
|
|
23
|
+
info.responsesComposition.excludedBytes = Math.max(0, new TextEncoder().encode(diagnosticOriginal).length - new TextEncoder().encode(diagnosticJson).length);
|
|
24
|
+
info.responsesComposition.partial = diagnosticJson !== diagnosticOriginal;`;
|
|
25
|
+
|
|
26
|
+
export function patchPxpipeSource(source, version) {
|
|
27
|
+
if (version !== "0.14.0") throw new Error(`Review the pxpipe diagnostic patch before using version ${version}`);
|
|
28
|
+
if (source.includes(replacement)) return source;
|
|
29
|
+
if (source.split(original).length !== 2) throw new Error("pxpipe diagnostic patch target changed");
|
|
30
|
+
return source.replace(original, replacement);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function patchPxpipe() {
|
|
34
|
+
const entry = fileURLToPath(import.meta.resolve("pxpipe-proxy"));
|
|
35
|
+
const manifest = JSON.parse(readFileSync(resolve(dirname(entry), "../../package.json"), "utf8"));
|
|
36
|
+
const file = resolve(dirname(entry), "openai.js");
|
|
37
|
+
const source = readFileSync(file, "utf8");
|
|
38
|
+
const patched = patchPxpipeSource(source, manifest.version);
|
|
39
|
+
if (patched !== source) {
|
|
40
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
41
|
+
try { writeFileSync(temporary, patched); renameSync(temporary, file); }
|
|
42
|
+
finally { rmSync(temporary, { force: true }); }
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) patchPxpipe();
|
package/src/index.js
CHANGED
|
@@ -73,6 +73,7 @@ ${bold("PROXY OPTIONS (start/up/restart proxy):")}
|
|
|
73
73
|
${gray("--interceptor <file.mjs>")} JavaScript hooks loaded at startup; quote paths with spaces
|
|
74
74
|
${gray("--preset <name>")} pxpipe | headroom | rtk | headroom-pxpipe | rtk-pxpipe |
|
|
75
75
|
rtk-headroom-pxpipe | none (fresh default: none)
|
|
76
|
+
pxpipe runs in up to 2 persistent workers; excluded models skip the queue
|
|
76
77
|
${gray("--headroom-url <url>")} Headroom service (default: http://127.0.0.1:8787)
|
|
77
78
|
${gray("--rtk-filter <name>")} Fixed rtk pipe filter; --rtk-filter= restores auto-detection
|
|
78
79
|
${gray("--max-body-bytes <num>")} Positive integer; buffered request / WebSocket limit
|
package/src/proxy-presets.js
CHANGED
|
@@ -4,6 +4,7 @@ import zlib from "node:zlib";
|
|
|
4
4
|
import { performance } from "node:perf_hooks";
|
|
5
5
|
import { tokenStage } from "./proxy-stats.js";
|
|
6
6
|
import { requestImages } from "./request-images.js";
|
|
7
|
+
import { createPxpipePool } from "./pxpipe-pool.js";
|
|
7
8
|
|
|
8
9
|
// Fixed recipes; the user's --interceptor runs afterwards and can inspect/edit the result.
|
|
9
10
|
const PRESETS = ["none", "pxpipe", "headroom", "rtk", "headroom-pxpipe", "rtk-pxpipe", "rtk-headroom-pxpipe"];
|
|
@@ -79,12 +80,13 @@ function rtkPipe(text, filter, limit) {
|
|
|
79
80
|
|
|
80
81
|
export async function createPresetHooks(config, onStats = () => {}) {
|
|
81
82
|
if (!config.preset || config.preset === "none") return {};
|
|
82
|
-
const { countTokens: tokenize } = await import("gpt-tokenizer/encoding/o200k_base");
|
|
83
|
+
const { countTokens: tokenize } = config.preset.startsWith("rtk") ? await import("gpt-tokenizer/encoding/o200k_base") : {};
|
|
83
84
|
function countTokens(text) {
|
|
84
85
|
try { return tokenize(text, { disallowedSpecial: new Set() }); }
|
|
85
86
|
catch { return NaN; } // Observability must not reject an otherwise valid request.
|
|
86
87
|
}
|
|
87
|
-
const px = config.preset.includes("pxpipe") ? await import("pxpipe-proxy") : null;
|
|
88
|
+
const px = config.preset.includes("pxpipe") ? await import("pxpipe-proxy/applicability") : null;
|
|
89
|
+
const pool = px ? createPxpipePool(config.maxBodyBytes) : null;
|
|
88
90
|
const models = config.models?.split(",");
|
|
89
91
|
const wsModels = new WeakMap();
|
|
90
92
|
const warnedEncodings = new Set();
|
|
@@ -139,6 +141,7 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
139
141
|
const bypassPxpipe = px && config.pxpipeNativeImages === "bypass" && requestImages(body, { identities: false }).length > 0;
|
|
140
142
|
let changed = false;
|
|
141
143
|
const stages = [];
|
|
144
|
+
let pxpipeTimings = {};
|
|
142
145
|
const report = error => {
|
|
143
146
|
// Observability must never interrupt proxy traffic; no request bodies are passed to the recorder.
|
|
144
147
|
// Optional correlation only; never pass headers or bodies to the recorder.
|
|
@@ -154,7 +157,7 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
154
157
|
} catch {}
|
|
155
158
|
try {
|
|
156
159
|
const update = onStats({ model, preset: config.preset, transport: websocket ? "WS" : "HTTP", changed, stages, error,
|
|
157
|
-
timings: { presetMs: Math.round((performance.now() - started) * 10) / 10 },
|
|
160
|
+
timings: { presetMs: Math.round((performance.now() - started) * 10) / 10, ...pxpipeTimings },
|
|
158
161
|
...source, ...(requestId ? { requestId } : {}) });
|
|
159
162
|
// ponytail: WS measures presets only; response timings need per-response-ID correlation.
|
|
160
163
|
if (!websocket && typeof update === "function") context.updateTiming = update;
|
|
@@ -187,28 +190,14 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
187
190
|
stages.push(tokenStage("pxpipe", 0, 0, false, "native_images_present", "pxpipe_estimate"));
|
|
188
191
|
} else if (px && (models ? models.some(m => m.endsWith("*") ? model.startsWith(m.slice(0, -1)) : model === m) : px.isPxpipeSupportedModel(model) || px.isPxpipeSupportedGptModel(model))) {
|
|
189
192
|
const bytes = Buffer.from(JSON.stringify({ ...body, model }));
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
if (!Number.isFinite(before) || !Number.isFinite(after)) {
|
|
199
|
-
// Anthropic's transformer lacks token totals: count text locally and include newly rendered images.
|
|
200
|
-
const textTokens = value => countTokens(JSON.stringify(value, (key, item) =>
|
|
201
|
-
["image", "input_image", "image_url"].includes(item?.type) || key === "encrypted_content" ? undefined : item));
|
|
202
|
-
before = textTokens(JSON.parse(bytes));
|
|
203
|
-
let imageTokens;
|
|
204
|
-
try { imageTokens = info.imageDims?.reduce((sum, d) => sum + px.openAIVisionTokens(model, d.width, d.height), 0); } catch {}
|
|
205
|
-
after = Number.isFinite(imageTokens) ? textTokens(JSON.parse(Buffer.from(result.body))) + imageTokens : undefined;
|
|
206
|
-
method = "o200k_and_vision_estimate";
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
stages.push(tokenStage("pxpipe", before, after, Boolean(info.compressed),
|
|
210
|
-
info.compressed ? "applied" : String(info.reason || "unchanged").split(/[^a-z_]/i)[0].slice(0, 40), method));
|
|
211
|
-
if (result.info?.compressed) {
|
|
193
|
+
let sessionId;
|
|
194
|
+
try { sessionId = JSON.parse(context.headers?.["x-codex-turn-metadata"] || "{}").session_id; } catch {}
|
|
195
|
+
const result = await pool.run({ body: bytes, format, model }, {
|
|
196
|
+
sessionId: typeof sessionId === "string" ? sessionId : undefined, signal: context.signal,
|
|
197
|
+
});
|
|
198
|
+
pxpipeTimings = Object.fromEntries(Object.entries(result.timings).map(([key, value]) => [key, Math.round(value * 10) / 10]));
|
|
199
|
+
stages.push(result.stage);
|
|
200
|
+
if (result.stage.applied) {
|
|
212
201
|
const transformed = JSON.parse(Buffer.from(result.body).toString("utf8"));
|
|
213
202
|
if (!Object.hasOwn(body, "model")) delete transformed.model;
|
|
214
203
|
// Only replace the AI request, preserving a WebSocket event's outer fields.
|
|
@@ -222,10 +211,11 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
222
211
|
const output = changed ? Buffer.from(JSON.stringify(envelope)) : raw;
|
|
223
212
|
report(false);
|
|
224
213
|
return output;
|
|
225
|
-
} catch (error) { report(
|
|
214
|
+
} catch (error) { report(!context.signal?.aborted); throw error; }
|
|
226
215
|
}
|
|
227
216
|
|
|
228
217
|
return {
|
|
218
|
+
close: () => pool?.close(),
|
|
229
219
|
async onRequest(context) {
|
|
230
220
|
const started = performance.now();
|
|
231
221
|
if (context.method !== "POST" || !/\bapplication\/(?:[\w.-]+\+)?json\b/i.test(String(context.headers["content-type"] || ""))) return;
|
package/src/proxy.js
CHANGED
|
@@ -4,7 +4,7 @@ import { resolve } from "node:path";
|
|
|
4
4
|
import { pathToFileURL } from "node:url";
|
|
5
5
|
import { Transform } from "node:stream";
|
|
6
6
|
import { pipeline } from "node:stream/promises";
|
|
7
|
-
import { performance } from "node:perf_hooks";
|
|
7
|
+
import { performance, monitorEventLoopDelay } from "node:perf_hooks";
|
|
8
8
|
import WebSocket, { WebSocketServer } from "ws";
|
|
9
9
|
import { normalizePresetOptions, createPresetHooks } from "./proxy-presets.js";
|
|
10
10
|
|
|
@@ -82,8 +82,16 @@ export async function startProxy(options) {
|
|
|
82
82
|
for (const name of HOOKS) {
|
|
83
83
|
if (hooks[name] !== undefined && typeof hooks[name] !== "function") throw new TypeError(`${name} must be a function`);
|
|
84
84
|
}
|
|
85
|
-
const
|
|
85
|
+
const loopDelay = monitorEventLoopDelay({ resolution: 20 });
|
|
86
|
+
loopDelay.enable();
|
|
87
|
+
const preset = await createPresetHooks(config, event => {
|
|
88
|
+
// Process-wide maximum since the preceding preset event; never a request CPU duration.
|
|
89
|
+
event.timings.eventLoopLagMs = Math.max(0, Math.round((loopDelay.max / 1e6 - 20) * 10) / 10);
|
|
90
|
+
loopDelay.reset();
|
|
91
|
+
return options.onStats?.(event);
|
|
92
|
+
}).catch(error => { loopDelay.disable(); throw error; });
|
|
86
93
|
for (const [name, hook] of Object.entries(preset)) {
|
|
94
|
+
if (name === "close") continue;
|
|
87
95
|
const custom = hooks[name];
|
|
88
96
|
hooks[name] = async context => { await hook(context); await custom?.(context); };
|
|
89
97
|
}
|
|
@@ -174,6 +182,7 @@ export async function startProxy(options) {
|
|
|
174
182
|
let finished = false;
|
|
175
183
|
let failed = false;
|
|
176
184
|
const timings = { state: "waiting" };
|
|
185
|
+
const cancellation = new AbortController();
|
|
177
186
|
const elapsed = since => Math.round((performance.now() - since) * 10) / 10;
|
|
178
187
|
const publishTiming = () => {
|
|
179
188
|
// Optional recorder updater: never emit a second preset event or disrupt traffic.
|
|
@@ -189,12 +198,14 @@ export async function startProxy(options) {
|
|
|
189
198
|
const failRequest = error => { failed = true; fail(response, error); };
|
|
190
199
|
response.once("finish", () => finishTiming(failed ? "error" : "completed"));
|
|
191
200
|
response.once("close", () => {
|
|
201
|
+
cancellation.abort();
|
|
192
202
|
finishTiming(failed ? "error" : "aborted");
|
|
193
203
|
upstream?.destroy();
|
|
194
204
|
});
|
|
195
205
|
request.on("error", error => { upstream?.destroy(); failRequest(error); });
|
|
196
206
|
try {
|
|
197
207
|
context = requestContext(request);
|
|
208
|
+
context.signal = cancellation.signal;
|
|
198
209
|
if (hooks.onRequest) {
|
|
199
210
|
context.body = await readBody(request, config.maxBodyBytes);
|
|
200
211
|
await hooks.onRequest(context);
|
|
@@ -263,6 +274,9 @@ export async function startProxy(options) {
|
|
|
263
274
|
socket.once("close", () => { if (!client) upstream?.terminate(); });
|
|
264
275
|
try {
|
|
265
276
|
const context = requestContext(request);
|
|
277
|
+
const cancellation = new AbortController();
|
|
278
|
+
context.signal = cancellation.signal;
|
|
279
|
+
socket.once("close", () => cancellation.abort());
|
|
266
280
|
const headers = headersForHop(context.headers);
|
|
267
281
|
for (const name of Object.keys(headers)) if (name.startsWith("sec-websocket-")) delete headers[name];
|
|
268
282
|
headers.host = target.host;
|
|
@@ -336,17 +350,21 @@ export async function startProxy(options) {
|
|
|
336
350
|
server.off("error", reject);
|
|
337
351
|
resolveListen();
|
|
338
352
|
});
|
|
339
|
-
});
|
|
353
|
+
}).catch(async error => { loopDelay.disable(); wsServer.close(); await preset.close?.(); throw error; });
|
|
340
354
|
const address = server.address();
|
|
341
355
|
const url = `http://${address.family === "IPv6" ? `[${address.address}]` : address.address}:${address.port}`;
|
|
356
|
+
let closing;
|
|
342
357
|
return {
|
|
343
358
|
url,
|
|
344
|
-
close: () =>
|
|
359
|
+
close: () => {
|
|
360
|
+
loopDelay.disable();
|
|
361
|
+
return closing ||= Promise.all([preset.close?.(), new Promise((resolveClose, reject) => {
|
|
345
362
|
for (const ws of upstreamSockets) ws.terminate();
|
|
346
363
|
for (const ws of wsServer.clients) ws.terminate();
|
|
347
364
|
for (const socket of connections) socket.destroy();
|
|
348
365
|
wsServer.close();
|
|
349
366
|
server.close(error => error ? reject(error) : resolveClose());
|
|
350
|
-
|
|
367
|
+
})]).then(() => undefined);
|
|
368
|
+
},
|
|
351
369
|
};
|
|
352
370
|
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { Worker } from "node:worker_threads";
|
|
2
|
+
import { performance } from "node:perf_hooks";
|
|
3
|
+
|
|
4
|
+
export function createPxpipePool(maxBodyBytes = 64 * 1024 * 1024, workerUrl = new URL("./pxpipe-thread.js", import.meta.url)) {
|
|
5
|
+
// The standalone CLI embeds a separate bundle: runtime relative files do not exist there.
|
|
6
|
+
if (typeof AIH_PXPIPE_THREAD_SOURCE !== "undefined") workerUrl = new URL(`data:text/javascript,${encodeURIComponent(AIH_PXPIPE_THREAD_SOURCE)}`);
|
|
7
|
+
const slots = Array.from({ length: 2 }, () => ({ worker: null, ready: false, job: null, queue: [] }));
|
|
8
|
+
let closed = false, sequence = 0, queuedBytes = 0;
|
|
9
|
+
const pendingTerminations = new Set();
|
|
10
|
+
const terminate = slot => {
|
|
11
|
+
const worker = slot.worker;
|
|
12
|
+
slot.worker = null;
|
|
13
|
+
slot.ready = false;
|
|
14
|
+
if (!worker) return;
|
|
15
|
+
const termination = worker.terminate();
|
|
16
|
+
pendingTerminations.add(termination);
|
|
17
|
+
termination.then(() => pendingTerminations.delete(termination), () => pendingTerminations.delete(termination));
|
|
18
|
+
};
|
|
19
|
+
const settle = (job, error, result) => {
|
|
20
|
+
job.signal?.removeEventListener("abort", job.abort);
|
|
21
|
+
if (error) job.reject(error); else job.resolve(result);
|
|
22
|
+
};
|
|
23
|
+
function dispatch(slot) {
|
|
24
|
+
if (closed || slot.job || !slot.queue.length) return;
|
|
25
|
+
if (!slot.worker) {
|
|
26
|
+
try { start(slot); } catch (error) { fail(slot, error); return; }
|
|
27
|
+
}
|
|
28
|
+
if (!slot.ready) return;
|
|
29
|
+
const job = slot.queue.shift();
|
|
30
|
+
queuedBytes -= job.bytes;
|
|
31
|
+
slot.job = job;
|
|
32
|
+
job.queueMs = performance.now() - job.queuedAt;
|
|
33
|
+
slot.worker.ref();
|
|
34
|
+
try { slot.worker.postMessage({ ...job.input, id: job.id }); }
|
|
35
|
+
catch (error) { fail(slot, error); }
|
|
36
|
+
}
|
|
37
|
+
function fail(slot, error) {
|
|
38
|
+
if (slot.job) settle(slot.job, error);
|
|
39
|
+
slot.job = null;
|
|
40
|
+
// A worker failing to initialize must reject its queue rather than restart endlessly.
|
|
41
|
+
for (const job of slot.queue.splice(0)) { queuedBytes -= job.bytes; settle(job, error); }
|
|
42
|
+
terminate(slot);
|
|
43
|
+
}
|
|
44
|
+
function start(slot) {
|
|
45
|
+
const worker = slot.worker = new Worker(workerUrl, { execArgv: [] });
|
|
46
|
+
worker.on("message", result => {
|
|
47
|
+
if (slot.worker !== worker) return;
|
|
48
|
+
if (result.ready) { slot.ready = true; if (!slot.queue.length) worker.unref(); dispatch(slot); return; }
|
|
49
|
+
const job = slot.job;
|
|
50
|
+
if (!job || result.id !== job.id) return fail(slot, new Error("Unexpected pxpipe worker response"));
|
|
51
|
+
slot.job = null;
|
|
52
|
+
worker.unref();
|
|
53
|
+
if (result.error) settle(job, new Error(result.error));
|
|
54
|
+
else settle(job, null, { ...result, timings: { ...result.timings, pxpipeQueueMs: job.queueMs } });
|
|
55
|
+
dispatch(slot);
|
|
56
|
+
});
|
|
57
|
+
worker.on("error", error => { if (slot.worker === worker) fail(slot, error); });
|
|
58
|
+
worker.on("exit", code => { if (slot.worker === worker) fail(slot, new Error(`pxpipe worker exited (${code})`)); });
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
run(input, { sessionId, signal } = {}) {
|
|
62
|
+
if (closed) return Promise.reject(new Error("pxpipe pool is closed"));
|
|
63
|
+
if (signal?.aborted) return Promise.reject(signal.reason);
|
|
64
|
+
if (slots.reduce((n, slot) => n + slot.queue.length, 0) >= 32 || queuedBytes + input.body.byteLength > maxBodyBytes)
|
|
65
|
+
return Promise.reject(Object.assign(new Error("pxpipe queue is full"), { statusCode: 503 }));
|
|
66
|
+
// ponytail: fixed session affinity preserves caches; two busy sessions can share a lane.
|
|
67
|
+
let hash = 0;
|
|
68
|
+
for (const char of sessionId || "") hash = (Math.imul(hash, 31) + char.charCodeAt(0)) >>> 0;
|
|
69
|
+
const slot = sessionId ? slots[hash % slots.length]
|
|
70
|
+
: slots.reduce((best, current) => current.queue.length + Boolean(current.job) < best.queue.length + Boolean(best.job) ? current : best);
|
|
71
|
+
return new Promise((resolve, reject) => {
|
|
72
|
+
const job = { id: ++sequence, input, resolve, reject, signal, bytes: input.body.byteLength, queuedAt: performance.now() };
|
|
73
|
+
job.abort = () => {
|
|
74
|
+
if (slot.job === job) { slot.job = null; terminate(slot); }
|
|
75
|
+
else { const index = slot.queue.indexOf(job); if (index < 0) return; slot.queue.splice(index, 1); queuedBytes -= job.bytes; }
|
|
76
|
+
settle(job, signal.reason);
|
|
77
|
+
dispatch(slot);
|
|
78
|
+
};
|
|
79
|
+
signal?.addEventListener("abort", job.abort, { once: true });
|
|
80
|
+
slot.queue.push(job);
|
|
81
|
+
queuedBytes += job.bytes;
|
|
82
|
+
dispatch(slot);
|
|
83
|
+
});
|
|
84
|
+
},
|
|
85
|
+
async close() {
|
|
86
|
+
closed = true;
|
|
87
|
+
for (const slot of slots) fail(slot, new Error("pxpipe pool is closed"));
|
|
88
|
+
await Promise.allSettled([...pendingTerminations]);
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { parentPort } from "node:worker_threads";
|
|
2
|
+
import { performance } from "node:perf_hooks";
|
|
3
|
+
import { countTokens } from "gpt-tokenizer/encoding/o200k_base";
|
|
4
|
+
import * as px from "pxpipe-proxy";
|
|
5
|
+
import { tokenStage } from "./proxy-stats.js";
|
|
6
|
+
|
|
7
|
+
parentPort.on("message", async ({ id, body, format, model }) => {
|
|
8
|
+
const started = performance.now();
|
|
9
|
+
const cpu = process.threadCpuUsage?.();
|
|
10
|
+
try {
|
|
11
|
+
const result = await (format === "anthropic" ? px.transformRequest(body, { model })
|
|
12
|
+
: format === "chat" ? px.transformOpenAIChatCompletions(body, { model }) : px.transformOpenAIResponses(body, { model }));
|
|
13
|
+
const info = result.info || {};
|
|
14
|
+
let before = 0, after = 0, method = "pxpipe_estimate";
|
|
15
|
+
if (info.compressed) {
|
|
16
|
+
before = info.baselineImagedTokens;
|
|
17
|
+
after = Number.isFinite(info.imageTokens) ? info.imageTokens + (info.nativeInjectedTokens ?? 0) : undefined;
|
|
18
|
+
if (!Number.isFinite(before) || !Number.isFinite(after)) {
|
|
19
|
+
const textTokens = value => {
|
|
20
|
+
try { return countTokens(JSON.stringify(value, (key, item) =>
|
|
21
|
+
["image", "input_image", "output_image", "image_url"].includes(item?.type) || key === "encrypted_content" ? undefined : item), { disallowedSpecial: new Set() }); }
|
|
22
|
+
catch { return NaN; }
|
|
23
|
+
};
|
|
24
|
+
before = textTokens(JSON.parse(Buffer.from(body)));
|
|
25
|
+
let imageTokens;
|
|
26
|
+
try { imageTokens = info.imageDims?.reduce((sum, d) => sum + px.openAIVisionTokens(model, d.width, d.height), 0); } catch {}
|
|
27
|
+
after = Number.isFinite(imageTokens) ? textTokens(JSON.parse(Buffer.from(result.body))) + imageTokens : undefined;
|
|
28
|
+
method = "o200k_and_vision_estimate";
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
const stage = tokenStage("pxpipe", before, after, Boolean(info.compressed),
|
|
32
|
+
info.compressed ? "applied" : String(info.reason || "unchanged").split(/[^a-z_]/i)[0].slice(0, 40), method);
|
|
33
|
+
if (info.responsesComposition) stage.diagnostics = {
|
|
34
|
+
partial: Boolean(info.responsesComposition.partial), excludedBytes: info.responsesComposition.excludedBytes ?? 0,
|
|
35
|
+
};
|
|
36
|
+
const output = info.compressed ? Uint8Array.from(result.body) : undefined;
|
|
37
|
+
const usage = cpu && process.threadCpuUsage(cpu);
|
|
38
|
+
parentPort.postMessage({ id, body: output, stage, timings: {
|
|
39
|
+
pxpipeMs: performance.now() - started,
|
|
40
|
+
...(usage ? { pxpipeCpuMs: (usage.user + usage.system) / 1000 } : {}),
|
|
41
|
+
} }, output ? [output.buffer] : []);
|
|
42
|
+
} catch (error) {
|
|
43
|
+
parentPort.postMessage({ id, error: error.message });
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
parentPort.postMessage({ ready: true });
|
package/src/tui.js
CHANGED
|
@@ -393,6 +393,11 @@ export class Dashboard {
|
|
|
393
393
|
...(event.error ? [] : [savedTokens(unmeasured ? null : event.saved) + (partial && !unmeasured ? yellow(" (parziale)") : "")]),
|
|
394
394
|
...(timing ? [
|
|
395
395
|
`proxy: ${duration(timing.presetMs)}`,
|
|
396
|
+
...(Number.isFinite(timing.pxpipeQueueMs) ? [
|
|
397
|
+
`coda: ${duration(timing.pxpipeQueueMs)}`, `pxpipe: ${duration(timing.pxpipeMs)}`,
|
|
398
|
+
...(Number.isFinite(timing.pxpipeCpuMs) ? [`CPU: ${duration(timing.pxpipeCpuMs)}`] : []),
|
|
399
|
+
] : []),
|
|
400
|
+
...(Number.isFinite(timing.eventLoopLagMs) ? [`loop max: ${duration(timing.eventLoopLagMs)}`] : []),
|
|
396
401
|
...(event.transport === "HTTP" ? [
|
|
397
402
|
`header: ${duration(timing.upstreamHeadersMs)}`, `tot: ${duration(timing.totalMs)}`,
|
|
398
403
|
...(Number.isInteger(timing.statusCode) && timing.statusCode >= 100 && timing.statusCode <= 599
|