@tiens.nguyen/gu-cli 1.0.931 → 1.0.932

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.
@@ -4693,7 +4693,37 @@ def _learn_context_window(base_url: str, model_id: str, err) -> int:
4693
4693
  _UNKNOWN_CTX_COMPACT_AT = 24000
4694
4694
 
4695
4695
 
4696
- def _compact_threshold(context_window: int) -> int:
4696
+ def _autocompact_path() -> str:
4697
+ """The user's autocompact choice (GH #538), written by gu's startup question and /autocompact."""
4698
+ return os.path.join(os.path.expanduser("~"), ".gonext", "autocompact.json")
4699
+
4700
+
4701
+ def _autocompact_cap(model_id: str = "") -> int:
4702
+ """The most prompt tokens a turn may grow to before older steps are compacted, or 0 for none.
4703
+
4704
+ GH #538. gu asks once (default 400k): compacting a 1M model near 2/3 of its window means every
4705
+ step of a long session resends ~666k tokens — slow and costly, for no gain on most tasks.
4706
+ The file: {"all": 400000 | null, "models": {"<model id>": 400000 | null}}. A model's own entry
4707
+ wins over "all"; null means "keep" (no cap: the 2/3 rule alone). Missing or unreadable → 0.
4708
+ """
4709
+ try:
4710
+ with open(_autocompact_path(), "r", encoding="utf-8") as fh:
4711
+ data = json.load(fh)
4712
+ except Exception: # noqa: BLE001 — no file is the normal case before the question is answered
4713
+ return 0
4714
+ if not isinstance(data, dict):
4715
+ return 0
4716
+ models = data.get("models") if isinstance(data.get("models"), dict) else {}
4717
+ key = str(model_id or "").strip().lower()
4718
+ val = models[key] if key and key in models else data.get("all")
4719
+ try:
4720
+ cap = int(val or 0)
4721
+ except (TypeError, ValueError):
4722
+ return 0
4723
+ return cap if cap >= 16000 else 0 # a nonsense value never shrinks the window to nothing
4724
+
4725
+
4726
+ def _compact_threshold(context_window: int, cap: int = 0) -> int:
4697
4727
  """Prompt tokens at which older steps get compacted.
4698
4728
 
4699
4729
  Two thirds of the window: late enough that a normal turn never trips it, early enough that
@@ -4708,10 +4738,14 @@ def _compact_threshold(context_window: int) -> int:
4708
4738
  the fix (GONEXT_CODING_CONTEXT_WINDOW) is discoverable instead of buried in a log.
4709
4739
 
4710
4740
  The docstring used to say 32k while the code returned 24000; the number is 24000.
4741
+
4742
+ `cap` (GH #538, _autocompact_cap): the user's limit — the threshold never goes above it.
4711
4743
  """
4712
4744
  if context_window and context_window > 4096:
4713
- return int(context_window * 2 / 3)
4714
- return _UNKNOWN_CTX_COMPACT_AT
4745
+ base = int(context_window * 2 / 3)
4746
+ else:
4747
+ base = _UNKNOWN_CTX_COMPACT_AT
4748
+ return min(base, cap) if cap and cap > 0 else base
4715
4749
 
4716
4750
 
4717
4751
  def _is_billing_failure(err) -> bool:
@@ -6831,14 +6865,15 @@ def _same_embed_model(a: str, b: str) -> bool:
6831
6865
  _RUNTOOL_PREFIX = "__RUNTOOL__::"
6832
6866
 
6833
6867
 
6834
- def _fmt_call(name: str, **kw) -> str:
6835
- """A tool call rendered the way the model writes it. Skips empty/default arguments."""
6868
+ def _fmt_call(_tool: str, /, **kw) -> str:
6869
+ """A tool call rendered the way the model writes it. Skips empty/default arguments.
6870
+ The tool name is positional-only: symbol_context has an argument called `name` (GH #552)."""
6836
6871
  parts = []
6837
6872
  for k, v in kw.items():
6838
6873
  if v is None or v == "" or (isinstance(v, int) and not isinstance(v, bool) and v == 0):
6839
6874
  continue
6840
6875
  parts.append(f"{k}={json.dumps(v)}" if isinstance(v, str) else f"{k}={v}")
6841
- return f"{name}({', '.join(parts)})"
6876
+ return f"{_tool}({', '.join(parts)})"
6842
6877
 
6843
6878
 
6844
6879
  def _emit_running(label: str, detail: str) -> None:
@@ -8025,6 +8060,131 @@ def _stray_script_char(code: str, filename: str = ""):
8025
8060
  return None
8026
8061
 
8027
8062
 
