@tiens.nguyen/gu-cli 1.0.850 → 1.0.852

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,
@@ -9562,6 +9562,9 @@ _SHELLS_KEEP = 20 # newest records kept, running or not
9562
9562
  _SHELLS_KEEP_DONE_S = 86400 # a finished shell is listed for a day
9563
9563
 
9564
9564
 
9565
+ _FG_SHELL_AFTER_S = 4 # a foreground command shows up as a shell after this many seconds (#407)
9566
+
9567
+
9565
9568
  def _shells_path() -> str:
9566
9569
  import os
9567
9570
  base = os.path.join(os.path.expanduser("~"), ".gonext")
@@ -9612,12 +9615,12 @@ def _shell_exit_code(s: dict):
9612
9615
  return (None, None)
9613
9616
 
9614
9617
 
9615
- def _shells_add_new(rec: dict) -> None:
9616
- """Append one record to shells.json under an exclusive lock, RE-READING the file inside the
9617
- lock so two overlapping turns do not overwrite each other's record (#387). _to_background used
9618
- to _shells_load() OUTSIDE any lock then _shells_save() the grown list — a concurrent reader's
9619
- own save in between silently dropped this record, and the repl's "N shells running (click)"
9620
- link disappeared for a live background task."""
9618
+ def _shells_edit(mutate) -> None:
9619
+ """Rewrite shells.json under an exclusive lock, RE-READING the file inside the lock so two
9620
+ overlapping turns do not overwrite each other's change (#387). `mutate(shells) -> shells`.
9621
+ _to_background used to _shells_load() OUTSIDE any lock then _shells_save() the grown list — a
9622
+ concurrent reader's own save in between silently dropped the record, and the repl's "N shells
9623
+ running (click)" link disappeared for a live background task."""
9621
9624
  import fcntl # macOS/Linux posix lock; the workspace here is the user's Mac
9622
9625
  import json as _json
9623
9626
  import os
@@ -9633,7 +9636,7 @@ def _shells_add_new(rec: dict) -> None:
9633
9636
  except Exception: # noqa: BLE001
9634
9637
  shells = []
9635
9638
  shells = [s for s in shells if isinstance(s, dict) and s.get("pid")]
9636
- shells.append(rec)
9639
+ shells = mutate(shells)
9637
9640
  # Same prune policy as _shells_save so the file stays bounded.
9638
9641
  now = _t.time()
9639
9642
  kept = []
@@ -9655,9 +9658,21 @@ def _shells_add_new(rec: dict) -> None:
9655
9658
  os.close(lock_fd)
9656
9659
  except OSError:
9657
9660
  pass
9661
+
9662
+
9663
+ def _shells_add_new(rec: dict) -> None:
9664
+ """Register one record. A record with the same pid is REPLACED, not duplicated (#407): a
9665
+ command shown early as a foreground shell becomes the background shell in place."""
9666
+ key = str(rec.get("id") or rec.get("pid")) # a real record's id is its pid
9667
+ _shells_edit(lambda shells: [s for s in shells if str(s.get("id") or s.get("pid")) != key] + [rec])
9658
9668
  _log(f"shells.json +1 → pid {rec.get('pid')} registered (#387)")
9659
9669
 
9660
9670
 
9671
+ def _shells_drop(pid) -> None:
9672
+ """Remove a record — a foreground command that finished inline (its result went to the model)."""
9673
+ _shells_edit(lambda shells: [s for s in shells if str(s.get("id") or s.get("pid")) != str(pid)])
9674
+
9675
+
9661
9676
  def _shell_state(s: dict, alive=None, now=None) -> dict:
9662
9677
  """{state, code, runtime, ended} for a shell record. state: running | exited (0) | failed |
9663
9678
  killed | ended (gone, exit code unknown). `alive` is injectable so tests need no process."""
@@ -9668,7 +9683,8 @@ def _shell_state(s: dict, alive=None, now=None) -> dict:
9668
9683
  if alive is None:
9669
9684
  alive = code is None and bool(_ws_record_pids(s))
9670
9685
  if alive and code is None and not s.get("killed"):
9671
- return {"state": "running", "code": None, "runtime": max(0.0, now - started), "ended": now}
9686
+ return {"state": "running", "code": None, "runtime": max(0.0, now - started), "ended": now,
9687
+ "foreground": bool(s.get("foreground"))}
9672
9688
  ended = float(s.get("ended") or code_at or now)
9673
9689
  if s.get("killed"):
9674
9690
  state = "killed"
@@ -9690,7 +9706,7 @@ def _fmt_runtime(seconds: float) -> str:
9690
9706
 
