@drakonkat/ai-helper 1.1.1 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/config.js CHANGED
@@ -1,5 +1,9 @@
1
1
  import { homedir } from "node:os";
2
2
  import { join } from "node:path";
3
+ // Node 18 uses assert; newer Node uses with. Bun embeds this JSON when compiling.
4
+ const { default: packageInfo } = await import("../package.json", {
5
+ with: { type: "json" }, assert: { type: "json" },
6
+ });
3
7
 
4
8
  /**
5
9
  * Pre-configured AI ecosystem services managed by aih
@@ -9,6 +13,7 @@ export const SERVICES = {
9
13
  id: "pxpipe",
10
14
  name: "pxpipe",
11
15
  command: "npx pxpipe-proxy",
16
+ repositoryUrl: "https://github.com/teamchong/pxpipe",
12
17
  description: "AI LLM / MCP reverse proxy bridge (pxpipe-proxy)",
13
18
  defaultPort: 47821,
14
19
  defaultUrl: "http://localhost:47821",
@@ -19,6 +24,7 @@ export const SERVICES = {
19
24
  name: "ocx",
20
25
  command: "ocx start",
21
26
  stopCommand: "ocx stop",
27
+ repositoryUrl: "https://github.com/lidge-jun/opencodex",
22
28
  description: "OpenCode Interpreter daemon service (ocx start)",
23
29
  defaultPort: 10100,
24
30
  defaultUrl: "http://localhost:10100",
@@ -29,6 +35,7 @@ export const SERVICES = {
29
35
  name: "agentmemory",
30
36
  command: "npx @agentmemory/agentmemory",
31
37
  stopCommand: "npx @agentmemory/agentmemory stop --force",
38
+ repositoryUrl: "https://github.com/rohitg00/agentmemory",
32
39
  description: "Long-term persistent agent memory service (@agentmemory/agentmemory)",
33
40
  defaultPort: 3113,
34
41
  defaultUrl: "http://localhost:3113",
@@ -38,6 +45,7 @@ export const SERVICES = {
38
45
  id: "headroom",
39
46
  name: "headroom",
40
47
  command: "headroom proxy",
48
+ repositoryUrl: "https://github.com/headroomlabs-ai/headroom",
41
49
  description: "Context optimization & LLM proxy (headroom proxy)",
42
50
  defaultPort: 8787,
43
51
  defaultUrl: "http://localhost:8787/dashboard",
@@ -49,4 +57,6 @@ export const SERVICE_IDS = Object.keys(SERVICES);
49
57
 
50
58
  export const APP_NAME = "ai-helper";
51
59
  export const CLI_NAME = "aih";
52
- export const VERSION = "1.1.0";
60
+ export const VERSION = packageInfo.version;
61
+ export const PACKAGE_NAME = packageInfo.name;
62
+ export const APP_REPOSITORY_URL = packageInfo.repository.url.replace(/^git\+/, "").replace(/\.git$/, "");
package/src/index.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { APP_NAME, CLI_NAME, SERVICES, SERVICE_IDS, VERSION } from "./config.js";
2
2
  import { manager } from "./manager.js";
3
+ import { checkForUpdates } from "./update.js";
4
+ import { readProxyStats, proxyStatsLines } from "./proxy-stats.js";
3
5
  import {
4
6
  badgeStatus,
5
7
  bold,
@@ -16,6 +18,7 @@ import {
16
18
  import { isLocalBinInPath, getAddToPathInstructions, getLocalBinDir, ensureDir } from "./utils/path.js";
17
19
  import { join } from "node:path";
18
20
  import { copyFileSync } from "node:fs";
21
+ import { parseArgs } from "node:util";
19
22
 
20
23
  function printHelp() {
21
24
  printBanner();
@@ -27,9 +30,11 @@ ${bold("COMMANDS:")}
27
30
  ${yellow("status -ui")} Interactive live dashboard: manage services and watch the AI pipeline
28
31
  ${yellow("open")}, ${yellow("dash")} [services...] Open web dashboard(s) directly in your default browser
29
32
  ${yellow("start")}, ${yellow("up")} [services...] Start all or specified services (pxpipe, ocx, agentmemory, headroom)
33
+ ${yellow("start proxy")} <upstream> Start HTTP/SSE/WebSocket proxy (default: 127.0.0.1:10101)
30
34
  ${yellow("stop")}, ${yellow("down")} [services...] Stop all or specified services
31
35
  ${yellow("restart")} [services...] Restart all or specified services
32
36
  ${yellow("logs")} <service> [-n 50] [-f] View or stream live logs for a service
37
+ ${yellow("stats proxy")} [--json] Show proxy token savings estimates and recent requests
33
38
  ${yellow("install")} Build standalone binary to ~/.local/bin and verify PATH
34
39
  ${yellow("version")}, ${yellow("-v")} Show version information
35
40
  ${yellow("help")}, ${yellow("-h")} Show this help message
@@ -44,8 +49,20 @@ ${bold("OPTIONS:")}
44
49
  ${gray("-n, --lines <num>")} Number of log lines to show (default: 50)
45
50
  ${gray("-f, --follow")} Follow log output in real-time
46
51
  ${gray("--json")} Output results in JSON format
52
+ ${gray("--repo")} Open GitHub repositories instead of dashboards (open only)
53
+ ${gray("--listen <http://host:port>")} Proxy loopback listening address
54
+ ${gray("--interceptor <file.mjs>")} Proxy JavaScript hooks (loaded at startup)
55
+ ${gray("--preset <name>")} pxpipe | headroom | rtk | headroom-pxpipe | rtk-pxpipe | none
56
+ ${gray("--models <list>")} pxpipe model allowlist, comma-separated (trailing * supported)
57
+ ${gray("--headroom-url <url>")} Headroom service (default: http://127.0.0.1:8787)
58
+ ${gray("--rtk-filter <name>")} Fixed rtk pipe filter (default: auto-detect)
59
+ ${gray("--max-body-bytes <num>")} Proxy buffered request / WebSocket limit (default: 67108864)
47
60
  ${gray("-ui, --ui")} Open the interactive dashboard (status only, requires a TTY)
48
61
 
62
+ ${bold("CODEX CONFIGURATION:")}
63
+ Starting aih's proxy, or ocx with an active proxy, updates Codex's two base URLs.
64
+ Respects CODEX_HOME; set AIH_CODEX_AUTOCONFIG=0 to leave config.toml untouched.
65
+
49
66
  ${bold("EXAMPLES:")}
50
67
  ${dim("$")} ${cyan("npx ai-helper")} status
51
68
  ${dim("$")} ${cyan(CLI_NAME)} open ${dim("# Opens all running dashboards in browser")}
@@ -62,6 +79,11 @@ function printVersion() {
62
79
  console.log(`${bold(cyan(CLI_NAME))} version ${bold(VERSION)} (${runtime}, ${process.platform}-${process.arch})`);
63
80
  }
64
81
 
82
+ function printCodexConfig(result) {
83
+ const config = result.codexConfig;
84
+ if (config?.message) console.log((config.status === "warning" ? yellow : dim)(` ${config.message}`));
85
+ }
86
+
65
87
  async function runInstall() {
66
88
  printBanner();
67
89
  console.log(cyan("⚙ Building standalone binary and installing to ~/.local/bin...\n"));
@@ -81,14 +103,7 @@ async function runInstall() {
81
103
 
82
104
  try {
83
105
  const buildProc = Bun.spawn(
84
- [
85
- process.execPath,
86
- "build",
87
- "--compile",
88
- "--minify",
89
- `--outfile=${tempBuildPath}`,
90
- join(import.meta.dir, "index.js"),
91
- ],
106
+ [process.execPath, join(import.meta.dir, "../scripts/build.js"), tempBuildPath],
92
107
  { stdout: "pipe", stderr: "pipe" }
93
108
  );
94
109
 
@@ -134,9 +149,38 @@ async function runInstall() {
134
149
  export async function main() {
135
150
  const rawArgs = process.argv.slice(2);
136
151
 
152
+ if (["start", "up", "restart"].includes(rawArgs[0]) && rawArgs[1] === "proxy" && !rawArgs.includes("--help") && !rawArgs.includes("-h")) {
153
+ const { values, positionals } = parseArgs({ args: rawArgs.slice(2), allowPositionals: true, options: {
154
+ listen: { type: "string" }, interceptor: { type: "string" },
155
+ preset: { type: "string" }, models: { type: "string" },
156
+ "headroom-url": { type: "string" }, "rtk-filter": { type: "string" },
157
+ "max-body-bytes": { type: "string" }, json: { type: "boolean" },
158
+ } });
159
+ if (positionals.length > 1) throw new Error("Expected one upstream URL");
160
+ const options = {};
161
+ if (positionals[0]) options.upstream = positionals[0];
162
+ if (values.listen !== undefined) options.listen = values.listen;
163
+ if (values.interceptor !== undefined) options.interceptor = values.interceptor;
164
+ for (const [flag, key] of Object.entries({ preset: "preset", models: "models", "headroom-url": "headroomUrl", "rtk-filter": "rtkFilter" })) {
165
+ if (values[flag] !== undefined) options[key] = values[flag];
166
+ }
167
+ if (values["max-body-bytes"] !== undefined) options.maxBodyBytes = values["max-body-bytes"];
168
+ if (rawArgs[0] !== "restart") await checkForUpdates();
169
+ const result = rawArgs[0] === "restart"
170
+ ? await manager.restartService("proxy", options)
171
+ : await manager.startService("proxy", options);
172
+ if (values.json) console.log(JSON.stringify(result));
173
+ else if (result.success) console.log(green(`Proxy ${result.alreadyRunning ? "already running" : "started"} (PID: ${result.pid}) at ${result.url}`));
174
+ else console.error(red(result.message));
175
+ if (!values.json) printCodexConfig(result);
176
+ if (!result.success) process.exitCode = 1;
177
+ return;
178
+ }
179
+
137
180
  let jsonOutput = false;
138
181
  let follow = false;
139
182
  let uiMode = false;
183
+ let repoMode = false;
140
184
  let lines = 50;
141
185
  const positionalArgs = [];
142
186
 
@@ -144,6 +188,8 @@ export async function main() {
144
188
  const arg = rawArgs[i];
145
189
  if (arg === "--json") {
146
190
  jsonOutput = true;
191
+ } else if (arg === "--repo") {
192
+ repoMode = true;
147
193
  } else if (arg === "-ui" || arg === "--ui") {
148
194
  uiMode = true;
149
195
  } else if (arg === "-f" || arg === "--follow") {
@@ -173,6 +219,20 @@ export async function main() {
173
219
  const targets = positionalArgs.slice(1);
174
220
 
175
221
  switch (command) {
222
+ case "stats": {
223
+ if (targets.length > 1 || (targets[0] && targets[0] !== "proxy")) throw new Error("Usage: aih stats proxy [--json]");
224
+ const stats = readProxyStats();
225
+ if (jsonOutput) console.log(JSON.stringify(stats, null, 2));
226
+ else {
227
+ console.log(proxyStatsLines(stats).join("\n"));
228
+ if (stats) console.log(` Dal ${stats.since} | aggiornato ${stats.updatedAt}`);
229
+ for (const event of stats?.recent.slice(-5) || []) {
230
+ console.log(` ${event.at} ${event.transport} ${event.model} ${event.preset}: ${event.error ? "errore" : `${event.saved} token stimati`}`);
231
+ for (const stage of event.stages) console.log(` ${stage.name}: ${stage.saved ?? "?"} (${stage.reason}, ${stage.method})`);
232
+ }
233
+ }
234
+ break;
235
+ }
176
236
  case "status":
177
237
  case "ps":
178
238
  case "ls":
@@ -199,7 +259,8 @@ export async function main() {
199
259
  "STATUS",
200
260
  { header: "PID", align: "right" },
201
261
  { header: "UPTIME", align: "right" },
202
- "DASHBOARD / URL",
262
+ "ADDRESS",
263
+ "REPO",
203
264
  "COMMAND",
204
265
  ];
205
266
 
@@ -208,9 +269,10 @@ export async function main() {
208
269
  badgeStatus(s.status),
209
270
  s.pid ? String(s.pid) : dim("-"),
210
271
  s.status === "running" ? s.uptime : dim("-"),
211
- s.status === "running" && s.url && s.url !== "-"
272
+ s.id === "proxy" ? dim(`${s.url} (proxy)`) : s.status === "running" && s.url && s.url !== "-"
212
273
  ? cyan(underline(s.url))
213
274
  : dim(s.url || "-"),
275
+ s.repositoryUrl ? cyan(underline(s.repositoryUrl)) : dim("-"),
214
276
  dim(s.command),
215
277
  ]);
216
278
 
@@ -225,6 +287,12 @@ export async function main() {
225
287
  case "dash": {
226
288
  printBanner();
227
289
  const svcsToOpen = targets.length > 0 ? targets : undefined;
290
+ if (repoMode) {
291
+ const opened = await manager.openRepository(svcsToOpen);
292
+ if (!opened.length) console.log(yellow("No GitHub repositories available to open."));
293
+ for (const item of opened) console.log(` ${bold(item.name)}: ${cyan(underline(item.url))}`);
294
+ break;
295
+ }
228
296
  const opened = await manager.openDashboard(svcsToOpen);
229
297
 
230
298
  if (opened.length === 0) {
@@ -243,13 +311,17 @@ export async function main() {
243
311
 
244
312
  case "start":
245
313
  case "up": {
246
- printBanner();
247
- const svcsToStart = targets.length > 0 ? targets : SERVICE_IDS;
248
- console.log(cyan(`Starting service(s): ${svcsToStart.join(", ")}...\n`));
314
+ await checkForUpdates();
315
+ if (!jsonOutput) printBanner();
316
+ const svcsToStart = targets.length > 0 ? targets : Object.keys(manager.readState().services);
317
+ if (!jsonOutput) console.log(cyan(`Starting service(s): ${svcsToStart.join(", ")}...\n`));
318
+ const results = [];
249
319
 
250
320
  for (const id of svcsToStart) {
251
- process.stdout.write(` Launching ${bold(id)}... `);
321
+ if (!jsonOutput) process.stdout.write(` Launching ${bold(id)}... `);
252
322
  const res = await manager.startService(id);
323
+ results.push({ id, ...res });
324
+ if (jsonOutput) continue;
253
325
  if (res.success) {
254
326
  if (res.alreadyRunning) {
255
327
  console.log(yellow(`already running (PID: ${res.pid})`));
@@ -259,15 +331,16 @@ export async function main() {
259
331
  } else {
260
332
  console.log(red(`failed: ${res.message}`));
261
333
  }
334
+ printCodexConfig(res);
262
335
  }
263
- console.log("");
336
+ console.log(jsonOutput ? JSON.stringify(results, null, 2) : "");
264
337
  break;
265
338
  }
266
339
 
267
340
  case "stop":
268
341
  case "down": {
269
342
  printBanner();
270
- const svcsToStop = targets.length > 0 ? targets : SERVICE_IDS;
343
+ const svcsToStop = targets.length > 0 ? targets : Object.keys(manager.readState().services);
271
344
  console.log(cyan(`Stopping service(s): ${svcsToStop.join(", ")}...\n`));
272
345
 
273
346
  for (const id of svcsToStop) {
@@ -284,20 +357,24 @@ export async function main() {
284
357
  }
285
358
 
286
359
  case "restart": {
287
- printBanner();
288
- const svcsToRestart = targets.length > 0 ? targets : SERVICE_IDS;
289
- console.log(cyan(`Restarting service(s): ${svcsToRestart.join(", ")}...\n`));
360
+ if (!jsonOutput) printBanner();
361
+ const svcsToRestart = targets.length > 0 ? targets : Object.keys(manager.readState().services);
362
+ if (!jsonOutput) console.log(cyan(`Restarting service(s): ${svcsToRestart.join(", ")}...\n`));
363
+ const results = [];
290
364
 
291
365
  for (const id of svcsToRestart) {
292
- process.stdout.write(` Restarting ${bold(id)}... `);
366
+ if (!jsonOutput) process.stdout.write(` Restarting ${bold(id)}... `);
293
367
  const res = await manager.restartService(id);
368
+ results.push({ id, ...res });
369
+ if (jsonOutput) continue;
294
370
  if (res.success) {
295
371
  console.log(green(`started (PID: ${res.pid})`));
296
372
  } else {
297
373
  console.log(red(`failed: ${res.message}`));
298
374
  }
375
+ printCodexConfig(res);
299
376
  }
300
- console.log("");
377
+ console.log(jsonOutput ? JSON.stringify(results, null, 2) : "");
301
378
  break;
302
379
  }
303
380
 
@@ -311,7 +388,7 @@ export async function main() {
311
388
  process.exit(1);
312
389
  }
313
390
 
314
- if (!SERVICE_IDS.includes(targetService)) {
391
+ if (!SERVICE_IDS.includes(targetService) && targetService !== "proxy") {
315
392
  console.log(yellow(`⚠ Warning: '${targetService}' is not a standard service. Looking for log file anyway...`));
316
393
  }
317
394
 
package/src/manager.js CHANGED
@@ -1,5 +1,10 @@
1
1
  import { existsSync, readFileSync, writeFileSync, statSync, openSync, readSync, closeSync } from "node:fs";
2
- import { SERVICES, SERVICE_IDS } from "./config.js";
2
+ import { execFileSync, spawn } from "node:child_process";
3
+ import { fileURLToPath } from "node:url";
4
+ import { join } from "node:path";
5
+ import { normalizeProxyOptions } from "./proxy.js";
6
+ import { SERVICES, SERVICE_IDS, APP_REPOSITORY_URL } from "./config.js";
7
+ import { configureCodexForProxy } from "./codex-routing.js";
3
8
  import { ensureDir, getAihDir, getLogsDir, getServiceLogPath, getStateFilePath } from "./utils/path.js";
4
9
  import {
5
10
  isPidRunning,
@@ -58,9 +63,9 @@ export class ServiceManager {
58
63
  let needsSave = false;
59
64
 
60
65
  // Discover active verified daemon processes from OS
61
- const discovered = await discoverRunningProcesses();
66
+ const discovered = await discoverRunningProcesses({ knownServices: state.services });
62
67
 
63
- for (const id of SERVICE_IDS) {
68
+ for (const id of Object.keys(state.services)) {
64
69
  const svc = state.services[id];
65
70
  const info = discovered[id];
66
71
 
@@ -140,7 +145,7 @@ export class ServiceManager {
140
145
  */
