@drakonkat/ai-helper 1.2.9 → 1.2.11
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 +21 -0
- package/README.md +30 -2
- package/docs/pxpipe-performance-2026-09-30.md +205 -0
- package/package.json +3 -2
- package/src/proxy-presets.js +13 -4
- package/src/proxy-stats.js +24 -10
- package/src/proxy.js +47 -8
- package/src/tui.js +23 -1
- package/src/utils/process.js +15 -9
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,27 @@ All notable changes to **`ai-helper` (`aih`)** are documented in this file.
|
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
+
## [1.2.11] - 2026-09-30
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
- Upgrade the embedded `pxpipe-proxy` dependency from 0.13.2 to 0.14.0 and synchronize npm and Bun lockfiles.
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
- Document offline CPU profiling, opaque-data tokenization costs, and isolated worker-thread experiments. These experiments do not change production proxy processing.
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
## [1.2.10] - 2026-09-29
|
|
18
|
+
|
|
19
|
+
### Added
|
|
20
|
+
- Show preset processing time, upstream response-header latency, total HTTP/SSE duration, upstream status and interrupted/failed responses in the live request stream. WebSocket events report preset time only.
|
|
21
|
+
- Regression coverage for streaming, concurrent requests, transport failures, cancellation and timing persistence without duplicate counters.
|
|
22
|
+
|
|
23
|
+
### Fixed
|
|
24
|
+
- Close parent log descriptors after spawning detached services and allow cold Windows process discovery to finish in CI.
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
7
28
|
## [1.2.9] - 2026-09-29
|
|
8
29
|
|
|
9
30
|
### Added
|
package/README.md
CHANGED
|
@@ -197,11 +197,33 @@ upgrade, restart the proxy and reopen the updated dashboard; a source checkout
|
|
|
197
197
|
can be run directly with `node bin/cli.js status --ui` to avoid an older global
|
|
198
198
|
installation taking precedence on PATH.
|
|
199
199
|
|
|
200
|
+
Request timings use a monotonic clock and appear on new events:
|
|
201
|
+
|
|
202
|
+
- `proxy`: preset processing, including request decompression and serialization,
|
|
203
|
+
but excluding client upload, custom interceptors and forwarding.
|
|
204
|
+
- `header`: time from dispatching the upstream HTTP request to receiving its
|
|
205
|
+
response headers, including connection setup and upstream request upload.
|
|
206
|
+
This is **not** time to first model token; SSE headers can arrive before output.
|
|
207
|
+
- `tot`: time from receiving the client's HTTP request headers until the proxy
|
|
208
|
+
finishes sending the response (or the connection fails/closes). Includes client
|
|
209
|
+
upload, preset/interceptor work, upstream waiting and streaming/downstream
|
|
210
|
+
backpressure; it does not confirm delivery to the client application.
|
|
211
|
+
|
|
212
|
+
HTTP/SSE entries also show the upstream HTTP status and incomplete/error states.
|
|
213
|
+
The existing event is updated without counting another request. A pending state
|
|
214
|
+
only means no completion was recorded (for example after a proxy crash), not a
|
|
215
|
+
global count of active calls. Updates do not bring evicted events back into the
|
|
216
|
+
bounded recent list. WebSocket events report **only preset time**: connection
|
|
217
|
+
duration and arbitrary response frames cannot safely be attributed to individual
|
|
218
|
+
calls. Missing/older timings remain `n/d`. Error responses that arrive normally
|
|
219
|
+
(such as HTTP 500) retain their status; a transport failure is marked separately
|
|
220
|
+
from a preset error. Preset `none` remains unrecorded.
|
|
221
|
+
|
|
200
222
|
Press **`d`** for source/configuration details and per-stage
|
|
201
223
|
before/after token counts, percentages and measurement methods. Unknown savings
|
|
202
224
|
remain unknown; partial estimates and token increases are explicitly marked.
|
|
203
|
-
The panels do not infer provider cache savings, costs,
|
|
204
|
-
active
|
|
225
|
+
The panels do not infer provider cache savings, costs, model-only latency or
|
|
226
|
+
active request counts. Preset `none` and interceptor-only traffic are not recorded.
|
|
205
227
|
|
|
206
228
|
A running process is not a health check, and the final upstream is not monitored.
|
|
207
229
|
Snapshot read time is separate from last-event time: an idle proxy is not stale
|
|
@@ -296,6 +318,12 @@ then the built-in proxy with these options:
|
|
|
296
318
|
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*"
|
|
297
319
|
```
|
|
298
320
|
|
|
321
|
+
The built-in proxy uses the pinned `pxpipe-proxy` **0.14.0** library. Update aih
|
|
322
|
+
to receive this embedded version; updating the separate global `pxpipe` command
|
|
323
|
+
does not update an older aih installation or standalone binary. See the
|
|
324
|
+
[offline CPU profiling report](docs/pxpipe-performance-2026-09-30.md) for measured
|
|
325
|
+
tokenization costs and worker-thread experiments.
|
|
326
|
+
|
|
299
327
|
Pass `--models` to `aih start` (or `aih up`) to override the proxy's model list:
|
|
300
328
|
|
|
301
329
|
```bash
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
# Profilazione pxpipe — 30 settembre 2026
|
|
2
|
+
|
|
3
|
+
Il progetto usava `pxpipe-proxy` **0.13.2**. È stato aggiornato a **0.14.0** in
|
|
4
|
+
`package.json`, `package-lock.json`, `bun.lock` e nell'installazione locale.
|
|
5
|
+
La build standalone è stata ricompilata con la nuova dipendenza.
|
|
6
|
+
La libreria usa ora `gpt-tokenizer` 4.0.0; il conteggio del progetto mantiene
|
|
7
|
+
la propria dipendenza diretta 3.4.0.
|
|
8
|
+
|
|
9
|
+
La profilazione identifica un problema riproducibile nel conteggio diagnostico
|
|
10
|
+
dei dati opachi. L'aggiornamento da solo non elimina questo caso lento.
|
|
11
|
+
La modifica alle statistiche e il multithreading descritti sotto sono esperimenti
|
|
12
|
+
isolati, non modifiche al proxy gestito in esecuzione.
|
|
13
|
+
|
|
14
|
+
## Ambiente e metodo
|
|
15
|
+
|
|
16
|
+
- Windows, Node.js 22.22.1, Intel i7-10700K: 8 core e 16 processori logici.
|
|
17
|
+
- RAM: circa 64 GiB. GPU: NVIDIA RTX 2080 Ti, 11 GiB.
|
|
18
|
+
- Benchmark HTTP locale esistente: 10 fixture Responses per modello,
|
|
19
|
+
`gpt-6-astra` e `anthropic/claude-opus-5-5`, preset `none` e `pxpipe`.
|
|
20
|
+
- Profili CPU V8 tramite Inspector, intervallo di campionamento 1 ms; misura
|
|
21
|
+
del tempo trascorso, CPU e ritardo massimo di un timer da 10 ms.
|
|
22
|
+
- Input di stress: fixture sintetica `responses-dense-context` da circa 149 kB,
|
|
23
|
+
con un elemento `reasoning.encrypted_content` aggiunto; confronto fra base64
|
|
24
|
+
pseudocasuale e una sequenza ripetitiva di `A` della stessa lunghezza.
|
|
25
|
+
- Nessuna chiamata a provider: i tempi sono locali e non includono una risposta LLM.
|
|
26
|
+
|
|
27
|
+
Le misure di stress sono singole osservazioni controllate, non una distribuzione
|
|
28
|
+
di latenza del traffico reale. I nomi `cold` dei file indicano cache del renderer
|
|
29
|
+
svuotata: la cache del tokenizer rimane attiva nel processo. Claude viene misurato
|
|
30
|
+
per primo; il campione GPT successivo può riutilizzare la tokenizzazione dello
|
|
31
|
+
stesso input. Pertanto non dimostrano che il problema riguardi solo Claude.
|
|
32
|
+
I processi separati permettono invece il confronto delle due versioni sul primo
|
|
33
|
+
campione Claude.
|
|
34
|
+
|
|
35
|
+
## Confronto delle versioni
|
|
36
|
+
|
|
37
|
+
Sul corpus ordinario il benchmark completa tutte le 40 richieste per versione,
|
|
38
|
+
con controlli di conservazione superati. Alcuni costi vision rimangono sconosciuti:
|
|
39
|
+
non si deduce da questo test una migliore qualità semantica o un risparmio fatturato.
|
|
40
|
+
|
|
41
|
+
| Versione / modello | Mediana HTTP con pxpipe | p95 HTTP con pxpipe |
|
|
42
|
+
|---|---:|---:|
|
|
43
|
+
| 0.13.2 / Astra | 3,1 ms | 327,7 ms |
|
|
44
|
+
| 0.14.0 / Astra | 2,6 ms | 335,1 ms |
|
|
45
|
+
| 0.13.2 / Claude | 3,1 ms | 253,5 ms |
|
|
46
|
+
| 0.14.0 / Claude | 3,8 ms | 269,3 ms |
|
|
47
|
+
|
|
48
|
+
Dieci richieste eterogenee per riga e un solo round non consentono di attribuire
|
|
49
|
+
significato statistico alle piccole differenze. L'inizializzazione e le cache
|
|
50
|
+
influenzano soprattutto il caso di contesto denso.
|
|
51
|
+
|
|
52
|
+
Il problema emerge con sequenze opache lunghe e ripetitive:
|
|
53
|
+
|
|
54
|
+
| Input / versione | Trasformazione locale | Ritardo massimo del timer |
|
|
55
|
+
|---|---:|---:|
|
|
56
|
+
| 128 KiB ripetitivi / 0.13.2 | 9,749 s | 9,385 s |
|
|
57
|
+
| 128 KiB ripetitivi / 0.14.0 | 9,667 s | 9,334 s |
|
|
58
|
+
| 256 KiB ripetitivi / 0.14.0 | 51,636 s | 51,265 s |
|
|
59
|
+
| 512 KiB base64 pseudocasuale / 0.14.0 | 0,870 s | 0,516 s |
|
|
60
|
+
| 512 KiB base64 in blocco immagine sintetico di tool / 0.14.0 | 0,665 s | 0,343 s |
|
|
61
|
+
|
|
62
|
+
Quindi conta anche la forma dei dati, non soltanto la dimensione. Lo stress con
|
|
63
|
+
`A` ripetute è intenzionalmente patologico; non rappresenta automaticamente una
|
|
64
|
+
cifratura o una PNG reale.
|
|
65
|
+
|
|
66
|
+
## Dove viene speso il tempo
|
|
67
|
+
|
|
68
|
+
In `pxpipe-proxy/dist/core/openai.js`, `transformOpenAIResponses` chiama
|
|
69
|
+
`measureResponsesComposition` prima della trasformazione. Questa funzione esegue
|
|
70
|
+
il tokenizer su `JSON.stringify(reasoning)`, includendo `encrypted_content`;
|
|
71
|
+
inoltre serializza alcuni output di tool contenenti immagini.
|
|
72
|
+
|
|
73
|
+
Il conteggio serve alla diagnostica della composizione. Nel caso ripetitivo:
|
|
74
|
+
|
|
75
|
+
- 128 KiB: **95,7%** dei campioni CPU è in `BytePairEncodingCore`.
|
|
76
|
+
- 256 KiB: **98,9%** dei campioni CPU è in `BytePairEncodingCore`.
|
|
77
|
+
|
|
78
|
+
`bytePairMerge` scansiona ripetutamente i ranghi per trovare il minimo ed elimina
|
|
79
|
+
elementi dagli array con `splice`. Su un pezzo molto lungo e ripetitivo questo
|
|
80
|
+
produce lavoro quadratico. La versione 4.0.0 del tokenizer mantiene questa
|
|
81
|
+
struttura: il suo aggiornamento non risolve il caso osservato.
|
|
82
|
+
|
|
83
|
+
La cache di tokenizzazione può nascondere il costo su un input identico già visto.
|
|
84
|
+
L'input cambiato nel test multithread forza nuovi conteggi. Un timer fermo per
|
|
85
|
+
oltre 51 secondi dimostra che la trasformazione può impedire al thread HTTP di
|
|
86
|
+
gestire tempestivamente altre connessioni, header e stream.
|
|
87
|
+
|
|
88
|
+
Questo fornisce una spiegazione plausibile dei ritardi del dashboard del 29
|
|
89
|
+
settembre. Non abbiamo profilato il payload esatto di quelle richieste: non è
|
|
90
|
+
ancora provato che contenessero lo stesso pattern patologico.
|
|
91
|
+
|
|
92
|
+
## Esperimento: evitare il conteggio dei dati opachi
|
|
93
|
+
|
|
94
|
+
Una copia separata di pxpipe 0.14.0 filtra `encrypted_content` e i blocchi immagine
|
|
95
|
+
**solo dalla copia usata per la diagnostica**. La richiesta originale continua
|
|
96
|
+
intatta nella trasformazione e nell'inoltro.
|
|
97
|
+
|
|
98
|
+
| Input Claude | 0.14.0 originale | Copia sperimentale | Accelerazione |
|
|
99
|
+
|---|---:|---:|---:|
|
|
100
|
+
| 128 KiB ripetitivi | 9,667 s | 0,415 s | circa 23× |
|
|
101
|
+
| 256 KiB ripetitivi | 51,636 s | 0,381 s | circa 135× |
|
|
102
|
+
|
|
103
|
+
Per il caso 256 KiB, gli SHA-256 dei payload in uscita coincidono in tutti e
|
|
104
|
+
quattro i confronti Claude/GPT, renderer freddo/caldo. Il probe controlla anche
|
|
105
|
+
la conservazione del reasoning opaco, delle immagini native e del modello.
|
|
106
|
+
|
|
107
|
+
Questa è una prova del margine di ottimizzazione, non una patch pronta per la
|
|
108
|
+
produzione: la diagnostica filtrata diventerebbe parziale. Una correzione stabile
|
|
109
|
+
deve dichiarare esplicitamente i byte opachi esclusi e non presentare il subtotale
|
|
110
|
+
come conteggio completo. Deve coprire anche compaction e altri media serializzati.
|
|
111
|
+
È preferibile una modifica nell'API upstream; una patch manuale a `node_modules`
|
|
112
|
+
verrebbe persa alla reinstallazione.
|
|
113
|
+
|
|
114
|
+
## Esperimento: due worker thread persistenti
|
|
115
|
+
|
|
116
|
+
I worker vengono inizializzati e riscaldati prima della misura. Le due richieste
|
|
117
|
+
hanno sequenze opache da 128 KiB diverse tra loro, per evitare un cache hit sul
|
|
118
|
+
pezzo lento; gli stessi input vengono poi inviati ai due worker. Un'asserzione
|
|
119
|
+
confronta gli hash degli output sequenziali e paralleli.
|
|
120
|
+
|
|
121
|
+
| Esecuzione | Tempo per il gruppo | Ritardo del thread principale |
|
|
122
|
+
|---|---:|---:|
|
|
123
|
+
| Due richieste sequenziali nel thread principale | 24,180 s | 12.185,5 ms |
|
|
124
|
+
| Una richiesta in un worker | 13,710 s | 16,0 ms |
|
|
125
|
+
| Due richieste in due worker | 13,777 s | 13,6 ms |
|
|
126
|
+
|
|
127
|
+
Il gruppo parallelo è **circa 1,75× più rapido**, con output identici. Il beneficio
|
|
128
|
+
più importante è la reattività del proxy: il thread delle connessioni continua
|
|
129
|
+
a lavorare mentre il tokenizer occupa altri core. Una singola richiesta non
|
|
130
|
+
diventa automaticamente più veloce solo spostandola in un worker.
|
|
131
|
+
|
|
132
|
+
Un'integrazione dovrebbe partire da due worker persistenti, una coda limitata,
|
|
133
|
+
propagazione degli errori e delle cancellazioni, e assegnazione stabile delle
|
|
134
|
+
sessioni per sfruttare le cache. Ogni worker ha tokenizer, atlanti e cache propri:
|
|
135
|
+
non conviene partire da 16 worker soltanto perché ci sono 16 processori logici.
|
|
136
|
+
I worker di Cloudflare citati da pxpipe sono un ambiente di esecuzione, non
|
|
137
|
+
l'implementazione Node `worker_threads`.
|
|
138
|
+
|
|
139
|
+
## GPU, cache e altre ottimizzazioni
|
|
140
|
+
|
|
141
|
+
La RTX 2080 Ti è disponibile, ma la libreria distribuita non espone un backend
|
|
142
|
+
GPU. Il renderer e i filtri PNG sono JavaScript; la compressione usa
|
|
143
|
+
`CompressionStream`. `@napi-rs/canvas` è una dipendenza di sviluppo upstream,
|
|
144
|
+
non il renderer nativo usato a runtime.
|
|
145
|
+
|
|
146
|
+
La GPU non elimina il conteggio diagnostico BPE. Nel caso da 256 KiB, anche
|
|
147
|
+
azzerando tutto il tempo fuori dal tokenizer il margine sarebbe solo circa
|
|
148
|
+
**1,1%**. Non è una misura di accelerazione GPU: è un limite ricavato dalla
|
|
149
|
+
composizione dei campioni CPU di questo caso. Un renderer GPU richiederebbe una
|
|
150
|
+
nuova implementazione e confronti di pixel, leggibilità e costi di trasferimento.
|
|
151
|
+
|
|
152
|
+
La cache delle immagini **esiste già**, con budget Node predefinito di 64 MiB.
|
|
153
|
+
Nei probe risulta un miss seguito da un hit, senza eviction o oggetti fuori budget.
|
|
154
|
+
Aumentarne il limite non risolve il conteggio opaco. Per molte richieste identiche
|
|
155
|
+
contemporanee, deduplicare i render in corso potrebbe evitare doppio lavoro;
|
|
156
|
+
il vantaggio va misurato sul traffico reale prima di aggiungere questa logica.
|
|
157
|
+
|
|
158
|
+
Ordine degli interventi:
|
|
159
|
+
|
|
160
|
+
1. Evitare la tokenizzazione di dati opachi/media per sola osservabilità,
|
|
161
|
+
mantenendo metriche parziali dichiarate e payload intatti.
|
|
162
|
+
2. Isolare la trasformazione dal thread HTTP con un piccolo pool persistente.
|
|
163
|
+
3. Se rimane un costo importante sul testo reale, confrontare un tokenizer
|
|
164
|
+
nativo o un algoritmo BPE più efficiente; nessun guadagno è stato misurato qui.
|
|
165
|
+
4. Ottimizzare renderer/cache soltanto se diventano dominanti dopo i primi passi.
|
|
166
|
+
|
|
167
|
+
## Verifiche e artefatti
|
|
168
|
+
|
|
169
|
+
- `npm test`: completato con exit code 0 dopo l'aggiornamento.
|
|
170
|
+
- `npm run build`: completato; nuova build in `dist/aih.exe`.
|
|
171
|
+
- Benchmark HTTP delle due versioni: 40/40 richieste riuscite ciascuno.
|
|
172
|
+
- `git diff --check`: superato.
|
|
173
|
+
- Durante i benchmark: nessuna chiamata a provider, installazione globale o riavvio dei servizi gestiti.
|
|
174
|
+
|
|
175
|
+
Gli input e i profili locali sono in
|
|
176
|
+
`benchmark-results/pxpipe-profile-2026-09-30/` (directory ignorata da Git):
|
|
177
|
+
|
|
178
|
+
- `core/report.md` e `updated-core/report.md`: benchmark HTTP prima/dopo.
|
|
179
|
+
- `probe.mjs`: misure e controlli eseguibili.
|
|
180
|
+
- `prepare-experiment.mjs`: creazione della copia sperimentale.
|
|
181
|
+
- `new-opaque-repeated-262144.json` e `sanitized-opaque-repeated-262144.json`.
|
|
182
|
+
- `new-opaque-repeated-262144-claude-cold.cpuprofile`: profilo V8 apribile nei DevTools.
|
|
183
|
+
- `new-threads.json`: confronto dei worker e hash degli output.
|
|
184
|
+
|
|
185
|
+
Esempi di ripetizione dalla root, con gli artefatti già presenti:
|
|
186
|
+
|
|
187
|
+
```powershell
|
|
188
|
+
node benchmark-results/pxpipe-profile-2026-09-30/probe.mjs --case opaque-repeated-262144
|
|
189
|
+
node benchmark-results/pxpipe-profile-2026-09-30/probe.mjs --sanitized --case opaque-repeated-262144
|
|
190
|
+
node benchmark-results/pxpipe-profile-2026-09-30/probe.mjs --case opaque-repeated-131072 --threads
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
La build locale aggiornata non sostituisce automaticamente il worker di un proxy
|
|
194
|
+
già avviato dall'installazione globale.
|
|
195
|
+
|
|
196
|
+
Per caricare la libreria aggiornata occorre installare ai-helper 1.2.11 e
|
|
197
|
+
riavviare il proxy con `aih restart proxy --json`. Aggiornare soltanto il pacchetto
|
|
198
|
+
globale `pxpipe-proxy` non aggiorna necessariamente la copia incorporata in
|
|
199
|
+
ai-helper o in un vecchio binario standalone. Su Windows, se il processo è stato
|
|
200
|
+
avviato con privilegi elevati, il riavvio richiede una PowerShell con gli stessi
|
|
201
|
+
privilegi; nel controllo locale la terminazione è stata negata con `Access is denied`.
|
|
202
|
+
|
|
203
|
+
Fonti primarie: [release pxpipe 0.14.0](https://github.com/teamchong/pxpipe/releases/tag/v0.14.0),
|
|
204
|
+
[Node.js 22: worker thread e pool persistenti](https://nodejs.org/docs/latest-v22.x/api/worker_threads.html).
|
|
205
|
+
Le misure e le conclusioni prestazionali sopra derivano dai profili locali.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@drakonkat/ai-helper",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.11",
|
|
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",
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
"scripts/build.js",
|
|
16
16
|
"scripts/bench-proxy.js",
|
|
17
17
|
"docs/benchmark.md",
|
|
18
|
+
"docs/pxpipe-performance-2026-09-30.md",
|
|
18
19
|
"README.md",
|
|
19
20
|
"LICENSE",
|
|
20
21
|
"ARCHITECTURE.md",
|
|
@@ -62,7 +63,7 @@
|
|
|
62
63
|
"license": "MIT",
|
|
63
64
|
"dependencies": {
|
|
64
65
|
"gpt-tokenizer": "3.4.0",
|
|
65
|
-
"pxpipe-proxy": "0.
|
|
66
|
+
"pxpipe-proxy": "0.14.0",
|
|
66
67
|
"toml-eslint-parser": "1.0.3",
|
|
67
68
|
"ws": "^8.21.3"
|
|
68
69
|
}
|
package/src/proxy-presets.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { promisify } from "node:util";
|
|
3
3
|
import zlib from "node:zlib";
|
|
4
|
+
import { performance } from "node:perf_hooks";
|
|
4
5
|
import { tokenStage } from "./proxy-stats.js";
|
|
5
6
|
import { requestImages } from "./request-images.js";
|
|
6
7
|
|
|
@@ -119,7 +120,7 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
119
120
|
JSON.stringify(result.messages) !== JSON.stringify(messages), result.compression_skipped ? "compression_skipped" : "processed", "headroom");
|
|
120
121
|
}
|
|
121
122
|
|
|
122
|
-
async function transform(raw, context, websocket = false) {
|
|
123
|
+
async function transform(raw, context, websocket = false, started = performance.now()) {
|
|
123
124
|
const path = new URL(context.path, "http://localhost").pathname;
|
|
124
125
|
const format = /\/(?:v1\/|anthropic\/)?messages$/.test(path) ? "anthropic"
|
|
125
126
|
: /\/chat\/completions$/.test(path) ? "chat" : /\/responses$/.test(path) ? "responses" : null;
|
|
@@ -151,7 +152,13 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
151
152
|
source = Object.fromEntries(Object.entries({ sessionId: metadata.session_id, threadId: metadata.thread_id, project })
|
|
152
153
|
.filter(([, value]) => typeof value === "string" && value.length).map(([key, value]) => [key, value.slice(0, 128)]));
|
|
153
154
|
} catch {}
|
|
154
|
-
try {
|
|
155
|
+
try {
|
|
156
|
+
const update = onStats({ model, preset: config.preset, transport: websocket ? "WS" : "HTTP", changed, stages, error,
|
|
157
|
+
timings: { presetMs: Math.round((performance.now() - started) * 10) / 10 },
|
|
158
|
+
...source, ...(requestId ? { requestId } : {}) });
|
|
159
|
+
// ponytail: WS measures presets only; response timings need per-response-ID correlation.
|
|
160
|
+
if (!websocket && typeof update === "function") context.updateTiming = update;
|
|
161
|
+
} catch {}
|
|
155
162
|
};
|
|
156
163
|
try {
|
|
157
164
|
// Fixed stage order, including the triple recipe: RTK -> Headroom -> pxpipe.
|
|
@@ -212,13 +219,15 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
212
219
|
} else if (px) {
|
|
213
220
|
stages.push(tokenStage("pxpipe", 0, 0, false, "model_excluded", "pxpipe_estimate"));
|
|
214
221
|
}
|
|
222
|
+
const output = changed ? Buffer.from(JSON.stringify(envelope)) : raw;
|
|
215
223
|
report(false);
|
|
216
|
-
return
|
|
224
|
+
return output;
|
|
217
225
|
} catch (error) { report(true); throw error; }
|
|
218
226
|
}
|
|
219
227
|
|
|
220
228
|
return {
|
|
221
229
|
async onRequest(context) {
|
|
230
|
+
const started = performance.now();
|
|
222
231
|
if (context.method !== "POST" || !/\bapplication\/(?:[\w.-]+\+)?json\b/i.test(String(context.headers["content-type"] || ""))) return;
|
|
223
232
|
const encoding = String(context.headers["content-encoding"] || "identity").toLowerCase();
|
|
224
233
|
if (encoding !== "identity" && !DECODERS[encoding]) {
|
|
@@ -229,7 +238,7 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
229
238
|
return;
|
|
230
239
|
}
|
|
231
240
|
const raw = encoding === "identity" ? context.body : await DECODERS[encoding](context.body, { maxOutputLength: config.maxBodyBytes });
|
|
232
|
-
const body = await transform(raw, context);
|
|
241
|
+
const body = await transform(raw, context, false, started);
|
|
233
242
|
if (body !== raw) {
|
|
234
243
|
context.body = body;
|
|
235
244
|
delete context.headers["content-encoding"];
|
package/src/proxy-stats.js
CHANGED
|
@@ -22,6 +22,18 @@ export function createProxyStatsRecorder(file = getProxyStatsPath()) {
|
|
|
22
22
|
const stats = readProxyStats(file) || { version: 1, since: new Date().toISOString(), requests: 0,
|
|
23
23
|
changed: 0, errors: 0, estimatedSavedTokens: 0, unmeasuredStages: 0, stages: {}, recent: [] };
|
|
24
24
|
let warned = false;
|
|
25
|
+
const warn = error => {
|
|
26
|
+
if (!warned) console.error(`[aih stats] Cannot save statistics: ${error.message}`);
|
|
27
|
+
warned = true;
|
|
28
|
+
};
|
|
29
|
+
const save = () => {
|
|
30
|
+
try {
|
|
31
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
32
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
33
|
+
writeFileSync(temporary, JSON.stringify(stats) + "\n");
|
|
34
|
+
renameSync(temporary, file);
|
|
35
|
+
} catch (error) { warn(error); }
|
|
36
|
+
};
|
|
25
37
|
return event => {
|
|
26
38
|
try {
|
|
27
39
|
stats.updatedAt = new Date().toISOString();
|
|
@@ -39,19 +51,21 @@ export function createProxyStatsRecorder(file = getProxyStatsPath()) {
|
|
|
39
51
|
}
|
|
40
52
|
stats.estimatedSavedTokens += saved;
|
|
41
53
|
const model = String(event.model).replace(/[\r\n]/g, " ").slice(0, 128);
|
|
42
|
-
|
|
54
|
+
const recent = { at: stats.updatedAt, model, preset: event.preset, transport: event.transport,
|
|
43
55
|
changed: event.changed, error: Boolean(event.error), saved: event.error ? null : saved,
|
|
44
|
-
sessionId: event.sessionId, threadId: event.threadId, project: event.project,
|
|
56
|
+
sessionId: event.sessionId, threadId: event.threadId, project: event.project,
|
|
57
|
+
...(event.timings ? { timings: { ...event.timings } } : {}), stages };
|
|
58
|
+
stats.recent.push(recent);
|
|
45
59
|
stats.recent = stats.recent.slice(-20);
|
|
46
|
-
|
|
47
|
-
const temporary = `${file}.${process.pid}.tmp`;
|
|
48
|
-
writeFileSync(temporary, JSON.stringify(stats) + "\n");
|
|
49
|
-
renameSync(temporary, file);
|
|
60
|
+
save();
|
|
50
61
|
console.log(`[aih stats] ${event.transport} ${model} ${event.preset}: ${event.error ? "processing failed" : stages.map(s => `${s.name}=${s.saved ?? "?"} (${s.reason})`).join(", ") + `; estimated saved=${saved} tokens`}`);
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
62
|
+
// Update this entry, never recount a request or resurrect an evicted entry.
|
|
63
|
+
return timings => {
|
|
64
|
+
if (!stats.recent.includes(recent)) return;
|
|
65
|
+
recent.timings = { ...recent.timings, ...timings };
|
|
66
|
+
save();
|
|
67
|
+
};
|
|
68
|
+
} catch (error) { warn(error); }
|
|
55
69
|
};
|
|
56
70
|
}
|
|
57
71
|
|
package/src/proxy.js
CHANGED
|
@@ -4,6 +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
8
|
import WebSocket, { WebSocketServer } from "ws";
|
|
8
9
|
import { normalizePresetOptions, createPresetHooks } from "./proxy-presets.js";
|
|
9
10
|
|
|
@@ -121,7 +122,7 @@ export async function startProxy(options) {
|
|
|
121
122
|
response.end(error.statusCode === 413 ? "Request body too large\n" : "Proxy request failed\n");
|
|
122
123
|
}
|
|
123
124
|
|
|
124
|
-
async function relayResponse(incoming, response, request) {
|
|
125
|
+
async function relayResponse(incoming, response, request, onFailure = error => fail(response, error)) {
|
|
125
126
|
const context = { request, statusCode: incoming.statusCode, headers: { ...incoming.headers } };
|
|
126
127
|
try {
|
|
127
128
|
await hooks.onResponse?.(context);
|
|
@@ -161,32 +162,69 @@ export async function startProxy(options) {
|
|
|
161
162
|
await pipeline(incoming, response);
|
|
162
163
|
}
|
|
163
164
|
} catch (error) {
|
|
164
|
-
|
|
165
|
+
onFailure(error);
|
|
165
166
|
incoming.destroy();
|
|
166
167
|
}
|
|
167
168
|
}
|
|
168
169
|
|
|
169
170
|
const server = http.createServer(async (request, response) => {
|
|
171
|
+
const started = performance.now();
|
|
170
172
|
let upstream;
|
|
171
|
-
|
|
172
|
-
|
|
173
|
+
let context;
|
|
174
|
+
let finished = false;
|
|
175
|
+
let failed = false;
|
|
176
|
+
const timings = { state: "waiting" };
|
|
177
|
+
const elapsed = since => Math.round((performance.now() - since) * 10) / 10;
|
|
178
|
+
const publishTiming = () => {
|
|
179
|
+
// Optional recorder updater: never emit a second preset event or disrupt traffic.
|
|
180
|
+
try { context?.updateTiming?.(timings); } catch {}
|
|
181
|
+
};
|
|
182
|
+
const finishTiming = state => {
|
|
183
|
+
if (finished) return;
|
|
184
|
+
finished = true;
|
|
185
|
+
timings.state = state;
|
|
186
|
+
timings.totalMs = elapsed(started);
|
|
187
|
+
publishTiming();
|
|
188
|
+
};
|
|
189
|
+
const failRequest = error => { failed = true; fail(response, error); };
|
|
190
|
+
response.once("finish", () => finishTiming(failed ? "error" : "completed"));
|
|
191
|
+
response.once("close", () => {
|
|
192
|
+
finishTiming(failed ? "error" : "aborted");
|
|
193
|
+
upstream?.destroy();
|
|
194
|
+
});
|
|
195
|
+
request.on("error", error => { upstream?.destroy(); failRequest(error); });
|
|
173
196
|
try {
|
|
174
|
-
|
|
197
|
+
context = requestContext(request);
|
|
175
198
|
if (hooks.onRequest) {
|
|
176
199
|
context.body = await readBody(request, config.maxBodyBytes);
|
|
177
200
|
await hooks.onRequest(context);
|
|
178
201
|
context.body = bytes(context.body);
|
|
179
202
|
if (context.body.length > config.maxBodyBytes) throw Object.assign(new Error("Modified request body exceeds maxBodyBytes"), { statusCode: 413 });
|
|
180
203
|
}
|
|
204
|
+
// A disconnect may have happened while the preset was still processing.
|
|
205
|
+
publishTiming();
|
|
181
206
|
if (response.destroyed) return;
|
|
182
207
|
const headers = headersForHop(context.headers);
|
|
183
208
|
headers.host = target.host;
|
|
184
209
|
if (context.body !== undefined) headers["content-length"] = String(context.body.length);
|
|
185
210
|
else if (context.headers.trailer) headers.trailer = context.headers.trailer;
|
|
211
|
+
const sentAt = performance.now();
|
|
186
212
|
upstream = (target.protocol === "https:" ? https : http).request(target, {
|
|
187
213
|
method: context.method, path: upstreamPath(context.path), headers,
|
|
188
|
-
}, incoming => {
|
|
189
|
-
|
|
214
|
+
}, incoming => {
|
|
215
|
+
// Mark upstream truncation before pipeline destroys the downstream response.
|
|
216
|
+
incoming.once("aborted", () => { failed = true; });
|
|
217
|
+
incoming.once("error", () => { failed = true; });
|
|
218
|
+
if (!finished) {
|
|
219
|
+
// Header arrival is observable without consuming/buffering SSE body chunks.
|
|
220
|
+
timings.upstreamHeadersMs = elapsed(sentAt);
|
|
221
|
+
timings.statusCode = incoming.statusCode;
|
|
222
|
+
timings.state = "responding";
|
|
223
|
+
publishTiming();
|
|
224
|
+
}
|
|
225
|
+
void relayResponse(incoming, response, context, failRequest);
|
|
226
|
+
});
|
|
227
|
+
upstream.on("error", failRequest);
|
|
190
228
|
request.on("aborted", () => upstream.destroy());
|
|
191
229
|
if (context.body !== undefined) upstream.end(context.body);
|
|
192
230
|
else {
|
|
@@ -195,7 +233,8 @@ export async function startProxy(options) {
|
|
|
195
233
|
}
|
|
196
234
|
} catch (error) {
|
|
197
235
|
upstream?.destroy();
|
|
198
|
-
|
|
236
|
+
failRequest(error);
|
|
237
|
+
publishTiming();
|
|
199
238
|
}
|
|
200
239
|
});
|
|
201
240
|
// Long-lived SSE streams must not expire between model events.
|
package/src/tui.js
CHANGED
|
@@ -98,6 +98,11 @@ function age(timestamp, now) {
|
|
|
98
98
|
return `${Math.floor(seconds / 3600)}h`;
|
|
99
99
|
}
|
|
100
100
|
|
|
101
|
+
function duration(ms) {
|
|
102
|
+
if (!Number.isFinite(ms) || ms < 0) return "n/d";
|
|
103
|
+
return ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(1)}s`;
|
|
104
|
+
}
|
|
105
|
+
|
|
101
106
|
// Snapshot strings are data, never terminal escape sequences or extra rows.
|
|
102
107
|
function plain(value, fallback = "-") {
|
|
103
108
|
return stripAnsi(String(value ?? fallback)).replace(/[\x00-\x1f\x7f-\x9f]/g, " ");
|
|
@@ -350,7 +355,10 @@ export class Dashboard {
|
|
|
350
355
|
}
|
|
351
356
|
add([dim("elab/s: richieste elaborate dai preset, non tutto il traffico proxy")]);
|
|
352
357
|
add([dim("Risparmio: somma dei delta misurati per stadio; basi non sommabili")]);
|
|
353
|
-
add([dim("Errori preset != errori upstream;
|
|
358
|
+
add([dim("Errori preset != errori upstream; nessun conteggio globale delle richieste in corso")]);
|
|
359
|
+
add([dim("Tempi: proxy = preset; header = invio upstream -> header (non primo token)")]);
|
|
360
|
+
add([dim("Totale HTTP include upload, interceptor e streaming fino a fine invio/chiusura")]);
|
|
361
|
+
add([dim("WS: solo tempo preset; attesa esito non implica che la richiesta sia ancora attiva")]);
|
|
354
362
|
}
|
|
355
363
|
return lines.map(line => clip(line, width));
|
|
356
364
|
}
|
|
@@ -375,9 +383,23 @@ export class Dashboard {
|
|
|
375
383
|
const unmeasured = partial && stages.every(stage => !Number.isFinite(stage.saved));
|
|
376
384
|
const status = event.error ? red(bold("errore preset")) : event.changed === true ? green("modificata")
|
|
377
385
|
: event.changed === false ? dim("invariata") : dim("esito non disponibile");
|
|
386
|
+
const timing = event.timings;
|
|
387
|
+
const responseState = {
|
|
388
|
+
waiting: dim("attesa esito"), responding: cyan("risposta iniziata"),
|
|
389
|
+
error: red(event.error ? "non inoltrata" : "errore proxy/trasporto"), aborted: yellow("interrotta"),
|
|
390
|
+
}[timing?.state];
|
|
378
391
|
const lines = wrapCells([gray(time), cyan(plain(event.transport)), magenta(plain(event.model, "?")),
|
|
379
392
|
plain(event.preset), status,
|
|
380
393
|
...(event.error ? [] : [savedTokens(unmeasured ? null : event.saved) + (partial && !unmeasured ? yellow(" (parziale)") : "")]),
|
|
394
|
+
...(timing ? [
|
|
395
|
+
`proxy: ${duration(timing.presetMs)}`,
|
|
396
|
+
...(event.transport === "HTTP" ? [
|
|
397
|
+
`header: ${duration(timing.upstreamHeadersMs)}`, `tot: ${duration(timing.totalMs)}`,
|
|
398
|
+
...(Number.isInteger(timing.statusCode) && timing.statusCode >= 100 && timing.statusCode <= 599
|
|
399
|
+
? [timing.statusCode >= 400 ? red(`HTTP ${timing.statusCode}`) : `HTTP ${timing.statusCode}`] : []),
|
|
400
|
+
...(responseState ? [responseState] : []),
|
|
401
|
+
] : [dim("risposta WS: n/d")]),
|
|
402
|
+
] : [dim("tempi: n/d")]),
|
|
381
403
|
...(event.project ? [`progetto: ${plain(event.project)}`] : []),
|
|
382
404
|
...(event.sessionId || event.threadId ? [`sessione: ${plain(event.sessionId || event.threadId)}`] : []),
|
|
383
405
|
...(!this.showPipelineDetails ? stages.map(s => dim(`${plain(s.name)}: ${plain(s.reason)}`)) : []),
|
package/src/utils/process.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
|
-
import { openSync, appendFileSync } from "node:fs";
|
|
2
|
+
import { openSync, appendFileSync, closeSync } from "node:fs";
|
|
3
3
|
import { ensureDir, getLogsDir } from "./path.js";
|
|
4
4
|
|
|
5
5
|
/**
|
|
@@ -221,14 +221,20 @@ export function spawnDetachedProcess(command, logFilePath, options) {
|
|
|
221
221
|
|
|
222
222
|
const fd = openSync(logFilePath, "a");
|
|
223
223
|
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
224
|
+
let proc;
|
|
225
|
+
try {
|
|
226
|
+
proc = spawn(command, [], {
|
|
227
|
+
shell: true,
|
|
228
|
+
detached: true,
|
|
229
|
+
stdio: ["ignore", fd, fd],
|
|
230
|
+
env: { ...process.env, ...options?.env },
|
|
231
|
+
cwd: options?.cwd,
|
|
232
|
+
windowsHide: true,
|
|
233
|
+
});
|
|
234
|
+
} finally {
|
|
235
|
+
// The child owns its inherited handles; the parent must not keep the log open.
|
|
236
|
+
closeSync(fd);
|
|
237
|
+
}
|
|
232
238
|
|
|
233
239
|
proc.unref();
|
|
234
240
|
|