@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
@@ -101,11 +101,11 @@ var init_config = __esm({
101
101
 
102
102
  // src/lib/exe-daemon-client.ts
103
103
  import net from "net";
104
- import os3 from "os";
104
+ import os4 from "os";
105
105
  import { spawn } from "child_process";
106
106
  import { randomUUID } from "crypto";
107
107
  import { existsSync as existsSync3, unlinkSync as unlinkSync2, readFileSync as readFileSync3, openSync, closeSync, statSync } from "fs";
108
- import path3 from "path";
108
+ import path4 from "path";
109
109
  import { fileURLToPath } from "url";
110
110
  function handleData(chunk) {
111
111
  _buffer += chunk.toString();
@@ -156,17 +156,17 @@ function cleanupStaleFiles() {
156
156
  }
157
157
  }
158
158
  function findPackageRoot() {
159
- let dir = path3.dirname(fileURLToPath(import.meta.url));
160
- const { root } = path3.parse(dir);
159
+ let dir = path4.dirname(fileURLToPath(import.meta.url));
160
+ const { root } = path4.parse(dir);
161
161
  while (dir !== root) {
162
- if (existsSync3(path3.join(dir, "package.json"))) return dir;
163
- dir = path3.dirname(dir);
162
+ if (existsSync3(path4.join(dir, "package.json"))) return dir;
163
+ dir = path4.dirname(dir);
164
164
  }
165
165
  return null;
166
166
  }
167
167
  function spawnDaemon() {
168
- const freeGB = os3.freemem() / (1024 * 1024 * 1024);
169
- const totalGB = os3.totalmem() / (1024 * 1024 * 1024);
168
+ const freeGB = os4.freemem() / (1024 * 1024 * 1024);
169
+ const totalGB = os4.totalmem() / (1024 * 1024 * 1024);
170
170
  if (totalGB <= 8) {
171
171
  process.stderr.write(
172
172
  `[exed-client] SKIP: ${totalGB.toFixed(0)}GB system \u2014 embedding daemon disabled. Using keyword search only. Minimum 16GB recommended for vector search.
@@ -186,7 +186,7 @@ function spawnDaemon() {
186
186
  process.stderr.write("[exed-client] WARN: cannot find package root\n");
187
187
  return;
188
188
  }
189
- const daemonPath = path3.join(pkgRoot, "dist", "lib", "exe-daemon.js");
189
+ const daemonPath = path4.join(pkgRoot, "dist", "lib", "exe-daemon.js");
190
190
  if (!existsSync3(daemonPath)) {
191
191
  process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
192
192
  `);
@@ -195,7 +195,7 @@ function spawnDaemon() {
195
195
  const resolvedPath = daemonPath;
196
196
  process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
197
197
  `);
198
- const logPath = path3.join(path3.dirname(SOCKET_PATH), "exed.log");
198
+ const logPath = path4.join(path4.dirname(SOCKET_PATH), "exed.log");
199
199
  let stderrFd = "ignore";
200
200
  try {
201
201
  stderrFd = openSync(logPath, "a");
@@ -342,9 +342,9 @@ var init_exe_daemon_client = __esm({
342
342
  "src/lib/exe-daemon-client.ts"() {
343
343
  "use strict";
344
344
  init_config();
345
- SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path3.join(EXE_AI_DIR, "exed.sock");
346
- PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path3.join(EXE_AI_DIR, "exed.pid");
347
- SPAWN_LOCK_PATH = path3.join(EXE_AI_DIR, "exed-spawn.lock");
345
+ SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path4.join(EXE_AI_DIR, "exed.sock");
346
+ PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path4.join(EXE_AI_DIR, "exed.pid");
347
+ SPAWN_LOCK_PATH = path4.join(EXE_AI_DIR, "exed-spawn.lock");
348
348
  SPAWN_LOCK_STALE_MS = 3e4;
349
349
  CONNECT_TIMEOUT_MS = 15e3;
350
350
  REQUEST_TIMEOUT_MS = 3e4;
@@ -426,7 +426,7 @@ __export(db_daemon_client_exports, {
426
426
  createDaemonDbClient: () => createDaemonDbClient,
427
427
  initDaemonDbClient: () => initDaemonDbClient
428
428
  });
429
- function normalizeStatement(stmt) {
429
+ function normalizeStatement2(stmt) {
430
430
  if (typeof stmt === "string") {
431
431
  return { sql: stmt, args: [] };
432
432
  }
@@ -450,7 +450,7 @@ function createDaemonDbClient(fallbackClient) {
450
450
  if (!_useDaemon || !isClientConnected()) {
451
451
  return fallbackClient.execute(stmt);
452
452
  }
453
- const { sql, args } = normalizeStatement(stmt);
453
+ const { sql, args } = normalizeStatement2(stmt);
454
454
  const response = await sendDaemonRequest({
455
455
  type: "db-execute",
456
456
  sql,
@@ -475,7 +475,7 @@ function createDaemonDbClient(fallbackClient) {
475
475
  if (!_useDaemon || !isClientConnected()) {
476
476
  return fallbackClient.batch(stmts, mode);
477
477
  }
478
- const statements = stmts.map(normalizeStatement);
478
+ const statements = stmts.map(normalizeStatement2);
479
479
  const response = await sendDaemonRequest({
480
480
  type: "db-batch",
481
481
  statements,
@@ -637,14 +637,606 @@ function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
637
637
  return [];
638
638
  }
639
639
  }
640
+ var IDENTITY_DIR = path2.join(EXE_AI_DIR, "identity");
641
+
642
+ // src/lib/database-adapter.ts
643
+ import os3 from "os";
644
+ import path3 from "path";
645
+ import { createRequire } from "module";
646
+ import { pathToFileURL } from "url";
647
+ var VIEW_MAPPINGS = [
648
+ { view: "memories", source: "memory.memory_records" },
649
+ { view: "tasks", source: "memory.tasks" },
650
+ { view: "behaviors", source: "memory.behaviors" },
651
+ { view: "entities", source: "memory.entities" },
652
+ { view: "relationships", source: "memory.relationships" },
653
+ { view: "entity_memories", source: "memory.entity_memories" },
654
+ { view: "entity_aliases", source: "memory.entity_aliases" },
655
+ { view: "notifications", source: "memory.notifications" },
656
+ { view: "messages", source: "memory.messages" },
657
+ { view: "users", source: "wiki.users" },
658
+ { view: "workspaces", source: "wiki.workspaces" },
659
+ { view: "workspace_users", source: "wiki.workspace_users" },
660
+ { view: "documents", source: "wiki.workspace_documents" },
661
+ { view: "chats", source: "wiki.workspace_chats" }
662
+ ];
663
+ var UPSERT_KEYS = {
664
+ memories: ["id"],
665
+ tasks: ["id"],
666
+ behaviors: ["id"],
667
+ entities: ["id"],
668
+ relationships: ["id"],
669
+ entity_aliases: ["alias"],
670
+ notifications: ["id"],
671
+ messages: ["id"],
672
+ users: ["id"],
673
+ workspaces: ["id"],
674
+ workspace_users: ["id"],
675
+ documents: ["id"],
676
+ chats: ["id"]
677
+ };
678
+ var BOOLEAN_COLUMNS_BY_TABLE = {
679
+ memories: /* @__PURE__ */ new Set(["has_error", "draft"]),
680
+ behaviors: /* @__PURE__ */ new Set(["active"]),
681
+ notifications: /* @__PURE__ */ new Set(["read"]),
682
+ users: /* @__PURE__ */ new Set(["has_personal_memory"])
683
+ };
684
+ var BOOLEAN_COLUMN_NAMES = new Set(
685
+ Object.values(BOOLEAN_COLUMNS_BY_TABLE).flatMap((cols) => [...cols])
686
+ );
687
+ var IMMEDIATE_FALLBACK_PATTERNS = [
688
+ /\bPRAGMA\b/i,
689
+ /\bsqlite_master\b/i,
690
+ /(?:^|[.\s])(?:memories|conversations|entities)_fts\b/i,
691
+ /\bMATCH\b/i,
692
+ /\bvector_distance_cos\s*\(/i,
693
+ /\bjson_extract\s*\(/i,
694
+ /\bjulianday\s*\(/i,
695
+ /\bstrftime\s*\(/i,
696
+ /\blast_insert_rowid\s*\(/i
697
+ ];
698
+ var prismaClientPromise = null;
699
+ var compatibilityBootstrapPromise = null;
700
+ function quotedIdentifier(identifier) {
701
+ return `"${identifier.replace(/"/g, '""')}"`;
702
+ }
703
+ function unqualifiedTableName(name) {
704
+ const raw = name.trim().replace(/^"|"$/g, "");
705
+ const parts = raw.split(".");
706
+ return parts[parts.length - 1].replace(/^"|"$/g, "").toLowerCase();
707
+ }
708
+ function stripTrailingSemicolon(sql) {
709
+ return sql.trim().replace(/;+\s*$/u, "");
710
+ }
711
+ function appendClause(sql, clause) {
712
+ const trimmed = stripTrailingSemicolon(sql);
713
+ const returningMatch = /\sRETURNING\b[\s\S]*$/iu.exec(trimmed);
714
+ if (!returningMatch) {
715
+ return `${trimmed}${clause}`;
716
+ }
717
+ const idx = returningMatch.index;
718
+ return `${trimmed.slice(0, idx)}${clause}${trimmed.slice(idx)}`;
719
+ }
720
+ function normalizeStatement(stmt) {
721
+ if (typeof stmt === "string") {
722
+ return { kind: "positional", sql: stmt, args: [] };
723
+ }
724
+ const sql = stmt.sql;
725
+ if (Array.isArray(stmt.args) || stmt.args === void 0) {
726
+ return { kind: "positional", sql, args: stmt.args ?? [] };
727
+ }
728
+ return { kind: "named", sql, args: stmt.args };
729
+ }
730
+ function rewriteBooleanLiterals(sql) {
731
+ let out = sql;
732
+ for (const column of BOOLEAN_COLUMN_NAMES) {
733
+ const scoped = `((?:\\b[a-z_][a-z0-9_]*\\.)?${column})`;
734
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*0\\b`, "giu"), "$1 = FALSE");
735
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*1\\b`, "giu"), "$1 = TRUE");
736
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*0\\b`, "giu"), "$1 != FALSE");
737
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*1\\b`, "giu"), "$1 != TRUE");
738
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*0\\b`, "giu"), "$1 <> FALSE");
739
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*1\\b`, "giu"), "$1 <> TRUE");
740
+ }
741
+ return out;
742
+ }
743
+ function rewriteInsertOrIgnore(sql) {
744
+ if (!/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu.test(sql)) {
745
+ return sql;
746
+ }
747
+ const replaced = sql.replace(/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu, "INSERT INTO");
748
+ return /\bON\s+CONFLICT\b/iu.test(replaced) ? replaced : appendClause(replaced, " ON CONFLICT DO NOTHING");
749
+ }
750
+ function rewriteInsertOrReplace(sql) {
751
+ const match = /^\s*INSERT\s+OR\s+REPLACE\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)([\s\S]*)$/iu.exec(sql);
752
+ if (!match) {
753
+ return sql;
754
+ }
755
+ const rawTable = match[1];
756
+ const rawColumns = match[2];
757
+ const remainder = match[3];
758
+ const tableName = unqualifiedTableName(rawTable);
759
+ const conflictKeys = UPSERT_KEYS[tableName];
760
+ if (!conflictKeys?.length) {
761
+ return sql;
762
+ }
763
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
764
+ const updateColumns = columns.filter((col) => !conflictKeys.includes(col));
765
+ const conflictTarget = conflictKeys.map(quotedIdentifier).join(", ");
766
+ const updateClause = updateColumns.length === 0 ? " DO NOTHING" : ` DO UPDATE SET ${updateColumns.map((col) => `${quotedIdentifier(col)} = EXCLUDED.${quotedIdentifier(col)}`).join(", ")}`;
767
+ return `INSERT INTO ${rawTable} (${rawColumns})${appendClause(remainder, ` ON CONFLICT (${conflictTarget})${updateClause}`)}`;
768
+ }
769
+ function rewriteSql(sql) {
770
+ let out = sql;
771
+ out = out.replace(/\bdatetime\(\s*['"]now['"]\s*\)/giu, "CURRENT_TIMESTAMP");
772
+ out = out.replace(/\bvector32\s*\(\s*\?\s*\)/giu, "?");
773
+ out = rewriteBooleanLiterals(out);
774
+ out = rewriteInsertOrReplace(out);
775
+ out = rewriteInsertOrIgnore(out);
776
+ return stripTrailingSemicolon(out);
777
+ }
778
+ function toBoolean(value) {
779
+ if (value === null || value === void 0) return value;
780
+ if (typeof value === "boolean") return value;
781
+ if (typeof value === "number") return value !== 0;
782
+ if (typeof value === "bigint") return value !== 0n;
783
+ if (typeof value === "string") {
784
+ const normalized = value.trim().toLowerCase();
785
+ if (normalized === "0" || normalized === "false") return false;
786
+ if (normalized === "1" || normalized === "true") return true;
787
+ }
788
+ return Boolean(value);
789
+ }
790
+ function countQuestionMarks(sql, end) {
791
+ let count = 0;
792
+ let inSingle = false;
793
+ let inDouble = false;
794
+ let inLineComment = false;
795
+ let inBlockComment = false;
796
+ for (let i = 0; i < end; i++) {
797
+ const ch = sql[i];
798
+ const next = sql[i + 1];
799
+ if (inLineComment) {
800
+ if (ch === "\n") inLineComment = false;
801
+ continue;
802
+ }
803
+ if (inBlockComment) {
804
+ if (ch === "*" && next === "/") {
805
+ inBlockComment = false;
806
+ i += 1;
807
+ }
808
+ continue;
809
+ }
810
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
811
+ inLineComment = true;
812
+ i += 1;
813
+ continue;
814
+ }
815
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
816
+ inBlockComment = true;
817
+ i += 1;
818
+ continue;
819
+ }
820
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
821
+ inSingle = !inSingle;
822
+ continue;
823
+ }
824
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
825
+ inDouble = !inDouble;
826
+ continue;
827
+ }
828
+ if (!inSingle && !inDouble && ch === "?") {
829
+ count += 1;
830
+ }
831
+ }
832
+ return count;
833
+ }
834
+ function findBooleanPlaceholderIndexes(sql) {
835
+ const indexes = /* @__PURE__ */ new Set();
836
+ for (const column of BOOLEAN_COLUMN_NAMES) {
837
+ const pattern = new RegExp(`(?:\\b[a-z_][a-z0-9_]*\\.)?${column}\\s*=\\s*\\?`, "giu");
838
+ for (const match of sql.matchAll(pattern)) {
839
+ const matchText = match[0];
840
+ const qIndex = match.index + matchText.lastIndexOf("?");
841
+ indexes.add(countQuestionMarks(sql, qIndex + 1));
842
+ }
843
+ }
844
+ return indexes;
845
+ }
846
+ function coerceInsertBooleanArgs(sql, args) {
847
+ const match = /^\s*INSERT(?:\s+OR\s+(?:IGNORE|REPLACE))?\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)/iu.exec(sql);
848
+ if (!match) return;
849
+ const rawTable = match[1];
850
+ const rawColumns = match[2];
851
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
852
+ if (!boolColumns?.size) return;
853
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
854
+ for (const [index, column] of columns.entries()) {
855
+ if (boolColumns.has(column) && index < args.length) {
856
+ args[index] = toBoolean(args[index]);
857
+ }
858
+ }
859
+ }
860
+ function coerceUpdateBooleanArgs(sql, args) {
861
+ const match = /^\s*UPDATE\s+([A-Za-z0-9_."]+)\s+SET\s+([\s\S]+?)(?:\s+WHERE\b|$)/iu.exec(sql);
862
+ if (!match) return;
863
+ const rawTable = match[1];
864
+ const setClause = match[2];
865
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
866
+ if (!boolColumns?.size) return;
867
+ const assignments = setClause.split(",");
868
+ let placeholderIndex = 0;
869
+ for (const assignment of assignments) {
870
+ if (!assignment.includes("?")) continue;
871
+ placeholderIndex += 1;
872
+ const colMatch = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*\?/iu.exec(assignment);
873
+ if (colMatch && boolColumns.has(colMatch[1])) {
874
+ args[placeholderIndex - 1] = toBoolean(args[placeholderIndex - 1]);
875
+ }
876
+ }
877
+ }
878
+ function coerceBooleanArgs(sql, args) {
879
+ const nextArgs = [...args];
880
+ coerceInsertBooleanArgs(sql, nextArgs);
881
+ coerceUpdateBooleanArgs(sql, nextArgs);
882
+ const placeholderIndexes = findBooleanPlaceholderIndexes(sql);
883
+ for (const index of placeholderIndexes) {
884
+ if (index > 0 && index <= nextArgs.length) {
885
+ nextArgs[index - 1] = toBoolean(nextArgs[index - 1]);
886
+ }
887
+ }
888
+ return nextArgs;
889
+ }
890
+ function convertQuestionMarksToDollarParams(sql) {
891
+ let out = "";
892
+ let placeholder = 0;
893
+ let inSingle = false;
894
+ let inDouble = false;
895
+ let inLineComment = false;
896
+ let inBlockComment = false;
897
+ for (let i = 0; i < sql.length; i++) {
898
+ const ch = sql[i];
899
+ const next = sql[i + 1];
900
+ if (inLineComment) {
901
+ out += ch;
902
+ if (ch === "\n") inLineComment = false;
903
+ continue;
904
+ }
905
+ if (inBlockComment) {
906
+ out += ch;
907
+ if (ch === "*" && next === "/") {
908
+ out += next;
909
+ inBlockComment = false;
910
+ i += 1;
911
+ }
912
+ continue;
913
+ }
914
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
915
+ out += ch + next;
916
+ inLineComment = true;
917
+ i += 1;
918
+ continue;
919
+ }
920
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
921
+ out += ch + next;
922
+ inBlockComment = true;
923
+ i += 1;
924
+ continue;
925
+ }
926
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
927
+ inSingle = !inSingle;
928
+ out += ch;
929
+ continue;
930
+ }
931
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
932
+ inDouble = !inDouble;
933
+ out += ch;
934
+ continue;
935
+ }
936
+ if (!inSingle && !inDouble && ch === "?") {
937
+ placeholder += 1;
938
+ out += `$${placeholder}`;
939
+ continue;
940
+ }
941
+ out += ch;
942
+ }
943
+ return out;
944
+ }
945
+ function translateStatementForPostgres(stmt) {
946
+ const normalized = normalizeStatement(stmt);
947
+ if (normalized.kind === "named") {
948
+ throw new Error("Named SQL parameters are not supported by the Prisma adapter.");
949
+ }
950
+ const rewrittenSql = rewriteSql(normalized.sql);
951
+ const coercedArgs = coerceBooleanArgs(rewrittenSql, normalized.args);
952
+ return {
953
+ sql: convertQuestionMarksToDollarParams(rewrittenSql),
954
+ args: coercedArgs
955
+ };
956
+ }
957
+ function shouldBypassPostgres(stmt) {
958
+ const normalized = normalizeStatement(stmt);
959
+ if (normalized.kind === "named") {
960
+ return true;
961
+ }
962
+ return IMMEDIATE_FALLBACK_PATTERNS.some((pattern) => pattern.test(normalized.sql));
963
+ }
964
+ function shouldFallbackOnError(error) {
965
+ const message = error instanceof Error ? error.message : String(error);
966
+ return /42P01|42883|42601|does not exist|syntax error|not supported|Named SQL parameters are not supported/iu.test(message);
967
+ }
968
+ function isReadQuery(sql) {
969
+ const trimmed = sql.trimStart();
970
+ return /^(SELECT|WITH|SHOW|EXPLAIN|VALUES)\b/iu.test(trimmed) || /\bRETURNING\b/iu.test(trimmed);
971
+ }
972
+ function buildRow(row, columns) {
973
+ const values = columns.map((column) => row[column]);
974
+ return Object.assign(values, row);
975
+ }
976
+ function buildResultSet(rows, rowsAffected = 0) {
977
+ const columns = rows[0] ? Object.keys(rows[0]) : [];
978
+ const resultRows = rows.map((row) => buildRow(row, columns));
979
+ return {
980
+ columns,
981
+ columnTypes: columns.map(() => ""),
982
+ rows: resultRows,
983
+ rowsAffected,
984
+ lastInsertRowid: void 0,
985
+ toJSON() {
986
+ return {
987
+ columns,
988
+ columnTypes: columns.map(() => ""),
989
+ rows,
990
+ rowsAffected,
991
+ lastInsertRowid: void 0
992
+ };
993
+ }
994
+ };
995
+ }
996
+ async function loadPrismaClient() {
997
+ if (!prismaClientPromise) {
998
+ prismaClientPromise = (async () => {
999
+ const explicitPath = process.env.EXE_OS_PRISMA_CLIENT_PATH;
1000
+ if (explicitPath) {
1001
+ const module2 = await import(pathToFileURL(explicitPath).href);
1002
+ const PrismaClient2 = module2.PrismaClient ?? module2.default?.PrismaClient;
1003
+ if (!PrismaClient2) {
1004
+ throw new Error(`No PrismaClient export found at ${explicitPath}`);
1005
+ }
1006
+ return new PrismaClient2();
1007
+ }
1008
+ const exeDbRoot = process.env.EXE_DB_ROOT ?? path3.join(os3.homedir(), "exe-db");
1009
+ const requireFromExeDb = createRequire(path3.join(exeDbRoot, "package.json"));
1010
+ const prismaEntry = requireFromExeDb.resolve("@prisma/client");
1011
+ const module = await import(pathToFileURL(prismaEntry).href);
1012
+ const PrismaClient = module.PrismaClient ?? module.default?.PrismaClient;
1013
+ if (!PrismaClient) {
1014
+ throw new Error(`No PrismaClient export found in ${prismaEntry}`);
1015
+ }
1016
+ return new PrismaClient();
1017
+ })();
1018
+ }
1019
+ return prismaClientPromise;
1020
+ }
1021
+ async function ensureCompatibilityViews(prisma) {
1022
+ if (!compatibilityBootstrapPromise) {
1023
+ compatibilityBootstrapPromise = (async () => {
1024
+ for (const mapping of VIEW_MAPPINGS) {
1025
+ const relation = mapping.source.replace(/"/g, "");
1026
+ const rows = await prisma.$queryRawUnsafe(
1027
+ "SELECT to_regclass($1) AS regclass",
1028
+ relation
1029
+ );
1030
+ if (!rows[0]?.regclass) {
1031
+ continue;
1032
+ }
1033
+ await prisma.$executeRawUnsafe(
1034
+ `CREATE OR REPLACE VIEW public.${quotedIdentifier(mapping.view)} AS SELECT * FROM ${mapping.source}`
1035
+ );
1036
+ }
1037
+ })();
1038
+ }
1039
+ return compatibilityBootstrapPromise;
1040
+ }
1041
+ async function executeOnPrisma(executor, stmt) {
1042
+ const translated = translateStatementForPostgres(stmt);
1043
+ if (isReadQuery(translated.sql)) {
1044
+ const rows = await executor.$queryRawUnsafe(
1045
+ translated.sql,
1046
+ ...translated.args
1047
+ );
1048
+ return buildResultSet(rows, /\bRETURNING\b/iu.test(translated.sql) ? rows.length : 0);
1049
+ }
1050
+ const rowsAffected = await executor.$executeRawUnsafe(translated.sql, ...translated.args);
1051
+ return buildResultSet([], rowsAffected);
1052
+ }
1053
+ function splitSqlStatements(sql) {
1054
+ const parts = [];
1055
+ let current = "";
1056
+ let inSingle = false;
1057
+ let inDouble = false;
1058
+ let inLineComment = false;
1059
+ let inBlockComment = false;
1060
+ for (let i = 0; i < sql.length; i++) {
1061
+ const ch = sql[i];
1062
+ const next = sql[i + 1];
1063
+ if (inLineComment) {
1064
+ current += ch;
1065
+ if (ch === "\n") inLineComment = false;
1066
+ continue;
1067
+ }
1068
+ if (inBlockComment) {
1069
+ current += ch;
1070
+ if (ch === "*" && next === "/") {
1071
+ current += next;
1072
+ inBlockComment = false;
1073
+ i += 1;
1074
+ }
1075
+ continue;
1076
+ }
1077
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
1078
+ current += ch + next;
1079
+ inLineComment = true;
1080
+ i += 1;
1081
+ continue;
1082
+ }
1083
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
1084
+ current += ch + next;
1085
+ inBlockComment = true;
1086
+ i += 1;
1087
+ continue;
1088
+ }
1089
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
1090
+ inSingle = !inSingle;
1091
+ current += ch;
1092
+ continue;
1093
+ }
1094
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
1095
+ inDouble = !inDouble;
1096
+ current += ch;
1097
+ continue;
1098
+ }
1099
+ if (!inSingle && !inDouble && ch === ";") {
1100
+ if (current.trim()) {
1101
+ parts.push(current.trim());
1102
+ }
1103
+ current = "";
1104
+ continue;
1105
+ }
1106
+ current += ch;
1107
+ }
1108
+ if (current.trim()) {
1109
+ parts.push(current.trim());
1110
+ }
1111
+ return parts;
1112
+ }
1113
+ async function createPrismaDbAdapter(fallbackClient) {
1114
+ const prisma = await loadPrismaClient();
1115
+ await ensureCompatibilityViews(prisma);
1116
+ let closed = false;
1117
+ let adapter;
1118
+ const fallbackExecute = async (stmt, error) => {
1119
+ if (!fallbackClient) {
1120
+ if (error) throw error;
1121
+ throw new Error("No fallback SQLite client is available for this Prisma-routed query.");
1122
+ }
1123
+ if (error) {
1124
+ process.stderr.write(
1125
+ `[database-adapter] Falling back to SQLite: ${error instanceof Error ? error.message : String(error)}
1126
+ `
1127
+ );
1128
+ }
1129
+ return fallbackClient.execute(stmt);
1130
+ };
1131
+ adapter = {
1132
+ async execute(stmt) {
1133
+ if (shouldBypassPostgres(stmt)) {
1134
+ return fallbackExecute(stmt);
1135
+ }
1136
+ try {
1137
+ return await executeOnPrisma(prisma, stmt);
1138
+ } catch (error) {
1139
+ if (shouldFallbackOnError(error)) {
1140
+ return fallbackExecute(stmt, error);
1141
+ }
1142
+ throw error;
1143
+ }
1144
+ },
1145
+ async batch(stmts, mode) {
1146
+ if (stmts.some((stmt) => shouldBypassPostgres(stmt))) {
1147
+ if (!fallbackClient) {
1148
+ throw new Error("Cannot batch unsupported SQLite-only statements without a fallback client.");
1149
+ }
1150
+ return fallbackClient.batch(stmts, mode);
1151
+ }
1152
+ try {
1153
+ if (prisma.$transaction) {
1154
+ return await prisma.$transaction(async (tx) => {
1155
+ const results2 = [];
1156
+ for (const stmt of stmts) {
1157
+ results2.push(await executeOnPrisma(tx, stmt));
1158
+ }
1159
+ return results2;
1160
+ });
1161
+ }
1162
+ const results = [];
1163
+ for (const stmt of stmts) {
1164
+ results.push(await executeOnPrisma(prisma, stmt));
1165
+ }
1166
+ return results;
1167
+ } catch (error) {
1168
+ if (fallbackClient && shouldFallbackOnError(error)) {
1169
+ process.stderr.write(
1170
+ `[database-adapter] Falling back batch to SQLite: ${error instanceof Error ? error.message : String(error)}
1171
+ `
1172
+ );
1173
+ return fallbackClient.batch(stmts, mode);
1174
+ }
1175
+ throw error;
1176
+ }
1177
+ },
1178
+ async migrate(stmts) {
1179
+ if (fallbackClient) {
1180
+ return fallbackClient.migrate(stmts);
1181
+ }
1182
+ return adapter.batch(stmts, "deferred");
1183
+ },
1184
+ async transaction(mode) {
1185
+ if (!fallbackClient) {
1186
+ throw new Error("Interactive transactions are only supported on the SQLite fallback client.");
1187
+ }
1188
+ return fallbackClient.transaction(mode);
1189
+ },
1190
+ async executeMultiple(sql) {
1191
+ if (fallbackClient && shouldBypassPostgres(sql)) {
1192
+ return fallbackClient.executeMultiple(sql);
1193
+ }
1194
+ for (const statement of splitSqlStatements(sql)) {
1195
+ await adapter.execute(statement);
1196
+ }
1197
+ },
1198
+ async sync() {
1199
+ if (fallbackClient) {
1200
+ return fallbackClient.sync();
1201
+ }
1202
+ return { frame_no: 0, frames_synced: 0 };
1203
+ },
1204
+ close() {
1205
+ closed = true;
1206
+ prismaClientPromise = null;
1207
+ compatibilityBootstrapPromise = null;
1208
+ void prisma.$disconnect?.();
1209
+ },
1210
+ get closed() {
1211
+ return closed;
1212
+ },
1213
+ get protocol() {
1214
+ return "prisma-postgres";
1215
+ }
1216
+ };
1217
+ return adapter;
1218
+ }
640
1219
 
