my-durable 0.0.117 → 0.0.119

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.
@@ -12,6 +12,7 @@ import {
12
12
  type SelectItem,
13
13
  } from "@earendil-works/pi-tui";
14
14
  import { THINKING_LEVELS, type ThinkingLevel } from "../../dpi-sdk/src/api.ts";
15
+ import type { EnvFileView, NotifySinkView, ScheduleView } from "../../dpi-sdk/src/api.ts";
15
16
  import { agentTree, type TreeNode } from "../../dpi-sdk/src/models.ts";
16
17
  import { oneLine, sanitizeTerminal } from "./sanitize.ts";
17
18
  import type { App } from "./app.ts";
@@ -39,7 +40,9 @@ class Title implements Component {
39
40
  */
40
41
  export class Picker extends Box {
41
42
  list: SelectList;
42
- private filter = "";
43
+ // run-12: protected so ActionPicker can tell "no filter yet" from "typed
44
+ // something" — its row hotkeys (t/d/n) must yield to an active filter.
45
+ protected filter = "";
43
46
  private title: Title;
44
47
  private readonly hintText: string;
45
48
  constructor(
@@ -119,6 +122,36 @@ export class Picker extends Box {
119
122
  }
120
123
  }
121
124
 
125
+ /** A picker whose rows take action hotkeys (run-12 ops surfaces: t/d/n on
126
+ * /schedules and /env). The hotkey fires on the highlighted row only, and it
127
+ * yields to an active filter — once the user has typed anything, letters
128
+ * belong to the filter until backspace empties it, so "find the schedule
129
+ * whose name has a t in it" still works. */
130
+ export class ActionPicker extends Picker {
131
+ constructor(
132
+ label: string,
133
+ items: SelectItem[],
134
+ onPick: (item: SelectItem) => void,
135
+ onCancel: () => void,
136
+ hint: string,
137
+ private readonly hotkeys: Record<string, (item: SelectItem) => void>,
138
+ subtitle?: string,
139
+ ) {
140
+ super(label, items, onPick, onCancel, hint, subtitle);
141
+ }
142
+ handleInput(data: string) {
143
+ const act = data.length === 1 ? this.hotkeys[data] : undefined;
144
+ if (act && !this.filter) {
145
+ // SelectList reports "nothing selected" as null (empty list) — a
146
+ // hotkey with no row is a no-op, not a crash.
147
+ const item = this.list.getSelectedItem();
148
+ if (item) act(item);
149
+ return;
150
+ }
151
+ super.handleInput(data);
152
+ }
153
+ }
154
+
122
155
  /** One line of text input. */
123
156
  export class Prompt extends Box implements Focusable {
124
157
  readonly input = new Input();
@@ -260,7 +293,7 @@ export class Panel extends Box {
260
293
  export async function pickSession(app: App) {
261
294
  const tree = await app.client.tree();
262
295
  const items: SelectItem[] = [
263
- { value: "+new", label: "+ New session", description: `choose a directory on ${sanitizeTerminal(app.device.id)}` },
296
+ { value: "+new", label: "+ New session", description: `choose a directory on ${oneLine(app.device.id)}` },
264
297
  ...tree.sessions.map((s) => {
265
298
  const agents = Array.isArray(s.agents) ? s.agents : [];
266
299
  return {
@@ -271,7 +304,7 @@ export async function pickSession(app: App) {
271
304
  }),
272
305
  ];
273
306
  app.overlay(
274
- new Picker(`Sessions on ${sanitizeTerminal(app.device.id)}`, items, (item) => {
307
+ new Picker(`Sessions on ${oneLine(app.device.id)}`, items, (item) => {
275
308
  app.closeOverlay();
276
309
  if (item.value === "+new") return void newSession(app);
277
310
  const s = tree.sessions.find((x) => x.id === item.value)!;
@@ -477,3 +510,320 @@ export function pickDevice(app: App) {
477
510
  ),
478
511
  );
479
512
  }
513
+
514
+ // --------------------------------------------- run-12: device-ops pickers
515
+ // The SDK already spoke schedules/env/notify (and the FE already had panels
516
+ // for them) — run-12 gives the SSH operator the same doors from the palette.
517
+ // Every row is composed through oneLine: names, urls, errors and paths below
518
+ // are device-authored and must never split their rendered row (run-9).
519
+
520
+ /** Wall clock for schedule rows — the device computed the epoch, the operator
521
+ * reads it in the terminal's own timezone. */
522
+ const fmtClock = (ms: number) => {
523
+ const d = new Date(ms);
524
+ const hhmm = `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
525
+ return `${d.getDate()} ${d.toLocaleString("en", { month: "short" })} ${hhmm}`;
526
+ };
527
+
528
+ /** The trigger half of a schedule row: "every 30m" or "daily 09:30".
529
+ * dailyAt is device-authored — oneLine at this compose boundary (r12
530
+ * review m1: LF here would split the picker row). */
531
+ const triggerOf = (s: Pick<ScheduleView, "everyMinutes" | "dailyAt">) =>
532
+ s.everyMinutes != null
533
+ ? `every ${s.everyMinutes}m`
534
+ : s.dailyAt
535
+ ? `daily ${oneLine(s.dailyAt)}`
536
+ : "no trigger";
537
+
538
+ /**
539
+ * The /schedules n trigger grammar (run-12): the device clock supports exactly
540
+ * two triggers — `every <minutes>` (5–1440) and `daily HH:MM` local time. A
541
+ * cron expression is deliberately NOT accepted: the device would refuse it
542
+ * anyway, so the palette refuses it first with a re-ask instead of a lost
543
+ * create call. Exported for unit tests.
544
+ */
545
+ export function parseScheduleTrigger(text: string): { everyMinutes: number } | { dailyAt: string } | undefined {
546
+ const t = text.trim().toLowerCase();
547
+ const every = t.match(/^every\s+(\d+)\s*m?(?:in)?s?$/);
548
+ if (every) {
549
+ const n = Number(every[1]);
550
+ return n >= 5 && n <= 1440 ? { everyMinutes: n } : undefined;
551
+ }
552
+ const daily = t.match(/^daily\s+(\d{1,2}):(\d{2})$/);
553
+ if (daily) {
554
+ const h = Number(daily[1]);
555
+ const m = Number(daily[2]);
556
+ if (h <= 23 && m <= 59) return { dailyAt: `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}` };
557
+ }
558
+ return undefined;
559
+ }
560
+
561
+ /** Prompts until the text parses as a trigger; esc (undefined) cancels the
562
+ * whole new-schedule chain. A bad answer re-asks instead of dead-ending. */
563
+ async function promptScheduleTrigger(app: App) {
564
+ for (;;) {
565
+ const text = await app.prompt("Trigger — `every <minutes>` (5-1440) or `daily HH:MM`", "");
566
+ if (text === undefined) return undefined;
567
+ const parsed = parseScheduleTrigger(text);
568
+ if (parsed) return parsed;
569
+ app.flash("trigger must be `every <minutes>` (5-1440) or `daily HH:MM`", true);
570
+ }
571
+ }
572
+
573
+ /**
574
+ * The /schedules n chain (run-12): name → trigger → cwd (the SAME walkDirs the
575
+ * new-session flow uses) → prompt text, then one createSchedule call. Model
576
+ * and retention stay on their device defaults — the palette is a keyboard,
577
+ * not a form (run-12 Unit B scope).
578
+ */
579
+ async function newScheduleFlow(app: App) {
580
+ const name = ((await app.prompt("Schedule name", "")) ?? "").trim();
581
+ if (!name) return app.flash("new schedule cancelled"), undefined;
582
+ const trigger = await promptScheduleTrigger(app);
583
+ if (!trigger) return app.flash("new schedule cancelled"), undefined;
584
+ const cwd = await walkDirs(app, "");
585
+ // undefined = esc, null = the device listing failed (already flashed — R4
586
+ // finding 8 sentinels). Either way the chain stops HERE, honestly.
587
+ if (cwd === undefined) return app.flash("new schedule cancelled"), undefined;
588
+ if (cwd === null) return;
589
+ const text = (await app.prompt("Prompt text for each run", ""))?.trim();
590
+ if (!text) return app.flash("new schedule cancelled"), undefined;
591
+ await app.run(async () => {
592
+ app.setPending(`creating schedule ${name}…`);
593
+ try {
594
+ const s = await app.client.createSchedule({ name, cwd, prompt: text, ...trigger });
595
+ app.flash(`schedule ${oneLine(s.name)} created — ${triggerOf(s)}`);
596
+ app.logEvent("sched", `created ${oneLine(s.name)} · ${triggerOf(s)} · ${oneLine(cwd)}`);
597
+ } finally {
598
+ app.setPending(null);
599
+ }
600
+ });
601
+ }
602
+
603
+ /** /schedules (run-12): list · enter run now · t toggle · d delete · n new. */
604
+ export async function pickSchedules(app: App) {
605
+ let list: ScheduleView[];
606
+ try {
607
+ list = (await app.client.schedules()).schedules;
608
+ } catch (e) {
609
+ return app.notify(`schedules: ${(e as Error).message.slice(0, 80)}`, true);
610
+ }
611
+ const items: SelectItem[] = [
612
+ { value: "+new", label: "+ New schedule", description: "the device runs each one on its own clock" },
613
+ ...list.map((s) => ({
614
+ value: s.id,
615
+ label: `${s.enabled ? "●" : "○"} ${oneLine(s.name)}`,
616
+ description: `${triggerOf(s)} · next ${s.nextRunAt ? fmtClock(s.nextRunAt) : "—"}${s.running ? " · running now" : ""}${s.lastOutcome ? ` · last ${oneLine(String(s.lastOutcome))}` : ""}`,
617
+ })),
618
+ ];
619
+ app.overlay(
620
+ new ActionPicker(
621
+ `Schedules on ${oneLine(app.device.id)}`,
622
+ items,
623
+ async (item) => {
624
+ app.closeOverlay();
625
+ if (item.value === "+new") {
626
+ await newScheduleFlow(app);
627
+ return void pickSchedules(app);
628
+ }
629
+ const s = list.find((x) => x.id === item.value)!;
630
+ await app.run(async () => {
631
+ const after = await app.client.runSchedule(s.id);
632
+ app.notify(`▶ ${oneLine(after.name)} — session started (log view: L)`);
633
+ app.logEvent("sched", `${oneLine(after.name)} triggered by hand · ${triggerOf(after)}`);
634
+ });
635
+ // next/last changed — reopen on fresh state rather than showing a stale row.
636
+ void pickSchedules(app);
637
+ },
638
+ () => app.closeOverlay(),
639
+ "enter run now · t on/off · d delete · n new · esc close",
640
+ {
641
+ t: async (item) => {
642
+ if (item.value === "+new") return;
643
+ const s = list.find((x) => x.id === item.value)!;
644
+ app.closeOverlay();
645
+ await app.run(async () => {
646
+ const after = await app.client.updateSchedule(s.id, { enabled: !s.enabled });
647
+ app.notify(`${oneLine(after.name)} ${after.enabled ? "enabled ●" : "disabled ○"}`);
648
+ app.logEvent("sched", `${oneLine(after.name)} ${after.enabled ? "enabled" : "disabled"}`);
649
+ });
650
+ void pickSchedules(app);
651
+ },
652
+ d: async (item) => {
653
+ if (item.value === "+new") return;
654
+ const s = list.find((x) => x.id === item.value)!;
655
+ // The same y/n gate /reset asks (R4 finding 4): a destructive door
656
+ // confirms; esc or anything not starting with y keeps the schedule.
657
+ const ok = await app.prompt(`Delete schedule ${oneLine(s.name)}? y/n`, "");
658
+ if (ok === undefined || !ok.trim().toLowerCase().startsWith("y"))
659
+ return app.flash("delete cancelled"), undefined;
660
+ app.closeOverlay();
661
+ await app.run(async () => {
662
+ await app.client.removeSchedule(s.id);
663
+ app.notify(`deleted ${oneLine(s.name)}`);
664
+ app.logEvent("sched", `deleted ${oneLine(s.name)} · ${triggerOf(s)}`);
665
+ });
666
+ void pickSchedules(app);
667
+ },
668
+ n: async () => {
669
+ app.closeOverlay();
670
+ await newScheduleFlow(app);
671
+ void pickSchedules(app);
672
+ },
673
+ },
674
+ ),
675
+ );
676
+ }
677
+
678
+ /** /env (run-12): the device's env file — list, edit, set, remove. Secrets
679
+ * arrive masked from the backend and are never round-tripped: editing a
680
+ * secret prefills BLANK (a prefilled mask would overwrite the real value). */
681
+ export async function pickEnv(app: App) {
682
+ let view: EnvFileView;
683
+ try {
684
+ view = await app.client.envView();
685
+ } catch (e) {
686
+ return app.notify(`env: ${(e as Error).message.slice(0, 80)}`, true);
687
+ }
688
+ const items: SelectItem[] = [
689
+ { value: "+new", label: "+ Set variable", description: "add or overwrite one key in the env file" },
690
+ ...view.vars.map((v) => ({
691
+ value: v.key,
692
+ label: `${oneLine(v.key)}=${oneLine(v.masked)}`,
693
+ description: v.source === "process" || v.managed ? "read-only" : "file · editable",
694
+ })),
695
+ ];
696
+ const editable = (v: { source: string; managed: boolean }) => !(v.source === "process" || v.managed);
697
+ const editVar = async (key: string) => {
698
+ const v = view.vars.find((x) => x.key === key);
699
+ if (!v) return;
700
+ if (!editable(v))
701
+ return app.notify(
702
+ `${oneLine(v.key)} is read-only (${v.managed ? "managed by the device" : "inherited from the process env"})`,
703
+ );
704
+ const value = await app.prompt(
705
+ `Value for ${oneLine(v.key)}${v.secret ? " (secret — the file keeps it masked)" : ""}`,
706
+ v.secret ? "" : oneLine(v.masked),
707
+ );
708
+ if (value === undefined) return app.flash("edit cancelled"), undefined;
709
+ // An empty submit on a masked row is far more likely a stray enter than an
710
+ // intent to blank the variable — removing has its own confirmed door (d).
711
+ if (!value) return app.flash("cancelled — an empty value would clear the variable (d removes)"), undefined;
712
+ app.closeOverlay();
713
+ await app.run(async () => {
714
+ await app.client.setEnvVar(v.key, value);
715
+ app.notify(`${oneLine(v.key)} saved`);
716
+ app.logEvent("env", `set ${oneLine(v.key)}`);
717
+ });
718
+ void pickEnv(app);
719
+ };
720
+ app.overlay(
721
+ new ActionPicker(
722
+ `Device env${view.envFile ? ` — ${oneLine(view.envFile)}` : ""}`,
723
+ items,
724
+ (item) => {
725
+ if (item.value === "+new") {
726
+ app.closeOverlay();
727
+ void setNewVar(app).then(() => pickEnv(app));
728
+ return;
729
+ }
730
+ void editVar(item.value);
731
+ },
732
+ () => app.closeOverlay(),
733
+ "enter edit · d remove · n set new · esc close",
734
+ {
735
+ d: async (item) => {
736
+ if (item.value === "+new") return;
737
+ const v = view.vars.find((x) => x.key === item.value);
738
+ if (!v) return;
739
+ if (!editable(v)) return app.notify(`${oneLine(v.key)} is read-only`);
740
+ const ok = await app.prompt(`Remove ${oneLine(v.key)} from the env file? y/n`, "");
741
+ if (ok === undefined || !ok.trim().toLowerCase().startsWith("y"))
742
+ return app.flash("remove cancelled"), undefined;
743
+ app.closeOverlay();
744
+ await app.run(async () => {
745
+ await app.client.removeEnvVar(v.key);
746
+ app.notify(`removed ${oneLine(v.key)}`);
747
+ app.logEvent("env", `removed ${oneLine(v.key)}`);
748
+ });
749
+ void pickEnv(app);
750
+ },
751
+ n: async () => {
752
+ app.closeOverlay();
753
+ await setNewVar(app);
754
+ void pickEnv(app);
755
+ },
756
+ },
757
+ // The backend flags this — surfacing it where the edit happens beats a
758
+ // separate "did my change apply?" trip to the FE.
759
+ view.restartRequired ? "changed since boot — restart the device to apply" : undefined,
760
+ ),
761
+ );
762
+ }
763
+
764
+ /** The /env n chain: key → value → one setEnvVar call. Re-asks on a key that
765
+ * could not live in an env file, mirroring promptScheduleTrigger. */
766
+ async function setNewVar(app: App) {
767
+ let key = "";
768
+ for (;;) {
769
+ key = ((await app.prompt("Key (letters, digits, _ — e.g. MY_TOOL_TOKEN)", "")) ?? "").trim();
770
+ if (!key) return app.flash("set cancelled"), undefined;
771
+ if (/^[A-Za-z_][A-Za-z0-9_.]*$/.test(key)) break;
772
+ app.flash("keys start with a letter or _ and carry letters, digits, _ and . only", true);
773
+ }
774
+ const value = (await app.prompt(`Value for ${oneLine(key)}`, ""))?.trim();
775
+ if (!value) return app.flash("set cancelled"), undefined;
776
+ await app.run(async () => {
777
+ await app.client.setEnvVar(key, value);
778
+ app.notify(`${oneLine(key)} saved`);
779
+ app.logEvent("env", `set ${oneLine(key)}`);
780
+ });
781
+ }
782
+
783
+ /** /notify (run-12): list the sinks and fire a test event. NO sink CRUD from
784
+ * the TUI — sinks hold credentials (webhook URLs, ntfy topics), and the web
785
+ * FE is their managed home; the palette only proves the pipe works. */
786
+ export async function pickNotify(app: App) {
787
+ let sinks: NotifySinkView[];
788
+ try {
789
+ sinks = (await app.client.notifySinks()).sinks;
790
+ } catch (e) {
791
+ return app.notify(`notify: ${(e as Error).message.slice(0, 80)}`, true);
792
+ }
793
+ if (!sinks.length)
794
+ return app.notify("no notify sinks on this device — manage them in the web FE (they hold credentials)");
795
+ const test = async () => {
796
+ try {
797
+ const { results } = await app.client.testNotifySinks();
798
+ const sent = results.filter((r) => r.status === "sent").length;
799
+ const failed = results.filter((r) => r.status === "failed").length;
800
+ const skipped = results.length - sent - failed;
801
+ app.notify(
802
+ `notify test: ${sent} sent${failed ? ` · ${failed} failed` : ""}${skipped ? ` · ${skipped} skipped` : ""}${failed ? " (log view: L)" : ""}`,
803
+ );
804
+ for (const r of results)
805
+ app.logEvent(
806
+ "notify",
807
+ `${oneLine(r.kind)} ${oneLine(r.id)} — ${r.status}${r.detail ? ` · ${oneLine(r.detail).slice(0, 60)}` : ""}${r.ms != null ? ` · ${r.ms}ms` : ""}`,
808
+ );
809
+ } catch (e) {
810
+ app.notify(`notify test: ${(e as Error).message.slice(0, 80)}`, true);
811
+ }
812
+ };
813
+ app.overlay(
814
+ new ActionPicker(
815
+ "Notify sinks (testing only — CRUD lives in the web FE)",
816
+ sinks.map((s) => ({
817
+ value: s.id,
818
+ // kind is device-authored and sits in a LABEL (never LF-normalized
819
+ // by pi-tui — r12 review m1) — oneLine here, not just the description.
820
+ label: `${s.enabled ? "●" : "○"} ${oneLine(String(s.kind))}${s.label ? ` ${oneLine(s.label)}` : ""}`,
821
+ description: `${oneLine(s.url)}${s.lastStatus ? ` · last ${oneLine(String(s.lastStatus))}` : ""}${s.lastError ? ` · ${oneLine(s.lastError).slice(0, 40)}` : ""}${s.silencedUntil && s.silencedUntil > Date.now() ? " · silenced" : ""}`,
822
+ })),
823
+ () => void test(),
824
+ () => app.closeOverlay(),
825
+ "enter/t test every enabled sink · esc close",
826
+ { t: () => void test() },
827
+ ),
828
+ );
829
+ }
@@ -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`) : ""}`,
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.117",
3
+ "version": "0.0.119",
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": {