@tiens.nguyen/gu-cli 1.0.930 → 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.
- package/autocompact.mjs +136 -0
- package/browser-bridge.mjs +8 -0
- package/browser-extension/README.md +4 -0
- package/browser-extension/actions.js +366 -5
- package/browser-extension/background.js +104 -14
- package/browser-extension/manifest.json +1 -1
- package/browser-extension/popup.html +83 -15
- package/browser-extension/popup.js +145 -35
- package/clear-state.mjs +12 -1
- package/cli-token.mjs +48 -1
- package/client-expert-api.mjs +105 -20
- package/client-expert-run.mjs +179 -120
- package/client-expert-setup.mjs +3 -2
- package/free-model.mjs +20 -0
- package/gonext_agent_chat.py +470 -17
- package/gu-cli.mjs +46 -6
- package/gu-repl.mjs +426 -25
- package/gu_browser.py +83 -9
- package/gu_gif.py +101 -0
- package/install-path.mjs +52 -20
- package/lsp-client.mjs +267 -0
- package/lsp-host.mjs +391 -0
- package/lsp-registry.mjs +568 -0
- package/model-doctor.mjs +5 -2
- package/next-suggestion.mjs +137 -0
- package/package.json +9 -1
- package/powershell-alias.mjs +12 -1
- package/setup-fixes.mjs +240 -0
- package/step-group.mjs +59 -18
- package/terminal-layout.mjs +82 -3
- package/win-shell.mjs +26 -0
package/gonext_agent_chat.py
CHANGED
|
@@ -2518,6 +2518,23 @@ _scaffold_problem = _psc.scaffold_problem
|
|
|
2518
2518
|
_SCAFFOLD_REQUIRED = _psc.SCAFFOLD_REQUIRED
|
|
2519
2519
|
|
|
2520
2520
|
|
|
2521
|
+
# Cloudflare (in front of gucli.com since 2 Nov 2026) refuses Python's default "Python-urllib/x"
|
|
2522
|
+
# client name with error 1010 before the API sees the request. Every direct call to the gu service
|
|
2523
|
+
# names itself instead; the default API host (chat-api-v2) is not behind Cloudflare, gucli.com is.
|
|
2524
|
+
def _internal_label() -> str:
|
|
2525
|
+
"""Our own machines only: GU_INTERNAL_LABEL or ~/.gonext/internal-label (real users have neither)."""
|
|
2526
|
+
v = os.environ.get("GU_INTERNAL_LABEL", "").strip()
|
|
2527
|
+
if not v:
|
|
2528
|
+
try:
|
|
2529
|
+
v = open(os.path.join(os.path.expanduser("~"), ".gonext", "internal-label"), encoding="utf-8").read().strip()
|
|
2530
|
+
except OSError:
|
|
2531
|
+
v = ""
|
|
2532
|
+
return re.sub(r"[^A-Za-z0-9._-]", "", v)[:40]
|
|
2533
|
+
|
|
2534
|
+
|
|
2535
|
+
_GU_UA = "gu-agent/1.0 (+https://gucli.com" + (f"; internal:{_internal_label()}" if _internal_label() else "") + ")"
|
|
2536
|
+
|
|
2537
|
+
|
|
2521
2538
|
def _load_prompt_scaffold(api_base: str, worker_key: str):
|
|
2522
2539
|
"""The scaffold for this turn → (template, version, source).
|
|
2523
2540
|
|
|
@@ -2573,7 +2590,7 @@ def _fetch_prompt_scaffold(api_base: str, worker_key: str, name: str = "code-age
|
|
|
2573
2590
|
from urllib.parse import urlencode
|
|
2574
2591
|
req = urllib.request.Request(
|
|
2575
2592
|
f"{base}/api/worker/prompt-scaffold?{urlencode({'name': name})}",
|
|
2576
|
-
headers={"X-Worker-Key": worker_key}, method="GET")
|
|
2593
|
+
headers={"X-Worker-Key": worker_key, "User-Agent": _GU_UA}, method="GET")
|
|
2577
2594
|
try:
|
|
2578
2595
|
with urllib.request.urlopen(req, timeout=15, context=_ssl_context()) as resp:
|
|
2579
2596
|
data = json.loads(resp.read().decode("utf-8", "replace") or "{}")
|
|
@@ -4519,7 +4536,7 @@ def _fetch_cloud_limits(api_base: str, timeout: float = 5.0) -> int:
|
|
|
4519
4536
|
if not base:
|
|
4520
4537
|
return 0
|
|
4521
4538
|
try:
|
|
4522
|
-
req = urllib.request.Request(f"{base}/api/model-limits", method="GET")
|
|
4539
|
+
req = urllib.request.Request(f"{base}/api/model-limits", method="GET", headers={"User-Agent": _GU_UA})
|
|
4523
4540
|
with urllib.request.urlopen(req, timeout=timeout, context=_ssl_context()) as resp:
|
|
4524
4541
|
data = json.loads(resp.read().decode("utf-8", "replace") or "{}")
|
|
4525
4542
|
except Exception as e: # noqa: BLE001
|
|
@@ -4676,7 +4693,37 @@ def _learn_context_window(base_url: str, model_id: str, err) -> int:
|
|
|
4676
4693
|
_UNKNOWN_CTX_COMPACT_AT = 24000
|
|
4677
4694
|
|
|
4678
4695
|
|
|
4679
|
-
def
|
|
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:
|
|
4680
4727
|
"""Prompt tokens at which older steps get compacted.
|
|
4681
4728
|
|
|
4682
4729
|
Two thirds of the window: late enough that a normal turn never trips it, early enough that
|
|
@@ -4691,10 +4738,14 @@ def _compact_threshold(context_window: int) -> int:
|
|
|
4691
4738
|
the fix (GONEXT_CODING_CONTEXT_WINDOW) is discoverable instead of buried in a log.
|
|
4692
4739
|
|
|
4693
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.
|
|
4694
4743
|
"""
|
|
4695
4744
|
if context_window and context_window > 4096:
|
|
4696
|
-
|
|
4697
|
-
|
|
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
|
|
4698
4749
|
|
|
4699
4750
|
|
|
4700
4751
|
def _is_billing_failure(err) -> bool:
|
|
@@ -6814,14 +6865,15 @@ def _same_embed_model(a: str, b: str) -> bool:
|
|
|
6814
6865
|
_RUNTOOL_PREFIX = "__RUNTOOL__::"
|
|
6815
6866
|
|
|
6816
6867
|
|
|
6817
|
-
def _fmt_call(
|
|
6818
|
-
"""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)."""
|
|
6819
6871
|
parts = []
|
|
6820
6872
|
for k, v in kw.items():
|
|
6821
6873
|
if v is None or v == "" or (isinstance(v, int) and not isinstance(v, bool) and v == 0):
|
|
6822
6874
|
continue
|
|
6823
6875
|
parts.append(f"{k}={json.dumps(v)}" if isinstance(v, str) else f"{k}={v}")
|
|
6824
|
-
return f"{
|
|
6876
|
+
return f"{_tool}({', '.join(parts)})"
|
|
6825
6877
|
|
|
6826
6878
|
|
|
6827
6879
|
def _emit_running(label: str, detail: str) -> None:
|
|
@@ -7539,7 +7591,7 @@ def _rag_resolve_embed_api_key(api_base: str, worker_key: str, job_id: str = "")
|
|
|
7539
7591
|
from urllib.parse import urlencode
|
|
7540
7592
|
req = urllib.request.Request(
|
|
7541
7593
|
f"{base}/api/worker/coding-key?{urlencode({'role': 'embed', 'backendId': 'embed-ollama', **({'jobId': job_id} if job_id else {})})}",
|
|
7542
|
-
headers={"X-Worker-Key": worker_key}, method="GET")
|
|
7594
|
+
headers={"X-Worker-Key": worker_key, "User-Agent": _GU_UA}, method="GET")
|
|
7543
7595
|
with urllib.request.urlopen(req, timeout=8, context=_ssl_context()) as resp:
|
|
7544
7596
|
data = json.loads(resp.read().decode("utf-8", "replace") or "{}")
|
|
7545
7597
|
return (data.get("apiKey") or "").strip()
|
|
@@ -8008,6 +8060,131 @@ def _stray_script_char(code: str, filename: str = ""):
|
|
|
8008
8060
|
return None
|
|
8009
8061
|
|
|
8010
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
|
+
|
|
8011
8188
|
def _write_sanity_error(path: str, content: str):
|
|
8012
8189
|
"""Why this write should NOT be reported as a success, or None if it is fine.
|
|
8013
8190
|
|
|
@@ -8123,6 +8300,86 @@ def _ws_backup_root() -> str:
|
|
|
8123
8300
|
return root
|
|
8124
8301
|
|
|
8125
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
|
+
|
|
8126
8383
|
def _ws_snapshot(path: str) -> str:
|
|
8127
8384
|
"""Copy the file to the run's backup dir before its FIRST edit in this run, so
|
|
8128
8385
|
every change is revertible. Returns the backup path ('' if new file)."""
|
|
@@ -8134,7 +8391,7 @@ def _ws_snapshot(path: str) -> str:
|
|
|
8134
8391
|
if c["path"] == path and c.get("backup"):
|
|
8135
8392
|
return c["backup"]
|
|
8136
8393
|
root = _ws_backup_root()
|
|
8137
|
-
dest =
|
|
8394
|
+
dest = _ws_backup_dest(root, path)
|
|
8138
8395
|
os.makedirs(os.path.dirname(dest), exist_ok=True)
|
|
8139
8396
|
shutil.copy2(path, dest)
|
|
8140
8397
|
return dest
|
|
@@ -10128,6 +10385,9 @@ def _ws_request_approval(api_base, worker_key, job_id, command, reason, deadline
|
|
|
10128
10385
|
_emit({"type": "step", "text": "Awaiting your choice: set up S3, or save on this computer?"})
|
|
10129
10386
|
elif command.startswith("__BROWSER__::"):
|
|
10130
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"})
|
|
10131
10391
|
elif command.startswith("__MCPTOOL__::"):
|
|
10132
10392
|
_srv, _, _rest = command[len("__MCPTOOL__::"):].partition("\t")
|
|
10133
10393
|
_emit({"type": "step", "text": f"Awaiting your approval: MCP tool {_srv}/{_rest.split(chr(9))[0]}"})
|
|
@@ -10216,10 +10476,21 @@ _INFLIGHT_CMDS: set = set()
|
|
|
10216
10476
|
_STOP = {"writing": 0, "requested": False}
|
|
10217
10477
|
|
|
10218
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
|
+
|
|
10219
10485
|
def _stop_now():
|
|
10220
10486
|
for pid in list(_INFLIGHT_CMDS):
|
|
10221
10487
|
_ws_kill_tree(pid, force=True)
|
|
10222
10488
|
_INFLIGHT_CMDS.clear()
|
|
10489
|
+
for _fn in list(_ON_STOP):
|
|
10490
|
+
try:
|
|
10491
|
+
_fn()
|
|
10492
|
+
except Exception: # noqa: BLE001
|
|
10493
|
+
pass
|
|
10223
10494
|
try:
|
|
10224
10495
|
_log("stopped by the worker — killed the command in flight")
|
|
10225
10496
|
except Exception: # noqa: BLE001
|
|
@@ -11484,6 +11755,19 @@ def run_agent_chat(cfg):
|
|
|
11484
11755
|
# risky command and asks the user via the API instead of hard-blocking it.
|
|
11485
11756
|
_job_id = (cfg.get("jobId") or "").strip()
|
|
11486
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)
|
|
11487
11771
|
# Skills and MCP servers (task #269). The worker scans ~/.gonext/skills, ~/.gonext/mcp.json and
|
|
11488
11772
|
# this folder's .gonext/skills + .mcp.json for every turn; none present = neither appears
|
|
11489
11773
|
# anywhere in the prompt. Names only here — a skill's body is read when it is used.
|
|
@@ -12850,6 +13134,12 @@ def run_agent_chat(cfg):
|
|
|
12850
13134
|
# drops the whole entry: after an edit the line numbers mean something else, and a stale
|
|
12851
13135
|
# range would refuse a read the model genuinely needs.
|
|
12852
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 = []
|
|
12853
13143
|
|
|
12854
13144
|
def _server_log_tail_for_url(url: str) -> str:
|
|
12855
13145
|
"""If `url` is a localhost server we started via run_command, return the tail of
|
|
@@ -12906,12 +13196,12 @@ def run_agent_chat(cfg):
|
|
|
12906
13196
|
"""
|
|
12907
13197
|
prev = _read_ranges.get(rp)
|
|
12908
13198
|
if not prev or prev[0] != mt:
|
|
12909
|
-
|
|
13199
|
+
_pending_ranges.append((rp, mt, s, e))
|
|
12910
13200
|
return ""
|
|
12911
13201
|
served = prev[1]
|
|
12912
13202
|
hit = _range_is_covered(served, s, e)
|
|
12913
13203
|
if hit is None:
|
|
12914
|
-
|
|
13204
|
+
_pending_ranges.append((rp, mt, s, e))
|
|
12915
13205
|
return ""
|
|
12916
13206
|
import os as _os3
|
|
12917
13207
|
name = _os3.path.basename(rp)
|
|
@@ -12921,6 +13211,23 @@ def run_agent_chat(cfg):
|
|
|
12921
13211
|
f"on it instead of re-reading. If you need something you have NOT seen, read a "
|
|
12922
13212
|
f"different range (the file has {total} lines) or narrow it down with grep_repo.")
|
|
12923
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
|
+
|
|
12924
13231
|
def _dedup(tool_name: str, arg: str, next_hint: str):
|
|
12925
13232
|
"""Return (is_repeat, message). On a repeat, message steers the model forward."""
|
|
12926
13233
|
key = _norm_query(arg) if tool_name == "web_search" else (arg or "").strip().lower()
|
|
@@ -13484,7 +13791,7 @@ def run_agent_chat(cfg):
|
|
|
13484
13791
|
if not _CLOUD_LIMITS["loaded"]:
|
|
13485
13792
|
_fetch_cloud_limits(worker_api_base)
|
|
13486
13793
|
_ctx_window = _model_context_window(coding_base_url, coding_model_id, coding_api_key)
|
|
13487
|
-
_compact_at = _compact_threshold(_ctx_window)
|
|
13794
|
+
_compact_at = _compact_threshold(_ctx_window, _autocompact_cap(coding_model_id))
|
|
13488
13795
|
_caps = _set_obs_caps(_ctx_window)
|
|
13489
13796
|
_log(f"read caps: {_caps['read']} chars / {_caps['lines']} lines per read, {_caps['search']} chars "
|
|
13490
13797
|
f"per search — for a {_ctx_window or 'unknown'}-token window (issues #49, #105)")
|
|
@@ -13660,6 +13967,21 @@ def run_agent_chat(cfg):
|
|
|
13660
13967
|
except Exception as e: # noqa: BLE001
|
|
13661
13968
|
_log(f"browser screenshot attach skip: {e}")
|
|
13662
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
|
+
|
|
13663
13985
|
# A background shell that finished during this step is told to the model now (#362).
|
|
13664
13986
|
try:
|
|
13665
13987
|
_obs_now = getattr(step_log, "observations", None)
|
|
@@ -16249,6 +16571,25 @@ def run_agent_chat(cfg):
|
|
|
16249
16571
|
_last_obs["text"] = msg
|
|
16250
16572
|
return msg
|
|
16251
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
|
+
|
|
16252
16593
|
@tool
|
|
16253
16594
|
def symbol_context(name: str, path: str = "") -> str:
|
|
16254
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.
|
|
@@ -16430,6 +16771,7 @@ def run_agent_chat(cfg):
|
|
|
16430
16771
|
range(max(1, s - 2), min(len(lines), s + len(new_lines) + 1) + 1))
|
|
16431
16772
|
out = (f"Replaced lines {s}-{e} of {rp} with {len(new_lines)} line(s). "
|
|
16432
16773
|
f"Backup saved. Updated region:\n{shown}")
|
|
16774
|
+
out += _lsp_after_write(rp, "".join(lines), [s, s + max(0, len(new_lines) - 1)])
|
|
16433
16775
|
_last_obs["text"] = out
|
|
16434
16776
|
return out
|
|
16435
16777
|
except Exception as ex: # noqa: BLE001
|
|
@@ -16477,6 +16819,8 @@ def run_agent_chat(cfg):
|
|
|
16477
16819
|
added=[(start_no + i, t) for i, t in enumerate(new_ls)],
|
|
16478
16820
|
)})
|
|
16479
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)])
|
|
16480
16824
|
_last_obs["text"] = out
|
|
16481
16825
|
return out
|
|
16482
16826
|
except Exception as ex: # noqa: BLE001
|
|
@@ -16541,6 +16885,7 @@ def run_agent_chat(cfg):
|
|
|
16541
16885
|
)})
|
|
16542
16886
|
_seen.add(_ch) # remember this content so a later revert-to-it is caught
|
|
16543
16887
|
out = f"{'Overwrote' if existed else 'Created'} {rp} ({len(content)} chars)."
|
|
16888
|
+
out += _lsp_after_write(rp, content, None)
|
|
16544
16889
|
_last_obs["text"] = out
|
|
16545
16890
|
return out
|
|
16546
16891
|
except Exception as ex: # noqa: BLE001
|
|
@@ -16676,6 +17021,16 @@ def run_agent_chat(cfg):
|
|
|
16676
17021
|
msg = "Error: empty command."
|
|
16677
17022
|
_last_obs["text"] = msg
|
|
16678
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
|
|
16679
17034
|
# AN `&&` CHAIN IS ONE STEP (task #274): each part runs through THIS function —
|
|
16680
17035
|
# allowlist, risk gate, approval, server detection, all of it — in order, and
|
|
16681
17036
|
# the first failure stops the rest. `cd DIR` sets the folder for what follows.
|
|
@@ -17437,6 +17792,48 @@ def run_agent_chat(cfg):
|
|
|
17437
17792
|
# (Allow once / Always in this folder / No), unless this folder is on the "always" list in
|
|
17438
17793
|
# ~/.gonext/browser-allow.json. A "No" holds for the rest of the turn.
|
|
17439
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.")
|
|
17440
17837
|
|
|
17441
17838
|
def _browser_ask(what: str):
|
|
17442
17839
|
"""→ "" when the browser may be used, else the message for the model."""
|
|
@@ -17466,16 +17863,17 @@ def run_agent_chat(cfg):
|
|
|
17466
17863
|
def browser(action: str, url: str = "", ref: int = 0, x: int = -1, y: int = -1,
|
|
17467
17864
|
text: str = "", clear: bool = False, submit: bool = False,
|
|
17468
17865
|
direction: str = "", amount: int = 0, seconds: int = 0, tab: str = "",
|
|
17469
|
-
new_tab: bool = False, focus: bool = False
|
|
17866
|
+
new_tab: bool = False, focus: bool = False, failed: bool = False, body: bool = False,
|
|
17867
|
+
path: str = "") -> str:
|
|
17470
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).
|
|
17471
17869
|
|
|
17472
17870
|
Args:
|
|
17473
|
-
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
|
|
17474
17872
|
url: for open — a full http(s):// or file:// url (localhost:3000 is taken as http://localhost:3000)
|
|
17475
17873
|
ref: an element's [n] from the last read, for click/hover/type
|
|
17476
17874
|
x: page x coordinate for click/hover (from read's @x,y or the screenshot), when no ref
|
|
17477
17875
|
y: page y coordinate, with x
|
|
17478
|
-
text: what to type (type), the key(s) to press (key),
|
|
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/")
|
|
17479
17877
|
clear: type only — replace the field's current value instead of adding to it
|
|
17480
17878
|
submit: type only — press Enter after typing
|
|
17481
17879
|
direction: scroll only — down (default), up, left or right
|
|
@@ -17484,9 +17882,20 @@ def run_agent_chat(cfg):
|
|
|
17484
17882
|
tab: switch only — a tab id from tabs (a number, or an id like "8F3A…" in gu's own window)
|
|
17485
17883
|
new_tab: open only — open in a new tab instead of the current gu tab
|
|
17486
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)
|
|
17487
17888
|
"""
|
|
17488
17889
|
import gu_browser as _gb
|
|
17489
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
|
|
17490
17899
|
try:
|
|
17491
17900
|
cmd = {"action": a}
|
|
17492
17901
|
if url:
|
|
@@ -17502,7 +17911,8 @@ def run_agent_chat(cfg):
|
|
|
17502
17911
|
cmd["x"], cmd["y"] = float(x), float(y)
|
|
17503
17912
|
if text:
|
|
17504
17913
|
cmd["text"] = str(text)
|
|
17505
|
-
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)):
|
|
17506
17916
|
if v:
|
|
17507
17917
|
cmd[k] = True
|
|
17508
17918
|
if direction:
|
|
@@ -17513,10 +17923,30 @@ def run_agent_chat(cfg):
|
|
|
17513
17923
|
cmd["seconds"] = int(seconds)
|
|
17514
17924
|
if tab:
|
|
17515
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
|
|
17516
17932
|
shot_ok = a == "screenshot" and (
|
|
17517
17933
|
_is_anthropic_url(coding_base_url) or _coder_takes_images(coding_base_url, coding_model_id))
|
|
17518
17934
|
if a == "screenshot" and not shot_ok:
|
|
17519
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
|
|
17520
17950
|
what = cmd.get("url") or (f"[{ref}]" if ref else f"{int(x)},{int(y)}" if "x" in cmd else
|
|
17521
17951
|
_clip(str(text), 50) if text else "")
|
|
17522
17952
|
_emit({"type": "step", "text": f"Browser {a}" + (f" → {what}" if what else "")})
|
|
@@ -17535,6 +17965,12 @@ def run_agent_chat(cfg):
|
|
|
17535
17965
|
cmd, log=_log, own=_gb.own_allowed(),
|
|
17536
17966
|
on_wait=lambda: _emit({"type": "step", "text": "Waiting for Chrome to connect…"}))
|
|
17537
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
|
|
17538
17974
|
if where and where != _browser_consent["where"]:
|
|
17539
17975
|
_browser_consent["where"] = where
|
|
17540
17976
|
_emit({"type": "step", "text": "Using gu's own Chrome window" if where == "chrome"
|
|
@@ -17569,6 +18005,11 @@ def run_agent_chat(cfg):
|
|
|
17569
18005
|
+ "\n--- the page now (no need to read again) ---\n" + _gb.format_read(res2)
|
|
17570
18006
|
except Exception: # noqa: BLE001
|
|
17571
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)
|
|
17572
18013
|
if ok and where == "chrome" and a == "open":
|
|
17573
18014
|
msg = ("(NO gu extension is connected, so this is gu's own Chrome window — a separate "
|
|
17574
18015
|
"profile, NOT signed in to the user's accounts. Say so if it matters to the task.)\n" + msg)
|
|
@@ -17599,6 +18040,10 @@ def run_agent_chat(cfg):
|
|
|
17599
18040
|
agent_tools += [symbol_context, grep_repo, read_file_lines, edit_lines, edit_file,
|
|
17600
18041
|
create_file, create_folder, run_command, stop_server,
|
|
17601
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)
|
|
17602
18047
|
if _browser_on():
|
|
17603
18048
|
agent_tools.append(browser)
|
|
17604
18049
|
# Workspace RAG (task #133): semantic search over the PROJECT itself, not just a
|
|
@@ -17618,6 +18063,8 @@ def run_agent_chat(cfg):
|
|
|
17618
18063
|
# READ-ONLY BY CONSTRUCTION: its tool list has no edit, write, command or network
|
|
17619
18064
|
# tool, so it cannot change anything whatever the text says.
|
|
17620
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
|
|
17621
18068
|
if _RAG_AVAILABLE:
|
|
17622
18069
|
_explore_tools.append(rag_search_workspace)
|
|
17623
18070
|
|
|
@@ -17971,6 +18418,12 @@ def run_agent_chat(cfg):
|
|
|
17971
18418
|
or _fallback_recap(_turn_steps, _last_obs.get("text"))
|
|
17972
18419
|
or "[No result]")
|
|
17973
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}")
|
|
17974
18427
|
# GH #428: close the Chrome tabs gu opened this turn (shared tabs are only let go of).
|
|
17975
18428
|
try:
|
|
17976
18429
|
if _browser_consent.get("ok"):
|