@drakonkat/ai-helper 1.2.13 → 1.2.15

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
@@ -74,6 +74,11 @@ $ports = Get-NetTCPConnection -State Listen | Select-Object LocalPort, OwningPro
74
74
  3. Automatically computes uptimes from `CreationDate`.
75
75
  4. Maps dynamic ports to Web Dashboard URLs.
76
76
 
77
+ PowerShell discovery queries have a 10-second deadline so a cold or stalled CIM
78
+ provider cannot block status indefinitely. A failed scan is discarded; persisted
79
+ service PIDs are still checked for liveness and the next status refresh retries
80
+ external-process discovery.
81
+
77
82
  ### Unix Implementation
78
83
  Uses `ps -eo pid,command` to match command line strings and extract active PIDs.
79
84
 
package/CHANGELOG.md CHANGED
@@ -4,6 +4,28 @@ All notable changes to **`ai-helper` (`aih`)** are documented in this file.
4
4
 
5
5
  ---
6
6
 
7
+ ## [1.2.15] - 2026-10-26
8
+
9
+ ### Added
10
+ - 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.
11
+ - `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.
12
+ - Separate desired proxy settings from the running worker, preserve explicit empty resets and attempt recovery of the previous worker after failed setup application.
13
+ - CLI `--pxpipe-native-images allow|bypass` and explicit `--models "*"` selection.
14
+
15
+ ### Changed
16
+ - 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.
17
+ - Benchmark JSON records include proxy/worker timings and live provider headers/first-output timings when available.
18
+
19
+ ---
20
+
21
+ ## [1.2.14] - 2026-09-30
22
+
23
+ ### Fixed
24
+ - Bound Windows PowerShell/CIM discovery to 10 seconds so a cold or stalled provider cannot hang CLI status or port discovery. Discard failed scans while preserving live service PIDs already recorded in state.
25
+ - Treat subprocess termination without an exit code as failure and add a regression check for command deadlines. This fixes the Windows/Node 20 CI status test failure.
26
+
27
+ ---
28
+
7
29
  ## [1.2.13] - 2026-09-30
8
30
 
9
31
  ### Fixed
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,
@@ -363,7 +410,9 @@ aih start
363
410
 
364
411
  The preference is saved in `~/.aih/state.json` (or `AIH_HOME/state.json`).
365
412
  It applies to `start`/`up` and proxy starts/restarts; an explicit `--models`
366
- takes precedence without changing the preference. `aih config pxpipe-models=`
413
+ takes precedence without changing the legacy preference. If a dashboard setup
414
+ exists, successful starts retain their effective options in that setup instead.
415
+ `aih config pxpipe-models=`
367
416
  saves pxpipe's default selection. Configuration does not restart a running proxy.
368
417
 
369
418
  The value is passed only to the built-in proxy; `ocx` and `agentmemory` start
@@ -371,7 +420,8 @@ normally. `--models=` passes an empty string; `--models ""` also works when your
371
420
  shell preserves empty arguments. A bare `--models` without a value is an error.
372
421
  See [Select models](#select-models) for matching and compression behavior.
373
422
 
374
- The no-target `start`/`up` commands supply the upstream, listener and preset above
423
+ Without a saved Startup selection, no-target `start`/`up` launches OCX, AgentMemory
424
+ and proxy. Unless a dashboard setup has been saved, these commands supply the upstream, listener and preset above
375
425
  on every invocation, plus the configured model list (or the list above if unset),
376
426
  unless `--models` overrides it.
377
427
  Other saved proxy options are retained.
@@ -481,7 +531,8 @@ options; defaults in this table apply when no saved value exists.
481
531
  | --- | --- |
482
532
  | `--listen http://127.0.0.1:10102` | Loopback HTTP listener; default `http://127.0.0.1:10101`. |
483
533
  | `--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*"` | pxpipe model selection; `--models=` restores pxpipe's defaults. Also accepted by generic `start`/`up`. |
534
+ | `--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`. |
535
+ | `--pxpipe-native-images allow\|bypass` | Allow pxpipe on native-image requests (default) or bypass that stage. |
485
536
  | `--interceptor "./my hooks/interceptor.mjs"` | Custom JavaScript hooks, loaded at startup; default none. `--interceptor=` clears the saved path. |
486
537
  | `--headroom-url http://127.0.0.1:8787` | Headroom compression service; default shown. |
487
538
  | `--rtk-filter grep` | Fixed RTK filter for matching tool output; default auto-detection. `--rtk-filter=` resets it. |
@@ -588,8 +639,11 @@ grep-output filter to every tool result, so use it only with matching output.
588
639
 
589
640
  ### Select models
590
641
 
591
- **All models are forwarded.** `--models` selects only which models pxpipe may
592
- compress; Headroom/RTK still process eligible requests outside that list.
642
+ **All models are forwarded.** An explicit `--models` list selects the entire
643
+ compression recipe: excluded requests bypass RTK, Headroom and pxpipe unchanged.
644
+ This replaces the older pxpipe-only filtering behavior. `--models "*"` includes
645
+ all models. With an empty/omitted selection, pxpipe uses its supported-model
646
+ defaults while RTK/Headroom process all eligible requests.
593
647
  Names match the `model` in the request, including any provider prefix.
594
648
  For example, an AGY catalog entry can be `google-antigravity/gemini-3.8-flash`,
595
649
  while Astra is `gpt-6-astra`.