8063
+ def _lsp_post(lsp_cfg: dict, path: str, body: dict, timeout: float) -> dict:
8064
+ """POST to the worker's language-server host (lsp-host.mjs) on 127.0.0.1."""
8065
+ import urllib.request as _u
8066
+ req = _u.Request(lsp_cfg["url"] + path, data=json.dumps(body).encode("utf-8"), method="POST",
8067
+ headers={"Content-Type": "application/json", "X-Gu-Lsp-Token": str(lsp_cfg.get("token") or "")})
8068
+ # 127.0.0.1 must never go through a proxy from the environment.
8069
+ opener = _u.build_opener(_u.ProxyHandler({}))
8070
+ with opener.open(req, timeout=timeout) as resp:
8071
+ return json.loads(resp.read().decode("utf-8"))
8072
+
8073
+
8074
+ def _lsp_code_check(lsp_cfg, turn, rp, content, changed, workspace, ask=None, emit=None, log=None) -> str:
8075
+ """Text to add to a write tool's result: the file's errors from its language server, or "".
8076
+
8077
+ GH #540, like Claude Code's code-intelligence plugins: code that does not compile is reported in
8078
+ the SAME step that wrote it, so the agent fixes it before saying it is done. Never raises and
8079
+ never waits long: the host answers within a budget (3 s once the server is warm, 10 s while it
8080
+ starts), and every non-answer — no server, still starting, timeout — adds nothing.
8081
+
8082
+ `turn` is this turn's memory ({"warm": set(), "said": set()}); `ask(command) -> bool` puts the
8083
+ offer to the user (the terminal shows Yes / Not now / Never…); `changed` is [from, to] or None.
8084
+ """
8085
+ emit = emit or (lambda ev: None)
8086
+ log = log or (lambda s: None)
8087
+ if not lsp_cfg:
8088
+ return ""
8089
+ try:
8090
+ ext = os.path.splitext(rp)[1].lower()
8091
+ if ext not in (lsp_cfg.get("exts") or []):
8092
+ return ""
8093
+ budget = 3000 if ext in turn["warm"] else 10000
8094
+ body = {"file": rp, "text": content, "changed": changed, "workspace": workspace, "budgetMs": budget}
8095
+ r = _lsp_post(lsp_cfg, "/check", body, budget / 1000 + 5)
8096
+ if r.get("status") == "offer":
8097
+ command = "__LSP__::" + "\t".join([
8098
+ str(r.get("lang") or ""), str(r.get("name") or ""), str(r.get("server") or ""),
8099
+ "install" if r.get("needsInstall") else "on", str(r.get("size") or "")])
8100
+ if not (ask and ask(command)):
8101
+ return ""
8102
+ body["budgetMs"] = 10000
8103
+ r = _lsp_post(lsp_cfg, "/check", body, 15)
8104
+ status = r.get("status")
8105
+ server = str(r.get("server") or "language server")
8106
+ if status == "installing":
8107
+ if server not in turn["said"]:
8108
+ turn["said"].add(server)
8109
+ emit({"type": "step", "text": f"Installing language server → {server} (errors are checked from the next edit)"})
8110
+ return ""
8111
+ if status != "ok":
8112
+ if status not in ("off", "unsupported"):
8113
+ log(f"code check skipped for {rp}: {status} {r.get('why') or ''}".rstrip())
8114
+ return ""
8115
+ turn["warm"].add(ext)
8116
+ n_err, n_warn, rows = int(r.get("errors") or 0), int(r.get("warnings") or 0), r.get("rows") or []
8117
+ total = n_err + n_warn
8118
+ # "problems", not "errors": the step row groups with the look-ups instead of popping as a
8119
+ # failure — the agent is about to fix them; the user is told when the TURN fails.
8120
+ emit({"type": "step", "text": f"Checking code → {os.path.basename(rp)}: "
8121
+ + (f"{total} problem{'s' if total != 1 else ''}" if total else "no problems")})
8122
+ if not total:
8123
+ return f"\n\nCode check ({server}): no errors."
8124
+ head = f"{n_err} error{'s' if n_err != 1 else ''}" + (
8125
+ f", {n_warn} warning{'s' if n_warn != 1 else ''} on the changed lines" if n_warn else "")
8126
+ lines = [f" line {x.get('line')}:{x.get('col')} {x.get('kind')}: {x.get('message')}" for x in rows]
8127
+ if total > len(rows):
8128
+ lines.append(f" (+{total - len(rows)} more)")
8129
+ return (f"\n\nCode check ({server}) — {head}:\n" + "\n".join(lines)
8130
+ + "\nThese come from the language's own compiler/type checker. Fix them before you finish.")
8131
+ except Exception as e: # noqa: BLE001 — a code check must never break a write
8132
+ log(f"code check failed for {rp}: {e}")
8133
+ return ""
8134
+
8135
+
8136
+ _LSP_OPS = ("definition", "references", "type", "symbol")
8137
+
8138
+
8139
+ def _lsp_query_text(lsp_cfg, op, rp, line, symbol, workspace) -> str:
8140
+ """The `lsp` tool's answer (GH #541): what the language server says about a symbol, as text.
8141
+
8142
+ Paths are shown relative to the workspace, each with its line's own text, so the model can act
8143
+ on them without another read. Every failure is a sentence that points back to the grep tools.
8144
+ """
8145
+ op = str(op or "").strip().lower()
8146
+ if op not in _LSP_OPS:
8147
+ return f"Error: operation must be one of {', '.join(_LSP_OPS)}."
8148
+ if op != "symbol" and not int(line or 0):
8149
+ return "Error: give the line (1-based) where the symbol appears in that file."
8150
+ try:
8151
+ r = _lsp_post(lsp_cfg, "/query", {"op": op, "file": rp, "line": int(line or 0), "symbol": symbol or "",
8152
+ "query": symbol or "", "workspace": workspace, "budgetMs": 8000}, 15)
8153
+ except Exception as e: # noqa: BLE001
8154
+ return f"The language server did not answer ({e}). Use symbol_context or grep_repo instead."
8155
+ st = r.get("status")
8156
+ if st == "off":
8157
+ return (f"No language server is on for {r.get('name') or 'this language'} — use symbol_context or grep_repo. "
8158
+ "(The user can turn one on with /lsp.)")
8159
+ if st == "unsupported":
8160
+ return "No language server knows this file type — use symbol_context or grep_repo."
8161
+ if st in ("starting", "timeout"):
8162
+ return f"The language server is still {'starting' if st == 'starting' else 'busy'} — try again in a moment, or use symbol_context."
8163
+ if st != "ok":
8164
+ return f"The language server could not answer ({r.get('why') or st}). Use symbol_context or grep_repo."
8165
+ if op == "type":
8166
+ t = str(r.get("type") or "").strip()
8167
+ return t or f"The language server has no type information for '{symbol}' on line {line}."
8168
+
8169
+ def rel(f):
8170
+ try:
8171
+ return os.path.relpath(f, workspace) if workspace and not os.path.relpath(f, workspace).startswith("..") else f
8172
+ except ValueError:
8173
+ return f
8174
+ res = r.get("results") or []
8175
+ if not res:
8176
+ return {"definition": f"No definition found for '{symbol}' (line {line}).",
8177
+ "references": f"No references found for '{symbol}'.",
8178
+ "symbol": f"No symbol matching '{symbol}' in this project."}[op]
8179
+ rows = []
8180
+ for x in res[:30]:
8181
+ label = f"{x.get('kind') + ' ' if x.get('kind') else ''}{x.get('name') + ' — ' if x.get('name') else ''}"
8182
+ rows.append(f"{rel(x.get('file') or '')}:{x.get('line')} {label}{x.get('text') or ''}".rstrip())
8183
+ more = f"\n(+{len(res) - 30} more)" if len(res) > 30 else ""
8184
+ head = {"definition": "Defined at", "references": f"{len(res)} reference(s)", "symbol": f"{len(res)} symbol(s)"}[op]
8185
+ return f"{head} ({r.get('server')}):\n" + "\n".join(rows) + more
8186
+
8187
+
8028
8188
  def _write_sanity_error(path: str, content: str):
