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.
@@ -12,7 +12,9 @@ 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 { ArchivedView, DeviceTree, EnvFileView, NotifySinkView, ScheduleView } from "../../dpi-sdk/src/api.ts";
15
16
  import { agentTree, type TreeNode } from "../../dpi-sdk/src/models.ts";
17
+ import { fmtBytes, fmtDur } from "./commands.ts";
16
18
  import { oneLine, sanitizeTerminal } from "./sanitize.ts";
17
19
  import type { App } from "./app.ts";
18
20
  import { c, selectTheme } from "./theme.ts";
@@ -39,7 +41,9 @@ class Title implements Component {
39
41
  */
40
42
  export class Picker extends Box {
41
43
  list: SelectList;
42
- private filter = "";
44
+ // run-12: protected so ActionPicker can tell "no filter yet" from "typed
45
+ // something" — its row hotkeys (t/d/n) must yield to an active filter.
46
+ protected filter = "";
43
47
  private title: Title;
44
48
  private readonly hintText: string;
45
49
  constructor(
@@ -119,6 +123,36 @@ export class Picker extends Box {
119
123
  }
120
124
  }
121
125
 
126
+ /** A picker whose rows take action hotkeys (run-12 ops surfaces: t/d/n on
127
+ * /schedules and /env). The hotkey fires on the highlighted row only, and it
128
+ * yields to an active filter — once the user has typed anything, letters
129
+ * belong to the filter until backspace empties it, so "find the schedule
130
+ * whose name has a t in it" still works. */
131
+ export class ActionPicker extends Picker {
132
+ constructor(
133
+ label: string,
134
+ items: SelectItem[],
135
+ onPick: (item: SelectItem) => void,
136
+ onCancel: () => void,
137
+ hint: string,
138
+ private readonly hotkeys: Record<string, (item: SelectItem) => void>,
139
+ subtitle?: string,
140
+ ) {
141
+ super(label, items, onPick, onCancel, hint, subtitle);
142
+ }
143
+ handleInput(data: string) {
144
+ const act = data.length === 1 ? this.hotkeys[data] : undefined;
145
+ if (act && !this.filter) {
146
+ // SelectList reports "nothing selected" as null (empty list) — a
147
+ // hotkey with no row is a no-op, not a crash.
148
+ const item = this.list.getSelectedItem();
149
+ if (item) act(item);
150
+ return;
151
+ }
152
+ super.handleInput(data);
153
+ }
154
+ }
155
+
122
156
  /** One line of text input. */
123
157
  export class Prompt extends Box implements Focusable {
124
158
  readonly input = new Input();
@@ -257,34 +291,59 @@ export class Panel extends Box {
257
291
 
258
292
  // ------------------------------------------------------------------ flows
259
293
 
260
- export async function pickSession(app: App) {
261
- const tree = await app.client.tree();
262
- const items: SelectItem[] = [
263
- { value: "+new", label: "+ New session", description: `choose a directory on ${sanitizeTerminal(app.device.id)}` },
264
- ...tree.sessions.map((s) => {
265
- const agents = Array.isArray(s.agents) ? s.agents : [];
266
- return {
267
- value: s.id,
268
- label: oneLine(String(s.name ?? "")),
269
- description: `${oneLine(String(s.cwd ?? "").split("/").slice(-2).join("/"))} │ ${agents.length} agent${agents.length === 1 ? "" : "s"}${s.busy ? " │ working" : ""}`,
270
- };
271
- }),
272
- ];
273
- app.overlay(
274
- new Picker(`Sessions on ${sanitizeTerminal(app.device.id)}`, items, (item) => {
275
- app.closeOverlay();
276
- if (item.value === "+new") return void newSession(app);
277
- const s = tree.sessions.find((x) => x.id === item.value)!;
278
- const root = s.agents.find((a) => a.kind === "root") ?? s.agents[0];
279
- void app.attach(s.id, root?.id ?? 1);
280
- }, () => {
281
- // Esc must never surprise-quit (0.0.52): with no attached session the
282
- // cancel used to pass exitIfNothing=true and picker→Esc→Esc killed the
283
- // whole process (R4 finding 1). Landing in the herd/network view is the
284
- // honest cancel; quitting stays on q / ctrl+c / /quit.
285
- app.closeOverlay();
286
- }),
287
- );
294
+ /**
295
+ * The session picker. run-13: resolves with the picked session's id
296
+ * (undefined on esc or +New) so /export can reuse this same door — every
297
+ * existing caller ignores the value, and attach-on-pick is unchanged. A
298
+ * failed tree() now lands in an error toast like the other ops pickers
299
+ * (through /sessions it used to surface as an unhandled rejection).
300
+ */
301
+ export function pickSession(app: App): Promise<string | undefined> {
302
+ return new Promise((done) => {
303
+ void (async () => {
304
+ let tree: DeviceTree;
305
+ try {
306
+ tree = await app.client.tree();
307
+ } catch (e) {
308
+ app.notify(`sessions: ${(e as Error).message.slice(0, 80)}`, true);
309
+ return done(undefined);
310
+ }
311
+ const items: SelectItem[] = [
312
+ { value: "+new", label: "+ New session", description: `choose a directory on ${oneLine(app.device.id)}` },
313
+ ...tree.sessions.map((s) => {
314
+ const agents = Array.isArray(s.agents) ? s.agents : [];
315
+ return {
316
+ value: s.id,
317
+ label: oneLine(String(s.name ?? "")),
318
+ description: `${oneLine(String(s.cwd ?? "").split("/").slice(-2).join("/"))} │ ${agents.length} agent${agents.length === 1 ? "" : "s"}${s.busy ? " │ working" : ""}`,
319
+ };
320
+ }),
321
+ ];
322
+ app.overlay(
323
+ new Picker(`Sessions on ${oneLine(app.device.id)}`, items, (item) => {
324
+ app.closeOverlay();
325
+ // +New hands the flow to the new-session chain — resolve undefined so
326
+ // a waiting /export stays quiet instead of flashing "cancelled" over
327
+ // a flow that is telling its own story.
328
+ if (item.value === "+new") {
329
+ done(undefined);
330
+ return void newSession(app);
331
+ }
332
+ const s = tree.sessions.find((x) => x.id === item.value)!;
333
+ const root = s.agents.find((a) => a.kind === "root") ?? s.agents[0];
334
+ void app.attach(s.id, root?.id ?? 1);
335
+ done(s.id);
336
+ }, () => {
337
+ // Esc must never surprise-quit (0.0.52): with no attached session the
338
+ // cancel used to pass exitIfNothing=true and picker→Esc→Esc killed the
339
+ // whole process (R4 finding 1). Landing in the herd/network view is the
340
+ // honest cancel; quitting stays on q / ctrl+c / /quit.
341
+ app.closeOverlay();
342
+ done(undefined);
343
+ }),
344
+ );
345
+ })();
346
+ });
288
347
  }
289
348
 
290
349
  export async function newSession(app: App, presetName?: string) {
@@ -477,3 +536,435 @@ export function pickDevice(app: App) {
477
536
  ),
478
537
  );
479
538
  }
539
+
540
+ // --------------------------------------------- run-12: device-ops pickers
541
+ // The SDK already spoke schedules/env/notify (and the FE already had panels
542
+ // for them) — run-12 gives the SSH operator the same doors from the palette.
543
+ // Every row is composed through oneLine: names, urls, errors and paths below
544
+ // are device-authored and must never split their rendered row (run-9).
545
+
546
+ /** Wall clock for schedule rows — the device computed the epoch, the operator
547
+ * reads it in the terminal's own timezone. */
548
+ const fmtClock = (ms: number) => {
549
+ const d = new Date(ms);
550
+ const hhmm = `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
551
+ return `${d.getDate()} ${d.toLocaleString("en", { month: "short" })} ${hhmm}`;
552
+ };
553
+
554
+ /** The trigger half of a schedule row: "every 30m" or "daily 09:30".
555
+ * dailyAt is device-authored — oneLine at this compose boundary (r12
556
+ * review m1: LF here would split the picker row). */
557
+ const triggerOf = (s: Pick<ScheduleView, "everyMinutes" | "dailyAt">) =>
558
+ s.everyMinutes != null
559
+ ? `every ${s.everyMinutes}m`
560
+ : s.dailyAt
561
+ ? `daily ${oneLine(s.dailyAt)}`
562
+ : "no trigger";
563
+
564
+ /**
565
+ * The /schedules n trigger grammar (run-12): the device clock supports exactly
566
+ * two triggers — `every <minutes>` (5–1440) and `daily HH:MM` local time. A
567
+ * cron expression is deliberately NOT accepted: the device would refuse it
568
+ * anyway, so the palette refuses it first with a re-ask instead of a lost
569
+ * create call. Exported for unit tests.
570
+ */
571
+ export function parseScheduleTrigger(text: string): { everyMinutes: number } | { dailyAt: string } | undefined {
572
+ const t = text.trim().toLowerCase();
573
+ const every = t.match(/^every\s+(\d+)\s*m?(?:in)?s?$/);
574
+ if (every) {
575
+ const n = Number(every[1]);
576
+ return n >= 5 && n <= 1440 ? { everyMinutes: n } : undefined;
577
+ }
578
+ const daily = t.match(/^daily\s+(\d{1,2}):(\d{2})$/);
579
+ if (daily) {
580
+ const h = Number(daily[1]);
581
+ const m = Number(daily[2]);
582
+ if (h <= 23 && m <= 59) return { dailyAt: `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}` };
583
+ }
584
+ return undefined;
585
+ }
586
+
587
+ /** Prompts until the text parses as a trigger; esc (undefined) cancels the
588
+ * whole new-schedule chain. A bad answer re-asks instead of dead-ending. */
589
+ async function promptScheduleTrigger(app: App) {
590
+ for (;;) {
591
+ const text = await app.prompt("Trigger — `every <minutes>` (5-1440) or `daily HH:MM`", "");
592
+ if (text === undefined) return undefined;
593
+ const parsed = parseScheduleTrigger(text);
594
+ if (parsed) return parsed;
595
+ app.flash("trigger must be `every <minutes>` (5-1440) or `daily HH:MM`", true);
596
+ }
597
+ }
598
+
599
+ /**
600
+ * The /schedules n chain (run-12): name → trigger → cwd (the SAME walkDirs the
601
+ * new-session flow uses) → prompt text, then one createSchedule call. Model
602
+ * and retention stay on their device defaults — the palette is a keyboard,
603
+ * not a form (run-12 Unit B scope).
604
+ */
605
+ async function newScheduleFlow(app: App) {
606
+ const name = ((await app.prompt("Schedule name", "")) ?? "").trim();
607
+ if (!name) return app.flash("new schedule cancelled"), undefined;
608
+ const trigger = await promptScheduleTrigger(app);
609
+ if (!trigger) return app.flash("new schedule cancelled"), undefined;
610
+ const cwd = await walkDirs(app, "");
611
+ // undefined = esc, null = the device listing failed (already flashed — R4
612
+ // finding 8 sentinels). Either way the chain stops HERE, honestly.
613
+ if (cwd === undefined) return app.flash("new schedule cancelled"), undefined;
614
+ if (cwd === null) return;
615
+ const text = (await app.prompt("Prompt text for each run", ""))?.trim();
616
+ if (!text) return app.flash("new schedule cancelled"), undefined;
617
+ await app.run(async () => {
618
+ app.setPending(`creating schedule ${name}…`);
619
+ try {
620
+ const s = await app.client.createSchedule({ name, cwd, prompt: text, ...trigger });
621
+ app.flash(`schedule ${oneLine(s.name)} created — ${triggerOf(s)}`);
622
+ app.logEvent("sched", `created ${oneLine(s.name)} · ${triggerOf(s)} · ${oneLine(cwd)}`);
623
+ } finally {
624
+ app.setPending(null);
625
+ }
626
+ });
627
+ }
628
+
629
+ /** /schedules (run-12): list · enter run now · t toggle · d delete · n new. */
630
+ export async function pickSchedules(app: App) {
631
+ let list: ScheduleView[];
632
+ try {
633
+ list = (await app.client.schedules()).schedules;
634
+ } catch (e) {
635
+ return app.notify(`schedules: ${(e as Error).message.slice(0, 80)}`, true);
636
+ }
637
+ const items: SelectItem[] = [
638
+ { value: "+new", label: "+ New schedule", description: "the device runs each one on its own clock" },
639
+ ...list.map((s) => ({
640
+ value: s.id,
641
+ label: `${s.enabled ? "●" : "○"} ${oneLine(s.name)}`,
642
+ description: `${triggerOf(s)} · next ${s.nextRunAt ? fmtClock(s.nextRunAt) : "—"}${s.running ? " · running now" : ""}${s.lastOutcome ? ` · last ${oneLine(String(s.lastOutcome))}` : ""}`,
643
+ })),
644
+ ];
645
+ app.overlay(
646
+ new ActionPicker(
647
+ `Schedules on ${oneLine(app.device.id)}`,
648
+ items,
649
+ async (item) => {
650
+ app.closeOverlay();
651
+ if (item.value === "+new") {
652
+ await newScheduleFlow(app);
653
+ return void pickSchedules(app);
654
+ }
655
+ const s = list.find((x) => x.id === item.value)!;
656
+ await app.run(async () => {
657
+ const after = await app.client.runSchedule(s.id);
658
+ app.notify(`▶ ${oneLine(after.name)} — session started (log view: L)`);
659
+ app.logEvent("sched", `${oneLine(after.name)} triggered by hand · ${triggerOf(after)}`);
660
+ });
661
+ // next/last changed — reopen on fresh state rather than showing a stale row.
662
+ void pickSchedules(app);
663
+ },
664
+ () => app.closeOverlay(),
665
+ "enter run now · t on/off · d delete · n new · esc close",
666
+ {
667
+ t: async (item) => {
668
+ if (item.value === "+new") return;
669
+ const s = list.find((x) => x.id === item.value)!;
670
+ app.closeOverlay();
671
+ await app.run(async () => {
672
+ const after = await app.client.updateSchedule(s.id, { enabled: !s.enabled });
673
+ app.notify(`${oneLine(after.name)} ${after.enabled ? "enabled ●" : "disabled ○"}`);
674
+ app.logEvent("sched", `${oneLine(after.name)} ${after.enabled ? "enabled" : "disabled"}`);
675
+ });
676
+ void pickSchedules(app);
677
+ },
678
+ d: async (item) => {
679
+ if (item.value === "+new") return;
680
+ const s = list.find((x) => x.id === item.value)!;
681
+ // The same y/n gate /reset asks (R4 finding 4): a destructive door
682
+ // confirms; esc or anything not starting with y keeps the schedule.
683
+ const ok = await app.prompt(`Delete schedule ${oneLine(s.name)}? y/n`, "");
684
+ if (ok === undefined || !ok.trim().toLowerCase().startsWith("y"))
685
+ return app.flash("delete cancelled"), undefined;
686
+ app.closeOverlay();
687
+ await app.run(async () => {
688
+ await app.client.removeSchedule(s.id);
689
+ app.notify(`deleted ${oneLine(s.name)}`);
690
+ app.logEvent("sched", `deleted ${oneLine(s.name)} · ${triggerOf(s)}`);
691
+ });
692
+ void pickSchedules(app);
693
+ },
694
+ n: async () => {
695
+ app.closeOverlay();
696
+ await newScheduleFlow(app);
697
+ void pickSchedules(app);
698
+ },
699
+ },
700
+ ),
701
+ );
702
+ }
703
+
704
+ /** /env (run-12): the device's env file — list, edit, set, remove. Secrets
705
+ * arrive masked from the backend and are never round-tripped: editing a
706
+ * secret prefills BLANK (a prefilled mask would overwrite the real value). */
707
+ export async function pickEnv(app: App) {
708
+ let view: EnvFileView;
709
+ try {
710
+ view = await app.client.envView();
711
+ } catch (e) {
712
+ return app.notify(`env: ${(e as Error).message.slice(0, 80)}`, true);
713
+ }
714
+ const items: SelectItem[] = [
715
+ { value: "+new", label: "+ Set variable", description: "add or overwrite one key in the env file" },
716
+ ...view.vars.map((v) => ({
717
+ value: v.key,
718
+ label: `${oneLine(v.key)}=${oneLine(v.masked)}`,
719
+ description: v.source === "process" || v.managed ? "read-only" : "file · editable",
720
+ })),
721
+ ];
722
+ const editable = (v: { source: string; managed: boolean }) => !(v.source === "process" || v.managed);
723
+ const editVar = async (key: string) => {
724
+ const v = view.vars.find((x) => x.key === key);
725
+ if (!v) return;
726
+ if (!editable(v))
727
+ return app.notify(
728
+ `${oneLine(v.key)} is read-only (${v.managed ? "managed by the device" : "inherited from the process env"})`,
729
+ );
730
+ const value = await app.prompt(
731
+ `Value for ${oneLine(v.key)}${v.secret ? " (secret — the file keeps it masked)" : ""}`,
732
+ v.secret ? "" : oneLine(v.masked),
733
+ );
734
+ if (value === undefined) return app.flash("edit cancelled"), undefined;
735
+ // An empty submit on a masked row is far more likely a stray enter than an
736
+ // intent to blank the variable — removing has its own confirmed door (d).
737
+ if (!value) return app.flash("cancelled — an empty value would clear the variable (d removes)"), undefined;
738
+ app.closeOverlay();
739
+ await app.run(async () => {
740
+ await app.client.setEnvVar(v.key, value);
741
+ app.notify(`${oneLine(v.key)} saved`);
742
+ app.logEvent("env", `set ${oneLine(v.key)}`);
743
+ });
744
+ void pickEnv(app);
745
+ };
746
+ app.overlay(
747
+ new ActionPicker(
748
+ `Device env${view.envFile ? ` — ${oneLine(view.envFile)}` : ""}`,
749
+ items,
750
+ (item) => {
751
+ if (item.value === "+new") {
752
+ app.closeOverlay();
753
+ void setNewVar(app).then(() => pickEnv(app));
754
+ return;
755
+ }
756
+ void editVar(item.value);
757
+ },
758
+ () => app.closeOverlay(),
759
+ "enter edit · d remove · n set new · esc close",
760
+ {
761
+ d: async (item) => {
762
+ if (item.value === "+new") return;
763
+ const v = view.vars.find((x) => x.key === item.value);
764
+ if (!v) return;
765
+ if (!editable(v)) return app.notify(`${oneLine(v.key)} is read-only`);
766
+ const ok = await app.prompt(`Remove ${oneLine(v.key)} from the env file? y/n`, "");
767
+ if (ok === undefined || !ok.trim().toLowerCase().startsWith("y"))
768
+ return app.flash("remove cancelled"), undefined;
769
+ app.closeOverlay();
770
+ await app.run(async () => {
771
+ await app.client.removeEnvVar(v.key);
772
+ app.notify(`removed ${oneLine(v.key)}`);
773
+ app.logEvent("env", `removed ${oneLine(v.key)}`);
774
+ });
775
+ void pickEnv(app);
776
+ },
777
+ n: async () => {
778
+ app.closeOverlay();
779
+ await setNewVar(app);
780
+ void pickEnv(app);
781
+ },
782
+ },
783
+ // The backend flags this — surfacing it where the edit happens beats a
784
+ // separate "did my change apply?" trip to the FE.
785
+ view.restartRequired ? "changed since boot — restart the device to apply" : undefined,
786
+ ),
787
+ );
788
+ }
789
+
790
+ /** The /env n chain: key → value → one setEnvVar call. Re-asks on a key that
791
+ * could not live in an env file, mirroring promptScheduleTrigger. */
792
+ async function setNewVar(app: App) {
793
+ let key = "";
794
+ for (;;) {
795
+ key = ((await app.prompt("Key (letters, digits, _ — e.g. MY_TOOL_TOKEN)", "")) ?? "").trim();
796
+ if (!key) return app.flash("set cancelled"), undefined;
797
+ if (/^[A-Za-z_][A-Za-z0-9_.]*$/.test(key)) break;
798
+ app.flash("keys start with a letter or _ and carry letters, digits, _ and . only", true);
799
+ }
800
+ const value = (await app.prompt(`Value for ${oneLine(key)}`, ""))?.trim();
801
+ if (!value) return app.flash("set cancelled"), undefined;
802
+ await app.run(async () => {
803
+ await app.client.setEnvVar(key, value);
804
+ app.notify(`${oneLine(key)} saved`);
805
+ app.logEvent("env", `set ${oneLine(key)}`);
806
+ });
807
+ }
808
+
809
+ /** /notify (run-12): list the sinks and fire a test event. NO sink CRUD from
810
+ * the TUI — sinks hold credentials (webhook URLs, ntfy topics), and the web
811
+ * FE is their managed home; the palette only proves the pipe works. */
812
+ export async function pickNotify(app: App) {
813
+ let sinks: NotifySinkView[];
814
+ try {
815
+ sinks = (await app.client.notifySinks()).sinks;
816
+ } catch (e) {
817
+ return app.notify(`notify: ${(e as Error).message.slice(0, 80)}`, true);
818
+ }
819
+ if (!sinks.length)
820
+ return app.notify("no notify sinks on this device — manage them in the web FE (they hold credentials)");
821
+ const test = async () => {
822
+ try {
823
+ const { results } = await app.client.testNotifySinks();
824
+ const sent = results.filter((r) => r.status === "sent").length;
825
+ const failed = results.filter((r) => r.status === "failed").length;
826
+ const skipped = results.length - sent - failed;
827
+ app.notify(
828
+ `notify test: ${sent} sent${failed ? ` · ${failed} failed` : ""}${skipped ? ` · ${skipped} skipped` : ""}${failed ? " (log view: L)" : ""}`,
829
+ );
830
+ for (const r of results)
831
+ app.logEvent(
832
+ "notify",
833
+ `${oneLine(r.kind)} ${oneLine(r.id)} — ${r.status}${r.detail ? ` · ${oneLine(r.detail).slice(0, 60)}` : ""}${r.ms != null ? ` · ${r.ms}ms` : ""}`,
834
+ );
835
+ } catch (e) {
836
+ app.notify(`notify test: ${(e as Error).message.slice(0, 80)}`, true);
837
+ }
838
+ };
839
+ app.overlay(
840
+ new ActionPicker(
841
+ "Notify sinks (testing only — CRUD lives in the web FE)",
842
+ sinks.map((s) => ({
843
+ value: s.id,
844
+ // kind is device-authored and sits in a LABEL (never LF-normalized
845
+ // by pi-tui — r12 review m1) — oneLine here, not just the description.
846
+ label: `${s.enabled ? "●" : "○"} ${oneLine(String(s.kind))}${s.label ? ` ${oneLine(s.label)}` : ""}`,
847
+ 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" : ""}`,
848
+ })),
849
+ () => void test(),
850
+ () => app.closeOverlay(),
851
+ "enter/t test every enabled sink · esc close",
852
+ { t: () => void test() },
853
+ ),
854
+ );
855
+ }
856
+
857
+ // ---------------------------------------------- run-13: :archive
858
+ // The SDK's archive surface (policy #3): list bundles, read a transcript,
859
+ // restore. NO delete door — the SDK exposes no endpoint, and the palette does
860
+ // not invent one (run-13 scope). fmtBytes/fmtDur come from commands.ts (their
861
+ // home since run-12); the import is function-referenced only, so the benign
862
+ // pickers↔commands cycle is safe under ESM live bindings.
863
+
864
+ /** Transcript dump caps (run-13 A2, the r9 diagnostics-caps pattern): the log
865
+ * view is a 500-entry ring, so one :archive enter may add at most 400 lines /
866
+ * 100 KiB, with a LEADING marker naming what was cut — never a silent crop.
867
+ * Each surviving line is sanitizeTerminal'd HERE: logEvent writes its text
868
+ * verbatim (no normalizer downstream), so this helper is the chokepoint. */
869
+ const TRANSCRIPT_MAX_LINES = 400;
870
+ const TRANSCRIPT_MAX_BYTES = 100 * 1024;
871
+
872
+ export function capTranscriptLines(text: string): string[] {
873
+ const raw = String(text ?? "");
874
+ let cut = false;
875
+ let body = raw;
876
+ if (Buffer.byteLength(body, "utf8") > TRANSCRIPT_MAX_BYTES) {
877
+ // Byte-boundary cut on the UTF-8 encoding (a char-count slice could leave
878
+ // up to 4× the budget for multibyte text); toString drops any dangling
879
+ // multibyte fragment as U+FFFD.
880
+ cut = true;
881
+ body = Buffer.from(body, "utf8").subarray(0, TRANSCRIPT_MAX_BYTES).toString("utf8");
882
+ }
883
+ const total = raw.split("\n").length;
884
+ const all = body.split("\n");
885
+ const lines = all.slice(0, TRANSCRIPT_MAX_LINES);
886
+ if (all.length > TRANSCRIPT_MAX_LINES) cut = true;
887
+ const out = lines.map((l) => sanitizeTerminal(l));
888
+ if (cut) {
889
+ // The count names the lines the operator will not see (a byte cut can hide
890
+ // more than the count shows — it is a lower bound, still honest).
891
+ const dropped = Math.max(1, total - lines.length);
892
+ out.unshift(`... truncated (${dropped} line${dropped === 1 ? "" : "s"})`);
893
+ }
894
+ return out;
895
+ }
896
+
897
+ /** /archive (run-13 A2): archived sessions, newest first. Every device-
898
+ * authored field goes through oneLine INCLUDING the label path — pi-tui
899
+ * LF-normalizes descriptions only, so label strings must be collapsed at
900
+ * compose time (the r12 m1 lesson, pinned by test). Enter keeps the list up
901
+ * (reading is read-only, the pickNotify pattern) and dumps the markdown
902
+ * transcript into the log view through the caps above; r restores behind the
903
+ * same y/n gate /reset uses, then the list refetches without the row. */
904
+ export async function pickArchived(app: App) {
905
+ let list: ArchivedView[];
906
+ try {
907
+ list = (await app.client.archived()).sessions;
908
+ } catch (e) {
909
+ return app.notify(`archive: ${(e as Error).message.slice(0, 80)}`, true);
910
+ }
911
+ if (!list.length) return app.notify("no archived sessions on this device");
912
+ // archivedAt is relay-borne — coerce (a string/garbage field must not break
913
+ // the sort, R19 discipline) and sort newest-first.
914
+ const sessions = [...list].sort((a, b) => (Number(b.archivedAt) || 0) - (Number(a.archivedAt) || 0));
915
+ const items: SelectItem[] = sessions.map((s) => ({
916
+ // value is never rendered (filter matches label+description only) — keep
917
+ // the RAW id so transcript/restore hit the device's true session.
918
+ value: String(s.sessionId ?? ""),
919
+ label: `${s.hasManifest === true ? "◈" : "◇"} ${oneLine(String(s.name ?? ""))}`,
920
+ description: `${oneLine(String(s.cwd ?? ""))} · ${oneLine(String(Number(s.turns) || 0))} turns · ${fmtBytes(Number(s.bytes) || 0)} · archived ${fmtDur(Math.max(0, (Date.now() - (Number(s.archivedAt) || 0)) / 1000))} ago`,
921
+ }));
922
+ const showTranscript = async (item: SelectItem) => {
923
+ const s = sessions.find((x) => x.sessionId === item.value);
924
+ const label = oneLine(String(s?.name ?? item.value));
925
+ try {
926
+ const view = await app.client.archivedTranscript(item.value, "markdown");
927
+ const raw = String(view.text ?? "");
928
+ if (!raw.trim()) return app.notify(`transcript: ${label} is empty`);
929
+ const lines = capTranscriptLines(raw);
930
+ // Raw markdown is fine — the TUI does not render md, it prints lines.
931
+ for (const line of lines) app.logEvent("arch", line);
932
+ app.notify(`${label} — transcript, ${lines.length} line${lines.length === 1 ? "" : "s"} (log view: L)`);
933
+ } catch (e) {
934
+ app.notify(`transcript: ${(e as Error).message.slice(0, 80)}`, true);
935
+ }
936
+ };
937
+ const restore = async (item: SelectItem) => {
938
+ const s = sessions.find((x) => x.sessionId === item.value);
939
+ const label = oneLine(String(s?.name ?? item.value));
940
+ // The same y/n gate /reset and /schedules d ask (R4 finding 4): a
941
+ // state-changing door confirms; esc or anything not starting with y keeps
942
+ // the bundle archived.
943
+ const ok = await app.prompt(`Restore ${label}? y/n`, "");
944
+ if (ok === undefined || !ok.trim().toLowerCase().startsWith("y"))
945
+ return app.flash("restore cancelled"), undefined;
946
+ app.closeOverlay();
947
+ await app.run(async () => {
948
+ const restored = await app.client.restoreArchived(item.value);
949
+ const name = oneLine(String((restored as { name?: string })?.name ?? label));
950
+ // The app's session list refetches on its next view entry — no hook
951
+ // needed; the toast points the operator at g.
952
+ app.notify(`restored ${name} — press g to open it`);
953
+ app.logEvent("arch", `restored ${name}`);
954
+ });
955
+ // The row is gone on the device — refetch instead of showing a stale list
956
+ // (the pickSchedules d pattern).
957
+ void pickArchived(app);
958
+ };
959
+ app.overlay(
960
+ new ActionPicker(
961
+ `Archived on ${oneLine(app.device.id)}`,
962
+ items,
963
+ (item) => void showTranscript(item),
964
+ () => app.closeOverlay(),
965
+ "enter transcript · r restore · esc close",
966
+ { r: restore },
967
+ "◈ manifest · ◇ bundle only",
968
+ ),
969
+ );
970
+ }