641
1220
  // src/lib/database.ts
642
1221
  var _client = null;
643
1222
  var _resilientClient = null;
644
1223
  var _walCheckpointTimer = null;
645
1224
  var _daemonClient = null;
1225
+ var _adapterClient = null;
646
1226
  var initTurso = initDatabase;
647
1227
  async function initDatabase(config) {
1228
+ if (_walCheckpointTimer) {
1229
+ clearInterval(_walCheckpointTimer);
1230
+ _walCheckpointTimer = null;
1231
+ }
1232
+ if (_daemonClient) {
1233
+ _daemonClient.close();
1234
+ _daemonClient = null;
1235
+ }
1236
+ if (_adapterClient && _adapterClient !== _resilientClient) {
1237
+ _adapterClient.close();
1238
+ }
1239
+ _adapterClient = null;
648
1240
  if (_client) {
649
1241
  _client.close();
650
1242
  _client = null;
@@ -658,6 +1250,7 @@ async function initDatabase(config) {
658
1250
  }
659
1251
  _client = createClient(opts);
660
1252
  _resilientClient = wrapWithRetry(_client);
1253
+ _adapterClient = _resilientClient;
661
1254
  _client.execute("PRAGMA busy_timeout = 30000").catch(() => {
662
1255
  });
663
1256
  _client.execute("PRAGMA journal_mode = WAL").catch(() => {
@@ -668,14 +1261,20 @@ async function initDatabase(config) {
668
1261
  });
669
1262
  }, 3e4);
670
1263
  _walCheckpointTimer.unref();
1264
+ if (process.env.DATABASE_URL) {
1265
+ _adapterClient = await createPrismaDbAdapter(_resilientClient);
1266
+ }
671
1267
  }
