@tiens.nguyen/gu-cli 1.0.932 → 1.0.936
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/cli-token.mjs +6 -3
- package/client-expert-api.mjs +4 -0
- package/client-expert-run.mjs +84 -0
- package/coding-provider-setup.mjs +27 -0
- package/free-model.mjs +33 -6
- package/gonext_agent_chat.py +298 -13
- package/gu-cli.mjs +46 -0
- package/gu-repl.mjs +137 -5
- package/gu_turn_notes.py +29 -2
- package/model-doctor.mjs +29 -5
- package/model-prices.mjs +22 -0
- package/package.json +2 -1
- package/python-unix.mjs +120 -0
- package/setup-fixes.mjs +6 -1
- package/turn-notes.mjs +65 -0
package/gonext_agent_chat.py
CHANGED
|
@@ -30,7 +30,7 @@ import os
|
|
|
30
30
|
import random
|
|
31
31
|
import re
|
|
32
32
|
import socket
|
|
33
|
-
from urllib.parse import urlparse
|
|
33
|
+
from urllib.parse import unquote, urlparse
|
|
34
34
|
import sys
|
|
35
35
|
import threading
|
|
36
36
|
import time
|
|
@@ -3418,6 +3418,9 @@ _DEEPSEEK_THINKING_HOSTS = frozenset({
|
|
|
3418
3418
|
})
|
|
3419
3419
|
|
|
3420
3420
|
|
|
3421
|
+
_OPENROUTER_HOST = "openrouter.ai"
|
|
3422
|
+
|
|
3423
|
+
|
|
3421
3424
|
def _deepseek_thinking_kwargs(model_id, base_url="", env=None) -> dict:
|
|
3422
3425
|
"""Request fields that turn DeepSeek V4's thinking OFF in the coding loop (GH #430), or {}.
|
|
3423
3426
|
|
|
@@ -3434,11 +3437,14 @@ def _deepseek_thinking_kwargs(model_id, base_url="", env=None) -> dict:
|
|
|
3434
3437
|
mode = str(env.get("GONEXT_DEEPSEEK_THINKING", "")).strip().lower()
|
|
3435
3438
|
if mode in ("on", "1", "true", "yes"):
|
|
3436
3439
|
return {}
|
|
3437
|
-
|
|
3438
|
-
|
|
3439
|
-
|
|
3440
|
-
|
|
3441
|
-
|
|
3440
|
+
from urllib.parse import urlparse
|
|
3441
|
+
host = (urlparse(str(base_url or "")).hostname or "").lower().rstrip(".")
|
|
3442
|
+
# GH #570, MEASURED 2026-12-03 (deepseek/deepseek-v4-pro): OpenRouter ignores DeepSeek's `thinking` field
|
|
3443
|
+
# (188 reasoning tokens with it, 396 without) and takes its own `reasoning` switch (0 with it).
|
|
3444
|
+
if host == _OPENROUTER_HOST:
|
|
3445
|
+
return {"extra_body": {"reasoning": {"enabled": False}}}
|
|
3446
|
+
if mode not in ("off", "0", "false", "no") and host not in _DEEPSEEK_THINKING_HOSTS:
|
|
3447
|
+
return {}
|
|
3442
3448
|
return {"extra_body": {"thinking": {"type": "disabled"}}}
|
|
3443
3449
|
|
|
3444
3450
|
|
|
@@ -11597,17 +11603,63 @@ def _png_b64_len(im) -> int:
|
|
|
11597
11603
|
return (len(buf.getvalue()) + 2) // 3 * 4
|
|
11598
11604
|
|
|
11599
11605
|
|
|
11600
|
-
def
|
|
11601
|
-
"""
|
|
11606
|
+
def _parse_crop(crop):
|
|
11607
|
+
""""left,top,right,bottom" as fractions 0–1 (or percents 0–100) of the upright image → a tuple
|
|
11608
|
+
of fractions, None for no crop. Raises ValueError with what is wrong. Pure."""
|
|
11609
|
+
s = str(crop or "").strip()
|
|
11610
|
+
if not s:
|
|
11611
|
+
return None
|
|
11612
|
+
try:
|
|
11613
|
+
v = [float(x) for x in re.split(r"[,\s]+", s) if x != ""]
|
|
11614
|
+
except ValueError:
|
|
11615
|
+
raise ValueError(f"crop {crop!r}: four numbers, left,top,right,bottom (fractions 0-1)") from None
|
|
11616
|
+
if len(v) != 4:
|
|
11617
|
+
raise ValueError(f"crop {crop!r}: four numbers, left,top,right,bottom (fractions 0-1)")
|
|
11618
|
+
if max(v) > 1.0:
|
|
11619
|
+
v = [x / 100.0 for x in v] # percents
|
|
11620
|
+
l, t, r, b = [min(1.0, max(0.0, x)) for x in v]
|
|
11621
|
+
if r - l < 0.02 or b - t < 0.02:
|
|
11622
|
+
raise ValueError(f"crop {crop!r}: right must be more than left, bottom more than top")
|
|
11623
|
+
return (l, t, r, b)
|
|
11624
|
+
|
|
11625
|
+
|
|
11626
|
+
def _prepare_image(path, rotate=0, crop=None, info=None):
|
|
11627
|
+
"""Open `path` and return a PIL image Claude will accept, or raise ValueError(reason).
|
|
11628
|
+
|
|
11629
|
+
GH #559 — what Claude Code did with sips on the owner's phone photo: turn it upright, then cut
|
|
11630
|
+
out the table so its small text survives. `rotate` = degrees CLOCKWISE (90/180/270), after the
|
|
11631
|
+
photo's own EXIF turn; `crop` = (left, top, right, bottom) fractions of that upright picture
|
|
11632
|
+
(see _parse_crop). Both act on the FULL-resolution picture, before the shrink to 1568 px — a
|
|
11633
|
+
crop is a zoom. `info` (a dict) gets the full size and the region sent."""
|
|
11602
11634
|
from PIL import Image
|
|
11603
11635
|
try:
|
|
11604
11636
|
with Image.open(path) as src:
|
|
11605
11637
|
src.load() # a truncated or non-image file fails here, not later in the request
|
|
11606
11638
|
im = src.copy()
|
|
11639
|
+
try:
|
|
11640
|
+
# A phone photo is stored sideways with an EXIF "rotate me" tag; the copy drops
|
|
11641
|
+
# the tag, so the model would read the text on its side (GH #559).
|
|
11642
|
+
from PIL import ImageOps
|
|
11643
|
+
im = ImageOps.exif_transpose(src) or im
|
|
11644
|
+
except Exception: # noqa: BLE001
|
|
11645
|
+
pass
|
|
11607
11646
|
except Image.DecompressionBombError:
|
|
11608
11647
|
raise ValueError("too many pixels to open safely") from None
|
|
11609
11648
|
except Exception as e: # noqa: BLE001
|
|
11610
11649
|
raise ValueError(f"not a readable image ({type(e).__name__})") from None
|
|
11650
|
+
rot = int(rotate or 0) % 360
|
|
11651
|
+
if rot not in (0, 90, 180, 270):
|
|
11652
|
+
raise ValueError(f"rotate {rotate!r}: use 90, 180 or 270 (degrees clockwise)")
|
|
11653
|
+
if rot:
|
|
11654
|
+
im = im.rotate(-rot, expand=True)
|
|
11655
|
+
full = im.size
|
|
11656
|
+
if crop:
|
|
11657
|
+
l, t, r, b = crop
|
|
11658
|
+
box = (int(l * im.width), int(t * im.height), max(int(l * im.width) + 1, int(r * im.width)),
|
|
11659
|
+
max(int(t * im.height) + 1, int(b * im.height)))
|
|
11660
|
+
im = im.crop(box)
|
|
11661
|
+
if info is not None:
|
|
11662
|
+
info.update(full=full, region=im.size)
|
|
11611
11663
|
# Colour modes PNG cannot hold, or holds oddly: CMYK photos, 16-bit, float, palette.
|
|
11612
11664
|
if im.mode == "P":
|
|
11613
11665
|
im = im.convert("RGBA" if "transparency" in im.info else "RGB")
|
|
@@ -11685,6 +11737,92 @@ def _load_turn_images(refs):
|
|
|
11685
11737
|
return out, failed
|
|
11686
11738
|
|
|
11687
11739
|
|
|
11740
|
+
# AN IMAGE FILE IN THE PROJECT (GH #559). Claude Code's Read gives the model the picture itself.
|
|
11741
|
+
# gu had no way to: asked about a photo in the folder, the agent opened it in the browser, read it
|
|
11742
|
+
# as text (EXIF only), then brew-installed tesseract and tesseract-lang — minutes, and the model
|
|
11743
|
+
# never saw it. view_image gives the picture to a model that can see it: the coder itself when it
|
|
11744
|
+
# takes images, else the talking (agent) model reads it once and returns what it shows.
|
|
11745
|
+
_IMAGE_READ_TIMEOUT_S = 90
|
|
11746
|
+
_MAX_STEP_IMAGES = 4 # pictures attached to one step (view_image + screenshots)
|
|
11747
|
+
_IMAGE_FILE_EXTS = (".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tif", ".tiff")
|
|
11748
|
+
|
|
11749
|
+
|
|
11750
|
+
def _is_image_path(path) -> bool:
|
|
11751
|
+
return os.path.splitext(str(path or ""))[1].lower() in _IMAGE_FILE_EXTS
|
|
11752
|
+
|
|
11753
|
+
|
|
11754
|
+
def _image_not_text_msg(path) -> str:
|
|
11755
|
+
"""What a text reader says when it is handed a picture, instead of its bytes as text."""
|
|
11756
|
+
return (f"{path} is an image file, not text. Call view_image(path={str(path)!r}) to see it "
|
|
11757
|
+
"(add question=... for what to look for). Do not open it in the browser and do not "
|
|
11758
|
+
"install OCR software.")
|
|
11759
|
+
|
|
11760
|
+
|
|
11761
|
+
_IMAGE_READ_PROMPT = (
|
|
11762
|
+
"Read this image for another assistant who cannot see it. First write out ALL the text in it, "
|
|
11763
|
+
"exactly as written — keep the original language, accents, spelling, numbers, account numbers, "
|
|
11764
|
+
"amounts and dates; keep rows and columns together (a table as lines of `cell | cell`). Then, "
|
|
11765
|
+
"in a few lines, say what the image is and how it is laid out. Mark anything you cannot read "
|
|
11766
|
+
"as [unreadable] rather than guessing.")
|
|
11767
|
+
|
|
11768
|
+
|
|
11769
|
+
def _image_data_url(im) -> str:
|
|
11770
|
+
"""A PIL image → a data: URL (JPEG for photos — a fraction of PNG's bytes; PNG with alpha)."""
|
|
11771
|
+
import base64
|
|
11772
|
+
import io
|
|
11773
|
+
buf = io.BytesIO()
|
|
11774
|
+
if im.mode in ("RGBA", "LA"):
|
|
11775
|
+
im.save(buf, format="PNG")
|
|
11776
|
+
kind = "png"
|
|
11777
|
+
else:
|
|
11778
|
+
im.convert("RGB").save(buf, format="JPEG", quality=90)
|
|
11779
|
+
kind = "jpeg"
|
|
11780
|
+
return f"data:image/{kind};base64," + base64.b64encode(buf.getvalue()).decode("ascii")
|
|
11781
|
+
|
|
11782
|
+
|
|
11783
|
+
def _read_image_with_model(im, base_url, api_key, model_id, question="", client_factory=None) -> str:
|
|
11784
|
+
"""Ask a model that can see images to read `im` → its text. Raises on failure or an empty reply."""
|
|
11785
|
+
prompt = _IMAGE_READ_PROMPT + (f"\n\nAlso answer, from the image only: {question.strip()}" if (question or "").strip() else "")
|
|
11786
|
+
if client_factory is None:
|
|
11787
|
+
from openai import OpenAI
|
|
11788
|
+
|
|
11789
|
+
def client_factory():
|
|
11790
|
+
# 90 s, no retry: the coder waits on this with nothing new on screen. Up to 6 minutes
|
|
11791
|
+
# (180 s x 2) looked like a hang (GH #559 review).
|
|
11792
|
+
return OpenAI(base_url=base_url, api_key=api_key or "local",
|
|
11793
|
+
http_client=_proxy_http_client(base_url), max_retries=0,
|
|
11794
|
+
timeout=_IMAGE_READ_TIMEOUT_S)
|
|
11795
|
+
# Through _create_with_repair: counted in the turn's other-calls tokens (and so charged to a free
|
|
11796
|
+
# model's allowance, GH #501) — a direct create() was missed (GH #559 review) — and a request
|
|
11797
|
+
# shape the host refuses is fixed and retried like every other call.
|
|
11798
|
+
resp = _create_with_repair(
|
|
11799
|
+
client_factory(),
|
|
11800
|
+
model=model_id,
|
|
11801
|
+
messages=[{"role": "user", "content": [
|
|
11802
|
+
{"type": "text", "text": prompt},
|
|
11803
|
+
{"type": "image_url", "image_url": {"url": _image_data_url(im)}},
|
|
11804
|
+
]}],
|
|
11805
|
+
temperature=0,
|
|
11806
|
+
max_tokens=3000,
|
|
11807
|
+
)
|
|
11808
|
+
text = ((resp.choices[0].message.content if resp and resp.choices else "") or "").strip()
|
|
11809
|
+
text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL | re.IGNORECASE).strip()
|
|
11810
|
+
if not text:
|
|
11811
|
+
raise RuntimeError(f"{model_id} returned no text for the image")
|
|
11812
|
+
return text
|
|
11813
|
+
|
|
11814
|
+
|
|
11815
|
+
def _image_route(coder, agent, takes=None) -> str:
|
|
11816
|
+
"""Who sees a project image: "coder" (attached to the step), "agent" (it reads it and the coder
|
|
11817
|
+
gets the text), or "" (no model here can). coder/agent = (base_url, model_id). Pure but for `takes`."""
|
|
11818
|
+
takes = takes or (lambda b, m: _is_anthropic_url(b) or _coder_takes_images(b, m))
|
|
11819
|
+
if coder[0] and coder[1] and takes(*coder):
|
|
11820
|
+
return "coder"
|
|
11821
|
+
if agent[0] and agent[1] and tuple(agent) != tuple(coder) and takes(*agent):
|
|
11822
|
+
return "agent"
|
|
11823
|
+
return ""
|
|
11824
|
+
|
|
11825
|
+
|
|
11688
11826
|
def _label_failed_images(text, failed):
|
|
11689
11827
|
"""Say which images did not make it, where the model reads their labels — a bare
|
|
11690
11828
|
"[Image #1]" with nothing attached invites the model to guess what it shows."""
|
|
@@ -11754,6 +11892,16 @@ def run_agent_chat(cfg):
|
|
|
11754
11892
|
# REPL) can show a Yes/No picker. When both are present, run_command PAUSES on a
|
|
11755
11893
|
# risky command and asks the user via the API instead of hard-blocking it.
|
|
11756
11894
|
_job_id = (cfg.get("jobId") or "").strip()
|
|
11895
|
+
|
|
11896
|
+
def _send_now_requested() -> bool:
|
|
11897
|
+
"""GH #560: Ctrl+X Ctrl+S in gu — a waited-on command gives way to the user's message."""
|
|
11898
|
+
if not _job_id:
|
|
11899
|
+
return False
|
|
11900
|
+
try:
|
|
11901
|
+
import gu_turn_notes as _tn
|
|
11902
|
+
return _tn.send_now_requested(_job_id)
|
|
11903
|
+
except Exception: # noqa: BLE001
|
|
11904
|
+
return False
|
|
11757
11905
|
_interactive_approval = bool(cfg.get("interactiveApproval"))
|
|
11758
11906
|
# GH #540: the worker's language-server host — {url, token, exts}, or None (web, remote, older
|
|
11759
11907
|
# worker). After every write the agent asks it for the file's errors; see _lsp_after_write.
|
|
@@ -13948,7 +14096,9 @@ def run_agent_chat(cfg):
|
|
|
13948
14096
|
saved += _trim_tool_call_args(_st, 120)
|
|
13949
14097
|
return saved
|
|
13950
14098
|
|
|
13951
|
-
|
|
14099
|
+
# The pictures this step's tools took — browser screenshots (#363) and view_image (GH #559). A
|
|
14100
|
+
# LIST: one slot kept only the last, while every earlier call still said "attached" (GH #559 review).
|
|
14101
|
+
_browser_shot = {"imgs": []}
|
|
13952
14102
|
|
|
13953
14103
|
def step_callback(step_log):
|
|
13954
14104
|
step_num = getattr(step_log, "step_number", "?")
|
|
@@ -13957,9 +14107,9 @@ def run_agent_chat(cfg):
|
|
|
13957
14107
|
# observation (#363). Only the newest two stay in memory: every image is re-sent on every
|
|
13958
14108
|
# later step, and an old view of a page that has since changed only misleads.
|
|
13959
14109
|
try:
|
|
13960
|
-
if _browser_shot.get("
|
|
13961
|
-
step_log.observations_images =
|
|
13962
|
-
_browser_shot["
|
|
14110
|
+
if _browser_shot.get("imgs"):
|
|
14111
|
+
step_log.observations_images = list(_browser_shot["imgs"])
|
|
14112
|
+
_browser_shot["imgs"] = []
|
|
13963
14113
|
_with = [s for s in (getattr(getattr(_agent_ref.get("a"), "memory", None), "steps", None) or [])
|
|
13964
14114
|
if getattr(s, "observations_images", None) and s is not step_log]
|
|
13965
14115
|
for _old in _with[:-1]:
|
|
@@ -15866,6 +16016,11 @@ def run_agent_chat(cfg):
|
|
|
15866
16016
|
_emit_read("Reading file", path, "failed: no such file")
|
|
15867
16017
|
_last_obs["text"] = msg
|
|
15868
16018
|
return msg
|
|
16019
|
+
if _is_image_path(rp):
|
|
16020
|
+
msg = _image_not_text_msg(path) # GH #559: a picture, not its bytes as text
|
|
16021
|
+
_emit_read("Reading file", path, "an image — use view_image")
|
|
16022
|
+
_last_obs["text"] = msg
|
|
16023
|
+
return msg
|
|
15869
16024
|
if os.path.getsize(rp) > 5 * 1024 * 1024:
|
|
15870
16025
|
msg = "Error: file too large to read (> 5 MB)."
|
|
15871
16026
|
_emit_read("Reading file", path, "failed: larger than 5 MB")
|
|
@@ -15889,6 +16044,106 @@ def run_agent_chat(cfg):
|
|
|
15889
16044
|
_last_obs["text"] = msg
|
|
15890
16045
|
return msg
|
|
15891
16046
|
|
|
16047
|
+
@tool
|
|
16048
|
+
def say(text: str) -> str:
|
|
16049
|
+
"""Tell the user one short line NOW, while you keep working — e.g. to answer a note they typed during the turn ("Noted: I'll add the test after this fix."). Does not end the turn; it is not the final answer.
|
|
16050
|
+
|
|
16051
|
+
Args:
|
|
16052
|
+
text: one short line, at most about 200 characters.
|
|
16053
|
+
"""
|
|
16054
|
+
# GH #562: printed by gu as normal text under the user's message, between the steps.
|
|
16055
|
+
line = " ".join(str(text or "").split())[:300]
|
|
16056
|
+
if not line:
|
|
16057
|
+
return "Nothing said: the text was empty."
|
|
16058
|
+
_emit({"type": "step", "text": f"__SAY__::{line}"})
|
|
16059
|
+
_log("said one line to the user")
|
|
16060
|
+
return "Said. Go on with the task."
|
|
16061
|
+
|
|
16062
|
+
@tool
|
|
16063
|
+
def view_image(path: str, question: str = "", rotate: int = 0, crop: str = "") -> str:
|
|
16064
|
+
"""Look at an image file (png, jpg, jpeg, gif, webp, bmp, tiff) — a photo, screenshot or scan in the project. Use this for ANY picture: never open a local image in the browser, never read it as text, never install OCR or image software. If the picture is sideways, call again with rotate. If text is small or blurry, call again with crop to zoom into that part (a crop keeps the full resolution).
|
|
16065
|
+
|
|
16066
|
+
Args:
|
|
16067
|
+
path: the image file's path.
|
|
16068
|
+
question: optional — what to look for or read in it (e.g. "the bank account numbers").
|
|
16069
|
+
rotate: optional — turn it clockwise by 90, 180 or 270 degrees first (for a sideways photo).
|
|
16070
|
+
crop: optional — "left,top,right,bottom" as fractions 0-1 of the upright picture, e.g. "0.5,0,1,0.4" = the top-right part.
|
|
16071
|
+
"""
|
|
16072
|
+
try:
|
|
16073
|
+
import os
|
|
16074
|
+
rp = _rag_read_allowed((path or "").strip())
|
|
16075
|
+
if not os.path.isfile(rp):
|
|
16076
|
+
msg = f"Error: not a file: {path}"
|
|
16077
|
+
_emit_read("Viewing image", path, "failed: no such file")
|
|
16078
|
+
_last_obs["text"] = msg
|
|
16079
|
+
return msg
|
|
16080
|
+
if not _is_image_path(rp):
|
|
16081
|
+
msg = f"Error: {path} is not an image file ({', '.join(_IMAGE_FILE_EXTS)}). Read it with read_text_file."
|
|
16082
|
+
_emit_read("Viewing image", path, "failed: not an image")
|
|
16083
|
+
_last_obs["text"] = msg
|
|
16084
|
+
return msg
|
|
16085
|
+
route = _image_route((coding_base_url, coding_model_id), (agent_base_url, agent_model_id))
|
|
16086
|
+
if not route:
|
|
16087
|
+
msg = (f"No model set up here can see images (coder {coding_model_id or '?'}, agent "
|
|
16088
|
+
f"{agent_model_id or '?'}), so the picture cannot be read. Tell the user that in one "
|
|
16089
|
+
"line and that /model can switch to a model that sees images (Claude, Kimi K3, "
|
|
16090
|
+
"Qwen 3.6 Plus and others). Do NOT install OCR software or open the image in the browser.")
|
|
16091
|
+
_emit_read("Viewing image", path, "no model here can see images")
|
|
16092
|
+
_last_obs["text"] = msg
|
|
16093
|
+
return msg
|
|
16094
|
+
_info = {}
|
|
16095
|
+
try:
|
|
16096
|
+
im = _prepare_image(rp, rotate=rotate, crop=_parse_crop(crop), info=_info)
|
|
16097
|
+
except ValueError as e:
|
|
16098
|
+
msg = f"Error: {path} could not be opened as an image: {e}"
|
|
16099
|
+
_emit_read("Viewing image", path, f"failed: {e}")
|
|
16100
|
+
_last_obs["text"] = msg
|
|
16101
|
+
return msg
|
|
16102
|
+
_fw, _fh = _info.get("full") or im.size
|
|
16103
|
+
_what = (f"{rp} (full picture {_fw}x{_fh}"
|
|
16104
|
+
+ (f", turned {int(rotate) % 360}° clockwise" if int(rotate or 0) % 360 else "")
|
|
16105
|
+
+ (f", region {crop} = {_info['region'][0]}x{_info['region'][1]} px" if (crop or "").strip() else "")
|
|
16106
|
+
+ f", sent at {im.width}x{im.height})")
|
|
16107
|
+
_how = ("" if (crop or "").strip() else
|
|
16108
|
+
" If it is sideways, call view_image again with rotate; if text is too small, zoom in with crop.")
|
|
16109
|
+
_detail = f"{im.width}x{im.height}" + (f" · rotate {int(rotate) % 360}" if int(rotate or 0) % 360 else "") \
|
|
16110
|
+
+ (f" · crop {crop}" if (crop or "").strip() else "")
|
|
16111
|
+
if route == "coder":
|
|
16112
|
+
if len(_browser_shot["imgs"]) >= _MAX_STEP_IMAGES:
|
|
16113
|
+
msg = (f"Not attached: {_MAX_STEP_IMAGES} pictures are already attached to this step. "
|
|
16114
|
+
"Look at those first, then call view_image again in a later step.")
|
|
16115
|
+
_emit_read("Viewing image", path, "not attached — too many in one step")
|
|
16116
|
+
_last_obs["text"] = msg
|
|
16117
|
+
return msg
|
|
16118
|
+
_browser_shot["imgs"].append(im) # attached to this step, like a browser screenshot
|
|
16119
|
+
msg = f"{_what} — the image is attached to this observation. Look at it and read what it shows.{_how}"
|
|
16120
|
+
_emit_read("Viewing image", path, _detail)
|
|
16121
|
+
_last_obs["text"] = msg
|
|
16122
|
+
return msg
|
|
16123
|
+
_emit_running("Viewing image", f"{path} — {agent_model_id} reads it")
|
|
16124
|
+
try:
|
|
16125
|
+
text = _read_image_with_model(im, agent_base_url, agent_api_key, agent_model_id, question)
|
|
16126
|
+
except Exception as e: # noqa: BLE001
|
|
16127
|
+
_slow = "timeout" in type(e).__name__.lower() or "timed out" in str(e).lower()
|
|
16128
|
+
msg = (f"Error: {agent_model_id} could not read the image"
|
|
16129
|
+
+ (f" (no answer within {_IMAGE_READ_TIMEOUT_S} s)" if _slow else f" ({type(e).__name__}: {_clip(str(e), 200)})")
|
|
16130
|
+
+ ". Tell the user in one line; do NOT install OCR software or open the image in the browser.")
|
|
16131
|
+
_emit_read("Viewing image", path, "no answer in time" if _slow else f"failed: {type(e).__name__}")
|
|
16132
|
+
_last_obs["text"] = msg
|
|
16133
|
+
return msg
|
|
16134
|
+
msg = (f"{_what}, read by {agent_model_id} (the coding model "
|
|
16135
|
+
f"{coding_model_id} cannot see images):\n{text}\n(To read a part more closely, call "
|
|
16136
|
+
"view_image again with crop; if the reader says it is sideways, with rotate.)")
|
|
16137
|
+
_emit_read("Viewing image", path, f"{_detail} · read by {agent_model_id}")
|
|
16138
|
+
msg = _ws_cap_obs(msg, cap=_OBS_CAPS["read"])
|
|
16139
|
+
_last_obs["text"] = msg
|
|
16140
|
+
return msg
|
|
16141
|
+
except Exception as e: # noqa: BLE001
|
|
16142
|
+
msg = f"Error: view_image failed: {type(e).__name__}: {e}"
|
|
16143
|
+
_emit_read("Viewing image", path, f"failed: {type(e).__name__}")
|
|
16144
|
+
_last_obs["text"] = msg
|
|
16145
|
+
return msg
|
|
16146
|
+
|
|
15892
16147
|
def _rag_unavailable_msg() -> str:
|
|
15893
16148
|
"""Why RAG can't run, naming the ACTUAL missing piece (task #133).
|
|
15894
16149
|
|
|
@@ -16693,6 +16948,11 @@ def run_agent_chat(cfg):
|
|
|
16693
16948
|
start_line=int(start_line or 1),
|
|
16694
16949
|
end_line=int(end_line or 0)))
|
|
16695
16950
|
rp = _rag_read_allowed((path or "").strip())
|
|
16951
|
+
if _is_image_path(rp):
|
|
16952
|
+
msg = _image_not_text_msg(path) # GH #559
|
|
16953
|
+
_emit_read("Reading lines", path, "an image — use view_image")
|
|
16954
|
+
_last_obs["text"] = msg
|
|
16955
|
+
return msg
|
|
16696
16956
|
with _open_project_text(rp) as fh:
|
|
16697
16957
|
lines = fh.readlines()
|
|
16698
16958
|
s = max(1, int(start_line or 1))
|
|
@@ -17472,6 +17732,15 @@ def run_agent_chat(cfg):
|
|
|
17472
17732
|
msg = _to_background("started")
|
|
17473
17733
|
_last_obs["text"] = msg
|
|
17474
17734
|
return msg
|
|
17735
|
+
# GH #560: the user pressed Ctrl+X Ctrl+S ("send now") on a message typed during the
|
|
17736
|
+
# turn. Stop WAITING, not the command: it goes on as a background shell, exactly as
|
|
17737
|
+
# at the deadline below, and the step ends so the model reads the message now.
|
|
17738
|
+
if _send_now_requested():
|
|
17739
|
+
_emit({"type": "step", "text": "Your message → the agent reads it now"})
|
|
17740
|
+
msg = _to_background("moved to the background because the user sent a message "
|
|
17741
|
+
"(it follows this result) — read it before going on")
|
|
17742
|
+
_last_obs["text"] = msg
|
|
17743
|
+
return msg
|
|
17475
17744
|
# THE DEADLINE HANDS OFF, IT NO LONGER KILLS (task #360): a 7-minute build
|
|
17476
17745
|
# is the command doing its job, not a hang. The 1h turn budget and
|
|
17477
17746
|
# stop_server still bound it.
|
|
@@ -17601,6 +17870,9 @@ def run_agent_chat(cfg):
|
|
|
17601
17870
|
deadline = _t.time() + max(0, min(int(wait_seconds or 0), 540))
|
|
17602
17871
|
st = _shell_state(sh)
|
|
17603
17872
|
while st["state"] == "running" and _t.time() < deadline:
|
|
17873
|
+
if _send_now_requested(): # GH #560: stop waiting; the user's message is read next
|
|
17874
|
+
_emit({"type": "step", "text": "Your message → the agent reads it now"})
|
|
17875
|
+
break
|
|
17604
17876
|
_t.sleep(2)
|
|
17605
17877
|
st = _shell_state(sh)
|
|
17606
17878
|
try:
|
|
@@ -17923,6 +18195,14 @@ def run_agent_chat(cfg):
|
|
|
17923
18195
|
cmd["seconds"] = int(seconds)
|
|
17924
18196
|
if tab:
|
|
17925
18197
|
cmd["tab"] = int(tab) if str(tab).strip().isdigit() else str(tab).strip()
|
|
18198
|
+
_furl = str(cmd.get("url") or "")
|
|
18199
|
+
if a == "open" and (_furl.startswith("file:") or not re.match(r"^[a-z][a-z0-9+.-]*:", _furl, re.I)) \
|
|
18200
|
+
and _is_image_path(unquote(urlparse(_furl).path or _furl)):
|
|
18201
|
+
# GH #559: a picture on disk is not a web page — waking Chrome to show it took
|
|
18202
|
+
# a minute and the model still could not read it.
|
|
18203
|
+
msg = _image_not_text_msg(unquote(urlparse(_furl).path or _furl))
|
|
18204
|
+
_last_obs["text"] = msg
|
|
18205
|
+
return msg
|
|
17926
18206
|
if a == "upload":
|
|
17927
18207
|
# GH #547: only a file the agent may read anyway, and one that exists.
|
|
17928
18208
|
_up = _rag_read_allowed((path or "").strip())
|
|
@@ -17984,7 +18264,7 @@ def run_agent_chat(cfg):
|
|
|
17984
18264
|
msg = f"Error: browser {a} failed: {res}"
|
|
17985
18265
|
elif a == "screenshot" and shot_ok:
|
|
17986
18266
|
im, note = _gb.decode_screenshot(res, _IMAGE_MAX_EDGE)
|
|
17987
|
-
_browser_shot["
|
|
18267
|
+
_browser_shot["imgs"].append(im)
|
|
17988
18268
|
msg = _gb.format_result("screenshot", res) + "\n" + note + " The image is attached to this observation."
|
|
17989
18269
|
elif a == "screenshot":
|
|
17990
18270
|
msg = ("(This coding model is not sent images, so here is the page as text.)\n"
|
|
@@ -18056,6 +18336,11 @@ def run_agent_chat(cfg):
|
|
|
18056
18336
|
# (S3 indexing) isn't configured.
|
|
18057
18337
|
if not _RAG_AVAILABLE:
|
|
18058
18338
|
agent_tools += [list_dir, read_text_file]
|
|
18339
|
+
# GH #559: pictures in the project — one step to the model, like Claude Code's Read.
|
|
18340
|
+
agent_tools.insert(agent_tools.index(read_text_file) + 1, view_image)
|
|
18341
|
+
# GH #562: gu's terminal (a job id) can show a line mid-turn — the answer to a note the user typed.
|
|
18342
|
+
if _job_id:
|
|
18343
|
+
agent_tools.append(say)
|
|
18059
18344
|
|
|
18060
18345
|
# EXPLORE (task #276) — Claude Code's Explore subagent, for gu. Every grep and read
|
|
18061
18346
|
# used to land in THIS loop and be re-sent on every later step. explore() searches
|
package/gu-cli.mjs
CHANGED
|
@@ -1869,6 +1869,52 @@ if (args[0] === "deps") {
|
|
|
1869
1869
|
process.exit(ok ? 0 : 1);
|
|
1870
1870
|
}
|
|
1871
1871
|
|
|
1872
|
+
if (args[0] === "prepare") {
|
|
1873
|
+
// GH #561: the installers run this right after npm. Everything the first `gu` would install without asking
|
|
1874
|
+
// anything — Python (Windows), the agent framework, the document tools, the API, its dependencies, the database —
|
|
1875
|
+
// is done NOW, while the user expects to wait, and the API is started once as a check. Running the installer is
|
|
1876
|
+
// the agreement, so nothing is asked here (`curl | sh` may have no keyboard); every change is said (#557).
|
|
1877
|
+
// worker.env is never written: the first `gu` still asks its real questions (mode, license, promo code, models).
|
|
1878
|
+
const md = await import("./model-doctor.mjs");
|
|
1879
|
+
process.env.GU_PIP_QUIET = "1";
|
|
1880
|
+
console.log("\n Getting gu ready …");
|
|
1881
|
+
// Running the installer agrees to the agent framework and the document tools. Installing PYTHON itself is still
|
|
1882
|
+
// asked (Windows): with no keyboard (`curl | sh`) it is not installed now unless GU_INSTALL_YES=1, and the first
|
|
1883
|
+
// gu asks.
|
|
1884
|
+
const { askLine } = await import("./agent-deps-preflight.mjs");
|
|
1885
|
+
const out = await md.ensureAgentDeps({
|
|
1886
|
+
log: (l) => console.log(l),
|
|
1887
|
+
confirm: async (q, defYes = true) => {
|
|
1888
|
+
if (!process.stdin.isTTY) return process.env.GU_INSTALL_YES === "1";
|
|
1889
|
+
const typed = String(await askLine(" " + q + (defYes ? " [Y/n]: " : " [y/N]: "))).trim().toLowerCase();
|
|
1890
|
+
return typed === "" ? defYes : /^y(es)?$/.test(typed);
|
|
1891
|
+
},
|
|
1892
|
+
modelHost: false,
|
|
1893
|
+
agreed: ["agentLibs", "skillsLibs"],
|
|
1894
|
+
skillsPack: true,
|
|
1895
|
+
});
|
|
1896
|
+
const depsOk = out.agentLibs === "installed" || out.agentLibs === "present";
|
|
1897
|
+
|
|
1898
|
+
let stack = { ok: true, skipped: "" };
|
|
1899
|
+
if (!args.includes("--no-api")) {
|
|
1900
|
+
const { prepareLocalStack } = await import("./client-expert-run.mjs");
|
|
1901
|
+
stack = await prepareLocalStack({});
|
|
1902
|
+
}
|
|
1903
|
+
// One plain line on screen; the reason something was left goes to ~/.gonext/logs/prepare.log (GH #564), for support.
|
|
1904
|
+
if (!(depsOk && stack.ok)) {
|
|
1905
|
+
try {
|
|
1906
|
+
const { appendFileSync, mkdirSync } = await import("node:fs");
|
|
1907
|
+
const { join } = await import("node:path");
|
|
1908
|
+
const { homedir } = await import("node:os");
|
|
1909
|
+
const dir = join(homedir(), ".gonext", "logs");
|
|
1910
|
+
mkdirSync(dir, { recursive: true });
|
|
1911
|
+
appendFileSync(join(dir, "prepare.log"), `${new Date().toISOString()} agent=${out.agentLibs ?? "?"} python=${out.python3 ?? "?"} api=${stack.ok ? "ok" : "left"}: ${stack.skipped || "-"}\n`);
|
|
1912
|
+
} catch { /* the log is a convenience */ }
|
|
1913
|
+
}
|
|
1914
|
+
console.log(depsOk && stack.ok ? " ✓ gu is ready" : " · A few things are left — the first gu finishes them.");
|
|
1915
|
+
process.exit(depsOk && stack.ok ? 0 : 1);
|
|
1916
|
+
}
|
|
1917
|
+
|
|
1872
1918
|
if (args[0] === "doctor") {
|
|
1873
1919
|
// Task #304: a Mac whose MongoDB runs in Docker is told the native option, once, up front —
|
|
1874
1920
|
// a working Docker MongoDB is left alone (it is a choice), a silent one is named as stuck.
|