@tiens.nguyen/gu-cli 1.0.904 → 1.0.906

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.
@@ -192,19 +192,17 @@ export class OwnChrome {
192
192
  const pages = await this.pages();
193
193
  const reuse = newTab ? null : pages.find((t) => t.targetId === this.current) || pages[0];
194
194
  // A new tab starts blank and is navigated once attached, so its load events are seen.
195
- const id = reuse ? reuse.targetId : (await this.send("Target.createTarget", { url: "about:blank" })).targetId;
195
+ const id = reuse ? reuse.targetId : (await this.send("Target.createTarget", { url: "about:blank", background: true })).targetId;
196
196
  await this.host().attach(id);
197
197
  this.loading.add(id);
198
198
  await this.cdp(id, "Page.navigate", { url });
199
- this.current = id;
200
- await this.send("Target.activateTarget", { targetId: id }).catch(() => {});
199
+ this.current = id; // gu does not bring the tab to the front (#422)
201
200
  return id;
202
201
  },
203
202
  tabs: async () => (await this.pages()).map((t) => ({ id: t.targetId, title: t.title, url: t.url, current: t.targetId === this.current })),
204
203
  switchTo: async (id) => {
205
204
  if (!(await this.pages()).some((t) => t.targetId === id)) return false;
206
205
  this.current = id;
207
- await this.send("Target.activateTarget", { targetId: id }).catch(() => {});
208
206
  return true;
209
207
  },