9691
9707
  def _shell_status_text(st: dict) -> str:
9692
9708
  if st["state"] == "running":
9693
- return "running"
9709
+ return "running (foreground, still waiting)" if st.get("foreground") else "running"
9694
9710
  if st["state"] in ("exited", "failed"):
9695
9711
  return f"exited {st['code']}"
9696
9712
  # WHO STOPPED IT (#362/#143). A bare "killed" read as a crash — "shell got status killed why?"
@@ -15670,6 +15686,7 @@ def run_agent_chat(cfg):
15670
15686
  # the toggle off raises the bar to every command. Off is the cautious setting,
15671
15687
  # so it may only ever add questions — never remove one.
15672
15688
  if not _ask_reason and not _accept_edits:
15689
+ # gu-repl.mjs approvalPrompt matches this prefix to offer "Yes for all later ones" (#200)
15673
15690
  _ask_reason = "accept edits is off, so every command is confirmed first"
15674
15691
  # ELEVATION: find out what we are ALLOWED to do before asking, so the question
15675
15692
  # states it. "this needs root and sudo needs a password we cannot type" is a
@@ -15783,15 +15800,27 @@ def run_agent_chat(cfg):
15783
15800
  )
15784
15801
  _INFLIGHT_CMDS.add(proc.pid) # killed with the agent until it is classified
15785
15802
  start = _t.time()
15786
-
15787
- def _to_background(why: str) -> str:
15788
- """Leave the command running as a background shell; say so to the model."""
15789
- _shells_add_new({
15803
+ # SHOWN EARLY (#407, GitHub #198): a command that runs past _FG_SHELL_AFTER_S is
15804
+ # listed as a shell (foreground: true) so the header and /shells show what the
15805
+ # user is waiting for, instead of nothing until the timeout hands it off.
15806
+ # shown = record written; bg = _to_background took over (keep the record).
15807
+ _fg = {"shown": False, "bg": False}
15808
+
15809
+ def _fg_record(foreground: bool = False) -> dict:
15810
+ rec = {
15790
15811
  "id": str(proc.pid), "pid": proc.pid, "pgid": proc.pid,
15791
15812
  "command": command, "workdir": wd, "log": log_path,
15792
15813
  "exit_file": exit_path if _use_shell else "",
15793
15814
  "started": start, "started_at": _t.strftime("%Y-%m-%d %H:%M:%S"),
15794
- })
15815
+ }
15816
+ if foreground:
15817
+ rec["foreground"] = True
15818
+ return rec
15819
+
15820
+ def _to_background(why: str) -> str:
15821
+ """Leave the command running as a background shell; say so to the model."""
15822
+ _fg["bg"] = True # same pid → replaces the early foreground record, no duplicate
15823
+ _shells_add_new(_fg_record())
15795
15824
  _emit({"type": "step", "text":
15796
15825
  f"Running in background → {_trim_words(command)} (shell {proc.pid})"})
15797
15826
  tail = _ws_distill_output(_read_log())
@@ -15941,6 +15970,12 @@ def run_agent_chat(cfg):
15941
15970
  + (f"\nStartup output:\n{tail}" if tail.strip() else ""))
15942
15971
  _last_obs["text"] = result
15943
15972
  return result
15973
+ if not _fg["shown"] and _t.time() - start >= _FG_SHELL_AFTER_S:
15974
+ _fg["shown"] = True
15975
+ try:
15976
+ _shells_add_new(_fg_record(foreground=True))
15977
+ except Exception as _ex: # noqa: BLE001 — a display aid must never fail the run
15978
+ _log(f"foreground shell record failed: {_ex}")
15944
15979
  # A job sent to the background on purpose, once it has had its 3s to show
15945
15980
  # it is neither a server nor an app.
15946
15981
  if background and _t.time() - start >= 3:
@@ -15964,6 +15999,13 @@ def run_agent_chat(cfg):
15964
15999
  # (tracked in the servers file for stop_server): no longer in flight either way.
15965
16000
  if proc is not None:
15966
16001
  _INFLIGHT_CMDS.discard(proc.pid)
16002
+ # It finished inline (result went to the model) or became a server/app (tracked
16003
+ # in servers.json): the early foreground record has done its job (#407).
16004
+ if _fg["shown"] and not _fg["bg"]:
16005
+ try:
16006
+ _shells_drop(proc.pid)
16007
+ except Exception as _ex: # noqa: BLE001
16008
+ _log(f"foreground shell drop failed: {_ex}")
15967
16009
  try:
15968
16010
  log_fh.close()
