@tiens.nguyen/gu-cli 1.0.931 → 1.0.935

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.
@@ -30,7 +30,7 @@ import os
30
30
  import random
31
31
  import re
32
32
  import socket
33
- from urllib.parse import urlparse
33
+ from urllib.parse import unquote, urlparse
34
34
  import sys
35
35
  import threading
36
36
  import time
@@ -3418,6 +3418,9 @@ _DEEPSEEK_THINKING_HOSTS = frozenset({
3418
3418
  })
3419
3419
 
3420
3420
 
3421
+ _OPENROUTER_HOST = "openrouter.ai"
3422
+
3423
+
3421
3424
  def _deepseek_thinking_kwargs(model_id, base_url="", env=None) -> dict:
3422
3425
  """Request fields that turn DeepSeek V4's thinking OFF in the coding loop (GH #430), or {}.
3423
3426
 
@@ -3434,11 +3437,14 @@ def _deepseek_thinking_kwargs(model_id, base_url="", env=None) -> dict:
3434
3437
  mode = str(env.get("GONEXT_DEEPSEEK_THINKING", "")).strip().lower()
3435
3438
  if mode in ("on", "1", "true", "yes"):
3436
3439
  return {}
3437
- if mode not in ("off", "0", "false", "no"):
3438
- from urllib.parse import urlparse
3439
- host = (urlparse(str(base_url or "")).hostname or "").lower().rstrip(".")
3440
- if host not in _DEEPSEEK_THINKING_HOSTS:
3441
- return {}
3440
+ from urllib.parse import urlparse
3441
+ host = (urlparse(str(base_url or "")).hostname or "").lower().rstrip(".")
3442
+ # GH #570, MEASURED 2026-12-03 (deepseek/deepseek-v4-pro): OpenRouter ignores DeepSeek's `thinking` field
3443
+ # (188 reasoning tokens with it, 396 without) and takes its own `reasoning` switch (0 with it).
3444
+ if host == _OPENROUTER_HOST:
3445
+ return {"extra_body": {"reasoning": {"enabled": False}}}
3446
+ if mode not in ("off", "0", "false", "no") and host not in _DEEPSEEK_THINKING_HOSTS:
3447
+ return {}
3442
3448
  return {"extra_body": {"thinking": {"type": "disabled"}}}
3443
3449
 
3444
3450
 
@@ -4693,7 +4699,37 @@ def _learn_context_window(base_url: str, model_id: str, err) -> int:
4693
4699
  _UNKNOWN_CTX_COMPACT_AT = 24000
4694
4700
 
4695
4701
 
4696
- def _compact_threshold(context_window: int) -> int:
4702
+ def _autocompact_path() -> str:
4703
+ """The user's autocompact choice (GH #538), written by gu's startup question and /autocompact."""
4704
+ return os.path.join(os.path.expanduser("~"), ".gonext", "autocompact.json")
4705
+
4706
+
4707
+ def _autocompact_cap(model_id: str = "") -> int:
4708
+ """The most prompt tokens a turn may grow to before older steps are compacted, or 0 for none.
4709
+
4710
+ GH #538. gu asks once (default 400k): compacting a 1M model near 2/3 of its window means every
4711
+ step of a long session resends ~666k tokens — slow and costly, for no gain on most tasks.
4712
+ The file: {"all": 400000 | null, "models": {"<model id>": 400000 | null}}. A model's own entry
4713
+ wins over "all"; null means "keep" (no cap: the 2/3 rule alone). Missing or unreadable → 0.
4714
+ """
4715
+ try:
4716
+ with open(_autocompact_path(), "r", encoding="utf-8") as fh:
4717
+ data = json.load(fh)
4718
+ except Exception: # noqa: BLE001 — no file is the normal case before the question is answered
4719
+ return 0
4720
+ if not isinstance(data, dict):
4721
+ return 0
4722
+ models = data.get("models") if isinstance(data.get("models"), dict) else {}
4723
+ key = str(model_id or "").strip().lower()
4724
+ val = models[key] if key and key in models else data.get("all")
4725
+ try:
4726
+ cap = int(val or 0)
4727
+ except (TypeError, ValueError):
4728
+ return 0
4729
+ return cap if cap >= 16000 else 0 # a nonsense value never shrinks the window to nothing
4730
+
4731
+
4732
+ def _compact_threshold(context_window: int, cap: int = 0) -> int:
4697
4733
  """Prompt tokens at which older steps get compacted.
4698
4734
 
4699
4735
  Two thirds of the window: late enough that a normal turn never trips it, early enough that
@@ -4708,10 +4744,14 @@ def _compact_threshold(context_window: int) -> int:
4708
4744
  the fix (GONEXT_CODING_CONTEXT_WINDOW) is discoverable instead of buried in a log.
4709
4745
 
4710
4746
  The docstring used to say 32k while the code returned 24000; the number is 24000.
