@tiens.nguyen/gu-cli 1.0.930 → 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.
package/gu-repl.mjs CHANGED
@@ -24,6 +24,8 @@
24
24
  * Commands: /exit /model /new /help Ctrl-C stops following the current run.
25
25
  */
26
26
  import { RELAUNCHED } from "./gu-relaunch.mjs"; // FIRST: may replace this process (#358)
27
+ import { installInternalLabel } from "./cli-token.mjs";
28
+ installInternalLabel(); // our own machines only (GU_INTERNAL_LABEL / ~/.gonext/internal-label): label gucli.com requests
27
29
  import { readFile, mkdir, writeFile, unlink, rename } from "node:fs/promises";
28
30
  import { readStepTokens, readTurnCache } from "./step-tokens.mjs";
29
31
  import { snapshotInput, restoreInput, replaceStoppedQuestion, restoredQuestionLetGo, stopNoteLines } from "./turn-stop.mjs";
@@ -144,7 +146,7 @@ import {
144
146
  trimWords,
145
147
  } from "./terminal-layout.mjs";
146
148
  import { completedFlush, splitLiveStream } from "./completed-flush.mjs";
147
- import { isScaffoldStep, isGroupableStep, stepGroupMark, stepGroupRows, relativizePaths } from "./step-group.mjs";
149
+ import { isScaffoldStep, isGroupableStep, stepGroupRows, stepRowSpans, relativizePaths } from "./step-group.mjs";
148
150
  import { clearLogsNoticeText } from "./clear-logs.mjs";
149
151
  import { commandAllowedIn, commandAllowProject, commandAllowSource, commandForget, commandProjectAllowed, sourcedFileOf, PROJECT_CHOICE } from "./command-allow.mjs";
150
152
  import { allowIn, allowedIn, bridgeCommand, browserReport, bridgeStatus, extensionDir, findDevInstalls, helpInstall, installExtensionFiles, installSteps, localLeftovers, openExtensionsPage, removeLocalFiles, STORE_URL, stopBridge } from "./browser-command.mjs";
@@ -157,6 +159,7 @@ import { readHooks } from "./hooks-config.mjs";
157
159
  import { readSkillSource, sourceLabel, SKILL_SOURCE_KEY } from "./skill-source.mjs";
158
160
  import { codingBannerLabel, isOllamaCloudUrl, SECRET_KEY_HINT } from "./coding-key-prompt.mjs";
159
161
  import { questionEchoText, thoughtPrintSeq, wrapDiffText } from "./terminal-layout.mjs";
162
+ import { focusReport, createMouseParking } from "./terminal-layout.mjs"; // GH #558
160
163
  import { createTurnQueue, droppedNote } from "./turn-queue.mjs"; // GH #429: questions typed during a turn wait here
161
164
  import { sendNote, takeUnread, sweepOldNotes, parseUserNote, questionWithNotes, USERNOTE_PREFIX } from "./turn-notes.mjs"; // GH #506: …or go to the running turn
162
165
  import { globalPrefixOf } from "./install-path.mjs";
@@ -171,6 +174,9 @@ import {
171
174
  parseModelFallback,
172
175
  } from "./model-fallback.mjs";
173
176
  import { codingChoiceTags, coderDisplayName, coderWhere, whereOfActiveCoder } from "./coding-choice-tags.mjs";
177
+ import { LSP_OFFER_MS, OFFER_CHOICES, allLanguages, applyOfferAnswer, canInstall, lspById, lspHostPath, lspStatePath, offerRows, readLspState, resolveServer, writeLspState } from "./lsp-registry.mjs";
178
+ import { AUTOCOMPACT_ASK_MS, applyChoice, autocompactPath, commandChoices, describeAutocompact, parseAutocompactArg, readAutocompact, startupChoices, startupText, writeAutocompact } from "./autocompact.mjs";
179
+ import { ghostText, shouldSuggest, suggestNext, suggestionsOnFromFile, suggestionsToggle } from "./next-suggestion.mjs";
174
180
  import { TITLE_POP, TITLE_PUSH, idleTitle, needsSummary, summariseForTitle, titleModel, titleSeq, trimTitle } from "./terminal-title.mjs";
175
181
  import { IMAGE_NEEDS_CLAUDE, coderTakesImagesFor, loadCloudImageCoders, saveCloudImageCoders, clipboardImageToFile, fitImageNotice, imageMarkersForDisplay, createImageStore, imagePasteKey, imagePathFromPaste, isClaudeCoderUrl, isImagePasteKey, storeImageFile } from "./image-paste.mjs";
