@drakonkat/ai-helper 1.2.10 → 1.2.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/README.md +28 -0
- package/docs/pxpipe-performance-2026-09-30.md +250 -0
- package/package.json +6 -3
- package/scripts/build.js +7 -0
- package/scripts/patch-pxpipe.js +46 -0
- package/src/index.js +1 -0
- package/src/proxy-presets.js +16 -26
- package/src/proxy.js +23 -5
- package/src/pxpipe-pool.js +91 -0
- package/src/pxpipe-thread.js +46 -0
- package/src/tui.js +5 -0
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,28 @@ All notable changes to **`ai-helper` (`aih`)** are documented in this file.
|
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
+
## [1.2.12] - 2026-09-30
|
|
8
|
+
|
|
9
|
+
### Fixed
|
|
10
|
+
- Exclude opaque reasoning, compaction and media from pxpipe's diagnostic token counts, retaining forwarded payloads and reporting partial counts explicitly. Apply the version-checked correction on installation and standalone builds.
|
|
11
|
+
- Run pxpipe transformations and token estimates in up to two persistent CPU workers so heavy requests cannot block HTTP/SSE or excluded models. Bound waiting work, cancel disconnected requests, recover from worker crashes and close workers on shutdown.
|
|
12
|
+
|
|
13
|
+
### Added
|
|
14
|
+
- Show worker queue, processing, supported thread CPU and sampled event-loop delay separately in the request stream.
|
|
15
|
+
- Regression checks for opaque payload preservation, excluded-model responsiveness, bounded queues, cancellation, crash recovery and shutdown.
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## [1.2.11] - 2026-09-30
|
|
20
|
+
|
|
21
|
+
### Changed
|
|
22
|
+
- Upgrade the embedded `pxpipe-proxy` dependency from 0.13.2 to 0.14.0 and synchronize npm and Bun lockfiles.
|
|
23
|
+
|
|
24
|
+
### Added
|
|
25
|
+
- Document offline CPU profiling, opaque-data tokenization costs, and isolated worker-thread experiments. These experiments do not change production proxy processing.
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
7
29
|
## [1.2.10] - 2026-09-29
|
|
8
30
|
|
|
9
31
|
### Added
|
package/README.md
CHANGED
|
@@ -318,6 +318,34 @@ then the built-in proxy with these options:
|
|
|
318
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*"
|
|
319
319
|
```
|
|
320
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
|
+
|
|
327
|
+
Pxpipe transformations and their token estimates run in up to **two persistent
|
|
328
|
+
CPU workers**. Excluded models bypass the worker queue; HTTP and SSE streaming
|
|
329
|
+
remain on the main thread. Sessions have stable worker affinity to reuse caches.
|
|
330
|
+
The queue is limited to 32 waiting requests and `--max-body-bytes` of waiting
|
|
331
|
+
input; overload returns HTTP 503. Disconnecting cancels queued work or terminates
|
|
332
|
+
and replaces the active worker. Shutdown closes both workers.
|
|
333
|
+
|
|
334
|
+
Installation applies a version-checked correction to pxpipe 0.14.0: diagnostic
|
|
335
|
+
composition counts exclude encrypted reasoning, opaque compaction and media data,
|
|
336
|
+
including JSON-serialized tool media. Forwarded payloads keep these values intact.
|
|
337
|
+
`responsesComposition.partial` and `excludedBytes` identify incomplete diagnostic
|
|
338
|
+
counts. Lifecycle scripts must be enabled for this correction; standalone builds
|
|
339
|
+
include it automatically. Dependency upgrades require reviewing the correction.
|
|
340
|
+
|
|
341
|
+
The request stream separates total preset time (`proxy`), worker queue time
|
|
342
|
+
(`coda`), transformation time (`pxpipe`) and, on supporting Node versions, worker
|
|
343
|
+
CPU time (`CPU`). Header and total response times retain their existing meaning;
|
|
344
|
+
worker isolation does not shorten provider generation time.
|
|
345
|
+
`loop max` is the maximum sampled main-thread scheduling delay since the preceding
|
|
346
|
+
preset event beyond the 20 ms sampling interval, shared across requests. Queue
|
|
347
|
+
time includes cold worker startup.
|
|
348
|
+
|
|
321
349
|
Pass `--models` to `aih start` (or `aih up`) to override the proxy's model list:
|
|
322
350
|
|
|
323
351
|
```bash
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
# Profilazione pxpipe — 30 settembre 2026
|
|
2
|
+
|
|
3
|
+
**Aggiornamento aih 1.2.12:** gli interventi sul conteggio diagnostico e sui worker
|
|
4
|
+
sono ora integrati. Le sezioni sperimentali sotto conservano le misure originali;
|
|
5
|
+
il nuovo controllo di produzione è descritto in fondo.
|
|
6
|
+
|
|
7
|
+
Il progetto usava `pxpipe-proxy` **0.13.2**. È stato aggiornato a **0.14.0** in
|
|
8
|
+
`package.json`, `package-lock.json`, `bun.lock` e nell'installazione locale.
|
|
9
|
+
La build standalone è stata ricompilata con la nuova dipendenza.
|
|
10
|
+
La libreria usa ora `gpt-tokenizer` 4.0.0; il conteggio del progetto mantiene
|
|
11
|
+
la propria dipendenza diretta 3.4.0.
|
|
12
|
+
|
|
13
|
+
La profilazione identifica un problema riproducibile nel conteggio diagnostico
|
|
14
|
+
dei dati opachi. L'aggiornamento da solo non elimina questo caso lento.
|
|
15
|
+
La modifica alle statistiche e il multithreading descritti sotto sono esperimenti
|
|
16
|
+
isolati, non modifiche al proxy gestito in esecuzione.
|
|
17
|
+
|
|
18
|
+
## Ambiente e metodo
|
|
19
|
+
|
|
20
|
+
- Windows, Node.js 22.22.1, Intel i7-10700K: 8 core e 16 processori logici.
|
|
21
|
+
- RAM: circa 64 GiB. GPU: NVIDIA RTX 2080 Ti, 11 GiB.
|
|
22
|
+
- Benchmark HTTP locale esistente: 10 fixture Responses per modello,
|
|
23
|
+
`gpt-6-astra` e `anthropic/claude-opus-5-5`, preset `none` e `pxpipe`.
|
|
24
|
+
- Profili CPU V8 tramite Inspector, intervallo di campionamento 1 ms; misura
|
|
25
|
+
del tempo trascorso, CPU e ritardo massimo di un timer da 10 ms.
|
|
26
|
+
- Input di stress: fixture sintetica `responses-dense-context` da circa 149 kB,
|
|
27
|
+
con un elemento `reasoning.encrypted_content` aggiunto; confronto fra base64
|
|
28
|
+
pseudocasuale e una sequenza ripetitiva di `A` della stessa lunghezza.
|
|
29
|
+
- Nessuna chiamata a provider: i tempi sono locali e non includono una risposta LLM.
|
|
30
|
+
|
|
31
|
+
Le misure di stress sono singole osservazioni controllate, non una distribuzione
|
|
32
|
+
di latenza del traffico reale. I nomi `cold` dei file indicano cache del renderer
|
|
33
|
+
svuotata: la cache del tokenizer rimane attiva nel processo. Claude viene misurato
|
|
34
|
+
per primo; il campione GPT successivo può riutilizzare la tokenizzazione dello
|
|
35
|
+
stesso input. Pertanto non dimostrano che il problema riguardi solo Claude.
|
|
36
|
+
I processi separati permettono invece il confronto delle due versioni sul primo
|
|
37
|
+
campione Claude.
|
|
38
|
+
|
|
39
|
+
## Confronto delle versioni
|
|
40
|
+
|
|
41
|
+
Sul corpus ordinario il benchmark completa tutte le 40 richieste per versione,
|
|
42
|
+
con controlli di conservazione superati. Alcuni costi vision rimangono sconosciuti:
|
|
43
|
+
non si deduce da questo test una migliore qualità semantica o un risparmio fatturato.
|
|
44
|
+
|
|
45
|
+
| Versione / modello | Mediana HTTP con pxpipe | p95 HTTP con pxpipe |
|
|
46
|
+
|---|---:|---:|
|
|
47
|
+
| 0.13.2 / Astra | 3,1 ms | 327,7 ms |
|
|
48
|
+
| 0.14.0 / Astra | 2,6 ms | 335,1 ms |
|
|
49
|
+
| 0.13.2 / Claude | 3,1 ms | 253,5 ms |
|
|
50
|
+
| 0.14.0 / Claude | 3,8 ms | 269,3 ms |
|
|
51
|
+
|
|
52
|
+
Dieci richieste eterogenee per riga e un solo round non consentono di attribuire
|
|
53
|
+
significato statistico alle piccole differenze. L'inizializzazione e le cache
|
|
54
|
+
influenzano soprattutto il caso di contesto denso.
|
|
55
|
+
|
|
56
|
+
Il problema emerge con sequenze opache lunghe e ripetitive:
|
|
57
|
+
|
|
58
|
+
| Input / versione | Trasformazione locale | Ritardo massimo del timer |
|
|
59
|
+
|---|---:|---:|
|
|
60
|
+
| 128 KiB ripetitivi / 0.13.2 | 9,749 s | 9,385 s |
|
|
61
|
+
| 128 KiB ripetitivi / 0.14.0 | 9,667 s | 9,334 s |
|
|
62
|
+
| 256 KiB ripetitivi / 0.14.0 | 51,636 s | 51,265 s |
|
|
63
|
+
| 512 KiB base64 pseudocasuale / 0.14.0 | 0,870 s | 0,516 s |
|
|
64
|
+
| 512 KiB base64 in blocco immagine sintetico di tool / 0.14.0 | 0,665 s | 0,343 s |
|
|
65
|
+
|
|
66
|
+
Quindi conta anche la forma dei dati, non soltanto la dimensione. Lo stress con
|
|
67
|
+
`A` ripetute è intenzionalmente patologico; non rappresenta automaticamente una
|
|
68
|
+
cifratura o una PNG reale.
|
|
69
|
+
|
|
70
|
+
## Dove viene speso il tempo
|
|
71
|
+
|
|
72
|
+
In `pxpipe-proxy/dist/core/openai.js`, `transformOpenAIResponses` chiama
|
|
73
|
+
`measureResponsesComposition` prima della trasformazione. Questa funzione esegue
|
|
74
|
+
il tokenizer su `JSON.stringify(reasoning)`, includendo `encrypted_content`;
|
|
75
|
+
inoltre serializza alcuni output di tool contenenti immagini.
|
|
76
|
+
|
|
77
|
+
Il conteggio serve alla diagnostica della composizione. Nel caso ripetitivo:
|
|
78
|
+
|
|
79
|
+
- 128 KiB: **95,7%** dei campioni CPU è in `BytePairEncodingCore`.
|
|
80
|
+
- 256 KiB: **98,9%** dei campioni CPU è in `BytePairEncodingCore`.
|
|
81
|
+
|
|
82
|
+
`bytePairMerge` scansiona ripetutamente i ranghi per trovare il minimo ed elimina
|
|
83
|
+
elementi dagli array con `splice`. Su un pezzo molto lungo e ripetitivo questo
|
|
84
|
+
produce lavoro quadratico. La versione 4.0.0 del tokenizer mantiene questa
|
|
85
|
+
struttura: il suo aggiornamento non risolve il caso osservato.
|
|
86
|
+
|
|
87
|
+
La cache di tokenizzazione può nascondere il costo su un input identico già visto.
|
|
88
|
+
L'input cambiato nel test multithread forza nuovi conteggi. Un timer fermo per
|
|
89
|
+
oltre 51 secondi dimostra che la trasformazione può impedire al thread HTTP di
|
|
90
|
+
gestire tempestivamente altre connessioni, header e stream.
|
|
91
|
+
|
|
92
|
+
Questo fornisce una spiegazione plausibile dei ritardi del dashboard del 29
|
|
93
|
+
settembre. Non abbiamo profilato il payload esatto di quelle richieste: non è
|
|
94
|
+
ancora provato che contenessero lo stesso pattern patologico.
|
|
95
|
+
|
|
96
|
+
## Esperimento: evitare il conteggio dei dati opachi
|
|
97
|
+
|
|
98
|
+
Una copia separata di pxpipe 0.14.0 filtra `encrypted_content` e i blocchi immagine
|
|
99
|
+
**solo dalla copia usata per la diagnostica**. La richiesta originale continua
|
|
100
|
+
intatta nella trasformazione e nell'inoltro.
|
|
101
|
+
|
|
102
|
+
| Input Claude | 0.14.0 originale | Copia sperimentale | Accelerazione |
|
|
103
|
+
|---|---:|---:|---:|
|
|
104
|
+
| 128 KiB ripetitivi | 9,667 s | 0,415 s | circa 23× |
|
|
105
|
+
| 256 KiB ripetitivi | 51,636 s | 0,381 s | circa 135× |
|
|
106
|
+
|
|
107
|
+
Per il caso 256 KiB, gli SHA-256 dei payload in uscita coincidono in tutti e
|
|
108
|
+
quattro i confronti Claude/GPT, renderer freddo/caldo. Il probe controlla anche
|
|
109
|
+
la conservazione del reasoning opaco, delle immagini native e del modello.
|
|
110
|
+
|
|
111
|
+
Questa è una prova del margine di ottimizzazione, non una patch pronta per la
|
|
112
|
+
produzione: la diagnostica filtrata diventerebbe parziale. Una correzione stabile
|
|
113
|
+
deve dichiarare esplicitamente i byte opachi esclusi e non presentare il subtotale
|
|
114
|
+
come conteggio completo. Deve coprire anche compaction e altri media serializzati.
|
|
115
|
+
È preferibile una modifica nell'API upstream; una patch manuale a `node_modules`
|
|
116
|
+
verrebbe persa alla reinstallazione.
|
|
117
|
+
|
|
118
|
+
## Esperimento: due worker thread persistenti
|
|
119
|
+
|
|
120
|
+
I worker vengono inizializzati e riscaldati prima della misura. Le due richieste
|
|
121
|
+
hanno sequenze opache da 128 KiB diverse tra loro, per evitare un cache hit sul
|
|
122
|
+
pezzo lento; gli stessi input vengono poi inviati ai due worker. Un'asserzione
|
|
123
|
+
confronta gli hash degli output sequenziali e paralleli.
|
|
124
|
+
|
|
125
|
+
| Esecuzione | Tempo per il gruppo | Ritardo del thread principale |
|
|
126
|
+
|---|---:|---:|
|
|
127
|
+
| Due richieste sequenziali nel thread principale | 24,180 s | 12.185,5 ms |
|
|
128
|
+
| Una richiesta in un worker | 13,710 s | 16,0 ms |
|
|
129
|
+
| Due richieste in due worker | 13,777 s | 13,6 ms |
|
|
130
|
+
|
|
131
|
+
Il gruppo parallelo è **circa 1,75× più rapido**, con output identici. Il beneficio
|
|
132
|
+
più importante è la reattività del proxy: il thread delle connessioni continua
|
|
133
|
+
a lavorare mentre il tokenizer occupa altri core. Una singola richiesta non
|
|
134
|
+
diventa automaticamente più veloce solo spostandola in un worker.
|
|
135
|
+
|
|
136
|
+
Un'integrazione dovrebbe partire da due worker persistenti, una coda limitata,
|
|
137
|
+
propagazione degli errori e delle cancellazioni, e assegnazione stabile delle
|
|
138
|
+
sessioni per sfruttare le cache. Ogni worker ha tokenizer, atlanti e cache propri:
|
|
139
|
+
non conviene partire da 16 worker soltanto perché ci sono 16 processori logici.
|
|
140
|
+
I worker di Cloudflare citati da pxpipe sono un ambiente di esecuzione, non
|
|
141
|
+
l'implementazione Node `worker_threads`.
|
|
142
|
+
|
|
143
|
+
## GPU, cache e altre ottimizzazioni
|
|
144
|
+
|
|
145
|
+
La RTX 2080 Ti è disponibile, ma la libreria distribuita non espone un backend
|
|
146
|
+
GPU. Il renderer e i filtri PNG sono JavaScript; la compressione usa
|
|
147
|
+
`CompressionStream`. `@napi-rs/canvas` è una dipendenza di sviluppo upstream,
|
|
148
|
+
non il renderer nativo usato a runtime.
|
|
149
|
+
|
|
150
|
+
La GPU non elimina il conteggio diagnostico BPE. Nel caso da 256 KiB, anche
|
|
151
|
+
azzerando tutto il tempo fuori dal tokenizer il margine sarebbe solo circa
|
|
152
|
+
**1,1%**. Non è una misura di accelerazione GPU: è un limite ricavato dalla
|
|
153
|
+
composizione dei campioni CPU di questo caso. Un renderer GPU richiederebbe una
|
|
154
|
+
nuova implementazione e confronti di pixel, leggibilità e costi di trasferimento.
|
|
155
|
+
|
|
156
|
+
La cache delle immagini **esiste già**, con budget Node predefinito di 64 MiB.
|
|
157
|
+
Nei probe risulta un miss seguito da un hit, senza eviction o oggetti fuori budget.
|
|
158
|
+
Aumentarne il limite non risolve il conteggio opaco. Per molte richieste identiche
|
|
159
|
+
contemporanee, deduplicare i render in corso potrebbe evitare doppio lavoro;
|
|
160
|
+
il vantaggio va misurato sul traffico reale prima di aggiungere questa logica.
|
|
161
|
+
|
|
162
|
+
Ordine degli interventi:
|
|
163
|
+
|
|
164
|
+
1. Evitare la tokenizzazione di dati opachi/media per sola osservabilità,
|
|
165
|
+
mantenendo metriche parziali dichiarate e payload intatti.
|
|
166
|
+
2. Isolare la trasformazione dal thread HTTP con un piccolo pool persistente.
|
|
167
|
+
3. Se rimane un costo importante sul testo reale, confrontare un tokenizer
|
|
168
|
+
nativo o un algoritmo BPE più efficiente; nessun guadagno è stato misurato qui.
|
|
169
|
+
4. Ottimizzare renderer/cache soltanto se diventano dominanti dopo i primi passi.
|
|
170
|
+
|
|
171
|
+
## Verifiche e artefatti
|
|
172
|
+
|
|
173
|
+
- `npm test`: completato con exit code 0 dopo l'aggiornamento.
|
|
174
|
+
- `npm run build`: completato; nuova build in `dist/aih.exe`.
|
|
175
|
+
- Benchmark HTTP delle due versioni: 40/40 richieste riuscite ciascuno.
|
|
176
|
+
- `git diff --check`: superato.
|
|
177
|
+
- Durante i benchmark: nessuna chiamata a provider, installazione globale o riavvio dei servizi gestiti.
|
|
178
|
+
|
|
179
|
+
Gli input e i profili locali sono in
|
|
180
|
+
`benchmark-results/pxpipe-profile-2026-09-30/` (directory ignorata da Git):
|
|
181
|
+
|
|
182
|
+
- `core/report.md` e `updated-core/report.md`: benchmark HTTP prima/dopo.
|
|
183
|
+
- `probe.mjs`: misure e controlli eseguibili.
|
|
184
|
+
- `prepare-experiment.mjs`: creazione della copia sperimentale.
|
|
185
|
+
- `new-opaque-repeated-262144.json` e `sanitized-opaque-repeated-262144.json`.
|
|
186
|
+
- `new-opaque-repeated-262144-claude-cold.cpuprofile`: profilo V8 apribile nei DevTools.
|
|
187
|
+
- `new-threads.json`: confronto dei worker e hash degli output.
|
|
188
|
+
|
|
189
|
+
Esempi di ripetizione dalla root, con gli artefatti già presenti:
|
|
190
|
+
|
|
191
|
+
```powershell
|
|
192
|
+
node benchmark-results/pxpipe-profile-2026-09-30/probe.mjs --case opaque-repeated-262144
|
|
193
|
+
node benchmark-results/pxpipe-profile-2026-09-30/probe.mjs --sanitized --case opaque-repeated-262144
|
|
194
|
+
node benchmark-results/pxpipe-profile-2026-09-30/probe.mjs --case opaque-repeated-131072 --threads
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
La build locale aggiornata non sostituisce automaticamente il worker di un proxy
|
|
198
|
+
già avviato dall'installazione globale.
|
|
199
|
+
|
|
200
|
+
Per caricare la libreria aggiornata occorre installare ai-helper 1.2.11 e
|
|
201
|
+
riavviare il proxy con `aih restart proxy --json`. Aggiornare soltanto il pacchetto
|
|
202
|
+
globale `pxpipe-proxy` non aggiorna necessariamente la copia incorporata in
|
|
203
|
+
ai-helper o in un vecchio binario standalone. Su Windows, se il processo è stato
|
|
204
|
+
avviato con privilegi elevati, il riavvio richiede una PowerShell con gli stessi
|
|
205
|
+
privilegi; nel controllo locale la terminazione è stata negata con `Access is denied`.
|
|
206
|
+
|
|
207
|
+
Fonti primarie: [release pxpipe 0.14.0](https://github.com/teamchong/pxpipe/releases/tag/v0.14.0),
|
|
208
|
+
[Node.js 22: worker thread e pool persistenti](https://nodejs.org/docs/latest-v22.x/api/worker_threads.html).
|
|
209
|
+
Le misure e le conclusioni prestazionali sopra derivano dai profili locali.
|
|
210
|
+
|
|
211
|
+
## Integrazione in aih 1.2.12
|
|
212
|
+
|
|
213
|
+
L'installazione e la build applicano automaticamente una correzione controllata
|
|
214
|
+
per pxpipe 0.14.0. La sola copia diagnostica esclude reasoning cifrato, compaction
|
|
215
|
+
opaca e media, anche serializzati nel JSON di un output tool. Le metriche espongono
|
|
216
|
+
`responsesComposition.partial` e `excludedBytes`; la richiesta trasformata non
|
|
217
|
+
viene privata di questi dati. La correzione è idempotente e rifiuta versioni o
|
|
218
|
+
target diversi, così un aggiornamento della dipendenza richiede una revisione.
|
|
219
|
+
|
|
220
|
+
Il proxy usa al massimo due worker persistenti, avviati al primo lavoro e
|
|
221
|
+
assegnati stabilmente per sessione. I modelli esclusi evitano la coda. Al massimo
|
|
222
|
+
32 richieste e `maxBodyBytes` di input possono attendere; oltre il limite viene
|
|
223
|
+
restituito HTTP 503. Una disconnessione elimina il lavoro in coda oppure termina
|
|
224
|
+
e sostituisce il worker attivo. La chiusura del proxy termina tutti i worker.
|
|
225
|
+
La build standalone incorpora separatamente anche il codice dei thread.
|
|
226
|
+
|
|
227
|
+
Il nuovo probe usa la medesima fixture Responses con 256 KiB ripetitivi e confronta
|
|
228
|
+
gli SHA-256 con il risultato 0.14.0 originale già registrato:
|
|
229
|
+
|
|
230
|
+
| Modello / stato | Tempo totale preset | Tempo nel worker | Coda / avvio worker |
|
|
231
|
+
|---|---:|---:|---:|
|
|
232
|
+
| Claude / primo uso | 1.026 ms | 406 ms | 612 ms |
|
|
233
|
+
| Astra / primo uso | 1.016 ms | 418 ms | 591 ms |
|
|
234
|
+
| Claude / cache calda | 171 ms | 167 ms | 0 ms |
|
|
235
|
+
| Astra / cache calda | 186 ms | 181 ms | 0 ms |
|
|
236
|
+
|
|
237
|
+
I due primi usi sono concorrenti, con cache indipendenti. Gli output coincidono
|
|
238
|
+
con quelli originali in tutti e quattro i confronti. Sol escluso passa in 0,6 ms;
|
|
239
|
+
il ritardo massimo del timer principale è 11,1 ms. Queste misure singole e
|
|
240
|
+
sintetiche non garantiscono la latenza del traffico reale né quella del provider.
|
|
241
|
+
|
|
242
|
+
Il dashboard mostra separatamente `coda`, `pxpipe`, CPU del thread quando
|
|
243
|
+
supportata da Node e `loop max`: quest'ultimo è il massimo ritardo campionato del
|
|
244
|
+
thread principale dall'evento preset precedente, condiviso tra le richieste.
|
|
245
|
+
|
|
246
|
+
Verifica ripetibile nel repository: `node --test test/pxpipe-performance.test.js`.
|
|
247
|
+
I nuovi test controllano anche output identici prima/dopo la correzione, media
|
|
248
|
+
nativi, compaction, Sol escluso durante due lavori CPU, coda limitata, cancellazione,
|
|
249
|
+
crash e chiusura. La suite completa e il test CLI standalone sono passati.
|
|
250
|
+
Il probe e `optimized-production.json` rimangono negli artefatti locali ignorati.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@drakonkat/ai-helper",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.12",
|
|
4
4
|
"description": "Zero-config background service manager, auto-discovery daemon & dashboard launcher for AI agent ecosystems (pxpipe, ocx, agentmemory, headroom)",
|
|
5
5
|
"main": "src/index.js",
|
|
6
6
|
"module": "src/index.js",
|
|
@@ -13,8 +13,10 @@
|
|
|
13
13
|
"bin",
|
|
14
14
|
"src",
|
|
15
15
|
"scripts/build.js",
|
|
16
|
+
"scripts/patch-pxpipe.js",
|
|
16
17
|
"scripts/bench-proxy.js",
|
|
17
18
|
"docs/benchmark.md",
|
|
19
|
+
"docs/pxpipe-performance-2026-09-30.md",
|
|
18
20
|
"README.md",
|
|
19
21
|
"LICENSE",
|
|
20
22
|
"ARCHITECTURE.md",
|
|
@@ -35,9 +37,10 @@
|
|
|
35
37
|
},
|
|
36
38
|
"homepage": "https://github.com/drakonkat/ai-helper#readme",
|
|
37
39
|
"scripts": {
|
|
40
|
+
"postinstall": "node scripts/patch-pxpipe.js",
|
|
38
41
|
"start": "node ./bin/cli.js",
|
|
39
42
|
"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 test/service-updates.test.js && node --test test/proxy.test.js test/codex-config.test.js test/codex-routing.test.js test/codex-manager.test.js test/benchmark-live.test.js test/benchmark-measurement.test.js test/benchmark-quality.test.js test/benchmark-report.test.js test/benchmark-runner.test.js test/benchmark-multimodal.test.js",
|
|
43
|
+
"test": "bun test test/aih.test.js test/metrics.test.js test/discovery.test.js test/tui-pipeline.test.js test/tui-versions.test.js test/versions.test.js test/repositories.test.js test/service-updates.test.js && node --test test/proxy.test.js test/pxpipe-performance.test.js test/codex-config.test.js test/codex-routing.test.js test/codex-manager.test.js test/benchmark-live.test.js test/benchmark-measurement.test.js test/benchmark-quality.test.js test/benchmark-report.test.js test/benchmark-runner.test.js test/benchmark-multimodal.test.js",
|
|
41
44
|
"bench:proxy": "node scripts/bench-proxy.js",
|
|
42
45
|
"bench:models": "node scripts/bench-proxy.js --compare-models gpt-6-astra,anthropic/claude-fable-5-1 --formats responses",
|
|
43
46
|
"test:benchmark": "node --test test/benchmark-live.test.js test/benchmark-measurement.test.js test/benchmark-quality.test.js test/benchmark-report.test.js test/benchmark-runner.test.js test/benchmark-multimodal.test.js",
|
|
@@ -62,7 +65,7 @@
|
|
|
62
65
|
"license": "MIT",
|
|
63
66
|
"dependencies": {
|
|
64
67
|
"gpt-tokenizer": "3.4.0",
|
|
65
|
-
"pxpipe-proxy": "0.
|
|
68
|
+
"pxpipe-proxy": "0.14.0",
|
|
66
69
|
"toml-eslint-parser": "1.0.3",
|
|
67
70
|
"ws": "^8.21.3"
|
|
68
71
|
}
|
package/scripts/build.js
CHANGED
|
@@ -1,10 +1,17 @@
|
|
|
1
1
|
import { resolve } from "node:path";
|
|
2
|
+
import { patchPxpipe } from "./patch-pxpipe.js";
|
|
2
3
|
|
|
3
4
|
// Embed a Node worker so the compiled CLI uses the same proxy transport as npm.
|
|
4
5
|
const root = resolve(import.meta.dir, "..");
|
|
5
6
|
const outfile = process.argv[2] || resolve(root, "dist", process.platform === "win32" ? "aih.exe" : "aih");
|
|
7
|
+
patchPxpipe();
|
|
8
|
+
const thread = await Bun.build({
|
|
9
|
+
entrypoints: [resolve(root, "src/pxpipe-thread.js")], target: "node", format: "esm", minify: true,
|
|
10
|
+
});
|
|
11
|
+
if (!thread.success) throw new AggregateError(thread.logs, "Pxpipe thread build failed");
|
|
6
12
|
const worker = await Bun.build({
|
|
7
13
|
entrypoints: [resolve(root, "src/proxy-worker.js")], target: "node", format: "esm", minify: true,
|
|
14
|
+
define: { AIH_PXPIPE_THREAD_SOURCE: JSON.stringify(await thread.outputs[0].text()) },
|
|
8
15
|
});
|
|
9
16
|
if (!worker.success) throw new AggregateError(worker.logs, "Proxy worker build failed");
|
|
10
17
|
const result = await Bun.build({
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync, renameSync, rmSync } from "node:fs";
|
|
2
|
+
import { dirname, resolve } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
|
|
5
|
+
const original = "info.responsesComposition = measureResponsesComposition(req, inputWasString, originalInputString, inputItems);";
|
|
6
|
+
// Only the diagnostic copy is filtered. The transformer continues using req/inputItems unchanged.
|
|
7
|
+
const replacement = `// aih: partial diagnostics exclude opaque payloads (pxpipe 0.14.0).
|
|
8
|
+
const diagnosticOriginal = JSON.stringify(req);
|
|
9
|
+
const diagnosticJson = JSON.stringify(req, (key, value) => {
|
|
10
|
+
if (key === 'encrypted_content') return undefined;
|
|
11
|
+
if (['image', 'input_image', 'output_image', 'image_url', 'input_audio', 'audio', 'audio_url', 'input_video', 'video', 'video_url'].includes(value?.type) || value?.inline_data || value?.inlineData)
|
|
12
|
+
return { type: value.type || 'opaque_media' };
|
|
13
|
+
if (['compaction', 'compaction_trigger', 'context_compaction'].includes(value?.type))
|
|
14
|
+
return { type: value.type, id: value.id };
|
|
15
|
+
// Tool outputs may contain JSON-serialized media instead of a content array.
|
|
16
|
+
if (key === 'output' && typeof value === 'string' && /"(?:encrypted_content|inline_data|inlineData)"|"type"\\s*:\\s*"(?:image|input_image|output_image|image_url|input_audio|audio|audio_url|input_video|video|video_url)"/.test(value)) {
|
|
17
|
+
try { const parsed = JSON.parse(value); if (parsed && typeof parsed === 'object') return parsed; } catch {}
|
|
18
|
+
}
|
|
19
|
+
return value;
|
|
20
|
+
});
|
|
21
|
+
const diagnosticRequest = JSON.parse(diagnosticJson);
|
|
22
|
+
info.responsesComposition = measureResponsesComposition(diagnosticRequest, inputWasString, originalInputString, inputWasString ? [] : diagnosticRequest.input);
|
|
23
|
+
info.responsesComposition.excludedBytes = Math.max(0, new TextEncoder().encode(diagnosticOriginal).length - new TextEncoder().encode(diagnosticJson).length);
|
|
24
|
+
info.responsesComposition.partial = diagnosticJson !== diagnosticOriginal;`;
|
|
25
|
+
|
|
26
|
+
export function patchPxpipeSource(source, version) {
|
|
27
|
+
if (version !== "0.14.0") throw new Error(`Review the pxpipe diagnostic patch before using version ${version}`);
|
|
28
|
+
if (source.includes(replacement)) return source;
|
|
29
|
+
if (source.split(original).length !== 2) throw new Error("pxpipe diagnostic patch target changed");
|
|
30
|
+
return source.replace(original, replacement);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function patchPxpipe() {
|
|
34
|
+
const entry = fileURLToPath(import.meta.resolve("pxpipe-proxy"));
|
|
35
|
+
const manifest = JSON.parse(readFileSync(resolve(dirname(entry), "../../package.json"), "utf8"));
|
|
36
|
+
const file = resolve(dirname(entry), "openai.js");
|
|
37
|
+
const source = readFileSync(file, "utf8");
|
|
38
|
+
const patched = patchPxpipeSource(source, manifest.version);
|
|
39
|
+
if (patched !== source) {
|
|
40
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
41
|
+
try { writeFileSync(temporary, patched); renameSync(temporary, file); }
|
|
42
|
+
finally { rmSync(temporary, { force: true }); }
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) patchPxpipe();
|
package/src/index.js
CHANGED
|
@@ -73,6 +73,7 @@ ${bold("PROXY OPTIONS (start/up/restart proxy):")}
|
|
|
73
73
|
${gray("--interceptor <file.mjs>")} JavaScript hooks loaded at startup; quote paths with spaces
|
|
74
74
|
${gray("--preset <name>")} pxpipe | headroom | rtk | headroom-pxpipe | rtk-pxpipe |
|
|
75
75
|
rtk-headroom-pxpipe | none (fresh default: none)
|
|
76
|
+
pxpipe runs in up to 2 persistent workers; excluded models skip the queue
|
|
76
77
|
${gray("--headroom-url <url>")} Headroom service (default: http://127.0.0.1:8787)
|
|
77
78
|
${gray("--rtk-filter <name>")} Fixed rtk pipe filter; --rtk-filter= restores auto-detection
|
|
78
79
|
${gray("--max-body-bytes <num>")} Positive integer; buffered request / WebSocket limit
|
package/src/proxy-presets.js
CHANGED
|
@@ -4,6 +4,7 @@ import zlib from "node:zlib";
|
|
|
4
4
|
import { performance } from "node:perf_hooks";
|
|
5
5
|
import { tokenStage } from "./proxy-stats.js";
|
|
6
6
|
import { requestImages } from "./request-images.js";
|
|
7
|
+
import { createPxpipePool } from "./pxpipe-pool.js";
|
|
7
8
|
|
|
8
9
|
// Fixed recipes; the user's --interceptor runs afterwards and can inspect/edit the result.
|
|
9
10
|
const PRESETS = ["none", "pxpipe", "headroom", "rtk", "headroom-pxpipe", "rtk-pxpipe", "rtk-headroom-pxpipe"];
|
|
@@ -79,12 +80,13 @@ function rtkPipe(text, filter, limit) {
|
|
|
79
80
|
|
|
80
81
|
export async function createPresetHooks(config, onStats = () => {}) {
|
|
81
82
|
if (!config.preset || config.preset === "none") return {};
|
|
82
|
-
const { countTokens: tokenize } = await import("gpt-tokenizer/encoding/o200k_base");
|
|
83
|
+
const { countTokens: tokenize } = config.preset.startsWith("rtk") ? await import("gpt-tokenizer/encoding/o200k_base") : {};
|
|
83
84
|
function countTokens(text) {
|
|
84
85
|
try { return tokenize(text, { disallowedSpecial: new Set() }); }
|
|
85
86
|
catch { return NaN; } // Observability must not reject an otherwise valid request.
|
|
86
87
|
}
|
|
87
|
-
const px = config.preset.includes("pxpipe") ? await import("pxpipe-proxy") : null;
|
|
88
|
+
const px = config.preset.includes("pxpipe") ? await import("pxpipe-proxy/applicability") : null;
|
|
89
|
+
const pool = px ? createPxpipePool(config.maxBodyBytes) : null;
|
|
88
90
|
const models = config.models?.split(",");
|
|
89
91
|
const wsModels = new WeakMap();
|
|
90
92
|
const warnedEncodings = new Set();
|
|
@@ -139,6 +141,7 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
139
141
|
const bypassPxpipe = px && config.pxpipeNativeImages === "bypass" && requestImages(body, { identities: false }).length > 0;
|
|
140
142
|
let changed = false;
|
|
141
143
|
const stages = [];
|
|
144
|
+
let pxpipeTimings = {};
|
|
142
145
|
const report = error => {
|
|
143
146
|
// Observability must never interrupt proxy traffic; no request bodies are passed to the recorder.
|
|
144
147
|
// Optional correlation only; never pass headers or bodies to the recorder.
|
|
@@ -154,7 +157,7 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
154
157
|
} catch {}
|
|
155
158
|
try {
|
|
156
159
|
const update = onStats({ model, preset: config.preset, transport: websocket ? "WS" : "HTTP", changed, stages, error,
|
|
157
|
-
timings: { presetMs: Math.round((performance.now() - started) * 10) / 10 },
|
|
160
|
+
timings: { presetMs: Math.round((performance.now() - started) * 10) / 10, ...pxpipeTimings },
|
|
158
161
|
...source, ...(requestId ? { requestId } : {}) });
|
|
159
162
|
// ponytail: WS measures presets only; response timings need per-response-ID correlation.
|
|
160
163
|
if (!websocket && typeof update === "function") context.updateTiming = update;
|
|
@@ -187,28 +190,14 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
187
190
|
stages.push(tokenStage("pxpipe", 0, 0, false, "native_images_present", "pxpipe_estimate"));
|
|
188
191
|
} else if (px && (models ? models.some(m => m.endsWith("*") ? model.startsWith(m.slice(0, -1)) : model === m) : px.isPxpipeSupportedModel(model) || px.isPxpipeSupportedGptModel(model))) {
|
|
189
192
|
const bytes = Buffer.from(JSON.stringify({ ...body, model }));
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
if (!Number.isFinite(before) || !Number.isFinite(after)) {
|
|
199
|
-
// Anthropic's transformer lacks token totals: count text locally and include newly rendered images.
|
|
200
|
-
const textTokens = value => countTokens(JSON.stringify(value, (key, item) =>
|
|
201
|
-
["image", "input_image", "image_url"].includes(item?.type) || key === "encrypted_content" ? undefined : item));
|
|
202
|
-
before = textTokens(JSON.parse(bytes));
|
|
203
|
-
let imageTokens;
|
|
204
|
-
try { imageTokens = info.imageDims?.reduce((sum, d) => sum + px.openAIVisionTokens(model, d.width, d.height), 0); } catch {}
|
|
205
|
-
after = Number.isFinite(imageTokens) ? textTokens(JSON.parse(Buffer.from(result.body))) + imageTokens : undefined;
|
|
206
|
-
method = "o200k_and_vision_estimate";
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
stages.push(tokenStage("pxpipe", before, after, Boolean(info.compressed),
|
|
210
|
-
info.compressed ? "applied" : String(info.reason || "unchanged").split(/[^a-z_]/i)[0].slice(0, 40), method));
|
|
211
|
-
if (result.info?.compressed) {
|
|
193
|
+
let sessionId;
|
|
194
|
+
try { sessionId = JSON.parse(context.headers?.["x-codex-turn-metadata"] || "{}").session_id; } catch {}
|
|
195
|
+
const result = await pool.run({ body: bytes, format, model }, {
|
|
196
|
+
sessionId: typeof sessionId === "string" ? sessionId : undefined, signal: context.signal,
|
|
197
|
+
});
|
|
198
|
+
pxpipeTimings = Object.fromEntries(Object.entries(result.timings).map(([key, value]) => [key, Math.round(value * 10) / 10]));
|
|
199
|
+
stages.push(result.stage);
|
|
200
|
+
if (result.stage.applied) {
|
|
212
201
|
const transformed = JSON.parse(Buffer.from(result.body).toString("utf8"));
|
|
213
202
|
if (!Object.hasOwn(body, "model")) delete transformed.model;
|
|
214
203
|
// Only replace the AI request, preserving a WebSocket event's outer fields.
|
|
@@ -222,10 +211,11 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
222
211
|
const output = changed ? Buffer.from(JSON.stringify(envelope)) : raw;
|
|
223
212
|
report(false);
|
|
224
213
|
return output;
|
|
225
|
-
} catch (error) { report(
|
|
214
|
+
} catch (error) { report(!context.signal?.aborted); throw error; }
|
|
226
215
|
}
|
|
227
216
|
|
|
228
217
|
return {
|
|
218
|
+
close: () => pool?.close(),
|
|
229
219
|
async onRequest(context) {
|
|
230
220
|
const started = performance.now();
|
|
231
221
|
if (context.method !== "POST" || !/\bapplication\/(?:[\w.-]+\+)?json\b/i.test(String(context.headers["content-type"] || ""))) return;
|
package/src/proxy.js
CHANGED
|
@@ -4,7 +4,7 @@ import { resolve } from "node:path";
|
|
|
4
4
|
import { pathToFileURL } from "node:url";
|
|
5
5
|
import { Transform } from "node:stream";
|
|
6
6
|
import { pipeline } from "node:stream/promises";
|
|
7
|
-
import { performance } from "node:perf_hooks";
|
|
7
|
+
import { performance, monitorEventLoopDelay } from "node:perf_hooks";
|
|
8
8
|
import WebSocket, { WebSocketServer } from "ws";
|
|
9
9
|
import { normalizePresetOptions, createPresetHooks } from "./proxy-presets.js";
|
|
10
10
|
|
|
@@ -82,8 +82,16 @@ export async function startProxy(options) {
|
|
|
82
82
|
for (const name of HOOKS) {
|
|
83
83
|
if (hooks[name] !== undefined && typeof hooks[name] !== "function") throw new TypeError(`${name} must be a function`);
|
|
84
84
|
}
|
|
85
|
-
const
|
|
85
|
+
const loopDelay = monitorEventLoopDelay({ resolution: 20 });
|
|
86
|
+
loopDelay.enable();
|
|
87
|
+
const preset = await createPresetHooks(config, event => {
|
|
88
|
+
// Process-wide maximum since the preceding preset event; never a request CPU duration.
|
|
89
|
+
event.timings.eventLoopLagMs = Math.max(0, Math.round((loopDelay.max / 1e6 - 20) * 10) / 10);
|
|
90
|
+
loopDelay.reset();
|
|
91
|
+
return options.onStats?.(event);
|
|
92
|
+
}).catch(error => { loopDelay.disable(); throw error; });
|
|
86
93
|
for (const [name, hook] of Object.entries(preset)) {
|
|
94
|
+
if (name === "close") continue;
|
|
87
95
|
const custom = hooks[name];
|
|
88
96
|
hooks[name] = async context => { await hook(context); await custom?.(context); };
|
|
89
97
|
}
|
|
@@ -174,6 +182,7 @@ export async function startProxy(options) {
|
|
|
174
182
|
let finished = false;
|
|
175
183
|
let failed = false;
|
|
176
184
|
const timings = { state: "waiting" };
|
|
185
|
+
const cancellation = new AbortController();
|
|
177
186
|
const elapsed = since => Math.round((performance.now() - since) * 10) / 10;
|
|
178
187
|
const publishTiming = () => {
|
|
179
188
|
// Optional recorder updater: never emit a second preset event or disrupt traffic.
|
|
@@ -189,12 +198,14 @@ export async function startProxy(options) {
|
|
|
189
198
|
const failRequest = error => { failed = true; fail(response, error); };
|
|
190
199
|
response.once("finish", () => finishTiming(failed ? "error" : "completed"));
|
|
191
200
|
response.once("close", () => {
|
|
201
|
+
cancellation.abort();
|
|
192
202
|
finishTiming(failed ? "error" : "aborted");
|
|
193
203
|
upstream?.destroy();
|
|
194
204
|
});
|
|
195
205
|
request.on("error", error => { upstream?.destroy(); failRequest(error); });
|
|
196
206
|
try {
|
|
197
207
|
context = requestContext(request);
|
|
208
|
+
context.signal = cancellation.signal;
|
|
198
209
|
if (hooks.onRequest) {
|
|
199
210
|
context.body = await readBody(request, config.maxBodyBytes);
|
|
200
211
|
await hooks.onRequest(context);
|
|
@@ -263,6 +274,9 @@ export async function startProxy(options) {
|
|
|
263
274
|
socket.once("close", () => { if (!client) upstream?.terminate(); });
|
|
264
275
|
try {
|
|
265
276
|
const context = requestContext(request);
|
|
277
|
+
const cancellation = new AbortController();
|
|
278
|
+
context.signal = cancellation.signal;
|
|
279
|
+
socket.once("close", () => cancellation.abort());
|
|
266
280
|
const headers = headersForHop(context.headers);
|
|
267
281
|
for (const name of Object.keys(headers)) if (name.startsWith("sec-websocket-")) delete headers[name];
|
|
268
282
|
headers.host = target.host;
|
|
@@ -336,17 +350,21 @@ export async function startProxy(options) {
|
|
|
336
350
|
server.off("error", reject);
|
|
337
351
|
resolveListen();
|
|
338
352
|
});
|
|
339
|
-
});
|
|
353
|
+
}).catch(async error => { loopDelay.disable(); wsServer.close(); await preset.close?.(); throw error; });
|
|
340
354
|
const address = server.address();
|
|
341
355
|
const url = `http://${address.family === "IPv6" ? `[${address.address}]` : address.address}:${address.port}`;
|
|
356
|
+
let closing;
|
|
342
357
|
return {
|
|
343
358
|
url,
|
|
344
|
-
close: () =>
|
|
359
|
+
close: () => {
|
|
360
|
+
loopDelay.disable();
|
|
361
|
+
return closing ||= Promise.all([preset.close?.(), new Promise((resolveClose, reject) => {
|
|
345
362
|
for (const ws of upstreamSockets) ws.terminate();
|
|
346
363
|
for (const ws of wsServer.clients) ws.terminate();
|
|
347
364
|
for (const socket of connections) socket.destroy();
|
|
348
365
|
wsServer.close();
|
|
349
366
|
server.close(error => error ? reject(error) : resolveClose());
|
|
350
|
-
|
|
367
|
+
})]).then(() => undefined);
|
|
368
|
+
},
|
|
351
369
|
};
|
|
352
370
|
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { Worker } from "node:worker_threads";
|
|
2
|
+
import { performance } from "node:perf_hooks";
|
|
3
|
+
|
|
4
|
+
export function createPxpipePool(maxBodyBytes = 64 * 1024 * 1024, workerUrl = new URL("./pxpipe-thread.js", import.meta.url)) {
|
|
5
|
+
// The standalone CLI embeds a separate bundle: runtime relative files do not exist there.
|
|
6
|
+
if (typeof AIH_PXPIPE_THREAD_SOURCE !== "undefined") workerUrl = new URL(`data:text/javascript,${encodeURIComponent(AIH_PXPIPE_THREAD_SOURCE)}`);
|
|
7
|
+
const slots = Array.from({ length: 2 }, () => ({ worker: null, ready: false, job: null, queue: [] }));
|
|
8
|
+
let closed = false, sequence = 0, queuedBytes = 0;
|
|
9
|
+
const pendingTerminations = new Set();
|
|
10
|
+
const terminate = slot => {
|
|
11
|
+
const worker = slot.worker;
|
|
12
|
+
slot.worker = null;
|
|
13
|
+
slot.ready = false;
|
|
14
|
+
if (!worker) return;
|
|
15
|
+
const termination = worker.terminate();
|
|
16
|
+
pendingTerminations.add(termination);
|
|
17
|
+
termination.then(() => pendingTerminations.delete(termination), () => pendingTerminations.delete(termination));
|
|
18
|
+
};
|
|
19
|
+
const settle = (job, error, result) => {
|
|
20
|
+
job.signal?.removeEventListener("abort", job.abort);
|
|
21
|
+
if (error) job.reject(error); else job.resolve(result);
|
|
22
|
+
};
|
|
23
|
+
function dispatch(slot) {
|
|
24
|
+
if (closed || slot.job || !slot.queue.length) return;
|
|
25
|
+
if (!slot.worker) {
|
|
26
|
+
try { start(slot); } catch (error) { fail(slot, error); return; }
|
|
27
|
+
}
|
|
28
|
+
if (!slot.ready) return;
|
|
29
|
+
const job = slot.queue.shift();
|
|
30
|
+
queuedBytes -= job.bytes;
|
|
31
|
+
slot.job = job;
|
|
32
|
+
job.queueMs = performance.now() - job.queuedAt;
|
|
33
|
+
slot.worker.ref();
|
|
34
|
+
try { slot.worker.postMessage({ ...job.input, id: job.id }); }
|
|
35
|
+
catch (error) { fail(slot, error); }
|
|
36
|
+
}
|
|
37
|
+
function fail(slot, error) {
|
|
38
|
+
if (slot.job) settle(slot.job, error);
|
|
39
|
+
slot.job = null;
|
|
40
|
+
// A worker failing to initialize must reject its queue rather than restart endlessly.
|
|
41
|
+
for (const job of slot.queue.splice(0)) { queuedBytes -= job.bytes; settle(job, error); }
|
|
42
|
+
terminate(slot);
|
|
43
|
+
}
|
|
44
|
+
function start(slot) {
|
|
45
|
+
const worker = slot.worker = new Worker(workerUrl, { execArgv: [] });
|
|
46
|
+
worker.on("message", result => {
|
|
47
|
+
if (slot.worker !== worker) return;
|
|
48
|
+
if (result.ready) { slot.ready = true; if (!slot.queue.length) worker.unref(); dispatch(slot); return; }
|
|
49
|
+
const job = slot.job;
|
|
50
|
+
if (!job || result.id !== job.id) return fail(slot, new Error("Unexpected pxpipe worker response"));
|
|
51
|
+
slot.job = null;
|
|
52
|
+
worker.unref();
|
|
53
|
+
if (result.error) settle(job, new Error(result.error));
|
|
54
|
+
else settle(job, null, { ...result, timings: { ...result.timings, pxpipeQueueMs: job.queueMs } });
|
|
55
|
+
dispatch(slot);
|
|
56
|
+
});
|
|
57
|
+
worker.on("error", error => { if (slot.worker === worker) fail(slot, error); });
|
|
58
|
+
worker.on("exit", code => { if (slot.worker === worker) fail(slot, new Error(`pxpipe worker exited (${code})`)); });
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
run(input, { sessionId, signal } = {}) {
|
|
62
|
+
if (closed) return Promise.reject(new Error("pxpipe pool is closed"));
|
|
63
|
+
if (signal?.aborted) return Promise.reject(signal.reason);
|
|
64
|
+
if (slots.reduce((n, slot) => n + slot.queue.length, 0) >= 32 || queuedBytes + input.body.byteLength > maxBodyBytes)
|
|
65
|
+
return Promise.reject(Object.assign(new Error("pxpipe queue is full"), { statusCode: 503 }));
|
|
66
|
+
// ponytail: fixed session affinity preserves caches; two busy sessions can share a lane.
|
|
67
|
+
let hash = 0;
|
|
68
|
+
for (const char of sessionId || "") hash = (Math.imul(hash, 31) + char.charCodeAt(0)) >>> 0;
|
|
69
|
+
const slot = sessionId ? slots[hash % slots.length]
|
|
70
|
+
: slots.reduce((best, current) => current.queue.length + Boolean(current.job) < best.queue.length + Boolean(best.job) ? current : best);
|
|
71
|
+
return new Promise((resolve, reject) => {
|
|
72
|
+
const job = { id: ++sequence, input, resolve, reject, signal, bytes: input.body.byteLength, queuedAt: performance.now() };
|
|
73
|
+
job.abort = () => {
|
|
74
|
+
if (slot.job === job) { slot.job = null; terminate(slot); }
|
|
75
|
+
else { const index = slot.queue.indexOf(job); if (index < 0) return; slot.queue.splice(index, 1); queuedBytes -= job.bytes; }
|
|
76
|
+
settle(job, signal.reason);
|
|
77
|
+
dispatch(slot);
|
|
78
|
+
};
|
|
79
|
+
signal?.addEventListener("abort", job.abort, { once: true });
|
|
80
|
+
slot.queue.push(job);
|
|
81
|
+
queuedBytes += job.bytes;
|
|
82
|
+
dispatch(slot);
|
|
83
|
+
});
|
|
84
|
+
},
|
|
85
|
+
async close() {
|
|
86
|
+
closed = true;
|
|
87
|
+
for (const slot of slots) fail(slot, new Error("pxpipe pool is closed"));
|
|
88
|
+
await Promise.allSettled([...pendingTerminations]);
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { parentPort } from "node:worker_threads";
|
|
2
|
+
import { performance } from "node:perf_hooks";
|
|
3
|
+
import { countTokens } from "gpt-tokenizer/encoding/o200k_base";
|
|
4
|
+
import * as px from "pxpipe-proxy";
|
|
5
|
+
import { tokenStage } from "./proxy-stats.js";
|
|
6
|
+
|
|
7
|
+
parentPort.on("message", async ({ id, body, format, model }) => {
|
|
8
|
+
const started = performance.now();
|
|
9
|
+
const cpu = process.threadCpuUsage?.();
|
|
10
|
+
try {
|
|
11
|
+
const result = await (format === "anthropic" ? px.transformRequest(body, { model })
|
|
12
|
+
: format === "chat" ? px.transformOpenAIChatCompletions(body, { model }) : px.transformOpenAIResponses(body, { model }));
|
|
13
|
+
const info = result.info || {};
|
|
14
|
+
let before = 0, after = 0, method = "pxpipe_estimate";
|
|
15
|
+
if (info.compressed) {
|
|
16
|
+
before = info.baselineImagedTokens;
|
|
17
|
+
after = Number.isFinite(info.imageTokens) ? info.imageTokens + (info.nativeInjectedTokens ?? 0) : undefined;
|
|
18
|
+
if (!Number.isFinite(before) || !Number.isFinite(after)) {
|
|
19
|
+
const textTokens = value => {
|
|
20
|
+
try { return countTokens(JSON.stringify(value, (key, item) =>
|
|
21
|
+
["image", "input_image", "output_image", "image_url"].includes(item?.type) || key === "encrypted_content" ? undefined : item), { disallowedSpecial: new Set() }); }
|
|
22
|
+
catch { return NaN; }
|
|
23
|
+
};
|
|
24
|
+
before = textTokens(JSON.parse(Buffer.from(body)));
|
|
25
|
+
let imageTokens;
|
|
26
|
+
try { imageTokens = info.imageDims?.reduce((sum, d) => sum + px.openAIVisionTokens(model, d.width, d.height), 0); } catch {}
|
|
27
|
+
after = Number.isFinite(imageTokens) ? textTokens(JSON.parse(Buffer.from(result.body))) + imageTokens : undefined;
|
|
28
|
+
method = "o200k_and_vision_estimate";
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
const stage = tokenStage("pxpipe", before, after, Boolean(info.compressed),
|
|
32
|
+
info.compressed ? "applied" : String(info.reason || "unchanged").split(/[^a-z_]/i)[0].slice(0, 40), method);
|
|
33
|
+
if (info.responsesComposition) stage.diagnostics = {
|
|
34
|
+
partial: Boolean(info.responsesComposition.partial), excludedBytes: info.responsesComposition.excludedBytes ?? 0,
|
|
35
|
+
};
|
|
36
|
+
const output = info.compressed ? Uint8Array.from(result.body) : undefined;
|
|
37
|
+
const usage = cpu && process.threadCpuUsage(cpu);
|
|
38
|
+
parentPort.postMessage({ id, body: output, stage, timings: {
|
|
39
|
+
pxpipeMs: performance.now() - started,
|
|
40
|
+
...(usage ? { pxpipeCpuMs: (usage.user + usage.system) / 1000 } : {}),
|
|
41
|
+
} }, output ? [output.buffer] : []);
|
|
42
|
+
} catch (error) {
|
|
43
|
+
parentPort.postMessage({ id, error: error.message });
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
parentPort.postMessage({ ready: true });
|
package/src/tui.js
CHANGED
|
@@ -393,6 +393,11 @@ export class Dashboard {
|
|
|
393
393
|
...(event.error ? [] : [savedTokens(unmeasured ? null : event.saved) + (partial && !unmeasured ? yellow(" (parziale)") : "")]),
|
|
394
394
|
...(timing ? [
|
|
395
395
|
`proxy: ${duration(timing.presetMs)}`,
|
|
396
|
+
...(Number.isFinite(timing.pxpipeQueueMs) ? [
|
|
397
|
+
`coda: ${duration(timing.pxpipeQueueMs)}`, `pxpipe: ${duration(timing.pxpipeMs)}`,
|
|
398
|
+
...(Number.isFinite(timing.pxpipeCpuMs) ? [`CPU: ${duration(timing.pxpipeCpuMs)}`] : []),
|
|
399
|
+
] : []),
|
|
400
|
+
...(Number.isFinite(timing.eventLoopLagMs) ? [`loop max: ${duration(timing.eventLoopLagMs)}`] : []),
|
|
396
401
|
...(event.transport === "HTTP" ? [
|
|
397
402
|
`header: ${duration(timing.upstreamHeadersMs)}`, `tot: ${duration(timing.totalMs)}`,
|
|
398
403
|
...(Number.isInteger(timing.statusCode) && timing.statusCode >= 100 && timing.statusCode <= 599
|