@drakonkat/ai-helper 1.1.0 → 1.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +14 -3
- package/CHANGELOG.md +15 -0
- package/README.md +417 -24
- package/docs/benchmark.md +273 -0
- package/package.json +17 -5
- package/scripts/bench-proxy.js +107 -0
- package/scripts/build.js +16 -0
- package/src/benchmark/fixtures.js +150 -0
- package/src/benchmark/live.js +78 -0
- package/src/benchmark/measurement.js +180 -0
- package/src/benchmark/quality.js +144 -0
- package/src/benchmark/report.js +141 -0
- package/src/benchmark/runner.js +269 -0
- package/src/codex-config.js +247 -0
- package/src/codex-routing.js +132 -0
- package/src/config.js +11 -1
- package/src/index.js +112 -22
- package/src/manager.js +126 -13
- package/src/proxy-interceptor.example.mjs +33 -0
- package/src/proxy-presets.js +226 -0
- package/src/proxy-stats.js +64 -0
- package/src/proxy-worker.js +17 -0
- package/src/proxy.js +313 -0
- package/src/tui.js +694 -0
- package/src/update.js +41 -0
- package/src/utils/metrics.js +315 -0
- package/src/utils/process.js +120 -140
- package/src/utils/versions.js +171 -0
package/src/tui.js
ADDED
|
@@ -0,0 +1,694 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { 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 } from "./utils/process.js";
|
|
21
|
+
import { readProxyStats, proxyStatsLines } from "./proxy-stats.js";
|
|
22
|
+
import { getServiceVersions } from "./utils/versions.js";
|
|
23
|
+
import {
|
|
24
|
+
baseUrl,
|
|
25
|
+
diffRates,
|
|
26
|
+
fetchText,
|
|
27
|
+
parseProm,
|
|
28
|
+
probeChain,
|
|
29
|
+
readSavingsBreakdown,
|
|
30
|
+
tailJsonl,
|
|
31
|
+
} from "./utils/metrics.js";
|
|
32
|
+
|
|
33
|
+
const TICK_MS = 1000;
|
|
34
|
+
const STALE_MS = 5 * TICK_MS;
|
|
35
|
+
const VERSION_CHECK_MS = 5 * 60 * 1000;
|
|
36
|
+
const MAX_EVENTS = 200;
|
|
37
|
+
|
|
38
|
+
const ALT_SCREEN_ON = "\x1b[?1049h";
|
|
39
|
+
const ALT_SCREEN_OFF = "\x1b[?1049l";
|
|
40
|
+
const CURSOR_HIDE = "\x1b[?25l";
|
|
41
|
+
const CURSOR_SHOW = "\x1b[?25h";
|
|
42
|
+
const CURSOR_HOME = "\x1b[H";
|
|
43
|
+
const CLEAR_LINE = "\x1b[K";
|
|
44
|
+
const CLEAR_BELOW = "\x1b[J";
|
|
45
|
+
const RESET = "\x1b[0m";
|
|
46
|
+
const KEY_UP = "\x1b[A";
|
|
47
|
+
const KEY_DOWN = "\x1b[B";
|
|
48
|
+
|
|
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
|
+
/**
|
|
61
|
+
* Truncates a possibly coloured string to a visible width, keeping escape
|
|
62
|
+
* sequences intact and always closing with a reset.
|
|
63
|
+
* @param {string} text
|
|
64
|
+
* @param {number} width
|
|
65
|
+
* @returns {string}
|
|
66
|
+
*/
|
|
67
|
+
function clip(text, width) {
|
|
68
|
+
if (width <= 0) return "";
|
|
69
|
+
const str = String(text);
|
|
70
|
+
if (stripAnsi(str).length <= width) return str;
|
|
71
|
+
|
|
72
|
+
let out = "";
|
|
73
|
+
let visible = 0;
|
|
74
|
+
let i = 0;
|
|
75
|
+
while (i < str.length && visible < width) {
|
|
76
|
+
if (str[i] === "\x1b") {
|
|
77
|
+
const end = str.indexOf("m", i);
|
|
78
|
+
if (end === -1) break;
|
|
79
|
+
out += str.slice(i, end + 1);
|
|
80
|
+
i = end + 1;
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
out += str[i];
|
|
84
|
+
visible++;
|
|
85
|
+
i++;
|
|
86
|
+
}
|
|
87
|
+
return out + RESET;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Compact human formatting for counters and rates.
|
|
92
|
+
* @param {number | null | undefined} value
|
|
93
|
+
* @param {number} [decimals]
|
|
94
|
+
* @returns {string}
|
|
95
|
+
*/
|
|
96
|
+
function num(value, decimals = 0) {
|
|
97
|
+
if (value === null || value === undefined || !Number.isFinite(value)) return "-";
|
|
98
|
+
if (Math.abs(value) >= 1000000) return `${(value / 1000000).toFixed(1)}M`;
|
|
99
|
+
if (Math.abs(value) >= 1000) return `${(value / 1000).toFixed(1)}k`;
|
|
100
|
+
return value.toFixed(decimals);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* @param {number | null | undefined} value
|
|
105
|
+
* @returns {string}
|
|
106
|
+
*/
|
|
107
|
+
function pct(value) {
|
|
108
|
+
if (value === null || value === undefined || !Number.isFinite(value)) return "-";
|
|
109
|
+
return `${(value * 100).toFixed(1)}%`;
|
|
110
|
+
}
|
|
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
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Colours a pipeline node by its live state.
|
|
148
|
+
* @param {{ label: string; state: string }} node
|
|
149
|
+
* @returns {string}
|
|
150
|
+
*/
|
|
151
|
+
function paintNode(node) {
|
|
152
|
+
switch (node.state) {
|
|
153
|
+
case "healthy":
|
|
154
|
+
return green(`[ ${node.label}: verificato ]`);
|
|
155
|
+
case "running":
|
|
156
|
+
return `[ ${node.label}: processo attivo ]`;
|
|
157
|
+
case "error":
|
|
158
|
+
return red(bold(`[ ${node.label}: errore ]`));
|
|
159
|
+
case "stopped":
|
|
160
|
+
return dim(`[ ${node.label}: fermo ]`);
|
|
161
|
+
case "static":
|
|
162
|
+
return `[ ${node.label} ]`;
|
|
163
|
+
default:
|
|
164
|
+
return yellow(`[ ${node.label}: non verificato ]`);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export class Dashboard {
|
|
169
|
+
constructor({ getVersions = getServiceVersions } = {}) {
|
|
170
|
+
this.statuses = [];
|
|
171
|
+
this.getVersions = getVersions;
|
|
172
|
+
this.versions = {};
|
|
173
|
+
this.versionsKey = "";
|
|
174
|
+
this.versionsAt = 0;
|
|
175
|
+
this.versionsLoading = false;
|
|
176
|
+
this.metrics = null;
|
|
177
|
+
this.metricsAt = null;
|
|
178
|
+
this.metricsError = null;
|
|
179
|
+
this.metricsKey = "";
|
|
180
|
+
this.sampleMs = null;
|
|
181
|
+
this.rates = {};
|
|
182
|
+
this.prevMetrics = null;
|
|
183
|
+
this.prevAt = 0;
|
|
184
|
+
this.chain = [];
|
|
185
|
+
this.chainAt = null;
|
|
186
|
+
this.showPipelineDetails = false;
|
|
187
|
+
this.health = null;
|
|
188
|
+
this.events = [];
|
|
189
|
+
this.eventsOffset = undefined;
|
|
190
|
+
this.eventsFile = getEventsFilePath();
|
|
191
|
+
this.eventsFileSeen = false;
|
|
192
|
+
this.savings = null;
|
|
193
|
+
this.proxyStats = null;
|
|
194
|
+
this.selected = 0;
|
|
195
|
+
this.status = "";
|
|
196
|
+
this.busy = false;
|
|
197
|
+
this.running = false;
|
|
198
|
+
this.timer = null;
|
|
199
|
+
this.refreshing = false;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** @returns {any} */
|
|
203
|
+
currentService() {
|
|
204
|
+
return this.statuses[this.selected];
|
|
205
|
+
}
|
|
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
|
+
|
|
231
|
+
/**
|
|
232
|
+
* One data tick. Every source is optional: a failing fetch degrades its own
|
|
233
|
+
* panel and never breaks the loop.
|
|
234
|
+
*/
|
|
235
|
+
async refresh() {
|
|
236
|
+
if (this.refreshing) return;
|
|
237
|
+
this.refreshing = true;
|
|
238
|
+
try {
|
|
239
|
+
this.statuses = await manager.getStatus();
|
|
240
|
+
void this.refreshVersions();
|
|
241
|
+
if (this.selected >= this.statuses.length) {
|
|
242
|
+
this.selected = Math.max(0, this.statuses.length - 1);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const headroom = this.statuses.find(s => s.id === "headroom");
|
|
246
|
+
const headroomBase = headroom && headroom.status === "running" ? baseUrl(headroom.url) : "";
|
|
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);
|
|
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);
|
|
260
|
+
this.prevMetrics = parsed;
|
|
261
|
+
this.prevAt = now;
|
|
262
|
+
this.metrics = parsed;
|
|
263
|
+
this.metricsAt = now;
|
|
264
|
+
this.metricsError = null;
|
|
265
|
+
} else {
|
|
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";
|
|
270
|
+
this.rates = {};
|
|
271
|
+
this.prevMetrics = null;
|
|
272
|
+
this.sampleMs = null;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
this.chain = probed.nodes;
|
|
276
|
+
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
|
+
} catch (err) {
|
|
289
|
+
this.metricsError = "aggiornamento fallito";
|
|
290
|
+
this.rates = {};
|
|
291
|
+
this.prevMetrics = null;
|
|
292
|
+
this.chainAt = null;
|
|
293
|
+
this.status = red(`Refresh error: ${err?.message || err}`);
|
|
294
|
+
} finally {
|
|
295
|
+
this.refreshing = false;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
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
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Builds the whole screen as an array of lines.
|
|
356
|
+
* @returns {string[]}
|
|
357
|
+
*/
|
|
358
|
+
buildLines() {
|
|
359
|
+
const width = Math.max(40, process.stdout.columns || 100);
|
|
360
|
+
const height = Math.max(12, process.stdout.rows || 30);
|
|
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;
|
|
376
|
+
|
|
377
|
+
const title = `${bold(cyan(APP_NAME))} ${gray("v" + VERSION)} ${dim("live dashboard")}`;
|
|
378
|
+
const clock = dim(new Date().toLocaleTimeString());
|
|
379
|
+
const titlePad = Math.max(1, width - stripAnsi(title).length - stripAnsi(clock).length);
|
|
380
|
+
lines.push(title + " ".repeat(titlePad) + clock);
|
|
381
|
+
lines.push(gray("-".repeat(width)));
|
|
382
|
+
|
|
383
|
+
const headers = [
|
|
384
|
+
" ",
|
|
385
|
+
"SERVICE",
|
|
386
|
+
"STATUS",
|
|
387
|
+
"VERSION",
|
|
388
|
+
"UPDATE",
|
|
389
|
+
{ header: "PID", align: "right" },
|
|
390
|
+
{ header: "UPTIME", align: "right" },
|
|
391
|
+
"REPO",
|
|
392
|
+
"URL",
|
|
393
|
+
];
|
|
394
|
+
const rows = this.statuses.map((s, idx) => {
|
|
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");
|
|
402
|
+
return [
|
|
403
|
+
active ? cyan(bold(">")) : " ",
|
|
404
|
+
active ? bold(white(s.id)) : bold(s.id),
|
|
405
|
+
badgeStatus(s.status),
|
|
406
|
+
version?.version || dim("n/d"),
|
|
407
|
+
update,
|
|
408
|
+
s.pid ? String(s.pid) : dim("-"),
|
|
409
|
+
s.status === "running" ? s.uptime : dim("-"),
|
|
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 || "-"),
|
|
412
|
+
];
|
|
413
|
+
});
|
|
414
|
+
if (rows.length > 0) {
|
|
415
|
+
const table = renderTable(headers, rows).split("\n");
|
|
416
|
+
for (const line of table) lines.push(line);
|
|
417
|
+
} else {
|
|
418
|
+
lines.push(dim(" No services."));
|
|
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
|
+
}
|
|
427
|
+
lines.push("");
|
|
428
|
+
|
|
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("");
|
|
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(" . ")));
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
const slots = Math.max(1, height - lines.length - footerLines);
|
|
457
|
+
|
|
458
|
+
if (this.events.length === 0) {
|
|
459
|
+
lines.push(
|
|
460
|
+
" " +
|
|
461
|
+
dim(
|
|
462
|
+
this.eventsFileSeen
|
|
463
|
+
? "in attesa di richieste..."
|
|
464
|
+
: "nessun file eventi: headroom non ha ancora scritto savings_events.jsonl"
|
|
465
|
+
)
|
|
466
|
+
);
|
|
467
|
+
} else {
|
|
468
|
+
for (const ev of this.events.slice(-slots)) {
|
|
469
|
+
const time = ev.ts ? String(ev.ts).slice(11, 19) : "--:--:--";
|
|
470
|
+
const before = Number(ev.before);
|
|
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
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
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
|
+
}
|
|
493
|
+
lines.push(gray("-".repeat(width)));
|
|
494
|
+
|
|
495
|
+
lines.push(...keyLines);
|
|
496
|
+
lines.push(this.busy ? yellow(this.status) : this.status || dim("pronto"));
|
|
497
|
+
|
|
498
|
+
return lines.slice(0, height).map(line => clip(line, width));
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
render() {
|
|
502
|
+
if (!this.running) return;
|
|
503
|
+
const painted = this.buildLines().map(line => line + CLEAR_LINE);
|
|
504
|
+
process.stdout.write(CURSOR_HOME + painted.join("\n") + CLEAR_BELOW);
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* Runs a manager action, keeping the UI responsive and always refreshing
|
|
509
|
+
* afterwards so the table reflects the new reality.
|
|
510
|
+
* @param {string} label
|
|
511
|
+
* @param {(svc: any) => Promise<any>} action
|
|
512
|
+
*/
|
|
513
|
+
async runAction(label, action) {
|
|
514
|
+
if (this.busy) return;
|
|
515
|
+
const svc = this.currentService();
|
|
516
|
+
if (!svc) return;
|
|
517
|
+
|
|
518
|
+
this.busy = true;
|
|
519
|
+
this.status = `${label} ${svc.id}...`;
|
|
520
|
+
this.render();
|
|
521
|
+
|
|
522
|
+
try {
|
|
523
|
+
const res = await action(svc);
|
|
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);
|
|
527
|
+
} catch (err) {
|
|
528
|
+
this.status = red(`${label} ${svc.id}: ${err?.message || err}`);
|
|
529
|
+
} finally {
|
|
530
|
+
this.busy = false;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
await this.refresh();
|
|
534
|
+
this.render();
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/**
|
|
538
|
+
* @param {string} key
|
|
539
|
+
*/
|
|
540
|
+
onKey(key) {
|
|
541
|
+
if (key === "\u0003" || key === "q") {
|
|
542
|
+
this.stop();
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
switch (key) {
|
|
547
|
+
case "d":
|
|
548
|
+
this.showPipelineDetails = !this.showPipelineDetails;
|
|
549
|
+
this.render();
|
|
550
|
+
return;
|
|
551
|
+
case KEY_UP:
|
|
552
|
+
this.selected = Math.max(0, this.selected - 1);
|
|
553
|
+
this.render();
|
|
554
|
+
return;
|
|
555
|
+
case KEY_DOWN:
|
|
556
|
+
this.selected = Math.min(this.statuses.length - 1, this.selected + 1);
|
|
557
|
+
this.render();
|
|
558
|
+
return;
|
|
559
|
+
case "s":
|
|
560
|
+
this.runAction("Avvio", svc => manager.startService(svc.id));
|
|
561
|
+
return;
|
|
562
|
+
case "x":
|
|
563
|
+
this.runAction("Stop", svc => manager.stopService(svc.id));
|
|
564
|
+
return;
|
|
565
|
+
case "r":
|
|
566
|
+
this.runAction("Riavvio", svc => manager.restartService(svc.id));
|
|
567
|
+
return;
|
|
568
|
+
case "k":
|
|
569
|
+
this.runAction("Kill", async svc => {
|
|
570
|
+
if (!svc.pid) return { success: false, message: `${svc.id}: nessun PID da terminare` };
|
|
571
|
+
return killProcessTree(svc.pid);
|
|
572
|
+
});
|
|
573
|
+
return;
|
|
574
|
+
case "o":
|
|
575
|
+
if (!this.currentService()?.dashboardUrl) return;
|
|
576
|
+
this.runAction("Dashboard", async svc => {
|
|
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" };
|
|
586
|
+
});
|
|
587
|
+
return;
|
|
588
|
+
default:
|
|
589
|
+
return;
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
enterScreen() {
|
|
594
|
+
process.stdout.write(ALT_SCREEN_ON + CURSOR_HIDE);
|
|
595
|
+
if (process.stdin.isTTY) {
|
|
596
|
+
process.stdin.setRawMode(true);
|
|
597
|
+
process.stdin.resume();
|
|
598
|
+
process.stdin.setEncoding("utf-8");
|
|
599
|
+
process.stdin.on("data", this.onData);
|
|
600
|
+
}
|
|
601
|
+
process.stdout.on("resize", this.onResize);
|
|
602
|
+
process.on("SIGINT", this.onSigint);
|
|
603
|
+
process.on("uncaughtException", this.onFatal);
|
|
604
|
+
process.on("unhandledRejection", this.onFatal);
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
/** Always restores the terminal, even on a crash. */
|
|
608
|
+
leaveScreen() {
|
|
609
|
+
if (process.stdin.isTTY) {
|
|
610
|
+
try {
|
|
611
|
+
process.stdin.setRawMode(false);
|
|
612
|
+
} catch {}
|
|
613
|
+
process.stdin.off("data", this.onData);
|
|
614
|
+
process.stdin.pause();
|
|
615
|
+
}
|
|
616
|
+
process.stdout.off("resize", this.onResize);
|
|
617
|
+
process.off("SIGINT", this.onSigint);
|
|
618
|
+
process.off("uncaughtException", this.onFatal);
|
|
619
|
+
process.off("unhandledRejection", this.onFatal);
|
|
620
|
+
process.stdout.write(CURSOR_SHOW + ALT_SCREEN_OFF);
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
stop() {
|
|
624
|
+
if (!this.running) return;
|
|
625
|
+
this.running = false;
|
|
626
|
+
if (this.timer) clearInterval(this.timer);
|
|
627
|
+
this.timer = null;
|
|
628
|
+
this.leaveScreen();
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
async start() {
|
|
632
|
+
this.onData = chunk => {
|
|
633
|
+
for (const key of splitKeys(String(chunk))) this.onKey(key);
|
|
634
|
+
};
|
|
635
|
+
this.onResize = () => this.render();
|
|
636
|
+
this.onSigint = () => this.stop();
|
|
637
|
+
this.onFatal = err => {
|
|
638
|
+
this.stop();
|
|
639
|
+
console.error(red(`[aih] ${err?.message || err}`));
|
|
640
|
+
process.exitCode = 1;
|
|
641
|
+
};
|
|
642
|
+
|
|
643
|
+
this.running = true;
|
|
644
|
+
this.enterScreen();
|
|
645
|
+
|
|
646
|
+
await this.refresh();
|
|
647
|
+
this.render();
|
|
648
|
+
|
|
649
|
+
this.timer = setInterval(async () => {
|
|
650
|
+
if (!this.running || this.busy) return;
|
|
651
|
+
await this.refresh();
|
|
652
|
+
this.render();
|
|
653
|
+
}, TICK_MS);
|
|
654
|
+
|
|
655
|
+
await new Promise(resolve => {
|
|
656
|
+
const check = setInterval(() => {
|
|
657
|
+
if (!this.running) {
|
|
658
|
+
clearInterval(check);
|
|
659
|
+
resolve();
|
|
660
|
+
}
|
|
661
|
+
}, 100);
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
/**
|
|
667
|
+
* Splits a raw stdin chunk into individual keys, keeping arrow escape
|
|
668
|
+
* sequences whole so a fast keypress burst is not misread as letters.
|
|
669
|
+
* @param {string} chunk
|
|
670
|
+
* @returns {string[]}
|
|
671
|
+
*/
|
|
672
|
+
export function splitKeys(chunk) {
|
|
673
|
+
const keys = [];
|
|
674
|
+
let i = 0;
|
|
675
|
+
while (i < chunk.length) {
|
|
676
|
+
if (chunk[i] === "\x1b" && chunk[i + 1] === "[" && chunk[i + 2]) {
|
|
677
|
+
keys.push(chunk.slice(i, i + 3));
|
|
678
|
+
i += 3;
|
|
679
|
+
continue;
|
|
680
|
+
}
|
|
681
|
+
keys.push(chunk[i]);
|
|
682
|
+
i++;
|
|
683
|
+
}
|
|
684
|
+
return keys;
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/**
|
|
688
|
+
* Entry point for the interactive dashboard.
|
|
689
|
+
* @returns {Promise<void>}
|
|
690
|
+
*/
|
|
691
|
+
export async function runDashboard() {
|
|
692
|
+
const dashboard = new Dashboard();
|
|
693
|
+
await dashboard.start();
|
|
694
|
+
}
|