@tiens.nguyen/gu-cli 1.0.940 → 1.0.942

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.
@@ -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
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * GH #595: WHICH TASK the memory skill is recording this session's work under — on gu's bar, so a
3
+ * misfiling is seen before the work is done, not after. Reported 2026-12-04: a morning's laggy-call
4
+ * investigation in meetings was filed under the open JBL task, and nothing on screen said so.
5
+ *
6
+ * gu and Claude Code share ONE memory (the same skill runtime, the same .claude-memory in the
7
+ * project), so the question is never "which skill" — it is "which task". The memory's own CLI
8
+ * answers it (current-task: what a message naming no task would be filed under), and /task
9
+ * switches it (set-task).
10
+ */
11
+ import { execFile } from "node:child_process";
12
+ import { existsSync } from "node:fs";
13
+ import { dirname, join } from "node:path";
14
+
15
+ /** The memory runtime gu's hooks run, from the hooks config → { python, cli } or null when not installed. */
16
+ export function memoryRuntime(hooks) {
17
+ for (const groups of Object.values(hooks ?? {})) {
18
+ for (const g of Array.isArray(groups) ? groups : []) {
19
+ for (const h of g?.hooks ?? []) {
20
+ const script = (h?.args ?? []).find((a) => /memory_hook\.py$/.test(String(a)));
21
+ if (!script || !h.command) continue;
22
+ const cli = join(dirname(dirname(String(script))), "memory_cli.py");
23
+ if (existsSync(cli)) return { python: String(h.command), cli };
24
+ }
25
+ }
26
+ }
27
+ return null;
28
+ }
29
+
30
+ function run(runtime, args, { timeoutMs = 8000, execImpl = execFile } = {}) {
31
+ return new Promise((resolve) => {
32
+ execImpl(runtime.python, [runtime.cli, ...args], { timeout: timeoutMs, encoding: "utf8" }, (err, stdout) => {
33
+ if (err) return resolve(null);
34
+ try {
35
+ resolve(JSON.parse(String(stdout)));
36
+ } catch {
37
+ resolve(null);
38
+ }
39
+ });
40
+ });
41
+ }
42
+
43
+ /** → { project, task: {id,title,status}|null, chosen, open: [...] } or null (no memory here / not readable). */
44
+ export async function currentTask({ runtime, cwd, session = "", execImpl } = {}) {
45
+ if (!runtime || !cwd) return null;
46
+ const r = await run(runtime, ["current-task", "--cwd", cwd, "--session", session], { execImpl });
47
+ return r?.current ?? null;
48
+ }
49
+
50
+ /** File this session's next steps under task `id`. → { id, title } or null. */
51
+ export async function setTask({ runtime, cwd, session, id, execImpl } = {}) {
52
+ if (!runtime || !cwd || !session) return null;
53
+ const r = await run(runtime, ["set-task", "--cwd", cwd, "--session", session, "--task", String(id)], { execImpl });
54
+ return r?.task ?? null;
55
+ }
56
+
57
+ const clip = (s, n) => {
58
+ const a = Array.from(String(s ?? "").replace(/\s+/g, " ").trim());
59
+ return a.length <= n ? a.join("") : a.slice(0, Math.max(1, n - 1)).join("") + "…";
60
+ };
61
+
62
+ /**
63
+ * The bar's text → { text, warn } ("" when the memory skill is in neither skill set).
64
+ *
65
+ * GH #601 (owner, with a screenshot): "memory" in yellow and (/task) in yellow — NO task title after
66
+ * it; the task is what /task shows and changes. Whose skills stays, as one word (GH #595: a folder uses
67
+ * Claude Code's skills or gu's own, /switch-skill, and only one set may have the memory skill):
68
+ * "◆ gu's memory (/task)". Memory only in the OTHER set → "◆ gu's memory off — /switch-skill".
69
+ */
70
+ export function memoryBarText(_cur, room = 40, { label = "", active = true, otherHas = false } = {}) {
71
+ const whose = /claude/i.test(label) ? "Claude's " : label ? "gu's " : "";
72
+ if (!active) {
73
+ if (!otherHas) return { text: "", warn: false };
74
+ return { text: clip(`◆ ${whose}memory off — /switch-skill`, room), warn: true };
75
+ }
76
+ return { text: clip(`◆ ${whose}memory`, Math.max(4, room - 9)) + " (/task)", warn: true };
77
+ }
78
+
79
+ /** The /task picker's rows: the open tasks, the current one marked. */
80
+ export function taskPickerLabels(cur, width = 80) {
81
+ const rows = Array.isArray(cur?.open) ? cur.open : [];
82
+ return rows.map((t) => {
83
+ const mark = cur?.task && t.id === cur.task.id ? "● " : " ";
84
+ const status = t.status === "in_progress" ? "" : ` · ${t.status}`;
85
+ return mark + clip(`#${t.id} ${t.title}`, Math.max(20, width - 12 - status.length)) + status;
86
+ });
87
+ }
@@ -28,7 +28,9 @@ export const SUGGESTION_MAX_CHARS = 80;
28
28
  /** Shorter than this, an answer is a greeting or a one-liner: nothing follows from it. */
