@tiens.nguyen/gu-cli 1.0.912 → 1.0.914

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/free-model.mjs CHANGED
@@ -51,15 +51,63 @@ const sameServer = (a, b) => {
51
51
  };
52
52
 
53
53
  /** Is this coder URL the free model's? */
54
- export const isFreeServer = (state, url) => Boolean(state?.url) && sameServer(state.url, url);
54
+ export const isFreeServer = (state, url) =>
55
+ Boolean(state?.url) && (sameServer(state.url, url) || (Array.isArray(state.urls) && state.urls.some((u) => sameServer(u, url))));
55
56
 
56
57
  /** The state as of `now`: a new month starts at zero spent. */
57
58
  export function current(state, now = new Date()) {
58
59
  if (!state) return null;
59
60
  const p = periodKey(now);
60
- return state.period === p ? state : { ...state, period: p, spentMicro: 0 };
61
+ if (state.period === p) return state;
62
+ const providers = Object.fromEntries(Object.entries(state.providers ?? {}).map(([u, v]) => [u, { ...v, spentMicro: 0 }]));
63
+ return { ...state, period: p, spentMicro: 0, providers };
61
64
  }
62
65
 
66
+ /**
67
+ * Which allowance a turn on `url` draws from (GH #445): an extra provider's own, or the primary's. The state is
68
+ * `current()` already. → { extra: url | null, label, allowanceMicro, spentMicro }
69
+ */
70
+ export function slotFor(state, url) {
71
+ const key = Object.keys(state?.providers ?? {}).find((u) => sameServer(u, url));
72
+ if (key) {
73
+ const v = state.providers[key];
74
+ return { extra: key, label: v.label || safeHost(key), allowanceMicro: whole(v.allowanceMicro), spentMicro: whole(v.spentMicro) };
75
+ }
76
+ return { extra: null, label: "", allowanceMicro: whole(state?.allowanceMicro), spentMicro: whole(state?.spentMicro) };
77
+ }
78
+
79
+ const safeHost = (u) => {
80
+ try {
81
+ return new URL(u).hostname;
82
+ } catch {
83
+ return String(u);
84
+ }
85
+ };
86
+
87
+ /**
88
+ * Every provider of a preset, the primary first (GH #444): [{ baseUrl, apiKey, keyId, models: [{ id, price }] }].
89
+ * An older server sends only the primary.
90
+ */
91
+ export function presetProviders(preset) {
92
+ const extras = Array.isArray(preset?.extraProviders) ? preset.extraProviders.filter((p) => p && typeof p.baseUrl === "string") : [];
93
+ return [
94
+ { baseUrl: preset.baseUrl, apiKey: preset.apiKey || "", keyId: preset.keyId, models: presetModels(preset) },
95
+ ...extras.map((p) => ({
96
+ baseUrl: p.baseUrl,
97
+ // "" = this provider's allowance is used up: the service does not hand out its key (nothing to add or change)
98
+ apiKey: p.apiKey || "",
99
+ keyId: p.keyId,
100
+ label: p.label || "",
101
+ allowanceMicro: whole(p.allowanceMicro),
102
+ spentMicro: whole(p.spentMicro),
103
+ models: presetModels({ model: p.models?.[0]?.id, price: p.models?.[0]?.price, models: p.models }),
104
+ })),
105
+ ];
106
+ }
107
+
108
+ /** Did the service hand out the primary provider's key? (Not when ITS allowance is used up.) */
109
+ export const hasPrimaryKey = (preset) => Boolean(preset?.apiKey);
110
+
63
111
  /** The models the preset offers: [{ id, price }], default first. An older server sends just `model` + `price`. */