4747
+
4748
+ `cap` (GH #538, _autocompact_cap): the user's limit — the threshold never goes above it.
4711
4749
  """
4712
4750
  if context_window and context_window > 4096:
4713
- return int(context_window * 2 / 3)
4714
- return _UNKNOWN_CTX_COMPACT_AT
4751
+ base = int(context_window * 2 / 3)
4752
+ else:
4753
+ base = _UNKNOWN_CTX_COMPACT_AT
4754
+ return min(base, cap) if cap and cap > 0 else base
4715
4755
 
4716
4756
 
4717
4757
  def _is_billing_failure(err) -> bool:
@@ -6831,14 +6871,15 @@ def _same_embed_model(a: str, b: str) -> bool:
6831
6871
  _RUNTOOL_PREFIX = "__RUNTOOL__::"
6832
6872
 
6833
6873
 
6834
- def _fmt_call(name: str, **kw) -> str:
6835
- """A tool call rendered the way the model writes it. Skips empty/default arguments."""
6874
+ def _fmt_call(_tool: str, /, **kw) -> str:
6875
+ """A tool call rendered the way the model writes it. Skips empty/default arguments.
6876
+ The tool name is positional-only: symbol_context has an argument called `name` (GH #552)."""
6836
6877
  parts = []
6837
6878
  for k, v in kw.items():
6838
6879
  if v is None or v == "" or (isinstance(v, int) and not isinstance(v, bool) and v == 0):
6839
6880
  continue
6840
6881
  parts.append(f"{k}={json.dumps(v)}" if isinstance(v, str) else f"{k}={v}")
6841
- return f"{name}({', '.join(parts)})"
6882
+ return f"{_tool}({', '.join(parts)})"
6842
6883
 
6843
6884
 
6844
6885
  def _emit_running(label: str, detail: str) -> None:
@@ -8025,6 +8066,131 @@ def _stray_script_char(code: str, filename: str = ""):
8025
8066
  return None
8026
8067
 
8027
8068
 
8069
+ def _lsp_post(lsp_cfg: dict, path: str, body: dict, timeout: float) -> dict:
8070
+ """POST to the worker's language-server host (lsp-host.mjs) on 127.0.0.1."""
8071
+ import urllib.request as _u
8072
+ req = _u.Request(lsp_cfg["url"] + path, data=json.dumps(body).encode("utf-8"), method="POST",
8073
+ headers={"Content-Type": "application/json", "X-Gu-Lsp-Token": str(lsp_cfg.get("token") or "")})
8074
+ # 127.0.0.1 must never go through a proxy from the environment.
8075
+ opener = _u.build_opener(_u.ProxyHandler({}))
8076
+ with opener.open(req, timeout=timeout) as resp:
8077
+ return json.loads(resp.read().decode("utf-8"))
8078
+
8079
+
8080
+ def _lsp_code_check(lsp_cfg, turn, rp, content, changed, workspace, ask=None, emit=None, log=None) -> str:
8081
+ """Text to add to a write tool's result: the file's errors from its language server, or "".
8082
+
8083
+ GH #540, like Claude Code's code-intelligence plugins: code that does not compile is reported in
8084
+ the SAME step that wrote it, so the agent fixes it before saying it is done. Never raises and
8085
+ never waits long: the host answers within a budget (3 s once the server is warm, 10 s while it
8086
+ starts), and every non-answer — no server, still starting, timeout — adds nothing.
8087
+
8088
+ `turn` is this turn's memory ({"warm": set(), "said": set()}); `ask(command) -> bool` puts the
8089
+ offer to the user (the terminal shows Yes / Not now / Never…); `changed` is [from, to] or None.
8090
+ """
8091
+ emit = emit or (lambda ev: None)
8092
+ log = log or (lambda s: None)
8093
+ if not lsp_cfg:
8094
+ return ""
8095
+ try:
8096
+ ext = os.path.splitext(rp)[1].lower()
8097
+ if ext not in (lsp_cfg.get("exts") or []):
8098
+ return ""
8099
+ budget = 3000 if ext in turn["warm"] else 10000
8100
+ body = {"file": rp, "text": content, "changed": changed, "workspace": workspace, "budgetMs": budget}
8101
+ r = _lsp_post(lsp_cfg, "/check", body, budget / 1000 + 5)
8102
+ if r.get("status") == "offer":
8103
+ command = "__LSP__::" + "\t".join([
8104
+ str(r.get("lang") or ""), str(r.get("name") or ""), str(r.get("server") or ""),
8105
+ "install" if r.get("needsInstall") else "on", str(r.get("size") or "")])
8106
+ if not (ask and ask(command)):
8107
+ return ""
8108
+ body["budgetMs"] = 10000
8109
+ r = _lsp_post(lsp_cfg, "/check", body, 15)
8110
+ status = r.get("status")
8111
+ server = str(r.get("server") or "language server")
8112
+ if status == "installing":
8113
+ if server not in turn["said"]:
8114
+ turn["said"].add(server)
8115
+ emit({"type": "step", "text": f"Installing language server → {server} (errors are checked from the next edit)"})
8116
+ return ""
8117
+ if status != "ok":
8118
+ if status not in ("off", "unsupported"):
8119
+ log(f"code check skipped for {rp}: {status} {r.get('why') or ''}".rstrip())
8120
+ return ""
8121
+ turn["warm"].add(ext)
8122
+ n_err, n_warn, rows = int(r.get("errors") or 0), int(r.get("warnings") or 0), r.get("rows") or []
8123
+ total = n_err + n_warn
8124
+ # "problems", not "errors": the step row groups with the look-ups instead of popping as a
8125
+ # failure — the agent is about to fix them; the user is told when the TURN fails.
8126
+ emit({"type": "step", "text": f"Checking code → {os.path.basename(rp)}: "
8127
+ + (f"{total} problem{'s' if total != 1 else ''}" if total else "no problems")})
8128
+ if not total:
8129
+ return f"\n\nCode check ({server}): no errors."
8130
+ head = f"{n_err} error{'s' if n_err != 1 else ''}" + (
8131
+ f", {n_warn} warning{'s' if n_warn != 1 else ''} on the changed lines" if n_warn else "")
8132
+ lines = [f" line {x.get('line')}:{x.get('col')} {x.get('kind')}: {x.get('message')}" for x in rows]
8133
+ if total > len(rows):
8134
+ lines.append(f" (+{total - len(rows)} more)")
8135
+ return (f"\n\nCode check ({server}) — {head}:\n" + "\n".join(lines)
8136
+ + "\nThese come from the language's own compiler/type checker. Fix them before you finish.")
8137
+ except Exception as e: # noqa: BLE001 — a code check must never break a write
8138
+ log(f"code check failed for {rp}: {e}")
8139
+ return ""
8140
+
8141
+
8142
+ _LSP_OPS = ("definition", "references", "type", "symbol")
8143
+
8144
+
8145
+ def _lsp_query_text(lsp_cfg, op, rp, line, symbol, workspace) -> str:
8146
+ """The `lsp` tool's answer (GH #541): what the language server says about a symbol, as text.
8147
+
8148
+ Paths are shown relative to the workspace, each with its line's own text, so the model can act
8149
+ on them without another read. Every failure is a sentence that points back to the grep tools.
8150
+ """
8151
+ op = str(op or "").strip().lower()
8152
+ if op not in _LSP_OPS:
8153
+ return f"Error: operation must be one of {', '.join(_LSP_OPS)}."
8154
+ if op != "symbol" and not int(line or 0):
8155
+ return "Error: give the line (1-based) where the symbol appears in that file."
8156
+ try:
8157
+ r = _lsp_post(lsp_cfg, "/query", {"op": op, "file": rp, "line": int(line or 0), "symbol": symbol or "",
8158
+ "query": symbol or "", "workspace": workspace, "budgetMs": 8000}, 15)
8159
+ except Exception as e: # noqa: BLE001
8160
+ return f"The language server did not answer ({e}). Use symbol_context or grep_repo instead."
8161
+ st = r.get("status")
8162
+ if st == "off":
8163
+ return (f"No language server is on for {r.get('name') or 'this language'} — use symbol_context or grep_repo. "
8164
+ "(The user can turn one on with /lsp.)")
8165
+ if st == "unsupported":
8166
+ return "No language server knows this file type — use symbol_context or grep_repo."
8167
+ if st in ("starting", "timeout"):
8168
+ return f"The language server is still {'starting' if st == 'starting' else 'busy'} — try again in a moment, or use symbol_context."
8169
+ if st != "ok":
8170
+ return f"The language server could not answer ({r.get('why') or st}). Use symbol_context or grep_repo."
8171
+ if op == "type":
8172
+ t = str(r.get("type") or "").strip()
8173
+ return t or f"The language server has no type information for '{symbol}' on line {line}."
8174
+
8175
+ def rel(f):
8176
+ try:
8177
+ return os.path.relpath(f, workspace) if workspace and not os.path.relpath(f, workspace).startswith("..") else f
8178
+ except ValueError:
8179
+ return f
8180
+ res = r.get("results") or []
8181
+ if not res:
8182
+ return {"definition": f"No definition found for '{symbol}' (line {line}).",
8183
+ "references": f"No references found for '{symbol}'.",
8184
+ "symbol": f"No symbol matching '{symbol}' in this project."}[op]
8185
+ rows = []
8186
+ for x in res[:30]:
8187
+ label = f"{x.get('kind') + ' ' if x.get('kind') else ''}{x.get('name') + ' — ' if x.get('name') else ''}"
8188
+ rows.append(f"{rel(x.get('file') or '')}:{x.get('line')} {label}{x.get('text') or ''}".rstrip())
8189
+ more = f"\n(+{len(res) - 30} more)" if len(res) > 30 else ""
8190
+ head = {"definition": "Defined at", "references": f"{len(res)} reference(s)", "symbol": f"{len(res)} symbol(s)"}[op]
8191
+ return f"{head} ({r.get('server')}):\n" + "\n".join(rows) + more
8192
+
8193
+
8028
8194
  def _write_sanity_error(path: str, content: str):
8029
8195
  """Why this write should NOT be reported as a success, or None if it is fine.
8030
8196
 
@@ -8140,6 +8306,86 @@ def _ws_backup_root() -> str:
8140
8306
  return root
8141
8307
 
8142
8308
 
8309
+ # GH #557, seen live on Windows 11: told an edit failed with "file is locked", the agent listed
8310
+ # every node process and ran `Stop-Process -Id <all of them>` — gu itself, its worker and its API
8311
+ # died mid-turn, without the user being asked. A command that stops processes is checked first.
8312
+ _KILL_VERB_RE = re.compile(
8313
+ r"(?i)(?<![\w-])(stop-process|spps|taskkill(?:\.exe)?|kill|pkill|killall|tskill)(?![\w-])")
8314
+ _KILL_BY_NAME_RE = re.compile(
8315
+ r"(?i)(?:(?:stop-process|spps)\b[^|;&]*-(?:name|processname)\s+['\"]?|taskkill\b[^|;&]*/im\s+['\"]?|"
8316
+ r"(?:pkill|killall)\s+(?:-\S+\s+)*['\"]?|get-process\s+(?:-name\s+)?['\"]?)"
8317
+ r"(node|python|python3|py|pythonw|gu|gu-cli|gu-repl)(?:\.exe)?\b")
8318
+ _GU_OWN_CMD_RE = re.compile(
8319
+ r"(?i)(gu-repl\.mjs|gu-cli\.mjs|gonext_agent_chat\.py|gu-local-worker|[\\/]\.gonext[\\/]api[\\/])")
8320
+
8321
+
8322
+ def _gu_kill_refusal(command: str, own: dict) -> str:
8323
+ """'' when the command stops no gu process, else why it must not run. Pure: `own` maps pid →
8324
+ what it is (gu's API, the worker, this turn…), from _gu_own_processes()."""
8325
+ if not command or not _KILL_VERB_RE.search(command):
8326
+ return ""
8327
+ m = _KILL_BY_NAME_RE.search(command)
8328
+ if m:
8329
+ return (f"it stops EVERY {m.group(1)} process by name, and gu itself runs as {m.group(1)} — "
8330
+ "the turn, gu's worker and its API would stop with it")
8331
+ if re.search(r"(?i)get-process\b[^;]*\|\s*(stop-process|spps)\b", command):
8332
+ return "it pipes a list of processes into Stop-Process, which can include gu's own"
8333
+ hit = [f"{pid} ({what})" for pid, what in own.items()
8334
+ if re.search(rf"(?<![\d]){int(pid)}(?![\d])", command)]
8335
+ if hit:
8336
+ return "it would stop gu itself: " + ", ".join(hit)
8337
+ return ""
8338
+
8339
+
8340
+ def _gu_own_processes() -> dict:
8341
+ """pid → what it is, for every process that is gu: this turn and its parent, the pid files
8342
+ in ~/.gonext, and any process whose command line is gu's (the REPL, the worker, the API)."""
8343
+ import subprocess
8344
+ own = {os.getpid(): "this turn", os.getppid(): "the gu worker running this turn"}
8345
+ gdir = os.path.join(os.path.expanduser("~"), ".gonext")
8346
+ for name, what in (("local-api.pid", "gu's local API"), ("worker.pid", "the gu worker")):
8347
+ try:
8348
+ with open(os.path.join(gdir, name), encoding="utf-8") as fh:
8349
+ own.setdefault(int(fh.read().strip().split()[0]), what)
8350
+ except (OSError, ValueError, IndexError):
8351
+ pass
8352
+ try:
8353
+ if _IS_WINDOWS:
8354
+ out = subprocess.run(
8355
+ ["powershell.exe", "-NoProfile", "-NonInteractive", "-Command",
8356
+ "Get-CimInstance Win32_Process | ForEach-Object { \"$($_.ProcessId) $($_.CommandLine)\" }"],
8357
+ capture_output=True, text=True, timeout=15).stdout
8358
+ else:
8359
+ out = subprocess.run(["ps", "-axo", "pid=,command="], capture_output=True, text=True, timeout=10).stdout
8360
+ for line in out.splitlines():
8361
+ pid, _, cmd = line.strip().partition(" ")
8362
+ if pid.isdigit() and _GU_OWN_CMD_RE.search(cmd):
8363
+ own.setdefault(int(pid), "gu")
8364
+ except Exception: # noqa: BLE001
8365
+ pass
8366
+ return own
8367
+
8368
+
8369
+ def _ws_backup_dest(root: str, path: str, sep: str = None) -> str:
8370
+ """Where a file's backup goes: its absolute path, re-rooted under the run's backup folder. Pure.
8371
+
8372
+ GH #557, seen live on Windows 11: `path.lstrip(os.sep)` leaves `C:\\Users\\…` absolute, so
8373
+ os.path.join threw the backup folder away and gu copied each file ONTO ITSELF — WinError 32,
8374
+ and every edit on Windows failed. The drive (`C:` → `C`, a share `\\\\srv\\share` → `srv_share`)
8375
+ becomes the first folder instead.
8376
+ """
8377
+ import ntpath
8378
+ import posixpath
8379
+ sep = sep or os.sep
8380
+ mod = ntpath if sep == "\\" else posixpath
8381
+ drive, rest = mod.splitdrive(path)
8382
+ rest = rest.lstrip("\\/")
8383
+ if drive:
8384
+ drive = drive.replace(":", "").strip("\\/").replace("\\", "_").replace("/", "_") or "drive"
8385
+ return mod.normpath(mod.join(root, drive, rest))
8386
+ return mod.normpath(mod.join(root, rest))
8387
+
8388
+
8143
8389
  def _ws_snapshot(path: str) -> str:
8144
8390
  """Copy the file to the run's backup dir before its FIRST edit in this run, so
8145
8391
  every change is revertible. Returns the backup path ('' if new file)."""
@@ -8151,7 +8397,7 @@ def _ws_snapshot(path: str) -> str:
8151
8397
  if c["path"] == path and c.get("backup"):
8152
8398
  return c["backup"]
8153
8399
  root = _ws_backup_root()
8154
- dest = os.path.join(root, path.lstrip(os.sep))
8400
+ dest = _ws_backup_dest(root, path)
8155
8401
  os.makedirs(os.path.dirname(dest), exist_ok=True)
8156
8402
  shutil.copy2(path, dest)
8157
8403
  return dest
@@ -10145,6 +10391,9 @@ def _ws_request_approval(api_base, worker_key, job_id, command, reason, deadline
10145
10391
  _emit({"type": "step", "text": "Awaiting your choice: set up S3, or save on this computer?"})
10146
10392
  elif command.startswith("__BROWSER__::"):
10147
10393
  _emit({"type": "step", "text": "Awaiting your approval: use a web browser"})
10394
+ elif command.startswith("__LSP__::"):
10395
+ _emit({"type": "step", "text": "Awaiting your choice: turn on "
10396
+ + (command[len("__LSP__::"):].split("\t") + ["", ""])[1] + " code intelligence"})
10148
10397
  elif command.startswith("__MCPTOOL__::"):
10149
10398
  _srv, _, _rest = command[len("__MCPTOOL__::"):].partition("\t")
10150
10399
  _emit({"type": "step", "text": f"Awaiting your approval: MCP tool {_srv}/{_rest.split(chr(9))[0]}"})
@@ -10233,10 +10482,21 @@ _INFLIGHT_CMDS: set = set()
10233
10482
  _STOP = {"writing": 0, "requested": False}
10234
10483
 
10235
10484
 
10485
+ # Run when the turn is stopped (worker SIGTERM / stop file): each must be quick — the worker kills
10486
+ # for good ~3 s later. GH #551: closes gu's Chrome tabs, which a stopped turn used to leave open
10487
+ # (with the popup stuck on "Stopping…" and Chrome's debugging banner up).
10488
+ _ON_STOP = []
10489
+
10490
+
10236
10491
  def _stop_now():
10237
10492
  for pid in list(_INFLIGHT_CMDS):
10238
10493
  _ws_kill_tree(pid, force=True)
10239
10494
  _INFLIGHT_CMDS.clear()
10495
+ for _fn in list(_ON_STOP):
10496
+ try:
10497
+ _fn()
10498
+ except Exception: # noqa: BLE001
10499
+ pass
10240
10500
  try:
10241
10501
  _log("stopped by the worker — killed the command in flight")
10242
10502
  except Exception: # noqa: BLE001
@@ -11343,17 +11603,63 @@ def _png_b64_len(im) -> int:
11343
11603
  return (len(buf.getvalue()) + 2) // 3 * 4
11344
11604
 
11345
11605
 
11346
- def _prepare_image(path):
11347
- """Open `path` and return a PIL image Claude will accept, or raise ValueError(reason)."""
11606
+ def _parse_crop(crop):
11607
+ """"left,top,right,bottom" as fractions 0–1 (or percents 0–100) of the upright image → a tuple
11608
+ of fractions, None for no crop. Raises ValueError with what is wrong. Pure."""
11609
+ s = str(crop or "").strip()
11610
+ if not s:
11611
+ return None
11612
+ try:
11613
+ v = [float(x) for x in re.split(r"[,\s]+", s) if x != ""]
11614
+ except ValueError:
11615
+ raise ValueError(f"crop {crop!r}: four numbers, left,top,right,bottom (fractions 0-1)") from None
11616
+ if len(v) != 4:
11617
+ raise ValueError(f"crop {crop!r}: four numbers, left,top,right,bottom (fractions 0-1)")
11618
+ if max(v) > 1.0:
11619
+ v = [x / 100.0 for x in v] # percents
11620
+ l, t, r, b = [min(1.0, max(0.0, x)) for x in v]
11621
+ if r - l < 0.02 or b - t < 0.02:
11622
+ raise ValueError(f"crop {crop!r}: right must be more than left, bottom more than top")
11623
+ return (l, t, r, b)
11624
+
11625
+
11626
+ def _prepare_image(path, rotate=0, crop=None, info=None):
11627
+ """Open `path` and return a PIL image Claude will accept, or raise ValueError(reason).
11628
+
11629
+ GH #559 — what Claude Code did with sips on the owner's phone photo: turn it upright, then cut
11630
+ out the table so its small text survives. `rotate` = degrees CLOCKWISE (90/180/270), after the
11631
+ photo's own EXIF turn; `crop` = (left, top, right, bottom) fractions of that upright picture
11632
+ (see _parse_crop). Both act on the FULL-resolution picture, before the shrink to 1568 px — a
11633
+ crop is a zoom. `info` (a dict) gets the full size and the region sent."""
11348
11634
  from PIL import Image
11349
11635
  try:
11350
11636
  with Image.open(path) as src:
11351
11637
  src.load() # a truncated or non-image file fails here, not later in the request
11352
11638
  im = src.copy()
11639
+ try:
11640
+ # A phone photo is stored sideways with an EXIF "rotate me" tag; the copy drops
11641
+ # the tag, so the model would read the text on its side (GH #559).
11642
+ from PIL import ImageOps
11643
+ im = ImageOps.exif_transpose(src) or im
11644
+ except Exception: # noqa: BLE001
11645
+ pass
11353
11646
  except Image.DecompressionBombError:
11354
11647
  raise ValueError("too many pixels to open safely") from None
11355
11648
  except Exception as e: # noqa: BLE001
11356
11649
  raise ValueError(f"not a readable image ({type(e).__name__})") from None
11650
+ rot = int(rotate or 0) % 360
11651
+ if rot not in (0, 90, 180, 270):
11652
+ raise ValueError(f"rotate {rotate!r}: use 90, 180 or 270 (degrees clockwise)")
11653
+ if rot:
11654
+ im = im.rotate(-rot, expand=True)
11655
+ full = im.size
11656
+ if crop:
11657
+ l, t, r, b = crop
11658
+ box = (int(l * im.width), int(t * im.height), max(int(l * im.width) + 1, int(r * im.width)),
11659
+ max(int(t * im.height) + 1, int(b * im.height)))
11660
+ im = im.crop(box)
11661
+ if info is not None:
11662
+ info.update(full=full, region=im.size)
11357
11663
  # Colour modes PNG cannot hold, or holds oddly: CMYK photos, 16-bit, float, palette.
11358
11664
  if im.mode == "P":
11359
11665
  im = im.convert("RGBA" if "transparency" in im.info else "RGB")
@@ -11431,6 +11737,92 @@ def _load_turn_images(refs):
11431
11737
  return out, failed
11432
11738
 
11433
11739
 
11740
+ # AN IMAGE FILE IN THE PROJECT (GH #559). Claude Code's Read gives the model the picture itself.
11741
+ # gu had no way to: asked about a photo in the folder, the agent opened it in the browser, read it
11742
+ # as text (EXIF only), then brew-installed tesseract and tesseract-lang — minutes, and the model
11743
+ # never saw it. view_image gives the picture to a model that can see it: the coder itself when it
11744
+ # takes images, else the talking (agent) model reads it once and returns what it shows.
11745
+ _IMAGE_READ_TIMEOUT_S = 90
11746
+ _MAX_STEP_IMAGES = 4 # pictures attached to one step (view_image + screenshots)
11747
+ _IMAGE_FILE_EXTS = (".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tif", ".tiff")
11748
+
11749
+
11750
+ def _is_image_path(path) -> bool:
11751
+ return os.path.splitext(str(path or ""))[1].lower() in _IMAGE_FILE_EXTS
11752
+
11753
+
11754
+ def _image_not_text_msg(path) -> str:
11755
+ """What a text reader says when it is handed a picture, instead of its bytes as text."""
11756
+ return (f"{path} is an image file, not text. Call view_image(path={str(path)!r}) to see it "
11757
+ "(add question=... for what to look for). Do not open it in the browser and do not "
11758
+ "install OCR software.")
11759
+
11760
+
11761
+ _IMAGE_READ_PROMPT = (
11762
+ "Read this image for another assistant who cannot see it. First write out ALL the text in it, "
11763
+ "exactly as written — keep the original language, accents, spelling, numbers, account numbers, "
11764
+ "amounts and dates; keep rows and columns together (a table as lines of `cell | cell`). Then, "
11765
+ "in a few lines, say what the image is and how it is laid out. Mark anything you cannot read "
11766
+ "as [unreadable] rather than guessing.")
11767
+
11768
+
11769
+ def _image_data_url(im) -> str:
11770
+ """A PIL image → a data: URL (JPEG for photos — a fraction of PNG's bytes; PNG with alpha)."""
11771
+ import base64
11772
+ import io
11773
+ buf = io.BytesIO()
11774
+ if im.mode in ("RGBA", "LA"):
11775
+ im.save(buf, format="PNG")
11776
+ kind = "png"
11777
+ else:
11778
+ im.convert("RGB").save(buf, format="JPEG", quality=90)
11779
+ kind = "jpeg"
11780
+ return f"data:image/{kind};base64," + base64.b64encode(buf.getvalue()).decode("ascii")
11781
+
11782
+
11783
+ def _read_image_with_model(im, base_url, api_key, model_id, question="", client_factory=None) -> str:
11784
+ """Ask a model that can see images to read `im` → its text. Raises on failure or an empty reply."""
11785
+ prompt = _IMAGE_READ_PROMPT + (f"\n\nAlso answer, from the image only: {question.strip()}" if (question or "").strip() else "")
11786
+ if client_factory is None:
11787
+ from openai import OpenAI
11788
+
11789
+ def client_factory():
11790
+ # 90 s, no retry: the coder waits on this with nothing new on screen. Up to 6 minutes
11791
+ # (180 s x 2) looked like a hang (GH #559 review).
11792
+ return OpenAI(base_url=base_url, api_key=api_key or "local",
11793
+ http_client=_proxy_http_client(base_url), max_retries=0,
11794
+ timeout=_IMAGE_READ_TIMEOUT_S)
11795
+ # Through _create_with_repair: counted in the turn's other-calls tokens (and so charged to a free
11796
+ # model's allowance, GH #501) — a direct create() was missed (GH #559 review) — and a request
11797
+ # shape the host refuses is fixed and retried like every other call.
11798
+ resp = _create_with_repair(
11799
+ client_factory(),
11800
+ model=model_id,
11801
+ messages=[{"role": "user", "content": [
11802
+ {"type": "text", "text": prompt},
11803
+ {"type": "image_url", "image_url": {"url": _image_data_url(im)}},
11804
+ ]}],
11805
+ temperature=0,
11806
+ max_tokens=3000,
11807
+ )
11808
+ text = ((resp.choices[0].message.content if resp and resp.choices else "") or "").strip()
11809
+ text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL | re.IGNORECASE).strip()
11810
+ if not text:
11811
+ raise RuntimeError(f"{model_id} returned no text for the image")
11812
+ return text
11813
+
11814
+
11815
+ def _image_route(coder, agent, takes=None) -> str:
11816
+ """Who sees a project image: "coder" (attached to the step), "agent" (it reads it and the coder
11817
+ gets the text), or "" (no model here can). coder/agent = (base_url, model_id). Pure but for `takes`."""
11818
+ takes = takes or (lambda b, m: _is_anthropic_url(b) or _coder_takes_images(b, m))
11819
+ if coder[0] and coder[1] and takes(*coder):
11820
+ return "coder"
11821
+ if agent[0] and agent[1] and tuple(agent) != tuple(coder) and takes(*agent):
11822
+ return "agent"
11823
+ return ""
11824
+
11825
+
11434
11826
  def _label_failed_images(text, failed):
11435
11827
  """Say which images did not make it, where the model reads their labels — a bare
11436
11828
  "[Image #1]" with nothing attached invites the model to guess what it shows."""
@@ -11500,7 +11892,30 @@ def run_agent_chat(cfg):
11500
11892
  # REPL) can show a Yes/No picker. When both are present, run_command PAUSES on a
11501
11893
  # risky command and asks the user via the API instead of hard-blocking it.
11502
11894
  _job_id = (cfg.get("jobId") or "").strip()
11895
+
11896
+ def _send_now_requested() -> bool:
11897
+ """GH #560: Ctrl+X Ctrl+S in gu — a waited-on command gives way to the user's message."""
11898
+ if not _job_id:
11899
+ return False
11900
+ try:
11901
+ import gu_turn_notes as _tn
11902
+ return _tn.send_now_requested(_job_id)
11903
+ except Exception: # noqa: BLE001
11904
+ return False
11503
11905
  _interactive_approval = bool(cfg.get("interactiveApproval"))
11906
+ # GH #540: the worker's language-server host — {url, token, exts}, or None (web, remote, older
11907
+ # worker). After every write the agent asks it for the file's errors; see _lsp_after_write.
11908
+ _lsp_cfg = cfg.get("lsp") if isinstance(cfg.get("lsp"), dict) and cfg["lsp"].get("url") else None
11909
+ _lsp_turn = {"warm": set(), "said": set()}
11910
+
11911
+ def _lsp_after_write(rp: str, content: str, changed=None) -> str:
11912
+ """The file's errors from its language server, for a write tool's result (GH #540)."""
11913
+ def _ask(command: str) -> bool:
11914
+ if not (_interactive_approval and _job_id and worker_api_base and worker_api_key):
11915
+ return False
11916
+ return _ws_request_approval(worker_api_base, worker_api_key, _job_id, command, "", deadline_s=45)
11917
+ return _lsp_code_check(_lsp_cfg, _lsp_turn, rp, content, changed,
11918
+ _WS_ACTIVE or _default_ws_root(), ask=_ask, emit=_emit, log=_log)
11504
11919
  # Skills and MCP servers (task #269). The worker scans ~/.gonext/skills, ~/.gonext/mcp.json and
11505
11920
  # this folder's .gonext/skills + .mcp.json for every turn; none present = neither appears
11506
11921
  # anywhere in the prompt. Names only here — a skill's body is read when it is used.
@@ -12867,6 +13282,12 @@ def run_agent_chat(cfg):
12867
13282
  # drops the whole entry: after an edit the line numbers mean something else, and a stale
12868
13283
  # range would refuse a read the model genuinely needs.
12869
13284
  _read_ranges: dict = {}
13285
+ # GH #552 (seen live): a read whose text never reached the model — several read_file_lines
13286
+ # calls in one code block without print(), where only the last value is shown — was still
13287
+ # recorded as "already shown", so every retry was refused and the model read the file with cat.
13288
+ # A range is recorded here first and counts as shown only when step_callback finds its text in
13289
+ # the step's observation.
13290
+ _pending_ranges: list = []
12870
13291
 
12871
13292
  def _server_log_tail_for_url(url: str) -> str:
12872
13293
  """If `url` is a localhost server we started via run_command, return the tail of
@@ -12923,12 +13344,12 @@ def run_agent_chat(cfg):
12923
13344
  """
12924
13345
  prev = _read_ranges.get(rp)
12925
13346
  if not prev or prev[0] != mt:
12926
- _read_ranges[rp] = (mt, [(s, e)])
13347
+ _pending_ranges.append((rp, mt, s, e))
12927
13348
  return ""
12928
13349
  served = prev[1]
12929
13350
  hit = _range_is_covered(served, s, e)
12930
13351
  if hit is None:
12931
- served.append((s, e))
13352
+ _pending_ranges.append((rp, mt, s, e))
12932
13353
  return ""
12933
13354
  import os as _os3
12934
13355
  name = _os3.path.basename(rp)
@@ -12938,6 +13359,23 @@ def run_agent_chat(cfg):
12938
13359
  f"on it instead of re-reading. If you need something you have NOT seen, read a "
12939
13360
  f"different range (the file has {total} lines) or narrow it down with grep_repo.")
12940
13361
 
13362
+ def _settle_pending_reads(observation) -> list:
13363
+ """After a step: each range read in it counts as shown only if its header line is in what
13364
+ the model was actually given. → the reads that were lost (not printed), for a note."""
13365
+ lost = []
13366
+ obs = observation if isinstance(observation, str) else ""
13367
+ for rp, mt, s, e in _pending_ranges:
13368
+ if f"(lines {s}-{e} of " in obs and rp in obs:
13369
+ prev = _read_ranges.get(rp)
13370
+ if not prev or prev[0] != mt:
13371
+ _read_ranges[rp] = (mt, [(s, e)])
13372
+ elif _range_is_covered(prev[1], s, e) is None:
13373
+ prev[1].append((s, e))
13374
+ else:
13375
+ lost.append((rp, s, e))
13376
+ _pending_ranges.clear()
13377
+ return lost
13378
+
12941
13379
  def _dedup(tool_name: str, arg: str, next_hint: str):
12942
13380
  """Return (is_repeat, message). On a repeat, message steers the model forward."""
12943
13381
  key = _norm_query(arg) if tool_name == "web_search" else (arg or "").strip().lower()
@@ -13501,7 +13939,7 @@ def run_agent_chat(cfg):
13501
13939
  if not _CLOUD_LIMITS["loaded"]:
13502
13940
  _fetch_cloud_limits(worker_api_base)
13503
13941
  _ctx_window = _model_context_window(coding_base_url, coding_model_id, coding_api_key)
13504
- _compact_at = _compact_threshold(_ctx_window)
13942
+ _compact_at = _compact_threshold(_ctx_window, _autocompact_cap(coding_model_id))
13505
13943
  _caps = _set_obs_caps(_ctx_window)
13506
13944
  _log(f"read caps: {_caps['read']} chars / {_caps['lines']} lines per read, {_caps['search']} chars "
13507
13945
  f"per search — for a {_ctx_window or 'unknown'}-token window (issues #49, #105)")
@@ -13658,7 +14096,9 @@ def run_agent_chat(cfg):
13658
14096
  saved += _trim_tool_call_args(_st, 120)
13659
14097
  return saved
13660
14098
 
13661
- _browser_shot = {"img": None} # the browser tool's newest screenshot, for this step (#363)
14099
+ # The pictures this step's tools took — browser screenshots (#363) and view_image (GH #559). A
14100
+ # LIST: one slot kept only the last, while every earlier call still said "attached" (GH #559 review).
14101
+ _browser_shot = {"imgs": []}
13662
14102
 
13663
14103
  def step_callback(step_log):
13664
14104
  step_num = getattr(step_log, "step_number", "?")
@@ -13667,9 +14107,9 @@ def run_agent_chat(cfg):
13667
14107
  # observation (#363). Only the newest two stay in memory: every image is re-sent on every
13668
14108
  # later step, and an old view of a page that has since changed only misleads.
13669
14109
  try:
13670
- if _browser_shot.get("img") is not None:
13671
- step_log.observations_images = [_browser_shot["img"]]
13672
- _browser_shot["img"] = None
14110
+ if _browser_shot.get("imgs"):
14111
+ step_log.observations_images = list(_browser_shot["imgs"])
14112
+ _browser_shot["imgs"] = []
13673
14113
  _with = [s for s in (getattr(getattr(_agent_ref.get("a"), "memory", None), "steps", None) or [])
13674
14114
  if getattr(s, "observations_images", None) and s is not step_log]
13675
14115
  for _old in _with[:-1]:
@@ -13677,6 +14117,21 @@ def run_agent_chat(cfg):
13677
14117
  except Exception as e: # noqa: BLE001
13678
14118
  _log(f"browser screenshot attach skip: {e}")
13679
14119
 
14120
+ # GH #552: reads whose text the model never saw are not "already shown" — and the model is
14121
+ # told why it saw nothing, so it prints them instead of falling back to cat.
14122
+ try:
14123
+ _lost = _settle_pending_reads(getattr(step_log, "observations", None))
14124
+ if _lost and isinstance(getattr(step_log, "observations", None), str):
14125
+ import os as _osl
14126
+ _names = ", ".join(f"{_osl.path.basename(rp)}:{s}-{e}" for rp, s, e in _lost[:5])
14127
+ step_log.observations += (
14128
+ f"\n\n(Note: read_file_lines returned text for {_names}, but your code did not print it, "
14129
+ "so it is not shown above. A tool's result is shown only when printed — "
14130
+ "use print(read_file_lines(...)) for each read.)")
14131
+ _log(f"step {step_num}: {len(_lost)} read(s) not printed — told the model")
14132
+ except Exception as e: # noqa: BLE001
14133
+ _log(f"pending read settle skip: {e}")
14134
+
13680
14135
  # A background shell that finished during this step is told to the model now (#362).
13681
14136
  try:
13682
14137
  _obs_now = getattr(step_log, "observations", None)
@@ -15561,6 +16016,11 @@ def run_agent_chat(cfg):
15561
16016
  _emit_read("Reading file", path, "failed: no such file")
15562
16017
  _last_obs["text"] = msg
15563
16018
  return msg
16019
+ if _is_image_path(rp):
16020
+ msg = _image_not_text_msg(path) # GH #559: a picture, not its bytes as text
16021
+ _emit_read("Reading file", path, "an image — use view_image")
16022
+ _last_obs["text"] = msg
16023
+ return msg
15564
16024
  if os.path.getsize(rp) > 5 * 1024 * 1024:
15565
16025
  msg = "Error: file too large to read (> 5 MB)."
15566
16026
  _emit_read("Reading file", path, "failed: larger than 5 MB")
@@ -15584,6 +16044,106 @@ def run_agent_chat(cfg):
15584
16044
  _last_obs["text"] = msg
15585
16045
  return msg
15586
16046
 
16047
+ @tool
16048
+ def say(text: str) -> str:
16049
+ """Tell the user one short line NOW, while you keep working — e.g. to answer a note they typed during the turn ("Noted: I'll add the test after this fix."). Does not end the turn; it is not the final answer.
16050
+
16051
+ Args:
16052
+ text: one short line, at most about 200 characters.
16053
+ """
16054
+ # GH #562: printed by gu as normal text under the user's message, between the steps.
16055
+ line = " ".join(str(text or "").split())[:300]
16056
+ if not line:
16057
+ return "Nothing said: the text was empty."
16058
+ _emit({"type": "step", "text": f"__SAY__::{line}"})
16059
+ _log("said one line to the user")
16060
+ return "Said. Go on with the task."
16061
+
16062
+ @tool
16063
+ def view_image(path: str, question: str = "", rotate: int = 0, crop: str = "") -> str:
16064
+ """Look at an image file (png, jpg, jpeg, gif, webp, bmp, tiff) — a photo, screenshot or scan in the project. Use this for ANY picture: never open a local image in the browser, never read it as text, never install OCR or image software. If the picture is sideways, call again with rotate. If text is small or blurry, call again with crop to zoom into that part (a crop keeps the full resolution).
16065
+
16066
+ Args:
16067
+ path: the image file's path.
16068
+ question: optional — what to look for or read in it (e.g. "the bank account numbers").
16069
+ rotate: optional — turn it clockwise by 90, 180 or 270 degrees first (for a sideways photo).
16070
+ crop: optional — "left,top,right,bottom" as fractions 0-1 of the upright picture, e.g. "0.5,0,1,0.4" = the top-right part.
16071
+ """
16072
+ try:
16073
+ import os
16074
+ rp = _rag_read_allowed((path or "").strip())
16075
+ if not os.path.isfile(rp):
16076
+ msg = f"Error: not a file: {path}"
16077
+ _emit_read("Viewing image", path, "failed: no such file")
16078
+ _last_obs["text"] = msg
16079
+ return msg
16080
+ if not _is_image_path(rp):
16081
+ msg = f"Error: {path} is not an image file ({', '.join(_IMAGE_FILE_EXTS)}). Read it with read_text_file."
16082
+ _emit_read("Viewing image", path, "failed: not an image")
16083
+ _last_obs["text"] = msg
16084
+ return msg
16085
+ route = _image_route((coding_base_url, coding_model_id), (agent_base_url, agent_model_id))
16086
+ if not route:
16087
+ msg = (f"No model set up here can see images (coder {coding_model_id or '?'}, agent "
16088
+ f"{agent_model_id or '?'}), so the picture cannot be read. Tell the user that in one "
16089
+ "line and that /model can switch to a model that sees images (Claude, Kimi K3, "
16090
+ "Qwen 3.6 Plus and others). Do NOT install OCR software or open the image in the browser.")
16091
+ _emit_read("Viewing image", path, "no model here can see images")
16092
+ _last_obs["text"] = msg
16093
+ return msg
16094
+ _info = {}
16095
+ try:
16096
+ im = _prepare_image(rp, rotate=rotate, crop=_parse_crop(crop), info=_info)
16097
+ except ValueError as e:
16098
+ msg = f"Error: {path} could not be opened as an image: {e}"
16099
+ _emit_read("Viewing image", path, f"failed: {e}")
16100
+ _last_obs["text"] = msg
16101
+ return msg
16102
+ _fw, _fh = _info.get("full") or im.size
16103
+ _what = (f"{rp} (full picture {_fw}x{_fh}"
16104
+ + (f", turned {int(rotate) % 360}° clockwise" if int(rotate or 0) % 360 else "")
16105
+ + (f", region {crop} = {_info['region'][0]}x{_info['region'][1]} px" if (crop or "").strip() else "")
16106
+ + f", sent at {im.width}x{im.height})")
16107
+ _how = ("" if (crop or "").strip() else
16108
+ " If it is sideways, call view_image again with rotate; if text is too small, zoom in with crop.")
16109
+ _detail = f"{im.width}x{im.height}" + (f" · rotate {int(rotate) % 360}" if int(rotate or 0) % 360 else "") \
16110
+ + (f" · crop {crop}" if (crop or "").strip() else "")
16111
+ if route == "coder":
16112
+ if len(_browser_shot["imgs"]) >= _MAX_STEP_IMAGES:
16113
+ msg = (f"Not attached: {_MAX_STEP_IMAGES} pictures are already attached to this step. "
16114
+ "Look at those first, then call view_image again in a later step.")
16115
+ _emit_read("Viewing image", path, "not attached — too many in one step")
16116
+ _last_obs["text"] = msg
16117
+ return msg
16118
+ _browser_shot["imgs"].append(im) # attached to this step, like a browser screenshot
16119
+ msg = f"{_what} — the image is attached to this observation. Look at it and read what it shows.{_how}"
16120
+ _emit_read("Viewing image", path, _detail)
16121
+ _last_obs["text"] = msg
16122
+ return msg
16123
+ _emit_running("Viewing image", f"{path} — {agent_model_id} reads it")
16124
+ try:
16125
+ text = _read_image_with_model(im, agent_base_url, agent_api_key, agent_model_id, question)
16126
+ except Exception as e: # noqa: BLE001
16127
+ _slow = "timeout" in type(e).__name__.lower() or "timed out" in str(e).lower()
16128
+ msg = (f"Error: {agent_model_id} could not read the image"
16129
+ + (f" (no answer within {_IMAGE_READ_TIMEOUT_S} s)" if _slow else f" ({type(e).__name__}: {_clip(str(e), 200)})")
16130
+ + ". Tell the user in one line; do NOT install OCR software or open the image in the browser.")
16131
+ _emit_read("Viewing image", path, "no answer in time" if _slow else f"failed: {type(e).__name__}")
16132
+ _last_obs["text"] = msg
16133
+ return msg
16134
+ msg = (f"{_what}, read by {agent_model_id} (the coding model "
16135
+ f"{coding_model_id} cannot see images):\n{text}\n(To read a part more closely, call "
16136
+ "view_image again with crop; if the reader says it is sideways, with rotate.)")
16137
+ _emit_read("Viewing image", path, f"{_detail} · read by {agent_model_id}")
16138
+ msg = _ws_cap_obs(msg, cap=_OBS_CAPS["read"])
16139
+ _last_obs["text"] = msg
16140
+ return msg
16141
+ except Exception as e: # noqa: BLE001
16142
+ msg = f"Error: view_image failed: {type(e).__name__}: {e}"
16143
+ _emit_read("Viewing image", path, f"failed: {type(e).__name__}")
16144
+ _last_obs["text"] = msg
16145
+ return msg
16146
+
15587
16147
  def _rag_unavailable_msg() -> str:
15588
16148
  """Why RAG can't run, naming the ACTUAL missing piece (task #133).
15589
16149
 
@@ -16266,6 +16826,25 @@ def run_agent_chat(cfg):
16266
16826
  _last_obs["text"] = msg
16267
16827
  return msg
16268
16828
 
16829
+ @tool
16830
+ def lsp(operation: str, path: str, line: int = 0, symbol: str = "") -> str:
16831
+ """Ask the LANGUAGE SERVER (the language's own compiler — exact, unlike text search) about a symbol. Read-only. operation: "definition" (where the symbol on that line is defined), "references" (every place it is used), "type" (its type and signature), "symbol" (find a function/class/type by name in the project; line not needed). Prefer it over grep_repo for definitions and references in languages it supports; if it says no server is on, use symbol_context or grep_repo.
16832
+
16833
+ Args:
16834
+ operation: definition, references, type, or symbol.
16835
+ path: a file in the workspace — where the symbol appears (for "symbol": any file of that language in the project).
16836
+ line: 1-based line where the symbol appears (not needed for "symbol").
16837
+ symbol: the symbol's name, e.g. "Greeter" (for "symbol": the name or part of it to search for).
16838
+ """
16839
+ try:
16840
+ rp = _rag_read_allowed((path or "").strip())
16841
+ except Exception as ex: # noqa: BLE001
16842
+ return f"Error: {ex}"
16843
+ _emit_running("Asking language server", _fmt_call("lsp", operation=operation, path=path, symbol=symbol))
16844
+ out = _lsp_query_text(_lsp_cfg, operation, rp, line, symbol, _WS_ACTIVE or _default_ws_root())
16845
+ _last_obs["text"] = out
16846
+ return out
16847
+
16269
16848
  @tool
16270
16849
  def symbol_context(name: str, path: str = "") -> str:
16271
16850
  """Where a function/class/type is DEFINED, who CALLS it, and which TESTS cover it — in ONE step. Use this instead of grep_repo + read_file_lines whenever you are looking for a named thing.
@@ -16369,6 +16948,11 @@ def run_agent_chat(cfg):
16369
16948
  start_line=int(start_line or 1),
16370
16949
  end_line=int(end_line or 0)))
16371
16950
  rp = _rag_read_allowed((path or "").strip())
16951
+ if _is_image_path(rp):
16952
+ msg = _image_not_text_msg(path) # GH #559
16953
+ _emit_read("Reading lines", path, "an image — use view_image")
16954
+ _last_obs["text"] = msg
16955
+ return msg
16372
16956
  with _open_project_text(rp) as fh:
16373
16957
  lines = fh.readlines()
16374
16958
  s = max(1, int(start_line or 1))
@@ -16447,6 +17031,7 @@ def run_agent_chat(cfg):
16447
17031
  range(max(1, s - 2), min(len(lines), s + len(new_lines) + 1) + 1))