176
182
  import {
@@ -600,8 +606,7 @@ const PICK_MANY_HINT = "↑/↓ · space toggles · ctrl+a all · Enter saves ·
600
606
  // grows past it). A server saved with more before the rule keeps them: see extraModelRoom.
601
607
  const MAX_ALT_CODERS = 2;
602
608
  const BULLET = "●"; // a neutral completed action (informational step)
603
- const CHECK = "✓"; // a step that succeeded
604
- const CROSS = "✗"; // a step that FAILED
609
+ const CROSS = "✗"; // a step that FAILED (one that is not a command's — those join the group, GH #530)
605
610
  const brightText = (s) => s; // default terminal colour (un-dimmed) — the "pops" text weight
606
611
  // The "spotlight the answer" hierarchy: successes and neutral steps RECEDE (dim), a FAILURE
607
612
  // POPS (red ✗ + full-bright text) — the one thing the user must not miss while everything
@@ -610,9 +615,11 @@ const brightText = (s) => s; // default terminal colour (un-dimmed) — the "pop
610
615
  // forward reference here is a startup crash, not a lint warning.
611
616
  const BULLET_STYLE = {
612
617
  fail: { mark: CROSS, markColor: red, textColor: brightText },
613
- // A look-up (grep/pgrep/rg…) that found nothing: not an error — a dim grey ✗, dim text.
614
- soft: { mark: CROSS, markColor: dim, textColor: dim },
615
- ok: { mark: CHECK, markColor: accent, textColor: dim },
618
+ // GH #530: commands (finished, failed, or a look-up that found nothing) and searches go into the
619
+ // counted group with NO mark — the ✓ in front of every one was noise. These two are what an
620
+ // ungroupable one falls back to: no mark (the slot stays a space so the text does not move).
621
+ soft: { mark: " ", markColor: dim, textColor: dim },
622
+ ok: { mark: " ", markColor: dim, textColor: dim },
616
623
  // #383 (GitHub #173): a "●" row that stands alone is the agent saying something — a warning, a
617
624
  // wait for approval — so its text is white. Look-ups and finished commands are activity and go
618
625
  // into the dim counted group instead (step-group.mjs); they never reach this style.
@@ -647,6 +654,14 @@ if (argv.includes("--version") || argv[0] === "version") {
647
654
  console.log(REPL_VERSION);
648
655
  process.exit(0);
649
656
  }
657
+ // `gu internal [label|off]` — marks THIS computer as one of ours (the Windows test VM) so Cloudflare can tell it
658
+ // from real users. One word, no env vars. No label = the computer's host name. Hidden: not in the help list.
659
+ if (argv[0] === "internal") {
660
+ const { setInternalLabel } = await import("./cli-token.mjs");
661
+ const r = setInternalLabel(argv[1]);
662
+ console.log(r.label ? `This computer is marked as ours: "${r.label}". gu's requests to gucli.com now say so.` : "This computer is no longer marked as ours.");
663
+ process.exit(0);
664
+ }
650
665
  const cliVerdict = classifyCliArg(argv, CLI_SUBCOMMANDS);
651
666
  if (cliVerdict.kind === "unknown") {
652
667
  console.error(red(`gu: unknown command "${cliVerdict.typed}"`));
@@ -724,6 +739,20 @@ if (REPL_LOG) {
724
739
  console.log(dim(" --log: detailed logging is on for this run (~/.gonext/worker.log); back to minimal when gu closes."));
725
740
  }
726
741
 
742
+ // WHAT THE INSTALL DID, FIRST (GH #557 follow-up): npm hides postinstall output, so gu says what
743
+ // it changed for the user (PATH, PowerShell's `gu` alias) before anything else it prints or asks.
744
+ // On this computer's first start it also checks those itself — npm can skip install scripts.
745
+ // Done, then said; never a reason not to start.
746
+ if (process.stdout.isTTY) {
747
+ try {
748
+ const { startupSetupReport } = await import("./setup-fixes.mjs");
749
+ const text = await startupSetupReport({ here: DIR, color: true });
750
+ if (text) console.log("\n" + text.replace(/^/gm, " ") + "\n");
751
+ } catch {
752
+ /* never blocks gu */
753
+ }
754
+ }
755
+
727
756
  // THE AGENT'S PYTHON PACKAGES COME FIRST (GH #308), before the first-run setup and the terminal below create their readline and
728
757
  // raw keyboard — and before stdout is hooked for the pinned input bar (whose state does not exist yet here): the install ran from inside the live terminal and froze it on a new Windows 11 machine.
729
758
  {
@@ -1060,6 +1089,9 @@ const COMMANDS = [
1060
1089
  // has already confused the person who built both. The descriptions carry the distinction.
1061
1090
  { name: "/model", desc: "switch the CODING model (the one that writes code) for this session" },
1062
1091
  { name: "/quick-models", desc: "pick up to 2 coding models to flip between with ← / → at the prompt" },
1092
+ { name: "/lsp", desc: "language servers: the agent sees compile/type errors after each edit — status, on/off, restart" },
1093
+ { name: "/autocompact", desc: "when older steps are compacted: near 400k tokens (default), another size, or near the model's limit" },
1094
+ { name: "/suggestions", desc: "turn the suggested next message (Tab takes it) on or off" },
1063
1095
  // /provider IS NOT LISTED HERE ANY MORE — see HIDDEN_COMMANDS. It was promoted to a top-level
1064
1096
  // command when editing a provider was genuinely unreachable, and by the very next change
1065
1097
  // /model carried "add or change a provider — Claude API, OpenAI, Kimi…" as a row in EVERY branch of
@@ -1358,6 +1390,13 @@ const CLICK_TO_POSITION_ENABLED = true;
1358
1390
  // readline's own reader).
1359
1391
  const PASTE_MODE_ON = "\x1b[?2004h"; // ask the terminal to bracket pastes
1360
1392
  const PASTE_MODE_OFF = "\x1b[?2004l";
1393
+ // Focus reporting (GH #558): the terminal sends ESC[I / ESC[O as the window gains and loses
1394
+ // focus, and gu lets go of the mouse while it is away — see createMouseParking.
1395
+ const FOCUS_MODE_ON = "\x1b[?1004h";
1396
+ const FOCUS_MODE_OFF = "\x1b[?1004l";
1397
+ // Assigned next to the mouse modes it switches (further down); `let` so input that arrives
1398
+ // before then finds null instead of a TDZ error.
1399
+ let mouseParking = null;
1361
1400
  // The paste is BUFFERED here rather than passed through: readline never sees a single byte of
1362
1401
  // it, so its newlines cannot submit the turn, and at paste-end we decide what to show — a
1363
1402
  // short paste goes in literally, a long one becomes "[Pasted text #N +M lines]" with the real
@@ -1387,6 +1426,17 @@ function mouseFlush() {
1387
1426
  _mouseTimer = null;
1388
1427
  mouseReplay(mouseReader.flush());
1389
1428
  }
1429
+ /**
1430
+ * GH #558: the window gained or lost focus → let go of / take back the mouse; true = it was a
1431
+ * focus report, swallow it. Anything else that reaches _ttyWrite is someone at the window.
1432
+ */
1433
+ function onFocusOrActivity(key) {
1434
+ const focus = focusReport(key);
1435
+ if (focus === "out") mouseParking?.focusOut();
1436
+ else if (focus === "in") mouseParking?.focusIn();
1437
+ else mouseParking?.activity();
1438
+ return focus !== null;
1439
+ }
1390
1440
  const _origTtyWrite = rl._ttyWrite.bind(rl);
1391
1441
  rl._ttyWrite = (str, key) => {
1392
1442
  // A LIST PICKER OWNS EVERY KEY WHILE IT IS UP, and this has to happen HERE rather than in the
@@ -1403,7 +1453,9 @@ rl._ttyWrite = (str, key) => {
1403
1453
  // is up there is no line to edit, so anything readline does to `rl.line` — kill-to-end,
1404
1454
  // word-delete, history — is invisible work on a buffer the user cannot see, which then
1405
1455
  // surfaces the moment the picker closes.
1456
+ if (onFocusOrActivity(key)) return; // GH #558: focus in/out is not a key, whoever owns them
1406
1457
  if (listPickerActive) return;
1458
+ if (nextHint && nextHintKey(str, key)) return; // GH #536: Tab takes the suggestion
1407
1459
  if (key?.name === "paste-start") {
1408
1460
  pasteBuffer = "";
1409
1461
  return; // swallow the marker
@@ -1478,6 +1530,8 @@ rl._ttyWrite = (str, key) => {
1478
1530
  }
1479
1531
  if (verdict.action === "consume") {
1480
1532
  mouseClearTimer();
1533
+ if (verdict.focus === "out") mouseParking?.focusOut(); // the ESC-timed-out shape (GH #558)
1534
+ else if (verdict.focus === "in") mouseParking?.focusIn();
1481
1535
  if (verdict.report) applyMouseReport(verdict.report); // null: focus in/out, a win32 record
1482
1536
  return;
1483
1537
  }
@@ -1827,9 +1881,9 @@ function applyClick({ row, col }) {
1827
1881
  rl._refreshLine();
1828
1882
  }
1829
1883
  if (IS_TTY) {
1830
- ui(PASTE_MODE_ON);
1831
- // Never leave the terminal in bracketed-paste mode — the user's shell would inherit it.
1832
- process.on("exit", () => _stdoutWrite(PASTE_MODE_OFF));
1884
+ ui(PASTE_MODE_ON + FOCUS_MODE_ON);
1885
+ // Never leave the terminal in bracketed-paste or focus mode — the user's shell would inherit it.
1886
+ process.on("exit", () => _stdoutWrite(PASTE_MODE_OFF + FOCUS_MODE_OFF));
1833
1887
  }
1834
1888
 
1835
1889
  // THE TAB SAYS WHAT IS BEING WORKED ON (task #357) — see terminal-title.mjs. Until the first
@@ -1848,6 +1902,231 @@ if (TITLE_ON) {
1848
1902
  process.on("exit", () => _stdoutWrite(titleSeq("") + TITLE_POP));
1849
1903
  }
1850
1904
 
1905
+ // ---------- language servers (GH #539/#540) --------------------------------------------------
1906
+ // The choices live in ~/.gonext/lsp-state.json (the offer and /lsp write it); the worker's host
1907
+ // (lsp-host.mjs) reads it, runs the servers, and says what is running on /status.
1908
+ const loadLspState = () => {
1909
+ try {
1910
+ return readLspState(readFileSync(lspStatePath(homedir()), "utf8"));
1911
+ } catch {
1912
+ return readLspState("");
1913
+ }
1914
+ };
1915
+ function saveLspState(state) {
1916
+ try {
1917
+ mkdirSync(dirname(lspStatePath(homedir())), { recursive: true });
1918
+ writeFileSync(lspStatePath(homedir()), writeLspState(state));
1919
+ } catch (e) {
1920
+ console.log(GUTTER + yellow(`could not save the language-server choice (${e?.message || e})`));
1921
+ }
1922
+ }
1923
+
1924
+ /** Ask the worker's host something (GET /status, POST /stop). null when no worker is running it. */
1925
+ async function lspHostCall(path, body = null) {
1926
+ try {
1927
+ const { url, token } = JSON.parse(readFileSync(lspHostPath(homedir()), "utf8"));
1928
+ const res = await fetch(url + path, {
1929
+ method: body ? "POST" : "GET",
1930
+ headers: { "X-Gu-Lsp-Token": token, "Content-Type": "application/json" },
1931
+ body: body ? JSON.stringify(body) : undefined,
1932
+ signal: AbortSignal.timeout(3000),
1933
+ });
1934
+ return res.ok ? await res.json() : null;
1935
+ } catch {
1936
+ return null;
1937
+ }
1938
+ }
1939
+
1940
+ /** One line per language: the choice, whether its server is here, and what is running. */
1941
+ function lspStatusLine(row) {
1942
+ const choice = { on: "on", off: "off", never: "off (never offered)" }[row.choice] ?? "not set — offered on the first edit";
1943
+ const where = row.installing ? "installing…" : row.installError ? `install failed: ${row.installError}` : row.found ? `${row.server} found` : row.canInstall ? `${row.server} not installed (gu can install it)` : `${row.server} not found${row.hint ? ` — ${row.hint}` : ""}`;
1944
+ const running = (row.running?.length ? ` · running in ${row.running.length} project${row.running.length > 1 ? "s" : ""}` : "") +
1945
+ // A heavy server (Java, Kotlin) can take minutes to read a project the first time (GH #543).
1946
+ (row.starting?.length ? ` · starting in ${row.starting.length} project${row.starting.length > 1 ? "s" : ""} (a first start can take minutes)` : "");
1947
+ return `${row.name}: ${choice} · ${where}${running}`;
1948
+ }
1949
+
1950
+ /** /lsp — what each language server is doing, and turn one on or off. */
1951
+ async function lspCommand(arg) {
1952
+ const [verb = "", which = ""] = String(arg ?? "").trim().toLowerCase().split(/\s+/);
1953
+ const ws = resolve(process.cwd());
1954
+ const langs = allLanguages({ home: homedir(), workspace: ws });
1955
+ const live = (await lspHostCall(`/status?workspace=${encodeURIComponent(ws)}`))?.languages;
1956
+ const st = loadLspState();
1957
+ const rows = live ?? langs.map((l) => ({
1958
+ id: l.id, name: l.name, server: l.server, choice: st.languages[l.id] ?? "", hint: l.hint ?? "",
1959
+ found: Boolean(resolveServer(l, { home: homedir() })), canInstall: canInstall(l), running: [],
1960
+ }));
1961
+ const set = async (id, on) => {
1962
+ const lang = lspById(id, langs);
1963
+ if (!lang) {
1964
+ console.log(GUTTER + dim(`no language "${id}" — ${langs.map((l) => l.id).join(", ")}`) + "\n");
1965
+ return;
1966
+ }
1967
+ const next = loadLspState();
1968
+ next.languages[id] = on ? "on" : "off";
1969
+ saveLspState(next);
1970
+ if (!on) await lspHostCall("/stop", { lang: id });
1971
+ const row = rows.find((r) => r.id === id);
1972
+ console.log(GUTTER + accent(`✓ ${lang.name} code intelligence ${on ? "on" : "off"}`) +
1973
+ dim(on && row && !row.found && canInstall(lang) ? ` — gu installs ${lang.server} at the next ${lang.name} edit` : "") + "\n");
1974
+ };
1975
+ if (verb === "on" || verb === "off") return set(which, verb === "on");
1976
+ if (verb === "restart") {
1977
+ await lspHostCall("/stop", { lang: which });
1978
+ console.log(GUTTER + dim("stopped — each server starts again at the next edit of its language.") + "\n");
1979
+ return;
1980
+ }
1981
+ console.log(GUTTER + accent("Language servers") + dim(" — the agent sees compile/type errors right after each edit"));
1982
+ for (const r of rows) console.log(GUTTER + " " + dim(lspStatusLine(r)));
1983
+ if (!live) console.log(GUTTER + dim(" (the worker is not running one right now)"));
1984
+ const items = [...rows.map((r) => (r.choice === "on" ? `Turn off ${r.name}` : `Turn on ${r.name}`)), "Restart all servers"];
1985
+ const idx = await pickFromList(items, 0);
1986
+ if (idx < 0) return console.log(GUTTER + dim("(unchanged)") + "\n");
1987
+ if (idx === rows.length) {
1988
+ await lspHostCall("/stop", { lang: "" });
1989
+ return console.log(GUTTER + dim("stopped — each server starts again at the next edit of its language.") + "\n");
1990
+ }
1991
+ await set(rows[idx].id, rows[idx].choice !== "on");
1992
+ }
1993
+
1994
+ // ---------- autocompact (GH #538) ------------------------------------------------------------
1995
+ // When the agent compacts a turn's older steps: asked once per computer (no answer = 400k, all
1996
+ // models), changed with /autocompact. The agent reads the same file. See autocompact.mjs.
1997
+ const AUTOCOMPACT_FILE = autocompactPath(homedir());
1998
+ const loadAutocompact = () => {
1999
+ try {
2000
+ return readAutocompact(readFileSync(AUTOCOMPACT_FILE, "utf8"));
2001
+ } catch {
2002
+ return readAutocompact("");
2003
+ }
2004
+ };
2005
+ function saveAutocompact(state) {
2006
+ mkdirSync(dirname(AUTOCOMPACT_FILE), { recursive: true });
2007
+ writeFileSync(AUTOCOMPACT_FILE, writeAutocompact(state));
2008
+ }
2009
+
2010
+ /** The startup question — only when it has never been answered, and only on a terminal. */
2011
+ async function askAutocompactOnce() {
2012
+ if (!process.stdin.isTTY || loadAutocompact().answered) return;
2013
+ const model = activeCodingModelId();
2014
+ const { title, body } = startupText();
2015
+ console.log(GUTTER + accent(title) + dim(` (no answer in ${AUTOCOMPACT_ASK_MS / 1000}s = Apply, all models)`));
2016
+ console.log(wrapGutter(body, dim));
2017
+ const choices = startupChoices(model);
2018
+ const idx = await pickFromList(choices.map((c) => c.label), 0, { timeoutMs: AUTOCOMPACT_ASK_MS, timeoutIndex: 0 });
2019
+ // Esc (or anything that is not a row) is "not choosing" — and not choosing means the default.
2020
+ const pick = choices[idx] ?? choices[0];
2021
+ const state = applyChoice(loadAutocompact(), pick.apply, model);
2022
+ try {
2023
+ saveAutocompact(state);
2024
+ console.log(GUTTER + accent("✓ " + describeAutocompact(state, model)) + "\n");
2025
+ } catch (e) {
2026
+ console.log(GUTTER + yellow(`could not save the autocompact choice (${e?.message || e}) — gu will ask again next time.`) + "\n");
2027
+ }
2028
+ }
2029
+
2030
+ /** /autocompact [<tokens>|keep] — a picker without an argument, all models with one. */
2031
+ async function autocompactCommand(arg) {
2032
+ const model = activeCodingModelId();
2033
+ let state = loadAutocompact();
2034
+ if (String(arg ?? "").trim()) {
2035
+ const parsed = parseAutocompactArg(arg);
2036
+ if (!parsed) {
2037
+ console.log(GUTTER + dim("usage: /autocompact · /autocompact 400k · /autocompact keep") + "\n");
2038
+ return;
2039
+ }
2040
+ state = applyChoice(state, { scope: "all", cap: parsed.cap }, model);
2041
+ } else {
2042
+ console.log(GUTTER + dim(describeAutocompact(state, model)));
2043
+ const { rows, current } = commandChoices(state, model);
2044
+ const idx = await pickFromList(rows.map((r) => r.label), current);
2045
+ if (idx < 0 || !rows[idx]) {
2046
+ console.log(GUTTER + dim("(unchanged)") + "\n");
2047
+ return;
2048
+ }
2049
+ state = applyChoice(state, rows[idx].apply, model);
2050
+ }
2051
+ try {
2052
+ saveAutocompact(state);
2053
+ console.log(GUTTER + accent("✓ " + describeAutocompact(state, model)) + dim(" · from the next turn") + "\n");
2054
+ } catch (e) {
2055
+ console.log(GUTTER + yellow(`could not save it (${e?.message || e})`) + "\n");
2056
+ }
2057
+ }
2058
+
2059
+ // ---------- the next message, suggested (GH #536) -------------------------------------------
2060
+ // After SOME turns the empty input shows a dim suggestion; Tab puts it in the input. See
2061
+ // next-suggestion.mjs for when (two gates: cheap rules, then the coder answering NONE or a reply).
2062
+ const SUGGESTIONS_FILE = join(homedir(), ".gonext", "prompt-suggestions");
2063
+ let suggestionsOn = (() => {
2064
+ try {
2065
+ return suggestionsOnFromFile(readFileSync(SUGGESTIONS_FILE, "utf8"));
2066
+ } catch {
2067
+ return true; // never set: on
2068
+ }
2069
+ })();
2070
+ let nextHint = ""; // the suggestion on screen now, "" when none
2071
+ let _nextHintSeq = 0; // bumped by anything that makes a pending suggestion stale
2072
+
2073
+ /** Take the suggestion away (typing, Esc, a new question, a later turn). */
2074
+ function clearNextHint() {
2075
+ _nextHintSeq++;
2076
+ if (!nextHint) return;
2077
+ nextHint = "";
2078
+ paintBar();
2079
+ }
2080
+
2081
+ /**
2082
+ * A key while a suggestion is shown (called from _ttyWrite). Tab TAKES it into the input — not
2083
+ * sent, to edit or Enter — and the key is used up (→ true). Anything else the user does with the
2084
+ * keyboard (typing, Esc, arrows, Enter, a paste) puts it away and goes on as usual; Shift+Tab
2085
+ * (the edit mode) leaves it.
2086
+ */
2087
+ function nextHintKey(str, key) {
2088
+ if (key?.name === "tab" && !key.shift && !key.ctrl && !key.meta && promptIdleForHint()) {
2089
+ const take = nextHint;
2090
+ clearNextHint();
2091
+ rl.line = take;
2092
+ rl.cursor = take.length;
2093
+ rl._refreshLine();
2094
+ paintBar();
2095
+ return true;
2096
+ }
2097
+ const typing = (key?.name && key.name !== "tab") || (typeof str === "string" && str.length > 0 && !str.startsWith("\x1b"));
2098
+ if (typing) clearNextHint();
2099
+ return false;
2100
+ }
2101
+
2102
+ /** Is the prompt idle and empty — the only state a suggestion may be drawn into? */
2103
+ const promptIdleForHint = () =>
2104
+ barPinned() && footerActive && inputVisible && !following && rl.line === "" && !askWaiting && !secretInput
2105
+ && !inlinePrompt && !slashOverlayActive && !listPickerActive && !approvalActive && !zonePanel;
2106
+
2107
+ /**
2108
+ * After a completed turn: ask the coder it ran on for the obvious next message, in the background.
2109
+ * Fire-and-forget like the title: never delays anything, never prints, and a reply that arrives
2110
+ * after the user started typing (or asked something else) is thrown away.
2111
+ */
2112
+ function offerNextHint(question, answer) {
2113
+ clearNextHint();
2114
+ if (!shouldSuggest({ question, answer, enabled: suggestionsOn })) return;
2115
+ const mine = _nextHintSeq;
2116
+ void (async () => {
2117
+ const settings = await fetchWorkerSettings();
2118
+ if (!settings || mine !== _nextHintSeq) return;
2119
+ const target = titleModel(settings, { url: activeCodingUrl(), model: activeCodingModelId() });
2120
+ if (!target) return;
2121
+ const key = target.backendId ? await fetchKeyForBackend(target.backendId) : null;
2122
+ if (mine !== _nextHintSeq) return;
2123
+ const hint = await suggestNext({ question, answer }, { fetchImpl: doctorFetch, target, apiKey: key?.apiKey ?? "" });
2124
+ if (!hint || mine !== _nextHintSeq || !promptIdleForHint()) return;
2125
+ nextHint = hint;
2126
+ paintBar();
2127
+ })().catch(() => {});
2128
+ }
2129
+
1851
2130
  /**
1852
2131
  * A new question: the trimmed text now, and — only when it had to be cut — the agent model's
1853
2132
  * few-word summary whenever it arrives. Fire-and-forget by design: it never delays the turn,
@@ -3376,6 +3655,8 @@ function frozenZone() {
3376
3655
  // clipboard.
3377
3656
  selection: secretInput ? null : inputSelection,
3378
3657
  highlight: highlightRow,
3658
+ // GH #536: the suggested next message, while the prompt is idle and empty.
3659
+ ghost: nextHint && promptIdleForHint() ? dim(ghostText(nextHint)) : "",
3379
3660
  });
3380
3661
  const footer = footerBuilt();
3381
3662
  const rows = status.concat(notice ? [notice.row] : [], zone.rows, askHintRows(width), footer.rows);
@@ -3957,6 +4238,23 @@ const hoverCtl = createHoverController({
3957
4238
  * lines 2×", one row until it is clicked open. They differ only in how their rows are made, so
3958
4239
  * that is the one place they are told apart.
3959
4240
  */
4241
+ /**
4242
+ * One row of a step group, painted (GH #530): dim, or bright while hovered; the command count bold
4243
+ * and "1 failed" red — the only part of the row that asks to be read. Hovered, the row is one
4244
+ * bright run (the cue it opens): neighbouring spans of one colour are painted together.
4245
+ */
4246
+ const paintStepRow = (text, hovered) => {
4247
+ const plain = (s) => (hovered ? hoverThought(s) : dim(s));
4248
+ const spanPaint = { count: hovered ? plain : bold, failed: red };
4249
+ const runs = [];
4250
+ for (const sp of stepRowSpans(text)) {
4251
+ const fn = spanPaint[sp.style] ?? plain;
4252
+ if (runs.length && runs[runs.length - 1].fn === fn) runs[runs.length - 1].text += sp.text;
4253
+ else runs.push({ fn, text: sp.text });
4254
+ }
4255
+ return runs.map((x) => x.fn(x.text)).join("");
4256
+ };
4257
+
3960
4258
  const paintThoughtRows = (block, hovered, collapsed = block.collapsed) => {
3961
4259
  if (block.kind === "command") {
3962
4260
  // #204: the Allow prompt's command — wrapped under its own indent, long ones collapsed.
@@ -3964,12 +4262,8 @@ const paintThoughtRows = (block, hovered, collapsed = block.collapsed) => {
3964
4262
  return commandBlockRows(block.text, { width: commandWidth(), indent: GUTTER, collapsed, maxRows: COMMAND_COLLAPSED_ROWS }).map(paint);
3965
4263
  }
3966
4264
  if (block.kind === "steps") {
3967
- // Activity (look-ups, finished commands): dim, like a ✓ row; bright while hovered.
3968
- const paint = (r) => (hovered ? hoverThought(r) : dim(r));
3969
- const ok = stepGroupMark(block.items) === "ok";
3970
- return stepGroupRows(block.items, { width: thoughtWidth(), collapsed }).map(
3971
- (r) => (r.head ? markLine(ok ? accent(CHECK) : dim(BULLET)) : GUTTER) + paint(r.text)
3972
- );
4265
+ // Activity (look-ups, commands): dim, bright while hovered, NO mark (GH #530).
4266
+ return stepGroupRows(block.items, { width: thoughtWidth(), collapsed }).map((r) => GUTTER + paintStepRow(r.text, hovered));
3973
4267
  }
3974
4268
  // THE AGENT'S OWN WORDS ARE WHITE (#383, GitHub #173) — what it found, what it will do next.
3975
4269
  // They were grey scaffolding (#148), as dim as the commands, and the user missed them; now
@@ -4826,6 +5120,7 @@ if (process.stdin.isTTY) {
4826
5120
  // for the whole paste window; `pasteBuffer` is opened on the paste-start event, which is
4827
5121
  // fully dispatched before the first payload key arrives.
4828
5122
  if (pasteBuffer !== null) return;
5123
+ if (focusReport(key)) return; // switching windows is not typing (GH #558)
4829
5124
  // The wheel is not the keyboard (see trackMouseKey): scrolling must not count as typing,
4830
5125
  // or it undoes itself.
4831
5126
  if (trackMouseKey(_ch, key)) return;
@@ -4848,6 +5143,7 @@ if (process.stdin.isTTY) {
4848
5143
  // re-rendered the slash overlay (the line still starts with "/" from before the paste) and
4849
5144
  // re-walked the paste store. Same for a mouse report's characters, which are not keys.
4850
5145
  if (pasteBuffer !== null) return;
5146
+ if (focusReport(key)) return; // GH #558
4851
5147
  if (inMouseKeyWindow()) {
4852
5148
  turnTyping.reset(); // a held "[" was the start of that report (GH #382)
4853
5149
  return;
@@ -5032,7 +5328,7 @@ const MOUSE_OFF = "\x1b[?1003l\x1b[?1002l\x1b[?1000l\x1b[?1006l";
5032
5328
  let _mouseEnabled = false;
5033
5329
  const enableMouse = () => {
5034
5330
  if (!hoverMouse || _mouseEnabled || !process.stdin.isTTY) return;
5035
- ui(MOUSE_ON);
5331
+ if (!mouseParking?.parked()) ui(MOUSE_ON); // away (GH #558): focus-in turns it on
5036
5332
  _mouseEnabled = true;
5037
5333
  };
5038
5334
  const disableMouse = () => {
@@ -5041,7 +5337,7 @@ const disableMouse = () => {
5041
5337
  _mouseEnabled = false;
5042
5338
  // MOUSE_OFF clears ?1000/?1006 as well, which is OUR wheel + click capture (task #141) —
5043
5339
  // put it straight back, or scrolling silently returns to the terminal after a /hover turn.
5044
- if (_clickEnabled) ui(CLICK_ON);
5340
+ if (_clickEnabled && !mouseParking?.parked()) ui(CLICK_ON);
5045
5341
  };
5046
5342
  // ---------- click-to-position the caret at the PROMPT (task #137) ------------------------
5047
5343
  // BUTTON-ONLY reporting (?1000h), NOT the any-motion ?1003h the hover feature uses: a click
@@ -5075,8 +5371,10 @@ const enableClickToPosition = () => {
5075
5371
  if (_clickEnabled || !process.stdin.isTTY) return;
5076
5372
  // Never fight the hover mode: ?1003h already reports clicks, so if it's on, leave it alone.
5077
5373
  // Bracketed paste is enabled once at startup (see the _ttyWrite wrap), not here.
5078
- if (CLICK_TO_POSITION_ENABLED && !_mouseEnabled) ui(CLICK_ON);
5374
+ if (CLICK_TO_POSITION_ENABLED && !_mouseEnabled && !mouseParking?.parked()) ui(CLICK_ON);
5079
5375
  _clickEnabled = true;
5376
+ // A new prompt starts the idle clock over SSH (GH #558) without taking a let-go mouse back.
5377
+ mouseParking?.arm();
5080
5378
  };
5081
5379
  const disableClickToPosition = () => {
5082
5380
  if (!_clickEnabled) return;
@@ -5088,6 +5386,21 @@ const disableClickToPosition = () => {
5088
5386
  _clickEnabled = false;
5089
5387
  };
5090
5388
 
5389
+ // GH #558: let go of the mouse while the window is away, so a gu that dies without exiting (an
5390
+ // SSH connection reset, kill -9) cannot leave the terminal reporting every move to the shell.
5391
+ // The idle release is for SSH only: a local gu that exits clears the modes itself.
5392
+ const MOUSE_IDLE_MS = 3 * 60 * 1000;
5393
+ mouseParking = createMouseParking({
5394
+ idleMs: process.env.SSH_CONNECTION || process.env.SSH_TTY ? MOUSE_IDLE_MS : 0,
5395
+ release: () => {
5396
+ if (_mouseEnabled || _clickEnabled) ui(MOUSE_OFF);
5397
+ },
5398
+ restore: () => {
5399
+ if (_mouseEnabled) ui(MOUSE_ON);
5400
+ else if (_clickEnabled && CLICK_TO_POSITION_ENABLED) ui(CLICK_ON);
5401
+ },
5402
+ });
5403
+ process.on("exit", () => mouseParking.stop());
5091
5404
  // Safety net: never leave the user's terminal in mouse-reporting mode (would break their
5092
5405
  // shell's selection) if we exit ungracefully.
5093
5406
  process.on("exit", disableMouse);
@@ -7827,6 +8140,7 @@ function withTerminalHandedOver(run, { keepScreen = false } = {}) {
7827
8140
  disableMouse();
7828
8141
  disableClickToPosition();
7829
8142
  ui(PASTE_MODE_OFF);
8143
+ ui(FOCUS_MODE_OFF); // an editor or pager must not receive our focus reports
7830
8144
  if (!keepScreen) unpinBar();
7831
8145
  const wasRaw = Boolean(process.stdin.isRaw);
7832
8146
  try {
@@ -7845,6 +8159,7 @@ function withTerminalHandedOver(run, { keepScreen = false } = {}) {
7845
8159
  }
7846
8160
  rl.resume();
7847
8161
  ui(PASTE_MODE_ON);
8162
+ ui(FOCUS_MODE_ON);
7848
8163
  if (hadHover) enableMouse();
7849
8164
  if (hadClick) enableClickToPosition();
7850
8165
  // The window may have been resized while the editor ran, and no resize event reached us.
@@ -8943,7 +9258,14 @@ async function noteTurnCost(inputTokens, breakdown, coder = null) {
8943
9258
  const rows = await loadPrices();
8944
9259
  const url = coder?.url ?? activeCodingUrl();
8945
9260
  const model = coder?.model ?? activeCodingModelId();
8946
- const price = mp.findPrice(rows, url, model);
9261
+ // GH #533: on the free model's key the allowance charges the PROMO's price (its own, else the dearest
9262
+ // listed) — the bar shows that, even when the published table has a (pay-as-you-go estimate) row too.
9263
+ let price = null;
9264
+ if (freeModel) {
9265
+ const fm = await import("./free-model.mjs");
9266
+ price = fm.freeModelPriceRow(freeModel, url, model);
9267
+ }
9268
+ price ??= mp.findPrice(rows, url, model);
8947
9269
  const cache = readTurnCache(breakdown) ?? { cached: 0, cacheReported: false, firstIn: 0 };
8948
9270
  const c = mp.turnCost({ input: inputTokens, ...cache, price });
8949
9271
  if (!c) {
@@ -11840,6 +12162,8 @@ const MCPTOOL_PREFIX = "__MCPTOOL__::";
11840
12162
  // The agent's first use of the browser in a turn (#150): "<folder>\t<what it is about to do>".
11841
12163
  // "Always" puts the folder on ~/.gonext/browser-allow.json, which the agent reads before asking.
11842
12164
  const BROWSER_PREFIX = "__BROWSER__::";
12165
+ // GH #540: the agent edited a file whose language has a server gu could use — offer it.
12166
+ const LSP_PREFIX = "__LSP__::";
11843
12167
  // How long the browser question waits before "Yes, this time" (GH #411).
11844
12168
  const BROWSER_APPROVAL_MS = 10_000;
11845
12169
  async function approvalPrompt(command) {
@@ -11899,6 +12223,42 @@ async function approvalPrompt(command) {
11899
12223
  );
11900
12224
  return { allow: idx === 0, dontAsk: false };
11901
12225
  }
12226
+ if (command.startsWith(LSP_PREFIX)) {
12227
+ // Claude Code's rules: Yes / Not now / Never for this language / Never ask; no answer in 30 s
12228
+ // counts as ignored, and after 5 ignored offers gu stops offering. Every answer is saved here —
12229
+ // the worker's host only reads the file. Only "Yes" lets the agent go on to use it now.
12230
+ const [id = "", name = "", server = "", how = "", size = ""] = command.slice(LSP_PREFIX.length).split("\t");
12231
+ const lang = lspById(id, allLanguages({ home: homedir(), workspace: resolve(process.cwd()) }));
12232
+ if (!lang || !process.stdin.isTTY) return { allow: false, dontAsk: false };
12233
+ const needsInstall = how === "install";
12234
+ const where = lang.custom
12235
+ // A project's lsp.json names a program to run — say exactly which, and from which file, so a
12236
+ // cloned repo cannot start something unseen (GH #542).
12237
+ ? ` It runs: ${[lang.command, ...lang.args].join(" ")} (set in ${lang.source.replace(homedir(), "~")}).`
12238
+ : !needsInstall
12239
+ ? " It is already on this computer — nothing to download."
12240
+ : lang.tool
12241
+ ? ` gu runs \`${lang.tool.what}\` (${size || lang.size}). It is open source (${lang.licence}).`
12242
+ : ` gu installs it from npm (${size || lang.size}, into ~/.gonext/lsp — no admin rights). It is open source (${lang.licence}).`;
12243
+ process.stdout.write(
12244
+ // GH #554: on the gutter like every other line of the turn — it sat two columns to the left.
12245
+ "\n" + GUTTER + accent(`${name} code intelligence`) + dim(` (no answer in ${LSP_OFFER_MS / 1000}s = not now)`) + "\n" +
12246
+ wrapGutter(
12247
+ `The agent just edited a ${name} file. With ${server} (a language server) it sees compile and type errors right after each edit and fixes them before it says it is done.` + where,
12248
+ dim,
12249
+ ) + "\n",
12250
+ );
12251
+ const idx = await pickFromList(offerRows(lang, { needsInstall }), 0, { timeoutMs: LSP_OFFER_MS, timeoutIndex: -2 });
12252
+ const choice = idx === -2 ? "ignored" : OFFER_CHOICES[idx] ?? "not-now";
12253
+ saveLspState(applyOfferAnswer(loadLspState(), id, choice));
12254
+ const said = {
12255
+ yes: needsInstall ? `installing ${server} — errors are checked from the next edit. /lsp shows it.` : `${name} code intelligence is on. /lsp turns it off.`,
12256
+ never: `won't offer ${name} again — /lsp turns it on.`,
12257
+ "never-ask": "won't offer language servers again — /lsp turns one on.",
12258
+ }[choice];
12259
+ if (said) process.stdout.write(GUTTER + dim(said) + "\n");
12260
+ return { allow: choice === "yes", dontAsk: false };
12261
+ }
11902
12262
  if (command.startsWith(BROWSER_PREFIX)) {
11903
12263
  const [folder = "", what = ""] = command.slice(BROWSER_PREFIX.length).split("\t");
11904
12264
  if (!process.stdin.isTTY) return { allow: false, dontAsk: false };
@@ -15416,15 +15776,28 @@ async function main() {
15416
15776
  // anyway: one is already bound to the port. On loopback a 15s wait rather than an
15417
15777
  // instant refusal almost always means the API is up but stuck on MongoDB.
15418
15778
  const hung = isTimeout(err);
15779
+ // Name the storage this computer actually uses (GH #557 follow-up): a gudb computer has no
15780
+ // MongoDB, and telling its owner to look at one sends them after a program they never had.
15781
+ let onGudb = false;
15782
+ try {
15783
+ const { readLocalDb } = await import("./client-expert-api.mjs");
15784
+ onGudb = readLocalDb() === "gudb";
15785
+ } catch {
15786
+ /* unknown — say MongoDB, as before */
15787
+ }
15419
15788
  console.error(
15420
15789
  red("gu: the local API " + (hung ? "is not answering on " : "isn't running on ") + apiBase + ".") +
15421
- dim("\n Local mode keeps your conversations in MongoDB on this machine, and that") +
15422
- dim("\n API is what reads it. It does not survive a reboot on its own.\n")
15790
+ dim(
15791
+ onGudb
15792
+ ? "\n Local mode keeps your conversations in a database file on this machine, and"
15793
+ : "\n Local mode keeps your conversations in MongoDB on this machine, and that"
15794
+ ) +
15795
+ dim(onGudb ? "\n that API is what reads it. It does not survive a reboot on its own.\n" : "\n API is what reads it. It does not survive a reboot on its own.\n")
15423
15796
  );
15424
15797
  // ASK MONGODB ITSELF before telling the reader to (task #329). It can die AFTER the startup
15425
15798
  // check passed, and "is mongod running?" is a question this process answers in milliseconds.
15426
15799
  let mongoDown = "";
15427
- if (hung) {
15800
+ if (hung && !onGudb) {
15428
15801
  try {
15429
15802
  const { localMongoDown } = await import("./client-expert-run.mjs");
15430
15803
  const { localMongoUri } = await import("./client-expert-api.mjs");
@@ -15443,11 +15816,11 @@ async function main() {
15443
15816
  // Do NOT try to start it — the port is taken by the process that is failing to answer.
15444
15817
  console.error(
15445
15818
  dim(" Something IS listening there but did not reply within ") +
15446
- dim(`${API_CALL_TIMEOUT_MS / 1000}s, so the API is running and stuck —`) +
15447
- dim("\n usually on MongoDB. Check, in this order:") +
15819
+ dim(`${API_CALL_TIMEOUT_MS / 1000}s, so the API is running and stuck` + (onGudb ? "." : " —")) +
15820
+ dim(onGudb ? "\n Check, in this order:" : "\n usually on MongoDB. Check, in this order:") +
15448
15821
  dim("\n gu-cli api status does it answer at all?") +
15449
15822
  dim("\n ~/.gonext/local-api.log what it was doing when it stopped answering") +
15450
- dim("\n is mongod running? the API waits on it and never times out itself") +
15823
+ (onGudb ? "" : dim("\n is mongod running? the API waits on it and never times out itself")) +
15451
15824
  dim("\n Then restart it: gu-cli api stop && gu-cli api start\n")
15452
15825
  );
15453
15826
  } else {
@@ -15489,6 +15862,7 @@ async function main() {
15489
15862
  }
15490
15863
  delete process.env.GU_API_REOPENED; // GH #397: started — the next start may re-open again
15491
15864
  console.log(wrapGutter("Ask about this repo. Type / to see commands (Tab completes). Ctrl-C aborts a running turn.", dim) + "\n");
15865
+ await askAutocompactOnce(); // GH #538: once per computer — no answer means 400k, all models
15492
15866
  // #221: gu runs, but its own npm folder is not on PATH (npm skipped the postinstall that adds it).
15493
15867
  try {
15494
15868
  const { pathNoticeLine } = await import("./env-check.mjs");
@@ -15732,6 +16106,7 @@ async function main() {
15732
16106
  if (turnQueue.size > 0 && _lineQueue.length === 0) _lineQueue.push(turnQueue.shift());
15733
16107
  for (;;) {
15734
16108
  lineRaw = await nextLine();
16109
+ clearNextHint(); // GH #536: whatever was sent, the suggestion was for the moment before it
15735
16110
  const echoed = enterEchoed;
15736
16111
  enterEchoed = false;
15737
16112
  if (lineRaw === null || lineRaw.trim()) break;
@@ -15851,6 +16226,30 @@ async function main() {
15851
16226
  printCommands();
15852
16227
  continue;
15853
16228
  }
16229
+ if (line === "/lsp" || line.startsWith("/lsp ")) {
16230
+ await lspCommand(line.slice("/lsp".length));
16231
+ continue;
16232
+ }
16233
+ if (line === "/autocompact" || line.startsWith("/autocompact ")) {
16234
+ await autocompactCommand(line.slice("/autocompact".length));
16235
+ continue;
16236
+ }
16237
+ if (line === "/suggestions" || line.startsWith("/suggestions ")) {
16238
+ // GH #536: the suggested next message after a turn — on by default, remembered for every folder.
16239
+ suggestionsOn = suggestionsToggle(line.slice("/suggestions".length), suggestionsOn);
16240
+ try {
16241
+ mkdirSync(dirname(SUGGESTIONS_FILE), { recursive: true });
16242
+ writeFileSync(SUGGESTIONS_FILE, suggestionsOn ? "on\n" : "off\n");
16243
+ } catch {}
16244
+ if (!suggestionsOn) clearNextHint();
16245
+ console.log(
16246
+ GUTTER + (suggestionsOn ? accent("suggestions: ON") : dim("suggestions: OFF")) +
16247
+ dim(suggestionsOn
16248
+ ? " — after some answers a next message appears in the input; Tab takes it.\n"
16249
+ : " — no suggested next message after a turn. /suggestions on brings it back.\n")
16250
+ );
16251
+ continue;
16252
+ }
15854
16253
  if (line === "/hover") {
15855
16254
  // Mouse hover/click on the thinking line (#96) vs. scrolling during a turn: the terminal
15856
16255
  // only reports wheel events to US when mouse tracking is on, so they're exclusive. Off by
@@ -16429,6 +16828,8 @@ async function main() {
16429
16828
  // #343: the turn's own record of the fallback, under its answer — the bar's row can be
16430
16829
  // gone by the next turn, and the scrollback is where "which model wrote this?" is asked.
16431
16830
  if (fellBack) printFallbackLine(fellBack);
16831
+ // GH #536: maybe a suggested next message — not when a queued question runs next anyway.
16832
+ if (turnQueue.size === 0 && _lineQueue.length === 0) offerNextHint(taskLine, answer);
16432
16833
  } else {
16433
16834
  // A turn that ended WITHOUT an answer (Ctrl+C cancel, or an abort/failure) must not
16434
16835
  // silently launch another turn. Any keystrokes the user typed DURING the dead turn