@drakonkat/ai-helper 1.2.2 → 1.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1 -0
- package/README.md +77 -13
- package/docs/benchmark.md +110 -10
- package/package.json +3 -3
- package/scripts/bench-proxy.js +11 -7
- package/src/benchmark/fixtures.js +16 -4
- package/src/benchmark/live.js +130 -1
- package/src/benchmark/quality-fixtures.js +95 -0
- package/src/benchmark/quality.js +71 -9
- package/src/benchmark/report.js +23 -2
- package/src/benchmark/runner.js +29 -11
- package/src/config.js +8 -0
- package/src/index.js +61 -6
- package/src/manager.js +108 -3
- package/src/proxy-presets.js +18 -9
- package/src/request-images.js +69 -0
- package/src/service-updates.js +68 -0
- package/src/tui.js +202 -149
- package/src/utils/metrics.js +17 -12
- package/src/utils/versions.js +1 -7
package/src/tui.js
CHANGED
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
import { homedir } from "node:os";
|
|
2
|
-
import { join } from "node:path";
|
|
3
1
|
import { APP_NAME, VERSION } from "./config.js";
|
|
4
2
|
import { manager } from "./manager.js";
|
|
5
3
|
import {
|
|
@@ -18,22 +16,17 @@ import {
|
|
|
18
16
|
yellow,
|
|
19
17
|
} from "./utils/format.js";
|
|
20
18
|
import { killProcessTree } from "./utils/process.js";
|
|
21
|
-
import {
|
|
19
|
+
import { getProxyStatsPath, readProxyStats } from "./proxy-stats.js";
|
|
22
20
|
import { getServiceVersions } from "./utils/versions.js";
|
|
23
21
|
import {
|
|
24
|
-
baseUrl,
|
|
25
22
|
diffRates,
|
|
26
|
-
fetchText,
|
|
27
|
-
parseProm,
|
|
28
23
|
probeChain,
|
|
29
|
-
readSavingsBreakdown,
|
|
30
|
-
tailJsonl,
|
|
31
24
|
} from "./utils/metrics.js";
|
|
32
25
|
|
|
33
26
|
const TICK_MS = 1000;
|
|
34
27
|
const STALE_MS = 5 * TICK_MS;
|
|
35
28
|
const VERSION_CHECK_MS = 5 * 60 * 1000;
|
|
36
|
-
const MAX_EVENTS =
|
|
29
|
+
const MAX_EVENTS = 20;
|
|
37
30
|
|
|
38
31
|
const ALT_SCREEN_ON = "\x1b[?1049h";
|
|
39
32
|
const ALT_SCREEN_OFF = "\x1b[?1049l";
|
|
@@ -46,17 +39,6 @@ const RESET = "\x1b[0m";
|
|
|
46
39
|
const KEY_UP = "\x1b[A";
|
|
47
40
|
const KEY_DOWN = "\x1b[B";
|
|
48
41
|
|
|
49
|
-
/**
|
|
50
|
-
* Location of headroom's append-only savings event log: the only real-time
|
|
51
|
-
* per-request source in the ecosystem (pxpipe exposes no API).
|
|
52
|
-
* @returns {string}
|
|
53
|
-
*/
|
|
54
|
-
function getEventsFilePath() {
|
|
55
|
-
const custom = process.env.HEADROOM_HOME;
|
|
56
|
-
const base = custom && custom.trim().length > 0 ? custom : join(homedir(), ".headroom");
|
|
57
|
-
return join(base, "savings_events.jsonl");
|
|
58
|
-
}
|
|
59
|
-
|
|
60
42
|
/**
|
|
61
43
|
* Truncates a possibly coloured string to a visible width, keeping escape
|
|
62
44
|
* sequences intact and always closing with a reset.
|
|
@@ -116,6 +98,28 @@ function age(timestamp, now) {
|
|
|
116
98
|
return `${Math.floor(seconds / 3600)}h`;
|
|
117
99
|
}
|
|
118
100
|
|
|
101
|
+
// Snapshot strings are data, never terminal escape sequences or extra rows.
|
|
102
|
+
function plain(value, fallback = "-") {
|
|
103
|
+
return stripAnsi(String(value ?? fallback)).replace(/[\x00-\x1f\x7f-\x9f]/g, " ");
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function timestamp(value) {
|
|
107
|
+
if (typeof value !== "string") return null;
|
|
108
|
+
const parsed = Date.parse(value);
|
|
109
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function stageList(event) {
|
|
113
|
+
return Array.isArray(event?.stages) ? event.stages.filter(s => s && typeof s === "object") : [];
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function savedTokens(value) {
|
|
117
|
+
if (!Number.isFinite(value)) return dim("non misurato");
|
|
118
|
+
if (value > 0) return green(`-${num(value)} tok`);
|
|
119
|
+
if (value < 0) return yellow(`+${num(-value)} tok`);
|
|
120
|
+
return dim("0 tok");
|
|
121
|
+
}
|
|
122
|
+
|
|
119
123
|
/** Wrap complete fields, falling back to words for long descriptions. */
|
|
120
124
|
function wrapCells(cells, width, separator = " | ", indent = " ") {
|
|
121
125
|
const lines = [];
|
|
@@ -129,14 +133,25 @@ function wrapCells(cells, width, separator = " | ", indent = " ") {
|
|
|
129
133
|
lines.push(line);
|
|
130
134
|
line = indent;
|
|
131
135
|
}
|
|
132
|
-
|
|
136
|
+
if (stripAnsi(word).length > width - indent.length) {
|
|
137
|
+
if (line !== indent) lines.push(line);
|
|
138
|
+
let remaining = stripAnsi(word);
|
|
139
|
+
const chunkWidth = Math.max(1, width - indent.length);
|
|
140
|
+
while (remaining.length > chunkWidth) {
|
|
141
|
+
lines.push(indent + remaining.slice(0, chunkWidth));
|
|
142
|
+
remaining = remaining.slice(chunkWidth);
|
|
143
|
+
}
|
|
144
|
+
line = indent + remaining;
|
|
145
|
+
} else line += (line === indent ? "" : " ") + word;
|
|
133
146
|
}
|
|
134
147
|
continue;
|
|
135
148
|
}
|
|
136
149
|
const next = line === indent ? cell : dim(separator) + cell;
|
|
137
150
|
if (line !== indent && stripAnsi(line + next).length > width) {
|
|
138
151
|
lines.push(line);
|
|
139
|
-
|
|
152
|
+
// Do not let the continuation arrow clip a field that just fits.
|
|
153
|
+
const arrow = separator === " -> " && stripAnsi(cell).length + indent.length + 3 <= width ? dim("-> ") : "";
|
|
154
|
+
line = indent + arrow + cell;
|
|
140
155
|
} else line += next;
|
|
141
156
|
}
|
|
142
157
|
if (line !== indent) lines.push(line);
|
|
@@ -166,14 +181,16 @@ function paintNode(node) {
|
|
|
166
181
|
}
|
|
167
182
|
|
|
168
183
|
export class Dashboard {
|
|
169
|
-
constructor({ getVersions = getServiceVersions } = {}) {
|
|
184
|
+
constructor({ getVersions = getServiceVersions, getProxyStats = readProxyStats } = {}) {
|
|
170
185
|
this.statuses = [];
|
|
171
186
|
this.getVersions = getVersions;
|
|
172
187
|
this.versions = {};
|
|
173
188
|
this.versionsKey = "";
|
|
174
189
|
this.versionsAt = 0;
|
|
175
190
|
this.versionsLoading = false;
|
|
176
|
-
this.
|
|
191
|
+
this.versionsGeneration = 0;
|
|
192
|
+
this.getProxyStats = getProxyStats;
|
|
193
|
+
this.metricsFile = getProxyStatsPath();
|
|
177
194
|
this.metricsAt = null;
|
|
178
195
|
this.metricsError = null;
|
|
179
196
|
this.metricsKey = "";
|
|
@@ -184,12 +201,7 @@ export class Dashboard {
|
|
|
184
201
|
this.chain = [];
|
|
185
202
|
this.chainAt = null;
|
|
186
203
|
this.showPipelineDetails = false;
|
|
187
|
-
this.health = null;
|
|
188
204
|
this.events = [];
|
|
189
|
-
this.eventsOffset = undefined;
|
|
190
|
-
this.eventsFile = getEventsFilePath();
|
|
191
|
-
this.eventsFileSeen = false;
|
|
192
|
-
this.savings = null;
|
|
193
205
|
this.proxyStats = null;
|
|
194
206
|
this.selected = 0;
|
|
195
207
|
this.status = "";
|
|
@@ -209,20 +221,21 @@ export class Dashboard {
|
|
|
209
221
|
const key = JSON.stringify(this.statuses.map(s => [s.id, s.status, s.pid, s.url]));
|
|
210
222
|
if (key !== this.versionsKey) {
|
|
211
223
|
this.versionsKey = key;
|
|
212
|
-
this.
|
|
213
|
-
this.versions = {};
|
|
224
|
+
this.invalidateVersions();
|
|
214
225
|
}
|
|
215
|
-
if (this.versionsLoading || (this.versionsAt && Date.now() - this.versionsAt < VERSION_CHECK_MS)) return;
|
|
226
|
+
if (this.busy || this.versionsLoading || (this.versionsAt && Date.now() - this.versionsAt < VERSION_CHECK_MS)) return;
|
|
216
227
|
|
|
228
|
+
const generation = this.versionsGeneration;
|
|
229
|
+
const isCurrent = () => key === this.versionsKey && generation === this.versionsGeneration;
|
|
217
230
|
this.versionsLoading = true;
|
|
218
231
|
try {
|
|
219
232
|
const versions = await this.getVersions(this.statuses);
|
|
220
|
-
if (
|
|
233
|
+
if (isCurrent()) this.versions = versions;
|
|
221
234
|
} catch {
|
|
222
235
|
// An unavailable registry must not interrupt service controls or metrics.
|
|
223
|
-
if (
|
|
236
|
+
if (isCurrent()) this.versions = {};
|
|
224
237
|
} finally {
|
|
225
|
-
if (
|
|
238
|
+
if (isCurrent()) this.versionsAt = Date.now();
|
|
226
239
|
this.versionsLoading = false;
|
|
227
240
|
this.render();
|
|
228
241
|
}
|
|
@@ -242,31 +255,31 @@ export class Dashboard {
|
|
|
242
255
|
this.selected = Math.max(0, this.statuses.length - 1);
|
|
243
256
|
}
|
|
244
257
|
|
|
245
|
-
const
|
|
246
|
-
const
|
|
247
|
-
|
|
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);
|
|
258
|
+
const proxy = this.statuses.find(s => s.id === "proxy");
|
|
259
|
+
const stats = await this.getProxyStats();
|
|
260
|
+
const probed = await probeChain(this.statuses, { nativeOnly: true });
|
|
256
261
|
const now = Date.now();
|
|
257
|
-
|
|
262
|
+
const metricsKey = JSON.stringify([proxy?.url, proxy?.pid, proxy?.status, stats?.since]);
|
|
263
|
+
if (metricsKey !== this.metricsKey || (stats && stats.requests < this.prevMetrics?.requests)) this.prevMetrics = null;
|
|
264
|
+
this.metricsKey = metricsKey;
|
|
265
|
+
if (stats) {
|
|
266
|
+
// updatedAt is the last preset event, not a heartbeat. An idle proxy's
|
|
267
|
+
// unchanged snapshot is still readable; retain its real last-event age.
|
|
268
|
+
this.proxyStats = stats;
|
|
269
|
+
this.metricsAt = now;
|
|
270
|
+
this.events = stats.recent.filter(ev => ev && typeof ev === "object" && !Array.isArray(ev)).slice(-MAX_EVENTS);
|
|
271
|
+
}
|
|
272
|
+
this.metricsError = !proxy ? "Proxy AIH non configurato"
|
|
273
|
+
: proxy.status !== "running" ? "Proxy AIH non in esecuzione"
|
|
274
|
+
: !stats ? "Statistiche proxy assenti o non valide" : null;
|
|
275
|
+
if (!this.metricsError) {
|
|
276
|
+
const counters = { requests: stats.requests };
|
|
258
277
|
this.sampleMs = this.prevMetrics ? now - this.prevAt : null;
|
|
259
|
-
this.rates = diffRates(this.prevMetrics,
|
|
260
|
-
this.prevMetrics =
|
|
278
|
+
this.rates = diffRates(this.prevMetrics, counters, this.sampleMs);
|
|
279
|
+
this.prevMetrics = counters;
|
|
261
280
|
this.prevAt = now;
|
|
262
|
-
this.metrics = parsed;
|
|
263
|
-
this.metricsAt = now;
|
|
264
|
-
this.metricsError = null;
|
|
265
281
|
} else {
|
|
266
|
-
// Keep the last totals for diagnosis, never
|
|
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";
|
|
282
|
+
// Keep the last totals and events for diagnosis, but never old rates.
|
|
270
283
|
this.rates = {};
|
|
271
284
|
this.prevMetrics = null;
|
|
272
285
|
this.sampleMs = null;
|
|
@@ -274,21 +287,11 @@ export class Dashboard {
|
|
|
274
287
|
|
|
275
288
|
this.chain = probed.nodes;
|
|
276
289
|
this.chainAt = now;
|
|
277
|
-
this.health = probed.health;
|
|
278
|
-
|
|
279
|
-
const tail = tailJsonl(this.eventsFile, this.eventsOffset, MAX_EVENTS);
|
|
280
|
-
this.eventsOffset = tail.offset;
|
|
281
|
-
if (tail.offset > 0) this.eventsFileSeen = true;
|
|
282
|
-
if (tail.events.length > 0) {
|
|
283
|
-
this.events = this.events.concat(tail.events).slice(-MAX_EVENTS);
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
this.savings = readSavingsBreakdown();
|
|
287
|
-
this.proxyStats = readProxyStats();
|
|
288
290
|
} catch (err) {
|
|
289
291
|
this.metricsError = "aggiornamento fallito";
|
|
290
292
|
this.rates = {};
|
|
291
293
|
this.prevMetrics = null;
|
|
294
|
+
this.sampleMs = null;
|
|
292
295
|
this.chainAt = null;
|
|
293
296
|
this.status = red(`Refresh error: ${err?.message || err}`);
|
|
294
297
|
} finally {
|
|
@@ -298,59 +301,130 @@ export class Dashboard {
|
|
|
298
301
|
|
|
299
302
|
/** Pipeline rows wrap whole fields rather than clipping useful values. */
|
|
300
303
|
pipelineLines(width, now = Date.now()) {
|
|
301
|
-
const lines = [bold("PIPELINE") + dim(" metriche
|
|
304
|
+
const lines = [bold("PIPELINE") + dim(" metriche proxy AIH")];
|
|
302
305
|
const add = (cells, separator) => lines.push(...wrapCells(cells, width, separator));
|
|
303
306
|
const chainFresh = this.chainAt !== null && now - this.chainAt <= STALE_MS;
|
|
304
307
|
add(this.chain.map(node => paintNode(chainFresh || node.state === "static"
|
|
305
308
|
? node : { ...node, state: "unknown" })), " -> ");
|
|
306
309
|
|
|
307
|
-
const stale = this.
|
|
310
|
+
const stale = this.metricsStale(now);
|
|
308
311
|
const freshness = this.metricsAt === null ? "nessun campione"
|
|
309
312
|
: `ultimo campione ${age(this.metricsAt, now)} fa`;
|
|
310
|
-
const freshnessText = stale ? yellow(`Dati non aggiornati: ${freshness}`) : `
|
|
313
|
+
const freshnessText = stale ? yellow(`Dati non aggiornati: ${freshness}`) : `Letti ${age(this.metricsAt, now)} fa`;
|
|
311
314
|
if (stripAnsi(lines[0] + " | " + freshnessText).length <= width) lines[0] += dim(" | ") + freshnessText;
|
|
312
315
|
else add([freshnessText]);
|
|
313
316
|
if (this.metricsError) add([yellow(this.metricsError)]);
|
|
314
317
|
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
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`;
|
|
318
|
+
const preset = this.statuses.find(s => s.id === "proxy")?.proxyOptions?.preset;
|
|
319
|
+
if (preset === "none") add([yellow("Preset none: traffico non registrato nelle metriche")]);
|
|
320
|
+
if (this.proxyStats) {
|
|
321
|
+
const m = this.proxyStats;
|
|
322
|
+
const lastAt = timestamp(m.updatedAt);
|
|
323
|
+
add([bold("Elaborazioni preset"), stale ? dim("attivita non disponibile")
|
|
324
|
+
: `${cyan(bold(num(this.rates.requests, 2)))} elab/s`,
|
|
325
|
+
`Ultimo evento ${lastAt === null ? "-" : age(lastAt, now) + " fa"}`]);
|
|
326
|
+
const changedRatio = Number.isFinite(m.changed) && m.requests > 0 ? m.changed / m.requests : null;
|
|
329
327
|
add([bold("Dall'avvio dei contatori") + (stale ? yellow(" (ultimo campione)") : "")]);
|
|
330
|
-
add([`
|
|
331
|
-
`
|
|
328
|
+
add([`Richieste ${bold(num(m.requests))}`, `Modificate ${bold(num(m.changed))} (${pct(changedRatio)})`,
|
|
329
|
+
`Errori preset ${m.errors > 0 ? red(bold(num(m.errors))) : num(m.errors)}`]);
|
|
330
|
+
add([`risparmio stimato ${bold(num(m.estimatedSavedTokens))} token${m.unmeasuredStages > 0 ? yellow(" (parziale)") : ""}`]);
|
|
331
|
+
for (const [name, stage] of Object.entries(m.stages || {})) {
|
|
332
|
+
if (!stage || typeof stage !== "object") continue;
|
|
333
|
+
add([`${plain(name)}: ${bold(num(stage.saved))} token`, `applicato ${num(stage.applied)}/${num(stage.requests)}`,
|
|
334
|
+
...(stage.unmeasured > 0 ? [yellow(`non misurati ${num(stage.unmeasured)}`)] : [])]);
|
|
335
|
+
}
|
|
332
336
|
}
|
|
337
|
+
add([dim("Stime dei preset; esclusi interceptor, cache e fatturazione.")]);
|
|
333
338
|
|
|
334
339
|
if (this.showPipelineDetails) {
|
|
340
|
+
add([`Fonte: ${plain(this.metricsFile)}`]);
|
|
341
|
+
if (this.proxyStats?.since) add([`Contatori dal ${plain(this.proxyStats.since)} (persistono ai riavvii)`]);
|
|
335
342
|
for (const node of this.chain) {
|
|
336
|
-
if (node.detail) add([`${node.label}: ${node.detail}`]);
|
|
343
|
+
if (node.detail) add([`${node.label}: ${plain(node.detail)}`]);
|
|
337
344
|
if (node.state === "running") add([yellow(`${node.label}: health non verificato`)]);
|
|
338
345
|
}
|
|
339
346
|
if (!chainFresh) add([yellow("Stati della catena non aggiornati")]);
|
|
340
|
-
if (this.
|
|
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)}`]);
|
|
347
|
+
if (this.proxyStats && !stale) {
|
|
343
348
|
add([dim(this.sampleMs === null ? "Velocita: in attesa del secondo campione"
|
|
344
349
|
: `Velocita: ultimo intervallo di ${(this.sampleMs / 1000).toFixed(1)} s`)]);
|
|
345
350
|
}
|
|
346
|
-
add([dim("
|
|
347
|
-
add([dim("
|
|
348
|
-
add([dim("
|
|
349
|
-
add([dim("Cache richieste != risparmio economico")]);
|
|
351
|
+
add([dim("elab/s: richieste elaborate dai preset, non tutto il traffico proxy")]);
|
|
352
|
+
add([dim("Risparmio: somma dei delta misurati per stadio; basi non sommabili")]);
|
|
353
|
+
add([dim("Errori preset != errori upstream; latenza e richieste in corso non misurate")]);
|
|
350
354
|
}
|
|
351
355
|
return lines.map(line => clip(line, width));
|
|
352
356
|
}
|
|
353
357
|
|
|
358
|
+
/** Updates can change an installed version without changing status or PID. */
|
|
359
|
+
invalidateVersions() {
|
|
360
|
+
this.versionsGeneration++;
|
|
361
|
+
this.versionsAt = 0;
|
|
362
|
+
this.versions = {};
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
metricsStale(now = Date.now()) {
|
|
366
|
+
return this.metricsAt === null || Boolean(this.metricsError) || now - this.metricsAt > STALE_MS;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** Native recent events are a bounded snapshot, not an append-only log. */
|
|
370
|
+
requestLines(event, width) {
|
|
371
|
+
const at = timestamp(event.at);
|
|
372
|
+
const time = at === null ? "--:--:--" : new Date(at).toLocaleTimeString("it-IT", { hour12: false });
|
|
373
|
+
const stages = stageList(event);
|
|
374
|
+
const partial = !event.error && stages.some(stage => !Number.isFinite(stage.saved));
|
|
375
|
+
const unmeasured = partial && stages.every(stage => !Number.isFinite(stage.saved));
|
|
376
|
+
const status = event.error ? red(bold("errore preset")) : event.changed === true ? green("modificata")
|
|
377
|
+
: event.changed === false ? dim("invariata") : dim("esito non disponibile");
|
|
378
|
+
const lines = wrapCells([gray(time), cyan(plain(event.transport)), magenta(plain(event.model, "?")),
|
|
379
|
+
plain(event.preset), status,
|
|
380
|
+
...(event.error ? [] : [savedTokens(unmeasured ? null : event.saved) + (partial && !unmeasured ? yellow(" (parziale)") : "")]),
|
|
381
|
+
...(!this.showPipelineDetails ? stages.map(s => dim(`${plain(s.name)}: ${plain(s.reason)}`)) : []),
|
|
382
|
+
], width, " ");
|
|
383
|
+
if (this.showPipelineDetails) {
|
|
384
|
+
for (const stage of stages) {
|
|
385
|
+
const ratio = Number.isFinite(stage.before) && stage.before > 0 && Number.isFinite(stage.saved)
|
|
386
|
+
? stage.saved / stage.before : null;
|
|
387
|
+
lines.push(...wrapCells([`${plain(stage.name)}: ${stage.applied ? "applicato" : "bypass"}`,
|
|
388
|
+
`${num(stage.before)} -> ${num(stage.after)} tok (${pct(ratio)})`,
|
|
389
|
+
plain(stage.reason), dim(plain(stage.method)),
|
|
390
|
+
], width, " | ", " "));
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
return lines;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
streamLines(width, maxRows = Infinity, now = Date.now()) {
|
|
397
|
+
if (maxRows <= 0) return [];
|
|
398
|
+
const lines = [clip(bold("STREAM RICHIESTE")
|
|
399
|
+
+ (this.metricsStale(now) && this.proxyStats ? yellow(" (storico)") : "")
|
|
400
|
+
+ dim(" proxy AIH / elaborazioni preset"), width)];
|
|
401
|
+
if (maxRows === 1) return lines;
|
|
402
|
+
if (!this.events.length) {
|
|
403
|
+
const preset = this.statuses.find(s => s.id === "proxy")?.proxyOptions?.preset;
|
|
404
|
+
const message = preset === "none" ? "preset none: nessun evento di elaborazione"
|
|
405
|
+
: this.proxyStats ? "in attesa di richieste elaborate dai preset..."
|
|
406
|
+
: "nessun evento proxy disponibile";
|
|
407
|
+
return lines.concat(wrapCells([dim(message)], width).slice(0, maxRows - 1));
|
|
408
|
+
}
|
|
409
|
+
const groups = [];
|
|
410
|
+
let available = maxRows - lines.length;
|
|
411
|
+
// Keep newest complete entries, then show them in chronological order.
|
|
412
|
+
for (const event of this.events.slice().reverse()) {
|
|
413
|
+
const group = this.requestLines(event, width);
|
|
414
|
+
if (group.length > available) {
|
|
415
|
+
if (!groups.length) {
|
|
416
|
+
const clipped = group.slice(0, available);
|
|
417
|
+
if (clipped.length) clipped[clipped.length - 1] = clip(clipped.at(-1), Math.max(0, width - 4)) + dim(" ...");
|
|
418
|
+
groups.unshift(clipped);
|
|
419
|
+
}
|
|
420
|
+
break;
|
|
421
|
+
}
|
|
422
|
+
groups.unshift(group);
|
|
423
|
+
available -= group.length;
|
|
424
|
+
}
|
|
425
|
+
return lines.concat(groups.flat());
|
|
426
|
+
}
|
|
427
|
+
|
|
354
428
|
/**
|
|
355
429
|
* Builds the whole screen as an array of lines.
|
|
356
430
|
* @returns {string[]}
|
|
@@ -368,6 +442,7 @@ export class Dashboard {
|
|
|
368
442
|
`${dim("s")} start`,
|
|
369
443
|
`${dim("x")} stop`,
|
|
370
444
|
`${dim("r")} restart`,
|
|
445
|
+
`${dim("u")} update`,
|
|
371
446
|
`${dim("k")} kill`,
|
|
372
447
|
...(svc?.dashboardUrl ? [`${dim("o")} dashboard`] : []),
|
|
373
448
|
...(svc?.repositoryUrl ? [`${dim("g")} GitHub`] : []),
|
|
@@ -426,63 +501,31 @@ export class Dashboard {
|
|
|
426
501
|
}
|
|
427
502
|
lines.push("");
|
|
428
503
|
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
if (
|
|
433
|
-
lines.push("");
|
|
434
|
-
}
|
|
435
|
-
|
|
436
|
-
lines.push(...this.pipelineLines(width));
|
|
437
|
-
lines.push("");
|
|
438
|
-
|
|
439
|
-
lines.push(bold("STREAM RICHIESTE") + dim(" " + this.eventsFile));
|
|
440
|
-
|
|
441
|
-
// Every event in the stream is source "proxy": headroom is the only service
|
|
442
|
-
// that reports per-request savings. The split below is the one place that
|
|
443
|
-
// says how much came from compression versus provider cache reuse.
|
|
444
|
-
if (this.savings) {
|
|
445
|
-
const sv = this.savings;
|
|
446
|
-
const savingsCells = [
|
|
447
|
-
`${dim("risparmio")} ${green(bold(num(sv.total)))}`,
|
|
448
|
-
`${dim("compress")} ${bold(num(sv.compression))}`,
|
|
449
|
-
`${dim("cache")} ${bold(num(sv.cacheReads))}`,
|
|
450
|
-
`${dim("inviati")} ${bold(num(sv.submitted))}`,
|
|
451
|
-
`${dim("efficienza")} ${green(bold(pct(sv.ratio)))}`,
|
|
452
|
-
];
|
|
453
|
-
lines.push(" " + savingsCells.join(dim(" . ")));
|
|
504
|
+
const bodyLimit = height - footerLines;
|
|
505
|
+
if (lines.length > bodyLimit - 4) {
|
|
506
|
+
lines.length = Math.max(0, bodyLimit - 4);
|
|
507
|
+
if (lines.length) lines[lines.length - 1] = dim(" ... servizi: aumenta l'altezza");
|
|
454
508
|
}
|
|
455
|
-
|
|
456
|
-
const
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
const after = Number(ev.after);
|
|
472
|
-
const saved = Number(ev.saved);
|
|
473
|
-
const ratio = Number.isFinite(before) && before > 0 ? saved / before : null;
|
|
474
|
-
const cost = Number(ev.cost_usd);
|
|
475
|
-
const cells = [
|
|
476
|
-
gray(time),
|
|
477
|
-
magenta(String(ev.model || "?").padEnd(16).slice(0, 16)),
|
|
478
|
-
`${dim("tok")} ${num(before)}${gray("->")}${num(after)}`,
|
|
479
|
-
green(`-${num(saved)} (${pct(ratio)})`),
|
|
480
|
-
dim(Number.isFinite(cost) ? "$" + cost.toFixed(4) : "-"),
|
|
481
|
-
dim(String(ev.source || ev.client || "")),
|
|
482
|
-
];
|
|
483
|
-
lines.push(" " + cells.join(" "));
|
|
484
|
-
}
|
|
509
|
+
const room = bodyLimit - lines.length;
|
|
510
|
+
const streamRows = this.events.length ? Math.min(6, Math.max(2, Math.floor(room / 3))) : 2;
|
|
511
|
+
const pipelineBudget = room - streamRows - 1;
|
|
512
|
+
let pipeline = this.pipelineLines(width);
|
|
513
|
+
if (pipeline.length > pipelineBudget) {
|
|
514
|
+
// Never let expanded pipeline explanations consume the request stream.
|
|
515
|
+
// On small screens prioritize native totals over the topology/details.
|
|
516
|
+
const m = this.proxyStats;
|
|
517
|
+
const header = m && this.metricsStale() ? bold("PIPELINE") + yellow(" (storico)") + dim(" metriche proxy AIH") : pipeline[0];
|
|
518
|
+
pipeline = [header, ...wrapCells(m ? [
|
|
519
|
+
`Richieste ${num(m.requests)}`, `Modificate ${num(m.changed)}`, `Errori preset ${num(m.errors)}`,
|
|
520
|
+
`risparmio stimato ${num(m.estimatedSavedTokens)} token${m.unmeasuredStages > 0 ? " (parziale)" : ""}`,
|
|
521
|
+
...(this.metricsStale() ? [yellow("Dati storici / attivita non disponibile")] : []),
|
|
522
|
+
] : [yellow(this.metricsError || "nessun campione")], width)];
|
|
523
|
+
pipeline = pipeline.slice(0, Math.max(1, pipelineBudget - 1));
|
|
524
|
+
if (pipelineBudget > 1) pipeline.push(dim(" ... aumenta l'altezza per la pipeline"));
|
|
485
525
|
}
|
|
526
|
+
lines.push(...pipeline);
|
|
527
|
+
lines.push("");
|
|
528
|
+
lines.push(...this.streamLines(width, Math.max(2, height - lines.length - footerLines)));
|
|
486
529
|
|
|
487
530
|
while (lines.length < height - footerLines) lines.push("");
|
|
488
531
|
// Keep controls reachable even when expanded details exceed the terminal.
|
|
@@ -565,6 +608,16 @@ export class Dashboard {
|
|
|
565
608
|
case "r":
|
|
566
609
|
this.runAction("Riavvio", svc => manager.restartService(svc.id));
|
|
567
610
|
return;
|
|
611
|
+
case "u":
|
|
612
|
+
return this.runAction("Aggiornamento", async svc => {
|
|
613
|
+
this.invalidateVersions();
|
|
614
|
+
try {
|
|
615
|
+
return await manager.updateService(svc.id);
|
|
616
|
+
} finally {
|
|
617
|
+
// Drop pre-update and mid-update checks even if installation failed.
|
|
618
|
+
this.invalidateVersions();
|
|
619
|
+
}
|
|
620
|
+
});
|
|
568
621
|
case "k":
|
|
569
622
|
this.runAction("Kill", async svc => {
|
|
570
623
|
if (!svc.pid) return { success: false, message: `${svc.id}: nessun PID da terminare` };
|
package/src/utils/metrics.js
CHANGED
|
@@ -253,28 +253,33 @@ export async function fetchJson(url, timeoutMs = 2000) {
|
|
|
253
253
|
|
|
254
254
|
/**
|
|
255
255
|
* Resolves the operational pipeline the AI calls flow through.
|
|
256
|
-
*
|
|
257
|
-
*
|
|
258
|
-
*
|
|
259
|
-
*
|
|
256
|
+
* Native topology uses only the proxy's configured stages and process state;
|
|
257
|
+
* an upstream URL is configuration, not proof that the destination is healthy.
|
|
258
|
+
* Without a proxy, legacy callers may still probe headroom's /health. Set
|
|
259
|
+
* nativeOnly to prevent that fallback when native proxy status is unavailable.
|
|
260
|
+
* @param {Array<{ id: string; status: string; url?: string; proxyOptions?: object }>} statuses
|
|
261
|
+
* @param {{ nativeOnly?: boolean }} [options]
|
|
260
262
|
* @returns {Promise<{ nodes: Array<{ id: string; label: string; state: string; detail: string }>; health: any | null }>}
|
|
261
263
|
*/
|
|
262
|
-
export async function probeChain(statuses) {
|
|
264
|
+
export async function probeChain(statuses, { nativeOnly = false } = {}) {
|
|
263
265
|
const byId = {};
|
|
264
266
|
for (const svc of statuses || []) byId[svc.id] = svc;
|
|
265
267
|
|
|
266
268
|
const proxy = byId.proxy;
|
|
267
|
-
if (proxy
|
|
268
|
-
const
|
|
269
|
-
const
|
|
270
|
-
|
|
271
|
-
|
|
269
|
+
if (proxy || nativeOnly) {
|
|
270
|
+
const options = proxy?.proxyOptions || {};
|
|
271
|
+
const preset = typeof options.preset === "string" ? options.preset : "none";
|
|
272
|
+
const labels = { pxpipe: "pxpipe (libreria)", rtk: "rtk (pipe)", headroom: "headroom (compress)" };
|
|
273
|
+
const stages = preset.split("-").filter(id => Object.hasOwn(labels, id)).map(id => ({
|
|
274
|
+
id, label: labels[id],
|
|
275
|
+
state: id === "pxpipe" ? proxy?.status || "unknown" : "static",
|
|
276
|
+
detail: id === "headroom" ? options.headroomUrl || "" : "",
|
|
272
277
|
}));
|
|
273
278
|
return { nodes: [
|
|
274
279
|
{ id: "client", label: "client", state: "static", detail: "AI agents / CLI" },
|
|
275
|
-
{ id: "proxy", label: "aih proxy", state: proxy
|
|
280
|
+
{ id: "proxy", label: "aih proxy", state: proxy?.status || "unknown", detail: proxy?.url || "" },
|
|
276
281
|
...stages,
|
|
277
|
-
{ id: "upstream", label: "upstream", state: "
|
|
282
|
+
{ id: "upstream", label: "upstream", state: "unknown", detail: options.upstream || "" },
|
|
278
283
|
], health: null };
|
|
279
284
|
}
|
|
280
285
|
|
package/src/utils/versions.js
CHANGED
|
@@ -2,13 +2,7 @@ import { execFile } from "node:child_process";
|
|
|
2
2
|
import { readFile, realpath } from "node:fs/promises";
|
|
3
3
|
import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
|
|
4
4
|
import { baseUrl, fetchJson } from "./metrics.js";
|
|
5
|
-
|
|
6
|
-
const PACKAGES = {
|
|
7
|
-
pxpipe: { name: "pxpipe-proxy", bin: "pxpipe" },
|
|
8
|
-
ocx: { name: "@bitkyc08/opencodex", bin: "ocx", health: "/healthz", service: "opencodex" },
|
|
9
|
-
agentmemory: { name: "@agentmemory/agentmemory", bin: "agentmemory", health: "/agentmemory/health", service: "agentmemory" },
|
|
10
|
-
headroom: { name: "headroom-ai", bin: "headroom", health: "/health", pypi: true },
|
|
11
|
-
};
|
|
5
|
+
import { SERVICE_PACKAGES as PACKAGES } from "../config.js";
|
|
12
6
|
|
|
13
7
|
function parseVersion(value) {
|
|
14
8
|
if (typeof value !== "string") return null;
|