@drakonkat/ai-helper 1.1.0 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ARCHITECTURE.md CHANGED
@@ -91,10 +91,21 @@ Uses `ps -eo pid,command` to match command line strings and extract active PIDs.
91
91
 
92
92
  ---
93
93
 
94
- ## 5. Zero-Dependency & Cross-Runtime Design
94
+ ## 5. Runtime Design
95
95
 
96
- `ai-helper` relies solely on standard built-in modules:
96
+ The service manager uses standard built-in modules:
97
97
  - `node:child_process` & `node:fs`
98
- - Works out of the box on **Node.js (>= 18.0.0)** and **Bun (>= 1.0.0)**.
98
+ - The CLI runs on **Node.js (>= 20.19.0)** and **Bun**.
99
99
  - Standalone binaries can be generated with `bun build --compile`.
100
100
 
101
+ The interceptor proxy uses Node's HTTP/HTTPS streams and the `ws` package.
102
+ Its worker always runs on Node, including when launched by Bun: Bun's compatibility
103
+ layers do not preserve all required WebSocket handshake and HTTP cancellation
104
+ behavior. `scripts/build.js` embeds a bundled Node worker in the compiled CLI;
105
+ on startup it is written to `AIH_HOME/proxy-worker.mjs`. Build with `bun run build`
106
+ to include this worker. Node must remain available on PATH.
107
+
108
+ The manager spawns the worker directly, without a shell, and waits for an IPC
109
+ ready/error message before saving its PID and configuration. Proxy stop targets
110
+ that PID only; it does not kill other processes by listening port. Interceptors
111
+ are loaded in the worker and use the same code path in source and compiled builds.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,21 @@ All notable changes to **`ai-helper` (`aih`)** are documented in this file.
4
4
 
5
5
  ---
6
6
 
7
+ ## [Unreleased]
8
+
9
+ ### Added
10
+ - GitHub `REPO` column in plain status and the live dashboard, `repositoryUrl` in JSON, and repository opening with `g` or `aih open <service> --repo`.
11
+ - Automatic Codex proxy URL configuration on managed proxy start/restart and ocx start/restart with an active proxy, including actual bound ports, ocx readiness checks, TOML-preserving edits, first-write backups, and `AIH_CODEX_AUTOCONFIG=0` opt-out.
12
+
13
+ ---
14
+
15
+ ## [1.1.1] - 2026-08-27
16
+
17
+ ### Updates
18
+ - Added TUI updates and fixed the agentMemory dashboard flow.
19
+
20
+ ---
21
+
7
22
  ## [1.1.0] - 2026-08-27
8
23
 
9
24
  ### 🚀 New Features
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
66
  # Start all background services
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,66 @@ 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
+ The `PIPELINE` panel separates current activity from Headroom's cumulative
152
+ statistics (since its counters started). `Token risparmiati` is saved tokens /
153
+ (input + saved); `Richieste cached` is cached requests / total requests, not a
154
+ cost-saving percentage. `Durata media` is the cumulative mean request latency.
155
+ Press **`d`** to toggle URLs, versions, token rates and metric definitions.
156
+ Rates use the interval between samples, not streaming token-generation speed.
157
+ Only explicit health checks show a service as `verificato`; a running process
158
+ alone is not a health check, and the final upstream is not monitored.
159
+ After a failed collection or five seconds without a sample, totals are marked
160
+ as old and live activity/rates are hidden until collection recovers.
161
+
124
162
  ---
125
163
 
126
164
  ### 2. Open Dashboards in Browser
127
165
 
128
166
  ```bash
129
- # Open all currently running service dashboards
167
+ # Open service dashboards (proxy is excluded)
130
168
  aih open
131
169
 
132
170
  # Open only a specific dashboard
133
171
  aih open agentmemory # Opens http://localhost:3113
134
172
  aih open ocx # Opens http://localhost:10100
135
173
  aih open pxpipe # Opens http://localhost:47821
174
+
175
+ # Open a repository instead of a dashboard (also works for the built-in proxy)
176
+ aih open ocx --repo
177
+ aih open proxy --repo
136
178
  ```
