@askexenow/exe-os 0.9.7 → 0.9.8

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 (95) hide show
  1. package/dist/bin/backfill-conversations.js +754 -79
  2. package/dist/bin/backfill-responses.js +752 -77
  3. package/dist/bin/backfill-vectors.js +752 -77
  4. package/dist/bin/cleanup-stale-review-tasks.js +657 -35
  5. package/dist/bin/cli.js +1388 -605
  6. package/dist/bin/exe-agent-config.js +123 -95
  7. package/dist/bin/exe-agent.js +41 -25
  8. package/dist/bin/exe-assign.js +732 -57
  9. package/dist/bin/exe-boot.js +784 -153
  10. package/dist/bin/exe-call.js +209 -138
  11. package/dist/bin/exe-cloud.js +35 -12
  12. package/dist/bin/exe-dispatch.js +692 -70
  13. package/dist/bin/exe-doctor.js +648 -26
  14. package/dist/bin/exe-export-behaviors.js +650 -20
  15. package/dist/bin/exe-forget.js +635 -13
  16. package/dist/bin/exe-gateway.js +1053 -271
  17. package/dist/bin/exe-heartbeat.js +665 -43
  18. package/dist/bin/exe-kill.js +646 -16
  19. package/dist/bin/exe-launch-agent.js +887 -97
  20. package/dist/bin/exe-link.js +658 -43
  21. package/dist/bin/exe-new-employee.js +378 -177
  22. package/dist/bin/exe-pending-messages.js +656 -34
  23. package/dist/bin/exe-pending-notifications.js +635 -13
  24. package/dist/bin/exe-pending-reviews.js +659 -37
  25. package/dist/bin/exe-rename.js +645 -30
  26. package/dist/bin/exe-review.js +635 -13
  27. package/dist/bin/exe-search.js +771 -88
  28. package/dist/bin/exe-session-cleanup.js +834 -150
  29. package/dist/bin/exe-settings.js +127 -91
  30. package/dist/bin/exe-start-codex.js +729 -94
  31. package/dist/bin/exe-start-opencode.js +717 -82
  32. package/dist/bin/exe-status.js +657 -35
  33. package/dist/bin/exe-team.js +635 -13
  34. package/dist/bin/git-sweep.js +720 -89
  35. package/dist/bin/graph-backfill.js +643 -13
  36. package/dist/bin/graph-export.js +646 -16
  37. package/dist/bin/install.js +596 -193
  38. package/dist/bin/scan-tasks.js +724 -93
  39. package/dist/bin/setup.js +1038 -210
  40. package/dist/bin/shard-migrate.js +645 -15
  41. package/dist/bin/wiki-sync.js +646 -16
  42. package/dist/gateway/index.js +1027 -245
  43. package/dist/hooks/bug-report-worker.js +891 -170
  44. package/dist/hooks/commit-complete.js +718 -87
  45. package/dist/hooks/error-recall.js +776 -93
  46. package/dist/hooks/exe-heartbeat-hook.js +85 -71
  47. package/dist/hooks/ingest-worker.js +840 -156
  48. package/dist/hooks/ingest.js +90 -73
  49. package/dist/hooks/instructions-loaded.js +669 -38
  50. package/dist/hooks/notification.js +661 -30
  51. package/dist/hooks/post-compact.js +674 -43
  52. package/dist/hooks/pre-compact.js +718 -87
  53. package/dist/hooks/pre-tool-use.js +872 -125
  54. package/dist/hooks/prompt-ingest-worker.js +758 -83
  55. package/dist/hooks/prompt-submit.js +1060 -319
  56. package/dist/hooks/response-ingest-worker.js +758 -83
  57. package/dist/hooks/session-end.js +721 -90
  58. package/dist/hooks/session-start.js +1031 -207
  59. package/dist/hooks/stop.js +680 -49
  60. package/dist/hooks/subagent-stop.js +674 -43
  61. package/dist/hooks/summary-worker.js +816 -132
  62. package/dist/index.js +1015 -232
  63. package/dist/lib/cloud-sync.js +663 -48
  64. package/dist/lib/consolidation.js +26 -3
  65. package/dist/lib/database.js +626 -18
  66. package/dist/lib/db.js +2261 -0
  67. package/dist/lib/device-registry.js +640 -25
  68. package/dist/lib/embedder.js +96 -43
  69. package/dist/lib/employee-templates.js +16 -0
  70. package/dist/lib/employees.js +259 -83
  71. package/dist/lib/exe-daemon-client.js +101 -63
  72. package/dist/lib/exe-daemon.js +894 -162
  73. package/dist/lib/hybrid-search.js +771 -88
  74. package/dist/lib/identity.js +27 -7
  75. package/dist/lib/messaging.js +55 -28
  76. package/dist/lib/reminders.js +21 -1
  77. package/dist/lib/schedules.js +636 -14
  78. package/dist/lib/skill-learning.js +21 -1
  79. package/dist/lib/store.js +643 -13
  80. package/dist/lib/task-router.js +82 -71
  81. package/dist/lib/tasks.js +98 -71
  82. package/dist/lib/tmux-routing.js +87 -60
  83. package/dist/lib/token-spend.js +26 -6
  84. package/dist/mcp/server.js +1784 -458
  85. package/dist/mcp/tools/complete-reminder.js +21 -1
  86. package/dist/mcp/tools/create-reminder.js +21 -1
  87. package/dist/mcp/tools/create-task.js +290 -164
  88. package/dist/mcp/tools/deactivate-behavior.js +24 -4
  89. package/dist/mcp/tools/list-reminders.js +21 -1
  90. package/dist/mcp/tools/list-tasks.js +195 -38
  91. package/dist/mcp/tools/send-message.js +58 -31
  92. package/dist/mcp/tools/update-task.js +75 -48
  93. package/dist/runtime/index.js +720 -89
  94. package/dist/tui/App.js +853 -123
  95. package/package.json +3 -2
@@ -323,6 +323,118 @@ var init_db_retry = __esm({
323
323
  }
324
324
  });
325
325
 
326
+ // src/lib/runtime-table.ts
327
+ var RUNTIME_TABLE, DEFAULT_RUNTIME;
328
+ var init_runtime_table = __esm({
329
+ "src/lib/runtime-table.ts"() {
330
+ "use strict";
331
+ RUNTIME_TABLE = {
332
+ codex: {
333
+ binary: "codex",
334
+ launchMode: "interactive",
335
+ autoApproveFlag: "--dangerously-bypass-approvals-and-sandbox",
336
+ inlineFlag: "--no-alt-screen",
337
+ apiKeyEnv: "OPENAI_API_KEY",
338
+ defaultModel: "gpt-5.4"
339
+ },
340
+ opencode: {
341
+ binary: "opencode",
342
+ launchMode: "exec",
343
+ autoApproveFlag: "--dangerously-skip-permissions",
344
+ inlineFlag: "",
345
+ apiKeyEnv: "ANTHROPIC_API_KEY",
346
+ defaultModel: "anthropic/claude-sonnet-4-6"
347
+ }
348
+ };
349
+ DEFAULT_RUNTIME = "claude";
350
+ }
351
+ });
352
+
353
+ // src/lib/agent-config.ts
354
+ var agent_config_exports = {};
355
+ __export(agent_config_exports, {
356
+ AGENT_CONFIG_PATH: () => AGENT_CONFIG_PATH,
357
+ DEFAULT_MODELS: () => DEFAULT_MODELS,
358
+ KNOWN_RUNTIMES: () => KNOWN_RUNTIMES,
359
+ RUNTIME_LABELS: () => RUNTIME_LABELS,
360
+ clearAgentRuntime: () => clearAgentRuntime,
361
+ getAgentRuntime: () => getAgentRuntime,
362
+ loadAgentConfig: () => loadAgentConfig,
363
+ saveAgentConfig: () => saveAgentConfig,
364
+ setAgentRuntime: () => setAgentRuntime
365
+ });
366
+ import { readFileSync as readFileSync2, writeFileSync, existsSync as existsSync2, mkdirSync } from "fs";
367
+ import path2 from "path";
368
+ function loadAgentConfig() {
369
+ if (!existsSync2(AGENT_CONFIG_PATH)) return {};
370
+ try {
371
+ return JSON.parse(readFileSync2(AGENT_CONFIG_PATH, "utf-8"));
372
+ } catch {
373
+ return {};
374
+ }
375
+ }
376
+ function saveAgentConfig(config) {
377
+ const dir = path2.dirname(AGENT_CONFIG_PATH);
378
+ if (!existsSync2(dir)) mkdirSync(dir, { recursive: true });
379
+ writeFileSync(AGENT_CONFIG_PATH, JSON.stringify(config, null, 2) + "\n", "utf-8");
380
+ }
381
+ function getAgentRuntime(agentId) {
382
+ const config = loadAgentConfig();
383
+ const entry = config[agentId];
384
+ if (entry) return entry;
385
+ const orgDefault = config["default"];
386
+ if (orgDefault) return orgDefault;
387
+ return { runtime: DEFAULT_RUNTIME, model: DEFAULT_MODELS[DEFAULT_RUNTIME] };
388
+ }
389
+ function setAgentRuntime(agentId, runtime, model) {
390
+ const knownModels = KNOWN_RUNTIMES[runtime];
391
+ if (!knownModels) {
392
+ return {
393
+ ok: false,
394
+ error: `Unknown runtime "${runtime}". Valid: ${Object.keys(KNOWN_RUNTIMES).join(", ")}`
395
+ };
396
+ }
397
+ if (!knownModels.includes(model)) {
398
+ return {
399
+ ok: false,
400
+ error: `Unknown model "${model}" for runtime "${runtime}". Valid: ${knownModels.join(", ")}`
401
+ };
402
+ }
403
+ const config = loadAgentConfig();
404
+ config[agentId] = { runtime, model };
405
+ saveAgentConfig(config);
406
+ return { ok: true };
407
+ }
408
+ function clearAgentRuntime(agentId) {
409
+ const config = loadAgentConfig();
410
+ delete config[agentId];
411
+ saveAgentConfig(config);
412
+ }
413
+ var AGENT_CONFIG_PATH, KNOWN_RUNTIMES, RUNTIME_LABELS, DEFAULT_MODELS;
414
+ var init_agent_config = __esm({
415
+ "src/lib/agent-config.ts"() {
416
+ "use strict";
417
+ init_config();
418
+ init_runtime_table();
419
+ AGENT_CONFIG_PATH = path2.join(EXE_AI_DIR, "agent-config.json");
420
+ KNOWN_RUNTIMES = {
421
+ claude: ["claude-opus-4", "claude-sonnet-4", "claude-haiku-4.5"],
422
+ codex: ["gpt-5.4", "gpt-5.5", "gpt-5.3-codex-spark", "o3", "o4-mini"],
423
+ opencode: ["anthropic/claude-sonnet-4-6", "openai/gpt-5.4", "google/gemini-2.5-pro", "deepseek/deepseek-r3", "minimax/minimax-m2.5"]
424
+ };
425
+ RUNTIME_LABELS = {
426
+ claude: "Claude Code (Anthropic)",
427
+ codex: "Codex (OpenAI)",
428
+ opencode: "OpenCode (open source)"
429
+ };
430
+ DEFAULT_MODELS = {
431
+ claude: "claude-opus-4",
432
+ codex: RUNTIME_TABLE.codex?.defaultModel ?? "gpt-5.4",
433
+ opencode: RUNTIME_TABLE.opencode?.defaultModel ?? "anthropic/claude-sonnet-4-6"
434
+ };
435
+ }
436
+ });
437
+
326
438
  // src/lib/employees.ts
327
439
  var employees_exports = {};