8029
8189
  """Why this write should NOT be reported as a success, or None if it is fine.
8030
8190
 
@@ -8140,6 +8300,86 @@ def _ws_backup_root() -> str:
8140
8300
  return root
8141
8301
 
8142
8302
 
8303
+ # GH #557, seen live on Windows 11: told an edit failed with "file is locked", the agent listed
8304
+ # every node process and ran `Stop-Process -Id <all of them>` — gu itself, its worker and its API
8305
+ # died mid-turn, without the user being asked. A command that stops processes is checked first.
8306
+ _KILL_VERB_RE = re.compile(
8307
+ r"(?i)(?<![\w-])(stop-process|spps|taskkill(?:\.exe)?|kill|pkill|killall|tskill)(?![\w-])")
8308
+ _KILL_BY_NAME_RE = re.compile(
8309
+ r"(?i)(?:(?:stop-process|spps)\b[^|;&]*-(?:name|processname)\s+['\"]?|taskkill\b[^|;&]*/im\s+['\"]?|"
8310
+ r"(?:pkill|killall)\s+(?:-\S+\s+)*['\"]?|get-process\s+(?:-name\s+)?['\"]?)"
8311
+ r"(node|python|python3|py|pythonw|gu|gu-cli|gu-repl)(?:\.exe)?\b")
8312
+ _GU_OWN_CMD_RE = re.compile(
8313
+ r"(?i)(gu-repl\.mjs|gu-cli\.mjs|gonext_agent_chat\.py|gu-local-worker|[\\/]\.gonext[\\/]api[\\/])")
8314
+
8315
+
8316
+ def _gu_kill_refusal(command: str, own: dict) -> str:
8317
+ """'' when the command stops no gu process, else why it must not run. Pure: `own` maps pid →
8318
+ what it is (gu's API, the worker, this turn…), from _gu_own_processes()."""
8319
+ if not command or not _KILL_VERB_RE.search(command):
8320
+ return ""
8321
+ m = _KILL_BY_NAME_RE.search(command)
8322
+ if m:
8323
+ return (f"it stops EVERY {m.group(1)} process by name, and gu itself runs as {m.group(1)} — "
8324
+ "the turn, gu's worker and its API would stop with it")
8325
+ if re.search(r"(?i)get-process\b[^;]*\|\s*(stop-process|spps)\b", command):
8326
+ return "it pipes a list of processes into Stop-Process, which can include gu's own"
8327
+ hit = [f"{pid} ({what})" for pid, what in own.items()
8328
+ if re.search(rf"(?<![\d]){int(pid)}(?![\d])", command)]
8329
+ if hit:
8330
+ return "it would stop gu itself: " + ", ".join(hit)
8331
+ return ""
8332
+
8333
+
8334
+ def _gu_own_processes() -> dict:
8335
+ """pid → what it is, for every process that is gu: this turn and its parent, the pid files
8336
+ in ~/.gonext, and any process whose command line is gu's (the REPL, the worker, the API)."""
8337
+ import subprocess
8338
+ own = {os.getpid(): "this turn", os.getppid(): "the gu worker running this turn"}
8339
+ gdir = os.path.join(os.path.expanduser("~"), ".gonext")
8340
+ for name, what in (("local-api.pid", "gu's local API"), ("worker.pid", "the gu worker")):
8341
+ try:
8342
+ with open(os.path.join(gdir, name), encoding="utf-8") as fh:
8343
+ own.setdefault(int(fh.read().strip().split()[0]), what)
8344
+ except (OSError, ValueError, IndexError):
8345
+ pass
8346
+ try:
8347
+ if _IS_WINDOWS:
8348
+ out = subprocess.run(
8349
+ ["powershell.exe", "-NoProfile", "-NonInteractive", "-Command",
8350
+ "Get-CimInstance Win32_Process | ForEach-Object { \"$($_.ProcessId) $($_.CommandLine)\" }"],
8351
+ capture_output=True, text=True, timeout=15).stdout
8352
+ else:
8353
+ out = subprocess.run(["ps", "-axo", "pid=,command="], capture_output=True, text=True, timeout=10).stdout
8354
+ for line in out.splitlines():
8355
+ pid, _, cmd = line.strip().partition(" ")
8356
+ if pid.isdigit() and _GU_OWN_CMD_RE.search(cmd):
8357
+ own.setdefault(int(pid), "gu")
8358
+ except Exception: # noqa: BLE001
8359
+ pass
8360
+ return own
8361
+
8362
+
8363
+ def _ws_backup_dest(root: str, path: str, sep: str = None) -> str:
8364
+ """Where a file's backup goes: its absolute path, re-rooted under the run's backup folder. Pure.
8365
+
8366
+ GH #557, seen live on Windows 11: `path.lstrip(os.sep)` leaves `C:\\Users\\…` absolute, so
8367
+ os.path.join threw the backup folder away and gu copied each file ONTO ITSELF — WinError 32,
8368
+ and every edit on Windows failed. The drive (`C:` → `C`, a share `\\\\srv\\share` → `srv_share`)
8369
+ becomes the first folder instead.
8370
+ """
8371
+ import ntpath
8372
+ import posixpath
8373
+ sep = sep or os.sep
8374
+ mod = ntpath if sep == "\\" else posixpath
8375
+ drive, rest = mod.splitdrive(path)
8376
+ rest = rest.lstrip("\\/")
8377
+ if drive:
8378
+ drive = drive.replace(":", "").strip("\\/").replace("\\", "_").replace("/", "_") or "drive"
8379
+ return mod.normpath(mod.join(root, drive, rest))
8380
+ return mod.normpath(mod.join(root, rest))
8381
+
8382
+
8143
8383
  def _ws_snapshot(path: str) -> str:
8144
8384
  """Copy the file to the run's backup dir before its FIRST edit in this run, so
8145
8385
  every change is revertible. Returns the backup path ('' if new file)."""
@@ -8151,7 +8391,7 @@ def _ws_snapshot(path: str) -> str:
8151
8391
  if c["path"] == path and c.get("backup"):
8152
8392
  return c["backup"]
8153
8393
  root = _ws_backup_root()
8154
- dest = os.path.join(root, path.lstrip(os.sep))
8394
+ dest = _ws_backup_dest(root, path)
8155
8395
  os.makedirs(os.path.dirname(dest), exist_ok=True)
8156
8396
  shutil.copy2(path, dest)
8157
8397
  return dest
@@ -10145,6 +10385,9 @@ def _ws_request_approval(api_base, worker_key, job_id, command, reason, deadline
10145
10385
  _emit({"type": "step", "text": "Awaiting your choice: set up S3, or save on this computer?"})
10146
10386
  elif command.startswith("__BROWSER__::"):
10147
10387
  _emit({"type": "step", "text": "Awaiting your approval: use a web browser"})
10388
+ elif command.startswith("__LSP__::"):
10389
+ _emit({"type": "step", "text": "Awaiting your choice: turn on "
10390
+ + (command[len("__LSP__::"):].split("\t") + ["", ""])[1] + " code intelligence"})
10148
10391
  elif command.startswith("__MCPTOOL__::"):
10149
10392
  _srv, _, _rest = command[len("__MCPTOOL__::"):].partition("\t")
10150
10393
  _emit({"type": "step", "text": f"Awaiting your approval: MCP tool {_srv}/{_rest.split(chr(9))[0]}"})
@@ -10233,10 +10476,21 @@ _INFLIGHT_CMDS: set = set()
10233
10476
  _STOP = {"writing": 0, "requested": False}
10234
10477
 
10235
10478
 
10479
+ # Run when the turn is stopped (worker SIGTERM / stop file): each must be quick — the worker kills
10480
+ # for good ~3 s later. GH #551: closes gu's Chrome tabs, which a stopped turn used to leave open
10481
+ # (with the popup stuck on "Stopping…" and Chrome's debugging banner up).
10482
+ _ON_STOP = []
10483
+
10484
+
10236
10485
  def _stop_now():
10237
10486
  for pid in list(_INFLIGHT_CMDS):
10238
10487
  _ws_kill_tree(pid, force=True)
10239
10488
  _INFLIGHT_CMDS.clear()
10489
+ for _fn in list(_ON_STOP):
10490
+ try:
10491
+ _fn()
10492
+ except Exception: # noqa: BLE001
10493
+ pass
10240
10494
  try:
10241
10495
  _log("stopped by the worker — killed the command in flight")
10242
10496
  except Exception: # noqa: BLE001
@@ -11501,6 +11755,19 @@ def run_agent_chat(cfg):
11501
11755
  # risky command and asks the user via the API instead of hard-blocking it.
11502
11756
  _job_id = (cfg.get("jobId") or "").strip()
11503
11757
  _interactive_approval = bool(cfg.get("interactiveApproval"))
11758
+ # GH #540: the worker's language-server host — {url, token, exts}, or None (web, remote, older
11759
+ # worker). After every write the agent asks it for the file's errors; see _lsp_after_write.
11760
+ _lsp_cfg = cfg.get("lsp") if isinstance(cfg.get("lsp"), dict) and cfg["lsp"].get("url") else None
11761
+ _lsp_turn = {"warm": set(), "said": set()}
11762
+
11763
+ def _lsp_after_write(rp: str, content: str, changed=None) -> str:
11764
+ """The file's errors from its language server, for a write tool's result (GH #540)."""
11765
+ def _ask(command: str) -> bool:
11766
+ if not (_interactive_approval and _job_id and worker_api_base and worker_api_key):
11767
+ return False
11768
+ return _ws_request_approval(worker_api_base, worker_api_key, _job_id, command, "", deadline_s=45)
11769
+ return _lsp_code_check(_lsp_cfg, _lsp_turn, rp, content, changed,
11770
+ _WS_ACTIVE or _default_ws_root(), ask=_ask, emit=_emit, log=_log)
11504
11771
  # Skills and MCP servers (task #269). The worker scans ~/.gonext/skills, ~/.gonext/mcp.json and
11505
11772
  # this folder's .gonext/skills + .mcp.json for every turn; none present = neither appears
11506
11773
  # anywhere in the prompt. Names only here — a skill's body is read when it is used.
@@ -12867,6 +13134,12 @@ def run_agent_chat(cfg):
12867
13134
  # drops the whole entry: after an edit the line numbers mean something else, and a stale
12868
13135
  # range would refuse a read the model genuinely needs.
12869
13136
  _read_ranges: dict = {}
13137
+ # GH #552 (seen live): a read whose text never reached the model — several read_file_lines
13138
+ # calls in one code block without print(), where only the last value is shown — was still
13139
+ # recorded as "already shown", so every retry was refused and the model read the file with cat.
13140
+ # A range is recorded here first and counts as shown only when step_callback finds its text in
13141
+ # the step's observation.
13142
+ _pending_ranges: list = []
12870
13143
 
12871
13144
  def _server_log_tail_for_url(url: str) -> str:
12872
13145
  """If `url` is a localhost server we started via run_command, return the tail of
@@ -12923,12 +13196,12 @@ def run_agent_chat(cfg):
12923
13196
  """
12924
13197
  prev = _read_ranges.get(rp)
12925
13198
  if not prev or prev[0] != mt:
12926
- _read_ranges[rp] = (mt, [(s, e)])
13199
+ _pending_ranges.append((rp, mt, s, e))
12927
13200
  return ""
12928
13201
  served = prev[1]
12929
13202
  hit = _range_is_covered(served, s, e)
12930
13203
  if hit is None:
12931
- served.append((s, e))
13204
+ _pending_ranges.append((rp, mt, s, e))
12932
13205
  return ""
12933
13206
  import os as _os3
12934
13207
  name = _os3.path.basename(rp)
@@ -12938,6 +13211,23 @@ def run_agent_chat(cfg):
12938
13211
  f"on it instead of re-reading. If you need something you have NOT seen, read a "
12939
13212
  f"different range (the file has {total} lines) or narrow it down with grep_repo.")
12940
13213
 
13214
+ def _settle_pending_reads(observation) -> list:
13215
+ """After a step: each range read in it counts as shown only if its header line is in what
13216
+ the model was actually given. → the reads that were lost (not printed), for a note."""
13217
+ lost = []
13218
+ obs = observation if isinstance(observation, str) else ""
13219
+ for rp, mt, s, e in _pending_ranges:
13220
+ if f"(lines {s}-{e} of " in obs and rp in obs:
13221
+ prev = _read_ranges.get(rp)
13222
+ if not prev or prev[0] != mt:
13223
+ _read_ranges[rp] = (mt, [(s, e)])
13224
+ elif _range_is_covered(prev[1], s, e) is None:
13225
+ prev[1].append((s, e))
13226
+ else:
13227
+ lost.append((rp, s, e))
13228
+ _pending_ranges.clear()
13229
+ return lost
13230
+
12941
13231
  def _dedup(tool_name: str, arg: str, next_hint: str):
12942
13232
  """Return (is_repeat, message). On a repeat, message steers the model forward."""
12943
13233
  key = _norm_query(arg) if tool_name == "web_search" else (arg or "").strip().lower()
@@ -13501,7 +13791,7 @@ def run_agent_chat(cfg):
13501
13791
  if not _CLOUD_LIMITS["loaded"]:
13502
13792
  _fetch_cloud_limits(worker_api_base)
13503
13793
  _ctx_window = _model_context_window(coding_base_url, coding_model_id, coding_api_key)
13504
- _compact_at = _compact_threshold(_ctx_window)
13794
+ _compact_at = _compact_threshold(_ctx_window, _autocompact_cap(coding_model_id))
13505
13795
  _caps = _set_obs_caps(_ctx_window)
13506
13796
  _log(f"read caps: {_caps['read']} chars / {_caps['lines']} lines per read, {_caps['search']} chars "
13507
13797
  f"per search — for a {_ctx_window or 'unknown'}-token window (issues #49, #105)")
@@ -13677,6 +13967,21 @@ def run_agent_chat(cfg):
13677
13967
  except Exception as e: # noqa: BLE001
13678
13968
  _log(f"browser screenshot attach skip: {e}")
13679
13969
 
13970
+ # GH #552: reads whose text the model never saw are not "already shown" — and the model is
13971
+ # told why it saw nothing, so it prints them instead of falling back to cat.
13972
+ try:
13973
+ _lost = _settle_pending_reads(getattr(step_log, "observations", None))
13974
+ if _lost and isinstance(getattr(step_log, "observations", None), str):
13975
+ import os as _osl
13976
+ _names = ", ".join(f"{_osl.path.basename(rp)}:{s}-{e}" for rp, s, e in _lost[:5])
13977
+ step_log.observations += (
13978
+ f"\n\n(Note: read_file_lines returned text for {_names}, but your code did not print it, "
13979
+ "so it is not shown above. A tool's result is shown only when printed — "
13980
+ "use print(read_file_lines(...)) for each read.)")
13981
+ _log(f"step {step_num}: {len(_lost)} read(s) not printed — told the model")
13982
+ except Exception as e: # noqa: BLE001
13983
+ _log(f"pending read settle skip: {e}")
13984
+
13680
13985
  # A background shell that finished during this step is told to the model now (#362).
13681
13986
  try:
13682
13987
  _obs_now = getattr(step_log, "observations", None)
@@ -16266,6 +16571,25 @@ def run_agent_chat(cfg):
16266
16571
  _last_obs["text"] = msg
16267
16572
  return msg
16268
16573
 
16574
+ @tool
16575
+ def lsp(operation: str, path: str, line: int = 0, symbol: str = "") -> str:
16576
+ """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.
16577
+
16578
+ Args:
16579
+ operation: definition, references, type, or symbol.
16580
+ path: a file in the workspace — where the symbol appears (for "symbol": any file of that language in the project).
16581
+ line: 1-based line where the symbol appears (not needed for "symbol").
16582
+ symbol: the symbol's name, e.g. "Greeter" (for "symbol": the name or part of it to search for).
16583
+ """
16584
+ try:
16585
+ rp = _rag_read_allowed((path or "").strip())
16586
+ except Exception as ex: # noqa: BLE001
16587
+ return f"Error: {ex}"
16588
+ _emit_running("Asking language server", _fmt_call("lsp", operation=operation, path=path, symbol=symbol))
16589
+ out = _lsp_query_text(_lsp_cfg, operation, rp, line, symbol, _WS_ACTIVE or _default_ws_root())
16590
+ _last_obs["text"] = out
16591
+ return out
16592
+
16269
16593
  @tool
16270
16594
  def symbol_context(name: str, path: str = "") -> str:
16271
16595
  """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.
@@ -16447,6 +16771,7 @@ def run_agent_chat(cfg):
16447
16771
  range(max(1, s - 2), min(len(lines), s + len(new_lines) + 1) + 1))
16448
16772
  out = (f"Replaced lines {s}-{e} of {rp} with {len(new_lines)} line(s). "
16449
16773
  f"Backup saved. Updated region:\n{shown}")
16774
+ out += _lsp_after_write(rp, "".join(lines), [s, s + max(0, len(new_lines) - 1)])
16450
16775
  _last_obs["text"] = out
16451
16776
  return out
16452
16777
  except Exception as ex: # noqa: BLE001
@@ -16494,6 +16819,8 @@ def run_agent_chat(cfg):
16494
16819
  added=[(start_no + i, t) for i, t in enumerate(new_ls)],
16495
16820
  )})
16496
16821
  out = f"Replaced 1 occurrence in {rp}. Backup saved."
16822
+ out += _lsp_after_write(rp, text.replace(old_string, new_string, 1),
16823
+ [start_no, start_no + max(0, len(new_ls) - 1)])
16497
16824
  _last_obs["text"] = out
16498
16825
  return out
16499
16826
  except Exception as ex: # noqa: BLE001
@@ -16558,6 +16885,7 @@ def run_agent_chat(cfg):
16558
16885
  )})
16559
16886
  _seen.add(_ch) # remember this content so a later revert-to-it is caught
16560
16887
  out = f"{'Overwrote' if existed else 'Created'} {rp} ({len(content)} chars)."
16888
+ out += _lsp_after_write(rp, content, None)
16561
16889
  _last_obs["text"] = out
16562
16890
  return out
16563
16891
  except Exception as ex: # noqa: BLE001
@@ -16693,6 +17021,16 @@ def run_agent_chat(cfg):
16693
17021
  msg = "Error: empty command."
16694
17022
  _last_obs["text"] = msg
16695
17023
  return msg
17024
+ # GH #557: never stop gu itself (checked only when the line stops processes).
17025
+ _gk = _gu_kill_refusal(command, _gu_own_processes()) if _KILL_VERB_RE.search(command or "") else ""
17026
+ if _gk:
17027
+ msg = (f"Error: that command did NOT run — {_gk}. Stop only a process you started "
17028
+ "in this turn, by its own PID (find it by its port or its command line), "
17029
+ "and never gu's. If a file looks locked, read the tool's error again instead: "
17030
+ "gu does not hold your files open.")
17031
+ _log(f"run_command refused: would stop gu ({_gk})")
17032
+ _last_obs["text"] = msg
17033
+ return msg
16696
17034
  # AN `&&` CHAIN IS ONE STEP (task #274): each part runs through THIS function —
16697
17035
  # allowlist, risk gate, approval, server detection, all of it — in order, and
16698
17036
  # the first failure stops the rest. `cd DIR` sets the folder for what follows.
@@ -17454,6 +17792,48 @@ def run_agent_chat(cfg):
17454
17792
  # (Allow once / Always in this folder / No), unless this folder is on the "always" list in
17455
17793
  # ~/.gonext/browser-allow.json. A "No" holds for the rest of the turn.
17456
17794
  _browser_consent = {"ok": False, "no": False, "where": ""}
17795
+ import gu_gif as _gu_gif
17796
+ _gif = _gu_gif.GifRecorder() # GH #548: browser(action="record_start" … "record_stop")
17797
+
17798
+ def _gif_frame(click=None):
17799
+ """One frame of the recording: a screenshot of gu's tab now. Never fails the step."""
17800
+ try:
17801
+ import gu_browser as _gbf
17802
+ okf, resf, _ncf = _gbf.command({"action": "screenshot"}, log=_log, own=_gbf.own_allowed())
17803
+ if okf and isinstance(resf, dict) and resf.get("image"):
17804
+ im, _note = _gbf.decode_screenshot(resf, max_edge=100000)
17805
+ _gif.add(im, click)
17806
+ except Exception as _fe: # noqa: BLE001
17807
+ _log(f"gif frame skipped: {type(_fe).__name__}: {_fe}")
17808
+
17809
+ def _browser_stopped():
17810
+ """GH #551: Stop in the gu extension = Ctrl+C. The agent cancels its own job (the
17811
+ same call the terminal makes); the worker then stops this process and the terminal
17812
+ says "(cancelled — the agent was stopped)". Without a job to cancel, the extension
17813
+ already refuses every further command with a message telling the model to stop."""
17814
+ _browser_consent["stopped"] = True
17815
+ _emit({"type": "step", "text": "⏹ Stopped from Chrome"})
17816
+ if not (_job_id and worker_api_base and worker_api_key):
17817
+ return
17818
+ _req = urllib.request.Request(
17819
+ f"{worker_api_base.rstrip('/')}/api/worker/jobs/cancel", method="POST",
17820
+ data=json.dumps({"jobId": _job_id}).encode(),
17821
+ headers={"Content-Type": "application/json", "X-Worker-Key": worker_api_key})
17822
+ try:
17823
+ with urllib.request.urlopen(_req, timeout=15, context=_ssl_context()) as _r:
17824
+ _log(f"browser: Stop from Chrome → job {_job_id} cancel answered {_r.status}")
17825
+ except Exception as _ce: # noqa: BLE001
17826
+ _log(f"browser: Stop from Chrome → cancel failed: {type(_ce).__name__}: {_ce}")
17827
+
17828
+ def _gif_save(why: str = "") -> str:
17829
+ r = _gif.save()
17830
+ if not r:
17831
+ return "The recording had no frames — nothing was saved."
17832
+ path, n, size = r
17833
+ _emit({"type": "step", "text": f"Recorded GIF → {path}"})
17834
+ return (f"Saved the recording{why}: {path} ({n} frames, {size // 1024} KB"
17835
+ + (f"; the {_gif.dropped} oldest middle steps were dropped to stay under 120 frames" if _gif.dropped else "")
17836
+ + "). Give the user this full path.")
17457
17837
 
17458
17838
  def _browser_ask(what: str):
17459
17839
  """→ "" when the browser may be used, else the message for the model."""
@@ -17483,16 +17863,17 @@ def run_agent_chat(cfg):
17483
17863
  def browser(action: str, url: str = "", ref: int = 0, x: int = -1, y: int = -1,
17484
17864
  text: str = "", clear: bool = False, submit: bool = False,
17485
17865
  direction: str = "", amount: int = 0, seconds: int = 0, tab: str = "",
17486
- new_tab: bool = False, focus: bool = False) -> str:
17866
+ new_tab: bool = False, focus: bool = False, failed: bool = False, body: bool = False,
17867
+ path: str = "") -> str:
17487
17868
  """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
17869
 
17489
17870
  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
17871
+ 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
17872
  url: for open — a full http(s):// or file:// url (localhost:3000 is taken as http://localhost:3000)
17492
17873
  ref: an element's [n] from the last read, for click/hover/type
17493
17874
  x: page x coordinate for click/hover (from read's @x,y or the screenshot), when no ref
17494
17875
  y: page y coordinate, with x
17495
- text: what to type (type), the key(s) to press (key), or the JavaScript expression (js)
17876
+ 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
17877
  clear: type only — replace the field's current value instead of adding to it
17497
17878
  submit: type only — press Enter after typing
17498
17879
  direction: scroll only — down (default), up, left or right
@@ -17501,9 +17882,20 @@ def run_agent_chat(cfg):
17501
17882
  tab: switch only — a tab id from tabs (a number, or an id like "8F3A…" in gu's own window)
17502
17883
  new_tab: open only — open in a new tab instead of the current gu tab
17503
17884
  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)
17885
+ failed: network only — just the requests that failed or answered 400 and above
17886
+ body: network only — also the response body of the first failed request (up to 2 KB), usually the server's error message
17887
+ path: upload only — the file to upload (inside the workspace or the temp folder)
17504
17888
  """
