@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.
package/src/tui.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { homedir } from "node:os";
2
2
  import { join } from "node:path";
3
- import { SERVICES, APP_NAME, VERSION } from "./config.js";
3
+ import { APP_NAME, VERSION } from "./config.js";
4
4
  import { manager } from "./manager.js";
5
5
  import {
6
6
  badgeStatus,
@@ -17,7 +17,9 @@ import {
17
17
  white,
18
18
  yellow,
19
19
  } from "./utils/format.js";
20
- import { killProcessTree, openBrowser } from "./utils/process.js";
20
+ import { killProcessTree } from "./utils/process.js";
21
+ import { readProxyStats, proxyStatsLines } from "./proxy-stats.js";
22
+ import { getServiceVersions } from "./utils/versions.js";
21
23
  import {
22
24
  baseUrl,
23
25
  diffRates,
@@ -29,6 +31,8 @@ import {
29
31
  } from "./utils/metrics.js";
30
32
 
31
33
  const TICK_MS = 1000;
34
+ const STALE_MS = 5 * TICK_MS;
35
+ const VERSION_CHECK_MS = 5 * 60 * 1000;
32
36
  const MAX_EVENTS = 200;
33
37
 
34
38
  const ALT_SCREEN_ON = "\x1b[?1049h";
@@ -105,39 +109,88 @@ function pct(value) {
105
109
  return `${(value * 100).toFixed(1)}%`;
106
110
  }
107
111
 
112
+ function age(timestamp, now) {
113
+ const seconds = Math.max(0, Math.floor((now - timestamp) / 1000));
114
+ if (seconds < 60) return `${seconds}s`;
115
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m`;
116
+ return `${Math.floor(seconds / 3600)}h`;
117
+ }
118
+
119
+ /** Wrap complete fields, falling back to words for long descriptions. */
120
+ function wrapCells(cells, width, separator = " | ", indent = " ") {
121
+ const lines = [];
122
+ let line = indent;
123
+ for (const cell of cells) {
124
+ if (stripAnsi(cell).length > width - indent.length) {
125
+ if (line !== indent) lines.push(line);
126
+ line = indent;
127
+ for (const word of cell.split(" ")) {
128
+ if (line !== indent && stripAnsi(line + " " + word).length > width) {
129
+ lines.push(line);
130
+ line = indent;
131
+ }
132
+ line += (line === indent ? "" : " ") + word;
133
+ }
134
+ continue;
135
+ }
136
+ const next = line === indent ? cell : dim(separator) + cell;
137
+ if (line !== indent && stripAnsi(line + next).length > width) {
138
+ lines.push(line);
139
+ line = indent + (separator === " -> " ? dim("-> ") : "") + cell;
140
+ } else line += next;
141
+ }
142
+ if (line !== indent) lines.push(line);
143
+ return lines.map(line => clip(line, width));
144
+ }
145
+
108
146
  /**
109
147
  * Colours a pipeline node by its live state.
110
148
  * @param {{ label: string; state: string }} node
111
149
  * @returns {string}
112
150
  */
113
151
  function paintNode(node) {
114
- const label = `[ ${node.label} ]`;
115
152
  switch (node.state) {
153
+ case "healthy":
154
+ return green(`[ ${node.label}: verificato ]`);
116
155
  case "running":
117
- return green(bold(label));
156
+ return `[ ${node.label}: processo attivo ]`;
118
157
  case "error":
119
- return red(bold(label));
158
+ return red(bold(`[ ${node.label}: errore ]`));
120
159
  case "stopped":
121
- return gray(label);
160
+ return dim(`[ ${node.label}: fermo ]`);
161
+ case "static":
162
+ return `[ ${node.label} ]`;
122
163
  default:
123
- return dim(label);
164
+ return yellow(`[ ${node.label}: non verificato ]`);
124
165
  }
125
166
  }
126
167
 
127
168
  export class Dashboard {
128
- constructor() {
169
+ constructor({ getVersions = getServiceVersions } = {}) {
129
170
  this.statuses = [];
171
+ this.getVersions = getVersions;
172
+ this.versions = {};
173
+ this.versionsKey = "";
174
+ this.versionsAt = 0;
175
+ this.versionsLoading = false;
130
176
  this.metrics = null;
177
+ this.metricsAt = null;
178
+ this.metricsError = null;
179
+ this.metricsKey = "";
180
+ this.sampleMs = null;
131
181
  this.rates = {};
132
182
  this.prevMetrics = null;
133
183
  this.prevAt = 0;
134
184
  this.chain = [];
185
+ this.chainAt = null;
186
+ this.showPipelineDetails = false;
135
187
  this.health = null;
136
188
  this.events = [];
137
189
  this.eventsOffset = undefined;
138
190
  this.eventsFile = getEventsFilePath();
139
191
  this.eventsFileSeen = false;
140
192
  this.savings = null;
193
+ this.proxyStats = null;
141
194
  this.selected = 0;
142
195
  this.status = "";
143
196
  this.busy = false;
@@ -151,6 +204,30 @@ export class Dashboard {
151
204
  return this.statuses[this.selected];
152
205
  }
153
206
 
207
+ /** Checks versions independently of the one-second status/metrics refresh. */
208
+ async refreshVersions() {
209
+ const key = JSON.stringify(this.statuses.map(s => [s.id, s.status, s.pid, s.url]));
210
+ if (key !== this.versionsKey) {
211
+ this.versionsKey = key;
212
+ this.versionsAt = 0;
213
+ this.versions = {};
214
+ }
215
+ if (this.versionsLoading || (this.versionsAt && Date.now() - this.versionsAt < VERSION_CHECK_MS)) return;
216
+
217
+ this.versionsLoading = true;
218
+ try {
219
+ const versions = await this.getVersions(this.statuses);
220
+ if (key === this.versionsKey) this.versions = versions;
221
+ } catch {
222
+ // An unavailable registry must not interrupt service controls or metrics.
223
+ if (key === this.versionsKey) this.versions = {};
224
+ } finally {
225
+ if (key === this.versionsKey) this.versionsAt = Date.now();
226
+ this.versionsLoading = false;
227
+ this.render();
228
+ }
229
+ }
230
+
154
231
  /**
155
232
  * One data tick. Every source is optional: a failing fetch degrades its own
156
233
  * panel and never breaks the loop.
@@ -160,6 +237,7 @@ export class Dashboard {
160
237
  this.refreshing = true;
161
238
  try {
162
239
  this.statuses = await manager.getStatus();
240
+ void this.refreshVersions();
163
241
  if (this.selected >= this.statuses.length) {
164
242
  this.selected = Math.max(0, this.statuses.length - 1);
165
243
  }
@@ -167,22 +245,35 @@ export class Dashboard {
167
245
  const headroom = this.statuses.find(s => s.id === "headroom");
168
246
  const headroomBase = headroom && headroom.status === "running" ? baseUrl(headroom.url) : "";
169
247
 
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);
248
+ const metricsKey = JSON.stringify([headroomBase, headroom?.pid]);
249
+ if (metricsKey !== this.metricsKey) this.prevMetrics = null;
250
+ this.metricsKey = metricsKey;
251
+ const [metricsText, probed] = await Promise.all([
252
+ headroomBase ? fetchText(`${headroomBase}/metrics`, 2000) : null,
253
+ probeChain(this.statuses),
254
+ ]);
255
+ const parsed = parseProm(metricsText);
256
+ const now = Date.now();
257
+ if (Object.keys(parsed).some(name => name.startsWith("headroom_"))) {
258
+ this.sampleMs = this.prevMetrics ? now - this.prevAt : null;
259
+ this.rates = diffRates(this.prevMetrics, parsed, this.sampleMs);
175
260
  this.prevMetrics = parsed;
176
261
  this.prevAt = now;
177
262
  this.metrics = parsed;
263
+ this.metricsAt = now;
264
+ this.metricsError = null;
178
265
  } else {
179
- this.metrics = null;
266
+ // Keep the last totals for diagnosis, never an old gauge or rate as live.
267
+ this.metricsError = headroom?.status !== "running" ? "Headroom non in esecuzione"
268
+ : !headroomBase ? "URL Headroom non disponibile"
269
+ : metricsText === null ? "raccolta fallita" : "risposta senza metriche Headroom";
180
270
  this.rates = {};
181
271
  this.prevMetrics = null;
272
+ this.sampleMs = null;
182
273
  }
183
274
 
184
- const probed = await probeChain(this.statuses);
185
275
  this.chain = probed.nodes;
276
+ this.chainAt = now;
186
277
  this.health = probed.health;
187
278
 
188
279
  const tail = tailJsonl(this.eventsFile, this.eventsOffset, MAX_EVENTS);
@@ -193,13 +284,73 @@ export class Dashboard {
193
284
  }
194
285
 
195
286
  this.savings = readSavingsBreakdown();
287
+ this.proxyStats = readProxyStats();
196
288
  } catch (err) {
289
+ this.metricsError = "aggiornamento fallito";
290
+ this.rates = {};
291
+ this.prevMetrics = null;
292
+ this.chainAt = null;
197
293
  this.status = red(`Refresh error: ${err?.message || err}`);
198
294
  } finally {
199
295
  this.refreshing = false;
200
296
  }
201
297
  }
202
298
 
299
+ /** Pipeline rows wrap whole fields rather than clipping useful values. */
300
+ pipelineLines(width, now = Date.now()) {
301
+ const lines = [bold("PIPELINE") + dim(" metriche Headroom")];
302
+ const add = (cells, separator) => lines.push(...wrapCells(cells, width, separator));
303
+ const chainFresh = this.chainAt !== null && now - this.chainAt <= STALE_MS;
304
+ add(this.chain.map(node => paintNode(chainFresh || node.state === "static"
305
+ ? node : { ...node, state: "unknown" })), " -> ");
306
+
307
+ const stale = this.metricsAt === null || Boolean(this.metricsError) || now - this.metricsAt > STALE_MS;
308
+ const freshness = this.metricsAt === null ? "nessun campione"
309
+ : `ultimo campione ${age(this.metricsAt, now)} fa`;
310
+ const freshnessText = stale ? yellow(`Dati non aggiornati: ${freshness}`) : `Aggiornati ${age(this.metricsAt, now)} fa`;
311
+ if (stripAnsi(lines[0] + " | " + freshnessText).length <= width) lines[0] += dim(" | ") + freshnessText;
312
+ else add([freshnessText]);
313
+ if (this.metricsError) add([yellow(this.metricsError)]);
314
+
315
+ if (this.metrics) {
316
+ const m = this.metrics;
317
+ add([bold("Adesso"), stale ? dim("attivita non disponibile")
318
+ : `${cyan(bold(num(m.headroom_inbound_requests_active)))} in corso`,
319
+ ...(stale ? [] : [`${bold(num(this.rates.headroom_requests_total, 2))} req/s`])]);
320
+ const input = m.headroom_tokens_input_total;
321
+ const saved = m.headroom_tokens_saved_total;
322
+ const savingRatio = Number.isFinite(input) && Number.isFinite(saved) && input + saved > 0
323
+ ? saved / (input + saved) : null;
324
+ const cacheRatio = Number.isFinite(m.headroom_requests_cached_total) && m.headroom_requests_total > 0
325
+ ? m.headroom_requests_cached_total / m.headroom_requests_total : null;
326
+ const latency = Number.isFinite(m.headroom_latency_ms_sum) && m.headroom_latency_ms_count > 0
327
+ ? m.headroom_latency_ms_sum / m.headroom_latency_ms_count : null;
328
+ const duration = latency === null ? "-" : latency < 1000 ? `${Math.round(latency)} ms` : `${(latency / 1000).toFixed(1)} s`;
329
+ add([bold("Dall'avvio dei contatori") + (stale ? yellow(" (ultimo campione)") : "")]);
330
+ add([`Token risparmiati ${bold(pct(savingRatio))}`, `Richieste cached ${bold(pct(cacheRatio))}`,
331
+ `Durata media ${bold(duration)}`]);
332
+ }
333
+
334
+ if (this.showPipelineDetails) {
335
+ for (const node of this.chain) {
336
+ if (node.detail) add([`${node.label}: ${node.detail}`]);
337
+ if (node.state === "running") add([yellow(`${node.label}: health non verificato`)]);
338
+ }
339
+ if (!chainFresh) add([yellow("Stati della catena non aggiornati")]);
340
+ if (this.metrics && !stale) {
341
+ add([`Token in/s ${num(this.rates.headroom_tokens_input_total, 1)}`,
342
+ `Token out/s ${num(this.rates.headroom_tokens_output_total, 1)}`]);
343
+ add([dim(this.sampleMs === null ? "Velocita: in attesa del secondo campione"
344
+ : `Velocita: ultimo intervallo di ${(this.sampleMs / 1000).toFixed(1)} s`)]);
345
+ }
346
+ add([dim("Token risparmiati: saved / (input + saved)")]);
347
+ add([dim("Richieste cached: cached / richieste totali")]);
348
+ add([dim("Durata media: somma latenze / campioni")]);
349
+ add([dim("Cache richieste != risparmio economico")]);
350
+ }
351
+ return lines.map(line => clip(line, width));
352
+ }
353
+
203
354
  /**
204
355
  * Builds the whole screen as an array of lines.
205
356
  * @returns {string[]}
@@ -208,6 +359,20 @@ export class Dashboard {
208
359
  const width = Math.max(40, process.stdout.columns || 100);
209
360
  const height = Math.max(12, process.stdout.rows || 30);
210
361
  const lines = [];
362
+ const svc = this.currentService();
363
+ const target = svc ? bold(svc.id) : dim("-");
364
+ const keyLines = wrapCells([
365
+ `${dim("d")} ${this.showPipelineDetails ? "riduci" : "dettagli"}`,
366
+ `${dim("q")} esci`,
367
+ `${dim("up/down")} seleziona (${target})`,
368
+ `${dim("s")} start`,
369
+ `${dim("x")} stop`,
370
+ `${dim("r")} restart`,
371
+ `${dim("k")} kill`,
372
+ ...(svc?.dashboardUrl ? [`${dim("o")} dashboard`] : []),
373
+ ...(svc?.repositoryUrl ? [`${dim("g")} GitHub`] : []),
374
+ ], width, " ", "");
375
+ const footerLines = keyLines.length + 2;
211
376
 
212
377
  const title = `${bold(cyan(APP_NAME))} ${gray("v" + VERSION)} ${dim("live dashboard")}`;
213
378
  const clock = dim(new Date().toLocaleTimeString());
@@ -219,19 +384,31 @@ export class Dashboard {
219
384
  " ",
220
385
  "SERVICE",
221
386
  "STATUS",
387
+ "VERSION",
388
+ "UPDATE",
222
389
  { header: "PID", align: "right" },
223
390
  { header: "UPTIME", align: "right" },
391
+ "REPO",
224
392
  "URL",
225
393
  ];
226
394
  const rows = this.statuses.map((s, idx) => {
227
395
  const active = idx === this.selected;
396
+ const version = this.versions[s.id];
397
+ const update = version?.updateAvailable === true
398
+ ? yellow(bold(`↑ ${version.latestVersion}`))
399
+ : version?.updateAvailable === false
400
+ ? green("aggiornato")
401
+ : dim(this.versionsLoading && !version ? "verifica..." : "n/d");
228
402
  return [
229
403
  active ? cyan(bold(">")) : " ",
230
404
  active ? bold(white(s.id)) : bold(s.id),
231
405
  badgeStatus(s.status),
406
+ version?.version || dim("n/d"),
407
+ update,
232
408
  s.pid ? String(s.pid) : dim("-"),
233
409
  s.status === "running" ? s.uptime : dim("-"),
234
- s.status === "running" && s.url && s.url !== "-" ? cyan(underline(s.url)) : dim(s.url || "-"),
410
+ s.repositoryUrl ? cyan(underline(s.repositoryUrl.replace("https://github.com/", ""))) : dim("-"),
411
+ s.id === "proxy" ? dim(`${s.url} (proxy)`) : s.status === "running" && s.url && s.url !== "-" ? cyan(underline(s.url)) : dim(s.url || "-"),
235
412
  ];
236
413
  });
237
414
  if (rows.length > 0) {
@@ -240,49 +417,23 @@ export class Dashboard {
240
417
  } else {
241
418
  lines.push(dim(" No services."));
242
419
  }
420
+ if (svc?.repositoryUrl) {
421
+ // Keep both full links accessible when terminal width clips their columns.
422
+ lines.push(...wrapCells([
423
+ ...(svc.url && svc.url !== "-" ? [`${dim("URL:")} ${cyan(underline(svc.url))}`] : []),
424
+ `${dim("GitHub (g):")} ${cyan(underline(svc.repositoryUrl))}`,
425
+ ], width));
426
+ }
243
427
  lines.push("");
244
428
 
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)"));
429
+ if (this.statuses.some(s => s.id === "proxy") || this.proxyStats) {
430
+ lines.push(...proxyStatsLines(this.proxyStats));
431
+ const last = this.proxyStats?.recent.at(-1);
432
+ if (last) lines.push(dim(` Ultima: ${last.model} ${last.preset} | ${last.error ? "errore" : last.stages.map(s => `${s.name}: ${s.reason}`).join(" | ")}`));
433
+ lines.push("");
285
434
  }
435
+
436
+ lines.push(...this.pipelineLines(width));
286
437
  lines.push("");
287
438
 
288
439
  lines.push(bold("STREAM RICHIESTE") + dim(" " + this.eventsFile));
@@ -302,7 +453,6 @@ export class Dashboard {
302
453
  lines.push(" " + savingsCells.join(dim(" . ")));
303
454
  }
304
455
 
305
- const footerLines = 3;
306
456
  const slots = Math.max(1, height - lines.length - footerLines);
307
457
 
308
458
  if (this.events.length === 0) {
@@ -335,20 +485,14 @@ export class Dashboard {
335
485
  }
336
486
 
337
487
  while (lines.length < height - footerLines) lines.push("");
488
+ // Keep controls reachable even when expanded details exceed the terminal.
489
+ if (lines.length > height - footerLines) {
490
+ lines.length = height - footerLines;
491
+ lines[lines.length - 1] = dim(" ... aumenta l'altezza o premi d per ridurre i dettagli");
492
+ }
338
493
  lines.push(gray("-".repeat(width)));
339
494
 
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(" "));
495
+ lines.push(...keyLines);
352
496
  lines.push(this.busy ? yellow(this.status) : this.status || dim("pronto"));
353
497
 
354
498
  return lines.slice(0, height).map(line => clip(line, width));
@@ -377,8 +521,9 @@ export class Dashboard {
377
521
 
378
522
  try {
379
523
  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);
524
+ const message = [res?.message || `${label} ${svc.id}: fatto`, res?.codexConfig?.message].filter(Boolean).join(" | ");
525
+ this.status = res && res.success === false ? red(message)
526
+ : res?.codexConfig?.status === "warning" ? yellow(message) : green(message);
382
527
  } catch (err) {
383
528
  this.status = red(`${label} ${svc.id}: ${err?.message || err}`);
384
529
  } finally {
@@ -399,6 +544,10 @@ export class Dashboard {
399
544
  }
400
545
 
401
546
  switch (key) {
547
+ case "d":
548
+ this.showPipelineDetails = !this.showPipelineDetails;
549
+ this.render();
550
+ return;
402
551
  case KEY_UP:
403
552
  this.selected = Math.max(0, this.selected - 1);
404
553
  this.render();
@@ -423,11 +572,17 @@ export class Dashboard {
423
572
  });
424
573
  return;
425
574
  case "o":
575
+ if (!this.currentService()?.dashboardUrl) return;
426
576
  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}` };
577
+ const opened = await manager.openDashboard([svc.id]);
578
+ return { success: opened.length > 0, message: opened.length ? `Aperto ${opened[0].url}` : "Nessuna dashboard disponibile" };
579
+ });
580
+ return;
581
+ case "g":
582
+ if (!this.currentService()?.repositoryUrl) return;
583
+ this.runAction("GitHub", async svc => {
584
+ const opened = await manager.openRepository([svc.id]);
585
+ return { success: opened.length > 0, message: opened.length ? `Aperto ${opened[0].url}` : "Nessun repository disponibile" };
431
586
  });
