@drakonkat/ai-helper 1.2.17 → 1.2.18

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,7 +1,9 @@
1
- import { APP_NAME, VERSION } from "./config.js";
1
+ import { APP_NAME, SERVICES, VERSION } from "./config.js";
2
2
  import { manager } from "./manager.js";
3
3
  import { ProxySetupWizard } from "./tui-proxy-setup.js";
4
4
  import { preflightProxy } from "./proxy-setup.js";
5
+ import { preflightHindsight } from "./hindsight.js";
6
+ import { hasHealthCheck, probeServiceHealth } from "./health.js";
5
7
  import {
6
8
  badgeStatus,
7
9
  bold,
@@ -28,6 +30,8 @@ import {
28
30
  const TICK_MS = 1000;
29
31
  const STALE_MS = 5 * TICK_MS;
30
32
  const VERSION_CHECK_MS = 5 * 60 * 1000;
33
+ const HEALTH_CHECK_MS = 5 * TICK_MS;
34
+ const HEALTH_STALE_MS = 3 * HEALTH_CHECK_MS;
31
35
  const MAX_EVENTS = 20;
32
36
 
33
37
  const ALT_SCREEN_ON = "\x1b[?1049h";
@@ -101,7 +105,7 @@ function age(timestamp, now) {
101
105
  }
102
106
 
103
107
  function duration(ms) {
104
- if (!Number.isFinite(ms) || ms < 0) return "n/d";
108
+ if (!Number.isFinite(ms) || ms < 0) return "n/a";
105
109
  return ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(1)}s`;
106
110
  }
107
111
 
@@ -121,7 +125,7 @@ function stageList(event) {
121
125
  }
122
126
 
123
127
  function savedTokens(value) {
124
- if (!Number.isFinite(value)) return dim("non misurato");
128
+ if (!Number.isFinite(value)) return dim("not measured");
125
129
  if (value > 0) return green(`-${num(value)} tok`);
126
130
  if (value < 0) return yellow(`+${num(-value)} tok`);
127
131
  return dim("0 tok");
@@ -173,24 +177,29 @@ function wrapCells(cells, width, separator = " | ", indent = " ") {
173
177
  function paintNode(node) {
174
178
  switch (node.state) {
175
179
  case "healthy":
176
- return green(`[ ${node.label}: verificato ]`);
180
+ return green(`[ ${node.label}: verified ]`);
177
181
  case "running":
178
- return `[ ${node.label}: processo attivo ]`;
182
+ return `[ ${node.label}: process running ]`;
179
183
  case "error":
180
- return red(bold(`[ ${node.label}: errore ]`));
184
+ return red(bold(`[ ${node.label}: error ]`));
181
185
  case "stopped":
182
- return dim(`[ ${node.label}: fermo ]`);
186
+ return dim(`[ ${node.label}: stopped ]`);
183
187
  case "static":
184
188
  return `[ ${node.label} ]`;
185
189
  default:
186
- return yellow(`[ ${node.label}: non verificato ]`);
190
+ return yellow(`[ ${node.label}: not verified ]`);
187
191
  }
188
192
  }
189
193
 
190
194
  export class Dashboard {
191
- constructor({ getVersions = getServiceVersions, getProxyStats = readProxyStats } = {}) {
195
+ constructor({ getVersions = getServiceVersions, getProxyStats = readProxyStats, getHealth = probeServiceHealth } = {}) {
192
196
  this.statuses = [];
193
197
  this.getVersions = getVersions;
198
+ this.getHealth = getHealth;
199
+ this.health = {};
200
+ this.healthAt = 0;
201
+ this.healthKey = "";
202
+ this.healthLoading = false;
194
203
  this.versions = {};
195
204
  this.versionsKey = "";
196
205
  this.versionsAt = 0;
@@ -218,6 +227,51 @@ export class Dashboard {
218
227
  this.refreshing = false;
219
228
  }
220
229
 
230
+ /**
231
+ * Reads every service's health endpoint every few seconds, independently of the
232
+ * 1 s tick; a start/stop/restart (status, PID, URL or container change) triggers an immediate check.
233
+ */
234
+ async refreshHealth(now = Date.now()) {
235
+ const targets = this.statuses.filter(s => hasHealthCheck({ ...s, runtime: s.runtime || SERVICES[s.id]?.runtime }));
236
+ const key = JSON.stringify(targets.map(s => [s.id, s.status, s.pid, s.url, s.containerId, s.apiUrl, s.runtimeError]));
237
+ if (key !== this.healthKey) {
238
+ this.healthKey = key;
239
+ this.healthAt = 0;
240
+ }
241
+ if (this.healthLoading || (this.healthAt && now - this.healthAt < HEALTH_CHECK_MS)) return;
242
+ this.healthLoading = true;
243
+ try {
244
+ const entries = await Promise.all(targets.map(async s => [s.id, s.status === "running"
245
+ ? await Promise.resolve().then(() => this.getHealth({ ...s, runtime: s.runtime || SERVICES[s.id]?.runtime }))
246
+ .catch(error => ({ state: "unreachable", error: error?.message || String(error), checkedAt: Date.now() }))
247
+ : { state: s.runtimeError ? "docker" : "stopped", error: s.runtimeError, checkedAt: Date.now() }]));
248
+ if (key === this.healthKey) this.health = Object.fromEntries(entries);
249
+ } finally {
250
+ if (key === this.healthKey) this.healthAt = Date.now();
251
+ this.healthLoading = false;
252
+ this.render();
253
+ }
254
+ }
255
+
256
+ healthCell(svc, now = Date.now()) {
257
+ const health = this.health[svc.id];
258
+ if (!health) return dim(hasHealthCheck({ ...svc, runtime: svc.runtime || SERVICES[svc.id]?.runtime }) ? "checking..." : "-");
259
+ const label = {
260
+ healthy: green("ok"), degraded: red(bold("degraded")), unreachable: red("unreachable"),
261
+ unverified: yellow("unverified"), stopped: dim("stopped"), docker: yellow("no docker"),
262
+ }[health.state] || dim("n/a");
263
+ return label;
264
+ }
265
+
266
+ /** Age of the last /health reading; stale readings are highlighted. */
267
+ lastCheckCell(svc, now = Date.now()) {
268
+ const health = this.health[svc.id];
269
+ // A stopped service is not contacted, so there is no interaction to date.
270
+ if (!Number.isFinite(health?.checkedAt) || health.state === "stopped") return dim("-");
271
+ const text = `${age(health.checkedAt, now)} ago`;
272
+ return now - health.checkedAt > HEALTH_STALE_MS ? yellow(text) : text;
273
+ }
274
+
221
275
  /** @returns {any} */
222
276
  currentService() {
223
277
  return this.statuses[this.selected];
@@ -258,6 +312,7 @@ export class Dashboard {
258
312
  try {
259
313
  this.statuses = await manager.getStatus();
260
314
  void this.refreshVersions();
315
+ void this.refreshHealth();
261
316
  if (this.selected >= this.statuses.length) {
262
317
  this.selected = Math.max(0, this.statuses.length - 1);
263
318
  }
@@ -280,9 +335,9 @@ export class Dashboard {
280
335
  this.metricsAt = now;
281
336
  this.events = stats.recent.filter(ev => ev && typeof ev === "object" && !Array.isArray(ev)).slice(-MAX_EVENTS);
282
337
  }
283
- this.metricsError = !proxy ? "Proxy AIH non configurato"
284
- : proxy.status !== "running" ? "Proxy AIH non in esecuzione"
285
- : !stats ? "Statistiche proxy assenti o non valide" : null;
338
+ this.metricsError = !proxy ? "AIH proxy not configured"
339
+ : proxy.status !== "running" ? "AIH proxy not running"
340
+ : !stats ? "Proxy statistics missing or invalid" : null;
286
341
  if (!this.metricsError) {
287
342
  const counters = { requests: stats.requests };
288
343
  this.sampleMs = this.prevMetrics ? now - this.prevAt : null;
@@ -296,10 +351,12 @@ export class Dashboard {
296
351
  this.sampleMs = null;
297
352
  }
298
353
 
299
- this.chain = probed.nodes;
354
+ // A verified health reading upgrades "process running" to "verified" in the chain.
355
+ this.chain = probed.nodes.map(node => node.id === "proxy" && node.state === "running"
356
+ && this.health.proxy?.state === "healthy" ? { ...node, state: "healthy" } : node);
300
357
  this.chainAt = now;
301
358
  } catch (err) {
302
- this.metricsError = "aggiornamento fallito";
359
+ this.metricsError = "refresh failed";
303
360
  this.rates = {};
304
361
  this.prevMetrics = null;
305
362
  this.sampleMs = null;
@@ -312,59 +369,59 @@ export class Dashboard {
312
369
 
313
370
  /** Pipeline rows wrap whole fields rather than clipping useful values. */
314
371
  pipelineLines(width, now = Date.now()) {
315
- const lines = [bold("PIPELINE") + dim(" metriche proxy AIH")];
372
+ const lines = [bold("PIPELINE") + dim(" AIH proxy metrics")];
316
373
  const add = (cells, separator) => lines.push(...wrapCells(cells, width, separator));
317
374
  const chainFresh = this.chainAt !== null && now - this.chainAt <= STALE_MS;
318
375
  add(this.chain.map(node => paintNode(chainFresh || node.state === "static"
319
376
  ? node : { ...node, state: "unknown" })), " -> ");
320
377
 
321
378
  const stale = this.metricsStale(now);
322
- const freshness = this.metricsAt === null ? "nessun campione"
323
- : `ultimo campione ${age(this.metricsAt, now)} fa`;
324
- const freshnessText = stale ? yellow(`Dati non aggiornati: ${freshness}`) : `Letti ${age(this.metricsAt, now)} fa`;
379
+ const freshness = this.metricsAt === null ? "no sample"
380
+ : `last sample ${age(this.metricsAt, now)} ago`;
381
+ const freshnessText = stale ? yellow(`Stale data: ${freshness}`) : `Read ${age(this.metricsAt, now)} ago`;
325
382
  if (stripAnsi(lines[0] + " | " + freshnessText).length <= width) lines[0] += dim(" | ") + freshnessText;
326
383
  else add([freshnessText]);
327
384
  if (this.metricsError) add([yellow(this.metricsError)]);
328
385
 
329
386
  const preset = this.statuses.find(s => s.id === "proxy")?.proxyOptions?.preset;
330
- if (preset === "none") add([yellow("Preset none: traffico non registrato nelle metriche")]);
387
+ if (preset === "none") add([yellow("Preset none: traffic not recorded in metrics")]);
331
388
  if (this.proxyStats) {
332
389
  const m = this.proxyStats;
333
390
  const lastAt = timestamp(m.updatedAt);
334
- add([bold("Elaborazioni preset"), stale ? dim("attivita non disponibile")
335
- : `${cyan(bold(num(this.rates.requests, 2)))} elab/s`,
336
- `Ultimo evento ${lastAt === null ? "-" : age(lastAt, now) + " fa"}`]);
391
+ add([bold("Preset processing"), stale ? dim("activity unavailable")
392
+ : `${cyan(bold(num(this.rates.requests, 2)))} proc/s`,
393
+ `Last event ${lastAt === null ? "-" : age(lastAt, now) + " ago"}`]);
337
394
  const changedRatio = Number.isFinite(m.changed) && m.requests > 0 ? m.changed / m.requests : null;
338
- add([bold("Dall'avvio dei contatori") + (stale ? yellow(" (ultimo campione)") : "")]);
339
- add([`Richieste ${bold(num(m.requests))}`, `Modificate ${bold(num(m.changed))} (${pct(changedRatio)})`,
340
- `Errori preset ${m.errors > 0 ? red(bold(num(m.errors))) : num(m.errors)}`]);
341
- add([`risparmio stimato ${bold(num(m.estimatedSavedTokens))} token${m.unmeasuredStages > 0 ? yellow(" (parziale)") : ""}`]);
395
+ add([bold("Since counters started") + (stale ? yellow(" (last sample)") : "")]);
396
+ add([`Requests ${bold(num(m.requests))}`, `Changed ${bold(num(m.changed))} (${pct(changedRatio)})`,
397
+ `Preset errors ${m.errors > 0 ? red(bold(num(m.errors))) : num(m.errors)}`]);
398
+ add([`estimated savings ${bold(num(m.estimatedSavedTokens))} tokens${m.unmeasuredStages > 0 ? yellow(" (partial)") : ""}`]);
342
399
  for (const [name, stage] of Object.entries(m.stages || {})) {
343
400
  if (!stage || typeof stage !== "object") continue;
344
- add([`${plain(name)}: ${bold(num(stage.saved))} token`, `applicato ${num(stage.applied)}/${num(stage.requests)}`,
345
- ...(stage.unmeasured > 0 ? [yellow(`non misurati ${num(stage.unmeasured)}`)] : [])]);
401
+ add([`${plain(name)}: ${bold(num(stage.saved))} tokens`, `applied ${num(stage.applied)}/${num(stage.requests)}`,
402
+ ...(stage.unmeasured > 0 ? [yellow(`unmeasured ${num(stage.unmeasured)}`)] : [])]);
346
403
  }
347
404
  }
348
- add([dim("Stime dei preset; esclusi interceptor, cache e fatturazione.")]);
405
+ add([dim("Preset estimates; excludes interceptors, cache and billing.")]);
349
406
 
350
407
  if (this.showPipelineDetails) {
351
- add([`Fonte: ${plain(this.metricsFile)}`]);
352
- if (this.proxyStats?.since) add([`Contatori dal ${plain(this.proxyStats.since)} (persistono ai riavvii)`]);
408
+ add([`Source: ${plain(this.metricsFile)}`]);
409
+ if (this.proxyStats?.since) add([`Counters since ${plain(this.proxyStats.since)} (persist across restarts)`]);
353
410
  for (const node of this.chain) {
354
411
  if (node.detail) add([`${node.label}: ${plain(node.detail)}`]);
355
- if (node.state === "running") add([yellow(`${node.label}: health non verificato`)]);
412
+ if (node.state === "running") add([yellow(`${node.label}: health not verified`)]);
356
413
  }
357
- if (!chainFresh) add([yellow("Stati della catena non aggiornati")]);
414
+ if (!chainFresh) add([yellow("Chain states are stale")]);
358
415
  if (this.proxyStats && !stale) {
359
- add([dim(this.sampleMs === null ? "Velocita: in attesa del secondo campione"
360
- : `Velocita: ultimo intervallo di ${(this.sampleMs / 1000).toFixed(1)} s`)]);
416
+ add([dim(this.sampleMs === null ? "Rate: waiting for the second sample"
417
+ : `Rate: last interval ${(this.sampleMs / 1000).toFixed(1)} s`)]);
361
418
  }
362
- add([dim("elab/s: richieste elaborate dai preset, non tutto il traffico proxy")]);
363
- add([dim("Risparmio: somma dei delta misurati per stadio; basi non sommabili")]);
364
- add([dim("Errori preset != errori upstream; nessun conteggio globale delle richieste in corso")]);
365
- add([dim("Tempi: proxy = preset; header = invio upstream -> header (non primo token)")]);
366
- add([dim("Totale HTTP include upload, interceptor e streaming fino a fine invio/chiusura")]);
367
- add([dim("WS: solo tempo preset; attesa esito non implica che la richiesta sia ancora attiva")]);
419
+ add([dim("proc/s: requests processed by presets, not all proxy traffic")]);
420
+ add([dim("Savings: sum of measured per-stage deltas; bases are not additive")]);
421
+ add([dim("Preset errors != upstream errors; no global count of in-flight requests")]);
422
+ add([dim("Timings: proxy = presets; header = upstream send -> headers (not first token)")]);
423
+ add([dim("HTTP total includes upload, interceptors and streaming until finish/close")]);
424
+ add([dim("WS: preset time only; awaiting outcome does not mean the request is still active")]);
368
425
  }
369
426
  return lines.map(line => clip(line, width));
370
427
  }
@@ -383,43 +440,43 @@ export class Dashboard {
383
440
  /** Native recent events are a bounded snapshot, not an append-only log. */
384
441
  requestLines(event, width) {
385
442
  const at = timestamp(event.at);
386
- const time = at === null ? "--:--:--" : new Date(at).toLocaleTimeString("it-IT", { hour12: false });
443
+ const time = at === null ? "--:--:--" : new Date(at).toLocaleTimeString("en-GB", { hour12: false });
387
444
  const stages = stageList(event);
388
445
  const partial = !event.error && stages.some(stage => !Number.isFinite(stage.saved));
389
446
  const unmeasured = partial && stages.every(stage => !Number.isFinite(stage.saved));
390
- const status = event.error ? red(bold("errore preset")) : event.changed === true ? green("modificata")
391
- : event.changed === false ? dim("invariata") : dim("esito non disponibile");
447
+ const status = event.error ? red(bold("preset error")) : event.changed === true ? green("changed")
448
+ : event.changed === false ? dim("unchanged") : dim("outcome unavailable");
392
449
  const timing = event.timings;
393
450
  const responseState = {
394
- waiting: dim("attesa esito"), responding: cyan("risposta iniziata"),
395
- error: red(event.error ? "non inoltrata" : "errore proxy/trasporto"), aborted: yellow("interrotta"),
451
+ waiting: dim("awaiting outcome"), responding: cyan("response started"),
452
+ error: red(event.error ? "not forwarded" : "proxy/transport error"), aborted: yellow("aborted"),
396
453
  }[timing?.state];
397
454
  const lines = wrapCells([gray(time), cyan(plain(event.transport)), magenta(plain(event.model, "?")),
398
455
  plain(event.preset), status,
399
- ...(event.error ? [] : [savedTokens(unmeasured ? null : event.saved) + (partial && !unmeasured ? yellow(" (parziale)") : "")]),
456
+ ...(event.error ? [] : [savedTokens(unmeasured ? null : event.saved) + (partial && !unmeasured ? yellow(" (partial)") : "")]),
400
457
  ...(timing ? [
401
458
  `proxy: ${duration(timing.presetMs)}`,
402
459
  ...(Number.isFinite(timing.pxpipeQueueMs) ? [
403
- `coda: ${duration(timing.pxpipeQueueMs)}`, `pxpipe: ${duration(timing.pxpipeMs)}`,
460
+ `queue: ${duration(timing.pxpipeQueueMs)}`, `pxpipe: ${duration(timing.pxpipeMs)}`,
404
461
  ...(Number.isFinite(timing.pxpipeCpuMs) ? [`CPU: ${duration(timing.pxpipeCpuMs)}`] : []),
405
462
  ] : []),
406
- ...(Number.isFinite(timing.eventLoopLagMs) ? [`loop max: ${duration(timing.eventLoopLagMs)}`] : []),
463
+ ...(Number.isFinite(timing.eventLoopLagMs) ? [`max loop lag: ${duration(timing.eventLoopLagMs)}`] : []),
407
464
  ...(event.transport === "HTTP" ? [
408
465
  `header: ${duration(timing.upstreamHeadersMs)}`, `tot: ${duration(timing.totalMs)}`,
409
466
  ...(Number.isInteger(timing.statusCode) && timing.statusCode >= 100 && timing.statusCode <= 599
410
467
  ? [timing.statusCode >= 400 ? red(`HTTP ${timing.statusCode}`) : `HTTP ${timing.statusCode}`] : []),
411
468
  ...(responseState ? [responseState] : []),
412
- ] : [dim("risposta WS: n/d")]),
413
- ] : [dim("tempi: n/d")]),
414
- ...(event.project ? [`progetto: ${plain(event.project)}`] : []),
415
- ...(event.sessionId || event.threadId ? [`sessione: ${plain(event.sessionId || event.threadId)}`] : []),
469
+ ] : [dim("WS response: n/a")]),
470
+ ] : [dim("timings: n/a")]),
471
+ ...(event.project ? [`project: ${plain(event.project)}`] : []),
472
+ ...(event.sessionId || event.threadId ? [`session: ${plain(event.sessionId || event.threadId)}`] : []),
416
473
  ...(!this.showPipelineDetails ? stages.map(s => dim(`${plain(s.name)}: ${plain(s.reason)}`)) : []),
417
474
  ], width, " ");
418
475
  if (this.showPipelineDetails) {
419
476
  for (const stage of stages) {
420
477
  const ratio = Number.isFinite(stage.before) && stage.before > 0 && Number.isFinite(stage.saved)
421
478
  ? stage.saved / stage.before : null;
422
- lines.push(...wrapCells([`${plain(stage.name)}: ${stage.applied ? "applicato" : "bypass"}`,
479
+ lines.push(...wrapCells([`${plain(stage.name)}: ${stage.applied ? "applied" : "bypass"}`,
423
480
  `${num(stage.before)} -> ${num(stage.after)} tok (${pct(ratio)})`,
424
481
  plain(stage.reason), dim(plain(stage.method)),
425
482
  ], width, " | ", " "));
@@ -430,15 +487,15 @@ export class Dashboard {
430
487
 
431
488
  streamLines(width, maxRows = Infinity, now = Date.now()) {
432
489
  if (maxRows <= 0) return [];
433
- const lines = [clip(bold("STREAM RICHIESTE")
434
- + (this.metricsStale(now) && this.proxyStats ? yellow(" (storico)") : "")
435
- + dim(" proxy AIH / elaborazioni preset"), width)];
490
+ const lines = [clip(bold("REQUEST STREAM")
491
+ + (this.metricsStale(now) && this.proxyStats ? yellow(" (historical)") : "")
492
+ + dim(" AIH proxy / preset processing"), width)];
436
493
  if (maxRows === 1) return lines;
437
494
  if (!this.events.length) {
438
495
  const preset = this.statuses.find(s => s.id === "proxy")?.proxyOptions?.preset;
439
- const message = preset === "none" ? "preset none: nessun evento di elaborazione"
440
- : this.proxyStats ? "in attesa di richieste elaborate dai preset..."
441
- : "nessun evento proxy disponibile";
496
+ const message = preset === "none" ? "preset none: no processing events"
497
+ : this.proxyStats ? "waiting for requests processed by presets..."
498
+ : "no proxy events available";
442
499
  return lines.concat(wrapCells([dim(message)], width).slice(0, maxRows - 1));
443
500
  }
444
501
  const groups = [];
@@ -472,11 +529,11 @@ export class Dashboard {
472
529
  const svc = this.currentService();
473
530
  const target = svc ? bold(svc.id) : dim("-");
474
531
  const keyLines = wrapCells([
475
- `${dim("d")} ${this.showPipelineDetails ? "riduci" : "dettagli"}`,
476
- `${dim("q")} esci`,
477
- `${dim("up/down")} seleziona (${target})`,
532
+ `${dim("d")} ${this.showPipelineDetails ? "less" : "details"}`,
533
+ `${dim("q")} quit`,
534
+ `${dim("up/down")} select (${target})`,
478
535
  `${dim("s")} start`,
479
- `${dim("c")} setup proxy`,
536
+ `${dim("c")} setup`,
480
537
  `${dim("x")} stop`,
481
538
  `${dim("r")} restart`,
482
539
  `${dim("u")} update`,
@@ -496,10 +553,12 @@ export class Dashboard {
496
553
  " ",
497
554
  "SERVICE",
498
555
  "STATUS",
556
+ "HEALTH",
499
557
  "VERSION",
500
558
  "UPDATE",
501
559
  { header: "PID", align: "right" },
502
560
  { header: "UPTIME", align: "right" },
561
+ "LAST CHECK",
503
562
  "REPO",
504
563
  "URL",
505
564
  ];
@@ -509,16 +568,18 @@ export class Dashboard {
509
568
  const update = version?.updateAvailable === true
510
569
  ? yellow(bold(`↑ ${version.latestVersion}`))
511
570
  : version?.updateAvailable === false
512
- ? green("aggiornato")
513
- : dim(this.versionsLoading && !version ? "verifica..." : "n/d");
571
+ ? green("up to date")
572
+ : dim(this.versionsLoading && !version ? "checking..." : "n/a");
514
573
  return [
515
574
  active ? cyan(bold(">")) : " ",
516
575
  active ? bold(white(s.id)) : bold(s.id),
517
576
  badgeStatus(s.status),
518
- version?.version || dim("n/d"),
577
+ this.healthCell(s),
578
+ version?.version || dim("n/a"),
519
579
  update,
520
580
  s.pid ? String(s.pid) : dim("-"),
521
581
  s.status === "running" ? s.uptime : dim("-"),
582
+ this.lastCheckCell(s),
522
583
  s.repositoryUrl ? cyan(underline(s.repositoryUrl.replace("https://github.com/", ""))) : dim("-"),
523
584
  s.id === "proxy" ? dim(`${s.url} (proxy)`) : s.status === "running" && s.url && s.url !== "-" ? cyan(underline(s.url)) : dim(s.url || "-"),
524
585
  ];
@@ -529,19 +590,12 @@ export class Dashboard {
529
590
  } else {
530
591
  lines.push(dim(" No services."));
531
592
  }
532
- if (svc?.repositoryUrl) {
533
- // Keep both full links accessible when terminal width clips their columns.
534
- lines.push(...wrapCells([
535
- ...(svc.url && svc.url !== "-" ? [`${dim("URL:")} ${cyan(underline(svc.url))}`] : []),
536
- `${dim("GitHub (g):")} ${cyan(underline(svc.repositoryUrl))}`,
537
- ], width));
538
- }
539
593
  lines.push("");
540
594
 
541
595
  const bodyLimit = height - footerLines;
542
596
  if (lines.length > bodyLimit - 4) {
543
597
  lines.length = Math.max(0, bodyLimit - 4);
544
- if (lines.length) lines[lines.length - 1] = dim(" ... servizi: aumenta l'altezza");
598
+ if (lines.length) lines[lines.length - 1] = dim(" ... services: enlarge the terminal");
545
599
  }
546
600
  const room = bodyLimit - lines.length;
547
601
  const streamRows = this.events.length ? Math.min(6, Math.max(2, Math.floor(room / 3))) : 2;
@@ -551,14 +605,14 @@ export class Dashboard {
551
605
  // Never let expanded pipeline explanations consume the request stream.
552
606
  // On small screens prioritize native totals over the topology/details.
553
607
  const m = this.proxyStats;
554
- const header = m && this.metricsStale() ? bold("PIPELINE") + yellow(" (storico)") + dim(" metriche proxy AIH") : pipeline[0];
608
+ const header = m && this.metricsStale() ? bold("PIPELINE") + yellow(" (historical)") + dim(" AIH proxy metrics") : pipeline[0];
555
609
  pipeline = [header, ...wrapCells(m ? [
556
- `Richieste ${num(m.requests)}`, `Modificate ${num(m.changed)}`, `Errori preset ${num(m.errors)}`,
557
- `risparmio stimato ${num(m.estimatedSavedTokens)} token${m.unmeasuredStages > 0 ? " (parziale)" : ""}`,
558
- ...(this.metricsStale() ? [yellow("Dati storici / attivita non disponibile")] : []),
559
- ] : [yellow(this.metricsError || "nessun campione")], width)];
610
+ `Requests ${num(m.requests)}`, `Changed ${num(m.changed)}`, `Preset errors ${num(m.errors)}`,
611
+ `estimated savings ${num(m.estimatedSavedTokens)} tokens${m.unmeasuredStages > 0 ? " (partial)" : ""}`,
612
+ ...(this.metricsStale() ? [yellow("Historical data / activity unavailable")] : []),
613
+ ] : [yellow(this.metricsError || "no sample")], width)];
560
614
  pipeline = pipeline.slice(0, Math.max(1, pipelineBudget - 1));
561
- if (pipelineBudget > 1) pipeline.push(dim(" ... aumenta l'altezza per la pipeline"));
615
+ if (pipelineBudget > 1) pipeline.push(dim(" ... enlarge the terminal for the pipeline"));
562
616
  }
563
617
  lines.push(...pipeline);
564
618
  lines.push("");
@@ -568,12 +622,12 @@ export class Dashboard {
568
622
  // Keep controls reachable even when expanded details exceed the terminal.
569
623
  if (lines.length > height - footerLines) {
570
624
  lines.length = height - footerLines;
571
- lines[lines.length - 1] = dim(" ... aumenta l'altezza o premi d per ridurre i dettagli");
625
+ lines[lines.length - 1] = dim(" ... enlarge the terminal or press d for fewer details");
572
626
  }
573
627
  lines.push(gray("-".repeat(width)));
574
628
 
575
629
  lines.push(...keyLines);
576
- lines.push(this.busy ? yellow(this.status) : this.status || dim("pronto"));
630
+ lines.push(this.busy ? yellow(this.status) : this.status || dim("ready"));
577
631
 
578
632
  return lines.slice(0, height).map(line => clip(line, width));
579
633
  }
@@ -601,7 +655,7 @@ export class Dashboard {
601
655
 
602
656
  try {
603
657
  const res = await action(svc);
604
- const message = [res?.message || `${label} ${svc.id}: fatto`, res?.codexConfig?.message].filter(Boolean).join(" | ");
658
+ const message = [res?.message || `${label} ${svc.id}: done`, res?.codexConfig?.message].filter(Boolean).join(" | ");
605
659
  this.status = res && res.success === false ? red(message)
606
660
  : res?.codexConfig?.status === "warning" ? yellow(message) : green(message);
607
661
  } catch (err) {
@@ -651,16 +705,16 @@ export class Dashboard {
651
705
  this.render();
652
706
  return;
653
707
  case "s":
654
- this.runAction("Avvio", svc => manager.startService(svc.id));
708
+ this.runAction("Start", svc => manager.startService(svc.id));
655
709
  return;
656
710
  case "x":
657
711
  this.runAction("Stop", svc => manager.stopService(svc.id));
658
712
  return;
659
713
  case "r":
660
- this.runAction("Riavvio", svc => manager.restartService(svc.id));
714
+ this.runAction("Restart", svc => manager.restartService(svc.id));
661
715
  return;
662
716
  case "u":
663
- return this.runAction("Aggiornamento", async svc => {
717
+ return this.runAction("Update", async svc => {
664
718
  this.invalidateVersions();
665
719
  try {
666
720
  return await manager.updateService(svc.id);
@@ -671,7 +725,7 @@ export class Dashboard {
671
725
  });
672
726
  case "k":
673
727
  this.runAction("Kill", async svc => {
674
- if (!svc.pid) return { success: false, message: `${svc.id}: nessun PID da terminare` };
728
+ if (!svc.pid) return { success: false, message: `${svc.id}: no PID to kill` };
675
729
  return killProcessTree(svc.pid);
676
730
  });
677
731
  return;
@@ -679,14 +733,14 @@ export class Dashboard {
679
733
  if (!this.currentService()?.dashboardUrl) return;
680
734
  this.runAction("Dashboard", async svc => {
681
735
  const opened = await manager.openDashboard([svc.id]);
682
- return { success: opened.length > 0, message: opened.length ? `Aperto ${opened[0].url}` : "Nessuna dashboard disponibile" };
736
+ return { success: opened.length > 0, message: opened.length ? `Opened ${opened[0].url}` : "No dashboard available" };
683
737
  });
684
738
  return;
685
739
  case "g":
686
740
  if (!this.currentService()?.repositoryUrl) return;
687
741
  this.runAction("GitHub", async svc => {
688
742
  const opened = await manager.openRepository([svc.id]);
689
- return { success: opened.length > 0, message: opened.length ? `Aperto ${opened[0].url}` : "Nessun repository disponibile" };
743
+ return { success: opened.length > 0, message: opened.length ? `Opened ${opened[0].url}` : "No repository available" };
690
744
  });
691
745
  return;
692
746
  default:
@@ -701,11 +755,14 @@ export class Dashboard {
701
755
  this.render();
702
756
  try {
703
757
  const options = wizard.validate();
758
+ const hindsight = wizard.hindsightSettings();
704
759
  if (command === "check") {
705
760
  wizard.checks = [];
706
- wizard.checks = await preflightProxy(options, (await manager.syncState()).services.proxy);
761
+ const checks = await preflightProxy(options, (await manager.syncState()).services.proxy);
762
+ if (hindsight) checks.push(...await preflightHindsight(hindsight.config, { newKey: hindsight.apiKey }));
763
+ wizard.checks = checks;
707
764
  } else {
708
- const startup = { startServices: wizard.draft.startServices.split(",") };
765
+ const startup = { startServices: wizard.draft.startServices.split(","), ...(hindsight ? { hindsight } : {}) };
709
766
  const result = command === "save" ? manager.saveProxyConfiguration(options, startup)
710
767
  : await manager.applyProxyConfiguration(options, startup);
711
768
  if (!result.success) throw new Error(result.message);
@@ -12,7 +12,7 @@ const INITIAL_TAIL_BYTES = 64 * 1024;
12
12
  * Headroom keeps a rolling breakdown of where the token savings came from in
13
13
  * subscription_state.json. This is the only place in the ecosystem that splits
14
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
15
+ * only ever reports source "proxy", and neither pxpipe nor hindsight publish
16
16
  * savings counters of their own.
17
17
  * @returns {string}
18
18
  */
@@ -269,7 +269,7 @@ export async function probeChain(statuses, { nativeOnly = false } = {}) {
269
269
  if (proxy || nativeOnly) {
270
270
  const options = proxy?.proxyOptions || {};
271
271
  const preset = typeof options.preset === "string" ? options.preset : "none";
272
- const labels = { pxpipe: "pxpipe (libreria)", rtk: "rtk (pipe)", headroom: "headroom (compress)" };
272
+ const labels = { pxpipe: "pxpipe (library)", rtk: "rtk (pipe)", headroom: "headroom (compress)" };
273
273
  const stages = preset.split("-").filter(id => Object.hasOwn(labels, id)).map(id => ({
274
274
  id, label: labels[id],
275
275
  state: id === "pxpipe" ? proxy?.status || "unknown" : "static",
@@ -311,7 +311,7 @@ export async function probeChain(statuses, { nativeOnly = false } = {}) {
311
311
  if (baseUrl(upstream.url) && baseUrl(upstream.url) === baseUrl(byId.pxpipe?.url)) {
312
312
  if (nodes[2].state === "running") nodes[2].state = checkedState(upstream.status, nodes[2].state);
313
313
  } else {
314
- nodes[1].detail += ` | inoltro: ${upstream.url} (destinazione non verificata)`;
314
+ nodes[1].detail += ` | forwards to: ${upstream.url} (destination not verified)`;
315
315
  }
316
316
  }
317
317
  }