64
112
  export function presetModels(preset) {
65
113
  const list = Array.isArray(preset?.models) ? preset.models.filter((m) => m && typeof m.id === "string" && m.id) : [];
@@ -70,6 +118,10 @@ export function presetModels(preset) {
70
118
  * The price a turn on `model` is charged at: that model's own, else the DEAREST of the list — a model the
71
119
  * server did not list is never charged as free or cheap.
72
120
  */
121
+ export function allPresetModels(preset) {
122
+ return presetProviders(preset).flatMap((p) => p.models);
123
+ }
124
+
73
125
  export function priceForModel(state, model) {
74
126
  const m = state?.models ?? {};
75
127
  if (model && m[model]) return m[model];
@@ -82,10 +134,15 @@ export function priceForModel(state, model) {
82
134
  }
83
135
 
84
136
  /** After a turn on the free model (on `model`, one of its list): the new state. */
85
- export function addTurn(state, usage, now = new Date(), model = "") {
137
+ export function addTurn(state, usage, now = new Date(), model = "", url = "") {
86
138
  const s = current(state, now);
87
139
  if (!s) return null;
88
- return { ...s, spentMicro: whole(s.spentMicro) + turnCostMicro(usage, priceForModel(s, model)) };
140
+ const cost = turnCostMicro(usage, priceForModel(s, model));
141
+ const slot = url ? slotFor(s, url) : null;
142
+ if (slot?.extra) {
143
+ return { ...s, providers: { ...s.providers, [slot.extra]: { ...s.providers[slot.extra], spentMicro: slot.spentMicro + cost } } };
144
+ }
145
+ return { ...s, spentMicro: whole(s.spentMicro) + cost };
89
146
  }
90
147
 
91
148
  /** After the service answered the preset: what gu keeps (never the key itself). */
@@ -97,7 +154,18 @@ export function stateFromPreset(preset, prev, now = new Date()) {
97
154
  model: preset.model,
98
155
  keyId: preset.keyId,
99
156
  price: preset.price,
100
- models: Object.fromEntries(presetModels(preset).map((m) => [m.id, m.price])),
157
+ models: Object.fromEntries(allPresetModels(preset).map((m) => [m.id, m.price])),
158
+ // Every provider's endpoint: a turn on any of them is the free model's (#444).
159
+ urls: presetProviders(preset).map((p) => p.baseUrl),
160
+ // Each provider's key fingerprint, so a rotated key on any of them is noticed.
161
+ keyIds: Object.fromEntries(presetProviders(preset).map((p) => [p.baseUrl, p.keyId])),
162
+ // Each extra provider's OWN allowance and spend (#445): the higher of ours and the service's, like the primary's.
163
+ providers: Object.fromEntries(
164
+ presetProviders(preset).slice(1).map((p) => {
165
+ const before = prev && prev.period === periodKey(now) ? whole(prev.providers?.[p.baseUrl]?.spentMicro) : 0;
166
+ return [p.baseUrl, { label: p.label, allowanceMicro: p.allowanceMicro, spentMicro: Math.max(before, p.spentMicro) }];
167
+ })
168
+ ),
101
169
  period: p,
102
170
  allowanceMicro: whole(preset.allowanceMicro),
103
171
  // The higher of ours and the service's: a reinstall cannot reset it, another computer's use counts.
@@ -110,26 +178,31 @@ const usd = (micro) => `$${(whole(micro) / 1e6).toFixed(2)}`;
110
178
  /**
111
179
  * The line to show, or null. `over` is the refusal itself; warn/low are shown once per level.
112
180
  */
113
- export function notice(state, now = new Date()) {
181
+ export function notice(state, now = new Date(), url = "") {
114
182
  const s = current(state, now);
115
- if (!s || !s.allowanceMicro) return null;
116
- const level = levelFor(s.spentMicro, s.allowanceMicro);
117
- const pct = Math.min(100, Math.floor((100 * whole(s.spentMicro)) / s.allowanceMicro));
183
+ if (!s) return null;
184
+ const slot = slotFor(s, url);
185
+ if (!slot.allowanceMicro) return null;
186
+ const level = levelFor(slot.spentMicro, slot.allowanceMicro);
187
+ const pct = Math.min(100, Math.floor((100 * slot.spentMicro) / slot.allowanceMicro));
188
+ const name = slot.extra ? slot.label : "free model";
189
+ const Name = slot.extra ? slot.label : "Free model";
118
190
  if (level === "over") {
119
- return { level, text: `Your free model allowance for this month (${usd(s.allowanceMicro)}) is used up. Add your own model key with /model — or a local one with Ollama — to keep going; it renews on the 1st.` };
191
+ const other = slot.extra ? " — or another free model with /model —" : "";
192
+ return { level, text: `Your ${name} allowance for this month (${usd(slot.allowanceMicro)}) is used up. Add your own model key with /model${other} — or a local one with Ollama — to keep going; it renews on the 1st.` };
120
193
  }
121
- if (level === "low") return { level, text: `Free model: ${pct}% of this month's ${usd(s.allowanceMicro)} used — almost gone. Add your own key with /model before it ends.` };
122
- if (level === "warn") return { level, text: `Free model: ${pct}% of this month's ${usd(s.allowanceMicro)} used.` };
194
+ if (level === "low") return { level, text: `${Name}: ${pct}% of this month's ${usd(slot.allowanceMicro)} used — almost gone. Add your own key with /model before it ends.` };
195
+ if (level === "warn") return { level, text: `${Name}: ${pct}% of this month's ${usd(slot.allowanceMicro)} used.` };
123
196
  return { level, text: null };
124
197
  }
125
198
 
126
199
  /**
127
200
  * Is a NEW turn on this coder refused? Only at the START of a turn — never mid-turn — and only when
128
- * the coder IS the free model. → the sentence, or null.
201
+ * the coder IS the free model (any provider; each has its own allowance). → the sentence, or null.
129
202
  */
130
203
  export function blockReason(state, coderUrl, now = new Date()) {
131
204
  if (!isFreeServer(state, coderUrl)) return null;
132
- const n = notice(state, now);
205
+ const n = notice(state, now, coderUrl);
133
206
  return n?.level === "over" ? n.text : null;
134
207
  }
135
208
 
@@ -175,7 +248,8 @@ export async function fetchPreset({ hostedBase, token, fetchImpl = fetch, timeou
175
248
  const r = await call(fetchImpl, `${String(hostedBase).replace(/\/+$/, "")}/api/billing/cli-token/model-preset`, {
176
249
  headers: { Authorization: `Bearer ${String(token).trim()}` },
177
250
  }, timeoutMs);
178
- if (r.ok && typeof r.body.baseUrl === "string" && typeof r.body.apiKey === "string" && r.body.apiKey) {
251
+ // The primary's key is "" when ITS allowance is used up but another provider's is not (GH #445): still a preset.
252
+ if (r.ok && typeof r.body.baseUrl === "string" && typeof r.body.apiKey === "string" && (r.body.apiKey || r.body.over === true)) {
179
253
  return { ok: true, preset: r.body };
180
254
  }
181
255
  if (r.status === 0) return { ok: false, why: "offline", error: "could not reach the gu service." };
@@ -189,7 +263,11 @@ export async function reportSpend({ hostedBase, token, state, fetchImpl = fetch,
189
263
  const r = await call(fetchImpl, `${String(hostedBase).replace(/\/+$/, "")}/api/billing/cli-token/model-usage`, {
190
264
  method: "POST",
191
265
  headers: { Authorization: `Bearer ${String(token).trim()}`, "Content-Type": "application/json" },
192
- body: JSON.stringify({ period: state.period, spentMicro: whole(state.spentMicro) }),
266
+ body: JSON.stringify({
267
+ period: state.period,
268
+ spentMicro: whole(state.spentMicro),
269
+ extras: Object.entries(state.providers ?? {}).map(([baseUrl, v]) => ({ baseUrl, spentMicro: whole(v.spentMicro) })),
270
+ }),
193
271
  }, timeoutMs);
194
272
  return r.ok && Number.isFinite(Number(r.body.spentMicro)) ? Number(r.body.spentMicro) : null;
195
273
  }
@@ -202,6 +280,17 @@ export async function reportSpend({ hostedBase, token, state, fetchImpl = fetch,
202
280
  * → { ok: true, rowId, keyAdded } | { ok: false, why }
203
281
  */
204
282
  export async function applyPreset(preset, api, { rotateOnly = false } = {}) {
283
+ // The primary's allowance is used up (its key withheld): nothing to add or switch for it; the other providers still apply.
284
+ if (!preset.apiKey) {
285
+ let added = false;
286
+ for (const p of presetProviders(preset).slice(1)) {
287
+ if (!p.apiKey) continue;
288
+ const r = await applyExtraProvider(p, api);
289
+ if (!r.ok) return r;
290
+ added = added || r.keyAdded;
291
+ }
292
+ return { ok: true, rowId: "", keyAdded: added };
293
+ }
205
294
  const settings = await api.settings();
206
295
  if (!settings) return { ok: false, why: "couldn't read this account's settings from the local API" };
207
296
  const rows = Array.isArray(settings.agentCodingBackends) ? settings.agentCodingBackends : [];
@@ -247,5 +336,45 @@ export async function applyPreset(preset, api, { rotateOnly = false } = {}) {
247
336
  keyAdded = true;
248
337
  }
249
338
  if (!(await api.setDefaultKey(row.id, keyId))) return { ok: false, why: "couldn't make the key that server's default" };
339
+ // The other providers (#444): a server row and a key each. They never change the coder or the agent model.
340
+ for (const extraProvider of presetProviders(preset).slice(1)) {
341
+ if (!extraProvider.apiKey) continue; // that provider's allowance is used up
342
+ const r = await applyExtraProvider(extraProvider, api);
343
+ if (!r.ok) return r;
344
+ keyAdded = keyAdded || r.keyAdded;
345
+ }
250
346
  return { ok: true, rowId: row.id, keyAdded };
251
347
  }
348
+
349
+ async function applyExtraProvider(p, api) {
350
+ const ids = p.models.map((m) => m.id);
351
+ const settings = await api.settings();
352
+ if (!settings) return { ok: false, why: "couldn't read this account's settings from the local API" };
353
+ const rows = Array.isArray(settings.agentCodingBackends) ? settings.agentCodingBackends : [];
354
+ const mine = rows.find((r) => r && sameServer(r.url, p.baseUrl));
355
+ if (!mine) {
356
+ const next = [...rows, { kind: "openai", url: p.baseUrl, defaultModel: ids[0], models: ids.slice(1), enabled: true }];
357
+ if (!(await api.saveSettings({ agentCodingBackends: next }))) return { ok: false, why: "the local API refused the settings" };
358
+ } else {
359
+ const def = mine.defaultModel || ids[0];
360
+ const list = [...new Set([...(mine.models ?? []), ...ids])].filter((m) => m !== def);
361
+ if (JSON.stringify([...list].sort()) !== JSON.stringify([...(mine.models ?? [])].sort())) {
362
+ const next = rows.map((r) => (r === mine ? { ...r, models: list, enabled: true } : r));
363
+ if (!(await api.saveSettings({ agentCodingBackends: next }))) return { ok: false, why: "the local API refused the settings" };
364
+ }
365
+ }
366
+ const fresh = (await api.settings()) ?? {};
367
+ const row = (fresh.agentCodingBackends ?? []).find((r) => r && sameServer(r.url, p.baseUrl));
368
+ if (!row?.id) return { ok: false, why: "the server row was not saved" };
369
+ const keys = (await api.keys()) ?? [];
370
+ const named = keys.find((k) => k?.backendId === row.id && k?.name === `${FREE_KEY_NAME} ${p.keyId}`);
371
+ let keyId = named?.id ?? "";
372
+ let keyAdded = false;
373
+ if (!keyId) {
374
+ keyId = await api.addKey(`${FREE_KEY_NAME} ${p.keyId}`, p.apiKey, row.id);
375
+ if (!keyId) return { ok: false, why: "the local API refused the key" };
376
+ keyAdded = true;
377
+ }
378
+ if (!(await api.setDefaultKey(row.id, keyId))) return { ok: false, why: "couldn't make the key that server's default" };
379
+ return { ok: true, keyAdded };
380
+ }
@@ -722,6 +722,79 @@ def _bk_ddg_html(q, timeout=6):
722
722
  return out
723
723
 
724
724
 
725
+ # GH #455: DuckDuckGo's HTML endpoint answers 200 with ZERO results once a few searches arrive in a
726
+ # row (measured: results 1-3 fine, 4-6 empty). A second keyless engine (Bing) answered 6 of 6 in the
727
+ # same test, and an engine that returned nothing is left alone for a while instead of being hit again.
728
+ _ENGINE_COOL: dict = {} # engine name -> time.time() until which it is skipped
729
+ _ENGINE_COOL_SECS = 180
730
+
731
+
732
+ def _engine_cooling(name):
733
+ import time as _t
734
+ return _ENGINE_COOL.get(name, 0) > _t.time()
735
+
736
+
737
+ def _engine_cool(name, secs=None):
738
+ import time as _t
739
+ _ENGINE_COOL[name] = _t.time() + (secs or _ENGINE_COOL_SECS)
740
+ _log(f"web_search: {name} returned no results; skipping it for {secs or _ENGINE_COOL_SECS}s")
741
+
742
+
743
+ def _bing_real_url(href):
744
+ """Bing wraps every result link as bing.com/ck/a?...&u=a1<base64url>; unwrap to the real URL."""
745
+ import base64
746
+ import html as _html
747
+ from urllib.parse import urlsplit, parse_qs
748
+ href = _html.unescape(href or "")
749
+ if "bing.com/ck/a" not in href:
750
+ return href
751
+ u = (parse_qs(urlsplit(href).query).get("u") or [""])[0]
752
+ if u.startswith("a1"):
753
+ t = u[2:]
754
+ try:
755
+ return base64.urlsafe_b64decode(t + "=" * (-len(t) % 4)).decode("utf-8", "replace")
756
+ except Exception: # noqa: BLE001
757
+ return ""
758
+ return ""
759
+
760
+
761
+ _SEARCH_STOP = frozenset("a an and are as at be by do does for from how in is it of on or the to what when where which who why with".split())
762
+
763
+
764
+ def _result_relevant(r, query):
765
+ """Bing (and DDG) sometimes answer a scripted request with unrelated pages (measured: 'nextjs 15 caching
766
+ behaviour' → zhihu.com, 'postgres 17 vacuum settings' → baidu). People put the subject first, so a result
767
+ is kept only if the query's first meaningful word (not a stop word, not a bare version number) appears in
768
+ its title, snippet or URL. Measured on 8 queries: 6 kept every good page, the 2 junk answers were dropped."""
769
+ toks = [t for t in re.findall(r"[a-z0-9.#+]+", (query or "").lower())
770
+ if t not in _SEARCH_STOP and len(t) > 1 and not re.fullmatch(r"[\d.]+", t)]
771
+ if not toks:
772
+ return True
773
+ return toks[0] in f"{r.get('title','')} {r.get('snippet','')} {r.get('url','')}".lower()
774
+
775
+
776
+ def _bk_bing_html(q, timeout=6):
777
+ """Bing HTML results → [{title,snippet,url}] (keyless). One <li class="b_algo"> per result."""
778
+ from urllib.parse import quote
779
+ body = _get_text(f"https://www.bing.com/search?q={quote(q)}&setlang=en", timeout=timeout)
780
+ if not body:
781
+ return []
782
+ out = []
783
+ for blk in re.findall(r'<li class="b_algo"[^>]*>.*?</li>', body, re.S):
784
+ blk = re.sub(r"<link[^>]*>", "", blk)
785
+ h = re.search(r'<h2[^>]*>\s*<a[^>]*href="([^"]*)"[^>]*>(.*?)</a>', blk, re.S)
786
+ if not h:
787
+ continue
788
+ real = _bing_real_url(h.group(1))
789
+ title = _search_strip(h.group(2))
790
+ if not real.startswith("http") or not title:
791
+ continue
792
+ sm = (re.search(r'<p[^>]*class="[^"]*b_lineclamp[^"]*"[^>]*>(.*?)</p>', blk, re.S)
793
+ or re.search(r'<div class="b_caption[^"]*"[^>]*>.*?<p[^>]*>(.*?)</p>', blk, re.S))
794
+ out.append({"title": title[:120], "snippet": _search_strip(sm.group(1)) if sm else "", "url": real})
795
+ return out
796
+
797
+
725
798
  def _bk_searxng(q, base, timeout=6):
726
799
  """Self-hosted SearXNG JSON API → {results:[{title,snippet,url}], answers:[str]} (keyless).
727
800
 
@@ -960,7 +1033,11 @@ def _web_search_impl(query, max_results=5, searxng_url="",
960
1033
  overall = 5 # overall deadline; a straggler is abandoned (shutdown is non-blocking)
961
1034
 
962
1035
  # Result-producing backends (run in parallel). Order = tie-break priority in the merge.
963
- tasks = [("ddg", lambda: _bk_ddg_html(q, per_timeout))]
1036
+ tasks = []
1037
+ if not _engine_cooling("ddg"):
1038
+ tasks.append(("ddg", lambda: _bk_ddg_html(q, per_timeout)))
1039
+ if not _engine_cooling("bing"):
1040
+ tasks.append(("bing", lambda: _bk_bing_html(q, per_timeout)))
964
1041
  if searxng:
965
1042
  # SearXNG aggregates Wikipedia (and everything else) server-side, so the standalone
966
1043
  # Wikipedia backend is redundant here — and its full-text API is the slow straggler
@@ -996,23 +1073,30 @@ def _web_search_impl(query, max_results=5, searxng_url="",
996
1073
  results_by[name] = r
997
1074
  finally:
998
1075
  ex.shutdown(wait=False, cancel_futures=True)
1076
+ for _eng in ("ddg", "bing"): # asked and got nothing → leave it alone for a while (GH #455)
1077
+ if _eng in results_by and not results_by[_eng]:
1078
+ _engine_cool(_eng)
999
1079
 
1000
1080
  # Merge + dedupe by normalized URL; rank by cross-engine AGREEMENT then first-seen order.
1001
1081
  merged = {}
1002
1082
  order = 0
1003
- for name in ("searxng", "ddg", "wikipedia"):
1004
- for r in results_by.get(name, []):
1083
+ for name in ("searxng", "ddg", "bing", "wikipedia"):
1084
+ rs = results_by.get(name, [])
1085
+ if name in ("ddg", "bing"):
1086
+ rs = [r for r in rs if _result_relevant(r, q)]
1087
+ for r in rs:
1005
1088
  nu = _norm_url(r.get("url"))
1006
1089
  if not nu:
1007
1090
  continue
1008
1091
  if nu in merged:
1009
- merged[nu]["hits"] += 1
1092
+ if name != "wikipedia": # GH #455: the encyclopedia must not outrank real web hits
1093
+ merged[nu]["hits"] += 1
1010
1094
  if not merged[nu]["snippet"] and r.get("snippet"):
1011
1095
  merged[nu]["snippet"] = r["snippet"]
1012
1096
  else:
1013
1097
  merged[nu] = {
1014
1098
  "title": r.get("title") or r["url"], "snippet": r.get("snippet", ""),
1015
- "url": r["url"], "hits": 1, "order": order,
1099
+ "url": r["url"], "hits": 0 if name == "wikipedia" else 1, "order": order,
1016
1100
  }
1017
1101
  order += 1
1018
1102
  ranked = sorted(merged.values(), key=lambda e: (-e["hits"], e["order"]))[:max_results]
@@ -1024,7 +1108,8 @@ def _web_search_impl(query, max_results=5, searxng_url="",
1024
1108
  "web_search backends → "
1025
1109
  f"searxng={'on' if searxng else 'off'}"
1026
1110
  + (f"({len(results_by.get('searxng', []))})" if searxng else "")
1027
- + f" ddg({len(results_by.get('ddg', []))})"
1111
+ + f" ddg({len(results_by.get('ddg', []))}{'*' if _engine_cooling('ddg') else ''})"
1112
+ + f" bing({len(results_by.get('bing', []))}{'*' if _engine_cooling('bing') else ''})"
1028
1113
  + (f" wikipedia({len(results_by.get('wikipedia', []))})" if not searxng else "")
1029
1114
  + f" answers({len(answers)}) → {len(ranked)} ranked"
1030
1115
  + (f" [searxng={searxng}]" if searxng else "")
@@ -1050,6 +1135,12 @@ def _web_search_impl(query, max_results=5, searxng_url="",
1050
1135
  page_texts = _read_pages(ranked[:read_k], q, page_chars) if (read_on and ranked) else {}
1051
1136
 
1052
1137
  parts = []
1138
+ # GH #455: every web engine came back empty and only the encyclopedia matched. Say so — those
1139
+ # pages are matches on the words, not an answer, and the model must not present them as one.
1140
+ if ranked and not answers and all(e["hits"] == 0 for e in ranked):
1141
+ parts.append("Note: the web search engines returned nothing for this query (they may be rate "
1142
+ "limiting). The pages below are Wikipedia matches only and may not answer it. "
1143
+ "Say that, or try again with different words.")
1053
1144
  # Answer box(es) first — a direct answer often needs no page read at all.
1054
1145
  answer_lines = [f"• {a[:600]}" for a in answers[:3]]
1055
1146
  if summary:
package/gu-repl.mjs CHANGED
@@ -8925,9 +8925,12 @@ async function setUpFreeModel({ token, announce = false } = {}) {
8925
8925
  return false;
8926
8926
  }
8927
8927
  const first = !freeModel || freeModel.url !== got.preset.baseUrl;
8928
- const keyChanged = !first && freeModel.keyId !== got.preset.keyId;
8929
- // The owner added or removed a model: the server row's list follows (what the person is on stays).
8930
- const ids = (p) => fm.presetModels(p).map((m) => m.id).join(",");
8928
+ // A rotated key on ANY provider (the primary's, or an extra one's) counts (GH #444).
8929
+ const keysNow = JSON.stringify(Object.fromEntries(fm.presetProviders(got.preset).map((p) => [p.baseUrl, p.keyId])));
8930
+ const keysThen = JSON.stringify(freeModel?.keyIds ?? Object.fromEntries([[freeModel?.url, freeModel?.keyId]]));
8931
+ const keyChanged = !first && keysNow !== keysThen;
8932
+ // The owner added or removed a model or a provider: the server rows' lists follow (what the person is on stays).
8933
+ const ids = (p) => fm.allPresetModels(p).map((m) => m.id).join(",");
8931
8934
  const listChanged = !first && !keyChanged && Object.keys(freeModel.models ?? {}).join(",") !== ids(got.preset);
8932
8935
  if (!first && !keyChanged && !listChanged) {
8933
8936
  freeModel = fm.stateFromPreset(got.preset, freeModel);
@@ -8941,7 +8944,7 @@ async function setUpFreeModel({ token, announce = false } = {}) {
8941
8944
  }
8942
8945
  freeModel = fm.stateFromPreset(got.preset, freeModel);
8943
8946
  fm.writeState(freeModelDir(), freeModel);
8944
- if (first) {
8947
+ if (first && fm.hasPrimaryKey(got.preset)) {
8945
8948
  await refreshAfterPresetApply(null, { model: got.preset.model, url: got.preset.baseUrl }, { coder: true });
8946
8949
  console.log(GUTTER + accent(`✓ ${got.preset.model} is now your agent model and your coding model.`) +
8947
8950
  dim(" Free use renews each month; /model switches back to your own."));
@@ -8974,11 +8977,12 @@ async function noteFreeModelTurn(inputTokens, breakdown, outputTokens, coder) {
8974
8977
  const fm = await import("./free-model.mjs");
8975
8978
  if (!freeModel || !fm.isFreeServer(freeModel, coder?.url) || !(inputTokens > 0)) return;
8976
8979
  const cache = readTurnCache(breakdown) ?? { cached: 0, cacheReported: false };
8977
- freeModel = fm.addTurn(freeModel, { input: inputTokens, cached: cache.cached, cacheReported: cache.cacheReported, output: outputTokens ?? 0 }, new Date(), coder?.model);
8980
+ freeModel = fm.addTurn(freeModel, { input: inputTokens, cached: cache.cached, cacheReported: cache.cacheReported, output: outputTokens ?? 0 }, new Date(), coder?.model, coder?.url);
8978
8981
  fm.writeState(freeModelDir(), freeModel);
8979
- const n = fm.notice(freeModel);
8980
- if (n?.text && freeModelNoticed !== `${freeModel.period}:${n.level}`) {
8981
- freeModelNoticed = `${freeModel.period}:${n.level}`;
8982
+ const n = fm.notice(freeModel, new Date(), coder?.url);
8983
+ const noticeKey = `${freeModel.period}:${fm.slotFor(freeModel, coder?.url).extra ?? "main"}:${n?.level}`;
8984
+ if (n?.text && freeModelNoticed !== noticeKey) {
8985
+ freeModelNoticed = noticeKey;
8982
8986
  console.log(GUTTER + (n.level === "ok" ? dim(n.text) : yellow(n.text)) + "\n");
8983
8987
  }
8984
8988
  const ct = await import("./cli-token.mjs");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiens.nguyen/gu-cli",
3
- "version": "1.0.912",
3
+ "version": "1.0.914",
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",