@@ -670,7 +724,10 @@ npm run bench:proxy -- --headroom-url http://127.0.0.1:8787 --repetitions 5
670
724
  ```
671
725
 
672
726
  Results include JSON, JSONL, CSV and Markdown. Unknown image costs are not counted
673
- as zero, and offline checks never claim a semantic-quality winner. Benchmark-only
727
+ as zero. JSON/JSONL records retain available proxy preset, worker queue/processing,
728
+ CPU and event-loop timings, plus live provider headers and first output; see the
729
+ benchmark documentation for measurement boundaries. Offline checks never claim
730
+ a semantic-quality winner. Benchmark-only
674
731
  pxpipe allowlisting defaults to all fixture models so imaging is actually exercised.
675
732
  See [benchmark documentation](docs/benchmark.md) for corpus customization, live
676
733
  evaluation, privacy, limitations and quality/performance decision thresholds.
@@ -702,11 +759,11 @@ to restore RTK auto-detection.
702
759
  Use a fixed filter only when the tool output matches that format. Empty or larger
703
760
  results are discarded. Prompts, tool calls and binary content are left untouched;
704
761
  no command from an AI request is executed.
705
- - **headroom-pxpipe:** always applies Headroom first; `--models` gates only the
706
- following pxpipe stage.
762
+ - **headroom-pxpipe:** applies Headroom first, then pxpipe; an explicit `--models`
763
+ list gates both stages.
707
764
  - **rtk-pxpipe:** applies RTK to tool-result text first, then the pxpipe library.
708
- `--rtk-filter` controls RTK and `--models` gates only pxpipe; RTK still runs for
709
- models outside the allowlist. This chain needs RTK on PATH, with no Headroom service.
765
+ `--rtk-filter` controls RTK and an explicit `--models` list gates both stages.
766
+ This chain needs RTK on PATH, with no Headroom service.
710
767
 
711
768
  Presets process JSON POSTs on Messages, Chat Completions and Responses routes,
712
769
  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.13",
3
+ "version": "1.2.15",
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 && 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",
@@ -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
  `;
@@ -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;
@@ -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 => sink.records.get(event.requestId)?.events.push(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 launches ocx, agentmemory, then proxy with:
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; the list selects which ones pxpipe may process.
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 : ["ocx", "agentmemory", "proxy"];
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";
@@ -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
  */
@@ -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
+ }
@@ -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
- for (const key of splitKeys(String(chunk))) this.onKey(key);
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
- if (chunk[i] === "\x1b" && chunk[i + 1] === "[" && chunk[i + 2]) {
759
- keys.push(chunk.slice(i, i + 3));
760
- i += 3;
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
- keys.push(chunk[i]);
764
- i++;
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>}
@@ -15,14 +15,16 @@ export function sleep(ms) {
15
15
  * Helper to run a command and return stdout/stderr asynchronously.
16
16
  * @param {string} cmd
17
17
  * @param {string[]} args
18
+ * @param {number} [timeout=0] Maximum runtime in milliseconds; zero disables the deadline.
18
19
  * @returns {Promise<{ exitCode: number; stdout: string; stderr: string }>}
19
20
  */
20
- export function execCommand(cmd, args) {
21
+ export function execCommand(cmd, args, timeout = 0) {
21
22
  return new Promise(resolve => {
22
23
  try {
23
24
  const proc = spawn(cmd, args, {
24
25
  stdio: ["ignore", "pipe", "pipe"],
25
26
  windowsHide: true,
27
+ timeout,
26
28
  });
27
29
 
28
30
  let stdout = "";
@@ -32,7 +34,7 @@ export function execCommand(cmd, args) {
32
34
  proc.stderr?.on("data", d => (stderr += d.toString()));
33
35
 
34
36
  proc.on("close", exitCode => {
35
- resolve({ exitCode: exitCode ?? 0, stdout, stderr });
37
+ resolve({ exitCode: exitCode ?? 1, stdout, stderr });
36
38
  });
37
39
 
38
40
  proc.on("error", err => {
@@ -107,7 +109,8 @@ export async function findPidsListeningOnPorts(ports) {
107
109
  try {
108
110
  const portList = ports.join(", ");
109
111
  const script = `Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue | Where-Object { $_.LocalPort -in ${portList} } | Select-Object -ExpandProperty OwningProcess`;
110
- const res = await execCommand("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]);
112
+ const res = await execCommand("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], 10000);
113
+ if (res.exitCode !== 0) return [];
111
114
  const lines = res.stdout.trim().split(/\r?\n/);
112
115
  for (const line of lines) {
113
116
  const pid = parseInt(line.trim(), 10);
@@ -372,8 +375,9 @@ export async function discoverRunningProcesses({ knownServices = {} } = {}) {
372
375
  Select-Object LocalPort, OwningProcess
373
376
  @{ Procs = $procs; Ports = $ports } | ConvertTo-Json -Depth 3
374
377
  `;
375
- const res = await execCommand("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]);
376
- if (res.stdout.trim()) return discoverWindowsProcesses(JSON.parse(res.stdout), { knownServices });
378
+ // A cold or stalled CIM provider must not hold status and the dashboard indefinitely.
379
+ const res = await execCommand("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], 10000);
380
+ if (res.exitCode === 0 && res.stdout.trim()) return discoverWindowsProcesses(JSON.parse(res.stdout), { knownServices });
377
381
  } catch {}
378
382
  } else {
379
383
  try {