@drakonkat/ai-helper 1.2.2 → 1.2.4

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
@@ -3,7 +3,9 @@ import { execFileSync, spawn } from "node:child_process";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { join } from "node:path";
5
5
  import { normalizeProxyOptions } from "./proxy.js";
6
- import { SERVICES, SERVICE_IDS, APP_REPOSITORY_URL } from "./config.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";
7
9
  import { configureCodexForProxy } from "./codex-routing.js";
8
10
  import { ensureDir, getAihDir, getLogsDir, getServiceLogPath, getStateFilePath } from "./utils/path.js";
9
11
  import {
@@ -19,6 +21,107 @@ import {
19
21
  import { formatBytes, formatUptime, gray, red, yellow, green, cyan } from "./utils/format.js";
20
22
 
21
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
+
22
125
  /**
23
126
  * Reads raw state from disk without discovery.
24
127
  */
@@ -251,7 +354,8 @@ export class ServiceManager {
251
354
  }
252
355
 
253
356
  const logPath = getServiceLogPath(serviceId);
254
- const { pid } = spawnDetachedProcess(def.command, logPath, {
357
+ const command = serviceStartCommand(serviceId, current);
358
+ const { pid } = spawnDetachedProcess(command, logPath, {
255
359
  env: def.env,
256
360
  cwd: def.workingDir,
257
361
  });
@@ -259,7 +363,8 @@ export class ServiceManager {
259
363
  state.services[serviceId] = {
260
364
  id: def.id,
261
365
  name: def.name,
262
- command: def.command,
366
+ command,
367
+ ...(current?.launchVersion ? { launchVersion: current.launchVersion } : {}),
263
368
  status: "running",
264
369
  pid,
265
370
  startedAt: new Date().toISOString(),
@@ -2,9 +2,10 @@ import { spawn } from "node:child_process";
2
2
  import { promisify } from "node:util";
3
3
  import zlib from "node:zlib";
4
4
  import { tokenStage } from "./proxy-stats.js";
5
+ import { requestImages } from "./request-images.js";
5
6
 
6
7
  // Fixed recipes; the user's --interceptor runs afterwards and can inspect/edit the result.
7
- const PRESETS = ["none", "pxpipe", "headroom", "rtk", "headroom-pxpipe", "rtk-pxpipe"];
8
+ const PRESETS = ["none", "pxpipe", "headroom", "rtk", "headroom-pxpipe", "rtk-pxpipe", "rtk-headroom-pxpipe"];
8
9
  const DECODERS = { gzip: promisify(zlib.gunzip), deflate: promisify(zlib.inflate), br: promisify(zlib.brotliDecompress),
9
10
  ...(typeof zlib.zstdDecompress === "function" ? { zstd: promisify(zlib.zstdDecompress) } : {}) };
10
11
 
@@ -19,7 +20,9 @@ export function normalizePresetOptions(options) {
19
20
  }
20
21
  const rtkFilter = options.rtkFilter || undefined;
21
22
  if (rtkFilter && !/^[a-z][a-z0-9-]*$/.test(rtkFilter)) throw new Error("Invalid rtk filter name");
22
- return { preset, models: models?.join(","), headroomUrl: headroom.href, rtkFilter };
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 };
23
26
  }
24
27
 
25
28
  function toolTexts(body) {
@@ -131,6 +134,8 @@ export async function createPresetHooks(config, onStats = () => {}) {
131
134
  if (typeof model !== "string" || !model) return raw;
132
135
  if (websocket) wsModels.set(context, model);
133
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;
134
139
  let changed = false;
135
140
  const stages = [];
136
141
  const report = error => {
@@ -140,12 +145,8 @@ export async function createPresetHooks(config, onStats = () => {}) {
140
145
  try { onStats({ model, preset: config.preset, transport: websocket ? "WS" : "HTTP", changed, stages, error, ...(requestId ? { requestId } : {}) }); } catch {}
141
146
  };
142
147
  try {
143
- if (config.preset.startsWith("headroom")) {
144
- const before = JSON.stringify(body);
145
- stages.push(await headroom(body, model));
146
- changed = JSON.stringify(body) !== before;
147
- }
148
- if (config.preset === "rtk" || config.preset === "rtk-pxpipe") {
148
+ // Fixed stage order, including the triple recipe: RTK -> Headroom -> pxpipe.
149
+ if (config.preset === "rtk" || config.preset.startsWith("rtk-")) {
149
150
  let before = 0, after = 0, applied = false;
150
151
  for (const [object, key] of toolTexts(body)) {
151
152
  before += countTokens(object[key]);
@@ -160,7 +161,15 @@ export async function createPresetHooks(config, onStats = () => {}) {
160
161
  }
161
162
  stages.push(tokenStage("rtk", before, after, applied, applied ? "applied" : "unchanged", "o200k_estimate"));
162
163
  }
163
- if (px && (models ? models.some(m => m.endsWith("*") ? model.startsWith(m.slice(0, -1)) : model === m) : px.isPxpipeSupportedModel(model) || px.isPxpipeSupportedGptModel(model))) {
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))) {
164
173
  const bytes = Buffer.from(JSON.stringify({ ...body, model }));
165
174
  const options = { model };
166
175
  const result = await (format === "anthropic" ? px.transformRequest(bytes, options)
@@ -0,0 +1,69 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ const TYPES = new Set(["image", "image_url", "input_image", "output_image"]);
4
+ const canonical = value => Array.isArray(value) ? value.map(canonical)
5
+ : value && typeof value === "object" ? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])])) : value;
6
+ const hash = value => createHash("sha256").update(JSON.stringify(canonical(value))).digest("hex");
7
+ const textTypes = new Set(["text", "input_text", "output_text"]);
8
+
9
+ /** Only protocol content slots, never schemas, metadata or strings containing JSON. No URL fetches. */
10
+ export function requestImages(body, { identities = true } = {}) {
11
+ const images = [];
12
+ function content(value, owner, path) {
13
+ if (!Array.isArray(value)) return;
14
+ const nearbyText = identities ? value.filter(part => textTypes.has(part?.type) && typeof part.text === "string").map(part => part.text) : [];
15
+ const associationHash = identities ? hash({ ...owner, nearbyText }) : undefined;
16
+ for (const [index, part] of value.entries()) {
17
+ if (!part || typeof part !== "object") continue;
18
+ const inline = part.inline_data || part.inlineData;
19
+ if (TYPES.has(part.type) || /^image\//.test(inline?.mime_type || inline?.mimeType || "")) {
20
+ // Routing only needs presence: avoid serializing/hashing potentially huge attachments there.
21
+ images.push({ ...(identities ? { fingerprint: hash(part), associationHash } : {}), group: path, position: index });
22
+ } else if (part.type === "tool_result") {
23
+ content(part.content, { ...owner, toolCallId: part.tool_use_id || null }, `${path}/${index}/tool_result`);
24
+ }
25
+ }
26
+ }
27
+ content(body?.system, { scope: "system", role: "system" }, "system");
28
+ content(body?.instructions, { scope: "instructions", role: "system" }, "instructions");
29
+ for (const scope of ["input", "messages"]) {
30
+ for (const [index, item] of (Array.isArray(body?.[scope]) ? body[scope] : []).entries()) {
31
+ if (!item || typeof item !== "object") continue;
32
+ const owner = { scope, role: item.role || null, toolCallId: item.call_id || item.tool_call_id || null };
33
+ content(item.content, owner, `${scope}/${index}/content`);
34
+ if (item.type === "function_call_output") content(item.output, owner, `${scope}/${index}/output`);
35
+ }
36
+ }
37
+ return images;
38
+ }
39
+
40
+ /** Exact attachment/metadata preservation, relative order, grouping and adjacent native text. */
41
+ export function compareRequestImages(original, transformed) {
42
+ const before = requestImages(original), after = requestImages(transformed);
43
+ const wanted = new Set(before.map(x => x.fingerprint));
44
+ const originalsAfter = after.filter(x => wanted.has(x.fingerprint));
45
+ const counts = list => { const map = new Map(); for (const x of list) map.set(x.fingerprint, (map.get(x.fingerprint) || 0) + 1); return map; };
46
+ const b = counts(before), a = counts(originalsAfter);
47
+ let retained = 0, duplicated = 0;
48
+ for (const [fingerprint, count] of b) { retained += Math.min(count, a.get(fingerprint) || 0); duplicated += Math.max(0, (a.get(fingerprint) || 0) - count); }
49
+ const sequence = list => JSON.stringify(list.map(x => x.fingerprint));
50
+ const groups = list => { const map = new Map(); return list.map(x => { if (!map.has(x.group)) map.set(x.group, map.size); return map.get(x.group); }); };
51
+ const occurrences = new Map(), matches = new Map();
52
+ for (const item of originalsAfter) { if (!matches.has(item.fingerprint)) matches.set(item.fingerprint, []); matches.get(item.fingerprint).push(item); }
53
+ const checks = before.map((item, index) => {
54
+ const occurrence = occurrences.get(item.fingerprint) || 0;
55
+ occurrences.set(item.fingerprint, occurrence + 1);
56
+ const match = matches.get(item.fingerprint)?.[occurrence];
57
+ return { id: `native_image:${index}`, kind: "nativeImage", status: match ? "pass" : "fail", reason: match ? "native_image_unchanged" : "native_image_missing_or_changed" };
58
+ });
59
+ if (before.length) {
60
+ const ordered = sequence(before) === sequence(originalsAfter);
61
+ checks.push({ id: "native_images:order", kind: "nativeImage", status: ordered ? "pass" : "fail", reason: ordered ? "native_image_order_preserved" : "native_image_order_or_count_changed" });
62
+ const associated = ordered && before.every((x, i) => x.associationHash === originalsAfter[i].associationHash)
63
+ && JSON.stringify(groups(before)) === JSON.stringify(groups(originalsAfter));
64
+ checks.push({ id: "native_images:association", kind: "nativeImage", status: associated ? "pass" : "fail", reason: associated ? "native_image_association_preserved" : "native_image_association_or_adjacent_text_changed" });
65
+ }
66
+ return { status: checks.some(c => c.status === "fail") ? "fail" : before.length ? "pass" : "unscored",
67
+ before: before.length, after: after.length, retained, missingOrChanged: before.length - retained, duplicated,
68
+ addedOrChanged: after.length - originalsAfter.length, checks };
69
+ }
@@ -0,0 +1,68 @@
1
+ import { spawn } from "node:child_process";
2
+ import { closeSync, openSync, writeSync } from "node:fs";
3
+ import { SERVICE_PACKAGES, SERVICES } from "./config.js";
4
+ import { compareVersions } from "./utils/versions.js";
5
+ import { ensureDir, getLogsDir, getServiceLogPath } from "./utils/path.js";
6
+
7
+ /** Only allowlisted services/arguments reach an installer; never execute user input. */
8
+ export function serviceUpdateInvocation(id, platform = process.platform) {
9
+ if (!Object.hasOwn(SERVICE_PACKAGES, id)) throw new Error(`Service '${id}' cannot be updated separately`);
10
+ const pkg = SERVICE_PACKAGES[id];
11
+ // Headroom detects its own Python environment (uv, pipx, pip/venv).
12
+ // Do not run an arbitrary `pip` from PATH against a different interpreter.
13
+ if (pkg.pypi) return { command: "headroom", args: ["update", "--yes"] };
14
+ const args = ["install", "--global", `${pkg.name}@latest`, "--no-audit", "--no-fund"];
15
+ // npm.cmd cannot be spawned directly on Windows. These are fixed arguments,
16
+ // not paths or user-provided shell text; no shell is used on Unix.
17
+ return platform === "win32"
18
+ ? { command: "cmd.exe", args: ["/d", "/s", "/c", `npm ${args.join(" ")}`] }
19
+ : { command: "npm", args };
20
+ }
21
+
22
+ /** Pin npx after an explicit update, so a project's old dependency/cache cannot win. */
23
+ export function serviceStartCommand(id, state) {
24
+ const pkg = SERVICE_PACKAGES[id];
25
+ const version = state?.launchVersion;
26
+ if (pkg?.npx && typeof version === "string" && compareVersions(version, version) === 0) {
27
+ return `npx --yes ${pkg.name}@${version.trim().replace(/^v/, "")}`;
28
+ }
29
+ return SERVICES[id]?.command;
30
+ }
31
+
32
+ /** Capture installer output, keeping --json/TUI clean and full diagnostics in the service log. */
33
+ export function installServiceUpdate(id, { spawnImpl = spawn, platform = process.platform } = {}) {
34
+ const { command, args } = serviceUpdateInvocation(id, platform);
35
+ ensureDir(getLogsDir());
36
+ const logPath = getServiceLogPath(id);
37
+ const fd = openSync(logPath, "a");
38
+ writeSync(fd, `\n[aih] Update ${new Date().toISOString()}: ${command} ${args.join(" ")}\n`);
39
+ return new Promise(resolve => {
40
+ let tail = "";
41
+ let finished = false;
42
+ const finish = (exitCode, message) => {
43
+ if (finished) return;
44
+ finished = true;
45
+ closeSync(fd);
46
+ resolve({ success: exitCode === 0, exitCode, logPath,
47
+ message: message || (exitCode === 0 ? "Installer completed" : `Installer failed (${exitCode}): ${tail.trim() || "no output"}`) });
48
+ };
49
+ const collect = data => {
50
+ // Bound memory, not the log: package managers can produce many megabytes.
51
+ const text = String(data);
52
+ tail = (tail + text).slice(-4000);
53
+ if (!finished) { try { writeSync(fd, text); } catch {} }
54
+ };
55
+ try {
56
+ const child = spawnImpl(command, args, {
57
+ windowsHide: true, stdio: ["ignore", "pipe", "pipe"],
58
+ env: { ...process.env, CI: "1", npm_config_yes: "true", PIP_NO_INPUT: "1", NO_COLOR: "1" },
59
+ });
60
+ child.stdout?.on("data", collect);
61
+ child.stderr?.on("data", collect);
62
+ child.once("error", error => finish(1, `Cannot update '${id}': ${error.message}`));
63
+ // `close`, not `exit`: Headroom on Windows hands pip off to a child that
64
+ // inherits these pipes. Wait for that installer too before restarting.
65
+ child.once("close", (code, signal) => finish(code ?? 1, signal ? `Installer terminated by ${signal}` : undefined));
66
+ } catch (error) { finish(1, error.message); }
67
+ });
68
+ }