@askexenow/exe-os 0.9.16 → 0.9.18

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 (97) hide show
  1. package/dist/bin/backfill-conversations.js +1242 -909
  2. package/dist/bin/backfill-responses.js +1245 -912
  3. package/dist/bin/backfill-vectors.js +1244 -906
  4. package/dist/bin/cleanup-stale-review-tasks.js +1870 -417
  5. package/dist/bin/cli.js +217 -107
  6. package/dist/bin/exe-agent-config.js +2 -2
  7. package/dist/bin/exe-agent.js +62 -0
  8. package/dist/bin/exe-assign.js +346 -10
  9. package/dist/bin/exe-boot.js +387 -32
  10. package/dist/bin/exe-call.js +72 -2
  11. package/dist/bin/exe-cloud.js +8 -0
  12. package/dist/bin/exe-dispatch.js +1821 -225
  13. package/dist/bin/exe-doctor.js +720 -52
  14. package/dist/bin/exe-export-behaviors.js +1429 -148
  15. package/dist/bin/exe-forget.js +1408 -34
  16. package/dist/bin/exe-gateway.js +1629 -1295
  17. package/dist/bin/exe-heartbeat.js +1899 -448
  18. package/dist/bin/exe-kill.js +1624 -346
  19. package/dist/bin/exe-launch-agent.js +726 -90
  20. package/dist/bin/exe-link.js +27 -8
  21. package/dist/bin/exe-new-employee.js +75 -9
  22. package/dist/bin/exe-pending-messages.js +2769 -1316
  23. package/dist/bin/exe-pending-notifications.js +2829 -1376
  24. package/dist/bin/exe-pending-reviews.js +2847 -1392
  25. package/dist/bin/exe-rename.js +89 -8
  26. package/dist/bin/exe-review.js +1494 -312
  27. package/dist/bin/exe-search.js +1608 -1300
  28. package/dist/bin/exe-session-cleanup.js +194 -91
  29. package/dist/bin/exe-settings.js +10 -2
  30. package/dist/bin/exe-start-codex.js +769 -120
  31. package/dist/bin/exe-start-opencode.js +763 -108
  32. package/dist/bin/exe-status.js +1887 -434
  33. package/dist/bin/exe-team.js +1782 -324
  34. package/dist/bin/git-sweep.js +408 -33
  35. package/dist/bin/graph-backfill.js +681 -27
  36. package/dist/bin/graph-export.js +1419 -141
  37. package/dist/bin/install.js +4 -8
  38. package/dist/bin/intercom-check.js +8641 -0
  39. package/dist/bin/scan-tasks.js +553 -38
  40. package/dist/bin/setup.js +82 -10
  41. package/dist/bin/shard-migrate.js +682 -28
  42. package/dist/gateway/index.js +1629 -1295
  43. package/dist/hooks/bug-report-worker.js +1136 -183
  44. package/dist/hooks/codex-stop-task-finalizer.js +1060 -107
  45. package/dist/hooks/commit-complete.js +408 -33
  46. package/dist/hooks/error-recall.js +1608 -1300
  47. package/dist/hooks/ingest-worker.js +250 -7966
  48. package/dist/hooks/ingest.js +707 -119
  49. package/dist/hooks/instructions-loaded.js +383 -20
  50. package/dist/hooks/notification.js +383 -20
  51. package/dist/hooks/post-compact.js +384 -21
  52. package/dist/hooks/{response-ingest-worker.js → post-tool-combined.js} +4157 -1716
  53. package/dist/hooks/pre-compact.js +486 -45
  54. package/dist/hooks/pre-tool-use.js +385 -22
  55. package/dist/hooks/prompt-submit.js +291 -96
  56. package/dist/hooks/session-end.js +490 -48
  57. package/dist/hooks/session-start.js +236 -22
  58. package/dist/hooks/stop.js +192 -50
  59. package/dist/hooks/subagent-stop.js +95 -18
  60. package/dist/hooks/summary-worker.js +205 -361
  61. package/dist/index.js +221 -105
  62. package/dist/lib/agent-config.js +2 -2
  63. package/dist/lib/cloud-sync.js +27 -8
  64. package/dist/lib/consolidation.js +437 -41
  65. package/dist/lib/database.js +20 -8
  66. package/dist/lib/db-daemon-client.js +2 -2
  67. package/dist/lib/db.js +20 -8
  68. package/dist/lib/device-registry.js +27 -8
  69. package/dist/lib/employee-templates.js +62 -0
  70. package/dist/lib/employees.js +2 -2
  71. package/dist/lib/exe-daemon.js +6703 -6259
  72. package/dist/lib/hybrid-search.js +1608 -1300
  73. package/dist/lib/identity.js +1 -1
  74. package/dist/lib/messaging.js +11 -3
  75. package/dist/lib/reminders.js +1 -1
  76. package/dist/lib/schedules.js +718 -26
  77. package/dist/lib/session-registry.js +11 -0
  78. package/dist/lib/skill-learning.js +639 -9
  79. package/dist/lib/store.js +676 -27
  80. package/dist/lib/tasks.js +665 -27
  81. package/dist/lib/tmux-routing.js +732 -94
  82. package/dist/lib/token-spend.js +1 -1
  83. package/dist/mcp/server.js +856 -383
  84. package/dist/mcp/tools/complete-reminder.js +1 -1
  85. package/dist/mcp/tools/create-reminder.js +1 -1
  86. package/dist/mcp/tools/create-task.js +616 -46
  87. package/dist/mcp/tools/deactivate-behavior.js +9 -1
  88. package/dist/mcp/tools/list-reminders.js +1 -1
  89. package/dist/mcp/tools/list-tasks.js +10 -2
  90. package/dist/mcp/tools/send-message.js +11 -3
  91. package/dist/mcp/tools/update-task.js +677 -39
  92. package/dist/runtime/index.js +425 -37
  93. package/dist/tui/App.js +365 -34
  94. package/package.json +5 -2
  95. package/src/commands/exe/intercom.md +6 -17
  96. package/dist/bin/wiki-sync.js +0 -2991
  97. package/dist/hooks/prompt-ingest-worker.js +0 -3979
@@ -1,5 +1,11 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
+ }) : x)(function(x) {
6
+ if (typeof require !== "undefined") return require.apply(this, arguments);
7
+ throw Error('Dynamic require of "' + x + '" is not supported');
8
+ });
3
9
  var __esm = (fn, res) => function __init() {
4
10
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
11
  };
