@drakonkat/ai-helper 1.1.0 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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
+ }
@@ -0,0 +1,315 @@
1
+ import { existsSync, statSync, openSync, readSync, closeSync, readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+
5
+ /**
6
+ * On first read we only look at the tail of the events file, which is
7
+ * append-only and already several MB on an active machine.
8
+ */
9
+ const INITIAL_TAIL_BYTES = 64 * 1024;
10
+
11
+ /**
12
+ * Headroom keeps a rolling breakdown of where the token savings came from in
13
+ * subscription_state.json. This is the only place in the ecosystem that splits
14
+ * the total into compression vs provider cache reads: the per-request event log
15
+ * only ever reports source "proxy", and neither pxpipe nor agentmemory publish
16
+ * savings counters of their own.
17
+ * @returns {string}
18
+ */
19
+ export function getSavingsBreakdownPath() {
20
+ const custom = process.env.HEADROOM_HOME;
21
+ const base = custom && custom.trim().length > 0 ? custom : join(homedir(), ".headroom");
22
+ return join(base, "subscription_state.json");
23
+ }
24
+
25
+ /**
26
+ * Reads the savings breakdown. Returns null whenever the file is missing or
27
+ * malformed so the panel degrades instead of breaking the render loop.
28
+ * @param {string} [path]
29
+ * @returns {{ submitted: number, compression: number, cacheReads: number, total: number, ratio: number | null } | null}
30
+ */
31
+ export function readSavingsBreakdown(path) {
32
+ const file = path || getSavingsBreakdownPath();
33
+ if (!existsSync(file)) return null;
34
+
35
+ let parsed;
36
+ try {
37
+ parsed = JSON.parse(readFileSync(file, "utf-8"));
38
+ } catch {
39
+ return null;
40
+ }
41
+
42
+ const contribution = parsed?.contribution;
43
+ const saved = contribution?.tokens_saved;
44
+ if (!saved || typeof saved !== "object") return null;
45
+
46
+ const numeric = value => (Number.isFinite(Number(value)) ? Number(value) : 0);
47
+
48
+ const compression = numeric(saved.compression);
49
+ const cacheReads = numeric(saved.cache_reads);
50
+ const total = numeric(saved.total) || compression + cacheReads;
51
+ const submitted = numeric(contribution.tokens_submitted);
52
+
53
+ // The raw baseline is what would have been sent without any optimisation, so
54
+ // it is the only honest denominator for a savings percentage.
55
+ const baseline = numeric(contribution.raw_without_headroom) || submitted + total;
56
+
57
+ return {
58
+ submitted,
59
+ compression,
60
+ cacheReads,
61
+ total,
62
+ ratio: baseline > 0 ? total / baseline : null,
63
+ };
64
+ }
65
+
66
+ /**
67
+ * Parses a Prometheus text exposition payload into a flat name -> number map.
68
+ * Comment lines and labelled series are ignored: the dashboard only needs the
69
+ * plain global counters.
70
+ * @param {string} text
71
+ * @returns {Record<string, number>}
72
+ */
73
+ export function parseProm(text) {
74
+ const out = {};
75
+ if (!text || typeof text !== "string") return out;
76
+
77
+ for (const rawLine of text.split("\n")) {
78
+ const line = rawLine.trim();
79
+ if (line.length === 0 || line.startsWith("#")) continue;
80
+ if (line.includes("{")) continue;
81
+
82
+ const sep = line.lastIndexOf(" ");
83
+ if (sep <= 0) continue;
84
+
85
+ const name = line.slice(0, sep).trim();
86
+ const value = Number(line.slice(sep + 1).trim());
87
+ if (name.length === 0 || !Number.isFinite(value)) continue;
88
+
89
+ out[name] = value;
90
+ }
91
+
92
+ return out;
93
+ }
94
+
95
+ /**
96
+ * Turns two snapshots of cumulative counters into per-second rates.
97
+ * Returns null for a metric when no rate can be computed yet: no previous
98
+ * sample, a metric that just appeared, or a counter that went backwards
99
+ * (which means the service restarted).
100
+ * @param {Record<string, number> | null} prev
101
+ * @param {Record<string, number> | null} curr
102
+ * @param {number} deltaMs
103
+ * @returns {Record<string, number | null>}
104
+ */
105
+ export function diffRates(prev, curr, deltaMs) {
106
+ const rates = {};
107
+ if (!curr) return rates;
108
+
109
+ const usable = prev && Number.isFinite(deltaMs) && deltaMs > 0;
110
+
111
+ for (const key of Object.keys(curr)) {
112
+ if (!usable) {
113
+ rates[key] = null;
114
+ continue;
115
+ }
116
+
117
+ const before = prev[key];
118
+ if (typeof before !== "number") {
119
+ rates[key] = null;
120
+ continue;
121
+ }
122
+
123
+ const delta = curr[key] - before;
124
+ rates[key] = delta < 0 ? null : delta / (deltaMs / 1000);
125
+ }
126
+
127
+ return rates;
128
+ }
129
+
130
+ /**
131
+ * Incrementally reads new JSON lines from an append-only JSONL file.
132
+ * Only whole lines are consumed: the returned offset always points at a line
133
+ * boundary, so a half-written record is re-read on the next tick instead of
134
+ * being dropped. Malformed lines are skipped silently.
135
+ * @param {string} path
136
+ * @param {number} [fromOffset] Byte offset returned by a previous call.
137
+ * @param {number} [maxLines] Keep at most this many of the newest events.
138
+ * @returns {{ events: any[]; offset: number }}
139
+ */
140
+ export function tailJsonl(path, fromOffset, maxLines = 200) {
141
+ if (!path || !existsSync(path)) return { events: [], offset: 0 };
142
+
143
+ let size;
144
+ try {
145
+ size = statSync(path).size;
146
+ } catch {
147
+ return { events: [], offset: fromOffset || 0 };
148
+ }
149
+
150
+ let start;
151
+ if (typeof fromOffset === "number" && fromOffset >= 0 && fromOffset <= size) {
152
+ start = fromOffset;
153
+ } else {
154
+ // First read, or the file was truncated / rotated under us.
155
+ start = Math.max(0, size - INITIAL_TAIL_BYTES);
156
+ }
157
+
158
+ if (start >= size) return { events: [], offset: size };
159
+
160
+ const length = size - start;
161
+ const buffer = Buffer.alloc(length);
162
+ let fd;
163
+ try {
164
+ fd = openSync(path, "r");
165
+ readSync(fd, buffer, 0, length, start);
166
+ } catch {
167
+ return { events: [], offset: fromOffset || 0 };
168
+ } finally {
169
+ if (fd !== undefined) {
170
+ try {
171
+ closeSync(fd);
172
+ } catch {}
173
+ }
174
+ }
175
+
176
+ const text = buffer.toString("utf-8");
177
+ const lastNewline = text.lastIndexOf("\n");
178
+ if (lastNewline === -1) {
179
+ // No complete line in this window yet: stay where we are.
180
+ return { events: [], offset: start };
181
+ }
182
+
183
+ const consumed = text.slice(0, lastNewline + 1);
184
+ const offset = start + Buffer.byteLength(consumed, "utf-8");
185
+
186
+ const events = [];
187
+ const lines = text.slice(0, lastNewline).split("\n");
188
+ for (const line of lines.slice(-maxLines)) {
189
+ const trimmed = line.trim();
190
+ if (trimmed.length === 0) continue;
191
+ try {
192
+ events.push(JSON.parse(trimmed));
193
+ } catch {
194
+ // Truncated first line of the initial window, or a partial flush.
195
+ }
196
+ }
197
+
198
+ return { events, offset };
199
+ }
200
+
201
+ /**
202
+ * Strips any path from a service URL, leaving scheme://host:port.
203
+ * @param {string} [url]
204
+ * @returns {string}
205
+ */
206
+ export function baseUrl(url) {
207
+ if (!url || url === "-") return "";
208
+ try {
209
+ const parsed = new URL(url);
210
+ return parsed.origin;
211
+ } catch {
212
+ return "";
213
+ }
214
+ }
215
+
216
+ /**
217
+ * Fetches a URL with a hard timeout. Returns null on any failure so that a
218
+ * dead service degrades a panel instead of breaking the render loop.
219
+ * @param {string} url
220
+ * @param {number} timeoutMs
221
+ * @returns {Promise<string | null>}
222
+ */
223
+ export async function fetchText(url, timeoutMs = 2000) {
224
+ if (!url) return null;
225
+
226
+ const controller = new AbortController();
227
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
228
+ try {
229
+ const res = await fetch(url, { signal: controller.signal });
230
+ if (!res.ok) return null;
231
+ return await res.text();
232
+ } catch {
233
+ return null;
234
+ } finally {
235
+ clearTimeout(timer);
236
+ }
237
+ }
238
+
239
+ /**
240
+ * @param {string} url
241
+ * @param {number} timeoutMs
242
+ * @returns {Promise<any | null>}
243
+ */
244
+ export async function fetchJson(url, timeoutMs = 2000) {
245
+ const text = await fetchText(url, timeoutMs);
246
+ if (text === null) return null;
247
+ try {
248
+ return JSON.parse(text);
249
+ } catch {
250
+ return null;
251
+ }
252
+ }
253
+
254
+ /**
255
+ * Resolves the operational pipeline the AI calls flow through.
256
+ * The static chain (client -> headroom -> pxpipe -> upstream) is derived from
257
+ * the managed services; headroom's /health is used to confirm the live wiring
258
+ * and is optional, so the panel still renders when headroom is down.
259
+ * @param {Array<{ id: string; status: string; url?: string }>} statuses
260
+ * @returns {Promise<{ nodes: Array<{ id: string; label: string; state: string; detail: string }>; health: any | null }>}
261
+ */
262
+ export async function probeChain(statuses) {
263
+ const byId = {};
264
+ for (const svc of statuses || []) byId[svc.id] = svc;
265
+
266
+ const proxy = byId.proxy;
267
+ if (proxy?.proxyOptions) {
268
+ const preset = proxy.proxyOptions.preset || "none";
269
+ const stages = preset === "none" ? [] : preset.split("-").map(id => ({
270
+ id, label: id === "pxpipe" ? "pxpipe (libreria)" : id === "rtk" ? "rtk (pipe)" : "headroom (compress)",
271
+ state: id === "pxpipe" ? proxy.status : "static", detail: id === "headroom" ? proxy.proxyOptions.headroomUrl : "",
272
+ }));
273
+ return { nodes: [
274
+ { id: "client", label: "client", state: "static", detail: "AI agents / CLI" },
275
+ { id: "proxy", label: "aih proxy", state: proxy.status, detail: proxy.url },
276
+ ...stages,
277
+ { id: "upstream", label: "upstream", state: "static", detail: proxy.proxyOptions.upstream },
278
+ ], health: null };
279
+ }
280
+
281
+ const stateOf = id => byId[id]?.status || "unknown";
282
+
283
+ const nodes = [
284
+ { id: "client", label: "client", state: "static", detail: "AI agents / CLI" },
285
+ { id: "headroom", label: "headroom", state: stateOf("headroom"), detail: baseUrl(byId.headroom?.url) },
286
+ { id: "pxpipe", label: "pxpipe", state: stateOf("pxpipe"), detail: baseUrl(byId.pxpipe?.url) },
287
+ { id: "upstream", label: "upstream", state: "unknown", detail: "" },
288
+ ];
289
+
290
+ const headroomBase = baseUrl(byId.headroom?.url);
291
+ const health = headroomBase && nodes[1].state === "running"
292
+ ? await fetchJson(`${headroomBase}/health`, 2000)
293
+ : null;
294
+
295
+ const checkedState = (status, fallback) => status === "healthy"
296
+ ? "healthy"
297
+ : status === "unhealthy" || status === "error" || status === "degraded" ? "error" : fallback;
298
+
299
+ if (health) {
300
+ if (health.version) nodes[1].detail = `${nodes[1].detail} v${health.version}`.trim();
301
+ nodes[1].state = checkedState(health.status, nodes[1].state);
302
+
303
+ const upstream = health.checks?.upstream;
304
+ if (upstream?.url) {
305
+ // A configured forwarder is not necessarily the managed pxpipe instance.
306
+ if (baseUrl(upstream.url) && baseUrl(upstream.url) === baseUrl(byId.pxpipe?.url)) {
307
+ if (nodes[2].state === "running") nodes[2].state = checkedState(upstream.status, nodes[2].state);
308
+ } else {
309
+ nodes[1].detail += ` | inoltro: ${upstream.url} (destinazione non verificata)`;
310
+ }
311
+ }
312
+ }
313
+
314
+ return { nodes, health };
315
+ }
@@ -235,159 +235,139 @@ export function spawnDetachedProcess(command, logFilePath, options) {
235
235
  return { pid: proc.pid };
236
236
  }
237
237
 
238
+ // agentmemory binds a quartet derived from one anchor port N:
239
+ // REST N | streams N+1 | viewer N+2 | engine N+46023
240
+ const AGENTMEMORY_ENGINE_OFFSET = 46023;
241
+ const AGENTMEMORY_VIEWER_OFFSET = 2;
242
+ const AGENTMEMORY_DEFAULT_VIEWER = 3113;
243
+
244
+ /**
245
+ * Resolves the agentmemory viewer port from the ports a process is listening on.
246
+ * The engine port is the one that binds 0.0.0.0 and is usually discovered first,
247
+ * but the only browsable dashboard is the viewer, so derive it from the anchor.
248
+ * @param {number[]} ports
249
+ * @param {number[]} [viewerPorts] Ports owned by the Node viewer, not the iii engine.
250
+ * @returns {number}
251
+ */
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];
256
+ const candidates = (ports || []).filter(p => Number.isFinite(p) && p > 0);
257
+ if (candidates.length === 0) return AGENTMEMORY_DEFAULT_VIEWER;
258
+
259
+ // The engine port is the most reliable marker: it is the only one above the
260
+ // offset and always anchor + 46023, so it recovers the anchor by itself. This
261
+ // matters because the engine binds 0.0.0.0 while the rest of the quartet is
262
+ // loopback-only, so the engine is sometimes the only port we get to see.
263
+ const engine = candidates.find(p => p > AGENTMEMORY_ENGINE_OFFSET);
264
+ if (engine) return engine - AGENTMEMORY_ENGINE_OFFSET + AGENTMEMORY_VIEWER_OFFSET;
265
+
266
+ // Otherwise the lowest port is the REST anchor: REST is always bound, so the
267
+ // smallest one we can see is the base of the quartet.
268
+ return Math.min(...candidates) + AGENTMEMORY_VIEWER_OFFSET;
269
+ }
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
+
238
351
  /**
239
352
  * Scans the OS process table and listening ports to discover active services and their URLs.
240
353
  * @returns {Promise<Record<string, { pid: number; command: string; startedAt?: string; url?: string }>>}
241
354
  */
