@drakonkat/ai-helper 1.2.2 → 1.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1 -0
- package/README.md +77 -13
- package/docs/benchmark.md +110 -10
- package/package.json +3 -3
- package/scripts/bench-proxy.js +11 -7
- package/src/benchmark/fixtures.js +16 -4
- package/src/benchmark/live.js +130 -1
- package/src/benchmark/quality-fixtures.js +95 -0
- package/src/benchmark/quality.js +71 -9
- package/src/benchmark/report.js +23 -2
- package/src/benchmark/runner.js +29 -11
- package/src/config.js +8 -0
- package/src/index.js +61 -6
- package/src/manager.js +108 -3
- package/src/proxy-presets.js +18 -9
- package/src/request-images.js +69 -0
- package/src/service-updates.js +68 -0
- package/src/tui.js +202 -149
- package/src/utils/metrics.js +17 -12
- package/src/utils/versions.js +1 -7
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,7 @@ All notable changes to **`ai-helper` (`aih`)** are documented in this file.
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
9
|
### Added
|
|
10
|
+
- Explicit managed-service updates with `aih <service> update`, `aih update [services...]`, and the live dashboard's `u` shortcut. Includes clean JSON results, target validation, running-service restart/recovery, and version-cache invalidation; automatic checks remain read-only.
|
|
10
11
|
- GitHub `REPO` column in plain status and the live dashboard, `repositoryUrl` in JSON, and repository opening with `g` or `aih open <service> --repo`.
|
|
11
12
|
- Automatic Codex proxy URL configuration on managed proxy start/restart and ocx start/restart with an active proxy, including actual bound ports, ocx readiness checks, TOML-preserving edits, first-write backups, and `AIH_CODEX_AUTOCONFIG=0` opt-out.
|
|
12
13
|
|
package/README.md
CHANGED
|
@@ -63,7 +63,7 @@ npx @drakonkat/ai-helper status
|
|
|
63
63
|
# Open service web dashboards in your default browser
|
|
64
64
|
npx @drakonkat/ai-helper open
|
|
65
65
|
|
|
66
|
-
# Start
|
|
66
|
+
# Start ocx, agentmemory and the pxpipe proxy
|
|
67
67
|
npx @drakonkat/ai-helper start
|
|
68
68
|
```
|
|
69
69
|
|
|
@@ -148,16 +148,62 @@ installed version. `UPDATE` shows `↑ <version>` for an available update,
|
|
|
148
148
|
completed. Checks query npm/PyPI in the background every five minutes and after
|
|
149
149
|
a service restart; they never install or update services.
|
|
150
150
|
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
151
|
+
Press **`u`** to update the selected service to the latest available release.
|
|
152
|
+
The action checks the registry again, reports progress/results in the footer,
|
|
153
|
+
and refreshes version information even for stopped services. Repeated action
|
|
154
|
+
keys are ignored while an operation is in progress. Only services that were
|
|
155
|
+
running are stopped and restarted; stopped services stay stopped.
|
|
156
|
+
|
|
157
|
+
Both `PIPELINE` and `STREAM RICHIESTE` read the native AIH proxy snapshot,
|
|
158
|
+
`~/.aih/proxy-stats.json` (`AIH_HOME` overrides the directory), not Headroom's
|
|
159
|
+
metrics or savings event log. `PIPELINE` shows recorded requests, changed requests,
|
|
160
|
+
preset errors, estimated token savings and each stage's application/measurement
|
|
161
|
+
counts. `elab/s` measures preset processing between successful samples, not all
|
|
162
|
+
proxy traffic or token-generation speed. Counters persist across restarts.
|
|
163
|
+
|
|
164
|
+
`STREAM RICHIESTE` shows the latest recorded events with local time, model,
|
|
165
|
+
HTTP/WS transport, preset, changed/unchanged/error outcome, estimated savings
|
|
166
|
+
and stage reasons. Press **`d`** for source/configuration details and per-stage
|
|
167
|
+
before/after token counts, percentages and measurement methods. Unknown savings
|
|
168
|
+
remain unknown; partial estimates and token increases are explicitly marked.
|
|
169
|
+
The panels do not infer provider cache savings, costs, upstream latency or
|
|
170
|
+
active requests. Preset `none` and interceptor-only traffic are not recorded.
|
|
171
|
+
|
|
172
|
+
A running process is not a health check, and the final upstream is not monitored.
|
|
173
|
+
Snapshot read time is separate from last-event time: an idle proxy is not stale
|
|
174
|
+
just because no new event arrived. After a failed read, five seconds without a
|
|
175
|
+
sample or a stopped proxy, totals/events are historical and live rates are hidden.
|
|
176
|
+
Narrow terminals keep space for the newest events and service controls.
|
|
177
|
+
|
|
178
|
+
---
|
|
179
|
+
|
|
180
|
+
### Update Managed Services
|
|
181
|
+
|
|
182
|
+
```bash
|
|
183
|
+
aih ocx update # update OpenCodex to the latest available release
|
|
184
|
+
aih update ocx # equivalent command-first form
|
|
185
|
+
aih update ocx agentmemory # update selected services
|
|
186
|
+
aih update # pxpipe, ocx, agentmemory, headroom only
|
|
187
|
+
aih update ocx --json # JSON result array, exit code 1 on any failure
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
Updates are explicit: automatic version checks remain read-only. A current
|
|
191
|
+
installation is left unchanged. Running services are restarted after an update;
|
|
192
|
+
stopped services are not started. If installation fails after stopping a running
|
|
193
|
+
service, aih attempts to start it again and reports any recovery failure.
|
|
194
|
+
Unknown/custom service targets are rejected before any selected service is
|
|
195
|
+
changed. The built-in `proxy` is part of ai-helper itself and is excluded from
|
|
196
|
+
`aih update`: update the ai-helper package or rebuild the standalone executable
|
|
197
|
+
instead. The proxy's bundled pxpipe library is likewise updated with ai-helper,
|
|
198
|
+
not by updating the separate `pxpipe` service.
|
|
199
|
+
|
|
200
|
+
The Node services use `npm install --global <package>@latest` (`pxpipe-proxy`,
|
|
201
|
+
`@bitkyc08/opencodex`, `@agentmemory/agentmemory`), so npm must be available and
|
|
202
|
+
its global installation directory writable and on PATH. Headroom uses its own
|
|
203
|
+
`headroom update --yes` command to respect the existing Python installation.
|
|
204
|
+
Installer output is captured in `aih logs <service>` rather than mixed into
|
|
205
|
+
JSON or the live dashboard. An explicitly updated npx service is launched with
|
|
206
|
+
the verified package version so an older project dependency/cache cannot win.
|
|
161
207
|
|
|
162
208
|
---
|
|
163
209
|
|
|
@@ -182,7 +228,7 @@ aih open proxy --repo
|
|
|
182
228
|
### 3. Start Services
|
|
183
229
|
|
|
184
230
|
```bash
|
|
185
|
-
# Start
|
|
231
|
+
# Start ocx, agentmemory and the pxpipe proxy
|
|
186
232
|
aih start
|
|
187
233
|
|
|
188
234
|
# Start a specific service
|
|
@@ -190,6 +236,16 @@ aih start pxpipe
|
|
|
190
236
|
aih start agentmemory
|
|
191
237
|
```
|
|
192
238
|
|
|
239
|
+
Without service targets, `aih start` (or `aih up`) starts `ocx`, `agentmemory`,
|
|
240
|
+
then the built-in proxy with these options:
|
|
241
|
+
|
|
242
|
+
```bash
|
|
243
|
+
aih start proxy http://127.0.0.1:10100/ --listen http://127.0.0.1:10102 --preset pxpipe --models "gpt-6-astra,google-antigravity/gemini-3.8*,anthropic/claude-fable*"
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
If the proxy is already running with different options, use `aih restart proxy`
|
|
247
|
+
with the options above to apply them.
|
|
248
|
+
|
|
193
249
|
`aih start` (also `aih up` and starts targeting individual services) checks npm's
|
|
194
250
|
`latest` release of `@drakonkat/ai-helper`. If a newer version exists, it prints
|
|
195
251
|
the installed/latest versions and the update command to stderr. The check times
|
|
@@ -327,6 +383,14 @@ aih restart proxy --preset none --interceptor=
|
|
|
327
383
|
```
|
|
328
384
|
|
|
329
385
|
RTK presets require an `rtk` executable with `rtk pipe` support on PATH.
|
|
386
|
+
The optional `rtk-headroom-pxpipe` recipe runs RTK -> Headroom -> pxpipe, in that
|
|
387
|
+
order, and is included in the [benchmark](docs/benchmark.md). Adding/testing it
|
|
388
|
+
does not change the active proxy recipe. Double compression can lose facts and
|
|
389
|
+
should be evaluated before selecting it for everyday traffic.
|
|
390
|
+
The benchmark also offers an opt-in `--suite quality` (12 Responses cases) and
|
|
391
|
+
`*-native-bypass` flow variants to compare pxpipe with/without native image
|
|
392
|
+
attachments. These variants do not reconfigure the everyday proxy. See the
|
|
393
|
+
[quality and native-image benchmark](docs/benchmark.md#suite-qualità-e-richieste-con-immagini-native).
|
|
330
394
|
`--rtk-filter=` selects automatic detection; `--rtk-filter grep` applies the
|
|
331
395
|
grep-output filter to every tool result, so use it only with matching output.
|
|
332
396
|
|
|
@@ -507,7 +571,7 @@ above, without adding HTTP routes that could interfere with forwarded API paths.
|
|
|
507
571
|
| `model_excluded` | Match `--models` to the request's exact model ID, including provider prefixes; a new list replaces the old one. |
|
|
508
572
|
| Headroom shows `no_messages` | For Responses requests, this preset sends only tool-result text to Headroom. A request without tool outputs has nothing for that stage to compress. |
|
|
509
573
|
| Zero savings with `no_static_context`, `below_min_*` or `not_profitable` | The stage was reached but pxpipe chose to preserve the request. Zero savings is valid. |
|
|
510
|
-
|
|
|
574
|
+
| Headroom has traffic but the UI stream stays unchanged | Both UI panels use native proxy preset events. Point the client at the AIH listener and enable a preset; requests sent directly to Headroom are not included. |
|
|
511
575
|
| Startup fails | Read `aih logs proxy -n 100`. Check Node on PATH, upstream/listener ports, and the saved interceptor path. `aih restart proxy --interceptor=` clears a missing interceptor. |
|
|
512
576
|
| Windows build cannot replace `dist/aih.exe` (`EPERM`) | Exit any dashboard using that binary with `q`, then rebuild. |
|
|
513
577
|
|
package/docs/benchmark.md
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
# Benchmark dei flow del proxy
|
|
2
2
|
|
|
3
3
|
Il benchmark confronta **gli stessi input** attraverso i preset reali `none`,
|
|
4
|
-
`headroom`, `rtk`, `pxpipe`, `headroom-pxpipe`, `rtk-pxpipe
|
|
4
|
+
`headroom`, `rtk`, `pxpipe`, `headroom-pxpipe`, `rtk-pxpipe`,
|
|
5
|
+
`rtk-headroom-pxpipe`. Non legge né azzera
|
|
5
6
|
le statistiche del proxy quotidiano e non cambia client, configurazioni o servizi.
|
|
6
|
-
`none` viene sempre aggiunto come baseline.
|
|
7
|
-
|
|
7
|
+
`none` viene sempre aggiunto come baseline. Il preset `rtk-headroom-pxpipe`
|
|
8
|
+
esegue **RTK → Headroom → pxpipe** sul risultato dello stadio precedente; i tre
|
|
9
|
+
stadi sono riportati separatamente. La doppia compressione può perdere fatti:
|
|
10
|
+
Headroom non può recuperare informazioni già eliminate da RTK. Il nuovo preset
|
|
11
|
+
non viene selezionato automaticamente nel proxy quotidiano.
|
|
8
12
|
|
|
9
13
|
## Avvio rapido
|
|
10
14
|
|
|
@@ -15,7 +19,7 @@ si esegue dal checkout con Node, non nel binario Bun compilato.
|
|
|
15
19
|
# Smoke test senza Headroom, RTK o provider esterni
|
|
16
20
|
npm run bench:proxy -- --presets none,pxpipe --formats responses --warmup 0 --repetitions 1
|
|
17
21
|
|
|
18
|
-
# Tutti i
|
|
22
|
+
# Tutti i sette flow; Headroom deve essere già disponibile a questo indirizzo
|
|
19
23
|
npm run bench:proxy -- --headroom-url http://127.0.0.1:8787 --repetitions 5 --warmup 1
|
|
20
24
|
|
|
21
25
|
# Stessi casi Responses attraverso HTTP e WebSocket
|
|
@@ -118,17 +122,93 @@ un controllo di conservazione, non una prova di comprensione o correttezza.
|
|
|
118
122
|
|
|
119
123
|
## Valutazione live, esplicita e potenzialmente a pagamento
|
|
120
124
|
|
|
125
|
+
### Suite qualità e richieste con immagini native
|
|
126
|
+
|
|
127
|
+
`--suite core` resta il default storico: 30 fixture, 10 per protocollo.
|
|
128
|
+
`--suite quality` aggiunge un corpus **opt-in di 12 casi Responses**, destinato
|
|
129
|
+
anche al confronto Astra/Fable. `--suite all` unisce i due corpora (42 fixture
|
|
130
|
+
prima dei filtri/modelli). Il file passato con `--fixtures` è alternativo a
|
|
131
|
+
`--suite`: non viene mescolato implicitamente con casi integrati.
|
|
132
|
+
|
|
133
|
+
La suite qualità contiene:
|
|
134
|
+
|
|
135
|
+
- 2 casi con regole in istruzioni lunghe, non nel tool output: recupero di un
|
|
136
|
+
fatto e rispetto della priorità delle istruzioni rispetto a una nota del tool;
|
|
137
|
+
- 2 diagnostici di build, in fondo e in mezzo a output rumoroso, con risposta
|
|
138
|
+
JSON esatta comprendente errore, file, riga, colonna ed exit code;
|
|
139
|
+
- 1 campo assente per verificare l'astensione invece dell'invenzione di un valore;
|
|
140
|
+
- 7 casi con PNG nativi: singolo, multiplo/ordine, storico più allegato corrente,
|
|
141
|
+
risultato di tool, testo contraddittorio, detail low e controllo breve.
|
|
142
|
+
|
|
143
|
+
I PNG sono pixel deterministici di pannelli sintetici con codici leggibili,
|
|
144
|
+
senza metadati testuali o URL che contengano la soluzione. Sono **test di OCR e
|
|
145
|
+
associazione**, non una valutazione generale di foto, diagrammi o screenshot.
|
|
146
|
+
Le risposte attese e `evaluation.evidence` restano fuori da `body`, quindi non
|
|
147
|
+
vengono inviate ai modelli. Nessuna immagine remota viene scaricata dal benchmark.
|
|
148
|
+
|
|
149
|
+
```powershell
|
|
150
|
+
# Ispezionare/esportare i 12 input prima di usarli; nessuna chiamata LLM
|
|
151
|
+
node scripts/bench-proxy.js --suite quality --formats responses --list
|
|
152
|
+
node scripts/bench-proxy.js --suite quality --formats responses --export-fixtures quality-fixtures.json
|
|
153
|
+
|
|
154
|
+
# Replay offline: 12 casi × 2 modelli × 4 flow = 96 campioni
|
|
155
|
+
npm run bench:models -- --suite quality --presets none,headroom,headroom-pxpipe,headroom-pxpipe-native-bypass --repetitions 1 --warmup 0
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
Gli alias **solo benchmark** `pxpipe-native-bypass`,
|
|
159
|
+
`headroom-pxpipe-native-bypass`, `rtk-pxpipe-native-bypass` e
|
|
160
|
+
`rtk-headroom-pxpipe-native-bypass` usano la ricetta reale corrispondente, ma
|
|
161
|
+
saltano **solo pxpipe** quando la richiesta originale contiene immagini native.
|
|
162
|
+
Il rilevamento avviene prima di RTK/Headroom, comprende contenuti multimodali e
|
|
163
|
+
risultati di tool; ignora schemi, metadata e JSON citato come testo. Lo stadio
|
|
164
|
+
registra `native_images_present`, non un risparmio vision inventato.
|
|
165
|
+
|
|
166
|
+
Gli alias non sono inclusi nei 7 flow di default e non cambiano la configurazione
|
|
167
|
+
quotidiana. I flow senza suffisso mantengono il comportamento precedente.
|
|
168
|
+
Headroom/RTK restano attivi dove applicabili: il bypass di pxpipe **non è una
|
|
169
|
+
garanzia** che un altro stadio preservi l'allegato. Anche questo viene verificato.
|
|
170
|
+
Con tutti gli 11 flow e i 2 modelli, la suite qualità richiede **264 campioni per
|
|
171
|
+
round**; aggiungere `--live` li renderebbe altrettanti tentativi provider.
|
|
172
|
+
|
|
173
|
+
Nuovi controlli e campi del report:
|
|
174
|
+
|
|
175
|
+
- `answerChecks.exact`: uguaglianza case-sensitive, ignorando soltanto whitespace
|
|
176
|
+
iniziale/finale; niente spiegazioni aggiuntive;
|
|
177
|
+
- `answerChecks.jsonEquals`: JSON valido, nessun fence o prosa, stesso oggetto o
|
|
178
|
+
array atteso, stessi tipi/valori e nessuna chiave extra; ordine delle chiavi
|
|
179
|
+
irrilevante, chiavi duplicate rifiutate anche con escape Unicode;
|
|
180
|
+
- `answerChecks.maxChars`: tetto alla lunghezza, combinabile con gli altri check;
|
|
181
|
+
- `imageIntegrity`: hash del contenuto e di tutti gli attributi delle immagini
|
|
182
|
+
native, molteplicità, ordine relativo, raggruppamento e associazione a ruolo,
|
|
183
|
+
call ID e testo co-locato. Indici assoluti possono cambiare quando vengono
|
|
184
|
+
inseriti messaggi sintetici. Un cambio del testo co-locato viene segnalato in
|
|
185
|
+
modo conservativo, anche se una valutazione umana potrebbe ritenerlo innocuo;
|
|
186
|
+
- `addedOrChanged` conta immagini nuove **o native modificate**, non le presume
|
|
187
|
+
tutte correttamente generate. `nativeImagesRetained` non è un punteggio vision;
|
|
188
|
+
- `evidence` distingue risposte ancora disponibili nel testo da casi che
|
|
189
|
+
richiedono immagini native o renderizzate. Non è una validazione OCR.
|
|
190
|
+
|
|
191
|
+
Il selettore esclude un candidato con perdita/alterazione degli allegati anche
|
|
192
|
+
se la risposta supera i controlli. Nei casi dichiarati `rendered_context`, se
|
|
193
|
+
pxpipe si applica ma lascia la risposta nel testo (per esempio nella factsheet),
|
|
194
|
+
segnala `vision_evidence_not_discriminating`: quel pass non prova lettura delle
|
|
195
|
+
immagini. Una vera valutazione live rimane necessaria; il replay offline non
|
|
196
|
+
produce punteggi di comprensione visiva né sceglie un vincitore.
|
|
197
|
+
|
|
121
198
|
### GPT-6 Astra e Fable 5.1 sullo stesso corpus
|
|
122
199
|
|
|
123
200
|
Il comando dedicato seleziona gli ID del gateway `gpt-6-astra` e
|
|
124
201
|
`anthropic/claude-fable-5-1`, sul medesimo protocollo Responses:
|
|
125
202
|
|
|
126
203
|
```powershell
|
|
127
|
-
# Replay offline: 20 fixture ×
|
|
204
|
+
# Replay offline: 20 fixture × 7 flow = 140 campioni
|
|
128
205
|
npm run bench:models -- --repetitions 1 --warmup 0
|
|
129
206
|
|
|
130
|
-
# Smoke live: al massimo
|
|
131
|
-
npm run bench:models -- --live --upstream http://127.0.0.1:10100 --repetitions 1 --warmup 0 --max-live-calls
|
|
207
|
+
# Smoke live: al massimo 140 chiamate complessive, senza retry del runner
|
|
208
|
+
npm run bench:models -- --live --responses-stream --upstream http://127.0.0.1:10100 --repetitions 1 --warmup 0 --max-live-calls 140 --stop-on-error
|
|
209
|
+
|
|
210
|
+
# Solo baseline e nuova combinazione: 10 casi × 2 flow × 2 modelli = 40 chiamate
|
|
211
|
+
npm run bench:models -- --presets none,rtk-headroom-pxpipe --live --responses-stream --upstream http://127.0.0.1:10100 --repetitions 1 --warmup 0 --max-live-calls 40
|
|
132
212
|
```
|
|
133
213
|
|
|
134
214
|
Richiede un gateway che supporti **entrambi i modelli via Responses**; un endpoint
|
|
@@ -141,6 +221,14 @@ I costi vision locali per questi modelli non vengono ricavati arbitrariamente
|
|
|
141
221
|
da profili più vecchi: dove non supportati restano sconosciuti. La misura di
|
|
142
222
|
riferimento nel test live è l'usage restituito dal gateway/provider.
|
|
143
223
|
|
|
224
|
+
Gli upstream ChatGPT/Codex possono richiedere `stream: true` anche quando OCX
|
|
225
|
+
accetta sintatticamente il non-stream. Usare `--responses-stream`: il runner
|
|
226
|
+
consuma SSE fino all'evento terminale. Se il terminale omette l'output (come può
|
|
227
|
+
accadere con Astra), ricostruisce il testo dagli item finalizzati
|
|
228
|
+
`response.output_item.done`; l'usage proviene sempre dal terminale. I soli delta
|
|
229
|
+
non bastano a dichiarare una risposta completa. Stream
|
|
230
|
+
troncati o senza evento terminale restano errori, non risposte completate.
|
|
231
|
+
|
|
144
232
|
### Endpoint e credenziali
|
|
145
233
|
|
|
146
234
|
```powershell
|
|
@@ -156,6 +244,12 @@ Le credenziali sono opzionali per gateway locali che non le richiedono; non
|
|
|
156
244
|
vengono mai cercate automaticamente negli account o nei file dell'utente.
|
|
157
245
|
|
|
158
246
|
Il collector inoltra al provider **il payload realmente trasformato dal proxy**.
|
|
247
|
+
Con `--upstream http://127.0.0.1:10100` la catena è quindi
|
|
248
|
+
`runner → proxy privato del preset → collector privato → OCX`, **non** il proxy
|
|
249
|
+
quotidiano `rtk-pxpipe → OCX`. Il runner usa l'upstream esplicito, non quello del
|
|
250
|
+
client Codex; impostarlo invece alla porta del proxy quotidiano reintrodurrebbe
|
|
251
|
+
la doppia trasformazione. Le istanze proxy sono private, mentre OCX e il servizio
|
|
252
|
+
Headroom rimangono condivisi e non vengono riavviati o riconfigurati.
|
|
159
253
|
Ogni fixture pone una domanda con risposta nota contenuta nel tool output;
|
|
160
254
|
`answerChecks` valuta la risposta reale. I report includono:
|
|
161
255
|
|
|
@@ -166,9 +260,12 @@ Ogni fixture pone una domanda con risposta nota contenuta nel tool output;
|
|
|
166
260
|
|
|
167
261
|
Per Anthropic l'input normalizzato comprende input non-cached + letture/scritture
|
|
168
262
|
cache, evitando di confrontare scope diversi. Campi non restituiti restano null.
|
|
169
|
-
|
|
263
|
+
Di default streaming viene disabilitato; `--responses-stream` lo abilita solo per
|
|
264
|
+
Responses. Le Responses hanno `store: false` e non usano background jobs,
|
|
170
265
|
Chat usa una singola completion, e le risposte
|
|
171
|
-
|
|
266
|
+
richiedono il limite `--max-output-tokens` (default 256). Il gateway/provider può
|
|
267
|
+
ignorarlo: l'adapter ChatGPT di OCX osservato rimuove `max_output_tokens`, quindi
|
|
268
|
+
non è una garanzia di budget. Vengono utilizzati bearer
|
|
172
269
|
auth per OpenAI-compatible e `x-api-key` per Anthropic; redirect sono bloccati.
|
|
173
270
|
|
|
174
271
|
**Non è un agente autonomo:** nessun tool viene eseguito, nessun retry o follow-up
|
|
@@ -189,6 +286,8 @@ casi applicabili × flow (incluso none) × (warmup + repetitions)
|
|
|
189
286
|
Il numero viene mostrato prima delle chiamate; `--max-live-calls` (default 200)
|
|
190
287
|
blocca piani più grandi prima di inviare richieste. Per una campagna più ampia,
|
|
191
288
|
aumentare esplicitamente questo limite oppure ridurre corpus/rounds.
|
|
289
|
+
Il limite conta i tentativi HTTP del runner: eventuali retry o fallback interni
|
|
290
|
+
del gateway non sono sotto il suo controllo e vanno verificati nei log di OCX.
|
|
192
291
|
|
|
193
292
|
Non c'è controllo della cache remota: fissare modello/versioni/configurazioni e
|
|
194
293
|
ripetere le campagne. Ordine randomizzato riduce, ma non elimina, il bias della
|
|
@@ -227,7 +326,8 @@ Esempio minimo:
|
|
|
227
326
|
`checks.toolIncludes` cerca solo nei risultati dei tool; `requestIncludes` nel
|
|
228
327
|
testo nativo della richiesta. Le stringhe devono esistere già nell'originale.
|
|
229
328
|
`answerChecks.includes/excludes` sono confronti letterali case-sensitive, non un
|
|
230
|
-
LLM judge;
|
|
329
|
+
LLM judge; `exact`, `jsonEquals` e `maxChars` consentono controlli più rigorosi.
|
|
330
|
+
Non inserire le risposte nella domanda. Omettere `answerChecks` lascia
|
|
231
331
|
la risposta non valutata, e impedisce una raccomandazione live. Le fixture
|
|
232
332
|
integrate includono definizioni/coppie dei tool complete; rispettare i vincoli
|
|
233
333
|
del proprio provider nelle fixture personalizzate. Non usare riferimenti a
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@drakonkat/ai-helper",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.3",
|
|
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",
|
|
@@ -37,10 +37,10 @@
|
|
|
37
37
|
"scripts": {
|
|
38
38
|
"start": "node ./bin/cli.js",
|
|
39
39
|
"dev": "node ./bin/cli.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",
|
|
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 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",
|
|
41
41
|
"bench:proxy": "node scripts/bench-proxy.js",
|
|
42
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",
|
|
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 test/benchmark-multimodal.test.js",
|
|
44
44
|
"build": "bun run scripts/build.js",
|
|
45
45
|
"install-bin": "bun run scripts/install-bin.js"
|
|
46
46
|
},
|
package/scripts/bench-proxy.js
CHANGED
|
@@ -4,13 +4,15 @@ import { readFile, mkdir, writeFile, appendFile, readdir } from "node:fs/promise
|
|
|
4
4
|
import { resolve, join } from "node:path";
|
|
5
5
|
import { randomBytes } from "node:crypto";
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
7
|
-
import { runBenchmark, prepareBenchmark, BENCHMARK_PRESETS } from "../src/benchmark/runner.js";
|
|
7
|
+
import { runBenchmark, prepareBenchmark, BENCHMARK_PRESETS, SUPPORTED_BENCHMARK_PRESETS } from "../src/benchmark/runner.js";
|
|
8
8
|
import { buildReport, reportCsv, reportMarkdown } from "../src/benchmark/report.js";
|
|
9
9
|
|
|
10
10
|
const HELP = `Usage: node scripts/bench-proxy.js [options]
|
|
11
11
|
|
|
12
12
|
Offline by default: private loopback proxies and real compressors; no provider call.
|
|
13
|
-
--presets LIST ${
|
|
13
|
+
--presets LIST ${SUPPORTED_BENCHMARK_PRESETS.join(",")}
|
|
14
|
+
Default: ${BENCHMARK_PRESETS.join(",")}; none always included
|
|
15
|
+
--suite NAME core (default), quality (12 stronger Responses cases), all
|
|
14
16
|
--formats LIST responses,chat,anthropic (default: all)
|
|
15
17
|
--transports LIST http,ws (default: http; WS only for Responses)
|
|
16
18
|
--fixtures FILE JSON array of custom fixtures instead of built-in corpus
|
|
@@ -28,6 +30,7 @@ Offline by default: private loopback proxies and real compressors; no provider c
|
|
|
28
30
|
--out DIR New output directory (default: benchmark-results/<run-id>)
|
|
29
31
|
--save-payloads Opt-in originals/transformed payloads and live answers; may contain sensitive data
|
|
30
32
|
--live EXPLICITLY enable potentially billable provider calls
|
|
33
|
+
--responses-stream Request SSE for Responses (required by ChatGPT/Codex upstreams)
|
|
31
34
|
--upstream URL Live provider root BEFORE /v1, e.g. http://127.0.0.1:10100
|
|
32
35
|
--api-key-env NAME Environment variable holding credentials (never written to reports)
|
|
33
36
|
--max-output-tokens N Live answer cap (default: 256; no tool execution or retries)
|
|
@@ -44,15 +47,16 @@ Offline runs never claim a semantic-quality winner. See docs/benchmark.md.
|
|
|
44
47
|
`;
|
|
45
48
|
|
|
46
49
|
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"];
|
|
50
|
+
const strings = ["presets", "suite", "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"];
|
|
51
|
+
const booleans = ["help", "list", "save-payloads", "live", "responses-stream", "stop-on-error"];
|
|
49
52
|
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
53
|
if (values.help) { console.log(HELP); return 0; }
|
|
51
54
|
const list = name => values[name] === undefined ? undefined : values[name].split(",").map(s => s.trim());
|
|
52
55
|
const numeric = name => values[name] === undefined ? undefined : Number(values[name]);
|
|
53
56
|
const formats = list("formats");
|
|
54
57
|
if (formats && (formats.some(f => !["responses", "chat", "anthropic"].includes(f)) || new Set(formats).size !== formats.length)) throw new Error("Invalid formats list");
|
|
55
|
-
|
|
58
|
+
if (values.fixtures && values.suite) throw new Error("Use --fixtures OR --suite, not both");
|
|
59
|
+
const preview = values.list || values["export-fixtures"] ? prepareBenchmark({ model: values.model, compareModels: list("compare-models"), formats, suite: values.suite, presets: ["none"] }).fixtures : null;
|
|
56
60
|
if (values.list) { console.log(preview.map(f => `${f.id}\t${f.format}\t${f.category}`).join("\n")); return 0; }
|
|
57
61
|
if (values["export-fixtures"]) {
|
|
58
62
|
const file = resolve(values["export-fixtures"]);
|
|
@@ -65,11 +69,11 @@ export async function main(argv = process.argv.slice(2)) {
|
|
|
65
69
|
const thresholds = { maxQualityDrop: numeric("max-quality-drop") ?? 0, maxLatencyRegression: numeric("max-latency-regression") ?? 25 };
|
|
66
70
|
if (Object.values(thresholds).some(n => !Number.isFinite(n) || n < 0)) throw new Error("Thresholds must be nonnegative numbers");
|
|
67
71
|
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"),
|
|
72
|
+
const options = { presets: list("presets"), suite: values.suite, formats, transports: list("transports"), fixtures, model: values.model, compareModels: list("compare-models"),
|
|
69
73
|
repetitions: numeric("repetitions"), warmup: numeric("warmup"), seed: numeric("seed"),
|
|
70
74
|
headroomUrl: values["headroom-url"], rtkFilter: values["rtk-filter"], models: values.models,
|
|
71
75
|
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") };
|
|
76
|
+
upstream: values.upstream, apiKey, responsesStream: values["responses-stream"], maxOutputTokens: numeric("max-output-tokens"), maxLiveCalls: numeric("max-live-calls") };
|
|
73
77
|
const prepared = prepareBenchmark(options); // Validate before creating/reserving any output files.
|
|
74
78
|
const directory = resolve(values.out || join("benchmark-results", `${new Date().toISOString().replace(/[:.]/g, "-")}-${randomBytes(3).toString("hex")}`));
|
|
75
79
|
await mkdir(directory, { recursive: true });
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import { evaluatePreservation } from "./quality.js";
|
|
1
|
+
import { evaluatePreservation, validateAnswerChecks, requestTexts } from "./quality.js";
|
|
2
|
+
import { qualityFixtures } from "./quality-fixtures.js";
|
|
3
|
+
import { requestImages } from "../request-images.js";
|
|
2
4
|
|
|
3
5
|
const PATHS = { responses: "/v1/responses", chat: "/v1/chat/completions", anthropic: "/v1/messages" };
|
|
4
6
|
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.";
|
|
@@ -100,17 +102,19 @@ function request(format, model, scenario) {
|
|
|
100
102
|
}
|
|
101
103
|
|
|
102
104
|
/** Thirty reproducible, secret-free requests; commands are data, never executed. */
|
|
103
|
-
export function builtInFixtures({ model = "gpt-5.5", formats = Object.keys(PATHS) } = {}) {
|
|
105
|
+
export function builtInFixtures({ model = "gpt-5.5", formats = Object.keys(PATHS), suite = "core" } = {}) {
|
|
104
106
|
if (typeof model !== "string" || !model.trim()) throw new Error("fixture model must be a nonempty string");
|
|
105
107
|
if (!Array.isArray(formats) || !formats.length || formats.some(format => !Object.hasOwn(PATHS, format)) || new Set(formats).size !== formats.length) {
|
|
106
108
|
throw new Error(`fixture formats must be a nonempty, unique subset of: ${Object.keys(PATHS).join(", ")}`);
|
|
107
109
|
}
|
|
108
|
-
|
|
110
|
+
if (!["core", "quality", "all"].includes(suite)) throw new Error("fixture suite must be core, quality or all");
|
|
111
|
+
const core = suite === "quality" ? [] : formats.flatMap(format => scenarios().map(scenario => ({
|
|
109
112
|
id: `${format}-${scenario.id}`, category: scenario.category, format, path: PATHS[format],
|
|
110
113
|
body: request(format, model, scenario),
|
|
111
114
|
checks: { toolIncludes: [...(scenario.preserve || scenario.expected)], requestIncludes: [scenario.question] },
|
|
112
115
|
answerChecks: { includes: [...scenario.expected] },
|
|
113
116
|
})));
|
|
117
|
+
return [...core, ...(suite === "core" ? [] : qualityFixtures({ model, formats }))];
|
|
114
118
|
}
|
|
115
119
|
|
|
116
120
|
function object(value) { return value !== null && typeof value === "object" && !Array.isArray(value); }
|
|
@@ -141,7 +145,15 @@ export function validateFixtures(input) {
|
|
|
141
145
|
} else if (!Array.isArray(fixture.body.messages) || !fixture.body.messages.length) throw new Error(`${where}.body.messages must be a nonempty array`);
|
|
142
146
|
if (fixture.body.tools !== undefined && !Array.isArray(fixture.body.tools)) throw new Error(`${where}.body.tools must be an array`);
|
|
143
147
|
checkArrays(fixture.checks, ["toolIncludes", "requestIncludes"], `${where}.checks`);
|
|
144
|
-
if (fixture.answerChecks !== undefined)
|
|
148
|
+
if (fixture.answerChecks !== undefined) validateAnswerChecks(fixture.answerChecks, `${where}.answerChecks`);
|
|
149
|
+
if (fixture.evaluation !== undefined) {
|
|
150
|
+
const e = fixture.evaluation;
|
|
151
|
+
if (!object(e) || !["rendered_context", "native_image"].includes(e.kind) || Object.keys(e).some(k => !["kind", "evidence"].includes(k)) ||
|
|
152
|
+
!Array.isArray(e.evidence) || !e.evidence.length || e.evidence.some(x => typeof x !== "string" || !x.trim())) throw new Error(`${where}.evaluation requires kind and nonempty evidence strings`);
|
|
153
|
+
const nativeText = requestTexts(fixture.body).join("\n");
|
|
154
|
+
if (e.kind === "native_image" && (!requestImages(fixture.body).length || e.evidence.some(x => nativeText.includes(x)))) throw new Error(`${where}.evaluation native-image evidence must be absent from native text and images must exist`);
|
|
155
|
+
if (e.kind === "rendered_context" && e.evidence.some(x => !nativeText.includes(x))) throw new Error(`${where}.evaluation rendered-context evidence must exist in original text`);
|
|
156
|
+
}
|
|
145
157
|
const quality = evaluatePreservation(fixture.body, fixture.body, fixture.checks);
|
|
146
158
|
const invalid = quality.checks.find(check => check.reason === "not_in_original");
|
|
147
159
|
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"}`);
|
package/src/benchmark/live.js
CHANGED
|
@@ -20,6 +20,121 @@ export async function readLimited(response, maxBytes) {
|
|
|
20
20
|
return Buffer.concat(chunks).toString("utf8");
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
+
async function readResponsesStream(response, maxBytes, start) {
|
|
24
|
+
const reader = response.body.getReader();
|
|
25
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
26
|
+
const finalizedItems = new Map(), finalizedIds = new Map();
|
|
27
|
+
let size = 0, buffer = "", scanOffset = 0, event = "", data = [], firstOutputMs = null;
|
|
28
|
+
function finalizedItem(value) {
|
|
29
|
+
const { item, output_index: index } = value;
|
|
30
|
+
if (!Number.isSafeInteger(index) || index < 0 || !item || typeof item !== "object" || Array.isArray(item) ||
|
|
31
|
+
typeof item.id !== "string" || !item.id || typeof item.type !== "string" || !item.type || item.status === "in_progress") {
|
|
32
|
+
throw new Error("Provider SSE contained an invalid finalized output item");
|
|
33
|
+
}
|
|
34
|
+
if ((finalizedIds.has(item.id) && finalizedIds.get(item.id) !== index) ||
|
|
35
|
+
(finalizedItems.has(index) && JSON.stringify(finalizedItems.get(index)) !== JSON.stringify(item))) {
|
|
36
|
+
throw new Error("Provider SSE contained conflicting finalized output items");
|
|
37
|
+
}
|
|
38
|
+
finalizedItems.set(index, item); finalizedIds.set(item.id, index);
|
|
39
|
+
}
|
|
40
|
+
function mergedOutput(terminal) {
|
|
41
|
+
const items = new Map(finalizedItems), terminalIds = new Set();
|
|
42
|
+
for (const [position, item] of (terminal.output || []).entries()) {
|
|
43
|
+
if (!item || typeof item !== "object" || Array.isArray(item) || typeof item.type !== "string") throw new Error("Provider SSE contained an invalid terminal response");
|
|
44
|
+
const index = finalizedIds.get(item.id) ?? position, previous = items.get(index);
|
|
45
|
+
if ((item.id && terminalIds.has(item.id)) || (previous && (previous.type !== item.type ||
|
|
46
|
+
(item.id && previous.id && item.id !== previous.id)))) throw new Error("Provider SSE contained an invalid terminal response");
|
|
47
|
+
if (item.id) terminalIds.add(item.id);
|
|
48
|
+
// The terminal item wins over its earlier finalized event, but absent
|
|
49
|
+
// items retain their finalized content. Never reconstruct from deltas.
|
|
50
|
+
items.set(index, item);
|
|
51
|
+
}
|
|
52
|
+
const output = [...items].sort(([a], [b]) => a - b).map(([, item]) => item);
|
|
53
|
+
const restored = output.length > (terminal.output || []).length;
|
|
54
|
+
const merged = { ...terminal, output };
|
|
55
|
+
if (restored && merged.output_text === "") delete merged.output_text;
|
|
56
|
+
return { merged, restored };
|
|
57
|
+
}
|
|
58
|
+
function line(text) {
|
|
59
|
+
if (text.startsWith(":")) return null;
|
|
60
|
+
if (text) {
|
|
61
|
+
const colon = text.indexOf(":");
|
|
62
|
+
const field = colon < 0 ? text : text.slice(0, colon);
|
|
63
|
+
const content = colon < 0 ? "" : text.slice(colon + 1).replace(/^ /, "");
|
|
64
|
+
if (field === "event") event = content;
|
|
65
|
+
else if (field === "data") data.push(content);
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
const name = event, payload = data.join("\n");
|
|
69
|
+
event = ""; data = [];
|
|
70
|
+
if (!payload) return null;
|
|
71
|
+
if (payload === "[DONE]") throw new Error("Provider SSE ended without a terminal response");
|
|
72
|
+
let value;
|
|
73
|
+
try { value = JSON.parse(payload); }
|
|
74
|
+
catch { throw new Error("Provider SSE contained invalid event data"); }
|
|
75
|
+
if (!value || typeof value !== "object" || Array.isArray(value) ||
|
|
76
|
+
(name && value.type && name !== value.type)) throw new Error("Provider SSE contained invalid event data");
|
|
77
|
+
const type = value.type || name;
|
|
78
|
+
if (type === "response.output_text.delta" && typeof value.delta === "string" && value.delta.length && firstOutputMs === null) firstOutputMs = performance.now() - start;
|
|
79
|
+
if (type === "response.output_item.done") { finalizedItem(value); return null; }
|
|
80
|
+
if (type === "error") throw new Error("Provider SSE reported an error");
|
|
81
|
+
if (!["response.completed", "response.incomplete", "response.failed"].includes(type)) return null;
|
|
82
|
+
const terminal = value.response, status = type.slice("response.".length);
|
|
83
|
+
if (!terminal || typeof terminal !== "object" || Array.isArray(terminal) || terminal.status !== status ||
|
|
84
|
+
(terminal.output !== undefined && !Array.isArray(terminal.output)) ||
|
|
85
|
+
(status !== "failed" && !Array.isArray(terminal.output) && typeof terminal.output_text !== "string" && !finalizedItems.size)) {
|
|
86
|
+
throw new Error("Provider SSE contained an invalid terminal response");
|
|
87
|
+
}
|
|
88
|
+
let parsed, restored;
|
|
89
|
+
try {
|
|
90
|
+
const result = mergedOutput(terminal); restored = result.restored;
|
|
91
|
+
parsed = parseProviderResponse(result.merged, "responses");
|
|
92
|
+
if (result.merged.output.some(item => item.status === "incomplete")) parsed.complete = false;
|
|
93
|
+
}
|
|
94
|
+
catch { throw new Error("Provider SSE contained an invalid terminal response"); }
|
|
95
|
+
const missingFinalText = firstOutputMs !== null && !parsed.text && !parsed.additionalToolCalls;
|
|
96
|
+
return { ...parsed, firstOutputMs, outputFromFinalizedItems: restored,
|
|
97
|
+
...(missingFinalText ? { complete: false, error: "Provider SSE ended without finalized output text" } : {}),
|
|
98
|
+
...(status === "failed" ? { error: "Provider response failed" } : {}) };
|
|
99
|
+
}
|
|
100
|
+
function consume(final = false) {
|
|
101
|
+
let offset = 0, index = scanOffset;
|
|
102
|
+
for (; index < buffer.length; index++) {
|
|
103
|
+
if (buffer[index] !== "\n" && buffer[index] !== "\r") continue;
|
|
104
|
+
// A CR and LF can arrive in separate network chunks.
|
|
105
|
+
if (buffer[index] === "\r" && index === buffer.length - 1 && !final) break;
|
|
106
|
+
const result = line(buffer.slice(offset, index));
|
|
107
|
+
if (buffer[index] === "\r" && buffer[index + 1] === "\n") index++;
|
|
108
|
+
offset = index + 1;
|
|
109
|
+
if (result) return result;
|
|
110
|
+
}
|
|
111
|
+
buffer = buffer.slice(offset);
|
|
112
|
+
scanOffset = index - offset;
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
try {
|
|
116
|
+
while (true) {
|
|
117
|
+
const { value, done } = await reader.read();
|
|
118
|
+
if (done) {
|
|
119
|
+
buffer += decoder.decode();
|
|
120
|
+
const terminal = consume(true);
|
|
121
|
+
if (terminal) return terminal;
|
|
122
|
+
throw new Error("Provider SSE ended without a terminal response");
|
|
123
|
+
}
|
|
124
|
+
size += value.byteLength;
|
|
125
|
+
if (size > maxBytes) throw new Error("Response exceeds benchmark maxBodyBytes");
|
|
126
|
+
buffer += decoder.decode(value, { stream: true });
|
|
127
|
+
const terminal = consume();
|
|
128
|
+
if (terminal) return terminal;
|
|
129
|
+
}
|
|
130
|
+
} finally {
|
|
131
|
+
// Providers may keep SSE sockets open after a terminal event. Do not wait
|
|
132
|
+
// for EOF, leak a reader, or accept subsequent contradictory/delta events.
|
|
133
|
+
await reader.cancel().catch(() => {});
|
|
134
|
+
reader.releaseLock();
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
23
138
|
export async function callProvider(body, fixture, options) {
|
|
24
139
|
const headers = { "content-type": "application/json" };
|
|
25
140
|
if (options.apiKey) {
|
|
@@ -33,12 +148,26 @@ export async function callProvider(body, fixture, options) {
|
|
|
33
148
|
method: "POST", headers, body: JSON.stringify(body), redirect: "error",
|
|
34
149
|
signal: options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(options.timeoutMs)]) : AbortSignal.timeout(options.timeoutMs),
|
|
35
150
|
});
|
|
151
|
+
if (response.ok && fixture.format === "responses" && /^text\/event-stream(?:\s*;|\s*$)/i.test(response.headers.get("content-type") || "")) {
|
|
152
|
+
try {
|
|
153
|
+
const parsed = await readResponsesStream(response, options.maxBodyBytes, start);
|
|
154
|
+
return { status: response.status, durationMs: performance.now() - start, ...parsed };
|
|
155
|
+
} catch (error) {
|
|
156
|
+
// Only locally constructed diagnostics survive; never JSON parser errors,
|
|
157
|
+
// provider event bodies, echoed prompts or credentials.
|
|
158
|
+
const safe = ["Provider SSE ended without a terminal response", "Provider SSE contained invalid event data",
|
|
159
|
+
"Provider SSE reported an error", "Provider SSE contained an invalid terminal response", "Response exceeds benchmark maxBodyBytes",
|
|
160
|
+
"Provider SSE contained an invalid finalized output item", "Provider SSE contained conflicting finalized output items"];
|
|
161
|
+
return { status: response.status, durationMs: performance.now() - start, complete: false,
|
|
162
|
+
error: safe.includes(error.message) ? error.message : "Provider SSE could not be read" };
|
|
163
|
+
}
|
|
164
|
+
}
|
|
36
165
|
const raw = await readLimited(response, options.maxBodyBytes);
|
|
37
166
|
const durationMs = performance.now() - start;
|
|
38
167
|
// Never put provider error bodies (which can echo credentials/prompts) in reports.
|
|
39
168
|
if (!response.ok) return { status: response.status, durationMs, error: `Provider HTTP ${response.status}` };
|
|
40
169
|
let value;
|
|
41
|
-
try { value = JSON.parse(raw); } catch { return { status: response.status, durationMs, error: "Provider did not return JSON
|
|
170
|
+
try { value = JSON.parse(raw); } catch { return { status: response.status, durationMs, error: "Provider did not return JSON or a supported Responses SSE stream" }; }
|
|
42
171
|
try { return { status: response.status, durationMs, ...parseProviderResponse(value, fixture.format) }; }
|
|
43
172
|
catch { return { status: response.status, durationMs, error: "Provider returned an invalid response shape" }; }
|
|
44
173
|
}
|