my-durable 0.0.118 → 0.0.120

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.
@@ -3,22 +3,32 @@
3
3
  // App chrome. Pure string builders — no TTY, no timers — so every line is
4
4
  // unit-testable exactly like the reference's frame(w, h).
5
5
  import { truncateToWidth, visibleWidth, type Component } from "@earendil-works/pi-tui";
6
- import type { SessionSummary } from "../../dpi-sdk/src/api.ts";
6
+ import type {
7
+ DeviceUsageReport,
8
+ DeviceVitals,
9
+ EnvFileView,
10
+ NotifySinkView,
11
+ ScheduleView,
12
+ SessionSummary,
13
+ } from "../../dpi-sdk/src/api.ts";
7
14
  import type { GitStatus } from "../../dpi-sdk/src/client.ts";
8
15
  import type { DeviceRow } from "../../dpi-sdk/src/node/registry.ts";
9
16
  import { c, STATE_COLOR, STATE_GLYPH, type RowState } from "./theme.ts";
10
17
  import { oneLine, sanitizeTerminal } from "./sanitize.ts";
11
18
 
12
- export type View = "herd" | "network" | "agent" | "log";
19
+ export type View = "herd" | "network" | "agent" | "log" | "ops";
13
20
 
14
21
  export const VIEW_TABS: { id: View; label: string }[] = [
15
22
  // Order = the user's journey (and the digit keys): land in the network
16
23
  // (hub-first boot), pick a session into the herd dashboard, converse in the
17
- // agent view, watch the log. Tab cycles the same order.
24
+ // agent view, watch the log. Tab cycles the same order. Run-12 adds view 5
25
+ // "ops" — the device-ops surfaces (vitals/usage/schedules/env/notify) the
26
+ // SDK already exposed but no view rendered; digit 5 rides the same tab.
18
27
  { id: "network", label: "network" },
19
28
  { id: "herd", label: "herd" },
20
29
  { id: "agent", label: "agent" },
21
30
  { id: "log", label: "log" },
31
+ { id: "ops", label: "ops" },
22
32
  ];
23
33
 
24
34
  const rep = (ch: string, n: number) => ch.repeat(Math.max(0, n));