17505
17889
  import gu_browser as _gb
17506
17890
  a = (action or "").strip().lower().replace(" ", "_").replace("-", "_")
17891
+ if _browser_consent.get("stopped"):
17892
+ msg = _gb.STOPPED_BY_USER + ". Stop now: do not call any tool again, and tell the user you stopped."
17893
+ _last_obs["text"] = msg
17894
+ return msg
17895
+ if a == "record_stop":
17896
+ msg = _gif_save() if _gif.on else "Not recording — call record_start first."
17897
+ _last_obs["text"] = msg
17898
+ return msg
17507
17899
  try:
17508
17900
  cmd = {"action": a}
17509
17901
  if url:
@@ -17519,7 +17911,8 @@ def run_agent_chat(cfg):
17519
17911
  cmd["x"], cmd["y"] = float(x), float(y)
17520
17912
  if text:
17521
17913
  cmd["text"] = str(text)
17522
- for k, v in (("clear", clear), ("submit", submit), ("new_tab", new_tab), ("focus", focus)):
17914
+ for k, v in (("clear", clear), ("submit", submit), ("new_tab", new_tab), ("focus", focus),
17915
+ ("failed", failed), ("body", body)):
17523
17916
  if v:
17524
17917
  cmd[k] = True
17525
17918
  if direction:
@@ -17530,10 +17923,30 @@ def run_agent_chat(cfg):
17530
17923
  cmd["seconds"] = int(seconds)
17531
17924
  if tab:
17532
17925
  cmd["tab"] = int(tab) if str(tab).strip().isdigit() else str(tab).strip()
17926
+ if a == "upload":
17927
+ # GH #547: only a file the agent may read anyway, and one that exists.
17928
+ _up = _rag_read_allowed((path or "").strip())
17929
+ if not os.path.isfile(_up):
17930
+ return f"Error: upload needs an existing file — {path!r} is not one."
17931
+ cmd["path"] = _up
17533
17932
  shot_ok = a == "screenshot" and (
17534
17933
  _is_anthropic_url(coding_base_url) or _coder_takes_images(coding_base_url, coding_model_id))
17535
17934
  if a == "screenshot" and not shot_ok:
17536
17935
  cmd["action"] = "read" # this model is not sent images: it gets the page as text
17936
+ if a == "record_start":
17937
+ # GH #548: from now on every browser step is a frame, until record_stop or the
17938
+ # turn's end. The first frame is the page as it is now (when there is one).
17939
+ refused = _browser_ask("record the browser")
17940
+ if refused:
17941
+ _last_obs["text"] = refused
17942
+ return refused
17943
+ _gif.start(text)
17944
+ _gif_frame()
17945
+ _emit({"type": "step", "text": "Browser recording → started"})
17946
+ msg = ("Recording: every browser step from now on is a frame of a GIF. Call browser "
17947
+ "action=record_stop when done (it also stops by itself at the end of the turn).")
17948
+ _last_obs["text"] = msg
17949
+ return msg
17537
17950
  what = cmd.get("url") or (f"[{ref}]" if ref else f"{int(x)},{int(y)}" if "x" in cmd else
17538
17951
  _clip(str(text), 50) if text else "")
