@tiens.nguyen/gu-cli 1.0.921 → 1.0.925
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.
- package/browser-extension/actions.js +105 -5
- package/browser-extension/background.js +3 -1
- package/browser-extension/manifest.json +1 -1
- package/cli-token.mjs +12 -1
- package/client-expert-run.mjs +20 -6
- package/embed-model-command.mjs +13 -2
- package/gonext_agent_chat.py +88 -3
- package/gu-cli.mjs +4 -0
- package/gu-repl.mjs +109 -14
- package/gu_free_budget.py +165 -0
- package/gu_turn_notes.py +89 -0
- package/install-path.mjs +3 -0
- package/model-setup-ui.mjs +22 -7
- package/package.json +5 -1
- package/turn-notes.mjs +89 -0
- package/turn-queue.mjs +11 -18
|
@@ -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
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
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.
|
|
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
|
-
|
|
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++) {
|
package/client-expert-run.mjs
CHANGED
|
@@ -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(
|
|
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
|
-
|
|
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
|
}
|
package/embed-model-command.mjs
CHANGED
|
@@ -224,6 +224,16 @@ export function embedNotice({ state, model } = {}) {
|
|
|
224
224
|
return "no embed model — RAG is off · /embed-model";
|
|
225
225
|
}
|
|
226
226
|
|
|
227
|
+
/**
|
|
228
|
+
* AN OPEN WINDOW ON OLD CODE (GH #513): the gu on disk has another version than the one this window started
|
|
229
|
+
* with (a deploy, /update elsewhere, npm). Say so — never restart the window: what is on screen would go.
|
|
230
|
+
*/
|
|
231
|
+
export function versionNoticeRows(running, onDisk) {
|
|
232
|
+
const known = (v) => /^\d+\.\d+\.\d+/.test(String(v ?? ""));
|
|
233
|
+
if (!known(running) || !known(onDisk) || running === onDisk) return [];
|
|
234
|
+
return [`gu ${onDisk} is on this computer — Ctrl+C, then gu, to use it`];
|
|
235
|
+
}
|
|
236
|
+
|
|
227
237
|
/**
|
|
228
238
|
* WHICH SETUP ROWS THE BOTTOM BAR SHOWS (first-run noise, #188). A fresh install used to stack
|
|
229
239
|
* three warnings at once. Now they come in order of need, and pure (no OS-specific logic):
|
|
@@ -233,8 +243,9 @@ export function embedNotice({ state, model } = {}) {
|
|
|
233
243
|
* - no embed model → NOTHING until embedding was actually needed (`embedNeeded`: the agent tried
|
|
234
244
|
* a RAG tool, or the user opened /embed-model), then the embed row.
|
|
235
245
|
*/
|
|
236
|
-
export function setupNoticeRows({ noModel = false, agentMissing = false, embedMissing = false, embedNeeded = false, embedWhy } = {}) {
|
|
237
|
-
|
|
246
|
+
export function setupNoticeRows({ noModel = false, agentMissing = false, embedMissing = false, embedNeeded = false, embedWhy, promoPending = false } = {}) {
|
|
247
|
+
// GH #511: a promo code chosen at setup is about to set the model — "not set" there reads as a fault.
|
|
248
|
+
if (noModel) return [promoPending ? "free model: your promo code sets it up" : "coding model not set · /model"];
|
|
238
249
|
return [
|
|
239
250
|
...(embedMissing && embedNeeded ? [embedNotice(embedWhy) || "no embed model — RAG is off · /embed-model"] : []),
|
|
240
251
|
];
|
package/gonext_agent_chat.py
CHANGED
|
@@ -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,46 @@ 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
|
+
# GH #514: a marker, not a message — gu moves the user's own words into the history here.
|
|
13563
|
+
_emit({"type": "step", "text": f"__USERNOTE__::{_n}"})
|
|
13564
|
+
_log(f"step {step_num}: {_n} user note(s) added for the next step")
|
|
13565
|
+
except Exception as e: # noqa: BLE001
|
|
13566
|
+
_log(f"user note skip: {e}")
|
|
13567
|
+
|
|
13568
|
+
# GH #507: the free model's month, checked after EVERY step — not only at the turn's start.
|
|
13569
|
+
# When the next step would not fit, the agent stops HERE: this step is finished, the next
|
|
13570
|
+
# model call is never made. Amounts never reach the log (#497: no dollar amounts), only that.
|
|
13571
|
+
try:
|
|
13572
|
+
_fb_b = _FREE_TURN.get("b")
|
|
13573
|
+
if _fb_b is not None and not _FREE_TURN.get("hit") and not getattr(step_log, "is_final_answer", False):
|
|
13574
|
+
_fb_m = _FREE_TURN.get("model")
|
|
13575
|
+
_fb_in = int(getattr(_fb_m, "_code_tokens_total", 0) or 0)
|
|
13576
|
+
_fb_out = int(getattr(_fb_m, "_code_output_tokens_total", 0) or 0)
|
|
13577
|
+
_fb_cached = int(getattr(_fb_m, "_code_cached_tokens_total", 0) or 0)
|
|
13578
|
+
if not _fb_in and not _fb_out:
|
|
13579
|
+
# A coder without gu's counters: smolagents' per-step usage, summed (no cache figure,
|
|
13580
|
+
# so charged at the full input price — an estimate never undercharges).
|
|
13581
|
+
_tu = getattr(step_log, "token_usage", None)
|
|
13582
|
+
_fb_b.fallback_in += int(getattr(_tu, "input_tokens", 0) or 0)
|
|
13583
|
+
_fb_b.fallback_out += int(getattr(_tu, "output_tokens", 0) or 0)
|
|
13584
|
+
_fb_in, _fb_out = _fb_b.fallback_in, _fb_b.fallback_out
|
|
13585
|
+
with _AUX_LOCK:
|
|
13586
|
+
_fb_aux = [dict(v) for v in _AUX_USAGE.values()]
|
|
13587
|
+
if _fb_b.after_step(_fb_b.turn_spent(_fb_in, _fb_cached, _fb_cached > 0, _fb_out, _fb_aux)):
|
|
13588
|
+
_FREE_TURN["hit"] = True
|
|
13589
|
+
_emit({"type": "step", "text": "Pausing — this month's free-model allowance is used up"})
|
|
13590
|
+
_log(f"step {step_num}: free-model allowance would not cover the next step → pausing the turn")
|
|
13591
|
+
agent.interrupt()
|
|
13592
|
+
except Exception as e: # noqa: BLE001
|
|
13593
|
+
_log(f"free-model budget check skipped: {type(e).__name__}")
|
|
13594
|
+
|
|
13551
13595
|
# Task #74: an executor-timeout error means whatever the step's tool call
|
|
13552
13596
|
# achieved was NEVER reported to the model (a create_pdf may have finished —
|
|
13553
13597
|
# or may still be finishing — in the background). Flag it so a repeat
|
|
@@ -14448,6 +14492,8 @@ def run_agent_chat(cfg):
|
|
|
14448
14492
|
_emit({
|
|
14449
14493
|
"type": "code_request",
|
|
14450
14494
|
"step": self._call_index,
|
|
14495
|
+
# GH #509: the model this step is sent to (after any fallback, #343).
|
|
14496
|
+
"model": str(getattr(self, "model_id", "") or ""),
|
|
14451
14497
|
# 0, explicitly, not absent: the model has not answered yet and the
|
|
14452
14498
|
# page must be able to show a real zero rather than a blank that reads
|
|
14453
14499
|
# like missing data.
|
|
@@ -14528,6 +14574,9 @@ def run_agent_chat(cfg):
|
|
|
14528
14574
|
# from "your coding key is wrong". The key itself is never echoed.
|
|
14529
14575
|
if _is_auth_failure(e) or _is_billing_failure(e):
|
|
14530
14576
|
_host = _host_of(coding_base_url)
|
|
14577
|
+
if _is_billing_failure(e) and _FREE_TURN.get("b") is not None:
|
|
14578
|
+
import gu_free_budget as _fbm
|
|
14579
|
+
raise _AgentConfigError(_fbm.pause_message(out_of_credit=True)) from e
|
|
14531
14580
|
if _is_billing_failure(e):
|
|
14532
14581
|
# One line: WHO refused, WHY (their words, ids stripped), and
|
|
14533
14582
|
# the ONE thing that fixes it. Nothing about attempts or
|
|
@@ -14803,6 +14852,8 @@ def run_agent_chat(cfg):
|
|
|
14803
14852
|
_emit({
|
|
14804
14853
|
"type": "code_response",
|
|
14805
14854
|
"step": self._call_index,
|
|
14855
|
+
# GH #509: the model that answered this step — Flow 3D shows it per turn.
|
|
14856
|
+
"model": str(getattr(self, "model_id", "") or ""),
|
|
14806
14857
|
"text": _raw if isinstance(_raw, str)
|
|
14807
14858
|
else ("" if _raw is None else str(_raw)),
|
|
14808
14859
|
"inputTokens": _in2,
|
|
@@ -15000,6 +15051,11 @@ def run_agent_chat(cfg):
|
|
|
15000
15051
|
_log("no-code streak hit limit → ending the turn honestly "
|
|
15001
15052
|
"instead of looping on a coder that won't emit code")
|
|
15002
15053
|
_nocode_msg = _no_code_message(self.model_id)
|
|
15054
|
+
# GH #507: on a spent free-model month, empty replies are the limit talking.
|
|
15055
|
+
_fbx = _FREE_TURN.get("b")
|
|
15056
|
+
if _fbx is not None and _fbx.over:
|
|
15057
|
+
import gu_free_budget as _fbm
|
|
15058
|
+
_nocode_msg = _fbm.pause_message()
|
|
15003
15059
|
msg.content = ("<code>\nfinal_answer("
|
|
15004
15060
|
+ repr(_nocode_msg) + ")\n</code>")
|
|
15005
15061
|
self._no_code_streak = 0
|
|
@@ -17708,9 +17764,30 @@ def run_agent_chat(cfg):
|
|
|
17708
17764
|
task_with_hint += ("\n\n(The user pasted " + ", ".join(l for l, _ in _turn_image_refs)
|
|
17709
17765
|
+ " but this coding model is not sent images — say so if the "
|
|
17710
17766
|
"task needs them.)")
|
|
17767
|
+
# GH #507: what the free model's month has left for this turn (None: not the free model).
|
|
17768
|
+
try:
|
|
17769
|
+
import gu_free_budget as _fb_mod
|
|
17770
|
+
_FREE_TURN.update({"b": _fb_mod.load(coding_base_url, coding_model_id), "hit": False,
|
|
17771
|
+
"model": getattr(agent, "model", None)})
|
|
17772
|
+
if _FREE_TURN["b"] is not None:
|
|
17773
|
+
_log("free-model budget: checked after every step this turn")
|
|
17774
|
+
except Exception as e: # noqa: BLE001
|
|
17775
|
+
_FREE_TURN.update({"b": None, "hit": False, "model": None})
|
|
17776
|
+
_log(f"free-model budget not loaded: {type(e).__name__}")
|
|
17777
|
+
|
|
17778
|
+
def _run_or_pause(**kw):
|
|
17779
|
+
# agent.interrupt() (the budget check above) ends smolagents' run with an AgentError
|
|
17780
|
+
# at the top of the next step: that is a PAUSE, not a failure.
|
|
17781
|
+
try:
|
|
17782
|
+
return agent.run(task_with_hint, **kw)
|
|
17783
|
+
except Exception:
|
|
17784
|
+
if _FREE_TURN.get("hit"):
|
|
17785
|
+
return None
|
|
17786
|
+
raise
|
|
17787
|
+
|
|
17711
17788
|
with contextlib.redirect_stdout(sys.stderr):
|
|
17712
|
-
result =
|
|
17713
|
-
while _maxsteps_partial.get("hit"):
|
|
17789
|
+
result = _run_or_pause(images=_turn_images or None)
|
|
17790
|
+
while _maxsteps_partial.get("hit") and not _FREE_TURN.get("hit"):
|
|
17714
17791
|
if _always_extend:
|
|
17715
17792
|
_log(f"max-steps reached → auto-extending to {_MAXSTEP_CEILING} "
|
|
17716
17793
|
"(don't-ask-again session flag)")
|
|
@@ -17732,7 +17809,15 @@ def run_agent_chat(cfg):
|
|
|
17732
17809
|
agent.max_steps = _MAXSTEP_CEILING
|
|
17733
17810
|
_emit({"type": "step", "text": "Continuing — step budget extended…"})
|
|
17734
17811
|
_log(f"continuing run with raised budget {agent.max_steps}")
|
|
17735
|
-
result =
|
|
17812
|
+
result = _run_or_pause(reset=False)
|
|
17813
|
+
if _FREE_TURN.get("hit"):
|
|
17814
|
+
# The answer IS the pause: what to do, then what ran (so "continue" has it in the history).
|
|
17815
|
+
_recap = _fallback_recap(_turn_steps, "").replace(
|
|
17816
|
+
"**Status:** the model finished without writing a summary.", "").strip()
|
|
17817
|
+
_recap = re.sub(r"\s*</?code>\s*", " ", re.sub(r"(?m)^- Thought:[^<\n]*", "- ", _recap)).strip()
|
|
17818
|
+
_recap = re.sub(r"(?m)^-\s+", "- ", _recap)
|
|
17819
|
+
result = _fb_mod.pause_message(_recap)
|
|
17820
|
+
agent.interrupt_switch = False
|
|
17736
17821
|
# Final formatting — NO extra summarizer model call. In multi-step mode the
|
|
17737
17822
|
# agent's own final_answer() (or the max-steps fallback above) already holds the
|
|
17738
17823
|
# 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
|
@@ -157,11 +157,12 @@ import { readHooks } from "./hooks-config.mjs";
|
|
|
157
157
|
import { readSkillSource, sourceLabel, SKILL_SOURCE_KEY } from "./skill-source.mjs";
|
|
158
158
|
import { codingBannerLabel, isOllamaCloudUrl, SECRET_KEY_HINT } from "./coding-key-prompt.mjs";
|
|
159
159
|
import { questionEchoText, thoughtPrintSeq, wrapDiffText } from "./terminal-layout.mjs";
|
|
160
|
-
import { createTurnQueue,
|
|
160
|
+
import { createTurnQueue, droppedNote } from "./turn-queue.mjs"; // GH #429: questions typed during a turn wait here
|
|
161
|
+
import { sendNote, takeUnread, sweepOldNotes, parseUserNote, questionWithNotes, USERNOTE_PREFIX } 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";
|
|
164
|
-
import { embedNotice, embedState, setupNoticeRows } from "./embed-model-command.mjs";
|
|
165
|
+
import { embedNotice, embedState, setupNoticeRows, versionNoticeRows } from "./embed-model-command.mjs";
|
|
165
166
|
import { createConnectionWatch, modelHostsOf, offlineLine, probeReachable, stalledLine } from "./connection-watch.mjs";
|
|
166
167
|
import { HINTS, pickHint, hintRow, hintFits, HINT_AFTER_SECONDS } from "./hints.mjs";
|
|
167
168
|
import { normalizeQuick, quickReady, quickTarget, quickBarHint, quickWarning, QUICK_MAX } from "./quick-models.mjs";
|
|
@@ -238,6 +239,19 @@ const REPL_VERSION = (() => {
|
|
|
238
239
|
return "unknown";
|
|
239
240
|
}
|
|
240
241
|
})();
|
|
242
|
+
// The version on disk NOW, looked at every 20 s (GH #513). Unreadable (npm half-way through) → keep the last.
|
|
243
|
+
let diskVersion = REPL_VERSION;
|
|
244
|
+
setInterval(() => {
|
|
245
|
+
try {
|
|
246
|
+
const v = JSON.parse(readFileSync(join(DIR, "package.json"), "utf8")).version;
|
|
247
|
+
if (v && v !== diskVersion) {
|
|
248
|
+
diskVersion = v;
|
|
249
|
+
if (barPinned()) paintBar();
|
|
250
|
+
}
|
|
251
|
+
} catch {
|
|
252
|
+
/* try again next time */
|
|
253
|
+
}
|
|
254
|
+
}, 20_000).unref();
|
|
241
255
|
const ENV_FILE = join(homedir(), ".gonext", "worker.env");
|
|
242
256
|
const WS_FILE = join(homedir(), ".gonext", "workspaces.json");
|
|
243
257
|
const SESSIONS_DIR = join(homedir(), ".gonext", "sessions");
|
|
@@ -777,6 +791,8 @@ let openPresetsAtStart = false;
|
|
|
777
791
|
let addProviderAtStart = null;
|
|
778
792
|
// #490: setup's "Free model" — gu asks for the code once the terminal exists.
|
|
779
793
|
let voucherAtStart = false;
|
|
794
|
+
// GH #511: the code typed in setup's start question — redeemed at once, never asked a second time.
|
|
795
|
+
let voucherCodeAtStart = "";
|
|
780
796
|
|
|
781
797
|
// #220: a gu that STOPS ON AN ERROR says where help is — a start that failed (exit 1 before the
|
|
782
798
|
// prompt: no key, API unreachable, MongoDB down…) or a crash. One dim line, never during a session
|
|
@@ -930,6 +946,7 @@ if (!workerKey || !apiBase) {
|
|
|
930
946
|
if (setup.loadPreset) openPresetsAtStart = true;
|
|
931
947
|
if (setup.addProvider) addProviderAtStart = setup.addProvider;
|
|
932
948
|
if (setup.voucherAtStart) voucherAtStart = true;
|
|
949
|
+
if (setup.voucherCode) voucherCodeAtStart = setup.voucherCode;
|
|
933
950
|
// STOP when setup cannot go further.
|
|
934
951
|
//
|
|
935
952
|
// This used to fall through to the hosted sign-in, on the theory that "this machine
|
|
@@ -1236,6 +1253,27 @@ function pendingEchoRows() {
|
|
|
1236
1253
|
if (lines.length > 3) shown.push(dim(`${GUTTER}… ${lines.length - 3} more line(s)`));
|
|
1237
1254
|
return [...shown, ""];
|
|
1238
1255
|
}
|
|
1256
|
+
/** A message typed during a turn, drawn as every asked question is (GH #514). */
|
|
1257
|
+
function pastQuestion(text) {
|
|
1258
|
+
return questionEchoText(imageMarkersForDisplay(text), {
|
|
1259
|
+
width: process.stdout.columns || 80,
|
|
1260
|
+
paintPrompt: () => PROMPT_PAST,
|
|
1261
|
+
}) + "\n";
|
|
1262
|
+
}
|
|
1263
|
+
/** What waits for the agent, above the input box: dim ">> " rows, at most 3 lines each and 6 in all. */
|
|
1264
|
+
function waitingNoteRows() {
|
|
1265
|
+
if (!following) return [];
|
|
1266
|
+
const width = Math.max(20, process.stdout.columns || 80);
|
|
1267
|
+
const texts = [...waitingNotes.filter((n) => !n.shown).map((n) => n.text), ...turnQueue.list()];
|
|
1268
|
+
const rows = [];
|
|
1269
|
+
for (const t of texts) {
|
|
1270
|
+
const lines = pastQuestion(t).replace(/\n+$/, "").split("\n").map((l) => stripAnsiEscapes(l));
|
|
1271
|
+
rows.push(...lines.slice(0, 3).map((l) => dim(clipVisible(l, width - 1))));
|
|
1272
|
+
if (lines.length > 3) rows.push(dim(`${GUTTER}… ${lines.length - 3} more line(s)`));
|
|
1273
|
+
}
|
|
1274
|
+
if (!rows.length) return [];
|
|
1275
|
+
return ["", ...(rows.length > 6 ? [...rows.slice(0, 5), dim(`${GUTTER}… ${rows.length - 5} more line(s) waiting`)] : rows)];
|
|
1276
|
+
}
|
|
1239
1277
|
function flushPendingEcho() {
|
|
1240
1278
|
if (pendingEcho === null) return;
|
|
1241
1279
|
const text = pendingEcho;
|
|
@@ -1915,7 +1953,7 @@ let embedWhy = { state: "unset", model: "" };
|
|
|
1915
1953
|
// until embedding is actually needed (`embedNeeded`).
|
|
1916
1954
|
let embedNeeded = false;
|
|
1917
1955
|
const missingNoticeRows = () =>
|
|
1918
|
-
setupNoticeRows({ noModel: noModelAtAll, agentMissing, embedMissing, embedNeeded, embedWhy });
|
|
1956
|
+
setupNoticeRows({ noModel: noModelAtAll, agentMissing, embedMissing, embedNeeded, embedWhy, promoPending: voucherAtStart });
|
|
1919
1957
|
async function refreshNoModelAtAll() {
|
|
1920
1958
|
try {
|
|
1921
1959
|
const refreshed = await fetchAgentPayload([{ role: "user", content: "." }]);
|
|
@@ -2157,6 +2195,7 @@ const _lineQueue = [];
|
|
|
2157
2195
|
// GH #429: lines submitted WHILE A TURN RUNS wait here (FIFO); the main loop runs them one by one
|
|
2158
2196
|
// after the turn. Kept apart from _lineQueue, which every failed turn empties on purpose (#92).
|
|
2159
2197
|
const turnQueue = createTurnQueue();
|
|
2198
|
+
sweepOldNotes(); // GH #506: a crash can leave typed notes behind
|
|
2160
2199
|
/** A turn that did not finish throws its queued questions away — say how many, once. */
|
|
2161
2200
|
function dropQueuedQuestions() {
|
|
2162
2201
|
const n = turnQueue.clear();
|
|
@@ -2204,11 +2243,19 @@ rl.on("line", (l) => {
|
|
|
2204
2243
|
imageStore.clear();
|
|
2205
2244
|
typedDuringTurn = false;
|
|
2206
2245
|
turnTyping.reset();
|
|
2246
|
+
// GH #506: with a running job, the text goes to the agent's NEXT step (appended after the
|
|
2247
|
+
// current step's result — cache-safe). Not read by the end of the turn = the next question.
|
|
2248
|
+
// GH #514: like chat — no notices. Pinned, it waits as a ">> " row above the input box until the agent
|
|
2249
|
+
// reads it; with no frozen rows (piped, a tiny window) it is written into the history at once.
|
|
2250
|
+
if (queued && currentJobId && !cancelRequested && sendNote(currentJobId, queued)) {
|
|
2251
|
+
waitingNotes.push({ text: queued, shown: !barPinned() });
|
|
2252
|
+
if (barPinned()) paintBar();
|
|
2253
|
+
else process.stdout.write("\n" + pastQuestion(queued) + "\n");
|
|
2254
|
+
return;
|
|
2255
|
+
}
|
|
2207
2256
|
if (queued) {
|
|
2208
2257
|
if (turnQueue.push(queued)) {
|
|
2209
|
-
// No frozen row to carry the count (piped, or a window too short to pin one): say it here.
|
|
2210
2258
|
if (barPinned()) paintBar();
|
|
2211
|
-
else process.stdout.write(dim(`\n (queued — ${turnQueue.size} waiting; runs when this turn finishes)\n`));
|
|
2212
2259
|
} else {
|
|
2213
2260
|
process.stdout.write(dim(`\n (${turnQueue.size} questions are already queued — wait for one to run)\n`));
|
|
2214
2261
|
}
|
|
@@ -3077,7 +3124,8 @@ const footerBuilt = () =>
|
|
|
3077
3124
|
// Task #14: the skipped-setup warning — persistent (not a timed notice), red, its own row.
|
|
3078
3125
|
// …then the fallback rows (#343), YELLOW: a different model is doing the work — a warning,
|
|
3079
3126
|
// where the red rows above mean something is not set up at all.
|
|
3080
|
-
|
|
3127
|
+
// …and (GH #513), yellow too: this window runs older code than the gu now on this computer.
|
|
3128
|
+
missing: [...missingNoticeRows().map((r) => red(r)), ...fallbackNoticeRows().map((r) => yellow(r)), ...versionNoticeRows(REPL_VERSION, diskVersion).map((r) => yellow(r))],
|
|
3081
3129
|
});
|
|
3082
3130
|
const footerRows = () => footerBuilt().rows;
|
|
3083
3131
|
// An ask()'s hint lines (#305), drawn in yellow under its input while it waits. Plain text.
|
|
@@ -3238,7 +3286,7 @@ function closeZonePanel() {
|
|
|
3238
3286
|
function frozenZone() {
|
|
3239
3287
|
const width = Math.max(20, process.stdout.columns || 80);
|
|
3240
3288
|
if (zonePanel) {
|
|
3241
|
-
const status = footerActive ? [] : [...pendingEchoRows(), ...liveStatusRows];
|
|
3289
|
+
const status = footerActive ? [] : [...pendingEchoRows(), ...liveStatusRows, ...waitingNoteRows()];
|
|
3242
3290
|
// At least four rows of conversation stay visible, as with a tall input (maxInputRows).
|
|
3243
3291
|
const room = Math.max(3, viewportRows() - status.length - 2 - 4);
|
|
3244
3292
|
let body = [];
|
|
@@ -3261,7 +3309,7 @@ function frozenZone() {
|
|
|
3261
3309
|
// statusShown is already false — the prompt simply refuses to render any.
|
|
3262
3310
|
// #307: a question held until its turn prints anything sits on top of the status block — where
|
|
3263
3311
|
// it will land once committed, so nothing moves when it does.
|
|
3264
|
-
const status = footerActive ? [] : [...pendingEchoRows(), ...liveStatusRows];
|
|
3312
|
+
const status = footerActive ? [] : [...pendingEchoRows(), ...liveStatusRows, ...waitingNoteRows()];
|
|
3265
3313
|
// THE SEPARATOR CARRIES NOTHING (#318). What used to ride on it — jump-to-bottom, the update
|
|
3266
3314
|
// control, the gu token notice, the agents count — is on its own NOTICE ROW above it; the head
|
|
3267
3315
|
// is just the rule, with no blank to lift a control off the typed line.
|
|
@@ -8966,6 +9014,8 @@ async function setUpFreeModel({ token, announce = false } = {}) {
|
|
|
8966
9014
|
? `✓ ${got.preset.model} is now your agent model and your coding model.`
|
|
8967
9015
|
: `✓ ${agentM} is now your agent model and ${got.preset.model} your coding model.`) +
|
|
8968
9016
|
dim(" Free use renews each month; /model switches back to your own."));
|
|
9017
|
+
// GH #511: say plainly that setup is over and what to do now — the one line a new person needs.
|
|
9018
|
+
console.log(GUTTER + bold("Ready — type your first question below and press Enter."));
|
|
8969
9019
|
}
|
|
8970
9020
|
return true;
|
|
8971
9021
|
} catch (e) {
|
|
@@ -8990,7 +9040,10 @@ async function freeModelAtStart() {
|
|
|
8990
9040
|
}
|
|
8991
9041
|
|
|
8992
9042
|
/** After a turn on the free model: count it, say a notice once per level, tell the service. Never throws. */
|
|
8993
|
-
|
|
9043
|
+
// GH #507: how the agent's pause answer starts (gu_free_budget.py PAUSE_HEAD).
|
|
9044
|
+
const ALLOWANCE_PAUSE_PREFIX = "Paused: this month's free-model allowance is used up";
|
|
9045
|
+
|
|
9046
|
+
async function noteFreeModelTurn(inputTokens, breakdown, outputTokens, coder, aux = null, paused = false) {
|
|
8994
9047
|
try {
|
|
8995
9048
|
const fm = await import("./free-model.mjs");
|
|
8996
9049
|
if (!freeModel) return;
|
|
@@ -9005,6 +9058,7 @@ async function noteFreeModelTurn(inputTokens, breakdown, outputTokens, coder, au
|
|
|
9005
9058
|
fm.writeState(freeModelDir(), freeModel);
|
|
9006
9059
|
const n = fm.notice(freeModel, new Date(), coder?.url);
|
|
9007
9060
|
const noticeKey = `${freeModel.period}:${fm.slotFor(freeModel, coder?.url).extra ?? "main"}:${n?.level}`;
|
|
9061
|
+
if (paused && n?.level === "over") freeModelNoticed = noticeKey;
|
|
9008
9062
|
if (n?.text && freeModelNoticed !== noticeKey) {
|
|
9009
9063
|
freeModelNoticed = noticeKey;
|
|
9010
9064
|
console.log(GUTTER + (n.level === "ok" ? dim(n.text) : yellow(n.text)) + "\n");
|
|
@@ -11604,7 +11658,7 @@ const turnRowNotice = (width) =>
|
|
|
11604
11658
|
? cancelRequested
|
|
11605
11659
|
? visibleLen(SUPPORT_AFTER_STOP_NOTICE) + 12 <= width ? SUPPORT_AFTER_STOP_NOTICE : SUPPORT_AFTER_STOP_SHORT
|
|
11606
11660
|
: visibleLen(SUPPORT_AFTER_TURN_NOTICE) + 12 <= width ? SUPPORT_AFTER_TURN_NOTICE : SUPPORT_AFTER_TURN_SHORT
|
|
11607
|
-
:
|
|
11661
|
+
: "";
|
|
11608
11662
|
// Is the turn we are following one this terminal STARTED, or another terminal's that we merely
|
|
11609
11663
|
// attached to (task #211)? `attached` is local to runAgentTurn, and onInterrupt — which lives in
|
|
11610
11664
|
// main() — had no way to ask. So Ctrl+C while watching somebody else's agent took the "cancel my
|
|
@@ -11612,6 +11666,9 @@ const turnRowNotice = (width) =>
|
|
|
11612
11666
|
// non-destructive way back to your own prompt, which is the bug this flag exists to fix.
|
|
11613
11667
|
let followingAttached = false;
|
|
11614
11668
|
let followAborted = false;
|
|
11669
|
+
// GH #506/#514: what was typed during this turn — waiting for the agent, and what it has read.
|
|
11670
|
+
let waitingNotes = []; // {text, shown} — shown: already in the history (unpinned)
|
|
11671
|
+
let readNotes = []; // texts the agent read, kept with this turn's question
|
|
11615
11672
|
let currentJobId = null; // the running turn's jobId — so Ctrl+C can cancel it server-side
|
|
11616
11673
|
let cancelRequested = false; // a cancel POST has been sent for the current turn
|
|
11617
11674
|
// Interactive command-approval gate: while the agent is paused on a risky command, the
|
|
@@ -12827,6 +12884,7 @@ async function askForCliTokenInner(ct, dir, why, overLimit = false, short = "")
|
|
|
12827
12884
|
// A free-model promo code needs no token and no Pro plan: typed in this row, it gives the computer a token.
|
|
12828
12885
|
redeemPromo: async (code) => ct.redeemPromo({ hostedBase, device: await ct.thisDevice({ instanceId: myInstanceId || "" }).catch(() => null), code }),
|
|
12829
12886
|
promoFirst: voucherAtStart,
|
|
12887
|
+
promoCode: voucherAtStart ? voucherCodeAtStart : "", // GH #511: typed in setup — tried first, not asked again
|
|
12830
12888
|
// #315: a token is only good if THIS computer may use it — renew it from here (the server then
|
|
12831
12889
|
// says how much free time the computer has), save what came back, and run the licence rule.
|
|
12832
12890
|
accept: async (token) => {
|
|
@@ -12856,6 +12914,7 @@ async function askForCliTokenInner(ct, dir, why, overLimit = false, short = "")
|
|
|
12856
12914
|
if (r.ok && r.kind === "promo") {
|
|
12857
12915
|
// The code was the answer to "Free model": set that model up now — the later "Voucher code" question is moot.
|
|
12858
12916
|
voucherAtStart = false;
|
|
12917
|
+
voucherCodeAtStart = "";
|
|
12859
12918
|
const st = await ct.readState(dir);
|
|
12860
12919
|
await setUpFreeModel({ token: st.token, announce: true });
|
|
12861
12920
|
console.log("");
|
|
@@ -13809,6 +13868,22 @@ async function runAgentTurn(history, { attachJobId = "", ownJob = false } = {})
|
|
|
13809
13868
|
// Task #343: another model took over. Swallowed from the action list — it goes on the
|
|
13810
13869
|
// BAR, now, in yellow — and the turn leaves one line about it once it has ended (see the
|
|
13811
13870
|
// caller), so a fallback that lasted a single step can still be found afterwards.
|
|
13871
|
+
// GH #514: the agent just read what was typed — it becomes part of the history HERE, between its steps.
|
|
13872
|
+
if (line.startsWith(USERNOTE_PREFIX)) {
|
|
13873
|
+
const taken = waitingNotes.splice(0, parseUserNote(line));
|
|
13874
|
+
if (taken.length) {
|
|
13875
|
+
readNotes.push(...taken.map((n) => n.text));
|
|
13876
|
+
const unseen = taken.filter((n) => !n.shown);
|
|
13877
|
+
if (unseen.length) {
|
|
13878
|
+
releaseHeldThought();
|
|
13879
|
+
onContent();
|
|
13880
|
+
process.stdout.write((lastWasBlank ? "" : "\n") + unseen.map((n) => pastQuestion(n.text)).join("\n") + "\n");
|
|
13881
|
+
lastWasBlank = true;
|
|
13882
|
+
}
|
|
13883
|
+
}
|
|
13884
|
+
lastContentAt = Date.now();
|
|
13885
|
+
continue;
|
|
13886
|
+
}
|
|
13812
13887
|
if (line.startsWith(MODELFALLBACK_PREFIX)) {
|
|
13813
13888
|
const fb = parseModelFallback(line);
|
|
13814
13889
|
if (fb) {
|
|
@@ -14450,7 +14525,16 @@ async function runAgentTurn(history, { attachJobId = "", ownJob = false } = {})
|
|
|
14450
14525
|
typedDuringTurn = false;
|
|
14451
14526
|
turnTyping.reset();
|
|
14452
14527
|
endCompactLock(); // issue #120: never leave the terminal locked after a turn
|
|
14528
|
+
// GH #506: notes the agent never read run next — unless the turn was stopped, which drops them.
|
|
14529
|
+
{
|
|
14530
|
+
const unread = takeUnread(currentJobId);
|
|
14531
|
+
if (unread.length) {
|
|
14532
|
+
if (cancelRequested || followAborted) console.log(GUTTER + dim(droppedNote(unread.length)));
|
|
14533
|
+
else turnQueue.unshiftAll(unread);
|
|
14534
|
+
}
|
|
14535
|
+
}
|
|
14453
14536
|
currentJobId = null;
|
|
14537
|
+
waitingNotes = [];
|
|
14454
14538
|
// Drop anything typed (but not submitted) during the turn — echo was muted, so it's
|
|
14455
14539
|
// invisible; without this it would surface on the next prompt.
|
|
14456
14540
|
rl.line = "";
|
|
@@ -14610,6 +14694,7 @@ async function main() {
|
|
|
14610
14694
|
if (setup?.loadPreset) openPresetsAtStart = true;
|
|
14611
14695
|
if (setup?.addProvider) addProviderAtStart = setup.addProvider;
|
|
14612
14696
|
if (setup?.voucherAtStart) voucherAtStart = true;
|
|
14697
|
+
if (setup?.voucherCode) voucherCodeAtStart = setup.voucherCode;
|
|
14613
14698
|
}
|
|
14614
14699
|
} catch {
|
|
14615
14700
|
/* never block the REPL on the mode question — the banner still shows what is configured */
|
|
@@ -14916,7 +15001,10 @@ async function main() {
|
|
|
14916
15001
|
// client used to print a constant here instead of the account's model, so the one row
|
|
14917
15002
|
// that answers "which model am I using" named a value the user had never set and could
|
|
14918
15003
|
// not change. See clientAgentProblem in daemon-control for what the override was for.
|
|
14919
|
-
|
|
15004
|
+
// GH #511: NOTHING SET YET (a fresh install) — one plain row, not "same as the coding model" over "coder —".
|
|
15005
|
+
...(nothingToAnswerWith(p)
|
|
15006
|
+
? [lbl("model") + dim(voucherAtStart ? "not set yet — your promo code sets it up" : "not set yet — /model sets it up")]
|
|
15007
|
+
: [lbl("model") +
|
|
14920
15008
|
(agentLabel.known ? agentModelText(agentLabel) : dim(agentModelText(agentLabel))),
|
|
14921
15009
|
// Task #190: NOT `p.codingModelId || "—"`. While the API believes the coding key is
|
|
14922
15010
|
// missing it omits codingModelId altogether, so that read printed "coder —" three
|
|
@@ -14932,7 +15020,7 @@ async function main() {
|
|
|
14932
15020
|
sessionModel: sessionCodingModel,
|
|
14933
15021
|
}),
|
|
14934
15022
|
where: activeCoderWhere,
|
|
14935
|
-
}),
|
|
15023
|
+
})]),
|
|
14936
15024
|
lbl("RAG") +
|
|
14937
15025
|
(p.ragEnabled
|
|
14938
15026
|
? ragStorageLabel(sessionRagStorage)
|
|
@@ -15537,8 +15625,10 @@ async function main() {
|
|
|
15537
15625
|
// #490: setup's "Free model" — ask for the code now, then the same /voucher flow as typing it.
|
|
15538
15626
|
if (voucherAtStart) {
|
|
15539
15627
|
voucherAtStart = false;
|
|
15628
|
+
const typedInSetup = voucherCodeAtStart;
|
|
15629
|
+
voucherCodeAtStart = "";
|
|
15540
15630
|
try {
|
|
15541
|
-
const code = String(await ask(" Voucher code (Enter to skip, /voucher CODE later): ") ?? "").trim();
|
|
15631
|
+
const code = typedInSetup || String(await ask(" Voucher code (Enter to skip, /voucher CODE later): ") ?? "").trim();
|
|
15542
15632
|
if (code) await runVoucherCommand(`/voucher ${code}`);
|
|
15543
15633
|
else console.log(GUTTER + dim("No code yet — use /voucher CODE any time, or /model to pick your own."));
|
|
15544
15634
|
} catch (e) {
|
|
@@ -16186,6 +16276,7 @@ async function main() {
|
|
|
16186
16276
|
// another model's price on it.
|
|
16187
16277
|
const turnCoder = { url: activeCodingUrl(), model: activeCodingModelId() };
|
|
16188
16278
|
turnFallback = null; // #343: nothing has fallen back in THIS turn yet
|
|
16279
|
+
readNotes = []; // #514
|
|
16189
16280
|
if (reattach) console.log(GUTTER + dim("following the turn that was running when the connection went…\n"));
|
|
16190
16281
|
const turn = await runAgentTurn(history, reattach ? { attachJobId: reattach.jobId, ownJob: true } : {});
|
|
16191
16282
|
// NOT SENT (licence block, or the token prompt declined): runAgentTurn already said so.
|
|
@@ -16219,7 +16310,8 @@ async function main() {
|
|
|
16219
16310
|
lastTurnTotalOutput = outputTokens ?? 0;
|
|
16220
16311
|
// #323: what this turn's prompt tokens cost — on the token row and in /price.
|
|
16221
16312
|
void noteTurnCost(lastTurnInputTokens, lastPromptBreakdown, turnCoder);
|
|
16222
|
-
|
|
16313
|
+
// GH #507: a turn the agent PAUSED for the allowance already said so — the "used up" notice would repeat it.
|
|
16314
|
+
void noteFreeModelTurn(lastTurnInputTokens, lastPromptBreakdown, lastTurnOutputTokens, turnCoder, lastTurnAux, String(answer ?? "").startsWith(ALLOWANCE_PAUSE_PREFIX));
|
|
16223
16315
|
// A turn that FAILED carries the __TURN_FAILED__:: sentinel: the worker still delivers
|
|
16224
16316
|
// the text (both UIs need to show it), but it is a failure notice, not a reply. Print
|
|
16225
16317
|
// it as one and DROP it — persisting it would re-send "⚠️ your account is suspended" to
|
|
@@ -16243,6 +16335,9 @@ async function main() {
|
|
|
16243
16335
|
if (fellBack) printFallbackLine(fellBack);
|
|
16244
16336
|
} else if (answer) {
|
|
16245
16337
|
noteTaskSuccess();
|
|
16338
|
+
// GH #514: the next turns know what was added while this one ran.
|
|
16339
|
+
const asked = history[history.length - 1];
|
|
16340
|
+
if (readNotes.length && asked?.role === "user") asked.content = questionWithNotes(asked.content, readNotes);
|
|
16246
16341
|
history.push({ role: "assistant", content: answer });
|
|
16247
16342
|
// Persist after every successful turn (not just on clean exit) — an ungraceful
|
|
16248
16343
|
// termination (killed terminal, force-quit) would otherwise lose the whole
|
|
@@ -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)
|
package/gu_turn_notes.py
ADDED
|
@@ -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
|
package/model-setup-ui.mjs
CHANGED
|
@@ -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.
|
|
147
|
-
*
|
|
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
|
-
|
|
154
|
-
|
|
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 === ""
|
|
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.
|
|
3
|
+
"version": "1.0.925",
|
|
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,89 @@
|
|
|
1
|
+
// NOTES FOR THE RUNNING TURN (GH #506, shown like chat messages since #514).
|
|
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
|
+
/**
|
|
71
|
+
* IT LOOKS LIKE CHATTING (GH #514) — no notices. On Enter the message waits as a ">> …" row above the input
|
|
72
|
+
* box; when the agent reads it, it reports `__USERNOTE__::<count>` as a step, and gu moves that many rows into
|
|
73
|
+
* the history at that very point, drawn like any question.
|
|
74
|
+
*/
|
|
75
|
+
export const USERNOTE_PREFIX = "__USERNOTE__::";
|
|
76
|
+
|
|
77
|
+
/** → how many notes the agent just read; 0 when the line is not that report. */
|
|
78
|
+
export function parseUserNote(line) {
|
|
79
|
+
const s = String(line ?? "").trim();
|
|
80
|
+
if (!s.startsWith(USERNOTE_PREFIX)) return 0;
|
|
81
|
+
const n = Number(s.slice(USERNOTE_PREFIX.length));
|
|
82
|
+
return Number.isInteger(n) && n > 0 ? n : 0;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The turn's question as the next turns see it: what was added while it ran belongs to it. */
|
|
86
|
+
export function questionWithNotes(question, notes) {
|
|
87
|
+
const added = (notes ?? []).map((t) => String(t).trim()).filter(Boolean);
|
|
88
|
+
return added.length ? `${question}\n\n[Added by the user while you were working]\n${added.join("\n\n")}` : question;
|
|
89
|
+
}
|
package/turn-queue.mjs
CHANGED
|
@@ -6,10 +6,6 @@
|
|
|
6
6
|
|
|
7
7
|
export const MAX_QUEUED_QUESTIONS = 20;
|
|
8
8
|
|
|
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) ";
|
|
12
|
-
|
|
13
9
|
export function createTurnQueue({ max = MAX_QUEUED_QUESTIONS } = {}) {
|
|
14
10
|
const items = [];
|
|
15
11
|
return {
|
|
@@ -20,6 +16,17 @@ export function createTurnQueue({ max = MAX_QUEUED_QUESTIONS } = {}) {
|
|
|
20
16
|
return true;
|
|
21
17
|
},
|
|
22
18
|
/** The oldest queued item, or null. */
|
|
19
|
+
/** GH #506: notes the turn never read go FIRST — they were typed before anything queued later. */
|
|
20
|
+
unshiftAll(list) {
|
|
21
|
+
const room = Math.max(0, max - items.length);
|
|
22
|
+
const take = list.slice(0, room);
|
|
23
|
+
items.unshift(...take);
|
|
24
|
+
return take.length;
|
|
25
|
+
},
|
|
26
|
+
/** The waiting items, oldest first (GH #514: shown above the input box). */
|
|
27
|
+
list() {
|
|
28
|
+
return [...items];
|
|
29
|
+
},
|
|
23
30
|
shift() {
|
|
24
31
|
return items.length ? items.shift() : null;
|
|
25
32
|
},
|
|
@@ -35,20 +42,6 @@ export function createTurnQueue({ max = MAX_QUEUED_QUESTIONS } = {}) {
|
|
|
35
42
|
};
|
|
36
43
|
}
|
|
37
44
|
|
|
38
|
-
const fits = (s, width) => s.length + 12 <= width;
|
|
39
|
-
|
|
40
|
-
/** The input-row label while questions wait and nothing is being typed; "" when the queue is empty. */
|
|
41
|
-
export function queuedNotice(n, width = 80) {
|
|
42
|
-
if (!n) return "";
|
|
43
|
-
const long = `(${n} queued — runs after this turn; Ctrl-C drops them) `;
|
|
44
|
-
return fits(long, width) ? long : `(${n} queued) `;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/** The typing label that fits the row. */
|
|
48
|
-
export function typingNotice(width = 80) {
|
|
49
|
-
return fits(TYPING_NOTICE, width) ? TYPING_NOTICE : TYPING_SHORT;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
45
|
/** One line for the transcript when queued questions are thrown away. */
|
|
53
46
|
export function droppedNote(n) {
|
|
54
47
|
return `(${n} queued question${n === 1 ? "" : "s"} not run — the turn did not finish; type ${n === 1 ? "it" : "them"} again)`;
|