@tiens.nguyen/gu-cli 1.0.900 → 1.0.901

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
  }
@@ -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 {
@@ -7345,10 +7346,25 @@ async function chooseModel() {
7345
7346
  const activeChoice = choices[activeIdx >= 0 ? activeIdx : choices.findIndex((c) => c.id === def)];
7346
7347
  const activeUrl = String(activeChoice?.url ?? "");
7347
7348
  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}…`));
7349
+ // ONE "pick another model on <host>…" ROW PER PROVIDER (GH #407), the one in use first. A model belongs to a
7350
+ // provider, so its full list is reached through that provider — and with Qwen, Kimi and Claude set up, the
7351
+ // row for the current one alone left the other two three menus away. Up to 3 providers: a row each. More:
7352
+ // the current one, and one row that asks which provider.
7353
+ const hostKey = (c) => hostOf(String(c.url ?? ""));
7354
+ const listable = (c) => ["openai", "ollama"].includes(c.kind ?? "") && Boolean(c.url);
7355
+ const providerReps = [];
7356
+ for (const c of [activeChoice, ...choices]) {
7357
+ if (c && listable(c) && !providerReps.some((r) => hostKey(r) === hostKey(c))) providerReps.push(c);
7358
+ }
7359
+ const MAX_PROVIDER_ROWS = 3;
7360
+ const rowReps = providerReps.length <= MAX_PROVIDER_ROWS ? providerReps : providerReps.slice(0, 1);
7361
+ const MODEL_ROWS = new Map(); // row index → a choice on that provider
7362
+ for (const rep of rowReps) {
7363
+ MODEL_ROWS.set(labels.length, rep);
7364
+ labels.push(actionRow(`pick another model on ${hostKey(rep)}…`));
7365
+ }
7366
+ const OTHER_PROVIDERS = providerReps.length > MAX_PROVIDER_ROWS ? labels.length : -1;
7367
+ if (OTHER_PROVIDERS >= 0) labels.push(actionRow("pick another model on another provider…"));
7352
7368
  const KEYS = keyHost ? labels.length : -1;
7353
7369
  if (keyHost) labels.push(actionRow(`API keys for ${keyHost} — switch, add or remove…`));
7354
7370
  // Task #223. Appended LAST, after the models: a new row must never shift an index someone
@@ -7376,8 +7392,19 @@ async function chooseModel() {
7376
7392
  console.log(dim(" (cancelled)\n"));
7377
7393
  return;
7378
7394
  }
7379
- if (idx === MODELS) {
7380
- if ((await pickModelOnCoderServer(activeChoice, def)) === BACK) return chooseModel();
7395
+ if (MODEL_ROWS.has(idx)) {
7396
+ if ((await pickModelOnCoderServer(MODEL_ROWS.get(idx), def)) === BACK) return chooseModel();
7397
+ return;
7398
+ }
7399
+ if (idx === OTHER_PROVIDERS) {
7400
+ const others = providerReps.slice(1);
7401
+ const which = await pickFromList(others.map((r) => hostKey(r)), 0, {
7402
+ back: true,
7403
+ header: () => [dim(` Which provider's models? (${PICK_ARROWS}):`)],
7404
+ headerRows: 1,
7405
+ });
7406
+ if (which === PICK_BACK || which < 0) return chooseModel();
7407
+ if ((await pickModelOnCoderServer(others[which], def)) === BACK) return chooseModel();
7381
7408
  return;
7382
7409
  }
7383
7410
  if (idx === KEYS) {
@@ -7525,6 +7552,9 @@ async function applyChosenCoder(chosen, { def = "", tag = "", quick = false } =
7525
7552
  sessionApiKeyTail = prevCoder.tail;
7526
7553
  await saveSessionCoding(resolve(process.cwd()));
7527
7554
  console.log(dim(" (cancelled — the coding model was not changed)\n"));
7555
+ // The restore above is only state: repaint, or the bar keeps naming the cancelled coder until
7556
+ // something else redraws it (it used to be covered by an earlier repaint).
7557
+ if (barPinned()) paintBar();
7528
7558
  return;
7529
7559
  }
7530
7560
  }