141
146
  async getStatus(targetServices) {
142
147
  const state = await this.syncState();
143
- const targets = targetServices && targetServices.length > 0 ? targetServices : SERVICE_IDS;
148
+ const targets = targetServices && targetServices.length > 0 ? targetServices : Object.keys(state.services);
144
149
 
145
150
  return targets.map(id => {
146
151
  const def = SERVICES[id] || {
@@ -173,6 +178,8 @@ export class ServiceManager {
173
178
  description: def.description,
174
179
  uptime: svcState.status === "running" ? formatUptime(svcState.startedAt) : "-",
175
180
  url,
181
+ dashboardUrl: id === "proxy" || url === "-" ? null : url,
182
+ repositoryUrl: id === "proxy" ? APP_REPOSITORY_URL : def.repositoryUrl || null,
176
183
  logPath,
177
184
  logSize,
178
185
  };
@@ -187,7 +194,7 @@ export class ServiceManager {
187
194
  const opened = [];
188
195
 
189
196
  for (const svc of statuses) {
190
- const url = svc.url || SERVICES[svc.id]?.defaultUrl;
197
+ const url = svc.dashboardUrl;
191
198
  if (url && url !== "-") {
192
199
  openBrowser(url);
193
200
  opened.push({ id: svc.id, name: svc.name, url, status: svc.status });
@@ -197,10 +204,33 @@ export class ServiceManager {
197
204
  return opened;
198
205
  }
199
206
 
207
+ /** Repository metadata is static; opening it does not require process discovery. */
208
+ async openRepository(targetServices) {
209
+ const targets = targetServices?.length ? targetServices : Object.keys(this.readState().services);
210
+ const opened = [];
211
+ for (const id of targets) {
212
+ const url = id === "proxy" ? APP_REPOSITORY_URL : SERVICES[id]?.repositoryUrl;
213
+ if (!url) continue;
214
+ openBrowser(url);
215
+ opened.push({ id, name: SERVICES[id]?.name || id, url });
216
+ }
217
+ return opened;
218
+ }
219
+
220
+ async configureCodexProxy(options = {}) {
221
+ try {
222
+ return await configureCodexForProxy(this.loadState(), { ...options, readState: () => this.loadState() });
223
+ } catch {
224
+ // Config I/O must not tear down a proxy that has already reported ready.
225
+ return { status: "warning", message: "Service started, but Codex configuration could not be updated safely." };
226
+ }
227
+ }
228
+
200
229
  /**
201
230
  * Starts a single service by ID.
202
231
  */
203
- async startService(serviceId) {
232
+ async startService(serviceId, options) {
233
+ if (serviceId === "proxy") return this.startProxyService(options);
204
234
  const def = SERVICES[serviceId];
205
235
  if (!def) {
206
236
  return { success: false, message: `Unknown service '${serviceId}'. Available: ${SERVICE_IDS.join(", ")}` };
@@ -216,6 +246,7 @@ export class ServiceManager {
216
246
  pid: current.pid,
217
247
  alreadyRunning: true,
218
248
  url: current.url || def.defaultUrl,
249
+ ...(serviceId === "ocx" ? { codexConfig: await this.configureCodexProxy({ waitForOcx: true }) } : {}),
219
250
  };
220
251
  }
221
252
 
@@ -256,14 +287,87 @@ export class ServiceManager {
256
287
  message: `Service '${serviceId}' started successfully (PID: ${updatedSvc.pid})`,
257
288
  pid: updatedSvc.pid,
258
289
  url: updatedSvc.url || def.defaultUrl,
290
+ ...(serviceId === "ocx" ? { codexConfig: await this.configureCodexProxy({ waitForOcx: true }) } : {}),
259
291
  };
260
292
  }
261
293
 
294
+ async startProxyService(options) {
295
+ const state = this.loadState();
296
+ const current = state.services.proxy;
297
+ const config = normalizeProxyOptions({ ...current?.proxyOptions, ...options });
298
+ if (current?.status === "running" && isPidRunning(current.pid)) {
299
+ if (JSON.stringify(config) !== JSON.stringify(current.proxyOptions)) {
300
+ throw new Error("Proxy is already running with different options; use 'aih restart proxy <upstream> [options]'");
301
+ }
302
+ return { success: true, alreadyRunning: true, pid: current.pid, url: current.url,
303
+ codexConfig: await this.configureCodexProxy() };
304
+ }
305
+ ensureDir(getLogsDir());
306
+ const compiled = typeof Bun !== "undefined" && /^(?:\/\$bunfs\/|[A-Z]:\/~BUN\/)/i.test(Bun.main);
307
+ let workerPath = fileURLToPath(new URL("./proxy-worker.js", import.meta.url));
308
+ if (compiled) {
309
+ if (typeof AIH_PROXY_WORKER_SOURCE === "undefined") throw new Error("Rebuild with 'bun run build' to include the proxy worker");
310
+ workerPath = join(getAihDir(), "proxy-worker.mjs");
311
+ writeFileSync(workerPath, AIH_PROXY_WORKER_SOURCE);
312
+ }
313
+ let nodeExecutable = process.execPath;
314
+ if (typeof Bun !== "undefined") {
315
+ // NVM shims can drop IPC handles and expose the launcher's PID. Spawn Node itself.
316
+ try {
317
+ nodeExecutable = execFileSync("node", ["-p", "process.execPath"], {
318
+ encoding: "utf8", windowsHide: true, timeout: 5000,
319
+ }).trim();
320
+ } catch (error) {
321
+ throw new Error(`Cannot resolve Node.js 20.19+ on PATH: ${error.message}`);
322
+ }
323
+ }
324
+ const fd = openSync(getServiceLogPath("proxy"), "a");
325
+ let child;
326
+ try {
327
+ // Bun's HTTP/ws shims omit handshake events and cancellation; always use Node.
328
+ child = spawn(nodeExecutable, [workerPath], {
329
+ detached: true, windowsHide: true, stdio: ["ignore", fd, fd, "ipc"],
330
+ env: { ...process.env, AIH_PROXY_OPTIONS: JSON.stringify(config) },
331
+ });
332
+ } finally { closeSync(fd); }
333
+ try {
334
+ const ready = await new Promise((resolveReady, reject) => {
335
+ const timeout = setTimeout(() => finish(new Error("Proxy startup timed out; check 'aih logs proxy'")), 15000);
336
+ const onError = error => finish(error.code === "ENOENT" ? new Error("Proxy requires Node.js 20.19+ on PATH") : error);
337
+ const onExit = code => finish(new Error(`Proxy exited during startup (${code}); check 'aih logs proxy'`));
338
+ const onMessage = message => {
339
+ if (message.error) finish(new Error(message.error));
340
+ else if (message.url) finish(null, message);
341
+ };
342
+ const finish = (error, result) => {
343
+ clearTimeout(timeout);
344
+ child.off("error", onError).off("exit", onExit).off("message", onMessage);
345
+ error ? reject(error) : resolveReady(result);
346
+ };
347
+ child.once("error", onError).once("exit", onExit).on("message", onMessage);
348
+ });
349
+ const updated = this.loadState();
350
+ updated.services.proxy = {
351
+ id: "proxy", name: "proxy", command: `aih start proxy ${config.upstream}`,
352
+ status: "running", pid: child.pid, startedAt: new Date().toISOString(),
353
+ url: ready.url, proxyOptions: config,
354
+ };
355
+ this.saveState(updated);
356
+ return { success: true, pid: child.pid, url: ready.url, codexConfig: await this.configureCodexProxy() };
357
+ } catch (error) {
358
+ if (child.pid) await killProcessTree(child.pid);
359
+ throw error;
360
+ } finally {
361
+ if (child.connected) child.disconnect();
362
+ child.unref();
363
+ }
364
+ }
365
+
262
366
  /**
263
367
  * Starts all or selected services.
264
368
  */
265
369
  async startServices(serviceIds) {
266
- const targets = serviceIds && serviceIds.length > 0 ? serviceIds : SERVICE_IDS;
370
+ const targets = serviceIds && serviceIds.length > 0 ? serviceIds : Object.keys(this.readState().services);
267
371
  const results = {};
268
372
 
269
373
  for (const id of targets) {
@@ -281,6 +385,8 @@ export class ServiceManager {
281
385
  const state = await this.syncState();
282
386
  const current = state.services[serviceId];
283
387
 
388
+ if (!current) return { success: false, message: `Unknown service '${serviceId}'` };
389
+
284
390
  // 1. If service has a dedicated graceful stopCommand, run it
285
391
  if (def?.stopCommand) {
286
392
  const isWin = process.platform === "win32";
@@ -294,7 +400,8 @@ export class ServiceManager {
294
400
 
295
401
  // 2. Kill recorded process tree if still active
296
402
  if (current && current.pid && isPidRunning(current.pid)) {
297
- await killProcessTree(current.pid);
403
+ const result = await killProcessTree(current.pid);
404
+ if (!result.success) return result;
298
405
  }
299
406
 
300
407
  // 3. Clean up any remaining processes holding the service's ports
@@ -323,7 +430,7 @@ export class ServiceManager {
323
430
  * Stops all or selected services.
324
431
  */
325
432
  async stopServices(serviceIds) {
326
- const targets = serviceIds && serviceIds.length > 0 ? serviceIds : SERVICE_IDS;
433
+ const targets = serviceIds && serviceIds.length > 0 ? serviceIds : Object.keys(this.readState().services);
327
434
  const results = {};
328
435
 
329
436
  for (const id of targets) {
@@ -336,17 +443,23 @@ export class ServiceManager {
336
443
  /**
337
444
  * Restarts a single service by ID.
338
445
  */
339
- async restartService(serviceId) {
340
- await this.stopService(serviceId);
446
+ async restartService(serviceId, options) {
447
+ if (serviceId === "proxy") {
448
+ const current = this.readState().services.proxy;
449
+ normalizeProxyOptions({ ...current?.proxyOptions, ...options });
450
+ if (!current) return this.startService(serviceId, options);
451
+ }
452
+ const stopped = await this.stopService(serviceId);
453
+ if (!stopped.success) return stopped;
341
454
  await sleep(600);
342
- return await this.startService(serviceId);
455
+ return await this.startService(serviceId, options);
343
456
  }
344
457
 
345
458
  /**
346
459
  * Restarts all or selected services.
347
460
  */
348
461
  async restartServices(serviceIds) {
349
- const targets = serviceIds && serviceIds.length > 0 ? serviceIds : SERVICE_IDS;
462
+ const targets = serviceIds && serviceIds.length > 0 ? serviceIds : Object.keys(this.readState().services);
350
463
  const results = {};
351
464
 
352
465
  for (const id of targets) {
@@ -0,0 +1,33 @@
1
+ // Copy this file, edit it and pass --interceptor /path/to/interceptor.mjs.
2
+ // Hooks may be async. Mutate context; return values are ignored.
3
+ export function onRequest(context) {
4
+ console.log(`[request] ${context.method} ${context.path}: ${context.body.length} bytes; type=${context.headers["content-type"] || "missing"}; encoding=${context.headers["content-encoding"] || "identity"}`);
5
+ // const json = JSON.parse(context.body.toString("utf8"));
6
+ // json.model = "another-model";
7
+ // context.body = JSON.stringify(json);
8
+ }
9
+
10
+ export function onResponse(context) {
11
+ console.log(`[response] ${context.request.path}: ${context.statusCode}`);
12
+ }
13
+
14
+ // Optional whole-body hook for non-SSE responses (buffers up to maxBodyBytes):
15
+ // export function onResponseBody(context) {
16
+ // console.log(context.body.toString("utf8"));
17
+ // }
18
+
19
+ export function onResponseChunk(context) {
20
+ // Raw bytes, possibly compressed. A chunk is NOT necessarily a full SSE event,
21
+ // JSON document or UTF-8 character. Keep incremental decoding/parsing state on
22
+ // context.request if needed; never assume chunk boundaries are message boundaries.
23
+ console.log(`[response chunk] ${context.request.path}: ${context.body.length} bytes`);
24
+ }
25
+
26
+ export function onWebSocketMessage(context) {
27
+ console.log(`[ws ${context.direction}] ${context.body.length} bytes, binary=${context.isBinary}`);
28
+ // Text messages are complete, unlike HTTP response chunks:
29
+ // if (!context.isBinary) {
30
+ // const json = JSON.parse(context.body.toString("utf8"));
31
+ // context.body = JSON.stringify(json);
32
+ // }
33
+ }