@tiens.nguyen/gu-cli 1.0.921 → 1.0.922

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.
@@ -24,6 +24,7 @@ export function sleep(ms) {
24
24
  }
25
25
 
26
26
  export function forgetTab(tabId) {
27
+ frameScripts.delete(tabId);
27
28
  consoleBuf.delete(tabId);
28
29
  freshErrors.delete(tabId);
29
30
  dialogs.delete(tabId);
@@ -57,11 +58,103 @@ export function onCdpEvent(tabId, method, params, cdp) {
57
58
  }
58
59
  }
59
60
 
60
- /** The domains a freshly attached tab needs, for the events above. */
61
+ /** The domains a freshly attached tab needs, for the events above — and gu's frame on the tab (GH #512). */
61
62
  export async function enableDomains(cdp, tabId) {
62
63
  await cdp(tabId, "Runtime.enable");
63
64
  await cdp(tabId, "Page.enable");
64
65
  await cdp(tabId, "Log.enable").catch(() => {});
66
+ await showFrame(cdp, tabId);
67
+ }
68
+
69
+ // ── "gu is working here" (GH #512) ─────────────────────────────────────────────────────────
70
+ // Runs IN the page: a purple outline round the viewport and a tab at the top centre, so the person
71
+ // sees which tab gu drives (Claude's extension does the same). "on" draws it, "off" removes it,
72
+ // "hide"/"show" are for gu's own screenshots — the model must never see it, or try to click it.
73
+ // Like the cursor: shadow DOM, pointer-events:none (clicks, elementFromPoint and read look through it),
74
+ // DOM calls only (strict CSP / Trusted Types pages still show it), the highest z-index.
75
+ export const FRAME_LABEL = "gu is working here";
76
+ function guFrame(mode) {
77
+ try {
78
+ const d = document;
79
+ const ID = "__gu_frame";
80
+ let h = d.getElementById(ID);
81
+ if (mode === "off") {
82
+ if (h) h.remove();
83
+ return true;
84
+ }
85
+ if (mode === "hide" || mode === "show") {
86
+ if (h) h.style.visibility = mode === "hide" ? "hidden" : "visible";
87
+ return true;
88
+ }
89
+ const put = () => {
90
+ if (d.getElementById(ID)) return;
91
+ h = d.createElement("div");
92
+ h.id = ID;
93
+ h.style.cssText = "all:initial;position:fixed;inset:0;z-index:2147483646;pointer-events:none";
94
+ const root = h.attachShadow ? h.attachShadow({ mode: "closed" }) : h;
95
+ const ring = d.createElement("div");
96
+ ring.style.cssText = "position:fixed;inset:0;pointer-events:none;box-sizing:border-box;border:3px solid #7c3aed;" +
97
+ "box-shadow:inset 0 0 28px 4px rgba(124,58,237,.6);border-radius:2px";
98
+ const pill = d.createElement("div");
99
+ pill.style.cssText = "position:fixed;top:0;left:50%;transform:translateX(-50%);pointer-events:none;display:flex;align-items:center;gap:8px;" +
100
+ "background:#7c3aed;color:#fff;font:600 14px/1 -apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif;" +
101
+ "padding:9px 18px 10px;border-radius:0 0 10px 10px;box-shadow:0 3px 10px rgba(0,0,0,.3);white-space:nowrap;letter-spacing:.1px";
102
+ const mark = d.createElement("span");
103
+ mark.textContent = "gu";
104
+ mark.style.cssText = "background:#fff;color:#7c3aed;font:700 11px/1 -apple-system,system-ui,sans-serif;padding:3px 5px;border-radius:5px";
105
+ const text = d.createElement("span");
106
+ text.textContent = "is working here";
107
+ pill.append(mark, text);
108
+ root.append(ring, pill);
109
+ (d.documentElement || d.body).appendChild(h);
110
+ };
111
+ // At document start (a new page) there may be no <html> yet: draw as soon as there is.
112
+ if (d.documentElement) put();
113
+ else d.addEventListener("readystatechange", put, { once: true });
114
+ // Some single-page apps rebuild <html>'s children: put it back when it is taken out.
115
+ if (!d.__guFrameWatch && typeof MutationObserver === "function" && d.documentElement) {
116
+ d.__guFrameWatch = new MutationObserver(() => {
117
+ if (!d.getElementById(ID) && !d.__guFrameOff) put();
118
+ });
119
+ d.__guFrameWatch.observe(d.documentElement, { childList: true });
120
+ }
121
+ d.__guFrameOff = false;
122
+ return true;
123
+ } catch {
124
+ return false;
125
+ }
126
+ }
127
+ const frameScripts = new Map(); // tabId → the new-document script's id, so "off" can stop it
128
+
129
+ /** Draws the frame now and on every page the tab loads after. Never fails. */
130
+ export async function showFrame(cdp, tabId) {
131
+ try {
132
+ if (!frameScripts.has(tabId)) {
133
+ const r = await cdp(tabId, "Page.addScriptToEvaluateOnNewDocument", { source: `(${guFrame})("on")` });
134
+ if (r?.identifier) frameScripts.set(tabId, r.identifier);
135
+ }
136
+ await cdp(tabId, "Runtime.evaluate", { expression: `(${guFrame})("on")`, returnByValue: true });
137
+ } catch {
138
+ /* a chrome:// page or a closed tab: nothing to draw on */
139
+ }
140
+ }
141
+
142
+ /** Removes the frame (gu lets go of the tab). Call BEFORE detaching the debugger. Never fails. */
143
+ export async function hideFrame(cdp, tabId) {
144
+ const sid = frameScripts.get(tabId);
145
+ frameScripts.delete(tabId);
146
+ try {
147
+ if (sid) await cdp(tabId, "Page.removeScriptToEvaluateOnNewDocument", { identifier: sid });
148
+ await cdp(tabId, "Runtime.evaluate", { expression: `(document.__guFrameOff=true,(${guFrame})("off"))`, returnByValue: true });
149
+ } catch {
150
+ /* already gone */
151
+ }
152
+ }
153
+
154
+ /** For a screenshot: hide → shoot → show. */
155
+ async function frameVisible(host, tabId, on) {
156
+ if (!frameScripts.has(tabId)) return;
157
+ await host.cdp(tabId, "Runtime.evaluate", { expression: `(${guFrame})("${on ? "show" : "hide"}")`, returnByValue: true }).catch(() => {});
65
158
  }
66
159
 