@@ -8572,7 +8602,10 @@ async function applyTransferDoc(value, opts = {}) {
8572
8602
  * bar and /model kept showing the old coder), and the "no embed model" / "no agent model"
8573
8603
  * warnings. /model already does this after a change; applying a preset must too.
8574
8604
  */
8605
+ // The agent model's server, for the connection watch (GH #409). "" = it is the coder's (no separate agent model).
8606
+ let agentUrlSeen = "";
8575
8607
  function seedDefaultCoder(p) {
8608
+ if (p) agentUrlSeen = p.agentMissing === true ? "" : String(p.agentBaseURL ?? "");
8576
8609
  // The ONE place the account-default coder fields are read (startup + after a preset apply).
8577
8610
  // Anything that wants THIS folder's coder uses sessionCodingModel / activeCoderName() instead.
8578
8611
  if (p?.codingModelId) defaultCodingModel = p.codingModelId;
@@ -9371,6 +9404,7 @@ async function saveAgentModel(agentUrl, model, host, extra = []) {
9371
9404
  console.log(GUTTER + dim("if this machine's local API is old, restart it with `gu api restart`.\n"));
9372
9405
  return false;
9373
9406
  }
9407
+ agentUrlSeen = agentUrl;
9374
9408
  console.log(accent(` ✓ agent model → ${model}`) + dim(` · ${host}`));
9375
9409
  for (const l of extra) console.log(l);
9376
9410
  console.log(dim(" takes effect on your next question.\n"));
@@ -9508,14 +9542,30 @@ async function chooseAgentModel() {
9508
9542
  `same as the coding model${dim(" — follows /model")}` + (current ? "" : accent(" (current)")),
9509
9543
  ...saved.map((c) => c.label + (c.current ? accent(" (current)") : "")),
9510
9544
  ];
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}…`));
9545
+ // ONE "pick another model on <host>…" ROW PER PROVIDER (GH #407): the agent's own provider first, else the
9546
+ // coder's (its saved key is reused), then the rest. Up to 3 providers a row each; more, the first plus one
9547
+ // row that asks which provider.
9548
+ const psv = await import("./coding-provider-setup.mjs");
9549
+ const norm = (u) => psv.ensureV1Root(String(u ?? "")).toLowerCase();
9550
+ const firstUrl = curHost ? norm(settings.agentModelUrl) : norm(sessionCodingUrl || defaultCodingUrl || "");
9551
+ const providerReps = [];
9552
+ for (const c of [saved.find((x) => norm(x.url) === firstUrl), ...saved]) {
9553
+ if (c && !providerReps.some((r) => norm(r.url) === norm(c.url))) providerReps.push(c);
9554
+ }
9555
+ const MAX_PROVIDER_ROWS = 3;
9556
+ const rowReps = providerReps.length <= MAX_PROVIDER_ROWS ? providerReps : providerReps.slice(0, 1);
9557
+ const MODEL_ROWS = new Map(); // row index → { rep, own } (own = the agent's current provider)
9558
+ for (const rep of rowReps) {
9559
+ MODEL_ROWS.set(labels.length, { rep, own: Boolean(curHost) && norm(rep.url) === firstUrl });
9560
+ labels.push(actionRow(`pick another model on ${rep.host}…`));
9561
+ }
9562
+ const OTHER_PROVIDERS = providerReps.length > MAX_PROVIDER_ROWS ? labels.length : -1;
9563
+ if (OTHER_PROVIDERS >= 0) labels.push(actionRow("pick another model on another provider…"));
9564
+ // Opens that provider's full list: the agent's current provider through its own recovery-aware list,
9565
+ // any other through the add flow, which reuses the saved key and lists the models with it.
9566
+ const pickOn = async ({ rep, own }) => own
9567
+ ? agentModelOnServer({ back: true, start: "models" })
9568
+ : addServer({ role: "agent", dialect: rep.kind === "ollama" ? "ollama" : "openai", url: rep.url, back: true });
9519
9569
  const KEYS = curHost && needsKey ? labels.length : -1;
9520
9570
  if (KEYS >= 0) labels.push(actionRow(`API keys for ${curHost} — switch, add or remove…`));
9521
9571
  const ADD = labels.length;
@@ -9539,14 +9589,19 @@ async function chooseAgentModel() {
9539
9589
  console.log(dim(" (cancelled)\n"));
9540
9590
  return;
9541
9591
  }
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;
9592
+ if (MODEL_ROWS.has(idx)) {
9593
+ if ((await pickOn(MODEL_ROWS.get(idx))) === BACK) continue;
9545
9594
  return;
9546
9595
  }
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;
9596
+ if (idx === OTHER_PROVIDERS) {
9597
+ const others = providerReps.slice(1);
9598
+ const which = await pickFromList(others.map((r) => r.host), 0, {
9599
+ back: true,
9600
+ header: () => [dim(` Which provider's models? (${PICK_ARROWS}):`)],
9601
+ headerRows: 1,
9602
+ });
9603
+ if (which === PICK_BACK || which < 0) continue;
9604
+ if ((await pickOn({ rep: others[which], own: false })) === BACK) continue;
9550
9605
  return;
