@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.
@@ -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,83 @@ 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
+ // 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);
243
+ const { GudbDb } = await import(pathToFileURL(join(apiDir, "gudb", "db.js")).href);
244
+ const g = new GudbDb(gudbFile(home));
245
+ return { db: g, close: async () => g.close() };
246
+ }
247
+ const { MongoClient } = loadMongoDriver(apiDir);
248
+ const client = new MongoClient(mongoUri, { serverSelectionTimeoutMS: timeoutMs });
249
+ await client.connect();
250
+ return { db: client.db(dbName), close: () => client.close().catch(() => {}) };
251
+ }
252
+
253
+ /** Does this unpacked API package contain gudb? */
254
+ export async function apiHasGudb(apiDir) {
255
+ try {
256
+ await access(join(apiDir, "gudb", "db.js"));
257
+ return true;
258
+ } catch {
259
+ return false;
260
+ }
261
+ }
262
+
183
263
  export function apiEnv({
184
264
  port = LOCAL_API_PORT,
185
265
  mongoUri = localMongoUri(),
@@ -187,13 +267,16 @@ export function apiEnv({
187
267
  base = {},
188
268
  hostedBase = hostedApiBase(),
189
269
  home = homedir(),
270
+ localDb = readLocalDb(),
190
271
  } = {}) {
191
- return {
272
+ const storage =
273
+ localDb === "gudb"
274
+ ? { DATA_BACKEND: "mongo", GU_DB: "gudb", GUDB_PATH: gudbFile(home) }
275
+ : { DATA_BACKEND: "mongo", MONGODB_URI: mongoUri, MONGODB_DB: dbName };
276
+ const out = {
192
277
  ...base,
193
278
  PORT: String(port),
194
- DATA_BACKEND: "mongo",
195
- MONGODB_URI: mongoUri,
196
- MONGODB_DB: dbName,
279
+ ...storage,
197
280
  // THE AGENT'S PROMPT SCAFFOLD IS NOT ON THIS MACHINE (task #246). The local API forwards the
198
281
  // worker's request to the hosted API, signed with this machine's gu CLI token, and keeps the
199
282
  // answer in memory only — so private mode needs internet for a turn, and says so when it has
@@ -201,6 +284,12 @@ export function apiEnv({
201
284
  PROMPT_SCAFFOLD_UPSTREAM: hostedBase,
202
285
  GU_CLI_TOKEN_FILE: join(home, ".gonext", "cli-token.json"),
203
286
  };
287
+ // gudb: a MONGODB_URI inherited from the shell must not send the API to a MongoDB after all.
288
+ if (localDb === "gudb") {
289
+ delete out.MONGODB_URI;
290
+ delete out.MONGODB_HOST;
291
+ }
292
+ return out;
204
293
  }
205
294
 
206
295
  /** The hosted gu API — where a Client Expert machine's token is renewed and its scaffold fetched. */
@@ -361,12 +450,12 @@ export async function seedDatabase({
361
450
  dbName = LOCAL_DB_NAME,
362
451
  userId,
363
452
  workerKey,
453
+ localDb = readLocalDb(),
454
+ home = homedir(),
364
455
  } = {}) {
365
- const { MongoClient } = loadMongoDriver(apiDir);
366
- const client = new MongoClient(mongoUri, { serverSelectionTimeoutMS: 8000 });
367
- await client.connect();
456
+ const store = await openLocalStore({ apiDir, mongoUri, dbName, localDb, home });
368
457
  try {
369
- const db = client.db(dbName);
458
+ const db = store.db;
370
459
  const keys = db.collection("worker_keys");
371
460
  await keys.createIndex({ keyHash: 1 }, { unique: true });
372
461
  const key = workerKey || generateWorkerKey();
@@ -383,9 +472,9 @@ export async function seedDatabase({
383
472
  },
384
473
  { upsert: true }
385
474
  );
386
- return { workerKey: key, userId: uid, dbName };
475
+ return { workerKey: key, userId: uid, dbName: localDb === "gudb" ? "built in" : dbName };
387
476
  } finally {
388
- await client.close().catch(() => {});
477
+ await store.close();
389
478
  }
390
479
  }
391
480
 
@@ -1072,16 +1161,16 @@ export async function modelsAlreadyConfigured({
1072
1161
  mongoUri = localMongoUri(),
1073
1162
  dbName = LOCAL_DB_NAME,
1074
1163
  userId,
1164
+ localDb = readLocalDb(),
1165
+ home = homedir(),
1075
1166
  } = {}) {
1076
1167
  try {
1077
- const { MongoClient } = loadMongoDriver(apiDir);
1078
- const client = new MongoClient(mongoUri, { serverSelectionTimeoutMS: 4000 });
1079
- await client.connect();
1168
+ const store = await openLocalStore({ apiDir, mongoUri, dbName, localDb, home, timeoutMs: 4000 });
1080
1169
  try {
1081
- const existing = (await client.db(dbName).collection("settings").findOne({ userId })) ?? {};
1170
+ const existing = (await store.db.collection("settings").findOne({ userId })) ?? {};
1082
1171
  return modelsConfiguredIn(existing);
1083
1172
  } finally {
1084
- await client.close().catch(() => {});
1173
+ await store.close();
1085
1174
  }
1086
1175
  } catch {
1087
1176
  return false;
@@ -1099,12 +1188,12 @@ export async function seedSettings({
1099
1188
  models = CLIENT_EXPERT_MODELS,
1100
1189
  // #301: the model questions were skipped — write no model field at all.
1101
1190
  skipModels = false,
1191
+ localDb = readLocalDb(),
1192
+ home = homedir(),
1102
1193
  } = {}) {
1103
- const { MongoClient } = loadMongoDriver(apiDir);
1104
- const client = new MongoClient(mongoUri, { serverSelectionTimeoutMS: 8000 });
1105
- await client.connect();
1194
+ const store = await openLocalStore({ apiDir, mongoUri, dbName, localDb, home });
1106
1195
  try {
1107
- const col = client.db(dbName).collection("settings");
1196
+ const col = store.db.collection("settings");
1108
1197
  const existing = (await col.findOne({ userId })) ?? {};
1109
1198
  const patch = settingsPatch({ existing, models, skipModels });
1110
1199
  if (Object.keys(patch).length > 0) {
@@ -1116,7 +1205,7 @@ export async function seedSettings({
1116
1205
  }
1117
1206
  return patch;
1118
1207
  } finally {
1119
- await client.close().catch(() => {});
1208
+ await store.close();
1120
1209
  }
1121
1210
  }
1122
1211