67
160
  async function evaluate(host, tabId, expression) {
@@ -341,10 +434,17 @@ export async function runAction(cmd, host) {
341
434
  // #422: try the background tab first; only when that fails or stalls is the TAB (never the
342
435
  // window) brought forward, because some Chrome versions do not paint a hidden tab.
343
436
  const grab = () => host.cdp(id, "Page.captureScreenshot", { format: "jpeg", quality: 80 });
344
- let shot = await Promise.race([grab().catch(() => null), sleep(cmd.shot_wait_ms || 4000).then(() => null)]);
345
- if (!shot) {
346
- await host.activate(id);
347
- shot = await grab();
437
+ // GH #512: the model sees the page, not gu's own frame (it would try to read or click it).
438
+ await frameVisible(host, id, false);
439
+ let shot;
440
+ try {
441
+ shot = await Promise.race([grab().catch(() => null), sleep(cmd.shot_wait_ms || 4000).then(() => null)]);
442
+ if (!shot) {
443
+ await host.activate(id);
444
+ shot = await grab();
445
+ }
446
+ } finally {
447
+ await frameVisible(host, id, true);
348
448
  }
349
449
  const m = await host.cdp(id, "Page.getLayoutMetrics");
350
450
  const vp = m.cssVisualViewport || m.visualViewport || {};
@@ -10,7 +10,7 @@
10
10
  // other tabs are never read, captured or controlled. What each command does is in actions.js,
11
11
  // shared with gu's own Chrome window (browser-chrome.mjs).
12
12
 
13
- import { enableDomains, forgetTab, onCdpEvent, runAction } from "./actions.js";
13
+ import { enableDomains, forgetTab, hideFrame, onCdpEvent, runAction } from "./actions.js";
14
14
 
15
15
  const DEFAULT_PORT = 4127;
16
16
  const VERSION = chrome.runtime.getManifest().version;
@@ -166,6 +166,8 @@ async function unshare(tabId) {
166
166
  const s = await state();
167
167
  await saveState({ tabs: s.tabs.filter((t) => t !== tabId), shared: s.shared.filter((t) => t !== tabId), current: s.current === tabId ? null : s.current });
168
168
  await chrome.tabs.ungroup(tabId).catch(() => {});
169
+ // GH #512: the tab is the user's again — take gu's frame off it while the debugger can still reach it.
170
+ if (attached.has(tabId)) await hideFrame(cdp, tabId);
169
171
  if (attached.has(tabId)) await chrome.debugger.detach({ tabId }).catch(() => {});
170
172
  attached.delete(tabId);
171
173
  forgetTab(tabId);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "gu browser",
4
- "version": "1.0.9",
4
+ "version": "1.0.10",
5
5
  "description": "Lets the gu coding agent open, see and operate web pages in its own tabs (tab group \"gu\") with a real mouse and keyboard.",
6
6
  "minimum_chrome_version": "116",
7
7
  "icons": {
package/cli-token.mjs CHANGED
@@ -300,6 +300,9 @@ export async function promptForToken({
300
300
  // With `promoFirst` (the person chose "Free model" at the start) the row asks for the code, and says nothing of Pro.
301
301
  redeemPromo = null,
302
302
  promoFirst = false,
303
+ // GH #511: the code already typed in setup's start question. Tried once before asking; a code the service
304
+ // refuses is said, and the row then asks as it always did.
305
+ promoCode = "",
303
306
  }) {
304
307
  const quitLine = (lead) => lead + (onSupport ? "/support asks for help · " : "") + "/exit or Ctrl+C quits gu.";
305
308
  const accountUrl = `${String(site).replace(/^https?:\/\//, "")}/account`;
@@ -374,7 +377,15 @@ export async function promptForToken({
374
377
  if (!r.ok) log(`That token can't be used on this computer: ${r.reason}`, "warn");
375
378
  return r.ok;
376
379
  };
377
- const ask1 = () => ask(promoFirst && redeemPromo ? "Promo code: " : "Input token: ", { prefill: shown, hint, atomic: true, noCancel: required });
380
+ let preTyped = promoFirst && redeemPromo ? String(promoCode ?? "").trim() : "";
381
+ const ask1 = () => {
382
+ if (preTyped) {
383
+ const t = preTyped;
384
+ preTyped = "";
385
+ return t;
386
+ }
387
+ return ask(promoFirst && redeemPromo ? "Promo code: " : "Input token: ", { prefill: shown, hint, atomic: true, noCancel: required });
388
+ };
378
389
  // A promo code is short and has no "." — a token always has one (payload.signature).
379
390
  const looksLikeCode = (t) => Boolean(redeemPromo) && /^[A-Za-z0-9_-]{4,32}$/.test(t) && !t.includes(".");
380
391
  for (let round = 0; required ? round < maxRounds : round < 2; round++) {
@@ -51,6 +51,8 @@ import {
51
51
  parseProviderChoice,
52
52
  startMenu,
53
53
  parseStartChoice,
54
+ startEnterNumber,
55
+ promoCodeOf,
54
56
  keyProviderMenu,
55
57
  parseKeyProvider,
56
58
  } from "./model-setup-ui.mjs";
@@ -1550,25 +1552,37 @@ export async function runClientExpertSetup({
1550
1552
  // yet. Enter = their own / the shared Ollama, which is what Enter has always meant here. A key, a code
1551
1553
  // or a preset is HANDED to gu itself (the terminal those flows need does not exist yet).
1552
1554
  const presets = countSavedPresets();
1555
+ // GH #511: Enter = the promo code, unless an Ollama answers on THIS machine (then "My own model", as before).
1556
+ const ollamaHere = (await localOllamaDefault("", fetchOllamaTags).catch(() => "")) !== "";
1557
+ const enter = ollamaHere ? "own" : "free";
1553
1558
  console.log("");
1554
- const [title, ...rows] = startMenu({ presets });
1559
+ const [title, ...rows] = startMenu({ presets, enter });
1555
1560
  console.log(" " + bold(title));
1556
1561
  for (const r of rows) console.log(dim(" " + r));
1557
1562
  let start = null;
1558
1563
  for (let t = 0; t < 3 && !start; t++) {
1559
- start = parseStartChoice(await askStep(" choose [3]: "));
1564
+ start = parseStartChoice(await askStep(` choose [${startEnterNumber(enter)}]: `), { enter });
1560
1565
  if (start === "preset" && presets === 0) {
1561
1566
  console.log(dim(" No presets saved yet. Save one later with /save-preset — pick another for now."));
1562
1567
  start = null;
1563
1568
  }
1564
1569
  }
1565
- start = start ?? "own";
1570
+ start = start ?? (enter === "own" ? "own" : "later");
1566
1571
  if (start === "later" || start === "preset") {
1567
1572
  chosenModels = { skipped: true, keys: [], loadPreset: start === "preset" };
1568
1573
  throw new SkipModelQuestion();
1569
1574
  }
1570
1575
  if (start === "free") {
1571
- chosenModels = { skipped: true, keys: [], voucherAtStart: true };
1576
+ // GH #511: the code is asked HERE, in the same question, and handed to gu, which redeems it at once —
1577
+ // no second "Promo code:" once gu starts. Enter = type it later (gu asks then, as before).
1578
+ let code = "";
1579
+ for (let t = 0; t < 3 && !code; t++) {
1580
+ const raw = String((await askStep(" Promo code (Enter to type it later): ")) ?? "").trim();
1581
+ if (!raw || raw === SKIP_ALL) break;
1582
+ code = promoCodeOf(raw);
1583
+ if (!code) console.log(dim(" That doesn't look like a code (letters, numbers and dashes) — try again, or Enter for later."));
1584
+ }
1585
+ chosenModels = { skipped: true, keys: [], voucherAtStart: true, ...(code ? { voucherCode: code } : {}) };
1572
1586
  throw new SkipModelQuestion();
1573
1587
  }
1574
1588
  if (start === "key") {
@@ -1695,7 +1709,7 @@ export async function runClientExpertSetup({
1695
1709
  console.log(" " + cyan(addProvider ? `✓ ${addProvider.name || "Provider"} chosen` : voucherAtStart ? "✓ Promo code chosen" : "✓ Model setup skipped") + dim(addProvider
1696
1710
  ? (addProvider.key ? " — gu checks your key and lists its models as soon as it starts" : " — gu asks for its key and model as soon as it starts")
1697
1711
  : voucherAtStart
1698
- ? " — gu asks for your code as soon as it starts"
1712
+ ? (chosenModels?.voucherCode ? ` — ${chosenModels.voucherCode} is redeemed as soon as gu starts` : " — gu asks for your code as soon as it starts")
1699
1713
  : loadPreset
1700
1714
  ? " — the preset picker opens as soon as gu starts"
1701
1715
  : " — set them any time with /model (or /use-presets)"));
@@ -1748,5 +1762,5 @@ export async function runClientExpertSetup({
1748
1762
  );
1749
1763
  // #301: the caller opens /use-presets once the terminal exists — the picker, the plan and the
1750
1764
  // confirmation are that command's, not rebuilt here.
1751
- return { complete: true, stoppedAt: null, ...(loadPreset ? { loadPreset: true } : {}), ...(addProvider ? { addProvider } : {}), ...(voucherAtStart ? { voucherAtStart: true } : {}) };
1765
+ return { complete: true, stoppedAt: null, ...(loadPreset ? { loadPreset: true } : {}), ...(addProvider ? { addProvider } : {}), ...(voucherAtStart ? { voucherAtStart: true, ...(chosenModels?.voucherCode ? { voucherCode: chosenModels.voucherCode } : {}) } : {}) };
1752
1766
  }
@@ -233,8 +233,9 @@ export function embedNotice({ state, model } = {}) {
233
233
  * - no embed model → NOTHING until embedding was actually needed (`embedNeeded`: the agent tried
234
234
  * a RAG tool, or the user opened /embed-model), then the embed row.
235
235
  */
236
- export function setupNoticeRows({ noModel = false, agentMissing = false, embedMissing = false, embedNeeded = false, embedWhy } = {}) {
237
- if (noModel) return ["coding model not set · /model"];
236
+ export function setupNoticeRows({ noModel = false, agentMissing = false, embedMissing = false, embedNeeded = false, embedWhy, promoPending = false } = {}) {
237
+ // GH #511: a promo code chosen at setup is about to set the model — "not set" there reads as a fault.
238
+ if (noModel) return [promoPending ? "free model: your promo code sets it up" : "coding model not set · /model"];
238
239
  return [
239
240
  ...(embedMissing && embedNeeded ? [embedNotice(embedWhy) || "no embed model — RAG is off · /embed-model"] : []),
240
241
  ];
@@ -3626,6 +3626,10 @@ def _remember_shape(key: str, new_kw: dict, action: str) -> None:
3626
3626
  _AUX_USAGE: dict = {}
3627
3627
  _AUX_LOCK = threading.Lock()
3628
3628
 
3629
+ # GH #507: this turn's free-model budget (gu_free_budget.Budget, or None when the coder is not the free
3630
+ # model), whether the turn was paused for it, and the coder model whose token counters it reads.
3631
+ _FREE_TURN: dict = {"b": None, "hit": False, "model": None}
3632
+
3629
3633
 
3630
3634
  def _aux_text_len(messages) -> int:
3631
3635
  n = 0
@@ -13548,6 +13552,45 @@ def run_agent_chat(cfg):
13548
13552
  except Exception as e: # noqa: BLE001
13549
13553
  _log(f"shell-finished note skip: {e}")
13550
13554
 
13555
+ # GH #506: what the user typed while this turn runs reaches the model NOW, appended after
13556
+ # this step's result (the newest text — the cached prefix is untouched). Counts only in the log.
13557
+ try:
13558
+ if _job_id:
13559
+ import gu_turn_notes as _turn_notes
13560
+ _n = _turn_notes.add_to_step(step_log, _job_id)
13561
+ if _n:
13562
+ _emit({"type": "step", "text": f"Read your note{'s' if _n > 1 else ''} — taking {'them' if _n > 1 else 'it'} into account"})
13563
+ _log(f"step {step_num}: {_n} user note(s) added for the next step")
13564
+ except Exception as e: # noqa: BLE001
13565
+ _log(f"user note skip: {e}")
13566
+
13567
+ # GH #507: the free model's month, checked after EVERY step — not only at the turn's start.
13568
+ # When the next step would not fit, the agent stops HERE: this step is finished, the next
13569
+ # model call is never made. Amounts never reach the log (#497: no dollar amounts), only that.
13570
+ try:
13571
+ _fb_b = _FREE_TURN.get("b")
13572
+ if _fb_b is not None and not _FREE_TURN.get("hit") and not getattr(step_log, "is_final_answer", False):
13573
+ _fb_m = _FREE_TURN.get("model")
13574
+ _fb_in = int(getattr(_fb_m, "_code_tokens_total", 0) or 0)
13575
+ _fb_out = int(getattr(_fb_m, "_code_output_tokens_total", 0) or 0)
13576
+ _fb_cached = int(getattr(_fb_m, "_code_cached_tokens_total", 0) or 0)
13577
+ if not _fb_in and not _fb_out:
13578
+ # A coder without gu's counters: smolagents' per-step usage, summed (no cache figure,
13579
+ # so charged at the full input price — an estimate never undercharges).
13580
+ _tu = getattr(step_log, "token_usage", None)
13581
+ _fb_b.fallback_in += int(getattr(_tu, "input_tokens", 0) or 0)
13582
+ _fb_b.fallback_out += int(getattr(_tu, "output_tokens", 0) or 0)
13583
+ _fb_in, _fb_out = _fb_b.fallback_in, _fb_b.fallback_out
13584
+ with _AUX_LOCK:
13585
+ _fb_aux = [dict(v) for v in _AUX_USAGE.values()]
13586
+ if _fb_b.after_step(_fb_b.turn_spent(_fb_in, _fb_cached, _fb_cached > 0, _fb_out, _fb_aux)):
13587
+ _FREE_TURN["hit"] = True
13588
+ _emit({"type": "step", "text": "Pausing — this month's free-model allowance is used up"})
13589
+ _log(f"step {step_num}: free-model allowance would not cover the next step → pausing the turn")
13590
+ agent.interrupt()
13591
+ except Exception as e: # noqa: BLE001
13592
+ _log(f"free-model budget check skipped: {type(e).__name__}")
13593
+
13551
13594
  # Task #74: an executor-timeout error means whatever the step's tool call
13552
13595
  # achieved was NEVER reported to the model (a create_pdf may have finished —
13553
13596
  # or may still be finishing — in the background). Flag it so a repeat
@@ -14448,6 +14491,8 @@ def run_agent_chat(cfg):
14448
14491
  _emit({
14449
14492
  "type": "code_request",
14450
14493
  "step": self._call_index,
14494
+ # GH #509: the model this step is sent to (after any fallback, #343).
14495
+ "model": str(getattr(self, "model_id", "") or ""),
14451
14496
  # 0, explicitly, not absent: the model has not answered yet and the
14452
14497
  # page must be able to show a real zero rather than a blank that reads
14453
14498
  # like missing data.
@@ -14528,6 +14573,9 @@ def run_agent_chat(cfg):
14528
14573
  # from "your coding key is wrong". The key itself is never echoed.
14529
14574
  if _is_auth_failure(e) or _is_billing_failure(e):
14530
14575
  _host = _host_of(coding_base_url)
14576
+ if _is_billing_failure(e) and _FREE_TURN.get("b") is not None:
14577
+ import gu_free_budget as _fbm
14578
+ raise _AgentConfigError(_fbm.pause_message(out_of_credit=True)) from e
14531
14579
  if _is_billing_failure(e):
14532
14580
  # One line: WHO refused, WHY (their words, ids stripped), and
14533
14581
  # the ONE thing that fixes it. Nothing about attempts or
@@ -14803,6 +14851,8 @@ def run_agent_chat(cfg):
14803
14851
  _emit({
14804
14852
  "type": "code_response",
14805
14853
  "step": self._call_index,
14854
+ # GH #509: the model that answered this step — Flow 3D shows it per turn.
14855
+ "model": str(getattr(self, "model_id", "") or ""),
14806
14856
  "text": _raw if isinstance(_raw, str)
14807
14857
  else ("" if _raw is None else str(_raw)),
14808
14858
  "inputTokens": _in2,
@@ -15000,6 +15050,11 @@ def run_agent_chat(cfg):
15000
15050
  _log("no-code streak hit limit → ending the turn honestly "
15001
15051
  "instead of looping on a coder that won't emit code")
15002
15052
  _nocode_msg = _no_code_message(self.model_id)
15053
+ # GH #507: on a spent free-model month, empty replies are the limit talking.
15054
+ _fbx = _FREE_TURN.get("b")
15055
+ if _fbx is not None and _fbx.over:
15056
+ import gu_free_budget as _fbm
15057
+ _nocode_msg = _fbm.pause_message()
15003
15058
  msg.content = ("<code>\nfinal_answer("
15004
15059
  + repr(_nocode_msg) + ")\n</code>")
15005
15060
  self._no_code_streak = 0
@@ -17708,9 +17763,30 @@ def run_agent_chat(cfg):
17708
17763
  task_with_hint += ("\n\n(The user pasted " + ", ".join(l for l, _ in _turn_image_refs)
17709
17764
  + " but this coding model is not sent images — say so if the "
17710
17765
  "task needs them.)")
17766
+ # GH #507: what the free model's month has left for this turn (None: not the free model).
17767
+ try:
17768
+ import gu_free_budget as _fb_mod
17769
+ _FREE_TURN.update({"b": _fb_mod.load(coding_base_url, coding_model_id), "hit": False,
17770
+ "model": getattr(agent, "model", None)})
17771
+ if _FREE_TURN["b"] is not None:
17772
+ _log("free-model budget: checked after every step this turn")
17773
+ except Exception as e: # noqa: BLE001
17774
+ _FREE_TURN.update({"b": None, "hit": False, "model": None})
17775
+ _log(f"free-model budget not loaded: {type(e).__name__}")
17776
+
17777
+ def _run_or_pause(**kw):
17778
+ # agent.interrupt() (the budget check above) ends smolagents' run with an AgentError
17779
+ # at the top of the next step: that is a PAUSE, not a failure.
17780
+ try:
17781
+ return agent.run(task_with_hint, **kw)
17782
+ except Exception:
17783
+ if _FREE_TURN.get("hit"):
17784
+ return None
17785
+ raise
17786
+
17711
17787
  with contextlib.redirect_stdout(sys.stderr):
17712
- result = agent.run(task_with_hint, images=_turn_images or None)
17713
- while _maxsteps_partial.get("hit"):
17788
+ result = _run_or_pause(images=_turn_images or None)
17789
+ while _maxsteps_partial.get("hit") and not _FREE_TURN.get("hit"):
17714
17790
  if _always_extend:
17715
17791
  _log(f"max-steps reached → auto-extending to {_MAXSTEP_CEILING} "
17716
17792
  "(don't-ask-again session flag)")
@@ -17732,7 +17808,15 @@ def run_agent_chat(cfg):
17732
17808
  agent.max_steps = _MAXSTEP_CEILING
17733
17809
  _emit({"type": "step", "text": "Continuing — step budget extended…"})
17734
17810
  _log(f"continuing run with raised budget {agent.max_steps}")
17735
- result = agent.run(task_with_hint, reset=False)
17811
+ result = _run_or_pause(reset=False)
17812
+ if _FREE_TURN.get("hit"):
17813
+ # The answer IS the pause: what to do, then what ran (so "continue" has it in the history).
17814
+ _recap = _fallback_recap(_turn_steps, "").replace(
17815
+ "**Status:** the model finished without writing a summary.", "").strip()
17816
+ _recap = re.sub(r"\s*</?code>\s*", " ", re.sub(r"(?m)^- Thought:[^<\n]*", "- ", _recap)).strip()
17817
+ _recap = re.sub(r"(?m)^-\s+", "- ", _recap)
17818
+ result = _fb_mod.pause_message(_recap)
17819
+ agent.interrupt_switch = False
17736
17820
  # Final formatting — NO extra summarizer model call. In multi-step mode the
17737
17821
  # agent's own final_answer() (or the max-steps fallback above) already holds the
17738
17822
  # synthesized answer; we just strip the internal hint tags we appended to tool
package/gu-cli.mjs CHANGED
@@ -4660,6 +4660,8 @@ async function runAgentChatJob(job) {
4660
4660
  promptBreakdown:
4661
4661
  event.breakdown && typeof event.breakdown === "object" ? event.breakdown : undefined,
4662
4662
  codingUrl: payload?.codingBaseURL ?? "",
4663
+ // GH #509: which MODEL answered (the agent says; else the job's planned one).
4664
+ codingModel: (typeof event.model === "string" && event.model) || payload?.codingModelId || "",
4663
4665
  }),
4664
4666
  }).catch(() => {});
4665
4667
  } else if (event.type === "code_response" && typeof event.text === "string") {
@@ -4694,6 +4696,8 @@ async function runAgentChatJob(job) {
4694
4696
  ? event.promptBreakdown
4695
4697
  : undefined,
4696
4698
  codingUrl: payload?.codingBaseURL ?? "",
4699
+ // GH #509: which MODEL answered (the agent says; else the job's planned one).
4700
+ codingModel: (typeof event.model === "string" && event.model) || payload?.codingModelId || "",
4697
4701
  }),
4698
4702
  }).catch(() => {});
4699
4703
  } else if (event.type === "final" && typeof event.text === "string") {
package/gu-repl.mjs CHANGED
@@ -158,6 +158,7 @@ import { readSkillSource, sourceLabel, SKILL_SOURCE_KEY } from "./skill-source.m
158
158
  import { codingBannerLabel, isOllamaCloudUrl, SECRET_KEY_HINT } from "./coding-key-prompt.mjs";
159
159
  import { questionEchoText, thoughtPrintSeq, wrapDiffText } from "./terminal-layout.mjs";
160
160
  import { createTurnQueue, queuedNotice, typingNotice, droppedNote } from "./turn-queue.mjs"; // GH #429: questions typed during a turn wait here
161
+ import { sendNote, takeUnread, sweepOldNotes, sentNotice, SENT_NOTE } from "./turn-notes.mjs"; // GH #506: …or go to the running turn
161
162
  import { globalPrefixOf } from "./install-path.mjs";
162
163
  import { indentBlock, commandBlockRows, wrapIndented } from "./terminal-layout.mjs"; // every line of an Allow-prompt detail indented (#189); wrapped + collapsible command (#204)
163
164
  import { firstGuOnPath, pathGuMismatch, guOnPathIsCurrent, updateAttemptRecord, repeatUpdateNotice } from "./update-verify.mjs";
@@ -777,6 +778,8 @@ let openPresetsAtStart = false;
777
778
  let addProviderAtStart = null;
778
779
  // #490: setup's "Free model" — gu asks for the code once the terminal exists.
779
780
  let voucherAtStart = false;
781
+ // GH #511: the code typed in setup's start question — redeemed at once, never asked a second time.
782
+ let voucherCodeAtStart = "";
780
783
 
781
784
  // #220: a gu that STOPS ON AN ERROR says where help is — a start that failed (exit 1 before the
782
785
  // prompt: no key, API unreachable, MongoDB down…) or a crash. One dim line, never during a session
@@ -930,6 +933,7 @@ if (!workerKey || !apiBase) {
930
933
  if (setup.loadPreset) openPresetsAtStart = true;
931
934
  if (setup.addProvider) addProviderAtStart = setup.addProvider;
932
935
  if (setup.voucherAtStart) voucherAtStart = true;
936
+ if (setup.voucherCode) voucherCodeAtStart = setup.voucherCode;
933
937
  // STOP when setup cannot go further.
934
938
  //
935
939
  // This used to fall through to the hosted sign-in, on the theory that "this machine
@@ -1915,7 +1919,7 @@ let embedWhy = { state: "unset", model: "" };
1915
1919
  // until embedding is actually needed (`embedNeeded`).
1916
1920
  let embedNeeded = false;
1917
1921
  const missingNoticeRows = () =>
1918
- setupNoticeRows({ noModel: noModelAtAll, agentMissing, embedMissing, embedNeeded, embedWhy });
1922
+ setupNoticeRows({ noModel: noModelAtAll, agentMissing, embedMissing, embedNeeded, embedWhy, promoPending: voucherAtStart });
1919
1923
  async function refreshNoModelAtAll() {
1920
1924
  try {
1921
1925
  const refreshed = await fetchAgentPayload([{ role: "user", content: "." }]);
@@ -2157,6 +2161,7 @@ const _lineQueue = [];
2157
2161
  // GH #429: lines submitted WHILE A TURN RUNS wait here (FIFO); the main loop runs them one by one
2158
2162
  // after the turn. Kept apart from _lineQueue, which every failed turn empties on purpose (#92).
2159
2163
  const turnQueue = createTurnQueue();
2164
+ sweepOldNotes(); // GH #506: a crash can leave typed notes behind
2160
2165
  /** A turn that did not finish throws its queued questions away — say how many, once. */
2161
2166
  function dropQueuedQuestions() {
2162
2167
  const n = turnQueue.clear();
@@ -2204,6 +2209,15 @@ rl.on("line", (l) => {
2204
2209
  imageStore.clear();
2205
2210
  typedDuringTurn = false;
2206
2211
  turnTyping.reset();
2212
+ // GH #506: with a running job, the text goes to the agent's NEXT step (appended after the
2213
+ // current step's result — cache-safe). Not read by the end of the turn = the next question.
2214
+ if (queued && currentJobId && !cancelRequested && sendNote(currentJobId, queued)) {
2215
+ notesSent += 1;
2216
+ // Pinned: the input row says it (a line written mid-turn would break the zone, #321).
2217
+ if (barPinned()) paintBar();
2218
+ else process.stdout.write(dim(`\n ${SENT_NOTE}\n`));
2219
+ return;
2220
+ }
2207
2221
  if (queued) {
2208
2222
  if (turnQueue.push(queued)) {
2209
2223
  // No frozen row to carry the count (piped, or a window too short to pin one): say it here.
@@ -8966,6 +8980,8 @@ async function setUpFreeModel({ token, announce = false } = {}) {
8966
8980
  ? `✓ ${got.preset.model} is now your agent model and your coding model.`
8967
8981
  : `✓ ${agentM} is now your agent model and ${got.preset.model} your coding model.`) +
8968
8982
  dim(" Free use renews each month; /model switches back to your own."));
8983
+ // GH #511: say plainly that setup is over and what to do now — the one line a new person needs.
8984
+ console.log(GUTTER + bold("Ready — type your first question below and press Enter."));
8969
8985
  }
8970
8986
  return true;
8971
8987
  } catch (e) {
@@ -8990,7 +9006,10 @@ async function freeModelAtStart() {
8990
9006
  }
8991
9007
 
8992
9008
  /** After a turn on the free model: count it, say a notice once per level, tell the service. Never throws. */
8993
- async function noteFreeModelTurn(inputTokens, breakdown, outputTokens, coder, aux = null) {
9009
+ // GH #507: how the agent's pause answer starts (gu_free_budget.py PAUSE_HEAD).
9010
+ const ALLOWANCE_PAUSE_PREFIX = "Paused: this month's free-model allowance is used up";
9011
+
9012
+ async function noteFreeModelTurn(inputTokens, breakdown, outputTokens, coder, aux = null, paused = false) {
8994
9013
  try {
8995
9014
  const fm = await import("./free-model.mjs");
8996
9015
  if (!freeModel) return;
@@ -9005,6 +9024,7 @@ async function noteFreeModelTurn(inputTokens, breakdown, outputTokens, coder, au
9005
9024
  fm.writeState(freeModelDir(), freeModel);
9006
9025
  const n = fm.notice(freeModel, new Date(), coder?.url);
9007
9026
  const noticeKey = `${freeModel.period}:${fm.slotFor(freeModel, coder?.url).extra ?? "main"}:${n?.level}`;
9027
+ if (paused && n?.level === "over") freeModelNoticed = noticeKey;
9008
9028
  if (n?.text && freeModelNoticed !== noticeKey) {
9009
9029
  freeModelNoticed = noticeKey;
9010
9030
  console.log(GUTTER + (n.level === "ok" ? dim(n.text) : yellow(n.text)) + "\n");
@@ -11604,7 +11624,11 @@ const turnRowNotice = (width) =>
11604
11624
  ? cancelRequested
11605
11625
  ? visibleLen(SUPPORT_AFTER_STOP_NOTICE) + 12 <= width ? SUPPORT_AFTER_STOP_NOTICE : SUPPORT_AFTER_STOP_SHORT
11606
11626
  : visibleLen(SUPPORT_AFTER_TURN_NOTICE) + 12 <= width ? SUPPORT_AFTER_TURN_NOTICE : SUPPORT_AFTER_TURN_SHORT
11607
- : typedDuringTurn ? typingNotice(width) : queuedNotice(turnQueue.size, width);
11627
+ : typedDuringTurn
11628
+ ? typingNotice(width)
11629
+ : notesSent
11630
+ ? sentNotice(notesSent, width)
11631
+ : queuedNotice(turnQueue.size, width);
11608
11632
  // Is the turn we are following one this terminal STARTED, or another terminal's that we merely
11609
11633
  // attached to (task #211)? `attached` is local to runAgentTurn, and onInterrupt — which lives in
11610
11634
  // main() — had no way to ask. So Ctrl+C while watching somebody else's agent took the "cancel my
@@ -11612,6 +11636,7 @@ const turnRowNotice = (width) =>
11612
11636
  // non-destructive way back to your own prompt, which is the bug this flag exists to fix.
11613
11637
  let followingAttached = false;
11614
11638
  let followAborted = false;
11639
+ let notesSent = 0; // GH #506: notes handed to the running turn (the input row says so)
11615
11640
  let currentJobId = null; // the running turn's jobId — so Ctrl+C can cancel it server-side
11616
11641
  let cancelRequested = false; // a cancel POST has been sent for the current turn
11617
11642
  // Interactive command-approval gate: while the agent is paused on a risky command, the
@@ -12827,6 +12852,7 @@ async function askForCliTokenInner(ct, dir, why, overLimit = false, short = "")
12827
12852
  // A free-model promo code needs no token and no Pro plan: typed in this row, it gives the computer a token.
12828
12853
  redeemPromo: async (code) => ct.redeemPromo({ hostedBase, device: await ct.thisDevice({ instanceId: myInstanceId || "" }).catch(() => null), code }),
12829
12854
  promoFirst: voucherAtStart,
12855
+ promoCode: voucherAtStart ? voucherCodeAtStart : "", // GH #511: typed in setup — tried first, not asked again
12830
12856
  // #315: a token is only good if THIS computer may use it — renew it from here (the server then
12831
12857
  // says how much free time the computer has), save what came back, and run the licence rule.
12832
12858
  accept: async (token) => {
@@ -12856,6 +12882,7 @@ async function askForCliTokenInner(ct, dir, why, overLimit = false, short = "")
12856
12882
  if (r.ok && r.kind === "promo") {
12857
12883
  // The code was the answer to "Free model": set that model up now — the later "Voucher code" question is moot.
12858
12884
  voucherAtStart = false;
12885
+ voucherCodeAtStart = "";
12859
12886
  const st = await ct.readState(dir);
12860
12887
  await setUpFreeModel({ token: st.token, announce: true });
12861
12888
  console.log("");
@@ -14450,7 +14477,16 @@ async function runAgentTurn(history, { attachJobId = "", ownJob = false } = {})
14450
14477
  typedDuringTurn = false;
14451
14478
  turnTyping.reset();
14452
14479
  endCompactLock(); // issue #120: never leave the terminal locked after a turn
14480
+ // GH #506: notes the agent never read run next — unless the turn was stopped, which drops them.
14481
+ {
14482
+ const unread = takeUnread(currentJobId);
14483
+ if (unread.length) {
14484
+ if (cancelRequested || followAborted) console.log(GUTTER + dim(droppedNote(unread.length)));
14485
+ else turnQueue.unshiftAll(unread);
14486
+ }
14487
+ }
14453
14488
  currentJobId = null;
14489
+ notesSent = 0;
14454
14490
  // Drop anything typed (but not submitted) during the turn — echo was muted, so it's
14455
14491
  // invisible; without this it would surface on the next prompt.
14456
14492
  rl.line = "";
@@ -14610,6 +14646,7 @@ async function main() {
14610
14646
  if (setup?.loadPreset) openPresetsAtStart = true;
14611
14647
  if (setup?.addProvider) addProviderAtStart = setup.addProvider;
14612
14648
  if (setup?.voucherAtStart) voucherAtStart = true;
14649
+ if (setup?.voucherCode) voucherCodeAtStart = setup.voucherCode;
14613
14650
  }
14614
14651
  } catch {
14615
14652
  /* never block the REPL on the mode question — the banner still shows what is configured */
@@ -14916,7 +14953,10 @@ async function main() {
14916
14953
  // client used to print a constant here instead of the account's model, so the one row
14917
14954
  // that answers "which model am I using" named a value the user had never set and could
14918
14955
  // not change. See clientAgentProblem in daemon-control for what the override was for.
14919
- lbl("model") +
14956
+ // GH #511: NOTHING SET YET (a fresh install) — one plain row, not "same as the coding model" over "coder —".
14957
+ ...(nothingToAnswerWith(p)
14958
+ ? [lbl("model") + dim(voucherAtStart ? "not set yet — your promo code sets it up" : "not set yet — /model sets it up")]
14959
+ : [lbl("model") +
14920
14960
  (agentLabel.known ? agentModelText(agentLabel) : dim(agentModelText(agentLabel))),
14921
14961
  // Task #190: NOT `p.codingModelId || "—"`. While the API believes the coding key is
14922
14962
  // missing it omits codingModelId altogether, so that read printed "coder —" three
@@ -14932,7 +14972,7 @@ async function main() {
14932
14972
  sessionModel: sessionCodingModel,
14933
14973
  }),
14934
14974
  where: activeCoderWhere,
14935
- }),
14975
+ })]),
14936
14976
  lbl("RAG") +
14937
14977
  (p.ragEnabled
14938
14978
  ? ragStorageLabel(sessionRagStorage)
@@ -15537,8 +15577,10 @@ async function main() {
15537
15577
  // #490: setup's "Free model" — ask for the code now, then the same /voucher flow as typing it.
15538
15578
  if (voucherAtStart) {
15539
15579
  voucherAtStart = false;
15580
+ const typedInSetup = voucherCodeAtStart;
15581
+ voucherCodeAtStart = "";
15540
15582
  try {
15541
- const code = String(await ask(" Voucher code (Enter to skip, /voucher CODE later): ") ?? "").trim();
15583
+ const code = typedInSetup || String(await ask(" Voucher code (Enter to skip, /voucher CODE later): ") ?? "").trim();
15542
15584
  if (code) await runVoucherCommand(`/voucher ${code}`);
15543
15585
  else console.log(GUTTER + dim("No code yet — use /voucher CODE any time, or /model to pick your own."));
15544
15586
  } catch (e) {
@@ -16219,7 +16261,8 @@ async function main() {
16219
16261
  lastTurnTotalOutput = outputTokens ?? 0;
16220
16262
  // #323: what this turn's prompt tokens cost — on the token row and in /price.
16221
16263
  void noteTurnCost(lastTurnInputTokens, lastPromptBreakdown, turnCoder);
16222
- void noteFreeModelTurn(lastTurnInputTokens, lastPromptBreakdown, lastTurnOutputTokens, turnCoder, lastTurnAux);
16264
+ // GH #507: a turn the agent PAUSED for the allowance already said so — the "used up" notice would repeat it.
16265
+ void noteFreeModelTurn(lastTurnInputTokens, lastPromptBreakdown, lastTurnOutputTokens, turnCoder, lastTurnAux, String(answer ?? "").startsWith(ALLOWANCE_PAUSE_PREFIX));
16223
16266
  // A turn that FAILED carries the __TURN_FAILED__:: sentinel: the worker still delivers
16224
16267
  // the text (both UIs need to show it), but it is a failure notice, not a reply. Print
16225
16268
  // it as one and DROP it — persisting it would re-send "⚠️ your account is suspended" to
@@ -0,0 +1,165 @@
1
+ """THE FREE MODEL'S MONTH, CHECKED BETWEEN STEPS (GH #507).
2
+
3
+ gu used to check the free model's allowance only at the START of a turn and count the turn's spend only
4
+ at its END — so a long turn ran on, well past the allowance, and usually ended in a confusing error.
5
+
6
+ Now the agent reads what is left (~/.gonext/free-model.json, which gu writes; it never holds the key),
7
+ adds up what THIS turn has spent after every step, and PAUSES before the step that would not fit:
8
+ the step that ran stays finished (no half-written file), and the turn ends with a plain message the
9
+ user can act on, then "continue".
10
+
11
+ The cost formula is gu's (free-model.mjs turnCostMicro) — the same fixture is checked on both sides
12
+ (tests/free-budget.test.mjs and test_gu_free_budget.py), so the two can never drift apart.
13
+ Pure except load(); never raises.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import math
19
+ import os
20
+ import time
21
+
22
+ STATE_FILE = os.path.join("~", ".gonext", "free-model.json")
23
+
24
+
25
+ def _whole(n) -> int:
26
+ try:
27
+ v = float(n)
28
+ except (TypeError, ValueError):
29
+ return 0
30
+ return int(math.floor(v)) if math.isfinite(v) and v > 0 else 0
31
+
32
+
33
+ def _num(n, default=0.0) -> float:
34
+ try:
35
+ v = float(n)
36
+ except (TypeError, ValueError):
37
+ return default
38
+ return v if math.isfinite(v) else default
39
+
40
+
41
+ def cost_micro(inp=0, cached=0, cache_reported=False, out=0, price=None) -> int:
42
+ """Micro-dollars for this usage — exactly free-model.mjs turnCostMicro (rounds UP)."""
43
+ price = price or {}
44
+ sent = _whole(inp)
45
+ hit = min(_whole(cached), sent) if cache_reported else 0
46
+ in_p = _num(price.get("inputPerM"))
47
+ cached_p = _num(price.get("cachedPerM"), in_p) if price.get("cachedPerM") is not None else in_p
48
+ out_p = _num(price.get("outputPerM"))
49
+ return int(math.ceil((sent - hit) * in_p + hit * cached_p + _whole(out) * out_p))
50
+
51
+
52
+ def _norm(u) -> str:
53
+ return str(u or "").strip().rstrip("/").lower()
54
+
55
+
56
+ def _period(now: float) -> str:
57
+ return time.strftime("%Y-%m", time.gmtime(now))
58
+
59
+
60
+ def price_for(state: dict, model: str) -> dict:
61
+ """free-model.mjs priceForModel: the model's own, else the DEAREST listed (never charged as cheap)."""
62
+ m = state.get("models") if isinstance(state.get("models"), dict) else {}
63
+ if model and isinstance(m.get(model), dict):
64
+ return m[model]
65
+ allp = [p for p in m.values() if isinstance(p, dict)]
66
+ if not allp:
67
+ return state.get("price") if isinstance(state.get("price"), dict) else {}
68
+ return {"inputPerM": max(_num(p.get("inputPerM")) for p in allp),
69
+ "outputPerM": max(_num(p.get("outputPerM")) for p in allp)}
70
+
71
+
72
+ def slot_for(state: dict, url: str):
73
+ """Which allowance a call on `url` draws from, or None when `url` is not the free model.
74
+ → {"key", "remaining"} where key = the extra provider's URL or "" for the primary."""
75
+ if not isinstance(state, dict) or not state.get("url"):
76
+ return None
77
+ n = _norm(url)
78
+ if not n:
79
+ return None
80
+ same_month = state.get("period") == _period(time.time())
81
+ for k, v in (state.get("providers") or {}).items():
82
+ if _norm(k) == n and isinstance(v, dict):
83
+ spent = _whole(v.get("spentMicro")) if same_month else 0
84
+ return {"key": k, "remaining": _whole(v.get("allowanceMicro")) - spent}
85
+ urls = [state.get("url")] + list(state.get("urls") or [])
86
+ if any(_norm(u) == n for u in urls):
87
+ spent = _whole(state.get("spentMicro")) if same_month else 0
88
+ return {"key": "", "remaining": _whole(state.get("allowanceMicro")) - spent}
89
+ return None
90
+
91
+
92
+ class Budget:
93
+ """This turn's budget on the free model. `remaining` = what the month had left when the turn began."""
94
+
95
+ def __init__(self, state: dict, coder_url: str, coder_model: str):
96
+ self.state = state
97
+ self.slot = slot_for(state, coder_url)
98
+ self.coder_url = coder_url
99
+ self.price = price_for(state, coder_model)
100
+ self.spent = 0
101
+ self.last_step = 0
102
+ self.fallback_in = 0
103
+ self.fallback_out = 0
104
+
105
+ @property
106
+ def active(self) -> bool:
107
+ return self.slot is not None
108
+
109
+ @property
110
+ def remaining(self) -> int:
111
+ return self.slot["remaining"] if self.slot else 0
112
+
113
+ def turn_spent(self, inp, cached, cache_reported, out, aux=None) -> int:
114
+ """The turn so far: the coder's totals + the other calls (chat model…) on the SAME allowance."""
115
+ total = cost_micro(inp, cached, cache_reported, out, self.price)
116
+ for a in aux or []:
117
+ if not isinstance(a, dict):
118
+ continue
119
+ s = slot_for(self.state, a.get("url"))
120
+ if s is None or s["key"] != self.slot["key"]:
121
+ continue
122
+ total += cost_micro(a.get("input"), a.get("cached"), a.get("cacheReported") is True,
123
+ a.get("output"), price_for(self.state, str(a.get("model") or "")))
124
+ return total
125
+
126
+ def after_step(self, spent_now: int) -> bool:
127
+ """Record the turn's spend after a step → True when the NEXT step would not fit.
128
+ The next step is expected to cost about what the last one did (context only grows)."""
129
+ spent_now = max(int(spent_now), self.spent)
130
+ self.last_step = spent_now - self.spent
131
+ self.spent = spent_now
132
+ return self.active and self.remaining - self.spent < max(self.last_step, 1)
133
+
134
+ @property
135
+ def over(self) -> bool:
136
+ return self.active and self.spent >= self.remaining
137
+
138
+
139
+ def load(coder_url: str, coder_model: str, path: str | None = None):
140
+ """The turn's Budget, or None (not the free model, no state, unreadable). Never raises."""
141
+ try:
142
+ with open(os.path.expanduser(path or STATE_FILE), encoding="utf-8") as fh:
143
+ state = json.load(fh)
144
+ b = Budget(state, coder_url, coder_model)
145
+ return b if b.active else None
146
+ except (OSError, ValueError, TypeError, AttributeError):
147
+ return None
148
+
149
+
150
+ PAUSE_HEAD = ("Paused: this month's free-model allowance is used up, so I stopped before the next step. "
151
+ "The steps that ran are finished; nothing was left half-done.")
152
+ PAUSE_WAYS = ("To keep going, add your own model key with /model, a local model with Ollama, or a new "
153
+ "code with /voucher, then type continue. The free model renews on the 1st.")
154
+ OUT_OF_CREDIT = ("Paused: the free model can't take more requests right now (its account is out of credit; "
155
+ "this is not your allowance). The steps that ran are finished.")
156
+
157
+
158
+ def pause_message(recap: str = "", out_of_credit: bool = False) -> str:
159
+ head = OUT_OF_CREDIT if out_of_credit else PAUSE_HEAD
160
+ ways = ("Add your own model key with /model, or a local model with Ollama, then type continue."
161
+ if out_of_credit else PAUSE_WAYS)
162
+ body = [head, "", ways]
163
+ if recap.strip():
164
+ body += ["", recap.strip()]
165
+ return "\n".join(body)
@@ -0,0 +1,89 @@
1
+ """NOTES TYPED DURING A TURN, read by the running agent at its next step (GH #506).
2
+
3
+ gu writes what the user typed while a turn runs to ~/.gonext/turn-notes/<jobId>.jsonl. The agent's
4
+ step callback TAKES the file (rename, then read) after a step and adds the notes to that step's
5
+ observations — the newest text of the conversation, not yet sent to the model. So the prompt is only
6
+ APPENDED to: the system prompt, the tool reference and every earlier step stay byte-identical, and
7
+ the prompt cache keeps working. A note nobody took by the end of the turn stays in the file; gu then
8
+ runs it as the next question.
9
+
10
+ The log never holds what the user typed (log policy #248): counts only.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import os
16
+ import re
17
+ import time
18
+
19
+ NOTE_HEAD = "----- A NOTE FROM THE USER (typed while you were working) -----"
20
+ NOTE_TAIL = ("Take it into account from your next step on. It adds to the task; it replaces the task "
21
+ "only if it says so.")
22
+
23
+
24
+ def notes_dir() -> str:
25
+ return os.path.join(os.path.expanduser("~"), ".gonext", "turn-notes")
26
+
27
+
28
+ def _safe(job_id: str) -> str:
29
+ return re.sub(r"[^A-Za-z0-9_-]", "", str(job_id or ""))[:80]
30
+
31
+
32
+ def notes_path(job_id: str) -> str:
33
+ return os.path.join(notes_dir(), _safe(job_id) + ".jsonl")
34
+
35
+
36
+ def take_notes(job_id: str) -> list[str]:
37
+ """The notes waiting for this job, oldest first — and they are gone from the file. [] when none."""
38
+ if not _safe(job_id):
39
+ return []
40
+ path = notes_path(job_id)
41
+ if not os.path.exists(path):
42
+ return []
43
+ taken = f"{path}.taken-{os.getpid()}-{int(time.time() * 1000)}"
44
+ try:
45
+ os.replace(path, taken) # atomic: a line gu writes from now on starts a new file
46
+ except OSError:
47
+ return []
48
+ texts: list[str] = []
49
+ try:
50
+ with open(taken, encoding="utf-8") as fh:
51
+ for line in fh:
52
+ line = line.strip()
53
+ if not line:
54
+ continue
55
+ try:
56
+ t = str(json.loads(line).get("text") or "").strip()
57
+ except (ValueError, AttributeError):
58
+ continue
59
+ if t:
60
+ texts.append(t)
61
+ finally:
62
+ try:
63
+ os.remove(taken)
64
+ except OSError:
65
+ pass
66
+ return texts
67
+
68
+
69
+ def note_block(texts: list[str]) -> str:
70
+ """The text added after a step's observations."""
71
+ body = "\n\n".join(texts)
72
+ return f"{NOTE_HEAD}\n{body}\n{NOTE_TAIL}"
73
+
74
+
75
+ def add_to_step(step_log, job_id: str) -> int:
76
+ """Called from the step callback: give the notes to the NEXT step. → how many were added.
77
+
78
+ Not on the final step (no step reads it; gu runs the note as the next question instead), and
79
+ only on an action step (the one whose observations the next model call sends).
80
+ """
81
+ if getattr(step_log, "is_final_answer", False) or not hasattr(step_log, "observations"):
82
+ return 0
83
+ texts = take_notes(job_id)
84
+ if not texts:
85
+ return 0
86
+ obs = getattr(step_log, "observations", None)
87
+ head = obs + "\n\n" if isinstance(obs, str) and obs.strip() else ""
88
+ step_log.observations = head + note_block(texts)
89
+ return len(texts)
package/install-path.mjs CHANGED
@@ -108,6 +108,9 @@ export function fixPathPrefix({ here = "", env = process.env, exists = existsSyn
108
108
  function main() {
109
109
  if (platform() === "win32") return windowsNotes(); // registry PATH: report, never edit (#375)
110
110
  if (process.env.CI) return; // no user shell to help in CI
111
+ // GH #511: install.sh adds PATH itself, with the STABLE ~/.local/share/gu/node/bin (npm reports the
112
+ // versioned folder, which a Node update removes) — one line in the shell file, not two.
113
+ if (process.env.GU_INSTALLER === "sh") return;
111
114
  const prefix = process.env.npm_config_prefix;
112
115
  if (!prefix) return; // not an npm install context
113
116
  // A LOCAL install (`npm install @tiens.nguyen/gu-cli` inside a project) must NEVER
@@ -143,25 +143,34 @@ export function parseModelSetupChoice(raw) {
143
143
 
144
144
  /**
145
145
  * THE ONE START QUESTION (GH #490). Replaces "guided / preset / skip" followed by an eight-row provider
146
- * list: what people bring decides everything else. Enter keeps the long-standing path (an Ollama server —
147
- * this machine's, or the shared one), so nobody who presses Enter gets something different.
146
+ * list: what people bring decides everything else.
147
+ *
148
+ * WHAT ENTER PICKS (GH #511): it used to be "My own model" on every machine — but a new person rarely has
149
+ * Ollama running, so Enter led to a server question they could not answer. Now Enter is the promo code
150
+ * (what gucli.com hands out), and "My own model" only when an Ollama is ANSWERING on this machine.
151
+ * `enter` = "free" | "own".
148
152
  */
149
- export function startMenu({ presets = 0 } = {}) {
153
+ export function startMenu({ presets = 0, enter = "free" } = {}) {
154
+ const mark = (k) => (enter === k ? " (Enter)" : "");
150
155
  return [
151
156
  "How do you want to start?",
152
157
  " 1 I have a key — Claude, DeepSeek, OpenAI, Qwen, Kimi…",
153
- " 2 Use promo code — I have a code from gucli.com",
154
- " 3 My own model — Ollama on this machine, or another server (Enter)",
158
+ ` 2 Use promo code — I have a code from gucli.com${mark("free")}`,
159
+ ` 3 My own model — Ollama on this machine, or another server${mark("own")}`,
155
160
  " 4 Later — set it up with /model",
156
161
  ...(presets > 0 ? [` 5 Load a saved preset (${presets} saved)`] : []),
157
162
  ];
158
163
  }
159
164
 
165
+ /** The number Enter stands for, for the "choose [N]:" prompt. */
166
+ export const startEnterNumber = (enter = "free") => (enter === "own" ? "3" : "2");
167
+
160
168
  /** An answer to startMenu (2 = "Use promo code": a promo code is not always free) → "key" | "free" | "own" | "later" | "preset", or null to ask again. */
161
- export function parseStartChoice(raw) {
169
+ export function parseStartChoice(raw, { enter = "free" } = {}) {
162
170
  if (raw === SKIP_ALL) return "later";
163
171
  const t = String(raw ?? "").trim().toLowerCase();
164
- if (t === "" || t === "3" || t === "own" || t === "ollama" || t === "o") return "own";
172
+ if (t === "") return enter === "own" ? "own" : "free";
173
+ if (t === "3" || t === "own" || t === "ollama" || t === "o") return "own";
165
174
  if (t === "1" || t === "key" || t === "k") return "key";
166
175
  if (t === "2" || t === "promo" || t === "free" || t === "f" || t === "code" || t === "c") return "free";
167
176
  if (t === "4" || t === "later" || t === "l" || t === "s" || t === "skip" || t === "n" || t === "no" || t === "-") return "later";
@@ -169,6 +178,12 @@ export function parseStartChoice(raw) {
169
178
  return null;
170
179
  }
171
180
 
181
+ /** A promo code as typed at the start (GH #511): its shape only — the service decides if it is good. "" = none. */
182
+ export function promoCodeOf(raw) {
183
+ const t = String(raw ?? "").trim();
184
+ return /^[A-Za-z0-9_-]{4,32}$/.test(t) ? t : "";
185
+ }
186
+
172
187
  /** "I have a key" → which provider the key is for: every preset, then another URL. No default: a key fits one provider. */
173
188
  export function keyProviderMenu(presets = []) {
174
189
  return [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiens.nguyen/gu-cli",
3
- "version": "1.0.921",
3
+ "version": "1.0.922",
4
4
  "description": "gu: the coding agent in your terminal. It reads your repo, makes the change and runs the tests, with your own models (Ollama or any OpenAI-compatible provider). Free installs keep the agent, its API and its database on your machine. macOS, Linux and Windows.",
5
5
  "keywords": [
6
6
  "ai",
@@ -36,6 +36,7 @@
36
36
  "ui:accept": "UPDATE_UI=1 node --test --test-concurrency=1 tests/ui/ui.test.mjs",
37
37
  "test:keys": "node --test tests/key-choice-regression.test.mjs tests/coding-key-line.test.mjs tests/coding-key-picker.test.mjs tests/coding-key-prompt.test.mjs tests/coding-key-notice.test.mjs tests/coding-key-fallback-line.test.mjs tests/manage-coding-providers.test.mjs tests/add-coding-provider.test.mjs tests/coding-provider-setup.test.mjs",
38
38
  "deploy:local": "npm install -g .",
39
+ "deploy:dev": "node scripts/dev-deploy.mjs",
39
40
  "run": "gu-cli",
40
41
  "publish:org": "npm publish --access public",
41
42
  "preflight": "node scripts/preflight.mjs",
@@ -186,6 +187,9 @@
186
187
  "gu_test_digest.py",
187
188
  "gu_browser.py",
188
189
  "gu_powershell.py",
190
+ "gu_turn_notes.py",
191
+ "gu_free_budget.py",
192
+ "turn-notes.mjs",
189
193
  "gu_hooks.py",
190
194
  "prompt_scaffold_check.py",
191
195
  "gonext_transcribe.py",
package/turn-notes.mjs ADDED
@@ -0,0 +1,77 @@
1
+ // NOTES FOR THE RUNNING TURN (GH #506).
2
+ //
3
+ // Enter during a turn used to QUEUE the question for after the turn (#429). Now it is written to
4
+ // ~/.gonext/turn-notes/<jobId>.jsonl, and the agent (gu_turn_notes.py) adds it after its current
5
+ // step's result, so the model reads it at its NEXT step — appended at the end of the conversation,
6
+ // which keeps the prompt cache. A note the agent did not take by the end of the turn (the turn was
7
+ // a plain reply, or ended on that very step) is taken back here and runs as the next question.
8
+ //
9
+ // The file is private (0600): it holds what the user typed.
10
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync } from "node:fs";
11
+ import { homedir } from "node:os";
12
+ import { join } from "node:path";
13
+
14
+ export const notesDir = (home = homedir()) => join(home, ".gonext", "turn-notes");
15
+ const safe = (jobId) => String(jobId ?? "").replace(/[^A-Za-z0-9_-]/g, "").slice(0, 80);
16
+ export const notesPath = (jobId, home) => join(notesDir(home), `${safe(jobId)}.jsonl`);
17
+
18
+ /** Hand a note to the running turn → true when written. */
19
+ export function sendNote(jobId, text, home) {
20
+ const t = String(text ?? "").trim();
21
+ if (!safe(jobId) || !t) return false;
22
+ try {
23
+ mkdirSync(notesDir(home), { recursive: true, mode: 0o700 });
24
+ appendFileSync(notesPath(jobId, home), JSON.stringify({ text: t, at: new Date().toISOString() }) + "\n", { mode: 0o600 });
25
+ return true;
26
+ } catch {
27
+ return false;
28
+ }
29
+ }
30
+
31
+ /** The notes the agent never took, oldest first; the file is removed. [] when none. */
32
+ export function takeUnread(jobId, home) {
33
+ if (!safe(jobId)) return [];
34
+ const path = notesPath(jobId, home);
35
+ if (!existsSync(path)) return [];
36
+ const taken = `${path}.back-${process.pid}-${Date.now()}`;
37
+ try {
38
+ renameSync(path, taken);
39
+ } catch {
40
+ return [];
41
+ }
42
+ try {
43
+ return readFileSync(taken, "utf8")
44
+ .split("\n")
45
+ .map((l) => {
46
+ try {
47
+ return String(JSON.parse(l).text ?? "").trim();
48
+ } catch {
49
+ return "";
50
+ }
51
+ })
52
+ .filter(Boolean);
53
+ } finally {
54
+ rmSync(taken, { force: true });
55
+ }
56
+ }
57
+
58
+ /** Files left by a crash, older than a day, are removed (they hold typed text). */
59
+ export function sweepOldNotes(home, now = Date.now()) {
60
+ try {
61
+ for (const f of readdirSync(notesDir(home))) {
62
+ const p = join(notesDir(home), f);
63
+ if (now - statSync(p).mtimeMs > 86_400_000) rmSync(p, { force: true });
64
+ }
65
+ } catch {
66
+ /* no folder yet */
67
+ }
68
+ }
69
+
70
+ /** The line under the input row after Enter. */
71
+ export const SENT_NOTE = "↳ sent to the running turn — the agent reads it at its next step";
72
+
73
+ /** The input-row label after notes were sent during this turn. */
74
+ export function sentNotice(n, width = 80) {
75
+ const long = `(${n === 1 ? "note" : `${n} notes`} sent — the agent reads ${n === 1 ? "it" : "them"} at its next step) `;
76
+ return long.length + 12 <= width ? long : `(${n === 1 ? "note" : `${n} notes`} sent) `;
77
+ }
package/turn-queue.mjs CHANGED
@@ -7,8 +7,10 @@
7
7
  export const MAX_QUEUED_QUESTIONS = 20;
8
8
 
9
9
  /** What the input row says while the user is typing during a turn. */
10
- export const TYPING_NOTICE = "(turn running — Enter queues your question for when it finishes) ";
11
- export const TYPING_SHORT = "(Enter queues it) ";
10
+ // GH #506: Enter now hands the text to the RUNNING turn (turn-notes.mjs); the queue below keeps what
11
+ // the agent did not read before the turn ended.
12
+ export const TYPING_NOTICE = "(turn running — Enter sends it to the agent's next step) ";
13
+ export const TYPING_SHORT = "(Enter sends it) ";
12
14
 
13
15
  export function createTurnQueue({ max = MAX_QUEUED_QUESTIONS } = {}) {
14
16
  const items = [];
@@ -20,6 +22,13 @@ export function createTurnQueue({ max = MAX_QUEUED_QUESTIONS } = {}) {
20
22
  return true;
21
23
  },
22
24
  /** The oldest queued item, or null. */
25
+ /** GH #506: notes the turn never read go FIRST — they were typed before anything queued later. */
26
+ unshiftAll(list) {
27
+ const room = Math.max(0, max - items.length);
28
+ const take = list.slice(0, room);
29
+ items.unshift(...take);
30
+ return take.length;
31
+ },
23
32
  shift() {
24
33
  return items.length ? items.shift() : null;
25
34
  },