@drakonkat/ai-helper 1.2.8 → 1.2.10
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 +19 -0
- package/README.md +64 -3
- package/package.json +1 -1
- package/src/gpt-launchers.js +189 -0
- package/src/gpt.js +174 -0
- package/src/index.js +24 -0
- package/src/proxy-presets.js +22 -4
- package/src/proxy-stats.js +25 -10
- package/src/proxy.js +47 -8
- package/src/tui.js +25 -1
- package/src/utils/format.js +19 -0
- package/src/utils/process.js +15 -9
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,25 @@ All notable changes to **`ai-helper` (`aih`)** are documented in this file.
|
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
+
## [1.2.10] - 2026-09-29
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
- Show preset processing time, upstream response-header latency, total HTTP/SSE duration, upstream status and interrupted/failed responses in the live request stream. WebSocket events report preset time only.
|
|
11
|
+
- Regression coverage for streaming, concurrent requests, transport failures, cancellation and timing persistence without duplicate counters.
|
|
12
|
+
|
|
13
|
+
### Fixed
|
|
14
|
+
- Close parent log descriptors after spawning detached services and allow cold Windows process discovery to finish in CI.
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## [1.2.9] - 2026-09-29
|
|
19
|
+
|
|
20
|
+
### Added
|
|
21
|
+
- Show the originating Codex session and Git project in the live request stream when request metadata is available; persist these identifiers in the proxy statistics snapshot.
|
|
22
|
+
- Include the Windows Astra launcher from main alongside the native proxy commands, and workstation restore scripts in the repository.
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
7
26
|
## [1.2.8] - 2026-09-24
|
|
8
27
|
|
|
9
28
|
### Added
|
package/README.md
CHANGED
|
@@ -189,11 +189,41 @@ proxy traffic or token-generation speed. Counters persist across restarts.
|
|
|
189
189
|
|
|
190
190
|
`STREAM RICHIESTE` shows the latest recorded events with local time, model,
|
|
191
191
|
HTTP/WS transport, preset, changed/unchanged/error outcome, estimated savings
|
|
192
|
-
and stage reasons.
|
|
192
|
+
and stage reasons. When Codex supplies `x-codex-turn-metadata`, events also show
|
|
193
|
+
the session ID (falling back to the thread ID) and Git project (`owner/repo` from
|
|
194
|
+
the first available workspace remote). These fields are recorded only for new
|
|
195
|
+
requests; older events or clients without this metadata omit them. After an
|
|
196
|
+
upgrade, restart the proxy and reopen the updated dashboard; a source checkout
|
|
197
|
+
can be run directly with `node bin/cli.js status --ui` to avoid an older global
|
|
198
|
+
installation taking precedence on PATH.
|
|
199
|
+
|
|
200
|
+
Request timings use a monotonic clock and appear on new events:
|
|
201
|
+
|
|
202
|
+
- `proxy`: preset processing, including request decompression and serialization,
|
|
203
|
+
but excluding client upload, custom interceptors and forwarding.
|
|
204
|
+
- `header`: time from dispatching the upstream HTTP request to receiving its
|
|
205
|
+
response headers, including connection setup and upstream request upload.
|
|
206
|
+
This is **not** time to first model token; SSE headers can arrive before output.
|
|
207
|
+
- `tot`: time from receiving the client's HTTP request headers until the proxy
|
|
208
|
+
finishes sending the response (or the connection fails/closes). Includes client
|
|
209
|
+
upload, preset/interceptor work, upstream waiting and streaming/downstream
|
|
210
|
+
backpressure; it does not confirm delivery to the client application.
|
|
211
|
+
|
|
212
|
+
HTTP/SSE entries also show the upstream HTTP status and incomplete/error states.
|
|
213
|
+
The existing event is updated without counting another request. A pending state
|
|
214
|
+
only means no completion was recorded (for example after a proxy crash), not a
|
|
215
|
+
global count of active calls. Updates do not bring evicted events back into the
|
|
216
|
+
bounded recent list. WebSocket events report **only preset time**: connection
|
|
217
|
+
duration and arbitrary response frames cannot safely be attributed to individual
|
|
218
|
+
calls. Missing/older timings remain `n/d`. Error responses that arrive normally
|
|
219
|
+
(such as HTTP 500) retain their status; a transport failure is marked separately
|
|
220
|
+
from a preset error. Preset `none` remains unrecorded.
|
|
221
|
+
|
|
222
|
+
Press **`d`** for source/configuration details and per-stage
|
|
193
223
|
before/after token counts, percentages and measurement methods. Unknown savings
|
|
194
224
|
remain unknown; partial estimates and token increases are explicitly marked.
|
|
195
|
-
The panels do not infer provider cache savings, costs,
|
|
196
|
-
active
|
|
225
|
+
The panels do not infer provider cache savings, costs, model-only latency or
|
|
226
|
+
active request counts. Preset `none` and interceptor-only traffic are not recorded.
|
|
197
227
|
|
|
198
228
|
A running process is not a health check, and the final upstream is not monitored.
|
|
199
229
|
Snapshot read time is separate from last-event time: an idle proxy is not stale
|
|
@@ -332,6 +362,37 @@ the installed/latest versions and the update command to stderr. The check times
|
|
|
332
362
|
out after 1.5 seconds; network errors never prevent startup. Updates are not
|
|
333
363
|
installed automatically. Compiled executables must be rebuilt to update them.
|
|
334
364
|
|
|
365
|
+
### Astra / `--gpt` (Windows)
|
|
366
|
+
|
|
367
|
+
```powershell
|
|
368
|
+
aih start --gpt
|
|
369
|
+
aih start --gpt --json
|
|
370
|
+
```
|
|
371
|
+
|
|
372
|
+
Uses the configured Windows compression stack: starts OCX when needed, then pxpipe on **47822** and Headroom on **8788**, and selects **gpt-6-astra** with the `pxpipe-codex` provider in Codex's user config. Requests follow **Codex → Headroom → pxpipe → OCX → ChatGPT subscription**. OCX retains its canonical OpenAI endpoint and uses account pool mode; Anthropic's OCX endpoint is direct to avoid a routing loop.
|
|
373
|
+
|
|
374
|
+
The provider keeps `requires_openai_auth = true` so Codex shows your signed-in ChatGPT profile. `experimental_bearer_token = "local-proxy"` keeps model requests using the local placeholder credential; OCX supplies the real upstream credentials. Both settings are needed: enabling OpenAI auth alone sends the ChatGPT token to the proxies and can break Claude routing. Reopen Codex if an already-running app still displays the provider label after this configuration change.
|
|
375
|
+
|
|
376
|
+
The startup uses the same banner, colors and per-process output as plain `aih start`, including the actual listening PID:
|
|
377
|
+
|
|
378
|
+
```text
|
|
379
|
+
Starting service(s): ocx, pxpipe, headroom...
|
|
380
|
+
|
|
381
|
+
Launching ocx... already running (PID: 1100)
|
|
382
|
+
Launching pxpipe... started (PID: 2200)
|
|
383
|
+
Launching headroom... started (PID: 3300)
|
|
384
|
+
```
|
|
385
|
+
|
|
386
|
+
The JavaScript launchers are **included in the package and standalone build**; no external `.ps1` files are required. Install/login to OCX and install Node.js, pxpipe-proxy and Headroom first. AIH finds Node and Headroom through `PATH` (also `~/.local/bin/headroom.exe`), and pxpipe through global npm or its npm cache, without fixed cache hashes or user-specific paths. Missing dependencies produce an installation hint; AIH does not install tools or create subscription credentials.
|
|
387
|
+
|
|
388
|
+
Paths default to the current user's home and respect `CODEX_HOME`, `APPDATA`, `LOCALAPPDATA`, `XDG_CONFIG_HOME`, and npm's cache/prefix configuration. Nonstandard installations can set `NODE_BINARY`, `PXPIPE_CLI_PATH` (the package's `bin/cli.js`) and `HEADROOM_BINARY`. Existing `PXPIPE_CONFIG`, `PXPIPE_LOG`, `PXPIPE_GPT_PROFILES`, `HEADROOM_WORKSPACE_DIR`, `HEADROOM_CONFIG_DIR` and `HEADROOM_SETTINGS_PATH` overrides are supported. The bundled Astra compression profile matches the previous launcher; Headroom runs with `--lossless --no-cache`.
|
|
389
|
+
|
|
390
|
+
Startup follows dependency order (OCX, pxpipe, Headroom); **requests flow the other way: Headroom → pxpipe → OCX**, which selects the final endpoint by model. Both pxpipe upstreams point to OCX on 10100. Hidden, on-demand Windows tasks named `AIH-GPT-<user>-pxpipe` and `AIH-GPT-<user>-headroom` keep the proxies alive independently of Codex, without boot/login triggers or external script files. Logs are `gpt-<service>.stdout.log` / `gpt-<service>.stderr.log` in `~/.pxpipe` and the Headroom workspace. Healthy existing instances are reused, including instances started by the old launchers; existing external scripts/tasks are not removed or changed. An occupied but unhealthy port fails its readiness check rather than spawning a duplicate.
|
|
391
|
+
|
|
392
|
+
Plain `aih start`, stop/restart and the TUI retain their existing service behavior; use `aih start --gpt` to bring up/check this chain and its printed URLs to access its dashboards. `--json` prints only JSON, including a `services` array with process IDs and already-running status.
|
|
393
|
+
|
|
394
|
+
The command backs up configuration files under `~/.aih/backups/gpt-*`, checks Headroom's actual upstream settings and verifies that Astra appears in the model catalog through the chain. AIH selects Astra last, after these checks. OCX can also sync Codex config during its own cold startup, so AIH saves the original before starting OCX; that backup remains available if startup fails. **Start a new Codex task** afterward: existing tasks can retain their old provider even after restarting the app. The existing pxpipe compression profile and Headroom compression options are preserved.
|
|
395
|
+
|
|
335
396
|
---
|
|
336
397
|
|
|
337
398
|
### 4. Stop Services
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@drakonkat/ai-helper",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.10",
|
|
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",
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { delimiter, dirname, join, resolve } from "node:path";
|
|
3
|
+
import { homedir, tmpdir, userInfo } from "node:os";
|
|
4
|
+
import { execCommand } from "./utils/process.js";
|
|
5
|
+
|
|
6
|
+
const MARKER = "AIH_GPT_LAUNCHER_V1";
|
|
7
|
+
const PXPIPE_PROFILE = '{"gpt-6-astra":{"stripCols":95,"maxHeightPx":1932,"style":{"font":"jetbrains-mono-12","cellWBonus":0,"cellHBonus":0,"aa":true,"grid":false,"gridCols":0}}}';
|
|
8
|
+
|
|
9
|
+
function value(env, name) {
|
|
10
|
+
const key = Object.keys(env).find(key => key.toUpperCase() === name.toUpperCase());
|
|
11
|
+
return key === undefined ? undefined : env[key];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function file(path) {
|
|
15
|
+
try { return statSync(path).isFile(); } catch { return false; }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function directories(env) {
|
|
19
|
+
return (value(env, "PATH") || "").split(delimiter).map(path => path.trim().replace(/^"(.*)"$/, "$1")).filter(Boolean);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function binary(name, override, paths, fallback) {
|
|
23
|
+
if (override) {
|
|
24
|
+
const found = [override, ...paths.map(path => join(path, override))].find(file);
|
|
25
|
+
if (found) return resolve(found);
|
|
26
|
+
throw new Error(`${name} executable not found at ${override}. Correct the executable override before retrying.`);
|
|
27
|
+
}
|
|
28
|
+
const found = [...paths.flatMap(path => [join(path, `${name}.exe`), join(path, name)]), fallback].filter(Boolean).find(file);
|
|
29
|
+
if (found) return resolve(found);
|
|
30
|
+
throw new Error(`${name} is not installed or not on PATH. Install ${name === "node" ? "Node.js (or set NODE_BINARY)" : "Headroom (or set HEADROOM_BINARY)"} before starting GPT.`);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function pxpipeCli(home, env, paths, node, run) {
|
|
34
|
+
const override = value(env, "PXPIPE_CLI_PATH");
|
|
35
|
+
if (override) {
|
|
36
|
+
if (!file(override)) throw new Error(`PXPIPE_CLI_PATH does not point to an installed cli.js: ${override}`);
|
|
37
|
+
return resolve(override);
|
|
38
|
+
}
|
|
39
|
+
const appdata = value(env, "APPDATA") || join(home, "AppData", "Roaming");
|
|
40
|
+
const local = value(env, "LOCALAPPDATA") || join(home, "AppData", "Local");
|
|
41
|
+
const prefixes = [...paths, dirname(node), join(appdata, "npm"), value(env, "npm_config_prefix")].filter(Boolean);
|
|
42
|
+
const cli = root => join(root, "pxpipe-proxy", "bin", "cli.js");
|
|
43
|
+
const globalCli = prefixes.flatMap(prefix => [cli(join(prefix, "node_modules")), cli(join(dirname(prefix), "lib", "node_modules"))]).find(file);
|
|
44
|
+
if (globalCli) return resolve(globalCli);
|
|
45
|
+
|
|
46
|
+
const caches = [value(env, "npm_config_cache"), join(local, "npm-cache"), join(appdata, "npm-cache"), join(home, ".npm")].filter(Boolean);
|
|
47
|
+
// Use npm's installed JS entry point, never a shell shim (or an npx install).
|
|
48
|
+
const npm = prefixes.map(prefix => join(prefix, "node_modules", "npm", "bin", "npm-cli.js")).find(file);
|
|
49
|
+
if (npm) {
|
|
50
|
+
const root = await run(node, [npm, "root", "--global"]);
|
|
51
|
+
if (root.exitCode === 0 && file(cli(root.stdout.trim()))) return resolve(cli(root.stdout.trim()));
|
|
52
|
+
const cache = await run(node, [npm, "config", "get", "cache"]);
|
|
53
|
+
if (cache.exitCode === 0 && cache.stdout.trim()) caches.unshift(cache.stdout.trim());
|
|
54
|
+
}
|
|
55
|
+
for (const cache of new Set(caches)) {
|
|
56
|
+
const npx = join(cache, "_npx");
|
|
57
|
+
let candidates;
|
|
58
|
+
try {
|
|
59
|
+
candidates = readdirSync(npx, { withFileTypes: true })
|
|
60
|
+
.filter(entry => entry.isDirectory())
|
|
61
|
+
.map(entry => cli(join(npx, entry.name, "node_modules")))
|
|
62
|
+
.filter(file)
|
|
63
|
+
.sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs);
|
|
64
|
+
} catch { continue; }
|
|
65
|
+
if (candidates.length) return resolve(candidates[0]);
|
|
66
|
+
}
|
|
67
|
+
throw new Error("pxpipe-proxy is not installed on PATH, in global npm, or in the npm cache. Install it with npm install --global pxpipe-proxy, or set PXPIPE_CLI_PATH to its bin/cli.js.");
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Resolve a cold-start command without starting anything or installing packages. */
|
|
71
|
+
export async function resolveGptLaunch(id, { home = homedir(), env = process.env, run = execCommand } = {}) {
|
|
72
|
+
if (id !== "pxpipe" && id !== "headroom") throw new Error(`Unknown GPT launcher: ${id}`);
|
|
73
|
+
const paths = directories(env);
|
|
74
|
+
const node = binary("node", value(env, "NODE_BINARY"), paths);
|
|
75
|
+
const username = value(env, "USERNAME") || userInfo().username;
|
|
76
|
+
const domain = value(env, "USERDOMAIN");
|
|
77
|
+
const taskUser = domain ? `${domain}\\${username}` : username;
|
|
78
|
+
const systemRoot = value(env, "SystemRoot");
|
|
79
|
+
const taskName = `AIH-GPT-${username.replace(/[\\/:*?"<>|\[\]]/g, "_")}-${id}`;
|
|
80
|
+
const spec = {
|
|
81
|
+
id, node, taskName, taskUser,
|
|
82
|
+
schtasks: systemRoot && existsSync(join(systemRoot, "System32", "schtasks.exe")) ? join(systemRoot, "System32", "schtasks.exe") : "schtasks.exe",
|
|
83
|
+
env: { ...(value(env, "PATH") !== undefined ? { PATH: value(env, "PATH") } : {}) },
|
|
84
|
+
};
|
|
85
|
+
if (id === "pxpipe") {
|
|
86
|
+
spec.command = node;
|
|
87
|
+
spec.args = [await pxpipeCli(home, env, paths, node, run)];
|
|
88
|
+
spec.cwd = join(home, ".pxpipe");
|
|
89
|
+
Object.assign(spec.env, {
|
|
90
|
+
HOST: "127.0.0.1", PORT: "47822",
|
|
91
|
+
PXPIPE_UPSTREAM: "http://127.0.0.1:10100",
|
|
92
|
+
ANTHROPIC_UPSTREAM: "http://127.0.0.1:10100",
|
|
93
|
+
OPENAI_UPSTREAM: "http://127.0.0.1:10100",
|
|
94
|
+
PXPIPE_CONFIG: value(env, "PXPIPE_CONFIG") || join(value(env, "XDG_CONFIG_HOME") || join(home, ".config"), "pxpipe", "config.json"),
|
|
95
|
+
PXPIPE_LOG: value(env, "PXPIPE_LOG") || join(spec.cwd, "events.jsonl"),
|
|
96
|
+
PXPIPE_GPT_PROFILES: value(env, "PXPIPE_GPT_PROFILES") ?? PXPIPE_PROFILE,
|
|
97
|
+
});
|
|
98
|
+
spec.clearEnv = ["PXPIPE_MODELS", "OPENAI_API_KEY", "PXPIPE_PROVIDER", "PXPIPE_GATEWAY_BASE_URL", "PXPIPE_GATEWAY_HEADERS", "OPENAI_MODELS", "CLOUDFLARE_MODELS", "CLOUDFLARE_ACCOUNT_ID", "CLOUDFLARE_API_TOKEN"];
|
|
99
|
+
} else {
|
|
100
|
+
spec.command = binary("headroom", value(env, "HEADROOM_BINARY"), paths, join(home, ".local", "bin", "headroom.exe"));
|
|
101
|
+
spec.args = ["proxy", "--host", "127.0.0.1", "--port", "8788", "--openai-api-url", "http://127.0.0.1:47822", "--anthropic-api-url", "http://127.0.0.1:47822", "--lossless", "--no-cache"];
|
|
102
|
+
spec.cwd = value(env, "HEADROOM_WORKSPACE_DIR") || join(home, ".headroom");
|
|
103
|
+
Object.assign(spec.env, {
|
|
104
|
+
HEADROOM_WORKSPACE_DIR: spec.cwd,
|
|
105
|
+
HEADROOM_CONFIG_DIR: value(env, "HEADROOM_CONFIG_DIR") || join(spec.cwd, "config"),
|
|
106
|
+
HEADROOM_SETTINGS_PATH: value(env, "HEADROOM_SETTINGS_PATH") || join(spec.cwd, "settings.json"),
|
|
107
|
+
});
|
|
108
|
+
spec.clearEnv = ["ANTHROPIC_TARGET_API_URL", "OPENAI_TARGET_API_URL"];
|
|
109
|
+
}
|
|
110
|
+
spec.stdoutLog = join(spec.cwd, `gpt-${id}.stdout.log`);
|
|
111
|
+
spec.stderrLog = join(spec.cwd, `gpt-${id}.stderr.log`);
|
|
112
|
+
return spec;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Keep this self-contained: Bun can rename imports when compiling the binary.
|
|
116
|
+
// The scheduled action injects Node's modules rather than capturing our imports.
|
|
117
|
+
function runService(spec, fs, spawn) {
|
|
118
|
+
const env = { ...process.env };
|
|
119
|
+
const replaced = new Set([...spec.clearEnv, ...Object.keys(spec.env)].map(key => key.toUpperCase()));
|
|
120
|
+
for (const key of Object.keys(env)) if (replaced.has(key.toUpperCase())) delete env[key];
|
|
121
|
+
Object.assign(env, spec.env);
|
|
122
|
+
const stdout = fs.openSync(spec.stdoutLog, "a");
|
|
123
|
+
const stderr = fs.openSync(spec.stderrLog, "a");
|
|
124
|
+
const child = spawn(spec.command, spec.args, {
|
|
125
|
+
cwd: spec.cwd, env, windowsHide: true, stdio: ["ignore", stdout, stderr],
|
|
126
|
+
});
|
|
127
|
+
child.on("error", error => {
|
|
128
|
+
fs.writeSync(stderr, `[aih] ${error.message}\n`);
|
|
129
|
+
process.exitCode = 1;
|
|
130
|
+
});
|
|
131
|
+
child.on("close", code => {
|
|
132
|
+
fs.closeSync(stdout);
|
|
133
|
+
fs.closeSync(stderr);
|
|
134
|
+
process.exitCode = code >= 0 && code !== null ? code : 1;
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function xml(text) {
|
|
139
|
+
return String(text).replace(/[&<>"']/g, char => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char]);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function unxml(text) {
|
|
143
|
+
return text.replace(/&(?:amp|lt|gt|quot|apos);/g, entity => ({ "&": "&", "<": "<", ">": ">", """: '"', "'": "'" })[entity]);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function quoteArgument(argument) {
|
|
147
|
+
return `"${argument.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, "$1$1")}"`;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Start a hidden, persistent per-user task. Its definition intentionally survives CLI exit. */
|
|
151
|
+
export async function launchGptProcess(spec, { run = execCommand } = {}) {
|
|
152
|
+
const description = `ai-helper GPT launcher v1: ${spec.taskName} (${spec.taskUser})`;
|
|
153
|
+
const existing = await run(spec.schtasks, ["/Query", "/TN", spec.taskName, "/XML"]);
|
|
154
|
+
const update = existing.exitCode === 0;
|
|
155
|
+
if (update) {
|
|
156
|
+
const oldDescription = existing.stdout.match(/<Description>([\s\S]*?)<\/Description>/)?.[1];
|
|
157
|
+
const oldArguments = existing.stdout.match(/<Arguments>([\s\S]*?)<\/Arguments>/)?.[1];
|
|
158
|
+
if (unxml(oldDescription || "") !== description || !unxml(oldArguments || "").includes(`/*${MARKER}*/`)) {
|
|
159
|
+
throw new Error(`Scheduled task ${spec.taskName} is not owned by ai-helper; it was not changed. Rename that task or use a different Windows account.`);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
mkdirSync(spec.cwd, { recursive: true });
|
|
164
|
+
for (const path of [spec.stdoutLog, spec.stderrLog]) mkdirSync(dirname(path), { recursive: true });
|
|
165
|
+
const { command, args, cwd, env, clearEnv, stdoutLog, stderrLog } = spec;
|
|
166
|
+
const payload = Buffer.from(JSON.stringify({ command, args, cwd, env, clearEnv, stdoutLog, stderrLog })).toString("base64");
|
|
167
|
+
const script = `/*${MARKER}*/(${runService.toString()})(JSON.parse(Buffer.from("${payload}","base64").toString("utf8")),require("node:fs"),require("node:child_process").spawn)`;
|
|
168
|
+
const argumentsText = ["-e", script].map(quoteArgument).join(" ");
|
|
169
|
+
const definition = `<?xml version="1.0" encoding="UTF-16"?>
|
|
170
|
+
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
171
|
+
<RegistrationInfo><Description>${xml(description)}</Description></RegistrationInfo>
|
|
172
|
+
<Triggers />
|
|
173
|
+
<Principals><Principal id="Author"><UserId>${xml(spec.taskUser)}</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>
|
|
174
|
+
<Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries><AllowHardTerminate>true</AllowHardTerminate><StartWhenAvailable>false</StartWhenAvailable><RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable><Enabled>true</Enabled><Hidden>true</Hidden><ExecutionTimeLimit>PT0S</ExecutionTimeLimit></Settings>
|
|
175
|
+
<Actions Context="Author"><Exec><Command>${xml(spec.node)}</Command><Arguments>${xml(argumentsText)}</Arguments><WorkingDirectory>${xml(spec.cwd)}</WorkingDirectory></Exec></Actions>
|
|
176
|
+
</Task>`;
|
|
177
|
+
const temporary = mkdtempSync(join(tmpdir(), "aih-gpt-task-"));
|
|
178
|
+
try {
|
|
179
|
+
const path = join(temporary, "task.xml");
|
|
180
|
+
writeFileSync(path, `\uFEFF${definition}`, "utf16le");
|
|
181
|
+
const created = await run(spec.schtasks, ["/Create", "/TN", spec.taskName, "/XML", path, ...(update ? ["/F"] : [])]);
|
|
182
|
+
if (created.exitCode !== 0) throw new Error(`Cannot register ${spec.taskName}: ${created.stderr.trim() || created.stdout.trim() || "Task Scheduler rejected the task"}`);
|
|
183
|
+
} finally {
|
|
184
|
+
rmSync(temporary, { recursive: true, force: true });
|
|
185
|
+
}
|
|
186
|
+
const started = await run(spec.schtasks, ["/Run", "/TN", spec.taskName]);
|
|
187
|
+
if (started.exitCode !== 0) throw new Error(`Cannot start ${spec.taskName}: ${started.stderr.trim() || started.stdout.trim() || "Task Scheduler rejected the start"}`);
|
|
188
|
+
return { taskName: spec.taskName, stdoutLog: spec.stdoutLog, stderrLog: spec.stderrLog };
|
|
189
|
+
}
|
package/src/gpt.js
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { getAihDir } from "./utils/path.js";
|
|
5
|
+
import { execCommand, findPidsListeningOnPorts, sleep } from "./utils/process.js";
|
|
6
|
+
import { launchGptProcess, resolveGptLaunch } from "./gpt-launchers.js";
|
|
7
|
+
|
|
8
|
+
export const ASTRA_MODEL = "gpt-6-astra";
|
|
9
|
+
export const GPT_SERVICE_IDS = ["ocx", "pxpipe", "headroom"];
|
|
10
|
+
export const GPT_URLS = {
|
|
11
|
+
ocx: "http://127.0.0.1:10100",
|
|
12
|
+
pxpipe: "http://127.0.0.1:47822",
|
|
13
|
+
headroom: "http://127.0.0.1:8788",
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
// The GPT chain uses its own ports without changing the normal service defaults.
|
|
17
|
+
export function configureCodexForAstra(text) {
|
|
18
|
+
const newline = text.includes("\r\n") ? "\r\n" : "\n";
|
|
19
|
+
const bom = text.startsWith("\uFEFF") ? "\uFEFF" : "";
|
|
20
|
+
text = text.replace(/^\uFEFF/, "").replace(/\r\n/g, "\n");
|
|
21
|
+
const firstTable = text.search(/^[ \t]*\[/m);
|
|
22
|
+
let root = firstTable < 0 ? text : text.slice(0, firstTable);
|
|
23
|
+
let tables = firstTable < 0 ? "" : text.slice(firstTable);
|
|
24
|
+
// ponytail: scoped TOML editing; reject complex target sections instead of guessing.
|
|
25
|
+
const headers = tables.match(/^[ \t]*\[[^\n]*pxpipe-codex[^\n]*$/gm) || [];
|
|
26
|
+
if (/"""|'''/.test(root) || headers.length > 1 ||
|
|
27
|
+
headers.some(h => !/^[ \t]*\[model_providers\.pxpipe-codex\][ \t]*(?:#.*)?$/.test(h))) {
|
|
28
|
+
throw new Error("Unsupported multiline/nested Codex configuration; config.toml was not changed.");
|
|
29
|
+
}
|
|
30
|
+
for (const [key, value] of Object.entries({ model: ASTRA_MODEL, model_provider: "pxpipe-codex" })) {
|
|
31
|
+
const pattern = new RegExp(`^[ \\t]*${key}[ \\t]*=[^\\n]*$`, "gm");
|
|
32
|
+
if ((root.match(pattern) || []).length > 1) throw new Error(`Duplicate Codex setting: ${key}`);
|
|
33
|
+
root = pattern.test(root)
|
|
34
|
+
? root.replace(pattern, `${key} = "${value}"`)
|
|
35
|
+
: `${root.trimEnd()}\n${key} = "${value}"\n\n`;
|
|
36
|
+
}
|
|
37
|
+
const provider = [
|
|
38
|
+
"[model_providers.pxpipe-codex]",
|
|
39
|
+
'name = "Headroom -> pxpipe -> OCX"',
|
|
40
|
+
`base_url = "${GPT_URLS.headroom}/v1"`,
|
|
41
|
+
'wire_api = "responses"',
|
|
42
|
+
"requires_openai_auth = true",
|
|
43
|
+
// Preserve the ChatGPT profile while OCX supplies the real upstream credentials.
|
|
44
|
+
'experimental_bearer_token = "local-proxy"',
|
|
45
|
+
"supports_websockets = false",
|
|
46
|
+
"", "",
|
|
47
|
+
].join("\n");
|
|
48
|
+
const pattern = /^[ \t]*\[model_providers\.pxpipe-codex\][ \t]*(?:#.*)?(?:\n|$)[\s\S]*?(?=^[ \t]*\[|(?![\s\S]))/m;
|
|
49
|
+
if (/"""|'''/.test(tables.match(pattern)?.[0] || "")) {
|
|
50
|
+
throw new Error("Unsupported multiline provider configuration; config.toml was not changed.");
|
|
51
|
+
}
|
|
52
|
+
tables = pattern.test(tables) ? tables.replace(pattern, () => provider) : `${tables.trimEnd()}\n\n${provider}`;
|
|
53
|
+
return bom + (root + tables).replace(/\n/g, newline);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function requestJson(url, options = {}) {
|
|
57
|
+
const response = await fetch(url, { ...options, signal: AbortSignal.timeout(5000) });
|
|
58
|
+
if (!response.ok) throw new Error(`${url}: HTTP ${response.status}`);
|
|
59
|
+
return response.json();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export async function startGpt({ manager, home = homedir(), env = process.env, codexHome = env.CODEX_HOME || join(home, ".codex"),
|
|
63
|
+
platform = process.platform, request = requestJson, run = execCommand, pause = sleep,
|
|
64
|
+
findPids = findPidsListeningOnPorts, resolveLaunch = resolveGptLaunch, launchProcess = launchGptProcess,
|
|
65
|
+
withProgress = async (_id, start) => start() } = {}) {
|
|
66
|
+
if (platform !== "win32") throw new Error("aih start --gpt currently requires Windows.");
|
|
67
|
+
const ocxPath = join(home, ".opencodex", "config.json");
|
|
68
|
+
const headroomPath = env.HEADROOM_SETTINGS_PATH || join(env.HEADROOM_WORKSPACE_DIR || join(home, ".headroom"), "settings.json");
|
|
69
|
+
const codexPath = join(codexHome, "config.toml");
|
|
70
|
+
for (const file of [ocxPath, codexPath]) {
|
|
71
|
+
if (!existsSync(file)) throw new Error(`Missing compression setup: ${file}. See README: Astra / --gpt.`);
|
|
72
|
+
}
|
|
73
|
+
configureCodexForAstra(readFileSync(codexPath, "utf8")); // Validate before starting or changing anything.
|
|
74
|
+
const ocxConfig = JSON.parse(readFileSync(ocxPath, "utf8").replace(/^\uFEFF/, ""));
|
|
75
|
+
const openai = ocxConfig.providers?.openai;
|
|
76
|
+
if (!openai || openai.disabled || openai.authMode !== "forward" ||
|
|
77
|
+
openai.baseUrl?.replace(/\/+$/, "") !== "https://chatgpt.com/backend-api/codex") {
|
|
78
|
+
throw new Error("Enable the canonical OpenAI subscription provider in OCX before using --gpt.");
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
let backupDir;
|
|
82
|
+
function backup(file, name) {
|
|
83
|
+
if (!backupDir) {
|
|
84
|
+
const parent = join(getAihDir(), "backups");
|
|
85
|
+
mkdirSync(parent, { recursive: true });
|
|
86
|
+
backupDir = mkdtempSync(join(parent, "gpt-"));
|
|
87
|
+
}
|
|
88
|
+
if (existsSync(file) && !existsSync(join(backupDir, name))) copyFileSync(file, join(backupDir, name));
|
|
89
|
+
}
|
|
90
|
+
function writeBackedUp(file, value, name) {
|
|
91
|
+
if (existsSync(file) && readFileSync(file, "utf8") === value) return;
|
|
92
|
+
backup(file, name);
|
|
93
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
94
|
+
const temp = `${file}.aih-${process.pid}.tmp`;
|
|
95
|
+
writeFileSync(temp, value, "utf8");
|
|
96
|
+
renameSync(temp, file);
|
|
97
|
+
}
|
|
98
|
+
async function waitFor(label, url, valid) {
|
|
99
|
+
let lastError;
|
|
100
|
+
for (let attempt = 0; attempt < 30; attempt++) {
|
|
101
|
+
try {
|
|
102
|
+
const body = await request(url);
|
|
103
|
+
if (valid(body)) return body;
|
|
104
|
+
lastError = "unexpected health response";
|
|
105
|
+
} catch (error) { lastError = error.message; }
|
|
106
|
+
await pause(1000);
|
|
107
|
+
}
|
|
108
|
+
throw new Error(`${label} is not ready: ${lastError}`);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const services = [];
|
|
112
|
+
async function startService(id, healthPath, valid, launch) {
|
|
113
|
+
const result = await withProgress(id, async () => {
|
|
114
|
+
const url = GPT_URLS[id];
|
|
115
|
+
const port = Number(new URL(url).port);
|
|
116
|
+
const health = await request(`${url}${healthPath}`).catch(() => null);
|
|
117
|
+
let alreadyRunning = Boolean(health && valid(health));
|
|
118
|
+
const listeners = await findPids([port]);
|
|
119
|
+
if (!alreadyRunning && !listeners.length) {
|
|
120
|
+
const launched = await launch();
|
|
121
|
+
alreadyRunning = Boolean(launched?.alreadyRunning);
|
|
122
|
+
} else {
|
|
123
|
+
// Never spawn a second process onto an occupied port, even if it is unhealthy.
|
|
124
|
+
alreadyRunning = true;
|
|
125
|
+
}
|
|
126
|
+
await waitFor(id, `${url}${healthPath}`, valid);
|
|
127
|
+
const [pid] = await findPids([port]);
|
|
128
|
+
if (!pid) throw new Error(`Cannot determine ${id}'s listening PID on port ${port}.`);
|
|
129
|
+
return { id, success: true, alreadyRunning, pid, url };
|
|
130
|
+
});
|
|
131
|
+
services.push(result);
|
|
132
|
+
}
|
|
133
|
+
await startService("ocx", "/healthz", h => h.service === "opencodex" && h.status === "ok", async () => {
|
|
134
|
+
// OCX can inject its own Codex settings during startup, before our final selection.
|
|
135
|
+
backup(codexPath, "codex-config.toml");
|
|
136
|
+
const result = await manager.startService("ocx");
|
|
137
|
+
if (!result.success) throw new Error(result.message);
|
|
138
|
+
return result;
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
// Update the live router through OCX's API; editing its JSON alone does not reload it.
|
|
142
|
+
const patches = [];
|
|
143
|
+
if (ocxConfig.providers.anthropic && ocxConfig.providers.anthropic.baseUrl !== "https://api.anthropic.com") {
|
|
144
|
+
patches.push(["anthropic", { baseUrl: "https://api.anthropic.com" }]);
|
|
145
|
+
}
|
|
146
|
+
if (openai.codexAccountMode !== "pool") patches.push(["openai", { codexAccountMode: "pool" }]);
|
|
147
|
+
if (patches.length) {
|
|
148
|
+
const token = readFileSync(join(home, ".opencodex", "admin-api-token"), "utf8").trim();
|
|
149
|
+
backup(ocxPath, "ocx-config.json");
|
|
150
|
+
for (const [provider, patch] of patches) {
|
|
151
|
+
const result = await request(`${GPT_URLS.ocx}/api/providers?name=${provider}`, {
|
|
152
|
+
method: "PATCH", headers: { "content-type": "application/json", "x-opencodex-api-key": token },
|
|
153
|
+
body: JSON.stringify(patch),
|
|
154
|
+
});
|
|
155
|
+
if (!result.success) throw new Error(`OCX rejected the ${provider} configuration.`);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
const headroom = existsSync(headroomPath) ? JSON.parse(readFileSync(headroomPath, "utf8").replace(/^\uFEFF/, "")) : {};
|
|
159
|
+
if (headroom.anthropic_base_url !== GPT_URLS.pxpipe || headroom.openai_base_url !== GPT_URLS.pxpipe) {
|
|
160
|
+
writeBackedUp(headroomPath, JSON.stringify({ ...headroom, anthropic_base_url: GPT_URLS.pxpipe,
|
|
161
|
+
openai_base_url: GPT_URLS.pxpipe }, null, 2) + "\n", "headroom-settings.json");
|
|
162
|
+
}
|
|
163
|
+
const launchProxy = async id => launchProcess(await resolveLaunch(id, { home, env, run }), { run });
|
|
164
|
+
await startService("pxpipe", "/proxy-stats", h => h && typeof h === "object", () => launchProxy("pxpipe"));
|
|
165
|
+
await startService("headroom", "/health", h => h.status === "healthy" &&
|
|
166
|
+
h.config?.openai_api_url === GPT_URLS.pxpipe && h.config?.anthropic_api_url === GPT_URLS.pxpipe,
|
|
167
|
+
() => launchProxy("headroom"));
|
|
168
|
+
// A healthy process alone does not prove that the local chain reaches OCX's model router.
|
|
169
|
+
const models = await request(`${GPT_URLS.headroom}/v1/models`, { headers: { Authorization: "Bearer local-proxy" } });
|
|
170
|
+
if (!models.data?.some(m => m.id === ASTRA_MODEL)) throw new Error(`OCX does not expose ${ASTRA_MODEL} through the chain.`);
|
|
171
|
+
writeBackedUp(codexPath, configureCodexForAstra(readFileSync(codexPath, "utf8")), "codex-config.toml");
|
|
172
|
+
return { model: ASTRA_MODEL, urls: GPT_URLS, services, backupDir,
|
|
173
|
+
note: "Start a NEW Codex task: existing tasks retain their provider. The existing pxpipe compression profile is preserved." };
|
|
174
|
+
}
|
package/src/index.js
CHANGED
|
@@ -10,6 +10,8 @@ import {
|
|
|
10
10
|
gray,
|
|
11
11
|
green,
|
|
12
12
|
printBanner,
|
|
13
|
+
printStartBanner,
|
|
14
|
+
printServiceStart,
|
|
13
15
|
red,
|
|
14
16
|
renderTable,
|
|
15
17
|
yellow,
|
|
@@ -61,6 +63,7 @@ ${bold("OPTIONS:")}
|
|
|
61
63
|
${gray("-f, --follow")} Follow log output in real-time (logs only)
|
|
62
64
|
${gray("--json")} JSON for status, start/up, restart, update and stats
|
|
63
65
|
${gray("--repo")} Open GitHub repositories instead of dashboards (open only)
|
|
66
|
+
${gray("--gpt")} Start the configured Windows Astra chain (start/up only)
|
|
64
67
|
${gray("-ui, --ui")} Open the interactive dashboard (status only, requires a TTY)
|
|
65
68
|
${gray("--models <list>")} pxpipe model allowlist (start/up and start/up/restart proxy)
|
|
66
69
|
|
|
@@ -110,6 +113,7 @@ ${bold("EXAMPLES - STATUS, DASHBOARDS AND LOGS:")}
|
|
|
110
113
|
|
|
111
114
|
${bold("EXAMPLES - START, STOP AND UPDATE:")}
|
|
112
115
|
${dim("$")} ${cyan(CLI_NAME)} start
|
|
116
|
+
${dim("$")} ${cyan(CLI_NAME)} start --gpt ${dim("# OCX -> pxpipe -> Headroom, Codex model: Astra")}
|
|
113
117
|
${dim("$")} ${cyan(CLI_NAME)} config pxpipe-models="gpt-6-astra,claude-opus-5-5"
|
|
114
118
|
${dim("$")} ${cyan(CLI_NAME)} start --models "gpt-6-astra,anthropic/claude-fable*" --json
|
|
115
119
|
${dim("$")} ${cyan(CLI_NAME)} up --models="google-antigravity/gemini-3.8*"
|
|
@@ -238,6 +242,7 @@ export async function main({ updateSelfImpl = updateSelf } = {}) {
|
|
|
238
242
|
let jsonOutput = false;
|
|
239
243
|
let follow = false;
|
|
240
244
|
let uiMode = false;
|
|
245
|
+
let gptMode = false;
|
|
241
246
|
let repoMode = false;
|
|
242
247
|
let lines = 50;
|
|
243
248
|
let models;
|
|
@@ -247,6 +252,8 @@ export async function main({ updateSelfImpl = updateSelf } = {}) {
|
|
|
247
252
|
const arg = rawArgs[i];
|
|
248
253
|
if (arg === "--json") {
|
|
249
254
|
jsonOutput = true;
|
|
255
|
+
} else if (arg === "--gpt") {
|
|
256
|
+
gptMode = true;
|
|
250
257
|
} else if (arg === "--repo") {
|
|
251
258
|
repoMode = true;
|
|
252
259
|
} else if (arg === "-ui" || arg === "--ui") {
|
|
@@ -285,6 +292,23 @@ export async function main({ updateSelfImpl = updateSelf } = {}) {
|
|
|
285
292
|
const command = serviceFirstUpdate ? "update" : positionalArgs[0]?.toLowerCase() || "status";
|
|
286
293
|
const targets = serviceFirstUpdate ? [positionalArgs[0].toLowerCase()] : positionalArgs.slice(1);
|
|
287
294
|
|
|
295
|
+
if (gptMode) {
|
|
296
|
+
if (!["start", "up"].includes(command) || targets.length || uiMode) {
|
|
297
|
+
throw new Error("Use 'aih start --gpt' without service names or --ui.");
|
|
298
|
+
}
|
|
299
|
+
const { startGpt, GPT_SERVICE_IDS } = await import("./gpt.js");
|
|
300
|
+
if (!jsonOutput) printStartBanner(GPT_SERVICE_IDS);
|
|
301
|
+
const result = await startGpt({ manager, withProgress: jsonOutput ? undefined : printServiceStart });
|
|
302
|
+
if (jsonOutput) console.log(JSON.stringify(result, null, 2));
|
|
303
|
+
else {
|
|
304
|
+
console.log("");
|
|
305
|
+
console.log(green(`Astra ready: Codex -> Headroom (${result.urls.headroom}) -> pxpipe (${result.urls.pxpipe}) -> OCX (${result.urls.ocx}) -> model endpoint`));
|
|
306
|
+
console.log(result.note);
|
|
307
|
+
if (result.backupDir) console.log(`Configuration backups: ${result.backupDir}`);
|
|
308
|
+
}
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
|
|
288
312
|
switch (command) {
|
|
289
313
|
case "config": {
|
|
290
314
|
if (targets.length !== 1 || !targets[0].startsWith("pxpipe-models=") || rawArgs.some(arg => arg.startsWith("-"))) {
|
package/src/proxy-presets.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { promisify } from "node:util";
|
|
3
3
|
import zlib from "node:zlib";
|
|
4
|
+
import { performance } from "node:perf_hooks";
|
|
4
5
|
import { tokenStage } from "./proxy-stats.js";
|
|
5
6
|
import { requestImages } from "./request-images.js";
|
|
6
7
|
|
|
@@ -119,7 +120,7 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
119
120
|
JSON.stringify(result.messages) !== JSON.stringify(messages), result.compression_skipped ? "compression_skipped" : "processed", "headroom");
|
|
120
121
|
}
|
|
121
122
|
|
|
122
|
-
async function transform(raw, context, websocket = false) {
|
|
123
|
+
async function transform(raw, context, websocket = false, started = performance.now()) {
|
|
123
124
|
const path = new URL(context.path, "http://localhost").pathname;
|
|
124
125
|
const format = /\/(?:v1\/|anthropic\/)?messages$/.test(path) ? "anthropic"
|
|
125
126
|
: /\/chat\/completions$/.test(path) ? "chat" : /\/responses$/.test(path) ? "responses" : null;
|
|
@@ -142,7 +143,22 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
142
143
|
// Observability must never interrupt proxy traffic; no request bodies are passed to the recorder.
|
|
143
144
|
// Optional correlation only; never pass headers or bodies to the recorder.
|
|
144
145
|
const requestId = typeof context.headers?.["x-request-id"] === "string" ? context.headers["x-request-id"].slice(0, 128) : undefined;
|
|
145
|
-
|
|
146
|
+
let source = {};
|
|
147
|
+
try {
|
|
148
|
+
const metadata = JSON.parse(context.headers?.["x-codex-turn-metadata"] || "{}");
|
|
149
|
+
const remotes = Object.values(metadata.workspaces || {}).flatMap(workspace => Object.values(workspace?.associated_remote_urls || {}));
|
|
150
|
+
const project = remotes.filter(value => typeof value === "string").map(value => value.replace(/^[^@/]+@[^:/]+:/, "")
|
|
151
|
+
.replace(/^[a-z]+:\/\/[^/]+/i, "").split(/[?#]/)[0].replace(/\.git$/i, "").split("/").filter(Boolean).slice(-2).join("/")).find(Boolean);
|
|
152
|
+
source = Object.fromEntries(Object.entries({ sessionId: metadata.session_id, threadId: metadata.thread_id, project })
|
|
153
|
+
.filter(([, value]) => typeof value === "string" && value.length).map(([key, value]) => [key, value.slice(0, 128)]));
|
|
154
|
+
} catch {}
|
|
155
|
+
try {
|
|
156
|
+
const update = onStats({ model, preset: config.preset, transport: websocket ? "WS" : "HTTP", changed, stages, error,
|
|
157
|
+
timings: { presetMs: Math.round((performance.now() - started) * 10) / 10 },
|
|
158
|
+
...source, ...(requestId ? { requestId } : {}) });
|
|
159
|
+
// ponytail: WS measures presets only; response timings need per-response-ID correlation.
|
|
160
|
+
if (!websocket && typeof update === "function") context.updateTiming = update;
|
|
161
|
+
} catch {}
|
|
146
162
|
};
|
|
147
163
|
try {
|
|
148
164
|
// Fixed stage order, including the triple recipe: RTK -> Headroom -> pxpipe.
|
|
@@ -203,13 +219,15 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
203
219
|
} else if (px) {
|
|
204
220
|
stages.push(tokenStage("pxpipe", 0, 0, false, "model_excluded", "pxpipe_estimate"));
|
|
205
221
|
}
|
|
222
|
+
const output = changed ? Buffer.from(JSON.stringify(envelope)) : raw;
|
|
206
223
|
report(false);
|
|
207
|
-
return
|
|
224
|
+
return output;
|
|
208
225
|
} catch (error) { report(true); throw error; }
|
|
209
226
|
}
|
|
210
227
|
|
|
211
228
|
return {
|
|
212
229
|
async onRequest(context) {
|
|
230
|
+
const started = performance.now();
|
|
213
231
|
if (context.method !== "POST" || !/\bapplication\/(?:[\w.-]+\+)?json\b/i.test(String(context.headers["content-type"] || ""))) return;
|
|
214
232
|
const encoding = String(context.headers["content-encoding"] || "identity").toLowerCase();
|
|
215
233
|
if (encoding !== "identity" && !DECODERS[encoding]) {
|
|
@@ -220,7 +238,7 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
220
238
|
return;
|
|
221
239
|
}
|
|
222
240
|
const raw = encoding === "identity" ? context.body : await DECODERS[encoding](context.body, { maxOutputLength: config.maxBodyBytes });
|
|
223
|
-
const body = await transform(raw, context);
|
|
241
|
+
const body = await transform(raw, context, false, started);
|
|
224
242
|
if (body !== raw) {
|
|
225
243
|
context.body = body;
|
|
226
244
|
delete context.headers["content-encoding"];
|
package/src/proxy-stats.js
CHANGED
|
@@ -22,6 +22,18 @@ export function createProxyStatsRecorder(file = getProxyStatsPath()) {
|
|
|
22
22
|
const stats = readProxyStats(file) || { version: 1, since: new Date().toISOString(), requests: 0,
|
|
23
23
|
changed: 0, errors: 0, estimatedSavedTokens: 0, unmeasuredStages: 0, stages: {}, recent: [] };
|
|
24
24
|
let warned = false;
|
|
25
|
+
const warn = error => {
|
|
26
|
+
if (!warned) console.error(`[aih stats] Cannot save statistics: ${error.message}`);
|
|
27
|
+
warned = true;
|
|
28
|
+
};
|
|
29
|
+
const save = () => {
|
|
30
|
+
try {
|
|
31
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
32
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
33
|
+
writeFileSync(temporary, JSON.stringify(stats) + "\n");
|
|
34
|
+
renameSync(temporary, file);
|
|
35
|
+
} catch (error) { warn(error); }
|
|
36
|
+
};
|
|
25
37
|
return event => {
|
|
26
38
|
try {
|
|
27
39
|
stats.updatedAt = new Date().toISOString();
|
|
@@ -39,18 +51,21 @@ export function createProxyStatsRecorder(file = getProxyStatsPath()) {
|
|
|
39
51
|
}
|
|
40
52
|
stats.estimatedSavedTokens += saved;
|
|
41
53
|
const model = String(event.model).replace(/[\r\n]/g, " ").slice(0, 128);
|
|
42
|
-
|
|
43
|
-
changed: event.changed, error: Boolean(event.error), saved: event.error ? null : saved,
|
|
54
|
+
const recent = { at: stats.updatedAt, model, preset: event.preset, transport: event.transport,
|
|
55
|
+
changed: event.changed, error: Boolean(event.error), saved: event.error ? null : saved,
|
|
56
|
+
sessionId: event.sessionId, threadId: event.threadId, project: event.project,
|
|
57
|
+
...(event.timings ? { timings: { ...event.timings } } : {}), stages };
|
|
58
|
+
stats.recent.push(recent);
|
|
44
59
|
stats.recent = stats.recent.slice(-20);
|
|
45
|
-
|
|
46
|
-
const temporary = `${file}.${process.pid}.tmp`;
|
|
47
|
-
writeFileSync(temporary, JSON.stringify(stats) + "\n");
|
|
48
|
-
renameSync(temporary, file);
|
|
60
|
+
save();
|
|
49
61
|
console.log(`[aih stats] ${event.transport} ${model} ${event.preset}: ${event.error ? "processing failed" : stages.map(s => `${s.name}=${s.saved ?? "?"} (${s.reason})`).join(", ") + `; estimated saved=${saved} tokens`}`);
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
62
|
+
// Update this entry, never recount a request or resurrect an evicted entry.
|
|
63
|
+
return timings => {
|
|
64
|
+
if (!stats.recent.includes(recent)) return;
|
|
65
|
+
recent.timings = { ...recent.timings, ...timings };
|
|
66
|
+
save();
|
|
67
|
+
};
|
|
68
|
+
} catch (error) { warn(error); }
|
|
54
69
|
};
|
|
55
70
|
}
|
|
56
71
|
|
package/src/proxy.js
CHANGED
|
@@ -4,6 +4,7 @@ import { resolve } from "node:path";
|
|
|
4
4
|
import { pathToFileURL } from "node:url";
|
|
5
5
|
import { Transform } from "node:stream";
|
|
6
6
|
import { pipeline } from "node:stream/promises";
|
|
7
|
+
import { performance } from "node:perf_hooks";
|
|
7
8
|
import WebSocket, { WebSocketServer } from "ws";
|
|
8
9
|
import { normalizePresetOptions, createPresetHooks } from "./proxy-presets.js";
|
|
9
10
|
|
|
@@ -121,7 +122,7 @@ export async function startProxy(options) {
|
|
|
121
122
|
response.end(error.statusCode === 413 ? "Request body too large\n" : "Proxy request failed\n");
|
|
122
123
|
}
|
|
123
124
|
|
|
124
|
-
async function relayResponse(incoming, response, request) {
|
|
125
|
+
async function relayResponse(incoming, response, request, onFailure = error => fail(response, error)) {
|
|
125
126
|
const context = { request, statusCode: incoming.statusCode, headers: { ...incoming.headers } };
|
|
126
127
|
try {
|
|
127
128
|
await hooks.onResponse?.(context);
|
|
@@ -161,32 +162,69 @@ export async function startProxy(options) {
|
|
|
161
162
|
await pipeline(incoming, response);
|
|
162
163
|
}
|
|
163
164
|
} catch (error) {
|
|
164
|
-
|
|
165
|
+
onFailure(error);
|
|
165
166
|
incoming.destroy();
|
|
166
167
|
}
|
|
167
168
|
}
|
|
168
169
|
|
|
169
170
|
const server = http.createServer(async (request, response) => {
|
|
171
|
+
const started = performance.now();
|
|
170
172
|
let upstream;
|
|
171
|
-
|
|
172
|
-
|
|
173
|
+
let context;
|
|
174
|
+
let finished = false;
|
|
175
|
+
let failed = false;
|
|
176
|
+
const timings = { state: "waiting" };
|
|
177
|
+
const elapsed = since => Math.round((performance.now() - since) * 10) / 10;
|
|
178
|
+
const publishTiming = () => {
|
|
179
|
+
// Optional recorder updater: never emit a second preset event or disrupt traffic.
|
|
180
|
+
try { context?.updateTiming?.(timings); } catch {}
|
|
181
|
+
};
|
|
182
|
+
const finishTiming = state => {
|
|
183
|
+
if (finished) return;
|
|
184
|
+
finished = true;
|
|
185
|
+
timings.state = state;
|
|
186
|
+
timings.totalMs = elapsed(started);
|
|
187
|
+
publishTiming();
|
|
188
|
+
};
|
|
189
|
+
const failRequest = error => { failed = true; fail(response, error); };
|
|
190
|
+
response.once("finish", () => finishTiming(failed ? "error" : "completed"));
|
|
191
|
+
response.once("close", () => {
|
|
192
|
+
finishTiming(failed ? "error" : "aborted");
|
|
193
|
+
upstream?.destroy();
|
|
194
|
+
});
|
|
195
|
+
request.on("error", error => { upstream?.destroy(); failRequest(error); });
|
|
173
196
|
try {
|
|
174
|
-
|
|
197
|
+
context = requestContext(request);
|
|
175
198
|
if (hooks.onRequest) {
|
|
176
199
|
context.body = await readBody(request, config.maxBodyBytes);
|
|
177
200
|
await hooks.onRequest(context);
|
|
178
201
|
context.body = bytes(context.body);
|
|
179
202
|
if (context.body.length > config.maxBodyBytes) throw Object.assign(new Error("Modified request body exceeds maxBodyBytes"), { statusCode: 413 });
|
|
180
203
|
}
|
|
204
|
+
// A disconnect may have happened while the preset was still processing.
|
|
205
|
+
publishTiming();
|
|
181
206
|
if (response.destroyed) return;
|
|
182
207
|
const headers = headersForHop(context.headers);
|
|
183
208
|
headers.host = target.host;
|
|
184
209
|
if (context.body !== undefined) headers["content-length"] = String(context.body.length);
|
|
185
210
|
else if (context.headers.trailer) headers.trailer = context.headers.trailer;
|
|
211
|
+
const sentAt = performance.now();
|
|
186
212
|
upstream = (target.protocol === "https:" ? https : http).request(target, {
|
|
187
213
|
method: context.method, path: upstreamPath(context.path), headers,
|
|
188
|
-
}, incoming => {
|
|
189
|
-
|
|
214
|
+
}, incoming => {
|
|
215
|
+
// Mark upstream truncation before pipeline destroys the downstream response.
|
|
216
|
+
incoming.once("aborted", () => { failed = true; });
|
|
217
|
+
incoming.once("error", () => { failed = true; });
|
|
218
|
+
if (!finished) {
|
|
219
|
+
// Header arrival is observable without consuming/buffering SSE body chunks.
|
|
220
|
+
timings.upstreamHeadersMs = elapsed(sentAt);
|
|
221
|
+
timings.statusCode = incoming.statusCode;
|
|
222
|
+
timings.state = "responding";
|
|
223
|
+
publishTiming();
|
|
224
|
+
}
|
|
225
|
+
void relayResponse(incoming, response, context, failRequest);
|
|
226
|
+
});
|
|
227
|
+
upstream.on("error", failRequest);
|
|
190
228
|
request.on("aborted", () => upstream.destroy());
|
|
191
229
|
if (context.body !== undefined) upstream.end(context.body);
|
|
192
230
|
else {
|
|
@@ -195,7 +233,8 @@ export async function startProxy(options) {
|
|
|
195
233
|
}
|
|
196
234
|
} catch (error) {
|
|
197
235
|
upstream?.destroy();
|
|
198
|
-
|
|
236
|
+
failRequest(error);
|
|
237
|
+
publishTiming();
|
|
199
238
|
}
|
|
200
239
|
});
|
|
201
240
|
// Long-lived SSE streams must not expire between model events.
|
package/src/tui.js
CHANGED
|
@@ -98,6 +98,11 @@ function age(timestamp, now) {
|
|
|
98
98
|
return `${Math.floor(seconds / 3600)}h`;
|
|
99
99
|
}
|
|
100
100
|
|
|
101
|
+
function duration(ms) {
|
|
102
|
+
if (!Number.isFinite(ms) || ms < 0) return "n/d";
|
|
103
|
+
return ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(1)}s`;
|
|
104
|
+
}
|
|
105
|
+
|
|
101
106
|
// Snapshot strings are data, never terminal escape sequences or extra rows.
|
|
102
107
|
function plain(value, fallback = "-") {
|
|
103
108
|
return stripAnsi(String(value ?? fallback)).replace(/[\x00-\x1f\x7f-\x9f]/g, " ");
|
|
@@ -350,7 +355,10 @@ export class Dashboard {
|
|
|
350
355
|
}
|
|
351
356
|
add([dim("elab/s: richieste elaborate dai preset, non tutto il traffico proxy")]);
|
|
352
357
|
add([dim("Risparmio: somma dei delta misurati per stadio; basi non sommabili")]);
|
|
353
|
-
add([dim("Errori preset != errori upstream;
|
|
358
|
+
add([dim("Errori preset != errori upstream; nessun conteggio globale delle richieste in corso")]);
|
|
359
|
+
add([dim("Tempi: proxy = preset; header = invio upstream -> header (non primo token)")]);
|
|
360
|
+
add([dim("Totale HTTP include upload, interceptor e streaming fino a fine invio/chiusura")]);
|
|
361
|
+
add([dim("WS: solo tempo preset; attesa esito non implica che la richiesta sia ancora attiva")]);
|
|
354
362
|
}
|
|
355
363
|
return lines.map(line => clip(line, width));
|
|
356
364
|
}
|
|
@@ -375,9 +383,25 @@ export class Dashboard {
|
|
|
375
383
|
const unmeasured = partial && stages.every(stage => !Number.isFinite(stage.saved));
|
|
376
384
|
const status = event.error ? red(bold("errore preset")) : event.changed === true ? green("modificata")
|
|
377
385
|
: event.changed === false ? dim("invariata") : dim("esito non disponibile");
|
|
386
|
+
const timing = event.timings;
|
|
387
|
+
const responseState = {
|
|
388
|
+
waiting: dim("attesa esito"), responding: cyan("risposta iniziata"),
|
|
389
|
+
error: red(event.error ? "non inoltrata" : "errore proxy/trasporto"), aborted: yellow("interrotta"),
|
|
390
|
+
}[timing?.state];
|
|
378
391
|
const lines = wrapCells([gray(time), cyan(plain(event.transport)), magenta(plain(event.model, "?")),
|
|
379
392
|
plain(event.preset), status,
|
|
380
393
|
...(event.error ? [] : [savedTokens(unmeasured ? null : event.saved) + (partial && !unmeasured ? yellow(" (parziale)") : "")]),
|
|
394
|
+
...(timing ? [
|
|
395
|
+
`proxy: ${duration(timing.presetMs)}`,
|
|
396
|
+
...(event.transport === "HTTP" ? [
|
|
397
|
+
`header: ${duration(timing.upstreamHeadersMs)}`, `tot: ${duration(timing.totalMs)}`,
|
|
398
|
+
...(Number.isInteger(timing.statusCode) && timing.statusCode >= 100 && timing.statusCode <= 599
|
|
399
|
+
? [timing.statusCode >= 400 ? red(`HTTP ${timing.statusCode}`) : `HTTP ${timing.statusCode}`] : []),
|
|
400
|
+
...(responseState ? [responseState] : []),
|
|
401
|
+
] : [dim("risposta WS: n/d")]),
|
|
402
|
+
] : [dim("tempi: n/d")]),
|
|
403
|
+
...(event.project ? [`progetto: ${plain(event.project)}`] : []),
|
|
404
|
+
...(event.sessionId || event.threadId ? [`sessione: ${plain(event.sessionId || event.threadId)}`] : []),
|
|
381
405
|
...(!this.showPipelineDetails ? stages.map(s => dim(`${plain(s.name)}: ${plain(s.reason)}`)) : []),
|
|
382
406
|
], width, " ");
|
|
383
407
|
if (this.showPipelineDetails) {
|
package/src/utils/format.js
CHANGED
|
@@ -158,3 +158,22 @@ export function printBanner() {
|
|
|
158
158
|
);
|
|
159
159
|
}
|
|
160
160
|
|
|
161
|
+
export function printStartBanner(ids) {
|
|
162
|
+
printBanner();
|
|
163
|
+
console.log(cyan(`Starting service(s): ${ids.join(", ")}...\n`));
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export async function printServiceStart(id, start) {
|
|
167
|
+
process.stdout.write(` Launching ${bold(id)}... `);
|
|
168
|
+
try {
|
|
169
|
+
const result = await start();
|
|
170
|
+
if (!result.success) console.log(red(`failed: ${result.message}`));
|
|
171
|
+
else if (result.alreadyRunning) console.log(yellow(`already running (PID: ${result.pid})`));
|
|
172
|
+
else console.log(green(`started (PID: ${result.pid})`));
|
|
173
|
+
return result;
|
|
174
|
+
} catch (error) {
|
|
175
|
+
console.log(red(`failed: ${error.message}`));
|
|
176
|
+
throw error;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
package/src/utils/process.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
|
-
import { openSync, appendFileSync } from "node:fs";
|
|
2
|
+
import { openSync, appendFileSync, closeSync } from "node:fs";
|
|
3
3
|
import { ensureDir, getLogsDir } from "./path.js";
|
|
4
4
|
|
|
5
5
|
/**
|
|
@@ -221,14 +221,20 @@ export function spawnDetachedProcess(command, logFilePath, options) {
|
|
|
221
221
|
|
|
222
222
|
const fd = openSync(logFilePath, "a");
|
|
223
223
|
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
224
|
+
let proc;
|
|
225
|
+
try {
|
|
226
|
+
proc = spawn(command, [], {
|
|
227
|
+
shell: true,
|
|
228
|
+
detached: true,
|
|
229
|
+
stdio: ["ignore", fd, fd],
|
|
230
|
+
env: { ...process.env, ...options?.env },
|
|
231
|
+
cwd: options?.cwd,
|
|
232
|
+
windowsHide: true,
|
|
233
|
+
});
|
|
234
|
+
} finally {
|
|
235
|
+
// The child owns its inherited handles; the parent must not keep the log open.
|
|
236
|
+
closeSync(fd);
|
|
237
|
+
}
|
|
232
238
|
|
|
233
239
|
proc.unref();
|
|
234
240
|
|