328
440
  __export(employees_exports, {
@@ -338,6 +450,7 @@ __export(employees_exports, {
338
450
  getEmployeeByRole: () => getEmployeeByRole,
339
451
  getEmployeeNamesByRole: () => getEmployeeNamesByRole,
340
452
  hasRole: () => hasRole,
453
+ hireEmployee: () => hireEmployee,
341
454
  isCoordinatorName: () => isCoordinatorName,
342
455
  isCoordinatorRole: () => isCoordinatorRole,
343
456
  isMultiInstance: () => isMultiInstance,
@@ -350,9 +463,9 @@ __export(employees_exports, {
350
463
  validateEmployeeName: () => validateEmployeeName
351
464
  });
352
465
  import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
353
- import { existsSync as existsSync2, symlinkSync, readlinkSync, readFileSync as readFileSync2, renameSync as renameSync2, unlinkSync, writeFileSync } from "fs";
466
+ import { existsSync as existsSync3, symlinkSync, readlinkSync, readFileSync as readFileSync3, renameSync as renameSync2, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
354
467
  import { execSync } from "child_process";
355
- import path2 from "path";
468
+ import path3 from "path";
356
469
  import os2 from "os";
357
470
  function normalizeRole(role) {
358
471
  return (role ?? "").trim().toLowerCase();
@@ -389,7 +502,7 @@ function validateEmployeeName(name) {
389
502
  return { valid: true };
390
503
  }
391
504
  async function loadEmployees(employeesPath = EMPLOYEES_PATH) {
392
- if (!existsSync2(employeesPath)) {
505
+ if (!existsSync3(employeesPath)) {
393
506
  return [];
394
507
  }
395
508
  const raw = await readFile2(employeesPath, "utf-8");
@@ -400,13 +513,13 @@ async function loadEmployees(employeesPath = EMPLOYEES_PATH) {
400
513
  }
401
514
  }
402
515
  async function saveEmployees(employees, employeesPath = EMPLOYEES_PATH) {
403
- await mkdir2(path2.dirname(employeesPath), { recursive: true });
516
+ await mkdir2(path3.dirname(employeesPath), { recursive: true });
404
517
  await writeFile2(employeesPath, JSON.stringify(employees, null, 2) + "\n", "utf-8");
405
518
  }
406
519
  function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
407
- if (!existsSync2(employeesPath)) return [];
520
+ if (!existsSync3(employeesPath)) return [];
408
521
  try {
409
- return JSON.parse(readFileSync2(employeesPath, "utf-8"));
522
+ return JSON.parse(readFileSync3(employeesPath, "utf-8"));
410
523
  } catch {
411
524
  return [];
412
525
  }
@@ -448,6 +561,52 @@ function addEmployee(employees, employee) {
448
561
  }
449
562
  return [...employees, normalized];
450
563
  }
564
+ function appendToCoordinatorTeam(employee) {
565
+ const coordinator = getCoordinatorEmployee(loadEmployeesSync());
566
+ if (!coordinator) return;
567
+ const idPath = path3.join(IDENTITY_DIR, `${coordinator.name}.md`);
568
+ if (!existsSync3(idPath)) return;
569
+ const content = readFileSync3(idPath, "utf-8");
570
+ if (content.includes(`**${capitalize(employee.name)}`)) return;
571
+ const teamMatch = content.match(TEAM_SECTION_RE);
572
+ if (!teamMatch || teamMatch.index === void 0) return;
573
+ const afterTeam = content.slice(teamMatch.index + teamMatch[0].length);
574
+ const nextHeading = afterTeam.match(/\n## /);
575
+ const entry = `
576
+ **${capitalize(employee.name)} (${employee.role}):** Newly hired. Update this description as the role develops.
577
+ `;
578
+ let updated;
579
+ if (nextHeading && nextHeading.index !== void 0) {
580
+ const insertAt = teamMatch.index + teamMatch[0].length + nextHeading.index;
581
+ updated = content.slice(0, insertAt) + entry + content.slice(insertAt);
582
+ } else {
583
+ updated = content.trimEnd() + "\n" + entry;
584
+ }
585
+ writeFileSync2(idPath, updated, "utf-8");
586
+ }
587
+ function capitalize(s) {
588
+ return s.charAt(0).toUpperCase() + s.slice(1);
589
+ }
590
+ async function hireEmployee(employee) {
591
+ const employees = await loadEmployees();
592
+ const updated = addEmployee(employees, employee);
593
+ await saveEmployees(updated);
594
+ try {
595
+ appendToCoordinatorTeam(employee);
596
+ } catch {
597
+ }
598
+ try {
599
+ const { loadAgentConfig: loadAgentConfig2, saveAgentConfig: saveAgentConfig2 } = await Promise.resolve().then(() => (init_agent_config(), agent_config_exports));
600
+ const config = loadAgentConfig2();
601
+ const name = employee.name.toLowerCase();
602
+ if (!config[name] && config["default"]) {
603
+ config[name] = { ...config["default"] };
604
+ saveAgentConfig2(config);
605
+ }
606
+ } catch {
607
+ }
608
+ return updated;
609
+ }
451
610
  async function normalizeRosterCase(rosterPath) {
452
611
  const employees = await loadEmployees(rosterPath);
453
612
  let changed = false;
@@ -457,14 +616,14 @@ async function normalizeRosterCase(rosterPath) {
457
616
  emp.name = emp.name.toLowerCase();
458
617
  changed = true;
459
618
  try {
460
- const identityDir = path2.join(os2.homedir(), ".exe-os", "identity");
461
- const oldPath = path2.join(identityDir, `${oldName}.md`);
462
- const newPath = path2.join(identityDir, `${emp.name}.md`);
463
- if (existsSync2(oldPath) && !existsSync2(newPath)) {
619
+ const identityDir = path3.join(os2.homedir(), ".exe-os", "identity");
620
+ const oldPath = path3.join(identityDir, `${oldName}.md`);
621
+ const newPath = path3.join(identityDir, `${emp.name}.md`);
622
+ if (existsSync3(oldPath) && !existsSync3(newPath)) {
464
623
  renameSync2(oldPath, newPath);
465
- } else if (existsSync2(oldPath) && oldPath !== newPath) {
466
- const content = readFileSync2(oldPath, "utf-8");
467
- writeFileSync(newPath, content, "utf-8");
624
+ } else if (existsSync3(oldPath) && oldPath !== newPath) {
625
+ const content = readFileSync3(oldPath, "utf-8");
626
+ writeFileSync2(newPath, content, "utf-8");
468
627
  if (oldPath.toLowerCase() !== newPath.toLowerCase()) {
469
628
  unlinkSync(oldPath);
470
629
  }
@@ -494,7 +653,7 @@ function registerBinSymlinks(name) {
494
653
  errors.push("Could not find 'exe-os' in PATH");
495
654
  return { created, skipped, errors };
496
655
  }
497
- const binDir = path2.dirname(exeBinPath);
656
+ const binDir = path3.dirname(exeBinPath);
498
657
  let target;
499
658
  try {
500
659
  target = readlinkSync(exeBinPath);
@@ -504,8 +663,8 @@ function registerBinSymlinks(name) {
504
663
  }
505
664
  for (const suffix of ["", "-opencode"]) {
506
665
  const linkName = `${name}${suffix}`;
507
- const linkPath = path2.join(binDir, linkName);
508
- if (existsSync2(linkPath)) {
666
+ const linkPath = path3.join(binDir, linkName);
667
+ if (existsSync3(linkPath)) {
509
668
  skipped.push(linkName);
510
669
  continue;
511
670
  }
@@ -518,25 +677,611 @@ function registerBinSymlinks(name) {
518
677
  }
519
678
  return { created, skipped, errors };
520
679
  }
521
- var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE, MULTI_INSTANCE_ROLES;
680
+ var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE, MULTI_INSTANCE_ROLES, IDENTITY_DIR, TEAM_SECTION_RE;
522
681
  var init_employees = __esm({
523
682
  "src/lib/employees.ts"() {
524
683
  "use strict";
525
684
  init_config();
526
- EMPLOYEES_PATH = path2.join(EXE_AI_DIR, "exe-employees.json");
685
+ EMPLOYEES_PATH = path3.join(EXE_AI_DIR, "exe-employees.json");
527
686
  DEFAULT_COORDINATOR_TEMPLATE_NAME = "exe";
528
687
  COORDINATOR_ROLE = "COO";
529
688
  MULTI_INSTANCE_ROLES = /* @__PURE__ */ new Set(["principal engineer", "content production specialist", "staff code reviewer"]);
689
+ IDENTITY_DIR = path3.join(EXE_AI_DIR, "identity");
690
+ TEAM_SECTION_RE = /^## Team\b.*$/m;
691
+ }
692
+ });
693
+
694
+ // src/lib/database-adapter.ts
695
+ import os3 from "os";
696
+ import path4 from "path";
697
+ import { createRequire } from "module";
698
+ import { pathToFileURL } from "url";
699
+ function quotedIdentifier(identifier) {
700
+ return `"${identifier.replace(/"/g, '""')}"`;
701
+ }
702
+ function unqualifiedTableName(name) {
703
+ const raw = name.trim().replace(/^"|"$/g, "");
704
+ const parts = raw.split(".");
705
+ return parts[parts.length - 1].replace(/^"|"$/g, "").toLowerCase();
706
+ }
707
+ function stripTrailingSemicolon(sql) {
708
+ return sql.trim().replace(/;+\s*$/u, "");
709
+ }
710
+ function appendClause(sql, clause) {
711
+ const trimmed = stripTrailingSemicolon(sql);
712
+ const returningMatch = /\sRETURNING\b[\s\S]*$/iu.exec(trimmed);
713
+ if (!returningMatch) {
714
+ return `${trimmed}${clause}`;
715
+ }
716
+ const idx = returningMatch.index;
717
+ return `${trimmed.slice(0, idx)}${clause}${trimmed.slice(idx)}`;
718
+ }
719
+ function normalizeStatement(stmt) {
720
+ if (typeof stmt === "string") {
721
+ return { kind: "positional", sql: stmt, args: [] };
722
+ }
723
+ const sql = stmt.sql;
724
+ if (Array.isArray(stmt.args) || stmt.args === void 0) {
725
+ return { kind: "positional", sql, args: stmt.args ?? [] };
726
+ }
727
+ return { kind: "named", sql, args: stmt.args };
728
+ }
729
+ function rewriteBooleanLiterals(sql) {
730
+ let out = sql;
731
+ for (const column of BOOLEAN_COLUMN_NAMES) {
732
+ const scoped = `((?:\\b[a-z_][a-z0-9_]*\\.)?${column})`;
733
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*0\\b`, "giu"), "$1 = FALSE");
734
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*1\\b`, "giu"), "$1 = TRUE");
735
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*0\\b`, "giu"), "$1 != FALSE");
736
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*1\\b`, "giu"), "$1 != TRUE");
737
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*0\\b`, "giu"), "$1 <> FALSE");
738
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*1\\b`, "giu"), "$1 <> TRUE");
739
+ }
740
+ return out;
741
+ }
742
+ function rewriteInsertOrIgnore(sql) {
743
+ if (!/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu.test(sql)) {
744
+ return sql;
745
+ }
746
+ const replaced = sql.replace(/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu, "INSERT INTO");
747
+ return /\bON\s+CONFLICT\b/iu.test(replaced) ? replaced : appendClause(replaced, " ON CONFLICT DO NOTHING");
748
+ }
749
+ function rewriteInsertOrReplace(sql) {
750
+ const match = /^\s*INSERT\s+OR\s+REPLACE\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)([\s\S]*)$/iu.exec(sql);
751
+ if (!match) {
752
+ return sql;
753
+ }
754
+ const rawTable = match[1];
755
+ const rawColumns = match[2];
756
+ const remainder = match[3];
757
+ const tableName = unqualifiedTableName(rawTable);
758
+ const conflictKeys = UPSERT_KEYS[tableName];
759
+ if (!conflictKeys?.length) {
760
+ return sql;
761
+ }
762
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
763
+ const updateColumns = columns.filter((col) => !conflictKeys.includes(col));
764
+ const conflictTarget = conflictKeys.map(quotedIdentifier).join(", ");
765
+ const updateClause = updateColumns.length === 0 ? " DO NOTHING" : ` DO UPDATE SET ${updateColumns.map((col) => `${quotedIdentifier(col)} = EXCLUDED.${quotedIdentifier(col)}`).join(", ")}`;
766
+ return `INSERT INTO ${rawTable} (${rawColumns})${appendClause(remainder, ` ON CONFLICT (${conflictTarget})${updateClause}`)}`;
767
+ }
768
+ function rewriteSql(sql) {
769
+ let out = sql;
770
+ out = out.replace(/\bdatetime\(\s*['"]now['"]\s*\)/giu, "CURRENT_TIMESTAMP");
771
+ out = out.replace(/\bvector32\s*\(\s*\?\s*\)/giu, "?");
772
+ out = rewriteBooleanLiterals(out);
773
+ out = rewriteInsertOrReplace(out);
774
+ out = rewriteInsertOrIgnore(out);
775
+ return stripTrailingSemicolon(out);
776
+ }
777
+ function toBoolean(value) {
778
+ if (value === null || value === void 0) return value;
779
+ if (typeof value === "boolean") return value;
780
+ if (typeof value === "number") return value !== 0;
781
+ if (typeof value === "bigint") return value !== 0n;
782
+ if (typeof value === "string") {
783
+ const normalized = value.trim().toLowerCase();
784
+ if (normalized === "0" || normalized === "false") return false;
785
+ if (normalized === "1" || normalized === "true") return true;
786
+ }
787
+ return Boolean(value);
788
+ }
789
+ function countQuestionMarks(sql, end) {
790
+ let count = 0;
791
+ let inSingle = false;
792
+ let inDouble = false;
793
+ let inLineComment = false;
794
+ let inBlockComment = false;
795
+ for (let i = 0; i < end; i++) {
796
+ const ch = sql[i];
797
+ const next = sql[i + 1];
798
+ if (inLineComment) {
799
+ if (ch === "\n") inLineComment = false;
800
+ continue;
801
+ }
802
+ if (inBlockComment) {
803
+ if (ch === "*" && next === "/") {
804
+ inBlockComment = false;
805
+ i += 1;
806
+ }
807
+ continue;
808
+ }
809
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
810
+ inLineComment = true;
811
+ i += 1;
812
+ continue;
813
+ }
814
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
815
+ inBlockComment = true;
816
+ i += 1;
817
+ continue;
818
+ }
819
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
820
+ inSingle = !inSingle;
821
+ continue;
822
+ }
823
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
824
+ inDouble = !inDouble;
825
+ continue;
826
+ }
827
+ if (!inSingle && !inDouble && ch === "?") {
828
+ count += 1;
829
+ }
830
+ }
831
+ return count;
832
+ }
833
+ function findBooleanPlaceholderIndexes(sql) {
834
+ const indexes = /* @__PURE__ */ new Set();
835
+ for (const column of BOOLEAN_COLUMN_NAMES) {
836
+ const pattern = new RegExp(`(?:\\b[a-z_][a-z0-9_]*\\.)?${column}\\s*=\\s*\\?`, "giu");
837
+ for (const match of sql.matchAll(pattern)) {
838
+ const matchText = match[0];
839
+ const qIndex = match.index + matchText.lastIndexOf("?");
840
+ indexes.add(countQuestionMarks(sql, qIndex + 1));
841
+ }
842
+ }
843
+ return indexes;
844
+ }
845
+ function coerceInsertBooleanArgs(sql, args) {
846
+ const match = /^\s*INSERT(?:\s+OR\s+(?:IGNORE|REPLACE))?\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)/iu.exec(sql);
847
+ if (!match) return;
848
+ const rawTable = match[1];
849
+ const rawColumns = match[2];
850
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
851
+ if (!boolColumns?.size) return;
852
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
853
+ for (const [index, column] of columns.entries()) {
854
+ if (boolColumns.has(column) && index < args.length) {
855
+ args[index] = toBoolean(args[index]);
856
+ }
857
+ }
858
+ }
859
+ function coerceUpdateBooleanArgs(sql, args) {
860
+ const match = /^\s*UPDATE\s+([A-Za-z0-9_."]+)\s+SET\s+([\s\S]+?)(?:\s+WHERE\b|$)/iu.exec(sql);
861
+ if (!match) return;
862
+ const rawTable = match[1];
863
+ const setClause = match[2];
864
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
865
+ if (!boolColumns?.size) return;
866
+ const assignments = setClause.split(",");
867
+ let placeholderIndex = 0;
868
+ for (const assignment of assignments) {
869
+ if (!assignment.includes("?")) continue;
870
+ placeholderIndex += 1;
871
+ const colMatch = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*\?/iu.exec(assignment);
872
+ if (colMatch && boolColumns.has(colMatch[1])) {
873
+ args[placeholderIndex - 1] = toBoolean(args[placeholderIndex - 1]);
874
+ }
875
+ }
876
+ }
877
+ function coerceBooleanArgs(sql, args) {
878
+ const nextArgs = [...args];
879
+ coerceInsertBooleanArgs(sql, nextArgs);
880
+ coerceUpdateBooleanArgs(sql, nextArgs);
881
+ const placeholderIndexes = findBooleanPlaceholderIndexes(sql);
882
+ for (const index of placeholderIndexes) {
883
+ if (index > 0 && index <= nextArgs.length) {
884
+ nextArgs[index - 1] = toBoolean(nextArgs[index - 1]);
885
+ }
886
+ }
887
+ return nextArgs;
888
+ }
889
+ function convertQuestionMarksToDollarParams(sql) {
890
+ let out = "";
891
+ let placeholder = 0;
892
+ let inSingle = false;
893
+ let inDouble = false;
894
+ let inLineComment = false;
895
+ let inBlockComment = false;
896
+ for (let i = 0; i < sql.length; i++) {
897
+ const ch = sql[i];
898
+ const next = sql[i + 1];
899
+ if (inLineComment) {
900
+ out += ch;
901
+ if (ch === "\n") inLineComment = false;
902
+ continue;
903
+ }
904
+ if (inBlockComment) {
905
+ out += ch;
906
+ if (ch === "*" && next === "/") {
907
+ out += next;
908
+ inBlockComment = false;
909
+ i += 1;
910
+ }
911
+ continue;
912
+ }
913
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
914
+ out += ch + next;
915
+ inLineComment = true;
916
+ i += 1;
917
+ continue;
918
+ }
919
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
920
+ out += ch + next;
921
+ inBlockComment = true;
922
+ i += 1;
923
+ continue;
924
+ }
925
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
926
+ inSingle = !inSingle;
927
+ out += ch;
928
+ continue;
929
+ }
930
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
931
+ inDouble = !inDouble;
932
+ out += ch;
933
+ continue;
934
+ }
935
+ if (!inSingle && !inDouble && ch === "?") {
936
+ placeholder += 1;
937
+ out += `$${placeholder}`;
938
+ continue;
939
+ }
940
+ out += ch;
941
+ }
942
+ return out;
943
+ }
944
+ function translateStatementForPostgres(stmt) {
945
+ const normalized = normalizeStatement(stmt);
946
+ if (normalized.kind === "named") {
947
+ throw new Error("Named SQL parameters are not supported by the Prisma adapter.");
948
+ }
949
+ const rewrittenSql = rewriteSql(normalized.sql);
950
+ const coercedArgs = coerceBooleanArgs(rewrittenSql, normalized.args);
951
+ return {
952
+ sql: convertQuestionMarksToDollarParams(rewrittenSql),
953
+ args: coercedArgs
954
+ };
955
+ }
956
+ function shouldBypassPostgres(stmt) {
957
+ const normalized = normalizeStatement(stmt);
958
+ if (normalized.kind === "named") {
959
+ return true;
960
+ }
961
+ return IMMEDIATE_FALLBACK_PATTERNS.some((pattern) => pattern.test(normalized.sql));
962
+ }
963
+ function shouldFallbackOnError(error) {
964
+ const message = error instanceof Error ? error.message : String(error);
965
+ return /42P01|42883|42601|does not exist|syntax error|not supported|Named SQL parameters are not supported/iu.test(message);
966
+ }
967
+ function isReadQuery(sql) {
968
+ const trimmed = sql.trimStart();
969
+ return /^(SELECT|WITH|SHOW|EXPLAIN|VALUES)\b/iu.test(trimmed) || /\bRETURNING\b/iu.test(trimmed);
970
+ }
971
+ function buildRow(row, columns) {
972
+ const values = columns.map((column) => row[column]);
973
+ return Object.assign(values, row);
974
+ }
975
+ function buildResultSet(rows, rowsAffected = 0) {
976
+ const columns = rows[0] ? Object.keys(rows[0]) : [];
977
+ const resultRows = rows.map((row) => buildRow(row, columns));
978
+ return {
979
+ columns,
980
+ columnTypes: columns.map(() => ""),
981
+ rows: resultRows,
982
+ rowsAffected,
983
+ lastInsertRowid: void 0,
984
+ toJSON() {
985
+ return {
986
+ columns,
987
+ columnTypes: columns.map(() => ""),
988
+ rows,
989
+ rowsAffected,
990
+ lastInsertRowid: void 0
991
+ };
992
+ }
993
+ };
994
+ }
995
+ async function loadPrismaClient() {
996
+ if (!prismaClientPromise) {
997
+ prismaClientPromise = (async () => {
998
+ const explicitPath = process.env.EXE_OS_PRISMA_CLIENT_PATH;
999
+ if (explicitPath) {
1000
+ const module2 = await import(pathToFileURL(explicitPath).href);
1001
+ const PrismaClient2 = module2.PrismaClient ?? module2.default?.PrismaClient;
1002
+ if (!PrismaClient2) {
1003
+ throw new Error(`No PrismaClient export found at ${explicitPath}`);
1004
+ }
1005
+ return new PrismaClient2();
1006
+ }
1007
+ const exeDbRoot = process.env.EXE_DB_ROOT ?? path4.join(os3.homedir(), "exe-db");
1008
+ const requireFromExeDb = createRequire(path4.join(exeDbRoot, "package.json"));
1009
+ const prismaEntry = requireFromExeDb.resolve("@prisma/client");
1010
+ const module = await import(pathToFileURL(prismaEntry).href);
1011
+ const PrismaClient = module.PrismaClient ?? module.default?.PrismaClient;
1012
+ if (!PrismaClient) {
1013
+ throw new Error(`No PrismaClient export found in ${prismaEntry}`);
1014
+ }
1015
+ return new PrismaClient();
1016
+ })();
1017
+ }
1018
+ return prismaClientPromise;
1019
+ }
1020
+ async function ensureCompatibilityViews(prisma) {
1021
+ if (!compatibilityBootstrapPromise) {
1022
+ compatibilityBootstrapPromise = (async () => {
1023
+ for (const mapping of VIEW_MAPPINGS) {
1024
+ const relation = mapping.source.replace(/"/g, "");
1025
+ const rows = await prisma.$queryRawUnsafe(
1026
+ "SELECT to_regclass($1) AS regclass",
1027
+ relation
1028
+ );
1029
+ if (!rows[0]?.regclass) {
1030
+ continue;
1031
+ }
1032
+ await prisma.$executeRawUnsafe(
1033
+ `CREATE OR REPLACE VIEW public.${quotedIdentifier(mapping.view)} AS SELECT * FROM ${mapping.source}`
1034
+ );
1035
+ }
1036
+ })();
1037
+ }
1038
+ return compatibilityBootstrapPromise;
1039
+ }
1040
+ async function executeOnPrisma(executor, stmt) {
1041
+ const translated = translateStatementForPostgres(stmt);
1042
+ if (isReadQuery(translated.sql)) {
1043
+ const rows = await executor.$queryRawUnsafe(
1044
+ translated.sql,
1045
+ ...translated.args
1046
+ );
1047
+ return buildResultSet(rows, /\bRETURNING\b/iu.test(translated.sql) ? rows.length : 0);
1048
+ }
1049
+ const rowsAffected = await executor.$executeRawUnsafe(translated.sql, ...translated.args);
1050
+ return buildResultSet([], rowsAffected);
1051
+ }
1052
+ function splitSqlStatements(sql) {
1053
+ const parts = [];
1054
+ let current = "";
1055
+ let inSingle = false;
1056
+ let inDouble = false;
1057
+ let inLineComment = false;
1058
+ let inBlockComment = false;
1059
+ for (let i = 0; i < sql.length; i++) {
1060
+ const ch = sql[i];
1061
+ const next = sql[i + 1];
1062
+ if (inLineComment) {
1063
+ current += ch;
1064
+ if (ch === "\n") inLineComment = false;
1065
+ continue;
1066
+ }
1067
+ if (inBlockComment) {
1068
+ current += ch;
1069
+ if (ch === "*" && next === "/") {
1070
+ current += next;
1071
+ inBlockComment = false;
1072
+ i += 1;
1073
+ }
1074
+ continue;
1075
+ }
1076
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
1077
+ current += ch + next;
1078
+ inLineComment = true;
1079
+ i += 1;
1080
+ continue;
1081
+ }
1082
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
1083
+ current += ch + next;
1084
+ inBlockComment = true;
1085
+ i += 1;
1086
+ continue;
1087
+ }
1088
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
1089
+ inSingle = !inSingle;
1090
+ current += ch;
1091
+ continue;
1092
+ }
1093
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
1094
+ inDouble = !inDouble;
1095
+ current += ch;
1096
+ continue;
1097
+ }
1098
+ if (!inSingle && !inDouble && ch === ";") {
1099
+ if (current.trim()) {
1100
+ parts.push(current.trim());
1101
+ }
1102
+ current = "";
1103
+ continue;
1104
+ }
1105
+ current += ch;
1106
+ }
1107
+ if (current.trim()) {
1108
+ parts.push(current.trim());
1109
+ }
1110
+ return parts;
1111
+ }
1112
+ async function createPrismaDbAdapter(fallbackClient) {
1113
+ const prisma = await loadPrismaClient();
1114
+ await ensureCompatibilityViews(prisma);
1115
+ let closed = false;
1116
+ let adapter;
1117
+ const fallbackExecute = async (stmt, error) => {
1118
+ if (!fallbackClient) {
1119
+ if (error) throw error;
1120
+ throw new Error("No fallback SQLite client is available for this Prisma-routed query.");
1121
+ }
1122
+ if (error) {
1123
+ process.stderr.write(
1124
+ `[database-adapter] Falling back to SQLite: ${error instanceof Error ? error.message : String(error)}
1125
+ `
1126
+ );
1127
+ }
1128
+ return fallbackClient.execute(stmt);
1129
+ };
1130
+ adapter = {
1131
+ async execute(stmt) {
1132
+ if (shouldBypassPostgres(stmt)) {
1133
+ return fallbackExecute(stmt);
1134
+ }
1135
+ try {
1136
+ return await executeOnPrisma(prisma, stmt);
1137
+ } catch (error) {
1138
+ if (shouldFallbackOnError(error)) {
1139
+ return fallbackExecute(stmt, error);
1140
+ }
1141
+ throw error;
1142
+ }
1143
+ },
1144
+ async batch(stmts, mode) {
1145
+ if (stmts.some((stmt) => shouldBypassPostgres(stmt))) {
1146
+ if (!fallbackClient) {
1147
+ throw new Error("Cannot batch unsupported SQLite-only statements without a fallback client.");
1148
+ }
1149
+ return fallbackClient.batch(stmts, mode);
1150
+ }
1151
+ try {
1152
+ if (prisma.$transaction) {
1153
+ return await prisma.$transaction(async (tx) => {
1154
+ const results2 = [];
1155
+ for (const stmt of stmts) {
1156
+ results2.push(await executeOnPrisma(tx, stmt));
1157
+ }
1158
+ return results2;
1159
+ });
1160
+ }
1161
+ const results = [];
1162
+ for (const stmt of stmts) {
1163
+ results.push(await executeOnPrisma(prisma, stmt));
1164
+ }
1165
+ return results;
1166
+ } catch (error) {
1167
+ if (fallbackClient && shouldFallbackOnError(error)) {
1168
+ process.stderr.write(
1169
+ `[database-adapter] Falling back batch to SQLite: ${error instanceof Error ? error.message : String(error)}
1170
+ `
1171
+ );
1172
+ return fallbackClient.batch(stmts, mode);
1173
+ }
1174
+ throw error;
1175
+ }
1176
+ },
1177
+ async migrate(stmts) {
1178
+ if (fallbackClient) {
1179
+ return fallbackClient.migrate(stmts);
1180
+ }
1181
+ return adapter.batch(stmts, "deferred");
1182
+ },
1183
+ async transaction(mode) {
1184
+ if (!fallbackClient) {
1185
+ throw new Error("Interactive transactions are only supported on the SQLite fallback client.");
1186
+ }
1187
+ return fallbackClient.transaction(mode);
1188
+ },
1189
+ async executeMultiple(sql) {
1190
+ if (fallbackClient && shouldBypassPostgres(sql)) {
1191
+ return fallbackClient.executeMultiple(sql);
1192
+ }
1193
+ for (const statement of splitSqlStatements(sql)) {
1194
+ await adapter.execute(statement);
1195
+ }
1196
+ },
1197
+ async sync() {
1198
+ if (fallbackClient) {
1199
+ return fallbackClient.sync();
1200
+ }
1201
+ return { frame_no: 0, frames_synced: 0 };
1202
+ },
1203
+ close() {
1204
+ closed = true;
1205
+ prismaClientPromise = null;
1206
+ compatibilityBootstrapPromise = null;
1207
+ void prisma.$disconnect?.();
1208
+ },
1209
+ get closed() {
1210
+ return closed;
1211
+ },
1212
+ get protocol() {
1213
+ return "prisma-postgres";
1214
+ }
1215
+ };
1216
+ return adapter;
1217
+ }
1218
+ var VIEW_MAPPINGS, UPSERT_KEYS, BOOLEAN_COLUMNS_BY_TABLE, BOOLEAN_COLUMN_NAMES, IMMEDIATE_FALLBACK_PATTERNS, prismaClientPromise, compatibilityBootstrapPromise;
1219
+ var init_database_adapter = __esm({
1220
+ "src/lib/database-adapter.ts"() {
1221
+ "use strict";
1222
+ VIEW_MAPPINGS = [
1223
+ { view: "memories", source: "memory.memory_records" },
1224
+ { view: "tasks", source: "memory.tasks" },
1225
+ { view: "behaviors", source: "memory.behaviors" },
1226
+ { view: "entities", source: "memory.entities" },
1227
+ { view: "relationships", source: "memory.relationships" },
1228
+ { view: "entity_memories", source: "memory.entity_memories" },
1229
+ { view: "entity_aliases", source: "memory.entity_aliases" },
1230
+ { view: "notifications", source: "memory.notifications" },
1231
+ { view: "messages", source: "memory.messages" },
1232
+ { view: "users", source: "wiki.users" },
1233
+ { view: "workspaces", source: "wiki.workspaces" },
1234
+ { view: "workspace_users", source: "wiki.workspace_users" },
1235
+ { view: "documents", source: "wiki.workspace_documents" },
1236
+ { view: "chats", source: "wiki.workspace_chats" }
1237
+ ];
1238
+ UPSERT_KEYS = {
1239
+ memories: ["id"],
1240
+ tasks: ["id"],
1241
+ behaviors: ["id"],
1242
+ entities: ["id"],
1243
+ relationships: ["id"],
1244
+ entity_aliases: ["alias"],
1245
+ notifications: ["id"],
1246
+ messages: ["id"],
1247
+ users: ["id"],
1248
+ workspaces: ["id"],
1249
+ workspace_users: ["id"],
1250
+ documents: ["id"],
1251
+ chats: ["id"]
1252
+ };
1253
+ BOOLEAN_COLUMNS_BY_TABLE = {
1254
+ memories: /* @__PURE__ */ new Set(["has_error", "draft"]),
1255
+ behaviors: /* @__PURE__ */ new Set(["active"]),
1256
+ notifications: /* @__PURE__ */ new Set(["read"]),
1257
+ users: /* @__PURE__ */ new Set(["has_personal_memory"])
1258
+ };
1259
+ BOOLEAN_COLUMN_NAMES = new Set(
1260
+ Object.values(BOOLEAN_COLUMNS_BY_TABLE).flatMap((cols) => [...cols])
1261
+ );
1262
+ IMMEDIATE_FALLBACK_PATTERNS = [
1263
+ /\bPRAGMA\b/i,
1264
+ /\bsqlite_master\b/i,
1265
+ /(?:^|[.\s])(?:memories|conversations|entities)_fts\b/i,
1266
+ /\bMATCH\b/i,
1267
+ /\bvector_distance_cos\s*\(/i,
1268
+ /\bjson_extract\s*\(/i,
1269
+ /\bjulianday\s*\(/i,
1270
+ /\bstrftime\s*\(/i,
1271
+ /\blast_insert_rowid\s*\(/i
1272
+ ];
1273
+ prismaClientPromise = null;
1274
+ compatibilityBootstrapPromise = null;
530
1275
  }
531
1276
  });
532
1277
 
533
1278
  // src/lib/exe-daemon-client.ts
534
1279
  import net from "net";
535
- import os3 from "os";
1280
+ import os4 from "os";
536
1281
  import { spawn } from "child_process";
537
1282
  import { randomUUID } from "crypto";
538
- import { existsSync as existsSync3, unlinkSync as unlinkSync2, readFileSync as readFileSync3, openSync, closeSync, statSync } from "fs";
539
- import path3 from "path";
1283
+ import { existsSync as existsSync4, unlinkSync as unlinkSync2, readFileSync as readFileSync4, openSync, closeSync, statSync } from "fs";
1284
+ import path5 from "path";
540
1285
  import { fileURLToPath } from "url";
541
1286
  function handleData(chunk) {
542
1287
  _buffer += chunk.toString();
@@ -564,9 +1309,9 @@ function handleData(chunk) {
564
1309
  }
565
1310
  }
566
1311
  function cleanupStaleFiles() {
567
- if (existsSync3(PID_PATH)) {
1312
+ if (existsSync4(PID_PATH)) {
568
1313
  try {
569
- const pid = parseInt(readFileSync3(PID_PATH, "utf8").trim(), 10);
1314
+ const pid = parseInt(readFileSync4(PID_PATH, "utf8").trim(), 10);
570
1315
  if (pid > 0) {
571
1316
  try {
572
1317
  process.kill(pid, 0);
@@ -587,17 +1332,17 @@ function cleanupStaleFiles() {
587
1332
  }
588
1333
  }
589
1334
  function findPackageRoot() {
590
- let dir = path3.dirname(fileURLToPath(import.meta.url));
591
- const { root } = path3.parse(dir);
1335
+ let dir = path5.dirname(fileURLToPath(import.meta.url));
1336
+ const { root } = path5.parse(dir);
592
1337
  while (dir !== root) {
593
- if (existsSync3(path3.join(dir, "package.json"))) return dir;
594
- dir = path3.dirname(dir);
1338
+ if (existsSync4(path5.join(dir, "package.json"))) return dir;
1339
+ dir = path5.dirname(dir);
595
1340
  }
596
1341
  return null;
597
1342
  }
598
1343
  function spawnDaemon() {
599
- const freeGB = os3.freemem() / (1024 * 1024 * 1024);
600
- const totalGB = os3.totalmem() / (1024 * 1024 * 1024);
1344
+ const freeGB = os4.freemem() / (1024 * 1024 * 1024);
1345
+ const totalGB = os4.totalmem() / (1024 * 1024 * 1024);
601
1346
  if (totalGB <= 8) {
602
1347
  process.stderr.write(
603
1348
  `[exed-client] SKIP: ${totalGB.toFixed(0)}GB system \u2014 embedding daemon disabled. Using keyword search only. Minimum 16GB recommended for vector search.
@@ -617,8 +1362,8 @@ function spawnDaemon() {
617
1362
  process.stderr.write("[exed-client] WARN: cannot find package root\n");
618
1363
  return;
619
1364
  }
620
- const daemonPath = path3.join(pkgRoot, "dist", "lib", "exe-daemon.js");
621
- if (!existsSync3(daemonPath)) {
1365
+ const daemonPath = path5.join(pkgRoot, "dist", "lib", "exe-daemon.js");
1366
+ if (!existsSync4(daemonPath)) {
622
1367
  process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
623
1368
  `);
624
1369
  return;
@@ -626,7 +1371,7 @@ function spawnDaemon() {
626
1371
  const resolvedPath = daemonPath;
627
1372
  process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
628
1373
  `);
629
- const logPath = path3.join(path3.dirname(SOCKET_PATH), "exed.log");
1374
+ const logPath = path5.join(path5.dirname(SOCKET_PATH), "exed.log");
630
1375
  let stderrFd = "ignore";
631
1376
  try {
632
1377
  stderrFd = openSync(logPath, "a");
@@ -777,74 +1522,123 @@ async function pingDaemon() {
777
1522
  return null;
778
1523
  }
779
1524
  function killAndRespawnDaemon() {
780
- process.stderr.write("[exed-client] Killing daemon for restart...\n");
781
- if (existsSync3(PID_PATH)) {
782
- try {
783
- const pid = parseInt(readFileSync3(PID_PATH, "utf8").trim(), 10);
784
- if (pid > 0) {
785
- try {
786
- process.kill(pid, "SIGKILL");
787
- } catch {
1525
+ if (!acquireSpawnLock()) {
1526
+ process.stderr.write("[exed-client] Another process is already restarting daemon \u2014 skipping\n");
1527
+ if (_socket) {
1528
+ _socket.destroy();
1529
+ _socket = null;
1530
+ }
1531
+ _connected = false;
1532
+ _buffer = "";
1533
+ return;
1534
+ }
1535
+ try {
1536
+ process.stderr.write("[exed-client] Killing daemon for restart...\n");
1537
+ if (existsSync4(PID_PATH)) {
1538
+ try {
1539
+ const pid = parseInt(readFileSync4(PID_PATH, "utf8").trim(), 10);
1540
+ if (pid > 0) {
1541
+ try {
1542
+ process.kill(pid, "SIGKILL");
1543
+ } catch {
1544
+ }
788
1545
  }
1546
+ } catch {
789
1547
  }
1548
+ }
1549
+ if (_socket) {
1550
+ _socket.destroy();
1551
+ _socket = null;
1552
+ }
1553
+ _connected = false;
1554
+ _buffer = "";
1555
+ try {
1556
+ unlinkSync2(PID_PATH);
790
1557
  } catch {
791
1558
  }
1559
+ try {
1560
+ unlinkSync2(SOCKET_PATH);
1561
+ } catch {
1562
+ }
1563
+ spawnDaemon();
1564
+ } finally {
1565
+ releaseSpawnLock();
792
1566
  }
793
- if (_socket) {
794
- _socket.destroy();
795
- _socket = null;
796
- }
797
- _connected = false;
798
- _buffer = "";
1567
+ }
1568
+ function isDaemonTooYoung() {
799
1569
  try {
800
- unlinkSync2(PID_PATH);
1570
+ const stat = statSync(PID_PATH);
1571
+ return Date.now() - stat.mtimeMs < MIN_DAEMON_AGE_MS;
801
1572
  } catch {
1573
+ return false;
802
1574
  }
803
- try {
804
- unlinkSync2(SOCKET_PATH);
805
- } catch {
1575
+ }
1576
+ async function retryThenRestart(doRequest, label) {
1577
+ const result = await doRequest();
1578
+ if (!result.error) {
1579
+ _consecutiveFailures = 0;
1580
+ return result;
1581
+ }
1582
+ _consecutiveFailures++;
1583
+ for (let i = 0; i < MAX_RETRIES_BEFORE_RESTART; i++) {
1584
+ const delayMs = RETRY_DELAYS_MS[i] ?? 5e3;
1585
+ process.stderr.write(`[exed-client] ${label} failed (${result.error}), retry ${i + 1}/${MAX_RETRIES_BEFORE_RESTART} in ${delayMs}ms
1586
+ `);
1587
+ await new Promise((r) => setTimeout(r, delayMs));
1588
+ if (!_connected) {
1589
+ if (!await connectToSocket()) continue;
1590
+ }
1591
+ const retry = await doRequest();
1592
+ if (!retry.error) {
1593
+ _consecutiveFailures = 0;
1594
+ return retry;
1595
+ }
1596
+ _consecutiveFailures++;
1597
+ }
1598
+ if (isDaemonTooYoung()) {
1599
+ process.stderr.write(`[exed-client] ${label}: daemon too young (< ${MIN_DAEMON_AGE_MS / 1e3}s) \u2014 skipping restart
1600
+ `);
1601
+ return { error: result.error };
1602
+ }
1603
+ process.stderr.write(`[exed-client] ${label}: ${_consecutiveFailures} consecutive failures \u2014 restarting daemon
1604
+ `);
1605
+ killAndRespawnDaemon();
1606
+ const start = Date.now();
1607
+ let delay2 = 200;
1608
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
1609
+ await new Promise((r) => setTimeout(r, delay2));
1610
+ if (await connectToSocket()) break;
1611
+ delay2 = Math.min(delay2 * 2, 3e3);
806
1612
  }
807
- spawnDaemon();
1613
+ if (!_connected) return { error: "Daemon restart failed" };
1614
+ const final = await doRequest();
1615
+ if (!final.error) _consecutiveFailures = 0;
1616
+ return final;
808
1617
  }
809
1618
  async function embedViaClient(text, priority = "high") {
810
1619
  if (!_connected && !await connectEmbedDaemon()) return null;
811
1620
  _requestCount++;
812
1621
  if (_requestCount % HEALTH_CHECK_INTERVAL === 0) {
813
1622
  const health = await pingDaemon();
814
- if (!health) {
1623
+ if (!health && !isDaemonTooYoung()) {
815
1624
  process.stderr.write(`[exed-client] Periodic health check failed at request ${_requestCount} \u2014 restarting daemon
816
1625
  `);
817
1626
  killAndRespawnDaemon();
818
1627
  const start = Date.now();
819
- let delay2 = 200;
1628
+ let d = 200;
820
1629
  while (Date.now() - start < CONNECT_TIMEOUT_MS) {
821
- await new Promise((r) => setTimeout(r, delay2));
1630
+ await new Promise((r) => setTimeout(r, d));
822
1631
  if (await connectToSocket()) break;
823
- delay2 = Math.min(delay2 * 2, 3e3);
1632
+ d = Math.min(d * 2, 3e3);
824
1633
  }
825
1634
  if (!_connected) return null;
826
1635
  }
827
1636
  }
828
- const result = await sendRequest([text], priority);
829
- if (!result.error && result.vectors?.[0]) return result.vectors[0];
830
- if (result.error) {
831
- process.stderr.write(`[exed-client] Embed failed (${result.error}) \u2014 attempting restart
832
- `);
833
- killAndRespawnDaemon();
834
- const start = Date.now();
835
- let delay2 = 200;
836
- while (Date.now() - start < CONNECT_TIMEOUT_MS) {
837
- await new Promise((r) => setTimeout(r, delay2));
838
- if (await connectToSocket()) break;
839
- delay2 = Math.min(delay2 * 2, 3e3);
840
- }
841
- if (!_connected) return null;
842
- const retry = await sendRequest([text], priority);
843
- if (!retry.error && retry.vectors?.[0]) return retry.vectors[0];
844
- process.stderr.write(`[exed-client] Embed retry also failed: ${retry.error ?? "no vector"}
845
- `);
846
- }
847
- return null;
1637
+ const result = await retryThenRestart(
1638
+ () => sendRequest([text], priority),
1639
+ "Embed"
1640
+ );
1641
+ return !result.error && result.vectors?.[0] ? result.vectors[0] : null;
848
1642
  }
849
1643
  function disconnectClient() {
850
1644
  if (_socket) {
@@ -862,14 +1656,14 @@ function disconnectClient() {
862
1656
  function isClientConnected() {
863
1657
  return _connected;
864
1658
  }
865
- 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;
1659
+ var SOCKET_PATH, PID_PATH, SPAWN_LOCK_PATH, SPAWN_LOCK_STALE_MS, CONNECT_TIMEOUT_MS, REQUEST_TIMEOUT_MS, _socket, _connected, _buffer, _requestCount, _consecutiveFailures, HEALTH_CHECK_INTERVAL, MAX_RETRIES_BEFORE_RESTART, RETRY_DELAYS_MS, MIN_DAEMON_AGE_MS, _pending, MAX_BUFFER;
866
1660
  var init_exe_daemon_client = __esm({
867
1661
  "src/lib/exe-daemon-client.ts"() {
868
1662
  "use strict";
869
1663
  init_config();
870
- SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path3.join(EXE_AI_DIR, "exed.sock");
871
- PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path3.join(EXE_AI_DIR, "exed.pid");
872
- SPAWN_LOCK_PATH = path3.join(EXE_AI_DIR, "exed-spawn.lock");
1664
+ SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path5.join(EXE_AI_DIR, "exed.sock");
1665
+ PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path5.join(EXE_AI_DIR, "exed.pid");
1666
+ SPAWN_LOCK_PATH = path5.join(EXE_AI_DIR, "exed-spawn.lock");
873
1667
  SPAWN_LOCK_STALE_MS = 3e4;
874
1668
  CONNECT_TIMEOUT_MS = 15e3;
875
1669
  REQUEST_TIMEOUT_MS = 3e4;
@@ -877,7 +1671,11 @@ var init_exe_daemon_client = __esm({
877
1671
  _connected = false;
878
1672
  _buffer = "";
879
1673
  _requestCount = 0;
1674
+ _consecutiveFailures = 0;
880
1675
  HEALTH_CHECK_INTERVAL = 100;
1676
+ MAX_RETRIES_BEFORE_RESTART = 3;
1677
+ RETRY_DELAYS_MS = [1e3, 3e3, 5e3];
1678
+ MIN_DAEMON_AGE_MS = 3e4;
881
1679
  _pending = /* @__PURE__ */ new Map();
882
1680
  MAX_BUFFER = 1e7;
883
1681
  }
@@ -953,7 +1751,7 @@ __export(db_daemon_client_exports, {
953
1751
  createDaemonDbClient: () => createDaemonDbClient,
954
1752
  initDaemonDbClient: () => initDaemonDbClient
955
1753
  });
956
- function normalizeStatement(stmt) {
1754
+ function normalizeStatement2(stmt) {
957
1755
  if (typeof stmt === "string") {
958
1756
  return { sql: stmt, args: [] };
959
1757
  }
@@ -977,7 +1775,7 @@ function createDaemonDbClient(fallbackClient) {
977
1775
  if (!_useDaemon || !isClientConnected()) {
978
1776
  return fallbackClient.execute(stmt);
979
1777
  }
980
- const { sql, args } = normalizeStatement(stmt);
1778
+ const { sql, args } = normalizeStatement2(stmt);
981
1779
  const response = await sendDaemonRequest({
982
1780
  type: "db-execute",
983
1781
  sql,
@@ -1002,7 +1800,7 @@ function createDaemonDbClient(fallbackClient) {
1002
1800
  if (!_useDaemon || !isClientConnected()) {
1003
1801
  return fallbackClient.batch(stmts, mode);
1004
1802
  }
1005
- const statements = stmts.map(normalizeStatement);
1803
+ const statements = stmts.map(normalizeStatement2);
1006
1804
  const response = await sendDaemonRequest({
1007
1805
  type: "db-batch",
1008
1806
  statements,
@@ -1097,6 +1895,18 @@ __export(database_exports, {
1097
1895
  });
1098
1896
  import { createClient } from "@libsql/client";
1099
1897
  async function initDatabase(config) {
1898
+ if (_walCheckpointTimer) {
1899
+ clearInterval(_walCheckpointTimer);
1900
+ _walCheckpointTimer = null;
1901
+ }
1902
+ if (_daemonClient) {
1903
+ _daemonClient.close();
1904
+ _daemonClient = null;
1905
+ }
1906
+ if (_adapterClient && _adapterClient !== _resilientClient) {
1907
+ _adapterClient.close();
1908
+ }
1909
+ _adapterClient = null;
1100
1910
  if (_client) {
1101
1911
  _client.close();
1102
1912
  _client = null;
@@ -1110,6 +1920,7 @@ async function initDatabase(config) {
1110
1920
  }
1111
1921
  _client = createClient(opts);
1112
1922
  _resilientClient = wrapWithRetry(_client);
1923
+ _adapterClient = _resilientClient;
1113
1924
  _client.execute("PRAGMA busy_timeout = 30000").catch(() => {
1114
1925
  });
1115
1926
  _client.execute("PRAGMA journal_mode = WAL").catch(() => {
@@ -1120,14 +1931,20 @@ async function initDatabase(config) {
1120
1931
  });
1121
1932
  }, 3e4);
1122
1933
  _walCheckpointTimer.unref();
1934
+ if (process.env.DATABASE_URL) {
1935
+ _adapterClient = await createPrismaDbAdapter(_resilientClient);
1936
+ }
1123
1937
  }
1124
1938
  function isInitialized() {
1125
- return _client !== null;
1939
+ return _adapterClient !== null || _client !== null;
1126
1940
  }
1127
1941
  function getClient() {
1128
- if (!_resilientClient) {
1942
+ if (!_adapterClient) {
1129
1943
  throw new Error("Database client not initialized. Call initDatabase() first.");
1130
1944
  }
1945
+ if (process.env.DATABASE_URL) {
1946
+ return _adapterClient;
1947
+ }
1131
1948
  if (process.env.EXE_IS_DAEMON === "1") {
1132
1949
  return _resilientClient;
1133
1950
  }
@@ -1137,6 +1954,7 @@ function getClient() {
1137
1954
  return _resilientClient;
1138
1955
  }
1139
1956
  async function initDaemonClient() {
1957
+ if (process.env.DATABASE_URL) return;
1140
1958
  if (process.env.EXE_IS_DAEMON === "1") return;
1141
1959
  if (!_resilientClient) return;
1142
1960
  try {
@@ -2081,26 +2899,36 @@ async function ensureSchema() {
2081
2899
  }
2082
2900
  }
2083
2901
  async function disposeDatabase() {
2902
+ if (_walCheckpointTimer) {
2903
+ clearInterval(_walCheckpointTimer);
2904
+ _walCheckpointTimer = null;
2905
+ }
2084
2906
  if (_daemonClient) {
2085
2907
  _daemonClient.close();
2086
2908
  _daemonClient = null;
2087
2909
  }
2910
+ if (_adapterClient && _adapterClient !== _resilientClient) {
2911
+ _adapterClient.close();
2912
+ }
2913
+ _adapterClient = null;
2088
2914
  if (_client) {
2089
2915
  _client.close();
2090
2916
  _client = null;
2091
2917
  _resilientClient = null;
2092
2918
  }
2093
2919
  }
2094
- var _client, _resilientClient, _walCheckpointTimer, _daemonClient, initTurso, disposeTurso;
2920
+ var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso, disposeTurso;
2095
2921
  var init_database = __esm({
2096
2922
  "src/lib/database.ts"() {
2097
2923
  "use strict";
2098
2924
  init_db_retry();
2099
2925
  init_employees();
2926
+ init_database_adapter();
2100
2927
  _client = null;
2101
2928
  _resilientClient = null;
2102
2929
  _walCheckpointTimer = null;
2103
2930
  _daemonClient = null;
2931
+ _adapterClient = null;
2104
2932
  initTurso = initDatabase;
2105
2933
  disposeTurso = disposeDatabase;
2106
2934
  }
@@ -2108,14 +2936,14 @@ var init_database = __esm({
2108
2936
 
2109
2937
  // src/lib/keychain.ts
2110
2938
  import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
2111
- import { existsSync as existsSync4 } from "fs";
2112
- import path4 from "path";
2113
- import os4 from "os";
2939
+ import { existsSync as existsSync5 } from "fs";
2940
+ import path6 from "path";
2941
+ import os5 from "os";
2114
2942
  function getKeyDir() {
2115
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path4.join(os4.homedir(), ".exe-os");
2943
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path6.join(os5.homedir(), ".exe-os");
2116
2944
  }
2117
2945
  function getKeyPath() {
2118
- return path4.join(getKeyDir(), "master.key");
2946
+ return path6.join(getKeyDir(), "master.key");
2119
2947
  }
2120
2948
  async function tryKeytar() {
2121
2949
  try {
@@ -2136,9 +2964,9 @@ async function getMasterKey() {
2136
2964
  }
2137
2965
  }
2138
2966
  const keyPath = getKeyPath();
2139
- if (!existsSync4(keyPath)) {
2967
+ if (!existsSync5(keyPath)) {
2140
2968
  process.stderr.write(
2141
- `[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2969
+ `[keychain] Key not found at ${keyPath} (HOME=${os5.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2142
2970
  `
2143
2971
  );
2144
2972
  return null;
@@ -2231,13 +3059,13 @@ __export(shard_manager_exports, {
2231
3059
  listShards: () => listShards,
2232
3060
  shardExists: () => shardExists
2233
3061
  });
2234
- import path5 from "path";
2235
- import { existsSync as existsSync5, mkdirSync, readdirSync } from "fs";
3062
+ import path7 from "path";
3063
+ import { existsSync as existsSync6, mkdirSync as mkdirSync2, readdirSync } from "fs";
2236
3064
  import { createClient as createClient2 } from "@libsql/client";
2237
3065
  function initShardManager(encryptionKey) {
2238
3066
  _encryptionKey = encryptionKey;
2239
- if (!existsSync5(SHARDS_DIR)) {
2240
- mkdirSync(SHARDS_DIR, { recursive: true });
3067
+ if (!existsSync6(SHARDS_DIR)) {
3068
+ mkdirSync2(SHARDS_DIR, { recursive: true });
2241
3069
  }
2242
3070
  _shardingEnabled = true;
2243
3071
  }
@@ -2257,7 +3085,7 @@ function getShardClient(projectName) {
2257
3085
  }
2258
3086
  const cached = _shards.get(safeName);
2259
3087
  if (cached) return cached;
2260
- const dbPath = path5.join(SHARDS_DIR, `${safeName}.db`);
3088
+ const dbPath = path7.join(SHARDS_DIR, `${safeName}.db`);
2261
3089
  const client = createClient2({
2262
3090
  url: `file:${dbPath}`,
2263
3091
  encryptionKey: _encryptionKey
@@ -2267,10 +3095,10 @@ function getShardClient(projectName) {
2267
3095
  }
2268
3096
  function shardExists(projectName) {
2269
3097
  const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
2270
- return existsSync5(path5.join(SHARDS_DIR, `${safeName}.db`));
3098
+ return existsSync6(path7.join(SHARDS_DIR, `${safeName}.db`));
2271
3099
  }
2272
3100
  function listShards() {
2273
- if (!existsSync5(SHARDS_DIR)) return [];
3101
+ if (!existsSync6(SHARDS_DIR)) return [];
2274
3102
  return readdirSync(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
2275
3103
  }
2276
3104
  async function ensureShardSchema(client) {
@@ -2344,7 +3172,23 @@ async function ensureShardSchema(client) {
2344
3172
  // MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
2345
3173
  "ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
2346
3174
  "ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
2347
- "ALTER TABLE memories ADD COLUMN trajectory TEXT"
3175
+ "ALTER TABLE memories ADD COLUMN trajectory TEXT",
3176
+ // Metadata enrichment columns (must match database.ts)
3177
+ "ALTER TABLE memories ADD COLUMN intent TEXT",
3178
+ "ALTER TABLE memories ADD COLUMN outcome TEXT",
3179
+ "ALTER TABLE memories ADD COLUMN domain TEXT",
3180
+ "ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
3181
+ "ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
3182
+ "ALTER TABLE memories ADD COLUMN chain_position TEXT",
3183
+ "ALTER TABLE memories ADD COLUMN review_status TEXT",
3184
+ "ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
3185
+ "ALTER TABLE memories ADD COLUMN file_paths TEXT",
3186
+ "ALTER TABLE memories ADD COLUMN commit_hash TEXT",
3187
+ "ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
3188
+ "ALTER TABLE memories ADD COLUMN token_cost REAL",
3189
+ "ALTER TABLE memories ADD COLUMN audience TEXT",
3190
+ "ALTER TABLE memories ADD COLUMN language_type TEXT",
3191
+ "ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
2348
3192
  ]) {
2349
3193
  try {
2350
3194
  await client.execute(col);
@@ -2456,7 +3300,7 @@ var init_shard_manager = __esm({
2456
3300
  "src/lib/shard-manager.ts"() {
2457
3301
  "use strict";
2458
3302
  init_config();
2459
- SHARDS_DIR = path5.join(EXE_AI_DIR, "shards");
3303
+ SHARDS_DIR = path7.join(EXE_AI_DIR, "shards");
2460
3304
  _shards = /* @__PURE__ */ new Map();
2461
3305
  _encryptionKey = null;
2462
3306
  _shardingEnabled = false;
@@ -3319,8 +4163,8 @@ __export(reranker_exports, {
3319
4163
  rerankWithContext: () => rerankWithContext,
3320
4164
  rerankWithScores: () => rerankWithScores
3321
4165
  });
3322
- import path6 from "path";
3323
- import { existsSync as existsSync6 } from "fs";
4166
+ import path8 from "path";
4167
+ import { existsSync as existsSync7 } from "fs";
3324
4168
  function resetIdleTimer() {
3325
4169
  if (_idleTimer) clearTimeout(_idleTimer);
3326
4170
  _idleTimer = setTimeout(() => {
@@ -3331,18 +4175,18 @@ function resetIdleTimer() {
3331
4175
  }
3332
4176
  }
3333
4177
  function isRerankerAvailable() {
3334
- return existsSync6(path6.join(MODELS_DIR, RERANKER_MODEL_FILE));
4178
+ return existsSync7(path8.join(MODELS_DIR, RERANKER_MODEL_FILE));
3335
4179
  }
3336
4180
  function getRerankerModelPath() {
3337
- return path6.join(MODELS_DIR, RERANKER_MODEL_FILE);
4181
+ return path8.join(MODELS_DIR, RERANKER_MODEL_FILE);
3338
4182
  }
3339
4183
  async function ensureLoaded() {
3340
4184
  if (_rerankerContext) {
3341
4185
  resetIdleTimer();
3342
4186
  return;
3343
4187
  }
3344
- const modelPath = path6.join(MODELS_DIR, RERANKER_MODEL_FILE);
3345
- if (!existsSync6(modelPath)) {
4188
+ const modelPath = path8.join(MODELS_DIR, RERANKER_MODEL_FILE);
4189
+ if (!existsSync7(modelPath)) {
3346
4190
  throw new Error(
3347
4191
  `Reranker model not found at ${modelPath}. Run /exe-setup to download it.`
3348
4192
  );
@@ -3475,10 +4319,10 @@ async function disposeEmbedder() {
3475
4319
  async function embedDirect(text) {
3476
4320
  const llamaCpp = await import("node-llama-cpp");
3477
4321
  const { MODELS_DIR: MODELS_DIR2 } = await Promise.resolve().then(() => (init_config(), config_exports));
3478
- const { existsSync: existsSync13 } = await import("fs");
3479
- const path17 = await import("path");
3480
- const modelPath = path17.join(MODELS_DIR2, "jina-embeddings-v5-small-q4_k_m.gguf");
3481
- if (!existsSync13(modelPath)) {
4322
+ const { existsSync: existsSync14 } = await import("fs");
4323
+ const path18 = await import("path");
4324
+ const modelPath = path18.join(MODELS_DIR2, "jina-embeddings-v5-small-q4_k_m.gguf");
4325
+ if (!existsSync14(modelPath)) {
3482
4326
  throw new Error(`Embedding model not found at ${modelPath}. Run '/exe-setup' to download it.`);
3483
4327
  }
3484
4328
  const llama = await llamaCpp.getLlama();
@@ -3513,7 +4357,7 @@ __export(project_name_exports, {
3513
4357
  getProjectName: () => getProjectName
3514
4358
  });
3515
4359
  import { execSync as execSync2 } from "child_process";
3516
- import path7 from "path";
4360
+ import path9 from "path";
3517
4361
  function getProjectName(cwd) {
3518
4362
  const dir = cwd ?? process.cwd();
3519
4363
  if (_cached && _cachedCwd === dir) return _cached;
@@ -3526,7 +4370,7 @@ function getProjectName(cwd) {
3526
4370
  timeout: 2e3,
3527
4371
  stdio: ["pipe", "pipe", "pipe"]
3528
4372
  }).trim();
3529
- repoRoot = path7.dirname(gitCommonDir);
4373
+ repoRoot = path9.dirname(gitCommonDir);
3530
4374
  } catch {
3531
4375
  repoRoot = execSync2("git rev-parse --show-toplevel", {
3532
4376
  cwd: dir,
@@ -3535,11 +4379,11 @@ function getProjectName(cwd) {
3535
4379
  stdio: ["pipe", "pipe", "pipe"]
3536
4380
  }).trim();
3537
4381
  }
3538
- _cached = path7.basename(repoRoot);
4382
+ _cached = path9.basename(repoRoot);
3539
4383
  _cachedCwd = dir;
3540
4384
  return _cached;
3541
4385
  } catch {
3542
- _cached = path7.basename(dir);
4386
+ _cached = path9.basename(dir);
3543
4387
  _cachedCwd = dir;
3544
4388
  return _cached;
3545
4389
  }
@@ -3563,8 +4407,8 @@ __export(file_grep_exports, {
3563
4407
  grepProjectFiles: () => grepProjectFiles
3564
4408
  });
3565
4409
  import { execSync as execSync3 } from "child_process";
3566
- import { readFileSync as readFileSync4, readdirSync as readdirSync2, statSync as statSync2, existsSync as existsSync7 } from "fs";
3567
- import path8 from "path";
4410
+ import { readFileSync as readFileSync5, readdirSync as readdirSync2, statSync as statSync2, existsSync as existsSync8 } from "fs";
4411
+ import path10 from "path";
3568
4412
  import crypto from "crypto";
3569
4413
  function hasRipgrep() {
3570
4414
  if (_hasRg === null) {
@@ -3604,7 +4448,7 @@ async function grepProjectFiles(query, projectRoot, options) {
3604
4448
  session_id: "file-grep",
3605
4449
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3606
4450
  tool_name: "file_grep",
3607
- project_name: path8.basename(projectRoot),
4451
+ project_name: path10.basename(projectRoot),
3608
4452
  has_error: false,
3609
4453
  raw_text: `${prefix} ${buildSnippet(hit, projectRoot)}`,
3610
4454
  vector: null,
@@ -3616,7 +4460,7 @@ function getChunkContext(filePath, lineNumber) {
3616
4460
  try {
3617
4461
  const ext = filePath.split(".").pop()?.toLowerCase();
3618
4462
  if (ext !== "ts" && ext !== "tsx" && ext !== "js" && ext !== "jsx") return "";
3619
- const source = readFileSync4(filePath, "utf8");
4463
+ const source = readFileSync5(filePath, "utf8");
3620
4464
  const lines = source.split("\n");
3621
4465
  for (let i = Math.min(lineNumber - 1, lines.length - 1); i >= 0; i--) {
3622
4466
  const line = lines[i];
@@ -3678,11 +4522,11 @@ function grepWithNodeFs(pattern, projectRoot, patterns) {
3678
4522
  const files = collectFiles(projectRoot, patterns ?? DEFAULT_PATTERNS);
3679
4523
  const hits = [];
3680
4524
  for (const filePath of files.slice(0, MAX_FILES)) {
3681
- const absPath = path8.join(projectRoot, filePath);
4525
+ const absPath = path10.join(projectRoot, filePath);
3682
4526
  try {
3683
4527
  const stat = statSync2(absPath);
3684
4528
  if (stat.size > MAX_FILE_SIZE) continue;
3685
- const content = readFileSync4(absPath, "utf8");
4529
+ const content = readFileSync5(absPath, "utf8");
3686
4530
  const lines = content.split("\n");
3687
4531
  const matches = content.match(regex);
3688
4532
  if (!matches || matches.length === 0) continue;
@@ -3705,15 +4549,15 @@ function collectFiles(root, patterns) {
3705
4549
  const files = [];
3706
4550
  function walk(dir, relative) {
3707
4551
  if (files.length >= MAX_FILES) return;
3708
- const basename = path8.basename(dir);
4552
+ const basename = path10.basename(dir);
3709
4553
  if (EXCLUDE_DIRS.includes(basename)) return;
3710
4554
  try {
3711
4555
  const entries = readdirSync2(dir, { withFileTypes: true });
3712
4556
  for (const entry of entries) {
3713
4557
  if (files.length >= MAX_FILES) return;
3714
- const rel = path8.join(relative, entry.name);
4558
+ const rel = path10.join(relative, entry.name);
3715
4559
  if (entry.isDirectory()) {
3716
- walk(path8.join(dir, entry.name), rel);
4560
+ walk(path10.join(dir, entry.name), rel);
3717
4561
  } else if (entry.isFile()) {
3718
4562
  for (const pat of patterns) {
3719
4563
  if (matchGlob(rel, pat)) {
@@ -3745,7 +4589,7 @@ function matchGlob(filePath, pattern) {
3745
4589
  if (slashIdx !== -1) {
3746
4590
  const dir = pattern.slice(0, slashIdx);
3747
4591
  const ext2 = pattern.slice(slashIdx + 1).replace("*", "");
3748
- const fileDir = path8.dirname(filePath);
4592
+ const fileDir = path10.dirname(filePath);
3749
4593
  return fileDir === dir && filePath.endsWith(ext2);
3750
4594
  }
3751
4595
  const ext = pattern.replace("*", "");
@@ -3753,9 +4597,9 @@ function matchGlob(filePath, pattern) {
3753
4597
  }
3754
4598
  function buildSnippet(hit, projectRoot) {
3755
4599
  try {
3756
- const absPath = path8.join(projectRoot, hit.filePath);
3757
- if (!existsSync7(absPath)) return hit.matchLine;
3758
- const lines = readFileSync4(absPath, "utf8").split("\n");
4600
+ const absPath = path10.join(projectRoot, hit.filePath);
4601
+ if (!existsSync8(absPath)) return hit.matchLine;
4602
+ const lines = readFileSync5(absPath, "utf8").split("\n");
3759
4603
  const start = Math.max(0, hit.lineNumber - 3);
3760
4604
  const end = Math.min(lines.length, hit.lineNumber + 2);
3761
4605
  return lines.slice(start, end).join("\n").slice(0, 500);
@@ -4971,9 +5815,9 @@ var init_session_key = __esm({
4971
5815
  });
4972
5816
 
4973
5817
  // src/lib/active-agent.ts
4974
- import { readFileSync as readFileSync5, writeFileSync as writeFileSync2, mkdirSync as mkdirSync2, unlinkSync as unlinkSync3, readdirSync as readdirSync3 } from "fs";
5818
+ import { readFileSync as readFileSync6, writeFileSync as writeFileSync3, mkdirSync as mkdirSync3, unlinkSync as unlinkSync3, readdirSync as readdirSync3 } from "fs";
4975
5819
  import { execSync as execSync5 } from "child_process";
4976
- import path9 from "path";
5820
+ import path11 from "path";
4977
5821
  function isNameWithOptionalInstance(candidate, baseName) {
4978
5822
  if (candidate === baseName) return true;
4979
5823
  if (!candidate.startsWith(baseName)) return false;
@@ -5017,12 +5861,12 @@ function resolveActiveAgentFromTmuxSession(sessionName) {
5017
5861
  return null;
5018
5862
  }
5019
5863
  function getMarkerPath() {
5020
- return path9.join(CACHE_DIR, `active-agent-${getSessionKey()}.json`);
5864
+ return path11.join(CACHE_DIR, `active-agent-${getSessionKey()}.json`);
5021
5865
  }
5022
5866
  function writeActiveAgent(agentId, agentRole) {
5023
5867
  try {
5024
- mkdirSync2(CACHE_DIR, { recursive: true });
5025
- writeFileSync2(
5868
+ mkdirSync3(CACHE_DIR, { recursive: true });
5869
+ writeFileSync3(
5026
5870
  getMarkerPath(),
5027
5871
  JSON.stringify({ agentId, agentRole, startedAt: (/* @__PURE__ */ new Date()).toISOString() })
5028
5872
  );
@@ -5038,7 +5882,7 @@ function clearActiveAgent() {
5038
5882
  function getActiveAgent() {
5039
5883
  try {
5040
5884
  const markerPath = getMarkerPath();
5041
- const raw = readFileSync5(markerPath, "utf8");
5885
+ const raw = readFileSync6(markerPath, "utf8");
5042
5886
  const data = JSON.parse(raw);
5043
5887
  if (data.agentId) {
5044
5888
  if (data.startedAt) {
@@ -5086,14 +5930,14 @@ function getAllActiveAgents() {
5086
5930
  const key = file.slice("active-agent-".length, -".json".length);
5087
5931
  if (key === "undefined") continue;
5088
5932
  try {
5089
- const raw = readFileSync5(path9.join(CACHE_DIR, file), "utf8");
5933
+ const raw = readFileSync6(path11.join(CACHE_DIR, file), "utf8");
5090
5934
  const data = JSON.parse(raw);
5091
5935
  if (!data.agentId) continue;
5092
5936
  if (data.startedAt) {
5093
5937
  const age = Date.now() - new Date(data.startedAt).getTime();
5094
5938
  if (age > STALE_MS) {
5095
5939
  try {
5096
- unlinkSync3(path9.join(CACHE_DIR, file));
5940
+ unlinkSync3(path11.join(CACHE_DIR, file));
5097
5941
  } catch {
5098
5942
  }
5099
5943
  continue;
@@ -5116,11 +5960,11 @@ function getAllActiveAgents() {
5116
5960
  function cleanupSessionMarkers() {
5117
5961
  const key = getSessionKey();
5118
5962
  try {
5119
- unlinkSync3(path9.join(CACHE_DIR, `active-agent-${key}.json`));
5963
+ unlinkSync3(path11.join(CACHE_DIR, `active-agent-${key}.json`));
5120
5964
  } catch {
5121
5965
  }
5122
5966
  try {
5123
- unlinkSync3(path9.join(CACHE_DIR, "active-agent-undefined.json"));
5967
+ unlinkSync3(path11.join(CACHE_DIR, "active-agent-undefined.json"));
5124
5968
  } catch {
5125
5969
  }
5126
5970
  }
@@ -5131,7 +5975,7 @@ var init_active_agent = __esm({
5131
5975
  init_config();
5132
5976
  init_session_key();
5133
5977
  init_employees();
5134
- CACHE_DIR = path9.join(EXE_AI_DIR, "session-cache");
5978
+ CACHE_DIR = path11.join(EXE_AI_DIR, "session-cache");
5135
5979
  STALE_MS = 24 * 60 * 60 * 1e3;
5136
5980
  }
5137
5981
  });
@@ -5154,13 +5998,13 @@ var init_active_agent2 = __esm({
5154
5998
  });
5155
5999
 
5156
6000
  // src/lib/session-registry.ts
5157
- import path10 from "path";
5158
- import os5 from "os";
6001
+ import path12 from "path";
6002
+ import os6 from "os";
5159
6003
  var REGISTRY_PATH;
5160
6004
  var init_session_registry = __esm({
5161
6005
  "src/lib/session-registry.ts"() {
5162
6006
  "use strict";
5163
- REGISTRY_PATH = path10.join(os5.homedir(), ".exe-os", "session-registry.json");
6007
+ REGISTRY_PATH = path12.join(os6.homedir(), ".exe-os", "session-registry.json");
5164
6008
  }
5165
6009
  });
5166
6010
 
@@ -5300,83 +6144,39 @@ var init_provider_table = __esm({
5300
6144
  }
5301
6145
  });
5302
6146
 
5303
- // src/lib/runtime-table.ts
5304
- var RUNTIME_TABLE;
5305
- var init_runtime_table = __esm({
5306
- "src/lib/runtime-table.ts"() {
5307
- "use strict";
5308
- RUNTIME_TABLE = {
5309
- codex: {
5310
- binary: "codex",
5311
- launchMode: "interactive",
5312
- autoApproveFlag: "--dangerously-bypass-approvals-and-sandbox",
5313
- inlineFlag: "--no-alt-screen",
5314
- apiKeyEnv: "OPENAI_API_KEY",
5315
- defaultModel: "gpt-5.4"
5316
- },
5317
- opencode: {
5318
- binary: "opencode",
5319
- launchMode: "exec",
5320
- autoApproveFlag: "--dangerously-skip-permissions",
5321
- inlineFlag: "",
5322
- apiKeyEnv: "ANTHROPIC_API_KEY",
5323
- defaultModel: "anthropic/claude-sonnet-4-6"
5324
- }
5325
- };
5326
- }
5327
- });
5328
-
5329
- // src/lib/agent-config.ts
5330
- import { readFileSync as readFileSync6, writeFileSync as writeFileSync3, existsSync as existsSync8, mkdirSync as mkdirSync3 } from "fs";
5331
- import path11 from "path";
5332
- var AGENT_CONFIG_PATH, DEFAULT_MODELS;
5333
- var init_agent_config = __esm({
5334
- "src/lib/agent-config.ts"() {
5335
- "use strict";
5336
- init_config();
5337
- init_runtime_table();
5338
- AGENT_CONFIG_PATH = path11.join(EXE_AI_DIR, "agent-config.json");
5339
- DEFAULT_MODELS = {
5340
- claude: "claude-opus-4",
5341
- codex: RUNTIME_TABLE.codex?.defaultModel ?? "gpt-5.4",
5342
- opencode: RUNTIME_TABLE.opencode?.defaultModel ?? "anthropic/claude-sonnet-4-6"
5343
- };
5344
- }
5345
- });
5346
-
5347
6147
  // src/lib/intercom-queue.ts
5348
6148
  import { readFileSync as readFileSync7, writeFileSync as writeFileSync4, renameSync as renameSync3, existsSync as existsSync9, mkdirSync as mkdirSync4 } from "fs";
5349
- import path12 from "path";
5350
- import os6 from "os";
6149
+ import path13 from "path";
6150
+ import os7 from "os";
5351
6151
  var QUEUE_PATH, TTL_MS, INTERCOM_LOG;
5352
6152
  var init_intercom_queue = __esm({
5353
6153
  "src/lib/intercom-queue.ts"() {
5354
6154
  "use strict";
5355
- QUEUE_PATH = path12.join(os6.homedir(), ".exe-os", "intercom-queue.json");
6155
+ QUEUE_PATH = path13.join(os7.homedir(), ".exe-os", "intercom-queue.json");
5356
6156
  TTL_MS = 60 * 60 * 1e3;
5357
- INTERCOM_LOG = path12.join(os6.homedir(), ".exe-os", "intercom.log");
6157
+ INTERCOM_LOG = path13.join(os7.homedir(), ".exe-os", "intercom.log");
5358
6158
  }
5359
6159
  });
5360
6160
 
5361
6161
  // src/lib/license.ts
5362
6162
  import { readFileSync as readFileSync8, writeFileSync as writeFileSync5, existsSync as existsSync10, mkdirSync as mkdirSync5 } from "fs";
5363
6163
  import { randomUUID as randomUUID3 } from "crypto";
5364
- import path13 from "path";
6164
+ import path14 from "path";
5365
6165
  import { jwtVerify, importSPKI } from "jose";
5366
6166
  var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH;
5367
6167
  var init_license = __esm({
5368
6168
  "src/lib/license.ts"() {
5369
6169
  "use strict";
5370
6170
  init_config();
5371
- LICENSE_PATH = path13.join(EXE_AI_DIR, "license.key");
5372
- CACHE_PATH = path13.join(EXE_AI_DIR, "license-cache.json");
5373
- DEVICE_ID_PATH = path13.join(EXE_AI_DIR, "device-id");
6171
+ LICENSE_PATH = path14.join(EXE_AI_DIR, "license.key");
6172
+ CACHE_PATH = path14.join(EXE_AI_DIR, "license-cache.json");
6173
+ DEVICE_ID_PATH = path14.join(EXE_AI_DIR, "device-id");
5374
6174
  }
5375
6175
  });
5376
6176
 
5377
6177
  // src/lib/plan-limits.ts
5378
6178
  import { readFileSync as readFileSync9, existsSync as existsSync11 } from "fs";
5379
- import path14 from "path";
6179
+ import path15 from "path";
5380
6180
  var CACHE_PATH2;
5381
6181
  var init_plan_limits = __esm({
5382
6182
  "src/lib/plan-limits.ts"() {
@@ -5385,14 +6185,14 @@ var init_plan_limits = __esm({
5385
6185
  init_employees();
5386
6186
  init_license();
5387
6187
  init_config();
5388
- CACHE_PATH2 = path14.join(EXE_AI_DIR, "license-cache.json");
6188
+ CACHE_PATH2 = path15.join(EXE_AI_DIR, "license-cache.json");
5389
6189
  }
5390
6190
  });
5391
6191
 
5392
6192
  // src/lib/tmux-routing.ts
5393
6193
  import { readFileSync as readFileSync10, writeFileSync as writeFileSync6, mkdirSync as mkdirSync6, existsSync as existsSync12, appendFileSync, readdirSync as readdirSync4 } from "fs";
5394
- import path15 from "path";
5395
- import os7 from "os";
6194
+ import path16 from "path";
6195
+ import os8 from "os";
5396
6196
  import { fileURLToPath as fileURLToPath2 } from "url";
5397
6197
  function getMySession() {
5398
6198
  return getTransport().getMySession();
@@ -5405,7 +6205,7 @@ function extractRootExe(name) {
5405
6205
  }
5406
6206
  function getParentExe(sessionKey) {
5407
6207
  try {
5408
- const data = JSON.parse(readFileSync10(path15.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
6208
+ const data = JSON.parse(readFileSync10(path16.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
5409
6209
  return data.parentExe || null;
5410
6210
  } catch {
5411
6211
  return null;
@@ -5448,10 +6248,10 @@ var init_tmux_routing = __esm({
5448
6248
  init_intercom_queue();
5449
6249
  init_plan_limits();
5450
6250
  init_employees();
5451
- SPAWN_LOCK_DIR = path15.join(os7.homedir(), ".exe-os", "spawn-locks");
5452
- SESSION_CACHE = path15.join(os7.homedir(), ".exe-os", "session-cache");
5453
- INTERCOM_LOG2 = path15.join(os7.homedir(), ".exe-os", "intercom.log");
5454
- DEBOUNCE_FILE = path15.join(SESSION_CACHE, "intercom-debounce.json");
6251
+ SPAWN_LOCK_DIR = path16.join(os8.homedir(), ".exe-os", "spawn-locks");
6252
+ SESSION_CACHE = path16.join(os8.homedir(), ".exe-os", "session-cache");
6253
+ INTERCOM_LOG2 = path16.join(os8.homedir(), ".exe-os", "intercom.log");
6254
+ DEBOUNCE_FILE = path16.join(SESSION_CACHE, "intercom-debounce.json");
5455
6255
  DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
5456
6256
  }
5457
6257
  });
@@ -5487,8 +6287,8 @@ var init_task_scope = __esm({
5487
6287
 
5488
6288
  // src/adapters/claude/hooks/session-start.ts
5489
6289
  init_config();
5490
- import path16 from "path";
5491
- import { unlinkSync as unlinkSync4 } from "fs";
6290
+ import path17 from "path";
6291
+ import { unlinkSync as unlinkSync4, existsSync as existsSync13, readFileSync as readFileSync11 } from "fs";
5492
6292
  if (!process.env.AGENT_ID) {
5493
6293
  process.env.AGENT_ID = "default";
5494
6294
  process.env.AGENT_ROLE = "employee";
@@ -5521,8 +6321,8 @@ process.stdin.on("end", async () => {
5521
6321
  const source = data.source ?? "startup";
5522
6322
  if (source === "startup") {
5523
6323
  try {
5524
- const undefinedPath = path16.join(
5525
- process.env.EXE_OS_DIR ?? path16.join(process.env.HOME ?? "", ".exe-os"),
6324
+ const undefinedPath = path17.join(
6325
+ process.env.EXE_OS_DIR ?? path17.join(process.env.HOME ?? "", ".exe-os"),
5526
6326
  "session-cache",
5527
6327
  "active-agent-undefined.json"
5528
6328
  );
@@ -5533,6 +6333,30 @@ process.stdin.on("end", async () => {
5533
6333
  await initStore2({ dbPath: hookConfig.dbPath, lightweight: true });
5534
6334
  const agent = getActiveAgent2();
5535
6335
  const agentId = agent.agentId;
6336
+ if (agentId !== "default") {
6337
+ try {
6338
+ const cacheDir = path17.join(
6339
+ process.env.EXE_OS_DIR ?? path17.join(process.env.HOME ?? "", ".exe-os"),
6340
+ "session-cache"
6341
+ );
6342
+ const markerPath = path17.join(cacheDir, `current-task-${agentId}.json`);
6343
+ if (existsSync13(markerPath)) {
6344
+ const marker = JSON.parse(readFileSync11(markerPath, "utf-8"));
6345
+ if (marker.taskId) {
6346
+ const client = getClient2();
6347
+ const result = await client.execute({
6348
+ sql: "SELECT status FROM tasks WHERE id = ? LIMIT 1",
6349
+ args: [marker.taskId]
6350
+ });
6351
+ const status = result.rows[0]?.status;
6352
+ if (!status || status !== "in_progress") {
6353
+ unlinkSync4(markerPath);
6354
+ }
6355
+ }
6356
+ }
6357
+ } catch {
6358
+ }
6359
+ }
5536
6360
  try {
5537
6361
  const sessionId = data.session_id;
5538
6362
  if (sessionId && agentId !== "default") {