@tiens.nguyen/gu-cli 1.0.906 → 1.0.908
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-bridge.mjs +2 -1
- package/browser-chrome.mjs +3 -0
- package/browser-extension/actions.js +6 -1
- package/browser-extension/background.js +43 -7
- package/browser-extension/manifest.json +1 -1
- package/gonext_agent_chat.py +129 -15
- package/gu-repl.mjs +134 -57
- package/gu_browser.py +63 -2
- package/package.json +2 -1
- package/terminal-layout.mjs +23 -0
- package/turn-queue.mjs +55 -0
package/browser-bridge.mjs
CHANGED
|
@@ -165,7 +165,7 @@ export function startBridge({ port = DEFAULT_PORT, token = randomBytes(24).toStr
|
|
|
165
165
|
id: ext ? extId(ext.origin) : null,
|
|
166
166
|
installType: ext?.installType || null,
|
|
167
167
|
ownChrome: Boolean(own?.running),
|
|
168
|
-
refused: [...refused].filter(([, at]) => at > since).map(([id, at]) => ({ id, at })),
|
|
168
|
+
refused: [...refused].filter(([id, at]) => at > since && !(ext && id === extId(ext.origin))).map(([id, at]) => ({ id, at })),
|
|
169
169
|
pid: process.pid,
|
|
170
170
|
});
|
|
171
171
|
}
|
|
@@ -218,6 +218,7 @@ export function startBridge({ port = DEFAULT_PORT, token = randomBytes(24).toStr
|
|
|
218
218
|
}
|
|
219
219
|
if (ext) ext.socket.destroy();
|
|
220
220
|
ext = { socket, version: null, installType: null, origin };
|
|
221
|
+
refused.delete(extId(origin)); // it was turned away earlier but holds the connection now: not "refused" any more
|
|
221
222
|
log(`extension connected (${origin})`);
|
|
222
223
|
let buf = Buffer.alloc(0);
|
|
223
224
|
let parts = [];
|
package/browser-chrome.mjs
CHANGED
|
@@ -197,6 +197,8 @@ export class OwnChrome {
|
|
|
197
197
|
this.loading.add(id);
|
|
198
198
|
await this.cdp(id, "Page.navigate", { url });
|
|
199
199
|
this.current = id; // gu does not bring the tab to the front (#422)
|
|
200
|
+
(this.notes ??= []).push(reuse ? `reused gu's current tab ${id} in gu's own Chrome window (navigated it) — pass new_tab to open another`
|
|
201
|
+
: `opened NEW tab ${id} in gu's own Chrome window because ${newTab ? "new_tab was set" : "gu had no tab open yet"}`);
|
|
200
202
|
return id;
|
|
201
203
|
},
|
|
202
204
|
tabs: async () => (await this.pages()).map((t) => ({ id: t.targetId, title: t.title, url: t.url, current: t.targetId === this.current })),
|
|
@@ -224,6 +226,7 @@ export class OwnChrome {
|
|
|
224
226
|
},
|
|
225
227
|
activate: (id) => this.send("Target.activateTarget", { targetId: id }).catch(() => {}),
|
|
226
228
|
close: (id) => this.send("Target.closeTarget", { targetId: id }),
|
|
229
|
+
takeNotes: () => (this.notes ??= []).splice(0),
|
|
227
230
|
};
|
|
228
231
|
}
|
|
229
232
|
|
|
@@ -303,7 +303,9 @@ async function after(host, tabId, extra = {}) {
|
|
|
303
303
|
const dl = dialogs.get(tabId) || [];
|
|
304
304
|
freshErrors.delete(tabId);
|
|
305
305
|
dialogs.delete(tabId);
|
|
306
|
-
|
|
306
|
+
// GH #428: why a tab was opened or adopted, so the user and the model are never left guessing.
|
|
307
|
+
const notes = host.takeNotes ? host.takeNotes() : [];
|
|
308
|
+
return { tab: tabId, url: t?.url || "", title: t?.title || "", errors: errs, dialogs: dl, notes, ...extra };
|
|
307
309
|
}
|
|
308
310
|
|
|
309
311
|
export async function runAction(cmd, host) {
|
|
@@ -314,12 +316,15 @@ export async function runAction(cmd, host) {
|
|
|
314
316
|
const id = await host.open(url, Boolean(cmd.new_tab));
|
|
315
317
|
await host.attach(id);
|
|
316
318
|
await waitLoaded(host, id);
|
|
319
|
+
if (cmd.focus) await host.activate(id); // opt-in (GH #428): show the user where gu works
|
|
317
320
|
return after(host, id);
|
|
318
321
|
}
|
|
319
322
|
if (a === "tabs") return { tabs: await host.tabs() };
|
|
323
|
+
if (a === "cleanup") return host.cleanup ? host.cleanup() : { closed: [], released: [] }; // end of turn (GH #428)
|
|
320
324
|
if (a === "switch") {
|
|
321
325
|
const id = cmd.tab;
|
|
322
326
|
if (!(await host.switchTo(id))) throw new Error(`tab ${cmd.tab} is not one of gu's tabs — see action "tabs"`);
|
|
327
|
+
if (cmd.focus) await host.activate(Number.isNaN(Number(id)) ? id : Number(id));
|
|
323
328
|
return after(host, id);
|
|
324
329
|
}
|
|
325
330
|
const id = await host.current();
|
|
@@ -19,6 +19,7 @@ let ws = null;
|
|
|
19
19
|
let connecting = false; // set before the first await: startup fires connect() several times at once
|
|
20
20
|
let pingTimer = null;
|
|
21
21
|
const attached = new Set();
|
|
22
|
+
const notes = []; // why gu opened or adopted a tab — handed to the next command's answer (GH #428)
|
|
22
23
|
|
|
23
24
|
// ── connection ──────────────────────────────────────────────────────────────────────────────
|
|
24
25
|
async function bridgePort() {
|
|
@@ -94,7 +95,8 @@ chrome.runtime.onMessage.addListener((msg, _sender, reply) => {
|
|
|
94
95
|
} else if (msg?.type === "share") {
|
|
95
96
|
// "Let gu use this tab" (#150): the user hands gu a tab of their own.
|
|
96
97
|
addToGroup(msg.tabId)
|
|
97
|
-
.then(() =>
|
|
98
|
+
.then(() => state())
|
|
99
|
+
.then((s) => saveState({ current: msg.tabId, shared: s.shared.includes(msg.tabId) ? s.shared : [...s.shared, msg.tabId] }))
|
|
98
100
|
.then(() => reply({ ok: true }), (e) => reply({ ok: false, error: String(e?.message || e) }));
|
|
99
101
|
return true;
|
|
100
102
|
} else if (msg?.type === "unshare") {
|
|
@@ -124,8 +126,8 @@ async function onCommand(sock, data) {
|
|
|
124
126
|
|
|
125
127
|
// ── gu's tabs ───────────────────────────────────────────────────────────────────────────────
|
|
126
128
|
async function state() {
|
|
127
|
-
const s = await chrome.storage.session.get(["tabs", "current", "group"]);
|
|
128
|
-
return { tabs: s.tabs || [], current: s.current ?? null, group: s.group ?? null };
|
|
129
|
+
const s = await chrome.storage.session.get(["tabs", "current", "group", "shared"]);
|
|
130
|
+
return { tabs: s.tabs || [], current: s.current ?? null, group: s.group ?? null, shared: s.shared || [] };
|
|
129
131
|
}
|
|
130
132
|
|
|
131
133
|
async function saveState(patch) {
|
|
@@ -162,7 +164,7 @@ async function addToGroup(tabId) {
|
|
|
162
164
|
// "Stop sharing": the tab leaves the group, gu lets go of it, and never touches it again.
|
|
163
165
|
async function unshare(tabId) {
|
|
164
166
|
const s = await state();
|
|
165
|
-
await saveState({ tabs: s.tabs.filter((t) => t !== tabId), current: s.current === tabId ? null : s.current });
|
|
167
|
+
await saveState({ tabs: s.tabs.filter((t) => t !== tabId), shared: s.shared.filter((t) => t !== tabId), current: s.current === tabId ? null : s.current });
|
|
166
168
|
await chrome.tabs.ungroup(tabId).catch(() => {});
|
|
167
169
|
if (attached.has(tabId)) await chrome.debugger.detach({ tabId }).catch(() => {});
|
|
168
170
|
attached.delete(tabId);
|
|
@@ -175,6 +177,7 @@ chrome.tabs.onCreated.addListener(async (tab) => {
|
|
|
175
177
|
if (tab.openerTabId != null && s.tabs.includes(tab.openerTabId)) {
|
|
176
178
|
await addToGroup(tab.id).catch(() => {});
|
|
177
179
|
await saveState({ current: tab.id });
|
|
180
|
+
notes.push(`tab ${tab.id} was opened by gu's tab ${tab.openerTabId} (link or popup) — added to gu's group and now gu's current tab`);
|
|
178
181
|
}
|
|
179
182
|
});
|
|
180
183
|
|
|
@@ -211,17 +214,23 @@ const host = {
|
|
|
211
214
|
let tab = newTab ? null : tabs.find((t) => t.id === s.current) || tabs[tabs.length - 1];
|
|
212
215
|
// #422: never bring the tab or the window to the front — gu drives it over the debugger, which
|
|
213
216
|
// works on a background tab, so the user's own tab and window keep the focus.
|
|
214
|
-
if (tab)
|
|
215
|
-
|
|
217
|
+
if (tab) {
|
|
218
|
+
tab = await chrome.tabs.update(tab.id, { url });
|
|
219
|
+
notes.push(`reused gu's current tab ${tab.id} (navigated it) — pass new_tab to open another`);
|
|
220
|
+
} else {
|
|
216
221
|
tab = await chrome.tabs.create({ url, active: false });
|
|
217
222
|
await addToGroup(tab.id);
|
|
223
|
+
notes.push(`opened NEW tab ${tab.id} in the "gu" group because ${newTab ? "new_tab was set" : "gu had no tab open yet"}`);
|
|
218
224
|
}
|
|
219
225
|
await saveState({ current: tab.id });
|
|
220
226
|
return tab.id;
|
|
221
227
|
},
|
|
222
228
|
async tabs() {
|
|
223
229
|
const s = await state();
|
|
224
|
-
|
|
230
|
+
const live = await liveTabs();
|
|
231
|
+
// Same rule as current(): when the stored current tab is gone, gu acts on the last tab, so mark that one.
|
|
232
|
+
const curId = (live.find((t) => t.id === s.current) || live[live.length - 1] || {}).id;
|
|
233
|
+
return live.map((t) => ({ id: t.id, title: t.title, url: t.url, current: t.id === curId, shared: s.shared.includes(t.id) }));
|
|
225
234
|
},
|
|
226
235
|
async switchTo(tabId) {
|
|
227
236
|
const id = Number(tabId);
|
|
@@ -245,6 +254,33 @@ const host = {
|
|
|
245
254
|
async close(tabId) {
|
|
246
255
|
await chrome.tabs.remove(tabId);
|
|
247
256
|
},
|
|
257
|
+
takeNotes() {
|
|
258
|
+
return notes.splice(0);
|
|
259
|
+
},
|
|
260
|
+
// End of a turn (GH #428): close the tabs gu opened; a tab the user shared is only let go of
|
|
261
|
+
// (taken out of the group, debugger detached) and stays open.
|
|
262
|
+
async cleanup() {
|
|
263
|
+
const s = await state();
|
|
264
|
+
const closed = [];
|
|
265
|
+
const released = [];
|
|
266
|
+
for (const id of s.tabs) {
|
|
267
|
+
if (s.shared.includes(id)) {
|
|
268
|
+
await unshare(id).catch(() => {});
|
|
269
|
+
released.push(id);
|
|
270
|
+
} else {
|
|
271
|
+
try {
|
|
272
|
+
await chrome.tabs.remove(id);
|
|
273
|
+
closed.push(id);
|
|
274
|
+
} catch {
|
|
275
|
+
/* already closed */
|
|
276
|
+
}
|
|
277
|
+
attached.delete(id);
|
|
278
|
+
forgetTab(id);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
await saveState({ tabs: [], shared: [], current: null, group: null });
|
|
282
|
+
return { closed, released };
|
|
283
|
+
},
|
|
248
284
|
};
|
|
249
285
|
|
|
250
286
|
async function run(cmd) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"manifest_version": 3,
|
|
3
3
|
"name": "gu browser",
|
|
4
|
-
"version": "1.0.
|
|
4
|
+
"version": "1.0.9",
|
|
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/gonext_agent_chat.py
CHANGED
|
@@ -3239,6 +3239,53 @@ def _output_limit_from_error(text) -> int:
|
|
|
3239
3239
|
return 0
|
|
3240
3240
|
|
|
3241
3241
|
|
|
3242
|
+
_DEEPSEEK_V4_RE = re.compile(r"deepseek[-_.]?v4", re.I)
|
|
3243
|
+
# Hosts known to take DeepSeek's own `thinking` request field (GH #430). Another host serving the
|
|
3244
|
+
# same model (OpenRouter, Together, vLLM…) spells the switch differently or not at all, so it
|
|
3245
|
+
# keeps today's request unchanged unless GONEXT_DEEPSEEK_THINKING=off forces the field.
|
|
3246
|
+
_DEEPSEEK_THINKING_HOSTS = frozenset({"api.deepseek.com", "token-plan.maas.qwencloudapi.com"})
|
|
3247
|
+
|
|
3248
|
+
|
|
3249
|
+
def _deepseek_thinking_kwargs(model_id, base_url="", env=None) -> dict:
|
|
3250
|
+
"""Request fields that turn DeepSeek V4's thinking OFF in the coding loop (GH #430), or {}.
|
|
3251
|
+
|
|
3252
|
+
Thinking is on by default for DeepSeek V4. gu's loop is TEXT tool calls (<code> blocks, no
|
|
3253
|
+
`tools` field); with thinking on, the model drifts into its NATIVE tool format (DSML markup),
|
|
3254
|
+
restates the task every step and sometimes ends with no answer.
|
|
3255
|
+
|
|
3256
|
+
GONEXT_DEEPSEEK_THINKING: unset → only on a host in _DEEPSEEK_THINKING_HOSTS; "off" → any
|
|
3257
|
+
host; "on" → never (provider default). Every other model gets {}. A host that rejects the
|
|
3258
|
+
field has it dropped once and remembered (_repair_request / _apply_request_shape)."""
|
|
3259
|
+
env = os.environ if env is None else env
|
|
3260
|
+
if not _DEEPSEEK_V4_RE.search(str(model_id or "")):
|
|
3261
|
+
return {}
|
|
3262
|
+
mode = str(env.get("GONEXT_DEEPSEEK_THINKING", "")).strip().lower()
|
|
3263
|
+
if mode in ("on", "1", "true", "yes"):
|
|
3264
|
+
return {}
|
|
3265
|
+
if mode not in ("off", "0", "false", "no"):
|
|
3266
|
+
from urllib.parse import urlparse
|
|
3267
|
+
host = (urlparse(str(base_url or "")).hostname or "").lower().rstrip(".")
|
|
3268
|
+
if host not in _DEEPSEEK_THINKING_HOSTS:
|
|
3269
|
+
return {}
|
|
3270
|
+
return {"extra_body": {"thinking": {"type": "disabled"}}}
|
|
3271
|
+
|
|
3272
|
+
|
|
3273
|
+
def _coding_extra_kwargs(ollama_tweaks: bool, base_url, model_id, env=None):
|
|
3274
|
+
"""Extra request fields for the coding model → (kwargs, log line or ""). Pure, so the whole
|
|
3275
|
+
provider matrix is testable (tests/test_coding_extra_kwargs_430.py): ONLY an Ollama server
|
|
3276
|
+
and DeepSeek V4 on an allowed host get anything; every other provider gets {}."""
|
|
3277
|
+
if ollama_tweaks:
|
|
3278
|
+
return ({"reasoning_effort": "none"},
|
|
3279
|
+
"coding server is Ollama → reasoning_effort='none' (disable thinking) + streaming")
|
|
3280
|
+
if _is_anthropic_url(base_url):
|
|
3281
|
+
return {}, ""
|
|
3282
|
+
ds = _deepseek_thinking_kwargs(model_id, base_url, env)
|
|
3283
|
+
if ds:
|
|
3284
|
+
return ds, ("coding model is DeepSeek V4 → thinking off for the tool loop (GH #430; "
|
|
3285
|
+
"GONEXT_DEEPSEEK_THINKING=on to keep it)")
|
|
3286
|
+
return {}, ""
|
|
3287
|
+
|
|
3288
|
+
|
|
3242
3289
|
def _repair_request(kwargs: dict, err):
|
|
3243
3290
|
"""One fix for a 400 that rejected the request SHAPE. Pure.
|
|
3244
3291
|
|
|
@@ -3272,7 +3319,16 @@ def _repair_request(kwargs: dict, err):
|
|
|
3272
3319
|
bad = [p for p in _unsupported_sampling_params(err) if p in kw]
|
|
3273
3320
|
if bad:
|
|
3274
3321
|
return _without_params(kw, bad), "drop:" + ",".join(bad)
|
|
3275
|
-
# 4.
|
|
3322
|
+
# 4. a host that does not know DeepSeek's `thinking` field (GH #430)
|
|
3323
|
+
eb = kw.get("extra_body")
|
|
3324
|
+
if isinstance(eb, dict) and "thinking" in eb and "thinking" in msg:
|
|
3325
|
+
eb = {k: v for k, v in eb.items() if k != "thinking"}
|
|
3326
|
+
if eb:
|
|
3327
|
+
kw["extra_body"] = eb
|
|
3328
|
+
else:
|
|
3329
|
+
kw.pop("extra_body")
|
|
3330
|
+
return kw, "drop:thinking"
|
|
3331
|
+
# 5. any other optional field the provider says it does not know
|
|
3276
3332
|
if rejects:
|
|
3277
3333
|
names = [n for n in re.findall(r"['\"`]([a-z_]+)['\"`]", msg)
|
|
3278
3334
|
if n in _DROPPABLE_PARAMS and n in kw]
|
|
@@ -3359,7 +3415,15 @@ def _apply_request_shape(kwargs: dict, key: str, model: str) -> dict:
|
|
|
3359
3415
|
if old in kw and new not in kw:
|
|
3360
3416
|
kw[new] = kw.pop(old)
|
|
3361
3417
|
for p in entry.get("drop") or []:
|
|
3362
|
-
if p
|
|
3418
|
+
if p == "thinking" and isinstance(kw.get("extra_body"), dict):
|
|
3419
|
+
# Lives INSIDE extra_body (GH #430): a top-level pop would miss it and every
|
|
3420
|
+
# request would pay the 400 again.
|
|
3421
|
+
eb = {k: v for k, v in kw["extra_body"].items() if k != "thinking"}
|
|
3422
|
+
if eb:
|
|
3423
|
+
kw["extra_body"] = eb
|
|
3424
|
+
else:
|
|
3425
|
+
kw.pop("extra_body")
|
|
3426
|
+
elif p not in ("model", "messages", "stream"):
|
|
3363
3427
|
kw.pop(p, None)
|
|
3364
3428
|
return _clamp_output_budget(kw, model, entry.get("max_out") or 0)
|
|
3365
3429
|
|
|
@@ -3409,6 +3473,9 @@ def _create_with_repair(client, **kwargs):
|
|
|
3409
3473
|
elif action.startswith("clamp:"):
|
|
3410
3474
|
_log(f"model {model!r} caps its output at {new_kw[action[6:]]} tokens; "
|
|
3411
3475
|
"retrying with it (remembered)")
|
|
3476
|
+
elif action == "drop:thinking":
|
|
3477
|
+
_log(f"host rejects the thinking field for {model!r}; retrying without it "
|
|
3478
|
+
"(remembered, GH #430)")
|
|
3412
3479
|
else:
|
|
3413
3480
|
_log(f"model {model!r} rejects {', '.join(dropped)}; "
|
|
3414
3481
|
"retrying at the model's own default")
|
|
@@ -4789,8 +4856,16 @@ def _fallback_recap(steps, last_text="") -> str:
|
|
|
4789
4856
|
tried = []
|
|
4790
4857
|
for st in (steps or [])[-8:]:
|
|
4791
4858
|
did = str(st.get("did") or "").strip().replace(chr(10), " ")
|
|
4792
|
-
|
|
4793
|
-
|
|
4859
|
+
# A whole identifier only (GH #430): the old pattern matched the tail of "Image(" as
|
|
4860
|
+
# "mage(" and always picked the wrapper "print(" — useless labels like
|
|
4861
|
+
# "- mage(contentsOfFile: path)". Skip print/len/str wrappers, take the tool call.
|
|
4862
|
+
label = ""
|
|
4863
|
+
for m in re.finditer(r"(?<![\w.])([a-z_][a-z0-9_]*)\(", did):
|
|
4864
|
+
if m.group(1) not in ("print", "len", "str", "repr", "list", "dict", "int", "sorted"):
|
|
4865
|
+
label = did[m.start():m.start() + 70].strip()
|
|
4866
|
+
break
|
|
4867
|
+
if not label:
|
|
4868
|
+
label = did[:70].strip()
|
|
4794
4869
|
if label:
|
|
4795
4870
|
tried.append("- " + label)
|
|
4796
4871
|
last = str(last_text or "").strip()
|
|
@@ -4804,6 +4879,15 @@ def _fallback_recap(steps, last_text="") -> str:
|
|
|
4804
4879
|
return chr(10).join(out)
|
|
4805
4880
|
|
|
4806
4881
|
|
|
4882
|
+
def _answer_is_blank(answer) -> bool:
|
|
4883
|
+
"""True when a final answer shows the user nothing: None, whitespace, or only tool-call
|
|
4884
|
+
markup that _strip_tool_tags removes (GH #430)."""
|
|
4885
|
+
try:
|
|
4886
|
+
return not _strip_tool_tags(_humanize_answer(answer).strip())
|
|
4887
|
+
except Exception: # noqa: BLE001
|
|
4888
|
+
return not str(answer or "").strip()
|
|
4889
|
+
|
|
4890
|
+
|
|
4807
4891
|
def _humanize_answer(result) -> str:
|
|
4808
4892
|
"""Task #131: a final answer that is a dict/list (or a string that is just a JSON /
|
|
4809
4893
|
Python-dict literal, as DeepSeek produces) is rendered as readable markdown instead of
|
|
@@ -13040,6 +13124,17 @@ def run_agent_chat(cfg):
|
|
|
13040
13124
|
def _final_answer_gate(final_answer, memory, agent=None):
|
|
13041
13125
|
"""smolagents final_answer_check. True = accept; raising = reject with the message
|
|
13042
13126
|
the model then sees. Only nudges when the answer hands the job back to the user."""
|
|
13127
|
+
# GH #430: an answer that is empty, or only tool-call markup the user never sees,
|
|
13128
|
+
# goes back to the model ONCE — it still has the whole turn in context, unlike any
|
|
13129
|
+
# repair after the run. Its own flag, so it never uses up the punt nudge below.
|
|
13130
|
+
if _answer_is_blank(final_answer) and not _completion_gate.get("blank_nudged"):
|
|
13131
|
+
_completion_gate["blank_nudged"] = True
|
|
13132
|
+
_log("final_answer was empty or only tool-call markup → asking for the answer (GH #430)")
|
|
13133
|
+
raise ValueError(
|
|
13134
|
+
"Your final_answer is EMPTY (or only tool-call markup, which the user never sees). "
|
|
13135
|
+
"Call final_answer again with the actual answer to the user's question, in plain "
|
|
13136
|
+
"words, based on what your steps found. If the work is unfinished, say what is "
|
|
13137
|
+
"done and what is left.")
|
|
13043
13138
|
if _completion_gate["nudged"]:
|
|
13044
13139
|
return True # already nudged once this turn — accept, never loop
|
|
13045
13140
|
ans = str(final_answer if final_answer is not None else "")
|
|
@@ -14782,12 +14877,12 @@ def run_agent_chat(cfg):
|
|
|
14782
14877
|
# honor reasoning_effort="none". Thinking burned ~430 of 487 output tokens in
|
|
14783
14878
|
# the live test — minutes per step on a slow GPU — so disable it explicitly.
|
|
14784
14879
|
# Sniffed per-server because MLX might reject the unknown param.
|
|
14785
|
-
extra_model_kwargs = {}
|
|
14786
14880
|
# `coding_backend` was resolved once, above, and `coding_flags` derives everything
|
|
14787
14881
|
# from it — do NOT re-derive any of this from the kind or a URL sniff here.
|
|
14788
|
-
|
|
14789
|
-
|
|
14790
|
-
|
|
14882
|
+
extra_model_kwargs, _extra_why = _coding_extra_kwargs(
|
|
14883
|
+
coding_flags["ollama_tweaks"], coding_base_url, coding_model_id)
|
|
14884
|
+
if _extra_why:
|
|
14885
|
+
_log(_extra_why)
|
|
14791
14886
|
_stream_coder = coding_flags["stream"]
|
|
14792
14887
|
_log(f"coding backend: {coding_backend} ({_backend_why}; "
|
|
14793
14888
|
f"kind={coding_kind or 'auto'}, {_host_of(coding_base_url)}) "
|
|
@@ -16879,7 +16974,7 @@ def run_agent_chat(cfg):
|
|
|
16879
16974
|
def browser(action: str, url: str = "", ref: int = 0, x: int = -1, y: int = -1,
|
|
16880
16975
|
text: str = "", clear: bool = False, submit: bool = False,
|
|
16881
16976
|
direction: str = "", amount: int = 0, seconds: int = 0, tab: str = "",
|
|
16882
|
-
new_tab: bool = False) -> str:
|
|
16977
|
+
new_tab: bool = False, focus: bool = False) -> str:
|
|
16883
16978
|
"""Use a REAL Chrome browser like a person does — open a page, see it, click with the mouse, type with the keyboard — to test a UI flow, check a page renders, fill a form or click through an app. The first call asks the user's permission. It uses the user's Chrome through the gu extension when that is installed, otherwise gu's own Chrome window (a separate profile: not logged in to the user's accounts). Loop: open → read (or screenshot) → click / type → read again to check what happened. Only gu's own tabs, and tabs the user shared, are used. If the answer starts BROWSER NOT AVAILABLE, stop and tell the user (the answer says what to do).
|
|
16884
16979
|
|
|
16885
16980
|
Args:
|
|
@@ -16896,6 +16991,7 @@ def run_agent_chat(cfg):
|
|
|
16896
16991
|
seconds: wait only — 1 to 30
|
|
16897
16992
|
tab: switch only — a tab id from tabs (a number, or an id like "8F3A…" in gu's own window)
|
|
16898
16993
|
new_tab: open only — open in a new tab instead of the current gu tab
|
|
16994
|
+
focus: open / switch only — also bring that tab to the front so the user can see where gu works (off by default: the user's own tab keeps the focus)
|
|
16899
16995
|
"""
|
|
16900
16996
|
import gu_browser as _gb
|
|
16901
16997
|
a = (action or "").strip().lower().replace(" ", "_").replace("-", "_")
|
|
@@ -16914,7 +17010,7 @@ def run_agent_chat(cfg):
|
|
|
16914
17010
|
cmd["x"], cmd["y"] = float(x), float(y)
|
|
16915
17011
|
if text:
|
|
16916
17012
|
cmd["text"] = str(text)
|
|
16917
|
-
for k, v in (("clear", clear), ("submit", submit), ("new_tab", new_tab)):
|
|
17013
|
+
for k, v in (("clear", clear), ("submit", submit), ("new_tab", new_tab), ("focus", focus)):
|
|
16918
17014
|
if v:
|
|
16919
17015
|
cmd[k] = True
|
|
16920
17016
|
if direction:
|
|
@@ -16942,8 +17038,9 @@ def run_agent_chat(cfg):
|
|
|
16942
17038
|
_browser_consent["ext_checked"] = True
|
|
16943
17039
|
_ext_ok, _browser_consent["ext_note"] = _gb.ensure_extension(
|
|
16944
17040
|
log=_log, emit=lambda t: _emit({"type": "step", "text": t}))
|
|
17041
|
+
# GH #428: GU_BROWSER_FALLBACK=off stops gu from silently using its own Chrome window.
|
|
16945
17042
|
ok, res, not_connected = _gb.command(
|
|
16946
|
-
cmd, log=_log, own=
|
|
17043
|
+
cmd, log=_log, own=_gb.own_allowed(),
|
|
16947
17044
|
on_wait=lambda: _emit({"type": "step", "text": "Waiting for Chrome to connect…"}))
|
|
16948
17045
|
where = res.pop("_backend", "") if ok and isinstance(res, dict) else ""
|
|
16949
17046
|
if where and where != _browser_consent["where"]:
|
|
@@ -16966,10 +17063,14 @@ def run_agent_chat(cfg):
|
|
|
16966
17063
|
+ _gb.format_result("read", res))
|
|
16967
17064
|
else:
|
|
16968
17065
|
msg = _gb.format_result(a, res)
|
|
17066
|
+
if a == "tabs":
|
|
17067
|
+
_pl = _gb.profile_line() # GH #428: which Chrome profile/extension gu is using
|
|
17068
|
+
if _pl:
|
|
17069
|
+
msg += "\n" + _pl
|
|
16969
17070
|
if a in ("open", "click", "double_click", "right_click", "type", "key", "back", "reload"):
|
|
16970
17071
|
# GH #421: show the page after an action, so the model needs no extra `read` step
|
|
16971
17072
|
try:
|
|
16972
|
-
ok2, res2, _nc2 = _gb.command({"action": "read"}, log=_log, own=
|
|
17073
|
+
ok2, res2, _nc2 = _gb.command({"action": "read"}, log=_log, own=_gb.own_allowed())
|
|
16973
17074
|
if ok2 and isinstance(res2, dict):
|
|
16974
17075
|
res2.pop("_backend", None)
|
|
16975
17076
|
msg = msg.replace("\n(read or screenshot to see the page now)", "") \
|
|
@@ -16977,8 +17078,8 @@ def run_agent_chat(cfg):
|
|
|
16977
17078
|
except Exception: # noqa: BLE001
|
|
16978
17079
|
pass
|
|
16979
17080
|
if ok and where == "chrome" and a == "open":
|
|
16980
|
-
msg = ("(gu's own Chrome window — a separate
|
|
16981
|
-
"accounts.)\n" + msg)
|
|
17081
|
+
msg = ("(NO gu extension is connected, so this is gu's own Chrome window — a separate "
|
|
17082
|
+
"profile, NOT signed in to the user's accounts. Say so if it matters to the task.)\n" + msg)
|
|
16982
17083
|
if ok and where == "chrome" and _browser_consent.get("ext_note"):
|
|
16983
17084
|
msg = _browser_consent.pop("ext_note") + "\n" + msg
|
|
16984
17085
|
except Exception as ex: # noqa: BLE001
|
|
@@ -17341,10 +17442,23 @@ def run_agent_chat(cfg):
|
|
|
17341
17442
|
_emit({"type": "step", "text": _retr})
|
|
17342
17443
|
_log(f"retrieval summary: {_c(_retr)}")
|
|
17343
17444
|
_emit({"type": "step", "text": "Composing answer…"})
|
|
17344
|
-
|
|
17445
|
+
# GH #430: a blank final_answer was already sent back once by _final_answer_gate (the
|
|
17446
|
+
# model still had the turn in context then). No context-free summary call here — it
|
|
17447
|
+
# could claim work it never verified. What is left is the honest recap.
|
|
17448
|
+
final_text = _strip_tool_tags(_humanize_answer(result).strip())
|
|
17449
|
+
final_text = (final_text
|
|
17345
17450
|
or _fallback_recap(_turn_steps, _last_obs.get("text"))
|
|
17346
17451
|
or "[No result]")
|
|
17347
17452
|
_log(f"done (deterministic, no summarizer call): {len(final_text)} chars")
|
|
17453
|
+
# GH #428: close the Chrome tabs gu opened this turn (shared tabs are only let go of).
|
|
17454
|
+
try:
|
|
17455
|
+
if _browser_consent.get("ok"):
|
|
17456
|
+
import gu_browser as _gb_end
|
|
17457
|
+
_ct = _gb_end.cleanup(log=_log)
|
|
17458
|
+
if _ct:
|
|
17459
|
+
_log(f"browser cleanup: {_ct}")
|
|
17460
|
+
except Exception as _ce: # noqa: BLE001
|
|
17461
|
+
_log(f"browser cleanup skipped: {type(_ce).__name__}: {_ce}")
|
|
17348
17462
|
_emit({"type": "final", "text": final_text})
|
|
17349
17463
|
# onTurnEnd (task #270): after the answer is out, so a slow hook never delays it.
|
|
17350
17464
|
if _hooks and _hooks.has("onTurnEnd"):
|
package/gu-repl.mjs
CHANGED
|
@@ -139,6 +139,7 @@ import {
|
|
|
139
139
|
CANCEL_LINE,
|
|
140
140
|
shouldCancelPrompt,
|
|
141
141
|
rankSlashCommands,
|
|
142
|
+
autoSelectSlash,
|
|
142
143
|
slashMenuWindow,
|
|
143
144
|
trimWords,
|
|
144
145
|
} from "./terminal-layout.mjs";
|
|
@@ -156,6 +157,7 @@ import { readHooks } from "./hooks-config.mjs";
|
|
|
156
157
|
import { readSkillSource, sourceLabel, SKILL_SOURCE_KEY } from "./skill-source.mjs";
|
|
157
158
|
import { codingBannerLabel, isOllamaCloudUrl, SECRET_KEY_HINT } from "./coding-key-prompt.mjs";
|
|
158
159
|
import { questionEchoText, thoughtPrintSeq, wrapDiffText } from "./terminal-layout.mjs";
|
|
160
|
+
import { createTurnQueue, queuedNotice, typingNotice, droppedNote } from "./turn-queue.mjs"; // GH #429: questions typed during a turn wait here
|
|
159
161
|
import { globalPrefixOf } from "./install-path.mjs";
|
|
160
162
|
import { indentBlock, commandBlockRows, wrapIndented } from "./terminal-layout.mjs"; // every line of an Allow-prompt detail indented (#189); wrapped + collapsible command (#204)
|
|
161
163
|
import { firstGuOnPath, pathGuMismatch, guOnPathIsCurrent, updateAttemptRecord, repeatUpdateNotice } from "./update-verify.mjs";
|
|
@@ -2149,6 +2151,15 @@ const describeApiFailure = (err, what) => {
|
|
|
2149
2151
|
return `${what}: ${err?.message ?? err}`;
|
|
2150
2152
|
};
|
|
2151
2153
|
const _lineQueue = [];
|
|
2154
|
+
// GH #429: lines submitted WHILE A TURN RUNS wait here (FIFO); the main loop runs them one by one
|
|
2155
|
+
// after the turn. Kept apart from _lineQueue, which every failed turn empties on purpose (#92).
|
|
2156
|
+
const turnQueue = createTurnQueue();
|
|
2157
|
+
/** A turn that did not finish throws its queued questions away — say how many, once. */
|
|
2158
|
+
function dropQueuedQuestions() {
|
|
2159
|
+
const n = turnQueue.clear();
|
|
2160
|
+
if (n > 0) console.log(GUTTER + dim(droppedNote(n)));
|
|
2161
|
+
return n;
|
|
2162
|
+
}
|
|
2152
2163
|
// EVERY reader waiting for a submitted line, innermost LAST (task #182 follow-up).
|
|
2153
2164
|
//
|
|
2154
2165
|
// This was ONE slot, and a second reader silently overwrote the first. That is fine while every
|
|
@@ -2180,17 +2191,25 @@ rl.on("line", (l) => {
|
|
|
2180
2191
|
rl.cursor = 0;
|
|
2181
2192
|
return;
|
|
2182
2193
|
}
|
|
2183
|
-
// While a turn is running,
|
|
2184
|
-
//
|
|
2185
|
-
//
|
|
2194
|
+
// While a turn is running, Enter QUEUES what was typed (GH #429; it used to be dropped, #92/#258).
|
|
2195
|
+
// The main loop runs the queue one question at a time after the turn. Ctrl+C aborts the turn
|
|
2196
|
+
// AND empties the queue. An empty Enter is ignored.
|
|
2186
2197
|
if (following) {
|
|
2187
2198
|
rl.line = "";
|
|
2188
2199
|
rl.cursor = 0;
|
|
2189
|
-
|
|
2190
|
-
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
|
|
2200
|
+
const queued = imageStore.expand(expandPasteTokens(stripAnsiEscapes(l))).trim();
|
|
2201
|
+
imageStore.clear();
|
|
2202
|
+
typedDuringTurn = false;
|
|
2203
|
+
turnTyping.reset();
|
|
2204
|
+
if (queued) {
|
|
2205
|
+
if (turnQueue.push(queued)) {
|
|
2206
|
+
// No frozen row to carry the count (piped, or a window too short to pin one): say it here.
|
|
2207
|
+
if (barPinned()) paintBar();
|
|
2208
|
+
else process.stdout.write(dim(`\n (queued — ${turnQueue.size} waiting; runs when this turn finishes)\n`));
|
|
2209
|
+
} else {
|
|
2210
|
+
process.stdout.write(dim(`\n (${turnQueue.size} questions are already queued — wait for one to run)\n`));
|
|
2211
|
+
}
|
|
2212
|
+
} else if (barPinned()) paintBar();
|
|
2194
2213
|
return;
|
|
2195
2214
|
}
|
|
2196
2215
|
// Enter left the cursor on the row where the live slash-hint started — erase it so the
|
|
@@ -2342,6 +2361,9 @@ function renderSlashOverlay(sel) {
|
|
|
2342
2361
|
const line = rl.line;
|
|
2343
2362
|
const cmds = rankSlashCommands(allCommands(), line);
|
|
2344
2363
|
slashNames = cmds.map((c) => c.name);
|
|
2364
|
+
// Nothing picked with ↑/↓: highlight the one command the typed text can only mean ("/mo" → /model),
|
|
2365
|
+
// so Enter runs it instead of submitting the unfinished "/mo".
|
|
2366
|
+
if (sel < 0) sel = autoSelectSlash(cmds, line);
|
|
2345
2367
|
if (sel >= cmds.length) sel = cmds.length - 1;
|
|
2346
2368
|
slashSel = sel;
|
|
2347
2369
|
slashPrefix = line;
|
|
@@ -3270,8 +3292,8 @@ function frozenZone() {
|
|
|
3270
3292
|
// sits in the scrolling output while the caret lives down here, so with the echo muted at
|
|
3271
3293
|
// BOTH ends the terminal reacted to a keystroke in no visible way at all. One bullet per
|
|
3272
3294
|
// character, so the row cannot carry the key and typing is still obviously working.
|
|
3273
|
-
line: inputLineFor({ line: rl.line, visible: inputVisible, secret: secretInput }),
|
|
3274
|
-
cursor: inputVisible ? rl.cursor ?? rl.line.length : 0,
|
|
3295
|
+
line: inputLineFor({ line: rl.line, visible: inputVisible || (following && typedDuringTurn), secret: secretInput }),
|
|
3296
|
+
cursor: inputVisible || (following && typedDuringTurn) ? rl.cursor ?? rl.line.length : 0,
|
|
3275
3297
|
rule: (w) => dim("─".repeat(w)),
|
|
3276
3298
|
maxRows: maxInputRows(),
|
|
3277
3299
|
// The typed line is selectable too (task #177), and the highlight is applied HERE rather
|
|
@@ -4808,13 +4830,20 @@ if (process.stdin.isTTY) {
|
|
|
4808
4830
|
// be sent — say so in the input row now, not after they have typed the whole thing (#258).
|
|
4809
4831
|
// Not every printable key is typing: a mouse report or cursor reply whose ESC came alone
|
|
4810
4832
|
// arrives as "[", "^[[", "[12;5R" (Windows, GH #382) — the detector sits those out.
|
|
4811
|
-
if (turnTyping.feed(_ch, key) && !typedDuringTurn)
|
|
4812
|
-
|
|
4813
|
-
|
|
4833
|
+
if (turnTyping.feed(_ch, key) && !typedDuringTurn) typedDuringTurn = true;
|
|
4834
|
+
// GH #429: once the user is really typing, the line is a DRAFT for the queue — kept and drawn
|
|
4835
|
+
// in the input row; Enter queues it. Before that (terminal replies, nav keys) it stays wiped.
|
|
4836
|
+
if (typedDuringTurn) {
|
|
4837
|
+
if (key && (key.name === "up" || key.name === "down")) {
|
|
4838
|
+
rl.line = turnDraft; // history recall is not typing — put the draft back
|
|
4839
|
+
rl.cursor = rl.line.length;
|
|
4840
|
+
} else turnDraft = rl.line;
|
|
4841
|
+
} else {
|
|
4842
|
+
rl.line = "";
|
|
4843
|
+
rl.cursor = 0;
|
|
4814
4844
|
}
|
|
4815
|
-
rl.line = "";
|
|
4816
|
-
rl.cursor = 0;
|
|
4817
4845
|
rl.historyIndex = -1;
|
|
4846
|
+
if (barPinned()) paintBar();
|
|
4818
4847
|
return;
|
|
4819
4848
|
}
|
|
4820
4849
|
// AT THE PROMPT, Ctrl+T opens the newest printed thought block (task #148) — the no-mouse
|
|
@@ -5434,9 +5463,24 @@ async function ensureWorkspace() {
|
|
|
5434
5463
|
// python side already uses for per-URL RAG work dirs (sha256, 32 hex chars), applied
|
|
5435
5464
|
// here to the workspace path instead so returning to the SAME folder reloads the SAME
|
|
5436
5465
|
// conversation.
|
|
5466
|
+
const _folderHash = (cwd) => createHash("sha256").update(cwd).digest("hex").slice(0, 32);
|
|
5467
|
+
/** The per-folder shared file — preferences only (coding model, keys, settings). */
|
|
5468
|
+
function folderSessionPath(cwd) {
|
|
5469
|
+
return join(SESSIONS_DIR, `${_folderHash(cwd)}.json`);
|
|
5470
|
+
}
|
|
5471
|
+
/**
|
|
5472
|
+
* The per-instance file — conversation history belongs here (task #550).
|
|
5473
|
+
*
|
|
5474
|
+
* Two gu terminals in the same folder each get their own history, so save/load
|
|
5475
|
+
* are independent day to day. The old single-file format is migrated on first load
|
|
5476
|
+
* (history key moved from the folder file into the first instance file seen).
|
|
5477
|
+
* Returns the old path when sessionInstanceId is empty (startup, before init), so
|
|
5478
|
+
* the load at line 15148 uses the folder file and migrates.
|
|
5479
|
+
*/
|
|
5437
5480
|
function sessionFilePath(cwd) {
|
|
5438
|
-
|
|
5439
|
-
|
|
5481
|
+
return sessionInstanceId
|
|
5482
|
+
? join(SESSIONS_DIR, `${_folderHash(cwd)}-${sessionInstanceId}.json`)
|
|
5483
|
+
: folderSessionPath(cwd);
|
|
5440
5484
|
}
|
|
5441
5485
|
|
|
5442
5486
|
// Cap what's kept on disk — the worker already truncates what it actually SENDS to the
|
|
@@ -5567,7 +5611,18 @@ async function pushWorkspaceSync(cwd, history, { del = false, key = "", name = "
|
|
|
5567
5611
|
|
|
5568
5612
|
async function loadSession(cwd) {
|
|
5569
5613
|
try {
|
|
5570
|
-
|
|
5614
|
+
// Task #550: history lives in a PER-INSTANCE file now. If the instance file exists,
|
|
5615
|
+
// read from it; otherwise try the OLD folder-level file (first launch after this change).
|
|
5616
|
+
const ip = sessionFilePath(cwd);
|
|
5617
|
+
let raw = null;
|
|
5618
|
+
try { raw = JSON.parse(await readFile(ip, "utf8")); } catch { /* no instance file yet */ }
|
|
5619
|
+
if (raw && Array.isArray(raw.history) && raw.history.length) {
|
|
5620
|
+
// Instance file exists with history — use it.
|
|
5621
|
+
} else if (ip !== folderSessionPath(cwd)) {
|
|
5622
|
+
// Fall back to the old folder-level file, which still carries history for this folder.
|
|
5623
|
+
// Read the history FROM it but leave the rest (preferences) where it is.
|
|
5624
|
+
try { raw = JSON.parse(await readFile(folderSessionPath(cwd), "utf8")); } catch { raw = null; }
|
|
5625
|
+
}
|
|
5571
5626
|
const history = Array.isArray(raw?.history) ? raw.history : [];
|
|
5572
5627
|
// Sessions saved BEFORE task #144 can contain failure banners stored as assistant turns
|
|
5573
5628
|
// ("⚠️ api.moonshot.ai refused: …suspended…"). New ones are dropped at the source, but an
|
|
@@ -5592,7 +5647,7 @@ async function loadSession(cwd) {
|
|
|
5592
5647
|
// the real question instead of being sent to the model as the word "continue".
|
|
5593
5648
|
async function loadSessionUnfinishedTask(cwd) {
|
|
5594
5649
|
try {
|
|
5595
|
-
return unfinishedTaskFromSession(JSON.parse(await readFile(
|
|
5650
|
+
return unfinishedTaskFromSession(JSON.parse(await readFile(folderSessionPath(cwd), "utf8")));
|
|
5596
5651
|
} catch {
|
|
5597
5652
|
return "";
|
|
5598
5653
|
}
|
|
@@ -5647,13 +5702,13 @@ async function updateSessionFile(cwd, mutate) {
|
|
|
5647
5702
|
const run = async () => {
|
|
5648
5703
|
let raw = {};
|
|
5649
5704
|
try {
|
|
5650
|
-
raw = JSON.parse(await readFile(
|
|
5705
|
+
raw = JSON.parse(await readFile(folderSessionPath(cwd), "utf8")) || {};
|
|
5651
5706
|
} catch {
|
|
5652
5707
|
raw = {}; // no file yet, or an unreadable one — a fresh object is the honest start
|
|
5653
5708
|
}
|
|
5654
5709
|
const next = (await mutate(raw)) ?? raw;
|
|
5655
5710
|
await mkdir(SESSIONS_DIR, { recursive: true });
|
|
5656
|
-
const path =
|
|
5711
|
+
const path = folderSessionPath(cwd);
|
|
5657
5712
|
// The pid is in the temp name so two gu processes in the same folder cannot land on
|
|
5658
5713
|
// each other's half-written file — the chain only serializes writes inside ONE process.
|
|
5659
5714
|
const tmp = `${path}.${process.pid}.tmp`;
|
|
@@ -5700,7 +5755,7 @@ async function rememberUnfinishedTask(cwd, task) {
|
|
|
5700
5755
|
// session file). Read it once at startup so the banner and agent-ask reflect it.
|
|
5701
5756
|
async function loadSessionTestAuto(cwd) {
|
|
5702
5757
|
try {
|
|
5703
|
-
const raw = JSON.parse(await readFile(
|
|
5758
|
+
const raw = JSON.parse(await readFile(folderSessionPath(cwd), "utf8"));
|
|
5704
5759
|
return raw?.testAuto === true;
|
|
5705
5760
|
} catch {
|
|
5706
5761
|
return false;
|
|
@@ -5712,7 +5767,7 @@ async function loadSessionTestAuto(cwd) {
|
|
|
5712
5767
|
// lost on restart). Returns {name,host,user} or null.
|
|
5713
5768
|
async function loadSessionServer(cwd) {
|
|
5714
5769
|
try {
|
|
5715
|
-
const raw = JSON.parse(await readFile(
|
|
5770
|
+
const raw = JSON.parse(await readFile(folderSessionPath(cwd), "utf8"));
|
|
5716
5771
|
const s = raw?.deployServer;
|
|
5717
5772
|
return s && typeof s.host === "string" && typeof s.user === "string" ? s : null;
|
|
5718
5773
|
} catch {
|
|
@@ -5729,7 +5784,7 @@ async function loadSessionServer(cwd) {
|
|
|
5729
5784
|
// existed reads as on.
|
|
5730
5785
|
async function loadSessionShowThought(cwd) {
|
|
5731
5786
|
try {
|
|
5732
|
-
const raw = JSON.parse(await readFile(
|
|
5787
|
+
const raw = JSON.parse(await readFile(folderSessionPath(cwd), "utf8"));
|
|
5733
5788
|
return raw?.showThought !== false;
|
|
5734
5789
|
} catch {
|
|
5735
5790
|
return true;
|
|
@@ -5739,7 +5794,7 @@ async function loadSessionShowThought(cwd) {
|
|
|
5739
5794
|
// Peak single-request agent-code-model token count remembered per folder (task #84).
|
|
5740
5795
|
async function loadSessionMaxCodeTokens(cwd) {
|
|
5741
5796
|
try {
|
|
5742
|
-
const raw = JSON.parse(await readFile(
|
|
5797
|
+
const raw = JSON.parse(await readFile(folderSessionPath(cwd), "utf8"));
|
|
5743
5798
|
return Number.isFinite(raw?.maxCodeTokens) ? raw.maxCodeTokens : 0;
|
|
5744
5799
|
} catch {
|
|
5745
5800
|
return 0;
|
|
@@ -5835,7 +5890,7 @@ async function saveSessionCodingKeyId(cwd) {
|
|
|
5835
5890
|
async function loadSessionFolderKeyId(cwd, role) {
|
|
5836
5891
|
const { roleOf } = await import("./server-keys.mjs");
|
|
5837
5892
|
try {
|
|
5838
|
-
const raw = JSON.parse(await readFile(
|
|
5893
|
+
const raw = JSON.parse(await readFile(folderSessionPath(cwd), "utf8"));
|
|
5839
5894
|
const v = raw?.[roleOf(role).field];
|
|
5840
5895
|
return typeof v === "string" ? v.trim() : "";
|
|
5841
5896
|
} catch {
|
|
@@ -5873,7 +5928,7 @@ async function saveFolderKeyPick(role, id) {
|
|
|
5873
5928
|
|
|
5874
5929
|
async function loadSessionCodingKeyId(cwd) {
|
|
5875
5930
|
try {
|
|
5876
|
-
const raw = JSON.parse(await readFile(
|
|
5931
|
+
const raw = JSON.parse(await readFile(folderSessionPath(cwd), "utf8"));
|
|
5877
5932
|
return typeof raw?.codingKeyId === "string" ? raw.codingKeyId.trim() : "";
|
|
5878
5933
|
} catch {
|
|
5879
5934
|
return "";
|
|
@@ -5882,7 +5937,7 @@ async function loadSessionCodingKeyId(cwd) {
|
|
|
5882
5937
|
|
|
5883
5938
|
async function loadSessionCoding(cwd) {
|
|
5884
5939
|
try {
|
|
5885
|
-
const raw = JSON.parse(await readFile(
|
|
5940
|
+
const raw = JSON.parse(await readFile(folderSessionPath(cwd), "utf8"));
|
|
5886
5941
|
const model = typeof raw?.codingModel === "string" ? raw.codingModel.trim() : "";
|
|
5887
5942
|
if (!model) return null;
|
|
5888
5943
|
return {
|
|
@@ -5897,7 +5952,7 @@ async function loadSessionCoding(cwd) {
|
|
|
5897
5952
|
|
|
5898
5953
|
async function loadQuickModels(cwd) {
|
|
5899
5954
|
try {
|
|
5900
|
-
return normalizeQuick(JSON.parse(await readFile(
|
|
5955
|
+
return normalizeQuick(JSON.parse(await readFile(folderSessionPath(cwd), "utf8"))?.quickModels);
|
|
5901
5956
|
} catch {
|
|
5902
5957
|
return [];
|
|
5903
5958
|
}
|
|
@@ -5918,7 +5973,7 @@ async function saveQuickModels(cwd) {
|
|
|
5918
5973
|
* testable; only the file I/O is here. */
|
|
5919
5974
|
async function loadSessionRagStorage(cwd) {
|
|
5920
5975
|
try {
|
|
5921
|
-
return ragStorageFromSession(JSON.parse(await readFile(
|
|
5976
|
+
return ragStorageFromSession(JSON.parse(await readFile(folderSessionPath(cwd), "utf8")));
|
|
5922
5977
|
} catch {
|
|
5923
5978
|
return "local";
|
|
5924
5979
|
}
|
|
@@ -5961,7 +6016,7 @@ async function saveSessionShowThought(cwd, on) {
|
|
|
5961
6016
|
// to prevent.
|
|
5962
6017
|
async function loadSessionSkip(cwd, key) {
|
|
5963
6018
|
try {
|
|
5964
|
-
const raw = JSON.parse(await readFile(
|
|
6019
|
+
const raw = JSON.parse(await readFile(folderSessionPath(cwd), "utf8"));
|
|
5965
6020
|
return raw?.[key] === true;
|
|
5966
6021
|
} catch {
|
|
5967
6022
|
return false;
|
|
@@ -6004,7 +6059,7 @@ async function savePromptBreakdown(cwd, breakdown) {
|
|
|
6004
6059
|
/** This folder's last known breakdown, or null. Marked stale — it is not THIS turn's prompt. */
|
|
6005
6060
|
async function loadPromptBreakdown(cwd) {
|
|
6006
6061
|
try {
|
|
6007
|
-
const raw = JSON.parse(await readFile(
|
|
6062
|
+
const raw = JSON.parse(await readFile(folderSessionPath(cwd), "utf8"));
|
|
6008
6063
|
const b = raw?.promptBreakdown;
|
|
6009
6064
|
return b && typeof b === "object" ? { ...b, stale: true } : null;
|
|
6010
6065
|
} catch {
|
|
@@ -6040,7 +6095,7 @@ async function reportPreviousStepFailures({ clientMode = false } = {}) {
|
|
|
6040
6095
|
const cwd = resolve(process.cwd());
|
|
6041
6096
|
let raw = {};
|
|
6042
6097
|
try {
|
|
6043
|
-
raw = JSON.parse(await readFile(
|
|
6098
|
+
raw = JSON.parse(await readFile(folderSessionPath(cwd), "utf8")) || {};
|
|
6044
6099
|
} catch {
|
|
6045
6100
|
return;
|
|
6046
6101
|
}
|
|
@@ -6086,30 +6141,41 @@ async function saveSessionSkip(cwd, key, on) {
|
|
|
6086
6141
|
async function saveSession(cwd, history, { unfinishedTask = sessionUnfinishedTask } = {}) {
|
|
6087
6142
|
try {
|
|
6088
6143
|
const trimmed = history.slice(-MAX_PERSISTED_MESSAGES);
|
|
6089
|
-
//
|
|
6090
|
-
//
|
|
6091
|
-
//
|
|
6092
|
-
//
|
|
6093
|
-
//
|
|
6094
|
-
await updateSessionFile(cwd, (raw) =>
|
|
6095
|
-
|
|
6144
|
+
// Task #550: TWO writes — shared prefs stay in the per-folder file so model/key
|
|
6145
|
+
// picks survive across terminals; conversation history goes into a PER-INSTANCE
|
|
6146
|
+
// file so two gu terminals in the same folder do not overwrite each other.
|
|
6147
|
+
//
|
|
6148
|
+
// PREFERENCES (folder file) — every key EXCEPT history.
|
|
6149
|
+
await updateSessionFile(cwd, (raw) => {
|
|
6150
|
+
// Migrate: folder file still carries a `history` key from an older version → keep only prefs.
|
|
6151
|
+
delete raw.history;
|
|
6152
|
+
return Object.assign(raw, {
|
|
6096
6153
|
cwd,
|
|
6097
6154
|
updatedAt: new Date().toISOString(),
|
|
6098
6155
|
testAuto: sessionTestAuto,
|
|
6099
|
-
deployServer: selectedServer,
|
|
6100
|
-
maxCodeTokens: sessionMaxCodeTokens,
|
|
6101
|
-
ragStorage: sessionRagStorage,
|
|
6102
|
-
showThought: sessionShowThought,
|
|
6103
|
-
unfinishedTask,
|
|
6104
|
-
// The /model pick, so it survives an exit (see loadSessionCoding). Empty means "the
|
|
6105
|
-
// account default" and is written as such rather than omitted, so choosing the
|
|
6106
|
-
// default again CLEARS a previous override instead of leaving it stored.
|
|
6156
|
+
deployServer: selectedServer,
|
|
6157
|
+
maxCodeTokens: sessionMaxCodeTokens,
|
|
6158
|
+
ragStorage: sessionRagStorage,
|
|
6159
|
+
showThought: sessionShowThought,
|
|
6160
|
+
unfinishedTask,
|
|
6107
6161
|
codingModel: sessionCodingModel,
|
|
6108
6162
|
codingLabel: sessionCodingLabel,
|
|
6109
6163
|
codingUrl: sessionCodingUrl,
|
|
6110
|
-
|
|
6111
|
-
|
|
6112
|
-
)
|
|
6164
|
+
});
|
|
6165
|
+
});
|
|
6166
|
+
// HISTORY (instance file) — the NEW file carries only conversation history.
|
|
6167
|
+
if (sessionInstanceId) {
|
|
6168
|
+
const ip = sessionFilePath(cwd);
|
|
6169
|
+
const raw = {};
|
|
6170
|
+
try { Object.assign(raw, JSON.parse(await readFile(ip, "utf8"))); } catch { /* new file */ }
|
|
6171
|
+
raw.cwd = cwd;
|
|
6172
|
+
raw.updatedAt = new Date().toISOString();
|
|
6173
|
+
raw.history = trimmed;
|
|
6174
|
+
await mkdir(SESSIONS_DIR, { recursive: true });
|
|
6175
|
+
const tmp = `${ip}.${process.pid}.tmp`;
|
|
6176
|
+
await writeFile(tmp, JSON.stringify(raw, null, 2) + "\n");
|
|
6177
|
+
await rename(tmp, ip);
|
|
6178
|
+
}
|
|
6113
6179
|
} catch (err) {
|
|
6114
6180
|
// Non-fatal — losing session persistence should never crash or block the REPL.
|
|
6115
6181
|
console.error(dim(`(session save failed: ${err.message})`));
|
|
@@ -11378,9 +11444,8 @@ let following = false;
|
|
|
11378
11444
|
// typed while the previous one was still queued simply vanished. Now the input row says so the
|
|
11379
11445
|
// moment a key lands, and keeps saying it until the turn ends. Nothing is queued or sent.
|
|
11380
11446
|
let typedDuringTurn = false;
|
|
11447
|
+
let turnDraft = ""; // GH #429: what is being typed for the queue while a turn runs
|
|
11381
11448
|
const turnTyping = createTurnTypingDetector(); // what counts as typing during a turn (GH #382)
|
|
11382
|
-
const TYPED_DURING_TURN_NOTICE = "(a turn is running — typing is not sent; type it again when it finishes) ";
|
|
11383
|
-
const TYPED_DURING_TURN_SHORT = "(turn running — not sent) ";
|
|
11384
11449
|
// "? support" clicked during a turn (GH #382): it opens when the turn ends; Ctrl-C ends it now.
|
|
11385
11450
|
let supportAfterTurn = false;
|
|
11386
11451
|
const SUPPORT_AFTER_TURN_NOTICE = "(support opens when this turn ends — Ctrl-C stops the turn now) ";
|
|
@@ -11388,9 +11453,6 @@ const SUPPORT_AFTER_TURN_SHORT = "(support after this turn — Ctrl-C) ";
|
|
|
11388
11453
|
// After the first Ctrl-C the turn is stopping; a worker that never answers needs a second one.
|
|
11389
11454
|
const SUPPORT_AFTER_STOP_NOTICE = "(support opens when this turn ends — Ctrl-C again to stop waiting) ";
|
|
11390
11455
|
const SUPPORT_AFTER_STOP_SHORT = "(support after this turn — Ctrl-C again) ";
|
|
11391
|
-
/** The notice that fits: the input row must never wrap because of its label (#109/#132). */
|
|
11392
|
-
const typedNotice = (width) =>
|
|
11393
|
-
visibleLen(TYPED_DURING_TURN_NOTICE) + 12 <= width ? TYPED_DURING_TURN_NOTICE : TYPED_DURING_TURN_SHORT;
|
|
11394
11456
|
/** What the input row says during a turn instead of ">>", or "" — queued support comes first. */
|
|
11395
11457
|
const turnRowNotice = (width) =>
|
|
11396
11458
|
!following
|
|
@@ -11399,7 +11461,7 @@ const turnRowNotice = (width) =>
|
|
|
11399
11461
|
? cancelRequested
|
|
11400
11462
|
? visibleLen(SUPPORT_AFTER_STOP_NOTICE) + 12 <= width ? SUPPORT_AFTER_STOP_NOTICE : SUPPORT_AFTER_STOP_SHORT
|
|
11401
11463
|
: visibleLen(SUPPORT_AFTER_TURN_NOTICE) + 12 <= width ? SUPPORT_AFTER_TURN_NOTICE : SUPPORT_AFTER_TURN_SHORT
|
|
11402
|
-
: typedDuringTurn ?
|
|
11464
|
+
: typedDuringTurn ? typingNotice(width) : queuedNotice(turnQueue.size, width);
|
|
11403
11465
|
// Is the turn we are following one this terminal STARTED, or another terminal's that we merely
|
|
11404
11466
|
// attached to (task #211)? `attached` is local to runAgentTurn, and onInterrupt — which lives in
|
|
11405
11467
|
// main() — had no way to ask. So Ctrl+C while watching somebody else's agent took the "cancel my
|
|
@@ -12327,6 +12389,10 @@ async function tryStartLocalApi() {
|
|
|
12327
12389
|
let localDaemonRunning = false;
|
|
12328
12390
|
// This machine's id (task #134) — sent with each turn so the API can pin it here.
|
|
12329
12391
|
let myInstanceId = "";
|
|
12392
|
+
// Per-terminal session identity (task #550): two gu terminals in the same folder
|
|
12393
|
+
// each get their own conversation history. This is a UUID generated at launch and
|
|
12394
|
+
// never persisted — it lives only for this process.
|
|
12395
|
+
let sessionInstanceId = "";
|
|
12330
12396
|
// The agent model a client machine actually uses (task #134) — filled in at startup.
|
|
12331
12397
|
// Step-budget opt-out (task #80): set once the user picks "yes, don't ask again" at a
|
|
12332
12398
|
// max-step prompt. Session-scoped (not persisted per folder); sent to /agent-ask each turn
|
|
@@ -14390,6 +14456,10 @@ async function main() {
|
|
|
14390
14456
|
const status = await ctl.daemonStatus();
|
|
14391
14457
|
localDaemonRunning = status.running;
|
|
14392
14458
|
myInstanceId = await ctl.getInstanceId();
|
|
14459
|
+
// Task #550: a fresh session-id per launch, so two gu terminals in the same
|
|
14460
|
+
// project folder each get their own conversation history. The UUID is
|
|
14461
|
+
// generated ONCE here — it never gets persisted; it is this process's identity.
|
|
14462
|
+
if (!sessionInstanceId) sessionInstanceId = randomUUID();
|
|
14393
14463
|
// Task #134 CORRECTION: "client" means this machine doesn't HOST MODELS — it does NOT
|
|
14394
14464
|
// mean it can't run turns. The agent itself is just orchestration (it imports no mlx and
|
|
14395
14465
|
// reaches the model over HTTP), so it runs HERE, where the files are, and calls the
|
|
@@ -15216,6 +15286,7 @@ async function main() {
|
|
|
15216
15286
|
// not just detach. The worker sees the "cancelled" status and kills the Python
|
|
15217
15287
|
// agent; the poll loop then returns cleanly with the "(cancelled)" note.
|
|
15218
15288
|
cancelRequested = true;
|
|
15289
|
+
dropQueuedQuestions(); // GH #429: stopping the turn also drops what waits behind it
|
|
15219
15290
|
if (supportAfterTurn && barPinned()) paintBar(); // its row now says "Ctrl-C again" (GH #382)
|
|
15220
15291
|
const jobId = currentJobId;
|
|
15221
15292
|
// #307: while the question is still held (nothing printed yet), nothing goes to the
|
|
@@ -15232,6 +15303,7 @@ async function main() {
|
|
|
15232
15303
|
// Second Ctrl+C (or no jobId yet): give up waiting locally. The worker keeps
|
|
15233
15304
|
// trying to stop, but we stop following.
|
|
15234
15305
|
followAborted = true;
|
|
15306
|
+
dropQueuedQuestions();
|
|
15235
15307
|
if (pendingEcho === null) process.stdout.write("\n" + GUTTER + red("^C ")); // #307
|
|
15236
15308
|
}
|
|
15237
15309
|
} else {
|
|
@@ -15329,6 +15401,8 @@ async function main() {
|
|
|
15329
15401
|
_lineQueue.unshift("/support");
|
|
15330
15402
|
}
|
|
15331
15403
|
mainPromptWaiting = true; // a finished background shell may start a recap turn now (#362)
|
|
15404
|
+
// GH #429: the next question typed during the turn that just ended runs now, in order.
|
|
15405
|
+
if (turnQueue.size > 0 && _lineQueue.length === 0) _lineQueue.push(turnQueue.shift());
|
|
15332
15406
|
for (;;) {
|
|
15333
15407
|
lineRaw = await nextLine();
|
|
15334
15408
|
const echoed = enterEchoed;
|
|
@@ -15962,6 +16036,7 @@ async function main() {
|
|
|
15962
16036
|
// is kept out of it. Its status says it was not done, and still stands.
|
|
15963
16037
|
await markInterrupted(cwd, history, taskLine, "failed");
|
|
15964
16038
|
if (_lineQueue.length > 0) _lineQueue.length = 0;
|
|
16039
|
+
dropQueuedQuestions();
|
|
15965
16040
|
// …but REMEMBER it, so "continue" retries the real question once the cause is fixed
|
|
15966
16041
|
// (typically /model to a working coder). Deliberately not the same thing as putting it
|
|
15967
16042
|
// back in history: this is a one-shot resume, not a persisted turn.
|
|
@@ -16032,6 +16107,7 @@ async function main() {
|
|
|
16032
16107
|
// that's typed AFTER the cancel note, so it arrives through the live waiter, not the
|
|
16033
16108
|
// queue.
|
|
16034
16109
|
if (_lineQueue.length > 0) _lineQueue.length = 0;
|
|
16110
|
+
dropQueuedQuestions();
|
|
16035
16111
|
// Ctrl+C cancel already printed its own "(cancelled)" note in runAgentTurn — a
|
|
16036
16112
|
// second "(no answer)" line here would be redundant/misleading.
|
|
16037
16113
|
if (cancelled) {
|
|
@@ -16054,6 +16130,7 @@ async function main() {
|
|
|
16054
16130
|
// Same reasoning as the no-answer branch (bug #92): don't let input buffered during a
|
|
16055
16131
|
// turn that just threw auto-fire the next one.
|
|
16056
16132
|
if (_lineQueue.length > 0) _lineQueue.length = 0;
|
|
16133
|
+
dropQueuedQuestions();
|
|
16057
16134
|
await rememberUnfinishedTask(cwd, taskLine); // …and "continue" can retry it (task #150)
|
|
16058
16135
|
// #302 part 3: the connection went, not the turn — keep its job so "continue" follows it.
|
|
16059
16136
|
lostTurn = err?.lostJobId ? { jobId: err.lostJobId, taskLine } : null;
|
package/gu_browser.py
CHANGED
|
@@ -534,6 +534,64 @@ def connect(wait=True, log=None, on_wait=None, own=False):
|
|
|
534
534
|
return st, None
|
|
535
535
|
|
|
536
536
|
|
|
537
|
+
def own_allowed():
|
|
538
|
+
"""GH #428: gu's own Chrome window may stand in for a missing extension unless the user turned
|
|
539
|
+
that off (GU_BROWSER_FALLBACK=off|0|no|false)."""
|
|
540
|
+
return os.environ.get("GU_BROWSER_FALLBACK", "on").strip().lower() not in ("off", "0", "no", "false")
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def keep_tabs():
|
|
544
|
+
"""GU_BROWSER_KEEP_TABS=1 keeps gu's tabs open after the turn."""
|
|
545
|
+
return os.environ.get("GU_BROWSER_KEEP_TABS", "").strip().lower() in ("1", "on", "yes", "true")
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def profile_line():
|
|
549
|
+
"""One line: which Chrome gu is using (the extension that holds the bridge, other copies refused)."""
|
|
550
|
+
st = _read_state()
|
|
551
|
+
if not st:
|
|
552
|
+
return ""
|
|
553
|
+
try:
|
|
554
|
+
s = _http(st, "GET", "/status", timeout=3)
|
|
555
|
+
except OSError:
|
|
556
|
+
return ""
|
|
557
|
+
if s.get("connected"):
|
|
558
|
+
line = (f"Connected Chrome: gu extension v{s.get('version')} ({s.get('installType')}), extension id {s.get('id')} — "
|
|
559
|
+
"one Chrome profile at a time; the first extension to connect wins.")
|
|
560
|
+
ref = [r.get("id") for r in s.get("refused") or []]
|
|
561
|
+
if ref:
|
|
562
|
+
line += (f"\nRefused (another profile/copy also has the gu extension): {', '.join(ref)} — "
|
|
563
|
+
"turn it off in the profiles you do not use with gu.")
|
|
564
|
+
return line
|
|
565
|
+
if s.get("ownChrome"):
|
|
566
|
+
return "No gu extension connected — using gu's own Chrome window (separate profile, not signed in)."
|
|
567
|
+
return "No gu extension connected."
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def cleanup(log=None):
|
|
571
|
+
"""End of a turn (GH #428): the extension closes the tabs gu opened and lets go of tabs the user
|
|
572
|
+
shared. Only when the extension is connected — never starts anything. → short text or ""."""
|
|
573
|
+
if keep_tabs():
|
|
574
|
+
return ""
|
|
575
|
+
st = _read_state()
|
|
576
|
+
if not st:
|
|
577
|
+
return ""
|
|
578
|
+
try:
|
|
579
|
+
s = _http(st, "GET", "/status", timeout=2)
|
|
580
|
+
if not s.get("connected"):
|
|
581
|
+
return ""
|
|
582
|
+
r = _http(st, "POST", "/cmd", body={"action": "cleanup", "timeout_ms": 8000}, timeout=12)
|
|
583
|
+
except OSError:
|
|
584
|
+
return ""
|
|
585
|
+
res = r.get("result") or {}
|
|
586
|
+
if not r.get("ok") or not isinstance(res, dict):
|
|
587
|
+
return ""
|
|
588
|
+
closed, released = res.get("closed") or [], res.get("released") or []
|
|
589
|
+
if not closed and not released:
|
|
590
|
+
return ""
|
|
591
|
+
return (f"Closed {len(closed)} gu tab(s)" + (f", released {len(released)} shared tab(s)" if released else "")
|
|
592
|
+
+ " in Chrome.")
|
|
593
|
+
|
|
594
|
+
|
|
537
595
|
def command(cmd, log=None, on_wait=None, own=False):
|
|
538
596
|
"""Send one command. → (ok, result_or_error, not_connected).
|
|
539
597
|
own=True: without the extension, the bridge uses gu's own Chrome window (#150). The result
|
|
@@ -563,6 +621,8 @@ def command(cmd, log=None, on_wait=None, own=False):
|
|
|
563
621
|
# ── what the model reads ────────────────────────────────────────────────────────────────────
|
|
564
622
|
def _head(res):
|
|
565
623
|
out = f"Page: {res.get('title') or '(no title)'} — {res.get('url') or ''}"
|
|
624
|
+
for n in res.get("notes") or []: # GH #428: why a tab was opened / adopted
|
|
625
|
+
out += f"\nNote: {n}"
|
|
566
626
|
for d in res.get("dialogs") or []:
|
|
567
627
|
out += f"\nA dialog opened and gu accepted it: {d}"
|
|
568
628
|
errs = res.get("errors") or []
|
|
@@ -592,8 +652,9 @@ def format_result(action, res):
|
|
|
592
652
|
tabs = res.get("tabs") or []
|
|
593
653
|
if not tabs:
|
|
594
654
|
return "gu has no tab open."
|
|
595
|
-
return "gu's tabs:\n" + "\n".join(
|
|
596
|
-
f" {t['id']}{' (current)' if t.get('current') else ''}
|
|
655
|
+
return "gu's tabs (gu works on the one marked current — not on the tab you have in front):\n" + "\n".join(
|
|
656
|
+
f" {t['id']}{' (current)' if t.get('current') else ''}{' (shared by you — gu lets go of it at the end)' if t.get('shared') else ''}: "
|
|
657
|
+
f"{t.get('title') or ''} — {t.get('url')}" for t in tabs)
|
|
597
658
|
if a == "read":
|
|
598
659
|
return format_read(res)
|
|
599
660
|
if a == "close":
|
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.908",
|
|
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",
|
|
@@ -81,6 +81,7 @@
|
|
|
81
81
|
"python-windows.mjs",
|
|
82
82
|
"terminal-hover.mjs",
|
|
83
83
|
"terminal-layout.mjs",
|
|
84
|
+
"turn-queue.mjs",
|
|
84
85
|
"terminal-viewport.mjs",
|
|
85
86
|
"terminal-copy.mjs",
|
|
86
87
|
"version-check.mjs",
|
package/terminal-layout.mjs
CHANGED
|
@@ -3369,6 +3369,29 @@ export function rankSlashCommands(cmds, typed) {
|
|
|
3369
3369
|
return scored.map((s) => s.c);
|
|
3370
3370
|
}
|
|
3371
3371
|
|
|
3372
|
+
/**
|
|
3373
|
+
* THE ROW ENTER WILL RUN WHEN THE USER HAS NOT PRESSED ↑/↓ (GH: "/mo" + Enter should be /model).
|
|
3374
|
+
* `cmds` is the ranked list from rankSlashCommands. Returns its index, or -1 for "run what was typed".
|
|
3375
|
+
* - the typed word is exactly a command name or alias → that command
|
|
3376
|
+
* - exactly ONE command has a name/alias that STARTS with it → that command
|
|
3377
|
+
* - several do ("/m" → /model, /mcp), arguments were typed ("/model x"), or none → -1
|
|
3378
|
+
*/
|
|
3379
|
+
export function autoSelectSlash(cmds, typed) {
|
|
3380
|
+
const parts = String(typed ?? "").trim().split(/\s+/);
|
|
3381
|
+
if (parts.length !== 1 || !parts[0].startsWith("/")) return -1;
|
|
3382
|
+
const word = parts[0].toLowerCase();
|
|
3383
|
+
if (word === "/") return -1;
|
|
3384
|
+
const all = (c) => [c.name, ...(c.aliases ?? [])].map((n) => String(n).toLowerCase());
|
|
3385
|
+
const list = cmds ?? [];
|
|
3386
|
+
const exact = list.findIndex((c) => all(c).includes(word));
|
|
3387
|
+
if (exact >= 0) return exact;
|
|
3388
|
+
const starts = [];
|
|
3389
|
+
list.forEach((c, i) => {
|
|
3390
|
+
if (all(c).some((n) => n.startsWith(word))) starts.push(i);
|
|
3391
|
+
});
|
|
3392
|
+
return starts.length === 1 ? starts[0] : -1;
|
|
3393
|
+
}
|
|
3394
|
+
|
|
3372
3395
|
/**
|
|
3373
3396
|
* Which slice of the ranked list is on screen. `sel` -1 = nothing highlighted (window at the top).
|
|
3374
3397
|
* → { from, to, above, below, top } — above/below are how many are hidden on each side.
|
package/turn-queue.mjs
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// QUEUE FOR QUESTIONS TYPED WHILE A TURN IS RUNNING (GH #429).
|
|
2
|
+
//
|
|
3
|
+
// Typing during a turn used to be dropped ("typing is not sent; type it again when it finishes").
|
|
4
|
+
// Now Enter queues the question (FIFO) and the main loop runs it when the current turn has ended.
|
|
5
|
+
// Pure and terminal-free so the order / limits / texts are unit-testable.
|
|
6
|
+
|
|
7
|
+
export const MAX_QUEUED_QUESTIONS = 20;
|
|
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
|
+
export function createTurnQueue({ max = MAX_QUEUED_QUESTIONS } = {}) {
|
|
14
|
+
const items = [];
|
|
15
|
+
return {
|
|
16
|
+
/** → true when queued, false when the queue is full. */
|
|
17
|
+
push(item) {
|
|
18
|
+
if (items.length >= max) return false;
|
|
19
|
+
items.push(item);
|
|
20
|
+
return true;
|
|
21
|
+
},
|
|
22
|
+
/** The oldest queued item, or null. */
|
|
23
|
+
shift() {
|
|
24
|
+
return items.length ? items.shift() : null;
|
|
25
|
+
},
|
|
26
|
+
/** Drop everything → how many were dropped. */
|
|
27
|
+
clear() {
|
|
28
|
+
const n = items.length;
|
|
29
|
+
items.length = 0;
|
|
30
|
+
return n;
|
|
31
|
+
},
|
|
32
|
+
get size() {
|
|
33
|
+
return items.length;
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
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
|
+
/** One line for the transcript when queued questions are thrown away. */
|
|
53
|
+
export function droppedNote(n) {
|
|
54
|
+
return `(${n} queued question${n === 1 ? "" : "s"} not run — the turn did not finish; type ${n === 1 ? "it" : "them"} again)`;
|
|
55
|
+
}
|