@tiens.nguyen/gu-cli 1.0.931 → 1.0.932

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,137 @@
1
+ /**
2
+ * THE NEXT MESSAGE, SUGGESTED (GH #536) — pure helpers; gu-repl.mjs draws and wires it.
3
+ *
4
+ * Like Claude Code: after some turns the empty input box shows a dim suggestion for what to send
5
+ * next, and Tab puts it into the input (to edit, or send with Enter). SOME turns, not every turn —
6
+ * an answer that ends "Shall I merge?" has an obvious next message ("yes, merge it"); a plain
7
+ * factual answer has none, and a guess there is noise the user learns to ignore.
8
+ *
9
+ * TWO GATES decide that, and both must pass:
10
+ * 1. shouldSuggest — cheap rules before any call: a completed turn, a real question (not a
11
+ * /command), an answer long enough to lead somewhere.
12
+ * 2. The model — one small side call to the coder the turn ran on (the same road as the window
13
+ * title, terminal-title.mjs), told to answer NONE unless the next message is obvious. Its
14
+ * reply then goes through pickSuggestion, which refuses anything that is not a short reply
15
+ * the user would plausibly type.
16
+ *
17
+ * Pure: no terminal and no network of its own. `fetchImpl` is injected.
18
+ */
19
+
20
+ import { chatEndpoint, cleanTitleText } from "./terminal-title.mjs";
21
+
22
+ /** How much of the question and of the answer's END the model is shown. The ask is at the end. */
23
+ export const QUESTION_MAX = 600;
24
+ export const ANSWER_TAIL_MAX = 2400;
25
+ /** A suggestion is something typed in one go: a few words, one row. */
26
+ export const SUGGESTION_MAX_WORDS = 12;
27
+ export const SUGGESTION_MAX_CHARS = 80;
28
+ /** Shorter than this, an answer is a greeting or a one-liner: nothing follows from it. */
29
+ export const MIN_ANSWER_CHARS = 40;
30
+ /** The side call waits this long at most; after that there is simply no suggestion. */
31
+ export const SUGGEST_TIMEOUT_MS = 8_000;
32
+
33
+ /** Gate 1: is this turn worth asking about at all? */
34
+ export function shouldSuggest({ question = "", answer = "", enabled = true } = {}) {
35
+ if (!enabled) return false;
36
+ const q = String(question ?? "").trim();
37
+ const a = String(answer ?? "").trim();
38
+ if (!q || q.startsWith("/")) return false;
39
+ return a.length >= MIN_ANSWER_CHARS;
40
+ }
41
+
42
+ const SYSTEM =
43
+ "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.";
50
+
51
+ const tail = (s, n) => {
52
+ const chars = Array.from(String(s ?? ""));
53
+ return chars.length <= n ? chars.join("") : "…" + chars.slice(chars.length - n).join("");
54
+ };
55
+
56
+ export function suggestionRequest(model, { question = "", answer = "" } = {}) {
57
+ const q = Array.from(cleanTitleText(question)).slice(0, QUESTION_MAX).join("");
58
+ return {
59
+ model,
60
+ stream: false,
61
+ max_tokens: 300, // room for a reasoning model to think briefly and still answer
62
+ messages: [
63
+ { role: "system", content: SYSTEM },
64
+ { role: "user", content: `User's request:\n${q}\n\nEnd of the assistant's answer:\n${tail(answer, ANSWER_TAIL_MAX)}` },
65
+ ],
66
+ };
67
+ }
68
+
69
+ // Something that looks like a credential never goes into the input box: an API key prefix, or a
70
+ // long unbroken run of letters and digits.
71
+ const SECRETISH = /\b(?:sk|pk|rk|ghp|gho|xox[abp]|AKIA|AIza)[-_A-Za-z0-9]{8,}|[A-Za-z0-9+/_-]{32,}/;
72
+
73
+ /**
74
+ * Gate 2's second half: the suggestion out of the model's reply, or "" when it is not one.
75
+ * Refused: NONE, more than one line, too long or too short, a question, the request repeated,
76
+ * a /command (gu's own are typed, not guessed), anything that looks like a secret.
77
+ */
78
+ export function pickSuggestion(body, { question = "" } = {}) {
79
+ let raw = body?.choices?.[0]?.message?.content;
80
+ if (typeof raw !== "string") return "";
81
+ raw = raw.replace(/<think>[\s\S]*?<\/think>/gi, "").trim();
82
+ const lines = raw.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
83
+ if (lines.length !== 1) return "";
84
+ const line = cleanTitleText(lines[0])
85
+ .replace(/^(?:suggestion|next message|user)\s*:\s*/i, "")
86
+ .replace(/^["'“”‘’`*]+|["'“”‘’`*]+$/gu, "")
87
+ .replace(/[.。]+$/u, "")
88
+ .trim();
89
+ if (!line || /^none\b/i.test(line)) return "";
90
+ if (line.startsWith("/")) return "";
91
+ if (/[??]$/u.test(line)) return "";
92
+ const words = line.split(/\s+/).length;
93
+ if (words > SUGGESTION_MAX_WORDS || Array.from(line).length > SUGGESTION_MAX_CHARS) return "";
94
+ if (Array.from(line).length < 2) return "";
95
+ const norm = (s) => cleanTitleText(s).toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim();
96
+ if (norm(line) === norm(question)) return "";
97
+ if (SECRETISH.test(line)) return "";
98
+ return line;
99
+ }
100
+
101
+ /**
102
+ * Ask the coder for the next message. → the suggestion, or "" for every reason there is not one.
103
+ * `target` is { url, model } (titleModel in terminal-title.mjs); `apiKey` goes as a Bearer token.
104
+ * Never throws: it runs after a turn, beside the prompt, and must not be able to disturb either.
105
+ */
106
+ export async function suggestNext(
107
+ { question = "", answer = "" } = {},
108
+ { fetchImpl = fetch, timeoutMs = SUGGEST_TIMEOUT_MS, target = null, apiKey = "" } = {},
109
+ ) {
110
+ if (!target?.url || !target?.model) return "";
111
+ try {
112
+ const res = await fetchImpl(chatEndpoint(target.url), {
113
+ method: "POST",
114
+ headers: { "Content-Type": "application/json", ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}) },
115
+ body: JSON.stringify(suggestionRequest(target.model, { question, answer })),
116
+ signal: AbortSignal.timeout(timeoutMs),
117
+ });
118
+ if (!res?.ok) return "";
119
+ return pickSuggestion(await res.json(), { question });
120
+ } catch {
121
+ return "";
122
+ }
123
+ }
124
+
125
+ /** The ghost row's text: the suggestion, then how to take it. The caller paints it dim. */
126
+ export const ghostText = (suggestion) => (suggestion ? `${suggestion} (Tab)` : "");
127
+
128
+ /** `/suggestions`, `/suggestions on`, `/suggestions off` → the new setting (a bare one flips it). */
129
+ export function suggestionsToggle(arg, current) {
130
+ const a = String(arg ?? "").trim().toLowerCase();
131
+ if (a === "on") return true;
132
+ if (a === "off") return false;
133
+ return !current;
134
+ }
135
+
136
+ /** The saved setting: the file holds "off" when the user turned it off. Default: on. */
137
+ export const suggestionsOnFromFile = (text) => String(text ?? "").trim().toLowerCase() !== "off";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiens.nguyen/gu-cli",
3
- "version": "1.0.931",
3
+ "version": "1.0.932",
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",
@@ -99,6 +99,13 @@
99
99
  "preset-editor.mjs",
