@tiens.nguyen/gu-cli 1.0.930 → 1.0.932

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.
@@ -27,6 +27,9 @@ import { writeFile, mkdir, readFile, access } from "node:fs/promises";
27
27
  import { readFileSync } from "node:fs";
28
28
  import { homedir } from "node:os";
29
29
  import { join } from "node:path";
30
+ import { pathToFileURL } from "node:url";
31
+ import { compareVersions } from "./version-check.mjs";
32
+ import { nodeAtLeast } from "./node-version.mjs";
30
33
 
31
34
  /** Where the local API listens by default. 4100 keeps clear of the hosted API and of Vite's 5173. */
32
35
  export const DEFAULT_LOCAL_API_PORT = 4100;
@@ -180,6 +183,79 @@ export function generateLocalUserId() {
180
183
  * DATA_BACKEND is the whole point: it defaults to "dynamo" inside the API, so omitting it
181
184
  * yields a server that runs and persists nothing.
182
185
  */
186
+ // ---------------------------------------------------------------------------------------------
187
+ // gudb (GH #534): Local mode's database without a MongoDB server — one SQLite file the local API
188
+ // opens itself (api/src/gudb). Chosen once per computer and remembered in ~/.gonext/local-db, so every
189
+ // later `gu api start|restart|upgrade`, doctor and the terminal's own restart start the API with the
190
+ // same storage. A computer already set up with MongoDB keeps it.
191
+ // ---------------------------------------------------------------------------------------------
192
+ /** node:sqlite, which gudb runs on, is in Node 22.5 and later. */
193
+ export const GUDB_MIN_NODE = "22.5.0";
194
+ /** The first published local API package that contains gudb (api/src/gudb → <apiDir>/gudb/db.js). */
195
+ export const GUDB_MIN_API = "1.0.337";
196
+ export const LOCAL_DB_FILE = join(homedir(), ".gonext", "local-db");
197
+ export const gudbFile = (home = homedir()) => join(home, ".gonext", "gudb", "gu.db");
198
+
199
+ /** The storage this computer's local API uses: "gudb", "mongo", or "" when not chosen yet. */
200
+ export function readLocalDb({ path = LOCAL_DB_FILE } = {}) {
201
+ try {
202
+ const v = readFileSync(path, "utf8").trim();
203
+ return v === "gudb" || v === "mongo" ? v : "";
204
+ } catch {
205
+ return "";
206
+ }
207
+ }
208
+
209
+ export async function writeLocalDb(kind, { path = LOCAL_DB_FILE } = {}) {
210
+ await mkdir(join(path, ".."), { recursive: true });
211
+ await writeFile(path, kind + "\n", "utf8");
212
+ }
213
+
214
+ /**
215
+ * Which storage a Local setup uses → { kind: "gudb" | "mongo", why }. Pure.
216
+ * · GONEXT_LOCAL_DB=mongo|gudb decides (gudb still needs Node 22.5+);
217
+ * · a choice already made on this computer is kept;
218
+ * · a computer whose setup already went through MongoDB keeps MongoDB (its data is there);
219
+ * · otherwise gudb — when Node is new enough and the published API has it.
220
+ */
221
+ export function localDbChoice({ env = process.env, saved = "", nodeVersion = process.version, latestApi = "", mongoAlreadySetUp = false } = {}) {
222
+ const asked = String(env.GONEXT_LOCAL_DB ?? "").trim().toLowerCase();
223
+ const nodeOk = nodeAtLeast(nodeVersion, GUDB_MIN_NODE);
224
+ if (asked === "mongo") return { kind: "mongo", why: "GONEXT_LOCAL_DB=mongo" };
225
+ if (saved) return { kind: saved, why: "chosen earlier on this computer" };
226
+ if (mongoAlreadySetUp) return { kind: "mongo", why: "this computer was set up with MongoDB" };
227
+ if (!nodeOk) return { kind: "mongo", why: `Node ${nodeVersion}: the built-in database needs Node ${GUDB_MIN_NODE} or newer` };
228
+ if (asked === "gudb") return { kind: "gudb", why: "GONEXT_LOCAL_DB=gudb" };
229
+ if (latestApi && compareVersions(latestApi, GUDB_MIN_API) < 0) return { kind: "mongo", why: `the published API (${latestApi}) has no built-in database yet` };
230
+ return { kind: "gudb", why: "built in" };
231
+ }
232
+
233
+ /**
234
+ * The local database, opened the way the local API opens it → { db, close }. `db.collection(name)` takes
235
+ * the same driver calls either way (gudb implements them), so the seeding below is written once.
236
+ */
237
+ export async function openLocalStore({ apiDir, mongoUri = localMongoUri(), dbName = LOCAL_DB_NAME, localDb = readLocalDb(), home = homedir(), timeoutMs = 8000 } = {}) {
238
+ if (localDb === "gudb") {
239
+ const { GudbDb } = await import(pathToFileURL(join(apiDir, "gudb", "db.js")).href);
240
+ const g = new GudbDb(gudbFile(home));
241
+ return { db: g, close: async () => g.close() };
242
+ }
243
+ const { MongoClient } = loadMongoDriver(apiDir);
244
+ const client = new MongoClient(mongoUri, { serverSelectionTimeoutMS: timeoutMs });
245
+ await client.connect();
246
+ return { db: client.db(dbName), close: () => client.close().catch(() => {}) };
247
+ }
248
+
249
+ /** Does this unpacked API package contain gudb? */
250
+ export async function apiHasGudb(apiDir) {
251
+ try {
252
+ await access(join(apiDir, "gudb", "db.js"));
253
+ return true;
254
+ } catch {
255
+ return false;
256
+ }
257
+ }
258
+
183
259
  export function apiEnv({
184
260
  port = LOCAL_API_PORT,
185
261
  mongoUri = localMongoUri(),
@@ -187,13 +263,16 @@ export function apiEnv({
187
263
  base = {},
188
264
  hostedBase = hostedApiBase(),
189
265
  home = homedir(),
266
+ localDb = readLocalDb(),
190
267
  } = {}) {
191
- return {
268
+ const storage =
269
+ localDb === "gudb"
270
+ ? { DATA_BACKEND: "mongo", GU_DB: "gudb", GUDB_PATH: gudbFile(home) }
271
+ : { DATA_BACKEND: "mongo", MONGODB_URI: mongoUri, MONGODB_DB: dbName };
272
+ const out = {
192
273
  ...base,
193
274
  PORT: String(port),
194
- DATA_BACKEND: "mongo",
195
- MONGODB_URI: mongoUri,
196
- MONGODB_DB: dbName,
275
+ ...storage,
197
276
  // THE AGENT'S PROMPT SCAFFOLD IS NOT ON THIS MACHINE (task #246). The local API forwards the
198
277
  // worker's request to the hosted API, signed with this machine's gu CLI token, and keeps the
199
278
  // answer in memory only — so private mode needs internet for a turn, and says so when it has
@@ -201,6 +280,12 @@ export function apiEnv({
201
280
  PROMPT_SCAFFOLD_UPSTREAM: hostedBase,
202
281
  GU_CLI_TOKEN_FILE: join(home, ".gonext", "cli-token.json"),
203
282
  };
283
+ // gudb: a MONGODB_URI inherited from the shell must not send the API to a MongoDB after all.
284
+ if (localDb === "gudb") {
285
+ delete out.MONGODB_URI;
286
+ delete out.MONGODB_HOST;
287
+ }
288
+ return out;
204
289
  }
205
290
 
206
291
  /** The hosted gu API — where a Client Expert machine's token is renewed and its scaffold fetched. */
@@ -361,12 +446,12 @@ export async function seedDatabase({
361
446
  dbName = LOCAL_DB_NAME,
362
447
  userId,
363
448
  workerKey,
449
+ localDb = readLocalDb(),
450
+ home = homedir(),
364
451
  } = {}) {
365
- const { MongoClient } = loadMongoDriver(apiDir);
366
- const client = new MongoClient(mongoUri, { serverSelectionTimeoutMS: 8000 });
367
- await client.connect();
452
+ const store = await openLocalStore({ apiDir, mongoUri, dbName, localDb, home });
368
453
  try {
369
- const db = client.db(dbName);
454
+ const db = store.db;
370
455
  const keys = db.collection("worker_keys");
371
456
  await keys.createIndex({ keyHash: 1 }, { unique: true });
372
457
  const key = workerKey || generateWorkerKey();
@@ -383,9 +468,9 @@ export async function seedDatabase({
383
468
  },
384
469
  { upsert: true }
385
470
  );
386
- return { workerKey: key, userId: uid, dbName };
471
+ return { workerKey: key, userId: uid, dbName: localDb === "gudb" ? "built in" : dbName };
387
472
  } finally {
388
- await client.close().catch(() => {});
473
+ await store.close();
389
474
  }
390
475
  }
391
476
 
@@ -1072,16 +1157,16 @@ export async function modelsAlreadyConfigured({
1072
1157
  mongoUri = localMongoUri(),
1073
1158
  dbName = LOCAL_DB_NAME,
1074
1159
  userId,
1160
+ localDb = readLocalDb(),
1161
+ home = homedir(),
1075
1162
  } = {}) {
1076
1163
  try {
1077
- const { MongoClient } = loadMongoDriver(apiDir);
1078
- const client = new MongoClient(mongoUri, { serverSelectionTimeoutMS: 4000 });
1079
- await client.connect();
1164
+ const store = await openLocalStore({ apiDir, mongoUri, dbName, localDb, home, timeoutMs: 4000 });
1080
1165
  try {
1081
- const existing = (await client.db(dbName).collection("settings").findOne({ userId })) ?? {};
1166
+ const existing = (await store.db.collection("settings").findOne({ userId })) ?? {};
1082
1167
  return modelsConfiguredIn(existing);
1083
1168
  } finally {
1084
- await client.close().catch(() => {});
1169
+ await store.close();
1085
1170
  }
1086
1171
  } catch {
1087
1172
  return false;
@@ -1099,12 +1184,12 @@ export async function seedSettings({
1099
1184
  models = CLIENT_EXPERT_MODELS,
1100
1185
  // #301: the model questions were skipped — write no model field at all.
1101
1186
  skipModels = false,
1187
+ localDb = readLocalDb(),
1188
+ home = homedir(),
1102
1189
  } = {}) {
1103
- const { MongoClient } = loadMongoDriver(apiDir);
1104
- const client = new MongoClient(mongoUri, { serverSelectionTimeoutMS: 8000 });
1105
- await client.connect();
1190
+ const store = await openLocalStore({ apiDir, mongoUri, dbName, localDb, home });
1106
1191
  try {
1107
- const col = client.db(dbName).collection("settings");
1192
+ const col = store.db.collection("settings");
1108
1193
  const existing = (await col.findOne({ userId })) ?? {};
1109
1194
  const patch = settingsPatch({ existing, models, skipModels });
1110
1195
  if (Object.keys(patch).length > 0) {
@@ -1116,7 +1201,7 @@ export async function seedSettings({
1116
1201
  }
1117
1202
  return patch;
1118
1203
  } finally {
1119
- await client.close().catch(() => {});
1204
+ await store.close();
1120
1205
  }
1121
1206
  }
1122
1207
 
@@ -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/"));
1294
- }
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;
1352
+ // Setup INSTALLED it a moment ago, so it has no credentials of its own to ask about.
1353
+ mongo.installedNow = !hadServer;
1320
1354
  }
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,25 @@ 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
+ }
@@ -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",
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);