16448
17032
  out = (f"Replaced lines {s}-{e} of {rp} with {len(new_lines)} line(s). "
16449
17033
  f"Backup saved. Updated region:\n{shown}")
17034
+ out += _lsp_after_write(rp, "".join(lines), [s, s + max(0, len(new_lines) - 1)])
16450
17035
  _last_obs["text"] = out
16451
17036
  return out
16452
17037
  except Exception as ex: # noqa: BLE001
@@ -16494,6 +17079,8 @@ def run_agent_chat(cfg):
16494
17079
  added=[(start_no + i, t) for i, t in enumerate(new_ls)],
16495
17080
  )})
16496
17081
  out = f"Replaced 1 occurrence in {rp}. Backup saved."
17082
+ out += _lsp_after_write(rp, text.replace(old_string, new_string, 1),
17083
+ [start_no, start_no + max(0, len(new_ls) - 1)])
16497
17084
  _last_obs["text"] = out
16498
17085
  return out
16499
17086
  except Exception as ex: # noqa: BLE001
@@ -16558,6 +17145,7 @@ def run_agent_chat(cfg):
16558
17145
  )})
16559
17146
  _seen.add(_ch) # remember this content so a later revert-to-it is caught
16560
17147
  out = f"{'Overwrote' if existed else 'Created'} {rp} ({len(content)} chars)."
