@drakonkat/ai-helper 1.1.0 → 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,273 @@
1
+ # Benchmark dei flow del proxy
2
+
3
+ Il benchmark confronta **gli stessi input** attraverso i preset reali `none`,
4
+ `headroom`, `rtk`, `pxpipe`, `headroom-pxpipe`, `rtk-pxpipe`. Non legge né azzera
5
+ le statistiche del proxy quotidiano e non cambia client, configurazioni o servizi.
6
+ `none` viene sempre aggiunto come baseline. Non sono implementate nuove pipeline
7
+ di produzione, né una doppia compressione RTK → Headroom.
8
+
9
+ ## Avvio rapido
10
+
11
+ Richiede Node.js compatibile con il progetto e dipendenze installate. Il runner
12
+ si esegue dal checkout con Node, non nel binario Bun compilato.
13
+
14
+ ```powershell
15
+ # Smoke test senza Headroom, RTK o provider esterni
16
+ npm run bench:proxy -- --presets none,pxpipe --formats responses --warmup 0 --repetitions 1
17
+
18
+ # Tutti i sei flow; Headroom deve essere già disponibile a questo indirizzo
19
+ npm run bench:proxy -- --headroom-url http://127.0.0.1:8787 --repetitions 5 --warmup 1
20
+
21
+ # Stessi casi Responses attraverso HTTP e WebSocket
22
+ npm run bench:proxy -- --presets none,rtk,pxpipe,rtk-pxpipe --formats responses --transports http,ws
23
+
24
+ # Elenca oppure esporta il corpus per modificarlo
25
+ npm run bench:proxy -- --list
26
+ npm run bench:proxy -- --formats responses --export-fixtures my-fixtures.json
27
+ npm run bench:proxy -- --fixtures my-fixtures.json --out benchmark-results/my-experiment
28
+
29
+ # Test automatici del sistema (nessuna chiamata a provider reali)
30
+ npm run test:benchmark
31
+ ```
32
+
33
+ RTK richiede un eseguibile con `rtk pipe` su PATH. Headroom usa esclusivamente
34
+ `POST /v1/compress`, in `lossy_inline`, con eventuale `HEADROOM_PROXY_TOKEN`.
35
+ Il runner non avvia/installa questi servizi: se mancano, registra **errori** per
36
+ i flow interessati, continua gli altri e termina con codice 2.
37
+ Le chiamate reali possono incrementare le metriche interne di Headroom/RTK e
38
+ scaldare le loro cache; restano invece isolate le statistiche del proxy aih gestito.
39
+
40
+ **Pxpipe nel benchmark è opt-in sui modelli del corpus**, anche se il gate di
41
+ default del proxy normale li escluderebbe. Questo serve a esercitare davvero i
42
+ flow con immagini: non è una garanzia di supporto o qualità del modello. Con
43
+ `--models` si può specificare l'allowlist esatta da testare; i `model_excluded`
44
+ rimangono visibili in `stageReasons`. Nessuna configurazione di produzione cambia.
45
+
46
+ `--rtk-filter` applica un filtro fisso a tutti i tool output: usarlo soltanto su
47
+ un corpus omogeneo compatibile. Senza flag viene usata l'autodetection.
48
+
49
+ ## Cosa viene misurato
50
+
51
+ ### Replay offline (default)
52
+
53
+ Ogni preset ha un proxy reale su una porta loopback effimera, con un collector
54
+ locale come upstream. Il collector osserva il payload effettivamente inoltrato.
55
+ Non vengono effettuate chiamate LLM. Headroom, se selezionato, riceve i testi da
56
+ comprimere: un `--headroom-url` remoto comporta l'invio a quel servizio.
57
+
58
+ Il corpus integrato contiene **30 fixture sintetiche**, 10 scenari per Responses,
59
+ Chat Completions e Anthropic Messages: build, test, stack trace, log, grep, git,
60
+ JSON, output breve e contesto statico denso. Non contiene dati di lavoro reali.
61
+
62
+ - Ordine di casi e flow randomizzato con seed riproducibile.
63
+ - Default: 1 round di warmup e 3 misurati per caso/flow/trasporto.
64
+ - Warmup conservati nei record ma esclusi dalle aggregazioni.
65
+ - HTTP misura il round-trip fino al collector, inclusa la trasformazione.
66
+ - WS usa una nuova connessione per campione Responses e misura separatamente
67
+ handshake (`connectionMs`) e round-trip del messaggio (`durationMs`).
68
+ - `firstRequest` identifica la prima richiesta al proxy del benchmark, **non**
69
+ un vero avvio a freddo di RTK, Headroom, librerie o cache del provider.
70
+ - `meta.startup` misura l'inizializzazione dei proxy. Non equivale al tempo di
71
+ avvio di processi esterni; per misurarlo serve una campagna separata controllata.
72
+
73
+ I risultati sono separati per **modello, protocollo e trasporto**, anche per
74
+ categoria nel JSON. Headroom riceve solo tool text per Responses, ma i messaggi
75
+ per Chat/Messages: non bisogna confrontare percentuali di scope diversi.
76
+
77
+ ### Conteggio uniforme
78
+
79
+ I conteggi dichiarati da Headroom/RTK/pxpipe sono conservati in `stages` soltanto
80
+ come diagnostica. La metrica comune viene ricalcolata prima e dopo il proxy:
81
+
82
+ - testo e struttura JSON canonica: tokenizer `o200k_base` identico per ogni flow;
83
+ - tool text: conteggio separato dei soli risultati testuali;
84
+ - immagini PNG: dimensioni IHDR e profilo vision della versione pxpipe installata
85
+ per famiglie OpenAI riconosciute con detail esplicito `high`/`original`;
86
+ - base64, dati cifrati e media non vengono conteggiati come testo;
87
+ - modello/dettaglio/formato immagine non misurabile, media opachi o resize non
88
+ modellato ⇒ totale **null / sconosciuto**, mai zero. `knownTokens` è soltanto
89
+ il subtotale noto della stima locale, non una garanzia sul consumo del provider.
90
+
91
+ Questi sono **token stimati**, non l'esatta serializzazione del provider né una
92
+ fattura. Per le immagini Anthropic/Gemini non viene inventato un costo OpenAI.
93
+ Il trasferimento di testo in immagini non è considerato un risparmio totale del
94
+ 100%: `toolText` resta diagnostico, mentre il totale include il costo vision o è
95
+ sconosciuto. `imageMeasurements` e `warnings` spiegano le approssimazioni.
96
+
97
+ La percentuale aggregata è ponderata:
98
+
99
+ ```text
100
+ 100 × (somma token prima − somma token dopo) / somma token prima
101
+ ```
102
+
103
+ Non è la media delle percentuali. Errori, output invariati, risparmi negativi e
104
+ costi sconosciuti rimangono visibili. La copertura indica quante richieste hanno
105
+ un confronto completo; un totale parziale non può vincere la selezione automatica.
106
+
107
+ ### Qualità offline
108
+
109
+ Ogni fixture dichiara fatti che devono sopravvivere: codice di errore, file/riga,
110
+ valori JSON, identificatore del test, ecc. Vengono controllati anche modello,
111
+ nomi dei tool e coppie call/result native presenti nell'originale.
112
+
113
+ Gli esiti sono `pass`, `fail`, `indeterminate`, `unscored`. Se un fatto non è più
114
+ testo ma potrebbero contenerlo le immagini, l'esito è `indeterminate`: nessun OCR
115
+ o modello ha verificato che sia leggibile. Il runner **non dichiara un vincitore
116
+ di qualità sulla base del solo replay offline**. La presenza delle stringhe è
117
+ un controllo di conservazione, non una prova di comprensione o correttezza.
118
+
119
+ ## Valutazione live, esplicita e potenzialmente a pagamento
120
+
121
+ ### GPT-6 Astra e Fable 5.1 sullo stesso corpus
122
+
123
+ Il comando dedicato seleziona gli ID del gateway `gpt-6-astra` e
124
+ `anthropic/claude-fable-5-1`, sul medesimo protocollo Responses:
125
+
126
+ ```powershell
127
+ # Replay offline: 20 fixture × 6 flow = 120 campioni
128
+ npm run bench:models -- --repetitions 1 --warmup 0
129
+
130
+ # Smoke live: al massimo 120 chiamate complessive, senza retry
131
+ npm run bench:models -- --live --upstream http://127.0.0.1:10100 --repetitions 1 --warmup 0 --max-live-calls 120
132
+ ```
133
+
134
+ Richiede un gateway che supporti **entrambi i modelli via Responses**; un endpoint
135
+ Anthropic diretto non accetta questa combinazione. `--compare-models` permette
136
+ altre liste ed è distinto da `--models`, che controlla solo l'allowlist pxpipe.
137
+ I report mantengono baseline, latenza, qualità e usage **separati per modello**;
138
+ il limite chiamate si applica all'intera matrice, non a ciascun modello.
139
+
140
+ I costi vision locali per questi modelli non vengono ricavati arbitrariamente
141
+ da profili più vecchi: dove non supportati restano sconosciuti. La misura di
142
+ riferimento nel test live è l'usage restituito dal gateway/provider.
143
+
144
+ ### Endpoint e credenziali
145
+
146
+ ```powershell
147
+ # Impostare BENCH_API_KEY nell'ambiente, senza inserirla nella command line.
148
+ # L'upstream è la radice PRIMA di /v1: il percorso viene dalla fixture.
149
+ npm run bench:proxy -- --live --upstream http://127.0.0.1:10100 --api-key-env BENCH_API_KEY --formats responses --model gpt-5.5 --repetitions 3 --warmup 0
150
+ ```
151
+
152
+ Scegliere un modello effettivamente supportato dal proprio upstream. Per un
153
+ endpoint Anthropic usare `--formats anthropic` e un modello Anthropic. Un corpus
154
+ multiformato live richiede un upstream che accetti tutti i protocolli selezionati.
155
+ Le credenziali sono opzionali per gateway locali che non le richiedono; non
156
+ vengono mai cercate automaticamente negli account o nei file dell'utente.
157
+
158
+ Il collector inoltra al provider **il payload realmente trasformato dal proxy**.
159
+ Ogni fixture pone una domanda con risposta nota contenuta nel tool output;
160
+ `answerChecks` valuta la risposta reale. I report includono:
161
+
162
+ - qualità della risposta per campione e tasso di pass;
163
+ - durata totale proxy + collector + provider, e durata del solo provider;
164
+ - input/output/cache read/cache write/reasoning dichiarati dal provider;
165
+ - risposta completa o troncata, tool aggiuntivi richiesti dal modello.
166
+
167
+ Per Anthropic l'input normalizzato comprende input non-cached + letture/scritture
168
+ cache, evitando di confrontare scope diversi. Campi non restituiti restano null.
169
+ Streaming viene disabilitato, le Responses hanno `store: false` e `background: false`,
170
+ Chat usa una singola completion, e le risposte
171
+ sono limitate da `--max-output-tokens` (default 256). Vengono utilizzati bearer
172
+ auth per OpenAI-compatible e `x-api-key` per Anthropic; redirect sono bloccati.
173
+
174
+ **Non è un agente autonomo:** nessun tool viene eseguito, nessun retry o follow-up
175
+ automatico. Tool richiesti e risposte incomplete squalificano il candidato. La
176
+ modalità live accetta solo definizioni di tool function/client, non tool eseguiti
177
+ dal provider come web search o code interpreter. La
178
+ qualità misurata riguarda queste domande/fixture, non una completa attività di
179
+ coding. Per valutare task agentici servono sessioni controllate con repository
180
+ identico, test di accettazione e conteggio di tutte le riletture/retry; questo
181
+ runner non pretende di coprirli.
182
+
183
+ Warmup live **consumano token**. Il numero massimo pianificato di chiamate è:
184
+
185
+ ```text
186
+ casi applicabili × flow (incluso none) × (warmup + repetitions)
187
+ ```
188
+
189
+ Il numero viene mostrato prima delle chiamate; `--max-live-calls` (default 200)
190
+ blocca piani più grandi prima di inviare richieste. Per una campagna più ampia,
191
+ aumentare esplicitamente questo limite oppure ridurre corpus/rounds.
192
+
193
+ Non c'è controllo della cache remota: fissare modello/versioni/configurazioni e
194
+ ripetere le campagne. Ordine randomizzato riduce, ma non elimina, il bias della
195
+ cache e del carico. Una richiesta annullata può comunque essere fatturata senza
196
+ restituire usage: i report non rappresentano una fattura completa. L'abort del
197
+ campione viene propagato alla fetch del provider; non è una garanzia che il
198
+ provider interrompa il proprio lavoro.
199
+
200
+ ## Fixture proprie
201
+
202
+ Esportare il corpus è il modo più semplice per partire. Il file deve essere un
203
+ array JSON di richieste standalone, già sanificate, senza header o credenziali.
204
+ Esempio minimo:
205
+
206
+ ```json
207
+ [
208
+ {
209
+ "id": "incident-01",
210
+ "category": "logs",
211
+ "format": "responses",
212
+ "path": "/v1/responses",
213
+ "body": {
214
+ "model": "gpt-5.5",
215
+ "input": [
216
+ {"type":"function_call","call_id":"c1","name":"read_log","arguments":"{}"},
217
+ {"type":"function_call_output","call_id":"c1","output":"INFO ready\nERROR E_QUEUE_FULL at worker.ts:18"},
218
+ {"role":"user","content":"Return the error code and source location."}
219
+ ]
220
+ },
221
+ "checks": {"toolIncludes":["E_QUEUE_FULL","worker.ts:18"]},
222
+ "answerChecks": {"includes":["E_QUEUE_FULL","worker.ts:18"],"excludes":["no errors"]}
223
+ }
224
+ ]
225
+ ```
226
+
227
+ `checks.toolIncludes` cerca solo nei risultati dei tool; `requestIncludes` nel
228
+ testo nativo della richiesta. Le stringhe devono esistere già nell'originale.
229
+ `answerChecks.includes/excludes` sono confronti letterali case-sensitive, non un
230
+ LLM judge; non inserire le risposte nella domanda. Omettere `answerChecks` lascia
231
+ la risposta non valutata, e impedisce una raccomandazione live. Le fixture
232
+ integrate includono definizioni/coppie dei tool complete; rispettare i vincoli
233
+ del proprio provider nelle fixture personalizzate. Non usare riferimenti a
234
+ stato remoto (`previous_response_id`) per un confronto standalone riproducibile.
235
+
236
+ ## Report e decisioni
237
+
238
+ Ogni esecuzione crea una directory nuova, normalmente sotto `benchmark-results/`
239
+ (gitignored), senza sovrascrivere run precedenti:
240
+
241
+ - `report.md`: riepilogo leggibile e candidati;
242
+ - `report.json`: manifest/versioni/hash, tutti i campioni, aggregazioni e decisioni;
243
+ - `results.csv`: righe importabili in fogli di calcolo;
244
+ - `records.jsonl`: append progressivo, disponibile anche dopo un'interruzione.
245
+
246
+ Non vengono salvati prompt/output/credenziali di default; i valori attesi delle
247
+ asserzioni sono sostituiti con hash. Gli identificatori delle fixture/modelli e
248
+ gli endpoint configurati restano nel manifest: evitare segreti nei nomi/path.
249
+ `--save-payloads` abilita esplicitamente una sottodirectory con originali,
250
+ trasformati e risposte live, utile per ispezionare le regressioni e potenzialmente
251
+ **sensibile**. Non caricarla automaticamente su servizi esterni.
252
+
253
+ La selezione considera solo run live completi, campioni abbinati alla baseline,
254
+ senza errori, con usage completo e risposte valutate/complete. Soglie configurabili:
255
+
256
+ - `--max-quality-drop 0`: nessuna diminuzione ammessa del pass rate (punti percentuali);
257
+ - `--max-latency-regression 25`: aumento massimo del p95 rispetto a `none` (%).
258
+
259
+ Tra i candidati ammissibili, la **frontiera di Pareto** elenca quelli non dominati
260
+ su risparmio input dichiarato dal provider, p95 e pass rate. Non sceglie un peso
261
+ arbitrario tra qualità e velocità, non equipara token risparmiati a denaro e non
262
+ afferma significatività statistica. Con pochi campioni usare i risultati come
263
+ segnale esplorativo, poi aumentare corpus/ripetizioni e verificare le regressioni.
264
+
265
+ Il manifest registra seed, hash corpus, versioni locali di Node/RTK/pxpipe/tokenizer,
266
+ URL e configurazione scelta. `headroomLocalCli` **non certifica** la versione o i
267
+ flag di un servizio Headroom remoto: fissarli/annotarli esternamente per confronti
268
+ tra macchine o date diverse.
269
+
270
+ Exit code: **0** run completato senza errori di richiesta; **2** errori o
271
+ interruzione; **1** opzioni/setup non validi. Una regressione di qualità non
272
+ cambia da sola l'exit code: consultare `decisions`. Nessuna modifica è applicata
273
+ automaticamente al flow del proxy in uso.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drakonkat/ai-helper",
3
- "version": "1.1.0",
3
+ "version": "1.2.2",
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",
@@ -12,13 +12,16 @@
12
12
  "files": [
13
13
  "bin",
14
14
  "src",
15
+ "scripts/build.js",
16
+ "scripts/bench-proxy.js",
17
+ "docs/benchmark.md",
15
18
  "README.md",
16
19
  "LICENSE",
17
20
  "ARCHITECTURE.md",
18
21
  "CHANGELOG.md"
19
22
  ],
