@tiens.nguyen/gu-cli 1.0.930 → 1.0.931

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
@@ -28,7 +28,7 @@
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
+ import { readFileSync, writeFileSync, mkdirSync, unlinkSync } from "node:fs";
32
32
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
33
33
  import { hostname as osHostname, userInfo } from "node:os";
34
34
  import { dirname, join } from "node:path";
@@ -53,6 +53,53 @@ export function guHeaders(mode, version = GU_VERSION) {
53
53
  };
54
54
  }
55
55
 
56
+ /**
57
+ * An OPT-IN label for OUR OWN machines (e.g. the Windows 11 test VM). Set GU_INTERNAL_LABEL=gu-win11, or put the
58
+ * label in ~/.gonext/internal-label. Real users have neither, so nothing changes for them. When set, every request
59
+ * gu makes to a gucli.com host carries `User-Agent: gu/<version> (internal:<label>)` and `x-gu-internal: <label>`,
60
+ * so Cloudflare analytics (filter on User-Agent) and the API can tell our traffic from real users'.
61
+ */
62
+ export function internalLabel(env = process.env, home = process.env.HOME || process.env.USERPROFILE || "") {
63
+ let v = String(env.GU_INTERNAL_LABEL ?? "").trim();
64
+ if (!v && home) {
65
+ try { v = readFileSync(join(home, ".gonext", "internal-label"), "utf8").trim(); } catch { /* none */ }
66
+ }
67
+ return v.replace(/[^A-Za-z0-9._-]/g, "").slice(0, 40);
68
+ }
69
+
70
+ /** `gu internal [label|off]`: writes (or removes) ~/.gonext/internal-label. No label → this computer's host name. */
71
+ export function setInternalLabel(arg, { home = process.env.HOME || process.env.USERPROFILE || "", host = osHostname() } = {}) {
72
+ const file = join(home, ".gonext", "internal-label");
73
+ if (String(arg ?? "").toLowerCase() === "off") {
74
+ try { unlinkSync(file); } catch { /* already off */ }
75
+ return { label: "", file };
76
+ }
77
+ const label = String(arg || host).replace(/[^A-Za-z0-9._-]/g, "").slice(0, 40);
78
+ mkdirSync(dirname(file), { recursive: true });
79
+ writeFileSync(file, label + "\n", "utf8");
80
+ return { label, file };
81
+ }
82
+
83
+ /** Patches fetch (once) so requests to gucli.com hosts carry the internal label. No label → does nothing. */
84
+ export function installInternalLabel({ label = internalLabel(), version = GU_VERSION, target = globalThis } = {}) {
85
+ if (!label || target.__guInternalLabel) return false;
86
+ const orig = target.fetch;
87
+ target.fetch = (input, init = {}) => {
88
+ try {
89
+ const url = new URL(typeof input === "string" ? input : input?.url ?? String(input));
90
+ if (/(^|\.)gucli\.com$/i.test(url.hostname)) {
91
+ const h = new Headers(init.headers ?? (typeof input === "object" ? input.headers : undefined));
92
+ h.set("user-agent", `gu/${version || "0"} (internal:${label})`);
93
+ h.set("x-gu-internal", label);
94
+ init = { ...init, headers: h };
95
+ }
96
+ } catch { /* not a URL: pass through */ }
97
+ return orig(input, init);
98
+ };
99
+ target.__guInternalLabel = label;
100
+ return true;
101
+ }
102
+
56
103
  /** The public half of the API's CLI_TOKEN_PRIVATE_KEY, base64 SPKI DER (Ed25519). Generated 2026-09-17. */
57
104
  export const EMBEDDED_PUBLIC_KEY = "MCowBQYDK2VwAyEA2xkKnY+xWGoS4Nvc7DEHCCurdQQYZGl/x7kPp+gDmvY=";
58
105
 
package/free-model.mjs CHANGED
@@ -133,6 +133,26 @@ export function priceForModel(state, model) {
133
133
  };
134
134
  }
135
135
 
