@tiens.nguyen/gu-cli 1.0.939 → 1.0.941
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/README.md +17 -7
- package/agent-deps-preflight.mjs +1 -1
- package/autocompact.mjs +2 -2
- package/browser-bridge.mjs +2 -2
- package/browser-chrome.mjs +2 -2
- package/browser-command.mjs +4 -4
- package/browser-extension/README.md +6 -6
- package/clear-logs.mjs +3 -3
- package/clear-state.mjs +3 -3
- package/cli-token.mjs +8 -8
- package/client-expert-api.mjs +9 -9
- package/client-expert-run.mjs +7 -7
- package/client-expert-setup.mjs +4 -4
- package/command-allow.mjs +1 -1
- package/conversation-archive.mjs +2 -2
- package/credential-recovery.mjs +1 -1
- package/daemon-control.mjs +4 -4
- package/device-login.mjs +3 -3
- package/free-model.mjs +1 -1
- package/full-log-command.mjs +1 -1
- package/gonext_agent_chat.py +160 -89
- package/gu-cli.mjs +55 -29
- package/gu-home-move.mjs +193 -0
- package/gu-repl.mjs +342 -59
- package/gu_browser.py +3 -3
- package/gu_free_budget.py +2 -2
- package/gu_gif.py +1 -1
- package/gu_hooks.py +1 -1
- package/gu_turn_notes.py +2 -2
- package/gu_turn_trail.py +138 -0
- package/gudb-size.mjs +198 -0
- package/hooks-config.mjs +4 -4
- package/image-paste.mjs +8 -8
- package/install-path.mjs +1 -1
- package/log-level.mjs +1 -1
- package/log-policy.mjs +1 -1
- package/lsp-host.mjs +2 -2
- package/lsp-registry.mjs +9 -9
- package/mcp-command.mjs +1 -1
- package/mcp-config.mjs +5 -5
- package/memory-task.mjs +85 -0
- package/model-doctor.mjs +10 -10
- package/mongo-mac.mjs +2 -2
- package/mongo-windows.mjs +3 -3
- package/next-suggestion.mjs +13 -8
- package/package.json +5 -1
- package/platform-tools.mjs +3 -3
- package/poll-errors.mjs +2 -2
- package/prompt_scaffold_check.py +1 -1
- package/proxy-store.mjs +1 -1
- package/python-unix.mjs +6 -6
- package/python-windows.mjs +1 -1
- package/rag-selftest.mjs +2 -2
- package/resume-memory.mjs +1 -1
- package/scripts/image-paste-check.mjs +1 -1
- package/setup-fixes.mjs +4 -4
- package/shell-details.mjs +2 -2
- package/skill-install.mjs +9 -9
- package/skill-package.mjs +10 -10
- package/skill-source.mjs +4 -4
- package/skills-copy.mjs +15 -15
- package/skills.mjs +4 -4
- package/support-bundle.mjs +6 -6
- package/support-report.mjs +5 -5
- package/terminal-layout.mjs +25 -1
- package/turn-notes.mjs +2 -2
- package/version-check.mjs +1 -1
- package/workspace-revert.mjs +2 -2
package/gu_browser.py
CHANGED
|
@@ -30,7 +30,7 @@ _EXT_MISS = {"at": 0}
|
|
|
30
30
|
|
|
31
31
|
|
|
32
32
|
def data_dir():
|
|
33
|
-
return os.path.join(os.path.expanduser("~"), ".
|
|
33
|
+
return os.path.join(os.path.expanduser("~"), ".gu")
|
|
34
34
|
|
|
35
35
|
|
|
36
36
|
def state_path():
|
|
@@ -44,7 +44,7 @@ def seen_path():
|
|
|
44
44
|
|
|
45
45
|
|
|
46
46
|
def extension_dir():
|
|
47
|
-
"""The folder the user loads into Chrome. A fixed place under ~/.
|
|
47
|
+
"""The folder the user loads into Chrome. A fixed place under ~/.gu, not the npm package:
|
|
48
48
|
an update moves the package, and Chrome would lose an unpacked extension loaded from there."""
|
|
49
49
|
return os.environ.get("GU_BROWSER_EXT_DIR") or os.path.join(data_dir(), "browser-extension")
|
|
50
50
|
|
|
@@ -168,7 +168,7 @@ def install_text(reason="not connected"):
|
|
|
168
168
|
return (f"BROWSER NOT AVAILABLE — {reason}. This is a problem in gu's own browser bridge, NOT a "
|
|
169
169
|
"missing or broken Chrome: do NOT install, reinstall, move or delete any browser. STOP "
|
|
170
170
|
"and tell the user, with that error: update gu (npm install -g @tiens.nguyen/gu-cli@latest), "
|
|
171
|
-
"restart it, and ask again; the bridge's log is ~/.
|
|
171
|
+
"restart it, and ask again; the bridge's log is ~/.gu/browser-bridge.log.")
|
|
172
172
|
no_chrome = "no chrome found" in str(reason).lower()
|
|
173
173
|
if last_seen().get("installType") == "normal" and not no_chrome:
|
|
174
174
|
# The Chrome Web Store copy is installed: never point at the developer folder again (#145).
|
package/gu_free_budget.py
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
gu used to check the free model's allowance only at the START of a turn and count the turn's spend only
|
|
4
4
|
at its END — so a long turn ran on, well past the allowance, and usually ended in a confusing error.
|
|
5
5
|
|
|
6
|
-
Now the agent reads what is left (~/.
|
|
6
|
+
Now the agent reads what is left (~/.gu/free-model.json, which gu writes; it never holds the key),
|
|
7
7
|
adds up what THIS turn has spent after every step, and PAUSES before the step that would not fit:
|
|
8
8
|
the step that ran stays finished (no half-written file), and the turn ends with a plain message the
|
|
9
9
|
user can act on, then "continue".
|
|
@@ -19,7 +19,7 @@ import math
|
|
|
19
19
|
import os
|
|
20
20
|
import time
|
|
21
21
|
|
|
22
|
-
STATE_FILE = os.path.join("~", ".
|
|
22
|
+
STATE_FILE = os.path.join("~", ".gu", "free-model.json")
|
|
23
23
|
|
|
24
24
|
|
|
25
25
|
def _whole(n) -> int:
|
package/gu_gif.py
CHANGED
|
@@ -17,7 +17,7 @@ HOLD_MS = 1800 # the first and last frames, so it starts and ends steadily
|
|
|
17
17
|
|
|
18
18
|
|
|
19
19
|
def recordings_dir(home=None):
|
|
20
|
-
return os.path.join(home or os.path.expanduser("~"), ".
|
|
20
|
+
return os.path.join(home or os.path.expanduser("~"), ".gu", "recordings")
|
|
21
21
|
|
|
22
22
|
|
|
23
23
|
def gif_name(label="", now=None):
|
package/gu_hooks.py
CHANGED
|
@@ -249,7 +249,7 @@ class HookRunner:
|
|
|
249
249
|
# ---- onStart: once per session ---------------------------------------------------------------
|
|
250
250
|
|
|
251
251
|
def _state_path() -> str:
|
|
252
|
-
return os.path.join(os.path.expanduser("~"), ".
|
|
252
|
+
return os.path.join(os.path.expanduser("~"), ".gu", "hooks-state.json")
|
|
253
253
|
|
|
254
254
|
|
|
255
255
|
def is_new_session(cwd: str, session_id: str, path: str | None = None) -> bool:
|
package/gu_turn_notes.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"""NOTES TYPED DURING A TURN, read by the running agent at its next step (GH #506).
|
|
2
2
|
|
|
3
|
-
gu writes what the user typed while a turn runs to ~/.
|
|
3
|
+
gu writes what the user typed while a turn runs to ~/.gu/turn-notes/<jobId>.jsonl. The agent's
|
|
4
4
|
step callback TAKES the file (rename, then read) after a step and adds the notes to that step's
|
|
5
5
|
observations — the newest text of the conversation, not yet sent to the model. So the prompt is only
|
|
6
6
|
APPENDED to: the system prompt, the tool reference and every earlier step stay byte-identical, and
|
|
@@ -25,7 +25,7 @@ NOTE_TAIL = ("Answer it FIRST, in one short line, with say(\"...\") — what you
|
|
|
25
25
|
|
|
26
26
|
|
|
27
27
|
def notes_dir() -> str:
|
|
28
|
-
return os.path.join(os.path.expanduser("~"), ".
|
|
28
|
+
return os.path.join(os.path.expanduser("~"), ".gu", "turn-notes")
|
|
29
29
|
|
|
30
30
|
|
|
31
31
|
def _safe(job_id: str) -> str:
|
package/gu_turn_trail.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""GH #585: what earlier turns of this conversation RAN, for the turns after them.
|
|
2
|
+
|
|
3
|
+
The history carries only each turn's ANSWER. An answer says "I connected to the production
|
|
4
|
+
MongoDB", never how (ssh to the server, mongosh there, the URI in the server's .env), so the
|
|
5
|
+
next question searched for the database again from zero. Each finished turn now leaves its
|
|
6
|
+
steps here (one file per folder, secrets hidden), and a later turn of the SAME conversation
|
|
7
|
+
gets them back: only turns whose question is still in the history it was sent.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import time
|
|
16
|
+
|
|
17
|
+
KEEP_TURNS = 6 # turns kept per folder
|
|
18
|
+
STEP_DID = 400 # chars of a step's code kept
|
|
19
|
+
STEP_FOUND = 400 # chars of what it found
|
|
20
|
+
BLOCK_BUDGET = 3500 # chars handed to the next turn, newest steps first (~1k tokens)
|
|
21
|
+
# A model on this machine or the LAN reads its prompt slowly (ollama1: ~2.3 tokens/s), so 1k
|
|
22
|
+
# more tokens is minutes on every turn's first step. There it gets the commands only (~300 tokens).
|
|
23
|
+
LOCAL_BUDGET = 1200
|
|
24
|
+
|
|
25
|
+
_RULES = [
|
|
26
|
+
# An env name (.env, export, docker -e): MONGODB_URI=…, DB_PASSWORD=…, GH_TOKEN=…
|
|
27
|
+
(re.compile(r"(\b[A-Z0-9_]*(?:SECRET|PASSWORD|PASSWD|PWD|TOKEN|API_?KEY|ACCESS_KEY|PRIVATE_KEY|_KEY|_URI|_URL|DSN|AUTH|CREDENTIALS?|COOKIE)[A-Z0-9_]*\s*=\s*[\"']?)([^\s\"']+)"), r"\1***"),
|
|
28
|
+
# A config key (JSON, YAML): "password": "…", apiKey: …
|
|
29
|
+
(re.compile(r"(?i)([\"']?\b(?:password|passwd|secret|client_?secret|token|access_?token|refresh_?token|api_?key|apikey|access_?key|private_?key)[\"']?\s*[:=]\s*[\"']?)([^\s\"',}]+)"), r"\1***"),
|
|
30
|
+
# scheme://user:password@host
|
|
31
|
+
(re.compile(r"(?i)\b([a-z][a-z0-9+.-]*://[^\s:/@]+:)([^\s@/]+)@"), r"\1***@"),
|
|
32
|
+
# Authorization headers
|
|
33
|
+
(re.compile(r"(?i)(authorization:\s*[a-z]+\s+)[^\s'\"]+"), r"\1***"),
|
|
34
|
+
(re.compile(r"(?i)\b(bearer)\s+[A-Za-z0-9._~+/=-]{12,}"), r"\1 ***"),
|
|
35
|
+
# --password x / --token=x
|
|
36
|
+
(re.compile(r"(?i)(--?(?:password|passwd|pass|token|api-key|secret)[= ])(\S+)"), r"\1***"),
|
|
37
|
+
# well-known key shapes
|
|
38
|
+
(re.compile(r"\b(?:sk-[A-Za-z0-9_-]{16,}|AIza[0-9A-Za-z_-]{20,}|gh[pousr]_[A-Za-z0-9]{20,}|wk_[A-Za-z0-9]{16,}|AKIA[0-9A-Z]{16}|xox[abprs]-[A-Za-z0-9-]{10,})"), "***"),
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def redact(text: str) -> str:
|
|
43
|
+
s = str(text or "")
|
|
44
|
+
for rx, sub in _RULES:
|
|
45
|
+
s = rx.sub(sub, s)
|
|
46
|
+
return s
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _clip(s: str, n: int) -> str:
|
|
50
|
+
s = str(s or "").strip()
|
|
51
|
+
return s if len(s) <= n else s[: n - 1] + "…"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def path_for(workspace: str, home: str | None = None) -> str:
|
|
55
|
+
h = hashlib.sha256(workspace.encode("utf-8")).hexdigest()[:32]
|
|
56
|
+
base = os.path.join(home or os.path.expanduser("~"), ".gu", "agent-turns")
|
|
57
|
+
os.makedirs(base, exist_ok=True)
|
|
58
|
+
return os.path.join(base, f"{h}.trail.json")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _key(q: str) -> str:
|
|
62
|
+
"""A question as the history keeps it: gu may append notes under it later (GH #514)."""
|
|
63
|
+
return re.sub(r"\s+", " ", str(q or "")).strip().lower()[:160]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _load(path: str) -> list:
|
|
67
|
+
try:
|
|
68
|
+
with open(path, encoding="utf-8") as f:
|
|
69
|
+
d = json.load(f)
|
|
70
|
+
return d if isinstance(d, list) else []
|
|
71
|
+
except (OSError, ValueError):
|
|
72
|
+
return []
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def save(workspace: str, question: str, steps: list, home: str | None = None) -> int:
|
|
76
|
+
"""Record a finished turn's steps. Returns how many were kept. Never raises."""
|
|
77
|
+
try:
|
|
78
|
+
kept = []
|
|
79
|
+
for st in steps or []:
|
|
80
|
+
if not isinstance(st, dict):
|
|
81
|
+
continue
|
|
82
|
+
did = _clip(redact(st.get("did")), STEP_DID)
|
|
83
|
+
if not did:
|
|
84
|
+
continue
|
|
85
|
+
kept.append({"did": did, "found": _clip(redact(st.get("found")), STEP_FOUND)})
|
|
86
|
+
if not kept or not _key(question):
|
|
87
|
+
return 0
|
|
88
|
+
path = path_for(workspace, home)
|
|
89
|
+
turns = [t for t in _load(path) if t.get("q") != _key(question)]
|
|
90
|
+
turns.append({"q": _key(question), "asked": _clip(question, 200), "at": int(time.time()), "steps": kept})
|
|
91
|
+
tmp = path + ".tmp"
|
|
92
|
+
with open(tmp, "w", encoding="utf-8") as f:
|
|
93
|
+
json.dump(turns[-KEEP_TURNS:], f)
|
|
94
|
+
os.replace(tmp, path)
|
|
95
|
+
return len(kept)
|
|
96
|
+
except Exception: # noqa: BLE001
|
|
97
|
+
return 0
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def block(workspace: str, earlier_questions: list, home: str | None = None, budget: int | None = None,
|
|
101
|
+
local_model: bool = False) -> str:
|
|
102
|
+
"""The steps of the earlier turns of THIS conversation, newest first within the budget,
|
|
103
|
+
shown oldest first. Empty when none is in the history (a new conversation, or /clear).
|
|
104
|
+
local_model: the coder runs on this machine or the LAN — commands only, a smaller budget."""
|
|
105
|
+
if budget is None:
|
|
106
|
+
budget = LOCAL_BUDGET if local_model else BLOCK_BUDGET
|
|
107
|
+
try:
|
|
108
|
+
asked = {_key(q) for q in earlier_questions if _key(q)}
|
|
109
|
+
if not asked:
|
|
110
|
+
return ""
|
|
111
|
+
def _in_history(t):
|
|
112
|
+
k = t.get("q", "")
|
|
113
|
+
return any(a.startswith(k) or k.startswith(a) for a in asked)
|
|
114
|
+
turns = [t for t in _load(path_for(workspace, home)) if _in_history(t)]
|
|
115
|
+
if not turns:
|
|
116
|
+
return ""
|
|
117
|
+
parts, used = [], 0
|
|
118
|
+
for t in reversed(turns):
|
|
119
|
+
segs = []
|
|
120
|
+
for st in reversed(t.get("steps") or []):
|
|
121
|
+
seg = f" - ran: {st.get('did', '')}" + (
|
|
122
|
+
f"\n found: {st['found']}" if st.get("found") and not local_model else "")
|
|
123
|
+
if used + len(seg) > budget:
|
|
124
|
+
break
|
|
125
|
+
segs.append(seg)
|
|
126
|
+
used += len(seg)
|
|
127
|
+
if segs:
|
|
128
|
+
parts.append(f"Turn \"{t.get('asked', '')}\":\n" + "\n".join(reversed(segs)))
|
|
129
|
+
if used >= budget:
|
|
130
|
+
break
|
|
131
|
+
if not parts:
|
|
132
|
+
return ""
|
|
133
|
+
return ("WHAT EARLIER TURNS OF THIS CONVERSATION RAN (their answers above don't say how). "
|
|
134
|
+
"Reuse what worked — the same command, server, file or path — instead of searching "
|
|
135
|
+
"again. Secrets show as ***: read them again from where that step found them.\n"
|
|
136
|
+
+ "\n".join(reversed(parts)))
|
|
137
|
+
except Exception: # noqa: BLE001
|
|
138
|
+
return ""
|
package/gudb-size.mjs
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GH #594: gu's local database (gudb, ~/.gu/gudb/gu.db) — how big it is, what makes it big, and
|
|
3
|
+
* the one safe cleanup.
|
|
4
|
+
*
|
|
5
|
+
* Measured on the owner's Mac (2026-12-04): 25 MB after two days, 94% of it ONE field — the full
|
|
6
|
+
* prompt kept for every model step (`promptText` in c_agent_code_responses), saved only when "keep
|
|
7
|
+
* full model responses" is on. A busy day added 17 MB. Nothing else in gudb grows like that, and
|
|
8
|
+
* nothing expired it.
|
|
9
|
+
*
|
|
10
|
+
* The cleanup removes that saved TEXT (prompt and response) from steps older than N days and
|
|
11
|
+
* keeps every row — the usage numbers (tokens, model, time) stay. Then it compacts the file.
|
|
12
|
+
* Never touches jobs, settings, keys, workspaces or billing.
|
|
13
|
+
*/
|
|
14
|
+
import { existsSync, mkdirSync, readdirSync, rmSync, statSync, statfsSync } from "node:fs";
|
|
15
|
+
import { createRequire } from "node:module";
|
|
16
|
+
import { homedir } from "node:os";
|
|
17
|
+
import { dirname, join } from "node:path";
|
|
18
|
+
|
|
19
|
+
// Same path as client-expert-api.mjs gudbFile — not imported, so gu-repl can load this at startup cheaply.
|
|
20
|
+
export const gudbFile = (home = homedir()) => join(home, ".gu", "gudb", "gu.db");
|
|
21
|
+
|
|
22
|
+
/** A notice from here on; yellow from URGENT on. */
|
|
23
|
+
export const GUDB_NOTICE_BYTES = 1024 ** 3; // 1 GB
|
|
24
|
+
export const GUDB_URGENT_BYTES = 5 * 1024 ** 3; // 5 GB
|
|
25
|
+
/** Saved text older than this is what the cleanup offers to remove. */
|
|
26
|
+
export const KEEP_TEXT_DAYS = 14;
|
|
27
|
+
/** GH #594 #1: older than this, the worker removes it by itself (daily). The rows stay. */
|
|
28
|
+
export const AUTO_KEEP_TEXT_DAYS = 30;
|
|
29
|
+
/** GH #597: below this much free disk, gu warns — SQLite can't write, and compacting needs room. */
|
|
30
|
+
export const LOW_DISK_BYTES = 2 * 1024 ** 3;
|
|
31
|
+
/** GH #598: backups kept by /backup-db, newest first. */
|
|
32
|
+
export const KEEP_BACKUPS = 3;
|
|
33
|
+
|
|
34
|
+
const TABLE = "c_agent_code_responses";
|
|
35
|
+
|
|
36
|
+
function open(path, { readOnly = true } = {}) {
|
|
37
|
+
const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
|
|
38
|
+
const db = new DatabaseSync(path, readOnly ? { readOnly: true } : {});
|
|
39
|
+
db.exec("PRAGMA busy_timeout = 5000;");
|
|
40
|
+
return db;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The file with its WAL and shared-memory files: what it takes on disk. */
|
|
44
|
+
export function gudbBytes(path = gudbFile()) {
|
|
45
|
+
let n = 0;
|
|
46
|
+
for (const p of [path, `${path}-wal`, `${path}-shm`]) {
|
|
47
|
+
try {
|
|
48
|
+
n += statSync(p).size;
|
|
49
|
+
} catch {
|
|
50
|
+
/* not there */
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return n;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const cutoffIso = (days, now = Date.now()) => new Date(now - days * 86_400_000).toISOString();
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* What is in it. → { path, bytes, text: { bytes, rows }, oldText: { bytes, rows }, days } — or null
|
|
60
|
+
* when there is no gudb here (Cloud mode, a Mongo computer) or it can't be read.
|
|
61
|
+
*/
|
|
62
|
+
export function surveyGudb({ path = gudbFile(), days = KEEP_TEXT_DAYS, now = Date.now() } = {}) {
|
|
63
|
+
if (!existsSync(path)) return null;
|
|
64
|
+
let db;
|
|
65
|
+
try {
|
|
66
|
+
db = open(path);
|
|
67
|
+
const has = db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?").get(TABLE);
|
|
68
|
+
const sum = (where, ...args) => has
|
|
69
|
+
? db.prepare(`SELECT COUNT(*) AS rows, COALESCE(SUM(COALESCE(LENGTH(json_extract(doc,'$.promptText')),0) + COALESCE(LENGTH(json_extract(doc,'$.text')),0)),0) AS bytes
|
|
70
|
+
FROM ${TABLE} WHERE (json_extract(doc,'$.promptText') <> '' OR json_extract(doc,'$.text') <> '') ${where}`).get(...args)
|
|
71
|
+
: { rows: 0, bytes: 0 };
|
|
72
|
+
const text = sum("");
|
|
73
|
+
const oldText = sum("AND json_extract(doc,'$.createdAt') < ?", cutoffIso(days, now));
|
|
74
|
+
return { path, bytes: gudbBytes(path), text: { bytes: Number(text.bytes), rows: Number(text.rows) },
|
|
75
|
+
oldText: { bytes: Number(oldText.bytes), rows: Number(oldText.rows) }, days };
|
|
76
|
+
} catch {
|
|
77
|
+
return null;
|
|
78
|
+
} finally {
|
|
79
|
+
try { db?.close(); } catch { /* closed */ }
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Remove the saved prompt/response text from steps older than `days`, keep the rows, then compact.
|
|
85
|
+
* → { cleared: rows, before, after, freed } or { error }.
|
|
86
|
+
* Compacting (VACUUM) needs free disk about the size of the file, and waits for gu's API to be idle.
|
|
87
|
+
*/
|
|
88
|
+
export function clearOldText({ path = gudbFile(), days = KEEP_TEXT_DAYS, now = Date.now(), compact = true } = {}) {
|
|
89
|
+
const before = gudbBytes(path);
|
|
90
|
+
let db;
|
|
91
|
+
try {
|
|
92
|
+
db = open(path, { readOnly: false });
|
|
93
|
+
const r = db.prepare(`UPDATE ${TABLE} SET doc = json_remove(doc, '$.promptText', '$.text')
|
|
94
|
+
WHERE json_extract(doc,'$.createdAt') < ?
|
|
95
|
+
AND (json_extract(doc,'$.promptText') IS NOT NULL OR json_extract(doc,'$.text') IS NOT NULL)`)
|
|
96
|
+
.run(cutoffIso(days, now));
|
|
97
|
+
db.exec("PRAGMA wal_checkpoint(TRUNCATE);");
|
|
98
|
+
// Without compacting the file keeps its size, but SQLite reuses the freed pages for new rows —
|
|
99
|
+
// so the AUTOMATIC run (no long lock while gu works) still stops the growth.
|
|
100
|
+
let compacted = false;
|
|
101
|
+
if (compact) {
|
|
102
|
+
try {
|
|
103
|
+
db.exec("VACUUM;");
|
|
104
|
+
compacted = true;
|
|
105
|
+
} catch {
|
|
106
|
+
/* busy, or no room: the text is gone anyway; the space comes back next time */
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
db.exec("PRAGMA wal_checkpoint(TRUNCATE);");
|
|
110
|
+
const after = gudbBytes(path);
|
|
111
|
+
return { cleared: Number(r.changes), before, after, freed: Math.max(0, before - after), compacted };
|
|
112
|
+
} catch (e) {
|
|
113
|
+
return { error: String(e?.message ?? e) };
|
|
114
|
+
} finally {
|
|
115
|
+
try { db?.close(); } catch { /* closed */ }
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const human = (n) => {
|
|
120
|
+
const u = ["B", "KB", "MB", "GB", "TB"];
|
|
121
|
+
let i = 0;
|
|
122
|
+
let v = Number(n) || 0;
|
|
123
|
+
while (v >= 1024 && i < u.length - 1) { v /= 1024; i++; }
|
|
124
|
+
return `${v >= 10 || i === 0 ? Math.round(v) : v.toFixed(1)} ${u[i]}`;
|
|
125
|
+
};
|
|
126
|
+
export { human as gudbHuman };
|
|
127
|
+
|
|
128
|
+
/** The notice row's item, or "" below the threshold. → { text, urgent } | null */
|
|
129
|
+
export function gudbNotice(bytes, { threshold = GUDB_NOTICE_BYTES, urgent = GUDB_URGENT_BYTES } = {}) {
|
|
130
|
+
const n = Number(bytes) || 0;
|
|
131
|
+
if (n < threshold) return null;
|
|
132
|
+
return { text: `gu database ${human(n)} · clean old data (click)`, urgent: n >= urgent };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Free bytes on the disk that holds `dir` (or its nearest existing parent). null when unknown. */
|
|
136
|
+
export function freeDiskBytes(dir = join(homedir(), ".gu")) {
|
|
137
|
+
let d = dir;
|
|
138
|
+
while (d && !existsSync(d)) {
|
|
139
|
+
const up = dirname(d);
|
|
140
|
+
if (up === d) break;
|
|
141
|
+
d = up;
|
|
142
|
+
}
|
|
143
|
+
try {
|
|
144
|
+
const st = statfsSync(d);
|
|
145
|
+
return Number(st.bavail) * Number(st.bsize);
|
|
146
|
+
} catch {
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** GH #597: the notice row's item when the disk is nearly full, else null. */
|
|
152
|
+
export function lowDiskNotice(free, { threshold = LOW_DISK_BYTES } = {}) {
|
|
153
|
+
if (free == null || free >= threshold) return null;
|
|
154
|
+
return { text: `disk almost full · ${human(free)} free (click)`, urgent: true };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* The worker's daily run (GH #594 #1): saved text older than 30 days goes, rows stay, no compacting.
|
|
159
|
+
* → the clearOldText result, or null when there is no gudb here.
|
|
160
|
+
*/
|
|
161
|
+
export function autoClearOldText({ path = gudbFile(), days = AUTO_KEEP_TEXT_DAYS, now = Date.now() } = {}) {
|
|
162
|
+
if (!existsSync(path)) return null;
|
|
163
|
+
return clearOldText({ path, days, now, compact: false });
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* GH #598: a backup made BY SQLITE (VACUUM INTO) — consistent even while gu's API writes, WAL
|
|
168
|
+
* included, which a plain file copy is not. → { file, bytes, removed } or { error }.
|
|
169
|
+
* Refused when the disk would be left under LOW_DISK_BYTES; keeps the newest `keep`.
|
|
170
|
+
*/
|
|
171
|
+
export function backupGudb({ path = gudbFile(), dir = join(dirname(path), "backups"), keep = KEEP_BACKUPS,
|
|
172
|
+
now = Date.now(), free = freeDiskBytes(dirname(path)) } = {}) {
|
|
173
|
+
if (!existsSync(path)) return { error: "there is no gu database on this computer" };
|
|
174
|
+
const size = gudbBytes(path);
|
|
175
|
+
if (free != null && free - size < LOW_DISK_BYTES) {
|
|
176
|
+
return { error: `not enough free disk: a backup needs about ${human(size)} and would leave less than ${human(LOW_DISK_BYTES)} free` };
|
|
177
|
+
}
|
|
178
|
+
// 20261204-120000: sorts by time, matches the pattern the pruning below looks for
|
|
179
|
+
const stamp = new Date(now).toISOString().slice(0, 19).replace(/[-:]/g, "").replace("T", "-");
|
|
180
|
+
const file = join(dir, `gu-${stamp}.db`);
|
|
181
|
+
let db;
|
|
182
|
+
try {
|
|
183
|
+
mkdirSync(dir, { recursive: true });
|
|
184
|
+
if (existsSync(file)) rmSync(file);
|
|
185
|
+
db = open(path);
|
|
186
|
+
db.prepare("VACUUM INTO ?").run(file);
|
|
187
|
+
} catch (e) {
|
|
188
|
+
return { error: String(e?.message ?? e) };
|
|
189
|
+
} finally {
|
|
190
|
+
try { db?.close(); } catch { /* closed */ }
|
|
191
|
+
}
|
|
192
|
+
const all = readdirSync(dir).filter((f) => /^gu-\d{8}-\d{6}\.db$/.test(f)).sort().reverse();
|
|
193
|
+
const removed = [];
|
|
194
|
+
for (const old of all.slice(Math.max(1, keep))) {
|
|
195
|
+
try { rmSync(join(dir, old)); removed.push(old); } catch { /* left */ }
|
|
196
|
+
}
|
|
197
|
+
return { file, bytes: statSync(file).size, removed };
|
|
198
|
+
}
|
package/hooks-config.mjs
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
* HOOKS — commands gu runs at fixed moments of a turn (task #270). Where they are set, and which
|
|
3
3
|
* ones a turn gets.
|
|
4
4
|
*
|
|
5
|
-
* ~/.
|
|
6
|
-
* <project>/.
|
|
5
|
+
* ~/.gu/settings.json yours, every folder
|
|
6
|
+
* <project>/.gu/settings.json this project's — run only once you approve them here
|
|
7
7
|
*
|
|
8
8
|
* { "hooks": { "<event>": [ { "matcher": "edit_file|create_file",
|
|
9
9
|
* "hooks": [ { "type": "command", "command": "python3",
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
* What gu cannot honour is SAID, never skipped in silence: an event gu has no moment for
|
|
32
32
|
* (PreToolUse — a guard someone may be relying on), a hook that is not a command, a hook limited by
|
|
33
33
|
* an `if` rule gu cannot evaluate. Read-only: gu never writes Claude's settings files; the approval
|
|
34
|
-
* of a project's hooks is still kept in ~/.
|
|
34
|
+
* of a project's hooks is still kept in ~/.gu/settings.json.
|
|
35
35
|
*
|
|
36
36
|
* THE SESSION. onStart fires on the first turn of a gu session. The terminal writes a new session
|
|
37
37
|
* id into the folder's session file when it starts (and on /reset); sessionForTurn reads it back so
|
|
@@ -163,7 +163,7 @@ export function hooksFingerprint(hooks) {
|
|
|
163
163
|
|
|
164
164
|
/** How each source's files are NAMED to the user (labels in messages — not paths to open). */
|
|
165
165
|
const FILE_LABELS = {
|
|
166
|
-
gu: { user: "~/.
|
|
166
|
+
gu: { user: "~/.gu/settings.json", project: ".gu/settings.json", shown: "./.gu/settings.json" },
|
|
167
167
|
claude: { user: "~/.claude/settings.json", project: ".claude/settings.json", shown: "./.claude/settings.json" },
|
|
168
168
|
};
|
|
169
169
|
|
package/image-paste.mjs
CHANGED
|
@@ -9,9 +9,9 @@ import { readFileSync } from "node:fs";
|
|
|
9
9
|
*
|
|
10
10
|
* How it reaches the model. The API passes the message TEXT and nothing else, so the image rides
|
|
11
11
|
* in the text as a marker: the input shows "[Image #1]" (like "[Pasted text #1]"), and the line
|
|
12
|
-
* that is sent carries "[Image #1: /Users/…/.
|
|
12
|
+
* that is sent carries "[Image #1: /Users/…/.gu/images/…png]". The agent reads the file,
|
|
13
13
|
* attaches it to the request, and puts "[Image #1]" back in the text it shows the model. Files
|
|
14
|
-
* are copied into ~/.
|
|
14
|
+
* are copied into ~/.gu/images first; the agent reads images from there and nowhere else.
|
|
15
15
|
*
|
|
16
16
|
* Two ways in:
|
|
17
17
|
* · a key that reads the clipboard's image (a copied screenshot). Terminals paste only text, so
|
|
@@ -64,7 +64,7 @@ function fileImageKind(path) {
|
|
|
64
64
|
|
|
65
65
|
const NOT_AN_IMAGE = "that file is not an image (png, jpg, gif or webp)";
|
|
66
66
|
|
|
67
|
-
export const imagesDir = (home = homedir()) => join(home, ".
|
|
67
|
+
export const imagesDir = (home = homedir()) => join(home, ".gu", "images");
|
|
68
68
|
|
|
69
69
|
/**
|
|
70
70
|
* WHICH CODERS MAY BE SENT IMAGES (#284, #316): the list in image-capable-coders.json, shared with
|
|
@@ -90,10 +90,10 @@ export function cloudImageCoders(rows) {
|
|
|
90
90
|
}
|
|
91
91
|
|
|
92
92
|
/**
|
|
93
|
-
* The cloud list this gu last read, kept in ~/.
|
|
93
|
+
* The cloud list this gu last read, kept in ~/.gu/image-models.json so a start without network
|
|
94
94
|
* still knows it — and so the agent (gonext_agent_chat.py) reads the very same list.
|
|
95
95
|
*/
|
|
96
|
-
export const imageModelsFile = (home = homedir()) => join(home, ".
|
|
96
|
+
export const imageModelsFile = (home = homedir()) => join(home, ".gu", "image-models.json");
|
|
97
97
|
let cloudCoders = [];
|
|
98
98
|
export function setCloudImageCoders(list) {
|
|
99
99
|
cloudCoders = Array.isArray(list) ? list.filter((c) => c && c.host && c.exact) : [];
|
|
@@ -125,7 +125,7 @@ export function coderTakesImagesFor(url, model = "", coders = [...IMAGE_CODERS,
|
|
|
125
125
|
export function saveCloudImageCoders(rows, home = homedir()) {
|
|
126
126
|
const coders = cloudImageCoders(rows);
|
|
127
127
|
try {
|
|
128
|
-
mkdirSync(join(home, ".
|
|
128
|
+
mkdirSync(join(home, ".gu"), { recursive: true });
|
|
129
129
|
writeFileSync(imageModelsFile(home), JSON.stringify({ savedAt: new Date().toISOString(), coders }, null, 1) + "\n");
|
|
130
130
|
} catch {
|
|
131
131
|
/* not saved: this session still uses it */
|
|
@@ -207,7 +207,7 @@ function newImagePath(ext, home) {
|
|
|
207
207
|
return join(dir, `${stamp}-${Math.random().toString(36).slice(2, 8)}${ext}`);
|
|
208
208
|
}
|
|
209
209
|
|
|
210
|
-
/** Copy an image file into ~/.
|
|
210
|
+
/** Copy an image file into ~/.gu/images. → { path } or { error }. */
|
|
211
211
|
export function storeImageFile(src, { home = homedir() } = {}) {
|
|
212
212
|
let size = 0;
|
|
213
213
|
try {
|
|
@@ -258,7 +258,7 @@ export function clipboardImageCommand(dest, platform = process.platform) {
|
|
|
258
258
|
return { cmd: "sh", args: ["-c", `(wl-paste --type image/png 2>/dev/null || xclip -selection clipboard -t image/png -o 2>/dev/null) > '${dest.replace(/'/g, "'\\''")}' && [ -s '${dest.replace(/'/g, "'\\''")}' ]`] };
|
|
259
259
|
}
|
|
260
260
|
|
|
261
|
-
/** Save the clipboard's image into ~/.
|
|
261
|
+
/** Save the clipboard's image into ~/.gu/images. → { path } | { error } | { none: true }. */
|
|
262
262
|
export function clipboardImageToFile({ home = homedir(), platform = process.platform, run = spawnSync } = {}) {
|
|
263
263
|
const dest = newImagePath(".png", home);
|
|
264
264
|
const { cmd, args } = clipboardImageCommand(dest, platform);
|
package/install-path.mjs
CHANGED
|
@@ -127,7 +127,7 @@ export function addPathBlock({ dir, home = realUserHome() }) {
|
|
|
127
127
|
return { wrote, already, targets };
|
|
128
128
|
}
|
|
129
129
|
|
|
130
|
-
/** Under `sudo npm i -g` a file written into ~/.
|
|
130
|
+
/** Under `sudo npm i -g` a file written into ~/.gu would be root's: gu could not delete it. */
|
|
131
131
|
// A function DECLARATION: main() runs at the top of this file, before any `const` below exists.
|
|
132
132
|
function underSudo() {
|
|
133
133
|
return Boolean(process.env.SUDO_UID && process.getuid && process.getuid() === 0);
|
package/log-level.mjs
CHANGED
|
@@ -26,7 +26,7 @@ import { readFileSync, unlinkSync } from "node:fs";
|
|
|
26
26
|
import { homedir } from "node:os";
|
|
27
27
|
import { join } from "node:path";
|
|
28
28
|
|
|
29
|
-
export const LEASE_FILE = join(homedir(), ".
|
|
29
|
+
export const LEASE_FILE = join(homedir(), ".gu", "log-detail.json");
|
|
30
30
|
|
|
31
31
|
/** Is that process still running? (signal 0 asks without sending anything.) */
|
|
32
32
|
export function pidAlive(pid) {
|
package/log-policy.mjs
CHANGED
|
@@ -19,7 +19,7 @@ import { copyFile, readdir, readFile, rename, stat, truncate, unlink, writeFile
|
|
|
19
19
|
import { homedir } from "node:os";
|
|
20
20
|
import { join } from "node:path";
|
|
21
21
|
|
|
22
|
-
export const POLICY_FILE = join(homedir(), ".
|
|
22
|
+
export const POLICY_FILE = join(homedir(), ".gu", "log-policy.json");
|
|
23
23
|
export const REFRESH_MS = 5 * 60_000;
|
|
24
24
|
export const ROTATE = { maxBytes: 20 * 1024 * 1024, keep: 3 };
|
|
25
25
|
export const RUN_LOGS = { maxAgeMs: 7 * 86_400_000, maxFiles: 200 };
|
package/lsp-host.mjs
CHANGED
|
@@ -130,7 +130,7 @@ export class LspHost {
|
|
|
130
130
|
return entry;
|
|
131
131
|
}
|
|
132
132
|
|
|
133
|
-
/** Install a server into ~/.
|
|
133
|
+
/** Install a server into ~/.gu/lsp (npm), once at a time per language. */
|
|
134
134
|
install(lang) {
|
|
135
135
|
if (this.installing.has(installKey(lang))) return this.installing.get(installKey(lang));
|
|
136
136
|
const { cmd, args } = installCommand(lang, this.home);
|
|
@@ -329,7 +329,7 @@ export class LspHost {
|
|
|
329
329
|
}
|
|
330
330
|
|
|
331
331
|
/**
|
|
332
|
-
* Serve a host on 127.0.0.1 (a free port) and write where to reach it to ~/.
|
|
332
|
+
* Serve a host on 127.0.0.1 (a free port) and write where to reach it to ~/.gu/lsp-host.json.
|
|
333
333
|
* → { url, token, host, close }.
|
|
334
334
|
*/
|
|
335
335
|
export async function serveLspHost({ home, log = () => {}, host = new LspHost({ home, log }) } = {}) {
|
package/lsp-registry.mjs
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* see the table's `licence`). Claude Code's plugins are the same idea — a few lines saying which
|
|
10
10
|
* program serves which file types — without the install: gu offers to install it, with consent.
|
|
11
11
|
*
|
|
12
|
-
* The user's choices are ~/.
|
|
12
|
+
* The user's choices are ~/.gu/lsp-state.json, written by the terminal (the offer, /lsp) and
|
|
13
13
|
* read by the worker's host (lsp-host.mjs):
|
|
14
14
|
* { "languages": { "<id>": "on" | "off" | "never" }, "neverAsk": false, "ignored": 0 }
|
|
15
15
|
*/
|
|
@@ -260,12 +260,12 @@ export const LSP_LANGUAGES = BUILTIN_LANGUAGES;
|
|
|
260
260
|
* <workspace>/.gu/lsp.json this project, gu's file
|
|
261
261
|
* <workspace>/.lsp.json this project, Claude Code's plugin file (a team that set it up for
|
|
262
262
|
* Claude Code gets the same servers in gu)
|
|
263
|
-
* ~/.
|
|
263
|
+
* ~/.gu/lsp.json every project on this computer
|
|
264
264
|
* Each holds either Claude Code's shape — { "<id>": { command, args, extensionToLanguage, env,
|
|
265
265
|
* initializationOptions, settings, startupTimeout, … } } — or the same map under "lspServers".
|
|
266
266
|
*/
|
|
267
267
|
export const customLspFiles = (home, workspace) =>
|
|
268
|
-
[workspace && join(workspace, ".gu", "lsp.json"), workspace && join(workspace, ".lsp.json"), home && join(home, ".
|
|
268
|
+
[workspace && join(workspace, ".gu", "lsp.json"), workspace && join(workspace, ".lsp.json"), home && join(home, ".gu", "lsp.json")].filter(Boolean);
|
|
269
269
|
|
|
270
270
|
const ID_RE = /^[A-Za-z0-9][\w.-]{0,40}$/;
|
|
271
271
|
|
|
@@ -355,9 +355,9 @@ export function languageFor(file, langs = BUILTIN_LANGUAGES) {
|
|
|
355
355
|
export const lspExtensions = (langs = BUILTIN_LANGUAGES) => [...new Set(langs.flatMap((l) => Object.keys(l.exts)))];
|
|
356
356
|
|
|
357
357
|
/** Where gu installs npm servers: its own folder, no admin rights, nothing global. */
|
|
358
|
-
export const lspInstallDir = (home) => join(home, ".
|
|
359
|
-
export const lspStatePath = (home) => join(home, ".
|
|
360
|
-
export const lspHostPath = (home) => join(home, ".
|
|
358
|
+
export const lspInstallDir = (home) => join(home, ".gu", "lsp");
|
|
359
|
+
export const lspStatePath = (home) => join(home, ".gu", "lsp-state.json");
|
|
360
|
+
export const lspHostPath = (home) => join(home, ".gu", "lsp-host.json");
|
|
361
361
|
|
|
362
362
|
// ---------------------------------------------------------------------------------------------
|
|
363
363
|
// the user's choices
|
|
@@ -408,7 +408,7 @@ export function applyOfferAnswer(state, id, choice) {
|
|
|
408
408
|
|
|
409
409
|
/** The offer's rows, the first highlighted. Swift needs no download, so it is "turn on". */
|
|
410
410
|
export function offerRows(lang, { needsInstall }) {
|
|
411
|
-
const install = lang.tool ? `Yes, install ${lang.server} (${lang.tool.what})` : `Yes, install ${lang.server} (${lang.size}, into ~/.
|
|
411
|
+
const install = lang.tool ? `Yes, install ${lang.server} (${lang.tool.what})` : `Yes, install ${lang.server} (${lang.size}, into ~/.gu/lsp)`;
|
|
412
412
|
return [
|
|
413
413
|
needsInstall ? install : "Yes, turn it on",
|
|
414
414
|
"Not now",
|
|
@@ -450,7 +450,7 @@ export function xcodeDeveloperDir({ exists = existsSync, selected = "" } = {}) {
|
|
|
450
450
|
|
|
451
451
|
/**
|
|
452
452
|
* How to start a language's server here → { cmd, args, env } or null (not installed).
|
|
453
|
-
* Order: gu's own install (~/.
|
|
453
|
+
* Order: gu's own install (~/.gu/lsp), then PATH; Swift on macOS through xcrun with the Xcode
|
|
454
454
|
* picked above.
|
|
455
455
|
*/
|
|
456
456
|
export function resolveServer(lang, { home, platform = process.platform, env = process.env, run = execFileSync, exists = existsSync } = {}) {
|
|
@@ -494,7 +494,7 @@ export function resolveServer(lang, { home, platform = process.platform, env = p
|
|
|
494
494
|
}
|
|
495
495
|
|
|
496
496
|
/**
|
|
497
|
-
* Can gu install this language's server itself? npm ones always (into ~/.
|
|
497
|
+
* Can gu install this language's server itself? npm ones always (into ~/.gu/lsp); Go and Rust
|
|
498
498
|
* when their own tool (`go`, `rustup`) is on this computer. Swift and C/C++ come with their toolchain.
|
|
499
499
|
*/
|
|
500
500
|
export function canInstall(lang, { env = process.env, platform = process.platform } = {}) {
|
package/mcp-command.mjs
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* list every server, whether it connects, how many tools (the default)
|
|
5
5
|
* tools <name> that server's tools
|
|
6
6
|
* add … `claude mcp add`'s shape; `/mcp add` alone asks step by step
|
|
7
|
-
* remove <name> from your ~/.
|
|
7
|
+
* remove <name> from your ~/.gu/mcp.json
|
|
8
8
|
* enable|disable <name> keep it configured, stop starting it
|
|
9
9
|
* approve|unapprove <name> a project's .mcp.json server, for this folder
|
|
10
10
|
* allow <name> [tool] its tools run without asking (all, or one)
|