17148
+ out += _lsp_after_write(rp, content, None)
16561
17149
  _last_obs["text"] = out
16562
17150
  return out
16563
17151
  except Exception as ex: # noqa: BLE001
@@ -16693,6 +17281,16 @@ def run_agent_chat(cfg):
16693
17281
  msg = "Error: empty command."
16694
17282
  _last_obs["text"] = msg
16695
17283
  return msg
17284
+ # GH #557: never stop gu itself (checked only when the line stops processes).
17285
+ _gk = _gu_kill_refusal(command, _gu_own_processes()) if _KILL_VERB_RE.search(command or "") else ""
17286
+ if _gk:
17287
+ msg = (f"Error: that command did NOT run — {_gk}. Stop only a process you started "
17288
+ "in this turn, by its own PID (find it by its port or its command line), "
17289
+ "and never gu's. If a file looks locked, read the tool's error again instead: "
17290
+ "gu does not hold your files open.")
17291
+ _log(f"run_command refused: would stop gu ({_gk})")
17292
+ _last_obs["text"] = msg
17293
+ return msg
16696
17294
  # AN `&&` CHAIN IS ONE STEP (task #274): each part runs through THIS function —
16697
17295
  # allowlist, risk gate, approval, server detection, all of it — in order, and
16698
17296
  # the first failure stops the rest. `cd DIR` sets the folder for what follows.