20
23
  "engines": {
21
- "node": ">=18.0.0"
24
+ "node": ">=20.19.0"
22
25
  },
23
26
  "publishConfig": {
24
27
  "access": "public"
@@ -34,8 +37,11 @@
34
37
  "scripts": {
35
38
  "start": "node ./bin/cli.js",
36
39
  "dev": "node ./bin/cli.js",
37
- "test": "bun test",
38
- "build": "bun build --compile --minify --outfile dist/aih.exe src/index.js",
40
+ "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 && 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",
41
+ "bench:proxy": "node scripts/bench-proxy.js",
42
+ "bench:models": "node scripts/bench-proxy.js --compare-models gpt-6-astra,anthropic/claude-fable-5-1 --formats responses",
43
+ "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",
44
+ "build": "bun run scripts/build.js",
39
45
  "install-bin": "bun run scripts/install-bin.js"
40
46
  },
41
47
  "keywords": [
@@ -53,5 +59,11 @@
53
59
  "developer-tools"
54
60
  ],
55
61
  "author": "Mauro",
56
- "license": "MIT"
62
+ "license": "MIT",
63
+ "dependencies": {
64
+ "gpt-tokenizer": "3.4.0",
65
+ "pxpipe-proxy": "0.13.2",
66
+ "toml-eslint-parser": "1.0.3",
67
+ "ws": "^8.21.3"
68
+ }
57
69
  }
