@tiens.nguyen/gu-cli 1.0.931 → 1.0.935

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/model-prices.mjs CHANGED
@@ -205,6 +205,28 @@ export function costSegment(last) {
205
205
  }
206
206
 
207
207
  /** The line /prices prints when the coder in use has no price — why, and that nothing is broken. */
208
+ /**
209
+ * GH #570: OpenRouter publishes every model's price in its public GET /api/v1/models — per TOKEN, as strings.
210
+ * → price rows like the table's ({ host: "openrouter.ai", model, input, cachedInput?, output }, $ per million tokens);
211
+ * a model with no usable prompt price is left out (never a misleading $0 for an unknown one). Pure.
212
+ */
213
+ export function openRouterPriceRows(json) {
214
+ const perM = (v) => {
215
+ const n = Number(v);
216
+ return Number.isFinite(n) && n >= 0 ? Math.round(n * 1e6 * 1e6) / 1e6 : null;
217
+ };
218
+ const out = [];
219
+ for (const m of Array.isArray(json?.data) ? json.data : []) {
220
+ const id = typeof m?.id === "string" ? m.id.trim().toLowerCase() : "";
221
+ const input = perM(m?.pricing?.prompt);
222
+ if (!id || input == null || Number(m?.pricing?.prompt) < 0) continue;
223
+ const cached = perM(m?.pricing?.input_cache_read);
224
+ const output = perM(m?.pricing?.completion);
225
+ out.push({ host: "openrouter.ai", model: id, input, ...(cached != null ? { cachedInput: cached } : {}), ...(output != null ? { output } : {}) });
226
+ }
227
+ return out;
228
+ }
229
+
208
230
  export function noPriceLine({ model = "", host = "" } = {}) {
209
231
  const what = `${model || "the coder"}${host ? ` at ${host}` : ""}`;
210
232
  return `no price for ${what} — its turns show "no price" on the bar instead of a cost. The table prices hosted providers; a model on your own server has none.`;
@@ -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.935",
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",
@@ -80,6 +80,7 @@
80
80
  "mongo-mac.mjs",
81
81
  "mongo-windows.mjs",
82
82
  "python-windows.mjs",
83
+ "python-unix.mjs",
83
84
  "terminal-hover.mjs",
84
85
  "terminal-layout.mjs",
85
86
  "turn-queue.mjs",
@@ -99,6 +100,13 @@
99
100
  "preset-editor.mjs",
100
101
  "preset-apply.mjs",
101
102
  "model-prices.mjs",
103
+ "next-suggestion.mjs",
104
+ "autocompact.mjs",
105
+ "lsp-client.mjs",
106
+ "lsp-host.mjs",
107
+ "win-shell.mjs",
108
+ "setup-fixes.mjs",
109
+ "lsp-registry.mjs",
102
110
  "model-limits-notice.mjs",
103
111
  "device-login.mjs",
104
112
  "daemon-control.mjs",
@@ -186,6 +194,7 @@
186
194
  "gu_skills.py",
187
195
  "gu_test_digest.py",
188
196
  "gu_browser.py",
197
+ "gu_gif.py",
189
198
  "gu_powershell.py",
190
199
  "gu_turn_notes.py",
191
200
  "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,120 @@
1
+ /**
2
+ * PYTHON ON A MAC OR LINUX THAT HAS NONE GU CAN USE (GH #564).
3
+ *
4
+ * Measured on clean machines (2026-12-03): a Mac without the Command Line Tools has only Apple's stub python3 (it opens
5
+ * an "install the developer tools" window); a Mac WITH them has Python 3.9, too old for the agent's libraries (pip:
6
+ * "No matching distribution found for smolagents"); Ubuntu Server has python3 without venv/pip (python3-venv is its own
7
+ * package). On all three the agent could not run, and gu could only say "install Python".
8
+ *
9
+ * Like the Windows path (python-windows.mjs: python.org, for this user), gu now offers to bring its own: a standalone
10
+ * CPython build (python-build-standalone — the builds uv and others install), unpacked into ~/.gonext/python. No
11
+ * administrator, no sudo, nothing outside ~/.gonext. The archive is checked against a SHA-256 pinned HERE, so a changed
12
+ * file on the server is refused, never run. Bump the release on purpose, with its four hashes.
13
+ *
14
+ * Pure parts are separate; the download and the shell are injected so tests never fetch or unpack anything.
15
+ */
16
+ import { createHash } from "node:crypto";
17
+ import { execFile } from "node:child_process";
18
+ import { existsSync } from "node:fs";
19
+ import { mkdir, rename, rm, writeFile } from "node:fs/promises";
20
+ import { homedir } from "node:os";
21
+ import { join } from "node:path";
22
+
23
+ export const PYTHON_UNIX = {
24
+ version: "3.12.16",
25
+ release: "20261201",
26
+ // From the release's SHA256SUMS, checked against GitHub's own digest of each file (2026-12-03).
27
+ builds: {
28
+ "darwin-arm64": { triple: "aarch64-apple-darwin", sha256: "0e261d16dc690890b864c7e4895dd353b2b90d53177822ad3c16c5949e1417c2", mb: 25 },
29
+ "darwin-x64": { triple: "x86_64-apple-darwin", sha256: "5f511089f588c511ed3c26bbbc1de5047dcbead229d2a715160f4dd159c0180e", mb: 25 },
30
+ "linux-arm64": { triple: "aarch64-unknown-linux-gnu", sha256: "e1ce94941e27f99e4cdbabdfe5e82d05a35b76afbae977b8531d4afcd35b2566", mb: 53 },
31
+ "linux-x64": { triple: "x86_64-unknown-linux-gnu", sha256: "ed82eead6b80ced86c75b6c7ecaa204e2dc4cb5b780eea0475f68414595afe55", mb: 68 },
32
+ },
33
+ };
34
+
35
+ /** The build for this computer, or null (Windows, another CPU, a Linux without glibc such as Alpine). Pure. */
36
+ export function pythonBuildFor({ platform = process.platform, arch = process.arch, glibc = glibcVersion() } = {}) {
37
+ if (platform === "linux" && !glibc) return null; // the gnu builds need glibc; musl (Alpine) cannot run them
38
+ const b = PYTHON_UNIX.builds[`${platform}-${arch}`];
39
+ if (!b) return null;
40
+ const name = `cpython-${PYTHON_UNIX.version}+${PYTHON_UNIX.release}-${b.triple}-install_only.tar.gz`;
41
+ return {
42
+ ...b,
43
+ name,
44
+ url: `https://github.com/astral-sh/python-build-standalone/releases/download/${PYTHON_UNIX.release}/${encodeURIComponent(name)}`,
45
+ };
46
+ }
47
+
48
+ function glibcVersion() {
49
+ try {
50
+ return process.report?.getReport?.()?.header?.glibcVersionRuntime || "";
51
+ } catch {
52
+ return "";
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Can the agent run on this Python? → { ok, why }. "3.9.6" → too old; no venv/ensurepip (Debian's split) → cannot make
58
+ * gu's own environment. `probe(code)` runs `python3 -c code` → { ok, out }. Pure apart from the probe.
59
+ */
60
+ export async function pythonUsable(probe) {
61
+ const v = await probe("import sys; print('%d.%d.%d' % sys.version_info[:3])");
62
+ if (!v.ok) return { ok: false, why: "none", version: "" };
63
+ const version = String(v.out).trim();
64
+ const [maj, min] = version.split(".").map(Number);
65
+ if (!(maj > 3 || (maj === 3 && min >= 10))) return { ok: false, why: "old", version };
66
+ const venv = await probe("import venv, ensurepip");
67
+ if (!venv.ok) return { ok: false, why: "no-venv", version };
68
+ return { ok: true, why: "", version };
69
+ }
70
+
71
+ /** The question gu asks, in words that say what changes. Pure. */
72
+ export function pythonOfferText(usable, build) {
73
+ const have =
74
+ usable.why === "old" ? `this computer has Python ${usable.version}, too old for it` :
75
+ usable.why === "no-venv" ? `this computer's Python ${usable.version} cannot make gu's own environment (no venv)` :
76
+ "this computer has none gu can use";
77
+ return `The agent runs on Python 3.10 or newer, and ${have}. Install Python ${PYTHON_UNIX.version} for your user only? ` +
78
+ `(about ${build.mb} MB, into ~/.gonext/python; no password, nothing system-wide)`;
79
+ }
80
+
81
+ const sh = (file, args) =>
82
+ new Promise((resolve) => {
83
+ execFile(file, args, { timeout: 600000 }, (err, stdout, stderr) => resolve({ code: err ? (err.code ?? 1) : 0, out: String(stdout), err: String(stderr) }));
84
+ });
85
+
86
+ /**
87
+ * Download, check, unpack, and make gu's own environment (~/.gonext/venv) from it. → { ok, python?, error? }
88
+ * An older ~/.gonext/venv (made from a Python the agent cannot use) is moved aside, never deleted.
89
+ */
90
+ export async function installPythonUnix({ dir = join(homedir(), ".gonext"), build = pythonBuildFor(), fetchFn = fetch, run = sh, log = () => {} } = {}) {
91
+ if (!build) return { ok: false, error: "there is no standalone Python build for this computer" };
92
+ const archive = join(dir, build.name);
93
+ try {
94
+ await mkdir(dir, { recursive: true });
95
+ const res = await fetchFn(build.url, { redirect: "follow" });
96
+ if (!res.ok) return { ok: false, error: `download failed (HTTP ${res.status})` };
97
+ const bytes = Buffer.from(await res.arrayBuffer());
98
+ const got = createHash("sha256").update(bytes).digest("hex");
99
+ if (got !== build.sha256) return { ok: false, error: "the download did not match its pinned checksum, so it was NOT installed" };
100
+ await writeFile(archive, bytes);
101
+ } catch (e) {
102
+ return { ok: false, error: `download failed: ${e?.message ?? e}` };
103
+ }
104
+ // The archive holds one folder, python/ — unpacked fresh, so a half-finished earlier try leaves nothing behind.
105
+ const home = join(dir, "python");
106
+ await rm(home, { recursive: true, force: true });
107
+ const untar = await run("tar", ["-xzf", archive, "-C", dir]);
108
+ await rm(archive, { force: true }).catch(() => {});
109
+ const python = join(home, "bin", "python3"); // platform-ok: the standalone build's own file, macOS/Linux only (Windows uses python-windows.mjs)
110
+ if (untar.code !== 0 || !existsSync(python)) return { ok: false, error: `could not unpack it: ${untar.err.trim().split("\n")[0] || "tar failed"}` };
111
+ const venv = join(dir, "venv");
112
+ if (existsSync(venv)) {
113
+ const aside = `${venv}-old-${Date.now()}`;
114
+ await rename(venv, aside).catch(() => {});
115
+ log(` · the earlier environment was kept as ${aside}`);
116
+ }
117
+ const made = await run(python, ["-m", "venv", venv]);
118
+ if (made.code !== 0) return { ok: false, error: `could not make gu's environment: ${made.err.trim().split("\n").pop()}` };
119
+ return { ok: true, python: join(venv, "bin", "python") };
120
+ }
@@ -0,0 +1,245 @@
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
+ // GH #564: also the same folder under another name — the installer puts ~/.local/share/gu/node/bin (a link to
110
+ // node-v26…/bin) on PATH, and the first gu added the versioned spelling a second time.
111
+ const { realpathSync } = await import("node:fs");
112
+ const real = (p) => { try { return realpathSync(p); } catch { return p; } };
113
+ const want = real(binDir);
114
+ if (envPath.split(":").some((p) => p && (p === binDir || p === stable || real(p) === want))) return { done, failed };
115
+ const r = ip.addPathBlock({ dir: stable, home });
116
+ if (r.wrote) done.push(SAID.posixPath(stable, r.wrote.replace(home, "~")));
117
+ else if (!r.already) failed.push(SAID.posixPathFailed(stable));
118
+ return { done, failed };
119
+ }
120
+
121
+ // ------------------------------------------------------------------ Windows -------------------
122
+
123
+ /** Run one PowerShell command line, stdout trimmed (throws when that PowerShell is missing). */
124
+ function psRun(host, command) {
125
+ return execFileSync(host, ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", command], {
126
+ encoding: "utf8",
127
+ stdio: ["ignore", "pipe", "ignore"],
128
+ timeout: 30_000,
129
+ windowsHide: true,
130
+ }).trim();
131
+ }
132
+
133
+ /**
134
+ * The PowerShell alias, for every PowerShell on this computer. Injected `ps` for tests:
135
+ * ps(host, command) → stdout, throws when the host is missing. → { done, failed }.
136
+ */
137
+ export async function powershellFixes({ ps = psRun, fs = { existsSync, readFileSync, writeFileSync, mkdirSync } } = {}) {
138
+ const pa = await import("./powershell-alias.mjs");
139
+ const done = [];
140
+ const failed = [];
141
+ const hosts = [];
142
+ for (const host of pa.POWERSHELL_HOSTS) {
143
+ try {
144
+ hosts.push({ host, ...pa.parseHostProbe(ps(host, pa.HOST_PROBE)) });
145
+ } catch {
146
+ /* that PowerShell is not installed */
147
+ }
148
+ }
149
+ const profiles = pa.uniqueProfiles(hosts.map((h) => ({ host: h.host, profilePath: h.allHosts })));
150
+ for (const { host, profilePath } of profiles) {
151
+ const label = pa.hostLabel(host);
152
+ try {
153
+ const text = fs.existsSync(profilePath) ? fs.readFileSync(profilePath, "utf8") : "";
154
+ const next = pa.profileWithFix(text);
155
+ if (next !== null) {
156
+ fs.mkdirSync(dirname(profilePath), { recursive: true });
157
+ fs.writeFileSync(profilePath, next);
158
+ done.push(SAID.profile(profilePath, label));
159
+ }
160
+ } catch (e) {
161
+ failed.push(SAID.profileFailed(label, e?.message ?? String(e)));
162
+ }
163
+ }
164
+ // Each PowerShell keeps its own policy (5.1 in the registry, 7 in its config file).
165
+ for (const h of hosts) {
166
+ const was = pa.profileBlockedBy(h.policy);
167
+ if (!was) continue;
168
+ const label = pa.hostLabel(h.host);
169
+ let now = was;
170
+ try {
171
+ ps(h.host, "Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned -Force");
172
+ } catch {
173
+ /* checked below: a Group Policy wins and the command may still exit 0 */
174
+ }
175
+ try {
176
+ now = ps(h.host, pa.SAVED_POLICY_EXPR); // the saved policy, not this process's override
177
+ } catch {
178
+ /* keep `was` */
179
+ }
180
+ if (pa.profileBlockedBy(now)) failed.push(SAID.policyFailed(label, now));
181
+ else done.push(SAID.policy(label, was));
182
+ }
183
+ return { done, failed };
184
+ }
185
+
186
+ /** npm's global folder on the Windows user PATH. Injected `wp` (win-path.mjs) for tests. */
187
+ export async function windowsPathFixes({ dir, wp = null, env = process.env } = {}) {
188
+ const done = [];
189
+ const failed = [];
190
+ if (!dir) return { done, failed };
191
+ wp ??= await import("./win-path.mjs");
192
+ const saved = wp.readSavedPaths();
193
+ const status = wp.pathStatus({ dir, sessionPath: env.Path || env.PATH || "", ...saved, env });
194
+ if (status.saved) return { done, failed };
195
+ const r = wp.addToUserPath(dir);
196
+ if (r.ok) done.push(SAID.winPath(dir));
197
+ else failed.push(SAID.winPathFailed(dir, r.error || "PowerShell refused"));
198
+ return { done, failed };
199
+ }
200
+
201
+ /** Everything for this platform. `dir` = npm's global prefix (Windows) / its bin folder (POSIX). */
202
+ export async function applySetupFixes({ platform = process.platform, dir, home = homedir(), env = process.env, skipProfile = false } = {}) {
203
+ if (platform === "win32") {
204
+ const a = await windowsPathFixes({ dir, env });
205
+ const b = skipProfile || env.GU_INSTALL_NO_PROFILE === "1" ? { done: [], failed: [] } : await powershellFixes();
206
+ return { done: [...a.done, ...b.done], failed: [...a.failed, ...b.failed] };
207
+ }
208
+ return posixFixes({ binDir: dir, home, envPath: env.PATH ?? "" });
209
+ }
210
+
211
+ // ------------------------------------------------------------------ gu's first start ----------
212
+
213
+ /**
214
+ * At gu's start: say what the install did (saved by the postinstall), and on the first start on
215
+ * this computer check the setup ourselves — npm 11.21+ may never have run the postinstall.
216
+ * `here` = the folder gu runs from (only a global npm install gets the check). → the text to
217
+ * print, "" when there is nothing to say.
218
+ */
219
+ export async function startupSetupReport({ here, home = homedir(), platform = process.platform, env = process.env, color = false } = {}) {
220
+ const report = takeSetupNotes({ home });
221
+ if (!existsSync(CHECKED_FILE(home))) {
222
+ let dir = "";
223
+ if (platform === "win32") dir = (await import("./win-path.mjs")).windowsPrefixOf(here);
224
+ else {
225
+ const prefix = (await import("./install-path.mjs")).globalPrefixOf(here);
226
+ dir = prefix ? join(prefix, "bin") : "";
227
+ }
228
+ if (dir && !env.CI) {
229
+ try {
230
+ const r = await applySetupFixes({ platform, dir, home, env });
231
+ for (const d of r.done) if (!report.done.includes(d)) report.done.push(d);
232
+ for (const f of r.failed) if (!report.failed.includes(f)) report.failed.push(f);
233
+ } catch {
234
+ /* a check, never a reason for gu not to start */
235
+ }
236
+ }
237
+ try {
238
+ mkdirSync(dirname(CHECKED_FILE(home)), { recursive: true });
239
+ writeFileSync(CHECKED_FILE(home), new Date().toISOString() + "\n");
240
+ } catch {
241
+ /* asked again next start */
242
+ }
243
+ }
244
+ return formatSetupReport(report, { color });
245
+ }