@tiens.nguyen/gu-cli 1.0.931 → 1.0.935
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +6 -3
- package/client-expert-api.mjs +109 -20
- package/client-expert-run.mjs +263 -120
- package/client-expert-setup.mjs +3 -2
- package/coding-provider-setup.mjs +27 -0
- package/free-model.mjs +33 -6
- package/gonext_agent_chat.py +748 -27
- package/gu-cli.mjs +90 -6
- package/gu-repl.mjs +545 -29
- package/gu_browser.py +83 -9
- package/gu_gif.py +101 -0
- package/gu_turn_notes.py +29 -2
- 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 +34 -7
- package/model-prices.mjs +22 -0
- package/next-suggestion.mjs +137 -0
- package/package.json +10 -1
- package/powershell-alias.mjs +12 -1
- package/python-unix.mjs +120 -0
- package/setup-fixes.mjs +245 -0
- package/step-group.mjs +59 -18
- package/terminal-layout.mjs +82 -3
- package/turn-notes.mjs +65 -0
- package/win-shell.mjs +26 -0
package/gu_browser.py
CHANGED
|
@@ -460,6 +460,50 @@ def _http(st, method, path, body=None, timeout=10):
|
|
|
460
460
|
return {"_status": e.code, "error": str(e)}
|
|
461
461
|
|
|
462
462
|
|
|
463
|
+
STOPPED_BY_USER = "The user pressed Stop in Chrome"
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def watch_stop(on_stop, log=None, every_s=1.0, stop_event=None):
|
|
467
|
+
"""GH #551: the extension's Stop button, seen from the running turn. Remembers the bridge's
|
|
468
|
+
stop count now and calls on_stop() once when it goes up — a press before this turn started
|
|
469
|
+
never stops it. A background thread; it ends after on_stop, or when stop_event is set.
|
|
470
|
+
→ the thread, or None when there is no bridge to watch."""
|
|
471
|
+
st = _read_state()
|
|
472
|
+
if not st:
|
|
473
|
+
return None
|
|
474
|
+
try:
|
|
475
|
+
start = int(_http(st, "GET", "/stop", timeout=3).get("stops") or 0)
|
|
476
|
+
except (OSError, ValueError):
|
|
477
|
+
return None
|
|
478
|
+
|
|
479
|
+
def run():
|
|
480
|
+
misses = 0
|
|
481
|
+
while not (stop_event and stop_event.is_set()):
|
|
482
|
+
time.sleep(every_s)
|
|
483
|
+
try:
|
|
484
|
+
n = int(_http(st, "GET", "/stop", timeout=3).get("stops") or 0)
|
|
485
|
+
misses = 0
|
|
486
|
+
except (OSError, ValueError):
|
|
487
|
+
misses += 1
|
|
488
|
+
if misses > 30: # the bridge went away: nothing left to watch
|
|
489
|
+
return
|
|
490
|
+
continue
|
|
491
|
+
if n > start:
|
|
492
|
+
if log:
|
|
493
|
+
log("browser: the user pressed Stop in Chrome")
|
|
494
|
+
try:
|
|
495
|
+
on_stop()
|
|
496
|
+
except Exception as e: # noqa: BLE001
|
|
497
|
+
if log:
|
|
498
|
+
log(f"browser: stop failed: {type(e).__name__}: {e}")
|
|
499
|
+
return
|
|
500
|
+
|
|
501
|
+
import threading
|
|
502
|
+
t = threading.Thread(target=run, name="gu-browser-stop", daemon=True)
|
|
503
|
+
t.start()
|
|
504
|
+
return t
|
|
505
|
+
|
|
506
|
+
|
|
463
507
|
def _start_bridge(log=None):
|
|
464
508
|
"""Start browser-bridge.mjs detached (it outlives this turn) and wait for its state file."""
|
|
465
509
|
os.makedirs(data_dir(), exist_ok=True)
|
|
@@ -492,10 +536,11 @@ def connect(wait=True, log=None, on_wait=None, own=False):
|
|
|
492
536
|
→ (state, None) either way, and the wait for a sleeping extension is shorter."""
|
|
493
537
|
st = _read_state()
|
|
494
538
|
started = False
|
|
539
|
+
now = {}
|
|
495
540
|
try:
|
|
496
541
|
if not st:
|
|
497
542
|
raise OSError("no bridge")
|
|
498
|
-
_http(st, "GET", "/status", timeout=3)
|
|
543
|
+
now = _http(st, "GET", "/status", timeout=3)
|
|
499
544
|
except OSError:
|
|
500
545
|
st = _start_bridge(log)
|
|
501
546
|
started = True
|
|
@@ -513,6 +558,8 @@ def connect(wait=True, log=None, on_wait=None, own=False):
|
|
|
513
558
|
wait_ms = (8000 if (seen and not missed_lately) else 0) if wait else 0 # then gu's own window
|
|
514
559
|
else:
|
|
515
560
|
wait_ms = (35000 if (seen and started) else 8000 if seen else 4000) if wait else 0
|
|
561
|
+
if now.get("connected"):
|
|
562
|
+
wait_ms = 0 # already there: no wait, and no "Waiting for Chrome…" line before every step
|
|
516
563
|
if wait_ms >= 8000 and on_wait:
|
|
517
564
|
on_wait()
|
|
518
565
|
try:
|
|
@@ -567,19 +614,23 @@ def profile_line():
|
|
|
567
614
|
return "No gu extension connected."
|
|
568
615
|
|
|
569
616
|
|
|
570
|
-
def cleanup(log=None):
|
|
617
|
+
def cleanup(log=None, quick=False):
|
|
571
618
|
"""End of a turn (GH #428): the extension closes the tabs gu opened and lets go of tabs the user
|
|
572
|
-
shared. Only when the extension is connected — never starts anything. → short text or "".
|
|
619
|
+
shared. Only when the extension is connected — never starts anything. → short text or "".
|
|
620
|
+
quick=True: a stopped turn (Stop in Chrome, Ctrl+C) has ~3 s before the worker kills it, so
|
|
621
|
+
one short call and no status check (the bridge answers at once when nothing is connected)."""
|
|
573
622
|
if keep_tabs():
|
|
574
623
|
return ""
|
|
575
624
|
st = _read_state()
|
|
576
625
|
if not st:
|
|
577
626
|
return ""
|
|
578
627
|
try:
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
628
|
+
if not quick:
|
|
629
|
+
s = _http(st, "GET", "/status", timeout=2)
|
|
630
|
+
if not s.get("connected"):
|
|
631
|
+
return ""
|
|
632
|
+
r = _http(st, "POST", "/cmd", body={"action": "cleanup", "timeout_ms": 1500 if quick else 8000},
|
|
633
|
+
timeout=2 if quick else 12)
|
|
583
634
|
except OSError:
|
|
584
635
|
return ""
|
|
585
636
|
res = r.get("result") or {}
|
|
@@ -611,7 +662,12 @@ def command(cmd, log=None, on_wait=None, own=False):
|
|
|
611
662
|
if r.get("noChrome"):
|
|
612
663
|
return False, str(r.get("error")), True # nothing to drive: the install answer applies
|
|
613
664
|
if not r.get("ok"):
|
|
614
|
-
|
|
665
|
+
err = str(r.get("error") or "failed")
|
|
666
|
+
if 'unknown action "network"' in err:
|
|
667
|
+
# GH #546: a gu Chrome extension older than 1.0.11 (the store update may not have reached it).
|
|
668
|
+
err = ("network needs the gu Chrome extension 1.0.11 or later — Chrome updates it on its own "
|
|
669
|
+
"within a day, or the user can update it at chrome://extensions. Until then use console.")
|
|
670
|
+
return False, err, False
|
|
615
671
|
res = r.get("result") or {}
|
|
616
672
|
if isinstance(res, dict) and r.get("backend"):
|
|
617
673
|
res["_backend"] = r["backend"]
|
|
@@ -670,7 +726,25 @@ def format_result(action, res):
|
|
|
670
726
|
msgs = res.get("console") or []
|
|
671
727
|
out += ("\nConsole since the last read:\n" + "\n".join(f" [{m.get('level')}] {m.get('text')}" for m in msgs)
|
|
672
728
|
if msgs else "\nConsole: nothing new.")
|
|
673
|
-
if a
|
|
729
|
+
if a == "resize": # GH #549
|
|
730
|
+
seen = res.get("viewport")
|
|
731
|
+
out = (f"Page size: {res.get('resized')}." + (f" The page now sees {seen}." if seen else "") + "\n" + out
|
|
732
|
+
+ "\n(read or screenshot to see the layout at this size)")
|
|
733
|
+
if a == "upload": # GH #547
|
|
734
|
+
out = f"Uploaded {res.get('uploaded')} into {res.get('into')}.\n" + out
|
|
735
|
+
if a == "network": # GH #546
|
|
736
|
+
net = res.get("network") or {}
|
|
737
|
+
rows = net.get("rows") or []
|
|
738
|
+
if not rows:
|
|
739
|
+
out += "\nNetwork: no new requests since the last read (that match, if a filter was given)."
|
|
740
|
+
else:
|
|
741
|
+
out += f"\nNetwork requests since the last read ({net.get('total')}):\n" + "\n".join(" " + r for r in rows)
|
|
742
|
+
if net.get("more"):
|
|
743
|
+
out += f"\n (+{net['more']} earlier — filter with text, or failed=True)"
|
|
744
|
+
body = net.get("body")
|
|
745
|
+
if body:
|
|
746
|
+
out += f"\nResponse body of {body.get('url')} ({body.get('status')}):\n{body.get('text')}"
|
|
747
|
+
if a in ("open", "click", "double_click", "type", "key", "back", "reload", "upload"):
|
|
674
748
|
out += "\n(read or screenshot to see the page now)"
|
|
675
749
|
return out
|
|
676
750
|
|
package/gu_gif.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Record the agent's browser steps as an animated GIF (GH #548) — like Claude Code's gif_creator.
|
|
2
|
+
|
|
3
|
+
The browser tool adds one frame after every step while a recording is on (open, click, type…),
|
|
4
|
+
marks where a click landed, and saves the GIF when the agent says record_stop, or by itself at the
|
|
5
|
+
end of the turn. Pillow only (already used for screenshots). No model, no network: tested alone.
|
|
6
|
+
"""
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import time
|
|
10
|
+
|
|
11
|
+
MAX_FRAMES = 120
|
|
12
|
+
MAX_EDGE = 800 # px: a GIF is for a person to watch, not for clicking
|
|
13
|
+
PAD = (40, 40, 40) # around a frame smaller than the GIF (a resize during the recording)
|
|
14
|
+
MAX_BYTES = 10 * 1024 * 1024
|
|
15
|
+
STEP_MS = 900 # each step on screen for about a second
|
|
16
|
+
HOLD_MS = 1800 # the first and last frames, so it starts and ends steadily
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def recordings_dir(home=None):
|
|
20
|
+
return os.path.join(home or os.path.expanduser("~"), ".gonext", "recordings")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def gif_name(label="", now=None):
|
|
24
|
+
"""'20261202-153045-login-flow.gif' — time first, so they sort; the label made file-safe."""
|
|
25
|
+
stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime(now if now is not None else time.time()))
|
|
26
|
+
slug = re.sub(r"[^a-z0-9]+", "-", str(label or "").lower()).strip("-")[:40]
|
|
27
|
+
return f"{stamp}{'-' + slug if slug else ''}.gif"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def same_size(frames):
|
|
31
|
+
"""Every frame on a canvas of the largest width and height, centred, with its own shape."""
|
|
32
|
+
from PIL import Image
|
|
33
|
+
size = (max(f.width for f in frames), max(f.height for f in frames))
|
|
34
|
+
out = []
|
|
35
|
+
for f in frames:
|
|
36
|
+
if f.size != size:
|
|
37
|
+
canvas = Image.new("RGB", size, PAD)
|
|
38
|
+
canvas.paste(f, ((size[0] - f.width) // 2, (size[1] - f.height) // 2))
|
|
39
|
+
f = canvas
|
|
40
|
+
out.append(f)
|
|
41
|
+
return out
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class GifRecorder:
|
|
45
|
+
def __init__(self, max_frames=MAX_FRAMES, max_edge=MAX_EDGE):
|
|
46
|
+
self.max_frames, self.max_edge = max_frames, max_edge
|
|
47
|
+
self.frames = [] # [(PIL image, label)]
|
|
48
|
+
self.on = False
|
|
49
|
+
self.label = ""
|
|
50
|
+
self.dropped = 0
|
|
51
|
+
|
|
52
|
+
def start(self, label=""):
|
|
53
|
+
self.frames, self.on, self.label, self.dropped = [], True, str(label or ""), 0
|
|
54
|
+
|
|
55
|
+
def add(self, image, click=None):
|
|
56
|
+
"""One frame: `image` at the page's CSS size; `click` = (x, y) in CSS px, drawn as a ring."""
|
|
57
|
+
if not self.on or image is None:
|
|
58
|
+
return False
|
|
59
|
+
from PIL import ImageDraw
|
|
60
|
+
im = image.convert("RGB")
|
|
61
|
+
k = min(1.0, self.max_edge / max(im.size))
|
|
62
|
+
if k < 1.0:
|
|
63
|
+
im = im.resize((max(1, int(im.width * k)), max(1, int(im.height * k))))
|
|
64
|
+
if click:
|
|
65
|
+
x, y = click[0] * k, click[1] * k
|
|
66
|
+
d = ImageDraw.Draw(im)
|
|
67
|
+
for r, w in ((14, 4), (6, 0)):
|
|
68
|
+
box = (x - r, y - r, x + r, y + r)
|
|
69
|
+
if w:
|
|
70
|
+
d.ellipse(box, outline=(124, 92, 255), width=w)
|
|
71
|
+
else:
|
|
72
|
+
d.ellipse(box, fill=(124, 92, 255))
|
|
73
|
+
if len(self.frames) >= self.max_frames:
|
|
74
|
+
# Keep the first frame and the most recent ones: the story's start and its end.
|
|
75
|
+
self.frames.pop(1)
|
|
76
|
+
self.dropped += 1
|
|
77
|
+
self.frames.append(im)
|
|
78
|
+
return True
|
|
79
|
+
|
|
80
|
+
def save(self, folder=None, now=None):
|
|
81
|
+
"""Write the GIF → (path, frame count, bytes), and stop. None when nothing was recorded."""
|
|
82
|
+
self.on = False
|
|
83
|
+
if not self.frames:
|
|
84
|
+
return None
|
|
85
|
+
from PIL import Image
|
|
86
|
+
os.makedirs(folder or recordings_dir(), exist_ok=True)
|
|
87
|
+
path = os.path.join(folder or recordings_dir(), gif_name(self.label, now))
|
|
88
|
+
frames = list(self.frames)
|
|
89
|
+
# A GIF has one size. After a resize (mobile, tablet) the frames differ: the GIF is as big
|
|
90
|
+
# as the biggest, and each frame sits in the middle of it, never stretched.
|
|
91
|
+
frames = same_size(frames)
|
|
92
|
+
while True:
|
|
93
|
+
pal = [f.convert("P", palette=Image.ADAPTIVE, colors=128) for f in frames]
|
|
94
|
+
durations = [HOLD_MS] + [STEP_MS] * max(0, len(pal) - 2) + ([HOLD_MS] if len(pal) > 1 else [])
|
|
95
|
+
pal[0].save(path, save_all=True, append_images=pal[1:], duration=durations[:len(pal)], loop=0, optimize=True)
|
|
96
|
+
size = os.path.getsize(path)
|
|
97
|
+
if size <= MAX_BYTES or len(frames) <= 2:
|
|
98
|
+
break
|
|
99
|
+
frames = frames[:1] + frames[1:-1:2] + frames[-1:] # too big: every other step, ends kept
|
|
100
|
+
self.frames = []
|
|
101
|
+
return path, len(pal), size
|
package/gu_turn_notes.py
CHANGED
|
@@ -17,8 +17,11 @@ import re
|
|
|
17
17
|
import time
|
|
18
18
|
|
|
19
19
|
NOTE_HEAD = "----- A NOTE FROM THE USER (typed while you were working) -----"
|
|
20
|
-
|
|
21
|
-
|
|
20
|
+
# GH #562: answered at once, in one line, and the turn goes on — like Claude Code. The answer goes through
|
|
21
|
+
# say(), which gu prints as normal text right under the user's message.
|
|
22
|
+
NOTE_TAIL = ("Answer it FIRST, in one short line, with say(\"...\") — what you will do about it: now, or after the "
|
|
23
|
+
"current work. Then go on with the task in the same step. It adds to the task; it replaces the task, "
|
|
24
|
+
"or stops it, only if it says so.")
|
|
22
25
|
|
|
23
26
|
|
|
24
27
|
def notes_dir() -> str:
|
|
@@ -66,6 +69,29 @@ def take_notes(job_id: str) -> list[str]:
|
|
|
66
69
|
return texts
|
|
67
70
|
|
|
68
71
|
|
|
72
|
+
def now_path(job_id: str) -> str:
|
|
73
|
+
"""GH #560: gu creates this when the user presses Ctrl+X Ctrl+S ("send now")."""
|
|
74
|
+
return os.path.join(notes_dir(), _safe(job_id) + ".now")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def send_now_requested(job_id: str) -> bool:
|
|
78
|
+
"""True when the user asked for their message to be read NOW: a command the agent is waiting on
|
|
79
|
+
gives way (it is handed to the background, never killed) so the step ends and the note is read."""
|
|
80
|
+
if not _safe(job_id):
|
|
81
|
+
return False
|
|
82
|
+
try:
|
|
83
|
+
return os.path.exists(now_path(job_id))
|
|
84
|
+
except OSError:
|
|
85
|
+
return False
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def clear_send_now(job_id: str) -> None:
|
|
89
|
+
try:
|
|
90
|
+
os.remove(now_path(job_id))
|
|
91
|
+
except OSError:
|
|
92
|
+
pass
|
|
93
|
+
|
|
94
|
+
|
|
69
95
|
def note_block(texts: list[str]) -> str:
|
|
70
96
|
"""The text added after a step's observations."""
|
|
71
97
|
body = "\n\n".join(texts)
|
|
@@ -83,6 +109,7 @@ def add_to_step(step_log, job_id: str) -> int:
|
|
|
83
109
|
texts = take_notes(job_id)
|
|
84
110
|
if not texts:
|
|
85
111
|
return 0
|
|
112
|
+
clear_send_now(job_id) # GH #560: honoured — the note reaches the model with this step
|
|
86
113
|
obs = getattr(step_log, "observations", None)
|
|
87
114
|
head = obs + "\n\n" if isinstance(obs, str) and obs.strip() else ""
|
|
88
115
|
step_log.observations = head + note_block(texts)
|
package/install-path.mjs
CHANGED
|
@@ -20,8 +20,9 @@
|
|
|
20
20
|
* HARD RULES:
|
|
21
21
|
* - NEVER fail the install. Every path through this file ends in exit 0; npm treats a
|
|
22
22
|
* postinstall failure as a failed install and the user gets nothing.
|
|
23
|
-
* -
|
|
24
|
-
*
|
|
23
|
+
* - On Windows (GH #557 follow-up, owner's call): add npm's folder to the USER PATH in the
|
|
24
|
+
* registry and take PowerShell's `gu` alias out of the way, then SAY what was changed —
|
|
25
|
+
* see setup-fixes.mjs. The install never asks; it reports.
|
|
25
26
|
* - NEVER touch an rc file twice: the marker pair makes re-runs no-ops.
|
|
26
27
|
* - Under `sudo npm i -g`, write to the REAL user's home (SUDO_USER) and chown the
|
|
27
28
|
* file back, or the user's next login shell reads a root-owned rc file.
|
|
@@ -105,8 +106,36 @@ export function fixPathPrefix({ here = "", env = process.env, exists = existsSyn
|
|
|
105
106
|
return "";
|
|
106
107
|
}
|
|
107
108
|
|
|
108
|
-
|
|
109
|
-
|
|
109
|
+
/**
|
|
110
|
+
* The marked PATH block for `dir`, in the shell start files (rcFilesFor). Shared with
|
|
111
|
+
* setup-fixes.mjs (gu's first start). → { wrote: the first file changed | null, already: a
|
|
112
|
+
* file already had the block }.
|
|
113
|
+
*/
|
|
114
|
+
export function addPathBlock({ dir, home = realUserHome() }) {
|
|
115
|
+
const targets = rcFilesFor(home);
|
|
116
|
+
const block = `${BEGIN}\n# npm's global bin dir was not on PATH; added by @tiens.nguyen/gu-cli.\nexport PATH="${dir}:$PATH"\n${END}\n`;
|
|
117
|
+
let wrote = null;
|
|
118
|
+
let already = false;
|
|
119
|
+
for (const rc of targets) {
|
|
120
|
+
try {
|
|
121
|
+
if (ensureBlock(rc, block)) wrote = wrote || rc;
|
|
122
|
+
else already = true;
|
|
123
|
+
} catch {
|
|
124
|
+
/* unwritable: the caller says how to do it by hand */
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return { wrote, already, targets };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Under `sudo npm i -g` a file written into ~/.gonext would be root's: gu could not delete it. */
|
|
131
|
+
// A function DECLARATION: main() runs at the top of this file, before any `const` below exists.
|
|
132
|
+
function underSudo() {
|
|
133
|
+
return Boolean(process.env.SUDO_UID && process.getuid && process.getuid() === 0);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async function main() {
|
|
137
|
+
// GH #557 follow-up (owner, 2026-12-02): Windows too — DO it and say so; never only advise.
|
|
138
|
+
if (platform() === "win32") return windowsFixes();
|
|
110
139
|
if (process.env.CI) return; // no user shell to help in CI
|
|
111
140
|
// GH #511: install.sh adds PATH itself, with the STABLE ~/.local/share/gu/node/bin (npm reports the
|
|
112
141
|
// versioned folder, which a Node update removes) — one line in the shell file, not two.
|
|
@@ -132,12 +161,15 @@ function main() {
|
|
|
132
161
|
if (onPath) return; // nothing to fix — most installs
|
|
133
162
|
|
|
134
163
|
const home = realUserHome();
|
|
135
|
-
const targets =
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
164
|
+
const { wrote, targets } = addPathBlock({ dir: stable, home });
|
|
165
|
+
// npm hides postinstall output: gu says this at its next start too (setup-fixes.mjs).
|
|
166
|
+
if (wrote && !underSudo()) {
|
|
167
|
+
try {
|
|
168
|
+
const sf = await import("./setup-fixes.mjs");
|
|
169
|
+
sf.saveSetupNotes({ done: [sf.SAID.posixPath(stable, wrote.replace(home, "~"))] }, { home });
|
|
170
|
+
} catch {
|
|
171
|
+
/* the line below still says it */
|
|
172
|
+
}
|
|
141
173
|
}
|
|
142
174
|
|
|
143
175
|
if (wrote) {
|
|
@@ -151,20 +183,20 @@ function main() {
|
|
|
151
183
|
}
|
|
152
184
|
|
|
153
185
|
/**
|
|
154
|
-
* Windows (#375, GitHub #156):
|
|
155
|
-
*
|
|
156
|
-
*
|
|
157
|
-
* --foreground-scripts; the installer (install.ps1) is what most people see.
|
|
186
|
+
* Windows (#375, GitHub #156; GH #557 follow-up): npm's folder on the user PATH and PowerShell's
|
|
187
|
+
* `gu` alias out of the way — DONE, then said (setup-fixes.mjs). npm shows this output only with
|
|
188
|
+
* --foreground-scripts, so it is also saved for gu to say at its next start.
|
|
158
189
|
*/
|
|
159
|
-
async function
|
|
190
|
+
async function windowsFixes() {
|
|
160
191
|
if (process.env.CI || process.env.npm_config_global !== "true") return;
|
|
192
|
+
if (process.env.GU_INSTALLER === "ps1") return; // install.ps1 does the same and says it itself
|
|
161
193
|
const prefix = process.env.npm_config_prefix;
|
|
162
194
|
if (!prefix) return;
|
|
163
|
-
const
|
|
164
|
-
const
|
|
165
|
-
|
|
166
|
-
const
|
|
167
|
-
console.log(
|
|
195
|
+
const sf = await import("./setup-fixes.mjs");
|
|
196
|
+
const report = await sf.applySetupFixes({ platform: "win32", dir: prefix });
|
|
197
|
+
sf.saveSetupNotes(report);
|
|
198
|
+
const text = sf.formatSetupReport(report);
|
|
199
|
+
if (text) console.log(text.replace(/^/gm, "gu-cli: "));
|
|
168
200
|
}
|
|
169
201
|
|
|
170
202
|
/** The installer's home — the invoking user's, not root's, under sudo. */
|
package/lsp-client.mjs
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ONE LANGUAGE SERVER, SPOKEN TO (GH #540) — a small LSP client: JSON-RPC over the server's stdin and
|
|
3
|
+
* stdout, framed by Content-Length headers. No dependency. Only what gu uses: start, open/change a
|
|
4
|
+
* file, ask for its diagnostics, shut down.
|
|
5
|
+
*
|
|
6
|
+
* DIAGNOSTICS ARE PULLED when the server can be asked (`textDocument/diagnostic`, LSP 3.17), and
|
|
7
|
+
* waited for otherwise (`textDocument/publishDiagnostics`). Pull first, because the push-only path
|
|
8
|
+
* returned NOTHING in 25 s from sourcekit-lsp in the #537 spike, while a pull gave both planted
|
|
9
|
+
* errors in 0.6 s. Push stays as the fallback for servers that only push.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { spawn } from "node:child_process";
|
|
13
|
+
import { pathToFileURL } from "node:url";
|
|
14
|
+
import { shellCommand } from "./win-shell.mjs";
|
|
15
|
+
|
|
16
|
+
export const fileUri = (p) => pathToFileURL(p).href;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* One spelling per file, to store and look up pushed diagnostics (GH #557, seen live on Windows 11):
|
|
20
|
+
* gu says file:///C:/Users/…, typescript-language-server answers file:///c%3A/Users/…, so every
|
|
21
|
+
* code check waited for a file the server never named — "code check skipped: timeout" on each edit.
|
|
22
|
+
* The drive's colon is decoded and its letter lowercased; nothing else changes (a POSIX path's case matters).
|
|
23
|
+
*/
|
|
24
|
+
export const uriKey = (uri) =>
|
|
25
|
+
typeof uri === "string" && uri.startsWith("file:")
|
|
26
|
+
? uri.replace(/^file:\/\/\/([A-Za-z])(?::|%3[Aa])/, (_m, d) => `file:///${d.toLowerCase()}:`)
|
|
27
|
+
: uri;
|
|
28
|
+
|
|
29
|
+
/** Frames → messages. Feed it bytes; it calls onMessage for every complete message. */
|
|
30
|
+
export function createFrameReader(onMessage) {
|
|
31
|
+
let buf = Buffer.alloc(0);
|
|
32
|
+
return (chunk) => {
|
|
33
|
+
buf = Buffer.concat([buf, chunk]);
|
|
34
|
+
for (;;) {
|
|
35
|
+
const end = buf.indexOf("\r\n\r\n");
|
|
36
|
+
if (end < 0) return;
|
|
37
|
+
const m = /content-length:\s*(\d+)/i.exec(buf.slice(0, end).toString("ascii"));
|
|
38
|
+
if (!m) {
|
|
39
|
+
buf = buf.slice(end + 4); // a header block without a length: skip it
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
const len = Number(m[1]);
|
|
43
|
+
if (buf.length < end + 4 + len) return;
|
|
44
|
+
const body = buf.slice(end + 4, end + 4 + len).toString("utf8");
|
|
45
|
+
buf = buf.slice(end + 4 + len);
|
|
46
|
+
try {
|
|
47
|
+
onMessage(JSON.parse(body));
|
|
48
|
+
} catch {
|
|
49
|
+
/* a malformed message is dropped, not fatal */
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** `settings` looked up by a dotted section ("python.analysis") — null when it is not there. */
|
|
56
|
+
export function settingAt(settings, section) {
|
|
57
|
+
if (settings === undefined || settings === null) return null;
|
|
58
|
+
if (!section) return settings;
|
|
59
|
+
let v = settings;
|
|
60
|
+
for (const k of String(section).split(".")) {
|
|
61
|
+
if (v && typeof v === "object" && k in v) v = v[k];
|
|
62
|
+
else return null;
|
|
63
|
+
}
|
|
64
|
+
return v;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export const frame = (msg) => {
|
|
68
|
+
const body = Buffer.from(JSON.stringify(msg), "utf8");
|
|
69
|
+
return Buffer.concat([Buffer.from(`Content-Length: ${body.length}\r\n\r\n`, "ascii"), body]);
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
export class LspClient {
|
|
73
|
+
/**
|
|
74
|
+
* @param {{ cmd: string, args?: string[], env?: object, root: string, log?: (s: string) => void,
|
|
75
|
+
* spawnImpl?: Function, requestTimeoutMs?: number }} o
|
|
76
|
+
*/
|
|
77
|
+
constructor({ cmd, args = [], env = process.env, root, log = () => {}, spawnImpl = spawn, requestTimeoutMs = 60_000, initializationOptions, settings }) {
|
|
78
|
+
Object.assign(this, { cmd, args, env, root, log, spawnImpl, requestTimeoutMs, initializationOptions, settings });
|
|
79
|
+
this.nextId = 1;
|
|
80
|
+
this.pending = new Map();
|
|
81
|
+
this.docs = new Map(); // uri → { version, languageId }
|
|
82
|
+
this.pushed = new Map(); // uri → { version, at, diagnostics }
|
|
83
|
+
this.waiters = new Set();
|
|
84
|
+
this.capabilities = {};
|
|
85
|
+
this.alive = false;
|
|
86
|
+
this.lastUsed = Date.now();
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Start the server and complete the LSP handshake. Rejects if it cannot start. */
|
|
90
|
+
async start({ timeoutMs = 30_000 } = {}) {
|
|
91
|
+
const isCmd = process.platform === "win32" && /\.(cmd|bat)$/i.test(this.cmd);
|
|
92
|
+
// A .cmd runs only through cmd.exe; given as ONE string, so Node prints no DEP0190 (GH #557).
|
|
93
|
+
const sc = isCmd ? shellCommand(this.cmd, this.args) : { cmd: this.cmd, args: this.args, shell: false };
|
|
94
|
+
this.proc = this.spawnImpl(sc.cmd, sc.args, { cwd: this.root, env: this.env, stdio: ["pipe", "pipe", "pipe"], shell: sc.shell, windowsHide: true });
|
|
95
|
+
this.alive = true;
|
|
96
|
+
this.proc.on("error", (e) => this._died(`could not start: ${e?.message || e}`));
|
|
97
|
+
this.proc.on("exit", (code, sig) => this._died(`exited (${sig || code})`));
|
|
98
|
+
this.proc.stderr?.on("data", () => {}); // drained; servers log a lot there
|
|
99
|
+
this.proc.stdin?.on("error", () => {});
|
|
100
|
+
this.proc.stdout.on("data", createFrameReader((m) => this._onMessage(m)));
|
|
101
|
+
const init = await this.request(
|
|
102
|
+
"initialize",
|
|
103
|
+
{
|
|
104
|
+
processId: process.pid,
|
|
105
|
+
clientInfo: { name: "gu" },
|
|
106
|
+
rootUri: fileUri(this.root),
|
|
107
|
+
rootPath: this.root,
|
|
108
|
+
...(this.initializationOptions !== undefined ? { initializationOptions: this.initializationOptions } : {}),
|
|
109
|
+
workspaceFolders: [{ uri: fileUri(this.root), name: this.root.split(/[\\/]/).pop() || "root" }],
|
|
110
|
+
capabilities: {
|
|
111
|
+
textDocument: {
|
|
112
|
+
synchronization: { didSave: true, dynamicRegistration: false },
|
|
113
|
+
publishDiagnostics: { relatedInformation: false, versionSupport: true },
|
|
114
|
+
diagnostic: { dynamicRegistration: false, relatedDocumentSupport: false },
|
|
115
|
+
definition: { linkSupport: false },
|
|
116
|
+
references: {},
|
|
117
|
+
hover: { contentFormat: ["plaintext", "markdown"] },
|
|
118
|
+
},
|
|
119
|
+
workspace: { configuration: true, workspaceFolders: true },
|
|
120
|
+
window: { workDoneProgress: false },
|
|
121
|
+
},
|
|
122
|
+
},
|
|
123
|
+
timeoutMs,
|
|
124
|
+
);
|
|
125
|
+
this.capabilities = init?.capabilities ?? {};
|
|
126
|
+
this.notify("initialized", {});
|
|
127
|
+
// A custom server's `settings` (Claude Code's lspServers field) go the way the LSP sends them.
|
|
128
|
+
if (this.settings !== undefined) this.notify("workspace/didChangeConfiguration", { settings: this.settings });
|
|
129
|
+
return this;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
_died(why) {
|
|
133
|
+
if (!this.alive) return;
|
|
134
|
+
this.alive = false;
|
|
135
|
+
this.diedBecause = why;
|
|
136
|
+
this.log(`language server ${this.cmd} ${why}`);
|
|
137
|
+
for (const { reject, timer } of this.pending.values()) {
|
|
138
|
+
clearTimeout(timer);
|
|
139
|
+
reject(new Error(`language server ${why}`));
|
|
140
|
+
}
|
|
141
|
+
this.pending.clear();
|
|
142
|
+
for (const w of this.waiters) w();
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
_send(msg) {
|
|
146
|
+
if (!this.alive) throw new Error(`language server is not running${this.diedBecause ? ` (${this.diedBecause})` : ""}`);
|
|
147
|
+
this.proc.stdin.write(frame({ jsonrpc: "2.0", ...msg }));
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
request(method, params, timeoutMs = this.requestTimeoutMs) {
|
|
151
|
+
return new Promise((resolve, reject) => {
|
|
152
|
+
const id = this.nextId++;
|
|
153
|
+
const timer = setTimeout(() => {
|
|
154
|
+
this.pending.delete(id);
|
|
155
|
+
reject(new Error(`${method} timed out after ${timeoutMs} ms`));
|
|
156
|
+
}, timeoutMs);
|
|
157
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
158
|
+
try {
|
|
159
|
+
this._send({ id, method, params });
|
|
160
|
+
} catch (e) {
|
|
161
|
+
clearTimeout(timer);
|
|
162
|
+
this.pending.delete(id);
|
|
163
|
+
reject(e);
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
notify(method, params) {
|
|
169
|
+
this._send({ method, params });
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
_onMessage(m) {
|
|
173
|
+
if (m.id !== undefined && m.method === undefined) {
|
|
174
|
+
const p = this.pending.get(m.id);
|
|
175
|
+
if (!p) return;
|
|
176
|
+
this.pending.delete(m.id);
|
|
177
|
+
clearTimeout(p.timer);
|
|
178
|
+
if (m.error) p.reject(Object.assign(new Error(m.error.message || "LSP error"), { code: m.error.code }));
|
|
179
|
+
else p.resolve(m.result);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
if (m.method === "textDocument/publishDiagnostics") {
|
|
183
|
+
const { uri, version, diagnostics } = m.params ?? {};
|
|
184
|
+
this.pushed.set(uriKey(uri), { version, at: Date.now(), diagnostics: diagnostics ?? [] });
|
|
185
|
+
for (const w of this.waiters) w();
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
if (m.id !== undefined && m.method) {
|
|
189
|
+
// A request FROM the server. Answer the ones servers block on, with "nothing configured".
|
|
190
|
+
let result = null;
|
|
191
|
+
if (m.method === "workspace/configuration") result = (m.params?.items ?? []).map((it) => settingAt(this.settings, it?.section));
|
|
192
|
+
else if (m.method === "workspace/workspaceFolders") result = [{ uri: fileUri(this.root), name: "root" }];
|
|
193
|
+
try {
|
|
194
|
+
this._send({ id: m.id, result });
|
|
195
|
+
} catch {}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Tell the server a file's current text (open it the first time, a full change after). */
|
|
200
|
+
sync(path, languageId, text) {
|
|
201
|
+
this.lastUsed = Date.now();
|
|
202
|
+
const uri = fileUri(path);
|
|
203
|
+
const doc = this.docs.get(uri);
|
|
204
|
+
if (!doc) {
|
|
205
|
+
this.docs.set(uri, { version: 1, languageId });
|
|
206
|
+
this.notify("textDocument/didOpen", { textDocument: { uri, languageId, version: 1, text } });
|
|
207
|
+
} else {
|
|
208
|
+
doc.version += 1;
|
|
209
|
+
this.notify("textDocument/didChange", { textDocument: { uri, version: doc.version }, contentChanges: [{ text }] });
|
|
210
|
+
}
|
|
211
|
+
this.notify("textDocument/didSave", { textDocument: { uri }, text });
|
|
212
|
+
return { uri, version: this.docs.get(uri).version, at: Date.now() };
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** The diagnostics for a file just synced. Pull when the server can be asked; else wait for a push. */
|
|
216
|
+
async diagnostics(path, { timeoutMs = 3000, since = 0, version = 0 } = {}) {
|
|
217
|
+
this.lastUsed = Date.now();
|
|
218
|
+
const uri = fileUri(path);
|
|
219
|
+
if (this.capabilities?.diagnosticProvider) {
|
|
220
|
+
try {
|
|
221
|
+
const r = await this.request("textDocument/diagnostic", { textDocument: { uri } }, timeoutMs);
|
|
222
|
+
if (r && Array.isArray(r.items)) return { ok: true, diagnostics: r.items, via: "pull" };
|
|
223
|
+
} catch (e) {
|
|
224
|
+
if (/timed out/.test(String(e?.message))) return { ok: false, why: "timeout" };
|
|
225
|
+
// a server that advertises pull but refuses it: fall through to push
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
// PUSH: the first publish for this file after the change, then a short quiet period — servers
|
|
229
|
+
// often publish twice (syntax first, then types), and the second is the one that matters.
|
|
230
|
+
const deadline = Date.now() + timeoutMs;
|
|
231
|
+
const fresh = () => {
|
|
232
|
+
const p = this.pushed.get(uriKey(uri));
|
|
233
|
+
if (!p) return null;
|
|
234
|
+
if (version && p.version !== undefined && p.version !== null) return p.version >= version ? p : null;
|
|
235
|
+
return p.at >= since ? p : null;
|
|
236
|
+
};
|
|
237
|
+
let got = null;
|
|
238
|
+
while (Date.now() < deadline && this.alive) {
|
|
239
|
+
got = fresh();
|
|
240
|
+
if (got && Date.now() - got.at >= 350) break;
|
|
241
|
+
await new Promise((resolve) => {
|
|
242
|
+
const done = () => {
|
|
243
|
+
this.waiters.delete(done);
|
|
244
|
+
clearTimeout(t);
|
|
245
|
+
resolve();
|
|
246
|
+
};
|
|
247
|
+
const t = setTimeout(done, got ? 120 : Math.max(10, deadline - Date.now()));
|
|
248
|
+
this.waiters.add(done);
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
got = fresh();
|
|
252
|
+
return got ? { ok: true, diagnostics: got.diagnostics, via: "push" } : { ok: false, why: this.alive ? "timeout" : "stopped" };
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async shutdown({ timeoutMs = 2000 } = {}) {
|
|
256
|
+
if (!this.alive) return;
|
|
257
|
+
try {
|
|
258
|
+
await this.request("shutdown", null, timeoutMs);
|
|
259
|
+
this.notify("exit", null);
|
|
260
|
+
} catch {}
|
|
261
|
+
setTimeout(() => {
|
|
262
|
+
try {
|
|
263
|
+
if (this.alive) this.proc.kill();
|
|
264
|
+
} catch {}
|
|
265
|
+
}, 500).unref?.();
|
|
266
|
+
}
|
|
267
|
+
}
|