@drakonkat/ai-helper 1.1.1 → 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/README.md CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  <p align="center">
8
8
  <a href="https://www.npmjs.com/package/@drakonkat/ai-helper"><img src="https://img.shields.io/npm/v/@drakonkat/ai-helper.svg?color=blue&style=flat-square" alt="NPM Version" /></a>
9
- <a href="https://nodejs.org/"><img src="https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen.svg?style=flat-square" alt="Node Version" /></a>
9
+ <a href="https://nodejs.org/"><img src="https://img.shields.io/badge/node-%3E%3D20.19.0-brightgreen.svg?style=flat-square" alt="Node Version" /></a>
10
10
  <a href="https://bun.sh/"><img src="https://img.shields.io/badge/bun-compatible-f472b6.svg?style=flat-square" alt="Bun Compatible" /></a>
11
11
  <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-green.svg?style=flat-square" alt="License: MIT" /></a>
12
12
  <img src="https://img.shields.io/badge/platform-windows%20%7C%20macos%20%7C%20linux-lightgrey.svg?style=flat-square" alt="Platforms" />
@@ -20,6 +20,11 @@
20
20
  - [Managed Services & Dashboards](#-managed-services--dashboards)
21
21
  - [Key Features](#-key-features)
22
22
  - [CLI Reference](#-cli-reference)
23
+ - [HTTP / WebSocket Proxy](#http--websocket-proxy)
24
+ - [Start a compression pipeline](#start-a-compression-pipeline)
25
+ - [Select models](#select-models)
26
+ - [Proxy token savings](#proxy-token-savings)
27
+ - [Troubleshooting](#proxy-troubleshooting)
23
28
  - [Programmatic JSON API](#-programmatic-json-api)
24
29
  - [Architecture & Documentation](#-architecture--documentation)
25
30
  - [Configuration & State](#-configuration--state)
@@ -36,9 +41,9 @@ When building, testing, and collaborating with local AI agents, coding assistant
36
41
  3. **`agentmemory`**: Persistent long-term agent memory server (`npx @agentmemory/agentmemory`).
37
42
  4. **`headroom`**: LLM context optimization & compression proxy (`headroom proxy`).
38
43
 
39
- Manually opening separate terminal tabs for each service is messy, clutters your workspace, and easily leads to orphaned background processes and blocked ports.
44
+ Manually opening separate terminal tabs for each service is messy, clutters your workspace, and easily leads to orphaned background processes and blocked ports.
40
45
 
41
- **`aih`** solves this with a lightweight, zero-dependency CLI that:
46
+ **`aih`** solves this with a lightweight CLI that:
42
47
  - **Spawns and backgrounds** all services independently.
43
48
  - **Auto-discovers** existing instances already running in external PowerShell / CMD / terminal windows.
44
49
  - **Terminates process trees cleanly** (`taskkill /T /F` on Windows, process groups on Unix) so no child workers or ports remain trapped.
@@ -55,13 +60,17 @@ You can run `ai-helper` immediately using **`npx`** without cloning or installin
55
60
  # View services status and active dashboards
56
61
  npx @drakonkat/ai-helper status
57
62
 
58
- # Open all active web dashboards in your default browser
63
+ # Open service web dashboards in your default browser
59
64
  npx @drakonkat/ai-helper open
60
65
 
61
- # Start all background services
66
+ # Start ocx, agentmemory and the pxpipe proxy
62
67
  npx @drakonkat/ai-helper start
63
68
  ```
64
69
 
70
+ The CLI manages existing service commands: install/configure `ocx`, `headroom`
71
+ and any other services you want to use separately. The built-in proxy includes
72
+ the pxpipe library; its presets do not require a separate pxpipe proxy process.
73
+
65
74
  ### Global Installation
66
75
 
67
76
  To use the compact `aih` command globally anywhere in your terminal:
@@ -78,23 +87,25 @@ bun add -g @drakonkat/ai-helper
78
87
 
79
88
  ## 📦 Managed Services & Dashboards
80
89
 
81
- | Service | Background Command | Default Port / URL | Description |
82
- | :--- | :--- | :--- | :--- |
83
- | **`pxpipe`** | `npx pxpipe-proxy` | [`http://localhost:47821`](http://localhost:47821) | AI LLM & MCP protocol reverse proxy bridge |
84
- | **`ocx`** | `ocx start` | [`http://localhost:10100`](http://localhost:10100) | OpenCode interpreter execution daemon |
85
- | **`agentmemory`** | `npx @agentmemory/agentmemory` | [`http://localhost:3113`](http://localhost:3113) | Persistent agent long-term memory server & viewer |
86
- | **`headroom`** | `headroom proxy` | [`http://localhost:8787/dashboard`](http://localhost:8787/dashboard) | Context optimization & LLM compression proxy |
90
+ | Service | Background Command | Default Port / URL | GitHub | Description |
91
+ | :--- | :--- | :--- | :--- | :--- |
92
+ | **`pxpipe`** | `npx pxpipe-proxy` | [`http://localhost:47821`](http://localhost:47821) | [teamchong/pxpipe](https://github.com/teamchong/pxpipe) | AI LLM & MCP protocol reverse proxy bridge |
93
+ | **`ocx`** | `ocx start` | [`http://localhost:10100`](http://localhost:10100) | [lidge-jun/opencodex](https://github.com/lidge-jun/opencodex) | OpenCode interpreter execution daemon |
94
+ | **`agentmemory`** | `npx @agentmemory/agentmemory` | [`http://localhost:3113`](http://localhost:3113) | [rohitg00/agentmemory](https://github.com/rohitg00/agentmemory) | Persistent agent long-term memory server & viewer |
95
+ | **`headroom`** | `headroom proxy` | [`http://localhost:8787/dashboard`](http://localhost:8787/dashboard) | [headroomlabs-ai/headroom](https://github.com/headroomlabs-ai/headroom) | Context optimization & LLM compression proxy |
96
+ | **`proxy`** | `aih start proxy <upstream>` | `http://127.0.0.1:10101` | [drakonkat/ai-helper](https://github.com/drakonkat/ai-helper) | HTTP/SSE/WebSocket forwarding with optional presets; **no web dashboard** |
87
97
 
88
98
  ---
89
99
 
90
100
  ## ✨ Key Features
91
101
 
92
102
  - 🔍 **Real-Time Auto-Discovery**: Automatically queries OS process tables (`Win32_Process` and TCP listening connections on Windows, `ps` on Unix) to discover and manage processes started from external terminal windows.
93
- - 🌐 **One-Click Dashboard Launcher**: Run `aih open` to launch all active service dashboards in your browser in separate tabs.
103
+ - 🌐 **One-Click Dashboard Launcher**: Run `aih open` to launch service dashboards in your browser in separate tabs.
94
104
  - 🛡️ **Clean Process Tree Termination**: Kills parent and all nested child worker processes (`node.exe`, `iii.exe`, etc.) ensuring no ports remain locked.
95
105
  - 📜 **Live Log Streaming**: Unified stdout/stderr log capture per service with live real-time tailing (`aih logs <service> -f`).
96
106
  - 🤖 **Agent & Automation Friendly**: Native `--json` output format for IDE integrations, subagents, and automated workflows.
97
- - ⚡ **Zero Runtime Dependencies**: Built entirely on standard Node.js & Bun built-ins with instant startup time.
107
+ - 🔀 **Compression Presets**: pxpipe as a library, Headroom compression, RTK stdin filtering, or ordered combinations.
108
+ - 📊 **Proxy Savings**: Per-stage token estimates in `aih stats proxy`, the interactive UI and proxy logs.
98
109
 
99
110
  ---
100
111
 
@@ -104,35 +115,112 @@ bun add -g @drakonkat/ai-helper
104
115
 
105
116
  ```bash
106
117
  aih status
118
+ # Interactive view (press q to exit)
119
+ aih status -ui
107
120
  # or simply
108
121
  aih
109
122
  ```
110
123
 
111
124
  *Output:*
112
125
  ```text
113
- ai-helper v1.0.0 — Background AI Ecosystem Service Manager
126
+ ai-helper v1.1.1 — Background AI Ecosystem Service Manager
114
127
 
115
- SERVICE STATUS PID UPTIME DASHBOARD / URL COMMAND
116
- ─────────── ───────── ───── ────── ────────────────────── ────────────────────────────
117
- pxpipe ● RUNNING 36212 1h 42m http://localhost:47821 npx pxpipe-proxy
118
- ocx ● RUNNING 31540 54s http://localhost:10100 ocx start
119
- agentmemory ● RUNNING 44600 1h 32m http://localhost:3113 npx @agentmemory/agentmemory
128
+ SERVICE STATUS PID UPTIME ADDRESS REPO COMMAND
129
+ ─────────── ───────── ───── ────── ────────────────────── ───────────────────────────────────────── ────────────────────────────
130
+ pxpipe ● RUNNING 36212 1h 42m http://localhost:47821 https://github.com/teamchong/pxpipe npx pxpipe-proxy
131
+ ocx ● RUNNING 31540 54s http://localhost:10100 https://github.com/lidge-jun/opencodex ocx start
132
+ agentmemory ● RUNNING 44600 1h 32m http://localhost:3113 https://github.com/rohitg00/agentmemory npx @agentmemory/agentmemory
120
133
 
121
134
  Use 'aih open [service]' to open dashboards in browser or 'aih start' to launch.
122
135
  ```
123
136
 
137
+ Run `aih status --ui` in a terminal for the interactive live dashboard. Its
138
+ `REPO` column shows the GitHub owner/repository; the selected service's full
139
+ repository and dashboard URLs appear below the table. Press **`g`** to open its
140
+ repository. Plain `status` prints full repository links, and `status --json`
141
+ includes `repositoryUrl` (null for custom services without metadata). The built-in
142
+ proxy links to ai-helper's repository, not its forwarding address.
143
+
144
+ The dashboard's
145
+ `VERSION` column shows the running service version when available, otherwise the
146
+ installed version. `UPDATE` shows `↑ <version>` for an available update,
147
+ `aggiornato` when no newer version is found, or `n/d` when the check cannot be
148
+ completed. Checks query npm/PyPI in the background every five minutes and after
149
+ a service restart; they never install or update services.
150
+
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.
207
+
124
208
  ---
125
209
 
126
210
  ### 2. Open Dashboards in Browser
127
211
 
128
212
  ```bash
129
- # Open all currently running service dashboards
213
+ # Open service dashboards (proxy is excluded)
130
214
  aih open
131
215
 
132
216
  # Open only a specific dashboard
133
217
  aih open agentmemory # Opens http://localhost:3113
134
218
  aih open ocx # Opens http://localhost:10100
135
219
  aih open pxpipe # Opens http://localhost:47821
220
+
221
+ # Open a repository instead of a dashboard (also works for the built-in proxy)
222
+ aih open ocx --repo
223
+ aih open proxy --repo
136
224
  ```
137
225
 
138
226
  ---
@@ -140,7 +228,7 @@ aih open pxpipe # Opens http://localhost:47821
140
228
  ### 3. Start Services
141
229
 
142
230
  ```bash
143
- # Start all configured services
231
+ # Start ocx, agentmemory and the pxpipe proxy
144
232
  aih start
145
233
 
146
234
  # Start a specific service
@@ -148,6 +236,22 @@ aih start pxpipe
148
236
  aih start agentmemory
149
237
  ```
150
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
+
249
+ `aih start` (also `aih up` and starts targeting individual services) checks npm's
250
+ `latest` release of `@drakonkat/ai-helper`. If a newer version exists, it prints
251
+ the installed/latest versions and the update command to stderr. The check times
252
+ out after 1.5 seconds; network errors never prevent startup. Updates are not
253
+ installed automatically. Compiled executables must be rebuilt to update them.
254
+
151
255
  ---
152
256
 
153
257
  ### 4. Stop Services
@@ -189,6 +293,341 @@ aih logs ocx -f
189
293
 
190
294
  ---
191
295
 
296
+ ## HTTP / WebSocket Proxy
297
+
298
+ Requires **Node.js 20.19+** (also on PATH when using the Bun CLI or compiled executable).
299
+ Use **Node.js 24+ for Codex**, whose Zstandard request compression needs Node.js 22.15+.
300
+
301
+ ### Start a compression pipeline
302
+
303
+ For a local OpenCodex upstream on port `10100`, with the aih listener on `10102`:
304
+
305
+ ```bash
306
+ # Start the upstream and compression service, if not already running
307
+ aih start ocx
308
+ aih start headroom
309
+
310
+ # First start: Headroom -> pxpipe library -> OpenCodex
311
+ aih start proxy http://127.0.0.1:10100/ --listen http://127.0.0.1:10102 --preset headroom-pxpipe --models "gpt-6-astra,google-antigravity/gemini-3.8*"
312
+
313
+ # Inspect traffic and savings
314
+ aih stats proxy
315
+ aih status -ui
316
+ aih logs proxy -f
317
+ ```
318
+
319
+ Codex's two root base URLs are configured automatically after aih's proxy starts
320
+ successfully (see below). For other clients, set the API base URL to
321
+ **`http://127.0.0.1:10102/v1`**. The client
322
+ must connect to `10102` for these presets and statistics to run; connecting
323
+ directly to OpenCodex (`10100`), Headroom (`8787`) or pxpipe (`47821`) bypasses
324
+ this aih proxy. Keep the client's existing credentials and selected model.
325
+ Other clients are not configured automatically.
326
+
327
+ ### Automatic Codex configuration
328
+
329
+ After `aih start proxy` / `aih restart proxy`, and after `aih start ocx` /
330
+ `aih restart ocx` when an aih-managed proxy is running, aih sets these **root**
331
+ keys in `$CODEX_HOME/config.toml` (default: `~/.codex/config.toml`):
332
+
333
+ ```toml
334
+ openai_base_url = "http://127.0.0.1:10102/v1"
335
+ experimental_realtime_ws_base_url = "http://127.0.0.1:10102/v1"
336
+ ```
337
+
338
+ The URL uses the proxy's **actual bound host and port**, including dynamically
339
+ allocated ports, never its upstream address. Both keys use the HTTP base URL;
340
+ the realtime client handles the WebSocket transport. `start` on an already-running
341
+ service also reconciles the settings, and TUI start/restart actions use the same path.
342
+ When starting ocx, or a proxy targeting a known running ocx, aih waits up to 30 seconds
343
+ for ocx's `/readyz` response (`service: opencodex`, `status: ready`) before writing:
344
+ a live process or `/healthz` alone can precede ocx's own Codex configuration writes.
345
+ Older ocx versions without this readiness contract produce a warning rather than
346
+ risk a competing write. Neither credentials nor ocx's upstream/provider settings
347
+ are changed.
348
+
349
+ Automatic configuration targets root upstream URLs. For upstreams with a path
350
+ prefix (for example `/v1` or `/backend-api/codex`), aih warns and leaves Codex's
351
+ URLs unchanged: those routes require an explicitly chosen client base path to
352
+ avoid duplicating the API prefix.
353
+
354
+ Comments, line endings and other TOML settings are preserved. A first-write backup
355
+ of an existing file is kept at `config.toml.aih.bak` and never overwritten; a missing
356
+ config is created. Writes are locked and atomic. Invalid TOML, conflicting active
357
+ profile URL overrides, links, concurrent modifications, or filesystem errors leave
358
+ the config unchanged and produce a warning without stopping a successfully started
359
+ service. Profile/provider tables are never rewritten. Profiles selected explicitly
360
+ by a client and environment/CLI overrides can still take precedence over these root keys.
361
+
362
+ Set **`AIH_CODEX_AUTOCONFIG=0`** to disable this behavior, including in automation.
363
+ `status` and discovery are read-only with respect to Codex. Stopping the proxy does
364
+ not restore previous settings automatically; reconnect/reconfigure Codex before
365
+ using it without the proxy. Restart an already-open Codex client if it cached its
366
+ configuration. JSON start/restart results include a `codexConfig` outcome.
367
+
368
+ After the first start, use `restart` to change options; unspecified options are
369
+ retained. Choose one of these alternatives:
370
+
371
+ ```bash
372
+ # Keep the destination, listener and model selection; change the pipeline
373
+ aih restart proxy --preset rtk-pxpipe --rtk-filter=
374
+ aih restart proxy --preset pxpipe
375
+ aih restart proxy --preset headroom
376
+ aih restart proxy --preset rtk --rtk-filter=
377
+
378
+ # Return to Headroom -> pxpipe
379
+ aih restart proxy --preset headroom-pxpipe
380
+
381
+ # Forward without compression; clear any previously saved custom interceptor
382
+ aih restart proxy --preset none --interceptor=
383
+ ```
384
+
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).
394
+ `--rtk-filter=` selects automatic detection; `--rtk-filter grep` applies the
395
+ grep-output filter to every tool result, so use it only with matching output.
396
+
397
+ ### Select models
398
+
399
+ **All models are forwarded.** `--models` selects only which models pxpipe may
400
+ compress; Headroom/RTK still process eligible requests outside that list.
401
+ Names match the `model` in the request, including any provider prefix.
402
+ For example, an AGY catalog entry can be `google-antigravity/gemini-3.8-flash`,
403
+ while Astra is `gpt-6-astra`.
404
+
405
+ ```bash
406
+ # Exact Astra name plus any Gemini 3.8 variant under the AGY prefix
407
+ aih restart proxy --models "gpt-6-astra,google-antigravity/gemini-3.8*"
408
+
409
+ # Include the GPT-5.5 and GPT-5.6 selections too
410
+ aih restart proxy --models "gpt-5.5,gpt-5.6*,gpt-6-astra,google-antigravity/gemini-3.8*"
411
+
412
+ # Restore pxpipe's own default selection
413
+ aih restart proxy --models=
414
+ ```
415
+
416
+ An explicit list **replaces** the saved list. Only a trailing `*` is supported;
417
+ use the exact IDs from your client's model catalog. Selecting a model allows
418
+ compression but does not force it: pxpipe can leave short or unprofitable
419
+ requests unchanged. The upstream must support the selected model/API format.
420
+
421
+ ### Transport and lifecycle
422
+
423
+ ```bash
424
+ aih start proxy http://127.0.0.1:10100/
425
+ # Also accepts the shorthand: aih start proxy http:127.0.0.1:10100/
426
+
427
+ aih start proxy http://127.0.0.1:10100/ --listen http://127.0.0.1:10101 --interceptor ./interceptor.mjs
428
+ aih status proxy --json
429
+ aih logs proxy -f
430
+ aih restart proxy
431
+ aih stop proxy
432
+ ```
433
+
434
+ The positional URL is the **upstream destination**. The default listener is
435
+ `http://127.0.0.1:10101`. Point the AI client's API base URL at this listener,
436
+ keeping its usual API path: for example, `http://127.0.0.1:10101/v1` forwards
437
+ `/v1/responses` to `http://127.0.0.1:10100/v1/responses`. WebSockets use the same
438
+ port and path with `ws://`; an HTTPS upstream automatically uses WSS.
439
+ An upstream path is a prefix: upstream `https://example.com/backend-api/codex`
440
+ plus client `/responses` becomes `/backend-api/codex/responses`.
441
+
442
+ `start` runs in the background and reports success only after the socket is
443
+ listening and the interceptor has loaded. One proxy is managed at a time;
444
+ `restart proxy <upstream> [options]` changes its configuration. Omitted options
445
+ reuse the last successful configuration, stored in `~/.aih/state.json`.
446
+ Use `--interceptor=` to clear an interceptor. Once configured, the proxy also
447
+ participates in unqualified `start`, `stop`, `restart` and `status` commands.
448
+
449
+ HTTP methods, paths, queries, authentication headers, status codes, cookies and
450
+ payload bytes are forwarded. SSE stays streaming, with backpressure and upstream
451
+ cancellation when the client disconnects. HTTP redirects are returned to the
452
+ client without following or rewriting `Location`. WebSocket text/binary messages,
453
+ subprotocol selection, ping/pong and close codes are relayed. `Host`, hop-by-hop
454
+ headers and WebSocket handshake/framing are regenerated for each connection.
455
+ TLS certificates are verified normally; HTTP body compression is preserved.
456
+
457
+ This is a **reverse proxy**: apart from the explicit Codex startup integration
458
+ above, it does not configure clients, intercept unrelated machine traffic,
459
+ implement CONNECT/TLS interception, or translate
460
+ between AI API formats. Both sides must speak the same protocol. The listener
461
+ accepts loopback addresses only. OpenCodex's
462
+ [HTTP/SSE relay](https://github.com/lidge-jun/opencodex/blob/main/src/server/relay.ts)
463
+ and [WebSocket bridge](https://github.com/lidge-jun/opencodex/blob/main/src/server/ws-bridge.ts)
464
+ were reviewed as transport references; provider-specific rewriting is left to
465
+ the upstream service or your interceptor.
466
+
467
+ ### Reproducible proxy benchmarks
468
+
469
+ Compare the same corpus through real proxy presets without reconfiguring managed services
470
+ or mixing the aih proxy statistics. Offline replay measures common token estimates, latency and
471
+ information preservation; explicit `--live` adds provider usage and answer checks.
472
+
473
+ ```powershell
474
+ npm run bench:proxy -- --presets none,pxpipe --formats responses --warmup 0 --repetitions 1
475
+ npm run bench:proxy -- --headroom-url http://127.0.0.1:8787 --repetitions 5
476
+ ```
477
+
478
+ Results include JSON, JSONL, CSV and Markdown. Unknown image costs are not counted
479
+ as zero, and offline checks never claim a semantic-quality winner. Benchmark-only
480
+ pxpipe allowlisting defaults to all fixture models so imaging is actually exercised.
481
+ See [benchmark documentation](docs/benchmark.md) for corpus customization, live
482
+ evaluation, privacy, limitations and quality/performance decision thresholds.
483
+
484
+ ### Preset behavior
485
+
486
+ The recipes live in [src/proxy-presets.js](src/proxy-presets.js). All support
487
+ `--interceptor ./interceptor.mjs`, which runs **after** the preset for further
488
+ editing or logging. Configuration is saved; `aih restart proxy` reuses it.
489
+ Use `--models=` to restore pxpipe's default model selection and `--rtk-filter=`
490
+ to restore RTK auto-detection.
491
+
492
+ - **pxpipe:** calls the [pxpipe library](https://github.com/teamchong/pxpipe#library-use-no-proxy),
493
+ selecting the transformer for Anthropic Messages, OpenAI Chat Completions or
494
+ OpenAI Responses. `--models` is an explicit allowlist of exact names or trailing
495
+ `*` prefixes; without it, pxpipe's own supported-model defaults apply. The library
496
+ decides whether imaging is worthwhile; short/unprofitable requests stay unchanged.
497
+ An explicit allowlist opts those models into imaging; it is not a quality guarantee.
498
+ - **headroom:** sends messages to [`POST /v1/compress`](https://headroomlabs-ai.github.io/headroom/proxy/)
499
+ in `lossy_inline` mode, then forwards the result to your original upstream.
500
+ It carries system prompts and tool definitions unchanged. For Responses it compresses
501
+ only text in `function_call_output` items, preserving calls, IDs, reasoning and images.
502
+ This compression endpoint does not provide the full Headroom proxy's tool-schema
503
+ optimization or cache alignment. Set `HEADROOM_PROXY_TOKEN` before starting aih
504
+ if Headroom requires its own token; the client's provider credentials are never
505
+ sent to the compression service.
506
+ - **rtk:** runs [`rtk pipe`](https://github.com/rtk-ai/rtk) with tool-result text on
507
+ stdin. `--rtk-filter` selects one fixed filter for all results; omit it for detection.
508
+ Use a fixed filter only when the tool output matches that format. Empty or larger
509
+ results are discarded. Prompts, tool calls and binary content are left untouched;
510
+ no command from an AI request is executed.
511
+ - **headroom-pxpipe:** always applies Headroom first; `--models` gates only the
512
+ following pxpipe stage.
513
+ - **rtk-pxpipe:** applies RTK to tool-result text first, then the pxpipe library.
514
+ `--rtk-filter` controls RTK and `--models` gates only pxpipe; RTK still runs for
515
+ models outside the allowlist. This chain needs RTK on PATH, with no Headroom service.
516
+
517
+ Presets process JSON POSTs on Messages, Chat Completions and Responses routes,
518
+ and outgoing WebSocket `response.create` events (flat or nested under `response`).
519
+ WebSocket model selection uses the event's model, then the last model on that
520
+ connection, then the URL's `model` query. Requests with no resolvable model pass
521
+ through. Binary frames, response events and SSE are unchanged. Gzip, deflate,
522
+ Brotli and Zstandard HTTP request bodies are decoded with the configured size limit only for
523
+ inspection; changed bodies are sent as plain JSON with corrected headers.
524
+ Zstandard (`Content-Encoding: zstd`, used by Codex) requires Node.js 22.15+.
525
+ Unsupported encodings pass through with a warning in `aih logs proxy`, without preset processing.
526
+ Headroom and RTK have a 30-second timeout. A failed stage returns HTTP 502 or
527
+ closes the WebSocket; it never silently retries the AI request.
528
+
529
+ ### Proxy token savings
530
+
531
+ ```bash
532
+ aih stats proxy # cumulative savings by stage and last five requests
533
+ aih stats proxy --json # counters and last 20 requests, for scripts
534
+ aih status -ui # live proxy savings and configured pipeline
535
+ aih logs proxy -f # per-request [aih stats] lines
536
+ ```
537
+
538
+ Statistics start with the first eligible AI request processed by an active preset.
539
+ The worker stores counters and the last 20 measurements in `~/.aih/proxy-stats.json`
540
+ (`AIH_HOME` overrides the directory). They survive restarts and preset changes;
541
+ older traffic cannot be reconstructed. Prompts, tool outputs, images and credentials
542
+ are not stored in these statistics.
543
+
544
+ - Headroom supplies `tokens_before` and `tokens_after` for the messages sent to its
545
+ compression endpoint. These are Headroom's counts, not provider billing usage.
546
+ - RTK uses local `o200k_base` token counts on each tool output before/after filtering.
547
+ - pxpipe uses its estimated text baseline minus image tokens and injected text.
548
+ Where its transformer lacks these totals, a local text count plus the model's
549
+ image-cost estimate is used. Image base64 is never counted as ordinary text.
550
+ - The total sums **incremental** savings from consecutive stages, including negative
551
+ savings when a stage increases token use. Missing measurements are marked unknown
552
+ and the total is marked partial. Model exclusions and unprofitable requests appear
553
+ as zero savings with a reason.
554
+
555
+ These are **preset processing estimates**, before any custom interceptor. They do
556
+ not measure provider cache savings, prices, actual billed usage, or whether upstream
557
+ accepted the request. Errors in a preset count as processing failures with no credited
558
+ savings. Requests/events that the preset does not recognize are not counted.
559
+
560
+ The proxy has **no web dashboard**: its URL is a forwarding address. `aih open`
561
+ skips it, `aih open proxy` opens nothing, and the interactive UI offers no dashboard
562
+ shortcut when proxy is selected. Its statistics are available through the commands
563
+ above, without adding HTTP routes that could interfere with forwarded API paths.
564
+
565
+ ### Proxy troubleshooting
566
+
567
+ | Symptom | What to check |
568
+ | --- | --- |
569
+ | No proxy statistics | Confirm `aih status proxy --json` shows a preset and the expected listener, point the client at that listener, then send a new request. `--preset none` does not produce preset savings. |
570
+ | Traffic in logs, but no statistics | Check content type/encoding in the example interceptor logs and any `[aih preset]` warnings. Zstandard requests require Node.js 22.15+. Unsupported encodings are forwarded without preset processing. |
571
+ | `model_excluded` | Match `--models` to the request's exact model ID, including provider prefixes; a new list replaces the old one. |
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. |
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. |
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. |
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. |
576
+ | Windows build cannot replace `dist/aih.exe` (`EPERM`) | Exit any dashboard using that binary with `q`, then rebuild. |
577
+
578
+ With Windows NVM, the compiled CLI resolves the actual Node executable behind
579
+ the launcher before starting the worker. Node remains required on PATH even
580
+ when using the compiled aih executable.
581
+
582
+ ### JavaScript interceptor
583
+
584
+ Copy [src/proxy-interceptor.example.mjs](src/proxy-interceptor.example.mjs), edit
585
+ it and pass its path with `--interceptor`. Files run as trusted local JavaScript,
586
+ with normal Node imports and filesystem access. They load once at startup;
587
+ restart the proxy to apply edits. `.mjs` works regardless of the surrounding
588
+ package's module type. `.js` follows Node's usual package rules.
589
+
590
+ ```js
591
+ export async function onRequest(context) {
592
+ const body = JSON.parse(context.body.toString("utf8"));
593
+ console.log(context.method, context.path, body);
594
+ // body.model = "another-model";
595
+ context.body = JSON.stringify(body);
596
+ }
597
+
598
+ export function onWebSocketMessage(context) {
599
+ if (!context.isBinary) {
600
+ console.log(context.direction, context.body.toString("utf8"));
601
+ }
602
+ }
603
+ ```
604
+
605
+ All hooks are optional, may be async, and modify the supplied context in place;
606
+ return values are ignored. Unmodified bodies pass through. Body values accept
607
+ `Buffer`, `Uint8Array` or string. Header names use lowercase.
608
+
609
+ | Export | Context / behavior |
610
+ | --- | --- |
611
+ | `onRequest(context)` | `method`, `path`, `headers`, `upstream`, complete `body` Buffer. Runs for HTTP requests; enables request buffering. |
612
+ | `onResponse(context)` | `request`, `statusCode`, `headers`. Runs before response headers are sent. |
613
+ | `onResponseBody(context)` | Same response context plus complete `body` Buffer. Buffers non-SSE responses only; takes precedence over the chunk hook. Skipped for HEAD, 204 and 304. |
614
+ | `onResponseChunk(context)` | Same response context plus raw `body` chunk. Processes streaming responses without accumulating the whole body. |
615
+ | `onWebSocketMessage(context)` | `request` handshake metadata, `direction` (`request` or `response`), complete `body` Buffer and `isBinary`. Preserves message order, including async hooks. |
616
+
617
+ HTTP chunks can split JSON, SSE events and UTF-8 characters. Use incremental
618
+ decoding/parsing for streams; the whole-body response hook deliberately bypasses
619
+ SSE. Bodies remain in their original encoding, so decompress explicitly before
620
+ editing compressed data and update `content-encoding` and any integrity headers
621
+ if you change the representation. The proxy recalculates buffered body lengths
622
+ and removes `content-length` when transforming streamed responses.
623
+
624
+ `--max-body-bytes 67108864` controls buffered HTTP bodies, individual WebSocket
625
+ messages and each direction's pending WebSocket queue (64 MiB default).
626
+ Without body hooks, HTTP streams are not buffered or size-limited by the proxy.
627
+ Interceptor/upstream errors return HTTP 502 (oversized requests: 413), or close
628
+ the connection if headers have already been sent; failed WebSockets are closed.
629
+ Requests are never retried automatically.
630
+
192
631
  ## 🤖 Programmatic JSON API
193
632
 
194
633
  For AI agents, scripts, and CI/CD pipelines, use the `--json` flag:
@@ -209,7 +648,7 @@ aih status --json
209
648
  "uptime": "1h 42m",
210
649
  "url": "http://localhost:47821",
211
650
  "description": "AI LLM / MCP reverse proxy bridge (pxpipe-proxy)",
212
- "logPath": "C:\Users\user\.aih\logs\pxpipe.log",
651
+ "logPath": "C:\\Users\\user\\.aih\\logs\\pxpipe.log",
213
652
  "logSize": 48392
214
653
  },
215
654
  {
@@ -221,7 +660,7 @@ aih status --json
221
660
  "uptime": "54s",
222
661
  "url": "http://localhost:10100",
223
662
  "description": "OpenCode Interpreter daemon service (ocx start)",
224
- "logPath": "C:\Users\user\.aih\logs\ocx.log",
663
+ "logPath": "C:\\Users\\user\\.aih\\logs\\ocx.log",
225
664
  "logSize": 12480
226
665
  },
227
666
  {
@@ -233,7 +672,7 @@ aih status --json
233
672
  "uptime": "1h 32m",
234
673
  "url": "http://localhost:3113",
235
674
  "description": "Long-term persistent agent memory service (@agentmemory/agentmemory)",
236
- "logPath": "C:\Users\user\.aih\logs\agentmemory.log",
675
+ "logPath": "C:\\Users\\user\\.aih\\logs\\agentmemory.log",
237
676
  "logSize": 85190
238
677
  }
239
678
  ]
@@ -245,6 +684,7 @@ aih status --json
245
684
 
246
685
  State and log files are stored in the user's home directory under `~/.aih`:
247
686
  - **State File**: `~/.aih/state.json` (records active PIDs, start timestamps, URLs, and status).
687
+ - **Proxy Statistics**: `~/.aih/proxy-stats.json` (cumulative estimates and the last 20 measurements).
248
688
  - **Log Directory**: `~/.aih/logs/<service>.log` (stdout and stderr captured with startup banners).
249
689
 
250
690
  You can override the storage directory by setting the `AIH_HOME` environment variable:
@@ -269,18 +709,35 @@ export AIH_HOME=/custom/path/.aih
269
709
  git clone https://github.com/drakonkat/ai-helper.git
270
710
  cd ai-helper
271
711
 
712
+ # Install dependencies (Bun is also required for tests and compilation)
713
+ npm ci
714
+
272
715
  # Run CLI directly
273
716
  node bin/cli.js status
274
717
  # or with bun
275
718
  bun dev status
276
719
 
277
- # Run test suite
278
- bun test
720
+ # Run test suite (existing CLI checks on Bun, proxy integration checks on Node)
721
+ npm test
279
722
 
280
723
  # Optional: compile standalone binary (Windows/macOS/Linux)
281
724
  bun run build
282
725
  ```
283
726
 
727
+ To test the checkout before publishing or installing it globally, use
728
+ `node bin/cli.js` in place of `aih`, or the freshly compiled binary:
729
+
730
+ ```powershell
731
+ # Windows / PowerShell, from the repository directory
732
+ .\dist\aih.exe restart proxy http://127.0.0.1:10100/ --listen http://127.0.0.1:10102 --preset headroom-pxpipe --models "gpt-6-astra,google-antigravity/gemini-3.8*"
733
+ .\dist\aih.exe stats proxy
734
+ .\dist\aih.exe status -ui
735
+ ```
736
+
737
+ Use `./dist/aih` on macOS/Linux. Running an existing global `aih` does not test
738
+ changes in this checkout. Close the compiled UI with `q` before rebuilding it
739
+ on Windows; after a rebuild, restart the proxy to load the updated worker.
740
+
284
741
  ---
285
742
 
286
743
  ## 📄 License