@drakonkat/ai-helper 1.2.14 → 1.2.16
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 -1
- package/README.md +74 -11
- package/docs/benchmark.md +15 -0
- package/package.json +2 -2
- package/scripts/bench-proxy.js +1 -0
- package/src/benchmark/live.js +7 -6
- package/src/benchmark/runner.js +7 -1
- package/src/index.js +12 -4
- package/src/manager.js +69 -2
- package/src/proxy-presets.js +8 -2
- package/src/proxy-setup.js +78 -0
- package/src/service-updates.js +99 -3
- package/src/startup-services.js +14 -0
- package/src/tui-proxy-setup.js +196 -0
- package/src/tui.js +84 -8
- package/src/utils/tool-path.js +35 -0
- package/src/utils/update-installer.js +2 -2
- package/src/utils/versions.js +3 -0
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,27 @@ All notable changes to **`ai-helper` (`aih`)** are documented in this file.
|
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
+
## [1.2.16] - 2026-10-28
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
- `aih update headroom` (and `aih headroom update`) now installs Headroom when it is missing, bootstrapping uv/Python via winget, Homebrew, apt-get or dnf as needed, instead of failing.
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## [1.2.15] - 2026-10-26
|
|
15
|
+
|
|
16
|
+
### Added
|
|
17
|
+
- Multi-select Startup step in proxy setup to choose the services launched together by plain `aih start` / `aih up`, preserving explicit CLI targets and upstream-first ordering.
|
|
18
|
+
- `c` / setup proxy in `aih status --ui`: guided editing of all proxy options, conditional tool fields, local drafts, configuration diff, preflight, save-only and apply-now actions.
|
|
19
|
+
- Separate desired proxy settings from the running worker, preserve explicit empty resets and attempt recovery of the previous worker after failed setup application.
|
|
20
|
+
- CLI `--pxpipe-native-images allow|bypass` and explicit `--models "*"` selection.
|
|
21
|
+
|
|
22
|
+
### Changed
|
|
23
|
+
- Explicit model allowlists now gate the entire compression recipe, including RTK and Headroom, not only pxpipe. Excluded requests remain byte-identical and retain per-stage bypass telemetry.
|
|
24
|
+
- Benchmark JSON records include proxy/worker timings and live provider headers/first-output timings when available.
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
7
28
|
## [1.2.14] - 2026-09-30
|
|
8
29
|
|
|
9
30
|
### Fixed
|
|
@@ -71,7 +92,7 @@ All notable changes to **`ai-helper` (`aih`)** are documented in this file.
|
|
|
71
92
|
|
|
72
93
|
---
|
|
73
94
|
|
|
74
|
-
## [
|
|
95
|
+
## [1.2.16] - 2026-10-28
|
|
75
96
|
|
|
76
97
|
### Added
|
|
77
98
|
- Explicit managed-service updates with `aih <service> update`, `aih update [services...]`, and the live dashboard's `u` shortcut. Includes clean JSON results, target validation, running-service restart/recovery, and version-cache invalidation; automatic checks remain read-only.
|
package/README.md
CHANGED
|
@@ -167,6 +167,53 @@ repository. Plain `status` prints full repository links, and `status --json`
|
|
|
167
167
|
includes `repositoryUrl` (null for custom services without metadata). The built-in
|
|
168
168
|
proxy links to ai-helper's repository, not its forwarding address.
|
|
169
169
|
|
|
170
|
+
#### Guided proxy setup
|
|
171
|
+
|
|
172
|
+
Press **`c` — setup proxy** from anywhere in `aih status --ui`, even before the
|
|
173
|
+
proxy's first start. The wizard edits a local draft: upstream/listener, supported
|
|
174
|
+
ordered recipes, model list, Headroom URL, RTK filter, pxpipe native-image handling,
|
|
175
|
+
interceptor `.mjs` and maximum body size. Tool-specific fields appear only when
|
|
176
|
+
that tool is enabled. pxpipe is bundled as a library; its separate daemon is not required.
|
|
177
|
+
|
|
178
|
+
- **Enter/Tab** advances; **Shift+Tab** goes back. Arrows/Space select recipe/options.
|
|
179
|
+
- Text fields support arrows, Home/End, Backspace/Delete and **Ctrl+U** to clear.
|
|
180
|
+
Comma-separated model entries can be edited/removed directly; `*` selects all models.
|
|
181
|
+
- Each field shows **Initial value** (the draft loaded when setup opened) and
|
|
182
|
+
**Current setting** (the actual worker configuration, refreshed with the dashboard).
|
|
183
|
+
A stopped proxy is marked explicitly; an unconfigured proxy shows **not configured**.
|
|
184
|
+
Pending saved settings can differ from the current worker. The editable line is the new draft.
|
|
185
|
+
- The **Startup** step selects which services launch together with plain `aih start`
|
|
186
|
+
or `aih up`: OCX, AgentMemory, standalone pxpipe, Headroom and the built-in proxy.
|
|
187
|
+
Use **Up/Down** to move, **Space** to toggle and **Enter** to continue. Select at
|
|
188
|
+
least one service. Choices are saved with setup in `state.config.startServices`.
|
|
189
|
+
Upstream services launch first, followed by the built-in proxy. Until configured,
|
|
190
|
+
the defaults remain OCX, AgentMemory and proxy. Explicit targets such as
|
|
191
|
+
`aih start ocx` override the selection; `aih start --gpt` keeps its dedicated workflow.
|
|
192
|
+
Saving/applying setup does not launch the selected services immediately: the
|
|
193
|
+
selection takes effect on the next plain start/up. Apply now only starts/restarts the proxy.
|
|
194
|
+
- **Esc** cancels; a modified draft asks for confirmation before discarding it.
|
|
195
|
+
- The final summary marks differences from the running configuration. Use arrows
|
|
196
|
+
and Enter to choose an action, and **PgUp/PgDn** to scroll details.
|
|
197
|
+
- **Check** checks the listener, RTK executable, bundled pxpipe and interceptor
|
|
198
|
+
readability, then probes upstream/Headroom without credentials. Endpoint failures
|
|
199
|
+
are advisory: reachability is not proof of authenticated API compatibility.
|
|
200
|
+
Interceptor code is never executed by preflight.
|
|
201
|
+
- **Save only** persists the desired configuration without touching the current
|
|
202
|
+
process. It also works while stopped; it does not start dependencies or the proxy.
|
|
203
|
+
- **Save and apply now** repeats preflight, then starts/restarts the proxy. Restart
|
|
204
|
+
interrupts active requests and streams; this is not hot reload. On startup failure,
|
|
205
|
+
AIH attempts to restore the previous running configuration and reports recovery failures.
|
|
206
|
+
If stopping the current proxy fails, AIH saves the desired settings without starting
|
|
207
|
+
a replacement. For Windows access-denied errors, stop/restart from a terminal with
|
|
208
|
+
the same permissions as the proxy (Administrator if it was started elevated).
|
|
209
|
+
|
|
210
|
+
Desired settings live in `state.config.proxyOptions`; `state.services.proxy.proxyOptions`
|
|
211
|
+
continues to describe the actual worker. Saved setup wins over legacy `pxpipe-models`
|
|
212
|
+
and no-target start defaults. Explicit CLI options still override saved setup and,
|
|
213
|
+
once a setup exists, successful starts retain the effective configuration there.
|
|
214
|
+
`aih config pxpipe-models=...` explicitly updates the setup model preference too.
|
|
215
|
+
Empty optional values persist as resets, not as omitted overrides.
|
|
216
|
+
|
|
170
217
|
The dashboard's
|
|
171
218
|
`VERSION` column shows the running service version when available, otherwise the
|
|
172
219
|
installed version. `UPDATE` shows `↑ <version>` for an available update,
|
|
@@ -274,8 +321,14 @@ not by updating the separate `pxpipe` service.
|
|
|
274
321
|
|
|
275
322
|
The Node services use `npm install --global <package>@latest` (`pxpipe-proxy`,
|
|
276
323
|
`@bitkyc08/opencodex`, `@agentmemory/agentmemory`), so npm must be available and
|
|
277
|
-
its global installation directory writable and on PATH. Headroom
|
|
324
|
+
its global installation directory writable and on PATH. Headroom is updated with its own
|
|
278
325
|
`headroom update --yes` command to respect the existing Python installation.
|
|
326
|
+
**If Headroom is not installed, the same command installs it** on the machine running aih:
|
|
327
|
+
with `uv tool install --python 3.12 "headroom-ai[proxy]"` when uv exists; otherwise uv is
|
|
328
|
+
bootstrapped through Python 3.10+ (`python -m pip install --user uv`), and Python itself is
|
|
329
|
+
installed first with winget (Windows), Homebrew (macOS) or apt-get/dnf (Linux, needs root or
|
|
330
|
+
passwordless sudo). Tool directories are added to aih's PATH for the run and the first launch
|
|
331
|
+
is warmed up before the version check; open a new terminal to get `headroom` on your shell PATH.
|
|
279
332
|
Installer output is captured in `aih logs <service>` rather than mixed into
|
|
280
333
|
JSON or the live dashboard. An explicitly updated npx service is launched with
|
|
281
334
|
the verified package version so an older project dependency/cache cannot win.
|
|
@@ -363,7 +416,9 @@ aih start
|
|
|
363
416
|
|
|
364
417
|
The preference is saved in `~/.aih/state.json` (or `AIH_HOME/state.json`).
|
|
365
418
|
It applies to `start`/`up` and proxy starts/restarts; an explicit `--models`
|
|
366
|
-
takes precedence without changing the preference.
|
|
419
|
+
takes precedence without changing the legacy preference. If a dashboard setup
|
|
420
|
+
exists, successful starts retain their effective options in that setup instead.
|
|
421
|
+
`aih config pxpipe-models=`
|
|
367
422
|
saves pxpipe's default selection. Configuration does not restart a running proxy.
|
|
368
423
|
|
|
369
424
|
The value is passed only to the built-in proxy; `ocx` and `agentmemory` start
|
|
@@ -371,7 +426,8 @@ normally. `--models=` passes an empty string; `--models ""` also works when your
|
|
|
371
426
|
shell preserves empty arguments. A bare `--models` without a value is an error.
|
|
372
427
|
See [Select models](#select-models) for matching and compression behavior.
|
|
373
428
|
|
|
374
|
-
|
|
429
|
+
Without a saved Startup selection, no-target `start`/`up` launches OCX, AgentMemory
|
|
430
|
+
and proxy. Unless a dashboard setup has been saved, these commands supply the upstream, listener and preset above
|
|
375
431
|
on every invocation, plus the configured model list (or the list above if unset),
|
|
376
432
|
unless `--models` overrides it.
|
|
377
433
|
Other saved proxy options are retained.
|
|
@@ -481,7 +537,8 @@ options; defaults in this table apply when no saved value exists.
|
|
|
481
537
|
| --- | --- |
|
|
482
538
|
| `--listen http://127.0.0.1:10102` | Loopback HTTP listener; default `http://127.0.0.1:10101`. |
|
|
483
539
|
| `--preset headroom-pxpipe` | Pipeline; default `none`. Choices: `none`, `pxpipe`, `headroom`, `rtk`, `headroom-pxpipe`, `rtk-pxpipe`, `rtk-headroom-pxpipe`. |
|
|
484
|
-
| `--models "gpt-6-astra,anthropic/claude-fable*"` |
|
|
540
|
+
| `--models "gpt-6-astra,anthropic/claude-fable*"` | Entire pipeline allowlist; `--models "*"` selects all; empty restores pxpipe defaults with RTK/Headroom on all. Also accepted by generic `start`/`up`. |
|
|
541
|
+
| `--pxpipe-native-images allow\|bypass` | Allow pxpipe on native-image requests (default) or bypass that stage. |
|
|
485
542
|
| `--interceptor "./my hooks/interceptor.mjs"` | Custom JavaScript hooks, loaded at startup; default none. `--interceptor=` clears the saved path. |
|
|
486
543
|
| `--headroom-url http://127.0.0.1:8787` | Headroom compression service; default shown. |
|
|
487
544
|
| `--rtk-filter grep` | Fixed RTK filter for matching tool output; default auto-detection. `--rtk-filter=` resets it. |
|
|
@@ -588,8 +645,11 @@ grep-output filter to every tool result, so use it only with matching output.
|
|
|
588
645
|
|
|
589
646
|
### Select models
|
|
590
647
|
|
|
591
|
-
**All models are forwarded.** `--models` selects
|
|
592
|
-
|
|
648
|
+
**All models are forwarded.** An explicit `--models` list selects the entire
|
|
649
|
+
compression recipe: excluded requests bypass RTK, Headroom and pxpipe unchanged.
|
|
650
|
+
This replaces the older pxpipe-only filtering behavior. `--models "*"` includes
|
|
651
|
+
all models. With an empty/omitted selection, pxpipe uses its supported-model
|
|
652
|
+
defaults while RTK/Headroom process all eligible requests.
|
|
593
653
|
Names match the `model` in the request, including any provider prefix.
|
|
594
654
|
For example, an AGY catalog entry can be `google-antigravity/gemini-3.8-flash`,
|
|
595
655
|
while Astra is `gpt-6-astra`.
|
|
@@ -670,7 +730,10 @@ npm run bench:proxy -- --headroom-url http://127.0.0.1:8787 --repetitions 5
|
|
|
670
730
|
```
|
|
671
731
|
|
|
672
732
|
Results include JSON, JSONL, CSV and Markdown. Unknown image costs are not counted
|
|
673
|
-
as zero
|
|
733
|
+
as zero. JSON/JSONL records retain available proxy preset, worker queue/processing,
|
|
734
|
+
CPU and event-loop timings, plus live provider headers and first output; see the
|
|
735
|
+
benchmark documentation for measurement boundaries. Offline checks never claim
|
|
736
|
+
a semantic-quality winner. Benchmark-only
|
|
674
737
|
pxpipe allowlisting defaults to all fixture models so imaging is actually exercised.
|
|
675
738
|
See [benchmark documentation](docs/benchmark.md) for corpus customization, live
|
|
676
739
|
evaluation, privacy, limitations and quality/performance decision thresholds.
|
|
@@ -702,11 +765,11 @@ to restore RTK auto-detection.
|
|
|
702
765
|
Use a fixed filter only when the tool output matches that format. Empty or larger
|
|
703
766
|
results are discarded. Prompts, tool calls and binary content are left untouched;
|
|
704
767
|
no command from an AI request is executed.
|
|
705
|
-
- **headroom-pxpipe:**
|
|
706
|
-
|
|
768
|
+
- **headroom-pxpipe:** applies Headroom first, then pxpipe; an explicit `--models`
|
|
769
|
+
list gates both stages.
|
|
707
770
|
- **rtk-pxpipe:** applies RTK to tool-result text first, then the pxpipe library.
|
|
708
|
-
`--rtk-filter` controls RTK and `--models` gates
|
|
709
|
-
|
|
771
|
+
`--rtk-filter` controls RTK and an explicit `--models` list gates both stages.
|
|
772
|
+
This chain needs RTK on PATH, with no Headroom service.
|
|
710
773
|
|
|
711
774
|
Presets process JSON POSTs on Messages, Chat Completions and Responses routes,
|
|
712
775
|
and outgoing WebSocket `response.create` events (flat or nested under `response`).
|
package/docs/benchmark.md
CHANGED
|
@@ -258,6 +258,21 @@ Ogni fixture pone una domanda con risposta nota contenuta nel tool output;
|
|
|
258
258
|
- input/output/cache read/cache write/reasoning dichiarati dal provider;
|
|
259
259
|
- risposta completa o troncata, tool aggiuntivi richiesti dal modello.
|
|
260
260
|
|
|
261
|
+
I record JSON/JSONL conservano anche `proxyTimings`: `presetMs`,
|
|
262
|
+
`pxpipeQueueMs` (include l'avvio del worker), `pxpipeMs`, `pxpipeCpuMs` quando
|
|
263
|
+
supportato dal runtime, `eventLoopLagMs`, `upstreamHeadersMs` e `totalMs`.
|
|
264
|
+
La baseline `none` non emette eventi preset e ha `proxyTimings: null`.
|
|
265
|
+
`live.headersMs` misura gli header del provider e `live.firstOutputMs` il primo
|
|
266
|
+
delta testuale SSE osservato dal collector. Quest'ultimo non è un tempo al primo
|
|
267
|
+
token misurato dal client: il collector restituisce al runner solo a stream finito.
|
|
268
|
+
Per lo stesso motivo `proxyTimings.upstreamHeadersMs` misura gli header del
|
|
269
|
+
collector, **non** quelli del provider. Il ritardo event loop è condiviso e
|
|
270
|
+
campionato, non CPU imputabile a una singola richiesta. Le metriche sono annidate
|
|
271
|
+
e non vanno sommate tutte fra loro; valori non disponibili restano assenti/null.
|
|
272
|
+
RTK e Headroom non espongono tempi di stadio separati: sono inclusi in `presetMs`.
|
|
273
|
+
Le tabelle aggregate CSV/Markdown mantengono le metriche storiche; i dettagli
|
|
274
|
+
temporali sono disponibili nei record JSON/JSONL.
|
|
275
|
+
|
|
261
276
|
Per Anthropic l'input normalizzato comprende input non-cached + letture/scritture
|
|
262
277
|
cache, evitando di confrontare scope diversi. Campi non restituiti restano null.
|
|
263
278
|
Di default streaming viene disabilitato; `--responses-stream` lo abilita solo per
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@drakonkat/ai-helper",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.16",
|
|
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",
|
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
"postinstall": "node scripts/patch-pxpipe.js",
|
|
41
41
|
"start": "node ./bin/cli.js",
|
|
42
42
|
"dev": "node ./bin/cli.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",
|
|
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 test/headroom-install.test.js && node --test test/proxy-setup.test.js 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",
|
|
44
44
|
"bench:proxy": "node scripts/bench-proxy.js",
|
|
45
45
|
"bench:models": "node scripts/bench-proxy.js --compare-models gpt-6-astra,anthropic/claude-fable-5-1 --formats responses",
|
|
46
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",
|
package/scripts/bench-proxy.js
CHANGED
|
@@ -42,6 +42,7 @@ Offline by default: private loopback proxies and real compressors; no provider c
|
|
|
42
42
|
--help Show help
|
|
43
43
|
|
|
44
44
|
Reports: report.json, records.jsonl, results.csv, report.md. Managed config/aih proxy stats are untouched.
|
|
45
|
+
JSON records include proxy/worker timings and live provider headers/first-output timings when available.
|
|
45
46
|
Exit 0 completed without request errors; 2 request errors/interruption; 1 invalid setup.
|
|
46
47
|
Offline runs never claim a semantic-quality winner. See docs/benchmark.md.
|
|
47
48
|
`;
|
package/src/benchmark/live.js
CHANGED
|
@@ -148,28 +148,29 @@ export async function callProvider(body, fixture, options) {
|
|
|
148
148
|
method: "POST", headers, body: JSON.stringify(body), redirect: "error",
|
|
149
149
|
signal: options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(options.timeoutMs)]) : AbortSignal.timeout(options.timeoutMs),
|
|
150
150
|
});
|
|
151
|
+
const headersMs = performance.now() - start;
|
|
151
152
|
if (response.ok && fixture.format === "responses" && /^text\/event-stream(?:\s*;|\s*$)/i.test(response.headers.get("content-type") || "")) {
|
|
152
153
|
try {
|
|
153
154
|
const parsed = await readResponsesStream(response, options.maxBodyBytes, start);
|
|
154
|
-
return { status: response.status, durationMs: performance.now() - start, ...parsed };
|
|
155
|
+
return { status: response.status, headersMs, durationMs: performance.now() - start, ...parsed };
|
|
155
156
|
} catch (error) {
|
|
156
157
|
// Only locally constructed diagnostics survive; never JSON parser errors,
|
|
157
158
|
// provider event bodies, echoed prompts or credentials.
|
|
158
159
|
const safe = ["Provider SSE ended without a terminal response", "Provider SSE contained invalid event data",
|
|
159
160
|
"Provider SSE reported an error", "Provider SSE contained an invalid terminal response", "Response exceeds benchmark maxBodyBytes",
|
|
160
161
|
"Provider SSE contained an invalid finalized output item", "Provider SSE contained conflicting finalized output items"];
|
|
161
|
-
return { status: response.status, durationMs: performance.now() - start, complete: false,
|
|
162
|
+
return { status: response.status, headersMs, durationMs: performance.now() - start, complete: false,
|
|
162
163
|
error: safe.includes(error.message) ? error.message : "Provider SSE could not be read" };
|
|
163
164
|
}
|
|
164
165
|
}
|
|
165
166
|
const raw = await readLimited(response, options.maxBodyBytes);
|
|
166
167
|
const durationMs = performance.now() - start;
|
|
167
168
|
// Never put provider error bodies (which can echo credentials/prompts) in reports.
|
|
168
|
-
if (!response.ok) return { status: response.status, durationMs, error: `Provider HTTP ${response.status}` };
|
|
169
|
+
if (!response.ok) return { status: response.status, headersMs, durationMs, error: `Provider HTTP ${response.status}` };
|
|
169
170
|
let value;
|
|
170
|
-
try { value = JSON.parse(raw); } catch { return { status: response.status, durationMs, error: "Provider did not return JSON or a supported Responses SSE stream" }; }
|
|
171
|
-
try { return { status: response.status, durationMs, ...parseProviderResponse(value, fixture.format) }; }
|
|
172
|
-
catch { return { status: response.status, durationMs, error: "Provider returned an invalid response shape" }; }
|
|
171
|
+
try { value = JSON.parse(raw); } catch { return { status: response.status, headersMs, durationMs, error: "Provider did not return JSON or a supported Responses SSE stream" }; }
|
|
172
|
+
try { return { status: response.status, headersMs, durationMs, ...parseProviderResponse(value, fixture.format) }; }
|
|
173
|
+
catch { return { status: response.status, headersMs, durationMs, error: "Provider returned an invalid response shape" }; }
|
|
173
174
|
}
|
|
174
175
|
|
|
175
176
|
const number = n => Number.isFinite(n) && n >= 0 ? n : null;
|
package/src/benchmark/runner.js
CHANGED
|
@@ -223,7 +223,12 @@ export async function runBenchmark(inputOptions = {}) {
|
|
|
223
223
|
try {
|
|
224
224
|
state.proxy = await startProxy({ upstream: sink.url, listen: "http://127.0.0.1:0", ...flowOptions(preset),
|
|
225
225
|
headroomUrl: options.headroomUrl, rtkFilter: options.rtkFilter, models: options.models,
|
|
226
|
-
maxBodyBytes: options.maxBodyBytes, onStats: event =>
|
|
226
|
+
maxBodyBytes: options.maxBodyBytes, onStats: event => {
|
|
227
|
+
const entry = sink.records.get(event.requestId);
|
|
228
|
+
if (!entry) return;
|
|
229
|
+
entry.events.push(event);
|
|
230
|
+
return timings => { event.timings = { ...event.timings, ...timings }; };
|
|
231
|
+
} });
|
|
227
232
|
} catch (error) { state.error = `Preset setup failed (${error.name})`; }
|
|
228
233
|
state.startupMs = performance.now() - start;
|
|
229
234
|
}
|
|
@@ -270,6 +275,7 @@ export async function runBenchmark(inputOptions = {}) {
|
|
|
270
275
|
row.durationMs ??= performance.now() - start;
|
|
271
276
|
} finally { controller.abort(); sink.records.delete(id); }
|
|
272
277
|
row.stages = entry.events.flatMap(event => event.stages || []);
|
|
278
|
+
row.proxyTimings = entry.events.length ? { ...entry.events.at(-1).timings } : null;
|
|
273
279
|
records.push(row);
|
|
274
280
|
await options.onRecord?.(row);
|
|
275
281
|
}
|
package/src/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { APP_NAME, CLI_NAME, SERVICES, SERVICE_IDS, VERSION } from "./config.js";
|
|
2
2
|
import { manager } from "./manager.js";
|
|
3
|
+
import { normalizeStartServices } from "./startup-services.js";
|
|
3
4
|
import { checkForUpdates, updateSelf } from "./update.js";
|
|
4
5
|
import { readProxyStats, proxyStatsLines } from "./proxy-stats.js";
|
|
5
6
|
import {
|
|
@@ -76,17 +77,20 @@ ${bold("PROXY OPTIONS (start/up/restart proxy):")}
|
|
|
76
77
|
pxpipe runs in up to 2 persistent workers; excluded models skip the queue
|
|
77
78
|
${gray("--headroom-url <url>")} Headroom service (default: http://127.0.0.1:8787)
|
|
78
79
|
${gray("--rtk-filter <name>")} Fixed rtk pipe filter; --rtk-filter= restores auto-detection
|
|
80
|
+
${gray("--pxpipe-native-images <mode>")} allow | bypass (default: allow)
|
|
79
81
|
${gray("--max-body-bytes <num>")} Positive integer; buffered request / WebSocket limit
|
|
80
82
|
(default: 67108864 bytes = 64 MiB)
|
|
81
83
|
Saved proxy options are reused when omitted. To change a running proxy, use restart proxy.
|
|
82
84
|
|
|
83
85
|
${bold("START DEFAULTS AND MODEL VALUES:")}
|
|
84
|
-
Without service targets, start/up
|
|
86
|
+
Without service targets, start/up uses the Startup selection saved in status --ui setup.
|
|
87
|
+
Until configured, it launches ocx, agentmemory, then proxy with:
|
|
85
88
|
upstream: http://127.0.0.1:10100/ listen: http://127.0.0.1:10102 preset: pxpipe
|
|
86
89
|
models: gpt-6-astra,google-antigravity/gemini-3.8*,anthropic/claude-fable*
|
|
87
90
|
config pxpipe-models=<list> saves a replacement list; --models overrides it.
|
|
88
91
|
Model names are comma-separated; a trailing * matches a prefix (include provider names).
|
|
89
|
-
All models are forwarded;
|
|
92
|
+
All models are forwarded; an explicit list selects the entire compression pipeline.
|
|
93
|
+
--models "*" selects all models. Empty restores pxpipe defaults; RTK/Headroom run on all.
|
|
90
94
|
Value options accept --flag value or --flag=value. Quote lists, wildcards and spaced paths.
|
|
91
95
|
--models= restores pxpipe's default model selection; --models "" also works if the shell
|
|
92
96
|
preserves empty arguments. Bare --models without a value is an error.
|
|
@@ -217,6 +221,7 @@ export async function main({ updateSelfImpl = updateSelf } = {}) {
|
|
|
217
221
|
listen: { type: "string" }, interceptor: { type: "string" },
|
|
218
222
|
preset: { type: "string" }, models: { type: "string" },
|
|
219
223
|
"headroom-url": { type: "string" }, "rtk-filter": { type: "string" },
|
|
224
|
+
"pxpipe-native-images": { type: "string" },
|
|
220
225
|
"max-body-bytes": { type: "string" }, json: { type: "boolean" },
|
|
221
226
|
} });
|
|
222
227
|
if (positionals.length > 1) throw new Error("Expected one upstream URL");
|
|
@@ -224,7 +229,7 @@ export async function main({ updateSelfImpl = updateSelf } = {}) {
|
|
|
224
229
|
if (positionals[0]) options.upstream = positionals[0];
|
|
225
230
|
if (values.listen !== undefined) options.listen = values.listen;
|
|
226
231
|
if (values.interceptor !== undefined) options.interceptor = values.interceptor;
|
|
227
|
-
for (const [flag, key] of Object.entries({ preset: "preset", models: "models", "headroom-url": "headroomUrl", "rtk-filter": "rtkFilter" })) {
|
|
232
|
+
for (const [flag, key] of Object.entries({ preset: "preset", models: "models", "headroom-url": "headroomUrl", "rtk-filter": "rtkFilter", "pxpipe-native-images": "pxpipeNativeImages" })) {
|
|
228
233
|
if (values[flag] !== undefined) options[key] = values[flag];
|
|
229
234
|
}
|
|
230
235
|
if (values["max-body-bytes"] !== undefined) options.maxBodyBytes = values["max-body-bytes"];
|
|
@@ -317,6 +322,7 @@ export async function main({ updateSelfImpl = updateSelf } = {}) {
|
|
|
317
322
|
}
|
|
318
323
|
const state = manager.readState();
|
|
319
324
|
state.config = { ...state.config, pxpipeModels: targets[0].slice("pxpipe-models=".length) };
|
|
325
|
+
if (state.config.proxyOptions) state.config.proxyOptions.models = state.config.pxpipeModels;
|
|
320
326
|
manager.saveState(state);
|
|
321
327
|
console.log(green(`Saved pxpipe-models=${state.config.pxpipeModels}; applies on the next proxy start or restart.`));
|
|
322
328
|
break;
|
|
@@ -455,7 +461,7 @@ export async function main({ updateSelfImpl = updateSelf } = {}) {
|
|
|
455
461
|
case "up": {
|
|
456
462
|
await checkForUpdates();
|
|
457
463
|
if (!jsonOutput) printBanner();
|
|
458
|
-
const svcsToStart = targets.length > 0 ? targets :
|
|
464
|
+
const svcsToStart = targets.length > 0 ? targets : normalizeStartServices(manager.readState().config?.startServices);
|
|
459
465
|
if (!jsonOutput) console.log(cyan(`Starting service(s): ${svcsToStart.join(", ")}...\n`));
|
|
460
466
|
const results = [];
|
|
461
467
|
|
|
@@ -466,6 +472,8 @@ export async function main({ updateSelfImpl = updateSelf } = {}) {
|
|
|
466
472
|
listen: "http://127.0.0.1:10102",
|
|
467
473
|
preset: "pxpipe",
|
|
468
474
|
models: models ?? manager.readState().config?.pxpipeModels ?? "gpt-6-astra,google-antigravity/gemini-3.8*,anthropic/claude-fable*",
|
|
475
|
+
...manager.readState().config?.proxyOptions,
|
|
476
|
+
...(models !== undefined ? { models } : {}),
|
|
469
477
|
} : id === "proxy" && models !== undefined ? { models } : undefined);
|
|
470
478
|
results.push({ id, ...res });
|
|
471
479
|
if (jsonOutput) continue;
|
package/src/manager.js
CHANGED
|
@@ -3,6 +3,8 @@ import { execFileSync, spawn } from "node:child_process";
|
|
|
3
3
|
import { fileURLToPath } from "node:url";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { normalizeProxyOptions } from "./proxy.js";
|
|
6
|
+
import { normalizeStartServices } from "./startup-services.js";
|
|
7
|
+
import { preflightProxy, savedProxyOptions } from "./proxy-setup.js";
|
|
6
8
|
import { SERVICES, SERVICE_IDS, SERVICE_PACKAGES, APP_REPOSITORY_URL } from "./config.js";
|
|
7
9
|
import { compareVersions, getServiceVersions } from "./utils/versions.js";
|
|
8
10
|
import { installServiceUpdate, serviceStartCommand } from "./service-updates.js";
|
|
@@ -110,7 +112,7 @@ export class ServiceManager {
|
|
|
110
112
|
details.version = live.version;
|
|
111
113
|
}
|
|
112
114
|
return { ...details, success: true, updated, restarted: Boolean(started), codexConfig: started?.codexConfig,
|
|
113
|
-
message: `'${serviceId}' updated to ${details.version}${started ? " and restarted" : " (left stopped)"}` };
|
|
115
|
+
message: `'${serviceId}' ${details.previousVersion == null ? "installed" : "updated"} to ${details.version}${started ? " and restarted" : " (left stopped)"}` };
|
|
114
116
|
} catch (error) {
|
|
115
117
|
const recovery = stopped ? await restart() : null;
|
|
116
118
|
return { ...details, success: false, updated, restarted: Boolean(recovery?.success && !recovery.alreadyRunning), codexConfig: recovery?.codexConfig,
|
|
@@ -402,6 +404,7 @@ export class ServiceManager {
|
|
|
402
404
|
const config = normalizeProxyOptions({
|
|
403
405
|
...current?.proxyOptions,
|
|
404
406
|
...(state.config?.pxpipeModels !== undefined ? { models: state.config.pxpipeModels } : {}),
|
|
407
|
+
...state.config?.proxyOptions,
|
|
405
408
|
...options,
|
|
406
409
|
});
|
|
407
410
|
if (current?.status === "running" && isPidRunning(current.pid)) {
|
|
@@ -461,6 +464,7 @@ export class ServiceManager {
|
|
|
461
464
|
status: "running", pid: child.pid, startedAt: new Date().toISOString(),
|
|
462
465
|
url: ready.url, proxyOptions: config,
|
|
463
466
|
};
|
|
467
|
+
if (updated.config?.proxyOptions) updated.config.proxyOptions = savedProxyOptions(config);
|
|
464
468
|
this.saveState(updated);
|
|
465
469
|
return { success: true, pid: child.pid, url: ready.url, codexConfig: await this.configureCodexProxy() };
|
|
466
470
|
} catch (error) {
|
|
@@ -555,7 +559,7 @@ export class ServiceManager {
|
|
|
555
559
|
async restartService(serviceId, options) {
|
|
556
560
|
if (serviceId === "proxy") {
|
|
557
561
|
const current = this.readState().services.proxy;
|
|
558
|
-
normalizeProxyOptions({ ...current?.proxyOptions, ...options });
|
|
562
|
+
normalizeProxyOptions({ ...current?.proxyOptions, ...this.readState().config?.proxyOptions, ...options });
|
|
559
563
|
if (!current) return this.startService(serviceId, options);
|
|
560
564
|
}
|
|
561
565
|
const stopped = await this.stopService(serviceId);
|
|
@@ -564,6 +568,69 @@ export class ServiceManager {
|
|
|
564
568
|
return await this.startService(serviceId, options);
|
|
565
569
|
}
|
|
566
570
|
|
|
571
|
+
/** Desired configuration is separate from the running worker's snapshot. */
|
|
572
|
+
saveProxyConfiguration(options, { startServices } = {}) {
|
|
573
|
+
const config = normalizeProxyOptions(options);
|
|
574
|
+
const startup = startServices === undefined ? undefined : normalizeStartServices(startServices);
|
|
575
|
+
const state = this.readState();
|
|
576
|
+
state.config = { ...state.config, proxyOptions: savedProxyOptions(config) };
|
|
577
|
+
if (startup) state.config.startServices = startup;
|
|
578
|
+
this.saveState(state);
|
|
579
|
+
return { success: true, message: "Configuration saved for the next start/restart. Current proxy unchanged." };
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/** Validate before stopping; recover the old worker if applying the draft fails. */
|
|
583
|
+
async applyProxyConfiguration(options, { preflight = preflightProxy, startServices } = {}) {
|
|
584
|
+
if (this.proxySetupBusy) return { success: false, message: "Proxy setup already in progress" };
|
|
585
|
+
this.proxySetupBusy = true;
|
|
586
|
+
try {
|
|
587
|
+
const config = normalizeProxyOptions(options);
|
|
588
|
+
if (startServices !== undefined) startServices = normalizeStartServices(startServices);
|
|
589
|
+
const state = await this.syncState();
|
|
590
|
+
const previous = state.services.proxy;
|
|
591
|
+
const oldDesired = state.config?.proxyOptions;
|
|
592
|
+
const checks = await preflight(config, previous);
|
|
593
|
+
const wasRunning = previous?.status === "running";
|
|
594
|
+
if (wasRunning) {
|
|
595
|
+
const stopped = await this.stopService("proxy");
|
|
596
|
+
if (!stopped.success) {
|
|
597
|
+
this.saveProxyConfiguration(config, { startServices });
|
|
598
|
+
return { ...stopped, saved: true, applied: false,
|
|
599
|
+
message: `Configuration saved, but not applied: could not stop the current proxy. ${stopped.message} If access is denied, stop/restart the proxy from a terminal with the same permissions (Administrator if it was started elevated), then retry. Saved settings will be used on the next start/restart.` };
|
|
600
|
+
}
|
|
601
|
+
await sleep(600);
|
|
602
|
+
}
|
|
603
|
+
try {
|
|
604
|
+
const result = await this.startService("proxy", config);
|
|
605
|
+
if (!result.success) throw new Error(result.message || "Startup failed");
|
|
606
|
+
this.saveProxyConfiguration(config, { startServices });
|
|
607
|
+
return { ...result, checks, message: ["Configuration applied and saved", ...(checks || []).filter(c => c.startsWith("Warning:"))].join(" | ") };
|
|
608
|
+
} catch (error) {
|
|
609
|
+
// A failed start may have persisted a runtime entry before a later error.
|
|
610
|
+
try { await this.stopService("proxy"); } catch {}
|
|
611
|
+
const restored = this.readState();
|
|
612
|
+
restored.config = { ...restored.config };
|
|
613
|
+
if (oldDesired === undefined) delete restored.config.proxyOptions;
|
|
614
|
+
else restored.config.proxyOptions = oldDesired;
|
|
615
|
+
if (previous) restored.services.proxy = { ...previous, status: "stopped", pid: undefined, startedAt: undefined };
|
|
616
|
+
this.saveState(restored);
|
|
617
|
+
let recovery;
|
|
618
|
+
if (wasRunning && previous.proxyOptions) {
|
|
619
|
+
try {
|
|
620
|
+
const result = await this.startService("proxy", savedProxyOptions(previous.proxyOptions));
|
|
621
|
+
recovery = result.success ? "Previous configuration restored" : `Recovery failed: ${result.message}`;
|
|
622
|
+
} catch (restoreError) { recovery = `Recovery failed: ${restoreError.message}`; }
|
|
623
|
+
}
|
|
624
|
+
const recoveredState = this.readState();
|
|
625
|
+
recoveredState.config = { ...recoveredState.config };
|
|
626
|
+
if (oldDesired === undefined) delete recoveredState.config.proxyOptions;
|
|
627
|
+
else recoveredState.config.proxyOptions = oldDesired;
|
|
628
|
+
this.saveState(recoveredState);
|
|
629
|
+
return { success: false, message: `Apply failed: ${error.message}. ${recovery || "Proxy stopped; previous configuration preserved"}` };
|
|
630
|
+
}
|
|
631
|
+
} finally { this.proxySetupBusy = false; }
|
|
632
|
+
}
|
|
633
|
+
|
|
567
634
|
/**
|
|
568
635
|
* Restarts all or selected services.
|
|
569
636
|
*/
|
package/src/proxy-presets.js
CHANGED
|
@@ -7,7 +7,7 @@ import { requestImages } from "./request-images.js";
|
|
|
7
7
|
import { createPxpipePool } from "./pxpipe-pool.js";
|
|
8
8
|
|
|
9
9
|
// Fixed recipes; the user's --interceptor runs afterwards and can inspect/edit the result.
|
|
10
|
-
const PRESETS = ["none", "pxpipe", "headroom", "rtk", "headroom-pxpipe", "rtk-pxpipe", "rtk-headroom-pxpipe"];
|
|
10
|
+
export const PRESETS = Object.freeze(["none", "pxpipe", "headroom", "rtk", "headroom-pxpipe", "rtk-pxpipe", "rtk-headroom-pxpipe"]);
|
|
11
11
|
const DECODERS = { gzip: promisify(zlib.gunzip), deflate: promisify(zlib.inflate), br: promisify(zlib.brotliDecompress),
|
|
12
12
|
...(typeof zlib.zstdDecompress === "function" ? { zstd: promisify(zlib.zstdDecompress) } : {}) };
|
|
13
13
|
|
|
@@ -15,7 +15,7 @@ export function normalizePresetOptions(options) {
|
|
|
15
15
|
const preset = options.preset || "none";
|
|
16
16
|
if (!PRESETS.includes(preset)) throw new Error(`Unknown preset. Choose: ${PRESETS.join(", ")}`);
|
|
17
17
|
const models = options.models ? String(options.models).split(",").map(s => s.trim()) : undefined;
|
|
18
|
-
if (models?.some(s => !s || !/^[\w./:-]+\*?$/.test(s))) throw new Error("models must be comma-separated model names, optionally ending in *");
|
|
18
|
+
if (models?.some(s => !s || (s !== "*" && !/^[\w./:-]+\*?$/.test(s)))) throw new Error("models must be comma-separated model names, optionally ending in *, or * for all models");
|
|
19
19
|
const headroom = new URL(options.headroomUrl || "http://127.0.0.1:8787");
|
|
20
20
|
if (!["http:", "https:"].includes(headroom.protocol) || headroom.username || headroom.password || headroom.search || headroom.hash) {
|
|
21
21
|
throw new Error("headroomUrl must be HTTP(S) without credentials, query or fragment");
|
|
@@ -163,6 +163,12 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
163
163
|
if (!websocket && typeof update === "function") context.updateTiming = update;
|
|
164
164
|
} catch {}
|
|
165
165
|
};
|
|
166
|
+
// Preserve observability and byte-for-byte forwarding for excluded models.
|
|
167
|
+
if (models && !models.some(m => m.endsWith("*") ? model.startsWith(m.slice(0, -1)) : model === m)) {
|
|
168
|
+
for (const stage of config.preset.split("-")) stages.push(tokenStage(stage, 0, 0, false, "model_excluded", "not_measured"));
|
|
169
|
+
report(false);
|
|
170
|
+
return raw;
|
|
171
|
+
}
|
|
166
172
|
try {
|
|
167
173
|
// Fixed stage order, including the triple recipe: RTK -> Headroom -> pxpipe.
|
|
168
174
|
if (config.preset === "rtk" || config.preset.startsWith("rtk-")) {
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { createServer } from "node:net";
|
|
2
|
+
import { access, stat } from "node:fs/promises";
|
|
3
|
+
import { constants } from "node:fs";
|
|
4
|
+
import { execFile } from "node:child_process";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
import { normalizeProxyOptions } from "./proxy.js";
|
|
7
|
+
import { PRESETS } from "./proxy-presets.js";
|
|
8
|
+
|
|
9
|
+
export const PROXY_FIELDS = Object.freeze([
|
|
10
|
+
{ key: "upstream", group: "Connection", label: "Upstream URL", help: "Where the AIH proxy forwards requests, e.g. OCX. Required HTTP(S) URL; no credentials, query or fragment." },
|
|
11
|
+
{ key: "listen", group: "Connection", label: "Proxy listen address", help: "Where clients connect to the AIH proxy. HTTP on loopback, e.g. http://127.0.0.1:10101" },
|
|
12
|
+
{ key: "preset", group: "Pipeline", label: "Tool combination", choices: PRESETS, help: "Fixed order: RTK -> Headroom -> pxpipe. none = forwarding only." },
|
|
13
|
+
{ key: "models", group: "Models", label: "Included models", help: "* = all. Comma-separated names; trailing wildcard: anthropic/claude-fable*. Excluded models bypass the pipeline. Empty = pxpipe defaults; RTK/Headroom on all." },
|
|
14
|
+
{ key: "headroomUrl", group: "Tool options", label: "Headroom URL", stage: "headroom", help: "Headroom HTTP(S) endpoint. Default: http://127.0.0.1:8787" },
|
|
15
|
+
{ key: "rtkFilter", group: "Tool options", label: "RTK filter", stage: "rtk", help: "Empty = automatic detection. Lowercase letters, numbers and hyphens." },
|
|
16
|
+
{ key: "pxpipeNativeImages", group: "Tool options", label: "pxpipe native images", stage: "pxpipe", choices: ["allow", "bypass"], help: "allow = process requests; bypass = skip pxpipe for requests containing native images." },
|
|
17
|
+
{ key: "interceptor", group: "Advanced", label: "Interceptor file", help: "Path to a .mjs file (spaces allowed). Empty = none. Runs after the presets." },
|
|
18
|
+
{ key: "maxBodyBytes", group: "Advanced", label: "Maximum body size (bytes)", help: "Positive integer. Default 67108864 (64 MiB)." },
|
|
19
|
+
]);
|
|
20
|
+
|
|
21
|
+
export function proxySetupDraft(state) {
|
|
22
|
+
const options = { upstream: "", listen: "http://127.0.0.1:10101", preset: "none",
|
|
23
|
+
headroomUrl: "http://127.0.0.1:8787", pxpipeNativeImages: "allow", maxBodyBytes: 67108864,
|
|
24
|
+
models: state.config?.pxpipeModels, ...state.services?.proxy?.proxyOptions, ...state.config?.proxyOptions };
|
|
25
|
+
return Object.fromEntries(PROXY_FIELDS.map(({ key }) => [key, String(options[key] ?? "")]));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function normalizeSetupDraft(draft) {
|
|
29
|
+
return normalizeProxyOptions({ ...draft, upstream: draft.upstream.trim(), listen: draft.listen.trim(),
|
|
30
|
+
headroomUrl: draft.headroomUrl.trim(), interceptor: draft.interceptor.trim(), rtkFilter: draft.rtkFilter.trim() });
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// JSON drops undefined: explicit empty values must survive to clear older overrides.
|
|
34
|
+
export function savedProxyOptions(config) {
|
|
35
|
+
return { ...config, models: config.models ?? "", interceptor: config.interceptor ?? "", rtkFilter: config.rtkFilter ?? "" };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Never import the interceptor during preflight: configuration checks must not execute user code.
|
|
39
|
+
export async function preflightProxy(options, current, {
|
|
40
|
+
run = promisify(execFile), fetchImpl = fetch,
|
|
41
|
+
} = {}) {
|
|
42
|
+
const config = normalizeProxyOptions(options);
|
|
43
|
+
const checks = [];
|
|
44
|
+
if (config.interceptor) {
|
|
45
|
+
if (!config.interceptor.endsWith(".mjs")) throw new Error("Interceptor: select a .mjs file");
|
|
46
|
+
await access(config.interceptor, constants.R_OK);
|
|
47
|
+
if (!(await stat(config.interceptor)).isFile()) throw new Error("Interceptor: the path is not a file");
|
|
48
|
+
checks.push("Interceptor is readable (code not executed)");
|
|
49
|
+
}
|
|
50
|
+
if (config.preset.split("-").includes("rtk")) {
|
|
51
|
+
await run("rtk", ["--version"], { timeout: 5000, windowsHide: true, maxBuffer: 65536 });
|
|
52
|
+
checks.push("RTK available");
|
|
53
|
+
}
|
|
54
|
+
if (config.preset.includes("pxpipe")) {
|
|
55
|
+
await import("pxpipe-proxy");
|
|
56
|
+
checks.push("pxpipe library available (pxpipe service not required)");
|
|
57
|
+
}
|
|
58
|
+
const listen = new URL(config.listen);
|
|
59
|
+
const sameListener = current?.status === "running" && current?.url && (() => {
|
|
60
|
+
const active = new URL(current.url);
|
|
61
|
+
return active.port === listen.port && active.protocol === listen.protocol;
|
|
62
|
+
})();
|
|
63
|
+
if (!sameListener) await new Promise((resolve, reject) => {
|
|
64
|
+
const server = createServer();
|
|
65
|
+
server.once("error", error => reject(new Error(`Listen port unavailable: ${error.message}`)));
|
|
66
|
+
server.listen(Number(listen.port || 80), listen.hostname.replace(/^\[|\]$/g, ""), () => server.close(resolve));
|
|
67
|
+
});
|
|
68
|
+
checks.push(sameListener ? "Current listener: will be reused on restart" : "Listen port available");
|
|
69
|
+
// These probes are advisory: authenticated upstreams often reject unauthenticated HEAD.
|
|
70
|
+
for (const [name, url] of [["Upstream", config.upstream], ...(config.preset.includes("headroom") ? [["Headroom", new URL("health", config.headroomUrl.endsWith("/") ? config.headroomUrl : config.headroomUrl + "/").href]] : [])]) {
|
|
71
|
+
try {
|
|
72
|
+
const response = await fetchImpl(url, { method: "HEAD", redirect: "manual", signal: AbortSignal.timeout(3000) });
|
|
73
|
+
checks.push(`${name}: HTTP ${response.status} (reachable; authentication/functionality not verified)`);
|
|
74
|
+
await response.body?.cancel();
|
|
75
|
+
} catch { checks.push(`Warning: ${name} unreachable; check the URL and service before use`); }
|
|
76
|
+
}
|
|
77
|
+
return checks;
|
|
78
|
+
}
|
package/src/service-updates.js
CHANGED
|
@@ -1,7 +1,21 @@
|
|
|
1
|
+
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
1
4
|
import { SERVICE_PACKAGES, SERVICES } from "./config.js";
|
|
2
|
-
import { compareVersions } from "./utils/versions.js";
|
|
5
|
+
import { compareVersions, runVersionCommand } from "./utils/versions.js";
|
|
6
|
+
import { refreshToolPath } from "./utils/tool-path.js";
|
|
7
|
+
export { refreshToolPath, toolSearchDirectories } from "./utils/tool-path.js";
|
|
3
8
|
import { npmUpdateInvocation, runUpdateInstaller } from "./utils/update-installer.js";
|
|
4
9
|
|
|
10
|
+
/** pip requirement for a runnable Headroom proxy (the proxy dependencies are an extra). */
|
|
11
|
+
export const HEADROOM_REQUIREMENT = "headroom-ai[proxy]";
|
|
12
|
+
/**
|
|
13
|
+
* Headroom pulls native dependencies (e.g. zstandard) that lack wheels for very
|
|
14
|
+
* new Python releases, so it gets its own interpreter instead of the system one.
|
|
15
|
+
*/
|
|
16
|
+
export const HEADROOM_PYTHON = "3.12";
|
|
17
|
+
const MIN_PYTHON_MINOR = 10;
|
|
18
|
+
|
|
5
19
|
/** Only allowlisted services/arguments reach an installer; never execute user input. */
|
|
6
20
|
export function serviceUpdateInvocation(id, platform = process.platform) {
|
|
7
21
|
if (!Object.hasOwn(SERVICE_PACKAGES, id)) throw new Error(`Service '${id}' cannot be updated separately`);
|
|
@@ -23,6 +37,88 @@ export function serviceStartCommand(id, state) {
|
|
|
23
37
|
}
|
|
24
38
|
|
|
25
39
|
/** Capture installer output, keeping --json/TUI clean and full diagnostics in the service log. */
|
|
26
|
-
export function installServiceUpdate(id,
|
|
27
|
-
|
|
40
|
+
export function installServiceUpdate(id, options = {}) {
|
|
41
|
+
const { spawnImpl, platform = process.platform } = options;
|
|
42
|
+
// Validates the id synchronously, before anything can be spawned.
|
|
43
|
+
const invocation = serviceUpdateInvocation(id, platform);
|
|
44
|
+
if (!SERVICE_PACKAGES[id].pypi) return runUpdateInstaller(id, invocation, { spawnImpl });
|
|
45
|
+
return installHeadroom(id, invocation, options);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function findPython(probe, platform) {
|
|
49
|
+
const candidates = platform === "win32" ? [["python"], ["py", "-3"]] : [["python3"], ["python"]];
|
|
50
|
+
for (const [command, ...prefix] of candidates) {
|
|
51
|
+
const match = (await probe(command, [...prefix, "--version"]))?.match(/^Python (\d+)\.(\d+)/);
|
|
52
|
+
// On Windows the Store "python" alias fails this check instead of opening the Store.
|
|
53
|
+
if (match && Number(match[1]) === 3 && Number(match[2]) >= MIN_PYTHON_MINOR) return { command, prefix };
|
|
54
|
+
}
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Fixed package-manager invocation that installs Python, or null when none is usable. */
|
|
59
|
+
async function pythonInstallInvocation(platform, available) {
|
|
60
|
+
if (platform === "win32") {
|
|
61
|
+
return await available("winget") ? { command: "winget", args: ["install", "-e", "--id", "Python.Python.3.12",
|
|
62
|
+
"--scope", "user", "--silent", "--accept-package-agreements", "--accept-source-agreements"] } : null;
|
|
63
|
+
}
|
|
64
|
+
if (platform === "darwin") return await available("brew") ? { command: "brew", args: ["install", "python"] } : null;
|
|
65
|
+
const sudo = process.getuid?.() === 0 ? [] : ["sudo", "-n"];
|
|
66
|
+
const elevated = args => ({ command: [...sudo, ...args][0], args: [...sudo, ...args].slice(1) });
|
|
67
|
+
if (await available("apt-get")) return elevated(["apt-get", "install", "-y", "python3", "python3-pip", "python3-venv"]);
|
|
68
|
+
if (await available("dnf")) return elevated(["dnf", "install", "-y", "python3", "python3-pip"]);
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Install or update Headroom on this machine. An existing installation is
|
|
74
|
+
* updated by Headroom itself; otherwise the missing prerequisites (Python,
|
|
75
|
+
* pipx/uv) are installed first. Never shells out with user-provided text.
|
|
76
|
+
*/
|
|
77
|
+
async function installHeadroom(id, updateInvocation, { spawnImpl, platform = process.platform, probe = runVersionCommand, refreshPath = refreshToolPath } = {}) {
|
|
78
|
+
const run = (invocation, env) => runUpdateInstaller(id, invocation, { spawnImpl, env });
|
|
79
|
+
const available = async (command, args = ["--version"]) => (await probe(command, args, 5000)) !== null;
|
|
80
|
+
refreshPath();
|
|
81
|
+
// The first launch of a fresh Python install compiles bytecode and can take
|
|
82
|
+
// tens of seconds; warm it up so aih's short version probe does not time out.
|
|
83
|
+
const warmUp = async result => {
|
|
84
|
+
if (result.success) await probe("headroom", ["--version"], 180000);
|
|
85
|
+
return result;
|
|
86
|
+
};
|
|
87
|
+
if (await available("headroom")) return warmUp(await run(updateInvocation));
|
|
88
|
+
|
|
89
|
+
const failed = (message, last) => ({ success: false, exitCode: last?.exitCode ?? 1, logPath: last?.logPath, message });
|
|
90
|
+
const install = ["tool", "install", "--force", "--python", HEADROOM_PYTHON, HEADROOM_REQUIREMENT];
|
|
91
|
+
// uv links its managed Python with a junction. Under MSIX-packaged hosts (e.g. the Codex
|
|
92
|
+
// desktop app) %APPDATA% is virtualized and that junction dangles, so keep it in the real home.
|
|
93
|
+
const uvEnv = platform === "win32" && !process.env.UV_PYTHON_INSTALL_DIR
|
|
94
|
+
? { UV_PYTHON_INSTALL_DIR: join(homedir(), ".local", "share", "uv", "python") } : undefined;
|
|
95
|
+
let steps;
|
|
96
|
+
if (await available("uv")) {
|
|
97
|
+
steps = [{ command: "uv", args: install, env: uvEnv }];
|
|
98
|
+
} else {
|
|
99
|
+
// uv installs and manages the right Python itself; the system Python is only used to bootstrap uv.
|
|
100
|
+
let python = await findPython(probe, platform);
|
|
101
|
+
if (!python) {
|
|
102
|
+
const pythonInstall = await pythonInstallInvocation(platform, available);
|
|
103
|
+
if (!pythonInstall) return failed("Python 3." + MIN_PYTHON_MINOR + "+ is required to install Headroom and no supported package manager was found (winget, brew, apt-get, dnf). Install Python or uv manually and retry.");
|
|
104
|
+
const installed = await run(pythonInstall);
|
|
105
|
+
if (!installed.success) return { ...installed, message: "Cannot install Python for 'headroom': " + installed.message };
|
|
106
|
+
refreshPath();
|
|
107
|
+
python = await findPython(probe, platform);
|
|
108
|
+
if (!python) return failed("Python was installed but is not visible to this process yet; open a new terminal and run the update again.", installed);
|
|
109
|
+
}
|
|
110
|
+
const py = [...python.prefix, "-m"];
|
|
111
|
+
steps = [
|
|
112
|
+
{ command: python.command, args: [...py, "pip", "install", "--user", "--upgrade", "uv"], env: { PIP_BREAK_SYSTEM_PACKAGES: "1" } },
|
|
113
|
+
{ command: python.command, args: [...py, "uv", ...install], env: uvEnv },
|
|
114
|
+
{ command: python.command, args: [...py, "uv", "tool", "update-shell"] },
|
|
115
|
+
];
|
|
116
|
+
}
|
|
117
|
+
let result = { success: true, exitCode: 0 };
|
|
118
|
+
for (const { env, ...invocation } of steps) {
|
|
119
|
+
result = await run(invocation, env);
|
|
120
|
+
if (!result.success) return { ...result, message: "Cannot install 'headroom': " + result.message };
|
|
121
|
+
}
|
|
122
|
+
refreshPath();
|
|
123
|
+
return warmUp(result);
|
|
28
124
|
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { SERVICE_IDS } from "./config.js";
|
|
2
|
+
|
|
3
|
+
export const STARTUP_SERVICE_IDS = Object.freeze([
|
|
4
|
+
"ocx", "agentmemory", ...SERVICE_IDS.filter(id => !["ocx", "agentmemory"].includes(id)), "proxy",
|
|
5
|
+
]);
|
|
6
|
+
export const DEFAULT_START_SERVICES = Object.freeze(["ocx", "agentmemory", "proxy"]);
|
|
7
|
+
|
|
8
|
+
export function normalizeStartServices(value = DEFAULT_START_SERVICES) {
|
|
9
|
+
if (!Array.isArray(value) || !value.length || value.some(id => !STARTUP_SERVICE_IDS.includes(id))) {
|
|
10
|
+
throw new Error(`Select at least one startup service from: ${STARTUP_SERVICE_IDS.join(", ")}`);
|
|
11
|
+
}
|
|
12
|
+
// Start upstream services first and the built-in proxy last.
|
|
13
|
+
return STARTUP_SERVICE_IDS.filter(id => value.includes(id));
|
|
14
|
+
}
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { PROXY_FIELDS, proxySetupDraft, normalizeSetupDraft } from "./proxy-setup.js";
|
|
2
|
+
import { STARTUP_SERVICE_IDS, normalizeStartServices } from "./startup-services.js";
|
|
3
|
+
|
|
4
|
+
const STARTUP_FIELD = { key: "startServices", group: "Startup", label: "Services started by aih start / up",
|
|
5
|
+
choices: STARTUP_SERVICE_IDS, multiple: true,
|
|
6
|
+
help: "Arrows move; Space toggles. Choose at least one service. Explicit CLI targets override this list. RTK is a filter; bundled pxpipe does not need its standalone service. Changes take effect on the next aih start/up." };
|
|
7
|
+
|
|
8
|
+
const clean = value => String(value ?? "").replace(/[\x00-\x1f\x7f-\x9f]/g, " ");
|
|
9
|
+
|
|
10
|
+
/** Pure wizard state; all process and disk actions belong to Dashboard/manager. */
|
|
11
|
+
export class ProxySetupWizard {
|
|
12
|
+
constructor(state) {
|
|
13
|
+
this.draft = proxySetupDraft(state);
|
|
14
|
+
this.currentStartServices = normalizeStartServices(state.config?.startServices);
|
|
15
|
+
this.draft.startServices = this.currentStartServices.join(",");
|
|
16
|
+
this.serviceIndex = 0;
|
|
17
|
+
this.initial = { ...this.draft };
|
|
18
|
+
this.active = state.services?.proxy?.proxyOptions;
|
|
19
|
+
this.running = state.services?.proxy?.status === "running";
|
|
20
|
+
this.step = 0;
|
|
21
|
+
this.cursor = this.draft.upstream.length;
|
|
22
|
+
this.action = 0;
|
|
23
|
+
this.scroll = 0;
|
|
24
|
+
this.manualScroll = false;
|
|
25
|
+
this.error = "";
|
|
26
|
+
this.checks = [];
|
|
27
|
+
this.cancelPending = false;
|
|
28
|
+
this.pasting = false;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
get fields() { return [...PROXY_FIELDS.filter(f => !f.stage || this.draft.preset.split("-").includes(f.stage)), STARTUP_FIELD]; }
|
|
32
|
+
get field() { return this.fields[this.step]; }
|
|
33
|
+
get summary() { return this.step >= this.fields.length; }
|
|
34
|
+
get dirty() { return JSON.stringify(this.initial) !== JSON.stringify(this.draft); }
|
|
35
|
+
|
|
36
|
+
validate() {
|
|
37
|
+
normalizeStartServices(this.draft.startServices.split(","));
|
|
38
|
+
return normalizeSetupDraft(this.draft);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
validateField() {
|
|
42
|
+
const field = this.field;
|
|
43
|
+
const value = this.draft[field.key];
|
|
44
|
+
if (field.multiple) { normalizeStartServices(value.split(",")); return; }
|
|
45
|
+
// Validate only this field, against known valid defaults, without discarding other edits.
|
|
46
|
+
const base = proxySetupDraft({ services: {} });
|
|
47
|
+
base.upstream = "https://example.com";
|
|
48
|
+
if (field.key === "upstream") base.listen = "http://127.0.0.1:0";
|
|
49
|
+
base[field.key] = value;
|
|
50
|
+
normalizeSetupDraft(base);
|
|
51
|
+
if (field.key === "interceptor" && value && !value.endsWith(".mjs")) throw new Error("Select a .mjs file or leave empty");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
handle(key) {
|
|
55
|
+
if (key === "\x1b[200~") { this.pasting = true; return; }
|
|
56
|
+
if (key === "\x1b[201~") { this.pasting = false; return; }
|
|
57
|
+
if (this.pasting && (this.summary || this.field?.choices || /[\x00-\x1f\x7f-\x9f]/.test(key))) return;
|
|
58
|
+
if (this.cancelPending) {
|
|
59
|
+
if (key === "\r" || key === "\x1b") return "cancel";
|
|
60
|
+
this.cancelPending = false;
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
if (key === "\x1b") {
|
|
64
|
+
if (!this.dirty) return "cancel";
|
|
65
|
+
this.cancelPending = true;
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
this.error = "";
|
|
69
|
+
if (key === "\x1b[5~" || key === "\x1b[6~") {
|
|
70
|
+
this.scroll = Math.max(0, this.scroll + (key === "\x1b[5~" ? -4 : 4));
|
|
71
|
+
this.manualScroll = true;
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
this.manualScroll = false;
|
|
75
|
+
if (this.summary) {
|
|
76
|
+
if (this.pasting) return;
|
|
77
|
+
if (key === "\x1b[D" || key === "\x1b[Z") { this.step--; this.cursor = this.draft[this.field.key].length; return; }
|
|
78
|
+
if (key === "\x1b[A") this.action = (this.action + 4) % 5;
|
|
79
|
+
if (key === "\x1b[B" || key === "\t") this.action = (this.action + 1) % 5;
|
|
80
|
+
if (key === "\r" || key === "\n") {
|
|
81
|
+
if (this.action === 3) { this.step = 0; this.cursor = this.draft[this.field.key].length; return; }
|
|
82
|
+
if (this.action === 4) { this.cancelPending = this.dirty; return this.dirty ? undefined : "cancel"; }
|
|
83
|
+
try { this.validate(); } catch (error) { this.error = error.message; return; }
|
|
84
|
+
return ["check", "save", "apply"][this.action];
|
|
85
|
+
}
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
const f = this.field;
|
|
89
|
+
const value = this.draft[f.key];
|
|
90
|
+
if (key === "\x1b[Z") { this.step = Math.max(0, this.step - 1); this.cursor = this.draft[this.field.key].length; return; }
|
|
91
|
+
if (!this.pasting && (key === "\r" || key === "\n" || key === "\t")) {
|
|
92
|
+
try { this.validateField(); } catch (error) { this.error = error.message; return; }
|
|
93
|
+
this.step++;
|
|
94
|
+
if (!this.summary) this.cursor = this.draft[this.field.key].length;
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
if (f.choices) {
|
|
98
|
+
if (f.multiple) {
|
|
99
|
+
if (key === "\x1b[A") this.serviceIndex = (this.serviceIndex + f.choices.length - 1) % f.choices.length;
|
|
100
|
+
if (key === "\x1b[B") this.serviceIndex = (this.serviceIndex + 1) % f.choices.length;
|
|
101
|
+
if (key === " ") {
|
|
102
|
+
const selected = new Set(value.split(",").filter(Boolean));
|
|
103
|
+
const service = f.choices[this.serviceIndex];
|
|
104
|
+
if (selected.has(service)) selected.delete(service); else selected.add(service);
|
|
105
|
+
this.draft[f.key] = f.choices.filter(id => selected.has(id)).join(",");
|
|
106
|
+
}
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (["\x1b[A", "\x1b[B", "\x1b[C", "\x1b[D", " "].includes(key)) {
|
|
110
|
+
const delta = key === "\x1b[A" || key === "\x1b[D" ? -1 : 1;
|
|
111
|
+
const i = f.choices.indexOf(value);
|
|
112
|
+
this.draft[f.key] = f.choices[(i + delta + f.choices.length) % f.choices.length];
|
|
113
|
+
this.checks = [];
|
|
114
|
+
}
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
const previous = this.cursor - (Array.from(value.slice(0, this.cursor)).at(-1)?.length || 0);
|
|
118
|
+
const next = this.cursor + (Array.from(value.slice(this.cursor))[0]?.length || 0);
|
|
119
|
+
if (key === "\x1b[D") this.cursor = previous;
|
|
120
|
+
else if (key === "\x1b[C") this.cursor = next;
|
|
121
|
+
else if (key === "\x01" || key === "\x1b[H" || key === "\x1b[1~") this.cursor = 0;
|
|
122
|
+
else if (key === "\x05" || key === "\x1b[F" || key === "\x1b[4~") this.cursor = value.length;
|
|
123
|
+
else if (key === "\x15") { this.draft[f.key] = ""; this.cursor = 0; }
|
|
124
|
+
else if (key === "\x7f" || key === "\b") {
|
|
125
|
+
if (this.cursor) { this.draft[f.key] = value.slice(0, previous) + value.slice(this.cursor); this.cursor = previous; }
|
|
126
|
+
} else if (key === "\x1b[3~") this.draft[f.key] = value.slice(0, this.cursor) + value.slice(next);
|
|
127
|
+
else if (!/[\x00-\x1f\x7f-\x9f]/.test(key)) {
|
|
128
|
+
this.draft[f.key] = value.slice(0, this.cursor) + key + value.slice(this.cursor);
|
|
129
|
+
this.cursor += key.length;
|
|
130
|
+
}
|
|
131
|
+
if (value !== this.draft[f.key]) this.checks = [];
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
lines(width, height, busy = false) {
|
|
135
|
+
const wrap = text => {
|
|
136
|
+
const lines = [];
|
|
137
|
+
let line = "";
|
|
138
|
+
for (const word of clean(text).split(" ")) {
|
|
139
|
+
if (line && Array.from(line + " " + word).length > width) { lines.push(line); line = ""; }
|
|
140
|
+
const chars = Array.from(word);
|
|
141
|
+
while (chars.length > width) {
|
|
142
|
+
if (line) { lines.push(line); line = ""; }
|
|
143
|
+
lines.push(chars.splice(0, width).join(""));
|
|
144
|
+
}
|
|
145
|
+
line += (line ? " " : "") + chars.join("");
|
|
146
|
+
}
|
|
147
|
+
if (line || !lines.length) lines.push(line);
|
|
148
|
+
return lines;
|
|
149
|
+
};
|
|
150
|
+
const title = `PROXY SETUP | ${this.summary ? "Summary" : `${this.field.group} (${this.step + 1}/${this.fields.length})`}`;
|
|
151
|
+
let body = [];
|
|
152
|
+
if (this.summary) {
|
|
153
|
+
body = [...PROXY_FIELDS, STARTUP_FIELD].flatMap(f => {
|
|
154
|
+
const before = f.multiple ? this.currentStartServices.join(",") : String(this.active?.[f.key] ?? "");
|
|
155
|
+
const after = this.draft[f.key];
|
|
156
|
+
return wrap(`${before !== after ? "* " : " "}${f.label}: ${after || (f.key === "models" ? "pxpipe defaults; RTK/Headroom on all" : "(none)")}${before !== after ? ` (previous: ${before || "empty"})` : ""}`);
|
|
157
|
+
});
|
|
158
|
+
body.push(...wrap(this.running ? "WARNING: apply now restarts the proxy and interrupts active requests/streams." : "Apply now starts the proxy. Save only leaves it stopped."));
|
|
159
|
+
body.push(...this.checks.flatMap(wrap));
|
|
160
|
+
if (this.error) body.push(...wrap(`Error: ${this.error}`));
|
|
161
|
+
} else {
|
|
162
|
+
const f = this.field;
|
|
163
|
+
body.push(...wrap(f.label), ...wrap(f.help), "");
|
|
164
|
+
if (f.choices) body.push(...f.choices.map((v, i) => f.multiple
|
|
165
|
+
? `${i === this.serviceIndex ? ">" : " "} [${this.draft[f.key].split(",").includes(v) ? "x" : " "}] ${v}`
|
|
166
|
+
: `${v === this.draft[f.key] ? ">" : " "} ${v.replaceAll("-", " -> ")}`));
|
|
167
|
+
else {
|
|
168
|
+
const value = this.draft[f.key];
|
|
169
|
+
const start = Math.max(0, this.cursor - width + 6);
|
|
170
|
+
body.push(...wrap("> " + value.slice(start, this.cursor) + "|" + value.slice(this.cursor, start + width - 4)));
|
|
171
|
+
}
|
|
172
|
+
body.push(...wrap(`Initial value: ${this.initial[f.key] || "(empty)"}`));
|
|
173
|
+
const current = f.multiple ? this.currentStartServices.join(",") : this.active ? String(this.active[f.key] ?? "") || "(empty)" : "(not configured)";
|
|
174
|
+
body.push(...wrap(`Current setting: ${current}${!f.multiple && !this.running && this.active ? " (proxy stopped)" : ""}`));
|
|
175
|
+
}
|
|
176
|
+
const actions = ["Check", "Save only", "Save and apply now", "Edit", "Cancel"];
|
|
177
|
+
const controls = this.summary
|
|
178
|
+
? actions.map((a, i) => `${i === this.action ? ">" : " "} ${a}`)
|
|
179
|
+
: wrap("Enter/Tab next | Shift+Tab back | Esc cancel").concat(wrap(this.field.multiple ? "Arrows move | Space toggle" : this.field.choices ? "Arrows/Space change" : "Ctrl+U clear | Home/End move cursor"));
|
|
180
|
+
const hint = this.summary && this.action === 2
|
|
181
|
+
? this.running ? "RESTART: interrupts requests/streams." : "Apply starts the proxy."
|
|
182
|
+
: this.summary ? "Arrows select | Enter confirm | Esc cancel" : "Local draft; proxy unchanged.";
|
|
183
|
+
const status = this.cancelPending ? "Discard draft? Enter/Esc confirms; any other key continues" : busy ? "Operation in progress..." : this.error || hint;
|
|
184
|
+
const statusLines = wrap(status);
|
|
185
|
+
const tail = [...controls.flatMap(wrap), ...statusLines.slice(0, 2)];
|
|
186
|
+
const budget = Math.max(1, height - 3 - tail.length);
|
|
187
|
+
if (!this.summary && !this.manualScroll) {
|
|
188
|
+
// Keep the chosen preset visible on short terminals.
|
|
189
|
+
const selected = body.findIndex(line => line.startsWith("> "));
|
|
190
|
+
this.scroll = Math.max(0, selected - budget + 1);
|
|
191
|
+
}
|
|
192
|
+
this.scroll = Math.min(this.scroll, Math.max(0, body.length - budget));
|
|
193
|
+
return [clean(title).slice(0, width), "-".repeat(width), ...body.slice(this.scroll, this.scroll + budget),
|
|
194
|
+
...(body.length > budget ? ["PgUp/PgDn: scroll details"] : [""]), ...tail].slice(0, height);
|
|
195
|
+
}
|
|
196
|
+
}
|
package/src/tui.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { APP_NAME, VERSION } from "./config.js";
|
|
2
2
|
import { manager } from "./manager.js";
|
|
3
|
+
import { ProxySetupWizard } from "./tui-proxy-setup.js";
|
|
4
|
+
import { preflightProxy } from "./proxy-setup.js";
|
|
3
5
|
import {
|
|
4
6
|
badgeStatus,
|
|
5
7
|
bold,
|
|
@@ -261,6 +263,10 @@ export class Dashboard {
|
|
|
261
263
|
}
|
|
262
264
|
|
|
263
265
|
const proxy = this.statuses.find(s => s.id === "proxy");
|
|
266
|
+
if (this.proxySetup) {
|
|
267
|
+
this.proxySetup.active = proxy?.proxyOptions;
|
|
268
|
+
this.proxySetup.running = proxy?.status === "running";
|
|
269
|
+
}
|
|
264
270
|
const stats = await this.getProxyStats();
|
|
265
271
|
const probed = await probeChain(this.statuses, { nativeOnly: true });
|
|
266
272
|
const now = Date.now();
|
|
@@ -461,6 +467,7 @@ export class Dashboard {
|
|
|
461
467
|
buildLines() {
|
|
462
468
|
const width = Math.max(40, process.stdout.columns || 100);
|
|
463
469
|
const height = Math.max(12, process.stdout.rows || 30);
|
|
470
|
+
if (this.proxySetup) return this.proxySetup.lines(width, height, this.busy).map(line => clip(line, width));
|
|
464
471
|
const lines = [];
|
|
465
472
|
const svc = this.currentService();
|
|
466
473
|
const target = svc ? bold(svc.id) : dim("-");
|
|
@@ -469,6 +476,7 @@ export class Dashboard {
|
|
|
469
476
|
`${dim("q")} esci`,
|
|
470
477
|
`${dim("up/down")} seleziona (${target})`,
|
|
471
478
|
`${dim("s")} start`,
|
|
479
|
+
`${dim("c")} setup proxy`,
|
|
472
480
|
`${dim("x")} stop`,
|
|
473
481
|
`${dim("r")} restart`,
|
|
474
482
|
`${dim("u")} update`,
|
|
@@ -610,12 +618,26 @@ export class Dashboard {
|
|
|
610
618
|
* @param {string} key
|
|
611
619
|
*/
|
|
612
620
|
onKey(key) {
|
|
621
|
+
if (this.proxySetup && key !== "\u0003") {
|
|
622
|
+
if (this.busy) return;
|
|
623
|
+
const command = this.proxySetup.handle(key);
|
|
624
|
+
if (command === "cancel") this.proxySetup = null;
|
|
625
|
+
else if (command) this.runProxySetupAction(command);
|
|
626
|
+
this.render();
|
|
627
|
+
return;
|
|
628
|
+
}
|
|
613
629
|
if (key === "\u0003" || key === "q") {
|
|
614
630
|
this.stop();
|
|
615
631
|
return;
|
|
616
632
|
}
|
|
617
633
|
|
|
618
634
|
switch (key) {
|
|
635
|
+
case "c":
|
|
636
|
+
if (this.busy) return;
|
|
637
|
+
try { this.proxySetup = new ProxySetupWizard(manager.readState()); }
|
|
638
|
+
catch (error) { this.status = red(error.message); }
|
|
639
|
+
this.render();
|
|
640
|
+
return;
|
|
619
641
|
case "d":
|
|
620
642
|
this.showPipelineDetails = !this.showPipelineDetails;
|
|
621
643
|
this.render();
|
|
@@ -672,8 +694,32 @@ export class Dashboard {
|
|
|
672
694
|
}
|
|
673
695
|
}
|
|
674
696
|
|
|
697
|
+
async runProxySetupAction(command) {
|
|
698
|
+
if (this.busy || !this.proxySetup) return;
|
|
699
|
+
const wizard = this.proxySetup;
|
|
700
|
+
this.busy = true;
|
|
701
|
+
this.render();
|
|
702
|
+
try {
|
|
703
|
+
const options = wizard.validate();
|
|
704
|
+
if (command === "check") {
|
|
705
|
+
wizard.checks = [];
|
|
706
|
+
wizard.checks = await preflightProxy(options, (await manager.syncState()).services.proxy);
|
|
707
|
+
} else {
|
|
708
|
+
const startup = { startServices: wizard.draft.startServices.split(",") };
|
|
709
|
+
const result = command === "save" ? manager.saveProxyConfiguration(options, startup)
|
|
710
|
+
: await manager.applyProxyConfiguration(options, startup);
|
|
711
|
+
if (!result.success) throw new Error(result.message);
|
|
712
|
+
this.status = [result.message, result.codexConfig?.message].filter(Boolean).join(" | ");
|
|
713
|
+
this.proxySetup = null;
|
|
714
|
+
}
|
|
715
|
+
} catch (error) { wizard.error = error.message; }
|
|
716
|
+
finally { this.busy = false; }
|
|
717
|
+
await this.refresh();
|
|
718
|
+
this.render();
|
|
719
|
+
}
|
|
720
|
+
|
|
675
721
|
enterScreen() {
|
|
676
|
-
process.stdout.write(ALT_SCREEN_ON + CURSOR_HIDE);
|
|
722
|
+
process.stdout.write(ALT_SCREEN_ON + CURSOR_HIDE + "\x1b[?2004h");
|
|
677
723
|
if (process.stdin.isTTY) {
|
|
678
724
|
process.stdin.setRawMode(true);
|
|
679
725
|
process.stdin.resume();
|
|
@@ -688,6 +734,7 @@ export class Dashboard {
|
|
|
688
734
|
|
|
689
735
|
/** Always restores the terminal, even on a crash. */
|
|
690
736
|
leaveScreen() {
|
|
737
|
+
this.keyDecoder?.dispose();
|
|
691
738
|
if (process.stdin.isTTY) {
|
|
692
739
|
try {
|
|
693
740
|
process.stdin.setRawMode(false);
|
|
@@ -699,7 +746,7 @@ export class Dashboard {
|
|
|
699
746
|
process.off("SIGINT", this.onSigint);
|
|
700
747
|
process.off("uncaughtException", this.onFatal);
|
|
701
748
|
process.off("unhandledRejection", this.onFatal);
|
|
702
|
-
process.stdout.write(CURSOR_SHOW + ALT_SCREEN_OFF);
|
|
749
|
+
process.stdout.write("\x1b[?2004l" + CURSOR_SHOW + ALT_SCREEN_OFF);
|
|
703
750
|
}
|
|
704
751
|
|
|
705
752
|
stop() {
|
|
@@ -711,8 +758,9 @@ export class Dashboard {
|
|
|
711
758
|
}
|
|
712
759
|
|
|
713
760
|
async start() {
|
|
761
|
+
this.keyDecoder = new KeyDecoder(key => this.onKey(key));
|
|
714
762
|
this.onData = chunk => {
|
|
715
|
-
|
|
763
|
+
this.keyDecoder.push(String(chunk));
|
|
716
764
|
};
|
|
717
765
|
this.onResize = () => this.render();
|
|
718
766
|
this.onSigint = () => this.stop();
|
|
@@ -755,17 +803,45 @@ export function splitKeys(chunk) {
|
|
|
755
803
|
const keys = [];
|
|
756
804
|
let i = 0;
|
|
757
805
|
while (i < chunk.length) {
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
806
|
+
const escape = chunk.slice(i).match(/^\x1b\[[0-9;]*[A-Za-z~]/);
|
|
807
|
+
if (escape) {
|
|
808
|
+
keys.push(escape[0]);
|
|
809
|
+
i += escape[0].length;
|
|
761
810
|
continue;
|
|
762
811
|
}
|
|
763
|
-
|
|
764
|
-
|
|
812
|
+
const point = String.fromCodePoint(chunk.codePointAt(i));
|
|
813
|
+
keys.push(point);
|
|
814
|
+
i += point.length;
|
|
765
815
|
}
|
|
766
816
|
return keys;
|
|
767
817
|
}
|
|
768
818
|
|
|
819
|
+
/** CSI/paste sequences may arrive across separate stdin chunks. */
|
|
820
|
+
export class KeyDecoder {
|
|
821
|
+
constructor(onKey) { this.onKey = onKey; this.pending = ""; }
|
|
822
|
+
push(chunk) {
|
|
823
|
+
clearTimeout(this.timer);
|
|
824
|
+
const input = this.pending + chunk;
|
|
825
|
+
this.pending = "";
|
|
826
|
+
const partial = input.match(/\x1b(?:\[[0-9;]*)?$/);
|
|
827
|
+
const complete = partial ? input.slice(0, -partial[0].length) : input;
|
|
828
|
+
for (const key of splitKeys(complete)) this.onKey(key);
|
|
829
|
+
if (partial) {
|
|
830
|
+
this.pending = partial[0];
|
|
831
|
+
this.timer = setTimeout(() => this.flush(), 50);
|
|
832
|
+
this.timer.unref?.();
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
flush() {
|
|
836
|
+
clearTimeout(this.timer);
|
|
837
|
+
const pending = this.pending;
|
|
838
|
+
this.pending = "";
|
|
839
|
+
// A bare Esc is cancellation; truncated CSI must not turn into text/actions.
|
|
840
|
+
if (pending === "\x1b") this.onKey(pending);
|
|
841
|
+
}
|
|
842
|
+
dispose() { clearTimeout(this.timer); this.pending = ""; }
|
|
843
|
+
}
|
|
844
|
+
|
|
769
845
|
/**
|
|
770
846
|
* Entry point for the interactive dashboard.
|
|
771
847
|
* @returns {Promise<void>}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { existsSync, readdirSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { delimiter, join } from "node:path";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Directories where user-level installers put executables. A freshly installed
|
|
7
|
+
* tool is not on this process's PATH yet, so verification and startup would miss it.
|
|
8
|
+
*/
|
|
9
|
+
export function toolSearchDirectories({ platform = process.platform, env = process.env, home = homedir(), exists = existsSync, list = readdirSync } = {}) {
|
|
10
|
+
const dirs = [join(home, ".local", "bin")];
|
|
11
|
+
const pythons = root => {
|
|
12
|
+
try {
|
|
13
|
+
return list(root).filter(name => /^Python3\d+$/i.test(name)).sort().reverse().flatMap(name => [join(root, name), join(root, name, "Scripts")]);
|
|
14
|
+
} catch { return []; }
|
|
15
|
+
};
|
|
16
|
+
if (platform === "win32") {
|
|
17
|
+
if (env.LOCALAPPDATA) dirs.push(...pythons(join(env.LOCALAPPDATA, "Programs", "Python")));
|
|
18
|
+
if (env.ProgramFiles) dirs.push(...pythons(env.ProgramFiles));
|
|
19
|
+
} else {
|
|
20
|
+
dirs.push("/opt/homebrew/bin", "/usr/local/bin");
|
|
21
|
+
}
|
|
22
|
+
return dirs.filter(dir => exists(dir));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Append (never prepend) missing tool directories to this process's PATH. */
|
|
26
|
+
export function refreshToolPath(options = {}) {
|
|
27
|
+
const env = options.env || process.env;
|
|
28
|
+
const current = (env.PATH || env.Path || "").split(delimiter).filter(Boolean);
|
|
29
|
+
const same = (a, b) => (options.platform || process.platform) === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
|
|
30
|
+
const added = toolSearchDirectories({ ...options, env }).filter(dir => !current.some(entry => same(entry, dir)));
|
|
31
|
+
if (added.length) env.PATH = [...current, ...added].join(delimiter);
|
|
32
|
+
return added;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
@@ -13,7 +13,7 @@ export function npmUpdateInvocation(packageName, platform = process.platform) {
|
|
|
13
13
|
}
|
|
14
14
|
|
|
15
15
|
/** Capture installer output, keeping --json/TUI clean and full diagnostics in the log. */
|
|
16
|
-
export function runUpdateInstaller(id, { command, args }, { spawnImpl = spawn } = {}) {
|
|
16
|
+
export function runUpdateInstaller(id, { command, args }, { spawnImpl = spawn, env } = {}) {
|
|
17
17
|
ensureDir(getLogsDir());
|
|
18
18
|
const logPath = getServiceLogPath(id);
|
|
19
19
|
const fd = openSync(logPath, "a");
|
|
@@ -37,7 +37,7 @@ export function runUpdateInstaller(id, { command, args }, { spawnImpl = spawn }
|
|
|
37
37
|
try {
|
|
38
38
|
const child = spawnImpl(command, args, {
|
|
39
39
|
windowsHide: true, stdio: ["ignore", "pipe", "pipe"],
|
|
40
|
-
env: { ...process.env, CI: "1", npm_config_yes: "true", PIP_NO_INPUT: "1", NO_COLOR: "1" },
|
|
40
|
+
env: { ...process.env, CI: "1", npm_config_yes: "true", PIP_NO_INPUT: "1", NO_COLOR: "1", ...env },
|
|
41
41
|
});
|
|
42
42
|
child.stdout?.on("data", collect);
|
|
43
43
|
child.stderr?.on("data", collect);
|
package/src/utils/versions.js
CHANGED
|
@@ -3,6 +3,7 @@ import { readFile, realpath } from "node:fs/promises";
|
|
|
3
3
|
import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
|
|
4
4
|
import { baseUrl, fetchJson } from "./metrics.js";
|
|
5
5
|
import { SERVICE_PACKAGES as PACKAGES } from "../config.js";
|
|
6
|
+
import { refreshToolPath } from "./tool-path.js";
|
|
6
7
|
|
|
7
8
|
function parseVersion(value) {
|
|
8
9
|
if (typeof value !== "string") return null;
|
|
@@ -94,6 +95,8 @@ export async function readNpmVersionFromCommand(command, name) {
|
|
|
94
95
|
async function getInstalledVersion(status, command) {
|
|
95
96
|
const pkg = PACKAGES[status.id];
|
|
96
97
|
if (pkg.pypi) {
|
|
98
|
+
// User-level installers (uv/pipx) put the binary where this process may not look yet.
|
|
99
|
+
refreshToolPath();
|
|
97
100
|
// Headroom's Click CLI explicitly implements --version without starting a proxy.
|
|
98
101
|
const output = await runVersionCommand("headroom", ["--version"]);
|
|
99
102
|
return cleanVersion(output?.match(/^headroom, version\s+(\S+)$/im)?.[1]);
|