242
- export async function discoverRunningProcesses() {
355
+ export async function discoverRunningProcesses({ knownServices = {} } = {}) {
243
356
  const discovered = {};
244
357
  const currentPid = process.pid;
245
358
 
246
359
  if (process.platform === "win32") {
247
360
  try {
361
+ // Keep parents and children even when elevation hides their command lines.
248
362
  const script = `
249
- $procs = Get-CimInstance Win32_Process | Where-Object {
250
- $_.ProcessId -ne ${currentPid} -and
251
- $_.CommandLine -and
252
- ($_.CommandLine -match 'pxpipe-proxy|ocx|agentmemory|iii|headroom') -and
253
- ($_.CommandLine -notmatch 'ai-helper|\\baih(\\.exe)?\\b|bin\\\\cli\\.js|Get-CimInstance|Where-Object|Select-Object')
254
- } | Select-Object ProcessId, ParentProcessId, Name, CommandLine, CreationDate
255
-
256
- $ports = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue | Select-Object LocalPort, OwningProcess
257
-
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
258
367
  @{ Procs = $procs; Ports = $ports } | ConvertTo-Json -Depth 3
259
368
  `;
260
-
261
369
  const res = await execCommand("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]);
262
- if (!res.stdout.trim()) return discovered;
263
-
264
- let data;
265
- try {
266
- data = JSON.parse(res.stdout.trim());
267
- } catch {
268
- return discovered;
269
- }
270
-
271
- const procList = data?.Procs ? (Array.isArray(data.Procs) ? data.Procs : [data.Procs]) : [];
272
- const portList = data?.Ports ? (Array.isArray(data.Ports) ? data.Ports : [data.Ports]) : [];
273
-
274
- const pidToPorts = {};
275
- for (const p of portList) {
276
- if (p?.OwningProcess && p?.LocalPort) {
277
- if (!pidToPorts[p.OwningProcess]) pidToPorts[p.OwningProcess] = [];
278
- pidToPorts[p.OwningProcess].push(p.LocalPort);
279
- }
280
- }
281
-
282
- for (const item of procList) {
283
- const cmd = item.CommandLine || "";
284
- const pid = item.ProcessId;
285
- if (!pid || pid === currentPid || !isPidRunning(pid)) continue;
286
-
287
- // Skip any ai-helper / aih CLI executions
288
- if (cmd.includes("bin/cli.js") || cmd.includes("bin\\cli.js") || /\baih(\.exe)?\b/i.test(cmd)) {
289
- continue;
290
- }
291
-
292
- let startedAt;
293
- if (item.CreationDate) {
294
- const match = String(item.CreationDate).match(/\/Date\((\d+)\)\//);
295
- if (match) {
296
- startedAt = new Date(parseInt(match[1], 10)).toISOString();
297
- } else {
298
- const d = new Date(item.CreationDate);
299
- if (!isNaN(d.getTime())) {
300
- startedAt = d.toISOString();
301
- }
302
- }
303
- }
304
-
305
- const ports = pidToPorts[pid] || [];
306
-
307
- // 1. pxpipe
308
- if (cmd.includes("pxpipe-proxy")) {
309
- if (!discovered.pxpipe || (item.Name && item.Name.toLowerCase() === "node.exe" && cmd.includes("cli.js"))) {
310
- const webPort = ports.find(p => p > 1000 && p < 65000) || (discovered.pxpipe?.port);
311
- discovered.pxpipe = {
312
- pid,
313
- command: cmd,
314
- startedAt,
315
- port: webPort,
316
- url: webPort ? `http://localhost:${webPort}` : "http://localhost:47821",
317
- };
318
- }
319
- }
320
-
321
- // 2. ocx
322
- if (cmd.includes("ocx.mjs") || cmd.includes("opencodex") || (cmd.includes("ocx start") && !cmd.includes("aih "))) {
323
- const webPort = ports.find(p => p === 10100 || (p > 1000 && p < 65000));
324
- if (!discovered.ocx || cmd.includes("ocx.mjs start")) {
325
- discovered.ocx = {
326
- pid,
327
- command: cmd,
328
- startedAt,
329
- port: webPort || 10100,
330
- url: `http://localhost:${webPort || 10100}`,
331
- };
332
- }
333
- }
334
-
335
- // 3. agentmemory (daemon / iii-engine only, strictly exclude MCP stdio shims)
336
- const isMcpShim = cmd.includes("agentmemory-mcp") || cmd.includes("@agentmemory/mcp") || cmd.includes("agentmemory mcp");
337
-
338
- if (
339
- !isMcpShim &&
340
- (cmd.includes("@agentmemory/agentmemory") ||
341
- cmd.includes("agentmemory\\dist\\cli.mjs") ||
342
- cmd.includes("agentmemory/dist/cli.mjs") ||
343
- cmd.includes("iii-config.yaml") ||
344
- cmd.includes("iii.exe") ||
345
- (cmd.includes("agentmemory") && !cmd.includes("mcp") && !cmd.includes("aih ")))
346
- ) {
347
- const webPort = ports.find(p => p === 3113 || p === 43210 || (p > 1000 && p < 65000));
348
- if (!discovered.agentmemory || cmd.includes("agentmemory/agentmemory") || cmd.includes("dist\\cli.mjs")) {
349
- discovered.agentmemory = {
350
- pid,
351
- command: cmd,
352
- startedAt,
353
- port: webPort || 3113,
354
- url: `http://localhost:${webPort || 3113}`,
355
- };
356
- }
357
- }
358
-
359
- // 4. headroom
360
- if (cmd.includes("headroom proxy") || (cmd.includes("headroom") && !cmd.includes("aih "))) {
361
- const webPort = ports.find(p => p === 8787 || (p > 1000 && p < 65000));
362
- if (!discovered.headroom || cmd.includes("headroom proxy")) {
363
- discovered.headroom = {
364
- pid,
365
- command: cmd,
366
- startedAt,
367
- port: webPort || 8787,
368
- url: `http://localhost:${webPort || 8787}/dashboard`,
369
- };
370
- }
371
- }
372
- }
373
-
374
- for (const p of procList) {
375
- const ports = pidToPorts[p.ProcessId] || [];
376
- if (ports.length > 0) {
377
- if (ports.includes(47821) && discovered.pxpipe) {
378
- discovered.pxpipe.url = "http://localhost:47821";
379
- }
380
- if (ports.includes(10100) && discovered.ocx) {
381
- discovered.ocx.url = "http://localhost:10100";
382
- }
383
- if (ports.includes(3113) && discovered.agentmemory) {
384
- discovered.agentmemory.url = "http://localhost:3113";
385
- }
386
- if (ports.includes(8787) && discovered.headroom) {
387
- discovered.headroom.url = "http://localhost:8787/dashboard";
388
- }
389
- }
390
- }
370
+ if (res.stdout.trim()) return discoverWindowsProcesses(JSON.parse(res.stdout), { knownServices });
391
371
  } catch {}
392
372
  } else {
393
373
  try {