@@ -57,9 +63,9 @@ var MAX_RETRIES, BASE_DELAY_MS, MAX_JITTER_MS;
57
63
  var init_db_retry = __esm({
58
64
  "src/lib/db-retry.ts"() {
59
65
  "use strict";
60
- MAX_RETRIES = 3;
61
- BASE_DELAY_MS = 200;
62
- MAX_JITTER_MS = 300;
66
+ MAX_RETRIES = 5;
67
+ BASE_DELAY_MS = 250;
68
+ MAX_JITTER_MS = 400;
63
69
  }
64
70
  });
65
71
 
@@ -73,12 +79,25 @@ async function ensurePrivateDir(dirPath) {
73
79
  } catch {
74
80
  }
75
81
  }
82
+ function ensurePrivateDirSync(dirPath) {
83
+ mkdirSync(dirPath, { recursive: true, mode: PRIVATE_DIR_MODE });
84
+ try {
85
+ chmodSync(dirPath, PRIVATE_DIR_MODE);
86
+ } catch {
87
+ }
88
+ }
76
89
  async function enforcePrivateFile(filePath) {
77
90
  try {
78
91
  await chmod(filePath, PRIVATE_FILE_MODE);
79
92
  } catch {
80
93
  }
81
94
  }
95
+ function enforcePrivateFileSync(filePath) {
96
+ try {
97
+ if (existsSync(filePath)) chmodSync(filePath, PRIVATE_FILE_MODE);
98
+ } catch {
99
+ }
100
+ }
82
101
  var PRIVATE_DIR_MODE, PRIVATE_FILE_MODE;
