@askexenow/exe-os 0.9.7 → 0.9.9

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.
Files changed (101) hide show
  1. package/dist/bin/backfill-conversations.js +953 -105
  2. package/dist/bin/backfill-responses.js +952 -104
  3. package/dist/bin/backfill-vectors.js +956 -108
  4. package/dist/bin/cleanup-stale-review-tasks.js +802 -58
  5. package/dist/bin/cli.js +2292 -1070
  6. package/dist/bin/exe-agent-config.js +157 -101
  7. package/dist/bin/exe-agent.js +55 -29
  8. package/dist/bin/exe-assign.js +940 -92
  9. package/dist/bin/exe-boot.js +1424 -442
  10. package/dist/bin/exe-call.js +240 -141
  11. package/dist/bin/exe-cloud.js +198 -70
  12. package/dist/bin/exe-dispatch.js +951 -192
  13. package/dist/bin/exe-doctor.js +791 -51
  14. package/dist/bin/exe-export-behaviors.js +790 -42
  15. package/dist/bin/exe-forget.js +771 -31
  16. package/dist/bin/exe-gateway.js +1592 -521
  17. package/dist/bin/exe-heartbeat.js +850 -109
  18. package/dist/bin/exe-kill.js +783 -35
  19. package/dist/bin/exe-launch-agent.js +1030 -107
  20. package/dist/bin/exe-link.js +916 -110
  21. package/dist/bin/exe-new-employee.js +526 -217
  22. package/dist/bin/exe-pending-messages.js +1046 -62
  23. package/dist/bin/exe-pending-notifications.js +1318 -111
  24. package/dist/bin/exe-pending-reviews.js +1040 -72
  25. package/dist/bin/exe-rename.js +772 -59
  26. package/dist/bin/exe-review.js +772 -32
  27. package/dist/bin/exe-search.js +982 -128
  28. package/dist/bin/exe-session-cleanup.js +1180 -306
  29. package/dist/bin/exe-settings.js +185 -105
  30. package/dist/bin/exe-start-codex.js +886 -132
  31. package/dist/bin/exe-start-opencode.js +873 -119
  32. package/dist/bin/exe-status.js +803 -59
  33. package/dist/bin/exe-team.js +772 -32
  34. package/dist/bin/git-sweep.js +1046 -223
  35. package/dist/bin/graph-backfill.js +779 -31
  36. package/dist/bin/graph-export.js +785 -37
  37. package/dist/bin/install.js +632 -200
  38. package/dist/bin/scan-tasks.js +1055 -232
  39. package/dist/bin/setup.js +1419 -320
  40. package/dist/bin/shard-migrate.js +783 -35
  41. package/dist/bin/update.js +138 -49
  42. package/dist/bin/wiki-sync.js +782 -34
  43. package/dist/gateway/index.js +1444 -449
  44. package/dist/hooks/bug-report-worker.js +1141 -269
  45. package/dist/hooks/codex-stop-task-finalizer.js +4678 -0
  46. package/dist/hooks/commit-complete.js +1044 -221
  47. package/dist/hooks/error-recall.js +989 -135
  48. package/dist/hooks/exe-heartbeat-hook.js +99 -75
  49. package/dist/hooks/ingest-worker.js +4176 -3226
  50. package/dist/hooks/ingest.js +920 -168
  51. package/dist/hooks/instructions-loaded.js +874 -70
  52. package/dist/hooks/notification.js +860 -56
  53. package/dist/hooks/post-compact.js +881 -73
  54. package/dist/hooks/pre-compact.js +1050 -227
  55. package/dist/hooks/pre-tool-use.js +1084 -159
  56. package/dist/hooks/prompt-ingest-worker.js +1089 -164
  57. package/dist/hooks/prompt-submit.js +1469 -515
  58. package/dist/hooks/response-ingest-worker.js +1104 -179
  59. package/dist/hooks/session-end.js +1085 -251
  60. package/dist/hooks/session-start.js +1241 -231
  61. package/dist/hooks/stop.js +935 -109
  62. package/dist/hooks/subagent-stop.js +881 -73
  63. package/dist/hooks/summary-worker.js +1323 -307
  64. package/dist/index.js +1449 -452
  65. package/dist/lib/agent-config.js +28 -6
  66. package/dist/lib/cloud-sync.js +909 -115
  67. package/dist/lib/config.js +30 -10
  68. package/dist/lib/consolidation.js +42 -9
  69. package/dist/lib/database.js +739 -33
  70. package/dist/lib/db-daemon-client.js +73 -19
  71. package/dist/lib/db.js +2359 -0
  72. package/dist/lib/device-registry.js +760 -47
  73. package/dist/lib/embedder.js +201 -73
  74. package/dist/lib/employee-templates.js +30 -4
  75. package/dist/lib/employees.js +290 -86
  76. package/dist/lib/exe-daemon-client.js +187 -83
  77. package/dist/lib/exe-daemon.js +1696 -616
  78. package/dist/lib/hybrid-search.js +982 -128
  79. package/dist/lib/identity.js +43 -13
  80. package/dist/lib/license.js +133 -48
  81. package/dist/lib/messaging.js +167 -80
  82. package/dist/lib/reminders.js +35 -5
  83. package/dist/lib/schedules.js +772 -32
  84. package/dist/lib/skill-learning.js +54 -7
  85. package/dist/lib/store.js +779 -31
  86. package/dist/lib/task-router.js +94 -73
  87. package/dist/lib/tasks.js +298 -225
  88. package/dist/lib/tmux-routing.js +246 -172
  89. package/dist/lib/token-spend.js +52 -14
  90. package/dist/mcp/server.js +2893 -850
  91. package/dist/mcp/tools/complete-reminder.js +35 -5
  92. package/dist/mcp/tools/create-reminder.js +35 -5
  93. package/dist/mcp/tools/create-task.js +507 -323
  94. package/dist/mcp/tools/deactivate-behavior.js +40 -10
  95. package/dist/mcp/tools/list-reminders.js +35 -5
  96. package/dist/mcp/tools/list-tasks.js +277 -104
  97. package/dist/mcp/tools/send-message.js +129 -56
  98. package/dist/mcp/tools/update-task.js +1864 -188
  99. package/dist/runtime/index.js +1083 -259
  100. package/dist/tui/App.js +1501 -434
  101. package/package.json +3 -2
@@ -72,6 +72,44 @@ var init_db_retry = __esm({
72
72
  }
73
73
  });
74
74
 
75
+ // src/lib/secure-files.ts
76
+ import { chmodSync, existsSync, mkdirSync } from "fs";
77
+ import { chmod, mkdir } from "fs/promises";
78
+ async function ensurePrivateDir(dirPath) {
79
+ await mkdir(dirPath, { recursive: true, mode: PRIVATE_DIR_MODE });
80
+ try {
81
+ await chmod(dirPath, PRIVATE_DIR_MODE);
82
+ } catch {
83
+ }
84
+ }
85
+ function ensurePrivateDirSync(dirPath) {
86
+ mkdirSync(dirPath, { recursive: true, mode: PRIVATE_DIR_MODE });
87
+ try {
88
+ chmodSync(dirPath, PRIVATE_DIR_MODE);
89
+ } catch {
90
+ }
91
+ }
92
+ async function enforcePrivateFile(filePath) {
93
+ try {
94
+ await chmod(filePath, PRIVATE_FILE_MODE);
95
+ } catch {
96
+ }
97
+ }
98
+ function enforcePrivateFileSync(filePath) {
99
+ try {
100
+ if (existsSync(filePath)) chmodSync(filePath, PRIVATE_FILE_MODE);
101
+ } catch {
102
+ }
103
+ }
104
+ var PRIVATE_DIR_MODE, PRIVATE_FILE_MODE;
105
+ var init_secure_files = __esm({
106
+ "src/lib/secure-files.ts"() {
107
+ "use strict";
108
+ PRIVATE_DIR_MODE = 448;
109
+ PRIVATE_FILE_MODE = 384;
110
+ }
111
+ });
112
+
75
113
  // src/lib/config.ts
76
114
  var config_exports = {};
