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