@drakonkat/ai-helper 1.2.8 → 1.2.9

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 CHANGED
@@ -4,6 +4,14 @@ All notable changes to **`ai-helper` (`aih`)** are documented in this file.
4
4
 
5
5
  ---
6
6
 
7
+ ## [1.2.9] - 2026-09-29
8
+
9
+ ### Added
10
+ - 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.
11
+ - Include the Windows Astra launcher from main alongside the native proxy commands, and workstation restore scripts in the repository.
12
+
13
+ ---
14
+
7
15
  ## [1.2.8] - 2026-09-24
8
16
 
9
17
  ### Added
package/README.md CHANGED
@@ -189,7 +189,15 @@ 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. Press **`d`** for source/configuration details and per-stage
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
+ Press **`d`** for source/configuration details and per-stage
193
201
  before/after token counts, percentages and measurement methods. Unknown savings
194
202
  remain unknown; partial estimates and token increases are explicitly marked.
195
203
  The panels do not infer provider cache savings, costs, upstream latency or
@@ -332,6 +340,37 @@ the installed/latest versions and the update command to stderr. The check times
332
340
  out after 1.5 seconds; network errors never prevent startup. Updates are not
333
341
  installed automatically. Compiled executables must be rebuilt to update them.
334
342
 
343
+ ### Astra / `--gpt` (Windows)
344
+
345
+ ```powershell
346
+ aih start --gpt
347
+ aih start --gpt --json
348
+ ```
349
+
350
+ 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.
351
+
352
+ 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.
353
+
354
+ The startup uses the same banner, colors and per-process output as plain `aih start`, including the actual listening PID:
355
+
356
+ ```text
357
+ Starting service(s): ocx, pxpipe, headroom...
358
+
359
+ Launching ocx... already running (PID: 1100)
360
+ Launching pxpipe... started (PID: 2200)
361
+ Launching headroom... started (PID: 3300)
362
+ ```
363
+
364
+ 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.
365
+
366
+ 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`.
367
+
368
+ 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.
369
+
370
+ 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.
371
+
372
+ 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.
373
+
335
374
  ---
336
375
 
337
376
  ### 4. Stop Services
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drakonkat/ai-helper",
3
- "version": "1.2.8",
3
+ "version": "1.2.9",
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 => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&apos;" })[char]);
140
+ }
141
+
142
+ function unxml(text) {
143
+ return text.replace(/&(?:amp|lt|gt|quot|apos);/g, entity => ({ "&amp;": "&", "&lt;": "<", "&gt;": ">", "&quot;": '"', "&apos;": "'" })[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("-"))) {
@@ -142,7 +142,16 @@ export async function createPresetHooks(config, onStats = () => {}) {
142
142
  // Observability must never interrupt proxy traffic; no request bodies are passed to the recorder.
143
143
  // Optional correlation only; never pass headers or bodies to the recorder.
144
144
  const requestId = typeof context.headers?.["x-request-id"] === "string" ? context.headers["x-request-id"].slice(0, 128) : undefined;
145
- try { onStats({ model, preset: config.preset, transport: websocket ? "WS" : "HTTP", changed, stages, error, ...(requestId ? { requestId } : {}) }); } catch {}
145
+ let source = {};
146
+ try {
147
+ const metadata = JSON.parse(context.headers?.["x-codex-turn-metadata"] || "{}");
148
+ const remotes = Object.values(metadata.workspaces || {}).flatMap(workspace => Object.values(workspace?.associated_remote_urls || {}));
149
+ const project = remotes.filter(value => typeof value === "string").map(value => value.replace(/^[^@/]+@[^:/]+:/, "")
150
+ .replace(/^[a-z]+:\/\/[^/]+/i, "").split(/[?#]/)[0].replace(/\.git$/i, "").split("/").filter(Boolean).slice(-2).join("/")).find(Boolean);
151
+ source = Object.fromEntries(Object.entries({ sessionId: metadata.session_id, threadId: metadata.thread_id, project })
152
+ .filter(([, value]) => typeof value === "string" && value.length).map(([key, value]) => [key, value.slice(0, 128)]));
153
+ } catch {}
154
+ try { onStats({ model, preset: config.preset, transport: websocket ? "WS" : "HTTP", changed, stages, error, ...source, ...(requestId ? { requestId } : {}) }); } catch {}
146
155
  };
147
156
  try {
148
157
  // Fixed stage order, including the triple recipe: RTK -> Headroom -> pxpipe.
@@ -40,7 +40,8 @@ export function createProxyStatsRecorder(file = getProxyStatsPath()) {
40
40
  stats.estimatedSavedTokens += saved;
41
41
  const model = String(event.model).replace(/[\r\n]/g, " ").slice(0, 128);
42
42
  stats.recent.push({ at: stats.updatedAt, model, preset: event.preset, transport: event.transport,
43
- changed: event.changed, error: Boolean(event.error), saved: event.error ? null : saved, stages });
43
+ changed: event.changed, error: Boolean(event.error), saved: event.error ? null : saved,
44
+ sessionId: event.sessionId, threadId: event.threadId, project: event.project, stages });
44
45
  stats.recent = stats.recent.slice(-20);
45
46
  mkdirSync(dirname(file), { recursive: true });
46
47
  const temporary = `${file}.${process.pid}.tmp`;
package/src/tui.js CHANGED
@@ -378,6 +378,8 @@ export class Dashboard {
378
378
  const lines = wrapCells([gray(time), cyan(plain(event.transport)), magenta(plain(event.model, "?")),
379
379
  plain(event.preset), status,
380
380
  ...(event.error ? [] : [savedTokens(unmeasured ? null : event.saved) + (partial && !unmeasured ? yellow(" (parziale)") : "")]),
381
+ ...(event.project ? [`progetto: ${plain(event.project)}`] : []),
382
+ ...(event.sessionId || event.threadId ? [`sessione: ${plain(event.sessionId || event.threadId)}`] : []),
381
383
  ...(!this.showPipelineDetails ? stages.map(s => dim(`${plain(s.name)}: ${plain(s.reason)}`)) : []),
382
384
  ], width, " ");
383
385
  if (this.showPipelineDetails) {
@@ -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
+