29
29
  export const MIN_ANSWER_CHARS = 40;
30
30
  /** The side call waits this long at most; after that there is simply no suggestion. */
31
- export const SUGGEST_TIMEOUT_MS = 8_000;
31
+ // GH #587: a reasoning coder (deepseek-v4-pro) thinks first — 8s was often over before it answered.
32
+ // Nothing waits on it: a late suggestion is still shown if the prompt is still empty.
33
+ export const SUGGEST_TIMEOUT_MS = 20_000;
32
34
 
33
35
  /** Gate 1: is this turn worth asking about at all? */
34
36
  export function shouldSuggest({ question = "", answer = "", enabled = true } = {}) {
@@ -41,12 +43,15 @@ export function shouldSuggest({ question = "", answer = "", enabled = true } = {
41
43
 
42
44
  const SYSTEM =
43
45
  "You predict the user's NEXT message to a coding assistant in a terminal. You are shown the " +
44
- "user's last request and the end of the assistant's answer. If the answer clearly leads to ONE " +
45
- "obvious next message — it ends by asking the user to confirm or choose (for example \"Shall I " +
46
- "merge?\"), or it offers one specific next step — reply with ONLY that message, written as the " +
47
- "user would type it: 2 to 12 words, an instruction or a short reply such as \"yes, merge it\", " +
48
- "in the language the user writes in. If there is no single obvious next message, reply with " +
49
- "exactly NONE. No quotes, no explanation, never a question.";
46
+ "user's last request and the end of the assistant's answer. If the answer leads to a next " +
47
+ "message — it asks the user to confirm or choose (for example \"Shall I merge?\"), offers a " +
48
+ "next step, or lists what is \"left for you\" / waits for the user's go-ahead — reply with ONLY " +
49
+ "that message, written as the user would type it: 2 to 12 words, an instruction or a short " +
50
+ "reply such as \"yes, merge it\" or \"go ahead, upload the DMG\", in the language the user " +
51
+ "writes in. When it offers SEVERAL options, pick the one the answer recommends, else the " +
52
+ "simplest one, and name it (\"just upload the notarized DMG\") — never a bare \"yes\" that " +
53
+ "could mean either. Reply with exactly NONE only when the answer leads nowhere (a plain fact, " +
54
+ "an explanation, a finished task with nothing offered). No quotes, no explanation, never a question.";
50
55
 
51
56
  const tail = (s, n) => {
52
57
  const chars = Array.from(String(s ?? ""));
@@ -58,7 +63,7 @@ export function suggestionRequest(model, { question = "", answer = "" } = {}) {
58
63
  return {
59
64
  model,
60
65
  stream: false,
61
- max_tokens: 300, // room for a reasoning model to think briefly and still answer
66
+ max_tokens: 800, // GH #587: room for a reasoning model to think and still answer (300 could run out first)
62
67
  messages: [
63
68
  { role: "system", content: SYSTEM },
64
69
  { role: "user", content: `User's request:\n${q}\n\nEnd of the assistant's answer:\n${tail(answer, ANSWER_TAIL_MAX)}` },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiens.nguyen/gu-cli",
3
- "version": "1.0.940",
3
+ "version": "1.0.942",
4
4
  "description": "gu: the coding agent in your terminal. It reads your repo, makes the change and runs the tests, with your own models (Ollama or any OpenAI-compatible provider). Free installs keep the agent, its API and its database on your machine. macOS, Linux and Windows.",
5
5
  "keywords": [
6
6
  "ai",
@@ -121,6 +121,8 @@
121
121
  "support-bundle.mjs",
122
122
  "support-command.mjs",
123
123
  "clear-logs.mjs",
124
+ "gudb-size.mjs",
125
+ "memory-task.mjs",
124
126
  "platform-tools.mjs",
125
127
  "job-pools.mjs",
126
128
  "agent-stop.mjs",
@@ -201,6 +203,7 @@
201
203
  "gu_free_budget.py",
202
204
  "turn-notes.mjs",
203
205
  "gu_hooks.py",
206
+ "gu_turn_trail.py",
204
207
  "prompt_scaffold_check.py",
205
208
  "gonext_transcribe.py",
206
209
  "gonext_mlx_embed.py",
@@ -1977,6 +1977,9 @@ export function classifyTurnFailure(message) {
1977
1977
  // backend patterns below and was captioned "the coding model's backend failed … /model to switch
1978
1978
  // coder" — wrong on both counts, and switching coder cannot help. The message itself already
1979
1979
  // says the next step. Both wordings: this gu's, and 1.0.724's ("could not be loaded (HTTP 503)").
1980
+ // ACCESS — GH #603: the account's Cloud link was removed. Nothing ran and nothing in gu fixes it;
1981
+ // "/model to switch coder" or "continue" would both be wrong.
1982
+ if (/Your Cloud access was removed/i.test(t)) return "access";
1980
1983
  if (/The agent couldn't start|The agent's prompt (could not be loaded|could not be used)|agent's prompt templates could not be loaded/i.test(t)) {
1981
1984
  return "setup";
1982
1985
  }
@@ -2086,6 +2089,7 @@ export function retryAdvice({ resumable = true, failures = 1, kind = "task", min
2086
2089
  // GitHub #129: name the missing piece and the one step that fixes it.
2087
2090
  return 'the agent framework (smolagents + openai) is not installed in this machine\'s Python, so nothing ran — run /doctor to install it, or restart gu and answer yes to "Install the agent framework now?", then "continue" sends your question again.';
2088
2091
  }
2092
+ if (kind === "access") return null; // GH #603: the message says who to ask; retrying can't help
2089
2093
  if (kind === "setup") {
2090
2094
  // Nothing ran, so there is nothing to diagnose in the model or the question — only the step the
2091
2095
  // message above names. "continue" is right AFTER that step, never before.
@@ -2752,7 +2756,31 @@ export function agentPickerItems(rows, { width = 80 } = {}) {
2752
2756
  return out;
2753
2757
  }
2754
2758
 
2759
+ /**
2760
+ * The other agents as a PANEL in place of the input box (GH #586) — what the "N agents running
2761
+ * (click)" link opens while this terminal's own turn runs. The picker can't be used then
2762
+ * (switching to another agent is a turn of its own), and the click used to do nothing at all.
2763
+ * items: agentPickerItems(); sel: the highlighted row; note: one line about what just happened.
2764
+ */
2765
+ export function agentsPanelRows({ items = [], sel = 0, width = 80, rows = 10, note = "", gutter = " ",
2766
+ style = {} } = {}) {
2767
+ const S = { title: (t) => t, mark: (t) => t, dim: (t) => t, ...style };
2768
+ const room = Math.max(1, rows - 2); // title + footer
2769
+ const n = items.length;
2770
+ const at = Math.min(Math.max(0, sel | 0), Math.max(0, n - 1));
2771
+ const from = Math.max(0, Math.min(at - room + 1, n - room));
2772
+ const out = [gutter + S.title(n ? `Your other running agents (${n})` : "No other agents running for your account.")];
2773
+ for (let i = from; i < Math.min(n, from + room); i++) {
2774
+ const label = items[i].label.slice(0, Math.max(10, width - gutter.length - 3));
2775
+ out.push(gutter + (i === at ? S.mark("▸ " + label) : " " + label));
2776
+ }
2777
+ out.push(gutter + S.dim(note || (n ? "↑↓ choose · s stop it · Esc close — to switch to one, click again after this turn"
2778
+ : "Esc close")));
2779
+ return out;
2780
+ }
2781
+
2755
2782
  export const HIDDEN_COMMANDS = [
2783
+ "/tasks", // GH #595: the same as /task — listed once
2756
2784
  "/provider", // and /providers — /model's picker carries "add or change an
2757
2785
  "/providers", // OpenAI-compatible provider…" in every branch, so listing this
2758
2786
  // too offered two doors into one setting (reported as confusing)
@@ -3629,3 +3657,23 @@ export function commandBlockRows(text, { width = 80, indent = " ", collapsed =
3629
3657
  const hidden = rows.length - maxRows;
3630
3658
  return [...rows.slice(0, maxRows), clipVisible(indent + `… +${hidden} more rows — click to expand (ctrl+o)`, width)];
3631
3659
  }
3660
+
3661
+ /**
3662
+ * GH #593: a slash command typed DURING a turn — never a note to the agent.
3663
+ * "now" — only shows something, so it runs at once (the turn keeps going);
3664
+ * "after" — changes the session or needs the screen, so it runs when the turn ends;
3665
+ * null — not one of gu's commands ("/Users/me/app is broken" stays a message to the agent).
3666
+ * /model and /task have their own mid-turn handling (GH #588, #595) and are not decided here.
3667
+ */
3668
+ export const MID_TURN_NOW = new Set(["/", "/help", "/cost", "/prices", "/shells", "/suggestions", "/budget"]);
3669
+ // Shown, not changed — but only bare: "/mcp add …" and "/hooks off" change things and wait.
3670
+ export const MID_TURN_NOW_BARE = new Set(["/mcp", "/hooks"]);
3671
+ export function midTurnCommandKind(line, known = []) {
3672
+ const s = String(line ?? "").trim();
3673
+ if (!s.startsWith("/")) return null;
3674
+ const word = s.split(/\s+/)[0].toLowerCase();
3675
+ const bare = word === s.toLowerCase();
3676
+ if (MID_TURN_NOW.has(word)) return "now";
3677
+ if (MID_TURN_NOW_BARE.has(word)) return bare ? "now" : "after";
3678
+ return known.includes(word) ? "after" : null;
3679
+ }