@@ -17134,6 +17732,15 @@ def run_agent_chat(cfg):
17134
17732
  msg = _to_background("started")
17135
17733
  _last_obs["text"] = msg
17136
17734
  return msg
17735
+ # GH #560: the user pressed Ctrl+X Ctrl+S ("send now") on a message typed during the
17736
+ # turn. Stop WAITING, not the command: it goes on as a background shell, exactly as
17737
+ # at the deadline below, and the step ends so the model reads the message now.
17738
+ if _send_now_requested():
17739
+ _emit({"type": "step", "text": "Your message → the agent reads it now"})
17740
+ msg = _to_background("moved to the background because the user sent a message "
17741
+ "(it follows this result) — read it before going on")
17742
+ _last_obs["text"] = msg
17743
+ return msg
17137
17744
  # THE DEADLINE HANDS OFF, IT NO LONGER KILLS (task #360): a 7-minute build
17138
17745
  # is the command doing its job, not a hang. The 1h turn budget and
17139
17746
  # stop_server still bound it.
@@ -17263,6 +17870,9 @@ def run_agent_chat(cfg):
17263
17870
  deadline = _t.time() + max(0, min(int(wait_seconds or 0), 540))
17264
17871
  st = _shell_state(sh)
17265
17872
  while st["state"] == "running" and _t.time() < deadline:
17873
+ if _send_now_requested(): # GH #560: stop waiting; the user's message is read next
17874
+ _emit({"type": "step", "text": "Your message → the agent reads it now"})
17875
+ break
17266
17876
  _t.sleep(2)
17267
17877
  st = _shell_state(sh)
17268
17878
  try:
@@ -17454,6 +18064,48 @@ def run_agent_chat(cfg):
17454
18064
  # (Allow once / Always in this folder / No), unless this folder is on the "always" list in
17455
18065
  # ~/.gonext/browser-allow.json. A "No" holds for the rest of the turn.
17456
18066
  _browser_consent = {"ok": False, "no": False, "where": ""}
18067
+ import gu_gif as _gu_gif
18068
+ _gif = _gu_gif.GifRecorder() # GH #548: browser(action="record_start" … "record_stop")
18069
+
18070
+ def _gif_frame(click=None):
18071
+ """One frame of the recording: a screenshot of gu's tab now. Never fails the step."""
18072
+ try:
18073
+ import gu_browser as _gbf
18074
+ okf, resf, _ncf = _gbf.command({"action": "screenshot"}, log=_log, own=_gbf.own_allowed())
18075
+ if okf and isinstance(resf, dict) and resf.get("image"):
18076
+ im, _note = _gbf.decode_screenshot(resf, max_edge=100000)
18077
+ _gif.add(im, click)
18078
+ except Exception as _fe: # noqa: BLE001
18079
+ _log(f"gif frame skipped: {type(_fe).__name__}: {_fe}")
18080
+
18081
+ def _browser_stopped():
18082
+ """GH #551: Stop in the gu extension = Ctrl+C. The agent cancels its own job (the
18083
+ same call the terminal makes); the worker then stops this process and the terminal
18084
+ says "(cancelled — the agent was stopped)". Without a job to cancel, the extension
18085
+ already refuses every further command with a message telling the model to stop."""
18086
+ _browser_consent["stopped"] = True
18087
+ _emit({"type": "step", "text": "⏹ Stopped from Chrome"})
18088
+ if not (_job_id and worker_api_base and worker_api_key):
18089
+ return
18090
+ _req = urllib.request.Request(
18091
+ f"{worker_api_base.rstrip('/')}/api/worker/jobs/cancel", method="POST",
18092
+ data=json.dumps({"jobId": _job_id}).encode(),
18093
+ headers={"Content-Type": "application/json", "X-Worker-Key": worker_api_key})
18094
+ try:
18095
+ with urllib.request.urlopen(_req, timeout=15, context=_ssl_context()) as _r:
18096
+ _log(f"browser: Stop from Chrome → job {_job_id} cancel answered {_r.status}")
18097
+ except Exception as _ce: # noqa: BLE001
18098
+ _log(f"browser: Stop from Chrome → cancel failed: {type(_ce).__name__}: {_ce}")
18099
+
18100
+ def _gif_save(why: str = "") -> str:
18101
+ r = _gif.save()
18102
+ if not r:
18103
+ return "The recording had no frames — nothing was saved."
18104
+ path, n, size = r
18105
+ _emit({"type": "step", "text": f"Recorded GIF → {path}"})
18106
+ return (f"Saved the recording{why}: {path} ({n} frames, {size // 1024} KB"
18107
+ + (f"; the {_gif.dropped} oldest middle steps were dropped to stay under 120 frames" if _gif.dropped else "")
18108
+ + "). Give the user this full path.")
17457
18109
 
