aboutsummaryrefslogtreecommitdiffstats
path: root/pi-ext/answer-picker.ts
blob: a5f264011bd806095dd83dd8145d30c41fd4efef (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
/**
 * Answer Picker — preset follow-up prompts as clickable buttons in the pane frame.
 *
 * Puts the short prompts you type over and over ("continue", "yes", "run the
 * tests", ...) into the bottom frame row of pi's own pane, via the sl0p zellij
 * fork's OSC 5577 pane-status-bar protocol. Click one, or press alt+<N>, and it
 * is sent to the agent as a real user message.
 *
 *   ╭───────────────────────── pi ─────────────────────────╮
 *   │ transcript, editor, …                                │
 *   ╰ alt+N · ready ──[continue]─[yes]─[no]─[explain]───────╯
 *      ^ status text        ^ zellij-drawn, clickable
 *
 * ── WHERE THE ANSWERS COME FROM ──────────────────────────────────────────────
 * Two sources, with the file winning outright when it exists:
 *
 *   1. DEFAULTS below — the built-in set, used when no file is present.
 *   2. <cwd>/.pi-answers.md — per-project answers, read at session start.
 *
 * The file is authoritative rather than additive: it is SEEDED with DEFAULTS the
 * first time anything writes it, so "file wins" and "you still get the defaults"
 * are the same statement. That keeps precedence trivial to reason about (there is
 * no merge order to remember) while making the defaults editable — delete a line
 * from the file and that button is gone, which an additive model could not do.
 *
 * `/answers add <label> [text…]` appends and persists in one step, creating the
 * file (defaults + the new answer) if it does not exist yet. Hand-editing the
 * file is equally supported; `/answers reload` re-reads it.
 *
 * File format — a markdown list, label in backticks so the text may contain any
 * punctuation (including the em dash used as separator):
 *
 *     - `continue` — continue
 *     - `no` — no — don't do that
 *
 * Parsing takes the label from between the backticks and everything after the
 * first separator as the text, so a dash inside the text is not a problem. A
 * looser `- label: text` / `- label -> text` form is also accepted for
 * hand-written files.
 *
 * ── WHY OSC 5577 RATHER THAN DRAWING OUR OWN BUTTONS ─────────────────────────
 * v1 drew its own button row and enabled terminal mouse reporting inside pi.
 * Mouse reporting is per-terminal, not per-region — the wheel is just another
 * button in that protocol — so pi's pane lost native wheel scrolling and
 * click-drag selection as the price of clickable buttons. v2 moved the buttons to
 * a second pane to confine the tracking, which restored scrolling but cost an
 * extra pane, a picker process and a unix socket.
 *
 * OSC 5577 removes the tradeoff instead of relocating it: zellij draws the
 * buttons in the frame it already owns, hit-tests them itself, and reports a
 * click as a fixed-format sequence on our stdin. No mouse reporting anywhere, no
 * second pane, no socket. The frame row also does not shrink the content area, so
 * setting or clearing it never resizes the PTY nor sends SIGWINCH.
 *
 *   we send:   ESC ] 5577;1;buttons;ans-continue:continue;ans-yes:yes ESC \
 *              ESC ] 5577;1;status;alt+N · ready                      ESC \
 *   we get:    ESC ] 5577;1;click;ans-continue                        ESC \
 *
 * ── CONSEQUENCES OF THE PROTOCOL WE HAVE TO HANDLE ───────────────────────────
 *   - Click reports arrive INTERLEAVED with ordinary stdin, like a cursor-position
 *     or OSC 11 reply. We scan for them and strip them, because anything left in
 *     the stream would be typed into the editor as garbage. We do get whole
 *     reports: pi-tui's StdinBuffer holds an `ESC ]` sequence until its ST/BEL
 *     terminator arrives (isCompleteOscSequence), so a report split across
 *     read() boundaries is reassembled before it reaches us.
 *   - Ids are validated against the buttons we actually declared. They are
 *     DERIVED FROM THE LABEL (ans-<slug>) rather than positional, so that when
 *     the answer list changes, a click report for a button that no longer exists
 *     simply fails to match instead of resolving to whatever now occupies that
 *     index. Positional ids would silently fire the wrong prompt.
 *   - These are in-band escapes, so anything that writes to the pane (a `cat` of
 *     a hostile file) can declare buttons and draw a misleading bar. A click
 *     report is a hint that a user pressed something, not proof that we put it
 *     there — hence the allow-list, and hence keeping the action non-destructive
 *     (it sends a prompt; it does not deploy anything).
 *   - The bar survives detach/reattach AND session resurrection, so a restored
 *     pane can come back showing a stale bar. We re-assert on every session_start
 *     and clear on shutdown rather than trusting the screen.
 *   - Buttons are click-only; the protocol has no keyboard access. alt+1..9 is
 *     ours, is registered once against a live lookup (so answers added at runtime
 *     get a working key immediately), and works even with frames off — including
 *     mid-run, when the buttons themselves are deliberately withdrawn.
 *
 * ── BUTTONS ONLY EXIST BETWEEN TURNS ───────────────────────────────────────
 * While a run is in flight the buttons are withdrawn and only the status text
 * remains, so a click cannot queue a second answer behind the one already
 * working. They come back when the run settles — completed, errored, or
 * cancelled. That relies on agent_settled as much as agent_end: agent_settled is
 * what fires on the abort/error paths where agent_end never arrives, so an
 * escape-key cancel or a provider blow-up still restores them rather than
 * leaving the frame permanently bare.
 *
 * Withdrawing means sending `buttons` with an empty payload (an empty list),
 * NOT `clear` — `clear` would take the status text with it. Verified against the
 * fork: the buttons verb assigns parse_status_bar_buttons(payload), which
 * filter_maps away every field lacking an `id:label`, and only `clear` touches
 * status_bar.
 *   - The bar needs pane frames. With pane_frame_style "none"/"titles", or after
 *     TogglePaneFrames, it is simply not drawn — nothing breaks.
 *   - Protocol limits: 8 buttons, 512-char status, control chars stripped.
 *     Answers past the 8th stay keyboard-only rather than being silently dropped.
 */

import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
import fs from "node:fs";
import path from "node:path";

type Answer = { label: string; text: string };

/** Payload for the /answers list transcript entry. */
type AnswersListData = {
  answers: Answer[];
  source: "file" | "defaults";
  path: string;
  maxButtons: number;
};

/** Built-in set. Used until a .pi-answers.md exists, and seeds it when created. */
const DEFAULTS: readonly Answer[] = [
  { label: "continue", text: "continue" },
  { label: "yes", text: "yes, go ahead" },
  { label: "no", text: "no — don't do that" },
  { label: "explain", text: "explain what you just did, and why" },
  { label: "tests", text: "run the tests and fix anything that fails" },
  { label: "commit", text: "commit this with a clear message" },
];

/** Per-project answers, looked up in the cwd pi was started in. */
const ANSWERS_FILE = ".pi-answers.md";

const NUDGE_KEYS = ["alt+1", "alt+2", "alt+3", "alt+4", "alt+5", "alt+6", "alt+7", "alt+8", "alt+9"] as const;
const MIDRUN_DELIVERY: "steer" | "followUp" = "followUp";
const DEBOUNCE_MS = 250;

// Protocol ceilings (zellij drops the excess itself; we cap to stay predictable).
const MAX_BUTTONS = 8;
const MAX_STATUS = 512;
const MAX_LABEL = 24;

const OSC = "\x1b]5577;1;";
const ST = "\x1b\\";
const CLICK_RE = /\x1b\]5577;1;click;([A-Za-z0-9_-]{1,32})(?:\x1b\\|\x07)/g;

