@tiens.nguyen/gu-cli 1.0.925 → 1.0.929

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/add-server.mjs CHANGED
@@ -14,7 +14,7 @@
14
14
  * server kind ("dialect": an Ollama's /api/tags vs an OpenAI-compatible /v1/models) lives in
15
15
  * serverTarget() and listRequest().
16
16
  */
17
- import { defaultProviderUrl, ensureV1Root, hostLocality, isAnthropicUrl, isCancelWord, modelListRequest, normalizeProviderUrl, parseProviderModels, MAX_MODELS_PER_SERVER } from "./coding-provider-setup.mjs";
17
+ import { defaultProviderUrl, ensureV1Root, hostLocality, isAnthropicUrl, isKeylessHost, isCancelWord, modelListRequest, normalizeProviderUrl, parseProviderModels, MAX_MODELS_PER_SERVER } from "./coding-provider-setup.mjs";
18
18
 
19
19
  // Re-exported: the add-server screen's own name for the rule every URL prompt shares.
20
20
  export { isCancelWord };
@@ -144,7 +144,9 @@ export function roleRefusal(role, target) {
144
144
  export function keyRequirement(target) {
145
145
  if (!target?.ok) return "none";
146
146
  if (target.dialect === "ollama") return target.cloud ? "required" : "none";
147
- return target.locality === "loopback" || target.locality === "private" ? "optional" : "required";
147
+ if (target.locality === "loopback" || target.locality === "private") return "optional";
148
+ // A known LAN name (ollama1.getmarsic.cc, GH #521): Enter skips the key here too.
149
+ return isKeylessHost(target.host) ? "optional" : "required";
148
150
  }
149
151
 
150
152
  /**
@@ -18,7 +18,7 @@
18
18
  */
19
19
 
20
20
  import { modelRetired, ensureV1Root, isAnthropicUrl, modelListRequest } from "./coding-provider-setup.mjs";
21
- import { isOllamaCloudUrl } from "./coding-key-prompt.mjs";
21
+ import { isOllamaCloudUrl, isLocalNetworkUrl } from "./coding-key-prompt.mjs";
22
22
 
23
23
 
24
24
  /**
@@ -278,6 +278,12 @@ export function agentModelsFromBody(dialect, body, now = Date.now()) {
278
278
  * or LAN Ollama does not.
279
279
  */
280
280
  export function agentSourceNeedsKey(source) {
281
+ if (!agentSourceCanUseKey(source)) return false;
282
+ return !(source.dialect === "openai" && isLocalNetworkUrl(source.row.url));
283
+ }
284
+
285
+ /** MAY this source be given a key? Its stored key is sent, and "API keys for …" is offered (GH #521). */
286
+ export function agentSourceCanUseKey(source) {
281
287
  const row = source?.row;
282
288
  if (!row) return false;
283
289
  return source.dialect === "openai" || isOllamaCloudUrl(String(row.url ?? ""));
package/cli-token.mjs CHANGED
@@ -28,10 +28,31 @@
28
28
  */
29
29
  import { createHash, createPublicKey, verify } from "node:crypto";
30
30
  import { execFile } from "node:child_process";
31
+ import { readFileSync } from "node:fs";
31
32
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
32
33
  import { hostname as osHostname, userInfo } from "node:os";
33
34
  import { dirname, join } from "node:path";
34
35
 
36
+ /** This gu's version (package.json), "" when it cannot be read. */
37
+ export const GU_VERSION = (() => {
38
+ try {
39
+ return String(JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")).version ?? "");
40
+ } catch {
41
+ return "";
42
+ }
43
+ })();
44
+
45
+ /**
46
+ * GH #529: gu's version and mode on the requests it already makes to the gu service, so the admin
47
+ * Users page can say which versions are in use. Nothing else about the computer or the user.
48
+ */
49
+ export function guHeaders(mode, version = GU_VERSION) {
50
+ return {
51
+ ...(version ? { "x-gu-version": String(version) } : {}),
52
+ ...(mode ? { "x-gu-mode": String(mode) } : {}),
53
+ };
54
+ }
55
+
35
56
  /** The public half of the API's CLI_TOKEN_PRIVATE_KEY, base64 SPKI DER (Ed25519). Generated 2026-09-17. */
36
57
  export const EMBEDDED_PUBLIC_KEY = "MCowBQYDK2VwAyEA2xkKnY+xWGoS4Nvc7DEHCCurdQQYZGl/x7kPp+gDmvY=";
37
58
 
@@ -153,14 +174,14 @@ export async function trialDevice(opts = {}) {
153
174
  * { ok: false, why: "no-device" | "unreachable" | "http-NNN" | "bad-response" }
154
175
  * Never throws.
155
176
  */
156
- export async function claimTrial({ hostedBase, device, fetchImpl = fetch, timeoutMs = 8000 }) {
177
+ export async function claimTrial({ hostedBase, device, mode = "", fetchImpl = fetch, timeoutMs = 8000 }) {
157
178
  if (!device) return { ok: false, why: "no-device" };
158
179
  const base = String(hostedBase ?? "").replace(/\/+$/, "");
159
180
  if (!base) return { ok: false, why: "unreachable" };
160
181
  try {
161
182
  const res = await fetchImpl(`${base}/api/billing/cli-token/trial`, {
162
183
  method: "POST",
163
- headers: { "content-type": "application/json" },
184
+ headers: { "content-type": "application/json", ...guHeaders(mode) },
164
185
  body: JSON.stringify({ device }),
165
186
  signal: AbortSignal.timeout(timeoutMs),
166
187
  });
@@ -572,7 +593,7 @@ export async function renewToken({ mode, apiBase, hostedBase, token, workerKey,
572
593
  const base = String(mode === "expert" ? hostedBase : apiBase || hostedBase).replace(/\/+$/, "");
573
594
  const body = JSON.stringify(device ? { device } : {});
574
595
  let url;
575
- const headers = { "content-type": "application/json" };
596
+ const headers = { "content-type": "application/json", ...guHeaders(mode) };
576
597
  if (token) {
577
598
  url = `${base}/api/billing/cli-token/renew`;
578
599
  headers.authorization = `Bearer ${token}`;
@@ -593,6 +614,39 @@ export async function renewToken({ mode, apiBase, hostedBase, token, workerKey,
593
614
  }
594
615
  }
595
616
 
617
+ /**
618
+ * GH #529: "gu ran on this computer today" — POST /api/billing/cli-token/seen with the token, once a
619
+ * UTC day (the day is kept in ~/.gonext/cli-token-seen). It is what lets the admin page count users
620
+ * rather than installs. → { ok, why? }. Never throws; a failure is retried at the next hourly tick.
621
+ */
622
+ export const SEEN_FILE = "cli-token-seen";
623
+ export const utcDay = (d = new Date()) => d.toISOString().slice(0, 10);
624
+
625
+ export async function reportSeen({ dir, mode, apiBase, hostedBase, token, device, now = new Date(), fetchImpl = fetch, timeoutMs = 8000 }) {
626
+ if (!token || !device) return { ok: false, why: "no-credential" };
627
+ const file = join(dir, SEEN_FILE);
628
+ const today = utcDay(now);
629
+ const last = await readFile(file, "utf8").then((t) => t.trim(), () => "");
630
+ if (last === today) return { ok: true, why: "already" };
631
+ const base = String(mode === "expert" ? hostedBase : apiBase || hostedBase).replace(/\/+$/, "");
632
+ if (!base) return { ok: false, why: "no-api" };
633
+ try {
634
+ const res = await fetchImpl(`${base}/api/billing/cli-token/seen`, {
635
+ method: "POST",
636
+ headers: { "content-type": "application/json", authorization: `Bearer ${token}`, ...guHeaders(mode) },
637
+ body: JSON.stringify({ device }),
638
+ signal: AbortSignal.timeout(timeoutMs),
639
+ });
640
+ // 404: a gu service from before this call existed — nothing to retry until it is updated.
641
+ if (!res.ok && res.status !== 404) return { ok: false, why: `http-${res.status}` };
642
+ await mkdir(dir, { recursive: true });
643
+ await writeFile(file, today + "\n", "utf8");
644
+ return { ok: true };
645
+ } catch (e) {
646
+ return { ok: false, why: e?.name === "TimeoutError" ? "timeout" : "network" };
647
+ }
648
+ }
649
+
596
650
  /**
597
651
  * A free-model promo code with NO token (the computer's trial ended, or it never had one): the code is the
598
652
  * credential, and the answer carries a token for this computer that runs for the code's months. Never throws.
@@ -26,6 +26,7 @@ const identity = (s) => s;
26
26
  */
27
27
  import { keyInUse } from "./server-keys.mjs";
28
28
  import { resultLine } from "./first-hi.mjs";
29
+ import { isKeylessHost } from "./coding-provider-setup.mjs";
29
30
 
30
31
  export const SECRET_KEY_HINT = "type or paste the key, then press Enter — it stays masked";
31
32
 
@@ -80,9 +81,28 @@ export function isOllamaCloudUrl(url) {
80
81
  * belief that Ollama never authenticates — true of a local or LAN Ollama, false of ollama.com.
81
82
  */
82
83
  export function codingNeedsKey(kind, url) {
84
+ return codingCanUseKey(kind, url) && !(kind === "openai" && isLocalNetworkUrl(url));
85
+ }
86
+
87
+ /**
88
+ * MAY this coder be given a key? Wider than "must have one": an OpenAI-compatible server on your own
89
+ * network works without a key, but can be set to ask for one, so ctrl+k must still reach it (GH #521).
90
+ */
91
+ export function codingCanUseKey(kind, url) {
83
92
  return kind === "openai" || (kind === "ollama" && isOllamaCloudUrl(url));
84
93
  }
85
94
 
95
+ /** This machine, a private network or a known LAN name — the same rule "add a provider" and the API use. */
96
+ export function isLocalNetworkUrl(url) {
97
+ let host;
98
+ try {
99
+ host = new URL(String(url ?? "").trim()).hostname;
100
+ } catch {
101
+ return false;
102
+ }
103
+ return isKeylessHost(host);
104
+ }
105
+
86
106
  /**
87
107
  * @param payload the /agent-payload `payload` object (reads codingKeyMissing/codingKeyModel).
88
108
  * @param deps.askSecret async (prompt) => string — masked input; "" means the user skipped.
@@ -28,6 +28,26 @@ const METADATA_HOSTS = new Set([
28
28
  const IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
29
29
 
30
30
  /** Loopback, LAN, or a name that can only resolve inside a network. */
31
+ /**
32
+ * NAMES THAT WRAP A LAN BOX (GH #521). The owner's own Ollama servers get a public-looking DNS name
33
+ * (ollama1.getmarsic.cc → 192.168.x). Matched NARROWLY — ollama<number>.getmarsic.cc and nothing
34
+ * else under that domain — so no hosted provider can ever be read as keyless. Keep in step with
35
+ * KEYLESS_LAN_NAME in api/src/store/settingsTypes.ts.
36
+ */
37
+ export const KEYLESS_LAN_NAME = /^ollama\d*\.getmarsic\.cc$/;
38
+
39
+ /**
40
+ * May this server be called WITHOUT a key? This machine, a private network, or a known LAN name.
41
+ * Only the key question reads this; hostLocality stays the truth about WHERE a host is (it also
42
+ * guesses http vs https, which a wrapped name must not change).
43
+ */
44
+ export function isKeylessHost(hostname) {
45
+ const where = hostLocality(hostname);
46
+ if (where === "loopback" || where === "private") return true;
47
+ const host = String(hostname ?? "").toLowerCase().replace(/:\d+$/, "").replace(/\.$/, "");
48
+ return KEYLESS_LAN_NAME.test(host);
49
+ }
50
+
31
51
  export function hostLocality(hostname) {
32
52
  let host = String(hostname ?? "").toLowerCase().replace(/\.$/, "");
33
53
  // A PORT MAY COME ALONG. Callers hand this both a bare hostname (from URL.hostname) and a
package/command-allow.mjs CHANGED
@@ -3,6 +3,7 @@
3
3
  // question ("a destructive command ...") can be skipped by it - sudo, the denylist and deletes
4
4
  // outside the project are never covered by it.
5
5
  import { readFileSync, writeFileSync, mkdirSync, realpathSync } from "node:fs";
6
+ import { createHash } from "node:crypto";
6
7
  import { dirname, join, sep } from "node:path";
7
8
  import { homedir } from "node:os";
8
9
 
@@ -14,22 +15,86 @@ const real = (p) => {
14
15
  return p;
15
16
  }
16
17
  };
17
- export function commandAllowList() {
18
+ function readAll() {
18
19
  try {
19
- const f = JSON.parse(readFileSync(commandAllowPath(), "utf8")).folders;
20
- return Array.isArray(f) ? f : [];
20
+ const j = JSON.parse(readFileSync(commandAllowPath(), "utf8"));
21
+ return j && typeof j === "object" ? j : {};
21
22
  } catch {
22
- return [];
23
+ return {};
23
24
  }
24
25
  }
26
+ function writeAll(j) {
27
+ mkdirSync(dirname(commandAllowPath()), { recursive: true });
28
+ writeFileSync(commandAllowPath(), JSON.stringify(j, null, 2));
29
+ }
30
+ const inside = (f, r) => f === r || f.startsWith(r.replace(/[\\/]+$/, "") + sep);
31
+ export function commandAllowList() {
32
+ const f = readAll().folders;
33
+ return Array.isArray(f) ? f : [];
34
+ }
25
35
  /** Is `folder` on the list, or inside a folder that is (a project covers its subfolders)? */
26
36
  export function commandAllowedIn(folder) {
27
37
  const f = real(folder);
28
- return commandAllowList().some((r) => f === r || f.startsWith(r.replace(/[\\/]+$/, "") + sep));
38
+ return commandAllowList().some((r) => inside(f, r));
29
39
  }
40
+ /** Add the folder, or (allow=false) take it back. */
30
41
  export function commandAllowIn(folder, allow = true) {
31
42
  const f = real(folder);
32
- const folders = [...commandAllowList().filter((x) => x !== f), ...(allow ? [f] : [])];
33
- mkdirSync(dirname(commandAllowPath()), { recursive: true });
34
- writeFileSync(commandAllowPath(), JSON.stringify({ folders }, null, 2));
43
+ const j = readAll();
44
+ j.folders = [...commandAllowList().filter((x) => x !== f), ...(allow ? [f] : [])];
45
+ writeAll(j);
46
+ }
47
+
48
+ // "Yes, don't ask again for this project" (GH #515): no "Allow running this command?" at all here —
49
+ // including sudo and deletes outside the project. A list of its own, so an older, narrower yes
50
+ // ("always in this folder", destructive commands only) is never widened to this.
51
+ export const PROJECT_CHOICE = "Yes, don't ask again for this project";
52
+ export function projectList() {
53
+ const l = readAll().projects;
54
+ return Array.isArray(l) ? l : [];
55
+ }
56
+ export function commandProjectAllowed(folder) {
57
+ const f = real(folder);
58
+ return projectList().some((r) => inside(f, r));
59
+ }
60
+ export function commandAllowProject(folder) {
61
+ const f = real(folder);
62
+ const j = readAll();
63
+ j.projects = [...projectList().filter((x) => x !== f), f];
64
+ writeAll(j);
65
+ }
66
+
67
+ /**
68
+ * /command forget — gu asks again HERE. Every remembered yes that reaches this folder goes: one given
69
+ * for it, inside it, or for a folder above it (which covered it).
70
+ */
71
+ export function commandForget(folder) {
72
+ const f = real(folder);
73
+ const reaches = (r) => inside(f, String(r)) || inside(String(r), f);
74
+ const j = readAll();
75
+ j.folders = commandAllowList().filter((r) => !reaches(r));
76
+ j.projects = projectList().filter((r) => !reaches(r));
77
+ j.sourced = sourcedList().filter((e) => !reaches(e.folder));
78
+ writeAll(j);
79
+ }
80
+
81
+ // "Yes, don't ask again for this file" on the `source` question (GH #515): remembered for the file's
82
+ // CONTENTS — once it changes, gu asks again (a yes must not cover whatever is written into it later).
83
+ export const SOURCE_FILE_MARK = " · file: ";
84
+ /** The file the question is about, from its reason; "" for any other question. */
85
+ export function sourcedFileOf(why) {
86
+ const s = String(why ?? "");
87
+ if (!/^it runs text as code \((source|\.)\)/.test(s)) return "";
88
+ const i = s.indexOf(SOURCE_FILE_MARK);
89
+ return i < 0 ? "" : s.slice(i + SOURCE_FILE_MARK.length).trim();
90
+ }
91
+ export function sourcedList() {
92
+ const l = readAll().sourced;
93
+ return Array.isArray(l) ? l : [];
94
+ }
95
+ export function commandAllowSource(folder, path) {
96
+ const entry = { folder: real(folder), path, sha256: createHash("sha256").update(readFileSync(path)).digest("hex") };
97
+ const j = readAll();
98
+ j.sourced = [...sourcedList().filter((e) => !(e.path === path && e.folder === entry.folder)), entry];
99
+ writeAll(j);
35
100
  }
@@ -24,6 +24,7 @@ Emits NDJSON lines on stdout:
24
24
  {"type": "final", "text": "..."} — assistant answer
25
25
  """
26
26
  import contextlib
27
+ import hashlib
27
28
  import json
28
29
  import os
29
30
  import random
@@ -1805,6 +1806,28 @@ def _sentinel_against_ollama(agent_base_url, agent_model_id, probe=None):
1805
1806
  )
1806
1807
 
1807
1808
 
1809
+ def _server_of(url) -> tuple:
1810
+ """(scheme, host, port) of a server URL, so that two paths on one server compare equal."""
1811
+ try:
1812
+ u = urlparse(str(url or "").strip())
1813
+ scheme = (u.scheme or "").lower()
1814
+ return scheme, (u.hostname or "").lower(), u.port or {"http": 80, "https": 443}.get(scheme)
1815
+ except ValueError:
1816
+ return str(url or ""), "", None
1817
+
1818
+
1819
+ def _coder_auth_key(coding_api_key, coding_base_url, agent_api_key, agent_base_url) -> str:
1820
+ """The key sent to the coding server. A KEY BELONGS TO A SERVER (#245, GH #521): with no
1821
+ coding key, the chat model's key is used only when both are the same server. Any other server
1822
+ gets the placeholder "local" — never another provider's key (a keyless LAN box would have been
1823
+ sent the hosted chat key over plain http)."""
1824
+ if coding_api_key:
1825
+ return coding_api_key
1826
+ if _server_of(coding_base_url) == _server_of(agent_base_url):
1827
+ return agent_api_key
1828
+ return "local"
1829
+
1830
+
1808
1831
  def _resolve_coding_target(agent_base_url, agent_model_id, raw_coding_base, raw_coding_model,
1809
1832
  *, agent_api_key="", coding_api_key="", detect=None):
1810
1833
  """WHICH SERVER AND WHICH MODEL NAME does the CODE half of a turn actually use?
@@ -1846,7 +1869,9 @@ def _resolve_coding_target(agent_base_url, agent_model_id, raw_coding_base, raw_
1846
1869
  # A DIFFERENT dedicated coding server. If no model name was given, ask the
1847
1870
  # server which model it serves (mlx_lm.server otherwise tries to download a
1848
1871
  # mismatched name from HF and 404s).
1849
- detected = raw_coding_model or detect(raw_coding_base, coding_api_key or agent_api_key)
1872
+ detected = raw_coding_model or detect(
1873
+ raw_coding_base,
1874
+ _coder_auth_key(coding_api_key, raw_coding_base, agent_api_key, agent_base_url))
1850
1875
  if detected:
1851
1876
  return raw_coding_base, detected
1852
1877
  _log(
@@ -4081,10 +4106,14 @@ def _plain_reply(messages: list, base_url: str, api_key: str, model_id: str,
4081
4106
  # raw nginx 502 page can be a whole document) for whichever caller logs/surfaces it.
4082
4107
  # The FIRST error is the model the user asked for; when the stand-in failed differently
4083
4108
  # (e.g. a 502 on the fallback), the real cause would otherwise be hidden.
4084
- if first_err is not None and last_err is not first_err and str(first_err) != str(last_err):
4085
- raise RuntimeError(f"couldn't get a response ({_clip(str(first_err), 110)}; "
4086
- f"then {_clip(str(last_err), 70)})")
4087
- raise RuntimeError(f"couldn't get a response ({_clip(str(last_err), 160)})")
4109
+ # WHO did not answer (GH #521): "Connection error." alone named neither model nor server.
4110
+ def _who(t):
4111
+ return f"{t[1]} at {_host_of(t[0])}"
4112
+
4113
+ if first_err is not None and last_err is not first_err:
4114
+ raise RuntimeError(f"couldn't get a response ({_who(targets[0])}: {_clip(str(first_err), 110)}; "
4115
+ f"then {_who(targets[-1])}: {_clip(str(last_err), 70)})")
4116
+ raise RuntimeError(f"couldn't get a response ({_who(targets[0])}: {_clip(str(last_err), 160)})")
4088
4117
 
4089
4118
 
4090
4119
  # A model-server call can fail for two very different reasons, and they deserve
@@ -4507,6 +4536,8 @@ def _fetch_cloud_limits(api_base: str, timeout: float = 5.0) -> int:
4507
4536
  "regex": r.get("origin") == "table",
4508
4537
  "ctx": r.get("contextWindow") if isinstance(r.get("contextWindow"), int) and r.get("contextWindow") > 0 else 0,
4509
4538
  "out": r.get("maxOutput") if isinstance(r.get("maxOutput"), int) and r.get("maxOutput") > 0 else 0,
4539
+ # GH #528: the model takes images (the admin Models page, from the providers' catalogs).
4540
+ "images": r.get("images") is True,
4510
4541
  })
4511
4542
  _CLOUD_LIMITS["rows"] = rows
4512
4543
  _log(f"cloud token table: {len(rows)} rows")
@@ -8709,7 +8740,7 @@ def _ws_write_outside_reason(redirects, wd, roots=None):
8709
8740
  return "it writes a file OUTSIDE the project (" + ", ".join(outside[:3]) + ")"
8710
8741
 
8711
8742
 
8712
- def _ws_shell_command_risk(scan, denyset, wd="", allowset=None, roots=None):
8743
+ def _ws_shell_command_risk(scan, denyset, wd="", allowset=None, roots=None, env_file=None):
8713
8744
  """The run policy for a SHELL line, applied to each simple command in it.
8714
8745
 
8715
8746
  → (refuse, hard_reason, ask_reason): `refuse` is a finished error message (allowlist — never
@@ -8754,22 +8785,43 @@ def _ws_shell_command_risk(scan, denyset, wd="", allowset=None, roots=None):
8754
8785
  and all(x.startswith("-") for x in a[1:]):
8755
8786
  msg = f"it pipes text into {r}, which runs that text as code"
8756
8787
  return (None, msg, msg)
8788
+ # `cd sub && rm -rf x`: judge a delete (or a sourced file) from the folder the shell will be in.
8789
+ cwds, cur = {}, wd
8790
+ for c in top:
8791
+ a = c["argv"]
8792
+ if a and a[0] == "cd" and len(a) >= 2 and c["sep"] not in ("|", "|&"):
8793
+ cur = os.path.normpath(os.path.join(cur or os.getcwd(),
8794
+ os.path.expanduser(_shell_path_to_native(a[1]))))
8795
+ cwds[id(c)] = cur
8796
+ # GH #515: gu sources <workspace>/.gonext/env ITSELF before every line (#181), so a line that sources
8797
+ # that same file adds nothing — never ask. Another file the user said yes to for good is not asked
8798
+ # while it is unchanged, and only when nothing but `cd` (or such sources) runs before it in the line:
8799
+ # anything else could rewrite it first.
8800
+ own_env = _ws_env_file() if env_file is None else env_file
8801
+ top_ids = [id(c) for c in top]
8802
+ untouched = set() # top commands with only cd / cleared sources before them
8803
+ clean_so_far = True
8804
+ for c in top:
8805
+ if clean_so_far:
8806
+ untouched.add(id(c))
8807
+ a = c["argv"]
8808
+ if not (a and (a[0] == "cd" or (a[0] in ("source", ".") and len(a) == 2)) and not c["redirects"]):
8809
+ clean_so_far = False
8757
8810
  for c in every:
8758
8811
  a = c["argv"]
8759
8812
  if not a:
8760
8813
  continue
8761
8814
  if a[0] in _SHELL_EVAL_RUNNERS:
8815
+ target = _sourced_file(a, cwds.get(id(c), wd))
8816
+ if target:
8817
+ if own_env and target == os.path.realpath(own_env):
8818
+ continue
8819
+ if id(c) in top_ids and id(c) in untouched and _cmd_source_allowed(target, wd):
8820
+ continue
8821
+ return (None, None, f"it runs text as code ({a[0]}){_SOURCE_FILE_MARK}{target}")
8762
8822
  return (None, None, f"it runs text as code ({a[0]})")
8763
8823
  if "$" in a[0] or "`" in a[0]:
8764
8824
  return (None, None, f"the program to run is only known at run time ({a[0][:40]})")
8765
- # `cd sub && rm -rf x`: judge a delete from the folder the shell will be in when it runs.
8766
- cwds, cur = {}, wd
8767
- for c in top:
8768
- a = c["argv"]
8769
- if a and a[0] == "cd" and len(a) >= 2 and c["sep"] not in ("|", "|&"):
8770
- cur = os.path.normpath(os.path.join(cur or os.getcwd(),
8771
- os.path.expanduser(_shell_path_to_native(a[1]))))
8772
- cwds[id(c)] = cur
8773
8825
  for c in every:
8774
8826
  here = cwds.get(id(c), wd)
8775
8827
  if (_WS_DESTRUCTIVE_RE.search(" ".join(c["argv"]))
@@ -8828,6 +8880,23 @@ def _ps_native_paths(paths, wd):
8828
8880
  return out
8829
8881
 
8830
8882
 
8883
+ # gu-repl.mjs reads the path after this mark to offer "don't ask again for this file" (GH #515).
8884
+ _SOURCE_FILE_MARK = " · file: "
8885
+
8886
+
8887
+ def _sourced_file(argv, wd):
8888
+ """The real path `source X` / `. X` would read, or "" when it cannot be known for sure: extra
8889
+ arguments, a name only known at run time, a bare name (bash searches PATH for it), no such file."""
8890
+ if len(argv) != 2 or argv[0] not in ("source", "."):
8891
+ return ""
8892
+ p = argv[1]
8893
+ if "/" not in p or any(ch in p for ch in "$`*?[\t\n"):
8894
+ return ""
8895
+ p = os.path.expanduser(_shell_path_to_native(p))
8896
+ full = os.path.realpath(p if os.path.isabs(p) else os.path.join(wd or os.getcwd(), p))
8897
+ return full if os.path.isfile(full) else ""
8898
+
8899
+
8831
8900
  def _ws_ps_command_risk(scan, denyset, wd="", allowset=None, roots=None):
8832
8901
  """_ws_shell_command_risk for a PowerShell line. Same contract: (refuse, hard, ask)."""
8833
8902
  gp = _ps_mod()
@@ -9126,7 +9195,8 @@ _BG_LINE = ("A LONG job (build, deploy, big test run) → run_command(…, backg
9126
9195
  "polls; a build whose result you need next is simpler as one run_command(…, "
9127
9196
  "timeout_seconds=600). A command still running at its timeout moves to the background "
9128
9197
  "by itself instead of being killed. Setup every command needs (exports) goes ONCE in "
9129
- "<workspace>/.gonext/env, which is sourced before each command. A recipe that WORKED "
9198
+ "<workspace>/.gonext/env, which gu sources before each command by itself (never `source` "
9199
+ "it in a command). A recipe that WORKED "
9130
9200
  "after effort (a login, build flags, a deploy path) or a short project summary goes as "
9131
9201
  "ONE line in <workspace>/.gonext/notes.md, shown at the start of every later turn.\n")
9132
9202
 
@@ -9937,6 +10007,34 @@ def _cmd_allow_path():
9937
10007
  return os.environ.get("GU_COMMAND_ALLOW") or os.path.join(os.path.expanduser("~"), ".gonext", "command-allow.json")
9938
10008
 
9939
10009
 
10010
+ def _cmd_source_allowed(path, wd):
10011
+ """Did the user say "don't ask again for this file" (GH #515), here, for exactly these contents?"""
10012
+ try:
10013
+ with open(_cmd_allow_path(), encoding="utf-8") as f:
10014
+ entries = json.load(f).get("sourced") or []
10015
+ with open(path, "rb") as fh:
10016
+ digest = hashlib.sha256(fh.read()).hexdigest()
10017
+ here = os.path.realpath(wd or os.getcwd())
10018
+ return any(isinstance(e, dict) and e.get("path") == path and e.get("sha256") == digest
10019
+ and isinstance(e.get("folder"), str) and _ws_is_inside(here, [e["folder"]])
10020
+ for e in entries)
10021
+ except (OSError, ValueError, AttributeError, TypeError):
10022
+ return False
10023
+
10024
+
10025
+ def _cmd_project_allowed(folder):
10026
+ """Is `folder` in a project the user said "don't ask again for this project" in (GH #515)?"""
10027
+ if not folder:
10028
+ return False
10029
+ try:
10030
+ with open(_cmd_allow_path(), encoding="utf-8") as f:
10031
+ projects = json.load(f).get("projects") or []
10032
+ real = os.path.realpath(folder)
10033
+ return any(isinstance(r, str) and r and _ws_is_inside(real, [r]) for r in projects)
10034
+ except (OSError, ValueError, AttributeError, TypeError):
10035
+ return False
10036
+
10037
+
9940
10038
  def _cmd_allowed_in(folder):
9941
10039
  """Is `folder` on the always-allow list, or inside a folder that is?"""
9942
10040
  if not folder:
@@ -11253,9 +11351,9 @@ def _prepare_image(path):
11253
11351
  return im
11254
11352
 
11255
11353
 
11256
- # WHICH CODERS MAY BE SENT IMAGES (#284, #316) — the SAME list the CLI gates Ctrl+V with
11257
- # (image-capable-coders.json, beside this file), so the two can never disagree. A server/model is
11258
- # added there only after a real request with an image came back right.
11354
+ # WHICH CODERS MAY BE SENT IMAGES (#284, #316, GH #528) — the SAME lists the CLI gates Ctrl+V with:
11355
+ # image-capable-coders.json beside this file (Claude, Kimi K3 — verified by hand), plus every model the
11356
+ # cloud token table marks images: true (the admin Models page; the owner chose to trust the catalog).
11259
11357
  def _image_coders():
11260
11358
  # GU_IMAGE_CODERS_FILE: tests only — a stand-in coder on 127.0.0.1 is put on the list there.
11261
11359
  path = os.environ.get("GU_IMAGE_CODERS_FILE") or os.path.join(
@@ -11268,12 +11366,34 @@ def _image_coders():
11268
11366
  return [{"host": "api.anthropic.com"}]
11269
11367
 
11270
11368
 
11369
+ def _cloud_image_coders():
11370
+ """GH #528: the models the cloud list says take images — [{host, exact}].
11371
+
11372
+ From the cloud token table this job read (_CLOUD_LIMITS), else from ~/.gonext/image-models.json,
11373
+ which the CLI writes from the same table: the CLI's Ctrl+V gate and this one stay the same list."""
11374
+ rows = [r for r in _CLOUD_LIMITS["rows"] if r.get("images") and r.get("host") and not r.get("regex")]
11375
+ if rows:
11376
+ return [{"host": r["host"], "exact": str(r["model"]).strip().lower()} for r in rows]
11377
+ try:
11378
+ path = os.path.join(os.path.expanduser("~"), ".gonext", "image-models.json")
11379
+ with open(path, encoding="utf-8") as f:
11380
+ saved = json.load(f).get("coders") or []
11381
+ return [c for c in saved if isinstance(c, dict) and c.get("host") and c.get("exact")]
11382
+ except Exception: # noqa: BLE001
11383
+ return []
11384
+
11385
+
11271
11386
  def _coder_takes_images(url, model, coders=None):
11272
11387
  """May the question's pasted images be sent to this coding server + model?"""
11273
11388
  host = (urlparse(url or "").hostname or "").lower().rstrip(".")
11274
11389
  name = str(model or "").split("::")[-1].strip()
11275
- for c in (coders if coders is not None else _image_coders()):
11276
- if c.get("host") == host and (not c.get("model") or re.search(c["model"], name, re.I)):
11390
+ for c in (coders if coders is not None else _image_coders() + _cloud_image_coders()):
11391
+ if c.get("host") != host:
11392
+ continue
11393
+ if c.get("exact"):
11394
+ if c["exact"] == name.lower():
11395
+ return True
11396
+ elif not c.get("model") or re.search(c["model"], name, re.I):
11277
11397
  return True
11278
11398
  return False
11279
11399
 
@@ -11421,6 +11541,7 @@ def run_agent_chat(cfg):
11421
11541
  agent_base_url, agent_model_id, raw_coding_base, raw_coding_model,
11422
11542
  agent_api_key=agent_api_key, coding_api_key=coding_api_key,
11423
11543
  )
11544
+ coder_key = _coder_auth_key(coding_api_key, coding_base_url, agent_api_key, agent_base_url)
11424
11545
  # A coder WAS chosen and the chat model is doing its work (#343): its server would not say
11425
11546
  # which model it serves. Said when the agent path starts — a plain chat turn does no coding,
11426
11547
  # so there is nothing to have fallen back from.
@@ -12237,7 +12358,7 @@ def run_agent_chat(cfg):
12237
12358
  # Small prompt → fast. Fall back to the coding model if the chat model is down.
12238
12359
  answer = _plain_reply(messages, agent_base_url, agent_api_key, agent_model_id,
12239
12360
  coding_base_url, coding_model_id,
12240
- coding_api_key or agent_api_key)
12361
+ coder_key)
12241
12362
  _log(f"plain reply: {len(answer)} chars")
12242
12363
  _emit({"type": "final", "text": answer})
12243
12364
  return
@@ -14601,8 +14722,8 @@ def run_agent_chat(cfg):
14601
14722
  ) from e
14602
14723
  raise _AgentConfigError(
14603
14724
  f"The agent coding backend ({_host}) rejected the request: "
14604
- "NO coding API key was sent, so the local agent key was "
14605
- "used instead. Enter the API key for this coding backend — in "
14725
+ "NO coding API key is saved for it. Enter the API key for "
14726
+ "this coding backend — in "
14606
14727
  "gu: press ctrl+k; on the web: Settings → Agent "
14607
14728
  "(OpenAI-compatible, or Ollama with an https://ollama.com URL — "
14608
14729
  "local Ollama needs no key)."
@@ -14612,8 +14733,7 @@ def run_agent_chat(cfg):
14612
14733
  # key here 401s against a cloud coder, so the "This server has:
14613
14734
  # …" hint — the only useful part of this error — silently
14614
14735
  # vanished exactly when it was needed.
14615
- ids = _list_model_ids(coding_base_url,
14616
- coding_api_key or agent_api_key)
14736
+ ids = _list_model_ids(coding_base_url, coder_key)
14617
14737
  have = f" This server has: {', '.join(ids)}." if ids else ""
14618
14738
  raise _AgentConfigError(
14619
14739
  f"The agent coding model {coding_model_id!r} does not "
@@ -15257,8 +15377,8 @@ def run_agent_chat(cfg):
15257
15377
  model = _LoggingModel(
15258
15378
  model_id=coding_model_id,
15259
15379
  api_base=coding_base_url,
15260
- # Task #108: use the OpenAI-compatible coding key when set, else the chat key.
15261
- api_key=coding_api_key or agent_api_key,
15380
+ # Task #108: the coding key; without one, the chat key only on the chat server (GH #521).
15381
+ api_key=coder_key,
15262
15382
  # Stream for Ollama / OpenAI-compatible so a long generation keeps the connection
15263
15383
  # warm and can't trip a reverse-proxy idle read-timeout (smolagents still gets the
15264
15384
  # full text). Only a local MLX coder stays non-streaming.
@@ -16716,6 +16836,12 @@ def run_agent_chat(cfg):
16716
16836
  # question is dropped, not that one.
16717
16837
  _ask_reason = None if (_accept_edits or _ro_line) else (
16718
16838
  "accept edits is off, so every command is confirmed first")
16839
+ # GH #515: "Yes, don't ask again for this project" — every command question, of every
16840
+ # kind. Only where someone can be asked (web and unattended runs keep their blocks), and
16841
+ # accept edits switched off (Shift+Tab) still confirms: that is the user asking to be asked.
16842
+ if _ask_reason and _interactive_approval and _cmd_project_allowed(wd or _WS_ACTIVE or _default_ws_root()):
16843
+ _ask_reason = None if (_accept_edits or _ro_line) else (
16844
+ "accept edits is off, so every command is confirmed first")
16719
16845
  if _ask_reason:
16720
16846
  if _priv and _facts:
16721
16847
  _ask_reason += f" — {_facts['why']}"
package/gu-repl.mjs CHANGED
@@ -146,7 +146,7 @@ import {
146
146
  import { completedFlush, splitLiveStream } from "./completed-flush.mjs";
147
147
  import { isScaffoldStep, isGroupableStep, stepGroupMark, stepGroupRows, relativizePaths } from "./step-group.mjs";
148
148
  import { clearLogsNoticeText } from "./clear-logs.mjs";
149
- import { commandAllowIn, commandAllowedIn } from "./command-allow.mjs";
149
+ import { commandAllowedIn, commandAllowProject, commandAllowSource, commandForget, commandProjectAllowed, sourcedFileOf, PROJECT_CHOICE } from "./command-allow.mjs";
150
150
  import { allowIn, allowedIn, bridgeCommand, browserReport, bridgeStatus, extensionDir, findDevInstalls, helpInstall, installExtensionFiles, installSteps, localLeftovers, openExtensionsPage, removeLocalFiles, STORE_URL, stopBridge } from "./browser-command.mjs";
151
151
  import { commandLogFile, killShell, logTail, markAnnounced, readShells, recapQuestion, runningShells, shellsToRecap, statusText as shellStatusText, renderShellDetails, shellPanelRows, shellPickerLabel, shellState, shellsNotice } from "./shell-details.mjs";
152
152
  import { discoverSkills, matchSkillCommand } from "./skills.mjs";
@@ -172,7 +172,7 @@ import {
172
172
  } from "./model-fallback.mjs";
173
173
  import { codingChoiceTags, coderDisplayName, coderWhere, whereOfActiveCoder } from "./coding-choice-tags.mjs";
174
174
  import { TITLE_POP, TITLE_PUSH, idleTitle, needsSummary, summariseForTitle, titleModel, titleSeq, trimTitle } from "./terminal-title.mjs";
175
- import { IMAGE_NEEDS_CLAUDE, coderTakesImagesFor, clipboardImageToFile, fitImageNotice, imageMarkersForDisplay, createImageStore, imagePasteKey, imagePathFromPaste, isClaudeCoderUrl, isImagePasteKey, storeImageFile } from "./image-paste.mjs";
175
+ import { IMAGE_NEEDS_CLAUDE, coderTakesImagesFor, loadCloudImageCoders, saveCloudImageCoders, clipboardImageToFile, fitImageNotice, imageMarkersForDisplay, createImageStore, imagePasteKey, imagePathFromPaste, isClaudeCoderUrl, isImagePasteKey, storeImageFile } from "./image-paste.mjs";
176
176
  import {
177
177
  isDoubleClick,
178
178
  clickRun,
@@ -2042,8 +2042,12 @@ function showImageNotice(text) {
2042
2042
  imageNoticeTimer.unref?.();
2043
2043
  if (barPinned()) paintBar();
2044
2044
  }
2045
- /** Images go to the coding model; only a Claude coder takes them for now. */
2046
- // #316: Claude, and Kimi K3 on a server verified to take images — one list, shared with the agent.
2045
+ /**
2046
+ * Images go to the coding model when it takes them: Claude, Kimi K3 (image-capable-coders.json), and
2047
+ * since GH #528 every model the cloud list marks `images: true` — read from ~/.gonext/image-models.json
2048
+ * at start, refreshed with the cloud token table (refreshLimitsUpdate).
2049
+ */
2050
+ loadCloudImageCoders();
2047
2051
  const coderTakesImages = () => coderTakesImagesFor(sessionCodingUrl || defaultCodingUrl, sessionCodingModel || defaultCodingModel);
2048
2052
  function insertAtCaret(text) {
2049
2053
  dropSelectedInputText();
@@ -2762,6 +2766,19 @@ async function refreshCliToken() {
2762
2766
  await ct.writeState(dir, state).catch(() => {});
2763
2767
  tokenNotice = noticeNow();
2764
2768
  }
2769
+ // GH #529: once a UTC day, "gu ran here today" — counted on the admin Users page.
2770
+ if (state.token && process.env.GU_NO_UPDATE_CHECK !== "1") {
2771
+ const { DEFAULT_API_BASE } = await import("./device-login.mjs");
2772
+ const device = await ct.thisDevice({ instanceId: myInstanceId || "" }).catch(() => null);
2773
+ await ct.reportSeen({
2774
+ dir,
2775
+ mode,
2776
+ apiBase,
2777
+ hostedBase: String(process.env.GU_TOKEN_API_BASE ?? "").trim() || DEFAULT_API_BASE,
2778
+ token: state.token,
2779
+ device,
2780
+ }).catch(() => {});
2781
+ }
2765
2782
  if (!licenceDecided) {
2766
2783
  licenceDecided = true;
2767
2784
  const d = ct.enforcementDecision({ token: state.token, publicKeyB64: pk, site, deviceId: await thisDeviceId(ct) });
@@ -9272,6 +9289,13 @@ async function refreshLimitsUpdate() {
9272
9289
  const ln = await import("./model-limits-notice.mjs");
9273
9290
  const cloud = await fetchCloudLimits();
9274
9291
  if (!cloud) return;
9292
+ // GH #528: which models take images — kept on disk for the next start and for the agent.
9293
+ // An empty table (not filled yet) keeps what was saved rather than forgetting it.
9294
+ if (cloud.rows.length) {
9295
+ const before = coderTakesImages();
9296
+ saveCloudImageCoders(cloud.rows);
9297
+ if (coderTakesImages() !== before && barPinned()) paintBar();
9298
+ }
9275
9299
  const seenAt = await readLimitsSeen();
9276
9300
  const was = Boolean(limitsUpdate);
9277
9301
  if (!seenAt && cloud.updatedAt) {
@@ -9830,7 +9854,7 @@ async function chooseAgentModel() {
9830
9854
  // THE CURRENT PROVIDER'S OWN ROWS, ON THIS LIST (#248). They were one step down, behind "other
9831
9855
  // models, providers and API keys…" — which read like the "add a provider" row under it.
9832
9856
  const source = am.agentListSource(settings);
9833
- const needsKey = am.agentSourceNeedsKey(source);
9857
+ const canUseKey = am.agentSourceCanUseKey(source);
9834
9858
  for (;;) {
9835
9859
  // The first row is the default and the way back to ONE model: the coding model talks too (GH #397).
9836
9860
  const labels = [
@@ -9861,7 +9885,7 @@ async function chooseAgentModel() {
9861
9885
  const pickOn = async ({ rep, own }) => own
9862
9886
  ? agentModelOnServer({ back: true, start: "models" })
9863
9887
  : addServer({ role: "agent", dialect: rep.kind === "ollama" ? "ollama" : "openai", url: rep.url, back: true });
9864
- const KEYS = curHost && needsKey ? labels.length : -1;
9888
+ const KEYS = curHost && canUseKey ? labels.length : -1;
9865
9889
  if (KEYS >= 0) labels.push(actionRow(`API keys for ${curHost} — switch, add or remove…`));
9866
9890
  const ADD = labels.length;
9867
9891
  labels.push(actionRow("add a provider — Claude API, OpenAI, Kimi, Ollama…"));
@@ -10002,12 +10026,13 @@ async function agentModelOnServer({ back = false, start = "menu" } = {}) {
10002
10026
  // at all, so api.openai.com answered 401 however right the stored key was. Asked for the key
10003
10027
  // bound to THIS provider row — the same one the API will send with each turn.
10004
10028
  const needsKey = am.agentSourceNeedsKey(source);
10029
+ const canUseKey = am.agentSourceCanUseKey(source);
10005
10030
  const listHost = url ? hostOf(url) : "";
10006
10031
  let listKey = "";
10007
10032
  let keyProblem = false;
10008
- if (needsKey) {
10033
+ if (canUseKey) {
10009
10034
  listKey = (await withPendingStatus(`reading the key for ${listHost}`, () => fetchCodingKey(String(source.row?.id ?? "")))).key;
10010
- if (!listKey) {
10035
+ if (!listKey && needsKey) {
10011
10036
  keyProblem = true;
10012
10037
  failure = `no API key is stored for ${listHost}`;
10013
10038
  }
@@ -10029,7 +10054,7 @@ async function agentModelOnServer({ back = false, start = "menu" } = {}) {
10029
10054
  proxyFetch(url, { headers: am.agentListHeaders(listKey, url), signal: AbortSignal.timeout(10000) })
10030
10055
  );
10031
10056
  if (!r.ok) failure = `HTTP ${r.status}`;
10032
- if (!r.ok && needsKey && (r.status === 401 || r.status === 403)) keyProblem = true;
10057
+ if (!r.ok && canUseKey && (r.status === 401 || r.status === 403)) keyProblem = true;
10033
10058
  else models = am.agentModelsFromBody(source.dialect, await r.json().catch(() => null));
10034
10059
  // A 200 with nothing in it is not a working list. Saying "the box answered but listed no
10035
10060
  // models" is a different diagnosis from "unreachable", and the user can act on it.
@@ -10072,7 +10097,7 @@ async function agentModelOnServer({ back = false, start = "menu" } = {}) {
10072
10097
  let firstAction = "models";
10073
10098
  if (start !== "models") {
10074
10099
  console.log(dim(` Agent model — the one that TALKS: ${current || "unset"} on ${listHost}`));
10075
- const menu = am.agentMenuOptions({ host: listHost, modelCount: models.length, needsKey });
10100
+ const menu = am.agentMenuOptions({ host: listHost, modelCount: models.length, needsKey: canUseKey });
10076
10101
  const first = await pickFromList(menu.map((o) => o.label), 0, { back });
10077
10102
  if (first === PICK_BACK) return BACK;
10078
10103
  firstAction = first >= 0 ? menu[first].action : "cancel";
@@ -11024,17 +11049,19 @@ async function coderKeyState(override = "") {
11024
11049
  ? choices.find((c) => c.id === override)
11025
11050
  : choices.find((c) => c.isDefault);
11026
11051
  // Kind AND url: an Ollama coder at https://ollama.com needs a key; a local one does not.
11027
- const { codingNeedsKey } = await import("./coding-key-prompt.mjs");
11052
+ const { codingNeedsKey, codingCanUseKey } = await import("./coding-key-prompt.mjs");
11028
11053
  const needsKey = codingNeedsKey(active?.kind, active?.url);
11054
+ const canUseKey = codingCanUseKey(active?.kind, active?.url);
11029
11055
  return {
11030
11056
  needsKey,
11057
+ canUseKey,
11031
11058
  model: p.codingKeyModel || active?.model || "the coding model",
11032
11059
  missing: (codingKeyMissingKnown = needsKey && p.codingKeyMissing === true),
11033
11060
  // ASKED FOR THIS BACKEND, not for the account (task #223 follow-up): with several
11034
11061
  // providers the account default is a different credential from the one this coder gets,
11035
11062
  // so the masked tail shown here named a key that would never be used.
11036
11063
  stored:
11037
- needsKey && p.codingKeyMissing !== true
11064
+ canUseKey && p.codingKeyMissing !== true
11038
11065
  ? (await fetchCodingKey(typeof active?.backendId === "string" ? active.backendId : ""))
11039
11066
  .key
11040
11067
  : "",
@@ -11045,7 +11072,7 @@ async function coderKeyState(override = "") {
11045
11072
  provider: typeof active?.label === "string" ? active.label : "",
11046
11073
  };
11047
11074
  } catch {
11048
- return { needsKey: false, model: "", missing: false, stored: "", backendId: "", provider: "" };
11075
+ return { needsKey: false, canUseKey: false, model: "", missing: false, stored: "", backendId: "", provider: "" };
11049
11076
  }
11050
11077
  }
11051
11078
 
@@ -11232,7 +11259,7 @@ async function replaceCodingKey({ back = false } = {}) {
11232
11259
  const ks = await withPendingStatus("checking the coding model", () =>
11233
11260
  coderKeyState(sessionCodingModel)
11234
11261
  );
11235
- if (!ks.needsKey) {
11262
+ if (!ks.canUseKey) {
11236
11263
  console.log(
11237
11264
  "\n" + GUTTER + dim(`${ks.model || "This coding model"} needs no API key — nothing to set.\n`)
11238
11265
  );
@@ -11715,14 +11742,16 @@ function drawApprovalOptions(redraw) {
11715
11742
  // Both rows are a handful of columns wide, so they survive any resize on ONE physical row
11716
11743
  // each and the \x1b[2A count stays exact — which is why a resize can simply redraw here.
11717
11744
  const yes = approvalSel === 0 ? accent("▸ Yes") : dim(" Yes");
11745
+ const always = approvalSel === 1 ? accent("▸ " + PROJECT_CHOICE) : dim(" " + PROJECT_CHOICE);
11718
11746
  const tail = approvalDeadline ? " (auto-No in " + countdownLabel(approvalDeadline - Date.now()) + ")" : "";
11719
- const no = approvalSel === 1 ? accent("▸ No" + tail) : dim(" No" + tail);
11747
+ const no = approvalSel === 2 ? accent("▸ No" + tail) : dim(" No" + tail);
11748
+ const alwaysRow = clipVisible(GUTTER + always, Math.max(20, process.stdout.columns || 80) - 1);
11720
11749
  const noRow = clipVisible(GUTTER + no, Math.max(20, process.stdout.columns || 80) - 1);
11721
11750
  if (!redraw && barPinned() && !scrolledBack()) {
11722
11751
  const content = displayRows(transcript.lines(), Math.max(20, process.stdout.columns || 80) - 1).length;
11723
11752
  approvalOpenedOver = { content, pad: currentPad(content), height: viewportHeight() };
11724
11753
  }
11725
- regionUi((redraw ? "\x1b[2A" : "") + "\x1b[K" + GUTTER + yes + "\n\x1b[K" + noRow + "\n");
11754
+ regionUi((redraw ? "\x1b[3A" : "") + "\x1b[K" + GUTTER + yes + "\n\x1b[K" + alwaysRow + "\n\x1b[K" + noRow + "\n");
11726
11755
  }
11727
11756
  /** #204: the command block of the open Yes/No prompt — Ctrl+O toggles it (a click does too). */
11728
11757
  let approvalCommandBlock = null;
@@ -11744,7 +11773,7 @@ function printApprovalCommand(shown, { toggle = true } = {}) {
11744
11773
  if (thoughtBlocks.length > 200) thoughtBlocks = thoughtBlocks.slice(-200);
11745
11774
  return block;
11746
11775
  }
11747
- function finishApproval(allow, timedOut = false) {
11776
+ function finishApproval(allow, timedOut = false, forProject = false) {
11748
11777
  if (!approvalActive) return;
11749
11778
  approvalActive = false;
11750
11779
  approvalCommandBlock = null;
@@ -11756,21 +11785,21 @@ function finishApproval(allow, timedOut = false) {
11756
11785
  const over = approvalOpenedOver;
11757
11786
  approvalOpenedOver = null;
11758
11787
  if (over && barPinned() && !scrolledBack() && over.height === viewportHeight()) {
11759
- setPad(blockClosedPad({ contentRows: over.content, pad: over.pad, height: over.height, blockRows: 2 }), over.content);
11788
+ setPad(blockClosedPad({ contentRows: over.content, pad: over.pad, height: over.height, blockRows: 3 }), over.content);
11760
11789
  }
11761
- // Settle the picker: overwrite the two option lines with a single result line.
11762
- process.stdout.write("\x1b[2A\x1b[J" + GUTTER + (allow ? accent("▸ Yes — running it") : red(timedOut ? "▸ No — no answer in time, skipped" : "▸ No — skipped")) + "\n");
11790
+ // Settle the picker: overwrite the three option lines with a single result line.
11791
+ process.stdout.write("\x1b[3A\x1b[J" + GUTTER + (allow ? accent("▸ Yes — running it") : red(timedOut ? "▸ No — no answer in time, skipped" : "▸ No — skipped")) + "\n");
11763
11792
  const r = approvalResolve;
11764
11793
  approvalResolve = null;
11765
- if (r) r(!!allow);
11794
+ if (r) r(allow && forProject ? "project" : !!allow);
11766
11795
  }
11767
11796
  function onApprovalKey(key) {
11768
11797
  if (!key) return;
11769
11798
  if (key.name === "up" || key.name === "down") {
11770
- approvalSel = key.name === "up" ? 0 : 1; // 2 options: up=Yes, down=No
11799
+ approvalSel = Math.min(2, Math.max(0, approvalSel + (key.name === "up" ? -1 : 1))); // Yes · this project · No
11771
11800
  drawApprovalOptions(true);
11772
11801
  } else if (key.name === "return" || key.name === "enter") {
11773
- finishApproval(approvalSel === 0);
11802
+ finishApproval(approvalSel !== 2, false, approvalSel === 1);
11774
11803
  } else if (key.ctrl && key.name === "o" && approvalCommandBlock && thoughtBlocks.includes(approvalCommandBlock)) {
11775
11804
  toggleThoughtBlock(approvalCommandBlock); // #204: expand/collapse the long command
11776
11805
  }
@@ -11946,36 +11975,37 @@ async function approvalPrompt(command) {
11946
11975
  printApprovalCommand(shown, { toggle: false }); // a list picker follows — shown whole, wrapped (#204)
11947
11976
  process.stdout.write(indentBlock(why, { indent: GUTTER, paint: dim }) + "\n");
11948
11977
  const idx = await pickFromList(
11949
- ["Yes", "Yes for all later ones (turns accept edits on)", "No"],
11978
+ ["Yes", "Yes for all later ones (turns accept edits on)", PROJECT_CHOICE, "No"],
11950
11979
  0,
11951
- { timeoutMs: COMMAND_APPROVAL_MS, timeoutIndex: 2 }
11980
+ { timeoutMs: COMMAND_APPROVAL_MS, timeoutIndex: 3 }
11952
11981
  );
11953
11982
  if (idx === 1 && editMode === "manual") {
11954
11983
  switchEditMode();
11955
11984
  process.stdout.write(dim(" (won't ask for later commands — shift+tab to go back to manual)\n"));
11956
11985
  }
11957
- return { allow: idx === 0 || idx === 1, dontAsk: false };
11986
+ if (idx === 2) rememberProject();
11987
+ return { allow: idx >= 0 && idx <= 2, dontAsk: false };
11958
11988
  }
11959
- // GH #215 — "Yes, always in this folder". ONLY for the soft "a destructive command" question
11960
- // (the reason text comes from _ws_command_risk in gonext_agent_chat.py). sudo, the denylist and
11961
- // deletes outside the project give a different reason, so they keep the plain Yes/No below.
11962
- if (process.stdin.isTTY && why.startsWith("a destructive command")) {
11963
- printApprovalCommand(shown, { toggle: false }); // a list picker follows — shown whole, wrapped
11989
+ // GH #515 — `source <file>`: a yes can be remembered for that file while it stays unchanged.
11990
+ const sourced = process.stdin.isTTY ? sourcedFileOf(why) : "";
11991
+ if (sourced) {
11992
+ printApprovalCommand(shown, { toggle: false });
11964
11993
  process.stdout.write(indentBlock(why, { indent: GUTTER, paint: dim }) + "\n");
11965
11994
  const idx = await pickFromList(
11966
- ["Yes", "Yes, always in this folder", "No"],
11995
+ ["Yes", "Yes, don't ask again for this file", PROJECT_CHOICE, "No"],
11967
11996
  0,
11968
- { timeoutMs: COMMAND_APPROVAL_MS, timeoutIndex: 2 }
11997
+ { timeoutMs: COMMAND_APPROVAL_MS, timeoutIndex: 3 }
11969
11998
  );
11999
+ if (idx === 2) rememberProject();
11970
12000
  if (idx === 1) {
11971
12001
  try {
11972
- commandAllowIn(resolve(process.cwd()), true);
11973
- process.stdout.write(dim(" (won't ask about destructive commands in this folder again — /command forget undoes it)\n"));
12002
+ commandAllowSource(resolve(process.cwd()), sourced);
12003
+ process.stdout.write(dim(" (won't ask about this file again unless it changes — /command forget undoes it)\n"));
11974
12004
  } catch (e) {
11975
12005
  process.stdout.write(yellow(` could not save that (${e?.message || e}) — allowed this once\n`));
11976
12006
  }
11977
12007
  }
11978
- return { allow: idx === 0 || idx === 1, dontAsk: false };
12008
+ return { allow: idx >= 0 && idx <= 2, dontAsk: false };
11979
12009
  }
11980
12010
  const allow = await new Promise((resolve) => {
11981
12011
  if (!process.stdin.isTTY) {
@@ -12002,7 +12032,22 @@ async function approvalPrompt(command) {
12002
12032
  orig(v);
12003
12033
  };
12004
12034
  });
12005
- return { allow, dontAsk: false };
12035
+ if (allow === "project") rememberProject();
12036
+ return { allow: Boolean(allow), dontAsk: false };
12037
+ }
12038
+ /** GH #515: no more command questions in this project — and say exactly what that covers. */
12039
+ function rememberProject() {
12040
+ try {
12041
+ commandAllowProject(resolve(process.cwd()));
12042
+ // They asked not to be asked: the manual-edits switch (which confirms every command) goes back on.
12043
+ if (editMode === "manual") switchEditMode();
12044
+ process.stdout.write(
12045
+ GUTTER + dim("No more command questions here — sudo and outside deletes included.") + "\n" +
12046
+ GUTTER + dim("/command forget undoes it.") + "\n"
12047
+ );
12048
+ } catch (e) {
12049
+ process.stdout.write(yellow(` could not save that (${e?.message || e}) — allowed this once\n`));
12050
+ }
12006
12051
  }
12007
12052
  // Generic arrow-key list picker (↑/↓ + Enter) — used by /server so you navigate instead
12008
12053
  // of typing a number. Same mechanism as the Yes/No approval picker above, generalized to
@@ -15867,12 +15912,14 @@ async function main() {
15867
15912
  }
15868
15913
  if (line === "/command forget" || line === "/command status") {
15869
15914
  const here = resolve(process.cwd());
15870
- if (line === "/command forget") commandAllowIn(here, false);
15915
+ if (line === "/command forget") commandForget(here);
15871
15916
  console.log("\n" + GUTTER + (line === "/command forget"
15872
- ? accent("✓ gu asks again before a destructive command in this folder.")
15873
- : (commandAllowedIn(here)
15874
- ? accent("Destructive commands run without asking in this folder.") + dim(" (/command forget undoes it)")
15875
- : dim("gu asks before a destructive command in this folder."))) + "\n");
15917
+ ? accent("✓ gu asks again before risky commands in this folder.")
15918
+ : commandProjectAllowed(here)
15919
+ ? accent("gu never asks before a command in this project.") + dim(" (/command forget undoes it)")
15920
+ : commandAllowedIn(here)
15921
+ ? accent("Destructive commands run without asking in this folder.") + dim(" (/command forget undoes it)")
15922
+ : dim("gu asks before risky commands in this folder.")) + "\n");
15876
15923
  paintBar();
15877
15924
  continue;
15878
15925
  }
package/image-paste.mjs CHANGED
@@ -3,8 +3,9 @@ import { readFileSync } from "node:fs";
3
3
  * Pasting an image into the gu input (task #284).
4
4
  *
5
5
  * The image goes to the CODING model, the way Claude Code does it — no OCR step: the model sees
6
- * the screenshot itself. For now only a Claude coder (api.anthropic.com) may receive one; with
7
- * any other coder a paste is refused and the bar says to pick a Claude model.
6
+ * the screenshot itself. Only a coder that takes images may receive one (coderTakesImagesFor: Claude,
7
+ * Kimi K3, and since GH #528 every model the cloud list marks images:true); with any other coder a
8
+ * paste is refused and the bar says to pick another model.
8
9
  *
9
10
  * How it reaches the model. The API passes the message TEXT and nothing else, so the image rides
10
11
  * in the text as a marker: the input shows "[Image #1]" (like "[Pasted text #1]"), and the line
@@ -21,7 +22,7 @@ import { readFileSync } from "node:fs";
21
22
  * most reliable way; Windows Terminal quotes a path with spaces.
22
23
  */
23
24
  import { spawnSync } from "node:child_process";
24
- import { chmodSync, closeSync, copyFileSync, existsSync, mkdirSync, openSync, readSync, rmSync, statSync } from "node:fs";
25
+ import { chmodSync, closeSync, copyFileSync, existsSync, mkdirSync, openSync, readSync, rmSync, statSync, writeFileSync } from "node:fs";
25
26
  import { homedir } from "node:os";
26
27
  import path, { join } from "node:path";
27
28
 
@@ -72,8 +73,42 @@ export const imagesDir = (home = homedir()) => join(home, ".gonext", "images");
72
73
  */
73
74
  export const IMAGE_CODERS = JSON.parse(readFileSync(new URL("./image-capable-coders.json", import.meta.url), "utf8")).coders;
74
75
 
76
+ /**
77
+ * GH #528: THE CLOUD MODEL LIST. Rows of GET /api/model-limits with `images: true` (filled from the
78
+ * providers' catalogs on the admin Models page) — the owner chose to trust the catalog. A row names
79
+ * one model on one server exactly. Pure.
80
+ */
81
+ export function cloudImageCoders(rows) {
82
+ const out = [];
83
+ for (const r of Array.isArray(rows) ? rows : []) {
84
+ if (!r || r.images !== true || r.origin === "table") continue;
85
+ const host = String(r.host ?? "").trim().toLowerCase();
86
+ const exact = String(r.model ?? "").trim().toLowerCase();
87
+ if (host && exact) out.push({ host, exact });
88
+ }
89
+ return out;
90
+ }
91
+
92
+ /**
93
+ * The cloud list this gu last read, kept in ~/.gonext/image-models.json so a start without network
94
+ * still knows it — and so the agent (gonext_agent_chat.py) reads the very same list.
95
+ */
96
+ export const imageModelsFile = (home = homedir()) => join(home, ".gonext", "image-models.json");
97
+ let cloudCoders = [];
98
+ export function setCloudImageCoders(list) {
99
+ cloudCoders = Array.isArray(list) ? list.filter((c) => c && c.host && c.exact) : [];
100
+ }
101
+ export function loadCloudImageCoders(home = homedir()) {
102
+ try {
103
+ setCloudImageCoders(JSON.parse(readFileSync(imageModelsFile(home), "utf8")).coders);
104
+ } catch {
105
+ setCloudImageCoders([]);
106
+ }
107
+ return cloudCoders;
108
+ }
109
+
75
110
  /** May a pasted image be sent to this coder? `model` may be a qualified id ("openai::kimi-k3"). */
76
- export function coderTakesImagesFor(url, model = "", coders = IMAGE_CODERS) {
111
+ export function coderTakesImagesFor(url, model = "", coders = [...IMAGE_CODERS, ...cloudCoders]) {
77
112
  let host = "";
78
113
  try {
79
114
  host = new URL(String(url ?? "")).hostname.toLowerCase().replace(/\.$/, "");
@@ -81,7 +116,22 @@ export function coderTakesImagesFor(url, model = "", coders = IMAGE_CODERS) {
81
116
  return false;
82
117
  }
83
118
  const name = String(model ?? "").split("::").pop().trim();
84
- return coders.some((c) => c.host === host && (!c.model || new RegExp(c.model, "i").test(name)));
119
+ return coders.some(
120
+ (c) => c.host === host && (c.exact ? c.exact === name.toLowerCase() : !c.model || new RegExp(c.model, "i").test(name))
121
+ );
122
+ }
123
+
124
+ /** Save the cloud list for the next start and for the agent. Best effort; → the coders saved. */
125
+ export function saveCloudImageCoders(rows, home = homedir()) {
126
+ const coders = cloudImageCoders(rows);
127
+ try {
128
+ mkdirSync(join(home, ".gonext"), { recursive: true });
129
+ writeFileSync(imageModelsFile(home), JSON.stringify({ savedAt: new Date().toISOString(), coders }, null, 1) + "\n");
130
+ } catch {
131
+ /* not saved: this session still uses it */
132
+ }
133
+ setCloudImageCoders(coders);
134
+ return coders;
85
135
  }
86
136
 
87
137
  /** Is this coding server Claude's own API? (Kept for callers that ask exactly that.) */
@@ -93,11 +143,12 @@ export function isClaudeCoderUrl(url) {
93
143
  }
94
144
  }
95
145
 
96
- // The name is historical (#284 was Claude-only); since #316 Kimi K3 takes images too.
146
+ // The name is historical (#284 was Claude-only). Since GH #528 every model the cloud list says takes
147
+ // images does (Claude, Kimi, Gemini, Qwen…), so the notice names no model.
97
148
  export const IMAGE_NEEDS_CLAUDE =
98
- "image paste needs a coding model that takes images (Claude, or Kimi K3) — pick one with /model";
149
+ "this coding model does not take images — pick one that does with /model";
99
150
  /** The same, for a window too narrow for the full sentence: the fix (/model) must survive. */
100
- export const IMAGE_NEEDS_CLAUDE_SHORT = "images need Claude or Kimi K3 — /model";
151
+ export const IMAGE_NEEDS_CLAUDE_SHORT = "model takes no images — /model";
101
152
 
102
153
  /**
103
154
  * The notice as it fits `cols` columns (#54): the full sentence, else its short form, else the
@@ -18,7 +18,7 @@
18
18
  *
19
19
  * PURE. Everything here is strings in, strings out, so the whole table is a test.
20
20
  */
21
- import { hostLocality } from "./coding-provider-setup.mjs";
21
+ import { hostLocality, isKeylessHost } from "./coding-provider-setup.mjs";
22
22
 
23
23
  /**
24
24
  * What an Esc-aware prompt resolves to when Esc is pressed. A string no one can type (it starts
@@ -67,7 +67,7 @@ export function createHinter() {
67
67
  */
68
68
  export function shouldAskKey({ typed, host }) {
69
69
  if (!String(typed ?? "").trim()) return false;
70
- return hostLocality(host) === "public";
70
+ return hostLocality(host) === "public" && !isKeylessHost(host);
71
71
  }
72
72
 
73
73
  /** The server refused to list its models without credentials. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiens.nguyen/gu-cli",
3
- "version": "1.0.925",
3
+ "version": "1.0.929",
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",