136
+ /**
137
+ * GH #533: the price row the BAR uses for a turn on the free model's server when the price table has no row
138
+ * for the model (a model the person picked on the promo key, say qwen3.7-plus). It is exactly what the
139
+ * allowance is charged (priceForModel: the model's own, else the dearest listed), in model-prices.mjs units
140
+ * (USD per 1M prompt tokens) — so the bar no longer says "no price" for a turn that was charged. → null when
141
+ * `url` is not the free model's server or the promo lists no price at all.
142
+ */
143
+ export function freeModelPriceRow(state, url, model) {
144
+ if (!isFreeServer(state, url)) return null;
145
+ const p = priceForModel(state, model);
146
+ const input = Number(p?.inputPerM);
147
+ if (p?.inputPerM == null || !Number.isFinite(input) || input < 0) return null;
148
+ const cached = Number(p?.cachedPerM);
149
+ return {
150
+ input,
151
+ ...(p?.cachedPerM != null && Number.isFinite(cached) ? { cachedInput: cached } : {}),
152
+ promo: Boolean(state?.models?.[model]) ? "listed" : "dearest",
153
+ };
154
+ }
155
+
136
156
  /** After a turn on the free model (on `model`, one of its list): the new state. */
137
157
  export function addTurn(state, usage, now = new Date(), model = "", url = "") {
138
158
  const s = current(state, now);
@@ -2518,6 +2518,23 @@ _scaffold_problem = _psc.scaffold_problem
2518
2518
  _SCAFFOLD_REQUIRED = _psc.SCAFFOLD_REQUIRED
2519
2519
 
2520
2520
 
2521
+ # Cloudflare (in front of gucli.com since 2 Nov 2026) refuses Python's default "Python-urllib/x"
2522
+ # client name with error 1010 before the API sees the request. Every direct call to the gu service
2523
+ # names itself instead; the default API host (chat-api-v2) is not behind Cloudflare, gucli.com is.
2524
+ def _internal_label() -> str:
2525
+ """Our own machines only: GU_INTERNAL_LABEL or ~/.gonext/internal-label (real users have neither)."""
2526
+ v = os.environ.get("GU_INTERNAL_LABEL", "").strip()
2527
+ if not v:
2528
+ try:
2529
+ v = open(os.path.join(os.path.expanduser("~"), ".gonext", "internal-label"), encoding="utf-8").read().strip()
2530
+ except OSError:
2531
+ v = ""
2532
+ return re.sub(r"[^A-Za-z0-9._-]", "", v)[:40]
2533
+
2534
+
2535
+ _GU_UA = "gu-agent/1.0 (+https://gucli.com" + (f"; internal:{_internal_label()}" if _internal_label() else "") + ")"
2536
+
2537
+
2521
2538
  def _load_prompt_scaffold(api_base: str, worker_key: str):
2522
2539
  """The scaffold for this turn → (template, version, source).
2523
2540
 
@@ -2573,7 +2590,7 @@ def _fetch_prompt_scaffold(api_base: str, worker_key: str, name: str = "code-age
2573
2590
  from urllib.parse import urlencode
2574
2591
  req = urllib.request.Request(
2575
2592
  f"{base}/api/worker/prompt-scaffold?{urlencode({'name': name})}",
2576
- headers={"X-Worker-Key": worker_key}, method="GET")
2593
+ headers={"X-Worker-Key": worker_key, "User-Agent": _GU_UA}, method="GET")
2577
2594
  try:
2578
2595
  with urllib.request.urlopen(req, timeout=15, context=_ssl_context()) as resp:
2579
2596
  data = json.loads(resp.read().decode("utf-8", "replace") or "{}")
@@ -4519,7 +4536,7 @@ def _fetch_cloud_limits(api_base: str, timeout: float = 5.0) -> int:
4519
4536
  if not base:
4520
4537
  return 0
4521
4538
  try:
4522
- req = urllib.request.Request(f"{base}/api/model-limits", method="GET")
4539
+ req = urllib.request.Request(f"{base}/api/model-limits", method="GET", headers={"User-Agent": _GU_UA})
4523
4540
  with urllib.request.urlopen(req, timeout=timeout, context=_ssl_context()) as resp:
4524
4541
  data = json.loads(resp.read().decode("utf-8", "replace") or "{}")
4525
4542
  except Exception as e: # noqa: BLE001
@@ -7539,7 +7556,7 @@ def _rag_resolve_embed_api_key(api_base: str, worker_key: str, job_id: str = "")
7539
7556
  from urllib.parse import urlencode
7540
7557
  req = urllib.request.Request(
7541
7558
  f"{base}/api/worker/coding-key?{urlencode({'role': 'embed', 'backendId': 'embed-ollama', **({'jobId': job_id} if job_id else {})})}",
7542
- headers={"X-Worker-Key": worker_key}, method="GET")
7559
+ headers={"X-Worker-Key": worker_key, "User-Agent": _GU_UA}, method="GET")
7543
7560
  with urllib.request.urlopen(req, timeout=8, context=_ssl_context()) as resp:
7544
7561
  data = json.loads(resp.read().decode("utf-8", "replace") or "{}")
7545
7562
  return (data.get("apiKey") or "").strip()
package/gu-cli.mjs CHANGED
@@ -14,6 +14,8 @@
14
14
  import { localModeNodeProblem, requireSupportedNode } from "./node-version.mjs";
15
15
  // The brand accent, shared with the REPL — see accent.mjs.
16
16
  import { accent } from "./accent.mjs";
17
+ import { installInternalLabel } from "./cli-token.mjs";
18
+ installInternalLabel(); // our own machines only (GU_INTERNAL_LABEL / ~/.gonext/internal-label)
17
19
  import { paint } from "./theme.mjs";
18
20
  requireSupportedNode();
19
21
  import { mkdir, mkdtemp, readFile, rm, stat, unlink, writeFile } from "node:fs/promises";
package/gu-repl.mjs CHANGED
@@ -24,6 +24,8 @@
24
24
  * Commands: /exit /model /new /help Ctrl-C stops following the current run.
25
25
  */
26
26
  import { RELAUNCHED } from "./gu-relaunch.mjs"; // FIRST: may replace this process (#358)
27
+ import { installInternalLabel } from "./cli-token.mjs";
28
+ installInternalLabel(); // our own machines only (GU_INTERNAL_LABEL / ~/.gonext/internal-label): label gucli.com requests
27
29
  import { readFile, mkdir, writeFile, unlink, rename } from "node:fs/promises";
28
30
  import { readStepTokens, readTurnCache } from "./step-tokens.mjs";
29
31
  import { snapshotInput, restoreInput, replaceStoppedQuestion, restoredQuestionLetGo, stopNoteLines } from "./turn-stop.mjs";
@@ -647,6 +649,14 @@ if (argv.includes("--version") || argv[0] === "version") {
647
649
  console.log(REPL_VERSION);
648
650
  process.exit(0);
649
651
  }
652
+ // `gu internal [label|off]` — marks THIS computer as one of ours (the Windows test VM) so Cloudflare can tell it
653
+ // from real users. One word, no env vars. No label = the computer's host name. Hidden: not in the help list.
654
+ if (argv[0] === "internal") {
655
+ const { setInternalLabel } = await import("./cli-token.mjs");
656
+ const r = setInternalLabel(argv[1]);
657
+ console.log(r.label ? `This computer is marked as ours: "${r.label}". gu's requests to gucli.com now say so.` : "This computer is no longer marked as ours.");
658
+ process.exit(0);
659
+ }
650
660
  const cliVerdict = classifyCliArg(argv, CLI_SUBCOMMANDS);
651
661
  if (cliVerdict.kind === "unknown") {
652
662
  console.error(red(`gu: unknown command "${cliVerdict.typed}"`));
@@ -8943,7 +8953,14 @@ async function noteTurnCost(inputTokens, breakdown, coder = null) {
8943
8953
  const rows = await loadPrices();
8944
8954
  const url = coder?.url ?? activeCodingUrl();
8945
8955
  const model = coder?.model ?? activeCodingModelId();
8946
- const price = mp.findPrice(rows, url, model);
8956
+ // GH #533: on the free model's key the allowance charges the PROMO's price (its own, else the dearest
8957
+ // listed) — the bar shows that, even when the published table has a (pay-as-you-go estimate) row too.
8958
+ let price = null;
8959
+ if (freeModel) {
8960
+ const fm = await import("./free-model.mjs");
8961
+ price = fm.freeModelPriceRow(freeModel, url, model);
8962
+ }
8963
+ price ??= mp.findPrice(rows, url, model);
8947
8964
  const cache = readTurnCache(breakdown) ?? { cached: 0, cacheReported: false, firstIn: 0 };
8948
8965
  const c = mp.turnCost({ input: inputTokens, ...cache, price });
8949
8966
  if (!c) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiens.nguyen/gu-cli",
3
- "version": "1.0.930",
3
+ "version": "1.0.931",
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",