@tiens.nguyen/gu-cli 1.0.844 → 1.0.845

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.
@@ -16189,7 +16189,8 @@ def run_agent_chat(cfg):
16189
16189
  return ""
16190
16190
  if not (_interactive_approval and _job_id and worker_api_base and worker_api_key):
16191
16191
  return ("The browser needs the user's permission and this session cannot ask. Tell the "
16192
- "user to allow it (/browser allow in the gu terminal), then carry on without it.")
16192
+ "user to run this in the gu terminal, where gu asks for permission (Allow once / Always in this folder), "
16193
+ "then carry on without it.")
16193
16194
  if _ws_request_approval(worker_api_base, worker_api_key, _job_id,
16194
16195
  f"__BROWSER__::{folder}\t{what}", "", deadline_s=180):
16195
16196
  _browser_consent["ok"] = True
@@ -16259,6 +16260,12 @@ def run_agent_chat(cfg):
16259
16260
  if refused:
16260
16261
  _last_obs["text"] = refused
16261
16262
  return refused
16263
+ if not _browser_consent.get("ext_checked"):
16264
+ # Task #401: on a new machine the extension is missing — find out, open its store
16265
+ # page, show the steps and wait for it, before falling back to gu's own window.
16266
+ _browser_consent["ext_checked"] = True
16267
+ _ext_ok, _browser_consent["ext_note"] = _gb.ensure_extension(
16268
+ log=_log, emit=lambda t: _emit({"type": "step", "text": t}))
16262
16269
  ok, res, not_connected = _gb.command(
16263
16270
  cmd, log=_log, own=True,
16264
16271
  on_wait=lambda: _emit({"type": "step", "text": "Waiting for Chrome to connect…"}))
@@ -16268,9 +16275,9 @@ def run_agent_chat(cfg):
16268
16275
  _emit({"type": "step", "text": "Using gu's own Chrome window" if where == "chrome"
16269
16276
  else "Using your Chrome (gu extension)"})
16270
16277
  if not_connected:
16271
- _emit({"type": "step", "text": ("⚠ gu's browser bridge failed to start — /browser shows why"
16278
+ _emit({"type": "step", "text": ("⚠ gu's browser bridge failed to start"
16272
16279
  if str(res).startswith(_gb.BRIDGE_FAILED)
16273
- else "⚠ No browser gu can use — /browser shows why")})
16280
+ else "⚠ No browser gu can use")})
16274
16281
  msg = _gb.install_text(str(res))
16275
16282
  elif not ok:
16276
16283
  msg = f"Error: browser {a} failed: {res}"
@@ -16286,6 +16293,8 @@ def run_agent_chat(cfg):
16286
16293
  if ok and where == "chrome" and a == "open":
16287
16294
  msg = ("(gu's own Chrome window — a separate profile, not signed in to the user's "
16288
16295
  "accounts.)\n" + msg)
16296
+ if ok and where == "chrome" and _browser_consent.get("ext_note"):
16297
+ msg = _browser_consent.pop("ext_note") + "\n" + msg
16289
16298
  except Exception as ex: # noqa: BLE001
16290
16299
  msg = f"Error: browser {a} failed: {type(ex).__name__}: {ex}"
16291
16300
  _last_obs["text"] = msg
package/gu-repl.mjs CHANGED
@@ -150,6 +150,7 @@ import { readSkillSource, sourceLabel, SKILL_SOURCE_KEY } from "./skill-source.m
150
150
  import { codingBannerLabel, isOllamaCloudUrl, SECRET_KEY_HINT } from "./coding-key-prompt.mjs";
151
151
  import { questionEchoText, thoughtPrintSeq, wrapDiffText } from "./terminal-layout.mjs";
152
152
  import { globalPrefixOf } from "./install-path.mjs";
153
+ import { indentBlock } from "./terminal-layout.mjs"; // every line of an Allow-prompt detail indented (#189)
153
154
  import { firstGuOnPath, pathGuMismatch, guOnPathIsCurrent, updateAttemptRecord, repeatUpdateNotice } from "./update-verify.mjs";
154
155
  import { embedNotice, embedState, setupNoticeRows } from "./embed-model-command.mjs";
