@tiens.nguyen/gu-cli 1.0.931 → 1.0.935

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.
@@ -40,6 +40,11 @@ import {
40
40
  LOCAL_API_BASE,
41
41
  API_LOG_FILE,
42
42
  LOCAL_MONGO_URI,
43
+ localDbChoice,
44
+ readLocalDb,
45
+ writeLocalDb,
46
+ apiHasGudb,
47
+ gudbFile,
43
48
  } from "./client-expert-api.mjs";
44
49
  import { askOllamaSetup, localOllamaDefault } from "./ollama-setup.mjs";
45
50
  import {
@@ -661,7 +666,9 @@ export async function ensureNativeMongo(ask, mongo, {
661
666
  * "" when the database at `uri` answers a MongoDB handshake, else the "host:port" that does not.
662
667
  * mongodb+srv names a cluster rather than a host:port, so it is never reported down from here.
663
668
  */
664
- export async function localMongoDown(uri = LOCAL_MONGO_URI, { check = null } = {}) {
669
+ export async function localMongoDown(uri = LOCAL_MONGO_URI, { check = null, localDb = readLocalDb() } = {}) {
670
+ // GH #534: a computer on the built-in database (gudb) has no MongoDB to be down.
671
+ if (localDb === "gudb") return "";
665
672
  if (/^mongodb\+srv:/i.test(String(uri))) return "";
666
673
  const { host, port } = mongoHostPort(uri);
667
674
  const answers = check ?? (await import("./mongo-native.mjs")).mongoAnswers;
@@ -681,6 +688,7 @@ export async function localMongoDown(uri = LOCAL_MONGO_URI, { check = null } = {
681
688
  * milliseconds, with the same handshake setup uses.
682
689
  */
683
690
  export async function preflightLocalMongo({
691
+ localDb = readLocalDb(),
684
692
  ask,
685
693
  isTty = false,
686
694
  platform = process.platform,
@@ -693,7 +701,7 @@ export async function preflightLocalMongo({
693
701
  isRoot = typeof process.getuid === "function" && process.getuid() === 0,
694
702
  log = (l) => console.log(l),
695
703
  } = {}) {
696
- if (!(await localMongoDown(uri, { check }))) return { ok: true, fixed: false, installed: false };
704
+ if (!(await localMongoDown(uri, { check, localDb }))) return { ok: true, fixed: false, installed: false };
697
705
  const { host, port } = mongoHostPort(uri);
698
706
 
699
707
  const local = /^(127\.|localhost$|\[?::1\]?$)/i.test(host);
@@ -1223,10 +1231,26 @@ export async function runClientExpertSetup({
1223
1231
  }
1224
1232
 
1225
1233
  let state = await loadState();
1226
- const mongo = await probeMongo();
1234
+ // GH #534: the built-in database (gudb, one file) unless this computer already uses MongoDB. Asked
1235
+ // before the MongoDB step, which it replaces: "is the published API new enough to have it?" is read
1236
+ // from the same index the API step downloads from (a failure here just means "decide as if not").
1237
+ let latestApi = "";
1238
+ try {
1239
+ latestApi = String((await fetchLatestApi())?.version ?? "");
1240
+ } catch {
1241
+ latestApi = "";
1242
+ }
1243
+ const dbChoice = localDbChoice({
1244
+ saved: readLocalDb(),
1245
+ latestApi,
1246
+ mongoAlreadySetUp: state.mongo === "done" && state.localDb !== "gudb",
1247
+ });
1248
+ const useGudb = dbChoice.kind === "gudb";
1249
+ const mongo = useGudb ? { running: false, installed: false } : await probeMongo();
1227
1250
  const probe = {
1228
1251
  mode: "client-expert",
1229
1252
  mongoRunning: mongo.running,
1253
+ localDb: useGudb ? "gudb" : "mongo",
1230
1254
  // Everything below MongoDB is not implemented yet — reported honestly rather than guessed.
1231
1255
  dbReady: false,
1232
1256
  apiInstalled: false,
@@ -1237,123 +1261,133 @@ export async function runClientExpertSetup({
1237
1261
  };
1238
1262
  state = recordStep(state, "mode", "done");
1239
1263
  await saveState(state);
1264
+ let mongoUri = LOCAL_MONGO_URI;
1265
+ if (useGudb) {
1266
+ // GH #534: nothing to install, no port, no password — the local API opens one file.
1267
+ console.log("\n " + cyan("✓ Database: built in") + dim(` — one file, ${gudbFile()} (no MongoDB needed)`));
1268
+ state = { ...state, localDb: "gudb" };
1269
+ } else {
1270
+ if (!/chosen earlier|set up with MongoDB/.test(dbChoice.why)) console.log(dim(`\n Using MongoDB: ${dbChoice.why}.`));
1240
1271
 
1241
- const plan = planSetup({ recorded: state, probe });
1242
- console.log("\n " + bold("Local mode setup") + dim(` ${machine.platform}/${machine.arch}`));
1243
- for (const step of plan.steps) {
1244
- const mark = step.state === "done" ? cyan("✓") : step.state === "reopened" ? yellow("↻") : dim("·");
1245
- console.log(` ${mark} ${step.state === "done" ? dim(step.title) : step.title}`);
1246
- }
1247
- if (plan.resuming) {
1248
- console.log("\n " + dim(`resuming — you stopped during "${plan.next}" last time`));
1249
- const why = stepReason(state, plan.next);
1250
- if (why) console.log(" " + dim(`(${why})`));
1251
- const resume = resumeAction(state, plan.next);
1252
- for (const c of resume.cleanup) console.log(" " + dim(`first: ${c}`));
1253
- }
1272
+ const plan = planSetup({ recorded: state, probe });
1273
+ console.log("\n " + bold("Local mode setup") + dim(` ${machine.platform}/${machine.arch}`));
1274
+ for (const step of plan.steps) {
1275
+ const mark = step.state === "done" ? cyan("✓") : step.state === "reopened" ? yellow("↻") : dim("·");
1276
+ console.log(` ${mark} ${step.state === "done" ? dim(step.title) : step.title}`);
1277
+ }
1278
+ if (plan.resuming) {
1279
+ console.log("\n " + dim(`resuming — you stopped during "${plan.next}" last time`));
1280
+ const why = stepReason(state, plan.next);
1281
+ if (why) console.log(" " + dim(`(${why})`));
1282
+ const resume = resumeAction(state, plan.next);
1283
+ for (const c of resume.cleanup) console.log(" " + dim(`first: ${c}`));
1284
+ }
1254
1285
 
1255
- if (plan.next === "mongo") {
1256
- // SHOW THE COMMANDS, ASK, THEN RUN THEM (task #329) — on macOS, Ubuntu and Windows 11 alike.
1257
- //
1258
- // This used to only check: "installing a database is a system-wide change needing sudo… the
1259
- // user can do better themselves", written after an earlier "Install MongoDB now? [y/N]" that
1260
- // printed the same commands whichever way it was answered. That was the right verdict on a
1261
- // question that changed nothing and the wrong fix for it — a first install that ends in "run
1262
- // these five lines and come back" is where people stop. So the question is back and a yes is
1263
- // honoured: the commands run in the user's own terminal, where sudo asks for its password.
1264
- console.log("\n " + bold(mongo.installed ? "MongoDB is not running on this machine." : "MongoDB is not installed on this machine."));
1265
- console.log(dim(" Local mode keeps every conversation and token count in a database"));
1266
- console.log(dim(" on THIS machine, so it needs one before setup can go further."));
1267
- // A MAC GETS NATIVE MONGODB, NOT DOCKER (task #304): Homebrew's mongodb-community as a brew
1268
- // service. Docker on a Mac puts every call through its VM, and a stuck Docker Desktop keeps
1269
- // 27017 open while nothing answers — the failure that stopped this project's own Mac.
1270
- //
1271
- // ELSEWHERE, DOCKER IS OFFERED ONLY WHERE IT ALREADY ANSWERS — one container, no system
1272
- // service — and declining it, or not having it, leads to the native install rather than to
1273
- // "Docker is not available here": a machine without Docker is the ordinary case on a server
1274
- // and on Windows, not an error to open with.
1275
- let explained = false;
1276
- const hadServer = Boolean(mongo.installed);
1277
- if (machine.platform !== "darwin" && !mongo.silentPort && (await probeDockerForMongo()).usable) {
1278
- if (await startMongoInDocker(ask)) {
1279
- mongo.running = true;
1280
- probe.mongoRunning = true;
1286
+ if (plan.next === "mongo") {
1287
+ // SHOW THE COMMANDS, ASK, THEN RUN THEM (task #329) — on macOS, Ubuntu and Windows 11 alike.
1288
+ //
1289
+ // This used to only check: "installing a database is a system-wide change needing sudo… the
1290
+ // user can do better themselves", written after an earlier "Install MongoDB now? [y/N]" that
1291
+ // printed the same commands whichever way it was answered. That was the right verdict on a
1292
+ // question that changed nothing and the wrong fix for it — a first install that ends in "run
1293
+ // these five lines and come back" is where people stop. So the question is back and a yes is
1294
+ // honoured: the commands run in the user's own terminal, where sudo asks for its password.
1295
+ console.log("\n " + bold(mongo.installed ? "MongoDB is not running on this machine." : "MongoDB is not installed on this machine."));
1296
+ console.log(dim(" Local mode keeps every conversation and token count in a database"));
1297
+ console.log(dim(" on THIS machine, so it needs one before setup can go further."));
1298
+ // A MAC GETS NATIVE MONGODB, NOT DOCKER (task #304): Homebrew's mongodb-community as a brew
1299
+ // service. Docker on a Mac puts every call through its VM, and a stuck Docker Desktop keeps
1300
+ // 27017 open while nothing answers — the failure that stopped this project's own Mac.
1301
+ //
1302
+ // ELSEWHERE, DOCKER IS OFFERED ONLY WHERE IT ALREADY ANSWERS — one container, no system
1303
+ // service — and declining it, or not having it, leads to the native install rather than to
1304
+ // "Docker is not available here": a machine without Docker is the ordinary case on a server
1305
+ // and on Windows, not an error to open with.
1306
+ let explained = false;
1307
+ const hadServer = Boolean(mongo.installed);
1308
+ if (machine.platform !== "darwin" && !mongo.silentPort && (await probeDockerForMongo()).usable) {
1309
+ if (await startMongoInDocker(ask)) {
1310
+ mongo.running = true;
1311
+ probe.mongoRunning = true;
1312
+ }
1281
1313
  }
1282
- }
1283
- if (!probe.mongoRunning) {
1284
- const r = await ensureNativeMongo(ask, mongo, { platform: machine.platform });
1285
- if (r.ok) {
1314
+ if (!probe.mongoRunning) {
1315
+ const r = await ensureNativeMongo(ask, mongo, { platform: machine.platform });
1316
+ if (r.ok) {
1317
+ mongo.running = true;
1318
+ probe.mongoRunning = true;
1319
+ }
1320
+ explained = r.explained;
1321
+ }
1322
+ if (!probe.mongoRunning && !explained) {
1323
+ // A platform with no plan at all — unreachable past the gate, kept so it is never silent.
1324
+ console.log(dim("\n Install MongoDB Community, then run gu again: https://www.mongodb.com/docs/manual/installation/"));
1325
+ }
1326
+ // STOP ONLY IF IT IS STILL NOT RUNNING. When Docker started one above there is nothing to
1327
+ // wait for, so setup carries straight on in this run — sending someone away to re-run
1328
+ // `gu` after we have just solved their problem for them is the kind of small
1329
+ // indignity that makes a tool feel unfinished.
1330
+ if (!probe.mongoRunning) {
1331
+ // No "meanwhile this works in CLIENT mode" any more: that fallback signed the user in,
1332
+ // which wrote the worker.env that marks a machine as paired — and then refused Local
1333
+ // mode because the machine was paired. Nothing is configured here yet, so the honest
1334
+ // end of this path is the instruction and an exit.
1335
+ console.log("\n " + dim("Run `gu` again once it is running — setup continues from here."));
1336
+ // Recorded as interrupted, not failed: nothing went wrong, the user simply has something
1337
+ // to do first. The next run greets them as a resume rather than as a stranger.
1338
+ state = recordStep(state, "mongo", "interrupted", {
1339
+ reason: mongo.installed ? "installed but not answering" : "not installed yet",
1340
+ });
1341
+ await saveState(state);
1342
+ console.log("");
1343
+ return { complete: false, stoppedAt: "mongo" };
1344
+ }
1345
+ // Re-probe rather than trusting the flag: the socket answered, but `how` is what the
1346
+ // success line below reports, and it should say what actually found it.
1347
+ const after = await probeMongo();
1348
+ if (after.running) {
1286
1349
  mongo.running = true;
1287
- probe.mongoRunning = true;
1350
+ mongo.how = after.how;
1288
1351
  }
1289
- explained = r.explained;
1290
- }
1291
- if (!probe.mongoRunning && !explained) {
1292
- // A platform with no plan at all — unreachable past the gate, kept so it is never silent.
1293
- console.log(dim("\n Install MongoDB Community, then run gu again: https://www.mongodb.com/docs/manual/installation/"));
1352
+ // Setup INSTALLED it a moment ago, so it has no credentials of its own to ask about.
1353
+ mongo.installedNow = !hadServer;
1294
1354
  }
1295
- // STOP ONLY IF IT IS STILL NOT RUNNING. When Docker started one above there is nothing to
1296
- // wait for, so setup carries straight on in this run — sending someone away to re-run
1297
- // `gu` after we have just solved their problem for them is the kind of small
1298
- // indignity that makes a tool feel unfinished.
1299
- if (!probe.mongoRunning) {
1300
- // No "meanwhile this works in CLIENT mode" any more: that fallback signed the user in,
1301
- // which wrote the worker.env that marks a machine as paired — and then refused Local
1302
- // mode because the machine was paired. Nothing is configured here yet, so the honest
1303
- // end of this path is the instruction and an exit.
1304
- console.log("\n " + dim("Run `gu` again once it is running — setup continues from here."));
1305
- // Recorded as interrupted, not failed: nothing went wrong, the user simply has something
1306
- // to do first. The next run greets them as a resume rather than as a stranger.
1307
- state = recordStep(state, "mongo", "interrupted", {
1308
- reason: mongo.installed ? "installed but not answering" : "not installed yet",
1309
- });
1310
- await saveState(state);
1311
- console.log("");
1312
- return { complete: false, stoppedAt: "mongo" };
1313
- }
1314
- // Re-probe rather than trusting the flag: the socket answered, but `how` is what the
1315
- // success line below reports, and it should say what actually found it.
1316
- const after = await probeMongo();
1317
- if (after.running) {
1318
- mongo.running = true;
1319
- mongo.how = after.how;
1320
- }
1321
- // Setup INSTALLED it a moment ago, so it has no credentials of its own to ask about.
1322
- mongo.installedNow = !hadServer;
1323
- }
1324
1355
 
1325
- console.log("\n " + cyan("✓ MongoDB is running") + dim(` (${mongo.how})`));
1326
-
1327
- // --- whose MongoDB is it? (task #15) ---------------------------------------------------
1328
- // Something answering on 27017 is not necessarily a database setup can USE: an instance the
1329
- // OS already had may carry its own admin credentials, and seeding into it with the default
1330
- // empty pair fails two steps later, after the 360-package install, with a message pointing
1331
- // at the wrong thing. Confirm the credentials HERE, where changing the answer is cheap.
1332
- // A uri already in state — a resumed run — is reused silently, like every other answered
1333
- // question, and a URI forced via GONEXT_LOCAL_MONGO_URI is taken as deliberate.
1334
- let mongoUri = LOCAL_MONGO_URI;
1335
- const credsDecision = mongoCredsDecision(state);
1336
- if (credsDecision === "custom") {
1337
- mongoUri = state.localMongoUri;
1338
- if (mongoUri !== LOCAL_MONGO_URI) {
1339
- console.log(dim(" using the MongoDB credentials from the previous run"));
1340
- }
1341
- } else if (credsDecision === "ask" && mongo.installedNow) {
1342
- state = { ...state, mongoCredsConfirmed: true };
1343
- } else if (credsDecision === "ask") {
1344
- const credsChoice = await askMongoCredentials(ask, askSecret);
1345
- if (credsChoice.exit) {
1346
- console.log("\n " + dim("No working MongoDB credentials — setup stops here."));
1347
- console.log(dim(" To start over: `gu clear`, then `gu` again.\n"));
1348
- state = recordStep(state, "mongo", "interrupted", {
1349
- reason: "declined at the MongoDB credentials check",
1350
- });
1351
- await saveState(state);
1352
- return { complete: false, stoppedAt: "mongo" };
1356
+ console.log("\n " + cyan("✓ MongoDB is running") + dim(` (${mongo.how})`));
1357
+
1358
+ // --- whose MongoDB is it? (task #15) ---------------------------------------------------
1359
+ // Something answering on 27017 is not necessarily a database setup can USE: an instance the
1360
+ // OS already had may carry its own admin credentials, and seeding into it with the default
1361
+ // empty pair fails two steps later, after the 360-package install, with a message pointing
1362
+ // at the wrong thing. Confirm the credentials HERE, where changing the answer is cheap.
1363
+ // A uri already in state — a resumed run — is reused silently, like every other answered
1364
+ // question, and a URI forced via GONEXT_LOCAL_MONGO_URI is taken as deliberate.
1365
+ mongoUri = LOCAL_MONGO_URI;
1366
+ const credsDecision = mongoCredsDecision(state);
1367
+ if (credsDecision === "custom") {
1368
+ mongoUri = state.localMongoUri;
1369
+ if (mongoUri !== LOCAL_MONGO_URI) {
1370
+ console.log(dim(" using the MongoDB credentials from the previous run"));
1371
+ }
1372
+ } else if (credsDecision === "ask" && mongo.installedNow) {
1373
+ state = { ...state, mongoCredsConfirmed: true };
1374
+ } else if (credsDecision === "ask") {
1375
+ const credsChoice = await askMongoCredentials(ask, askSecret);
1376
+ if (credsChoice.exit) {
1377
+ console.log("\n " + dim("No working MongoDB credentials — setup stops here."));
1378
+ console.log(dim(" To start over: `gu clear`, then `gu` again.\n"));
1379
+ state = recordStep(state, "mongo", "interrupted", {
1380
+ reason: "declined at the MongoDB credentials check",
1381
+ });
1382
+ await saveState(state);
1383
+ return { complete: false, stoppedAt: "mongo" };
1384
+ }
1385
+ mongoUri = credsChoice.uri;
1386
+ state = credsChoice.custom ? { ...state, localMongoUri: mongoUri } : { ...state, mongoCredsConfirmed: true };
1353
1387
  }
1354
- mongoUri = credsChoice.uri;
1355
- state = credsChoice.custom ? { ...state, localMongoUri: mongoUri } : { ...state, mongoCredsConfirmed: true };
1388
+ state = { ...state, localDb: "mongo" };
1356
1389
  }
1390
+ await writeLocalDb(useGudb ? "gudb" : "mongo");
1357
1391
  state = recordStep(state, "mongo", "done");
1358
1392
  await saveState(state);
1359
1393
 
@@ -1393,6 +1427,15 @@ export async function runClientExpertSetup({
1393
1427
  unmark();
1394
1428
  }
1395
1429
  }
1430
+ if (useGudb && !(await apiHasGudb(apiInstallDir(manifest.version)))) {
1431
+ // The index said this version has it; the files say otherwise. Stop clearly rather than start an
1432
+ // API that would look for a MongoDB this computer does not have.
1433
+ console.log("\n " + red("✗ ") + "This API package has no built-in database. Run setup again with GONEXT_LOCAL_DB=mongo,");
1434
+ console.log(dim(" or wait for the next gu API release.\n"));
1435
+ state = recordStep(state, "api-files", "failed", { reason: "API package without gudb" });
1436
+ await saveState(state);
1437
+ return { complete: false, stoppedAt: "api-files" };
1438
+ }
1396
1439
  state = recordStep(state, "api-files", "done");
1397
1440
  await saveState(state);
1398
1441
 
@@ -1431,8 +1474,12 @@ export async function runClientExpertSetup({
1431
1474
  });
1432
1475
  } catch (e) {
1433
1476
  console.log("\n " + red("✗ ") + `Could not prepare the database: ${e.message}`);
1434
- console.log(dim(" MongoDB answered a moment ago, so this is usually a permissions or"));
1435
- console.log(dim(" connection-string problem. Nothing has been changed.\n"));
1477
+ if (useGudb) {
1478
+ console.log(dim(` The database file is ${gudbFile()}. Check that this folder can be written to.\n`));
1479
+ } else {
1480
+ console.log(dim(" MongoDB answered a moment ago, so this is usually a permissions or"));
1481
+ console.log(dim(" connection-string problem. Nothing has been changed.\n"));
1482
+ }
1436
1483
  state = recordStep(state, "database", "failed", { reason: e.message });
1437
1484
  await saveState(state);
1438
1485
  return { complete: false, stoppedAt: "database" };
@@ -1478,7 +1525,7 @@ export async function runClientExpertSetup({
1478
1525
  await saveState(state);
1479
1526
  return { complete: false, stoppedAt: "api-running" };
1480
1527
  }
1481
- console.log(" " + cyan("✓ API answering") + dim(` on ${LOCAL_API_BASE} (mongo, persistence on)`));
1528
+ console.log(" " + cyan("✓ API answering") + dim(` on ${LOCAL_API_BASE} (${health.body?.storage === "gudb" ? "built-in database" : "mongo"}, persistence on)`));
1482
1529
  state = recordStep(state, "api-running", "done");
1483
1530
  await saveState(state);
1484
1531
 
@@ -1754,13 +1801,109 @@ export async function runClientExpertSetup({
1754
1801
  await saveState(state);
1755
1802
  }
1756
1803
 
1757
- console.log(
1758
- "\n " + cyan(bold("Local mode is set up.")) +
1759
- dim("\n Everything — conversations, token counts, workspaces — stays in MongoDB on this") +
1760
- dim("\n machine. The API restarts with `gu-cli api start`; its log is") +
1761
- dim(`\n ${API_LOG_FILE}\n`)
1762
- );
1804
+ console.log(localModeDoneText({ localDb: readLocalDb(), dbFile: gudbFile(), apiLog: API_LOG_FILE, cyan, bold, dim }));
1763
1805
  // #301: the caller opens /use-presets once the terminal exists — the picker, the plan and the
1764
1806
  // confirmation are that command's, not rebuilt here.
1765
1807
  return { complete: true, stoppedAt: null, ...(loadPreset ? { loadPreset: true } : {}), ...(addProvider ? { addProvider } : {}), ...(voucherAtStart ? { voucherAtStart: true, ...(chosenModels?.voucherCode ? { voucherCode: chosenModels.voucherCode } : {}) } : {}) };
1766
1808
  }
1809
+
1810
+ /**
1811
+ * The last words of Local setup. It said "stays in MongoDB" on a computer set up on the built-in
1812
+ * database (GH #552, seen on the first gudb run) — the storage named is the one in use.
1813
+ */
1814
+ export function localModeDoneText({ localDb, dbFile, apiLog, cyan = (t) => t, bold = (t) => t, dim = (t) => t }) {
1815
+ const where = localDb === "gudb"
1816
+ ? ["stays on this machine, in one file:", ` ${dbFile}`]
1817
+ : ["stays in MongoDB on this machine."];
1818
+ return (
1819
+ "\n " + cyan(bold("Local mode is set up.")) +
1820
+ dim("\n Everything — conversations, token counts, workspaces — " + where[0]) +
1821
+ (where[1] ? dim("\n " + where[1]) : "") +
1822
+ dim("\n The API restarts with `gu-cli api start`; its log is") +
1823
+ dim(`\n ${apiLog}\n`)
1824
+ );
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
+ }
@@ -30,8 +30,9 @@ export const CLIENT_EXPERT_STEPS = [
30
30
  },
31
31
  {
32
32
  id: "mongo",
33
- title: "MongoDB installed and running",
34
- satisfied: (p) => p.mongoRunning === true,
33
+ title: "Database ready (built in, or MongoDB installed and running)",
34
+ // GH #534: the built-in database (gudb) needs nothing installed or running.
35
+ satisfied: (p) => p.mongoRunning === true || p.localDb === "gudb",
35
36
  },
36
37
  {
37
38
  id: "database",
@@ -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),