@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/ARCHITECTURE.md +14 -3
- package/CHANGELOG.md +9 -0
- package/README.md +483 -26
- package/docs/benchmark.md +373 -0
- package/package.json +17 -5
- package/scripts/bench-proxy.js +111 -0
- package/scripts/build.js +16 -0
- package/src/benchmark/fixtures.js +162 -0
- package/src/benchmark/live.js +207 -0
- package/src/benchmark/measurement.js +180 -0
- package/src/benchmark/quality-fixtures.js +95 -0
- package/src/benchmark/quality.js +206 -0
- package/src/benchmark/report.js +162 -0
- package/src/benchmark/runner.js +287 -0
- package/src/codex-config.js +247 -0
- package/src/codex-routing.js +132 -0
- package/src/config.js +19 -1
- package/src/index.js +158 -26
- package/src/manager.js +233 -15
- package/src/proxy-interceptor.example.mjs +33 -0
- package/src/proxy-presets.js +235 -0
- package/src/proxy-stats.js +64 -0
- package/src/proxy-worker.js +17 -0
- package/src/proxy.js +313 -0
- package/src/request-images.js +69 -0
- package/src/service-updates.js +68 -0
- package/src/tui.js +370 -162
- package/src/update.js +41 -0
- package/src/utils/metrics.js +39 -12
- package/src/utils/process.js +92 -146
- package/src/utils/versions.js +165 -0
package/src/update.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { PACKAGE_NAME, VERSION } from "./config.js";
|
|
2
|
+
|
|
3
|
+
export function isNewerVersion(latest, current) {
|
|
4
|
+
const parse = value => typeof value === "string"
|
|
5
|
+
? /^(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-]+)*)?$/.exec(value)
|
|
6
|
+
: null;
|
|
7
|
+
const a = parse(latest);
|
|
8
|
+
const b = parse(current);
|
|
9
|
+
if (!a || !b || a[0] !== latest || b[0] !== current) return false;
|
|
10
|
+
for (let i = 1; i <= 3; i++) {
|
|
11
|
+
if (BigInt(a[i]) !== BigInt(b[i])) return BigInt(a[i]) > BigInt(b[i]);
|
|
12
|
+
}
|
|
13
|
+
if (!a[4] || !b[4]) return Boolean(b[4]) && !a[4];
|
|
14
|
+
const left = a[4].split(".");
|
|
15
|
+
const right = b[4].split(".");
|
|
16
|
+
for (let i = 0; i < Math.max(left.length, right.length); i++) {
|
|
17
|
+
if (left[i] === right[i]) continue;
|
|
18
|
+
if (left[i] === undefined || right[i] === undefined) return right[i] === undefined;
|
|
19
|
+
const numericLeft = /^\d+$/.test(left[i]);
|
|
20
|
+
const numericRight = /^\d+$/.test(right[i]);
|
|
21
|
+
if (numericLeft && numericRight) return BigInt(left[i]) > BigInt(right[i]);
|
|
22
|
+
if (numericLeft !== numericRight) return numericRight;
|
|
23
|
+
return left[i] > right[i];
|
|
24
|
+
}
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function checkForUpdates({ fetchImpl = globalThis.fetch, notify = console.error } = {}) {
|
|
29
|
+
try {
|
|
30
|
+
const response = await fetchImpl(`https://registry.npmjs.org/${encodeURIComponent(PACKAGE_NAME)}/latest`, {
|
|
31
|
+
signal: AbortSignal.timeout(1500), headers: { accept: "application/json" },
|
|
32
|
+
});
|
|
33
|
+
if (!response.ok) return;
|
|
34
|
+
const { version } = await response.json();
|
|
35
|
+
if (isNewerVersion(version, VERSION)) {
|
|
36
|
+
notify(`[aih] Update available: ${VERSION} -> ${version}. Run: npm install -g ${PACKAGE_NAME}@latest`);
|
|
37
|
+
}
|
|
38
|
+
} catch {
|
|
39
|
+
// An unavailable registry must not prevent services from starting.
|
|
40
|
+
}
|
|
41
|
+
}
|
package/src/utils/metrics.js
CHANGED
|
@@ -253,38 +253,65 @@ export async function fetchJson(url, timeoutMs = 2000) {
|
|
|
253
253
|
|
|
254
254
|
/**
|
|
255
255
|
* Resolves the operational pipeline the AI calls flow through.
|
|
256
|
-
*
|
|
257
|
-
*
|
|
258
|
-
*
|
|
259
|
-
*
|
|
256
|
+
* Native topology uses only the proxy's configured stages and process state;
|
|
257
|
+
* an upstream URL is configuration, not proof that the destination is healthy.
|
|
258
|
+
* Without a proxy, legacy callers may still probe headroom's /health. Set
|
|
259
|
+
* nativeOnly to prevent that fallback when native proxy status is unavailable.
|
|
260
|
+
* @param {Array<{ id: string; status: string; url?: string; proxyOptions?: object }>} statuses
|
|
261
|
+
* @param {{ nativeOnly?: boolean }} [options]
|
|
260
262
|
* @returns {Promise<{ nodes: Array<{ id: string; label: string; state: string; detail: string }>; health: any | null }>}
|
|
261
263
|
*/
|
|
262
|
-
export async function probeChain(statuses) {
|
|
264
|
+
export async function probeChain(statuses, { nativeOnly = false } = {}) {
|
|
263
265
|
const byId = {};
|
|
264
266
|
for (const svc of statuses || []) byId[svc.id] = svc;
|
|
265
267
|
|
|
268
|
+
const proxy = byId.proxy;
|
|
269
|
+
if (proxy || nativeOnly) {
|
|
270
|
+
const options = proxy?.proxyOptions || {};
|
|
271
|
+
const preset = typeof options.preset === "string" ? options.preset : "none";
|
|
272
|
+
const labels = { pxpipe: "pxpipe (libreria)", rtk: "rtk (pipe)", headroom: "headroom (compress)" };
|
|
273
|
+
const stages = preset.split("-").filter(id => Object.hasOwn(labels, id)).map(id => ({
|
|
274
|
+
id, label: labels[id],
|
|
275
|
+
state: id === "pxpipe" ? proxy?.status || "unknown" : "static",
|
|
276
|
+
detail: id === "headroom" ? options.headroomUrl || "" : "",
|
|
277
|
+
}));
|
|
278
|
+
return { nodes: [
|
|
279
|
+
{ id: "client", label: "client", state: "static", detail: "AI agents / CLI" },
|
|
280
|
+
{ id: "proxy", label: "aih proxy", state: proxy?.status || "unknown", detail: proxy?.url || "" },
|
|
281
|
+
...stages,
|
|
282
|
+
{ id: "upstream", label: "upstream", state: "unknown", detail: options.upstream || "" },
|
|
283
|
+
], health: null };
|
|
284
|
+
}
|
|
285
|
+
|
|
266
286
|
const stateOf = id => byId[id]?.status || "unknown";
|
|
267
287
|
|
|
268
288
|
const nodes = [
|
|
269
289
|
{ id: "client", label: "client", state: "static", detail: "AI agents / CLI" },
|
|
270
290
|
{ id: "headroom", label: "headroom", state: stateOf("headroom"), detail: baseUrl(byId.headroom?.url) },
|
|
271
291
|
{ id: "pxpipe", label: "pxpipe", state: stateOf("pxpipe"), detail: baseUrl(byId.pxpipe?.url) },
|
|
272
|
-
{ id: "upstream", label: "upstream", state: "
|
|
292
|
+
{ id: "upstream", label: "upstream", state: "unknown", detail: "" },
|
|
273
293
|
];
|
|
274
294
|
|
|
275
295
|
const headroomBase = baseUrl(byId.headroom?.url);
|
|
276
|
-
const health = headroomBase
|
|
296
|
+
const health = headroomBase && nodes[1].state === "running"
|
|
297
|
+
? await fetchJson(`${headroomBase}/health`, 2000)
|
|
298
|
+
: null;
|
|
299
|
+
|
|
300
|
+
const checkedState = (status, fallback) => status === "healthy"
|
|
301
|
+
? "healthy"
|
|
302
|
+
: status === "unhealthy" || status === "error" || status === "degraded" ? "error" : fallback;
|
|
277
303
|
|
|
278
304
|
if (health) {
|
|
279
305
|
if (health.version) nodes[1].detail = `${nodes[1].detail} v${health.version}`.trim();
|
|
280
|
-
|
|
306
|
+
nodes[1].state = checkedState(health.status, nodes[1].state);
|
|
281
307
|
|
|
282
308
|
const upstream = health.checks?.upstream;
|
|
283
309
|
if (upstream?.url) {
|
|
284
|
-
//
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
310
|
+
// A configured forwarder is not necessarily the managed pxpipe instance.
|
|
311
|
+
if (baseUrl(upstream.url) && baseUrl(upstream.url) === baseUrl(byId.pxpipe?.url)) {
|
|
312
|
+
if (nodes[2].state === "running") nodes[2].state = checkedState(upstream.status, nodes[2].state);
|
|
313
|
+
} else {
|
|
314
|
+
nodes[1].detail += ` | inoltro: ${upstream.url} (destinazione non verificata)`;
|
|
288
315
|
}
|
|
289
316
|
}
|
|
290
317
|
}
|
package/src/utils/process.js
CHANGED
|
@@ -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
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
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 (
|
|
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,165 @@
|
|
|
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
|
+
import { SERVICE_PACKAGES as PACKAGES } from "../config.js";
|
|
6
|
+
|
|
7
|
+
function parseVersion(value) {
|
|
8
|
+
if (typeof value !== "string") return null;
|
|
9
|
+
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-]+)*)?$/);
|
|
10
|
+
if (!match) return null;
|
|
11
|
+
if (match[4]?.split(".").some(part => /^0\d+$/.test(part))) return null;
|
|
12
|
+
return { core: match.slice(1, 4).map(BigInt), pre: match[4]?.split(".") || [] };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function cleanVersion(value) {
|
|
16
|
+
return parseVersion(value) ? value.trim().replace(/^v/, "") : null;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Returns -1, 0, 1, or null when either version cannot be compared safely. */
|
|
20
|
+
export function compareVersions(left, right) {
|
|
21
|
+
const a = parseVersion(left);
|
|
22
|
+
const b = parseVersion(right);
|
|
23
|
+
if (!a || !b) return null;
|
|
24
|
+
for (let i = 0; i < 3; i++) {
|
|
25
|
+
if (a.core[i] !== b.core[i]) return a.core[i] < b.core[i] ? -1 : 1;
|
|
26
|
+
}
|
|
27
|
+
if (!a.pre.length || !b.pre.length) return a.pre.length === b.pre.length ? 0 : a.pre.length ? -1 : 1;
|
|
28
|
+
for (let i = 0; i < Math.max(a.pre.length, b.pre.length); i++) {
|
|
29
|
+
const x = a.pre[i];
|
|
30
|
+
const y = b.pre[i];
|
|
31
|
+
if (x === y) continue;
|
|
32
|
+
if (x === undefined || y === undefined) return x === undefined ? -1 : 1;
|
|
33
|
+
const xn = /^\d+$/.test(x);
|
|
34
|
+
const yn = /^\d+$/.test(y);
|
|
35
|
+
if (xn && yn) {
|
|
36
|
+
if (BigInt(x) !== BigInt(y)) return BigInt(x) < BigInt(y) ? -1 : 1;
|
|
37
|
+
} else if (xn !== yn) return xn ? -1 : 1;
|
|
38
|
+
else return x < y ? -1 : 1;
|
|
39
|
+
}
|
|
40
|
+
return 0;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Only bounded, read-only commands are used; never invoke npx or an updater. */
|
|
44
|
+
export function runVersionCommand(command, args, timeoutMs = 3000) {
|
|
45
|
+
return new Promise(resolveResult => {
|
|
46
|
+
execFile(command, args, { timeout: timeoutMs, maxBuffer: 256 * 1024, windowsHide: true }, (error, stdout) => {
|
|
47
|
+
resolveResult(error ? null : String(stdout).trim());
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function getProcessCommands(statuses) {
|
|
53
|
+
const pids = [...new Set(statuses.filter(s => s.status === "running").map(s => Number(s.pid)))]
|
|
54
|
+
.filter(pid => Number.isSafeInteger(pid) && pid > 0);
|
|
55
|
+
if (!pids.length) return {};
|
|
56
|
+
if (process.platform === "win32") {
|
|
57
|
+
const filter = pids.map(pid => `ProcessId = ${pid}`).join(" OR ");
|
|
58
|
+
const output = await runVersionCommand("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command",
|
|
59
|
+
`Get-CimInstance Win32_Process -Filter '${filter}' | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress`]);
|
|
60
|
+
try {
|
|
61
|
+
const parsed = JSON.parse(output);
|
|
62
|
+
return Object.fromEntries((Array.isArray(parsed) ? parsed : [parsed]).filter(Boolean).map(p => [p.ProcessId, p.CommandLine]));
|
|
63
|
+
} catch { return {}; }
|
|
64
|
+
}
|
|
65
|
+
const output = await runVersionCommand("ps", ["-p", pids.join(","), "-o", "pid=,args="]);
|
|
66
|
+
return Object.fromEntries((output || "").split("\n").flatMap(line => {
|
|
67
|
+
const match = line.trim().match(/^(\d+)\s+(.+)$/);
|
|
68
|
+
return match ? [[match[1], match[2]]] : [];
|
|
69
|
+
}));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function readPackageVersion(path, name) {
|
|
73
|
+
try {
|
|
74
|
+
const pkg = JSON.parse(await readFile(path, "utf8"));
|
|
75
|
+
return pkg.name === name ? cleanVersion(pkg.version) : null;
|
|
76
|
+
} catch { return null; }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Read the package referenced by this process, not an arbitrary npx cache entry. */
|
|
80
|
+
export async function readNpmVersionFromCommand(command, name) {
|
|
81
|
+
for (const match of (command || "").matchAll(/"([^"]+)"|'([^']+)'|(\S+)/g)) {
|
|
82
|
+
const token = match[1] || match[2] || match[3];
|
|
83
|
+
if (!isAbsolute(token)) continue;
|
|
84
|
+
const path = resolve(token).replace(/\\/g, "/");
|
|
85
|
+
const marker = `/node_modules/${name}/`;
|
|
86
|
+
const index = path.lastIndexOf(marker);
|
|
87
|
+
if (index < 0) continue;
|
|
88
|
+
const version = await readPackageVersion(`${path.slice(0, index + marker.length)}package.json`, name);
|
|
89
|
+
if (version) return version;
|
|
90
|
+
}
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async function getInstalledVersion(status, command) {
|
|
95
|
+
const pkg = PACKAGES[status.id];
|
|
96
|
+
if (pkg.pypi) {
|
|
97
|
+
// Headroom's Click CLI explicitly implements --version without starting a proxy.
|
|
98
|
+
const output = await runVersionCommand("headroom", ["--version"]);
|
|
99
|
+
return cleanVersion(output?.match(/^headroom, version\s+(\S+)$/im)?.[1]);
|
|
100
|
+
}
|
|
101
|
+
const running = await readNpmVersionFromCommand(command, pkg.name);
|
|
102
|
+
if (running) return running;
|
|
103
|
+
// A running service may be an older cached install, not the package on PATH.
|
|
104
|
+
if (status.status === "running") return null;
|
|
105
|
+
for (const directory of (process.env.PATH || "").split(delimiter).filter(Boolean)) {
|
|
106
|
+
// npm's Windows shims live alongside node_modules; Unix bins are symlinks.
|
|
107
|
+
for (const candidate of [join(directory, "node_modules", pkg.name, "package.json"),
|
|
108
|
+
join(directory, "..", "lib", "node_modules", pkg.name, "package.json")]) {
|
|
109
|
+
const version = await readPackageVersion(candidate, pkg.name);
|
|
110
|
+
if (version) return version;
|
|
111
|
+
}
|
|
112
|
+
try {
|
|
113
|
+
const bin = await realpath(join(directory, pkg.bin));
|
|
114
|
+
const version = await readNpmVersionFromCommand(JSON.stringify(bin), pkg.name);
|
|
115
|
+
if (version) return version;
|
|
116
|
+
// Bun/pnpm links may resolve outside node_modules; only trust named metadata.
|
|
117
|
+
for (let path = dirname(bin), i = 0; i < 3; path = dirname(path), i++) {
|
|
118
|
+
const version = await readPackageVersion(join(path, "package.json"), pkg.name);
|
|
119
|
+
if (version) return version;
|
|
120
|
+
}
|
|
121
|
+
} catch {}
|
|
122
|
+
}
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Installed/running and latest published versions. Unknowns stay null, including
|
|
128
|
+
* updateAvailable: a failed registry check is not evidence of being up to date.
|
|
129
|
+
* Optional readers keep tests offline and independent of installed services.
|
|
130
|
+
*/
|
|
131
|
+
export async function getServiceVersions(statuses, {
|
|
132
|
+
request = fetchJson,
|
|
133
|
+
processCommands = getProcessCommands,
|
|
134
|
+
installedVersion = getInstalledVersion,
|
|
135
|
+
} = {}) {
|
|
136
|
+
const services = (statuses || []).filter(status => PACKAGES[status.id]);
|
|
137
|
+
let commands;
|
|
138
|
+
const readCommands = () => commands ||= Promise.resolve().then(() => processCommands(services)).catch(() => ({}));
|
|
139
|
+
return Object.fromEntries(await Promise.all(services.map(async status => {
|
|
140
|
+
const pkg = PACKAGES[status.id];
|
|
141
|
+
const latest = (async () => {
|
|
142
|
+
try {
|
|
143
|
+
const url = pkg.pypi ? `https://pypi.org/pypi/${pkg.name}/json` : `https://registry.npmjs.org/${encodeURIComponent(pkg.name)}/latest`;
|
|
144
|
+
const data = await request(url, 3000);
|
|
145
|
+
return cleanVersion(pkg.pypi ? data?.info?.version : data?.version);
|
|
146
|
+
} catch { return null; }
|
|
147
|
+
})();
|
|
148
|
+
const installed = (async () => {
|
|
149
|
+
if (status.status === "running" && pkg.health && baseUrl(status.url)) {
|
|
150
|
+
try {
|
|
151
|
+
const data = await request(`${baseUrl(status.url)}${pkg.health}`, 2000);
|
|
152
|
+
const version = cleanVersion(data?.version);
|
|
153
|
+
if (version && (!pkg.service || data?.service === pkg.service)) return version;
|
|
154
|
+
} catch {}
|
|
155
|
+
}
|
|
156
|
+
try {
|
|
157
|
+
const command = status.status === "running" ? (await readCommands())[status.pid] : null;
|
|
158
|
+
return cleanVersion(await installedVersion(status, command));
|
|
159
|
+
} catch { return null; }
|
|
160
|
+
})();
|
|
161
|
+
const [version, latestVersion] = await Promise.all([installed, latest]);
|
|
162
|
+
const comparison = compareVersions(version, latestVersion);
|
|
163
|
+
return [status.id, { version, latestVersion, updateAvailable: comparison === null ? null : comparison < 0 }];
|
|
164
|
+
})));
|
|
165
|
+
}
|