@tiens.nguyen/gu-cli 1.0.900 → 1.0.902

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.
@@ -1048,6 +1048,25 @@ export function settingsPatch({ existing = {}, models = CLIENT_EXPERT_MODELS, sk
1048
1048
  * makes the real decision a moment later. Being wrong in that direction costs a question; being
1049
1049
  * wrong the other way costs the answer.
1050
1050
  */
1051
+ /**
1052
+ * Did a previous setup already choose models? ANY of the agent, the coder or the embedder counts.
1053
+ *
1054
+ * It used to be "settingsPatch(existing) is empty", i.e. EVERY role present — compared with the shared
1055
+ * defaults, which include an embedder. A box with no embedding model (so setup rightly wrote none) never
1056
+ * matched, and a completed machine re-asked all seven questions on every run. A role the user left
1057
+ * out is theirs to add later with /model; it is not a reason to ask again. A skipped setup writes no
1058
+ * model field at all, so it still asks.
1059
+ */
1060
+ export function modelsConfiguredIn(existing = {}) {
1061
+ const has = (v) => Boolean(String(v ?? "").trim());
1062
+ return (
1063
+ has(existing.agentModelUrl) || has(existing.agentModelName) || has(existing.agentModel) ||
1064
+ has(existing.agentCodingModelUrl) || has(existing.agentCodingModelName) ||
1065
+ (Array.isArray(existing.agentCodingBackends) && existing.agentCodingBackends.length > 0) ||
1066
+ existing.ragEnabled === true || has(existing.ragEmbedUrl)
1067
+ );
1068
+ }
1069
+
1051
1070
  export async function modelsAlreadyConfigured({
1052
1071
  apiDir,
1053
1072
  mongoUri = localMongoUri(),
@@ -1060,7 +1079,7 @@ export async function modelsAlreadyConfigured({
1060
1079
  await client.connect();
1061
1080
  try {
1062
1081
  const existing = (await client.db(dbName).collection("settings").findOne({ userId })) ?? {};
1063
- return Object.keys(settingsPatch({ existing })).length === 0;
1082
+ return modelsConfiguredIn(existing);
1064
1083
  } finally {
1065
1084
  await client.close().catch(() => {});
1066
1085
  }
@@ -449,6 +449,23 @@ export const MAX_BACKENDS = 8;
449
449
  * MAX_MODELS_PER_SERVER in api/src/store/settingsTypes.ts, which refuses a row that grows past it. */
450
450
  export const MAX_MODELS_PER_SERVER = 3;
451
451
 
452
+ /** The models one saved server row offers, its main (default) model first, no repeats (GH #412). */
453
+ export function rowModels(row) {
454
+ const all = [row?.defaultModel, ...(Array.isArray(row?.models) ? row.models : [])];
455
+ return [...new Set(all.map((m) => String(m ?? "").trim()).filter(Boolean))];
456
+ }
457
+
458
+ /**
459
+ * The row with `model` in place of `drop` (GH #412): a server already offering
460
+ * MAX_MODELS_PER_SERVER models cannot grow, so a new pick takes a slot. Replacing the main model
461
+ * makes the new pick the main one. Pure — the caller saves it.
462
+ */
463
+ export function replaceRowModel(row, drop, model) {
464
+ const extras = (Array.isArray(row?.models) ? row.models : []).filter((m) => m !== model);
465
+ if (String(row?.defaultModel ?? "").trim() === drop) return { ...row, defaultModel: model, models: extras.filter((m) => m !== drop) };
466
+ return { ...row, models: extras.map((m) => (m === drop ? model : m)) };
467
+ }
468
+
452
469
  /**
453
470
  * The backend rows an account ALREADY has, in the shape a save must preserve.
454
471
  *
@@ -0,0 +1,194 @@
1
+ /**
2
+ * CONNECTION WATCH (GH #409) — say so when the machine cannot reach the model.
3
+ *
4
+ * Reported: the MacBook lost its internet connection in the middle of a turn and the live line kept
5
+ * reading "Thinking… (821s)". With a LOCAL API (Client Expert) the job poll still works — the API is on
6
+ * this machine — so nothing in the poll loop notices that the model host (Kimi, Claude, Qwen…) is
7
+ * unreachable; the agent waits on its own timeouts and the counter just climbs.
8
+ *
9
+ * THE RULE: the stream is quiet for a while → ask the model host(s) whether they answer at all. ANY HTTP
10
+ * response (even 401/404/405) means "reachable"; only a thrown error — no DNS, refused, no route, timed
11
+ * out — means "cannot reach". It is a probe of the network path, not of the model: a slow model is not an
12
+ * outage, and a quiet stream alone never produces the warning.
13
+ *
14
+ * Pure (a probe and a clock are passed in) so every state is testable without a network.
15
+ */
16
+
17
+ /** Seconds of silence before the first probe: a streaming model is never silent this long. */
18
+ export const QUIET_BEFORE_PROBE_MS = 15_000;
19
+ /** How often to probe while quiet — often enough to notice the way back within a few seconds. */
20
+ export const PROBE_EVERY_MS = 6_000;
21
+ /** A probe that has not answered by now counts as "cannot reach". */
22
+ export const PROBE_TIMEOUT_MS = 5_000;
23
+ /** Down this long: add the way out (Ctrl-C) to the line. */
24
+ export const SHOW_WAY_OUT_AFTER_MS = 30_000;
25
+ /**
26
+ * A HOSTED model that has sent nothing for this long is almost certainly not working on it: they stream, and
27
+ * they ping. (A box on this machine or the LAN may legitimately spend minutes on a cold prompt-eval, so it
28
+ * is never flagged.) Longer than any normal pause, shorter than the hour the old client would have waited.
29
+ */
30
+ export const HOSTED_STALL_AFTER_MS = 240_000;
31
+ /** Failed checks in a row before "No connection" is shown. */
32
+ export const MISSES_BEFORE_DOWN = 2;
33
+
34
+ /** A host on this machine or a private network: slow there means busy, not lost. */
35
+ export function isPrivateHost(host) {
36
+ const h = String(host ?? "").replace(/:\d+$/, "").replace(/^\[|\]$/g, "").toLowerCase();
37
+ return (
38
+ h === "localhost" || h === "::1" || h.endsWith(".local") || h.endsWith(".lan") || h.endsWith(".internal") ||
39
+ /^127\./.test(h) || /^10\./.test(h) || /^192\.168\./.test(h) || /^172\.(1[6-9]|2\d|3[01])\./.test(h) ||
40
+ /^(fc|fd)[0-9a-f]{2}:/.test(h) || !h.includes(".") && !h.includes(":")
41
+ );
42
+ }
43
+
44
+ /**
45
+ * Hosted model providers whose silence is worth flagging. A allow-list on purpose: a box with a public name
46
+ * (the user's own Ollama behind a domain, a Tailscale address) can spend minutes on a cold prompt and is not
47
+ * "lost", so the stall warning is never shown for it.
48
+ */
49
+ const KNOWN_PROVIDER_SUFFIXES = [
50
+ "api.anthropic.com", "api.openai.com", "api.moonshot.ai", "api.moonshot.cn", "ollama.com", "openrouter.ai",
51
+ "api.deepseek.com", "generativelanguage.googleapis.com", "api.mistral.ai", "api.x.ai", "api.groq.com",
52
+ "aliyuncs.com", "api.together.xyz", "api.fireworks.ai",
53
+ ];
54
+ export function isKnownProviderHost(host) {
55
+ const h = String(host ?? "").replace(/:\d+$/, "").toLowerCase();
56
+ return KNOWN_PROVIDER_SUFFIXES.some((x) => h === x || h.endsWith(`.${x}`));
57
+ }
58
+
59
+ /** A timing from the environment (the screen tests shorten these), else the default. */
60
+ function envMs(name, dflt) {
61
+ const v = Number(process.env[name]);
62
+ return Number.isFinite(v) && v > 0 ? v : dflt;
63
+ }
64
+
65
+ /** The origin of a model URL, ready for a HEAD request; "" when it is not a URL. */
66
+ export function probeUrlOf(url) {
67
+ try {
68
+ const u = new URL(String(url ?? "").trim());
69
+ if (!/^https?:$/.test(u.protocol)) return "";
70
+ return `${u.origin}/`;
71
+ } catch {
72
+ return "";
73
+ }
74
+ }
75
+
76
+ /** Distinct, probe-able hosts from the model URLs a turn depends on. → [{ host, url }] */
77
+ export function modelHostsOf(urls) {
78
+ const out = [];
79
+ const seen = new Set();
80
+ for (const raw of urls ?? []) {
81
+ const url = probeUrlOf(raw);
82
+ if (!url || seen.has(url)) continue;
83
+ seen.add(url);
84
+ out.push({ host: new URL(url).host, url });
85
+ }
86
+ return out;
87
+ }
88
+
89
+ /** Can this URL be reached at all? Any HTTP answer is yes; a thrown error is no. */
90
+ export async function probeReachable(url, { fetchImpl = fetch, timeoutMs = PROBE_TIMEOUT_MS } = {}) {
91
+ try {
92
+ await fetchImpl(url, { method: "HEAD", signal: AbortSignal.timeout(timeoutMs), redirect: "manual" });
93
+ return true;
94
+ } catch {
95
+ return false;
96
+ }
97
+ }
98
+
99
+ /**
100
+ * The watch. `poll` is called from the live ticker (several times a second) and is cheap: it starts at most
101
+ * one probe at a time, and only when the stream has been quiet.
102
+ *
103
+ * probe(url) → Promise<boolean> hosts() → [{ host, url }] now() → ms
104
+ */
105
+ export function createConnectionWatch({
106
+ probe,
107
+ hosts,
108
+ now = Date.now,
109
+ quietBeforeProbeMs = envMs("GONEXT_NET_QUIET_MS", QUIET_BEFORE_PROBE_MS),
110
+ probeEveryMs = envMs("GONEXT_NET_PROBE_EVERY_MS", PROBE_EVERY_MS),
111
+ } = {}) {
112
+ let down = false;
113
+ let host = "";
114
+ let downSince = 0;
115
+ let lastProbeAt = 0;
116
+ let checking = false;
117
+ let misses = 0; // consecutive failed checks: one slow DNS lookup or timeout is not an outage
118
+
119
+ async function check() {
120
+ checking = true;
121
+ try {
122
+ let unreachable = null;
123
+ for (const h of hosts()) {
124
+ if (!(await probe(h.url))) {
125
+ unreachable = h;
126
+ break;
127
+ }
128
+ }
129
+ if (unreachable) {
130
+ misses += 1;
131
+ if (misses >= MISSES_BEFORE_DOWN) {
132
+ if (!down) downSince = now();
133
+ down = true;
134
+ host = unreachable.host;
135
+ }
136
+ } else {
137
+ misses = 0;
138
+ down = false;
139
+ }
140
+ } finally {
141
+ checking = false;
142
+ lastProbeAt = now();
143
+ }
144
+ }
145
+
146
+ return {
147
+ /** Call with how long the stream has been quiet. Never throws, never awaits. */
148
+ poll(quietMs) {
149
+ // A stream that flows again ends the outage on its own: no need to wait for the next probe.
150
+ if (down && quietMs < quietBeforeProbeMs && !checking) {
151
+ down = false;
152
+ misses = 0;
153
+ return;
154
+ }
155
+ if (checking) return;
156
+ if (!down && quietMs < quietBeforeProbeMs) return;
157
+ if (now() - lastProbeAt < probeEveryMs) return;
158
+ void check().catch(() => {});
159
+ },
160
+ /** { down, host, downForMs } */
161
+ state() {
162
+ return { down, host, downForMs: down ? Math.max(0, now() - downSince) : 0 };
163
+ },
164
+ /** The hosted model that has gone quiet for too long (and is reachable, or we would say "no connection"). */
165
+ stalled(quietMs, stallAfterMs = HOSTED_STALL_AFTER_MS) {
166
+ if (down || quietMs < stallAfterMs) return null;
167
+ return hosts().find((h) => isKnownProviderHost(h.host)) ?? null;
168
+ },
169
+ };
170
+ }
171
+
172
+ /**
173
+ * The line shown while the model cannot be reached. Plain text — the caller paints it. Names the host,
174
+ * says what gu is doing about it, and (after a while) how to stop.
175
+ */
176
+ export function offlineLine({ host, downForMs, width = 80 } = {}) {
177
+ const s = Math.max(1, Math.round((downForMs ?? 0) / 1000));
178
+ const waited = s >= 120 ? `${Math.floor(s / 60)}m ${String(s % 60).padStart(2, "0")}s` : `${s}s`;
179
+ const base = `No connection to ${host || "the model"} — waiting for it (${waited})`;
180
+ const withExit = (downForMs ?? 0) >= SHOW_WAY_OUT_AFTER_MS ? `${base} · Ctrl-C stops` : base;
181
+ const max = Math.max(24, width - 8); // gutter + bullet; no other text rides on this row
182
+ if (withExit.length <= max) return withExit;
183
+ if (base.length <= max) return base;
184
+ return `No connection to ${host || "the model"} (${waited})`.slice(0, max);
185
+ }
186
+
187
+ /** The line for a hosted model that has been silent too long though the network is fine. */
188
+ export function stalledLine({ host, quietMs, width = 80 } = {}) {
189
+ const m = Math.max(1, Math.floor((quietMs ?? 0) / 60000));
190
+ const full = `No reply from ${host || "the model"} for ${m} min — Ctrl-C, then "continue"`;
191
+ const max = Math.max(24, width - 8);
192
+ if (full.length <= max) return full;
193
+ return `No reply from ${host || "the model"} for ${m} min · Ctrl-C`.slice(0, max);
194
+ }
@@ -212,6 +212,97 @@ def _should_proxy(url):
212
212
  return origin in _PROXY_ORIGINS
213
213
 
214
214
 
215
+ def _keepalive_socket_options():
216
+ """TCP keepalive for model connections (GH #409).
217
+
218
+ A laptop that loses Wi-Fi mid-request leaves the connection HALF-OPEN: the OS never reports an error, so a
219
+ client with a long read timeout (the code model's is an hour) waits the whole hour on a socket that can no
220
+ longer answer — the live line read "Thinking… (1198s)" with the internet already back. Keepalive makes the OS
221
+ probe the peer: a dead one fails in ~70s, while a SLOW-but-alive server (a long cold prompt-eval) still
222
+ answers the probes at TCP level and is not cut off. Seconds: first probe after 30, then every 10, 4 misses."""
223
+ opts = [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)]
224
+ idle, interval, count = 30, 10, 4
225
+ if hasattr(socket, "TCP_KEEPIDLE"): # Linux, Windows 10 1709+ (Python 3.12+)
226
+ opts.append((socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, idle))
227
+ elif sys.platform == "darwin":
228
+ opts.append((socket.IPPROTO_TCP, 0x10, idle)) # TCP_KEEPALIVE: macOS's name for the idle time
229
+ if hasattr(socket, "TCP_KEEPINTVL"):
230
+ opts.append((socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval))
231
+ if hasattr(socket, "TCP_KEEPCNT"):
232
+ opts.append((socket.IPPROTO_TCP, socket.TCP_KEEPCNT, count))
233
+ return opts
234
+
235
+
236
+ def _sdk_http(sdk_module_name):
237
+ """(http library, the SDK's default client class) for "openai" or "anthropic".
238
+
239
+ Newer SDKs use `httpx2`, a fork of httpx: building a client from `import httpx` hands the SDK an object of
240
+ the WRONG library, which it rejects — and that import is not even installed there. So take the library the
241
+ SDK's own DefaultHttpxClient is built on. (None, None) when it cannot be told."""
242
+ try:
243
+ import importlib # noqa: PLC0415
244
+ sdk = importlib.import_module(sdk_module_name)
245
+ cls = sdk.DefaultHttpxClient
246
+ for base in cls.__mro__[1:]:
247
+ top = base.__module__.split(".")[0]
248
+ if top.startswith("httpx"):
249
+ return importlib.import_module(top), cls
250
+ except Exception: # noqa: BLE001
251
+ pass
252
+ return None, None
253
+
254
+
255
+ def _env_proxy_for(url):
256
+ """The proxy the environment names for this URL (HTTPS_PROXY / HTTP_PROXY, honouring NO_PROXY), or None.
257
+
258
+ A client given its own `transport=` stops reading these variables (httpx2: `allow_env_proxies = trust_env and
259
+ transport is None`), so a keepalive transport has to apply them itself or a user behind an env-only proxy
260
+ would suddenly go direct (GH #409 review)."""
261
+ try:
262
+ import urllib.parse # noqa: PLC0415
263
+ import urllib.request # noqa: PLC0415
264
+ parts = urllib.parse.urlsplit(url or "")
265
+ if not parts.hostname or urllib.request.proxy_bypass_environment(parts.hostname):
266
+ return None
267
+ return urllib.request.getproxies().get(parts.scheme) or None
268
+ except Exception: # noqa: BLE001
269
+ return None
270
+
271
+
272
+ def _keepalive_transport(lib, sdk, base_url):
273
+ """An HTTPTransport with TCP keepalive that keeps what the SDK's default client would have had: gu's own
274
+ proxy for routed URLs, else the environment's proxy, and the SDK's connection limits."""
275
+ kw = {"socket_options": _keepalive_socket_options()}
276
+ proxy = _PROXY_URL if _should_proxy(base_url) else _env_proxy_for(base_url)
277
+ if proxy:
278
+ kw["proxy"] = proxy
279
+ try:
280
+ import importlib # noqa: PLC0415
281
+ limits = importlib.import_module(sdk)._constants.DEFAULT_CONNECTION_LIMITS
282
+ if limits is not None:
283
+ kw["limits"] = limits
284
+ except Exception: # noqa: BLE001
285
+ pass
286
+ return lib.HTTPTransport(**kw)
287
+
288
+
289
+ def _keepalive_http_client(base_url, sdk="openai"):
290
+ """The SDK's own default client, plus TCP keepalive (and the proxy, when one applies), for
291
+ OpenAI(http_client=...) / Anthropic(http_client=...). None when it cannot be built: the caller then takes
292
+ the SDK's default client, exactly as before.
293
+
294
+ NOTE: with gu's proxy on, keepalive protects the link to the PROXY, not proxy -> model; a proxy on this same
295
+ machine makes it a no-op for the far hop."""
296
+ try:
297
+ lib, cls = _sdk_http(sdk)
298
+ if lib is None:
299
+ return None
300
+ return cls(transport=_keepalive_transport(lib, sdk, base_url))
301
+ except Exception as e: # noqa: BLE001
302
+ _log(f"keepalive: could not build an http client ({_proxy_redact(e)}) — using the default")
303
+ return None
304
+
305
+
215
306
  def _proxy_http_client(base_url):
216
307
  """
217
308
  An httpx client bound to the proxy, for OpenAI(http_client=...), or None to leave the call
@@ -222,8 +313,10 @@ def _proxy_http_client(base_url):
222
313
  if not _should_proxy(base_url):
223
314
  return None
224
315
  try:
225
- import httpx # noqa: PLC0415
226
- return httpx.Client(proxy=_PROXY_URL, timeout=None)
316
+ lib, _cls = _sdk_http("openai")
317
+ if lib is None:
318
+ import httpx as lib # noqa: PLC0415
319
+ return lib.Client(proxy=_PROXY_URL, timeout=None)
227
320
  except Exception as e: # noqa: BLE001
228
321
  # Never fail the turn over this: a direct attempt produces a real network error the user
229
322
  # can act on, while an exception here would break a path that may not need the proxy.
@@ -1378,7 +1471,10 @@ class _AnthropicChatAdapter:
1378
1471
  kwargs["base_url"] = root
1379
1472
  if timeout:
1380
1473
  kwargs["timeout"] = timeout
1381
- if _PROXY_URL:
1474
+ _hc = _keepalive_http_client(root if root else "https://api.anthropic.com", "anthropic") # GH #409
1475
+ if _hc is not None:
1476
+ kwargs["http_client"] = _hc
1477
+ elif _PROXY_URL:
1382
1478
  kwargs["http_client"] = anthropic.DefaultHttpxClient(proxy=_PROXY_URL)
1383
1479
  sdk_client = anthropic.Anthropic(**kwargs)
1384
1480
  self._sdk = sdk_client
@@ -14586,7 +14682,11 @@ def run_agent_chat(cfg):
14586
14682
  # fails into OUR retry loop rather than eating the whole 30min worker budget.
14587
14683
  # max_retries=0: the openai client's own silent retries would otherwise
14588
14684
  # stack multiplicatively with ours (3 × 3 attempts).
14589
- client_kwargs={"timeout": _code_request_timeout(), "max_retries": 0},
14685
+ client_kwargs={
14686
+ "timeout": _code_request_timeout(), "max_retries": 0,
14687
+ # GH #409: a dead connection is noticed in ~70s, not after the hour above.
14688
+ **({"http_client": _hc} if (_hc := _keepalive_http_client(coding_base_url)) is not None else {}),
14689
+ },
14590
14690
  **extra_model_kwargs,
14591
14691
  )
14592
14692
  @tool
package/gu-repl.mjs CHANGED
@@ -160,6 +160,7 @@ import { globalPrefixOf } from "./install-path.mjs";
160
160
  import { indentBlock, commandBlockRows, wrapIndented } from "./terminal-layout.mjs"; // every line of an Allow-prompt detail indented (#189); wrapped + collapsible command (#204)
161
161
  import { firstGuOnPath, pathGuMismatch, guOnPathIsCurrent, updateAttemptRecord, repeatUpdateNotice } from "./update-verify.mjs";
162
162
  import { embedNotice, embedState, setupNoticeRows } from "./embed-model-command.mjs";
163
+ import { createConnectionWatch, modelHostsOf, offlineLine, probeReachable, stalledLine } from "./connection-watch.mjs";
163
164
  import { HINTS, pickHint, hintRow, hintFits, HINT_AFTER_SECONDS } from "./hints.mjs";
164
165
  import { normalizeQuick, quickReady, quickTarget, quickBarHint, quickWarning, QUICK_MAX } from "./quick-models.mjs";
165
166
  import {
@@ -1671,11 +1672,15 @@ function applyMouseReport(report) {
1671
1672
  * making, and a press that turns out to be a drag spends none of them.
1672
1673
  */
1673
1674
  function applyClick({ row, col }) {
1674
- // Scrolled back: the only thing a click does is bring the view home — via the affordance the
1675
- // bar is showing, or anywhere at all, since the caret is not what the user is aiming at.
1675
+ // Scrolled back: a click on the jump affordance brings the view home; a click on a thought or
1676
+ // look-up group opens/closes it IN PLACE (GH #195 — a long answer pushes the thought off the
1677
+ // screen, the reader scrolls up to its "(+19 more — click to expand)", and the click used to be
1678
+ // swallowed here); anywhere else, with no jump affordance showing, also goes home as before.
1676
1679
  if (scrolledBack()) {
1677
1680
  const t = jumpRowTarget;
1678
- if (!t || row === t.row) jumpToBottom();
1681
+ if (t && row === t.row) jumpToBottom();
1682
+ else if (toggleThoughtAtRow(row)) return;
1683
+ else if (!t) jumpToBottom();
1679
1684
  return;
1680
1685
  }
1681
1686
  // The update control (task #181), if it is showing and the click landed ON it. Checked by
@@ -4226,6 +4231,7 @@ function hoverThoughtAtRow(row) {
4226
4231
  /** Swap one recorded block for its other form and repaint from the transcript. */
4227
4232
  function toggleThoughtBlock(block) {
4228
4233
  const painted = paintThoughtRows(block, false, !block.collapsed);
4234
+ const rowsBefore = screenRows().length;
4229
4235
  const newEnd = transcript.replaceRange(block.from, block.to, painted);
4230
4236
  if (newEnd === null) {
4231
4237
  // Scrolled out of the buffer — the block is gone, and so is the thing to toggle.
@@ -4236,7 +4242,10 @@ function toggleThoughtBlock(block) {
4236
4242
  // that arithmetic lives so a test can run it against real thoughts.
4237
4243
  applyToggleShift(thoughtBlocks, block, newEnd);
4238
4244
  hoverCtl.reset(); // the rows moved under the pointer — re-resolve on the next report
4239
- paintLiveTail();
4245
+ // At the live tail this is paintLiveTail, as before. Scrolled back (GH #195), it keeps the same
4246
+ // lines at the top of the view so the block opens under the pointer instead of the view
4247
+ // jumping to the bottom.
4248
+ repaintTailOrHoldView(rowsBefore);
4240
4249
  // #204: the Yes/No rows are in-place UI, not transcript — the repaint above wiped them, so the
4241
4250
  // open picker draws them again right under the (re-sized) command block.
4242
4251
  if (approvalActive) drawApprovalOptions(false);
@@ -7345,10 +7354,25 @@ async function chooseModel() {
7345
7354
  const activeChoice = choices[activeIdx >= 0 ? activeIdx : choices.findIndex((c) => c.id === def)];
7346
7355
  const activeUrl = String(activeChoice?.url ?? "");
7347
7356
  const keyHost = activeChoice && ((activeChoice.kind ?? "") === "openai" || /(^|\.)ollama\.com$/i.test(hostOf(activeUrl))) ? hostOf(activeUrl) : "";
7348
- // …and the rest of that server's models, the same row /agent-model has (#248). Not for local MLX.
7349
- const modelsHost = activeChoice && ["openai", "ollama"].includes(activeChoice.kind ?? "") && activeUrl ? hostOf(activeUrl) : "";
7350
- const MODELS = modelsHost ? labels.length : -1;
7351
- if (modelsHost) labels.push(actionRow(`pick another model on ${modelsHost}…`));
7357
+ // ONE "pick another model on <host>…" ROW PER PROVIDER (GH #407), the one in use first. A model belongs to a
7358
+ // provider, so its full list is reached through that provider — and with Qwen, Kimi and Claude set up, the
7359
+ // row for the current one alone left the other two three menus away. Up to 3 providers: a row each. More:
7360
+ // the current one, and one row that asks which provider.
7361
+ const hostKey = (c) => hostOf(String(c.url ?? ""));
7362
+ const listable = (c) => ["openai", "ollama"].includes(c.kind ?? "") && Boolean(c.url);
7363
+ const providerReps = [];
7364
+ for (const c of [activeChoice, ...choices]) {
7365
+ if (c && listable(c) && !providerReps.some((r) => hostKey(r) === hostKey(c))) providerReps.push(c);
7366
+ }
7367
+ const MAX_PROVIDER_ROWS = 3;
7368
+ const rowReps = providerReps.length <= MAX_PROVIDER_ROWS ? providerReps : providerReps.slice(0, 1);
7369
+ const MODEL_ROWS = new Map(); // row index → a choice on that provider
7370
+ for (const rep of rowReps) {
7371
+ MODEL_ROWS.set(labels.length, rep);
7372
+ labels.push(actionRow(`pick another model on ${hostKey(rep)}…`));
7373
+ }
7374
+ const OTHER_PROVIDERS = providerReps.length > MAX_PROVIDER_ROWS ? labels.length : -1;
7375
+ if (OTHER_PROVIDERS >= 0) labels.push(actionRow("pick another model on another provider…"));
7352
7376
  const KEYS = keyHost ? labels.length : -1;
7353
7377
  if (keyHost) labels.push(actionRow(`API keys for ${keyHost} — switch, add or remove…`));
7354
7378
  // Task #223. Appended LAST, after the models: a new row must never shift an index someone
@@ -7376,8 +7400,19 @@ async function chooseModel() {
7376
7400
  console.log(dim(" (cancelled)\n"));
7377
7401
  return;
7378
7402
  }
7379
- if (idx === MODELS) {
7380
- if ((await pickModelOnCoderServer(activeChoice, def)) === BACK) return chooseModel();
7403
+ if (MODEL_ROWS.has(idx)) {
7404
+ if ((await pickModelOnCoderServer(MODEL_ROWS.get(idx), def)) === BACK) return chooseModel();
7405
+ return;
7406
+ }
7407
+ if (idx === OTHER_PROVIDERS) {
7408
+ const others = providerReps.slice(1);
7409
+ const which = await pickFromList(others.map((r) => hostKey(r)), 0, {
7410
+ back: true,
7411
+ header: () => [dim(` Which provider's models? (${PICK_ARROWS}):`)],
7412
+ headerRows: 1,
7413
+ });
7414
+ if (which === PICK_BACK || which < 0) return chooseModel();
7415
+ if ((await pickModelOnCoderServer(others[which], def)) === BACK) return chooseModel();
7381
7416
  return;
7382
7417
  }
7383
7418
  if (idx === KEYS) {
@@ -7424,17 +7459,46 @@ async function pickModelOnCoderServer(active, def) {
7424
7459
  }
7425
7460
  const row = rows.find((b) => (b.id ?? b.kind) === p.id);
7426
7461
  const extras = Array.isArray(row?.models) ? row.models : [];
7462
+ let replacedActive = false; // the swap removed the very model this session is on (GH #412)
7427
7463
  if (model !== p.model && !extras.includes(model)) {
7464
+ let nextRow = { ...row, models: [...extras, model] };
7465
+ let dropped = "";
7466
+ // GH #412: a server keeps at most MAX_MODELS_PER_SERVER models (the API refuses a 4th), so a
7467
+ // full one cannot just grow — every pick here failed with "couldn't save that". Ask which
7468
+ // saved extra the new pick replaces. The main model is never offered: it may be the account
7469
+ // default other settings point at.
7470
+ if (row && ps.rowModels(row).length >= ps.MAX_MODELS_PER_SERVER) {
7471
+ const swappable = extras.filter((m) => String(m).trim() && m !== p.model);
7472
+ if (!swappable.length) {
7473
+ console.log(yellow(` ${p.host} already offers ${ps.MAX_MODELS_PER_SERVER} models — remove one in /model → manage providers first.\n`));
7474
+ return;
7475
+ }
7476
+ // Two short lines, not one: a wrapped row breaks the picker's erase (and 80 columns is common).
7477
+ console.log(dim(` ${p.host} keeps ${ps.MAX_MODELS_PER_SERVER} models (main: ${p.model}).`));
7478
+ console.log(dim(` Which one should ${model} replace?`));
7479
+ // Default to a model that is NOT the one in use, so Enter keeps the current coder's slot.
7480
+ const first = Math.max(0, swappable.findIndex((m) => m !== active.model));
7481
+ const idx = await pickFromList(swappable, first);
7482
+ if (idx < 0) {
7483
+ console.log(dim(" (nothing changed)\n"));
7484
+ return;
7485
+ }
7486
+ dropped = swappable[idx];
7487
+ nextRow = ps.replaceRowModel(row, dropped, model);
7488
+ }
7428
7489
  const md = await import("./model-doctor.mjs");
7429
- const saved = await withPendingStatus("saving", () =>
7430
- md.saveWorkerSettings(apiBase, workerKey, {
7431
- agentCodingBackends: rows.map((b) => ((b.id ?? b.kind) === p.id ? { ...b, models: [...extras, model] } : b)),
7490
+ const result = await withPendingStatus("saving", () =>
7491
+ md.saveWorkerSettingsDetailed(apiBase, workerKey, {
7492
+ agentCodingBackends: rows.map((b) => ((b.id ?? b.kind) === p.id ? nextRow : b)),
7432
7493
  })
7433
7494
  );
7434
- if (!saved) {
7435
- console.log(red(" couldn't save that — nothing changed.\n"));
7495
+ if (!result.ok) {
7496
+ // The API's own reason, when it gave one — "couldn't save that" alone hid the cap (GH #412).
7497
+ console.log(red(` couldn't save that${result.error ? ` (${result.error})` : ""} — nothing changed.\n`));
7436
7498
  return;
7437
- }
7499
+ } // Say what the swap did — the ✓ line below only names the model now in use (GH #412).
7500
+ if (dropped) console.log(dim(` ${model} replaced ${dropped} on ${p.host}.`));
7501
+ replacedActive = dropped !== "" && dropped === active.model;
7438
7502
  }
7439
7503
  // The choice as the API now lists it — its id is the API's to make, not this side's.
7440
7504
  const probe = await withPendingStatus("loading models", () => fetchAgentPayload([{ role: "user", content: "ping" }])).catch(() => null);
@@ -7443,6 +7507,8 @@ async function pickModelOnCoderServer(active, def) {
7443
7507
  );
7444
7508
  if (!chosen) {
7445
7509
  console.log(accent(` ✓ ${model} added to ${p.host}`) + dim(" · pick it in /model\n"));
7510
+ // The model in use was just taken off the list: say so, or the next turn runs on a coder that is gone.
7511
+ if (replacedActive) console.log(yellow(` ${active.model} was replaced — pick a model in /model now.\n`));
7446
7512
  return;
7447
7513
  }
7448
7514
  await applyChosenCoder(chosen, { def: String(probe?.codingDefault ?? def ?? "").trim() });
@@ -7525,6 +7591,9 @@ async function applyChosenCoder(chosen, { def = "", tag = "", quick = false } =
7525
7591
  sessionApiKeyTail = prevCoder.tail;
7526
7592
  await saveSessionCoding(resolve(process.cwd()));
7527
7593
  console.log(dim(" (cancelled — the coding model was not changed)\n"));
7594
+ // The restore above is only state: repaint, or the bar keeps naming the cancelled coder until
7595
+ // something else redraws it (it used to be covered by an earlier repaint).
7596
+ if (barPinned()) paintBar();
7528
7597
  return;
7529
7598
  }
7530
7599
  }
@@ -8572,7 +8641,10 @@ async function applyTransferDoc(value, opts = {}) {
8572
8641
  * bar and /model kept showing the old coder), and the "no embed model" / "no agent model"
8573
8642
  * warnings. /model already does this after a change; applying a preset must too.
8574
8643
  */
8644
+ // The agent model's server, for the connection watch (GH #409). "" = it is the coder's (no separate agent model).
8645
+ let agentUrlSeen = "";
8575
8646
  function seedDefaultCoder(p) {
8647
+ if (p) agentUrlSeen = p.agentMissing === true ? "" : String(p.agentBaseURL ?? "");
8576
8648
  // The ONE place the account-default coder fields are read (startup + after a preset apply).
8577
8649
  // Anything that wants THIS folder's coder uses sessionCodingModel / activeCoderName() instead.
8578
8650
  if (p?.codingModelId) defaultCodingModel = p.codingModelId;
@@ -9371,6 +9443,7 @@ async function saveAgentModel(agentUrl, model, host, extra = []) {
9371
9443
  console.log(GUTTER + dim("if this machine's local API is old, restart it with `gu api restart`.\n"));
9372
9444
  return false;
9373
9445
  }
9446
+ agentUrlSeen = agentUrl;
9374
9447
  console.log(accent(` ✓ agent model → ${model}`) + dim(` · ${host}`));
9375
9448
  for (const l of extra) console.log(l);
9376
9449
  console.log(dim(" takes effect on your next question.\n"));
@@ -9508,14 +9581,30 @@ async function chooseAgentModel() {
9508
9581
  `same as the coding model${dim(" — follows /model")}` + (current ? "" : accent(" (current)")),
9509
9582
  ...saved.map((c) => c.label + (c.current ? accent(" (current)") : "")),
9510
9583
  ];
9511
- const MODELS = curHost ? labels.length : -1;
9512
- if (curHost) labels.push(actionRow(`pick another model on ${curHost}…`));
9513
- // NO SEPARATE AGENT MODEL YET: offer the coder's own server, so a talking model from the provider
9514
- // already set up is one pick away — its saved key is reused (GH #397).
9515
- const coderUrl = (await import("./coding-provider-setup.mjs")).ensureV1Root(String(sessionCodingUrl || defaultCodingUrl || "")).toLowerCase();
9516
- const coderRow = curHost ? null : (saved.find((c) => c.url.toLowerCase() === coderUrl) ?? null);
9517
- const CODER_MODELS = coderRow ? labels.length : -1;
9518
- if (coderRow) labels.push(actionRow(`pick another model on ${coderRow.host}…`));
9584
+ // ONE "pick another model on <host>…" ROW PER PROVIDER (GH #407): the agent's own provider first, else the
9585
+ // coder's (its saved key is reused), then the rest. Up to 3 providers a row each; more, the first plus one
9586
+ // row that asks which provider.
9587
+ const psv = await import("./coding-provider-setup.mjs");
9588
+ const norm = (u) => psv.ensureV1Root(String(u ?? "")).toLowerCase();
9589
+ const firstUrl = curHost ? norm(settings.agentModelUrl) : norm(sessionCodingUrl || defaultCodingUrl || "");
9590
+ const providerReps = [];
9591
+ for (const c of [saved.find((x) => norm(x.url) === firstUrl), ...saved]) {
9592
+ if (c && !providerReps.some((r) => norm(r.url) === norm(c.url))) providerReps.push(c);
9593
+ }
9594
+ const MAX_PROVIDER_ROWS = 3;
9595
+ const rowReps = providerReps.length <= MAX_PROVIDER_ROWS ? providerReps : providerReps.slice(0, 1);
9596
+ const MODEL_ROWS = new Map(); // row index → { rep, own } (own = the agent's current provider)
9597
+ for (const rep of rowReps) {
9598
+ MODEL_ROWS.set(labels.length, { rep, own: Boolean(curHost) && norm(rep.url) === firstUrl });
9599
+ labels.push(actionRow(`pick another model on ${rep.host}…`));
9600
+ }
9601
+ const OTHER_PROVIDERS = providerReps.length > MAX_PROVIDER_ROWS ? labels.length : -1;
9602
+ if (OTHER_PROVIDERS >= 0) labels.push(actionRow("pick another model on another provider…"));
9603
+ // Opens that provider's full list: the agent's current provider through its own recovery-aware list,
9604
+ // any other through the add flow, which reuses the saved key and lists the models with it.
9605
+ const pickOn = async ({ rep, own }) => own
9606
+ ? agentModelOnServer({ back: true, start: "models" })
9607
+ : addServer({ role: "agent", dialect: rep.kind === "ollama" ? "ollama" : "openai", url: rep.url, back: true });
9519
9608
  const KEYS = curHost && needsKey ? labels.length : -1;
9520
9609
  if (KEYS >= 0) labels.push(actionRow(`API keys for ${curHost} — switch, add or remove…`));
9521
9610
  const ADD = labels.length;
@@ -9539,14 +9628,19 @@ async function chooseAgentModel() {
9539
9628
  console.log(dim(" (cancelled)\n"));
9540
9629
  return;
9541
9630
  }
9542
- if (idx === MODELS) {
9543
- // Straight to that server's full list; when it can't be listed, its recovery menu instead.
9544
- if ((await agentModelOnServer({ back: true, start: "models" })) === BACK) continue;
9631
+ if (MODEL_ROWS.has(idx)) {
9632
+ if ((await pickOn(MODEL_ROWS.get(idx))) === BACK) continue;
9545
9633
  return;
9546
9634
  }
9547
- if (idx === CODER_MODELS) {
9548
- const dialect = coderRow.kind === "ollama" ? "ollama" : "openai";
9549
- if ((await addServer({ role: "agent", dialect, url: coderRow.url, back: true })) === BACK) continue;
9635
+ if (idx === OTHER_PROVIDERS) {
9636
+ const others = providerReps.slice(1);
9637
+ const which = await pickFromList(others.map((r) => r.host), 0, {
9638
+ back: true,
9639
+ header: () => [dim(` Which provider's models? (${PICK_ARROWS}):`)],
9640
+ headerRows: 1,
9641
+ });
9642
+ if (which === PICK_BACK || which < 0) continue;
9643
+ if ((await pickOn({ rep: others[which], own: false })) === BACK) continue;
9550
9644
  return;
9551
9645
  }
9552
9646
  if (idx === KEYS) {
@@ -9589,6 +9683,7 @@ async function useCoderForAgent() {
9589
9683
  return;
9590
9684
  }
9591
9685
  if (sessionAgentKeyId) await saveFolderKeyPick("agent", "");
9686
+ agentUrlSeen = "";
9592
9687
  console.log(accent(" ✓ agent model → same as the coding model") + dim(" · /model switches both"));
9593
9688
  console.log(GUTTER + dim("takes effect on your next question.\n"));
9594
9689
  const after = (await fetchAgentPayload([{ role: "user", content: "." }]).catch(() => null))?.payload;
@@ -11454,6 +11549,8 @@ const MCPTOOL_PREFIX = "__MCPTOOL__::";
11454
11549
  // The agent's first use of the browser in a turn (#150): "<folder>\t<what it is about to do>".
11455
11550
  // "Always" puts the folder on ~/.gonext/browser-allow.json, which the agent reads before asking.
11456
11551
  const BROWSER_PREFIX = "__BROWSER__::";
11552
+ // How long the browser question waits before "Yes, this time" (GH #411).
11553
+ const BROWSER_APPROVAL_MS = 10_000;
11457
11554
  async function approvalPrompt(command) {
11458
11555
  // Wipe the live "thinking" status block BEFORE any picker draws, and stop the ticker from
11459
11556
  // redrawing it (the tick early-returns while a picker is active) — otherwise the block
@@ -11515,14 +11612,16 @@ async function approvalPrompt(command) {
11515
11612
  const [folder = "", what = ""] = command.slice(BROWSER_PREFIX.length).split("\t");
11516
11613
  if (!process.stdin.isTTY) return { allow: false, dontAsk: false };
11517
11614
  process.stdout.write(
11518
- "\n" + yellow("🌐 Allow gu to use a web browser?") + dim(" (no answer in ~3 min = Yes, this time)") + "\n" +
11615
+ "\n" + yellow("🌐 Allow gu to use a web browser?") + dim(` (no answer in ${BROWSER_APPROVAL_MS / 1000}s = Yes, this time)`) + "\n" +
11519
11616
  indentBlock(`It wants to: ${what || "open a page"}`, { indent: GUTTER, paint: dim }) + "\n" +
11520
11617
  dim(" In your Chrome if the gu extension is there, else in gu's own Chrome window.") + "\n"
11521
11618
  );
11522
11619
  // "Yes, this time" is THE default (#380, GitHub #167): highlighted, so Enter allows it once, and
11523
11620
  // also what an unanswered question becomes — the countdown used to sit on "No", which read as
11524
11621
  // the default. Remembering the folder is never automatic; it takes an explicit choice.
11525
- const idx = await pickFromList(["Yes, this time", "Yes, always in this folder", "No"], 0, { timeoutMs: 170000, timeoutIndex: 0 });
11622
+ // 10 s, not ~3 min (GH #411: "opening browser is not that serious"). Silence still means once
11623
+ // only — never the remembered "always".
11624
+ const idx = await pickFromList(["Yes, this time", "Yes, always in this folder", "No"], 0, { timeoutMs: BROWSER_APPROVAL_MS, timeoutIndex: 0 });
11526
11625
  if (idx === 1) {
11527
11626
  try {
11528
11627
  allowIn(folder || resolve(process.cwd()), true);
@@ -12824,6 +12923,9 @@ async function runAgentTurn(history, { attachJobId = "", ownJob = false } = {})
12824
12923
  const QUIET_MS = 700; // stream idle this long ⇒ we're waiting on the model
12825
12924
  const STALE_THOUGHT_MS = 25000; // no new tokens this long ⇒ the current Thought clause is stale (#95 A)
12826
12925
  let lastContentAt = Date.now();
12926
+ // GH #409: when the model last SENT anything — hidden ~~~ stream included, worker heartbeats excluded.
12927
+ // lastContentAt is not bumped inside a fence on purpose, so it cannot tell a silent model from a busy one.
12928
+ let lastDataAt = Date.now();
12827
12929
  let paintedThought = ""; // the thought currently painted, for statusNeedsLiveRepaint
12828
12930
  let thinking = false;
12829
12931
  let thinkingSince = 0;
@@ -12834,6 +12936,12 @@ async function runAgentTurn(history, { attachJobId = "", ownJob = false } = {})
12834
12936
  let blockHintRows = 0; // 1 while the tip row is part of the live block (see the click arithmetic)
12835
12937
  let lastWordBucket = -1; // 12s window index → rotate the word once per window (task: 30-spinner)
12836
12938
  let almostDone = false; // set from the worker's "…almost completed thinking…" heartbeat
12939
+ // GH #409: is the model host reachable at all? Probed only while the stream is quiet and the agent is waiting
12940
+ // on the model — the counter used to climb for ever ("Thinking… (821s)") with the internet gone.
12941
+ const netWatch = createConnectionWatch({
12942
+ probe: (u) => probeReachable(u, { fetchImpl: doctorFetch }),
12943
+ hosts: () => modelHostsOf([sessionCodingUrl || defaultCodingUrl, agentUrlSeen]),
12944
+ });
12837
12945
  let runningCmd = null; // the command currently executing (from a "Running → …" event)
12838
12946
  let runningTool = null; // { label, detail } for the tool executing right now (task #177)
12839
12947
  // The model's CURRENT Thought (task #64): while it streams its reasoning inside the
@@ -12994,6 +13102,13 @@ async function runAgentTurn(history, { attachJobId = "", ownJob = false } = {})
12994
13102
  liveThought = ""; fullLiveThought = ""; thoughtExpanded = false; // #96: nothing to expand once stale
12995
13103
  }
12996
13104
  const secs = thinkSecs();
13105
+ // A local command or tool is running: it is the command that is taking the time, not the network.
13106
+ netWatch.poll(runningCmd || runningTool ? 0 : now - lastDataAt);
13107
+ const net = netWatch.state();
13108
+ const offline = net.down && !runningCmd && !runningTool;
13109
+ // The network is fine but a HOSTED model has said nothing for minutes (a connection that died without an
13110
+ // error, an overloaded provider): say so instead of counting on. Never for a box on this machine / the LAN.
13111
+ const stalledOn = !offline && !runningCmd && !runningTool ? netWatch.stalled(now - lastDataAt) : null;
12997
13112
  // Rotate the playful word once per 12s window (guarded so the fast ticker doesn't re-roll
12998
13113
  // it many times within the same second). Off the WALL CLOCK, like the spinner: keyed to the
12999
13114
  // phase it also got re-picked at every phase start — and a phase starts after every printed
@@ -13083,6 +13198,16 @@ async function runAgentTurn(history, { attachJobId = "", ownJob = false } = {})
13083
13198
  // the purple one (ending in "…" when more was dropped); a click / Ctrl+T opens it up to
13084
13199
  // THOUGHT_OPEN_LINES. #350: the click and Ctrl+T ask the SAME question the highlight does —
13085
13200
  // they only count when opening actually shows more rows than the preview already does.
13201
+ // No connection: the line says so, in the warning colour, instead of a thought or "Thinking… (821s)".
13202
+ if (offline) {
13203
+ label = offlineLine({ host: net.host, downForMs: net.downForMs, width: process.stdout.columns || 80 });
13204
+ rest = "";
13205
+ } else if (stalledOn) {
13206
+ label = stalledLine({ host: stalledOn.host, quietMs: now - lastDataAt, width: process.stdout.columns || 80 });
13207
+ rest = "";
13208
+ }
13209
+ const warned = offline || Boolean(stalledOn);
13210
+ const labelPaint = warned ? yellow : thoughtPaint;
13086
13211
  const previewLines = rest ? wrapThought(rest, max, THOUGHT_PREVIEW_LINES) : [];
13087
13212
  const openLines = rest ? wrapThought(rest, max, THOUGHT_OPEN_LINES) : [];
13088
13213
  const clickable = split && previewLines.join("\n") !== openLines.join("\n");
@@ -13171,7 +13296,7 @@ async function runAgentTurn(history, { attachJobId = "", ownJob = false } = {})
13171
13296
  const clipRow = (r) => clipVisible(r, Math.max(20, process.stdout.columns || 80) - 1);
13172
13297
  const contentRows = [];
13173
13298
  for (let i = 0; i < LEAD_ROWS; i++) contentRows.push(""); // the separator — see LEAD_ROWS
13174
- contentRows.push(clipRow(`${markLine(thoughtPaint(BULLET))}${hovering ? hoverThought(label) : thoughtPaint(label)}`));
13299
+ contentRows.push(clipRow(`${markLine(labelPaint(BULLET))}${hovering && !warned ? hoverThought(label) : labelPaint(label)}`));
13175
13300
  for (const dr of detailRows) contentRows.push(clipRow(dim(dr)));
13176
13301
  for (const wl of expLines) contentRows.push(clipRow(GUTTER + dim(wl)));
13177
13302
  for (let i = 0; i < WORD_GAP; i++) contentRows.push(""); // see WORD_GAP
@@ -13385,6 +13510,8 @@ async function runAgentTurn(history, { attachJobId = "", ownJob = false } = {})
13385
13510
  // that might not arrive until the very end (most short replies have none at all).
13386
13511
  let carryFlushedLen = 0;
13387
13512
  const consume = (chunk) => {
13513
+ // The worker's own 45s heartbeats and its "No data from the model" notes say nothing about the model.
13514
+ if (String(chunk).split("\n").some((l) => l.trim() && !isHeartbeatLine(l) && !/^\s*No data from the model/.test(l))) lastDataAt = Date.now();
13388
13515
  carry += stripThinkTags(chunk);
13389
13516
  let nl;
13390
13517
  while ((nl = carry.indexOf("\n")) >= 0) {
package/gu_mcp.py CHANGED
@@ -88,7 +88,8 @@ class StdioMcpClient:
88
88
  except OSError as e:
89
89
  raise McpError(f'could not start "{self.command}": {e.strerror or e}') from None
90
90
  threading.Thread(target=self._read_stdout, daemon=True).start()
91
- threading.Thread(target=self._read_stderr, daemon=True).start()
91
+ self._stderr_thread = threading.Thread(target=self._read_stderr, daemon=True)
92
+ self._stderr_thread.start()
92
93
 
93
94
  def _read_stdout(self) -> None:
94
95
  try:
@@ -147,6 +148,17 @@ class StdioMcpClient:
147
148
  raise McpError(self._exit_reason()) from None
148
149
 
149
150
  def _exit_reason(self) -> str:
151
+ # Called the moment the server's pipe closes: the child may not be reaped yet and its
152
+ # last stderr line may still be in flight. Give both a moment, or the message flips
153
+ # between "exited (code N)" and "stopped answering" from run to run (GH #410).
154
+ if self.proc:
155
+ try:
156
+ self.proc.wait(timeout=1.5)
157
+ except subprocess.TimeoutExpired:
158
+ pass
159
+ t = getattr(self, "_stderr_thread", None)
160
+ if t and self.proc.poll() is not None:
161
+ t.join(timeout=1.5)
150
162
  code = self.proc.poll() if self.proc else None
151
163
  tail = next((l for l in reversed(self._stderr_tail) if l.strip()), "")
152
164
  why = f"the server exited (code {code})" if code is not None else "the server stopped answering"
package/model-doctor.mjs CHANGED
@@ -581,8 +581,12 @@ export function resolveConfiguredModels(settings) {
581
581
  * the CLI setup flow asks about. Returns true on success; never throws (a failed save must
582
582
  * not abort setup — the model still gets served from the chosen folder this session).
583
583
  */
584
- export async function saveWorkerSettings(apiBase, workerKey, patch, { timeoutMs = 6000 } = {}) {
585
- if (!apiBase || !workerKey || !patch || !Object.keys(patch).length) return false;
584
+ /**
585
+ * saveWorkerSettings, but with the API's reason when it refuses (GH #412): → { ok, error }.
586
+ * `error` is the body's `error` text on an HTTP failure, the network message on no answer.
587
+ */
588
+ export async function saveWorkerSettingsDetailed(apiBase, workerKey, patch, { timeoutMs = 6000 } = {}) {
589
+ if (!apiBase || !workerKey || !patch || !Object.keys(patch).length) return { ok: false, error: "" };
586
590
  try {
587
591
  const res = await fetch(`${String(apiBase).replace(/\/+$/, "")}/api/worker/settings`, {
588
592
  method: "POST",
@@ -590,12 +594,18 @@ export async function saveWorkerSettings(apiBase, workerKey, patch, { timeoutMs
590
594
  body: JSON.stringify(patch),
591
595
  signal: AbortSignal.timeout(timeoutMs),
592
596
  });
593
- return res.ok;
594
- } catch {
595
- return false;
597
+ if (res.ok) return { ok: true, error: "" };
598
+ const body = await res.json().catch(() => null);
599
+ return { ok: false, error: String(body?.error ?? `HTTP ${res.status}`).slice(0, 200) };
600
+ } catch (e) {
601
+ return { ok: false, error: String(e?.message ?? e).slice(0, 200) };
596
602
  }
597
603
  }
598
604
 
605
+ export async function saveWorkerSettings(apiBase, workerKey, patch, opts = {}) {
606
+ return (await saveWorkerSettingsDetailed(apiBase, workerKey, patch, opts)).ok;
607
+ }
608
+
599
609
  /**
600
610
  * Is an OpenAI-compatible model endpoint REACHABLE from this machine?
601
611
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiens.nguyen/gu-cli",
3
- "version": "1.0.900",
3
+ "version": "1.0.902",
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",
@@ -58,11 +58,13 @@
58
58
  "test:skills": "python3 scripts/py-tap.py tests/test_skills_mcp_turn.py tests/test_hooks_turn.py tests/test_claude_hooks.py tests/test_mcp_client.py && node --test tests/skills.test.mjs tests/mcp-config.test.mjs tests/hooks-config.test.mjs tests/switch-skill.test.mjs tests/slash-menu.test.mjs tests/conversation-archive.test.mjs",
59
59
  "capture:turn": "GONEXT_OLLAMA1_LIVE=1 node scripts/capture-turn-fixture.mjs",
60
60
  "test:bearer": "node --test tests/bearer-routing.test.mjs tests/bearer-verify.test.mjs",
61
- "test:bearer-e2e": "bash scripts/bearer-e2e.sh"
61
+ "test:bearer-e2e": "bash scripts/bearer-e2e.sh",
62
+ "test:pack": "node scripts/pack-smoke.mjs"
62
63
  },
63
64
  "files": [
64
65
  "accent.mjs",
65
66
  "agent-deps-preflight.mjs",
67
+ "connection-watch.mjs",
66
68
  "edit-card-render.mjs",
67
69
  "diff-syntax.mjs",
68
70
  "theme.mjs",
@@ -146,6 +148,7 @@
146
148
  "install-path.mjs",
147
149
  "update-verify.mjs",
148
150
  "skills.mjs",
151
+ "skills/",
149
152
  "skill-source.mjs",
150
153
  "skills-copy.mjs",
151
154
  "skill-package.mjs",
@@ -0,0 +1,55 @@
1
+ ---
2
+ name: gu-session-memory-orchestration
3
+ description: Project memory shared by gu and Claude Code. Use when a "Resume" block or memory snapshot appears, when the user says continue or resume, and before a wide repository search.
4
+ ---
5
+
6
+ # Session memory
7
+
8
+ Hooks save your work as it happens, in both gu and Claude Code: each request, your plan, every
9
+ command with its result, every edit (scripted ones too), and whether the turn finished or was cut
10
+ off. **You do not save steps, edits or checkpoints yourself.** Your part is below.
11
+
12
+ ## What you will see
13
+
14
+ - **`## Resume - task #N (tool, state time)`** at the start of a session, and again when the user
15
+ says "continue" or "resume": the latest unfinished work in this project, from either tool. It
16
+ lists the task, goal, plan (done, in progress, not started), last command and its result, files
17
+ touched, and the next step. `interrupted` = the turn was cut off; `unfinished` = still running
18
+ elsewhere or closed without finishing.
19
+ - **`## Memory snapshot`**: tasks in progress, requirements that match the request, recent edits.
20
+
21
+ ## Rules
22
+
23
+ 1. **Resume block.** If the request carries on that work, or the user says continue/resume, start
24
+ from **Next** (the first step not done) and say so in one line, e.g. *Continuing task #446 from
25
+ "gu commands".* Look at the files it lists before changing them, do not redo finished steps, and
26
+ if the last command failed, start by understanding why. If the request is about something else,
27
+ ignore the block and do not mention it.
28
+ 2. **Keep a plan for work with three or more steps**, and update it as each step starts and
29
+ finishes; that plan is what a resume continues from. If you have a to-do tool, use it. If you do
30
+ not, call `save_progress` with the whole plan each time.
31
+ 3. **Switching task?** Call `update_task` on the task you are moving to (status `in_progress`,
32
+ `process_state` = what you are about to do). A task named in the user's request (`#N`, `GH #N`)
33
+ is picked up without this.
34
+ 4. **Memory before a wide search.** Before searching the whole repository, try
35
+ `find_requirements`, `search_code_changes` and `line_hints`, then open only the files they name.
36
+ Line numbers from memory are hints: check them before you quote them.
37
+ 5. **Finished a task?** `update_task` with status `done` and a `next_action` for any follow-up.
38
+
39
+ ## Tools (`local-memory-sqlite` MCP server)
40
+
41
+ | Need | Tool |
42
+ | --- | --- |
43
+ | The whole resume state: full plan, last commands, files | `resume_task` |
44
+ | Save your plan when you have no to-do tool | `save_progress` |
45
+ | Requirements and tasks | `find_requirements`, `search_tasks`, `get_task`, `list_tasks` |
46
+ | Create or move a task | `save_task`, `update_task` |
47
+ | Where something was changed or found before | `search_code_changes`, `recent_code_changes`, `line_hints`, `search_steps` |
48
+
49
+ If the MCP tools are not connected, say so in one line and carry on: the hooks still save the work.
50
+
51
+ ## Good to know
52
+
53
+ - Memory lives in `.claude-memory/` at the project root (the git root), one database per project.
54
+ - Secrets are masked before they are stored, but do not write keys, tokens or passwords into a
55
+ plan, a task or a summary.
package/skills.mjs CHANGED
@@ -27,13 +27,39 @@
27
27
  */
28
28
  import { readdirSync, readFileSync, statSync } from "node:fs";
29
29
  import { homedir } from "node:os";
30
- import { join } from "node:path";
30
+ import { dirname, join } from "node:path";
31
+ import { fileURLToPath } from "node:url";
31
32
  import { resolveSkillSource, sourceDirName } from "./skill-source.mjs";
32
33
 
33
34
  export const SKILL_FILE = "SKILL.md";
34
35
  /** Claude Code's rule: lowercase letters, digits and hyphens, at most 64. It is also a slash command. */
35
36
  export const SKILL_NAME_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
36
37
 
38
+ /**
39
+ * CORE SKILLS (GH #344): skills that ship INSIDE the package, <package>/skills/core/<name>/SKILL.md.
40
+ * They are read from there on every scan and never copied into ~/.gonext/skills, so `npm i -g`
41
+ * is enough (no postinstall to fail under --ignore-scripts), an upgrade upgrades them, and
42
+ * `rm -rf ~/.gonext/skills` cannot remove them. They belong to gu, not to a skills folder, so they
43
+ * load whichever source /switch-skill chose.
44
+ *
45
+ * ORDER: project < core < yours. A personal skill with a core skill's name replaces it, visibly
46
+ * (`overrides: "core"`), except the LOCKED ones other features depend on.
47
+ */
48
+ export function coreSkillsDir() {
49
+ return join(dirname(fileURLToPath(import.meta.url)), "skills", "core");
50
+ }
51
+ /** Core skills a personal skill may not replace: hooks and the resume flow rely on them. */
52
+ export const LOCKED_CORE_SKILLS = ["gu-session-memory-orchestration"];
53
+
54
+ /** The gu version the core skills ship with (package.json beside skills/), "" if unreadable. */
55
+ export function coreSkillsVersion(dir = coreSkillsDir()) {
56
+ try {
57
+ return String(JSON.parse(readFileSync(join(dir, "..", "..", "package.json"), "utf8")).version ?? "");
58
+ } catch {
59
+ return "";
60
+ }
61
+ }
62
+
37
63
  export function userSkillsDir(home = homedir(), source = "gu") {
38
64
  return join(home, sourceDirName(source), "skills");
39
65
  }
@@ -155,23 +181,38 @@ export const HIDDEN_SKILLS = ["gu-session-memory-orchestration"];
155
181
  * `source` = whose skills ("gu" | "claude"); left out, it is the folder's own choice (/switch-skill).
156
182
  * Only that source's skills are listed — the two are never mixed.
157
183
  *
158
- * → { skills: [{ name, description, path, dir, scope, slash, source }], warnings: string[], source }
184
+ * `coreDir` = where the shipped skills are (default: the package's own); null/"" = none (tests).
185
+ *
186
+ * → { skills: [{ name, description, path, dir, scope, layer, slash, source, version?, overrides? }],
187
+ * warnings: string[], source }
159
188
  */
160
- export function discoverSkills({ cwd = process.cwd(), home = homedir(), reserved = [], source } = {}) {
189
+ export function discoverSkills({ cwd = process.cwd(), home = homedir(), reserved = [], source, coreDir = coreSkillsDir() } = {}) {
161
190
  const src = resolveSkillSource({ source, cwd, home });
162
191
  const user = scanDir(userSkillsDir(home, src), "user");
163
192
  const project =
164
193
  cwd && projectSkillsDir(cwd, src) !== userSkillsDir(home, src)
165
194
  ? scanDir(projectSkillsDir(cwd, src), "project")
166
195
  : { skills: [], warnings: [] };
196
+ const core = coreDir ? scanDir(coreDir, "core") : { skills: [], warnings: [] };
197
+ const version = core.skills.length ? coreSkillsVersion(coreDir) : "";
198
+ const warnings = [...user.warnings, ...project.warnings, ...core.warnings];
199
+ // project < core < yours.
167
200
  const byName = new Map();
168
- for (const s of user.skills) byName.set(s.name, s);
169
- for (const s of project.skills) if (!byName.has(s.name)) byName.set(s.name, s);
201
+ for (const s of project.skills) byName.set(s.name, { ...s, layer: "project" });
202
+ for (const s of core.skills) byName.set(s.name, { ...s, layer: "core", ...(version ? { version } : {}) });
203
+ for (const s of user.skills) {
204
+ const had = byName.get(s.name);
205
+ if (had?.layer === "core" && LOCKED_CORE_SKILLS.includes(s.name)) {
206
+ warnings.push(`user skill "${s.name}": the name belongs to a core skill that cannot be replaced — skipped`);
207
+ continue;
208
+ }
209
+ byName.set(s.name, { ...s, layer: "user", ...(had?.layer === "core" ? { overrides: "core", coreVersion: had.version } : {}) });
210
+ }
170
211
  const taken = new Set(reserved.map((r) => r.replace(/^\//, "")));
171
212
  const skills = [...byName.values()]
172
213
  .sort((a, b) => a.name.localeCompare(b.name))
173
214
  .map((s) => ({ ...s, slash: !taken.has(s.name), hidden: HIDDEN_SKILLS.includes(s.name), source: src }));
174
- return { skills, warnings: [...user.warnings, ...project.warnings], source: src };
215
+ return { skills, warnings, source: src };
175
216
  }
176
217
 
177
218
  /** What the worker hands the agent for one turn: enough to list them and to read one. */