@tiens.nguyen/gu-cli 1.0.846 → 1.0.848

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.
@@ -168,6 +168,88 @@ async function point(host, tabId, cmd) {
168
168
  throw new Error("say where: ref (a number from read) or x and y");
169
169
  }
170
170
 
171
+ // ── the visible gu cursor ───────────────────────────────────────────────────────────────────
172
+ // Runs IN the page. The DevTools input events move no real mouse pointer, so the user could not
173
+ // see where gu acts. This draws a purple "gu" arrow that glides to each point before gu clicks,
174
+ // hovers, types or scrolls there, and ripples on a click. It sits in a shadow root on <html> with
175
+ // pointer-events:none: it never takes a click, elementFromPoint looks through it, and read (which
176
+ // reads body.innerText) never sees it. Built with DOM calls only (no innerHTML), so pages with
177
+ // Trusted Types or strict CSP still show it. Returns how long the glide takes, in ms.
178
+ function guCursor(o) {
179
+ try {
180
+ const d = document;
181
+ const ID = "__gu_cursor";
182
+ let h = d.getElementById(ID);
183
+ if (!h || !h.__p) {
184
+ if (h) h.remove();
185
+ h = d.createElement("div");
186
+ h.id = ID;
187
+ h.style.cssText = "all:initial;position:fixed;left:0;top:0;width:0;height:0;overflow:visible;z-index:2147483647;pointer-events:none";
188
+ const root = h.attachShadow ? h.attachShadow({ mode: "open" }) : h;
189
+ const p = d.createElement("div");
190
+ p.style.cssText = "position:fixed;left:0;top:0;width:0;height:0;overflow:visible;pointer-events:none;will-change:transform;filter:drop-shadow(0 2px 3px rgba(0,0,0,.45))";
191
+ const NS = "http://www.w3.org/2000/svg";
192
+ const svg = d.createElementNS(NS, "svg");
193
+ svg.setAttribute("width", "28");
194
+ svg.setAttribute("height", "28");
195
+ svg.setAttribute("viewBox", "0 0 28 28");
196
+ svg.style.cssText = "display:block;position:absolute;left:0;top:0;overflow:visible";
197
+ const path = d.createElementNS(NS, "path");
198
+ path.setAttribute("d", "M3 2 L3 22 L8.5 17 L12 25.5 L15.5 24 L12 15.8 L19.5 15.8 Z");
199
+ path.setAttribute("fill", "#7c3aed");
200
+ path.setAttribute("stroke", "#ffffff");
201
+ path.setAttribute("stroke-width", "2");
202
+ path.setAttribute("stroke-linejoin", "round");
203
+ svg.appendChild(path);
204
+ const tag = d.createElement("div");
205
+ tag.textContent = "gu";
206
+ tag.style.cssText = "position:absolute;left:20px;top:24px;background:#7c3aed;color:#fff;font:600 11px/1 -apple-system,system-ui,sans-serif;padding:3px 6px;border-radius:8px;border:1.5px solid #fff;white-space:nowrap";
207
+ p.append(svg, tag);
208
+ root.appendChild(p);
209
+ h.__p = p;
210
+ h.__root = root;
211
+ }
212
+ if (!h.isConnected) (d.documentElement || d.body).appendChild(h);
213
+ const p = h.__p;
214
+ const x = Number(o.x), y = Number(o.y);
215
+ const first = h.dataset.x === undefined;
216
+ const fx = first ? x : Number(h.dataset.x), fy = first ? y : Number(h.dataset.y);
217
+ const at = (px, py) => `translate(${px - 3}px,${py - 2}px)`; // the arrow's tip is at (3,2)
218
+ const dist = Math.hypot(x - fx, y - fy);
219
+ const ms = first || dist < 2 ? 0 : Math.round(Math.min(450, Math.max(150, dist * 0.6)));
220
+ p.style.transform = at(x, y);
221
+ if (ms && p.animate) p.animate([{ transform: at(fx, fy) }, { transform: at(x, y) }], { duration: ms, easing: "cubic-bezier(.3,.7,.4,1)" });
222
+ h.dataset.x = String(x);
223
+ h.dataset.y = String(y);
224
+ const ripples = o.kind === "double_click" ? 2 : ["click", "right_click", "type"].includes(o.kind) ? 1 : 0;
225
+ const color = o.kind === "right_click" ? "#f59e0b" : "#a78bfa";
226
+ for (let i = 0; i < ripples; i++) {
227
+ setTimeout(() => {
228
+ const r = d.createElement("div");
229
+ r.style.cssText = `position:fixed;left:${x - 18}px;top:${y - 18}px;width:36px;height:36px;box-sizing:border-box;border:3px solid ${color};border-radius:50%;pointer-events:none;opacity:0`;
230
+ h.__root.appendChild(r);
231
+ if (r.animate) {
232
+ const an = r.animate([{ transform: "scale(.3)", opacity: 1 }, { transform: "scale(1.5)", opacity: 0 }], { duration: 550, easing: "ease-out" });
233
+ an.onfinish = () => r.remove();
234
+ } else setTimeout(() => r.remove(), 600);
235
+ }, ms + i * 160);
236
+ }
237
+ return ms;
238
+ } catch (e) {
239
+ return 0;
240
+ }
241
+ }
242
+
243
+ /** Shows the gu cursor at x,y and waits for its glide, so the user sees where gu acts. Never fails. */
244
+ async function showCursor(host, tabId, x, y, kind = "move") {
245
+ try {
246
+ const ms = await evaluate(host, tabId, `(${guCursor})(${JSON.stringify({ x, y, kind })})`);
247
+ if (ms) await sleep(Math.min(Number(ms) || 0, 500) + 40);
248
+ } catch {
249
+ // a page that refuses scripts still gets the click
250
+ }
251
+ }
252
+
171
253
  async function mouse(host, tabId, x, y, button = "left", clicks = 1) {
172
254
  await host.cdp(tabId, "Input.dispatchMouseEvent", { type: "mouseMoved", x, y });
173
255
  for (let i = 1; i <= clicks; i++) {
@@ -263,6 +345,7 @@ export async function runAction(cmd, host) {
263
345
  case "hover": {
264
346
  const p = await point(host, id, cmd);
265
347
  const hit = await hitAt(host, id, p.x, p.y);
348
+ await showCursor(host, id, p.x, p.y, a);
266
349
  if (a === "hover") await host.cdp(id, "Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x, y: p.y });
267
350
  else await mouse(host, id, p.x, p.y, a === "right_click" ? "right" : "left", a === "double_click" ? 2 : 1);
268
351
  await settle(host, id);
@@ -271,6 +354,7 @@ export async function runAction(cmd, host) {
271
354
  case "type": {
272
355
  if (hasRef(cmd)) {
273
356
  const p = await refPoint(host, id, cmd.ref);
357
+ await showCursor(host, id, p.x, p.y, "type");
274
358
  await mouse(host, id, p.x, p.y);
275
359
  if (cmd.clear) await pressKey(host, id, "ctrl+a");
276
360
  }
@@ -292,6 +376,7 @@ export async function runAction(cmd, host) {
292
376
  const dir = String(cmd.direction || "down").toLowerCase();
293
377
  const dx = dir === "left" ? -amount : dir === "right" ? amount : 0;
294
378
  const dy = dir === "up" ? -amount : dir === "down" ? amount : 0;
379
+ await showCursor(host, id, x, y, "scroll");
295
380
  await host.cdp(id, "Input.dispatchMouseEvent", { type: "mouseWheel", x, y, deltaX: dx, deltaY: dy });
296
381
  await sleep(300);
297
382
  return after(host, id, { scroll: await evaluate(host, id, "Math.round(scrollY) + ' of ' + Math.max(0, document.documentElement.scrollHeight - innerHeight)") });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "gu browser",
4
- "version": "1.0.4",
4
+ "version": "1.0.5",
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": {
@@ -7972,7 +7972,7 @@ def _ws_shell_command_risk(scan, denyset, wd="", allowset=None, roots=None):
7972
7972
  if "$" in a[0] or "`" in a[0]:
7973
7973
  return (None, None, f"the program to run is only known at run time ({a[0][:40]})")
7974
7974
  for c in every:
7975
- if _WS_DESTRUCTIVE_RE.search(" ".join(c["argv"])):
7975
+ if _WS_DESTRUCTIVE_RE.search(" ".join(c["argv"])) and not _agent_created_owns_delete(c["argv"], wd):
7976
7976
  return (None, None, "a destructive command (deletes files / wipes disk / powers off)")
7977
7977
  return (None, None, None)
7978
7978
 
@@ -8796,6 +8796,71 @@ _WS_DESTRUCTIVE_RE = re.compile(
8796
8796
  # files) and the system temp folder deleting stays free; anywhere else it asks.
8797
8797
  _WS_DELETE_RUNNERS = {"rm", "rmdir", "unlink", "del", "erase", "rd", "remove-item", "trash"}
8798
8798
 
8799
+ # ---- GU'S OWN FILES (issue #194): deleting a file gu itself made is cleanup, not risk -------
8800
+ # The edit/create tools and run_command redirects register every path they make in this session
8801
+ # set. When a later command deletes NOTHING BUT registered files - a bare `rm FILE...` with no
8802
+ # flags (no -r), no globs, no recursion - the destructive question would be gu asking to undo
8803
+ # its own work, so it just runs. Anything else (a flag, a path gu did not make, `rm -r`) asks
8804
+ # exactly as before. Entries leave the set when gu deletes the file, and the set is capped.
8805
+ _AGENT_CREATED_FILES = set()
8806
+ _AGENT_CREATED_MAX = 500
8807
+
8808
+
8809
+ def _agent_created_add(path):
8810
+ """Remember a file gu just made, so cleaning it up later asks nothing."""
8811
+ if not path:
8812
+ return
8813
+ try:
8814
+ path = os.path.realpath(path)
8815
+ except OSError:
8816
+ return
8817
+ while len(_AGENT_CREATED_FILES) >= _AGENT_CREATED_MAX:
8818
+ _AGENT_CREATED_FILES.pop() # arbitrary member - the cap is the point
8819
+ _AGENT_CREATED_FILES.add(path)
8820
+
8821
+
8822
+ def _agent_created_forget(path):
8823
+ try:
8824
+ _AGENT_CREATED_FILES.discard(os.path.realpath(path))
8825
+ except OSError:
8826
+ pass
8827
+
8828
+
8829
+ def _agent_created_rm_targets(argv, wd):
8830
+ """Resolved targets of a bare `rm FILE...`, or [] when anything makes it more than that."""
8831
+ runner = os.path.basename(argv[0]).lower() if argv else ""
8832
+ if runner.endswith(".exe"):
8833
+ runner = runner[:-4]
8834
+ if runner not in ("rm", "unlink"):
8835
+ return []
8836
+ args = [a for a in argv[1:] if a != "--"]
8837
+ files = [a for a in args if not a.startswith("-")]
8838
+ flags = "".join(a.lstrip("-") for a in args if a.startswith("-"))
8839
+ if not files:
8840
+ return []
8841
+ # The destructive gate wakes on -r/-f; a delete gets DANGEROUS on -r (a whole tree, maybe
8842
+ # more than what gu wrote), so that keeps asking even for our own. -f (and any other
8843
+ # non-recursive flag) just silences prompts for the SAME files - inherits the own-files pass.
8844
+ if "r" in flags.lower():
8845
+ return []
8846
+ targets = []
8847
+ for t in files:
8848
+ if any(ch in t for ch in "*?["):
8849
+ return [] # a GLOB can match files gu never made
8850
+ p = os.path.expanduser(_shell_path_to_native(t))
8851
+ p = p if os.path.isabs(p) else os.path.join(wd or os.getcwd(), p)
8852
+ try:
8853
+ targets.append(os.path.realpath(p))
8854
+ except OSError:
8855
+ return []
8856
+ return targets
8857
+
8858
+
8859
+ def _agent_created_owns_delete(argv, wd=""):
8860
+ """True only when the command deletes NOTHING BUT files gu itself made this session."""
8861
+ targets = _agent_created_rm_targets(argv, wd)
8862
+ return bool(targets) and all(t in _AGENT_CREATED_FILES for t in targets)
8863
+
8799
8864
 
8800
8865
  def _ws_delete_targets(argv):
8801
8866
  """The paths a delete command would remove ([] = not a delete)."""
@@ -8972,7 +9037,7 @@ def _ws_command_risk(command, argv, denyset, wd=""):
8972
9037
  outside = _ws_delete_outside_reason(argv, wd)
8973
9038
  if outside:
8974
9039
  return (outside, outside)
8975
- if _WS_DESTRUCTIVE_RE.search(cmd):
9040
+ if _WS_DESTRUCTIVE_RE.search(cmd) and not _agent_created_owns_delete(argv, wd):
8976
9041
  return (None, "a destructive command (deletes files / wipes disk / powers off)")
8977
9042
  return (None, None)
8978
9043
 
@@ -9207,6 +9272,7 @@ def _ws_write_file(path: str, content: str, action: str, backup) -> None:
9207
9272
  with open(target, "w", encoding="utf-8") as fh:
9208
9273
  fh.write(content)
9209
9274
  os.unlink(tmp)
9275
+ _agent_created_add(target)
9210
9276
  except BaseException:
9211
9277
  try:
9212
9278
  os.unlink(tmp)
@@ -15579,6 +15645,26 @@ def run_agent_chat(cfg):
15579
15645
  if _interactive_approval and _job_id:
15580
15646
  _accept_edits = _live_accept_edits(worker_api_base, worker_api_key,
15581
15647
  _job_id, _accept_edits)
15648
+ # Track what this line CREATES, so cleaning it up later is not a question
15649
+ # (issue #194): redirect targets inside the project join the own-files set;
15650
+ # an rm of nothing-but-own-files leaves it again once the line ran.
15651
+ if _use_shell and _scan.get("tokens"):
15652
+ for _oc in _shell_commands(_scan["tokens"]):
15653
+ _oa = _oc["argv"]
15654
+ if _agent_created_owns_delete(_oa, wd):
15655
+ for _ot in _agent_created_rm_targets(_oa, wd):
15656
+ _agent_created_forget(_ot)
15657
+ continue
15658
+ for _o, _otgt in _oc["redirects"]:
15659
+ if _o in (">", ">>", "1>", "1>>") and _otgt and not _otgt.startswith("&"):
15660
+ _op = os.path.expanduser(_otgt)
15661
+ _op = _op if os.path.isabs(_op) else os.path.join(wd or os.getcwd(), _op)
15662
+ try:
15663
+ _opr = os.path.realpath(_op)
15664
+ if any(_ws_is_inside(_opr, [os.path.realpath(r["path"])]) for r in _WS_ROOTS if r.get("path")):
15665
+ _agent_created_add(_opr)
15666
+ except Exception: # noqa: BLE001
15667
+ pass
15582
15668
  # ACCEPT EDITS OFF ⇒ ASK BEFORE RUNNING ANYTHING (task #179). The risk gate is
15583
15669
  # the FLOOR, not the whole policy: sudo and rm -rf ask either way, and turning
15584
15670
  # the toggle off raises the bar to every command. Off is the cautious setting,
package/gu-repl.mjs CHANGED
@@ -121,6 +121,7 @@ import {
121
121
  NO_MODEL_LINES,
122
122
  resizeRepaintTarget,
123
123
  workspaceSyncQuestion,
124
+ workspaceAccessQuestion,
124
125
  workspaceSyncLabel,
125
126
  activeCoderName,
126
127
  easeCount,
@@ -5133,24 +5134,21 @@ async function ensureWorkspace() {
5133
5134
  console.log(GUTTER + dim("RAG cannot index a folder this size, and file tools would range"));
5134
5135
  console.log(GUTTER + dim("over all of it. Answer n, then re-run gu inside a project."));
5135
5136
  }
5136
- const register = await askYesNo(
5137
- scopeWarning
5138
- ? "Register it anyway?"
5139
- : "Register it so the agent can read/edit code here?",
5140
- !scopeWarning /* default Yes for a normal folder, NO for a too-broad one */
5141
- );
5137
+ // ONE question covers register + run-commands + browser (GitHub #192). Yes = all three,
5138
+ // persisted, so gu never asks again for this folder.
5139
+ const access = workspaceAccessQuestion({ scopeWarning });
5140
+ for (const l of access.intro) console.log(GUTTER + dim(l));
5141
+ const register = await askYesNo(access.question, access.defaultYes);
5142
5142
  if (!register) {
5143
5143
  console.log(GUTTER + dim("Skipped — the agent will not be able to touch files here."));
5144
5144
  return;
5145
5145
  }
5146
- const allowRun = await askYesNo(
5147
- "Do you trust this folder — allow the agent to RUN build/test commands\n" +
5148
- "(npm test, mvn, pytest…)?",
5149
- true /* default Yes — you opened THIS folder with gu deliberately, and the
5150
- action-first workflows (start/test/build the project) need it; commands are
5151
- still allowlisted (npm/mvn/pytest/…) and run with a scrubbed env. Type n to
5152
- keep a workspace read/edit-only. */
5153
- );
5146
+ const allowRun = true;
5147
+ try {
5148
+ allowIn(cwd, true); // the browser's "always allow in this folder" list
5149
+ } catch (e) {
5150
+ console.log(GUTTER + yellow(`Could not save the browser permission (${e?.message || e}) — gu will ask when it first needs it.`));
5151
+ }
5154
5152
  // On Client Expert there is no cloud to sync TO — see workspaceSyncQuestion.
5155
5153
  const syncQ = workspaceSyncQuestion({ clientExpert: isClientExpert() });
5156
5154
  const allowSync = syncQ.ask
@@ -5175,7 +5173,7 @@ async function ensureWorkspace() {
5175
5173
  console.log(
5176
5174
  GUTTER +
5177
5175
  accent(`✓ workspace registered: ${basename(cwd)}`) +
5178
- (allowRun ? accent(" (run-commands enabled)") : dim(" (run-commands disabled)")) +
5176
+ (allowRun ? accent(" (run-commands + browser enabled)") : dim(" (run-commands disabled)")) +
5179
5177
  (isClientExpert()
5180
5178
  ? ""
5181
5179
  : allowSync
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiens.nguyen/gu-cli",
3
- "version": "1.0.846",
3
+ "version": "1.0.848",
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",
@@ -2571,6 +2571,28 @@ export function workspaceSyncQuestion({ clientExpert }) {
2571
2571
  : { ask: true, value: null, note: "" };
2572
2572
  }
2573
2573
 
2574
+ /**
2575
+ * The ONE first-run question for a new folder (GitHub #192). It used to be two or three separate
2576
+ * Y/n prompts (register, trust to run commands, then the browser on first use). They are one
2577
+ * decision, "may gu work in this folder?", so the answer covers all three, and the list says
2578
+ * exactly what Yes grants. A too-broad folder (home, /) flips the default to No.
2579
+ */
2580
+ export function workspaceAccessQuestion({ scopeWarning = "" } = {}) {
2581
+ return {
2582
+ intro: [
2583
+ "With your OK, gu can do these in this folder:",
2584
+ " • read and edit your code",
2585
+ " • run build/test commands (npm test, mvn, pytest…)",
2586
+ " • open and click web pages in your browser (UI tests)",
2587
+ "You can undo the browser part any time with /browser forget.",
2588
+ ],
2589
+ question: scopeWarning
2590
+ ? "Register it anyway and allow all of that?"
2591
+ : "Register this folder and allow all of that?",
2592
+ defaultYes: !scopeWarning,
2593
+ };
2594
+ }
2595
+
2574
2596
  /**
2575
2597
  * A counter that CLIMBS to its new value instead of jumping (user, 2026-09-05: "lets make it
2576
2598
  * dynamically going up so we can see it increase slowly… like 400 then 410, then 440, then 470