83
102
  var init_secure_files = __esm({
84
103
  "src/lib/secure-files.ts"() {
@@ -895,7 +914,547 @@ var init_database_adapter = __esm({
895
914
  }
896
915
  });
897
916
 
917
+ // src/types/memory.ts
918
+ var EMBEDDING_DIM;
919
+ var init_memory = __esm({
920
+ "src/types/memory.ts"() {
921
+ "use strict";
922
+ EMBEDDING_DIM = 1024;
923
+ }
924
+ });
925
+
926
+ // src/lib/daemon-auth.ts
927
+ import crypto from "crypto";
928
+ import path4 from "path";
929
+ import { existsSync as existsSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
930
+ function normalizeToken(token) {
931
+ if (!token) return null;
932
+ const trimmed = token.trim();
933
+ return trimmed.length > 0 ? trimmed : null;
934
+ }
935
+ function readDaemonToken() {
936
+ try {
937
+ if (!existsSync4(DAEMON_TOKEN_PATH)) return null;
938
+ return normalizeToken(readFileSync3(DAEMON_TOKEN_PATH, "utf8"));
939
+ } catch {
940
+ return null;
941
+ }
942
+ }
943
+ function ensureDaemonToken(seed) {
944
+ const existing = readDaemonToken();
945
+ if (existing) return existing;
946
+ const token = normalizeToken(seed) ?? crypto.randomBytes(32).toString("hex");
947
+ ensurePrivateDirSync(EXE_AI_DIR);
948
+ writeFileSync2(DAEMON_TOKEN_PATH, `${token}
949
+ `, "utf8");
950
+ enforcePrivateFileSync(DAEMON_TOKEN_PATH);
951
+ return token;
952
+ }
953
+ var DAEMON_TOKEN_PATH;
954
+ var init_daemon_auth = __esm({
955
+ "src/lib/daemon-auth.ts"() {
956
+ "use strict";
957
+ init_config();
958
+ init_secure_files();
959
+ DAEMON_TOKEN_PATH = path4.join(EXE_AI_DIR, "exed.token");
960
+ }
961
+ });
962
+
963
+ // src/lib/exe-daemon-client.ts
964
+ import net from "net";
965
+ import os4 from "os";
966
+ import { spawn } from "child_process";
967
+ import { randomUUID } from "crypto";
968
+ import { existsSync as existsSync5, unlinkSync as unlinkSync2, readFileSync as readFileSync4, openSync, closeSync, statSync } from "fs";
969
+ import path5 from "path";
970
+ import { fileURLToPath } from "url";
971
+ function handleData(chunk) {
972
+ _buffer += chunk.toString();
973
+ if (_buffer.length > MAX_BUFFER) {
974
+ _buffer = "";
975
+ return;
976
+ }
977
+ let newlineIdx;
978
+ while ((newlineIdx = _buffer.indexOf("\n")) !== -1) {
979
+ const line = _buffer.slice(0, newlineIdx).trim();
980
+ _buffer = _buffer.slice(newlineIdx + 1);
981
+ if (!line) continue;
982
+ try {
983
+ const response = JSON.parse(line);
984
+ const id = response.id;
985
+ if (!id) continue;
986
+ const entry = _pending.get(id);
987
+ if (entry) {
988
+ clearTimeout(entry.timer);
989
+ _pending.delete(id);
990
+ entry.resolve(response);
991
+ }
992
+ } catch {
993
+ }
994
+ }
995
+ }
996
+ function cleanupStaleFiles() {
997
+ if (existsSync5(PID_PATH)) {
998
+ try {
999
+ const pid = parseInt(readFileSync4(PID_PATH, "utf8").trim(), 10);
1000
+ if (pid > 0) {
1001
+ try {
1002
+ process.kill(pid, 0);
1003
+ return;
1004
+ } catch {
1005
+ }
1006
+ }
1007
+ } catch {
1008
+ }
1009
+ try {
1010
+ unlinkSync2(PID_PATH);
1011
+ } catch {
1012
+ }
1013
+ try {
1014
+ unlinkSync2(SOCKET_PATH);
1015
+ } catch {
1016
+ }
1017
+ }
1018
+ }
1019
+ function findPackageRoot() {
1020
+ let dir = path5.dirname(fileURLToPath(import.meta.url));
1021
+ const { root } = path5.parse(dir);
1022
+ while (dir !== root) {
1023
+ if (existsSync5(path5.join(dir, "package.json"))) return dir;
1024
+ dir = path5.dirname(dir);
1025
+ }
1026
+ return null;
1027
+ }
1028
+ function getAvailableMemoryGB() {
1029
+ if (process.platform === "darwin") {
1030
+ try {
1031
+ const { execSync: execSync3 } = __require("child_process");
1032
+ const vmstat = execSync3("vm_stat", { encoding: "utf8" });
1033
+ const pageSize = 16384;
1034
+ const pageSizeMatch = vmstat.match(/page size of (\d+) bytes/);
1035
+ const actualPageSize = pageSizeMatch ? parseInt(pageSizeMatch[1], 10) : pageSize;
1036
+ const free = vmstat.match(/Pages free:\s+(\d+)/);
1037
+ const inactive = vmstat.match(/Pages inactive:\s+(\d+)/);
1038
+ const speculative = vmstat.match(/Pages speculative:\s+(\d+)/);
1039
+ const freePages = free ? parseInt(free[1], 10) : 0;
1040
+ const inactivePages = inactive ? parseInt(inactive[1], 10) : 0;
1041
+ const speculativePages = speculative ? parseInt(speculative[1], 10) : 0;
1042
+ return (freePages + inactivePages + speculativePages) * actualPageSize / (1024 * 1024 * 1024);
1043
+ } catch {
1044
+ return os4.freemem() / (1024 * 1024 * 1024);
1045
+ }
1046
+ }
1047
+ return os4.freemem() / (1024 * 1024 * 1024);
1048
+ }
1049
+ function spawnDaemon() {
1050
+ const freeGB = getAvailableMemoryGB();
1051
+ const totalGB = os4.totalmem() / (1024 * 1024 * 1024);
1052
+ if (totalGB <= 8) {
1053
+ process.stderr.write(
1054
+ `[exed-client] SKIP: ${totalGB.toFixed(0)}GB system \u2014 embedding daemon disabled. Using keyword search only. Minimum 16GB recommended for vector search.
1055
+ `
1056
+ );
1057
+ return;
1058
+ }
1059
+ if (totalGB <= 16 && freeGB < 2) {
1060
+ process.stderr.write(
1061
+ `[exed-client] SKIP: low memory (${freeGB.toFixed(1)}GB available / ${totalGB.toFixed(0)}GB total). Embedding daemon not started \u2014 using keyword search only.
1062
+ `
1063
+ );
1064
+ return;
1065
+ }
1066
+ const pkgRoot = findPackageRoot();
1067
+ if (!pkgRoot) {
1068
+ process.stderr.write("[exed-client] WARN: cannot find package root\n");
1069
+ return;
1070
+ }
1071
+ const daemonPath = path5.join(pkgRoot, "dist", "lib", "exe-daemon.js");
1072
+ if (!existsSync5(daemonPath)) {
1073
+ process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
1074
+ `);
1075
+ return;
1076
+ }
1077
+ const resolvedPath = daemonPath;
1078
+ const daemonToken = ensureDaemonToken(process.env[DAEMON_TOKEN_ENV] ?? null);
1079
+ process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
1080
+ `);
1081
+ const logPath = path5.join(path5.dirname(SOCKET_PATH), "exed.log");
1082
+ let stderrFd = "ignore";
1083
+ try {
1084
+ stderrFd = openSync(logPath, "a");
1085
+ } catch {
1086
+ }
1087
+ const heapCapMB = totalGB <= 8 ? 256 : 512;
1088
+ const nodeArgs = [`--max-old-space-size=${heapCapMB}`, resolvedPath];
1089
+ const child = spawn(process.execPath, nodeArgs, {
1090
+ detached: true,
1091
+ stdio: ["ignore", "ignore", stderrFd],
1092
+ env: {
1093
+ ...process.env,
1094
+ TMUX: void 0,
1095
+ // Daemon is global — must not inherit session scope
1096
+ TMUX_PANE: void 0,
1097
+ // Prevents resolveExeSession() from scoping to one session
1098
+ EXE_DAEMON_SOCK: SOCKET_PATH,
1099
+ EXE_DAEMON_PID: PID_PATH,
1100
+ [DAEMON_TOKEN_ENV]: daemonToken
1101
+ }
1102
+ });
1103
+ child.unref();
1104
+ if (typeof stderrFd === "number") {
1105
+ try {
1106
+ closeSync(stderrFd);
1107
+ } catch {
1108
+ }
1109
+ }
1110
+ }
1111
+ function acquireSpawnLock() {
1112
+ try {
1113
+ const fd = openSync(SPAWN_LOCK_PATH, "wx");
1114
+ closeSync(fd);
1115
+ return true;
1116
+ } catch {
1117
+ try {
1118
+ const stat = statSync(SPAWN_LOCK_PATH);
1119
+ if (Date.now() - stat.mtimeMs > SPAWN_LOCK_STALE_MS) {
1120
+ try {
1121
+ unlinkSync2(SPAWN_LOCK_PATH);
1122
+ } catch {
1123
+ }
1124
+ try {
1125
+ const fd = openSync(SPAWN_LOCK_PATH, "wx");
1126
+ closeSync(fd);
1127
+ return true;
1128
+ } catch {
1129
+ }
1130
+ }
1131
+ } catch {
1132
+ }
1133
+ return false;
1134
+ }
1135
+ }
1136
+ function releaseSpawnLock() {
1137
+ try {
1138
+ unlinkSync2(SPAWN_LOCK_PATH);
1139
+ } catch {
1140
+ }
1141
+ }
1142
+ function connectToSocket() {
1143
+ return new Promise((resolve) => {
1144
+ if (_socket && _connected) {
1145
+ resolve(true);
1146
+ return;
1147
+ }
1148
+ const socket = net.createConnection({ path: SOCKET_PATH });
1149
+ const connectTimeout = setTimeout(() => {
1150
+ socket.destroy();
1151
+ resolve(false);
1152
+ }, 2e3);
1153
+ socket.on("connect", () => {
1154
+ clearTimeout(connectTimeout);
1155
+ _socket = socket;
1156
+ _connected = true;
1157
+ _buffer = "";
1158
+ socket.on("data", handleData);
1159
+ socket.on("close", () => {
1160
+ _connected = false;
1161
+ _socket = null;
1162
+ for (const [id, entry] of _pending) {
1163
+ clearTimeout(entry.timer);
1164
+ _pending.delete(id);
1165
+ entry.resolve({ error: "Connection closed" });
1166
+ }
1167
+ });
1168
+ socket.on("error", () => {
1169
+ _connected = false;
1170
+ _socket = null;
1171
+ });
1172
+ resolve(true);
1173
+ });
1174
+ socket.on("error", () => {
1175
+ clearTimeout(connectTimeout);
1176
+ resolve(false);
1177
+ });
1178
+ });
1179
+ }
1180
+ async function connectEmbedDaemon() {
1181
+ if (_socket && _connected) return true;
1182
+ if (await connectToSocket()) return true;
1183
+ if (acquireSpawnLock()) {
1184
+ try {
1185
+ cleanupStaleFiles();
1186
+ spawnDaemon();
1187
+ } finally {
1188
+ releaseSpawnLock();
1189
+ }
1190
+ }
1191
+ const start = Date.now();
1192
+ let delay2 = 100;
1193
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
1194
+ await new Promise((r) => setTimeout(r, delay2));
1195
+ if (await connectToSocket()) return true;
1196
+ delay2 = Math.min(delay2 * 2, 3e3);
1197
+ }
1198
+ return false;
1199
+ }
1200
+ function sendDaemonRequest(payload, timeoutMs = REQUEST_TIMEOUT_MS) {
1201
+ return new Promise((resolve) => {
1202
+ if (!_socket || !_connected) {
1203
+ resolve({ error: "Not connected" });
1204
+ return;
1205
+ }
1206
+ const id = randomUUID();
1207
+ const token = process.env[DAEMON_TOKEN_ENV] ?? readDaemonToken();
1208
+ const timer = setTimeout(() => {
1209
+ _pending.delete(id);
1210
+ resolve({ error: "Request timeout" });
1211
+ }, timeoutMs);
1212
+ _pending.set(id, { resolve, timer });
1213
+ try {
1214
+ _socket.write(JSON.stringify({ id, token, ...payload }) + "\n");
1215
+ } catch {
1216
+ clearTimeout(timer);
1217
+ _pending.delete(id);
1218
+ resolve({ error: "Write failed" });
1219
+ }
1220
+ });
1221
+ }
1222
+ function isClientConnected() {
1223
+ return _connected;
1224
+ }
1225
+ var SOCKET_PATH, PID_PATH, SPAWN_LOCK_PATH, SPAWN_LOCK_STALE_MS, CONNECT_TIMEOUT_MS, REQUEST_TIMEOUT_MS, DAEMON_TOKEN_ENV, _socket, _connected, _buffer, _pending, MAX_BUFFER;
1226
+ var init_exe_daemon_client = __esm({
1227
+ "src/lib/exe-daemon-client.ts"() {
1228
+ "use strict";
1229
+ init_config();
1230
+ init_daemon_auth();
1231
+ SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path5.join(EXE_AI_DIR, "exed.sock");
1232
+ PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path5.join(EXE_AI_DIR, "exed.pid");
1233
+ SPAWN_LOCK_PATH = path5.join(EXE_AI_DIR, "exed-spawn.lock");
1234
+ SPAWN_LOCK_STALE_MS = 3e4;
1235
+ CONNECT_TIMEOUT_MS = 15e3;
1236
+ REQUEST_TIMEOUT_MS = 3e4;
1237
+ DAEMON_TOKEN_ENV = "EXE_DAEMON_TOKEN";
1238
+ _socket = null;
1239
+ _connected = false;
1240
+ _buffer = "";
1241
+ _pending = /* @__PURE__ */ new Map();
1242
+ MAX_BUFFER = 1e7;
1243
+ }
1244
+ });
1245
+
1246
+ // src/lib/daemon-protocol.ts
1247
+ function serializeValue(v) {
1248
+ if (v === null || v === void 0) return null;
1249
+ if (typeof v === "bigint") return Number(v);
1250
+ if (typeof v === "boolean") return v ? 1 : 0;
1251
+ if (v instanceof Uint8Array) {
1252
+ return { __blob: Buffer.from(v).toString("base64") };
1253
+ }
1254
+ if (ArrayBuffer.isView(v)) {
1255
+ return { __blob: Buffer.from(v.buffer, v.byteOffset, v.byteLength).toString("base64") };
1256
+ }
1257
+ if (v instanceof ArrayBuffer) {
1258
+ return { __blob: Buffer.from(v).toString("base64") };
1259
+ }
1260
+ if (typeof v === "string" || typeof v === "number") return v;
1261
+ return String(v);
1262
+ }
1263
+ function deserializeValue(v) {
1264
+ if (v === null) return null;
1265
+ if (typeof v === "object" && v !== null && "__blob" in v) {
1266
+ const buf = Buffer.from(v.__blob, "base64");
1267
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
1268
+ }
1269
+ return v;
1270
+ }
1271
+ function deserializeResultSet(srs) {
1272
+ const rows = srs.rows.map((obj) => {
1273
+ const values = srs.columns.map(
1274
+ (col) => deserializeValue(obj[col] ?? null)
1275
+ );
1276
+ const row = values;
1277
+ for (let i = 0; i < srs.columns.length; i++) {
1278
+ const col = srs.columns[i];
1279
+ if (col !== void 0) {
1280
+ row[col] = values[i] ?? null;
1281
+ }
1282
+ }
1283
+ Object.defineProperty(row, "length", {
1284
+ value: values.length,
1285
+ enumerable: false
1286
+ });
1287
+ return row;
1288
+ });
1289
+ return {
1290
+ columns: srs.columns,
1291
+ columnTypes: srs.columnTypes ?? [],
1292
+ rows,
1293
+ rowsAffected: srs.rowsAffected,
1294
+ lastInsertRowid: srs.lastInsertRowid != null ? BigInt(srs.lastInsertRowid) : void 0,
1295
+ toJSON: () => ({
1296
+ columns: srs.columns,
1297
+ columnTypes: srs.columnTypes ?? [],
1298
+ rows: srs.rows,
1299
+ rowsAffected: srs.rowsAffected,
1300
+ lastInsertRowid: srs.lastInsertRowid
1301
+ })
1302
+ };
1303
+ }
1304
+ var init_daemon_protocol = __esm({
1305
+ "src/lib/daemon-protocol.ts"() {
1306
+ "use strict";
1307
+ }
1308
+ });
1309
+
1310
+ // src/lib/db-daemon-client.ts
1311
+ var db_daemon_client_exports = {};
1312
+ __export(db_daemon_client_exports, {
1313
+ createDaemonDbClient: () => createDaemonDbClient,
1314
+ initDaemonDbClient: () => initDaemonDbClient
1315
+ });
1316
+ function normalizeStatement2(stmt) {
1317
+ if (typeof stmt === "string") {
1318
+ return { sql: stmt, args: [] };
1319
+ }
1320
+ const sql = stmt.sql;
1321
+ let args = [];
1322
+ if (Array.isArray(stmt.args)) {
1323
+ args = stmt.args.map((v) => serializeValue(v));
1324
+ } else if (stmt.args && typeof stmt.args === "object") {
1325
+ const named = {};
1326
+ for (const [key, val] of Object.entries(stmt.args)) {
1327
+ named[key] = serializeValue(val);
1328
+ }
1329
+ return { sql, args: named };
1330
+ }
1331
+ return { sql, args };
1332
+ }
1333
+ function createDaemonDbClient(fallbackClient) {
1334
+ let _useDaemon = false;
1335
+ const client = {
1336
+ async execute(stmt) {
1337
+ if (!_useDaemon || !isClientConnected()) {
1338
+ return fallbackClient.execute(stmt);
1339
+ }
1340
+ const { sql, args } = normalizeStatement2(stmt);
1341
+ const response = await sendDaemonRequest({
1342
+ type: "db-execute",
1343
+ sql,
1344
+ args
1345
+ });
1346
+ if (response.error) {
1347
+ const errMsg = String(response.error);
1348
+ if (errMsg === "Not connected" || errMsg === "Request timeout" || errMsg === "Write failed" || errMsg === "DB not initialized") {
1349
+ process.stderr.write(`[db-daemon] Transport error (${errMsg}), falling back to direct
1350
+ `);
1351
+ return fallbackClient.execute(stmt);
1352
+ }
1353
+ throw new Error(errMsg);
1354
+ }
1355
+ if (response.db) {
1356
+ return deserializeResultSet(response.db);
1357
+ }
1358
+ process.stderr.write("[db-daemon] Unexpected response shape, falling back to direct\n");
1359
+ return fallbackClient.execute(stmt);
1360
+ },
1361
+ async batch(stmts, mode) {
1362
+ if (!_useDaemon || !isClientConnected()) {
1363
+ return fallbackClient.batch(stmts, mode);
1364
+ }
1365
+ const statements = stmts.map(normalizeStatement2);
1366
+ const response = await sendDaemonRequest({
1367
+ type: "db-batch",
1368
+ statements,
1369
+ mode: mode ?? "deferred"
1370
+ });
1371
+ if (response.error) {
1372
+ const errMsg = String(response.error);
1373
+ if (errMsg === "Not connected" || errMsg === "Request timeout" || errMsg === "Write failed" || errMsg === "DB not initialized") {
1374
+ process.stderr.write(`[db-daemon] Batch transport error (${errMsg}), falling back to direct
1375
+ `);
1376
+ return fallbackClient.batch(stmts, mode);
1377
+ }
1378
+ throw new Error(errMsg);
1379
+ }
1380
+ const batchResults = response["db-batch"];
1381
+ if (batchResults) {
1382
+ return batchResults.map(deserializeResultSet);
1383
+ }
1384
+ process.stderr.write("[db-daemon] Unexpected batch response shape, falling back to direct\n");
1385
+ return fallbackClient.batch(stmts, mode);
1386
+ },
1387
+ // Transaction support — delegate to fallback (transactions need direct connection)
1388
+ async transaction(mode) {
1389
+ return fallbackClient.transaction(mode);
1390
+ },
1391
+ // executeMultiple — delegate to fallback (used only for schema migrations)
1392
+ async executeMultiple(sql) {
1393
+ return fallbackClient.executeMultiple(sql);
1394
+ },
1395
+ // migrate — delegate to fallback
1396
+ async migrate(stmts) {
1397
+ return fallbackClient.migrate(stmts);
1398
+ },
1399
+ // Sync mode — delegate to fallback
1400
+ sync() {
1401
+ return fallbackClient.sync();
1402
+ },
1403
+ close() {
1404
+ _useDaemon = false;
1405
+ },
1406
+ get closed() {
1407
+ return fallbackClient.closed;
1408
+ },
1409
+ get protocol() {
1410
+ return fallbackClient.protocol;
1411
+ }
1412
+ };
1413
+ return {
1414
+ ...client,
1415
+ /** Enable daemon routing (call after confirming daemon is connected) */
1416
+ _enableDaemon() {
1417
+ _useDaemon = true;
1418
+ },
1419
+ /** Check if daemon routing is active */
1420
+ _isDaemonActive() {
1421
+ return _useDaemon && isClientConnected();
1422
+ }
1423
+ };
1424
+ }
1425
+ async function initDaemonDbClient(fallbackClient) {
1426
+ if (process.env.EXE_IS_DAEMON === "1") return null;
1427
+ const connected = await connectEmbedDaemon();
1428
+ if (!connected) {
1429
+ process.stderr.write("[db-daemon] Daemon unavailable \u2014 using direct SQLite\n");
1430
+ return null;
1431
+ }
1432
+ const client = createDaemonDbClient(fallbackClient);
1433
+ client._enableDaemon();
1434
+ process.stderr.write("[db-daemon] DB routing through daemon (single-writer)\n");
1435
+ return client;
1436
+ }
1437
+ var init_db_daemon_client = __esm({
1438
+ "src/lib/db-daemon-client.ts"() {
1439
+ "use strict";
1440
+ init_exe_daemon_client();
1441
+ init_daemon_protocol();
1442
+ }
1443
+ });
1444
+
898
1445
  // src/lib/database.ts
1446
+ var database_exports = {};
1447
+ __export(database_exports, {
1448
+ disposeDatabase: () => disposeDatabase,
1449
+ disposeTurso: () => disposeTurso,
1450
+ ensureSchema: () => ensureSchema,
1451
+ getClient: () => getClient,
1452
+ getRawClient: () => getRawClient,
1453
+ initDaemonClient: () => initDaemonClient,
1454
+ initDatabase: () => initDatabase,
1455
+ initTurso: () => initTurso,
1456
+ isInitialized: () => isInitialized
1457
+ });
899
1458
  import { createClient } from "@libsql/client";
900
1459
  async function initDatabase(config) {
901
1460
  if (_walCheckpointTimer) {
@@ -934,7 +1493,7 @@ async function initDatabase(config) {
934
1493
  });
935
1494
  }, 3e4);
936
1495
  _walCheckpointTimer.unref();
937
- if (process.env.DATABASE_URL) {
1496
+ if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") {
938
1497
  _adapterClient = await createPrismaDbAdapter(_resilientClient);
939
1498
  }
940
1499
  }
