@drakonkat/ai-helper 1.1.0 → 1.1.1

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/CHANGELOG.md CHANGED
@@ -4,6 +4,13 @@ All notable changes to **`ai-helper` (`aih`)** are documented in this file.
4
4
 
5
5
  ---
6
6
 
7
+ ## [1.1.1] - 2026-08-27
8
+
9
+ ### Updates
10
+ - Added TUI updates and fixed the agentMemory dashboard flow.
11
+
12
+ ---
13
+
7
14
  ## [1.1.0] - 2026-08-27
8
15
 
9
16
  ### 🚀 New Features
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drakonkat/ai-helper",
3
- "version": "1.1.0",
3
+ "version": "1.1.1",
4
4
  "description": "Zero-config background service manager, auto-discovery daemon & dashboard launcher for AI agent ecosystems (pxpipe, ocx, agentmemory, headroom)",
5
5
  "main": "src/index.js",
6
6
  "module": "src/index.js",
package/src/index.js CHANGED
@@ -24,6 +24,7 @@ function printHelp() {
24
24
 
25
25
  ${bold("COMMANDS:")}
26
26
  ${yellow("status")}, ${yellow("ps")} Show status, PID, uptime, and web dashboard URLs
27
+ ${yellow("status -ui")} Interactive live dashboard: manage services and watch the AI pipeline
27
28
  ${yellow("open")}, ${yellow("dash")} [services...] Open web dashboard(s) directly in your default browser
28
29
  ${yellow("start")}, ${yellow("up")} [services...] Start all or specified services (pxpipe, ocx, agentmemory, headroom)
29
30
  ${yellow("stop")}, ${yellow("down")} [services...] Stop all or specified services
@@ -43,6 +44,7 @@ ${bold("OPTIONS:")}
43
44
  ${gray("-n, --lines <num>")} Number of log lines to show (default: 50)
44
45
  ${gray("-f, --follow")} Follow log output in real-time
45
46
  ${gray("--json")} Output results in JSON format
47
+ ${gray("-ui, --ui")} Open the interactive dashboard (status only, requires a TTY)
46
48
 
47
49
  ${bold("EXAMPLES:")}
48
50
  ${dim("$")} ${cyan("npx ai-helper")} status
@@ -134,6 +136,7 @@ export async function main() {
134
136
 
135
137
  let jsonOutput = false;
136
138
  let follow = false;
139
+ let uiMode = false;
137
140
  let lines = 50;
138
141
  const positionalArgs = [];
139
142
 
@@ -141,6 +144,8 @@ export async function main() {
141
144
  const arg = rawArgs[i];
142
145
  if (arg === "--json") {
143
146
  jsonOutput = true;
147
+ } else if (arg === "-ui" || arg === "--ui") {
148
+ uiMode = true;
144
149
  } else if (arg === "-f" || arg === "--follow") {
145
150
  follow = true;
146
151
  } else if (arg === "-n" || arg === "--lines") {
@@ -172,6 +177,14 @@ export async function main() {
172
177
  case "ps":
173
178
  case "ls":
174
179
  case "list": {
180
+ // Interactive mode needs a real terminal: piping or redirecting falls
181
+ // back to the plain table so scripts keep working.
182
+ if (uiMode && !jsonOutput && process.stdout.isTTY && process.stdin.isTTY) {
183
+ const { runDashboard } = await import("./tui.js");
184
+ await runDashboard();
185
+ return;
186
+ }
187
+
175
188
  const statuses = await manager.getStatus(targets.length > 0 ? targets : undefined);
176
189
 
177
190
  if (jsonOutput) {
package/src/tui.js ADDED
@@ -0,0 +1,539 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+ import { SERVICES, APP_NAME, VERSION } from "./config.js";
4
+ import { manager } from "./manager.js";
5
+ import {
6
+ badgeStatus,
7
+ bold,
8
+ cyan,
9
+ dim,
10
+ gray,
11
+ green,
12
+ magenta,
13
+ red,
14
+ renderTable,
15
+ stripAnsi,
16
+ underline,
17
+ white,
18
+ yellow,
19
+ } from "./utils/format.js";
20
+ import { killProcessTree, openBrowser } from "./utils/process.js";
21
+ import {
22
+ baseUrl,
23
+ diffRates,
24
+ fetchText,
25
+ parseProm,
26
+ probeChain,
27
+ readSavingsBreakdown,
28
+ tailJsonl,
29
+ } from "./utils/metrics.js";
30
+
31
+ const TICK_MS = 1000;
32
+ const MAX_EVENTS = 200;
33
+
34
+ const ALT_SCREEN_ON = "\x1b[?1049h";
35
+ const ALT_SCREEN_OFF = "\x1b[?1049l";
36
+ const CURSOR_HIDE = "\x1b[?25l";
37
+ const CURSOR_SHOW = "\x1b[?25h";
38
+ const CURSOR_HOME = "\x1b[H";
39
+ const CLEAR_LINE = "\x1b[K";
40
+ const CLEAR_BELOW = "\x1b[J";
41
+ const RESET = "\x1b[0m";
42
+ const KEY_UP = "\x1b[A";
43
+ const KEY_DOWN = "\x1b[B";
44
+
45
+ /**
46
+ * Location of headroom's append-only savings event log: the only real-time
47
+ * per-request source in the ecosystem (pxpipe exposes no API).
48
+ * @returns {string}
49
+ */
50
+ function getEventsFilePath() {
51
+ const custom = process.env.HEADROOM_HOME;
52
+ const base = custom && custom.trim().length > 0 ? custom : join(homedir(), ".headroom");
53
+ return join(base, "savings_events.jsonl");
54
+ }
55
+
56
+ /**
57
+ * Truncates a possibly coloured string to a visible width, keeping escape
58
+ * sequences intact and always closing with a reset.
59
+ * @param {string} text
60
+ * @param {number} width
61
+ * @returns {string}
62
+ */
63
+ function clip(text, width) {
64
+ if (width <= 0) return "";
65
+ const str = String(text);
66
+ if (stripAnsi(str).length <= width) return str;
67
+
68
+ let out = "";
69
+ let visible = 0;
70
+ let i = 0;
71
+ while (i < str.length && visible < width) {
72
+ if (str[i] === "\x1b") {
73
+ const end = str.indexOf("m", i);
74
+ if (end === -1) break;
75
+ out += str.slice(i, end + 1);
76
+ i = end + 1;
77
+ continue;
78
+ }
79
+ out += str[i];
80
+ visible++;
81
+ i++;
82
+ }
83
+ return out + RESET;
84
+ }
85
+
86
+ /**
87
+ * Compact human formatting for counters and rates.
88
+ * @param {number | null | undefined} value
89
+ * @param {number} [decimals]
90
+ * @returns {string}
91
+ */
92
+ function num(value, decimals = 0) {
93
+ if (value === null || value === undefined || !Number.isFinite(value)) return "-";
94
+ if (Math.abs(value) >= 1000000) return `${(value / 1000000).toFixed(1)}M`;
95
+ if (Math.abs(value) >= 1000) return `${(value / 1000).toFixed(1)}k`;
96
+ return value.toFixed(decimals);
97
+ }
98
+
99
+ /**
100
+ * @param {number | null | undefined} value
101
+ * @returns {string}
102
+ */
103
+ function pct(value) {
104
+ if (value === null || value === undefined || !Number.isFinite(value)) return "-";
105
+ return `${(value * 100).toFixed(1)}%`;
106
+ }
107
+
108
+ /**
109
+ * Colours a pipeline node by its live state.
110
+ * @param {{ label: string; state: string }} node
111
+ * @returns {string}
112
+ */
113
+ function paintNode(node) {
114
+ const label = `[ ${node.label} ]`;
115
+ switch (node.state) {
116
+ case "running":
117
+ return green(bold(label));
118
+ case "error":
119
+ return red(bold(label));
120
+ case "stopped":
121
+ return gray(label);
122
+ default:
123
+ return dim(label);
124
+ }
125
+ }
126
+
127
+ export class Dashboard {
128
+ constructor() {
129
+ this.statuses = [];
130
+ this.metrics = null;
131
+ this.rates = {};
132
+ this.prevMetrics = null;
133
+ this.prevAt = 0;
134
+ this.chain = [];
135
+ this.health = null;
136
+ this.events = [];
137
+ this.eventsOffset = undefined;
138
+ this.eventsFile = getEventsFilePath();
139
+ this.eventsFileSeen = false;
140
+ this.savings = null;
141
+ this.selected = 0;
142
+ this.status = "";
143
+ this.busy = false;
144
+ this.running = false;
145
+ this.timer = null;
146
+ this.refreshing = false;
147
+ }
148
+
149
+ /** @returns {any} */
150
+ currentService() {
151
+ return this.statuses[this.selected];
152
+ }
153
+
154
+ /**
155
+ * One data tick. Every source is optional: a failing fetch degrades its own
156
+ * panel and never breaks the loop.
157
+ */
158
+ async refresh() {
159
+ if (this.refreshing) return;
160
+ this.refreshing = true;
161
+ try {
162
+ this.statuses = await manager.getStatus();
163
+ if (this.selected >= this.statuses.length) {
164
+ this.selected = Math.max(0, this.statuses.length - 1);
165
+ }
166
+
167
+ const headroom = this.statuses.find(s => s.id === "headroom");
168
+ const headroomBase = headroom && headroom.status === "running" ? baseUrl(headroom.url) : "";
169
+
170
+ const metricsText = headroomBase ? await fetchText(`${headroomBase}/metrics`, 2000) : null;
171
+ if (metricsText) {
172
+ const parsed = parseProm(metricsText);
173
+ const now = Date.now();
174
+ this.rates = diffRates(this.prevMetrics, parsed, now - this.prevAt);
175
+ this.prevMetrics = parsed;
176
+ this.prevAt = now;
177
+ this.metrics = parsed;
178
+ } else {
179
+ this.metrics = null;
180
+ this.rates = {};
181
+ this.prevMetrics = null;
182
+ }
183
+
184
+ const probed = await probeChain(this.statuses);
185
+ this.chain = probed.nodes;
186
+ this.health = probed.health;
187
+
188
+ const tail = tailJsonl(this.eventsFile, this.eventsOffset, MAX_EVENTS);
189
+ this.eventsOffset = tail.offset;
190
+ if (tail.offset > 0) this.eventsFileSeen = true;
191
+ if (tail.events.length > 0) {
192
+ this.events = this.events.concat(tail.events).slice(-MAX_EVENTS);
193
+ }
194
+
195
+ this.savings = readSavingsBreakdown();
196
+ } catch (err) {
197
+ this.status = red(`Refresh error: ${err?.message || err}`);
198
+ } finally {
199
+ this.refreshing = false;
200
+ }
201
+ }
202
+
203
+ /**
204
+ * Builds the whole screen as an array of lines.
205
+ * @returns {string[]}
206
+ */
207
+ buildLines() {
208
+ const width = Math.max(40, process.stdout.columns || 100);
209
+ const height = Math.max(12, process.stdout.rows || 30);
210
+ const lines = [];
211
+
212
+ const title = `${bold(cyan(APP_NAME))} ${gray("v" + VERSION)} ${dim("live dashboard")}`;
213
+ const clock = dim(new Date().toLocaleTimeString());
214
+ const titlePad = Math.max(1, width - stripAnsi(title).length - stripAnsi(clock).length);
215
+ lines.push(title + " ".repeat(titlePad) + clock);
216
+ lines.push(gray("-".repeat(width)));
217
+
218
+ const headers = [
219
+ " ",
220
+ "SERVICE",
221
+ "STATUS",
222
+ { header: "PID", align: "right" },
223
+ { header: "UPTIME", align: "right" },
224
+ "URL",
225
+ ];
226
+ const rows = this.statuses.map((s, idx) => {
227
+ const active = idx === this.selected;
228
+ return [
229
+ active ? cyan(bold(">")) : " ",
230
+ active ? bold(white(s.id)) : bold(s.id),
231
+ badgeStatus(s.status),
232
+ s.pid ? String(s.pid) : dim("-"),
233
+ s.status === "running" ? s.uptime : dim("-"),
234
+ s.status === "running" && s.url && s.url !== "-" ? cyan(underline(s.url)) : dim(s.url || "-"),
235
+ ];
236
+ });
237
+ if (rows.length > 0) {
238
+ const table = renderTable(headers, rows).split("\n");
239
+ for (const line of table) lines.push(line);
240
+ } else {
241
+ lines.push(dim(" No services."));
242
+ }
243
+ lines.push("");
244
+
245
+ lines.push(bold("PIPELINE"));
246
+ lines.push(" " + this.chain.map(paintNode).join(gray(" --> ")));
247
+
248
+ const details = this.chain
249
+ .map(n => (n.detail ? dim(`${n.label}: ${n.detail}`) : ""))
250
+ .filter(Boolean)
251
+ .join(dim(" | "));
252
+ if (details) lines.push(" " + details);
253
+
254
+ if (this.metrics) {
255
+ const m = this.metrics;
256
+ const r = this.rates;
257
+ const inTok = m.headroom_tokens_input_total;
258
+ const savedTok = m.headroom_tokens_saved_total;
259
+ const savingRatio =
260
+ Number.isFinite(inTok) && Number.isFinite(savedTok) && inTok + savedTok > 0
261
+ ? savedTok / (inTok + savedTok)
262
+ : null;
263
+ const cacheRatio =
264
+ Number.isFinite(m.headroom_requests_cached_total) && m.headroom_requests_total > 0
265
+ ? m.headroom_requests_cached_total / m.headroom_requests_total
266
+ : null;
267
+ const avgLatency =
268
+ Number.isFinite(m.headroom_latency_ms_sum) && m.headroom_latency_ms_count > 0
269
+ ? m.headroom_latency_ms_sum / m.headroom_latency_ms_count
270
+ : null;
271
+ const latencyText = avgLatency === null ? "-" : `${Math.round(avgLatency)}ms`;
272
+
273
+ const cells = [
274
+ `${dim("req/s")} ${bold(num(r.headroom_requests_total, 2))}`,
275
+ `${dim("attive")} ${bold(num(m.headroom_inbound_requests_active))}`,
276
+ `${dim("tok in/s")} ${bold(num(r.headroom_tokens_input_total, 1))}`,
277
+ `${dim("tok out/s")} ${bold(num(r.headroom_tokens_output_total, 1))}`,
278
+ `${dim("risparmio")} ${green(bold(pct(savingRatio)))}`,
279
+ `${dim("cache")} ${bold(pct(cacheRatio))}`,
280
+ `${dim("latenza")} ${bold(latencyText)}`,
281
+ ];
282
+ lines.push(" " + cells.join(dim(" . ")));
283
+ } else {
284
+ lines.push(" " + dim("metriche non disponibili (headroom non raggiungibile)"));
285
+ }
286
+ lines.push("");
287
+
288
+ lines.push(bold("STREAM RICHIESTE") + dim(" " + this.eventsFile));
289
+
290
+ // Every event in the stream is source "proxy": headroom is the only service
291
+ // that reports per-request savings. The split below is the one place that
292
+ // says how much came from compression versus provider cache reuse.
293
+ if (this.savings) {
294
+ const sv = this.savings;
295
+ const savingsCells = [
296
+ `${dim("risparmio")} ${green(bold(num(sv.total)))}`,
297
+ `${dim("compress")} ${bold(num(sv.compression))}`,
298
+ `${dim("cache")} ${bold(num(sv.cacheReads))}`,
299
+ `${dim("inviati")} ${bold(num(sv.submitted))}`,
300
+ `${dim("efficienza")} ${green(bold(pct(sv.ratio)))}`,
301
+ ];
302
+ lines.push(" " + savingsCells.join(dim(" . ")));
303
+ }
304
+
305
+ const footerLines = 3;
306
+ const slots = Math.max(1, height - lines.length - footerLines);
307
+
308
+ if (this.events.length === 0) {
309
+ lines.push(
310
+ " " +
311
+ dim(
312
+ this.eventsFileSeen
313
+ ? "in attesa di richieste..."
314
+ : "nessun file eventi: headroom non ha ancora scritto savings_events.jsonl"
315
+ )
316
+ );
317
+ } else {
318
+ for (const ev of this.events.slice(-slots)) {
319
+ const time = ev.ts ? String(ev.ts).slice(11, 19) : "--:--:--";
320
+ const before = Number(ev.before);
321
+ const after = Number(ev.after);
322
+ const saved = Number(ev.saved);
323
+ const ratio = Number.isFinite(before) && before > 0 ? saved / before : null;
324
+ const cost = Number(ev.cost_usd);
325
+ const cells = [
326
+ gray(time),
327
+ magenta(String(ev.model || "?").padEnd(16).slice(0, 16)),
328
+ `${dim("tok")} ${num(before)}${gray("->")}${num(after)}`,
329
+ green(`-${num(saved)} (${pct(ratio)})`),
330
+ dim(Number.isFinite(cost) ? "$" + cost.toFixed(4) : "-"),
331
+ dim(String(ev.source || ev.client || "")),
332
+ ];
333
+ lines.push(" " + cells.join(" "));
334
+ }
335
+ }
336
+
337
+ while (lines.length < height - footerLines) lines.push("");
338
+ lines.push(gray("-".repeat(width)));
339
+
340
+ const svc = this.currentService();
341
+ const target = svc ? bold(svc.id) : dim("-");
342
+ const keys = [
343
+ `${dim("up/down")} seleziona (${target})`,
344
+ `${dim("s")} start`,
345
+ `${dim("x")} stop`,
346
+ `${dim("r")} restart`,
347
+ `${dim("k")} kill`,
348
+ `${dim("o")} dashboard`,
349
+ `${dim("q")} esci`,
350
+ ];
351
+ lines.push(keys.join(" "));
352
+ lines.push(this.busy ? yellow(this.status) : this.status || dim("pronto"));
353
+
354
+ return lines.slice(0, height).map(line => clip(line, width));
355
+ }
356
+
357
+ render() {
358
+ if (!this.running) return;
359
+ const painted = this.buildLines().map(line => line + CLEAR_LINE);
360
+ process.stdout.write(CURSOR_HOME + painted.join("\n") + CLEAR_BELOW);
361
+ }
362
+
363
+ /**
364
+ * Runs a manager action, keeping the UI responsive and always refreshing
365
+ * afterwards so the table reflects the new reality.
366
+ * @param {string} label
367
+ * @param {(svc: any) => Promise<any>} action
368
+ */
369
+ async runAction(label, action) {
370
+ if (this.busy) return;
371
+ const svc = this.currentService();
372
+ if (!svc) return;
373
+
374
+ this.busy = true;
375
+ this.status = `${label} ${svc.id}...`;
376
+ this.render();
377
+
378
+ try {
379
+ const res = await action(svc);
380
+ const message = res?.message || `${label} ${svc.id}: fatto`;
381
+ this.status = res && res.success === false ? red(message) : green(message);
382
+ } catch (err) {
383
+ this.status = red(`${label} ${svc.id}: ${err?.message || err}`);
384
+ } finally {
385
+ this.busy = false;
386
+ }
387
+
388
+ await this.refresh();
389
+ this.render();
390
+ }
391
+
392
+ /**
393
+ * @param {string} key
394
+ */
395
+ onKey(key) {
396
+ if (key === "\u0003" || key === "q") {
397
+ this.stop();
398
+ return;
399
+ }
400
+
401
+ switch (key) {
402
+ case KEY_UP:
403
+ this.selected = Math.max(0, this.selected - 1);
404
+ this.render();
405
+ return;
406
+ case KEY_DOWN:
407
+ this.selected = Math.min(this.statuses.length - 1, this.selected + 1);
408
+ this.render();
409
+ return;
410
+ case "s":
411
+ this.runAction("Avvio", svc => manager.startService(svc.id));
412
+ return;
413
+ case "x":
414
+ this.runAction("Stop", svc => manager.stopService(svc.id));
415
+ return;
416
+ case "r":
417
+ this.runAction("Riavvio", svc => manager.restartService(svc.id));
418
+ return;
419
+ case "k":
420
+ this.runAction("Kill", async svc => {
421
+ if (!svc.pid) return { success: false, message: `${svc.id}: nessun PID da terminare` };
422
+ return killProcessTree(svc.pid);
423
+ });
424
+ return;
425
+ case "o":
426
+ this.runAction("Dashboard", async svc => {
427
+ const url = svc.url && svc.url !== "-" ? svc.url : SERVICES[svc.id]?.defaultUrl;
428
+ if (!url) return { success: false, message: `${svc.id}: nessuna URL disponibile` };
429
+ openBrowser(url);
430
+ return { success: true, message: `Aperto ${url}` };
431
+ });
432
+ return;
433
+ default:
434
+ return;
435
+ }
436
+ }
437
+
438
+ enterScreen() {
439
+ process.stdout.write(ALT_SCREEN_ON + CURSOR_HIDE);
440
+ if (process.stdin.isTTY) {
441
+ process.stdin.setRawMode(true);
442
+ process.stdin.resume();
443
+ process.stdin.setEncoding("utf-8");
444
+ process.stdin.on("data", this.onData);
445
+ }
446
+ process.stdout.on("resize", this.onResize);
447
+ process.on("SIGINT", this.onSigint);
448
+ process.on("uncaughtException", this.onFatal);
449
+ process.on("unhandledRejection", this.onFatal);
450
+ }
451
+
452
+ /** Always restores the terminal, even on a crash. */
453
+ leaveScreen() {
454
+ if (process.stdin.isTTY) {
455
+ try {
456
+ process.stdin.setRawMode(false);
457
+ } catch {}
458
+ process.stdin.off("data", this.onData);
459
+ process.stdin.pause();
460
+ }
461
+ process.stdout.off("resize", this.onResize);
462
+ process.off("SIGINT", this.onSigint);
463
+ process.off("uncaughtException", this.onFatal);
464
+ process.off("unhandledRejection", this.onFatal);
465
+ process.stdout.write(CURSOR_SHOW + ALT_SCREEN_OFF);
466
+ }
467
+
468
+ stop() {
469
+ if (!this.running) return;
470
+ this.running = false;
471
+ if (this.timer) clearInterval(this.timer);
472
+ this.timer = null;
473
+ this.leaveScreen();
474
+ }
475
+
476
+ async start() {
477
+ this.onData = chunk => {
478
+ for (const key of splitKeys(String(chunk))) this.onKey(key);
479
+ };
480
+ this.onResize = () => this.render();
481
+ this.onSigint = () => this.stop();
482
+ this.onFatal = err => {
483
+ this.stop();
484
+ console.error(red(`[aih] ${err?.message || err}`));
485
+ process.exitCode = 1;
486
+ };
487
+
488
+ this.running = true;
489
+ this.enterScreen();
490
+
491
+ await this.refresh();
492
+ this.render();
493
+
494
+ this.timer = setInterval(async () => {
495
+ if (!this.running || this.busy) return;
496
+ await this.refresh();
497
+ this.render();
498
+ }, TICK_MS);
499
+
500
+ await new Promise(resolve => {
501
+ const check = setInterval(() => {
502
+ if (!this.running) {
503
+ clearInterval(check);
504
+ resolve();
505
+ }
506
+ }, 100);
507
+ });
508
+ }
509
+ }
510
+
511
+ /**
512
+ * Splits a raw stdin chunk into individual keys, keeping arrow escape
513
+ * sequences whole so a fast keypress burst is not misread as letters.
514
+ * @param {string} chunk
515
+ * @returns {string[]}
516
+ */
517
+ export function splitKeys(chunk) {
518
+ const keys = [];
519
+ let i = 0;
520
+ while (i < chunk.length) {
521
+ if (chunk[i] === "\x1b" && chunk[i + 1] === "[" && chunk[i + 2]) {
522
+ keys.push(chunk.slice(i, i + 3));
523
+ i += 3;
524
+ continue;
525
+ }
526
+ keys.push(chunk[i]);
527
+ i++;
528
+ }
529
+ return keys;
530
+ }
531
+
532
+ /**
533
+ * Entry point for the interactive dashboard.
534
+ * @returns {Promise<void>}
535
+ */
536
+ export async function runDashboard() {
537
+ const dashboard = new Dashboard();
538
+ await dashboard.start();
539
+ }
@@ -0,0 +1,293 @@
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 stateOf = id => byId[id]?.status || "unknown";
267
+
268
+ const nodes = [
269
+ { id: "client", label: "client", state: "static", detail: "AI agents / CLI" },
270
+ { id: "headroom", label: "headroom", state: stateOf("headroom"), detail: baseUrl(byId.headroom?.url) },
271
+ { id: "pxpipe", label: "pxpipe", state: stateOf("pxpipe"), detail: baseUrl(byId.pxpipe?.url) },
272
+ { id: "upstream", label: "upstream", state: "static", detail: "" },
273
+ ];
274
+
275
+ const headroomBase = baseUrl(byId.headroom?.url);
276
+ const health = headroomBase ? await fetchJson(`${headroomBase}/health`, 2000) : null;
277
+
278
+ if (health) {
279
+ if (health.version) nodes[1].detail = `${nodes[1].detail} v${health.version}`.trim();
280
+ if (health.status && health.status !== "healthy") nodes[1].state = "error";
281
+
282
+ const upstream = health.checks?.upstream;
283
+ if (upstream?.url) {
284
+ // headroom reports where it actually forwards to, which is pxpipe.
285
+ nodes[2].detail = upstream.url;
286
+ if (upstream.status && upstream.status !== "healthy" && nodes[2].state === "running") {
287
+ nodes[2].state = "error";
288
+ }
289
+ }
290
+ }
291
+
292
+ return { nodes, health };
293
+ }
@@ -235,6 +235,35 @@ 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
+ * @returns {number}
250
+ */
251
+ export function resolveAgentmemoryViewerPort(ports) {
252
+ const candidates = (ports || []).filter(p => Number.isFinite(p) && p > 0);
253
+ if (candidates.length === 0) return AGENTMEMORY_DEFAULT_VIEWER;
254
+
255
+ // The engine port is the most reliable marker: it is the only one above the
256
+ // offset and always anchor + 46023, so it recovers the anchor by itself. This
257
+ // matters because the engine binds 0.0.0.0 while the rest of the quartet is
258
+ // loopback-only, so the engine is sometimes the only port we get to see.
259
+ const engine = candidates.find(p => p > AGENTMEMORY_ENGINE_OFFSET);
260
+ if (engine) return engine - AGENTMEMORY_ENGINE_OFFSET + AGENTMEMORY_VIEWER_OFFSET;
261
+
262
+ // Otherwise the lowest port is the REST anchor: REST is always bound, so the
263
+ // smallest one we can see is the base of the quartet.
264
+ return Math.min(...candidates) + AGENTMEMORY_VIEWER_OFFSET;
265
+ }
266
+
238
267
  /**
239
268
  * Scans the OS process table and listening ports to discover active services and their URLs.
240
269
  * @returns {Promise<Record<string, { pid: number; command: string; startedAt?: string; url?: string }>>}
@@ -344,14 +373,17 @@ export async function discoverRunningProcesses() {
344
373
  cmd.includes("iii.exe") ||
345
374
  (cmd.includes("agentmemory") && !cmd.includes("mcp") && !cmd.includes("aih ")))
346
375
  ) {
347
- const webPort = ports.find(p => p === 3113 || p === 43210 || (p > 1000 && p < 65000));
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);
348
380
  if (!discovered.agentmemory || cmd.includes("agentmemory/agentmemory") || cmd.includes("dist\\cli.mjs")) {
349
381
  discovered.agentmemory = {
350
382
  pid,
351
383
  command: cmd,
352
384
  startedAt,
353
- port: webPort || 3113,
354
- url: `http://localhost:${webPort || 3113}`,
385
+ port: viewerPort,
386
+ url: `http://localhost:${viewerPort}`,
355
387
  };
356
388
  }
357
389
  }
@@ -380,8 +412,10 @@ export async function discoverRunningProcesses() {
380
412
  if (ports.includes(10100) && discovered.ocx) {
381
413
  discovered.ocx.url = "http://localhost:10100";
382
414
  }
383
- if (ports.includes(3113) && discovered.agentmemory) {
384
- discovered.agentmemory.url = "http://localhost:3113";
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}`;
385
419
  }
386
420
  if (ports.includes(8787) && discovered.headroom) {
387
421
  discovered.headroom.url = "http://localhost:8787/dashboard";