@@ -257,9 +267,9 @@ export function renderNetwork(
257
267
 
258
268
  /**
259
269
  * The one-line viewbar under the header: active tab inverse + a right-aligned
260
- * hint. Every view carries its digit (1 network · 2 herd · 3 agent · 4 log) —
261
- * the digit keys work EVERYWHERE, so view switching is one glance away instead
262
- * of three mnemonics (g/N/L) to memorize.
270
+ * hint. Every view carries its digit (1 network · 2 herd · 3 agent · 4 log ·
271
+ * 5 ops) — the digit keys work EVERYWHERE, so view switching is one glance
272
+ * away instead of three mnemonics (g/N/L) to memorize.
263
273
  */
264
274
  export function renderViewbar(w: number, view: View, right: string): string {
265
275
  const tabs = VIEW_TABS.map((t, i) =>
@@ -280,7 +290,9 @@ export function renderStatusbar(
280
290
  ? ["tab complete", "↑ history", "enter send", "esc cancel"]
281
291
  : opts.view === "agent"
282
292
  ? ["g herd", "N network", "L log", "[ ] tabs", "m message"]
283
- : ["j/k move", "↵ open", "1-4 views", "⇥ tabs", "esc agent"];
293
+ : opts.view === "ops"
294
+ ? ["j/k scroll", "R refresh", "1-5 views", ": palette", "esc herd"]
295
+ : ["j/k move", "↵ open", "1-5 views", "⇥ tabs", "esc agent"];
284
296
  // Catalog miss degrades to "?" (R5 finding 5): "—" read as "no usage yet",
285
297
  // when it actually means the window is unknown — a different problem.
286
298
  const right = `${c.muted("ctx")} ${opts.ctxLeft === undefined ? c.muted("?") : c.text(`${opts.ctxLeft}%`)}${opts.background ? c.muted(` · ${opts.background} bg`) : ""} ${c.muted("dev")} ${c.text(fit(oneLine(String(opts.device ?? "")), 18))}`;
@@ -387,3 +399,159 @@ export function joinPanel(
387
399
  );
388
400
  return out;
389
401
  }
402
+
403
+ // ------------------------------------------------------------------- ops
404
+
405
+ /**
406
+ * View 5 "ops" data (run-12): the five device-ops reads the SDK client
407
+ * already exposed (vitals/deviceUsage/schedules/envView/notifySinks) but no
408
+ * TUI surface rendered. Each section is optional and fails ALONE — a 500 on
409
+ * /v1/schedules must not blank vitals — so the app fetches them
410
+ * independently and renderOps degrades per section.
411
+ */
412
+ export interface OpsData {
413
+ vitals?: DeviceVitals;
414
+ usage?: DeviceUsageReport;
415
+ schedules?: ScheduleView[];
416
+ env?: EnvFileView;
417
+ sinks?: NotifySinkView[];
418
+ }
419
+
420
+ /** Per-section fetch failures (run-12): keyed like OpsData, shown inline. */
421
+ export type OpsErrors = Partial<Record<keyof OpsData, string>>;
422
+
423
+ /** Host-health seconds → "3d 4h" / "5h 12m" / "42m" — compact, like ageOf. */
424
+ const uptimeOf = (seconds: number) => {
425
+ const t = Math.max(0, Math.floor(Number(seconds) || 0));
426
+ const d = Math.floor(t / 86400);
427
+ const h = Math.floor((t % 86400) / 3600);
428
+ const m = Math.floor((t % 3600) / 60);
429
+ if (d) return `${d}d ${h}h`;
430
+ if (h) return `${h}h ${m}m`;
431
+ return `${m}m`;
432
+ };
433
+
434
+ /** Bytes → "512MiB"-style, 1 decimal under 100 (the vitals mem/disk rows). */
435
+ const humanBytes = (n: number) => {
436
+ let v = Math.max(0, Number(n) || 0);
437
+ let u = 0;
438
+ while (v >= 1024 && u < 4) {
439
+ v /= 1024;
440
+ u += 1;
441
+ }
442
+ return `${u === 0 || v >= 100 ? Math.round(v) : v.toFixed(1)}${["B", "KiB", "MiB", "GiB", "TiB"][u]}`;
443
+ };
444
+
445
+ /** The schedule clock the device computed → "in 42m" / "due" / "—". */
446
+ const nextIn = (at: number | null | undefined, now: number) => {
447
+ if (at === null || at === undefined) return "—";
448
+ const s = Math.floor((at - now) / 1000);
449
+ if (s <= 0) return "due";
450
+ if (s < 60) return `in ${s}s`;
451
+ if (s < 3600) return `in ${Math.floor(s / 60)}m`;
452
+ if (s < 86400) return `in ${Math.floor(s / 3600)}h`;
453
+ return `in ${Math.floor(s / 86400)}d`;
454
+ };
455
+
456
+ /**
457
+ * The ops view body (run-12): stacked compact sections — VITALS (uptime ·
458
+ * mem/disk · event-loop lag · gitSpawns live/queued+high), USAGE, SCHEDULES
459
+ * (●/○ enabled glyph, device-computed next run), ENV (key=masked, truncated
460
+ * to width), NOTIFY sinks. Section headers ride the theme accent like the
461
+ * herd panel's OVERVIEW. Pure builder like every other render* here: every
462
+ * line is width-exact and SINGLE-LINE (run-9 invariant) — device-authored
463
+ * fields (schedule names, env keys/values, sink urls, disk paths) pass
464
+ * oneLine at this data boundary exactly like herdRows/networkRows do.
465
+ */
466
+ export function renderOps(
467
+ w: number,
468
+ data: OpsData,
469
+ opts: { errors?: OpsErrors; loading?: boolean; now?: number } = {},
470
+ ): string[] {
471
+ const now = opts.now ?? Date.now();
472
+ const lines: string[] = [];
473
+ const section = (title: string, key: keyof OpsData, rows: () => string[]) => {
474
+ lines.push(` ${c.accent(title)}`);
475
+ const err = opts.errors?.[key];
476
+ if (err !== undefined) lines.push(` ${c.err(`✗ ${oneLine(String(err ?? ""))}`)}`);
477
+ else if (data[key] === undefined)
478
+ // Missing ≠ empty: an unset section is still loading (or never fetched);
479
+ // an empty one says so in its own rows below.
480
+ lines.push(` ${c.muted(opts.loading ? "◌ loading…" : "— no data")}`);
481
+ else lines.push(...rows());
482
+ lines.push("");
483
+ };
484
+
485
+ section("VITALS", "vitals", () => {
486
+ const v = data.vitals!;
487
+ const out = [
488
+ ` ${c.muted("up")} ${c.text(uptimeOf(v.uptime))} ${c.muted("proc")} ${c.text(uptimeOf(v.processUptime))} ${c.muted("load")} ${c.text(v.loadavg.map((n) => (Number(n) || 0).toFixed(2)).join(" "))} ${c.muted(`×${Number(v.cpuCount) || 0}`)}`,
489
+ ` ${c.muted("mem")} ${c.text(`${humanBytes(v.memory.usedBytes)}/${humanBytes(v.memory.totalBytes)}`)} ${c.muted("free")} ${c.text(humanBytes(v.memory.freeBytes))} ${c.muted("rss")} ${c.text(humanBytes(v.memory.processRssBytes))} ${c.muted("heap")} ${c.text(humanBytes(v.memory.heapUsedBytes))}`,
490
+ ` ${c.muted("disk")} ${v.disk.known ? `${c.text(`${humanBytes(v.disk.freeBytes)}/${humanBytes(v.disk.totalBytes)}`)} ${c.muted("free")} ${c.muted(oneLine(String(v.disk.path ?? "")))}` : c.muted("unknown")}`,
491
+ // run-12 phase 1 typed these into the SDK: event-loop lag is the stall
492
+ // loadavg cannot express, and gitSpawns' queued(+high) is the number
493
+ // that says "a status fan-out is stalling the panel" (run-11 h2-2).
494
+ ` ${c.muted("evlag")} ${c.text(`${Math.round(Number(v.eventLoop?.lagMsLast) || 0)}ms`)} ${c.muted("last")} ${c.text(`${Math.round(Number(v.eventLoop?.lagMsMax1m) || 0)}ms`)} ${c.muted("max 1m")} ${c.muted(`${Number(v.eventLoop?.samples) || 0} samples`)}`,
495
+ ` ${c.muted("git")} ${c.text(`${Number(v.gitSpawns?.live) || 0} live`)} ${c.muted("·")} ${c.text(`${Number(v.gitSpawns?.queued) || 0} queued`)}${Number(v.gitSpawns?.queuedHigh) > 0 ? c.warn(` · ${Number(v.gitSpawns.queuedHigh)} high`) : ""}${Number(v.gitSpawns?.queuedAged) > 0 ? c.warn(` · ${Number(v.gitSpawns.queuedAged)} aged`) : ""}`,
496
+ ];
497
+ if (v.counts)
498
+ out.push(
499
+ ` ${c.muted("sessions")} ${c.text(String(Number(v.counts.sessions) || 0))} ${c.muted("archived")} ${c.text(String(Number(v.counts.archived) || 0))}`,
500
+ );
501
+ return out;
502
+ });
503
+
504
+ section("USAGE", "usage", () => {
505
+ const u = data.usage!;
506
+ const sessions = Array.isArray(u.sessions) ? u.sessions : [];
507
+ const out = [
508
+ ` ${c.text(`${compact(Number(u.totals?.tokens) || 0)} tokens`)} ${c.muted("·")} ${c.text(`$${(Number(u.totals?.cost) || 0).toFixed(2)}`)} ${c.muted(`· ${sessions.length} session${sessions.length === 1 ? "" : "s"}`)}`,
509
+ ];
510
+ for (const s of [...sessions].sort((a, b) => (Number(b.tokens) || 0) - (Number(a.tokens) || 0)).slice(0, 3))
511
+ out.push(
512
+ ` ${c.text(oneLine(String(s.name ?? s.id ?? "")))} ${c.muted(`${compact(Number(s.tokens) || 0)} · $${(Number(s.cost) || 0).toFixed(2)}`)}`,
513
+ );
514
+ return out;
515
+ });
516
+
517
+ section("SCHEDULES", "schedules", () => {
518
+ const list = Array.isArray(data.schedules) ? data.schedules : [];
519
+ if (!list.length) return [` ${c.muted("no schedules — :schedules to manage")}`];
520
+ return list.map((s) => {
521
+ // Exactly one trigger is set (ScheduleRecord); hostile wire data falls
522
+ // back to "daily ?" instead of throwing.
523
+ const trigger = s.everyMinutes
524
+ ? `every ${Number(s.everyMinutes)}m`
525
+ : `daily ${oneLine(String(s.dailyAt ?? "?"))}`;
526
+ const glyph = s.enabled ? c.ok("●") : c.muted("○");
527
+ return ` ${glyph} ${c.text(oneLine(String(s.name ?? s.id)))} ${c.muted(trigger)} ${c.muted(nextIn(s.nextRunAt, now))}${s.running ? c.warn(" · running") : ""}`;
528
+ });
529
+ });
530
+
531
+ section("ENV", "env", () => {
532
+ const e = data.env!;
533
+ const out = [
534
+ ` ${c.muted(oneLine(String(e.envFile ?? "")))}${e.restartRequired ? c.warn(" · restart required") : ""}`,
535
+ ];
536
+ const vars = Array.isArray(e.vars) ? e.vars : [];
537
+ if (!vars.length) out.push(` ${c.muted("no env vars")}`);
538
+ // Values arrive MASKED from the device (EnvVarView); the operator trusts
539
+ // their own terminal, so the masked form renders as-is, truncated to width.
540
+ for (const v of vars)
541
+ out.push(
542
+ ` ${c.text(oneLine(String(v.key ?? "")))}${c.muted("=")}${c.text(oneLine(String(v.masked ?? "")))}${v.managed ? c.muted(" (managed)") : ""}${v.source === "process" ? c.muted(" (process)") : ""}`,
543
+ );
544
+ return out;
545
+ });
546
+
547
+ section("NOTIFY", "sinks", () => {
548
+ const list = Array.isArray(data.sinks) ? data.sinks : [];
549
+ if (!list.length) return [` ${c.muted("no sinks — :notify to test")}`];
550
+ return list.map((s) => {
551
+ const glyph = s.enabled ? c.ok("●") : c.muted("○");
552
+ return ` ${glyph} ${c.muted(oneLine(String(s.kind ?? "")))} ${c.text(oneLine(String(s.url ?? "")))}${s.silencedUntil && s.silencedUntil > now ? c.warn(" · silenced") : ""}`;
553
+ });
554
+ });
555
+
556
+ return lines.map((l) => fit(l, w));
557
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "my-durable",
3
- "version": "0.0.118",
3
+ "version": "0.0.120",
4
4
  "description": "Durable Pi — the durable agent network: hub web UI, device backend daemon, TUI admin and the shared SDK, packaged as one runnable monorepo install",
5
5
  "license": "MIT",
6
6
  "repository": {