9551
9606
  }
9552
9607
  if (idx === KEYS) {
@@ -9589,6 +9644,7 @@ async function useCoderForAgent() {
9589
9644
  return;
9590
9645
  }
9591
9646
  if (sessionAgentKeyId) await saveFolderKeyPick("agent", "");
9647
+ agentUrlSeen = "";
9592
9648
  console.log(accent(" ✓ agent model → same as the coding model") + dim(" · /model switches both"));
9593
9649
  console.log(GUTTER + dim("takes effect on your next question.\n"));
9594
9650
  const after = (await fetchAgentPayload([{ role: "user", content: "." }]).catch(() => null))?.payload;
@@ -12824,6 +12880,9 @@ async function runAgentTurn(history, { attachJobId = "", ownJob = false } = {})
12824
12880
  const QUIET_MS = 700; // stream idle this long ⇒ we're waiting on the model
12825
12881
  const STALE_THOUGHT_MS = 25000; // no new tokens this long ⇒ the current Thought clause is stale (#95 A)
12826
12882
  let lastContentAt = Date.now();
12883
+ // GH #409: when the model last SENT anything — hidden ~~~ stream included, worker heartbeats excluded.
12884
+ // lastContentAt is not bumped inside a fence on purpose, so it cannot tell a silent model from a busy one.
12885
+ let lastDataAt = Date.now();
12827
12886
  let paintedThought = ""; // the thought currently painted, for statusNeedsLiveRepaint
12828
12887
  let thinking = false;
12829
12888
  let thinkingSince = 0;
@@ -12834,6 +12893,12 @@ async function runAgentTurn(history, { attachJobId = "", ownJob = false } = {})
12834
12893
  let blockHintRows = 0; // 1 while the tip row is part of the live block (see the click arithmetic)
12835
12894
  let lastWordBucket = -1; // 12s window index → rotate the word once per window (task: 30-spinner)
12836
12895
  let almostDone = false; // set from the worker's "…almost completed thinking…" heartbeat
12896
+ // GH #409: is the model host reachable at all? Probed only while the stream is quiet and the agent is waiting
12897
+ // on the model — the counter used to climb for ever ("Thinking… (821s)") with the internet gone.
12898
+ const netWatch = createConnectionWatch({
12899
+ probe: (u) => probeReachable(u, { fetchImpl: doctorFetch }),
12900
+ hosts: () => modelHostsOf([sessionCodingUrl || defaultCodingUrl, agentUrlSeen]),
12901
+ });
12837
12902
  let runningCmd = null; // the command currently executing (from a "Running → …" event)
12838
12903
  let runningTool = null; // { label, detail } for the tool executing right now (task #177)
12839
12904
  // The model's CURRENT Thought (task #64): while it streams its reasoning inside the
@@ -12994,6 +13059,13 @@ async function runAgentTurn(history, { attachJobId = "", ownJob = false } = {})
12994
13059
  liveThought = ""; fullLiveThought = ""; thoughtExpanded = false; // #96: nothing to expand once stale
12995
13060
  }
12996
13061
  const secs = thinkSecs();
