@drakonkat/ai-helper 1.2.17 → 1.2.19
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 +21 -4
- package/CHANGELOG.md +28 -0
- package/README.md +131 -40
- package/package.json +5 -4
- package/src/config.js +12 -12
- package/src/health.js +81 -0
- package/src/hindsight.js +285 -0
- package/src/index.js +34 -14
- package/src/manager.js +350 -9
- package/src/proxy.js +10 -0
- package/src/startup-services.js +5 -2
- package/src/tui-proxy-setup.js +81 -9
- package/src/tui.js +155 -93
- package/src/utils/metrics.js +3 -3
- package/src/utils/process.js +7 -65
- package/src/utils/versions.js +16 -3
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/
|
|
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("
|
|
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}:
|
|
180
|
+
return green(`[ ${node.label}: verified ]`);
|
|
177
181
|
case "running":
|
|
178
|
-
return `[ ${node.label}:
|
|
182
|
+
return `[ ${node.label}: process running ]`;
|
|
179
183
|
case "error":
|
|
180
|
-
return red(bold(`[ ${node.label}:
|
|
184
|
+
return red(bold(`[ ${node.label}: error ]`));
|
|
181
185
|
case "stopped":
|
|
182
|
-
return dim(`[ ${node.label}:
|
|
186
|
+
return dim(`[ ${node.label}: stopped ]`);
|
|
183
187
|
case "static":
|
|
184
188
|
return `[ ${node.label} ]`;
|
|
185
189
|
default:
|
|
186
|
-
return yellow(`[ ${node.label}:
|
|
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 ? "
|
|
284
|
-
: proxy.status !== "running" ? "
|
|
285
|
-
: !stats ? "
|
|
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
|
-
|
|
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 = "
|
|
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("
|
|
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 ? "
|
|
323
|
-
: `
|
|
324
|
-
const freshnessText = stale ? yellow(`
|
|
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:
|
|
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("
|
|
335
|
-
: `${cyan(bold(num(this.rates.requests, 2)))}
|
|
336
|
-
`
|
|
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("
|
|
339
|
-
add([`
|
|
340
|
-
`
|
|
341
|
-
add([`
|
|
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))}
|
|
345
|
-
...(stage.unmeasured > 0 ? [yellow(`
|
|
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("
|
|
405
|
+
add([dim("Preset estimates; excludes interceptors, cache and billing.")]);
|
|
349
406
|
|
|
350
407
|
if (this.showPipelineDetails) {
|
|
351
|
-
add([`
|
|
352
|
-
if (this.proxyStats?.since) add([`
|
|
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
|
|
412
|
+
if (node.state === "running") add([yellow(`${node.label}: health not verified`)]);
|
|
356
413
|
}
|
|
357
|
-
if (!chainFresh) add([yellow("
|
|
414
|
+
if (!chainFresh) add([yellow("Chain states are stale")]);
|
|
358
415
|
if (this.proxyStats && !stale) {
|
|
359
|
-
add([dim(this.sampleMs === null ? "
|
|
360
|
-
: `
|
|
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("
|
|
363
|
-
add([dim("
|
|
364
|
-
add([dim("
|
|
365
|
-
add([dim("
|
|
366
|
-
add([dim("
|
|
367
|
-
add([dim("WS:
|
|
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("
|
|
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("
|
|
391
|
-
: event.changed === false ? dim("
|
|
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("
|
|
395
|
-
error: red(event.error ? "
|
|
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(" (
|
|
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
|
-
`
|
|
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
|
|
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("
|
|
413
|
-
] : [dim("
|
|
414
|
-
...(event.project ? [`
|
|
415
|
-
...(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 ? "
|
|
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
|
|
434
|
-
+ (this.metricsStale(now) && this.proxyStats ? yellow(" (
|
|
435
|
-
+ dim(" proxy
|
|
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:
|
|
440
|
-
: this.proxyStats ? "
|
|
441
|
-
: "
|
|
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 ? "
|
|
476
|
-
`${dim("q")}
|
|
477
|
-
`${dim("up/down")}
|
|
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
|
|
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("
|
|
513
|
-
: dim(this.versionsLoading && !version ? "
|
|
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
|
-
|
|
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(" ...
|
|
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(" (
|
|
608
|
+
const header = m && this.metricsStale() ? bold("PIPELINE") + yellow(" (historical)") + dim(" AIH proxy metrics") : pipeline[0];
|
|
555
609
|
pipeline = [header, ...wrapCells(m ? [
|
|
556
|
-
`
|
|
557
|
-
`
|
|
558
|
-
...(this.metricsStale() ? [yellow("
|
|
559
|
-
] : [yellow(this.metricsError || "
|
|
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(" ...
|
|
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(" ...
|
|
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("
|
|
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}:
|
|
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) {
|
|
@@ -631,6 +685,9 @@ export class Dashboard {
|
|
|
631
685
|
return;
|
|
632
686
|
}
|
|
633
687
|
|
|
688
|
+
// Adopting a container needs a second, consecutive u on the same service.
|
|
689
|
+
const adopt = key === "u" && this.adoptPending === this.currentService()?.id;
|
|
690
|
+
this.adoptPending = null;
|
|
634
691
|
switch (key) {
|
|
635
692
|
case "c":
|
|
636
693
|
if (this.busy) return;
|
|
@@ -651,19 +708,21 @@ export class Dashboard {
|
|
|
651
708
|
this.render();
|
|
652
709
|
return;
|
|
653
710
|
case "s":
|
|
654
|
-
this.runAction("
|
|
711
|
+
this.runAction("Start", svc => manager.startService(svc.id));
|
|
655
712
|
return;
|
|
656
713
|
case "x":
|
|
657
714
|
this.runAction("Stop", svc => manager.stopService(svc.id));
|
|
658
715
|
return;
|
|
659
716
|
case "r":
|
|
660
|
-
this.runAction("
|
|
717
|
+
this.runAction("Restart", svc => manager.restartService(svc.id));
|
|
661
718
|
return;
|
|
662
719
|
case "u":
|
|
663
|
-
return this.runAction("
|
|
720
|
+
return this.runAction("Update", async svc => {
|
|
664
721
|
this.invalidateVersions();
|
|
665
722
|
try {
|
|
666
|
-
|
|
723
|
+
const result = await manager.updateService(svc.id, { adopt });
|
|
724
|
+
if (result.adoptable) this.adoptPending = svc.id;
|
|
725
|
+
return result;
|
|
667
726
|
} finally {
|
|
668
727
|
// Drop pre-update and mid-update checks even if installation failed.
|
|
669
728
|
this.invalidateVersions();
|
|
@@ -671,7 +730,7 @@ export class Dashboard {
|
|
|
671
730
|
});
|
|
672
731
|
case "k":
|
|
673
732
|
this.runAction("Kill", async svc => {
|
|
674
|
-
if (!svc.pid) return { success: false, message: `${svc.id}:
|
|
733
|
+
if (!svc.pid) return { success: false, message: `${svc.id}: no PID to kill` };
|
|
675
734
|
return killProcessTree(svc.pid);
|
|
676
735
|
});
|
|
677
736
|
return;
|
|
@@ -679,14 +738,14 @@ export class Dashboard {
|
|
|
679
738
|
if (!this.currentService()?.dashboardUrl) return;
|
|
680
739
|
this.runAction("Dashboard", async svc => {
|
|
681
740
|
const opened = await manager.openDashboard([svc.id]);
|
|
682
|
-
return { success: opened.length > 0, message: opened.length ? `
|
|
741
|
+
return { success: opened.length > 0, message: opened.length ? `Opened ${opened[0].url}` : "No dashboard available" };
|
|
683
742
|
});
|
|
684
743
|
return;
|
|
685
744
|
case "g":
|
|
686
745
|
if (!this.currentService()?.repositoryUrl) return;
|
|
687
746
|
this.runAction("GitHub", async svc => {
|
|
688
747
|
const opened = await manager.openRepository([svc.id]);
|
|
689
|
-
return { success: opened.length > 0, message: opened.length ? `
|
|
748
|
+
return { success: opened.length > 0, message: opened.length ? `Opened ${opened[0].url}` : "No repository available" };
|
|
690
749
|
});
|
|
691
750
|
return;
|
|
692
751
|
default:
|
|
@@ -701,11 +760,14 @@ export class Dashboard {
|
|
|
701
760
|
this.render();
|
|
702
761
|
try {
|
|
703
762
|
const options = wizard.validate();
|
|
763
|
+
const hindsight = wizard.hindsightSettings();
|
|
704
764
|
if (command === "check") {
|
|
705
765
|
wizard.checks = [];
|
|
706
|
-
|
|
766
|
+
const checks = await preflightProxy(options, (await manager.syncState()).services.proxy);
|
|
767
|
+
if (hindsight) checks.push(...await preflightHindsight(hindsight.config, { newKey: hindsight.apiKey }));
|
|
768
|
+
wizard.checks = checks;
|
|
707
769
|
} else {
|
|
708
|
-
const startup = { startServices: wizard.draft.startServices.split(",") };
|
|
770
|
+
const startup = { startServices: wizard.draft.startServices.split(","), ...(hindsight ? { hindsight } : {}) };
|
|
709
771
|
const result = command === "save" ? manager.saveProxyConfiguration(options, startup)
|
|
710
772
|
: await manager.applyProxyConfiguration(options, startup);
|
|
711
773
|
if (!result.success) throw new Error(result.message);
|
package/src/utils/metrics.js
CHANGED
|
@@ -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
|
|
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 (
|
|
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 += ` |
|
|
314
|
+
nodes[1].detail += ` | forwards to: ${upstream.url} (destination not verified)`;
|
|
315
315
|
}
|
|
316
316
|
}
|
|
317
317
|
}
|