100
100
  "preset-apply.mjs",
101
101
  "model-prices.mjs",
102
+ "next-suggestion.mjs",
103
+ "autocompact.mjs",
104
+ "lsp-client.mjs",
105
+ "lsp-host.mjs",
106
+ "win-shell.mjs",
107
+ "setup-fixes.mjs",
108
+ "lsp-registry.mjs",
102
109
  "model-limits-notice.mjs",
103
110
  "device-login.mjs",
104
111
  "daemon-control.mjs",
@@ -186,6 +193,7 @@
186
193
  "gu_skills.py",
187
194
  "gu_test_digest.py",
188
195
  "gu_browser.py",
196
+ "gu_gif.py",
189
197
  "gu_powershell.py",
190
198
  "gu_turn_notes.py",
191
199
  "gu_free_budget.py",
@@ -40,9 +40,20 @@ export const MEANWHILE = "Left alone. `gu-cli` and `gu.cmd` both run this progra
40
40
  */
41
41
  export const POWERSHELL_HOSTS = ["powershell", "pwsh"];
42
42
 
43
+ /**
44
+ * The execution policy a NEW PowerShell window will have — the saved scopes in PowerShell's own
45
+ * order of precedence, WITHOUT the Process scope (GH #557 follow-up, found on a Windows 11 VM).
46
+ * A plain `Get-ExecutionPolicy` answers for THIS process, and a child PowerShell inherits a parent
47
+ * run with `-ExecutionPolicy Bypass` (the usual way to run an installer one-liner): it said
48
+ * "Bypass" on a Restricted machine, the policy was left alone, and the profile line never ran.
49
+ * All scopes Undefined = Restricted, the Windows client default.
50
+ */
51
+ export const SAVED_POLICY_EXPR =
52
+ "$g = 'Restricted'; foreach ($s in 'MachinePolicy','UserPolicy','CurrentUser','LocalMachine') { $v = [string](Get-ExecutionPolicy -Scope $s); if ($v -ne 'Undefined') { $g = $v; break } }; $g";
53
+
43
54
  /** The one PowerShell command that reports where a host's profiles are and its policy (3 lines). */
