@tiens.nguyen/gu-cli 1.0.906 → 1.0.907
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 +21 -6
- package/gu-repl.mjs +85 -36
- package/gu_browser.py +63 -2
- package/package.json +1 -1
- package/terminal-layout.mjs +23 -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
|
@@ -16879,7 +16879,7 @@ def run_agent_chat(cfg):
|
|
|
16879
16879
|
def browser(action: str, url: str = "", ref: int = 0, x: int = -1, y: int = -1,
|
|
16880
16880
|
text: str = "", clear: bool = False, submit: bool = False,
|
|
16881
16881
|
direction: str = "", amount: int = 0, seconds: int = 0, tab: str = "",
|
|
16882
|
-
new_tab: bool = False) -> str:
|
|
16882
|
+
new_tab: bool = False, focus: bool = False) -> str:
|
|
16883
16883
|
"""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
16884
|
|
|
16885
16885
|
Args:
|
|
@@ -16896,6 +16896,7 @@ def run_agent_chat(cfg):
|
|
|
16896
16896
|
seconds: wait only — 1 to 30
|
|
16897
16897
|
tab: switch only — a tab id from tabs (a number, or an id like "8F3A…" in gu's own window)
|
|
16898
16898
|
new_tab: open only — open in a new tab instead of the current gu tab
|
|
16899
|
+
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
16900
|
"""
|
|
16900
16901
|
import gu_browser as _gb
|
|
16901
16902
|
a = (action or "").strip().lower().replace(" ", "_").replace("-", "_")
|
|
@@ -16914,7 +16915,7 @@ def run_agent_chat(cfg):
|
|
|
16914
16915
|
cmd["x"], cmd["y"] = float(x), float(y)
|
|
16915
16916
|
if text:
|
|
16916
16917
|
cmd["text"] = str(text)
|
|
16917
|
-
for k, v in (("clear", clear), ("submit", submit), ("new_tab", new_tab)):
|
|
16918
|
+
for k, v in (("clear", clear), ("submit", submit), ("new_tab", new_tab), ("focus", focus)):
|
|
16918
16919
|
if v:
|
|
16919
16920
|
cmd[k] = True
|
|
16920
16921
|
if direction:
|
|
@@ -16942,8 +16943,9 @@ def run_agent_chat(cfg):
|
|
|
16942
16943
|
_browser_consent["ext_checked"] = True
|
|
16943
16944
|
_ext_ok, _browser_consent["ext_note"] = _gb.ensure_extension(
|
|
16944
16945
|
log=_log, emit=lambda t: _emit({"type": "step", "text": t}))
|
|
16946
|
+
# GH #428: GU_BROWSER_FALLBACK=off stops gu from silently using its own Chrome window.
|
|
16945
16947
|
ok, res, not_connected = _gb.command(
|
|
16946
|
-
cmd, log=_log, own=
|
|
16948
|
+
cmd, log=_log, own=_gb.own_allowed(),
|
|
16947
16949
|
on_wait=lambda: _emit({"type": "step", "text": "Waiting for Chrome to connect…"}))
|
|
16948
16950
|
where = res.pop("_backend", "") if ok and isinstance(res, dict) else ""
|
|
16949
16951
|
if where and where != _browser_consent["where"]:
|
|
@@ -16966,10 +16968,14 @@ def run_agent_chat(cfg):
|
|
|
16966
16968
|
+ _gb.format_result("read", res))
|
|
16967
16969
|
else:
|
|
16968
16970
|
msg = _gb.format_result(a, res)
|
|
16971
|
+
if a == "tabs":
|
|
16972
|
+
_pl = _gb.profile_line() # GH #428: which Chrome profile/extension gu is using
|
|
16973
|
+
if _pl:
|
|
16974
|
+
msg += "\n" + _pl
|
|
16969
16975
|
if a in ("open", "click", "double_click", "right_click", "type", "key", "back", "reload"):
|
|
16970
16976
|
# GH #421: show the page after an action, so the model needs no extra `read` step
|
|
16971
16977
|
try:
|
|
16972
|
-
ok2, res2, _nc2 = _gb.command({"action": "read"}, log=_log, own=
|
|
16978
|
+
ok2, res2, _nc2 = _gb.command({"action": "read"}, log=_log, own=_gb.own_allowed())
|
|
16973
16979
|
if ok2 and isinstance(res2, dict):
|
|
16974
16980
|
res2.pop("_backend", None)
|
|
16975
16981
|
msg = msg.replace("\n(read or screenshot to see the page now)", "") \
|
|
@@ -16977,8 +16983,8 @@ def run_agent_chat(cfg):
|
|
|
16977
16983
|
except Exception: # noqa: BLE001
|
|
16978
16984
|
pass
|
|
16979
16985
|
if ok and where == "chrome" and a == "open":
|
|
16980
|
-
msg = ("(gu's own Chrome window — a separate
|
|
16981
|
-
"accounts.)\n" + msg)
|
|
16986
|
+
msg = ("(NO gu extension is connected, so this is gu's own Chrome window — a separate "
|
|
16987
|
+
"profile, NOT signed in to the user's accounts. Say so if it matters to the task.)\n" + msg)
|
|
16982
16988
|
if ok and where == "chrome" and _browser_consent.get("ext_note"):
|
|
16983
16989
|
msg = _browser_consent.pop("ext_note") + "\n" + msg
|
|
16984
16990
|
except Exception as ex: # noqa: BLE001
|
|
@@ -17345,6 +17351,15 @@ def run_agent_chat(cfg):
|
|
|
17345
17351
|
or _fallback_recap(_turn_steps, _last_obs.get("text"))
|
|
17346
17352
|
or "[No result]")
|
|
17347
17353
|
_log(f"done (deterministic, no summarizer call): {len(final_text)} chars")
|
|
17354
|
+
# GH #428: close the Chrome tabs gu opened this turn (shared tabs are only let go of).
|
|
17355
|
+
try:
|
|
17356
|
+
if _browser_consent.get("ok"):
|
|
17357
|
+
import gu_browser as _gb_end
|
|
17358
|
+
_ct = _gb_end.cleanup(log=_log)
|
|
17359
|
+
if _ct:
|
|
17360
|
+
_log(f"browser cleanup: {_ct}")
|
|
17361
|
+
except Exception as _ce: # noqa: BLE001
|
|
17362
|
+
_log(f"browser cleanup skipped: {type(_ce).__name__}: {_ce}")
|
|
17348
17363
|
_emit({"type": "final", "text": final_text})
|
|
17349
17364
|
# onTurnEnd (task #270): after the answer is out, so a slow hook never delays it.
|
|
17350
17365
|
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";
|
|
@@ -2342,6 +2343,9 @@ function renderSlashOverlay(sel) {
|
|
|
2342
2343
|
const line = rl.line;
|
|
2343
2344
|
const cmds = rankSlashCommands(allCommands(), line);
|
|
2344
2345
|
slashNames = cmds.map((c) => c.name);
|
|
2346
|
+
// Nothing picked with ↑/↓: highlight the one command the typed text can only mean ("/mo" → /model),
|
|
2347
|
+
// so Enter runs it instead of submitting the unfinished "/mo".
|
|
2348
|
+
if (sel < 0) sel = autoSelectSlash(cmds, line);
|
|
2345
2349
|
if (sel >= cmds.length) sel = cmds.length - 1;
|
|
2346
2350
|
slashSel = sel;
|
|
2347
2351
|
slashPrefix = line;
|
|
@@ -5434,9 +5438,24 @@ async function ensureWorkspace() {
|
|
|
5434
5438
|
// python side already uses for per-URL RAG work dirs (sha256, 32 hex chars), applied
|
|
5435
5439
|
// here to the workspace path instead so returning to the SAME folder reloads the SAME
|
|
5436
5440
|
// conversation.
|
|
5441
|
+
const _folderHash = (cwd) => createHash("sha256").update(cwd).digest("hex").slice(0, 32);
|
|
5442
|
+
/** The per-folder shared file — preferences only (coding model, keys, settings). */
|
|
5443
|
+
function folderSessionPath(cwd) {
|
|
5444
|
+
return join(SESSIONS_DIR, `${_folderHash(cwd)}.json`);
|
|
5445
|
+
}
|
|
5446
|
+
/**
|
|
5447
|
+
* The per-instance file — conversation history belongs here (task #550).
|
|
5448
|
+
*
|
|
5449
|
+
* Two gu terminals in the same folder each get their own history, so save/load
|
|
5450
|
+
* are independent day to day. The old single-file format is migrated on first load
|
|
5451
|
+
* (history key moved from the folder file into the first instance file seen).
|
|
5452
|
+
* Returns the old path when sessionInstanceId is empty (startup, before init), so
|
|
5453
|
+
* the load at line 15148 uses the folder file and migrates.
|
|
5454
|
+
*/
|
|
5437
5455
|
function sessionFilePath(cwd) {
|
|
5438
|
-
|
|
5439
|
-
|
|
5456
|
+
return sessionInstanceId
|
|
5457
|
+
? join(SESSIONS_DIR, `${_folderHash(cwd)}-${sessionInstanceId}.json`)
|
|
5458
|
+
: folderSessionPath(cwd);
|
|
5440
5459
|
}
|
|
5441
5460
|
|
|
5442
5461
|
// Cap what's kept on disk — the worker already truncates what it actually SENDS to the
|
|
@@ -5567,7 +5586,18 @@ async function pushWorkspaceSync(cwd, history, { del = false, key = "", name = "
|
|
|
5567
5586
|
|
|
5568
5587
|
async function loadSession(cwd) {
|
|
5569
5588
|
try {
|
|
5570
|
-
|
|
5589
|
+
// Task #550: history lives in a PER-INSTANCE file now. If the instance file exists,
|
|
5590
|
+
// read from it; otherwise try the OLD folder-level file (first launch after this change).
|
|
5591
|
+
const ip = sessionFilePath(cwd);
|
|
5592
|
+
let raw = null;
|
|
5593
|
+
try { raw = JSON.parse(await readFile(ip, "utf8")); } catch { /* no instance file yet */ }
|
|
5594
|
+
if (raw && Array.isArray(raw.history) && raw.history.length) {
|
|
5595
|
+
// Instance file exists with history — use it.
|
|
5596
|
+
} else if (ip !== folderSessionPath(cwd)) {
|
|
5597
|
+
// Fall back to the old folder-level file, which still carries history for this folder.
|
|
5598
|
+
// Read the history FROM it but leave the rest (preferences) where it is.
|
|
5599
|
+
try { raw = JSON.parse(await readFile(folderSessionPath(cwd), "utf8")); } catch { raw = null; }
|
|
5600
|
+
}
|
|
5571
5601
|
const history = Array.isArray(raw?.history) ? raw.history : [];
|
|
5572
5602
|
// Sessions saved BEFORE task #144 can contain failure banners stored as assistant turns
|
|
5573
5603
|
// ("⚠️ api.moonshot.ai refused: …suspended…"). New ones are dropped at the source, but an
|
|
@@ -5592,7 +5622,7 @@ async function loadSession(cwd) {
|
|
|
5592
5622
|
// the real question instead of being sent to the model as the word "continue".
|
|
5593
5623
|
async function loadSessionUnfinishedTask(cwd) {
|
|
5594
5624
|
try {
|
|
5595
|
-
return unfinishedTaskFromSession(JSON.parse(await readFile(
|
|
5625
|
+
return unfinishedTaskFromSession(JSON.parse(await readFile(folderSessionPath(cwd), "utf8")));
|
|
5596
5626
|
} catch {
|
|
5597
5627
|
return "";
|
|
5598
5628
|
}
|
|
@@ -5647,13 +5677,13 @@ async function updateSessionFile(cwd, mutate) {
|
|
|
5647
5677
|
const run = async () => {
|
|
5648
5678
|
let raw = {};
|
|
5649
5679
|
try {
|
|
5650
|
-
raw = JSON.parse(await readFile(
|
|
5680
|
+
raw = JSON.parse(await readFile(folderSessionPath(cwd), "utf8")) || {};
|
|
5651
5681
|
} catch {
|
|
5652
5682
|
raw = {}; // no file yet, or an unreadable one — a fresh object is the honest start
|
|
5653
5683
|
}
|
|
5654
5684
|
const next = (await mutate(raw)) ?? raw;
|
|
5655
5685
|
await mkdir(SESSIONS_DIR, { recursive: true });
|
|
5656
|
-
const path =
|
|
5686
|
+
const path = folderSessionPath(cwd);
|
|
5657
5687
|
// The pid is in the temp name so two gu processes in the same folder cannot land on
|
|
5658
5688
|
// each other's half-written file — the chain only serializes writes inside ONE process.
|
|
5659
5689
|
const tmp = `${path}.${process.pid}.tmp`;
|
|
@@ -5700,7 +5730,7 @@ async function rememberUnfinishedTask(cwd, task) {
|
|
|
5700
5730
|
// session file). Read it once at startup so the banner and agent-ask reflect it.
|
|
5701
5731
|
async function loadSessionTestAuto(cwd) {
|
|
5702
5732
|
try {
|
|
5703
|
-
const raw = JSON.parse(await readFile(
|
|
5733
|
+
const raw = JSON.parse(await readFile(folderSessionPath(cwd), "utf8"));
|
|
5704
5734
|
return raw?.testAuto === true;
|
|
5705
5735
|
} catch {
|
|
5706
5736
|
return false;
|
|
@@ -5712,7 +5742,7 @@ async function loadSessionTestAuto(cwd) {
|
|
|
5712
5742
|
// lost on restart). Returns {name,host,user} or null.
|
|
5713
5743
|
async function loadSessionServer(cwd) {
|
|
5714
5744
|
try {
|
|
5715
|
-
const raw = JSON.parse(await readFile(
|
|
5745
|
+
const raw = JSON.parse(await readFile(folderSessionPath(cwd), "utf8"));
|
|
5716
5746
|
const s = raw?.deployServer;
|
|
5717
5747
|
return s && typeof s.host === "string" && typeof s.user === "string" ? s : null;
|
|
5718
5748
|
} catch {
|
|
@@ -5729,7 +5759,7 @@ async function loadSessionServer(cwd) {
|
|
|
5729
5759
|
// existed reads as on.
|
|
5730
5760
|
async function loadSessionShowThought(cwd) {
|
|
5731
5761
|
try {
|
|
5732
|
-
const raw = JSON.parse(await readFile(
|
|
5762
|
+
const raw = JSON.parse(await readFile(folderSessionPath(cwd), "utf8"));
|
|
5733
5763
|
return raw?.showThought !== false;
|
|
5734
5764
|
} catch {
|
|
5735
5765
|
return true;
|
|
@@ -5739,7 +5769,7 @@ async function loadSessionShowThought(cwd) {
|
|
|
5739
5769
|
// Peak single-request agent-code-model token count remembered per folder (task #84).
|
|
5740
5770
|
async function loadSessionMaxCodeTokens(cwd) {
|
|
5741
5771
|
try {
|
|
5742
|
-
const raw = JSON.parse(await readFile(
|
|
5772
|
+
const raw = JSON.parse(await readFile(folderSessionPath(cwd), "utf8"));
|
|
5743
5773
|
return Number.isFinite(raw?.maxCodeTokens) ? raw.maxCodeTokens : 0;
|
|
5744
5774
|
} catch {
|
|
5745
5775
|
return 0;
|
|
@@ -5835,7 +5865,7 @@ async function saveSessionCodingKeyId(cwd) {
|
|
|
5835
5865
|
async function loadSessionFolderKeyId(cwd, role) {
|
|
5836
5866
|
const { roleOf } = await import("./server-keys.mjs");
|
|
5837
5867
|
try {
|
|
5838
|
-
const raw = JSON.parse(await readFile(
|
|
5868
|
+
const raw = JSON.parse(await readFile(folderSessionPath(cwd), "utf8"));
|
|
5839
5869
|
const v = raw?.[roleOf(role).field];
|
|
5840
5870
|
return typeof v === "string" ? v.trim() : "";
|
|
5841
5871
|
} catch {
|
|
@@ -5873,7 +5903,7 @@ async function saveFolderKeyPick(role, id) {
|
|
|
5873
5903
|
|
|
5874
5904
|
async function loadSessionCodingKeyId(cwd) {
|
|
5875
5905
|
try {
|
|
5876
|
-
const raw = JSON.parse(await readFile(
|
|
5906
|
+
const raw = JSON.parse(await readFile(folderSessionPath(cwd), "utf8"));
|
|
5877
5907
|
return typeof raw?.codingKeyId === "string" ? raw.codingKeyId.trim() : "";
|
|
5878
5908
|
} catch {
|
|
5879
5909
|
return "";
|
|
@@ -5882,7 +5912,7 @@ async function loadSessionCodingKeyId(cwd) {
|
|
|
5882
5912
|
|
|
5883
5913
|
async function loadSessionCoding(cwd) {
|
|
5884
5914
|
try {
|
|
5885
|
-
const raw = JSON.parse(await readFile(
|
|
5915
|
+
const raw = JSON.parse(await readFile(folderSessionPath(cwd), "utf8"));
|
|
5886
5916
|
const model = typeof raw?.codingModel === "string" ? raw.codingModel.trim() : "";
|
|
5887
5917
|
if (!model) return null;
|
|
5888
5918
|
return {
|
|
@@ -5897,7 +5927,7 @@ async function loadSessionCoding(cwd) {
|
|
|
5897
5927
|
|
|
5898
5928
|
async function loadQuickModels(cwd) {
|
|
5899
5929
|
try {
|
|
5900
|
-
return normalizeQuick(JSON.parse(await readFile(
|
|
5930
|
+
return normalizeQuick(JSON.parse(await readFile(folderSessionPath(cwd), "utf8"))?.quickModels);
|
|
5901
5931
|
} catch {
|
|
5902
5932
|
return [];
|
|
5903
5933
|
}
|
|
@@ -5918,7 +5948,7 @@ async function saveQuickModels(cwd) {
|
|
|
5918
5948
|
* testable; only the file I/O is here. */
|
|
5919
5949
|
async function loadSessionRagStorage(cwd) {
|
|
5920
5950
|
try {
|
|
5921
|
-
return ragStorageFromSession(JSON.parse(await readFile(
|
|
5951
|
+
return ragStorageFromSession(JSON.parse(await readFile(folderSessionPath(cwd), "utf8")));
|
|
5922
5952
|
} catch {
|
|
5923
5953
|
return "local";
|
|
5924
5954
|
}
|
|
@@ -5961,7 +5991,7 @@ async function saveSessionShowThought(cwd, on) {
|
|
|
5961
5991
|
// to prevent.
|
|
5962
5992
|
async function loadSessionSkip(cwd, key) {
|
|
5963
5993
|
try {
|
|
5964
|
-
const raw = JSON.parse(await readFile(
|
|
5994
|
+
const raw = JSON.parse(await readFile(folderSessionPath(cwd), "utf8"));
|
|
5965
5995
|
return raw?.[key] === true;
|
|
5966
5996
|
} catch {
|
|
5967
5997
|
return false;
|
|
@@ -6004,7 +6034,7 @@ async function savePromptBreakdown(cwd, breakdown) {
|
|
|
6004
6034
|
/** This folder's last known breakdown, or null. Marked stale — it is not THIS turn's prompt. */
|
|
6005
6035
|
async function loadPromptBreakdown(cwd) {
|
|
6006
6036
|
try {
|
|
6007
|
-
const raw = JSON.parse(await readFile(
|
|
6037
|
+
const raw = JSON.parse(await readFile(folderSessionPath(cwd), "utf8"));
|
|
6008
6038
|
const b = raw?.promptBreakdown;
|
|
6009
6039
|
return b && typeof b === "object" ? { ...b, stale: true } : null;
|
|
6010
6040
|
} catch {
|
|
@@ -6040,7 +6070,7 @@ async function reportPreviousStepFailures({ clientMode = false } = {}) {
|
|
|
6040
6070
|
const cwd = resolve(process.cwd());
|
|
6041
6071
|
let raw = {};
|
|
6042
6072
|
try {
|
|
6043
|
-
raw = JSON.parse(await readFile(
|
|
6073
|
+
raw = JSON.parse(await readFile(folderSessionPath(cwd), "utf8")) || {};
|
|
6044
6074
|
} catch {
|
|
6045
6075
|
return;
|
|
6046
6076
|
}
|
|
@@ -6086,30 +6116,41 @@ async function saveSessionSkip(cwd, key, on) {
|
|
|
6086
6116
|
async function saveSession(cwd, history, { unfinishedTask = sessionUnfinishedTask } = {}) {
|
|
6087
6117
|
try {
|
|
6088
6118
|
const trimmed = history.slice(-MAX_PERSISTED_MESSAGES);
|
|
6089
|
-
//
|
|
6090
|
-
//
|
|
6091
|
-
//
|
|
6092
|
-
//
|
|
6093
|
-
//
|
|
6094
|
-
await updateSessionFile(cwd, (raw) =>
|
|
6095
|
-
|
|
6119
|
+
// Task #550: TWO writes — shared prefs stay in the per-folder file so model/key
|
|
6120
|
+
// picks survive across terminals; conversation history goes into a PER-INSTANCE
|
|
6121
|
+
// file so two gu terminals in the same folder do not overwrite each other.
|
|
6122
|
+
//
|
|
6123
|
+
// PREFERENCES (folder file) — every key EXCEPT history.
|
|
6124
|
+
await updateSessionFile(cwd, (raw) => {
|
|
6125
|
+
// Migrate: folder file still carries a `history` key from an older version → keep only prefs.
|
|
6126
|
+
delete raw.history;
|
|
6127
|
+
return Object.assign(raw, {
|
|
6096
6128
|
cwd,
|
|
6097
6129
|
updatedAt: new Date().toISOString(),
|
|
6098
6130
|
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.
|
|
6131
|
+
deployServer: selectedServer,
|
|
6132
|
+
maxCodeTokens: sessionMaxCodeTokens,
|
|
6133
|
+
ragStorage: sessionRagStorage,
|
|
6134
|
+
showThought: sessionShowThought,
|
|
6135
|
+
unfinishedTask,
|
|
6107
6136
|
codingModel: sessionCodingModel,
|
|
6108
6137
|
codingLabel: sessionCodingLabel,
|
|
6109
6138
|
codingUrl: sessionCodingUrl,
|
|
6110
|
-
|
|
6111
|
-
|
|
6112
|
-
)
|
|
6139
|
+
});
|
|
6140
|
+
});
|
|
6141
|
+
// HISTORY (instance file) — the NEW file carries only conversation history.
|
|
6142
|
+
if (sessionInstanceId) {
|
|
6143
|
+
const ip = sessionFilePath(cwd);
|
|
6144
|
+
const raw = {};
|
|
6145
|
+
try { Object.assign(raw, JSON.parse(await readFile(ip, "utf8"))); } catch { /* new file */ }
|
|
6146
|
+
raw.cwd = cwd;
|
|
6147
|
+
raw.updatedAt = new Date().toISOString();
|
|
6148
|
+
raw.history = trimmed;
|
|
6149
|
+
await mkdir(SESSIONS_DIR, { recursive: true });
|
|
6150
|
+
const tmp = `${ip}.${process.pid}.tmp`;
|
|
6151
|
+
await writeFile(tmp, JSON.stringify(raw, null, 2) + "\n");
|
|
6152
|
+
await rename(tmp, ip);
|
|
6153
|
+
}
|
|
6113
6154
|
} catch (err) {
|
|
6114
6155
|
// Non-fatal — losing session persistence should never crash or block the REPL.
|
|
6115
6156
|
console.error(dim(`(session save failed: ${err.message})`));
|
|
@@ -12327,6 +12368,10 @@ async function tryStartLocalApi() {
|
|
|
12327
12368
|
let localDaemonRunning = false;
|
|
12328
12369
|
// This machine's id (task #134) — sent with each turn so the API can pin it here.
|
|
12329
12370
|
let myInstanceId = "";
|
|
12371
|
+
// Per-terminal session identity (task #550): two gu terminals in the same folder
|
|
12372
|
+
// each get their own conversation history. This is a UUID generated at launch and
|
|
12373
|
+
// never persisted — it lives only for this process.
|
|
12374
|
+
let sessionInstanceId = "";
|
|
12330
12375
|
// The agent model a client machine actually uses (task #134) — filled in at startup.
|
|
12331
12376
|
// Step-budget opt-out (task #80): set once the user picks "yes, don't ask again" at a
|
|
12332
12377
|
// max-step prompt. Session-scoped (not persisted per folder); sent to /agent-ask each turn
|
|
@@ -14390,6 +14435,10 @@ async function main() {
|
|
|
14390
14435
|
const status = await ctl.daemonStatus();
|
|
14391
14436
|
localDaemonRunning = status.running;
|
|
14392
14437
|
myInstanceId = await ctl.getInstanceId();
|
|
14438
|
+
// Task #550: a fresh session-id per launch, so two gu terminals in the same
|
|
14439
|
+
// project folder each get their own conversation history. The UUID is
|
|
14440
|
+
// generated ONCE here — it never gets persisted; it is this process's identity.
|
|
14441
|
+
if (!sessionInstanceId) sessionInstanceId = randomUUID();
|
|
14393
14442
|
// Task #134 CORRECTION: "client" means this machine doesn't HOST MODELS — it does NOT
|
|
14394
14443
|
// mean it can't run turns. The agent itself is just orchestration (it imports no mlx and
|
|
14395
14444
|
// reaches the model over HTTP), so it runs HERE, where the files are, and calls the
|
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.907",
|
|
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",
|
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.
|