/** Button fields are `;`-separated, so `;` `:` `%` must be %-escaped in labels. */
const escLabel = (s: string) => s.replace(/%/g, "%25").replace(/;/g, "%3B").replace(/:/g, "%3A");
// eslint-disable-next-line no-control-regex
const stripCtl = (s: string) => s.replace(/[\x00-\x1f\x7f]/g, "");

/**
 * Labels are delimited by backticks in the file, so a backtick inside one would
 * corrupt the format on the next write. Strip them here rather than at the write
 * site, so a hand-written ``- `` — x`` (empty backticks) also collapses to an
 * empty label and gets dropped instead of becoming a junk `` `` `` button.
 */
const cleanLabel = (s: string) => stripCtl(s).replace(/`/g, "").slice(0, MAX_LABEL).trim();

/** Markdown list item: canonical ``- `label` — text`` plus looser fallbacks. */
function parseAnswers(md: string): Answer[] {
  const out: Answer[] = [];
  const seen = new Set<string>();
  for (const raw of md.split(/\r?\n/)) {
    const line = raw.trim();
    if (!line.startsWith("-") && !line.startsWith("*")) continue;
    const item = line.replace(/^[-*]\s*/, "");
    if (!item) continue;

    let label: string;
    let text: string;
    const backticked = /^`([^`]{1,64})`\s*(.*)$/.exec(item);
    if (backticked) {
      label = backticked[1].trim();
      text = backticked[2].replace(/^\s*(?:—|--|->|:)\s*/, "").trim();
    } else {
      const sep = /\s+(?:—|--|->)\s+|:\s+/.exec(item);
      if (sep) {
        label = item.slice(0, sep.index).trim();
        text = item.slice(sep.index + sep[0].length).trim();
      } else {
        label = item.trim();
        text = label;
      }
    }
    label = cleanLabel(label);
    text = stripCtl(text).trim() || label;
    if (!label || seen.has(label.toLowerCase())) continue;
    seen.add(label.toLowerCase());
    out.push({ label, text });
  }
  return out;
}

function renderAnswers(list: readonly Answer[]): string {
  return [
    "# pi answer buttons",
    "",
    "<!-- Clickable buttons in this pane's zellij frame row (OSC 5577), also alt+1..9.",
    "     Format:  - `label` — text sent to the agent",
    "     This file is authoritative: it was seeded with answer-picker.ts defaults,",
    "     so deleting a line removes that button. `/answers reload` re-reads it. -->",
    "",
    ...list.map((a) => `- \`${a.label}\` — ${a.text}`),
    "",
  ].join("\n");
}

/**
 * Stable, label-derived button id. Deliberately not positional: if the answer
 * list changes, an in-flight click for a vanished button must fail the allow-list
 * rather than resolve to whatever took its index.
 */
function buttonId(label: string, idx: number, taken: Set<string>): string {
  const slug = label
    .toLowerCase()
    .replace(/[^a-z0-9_-]+/g, "-")
    .replace(/^-+|-+$/g, "")
    .slice(0, 24);
  let id = slug ? `ans-${slug}` : `ans-${idx}`;
  if (taken.has(id)) id = `${id}-${idx}`.slice(0, 32);
  return id;
}

export default function (pi: ExtensionAPI) {
  let answers: Answer[] = DEFAULTS.map((a) => ({ ...a }));
  /** id -> index allow-list for the buttons currently declared. */
  const declared = new Map<string, number>();
  let filePath: string | undefined;
  let fromFile = false;
  let barActive = false;
  let buttonsShown = false;
  let isRunning = false;
  let turn = 0;
  let lastFireAt = 0;
  let unsubInput: (() => void) | undefined;

  const inZellij = () => !!process.env.ZELLIJ || !!process.env.ZELLIJ_SESSION_NAME;

  function write(s: string) {
    try {
      process.stdout.write(s);
    } catch {
      /* closed stdout */
    }
  }

  // ── answers file ──────────────────────────────────────────────────────────
  function resolvePath(ctx: any): string {
    return path.join(ctx?.cwd || process.cwd(), ANSWERS_FILE);
  }

  function loadAnswers(ctx: any): { source: "file" | "defaults"; count: number; error?: string } {
    filePath = resolvePath(ctx);
    try {
      if (fs.existsSync(filePath)) {
        const parsed = parseAnswers(fs.readFileSync(filePath, "utf8"));
        if (parsed.length > 0) {
          answers = parsed;
          fromFile = true;
          return { source: "file", count: parsed.length };
        }
        // Present but unparseable: fall back rather than leave the user with no
        // buttons, and say so instead of failing silently.
        answers = DEFAULTS.map((a) => ({ ...a }));
        fromFile = false;
        return { source: "defaults", count: answers.length, error: `${ANSWERS_FILE} has no readable entries` };
      }
    } catch (err: any) {
      answers = DEFAULTS.map((a) => ({ ...a }));
      fromFile = false;
      return { source: "defaults", count: answers.length, error: err?.message ?? String(err) };
    }
    answers = DEFAULTS.map((a) => ({ ...a }));
    fromFile = false;
    return { source: "defaults", count: answers.length };
  }

  /** Persist current answers, creating the file (seeded with defaults) if needed. */
  function saveAnswers(ctx: any): string | undefined {
    const p = filePath ?? resolvePath(ctx);
    try {
      fs.writeFileSync(p, renderAnswers(answers), "utf8");
      filePath = p;
      fromFile = true;
      return undefined;
    } catch (err: any) {
      return err?.message ?? String(err);
    }
  }

  // ── OSC 5577 bar ──────────────────────────────────────────────────────────
  function showButtons() {
    if (!inZellij()) return;
    declared.clear();
    const spec: string[] = [];
    answers.slice(0, MAX_BUTTONS).forEach((a, idx) => {
      const id = buttonId(a.label, idx, new Set(declared.keys()));
      declared.set(id, idx);
      spec.push(`${id}:${escLabel(a.label)}`);
    });
    if (spec.length === 0) {
      hideButtons();
      return;
    }
    write(`${OSC}buttons;${spec.join(";")}${ST}`);
    buttonsShown = true;
    barActive = true;
  }

  /**
   * Drop ONLY the buttons, keeping the status text. `buttons` with no id:label
   * field parses to an empty list in the fork (parse_status_bar_buttons
   * filter_maps every field lacking a ':'), whereas `clear` is the one verb that
   * would also wipe the status.
   *
   * Clearing `declared` matters as much as the redraw: a click report already in
   * flight when the run started must not fire against a button that is no longer
   * on screen.
   */
  function hideButtons() {
    declared.clear();
    if (!inZellij() || !buttonsShown) return;
    buttonsShown = false;
    write(`${OSC}buttons${ST}`);
    barActive = true;
  }

  function setStatus() {
    if (!inZellij()) return;
    const state = isRunning ? "working" : "ready";
    const extra = answers.length > MAX_BUTTONS ? ` · +${answers.length - MAX_BUTTONS} via alt+N` : "";
    write(`${OSC}status;${stripCtl(`alt+N · ${state}${turn ? ` · #${turn}` : ""}${extra}`).slice(0, MAX_STATUS)}${ST}`);
    barActive = true;
  }

  function clearBar() {
    if (!barActive) return;
    barActive = false;
    buttonsShown = false;
    declared.clear();
    write(`${OSC}clear${ST}`);
  }

  /**
   * Assert the bar for the current state. Buttons exist only between turns:
   * while the agent is working they are withdrawn, so a click cannot queue a
   * second answer behind the one already in flight. The status text stays up
   * throughout, which is also what advertises that alt+N still works.
   */
  function refresh() {
    if (isRunning) hideButtons();
    else showButtons();
    setStatus();
  }

  function fire(idx: number) {
    const a = answers[idx];
    if (!a) return;
    const now = Date.now();
    if (now - lastFireAt < DEBOUNCE_MS) return;
    lastFireAt = now;
    if (isRunning) pi.sendUserMessage(a.text, { deliverAs: MIDRUN_DELIVERY });
    else pi.sendUserMessage(a.text);
  }

  function onInput(data: string): { consume?: boolean; data?: string } | undefined {
    if (!data.includes("5577")) return undefined;
    let residual = "";
    let cursor = 0;
    let saw = false;
    CLICK_RE.lastIndex = 0;
    let m: RegExpExecArray | null;
    while ((m = CLICK_RE.exec(data)) !== null) {
      saw = true;
      residual += data.slice(cursor, m.index);
      cursor = m.index + m[0].length;
      const idx = declared.get(m[1]);
      if (idx !== undefined) fire(idx); // unknown id: swallowed, never acted on
    }
    if (!saw) return undefined;
    residual += data.slice(cursor);
    return residual.length === 0 ? { consume: true } : { data: residual };
  }

  // ── /answers list rendering ───────────────────────────────────────────────
  // A ▪ marks an answer that has a clickable button; · marks one only reachable
  // by alt+N, because the protocol's 8-button row is full. Bodies are truncated
  // to the pane width and wrapped in full when the entry is expanded (ctrl+o).
  pi.registerEntryRenderer<AnswersListData>("answers-list", (entry, { expanded }, theme) => {
    const d = entry.data;
    if (!d) return undefined;
    return {
      render(width: number): string[] {
        const IND = "  ";
        const srcLabel = d.source === "file" ? path.basename(d.path) : "built-in defaults";
        const lines: string[] = [];

        lines.push(
          `${IND}${theme.fg("accent", "◈")} ${theme.fg("accent", theme.bold("answers"))}` +
            theme.fg("dim", `  ${d.answers.length} · ${srcLabel}`),
        );
        lines.push("");

        if (d.answers.length === 0) {
          lines.push(`${IND}${theme.fg("warning", "(none)")} ${theme.fg("dim", "— /answers init restores the defaults")}`);
        } else {
          const idxW = String(d.answers.length).length;
          const labelW = Math.min(20, Math.max(...d.answers.map((a) => a.label.length)));
          d.answers.forEach((a, i) => {
            const isBtn = i < d.maxButtons;
            const marker = isBtn ? theme.fg("accent", "▪") : theme.fg("dim", "·");
            const num = String(i + 1).padStart(idxW);
            const label = a.label.length > labelW ? `${a.label.slice(0, labelW - 1)}…` : a.label.padEnd(labelW);
            const prefix = `${IND}${marker} ${theme.fg("dim", num)}  ${theme.fg(isBtn ? "accent" : "muted", label)}  `;
            const avail = Math.max(8, width - visibleWidth(prefix) - 2);
            if (expanded) {
              const wrapped = wrapTextWithAnsi(a.text, avail);
              lines.push(prefix + theme.fg("muted", wrapped[0] ?? ""));
              for (const cont of wrapped.slice(1)) {
                lines.push(" ".repeat(visibleWidth(prefix)) + theme.fg("muted", cont));
              }
            } else {
              lines.push(prefix + theme.fg("muted", truncateToWidth(a.text, avail, "…")));
            }
          });
        }

        lines.push("");
        lines.push(
          `${IND}${theme.fg("dim", d.source === "file" ? d.path : `${d.path}  (created on first add)`)}`,
        );
        if (d.answers.length > d.maxButtons) {
          lines.push(`${IND}${theme.fg("dim", `▪ button  · alt+N only — the frame row holds ${d.maxButtons}`)}`);
        }
        lines.push(`${IND}${theme.fg("dim", "/answers add <label> [text…] · rm <label> · reload")}`);
        // Safety net: the header, footer and legend are fixed strings, so on a
        // narrow pane they would wrap and visually break the entry. Clamp every
        // line to the width (ANSI-aware) rather than trusting each producer.
        return lines.map((l) => (visibleWidth(l) > width ? truncateToWidth(l, width, "…") : l));
      },
      invalidate() {},
    };
  });

  // ── /answers ──────────────────────────────────────────────────────────────
  const SUBS = [
    { value: "list", label: "list", description: "show current answers and their source" },
    { value: "add", label: "add <label> [text…]", description: "add an answer and persist it" },
    { value: "rm", label: "rm <label>", description: "remove an answer and persist it" },
    { value: "reload", label: "reload", description: `re-read ${ANSWERS_FILE}` },
    { value: "init", label: "init", description: `create ${ANSWERS_FILE} from the defaults` },
    { value: "refresh", label: "refresh", description: "re-assert the buttons in the frame" },
  ];

  function summary(): string {
    const src = fromFile ? ANSWERS_FILE : "built-in defaults";
    const shown = Math.min(answers.length, MAX_BUTTONS);
    return `${answers.length} answers from ${src} (${shown} as buttons)`;
  }

  /**
   * Render the list into the transcript rather than a one-line notification:
   * the bodies are the useful part and they do not fit on one row. appendEntry
   * keeps it out of the LLM context while staying scrollable and copyable.
   */
  function showList(ctx: any) {
    pi.appendEntry<AnswersListData>("answers-list", {
      answers: answers.map((a) => ({ ...a })),
      source: fromFile ? "file" : "defaults",
      path: filePath ?? resolvePath(ctx),
      maxButtons: MAX_BUTTONS,
    });
  }

  pi.registerCommand("answers", {
    description: "Manage the clickable answer buttons (list/add/rm/reload/init)",
    getArgumentCompletions: (prefix: string) => {
      const first = prefix.trimStart();
      if (first.includes(" ")) {
        // completing a label for rm
        const [sub, ...rest] = first.split(/\s+/);
        if (sub === "rm" || sub === "remove" || sub === "del") {
          const p = (rest[0] ?? "").toLowerCase();
          return answers
            .filter((a) => a.label.toLowerCase().startsWith(p))
            .map((a) => ({ value: `rm ${a.label}`, label: a.label, description: a.text }));
        }
        return null;
      }
      return SUBS.filter((s) => s.value.startsWith(first));
    },
    handler: async (args: string, ctx: any) => {
      const notify = (msg: string, kind: "info" | "warning" | "error" = "info") => {
        if (ctx.hasUI) ctx.ui.notify(msg, kind);
      };
      const parts = args.trim().split(/\s+/).filter(Boolean);
      const sub = (parts[0] ?? "list").toLowerCase();
      const rest = parts.slice(1);

      if (sub === "list") {
        showList(ctx);
        return;
      }

      if (sub === "refresh") {
        refresh();
        notify(isRunning ? "bar re-asserted — buttons return when this turn settles" : `answer buttons re-asserted (${declared.size})`);
        return;
      }

      if (sub === "reload") {
        const res = loadAnswers(ctx);
        refresh();
        if (res.error) notify(`${res.error} — using defaults`, "warning");
        showList(ctx);
        return;
      }

      if (sub === "init") {
        if (fs.existsSync(resolvePath(ctx))) {
          notify(`${ANSWERS_FILE} already exists — use /answers reload`, "warning");
          return;
        }
        const err = saveAnswers(ctx);
        refresh();
        notify(err ? `could not write ${ANSWERS_FILE}: ${err}` : `wrote ${filePath} with ${answers.length} defaults`, err ? "error" : "info");
        return;
      }

      if (sub === "add") {
        const label = cleanLabel(rest[0] ?? "");
        if (!label) {
          notify("usage: /answers add <label> [text…]  (text defaults to the label)", "warning");
          return;
        }
        const text = stripCtl(rest.slice(1).join(" ")).trim() || label;
        // First write seeds the file with the defaults + this answer, which is
        // what makes "the file always wins" safe to state without caveats.
        const existing = answers.findIndex((a) => a.label.toLowerCase() === label.toLowerCase());
        if (existing >= 0) answers[existing] = { label, text };
        else answers.push({ label, text });
        const err = saveAnswers(ctx);
        refresh();
        if (err) {
          notify(`added "${label}" for this session, but could not write ${ANSWERS_FILE}: ${err}`, "error");
          return;
        }
        const overflow = answers.length > MAX_BUTTONS ? ` (button row is full — reachable via alt+${answers.length})` : "";
        notify(`${existing >= 0 ? "updated" : "added"} "${label}" → ${filePath}${overflow}`);
        return;
      }

      if (sub === "rm" || sub === "remove" || sub === "del") {
        const label = (rest[0] ?? "").toLowerCase();
        const at = answers.findIndex((a) => a.label.toLowerCase() === label);
        if (at < 0) {
          notify(`no answer labelled "${rest[0] ?? ""}"`, "warning");
          return;
        }
        const [gone] = answers.splice(at, 1);
        // Persist even when removing a default: the file is the record of intent,
        // so a removed default must be written down or it returns next session.
        const err = saveAnswers(ctx);
        refresh();
        notify(err ? `removed "${gone.label}" for this session, but could not write ${ANSWERS_FILE}: ${err}` : `removed "${gone.label}" → ${filePath}`, err ? "error" : "info");
        return;
      }

      notify(`unknown subcommand "${sub}" — try list / add / rm / reload / init / refresh`, "warning");
    },
  });

  // Registered once against a live lookup, so answers added at runtime work
  // immediately without re-registering shortcuts.
  NUDGE_KEYS.forEach((key, idx) => {
    pi.registerShortcut(key, { description: `Answer #${idx + 1}`, handler: () => fire(idx) });
  });

  pi.on("input", async (event) => {
    if (!event.text) return;
    turn++;
    setStatus();
  });

  // Withdraw the buttons for the whole in-flight window, and put them back when
  // the run settles. agent_settled is the important half of that pair: it fires
  // on the abort/error paths where agent_end never arrives, so an escape-key
  // cancel or a provider failure still gets the buttons back.
  pi.on("agent_start", async () => {
    isRunning = true;
    refresh();
  });
  const settle = () => {
    isRunning = false;
    refresh();
  };
  pi.on("agent_end", async () => settle());
  pi.on("agent_settled", async () => settle());

  pi.on("session_start", async (_e, ctx) => {
    isRunning = false;
    turn = 0;
    const res = loadAnswers(ctx);
    if (!ctx.hasUI || ctx.mode !== "tui") return;

    unsubInput?.();
    unsubInput = ctx.ui.onTerminalInput?.(onInput);

    refresh();
    if (res.error) ctx.ui.notify(`answer picker: ${res.error} — using defaults`, "warning");
  });

  pi.on("session_shutdown", async () => {
    clearBar();
    unsubInput?.();
    unsubInput = undefined;
  });
}