137
179
 
138
180
  ---
@@ -148,6 +190,12 @@ aih start pxpipe
148
190
  aih start agentmemory
149
191
  ```
150
192
 
193
+ `aih start` (also `aih up` and starts targeting individual services) checks npm's
194
+ `latest` release of `@drakonkat/ai-helper`. If a newer version exists, it prints
195
+ the installed/latest versions and the update command to stderr. The check times
196
+ out after 1.5 seconds; network errors never prevent startup. Updates are not
197
+ installed automatically. Compiled executables must be rebuilt to update them.
198
+
151
199
  ---
152
200
 
153
201
  ### 4. Stop Services
@@ -189,6 +237,333 @@ aih logs ocx -f
189
237
 
190
238
  ---
191
239
 
240
+ ## HTTP / WebSocket Proxy
241
+
242
+ Requires **Node.js 20.19+** (also on PATH when using the Bun CLI or compiled executable).
243
+ Use **Node.js 24+ for Codex**, whose Zstandard request compression needs Node.js 22.15+.
244
+
245
+ ### Start a compression pipeline
246
+
247
+ For a local OpenCodex upstream on port `10100`, with the aih listener on `10102`:
248
+
249
+ ```bash
250
+ # Start the upstream and compression service, if not already running
251
+ aih start ocx
252
+ aih start headroom
253
+
254
+ # First start: Headroom -> pxpipe library -> OpenCodex
255
+ 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*"
256
+
257
+ # Inspect traffic and savings
258
+ aih stats proxy
259
+ aih status -ui
260
+ aih logs proxy -f
261
+ ```
262
+
263
+ Codex's two root base URLs are configured automatically after aih's proxy starts
264
+ successfully (see below). For other clients, set the API base URL to
265
+ **`http://127.0.0.1:10102/v1`**. The client
266
+ must connect to `10102` for these presets and statistics to run; connecting
267
+ directly to OpenCodex (`10100`), Headroom (`8787`) or pxpipe (`47821`) bypasses
268
+ this aih proxy. Keep the client's existing credentials and selected model.
269
+ Other clients are not configured automatically.
270
+
271
+ ### Automatic Codex configuration
272
+
273
+ After `aih start proxy` / `aih restart proxy`, and after `aih start ocx` /
274
+ `aih restart ocx` when an aih-managed proxy is running, aih sets these **root**
275
+ keys in `$CODEX_HOME/config.toml` (default: `~/.codex/config.toml`):
276
+
277
+ ```toml
278
+ openai_base_url = "http://127.0.0.1:10102/v1"
279
+ experimental_realtime_ws_base_url = "http://127.0.0.1:10102/v1"
280
+ ```
281
+
282
+ The URL uses the proxy's **actual bound host and port**, including dynamically
283
+ allocated ports, never its upstream address. Both keys use the HTTP base URL;
284
+ the realtime client handles the WebSocket transport. `start` on an already-running
285
+ service also reconciles the settings, and TUI start/restart actions use the same path.
286
+ When starting ocx, or a proxy targeting a known running ocx, aih waits up to 30 seconds
287
+ for ocx's `/readyz` response (`service: opencodex`, `status: ready`) before writing:
288
+ a live process or `/healthz` alone can precede ocx's own Codex configuration writes.
289
+ Older ocx versions without this readiness contract produce a warning rather than
290
+ risk a competing write. Neither credentials nor ocx's upstream/provider settings
291
+ are changed.
292
+
293
+ Automatic configuration targets root upstream URLs. For upstreams with a path
294
+ prefix (for example `/v1` or `/backend-api/codex`), aih warns and leaves Codex's
295
+ URLs unchanged: those routes require an explicitly chosen client base path to
296
+ avoid duplicating the API prefix.
297
+
298
+ Comments, line endings and other TOML settings are preserved. A first-write backup
299
+ of an existing file is kept at `config.toml.aih.bak` and never overwritten; a missing
300
+ config is created. Writes are locked and atomic. Invalid TOML, conflicting active
301
+ profile URL overrides, links, concurrent modifications, or filesystem errors leave
302
+ the config unchanged and produce a warning without stopping a successfully started
303
+ service. Profile/provider tables are never rewritten. Profiles selected explicitly
304
+ by a client and environment/CLI overrides can still take precedence over these root keys.
305
+
306
+ Set **`AIH_CODEX_AUTOCONFIG=0`** to disable this behavior, including in automation.
307
+ `status` and discovery are read-only with respect to Codex. Stopping the proxy does
308
+ not restore previous settings automatically; reconnect/reconfigure Codex before
309
+ using it without the proxy. Restart an already-open Codex client if it cached its
310
+ configuration. JSON start/restart results include a `codexConfig` outcome.
311
+
312
+ After the first start, use `restart` to change options; unspecified options are
313
+ retained. Choose one of these alternatives:
314
+
315
+ ```bash
316
+ # Keep the destination, listener and model selection; change the pipeline
317
+ aih restart proxy --preset rtk-pxpipe --rtk-filter=
318
+ aih restart proxy --preset pxpipe
319
+ aih restart proxy --preset headroom
320
+ aih restart proxy --preset rtk --rtk-filter=
321
+
322
+ # Return to Headroom -> pxpipe
323
+ aih restart proxy --preset headroom-pxpipe
324
+
325
+ # Forward without compression; clear any previously saved custom interceptor
326
+ aih restart proxy --preset none --interceptor=
327
+ ```
328
+
329
+ RTK presets require an `rtk` executable with `rtk pipe` support on PATH.
330
+ `--rtk-filter=` selects automatic detection; `--rtk-filter grep` applies the
331
+ grep-output filter to every tool result, so use it only with matching output.
332
+
333
+ ### Select models
334
+
335
+ **All models are forwarded.** `--models` selects only which models pxpipe may
336
+ compress; Headroom/RTK still process eligible requests outside that list.
337
+ Names match the `model` in the request, including any provider prefix.
338
+ For example, an AGY catalog entry can be `google-antigravity/gemini-3.8-flash`,
339
+ while Astra is `gpt-6-astra`.
340
+
341
+ ```bash
342
+ # Exact Astra name plus any Gemini 3.8 variant under the AGY prefix
343
+ aih restart proxy --models "gpt-6-astra,google-antigravity/gemini-3.8*"
344
+
345
+ # Include the GPT-5.5 and GPT-5.6 selections too
346
+ aih restart proxy --models "gpt-5.5,gpt-5.6*,gpt-6-astra,google-antigravity/gemini-3.8*"
347
+
348
+ # Restore pxpipe's own default selection
349
+ aih restart proxy --models=
350
+ ```
351
+
352
+ An explicit list **replaces** the saved list. Only a trailing `*` is supported;
353
+ use the exact IDs from your client's model catalog. Selecting a model allows
354
+ compression but does not force it: pxpipe can leave short or unprofitable
355
+ requests unchanged. The upstream must support the selected model/API format.
356
+
357
+ ### Transport and lifecycle
358
+
359
+ ```bash
360
+ aih start proxy http://127.0.0.1:10100/
361
+ # Also accepts the shorthand: aih start proxy http:127.0.0.1:10100/
362
+
363
+ aih start proxy http://127.0.0.1:10100/ --listen http://127.0.0.1:10101 --interceptor ./interceptor.mjs
364
+ aih status proxy --json
365
+ aih logs proxy -f
366
+ aih restart proxy
367
+ aih stop proxy
368
+ ```
369
+
370
+ The positional URL is the **upstream destination**. The default listener is
371
+ `http://127.0.0.1:10101`. Point the AI client's API base URL at this listener,
372
+ keeping its usual API path: for example, `http://127.0.0.1:10101/v1` forwards
373
+ `/v1/responses` to `http://127.0.0.1:10100/v1/responses`. WebSockets use the same
374
+ port and path with `ws://`; an HTTPS upstream automatically uses WSS.
375
+ An upstream path is a prefix: upstream `https://example.com/backend-api/codex`
376
+ plus client `/responses` becomes `/backend-api/codex/responses`.
377
+
378
+ `start` runs in the background and reports success only after the socket is
379
+ listening and the interceptor has loaded. One proxy is managed at a time;
380
+ `restart proxy <upstream> [options]` changes its configuration. Omitted options
381
+ reuse the last successful configuration, stored in `~/.aih/state.json`.
382
+ Use `--interceptor=` to clear an interceptor. Once configured, the proxy also
383
+ participates in unqualified `start`, `stop`, `restart` and `status` commands.
384
+
385
+ HTTP methods, paths, queries, authentication headers, status codes, cookies and
386
+ payload bytes are forwarded. SSE stays streaming, with backpressure and upstream
387
+ cancellation when the client disconnects. HTTP redirects are returned to the
388
+ client without following or rewriting `Location`. WebSocket text/binary messages,
389
+ subprotocol selection, ping/pong and close codes are relayed. `Host`, hop-by-hop
390
+ headers and WebSocket handshake/framing are regenerated for each connection.
391
+ TLS certificates are verified normally; HTTP body compression is preserved.
392
+
393
+ This is a **reverse proxy**: apart from the explicit Codex startup integration
394
+ above, it does not configure clients, intercept unrelated machine traffic,
395
+ implement CONNECT/TLS interception, or translate
396
+ between AI API formats. Both sides must speak the same protocol. The listener
397
+ accepts loopback addresses only. OpenCodex's
398
+ [HTTP/SSE relay](https://github.com/lidge-jun/opencodex/blob/main/src/server/relay.ts)
399
+ and [WebSocket bridge](https://github.com/lidge-jun/opencodex/blob/main/src/server/ws-bridge.ts)
400
+ were reviewed as transport references; provider-specific rewriting is left to
401
+ the upstream service or your interceptor.
402
+
403
+ ### Reproducible proxy benchmarks
404
+
405
+ Compare the same corpus through real proxy presets without reconfiguring managed services
406
+ or mixing the aih proxy statistics. Offline replay measures common token estimates, latency and
407
+ information preservation; explicit `--live` adds provider usage and answer checks.
408
+
409
+ ```powershell
410
+ npm run bench:proxy -- --presets none,pxpipe --formats responses --warmup 0 --repetitions 1
411
+ npm run bench:proxy -- --headroom-url http://127.0.0.1:8787 --repetitions 5
412
+ ```
413
+
414
+ Results include JSON, JSONL, CSV and Markdown. Unknown image costs are not counted
415
+ as zero, and offline checks never claim a semantic-quality winner. Benchmark-only
416
+ pxpipe allowlisting defaults to all fixture models so imaging is actually exercised.
417
+ See [benchmark documentation](docs/benchmark.md) for corpus customization, live
418
+ evaluation, privacy, limitations and quality/performance decision thresholds.
419
+
420
+ ### Preset behavior
421
+
422
+ The recipes live in [src/proxy-presets.js](src/proxy-presets.js). All support
423
+ `--interceptor ./interceptor.mjs`, which runs **after** the preset for further
424
+ editing or logging. Configuration is saved; `aih restart proxy` reuses it.
425
+ Use `--models=` to restore pxpipe's default model selection and `--rtk-filter=`
426
+ to restore RTK auto-detection.
427
+
428
+ - **pxpipe:** calls the [pxpipe library](https://github.com/teamchong/pxpipe#library-use-no-proxy),
429
+ selecting the transformer for Anthropic Messages, OpenAI Chat Completions or
430
+ OpenAI Responses. `--models` is an explicit allowlist of exact names or trailing
431
+ `*` prefixes; without it, pxpipe's own supported-model defaults apply. The library
432
+ decides whether imaging is worthwhile; short/unprofitable requests stay unchanged.
433
+ An explicit allowlist opts those models into imaging; it is not a quality guarantee.
434
+ - **headroom:** sends messages to [`POST /v1/compress`](https://headroomlabs-ai.github.io/headroom/proxy/)
435
+ in `lossy_inline` mode, then forwards the result to your original upstream.
436
+ It carries system prompts and tool definitions unchanged. For Responses it compresses
437
+ only text in `function_call_output` items, preserving calls, IDs, reasoning and images.
438
+ This compression endpoint does not provide the full Headroom proxy's tool-schema
439
+ optimization or cache alignment. Set `HEADROOM_PROXY_TOKEN` before starting aih
440
+ if Headroom requires its own token; the client's provider credentials are never
441
+ sent to the compression service.
442
+ - **rtk:** runs [`rtk pipe`](https://github.com/rtk-ai/rtk) with tool-result text on
443
+ stdin. `--rtk-filter` selects one fixed filter for all results; omit it for detection.
444
+ Use a fixed filter only when the tool output matches that format. Empty or larger
445
+ results are discarded. Prompts, tool calls and binary content are left untouched;
446
+ no command from an AI request is executed.
447
+ - **headroom-pxpipe:** always applies Headroom first; `--models` gates only the
448
+ following pxpipe stage.
449
+ - **rtk-pxpipe:** applies RTK to tool-result text first, then the pxpipe library.
450
+ `--rtk-filter` controls RTK and `--models` gates only pxpipe; RTK still runs for
451
+ models outside the allowlist. This chain needs RTK on PATH, with no Headroom service.
452
+
453
+ Presets process JSON POSTs on Messages, Chat Completions and Responses routes,
454
+ and outgoing WebSocket `response.create` events (flat or nested under `response`).
455
+ WebSocket model selection uses the event's model, then the last model on that
456
+ connection, then the URL's `model` query. Requests with no resolvable model pass
457
+ through. Binary frames, response events and SSE are unchanged. Gzip, deflate,
458
+ Brotli and Zstandard HTTP request bodies are decoded with the configured size limit only for
459
+ inspection; changed bodies are sent as plain JSON with corrected headers.
460
+ Zstandard (`Content-Encoding: zstd`, used by Codex) requires Node.js 22.15+.
461
+ Unsupported encodings pass through with a warning in `aih logs proxy`, without preset processing.
462
+ Headroom and RTK have a 30-second timeout. A failed stage returns HTTP 502 or
463
+ closes the WebSocket; it never silently retries the AI request.
464
+
465
+ ### Proxy token savings
466
+
467
+ ```bash
468
+ aih stats proxy # cumulative savings by stage and last five requests
469
+ aih stats proxy --json # counters and last 20 requests, for scripts
470
+ aih status -ui # live proxy savings and configured pipeline
471
+ aih logs proxy -f # per-request [aih stats] lines
472
+ ```
473
+
474
+ Statistics start with the first eligible AI request processed by an active preset.
475
+ The worker stores counters and the last 20 measurements in `~/.aih/proxy-stats.json`
476
+ (`AIH_HOME` overrides the directory). They survive restarts and preset changes;
477
+ older traffic cannot be reconstructed. Prompts, tool outputs, images and credentials
478
+ are not stored in these statistics.
479
+
480
+ - Headroom supplies `tokens_before` and `tokens_after` for the messages sent to its
481
+ compression endpoint. These are Headroom's counts, not provider billing usage.
482
+ - RTK uses local `o200k_base` token counts on each tool output before/after filtering.
483
+ - pxpipe uses its estimated text baseline minus image tokens and injected text.
484
+ Where its transformer lacks these totals, a local text count plus the model's
485
+ image-cost estimate is used. Image base64 is never counted as ordinary text.
486
+ - The total sums **incremental** savings from consecutive stages, including negative
487
+ savings when a stage increases token use. Missing measurements are marked unknown
488
+ and the total is marked partial. Model exclusions and unprofitable requests appear
489
+ as zero savings with a reason.
490
+
491
+ These are **preset processing estimates**, before any custom interceptor. They do
492
+ not measure provider cache savings, prices, actual billed usage, or whether upstream
493
+ accepted the request. Errors in a preset count as processing failures with no credited
494
+ savings. Requests/events that the preset does not recognize are not counted.
495
+
496
+ The proxy has **no web dashboard**: its URL is a forwarding address. `aih open`
497
+ skips it, `aih open proxy` opens nothing, and the interactive UI offers no dashboard
498
+ shortcut when proxy is selected. Its statistics are available through the commands
499
+ above, without adding HTTP routes that could interfere with forwarded API paths.
500
+
501
+ ### Proxy troubleshooting
502
+
503
+ | Symptom | What to check |
504
+ | --- | --- |
505
+ | 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. |
506
+ | 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. |
507
+ | `model_excluded` | Match `--models` to the request's exact model ID, including provider prefixes; a new list replaces the old one. |
508
+ | Headroom shows `no_messages` | For Responses requests, this preset sends only tool-result text to Headroom. A request without tool outputs has nothing for that stage to compress. |
509
+ | Zero savings with `no_static_context`, `below_min_*` or `not_profitable` | The stage was reached but pxpipe chose to preserve the request. Zero savings is valid. |
510
+ | UI shows Headroom traffic but proxy statistics stay unchanged | The Headroom metrics/event panel is separate from the **PROXY** preset counters and can include other clients and older traffic. |
511
+ | Startup fails | Read `aih logs proxy -n 100`. Check Node on PATH, upstream/listener ports, and the saved interceptor path. `aih restart proxy --interceptor=` clears a missing interceptor. |
512
+ | Windows build cannot replace `dist/aih.exe` (`EPERM`) | Exit any dashboard using that binary with `q`, then rebuild. |
513
+
514
+ With Windows NVM, the compiled CLI resolves the actual Node executable behind
515
+ the launcher before starting the worker. Node remains required on PATH even
516
+ when using the compiled aih executable.
517
+
518
+ ### JavaScript interceptor
519
+
520
+ Copy [src/proxy-interceptor.example.mjs](src/proxy-interceptor.example.mjs), edit
521
+ it and pass its path with `--interceptor`. Files run as trusted local JavaScript,
522
+ with normal Node imports and filesystem access. They load once at startup;
523
+ restart the proxy to apply edits. `.mjs` works regardless of the surrounding
524
+ package's module type. `.js` follows Node's usual package rules.
525
+
526
+ ```js
527
+ export async function onRequest(context) {
528
+ const body = JSON.parse(context.body.toString("utf8"));
529
+ console.log(context.method, context.path, body);
530
+ // body.model = "another-model";
531
+ context.body = JSON.stringify(body);
532
+ }
533
+
534
+ export function onWebSocketMessage(context) {
535
+ if (!context.isBinary) {
536
+ console.log(context.direction, context.body.toString("utf8"));
537
+ }
538
+ }
539
+ ```
540
+
541
+ All hooks are optional, may be async, and modify the supplied context in place;
542
+ return values are ignored. Unmodified bodies pass through. Body values accept
543
+ `Buffer`, `Uint8Array` or string. Header names use lowercase.
544
+
545
+ | Export | Context / behavior |
546
+ | --- | --- |
547
+ | `onRequest(context)` | `method`, `path`, `headers`, `upstream`, complete `body` Buffer. Runs for HTTP requests; enables request buffering. |
548
+ | `onResponse(context)` | `request`, `statusCode`, `headers`. Runs before response headers are sent. |
549
+ | `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. |
550
+ | `onResponseChunk(context)` | Same response context plus raw `body` chunk. Processes streaming responses without accumulating the whole body. |
551
+ | `onWebSocketMessage(context)` | `request` handshake metadata, `direction` (`request` or `response`), complete `body` Buffer and `isBinary`. Preserves message order, including async hooks. |
552
+
553
+ HTTP chunks can split JSON, SSE events and UTF-8 characters. Use incremental
554
+ decoding/parsing for streams; the whole-body response hook deliberately bypasses
555
+ SSE. Bodies remain in their original encoding, so decompress explicitly before
556
+ editing compressed data and update `content-encoding` and any integrity headers
557
+ if you change the representation. The proxy recalculates buffered body lengths
558
+ and removes `content-length` when transforming streamed responses.
559
+
560
+ `--max-body-bytes 67108864` controls buffered HTTP bodies, individual WebSocket
561
+ messages and each direction's pending WebSocket queue (64 MiB default).
562
+ Without body hooks, HTTP streams are not buffered or size-limited by the proxy.
563
+ Interceptor/upstream errors return HTTP 502 (oversized requests: 413), or close
564
+ the connection if headers have already been sent; failed WebSockets are closed.
565
+ Requests are never retried automatically.
566
+
192
567
  ## 🤖 Programmatic JSON API
193
568
 
194
569
  For AI agents, scripts, and CI/CD pipelines, use the `--json` flag:
@@ -209,7 +584,7 @@ aih status --json
209
584
  "uptime": "1h 42m",
210
585
  "url": "http://localhost:47821",
211
586
  "description": "AI LLM / MCP reverse proxy bridge (pxpipe-proxy)",
212
- "logPath": "C:\Users\user\.aih\logs\pxpipe.log",
587
+ "logPath": "C:\\Users\\user\\.aih\\logs\\pxpipe.log",
213
588
  "logSize": 48392
214
589
  },
215
590
  {
@@ -221,7 +596,7 @@ aih status --json
221
596
  "uptime": "54s",
222
597
  "url": "http://localhost:10100",
223
598
  "description": "OpenCode Interpreter daemon service (ocx start)",
224
- "logPath": "C:\Users\user\.aih\logs\ocx.log",
599
+ "logPath": "C:\\Users\\user\\.aih\\logs\\ocx.log",
225
600
  "logSize": 12480
226
601
  },
227
602
  {
@@ -233,7 +608,7 @@ aih status --json
233
608
  "uptime": "1h 32m",
234
609
  "url": "http://localhost:3113",
235
610
  "description": "Long-term persistent agent memory service (@agentmemory/agentmemory)",
236
- "logPath": "C:\Users\user\.aih\logs\agentmemory.log",
611
+ "logPath": "C:\\Users\\user\\.aih\\logs\\agentmemory.log",
237
612
  "logSize": 85190
238
613
  }
239
614
  ]
@@ -245,6 +620,7 @@ aih status --json
245
620
 
246
621
  State and log files are stored in the user's home directory under `~/.aih`:
247
622
  - **State File**: `~/.aih/state.json` (records active PIDs, start timestamps, URLs, and status).
623
+ - **Proxy Statistics**: `~/.aih/proxy-stats.json` (cumulative estimates and the last 20 measurements).
248
624
  - **Log Directory**: `~/.aih/logs/<service>.log` (stdout and stderr captured with startup banners).
249
625
 
250
626
  You can override the storage directory by setting the `AIH_HOME` environment variable:
@@ -269,18 +645,35 @@ export AIH_HOME=/custom/path/.aih
269
645
  git clone https://github.com/drakonkat/ai-helper.git
270
646
  cd ai-helper
271
647
 
648
+ # Install dependencies (Bun is also required for tests and compilation)
649
+ npm ci
650
+
272
651
  # Run CLI directly
273
652
  node bin/cli.js status
274
653
  # or with bun
275
654
  bun dev status
276
655
 
277
- # Run test suite
278
- bun test
656
+ # Run test suite (existing CLI checks on Bun, proxy integration checks on Node)
657
+ npm test
279
658
 
280
659
  # Optional: compile standalone binary (Windows/macOS/Linux)
281
660
  bun run build
282
661
  ```
283
662
 
663
+ To test the checkout before publishing or installing it globally, use
664
+ `node bin/cli.js` in place of `aih`, or the freshly compiled binary:
665
+
666
+ ```powershell
667
+ # Windows / PowerShell, from the repository directory
668
+ .\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*"
669
+ .\dist\aih.exe stats proxy
670
+ .\dist\aih.exe status -ui
671
+ ```
672
+
673
+ Use `./dist/aih` on macOS/Linux. Running an existing global `aih` does not test
674
+ changes in this checkout. Close the compiled UI with `q` before rebuilding it
675
+ on Windows; after a rebuild, restart the proxy to load the updated worker.
676
+
284
677
  ---
285
678
 
286
679
  ## 📄 License