@tiens.nguyen/gu-cli 1.0.932 → 1.0.936

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
@@ -732,7 +732,7 @@ export async function redeemPromo({ hostedBase, device, code, fetchImpl = fetch,
732
732
  * trial (no account) or an account. Returns { ok: true, days, token } — the token already carries the
733
733
  * extra days — or { ok: false, why, error } where error is the service's own sentence. Never throws.
734
734
  */
735
- export async function redeemVoucher({ mode, apiBase, hostedBase, token, device, code, fetchImpl = fetch, timeoutMs = 8000 }) {
735
+ export async function redeemVoucher({ mode, apiBase, hostedBase, token, device, code, ageConfirmed = false, fetchImpl = fetch, timeoutMs = 8000 }) {
736
736
  const base = String(mode === "expert" ? hostedBase : apiBase || hostedBase).replace(/\/+$/, "");
737
737
  if (!token) return { ok: false, why: "no-token", error: "This computer has no gu token yet — restart gu to get the free trial, then try again." };
738
738
  if (!base) return { ok: false, why: "no-api", error: "No gu service address is set on this computer." };
@@ -740,7 +740,8 @@ export async function redeemVoucher({ mode, apiBase, hostedBase, token, device,
740
740
  const res = await fetchImpl(`${base}/api/billing/cli-token/voucher`, {
741
741
  method: "POST",
742
742
  headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
743
- body: JSON.stringify({ code: String(code ?? ""), ...(device ? { device } : {}) }),
743
+ // GH #567: a gu + Gemini code is sent again with ageConfirmed once the person said they are 18 or older.
744
+ body: JSON.stringify({ code: String(code ?? ""), ...(device ? { device } : {}), ...(ageConfirmed ? { ageConfirmed: true } : {}) }),
744
745
  signal: AbortSignal.timeout(timeoutMs),
745
746
  });
746
747
  const data = await res.json().catch(() => null);
@@ -748,7 +749,7 @@ export async function redeemVoucher({ mode, apiBase, hostedBase, token, device,
748
749
  const error = typeof data?.error === "string" && data.error
749
750
  ? data.error
750
751
  : res.status === 404 ? "This gu service does not take vouchers yet." : `The gu service answered HTTP ${res.status}.`;
751
- return { ok: false, why: typeof data?.why === "string" ? data.why : `http-${res.status}`, error };
752
+ return { ok: false, why: typeof data?.why === "string" ? data.why : `http-${res.status}`, error, ...(Number(data?.months) ? { months: Number(data.months) } : {}) };
752
753
  }
753
754
  return {
754
755
  ok: true,
@@ -756,6 +757,8 @@ export async function redeemVoucher({ mode, apiBase, hostedBase, token, device,
756
757
  token: typeof data?.token === "string" ? data.token : "",
757
758
  // #557: a free-model code carries a monthly allowance, not days.
758
759
  ...(data?.kind === "model-tokens" ? { kind: "model-tokens", centsPerMonth: Number(data.centsPerMonth ?? 0), months: Number(data.months ?? 0) } : {}),
760
+ // GH #567: gu + Gemini — months of the subscription; Google sets the project up, then the preset carries Gemini.
761
+ ...(data?.kind === "gemini" ? { kind: "gemini", months: Number(data.months ?? 0), paidUntil: typeof data.paidUntil === "string" ? data.paidUntil : "" } : {}),
759
762
  };
760
763
  } catch (e) {
761
764
  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." };
@@ -236,6 +236,10 @@ export function localDbChoice({ env = process.env, saved = "", nodeVersion = pro
236
236
  */
237
237
  export async function openLocalStore({ apiDir, mongoUri = localMongoUri(), dbName = LOCAL_DB_NAME, localDb = readLocalDb(), home = homedir(), timeoutMs = 8000 } = {}) {
238
238
  if (localDb === "gudb") {
239
+ // GH #564: Node 22 calls node:sqlite (gudb's engine) experimental — a line on gu's screen nobody can act on.
240
+ const emitWarning = process.emitWarning;
241
+ process.emitWarning = (w, ...rest) =>
242
+ /sqlite/i.test(String(w?.message ?? w)) ? undefined : emitWarning.call(process, w, ...rest);
239
243
  const { GudbDb } = await import(pathToFileURL(join(apiDir, "gudb", "db.js")).href);
240
244
  const g = new GudbDb(gudbFile(home));
241
245
  return { db: g, close: async () => g.close() };
@@ -1823,3 +1823,87 @@ export function localModeDoneText({ localDb, dbFile, apiLog, cyan = (t) => t, bo
1823
1823
  dim(`\n ${apiLog}\n`)
1824
1824
  );
1825
1825
  }
1826
+
1827
+ /**
1828
+ * THE INSTALLER FINISHES THE WORK THAT NEEDS NO ANSWER (GH #561).
1829
+ *
1830
+ * Measured on a new Windows 11 PC: the installer said "Ready", and the first `gu` then spent ~8 minutes
1831
+ * installing before its first question — Python, pip, the API and its dependencies, starting the API. None of
1832
+ * that asks anything. Done here, at install time (when people expect to wait), the first `gu` reuses all of it:
1833
+ * setup's "already downloaded", "dependencies installed", "worker key reused" and "API answering" paths.
1834
+ *
1835
+ * What it NEVER does: write worker.env (the first `gu` must still run its first-run questions — mode, license,
1836
+ * promo code, models), use MongoDB (that path asks questions), or install a permanent service. The API it starts
1837
+ * is the same detached process setup starts; after a reboot gu starts it again on its own (tryStartLocalApi).
1838
+ *
1839
+ * → { done: [lines said], skipped: "" | why, ok: boolean }. Never throws.
1840
+ */
1841
+ export async function prepareLocalStack({ log = (l) => console.log(l), env = process.env, start = true } = {}) {
1842
+ const done = [];
1843
+ const say = (l) => {
1844
+ done.push(l);
1845
+ log(l);
1846
+ };
1847
+ const skip = (why) => ({ done, skipped: why, ok: true });
1848
+ try {
1849
+ const { existsSync } = await import("node:fs");
1850
+ if (existsSync(join(homedir(), ".gonext", "worker.env"))) return skip("this computer is already set up");
1851
+ if (String(env.GU_LICENSE ?? "").trim()) return skip("a license was given — the mode is chosen at the first gu");
1852
+ const machine = await probeMachine();
1853
+ const gate = clientExpertAvailable({ workerEnvExists: false, ...machine });
1854
+ if (!gate.available) return skip(gate.message);
1855
+ if (localModeNodeProblem(process.version, machine.platform, { nvmVersions: nvmNodeVersions() })) {
1856
+ return skip("this Node.js is too old for the built-in database");
1857
+ }
1858
+ let manifest;
1859
+ try {
1860
+ manifest = await fetchLatestApi();
1861
+ } catch (e) {
1862
+ return { done, skipped: `the API index could not be reached (${e.message}) — the first gu does it`, ok: false };
1863
+ }
1864
+ let state = await loadState();
1865
+ const dbChoice = localDbChoice({
1866
+ saved: readLocalDb(),
1867
+ latestApi: String(manifest?.version ?? ""),
1868
+ mongoAlreadySetUp: state.mongo === "done" && state.localDb !== "gudb",
1869
+ });
1870
+ if (dbChoice.kind !== "gudb") return skip(`the database needs MongoDB here (${dbChoice.why}) — the first gu asks about it`);
1871
+
1872
+ if (!(await probeApiInstall(manifest.version)).installed) {
1873
+ log(` Downloading the API (${manifest.version}) …`);
1874
+ await downloadApiPackage(manifest, {});
1875
+ }
1876
+ const apiDir = apiInstallDir(manifest.version);
1877
+ if (!(await apiHasGudb(apiDir))) return { done, skipped: "this API package has no built-in database", ok: false };
1878
+ if (!(await apiDepsInstalled(apiDir))) {
1879
+ log(" Installing the API's dependencies … (about a minute)");
1880
+ await installApiDeps(apiDir, {});
1881
+ }
1882
+ say(` ✓ API ${manifest.version} downloaded, with its dependencies`);
1883
+ await writeLocalDb("gudb");
1884
+ const creds = await seedDatabase({
1885
+ apiDir, userId: state.localUserId, workerKey: state.localWorkerKey, localDb: "gudb",
1886
+ });
1887
+ state = { ...state, localDb: "gudb", localUserId: creds.userId, localWorkerKey: creds.workerKey };
1888
+ state = recordStep(recordStep(state, "api-files", "done"), "database", "done");
1889
+ await saveState(state);
1890
+ say(` ✓ Database ready — built in, one file: ${gudbFile()}`);
1891
+ if (!start) return { done, skipped: "", ok: true };
1892
+ let health = await probeLocalApi(LOCAL_API_PORT);
1893
+ if (!health.ok) {
1894
+ // GH #564: 4100 may be another program's (task #337) — move off it first, as the first gu does,
1895
+ // or "started" would be said while gu's API never opened its port.
1896
+ const settled = await settleApiPort({ log: (l) => log(l) });
1897
+ if (settled.refused) return { done, skipped: `port ${LOCAL_API_PORT} is in use — the first gu says what to do`, ok: false };
1898
+ await startLocalApi({ apiDir, log: (l) => log(l) });
1899
+ health = await waitForApi({ port: LOCAL_API_PORT });
1900
+ }
1901
+ if (!health.ok) {
1902
+ return { done, skipped: `the API did not answer (${health.why}) — see ${API_LOG_FILE}; the first gu tries again`, ok: false };
1903
+ }
1904
+ say(` ✓ API started and answering on http://127.0.0.1:${LOCAL_API_PORT}`);
1905
+ return { done, skipped: "", ok: true };
1906
+ } catch (e) {
1907
+ return { done, skipped: `${e instanceof Error ? e.message : e} — the first gu does the rest`, ok: false };
1908
+ }
1909
+ }
@@ -241,6 +241,8 @@ export const ANTHROPIC_VERSION = "2023-06-01";
241
241
  * so ensureV1Root leaves a "/v1beta/openai" root as it is. Still "beta" on Google's side.
242
242
  */
243
243
  export const GEMINI_API_URL = "https://generativelanguage.googleapis.com/v1beta/openai";
244
+ /** GH #570: OpenRouter, OpenAI-compatible; model ids carry the company ("deepseek/deepseek-v4-pro"). */
245
+ export const OPENROUTER_API_URL = "https://openrouter.ai/api/v1";
244
246
 
245
247
  export function isAnthropicUrl(url) {
246
248
  try {
@@ -300,6 +302,9 @@ export function providerPresets(role = "coding") {
300
302
  { name: "DeepSeek", url: "https://api.deepseek.com/v1", roles: ["coding", "agent"] },
301
303
  // #132. Ollama's cloud speaks Ollama's own API (/api/tags), so the preset names its dialect.
302
304
  { name: "Ollama cloud", url: "https://ollama.com", dialect: "ollama", roles: ["coding", "agent"] },
305
+ // GH #570: one key for many companies' models (DeepSeek, Qwen, Claude…), ids like "deepseek/deepseek-v4-pro".
306
+ // OpenAI-compatible, /api/v1. Not for the embedder until its /embeddings is tested live.
307
+ { name: "OpenRouter", url: OPENROUTER_API_URL, roles: ["coding", "agent"] },
303
308
  // Qwen's two plans take DIFFERENT keys (Token Plan sk-sp-..., pay-as-you-go sk-ws-...), so the
304
309
  // plan is in the name. Both are OpenAI-compatible and already carry their /compatible-mode/v1 path.
305
310
  { name: "Qwen Token Plan (OpenAI-compatible)", url: "https://token-plan.maas.qwencloudapi.com/compatible-mode/v1", roles: ["coding", "agent"] },
@@ -330,11 +335,33 @@ export function detectProvider(key, presets = providerPresets("coding")) {
330
335
  if (/^AQ\.[0-9A-Za-z_-]{40,}$/.test(k)) return by("Google AI Studio (Gemini)");
331
336
  if (k.startsWith("sk-sp-")) return by("Qwen Token Plan (OpenAI-compatible)");
332
337
  if (k.startsWith("sk-ws-")) return by("Qwen pay-as-you-go (OpenAI-compatible)");
338
+ // OpenRouter: "sk-or-v1-" + 64 hex digits (GH #570); checked before the bare "sk-" shapes below.
339
+ if (/^sk-or-v1-[0-9a-f]{64}$/.test(k)) return by("OpenRouter");
333
340
  if (k.startsWith("sk-proj-") || k.startsWith("sk-svcacct-")) return by("OpenAI");
334
341
  if (/^sk-[0-9a-f]{32}$/.test(k)) return by("DeepSeek");
335
342
  return null;
336
343
  }
337
344
 
345
+ /**
346
+ * GH #570: a long list of "company/model" ids (OpenRouter's) grouped by company, for a two-step pick → [{ name, ids }]
347
+ * sorted by name, or null when the list is short or not shaped that way (then it is shown as one list). Pure.
348
+ * The group of a model is everything before its first "/"; ids keep their order inside a group.
349
+ */
350
+ export function modelGroups(ids, { min = 60 } = {}) {
351
+ const list = Array.isArray(ids) ? ids.filter((x) => typeof x === "string" && x) : [];
352
+ if (list.length < min) return null;
353
+ const slashed = list.filter((x) => x.indexOf("/") > 0);
354
+ if (slashed.length < list.length * 0.9) return null;
355
+ const by = new Map();
356
+ for (const id of list) {
357
+ // OpenRouter's "~deepseek/…" aliases (a family's latest) sit with the company itself.
358
+ const name = id.indexOf("/") > 0 ? id.slice(0, id.indexOf("/")).replace(/^~/, "") : "other";
359
+ if (!by.has(name)) by.set(name, []);
360
+ by.get(name).push(id);
361
+ }
362
+ return by.size > 1 ? [...by].map(([name, g]) => ({ name, ids: g })).sort((a, b) => a.name.localeCompare(b.name)) : null;
363
+ }
364
+
338
365
  /** mlx_lm's placeholder, which is a mapping and not a model anyone can pick. */
339
366
  export const PLACEHOLDER_MODEL = "default_model";
340
367
 
package/free-model.mjs CHANGED
@@ -196,7 +196,14 @@ export function addAuxCalls(state, aux, now = new Date()) {
196
196
  /** After the service answered the preset: what gu keeps (never the key itself). */
197
197
  export function stateFromPreset(preset, prev, now = new Date()) {
198
198
  const p = periodKey(now);
199
- const mine = prev && prev.period === p ? whole(prev.spentMicro) : 0;
199
+ // GH #565: spend belongs to a provider's ADDRESS, not to "the main slot". When a new code makes another provider lead,
200
+ // the old main's spend moves with its address (now an extra), and the new lead starts from its own.
201
+ const spentAt = {};
202
+ if (prev && prev.period === p) {
203
+ for (const [u, v] of Object.entries(prev.providers ?? {})) spentAt[u] = whole(v?.spentMicro);
204
+ if (prev.url) spentAt[prev.url] = whole(prev.spentMicro);
205
+ }
206
+ const mine = whole(spentAt[preset.baseUrl]);
200
207
  return {
201
208
  url: preset.baseUrl,
202
209
  model: preset.model,
@@ -210,7 +217,7 @@ export function stateFromPreset(preset, prev, now = new Date()) {
210
217
  // Each extra provider's OWN allowance and spend (#445): the higher of ours and the service's, like the primary's.
211
218
  providers: Object.fromEntries(
212
219
  presetProviders(preset).slice(1).map((p) => {
213
- const before = prev && prev.period === periodKey(now) ? whole(prev.providers?.[p.baseUrl]?.spentMicro) : 0;
220
+ const before = whole(spentAt[p.baseUrl]);
214
221
  return [p.baseUrl, { label: p.label, allowanceMicro: p.allowanceMicro, spentMicro: Math.max(before, p.spentMicro) }];
215
222
  })
216
223
  ),
@@ -315,15 +322,34 @@ export async function reportSpend({ hostedBase, token, state, fetchImpl = fetch,
315
322
  body: JSON.stringify({
316
323
  period: state.period,
317
324
  spentMicro: whole(state.spentMicro),
318
- extras: Object.entries(state.providers ?? {}).map(([baseUrl, v]) => ({ baseUrl, spentMicro: whole(v.spentMicro) })),
325
+ // GH #565: the main model's spend by its address too, so the service keeps each provider's own counter.
326
+ extras: [
327
+ ...(state.url ? [{ baseUrl: state.url, spentMicro: whole(state.spentMicro) }] : []),
328
+ ...Object.entries(state.providers ?? {}).map(([baseUrl, v]) => ({ baseUrl, spentMicro: whole(v.spentMicro) })),
329
+ ],
319
330
  }),
320
331
  }, timeoutMs);
321
332
  return r.ok && Number.isFinite(Number(r.body.spentMicro)) ? Number(r.body.spentMicro) : null;
322
333
  }
323
334
 
324
- /** The model that talks: the one a code names (when it is not the coder), else the coder itself. */
335
+ /**
336
+ * GH #563: the talker on ANOTHER of the preset's providers (a Kimi K3 code: Kimi K3 Pro codes, DeepSeek Flash on Qwen
337
+ * Cloud talks) — when that provider's key was handed out. Else null.
338
+ */
339
+ export function talkerOf(preset) {
340
+ const t = preset?.talker;
341
+ if (!t || typeof t.baseUrl !== "string" || typeof t.model !== "string" || !t.baseUrl || !t.model) return null;
342
+ const host = presetProviders(preset).slice(1).find((p) => sameServer(p.baseUrl, t.baseUrl));
343
+ return host && host.apiKey ? { baseUrl: host.baseUrl, model: t.model } : null;
344
+ }
345
+
346
+ /** The model that talks: the talker elsewhere (#563), the one a code names (when it is not the coder), else the coder. */
325
347
  export const agentModelOf = (preset) =>
326
- typeof preset?.agentModel === "string" && preset.agentModel && preset.agentModel !== preset.model ? preset.agentModel : preset.model;
348
+ talkerOf(preset)?.model ??
349
+ (typeof preset?.agentModel === "string" && preset.agentModel && preset.agentModel !== preset.model ? preset.agentModel : preset.model);
350
+
351
+ /** The server the talking model is on: the talker's (#563), else the coder's. */
352
+ export const agentUrlOf = (preset) => talkerOf(preset)?.baseUrl ?? preset.baseUrl;
327
353
 
328
354
  /**
329
355
  * APPLY THE PRESET to this account, through the same local-API calls /use-presets uses (preset-apply's
@@ -368,7 +394,8 @@ export async function applyPreset(preset, api, { rotateOnly = false } = {}) {
368
394
  agentCodingModelUrl: preset.baseUrl,
369
395
  agentCodingModelName: preset.model,
370
396
  agentCodingModelKind: "openai",
371
- agentModelUrl: preset.baseUrl,
397
+ // GH #563: the talker may be on another of the preset's providers (its key is added below, with the extras).
398
+ agentModelUrl: agentUrlOf(preset),
372
399
  // A code may name a different model to TALK (the agent model); the coder stays the preset's model.
373
400
  agentModelName: agentModelOf(preset),
374
401
  agentModel: agentModelOf(preset),