13062
+ // A local command or tool is running: it is the command that is taking the time, not the network.
13063
+ netWatch.poll(runningCmd || runningTool ? 0 : now - lastDataAt);
13064
+ const net = netWatch.state();
13065
+ const offline = net.down && !runningCmd && !runningTool;
13066
+ // The network is fine but a HOSTED model has said nothing for minutes (a connection that died without an
13067
+ // error, an overloaded provider): say so instead of counting on. Never for a box on this machine / the LAN.
13068
+ const stalledOn = !offline && !runningCmd && !runningTool ? netWatch.stalled(now - lastDataAt) : null;
12997
13069
  // Rotate the playful word once per 12s window (guarded so the fast ticker doesn't re-roll
12998
13070
  // it many times within the same second). Off the WALL CLOCK, like the spinner: keyed to the
12999
13071
  // phase it also got re-picked at every phase start — and a phase starts after every printed
@@ -13083,6 +13155,16 @@ async function runAgentTurn(history, { attachJobId = "", ownJob = false } = {})
13083
13155
  // the purple one (ending in "…" when more was dropped); a click / Ctrl+T opens it up to
13084
13156
  // THOUGHT_OPEN_LINES. #350: the click and Ctrl+T ask the SAME question the highlight does —
13085
13157
  // they only count when opening actually shows more rows than the preview already does.
13158
+ // No connection: the line says so, in the warning colour, instead of a thought or "Thinking… (821s)".
13159
+ if (offline) {
13160
+ label = offlineLine({ host: net.host, downForMs: net.downForMs, width: process.stdout.columns || 80 });
13161
+ rest = "";
13162
+ } else if (stalledOn) {
13163
+ label = stalledLine({ host: stalledOn.host, quietMs: now - lastDataAt, width: process.stdout.columns || 80 });
13164
+ rest = "";
13165
+ }
13166
+ const warned = offline || Boolean(stalledOn);
13167
+ const labelPaint = warned ? yellow : thoughtPaint;
13086
13168
  const previewLines = rest ? wrapThought(rest, max, THOUGHT_PREVIEW_LINES) : [];
13087
13169
  const openLines = rest ? wrapThought(rest, max, THOUGHT_OPEN_LINES) : [];
13088
13170
  const clickable = split && previewLines.join("\n") !== openLines.join("\n");
@@ -13171,7 +13253,7 @@ async function runAgentTurn(history, { attachJobId = "", ownJob = false } = {})
13171
13253
  const clipRow = (r) => clipVisible(r, Math.max(20, process.stdout.columns || 80) - 1);
13172
13254
  const contentRows = [];
13173
13255
  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)}`));
13256
+ contentRows.push(clipRow(`${markLine(labelPaint(BULLET))}${hovering && !warned ? hoverThought(label) : labelPaint(label)}`));
13175
13257
  for (const dr of detailRows) contentRows.push(clipRow(dim(dr)));
13176
13258
  for (const wl of expLines) contentRows.push(clipRow(GUTTER + dim(wl)));
13177
13259
  for (let i = 0; i < WORD_GAP; i++) contentRows.push(""); // see WORD_GAP
@@ -13385,6 +13467,8 @@ async function runAgentTurn(history, { attachJobId = "", ownJob = false } = {})
13385
13467
  // that might not arrive until the very end (most short replies have none at all).
13386
13468
  let carryFlushedLen = 0;
13387
13469
  const consume = (chunk) => {
13470
+ // The worker's own 45s heartbeats and its "No data from the model" notes say nothing about the model.
13471
+ if (String(chunk).split("\n").some((l) => l.trim() && !isHeartbeatLine(l) && !/^\s*No data from the model/.test(l))) lastDataAt = Date.now();
13388
13472
  carry += stripThinkTags(chunk);
13389
13473
  let nl;
13390
13474
  while ((nl = carry.indexOf("\n")) >= 0) {
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.901",
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",
@@ -63,6 +63,7 @@
63
63
  "files": [
64
64
  "accent.mjs",
65
65
  "agent-deps-preflight.mjs",
66
+ "connection-watch.mjs",
66
67
  "edit-card-render.mjs",
67
68
  "diff-syntax.mjs",
68
69
  "theme.mjs",