17458
18110
  def _browser_ask(what: str):
17459
18111
  """→ "" when the browser may be used, else the message for the model."""
@@ -17483,16 +18135,17 @@ def run_agent_chat(cfg):
17483
18135
  def browser(action: str, url: str = "", ref: int = 0, x: int = -1, y: int = -1,
17484
18136
  text: str = "", clear: bool = False, submit: bool = False,
17485
18137
  direction: str = "", amount: int = 0, seconds: int = 0, tab: str = "",
17486
- new_tab: bool = False, focus: bool = False) -> str:
18138
+ new_tab: bool = False, focus: bool = False, failed: bool = False, body: bool = False,
18139
+ path: str = "") -> str:
17487
18140
  """Use a REAL Chrome browser like a person does — open a page, see it, click with the mouse, type with the keyboard — to test a UI flow, check a page renders, fill a form or click through an app. The first call asks the user's permission. It uses the user's Chrome through the gu extension when that is installed, otherwise gu's own Chrome window (a separate profile: not logged in to the user's accounts). Loop: open → read (or screenshot) → click / type → read again to check what happened. Only gu's own tabs, and tabs the user shared, are used. If the answer starts BROWSER NOT AVAILABLE, stop and tell the user (the answer says what to do).
17488
18141
 
17489
18142
  Args:
17490
- action: one of: open (url) · read (page text + visible interactive elements numbered [n] with x,y) · screenshot (an image of the page; pixels = click x,y) · click / double_click / right_click / hover (ref, or x and y) · type (text into the focused field; with ref it clicks that field first) · key (text: "Enter", "Tab", "Escape", "ctrl+a", "shift+Tab"… several separated by spaces) · scroll (direction, amount) · back · reload · wait (seconds) · js (text = a JavaScript expression run in the page; returns its value — gu's own Chrome window only: through the gu Chrome extension it is refused, so prefer read / console) · console (the page's console messages since the last call) · tabs · switch (tab) · close
18143
+ action: one of: open (url) · read (page text + visible interactive elements numbered [n] with x,y) · screenshot (an image of the page; pixels = click x,y) · click / double_click / right_click / hover (ref, or x and y) · type (text into the focused field; with ref it clicks that field first) · key (text: "Enter", "Tab", "Escape", "ctrl+a", "shift+Tab"… several separated by spaces) · scroll (direction, amount) · back · reload · wait (seconds) · js (text = a JavaScript expression run in the page; returns its value — gu's own Chrome window only: through the gu Chrome extension it is refused, so prefer read / console) · console (the page's console messages since the last call) · record_start (text = an optional name) / record_stop: record every browser step in between as a GIF the user can watch — record_stop gives its full path · resize (text = small, mobile, mobile-landscape, tablet, tablet-landscape, desktop, wide, reset, or a size like "375x667" — to check a responsive layout; below 1024 px wide it is a touch device; gu's tab only, undone at the end of the turn) · upload (path = a file in the workspace, into the page's file input: ref of the input or of the upload button — gu answers the file chooser) · network (the page's requests since the last call: method, status, URL, type, time — when a click seems to do nothing, read network and console) · tabs · switch (tab) · close
17491
18144
  url: for open — a full http(s):// or file:// url (localhost:3000 is taken as http://localhost:3000)
17492
18145
  ref: an element's [n] from the last read, for click/hover/type
17493
18146
  x: page x coordinate for click/hover (from read's @x,y or the screenshot), when no ref
17494
18147
  y: page y coordinate, with x
17495
- text: what to type (type), the key(s) to press (key), or the JavaScript expression (js)
18148
+ text: what to type (type), the key(s) to press (key), the JavaScript expression (js), the size (resize), or for network only the requests whose URL contains it (e.g. "/api/")
17496
18149
  clear: type only — replace the field's current value instead of adding to it
17497
18150
  submit: type only — press Enter after typing
17498
18151
  direction: scroll only — down (default), up, left or right
@@ -17501,9 +18154,20 @@ def run_agent_chat(cfg):
17501
18154
  tab: switch only — a tab id from tabs (a number, or an id like "8F3A…" in gu's own window)
17502
18155
  new_tab: open only — open in a new tab instead of the current gu tab
17503
18156
  focus: open / switch only — also bring that tab to the front so the user can see where gu works (off by default: the user's own tab keeps the focus)
18157
+ failed: network only — just the requests that failed or answered 400 and above
18158
+ body: network only — also the response body of the first failed request (up to 2 KB), usually the server's error message
18159
+ path: upload only — the file to upload (inside the workspace or the temp folder)
17504
18160
  """
17505
18161
  import gu_browser as _gb
17506
18162
  a = (action or "").strip().lower().replace(" ", "_").replace("-", "_")
18163
+ if _browser_consent.get("stopped"):
18164
+ msg = _gb.STOPPED_BY_USER + ". Stop now: do not call any tool again, and tell the user you stopped."
18165
+ _last_obs["text"] = msg
18166
+ return msg
18167
+ if a == "record_stop":
18168
+ msg = _gif_save() if _gif.on else "Not recording — call record_start first."
18169
+ _last_obs["text"] = msg
18170
+ return msg
17507
18171
  try:
