@drakonkat/ai-helper 1.1.1 → 1.2.3

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/manager.js CHANGED
@@ -1,5 +1,12 @@
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, SERVICE_PACKAGES, APP_REPOSITORY_URL } from "./config.js";
7
+ import { compareVersions, getServiceVersions } from "./utils/versions.js";
8
+ import { installServiceUpdate, serviceStartCommand } from "./service-updates.js";
9
+ import { configureCodexForProxy } from "./codex-routing.js";
3
10
  import { ensureDir, getAihDir, getLogsDir, getServiceLogPath, getStateFilePath } from "./utils/path.js";
4
11
  import {
5
12
  isPidRunning,
@@ -14,6 +21,107 @@ import {
14
21
  import { formatBytes, formatUptime, gray, red, yellow, green, cyan } from "./utils/format.js";
15
22
 
16
23
  export class ServiceManager {
24
+ updatesInProgress = new Set();
25
+
26
+ /** Explicit update: fresh check, stop if needed, install, verify, restore runtime state. */
27
+ async updateService(serviceId, { getVersions = getServiceVersions, install = installServiceUpdate } = {}) {
28
+ if (!Object.hasOwn(SERVICE_PACKAGES, serviceId)) {
29
+ return { success: false, message: serviceId === "proxy"
30
+ ? "The built-in proxy is part of ai-helper; update ai-helper itself to update it."
31
+ : `Unknown service '${serviceId}'. Available: ${SERVICE_IDS.join(", ")}` };
32
+ }
33
+ if (this.updatesInProgress.has(serviceId)) {
34
+ return { success: false, message: `An update for '${serviceId}' is already in progress` };
35
+ }
36
+ this.updatesInProgress.add(serviceId);
37
+ let stopped = false;
38
+ let updated = false;
39
+ let details = {};
40
+ const restart = async () => {
41
+ try { return await this.startService(serviceId); }
42
+ catch (error) { return { success: false, message: error.message }; }
43
+ };
44
+ const rememberLaunchVersion = version => {
45
+ if (!SERVICE_PACKAGES[serviceId].npx) return;
46
+ const state = this.readState();
47
+ const current = state.services[serviceId];
48
+ if (current.launchVersion === version) return;
49
+ current.launchVersion = version;
50
+ current.command = serviceStartCommand(serviceId, current);
51
+ this.saveState(state);
52
+ };
53
+ try {
54
+ const state = await this.syncState();
55
+ const current = state.services[serviceId] || { id: serviceId, status: "stopped" };
56
+ const before = (await getVersions([current]))[serviceId];
57
+ const latestVersion = before?.latestVersion;
58
+ details = { previousVersion: before?.version ?? null, latestVersion: latestVersion ?? null };
59
+ if (compareVersions(latestVersion, latestVersion) === null) {
60
+ return { ...details, success: false, message: `Cannot determine the latest version of '${serviceId}'; no changes made. Check your registry connection and retry.` };
61
+ }
62
+ const comparison = compareVersions(before.version, latestVersion);
63
+ if (comparison !== null && comparison >= 0) {
64
+ // A manual npm upgrade may have overtaken a previous explicit npx pin.
65
+ // Do not report current and then launch that old pin on the next start.
66
+ rememberLaunchVersion(before.version);
67
+ return { ...details, success: true, updated: false, alreadyUpToDate: true, version: before.version,
68
+ message: `'${serviceId}' is already up to date (${before.version})` };
69
+ }
70
+ if (current.status === "running") {
71
+ // stopService can throw after the process exited (e.g. state write
72
+ // failure). A guarded startService is safe even if it remains running.
73
+ stopped = true;
74
+ const result = await this.stopService(serviceId);
75
+ if (!result.success) throw new Error(`Update aborted: ${result.message}`);
76
+ if ((await this.syncState()).services[serviceId]?.status === "running") {
77
+ stopped = false; // Do not spawn a duplicate if an external supervisor revived it.
78
+ return { ...details, success: false, message: `Update aborted: '${serviceId}' is still running; stop its external supervisor and retry.` };
79
+ }
80
+ }
81
+ const installed = await install(serviceId);
82
+ if (!installed.success) throw new Error(`${installed.message}. See 'aih logs ${serviceId}'.`);
83
+ // Probe PATH, not the old daemon's health endpoint. Exit 0 alone is not
84
+ // evidence: native updaters can decline unsupported install methods.
85
+ const disk = (await getVersions([{ ...current, status: "stopped", pid: undefined }]))[serviceId];
86
+ const installedComparison = compareVersions(disk?.version, latestVersion);
87
+ if (installedComparison === null || installedComparison < 0) {
88
+ throw new Error(`Installer completed, but '${serviceId}' on PATH is ${disk?.version || "unverified"}, expected ${latestVersion}. Check the installation/PATH and 'aih logs ${serviceId}'`);
89
+ }
90
+ updated = true;
91
+ details.version = disk.version;
92
+ rememberLaunchVersion(disk.version);
93
+ let started;
94
+ if (stopped) {
95
+ stopped = false; // Only one restart attempt, including on startup failure.
96
+ started = await restart();
97
+ if (!started.success) return { ...details, success: false, updated, restarted: false,
98
+ message: `'${serviceId}' updated to ${disk.version}, but restart failed: ${started.message}` };
99
+ const running = (await this.syncState()).services[serviceId];
100
+ if (running?.status !== "running" || !running.pid) {
101
+ return { ...details, success: false, updated, restarted: false, codexConfig: started.codexConfig,
102
+ message: `'${serviceId}' updated, but exited after restart; check 'aih logs ${serviceId}'` };
103
+ }
104
+ const live = (await getVersions([running]))[serviceId];
105
+ const liveComparison = compareVersions(live?.version, latestVersion);
106
+ if (liveComparison === null || liveComparison < 0) {
107
+ return { ...details, success: false, updated, restarted: true, codexConfig: started.codexConfig,
108
+ message: `'${serviceId}' restarted, but its running version is ${live?.version || "unverified"} (expected ${latestVersion}); check 'aih logs ${serviceId}'` };
109
+ }
110
+ details.version = live.version;
111
+ }
112
+ return { ...details, success: true, updated, restarted: Boolean(started), codexConfig: started?.codexConfig,
113
+ message: `'${serviceId}' updated to ${details.version}${started ? " and restarted" : " (left stopped)"}` };
114
+ } catch (error) {
115
+ const recovery = stopped ? await restart() : null;
116
+ return { ...details, success: false, updated, restarted: Boolean(recovery?.success && !recovery.alreadyRunning), codexConfig: recovery?.codexConfig,
117
+ message: `Update failed: ${error.message}${recovery ? recovery.success
118
+ ? recovery.alreadyRunning ? ". Service is still running." : ". Service restarted after the failure (package rollback is not guaranteed)."
119
+ : `. Recovery restart failed: ${recovery.message}` : ""}` };
120
+ } finally {
121
+ this.updatesInProgress.delete(serviceId);
122
+ }
123
+ }
124
+
17
125
  /**
18
126
  * Reads raw state from disk without discovery.
19
127
  */
@@ -58,9 +166,9 @@ export class ServiceManager {
58
166
  let needsSave = false;
59
167
 
60
168
  // Discover active verified daemon processes from OS
61
- const discovered = await discoverRunningProcesses();
169
+ const discovered = await discoverRunningProcesses({ knownServices: state.services });
62
170
 
63
- for (const id of SERVICE_IDS) {
171
+ for (const id of Object.keys(state.services)) {
64
172
  const svc = state.services[id];
65
173
  const info = discovered[id];
66
174
 
@@ -140,7 +248,7 @@ export class ServiceManager {
140
248
  */
141
249
  async getStatus(targetServices) {
142
250
  const state = await this.syncState();
143
- const targets = targetServices && targetServices.length > 0 ? targetServices : SERVICE_IDS;
251
+ const targets = targetServices && targetServices.length > 0 ? targetServices : Object.keys(state.services);
144
252
 
145
253
  return targets.map(id => {
146
254
  const def = SERVICES[id] || {
@@ -173,6 +281,8 @@ export class ServiceManager {
173
281
  description: def.description,
174
282
  uptime: svcState.status === "running" ? formatUptime(svcState.startedAt) : "-",
175
283
  url,
284
+ dashboardUrl: id === "proxy" || url === "-" ? null : url,
285
+ repositoryUrl: id === "proxy" ? APP_REPOSITORY_URL : def.repositoryUrl || null,
176
286
  logPath,
177
287
  logSize,
178
288
  };
@@ -187,7 +297,7 @@ export class ServiceManager {
187
297
  const opened = [];
188
298
 
189
299
  for (const svc of statuses) {
190
- const url = svc.url || SERVICES[svc.id]?.defaultUrl;
300
+ const url = svc.dashboardUrl;
191
301
  if (url && url !== "-") {
192
302
  openBrowser(url);
193
303
  opened.push({ id: svc.id, name: svc.name, url, status: svc.status });
@@ -197,10 +307,33 @@ export class ServiceManager {
197
307
  return opened;
198
308
  }
199
309
 
310
+ /** Repository metadata is static; opening it does not require process discovery. */
311
+ async openRepository(targetServices) {
312
+ const targets = targetServices?.length ? targetServices : Object.keys(this.readState().services);
313
+ const opened = [];
314
+ for (const id of targets) {
315
+ const url = id === "proxy" ? APP_REPOSITORY_URL : SERVICES[id]?.repositoryUrl;
316
+ if (!url) continue;
317
+ openBrowser(url);
318
+ opened.push({ id, name: SERVICES[id]?.name || id, url });
319
+ }
320
+ return opened;
321
+ }
322
+
323
+ async configureCodexProxy(options = {}) {
324
+ try {
325
+ return await configureCodexForProxy(this.loadState(), { ...options, readState: () => this.loadState() });
326
+ } catch {
327
+ // Config I/O must not tear down a proxy that has already reported ready.
328
+ return { status: "warning", message: "Service started, but Codex configuration could not be updated safely." };
329
+ }
330
+ }
331
+
200
332
  /**
201
333
  * Starts a single service by ID.
202
334
  */
203
- async startService(serviceId) {
335
+ async startService(serviceId, options) {
336
+ if (serviceId === "proxy") return this.startProxyService(options);
204
337
  const def = SERVICES[serviceId];
205
338
  if (!def) {
206
339
  return { success: false, message: `Unknown service '${serviceId}'. Available: ${SERVICE_IDS.join(", ")}` };
@@ -216,11 +349,13 @@ export class ServiceManager {
216
349
  pid: current.pid,
217
350
  alreadyRunning: true,
218
351
  url: current.url || def.defaultUrl,
352
+ ...(serviceId === "ocx" ? { codexConfig: await this.configureCodexProxy({ waitForOcx: true }) } : {}),
219
353
  };
220
354
  }
221
355
 
222
356
  const logPath = getServiceLogPath(serviceId);
223
- const { pid } = spawnDetachedProcess(def.command, logPath, {
357
+ const command = serviceStartCommand(serviceId, current);
358
+ const { pid } = spawnDetachedProcess(command, logPath, {
224
359
  env: def.env,
225
360
  cwd: def.workingDir,
226
361
  });
@@ -228,7 +363,8 @@ export class ServiceManager {
228
363
  state.services[serviceId] = {
229
364
  id: def.id,
230
365
  name: def.name,
231
- command: def.command,
366
+ command,
367
+ ...(current?.launchVersion ? { launchVersion: current.launchVersion } : {}),
232
368
  status: "running",
233
369
  pid,
234
370
  startedAt: new Date().toISOString(),
@@ -256,14 +392,87 @@ export class ServiceManager {
256
392
  message: `Service '${serviceId}' started successfully (PID: ${updatedSvc.pid})`,
257
393
  pid: updatedSvc.pid,
258
394
  url: updatedSvc.url || def.defaultUrl,
395
+ ...(serviceId === "ocx" ? { codexConfig: await this.configureCodexProxy({ waitForOcx: true }) } : {}),
259
396
  };
260
397
  }
261
398
 
399
+ async startProxyService(options) {
400
+ const state = this.loadState();
401
+ const current = state.services.proxy;
402
+ const config = normalizeProxyOptions({ ...current?.proxyOptions, ...options });
403
+ if (current?.status === "running" && isPidRunning(current.pid)) {
404
+ if (JSON.stringify(config) !== JSON.stringify(current.proxyOptions)) {
405
+ throw new Error("Proxy is already running with different options; use 'aih restart proxy <upstream> [options]'");
406
+ }
407
+ return { success: true, alreadyRunning: true, pid: current.pid, url: current.url,
408
+ codexConfig: await this.configureCodexProxy() };
409
+ }
410
+ ensureDir(getLogsDir());
411
+ const compiled = typeof Bun !== "undefined" && /^(?:\/\$bunfs\/|[A-Z]:\/~BUN\/)/i.test(Bun.main);
412
+ let workerPath = fileURLToPath(new URL("./proxy-worker.js", import.meta.url));
413
+ if (compiled) {
414
+ if (typeof AIH_PROXY_WORKER_SOURCE === "undefined") throw new Error("Rebuild with 'bun run build' to include the proxy worker");
415
+ workerPath = join(getAihDir(), "proxy-worker.mjs");
416
+ writeFileSync(workerPath, AIH_PROXY_WORKER_SOURCE);
417
+ }
418
+ let nodeExecutable = process.execPath;
419
+ if (typeof Bun !== "undefined") {
420
+ // NVM shims can drop IPC handles and expose the launcher's PID. Spawn Node itself.
421
+ try {
422
+ nodeExecutable = execFileSync("node", ["-p", "process.execPath"], {
423
+ encoding: "utf8", windowsHide: true, timeout: 5000,
424
+ }).trim();
425
+ } catch (error) {
426
+ throw new Error(`Cannot resolve Node.js 20.19+ on PATH: ${error.message}`);
427
+ }
428
+ }
429
+ const fd = openSync(getServiceLogPath("proxy"), "a");
430
+ let child;
431
+ try {
432
+ // Bun's HTTP/ws shims omit handshake events and cancellation; always use Node.
433
+ child = spawn(nodeExecutable, [workerPath], {
434
+ detached: true, windowsHide: true, stdio: ["ignore", fd, fd, "ipc"],
435
+ env: { ...process.env, AIH_PROXY_OPTIONS: JSON.stringify(config) },
436
+ });
437
+ } finally { closeSync(fd); }
438
+ try {
439
+ const ready = await new Promise((resolveReady, reject) => {
440
+ const timeout = setTimeout(() => finish(new Error("Proxy startup timed out; check 'aih logs proxy'")), 15000);
441
+ const onError = error => finish(error.code === "ENOENT" ? new Error("Proxy requires Node.js 20.19+ on PATH") : error);
442
+ const onExit = code => finish(new Error(`Proxy exited during startup (${code}); check 'aih logs proxy'`));
443
+ const onMessage = message => {
444
+ if (message.error) finish(new Error(message.error));
445
+ else if (message.url) finish(null, message);
446
+ };
447
+ const finish = (error, result) => {
448
+ clearTimeout(timeout);
449
+ child.off("error", onError).off("exit", onExit).off("message", onMessage);
450
+ error ? reject(error) : resolveReady(result);
451
+ };
452
+ child.once("error", onError).once("exit", onExit).on("message", onMessage);
453
+ });
454
+ const updated = this.loadState();
455
+ updated.services.proxy = {
456
+ id: "proxy", name: "proxy", command: `aih start proxy ${config.upstream}`,
457
+ status: "running", pid: child.pid, startedAt: new Date().toISOString(),
458
+ url: ready.url, proxyOptions: config,
459
+ };
460
+ this.saveState(updated);
461
+ return { success: true, pid: child.pid, url: ready.url, codexConfig: await this.configureCodexProxy() };
462
+ } catch (error) {
463
+ if (child.pid) await killProcessTree(child.pid);
464
+ throw error;
465
+ } finally {
466
+ if (child.connected) child.disconnect();
467
+ child.unref();
468
+ }
469
+ }
470
+
262
471
  /**
263
472
  * Starts all or selected services.
264
473
  */
265
474
  async startServices(serviceIds) {
266
- const targets = serviceIds && serviceIds.length > 0 ? serviceIds : SERVICE_IDS;
475
+ const targets = serviceIds && serviceIds.length > 0 ? serviceIds : Object.keys(this.readState().services);
267
476
  const results = {};
268
477
 
269
478
  for (const id of targets) {
@@ -281,6 +490,8 @@ export class ServiceManager {
281
490
  const state = await this.syncState();
282
491
  const current = state.services[serviceId];
283
492
 
493
+ if (!current) return { success: false, message: `Unknown service '${serviceId}'` };
494
+
284
495
  // 1. If service has a dedicated graceful stopCommand, run it
285
496
  if (def?.stopCommand) {
286
497
  const isWin = process.platform === "win32";
@@ -294,7 +505,8 @@ export class ServiceManager {
294
505
 
295
506
  // 2. Kill recorded process tree if still active
296
507
  if (current && current.pid && isPidRunning(current.pid)) {
297
- await killProcessTree(current.pid);
508
+ const result = await killProcessTree(current.pid);
509
+ if (!result.success) return result;
298
510
  }
299
511
 
300
512
  // 3. Clean up any remaining processes holding the service's ports
@@ -323,7 +535,7 @@ export class ServiceManager {
323
535
  * Stops all or selected services.
324
536
  */
325
537
  async stopServices(serviceIds) {
326
- const targets = serviceIds && serviceIds.length > 0 ? serviceIds : SERVICE_IDS;
538
+ const targets = serviceIds && serviceIds.length > 0 ? serviceIds : Object.keys(this.readState().services);
327
539
  const results = {};
328
540
 
329
541
  for (const id of targets) {
@@ -336,17 +548,23 @@ export class ServiceManager {
336
548
  /**
337
549
  * Restarts a single service by ID.
338
550
  */
339
- async restartService(serviceId) {
340
- await this.stopService(serviceId);
551
+ async restartService(serviceId, options) {
552
+ if (serviceId === "proxy") {
553
+ const current = this.readState().services.proxy;
554
+ normalizeProxyOptions({ ...current?.proxyOptions, ...options });
555
+ if (!current) return this.startService(serviceId, options);
556
+ }
557
+ const stopped = await this.stopService(serviceId);
558
+ if (!stopped.success) return stopped;
341
559
  await sleep(600);
342
- return await this.startService(serviceId);
560
+ return await this.startService(serviceId, options);
343
561
  }
344
562
 
345
563
  /**
346
564
  * Restarts all or selected services.
347
565
  */
348
566
  async restartServices(serviceIds) {
349
- const targets = serviceIds && serviceIds.length > 0 ? serviceIds : SERVICE_IDS;
567
+ const targets = serviceIds && serviceIds.length > 0 ? serviceIds : Object.keys(this.readState().services);
350
568
  const results = {};
351
569
 
352
570
  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
+ }
@@ -0,0 +1,235 @@
1
+ import { spawn } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import zlib from "node:zlib";
4
+ import { tokenStage } from "./proxy-stats.js";
5
+ import { requestImages } from "./request-images.js";
6
+
7
+ // Fixed recipes; the user's --interceptor runs afterwards and can inspect/edit the result.
8
+ const PRESETS = ["none", "pxpipe", "headroom", "rtk", "headroom-pxpipe", "rtk-pxpipe", "rtk-headroom-pxpipe"];
9
+ const DECODERS = { gzip: promisify(zlib.gunzip), deflate: promisify(zlib.inflate), br: promisify(zlib.brotliDecompress),
10
+ ...(typeof zlib.zstdDecompress === "function" ? { zstd: promisify(zlib.zstdDecompress) } : {}) };
11
+
12
+ export function normalizePresetOptions(options) {
13
+ const preset = options.preset || "none";
14
+ if (!PRESETS.includes(preset)) throw new Error(`Unknown preset. Choose: ${PRESETS.join(", ")}`);
15
+ const models = options.models ? String(options.models).split(",").map(s => s.trim()) : undefined;
16
+ if (models?.some(s => !s || !/^[\w./:-]+\*?$/.test(s))) throw new Error("models must be comma-separated model names, optionally ending in *");
17
+ const headroom = new URL(options.headroomUrl || "http://127.0.0.1:8787");
18
+ if (!["http:", "https:"].includes(headroom.protocol) || headroom.username || headroom.password || headroom.search || headroom.hash) {
19
+ throw new Error("headroomUrl must be HTTP(S) without credentials, query or fragment");
20
+ }
21
+ const rtkFilter = options.rtkFilter || undefined;
22
+ if (rtkFilter && !/^[a-z][a-z0-9-]*$/.test(rtkFilter)) throw new Error("Invalid rtk filter name");
23
+ const pxpipeNativeImages = options.pxpipeNativeImages ?? "allow";
24
+ if (!["allow", "bypass"].includes(pxpipeNativeImages)) throw new Error("pxpipeNativeImages must be allow or bypass");
25
+ return { preset, models: models?.join(","), headroomUrl: headroom.href, rtkFilter, pxpipeNativeImages };
26
+ }
27
+
28
+ function toolTexts(body) {
29
+ const slots = [];
30
+ const add = (object, key) => { if (typeof object[key] === "string" && object[key]) slots.push([object, key]); };
31
+ for (const item of Array.isArray(body.input) ? body.input : []) {
32
+ if (item?.type !== "function_call_output") continue;
33
+ if (Array.isArray(item.output)) {
34
+ for (const part of item.output) if (part?.type === "input_text") add(part, "text");
35
+ } else add(item, "output");
36
+ }
37
+ for (const message of Array.isArray(body.messages) ? body.messages : []) {
38
+ if (message?.role === "tool") {
39
+ if (Array.isArray(message.content)) {
40
+ for (const part of message.content) if (part?.type === "text") add(part, "text");
41
+ } else add(message, "content");
42
+ }
43
+ if (!Array.isArray(message?.content)) continue;
44
+ for (const part of message.content) {
45
+ if (part?.type !== "tool_result") continue;
46
+ if (Array.isArray(part.content)) {
47
+ for (const block of part.content) if (block?.type === "text") add(block, "text");
48
+ } else add(part, "content");
49
+ }
50
+ }
51
+ return slots;
52
+ }
53
+
54
+ function rtkPipe(text, filter, limit) {
55
+ return new Promise((resolve, reject) => {
56
+ // Never execute a command from a tool call: RTK receives only stdin and fixed CLI flags.
57
+ const child = spawn("rtk", ["pipe", ...(filter ? ["--filter", filter] : [])], { windowsHide: true, shell: false, stdio: ["pipe", "pipe", "pipe"] });
58
+ const chunks = [];
59
+ let size = 0;
60
+ const fail = error => { child.kill(); reject(error); };
61
+ const timeout = setTimeout(() => fail(new Error("rtk pipe timed out")), 30000);
62
+ child.once("error", error => { clearTimeout(timeout); reject(error); });
63
+ child.stdin.on("error", fail);
64
+ child.stderr.resume();
65
+ child.stdout.on("data", chunk => {
66
+ size += chunk.length;
67
+ if (size > limit) fail(new Error("rtk output exceeds maxBodyBytes"));
68
+ else chunks.push(chunk);
69
+ });
70
+ child.once("close", code => {
71
+ clearTimeout(timeout);
72
+ if (code !== 0) reject(new Error(`rtk pipe exited with code ${code}`));
73
+ else resolve(Buffer.concat(chunks).toString("utf8"));
74
+ });
75
+ child.stdin.end(text);
76
+ });
77
+ }
78
+
79
+ export async function createPresetHooks(config, onStats = () => {}) {
80
+ if (!config.preset || config.preset === "none") return {};
81
+ const { countTokens: tokenize } = await import("gpt-tokenizer/encoding/o200k_base");
82
+ function countTokens(text) {
83
+ try { return tokenize(text, { disallowedSpecial: new Set() }); }
84
+ catch { return NaN; } // Observability must not reject an otherwise valid request.
85
+ }
86
+ const px = config.preset.includes("pxpipe") ? await import("pxpipe-proxy") : null;
87
+ const models = config.models?.split(",");
88
+ const wsModels = new WeakMap();
89
+ const warnedEncodings = new Set();
90
+
91
+ async function headroom(body, model) {
92
+ // Responses items (reasoning, calls, IDs, images) stay native. Compress only their tool text.
93
+ const slots = Array.isArray(body.input) ? toolTexts(body) : null;
94
+ const messages = slots ? slots.map(([object, key], i) => ({ role: "tool", tool_call_id: String(i), content: object[key] })) : body.messages;
95
+ if (!messages?.length) return tokenStage("headroom", 0, 0, false, "no_messages", "headroom");
96
+ const response = await fetch(config.headroomUrl.replace(/\/$/, "") + "/v1/compress", {
97
+ method: "POST", redirect: "error", signal: AbortSignal.timeout(30000),
98
+ headers: { "content-type": "application/json", ...(process.env.HEADROOM_PROXY_TOKEN ? { "x-headroom-proxy-token": process.env.HEADROOM_PROXY_TOKEN } : {}) },
99
+ // Inline mode needs no Headroom retrieval tool injected into the client.
100
+ body: JSON.stringify({ model, messages, config: { mode: "lossy_inline" } }),
101
+ });
102
+ if (!response.ok) throw new Error(`Headroom compression returned HTTP ${response.status}`);
103
+ const chunks = [];
104
+ let size = 0;
105
+ for await (const chunk of response.body) {
106
+ size += chunk.length;
107
+ if (size > config.maxBodyBytes) throw new Error("Headroom response exceeds maxBodyBytes");
108
+ chunks.push(chunk);
109
+ }
110
+ const result = JSON.parse(Buffer.concat(chunks).toString("utf8"));
111
+ if (!Array.isArray(result.messages)) throw new Error("Invalid Headroom response: missing messages");
112
+ if (slots) {
113
+ if (result.messages.length !== slots.length || result.messages.some((m, i) => m?.tool_call_id !== String(i) || typeof m.content !== "string")) {
114
+ throw new Error("Headroom changed the Responses tool output structure");
115
+ }
116
+ slots.forEach(([object, key], i) => { object[key] = result.messages[i].content; });
117
+ } else body.messages = result.messages;
118
+ return tokenStage("headroom", result.tokens_before, result.tokens_after,
119
+ JSON.stringify(result.messages) !== JSON.stringify(messages), result.compression_skipped ? "compression_skipped" : "processed", "headroom");
120
+ }
121
+
122
+ async function transform(raw, context, websocket = false) {
123
+ const path = new URL(context.path, "http://localhost").pathname;
124
+ const format = /\/(?:v1\/|anthropic\/)?messages$/.test(path) ? "anthropic"
125
+ : /\/chat\/completions$/.test(path) ? "chat" : /\/responses$/.test(path) ? "responses" : null;
126
+ if (!format) return raw;
127
+ let envelope;
128
+ try { envelope = JSON.parse(raw.toString("utf8")); } catch { return raw; }
129
+ if (!envelope || typeof envelope !== "object" || Array.isArray(envelope)) return raw;
130
+ if (websocket && envelope.type !== "response.create") return raw;
131
+ const body = websocket && envelope.response ? envelope.response : envelope;
132
+ if (!body || typeof body !== "object" || Array.isArray(body)) return raw;
133
+ const model = body.model || (websocket && (wsModels.get(context) || new URL(context.path, "http://localhost").searchParams.get("model")));
134
+ if (typeof model !== "string" || !model) return raw;
135
+ if (websocket) wsModels.set(context, model);
136
+ if (format === "responses" ? !(typeof body.input === "string" || Array.isArray(body.input)) : !Array.isArray(body.messages)) return raw;
137
+ // Snapshot BEFORE RTK/Headroom. A prior stage dropping an attachment must not enable imaging.
138
+ const bypassPxpipe = px && config.pxpipeNativeImages === "bypass" && requestImages(body, { identities: false }).length > 0;
139
+ let changed = false;
140
+ const stages = [];
141
+ const report = error => {
142
+ // Observability must never interrupt proxy traffic; no request bodies are passed to the recorder.
143
+ // Optional correlation only; never pass headers or bodies to the recorder.
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 {}
146
+ };
147
+ try {
148
+ // Fixed stage order, including the triple recipe: RTK -> Headroom -> pxpipe.
149
+ if (config.preset === "rtk" || config.preset.startsWith("rtk-")) {
150
+ let before = 0, after = 0, applied = false;
151
+ for (const [object, key] of toolTexts(body)) {
152
+ before += countTokens(object[key]);
153
+ const output = await rtkPipe(object[key], config.rtkFilter, config.maxBodyBytes);
154
+ // RTK may add framing or not recognize this output; only keep actual compression.
155
+ if (output.trim() && Buffer.byteLength(output) < Buffer.byteLength(object[key])) {
156
+ object[key] = output;
157
+ changed = true;
158
+ applied = true;
159
+ }
160
+ after += countTokens(object[key]);
161
+ }
162
+ stages.push(tokenStage("rtk", before, after, applied, applied ? "applied" : "unchanged", "o200k_estimate"));
163
+ }
164
+ if (config.preset.split("-").includes("headroom")) {
165
+ const before = JSON.stringify(body);
166
+ stages.push(await headroom(body, model));
167
+ // A Headroom no-op must not discard changes already made by RTK.
168
+ changed = JSON.stringify(body) !== before || changed;
169
+ }
170
+ if (bypassPxpipe) {
171
+ stages.push(tokenStage("pxpipe", 0, 0, false, "native_images_present", "pxpipe_estimate"));
172
+ } else if (px && (models ? models.some(m => m.endsWith("*") ? model.startsWith(m.slice(0, -1)) : model === m) : px.isPxpipeSupportedModel(model) || px.isPxpipeSupportedGptModel(model))) {
173
+ const bytes = Buffer.from(JSON.stringify({ ...body, model }));
174
+ const options = { model };
175
+ const result = await (format === "anthropic" ? px.transformRequest(bytes, options)
176
+ : format === "chat" ? px.transformOpenAIChatCompletions(bytes, options) : px.transformOpenAIResponses(bytes, options));
177
+ const info = result.info || {};
178
+ let before = 0, after = 0, method = "pxpipe_estimate";
179
+ if (info.compressed) {
180
+ before = info.baselineImagedTokens;
181
+ after = Number.isFinite(info.imageTokens) ? info.imageTokens + (info.nativeInjectedTokens ?? 0) : undefined;
182
+ if (!Number.isFinite(before) || !Number.isFinite(after)) {
183
+ // Anthropic's transformer lacks token totals: count text locally and include newly rendered images.
184
+ const textTokens = value => countTokens(JSON.stringify(value, (key, item) =>
185
+ ["image", "input_image", "image_url"].includes(item?.type) || key === "encrypted_content" ? undefined : item));
186
+ before = textTokens(JSON.parse(bytes));
187
+ let imageTokens;
188
+ try { imageTokens = info.imageDims?.reduce((sum, d) => sum + px.openAIVisionTokens(model, d.width, d.height), 0); } catch {}
189
+ after = Number.isFinite(imageTokens) ? textTokens(JSON.parse(Buffer.from(result.body))) + imageTokens : undefined;
190
+ method = "o200k_and_vision_estimate";
191
+ }
192
+ }
193
+ stages.push(tokenStage("pxpipe", before, after, Boolean(info.compressed),
194
+ info.compressed ? "applied" : String(info.reason || "unchanged").split(/[^a-z_]/i)[0].slice(0, 40), method));
195
+ if (result.info?.compressed) {
196
+ const transformed = JSON.parse(Buffer.from(result.body).toString("utf8"));
197
+ if (!Object.hasOwn(body, "model")) delete transformed.model;
198
+ // Only replace the AI request, preserving a WebSocket event's outer fields.
199
+ if (body !== envelope) envelope.response = transformed;
200
+ else { for (const key of Object.keys(body)) delete body[key]; Object.assign(body, transformed); }
201
+ changed = true;
202
+ }
203
+ } else if (px) {
204
+ stages.push(tokenStage("pxpipe", 0, 0, false, "model_excluded", "pxpipe_estimate"));
205
+ }
206
+ report(false);
207
+ return changed ? Buffer.from(JSON.stringify(envelope)) : raw;
208
+ } catch (error) { report(true); throw error; }
209
+ }
210
+
211
+ return {
212
+ async onRequest(context) {
213
+ if (context.method !== "POST" || !/\bapplication\/(?:[\w.-]+\+)?json\b/i.test(String(context.headers["content-type"] || ""))) return;
214
+ const encoding = String(context.headers["content-encoding"] || "identity").toLowerCase();
215
+ if (encoding !== "identity" && !DECODERS[encoding]) {
216
+ if (!warnedEncodings.has(encoding)) {
217
+ console.warn(`[aih preset] Skipped unsupported content-encoding=${encoding} on ${process.version}${encoding === "zstd" ? "; use Node.js 22.15+ for Zstandard requests" : ""}`);
218
+ warnedEncodings.add(encoding);
219
+ }
220
+ return;
221
+ }
222
+ const raw = encoding === "identity" ? context.body : await DECODERS[encoding](context.body, { maxOutputLength: config.maxBodyBytes });
223
+ const body = await transform(raw, context);
224
+ if (body !== raw) {
225
+ context.body = body;
226
+ delete context.headers["content-encoding"];
227
+ delete context.headers["content-md5"];
228
+ delete context.headers.digest;
229
+ }
230
+ },
231
+ async onWebSocketMessage(event) {
232
+ if (event.direction === "request" && !event.isBinary) event.body = await transform(event.body, event.request, true);
233
+ },
234
+ };
235
+ }