@drakonkat/ai-helper 1.1.0 → 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/ARCHITECTURE.md +14 -3
- package/CHANGELOG.md +15 -0
- package/README.md +417 -24
- package/docs/benchmark.md +273 -0
- package/package.json +17 -5
- package/scripts/bench-proxy.js +107 -0
- package/scripts/build.js +16 -0
- package/src/benchmark/fixtures.js +150 -0
- package/src/benchmark/live.js +78 -0
- package/src/benchmark/measurement.js +180 -0
- package/src/benchmark/quality.js +144 -0
- package/src/benchmark/report.js +141 -0
- package/src/benchmark/runner.js +269 -0
- package/src/codex-config.js +247 -0
- package/src/codex-routing.js +132 -0
- package/src/config.js +11 -1
- package/src/index.js +112 -22
- package/src/manager.js +126 -13
- package/src/proxy-interceptor.example.mjs +33 -0
- package/src/proxy-presets.js +226 -0
- package/src/proxy-stats.js +64 -0
- package/src/proxy-worker.js +17 -0
- package/src/proxy.js +313 -0
- package/src/tui.js +694 -0
- package/src/update.js +41 -0
- package/src/utils/metrics.js +315 -0
- package/src/utils/process.js +120 -140
- package/src/utils/versions.js +171 -0
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 =
|
|
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();
|
|
@@ -24,11 +27,14 @@ function printHelp() {
|
|
|
24
27
|
|
|
25
28
|
${bold("COMMANDS:")}
|
|
26
29
|
${yellow("status")}, ${yellow("ps")} Show status, PID, uptime, and web dashboard URLs
|
|
30
|
+
${yellow("status -ui")} Interactive live dashboard: manage services and watch the AI pipeline
|
|
27
31
|
${yellow("open")}, ${yellow("dash")} [services...] Open web dashboard(s) directly in your default browser
|
|
28
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)
|
|
29
34
|
${yellow("stop")}, ${yellow("down")} [services...] Stop all or specified services
|
|
30
35
|
${yellow("restart")} [services...] Restart all or specified services
|
|
31
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
|
|
32
38
|
${yellow("install")} Build standalone binary to ~/.local/bin and verify PATH
|
|
33
39
|
${yellow("version")}, ${yellow("-v")} Show version information
|
|
34
40
|
${yellow("help")}, ${yellow("-h")} Show this help message
|
|
@@ -43,6 +49,19 @@ ${bold("OPTIONS:")}
|
|
|
43
49
|
${gray("-n, --lines <num>")} Number of log lines to show (default: 50)
|
|
44
50
|
${gray("-f, --follow")} Follow log output in real-time
|
|
45
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)
|
|
60
|
+
${gray("-ui, --ui")} Open the interactive dashboard (status only, requires a TTY)
|
|
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.
|
|
46
65
|
|
|
47
66
|
${bold("EXAMPLES:")}
|
|
48
67
|
${dim("$")} ${cyan("npx ai-helper")} status
|
|
@@ -60,6 +79,11 @@ function printVersion() {
|
|
|
60
79
|
console.log(`${bold(cyan(CLI_NAME))} version ${bold(VERSION)} (${runtime}, ${process.platform}-${process.arch})`);
|
|
61
80
|
}
|
|
62
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
|
+
|
|
63
87
|
async function runInstall() {
|
|
64
88
|
printBanner();
|
|
65
89
|
console.log(cyan("⚙ Building standalone binary and installing to ~/.local/bin...\n"));
|
|
@@ -79,14 +103,7 @@ async function runInstall() {
|
|
|
79
103
|
|
|
80
104
|
try {
|
|
81
105
|
const buildProc = Bun.spawn(
|
|
82
|
-
[
|
|
83
|
-
process.execPath,
|
|
84
|
-
"build",
|
|
85
|
-
"--compile",
|
|
86
|
-
"--minify",
|
|
87
|
-
`--outfile=${tempBuildPath}`,
|
|
88
|
-
join(import.meta.dir, "index.js"),
|
|
89
|
-
],
|
|
106
|
+
[process.execPath, join(import.meta.dir, "../scripts/build.js"), tempBuildPath],
|
|
90
107
|
{ stdout: "pipe", stderr: "pipe" }
|
|
91
108
|
);
|
|
92
109
|
|
|
@@ -132,8 +149,38 @@ async function runInstall() {
|
|
|
132
149
|
export async function main() {
|
|
133
150
|
const rawArgs = process.argv.slice(2);
|
|
134
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
|
+
|
|
135
180
|
let jsonOutput = false;
|
|
136
181
|
let follow = false;
|
|
182
|
+
let uiMode = false;
|
|
183
|
+
let repoMode = false;
|
|
137
184
|
let lines = 50;
|
|
138
185
|
const positionalArgs = [];
|
|
139
186
|
|
|
@@ -141,6 +188,10 @@ export async function main() {
|
|
|
141
188
|
const arg = rawArgs[i];
|
|
142
189
|
if (arg === "--json") {
|
|
143
190
|
jsonOutput = true;
|
|
191
|
+
} else if (arg === "--repo") {
|
|
192
|
+
repoMode = true;
|
|
193
|
+
} else if (arg === "-ui" || arg === "--ui") {
|
|
194
|
+
uiMode = true;
|
|
144
195
|
} else if (arg === "-f" || arg === "--follow") {
|
|
145
196
|
follow = true;
|
|
146
197
|
} else if (arg === "-n" || arg === "--lines") {
|
|
@@ -168,10 +219,32 @@ export async function main() {
|
|
|
168
219
|
const targets = positionalArgs.slice(1);
|
|
169
220
|
|
|
170
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
|
+
}
|
|
171
236
|
case "status":
|
|
172
237
|
case "ps":
|
|
173
238
|
case "ls":
|
|
174
239
|
case "list": {
|
|
240
|
+
// Interactive mode needs a real terminal: piping or redirecting falls
|
|
241
|
+
// back to the plain table so scripts keep working.
|
|
242
|
+
if (uiMode && !jsonOutput && process.stdout.isTTY && process.stdin.isTTY) {
|
|
243
|
+
const { runDashboard } = await import("./tui.js");
|
|
244
|
+
await runDashboard();
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
|
|
175
248
|
const statuses = await manager.getStatus(targets.length > 0 ? targets : undefined);
|
|
176
249
|
|
|
177
250
|
if (jsonOutput) {
|
|
@@ -186,7 +259,8 @@ export async function main() {
|
|
|
186
259
|
"STATUS",
|
|
187
260
|
{ header: "PID", align: "right" },
|
|
188
261
|
{ header: "UPTIME", align: "right" },
|
|
189
|
-
"
|
|
262
|
+
"ADDRESS",
|
|
263
|
+
"REPO",
|
|
190
264
|
"COMMAND",
|
|
191
265
|
];
|
|
192
266
|
|
|
@@ -195,9 +269,10 @@ export async function main() {
|
|
|
195
269
|
badgeStatus(s.status),
|
|
196
270
|
s.pid ? String(s.pid) : dim("-"),
|
|
197
271
|
s.status === "running" ? s.uptime : dim("-"),
|
|
198
|
-
s.status === "running" && s.url && s.url !== "-"
|
|
272
|
+
s.id === "proxy" ? dim(`${s.url} (proxy)`) : s.status === "running" && s.url && s.url !== "-"
|
|
199
273
|
? cyan(underline(s.url))
|
|
200
274
|
: dim(s.url || "-"),
|
|
275
|
+
s.repositoryUrl ? cyan(underline(s.repositoryUrl)) : dim("-"),
|
|
201
276
|
dim(s.command),
|
|
202
277
|
]);
|
|
203
278
|
|
|
@@ -212,6 +287,12 @@ export async function main() {
|
|
|
212
287
|
case "dash": {
|
|
213
288
|
printBanner();
|
|
214
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
|
+
}
|
|
215
296
|
const opened = await manager.openDashboard(svcsToOpen);
|
|
216
297
|
|
|
217
298
|
if (opened.length === 0) {
|
|
@@ -230,13 +311,17 @@ export async function main() {
|
|
|
230
311
|
|
|
231
312
|
case "start":
|
|
232
313
|
case "up": {
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
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 = [];
|
|
236
319
|
|
|
237
320
|
for (const id of svcsToStart) {
|
|
238
|
-
process.stdout.write(` Launching ${bold(id)}... `);
|
|
321
|
+
if (!jsonOutput) process.stdout.write(` Launching ${bold(id)}... `);
|
|
239
322
|
const res = await manager.startService(id);
|
|
323
|
+
results.push({ id, ...res });
|
|
324
|
+
if (jsonOutput) continue;
|
|
240
325
|
if (res.success) {
|
|
241
326
|
if (res.alreadyRunning) {
|
|
242
327
|
console.log(yellow(`already running (PID: ${res.pid})`));
|
|
@@ -246,15 +331,16 @@ export async function main() {
|
|
|
246
331
|
} else {
|
|
247
332
|
console.log(red(`failed: ${res.message}`));
|
|
248
333
|
}
|
|
334
|
+
printCodexConfig(res);
|
|
249
335
|
}
|
|
250
|
-
console.log("");
|
|
336
|
+
console.log(jsonOutput ? JSON.stringify(results, null, 2) : "");
|
|
251
337
|
break;
|
|
252
338
|
}
|
|
253
339
|
|
|
254
340
|
case "stop":
|
|
255
341
|
case "down": {
|
|
256
342
|
printBanner();
|
|
257
|
-
const svcsToStop = targets.length > 0 ? targets :
|
|
343
|
+
const svcsToStop = targets.length > 0 ? targets : Object.keys(manager.readState().services);
|
|
258
344
|
console.log(cyan(`Stopping service(s): ${svcsToStop.join(", ")}...\n`));
|
|
259
345
|
|
|
260
346
|
for (const id of svcsToStop) {
|
|
@@ -271,20 +357,24 @@ export async function main() {
|
|
|
271
357
|
}
|
|
272
358
|
|
|
273
359
|
case "restart": {
|
|
274
|
-
printBanner();
|
|
275
|
-
const svcsToRestart = targets.length > 0 ? targets :
|
|
276
|
-
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 = [];
|
|
277
364
|
|
|
278
365
|
for (const id of svcsToRestart) {
|
|
279
|
-
process.stdout.write(` Restarting ${bold(id)}... `);
|
|
366
|
+
if (!jsonOutput) process.stdout.write(` Restarting ${bold(id)}... `);
|
|
280
367
|
const res = await manager.restartService(id);
|
|
368
|
+
results.push({ id, ...res });
|
|
369
|
+
if (jsonOutput) continue;
|
|
281
370
|
if (res.success) {
|
|
282
371
|
console.log(green(`started (PID: ${res.pid})`));
|
|
283
372
|
} else {
|
|
284
373
|
console.log(red(`failed: ${res.message}`));
|
|
285
374
|
}
|
|
375
|
+
printCodexConfig(res);
|
|
286
376
|
}
|
|
287
|
-
console.log("");
|
|
377
|
+
console.log(jsonOutput ? JSON.stringify(results, null, 2) : "");
|
|
288
378
|
break;
|
|
289
379
|
}
|
|
290
380
|
|
|
@@ -298,7 +388,7 @@ export async function main() {
|
|
|
298
388
|
process.exit(1);
|
|
299
389
|
}
|
|
300
390
|
|
|
301
|
-
if (!SERVICE_IDS.includes(targetService)) {
|
|
391
|
+
if (!SERVICE_IDS.includes(targetService) && targetService !== "proxy") {
|
|
302
392
|
console.log(yellow(`⚠ Warning: '${targetService}' is not a standard service. Looking for log file anyway...`));
|
|
303
393
|
}
|
|
304
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 {
|
|
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
|
|
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 :
|
|
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.
|
|
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 :
|
|
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 :
|
|
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
|
-
|
|
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 :
|
|
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
|
+
}
|