210
208
  current: async () => {
@@ -333,10 +333,16 @@ export async function runAction(cmd, host) {
333
333
  case "read":
334
334
  return { ...(await evaluate(host, id, `(${readPage})(${JSON.stringify({ maxText: cmd.max_text || 6000 })})`)), ...(await after(host, id)) };
335
335
  case "screenshot": {
336
- await host.activate(id); // a background tab is not painted
336
+ // #422: try the background tab first; only when that fails or stalls is the TAB (never the
337
+ // window) brought forward, because some Chrome versions do not paint a hidden tab.
338
+ const grab = () => host.cdp(id, "Page.captureScreenshot", { format: "jpeg", quality: 80 });
339
+ let shot = await Promise.race([grab().catch(() => null), sleep(cmd.shot_wait_ms || 4000).then(() => null)]);
340
+ if (!shot) {
341
+ await host.activate(id);
342
+ shot = await grab();
343
+ }
337
344
  const m = await host.cdp(id, "Page.getLayoutMetrics");
338
345
  const vp = m.cssVisualViewport || m.visualViewport || {};
339
- const shot = await host.cdp(id, "Page.captureScreenshot", { format: "jpeg", quality: 80 });
340
346
  return { ...(await after(host, id)), image: shot.data, mime: "image/jpeg", width: Math.round(vp.clientWidth), height: Math.round(vp.clientHeight) };
341
347
  }
342
348
  case "click":
@@ -209,13 +209,14 @@ const host = {
209
209
  const tabs = await liveTabs();
210
210
  const s = await state();
211
211
  let tab = newTab ? null : tabs.find((t) => t.id === s.current) || tabs[tabs.length - 1];
212
- if (tab) tab = await chrome.tabs.update(tab.id, { url, active: true });
212
+ // #422: never bring the tab or the window to the front — gu drives it over the debugger, which
213
+ // works on a background tab, so the user's own tab and window keep the focus.
214
+ if (tab) tab = await chrome.tabs.update(tab.id, { url });
213
215
  else {
214
- tab = await chrome.tabs.create({ url, active: true });
216
+ tab = await chrome.tabs.create({ url, active: false });
215
217
  await addToGroup(tab.id);
216
218
  }
217
219
  await saveState({ current: tab.id });
218
- await chrome.windows.update(tab.windowId, { focused: true }).catch(() => {});
219
220
  return tab.id;
220
221
  },
221
222
  async tabs() {
@@ -225,8 +226,7 @@ const host = {
225
226
  async switchTo(tabId) {
226
227
  const id = Number(tabId);
227
228
  if (!(await liveTabs()).some((t) => t.id === id)) return false;
228
- await chrome.tabs.update(id, { active: true });
229
- await saveState({ current: id });
229
+ await saveState({ current: id }); // gu's current tab only — the user's visible tab is left alone (#422)
230
230
  return true;
231
231
  },
232
232
  async current() {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "gu browser",
4
- "version": "1.0.5",
4
+ "version": "1.0.6",
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": {
@@ -5076,6 +5076,66 @@ def _dsml_to_code_block(text):
5076
5076
  return (prose + "\n" if prose else "") + "<code>\n" + body + "\n</code>"
5077
5077
 
5078
5078
 
5079
+ # DeepSeek DSML calls to ANY tool (issue #420). Seen live: a DSML invoke name="python_interpreter"
5080
+ # with a DSML parameter name="content" string="true" holding plain Python. The #119 reading only
5081
+ # knew name="code", so this reached the user as the final answer and nothing ran. A python /
5082
+ # code invoke IS the code; any other tool becomes print(tool(k=v)).
5083
+ _DSML_T = r"<[^<>\n]{0,8}DSML[^<>\n]{0,8}"
5084
+ _DSML_CLOSE_T = r"</[^<>\n]{0,8}DSML[^<>\n]{0,8}"
5085
+ _DSML_INVOKE = re.compile(_DSML_T + r"invoke\s+name\s*=\s*[\x22\x27]([A-Za-z_]\w*)[\x22\x27]\s*>")
5086
+ _DSML_PARAM = re.compile(
5087
+ _DSML_T + r"parameter\s+name\s*=\s*[\x22\x27]([A-Za-z_]\w*)[\x22\x27]"
5088
+ r"(?:\s+string\s*=\s*[\x22\x27](true|false)[\x22\x27])?\s*>([\s\S]*?)"
5089
+ r"(?:" + _DSML_CLOSE_T + r"parameter\s*>|" + _DSML_CLOSE_T + r"invoke\s*>|" + _DSML_CLOSE_T
5090
+ + r"calls\s*>|(?=" + _DSML_T + r"parameter\b)|(?=" + _DSML_T + r"invoke\b)|$)")
5091
+ _DSML_CODE_TOOLS = {"python_interpreter", "code", "python", "run_python"}
5092
+ _DSML_BLOCK = re.compile(_DSML_T + r"calls\s*>[\s\S]*?(?:" + _DSML_CLOSE_T + r"calls\s*>|$)")
5093
+ _DSML_STRAY = re.compile(r"</?[^<>\n]{0,8}DSML[^<>]*>")
5094
+
5095
+
5096
+ def _dsml_calls_to_code_block(text):
5097
+ """Rewrite DSML invoke/parameter calls of any tool into a code block, or return the text
5098
+ unchanged (no code tag already, and the result must COMPILE)."""
5099
+ if not text or "DSML" not in text or re.search(r"<\s*/?\s*code\b", text, re.I):
5100
+ return text
5101
+ invokes = list(_DSML_INVOKE.finditer(text))
5102
+ if not invokes:
5103
+ return text
5104
+ parts = []
5105
+ for i, m in enumerate(invokes):
5106
+ seg = text[m.end(): invokes[i + 1].start() if i + 1 < len(invokes) else len(text)]
5107
+ params = [(pm.group(1), pm.group(2), pm.group(3)) for pm in _DSML_PARAM.finditer(seg)]
5108
+ name = m.group(1)
5109
+ if name in _DSML_CODE_TOOLS:
5110
+ if not params or not params[0][2].strip():
5111
+ return text
5112
+ parts.append(params[0][2].strip("\n"))
5113
+ else:
5114
+ args = []
5115
+ for k, flag, val in params:
5116
+ val = val.strip("\n")
5117
+ lit = repr(val)
5118
+ if flag == "false":
5119
+ if val in _TC_JSON_WORDS:
5120
+ lit = _TC_JSON_WORDS[val]
5121
+ else:
5122
+ try:
5123
+ json.loads(val)
5124
+ lit = val
5125
+ except Exception: # noqa: BLE001
5126
+ lit = repr(val)
5127
+ args.append(k + "=" + lit)
5128
+ parts.append("print(" + name + "(" + ", ".join(args) + "))")
5129
+ body = "\n".join(parts)
5130
+ try:
5131
+ compile(body, "<gu-code>", "exec")
5132
+ except Exception: # noqa: BLE001
5133
+ return text
5134
+ first = _DSML_ANY.search(text)
5135
+ prose = text[:first.start()].rstrip() if first else ""
5136
+ return (prose + "\n" if prose else "") + "<" "code>\n" + body + "\n</" "code>"
5137
+
5138
+
5079
5139
  # DeepSeek plain tool-call markup (issue #133). Besides the DSML form above, DeepSeek-family
5080
5140
  # models answer with <tool_calls><invoke name="X"><parameter name="k" string="true">v</parameter>
5081
5141
  # </invoke></tool_calls>. That matched nothing, so it reached the user as the FINAL answer (an
@@ -5091,6 +5151,9 @@ _TC_JSON_WORDS = {"true": "True", "false": "False", "null": "None"}
5091
5151
 
5092
5152
  def _strip_toolcall_markup(text):
5093
5153
  """Remove tool_calls/invoke/parameter markup from text that is shown to the user."""
5154
+ if text and "DSML" in text:
5155
+ # DSML calls (#420): drop the whole calls block (its parameters hold code, not prose).
5156
+ text = _DSML_STRAY.sub("", _DSML_BLOCK.sub("", text)).strip()
5094
5157
  if not text or ("<tool_calls" not in text and "<invoke" not in text and "<parameter" not in text):
5095
5158
  return text
5096
5159
  return _TC_STRAY.sub("", _TC_BLOCK.sub("", text)).strip()
@@ -5196,6 +5259,10 @@ def _canonicalise_code_reply(text):
5196
5259
  if _dsml != text:
5197
5260
  _log("DSML tool-call markup converted to a code block (#119)")
5198
5261
  return _dsml
5262
+ _dsml2 = _dsml_calls_to_code_block(text)
5263
+ if _dsml2 != text:
5264
+ _log("DSML tool-call (any tool) converted to a code block (#420)")
5265
+ return _dsml2
5199
5266
  _tc = _toolcalls_to_code_block(text)
5200
5267
  if _tc != text:
5201
5268
  _log("tool_calls/invoke markup converted to a code block (#133)")
@@ -8308,6 +8375,7 @@ def _ws_shell_command_risk(scan, denyset, wd="", allowset=None, roots=None):
8308
8375
  for c in every:
8309
8376
  here = cwds.get(id(c), wd)
8310
8377
  if (_WS_DESTRUCTIVE_RE.search(" ".join(c["argv"]))
8378
+ and not _ws_readonly_argv(c["argv"])
8311
8379
  and not _agent_created_owns_delete(c["argv"], wd)
8312
8380
  and not _ws_delete_inside_only(c["argv"], here, roots)):
8313
8381
  return (None, None, "a destructive command (deletes files / wipes disk / powers off)")
@@ -9150,6 +9218,55 @@ _WS_DESTRUCTIVE_RE = re.compile(
9150
9218
  )
9151
9219
 
9152
9220
 
9221
+ # READ-ONLY COMMANDS NEVER ASK (GH: "cd / ls still ask to allow"). cd, ls, cat, grep, git status …
9222
+ # change nothing, so neither the "accept edits is off" blanket question nor the destructive-word
9223
+ # regex (which matched ARGUMENTS such as `ls dd`, `cat reboot.md`, `grep shutdown`) applies to a
9224
+ # line made only of them. A redirect to a file, `sed -i`, `find -delete`, `env x` etc. are not here.
9225
+ _WS_READONLY_CMDS = {
9226
+ "cd", "ls", "pwd", "cat", "head", "tail", "wc", "echo", "printf", "which", "type", "file",
9227
+ "stat", "du", "df", "tree", "grep", "egrep", "fgrep", "rg", "basename", "dirname", "realpath",
9228
+ "readlink", "whoami", "date", "uname", "cut", "diff", "test", "[", "true",
9229
+ "false", "id", "hostname", "nl", "less", "more", "tr", "column", "jq", "lsof", "ps",
9230
+ }
9231
+ _WS_READONLY_GIT = {"status", "log", "diff", "show", "rev-parse", "ls-files", "blame",
9232
+ "describe", "shortlog", "ls-remote"}
9233
+
9234
+
9235
+ def _ws_readonly_argv(argv):
9236
+ """True when this one simple command only reads."""
9237
+ if not argv:
9238
+ return False
9239
+ r = os.path.basename(argv[0])
9240
+ if r in _WS_READONLY_CMDS:
9241
+ return True
9242
+ if r == "git":
9243
+ rest = [x for x in argv[1:] if not x.startswith("-")]
9244
+ return bool(rest) and rest[0] in _WS_READONLY_GIT and "--set" not in argv \
9245
+ and not any(x.startswith("--output") for x in argv)
9246
+ return False
9247
+
9248
+
9249
+ def _ws_shell_all_readonly(scan):
9250
+ """True when EVERY simple command in a shell line (inside $( ) too) only reads and nothing
9251
+ is redirected into a file (2>/dev/null and 2>&1 are fine)."""
9252
+ try:
9253
+ if not scan or scan.get("error"):
9254
+ return False
9255
+ top, inner = _shell_all_commands(scan)
9256
+ every = top + inner
9257
+ if not every:
9258
+ return False
9259
+ for c in every:
9260
+ if not _ws_readonly_argv(c["argv"]):
9261
+ return False
9262
+ for _o, tgt in c["redirects"]:
9263
+ if tgt and tgt != "/dev/null" and not tgt.startswith("&"):
9264
+ return False
9265
+ return True
9266
+ except Exception: # noqa: BLE001
9267
+ return False
9268
+
9269
+
9153
9270
  # A DELETE OUTSIDE THE PROJECT IS THE USER'S CALL (runaway fix, 09-25). The destructive pattern
9154
9271
  # above only knows `rm -r` / `rm -f`, so `rm a.img b.img` sailed through: an unattended agent,
9155
9272
  # short of disk space, deleted two OTHER emulators' userdata-qemu.img in ~/.android/avd — files
@@ -9457,7 +9574,8 @@ def _ws_command_risk(command, argv, denyset, wd=""):
9457
9574
  outside = _ws_delete_outside_reason(argv, wd)
9458
9575
  if outside:
9459
9576
  return (outside, outside)
9460
- if (_WS_DESTRUCTIVE_RE.search(cmd) and not _agent_created_owns_delete(argv, wd)
9577
+ if (_WS_DESTRUCTIVE_RE.search(cmd) and not _ws_readonly_argv(argv)
9578
+ and not _agent_created_owns_delete(argv, wd)
9461
9579
  and not _ws_delete_inside_only(argv, wd)):
9462
9580
  return (None, "a destructive command (deletes files / wipes disk / powers off)")
9463
9581
  return (None, None)
@@ -10519,6 +10637,23 @@ def _ws_scrubbed_env() -> dict:
10519
10637
  # PowerShell finds its own modules (Microsoft.PowerShell.*) through it (#374).
10520
10638
  "PSModulePath")
10521
10639
  env = {k: os.environ[k] for k in keep if k in os.environ}
10640
+ # gu's own Python environment (~/.gonext/venv) FIRST on PATH: the document skills (xlsx, pptx, docx, pdf) are run as
10641
+ # `python scripts/...` and their libraries were installed there by `gu-cli deps`. Without this a bare `python` is the
10642
+ # system one (on Windows 11 often the Microsoft Store stub) and every import fails.
10643
+ try:
10644
+ venv_bin = os.path.join(os.path.expanduser("~"), ".gonext", "venv", "Scripts" if os.name == "nt" else "bin")
10645
+ if os.path.isdir(venv_bin):
10646
+ env["PATH"] = venv_bin + os.pathsep + env.get("PATH", "")
10647
+ env["VIRTUAL_ENV"] = os.path.dirname(venv_bin)
10648
+ except Exception:
10649
+ pass
10650
+ # The docx / pptx skills `require('docx')` / `require('pptxgenjs')`; `gu-cli deps` installs them here.
10651
+ try:
10652
+ node_libs = os.path.join(os.path.expanduser("~"), ".gonext", "node-libs", "node_modules")
10653
+ if os.path.isdir(node_libs):
10654
+ env["NODE_PATH"] = node_libs + (os.pathsep + env["NODE_PATH"] if env.get("NODE_PATH") else "")
10655
+ except Exception:
10656
+ pass
10522
10657
  # CI=1 makes watch-mode test runners (CRA's `npm test`, jest --watch) run ONCE and
10523
10658
  # exit instead of sitting in interactive watch mode until the timeout kills them.
10524
10659
  env["CI"] = "1"
@@ -16087,7 +16222,9 @@ def run_agent_chat(cfg):
16087
16222
  # the FLOOR, not the whole policy: sudo and rm -rf ask either way, and turning
16088
16223
  # the toggle off raises the bar to every command. Off is the cautious setting,
16089
16224
  # so it may only ever add questions — never remove one.
16090
- if not _ask_reason and not _accept_edits:
16225
+ _ro_line = (not _ps) and ((_use_shell and _ws_shell_all_readonly(_scan))
16226
+ or (not _use_shell and _ws_readonly_argv(argv)))
16227
+ if not _ask_reason and not _accept_edits and not _ro_line:
16091
16228
  # gu-repl.mjs approvalPrompt matches this prefix to offer "Yes for all later ones" (#200)
16092
16229
  _ask_reason = "accept edits is off, so every command is confirmed first"
16093
16230
  # ELEVATION: find out what we are ALLOWED to do before asking, so the question
@@ -16116,7 +16253,7 @@ def run_agent_chat(cfg):
16116
16253
  and _cmd_allowed_in(wd or _WS_ACTIVE or _default_ws_root())):
16117
16254
  # accept-edits OFF still confirms every command, so only the destructive
16118
16255
  # question is dropped, not that one.
16119
- _ask_reason = None if _accept_edits else (
16256
+ _ask_reason = None if (_accept_edits or _ro_line) else (
16120
16257
  "accept edits is off, so every command is confirmed first")
16121
16258
  if _ask_reason:
16122
16259
  if _priv and _facts:
@@ -16829,6 +16966,16 @@ def run_agent_chat(cfg):
16829
16966
  + _gb.format_result("read", res))
16830
16967
  else:
16831
16968
  msg = _gb.format_result(a, res)
16969
+ if a in ("open", "click", "double_click", "right_click", "type", "key", "back", "reload"):
16970
+ # GH #421: show the page after an action, so the model needs no extra `read` step
16971
+ try:
16972
+ ok2, res2, _nc2 = _gb.command({"action": "read"}, log=_log, own=True)
16973
+ if ok2 and isinstance(res2, dict):
16974
+ res2.pop("_backend", None)
16975
+ msg = msg.replace("\n(read or screenshot to see the page now)", "") \
16976
+ + "\n--- the page now (no need to read again) ---\n" + _gb.format_read(res2)
16977
+ except Exception: # noqa: BLE001
16978
+ pass
16832
16979
  if ok and where == "chrome" and a == "open":
16833
16980
  msg = ("(gu's own Chrome window — a separate profile, not signed in to the user's "
16834
16981
  "accounts.)\n" + msg)
@@ -16968,7 +17115,8 @@ def run_agent_chat(cfg):
16968
17115
  every call: an "Always allow" answered a moment ago was written there."""
16969
17116
  allow, deny = _mcp_mod.read_rules(_mcp_cfg.get("configPath"),
16970
17117
  _mcp_cfg.get("allow") or [], _mcp_cfg.get("deny") or [])
16971
- verdict = _mcp_mod.decide(allow, deny, server, tool_name)
17118
+ _ask = _mcp_mod.read_ask(_mcp_cfg.get("configPath"), _mcp_cfg.get("ask") or [])
17119
+ verdict = _mcp_mod.decide(allow, deny, server, tool_name, _ask)
16972
17120
  if verdict == "deny":
16973
17121
  return False, (f"MCP tool {server}/{tool_name} is blocked by a deny rule in "
16974
17122
  "~/.gonext/mcp.json. Do not call it again; carry on without it.")
package/gu-cli.mjs CHANGED
@@ -126,7 +126,7 @@ Usage:
126
126
  gu-cli stop [--models] # stop the daemon (--models: the model servers too)
127
127
  gu-cli logs [--lines N] [-f] # tail the background daemon log
128
128
  gu-cli logs <port|pid|chat|embed> [-f] # tail a MODEL server's log (e.g. logs 8090 -f)
129
- gu-cli deps # install the agent's Python packages (smolagents + openai)
129
+ gu-cli deps # install the agent's Python packages (smolagents + openai) and the document skills' libraries
130
130
  gu-cli doctor [--client] # set up models here (--client: agent deps only,
131
131
  # models stay on another machine)
132
132
  gu-cli api <start|stop|restart|status|upgrade> # the LOCAL API (Local/Client Expert only);
@@ -1832,9 +1832,11 @@ if (args[0] === "deps") {
1832
1832
  return typed === "" ? defYes : /^y(es)?$/.test(typed);
1833
1833
  },
1834
1834
  modelHost: false,
1835
- agreed: ["agentLibs"],
1835
+ agreed: ["agentLibs", "skillsLibs"],
1836
+ skillsPack: true,
1836
1837
  });
1837
1838
  const ok = out.agentLibs === "installed" || out.agentLibs === "present";
1839
+ if (ok && out.skillsLibs === "failed") console.log("\n ! some of the document skills' Python libraries did not install — see " + md.PIP_LOG_FILE);
1838
1840
  console.log(ok ? "\n ✓ the agent framework is ready." : "\n ✗ the agent framework is not installed — see the message above and " + md.PIP_LOG_FILE);
1839
1841
  process.exit(ok ? 0 : 1);
1840
1842
  }
package/gu-repl.mjs CHANGED
@@ -14740,7 +14740,7 @@ async function main() {
14740
14740
  // #325: say whose they are when this folder uses Claude Code's — even when there are none.
14741
14741
  const claudes = readSkillSource(process.cwd()) === "claude";
14742
14742
  if (bits.length || claudes) {
14743
- statusRows.push(lbl("skills") + dim((claudes ? "Claude's: " : "") + (bits.join(" · ") || "no skills or MCP servers") + (claudes ? " (/switch-skill · /mcp)" : " (/help · /mcp)")));
14743
+ statusRows.push(lbl("skills") + dim((bits.join(" · ") || "no skills or MCP servers") + (claudes ? " (/switch-skill · /mcp)" : " (/help · /mcp)")));
14744
14744
  }
14745
14745
  } catch {
14746
14746
  /* a broken file is reported below; the banner is not the place to fail */
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:
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.904",
3
+ "version": "1.0.906",
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
 
@@ -7,13 +7,15 @@ import argparse
7
7
  import logging
8
8
  import shutil
9
9
  import subprocess
10
+ import tempfile
10
11
  from pathlib import Path
11
12
 
12
- from office.soffice import get_soffice_env
13
+ from office.soffice import get_soffice_env, soffice_binary
13
14
 
14
15
  logger = logging.getLogger(__name__)
15
16
 
16
- LIBREOFFICE_PROFILE = "/tmp/libreoffice_docx_profile"
17
+ LIBREOFFICE_PROFILE = (Path(tempfile.gettempdir()) / "libreoffice_docx_profile").as_posix()
18
+ PROFILE_URI = Path(LIBREOFFICE_PROFILE).as_uri()
17
19
  MACRO_DIR = f"{LIBREOFFICE_PROFILE}/user/basic/Standard"
18
20
 
19
21
  ACCEPT_CHANGES_MACRO = """<?xml version="1.0" encoding="UTF-8"?>
@@ -56,9 +58,9 @@ def accept_changes(
56
58
  return None, "Error: Failed to setup LibreOffice macro"
57
59
 
58
60
  cmd = [
59
- "soffice",
61
+ soffice_binary(),
60
62
  "--headless",
61
- f"-env:UserInstallation=file://{LIBREOFFICE_PROFILE}",
63
+ f"-env:UserInstallation={PROFILE_URI}",
62
64
  "--norestore",
63
65
  "vnd.sun.star.script:Standard.Module1.AcceptAllTrackedChanges?language=Basic&location=application",
64
66
  str(output_path.absolute()),
@@ -98,9 +100,9 @@ def _setup_libreoffice_macro() -> bool:
98
100
  if not macro_dir.exists():
99
101
  subprocess.run(
100
102
  [
101
- "soffice",
103
+ soffice_binary(),
102
104
  "--headless",
103
- f"-env:UserInstallation=file://{LIBREOFFICE_PROFILE}",
105
+ f"-env:UserInstallation={PROFILE_URI}",
104
106
  "--terminate_after_init",
105
107
  ],
106
108
  capture_output=True,
@@ -17,16 +17,42 @@ callers that build their own argv (they must pass -env:UserInstallation too).
17
17
 
18
18
  import contextlib
19
19
  import os
20
+ import shutil
20
21
  import socket
21
22
  import subprocess
23
+ import sys
22
24
  import tempfile
23
25
  from collections.abc import Iterable
24
26
  from pathlib import Path
25
27
 
26
28
 
29
+ def soffice_binary() -> str:
30
+ """Path to soffice. On Windows (and macOS) LibreOffice is rarely on PATH, so look in its usual
31
+ install folders; fall back to the bare name so a missing install still raises FileNotFoundError."""
32
+ found = shutil.which("soffice")
33
+ if found:
34
+ return found
35
+ candidates = []
36
+ if sys.platform == "win32":
37
+ for var in ("ProgramFiles", "ProgramFiles(x86)", "ProgramW6432"):
38
+ base = os.environ.get(var)
39
+ if base:
40
+ candidates.append(Path(base) / "LibreOffice" / "program" / "soffice.exe")
41
+ local = os.environ.get("LOCALAPPDATA")
42
+ if local:
43
+ candidates.append(Path(local) / "Programs" / "LibreOffice" / "program" / "soffice.exe")
44
+ elif sys.platform == "darwin":
45
+ candidates.append(Path("/Applications/LibreOffice.app/Contents/MacOS/soffice"))
46
+ for candidate in candidates:
47
+ if candidate.is_file():
48
+ return str(candidate)
49
+ return "soffice"
50
+
51
+
27
52
  def get_soffice_env() -> dict:
28
53
  env = os.environ.copy()
29
- env["SAL_USE_VCLPLUGIN"] = "svp"
54
+ if sys.platform != "win32": # the headless "svp" VCL plugin does not exist on Windows builds
55
+ env["SAL_USE_VCLPLUGIN"] = "svp"
30
56
 
31
57
  if _needs_shim():
32
58
  shim = _ensure_shim()
@@ -43,7 +69,7 @@ def run_soffice(args: Iterable[str], **kwargs) -> subprocess.CompletedProcess:
43
69
  tempfile.TemporaryDirectory(prefix="lo_profile_", ignore_cleanup_errors=True)
44
70
  )
45
71
  args = [f"-env:UserInstallation={Path(profile).as_uri()}"] + args
46
- return subprocess.run(["soffice"] + args, env=get_soffice_env(), **kwargs)
72
+ return subprocess.run([soffice_binary()] + args, env=get_soffice_env(), **kwargs)
47
73
 
48
74
 
49
75
 
@@ -51,8 +77,14 @@ _SHIM_SO = Path(tempfile.gettempdir()) / "lo_socket_shim.so"
51
77
 
52
78
 
53
79
  def _needs_shim() -> bool:
80
+ # The shim is an LD_PRELOAD library: Linux only. Windows Python has no socket.AF_UNIX at all.
81
+ if sys.platform != "linux":
82
+ return False
83
+ af_unix = getattr(socket, "AF_UNIX", None)
84
+ if af_unix is None:
85
+ return False
54
86
  try:
55
- s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
87
+ s = socket.socket(af_unix, socket.SOCK_STREAM)
56
88
  s.close()
57
89
  return False
58
90
  except OSError:
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: pdf
3
- description: Use this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multiple PDFs into one, splitting PDFs apart, rotating pages, adding watermarks, creating new PDFs, filling PDF forms, encrypting/decrypting PDFs, extracting images, and OCR on scanned PDFs to make them searchable. If the user mentions a .pdf file or asks to produce one, use this skill.
3
+ description: Use for any PDF task: read or extract text and tables, merge, split, rotate, watermark, fill forms, encrypt, extract images, OCR, or create a PDF.
4
4
  license: Complete terms in LICENSE.txt
5
5
  ---
6
6
 
@@ -7,6 +7,7 @@ from pdf2image import convert_from_path
7
7
 
8
8
 
9
9
  def convert(pdf_path, output_dir, max_dim=1000):
10
+ os.makedirs(output_dir, exist_ok=True)
10
11
  images = convert_from_path(pdf_path, dpi=200)
11
12
 
12
13
  for i, image in enumerate(images):
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: pptx
3
- description: "Use this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or presentations as PowerPoint (.pptx) files; reading, parsing, or extracting text from any .pptx or .potx file (even if the extracted content will be used elsewhere, like in an email, summary, or creating a different type of slide deck); editing, modifying, or updating existing presentations; combining or splitting slide files; working with templates (.potx), layouts, speaker notes, or comments. Trigger whenever the user asks for a PowerPoint or .pptx file, or references a .pptx or .potx filename, regardless of what they plan to do with the content afterward. When the user asks for a deck, slides or a presentation without naming a file format, use this skill."
3
+ description: "Use when a .pptx or .potx is involved, or the user wants slides, a deck or a presentation: create, read, edit, combine, split, templates, speaker notes."
4
4
  license: Complete terms in LICENSE.txt
5
5
  ---
6
6
 
@@ -17,16 +17,42 @@ callers that build their own argv (they must pass -env:UserInstallation too).
17
17
 
18
18
  import contextlib
19
19
  import os
20
+ import shutil
20
21
  import socket
21
22
  import subprocess
23
+ import sys
22
24
  import tempfile
23
25
  from collections.abc import Iterable
24
26
  from pathlib import Path
25
27
 
26
28
 
29
+ def soffice_binary() -> str:
30
+ """Path to soffice. On Windows (and macOS) LibreOffice is rarely on PATH, so look in its usual
31
+ install folders; fall back to the bare name so a missing install still raises FileNotFoundError."""
32
+ found = shutil.which("soffice")
33
+ if found:
34
+ return found
35
+ candidates = []
36
+ if sys.platform == "win32":
37
+ for var in ("ProgramFiles", "ProgramFiles(x86)", "ProgramW6432"):
38
+ base = os.environ.get(var)
39
+ if base:
40
+ candidates.append(Path(base) / "LibreOffice" / "program" / "soffice.exe")
41
+ local = os.environ.get("LOCALAPPDATA")
42
+ if local:
43
+ candidates.append(Path(local) / "Programs" / "LibreOffice" / "program" / "soffice.exe")
44
+ elif sys.platform == "darwin":
45
+ candidates.append(Path("/Applications/LibreOffice.app/Contents/MacOS/soffice"))
46
+ for candidate in candidates:
47
+ if candidate.is_file():
48
+ return str(candidate)
49
+ return "soffice"
50
+
51
+
27
52
  def get_soffice_env() -> dict:
28
53
  env = os.environ.copy()
29
- env["SAL_USE_VCLPLUGIN"] = "svp"
54
+ if sys.platform != "win32": # the headless "svp" VCL plugin does not exist on Windows builds
55
+ env["SAL_USE_VCLPLUGIN"] = "svp"
30
56
 
31
57
  if _needs_shim():
32
58
  shim = _ensure_shim()
@@ -43,7 +69,7 @@ def run_soffice(args: Iterable[str], **kwargs) -> subprocess.CompletedProcess:
43
69
  tempfile.TemporaryDirectory(prefix="lo_profile_", ignore_cleanup_errors=True)
44
70
  )
45
71
  args = [f"-env:UserInstallation={Path(profile).as_uri()}"] + args
46
- return subprocess.run(["soffice"] + args, env=get_soffice_env(), **kwargs)
72
+ return subprocess.run([soffice_binary()] + args, env=get_soffice_env(), **kwargs)
47
73
 
48
74
 
49
75
 
@@ -51,8 +77,14 @@ _SHIM_SO = Path(tempfile.gettempdir()) / "lo_socket_shim.so"
51
77
 
52
78
 
53
79
  def _needs_shim() -> bool:
80
+ # The shim is an LD_PRELOAD library: Linux only. Windows Python has no socket.AF_UNIX at all.
81
+ if sys.platform != "linux":
82
+ return False
83
+ af_unix = getattr(socket, "AF_UNIX", None)
84
+ if af_unix is None:
85
+ return False
54
86
  try:
55
- s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
87
+ s = socket.socket(af_unix, socket.SOCK_STREAM)
56
88
  s.close()
57
89
  return False
58
90
  except OSError:
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: xlsx
3
- description: "Use this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like \"the xlsx in my downloads\") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved."
3
+ description: "Use when a spreadsheet (.xlsx, .xlsm, .csv, .tsv) is the input or output: open, edit, fix, clean, add formulas or charts, convert. Not for Word, HTML or the Google Sheets API."
4
4
  license: Complete terms in LICENSE.txt
5
5
  ---
6
6
 
@@ -17,16 +17,42 @@ callers that build their own argv (they must pass -env:UserInstallation too).
17
17
 
18
18
  import contextlib
19
19
  import os
20
+ import shutil
20
21
  import socket
21
22
  import subprocess
23
+ import sys
22
24
  import tempfile
23
25
  from collections.abc import Iterable
24
26
  from pathlib import Path
25
27
 
26
28
 
29
+ def soffice_binary() -> str:
30
+ """Path to soffice. On Windows (and macOS) LibreOffice is rarely on PATH, so look in its usual
31
+ install folders; fall back to the bare name so a missing install still raises FileNotFoundError."""
32
+ found = shutil.which("soffice")
33
+ if found:
34
+ return found
35
+ candidates = []
36
+ if sys.platform == "win32":
37
+ for var in ("ProgramFiles", "ProgramFiles(x86)", "ProgramW6432"):
38
+ base = os.environ.get(var)
39
+ if base:
40
+ candidates.append(Path(base) / "LibreOffice" / "program" / "soffice.exe")
41
+ local = os.environ.get("LOCALAPPDATA")
42
+ if local:
43
+ candidates.append(Path(local) / "Programs" / "LibreOffice" / "program" / "soffice.exe")
44
+ elif sys.platform == "darwin":
45
+ candidates.append(Path("/Applications/LibreOffice.app/Contents/MacOS/soffice"))
46
+ for candidate in candidates:
47
+ if candidate.is_file():
48
+ return str(candidate)
49
+ return "soffice"
50
+
51
+
27
52
  def get_soffice_env() -> dict:
28
53
  env = os.environ.copy()
29
- env["SAL_USE_VCLPLUGIN"] = "svp"
54
+ if sys.platform != "win32": # the headless "svp" VCL plugin does not exist on Windows builds
55
+ env["SAL_USE_VCLPLUGIN"] = "svp"
30
56
 
31
57
  if _needs_shim():
32
58
  shim = _ensure_shim()
@@ -43,7 +69,7 @@ def run_soffice(args: Iterable[str], **kwargs) -> subprocess.CompletedProcess:
43
69
  tempfile.TemporaryDirectory(prefix="lo_profile_", ignore_cleanup_errors=True)
44
70
  )
45
71
  args = [f"-env:UserInstallation={Path(profile).as_uri()}"] + args
46
- return subprocess.run(["soffice"] + args, env=get_soffice_env(), **kwargs)
72
+ return subprocess.run([soffice_binary()] + args, env=get_soffice_env(), **kwargs)
47
73
 
48
74
 
49
75
 
@@ -51,8 +77,14 @@ _SHIM_SO = Path(tempfile.gettempdir()) / "lo_socket_shim.so"
51
77
 
52
78
 
53
79
  def _needs_shim() -> bool:
80
+ # The shim is an LD_PRELOAD library: Linux only. Windows Python has no socket.AF_UNIX at all.
81
+ if sys.platform != "linux":
82
+ return False
83
+ af_unix = getattr(socket, "AF_UNIX", None)
84
+ if af_unix is None:
85
+ return False
54
86
  try:
55
- s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
87
+ s = socket.socket(af_unix, socket.SOCK_STREAM)
56
88
  s.close()
57
89
  return False
58
90
  except OSError:
@@ -18,10 +18,13 @@ import time
18
18
  import zipfile
19
19
  from pathlib import Path
20
20
 
21
- from office.soffice import get_soffice_env, run_soffice
21
+ from office.soffice import get_soffice_env, run_soffice, soffice_binary
22
22
 
23
23
  MACRO_FILENAME = "Module1.xba"
24
- SOFFICE_MISSING = "soffice not found on PATH; LibreOffice is required to recalculate"
24
+ SOFFICE_MISSING = (
25
+ "soffice not found; LibreOffice is required to recalculate "
26
+ "(Windows: winget install TheDocumentFoundation.LibreOffice, macOS: brew install --cask libreoffice)"
27
+ )
25
28
 
26
29
  MAX_LOCATIONS = 100
27
30
 
@@ -198,7 +201,7 @@ def _recalc_with_profile(filename, abs_path, timeout, profile_dir: Path):
198
201
  before = _stamp(abs_path)
199
202
 
200
203
  cmd = [
201
- "soffice",
204
+ soffice_binary(),
202
205
  "--headless",
203
206
  "--norestore",
204
207
  f"-env:UserInstallation={profile_url}",
package/skills.mjs CHANGED
@@ -46,7 +46,8 @@ export const SKILL_NAME_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
46
46
  * (`overrides: "core"`), except the LOCKED ones other features depend on.
47
47
  */
48
48
  export function coreSkillsDir() {
49
- return join(dirname(fileURLToPath(import.meta.url)), "skills", "core");
49
+ // GU_CORE_SKILLS_DIR: a test (or a packager) can point at another folder; unset = the package's own.
50
+ return process.env.GU_CORE_SKILLS_DIR || join(dirname(fileURLToPath(import.meta.url)), "skills", "core");
50
51
  }
51
52
  /** Core skills a personal skill may not replace: hooks and the resume flow rely on them. */
52
53
  export const LOCKED_CORE_SKILLS = ["gu-session-memory-orchestration"];