@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,3979 +0,0 @@
1
- var __defProp = Object.defineProperty;
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
- });
9
- var __esm = (fn, res) => function __init() {
10
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
- };
12
- var __export = (target, all) => {
13
- for (var name in all)
14
- __defProp(target, name, { get: all[name], enumerable: true });
15
- };
16
-
17
- // src/types/memory.ts
18
- var EMBEDDING_DIM;
19
- var init_memory = __esm({
20
- "src/types/memory.ts"() {
21
- "use strict";
22
- EMBEDDING_DIM = 1024;
23
- }
24
- });
25
-
26
- // src/lib/db-retry.ts
27
- function isBusyError(err) {
28
- if (err instanceof Error) {
29
- const msg = err.message.toLowerCase();
30
- return msg.includes("sqlite_busy") || msg.includes("database is locked");
31
- }
32
- return false;
33
- }
34
- function delay(ms) {
35
- return new Promise((resolve) => setTimeout(resolve, ms));
36
- }
37
- async function retryOnBusy(fn, label) {
38
- let lastError;
39
- for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
40
- try {
41
- return await fn();
42
- } catch (err) {
43
- lastError = err;
44
- if (!isBusyError(err) || attempt === MAX_RETRIES) {
45
- throw err;
46
- }
47
- const backoff = BASE_DELAY_MS * Math.pow(2, attempt);
48
- const jitter = Math.floor(Math.random() * MAX_JITTER_MS);
49
- process.stderr.write(
50
- `[exe-os] SQLITE_BUSY ${label} retry ${attempt + 1}/${MAX_RETRIES} \u2014 waiting ${backoff + jitter}ms
51
- `
52
- );
53
- await delay(backoff + jitter);
54
- }
55
- }
56
- throw lastError;
57
- }
58
- function wrapWithRetry(client) {
59
- return new Proxy(client, {
60
- get(target, prop, receiver) {
61
- if (prop === "execute") {
62
- return (sql) => retryOnBusy(() => target.execute(sql), "execute");
63
- }
64
- if (prop === "batch") {
65
- return (stmts, mode) => retryOnBusy(() => target.batch(stmts, mode), "batch");
66
- }
67
- return Reflect.get(target, prop, receiver);
68
- }
69
- });
70
- }
71
- var MAX_RETRIES, BASE_DELAY_MS, MAX_JITTER_MS;
72
- var init_db_retry = __esm({
73
- "src/lib/db-retry.ts"() {
74
- "use strict";
75
- MAX_RETRIES = 3;
76
- BASE_DELAY_MS = 200;
77
- MAX_JITTER_MS = 300;
78
- }
79
- });
80
-
81
- // src/lib/secure-files.ts
82
- import { chmodSync, existsSync, mkdirSync } from "fs";
83
- import { chmod, mkdir } from "fs/promises";
84
- async function ensurePrivateDir(dirPath) {
85
- await mkdir(dirPath, { recursive: true, mode: PRIVATE_DIR_MODE });
86
- try {
87
- await chmod(dirPath, PRIVATE_DIR_MODE);
88
- } catch {
89
- }
90
- }
91
- function ensurePrivateDirSync(dirPath) {
92
- mkdirSync(dirPath, { recursive: true, mode: PRIVATE_DIR_MODE });
93
- try {
94
- chmodSync(dirPath, PRIVATE_DIR_MODE);
95
- } catch {
96
- }
97
- }
98
- async function enforcePrivateFile(filePath) {
99
- try {
100
- await chmod(filePath, PRIVATE_FILE_MODE);
101
- } catch {
102
- }
103
- }
104
- function enforcePrivateFileSync(filePath) {
105
- try {
106
- if (existsSync(filePath)) chmodSync(filePath, PRIVATE_FILE_MODE);
107
- } catch {
108
- }
109
- }
110
- var PRIVATE_DIR_MODE, PRIVATE_FILE_MODE;
111
- var init_secure_files = __esm({
112
- "src/lib/secure-files.ts"() {
113
- "use strict";
114
- PRIVATE_DIR_MODE = 448;
115
- PRIVATE_FILE_MODE = 384;
116
- }
117
- });
118
-
119
- // src/lib/config.ts
120
- var config_exports = {};
121
- __export(config_exports, {
122
- CONFIG_MIGRATIONS: () => CONFIG_MIGRATIONS,
123
- CONFIG_PATH: () => CONFIG_PATH,
124
- CURRENT_CONFIG_VERSION: () => CURRENT_CONFIG_VERSION,
125
- DB_PATH: () => DB_PATH,
126
- EXE_AI_DIR: () => EXE_AI_DIR,
127
- LEGACY_LANCE_PATH: () => LEGACY_LANCE_PATH,
128
- MODELS_DIR: () => MODELS_DIR,
129
- loadConfig: () => loadConfig,
130
- loadConfigFrom: () => loadConfigFrom,
131
- loadConfigSync: () => loadConfigSync,
132
- migrateConfig: () => migrateConfig,
133
- saveConfig: () => saveConfig
134
- });
135
- import { readFile, writeFile } from "fs/promises";
136
- import { readFileSync, existsSync as existsSync2, renameSync } from "fs";
137
- import path2 from "path";
138
- import os from "os";
139
- function resolveDataDir() {
140
- if (process.env.EXE_OS_DIR) return process.env.EXE_OS_DIR;
141
- if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
142
- const newDir = path2.join(os.homedir(), ".exe-os");
143
- const legacyDir = path2.join(os.homedir(), ".exe-mem");
144
- if (!existsSync2(newDir) && existsSync2(legacyDir)) {
145
- try {
146
- renameSync(legacyDir, newDir);
147
- process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
148
- `);
149
- } catch {
150
- return legacyDir;
151
- }
152
- }
153
- return newDir;
154
- }
155
- function migrateLegacyConfig(raw) {
156
- if ("r2" in raw) {
157
- process.stderr.write(
158
- "[exe-os] Warning: config.json contains deprecated 'r2' field from v1.0. R2 sync has been replaced in v1.1. The 'r2' field will be ignored.\n"
159
- );
160
- delete raw.r2;
161
- }
162
- if ("syncIntervalMs" in raw) {
163
- delete raw.syncIntervalMs;
164
- }
165
- return raw;
166
- }
167
- function migrateConfig(raw) {
168
- const fromVersion = typeof raw.config_version === "number" ? raw.config_version : 0;
169
- let currentVersion = fromVersion;
170
- let migrated = false;
171
- if (currentVersion > CURRENT_CONFIG_VERSION) {
172
- return { config: raw, migrated: false, fromVersion };
173
- }
174
- for (const migration of CONFIG_MIGRATIONS) {
175
- if (currentVersion === migration.from && migration.to <= CURRENT_CONFIG_VERSION) {
176
- raw = migration.migrate(raw);
177
- currentVersion = migration.to;
178
- migrated = true;
179
- }
180
- }
181
- return { config: raw, migrated, fromVersion };
182
- }
183
- function normalizeScalingRoadmap(raw) {
184
- const defaultAuto = DEFAULT_CONFIG.scalingRoadmap.rerankerAutoTrigger;
185
- const userRoadmap = raw.scalingRoadmap ?? {};
186
- const userAuto = userRoadmap.rerankerAutoTrigger ?? {};
187
- if (userAuto.enabled === void 0 && raw.rerankerEnabled !== void 0) {
188
- userAuto.enabled = raw.rerankerEnabled;
189
- }
190
- raw.scalingRoadmap = {
191
- ...userRoadmap,
192
- rerankerAutoTrigger: { ...defaultAuto, ...userAuto }
193
- };
194
- }
195
- function normalizeSessionLifecycle(raw) {
196
- const defaultSL = DEFAULT_CONFIG.sessionLifecycle;
197
- const userSL = raw.sessionLifecycle ?? {};
198
- raw.sessionLifecycle = { ...defaultSL, ...userSL };
199
- }
200
- function normalizeAutoUpdate(raw) {
201
- const defaultAU = DEFAULT_CONFIG.autoUpdate;
202
- const userAU = raw.autoUpdate ?? {};
203
- raw.autoUpdate = { ...defaultAU, ...userAU };
204
- }
205
- async function loadConfig() {
206
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
207
- await ensurePrivateDir(dir);
208
- const configPath = path2.join(dir, "config.json");
209
- if (!existsSync2(configPath)) {
210
- return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
211
- }
212
- const raw = await readFile(configPath, "utf-8");
213
- try {
214
- let parsed = JSON.parse(raw);
215
- parsed = migrateLegacyConfig(parsed);
216
- const { config: migratedCfg, migrated, fromVersion } = migrateConfig(parsed);
217
- if (migrated) {
218
- process.stderr.write(`[exe-os] Config migrated from v${fromVersion} to v${migratedCfg.config_version}
219
- `);
220
- try {
221
- await writeFile(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
222
- await enforcePrivateFile(configPath);
223
- } catch {
224
- }
225
- }
226
- normalizeScalingRoadmap(migratedCfg);
227
- normalizeSessionLifecycle(migratedCfg);
228
- normalizeAutoUpdate(migratedCfg);
229
- const config = { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db"), ...migratedCfg };
230
- if (config.dbPath.startsWith("~")) {
231
- config.dbPath = config.dbPath.replace(/^~/, os.homedir());
232
- }
233
- return config;
234
- } catch {
235
- return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
236
- }
237
- }
238
- function loadConfigSync() {
239
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
240
- const configPath = path2.join(dir, "config.json");
241
- if (!existsSync2(configPath)) {
242
- return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
243
- }
244
- try {
245
- const raw = readFileSync(configPath, "utf-8");
246
- let parsed = JSON.parse(raw);
247
- parsed = migrateLegacyConfig(parsed);
248
- const { config: migratedCfg } = migrateConfig(parsed);
249
- normalizeScalingRoadmap(migratedCfg);
250
- normalizeSessionLifecycle(migratedCfg);
251
- normalizeAutoUpdate(migratedCfg);
252
- return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db"), ...migratedCfg };
253
- } catch {
254
- return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
255
- }
256
- }
257
- async function saveConfig(config) {
258
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
259
- await ensurePrivateDir(dir);
260
- const configPath = path2.join(dir, "config.json");
261
- await writeFile(configPath, JSON.stringify(config, null, 2) + "\n");
262
- await enforcePrivateFile(configPath);
263
- }
264
- async function loadConfigFrom(configPath) {
265
- const raw = await readFile(configPath, "utf-8");
266
- try {
267
- let parsed = JSON.parse(raw);
268
- parsed = migrateLegacyConfig(parsed);
269
- const { config: migratedCfg } = migrateConfig(parsed);
270
- normalizeScalingRoadmap(migratedCfg);
271
- normalizeSessionLifecycle(migratedCfg);
272
- normalizeAutoUpdate(migratedCfg);
273
- return { ...DEFAULT_CONFIG, ...migratedCfg };
274
- } catch {
275
- return { ...DEFAULT_CONFIG };
276
- }
277
- }
278
- var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
279
- var init_config = __esm({
280
- "src/lib/config.ts"() {
281
- "use strict";
282
- init_secure_files();
283
- EXE_AI_DIR = resolveDataDir();
284
- DB_PATH = path2.join(EXE_AI_DIR, "memories.db");
285
- MODELS_DIR = path2.join(EXE_AI_DIR, "models");
286
- CONFIG_PATH = path2.join(EXE_AI_DIR, "config.json");
287
- LEGACY_LANCE_PATH = path2.join(EXE_AI_DIR, "local.lance");
288
- CURRENT_CONFIG_VERSION = 1;
289
- DEFAULT_CONFIG = {
290
- config_version: CURRENT_CONFIG_VERSION,
291
- dbPath: DB_PATH,
292
- modelFile: "jina-embeddings-v5-small-q4_k_m.gguf",
293
- embeddingDim: 1024,
294
- batchSize: 20,
295
- flushIntervalMs: 1e4,
296
- autoIngestion: true,
297
- autoRetrieval: true,
298
- searchMode: "hybrid",
299
- hookSearchMode: "hybrid",
300
- fileGrepEnabled: true,
301
- splashEffect: true,
302
- consolidationEnabled: true,
303
- consolidationIntervalMs: 6 * 60 * 60 * 1e3,
304
- consolidationModel: "claude-haiku-4-5-20251001",
305
- consolidationMaxCallsPerRun: 20,
306
- selfQueryRouter: true,
307
- selfQueryModel: "claude-haiku-4-5-20251001",
308
- rerankerEnabled: true,
309
- scalingRoadmap: {
310
- rerankerAutoTrigger: {
311
- enabled: true,
312
- broadQueryMinCardinality: 5e4,
313
- fetchTopK: 150,
314
- returnTopK: 5
315
- }
316
- },
317
- graphRagEnabled: true,
318
- wikiEnabled: false,
319
- wikiUrl: "",
320
- wikiApiKey: "",
321
- wikiSyncIntervalMs: 30 * 60 * 1e3,
322
- wikiWorkspaceMapping: {},
323
- wikiAutoUpdate: true,
324
- wikiAutoUpdateThreshold: 0.5,
325
- wikiAutoUpdateCreateNew: true,
326
- skillLearning: true,
327
- skillThreshold: 3,
328
- skillModel: "claude-haiku-4-5-20251001",
329
- exeHeartbeat: {
330
- enabled: true,
331
- intervalSeconds: 60,
332
- staleInProgressThresholdHours: 2
333
- },
334
- sessionLifecycle: {
335
- idleKillEnabled: true,
336
- idleKillTicksRequired: 3,
337
- idleKillIntercomAckWindowMs: 1e4,
338
- maxAutoInstances: 10
339
- },
340
- autoUpdate: {
341
- checkOnBoot: true,
342
- autoInstall: false,
343
- checkIntervalMs: 24 * 60 * 60 * 1e3
344
- }
345
- };
346
- CONFIG_MIGRATIONS = [
347
- {
348
- from: 0,
349
- to: 1,
350
- migrate: (cfg) => {
351
- cfg.config_version = 1;
352
- return cfg;
353
- }
354
- }
355
- ];
356
- }
357
- });
358
-
359
- // src/lib/employees.ts
360
- import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
361
- import { existsSync as existsSync3, symlinkSync, readlinkSync, readFileSync as readFileSync2, renameSync as renameSync2, unlinkSync, writeFileSync } from "fs";
362
- import { execSync as execSync2 } from "child_process";
363
- import path3 from "path";
364
- import os2 from "os";
365
- function normalizeRole(role) {
366
- return (role ?? "").trim().toLowerCase();
367
- }
368
- function isCoordinatorRole(role) {
369
- return normalizeRole(role) === normalizeRole(COORDINATOR_ROLE);
370
- }
371
- function getCoordinatorEmployee(employees) {
372
- return employees.find((e) => isCoordinatorRole(e.role));
373
- }
374
- function getCoordinatorName(employees = loadEmployeesSync()) {
375
- return getCoordinatorEmployee(employees)?.name ?? DEFAULT_COORDINATOR_TEMPLATE_NAME;
376
- }
377
- function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
378
- if (!existsSync3(employeesPath)) return [];
379
- try {
380
- return JSON.parse(readFileSync2(employeesPath, "utf-8"));
381
- } catch {
382
- return [];
383
- }
384
- }
385
- var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE, IDENTITY_DIR;
386
- var init_employees = __esm({
387
- "src/lib/employees.ts"() {
388
- "use strict";
389
- init_config();
390
- EMPLOYEES_PATH = path3.join(EXE_AI_DIR, "exe-employees.json");
391
- DEFAULT_COORDINATOR_TEMPLATE_NAME = "exe";
392
- COORDINATOR_ROLE = "COO";
393
- IDENTITY_DIR = path3.join(EXE_AI_DIR, "identity");
394
- }
395
- });
396
-
397
- // src/lib/database-adapter.ts
398
- import os3 from "os";
399
- import path4 from "path";
400
- import { createRequire } from "module";
401
- import { pathToFileURL } from "url";
402
- function quotedIdentifier(identifier) {
403
- return `"${identifier.replace(/"/g, '""')}"`;
404
- }
405
- function unqualifiedTableName(name) {
406
- const raw = name.trim().replace(/^"|"$/g, "");
407
- const parts = raw.split(".");
408
- return parts[parts.length - 1].replace(/^"|"$/g, "").toLowerCase();
409
- }
410
- function stripTrailingSemicolon(sql) {
411
- return sql.trim().replace(/;+\s*$/u, "");
412
- }
413
- function appendClause(sql, clause) {
414
- const trimmed = stripTrailingSemicolon(sql);
415
- const returningMatch = /\sRETURNING\b[\s\S]*$/iu.exec(trimmed);
416
- if (!returningMatch) {
417
- return `${trimmed}${clause}`;
418
- }
419
- const idx = returningMatch.index;
420
- return `${trimmed.slice(0, idx)}${clause}${trimmed.slice(idx)}`;
421
- }
422
- function normalizeStatement(stmt) {
423
- if (typeof stmt === "string") {
424
- return { kind: "positional", sql: stmt, args: [] };
425
- }
426
- const sql = stmt.sql;
427
- if (Array.isArray(stmt.args) || stmt.args === void 0) {
428
- return { kind: "positional", sql, args: stmt.args ?? [] };
429
- }
430
- return { kind: "named", sql, args: stmt.args };
431
- }
432
- function rewriteBooleanLiterals(sql) {
433
- let out = sql;
434
- for (const column of BOOLEAN_COLUMN_NAMES) {
435
- const scoped = `((?:\\b[a-z_][a-z0-9_]*\\.)?${column})`;
436
- out = out.replace(new RegExp(`${scoped}\\s*=\\s*0\\b`, "giu"), "$1 = FALSE");
437
- out = out.replace(new RegExp(`${scoped}\\s*=\\s*1\\b`, "giu"), "$1 = TRUE");
438
- out = out.replace(new RegExp(`${scoped}\\s*!=\\s*0\\b`, "giu"), "$1 != FALSE");
439
- out = out.replace(new RegExp(`${scoped}\\s*!=\\s*1\\b`, "giu"), "$1 != TRUE");
440
- out = out.replace(new RegExp(`${scoped}\\s*<>\\s*0\\b`, "giu"), "$1 <> FALSE");
441
- out = out.replace(new RegExp(`${scoped}\\s*<>\\s*1\\b`, "giu"), "$1 <> TRUE");
442
- }
443
- return out;
444
- }
445
- function rewriteInsertOrIgnore(sql) {
446
- if (!/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu.test(sql)) {
447
- return sql;
448
- }
449
- const replaced = sql.replace(/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu, "INSERT INTO");
450
- return /\bON\s+CONFLICT\b/iu.test(replaced) ? replaced : appendClause(replaced, " ON CONFLICT DO NOTHING");
451
- }
452
- function rewriteInsertOrReplace(sql) {
453
- const match = /^\s*INSERT\s+OR\s+REPLACE\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)([\s\S]*)$/iu.exec(sql);
454
- if (!match) {
455
- return sql;
456
- }
457
- const rawTable = match[1];
458
- const rawColumns = match[2];
459
- const remainder = match[3];
460
- const tableName = unqualifiedTableName(rawTable);
461
- const conflictKeys = UPSERT_KEYS[tableName];
462
- if (!conflictKeys?.length) {
463
- return sql;
464
- }
465
- const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
466
- const updateColumns = columns.filter((col) => !conflictKeys.includes(col));
467
- const conflictTarget = conflictKeys.map(quotedIdentifier).join(", ");
468
- const updateClause = updateColumns.length === 0 ? " DO NOTHING" : ` DO UPDATE SET ${updateColumns.map((col) => `${quotedIdentifier(col)} = EXCLUDED.${quotedIdentifier(col)}`).join(", ")}`;
469
- return `INSERT INTO ${rawTable} (${rawColumns})${appendClause(remainder, ` ON CONFLICT (${conflictTarget})${updateClause}`)}`;
470
- }
471
- function rewriteSql(sql) {
472
- let out = sql;
473
- out = out.replace(/\bdatetime\(\s*['"]now['"]\s*\)/giu, "CURRENT_TIMESTAMP");
474
- out = out.replace(/\bvector32\s*\(\s*\?\s*\)/giu, "?");
475
- out = rewriteBooleanLiterals(out);
476
- out = rewriteInsertOrReplace(out);
477
- out = rewriteInsertOrIgnore(out);
478
- return stripTrailingSemicolon(out);
479
- }
480
- function toBoolean(value) {
481
- if (value === null || value === void 0) return value;
482
- if (typeof value === "boolean") return value;
483
- if (typeof value === "number") return value !== 0;
484
- if (typeof value === "bigint") return value !== 0n;
485
- if (typeof value === "string") {
486
- const normalized = value.trim().toLowerCase();
487
- if (normalized === "0" || normalized === "false") return false;
488
- if (normalized === "1" || normalized === "true") return true;
489
- }
490
- return Boolean(value);
491
- }
492
- function countQuestionMarks(sql, end) {
493
- let count = 0;
494
- let inSingle = false;
495
- let inDouble = false;
496
- let inLineComment = false;
497
- let inBlockComment = false;
498
- for (let i = 0; i < end; i++) {
499
- const ch = sql[i];
500
- const next = sql[i + 1];
501
- if (inLineComment) {
502
- if (ch === "\n") inLineComment = false;
503
- continue;
504
- }
505
- if (inBlockComment) {
506
- if (ch === "*" && next === "/") {
507
- inBlockComment = false;
508
- i += 1;
509
- }
510
- continue;
511
- }
512
- if (!inSingle && !inDouble && ch === "-" && next === "-") {
513
- inLineComment = true;
514
- i += 1;
515
- continue;
516
- }
517
- if (!inSingle && !inDouble && ch === "/" && next === "*") {
518
- inBlockComment = true;
519
- i += 1;
520
- continue;
521
- }
522
- if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
523
- inSingle = !inSingle;
524
- continue;
525
- }
526
- if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
527
- inDouble = !inDouble;
528
- continue;
529
- }
530
- if (!inSingle && !inDouble && ch === "?") {
531
- count += 1;
532
- }
533
- }
534
- return count;
535
- }
536
- function findBooleanPlaceholderIndexes(sql) {
537
- const indexes = /* @__PURE__ */ new Set();
538
- for (const column of BOOLEAN_COLUMN_NAMES) {
539
- const pattern = new RegExp(`(?:\\b[a-z_][a-z0-9_]*\\.)?${column}\\s*=\\s*\\?`, "giu");
540
- for (const match of sql.matchAll(pattern)) {
541
- const matchText = match[0];
542
- const qIndex = match.index + matchText.lastIndexOf("?");
543
- indexes.add(countQuestionMarks(sql, qIndex + 1));
544
- }
545
- }
546
- return indexes;
547
- }
548
- function coerceInsertBooleanArgs(sql, args) {
549
- const match = /^\s*INSERT(?:\s+OR\s+(?:IGNORE|REPLACE))?\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)/iu.exec(sql);
550
- if (!match) return;
551
- const rawTable = match[1];
552
- const rawColumns = match[2];
553
- const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
554
- if (!boolColumns?.size) return;
555
- const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
556
- for (const [index, column] of columns.entries()) {
557
- if (boolColumns.has(column) && index < args.length) {
558
- args[index] = toBoolean(args[index]);
559
- }
560
- }
561
- }
562
- function coerceUpdateBooleanArgs(sql, args) {
563
- const match = /^\s*UPDATE\s+([A-Za-z0-9_."]+)\s+SET\s+([\s\S]+?)(?:\s+WHERE\b|$)/iu.exec(sql);
564
- if (!match) return;
565
- const rawTable = match[1];
566
- const setClause = match[2];
567
- const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
568
- if (!boolColumns?.size) return;
569
- const assignments = setClause.split(",");
570
- let placeholderIndex = 0;
571
- for (const assignment of assignments) {
572
- if (!assignment.includes("?")) continue;
573
- placeholderIndex += 1;
574
- const colMatch = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*\?/iu.exec(assignment);
575
- if (colMatch && boolColumns.has(colMatch[1])) {
576
- args[placeholderIndex - 1] = toBoolean(args[placeholderIndex - 1]);
577
- }
578
- }
579
- }
580
- function coerceBooleanArgs(sql, args) {
581
- const nextArgs = [...args];
582
- coerceInsertBooleanArgs(sql, nextArgs);
583
- coerceUpdateBooleanArgs(sql, nextArgs);
584
- const placeholderIndexes = findBooleanPlaceholderIndexes(sql);
585
- for (const index of placeholderIndexes) {
586
- if (index > 0 && index <= nextArgs.length) {
587
- nextArgs[index - 1] = toBoolean(nextArgs[index - 1]);
588
- }
589
- }
590
- return nextArgs;
591
- }
592
- function convertQuestionMarksToDollarParams(sql) {
593
- let out = "";
594
- let placeholder = 0;
595
- let inSingle = false;
596
- let inDouble = false;
597
- let inLineComment = false;
598
- let inBlockComment = false;
599
- for (let i = 0; i < sql.length; i++) {
600
- const ch = sql[i];
601
- const next = sql[i + 1];
602
- if (inLineComment) {
603
- out += ch;
604
- if (ch === "\n") inLineComment = false;
605
- continue;
606
- }
607
- if (inBlockComment) {
608
- out += ch;
609
- if (ch === "*" && next === "/") {
610
- out += next;
611
- inBlockComment = false;
612
- i += 1;
613
- }
614
- continue;
615
- }
616
- if (!inSingle && !inDouble && ch === "-" && next === "-") {
617
- out += ch + next;
618
- inLineComment = true;
619
- i += 1;
620
- continue;
621
- }
622
- if (!inSingle && !inDouble && ch === "/" && next === "*") {
623
- out += ch + next;
624
- inBlockComment = true;
625
- i += 1;
626
- continue;
627
- }
628
- if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
629
- inSingle = !inSingle;
630
- out += ch;
631
- continue;
632
- }
633
- if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
634
- inDouble = !inDouble;
635
- out += ch;
636
- continue;
637
- }
638
- if (!inSingle && !inDouble && ch === "?") {
639
- placeholder += 1;
640
- out += `$${placeholder}`;
641
- continue;
642
- }
643
- out += ch;
644
- }
645
- return out;
646
- }
647
- function translateStatementForPostgres(stmt) {
648
- const normalized = normalizeStatement(stmt);
649
- if (normalized.kind === "named") {
650
- throw new Error("Named SQL parameters are not supported by the Prisma adapter.");
651
- }
652
- const rewrittenSql = rewriteSql(normalized.sql);
653
- const coercedArgs = coerceBooleanArgs(rewrittenSql, normalized.args);
654
- return {
655
- sql: convertQuestionMarksToDollarParams(rewrittenSql),
656
- args: coercedArgs
657
- };
658
- }
659
- function shouldBypassPostgres(stmt) {
660
- const normalized = normalizeStatement(stmt);
661
- if (normalized.kind === "named") {
662
- return true;
663
- }
664
- return IMMEDIATE_FALLBACK_PATTERNS.some((pattern) => pattern.test(normalized.sql));
665
- }
666
- function shouldFallbackOnError(error) {
667
- const message = error instanceof Error ? error.message : String(error);
668
- return /42P01|42883|42601|does not exist|syntax error|not supported|Named SQL parameters are not supported/iu.test(message);
669
- }
670
- function isReadQuery(sql) {
671
- const trimmed = sql.trimStart();
672
- return /^(SELECT|WITH|SHOW|EXPLAIN|VALUES)\b/iu.test(trimmed) || /\bRETURNING\b/iu.test(trimmed);
673
- }
674
- function buildRow(row, columns) {
675
- const values = columns.map((column) => row[column]);
676
- return Object.assign(values, row);
677
- }
678
- function buildResultSet(rows, rowsAffected = 0) {
679
- const columns = rows[0] ? Object.keys(rows[0]) : [];
680
- const resultRows = rows.map((row) => buildRow(row, columns));
681
- return {
682
- columns,
683
- columnTypes: columns.map(() => ""),
684
- rows: resultRows,
685
- rowsAffected,
686
- lastInsertRowid: void 0,
687
- toJSON() {
688
- return {
689
- columns,
690
- columnTypes: columns.map(() => ""),
691
- rows,
692
- rowsAffected,
693
- lastInsertRowid: void 0
694
- };
695
- }
696
- };
697
- }
698
- async function loadPrismaClient() {
699
- if (!prismaClientPromise) {
700
- prismaClientPromise = (async () => {
701
- const explicitPath = process.env.EXE_OS_PRISMA_CLIENT_PATH;
702
- if (explicitPath) {
703
- const module2 = await import(pathToFileURL(explicitPath).href);
704
- const PrismaClient2 = module2.PrismaClient ?? module2.default?.PrismaClient;
705
- if (!PrismaClient2) {
706
- throw new Error(`No PrismaClient export found at ${explicitPath}`);
707
- }
708
- return new PrismaClient2();
709
- }
710
- const exeDbRoot = process.env.EXE_DB_ROOT ?? path4.join(os3.homedir(), "exe-db");
711
- const requireFromExeDb = createRequire(path4.join(exeDbRoot, "package.json"));
712
- const prismaEntry = requireFromExeDb.resolve("@prisma/client");
713
- const module = await import(pathToFileURL(prismaEntry).href);
714
- const PrismaClient = module.PrismaClient ?? module.default?.PrismaClient;
715
- if (!PrismaClient) {
716
- throw new Error(`No PrismaClient export found in ${prismaEntry}`);
717
- }
718
- return new PrismaClient();
719
- })();
720
- }
721
- return prismaClientPromise;
722
- }
723
- async function ensureCompatibilityViews(prisma) {
724
- if (!compatibilityBootstrapPromise) {
725
- compatibilityBootstrapPromise = (async () => {
726
- for (const mapping of VIEW_MAPPINGS) {
727
- const relation = mapping.source.replace(/"/g, "");
728
- const rows = await prisma.$queryRawUnsafe(
729
- "SELECT to_regclass($1)::text AS regclass",
730
- relation
731
- );
732
- if (!rows[0]?.regclass) {
733
- continue;
734
- }
735
- await prisma.$executeRawUnsafe(
736
- `CREATE OR REPLACE VIEW public.${quotedIdentifier(mapping.view)} AS SELECT * FROM ${mapping.source}`
737
- );
738
- }
739
- })();
740
- }
741
- return compatibilityBootstrapPromise;
742
- }
743
- async function executeOnPrisma(executor, stmt) {
744
- const translated = translateStatementForPostgres(stmt);
745
- if (isReadQuery(translated.sql)) {
746
- const rows = await executor.$queryRawUnsafe(
747
- translated.sql,
748
- ...translated.args
749
- );
750
- return buildResultSet(rows, /\bRETURNING\b/iu.test(translated.sql) ? rows.length : 0);
751
- }
752
- const rowsAffected = await executor.$executeRawUnsafe(translated.sql, ...translated.args);
753
- return buildResultSet([], rowsAffected);
754
- }
755
- function splitSqlStatements(sql) {
756
- const parts = [];
757
- let current = "";
758
- let inSingle = false;
759
- let inDouble = false;
760
- let inLineComment = false;
761
- let inBlockComment = false;
762
- for (let i = 0; i < sql.length; i++) {
763
- const ch = sql[i];
764
- const next = sql[i + 1];
765
- if (inLineComment) {
766
- current += ch;
767
- if (ch === "\n") inLineComment = false;
768
- continue;
769
- }
770
- if (inBlockComment) {
771
- current += ch;
772
- if (ch === "*" && next === "/") {
773
- current += next;
774
- inBlockComment = false;
775
- i += 1;
776
- }
777
- continue;
778
- }
779
- if (!inSingle && !inDouble && ch === "-" && next === "-") {
780
- current += ch + next;
781
- inLineComment = true;
782
- i += 1;
783
- continue;
784
- }
785
- if (!inSingle && !inDouble && ch === "/" && next === "*") {
786
- current += ch + next;
787
- inBlockComment = true;
788
- i += 1;
789
- continue;
790
- }
791
- if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
792
- inSingle = !inSingle;
793
- current += ch;
794
- continue;
795
- }
796
- if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
797
- inDouble = !inDouble;
798
- current += ch;
799
- continue;
800
- }
801
- if (!inSingle && !inDouble && ch === ";") {
802
- if (current.trim()) {
803
- parts.push(current.trim());
804
- }
805
- current = "";
806
- continue;
807
- }
808
- current += ch;
809
- }
810
- if (current.trim()) {
811
- parts.push(current.trim());
812
- }
813
- return parts;
814
- }
815
- async function createPrismaDbAdapter(fallbackClient) {
816
- const prisma = await loadPrismaClient();
817
- await ensureCompatibilityViews(prisma);
818
- let closed = false;
819
- let adapter;
820
- const fallbackExecute = async (stmt, error) => {
821
- if (!fallbackClient) {
822
- if (error) throw error;
823
- throw new Error("No fallback SQLite client is available for this Prisma-routed query.");
824
- }
825
- if (error) {
826
- process.stderr.write(
827
- `[database-adapter] Falling back to SQLite: ${error instanceof Error ? error.message : String(error)}
828
- `
829
- );
830
- }
831
- return fallbackClient.execute(stmt);
832
- };
833
- adapter = {
834
- async execute(stmt) {
835
- if (shouldBypassPostgres(stmt)) {
836
- return fallbackExecute(stmt);
837
- }
838
- try {
839
- return await executeOnPrisma(prisma, stmt);
840
- } catch (error) {
841
- if (shouldFallbackOnError(error)) {
842
- return fallbackExecute(stmt, error);
843
- }
844
- throw error;
845
- }
846
- },
847
- async batch(stmts, mode) {
848
- if (stmts.some((stmt) => shouldBypassPostgres(stmt))) {
849
- if (!fallbackClient) {
850
- throw new Error("Cannot batch unsupported SQLite-only statements without a fallback client.");
851
- }
852
- return fallbackClient.batch(stmts, mode);
853
- }
854
- try {
855
- if (prisma.$transaction) {
856
- return await prisma.$transaction(async (tx) => {
857
- const results2 = [];
858
- for (const stmt of stmts) {
859
- results2.push(await executeOnPrisma(tx, stmt));
860
- }
861
- return results2;
862
- });
863
- }
864
- const results = [];
865
- for (const stmt of stmts) {
866
- results.push(await executeOnPrisma(prisma, stmt));
867
- }
868
- return results;
869
- } catch (error) {
870
- if (fallbackClient && shouldFallbackOnError(error)) {
871
- process.stderr.write(
872
- `[database-adapter] Falling back batch to SQLite: ${error instanceof Error ? error.message : String(error)}
873
- `
874
- );
875
- return fallbackClient.batch(stmts, mode);
876
- }
877
- throw error;
878
- }
879
- },
880
- async migrate(stmts) {
881
- if (fallbackClient) {
882
- return fallbackClient.migrate(stmts);
883
- }
884
- return adapter.batch(stmts, "deferred");
885
- },
886
- async transaction(mode) {
887
- if (!fallbackClient) {
888
- throw new Error("Interactive transactions are only supported on the SQLite fallback client.");
889
- }
890
- return fallbackClient.transaction(mode);
891
- },
892
- async executeMultiple(sql) {
893
- if (fallbackClient && shouldBypassPostgres(sql)) {
894
- return fallbackClient.executeMultiple(sql);
895
- }
896
- for (const statement of splitSqlStatements(sql)) {
897
- await adapter.execute(statement);
898
- }
899
- },
900
- async sync() {
901
- if (fallbackClient) {
902
- return fallbackClient.sync();
903
- }
904
- return { frame_no: 0, frames_synced: 0 };
905
- },
906
- close() {
907
- closed = true;
908
- prismaClientPromise = null;
909
- compatibilityBootstrapPromise = null;
910
- void prisma.$disconnect?.();
911
- },
912
- get closed() {
913
- return closed;
914
- },
915
- get protocol() {
916
- return "prisma-postgres";
917
- }
918
- };
919
- return adapter;
920
- }
921
- var VIEW_MAPPINGS, UPSERT_KEYS, BOOLEAN_COLUMNS_BY_TABLE, BOOLEAN_COLUMN_NAMES, IMMEDIATE_FALLBACK_PATTERNS, prismaClientPromise, compatibilityBootstrapPromise;
922
- var init_database_adapter = __esm({
923
- "src/lib/database-adapter.ts"() {
924
- "use strict";
925
- VIEW_MAPPINGS = [
926
- { view: "memories", source: "memory.memory_records" },
927
- { view: "tasks", source: "memory.tasks" },
928
- { view: "behaviors", source: "memory.behaviors" },
929
- { view: "entities", source: "memory.entities" },
930
- { view: "relationships", source: "memory.relationships" },
931
- { view: "entity_memories", source: "memory.entity_memories" },
932
- { view: "entity_aliases", source: "memory.entity_aliases" },
933
- { view: "notifications", source: "memory.notifications" },
934
- { view: "messages", source: "memory.messages" },
935
- { view: "users", source: "wiki.users" },
936
- { view: "workspaces", source: "wiki.workspaces" },
937
- { view: "workspace_users", source: "wiki.workspace_users" },
938
- { view: "documents", source: "wiki.workspace_documents" },
939
- { view: "chats", source: "wiki.workspace_chats" }
940
- ];
941
- UPSERT_KEYS = {
942
- memories: ["id"],
943
- tasks: ["id"],
944
- behaviors: ["id"],
945
- entities: ["id"],
946
- relationships: ["id"],
947
- entity_aliases: ["alias"],
948
- notifications: ["id"],
949
- messages: ["id"],
950
- users: ["id"],
951
- workspaces: ["id"],
952
- workspace_users: ["id"],
953
- documents: ["id"],
954
- chats: ["id"]
955
- };
956
- BOOLEAN_COLUMNS_BY_TABLE = {
957
- memories: /* @__PURE__ */ new Set(["has_error", "draft"]),
958
- behaviors: /* @__PURE__ */ new Set(["active"]),
959
- notifications: /* @__PURE__ */ new Set(["read"]),
960
- users: /* @__PURE__ */ new Set(["has_personal_memory"])
961
- };
962
- BOOLEAN_COLUMN_NAMES = new Set(
963
- Object.values(BOOLEAN_COLUMNS_BY_TABLE).flatMap((cols) => [...cols])
964
- );
965
- IMMEDIATE_FALLBACK_PATTERNS = [
966
- /\bPRAGMA\b/i,
967
- /\bsqlite_master\b/i,
968
- /(?:^|[.\s])(?:memories|conversations|entities)_fts\b/i,
969
- /\bMATCH\b/i,
970
- /\bvector_distance_cos\s*\(/i,
971
- /\bjson_extract\s*\(/i,
972
- /\bjulianday\s*\(/i,
973
- /\bstrftime\s*\(/i,
974
- /\blast_insert_rowid\s*\(/i
975
- ];
976
- prismaClientPromise = null;
977
- compatibilityBootstrapPromise = null;
978
- }
979
- });
980
-
981
- // src/lib/database.ts
982
- import { createClient } from "@libsql/client";
983
- async function initDatabase(config) {
984
- if (_walCheckpointTimer) {
985
- clearInterval(_walCheckpointTimer);
986
- _walCheckpointTimer = null;
987
- }
988
- if (_daemonClient) {
989
- _daemonClient.close();
990
- _daemonClient = null;
991
- }
992
- if (_adapterClient && _adapterClient !== _resilientClient) {
993
- _adapterClient.close();
994
- }
995
- _adapterClient = null;
996
- if (_client) {
997
- _client.close();
998
- _client = null;
999
- _resilientClient = null;
1000
- }
1001
- const opts = {
1002
- url: `file:${config.dbPath}`
1003
- };
1004
- if (config.encryptionKey) {
1005
- opts.encryptionKey = config.encryptionKey;
1006
- }
1007
- _client = createClient(opts);
1008
- _resilientClient = wrapWithRetry(_client);
1009
- _adapterClient = _resilientClient;
1010
- _client.execute("PRAGMA busy_timeout = 30000").catch(() => {
1011
- });
1012
- _client.execute("PRAGMA journal_mode = WAL").catch(() => {
1013
- });
1014
- if (_walCheckpointTimer) clearInterval(_walCheckpointTimer);
1015
- _walCheckpointTimer = setInterval(() => {
1016
- _client?.execute("PRAGMA wal_checkpoint(PASSIVE)").catch(() => {
1017
- });
1018
- }, 3e4);
1019
- _walCheckpointTimer.unref();
1020
- if (process.env.DATABASE_URL) {
1021
- _adapterClient = await createPrismaDbAdapter(_resilientClient);
1022
- }
1023
- }
1024
- function isInitialized() {
1025
- return _adapterClient !== null || _client !== null;
1026
- }
1027
- function getClient() {
1028
- if (!_adapterClient) {
1029
- throw new Error("Database client not initialized. Call initDatabase() first.");
1030
- }
1031
- if (process.env.DATABASE_URL) {
1032
- return _adapterClient;
1033
- }
1034
- if (process.env.EXE_IS_DAEMON === "1") {
1035
- return _resilientClient;
1036
- }
1037
- if (_daemonClient && _daemonClient._isDaemonActive()) {
1038
- return _daemonClient;
1039
- }
1040
- return _resilientClient;
1041
- }
1042
- function getRawClient() {
1043
- if (!_client) {
1044
- throw new Error("Database client not initialized. Call initDatabase() first.");
1045
- }
1046
- return _client;
1047
- }
1048
- async function ensureSchema() {
1049
- const client = getRawClient();
1050
- await client.execute("PRAGMA journal_mode = WAL");
1051
- await client.execute("PRAGMA busy_timeout = 30000");
1052
- await client.execute("PRAGMA wal_autocheckpoint = 1000");
1053
- try {
1054
- await client.execute("PRAGMA libsql_vector_search_ef = 128");
1055
- } catch {
1056
- }
1057
- await client.executeMultiple(`
1058
- CREATE TABLE IF NOT EXISTS memories (
1059
- id TEXT PRIMARY KEY,
1060
- agent_id TEXT NOT NULL,
1061
- agent_role TEXT NOT NULL,
1062
- session_id TEXT NOT NULL,
1063
- timestamp TEXT NOT NULL,
1064
- tool_name TEXT NOT NULL,
1065
- project_name TEXT NOT NULL,
1066
- has_error INTEGER NOT NULL DEFAULT 0,
1067
- raw_text TEXT NOT NULL,
1068
- vector F32_BLOB(1024),
1069
- version INTEGER NOT NULL DEFAULT 0
1070
- );
1071
-
1072
- CREATE INDEX IF NOT EXISTS idx_memories_agent
1073
- ON memories(agent_id);
1074
-
1075
- CREATE INDEX IF NOT EXISTS idx_memories_timestamp
1076
- ON memories(timestamp);
1077
-
1078
- CREATE INDEX IF NOT EXISTS idx_memories_session
1079
- ON memories(session_id);
1080
-
1081
- CREATE INDEX IF NOT EXISTS idx_memories_project
1082
- ON memories(project_name);
1083
-
1084
- CREATE INDEX IF NOT EXISTS idx_memories_tool
1085
- ON memories(tool_name);
1086
-
1087
- CREATE INDEX IF NOT EXISTS idx_memories_version
1088
- ON memories(version);
1089
-
1090
- CREATE INDEX IF NOT EXISTS idx_memories_agent_project
1091
- ON memories(agent_id, project_name);
1092
- `);
1093
- await client.executeMultiple(`
1094
- CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
1095
- raw_text,
1096
- content='memories',
1097
- content_rowid='rowid'
1098
- );
1099
-
1100
- CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
1101
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1102
- END;
1103
-
1104
- CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
1105
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1106
- END;
1107
-
1108
- CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
1109
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1110
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1111
- END;
1112
- `);
1113
- await client.executeMultiple(`
1114
- CREATE TABLE IF NOT EXISTS sync_meta (
1115
- key TEXT PRIMARY KEY,
1116
- value TEXT NOT NULL
1117
- );
1118
- `);
1119
- await client.executeMultiple(`
1120
- CREATE TABLE IF NOT EXISTS tasks (
1121
- id TEXT PRIMARY KEY,
1122
- title TEXT NOT NULL,
1123
- assigned_to TEXT NOT NULL,
1124
- assigned_by TEXT NOT NULL,
1125
- project_name TEXT NOT NULL,
1126
- priority TEXT NOT NULL DEFAULT 'p1',
1127
- status TEXT NOT NULL DEFAULT 'open',
1128
- task_file TEXT,
1129
- created_at TEXT NOT NULL,
1130
- updated_at TEXT NOT NULL
1131
- );
1132
-
1133
- CREATE INDEX IF NOT EXISTS idx_tasks_assignee_status
1134
- ON tasks(assigned_to, status);
1135
- `);
1136
- await client.executeMultiple(`
1137
- CREATE TABLE IF NOT EXISTS behaviors (
1138
- id TEXT PRIMARY KEY,
1139
- agent_id TEXT NOT NULL,
1140
- project_name TEXT,
1141
- domain TEXT,
1142
- content TEXT NOT NULL,
1143
- active INTEGER NOT NULL DEFAULT 1,
1144
- created_at TEXT NOT NULL,
1145
- updated_at TEXT NOT NULL
1146
- );
1147
-
1148
- CREATE INDEX IF NOT EXISTS idx_behaviors_agent
1149
- ON behaviors(agent_id, active);
1150
- `);
1151
- try {
1152
- const coordinatorName = getCoordinatorName();
1153
- const existing = await client.execute({
1154
- sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = ?",
1155
- args: [coordinatorName]
1156
- });
1157
- if (Number(existing.rows[0]?.cnt) === 0) {
1158
- const seededAt = "2026-03-25T00:00:00Z";
1159
- for (const [domain, content] of [
1160
- ["workflow", `Don't ask "keep going?" \u2014 just keep executing phases/plans autonomously`],
1161
- ["tool-use", "Always use create_task MCP tool, never write .md files directly for task creation"],
1162
- ["workflow", "Auto-start reviewing when idle and reviews are pending \u2014 never ask founder for permission"]
1163
- ]) {
1164
- await client.execute({
1165
- sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
1166
- VALUES (hex(randomblob(16)), ?, NULL, ?, ?, 1, ?, ?)`,
1167
- args: [coordinatorName, domain, content, seededAt, seededAt]
1168
- });
1169
- }
1170
- }
1171
- } catch {
1172
- }
1173
- try {
1174
- await client.execute({
1175
- sql: `ALTER TABLE behaviors ADD COLUMN priority TEXT DEFAULT 'p1'`,
1176
- args: []
1177
- });
1178
- } catch {
1179
- }
1180
- try {
1181
- await client.execute({
1182
- sql: `ALTER TABLE tasks ADD COLUMN blocked_by TEXT`,
1183
- args: []
1184
- });
1185
- } catch {
1186
- }
1187
- try {
1188
- await client.execute({
1189
- sql: `ALTER TABLE tasks ADD COLUMN parent_task_id TEXT`,
1190
- args: []
1191
- });
1192
- } catch {
1193
- }
1194
- try {
1195
- await client.execute({
1196
- sql: `CREATE INDEX IF NOT EXISTS idx_tasks_parent_task_id
1197
- ON tasks(parent_task_id)
1198
- WHERE parent_task_id IS NOT NULL`,
1199
- args: []
1200
- });
1201
- } catch {
1202
- }
1203
- try {
1204
- await client.execute({
1205
- sql: `UPDATE tasks SET status = 'done' WHERE status = 'completed'`,
1206
- args: []
1207
- });
1208
- } catch {
1209
- }
1210
- try {
1211
- await client.execute({
1212
- sql: `ALTER TABLE tasks ADD COLUMN reviewer TEXT`,
1213
- args: []
1214
- });
1215
- } catch {
1216
- }
1217
- try {
1218
- await client.execute({
1219
- sql: `ALTER TABLE tasks ADD COLUMN context TEXT`,
1220
- args: []
1221
- });
1222
- } catch {
1223
- }
1224
- try {
1225
- await client.execute({
1226
- sql: `ALTER TABLE tasks ADD COLUMN result TEXT`,
1227
- args: []
1228
- });
1229
- } catch {
1230
- }
1231
- try {
1232
- await client.execute({
1233
- sql: `ALTER TABLE tasks ADD COLUMN assigned_tmux TEXT`,
1234
- args: []
1235
- });
1236
- } catch {
1237
- }
1238
- try {
1239
- await client.execute({
1240
- sql: `ALTER TABLE tasks ADD COLUMN checkpoint TEXT`,
1241
- args: []
1242
- });
1243
- } catch {
1244
- }
1245
- try {
1246
- await client.execute({
1247
- sql: `ALTER TABLE tasks ADD COLUMN checkpoint_count INTEGER NOT NULL DEFAULT 0`,
1248
- args: []
1249
- });
1250
- } catch {
1251
- }
1252
- try {
1253
- await client.execute({
1254
- sql: `ALTER TABLE tasks ADD COLUMN complexity TEXT NOT NULL DEFAULT 'standard'`,
1255
- args: []
1256
- });
1257
- } catch {
1258
- }
1259
- try {
1260
- await client.execute({
1261
- sql: `ALTER TABLE tasks ADD COLUMN session_scope TEXT`,
1262
- args: []
1263
- });
1264
- } catch {
1265
- }
1266
- try {
1267
- await client.execute({
1268
- sql: `ALTER TABLE memories ADD COLUMN task_id TEXT`,
1269
- args: []
1270
- });
1271
- } catch {
1272
- }
1273
- try {
1274
- await client.execute({
1275
- sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
1276
- args: []
1277
- });
1278
- } catch {
1279
- }
1280
- try {
1281
- await client.execute({
1282
- sql: `ALTER TABLE memories ADD COLUMN author_device_id TEXT`,
1283
- args: []
1284
- });
1285
- } catch {
1286
- }
1287
- try {
1288
- await client.execute({
1289
- sql: `ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'`,
1290
- args: []
1291
- });
1292
- } catch {
1293
- }
1294
- await client.executeMultiple(`
1295
- CREATE TABLE IF NOT EXISTS consolidations (
1296
- id TEXT PRIMARY KEY,
1297
- consolidated_memory_id TEXT NOT NULL,
1298
- source_memory_id TEXT NOT NULL,
1299
- created_at TEXT NOT NULL
1300
- );
1301
-
1302
- CREATE INDEX IF NOT EXISTS idx_consolidations_source
1303
- ON consolidations(source_memory_id);
1304
-
1305
- CREATE INDEX IF NOT EXISTS idx_consolidations_consolidated
1306
- ON consolidations(consolidated_memory_id);
1307
- `);
1308
- await client.executeMultiple(`
1309
- CREATE TABLE IF NOT EXISTS reminders (
1310
- id TEXT PRIMARY KEY,
1311
- text TEXT NOT NULL,
1312
- created_at TEXT NOT NULL,
1313
- due_date TEXT,
1314
- completed_at TEXT
1315
- );
1316
- `);
1317
- await client.executeMultiple(`
1318
- CREATE TABLE IF NOT EXISTS notifications (
1319
- id TEXT PRIMARY KEY,
1320
- agent_id TEXT NOT NULL,
1321
- agent_role TEXT NOT NULL,
1322
- event TEXT NOT NULL,
1323
- project TEXT NOT NULL,
1324
- summary TEXT NOT NULL,
1325
- task_file TEXT,
1326
- session_scope TEXT,
1327
- read INTEGER NOT NULL DEFAULT 0,
1328
- created_at TEXT NOT NULL
1329
- );
1330
-
1331
- CREATE INDEX IF NOT EXISTS idx_notifications_read
1332
- ON notifications(read);
1333
-
1334
- CREATE INDEX IF NOT EXISTS idx_notifications_agent
1335
- ON notifications(agent_id, session_scope);
1336
-
1337
- CREATE INDEX IF NOT EXISTS idx_notifications_task_file
1338
- ON notifications(task_file);
1339
- `);
1340
- await client.executeMultiple(`
1341
- CREATE TABLE IF NOT EXISTS schedules (
1342
- id TEXT PRIMARY KEY,
1343
- cron TEXT NOT NULL,
1344
- description TEXT NOT NULL,
1345
- job_type TEXT NOT NULL DEFAULT 'report',
1346
- prompt TEXT,
1347
- assigned_to TEXT,
1348
- project_name TEXT,
1349
- active INTEGER NOT NULL DEFAULT 1,
1350
- use_crontab INTEGER NOT NULL DEFAULT 0,
1351
- created_at TEXT NOT NULL
1352
- );
1353
- `);
1354
- await client.executeMultiple(`
1355
- CREATE TABLE IF NOT EXISTS device_registry (
1356
- device_id TEXT PRIMARY KEY,
1357
- friendly_name TEXT NOT NULL,
1358
- hostname TEXT NOT NULL,
1359
- projects TEXT NOT NULL DEFAULT '[]',
1360
- agents TEXT NOT NULL DEFAULT '[]',
1361
- connected INTEGER DEFAULT 0,
1362
- last_seen TEXT NOT NULL
1363
- );
1364
- `);
1365
- await client.executeMultiple(`
1366
- CREATE TABLE IF NOT EXISTS messages (
1367
- id TEXT PRIMARY KEY,
1368
- from_agent TEXT NOT NULL,
1369
- from_device TEXT NOT NULL DEFAULT 'local',
1370
- target_agent TEXT NOT NULL,
1371
- target_project TEXT,
1372
- target_device TEXT NOT NULL DEFAULT 'local',
1373
- session_scope TEXT,
1374
- content TEXT NOT NULL,
1375
- priority TEXT DEFAULT 'normal',
1376
- status TEXT DEFAULT 'pending',
1377
- server_seq INTEGER,
1378
- retry_count INTEGER DEFAULT 0,
1379
- created_at TEXT NOT NULL,
1380
- delivered_at TEXT,
1381
- processed_at TEXT,
1382
- failed_at TEXT,
1383
- failure_reason TEXT
1384
- );
1385
-
1386
- CREATE INDEX IF NOT EXISTS idx_messages_target
1387
- ON messages(target_agent, session_scope, status);
1388
-
1389
- CREATE INDEX IF NOT EXISTS idx_messages_conversation_order
1390
- ON messages(target_agent, session_scope, from_agent, server_seq);
1391
- `);
1392
- try {
1393
- await client.execute({
1394
- sql: `ALTER TABLE notifications ADD COLUMN session_scope TEXT`,
1395
- args: []
1396
- });
1397
- } catch {
1398
- }
1399
- try {
1400
- await client.execute({
1401
- sql: `ALTER TABLE messages ADD COLUMN session_scope TEXT`,
1402
- args: []
1403
- });
1404
- } catch {
1405
- }
1406
- await client.executeMultiple(`
1407
- CREATE INDEX IF NOT EXISTS idx_notifications_agent_scope_read
1408
- ON notifications(agent_id, session_scope, read, created_at);
1409
-
1410
- CREATE INDEX IF NOT EXISTS idx_messages_target_scope_status
1411
- ON messages(target_agent, session_scope, status, created_at);
1412
- `);
1413
- try {
1414
- await client.execute({
1415
- sql: `UPDATE memories SET project_name = 'exe-create' WHERE project_name = 'web'`,
1416
- args: []
1417
- });
1418
- await client.execute({
1419
- sql: `UPDATE memories SET project_name = 'exe-os' WHERE project_name = 'worker'`,
1420
- args: []
1421
- });
1422
- await client.execute({
1423
- sql: `UPDATE tasks SET project_name = 'exe-create' WHERE project_name = 'web'`,
1424
- args: []
1425
- });
1426
- await client.execute({
1427
- sql: `UPDATE tasks SET project_name = 'exe-os' WHERE project_name = 'worker'`,
1428
- args: []
1429
- });
1430
- } catch {
1431
- }
1432
- await client.executeMultiple(`
1433
- CREATE TABLE IF NOT EXISTS trajectories (
1434
- id TEXT PRIMARY KEY,
1435
- task_id TEXT NOT NULL,
1436
- agent_id TEXT NOT NULL,
1437
- project_name TEXT NOT NULL,
1438
- task_title TEXT NOT NULL,
1439
- signature TEXT NOT NULL,
1440
- signature_hash TEXT NOT NULL,
1441
- tool_count INTEGER NOT NULL,
1442
- skill_id TEXT,
1443
- created_at TEXT NOT NULL
1444
- );
1445
-
1446
- CREATE INDEX IF NOT EXISTS idx_trajectories_hash
1447
- ON trajectories(signature_hash);
1448
-
1449
- CREATE INDEX IF NOT EXISTS idx_trajectories_agent
1450
- ON trajectories(agent_id);
1451
- `);
1452
- try {
1453
- await client.execute("ALTER TABLE trajectories ADD COLUMN skill_id TEXT");
1454
- } catch {
1455
- }
1456
- await client.executeMultiple(`
1457
- CREATE TABLE IF NOT EXISTS consolidations (
1458
- id TEXT PRIMARY KEY,
1459
- consolidated_memory_id TEXT NOT NULL,
1460
- source_memory_id TEXT NOT NULL,
1461
- created_at TEXT NOT NULL
1462
- );
1463
-
1464
- CREATE INDEX IF NOT EXISTS idx_consolidations_source
1465
- ON consolidations(source_memory_id);
1466
- `);
1467
- await client.executeMultiple(`
1468
- CREATE TABLE IF NOT EXISTS audit_trail (
1469
- id INTEGER PRIMARY KEY AUTOINCREMENT,
1470
- timestamp TEXT NOT NULL,
1471
- session_id TEXT NOT NULL,
1472
- agent_id TEXT NOT NULL,
1473
- tool TEXT NOT NULL,
1474
- input TEXT,
1475
- decision TEXT NOT NULL,
1476
- reason TEXT,
1477
- is_customer_facing INTEGER NOT NULL DEFAULT 0
1478
- );
1479
-
1480
- CREATE INDEX IF NOT EXISTS idx_audit_trail_agent
1481
- ON audit_trail(agent_id, timestamp);
1482
-
1483
- CREATE INDEX IF NOT EXISTS idx_audit_trail_session
1484
- ON audit_trail(session_id);
1485
- `);
1486
- try {
1487
- await client.execute({
1488
- sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
1489
- args: []
1490
- });
1491
- } catch {
1492
- }
1493
- try {
1494
- await client.execute({
1495
- sql: `ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5`,
1496
- args: []
1497
- });
1498
- } catch {
1499
- }
1500
- try {
1501
- await client.execute({
1502
- sql: `ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'`,
1503
- args: []
1504
- });
1505
- } catch {
1506
- }
1507
- try {
1508
- await client.execute({
1509
- sql: `ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7`,
1510
- args: []
1511
- });
1512
- } catch {
1513
- }
1514
- try {
1515
- await client.execute({
1516
- sql: `ALTER TABLE memories ADD COLUMN last_accessed TEXT`,
1517
- args: []
1518
- });
1519
- } catch {
1520
- }
1521
- try {
1522
- await client.execute({
1523
- sql: `UPDATE memories SET last_accessed = timestamp WHERE last_accessed IS NULL`,
1524
- args: []
1525
- });
1526
- } catch {
1527
- }
1528
- try {
1529
- await client.execute({
1530
- sql: `ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0`,
1531
- args: []
1532
- });
1533
- } catch {
1534
- }
1535
- try {
1536
- await client.execute({
1537
- sql: `ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0`,
1538
- args: []
1539
- });
1540
- } catch {
1541
- }
1542
- for (const col of [
1543
- "ALTER TABLE memories ADD COLUMN content_hash TEXT",
1544
- "ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT"
1545
- ]) {
1546
- try {
1547
- await client.execute(col);
1548
- } catch {
1549
- }
1550
- }
1551
- try {
1552
- await client.execute(
1553
- `CREATE INDEX IF NOT EXISTS idx_memories_content_hash ON memories(content_hash, agent_id)`
1554
- );
1555
- } catch {
1556
- }
1557
- await client.executeMultiple(`
1558
- CREATE TABLE IF NOT EXISTS entities (
1559
- id TEXT PRIMARY KEY,
1560
- name TEXT NOT NULL,
1561
- type TEXT NOT NULL,
1562
- first_seen TEXT NOT NULL,
1563
- last_seen TEXT NOT NULL,
1564
- properties TEXT DEFAULT '{}',
1565
- UNIQUE(name, type)
1566
- );
1567
-
1568
- CREATE TABLE IF NOT EXISTS relationships (
1569
- id TEXT PRIMARY KEY,
1570
- source_entity_id TEXT NOT NULL,
1571
- target_entity_id TEXT NOT NULL,
1572
- type TEXT NOT NULL,
1573
- weight REAL DEFAULT 1.0,
1574
- timestamp TEXT NOT NULL,
1575
- properties TEXT DEFAULT '{}',
1576
- UNIQUE(source_entity_id, target_entity_id, type)
1577
- );
1578
-
1579
- CREATE TABLE IF NOT EXISTS entity_memories (
1580
- entity_id TEXT NOT NULL,
1581
- memory_id TEXT NOT NULL,
1582
- PRIMARY KEY (entity_id, memory_id)
1583
- );
1584
-
1585
- CREATE TABLE IF NOT EXISTS relationship_memories (
1586
- relationship_id TEXT NOT NULL,
1587
- memory_id TEXT NOT NULL,
1588
- PRIMARY KEY (relationship_id, memory_id)
1589
- );
1590
-
1591
- CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
1592
- CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type);
1593
- CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_entity_id);
1594
- CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_entity_id);
1595
-
1596
- CREATE TABLE IF NOT EXISTS hyperedges (
1597
- id TEXT PRIMARY KEY,
1598
- label TEXT NOT NULL,
1599
- relation TEXT NOT NULL,
1600
- confidence REAL DEFAULT 1.0,
1601
- timestamp TEXT NOT NULL
1602
- );
1603
-
1604
- CREATE TABLE IF NOT EXISTS hyperedge_nodes (
1605
- hyperedge_id TEXT NOT NULL,
1606
- entity_id TEXT NOT NULL,
1607
- PRIMARY KEY (hyperedge_id, entity_id)
1608
- );
1609
-
1610
- CREATE VIRTUAL TABLE IF NOT EXISTS entities_fts USING fts5(
1611
- name,
1612
- content=entities,
1613
- content_rowid=rowid
1614
- );
1615
-
1616
- CREATE TRIGGER IF NOT EXISTS entities_fts_ai AFTER INSERT ON entities BEGIN
1617
- INSERT INTO entities_fts(rowid, name) VALUES (new.rowid, new.name);
1618
- END;
1619
-
1620
- CREATE TRIGGER IF NOT EXISTS entities_fts_ad AFTER DELETE ON entities BEGIN
1621
- INSERT INTO entities_fts(entities_fts, rowid, name) VALUES('delete', old.rowid, old.name);
1622
- END;
1623
-
1624
- CREATE TRIGGER IF NOT EXISTS entities_fts_au AFTER UPDATE ON entities BEGIN
1625
- INSERT INTO entities_fts(entities_fts, rowid, name) VALUES('delete', old.rowid, old.name);
1626
- INSERT INTO entities_fts(rowid, name) VALUES (new.rowid, new.name);
1627
- END;
1628
- `);
1629
- try {
1630
- await client.execute("INSERT INTO entities_fts(entities_fts) VALUES('rebuild')");
1631
- } catch {
1632
- }
1633
- await client.executeMultiple(`
1634
- CREATE TABLE IF NOT EXISTS entity_aliases (
1635
- alias TEXT NOT NULL PRIMARY KEY,
1636
- canonical_entity_id TEXT NOT NULL
1637
- );
1638
- CREATE INDEX IF NOT EXISTS idx_entity_aliases_canonical ON entity_aliases(canonical_entity_id);
1639
- `);
1640
- for (const col of [
1641
- "ALTER TABLE relationships ADD COLUMN confidence REAL DEFAULT 1.0",
1642
- "ALTER TABLE relationships ADD COLUMN confidence_label TEXT DEFAULT 'extracted'"
1643
- ]) {
1644
- try {
1645
- await client.execute(col);
1646
- } catch {
1647
- }
1648
- }
1649
- try {
1650
- await client.execute(
1651
- `CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)`
1652
- );
1653
- } catch {
1654
- }
1655
- await client.executeMultiple(`
1656
- CREATE TABLE IF NOT EXISTS identity (
1657
- id INTEGER PRIMARY KEY AUTOINCREMENT,
1658
- agent_id TEXT NOT NULL UNIQUE,
1659
- content_hash TEXT NOT NULL,
1660
- updated_at TEXT NOT NULL,
1661
- updated_by TEXT NOT NULL
1662
- );
1663
-
1664
- CREATE INDEX IF NOT EXISTS idx_identity_agent ON identity(agent_id);
1665
- `);
1666
- await client.executeMultiple(`
1667
- CREATE TABLE IF NOT EXISTS chat_history (
1668
- id INTEGER PRIMARY KEY AUTOINCREMENT,
1669
- session_id TEXT NOT NULL,
1670
- role TEXT NOT NULL,
1671
- content TEXT NOT NULL,
1672
- tool_name TEXT,
1673
- tool_id TEXT,
1674
- is_error INTEGER NOT NULL DEFAULT 0,
1675
- timestamp INTEGER NOT NULL
1676
- );
1677
-
1678
- CREATE INDEX IF NOT EXISTS idx_chat_history_session
1679
- ON chat_history(session_id, id);
1680
- `);
1681
- await client.executeMultiple(`
1682
- CREATE TABLE IF NOT EXISTS workspaces (
1683
- id TEXT PRIMARY KEY,
1684
- slug TEXT NOT NULL UNIQUE,
1685
- name TEXT NOT NULL,
1686
- owner_agent_id TEXT,
1687
- created_at TEXT NOT NULL,
1688
- metadata TEXT
1689
- );
1690
-
1691
- CREATE INDEX IF NOT EXISTS idx_workspaces_slug
1692
- ON workspaces(slug);
1693
- `);
1694
- await client.executeMultiple(`
1695
- CREATE TABLE IF NOT EXISTS documents (
1696
- id TEXT PRIMARY KEY,
1697
- workspace_id TEXT NOT NULL,
1698
- filename TEXT NOT NULL,
1699
- mime TEXT,
1700
- source_type TEXT,
1701
- user_id TEXT,
1702
- uploaded_at TEXT NOT NULL,
1703
- metadata TEXT,
1704
- FOREIGN KEY (workspace_id) REFERENCES workspaces(id)
1705
- );
1706
-
1707
- CREATE INDEX IF NOT EXISTS idx_documents_workspace
1708
- ON documents(workspace_id);
1709
-
1710
- CREATE INDEX IF NOT EXISTS idx_documents_user
1711
- ON documents(user_id);
1712
- `);
1713
- for (const column of [
1714
- "workspace_id TEXT",
1715
- "document_id TEXT",
1716
- "user_id TEXT",
1717
- "char_offset INTEGER",
1718
- "page_number INTEGER"
1719
- ]) {
1720
- try {
1721
- await client.execute({
1722
- sql: `ALTER TABLE memories ADD COLUMN ${column}`,
1723
- args: []
1724
- });
1725
- } catch {
1726
- }
1727
- }
1728
- for (const col of [
1729
- "ALTER TABLE memories ADD COLUMN source_path TEXT",
1730
- "ALTER TABLE memories ADD COLUMN source_type TEXT DEFAULT 'text'"
1731
- ]) {
1732
- try {
1733
- await client.execute(col);
1734
- } catch {
1735
- }
1736
- }
1737
- await client.executeMultiple(`
1738
- CREATE INDEX IF NOT EXISTS idx_memories_workspace
1739
- ON memories(workspace_id);
1740
-
1741
- CREATE INDEX IF NOT EXISTS idx_memories_document
1742
- ON memories(document_id);
1743
-
1744
- CREATE INDEX IF NOT EXISTS idx_memories_user
1745
- ON memories(user_id);
1746
- `);
1747
- await client.executeMultiple(`
1748
- CREATE TABLE IF NOT EXISTS session_kills (
1749
- id TEXT PRIMARY KEY,
1750
- session_name TEXT NOT NULL,
1751
- agent_id TEXT NOT NULL,
1752
- killed_at TIMESTAMP NOT NULL,
1753
- reason TEXT NOT NULL,
1754
- ticks_idle INTEGER,
1755
- estimated_tokens_saved INTEGER
1756
- );
1757
-
1758
- CREATE INDEX IF NOT EXISTS idx_session_kills_killed_at
1759
- ON session_kills(killed_at);
1760
-
1761
- CREATE INDEX IF NOT EXISTS idx_session_kills_agent
1762
- ON session_kills(agent_id);
1763
- `);
1764
- await client.execute(`
1765
- CREATE TABLE IF NOT EXISTS global_procedures (
1766
- id TEXT PRIMARY KEY,
1767
- title TEXT NOT NULL,
1768
- content TEXT NOT NULL,
1769
- priority TEXT NOT NULL DEFAULT 'p0',
1770
- domain TEXT,
1771
- active INTEGER NOT NULL DEFAULT 1,
1772
- created_at TEXT NOT NULL,
1773
- updated_at TEXT NOT NULL
1774
- )
1775
- `);
1776
- await client.executeMultiple(`
1777
- CREATE TABLE IF NOT EXISTS conversations (
1778
- id TEXT PRIMARY KEY,
1779
- platform TEXT NOT NULL,
1780
- external_id TEXT,
1781
- sender_id TEXT NOT NULL,
1782
- sender_name TEXT,
1783
- sender_phone TEXT,
1784
- sender_email TEXT,
1785
- recipient_id TEXT,
1786
- channel_id TEXT NOT NULL,
1787
- thread_id TEXT,
1788
- reply_to_id TEXT,
1789
- content_text TEXT,
1790
- content_media TEXT,
1791
- content_metadata TEXT,
1792
- agent_response TEXT,
1793
- agent_name TEXT,
1794
- timestamp TEXT NOT NULL,
1795
- ingested_at TEXT NOT NULL
1796
- );
1797
-
1798
- CREATE INDEX IF NOT EXISTS idx_conversations_platform
1799
- ON conversations(platform);
1800
-
1801
- CREATE INDEX IF NOT EXISTS idx_conversations_sender
1802
- ON conversations(sender_id);
1803
-
1804
- CREATE INDEX IF NOT EXISTS idx_conversations_timestamp
1805
- ON conversations(timestamp);
1806
-
1807
- CREATE INDEX IF NOT EXISTS idx_conversations_thread
1808
- ON conversations(thread_id);
1809
-
1810
- CREATE INDEX IF NOT EXISTS idx_conversations_channel
1811
- ON conversations(channel_id);
1812
- `);
1813
- await client.executeMultiple(`
1814
- CREATE TABLE IF NOT EXISTS session_agent_map (
1815
- session_uuid TEXT PRIMARY KEY,
1816
- agent_id TEXT NOT NULL,
1817
- session_name TEXT,
1818
- task_id TEXT,
1819
- project_name TEXT,
1820
- started_at TEXT NOT NULL,
1821
- cache_cold_count INTEGER NOT NULL DEFAULT 0
1822
- );
1823
-
1824
- CREATE INDEX IF NOT EXISTS idx_session_agent_map_agent
1825
- ON session_agent_map(agent_id);
1826
- `);
1827
- await client.executeMultiple(`
1828
- CREATE TABLE IF NOT EXISTS agent_file_reads (
1829
- session_uuid TEXT NOT NULL,
1830
- agent_id TEXT NOT NULL,
1831
- file_path TEXT NOT NULL,
1832
- read_at TEXT NOT NULL,
1833
- commit_hash TEXT,
1834
- PRIMARY KEY (session_uuid, file_path)
1835
- );
1836
-
1837
- CREATE INDEX IF NOT EXISTS idx_agent_file_reads_agent_read_at
1838
- ON agent_file_reads(agent_id, read_at);
1839
- `);
1840
- try {
1841
- const mapCount = await client.execute({ sql: `SELECT COUNT(*) as cnt FROM session_agent_map`, args: [] });
1842
- if (Number(mapCount.rows[0]?.cnt ?? 0) === 0) {
1843
- await client.execute({
1844
- sql: `INSERT OR IGNORE INTO session_agent_map (session_uuid, agent_id, session_name, started_at)
1845
- SELECT session_id, agent_id, '', MIN(timestamp)
1846
- FROM memories
1847
- WHERE session_id IS NOT NULL AND session_id != '' AND agent_id IS NOT NULL AND agent_id != ''
1848
- GROUP BY session_id, agent_id`,
1849
- args: []
1850
- });
1851
- }
1852
- } catch {
1853
- }
1854
- try {
1855
- await client.execute({
1856
- sql: `ALTER TABLE session_agent_map ADD COLUMN cache_cold_count INTEGER NOT NULL DEFAULT 0`,
1857
- args: []
1858
- });
1859
- } catch {
1860
- }
1861
- try {
1862
- await client.execute({
1863
- sql: `ALTER TABLE tasks ADD COLUMN budget_tokens INTEGER`,
1864
- args: []
1865
- });
1866
- } catch {
1867
- }
1868
- try {
1869
- await client.execute({
1870
- sql: `ALTER TABLE tasks ADD COLUMN budget_fallback_model TEXT`,
1871
- args: []
1872
- });
1873
- } catch {
1874
- }
1875
- try {
1876
- await client.execute({
1877
- sql: `ALTER TABLE tasks ADD COLUMN tokens_used INTEGER DEFAULT 0`,
1878
- args: []
1879
- });
1880
- } catch {
1881
- }
1882
- try {
1883
- await client.execute({
1884
- sql: `ALTER TABLE tasks ADD COLUMN tokens_warned_at INTEGER`,
1885
- args: []
1886
- });
1887
- } catch {
1888
- }
1889
- await client.executeMultiple(`
1890
- CREATE VIRTUAL TABLE IF NOT EXISTS conversations_fts USING fts5(
1891
- content_text,
1892
- sender_name,
1893
- agent_response,
1894
- content='conversations',
1895
- content_rowid='rowid'
1896
- );
1897
-
1898
- CREATE TRIGGER IF NOT EXISTS conversations_fts_ai AFTER INSERT ON conversations BEGIN
1899
- INSERT INTO conversations_fts(rowid, content_text, sender_name, agent_response)
1900
- VALUES (new.rowid, new.content_text, new.sender_name, new.agent_response);
1901
- END;
1902
-
1903
- CREATE TRIGGER IF NOT EXISTS conversations_fts_ad AFTER DELETE ON conversations BEGIN
1904
- INSERT INTO conversations_fts(conversations_fts, rowid, content_text, sender_name, agent_response)
1905
- VALUES('delete', old.rowid, old.content_text, old.sender_name, old.agent_response);
1906
- END;
1907
-
1908
- CREATE TRIGGER IF NOT EXISTS conversations_fts_au AFTER UPDATE ON conversations BEGIN
1909
- INSERT INTO conversations_fts(conversations_fts, rowid, content_text, sender_name, agent_response)
1910
- VALUES('delete', old.rowid, old.content_text, old.sender_name, old.agent_response);
1911
- INSERT INTO conversations_fts(rowid, content_text, sender_name, agent_response)
1912
- VALUES (new.rowid, new.content_text, new.sender_name, new.agent_response);
1913
- END;
1914
- `);
1915
- try {
1916
- await client.execute({
1917
- sql: `ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3`,
1918
- args: []
1919
- });
1920
- } catch {
1921
- }
1922
- try {
1923
- await client.execute(
1924
- `CREATE INDEX IF NOT EXISTS idx_memories_tier ON memories(tier)`
1925
- );
1926
- } catch {
1927
- }
1928
- try {
1929
- await client.execute({
1930
- sql: `UPDATE memories SET tier = 1 WHERE tool_name = 'commit_to_long_term_memory' AND importance >= 8 AND tier = 3`,
1931
- args: []
1932
- });
1933
- await client.execute({
1934
- sql: `UPDATE memories SET tier = 2 WHERE tool_name IN ('store_memory', 'manual') AND importance >= 5 AND tier = 3`,
1935
- args: []
1936
- });
1937
- } catch {
1938
- }
1939
- try {
1940
- await client.execute({
1941
- sql: `ALTER TABLE memories ADD COLUMN supersedes_id TEXT`,
1942
- args: []
1943
- });
1944
- } catch {
1945
- }
1946
- try {
1947
- await client.execute(
1948
- `CREATE INDEX IF NOT EXISTS idx_memories_supersedes ON memories(supersedes_id) WHERE supersedes_id IS NOT NULL`
1949
- );
1950
- } catch {
1951
- }
1952
- for (const col of [
1953
- "ALTER TABLE tasks ADD COLUMN checkpoint TEXT",
1954
- "ALTER TABLE tasks ADD COLUMN checkpoint_count INTEGER DEFAULT 0"
1955
- ]) {
1956
- try {
1957
- await client.execute(col);
1958
- } catch {
1959
- }
1960
- }
1961
- try {
1962
- await client.execute({
1963
- sql: `ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0`,
1964
- args: []
1965
- });
1966
- } catch {
1967
- }
1968
- try {
1969
- await client.execute(
1970
- `CREATE INDEX IF NOT EXISTS idx_memories_draft ON memories(draft) WHERE draft = 1`
1971
- );
1972
- } catch {
1973
- }
1974
- try {
1975
- await client.execute({
1976
- sql: `ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'`,
1977
- args: []
1978
- });
1979
- } catch {
1980
- }
1981
- try {
1982
- await client.execute(
1983
- `CREATE INDEX IF NOT EXISTS idx_memories_type ON memories(memory_type)`
1984
- );
1985
- } catch {
1986
- }
1987
- try {
1988
- await client.execute({
1989
- sql: `ALTER TABLE memories ADD COLUMN trajectory TEXT`,
1990
- args: []
1991
- });
1992
- } catch {
1993
- }
1994
- for (const col of [
1995
- "ALTER TABLE memories ADD COLUMN intent TEXT",
1996
- "ALTER TABLE memories ADD COLUMN outcome TEXT",
1997
- "ALTER TABLE memories ADD COLUMN domain TEXT",
1998
- "ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
1999
- "ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
2000
- "ALTER TABLE memories ADD COLUMN chain_position TEXT",
2001
- "ALTER TABLE memories ADD COLUMN review_status TEXT",
2002
- "ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
2003
- "ALTER TABLE memories ADD COLUMN file_paths TEXT",
2004
- "ALTER TABLE memories ADD COLUMN commit_hash TEXT",
2005
- "ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
2006
- "ALTER TABLE memories ADD COLUMN token_cost REAL",
2007
- "ALTER TABLE memories ADD COLUMN audience TEXT",
2008
- "ALTER TABLE memories ADD COLUMN language_type TEXT",
2009
- "ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
2010
- ]) {
2011
- try {
2012
- await client.execute(col);
2013
- } catch {
2014
- }
2015
- }
2016
- try {
2017
- await client.execute({
2018
- sql: `UPDATE tasks SET status = 'closed' WHERE status = 'done' AND result IS NOT NULL`,
2019
- args: []
2020
- });
2021
- } catch {
2022
- }
2023
- }
2024
- var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso;
2025
- var init_database = __esm({
2026
- "src/lib/database.ts"() {
2027
- "use strict";
2028
- init_db_retry();
2029
- init_employees();
2030
- init_database_adapter();
2031
- _client = null;
2032
- _resilientClient = null;
2033
- _walCheckpointTimer = null;
2034
- _daemonClient = null;
2035
- _adapterClient = null;
2036
- initTurso = initDatabase;
2037
- }
2038
- });
2039
-
2040
- // src/lib/shard-manager.ts
2041
- var shard_manager_exports = {};
2042
- __export(shard_manager_exports, {
2043
- disposeShards: () => disposeShards,
2044
- ensureShardSchema: () => ensureShardSchema,
2045
- getOpenShardCount: () => getOpenShardCount,
2046
- getReadyShardClient: () => getReadyShardClient,
2047
- getShardClient: () => getShardClient,
2048
- getShardsDir: () => getShardsDir,
2049
- initShardManager: () => initShardManager,
2050
- isShardingEnabled: () => isShardingEnabled,
2051
- listShards: () => listShards,
2052
- shardExists: () => shardExists
2053
- });
2054
- import path6 from "path";
2055
- import { existsSync as existsSync5, mkdirSync as mkdirSync2, readdirSync } from "fs";
2056
- import { createClient as createClient2 } from "@libsql/client";
2057
- function initShardManager(encryptionKey) {
2058
- _encryptionKey = encryptionKey;
2059
- if (!existsSync5(SHARDS_DIR)) {
2060
- mkdirSync2(SHARDS_DIR, { recursive: true });
2061
- }
2062
- _shardingEnabled = true;
2063
- if (_evictionTimer) clearInterval(_evictionTimer);
2064
- _evictionTimer = setInterval(evictIdleShards, EVICTION_INTERVAL_MS);
2065
- _evictionTimer.unref();
2066
- }
2067
- function isShardingEnabled() {
2068
- return _shardingEnabled;
2069
- }
2070
- function getShardsDir() {
2071
- return SHARDS_DIR;
2072
- }
2073
- function getShardClient(projectName) {
2074
- if (!_encryptionKey) {
2075
- throw new Error("Shard manager not initialized. Call initShardManager() first.");
2076
- }
2077
- const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
2078
- if (!safeName) {
2079
- throw new Error(`Invalid project name for shard: "${projectName}"`);
2080
- }
2081
- const cached = _shards.get(safeName);
2082
- if (cached) {
2083
- _shardLastAccess.set(safeName, Date.now());
2084
- return cached;
2085
- }
2086
- while (_shards.size >= MAX_OPEN_SHARDS) {
2087
- evictLRU();
2088
- }
2089
- const dbPath = path6.join(SHARDS_DIR, `${safeName}.db`);
2090
- const client = createClient2({
2091
- url: `file:${dbPath}`,
2092
- encryptionKey: _encryptionKey
2093
- });
2094
- _shards.set(safeName, client);
2095
- _shardLastAccess.set(safeName, Date.now());
2096
- return client;
2097
- }
2098
- function shardExists(projectName) {
2099
- const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
2100
- return existsSync5(path6.join(SHARDS_DIR, `${safeName}.db`));
2101
- }
2102
- function listShards() {
2103
- if (!existsSync5(SHARDS_DIR)) return [];
2104
- return readdirSync(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
2105
- }
2106
- async function ensureShardSchema(client) {
2107
- await client.execute("PRAGMA journal_mode = WAL");
2108
- await client.execute("PRAGMA busy_timeout = 30000");
2109
- try {
2110
- await client.execute("PRAGMA libsql_vector_search_ef = 128");
2111
- } catch {
2112
- }
2113
- await client.executeMultiple(`
2114
- CREATE TABLE IF NOT EXISTS memories (
2115
- id TEXT PRIMARY KEY,
2116
- agent_id TEXT NOT NULL,
2117
- agent_role TEXT NOT NULL,
2118
- session_id TEXT NOT NULL,
2119
- timestamp TEXT NOT NULL,
2120
- tool_name TEXT NOT NULL,
2121
- project_name TEXT NOT NULL,
2122
- has_error INTEGER NOT NULL DEFAULT 0,
2123
- raw_text TEXT NOT NULL,
2124
- vector F32_BLOB(1024),
2125
- version INTEGER NOT NULL DEFAULT 0
2126
- );
2127
-
2128
- CREATE INDEX IF NOT EXISTS idx_memories_agent ON memories(agent_id);
2129
- CREATE INDEX IF NOT EXISTS idx_memories_timestamp ON memories(timestamp);
2130
- CREATE INDEX IF NOT EXISTS idx_memories_agent_project ON memories(agent_id, project_name);
2131
- `);
2132
- await client.executeMultiple(`
2133
- CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
2134
- raw_text,
2135
- content='memories',
2136
- content_rowid='rowid'
2137
- );
2138
-
2139
- CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
2140
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
2141
- END;
2142
-
2143
- CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
2144
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
2145
- END;
2146
-
2147
- CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
2148
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
2149
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
2150
- END;
2151
- `);
2152
- for (const col of [
2153
- "ALTER TABLE memories ADD COLUMN task_id TEXT",
2154
- "ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0",
2155
- "ALTER TABLE memories ADD COLUMN author_device_id TEXT",
2156
- "ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'",
2157
- "ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5",
2158
- "ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'",
2159
- "ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0",
2160
- "ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0",
2161
- "ALTER TABLE memories ADD COLUMN content_hash TEXT",
2162
- "ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT",
2163
- "ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7",
2164
- "ALTER TABLE memories ADD COLUMN last_accessed TEXT",
2165
- // Wiki linkage columns (must match database.ts)
2166
- "ALTER TABLE memories ADD COLUMN workspace_id TEXT",
2167
- "ALTER TABLE memories ADD COLUMN document_id TEXT",
2168
- "ALTER TABLE memories ADD COLUMN user_id TEXT",
2169
- "ALTER TABLE memories ADD COLUMN char_offset INTEGER",
2170
- "ALTER TABLE memories ADD COLUMN page_number INTEGER",
2171
- // Source provenance columns (must match database.ts)
2172
- "ALTER TABLE memories ADD COLUMN source_path TEXT",
2173
- "ALTER TABLE memories ADD COLUMN source_type TEXT DEFAULT 'text'",
2174
- "ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3",
2175
- "ALTER TABLE memories ADD COLUMN supersedes_id TEXT",
2176
- // MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
2177
- "ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
2178
- "ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
2179
- "ALTER TABLE memories ADD COLUMN trajectory TEXT",
2180
- // Metadata enrichment columns (must match database.ts)
2181
- "ALTER TABLE memories ADD COLUMN intent TEXT",
2182
- "ALTER TABLE memories ADD COLUMN outcome TEXT",
2183
- "ALTER TABLE memories ADD COLUMN domain TEXT",
2184
- "ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
2185
- "ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
2186
- "ALTER TABLE memories ADD COLUMN chain_position TEXT",
2187
- "ALTER TABLE memories ADD COLUMN review_status TEXT",
2188
- "ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
2189
- "ALTER TABLE memories ADD COLUMN file_paths TEXT",
2190
- "ALTER TABLE memories ADD COLUMN commit_hash TEXT",
2191
- "ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
2192
- "ALTER TABLE memories ADD COLUMN token_cost REAL",
2193
- "ALTER TABLE memories ADD COLUMN audience TEXT",
2194
- "ALTER TABLE memories ADD COLUMN language_type TEXT",
2195
- "ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
2196
- ]) {
2197
- try {
2198
- await client.execute(col);
2199
- } catch {
2200
- }
2201
- }
2202
- for (const idx of [
2203
- "CREATE INDEX IF NOT EXISTS idx_memories_tier ON memories(tier)",
2204
- "CREATE INDEX IF NOT EXISTS idx_memories_supersedes ON memories(supersedes_id) WHERE supersedes_id IS NOT NULL"
2205
- ]) {
2206
- try {
2207
- await client.execute(idx);
2208
- } catch {
2209
- }
2210
- }
2211
- try {
2212
- await client.execute("CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)");
2213
- } catch {
2214
- }
2215
- for (const idx of [
2216
- "CREATE INDEX IF NOT EXISTS idx_memories_workspace ON memories(workspace_id)",
2217
- "CREATE INDEX IF NOT EXISTS idx_memories_document ON memories(document_id)",
2218
- "CREATE INDEX IF NOT EXISTS idx_memories_user ON memories(user_id)"
2219
- ]) {
2220
- try {
2221
- await client.execute(idx);
2222
- } catch {
2223
- }
2224
- }
2225
- await client.executeMultiple(`
2226
- CREATE TABLE IF NOT EXISTS entities (
2227
- id TEXT PRIMARY KEY,
2228
- name TEXT NOT NULL,
2229
- type TEXT NOT NULL,
2230
- first_seen TEXT NOT NULL,
2231
- last_seen TEXT NOT NULL,
2232
- properties TEXT DEFAULT '{}',
2233
- UNIQUE(name, type)
2234
- );
2235
-
2236
- CREATE TABLE IF NOT EXISTS relationships (
2237
- id TEXT PRIMARY KEY,
2238
- source_entity_id TEXT NOT NULL,
2239
- target_entity_id TEXT NOT NULL,
2240
- type TEXT NOT NULL,
2241
- weight REAL DEFAULT 1.0,
2242
- timestamp TEXT NOT NULL,
2243
- properties TEXT DEFAULT '{}',
2244
- UNIQUE(source_entity_id, target_entity_id, type)
2245
- );
2246
-
2247
- CREATE TABLE IF NOT EXISTS entity_memories (
2248
- entity_id TEXT NOT NULL,
2249
- memory_id TEXT NOT NULL,
2250
- PRIMARY KEY (entity_id, memory_id)
2251
- );
2252
-
2253
- CREATE TABLE IF NOT EXISTS relationship_memories (
2254
- relationship_id TEXT NOT NULL,
2255
- memory_id TEXT NOT NULL,
2256
- PRIMARY KEY (relationship_id, memory_id)
2257
- );
2258
-
2259
- CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
2260
- CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type);
2261
- CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_entity_id);
2262
- CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_entity_id);
2263
- CREATE INDEX IF NOT EXISTS idx_relationships_type ON relationships(type);
2264
-
2265
- CREATE TABLE IF NOT EXISTS hyperedges (
2266
- id TEXT PRIMARY KEY,
2267
- label TEXT NOT NULL,
2268
- relation TEXT NOT NULL,
2269
- confidence REAL DEFAULT 1.0,
2270
- timestamp TEXT NOT NULL
2271
- );
2272
-
2273
- CREATE TABLE IF NOT EXISTS hyperedge_nodes (
2274
- hyperedge_id TEXT NOT NULL,
2275
- entity_id TEXT NOT NULL,
2276
- PRIMARY KEY (hyperedge_id, entity_id)
2277
- );
2278
- `);
2279
- for (const col of [
2280
- "ALTER TABLE relationships ADD COLUMN confidence REAL DEFAULT 1.0",
2281
- "ALTER TABLE relationships ADD COLUMN confidence_label TEXT DEFAULT 'extracted'"
2282
- ]) {
2283
- try {
2284
- await client.execute(col);
2285
- } catch {
2286
- }
2287
- }
2288
- }
2289
- async function getReadyShardClient(projectName) {
2290
- const client = getShardClient(projectName);
2291
- await ensureShardSchema(client);
2292
- return client;
2293
- }
2294
- function evictLRU() {
2295
- let oldest = null;
2296
- let oldestTime = Infinity;
2297
- for (const [name, time] of _shardLastAccess) {
2298
- if (time < oldestTime) {
2299
- oldestTime = time;
2300
- oldest = name;
2301
- }
2302
- }
2303
- if (oldest) {
2304
- const client = _shards.get(oldest);
2305
- if (client) {
2306
- client.close();
2307
- }
2308
- _shards.delete(oldest);
2309
- _shardLastAccess.delete(oldest);
2310
- }
2311
- }
2312
- function evictIdleShards() {
2313
- const now = Date.now();
2314
- const toEvict = [];
2315
- for (const [name, lastAccess] of _shardLastAccess) {
2316
- if (now - lastAccess > SHARD_IDLE_MS) {
2317
- toEvict.push(name);
2318
- }
2319
- }
2320
- for (const name of toEvict) {
2321
- const client = _shards.get(name);
2322
- if (client) {
2323
- client.close();
2324
- }
2325
- _shards.delete(name);
2326
- _shardLastAccess.delete(name);
2327
- }
2328
- }
2329
- function getOpenShardCount() {
2330
- return _shards.size;
2331
- }
2332
- function disposeShards() {
2333
- if (_evictionTimer) {
2334
- clearInterval(_evictionTimer);
2335
- _evictionTimer = null;
2336
- }
2337
- for (const [, client] of _shards) {
2338
- client.close();
2339
- }
2340
- _shards.clear();
2341
- _shardLastAccess.clear();
2342
- _shardingEnabled = false;
2343
- _encryptionKey = null;
2344
- }
2345
- var SHARDS_DIR, SHARD_IDLE_MS, MAX_OPEN_SHARDS, EVICTION_INTERVAL_MS, _shards, _shardLastAccess, _evictionTimer, _encryptionKey, _shardingEnabled;
2346
- var init_shard_manager = __esm({
2347
- "src/lib/shard-manager.ts"() {
2348
- "use strict";
2349
- init_config();
2350
- SHARDS_DIR = path6.join(EXE_AI_DIR, "shards");
2351
- SHARD_IDLE_MS = 5 * 60 * 1e3;
2352
- MAX_OPEN_SHARDS = 10;
2353
- EVICTION_INTERVAL_MS = 60 * 1e3;
2354
- _shards = /* @__PURE__ */ new Map();
2355
- _shardLastAccess = /* @__PURE__ */ new Map();
2356
- _evictionTimer = null;
2357
- _encryptionKey = null;
2358
- _shardingEnabled = false;
2359
- }
2360
- });
2361
-
2362
- // src/lib/platform-procedures.ts
2363
- var PLATFORM_PROCEDURES, PLATFORM_PROCEDURE_TITLES;
2364
- var init_platform_procedures = __esm({
2365
- "src/lib/platform-procedures.ts"() {
2366
- "use strict";
2367
- PLATFORM_PROCEDURES = [
2368
- // --- Foundation: what is exe-os ---
2369
- {
2370
- title: "What is exe-os \u2014 the operating model every agent must understand",
2371
- domain: "architecture",
2372
- priority: "p0",
2373
- content: "Exe OS is an AI employee operating system. A founder runs 5-10 AI agents as a real org: COO, CTO, CMO, engineers, and content production specialists. Each agent has identity, expertise, and experience layers \u2014 persistent memory that makes them better over time. All data is local-first, E2EE, owned by the user. The MCP server is the ONLY data interface \u2014 never access the DB directly."
2374
- },
2375
- {
2376
- title: "Mode 1 \u2014 how exe-os runs inside Claude Code",
2377
- domain: "architecture",
2378
- priority: "p0",
2379
- content: "Mode 1: exe-os runs AS hooks + MCP + skills inside Claude Code, Codex, or OpenCode. The founder picks their default tool at setup. The COO manages employees in tmux sessions. Each coordinator session is a separate window/project. Employees run in their own tmux panes via create_task auto-spawn. The founder talks to the COO; the COO orchestrates the team. The tool is the shell, exe-os is the brain."
2380
- },
2381
- {
2382
- title: "Sessions explained \u2014 coordinator session names and projects",
2383
- domain: "architecture",
2384
- priority: "p0",
2385
- content: "Each coordinator session is an isolated project session. One might be exe-os development, another might be exe-wiki. Each session spawns its own employees using {employee}-{coordinatorSession}. Sessions share the same memory DB but tasks are scoped to the session that created them. A founder can run multiple projects simultaneously. Sessions never interfere with each other."
2386
- },
2387
- {
2388
- title: "Runtime settings \u2014 COO can view and change tools per agent",
2389
- domain: "workflow",
2390
- priority: "p1",
2391
- content: "exe-os supports three tools: Claude Code (Anthropic), Codex (OpenAI), and OpenCode (open source, 75+ providers). Each agent can use a different tool and model. COO uses set_agent_config MCP tool to view or change settings. Call with no args to show all agents. Call with agent_id + runtime + model to change. Users can also run `exe-os settings` from terminal for interactive arrow-key selection."
2392
- },
2393
- // --- Hierarchy and dispatch ---
2394
- {
2395
- title: "Chain of command \u2014 who talks to whom",
2396
- domain: "workflow",
2397
- priority: "p0",
2398
- content: "Founder -> COO -> CTO/CMO. CTO -> engineers. CMO -> content production. Never skip levels: the COO does not bypass managers for specialist work. Specialists report to their manager. If you need cross-team info, use ask_team_memory \u2014 don't read other agents' task folders. Each level owns dispatch downward and review upward."
2399
- },
2400
- {
2401
- title: "Single dispatch path \u2014 create_task only",
2402
- domain: "workflow",
2403
- priority: "p0",
2404
- content: "create_task is the ONLY way to dispatch work to another agent. No direct ensureEmployee calls, no manual tmux spawns, no send_message for actionable work. create_task \u2192 system auto-spawns \u2192 session correctly named. ONE PATH. No backdoors. No exceptions."
2405
- },
2406
- // --- Session isolation ---
2407
- {
2408
- title: "Session scoping \u2014 stay in your coordinator boundary",
2409
- domain: "security",
2410
- priority: "p0",
2411
- content: "Session scoping is mandatory. Managers dispatch to workers within their own coordinator session ONLY. Employee sessions use {employee}-{coordinatorSession}. Cross-session dispatch is blocked by the system. Verify session names before dispatch. Tasks are scoped to the creating coordinator session."
2412
- },
2413
- {
2414
- title: "Session isolation \u2014 never touch another session's work",
2415
- domain: "workflow",
2416
- priority: "p0",
2417
- content: "Sessions are isolated. A coordinator session owns ONLY tasks it dispatched. (1) Never close/update/cancel tasks from another coordinator session. (2) Never review work from a different session \u2014 report that it belongs to another session and skip. (3) Ignore other sessions' items in list_tasks results. (4) Employees inherit session: employee sessions work ONLY on their parent coordinator session's tasks. Cross-session work is a system violation."
2418
- },
2419
- // --- Engineering: session scoping in code ---
2420
- {
2421
- title: "Three-dimensional scoping \u2014 session, project, role \u2014 enforced in every query",
2422
- domain: "architecture",
2423
- priority: "p0",
2424
- content: "Every DB query, notification, review count, and task operation MUST be scoped on 3 dimensions: (1) Session \u2014 filter by session_scope matching the current coordinator session. (2) Project \u2014 filter by project_name. (3) Role \u2014 agents only see data at their hierarchy level. When writing ANY function that touches tasks, reviews, messages, or notifications: always accept a sessionScope parameter and pass it to the SQL WHERE clause. Unscoped queries are bugs. Test by running 2+ coordinator sessions simultaneously."
2425
- },
2426
- // --- Hard constraints ---
2427
- {
2428
- title: "What you CANNOT do in exe-os \u2014 hard constraints",
2429
- domain: "security",
2430
- priority: "p0",
2431
- content: "NEVER: (1) Access the database directly \u2014 it's SQLCipher encrypted, always fails. Use MCP tools only. (2) Manually spawn tmux sessions \u2014 create_task handles it. (3) Run git checkout main \u2014 agents work in worktrees. (4) Modify another agent's in-progress task. (5) Push to remote \u2014 the COO reviews and pushes. (6) Skip update_task(done) \u2014 it's the ONLY way your work gets reviewed. (7) Run git init."
2432
- },
2433
- // --- Operations ---
2434
- {
2435
- title: "Managers must supervise deployed workers",
2436
- domain: "workflow",
2437
- priority: "p0",
2438
- content: `Every manager (COO/CTO/CMO) who dispatches work to a worker MUST actively monitor them. Check tmux capture-pane every 10 minutes. Verify they're working, not stuck. If idle at prompt with in_progress task \u2192 send intercom. If stuck \u2192 unblock or escalate. "Standing by" without checking is negligence.`
2439
- },
2440
- {
2441
- title: "COO boot health check \u2014 memory, cloud sync, daemon on every launch",
2442
- domain: "workflow",
2443
- priority: "p0",
2444
- content: "On every /exe boot, COO MUST check system health BEFORE other work: (1) daemon \u2014 is exed PID alive, (2) cloud sync \u2014 grep workers.log for recent cloud-sync errors, (3) memory count \u2014 total in DB, (4) sync delta \u2014 local vs cloud storage_bytes. Report as 4-line status table. If ANY check fails, surface to founder immediately. Do not proceed to tasks until health confirmed."
2445
- },
2446
- {
2447
- title: "exe-build-adv mandatory for 3+ files",
2448
- domain: "workflow",
2449
- priority: "p0",
2450
- content: "exe-build-adv is MANDATORY for ALL work touching 3+ files. Run /exe-build-adv --auto BEFORE implementation. Pipeline: Spec \u2192 AC \u2192 Tests \u2192 Evaluate \u2192 Fix. No multi-file feature ships without pipeline artifacts. No exceptions \u2014 managers reject work without them."
2451
- },
2452
- {
2453
- title: "Desktop and TUI are the same product",
2454
- domain: "architecture",
2455
- priority: "p0",
2456
- content: "Desktop and TUI are the SAME product in different renderers. Same data contracts, same interactions, same acceptance criteria. Desktop tab specs in ARCHITECTURE.md ARE the TUI specs. When building TUI, cross-reference Desktop spec. Different tab names, identical behavior. Never treat them as separate products."
2457
- },
2458
- // --- Orchestration golden path ---
2459
- {
2460
- title: "Task lifecycle \u2014 the golden path every agent follows",
2461
- domain: "workflow",
2462
- priority: "p0",
2463
- content: "create_task is dispatch + delivery. Task lifecycle: open \u2192 in_progress (you start) \u2192 done (update_task when finished) \u2192 needs_review (reviewer nudged) \u2192 closed (COO only via close_task). DB is the reliable delivery \u2014 intercom is just a speedup nudge. If you finish a task, self-chain: check for next task immediately (step 7). Never wait for a nudge. Never say 'standing by.'"
2464
- },
2465
- {
2466
- title: "Intercom is a speedup, not delivery \u2014 DB is the source of truth",
2467
- domain: "architecture",
2468
- priority: "p0",
2469
- 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."
2470
- }
2471
- ];
2472
- PLATFORM_PROCEDURE_TITLES = new Set(
2473
- PLATFORM_PROCEDURES.map((p) => p.title)
2474
- );
2475
- }
2476
- });
2477
-
2478
- // src/lib/global-procedures.ts
2479
- var global_procedures_exports = {};
2480
- __export(global_procedures_exports, {
2481
- deactivateGlobalProcedure: () => deactivateGlobalProcedure,
2482
- getGlobalProceduresBlock: () => getGlobalProceduresBlock,
2483
- loadGlobalProcedures: () => loadGlobalProcedures,
2484
- storeGlobalProcedure: () => storeGlobalProcedure
2485
- });
2486
- import { randomUUID } from "crypto";
2487
- async function loadGlobalProcedures() {
2488
- const client = getClient();
2489
- const result = await client.execute({
2490
- sql: "SELECT * FROM global_procedures WHERE active = 1 ORDER BY priority ASC, created_at ASC",
2491
- args: []
2492
- });
2493
- const allRows = result.rows;
2494
- const customerOnly = allRows.filter((p) => !PLATFORM_PROCEDURE_TITLES.has(p.title));
2495
- if (customerOnly.length > 0) {
2496
- _customerCache = customerOnly.map((p) => `### ${p.title}
2497
- ${p.content}`).join("\n\n");
2498
- } else {
2499
- _customerCache = "";
2500
- }
2501
- _cacheLoaded = true;
2502
- return customerOnly;
2503
- }
2504
- function getGlobalProceduresBlock() {
2505
- const sections = [];
2506
- if (_platformCache) sections.push(_platformCache);
2507
- if (_cacheLoaded && _customerCache) sections.push(_customerCache);
2508
- if (sections.length === 0) return "";
2509
- return `## Organization-Wide Procedures (MANDATORY \u2014 supersedes all other rules)
2510
-
2511
- ${sections.join("\n\n")}
2512
- `;
2513
- }
2514
- async function storeGlobalProcedure(input) {
2515
- const id = randomUUID();
2516
- const now = (/* @__PURE__ */ new Date()).toISOString();
2517
- const client = getClient();
2518
- await client.execute({
2519
- sql: `INSERT INTO global_procedures (id, title, content, priority, domain, active, created_at, updated_at)
2520
- VALUES (?, ?, ?, ?, ?, 1, ?, ?)`,
2521
- args: [id, input.title, input.content, input.priority ?? "p0", input.domain ?? null, now, now]
2522
- });
2523
- await loadGlobalProcedures();
2524
- return id;
2525
- }
2526
- async function deactivateGlobalProcedure(id) {
2527
- const now = (/* @__PURE__ */ new Date()).toISOString();
2528
- const client = getClient();
2529
- const result = await client.execute({
2530
- sql: "UPDATE global_procedures SET active = 0, updated_at = ? WHERE id = ?",
2531
- args: [now, id]
2532
- });
2533
- await loadGlobalProcedures();
2534
- return result.rowsAffected > 0;
2535
- }
2536
- var _customerCache, _cacheLoaded, _platformCache;
2537
- var init_global_procedures = __esm({
2538
- "src/lib/global-procedures.ts"() {
2539
- "use strict";
2540
- init_database();
2541
- init_platform_procedures();
2542
- _customerCache = "";
2543
- _cacheLoaded = false;
2544
- _platformCache = PLATFORM_PROCEDURES.map((p) => `### ${p.title}
2545
- ${p.content}`).join("\n\n");
2546
- }
2547
- });
2548
-
2549
- // src/lib/daemon-auth.ts
2550
- import crypto from "crypto";
2551
- import path9 from "path";
2552
- import { existsSync as existsSync8, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
2553
- function normalizeToken(token) {
2554
- if (!token) return null;
2555
- const trimmed = token.trim();
2556
- return trimmed.length > 0 ? trimmed : null;
2557
- }
2558
- function readDaemonToken() {
2559
- try {
2560
- if (!existsSync8(DAEMON_TOKEN_PATH)) return null;
2561
- return normalizeToken(readFileSync5(DAEMON_TOKEN_PATH, "utf8"));
2562
- } catch {
2563
- return null;
2564
- }
2565
- }
2566
- function ensureDaemonToken(seed) {
2567
- const existing = readDaemonToken();
2568
- if (existing) return existing;
2569
- const token = normalizeToken(seed) ?? crypto.randomBytes(32).toString("hex");
2570
- ensurePrivateDirSync(EXE_AI_DIR);
2571
- writeFileSync3(DAEMON_TOKEN_PATH, `${token}
2572
- `, "utf8");
2573
- enforcePrivateFileSync(DAEMON_TOKEN_PATH);
2574
- return token;
2575
- }
2576
- var DAEMON_TOKEN_PATH;
2577
- var init_daemon_auth = __esm({
2578
- "src/lib/daemon-auth.ts"() {
2579
- "use strict";
2580
- init_config();
2581
- init_secure_files();
2582
- DAEMON_TOKEN_PATH = path9.join(EXE_AI_DIR, "exed.token");
2583
- }
2584
- });
2585
-
2586
- // src/lib/exe-daemon-client.ts
2587
- import net from "net";
2588
- import os6 from "os";
2589
- import { spawn } from "child_process";
2590
- import { randomUUID as randomUUID3 } from "crypto";
2591
- import { existsSync as existsSync9, unlinkSync as unlinkSync2, readFileSync as readFileSync6, openSync, closeSync, statSync } from "fs";
2592
- import path10 from "path";
2593
- import { fileURLToPath } from "url";
2594
- function handleData(chunk) {
2595
- _buffer += chunk.toString();
2596
- if (_buffer.length > MAX_BUFFER) {
2597
- _buffer = "";
2598
- return;
2599
- }
2600
- let newlineIdx;
2601
- while ((newlineIdx = _buffer.indexOf("\n")) !== -1) {
2602
- const line = _buffer.slice(0, newlineIdx).trim();
2603
- _buffer = _buffer.slice(newlineIdx + 1);
2604
- if (!line) continue;
2605
- try {
2606
- const response = JSON.parse(line);
2607
- const id = response.id;
2608
- if (!id) continue;
2609
- const entry = _pending.get(id);
2610
- if (entry) {
2611
- clearTimeout(entry.timer);
2612
- _pending.delete(id);
2613
- entry.resolve(response);
2614
- }
2615
- } catch {
2616
- }
2617
- }
2618
- }
2619
- function cleanupStaleFiles() {
2620
- if (existsSync9(PID_PATH)) {
2621
- try {
2622
- const pid = parseInt(readFileSync6(PID_PATH, "utf8").trim(), 10);
2623
- if (pid > 0) {
2624
- try {
2625
- process.kill(pid, 0);
2626
- return;
2627
- } catch {
2628
- }
2629
- }
2630
- } catch {
2631
- }
2632
- try {
2633
- unlinkSync2(PID_PATH);
2634
- } catch {
2635
- }
2636
- try {
2637
- unlinkSync2(SOCKET_PATH);
2638
- } catch {
2639
- }
2640
- }
2641
- }
2642
- function findPackageRoot() {
2643
- let dir = path10.dirname(fileURLToPath(import.meta.url));
2644
- const { root } = path10.parse(dir);
2645
- while (dir !== root) {
2646
- if (existsSync9(path10.join(dir, "package.json"))) return dir;
2647
- dir = path10.dirname(dir);
2648
- }
2649
- return null;
2650
- }
2651
- function getAvailableMemoryGB() {
2652
- if (process.platform === "darwin") {
2653
- try {
2654
- const { execSync: execSync3 } = __require("child_process");
2655
- const vmstat = execSync3("vm_stat", { encoding: "utf8" });
2656
- const pageSize = 16384;
2657
- const pageSizeMatch = vmstat.match(/page size of (\d+) bytes/);
2658
- const actualPageSize = pageSizeMatch ? parseInt(pageSizeMatch[1], 10) : pageSize;
2659
- const free = vmstat.match(/Pages free:\s+(\d+)/);
2660
- const inactive = vmstat.match(/Pages inactive:\s+(\d+)/);
2661
- const speculative = vmstat.match(/Pages speculative:\s+(\d+)/);
2662
- const freePages = free ? parseInt(free[1], 10) : 0;
2663
- const inactivePages = inactive ? parseInt(inactive[1], 10) : 0;
2664
- const speculativePages = speculative ? parseInt(speculative[1], 10) : 0;
2665
- return (freePages + inactivePages + speculativePages) * actualPageSize / (1024 * 1024 * 1024);
2666
- } catch {
2667
- return os6.freemem() / (1024 * 1024 * 1024);
2668
- }
2669
- }
2670
- return os6.freemem() / (1024 * 1024 * 1024);
2671
- }
2672
- function spawnDaemon() {
2673
- const freeGB = getAvailableMemoryGB();
2674
- const totalGB = os6.totalmem() / (1024 * 1024 * 1024);
2675
- if (totalGB <= 8) {
2676
- process.stderr.write(
2677
- `[exed-client] SKIP: ${totalGB.toFixed(0)}GB system \u2014 embedding daemon disabled. Using keyword search only. Minimum 16GB recommended for vector search.
2678
- `
2679
- );
2680
- return;
2681
- }
2682
- if (totalGB <= 16 && freeGB < 2) {
2683
- process.stderr.write(
2684
- `[exed-client] SKIP: low memory (${freeGB.toFixed(1)}GB available / ${totalGB.toFixed(0)}GB total). Embedding daemon not started \u2014 using keyword search only.
2685
- `
2686
- );
2687
- return;
2688
- }
2689
- const pkgRoot = findPackageRoot();
2690
- if (!pkgRoot) {
2691
- process.stderr.write("[exed-client] WARN: cannot find package root\n");
2692
- return;
2693
- }
2694
- const daemonPath = path10.join(pkgRoot, "dist", "lib", "exe-daemon.js");
2695
- if (!existsSync9(daemonPath)) {
2696
- process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
2697
- `);
2698
- return;
2699
- }
2700
- const resolvedPath = daemonPath;
2701
- const daemonToken = ensureDaemonToken(process.env[DAEMON_TOKEN_ENV] ?? null);
2702
- process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
2703
- `);
2704
- const logPath = path10.join(path10.dirname(SOCKET_PATH), "exed.log");
2705
- let stderrFd = "ignore";
2706
- try {
2707
- stderrFd = openSync(logPath, "a");
2708
- } catch {
2709
- }
2710
- const heapCapMB = totalGB <= 8 ? 256 : 512;
2711
- const nodeArgs = [`--max-old-space-size=${heapCapMB}`, resolvedPath];
2712
- const child = spawn(process.execPath, nodeArgs, {
2713
- detached: true,
2714
- stdio: ["ignore", "ignore", stderrFd],
2715
- env: {
2716
- ...process.env,
2717
- TMUX: void 0,
2718
- // Daemon is global — must not inherit session scope
2719
- TMUX_PANE: void 0,
2720
- // Prevents resolveExeSession() from scoping to one session
2721
- EXE_DAEMON_SOCK: SOCKET_PATH,
2722
- EXE_DAEMON_PID: PID_PATH,
2723
- [DAEMON_TOKEN_ENV]: daemonToken
2724
- }
2725
- });
2726
- child.unref();
2727
- if (typeof stderrFd === "number") {
2728
- try {
2729
- closeSync(stderrFd);
2730
- } catch {
2731
- }
2732
- }
2733
- }
2734
- function acquireSpawnLock() {
2735
- try {
2736
- const fd = openSync(SPAWN_LOCK_PATH, "wx");
2737
- closeSync(fd);
2738
- return true;
2739
- } catch {
2740
- try {
2741
- const stat = statSync(SPAWN_LOCK_PATH);
2742
- if (Date.now() - stat.mtimeMs > SPAWN_LOCK_STALE_MS) {
2743
- try {
2744
- unlinkSync2(SPAWN_LOCK_PATH);
2745
- } catch {
2746
- }
2747
- try {
2748
- const fd = openSync(SPAWN_LOCK_PATH, "wx");
2749
- closeSync(fd);
2750
- return true;
2751
- } catch {
2752
- }
2753
- }
2754
- } catch {
2755
- }
2756
- return false;
2757
- }
2758
- }
2759
- function releaseSpawnLock() {
2760
- try {
2761
- unlinkSync2(SPAWN_LOCK_PATH);
2762
- } catch {
2763
- }
2764
- }
2765
- function connectToSocket() {
2766
- return new Promise((resolve) => {
2767
- if (_socket && _connected) {
2768
- resolve(true);
2769
- return;
2770
- }
2771
- const socket = net.createConnection({ path: SOCKET_PATH });
2772
- const connectTimeout = setTimeout(() => {
2773
- socket.destroy();
2774
- resolve(false);
2775
- }, 2e3);
2776
- socket.on("connect", () => {
2777
- clearTimeout(connectTimeout);
2778
- _socket = socket;
2779
- _connected = true;
2780
- _buffer = "";
2781
- socket.on("data", handleData);
2782
- socket.on("close", () => {
2783
- _connected = false;
2784
- _socket = null;
2785
- for (const [id, entry] of _pending) {
2786
- clearTimeout(entry.timer);
2787
- _pending.delete(id);
2788
- entry.resolve({ error: "Connection closed" });
2789
- }
2790
- });
2791
- socket.on("error", () => {
2792
- _connected = false;
2793
- _socket = null;
2794
- });
2795
- resolve(true);
2796
- });
2797
- socket.on("error", () => {
2798
- clearTimeout(connectTimeout);
2799
- resolve(false);
2800
- });
2801
- });
2802
- }
2803
- async function connectEmbedDaemon() {
2804
- if (_socket && _connected) return true;
2805
- if (await connectToSocket()) return true;
2806
- if (acquireSpawnLock()) {
2807
- try {
2808
- cleanupStaleFiles();
2809
- spawnDaemon();
2810
- } finally {
2811
- releaseSpawnLock();
2812
- }
2813
- }
2814
- const start = Date.now();
2815
- let delay2 = 100;
2816
- while (Date.now() - start < CONNECT_TIMEOUT_MS) {
2817
- await new Promise((r) => setTimeout(r, delay2));
2818
- if (await connectToSocket()) return true;
2819
- delay2 = Math.min(delay2 * 2, 3e3);
2820
- }
2821
- return false;
2822
- }
2823
- function sendRequest(texts, priority) {
2824
- return sendDaemonRequest({ texts, priority });
2825
- }
2826
- function sendDaemonRequest(payload, timeoutMs = REQUEST_TIMEOUT_MS) {
2827
- return new Promise((resolve) => {
2828
- if (!_socket || !_connected) {
2829
- resolve({ error: "Not connected" });
2830
- return;
2831
- }
2832
- const id = randomUUID3();
2833
- const token = process.env[DAEMON_TOKEN_ENV] ?? readDaemonToken();
2834
- const timer = setTimeout(() => {
2835
- _pending.delete(id);
2836
- resolve({ error: "Request timeout" });
2837
- }, timeoutMs);
2838
- _pending.set(id, { resolve, timer });
2839
- try {
2840
- _socket.write(JSON.stringify({ id, token, ...payload }) + "\n");
2841
- } catch {
2842
- clearTimeout(timer);
2843
- _pending.delete(id);
2844
- resolve({ error: "Write failed" });
2845
- }
2846
- });
2847
- }
2848
- async function pingDaemon() {
2849
- if (!_socket || !_connected) return null;
2850
- const response = await sendDaemonRequest({ type: "health" }, 5e3);
2851
- if (response.health) {
2852
- return response.health;
2853
- }
2854
- return null;
2855
- }
2856
- function killAndRespawnDaemon() {
2857
- if (!acquireSpawnLock()) {
2858
- process.stderr.write("[exed-client] Another process is already restarting daemon \u2014 skipping\n");
2859
- if (_socket) {
2860
- _socket.destroy();
2861
- _socket = null;
2862
- }
2863
- _connected = false;
2864
- _buffer = "";
2865
- return;
2866
- }
2867
- try {
2868
- process.stderr.write("[exed-client] Killing daemon for restart...\n");
2869
- if (existsSync9(PID_PATH)) {
2870
- try {
2871
- const pid = parseInt(readFileSync6(PID_PATH, "utf8").trim(), 10);
2872
- if (pid > 0) {
2873
- try {
2874
- process.kill(pid, "SIGKILL");
2875
- } catch {
2876
- }
2877
- }
2878
- } catch {
2879
- }
2880
- }
2881
- if (_socket) {
2882
- _socket.destroy();
2883
- _socket = null;
2884
- }
2885
- _connected = false;
2886
- _buffer = "";
2887
- try {
2888
- unlinkSync2(PID_PATH);
2889
- } catch {
2890
- }
2891
- try {
2892
- unlinkSync2(SOCKET_PATH);
2893
- } catch {
2894
- }
2895
- spawnDaemon();
2896
- } finally {
2897
- releaseSpawnLock();
2898
- }
2899
- }
2900
- function isDaemonTooYoung() {
2901
- try {
2902
- const stat = statSync(PID_PATH);
2903
- return Date.now() - stat.mtimeMs < MIN_DAEMON_AGE_MS;
2904
- } catch {
2905
- return false;
2906
- }
2907
- }
2908
- async function retryThenRestart(doRequest, label) {
2909
- const result = await doRequest();
2910
- if (!result.error) {
2911
- _consecutiveFailures = 0;
2912
- return result;
2913
- }
2914
- _consecutiveFailures++;
2915
- for (let i = 0; i < MAX_RETRIES_BEFORE_RESTART; i++) {
2916
- const delayMs = RETRY_DELAYS_MS[i] ?? 5e3;
2917
- process.stderr.write(`[exed-client] ${label} failed (${result.error}), retry ${i + 1}/${MAX_RETRIES_BEFORE_RESTART} in ${delayMs}ms
2918
- `);
2919
- await new Promise((r) => setTimeout(r, delayMs));
2920
- if (!_connected) {
2921
- if (!await connectToSocket()) continue;
2922
- }
2923
- const retry = await doRequest();
2924
- if (!retry.error) {
2925
- _consecutiveFailures = 0;
2926
- return retry;
2927
- }
2928
- _consecutiveFailures++;
2929
- }
2930
- if (isDaemonTooYoung()) {
2931
- process.stderr.write(`[exed-client] ${label}: daemon too young (< ${MIN_DAEMON_AGE_MS / 1e3}s) \u2014 skipping restart
2932
- `);
2933
- return { error: result.error };
2934
- }
2935
- process.stderr.write(`[exed-client] ${label}: ${_consecutiveFailures} consecutive failures \u2014 restarting daemon
2936
- `);
2937
- killAndRespawnDaemon();
2938
- const start = Date.now();
2939
- let delay2 = 200;
2940
- while (Date.now() - start < CONNECT_TIMEOUT_MS) {
2941
- await new Promise((r) => setTimeout(r, delay2));
2942
- if (await connectToSocket()) break;
2943
- delay2 = Math.min(delay2 * 2, 3e3);
2944
- }
2945
- if (!_connected) return { error: "Daemon restart failed" };
2946
- const final = await doRequest();
2947
- if (!final.error) _consecutiveFailures = 0;
2948
- return final;
2949
- }
2950
- async function embedViaClient(text, priority = "high") {
2951
- if (!_connected && !await connectEmbedDaemon()) return null;
2952
- _requestCount++;
2953
- if (_requestCount % HEALTH_CHECK_INTERVAL === 0) {
2954
- const health = await pingDaemon();
2955
- if (!health && !isDaemonTooYoung()) {
2956
- process.stderr.write(`[exed-client] Periodic health check failed at request ${_requestCount} \u2014 restarting daemon
2957
- `);
2958
- killAndRespawnDaemon();
2959
- const start = Date.now();
2960
- let d = 200;
2961
- while (Date.now() - start < CONNECT_TIMEOUT_MS) {
2962
- await new Promise((r) => setTimeout(r, d));
2963
- if (await connectToSocket()) break;
2964
- d = Math.min(d * 2, 3e3);
2965
- }
2966
- if (!_connected) return null;
2967
- }
2968
- }
2969
- const result = await retryThenRestart(
2970
- () => sendRequest([text], priority),
2971
- "Embed"
2972
- );
2973
- return !result.error && result.vectors?.[0] ? result.vectors[0] : null;
2974
- }
2975
- function disconnectClient() {
2976
- if (_socket) {
2977
- _socket.destroy();
2978
- _socket = null;
2979
- }
2980
- _connected = false;
2981
- _buffer = "";
2982
- for (const [id, entry] of _pending) {
2983
- clearTimeout(entry.timer);
2984
- _pending.delete(id);
2985
- entry.resolve({ error: "Client disconnected" });
2986
- }
2987
- }
2988
- var SOCKET_PATH, PID_PATH, SPAWN_LOCK_PATH, SPAWN_LOCK_STALE_MS, CONNECT_TIMEOUT_MS, REQUEST_TIMEOUT_MS, DAEMON_TOKEN_ENV, _socket, _connected, _buffer, _requestCount, _consecutiveFailures, HEALTH_CHECK_INTERVAL, MAX_RETRIES_BEFORE_RESTART, RETRY_DELAYS_MS, MIN_DAEMON_AGE_MS, _pending, MAX_BUFFER;
2989
- var init_exe_daemon_client = __esm({
2990
- "src/lib/exe-daemon-client.ts"() {
2991
- "use strict";
2992
- init_config();
2993
- init_daemon_auth();
2994
- SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path10.join(EXE_AI_DIR, "exed.sock");
2995
- PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path10.join(EXE_AI_DIR, "exed.pid");
2996
- SPAWN_LOCK_PATH = path10.join(EXE_AI_DIR, "exed-spawn.lock");
2997
- SPAWN_LOCK_STALE_MS = 3e4;
2998
- CONNECT_TIMEOUT_MS = 15e3;
2999
- REQUEST_TIMEOUT_MS = 3e4;
3000
- DAEMON_TOKEN_ENV = "EXE_DAEMON_TOKEN";
3001
- _socket = null;
3002
- _connected = false;
3003
- _buffer = "";
3004
- _requestCount = 0;
3005
- _consecutiveFailures = 0;
3006
- HEALTH_CHECK_INTERVAL = 100;
3007
- MAX_RETRIES_BEFORE_RESTART = 3;
3008
- RETRY_DELAYS_MS = [1e3, 3e3, 5e3];
3009
- MIN_DAEMON_AGE_MS = 3e4;
3010
- _pending = /* @__PURE__ */ new Map();
3011
- MAX_BUFFER = 1e7;
3012
- }
3013
- });
3014
-
3015
- // src/lib/embedder.ts
3016
- var embedder_exports = {};
3017
- __export(embedder_exports, {
3018
- disposeEmbedder: () => disposeEmbedder,
3019
- embed: () => embed,
3020
- embedDirect: () => embedDirect,
3021
- getEmbedder: () => getEmbedder
3022
- });
3023
- async function getEmbedder() {
3024
- const ok = await connectEmbedDaemon();
3025
- if (!ok) {
3026
- throw new Error(
3027
- "Could not connect to embedding daemon. Ensure the model is installed (run /exe-setup)."
3028
- );
3029
- }
3030
- }
3031
- async function embed(text) {
3032
- const priority = process.env.EXE_EMBED_PRIORITY === "low" ? "low" : "high";
3033
- const vector = await embedViaClient(text, priority);
3034
- if (!vector) {
3035
- throw new Error(
3036
- "Embedding failed: daemon unavailable. Run /exe-setup to verify model installation."
3037
- );
3038
- }
3039
- if (vector.length !== EMBEDDING_DIM) {
3040
- throw new Error(
3041
- `Embedding dimension mismatch: expected ${EMBEDDING_DIM}, got ${vector.length}. Ensure the correct Jina v5-small Q4_K_M GGUF model is installed.`
3042
- );
3043
- }
3044
- return vector;
3045
- }
3046
- async function disposeEmbedder() {
3047
- disconnectClient();
3048
- }
3049
- async function embedDirect(text) {
3050
- const llamaCpp = await import("node-llama-cpp");
3051
- const { MODELS_DIR: MODELS_DIR2 } = await Promise.resolve().then(() => (init_config(), config_exports));
3052
- const { existsSync: existsSync10 } = await import("fs");
3053
- const path12 = await import("path");
3054
- const modelPath = path12.join(MODELS_DIR2, "jina-embeddings-v5-small-q4_k_m.gguf");
3055
- if (!existsSync10(modelPath)) {
3056
- throw new Error(`Embedding model not found at ${modelPath}. Run '/exe-setup' to download it.`);
3057
- }
3058
- const llama = await llamaCpp.getLlama();
3059
- const model = await llama.loadModel({ modelPath });
3060
- const context = await model.createEmbeddingContext();
3061
- try {
3062
- const embedding = await context.getEmbeddingFor(text);
3063
- const vector = Array.from(embedding.vector);
3064
- if (vector.length !== EMBEDDING_DIM) {
3065
- throw new Error(
3066
- `Embedding dimension mismatch: expected ${EMBEDDING_DIM}, got ${vector.length}.`
3067
- );
3068
- }
3069
- return vector;
3070
- } finally {
3071
- await context.dispose();
3072
- await model.dispose();
3073
- }
3074
- }
3075
- var init_embedder = __esm({
3076
- "src/lib/embedder.ts"() {
3077
- "use strict";
3078
- init_memory();
3079
- init_exe_daemon_client();
3080
- }
3081
- });
3082
-
3083
- // src/adapters/claude/hooks/prompt-ingest-worker.ts
3084
- import crypto2 from "crypto";
3085
- import { writeFileSync as writeFileSync4 } from "fs";
3086
- import path11 from "path";
3087
-
3088
- // src/lib/project-name.ts
3089
- import { execSync } from "child_process";
3090
- import path from "path";
3091
- var _cached = null;
3092
- var _cachedCwd = null;
3093
- function getProjectName(cwd) {
3094
- const dir = cwd ?? process.cwd();
3095
- if (_cached && _cachedCwd === dir) return _cached;
3096
- try {
3097
- let repoRoot;
3098
- try {
3099
- const gitCommonDir = execSync("git rev-parse --path-format=absolute --git-common-dir", {
3100
- cwd: dir,
3101
- encoding: "utf8",
3102
- timeout: 2e3,
3103
- stdio: ["pipe", "pipe", "pipe"]
3104
- }).trim();
3105
- repoRoot = path.dirname(gitCommonDir);
3106
- } catch {
3107
- repoRoot = execSync("git rev-parse --show-toplevel", {
3108
- cwd: dir,
3109
- encoding: "utf8",
3110
- timeout: 2e3,
3111
- stdio: ["pipe", "pipe", "pipe"]
3112
- }).trim();
3113
- }
3114
- _cached = path.basename(repoRoot);
3115
- _cachedCwd = dir;
3116
- return _cached;
3117
- } catch {
3118
- _cached = path.basename(dir);
3119
- _cachedCwd = dir;
3120
- return _cached;
3121
- }
3122
- }
3123
-
3124
- // src/lib/store.ts
3125
- init_memory();
3126
- init_database();
3127
- import { createHash } from "crypto";
3128
-
3129
- // src/lib/keychain.ts
3130
- import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
3131
- import { existsSync as existsSync4 } from "fs";
3132
- import path5 from "path";
3133
- import os4 from "os";
3134
- var SERVICE = "exe-mem";
3135
- var ACCOUNT = "master-key";
3136
- function getKeyDir() {
3137
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path5.join(os4.homedir(), ".exe-os");
3138
- }
3139
- function getKeyPath() {
3140
- return path5.join(getKeyDir(), "master.key");
3141
- }
3142
- async function tryKeytar() {
3143
- try {
3144
- return await import("keytar");
3145
- } catch {
3146
- return null;
3147
- }
3148
- }
3149
- async function getMasterKey() {
3150
- const keytar = await tryKeytar();
3151
- if (keytar) {
3152
- try {
3153
- const stored = await keytar.getPassword(SERVICE, ACCOUNT);
3154
- if (stored) {
3155
- return Buffer.from(stored, "base64");
3156
- }
3157
- } catch {
3158
- }
3159
- }
3160
- const keyPath = getKeyPath();
3161
- if (!existsSync4(keyPath)) {
3162
- process.stderr.write(
3163
- `[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
3164
- `
3165
- );
3166
- return null;
3167
- }
3168
- try {
3169
- const content = await readFile3(keyPath, "utf-8");
3170
- return Buffer.from(content.trim(), "base64");
3171
- } catch (err) {
3172
- process.stderr.write(
3173
- `[keychain] Key read failed at ${keyPath}: ${err instanceof Error ? err.message : String(err)}
3174
- `
3175
- );
3176
- return null;
3177
- }
3178
- }
3179
-
3180
- // src/lib/store.ts
3181
- init_config();
3182
-
3183
- // src/lib/state-bus.ts
3184
- var StateBus = class {
3185
- handlers = /* @__PURE__ */ new Map();
3186
- globalHandlers = /* @__PURE__ */ new Set();
3187
- /** Emit an event to all subscribers */
3188
- emit(event) {
3189
- const typeHandlers = this.handlers.get(event.type);
3190
- if (typeHandlers) {
3191
- for (const handler of typeHandlers) {
3192
- try {
3193
- handler(event);
3194
- } catch {
3195
- }
3196
- }
3197
- }
3198
- for (const handler of this.globalHandlers) {
3199
- try {
3200
- handler(event);
3201
- } catch {
3202
- }
3203
- }
3204
- }
3205
- /** Subscribe to a specific event type */
3206
- on(type, handler) {
3207
- if (!this.handlers.has(type)) {
3208
- this.handlers.set(type, /* @__PURE__ */ new Set());
3209
- }
3210
- this.handlers.get(type).add(handler);
3211
- }
3212
- /** Subscribe to ALL events */
3213
- onAny(handler) {
3214
- this.globalHandlers.add(handler);
3215
- }
3216
- /** Unsubscribe from a specific event type */
3217
- off(type, handler) {
3218
- this.handlers.get(type)?.delete(handler);
3219
- }
3220
- /** Unsubscribe from ALL events */
3221
- offAny(handler) {
3222
- this.globalHandlers.delete(handler);
3223
- }
3224
- /** Remove all listeners */
3225
- clear() {
3226
- this.handlers.clear();
3227
- this.globalHandlers.clear();
3228
- }
3229
- };
3230
- var orgBus = new StateBus();
3231
-
3232
- // src/lib/store.ts
3233
- var INIT_MAX_RETRIES = 3;
3234
- var INIT_RETRY_DELAY_MS = 1e3;
3235
- function isBusyError2(err) {
3236
- if (err instanceof Error) {
3237
- const msg = err.message.toLowerCase();
3238
- return msg.includes("sqlite_busy") || msg.includes("database is locked");
3239
- }
3240
- return false;
3241
- }
3242
- async function retryOnBusy2(fn, label) {
3243
- for (let attempt = 0; attempt <= INIT_MAX_RETRIES; attempt++) {
3244
- try {
3245
- return await fn();
3246
- } catch (err) {
3247
- if (!isBusyError2(err) || attempt === INIT_MAX_RETRIES) throw err;
3248
- process.stderr.write(
3249
- `[store] SQLITE_BUSY during ${label}, retry ${attempt + 1}/${INIT_MAX_RETRIES}
3250
- `
3251
- );
3252
- await new Promise((r) => setTimeout(r, INIT_RETRY_DELAY_MS * (attempt + 1)));
3253
- }
3254
- }
3255
- throw new Error("unreachable");
3256
- }
3257
- var _pendingRecords = [];
3258
- var _batchSize = 20;
3259
- var _flushIntervalMs = 1e4;
3260
- var _flushTimer = null;
3261
- var _flushing = false;
3262
- var _nextVersion = 1;
3263
- async function initStore(options) {
3264
- if (_flushTimer !== null) {
3265
- clearInterval(_flushTimer);
3266
- _flushTimer = null;
3267
- }
3268
- _pendingRecords = [];
3269
- _flushing = false;
3270
- _batchSize = options?.batchSize ?? 20;
3271
- _flushIntervalMs = options?.flushIntervalMs ?? 1e4;
3272
- let dbPath = options?.dbPath;
3273
- if (!dbPath) {
3274
- const config = await loadConfig();
3275
- dbPath = config.dbPath;
3276
- }
3277
- let masterKey = options?.masterKey ?? null;
3278
- if (!masterKey) {
3279
- masterKey = await getMasterKey();
3280
- if (!masterKey) {
3281
- throw new Error(
3282
- "No encryption key found. Run /exe-setup to generate one."
3283
- );
3284
- }
3285
- }
3286
- const hexKey = masterKey.toString("hex");
3287
- await initTurso({
3288
- dbPath,
3289
- encryptionKey: hexKey
3290
- });
3291
- await retryOnBusy2(() => ensureSchema(), "ensureSchema");
3292
- if (!options?.lightweight) {
3293
- try {
3294
- const { initShardManager: initShardManager2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
3295
- initShardManager2(hexKey);
3296
- } catch {
3297
- }
3298
- const client = getClient();
3299
- const vResult = await retryOnBusy2(
3300
- () => client.execute("SELECT MAX(version) as max_v FROM memories"),
3301
- "version-query"
3302
- );
3303
- _nextVersion = (Number(vResult.rows[0]?.max_v) || 0) + 1;
3304
- try {
3305
- const { loadGlobalProcedures: loadGlobalProcedures2 } = await Promise.resolve().then(() => (init_global_procedures(), global_procedures_exports));
3306
- await loadGlobalProcedures2();
3307
- } catch {
3308
- }
3309
- }
3310
- }
3311
- function classifyTier(record) {
3312
- if (record.tool_name === "commit_to_long_term_memory" && (record.importance ?? 0) >= 8) return 1;
3313
- if (["store_memory", "manual"].includes(record.tool_name ?? "") && (record.importance ?? 0) >= 5) return 2;
3314
- return 3;
3315
- }
3316
- function inferFilePaths(record) {
3317
- if (!["Read", "Write", "Edit"].includes(record.tool_name)) return null;
3318
- const firstLine = record.raw_text.split("\n")[0] ?? "";
3319
- const match = firstLine.match(/(\/[\w./-]+\.\w+)/);
3320
- return match ? JSON.stringify([match[1]]) : null;
3321
- }
3322
- function inferCommitHash(record) {
3323
- if (record.tool_name !== "Bash") return null;
3324
- const match = record.raw_text.match(/\b([a-f0-9]{7,40})\b/);
3325
- return match ? match[1] : null;
3326
- }
3327
- function inferLanguageType(record) {
3328
- const text = record.raw_text;
3329
- if (!text || text.length < 10) return null;
3330
- const trimmed = text.trimStart();
3331
- if (trimmed.startsWith("{") || trimmed.startsWith("[")) return "json";
3332
- if (/\b(SELECT|INSERT|UPDATE|DELETE|CREATE TABLE|ALTER TABLE)\b/i.test(text)) return "sql";
3333
- if (/\b(function |const |import |export |class |def |async |=>)\b/.test(text)) return "code";
3334
- if (trimmed.startsWith("#") || trimmed.startsWith("*")) return "prose";
3335
- return "mixed";
3336
- }
3337
- function inferDomain(record) {
3338
- const proj = (record.project_name ?? "").toLowerCase();
3339
- if (proj.includes("marketing") || proj.includes("content")) return "marketing";
3340
- if (proj.includes("crm") || proj.includes("customer")) return "customer";
3341
- return null;
3342
- }
3343
- async function writeMemory(record) {
3344
- if (record.vector !== null && record.vector.length !== EMBEDDING_DIM) {
3345
- throw new Error(
3346
- `Expected ${EMBEDDING_DIM}-dim vector, got ${record.vector.length}`
3347
- );
3348
- }
3349
- const contentHash = createHash("md5").update(record.raw_text).digest("hex");
3350
- if (_pendingRecords.some((r) => r.content_hash === contentHash && r.agent_id === record.agent_id)) {
3351
- return;
3352
- }
3353
- try {
3354
- const client = getClient();
3355
- const existing = await client.execute({
3356
- sql: "SELECT id FROM memories WHERE content_hash = ? AND agent_id = ? LIMIT 1",
3357
- args: [contentHash, record.agent_id]
3358
- });
3359
- if (existing.rows.length > 0) return;
3360
- } catch {
3361
- }
3362
- const dbRow = {
3363
- id: record.id,
3364
- agent_id: record.agent_id,
3365
- agent_role: record.agent_role,
3366
- session_id: record.session_id,
3367
- timestamp: record.timestamp,
3368
- tool_name: record.tool_name,
3369
- project_name: record.project_name,
3370
- has_error: record.has_error ? 1 : 0,
3371
- raw_text: record.raw_text,
3372
- vector: record.vector,
3373
- version: 0,
3374
- // Placeholder — assigned atomically at flush time
3375
- task_id: record.task_id ?? null,
3376
- importance: record.importance ?? 5,
3377
- status: record.status ?? "active",
3378
- confidence: record.confidence ?? 0.7,
3379
- last_accessed: record.last_accessed ?? record.timestamp,
3380
- workspace_id: record.workspace_id ?? null,
3381
- document_id: record.document_id ?? null,
3382
- user_id: record.user_id ?? null,
3383
- char_offset: record.char_offset ?? null,
3384
- page_number: record.page_number ?? null,
3385
- source_path: record.source_path ?? null,
3386
- source_type: record.source_type ?? null,
3387
- tier: record.tier ?? classifyTier(record),
3388
- supersedes_id: record.supersedes_id ?? null,
3389
- draft: record.draft ? 1 : 0,
3390
- memory_type: record.memory_type ?? "raw",
3391
- trajectory: record.trajectory ? JSON.stringify(record.trajectory) : null,
3392
- content_hash: contentHash,
3393
- intent: record.intent ?? null,
3394
- outcome: record.outcome ?? null,
3395
- domain: record.domain ?? inferDomain(record),
3396
- referenced_entities: record.referenced_entities ?? null,
3397
- retrieval_count: record.retrieval_count ?? 0,
3398
- chain_position: record.chain_position ?? null,
3399
- review_status: record.review_status ?? null,
3400
- context_window_pct: record.context_window_pct ?? null,
3401
- file_paths: record.file_paths ?? inferFilePaths(record),
3402
- commit_hash: record.commit_hash ?? inferCommitHash(record),
3403
- duration_ms: record.duration_ms ?? null,
3404
- token_cost: record.token_cost ?? null,
3405
- audience: record.audience ?? null,
3406
- language_type: record.language_type ?? inferLanguageType(record),
3407
- parent_memory_id: record.parent_memory_id ?? null
3408
- };
3409
- _pendingRecords.push(dbRow);
3410
- orgBus.emit({
3411
- type: "memory_stored",
3412
- agentId: record.agent_id,
3413
- project: record.project_name,
3414
- timestamp: record.timestamp
3415
- });
3416
- const MAX_PENDING = 1e3;
3417
- if (_pendingRecords.length > MAX_PENDING) {
3418
- const dropped = _pendingRecords.length - MAX_PENDING;
3419
- _pendingRecords = _pendingRecords.slice(-MAX_PENDING);
3420
- console.warn(`[store] Dropped ${dropped} oldest pending records (overflow)`);
3421
- }
3422
- if (_flushTimer === null) {
3423
- _flushTimer = setInterval(() => {
3424
- void flushBatch();
3425
- }, _flushIntervalMs);
3426
- if (_flushTimer && typeof _flushTimer === "object" && "unref" in _flushTimer) {
3427
- _flushTimer.unref();
3428
- }
3429
- }
3430
- if (_pendingRecords.length >= _batchSize) {
3431
- await flushBatch();
3432
- }
3433
- }
3434
- async function flushBatch() {
3435
- if (_flushing || _pendingRecords.length === 0) return 0;
3436
- _flushing = true;
3437
- try {
3438
- const batch = _pendingRecords.slice(0);
3439
- const client = getClient();
3440
- const vResult = await client.execute("SELECT MAX(version) as max_v FROM memories");
3441
- let baseVersion = (Number(vResult.rows[0]?.max_v) || 0) + 1;
3442
- for (const row of batch) {
3443
- row.version = baseVersion++;
3444
- }
3445
- _nextVersion = baseVersion;
3446
- const buildStmt = (row) => {
3447
- const hasVector = row.vector !== null;
3448
- const taskId = row.task_id ?? null;
3449
- const importance = row.importance ?? 5;
3450
- const status = row.status ?? "active";
3451
- const confidence = row.confidence ?? 0.7;
3452
- const lastAccessed = row.last_accessed ?? row.timestamp;
3453
- const workspaceId = row.workspace_id ?? null;
3454
- const documentId = row.document_id ?? null;
3455
- const userId = row.user_id ?? null;
3456
- const charOffset = row.char_offset ?? null;
3457
- const pageNumber = row.page_number ?? null;
3458
- const sourcePath = row.source_path ?? null;
3459
- const sourceType = row.source_type ?? null;
3460
- const tier = row.tier ?? 3;
3461
- const supersedesId = row.supersedes_id ?? null;
3462
- const draft = row.draft ? 1 : 0;
3463
- const memoryType = row.memory_type ?? "raw";
3464
- const trajectory = row.trajectory ?? null;
3465
- const contentHash = row.content_hash ?? null;
3466
- const intent = row.intent ?? null;
3467
- const outcome = row.outcome ?? null;
3468
- const domain = row.domain ?? null;
3469
- const referencedEntities = row.referenced_entities ?? null;
3470
- const retrievalCount = row.retrieval_count ?? 0;
3471
- const chainPosition = row.chain_position ?? null;
3472
- const reviewStatus = row.review_status ?? null;
3473
- const contextWindowPct = row.context_window_pct ?? null;
3474
- const filePaths = row.file_paths ?? null;
3475
- const commitHash = row.commit_hash ?? null;
3476
- const durationMs = row.duration_ms ?? null;
3477
- const tokenCost = row.token_cost ?? null;
3478
- const audience = row.audience ?? null;
3479
- const languageType = row.language_type ?? null;
3480
- const parentMemoryId = row.parent_memory_id ?? null;
3481
- const cols = `id, agent_id, agent_role, session_id, timestamp,
3482
- tool_name, project_name,
3483
- has_error, raw_text, vector, version, task_id, importance, status,
3484
- confidence, last_accessed,
3485
- workspace_id, document_id, user_id, char_offset, page_number,
3486
- source_path, source_type, tier, supersedes_id, draft, memory_type, trajectory, content_hash,
3487
- intent, outcome, domain, referenced_entities, retrieval_count,
3488
- chain_position, review_status, context_window_pct, file_paths, commit_hash,
3489
- duration_ms, token_cost, audience, language_type, parent_memory_id`;
3490
- const metaArgs = [
3491
- intent,
3492
- outcome,
3493
- domain,
3494
- referencedEntities,
3495
- retrievalCount,
3496
- chainPosition,
3497
- reviewStatus,
3498
- contextWindowPct,
3499
- filePaths,
3500
- commitHash,
3501
- durationMs,
3502
- tokenCost,
3503
- audience,
3504
- languageType,
3505
- parentMemoryId
3506
- ];
3507
- const baseArgs = [
3508
- row.id,
3509
- row.agent_id,
3510
- row.agent_role,
3511
- row.session_id,
3512
- row.timestamp,
3513
- row.tool_name,
3514
- row.project_name,
3515
- row.has_error,
3516
- row.raw_text
3517
- ];
3518
- const sharedArgs = [
3519
- row.version,
3520
- taskId,
3521
- importance,
3522
- status,
3523
- confidence,
3524
- lastAccessed,
3525
- workspaceId,
3526
- documentId,
3527
- userId,
3528
- charOffset,
3529
- pageNumber,
3530
- sourcePath,
3531
- sourceType,
3532
- tier,
3533
- supersedesId,
3534
- draft,
3535
- memoryType,
3536
- trajectory,
3537
- contentHash
3538
- ];
3539
- return {
3540
- sql: hasVector ? `INSERT OR IGNORE INTO memories (${cols})
3541
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, vector32(?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` : `INSERT OR IGNORE INTO memories (${cols})
3542
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
3543
- args: hasVector ? [...baseArgs, vectorToBlob(row.vector), ...sharedArgs, ...metaArgs] : [...baseArgs, ...sharedArgs, ...metaArgs]
3544
- };
3545
- };
3546
- const globalClient = getClient();
3547
- const globalStmts = batch.map(buildStmt);
3548
- await globalClient.batch(globalStmts, "write");
3549
- _pendingRecords.splice(0, batch.length);
3550
- try {
3551
- const { isShardingEnabled: isShardingEnabled2, getReadyShardClient: getReadyShardClient2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
3552
- if (isShardingEnabled2()) {
3553
- const byProject = /* @__PURE__ */ new Map();
3554
- for (const row of batch) {
3555
- const proj = row.project_name || "unknown";
3556
- if (!byProject.has(proj)) byProject.set(proj, []);
3557
- byProject.get(proj).push(row);
3558
- }
3559
- for (const [project, rows] of byProject) {
3560
- try {
3561
- const shardClient = await getReadyShardClient2(project);
3562
- const shardStmts = rows.map(buildStmt);
3563
- await shardClient.batch(shardStmts, "write");
3564
- } catch (err) {
3565
- process.stderr.write(
3566
- `[store] Shard write failed for ${project}: ${err instanceof Error ? err.message : String(err)}
3567
- `
3568
- );
3569
- }
3570
- }
3571
- }
3572
- } catch {
3573
- }
3574
- return batch.length;
3575
- } finally {
3576
- _flushing = false;
3577
- }
3578
- }
3579
- function vectorToBlob(vector) {
3580
- const f32 = vector instanceof Float32Array ? vector : new Float32Array(vector);
3581
- return JSON.stringify(Array.from(f32));
3582
- }
3583
-
3584
- // src/lib/plan-limits.ts
3585
- init_database();
3586
- init_employees();
3587
- import { readFileSync as readFileSync4, existsSync as existsSync7 } from "fs";
3588
- import path8 from "path";
3589
-
3590
- // src/lib/license.ts
3591
- init_config();
3592
- import { readFileSync as readFileSync3, writeFileSync as writeFileSync2, existsSync as existsSync6, mkdirSync as mkdirSync3 } from "fs";
3593
- import { randomUUID as randomUUID2 } from "crypto";
3594
- import { createRequire as createRequire2 } from "module";
3595
- import { pathToFileURL as pathToFileURL2 } from "url";
3596
- import os5 from "os";
3597
- import path7 from "path";
3598
- import { jwtVerify, importSPKI } from "jose";
3599
- var LICENSE_PATH = path7.join(EXE_AI_DIR, "license.key");
3600
- var CACHE_PATH = path7.join(EXE_AI_DIR, "license-cache.json");
3601
- var DEVICE_ID_PATH = path7.join(EXE_AI_DIR, "device-id");
3602
- var API_BASE = "https://askexe.com/cloud";
3603
- var RETRY_DELAY_MS = 500;
3604
- async function fetchRetry(url, init) {
3605
- try {
3606
- return await fetch(url, init);
3607
- } catch {
3608
- await new Promise((r) => setTimeout(r, RETRY_DELAY_MS));
3609
- return fetch(url, { ...init, signal: AbortSignal.timeout(1e4) });
3610
- }
3611
- }
3612
- var LICENSE_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
3613
- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEeHztAMOpR/ZMh+rWuOASjEZ54CGY
3614
- 4uj+UqeKCcvtgNHKmOK278HJaJcANe9xAeji8AFYu27q3WtzCi04pHudow==
3615
- -----END PUBLIC KEY-----`;
3616
- var LICENSE_JWT_ALG = "ES256";
3617
- var PLAN_LIMITS = {
3618
- free: { devices: 1, employees: 1, memories: 5e3 },
3619
- pro: { devices: 3, employees: 5, memories: 1e5 },
3620
- team: { devices: 10, employees: 20, memories: 1e6 },
3621
- agency: { devices: 50, employees: 100, memories: 1e7 },
3622
- enterprise: { devices: -1, employees: -1, memories: -1 }
3623
- };
3624
- var FREE_LICENSE = {
3625
- valid: true,
3626
- plan: "free",
3627
- email: "",
3628
- expiresAt: null,
3629
- deviceLimit: 1,
3630
- employeeLimit: 1,
3631
- memoryLimit: 5e3
3632
- };
3633
- function loadDeviceId() {
3634
- const deviceJsonPath = path7.join(EXE_AI_DIR, "device.json");
3635
- try {
3636
- if (existsSync6(deviceJsonPath)) {
3637
- const data = JSON.parse(readFileSync3(deviceJsonPath, "utf8"));
3638
- if (data.deviceId) return data.deviceId;
3639
- }
3640
- } catch {
3641
- }
3642
- try {
3643
- if (existsSync6(DEVICE_ID_PATH)) {
3644
- const id2 = readFileSync3(DEVICE_ID_PATH, "utf8").trim();
3645
- if (id2) return id2;
3646
- }
3647
- } catch {
3648
- }
3649
- const id = randomUUID2();
3650
- mkdirSync3(EXE_AI_DIR, { recursive: true });
3651
- writeFileSync2(DEVICE_ID_PATH, id, "utf8");
3652
- return id;
3653
- }
3654
- function loadLicense() {
3655
- try {
3656
- if (!existsSync6(LICENSE_PATH)) return null;
3657
- return readFileSync3(LICENSE_PATH, "utf8").trim();
3658
- } catch {
3659
- return null;
3660
- }
3661
- }
3662
- function saveLicense(apiKey) {
3663
- mkdirSync3(EXE_AI_DIR, { recursive: true });
3664
- writeFileSync2(LICENSE_PATH, apiKey.trim(), { encoding: "utf8", mode: 384 });
3665
- }
3666
- async function verifyLicenseJwt(token) {
3667
- try {
3668
- const key = await importSPKI(LICENSE_PUBLIC_KEY_PEM, LICENSE_JWT_ALG);
3669
- const { payload } = await jwtVerify(token, key, {
3670
- algorithms: [LICENSE_JWT_ALG]
3671
- });
3672
- const plan = payload.plan ?? "free";
3673
- const email = payload.sub ?? "";
3674
- const limits = PLAN_LIMITS[plan] ?? PLAN_LIMITS.free;
3675
- return {
3676
- valid: true,
3677
- plan,
3678
- email,
3679
- expiresAt: payload.exp ? new Date(payload.exp * 1e3).toISOString() : null,
3680
- deviceLimit: limits.devices,
3681
- employeeLimit: limits.employees,
3682
- memoryLimit: limits.memories
3683
- };
3684
- } catch {
3685
- return null;
3686
- }
3687
- }
3688
- async function getCachedLicense() {
3689
- try {
3690
- if (!existsSync6(CACHE_PATH)) return null;
3691
- const raw = JSON.parse(readFileSync3(CACHE_PATH, "utf8"));
3692
- if (!raw.token || typeof raw.token !== "string") return null;
3693
- return await verifyLicenseJwt(raw.token);
3694
- } catch {
3695
- return null;
3696
- }
3697
- }
3698
- function readCachedToken() {
3699
- try {
3700
- if (!existsSync6(CACHE_PATH)) return null;
3701
- const raw = JSON.parse(readFileSync3(CACHE_PATH, "utf8"));
3702
- return typeof raw.token === "string" ? raw.token : null;
3703
- } catch {
3704
- return null;
3705
- }
3706
- }
3707
- function getRawCachedPlan() {
3708
- try {
3709
- const token = readCachedToken();
3710
- if (!token) return null;
3711
- const parts = token.split(".");
3712
- if (parts.length !== 3) return null;
3713
- const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString());
3714
- const plan = payload.plan ?? "free";
3715
- const limits = PLAN_LIMITS[plan] ?? PLAN_LIMITS.free;
3716
- process.stderr.write(
3717
- `[license] WARN: using unverified cached plan (API unreachable, JWT expired). Plan: ${plan}
3718
- `
3719
- );
3720
- return {
3721
- valid: true,
3722
- plan,
3723
- email: payload.sub ?? "",
3724
- expiresAt: payload.exp ? new Date(payload.exp * 1e3).toISOString() : null,
3725
- deviceLimit: limits.devices,
3726
- employeeLimit: limits.employees,
3727
- memoryLimit: limits.memories
3728
- };
3729
- } catch {
3730
- return null;
3731
- }
3732
- }
3733
- function cacheResponse(token) {
3734
- try {
3735
- writeFileSync2(CACHE_PATH, JSON.stringify({ token }), "utf8");
3736
- } catch {
3737
- }
3738
- }
3739
- var _prismaPromise = null;
3740
- var _prismaFailed = false;
3741
- function loadPrismaForLicense() {
3742
- if (_prismaFailed) return null;
3743
- const dbUrl = process.env.DATABASE_URL;
3744
- if (!dbUrl) {
3745
- const exeDbRoot = process.env.EXE_DB_ROOT ?? path7.join(os5.homedir(), "exe-db");
3746
- if (!existsSync6(path7.join(exeDbRoot, "package.json"))) {
3747
- _prismaFailed = true;
3748
- return null;
3749
- }
3750
- }
3751
- if (!_prismaPromise) {
3752
- _prismaPromise = (async () => {
3753
- const explicitPath = process.env.EXE_OS_PRISMA_CLIENT_PATH;
3754
- if (explicitPath) {
3755
- const mod2 = await import(pathToFileURL2(explicitPath).href);
3756
- const Ctor2 = mod2.PrismaClient ?? mod2.default?.PrismaClient;
3757
- if (!Ctor2) throw new Error(`No PrismaClient at ${explicitPath}`);
3758
- return new Ctor2();
3759
- }
3760
- const exeDbRoot = process.env.EXE_DB_ROOT ?? path7.join(os5.homedir(), "exe-db");
3761
- const req = createRequire2(path7.join(exeDbRoot, "package.json"));
3762
- const entry = req.resolve("@prisma/client");
3763
- const mod = await import(pathToFileURL2(entry).href);
3764
- const Ctor = mod.PrismaClient ?? mod.default?.PrismaClient;
3765
- if (!Ctor) throw new Error(`No PrismaClient in ${entry}`);
3766
- return new Ctor();
3767
- })().catch((err) => {
3768
- _prismaFailed = true;
3769
- _prismaPromise = null;
3770
- throw err;
3771
- });
3772
- }
3773
- return _prismaPromise;
3774
- }
3775
- async function validateViaPostgres(apiKey) {
3776
- const loader = loadPrismaForLicense();
3777
- if (!loader) return null;
3778
- try {
3779
- const prisma = await loader;
3780
- const rows = await prisma.$queryRawUnsafe(
3781
- `SELECT plan, email, status, device_limit, employee_limit, memory_limit, expires_at
3782
- FROM billing.licenses WHERE key = $1 LIMIT 1`,
3783
- apiKey
3784
- );
3785
- if (!rows || rows.length === 0) return null;
3786
- const row = rows[0];
3787
- if (row.status !== "active") return null;
3788
- if (row.expires_at && new Date(row.expires_at) < /* @__PURE__ */ new Date()) return null;
3789
- const plan = row.plan;
3790
- const limits = PLAN_LIMITS[plan] ?? PLAN_LIMITS.free;
3791
- return {
3792
- valid: true,
3793
- plan,
3794
- email: row.email,
3795
- expiresAt: row.expires_at ? new Date(row.expires_at).toISOString() : null,
3796
- deviceLimit: row.device_limit ?? limits.devices,
3797
- employeeLimit: row.employee_limit ?? limits.employees,
3798
- memoryLimit: row.memory_limit ?? limits.memories
3799
- };
3800
- } catch {
3801
- return null;
3802
- }
3803
- }
3804
- async function validateViaCFWorker(apiKey, deviceId) {
3805
- try {
3806
- const res = await fetchRetry(`${API_BASE}/auth/activate`, {
3807
- method: "POST",
3808
- headers: { "Content-Type": "application/json" },
3809
- body: JSON.stringify({ apiKey, deviceId }),
3810
- signal: AbortSignal.timeout(1e4)
3811
- });
3812
- if (!res.ok) return null;
3813
- const data = await res.json();
3814
- if (data.error === "device_limit_exceeded") return null;
3815
- if (!data.valid) return null;
3816
- if (data.token) {
3817
- cacheResponse(data.token);
3818
- const verified = await verifyLicenseJwt(data.token);
3819
- if (verified) return verified;
3820
- }
3821
- const limits = PLAN_LIMITS[data.plan] ?? PLAN_LIMITS.free;
3822
- return {
3823
- valid: data.valid,
3824
- plan: data.plan,
3825
- email: data.email,
3826
- expiresAt: data.expiresAt,
3827
- deviceLimit: limits.devices,
3828
- employeeLimit: limits.employees,
3829
- memoryLimit: limits.memories
3830
- };
3831
- } catch {
3832
- return null;
3833
- }
3834
- }
3835
- async function validateLicense(apiKey, deviceId) {
3836
- const did = deviceId ?? loadDeviceId();
3837
- const pgResult = await validateViaPostgres(apiKey);
3838
- if (pgResult) {
3839
- try {
3840
- writeFileSync2(CACHE_PATH, JSON.stringify({ pgLicense: pgResult, ts: Date.now() }), "utf8");
3841
- } catch {
3842
- }
3843
- return pgResult;
3844
- }
3845
- const cfResult = await validateViaCFWorker(apiKey, did);
3846
- if (cfResult) return cfResult;
3847
- const cached = await getCachedLicense();
3848
- if (cached) return cached;
3849
- try {
3850
- if (existsSync6(CACHE_PATH)) {
3851
- const raw = JSON.parse(readFileSync3(CACHE_PATH, "utf8"));
3852
- if (raw.pgLicense && raw.ts && Date.now() - raw.ts < 7 * 24 * 60 * 60 * 1e3) {
3853
- return raw.pgLicense;
3854
- }
3855
- }
3856
- } catch {
3857
- }
3858
- const rawFallback = getRawCachedPlan();
3859
- if (rawFallback) return rawFallback;
3860
- return { ...FREE_LICENSE, valid: false };
3861
- }
3862
- var CACHE_MAX_AGE_MS = 36e5;
3863
- function getCacheAgeMs() {
3864
- try {
3865
- const { statSync: statSync2 } = __require("fs");
3866
- const s = statSync2(CACHE_PATH);
3867
- return Date.now() - s.mtimeMs;
3868
- } catch {
3869
- return Infinity;
3870
- }
3871
- }
3872
- async function checkLicense() {
3873
- let key = loadLicense();
3874
- if (!key) {
3875
- try {
3876
- const configPath = path7.join(EXE_AI_DIR, "config.json");
3877
- if (existsSync6(configPath)) {
3878
- const raw = JSON.parse(readFileSync3(configPath, "utf8"));
3879
- const cloud = raw.cloud;
3880
- if (cloud?.apiKey) {
3881
- key = cloud.apiKey;
3882
- saveLicense(key);
3883
- }
3884
- }
3885
- } catch {
3886
- }
3887
- }
3888
- if (!key) return FREE_LICENSE;
3889
- const cached = await getCachedLicense();
3890
- if (cached && getCacheAgeMs() < CACHE_MAX_AGE_MS) return cached;
3891
- const deviceId = loadDeviceId();
3892
- return validateLicense(key, deviceId);
3893
- }
3894
-
3895
- // src/lib/plan-limits.ts
3896
- init_config();
3897
- var PlanLimitError = class extends Error {
3898
- constructor(message) {
3899
- super(message);
3900
- this.name = "PlanLimitError";
3901
- }
3902
- };
3903
- var CACHE_PATH2 = path8.join(EXE_AI_DIR, "license-cache.json");
3904
- async function countActiveMemories() {
3905
- if (!isInitialized()) return 0;
3906
- const client = getClient();
3907
- const result = await client.execute(
3908
- "SELECT COUNT(*) as cnt FROM memories WHERE status = 'active' OR status IS NULL"
3909
- );
3910
- const row = result.rows[0];
3911
- return Number(row?.cnt ?? 0);
3912
- }
3913
- async function assertMemoryLimit() {
3914
- const license = await checkLicense();
3915
- if (license.memoryLimit < 0) return;
3916
- const count = await countActiveMemories();
3917
- if (count >= license.memoryLimit) {
3918
- throw new PlanLimitError(
3919
- `Memory limit reached: ${count}/${license.memoryLimit} active memories on the ${license.plan} plan. Upgrade at https://askexe.com to store more.`
3920
- );
3921
- }
3922
- }
3923
-
3924
- // src/adapters/claude/hooks/prompt-ingest-worker.ts
3925
- process.env.EXE_EMBED_PRIORITY = "low";
3926
- async function main() {
3927
- const promptText = process.env.EXE_PROMPT_TEXT;
3928
- const sessionId = process.env.EXE_SESSION_ID;
3929
- const agentId = process.env.AGENT_ID ?? "default";
3930
- const agentRole = process.env.AGENT_ROLE ?? "employee";
3931
- if (!promptText || !sessionId) {
3932
- process.stderr.write("[prompt-ingest-worker] Missing EXE_PROMPT_TEXT or EXE_SESSION_ID\n");
3933
- process.exit(1);
3934
- }
3935
- await initStore();
3936
- let vector;
3937
- let needsBackfill = false;
3938
- try {
3939
- const { embed: embed2 } = await Promise.resolve().then(() => (init_embedder(), embedder_exports));
3940
- vector = await embed2(promptText);
3941
- } catch (err) {
3942
- process.stderr.write(`[prompt-ingest-worker] EMBED FAILED: ${err instanceof Error ? err.message : String(err)}
3943
- `);
3944
- vector = null;
3945
- needsBackfill = true;
3946
- }
3947
- await assertMemoryLimit();
3948
- const confidence = agentId === "default" ? 0.9 : 0.7;
3949
- await writeMemory({
3950
- id: crypto2.randomUUID(),
3951
- agent_id: agentId,
3952
- agent_role: agentRole,
3953
- session_id: sessionId,
3954
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3955
- tool_name: "UserPrompt",
3956
- project_name: getProjectName(),
3957
- has_error: false,
3958
- raw_text: promptText,
3959
- vector,
3960
- confidence
3961
- });
3962
- await flushBatch();
3963
- if (needsBackfill) {
3964
- try {
3965
- const { EXE_AI_DIR: exeDir } = await Promise.resolve().then(() => (init_config(), config_exports));
3966
- const flagPath = path11.join(exeDir, "session-cache", "needs-backfill");
3967
- writeFileSync4(flagPath, "1");
3968
- } catch (err) {
3969
- process.stderr.write(`[prompt-ingest-worker] backfill flag write failed: ${err instanceof Error ? err.message : String(err)}
3970
- `);
3971
- }
3972
- }
3973
- }
3974
- main().catch((err) => {
3975
- process.stderr.write(`[prompt-ingest-worker] FATAL: ${err instanceof Error ? err.message : String(err)}
3976
- `);
3977
- }).finally(() => {
3978
- process.exit(0);
3979
- });