@@ -0,0 +1,107 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from "node:util";
3
+ import { readFile, mkdir, writeFile, appendFile, readdir } from "node:fs/promises";
4
+ import { resolve, join } from "node:path";
5
+ import { randomBytes } from "node:crypto";
6
+ import { fileURLToPath } from "node:url";
7
+ import { runBenchmark, prepareBenchmark, BENCHMARK_PRESETS } from "../src/benchmark/runner.js";
8
+ import { buildReport, reportCsv, reportMarkdown } from "../src/benchmark/report.js";
9
+
10
+ const HELP = `Usage: node scripts/bench-proxy.js [options]
11
+
12
+ Offline by default: private loopback proxies and real compressors; no provider call.
13
+ --presets LIST ${BENCHMARK_PRESETS.join(",")} (default: all; none always included)
14
+ --formats LIST responses,chat,anthropic (default: all)
15
+ --transports LIST http,ws (default: http; WS only for Responses)
16
+ --fixtures FILE JSON array of custom fixtures instead of built-in corpus
17
+ --export-fixtures FILE Write built-in fixtures as editable JSON, without running
18
+ --model NAME Override model identically for every fixture/flow
19
+ --compare-models LIST Replay each fixture for every model (mutually exclusive with --model)
20
+ --repetitions N Measured rounds (default: 3)
21
+ --warmup N Unscored rounds (default: 1; live warmups also cost tokens)
22
+ --seed N Reproducible randomized order (default: 42)
23
+ --headroom-url URL Compression service (default: http://127.0.0.1:8787)
24
+ --rtk-filter NAME Fixed filter for matching corpora only (default: auto)
25
+ --models LIST pxpipe allowlist (default: all fixture models, benchmark-only opt-in)
26
+ --timeout-ms N Per-request limit (default: 120000)
27
+ --max-body-bytes N Payload/response limit (default: 67108864)
28
+ --out DIR New output directory (default: benchmark-results/<run-id>)
29
+ --save-payloads Opt-in originals/transformed payloads and live answers; may contain sensitive data
30
+ --live EXPLICITLY enable potentially billable provider calls
31
+ --upstream URL Live provider root BEFORE /v1, e.g. http://127.0.0.1:10100
32
+ --api-key-env NAME Environment variable holding credentials (never written to reports)
33
+ --max-output-tokens N Live answer cap (default: 256; no tool execution or retries)
34
+ --max-live-calls N Refuse live plans above this call count (default: 200, including warmups)
35
+ --stop-on-error Stop after the first request error (useful for live smoke checks)
36
+ --max-quality-drop N Allowed answer pass-rate drop in percentage points (default: 0)
37
+ --max-latency-regression N Allowed p95 increase in percent (default: 25)
38
+ --list Print built-in fixture IDs without running
39
+ --help Show help
40
+
41
+ Reports: report.json, records.jsonl, results.csv, report.md. Managed config/aih proxy stats are untouched.
42
+ Exit 0 completed without request errors; 2 request errors/interruption; 1 invalid setup.
43
+ Offline runs never claim a semantic-quality winner. See docs/benchmark.md.
44
+ `;
45
+
46
+ export async function main(argv = process.argv.slice(2)) {
47
+ const strings = ["presets", "formats", "transports", "fixtures", "export-fixtures", "model", "compare-models", "repetitions", "warmup", "seed", "headroom-url", "rtk-filter", "models", "timeout-ms", "max-body-bytes", "out", "upstream", "api-key-env", "max-output-tokens", "max-live-calls", "max-quality-drop", "max-latency-regression"];
48
+ const booleans = ["help", "list", "save-payloads", "live", "stop-on-error"];
49
+ const { values } = parseArgs({ args: argv, options: { ...Object.fromEntries(strings.map(s => [s, { type: "string" }])), ...Object.fromEntries(booleans.map(s => [s, { type: "boolean" }])) }, strict: true, allowPositionals: false });
50
+ if (values.help) { console.log(HELP); return 0; }
51
+ const list = name => values[name] === undefined ? undefined : values[name].split(",").map(s => s.trim());
52
+ const numeric = name => values[name] === undefined ? undefined : Number(values[name]);
53
+ const formats = list("formats");
54
+ if (formats && (formats.some(f => !["responses", "chat", "anthropic"].includes(f)) || new Set(formats).size !== formats.length)) throw new Error("Invalid formats list");
55
+ const preview = values.list || values["export-fixtures"] ? prepareBenchmark({ model: values.model, compareModels: list("compare-models"), formats, presets: ["none"] }).fixtures : null;
56
+ if (values.list) { console.log(preview.map(f => `${f.id}\t${f.format}\t${f.category}`).join("\n")); return 0; }
57
+ if (values["export-fixtures"]) {
58
+ const file = resolve(values["export-fixtures"]);
59
+ await writeFile(file, JSON.stringify(preview, null, 2) + "\n", { flag: "wx" });
60
+ console.log(`Fixtures exported to ${file}`); return 0;
61
+ }
62
+ if (values["api-key-env"] && !values.live) throw new Error("--api-key-env requires --live");
63
+ const apiKey = values["api-key-env"] ? process.env[values["api-key-env"]] : undefined;
64
+ if (values["api-key-env"] && !apiKey) throw new Error("Credential environment variable is missing or empty");
65
+ const thresholds = { maxQualityDrop: numeric("max-quality-drop") ?? 0, maxLatencyRegression: numeric("max-latency-regression") ?? 25 };
66
+ if (Object.values(thresholds).some(n => !Number.isFinite(n) || n < 0)) throw new Error("Thresholds must be nonnegative numbers");
67
+ const fixtures = values.fixtures ? JSON.parse(await readFile(resolve(values.fixtures), "utf8")) : undefined;
68
+ const options = { presets: list("presets"), formats, transports: list("transports"), fixtures, model: values.model, compareModels: list("compare-models"),
69
+ repetitions: numeric("repetitions"), warmup: numeric("warmup"), seed: numeric("seed"),
70
+ headroomUrl: values["headroom-url"], rtkFilter: values["rtk-filter"], models: values.models,
71
+ timeoutMs: numeric("timeout-ms"), maxBodyBytes: numeric("max-body-bytes"), live: values.live,
72
+ upstream: values.upstream, apiKey, maxOutputTokens: numeric("max-output-tokens"), maxLiveCalls: numeric("max-live-calls") };
73
+ const prepared = prepareBenchmark(options); // Validate before creating/reserving any output files.
74
+ const directory = resolve(values.out || join("benchmark-results", `${new Date().toISOString().replace(/[:.]/g, "-")}-${randomBytes(3).toString("hex")}`));
75
+ await mkdir(directory, { recursive: true });
76
+ if ((await readdir(directory)).length) throw new Error("Output directory must be empty; choose a new run directory");
77
+ // Reserve a new run; never overwrite a previous benchmark's measurements.
78
+ await writeFile(join(directory, "records.jsonl"), "", { flag: "wx" });
79
+ if (values["save-payloads"]) await mkdir(join(directory, "payloads"));
80
+ const controller = new AbortController();
81
+ const interrupt = () => controller.abort();
82
+ process.once("SIGINT", interrupt);
83
+ if (values.live) console.error(`LIVE benchmark: up to ${prepared.cases.length * prepared.options.presets.length * (prepared.options.repetitions + prepared.options.warmup)} potentially billable provider calls, including warmups. No automatic retries or tool execution.`);
84
+ try {
85
+ const run = await runBenchmark({ ...options, signal: controller.signal,
86
+ onRecord: async row => {
87
+ await appendFile(join(directory, "records.jsonl"), JSON.stringify(row) + "\n");
88
+ if (row.status === "error") {
89
+ console.error(`${row.preset} / ${row.caseId}: ${row.error}`);
90
+ if (values["stop-on-error"]) controller.abort();
91
+ }
92
+ },
93
+ onPayload: values["save-payloads"] ? async payload => writeFile(join(directory, "payloads", `${payload.sequence}.json`), JSON.stringify(payload) + "\n", { flag: "wx" }) : undefined,
94
+ });
95
+ const report = buildReport(run, thresholds);
96
+ await writeFile(join(directory, "report.json"), JSON.stringify(report, null, 2) + "\n", { flag: "wx" });
97
+ await writeFile(join(directory, "results.csv"), reportCsv(report), { flag: "wx" });
98
+ await writeFile(join(directory, "report.md"), reportMarkdown(report), { flag: "wx" });
99
+ console.log(reportMarkdown(report));
100
+ console.log(`Reports saved to ${directory}`);
101
+ return report.meta.completed && !report.records.some(r => r.status === "error") ? 0 : 2;
102
+ } finally { process.removeListener("SIGINT", interrupt); }
103
+ }
104
+
105
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
106
+ main().then(code => { process.exitCode = code; }).catch(error => { console.error(`Benchmark: ${error.message}`); process.exitCode = 1; });
107
+ }
@@ -0,0 +1,16 @@
1
+ import { resolve } from "node:path";
2
+
3
+ // Embed a Node worker so the compiled CLI uses the same proxy transport as npm.
4
+ const root = resolve(import.meta.dir, "..");
5
+ const outfile = process.argv[2] || resolve(root, "dist", process.platform === "win32" ? "aih.exe" : "aih");
6
+ const worker = await Bun.build({
7
+ entrypoints: [resolve(root, "src/proxy-worker.js")], target: "node", format: "esm", minify: true,
8
+ });
9
+ if (!worker.success) throw new AggregateError(worker.logs, "Proxy worker build failed");
10
+ const result = await Bun.build({
11
+ entrypoints: [resolve(root, "src/index.js")], minify: true,
12
+ compile: { outfile },
13
+ define: { AIH_PROXY_WORKER_SOURCE: JSON.stringify(await worker.outputs[0].text()) },
14
+ });
15
+ if (!result.success) throw new AggregateError(result.logs, "CLI build failed");
16
+ console.log(`Built ${outfile} (proxy worker requires Node.js 20.19+ on PATH)`);
@@ -0,0 +1,150 @@
1
+ import { evaluatePreservation } from "./quality.js";
2
+
3
+ const PATHS = { responses: "/v1/responses", chat: "/v1/chat/completions", anthropic: "/v1/messages" };
4
+ const SYSTEM = "You are evaluating synthetic tool results. Answer the final question using only the tool output. Return the requested literal values, case-sensitive, without explanation. Never execute further tools.";
5
+ const repeat = (count, line) => Array.from({ length: count }, (_, index) => line(index)).join("\n");
6
+ const DENSE_CONTEXT = repeat(600, index => `Reference rule ${index}: the synthetic module component_${index} accepts value_${index}, validates type and range, and emits a structured diagnostic on invalid input. Preserve literal names and numerical values when reporting results.`);
7
+
8
+ function scenarios() {
9
+ return [
10
+ {
11
+ id: "build-success", category: "build", command: "npm run build",
12
+ output: `vite v6.2.0 building for production...\n${repeat(150, index => `transforming src/components/Widget${index}.tsx ... done`)}\n✓ 150 modules transformed.\ndist/index.html 0.46 kB │ gzip: 0.30 kB\ndist/assets/checkout-7f3c.js 183.42 kB │ gzip: 52.10 kB\n✓ built in 3.84s`,
13
+ question: "What is the emitted JavaScript bundle path?", expected: ["dist/assets/checkout-7f3c.js"],
14
+ },
15
+ {
16
+ id: "build-failure", category: "build", command: "npm run build",
17
+ output: `${repeat(120, index => `Checking project packages/module-${index}/tsconfig.json`)}\nsrc/payments/settlement.ts(73,9): error TS2322: Type 'string' is not assignable to type 'number'.\nFound 1 error.\nProcess exited with code 2.`,
18
+ question: "Report the compiler error code and the source location exactly as shown.", expected: ["TS2322", "src/payments/settlement.ts(73,9)"],
19
+ },
20
+ {
21
+ id: "test-failure", category: "test", command: "pytest -v",
22
+ output: `${repeat(100, index => `tests/test_health.py::test_case_${index} PASSED [ ${Math.min(99, index)}%]`)}\nFAILED tests/test_billing.py::test_refund_rounding - AssertionError: expected 42, got 41\nE assert 41 == 42\n=========================== 1 failed, 100 passed in 2.93s ===========================`,
23
+ question: "Which fully qualified test failed, and what were the expected and actual integers?", expected: ["tests/test_billing.py::test_refund_rounding", "42", "41"],
24
+ preserve: ["tests/test_billing.py::test_refund_rounding", "expected 42, got 41"],
25
+ },
26
+ {
27
+ id: "stack-trace", category: "stacktrace", command: "node scripts/checkout.js",
28
+ output: `TypeError: Cannot read properties of undefined (reading 'currency')\n at normalizeInvoice (/workspace/src/invoices/normalize.js:118:27)\n at submitInvoice (/workspace/src/invoices/submit.js:56:12)\n${repeat(110, index => ` at middleware${index} (/workspace/node_modules/router/layer.js:95:5)`)}\nCaused by: missing customer profile\nDiagnostic code: CUSTOMER_PROFILE_MISSING`,
29
+ question: "Return the first application source location and the diagnostic code.", expected: ["/workspace/src/invoices/normalize.js:118:27", "CUSTOMER_PROFILE_MISSING"],
30
+ },
31
+ {
32
+ id: "repeated-logs", category: "logs", command: "docker logs synthetic-worker",
33
+ output: `${repeat(240, index => `2026-01-01T12:${String(index % 60).padStart(2, "0")}:00Z INFO heartbeat worker=alpha queue_depth=0`)}\n2026-01-01T13:00:00Z ERROR request_id=req-9d82 code=QUEUE_LIMIT queue_depth=317 retry_after_ms=8500\n${repeat(80, index => `2026-01-01T13:01:${String(index % 60).padStart(2, "0")}Z INFO heartbeat worker=alpha queue_depth=0`)}`,
34
+ question: "For the ERROR event only, return request_id, code and retry_after_ms.", expected: ["req-9d82", "QUEUE_LIMIT", "8500"],
35
+ },
36
+ {
37
+ id: "grep-results", category: "search", command: "rg -n timeout src",
38
+ output: `${repeat(160, index => `src/generated/client${index}.ts:20:const timeoutMs = 5000;`)}\nsrc/gateway/retry.ts:87:const timeoutMs = 17321; // production override\nsrc/gateway/retry.ts:88:const retryLimit = 4;`,
39
+ question: "Return the production override source path, its line number and its timeout value.", expected: ["src/gateway/retry.ts", "87", "17321"],
40
+ preserve: ["src/gateway/retry.ts:87:const timeoutMs = 17321"],
41
+ },
42
+ {
43
+ id: "git-diff", category: "git", command: "git diff -- src",
44
+ output: `diff --git a/src/config/retries.js b/src/config/retries.js\nindex e183fd0..d0beaf1 100644\n--- a/src/config/retries.js\n+++ b/src/config/retries.js\n@@ -1,162 +1,162 @@\n${repeat(160, index => ` // Configuration reference item ${index}; keep consistent across deployments.`)}\n-export const BACKOFF_CAP_MS = 4000;\n+export const BACKOFF_CAP_MS = 12500;\n export const RETRY_LIMIT = 3;`,
45
+ question: "What configuration symbol changed, and what is its new value?", expected: ["BACKOFF_CAP_MS", "12500"],
46
+ },
47
+ {
48
+ id: "large-json", category: "json", command: "cat synthetic-status.json",
49
+ output: JSON.stringify({ records: Array.from({ length: 180 }, (_, index) => ({ id: `job-${index}`, state: "complete", duration_ms: 230 + index, attempts: 1 })), incident: { id: "inc-b62f", state: "blocked", reason: "SCHEMA_MISMATCH", affected_rows: 2917 } }, null, 2),
50
+ question: "Return the incident id, reason and affected_rows count.", expected: ["inc-b62f", "SCHEMA_MISMATCH", "2917"],
51
+ },
52
+ {
53
+ id: "short-output", category: "short", command: "node scripts/read-version.js",
54
+ output: "service_version=2.17.4-rc.3\nstatus=ready\n",
55
+ question: "What is the exact service version, including its suffix?", expected: ["2.17.4-rc.3"],
56
+ },
57
+ {
58
+ id: "dense-context", category: "context", command: "cat synthetic-deploy-report.txt", dense: true,
59
+ output: `${repeat(220, index => `Preflight check ${index}: valid; no remediation required; policy=documented`)}\nDeployment result: FAILED\nFailure domain: inventory-eu\nRecovery checkpoint: checkpoint-4e6b\nRequired action: REPLAY_PENDING_EVENTS\n`,
60
+ question: "Return the failure domain, recovery checkpoint and required action from the deployment report.", expected: ["inventory-eu", "checkpoint-4e6b", "REPLAY_PENDING_EVENTS"],
61
+ },
62
+ ];
63
+ }
64
+
65
+ function request(format, model, scenario) {
66
+ const instructions = scenario.dense ? `${SYSTEM}\n\n${DENSE_CONTEXT}` : SYSTEM;
67
+ const callId = `call_${scenario.id.replaceAll("-", "_")}`;
68
+ const parameters = { type: "object", properties: { cmd: { type: "string" } }, required: ["cmd"], additionalProperties: false };
69
+ const definition = { name: "exec_command", description: "Run the given shell command and return textual output.", parameters };
70
+ const args = { cmd: scenario.command };
71
+ if (format === "responses") return {
72
+ model, instructions, max_output_tokens: 256, stream: false,
73
+ tools: [{ type: "function", ...definition }],
74
+ input: [
75
+ { role: "user", content: "Inspect the synthetic command output." },
76
+ { type: "function_call", call_id: callId, name: definition.name, arguments: JSON.stringify(args) },
77
+ { type: "function_call_output", call_id: callId, output: scenario.output },
78
+ { role: "user", content: scenario.question },
79
+ ],
80
+ };
81
+ if (format === "chat") return {
82
+ model, max_completion_tokens: 256, stream: false, tools: [{ type: "function", function: definition }],
83
+ messages: [
84
+ { role: "system", content: instructions },
85
+ { role: "user", content: "Inspect the synthetic command output." },
86
+ { role: "assistant", content: null, tool_calls: [{ id: callId, type: "function", function: { name: definition.name, arguments: JSON.stringify(args) } }] },
87
+ { role: "tool", tool_call_id: callId, content: scenario.output },
88
+ { role: "user", content: scenario.question },
89
+ ],
90
+ };
91
+ return {
92
+ model, system: instructions, max_tokens: 256, stream: false,
93
+ tools: [{ name: definition.name, description: definition.description, input_schema: parameters }],
94
+ messages: [
95
+ { role: "user", content: "Inspect the synthetic command output." },
96
+ { role: "assistant", content: [{ type: "tool_use", id: callId, name: definition.name, input: args }] },
97
+ { role: "user", content: [{ type: "tool_result", tool_use_id: callId, content: scenario.output }, { type: "text", text: scenario.question }] },
98
+ ],
99
+ };
100
+ }
101
+
102
+ /** Thirty reproducible, secret-free requests; commands are data, never executed. */
103
+ export function builtInFixtures({ model = "gpt-5.5", formats = Object.keys(PATHS) } = {}) {
104
+ if (typeof model !== "string" || !model.trim()) throw new Error("fixture model must be a nonempty string");
105
+ if (!Array.isArray(formats) || !formats.length || formats.some(format => !Object.hasOwn(PATHS, format)) || new Set(formats).size !== formats.length) {
106
+ throw new Error(`fixture formats must be a nonempty, unique subset of: ${Object.keys(PATHS).join(", ")}`);
107
+ }
108
+ return formats.flatMap(format => scenarios().map(scenario => ({
109
+ id: `${format}-${scenario.id}`, category: scenario.category, format, path: PATHS[format],
110
+ body: request(format, model, scenario),
111
+ checks: { toolIncludes: [...(scenario.preserve || scenario.expected)], requestIncludes: [scenario.question] },
112
+ answerChecks: { includes: [...scenario.expected] },
113
+ })));
114
+ }
115
+
116
+ function object(value) { return value !== null && typeof value === "object" && !Array.isArray(value); }
117
+ function checkArrays(value, keys, where) {
118
+ if (!object(value)) throw new Error(`${where} must be an object`);
119
+ for (const key of Object.keys(value)) {
120
+ if (!keys.includes(key)) throw new Error(`${where}.${key} is unknown; allowed keys: ${keys.join(", ")}`);
121
+ if (!Array.isArray(value[key]) || value[key].some(text => typeof text !== "string" || !text.trim())) throw new Error(`${where}.${key} must be an array of nonempty strings`);
122
+ }
123
+ }
124
+
125
+ /** Validate a parsed JSON fixture array without changing it or inventing checks. */
126
+ export function validateFixtures(input) {
127
+ if (!Array.isArray(input) || !input.length) throw new Error("Fixtures must be a nonempty JSON array");
128
+ const ids = new Set();
129
+ input.forEach((fixture, index) => {
130
+ const where = `Fixture[${index}]${fixture?.id ? ` (${fixture.id})` : ""}`;
131
+ if (!object(fixture)) throw new Error(`${where} must be an object`);
132
+ for (const key of ["id", "category"]) if (typeof fixture[key] !== "string" || !fixture[key].trim()) throw new Error(`${where}.${key} must be a nonempty string`);
133
+ if (ids.has(fixture.id)) throw new Error(`${where}.id is duplicated`);
134
+ ids.add(fixture.id);
135
+ if (!Object.hasOwn(PATHS, fixture.format)) throw new Error(`${where}.format must be responses, chat or anthropic`);
136
+ if (fixture.path !== PATHS[fixture.format]) throw new Error(`${where}.path must be ${PATHS[fixture.format]} for ${fixture.format}`);
137
+ if (!object(fixture.body)) throw new Error(`${where}.body must be a request object`);
138
+ if (typeof fixture.body.model !== "string" || !fixture.body.model.trim()) throw new Error(`${where}.body.model must be a nonempty string`);
139
+ if (fixture.format === "responses") {
140
+ if (!(typeof fixture.body.input === "string" && fixture.body.input.trim()) && !(Array.isArray(fixture.body.input) && fixture.body.input.length)) throw new Error(`${where}.body.input must be nonempty text or an array`);
141
+ } else if (!Array.isArray(fixture.body.messages) || !fixture.body.messages.length) throw new Error(`${where}.body.messages must be a nonempty array`);
142
+ if (fixture.body.tools !== undefined && !Array.isArray(fixture.body.tools)) throw new Error(`${where}.body.tools must be an array`);
143
+ checkArrays(fixture.checks, ["toolIncludes", "requestIncludes"], `${where}.checks`);
144
+ if (fixture.answerChecks !== undefined) checkArrays(fixture.answerChecks, ["includes", "excludes"], `${where}.answerChecks`);
145
+ const quality = evaluatePreservation(fixture.body, fixture.body, fixture.checks);
146
+ const invalid = quality.checks.find(check => check.reason === "not_in_original");
147
+ if (invalid) throw new Error(`${where}.checks.${invalid.kind} assertion ${JSON.stringify(invalid.expected)} is absent from the original ${invalid.kind === "toolIncludes" ? "tool output" : "request text"}`);
148
+ });
149
+ return input;
150
+ }