latticesql 4.2.0 → 4.2.2

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/dist/cli.js CHANGED
@@ -205,10 +205,10 @@ function getOrCreateMasterKey() {
205
205
  }
206
206
  function readIdentity() {
207
207
  const dir = ensureConfigDir();
208
- const path2 = join2(dir, IDENTITY_FILENAME);
209
- if (!existsSync2(path2)) return { ...EMPTY_IDENTITY };
208
+ const path3 = join2(dir, IDENTITY_FILENAME);
209
+ if (!existsSync2(path3)) return { ...EMPTY_IDENTITY };
210
210
  try {
211
- const parsed = JSON.parse(readFileSync(path2, "utf8"));
211
+ const parsed = JSON.parse(readFileSync(path3, "utf8"));
212
212
  return {
213
213
  display_name: typeof parsed.display_name === "string" ? parsed.display_name : "",
214
214
  email: typeof parsed.email === "string" ? parsed.email : ""
@@ -219,26 +219,26 @@ function readIdentity() {
219
219
  }
220
220
  function writeIdentity(identity) {
221
221
  const dir = ensureConfigDir();
222
- const path2 = join2(dir, IDENTITY_FILENAME);
222
+ const path3 = join2(dir, IDENTITY_FILENAME);
223
223
  const body = JSON.stringify(
224
224
  { display_name: identity.display_name, email: identity.email },
225
225
  null,
226
226
  2
227
227
  );
228
- writeFileSync(path2, body + "\n", "utf8");
228
+ writeFileSync(path3, body + "\n", "utf8");
229
229
  if (platform2() !== "win32") {
230
230
  try {
231
- chmodSync2(path2, 384);
231
+ chmodSync2(path3, 384);
232
232
  } catch {
233
233
  }
234
234
  }
235
235
  }
236
236
  function readPreferences() {
237
237
  const dir = ensureConfigDir();
238
- const path2 = join2(dir, PREFERENCES_FILENAME);
239
- if (!existsSync2(path2)) return { ...DEFAULT_PREFERENCES };
238
+ const path3 = join2(dir, PREFERENCES_FILENAME);
239
+ if (!existsSync2(path3)) return { ...DEFAULT_PREFERENCES };
240
240
  try {
241
- const parsed = JSON.parse(readFileSync(path2, "utf8"));
241
+ const parsed = JSON.parse(readFileSync(path3, "utf8"));
242
242
  const agg = typeof parsed.aggressiveness === "number" ? parsed.aggressiveness : NaN;
243
243
  return {
244
244
  show_system_tables: typeof parsed.show_system_tables === "boolean" ? parsed.show_system_tables : DEFAULT_PREFERENCES.show_system_tables,
@@ -252,7 +252,7 @@ function readPreferences() {
252
252
  }
253
253
  function writePreferences(prefs) {
254
254
  const dir = ensureConfigDir();
255
- const path2 = join2(dir, PREFERENCES_FILENAME);
255
+ const path3 = join2(dir, PREFERENCES_FILENAME);
256
256
  const body = JSON.stringify(
257
257
  {
258
258
  show_system_tables: prefs.show_system_tables,
@@ -263,10 +263,10 @@ function writePreferences(prefs) {
263
263
  null,
264
264
  2
265
265
  );
266
- writeFileSync(path2, body + "\n", "utf8");
266
+ writeFileSync(path3, body + "\n", "utf8");
267
267
  if (platform2() !== "win32") {
268
268
  try {
269
- chmodSync2(path2, 384);
269
+ chmodSync2(path3, 384);
270
270
  } catch {
271
271
  }
272
272
  }
@@ -330,8 +330,8 @@ function withCredentialLock(fn) {
330
330
  }
331
331
  }
332
332
  }
333
- function writeFileAtomic(path2, data) {
334
- const tmp = `${path2}.${String(process.pid)}.${randomBytes2(4).toString("hex")}.tmp`;
333
+ function writeFileAtomic(path3, data) {
334
+ const tmp = `${path3}.${String(process.pid)}.${randomBytes2(4).toString("hex")}.tmp`;
335
335
  writeFileSync(tmp, data, "utf8");
336
336
  if (platform2() !== "win32") {
337
337
  try {
@@ -339,7 +339,7 @@ function writeFileAtomic(path2, data) {
339
339
  } catch {
340
340
  }
341
341
  }
342
- renameSync(tmp, path2);
342
+ renameSync(tmp, path3);
343
343
  }
344
344
  function mutateCredentials(mutate) {
345
345
  withCredentialLock(() => {
@@ -350,11 +350,11 @@ function mutateCredentials(mutate) {
350
350
  }
351
351
  function loadCredentials() {
352
352
  const dir = ensureConfigDir();
353
- const path2 = join2(dir, DB_CREDENTIALS_FILENAME);
354
- if (!existsSync2(path2)) return {};
353
+ const path3 = join2(dir, DB_CREDENTIALS_FILENAME);
354
+ if (!existsSync2(path3)) return {};
355
355
  const key = deriveKey(getOrCreateMasterKey());
356
356
  try {
357
- const ciphertext = readFileSync(path2, "utf8").trim();
357
+ const ciphertext = readFileSync(path3, "utf8").trim();
358
358
  const plaintext = decrypt(ciphertext, key);
359
359
  const parsed = JSON.parse(plaintext);
360
360
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
@@ -369,10 +369,10 @@ function loadCredentials() {
369
369
  }
370
370
  function saveCredentials(creds) {
371
371
  const dir = ensureConfigDir();
372
- const path2 = join2(dir, DB_CREDENTIALS_FILENAME);
372
+ const path3 = join2(dir, DB_CREDENTIALS_FILENAME);
373
373
  const key = deriveKey(getOrCreateMasterKey());
374
374
  const ciphertext = encrypt(JSON.stringify(creds), key);
375
- writeFileAtomic(path2, ciphertext + "\n");
375
+ writeFileAtomic(path3, ciphertext + "\n");
376
376
  }
377
377
  function listDbCredentials() {
378
378
  return Object.keys(loadCredentials()).sort();
@@ -420,11 +420,11 @@ function healRawDbUrl(configPath) {
420
420
  }
421
421
  function loadS3Configs() {
422
422
  const dir = ensureConfigDir();
423
- const path2 = join2(dir, S3_CONFIG_FILENAME);
424
- if (!existsSync2(path2)) return {};
423
+ const path3 = join2(dir, S3_CONFIG_FILENAME);
424
+ if (!existsSync2(path3)) return {};
425
425
  const key = deriveKey(getOrCreateMasterKey());
426
426
  try {
427
- const parsed = JSON.parse(decrypt(readFileSync(path2, "utf8").trim(), key));
427
+ const parsed = JSON.parse(decrypt(readFileSync(path3, "utf8").trim(), key));
428
428
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
429
429
  return parsed;
430
430
  }
@@ -438,12 +438,12 @@ function loadS3Configs() {
438
438
  }
439
439
  function saveS3Configs(cfgs) {
440
440
  const dir = ensureConfigDir();
441
- const path2 = join2(dir, S3_CONFIG_FILENAME);
441
+ const path3 = join2(dir, S3_CONFIG_FILENAME);
442
442
  const key = deriveKey(getOrCreateMasterKey());
443
- writeFileSync(path2, encrypt(JSON.stringify(cfgs), key) + "\n", "utf8");
443
+ writeFileSync(path3, encrypt(JSON.stringify(cfgs), key) + "\n", "utf8");
444
444
  if (platform2() !== "win32") {
445
445
  try {
446
- chmodSync2(path2, 384);
446
+ chmodSync2(path3, 384);
447
447
  } catch {
448
448
  }
449
449
  }
@@ -463,11 +463,11 @@ function deleteDbCredential(label) {
463
463
  }
464
464
  function loadAssistantCredentials() {
465
465
  const dir = ensureConfigDir();
466
- const path2 = join2(dir, ASSISTANT_CREDENTIALS_FILENAME);
467
- if (!existsSync2(path2)) return {};
466
+ const path3 = join2(dir, ASSISTANT_CREDENTIALS_FILENAME);
467
+ if (!existsSync2(path3)) return {};
468
468
  const key = deriveKey(getOrCreateMasterKey());
469
469
  try {
470
- const ciphertext = readFileSync(path2, "utf8").trim();
470
+ const ciphertext = readFileSync(path3, "utf8").trim();
471
471
  const plaintext = decrypt(ciphertext, key);
472
472
  const parsed = JSON.parse(plaintext);
473
473
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
@@ -482,13 +482,13 @@ function loadAssistantCredentials() {
482
482
  }
483
483
  function saveAssistantCredentials(creds) {
484
484
  const dir = ensureConfigDir();
485
- const path2 = join2(dir, ASSISTANT_CREDENTIALS_FILENAME);
485
+ const path3 = join2(dir, ASSISTANT_CREDENTIALS_FILENAME);
486
486
  const key = deriveKey(getOrCreateMasterKey());
487
487
  const ciphertext = encrypt(JSON.stringify(creds), key);
488
- writeFileSync(path2, ciphertext + "\n", "utf8");
488
+ writeFileSync(path3, ciphertext + "\n", "utf8");
489
489
  if (platform2() !== "win32") {
490
490
  try {
491
- chmodSync2(path2, 384);
491
+ chmodSync2(path3, 384);
492
492
  } catch {
493
493
  }
494
494
  }
@@ -999,10 +999,10 @@ function manifestPath(outputDir) {
999
999
  return join5(outputDir, ".lattice", "manifest.json");
1000
1000
  }
1001
1001
  function readManifest(outputDir) {
1002
- const path2 = manifestPath(outputDir);
1003
- if (!existsSync5(path2)) return null;
1002
+ const path3 = manifestPath(outputDir);
1003
+ if (!existsSync5(path3)) return null;
1004
1004
  try {
1005
- return JSON.parse(readFileSync4(path2, "utf8"));
1005
+ return JSON.parse(readFileSync4(path3, "utf8"));
1006
1006
  } catch {
1007
1007
  return null;
1008
1008
  }
@@ -1015,7 +1015,7 @@ var init_manifest = __esm({
1015
1015
  "src/lifecycle/manifest.ts"() {
1016
1016
  "use strict";
1017
1017
  init_writer();
1018
- TEMPLATE_VERSION = 1;
1018
+ TEMPLATE_VERSION = 2;
1019
1019
  }
1020
1020
  });
1021
1021
 
@@ -1190,20 +1190,130 @@ var init_render_cursor = __esm({
1190
1190
  }
1191
1191
  });
1192
1192
 
1193
+ // src/db/load-sqlite.ts
1194
+ import path from "path";
1195
+ import { createRequire } from "module";
1196
+ import { spawnSync } from "child_process";
1197
+ function runtimeRequire() {
1198
+ const importMetaUrl = import.meta.url;
1199
+ return importMetaUrl ? createRequire(importMetaUrl) : (
1200
+ // CJS fallback — Node provides `require` on every CJS module scope. Under
1201
+ // tsup's CJS output `import.meta.url` is rewritten to undefined, so this
1202
+ // branch keeps the loader working in the published .cjs bundle.
1203
+ __require
1204
+ );
1205
+ }
1206
+ function asCtor(mod) {
1207
+ return mod.default ?? mod;
1208
+ }
1209
+ function isAbiMismatch(err) {
1210
+ const message = err instanceof Error ? err.message : String(err);
1211
+ const code = err.code;
1212
+ return message.includes("NODE_MODULE_VERSION") || code === "ERR_DLOPEN_FAILED" || message.includes("was compiled against a different Node.js version");
1213
+ }
1214
+ function autoRebuildDisabled() {
1215
+ const v2 = process.env.LATTICE_SQLITE_NO_AUTOREBUILD;
1216
+ if (!v2) return false;
1217
+ const normalized = v2.trim().toLowerCase();
1218
+ return normalized !== "" && normalized !== "0" && normalized !== "false" && normalized !== "no";
1219
+ }
1220
+ function installRootFor(req) {
1221
+ const pkgJsonPath = req.resolve("better-sqlite3/package.json");
1222
+ return path.resolve(path.dirname(pkgJsonPath), "..", "..");
1223
+ }
1224
+ function defaultRebuild(installRoot) {
1225
+ const npmBin = process.platform === "win32" ? "npm.cmd" : "npm";
1226
+ const res = spawnSync(npmBin, ["rebuild", "better-sqlite3"], {
1227
+ cwd: installRoot,
1228
+ stdio: ["ignore", "pipe", "pipe"],
1229
+ encoding: "utf8",
1230
+ timeout: 5 * 60 * 1e3
1231
+ });
1232
+ if (res.error) {
1233
+ return { ok: false, reason: res.error.message };
1234
+ }
1235
+ if (res.status !== 0) {
1236
+ const stderr = res.stderr.trim();
1237
+ const tail = stderr ? stderr.slice(-300) : `npm rebuild exited with code ${String(res.status)}`;
1238
+ return { ok: false, reason: tail };
1239
+ }
1240
+ return { ok: true };
1241
+ }
1242
+ function resolveSqliteCtor(options = {}) {
1243
+ const req = options.require ?? runtimeRequire();
1244
+ const rebuild = options.rebuild ?? defaultRebuild;
1245
+ const resolveInstallRoot = options.installRoot ?? installRootFor;
1246
+ const log = options.log ?? ((msg) => process.stderr.write(msg + "\n"));
1247
+ let firstError;
1248
+ try {
1249
+ return asCtor(req("better-sqlite3"));
1250
+ } catch (err) {
1251
+ firstError = err;
1252
+ }
1253
+ if (!isAbiMismatch(firstError)) {
1254
+ throw new Error(PEER_DEP_MISSING_MESSAGE);
1255
+ }
1256
+ if (autoRebuildDisabled()) {
1257
+ throw new Error(
1258
+ rebuildFailedMessage("automatic rebuild is disabled (LATTICE_SQLITE_NO_AUTOREBUILD)")
1259
+ );
1260
+ }
1261
+ log("[latticesql] SQLite engine built for a different Node runtime \u2014 rebuilding better-sqlite3\u2026");
1262
+ let installRoot;
1263
+ try {
1264
+ installRoot = resolveInstallRoot(req);
1265
+ } catch (err) {
1266
+ throw new Error(
1267
+ rebuildFailedMessage(
1268
+ "could not locate the better-sqlite3 install root (" + (err instanceof Error ? err.message : String(err)) + ")"
1269
+ )
1270
+ );
1271
+ }
1272
+ const outcome = rebuild(installRoot);
1273
+ if (!outcome.ok) {
1274
+ throw new Error(rebuildFailedMessage(outcome.reason));
1275
+ }
1276
+ try {
1277
+ return asCtor(req("better-sqlite3"));
1278
+ } catch (err) {
1279
+ throw new Error(
1280
+ rebuildFailedMessage(
1281
+ "the rebuilt module still failed to load (" + (err instanceof Error ? err.message : String(err)) + ")"
1282
+ )
1283
+ );
1284
+ }
1285
+ }
1286
+ function rebuildFailedMessage(reason) {
1287
+ return "latticesql: the better-sqlite3 native module doesn\u2019t match this Node runtime and an automatic rebuild did not complete (" + reason + "). Run `npm rebuild better-sqlite3` (or reinstall) and retry.";
1288
+ }
1289
+ function loadSqlite() {
1290
+ if (_ctor) return _ctor;
1291
+ _ctor = resolveSqliteCtor();
1292
+ return _ctor;
1293
+ }
1294
+ var PEER_DEP_MISSING_MESSAGE, _ctor;
1295
+ var init_load_sqlite = __esm({
1296
+ "src/db/load-sqlite.ts"() {
1297
+ "use strict";
1298
+ PEER_DEP_MISSING_MESSAGE = "better-sqlite3 is a required peer dependency of latticesql \u2014 install it (npm install better-sqlite3).";
1299
+ _ctor = null;
1300
+ }
1301
+ });
1302
+
1193
1303
  // src/db/sqlite.ts
1194
- import Database from "better-sqlite3";
1195
1304
  var SQLiteAdapter;
1196
1305
  var init_sqlite = __esm({
1197
1306
  "src/db/sqlite.ts"() {
1198
1307
  "use strict";
1308
+ init_load_sqlite();
1199
1309
  SQLiteAdapter = class {
1200
1310
  dialect = "sqlite";
1201
1311
  _db = null;
1202
1312
  _path;
1203
1313
  _wal;
1204
1314
  _busyTimeout;
1205
- constructor(path2, options) {
1206
- this._path = path2;
1315
+ constructor(path3, options) {
1316
+ this._path = path3;
1207
1317
  this._wal = options?.wal ?? true;
1208
1318
  this._busyTimeout = options?.busyTimeout ?? 5e3;
1209
1319
  }
@@ -1212,7 +1322,8 @@ var init_sqlite = __esm({
1212
1322
  return this._db;
1213
1323
  }
1214
1324
  open() {
1215
- this._db = new Database(this._path);
1325
+ const Ctor = loadSqlite();
1326
+ this._db = new Ctor(this._path);
1216
1327
  this._db.pragma(`busy_timeout = ${this._busyTimeout.toString()}`);
1217
1328
  if (this._wal) {
1218
1329
  this._db.pragma("journal_mode = WAL");
@@ -1384,16 +1495,16 @@ var init_sqlite = __esm({
1384
1495
  });
1385
1496
 
1386
1497
  // src/db/postgres.ts
1387
- import path from "path";
1498
+ import path2 from "path";
1388
1499
  import { fileURLToPath } from "url";
1389
- import { createRequire } from "module";
1500
+ import { createRequire as createRequire2 } from "module";
1390
1501
  function moduleContext() {
1391
1502
  if (_moduleContext) return _moduleContext;
1392
1503
  const importMetaUrl = import.meta.url;
1393
1504
  if (importMetaUrl) {
1394
1505
  _moduleContext = {
1395
- dir: path.dirname(fileURLToPath(importMetaUrl)),
1396
- require: createRequire(importMetaUrl)
1506
+ dir: path2.dirname(fileURLToPath(importMetaUrl)),
1507
+ require: createRequire2(importMetaUrl)
1397
1508
  };
1398
1509
  } else {
1399
1510
  _moduleContext = { dir: __dirname, require: __require };
@@ -3322,14 +3433,14 @@ var init_core = __esm({
3322
3433
  columnRef(f6) {
3323
3434
  const col = `"${ident(f6.col)}"`;
3324
3435
  if (f6.jsonPath === void 0) return { sql: col, params: [] };
3325
- const path2 = Array.isArray(f6.jsonPath) ? f6.jsonPath : [f6.jsonPath];
3436
+ const path3 = Array.isArray(f6.jsonPath) ? f6.jsonPath : [f6.jsonPath];
3326
3437
  const numeric = isNumericComparison(f6);
3327
3438
  if (this.adapter.dialect === "postgres") {
3328
3439
  const extract2 = `((${col})::jsonb #>> ?::text[])`;
3329
3440
  const sql2 = numeric ? `(${extract2})::numeric` : extract2;
3330
- return { sql: sql2, params: [path2] };
3441
+ return { sql: sql2, params: [path3] };
3331
3442
  }
3332
- const jsonpath = `$.${path2.join(".")}`;
3443
+ const jsonpath = `$.${path3.join(".")}`;
3333
3444
  const extract = `json_extract(${col}, ?)`;
3334
3445
  const sql = numeric ? `CAST(${extract} AS REAL)` : extract;
3335
3446
  return { sql, params: [jsonpath] };
@@ -5904,8 +6015,8 @@ var init_pipeline = __esm({
5904
6015
 
5905
6016
  // src/render/interpolate.ts
5906
6017
  function interpolate(template, row) {
5907
- return template.replace(/\{\{([^}]+)\}\}/g, (_, path2) => {
5908
- const parts = path2.trim().split(".");
6018
+ return template.replace(/\{\{([^}]+)\}\}/g, (_, path3) => {
6019
+ const parts = path3.trim().split(".");
5909
6020
  let val = row;
5910
6021
  for (const part of parts) {
5911
6022
  if (val == null || typeof val !== "object") return "";
@@ -6054,13 +6165,13 @@ function uniqueDirName(displayName, existing) {
6054
6165
  }
6055
6166
  }
6056
6167
  function readRegistry(root6) {
6057
- const path2 = registryPath(root6);
6058
- if (!existsSync11(path2)) return { ...EMPTY_REGISTRY, workspaces: [] };
6168
+ const path3 = registryPath(root6);
6169
+ if (!existsSync11(path3)) return { ...EMPTY_REGISTRY, workspaces: [] };
6059
6170
  let parsed;
6060
6171
  try {
6061
- parsed = JSON.parse(readFileSync8(path2, "utf-8"));
6172
+ parsed = JSON.parse(readFileSync8(path3, "utf-8"));
6062
6173
  } catch (e6) {
6063
- throw new Error(`Lattice: corrupt workspace registry at "${path2}": ${e6.message}`);
6174
+ throw new Error(`Lattice: corrupt workspace registry at "${path3}": ${e6.message}`);
6064
6175
  }
6065
6176
  const reg = parsed;
6066
6177
  return {
@@ -6070,11 +6181,11 @@ function readRegistry(root6) {
6070
6181
  };
6071
6182
  }
6072
6183
  function writeRegistry(root6, registry) {
6073
- const path2 = registryPath(root6);
6074
- const tmp = `${path2}.tmp-${String(process.pid)}`;
6184
+ const path3 = registryPath(root6);
6185
+ const tmp = `${path3}.tmp-${String(process.pid)}`;
6075
6186
  writeFileSync4(tmp, `${JSON.stringify(registry, null, 2)}
6076
6187
  `, "utf-8");
6077
- renameSync3(tmp, path2);
6188
+ renameSync3(tmp, path3);
6078
6189
  }
6079
6190
  function listWorkspaces(root6) {
6080
6191
  return readRegistry(root6).workspaces;
@@ -7794,18 +7905,18 @@ function computedColumnOrder(table, computed) {
7794
7905
  const names = new Set(Object.keys(computed));
7795
7906
  const order = [];
7796
7907
  const state2 = /* @__PURE__ */ new Map();
7797
- const visit = (name, path2) => {
7908
+ const visit = (name, path3) => {
7798
7909
  const st = state2.get(name);
7799
7910
  if (st === "done") return;
7800
7911
  if (st === "visiting") {
7801
- const start = path2.indexOf(name);
7802
- throw new ComputedColumnCycleError(table, [...path2.slice(start), name]);
7912
+ const start = path3.indexOf(name);
7913
+ throw new ComputedColumnCycleError(table, [...path3.slice(start), name]);
7803
7914
  }
7804
7915
  state2.set(name, "visiting");
7805
7916
  const spec = computed[name];
7806
7917
  if (spec) {
7807
7918
  for (const dep of spec.deps) {
7808
- if (names.has(dep)) visit(dep, [...path2, name]);
7919
+ if (names.has(dep)) visit(dep, [...path3, name]);
7809
7920
  }
7810
7921
  }
7811
7922
  state2.set(name, "done");
@@ -15373,11 +15484,11 @@ function stripHtml(html) {
15373
15484
  const text = decodeXmlEntities(stripTags(noScript));
15374
15485
  return text.replace(/[ \t\f\r]+/g, " ").replace(/ *\n */g, "\n").replace(/\n{3,}/g, "\n\n").trim();
15375
15486
  }
15376
- async function unzip(path2) {
15487
+ async function unzip(path3) {
15377
15488
  const fflate = await loadParser("fflate");
15378
15489
  if (!fflate || typeof fflate.unzipSync !== "function") return null;
15379
15490
  try {
15380
- const buf = await readFile(path2);
15491
+ const buf = await readFile(path3);
15381
15492
  let total = 0;
15382
15493
  return fflate.unzipSync(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength), {
15383
15494
  filter: (file) => {
@@ -15406,35 +15517,35 @@ var init_helpers2 = __esm({
15406
15517
 
15407
15518
  // src/gui/ai/doc/ooxml.ts
15408
15519
  import { readFile as readFile2 } from "fs/promises";
15409
- async function extractDocx(path2) {
15520
+ async function extractDocx(path3) {
15410
15521
  const mod = await loadParser("mammoth");
15411
15522
  const lib = mod?.default ?? mod;
15412
15523
  if (!lib || typeof lib.extractRawText !== "function") return null;
15413
15524
  try {
15414
- const { value } = await lib.extractRawText({ path: path2 });
15525
+ const { value } = await lib.extractRawText({ path: path3 });
15415
15526
  return nullIfEmpty(value);
15416
15527
  } catch {
15417
15528
  return null;
15418
15529
  }
15419
15530
  }
15420
- async function extractDoc(path2) {
15531
+ async function extractDoc(path3) {
15421
15532
  const mod = await loadParser(
15422
15533
  "word-extractor"
15423
15534
  );
15424
15535
  const Ctor = mod && "default" in mod ? mod.default : mod;
15425
15536
  if (typeof Ctor !== "function") return null;
15426
15537
  try {
15427
- const doc = await new Ctor().extract(path2);
15538
+ const doc = await new Ctor().extract(path3);
15428
15539
  return nullIfEmpty(doc.getBody());
15429
15540
  } catch {
15430
15541
  return null;
15431
15542
  }
15432
15543
  }
15433
- async function extractPdf(path2) {
15544
+ async function extractPdf(path3) {
15434
15545
  const unpdf = await loadParser("unpdf");
15435
15546
  if (!unpdf || typeof unpdf.getDocumentProxy !== "function") return null;
15436
15547
  try {
15437
- const buf = await readFile2(path2);
15548
+ const buf = await readFile2(path3);
15438
15549
  const data = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
15439
15550
  const text = await withTimeout(
15440
15551
  (async () => {
@@ -15466,8 +15577,8 @@ function slideText(xml) {
15466
15577
  }
15467
15578
  return paras.join("\n");
15468
15579
  }
15469
- async function extractPptx(path2) {
15470
- const entries = await unzip(path2);
15580
+ async function extractPptx(path3) {
15581
+ const entries = await unzip(path3);
15471
15582
  if (!entries) return null;
15472
15583
  const slides = Object.keys(entries).filter((n3) => /^ppt\/slides\/slide\d+\.xml$/.test(n3)).sort((a6, b6) => partNumber(a6) - partNumber(b6));
15473
15584
  if (slides.length === 0) return null;
@@ -15485,8 +15596,8 @@ async function extractPptx(path2) {
15485
15596
  }
15486
15597
  return nullIfEmpty(parts.join("\n\n"));
15487
15598
  }
15488
- async function extractXlsx(path2) {
15489
- const entries = await unzip(path2);
15599
+ async function extractXlsx(path3) {
15600
+ const entries = await unzip(path3);
15490
15601
  if (!entries) return null;
15491
15602
  const shared = [];
15492
15603
  const ssBytes = entries["xl/sharedStrings.xml"];
@@ -15544,8 +15655,8 @@ function odfWhitespace(s2) {
15544
15655
  function odfParagraph(inner) {
15545
15656
  return decodeXmlEntities(stripTags(odfWhitespace(inner))).trim();
15546
15657
  }
15547
- async function extractOdfText(path2) {
15548
- const entries = await unzip(path2);
15658
+ async function extractOdfText(path3) {
15659
+ const entries = await unzip(path3);
15549
15660
  if (!entries) return null;
15550
15661
  const contentBytes = entries["content.xml"];
15551
15662
  if (!contentBytes) return null;
@@ -15567,8 +15678,8 @@ async function extractOdfText(path2) {
15567
15678
  }
15568
15679
  return nullIfEmpty(lines.join("\n"));
15569
15680
  }
15570
- async function extractOds(path2) {
15571
- const entries = await unzip(path2);
15681
+ async function extractOds(path3) {
15682
+ const entries = await unzip(path3);
15572
15683
  if (!entries) return null;
15573
15684
  const contentBytes = entries["content.xml"];
15574
15685
  if (!contentBytes) return null;
@@ -15627,8 +15738,8 @@ function resolveHref(baseDir, href) {
15627
15738
  }
15628
15739
  return normalizeZipPath(baseDir + h6);
15629
15740
  }
15630
- async function extractEpub(path2) {
15631
- const entries = await unzip(path2);
15741
+ async function extractEpub(path3) {
15742
+ const entries = await unzip(path3);
15632
15743
  if (!entries) return null;
15633
15744
  let order = [];
15634
15745
  const container = entries["META-INF/container.xml"];
@@ -15712,9 +15823,9 @@ function rtfToText(rtf) {
15712
15823
  s2 = s2.replace(/[{}]/g, "");
15713
15824
  return s2.replace(/[ \t]+/g, (m4) => m4.includes(" ") ? " " : " ").replace(/[ \t]\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
15714
15825
  }
15715
- async function extractRtf(path2) {
15826
+ async function extractRtf(path3) {
15716
15827
  try {
15717
- const raw = await readFile3(path2, "latin1");
15828
+ const raw = await readFile3(path3, "latin1");
15718
15829
  if (!raw.startsWith("{\\rtf")) return null;
15719
15830
  return nullIfEmpty(rtfToText(raw));
15720
15831
  } catch {
@@ -15760,27 +15871,27 @@ var init_other = __esm({
15760
15871
  });
15761
15872
 
15762
15873
  // src/gui/ai/doc-extractors.ts
15763
- async function extractDocument(path2, ext) {
15874
+ async function extractDocument(path3, ext) {
15764
15875
  switch (ext) {
15765
15876
  case ".docx":
15766
- return extractDocx(path2);
15877
+ return extractDocx(path3);
15767
15878
  case ".doc":
15768
- return extractDoc(path2);
15879
+ return extractDoc(path3);
15769
15880
  case ".pdf":
15770
- return extractPdf(path2);
15881
+ return extractPdf(path3);
15771
15882
  case ".pptx":
15772
- return extractPptx(path2);
15883
+ return extractPptx(path3);
15773
15884
  case ".xlsx":
15774
- return extractXlsx(path2);
15885
+ return extractXlsx(path3);
15775
15886
  case ".odt":
15776
15887
  case ".odp":
15777
- return extractOdfText(path2);
15888
+ return extractOdfText(path3);
15778
15889
  case ".ods":
15779
- return extractOds(path2);
15890
+ return extractOds(path3);
15780
15891
  case ".epub":
15781
- return extractEpub(path2);
15892
+ return extractEpub(path3);
15782
15893
  case ".rtf":
15783
- return extractRtf(path2);
15894
+ return extractRtf(path3);
15784
15895
  default:
15785
15896
  return null;
15786
15897
  }
@@ -15803,17 +15914,17 @@ function languageOf(name) {
15803
15914
  function truncate(s2) {
15804
15915
  return s2.length > MAX_TEXT2 ? s2.slice(0, MAX_TEXT2) : s2;
15805
15916
  }
15806
- async function parseFile(path2, mimeHint, originalName) {
15807
- const name = originalName ?? basename4(path2);
15917
+ async function parseFile(path3, mimeHint, originalName) {
15918
+ const name = originalName ?? basename4(path3);
15808
15919
  const ext = extname(name).toLowerCase();
15809
15920
  const lang = languageOf(name);
15810
15921
  if (lang) {
15811
- return { text: truncate(await readFile4(path2, "utf8")), language: lang };
15922
+ return { text: truncate(await readFile4(path3, "utf8")), language: lang };
15812
15923
  }
15813
15924
  if (mimeHint && TEXT_MIME.test(mimeHint) || TEXT_EXT.has(ext)) {
15814
- return { text: truncate(await readFile4(path2, "utf8")) };
15925
+ return { text: truncate(await readFile4(path3, "utf8")) };
15815
15926
  }
15816
- const doc = await extractDocument(path2, ext);
15927
+ const doc = await extractDocument(path3, ext);
15817
15928
  if (doc != null) {
15818
15929
  return { text: truncate(doc) };
15819
15930
  }
@@ -15883,7 +15994,7 @@ var init_extract = __esm({
15883
15994
  });
15884
15995
 
15885
15996
  // src/ai/llm-client.ts
15886
- import { createRequire as createRequire3 } from "module";
15997
+ import { createRequire as createRequire4 } from "module";
15887
15998
  var DEFAULT_MODEL;
15888
15999
  var init_llm_client = __esm({
15889
16000
  "src/ai/llm-client.ts"() {
@@ -16437,7 +16548,7 @@ var init_url_safety = __esm({
16437
16548
  import { JSDOM } from "jsdom";
16438
16549
  import { Readability } from "@mozilla/readability";
16439
16550
  import { basename as basename5 } from "path";
16440
- import { createRequire as createRequire4 } from "module";
16551
+ import { createRequire as createRequire5 } from "module";
16441
16552
  async function crawlUrl(rawUrl, opts = {}) {
16442
16553
  const u2 = await assertSafeUrl(rawUrl, opts.allowPrivate ?? false);
16443
16554
  const fetchImpl = opts.fetcher ?? fetch;
@@ -16684,7 +16795,7 @@ async function renderViaPlaywright(url, timeoutMs, warnIfMissing = false) {
16684
16795
  let chromium;
16685
16796
  try {
16686
16797
  const importMetaUrl = import.meta.url;
16687
- const req = importMetaUrl ? createRequire4(importMetaUrl) : __require;
16798
+ const req = importMetaUrl ? createRequire5(importMetaUrl) : __require;
16688
16799
  const pw = req("playwright");
16689
16800
  chromium = pw.chromium;
16690
16801
  } catch {
@@ -16856,8 +16967,8 @@ function isWriteConflict(e6) {
16856
16967
  function normalizeUrl(s2) {
16857
16968
  try {
16858
16969
  const u2 = new URL(s2.trim());
16859
- const path2 = u2.pathname.replace(/\/+$/, "");
16860
- return `${u2.protocol}//${u2.host.toLowerCase()}${path2}${u2.search}`;
16970
+ const path3 = u2.pathname.replace(/\/+$/, "");
16971
+ return `${u2.protocol}//${u2.host.toLowerCase()}${path3}${u2.search}`;
16861
16972
  } catch {
16862
16973
  return null;
16863
16974
  }
@@ -17615,7 +17726,7 @@ var init_tools = __esm({
17615
17726
  });
17616
17727
 
17617
17728
  // src/gui/ai/chat.ts
17618
- import { createRequire as createRequire5 } from "module";
17729
+ import { createRequire as createRequire6 } from "module";
17619
17730
  function capToolResult(s2) {
17620
17731
  if (s2.length <= MAX_TOOL_RESULT_CHARS) return s2;
17621
17732
  if (s2.length > MAX_TOOL_RESULT_SKIP)
@@ -17848,7 +17959,7 @@ async function* runChat(opts) {
17848
17959
  function loadSdk() {
17849
17960
  if (!_sdk) {
17850
17961
  const importMetaUrl = import.meta.url;
17851
- const req = importMetaUrl ? createRequire5(importMetaUrl) : __require;
17962
+ const req = importMetaUrl ? createRequire6(importMetaUrl) : __require;
17852
17963
  try {
17853
17964
  _sdk = req("@anthropic-ai/sdk");
17854
17965
  } catch (err) {
@@ -21675,14 +21786,14 @@ var init_readFile = __esm({
21675
21786
  "use strict";
21676
21787
  filePromises = {};
21677
21788
  fileIntercept = {};
21678
- readFile6 = (path2, options) => {
21679
- if (fileIntercept[path2] !== void 0) {
21680
- return fileIntercept[path2];
21789
+ readFile6 = (path3, options) => {
21790
+ if (fileIntercept[path3] !== void 0) {
21791
+ return fileIntercept[path3];
21681
21792
  }
21682
- if (!filePromises[path2] || options?.ignoreCache) {
21683
- filePromises[path2] = fsReadFile(path2, "utf8");
21793
+ if (!filePromises[path3] || options?.ignoreCache) {
21794
+ filePromises[path3] = fsReadFile(path3, "utf8");
21684
21795
  }
21685
- return filePromises[path2];
21796
+ return filePromises[path3];
21686
21797
  };
21687
21798
  }
21688
21799
  });
@@ -21800,8 +21911,8 @@ var init_externalDataInterceptor = __esm({
21800
21911
  getFileRecord() {
21801
21912
  return fileIntercept;
21802
21913
  },
21803
- interceptFile(path2, contents) {
21804
- fileIntercept[path2] = Promise.resolve(contents);
21914
+ interceptFile(path3, contents) {
21915
+ fileIntercept[path3] = Promise.resolve(contents);
21805
21916
  },
21806
21917
  getTokenRecord() {
21807
21918
  return tokenIntercept;
@@ -22135,13 +22246,13 @@ var init_resolveDefaultsModeConfig = __esm({
22135
22246
  }
22136
22247
  return { hostname: "169.254.169.254", path: "/" };
22137
22248
  };
22138
- imdsHttpGet = async ({ hostname, path: path2 }) => {
22249
+ imdsHttpGet = async ({ hostname, path: path3 }) => {
22139
22250
  const { request } = await import("http");
22140
22251
  return new Promise((resolve17, reject) => {
22141
22252
  const req = request({
22142
22253
  method: "GET",
22143
22254
  hostname: hostname.replace(/^\[(.+)]$/, "$1"),
22144
- path: path2,
22255
+ path: path3,
22145
22256
  timeout: 1e3,
22146
22257
  signal: AbortSignal.timeout(1e3)
22147
22258
  });
@@ -22342,8 +22453,8 @@ var init_createConfigValueProvider = __esm({
22342
22453
  return endpoint.url.href;
22343
22454
  }
22344
22455
  if ("hostname" in endpoint) {
22345
- const { protocol, hostname, port, path: path2 } = endpoint;
22346
- return `${protocol}//${hostname}${port ? ":" + port : ""}${path2}`;
22456
+ const { protocol, hostname, port, path: path3 } = endpoint;
22457
+ return `${protocol}//${hostname}${port ? ":" + port : ""}${path3}`;
22347
22458
  }
22348
22459
  }
22349
22460
  return endpoint;
@@ -22780,18 +22891,18 @@ var init_getAttrPathList = __esm({
22780
22891
  "node_modules/@smithy/core/dist-es/submodules/endpoints/util-endpoints/lib/getAttrPathList.js"() {
22781
22892
  "use strict";
22782
22893
  init_types3();
22783
- getAttrPathList = (path2) => {
22784
- const parts = path2.split(".");
22894
+ getAttrPathList = (path3) => {
22895
+ const parts = path3.split(".");
22785
22896
  const pathList = [];
22786
22897
  for (const part of parts) {
22787
22898
  const squareBracketIndex = part.indexOf("[");
22788
22899
  if (squareBracketIndex !== -1) {
22789
22900
  if (part.indexOf("]") !== part.length - 1) {
22790
- throw new EndpointError(`Path: '${path2}' does not end with ']'`);
22901
+ throw new EndpointError(`Path: '${path3}' does not end with ']'`);
22791
22902
  }
22792
22903
  const arrayIndex = part.slice(squareBracketIndex + 1, -1);
22793
22904
  if (Number.isNaN(parseInt(arrayIndex))) {
22794
- throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path2}'`);
22905
+ throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path3}'`);
22795
22906
  }
22796
22907
  if (squareBracketIndex !== 0) {
22797
22908
  pathList.push(part.slice(0, squareBracketIndex));
@@ -22813,9 +22924,9 @@ var init_getAttr = __esm({
22813
22924
  "use strict";
22814
22925
  init_types3();
22815
22926
  init_getAttrPathList();
22816
- getAttr = (value, path2) => getAttrPathList(path2).reduce((acc, index) => {
22927
+ getAttr = (value, path3) => getAttrPathList(path3).reduce((acc, index) => {
22817
22928
  if (typeof acc !== "object") {
22818
- throw new EndpointError(`Index '${index}' in '${path2}' not found in '${JSON.stringify(value)}'`);
22929
+ throw new EndpointError(`Index '${index}' in '${path3}' not found in '${JSON.stringify(value)}'`);
22819
22930
  } else if (Array.isArray(acc)) {
22820
22931
  const i6 = parseInt(index);
22821
22932
  return acc[i6 < 0 ? acc.length + i6 : i6];
@@ -22881,8 +22992,8 @@ var init_parseURL = __esm({
22881
22992
  return value;
22882
22993
  }
22883
22994
  if (typeof value === "object" && "hostname" in value) {
22884
- const { hostname: hostname2, port, protocol: protocol2 = "", path: path2 = "", query = {} } = value;
22885
- const url = new URL(`${protocol2}//${hostname2}${port ? `:${port}` : ""}${path2}`);
22995
+ const { hostname: hostname2, port, protocol: protocol2 = "", path: path3 = "", query = {} } = value;
22996
+ const url = new URL(`${protocol2}//${hostname2}${port ? `:${port}` : ""}${path3}`);
22886
22997
  url.search = Object.entries(query).map(([k6, v2]) => `${k6}=${v2}`).join("&");
22887
22998
  return url;
22888
22999
  }
@@ -25993,11 +26104,11 @@ var init_HttpBindingProtocol = __esm({
25993
26104
  const opTraits = translateTraits(operationSchema.traits);
25994
26105
  if (opTraits.http) {
25995
26106
  request.method = opTraits.http[0];
25996
- const [path2, search] = opTraits.http[1].split("?");
26107
+ const [path3, search] = opTraits.http[1].split("?");
25997
26108
  if (request.path == "/") {
25998
- request.path = path2;
26109
+ request.path = path3;
25999
26110
  } else {
26000
- request.path += path2;
26111
+ request.path += path3;
26001
26112
  }
26002
26113
  const traitSearchParams = new URLSearchParams(search ?? "");
26003
26114
  for (const [key, value] of traitSearchParams) {
@@ -27976,9 +28087,9 @@ var init_createPaginator = __esm({
27976
28087
  command = withCommand(command) ?? command;
27977
28088
  return await client.send(command, ...args);
27978
28089
  };
27979
- get2 = (fromObject, path2) => {
28090
+ get2 = (fromObject, path3) => {
27980
28091
  let cursor = fromObject;
27981
- const pathComponents = path2.split(".");
28092
+ const pathComponents = path3.split(".");
27982
28093
  for (const step of pathComponents) {
27983
28094
  if (!cursor || typeof cursor !== "object") {
27984
28095
  return void 0;
@@ -30470,10 +30581,10 @@ ${longDate}
30470
30581
  ${credentialScope}
30471
30582
  ${toHex(hashedRequest)}`;
30472
30583
  }
30473
- getCanonicalPath({ path: path2 }) {
30584
+ getCanonicalPath({ path: path3 }) {
30474
30585
  if (this.uriEscapePath) {
30475
30586
  const normalizedPathSegments = [];
30476
- for (const pathSegment of path2.split("/")) {
30587
+ for (const pathSegment of path3.split("/")) {
30477
30588
  if (pathSegment?.length === 0)
30478
30589
  continue;
30479
30590
  if (pathSegment === ".")
@@ -30484,11 +30595,11 @@ ${toHex(hashedRequest)}`;
30484
30595
  normalizedPathSegments.push(pathSegment);
30485
30596
  }
30486
30597
  }
30487
- const normalizedPath = `${path2?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path2?.endsWith("/") ? "/" : ""}`;
30598
+ const normalizedPath = `${path3?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path3?.endsWith("/") ? "/" : ""}`;
30488
30599
  const doubleEncoded = escapeUri(normalizedPath);
30489
30600
  return doubleEncoded.replace(/%2F/g, "/");
30490
30601
  }
30491
- return path2;
30602
+ return path3;
30492
30603
  }
30493
30604
  validateResolvedCredentials(credentials) {
30494
30605
  if (typeof credentials !== "object" || typeof credentials.accessKeyId !== "string" || typeof credentials.secretAccessKey !== "string") {
@@ -35405,16 +35516,16 @@ var init_Matcher = __esm({
35405
35516
  * @returns {string|undefined}
35406
35517
  */
35407
35518
  getCurrentTag() {
35408
- const path2 = this._matcher.path;
35409
- return path2.length > 0 ? path2[path2.length - 1].tag : void 0;
35519
+ const path3 = this._matcher.path;
35520
+ return path3.length > 0 ? path3[path3.length - 1].tag : void 0;
35410
35521
  }
35411
35522
  /**
35412
35523
  * Get current namespace.
35413
35524
  * @returns {string|undefined}
35414
35525
  */
35415
35526
  getCurrentNamespace() {
35416
- const path2 = this._matcher.path;
35417
- return path2.length > 0 ? path2[path2.length - 1].namespace : void 0;
35527
+ const path3 = this._matcher.path;
35528
+ return path3.length > 0 ? path3[path3.length - 1].namespace : void 0;
35418
35529
  }
35419
35530
  /**
35420
35531
  * Get current node's attribute value.
@@ -35422,9 +35533,9 @@ var init_Matcher = __esm({
35422
35533
  * @returns {*}
35423
35534
  */
35424
35535
  getAttrValue(attrName) {
35425
- const path2 = this._matcher.path;
35426
- if (path2.length === 0) return void 0;
35427
- return path2[path2.length - 1].values?.[attrName];
35536
+ const path3 = this._matcher.path;
35537
+ if (path3.length === 0) return void 0;
35538
+ return path3[path3.length - 1].values?.[attrName];
35428
35539
  }
35429
35540
  /**
35430
35541
  * Check if current node has an attribute.
@@ -35432,9 +35543,9 @@ var init_Matcher = __esm({
35432
35543
  * @returns {boolean}
35433
35544
  */
35434
35545
  hasAttr(attrName) {
35435
- const path2 = this._matcher.path;
35436
- if (path2.length === 0) return false;
35437
- const current = path2[path2.length - 1];
35546
+ const path3 = this._matcher.path;
35547
+ if (path3.length === 0) return false;
35548
+ const current = path3[path3.length - 1];
35438
35549
  return current.values !== void 0 && attrName in current.values;
35439
35550
  }
35440
35551
  /**
@@ -35442,18 +35553,18 @@ var init_Matcher = __esm({
35442
35553
  * @returns {number}
35443
35554
  */
35444
35555
  getPosition() {
35445
- const path2 = this._matcher.path;
35446
- if (path2.length === 0) return -1;
35447
- return path2[path2.length - 1].position ?? 0;
35556
+ const path3 = this._matcher.path;
35557
+ if (path3.length === 0) return -1;
35558
+ return path3[path3.length - 1].position ?? 0;
35448
35559
  }
35449
35560
  /**
35450
35561
  * Get current node's repeat counter (occurrence count of this tag name).
35451
35562
  * @returns {number}
35452
35563
  */
35453
35564
  getCounter() {
35454
- const path2 = this._matcher.path;
35455
- if (path2.length === 0) return -1;
35456
- return path2[path2.length - 1].counter ?? 0;
35565
+ const path3 = this._matcher.path;
35566
+ if (path3.length === 0) return -1;
35567
+ return path3[path3.length - 1].counter ?? 0;
35457
35568
  }
35458
35569
  /**
35459
35570
  * Get current node's sibling index (alias for getPosition).
@@ -47219,12 +47330,12 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
47219
47330
  const password = request.password ?? "";
47220
47331
  auth = `${username}:${password}`;
47221
47332
  }
47222
- let path2 = request.path;
47333
+ let path3 = request.path;
47223
47334
  if (queryString) {
47224
- path2 += `?${queryString}`;
47335
+ path3 += `?${queryString}`;
47225
47336
  }
47226
47337
  if (request.fragment) {
47227
- path2 += `#${request.fragment}`;
47338
+ path3 += `#${request.fragment}`;
47228
47339
  }
47229
47340
  let hostname = request.hostname ?? "";
47230
47341
  if (hostname[0] === "[" && hostname.endsWith("]")) {
@@ -47236,7 +47347,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
47236
47347
  headers: request.headers,
47237
47348
  host: hostname,
47238
47349
  method: request.method,
47239
- path: path2,
47350
+ path: path3,
47240
47351
  port: request.port,
47241
47352
  agent,
47242
47353
  auth
@@ -58203,12 +58314,12 @@ init_postgres();
58203
58314
 
58204
58315
  // src/gui/realtime.ts
58205
58316
  import { EventEmitter } from "events";
58206
- import { createRequire as createRequire2 } from "module";
58317
+ import { createRequire as createRequire3 } from "module";
58207
58318
  var _pgModule = null;
58208
58319
  function loadPg() {
58209
58320
  if (_pgModule) return _pgModule;
58210
58321
  const importMetaUrl = import.meta.url;
58211
- const requireFromHere = importMetaUrl ? createRequire2(importMetaUrl) : (
58322
+ const requireFromHere = importMetaUrl ? createRequire3(importMetaUrl) : (
58212
58323
  // CJS fallback — Node provides `require` on every CJS module scope.
58213
58324
  __require
58214
58325
  );
@@ -59582,7 +59693,7 @@ async function applySchemaConfig(active, entry, direction, autoRender) {
59582
59693
  const doc = loadConfigDoc(active.configPath);
59583
59694
  const inv = direction === "inverse";
59584
59695
  const ddl = [];
59585
- const has = (path2) => doc.getIn(path2) !== void 0;
59696
+ const has = (path3) => doc.getIn(path3) !== void 0;
59586
59697
  const reAddEntity = async (name, def) => {
59587
59698
  if (has(["entities", name])) {
59588
59699
  throw new Error(`Cannot restore "${name}": an entity with that name already exists`);
@@ -70125,9 +70236,9 @@ function rewriteDbLine(configPath, newValue) {
70125
70236
  function parseSaveBody(body) {
70126
70237
  const type = body.type;
70127
70238
  if (type === "sqlite") {
70128
- const path2 = typeof body.path === "string" && body.path.trim() ? body.path.trim() : "";
70129
- if (!path2) return null;
70130
- return { type: "sqlite", path: path2 };
70239
+ const path3 = typeof body.path === "string" && body.path.trim() ? body.path.trim() : "";
70240
+ if (!path3) return null;
70241
+ return { type: "sqlite", path: path3 };
70131
70242
  }
70132
70243
  if (type === "postgres") {
70133
70244
  const label = typeof body.label === "string" && body.label.trim() ? body.label.trim() : "";
@@ -71865,12 +71976,12 @@ import { basename as basename11, extname as extname2, resolve as resolve11, join
71865
71976
 
71866
71977
  // src/ai/vision.ts
71867
71978
  init_llm_client();
71868
- import { createRequire as createRequire6 } from "module";
71979
+ import { createRequire as createRequire7 } from "module";
71869
71980
  import { readFile as readFile8 } from "fs/promises";
71870
71981
  var DEFAULT_PROMPT = "Describe this image for a knowledge base in 2-4 factual sentences: what it shows, any visible text, and notable details. No preamble.";
71871
71982
  var MAX_DIM = 1568;
71872
- async function describeImage(auth, path2, opts = {}) {
71873
- const data = (await normalizeImage(path2, opts.maxBytes ?? 14e5)).toString("base64");
71983
+ async function describeImage(auth, path3, opts = {}) {
71984
+ const data = (await normalizeImage(path3, opts.maxBytes ?? 14e5)).toString("base64");
71874
71985
  const sender = opts.sender ?? defaultSender(auth);
71875
71986
  const text = await sender({
71876
71987
  media_type: "image/jpeg",
@@ -71881,8 +71992,8 @@ async function describeImage(auth, path2, opts = {}) {
71881
71992
  return text.trim();
71882
71993
  }
71883
71994
  var DEFAULT_PDF_PROMPT = "Read this document for a knowledge base. First transcribe its readable text, then add a 2-4 sentence factual summary of what it is and its key details. It may be a scanned/image-only PDF \u2014 read the text from the page images. No preamble.";
71884
- async function describePdf(auth, path2, opts = {}) {
71885
- const buf = await readFile8(path2);
71995
+ async function describePdf(auth, path3, opts = {}) {
71996
+ const buf = await readFile8(path3);
71886
71997
  const maxBytes = opts.maxBytes ?? 3e7;
71887
71998
  if (buf.length > maxBytes) {
71888
71999
  throw new Error(
@@ -71897,19 +72008,19 @@ async function describePdf(auth, path2, opts = {}) {
71897
72008
  });
71898
72009
  return text.trim();
71899
72010
  }
71900
- async function normalizeImage(path2, maxBytes) {
72011
+ async function normalizeImage(path3, maxBytes) {
71901
72012
  const sharpMod = await import("sharp");
71902
72013
  const sharp = sharpMod.default;
71903
72014
  let quality = 80;
71904
- let buf = await renderJpeg(sharp, path2, quality);
72015
+ let buf = await renderJpeg(sharp, path3, quality);
71905
72016
  while (buf.length > maxBytes && quality > 35) {
71906
72017
  quality -= 15;
71907
- buf = await renderJpeg(sharp, path2, quality);
72018
+ buf = await renderJpeg(sharp, path3, quality);
71908
72019
  }
71909
72020
  return buf;
71910
72021
  }
71911
- function renderJpeg(sharp, path2, quality) {
71912
- return sharp(path2).rotate().resize({ width: MAX_DIM, height: MAX_DIM, fit: "inside", withoutEnlargement: true }).jpeg({ quality }).toBuffer();
72022
+ function renderJpeg(sharp, path3, quality) {
72023
+ return sharp(path3).rotate().resize({ width: MAX_DIM, height: MAX_DIM, fit: "inside", withoutEnlargement: true }).jpeg({ quality }).toBuffer();
71913
72024
  }
71914
72025
  function buildVisionAnthropicConfig(auth) {
71915
72026
  const config = {};
@@ -71927,7 +72038,7 @@ function buildVisionAnthropicConfig(auth) {
71927
72038
  function defaultSender(auth) {
71928
72039
  return async (input) => {
71929
72040
  const importMetaUrl = import.meta.url;
71930
- const req = importMetaUrl ? createRequire6(importMetaUrl) : __require;
72041
+ const req = importMetaUrl ? createRequire7(importMetaUrl) : __require;
71931
72042
  const sdk = req("@anthropic-ai/sdk");
71932
72043
  const Anthropic = sdk.Anthropic ?? sdk.default;
71933
72044
  if (!Anthropic) throw new Error("Could not resolve Anthropic from '@anthropic-ai/sdk'");
@@ -71954,7 +72065,7 @@ function defaultSender(auth) {
71954
72065
  function defaultPdfSender(auth) {
71955
72066
  return async (input) => {
71956
72067
  const importMetaUrl = import.meta.url;
71957
- const req = importMetaUrl ? createRequire6(importMetaUrl) : __require;
72068
+ const req = importMetaUrl ? createRequire7(importMetaUrl) : __require;
71958
72069
  const sdk = req("@anthropic-ai/sdk");
71959
72070
  const Anthropic = sdk.Anthropic ?? sdk.default;
71960
72071
  if (!Anthropic) throw new Error("Could not resolve Anthropic from '@anthropic-ai/sdk'");
@@ -73275,28 +73386,28 @@ ${err.stack ?? ""}`
73275
73386
  return null;
73276
73387
  }
73277
73388
  }
73278
- async function extractImage(db, path2, mime) {
73389
+ async function extractImage(db, path3, mime) {
73279
73390
  if (!mime.startsWith("image/")) return null;
73280
73391
  const auth = await resolveClaudeAuth(db);
73281
73392
  if (!auth) return null;
73282
73393
  try {
73283
- const text = await describeImage(auth, path2);
73394
+ const text = await describeImage(auth, path3);
73284
73395
  return text.trim() ? { text, skip: false } : null;
73285
73396
  } catch (e6) {
73286
73397
  console.warn("[ingest] image vision failed:", e6.message);
73287
73398
  return null;
73288
73399
  }
73289
73400
  }
73290
- async function extractSource(db, path2, mime, name) {
73291
- const vision = await extractImage(db, path2, mime);
73401
+ async function extractSource(db, path3, mime, name) {
73402
+ const vision = await extractImage(db, path3, mime);
73292
73403
  if (vision) return vision;
73293
- const parsed = await parseFile(path2, mime, name);
73404
+ const parsed = await parseFile(path3, mime, name);
73294
73405
  if (!parsed.skip) return parsed;
73295
73406
  if (mime === "application/pdf") {
73296
73407
  const auth = await resolveClaudeAuth(db);
73297
73408
  if (auth) {
73298
73409
  try {
73299
- const text = await describePdf(auth, path2);
73410
+ const text = await describePdf(auth, path3);
73300
73411
  if (text.trim()) return { ...parsed, text, skip: false };
73301
73412
  } catch (e6) {
73302
73413
  console.warn("[ingest] Claude PDF read failed:", e6.message);
@@ -73709,11 +73820,11 @@ async function readImportSourceFromFile(db, fileId, latticeRoot) {
73709
73820
  [fileId]
73710
73821
  );
73711
73822
  if (!row) throw badRequest("Unknown import file: " + fileId);
73712
- const path2 = localPathOf2(row, latticeRoot);
73713
- if (!path2 || !existsSync27(path2)) {
73823
+ const path3 = localPathOf2(row, latticeRoot);
73824
+ if (!path3 || !existsSync27(path3)) {
73714
73825
  throw badRequest("The import file\u2019s bytes are not available locally.");
73715
73826
  }
73716
- const sizeBytes = statSync9(path2).size;
73827
+ const sizeBytes = statSync9(path3).size;
73717
73828
  if (sizeBytes > MAX_INGEST_BYTES) {
73718
73829
  throw badRequest(
73719
73830
  `The import file is too large (${String(Math.round(sizeBytes / 1e6))} MB); the limit is ${String(Math.round(MAX_INGEST_BYTES / 1e6))} MB.`
@@ -73722,11 +73833,11 @@ async function readImportSourceFromFile(db, fileId, latticeRoot) {
73722
73833
  const name = row.original_name ?? "";
73723
73834
  const mime = row.mime ?? "";
73724
73835
  if (/\.xlsx?$/i.test(name) || mime.includes("spreadsheet") || mime.includes("excel")) {
73725
- return excelToRecords(path2);
73836
+ return excelToRecords(path3);
73726
73837
  }
73727
73838
  let parsed;
73728
73839
  try {
73729
- parsed = JSON.parse(readFileSync23(path2, "utf8"));
73840
+ parsed = JSON.parse(readFileSync23(path3, "utf8"));
73730
73841
  } catch {
73731
73842
  throw badRequest("The import file is not valid JSON.");
73732
73843
  }
@@ -76506,7 +76617,7 @@ function printHelp() {
76506
76617
  );
76507
76618
  }
76508
76619
  function getVersion() {
76509
- if (true) return "4.2.0";
76620
+ if (true) return "4.2.2";
76510
76621
  try {
76511
76622
  const pkgPath = new URL("../package.json", import.meta.url).pathname;
76512
76623
  const pkg = JSON.parse(readFileSync25(pkgPath, "utf-8"));