432
587
  return;
433
588
  default:
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
+ }
@@ -263,28 +263,50 @@ export async function probeChain(statuses) {
263
263
  const byId = {};
264
264
  for (const svc of statuses || []) byId[svc.id] = svc;
265
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
+
266
281
  const stateOf = id => byId[id]?.status || "unknown";
267
282
 
268
283
  const nodes = [
269
284
  { id: "client", label: "client", state: "static", detail: "AI agents / CLI" },
270
285
  { id: "headroom", label: "headroom", state: stateOf("headroom"), detail: baseUrl(byId.headroom?.url) },
271
286
  { id: "pxpipe", label: "pxpipe", state: stateOf("pxpipe"), detail: baseUrl(byId.pxpipe?.url) },
272
- { id: "upstream", label: "upstream", state: "static", detail: "" },
287
+ { id: "upstream", label: "upstream", state: "unknown", detail: "" },
273
288
  ];
274
289
 
275
290
  const headroomBase = baseUrl(byId.headroom?.url);
276
- const health = headroomBase ? await fetchJson(`${headroomBase}/health`, 2000) : null;
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;
277
298
 
278
299
  if (health) {
279
300
  if (health.version) nodes[1].detail = `${nodes[1].detail} v${health.version}`.trim();
280
- if (health.status && health.status !== "healthy") nodes[1].state = "error";
301
+ nodes[1].state = checkedState(health.status, nodes[1].state);
281
302
 
282
303
  const upstream = health.checks?.upstream;
283
304
  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";
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)`;
288
310
  }
289
311
  }
290
312
  }