@tiens.nguyen/gu-cli 1.0.851 → 1.0.853

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.
@@ -0,0 +1,102 @@
1
+ /**
2
+ * gu `/budget` (#205): the SHORT terminal version of web-v2's /providers budgets.
3
+ *
4
+ * Data: GET {apiBase}/api/worker/providers-budget with the logged-in worker key. The server decides
5
+ * Pro / email / "has items" (api/src/providers/terminalBudget.ts); this module only turns its answer
6
+ * into plain lines. Pure (fetch is injected) so every message is testable without a network.
7
+ */
8
+
9
+ export const BUDGET_TIMEOUT_MS = 15_000;
10
+
11
+ /** -> { kind: "not_logged_in" | "relogin" | "http" | "offline" | "ok", status?, body? } */
12
+ export async function fetchProvidersBudget({ apiBase, workerKey, fetchImpl = fetch, timeoutMs = BUDGET_TIMEOUT_MS }) {
13
+ if (!String(workerKey ?? "").trim() || !String(apiBase ?? "").trim()) return { kind: "not_logged_in" };
14
+ let r;
15
+ try {
16
+ r = await fetchImpl(`${String(apiBase).replace(/\/+$/, "")}/api/worker/providers-budget`, {
17
+ headers: { "X-Worker-Key": String(workerKey).trim() },
18
+ signal: AbortSignal.timeout(timeoutMs),
19
+ });
20
+ } catch (e) {
21
+ return { kind: "offline", error: e instanceof Error ? e.message : String(e) };
22
+ }
23
+ if (r.status === 401 || r.status === 403) return { kind: "relogin", status: r.status };
24
+ let body = null;
25
+ try { body = await r.json(); } catch { body = null; }
26
+ if (!r.ok || !body || typeof body.state !== "string") return { kind: "http", status: r.status, body };
27
+ return { kind: "ok", status: r.status, body };
28
+ }
29
+
30
+ const money = (n, cur) => {
31
+ if (typeof n !== "number" || !Number.isFinite(n)) return "—";
32
+ const c = String(cur || "USD").toUpperCase();
33
+ return c === "USD" ? `$${n.toFixed(2)}` : `${n.toFixed(2)} ${c}`;
34
+ };
35
+
36
+ /** "2h ago" / "3d ago" / "just now" — or "—" when never fetched. */
37
+ export function ago(iso, now = new Date()) {
38
+ const t = Date.parse(iso ?? "");
39
+ if (!Number.isFinite(t)) return "—";
40
+ const s = Math.max(0, Math.round((now.getTime() - t) / 1000));
41
+ if (s < 60) return "just now";
42
+ if (s < 3600) return `${Math.floor(s / 60)}m ago`;
43
+ if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
44
+ return `${Math.floor(s / 86400)}d ago`;
45
+ }
46
+
47
+ const pad = (s, w) => (s.length >= w ? s : s + " ".repeat(w - s.length));
48
+ const clip = (s, w) => (s.length > w ? s.slice(0, w - 1) + "…" : s);
49
+
50
+ /** One compact row per provider: name, plan/budget, used, remaining, updated. */
51
+ export function budgetTable(rows, now = new Date()) {
52
+ const head = ["Provider", "Plan / budget", "Used", "Remaining", "Updated"];
53
+ const body = rows.map((p) => {
54
+ const planCell = p.plan || (p.status === "no_billing_api" ? "no billing API" : p.status === "auth_failed" ? "key rejected" : p.status === "error" ? "could not read" : p.period ? p.period : "—");
55
+ const used = money(p.used, p.currency) + (p.used != null && p.period ? ` (${p.period})` : "");
56
+ return [clip(String(p.name || p.provider || "?"), 24), clip(planCell, 22), used, money(p.remaining, p.currency), ago(p.fetchedAt, now)];
57
+ });
58
+ const w = head.map((h, i) => Math.max(h.length, ...body.map((r) => r[i].length)));
59
+ const line = (r) => r.map((c, i) => pad(c, w[i])).join(" ").trimEnd();
60
+ return [line(head), w.map((n) => "─".repeat(n)).join(" "), ...body.map(line)];
61
+ }
62
+
63
+ /**
64
+ * What /budget prints, as { tone: "ok" | "warn" | "error", lines }. `site` is the web base
65
+ * (siteUrl(): https://gu.getmarsic.cc or GU_SITE_URL).
66
+ */
67
+ export function budgetLines(result, { site, now = new Date() } = {}) {
68
+ const base = String(site || "https://gu.getmarsic.cc").replace(/\/+$/, "");
69
+ const providersUrl = `${base}/providers`;
70
+ switch (result?.kind) {
71
+ case "not_logged_in":
72
+ return { tone: "warn", lines: ["You are not logged in — run `gu login` first, then /budget again."] };
73
+ case "relogin":
74
+ return { tone: "warn", lines: ["Your gu login is no longer valid — run `gu login` again, then /budget."] };
75
+ case "offline":
76
+ return { tone: "error", lines: [`Could not reach the gu API${result.error ? ` (${result.error})` : ""} — check your connection and try again.`] };
77
+ case "http": {
78
+ const msg = result.body && typeof result.body.error === "string" ? result.body.error : `HTTP ${result.status}`;
79
+ return { tone: "error", lines: [`Could not read your provider budgets: ${msg}`] };
80
+ }
81
+ case "ok":
82
+ break;
83
+ default:
84
+ return { tone: "error", lines: ["Could not read your provider budgets."] };
85
+ }
86
+ const b = result.body;
87
+ if (b.state === "not_pro") {
88
+ return { tone: "warn", lines: ["Provider budgets in the terminal need the Pro plan.", `Upgrade: ${base}/pricing`] };
89
+ }
90
+ if (b.state === "no_email") {
91
+ return { tone: "warn", lines: ["gu does not know this account's email, so it cannot find your budget items — run `gu login` again."] };
92
+ }
93
+ if (b.state === "no_items") {
94
+ return { tone: "warn", lines: ["No provider items added yet — add them on the web:", providersUrl] };
95
+ }
96
+ const rows = Array.isArray(b.providers) ? b.providers : [];
97
+ if (!rows.length) return { tone: "warn", lines: ["No provider items added yet — add them on the web:", providersUrl] };
98
+ return {
99
+ tone: "ok",
100
+ lines: [`Provider budgets for ${b.email || "your account"} (${rows.length})`, "", ...budgetTable(rows, now), "", `Full view and refresh: ${providersUrl}`],
101
+ };
102
+ }
@@ -405,7 +405,7 @@ export function abandonPlan(recorded = {}) {
405
405
  /** The container this owns, and the volume its data lives in. */
406
406
  export const MONGO_DOCKER_NAME = "gu-mongo";
407
407
  export const MONGO_DOCKER_VOLUME = "gu-mongo-data";
408
- export const MONGO_DOCKER_IMAGE = "mongo:8";
408
+ export const MONGO_DOCKER_IMAGE = "mongo:9";
409
409
 
410
410
  /**
411
411
  * Run MongoDB in Docker instead of installing it. → { commands, summary }
@@ -415,7 +415,8 @@ export const MONGO_DOCKER_IMAGE = "mongo:8";
415
415
  * commands, a tap most people do not know they need, and a system-wide service. A user who
416
416
  * skipped the tap got `No available formula with the name "mongodb-community"`, which is where
417
417
  * this task started. One container is less to install, less to undo, and it is the same
418
- * mongo:8 the project's own end-to-end tests already run against.
418
+ * mongo:9 the project's own end-to-end tests already run against (task #203: one series, 9.0,
419
+ * on every platform — brew and winget users already had 9.0).
419
420
  *
420
421
  * TWO THINGS THAT ARE NOT OPTIONAL HERE:
421
422
  * · A NAMED VOLUME. This database holds the user's conversation history and token counts —
@@ -452,7 +453,8 @@ export function mongoDockerPlan({ exists = false, port = 27017 } = {}) {
452
453
  * THE CODENAME IS PART OF THE COMMAND (task #329). The plan used to say `jammy/mongodb-org/7.0`
453
454
  * to every Linux machine, and that repo does not exist for Ubuntu 24.04 (noble has no 7.0 —
454
455
  * checked: HTTP 404), so on the commonest server release `apt-get update` failed on the line
455
- * setup had just printed. 8.0 is published for focal, jammy and noble. A release between two
456
+ * setup had just printed. 9.0 (task #203) is published for jammy and noble only — focal/9.0 is
457
+ * HTTP 404 (checked 2026-10-20), so focal gets no commands, only the docs. A release between two
456
458
  * LTSes takes the LTS below it, which is what MongoDB's own instructions say to do.
457
459
  */
458
460
  export function ubuntuMongoRepo({ codename = "", versionId = "" } = {}) {
@@ -462,11 +464,16 @@ export function ubuntuMongoRepo({ codename = "", versionId = "" } = {}) {
462
464
  if (!Number.isFinite(v)) return "";
463
465
  if (v >= 24.04) return "noble";
464
466
  if (v >= 22.04) return "jammy";
465
- if (v >= 20.04) return "focal";
466
467
  return "";
467
468
  }
468
- export const MONGO_APT_CODENAMES = ["focal", "jammy", "noble"];
469
- export const MONGO_APT_SERIES = "8.0";
469
+ export const MONGO_APT_CODENAMES = ["jammy", "noble"];
470
+ export const MONGO_APT_SERIES = "9.0";
471
+ // The signing key is NOT named after the series: server-9.0.asc is HTTP 404, server-9.asc is the
472
+ // "MongoDB 9 Release Signing Key" that signs dists/*/mongodb-org/9.0 (gpg-verified 2026-10-20).
473
+ export const MONGO_APT_KEY = "9";
474
+ // winget can only pin an exact version, and it trails MongoDB's releases (9.0.4 is out, winget
475
+ // has 9.0.2). Pinned so Windows gets the same series as everyone else; bump it on purpose.
476
+ export const MONGO_WINGET_VERSION = "9.0.2";
470
477
  export const MONGO_LINUX_DOCS = "https://www.mongodb.com/docs/manual/administration/install-on-linux/";
471
478
 
472
479
  /**
@@ -497,7 +504,7 @@ export function mongoInstallPlan(platform, { os = null, isRoot = false } = {}) {
497
504
  commands: [
498
505
  // winget ships with Windows 11. The installer registers a SERVICE named MongoDB and
499
506
  // starts it, which is why the probe below looks for a service rather than a process.
500
- "winget install --id MongoDB.Server --accept-package-agreements --accept-source-agreements",
507
+ `winget install --id MongoDB.Server --exact --version ${MONGO_WINGET_VERSION} --accept-package-agreements --accept-source-agreements`,
501
508
  "winget install --id MongoDB.Shell --accept-package-agreements --accept-source-agreements",
502
509
  ],
503
510
  start: "net start MongoDB",
@@ -522,7 +529,7 @@ export function mongoInstallPlan(platform, { os = null, isRoot = false } = {}) {
522
529
  commands: [
523
530
  `${sudo}apt-get install -y gnupg curl`,
524
531
  // --yes: a second run must overwrite the key, not stop to ask whether it may.
525
- `curl -fsSL https://pgp.mongodb.com/server-${v}.asc | ${sudo}gpg --dearmor --yes -o ${key}`,
532
+ `curl -fsSL https://pgp.mongodb.com/server-${MONGO_APT_KEY}.asc | ${sudo}gpg --dearmor --yes -o ${key}`,
526
533
  `echo "deb [ arch=amd64,arm64 signed-by=${key} ] https://repo.mongodb.org/apt/ubuntu ${repo}/mongodb-org/${v} multiverse" | ${sudo}tee /etc/apt/sources.list.d/mongodb-org-${v}.list`,
527
534
  `${sudo}apt-get update && ${sudo}apt-get install -y mongodb-org`,
528
535
  start,
package/gu-repl.mjs CHANGED
@@ -151,7 +151,7 @@ import { readSkillSource, sourceLabel, SKILL_SOURCE_KEY } from "./skill-source.m
151
151
  import { codingBannerLabel, isOllamaCloudUrl, SECRET_KEY_HINT } from "./coding-key-prompt.mjs";
152
152
  import { questionEchoText, thoughtPrintSeq, wrapDiffText } from "./terminal-layout.mjs";
153
153
  import { globalPrefixOf } from "./install-path.mjs";
154
- import { indentBlock } from "./terminal-layout.mjs"; // every line of an Allow-prompt detail indented (#189)
154
+ import { indentBlock, commandBlockRows } from "./terminal-layout.mjs"; // every line of an Allow-prompt detail indented (#189); wrapped + collapsible command (#204)
155
155
  import { firstGuOnPath, pathGuMismatch, guOnPathIsCurrent, updateAttemptRecord, repeatUpdateNotice } from "./update-verify.mjs";
156
156
  import { embedNotice, embedState, setupNoticeRows } from "./embed-model-command.mjs";
157
157
  import {
@@ -965,6 +965,7 @@ const COMMANDS = [
965
965
  { name: "/doctor", desc: "check every configured model ANSWERS — especially the embedder, which a turn only reaches after several steps" },
966
966
  { name: "/browser", usage: "/browser [allow|forget|install|cleanup]", desc: "the gu Chrome extension the agent uses to open and click web pages (UI tests) — is it connected, and how to install it" },
967
967
  { name: "/shells", desc: "long commands the agent left running in the background — status, runtime, command, output; stop one" },
968
+ { name: "/budget", desc: "short view of your API provider budgets and balances (Pro) — the same items as the web /providers page" },
968
969
  { name: "/tokens", desc: "break down the last prompt sent to the coding model — how much of it was RAG" },
969
970
  { name: "/clear-logs", desc: "show what gu's logs, RAG indexes and old API versions take on disk, then ask what to clear — the logs first" },
970
971
  { name: "/prices", usage: "/prices [update]", desc: "the price table and the cache table, and what the last turn and this session cost — \"update\" applies gu's newest published tables" },
@@ -3690,6 +3691,11 @@ const hoverCtl = createHoverController({
3690
3691
  * that is the one place they are told apart.
3691
3692
  */
3692
3693
  const paintThoughtRows = (block, hovered, collapsed = block.collapsed) => {
3694
+ if (block.kind === "command") {
3695
+ // #204: the Allow prompt's command — wrapped under its own indent, long ones collapsed.
3696
+ const paint = (row) => (hovered ? hoverThought(row) : dim(row));
3697
+ return commandBlockRows(block.text, { width: commandWidth(), collapsed, maxRows: COMMAND_COLLAPSED_ROWS }).map(paint);
3698
+ }
3693
3699
  if (block.kind === "steps") {
3694
3700
  // Activity (look-ups, finished commands): dim, like a ✓ row; bright while hovered.
3695
3701
  const paint = (r) => (hovered ? hoverThought(r) : dim(r));
@@ -3710,6 +3716,10 @@ const paintThoughtRows = (block, hovered, collapsed = block.collapsed) => {
3710
3716
  return rows.map((r) => GUTTER + paint(r));
3711
3717
  };
3712
3718
 
3719
+ /** #204: rows of an Allow-prompt command shown before "click to expand", and the width they wrap at. */
3720
+ const COMMAND_COLLAPSED_ROWS = 8;
3721
+ const commandWidth = () => Math.max(30, (process.stdout.columns || 80) - 1);
3722
+
3713
3723
  /** Width available to a thought row: the screen, less the gutter it hangs in. */
3714
3724
  const thoughtWidth = () =>
3715
3725
  Math.max(24, (process.stdout.columns || 80) - GUTTER.length - 1);
@@ -4057,6 +4067,9 @@ function toggleThoughtBlock(block) {
4057
4067
  applyToggleShift(thoughtBlocks, block, newEnd);
4058
4068
  hoverCtl.reset(); // the rows moved under the pointer — re-resolve on the next report
4059
4069
  paintLiveTail();
4070
+ // #204: the Yes/No rows are in-place UI, not transcript — the repaint above wiped them, so the
4071
+ // open picker draws them again right under the (re-sized) command block.
4072
+ if (approvalActive) drawApprovalOptions(false);
4060
4073
  return true;
4061
4074
  }
4062
4075
 
@@ -10708,9 +10721,30 @@ function drawApprovalOptions(redraw) {
10708
10721
  }
10709
10722
  regionUi((redraw ? "\x1b[2A" : "") + "\x1b[K" + GUTTER + yes + "\n\x1b[K" + noRow + "\n");
10710
10723
  }
10724
+ /** #204: the command block of the open Yes/No prompt — Ctrl+O toggles it (a click does too). */
10725
+ let approvalCommandBlock = null;
10726
+ /**
10727
+ * Print "⚠ Allow running this command?" and the command (#204): every line indented, long lines
10728
+ * wrapped under that indent instead of at column 0, and a tall command collapsed to its first
10729
+ * rows with "click to expand". Registered as a clickable block only when it has two forms and
10730
+ * `toggle` is set (a list picker below cannot survive the repaint); otherwise shown whole.
10731
+ */
10732
+ function printApprovalCommand(shown, { toggle = true } = {}) {
10733
+ const canToggle = toggle && barPinned();
10734
+ const block = { kind: "command", from: 0, to: 0, text: shown, collapsed: canToggle };
10735
+ const painted = paintThoughtRows(block, false);
10736
+ process.stdout.write("\n" + yellow("⚠ Allow running this command?") + "\n" + painted.join("\n") + "\n");
10737
+ if (!canToggle || !blockCanToggle(block)) return null;
10738
+ block.to = transcript.dropped() + transcript.length() - 2;
10739
+ block.from = block.to - painted.length + 1;
10740
+ thoughtBlocks.push(block);
10741
+ if (thoughtBlocks.length > 200) thoughtBlocks = thoughtBlocks.slice(-200);
10742
+ return block;
10743
+ }
10711
10744
  function finishApproval(allow, timedOut = false) {
10712
10745
  if (!approvalActive) return;
10713
10746
  approvalActive = false;
10747
+ approvalCommandBlock = null;
10714
10748
  approvalDeadline = 0;
10715
10749
  // #324: on a full screen the two option rows SCROLLED the conversation up by two, and the one
10716
10750
  // result line below takes only one of them back — the content now ends a row above the region's
@@ -10734,6 +10768,8 @@ function onApprovalKey(key) {
10734
10768
  drawApprovalOptions(true);
10735
10769
  } else if (key.name === "return" || key.name === "enter") {
10736
10770
  finishApproval(approvalSel === 0);
10771
+ } else if (key.ctrl && key.name === "o" && approvalCommandBlock && thoughtBlocks.includes(approvalCommandBlock)) {
10772
+ toggleThoughtBlock(approvalCommandBlock); // #204: expand/collapse the long command
10737
10773
  }
10738
10774
  // Ctrl+C is delivered via readline "SIGINT" (onInterrupt), which also denies — see there.
10739
10775
  }
@@ -10900,10 +10936,8 @@ async function approvalPrompt(command) {
10900
10936
  // the bar shows it. Risky commands (sudo, rm -rf, denylist) keep the plain Yes/No: a blanket
10901
10937
  // "yes" must never cover those.
10902
10938
  if (process.stdin.isTTY && editMode === "manual" && why.startsWith("accept edits is off")) {
10903
- process.stdout.write(
10904
- "\n" + yellow("⚠ Allow running this command?") + "\n" + indentBlock(shown, { paint: dim }) + "\n" +
10905
- indentBlock(why, { paint: dim }) + "\n"
10906
- );
10939
+ printApprovalCommand(shown, { toggle: false }); // a list picker follows — shown whole, wrapped (#204)
10940
+ process.stdout.write(indentBlock(why, { paint: dim }) + "\n");
10907
10941
  const idx = await pickFromList(
10908
10942
  ["Yes", "Yes for all later ones (turns accept edits on)", "No"],
10909
10943
  0,
@@ -10921,10 +10955,8 @@ async function approvalPrompt(command) {
10921
10955
  resolve(false);
10922
10956
  return;
10923
10957
  }
10924
- process.stdout.write(
10925
- "\n" + yellow("⚠ Allow running this command?") + "\n" + indentBlock(shown, { paint: dim }) + "\n" +
10926
- (why ? indentBlock(why, { paint: dim }) + "\n" : "")
10927
- );
10958
+ approvalCommandBlock = printApprovalCommand(shown);
10959
+ if (why) process.stdout.write(indentBlock(why, { paint: dim }) + "\n");
10928
10960
  approvalSel = 0;
10929
10961
  approvalResolve = resolve;
10930
10962
  approvalActive = true;
@@ -14710,6 +14742,21 @@ async function main() {
14710
14742
  await runClearLogs();
14711
14743
  continue;
14712
14744
  }
14745
+ if (line === "/budget") {
14746
+ // #205: the short terminal version of web-v2's /providers budgets. The server judges Pro,
14747
+ // the account email and "has items" (api/src/providers/terminalBudget.ts).
14748
+ try {
14749
+ const bv = await import("./budget-view.mjs");
14750
+ const ct = await import("./cli-token.mjs");
14751
+ const result = await bv.fetchProvidersBudget({ apiBase, workerKey });
14752
+ const out = bv.budgetLines(result, { site: ct.siteUrl() });
14753
+ for (const l of out.lines) console.log(GUTTER + (out.tone === "ok" ? l : dim(l)));
14754
+ console.log("");
14755
+ } catch (e) {
14756
+ console.log(GUTTER + dim(`Could not show your budgets: ${e instanceof Error ? e.message : e}\n`));
14757
+ }
14758
+ continue;
14759
+ }
14713
14760
  if (line === "/tokens") {
14714
14761
  // Task #142: WHERE the last request's prompt went. The bar answers "how much is RAG";
14715
14762
  // this answers "and what displaced it", which is the part that tells you whether RAG is
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiens.nguyen/gu-cli",
3
- "version": "1.0.851",
3
+ "version": "1.0.853",
4
4
  "description": "Gu CLI — the gu terminal plus the local worker that runs agent / OCR / PDF / embedding jobs on your Mac (Ollama / MLX / OpenAI-compatible).",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -70,6 +70,7 @@
70
70
  "version-check.mjs",
71
71
  "rag-selftest.mjs",
72
72
  "cli-token.mjs",
73
+ "budget-view.mjs",
73
74
  "credential-recovery.mjs",
74
75
  "settings-transfer.mjs",
75
76
  "presets-transfer.mjs",
@@ -3250,3 +3250,59 @@ export function indentBlock(text, { indent = " ", paint = (s) => s } = {}) {
3250
3250
  while (lines.length > 1 && lines[lines.length - 1].trim() === "") lines.pop();
3251
3251
  return lines.map((l) => paint(indent + l)).join("\n");
3252
3252
  }
3253
+
3254
+ /**
3255
+ * ONE LONG LINE, WRAPPED WITH A HANGING INDENT (#204). The terminal soft-wraps a long command
3256
+ * line back to COLUMN 0, under the gutter — in the Allow prompt a `subprocess.run([...` or a
3257
+ * `curl … | grep` line broke out of the indented block and read as separate text. Each row is
3258
+ * cut to `width` here instead, and every continuation row starts under the line's own indent
3259
+ * plus `hang`, so the block's left edge stays straight. Prefers a break at a space in the back
3260
+ * half of the row; a long token (a URL) is cut hard.
3261
+ */
3262
+ export function wrapIndented(line, { width = 80, indent = " ", hang = " " } = {}) {
3263
+ const s = String(line ?? "");
3264
+ const lead = /^\s*/.exec(s)[0];
3265
+ const body = s.slice(lead.length);
3266
+ const first = indent + lead;
3267
+ const cont = indent + lead + hang;
3268
+ const w = Math.max(visibleLen(cont) + 8, width);
3269
+ const rows = [];
3270
+ let prefix = first;
3271
+ let chars = [...body];
3272
+ if (!chars.length) return [first];
3273
+ while (chars.length) {
3274
+ const room = w - visibleLen(prefix);
3275
+ let take = 0;
3276
+ let used = 0;
3277
+ while (take < chars.length && used + visibleLen(chars[take]) <= room) {
3278
+ used += visibleLen(chars[take]);
3279
+ take++;
3280
+ }
3281
+ if (take < chars.length) {
3282
+ const sp = chars.slice(0, take).lastIndexOf(" ");
3283
+ if (sp >= Math.floor(take / 2)) take = sp + 1;
3284
+ }
3285
+ rows.push(prefix + chars.slice(0, take).join("").replace(/\s+$/, ""));
3286
+ chars = chars.slice(take);
3287
+ while (chars.length && chars[0] === " ") chars.shift();
3288
+ prefix = cont;
3289
+ }
3290
+ return rows;
3291
+ }
3292
+
3293
+ /**
3294
+ * The rows of the Allow prompt's command (#204): every line indented, long lines wrapped under
3295
+ * that indent (wrapIndented), and a command taller than `maxRows` COLLAPSED to its first rows
3296
+ * plus "… +N more rows — click to expand". Expanded, it ends with "(click to collapse)". A block
3297
+ * that fits (or would hide a single row) has one form only and no affordance — a "click to
3298
+ * expand" with nothing behind it is a promise the block cannot keep. Plain text, no ANSI.
3299
+ */
3300
+ export function commandBlockRows(text, { width = 80, indent = " ", collapsed = true, maxRows = 8 } = {}) {
3301
+ const lines = String(text ?? "").split(/\r\n|\r|\n/);
3302
+ while (lines.length > 1 && lines[lines.length - 1].trim() === "") lines.pop();
3303
+ const rows = lines.flatMap((l) => wrapIndented(l, { width, indent }));
3304
+ if (rows.length <= maxRows + 1) return rows;
3305
+ if (!collapsed) return [...rows, clipVisible(indent + "(click to collapse · ctrl+o)", width)];
3306
+ const hidden = rows.length - maxRows;
3307
+ return [...rows.slice(0, maxRows), clipVisible(indent + `… +${hidden} more rows — click to expand (ctrl+o)`, width)];
3308
+ }