77
115
  __export(config_exports, {
@@ -88,8 +126,8 @@ __export(config_exports, {
88
126
  migrateConfig: () => migrateConfig,
89
127
  saveConfig: () => saveConfig
90
128
  });
91
- import { readFile, writeFile, mkdir, chmod } from "fs/promises";
92
- import { readFileSync, existsSync, renameSync } from "fs";
129
+ import { readFile, writeFile } from "fs/promises";
130
+ import { readFileSync, existsSync as existsSync2, renameSync } from "fs";
93
131
  import path from "path";
94
132
  import os from "os";
95
133
  function resolveDataDir() {
@@ -97,7 +135,7 @@ function resolveDataDir() {
97
135
  if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
98
136
  const newDir = path.join(os.homedir(), ".exe-os");
99
137
  const legacyDir = path.join(os.homedir(), ".exe-mem");
100
- if (!existsSync(newDir) && existsSync(legacyDir)) {
138
+ if (!existsSync2(newDir) && existsSync2(legacyDir)) {
101
139
  try {
102
140
  renameSync(legacyDir, newDir);
103
141
  process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
@@ -160,9 +198,9 @@ function normalizeAutoUpdate(raw) {
160
198
  }
161
199
  async function loadConfig() {
162
200
  const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
163
- await mkdir(dir, { recursive: true });
201
+ await ensurePrivateDir(dir);
164
202
  const configPath = path.join(dir, "config.json");
165
- if (!existsSync(configPath)) {
203
+ if (!existsSync2(configPath)) {
166
204
  return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
167
205
  }
168
206
  const raw = await readFile(configPath, "utf-8");
@@ -175,6 +213,7 @@ async function loadConfig() {
175
213
  `);
176
214
  try {
177
215
  await writeFile(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
216
+ await enforcePrivateFile(configPath);
178
217
  } catch {
179
218
  }
180
219
  }
@@ -193,7 +232,7 @@ async function loadConfig() {
193
232
  function loadConfigSync() {
194
233
  const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
195
234
  const configPath = path.join(dir, "config.json");
196
- if (!existsSync(configPath)) {
235
+ if (!existsSync2(configPath)) {
197
236
  return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
198
237
  }
199
238
  try {
@@ -211,12 +250,10 @@ function loadConfigSync() {
211
250
  }
212
251
  async function saveConfig(config) {
213
252
  const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
214
- await mkdir(dir, { recursive: true });
253
+ await ensurePrivateDir(dir);
215
254
  const configPath = path.join(dir, "config.json");
216
255
  await writeFile(configPath, JSON.stringify(config, null, 2) + "\n");
217
- if (config.cloud?.apiKey) {
218
- await chmod(configPath, 384);
219
- }
256
+ await enforcePrivateFile(configPath);
220
257
  }
221
258
  async function loadConfigFrom(configPath) {
222
259
  const raw = await readFile(configPath, "utf-8");
@@ -236,6 +273,7 @@ var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CON
236
273
  var init_config = __esm({
237
274
  "src/lib/config.ts"() {
238
275
  "use strict";
276
+ init_secure_files();
239
277
  EXE_AI_DIR = resolveDataDir();
240
278
  DB_PATH = path.join(EXE_AI_DIR, "memories.db");
241
279
  MODELS_DIR = path.join(EXE_AI_DIR, "models");
@@ -314,7 +352,7 @@ var init_config = __esm({
314
352
 
315
353
  // src/lib/employees.ts
316
354
  import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
317
- import { existsSync as existsSync2, symlinkSync, readlinkSync, readFileSync as readFileSync2, renameSync as renameSync2, unlinkSync, writeFileSync } from "fs";
355
+ import { existsSync as existsSync3, symlinkSync, readlinkSync, readFileSync as readFileSync2, renameSync as renameSync2, unlinkSync, writeFileSync } from "fs";
318
356
  import { execSync } from "child_process";
319
357
  import path2 from "path";
320
358
  import os2 from "os";
@@ -331,14 +369,14 @@ function getCoordinatorName(employees = loadEmployeesSync()) {
331
369
  return getCoordinatorEmployee(employees)?.name ?? DEFAULT_COORDINATOR_TEMPLATE_NAME;
332
370
  }
333
371
  function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
334
- if (!existsSync2(employeesPath)) return [];
372
+ if (!existsSync3(employeesPath)) return [];
335
373
  try {
336
374
  return JSON.parse(readFileSync2(employeesPath, "utf-8"));
337
375
  } catch {
338
376
  return [];
339
377
  }
340
378
  }
341
- var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE;
379
+ var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE, IDENTITY_DIR;
342
380
  var init_employees = __esm({
343
381
  "src/lib/employees.ts"() {
344
382
  "use strict";
@@ -346,12 +384,609 @@ var init_employees = __esm({
346
384
  EMPLOYEES_PATH = path2.join(EXE_AI_DIR, "exe-employees.json");
347
385
  DEFAULT_COORDINATOR_TEMPLATE_NAME = "exe";
348
386
  COORDINATOR_ROLE = "COO";
387
+ IDENTITY_DIR = path2.join(EXE_AI_DIR, "identity");
388
+ }
389
+ });
390
+
391
+ // src/lib/database-adapter.ts
392
+ import os3 from "os";
393
+ import path3 from "path";
394
+ import { createRequire } from "module";
395
+ import { pathToFileURL } from "url";
396
+ function quotedIdentifier(identifier) {
397
+ return `"${identifier.replace(/"/g, '""')}"`;
398
+ }
399
+ function unqualifiedTableName(name) {
400
+ const raw = name.trim().replace(/^"|"$/g, "");
401
+ const parts = raw.split(".");
402
+ return parts[parts.length - 1].replace(/^"|"$/g, "").toLowerCase();
403
+ }
404
+ function stripTrailingSemicolon(sql) {
405
+ return sql.trim().replace(/;+\s*$/u, "");
406
+ }
407
+ function appendClause(sql, clause) {
408
+ const trimmed = stripTrailingSemicolon(sql);
409
+ const returningMatch = /\sRETURNING\b[\s\S]*$/iu.exec(trimmed);
410
+ if (!returningMatch) {
411
+ return `${trimmed}${clause}`;
412
+ }
413
+ const idx = returningMatch.index;
414
+ return `${trimmed.slice(0, idx)}${clause}${trimmed.slice(idx)}`;
415
+ }
416
+ function normalizeStatement(stmt) {
417
+ if (typeof stmt === "string") {
418
+ return { kind: "positional", sql: stmt, args: [] };
419
+ }
420
+ const sql = stmt.sql;
421
+ if (Array.isArray(stmt.args) || stmt.args === void 0) {
422
+ return { kind: "positional", sql, args: stmt.args ?? [] };
423
+ }
424
+ return { kind: "named", sql, args: stmt.args };
425
+ }
426
+ function rewriteBooleanLiterals(sql) {
427
+ let out = sql;
428
+ for (const column of BOOLEAN_COLUMN_NAMES) {
429
+ const scoped = `((?:\\b[a-z_][a-z0-9_]*\\.)?${column})`;
430
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*0\\b`, "giu"), "$1 = FALSE");
431
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*1\\b`, "giu"), "$1 = TRUE");
432
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*0\\b`, "giu"), "$1 != FALSE");
433
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*1\\b`, "giu"), "$1 != TRUE");
434
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*0\\b`, "giu"), "$1 <> FALSE");
435
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*1\\b`, "giu"), "$1 <> TRUE");
436
+ }
437
+ return out;
438
+ }
439
+ function rewriteInsertOrIgnore(sql) {
440
+ if (!/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu.test(sql)) {
441
+ return sql;
442
+ }
443
+ const replaced = sql.replace(/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu, "INSERT INTO");
444
+ return /\bON\s+CONFLICT\b/iu.test(replaced) ? replaced : appendClause(replaced, " ON CONFLICT DO NOTHING");
445
+ }
446
+ function rewriteInsertOrReplace(sql) {
447
+ const match = /^\s*INSERT\s+OR\s+REPLACE\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)([\s\S]*)$/iu.exec(sql);
448
+ if (!match) {
449
+ return sql;
450
+ }
451
+ const rawTable = match[1];
452
+ const rawColumns = match[2];
453
+ const remainder = match[3];
454
+ const tableName = unqualifiedTableName(rawTable);
455
+ const conflictKeys = UPSERT_KEYS[tableName];
456
+ if (!conflictKeys?.length) {
457
+ return sql;
458
+ }
459
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
460
+ const updateColumns = columns.filter((col) => !conflictKeys.includes(col));
461
+ const conflictTarget = conflictKeys.map(quotedIdentifier).join(", ");
462
+ const updateClause = updateColumns.length === 0 ? " DO NOTHING" : ` DO UPDATE SET ${updateColumns.map((col) => `${quotedIdentifier(col)} = EXCLUDED.${quotedIdentifier(col)}`).join(", ")}`;
463
+ return `INSERT INTO ${rawTable} (${rawColumns})${appendClause(remainder, ` ON CONFLICT (${conflictTarget})${updateClause}`)}`;
464
+ }
465
+ function rewriteSql(sql) {
466
+ let out = sql;
467
+ out = out.replace(/\bdatetime\(\s*['"]now['"]\s*\)/giu, "CURRENT_TIMESTAMP");
468
+ out = out.replace(/\bvector32\s*\(\s*\?\s*\)/giu, "?");
469
+ out = rewriteBooleanLiterals(out);
470
+ out = rewriteInsertOrReplace(out);
471
+ out = rewriteInsertOrIgnore(out);
472
+ return stripTrailingSemicolon(out);
473
+ }
474
+ function toBoolean(value) {
475
+ if (value === null || value === void 0) return value;
476
+ if (typeof value === "boolean") return value;
477
+ if (typeof value === "number") return value !== 0;
478
+ if (typeof value === "bigint") return value !== 0n;
479
+ if (typeof value === "string") {
480
+ const normalized = value.trim().toLowerCase();
481
+ if (normalized === "0" || normalized === "false") return false;
482
+ if (normalized === "1" || normalized === "true") return true;
483
+ }
484
+ return Boolean(value);
485
+ }
486
+ function countQuestionMarks(sql, end) {
487
+ let count = 0;
488
+ let inSingle = false;
489
+ let inDouble = false;
490
+ let inLineComment = false;
491
+ let inBlockComment = false;
492
+ for (let i = 0; i < end; i++) {
493
+ const ch = sql[i];
494
+ const next = sql[i + 1];
495
+ if (inLineComment) {
496
+ if (ch === "\n") inLineComment = false;
497
+ continue;
498
+ }
499
+ if (inBlockComment) {
500
+ if (ch === "*" && next === "/") {
501
+ inBlockComment = false;
502
+ i += 1;
503
+ }
504
+ continue;
505
+ }
506
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
507
+ inLineComment = true;
508
+ i += 1;
509
+ continue;
510
+ }
511
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
512
+ inBlockComment = true;
513
+ i += 1;
514
+ continue;
515
+ }
516
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
517
+ inSingle = !inSingle;
518
+ continue;
519
+ }
520
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
521
+ inDouble = !inDouble;
522
+ continue;
523
+ }
524
+ if (!inSingle && !inDouble && ch === "?") {
525
+ count += 1;
526
+ }
527
+ }
528
+ return count;
529
+ }
530
+ function findBooleanPlaceholderIndexes(sql) {
531
+ const indexes = /* @__PURE__ */ new Set();
532
+ for (const column of BOOLEAN_COLUMN_NAMES) {
533
+ const pattern = new RegExp(`(?:\\b[a-z_][a-z0-9_]*\\.)?${column}\\s*=\\s*\\?`, "giu");
534
+ for (const match of sql.matchAll(pattern)) {
535
+ const matchText = match[0];
536
+ const qIndex = match.index + matchText.lastIndexOf("?");
537
+ indexes.add(countQuestionMarks(sql, qIndex + 1));
538
+ }
539
+ }
540
+ return indexes;
541
+ }
542
+ function coerceInsertBooleanArgs(sql, args) {
543
+ const match = /^\s*INSERT(?:\s+OR\s+(?:IGNORE|REPLACE))?\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)/iu.exec(sql);
544
+ if (!match) return;
545
+ const rawTable = match[1];
546
+ const rawColumns = match[2];
547
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
548
+ if (!boolColumns?.size) return;
549
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
550
+ for (const [index, column] of columns.entries()) {
551
+ if (boolColumns.has(column) && index < args.length) {
552
+ args[index] = toBoolean(args[index]);
553
+ }
554
+ }
555
+ }
556
+ function coerceUpdateBooleanArgs(sql, args) {
557
+ const match = /^\s*UPDATE\s+([A-Za-z0-9_."]+)\s+SET\s+([\s\S]+?)(?:\s+WHERE\b|$)/iu.exec(sql);
558
+ if (!match) return;
559
+ const rawTable = match[1];
560
+ const setClause = match[2];
561
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
562
+ if (!boolColumns?.size) return;
563
+ const assignments = setClause.split(",");
564
+ let placeholderIndex = 0;
565
+ for (const assignment of assignments) {
566
+ if (!assignment.includes("?")) continue;
567
+ placeholderIndex += 1;
568
+ const colMatch = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*\?/iu.exec(assignment);
569
+ if (colMatch && boolColumns.has(colMatch[1])) {
570
+ args[placeholderIndex - 1] = toBoolean(args[placeholderIndex - 1]);
571
+ }
572
+ }
573
+ }
574
+ function coerceBooleanArgs(sql, args) {
575
+ const nextArgs = [...args];
576
+ coerceInsertBooleanArgs(sql, nextArgs);
577
+ coerceUpdateBooleanArgs(sql, nextArgs);
578
+ const placeholderIndexes = findBooleanPlaceholderIndexes(sql);
579
+ for (const index of placeholderIndexes) {
580
+ if (index > 0 && index <= nextArgs.length) {
581
+ nextArgs[index - 1] = toBoolean(nextArgs[index - 1]);
582
+ }
583
+ }
584
+ return nextArgs;
585
+ }
586
+ function convertQuestionMarksToDollarParams(sql) {
587
+ let out = "";
588
+ let placeholder = 0;
589
+ let inSingle = false;
590
+ let inDouble = false;
591
+ let inLineComment = false;
592
+ let inBlockComment = false;
593
+ for (let i = 0; i < sql.length; i++) {
594
+ const ch = sql[i];
595
+ const next = sql[i + 1];
596
+ if (inLineComment) {
597
+ out += ch;
598
+ if (ch === "\n") inLineComment = false;
599
+ continue;
600
+ }
601
+ if (inBlockComment) {
602
+ out += ch;
603
+ if (ch === "*" && next === "/") {
604
+ out += next;
605
+ inBlockComment = false;
606
+ i += 1;
607
+ }
608
+ continue;
609
+ }
610
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
611
+ out += ch + next;
612
+ inLineComment = true;
613
+ i += 1;
614
+ continue;
615
+ }
616
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
617
+ out += ch + next;
618
+ inBlockComment = true;
619
+ i += 1;
620
+ continue;
621
+ }
622
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
623
+ inSingle = !inSingle;
624
+ out += ch;
625
+ continue;
626
+ }
627
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
628
+ inDouble = !inDouble;
629
+ out += ch;
630
+ continue;
631
+ }
632
+ if (!inSingle && !inDouble && ch === "?") {
633
+ placeholder += 1;
634
+ out += `$${placeholder}`;
635
+ continue;
636
+ }
637
+ out += ch;
638
+ }
639
+ return out;
640
+ }
641
+ function translateStatementForPostgres(stmt) {
642
+ const normalized = normalizeStatement(stmt);
643
+ if (normalized.kind === "named") {
644
+ throw new Error("Named SQL parameters are not supported by the Prisma adapter.");
645
+ }
646
+ const rewrittenSql = rewriteSql(normalized.sql);
647
+ const coercedArgs = coerceBooleanArgs(rewrittenSql, normalized.args);
648
+ return {
649
+ sql: convertQuestionMarksToDollarParams(rewrittenSql),
650
+ args: coercedArgs
651
+ };
652
+ }
653
+ function shouldBypassPostgres(stmt) {
654
+ const normalized = normalizeStatement(stmt);
655
+ if (normalized.kind === "named") {
656
+ return true;
657
+ }
658
+ return IMMEDIATE_FALLBACK_PATTERNS.some((pattern) => pattern.test(normalized.sql));
659
+ }
660
+ function shouldFallbackOnError(error) {
661
+ const message = error instanceof Error ? error.message : String(error);
662
+ return /42P01|42883|42601|does not exist|syntax error|not supported|Named SQL parameters are not supported/iu.test(message);
663
+ }
664
+ function isReadQuery(sql) {
665
+ const trimmed = sql.trimStart();
666
+ return /^(SELECT|WITH|SHOW|EXPLAIN|VALUES)\b/iu.test(trimmed) || /\bRETURNING\b/iu.test(trimmed);
667
+ }
668
+ function buildRow(row, columns) {
669
+ const values = columns.map((column) => row[column]);
670
+ return Object.assign(values, row);
671
+ }
672
+ function buildResultSet(rows, rowsAffected = 0) {
673
+ const columns = rows[0] ? Object.keys(rows[0]) : [];
674
+ const resultRows = rows.map((row) => buildRow(row, columns));
675
+ return {
676
+ columns,
677
+ columnTypes: columns.map(() => ""),
678
+ rows: resultRows,
679
+ rowsAffected,
680
+ lastInsertRowid: void 0,
681
+ toJSON() {
682
+ return {
683
+ columns,
684
+ columnTypes: columns.map(() => ""),
685
+ rows,
686
+ rowsAffected,
687
+ lastInsertRowid: void 0
688
+ };
689
+ }
690
+ };
691
+ }
692
+ async function loadPrismaClient() {
693
+ if (!prismaClientPromise) {
694
+ prismaClientPromise = (async () => {
695
+ const explicitPath = process.env.EXE_OS_PRISMA_CLIENT_PATH;
696
+ if (explicitPath) {
697
+ const module2 = await import(pathToFileURL(explicitPath).href);
698
+ const PrismaClient2 = module2.PrismaClient ?? module2.default?.PrismaClient;
699
+ if (!PrismaClient2) {
700
+ throw new Error(`No PrismaClient export found at ${explicitPath}`);
701
+ }
702
+ return new PrismaClient2();
703
+ }
704
+ const exeDbRoot = process.env.EXE_DB_ROOT ?? path3.join(os3.homedir(), "exe-db");
705
+ const requireFromExeDb = createRequire(path3.join(exeDbRoot, "package.json"));
706
+ const prismaEntry = requireFromExeDb.resolve("@prisma/client");
707
+ const module = await import(pathToFileURL(prismaEntry).href);
708
+ const PrismaClient = module.PrismaClient ?? module.default?.PrismaClient;
709
+ if (!PrismaClient) {
710
+ throw new Error(`No PrismaClient export found in ${prismaEntry}`);
711
+ }
712
+ return new PrismaClient();
713
+ })();
714
+ }
715
+ return prismaClientPromise;
716
+ }
717
+ async function ensureCompatibilityViews(prisma) {
718
+ if (!compatibilityBootstrapPromise) {
719
+ compatibilityBootstrapPromise = (async () => {
720
+ for (const mapping of VIEW_MAPPINGS) {
721
+ const relation = mapping.source.replace(/"/g, "");
722
+ const rows = await prisma.$queryRawUnsafe(
723
+ "SELECT to_regclass($1) AS regclass",
724
+ relation
725
+ );
726
+ if (!rows[0]?.regclass) {
727
+ continue;
728
+ }
729
+ await prisma.$executeRawUnsafe(
730
+ `CREATE OR REPLACE VIEW public.${quotedIdentifier(mapping.view)} AS SELECT * FROM ${mapping.source}`
731
+ );
732
+ }
733
+ })();
734
+ }
735
+ return compatibilityBootstrapPromise;
736
+ }
737
+ async function executeOnPrisma(executor, stmt) {
738
+ const translated = translateStatementForPostgres(stmt);
739
+ if (isReadQuery(translated.sql)) {
740
+ const rows = await executor.$queryRawUnsafe(
741
+ translated.sql,
742
+ ...translated.args
743
+ );
744
+ return buildResultSet(rows, /\bRETURNING\b/iu.test(translated.sql) ? rows.length : 0);
745
+ }
746
+ const rowsAffected = await executor.$executeRawUnsafe(translated.sql, ...translated.args);
747
+ return buildResultSet([], rowsAffected);
748
+ }
749
+ function splitSqlStatements(sql) {
750
+ const parts = [];
751
+ let current = "";
752
+ let inSingle = false;
753
+ let inDouble = false;
754
+ let inLineComment = false;
755
+ let inBlockComment = false;
756
+ for (let i = 0; i < sql.length; i++) {
757
+ const ch = sql[i];
758
+ const next = sql[i + 1];
759
+ if (inLineComment) {
760
+ current += ch;
761
+ if (ch === "\n") inLineComment = false;
762
+ continue;
763
+ }
764
+ if (inBlockComment) {
765
+ current += ch;
766
+ if (ch === "*" && next === "/") {
767
+ current += next;
768
+ inBlockComment = false;
769
+ i += 1;
770
+ }
771
+ continue;
772
+ }
773
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
774
+ current += ch + next;
775
+ inLineComment = true;
776
+ i += 1;
777
+ continue;
778
+ }
779
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
780
+ current += ch + next;
781
+ inBlockComment = true;
782
+ i += 1;
783
+ continue;
784
+ }
785
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
786
+ inSingle = !inSingle;
787
+ current += ch;
788
+ continue;
789
+ }
790
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
791
+ inDouble = !inDouble;
792
+ current += ch;
793
+ continue;
794
+ }
795
+ if (!inSingle && !inDouble && ch === ";") {
796
+ if (current.trim()) {
797
+ parts.push(current.trim());
798
+ }
799
+ current = "";
800
+ continue;
801
+ }
802
+ current += ch;
803
+ }
804
+ if (current.trim()) {
805
+ parts.push(current.trim());
806
+ }
807
+ return parts;
808
+ }
809
+ async function createPrismaDbAdapter(fallbackClient) {
810
+ const prisma = await loadPrismaClient();
811
+ await ensureCompatibilityViews(prisma);
812
+ let closed = false;
813
+ let adapter;
814
+ const fallbackExecute = async (stmt, error) => {
815
+ if (!fallbackClient) {
816
+ if (error) throw error;
817
+ throw new Error("No fallback SQLite client is available for this Prisma-routed query.");
818
+ }
819
+ if (error) {
820
+ process.stderr.write(
821
+ `[database-adapter] Falling back to SQLite: ${error instanceof Error ? error.message : String(error)}
822
+ `
823
+ );
824
+ }
825
+ return fallbackClient.execute(stmt);
826
+ };
827
+ adapter = {
828
+ async execute(stmt) {
829
+ if (shouldBypassPostgres(stmt)) {
830
+ return fallbackExecute(stmt);
831
+ }
832
+ try {
833
+ return await executeOnPrisma(prisma, stmt);
834
+ } catch (error) {
835
+ if (shouldFallbackOnError(error)) {
836
+ return fallbackExecute(stmt, error);
837
+ }
838
+ throw error;
839
+ }
840
+ },
841
+ async batch(stmts, mode) {
842
+ if (stmts.some((stmt) => shouldBypassPostgres(stmt))) {
843
+ if (!fallbackClient) {
844
+ throw new Error("Cannot batch unsupported SQLite-only statements without a fallback client.");
845
+ }
846
+ return fallbackClient.batch(stmts, mode);
847
+ }
848
+ try {
849
+ if (prisma.$transaction) {
850
+ return await prisma.$transaction(async (tx) => {
851
+ const results2 = [];
852
+ for (const stmt of stmts) {
853
+ results2.push(await executeOnPrisma(tx, stmt));
854
+ }
855
+ return results2;
856
+ });
857
+ }
858
+ const results = [];
859
+ for (const stmt of stmts) {
860
+ results.push(await executeOnPrisma(prisma, stmt));
861
+ }
862
+ return results;
863
+ } catch (error) {
864
+ if (fallbackClient && shouldFallbackOnError(error)) {
865
+ process.stderr.write(
866
+ `[database-adapter] Falling back batch to SQLite: ${error instanceof Error ? error.message : String(error)}
867
+ `
868
+ );
869
+ return fallbackClient.batch(stmts, mode);
870
+ }
871
+ throw error;
872
+ }
873
+ },
874
+ async migrate(stmts) {
875
+ if (fallbackClient) {
876
+ return fallbackClient.migrate(stmts);
877
+ }
878
+ return adapter.batch(stmts, "deferred");
879
+ },
880
+ async transaction(mode) {
881
+ if (!fallbackClient) {
882
+ throw new Error("Interactive transactions are only supported on the SQLite fallback client.");
883
+ }
884
+ return fallbackClient.transaction(mode);
885
+ },
886
+ async executeMultiple(sql) {
887
+ if (fallbackClient && shouldBypassPostgres(sql)) {
888
+ return fallbackClient.executeMultiple(sql);
889
+ }
890
+ for (const statement of splitSqlStatements(sql)) {
891
+ await adapter.execute(statement);
892
+ }
893
+ },
894
+ async sync() {
895
+ if (fallbackClient) {
896
+ return fallbackClient.sync();
897
+ }
898
+ return { frame_no: 0, frames_synced: 0 };
899
+ },
900
+ close() {
901
+ closed = true;
902
+ prismaClientPromise = null;
903
+ compatibilityBootstrapPromise = null;
904
+ void prisma.$disconnect?.();
905
+ },
906
+ get closed() {
907
+ return closed;
908
+ },
909
+ get protocol() {
910
+ return "prisma-postgres";
911
+ }
912
+ };
913
+ return adapter;
914
+ }
915
+ var VIEW_MAPPINGS, UPSERT_KEYS, BOOLEAN_COLUMNS_BY_TABLE, BOOLEAN_COLUMN_NAMES, IMMEDIATE_FALLBACK_PATTERNS, prismaClientPromise, compatibilityBootstrapPromise;
916
+ var init_database_adapter = __esm({
917
+ "src/lib/database-adapter.ts"() {
918
+ "use strict";
919
+ VIEW_MAPPINGS = [
920
+ { view: "memories", source: "memory.memory_records" },
921
+ { view: "tasks", source: "memory.tasks" },
922
+ { view: "behaviors", source: "memory.behaviors" },
923
+ { view: "entities", source: "memory.entities" },
924
+ { view: "relationships", source: "memory.relationships" },
925
+ { view: "entity_memories", source: "memory.entity_memories" },
926
+ { view: "entity_aliases", source: "memory.entity_aliases" },
927
+ { view: "notifications", source: "memory.notifications" },
928
+ { view: "messages", source: "memory.messages" },
929
+ { view: "users", source: "wiki.users" },
930
+ { view: "workspaces", source: "wiki.workspaces" },
931
+ { view: "workspace_users", source: "wiki.workspace_users" },
932
+ { view: "documents", source: "wiki.workspace_documents" },
933
+ { view: "chats", source: "wiki.workspace_chats" }
934
+ ];
935
+ UPSERT_KEYS = {
936
+ memories: ["id"],
937
+ tasks: ["id"],
938
+ behaviors: ["id"],
939
+ entities: ["id"],
940
+ relationships: ["id"],
941
+ entity_aliases: ["alias"],
942
+ notifications: ["id"],
943
+ messages: ["id"],
944
+ users: ["id"],
945
+ workspaces: ["id"],
946
+ workspace_users: ["id"],
947
+ documents: ["id"],
948
+ chats: ["id"]
949
+ };
950
+ BOOLEAN_COLUMNS_BY_TABLE = {
951
+ memories: /* @__PURE__ */ new Set(["has_error", "draft"]),
952
+ behaviors: /* @__PURE__ */ new Set(["active"]),
953
+ notifications: /* @__PURE__ */ new Set(["read"]),
954
+ users: /* @__PURE__ */ new Set(["has_personal_memory"])
955
+ };
956
+ BOOLEAN_COLUMN_NAMES = new Set(
957
+ Object.values(BOOLEAN_COLUMNS_BY_TABLE).flatMap((cols) => [...cols])
958
+ );
959
+ IMMEDIATE_FALLBACK_PATTERNS = [
960
+ /\bPRAGMA\b/i,
961
+ /\bsqlite_master\b/i,
962
+ /(?:^|[.\s])(?:memories|conversations|entities)_fts\b/i,
963
+ /\bMATCH\b/i,
964
+ /\bvector_distance_cos\s*\(/i,
965
+ /\bjson_extract\s*\(/i,
966
+ /\bjulianday\s*\(/i,
967
+ /\bstrftime\s*\(/i,
968
+ /\blast_insert_rowid\s*\(/i
969
+ ];
970
+ prismaClientPromise = null;
971
+ compatibilityBootstrapPromise = null;
349
972
  }
350
973
  });
351
974
 
352
975
  // src/lib/database.ts
353
976
  import { createClient } from "@libsql/client";
354
977
  async function initDatabase(config) {
978
+ if (_walCheckpointTimer) {
979
+ clearInterval(_walCheckpointTimer);
980
+ _walCheckpointTimer = null;
981
+ }
982
+ if (_daemonClient) {
983
+ _daemonClient.close();
984
+ _daemonClient = null;
985
+ }
986
+ if (_adapterClient && _adapterClient !== _resilientClient) {
987
+ _adapterClient.close();
988
+ }
989
+ _adapterClient = null;
355
990
  if (_client) {
356
991
  _client.close();
357
992
  _client = null;
@@ -365,6 +1000,7 @@ async function initDatabase(config) {
365
1000
  }
366
1001
  _client = createClient(opts);
367
1002
  _resilientClient = wrapWithRetry(_client);
1003
+ _adapterClient = _resilientClient;
368
1004
  _client.execute("PRAGMA busy_timeout = 30000").catch(() => {
369
1005
  });
370
1006
  _client.execute("PRAGMA journal_mode = WAL").catch(() => {
@@ -375,11 +1011,17 @@ async function initDatabase(config) {
375
1011
  });
376
1012
  }, 3e4);
377
1013
  _walCheckpointTimer.unref();
1014
+ if (process.env.DATABASE_URL) {
1015
+ _adapterClient = await createPrismaDbAdapter(_resilientClient);
1016
+ }
378
1017
  }
379
1018
  function getClient() {
380
- if (!_resilientClient) {
1019
+ if (!_adapterClient) {
381
1020
  throw new Error("Database client not initialized. Call initDatabase() first.");
382
1021
  }
1022
+ if (process.env.DATABASE_URL) {
1023
+ return _adapterClient;
1024
+ }
383
1025
  if (process.env.EXE_IS_DAEMON === "1") {
384
1026
  return _resilientClient;
385
1027
  }
@@ -672,6 +1314,7 @@ async function ensureSchema() {
672
1314
  project TEXT NOT NULL,
673
1315
  summary TEXT NOT NULL,
674
1316
  task_file TEXT,
1317
+ session_scope TEXT,
675
1318
  read INTEGER NOT NULL DEFAULT 0,
676
1319
  created_at TEXT NOT NULL
677
1320
  );
@@ -680,7 +1323,7 @@ async function ensureSchema() {
680
1323
  ON notifications(read);
681
1324
 
682
1325
  CREATE INDEX IF NOT EXISTS idx_notifications_agent
683
- ON notifications(agent_id);
1326
+ ON notifications(agent_id, session_scope);
684
1327
 
685
1328
  CREATE INDEX IF NOT EXISTS idx_notifications_task_file
686
1329
  ON notifications(task_file);
@@ -718,6 +1361,7 @@ async function ensureSchema() {
718
1361
  target_agent TEXT NOT NULL,
719
1362
  target_project TEXT,
720
1363
  target_device TEXT NOT NULL DEFAULT 'local',
1364
+ session_scope TEXT,
721
1365
  content TEXT NOT NULL,
722
1366
  priority TEXT DEFAULT 'normal',
723
1367
  status TEXT DEFAULT 'pending',
@@ -731,10 +1375,31 @@ async function ensureSchema() {
731
1375
  );
732
1376
 
733
1377
  CREATE INDEX IF NOT EXISTS idx_messages_target
734
- ON messages(target_agent, status);
1378
+ ON messages(target_agent, session_scope, status);
735
1379
 
736
1380
  CREATE INDEX IF NOT EXISTS idx_messages_conversation_order
737
- ON messages(target_agent, from_agent, server_seq);
1381
+ ON messages(target_agent, session_scope, from_agent, server_seq);
1382
+ `);
1383
+ try {
1384
+ await client.execute({
1385
+ sql: `ALTER TABLE notifications ADD COLUMN session_scope TEXT`,
1386
+ args: []
1387
+ });
1388
+ } catch {
1389
+ }
1390
+ try {
1391
+ await client.execute({
1392
+ sql: `ALTER TABLE messages ADD COLUMN session_scope TEXT`,
1393
+ args: []
1394
+ });
1395
+ } catch {
1396
+ }
1397
+ await client.executeMultiple(`
1398
+ CREATE INDEX IF NOT EXISTS idx_notifications_agent_scope_read
1399
+ ON notifications(agent_id, session_scope, read, created_at);
1400
+
1401
+ CREATE INDEX IF NOT EXISTS idx_messages_target_scope_status
1402
+ ON messages(target_agent, session_scope, status, created_at);
738
1403
  `);
739
1404
  try {
740
1405
  await client.execute({
@@ -1318,28 +1983,45 @@ async function ensureSchema() {
1318
1983
  } catch {
1319
1984
  }
1320
1985
  }
1986
+ try {
1987
+ await client.execute({
1988
+ sql: `UPDATE tasks SET status = 'closed' WHERE status = 'done' AND result IS NOT NULL`,
1989
+ args: []
1990
+ });
1991
+ } catch {
1992
+ }
1321
1993
  }
1322
1994
  async function disposeDatabase() {
1995
+ if (_walCheckpointTimer) {
1996
+ clearInterval(_walCheckpointTimer);
1997
+ _walCheckpointTimer = null;
1998
+ }
1323
1999
  if (_daemonClient) {
1324
2000
  _daemonClient.close();
1325
2001
  _daemonClient = null;
1326
2002
  }
2003
+ if (_adapterClient && _adapterClient !== _resilientClient) {
2004
+ _adapterClient.close();
2005
+ }
2006
+ _adapterClient = null;
1327
2007
  if (_client) {
1328
2008
  _client.close();
1329
2009
  _client = null;
1330
2010
  _resilientClient = null;
1331
2011
  }
1332
2012
  }
1333
- var _client, _resilientClient, _walCheckpointTimer, _daemonClient, initTurso, disposeTurso;
2013
+ var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso, disposeTurso;
1334
2014
  var init_database = __esm({
1335
2015
  "src/lib/database.ts"() {
1336
2016
  "use strict";
1337
2017
  init_db_retry();
1338
2018
  init_employees();
2019
+ init_database_adapter();
1339
2020
  _client = null;
1340
2021
  _resilientClient = null;
1341
2022
  _walCheckpointTimer = null;
1342
2023
  _daemonClient = null;
2024
+ _adapterClient = null;
1343
2025
  initTurso = initDatabase;
1344
2026
  disposeTurso = disposeDatabase;
1345
2027
  }
@@ -1347,14 +2029,14 @@ var init_database = __esm({
1347
2029
 
1348
2030
  // src/lib/keychain.ts
1349
2031
  import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
1350
- import { existsSync as existsSync3 } from "fs";
1351
- import path3 from "path";
1352
- import os3 from "os";
2032
+ import { existsSync as existsSync4 } from "fs";
2033
+ import path4 from "path";
2034
+ import os4 from "os";
1353
2035
  function getKeyDir() {
1354
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path3.join(os3.homedir(), ".exe-os");
2036
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path4.join(os4.homedir(), ".exe-os");
1355
2037
  }
1356
2038
  function getKeyPath() {
1357
- return path3.join(getKeyDir(), "master.key");
2039
+ return path4.join(getKeyDir(), "master.key");
1358
2040
  }
1359
2041
  async function tryKeytar() {
1360
2042
  try {
@@ -1375,9 +2057,9 @@ async function getMasterKey() {
1375
2057
  }
1376
2058
  }
1377
2059
  const keyPath = getKeyPath();
1378
- if (!existsSync3(keyPath)) {
2060
+ if (!existsSync4(keyPath)) {
1379
2061
  process.stderr.write(
1380
- `[keychain] Key not found at ${keyPath} (HOME=${os3.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2062
+ `[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
1381
2063
  `
1382
2064
  );
1383
2065
  return null;
@@ -1462,6 +2144,7 @@ var shard_manager_exports = {};
1462
2144
  __export(shard_manager_exports, {
1463
2145
  disposeShards: () => disposeShards,
1464
2146
  ensureShardSchema: () => ensureShardSchema,
2147
+ getOpenShardCount: () => getOpenShardCount,
1465
2148
  getReadyShardClient: () => getReadyShardClient,
1466
2149
  getShardClient: () => getShardClient,
1467
2150
  getShardsDir: () => getShardsDir,
@@ -1470,15 +2153,18 @@ __export(shard_manager_exports, {
1470
2153
  listShards: () => listShards,
1471
2154
  shardExists: () => shardExists
1472
2155
  });
1473
- import path4 from "path";
1474
- import { existsSync as existsSync4, mkdirSync, readdirSync } from "fs";
2156
+ import path5 from "path";
2157
+ import { existsSync as existsSync5, mkdirSync as mkdirSync2, readdirSync } from "fs";
1475
2158
  import { createClient as createClient2 } from "@libsql/client";
1476
2159
  function initShardManager(encryptionKey) {
1477
2160
  _encryptionKey = encryptionKey;
1478
- if (!existsSync4(SHARDS_DIR)) {
1479
- mkdirSync(SHARDS_DIR, { recursive: true });
2161
+ if (!existsSync5(SHARDS_DIR)) {
2162
+ mkdirSync2(SHARDS_DIR, { recursive: true });
1480
2163
  }
1481
2164
  _shardingEnabled = true;
2165
+ if (_evictionTimer) clearInterval(_evictionTimer);
2166
+ _evictionTimer = setInterval(evictIdleShards, EVICTION_INTERVAL_MS);
2167
+ _evictionTimer.unref();
1482
2168
  }
1483
2169
  function isShardingEnabled() {
1484
2170
  return _shardingEnabled;
@@ -1495,21 +2181,28 @@ function getShardClient(projectName) {
1495
2181
  throw new Error(`Invalid project name for shard: "${projectName}"`);
1496
2182
  }
1497
2183
  const cached = _shards.get(safeName);
1498
- if (cached) return cached;
1499
- const dbPath = path4.join(SHARDS_DIR, `${safeName}.db`);
2184
+ if (cached) {
2185
+ _shardLastAccess.set(safeName, Date.now());
2186
+ return cached;
2187
+ }
2188
+ while (_shards.size >= MAX_OPEN_SHARDS) {
2189
+ evictLRU();
2190
+ }
2191
+ const dbPath = path5.join(SHARDS_DIR, `${safeName}.db`);
1500
2192
  const client = createClient2({
1501
2193
  url: `file:${dbPath}`,
1502
2194
  encryptionKey: _encryptionKey
1503
2195
  });
1504
2196
  _shards.set(safeName, client);
2197
+ _shardLastAccess.set(safeName, Date.now());
1505
2198
  return client;
1506
2199
  }
1507
2200
  function shardExists(projectName) {
1508
2201
  const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1509
- return existsSync4(path4.join(SHARDS_DIR, `${safeName}.db`));
2202
+ return existsSync5(path5.join(SHARDS_DIR, `${safeName}.db`));
1510
2203
  }
1511
2204
  function listShards() {
1512
- if (!existsSync4(SHARDS_DIR)) return [];
2205
+ if (!existsSync5(SHARDS_DIR)) return [];
1513
2206
  return readdirSync(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
1514
2207
  }
1515
2208
  async function ensureShardSchema(client) {
@@ -1561,6 +2254,8 @@ async function ensureShardSchema(client) {
1561
2254
  for (const col of [
1562
2255
  "ALTER TABLE memories ADD COLUMN task_id TEXT",
1563
2256
  "ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0",
2257
+ "ALTER TABLE memories ADD COLUMN author_device_id TEXT",
2258
+ "ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'",
1564
2259
  "ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5",
1565
2260
  "ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'",
1566
2261
  "ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0",
@@ -1583,7 +2278,23 @@ async function ensureShardSchema(client) {
1583
2278
  // MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
1584
2279
  "ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
1585
2280
  "ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
1586
- "ALTER TABLE memories ADD COLUMN trajectory TEXT"
2281
+ "ALTER TABLE memories ADD COLUMN trajectory TEXT",
2282
+ // Metadata enrichment columns (must match database.ts)
2283
+ "ALTER TABLE memories ADD COLUMN intent TEXT",
2284
+ "ALTER TABLE memories ADD COLUMN outcome TEXT",
2285
+ "ALTER TABLE memories ADD COLUMN domain TEXT",
2286
+ "ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
2287
+ "ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
2288
+ "ALTER TABLE memories ADD COLUMN chain_position TEXT",
2289
+ "ALTER TABLE memories ADD COLUMN review_status TEXT",
2290
+ "ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
2291
+ "ALTER TABLE memories ADD COLUMN file_paths TEXT",
2292
+ "ALTER TABLE memories ADD COLUMN commit_hash TEXT",
2293
+ "ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
2294
+ "ALTER TABLE memories ADD COLUMN token_cost REAL",
2295
+ "ALTER TABLE memories ADD COLUMN audience TEXT",
2296
+ "ALTER TABLE memories ADD COLUMN language_type TEXT",
2297
+ "ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
1587
2298
  ]) {
1588
2299
  try {
1589
2300
  await client.execute(col);
@@ -1682,21 +2393,69 @@ async function getReadyShardClient(projectName) {
1682
2393
  await ensureShardSchema(client);
1683
2394
  return client;
1684
2395
  }
2396
+ function evictLRU() {
2397
+ let oldest = null;
2398
+ let oldestTime = Infinity;
2399
+ for (const [name, time] of _shardLastAccess) {
2400
+ if (time < oldestTime) {
2401
+ oldestTime = time;
2402
+ oldest = name;
2403
+ }
2404
+ }
2405
+ if (oldest) {
2406
+ const client = _shards.get(oldest);
2407
+ if (client) {
2408
+ client.close();
2409
+ }
2410
+ _shards.delete(oldest);
2411
+ _shardLastAccess.delete(oldest);
2412
+ }
2413
+ }
2414
+ function evictIdleShards() {
2415
+ const now = Date.now();
2416
+ const toEvict = [];
2417
+ for (const [name, lastAccess] of _shardLastAccess) {
2418
+ if (now - lastAccess > SHARD_IDLE_MS) {
2419
+ toEvict.push(name);
2420
+ }
2421
+ }
2422
+ for (const name of toEvict) {
2423
+ const client = _shards.get(name);
2424
+ if (client) {
2425
+ client.close();
2426
+ }
2427
+ _shards.delete(name);
2428
+ _shardLastAccess.delete(name);
2429
+ }
2430
+ }
2431
+ function getOpenShardCount() {
2432
+ return _shards.size;
2433
+ }
1685
2434
  function disposeShards() {
2435
+ if (_evictionTimer) {
2436
+ clearInterval(_evictionTimer);
2437
+ _evictionTimer = null;
2438
+ }
1686
2439
  for (const [, client] of _shards) {
1687
2440
  client.close();
1688
2441
  }
1689
2442
  _shards.clear();
2443
+ _shardLastAccess.clear();
1690
2444
  _shardingEnabled = false;
1691
2445
  _encryptionKey = null;
1692
2446
  }
1693
- var SHARDS_DIR, _shards, _encryptionKey, _shardingEnabled;
2447
+ var SHARDS_DIR, SHARD_IDLE_MS, MAX_OPEN_SHARDS, EVICTION_INTERVAL_MS, _shards, _shardLastAccess, _evictionTimer, _encryptionKey, _shardingEnabled;
1694
2448
  var init_shard_manager = __esm({
1695
2449
  "src/lib/shard-manager.ts"() {
1696
2450
  "use strict";
1697
2451
  init_config();
1698
- SHARDS_DIR = path4.join(EXE_AI_DIR, "shards");
2452
+ SHARDS_DIR = path5.join(EXE_AI_DIR, "shards");
2453
+ SHARD_IDLE_MS = 5 * 60 * 1e3;
2454
+ MAX_OPEN_SHARDS = 10;
2455
+ EVICTION_INTERVAL_MS = 60 * 1e3;
1699
2456
  _shards = /* @__PURE__ */ new Map();
2457
+ _shardLastAccess = /* @__PURE__ */ new Map();
2458
+ _evictionTimer = null;
1700
2459
  _encryptionKey = null;
1701
2460
  _shardingEnabled = false;
1702
2461
  }
@@ -2558,8 +3317,8 @@ __export(reranker_exports, {
2558
3317
  rerankWithContext: () => rerankWithContext,
2559
3318
  rerankWithScores: () => rerankWithScores
2560
3319
  });
2561
- import path5 from "path";
2562
- import { existsSync as existsSync5 } from "fs";
3320
+ import path6 from "path";
3321
+ import { existsSync as existsSync6 } from "fs";
2563
3322
  function resetIdleTimer() {
2564
3323
  if (_idleTimer) clearTimeout(_idleTimer);
2565
3324
  _idleTimer = setTimeout(() => {
@@ -2570,18 +3329,18 @@ function resetIdleTimer() {
2570
3329
  }
2571
3330
  }
2572
3331
  function isRerankerAvailable() {
2573
- return existsSync5(path5.join(MODELS_DIR, RERANKER_MODEL_FILE));
3332
+ return existsSync6(path6.join(MODELS_DIR, RERANKER_MODEL_FILE));
2574
3333
  }
2575
3334
  function getRerankerModelPath() {
2576
- return path5.join(MODELS_DIR, RERANKER_MODEL_FILE);
3335
+ return path6.join(MODELS_DIR, RERANKER_MODEL_FILE);
2577
3336
  }
2578
3337
  async function ensureLoaded() {
2579
3338
  if (_rerankerContext) {
2580
3339
  resetIdleTimer();
2581
3340
  return;
2582
3341
  }
2583
- const modelPath = path5.join(MODELS_DIR, RERANKER_MODEL_FILE);
2584
- if (!existsSync5(modelPath)) {
3342
+ const modelPath = path6.join(MODELS_DIR, RERANKER_MODEL_FILE);
3343
+ if (!existsSync6(modelPath)) {
2585
3344
  throw new Error(
2586
3345
  `Reranker model not found at ${modelPath}. Run /exe-setup to download it.`
2587
3346
  );
@@ -2677,13 +3436,50 @@ var init_reranker = __esm({
2677
3436
  }
2678
3437
  });
2679
3438
 
3439
+ // src/lib/daemon-auth.ts
3440
+ import crypto from "crypto";
3441
+ import path7 from "path";
3442
+ import { existsSync as existsSync7, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
3443
+ function normalizeToken(token) {
3444
+ if (!token) return null;
3445
+ const trimmed = token.trim();
3446
+ return trimmed.length > 0 ? trimmed : null;
3447
+ }
3448
+ function readDaemonToken() {
3449
+ try {
3450
+ if (!existsSync7(DAEMON_TOKEN_PATH)) return null;
3451
+ return normalizeToken(readFileSync3(DAEMON_TOKEN_PATH, "utf8"));
3452
+ } catch {
3453
+ return null;
3454
+ }
3455
+ }
3456
+ function ensureDaemonToken(seed) {
3457
+ const existing = readDaemonToken();
3458
+ if (existing) return existing;
3459
+ const token = normalizeToken(seed) ?? crypto.randomBytes(32).toString("hex");
3460
+ ensurePrivateDirSync(EXE_AI_DIR);
3461
+ writeFileSync2(DAEMON_TOKEN_PATH, `${token}
3462
+ `, "utf8");
3463
+ enforcePrivateFileSync(DAEMON_TOKEN_PATH);
3464
+ return token;
3465
+ }
3466
+ var DAEMON_TOKEN_PATH;
3467
+ var init_daemon_auth = __esm({
3468
+ "src/lib/daemon-auth.ts"() {
3469
+ "use strict";
3470
+ init_config();
3471
+ init_secure_files();
3472
+ DAEMON_TOKEN_PATH = path7.join(EXE_AI_DIR, "exed.token");
3473
+ }
3474
+ });
3475
+
2680
3476
  // src/lib/exe-daemon-client.ts
2681
3477
  import net from "net";
2682
- import os4 from "os";
3478
+ import os5 from "os";
2683
3479
  import { spawn } from "child_process";
2684
3480
  import { randomUUID as randomUUID2 } from "crypto";
2685
- import { existsSync as existsSync6, unlinkSync as unlinkSync2, readFileSync as readFileSync3, openSync, closeSync, statSync } from "fs";
2686
- import path6 from "path";
3481
+ import { existsSync as existsSync8, unlinkSync as unlinkSync2, readFileSync as readFileSync4, openSync, closeSync, statSync } from "fs";
3482
+ import path8 from "path";
2687
3483
  import { fileURLToPath } from "url";
2688
3484
  function handleData(chunk) {
2689
3485
  _buffer += chunk.toString();
@@ -2711,9 +3507,9 @@ function handleData(chunk) {
2711
3507
  }
2712
3508
  }
2713
3509
  function cleanupStaleFiles() {
2714
- if (existsSync6(PID_PATH)) {
3510
+ if (existsSync8(PID_PATH)) {
2715
3511
  try {
2716
- const pid = parseInt(readFileSync3(PID_PATH, "utf8").trim(), 10);
3512
+ const pid = parseInt(readFileSync4(PID_PATH, "utf8").trim(), 10);
2717
3513
  if (pid > 0) {
2718
3514
  try {
2719
3515
  process.kill(pid, 0);
@@ -2734,17 +3530,17 @@ function cleanupStaleFiles() {
2734
3530
  }
2735
3531
  }
2736
3532
  function findPackageRoot() {
2737
- let dir = path6.dirname(fileURLToPath(import.meta.url));
2738
- const { root } = path6.parse(dir);
3533
+ let dir = path8.dirname(fileURLToPath(import.meta.url));
3534
+ const { root } = path8.parse(dir);
2739
3535
  while (dir !== root) {
2740
- if (existsSync6(path6.join(dir, "package.json"))) return dir;
2741
- dir = path6.dirname(dir);
3536
+ if (existsSync8(path8.join(dir, "package.json"))) return dir;
3537
+ dir = path8.dirname(dir);
2742
3538
  }
2743
3539
  return null;
2744
3540
  }
2745
3541
  function spawnDaemon() {
2746
- const freeGB = os4.freemem() / (1024 * 1024 * 1024);
2747
- const totalGB = os4.totalmem() / (1024 * 1024 * 1024);
3542
+ const freeGB = os5.freemem() / (1024 * 1024 * 1024);
3543
+ const totalGB = os5.totalmem() / (1024 * 1024 * 1024);
2748
3544
  if (totalGB <= 8) {
2749
3545
  process.stderr.write(
2750
3546
  `[exed-client] SKIP: ${totalGB.toFixed(0)}GB system \u2014 embedding daemon disabled. Using keyword search only. Minimum 16GB recommended for vector search.
@@ -2764,16 +3560,17 @@ function spawnDaemon() {
2764
3560
  process.stderr.write("[exed-client] WARN: cannot find package root\n");
2765
3561
  return;
2766
3562
  }
2767
- const daemonPath = path6.join(pkgRoot, "dist", "lib", "exe-daemon.js");
2768
- if (!existsSync6(daemonPath)) {
3563
+ const daemonPath = path8.join(pkgRoot, "dist", "lib", "exe-daemon.js");
3564
+ if (!existsSync8(daemonPath)) {
2769
3565
  process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
2770
3566
  `);
2771
3567
  return;
2772
3568
  }
2773
3569
  const resolvedPath = daemonPath;
3570
+ const daemonToken = ensureDaemonToken(process.env[DAEMON_TOKEN_ENV] ?? null);
2774
3571
  process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
2775
3572
  `);
2776
- const logPath = path6.join(path6.dirname(SOCKET_PATH), "exed.log");
3573
+ const logPath = path8.join(path8.dirname(SOCKET_PATH), "exed.log");
2777
3574
  let stderrFd = "ignore";
2778
3575
  try {
2779
3576
  stderrFd = openSync(logPath, "a");
@@ -2791,7 +3588,8 @@ function spawnDaemon() {
2791
3588
  TMUX_PANE: void 0,
2792
3589
  // Prevents resolveExeSession() from scoping to one session
2793
3590
  EXE_DAEMON_SOCK: SOCKET_PATH,
2794
- EXE_DAEMON_PID: PID_PATH
3591
+ EXE_DAEMON_PID: PID_PATH,
3592
+ [DAEMON_TOKEN_ENV]: daemonToken
2795
3593
  }
2796
3594
  });
2797
3595
  child.unref();
@@ -2901,13 +3699,14 @@ function sendDaemonRequest(payload, timeoutMs = REQUEST_TIMEOUT_MS) {
2901
3699
  return;
2902
3700
  }
2903
3701
  const id = randomUUID2();
3702
+ const token = process.env[DAEMON_TOKEN_ENV] ?? readDaemonToken();
2904
3703
  const timer = setTimeout(() => {
2905
3704
  _pending.delete(id);
2906
3705
  resolve({ error: "Request timeout" });
2907
3706
  }, timeoutMs);
2908
3707
  _pending.set(id, { resolve, timer });
2909
3708
  try {
2910
- _socket.write(JSON.stringify({ id, ...payload }) + "\n");
3709
+ _socket.write(JSON.stringify({ id, token, ...payload }) + "\n");
2911
3710
  } catch {
2912
3711
  clearTimeout(timer);
2913
3712
  _pending.delete(id);
@@ -2924,74 +3723,123 @@ async function pingDaemon() {
2924
3723
  return null;
2925
3724
  }
2926
3725
  function killAndRespawnDaemon() {
2927
- process.stderr.write("[exed-client] Killing daemon for restart...\n");
2928
- if (existsSync6(PID_PATH)) {
2929
- try {
2930
- const pid = parseInt(readFileSync3(PID_PATH, "utf8").trim(), 10);
2931
- if (pid > 0) {
2932
- try {
2933
- process.kill(pid, "SIGKILL");
2934
- } catch {
3726
+ if (!acquireSpawnLock()) {
3727
+ process.stderr.write("[exed-client] Another process is already restarting daemon \u2014 skipping\n");
3728
+ if (_socket) {
3729
+ _socket.destroy();
3730
+ _socket = null;
3731
+ }
3732
+ _connected = false;
3733
+ _buffer = "";
3734
+ return;
3735
+ }
3736
+ try {
3737
+ process.stderr.write("[exed-client] Killing daemon for restart...\n");
3738
+ if (existsSync8(PID_PATH)) {
3739
+ try {
3740
+ const pid = parseInt(readFileSync4(PID_PATH, "utf8").trim(), 10);
3741
+ if (pid > 0) {
3742
+ try {
3743
+ process.kill(pid, "SIGKILL");
3744
+ } catch {
3745
+ }
2935
3746
  }
3747
+ } catch {
2936
3748
  }
3749
+ }
3750
+ if (_socket) {
3751
+ _socket.destroy();
3752
+ _socket = null;
3753
+ }
3754
+ _connected = false;
3755
+ _buffer = "";
3756
+ try {
3757
+ unlinkSync2(PID_PATH);
2937
3758
  } catch {
2938
3759
  }
3760
+ try {
3761
+ unlinkSync2(SOCKET_PATH);
3762
+ } catch {
3763
+ }
3764
+ spawnDaemon();
3765
+ } finally {
3766
+ releaseSpawnLock();
2939
3767
  }
2940
- if (_socket) {
2941
- _socket.destroy();
2942
- _socket = null;
2943
- }
2944
- _connected = false;
2945
- _buffer = "";
3768
+ }
3769
+ function isDaemonTooYoung() {
2946
3770
  try {
2947
- unlinkSync2(PID_PATH);
3771
+ const stat = statSync(PID_PATH);
3772
+ return Date.now() - stat.mtimeMs < MIN_DAEMON_AGE_MS;
2948
3773
  } catch {
3774
+ return false;
2949
3775
  }
2950
- try {
2951
- unlinkSync2(SOCKET_PATH);
2952
- } catch {
3776
+ }
3777
+ async function retryThenRestart(doRequest, label) {
3778
+ const result = await doRequest();
3779
+ if (!result.error) {
3780
+ _consecutiveFailures = 0;
3781
+ return result;
3782
+ }
3783
+ _consecutiveFailures++;
3784
+ for (let i = 0; i < MAX_RETRIES_BEFORE_RESTART; i++) {
3785
+ const delayMs = RETRY_DELAYS_MS[i] ?? 5e3;
3786
+ process.stderr.write(`[exed-client] ${label} failed (${result.error}), retry ${i + 1}/${MAX_RETRIES_BEFORE_RESTART} in ${delayMs}ms
3787
+ `);
3788
+ await new Promise((r) => setTimeout(r, delayMs));
3789
+ if (!_connected) {
3790
+ if (!await connectToSocket()) continue;
3791
+ }
3792
+ const retry = await doRequest();
3793
+ if (!retry.error) {
3794
+ _consecutiveFailures = 0;
3795
+ return retry;
3796
+ }
3797
+ _consecutiveFailures++;
3798
+ }
3799
+ if (isDaemonTooYoung()) {
3800
+ process.stderr.write(`[exed-client] ${label}: daemon too young (< ${MIN_DAEMON_AGE_MS / 1e3}s) \u2014 skipping restart
3801
+ `);
3802
+ return { error: result.error };
3803
+ }
3804
+ process.stderr.write(`[exed-client] ${label}: ${_consecutiveFailures} consecutive failures \u2014 restarting daemon
3805
+ `);
3806
+ killAndRespawnDaemon();
3807
+ const start = Date.now();
3808
+ let delay2 = 200;
3809
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
3810
+ await new Promise((r) => setTimeout(r, delay2));
3811
+ if (await connectToSocket()) break;
3812
+ delay2 = Math.min(delay2 * 2, 3e3);
2953
3813
  }
2954
- spawnDaemon();
3814
+ if (!_connected) return { error: "Daemon restart failed" };
3815
+ const final = await doRequest();
3816
+ if (!final.error) _consecutiveFailures = 0;
3817
+ return final;
2955
3818
  }
2956
3819
  async function embedViaClient(text, priority = "high") {
2957
3820
  if (!_connected && !await connectEmbedDaemon()) return null;
2958
3821
  _requestCount++;
2959
3822
  if (_requestCount % HEALTH_CHECK_INTERVAL === 0) {
2960
3823
  const health = await pingDaemon();
2961
- if (!health) {
3824
+ if (!health && !isDaemonTooYoung()) {
2962
3825
  process.stderr.write(`[exed-client] Periodic health check failed at request ${_requestCount} \u2014 restarting daemon
2963
3826
  `);
2964
3827
  killAndRespawnDaemon();
2965
3828
  const start = Date.now();
2966
- let delay2 = 200;
3829
+ let d = 200;
2967
3830
  while (Date.now() - start < CONNECT_TIMEOUT_MS) {
2968
- await new Promise((r) => setTimeout(r, delay2));
3831
+ await new Promise((r) => setTimeout(r, d));
2969
3832
  if (await connectToSocket()) break;
2970
- delay2 = Math.min(delay2 * 2, 3e3);
3833
+ d = Math.min(d * 2, 3e3);
2971
3834
  }
2972
3835
  if (!_connected) return null;
2973
3836
  }
2974
3837
  }
2975
- const result = await sendRequest([text], priority);
2976
- if (!result.error && result.vectors?.[0]) return result.vectors[0];
2977
- if (result.error) {
2978
- process.stderr.write(`[exed-client] Embed failed (${result.error}) \u2014 attempting restart
2979
- `);
2980
- killAndRespawnDaemon();
2981
- const start = Date.now();
2982
- let delay2 = 200;
2983
- while (Date.now() - start < CONNECT_TIMEOUT_MS) {
2984
- await new Promise((r) => setTimeout(r, delay2));
2985
- if (await connectToSocket()) break;
2986
- delay2 = Math.min(delay2 * 2, 3e3);
2987
- }
2988
- if (!_connected) return null;
2989
- const retry = await sendRequest([text], priority);
2990
- if (!retry.error && retry.vectors?.[0]) return retry.vectors[0];
2991
- process.stderr.write(`[exed-client] Embed retry also failed: ${retry.error ?? "no vector"}
2992
- `);
2993
- }
2994
- return null;
3838
+ const result = await retryThenRestart(
3839
+ () => sendRequest([text], priority),
3840
+ "Embed"
3841
+ );
3842
+ return !result.error && result.vectors?.[0] ? result.vectors[0] : null;
2995
3843
  }
2996
3844
  function disconnectClient() {
2997
3845
  if (_socket) {
@@ -3006,22 +3854,28 @@ function disconnectClient() {
3006
3854
  entry.resolve({ error: "Client disconnected" });
3007
3855
  }
3008
3856
  }
3009
- var SOCKET_PATH, PID_PATH, SPAWN_LOCK_PATH, SPAWN_LOCK_STALE_MS, CONNECT_TIMEOUT_MS, REQUEST_TIMEOUT_MS, _socket, _connected, _buffer, _requestCount, HEALTH_CHECK_INTERVAL, _pending, MAX_BUFFER;
3857
+ var SOCKET_PATH, PID_PATH, SPAWN_LOCK_PATH, SPAWN_LOCK_STALE_MS, CONNECT_TIMEOUT_MS, REQUEST_TIMEOUT_MS, DAEMON_TOKEN_ENV, _socket, _connected, _buffer, _requestCount, _consecutiveFailures, HEALTH_CHECK_INTERVAL, MAX_RETRIES_BEFORE_RESTART, RETRY_DELAYS_MS, MIN_DAEMON_AGE_MS, _pending, MAX_BUFFER;
3010
3858
  var init_exe_daemon_client = __esm({
3011
3859
  "src/lib/exe-daemon-client.ts"() {
3012
3860
  "use strict";
3013
3861
  init_config();
3014
- SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path6.join(EXE_AI_DIR, "exed.sock");
3015
- PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path6.join(EXE_AI_DIR, "exed.pid");
3016
- SPAWN_LOCK_PATH = path6.join(EXE_AI_DIR, "exed-spawn.lock");
3862
+ init_daemon_auth();
3863
+ SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path8.join(EXE_AI_DIR, "exed.sock");
3864
+ PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path8.join(EXE_AI_DIR, "exed.pid");
3865
+ SPAWN_LOCK_PATH = path8.join(EXE_AI_DIR, "exed-spawn.lock");
3017
3866
  SPAWN_LOCK_STALE_MS = 3e4;
3018
3867
  CONNECT_TIMEOUT_MS = 15e3;
3019
3868
  REQUEST_TIMEOUT_MS = 3e4;
3869
+ DAEMON_TOKEN_ENV = "EXE_DAEMON_TOKEN";
3020
3870
  _socket = null;
3021
3871
  _connected = false;
3022
3872
  _buffer = "";
3023
3873
  _requestCount = 0;
3874
+ _consecutiveFailures = 0;
3024
3875
  HEALTH_CHECK_INTERVAL = 100;
3876
+ MAX_RETRIES_BEFORE_RESTART = 3;
3877
+ RETRY_DELAYS_MS = [1e3, 3e3, 5e3];
3878
+ MIN_DAEMON_AGE_MS = 3e4;
3025
3879
  _pending = /* @__PURE__ */ new Map();
3026
3880
  MAX_BUFFER = 1e7;
3027
3881
  }
@@ -3064,10 +3918,10 @@ async function disposeEmbedder() {
3064
3918
  async function embedDirect(text) {
3065
3919
  const llamaCpp = await import("node-llama-cpp");
3066
3920
  const { MODELS_DIR: MODELS_DIR2 } = await Promise.resolve().then(() => (init_config(), config_exports));
3067
- const { existsSync: existsSync8 } = await import("fs");
3068
- const path9 = await import("path");
3069
- const modelPath = path9.join(MODELS_DIR2, "jina-embeddings-v5-small-q4_k_m.gguf");
3070
- if (!existsSync8(modelPath)) {
3921
+ const { existsSync: existsSync10 } = await import("fs");
3922
+ const path11 = await import("path");
3923
+ const modelPath = path11.join(MODELS_DIR2, "jina-embeddings-v5-small-q4_k_m.gguf");
3924
+ if (!existsSync10(modelPath)) {
3071
3925
  throw new Error(`Embedding model not found at ${modelPath}. Run '/exe-setup' to download it.`);
3072
3926
  }
3073
3927
  const llama = await llamaCpp.getLlama();
@@ -3102,7 +3956,7 @@ __export(project_name_exports, {
3102
3956
  getProjectName: () => getProjectName
3103
3957
  });
3104
3958
  import { execSync as execSync2 } from "child_process";
3105
- import path7 from "path";
3959
+ import path9 from "path";
3106
3960
  function getProjectName(cwd) {
3107
3961
  const dir = cwd ?? process.cwd();
3108
3962
  if (_cached && _cachedCwd === dir) return _cached;
@@ -3115,7 +3969,7 @@ function getProjectName(cwd) {
3115
3969
  timeout: 2e3,
3116
3970
  stdio: ["pipe", "pipe", "pipe"]
3117
3971
  }).trim();
3118
- repoRoot = path7.dirname(gitCommonDir);
3972
+ repoRoot = path9.dirname(gitCommonDir);
3119
3973
  } catch {
3120
3974
  repoRoot = execSync2("git rev-parse --show-toplevel", {
3121
3975
  cwd: dir,
@@ -3124,11 +3978,11 @@ function getProjectName(cwd) {
3124
3978
  stdio: ["pipe", "pipe", "pipe"]
3125
3979
  }).trim();
3126
3980
  }
3127
- _cached = path7.basename(repoRoot);
3981
+ _cached = path9.basename(repoRoot);
3128
3982
  _cachedCwd = dir;
3129
3983
  return _cached;
3130
3984
  } catch {
3131
- _cached = path7.basename(dir);
3985
+ _cached = path9.basename(dir);
3132
3986
  _cachedCwd = dir;
3133
3987
  return _cached;
3134
3988
  }
@@ -3152,9 +4006,9 @@ __export(file_grep_exports, {
3152
4006
  grepProjectFiles: () => grepProjectFiles
3153
4007
  });
3154
4008
  import { execSync as execSync3 } from "child_process";
3155
- import { readFileSync as readFileSync4, readdirSync as readdirSync2, statSync as statSync2, existsSync as existsSync7 } from "fs";
3156
- import path8 from "path";
3157
- import crypto from "crypto";
4009
+ import { readFileSync as readFileSync5, readdirSync as readdirSync2, statSync as statSync2, existsSync as existsSync9 } from "fs";
4010
+ import path10 from "path";
4011
+ import crypto2 from "crypto";
3158
4012
  function hasRipgrep() {
3159
4013
  if (_hasRg === null) {
3160
4014
  try {
@@ -3187,13 +4041,13 @@ async function grepProjectFiles(query, projectRoot, options) {
3187
4041
  const chunkCtx = getChunkContext(hit.filePath, hit.lineNumber);
3188
4042
  const prefix = chunkCtx ? `[file: ${hit.filePath}:${hit.lineNumber} in ${chunkCtx}]` : `[file: ${hit.filePath}:${hit.lineNumber}]`;
3189
4043
  return {
3190
- id: crypto.createHash("sha256").update(`${hit.filePath}:${hit.lineNumber}`).digest("hex").slice(0, 36),
4044
+ id: crypto2.createHash("sha256").update(`${hit.filePath}:${hit.lineNumber}`).digest("hex").slice(0, 36),
3191
4045
  agent_id: "project",
3192
4046
  agent_role: "file",
3193
4047
  session_id: "file-grep",
3194
4048
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3195
4049
  tool_name: "file_grep",
3196
- project_name: path8.basename(projectRoot),
4050
+ project_name: path10.basename(projectRoot),
3197
4051
  has_error: false,
3198
4052
  raw_text: `${prefix} ${buildSnippet(hit, projectRoot)}`,
3199
4053
  vector: null,
@@ -3205,7 +4059,7 @@ function getChunkContext(filePath, lineNumber) {
3205
4059
  try {
3206
4060
  const ext = filePath.split(".").pop()?.toLowerCase();
3207
4061
  if (ext !== "ts" && ext !== "tsx" && ext !== "js" && ext !== "jsx") return "";
3208
- const source = readFileSync4(filePath, "utf8");
4062
+ const source = readFileSync5(filePath, "utf8");
3209
4063
  const lines = source.split("\n");
3210
4064
  for (let i = Math.min(lineNumber - 1, lines.length - 1); i >= 0; i--) {
3211
4065
  const line = lines[i];
@@ -3267,11 +4121,11 @@ function grepWithNodeFs(pattern, projectRoot, patterns) {
3267
4121
  const files = collectFiles(projectRoot, patterns ?? DEFAULT_PATTERNS);
3268
4122
  const hits = [];
3269
4123
  for (const filePath of files.slice(0, MAX_FILES)) {
3270
- const absPath = path8.join(projectRoot, filePath);
4124
+ const absPath = path10.join(projectRoot, filePath);
3271
4125
  try {
3272
4126
  const stat = statSync2(absPath);
3273
4127
  if (stat.size > MAX_FILE_SIZE) continue;
3274
- const content = readFileSync4(absPath, "utf8");
4128
+ const content = readFileSync5(absPath, "utf8");
3275
4129
  const lines = content.split("\n");
3276
4130
  const matches = content.match(regex);
3277
4131
  if (!matches || matches.length === 0) continue;
@@ -3294,15 +4148,15 @@ function collectFiles(root, patterns) {
3294
4148
  const files = [];
3295
4149
  function walk(dir, relative) {
3296
4150
  if (files.length >= MAX_FILES) return;
3297
- const basename = path8.basename(dir);
4151
+ const basename = path10.basename(dir);
3298
4152
  if (EXCLUDE_DIRS.includes(basename)) return;
3299
4153
  try {
3300
4154
  const entries = readdirSync2(dir, { withFileTypes: true });
3301
4155
  for (const entry of entries) {
3302
4156
  if (files.length >= MAX_FILES) return;
3303
- const rel = path8.join(relative, entry.name);
4157
+ const rel = path10.join(relative, entry.name);
3304
4158
  if (entry.isDirectory()) {
3305
- walk(path8.join(dir, entry.name), rel);
4159
+ walk(path10.join(dir, entry.name), rel);
3306
4160
  } else if (entry.isFile()) {
3307
4161
  for (const pat of patterns) {
3308
4162
  if (matchGlob(rel, pat)) {
@@ -3334,7 +4188,7 @@ function matchGlob(filePath, pattern) {
3334
4188
  if (slashIdx !== -1) {
3335
4189
  const dir = pattern.slice(0, slashIdx);
3336
4190
  const ext2 = pattern.slice(slashIdx + 1).replace("*", "");
3337
- const fileDir = path8.dirname(filePath);
4191
+ const fileDir = path10.dirname(filePath);
3338
4192
  return fileDir === dir && filePath.endsWith(ext2);
3339
4193
  }
3340
4194
  const ext = pattern.replace("*", "");
@@ -3342,9 +4196,9 @@ function matchGlob(filePath, pattern) {
3342
4196
  }
3343
4197
  function buildSnippet(hit, projectRoot) {
3344
4198
  try {
3345
- const absPath = path8.join(projectRoot, hit.filePath);
3346
- if (!existsSync7(absPath)) return hit.matchLine;
3347
- const lines = readFileSync4(absPath, "utf8").split("\n");
4199
+ const absPath = path10.join(projectRoot, hit.filePath);
4200
+ if (!existsSync9(absPath)) return hit.matchLine;
4201
+ const lines = readFileSync5(absPath, "utf8").split("\n");
3348
4202
  const start = Math.max(0, hit.lineNumber - 3);
3349
4203
  const end = Math.min(lines.length, hit.lineNumber + 2);
3350
4204
  return lines.slice(start, end).join("\n").slice(0, 500);