17508
18172
  cmd = {"action": a}
17509
18173
  if url:
@@ -17519,7 +18183,8 @@ def run_agent_chat(cfg):
17519
18183
  cmd["x"], cmd["y"] = float(x), float(y)
17520
18184
  if text:
17521
18185
  cmd["text"] = str(text)
17522
- for k, v in (("clear", clear), ("submit", submit), ("new_tab", new_tab), ("focus", focus)):
18186
+ for k, v in (("clear", clear), ("submit", submit), ("new_tab", new_tab), ("focus", focus),
18187
+ ("failed", failed), ("body", body)):
17523
18188
  if v:
17524
18189
  cmd[k] = True
17525
18190
  if direction:
@@ -17530,10 +18195,38 @@ def run_agent_chat(cfg):
17530
18195
  cmd["seconds"] = int(seconds)
17531
18196
  if tab:
17532
18197
  cmd["tab"] = int(tab) if str(tab).strip().isdigit() else str(tab).strip()
18198
+ _furl = str(cmd.get("url") or "")
18199
+ if a == "open" and (_furl.startswith("file:") or not re.match(r"^[a-z][a-z0-9+.-]*:", _furl, re.I)) \
18200
+ and _is_image_path(unquote(urlparse(_furl).path or _furl)):
18201
+ # GH #559: a picture on disk is not a web page — waking Chrome to show it took
18202
+ # a minute and the model still could not read it.
18203
+ msg = _image_not_text_msg(unquote(urlparse(_furl).path or _furl))
18204
+ _last_obs["text"] = msg
18205
+ return msg
18206
+ if a == "upload":
18207
+ # GH #547: only a file the agent may read anyway, and one that exists.
18208
+ _up = _rag_read_allowed((path or "").strip())
18209
+ if not os.path.isfile(_up):
18210
+ return f"Error: upload needs an existing file — {path!r} is not one."
18211
+ cmd["path"] = _up
17533
18212
  shot_ok = a == "screenshot" and (
17534
18213
  _is_anthropic_url(coding_base_url) or _coder_takes_images(coding_base_url, coding_model_id))
17535
18214
  if a == "screenshot" and not shot_ok:
17536
18215
  cmd["action"] = "read" # this model is not sent images: it gets the page as text
18216
+ if a == "record_start":
18217
+ # GH #548: from now on every browser step is a frame, until record_stop or the
18218
+ # turn's end. The first frame is the page as it is now (when there is one).
18219
+ refused = _browser_ask("record the browser")
18220
+ if refused:
18221
+ _last_obs["text"] = refused
18222
+ return refused
18223
+ _gif.start(text)
18224
+ _gif_frame()
18225
+ _emit({"type": "step", "text": "Browser recording → started"})
18226
+ msg = ("Recording: every browser step from now on is a frame of a GIF. Call browser "
18227
+ "action=record_stop when done (it also stops by itself at the end of the turn).")
18228
+ _last_obs["text"] = msg
18229
+ return msg
17537
18230
  what = cmd.get("url") or (f"[{ref}]" if ref else f"{int(x)},{int(y)}" if "x" in cmd else
17538
18231
  _clip(str(text), 50) if text else "")
17539
18232
  _emit({"type": "step", "text": f"Browser {a}" + (f" → {what}" if what else "")})
@@ -17552,6 +18245,12 @@ def run_agent_chat(cfg):
17552
18245
  cmd, log=_log, own=_gb.own_allowed(),
17553
18246
  on_wait=lambda: _emit({"type": "step", "text": "Waiting for Chrome to connect…"}))
17554
18247
  where = res.pop("_backend", "") if ok and isinstance(res, dict) else ""
18248
+ if ok and not _browser_consent.get("stop_cleanup"):
18249
+ _browser_consent["stop_cleanup"] = True
18250
+ _ON_STOP.append(lambda: _gb.cleanup(log=_log, quick=True))
18251
+ if where == "extension" and not _browser_consent.get("stop_watch"):
18252
+ # GH #551: from the first command in the user's Chrome, its Stop button works.
18253
+ _browser_consent["stop_watch"] = _gb.watch_stop(_browser_stopped, log=_log) or True
17555
18254
  if where and where != _browser_consent["where"]:
17556
18255
  _browser_consent["where"] = where
17557
18256
  _emit({"type": "step", "text": "Using gu's own Chrome window" if where == "chrome"
@@ -17565,7 +18264,7 @@ def run_agent_chat(cfg):
17565
18264
  msg = f"Error: browser {a} failed: {res}"
17566
18265
  elif a == "screenshot" and shot_ok:
17567
18266
  im, note = _gb.decode_screenshot(res, _IMAGE_MAX_EDGE)
17568
- _browser_shot["img"] = im
18267
+ _browser_shot["imgs"].append(im)
17569
18268
  msg = _gb.format_result("screenshot", res) + "\n" + note + " The image is attached to this observation."
17570
18269
  elif a == "screenshot":
17571
18270
  msg = ("(This coding model is not sent images, so here is the page as text.)\n"
@@ -17586,6 +18285,11 @@ def run_agent_chat(cfg):
17586
18285
  + "\n--- the page now (no need to read again) ---\n" + _gb.format_read(res2)
17587
18286
  except Exception: # noqa: BLE001
17588
18287
  pass
18288
+ if ok and _gif.on and a in ("open", "click", "double_click", "right_click", "hover", "type", "key",
18289
+ "scroll", "back", "reload", "wait", "upload", "resize", "switch"):
18290
+ _at = str((res or {}).get("at") or "") if isinstance(res, dict) else ""
18291
+ _xy = tuple(float(v) for v in _at.split(",")) if re.match(r"^\d+(\.\d+)?,\d+(\.\d+)?$", _at) else None
18292
+ _gif_frame(_xy)
17589
18293
  if ok and where == "chrome" and a == "open":
17590
18294
  msg = ("(NO gu extension is connected, so this is gu's own Chrome window — a separate "
17591
18295
  "profile, NOT signed in to the user's accounts. Say so if it matters to the task.)\n" + msg)
@@ -17616,6 +18320,10 @@ def run_agent_chat(cfg):
17616
18320
  agent_tools += [symbol_context, grep_repo, read_file_lines, edit_lines, edit_file,
17617
18321
  create_file, create_folder, run_command, stop_server,
17618
18322
  shell_output, deploy_web]
18323
+ # GH #541: the language server's own answers — only when one is on for a language, so
18324
+ # the model never sees a tool that can only say "no server".
18325
+ if _lsp_cfg and _lsp_cfg.get("on"):
18326
+ agent_tools.insert(agent_tools.index(grep_repo), lsp)
17619
18327
  if _browser_on():
17620
18328
  agent_tools.append(browser)
17621
18329
  # Workspace RAG (task #133): semantic search over the PROJECT itself, not just a
@@ -17628,6 +18336,11 @@ def run_agent_chat(cfg):
17628
18336
  # (S3 indexing) isn't configured.
17629
18337
  if not _RAG_AVAILABLE:
17630
18338
  agent_tools += [list_dir, read_text_file]
18339
+ # GH #559: pictures in the project — one step to the model, like Claude Code's Read.
18340
+ agent_tools.insert(agent_tools.index(read_text_file) + 1, view_image)
18341
+ # GH #562: gu's terminal (a job id) can show a line mid-turn — the answer to a note the user typed.
18342
+ if _job_id:
18343
+ agent_tools.append(say)
17631
18344
 
17632
18345
  # EXPLORE (task #276) — Claude Code's Explore subagent, for gu. Every grep and read
17633
18346
  # used to land in THIS loop and be re-sent on every later step. explore() searches
@@ -17635,6 +18348,8 @@ def run_agent_chat(cfg):
17635
18348
  # READ-ONLY BY CONSTRUCTION: its tool list has no edit, write, command or network
17636
18349
  # tool, so it cannot change anything whatever the text says.
17637
18350
  _explore_tools = [symbol_context, grep_repo, read_file_lines, list_dir, read_text_file]
18351
+ if _lsp_cfg and _lsp_cfg.get("on"):
18352
+ _explore_tools.insert(1, lsp) # read-only: it belongs in explore's search kit too
17638
18353
  if _RAG_AVAILABLE:
17639
18354
  _explore_tools.append(rag_search_workspace)
17640
18355
 
@@ -17988,6 +18703,12 @@ def run_agent_chat(cfg):
17988
18703
  or _fallback_recap(_turn_steps, _last_obs.get("text"))
17989
18704
  or "[No result]")
17990
18705
  _log(f"done (deterministic, no summarizer call): {len(final_text)} chars")
18706
+ # GH #548: a recording still on at the end of the turn is saved, not lost.
18707
+ try:
18708
+ if _gif.on:
18709
+ _log(_gif_save(" (the turn ended while recording)"))
18710
+ except Exception as _ge: # noqa: BLE001
18711
+ _log(f"gif save at the end of the turn failed: {type(_ge).__name__}: {_ge}")
17991
18712
  # GH #428: close the Chrome tabs gu opened this turn (shared tabs are only let go of).
17992
18713
  try:
17993
18714
  if _browser_consent.get("ok"):