15969
16011
  except Exception: # noqa: BLE001
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 {
@@ -200,6 +200,8 @@ import {
200
200
  viewportRowsForLines,
201
201
  dragReduce,
202
202
  dragEventKind,
203
+ dragEdgeDirection,
204
+ shiftDragAnchor,
203
205
  selectionText,
204
206
  isEmptySelection,
205
207
  selectionCoversLines,
@@ -963,6 +965,7 @@ const COMMANDS = [
963
965
  { name: "/doctor", desc: "check every configured model ANSWERS — especially the embedder, which a turn only reaches after several steps" },
964
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" },
965
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" },
966
969
  { name: "/tokens", desc: "break down the last prompt sent to the coding model — how much of it was RAG" },
967
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" },
968
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" },
@@ -1450,10 +1453,15 @@ function applyMouseReport(report) {
1450
1453
  if (scrolledBack()) renderScrollback();
1451
1454
  else paintLiveTail();
1452
1455
  paintBar();
1456
+ // GH #201 — AUTOSCROLL. A pointer on the top/bottom row keeps scrolling the view so
1457
+ // the selection can grow past what fits on screen; it repeats on a timer because
1458
+ // an any-motion report only arrives when the pointer MOVES, not while it is held.
1459
+ startDragAutoscroll(dragEdgeDirection(Number(rowStr), transcriptRows()));
1453
1460
  }
1454
1461
  return; // mid-drag: hover must not also fire on this motion
1455
1462
  }
1456
1463
  if (act) { // the button came up: commit or cancel
1464
+ stopDragAutoscroll();
1457
1465
  const had = liveSelection;
1458
1466
  liveSelection = null;
1459
1467
  // Repaint only if a highlight was on screen — through the painter that owns the view
@@ -3390,6 +3398,36 @@ const screenRows = () => {
3390
3398
  const pad = currentPad(rows.length);
3391
3399
  return applySelectionHighlight(pad ? [...rows, ...Array(pad).fill("")] : rows, liveSelection);
3392
3400
  };
3401
+ // GH #201 — autoscroll while dragging a selection against the top/bottom edge.
3402
+ const DRAG_SCROLL_LINES = 2;
3403
+ const DRAG_SCROLL_MS = 80;
3404
+ let dragEdgeDir = 0;
3405
+ let dragEdgeTimer = null;
3406
+ function stopDragAutoscroll() {
3407
+ dragEdgeDir = 0;
3408
+ if (dragEdgeTimer) { clearInterval(dragEdgeTimer); dragEdgeTimer = null; }
3409
+ }
3410
+ function dragAutoscrollStep() {
3411
+ if (!dragState || !dragState.moved || !dragEdgeDir || !barPinned()) { stopDragAutoscroll(); return; }
3412
+ const before = scrollOffset;
3413
+ scrollView(dragEdgeDir * DRAG_SCROLL_LINES);
3414
+ const d = scrollOffset - before;
3415
+ if (!d) return; // already at the first line / the live tail
3416
+ // The view moved d lines: keep the anchor on the text it was on, then re-aim the highlight.
3417
+ dragState = shiftDragAnchor(dragState, d);
3418
+ liveSelection = toAbsoluteSelection({ start: dragState.anchor, end: dragState.focus });
3419
+ if (scrolledBack()) renderScrollback();
3420
+ else paintLiveTail();
3421
+ paintBar();
3422
+ }
3423
+ function startDragAutoscroll(dir) {
3424
+ if (!dir) { stopDragAutoscroll(); return; }
3425
+ dragEdgeDir = dir;
3426
+ if (!dragEdgeTimer) {
3427
+ dragEdgeTimer = setInterval(dragAutoscrollStep, DRAG_SCROLL_MS);
3428
+ dragEdgeTimer.unref?.();
3429
+ }
3430
+ }
3393
3431
  /**
3394
3432
  * Abandon any drag in progress and take its highlight off screen (task #177).
3395
3433
  *
@@ -3404,6 +3442,7 @@ const screenRows = () => {
3404
3442
  * painting per resize event is the mistake suspendClickForResize exists to avoid.
3405
3443
  */
3406
3444
  function endDrag({ repaint = true } = {}) {
3445
+ stopDragAutoscroll();
3407
3446
  dragState = null;
3408
3447
  const hadInput = inputSelection !== null;
3409
3448
  const hadLive = liveSelection !== null;
@@ -3652,6 +3691,11 @@ const hoverCtl = createHoverController({
3652
3691
  * that is the one place they are told apart.
3653
3692
  */
3654
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
+ }
3655
3699
  if (block.kind === "steps") {
3656
3700
  // Activity (look-ups, finished commands): dim, like a ✓ row; bright while hovered.
3657
3701
  const paint = (r) => (hovered ? hoverThought(r) : dim(r));
@@ -3672,6 +3716,10 @@ const paintThoughtRows = (block, hovered, collapsed = block.collapsed) => {
3672
3716
  return rows.map((r) => GUTTER + paint(r));
3673
3717
  };
3674
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
+
3675
3723
  /** Width available to a thought row: the screen, less the gutter it hangs in. */
3676
3724
  const thoughtWidth = () =>
3677
3725
  Math.max(24, (process.stdout.columns || 80) - GUTTER.length - 1);
@@ -4019,6 +4067,9 @@ function toggleThoughtBlock(block) {
4019
4067
  applyToggleShift(thoughtBlocks, block, newEnd);
4020
4068
  hoverCtl.reset(); // the rows moved under the pointer — re-resolve on the next report
4021
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);
4022
4073
  return true;
4023
4074
  }
4024
4075
 
@@ -10670,9 +10721,30 @@ function drawApprovalOptions(redraw) {
10670
10721
  }
10671
10722
  regionUi((redraw ? "\x1b[2A" : "") + "\x1b[K" + GUTTER + yes + "\n\x1b[K" + noRow + "\n");
10672
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
+ }
10673
10744
  function finishApproval(allow, timedOut = false) {
10674
10745
  if (!approvalActive) return;
10675
10746
  approvalActive = false;
10747
+ approvalCommandBlock = null;
10676
10748
  approvalDeadline = 0;
10677
10749
  // #324: on a full screen the two option rows SCROLLED the conversation up by two, and the one
10678
10750
  // result line below takes only one of them back — the content now ends a row above the region's
@@ -10696,6 +10768,8 @@ function onApprovalKey(key) {
10696
10768
  drawApprovalOptions(true);
10697
10769
  } else if (key.name === "return" || key.name === "enter") {
10698
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
10699
10773
  }
10700
10774
  // Ctrl+C is delivered via readline "SIGINT" (onInterrupt), which also denies — see there.
10701
10775
  }
@@ -10855,16 +10929,34 @@ async function approvalPrompt(command) {
10855
10929
  const tab = command.indexOf("\t");
10856
10930
  const shown = tab < 0 ? command : command.slice(0, tab);
10857
10931
  const why = tab < 0 ? "" : command.slice(tab + 1).trim();
10932
+ // GH #200 — "Yes for all later ones". ONLY for the soft question the agent asks because the
10933
+ // accept-edits switch is off (the reason text comes from gonext_agent_chat.py: "accept edits
10934
+ // is off, so every command is confirmed first"). That choice flips the switch back on, through
10935
+ // the same path Shift+Tab uses, so the running agent re-reads it before its next command and
10936
+ // the bar shows it. Risky commands (sudo, rm -rf, denylist) keep the plain Yes/No: a blanket
10937
+ // "yes" must never cover those.
10938
+ if (process.stdin.isTTY && editMode === "manual" && why.startsWith("accept edits is off")) {
10939
+ printApprovalCommand(shown, { toggle: false }); // a list picker follows — shown whole, wrapped (#204)
10940
+ process.stdout.write(indentBlock(why, { paint: dim }) + "\n");
10941
+ const idx = await pickFromList(
10942
+ ["Yes", "Yes for all later ones (turns accept edits on)", "No"],
10943
+ 0,
10944
+ { timeoutMs: 170000, timeoutIndex: 2 }
10945
+ );
10946
+ if (idx === 1 && editMode === "manual") {
10947
+ switchEditMode();
10948
+ process.stdout.write(dim(" (won't ask for later commands — shift+tab to go back to manual)\n"));
10949
+ }
10950
+ return { allow: idx === 0 || idx === 1, dontAsk: false };
10951
+ }
10858
10952
  const allow = await new Promise((resolve) => {
10859
10953
  if (!process.stdin.isTTY) {
10860
10954
  process.stdout.write("\n" + GUTTER + dim(`(approval needed for: ${shown}${why ? ` — ${why}` : ""} — no interactive terminal, skipping)`) + "\n");
10861
10955
  resolve(false);
10862
10956
  return;
10863
10957
  }
10864
- process.stdout.write(
10865
- "\n" + yellow("⚠ Allow running this command?") + "\n" + indentBlock(shown, { paint: dim }) + "\n" +
10866
- (why ? indentBlock(why, { paint: dim }) + "\n" : "")
10867
- );
10958
+ approvalCommandBlock = printApprovalCommand(shown);
10959
+ if (why) process.stdout.write(indentBlock(why, { paint: dim }) + "\n");
10868
10960
  approvalSel = 0;
10869
10961
  approvalResolve = resolve;
10870
10962
  approvalActive = true;
@@ -14650,6 +14742,21 @@ async function main() {
14650
14742
  await runClearLogs();
14651
14743
  continue;
14652
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
+ }
14653
14760
  if (line === "/tokens") {
14654
14761
  // Task #142: WHERE the last request's prompt went. The bar answers "how much is RAG";
14655
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.850",
3
+ "version": "1.0.852",
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",
package/shell-details.mjs CHANGED
@@ -92,7 +92,7 @@ export function shellState(rec, { alive, exit, now = Date.now() / 1000 } = {}) {
92
92
  const started = rec?.started != null ? Number(rec.started) : now;
93
93
  const ex = exit === undefined ? readExit(rec) : exit;
94
94
  const live = alive === undefined ? !ex && isAlive(rec) : alive;
95
- if (live && !ex && !rec?.killed) return { state: "running", code: null, runtime: Math.max(0, now - started), ended: now };
95
+ if (live && !ex && !rec?.killed) return { state: "running", code: null, runtime: Math.max(0, now - started), ended: now, foreground: Boolean(rec?.foreground) };
96
96
  const ended = Number(rec?.ended) || ex?.at || now;
97
97
  const state = rec?.killed ? "killed" : !ex ? "ended" : ex.code === 0 ? "exited" : "failed";
98
98
  return { state, code: ex ? ex.code : null, runtime: Math.max(0, ended - started), ended, by: String(rec?.killed_by ?? "") };
@@ -109,7 +109,7 @@ export function fmtRuntime(seconds) {
109
109
  }
110
110
 
111
111
  export function statusText(st) {
112
- if (st.state === "running") return "running";
112
+ if (st.state === "running") return st.foreground ? "running (foreground, still waiting)" : "running";
113
113
  if (st.state === "exited" || st.state === "failed") return `exited ${st.code}`;
114
114
  // Who stopped it (#362/#143): a bare "killed" read as a crash when the agent had stopped its own
115
115
  // search on purpose.
@@ -333,7 +333,9 @@ export async function killShell(rec, { path = shellsPath(), platform = process.p
333
333
  export function shellsToRecap(entries, { cwd = process.cwd(), since = 0 } = {}) {
334
334
  const under = sameProject(cwd);
335
335
  return entries
336
- .filter(({ rec, st }) => st.state !== "running" && st.state !== "killed" && !rec.seen && !rec.announced
336
+ // A foreground record (#407) is a command the agent is still waiting on inline — its result goes
337
+ // to the model; if the worker died mid-wait the leftover is not "a shell that finished".
338
+ .filter(({ rec, st }) => st.state !== "running" && st.state !== "killed" && !rec.foreground && !rec.seen && !rec.announced
337
339
  && st.ended >= since && under(rec.workdir))
338
340
  .map((e) => e.rec);
339
341
  }
@@ -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
+ }
@@ -589,6 +589,32 @@ export function dragEventKind(btn, press) {
589
589
  return (b & 0b11) === 0 ? "press" : null;
590
590
  }
591
591
 
592
+ /**
593
+ * Which way a drag should auto-scroll (GH #201): +1 = back into history (pointer on the top
594
+ * row or above it), -1 = toward the live tail (pointer on the last transcript row or below it),
595
+ * 0 = inside the view. `row` is the 1-based viewport row, `height` the transcript rows shown.
596
+ * Rows are clamped by the terminal, so "on the edge row" has to count as "past it".
597
+ */
598
+ export function dragEdgeDirection(row, height) {
599
+ const r = Number(row) | 0;
600
+ const h = Math.max(1, Number(height) | 0);
601
+ if (h < 3) return 0; // too short to tell an edge from the middle
602
+ if (r <= 1) return 1;
603
+ if (r >= h) return -1;
604
+ return 0;
605
+ }
606
+
607
+ /**
608
+ * The drag state after the view scrolled by `delta` lines (positive = back into history).
609
+ * The anchor is in SCREEN rows, and content moves `delta` rows down the screen when the view
610
+ * goes back, so the anchor moves with it — it may leave the screen, which is the point: the
611
+ * absolute row it names is unchanged. Pure; null in, null out.
612
+ */
613
+ export function shiftDragAnchor(state, delta) {
614
+ if (!state || !delta) return state;
615
+ return { ...state, anchor: { row: state.anchor.row + delta, col: state.anchor.col } };
616
+ }
617
+
592
618
  // The selection's colours (task #178). THE LOGO'S COLOUR, as a BACKGROUND — not as text.
593
619
  //
594
620
  // 105 is bright magenta, the sixteen-colour palette's purple, following the accent from cyan to