@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.
@@ -246,9 +246,13 @@ const AGENTMEMORY_DEFAULT_VIEWER = 3113;
246
246
  * The engine port is the one that binds 0.0.0.0 and is usually discovered first,
247
247
  * but the only browsable dashboard is the viewer, so derive it from the anchor.
248
248
  * @param {number[]} ports
249
+ * @param {number[]} [viewerPorts] Ports owned by the Node viewer, not the iii engine.
249
250
  * @returns {number}
250
251
  */
251
- export function resolveAgentmemoryViewerPort(ports) {
252
+ export function resolveAgentmemoryViewerPort(ports, viewerPorts = []) {
253
+ // The Node viewer and iii engine can own different parts of the port quartet.
254
+ const visibleViewerPorts = [...new Set(viewerPorts.filter(p => Number.isFinite(p) && p > 0))];
255
+ if (visibleViewerPorts.length === 1) return visibleViewerPorts[0];
252
256
  const candidates = (ports || []).filter(p => Number.isFinite(p) && p > 0);
253
257
  if (candidates.length === 0) return AGENTMEMORY_DEFAULT_VIEWER;
254
258
 
@@ -264,164 +268,106 @@ export function resolveAgentmemoryViewerPort(ports) {
264
268
  return Math.min(...candidates) + AGENTMEMORY_VIEWER_OFFSET;
265
269
  }
266
270
 
271
+ /** Resolve services from one Windows process/port snapshot, including child workers. */
272
+ export function discoverWindowsProcesses(data, { knownServices = {}, currentPid = process.pid, isRunning = isPidRunning } = {}) {
273
+ const array = value => value ? (Array.isArray(value) ? value : [value]) : [];
274
+ const procs = array(data?.Procs).filter(p => p.ProcessId && p.ProcessId !== currentPid);
275
+ const ports = array(data?.Ports).filter(p => p.LocalPort > 0 && p.OwningProcess > 0);
276
+ const byPid = new Map(procs.map(p => [p.ProcessId, p]));
277
+ const children = new Map();
278
+ const ownedPorts = new Map();
279
+ for (const p of procs) children.set(p.ParentProcessId, [...(children.get(p.ParentProcessId) || []), p]);
280
+ for (const p of ports) ownedPorts.set(p.OwningProcess, [...(ownedPorts.get(p.OwningProcess) || []), p]);
281
+ const runtime = p => /^(node|bun|python[\d.]*|headroom|ocx|iii|cmd|powershell|pwsh)(\.exe)?$/i.test(p.Name || "");
282
+ const engine = p => /^iii(?:\.exe)?$/i.test(p.Name || "");
283
+
284
+ function serviceOf(p) {
285
+ if (!runtime(p)) return;
286
+ const cmd = (p.CommandLine || "").replace(/\\/g, "/").toLowerCase();
287
+ // Do not exclude every bin/cli.js: pxpipe's real daemon uses that filename too.
288
+ if (/aih_gpt_launcher|get-ciminstance|where-object|(?:ai-helper|\.aih)\/(?:bin\/cli|src\/index)\.js/.test(cmd)) return;
289
+ if (/agentmemory-mcp|@agentmemory\/mcp|\bagentmemory\s+mcp\b|cli\.mjs["']?\s+mcp\b/.test(cmd)) return;
290
+ if (cmd.includes("pxpipe-proxy")) return "pxpipe";
291
+ if (cmd.includes("ocx.mjs") || (cmd.includes("opencodex") && !cmd.includes(".ps1")) || /\bocx(?:\.exe)?["']?\s+start\b/.test(cmd)) return "ocx";
292
+ if (engine(p) || /@agentmemory\/agentmemory|agentmemory\/dist\/cli\.mjs|iii-config\.yaml/.test(cmd)) return "agentmemory";
293
+ if (/headroom(?:\.exe)?["']?\s+proxy\b/.test(cmd)) return "headroom";
294
+ }
295
+
296
+ const discovered = {};
297
+ const ranks = {};
298
+ for (const seed of procs) {
299
+ let id = serviceOf(seed);
300
+ // Elevated processes may hide their command lines; a recorded PID still identifies their tree.
301
+ if (!id && !seed.CommandLine && runtime(seed)) {
302
+ id = Object.keys(knownServices).find(id => knownServices[id]?.pid === seed.ProcessId);
303
+ }
304
+ if (!id) continue;
305
+ let root = seed;
306
+ if (id === "agentmemory" && engine(seed)) {
307
+ const parent = byPid.get(seed.ParentProcessId);
308
+ if (parent && /^(node|bun)(\.exe)?$/i.test(parent.Name || "") &&
309
+ (!parent.CommandLine || serviceOf(parent) === id)) root = parent;
310
+ }
311
+ const family = new Map();
312
+ const pending = [root];
313
+ while (pending.length) {
314
+ const p = pending.pop();
315
+ if (family.has(p.ProcessId)) continue;
316
+ family.set(p.ProcessId, p);
317
+ pending.push(...(children.get(p.ProcessId) || []));
318
+ }
319
+ const listeners = [...family.keys()].flatMap(pid => ownedPorts.get(pid) || []);
320
+ if (!listeners.length) continue; // Shells, editors and hooks are not running daemons.
321
+ const available = listeners.map(p => p.LocalPort);
322
+ let port;
323
+ if (id === "agentmemory") {
324
+ const enginePorts = listeners.filter(p => engine(family.get(p.OwningProcess))).map(p => p.LocalPort);
325
+ const viewerPorts = listeners.filter(p => /^(node|bun)(\.exe)?$/i.test(family.get(p.OwningProcess)?.Name || "")).map(p => p.LocalPort);
326
+ port = resolveAgentmemoryViewerPort(enginePorts.length ? enginePorts : available, viewerPorts);
327
+ } else {
328
+ const explicit = Number(seed.CommandLine?.match(/\s--port(?:=|\s+)(\d+)/i)?.[1]);
329
+ const defaults = { pxpipe: [47822, 47821], headroom: [8788, 8787], ocx: [10100] };
330
+ port = [explicit, ...(defaults[id] || []), ...available].find(p => available.includes(p));
331
+ }
332
+ const owner = family.get((listeners.find(p => p.LocalPort === port) || listeners[0]).OwningProcess);
333
+ if (!isRunning(owner.ProcessId)) continue;
334
+ const rank = family.has(knownServices[id]?.pid) ? 1 : 0;
335
+ if (discovered[id] && ranks[id] >= rank) continue;
336
+ const date = owner.CreationDate;
337
+ const match = String(date || "").match(/\/Date\((\d+)\)\//);
338
+ const started = new Date(match ? Number(match[1]) : date || NaN);
339
+ discovered[id] = {
340
+ pid: owner.ProcessId,
341
+ command: owner.CommandLine || seed.CommandLine || knownServices[id]?.command || id,
342
+ startedAt: !isNaN(started.getTime()) ? started.toISOString() : undefined,
343
+ port,
344
+ url: `http://localhost:${port}${id === "headroom" ? "/dashboard" : ""}`,
345
+ };
346
+ ranks[id] = rank;
347
+ }
348
+ return discovered;
349
+ }
350
+
267
351
  /**
268
352
  * Scans the OS process table and listening ports to discover active services and their URLs.
269
353
  * @returns {Promise<Record<string, { pid: number; command: string; startedAt?: string; url?: string }>>}
270
354
  */
271
- export async function discoverRunningProcesses() {
355
+ export async function discoverRunningProcesses({ knownServices = {} } = {}) {
272
356
  const discovered = {};
273
357
  const currentPid = process.pid;
274
358
 
275
359
  if (process.platform === "win32") {
276
360
  try {
361
+ // Keep parents and children even when elevation hides their command lines.
277
362
  const script = `
278
- $procs = Get-CimInstance Win32_Process | Where-Object {
279
- $_.ProcessId -ne ${currentPid} -and
280
- $_.CommandLine -and
281
- ($_.CommandLine -match 'pxpipe-proxy|ocx|agentmemory|iii|headroom') -and
282
- ($_.CommandLine -notmatch 'ai-helper|\\baih(\\.exe)?\\b|bin\\\\cli\\.js|Get-CimInstance|Where-Object|Select-Object')
283
- } | Select-Object ProcessId, ParentProcessId, Name, CommandLine, CreationDate
284
-
285
- $ports = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue | Select-Object LocalPort, OwningProcess
286
-
363
+ $procs = Get-CimInstance Win32_Process | Where-Object { $_.ProcessId -ne ${currentPid} } |
364
+ Select-Object ProcessId, ParentProcessId, Name, CommandLine, CreationDate
365
+ $ports = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue |
366
+ Select-Object LocalPort, OwningProcess
287
367
  @{ Procs = $procs; Ports = $ports } | ConvertTo-Json -Depth 3
288
368
  `;
289
-
290
369
  const res = await execCommand("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]);
291
- if (!res.stdout.trim()) return discovered;
292
-
293
- let data;
294
- try {
295
- data = JSON.parse(res.stdout.trim());
296
- } catch {
297
- return discovered;
298
- }
299
-
300
- const procList = data?.Procs ? (Array.isArray(data.Procs) ? data.Procs : [data.Procs]) : [];
301
- const portList = data?.Ports ? (Array.isArray(data.Ports) ? data.Ports : [data.Ports]) : [];
302
-
303
- const pidToPorts = {};
304
- for (const p of portList) {
305
- if (p?.OwningProcess && p?.LocalPort) {
306
- if (!pidToPorts[p.OwningProcess]) pidToPorts[p.OwningProcess] = [];
307
- pidToPorts[p.OwningProcess].push(p.LocalPort);
308
- }
309
- }
310
-
311
- for (const item of procList) {
312
- const cmd = item.CommandLine || "";
313
- const pid = item.ProcessId;
314
- if (!pid || pid === currentPid || !isPidRunning(pid)) continue;
315
-
316
- // Skip any ai-helper / aih CLI executions
317
- if (cmd.includes("bin/cli.js") || cmd.includes("bin\\cli.js") || /\baih(\.exe)?\b/i.test(cmd)) {
318
- continue;
319
- }
320
-
321
- let startedAt;
322
- if (item.CreationDate) {
323
- const match = String(item.CreationDate).match(/\/Date\((\d+)\)\//);
324
- if (match) {
325
- startedAt = new Date(parseInt(match[1], 10)).toISOString();
326
- } else {
327
- const d = new Date(item.CreationDate);
328
- if (!isNaN(d.getTime())) {
329
- startedAt = d.toISOString();
330
- }
331
- }
332
- }
333
-
334
- const ports = pidToPorts[pid] || [];
335
-
336
- // 1. pxpipe
337
- if (cmd.includes("pxpipe-proxy")) {
338
- if (!discovered.pxpipe || (item.Name && item.Name.toLowerCase() === "node.exe" && cmd.includes("cli.js"))) {
339
- const webPort = ports.find(p => p > 1000 && p < 65000) || (discovered.pxpipe?.port);
340
- discovered.pxpipe = {
341
- pid,
342
- command: cmd,
343
- startedAt,
344
- port: webPort,
345
- url: webPort ? `http://localhost:${webPort}` : "http://localhost:47821",
346
- };
347
- }
348
- }
349
-
350
- // 2. ocx
351
- if (cmd.includes("ocx.mjs") || cmd.includes("opencodex") || (cmd.includes("ocx start") && !cmd.includes("aih "))) {
352
- const webPort = ports.find(p => p === 10100 || (p > 1000 && p < 65000));
353
- if (!discovered.ocx || cmd.includes("ocx.mjs start")) {
354
- discovered.ocx = {
355
- pid,
356
- command: cmd,
357
- startedAt,
358
- port: webPort || 10100,
359
- url: `http://localhost:${webPort || 10100}`,
360
- };
361
- }
362
- }
363
-
364
- // 3. agentmemory (daemon / iii-engine only, strictly exclude MCP stdio shims)
365
- const isMcpShim = cmd.includes("agentmemory-mcp") || cmd.includes("@agentmemory/mcp") || cmd.includes("agentmemory mcp");
366
-
367
- if (
368
- !isMcpShim &&
369
- (cmd.includes("@agentmemory/agentmemory") ||
370
- cmd.includes("agentmemory\\dist\\cli.mjs") ||
371
- cmd.includes("agentmemory/dist/cli.mjs") ||
372
- cmd.includes("iii-config.yaml") ||
373
- cmd.includes("iii.exe") ||
374
- (cmd.includes("agentmemory") && !cmd.includes("mcp") && !cmd.includes("aih ")))
375
- ) {
376
- // agentmemory opens a port quartet from one anchor N: REST N, streams N+1,
377
- // viewer N+2, engine N+46023. Only the viewer is a dashboard, so never point
378
- // the URL at the engine port even though it is the one usually listening.
379
- const viewerPort = resolveAgentmemoryViewerPort(ports);
380
- if (!discovered.agentmemory || cmd.includes("agentmemory/agentmemory") || cmd.includes("dist\\cli.mjs")) {
381
- discovered.agentmemory = {
382
- pid,
383
- command: cmd,
384
- startedAt,
385
- port: viewerPort,
386
- url: `http://localhost:${viewerPort}`,
387
- };
388
- }
389
- }
390
-
391
- // 4. headroom
392
- if (cmd.includes("headroom proxy") || (cmd.includes("headroom") && !cmd.includes("aih "))) {
393
- const webPort = ports.find(p => p === 8787 || (p > 1000 && p < 65000));
394
- if (!discovered.headroom || cmd.includes("headroom proxy")) {
395
- discovered.headroom = {
396
- pid,
397
- command: cmd,
398
- startedAt,
399
- port: webPort || 8787,
400
- url: `http://localhost:${webPort || 8787}/dashboard`,
401
- };
402
- }
403
- }
404
- }
405
-
406
- for (const p of procList) {
407
- const ports = pidToPorts[p.ProcessId] || [];
408
- if (ports.length > 0) {
409
- if (ports.includes(47821) && discovered.pxpipe) {
410
- discovered.pxpipe.url = "http://localhost:47821";
411
- }
412
- if (ports.includes(10100) && discovered.ocx) {
413
- discovered.ocx.url = "http://localhost:10100";
414
- }
415
- if (discovered.agentmemory && p.ProcessId === discovered.agentmemory.pid) {
416
- const viewerPort = resolveAgentmemoryViewerPort(ports);
417
- discovered.agentmemory.port = viewerPort;
418
- discovered.agentmemory.url = `http://localhost:${viewerPort}`;
419
- }
420
- if (ports.includes(8787) && discovered.headroom) {
421
- discovered.headroom.url = "http://localhost:8787/dashboard";
422
- }
423
- }
424
- }
370
+ if (res.stdout.trim()) return discoverWindowsProcesses(JSON.parse(res.stdout), { knownServices });
425
371
  } catch {}
426
372
  } else {
427
373
  try {
@@ -0,0 +1,171 @@
1
+ import { execFile } from "node:child_process";
2
+ import { readFile, realpath } from "node:fs/promises";
3
+ import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
4
+ import { baseUrl, fetchJson } from "./metrics.js";
5
+
6
+ const PACKAGES = {
7
+ pxpipe: { name: "pxpipe-proxy", bin: "pxpipe" },
8
+ ocx: { name: "@bitkyc08/opencodex", bin: "ocx", health: "/healthz", service: "opencodex" },
9
+ agentmemory: { name: "@agentmemory/agentmemory", bin: "agentmemory", health: "/agentmemory/health", service: "agentmemory" },
10
+ headroom: { name: "headroom-ai", bin: "headroom", health: "/health", pypi: true },
11
+ };
12
+
13
+ function parseVersion(value) {
14
+ if (typeof value !== "string") return null;
15
+ const match = value.trim().match(/^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/);
16
+ if (!match) return null;
17
+ if (match[4]?.split(".").some(part => /^0\d+$/.test(part))) return null;
18
+ return { core: match.slice(1, 4).map(BigInt), pre: match[4]?.split(".") || [] };
19
+ }
20
+
21
+ function cleanVersion(value) {
22
+ return parseVersion(value) ? value.trim().replace(/^v/, "") : null;
23
+ }
24
+
25
+ /** Returns -1, 0, 1, or null when either version cannot be compared safely. */
26
+ export function compareVersions(left, right) {
27
+ const a = parseVersion(left);
28
+ const b = parseVersion(right);
29
+ if (!a || !b) return null;
30
+ for (let i = 0; i < 3; i++) {
31
+ if (a.core[i] !== b.core[i]) return a.core[i] < b.core[i] ? -1 : 1;
32
+ }
33
+ if (!a.pre.length || !b.pre.length) return a.pre.length === b.pre.length ? 0 : a.pre.length ? -1 : 1;
34
+ for (let i = 0; i < Math.max(a.pre.length, b.pre.length); i++) {
35
+ const x = a.pre[i];
36
+ const y = b.pre[i];
37
+ if (x === y) continue;
38
+ if (x === undefined || y === undefined) return x === undefined ? -1 : 1;
39
+ const xn = /^\d+$/.test(x);
40
+ const yn = /^\d+$/.test(y);
41
+ if (xn && yn) {
42
+ if (BigInt(x) !== BigInt(y)) return BigInt(x) < BigInt(y) ? -1 : 1;
43
+ } else if (xn !== yn) return xn ? -1 : 1;
44
+ else return x < y ? -1 : 1;
45
+ }
46
+ return 0;
47
+ }
48
+
49
+ /** Only bounded, read-only commands are used; never invoke npx or an updater. */
50
+ export function runVersionCommand(command, args, timeoutMs = 3000) {
51
+ return new Promise(resolveResult => {
52
+ execFile(command, args, { timeout: timeoutMs, maxBuffer: 256 * 1024, windowsHide: true }, (error, stdout) => {
53
+ resolveResult(error ? null : String(stdout).trim());
54
+ });
55
+ });
56
+ }
57
+
58
+ async function getProcessCommands(statuses) {
59
+ const pids = [...new Set(statuses.filter(s => s.status === "running").map(s => Number(s.pid)))]
60
+ .filter(pid => Number.isSafeInteger(pid) && pid > 0);
61
+ if (!pids.length) return {};
62
+ if (process.platform === "win32") {
63
+ const filter = pids.map(pid => `ProcessId = ${pid}`).join(" OR ");
64
+ const output = await runVersionCommand("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command",
65
+ `Get-CimInstance Win32_Process -Filter '${filter}' | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress`]);
66
+ try {
67
+ const parsed = JSON.parse(output);
68
+ return Object.fromEntries((Array.isArray(parsed) ? parsed : [parsed]).filter(Boolean).map(p => [p.ProcessId, p.CommandLine]));
69
+ } catch { return {}; }
70
+ }
71
+ const output = await runVersionCommand("ps", ["-p", pids.join(","), "-o", "pid=,args="]);
72
+ return Object.fromEntries((output || "").split("\n").flatMap(line => {
73
+ const match = line.trim().match(/^(\d+)\s+(.+)$/);
74
+ return match ? [[match[1], match[2]]] : [];
75
+ }));
76
+ }
77
+
78
+ async function readPackageVersion(path, name) {
79
+ try {
80
+ const pkg = JSON.parse(await readFile(path, "utf8"));
81
+ return pkg.name === name ? cleanVersion(pkg.version) : null;
82
+ } catch { return null; }
83
+ }
84
+
85
+ /** Read the package referenced by this process, not an arbitrary npx cache entry. */
86
+ export async function readNpmVersionFromCommand(command, name) {
87
+ for (const match of (command || "").matchAll(/"([^"]+)"|'([^']+)'|(\S+)/g)) {
88
+ const token = match[1] || match[2] || match[3];
89
+ if (!isAbsolute(token)) continue;
90
+ const path = resolve(token).replace(/\\/g, "/");
91
+ const marker = `/node_modules/${name}/`;
92
+ const index = path.lastIndexOf(marker);
93
+ if (index < 0) continue;
94
+ const version = await readPackageVersion(`${path.slice(0, index + marker.length)}package.json`, name);
95
+ if (version) return version;
96
+ }
97
+ return null;
98
+ }
99
+
100
+ async function getInstalledVersion(status, command) {
101
+ const pkg = PACKAGES[status.id];
102
+ if (pkg.pypi) {
103
+ // Headroom's Click CLI explicitly implements --version without starting a proxy.
104
+ const output = await runVersionCommand("headroom", ["--version"]);
105
+ return cleanVersion(output?.match(/^headroom, version\s+(\S+)$/im)?.[1]);
106
+ }
107
+ const running = await readNpmVersionFromCommand(command, pkg.name);
108
+ if (running) return running;
109
+ // A running service may be an older cached install, not the package on PATH.
110
+ if (status.status === "running") return null;
111
+ for (const directory of (process.env.PATH || "").split(delimiter).filter(Boolean)) {
112
+ // npm's Windows shims live alongside node_modules; Unix bins are symlinks.
113
+ for (const candidate of [join(directory, "node_modules", pkg.name, "package.json"),
114
+ join(directory, "..", "lib", "node_modules", pkg.name, "package.json")]) {
115
+ const version = await readPackageVersion(candidate, pkg.name);
116
+ if (version) return version;
117
+ }
118
+ try {
119
+ const bin = await realpath(join(directory, pkg.bin));
120
+ const version = await readNpmVersionFromCommand(JSON.stringify(bin), pkg.name);
121
+ if (version) return version;
122
+ // Bun/pnpm links may resolve outside node_modules; only trust named metadata.
123
+ for (let path = dirname(bin), i = 0; i < 3; path = dirname(path), i++) {
124
+ const version = await readPackageVersion(join(path, "package.json"), pkg.name);
125
+ if (version) return version;
126
+ }
127
+ } catch {}
128
+ }
129
+ return null;
130
+ }
131
+
132
+ /**
133
+ * Installed/running and latest published versions. Unknowns stay null, including
134
+ * updateAvailable: a failed registry check is not evidence of being up to date.
135
+ * Optional readers keep tests offline and independent of installed services.
136
+ */
137
+ export async function getServiceVersions(statuses, {
138
+ request = fetchJson,
139
+ processCommands = getProcessCommands,
140
+ installedVersion = getInstalledVersion,
141
+ } = {}) {
142
+ const services = (statuses || []).filter(status => PACKAGES[status.id]);
143
+ let commands;
144
+ const readCommands = () => commands ||= Promise.resolve().then(() => processCommands(services)).catch(() => ({}));
145
+ return Object.fromEntries(await Promise.all(services.map(async status => {
146
+ const pkg = PACKAGES[status.id];
147
+ const latest = (async () => {
148
+ try {
149
+ const url = pkg.pypi ? `https://pypi.org/pypi/${pkg.name}/json` : `https://registry.npmjs.org/${encodeURIComponent(pkg.name)}/latest`;
150
+ const data = await request(url, 3000);
151
+ return cleanVersion(pkg.pypi ? data?.info?.version : data?.version);
152
+ } catch { return null; }
153
+ })();
154
+ const installed = (async () => {
155
+ if (status.status === "running" && pkg.health && baseUrl(status.url)) {
156
+ try {
157
+ const data = await request(`${baseUrl(status.url)}${pkg.health}`, 2000);
158
+ const version = cleanVersion(data?.version);
159
+ if (version && (!pkg.service || data?.service === pkg.service)) return version;
160
+ } catch {}
161
+ }
162
+ try {
163
+ const command = status.status === "running" ? (await readCommands())[status.pid] : null;
164
+ return cleanVersion(await installedVersion(status, command));
165
+ } catch { return null; }
166
+ })();
167
+ const [version, latestVersion] = await Promise.all([installed, latest]);
168
+ const comparison = compareVersions(version, latestVersion);
169
+ return [status.id, { version, latestVersion, updateAvailable: comparison === null ? null : comparison < 0 }];
170
+ })));
171
+ }