@@ -945,7 +1504,7 @@ function getClient() {
945
1504
  if (!_adapterClient) {
946
1505
  throw new Error("Database client not initialized. Call initDatabase() first.");
947
1506
  }
948
- if (process.env.DATABASE_URL) {
1507
+ if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") {
949
1508
  return _adapterClient;
950
1509
  }
951
1510
  if (process.env.EXE_IS_DAEMON === "1") {
@@ -956,6 +1515,22 @@ function getClient() {
956
1515
  }
957
1516
  return _resilientClient;
958
1517
  }
1518
+ async function initDaemonClient() {
1519
+ if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") return;
1520
+ if (process.env.EXE_IS_DAEMON === "1") return;
1521
+ if (process.env.VITEST) return;
1522
+ if (!_resilientClient) return;
1523
+ if (_daemonClient) return;
1524
+ try {
1525
+ const { initDaemonDbClient: initDaemonDbClient2 } = await Promise.resolve().then(() => (init_db_daemon_client(), db_daemon_client_exports));
1526
+ _daemonClient = await initDaemonDbClient2(_resilientClient);
1527
+ } catch (err) {
1528
+ process.stderr.write(
1529
+ `[database] Daemon client init failed (non-fatal): ${err instanceof Error ? err.message : String(err)}
1530
+ `
1531
+ );
1532
+ }
1533
+ }
959
1534
  function getRawClient() {
960
1535
  if (!_client) {
961
1536
  throw new Error("Database client not initialized. Call initDatabase() first.");
@@ -1094,6 +1669,13 @@ async function ensureSchema() {
1094
1669
  });
1095
1670
  } catch {
1096
1671
  }
1672
+ try {
1673
+ await client.execute({
1674
+ sql: `ALTER TABLE behaviors ADD COLUMN vector F32_BLOB(${EMBEDDING_DIM})`,
1675
+ args: []
1676
+ });
1677
+ } catch {
1678
+ }
1097
1679
  try {
1098
1680
  await client.execute({
1099
1681
  sql: `ALTER TABLE tasks ADD COLUMN blocked_by TEXT`,
@@ -1938,19 +2520,40 @@ async function ensureSchema() {
1938
2520
  } catch {
1939
2521
  }
1940
2522
  }
1941
- var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso;
2523
+ async function disposeDatabase() {
2524
+ if (_walCheckpointTimer) {
2525
+ clearInterval(_walCheckpointTimer);
2526
+ _walCheckpointTimer = null;
2527
+ }
2528
+ if (_daemonClient) {
2529
+ _daemonClient.close();
2530
+ _daemonClient = null;
2531
+ }
2532
+ if (_adapterClient && _adapterClient !== _resilientClient) {
2533
+ _adapterClient.close();
2534
+ }
2535
+ _adapterClient = null;
2536
+ if (_client) {
2537
+ _client.close();
2538
+ _client = null;
2539
+ _resilientClient = null;
2540
+ }
2541
+ }
2542
+ var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso, disposeTurso;
1942
2543
  var init_database = __esm({
1943
2544
  "src/lib/database.ts"() {
1944
2545
  "use strict";
1945
2546
  init_db_retry();
1946
2547
  init_employees();
1947
2548
  init_database_adapter();
2549
+ init_memory();
1948
2550
  _client = null;
1949
2551
  _resilientClient = null;
1950
2552
  _walCheckpointTimer = null;
1951
2553
  _daemonClient = null;
1952
2554
  _adapterClient = null;
1953
2555
  initTurso = initDatabase;
2556
+ disposeTurso = disposeDatabase;
1954
2557
  }
1955
2558
  });
1956
2559
 
@@ -1968,12 +2571,12 @@ __export(shard_manager_exports, {
1968
2571
  listShards: () => listShards,
1969
2572
  shardExists: () => shardExists
1970
2573
  });
1971
- import path5 from "path";
1972
- import { existsSync as existsSync5, mkdirSync as mkdirSync2, readdirSync } from "fs";
2574
+ import path7 from "path";
2575
+ import { existsSync as existsSync7, mkdirSync as mkdirSync2, readdirSync } from "fs";
1973
2576
  import { createClient as createClient2 } from "@libsql/client";
1974
2577
  function initShardManager(encryptionKey) {
1975
2578
  _encryptionKey = encryptionKey;
1976
- if (!existsSync5(SHARDS_DIR)) {
2579
+ if (!existsSync7(SHARDS_DIR)) {
1977
2580
  mkdirSync2(SHARDS_DIR, { recursive: true });
1978
2581
  }
1979
2582
  _shardingEnabled = true;
@@ -2003,7 +2606,7 @@ function getShardClient(projectName) {
2003
2606
  while (_shards.size >= MAX_OPEN_SHARDS) {
2004
2607
  evictLRU();
2005
2608
  }
2006
- const dbPath = path5.join(SHARDS_DIR, `${safeName}.db`);
2609
+ const dbPath = path7.join(SHARDS_DIR, `${safeName}.db`);
2007
2610
  const client = createClient2({
2008
2611
  url: `file:${dbPath}`,
2009
2612
  encryptionKey: _encryptionKey
@@ -2014,10 +2617,10 @@ function getShardClient(projectName) {
2014
2617
  }
2015
2618
  function shardExists(projectName) {
2016
2619
  const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
2017
- return existsSync5(path5.join(SHARDS_DIR, `${safeName}.db`));
2620
+ return existsSync7(path7.join(SHARDS_DIR, `${safeName}.db`));
2018
2621
  }
2019
2622
  function listShards() {
2020
- if (!existsSync5(SHARDS_DIR)) return [];
2623
+ if (!existsSync7(SHARDS_DIR)) return [];
2021
2624
  return readdirSync(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
2022
2625
  }
2023
2626
  async function ensureShardSchema(client) {
@@ -2264,7 +2867,7 @@ var init_shard_manager = __esm({
2264
2867
  "src/lib/shard-manager.ts"() {
2265
2868
  "use strict";
2266
2869
  init_config();
2267
- SHARDS_DIR = path5.join(EXE_AI_DIR, "shards");
2870
+ SHARDS_DIR = path7.join(EXE_AI_DIR, "shards");
2268
2871
  SHARD_IDLE_MS = 5 * 60 * 1e3;
2269
2872
  MAX_OPEN_SHARDS = 10;
2270
2873
  EVICTION_INTERVAL_MS = 60 * 1e3;
@@ -2384,6 +2987,68 @@ var init_platform_procedures = __esm({
2384
2987
  domain: "architecture",
2385
2988
  priority: "p0",
2386
2989
  content: "Tasks live in the DB. Intercom (tmux send-keys) is fire-and-forget \u2014 it may fail, get garbled, or arrive mid-work. Never rely on intercom for task delivery. The UserPromptSubmit hook checks the DB for new tasks on every prompt. Your operating procedures step 7 says check for next work. The daemon nudges idle agents as a speedup. If you have no tasks, you found them all."
2990
+ },
2991
+ // --- MCP is the ONLY data interface ---
2992
+ {
2993
+ title: "MCP disconnect \u2014 ask the user, never work around it",
2994
+ domain: "workflow",
2995
+ priority: "p0",
2996
+ content: "If MCP tools are unavailable, disconnected, or returning connection errors: STOP. Tell the user clearly: 'MCP server is disconnected. Please run /mcp to reconnect.' Do NOT attempt workarounds \u2014 no raw Node imports, no direct DB access, no CLI hacks, no daemon socket calls. MCP is the ONLY data interface. Working around it wastes time, hits bundling issues, and bypasses the contract boundary. Ask once, wait, proceed when reconnected."
2997
+ },
2998
+ // --- MCP Tool Catalog (Layer 0 — every agent knows what tools exist) ---
2999
+ {
3000
+ title: "MCP tools \u2014 memory and search",
3001
+ domain: "tool-use",
3002
+ priority: "p1",
3003
+ content: "recall_my_memory: search your own memories (semantic + FTS). ask_team_memory: search a colleague's memories by agent name. store_memory: persist a memory (decisions, summaries, context). commit_memory: high-importance memory that survives consolidation. search_everything: unified search across memories, tasks, entities, conversations. get_session_context: temporal window of memories around a timestamp. consolidate_memories: merge duplicate/related memories into insights. get_memory_cardinality: count memories per agent (health check)."
3004
+ },
3005
+ {
3006
+ title: "MCP tools \u2014 task orchestration",
3007
+ domain: "tool-use",
3008
+ priority: "p1",
3009
+ content: "create_task: dispatch work to an employee (auto-spawns session). The ONLY dispatch path. list_tasks: query tasks by status, assignee, project. get_task: fetch full task details by ID. update_task: change status (in_progress, done, blocked, cancelled) + add result summary. close_task: finalize a reviewed task (COO only). checkpoint_task: save progress state for crash recovery. resume_employee: re-spawn an employee session for an existing task."
3010
+ },
3011
+ {
3012
+ title: "MCP tools \u2014 knowledge graph (GraphRAG)",
3013
+ domain: "tool-use",
3014
+ priority: "p1",
3015
+ content: "query_relationships: find connections between entities in the knowledge graph. get_entity_neighbors: explore an entity's direct connections. get_hot_entities: find most-referenced entities (trending topics). get_graph_stats: graph health \u2014 entity/relationship counts, density. export_graph: export graph data for visualization. merge_entities: deduplicate entities (alias resolution). find_similar_trajectories: match tool-call patterns to past task solutions."
3016
+ },
3017
+ {
3018
+ title: "MCP tools \u2014 identity, behavior, and decisions",
3019
+ domain: "tool-use",
3020
+ priority: "p1",
3021
+ content: "get_identity: read an agent's exe.md (Layer 1 identity). update_identity: write an agent's exe.md. Identity > behavior \u2014 use for permanent rules. store_behavior: record a correction or pattern for an agent (Layer 2 expertise). list_behaviors: view an agent's active behaviors. deactivate_behavior: soft-delete a stale or conflicting behavior. store_decision: record an ADR (architectural decision record). get_decision: retrieve a past decision by query."
3022
+ },
3023
+ {
3024
+ title: "MCP tools \u2014 communication and messaging",
3025
+ domain: "tool-use",
3026
+ priority: "p1",
3027
+ content: "send_message: send supplementary context to another agent (NOT for actionable work \u2014 use create_task). acknowledge_messages: mark messages as read. send_whatsapp: send WhatsApp message via gateway (customer-facing alerts). query_conversations: search ingested conversations across all channels (WhatsApp, email, etc.)."
3028
+ },
3029
+ {
3030
+ title: "MCP tools \u2014 wiki, documents, and content",
3031
+ domain: "tool-use",
3032
+ priority: "p1",
3033
+ content: "create_wiki_page: create a wiki page in exe-wiki. list_wiki_pages: browse wiki pages. get_wiki_page: read a wiki page. update_wiki_page: edit a wiki page. ingest_document: import a file (PDF, MD, etc.) into memory as chunks. list_documents: browse ingested documents by workspace. purge_document: remove a document and its memory chunks. set_document_importance: adjust chunk importance scores. rerank_documents: re-score document relevance for a query."
3034
+ },
3035
+ {
3036
+ title: "MCP tools \u2014 system, operations, and admin",
3037
+ domain: "tool-use",
3038
+ priority: "p1",
3039
+ content: "get_agent_spend: token usage per agent/session (cost tracking). list_agent_sessions: view agent session history. get_session_kills: audit log of killed sessions. get_daemon_health: check exed daemon status. get_auto_wake_status: daemon auto-wake configuration. get_worker_gate: check worker deployment gates. run_memory_audit: health check \u2014 duplicates, null vectors, orphaned rows. run_consolidation: trigger sleep-time memory consolidation. cloud_sync: force a cloud sync cycle. backup_vps: trigger VPS backup."
3040
+ },
3041
+ {
3042
+ title: "MCP tools \u2014 config, licensing, and team",
3043
+ domain: "tool-use",
3044
+ priority: "p1",
3045
+ content: "set_agent_config: view/change per-agent runtime and model settings. list_employees: view the employee roster. add_person: add a person to the CRM contacts roster. list_people: browse CRM contacts. get_person: fetch contact details. get_license_status: check license validity. create_license: generate a new license key (admin). list_licenses: view all issued licenses. activate_license: activate a license on a device."
3046
+ },
3047
+ {
3048
+ title: "MCP tools \u2014 advanced (triggers, skills, orchestration)",
3049
+ domain: "tool-use",
3050
+ priority: "p1",
3051
+ content: "create_trigger: set up a scheduled recurring agent job (cron). list_triggers: view active triggers. load_skill: load a slash-command skill dynamically. apply_starter_pack: import a pre-built behavior + identity pack for a role. export_orchestration: export full org state (tasks, behaviors, identities) as portable JSON. import_orchestration: import org state into a new instance. deploy_client: deploy a customer client instance. query_company_brain: unified RAG query across all company knowledge. create_reminder: set a text reminder (shown in boot brief). list_reminders: view pending reminders. complete_reminder: mark a reminder done. global_procedure: manage Layer 0 procedures (actions: store, list, deactivate). Legacy aliases: store_global_procedure, list_global_procedures, deactivate_global_procedure."
2387
3052
  }
2388
3053
  ];
2389
3054
  PLATFORM_PROCEDURE_TITLES = new Set(
@@ -2400,7 +3065,7 @@ __export(global_procedures_exports, {
2400
3065
  loadGlobalProcedures: () => loadGlobalProcedures,
2401
3066
  storeGlobalProcedure: () => storeGlobalProcedure
2402
3067
  });
2403
- import { randomUUID } from "crypto";
3068
+ import { randomUUID as randomUUID2 } from "crypto";
2404
3069
  async function loadGlobalProcedures() {
2405
3070
  const client = getClient();
2406
3071
  const result = await client.execute({
@@ -2429,7 +3094,7 @@ ${sections.join("\n\n")}
2429
3094
  `;
2430
3095
  }
2431
3096
  async function storeGlobalProcedure(input) {
2432
- const id = randomUUID();
3097
+ const id = randomUUID2();
2433
3098
  const now = (/* @__PURE__ */ new Date()).toISOString();
2434
3099
  const client = getClient();
2435
3100
  await client.execute({
@@ -2465,25 +3130,26 @@ ${p.content}`).join("\n\n");
2465
3130
 
2466
3131
  // src/lib/schedules.ts
2467
3132
  init_database();
2468
- import crypto from "crypto";
3133
+ import crypto2 from "crypto";
2469
3134
  import { execSync as execSync2 } from "child_process";
2470
3135
 
2471
3136
  // src/lib/store.ts
2472
- import { createHash } from "crypto";
3137
+ init_memory();
2473
3138
  init_database();
3139
+ import { createHash } from "crypto";
2474
3140
 
2475
3141
  // src/lib/keychain.ts
2476
3142
  import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
2477
- import { existsSync as existsSync4 } from "fs";
2478
- import path4 from "path";
2479
- import os4 from "os";
3143
+ import { existsSync as existsSync6 } from "fs";
3144
+ import path6 from "path";
3145
+ import os5 from "os";
2480
3146
  var SERVICE = "exe-mem";
2481
3147
  var ACCOUNT = "master-key";
2482
3148
  function getKeyDir() {
2483
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path4.join(os4.homedir(), ".exe-os");
3149
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path6.join(os5.homedir(), ".exe-os");
2484
3150
  }
2485
3151
  function getKeyPath() {
2486
- return path4.join(getKeyDir(), "master.key");
3152
+ return path6.join(getKeyDir(), "master.key");
2487
3153
  }
2488
3154
  async function tryKeytar() {
2489
3155
  try {
@@ -2504,9 +3170,9 @@ async function getMasterKey() {
2504
3170
  }
2505
3171
  }
2506
3172
  const keyPath = getKeyPath();
2507
- if (!existsSync4(keyPath)) {
3173
+ if (!existsSync6(keyPath)) {
2508
3174
  process.stderr.write(
2509
- `[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
3175
+ `[keychain] Key not found at ${keyPath} (HOME=${os5.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2510
3176
  `
2511
3177
  );
2512
3178
  return null;
@@ -2635,6 +3301,11 @@ async function initStore(options) {
2635
3301
  encryptionKey: hexKey
2636
3302
  });
2637
3303
  await retryOnBusy2(() => ensureSchema(), "ensureSchema");
3304
+ try {
3305
+ const { initDaemonClient: initDaemonClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
3306
+ await initDaemonClient2();
3307
+ } catch {
3308
+ }
2638
3309
  if (!options?.lightweight) {
2639
3310
  try {
2640
3311
  const { initShardManager: initShardManager2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
@@ -2656,6 +3327,16 @@ async function initStore(options) {
2656
3327
  }
2657
3328
 
2658
3329
  // src/lib/schedules.ts
3330
+ var CRON_FIELD = /^[\d*/,\-]+$/;
3331
+ function isValidCron(cron) {
3332
+ const fields = cron.trim().split(/\s+/);
3333
+ if (fields.length !== 5) return false;
3334
+ return fields.every((f) => CRON_FIELD.test(f));
3335
+ }
3336
+ var SAFE_ID = /^[a-zA-Z0-9_\-]+$/;
3337
+ function isValidScheduleId(id) {
3338
+ return SAFE_ID.test(id) && id.length <= 128;
3339
+ }
2659
3340
  async function ensureDb() {
2660
3341
  if (!isInitialized()) {
2661
3342
  await initStore();
@@ -2721,9 +3402,12 @@ function parseHumanCron(input) {
2721
3402
  return `${minute} ${hour} * * ${dow}`;
2722
3403
  }
2723
3404
  async function createSchedule(input) {
3405
+ if (!isValidCron(input.cron)) {
3406
+ throw new Error(`Invalid cron expression: ${input.cron}. Must be 5 fields with only digits, *, /, -, comma.`);
3407
+ }
2724
3408
  await ensureDb();
2725
3409
  const client = getClient();
2726
- const id = crypto.randomUUID().slice(0, 8);
3410
+ const id = crypto2.randomUUID().slice(0, 8);
2727
3411
  const now = (/* @__PURE__ */ new Date()).toISOString();
2728
3412
  const prompt = input.prompt ?? input.description;
2729
3413
  await client.execute({
@@ -2794,6 +3478,12 @@ async function deleteSchedule(id) {
2794
3478
  return true;
2795
3479
  }
2796
3480
  function addToCrontab(id, cron, prompt, projectDir) {
3481
+ if (!isValidCron(cron)) {
3482
+ throw new Error(`Invalid cron expression: ${cron}`);
3483
+ }
3484
+ if (!isValidScheduleId(id)) {
3485
+ throw new Error(`Invalid schedule ID: ${id}`);
3486
+ }
2797
3487
  try {
2798
3488
  const cwd = projectDir ? `cd ${JSON.stringify(projectDir)} && ` : "";
2799
3489
  const escapedPrompt = prompt.replace(/"/g, '\\"');
@@ -2802,10 +3492,12 @@ function addToCrontab(id, cron, prompt, projectDir) {
2802
3492
  `(crontab -l 2>/dev/null; echo ${JSON.stringify(entry)}) | crontab -`,
2803
3493
  { timeout: 5e3, stdio: "ignore" }
2804
3494
  );
2805
- } catch {
3495
+ } catch (err) {
3496
+ if (err instanceof Error && err.message.startsWith("Invalid")) throw err;
2806
3497
  }
2807
3498
  }
2808
3499
  function removeFromCrontab(id) {
3500
+ if (!isValidScheduleId(id)) return;
2809
3501
  try {
2810
3502
  execSync2(
2811
3503
  `crontab -l 2>/dev/null | grep -v "exe-schedule:${id}" | crontab -`,