17539
17952
  _emit({"type": "step", "text": f"Browser {a}" + (f" → {what}" if what else "")})
@@ -17552,6 +17965,12 @@ def run_agent_chat(cfg):
17552
17965
  cmd, log=_log, own=_gb.own_allowed(),
17553
17966
  on_wait=lambda: _emit({"type": "step", "text": "Waiting for Chrome to connect…"}))
17554
17967
  where = res.pop("_backend", "") if ok and isinstance(res, dict) else ""
17968
+ if ok and not _browser_consent.get("stop_cleanup"):
17969
+ _browser_consent["stop_cleanup"] = True
17970
+ _ON_STOP.append(lambda: _gb.cleanup(log=_log, quick=True))
17971
+ if where == "extension" and not _browser_consent.get("stop_watch"):
17972
+ # GH #551: from the first command in the user's Chrome, its Stop button works.
17973
+ _browser_consent["stop_watch"] = _gb.watch_stop(_browser_stopped, log=_log) or True
17555
17974
  if where and where != _browser_consent["where"]:
17556
17975
  _browser_consent["where"] = where
17557
17976
  _emit({"type": "step", "text": "Using gu's own Chrome window" if where == "chrome"
@@ -17586,6 +18005,11 @@ def run_agent_chat(cfg):
17586
18005
  + "\n--- the page now (no need to read again) ---\n" + _gb.format_read(res2)
17587
18006
  except Exception: # noqa: BLE001
17588
18007
  pass
18008
+ if ok and _gif.on and a in ("open", "click", "double_click", "right_click", "hover", "type", "key",
18009
+ "scroll", "back", "reload", "wait", "upload", "resize", "switch"):
18010
+ _at = str((res or {}).get("at") or "") if isinstance(res, dict) else ""
18011
+ _xy = tuple(float(v) for v in _at.split(",")) if re.match(r"^\d+(\.\d+)?,\d+(\.\d+)?$", _at) else None
18012
+ _gif_frame(_xy)
17589
18013
  if ok and where == "chrome" and a == "open":
17590
18014
  msg = ("(NO gu extension is connected, so this is gu's own Chrome window — a separate "
17591
18015
  "profile, NOT signed in to the user's accounts. Say so if it matters to the task.)\n" + msg)
@@ -17616,6 +18040,10 @@ def run_agent_chat(cfg):
17616
18040
  agent_tools += [symbol_context, grep_repo, read_file_lines, edit_lines, edit_file,
17617
18041
  create_file, create_folder, run_command, stop_server,
17618
18042
  shell_output, deploy_web]
18043
+ # GH #541: the language server's own answers — only when one is on for a language, so
18044
+ # the model never sees a tool that can only say "no server".
18045
+ if _lsp_cfg and _lsp_cfg.get("on"):
18046
+ agent_tools.insert(agent_tools.index(grep_repo), lsp)
17619
18047
  if _browser_on():
17620
18048
  agent_tools.append(browser)
17621
18049
  # Workspace RAG (task #133): semantic search over the PROJECT itself, not just a
@@ -17635,6 +18063,8 @@ def run_agent_chat(cfg):
17635
18063
  # READ-ONLY BY CONSTRUCTION: its tool list has no edit, write, command or network
17636
18064
  # tool, so it cannot change anything whatever the text says.
17637
18065
  _explore_tools = [symbol_context, grep_repo, read_file_lines, list_dir, read_text_file]
18066
+ if _lsp_cfg and _lsp_cfg.get("on"):
18067
+ _explore_tools.insert(1, lsp) # read-only: it belongs in explore's search kit too
17638
18068
  if _RAG_AVAILABLE:
17639
18069
  _explore_tools.append(rag_search_workspace)
17640
18070
 
@@ -17988,6 +18418,12 @@ def run_agent_chat(cfg):
17988
18418
  or _fallback_recap(_turn_steps, _last_obs.get("text"))
17989
18419
  or "[No result]")
17990
18420
  _log(f"done (deterministic, no summarizer call): {len(final_text)} chars")
18421
+ # GH #548: a recording still on at the end of the turn is saved, not lost.
18422
+ try:
18423
+ if _gif.on:
18424
+ _log(_gif_save(" (the turn ended while recording)"))
18425
+ except Exception as _ge: # noqa: BLE001
18426
+ _log(f"gif save at the end of the turn failed: {type(_ge).__name__}: {_ge}")
17991
18427
  # GH #428: close the Chrome tabs gu opened this turn (shared tabs are only let go of).
17992
18428
  try:
17993
18429
  if _browser_consent.get("ok"):