44
55
  export const HOST_PROBE =
45
- "$PROFILE.CurrentUserAllHosts; $PROFILE.CurrentUserCurrentHost; Get-ExecutionPolicy";
56
+ "$PROFILE.CurrentUserAllHosts; $PROFILE.CurrentUserCurrentHost; " + SAVED_POLICY_EXPR;
46
57
 
47
58
  /** Parse HOST_PROBE output: { allHosts, currentHost, policy } (empty strings when missing). */
48
59
  export function parseHostProbe(out) {
@@ -0,0 +1,240 @@
1
+ /**
2
+ * gu PUTS ITSELF WHERE THE USER CAN RUN IT, AND SAYS SO (GH #557 follow-up).
3
+ *
4
+ * Owner's decision, 2026-12-02: "we do it for the user and say it out loud". Earlier installs
5
+ * only SAID what to do (#375), or asked first, and a user typing `gu` still met
6
+ * "'gu' is not recognized" or PowerShell's built-in `gu` (Get-Unique). Claude Code's installer
7
+ * prints the steps for the user to do; gu does them, then lists exactly what it changed and how
8
+ * to undo the part that touches a setting:
9
+ *
10
+ * · PATH — npm's global folder on the user PATH (Windows: the registry's User PATH;
11
+ * macOS/Linux: one marked block in the shell's start file, the install-path.mjs block);
12
+ * · Windows PowerShell — one line in each PowerShell's all-hosts profile that removes the `gu`
13
+ * alias, and, where the execution policy would stop that profile loading (Restricted — the
14
+ * Windows 11 default — or AllSigned), RemoteSigned for this user only.
15
+ *
16
+ * Runs from three places, all with the same words:
17
+ * 1. npm's postinstall (install-path.mjs) — npm hides its output, so what it did is also saved
18
+ * to ~/.gonext/setup-done.json and gu says it at its next start;
19
+ * 2. gu's first start on a computer — npm 11.21+ can skip install scripts entirely, so gu checks
20
+ * once itself (marker ~/.gonext/setup-checked);
21
+ * 3. the Windows installer (install.ps1), which has its own PowerShell copy of these steps.
22
+ *
23
+ * Never fails anything: a step that cannot be done is reported with the command to do it by hand.
24
+ */
25
+ import { execFileSync } from "node:child_process";
26
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
27
+ import { homedir } from "node:os";
28
+ import { dirname, join } from "node:path";
29
+
30
+ export const NOTES_FILE = (home = homedir()) => join(home, ".gonext", "setup-done.json");
31
+ export const CHECKED_FILE = (home = homedir()) => join(home, ".gonext", "setup-checked");
32
+
33
+ export const UNDO_POLICY = "Set-ExecutionPolicy -Scope CurrentUser Undefined";
34
+
35
+ // ------------------------------------------------------------------ the words -----------------
36
+
37
+ export const SAID = {
38
+ winPath: (dir) => `Added ${dir} to your user PATH, so \`gu\` works in every new terminal.`,
39
+ posixPath: (dir, rc) => `Added ${dir} to your PATH in ${rc}, so \`gu\` works in every new terminal.`,
40
+ profile: (path, label) =>
41
+ `Added one line to ${path} (${label}) that removes PowerShell's built-in \`gu\` alias (Get-Unique), so \`gu\` starts gu.`,
42
+ policy: (label, was) =>
43
+ `Set ${label}'s execution policy to RemoteSigned for your user only (it was ${was}, which stops profiles loading). To undo: ${UNDO_POLICY}`,
44
+ winPathFailed: (dir, why) => `Could not add ${dir} to your user PATH (${why}). Run \`gu-cli fix-path\`, or add it yourself.`,
45
+ posixPathFailed: (dir) => `Could not write your shell's start file. Add this line to it yourself: export PATH="${dir}:$PATH"`,
46
+ profileFailed: (label, why) => `Could not fix PowerShell's \`gu\` alias for ${label} (${why}). Run \`gu-cli fix-powershell\`; until then use \`gu.cmd\`.`,
47
+ policyFailed: (label, now) =>
48
+ `${label}'s execution policy is still ${now} (set by your organisation?), so the profile line will not run. Use \`gu.cmd\` in PowerShell, or \`gu\` in cmd.exe.`,
49
+ };
50
+
51
+ /** The block shown to the user: what gu changed, then what it could not. */
52
+ export function formatSetupReport({ done = [], failed = [] } = {}, { color = false, title = "gu set this up for you:" } = {}) {
53
+ if (!done.length && !failed.length) return "";
54
+ const g = (s) => (color ? `\x1b[32m${s}\x1b[0m` : s);
55
+ const y = (s) => (color ? `\x1b[33m${s}\x1b[0m` : s);
56
+ const out = [title];
57
+ for (const d of done) out.push(` ${g("✓")} ${d}`);
58
+ for (const f of failed) out.push(` ${y("!")} ${f}`);
59
+ if (done.length) out.push(" Open a new terminal to pick up the change.");
60
+ return out.join("\n");
61
+ }
62
+
63
+ // ------------------------------------------------------------------ remembered for gu ---------
64
+
65
+ /** Keep what an install did for gu's next start to say (npm hides postinstall output). */
66
+ export function saveSetupNotes(report, { home = homedir() } = {}) {
67
+ if (!report?.done?.length && !report?.failed?.length) return;
68
+ const file = NOTES_FILE(home);
69
+ let prev = { done: [], failed: [] };
70
+ try {
71
+ prev = JSON.parse(readFileSync(file, "utf8"));
72
+ } catch {
73
+ /* none yet */
74
+ }
75
+ const merged = {
76
+ at: new Date().toISOString(),
77
+ done: [...new Set([...(prev.done ?? []), ...(report.done ?? [])])],
78
+ failed: [...new Set([...(prev.failed ?? []), ...(report.failed ?? [])])],
79
+ };
80
+ mkdirSync(dirname(file), { recursive: true });
81
+ writeFileSync(file, JSON.stringify(merged, null, 2) + "\n");
82
+ }
83
+
84
+ /** What an install did, once: read and forgotten. */
85
+ export function takeSetupNotes({ home = homedir() } = {}) {
86
+ const file = NOTES_FILE(home);
87
+ try {
88
+ const n = JSON.parse(readFileSync(file, "utf8"));
89
+ rmSync(file, { force: true });
90
+ return { done: n.done ?? [], failed: n.failed ?? [] };
91
+ } catch {
92
+ return { done: [], failed: [] };
93
+ }
94
+ }
95
+
96
+ // ------------------------------------------------------------------ macOS / Linux -------------
97
+
98
+ /**
99
+ * npm's global bin folder on PATH, in the shell's start file. `binDir` = <prefix>/bin.
100
+ * → { done, failed }. Nothing when it is already on PATH (under either spelling, see stableBinDir).
101
+ */
102
+ export async function posixFixes({ binDir, home = homedir(), envPath = process.env.PATH ?? "" } = {}) {
103
+ const done = [];
104
+ const failed = [];
105
+ if (!binDir) return { done, failed };
106
+ const ip = await import("./install-path.mjs");
107
+ const { stableBinDir } = await import("./env-check.mjs");
108
+ const stable = stableBinDir(binDir);
109
+ if (envPath.split(":").some((p) => p === binDir || p === stable)) return { done, failed };
110
+ const r = ip.addPathBlock({ dir: stable, home });
111
+ if (r.wrote) done.push(SAID.posixPath(stable, r.wrote.replace(home, "~")));
112
+ else if (!r.already) failed.push(SAID.posixPathFailed(stable));
113
+ return { done, failed };
114
+ }
115
+
116
+ // ------------------------------------------------------------------ Windows -------------------
117
+
118
+ /** Run one PowerShell command line, stdout trimmed (throws when that PowerShell is missing). */
119
+ function psRun(host, command) {
120
+ return execFileSync(host, ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", command], {
121
+ encoding: "utf8",
122
+ stdio: ["ignore", "pipe", "ignore"],
123
+ timeout: 30_000,
124
+ windowsHide: true,
125
+ }).trim();
126
+ }
127
+
128
+ /**
129
+ * The PowerShell alias, for every PowerShell on this computer. Injected `ps` for tests:
130
+ * ps(host, command) → stdout, throws when the host is missing. → { done, failed }.
131
+ */
132
+ export async function powershellFixes({ ps = psRun, fs = { existsSync, readFileSync, writeFileSync, mkdirSync } } = {}) {
133
+ const pa = await import("./powershell-alias.mjs");
134
+ const done = [];
135
+ const failed = [];
136
+ const hosts = [];
137
+ for (const host of pa.POWERSHELL_HOSTS) {
138
+ try {
139
+ hosts.push({ host, ...pa.parseHostProbe(ps(host, pa.HOST_PROBE)) });
140
+ } catch {
141
+ /* that PowerShell is not installed */
142
+ }
143
+ }
144
+ const profiles = pa.uniqueProfiles(hosts.map((h) => ({ host: h.host, profilePath: h.allHosts })));
145
+ for (const { host, profilePath } of profiles) {
146
+ const label = pa.hostLabel(host);
147
+ try {
148
+ const text = fs.existsSync(profilePath) ? fs.readFileSync(profilePath, "utf8") : "";
149
+ const next = pa.profileWithFix(text);
150
+ if (next !== null) {
151
+ fs.mkdirSync(dirname(profilePath), { recursive: true });
152
+ fs.writeFileSync(profilePath, next);
153
+ done.push(SAID.profile(profilePath, label));
154
+ }
155
+ } catch (e) {
156
+ failed.push(SAID.profileFailed(label, e?.message ?? String(e)));
157
+ }
158
+ }
159
+ // Each PowerShell keeps its own policy (5.1 in the registry, 7 in its config file).
160
+ for (const h of hosts) {
161
+ const was = pa.profileBlockedBy(h.policy);
162
+ if (!was) continue;
163
+ const label = pa.hostLabel(h.host);
164
+ let now = was;
165
+ try {
166
+ ps(h.host, "Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned -Force");
167
+ } catch {
168
+ /* checked below: a Group Policy wins and the command may still exit 0 */
169
+ }
170
+ try {
171
+ now = ps(h.host, pa.SAVED_POLICY_EXPR); // the saved policy, not this process's override
172
+ } catch {
173
+ /* keep `was` */
174
+ }
175
+ if (pa.profileBlockedBy(now)) failed.push(SAID.policyFailed(label, now));
176
+ else done.push(SAID.policy(label, was));
177
+ }
178
+ return { done, failed };
179
+ }
180
+
181
+ /** npm's global folder on the Windows user PATH. Injected `wp` (win-path.mjs) for tests. */
182
+ export async function windowsPathFixes({ dir, wp = null, env = process.env } = {}) {
183
+ const done = [];
184
+ const failed = [];
185
+ if (!dir) return { done, failed };
186
+ wp ??= await import("./win-path.mjs");
187
+ const saved = wp.readSavedPaths();
188
+ const status = wp.pathStatus({ dir, sessionPath: env.Path || env.PATH || "", ...saved, env });
189
+ if (status.saved) return { done, failed };
190
+ const r = wp.addToUserPath(dir);
191
+ if (r.ok) done.push(SAID.winPath(dir));
192
+ else failed.push(SAID.winPathFailed(dir, r.error || "PowerShell refused"));
193
+ return { done, failed };
194
+ }
195
+
196
+ /** Everything for this platform. `dir` = npm's global prefix (Windows) / its bin folder (POSIX). */
197
+ export async function applySetupFixes({ platform = process.platform, dir, home = homedir(), env = process.env, skipProfile = false } = {}) {
198
+ if (platform === "win32") {
199
+ const a = await windowsPathFixes({ dir, env });
200
+ const b = skipProfile || env.GU_INSTALL_NO_PROFILE === "1" ? { done: [], failed: [] } : await powershellFixes();
201
+ return { done: [...a.done, ...b.done], failed: [...a.failed, ...b.failed] };
202
+ }
203
+ return posixFixes({ binDir: dir, home, envPath: env.PATH ?? "" });
204
+ }
205
+
206
+ // ------------------------------------------------------------------ gu's first start ----------
207
+
208
+ /**
209
+ * At gu's start: say what the install did (saved by the postinstall), and on the first start on
210
+ * this computer check the setup ourselves — npm 11.21+ may never have run the postinstall.
211
+ * `here` = the folder gu runs from (only a global npm install gets the check). → the text to
212
+ * print, "" when there is nothing to say.
213
+ */
214
+ export async function startupSetupReport({ here, home = homedir(), platform = process.platform, env = process.env, color = false } = {}) {
215
+ const report = takeSetupNotes({ home });
216
+ if (!existsSync(CHECKED_FILE(home))) {
217
+ let dir = "";
218
+ if (platform === "win32") dir = (await import("./win-path.mjs")).windowsPrefixOf(here);
219
+ else {
220
+ const prefix = (await import("./install-path.mjs")).globalPrefixOf(here);
221
+ dir = prefix ? join(prefix, "bin") : "";
222
+ }
223
+ if (dir && !env.CI) {
224
+ try {
225
+ const r = await applySetupFixes({ platform, dir, home, env });
226
+ for (const d of r.done) if (!report.done.includes(d)) report.done.push(d);
227
+ for (const f of r.failed) if (!report.failed.includes(f)) report.failed.push(f);
228
+ } catch {
229
+ /* a check, never a reason for gu not to start */
230
+ }
231
+ }
232
+ try {
233
+ mkdirSync(dirname(CHECKED_FILE(home)), { recursive: true });
234
+ writeFileSync(CHECKED_FILE(home), new Date().toISOString() + "\n");
235
+ } catch {
236
+ /* asked again next start */
237
+ }
238
+ }
239
+ return formatSetupReport(report, { color });
240
+ }
package/step-group.mjs CHANGED
@@ -1,3 +1,5 @@
1
+ import { isSoftFailCommand } from "./terminal-layout.mjs";
2
+
1
3
  /**
2
4
  * A TURN'S LOOK-UPS AS ONE LINE (task #326) — pure helpers; gu-repl.mjs does the drawing.
3
5
  *
@@ -10,7 +12,8 @@
10
12
  *
11
13
  * WHAT IS GROUPED: a neutral step of the shape "Label → detail" — the agent telling us what it
12
14
  * looked at. NOT grouped, because each is something the user must be able to see at a glance:
13
- * a failure (✗), a command's result (✓), an edit card, an approval, the answer.
15
+ * a failure that is not a command's (✗), an edit card, an approval, the answer. A FAILED COMMAND
16
+ * joins the group too (GH #530) and the row says so in red: "Ran 2 shell commands · 1 failed".
14
17
  *
15
18
  * NOTHING HERE KNOWS A TOOL'S NAME. The kind is whatever stands before the arrow, so a tool added
16
19
  * tomorrow is counted with no change here — the same rule the tool list itself follows (#37).
@@ -42,22 +45,24 @@ export function stepLabel(text) {
42
45
  return /^[A-Za-z][A-Za-z0-9 _.\-/]*$/.test(label) ? label : "";
43
46
  }
44
47
 
45
- // A COMMAND THAT FINISHED joins the group too (#383, GitHub #173): a turn that checks eight tools
46
- // printed eight "✓ Command finished → …" rows in a column. They are activity, like the look-ups —
47
- // one counted row, a click from the commands. A FAILED command never joins: it is the row to see.
48
- const COMMAND_DONE = /^Command finished → /;
49
- export const isCommandStep = (text) => COMMAND_DONE.test(String(text ?? "").trim());
48
+ // A COMMAND joins the group too (#383, GitHub #173): a turn that checks eight tools printed eight
49
+ // "✓ Command finished → …" rows in a column. They are activity, like the look-ups — one counted
50
+ // row, a click from the commands. GH #530: so does a FAILED command. It used to stand alone under
51
+ // a red ✗; now no row has a mark and the group's row ends "· 1 failed" in red — the one part
52
+ // that asks for attention. A look-up that found nothing (grep exits 1) is not counted as failed.
53
+ const COMMAND_STEP = /^Command (?:finished|failed) → (.*)$/;
54
+ export const isCommandStep = (text) => COMMAND_STEP.test(String(text ?? "").trim());
50
55
 
51
- /** Does this step join a group? `kind` is bulletKind()'s: neutral look-ups, and finished commands. */
52
- export function isGroupableStep(text, kind) {
53
- if (kind === "ok") return isCommandStep(text);
54
- return kind === "info" && !isScaffoldStep(text) && stepLabel(text) !== "";
56
+ /** A command that really failed — not a grep/pgrep/which that simply found nothing. */
57
+ export function isFailedCommandStep(text) {
58
+ const m = /^Command failed → (.*)$/.exec(String(text ?? "").trim());
59
+ return Boolean(m) && !isSoftFailCommand(m[1]);
55
60
  }
56
61
 
57
- /** The group's marker: ✓ when every step in it is a finished command, else the neutral ●. */
58
- export function stepGroupMark(items) {
59
- const list = items ?? [];
60
- return list.length && list.every(isCommandStep) ? "ok" : "info";
62
+ /** Does this step join a group? `kind` is bulletKind()'s: neutral look-ups, and commands. */
63
+ export function isGroupableStep(text, kind) {
64
+ if (kind === "ok" || kind === "fail" || kind === "soft") return isCommandStep(text);
65
+ return kind === "info" && !isScaffoldStep(text) && stepLabel(text) !== "";
61
66
  }
62
67
 
63
68
  // "Searching code" reads as work in progress; a finished group is said in the past. Only the first
@@ -74,16 +79,52 @@ function pastLabel(label) {
74
79
  return past ? [past, ...rest].join(" ") : label;
75
80
  }
76
81
 
77
- /** "searched code 3× · read lines 2× · listed files" — kinds in the order they first happened. */
82
+ /**
83
+ * "Searched code 3× · read lines 2× · ran 2 shell commands · 1 failed" — kinds in the order they
84
+ * first happened; the failed count follows the commands it belongs to.
85
+ */
78
86
  export function stepGroupSummary(items) {
79
87
  const counts = new Map();
88
+ let failed = 0;
80
89
  for (const it of items ?? []) {
81
- const label = stepLabel(it) || String(it ?? "").trim();
90
+ const label = isCommandStep(it) ? COMMANDS : stepLabel(it) || String(it ?? "").trim();
82
91
  counts.set(label, (counts.get(label) ?? 0) + 1);
92
+ if (isFailedCommandStep(it)) failed++;
83
93
  }
84
- return [...counts]
85
- .map(([label, n]) => (label === "Command finished" ? `ran ${n} command${n > 1 ? "s" : ""}` : pastLabel(label) + (n > 1 ? ` ${n}×` : "")))
94
+ const text = [...counts]
95
+ .map(([label, n]) =>
96
+ label === COMMANDS
97
+ ? `ran ${n} shell command${n > 1 ? "s" : ""}` + (failed ? ` · ${failed} failed` : "")
98
+ : pastLabel(label) + (n > 1 ? ` ${n}×` : "")
99
+ )
86
100
  .join(" · ");
101
+ return text.charAt(0).toUpperCase() + text.slice(1);
102
+ }
103
+ const COMMANDS = "\0commands";
104
+
105
+ /**
106
+ * A group row cut into the pieces the terminal paints differently (GH #530): the command count
107
+ * ("2" in "Ran 2 shell commands") and the failure ("1 failed", or "failed" in a lone
108
+ * "Command failed → …" row) — everything else is plain. Pure; the caller owns the colours.
109
+ * → [{ text, style: "count" | "failed" | null }]
110
+ */
111
+ export function stepRowSpans(text) {
112
+ const t = String(text ?? "");
113
+ const spans = [];
114
+ let rest = t;
115
+ const count = /^(.*?\b[Rr]an )(\d+)( shell commands?)/.exec(rest);
116
+ if (count) {
117
+ spans.push({ text: count[1], style: null }, { text: count[2], style: "count" });
118
+ rest = rest.slice(count[1].length + count[2].length);
119
+ }
120
+ const fail = /\b\d+ failed\b/.exec(rest) ?? (isFailedCommandStep(rest) ? /failed/.exec(rest) : null);
121
+ if (fail) {
122
+ if (fail.index) spans.push({ text: rest.slice(0, fail.index), style: null });
123
+ spans.push({ text: fail[0], style: "failed" });
124
+ rest = rest.slice(fail.index + fail[0].length);
125
+ }
126
+ if (rest) spans.push({ text: rest, style: null });
127
+ return spans;
87
128
  }
88
129
 
89
130
  function wrapWords(text, width) {
@@ -587,7 +587,8 @@ function mouseTextVerdict(text, plainLeads) {
587
587
  if (body === "") return { kind: "partial" };
588
588
  continue;
589
589
  }
590
- if (body === "I" || body === "O" || WIN32_BODY_DONE.test(body)) return { kind: "done", report: null };
590
+ if (body === "I" || body === "O") return { kind: "done", report: null, focus: body === "I" ? "in" : "out" };
591
+ if (WIN32_BODY_DONE.test(body)) return { kind: "done", report: null };
591
592
  if (body.length <= 40 && WIN32_BODY_PART.test(body)) return { kind: "partial" };
592
593
  }
593
594
  return { kind: "bad" };
@@ -620,7 +621,7 @@ export function createMouseReportReader() {
620
621
  if (v.kind === "partial") return { action: "hold" };
621
622
  held = null;
622
623
  // Whole in one key ("\x1b[O"): node would drop it anyway, but it is ours to drop.
623
- if (v.kind === "done") return { action: "consume", report: v.report };
624
+ if (v.kind === "done") return { action: "consume", report: v.report, focus: v.focus ?? null };
624
625
  return { action: "pass" };
625
626
  }
626
627
  held.push([str, key]);
@@ -628,7 +629,7 @@ export function createMouseReportReader() {
628
629
  const v = mouseTextVerdict(text, plainLeads);
629
630
  if (v.kind === "done") {
630
631
  held = null;
631
- return { action: "consume", report: v.report };
632
+ return { action: "consume", report: v.report, focus: v.focus ?? null };
632
633
  }
633
634
  if (v.kind === "partial") return { action: "hold" };
634
635
  // Not a report. If the key that broke it could START one ("[" after "[", an Esc), keep it.
@@ -650,6 +651,80 @@ export function createMouseReportReader() {
650
651
  };
651
652
  }
652
653
 
654
+ /**
655
+ * The terminal's focus report as node's keypress parser delivers it: "\x1b[I" (the window got
656
+ * focus) or "\x1b[O" (it lost it), sent because gu asks for them with ?1004h (GH #558).
657
+ * "in" | "out" | null. Not typing: a key listener that treats it as one would, for example,
658
+ * jump a scrolled-back view to the bottom every time the user switched windows.
659
+ */
660
+ export function focusReport(key) {
661
+ const seq = key?.sequence;
662
+ return seq === "\x1b[I" ? "in" : seq === "\x1b[O" ? "out" : null;
663
+ }
664
+
665
+ /**
666
+ * NEVER LEAVE A WINDOW REPORTING THE MOUSE TO NOBODY (GH #558).
667
+ *
668
+ * gu reports mouse motion at its prompt (?1003h). It switches that off when it exits, but a gu
669
+ * that dies without exiting cannot: an SSH connection reset (the remote machine went away), a
670
+ * kill -9, a closed lid. The terminal then keeps sending every mouse move — to the user's shell,
671
+ * which prints "35;72;42M35;73;42M…" with each move. Reported live after an SSH session to a
672
+ * deleted VM dropped.
673
+ *
674
+ * Nothing can reach the terminal after the connection is gone, so the mouse is let go BEFORE:
675
+ * - when the window loses focus (focus reporting, ?1004h) — taken back on focus-in;
676
+ * - over SSH, after `idleMs` with no input at the prompt (a locked screen may send no
677
+ * focus-out) — taken back on the next key or focus-in.
678
+ * A user at the window loses nothing: the window has focus and they are using it.
679
+ *
680
+ * `release()` / `restore()` write the terminal modes (the caller knows which mode is on);
681
+ * this only decides WHEN. `arm()` starts the idle clock without taking the mouse back — a
682
+ * prompt that appears while the user is away must not re-grab it.
683
+ */
684
+ export function createMouseParking({ release, restore, idleMs = 0, setTimer = setTimeout, clearTimer = clearTimeout } = {}) {
685
+ let parked = false;
686
+ let timer = null;
687
+ const stopClock = () => {
688
+ if (timer) clearTimer(timer);
689
+ timer = null;
690
+ };
691
+ const park = () => {
692
+ stopClock();
693
+ if (parked) return;
694
+ parked = true;
695
+ release();
696
+ };
697
+ const unpark = () => {
698
+ if (!parked) return;
699
+ parked = false;
700
+ restore();
701
+ };
702
+ const arm = () => {
703
+ if (!(idleMs > 0) || parked) return;
704
+ stopClock();
705
+ timer = setTimer(() => {
706
+ timer = null;
707
+ park();
708
+ }, idleMs);
709
+ timer?.unref?.();
710
+ };
711
+ return {
712
+ parked: () => parked,
713
+ focusOut: park,
714
+ focusIn() {
715
+ unpark();
716
+ arm();
717
+ },
718
+ /** A key, a paste, a mouse report: someone is here. */
719
+ activity() {
720
+ unpark();
721
+ arm();
722
+ },
723
+ arm,
724
+ stop: stopClock,
725
+ };
726
+ }
727
+
653
728
  /** Last line of defence at submit: a report that got past every reader is not a question. */
654
729
  export function stripLeakedMouseReports(line) {
655
730
  return String(line)
@@ -1043,6 +1118,9 @@ export const INPUT_HEAD_ROWS = 2;
1043
1118
  export function inputZoneRows({
1044
1119
  width, prompt = ">> ", promptCols = 3, line = "", cursor = 0, rule,
1045
1120
  maxRows = 10, selection = null, highlight = null,
1121
+ // GH #536: a suggested next message, ALREADY PAINTED (dim), drawn after the prompt while the line
1122
+ // is empty. Display only: it is not text — the caret stays at the start and no offset sees it.
1123
+ ghost = "",
1046
1124
  // Does the separator carry a control this time? Defaults TRUE so any caller that has not been
1047
1125
  // told about this keeps the old, roomier layout rather than silently losing a row.
1048
1126
  headControl = true,
@@ -1107,6 +1185,7 @@ export function inputZoneRows({
1107
1185
 
1108
1186
  const rows = shown.map((s, i) => {
1109
1187
  const head = top + i === 0 ? prompt : " ".repeat(promptCols);
1188
+ if (!text && ghost && top + i === 0) return clipVisible(head + ghost, w - 1);
1110
1189
  let row = clipVisible(head + text.slice(s.from, s.to), w - 1);
1111
1190
  // The selection is held in TEXT OFFSETS, so it survives a rewrap: the same characters stay
1112
1191
  // selected at any width. Each row paints only its own slice of it.