672
1268
  function isInitialized() {
673
- return _client !== null;
1269
+ return _adapterClient !== null || _client !== null;
674
1270
  }
675
1271
  function getClient() {
676
- if (!_resilientClient) {
1272
+ if (!_adapterClient) {
677
1273
  throw new Error("Database client not initialized. Call initDatabase() first.");
678
1274
  }
1275
+ if (process.env.DATABASE_URL) {
1276
+ return _adapterClient;
1277
+ }
679
1278
  if (process.env.EXE_IS_DAEMON === "1") {
680
1279
  return _resilientClient;
681
1280
  }
@@ -685,6 +1284,7 @@ function getClient() {
685
1284
  return _resilientClient;
686
1285
  }
687
1286
  async function initDaemonClient() {
1287
+ if (process.env.DATABASE_URL) return;
688
1288
  if (process.env.EXE_IS_DAEMON === "1") return;
689
1289
  if (!_resilientClient) return;
690
1290
  try {
@@ -1630,10 +2230,18 @@ async function ensureSchema() {
1630
2230
  }
1631
2231
  var disposeTurso = disposeDatabase;
1632
2232
  async function disposeDatabase() {
2233
+ if (_walCheckpointTimer) {
2234
+ clearInterval(_walCheckpointTimer);
2235
+ _walCheckpointTimer = null;
2236
+ }
1633
2237
  if (_daemonClient) {
1634
2238
  _daemonClient.close();
1635
2239
  _daemonClient = null;
1636
2240
  }
2241
+ if (_adapterClient && _adapterClient !== _resilientClient) {
2242
+ _adapterClient.close();
2243
+ }
2244
+ _adapterClient = null;
1637
2245
  if (_client) {
1638
2246
  _client.close();
1639
2247
  _client = null;