@tiens.nguyen/gu-cli 1.0.905 → 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/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
- const hash = createHash("sha256").update(cwd).digest("hex").slice(0, 32);
5439
- return join(SESSIONS_DIR, `${hash}.json`);
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
- const raw = JSON.parse(await readFile(sessionFilePath(cwd), "utf8"));
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(sessionFilePath(cwd), "utf8")));
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(sessionFilePath(cwd), "utf8")) || {};
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 = sessionFilePath(cwd);
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(sessionFilePath(cwd), "utf8"));
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(sessionFilePath(cwd), "utf8"));
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(sessionFilePath(cwd), "utf8"));
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(sessionFilePath(cwd), "utf8"));
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(sessionFilePath(cwd), "utf8"));
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(sessionFilePath(cwd), "utf8"));
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(sessionFilePath(cwd), "utf8"));
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(sessionFilePath(cwd), "utf8"))?.quickModels);
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(sessionFilePath(cwd), "utf8")));
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(sessionFilePath(cwd), "utf8"));
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(sessionFilePath(cwd), "utf8"));
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(sessionFilePath(cwd), "utf8")) || {};
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
- // MERGE, DO NOT REPLACE. This used to write a whole fresh object, which silently dropped
6090
- // every key it does not own — promptBreakdown, the skip flags, the first-run step outcomes
6091
- // — while savePromptBreakdown dropped these in return. Two writers, each erasing the
6092
- // other's field, is how a `/model` pick survived being saved and was gone by the next
6093
- // launch. Object.assign onto what is already there keeps both halves.
6094
- await updateSessionFile(cwd, (raw) =>
6095
- Object.assign(raw, {
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, // remember the /server pick per folder (task #69)
6100
- maxCodeTokens: sessionMaxCodeTokens, // peak per-request tokens (task #84)
6101
- ragStorage: sessionRagStorage, // where this folder's RAG index lives (#133/#180)
6102
- showThought: sessionShowThought, // print the model's reasoning (task #148)
6103
- unfinishedTask, // what a bare "continue" resumes (#150/#189)
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
- history: trimmed,
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
@@ -24,6 +24,11 @@ EXT_FILES = ("manifest.json", "background.js", "actions.js", "popup.html", "popu
24
24
  BRIDGE = os.path.join(HERE, "browser-bridge.mjs")
25
25
 
26
26
 
27
+ # When the last full wait for the extension came up empty (GH #421): the wait is not repeated for
28
+ # every command of the turn.
29
+ _EXT_MISS = {"at": 0}
30
+
31
+
27
32
  def data_dir():
28
33
  return os.path.join(os.path.expanduser("~"), ".gonext")
29
34
 
@@ -501,7 +506,11 @@ def connect(wait=True, log=None, on_wait=None, own=False):
501
506
  # long only when an extension has connected before — otherwise it is most likely not installed.
502
507
  seen = os.path.exists(seen_path())
503
508
  if own:
504
- wait_ms = (8000 if seen else 0) if wait else 0 # then gu's own window
509
+ # GH #421: wait for a sleeping extension ONCE per turn. After a miss, every later command
510
+ # only asks the bridge for the current state (wait_ms=0) and goes on in gu's own window;
511
+ # an extension that has reconnected meanwhile is still picked up by that status call.
512
+ missed_lately = time.time() - _EXT_MISS["at"] < 300
513
+ wait_ms = (8000 if (seen and not missed_lately) else 0) if wait else 0 # then gu's own window
505
514
  else:
506
515
  wait_ms = (35000 if (seen and started) else 8000 if seen else 4000) if wait else 0
507
516
  if wait_ms >= 8000 and on_wait:
@@ -511,7 +520,10 @@ def connect(wait=True, log=None, on_wait=None, own=False):
511
520
  except OSError as e:
512
521
  return None, f"the gu browser bridge is not answering ({e})"
513
522
  if not s.get("connected"):
523
+ if own and wait_ms >= 8000:
524
+ _EXT_MISS["at"] = time.time()
514
525
  return (st, None) if own else (None, "extension not connected")
526
+ _EXT_MISS["at"] = 0
515
527
  mark = {"version": s.get("version"), "installType": s.get("installType")}
516
528
  if last_seen() != mark:
517
529
  try:
@@ -522,6 +534,64 @@ def connect(wait=True, log=None, on_wait=None, own=False):
522
534
  return st, None
523
535
 
524
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
+
525
595
  def command(cmd, log=None, on_wait=None, own=False):
526
596
  """Send one command. → (ok, result_or_error, not_connected).
527
597
  own=True: without the extension, the bridge uses gu's own Chrome window (#150). The result
@@ -551,6 +621,8 @@ def command(cmd, log=None, on_wait=None, own=False):
551
621
  # ── what the model reads ────────────────────────────────────────────────────────────────────
552
622
  def _head(res):
553
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}"
554
626
  for d in res.get("dialogs") or []:
555
627
  out += f"\nA dialog opened and gu accepted it: {d}"
556
628
  errs = res.get("errors") or []
@@ -580,8 +652,9 @@ def format_result(action, res):
580
652
  tabs = res.get("tabs") or []
581
653
  if not tabs:
582
654
  return "gu has no tab open."
583
- return "gu's tabs:\n" + "\n".join(
584
- f" {t['id']}{' (current)' if t.get('current') else ''}: {t.get('title') or ''} — {t.get('url')}" for t in tabs)
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)
585
658
  if a == "read":
586
659
  return format_read(res)
587
660
  if a == "close":
package/gu_mcp.py CHANGED
@@ -337,14 +337,36 @@ def rule_matches(rule: str, server: str, tool: str) -> bool:
337
337
  return re.fullmatch(".*".join(re.escape(x) for x in r.split("*")), full) is not None
338
338
 
339
339
 
340
- def decide(allow: list, deny: list, server: str, tool: str) -> str:
340
+ # Allowed out of the box (#419): the user asking gu to send an email IS the approval.
341
+ # `/mcp disallow email-server` writes an "ask" rule that switches this back off.
342
+ DEFAULT_ALLOW = ["mcp__email-server__*"]
343
+
344
+
345
+ def decide(allow: list, deny: list, server: str, tool: str, ask: list | None = None) -> str:
341
346
  if any(rule_matches(r, server, tool) for r in deny or []):
342
347
  return "deny"
348
+ if any(rule_matches(r, server, tool) for r in ask or []):
349
+ return "ask"
343
350
  if any(rule_matches(r, server, tool) for r in allow or []):
344
351
  return "allow"
352
+ if any(rule_matches(r, server, tool) for r in DEFAULT_ALLOW):
353
+ return "allow"
345
354
  return "ask"
346
355
 
347
356
 
357
+ def read_ask(config_path: str | None, ask: list | None = None) -> list:
358
+ """The "ask" rules the turn started with plus whatever the file says now."""
359
+ out = list(ask or [])
360
+ if config_path:
361
+ try:
362
+ with open(config_path, encoding="utf-8") as fh:
363
+ perms = (json.load(fh) or {}).get("permissions") or {}
364
+ out += [str(x) for x in perms.get("ask") or []]
365
+ except (OSError, ValueError, AttributeError):
366
+ pass
367
+ return out
368
+
369
+
348
370
  def read_rules(config_path: str | None, allow: list, deny: list) -> tuple[list, list]:
349
371
  """The rules the turn started with, plus whatever the file says NOW — an "Always allow" chosen
350
372
  at the terminal a moment ago is written there, and has to count for the next call."""
package/mcp-command.mjs CHANGED
@@ -23,6 +23,7 @@ import {
23
23
  addAllowRule,
24
24
  addServer,
25
25
  approveProjectServer,
26
+ DEFAULT_ALLOW,
26
27
  describeServer,
27
28
  listServers,
28
29
  parseAddArgs,
@@ -165,8 +166,9 @@ export async function runMcpCommand(words, { cwd = process.cwd(), print = consol
165
166
  print(statusLine(s, results[s.name]), results[s.name]?.ok ? "ok" : undefined);
166
167
  if (!s.error) print(` ${describeServer(s)}`, "dim");
167
168
  }
168
- const { allow, deny } = readUserConfig();
169
- if (allow.length) print(`Runs without asking: ${allow.join(", ")}`, "dim");
169
+ const { allow, deny, ask } = readUserConfig();
170
+ const builtinAllow = DEFAULT_ALLOW.filter((r) => !ask.some((a) => a === r));
171
+ if (allow.length || builtinAllow.length) print(`Runs without asking: ${[...allow, ...builtinAllow].join(", ")}`, "dim");
170
172
  if (deny.length) print(`Blocked: ${deny.join(", ")}`, "dim");
171
173
  print("Tools of one: /mcp tools <name>", "dim");
172
174
  return 0;
package/mcp-config.mjs CHANGED
@@ -82,6 +82,7 @@ export function readUserConfig(home = homedir()) {
82
82
  disabled: Array.isArray(cfg.disabled) ? cfg.disabled.map(String) : [],
83
83
  allow: Array.isArray(cfg.permissions?.allow) ? cfg.permissions.allow.map(String) : [],
84
84
  deny: Array.isArray(cfg.permissions?.deny) ? cfg.permissions.deny.map(String) : [],
85
+ ask: Array.isArray(cfg.permissions?.ask) ? cfg.permissions.ask.map(String) : [],
85
86
  approvedProjects: isObj(cfg.approvedProjects) ? cfg.approvedProjects : {},
86
87
  };
87
88
  }
@@ -217,6 +218,7 @@ export function mcpForTurn({ cwd, home = homedir(), source } = {}) {
217
218
  .map(({ name, command, args, env, scope }) => ({ name, command, args, env, scope })),
218
219
  allow: user.allow,
219
220
  deny: user.deny,
221
+ ask: user.ask,
220
222
  configPath: userConfigPath(home),
221
223
  };
222
224
  }
@@ -235,12 +237,20 @@ export function ruleMatches(rule, server, tool) {
235
237
  }
236
238
 
237
239
  /** → "deny" | "allow" | "ask". Deny first, then allow; nothing matching = ask. */
238
- export function decide({ allow = [], deny = [] }, server, tool) {
240
+ export function decide({ allow = [], deny = [], ask = [] }, server, tool) {
239
241
  if (deny.some((r) => ruleMatches(r, server, tool))) return "deny";
242
+ // An "ask" rule (written by /mcp disallow) switches a default-allowed server back to asking.
243
+ if (ask.some((r) => ruleMatches(r, server, tool))) return "ask";
240
244
  if (allow.some((r) => ruleMatches(r, server, tool))) return "allow";
245
+ if (DEFAULT_ALLOW.some((r) => ruleMatches(r, server, tool))) return "allow";
241
246
  return "ask";
242
247
  }
243
248
 
249
+ /** Servers whose tools run without the approval prompt out of the box (#419): the user asking gu
250
+ * to send an email IS the approval. /mcp disallow email-server turns it off. */
251
+ export const DEFAULT_ALLOW = ["mcp__email-server__*"];
252
+ export const DEFAULT_ALLOW_SERVERS = new Set(["email-server"]);
253
+
244
254
  /* ---------------------------------------------------------------- changes -------------- */
245
255
 
246
256
  export function addServer({ name, command, args = [], env = {}, scope = "user", cwd, home = homedir(), source }) {
@@ -337,11 +347,22 @@ export function addAllowRule({ rule, home = homedir() }) {
337
347
  const allow = Array.isArray(raw.permissions.allow) ? raw.permissions.allow : [];
338
348
  if (!allow.includes(rule)) allow.push(rule);
339
349
  raw.permissions.allow = allow;
350
+ // Allowing a server again undoes an earlier /mcp disallow of it.
351
+ const srv = /^mcp__(.+?)(?:__|$)/.exec(String(rule))?.[1];
352
+ if (srv && Array.isArray(raw.permissions.ask)) {
353
+ raw.permissions.ask = raw.permissions.ask.filter((r) => !(r === `mcp__${srv}` || String(r).startsWith(`mcp__${srv}__`)));
354
+ }
340
355
  }, home);
341
356
  }
342
357
 
343
358
  export function removeAllowRules({ server, home = homedir() }) {
344
359
  updateUserConfig((raw) => {
360
+ if (DEFAULT_ALLOW_SERVERS.has(server)) {
361
+ raw.permissions = isObj(raw.permissions) ? raw.permissions : {};
362
+ const ask = Array.isArray(raw.permissions.ask) ? raw.permissions.ask : [];
363
+ if (!ask.includes(`mcp__${server}__*`)) ask.push(`mcp__${server}__*`);
364
+ raw.permissions.ask = ask;
365
+ }
345
366
  if (isObj(raw.permissions) && Array.isArray(raw.permissions.allow)) {
346
367
  raw.permissions.allow = raw.permissions.allow.filter(
347
368
  (r) => !(r === `mcp__${server}` || String(r).startsWith(`mcp__${server}__`))
package/model-doctor.mjs CHANGED
@@ -1358,13 +1358,84 @@ export async function ensureClaudeSdk({ log, confirm }) {
1358
1358
  return (await pyHasModule("anthropic")) ? "installed" : "failed";
1359
1359
  }
1360
1360
 
1361
+ /** Python libraries the bundled document skills (xlsx, pptx, docx, pdf) import. */
1362
+ export const SKILLS_PY_PACKAGES = [
1363
+ "openpyxl", "pandas", "markitdown", "defusedxml", "lxml", "python-pptx", "Pillow", "pypdf", "pdfplumber", "pypdfium2", "pdf2image",
1364
+ ];
1365
+ /** The import names of the packages above that the skills cannot work without (markitdown is optional). */
1366
+ export const SKILLS_PY_MODULES = ["openpyxl", "pandas", "defusedxml", "lxml", "pptx", "PIL", "pypdf", "pdfplumber", "pypdfium2", "pdf2image"];
1367
+
1368
+ /**
1369
+ * The document skills' Python libraries, into the same interpreter the agent uses. All at once first; if that
1370
+ * fails (one wheel missing for this Python), one by one, so a single bad package does not cost the others.
1371
+ * Never fatal: the agent itself runs without them, only the document skills do not.
1372
+ */
1373
+ export async function ensureSkillsLibs({ log, confirm, agreed = [], pip = pipInstall, has = pyHasModule }) {
1374
+ if (await has(SKILLS_PY_MODULES.join(", "))) return "present";
1375
+ if (!agreed.includes("skillsLibs") && !(await confirm("Install the Python libraries the document skills use (xlsx, pptx, docx, pdf)? about 150 MB", true))) {
1376
+ log(` Skipped — install later: ${python3Bin()} -m pip install -U ${SKILLS_PY_PACKAGES.join(" ")}`);
1377
+ return "skipped";
1378
+ }
1379
+ const failed = [];
1380
+ try {
1381
+ await pip(SKILLS_PY_PACKAGES, log);
1382
+ } catch (e) {
1383
+ log(yellow(` ${e instanceof Error ? e.message : e}`));
1384
+ log(" retrying the skills' libraries one at a time …");
1385
+ for (const pkg of SKILLS_PY_PACKAGES) {
1386
+ try {
1387
+ await pip([pkg], log);
1388
+ } catch {
1389
+ failed.push(pkg);
1390
+ }
1391
+ }
1392
+ }
1393
+ // pipInstall may have moved to a private venv; the agent framework must be there too.
1394
+ if (!(await hasAgentLibs())) {
1395
+ try { await pip(["smolagents", "openai"], log); } catch (e) { log(yellow(` ${e instanceof Error ? e.message : e}`)); }
1396
+ }
1397
+ if (failed.length) log(yellow(` could not install: ${failed.join(", ")} — the skills that need them will say so.`));
1398
+ return (await has(SKILLS_PY_MODULES.join(", "))) ? "installed" : "failed";
1399
+ }
1400
+
1401
+ /** npm packages the docx and pptx skills `require()`; they were documented as preinstalled but nothing installed them. */
1402
+ export const SKILLS_NODE_PACKAGES = ["docx", "pptxgenjs"];
1403
+ /** Where they go: ~/.gonext/node-libs/node_modules (the agent shell gets it as NODE_PATH). */
1404
+ export function skillsNodeDir() {
1405
+ return join(homedir(), ".gonext", "node-libs");
1406
+ }
1407
+ function npmInstallInto(dir, pkgs) {
1408
+ const win = platform() === "win32";
1409
+ return new Promise((resolve, reject) => {
1410
+ execFile(win ? "npm.cmd" : "npm", ["install", "--prefix", dir, "--no-audit", "--no-fund", "--loglevel=error", ...pkgs],
1411
+ { shell: win, timeout: 600000, windowsHide: true }, (err, _out, errOut) => {
1412
+ if (err) reject(new Error(String(errOut || err.message).trim().split("\n").slice(-3).join(" ")));
1413
+ else resolve();
1414
+ });
1415
+ });
1416
+ }
1417
+ /** Install docx + pptxgenjs for the skills. Never fatal. -> "present" | "installed" | "failed" */
1418
+ export async function ensureSkillsNodeLibs({ log, install = npmInstallInto, dir = skillsNodeDir() } = {}) {
1419
+ const missing = () => SKILLS_NODE_PACKAGES.filter((p) => !existsSync(join(dir, "node_modules", p)));
1420
+ if (!missing().length) return "present";
1421
+ try {
1422
+ await mkdir(dir, { recursive: true });
1423
+ log(` installing ${missing().join(", ")} for the docx/pptx skills ...`);
1424
+ await install(dir, missing());
1425
+ } catch (e) {
1426
+ log(yellow(` could not install ${missing().join(", ")} (${e?.message ?? e}) - the docx/pptx skills will say so. Later: npm install --prefix "${dir}" ${SKILLS_NODE_PACKAGES.join(" ")}`));
1427
+ return "failed";
1428
+ }
1429
+ return missing().length ? "failed" : "installed";
1430
+ }
1431
+
1361
1432
  /**
1362
1433
  * `agreed` names packages the caller has ALREADY asked about (task #333): `gu` asks "Install the
1363
1434
  * agent framework now?" and then called this, which asked "Install the agent framework
1364
1435
  * (smolagents + openai) — required to run the agent?" — the same question twice in a row on
1365
1436
  * every first install. A yes that was just given is not asked for again.
1366
1437
  */
1367
- export async function ensureAgentDeps({ log, confirm, modelHost = canHostMlxModels(), agreed = [], os = platform(), installPython = null }) {
1438
+ export async function ensureAgentDeps({ log, confirm, modelHost = canHostMlxModels(), agreed = [], os = platform(), installPython = null, skillsPack = false }) {
1368
1439
  const out = {};
1369
1440
  log("");
1370
1441
  log(" Checking the agent's dependencies…");
@@ -1443,6 +1514,12 @@ export async function ensureAgentDeps({ log, confirm, modelHost = canHostMlxMode
1443
1514
  // nobody asked for (it fired during a test run against the developer's own config).
1444
1515
  out.python = await pinPythonForDaemon({ log });
1445
1516
  }
1517
+ // Opt-in (gu-cli deps, the installer): the first `gu` start must not ask a second question.
1518
+ if (skillsPack && (out.agentLibs === "present" || out.agentLibs === "installed")) {
1519
+ out.skillsLibs = await ensureSkillsLibs({ log, confirm, agreed });
1520
+ if (out.skillsLibs === "installed") out.python = await pinPythonForDaemon({ log });
1521
+ out.skillsNode = await ensureSkillsNodeLibs({ log });
1522
+ }
1446
1523
  return out;
1447
1524
  }
1448
1525
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiens.nguyen/gu-cli",
3
- "version": "1.0.905",
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",
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: docx
3
- description: "Use this skill whenever the user wants to create, read, edit, or manipulate Word documents (.docx) or Word templates (.dotx). Triggers include: any mention of Microsoft Word Documents, such as 'Word doc', 'word document', '.docx', '.dotx', 'microsoft doc'. Also use when extracting or reorganizing content from .docx or .dotx files, inserting or replacing images in documents, find-and-replace in Word files, working with tracked changes or comments, or converting content into a polished Word document. If the user asks for a deliverable as a Word or .docx file (to download, email or print), use this skill. Do NOT use for PDFs, spreadsheets, Google Docs, or coding unrelated to document generation."
3
+ description: "Use to create, read or edit Word documents (.docx, .dotx): tracked changes, comments, images, find and replace. Not for PDFs, spreadsheets or Google Docs."
4
4
  license: Complete terms in LICENSE.txt
5
5
  ---
6
6