@tiens.nguyen/gu-cli 1.0.918 → 1.0.920

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/cli-token.mjs CHANGED
@@ -29,7 +29,7 @@
29
29
  import { createHash, createPublicKey, verify } from "node:crypto";
30
30
  import { execFile } from "node:child_process";
31
31
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
32
- import { hostname as osHostname } from "node:os";
32
+ import { hostname as osHostname, userInfo } from "node:os";
33
33
  import { dirname, join } from "node:path";
34
34
 
35
35
  /** The public half of the API's CLI_TOKEN_PRIVATE_KEY, base64 SPKI DER (Ed25519). Generated 2026-09-17. */
@@ -296,6 +296,10 @@ export async function promptForToken({
296
296
  // #250: "/support" (typed, or the footer's "? support" link) sends a help request from here —
297
297
  // a first install with no token had no other way to reach support. Runs, then asks again.
298
298
  onSupport = null,
299
+ // A free-model PROMO code typed in the same row (no token, no Pro): `redeemPromo(code)` → the voucher answer.
300
+ // With `promoFirst` (the person chose "Free model" at the start) the row asks for the code, and says nothing of Pro.
301
+ redeemPromo = null,
302
+ promoFirst = false,
299
303
  }) {
300
304
  const quitLine = (lead) => lead + (onSupport ? "/support asks for help · " : "") + "/exit or Ctrl+C quits gu.";
301
305
  const accountUrl = `${String(site).replace(/^https?:\/\//, "")}/account`;
@@ -354,16 +358,25 @@ export async function promptForToken({
354
358
  details = [...(why ? [why] : []), ...hint.filter((l) => !why || l !== why)];
355
359
  hint = [];
356
360
  }
361
+ // The person chose "Free model": ask for the code, and do not send them to buy Pro or make an account.
362
+ if (promoFirst && redeemPromo) {
363
+ shown = "";
364
+ details = [];
365
+ compactShort = "";
366
+ hint = ["Type the promo code from gucli.com, then Enter. No account and no Pro plan needed.", ...(trialOk ? ["Enter alone starts the free trial instead."] : [])];
367
+ }
357
368
  };
358
369
  await offer();
359
- log(overLimit && why ? `${short || why} Type ? for details.` : compactShort ? `${compactShort} Type ? for details.` : why || "This computer needs a gu token before the agent can start — one time only.", "title");
370
+ log(promoFirst && redeemPromo ? "Your free model starts with the promo code." : overLimit && why ? `${short || why} Type ? for details.` : compactShort ? `${compactShort} Type ? for details.` : why || "This computer needs a gu token before the agent can start — one time only.", "title");
360
371
  const entitled = async (token) => {
361
372
  if (!accept) return true;
362
373
  const r = await accept(token).catch(() => ({ ok: true })); // unknown = soft, like every other check here
363
374
  if (!r.ok) log(`That token can't be used on this computer: ${r.reason}`, "warn");
364
375
  return r.ok;
365
376
  };
366
- const ask1 = () => ask("Input token: ", { prefill: shown, hint, atomic: true, noCancel: required });
377
+ const ask1 = () => ask(promoFirst && redeemPromo ? "Promo code: " : "Input token: ", { prefill: shown, hint, atomic: true, noCancel: required });
378
+ // A promo code is short and has no "." — a token always has one (payload.signature).
379
+ const looksLikeCode = (t) => Boolean(redeemPromo) && /^[A-Za-z0-9_-]{4,32}$/.test(t) && !t.includes(".");
367
380
  for (let round = 0; required ? round < maxRounds : round < 2; round++) {
368
381
  const typed = String((await ask1()) ?? "").trim();
369
382
  // A way OUT of a required question (task #17): "/exit" is not a token, and treating it as one
@@ -383,11 +396,29 @@ export async function promptForToken({
383
396
  if (!required) round--; // "?" does not use up one of the two tries
384
397
  continue;
385
398
  }
399
+ if (!typed && promoFirst && redeemPromo && trialOk) {
400
+ // "Free model" chosen but no code yet, and this computer has a trial to offer: Enter takes the trial.
401
+ await writeState(dir, { token: trial.token, lastAttemptAt: new Date().toISOString() });
402
+ if (!(await entitled(trial.token))) continue;
403
+ log(`✓ free trial token saved — ${daysLeft(trial.endsAt)} days left on this computer, until ${shortDate(trial.endsAt)}.`, "ok");
404
+ return { ok: true, kind: "trial" };
405
+ }
386
406
  if (!typed) {
387
407
  if (!required) return { ok: false, why: "skipped" };
388
408
  if (!trialOk) await offer(); // no default: maybe the service is back, or the trial exists now
389
409
  continue;
390
410
  }
411
+ if (looksLikeCode(typed) && !(trialOk && (typed === shown || typed === trial.token))) {
412
+ const pr = await redeemPromo(typed);
413
+ if (pr?.ok && pr.token && verifyCliToken(pr.token, publicKeyB64).ok) {
414
+ await writeState(dir, { token: pr.token, lastAttemptAt: new Date().toISOString() });
415
+ if (!(await entitled(pr.token))) continue;
416
+ log(`✓ promo code accepted — free model $${((Number(pr.centsPerMonth) || 0) / 100).toFixed(2)} a month for ${pr.months} month${pr.months === 1 ? "" : "s"}.`, "ok");
417
+ return { ok: true, kind: "promo", promo: pr };
418
+ }
419
+ log(pr?.error || "That code was not accepted.", "warn");
420
+ continue;
421
+ }
391
422
  if (trialOk && (typed === shown || typed === trial.token)) {
392
423
  await writeState(dir, { token: trial.token, lastAttemptAt: new Date().toISOString() });
393
424
  if (!(await entitled(trial.token))) continue;
@@ -405,10 +436,28 @@ export async function promptForToken({
405
436
  return { ok: false, why: "refused" };
406
437
  }
407
438
 
439
+ const osUserName = () => {
440
+ try {
441
+ return userInfo().username;
442
+ } catch {
443
+ return "";
444
+ }
445
+ };
446
+
408
447
  /** What renewals send about this computer. The raw OS id never leaves the machine — only a salted hash. */
409
- export async function thisDevice({ platform = process.platform, hostName = osHostname(), machineId, instanceId } = {}) {
448
+ export async function thisDevice({
449
+ platform = process.platform,
450
+ hostName = osHostname(),
451
+ machineId,
452
+ instanceId,
453
+ // OFF unless GU_DEVICE_PER_USER is set (1 or a label): each OS user of a shared computer then counts as its own computer (its own trial and
454
+ // codes), for testing several people on one Mac. The default must never change — every saved token carries this id.
455
+ perUser = Boolean(process.env.GU_DEVICE_PER_USER) && process.env.GU_DEVICE_PER_USER !== "0",
456
+ // GU_DEVICE_PER_USER=1 → the OS user name; any other value is used as the label itself (a fresh identity for a re-take).
457
+ user = !["", "0", "1"].includes(process.env.GU_DEVICE_PER_USER ?? "") ? String(process.env.GU_DEVICE_PER_USER) : osUserName(),
458
+ } = {}) {
410
459
  const raw = machineId ?? (await osMachineId({ platform }));
411
- const source = raw || (instanceId ? `instance:${instanceId}` : "");
460
+ const source = raw ? (perUser && user ? `${raw}|user:${user}` : raw) : instanceId ? `instance:${instanceId}` : "";
412
461
  if (!source) return null;
413
462
  return {
414
463
  id: createHash("sha256").update(`gu-device-v1:${source}`).digest("hex"),
@@ -533,6 +582,39 @@ export async function renewToken({ mode, apiBase, hostedBase, token, workerKey,
533
582
  }
534
583
  }
535
584
 
585
+ /**
586
+ * A free-model promo code with NO token (the computer's trial ended, or it never had one): the code is the
587
+ * credential, and the answer carries a token for this computer that runs for the code's months. Never throws.
588
+ */
589
+ export async function redeemPromo({ hostedBase, device, code, fetchImpl = fetch, timeoutMs = 10000 }) {
590
+ const base = String(hostedBase ?? "").replace(/\/+$/, "");
591
+ if (!base) return { ok: false, why: "no-api", error: "No gu service address is set on this computer." };
592
+ if (!device) return { ok: false, why: "no-device", error: "This computer could not be identified, so a promo code cannot be used here." };
593
+ try {
594
+ const res = await fetchImpl(`${base}/api/billing/cli-token/promo`, {
595
+ method: "POST",
596
+ headers: { "content-type": "application/json" },
597
+ body: JSON.stringify({ code: String(code ?? ""), device }),
598
+ signal: AbortSignal.timeout(timeoutMs),
599
+ });
600
+ const data = await res.json().catch(() => null);
601
+ if (!res.ok) {
602
+ const error = typeof data?.error === "string" && data.error
603
+ ? data.error
604
+ : res.status === 404 ? "This gu service does not take promo codes yet." : `The gu service answered HTTP ${res.status}.`;
605
+ return { ok: false, why: typeof data?.why === "string" ? data.why : `http-${res.status}`, error };
606
+ }
607
+ return {
608
+ ok: typeof data?.token === "string",
609
+ token: typeof data?.token === "string" ? data.token : "",
610
+ centsPerMonth: Number(data?.centsPerMonth ?? 0),
611
+ months: Number(data?.months ?? 0),
612
+ };
613
+ } catch (e) {
614
+ return { ok: false, why: "network", error: e?.name === "TimeoutError" ? "The gu service did not answer in time. Try again." : "Can't reach the gu service right now." };
615
+ }
616
+ }
617
+
536
618
  /**
537
619
  * /voucher CODE (#425): redeem a marketing code with this computer's token as the credential — a
538
620
  * trial (no account) or an account. Returns { ok: true, days, token } — the token already carries the
@@ -1692,7 +1692,7 @@ export async function runClientExpertSetup({
1692
1692
  console.log("");
1693
1693
  // "skipped" is only true when nothing was chosen: a provider that was picked is NOT skipped,
1694
1694
  // its key and model are just asked in gu itself (GH #397).
1695
- console.log(" " + cyan(addProvider ? `✓ ${addProvider.name || "Provider"} chosen` : voucherAtStart ? "✓ Free model chosen" : "✓ Model setup skipped") + dim(addProvider
1695
+ console.log(" " + cyan(addProvider ? `✓ ${addProvider.name || "Provider"} chosen` : voucherAtStart ? "✓ Promo code chosen" : "✓ Model setup skipped") + dim(addProvider
1696
1696
  ? (addProvider.key ? " — gu checks your key and lists its models as soon as it starts" : " — gu asks for its key and model as soon as it starts")
1697
1697
  : voucherAtStart
1698
1698
  ? " — gu asks for your code as soon as it starts"
@@ -159,9 +159,16 @@ export function ensureV1Root(base) {
159
159
  const stripped = String(base ?? "")
160
160
  .replace(/\/+$/, "")
161
161
  .replace(/\/api(?:\/(?:generate|chat|tags|embeddings|embed)(?:\/v1)?)?$/i, "");
162
+ // GH #499: Google AI Studio's OpenAI layer IS ".../v1beta/openai" — it has no /v1, and adding
163
+ // one 404s every call. Only that documented root is exempt (see GEMINI_ROOT_RE).
164
+ if (GEMINI_ROOT_RE.test(stripped)) return stripped;
162
165
  return /\/v1$/i.test(stripped) ? stripped : `${stripped}/v1`;
163
166
  }
164
167
 
168
+ /** An OpenAI-compatible root that is complete as it stands: Gemini's "/v1beta/openai". Mirrored in
169
+ * normalizeOpenAiV1Root / normalizeOpenAiV1RootDedup (api) and _normalize_openai_base (python). */
170
+ const GEMINI_ROOT_RE = /\/v1beta\/openai$/i;
171
+
165
172
  /** What to say about a URL we refused. One line; the caller adds the gutter. */
166
173
  export function describeUrlProblem(why, typed = "") {
167
174
  switch (why) {
@@ -208,6 +215,13 @@ export function modelsUrlFor(url) {
208
215
  export const CLAUDE_API_URL = "https://api.anthropic.com/v1";
209
216
  export const ANTHROPIC_VERSION = "2023-06-01";
210
217
 
218
+ /**
219
+ * GOOGLE AI STUDIO / the Gemini API (GH #499). Its OpenAI-compatible layer is this exact root — a
220
+ * plain Bearer key, /chat/completions, GET /models — and it has NO /v1: adding one 404s every call,
221
+ * so ensureV1Root leaves a "/v1beta/openai" root as it is. Still "beta" on Google's side.
222
+ */
223
+ export const GEMINI_API_URL = "https://generativelanguage.googleapis.com/v1beta/openai";
224
+
211
225
  export function isAnthropicUrl(url) {
212
226
  try {
213
227
  return new URL(String(url ?? "")).hostname.toLowerCase().replace(/\.$/, "") === "api.anthropic.com";
@@ -258,6 +272,8 @@ export function describeListFailure({ host = "", reason = "failed", status = 0,
258
272
  export function providerPresets(role = "coding") {
259
273
  const all = [
260
274
  { name: "Claude API (Anthropic)", url: CLAUDE_API_URL, roles: ["coding", "agent"] },
275
+ // GH #499. Not for the embedder until its /embeddings is tested live.
276
+ { name: "Google AI Studio (Gemini)", url: GEMINI_API_URL, roles: ["coding", "agent"] },
261
277
  { name: "OpenAI", url: DEFAULT_PROVIDER_URL, roles: ["coding", "agent", "embed"] },
262
278
  { name: "Kimi (Moonshot)", url: "https://api.moonshot.ai/v1", roles: ["coding", "agent"] },
263
279
  // #490: DeepSeek is what many people already hold a key for. OpenAI-compatible, /v1 included.
@@ -287,6 +303,11 @@ export function detectProvider(key, presets = providerPresets("coding")) {
287
303
  if (!k) return null;
288
304
  const by = (name) => presets.find((p) => p.name === name) ?? null;
289
305
  if (k.startsWith("sk-ant-")) return by("Claude API (Anthropic)");
306
+ // Google API keys: "AIza" + 35 of [0-9A-Za-z_-] (39 in all). Case-sensitive, exact length.
307
+ if (/^AIza[0-9A-Za-z_-]{35}$/.test(k)) return by("Google AI Studio (Gemini)");
308
+ // Google's newer keys: "AQ." + the same alphabet (measured: 53 chars in all). Length is not pinned
309
+ // from one sample; 40+ keeps a short "AQ.something" from matching.
310
+ if (/^AQ\.[0-9A-Za-z_-]{40,}$/.test(k)) return by("Google AI Studio (Gemini)");
290
311
  if (k.startsWith("sk-sp-")) return by("Qwen Token Plan (OpenAI-compatible)");
291
312
  if (k.startsWith("sk-ws-")) return by("Qwen pay-as-you-go (OpenAI-compatible)");
292
313
  if (k.startsWith("sk-proj-") || k.startsWith("sk-svcacct-")) return by("OpenAI");
@@ -365,7 +386,10 @@ export function parseProviderModels(body, now = Date.now()) {
365
386
  const seen = new Set();
366
387
  let retired = 0;
367
388
  for (const r of rows) {
368
- const id = typeof r === "string" ? r.trim() : typeof r?.id === "string" ? r.id.trim() : "";
389
+ const raw = typeof r === "string" ? r.trim() : typeof r?.id === "string" ? r.id.trim() : "";
390
+ // GH #499: Google lists every model as "models/gemini-…" (measured). Show and store the bare
391
+ // name; only a single segment after the prefix counts, so "models/a/b" is left alone.
392
+ const id = raw.replace(/^models\/([^/]+)$/, "$1");
369
393
  if (!id || seen.has(id)) continue;
370
394
  seen.add(id);
371
395
  // BELIEVE THE PROVIDER when it says a model is done. Offering one that is already retired is
package/free-model.mjs CHANGED
@@ -145,6 +145,34 @@ export function addTurn(state, usage, now = new Date(), model = "", url = "") {
145
145
  return { ...s, spentMicro: whole(s.spentMicro) + cost };
146
146
  }
147
147
 
148
+ /**
149
+ * The turn's OTHER model calls (GH #501): the chat model's replies, search summaries, compaction —
150
+ * every call the coder's steps do not count. They run on the same key, so each one on a free-model
151
+ * server is charged to that server's slot at its own model's price. `aux` is what the worker
152
+ * passes on: [{ url, model, input, cached, cacheReported, output }]. Calls on other servers
153
+ * (the person's own keys) are not ours to count.
154
+ */
155
+ export function parseAux(raw) {
156
+ let list = raw;
157
+ if (typeof raw === "string") {
158
+ try {
159
+ list = JSON.parse(raw);
160
+ } catch {
161
+ return [];
162
+ }
163
+ }
164
+ return Array.isArray(list) ? list.filter((a) => a && typeof a.url === "string" && typeof a.model === "string") : [];
165
+ }
166
+
167
+ export function addAuxCalls(state, aux, now = new Date()) {
168
+ let s = state;
169
+ for (const a of parseAux(aux)) {
170
+ if (!isFreeServer(s, a.url) || !(whole(a.input) > 0 || whole(a.output) > 0)) continue;
171
+ s = addTurn(s, { input: a.input, cached: a.cached, cacheReported: a.cacheReported === true, output: a.output }, now, a.model, a.url) ?? s;
172
+ }
173
+ return s;
174
+ }
175
+
148
176
  /** After the service answered the preset: what gu keeps (never the key itself). */
149
177
  export function stateFromPreset(preset, prev, now = new Date()) {
150
178
  const p = periodKey(now);
@@ -173,7 +201,8 @@ export function stateFromPreset(preset, prev, now = new Date()) {
173
201
  };
174
202
  }
175
203
 
176
- const usd = (micro) => `$${(whole(micro) / 1e6).toFixed(2)}`;
204
+ // No dollar amounts (owner 2026-11-26): the allowance is the admin's to set per buyer and is never shown,
205
+ // only how much of it is used, in percent.
177
206
 
178
207
  /**
179
208
  * The line to show, or null. `over` is the refusal itself; warn/low are shown once per level.
@@ -189,10 +218,10 @@ export function notice(state, now = new Date(), url = "") {
189
218
  const Name = slot.extra ? slot.label : "Free model";
190
219
  if (level === "over") {
191
220
  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.` };
221
+ return { level, text: `Your ${name} allowance for this month 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.` };
193
222
  }
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.` };
223
+ if (level === "low") return { level, text: `${Name}: ${pct}% of this month's allowance used — almost gone. Add your own key with /model before it ends.` };
224
+ if (level === "warn") return { level, text: `${Name}: ${pct}% of this month's allowance used.` };
196
225
  return { level, text: null };
197
226
  }
198
227
 
@@ -272,6 +301,10 @@ export async function reportSpend({ hostedBase, token, state, fetchImpl = fetch,
272
301
  return r.ok && Number.isFinite(Number(r.body.spentMicro)) ? Number(r.body.spentMicro) : null;
273
302
  }
274
303
 
304
+ /** The model that talks: the one a code names (when it is not the coder), else the coder itself. */
305
+ export const agentModelOf = (preset) =>
306
+ typeof preset?.agentModel === "string" && preset.agentModel && preset.agentModel !== preset.model ? preset.agentModel : preset.model;
307
+
275
308
  /**
276
309
  * APPLY THE PRESET to this account, through the same local-API calls /use-presets uses (preset-apply's
277
310
  * `api`): the server is ADDED (or updated) — the person's other providers stay — its key is added as
@@ -316,8 +349,9 @@ export async function applyPreset(preset, api, { rotateOnly = false } = {}) {
316
349
  agentCodingModelName: preset.model,
317
350
  agentCodingModelKind: "openai",
318
351
  agentModelUrl: preset.baseUrl,
319
- agentModelName: preset.model,
320
- agentModel: preset.model,
352
+ // A code may name a different model to TALK (the agent model); the coder stays the preset's model.
353
+ agentModelName: agentModelOf(preset),
354
+ agentModel: agentModelOf(preset),
321
355
  }),
322
356
  };
323
357
  if (!(await api.saveSettings(patch))) return { ok: false, why: "the local API refused the settings" };
@@ -384,6 +384,11 @@ def _normalize_openai_base(url: str) -> str:
384
384
  return ""
385
385
  u = re.sub(r"/api(?:/(?:generate|chat|tags|embeddings|embed)(?:/v1)?)?$", "", u,
386
386
  flags=re.IGNORECASE)
387
+ # GH #499: Google AI Studio's OpenAI layer IS ".../v1beta/openai" — no /v1, and adding one
388
+ # 404s every call. Only that documented root is exempt. Mirrored in ensureV1Root (worker JS)
389
+ # and normalizeOpenAiV1Root / normalizeOpenAiV1RootDedup (api).
390
+ if u.lower().endswith("/v1beta/openai"):
391
+ return u
387
392
  return u if u.lower().endswith("/v1") else u + "/v1"
388
393
 
389
394
 
@@ -2607,6 +2612,25 @@ _CACHED_TOKEN_FIELDS = (
2607
2612
  )
2608
2613
 
2609
2614
 
2615
+ def _output_tokens_from_usage(usage, base_url="") -> int:
2616
+ """The OUTPUT tokens a step was billed for, from a usage chunk (GH #499).
2617
+
2618
+ Normally `completion_tokens`. Google's OpenAI layer is the exception: its completion_tokens
2619
+ EXCLUDES the hidden thinking, which is billed as output. Measured live (gemini-4-hydrogen,
2620
+ streamed, reasoning_effort=low): {completion_tokens: 30, prompt_tokens: 54, total_tokens: 153}
2621
+ — 99 billed, 30 reported. So on Google's host the output is total - prompt, never less than
2622
+ completion_tokens. Every other host keeps completion_tokens exactly as before."""
2623
+ out = int(_usage_field(usage, "completion_tokens") or 0)
2624
+ from urllib.parse import urlparse
2625
+ host = (urlparse(str(base_url or "")).hostname or "").lower().rstrip(".")
2626
+ if host == _GEMINI_HOST:
2627
+ total = _usage_field(usage, "total_tokens")
2628
+ prompt = _usage_field(usage, "prompt_tokens")
2629
+ if isinstance(total, (int, float)) and isinstance(prompt, (int, float)):
2630
+ out = max(out, int(total) - int(prompt))
2631
+ return out
2632
+
2633
+
2610
2634
  def _usage_reports_cache(usage) -> bool:
2611
2635
  """Did this server tell us ANYTHING about its prefix cache?
2612
2636
 
@@ -3264,8 +3288,10 @@ def _unsupported_sampling_params(err) -> list:
3264
3288
  bad = [p for p in ("temperature", "top_p") if p in msg]
3265
3289
  if not bad:
3266
3290
  return []
3291
+ # "deprecated": claude-sonnet-5-5 answers 400 "`temperature` is deprecated for this model." — the same
3292
+ # repair (drop it, ask again), and the plain reply of a Claude-only free-model user died without it.
3267
3293
  if any(k in msg for k in ("only 1", "unsupported", "not support", "invalid", "must be",
3268
- "does not support", "allowed")):
3294
+ "does not support", "allowed", "deprecated")):
3269
3295
  return bad
3270
3296
  return []
3271
3297
 
@@ -3293,7 +3319,11 @@ _TOKEN_KEYS = ("max_tokens", "max_completion_tokens")
3293
3319
  # Optional request fields that are safe to drop. NEVER model / messages / stream / tools.
3294
3320
  _DROPPABLE_PARAMS = ("stop", "presence_penalty", "frequency_penalty", "stream_options", "seed",
3295
3321
  "logprobs", "top_logprobs", "logit_bias", "n", "user",
3296
- "parallel_tool_calls", "service_tier", "store", "metadata")
3322
+ "parallel_tool_calls", "service_tier", "store", "metadata",
3323
+ # GH #499: Gemini 3 Flash is reported to 400 on some effort levels. Optional
3324
+ # everywhere gu sends it (Ollama "none", Gemini "low"): the model's own
3325
+ # default is better than a turn that cannot start.
3326
+ "reasoning_effort")
3297
3327
  _REJECT_WORDS = ("unsupported", "not supported", "unrecognized", "unknown parameter",
3298
3328
  "extra inputs", "not permitted", "unexpected keyword")
3299
3329
 
@@ -3370,6 +3400,37 @@ def _deepseek_thinking_kwargs(model_id, base_url="", env=None) -> dict:
3370
3400
  return {"extra_body": {"thinking": {"type": "disabled"}}}
3371
3401
 
3372
3402
 
3403
+ _GEMINI_HOST = "generativelanguage.googleapis.com"
3404
+ _GEMINI_3_4_RE = re.compile(r"^(?:models/)?gemini-[34](?![0-9])", re.I)
3405
+ _GEMINI_EFFORTS = ("minimal", "low", "medium", "high")
3406
+
3407
+
3408
+ def _gemini_thinking_kwargs(model_id, base_url="", env=None) -> dict:
3409
+ """Opt-in thinking level for Gemini in the coding loop (GH #499), or {} (the default).
3410
+
3411
+ Gemini 3 and 4 think on every call and cannot be switched off through Google's OpenAI layer
3412
+ (reasoning_effort "none" is accepted but still thinks), and the thinking is billed as output.
3413
+ MEASURED (2026-11-25, real gu turns, gemini-4-hydrogen, 5 runs each): "low" vs Google's default
3414
+ level cost about the same per turn ($0.056 vs $0.064 average; the run-to-run spread is larger than
3415
+ the gap) — output is only 1-3% of a turn's cost, the step count and the prompt dominate, and "low"
3416
+ took MORE steps on the bug-fix task (28 and 25 vs 18 and 20). So nothing is sent by default.
3417
+
3418
+ GONEXT_GEMINI_EFFORT = minimal|low|medium|high sends that level. Only on Google's host and only
3419
+ for Gemini 3/4 ids. "minimal" is rejected with a 400 by gemini-3.8-flash; a host that rejects the
3420
+ field has it dropped once (_repair_request)."""
3421
+ env = os.environ if env is None else env
3422
+ mode = str(env.get("GONEXT_GEMINI_EFFORT", "")).strip().lower()
3423
+ if mode not in _GEMINI_EFFORTS:
3424
+ return {}
3425
+ if not _GEMINI_3_4_RE.search(str(model_id or "").strip()):
3426
+ return {}
3427
+ from urllib.parse import urlparse
3428
+ host = (urlparse(str(base_url or "")).hostname or "").lower().rstrip(".")
3429
+ if host != _GEMINI_HOST:
3430
+ return {}
3431
+ return {"reasoning_effort": mode}
3432
+
3433
+
3373
3434
  def _coding_extra_kwargs(ollama_tweaks: bool, base_url, model_id, env=None):
3374
3435
  """Extra request fields for the coding model → (kwargs, log line or ""). Pure, so the whole
3375
3436
  provider matrix is testable (tests/test_coding_extra_kwargs_430.py): ONLY an Ollama server
@@ -3383,6 +3444,10 @@ def _coding_extra_kwargs(ollama_tweaks: bool, base_url, model_id, env=None):
3383
3444
  if ds:
3384
3445
  return ds, ("coding model is DeepSeek V4 → thinking off for the tool loop (GH #430; "
3385
3446
  "GONEXT_DEEPSEEK_THINKING=on to keep it)")
3447
+ gm = _gemini_thinking_kwargs(model_id, base_url, env)
3448
+ if gm:
3449
+ return gm, (f"coding model is Gemini → reasoning_effort={gm['reasoning_effort']!r} "
3450
+ "(GONEXT_GEMINI_EFFORT; it cannot be switched off — GH #499)")
3386
3451
  return {}, ""
3387
3452
 
3388
3453
 
@@ -3428,6 +3493,12 @@ def _repair_request(kwargs: dict, err):
3428
3493
  else:
3429
3494
  kw.pop("extra_body")
3430
3495
  return kw, "drop:thinking"
3496
+ # 4b. Gemini rejects an effort level it does not offer WITHOUT naming the field (GH #499, measured:
3497
+ # "Thinking level MINIMAL is not supported for this model. Please retry with other thinking
3498
+ # level."), so the generic field-name match below never sees it. The level is optional:
3499
+ # drop it and the model runs at its own default.
3500
+ if "reasoning_effort" in kw and re.search(r"thinking[ _](?:level|budget)|reasoning[ _]effort", msg):
3501
+ return _without_params(kw, ["reasoning_effort"]), "drop:reasoning_effort"
3431
3502
  # 5. any other optional field the provider says it does not know
3432
3503
  if rejects:
3433
3504
  names = [n for n in re.findall(r"['\"`]([a-z_]+)['\"`]", msg)
@@ -3542,12 +3613,146 @@ def _remember_shape(key: str, new_kw: dict, action: str) -> None:
3542
3613
  _save_shape(key, entry)
3543
3614
 
3544
3615
 
3616
+ # ---- every model call the coder's steps do not count (GH #501) --------------------------------
3617
+ #
3618
+ # The coder's steps report their own tokens ("tokens" events). Every OTHER call — the chat model's
3619
+ # replies, search summaries, compaction, titles — used to go uncounted, while running on the same
3620
+ # key. On the free model that key is the owner's, so those calls were paid for and charged to
3621
+ # nobody. Each one is now counted here, per (server, model), and sent as one cumulative
3622
+ # "aux_tokens" event; gu charges the ones on a free-model server to its allowance.
3623
+ #
3624
+ # The provider's own usage figure when it gives one (streams are asked for it); else an estimate
3625
+ # from the text, ~4 characters a token, rounded UP — an estimate must never undercharge.
3626
+ _AUX_USAGE: dict = {}
3627
+ _AUX_LOCK = threading.Lock()
3628
+
3629
+
3630
+ def _aux_text_len(messages) -> int:
3631
+ n = 0
3632
+ for m in messages or []:
3633
+ c = m.get("content") if isinstance(m, dict) else getattr(m, "content", None)
3634
+ if isinstance(c, str):
3635
+ n += len(c)
3636
+ elif isinstance(c, list):
3637
+ for part in c:
3638
+ t = part.get("text") if isinstance(part, dict) else None
3639
+ if isinstance(t, str):
3640
+ n += len(t)
3641
+ return n
3642
+
3643
+
3644
+ def _aux_est_tokens(chars: int) -> int:
3645
+ return (int(chars) + 3) // 4
3646
+
3647
+
3648
+ def _note_aux_usage(base_url: str, model: str, usage=None, est_in: int = 0, est_out: int = 0) -> None:
3649
+ """Add one call to the turn's other-calls count and emit the running total. Never raises."""
3650
+ try:
3651
+ if usage is not None and _usage_field(usage, "prompt_tokens") is not None:
3652
+ inp = int(_usage_field(usage, "prompt_tokens") or 0)
3653
+ out = _output_tokens_from_usage(usage, base_url)
3654
+ reported = _usage_reports_cache(usage)
3655
+ cached = _cached_tokens_from_usage(usage) if reported else 0
3656
+ estimated = False
3657
+ else:
3658
+ inp, out, cached, reported, estimated = int(est_in), int(est_out), 0, False, True
3659
+ if inp <= 0 and out <= 0:
3660
+ return
3661
+ key = f"{base_url}|{model}"
3662
+ with _AUX_LOCK:
3663
+ a = _AUX_USAGE.setdefault(key, {"url": base_url, "model": model, "input": 0, "cached": 0,
3664
+ "cacheReported": True, "output": 0, "estimated": False, "calls": 0})
3665
+ a["input"] += inp
3666
+ a["output"] += out
3667
+ a["cached"] += cached
3668
+ # One call without a cache figure makes the whole sum "not reported": charged at full price.
3669
+ a["cacheReported"] = a["cacheReported"] and reported
3670
+ a["estimated"] = a["estimated"] or estimated
3671
+ a["calls"] += 1
3672
+ snapshot = [dict(v) for v in _AUX_USAGE.values()]
3673
+ _emit({"type": "aux_tokens", "usage": snapshot})
3674
+ except Exception: # noqa: BLE001 — counting is never worth a failed reply
3675
+ pass
3676
+
3677
+
3678
+ class _AuxCountedStream:
3679
+ """Passes a streamed completion through unchanged, and counts it when the stream ends."""
3680
+
3681
+ def __init__(self, stream, base_url, model, est_in):
3682
+ self._stream, self._base, self._model, self._est_in = stream, base_url, model, est_in
3683
+ self._usage, self._chars, self._done = None, 0, False
3684
+
3685
+ def __iter__(self):
3686
+ try:
3687
+ for chunk in self._stream:
3688
+ u = getattr(chunk, "usage", None) if not isinstance(chunk, dict) else chunk.get("usage")
3689
+ if u is not None:
3690
+ self._usage = u
3691
+ try:
3692
+ choices = getattr(chunk, "choices", None) or []
3693
+ delta = getattr(choices[0], "delta", None) if choices else None
3694
+ for f in ("content", "reasoning_content", "reasoning"):
3695
+ v = getattr(delta, f, None) if delta is not None else None
3696
+ if isinstance(v, str):
3697
+ self._chars += len(v)
3698
+ except Exception: # noqa: BLE001
3699
+ pass
3700
+ yield chunk
3701
+ finally:
3702
+ self._finish()
3703
+
3704
+ def _finish(self):
3705
+ if self._done:
3706
+ return
3707
+ self._done = True
3708
+ _note_aux_usage(self._base, self._model, self._usage, self._est_in, _aux_est_tokens(self._chars))
3709
+
3710
+ def close(self):
3711
+ try:
3712
+ close = getattr(self._stream, "close", None)
3713
+ if callable(close):
3714
+ close()
3715
+ finally:
3716
+ self._finish()
3717
+
3718
+ def __getattr__(self, name):
3719
+ return getattr(self._stream, name)
3720
+
3721
+
3545
3722
  def _create_with_repair(client, **kwargs):
3546
3723
  """client.chat.completions.create that fixes a 400 about the request SHAPE and retries.
3547
3724
 
3548
3725
  Up to _REPAIR_MAX_ATTEMPTS repairs; each KIND of fix is applied at most once, so it can never
3549
- ping-pong between max_tokens and max_completion_tokens. An unfixable 400 is raised as it came."""
3726
+ ping-pong between max_tokens and max_completion_tokens. An unfixable 400 is raised as it came.
3727
+
3728
+ `_metered=True` = the caller counts this call itself (the coder's steps); every other call is
3729
+ counted here (GH #501)."""
3730
+ metered = bool(kwargs.pop("_metered", False))
3731
+ resp = _create_with_repair_raw(client, metered, **kwargs)
3732
+ if metered:
3733
+ return resp
3734
+ base = str(getattr(client, "base_url", "") or "")
3735
+ model = str(kwargs.get("model") or "")
3736
+ est_in = _aux_est_tokens(_aux_text_len(kwargs.get("messages")))
3737
+ if kwargs.get("stream"):
3738
+ return _AuxCountedStream(resp, base, model, est_in)
3739
+ out_chars = 0
3740
+ try:
3741
+ msg = resp.choices[0].message
3742
+ out_chars = sum(len(getattr(msg, f, None) or "") for f in ("content", "reasoning_content"))
3743
+ except Exception: # noqa: BLE001
3744
+ pass
3745
+ _note_aux_usage(base, model, getattr(resp, "usage", None), est_in, _aux_est_tokens(out_chars))
3746
+ return resp
3747
+
3748
+
3749
+ def _create_with_repair_raw(client, metered, **kwargs):
3550
3750
  base = str(getattr(client, "base_url", "") or "")
3751
+ # GH #501: ask a hosted server for the stream's usage — the counted figure beats an estimate.
3752
+ # Local servers are not asked: some refuse the field, and nothing on them is billed.
3753
+ if (not metered and kwargs.get("stream") and "stream_options" not in kwargs
3754
+ and not _is_local_url(base)):
3755
+ kwargs = {**kwargs, "stream_options": {"include_usage": True}}
3551
3756
  model = str(kwargs.get("model") or "")
3552
3757
  key = f"{base}|{model}"
3553
3758
  kw = _apply_request_shape(kwargs, key, model)
@@ -4199,6 +4404,9 @@ _KNOWN_CTX_WINDOWS: list = [
4199
4404
  (r"^claude-haiku-4-5", 200_000, "https://platform.claude.com/docs/en/about-claude/models/overview"),
4200
4405
  (r"^claude-(opus|sonnet|fable|mythos)-(5|4-[678])", 1_000_000,
4201
4406
  "https://platform.claude.com/docs/en/about-claude/models/overview"),
4407
+ # Gemini 4 (#499): Google's models page lists every Gemini 4 model at 1M context, read 2026-11-25.
4408
+ # Not gemini-3.x: the page gave no number for 3.8 Flash, so it stays unrecognised (and says so).
4409
+ (r"^(models/)?gemini-4", 1_000_000, "https://aistudio.google.com/docs/models"),
4202
4410
  (r"^kimi-k2", 256_000, "https://platform.kimi.ai/docs/api/chat.en-US"),
4203
4411
  (r"^kimi-k1", 128_000, "unverified — no vendor page found; corrected on first refusal"),
4204
4412
  # These three state their size in the name, which is its own citation.
@@ -4239,6 +4447,8 @@ _KNOWN_MAX_OUTPUT = [
4239
4447
  # Fable 5.1 / Opus 5.5 / Sonnet 5.5 = 128K max output, Haiku 4.5 = 64K.
4240
4448
  (r"^claude-haiku-4-5", 64_000, "https://platform.claude.com/docs/en/models/overview"),
4241
4449
  (r"^claude-(opus|sonnet|fable)-5", 128_000, "https://platform.claude.com/docs/en/models/overview"),
4450
+ (r"^(models/)?gemini-4", 64_000, "https://aistudio.google.com/docs/models (Gemini 4: 64K max "
4451
+ "output, read 2026-11-25)"),
4242
4452
  (r"^gpt-6", 128_000, "OpenAI API models overview (read through a web search summary; "
4243
4453
  "GPT-6 Astra / 6.1 Sol / 6 Luna: 128,000 output tokens)"),
4244
4454
  (r"^gpt-5\.1-codex-max", 128_000, "https://developers.openai.com/api/docs/models/gpt-5-codex "
@@ -13703,7 +13913,7 @@ def run_agent_chat(cfg):
13703
13913
  _log("streamed generate: request issued (stream=True), awaiting first token…")
13704
13914
  # Request-shape repair (max_tokens vs max_completion_tokens, sampling params the
13705
13915
  # model refuses, output cap named by the provider) — see _create_with_repair.
13706
- stream = _create_with_repair(self.client, **completion_kwargs)
13916
+ stream = _create_with_repair(self.client, _metered=True, **completion_kwargs)
13707
13917
  parts = []
13708
13918
  rparts = [] # reasoning-channel text (task #111: may hold the <code> block)
13709
13919
  role = "assistant"
@@ -13817,7 +14027,7 @@ def run_agent_chat(cfg):
13817
14027
  if usage is not None:
13818
14028
  self._last_usage_seen = True
13819
14029
  in_tok = getattr(usage, "prompt_tokens", 0) or in_tok
13820
- out_tok = getattr(usage, "completion_tokens", 0) or out_tok
14030
+ out_tok = _output_tokens_from_usage(usage, self._stream_key()[0]) or out_tok
13821
14031
  # Presence, not truth: a server that reports the branch at all is one
13822
14032
  # whose 0 MEANS "nothing was cached". Recorded even when the count is 0
13823
14033
  # so a genuine miss stays distinguishable from a silent server.
package/gu-cli.mjs CHANGED
@@ -24,6 +24,7 @@ import { createTaskPool, createFolderQueue } from "./job-pools.mjs";
24
24
  import { NO_STEP, foldStepTokens, withStepTokens, NO_CACHE, foldTurnCache, withTurnCache } from "./step-tokens.mjs";
25
25
  import { agentStoppedLine, jobEnded, jobStatusFrom409, stopGracefully } from "./agent-stop.mjs";
26
26
  import { ragJobConfig } from "./rag-job-config.mjs";
27
+ import { createThinkTagScrubber } from "./stream-think-tags.mjs";
27
28
  import { codingKeyFallbackLine, isOllamaCloudUrl } from "./coding-key-prompt.mjs";
28
29
  // Pure layout helpers — safe to import here (no side effects on load, unlike gu-repl.mjs).
29
30
  // Shared so the mid-run picker and the REPL's post-stop advice cannot word the same budget
@@ -4035,6 +4036,11 @@ async function runAgentChatJob(job) {
4035
4036
  let flushTimer = null;
4036
4037
  let fullText = "";
4037
4038
  let flushTail = Promise.resolve();
4039
+ // GH #501: the turn's other model calls (the chat model's replies, summaries…) as python
4040
+ // counted them — a JSON string the job carries as the breakdown's `aux`, so gu can charge
4041
+ // them to the free model. Its PATCH is awaited before the turn is marked done or failed.
4042
+ let auxUsage = null;
4043
+ let auxPatch = Promise.resolve();
4038
4044
  const CHUNK_DEBOUNCE_MS = 80;
4039
4045
  const CHUNK_MAX_BUF = 6144;
4040
4046
 
@@ -4412,8 +4418,13 @@ async function runAgentChatJob(job) {
4412
4418
  // it renders verbatim; `step` labels stay outside the fence as normal prose.
4413
4419
  // Tilde fences (~~~) avoid colliding with any ``` the model itself emits.
4414
4420
  let inStreamFence = false;
4421
+ // GH #498: a model that types "</think>" itself would close the turn's <think> block, and the
4422
+ // rest of the work would print as the answer. The raw stream goes through this first.
4423
+ const thinkTags = createThinkTagScrubber();
4415
4424
  const closeStreamFence = () => {
4416
4425
  if (inStreamFence) {
4426
+ const held = thinkTags.flush();
4427
+ if (held) enqueueText(held);
4417
4428
  inStreamFence = false;
4418
4429
  enqueueText("\n~~~\n\n");
4419
4430
  }
@@ -4528,7 +4539,8 @@ async function runAgentChatJob(job) {
4528
4539
  inStreamFence = true;
4529
4540
  enqueueText("~~~\n");
4530
4541
  }
4531
- enqueueText(event.text);
4542
+ const safe = thinkTags.push(event.text);
4543
+ if (safe) enqueueText(safe);
4532
4544
  } else if (event.type === "step" && typeof event.text === "string") {
4533
4545
  closeStreamFence();
4534
4546
  if (!inThink) {
@@ -4597,11 +4609,20 @@ async function runAgentChatJob(job) {
4597
4609
  agentMaxCodeTokens: latestMaxCodeTokens,
4598
4610
  agentOutputTokens: latestCodeOutputTokens,
4599
4611
  ...(latestPromptBreakdown
4600
- ? { agentPromptBreakdown: latestPromptBreakdown }
4612
+ ? { agentPromptBreakdown: auxUsage ? { ...latestPromptBreakdown, aux: auxUsage } : latestPromptBreakdown }
4601
4613
  : {}),
4602
4614
  }),
4603
4615
  }).catch(() => {});
4604
4616
  }
4617
+ } else if (event.type === "aux_tokens" && Array.isArray(event.usage)) {
4618
+ auxUsage = JSON.stringify(event.usage.slice(0, 32));
4619
+ const body = JSON.stringify({
4620
+ agentCodeTokens: latestCodeTokens,
4621
+ agentMaxCodeTokens: latestMaxCodeTokens,
4622
+ agentOutputTokens: latestCodeOutputTokens,
4623
+ agentPromptBreakdown: { ...(latestPromptBreakdown || {}), aux: auxUsage },
4624
+ });
4625
+ auxPatch = auxPatch.then(() => workerFetch(`/api/worker/jobs/${jobId}`, { method: "PATCH", body })).catch(() => {});
4605
4626
  } else if (event.type === "compact" && Number.isFinite(event.n)) {
4606
4627
  // Issue #120: a mid-turn compaction just landed — put it on the job straight away so
4607
4628
  // the REPL locks input and shows its progress bar now, not at the next request.
@@ -4711,6 +4732,7 @@ async function runAgentChatJob(job) {
4711
4732
  if (flushTimer) { clearTimeout(flushTimer); flushTimer = null; }
4712
4733
  await flushTail;
4713
4734
  await flushChunks();
4735
+ await auxPatch; // GH #501: the other calls' count is on the job before it reads as done
4714
4736
 
4715
4737
  const totalTimeSeconds = (Date.now() - start) / 1000;
4716
4738
  // Patient (#302 part 3): the turn is DONE; a network blip now must not throw its result away.
@@ -4761,6 +4783,7 @@ async function runAgentChatJob(job) {
4761
4783
  }
4762
4784
  await flushTail;
4763
4785
  await flushChunks().catch(() => {});
4786
+ await auxPatch; // GH #501: a failed turn's calls were billed too
4764
4787
  const message = e instanceof Error ? e.message : String(e);
4765
4788
  const failRes = await workerFetch(`/api/worker/jobs/${jobId}`, {
4766
4789
  method: "PATCH",
package/gu-repl.mjs CHANGED
@@ -2496,6 +2496,8 @@ let lastTurnTotalOutput = 0;
2496
2496
  // answer at a glance is "how much of this context is RAG, and is it growing?". `rag 4.2k 34%`
2497
2497
  // is that answer; the rest of the breakdown lives in /tokens, which has room for it.
2498
2498
  let lastPromptBreakdown = null;
2499
+ // GH #501: the turn's other model calls (chat model, summaries), as the worker passed them on.
2500
+ let lastTurnAux = null;
2499
2501
  /**
2500
2502
  * The "↓ N" beside the thinking line, EASED — see easeCount.
2501
2503
  *
@@ -8956,7 +8958,10 @@ async function setUpFreeModel({ token, announce = false } = {}) {
8956
8958
  fm.writeState(freeModelDir(), freeModel);
8957
8959
  if (first && fm.hasPrimaryKey(got.preset)) {
8958
8960
  await refreshAfterPresetApply(null, { model: got.preset.model, url: got.preset.baseUrl }, { coder: true });
8959
- console.log(GUTTER + accent(`✓ ${got.preset.model} is now your agent model and your coding model.`) +
8961
+ const agentM = fm.agentModelOf(got.preset);
8962
+ console.log(GUTTER + accent(agentM === got.preset.model
8963
+ ? `✓ ${got.preset.model} is now your agent model and your coding model.`
8964
+ : `✓ ${agentM} is now your agent model and ${got.preset.model} your coding model.`) +
8960
8965
  dim(" Free use renews each month; /model switches back to your own."));
8961
8966
  }
8962
8967
  return true;
@@ -8982,12 +8987,18 @@ async function freeModelAtStart() {
8982
8987
  }
8983
8988
 
8984
8989
  /** After a turn on the free model: count it, say a notice once per level, tell the service. Never throws. */
8985
- async function noteFreeModelTurn(inputTokens, breakdown, outputTokens, coder) {
8990
+ async function noteFreeModelTurn(inputTokens, breakdown, outputTokens, coder, aux = null) {
8986
8991
  try {
8987
8992
  const fm = await import("./free-model.mjs");
8988
- if (!freeModel || !fm.isFreeServer(freeModel, coder?.url) || !(inputTokens > 0)) return;
8989
- const cache = readTurnCache(breakdown) ?? { cached: 0, cacheReported: false };
8990
- freeModel = fm.addTurn(freeModel, { input: inputTokens, cached: cache.cached, cacheReported: cache.cacheReported, output: outputTokens ?? 0 }, new Date(), coder?.model, coder?.url);
8993
+ if (!freeModel) return;
8994
+ const before = freeModel;
8995
+ if (fm.isFreeServer(freeModel, coder?.url) && inputTokens > 0) {
8996
+ const cache = readTurnCache(breakdown) ?? { cached: 0, cacheReported: false };
8997
+ freeModel = fm.addTurn(freeModel, { input: inputTokens, cached: cache.cached, cacheReported: cache.cacheReported, output: outputTokens ?? 0 }, new Date(), coder?.model, coder?.url);
8998
+ }
8999
+ // GH #501: the chat model's calls (and every other non-coder call) on the free model's key.
9000
+ freeModel = fm.addAuxCalls(freeModel, aux, new Date());
9001
+ if (freeModel === before) return;
8991
9002
  fm.writeState(freeModelDir(), freeModel);
8992
9003
  const n = fm.notice(freeModel, new Date(), coder?.url);
8993
9004
  const noticeKey = `${freeModel.period}:${fm.slotFor(freeModel, coder?.url).extra ?? "main"}:${n?.level}`;
@@ -12686,6 +12697,8 @@ const wrapThought = (s, width, maxLines) => {
12686
12697
  * ("keep in cache until the user type gu").
12687
12698
  */
12688
12699
  let scaffoldNotice = null;
12700
+ /** A token was saved this run (pasted, trial or promo): the startup "isn't linked to your gu account yet" notice is then stale. */
12701
+ let cliTokenSavedThisRun = false;
12689
12702
 
12690
12703
  async function checkPromptScaffoldAtStart() {
12691
12704
  const tl = await import("./terminal-layout.mjs");
@@ -12733,6 +12746,7 @@ function announceScaffold() {
12733
12746
  if (listPickerActive || askWaiting || !inputVisible) return; // as announceCliUpdate (GH #397)
12734
12747
  const { kind, text } = scaffoldNotice;
12735
12748
  scaffoldNotice = null;
12749
+ if (kind === "link" && cliTokenSavedThisRun) return; // asked before the token existed; it exists now
12736
12750
  if (kind === "link") {
12737
12751
  // A setup step, said calmly (#292): the headline, then the steps on their own lines.
12738
12752
  // ONE yellow line (#222): the steps are the token question's own, behind "?" there.
@@ -12807,6 +12821,9 @@ async function askForCliTokenInner(ct, dir, why, overLimit = false, short = "")
12807
12821
  overLimit, // #209: the computer limit, not a missing plan — no "paste a Pro token"
12808
12822
  short, // #219: the one short yellow line; the rest is behind "?"
12809
12823
  onSupport: () => runSupport(), // #250: "/support" or the footer link, before there is a token
12824
+ // A free-model promo code needs no token and no Pro plan: typed in this row, it gives the computer a token.
12825
+ redeemPromo: async (code) => ct.redeemPromo({ hostedBase, device: await ct.thisDevice({ instanceId: myInstanceId || "" }).catch(() => null), code }),
12826
+ promoFirst: voucherAtStart,
12810
12827
  // #315: a token is only good if THIS computer may use it — renew it from here (the server then
12811
12828
  // says how much free time the computer has), save what came back, and run the licence rule.
12812
12829
  accept: async (token) => {
@@ -12828,6 +12845,17 @@ async function askForCliTokenInner(ct, dir, why, overLimit = false, short = "")
12828
12845
  if (r.ok) {
12829
12846
  licenceBlock = null; // the row only lets an entitled token through
12830
12847
  licenceDecided = true;
12848
+ cliTokenSavedThisRun = true;
12849
+ if (scaffoldNotice?.kind === "link") scaffoldNotice = null;
12850
+ }
12851
+ // "Enter alone starts the free trial" at the promo row IS the answer to "do you have a code": do not ask for one again.
12852
+ if (r.ok && r.kind === "trial" && voucherAtStart) voucherAtStart = false;
12853
+ if (r.ok && r.kind === "promo") {
12854
+ // The code was the answer to "Free model": set that model up now — the later "Voucher code" question is moot.
12855
+ voucherAtStart = false;
12856
+ const st = await ct.readState(dir);
12857
+ await setUpFreeModel({ token: st.token, announce: true });
12858
+ console.log("");
12831
12859
  }
12832
12860
  void refreshCliToken(); // the bar's line, now that there is a token to describe
12833
12861
  return r.ok;
@@ -13112,6 +13140,7 @@ async function runAgentTurn(history, { attachJobId = "", ownJob = false } = {})
13112
13140
  // in/out figures would sit there, looking live, until the first poll reports real numbers.
13113
13141
  lastTurnInputTokens = 0;
13114
13142
  lastTurnOutputTokens = 0;
13143
+ lastTurnAux = null;
13115
13144
  // First few KB of the raw stream as consumed — a cheap fingerprint to verify the
13116
13145
  // completed resultText really EXTENDS what we streamed (an old worker replaces it
13117
13146
  // with the shorter bare answer, which must not be sliced by shownChars).
@@ -14145,6 +14174,13 @@ async function runAgentTurn(history, { attachJobId = "", ownJob = false } = {})
14145
14174
  }
14146
14175
  // Task #142: the newest request's prompt breakdown. NOT monotonic — it is a snapshot of
14147
14176
  // what is in the context right now, so it must be allowed to shrink when a trim lands.
14177
+ // GH #501: the turn's other model calls ride the breakdown as `aux`; they are not part of
14178
+ // the context snapshot, and a turn with no coder step sends a breakdown of `aux` alone.
14179
+ if (job.agentPromptBreakdown && typeof job.agentPromptBreakdown === "object" && "aux" in job.agentPromptBreakdown) {
14180
+ lastTurnAux = job.agentPromptBreakdown.aux;
14181
+ const { aux: _aux, ...rest } = job.agentPromptBreakdown;
14182
+ job.agentPromptBreakdown = Object.keys(rest).length ? rest : null;
14183
+ }
14148
14184
  if (job.agentPromptBreakdown && typeof job.agentPromptBreakdown === "object") {
14149
14185
  lastPromptBreakdown = job.agentPromptBreakdown;
14150
14186
  liveStepTokens = readStepTokens(job.agentPromptBreakdown);
@@ -16180,7 +16216,7 @@ async function main() {
16180
16216
  lastTurnTotalOutput = outputTokens ?? 0;
16181
16217
  // #323: what this turn's prompt tokens cost — on the token row and in /price.
16182
16218
  void noteTurnCost(lastTurnInputTokens, lastPromptBreakdown, turnCoder);
16183
- void noteFreeModelTurn(lastTurnInputTokens, lastPromptBreakdown, lastTurnOutputTokens, turnCoder);
16219
+ void noteFreeModelTurn(lastTurnInputTokens, lastPromptBreakdown, lastTurnOutputTokens, turnCoder, lastTurnAux);
16184
16220
  // A turn that FAILED carries the __TURN_FAILED__:: sentinel: the worker still delivers
16185
16221
  // the text (both UIs need to show it), but it is a failure notice, not a reply. Print
16186
16222
  // it as one and DROP it — persisting it would re-send "⚠️ your account is suspended" to
package/model-prices.mjs CHANGED
@@ -26,6 +26,7 @@ const ANTHROPIC = "https://platform.claude.com/docs/en/about-claude/pricing";
26
26
  const OPENAI = "https://developers.openai.com/api/docs/pricing";
27
27
  const KIMI = "https://platform.kimi.ai/docs/pricing/chat";
28
28
  const OLLAMA = "https://ollama.com/pricing";
29
+ const GOOGLE = "https://aistudio.google.com/docs/pricing";
29
30
  const CHECKED = "2026-10-01";
30
31
 
31
32
  /** [host, model, input, cachedInput, output, cacheWrite?] — USD per 1M tokens. */
@@ -79,9 +80,14 @@ const ROWS = [
79
80
  ["ollama.com", "nemotron-3-nano", 0.06, null, 0.24],
80
81
  ["ollama.com", "nemotron-3-super", 0.015, 0.015, 0.6],
81
82
  ["ollama.com", "nemotron-3-ultra", 0.1, 0.1, 3],
83
+ // Google AI Studio (Gemini API, paid tier, standard). Output includes thinking. Cached-input prices
84
+ // are not published in what was checked, so null = no discount (never an invented number).
85
+ // gemini-3.8-flash: $0.75 / $3.75 until 2026-12-31, then $1.50 / $7.50 — update this row on 2027-01-01.
86
+ ["generativelanguage.googleapis.com", "gemini-3.8-flash", 0.75, null, 3.75],
87
+ ["generativelanguage.googleapis.com", "gemini-4-hydrogen", 1.5, null, 7.5],
82
88
  ];
83
- const PROVIDER = { "api.anthropic.com": "Anthropic", "api.openai.com": "OpenAI", "api.moonshot.ai": "Moonshot (Kimi)", "ollama.com": "Ollama cloud" };
84
- const SOURCE = { "api.anthropic.com": ANTHROPIC, "api.openai.com": OPENAI, "api.moonshot.ai": KIMI, "ollama.com": OLLAMA };
89
+ const PROVIDER = { "api.anthropic.com": "Anthropic", "api.openai.com": "OpenAI", "api.moonshot.ai": "Moonshot (Kimi)", "ollama.com": "Ollama cloud", "generativelanguage.googleapis.com": "Google (Gemini)" };
90
+ const SOURCE = { "api.anthropic.com": ANTHROPIC, "api.openai.com": OPENAI, "api.moonshot.ai": KIMI, "ollama.com": OLLAMA, "generativelanguage.googleapis.com": GOOGLE };
85
91
 
86
92
  /** The table gu ships — what an empty Mongo is seeded with and what the Deploy app exports. */
87
93
  export const PRICE_TABLE = Object.freeze({
@@ -150,20 +150,20 @@ export function startMenu({ presets = 0 } = {}) {
150
150
  return [
151
151
  "How do you want to start?",
152
152
  " 1 I have a key — Claude, DeepSeek, OpenAI, Qwen, Kimi…",
153
- " 2 Free model — I have a code from gucli.com",
153
+ " 2 Use promo code — I have a code from gucli.com",
154
154
  " 3 My own model — Ollama on this machine, or another server (Enter)",
155
155
  " 4 Later — set it up with /model",
156
156
  ...(presets > 0 ? [` 5 Load a saved preset (${presets} saved)`] : []),
157
157
  ];
158
158
  }
159
159
 
160
- /** An answer to startMenu → "key" | "free" | "own" | "later" | "preset", or null to ask again. */
160
+ /** An answer to startMenu (2 = "Use promo code": a promo code is not always free) → "key" | "free" | "own" | "later" | "preset", or null to ask again. */
161
161
  export function parseStartChoice(raw) {
162
162
  if (raw === SKIP_ALL) return "later";
163
163
  const t = String(raw ?? "").trim().toLowerCase();
164
164
  if (t === "" || t === "3" || t === "own" || t === "ollama" || t === "o") return "own";
165
165
  if (t === "1" || t === "key" || t === "k") return "key";
166
- if (t === "2" || t === "free" || t === "f" || t === "code") return "free";
166
+ if (t === "2" || t === "promo" || t === "free" || t === "f" || t === "code" || t === "c") return "free";
167
167
  if (t === "4" || t === "later" || t === "l" || t === "s" || t === "skip" || t === "n" || t === "no" || t === "-") return "later";
168
168
  if (t === "5" || t === "preset" || t === "p") return "preset";
169
169
  return null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiens.nguyen/gu-cli",
3
- "version": "1.0.918",
3
+ "version": "1.0.920",
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",
@@ -119,6 +119,7 @@
119
119
  "scripts/image-paste-check.mjs",
120
120
  "rag-job-config.mjs",
121
121
  "completed-flush.mjs",
122
+ "stream-think-tags.mjs",
122
123
  "verbose-lines.mjs",
123
124
  "banner-name.mjs",
124
125
  "agent-model-label.mjs",
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Remove literal <think> / </think> tags from the raw model token stream (GH #498).
3
+ *
4
+ * gu wraps a turn's work in ONE <think>…</think> block, and everything after the first </think>
5
+ * is the answer (answerFrom, splitLiveStream). The raw model stream is written inside that block,
6
+ * so a model that types the tag itself closes it early: DeepSeek V4.1 Flash on ollama.com put its
7
+ * reasoning in `content` and ended it with "</think>", and the rest of the turn's work (Thought,
8
+ * <code>, ~~~ fences, "Running →" lines) printed as the reply.
9
+ *
10
+ * Tags can arrive split across chunks ("</th" + "ink>"), so a tail that could still become a tag
11
+ * is held back until the next chunk decides it; flush() returns whatever is still held.
12
+ * Pure and separate from gu-cli.mjs so it can be tested.
13
+ */
14
+ const TAG_RE = /<\/?think>/gi;
15
+ const TAGS = ["<think>", "</think>"];
16
+
17
+ /** Length of the longest tail of `s` that is a proper prefix of a tag (0 if none). */
18
+ function heldTail(s) {
19
+ const low = s.slice(-8).toLowerCase();
20
+ for (let n = Math.min(low.length, 7); n > 0; n--) {
21
+ const tail = low.slice(-n);
22
+ if (TAGS.some((t) => t.length > n && t.startsWith(tail))) return n;
23
+ }
24
+ return 0;
25
+ }
26
+
27
+ export function createThinkTagScrubber() {
28
+ let carry = "";
29
+ return {
30
+ /** Text safe to show now; a possible partial tag at the end is kept for the next call. */
31
+ push(text) {
32
+ const s = (carry + String(text ?? "")).replace(TAG_RE, "");
33
+ const n = heldTail(s);
34
+ carry = n ? s.slice(-n) : "";
35
+ return n ? s.slice(0, -n) : s;
36
+ },
37
+ /** Whatever is still held (an unfinished tag start is just text after all). */
38
+ flush() {
39
+ const s = carry;
40
+ carry = "";
41
+ return s;
42
+ },
43
+ };
44
+ }