155
156
  import {
@@ -10796,7 +10797,7 @@ async function approvalPrompt(command) {
10796
10797
  if (!process.stdin.isTTY) return { allow: false, dontAsk: false };
10797
10798
  process.stdout.write(
10798
10799
  "\n" + yellow("🌐 Allow gu to use a web browser?") + dim(" (no answer in ~3 min = Yes, this time)") + "\n" +
10799
- dim(` It wants to: ${what || "open a page"}`) + "\n" +
10800
+ indentBlock(`It wants to: ${what || "open a page"}`, { paint: dim }) + "\n" +
10800
10801
  dim(" In your Chrome if the gu extension is there, else in gu's own Chrome window.") + "\n"
10801
10802
  );
10802
10803
  // "Yes, this time" is THE default (#380, GitHub #167): highlighted, so Enter allows it once, and
@@ -10818,7 +10819,7 @@ async function approvalPrompt(command) {
10818
10819
  if (!process.stdin.isTTY) return { allow: false, dontAsk: false };
10819
10820
  process.stdout.write(
10820
10821
  "\n" + yellow(`⚙ Allow the MCP tool ${server}/${tool}?`) + dim(" (no answer in ~3 min = No)") + "\n" +
10821
- (preview ? dim(" " + preview) + "\n" : "")
10822
+ (preview ? indentBlock(preview, { paint: dim }) + "\n" : "")
10822
10823
  );
10823
10824
  const idx = await pickFromList(
10824
10825
  ["Yes", `Yes, and always allow ${server}/${tool}`, `Yes, and always allow every ${server} tool`, "No"],
@@ -10862,8 +10863,8 @@ async function approvalPrompt(command) {
10862
10863
  return;
10863
10864
  }
10864
10865
  process.stdout.write(
10865
- "\n" + yellow("⚠ Allow running this command?") + "\n" + dim(" " + shown) + "\n" +
10866
- (why ? dim(" " + why) + "\n" : "")
10866
+ "\n" + yellow("⚠ Allow running this command?") + "\n" + indentBlock(shown, { paint: dim }) + "\n" +
10867
+ (why ? indentBlock(why, { paint: dim }) + "\n" : "")
10867
10868
  );
10868
10869
  approvalSel = 0;
10869
10870
  approvalResolve = resolve;
package/gu_browser.py CHANGED
@@ -169,7 +169,7 @@ def install_text(reason="not connected"):
169
169
  return (f"BROWSER NOT AVAILABLE ({reason}): the gu Chrome extension (Chrome Web Store) is "
170
170
  "installed but not connected — Chrome is probably closed. STOP and ask the user to "
171
171
  "open Chrome (the extension reconnects within 30 seconds, or its icon → Connect now), "
172
- "then continue. /browser in the gu terminal shows the status.")
172
+ "then continue.")
173
173
  # gu's own Chrome window needs no extension (#150), so this is reached only when there is no
174
174
  # Chrome to start at all.
175
175
  return (
@@ -180,6 +180,201 @@ def install_text(reason="not connected"):
180
180
  + (f" To use their own Chrome instead, they can add the gu extension: {STORE_URL}" if STORE_URL else ""))
181
181
 
182
182
 
183
+ # ── a new machine: is the gu extension in Chrome at all? (task #401, GitHub #191) ──────────────
184
+ # The agent finds out itself and tells the user what to do — no command for the user to type.
185
+ STORE_ID = "ldfcjapmdbgdkdhlbdkbkiankneabagj"
186
+ EXT_NAME = "gu browser"
187
+ OFFER_EVERY_S = 24 * 3600 # open the store page at most once a day, so a "no thanks" is not nagged
188
+
189
+
190
+ def browser_roots(home=None, platform=None, env=None):
191
+ """[(browser, profiles dir)] for each Chromium browser — same list as browser-command.mjs."""
192
+ home = home or os.path.expanduser("~")
193
+ platform = platform or sys.platform
194
+ env = os.environ if env is None else env
195
+ j = os.path.join
196
+ if platform == "darwin":
197
+ a = j(home, "Library", "Application Support")
198
+ return [("Chrome", j(a, "Google", "Chrome")), ("Chrome Beta", j(a, "Google", "Chrome Beta")),
199
+ ("Chrome Canary", j(a, "Google", "Chrome Canary")), ("Chromium", j(a, "Chromium")),
200
+ ("Edge", j(a, "Microsoft Edge")), ("Brave", j(a, "BraveSoftware", "Brave-Browser"))]
201
+ if platform.startswith("win"):
202
+ l = env.get("LOCALAPPDATA") or j(home, "AppData", "Local")
203
+ return [("Chrome", j(l, "Google", "Chrome", "User Data")), ("Chrome Beta", j(l, "Google", "Chrome Beta", "User Data")),
204
+ ("Chrome Canary", j(l, "Google", "Chrome SxS", "User Data")), ("Chromium", j(l, "Chromium", "User Data")),
205
+ ("Edge", j(l, "Microsoft", "Edge", "User Data")), ("Brave", j(l, "BraveSoftware", "Brave-Browser", "User Data"))]
206
+ c = env.get("XDG_CONFIG_HOME") or j(home, ".config")
207
+ return [("Chrome", j(c, "google-chrome")), ("Chrome Beta", j(c, "google-chrome-beta")), ("Chromium", j(c, "chromium")),
208
+ ("Edge", j(c, "microsoft-edge")), ("Brave", j(c, "BraveSoftware", "Brave-Browser"))]
209
+
210
+
211
+ def _is_gu(ext_id, entry):
212
+ if ext_id == STORE_ID or (entry.get("manifest") or {}).get("name") == EXT_NAME:
213
+ return True
214
+ path = entry.get("path")
215
+ if isinstance(path, str) and os.path.isabs(path):
216
+ try:
217
+ with open(os.path.join(path, "manifest.json"), encoding="utf-8") as f:
218
+ return json.load(f).get("name") == EXT_NAME
219
+ except (OSError, ValueError):
220
+ return False
221
+ return False
222
+
223
+
224
+ def find_installs(roots=None):
225
+ """→ [{browser, profile, id, kind: "store"|"developer", enabled}] for every browser profile with
226
+ the gu extension. Reads the profiles' Preferences only — gu never writes a browser's files."""
227
+ found = []
228
+ for browser, d in (browser_roots() if roots is None else roots):
229
+ try:
230
+ profiles = sorted(p for p in os.listdir(d) if p == "Default" or re.match(r"^Profile \d+$", p))
231
+ except OSError:
232
+ continue
233
+ for prof in profiles:
234
+ seen = set()
235
+ for fn in ("Secure Preferences", "Preferences"):
236
+ try:
237
+ with open(os.path.join(d, prof, fn), encoding="utf-8") as f:
238
+ settings = (json.load(f).get("extensions") or {}).get("settings") or {}
239
+ except (OSError, ValueError, AttributeError):
240
+ continue
241
+ for ext_id, e in settings.items():
242
+ if ext_id in seen or not isinstance(e, dict) or not _is_gu(ext_id, e):
243
+ continue
244
+ seen.add(ext_id)
245
+ reasons = e.get("disable_reasons")
246
+ enabled = not reasons and e.get("state", 1) != 0
247
+ found.append({"browser": browser, "profile": prof, "id": ext_id,
248
+ "kind": "store" if ext_id == STORE_ID else "developer", "enabled": enabled})
249
+ return found
250
+
251
+
252
+ def diagnose(installs):
253
+ """→ "missing" (not in any browser), "disabled" (only turned-off copies) or "installed"."""
254
+ if not installs:
255
+ return "missing"
256
+ return "installed" if any(i["enabled"] for i in installs) else "disabled"
257
+
258
+
259
+ def _offered_path():
260
+ return os.path.join(os.path.dirname(state_path()), "browser-extension-offered")
261
+
262
+
263
+ def should_offer(now=None):
264
+ try:
265
+ return (now or time.time()) - os.path.getmtime(_offered_path()) > OFFER_EVERY_S
266
+ except OSError:
267
+ return True
268
+
269
+
270
+ def mark_offered():
271
+ try:
272
+ os.makedirs(os.path.dirname(_offered_path()), exist_ok=True)
273
+ with open(_offered_path(), "w") as f:
274
+ f.write(str(int(time.time())))
275
+ except OSError:
276
+ pass
277
+
278
+
279
+ def open_store_page(url=None, platform=None):
280
+ """Open the extension's Chrome Web Store page — in Chrome when it is there. → whether it opened."""
281
+ url = url or STORE_URL
282
+ platform = platform or sys.platform
283
+ if not url or os.environ.get("GU_NO_OPEN_APPS"):
284
+ return False
285
+ try:
286
+ if platform == "darwin":
287
+ app = os.path.exists("/Applications/Google Chrome.app")
288
+ cmd = ["open", "-a", "Google Chrome", url] if app else ["open", url]
289
+ elif platform.startswith("win"):
290
+ cmd = ["cmd", "/c", "start", "", "chrome", url] if shutil.which("chrome") or os.path.exists(
291
+ os.path.join(os.environ.get("PROGRAMFILES", r"C:\Program Files"), "Google", "Chrome", "Application", "chrome.exe")) \
292
+ else ["explorer.exe", url]
293
+ else:
294
+ exe = next((shutil.which(n) for n in ("google-chrome", "google-chrome-stable", "chromium", "chromium-browser")
295
+ if shutil.which(n)), None)
296
+ cmd = [exe, url] if exe else ["xdg-open", url]
297
+ subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
298
+ **({"start_new_session": True} if os.name != "nt" else {}))
299
+ return True
300
+ except OSError:
301
+ return False
302
+
303
+
304
+ def setup_steps(state, installs=(), opened=False, url=None):
305
+ """The exact steps for the user, by what was found — the transcript shows them and the model
306
+ relays them. Never a command for the user to type."""
307
+ url = url or STORE_URL
308
+ if state == "missing":
309
+ where = ("gu opened its Chrome Web Store page in Chrome." if opened
310
+ else f"Open its Chrome Web Store page in Chrome: {url}")
311
+ return ["The gu Chrome extension is not installed in Chrome on this computer.",
312
+ where,
313
+ "Click \"Add to Chrome\", then \"Add extension\" — gu connects within a few seconds",
314
+ "and then works in your Chrome (your logins, tabs you share)."]
315
+ names = ", ".join(sorted({f"{i['browser']} ({i['profile']})" for i in installs}))
316
+ if state == "disabled":
317
+ return [f"The gu Chrome extension is installed but turned off ({names}).",
318
+ "Open chrome://extensions in Chrome and switch \"gu browser\" on."]
319
+ return [f"The gu Chrome extension is installed ({names}) but not connected —",
320
+ "Chrome is closed or the extension is asleep. Open Chrome: it connects",
321
+ "within 30 s (or click the gu icon → Connect now)."]
322
+
323
+
324
+ def _mark_seen(s):
325
+ try:
326
+ with open(seen_path(), "w") as f:
327
+ json.dump({"version": s.get("version"), "installType": s.get("installType")}, f)
328
+ except OSError:
329
+ pass
330
+
331
+
332
+ def ensure_extension(log=None, emit=None, wait_s=120, installs=None):
333
+ """Prefer the user's Chrome (task #401). When the extension is not connected, find out why
334
+ (not installed / turned off / installed but Chrome closed), open the store page when it is
335
+ missing, show the steps, and wait for it to connect.
336
+ → (connected, note): note is "" when connected, else the steps for the model to relay."""
337
+ st, _ = connect(wait=False, log=log, own=True)
338
+ if not st:
339
+ return False, "" # the bridge itself failed: command() reports that
340
+ try:
341
+ s = _http(st, "GET", "/status", timeout=5)
342
+ except OSError:
343
+ return False, ""
344
+ if s.get("connected"):
345
+ return True, ""
346
+ installs = find_installs() if installs is None else installs
347
+ state = diagnose(installs)
348
+ opened = False
349
+ if state == "missing" and should_offer():
350
+ opened = open_store_page()
351
+ mark_offered()
352
+ steps = setup_steps(state, installs, opened)
353
+ say = emit or (lambda _t: None)
354
+ for line in steps:
355
+ say(line)
356
+ if log:
357
+ log(f"browser: extension {state}, store page opened={opened}")
358
+ wait_total = wait_s if opened else 30 if state == "installed" else 0
359
+ end = time.time() + wait_total
360
+ if wait_total:
361
+ say("Waiting for the gu extension to connect…")
362
+ while time.time() < end:
363
+ chunk = int(min(60, max(1, end - time.time())) * 1000)
364
+ try:
365
+ s = _http(st, "GET", f"/status?wait_ms={chunk}", timeout=chunk / 1000 + 5)
366
+ except OSError:
367
+ break
368
+ if s.get("connected"):
369
+ _mark_seen(s)
370
+ say("✓ The gu extension is connected — using your Chrome.")
371
+ return True, ""
372
+ say("Using gu's own Chrome window for now.")
373
+ return False, ("GU EXTENSION NOT CONNECTED — gu is using its own Chrome window (a separate profile, "
374
+ "not signed in) for now. Tell the user, in these words, what to do so gu can use "
375
+ "their Chrome: " + " ".join(steps))
376
+
377
+
183
378
  def _node():
184
379
  return os.environ.get("GU_NODE") or shutil.which("node") or "node"
185
380
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiens.nguyen/gu-cli",
3
- "version": "1.0.844",
3
+ "version": "1.0.845",
4
4
  "description": "Gu CLI — the gu terminal plus the local worker that runs agent / OCR / PDF / embedding jobs on your Mac (Ollama / MLX / OpenAI-compatible).",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -3214,3 +3214,17 @@ export function tokenRowWithPrice({ withTotal = "", withoutTotal = "", price = "
3214
3214
  if (visibleLen(withTotal) + visibleLen(price) <= room) return withTotal + price;
3215
3215
  return withoutTotal + price;
3216
3216
  }
3217
+
3218
+
3219
+ /**
3220
+ * Indent EVERY line of a multi-line block (#189). The "Allow running this command?" prompt used
3221
+ * `dim(" " + command)`, which indents only the first line: a multi-line command (export …, cd …,
3222
+ * mkdir …, if … fi) came out ragged, the later lines at column 0. CRLF / lone CR (a command typed on
3223
+ * Windows) is treated like LF, trailing blank lines are dropped, and each line is painted on its own
3224
+ * so a terminal that resets colour at a newline (Windows console) still shows every line dimmed.
3225
+ */
3226
+ export function indentBlock(text, { indent = " ", paint = (s) => s } = {}) {
3227
+ const lines = String(text ?? "").split(/\r\n|\r|\n/);
3228
+ while (lines.length > 1 && lines[lines.length - 1].trim() === "") lines.pop();
3229
+ return lines.map((l) => paint(indent + l)).join("\n");
3230
+ }