@askexenow/exe-os 0.8.1 → 0.8.2

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 (106) hide show
  1. package/package.json +1 -1
  2. package/dist/bin/backfill-responses.js +0 -2064
  3. package/dist/bin/backfill-vectors.js +0 -1771
  4. package/dist/bin/cleanup-stale-review-tasks.js +0 -1468
  5. package/dist/bin/cli.js +0 -21371
  6. package/dist/bin/exe-agent.js +0 -2016
  7. package/dist/bin/exe-assign.js +0 -2176
  8. package/dist/bin/exe-boot.js +0 -6332
  9. package/dist/bin/exe-call.js +0 -341
  10. package/dist/bin/exe-cloud.js +0 -861
  11. package/dist/bin/exe-dispatch.js +0 -1159
  12. package/dist/bin/exe-doctor.js +0 -1786
  13. package/dist/bin/exe-export-behaviors.js +0 -1637
  14. package/dist/bin/exe-forget.js +0 -1784
  15. package/dist/bin/exe-gateway.js +0 -8140
  16. package/dist/bin/exe-healthcheck.js +0 -207
  17. package/dist/bin/exe-heartbeat.js +0 -1778
  18. package/dist/bin/exe-kill.js +0 -1622
  19. package/dist/bin/exe-launch-agent.js +0 -1847
  20. package/dist/bin/exe-link.js +0 -192
  21. package/dist/bin/exe-new-employee.js +0 -1384
  22. package/dist/bin/exe-pending-messages.js +0 -1576
  23. package/dist/bin/exe-pending-notifications.js +0 -1450
  24. package/dist/bin/exe-pending-reviews.js +0 -1598
  25. package/dist/bin/exe-repo-drift.js +0 -95
  26. package/dist/bin/exe-review.js +0 -1742
  27. package/dist/bin/exe-search.js +0 -3116
  28. package/dist/bin/exe-session-cleanup.js +0 -3360
  29. package/dist/bin/exe-settings.js +0 -365
  30. package/dist/bin/exe-status.js +0 -1661
  31. package/dist/bin/exe-team.js +0 -1453
  32. package/dist/bin/git-sweep.js +0 -2441
  33. package/dist/bin/graph-backfill.js +0 -2111
  34. package/dist/bin/graph-export.js +0 -1747
  35. package/dist/bin/install.js +0 -661
  36. package/dist/bin/list-providers.js +0 -140
  37. package/dist/bin/scan-tasks.js +0 -2039
  38. package/dist/bin/setup.js +0 -2717
  39. package/dist/bin/shard-migrate.js +0 -1637
  40. package/dist/bin/update.js +0 -98
  41. package/dist/bin/wiki-sync.js +0 -1657
  42. package/dist/gateway/index.js +0 -9256
  43. package/dist/hooks/bug-report-worker.js +0 -2903
  44. package/dist/hooks/commit-complete.js +0 -2364
  45. package/dist/hooks/error-recall.js +0 -3327
  46. package/dist/hooks/exe-heartbeat-hook.js +0 -237
  47. package/dist/hooks/ingest-worker.js +0 -5065
  48. package/dist/hooks/ingest.js +0 -695
  49. package/dist/hooks/instructions-loaded.js +0 -2069
  50. package/dist/hooks/notification.js +0 -1915
  51. package/dist/hooks/post-compact.js +0 -1940
  52. package/dist/hooks/pre-compact.js +0 -1935
  53. package/dist/hooks/pre-tool-use.js +0 -2380
  54. package/dist/hooks/prompt-ingest-worker.js +0 -2291
  55. package/dist/hooks/prompt-submit.js +0 -5189
  56. package/dist/hooks/response-ingest-worker.js +0 -2431
  57. package/dist/hooks/session-end.js +0 -2196
  58. package/dist/hooks/session-start.js +0 -3259
  59. package/dist/hooks/stop.js +0 -2025
  60. package/dist/hooks/subagent-stop.js +0 -1915
  61. package/dist/hooks/summary-worker.js +0 -2931
  62. package/dist/index.js +0 -12327
  63. package/dist/lib/cloud-sync.js +0 -500
  64. package/dist/lib/config.js +0 -235
  65. package/dist/lib/consolidation.js +0 -481
  66. package/dist/lib/crypto.js +0 -51
  67. package/dist/lib/database.js +0 -834
  68. package/dist/lib/device-registry.js +0 -1009
  69. package/dist/lib/embedder.js +0 -645
  70. package/dist/lib/employee-templates.js +0 -570
  71. package/dist/lib/employees.js +0 -182
  72. package/dist/lib/error-detector.js +0 -156
  73. package/dist/lib/exe-daemon-client.js +0 -456
  74. package/dist/lib/exe-daemon.js +0 -8699
  75. package/dist/lib/file-grep.js +0 -215
  76. package/dist/lib/hybrid-search.js +0 -3064
  77. package/dist/lib/identity-templates.js +0 -441
  78. package/dist/lib/identity.js +0 -228
  79. package/dist/lib/keychain.js +0 -145
  80. package/dist/lib/license.js +0 -382
  81. package/dist/lib/messaging.js +0 -1389
  82. package/dist/lib/reminders.js +0 -63
  83. package/dist/lib/schedules.js +0 -1525
  84. package/dist/lib/session-registry.js +0 -52
  85. package/dist/lib/skill-learning.js +0 -488
  86. package/dist/lib/status-brief.js +0 -240
  87. package/dist/lib/store.js +0 -1740
  88. package/dist/lib/task-router.js +0 -128
  89. package/dist/lib/tasks.js +0 -2585
  90. package/dist/lib/tmux-routing.js +0 -2969
  91. package/dist/lib/tmux-status.js +0 -261
  92. package/dist/lib/tmux-transport.js +0 -83
  93. package/dist/lib/transport.js +0 -128
  94. package/dist/lib/ws-auth.js +0 -19
  95. package/dist/lib/ws-client.js +0 -160
  96. package/dist/mcp/server.js +0 -10812
  97. package/dist/mcp/tools/complete-reminder.js +0 -67
  98. package/dist/mcp/tools/create-reminder.js +0 -52
  99. package/dist/mcp/tools/create-task.js +0 -1903
  100. package/dist/mcp/tools/deactivate-behavior.js +0 -268
  101. package/dist/mcp/tools/list-reminders.js +0 -62
  102. package/dist/mcp/tools/list-tasks.js +0 -491
  103. package/dist/mcp/tools/send-message.js +0 -1395
  104. package/dist/mcp/tools/update-task.js +0 -1807
  105. package/dist/runtime/index.js +0 -7201
  106. package/dist/tui/App.js +0 -17874
@@ -1,2196 +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/lib/config.ts
18
- import { readFile, writeFile, mkdir } from "fs/promises";
19
- import { readFileSync, existsSync, renameSync } from "fs";
20
- import path from "path";
21
- import os from "os";
22
- function resolveDataDir() {
23
- if (process.env.EXE_OS_DIR) return process.env.EXE_OS_DIR;
24
- if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
25
- const newDir = path.join(os.homedir(), ".exe-os");
26
- const legacyDir = path.join(os.homedir(), ".exe-mem");
27
- if (!existsSync(newDir) && existsSync(legacyDir)) {
28
- try {
29
- renameSync(legacyDir, newDir);
30
- process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
31
- `);
32
- } catch {
33
- return legacyDir;
34
- }
35
- }
36
- return newDir;
37
- }
38
- function migrateLegacyConfig(raw) {
39
- if ("r2" in raw) {
40
- process.stderr.write(
41
- "[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"
42
- );
43
- delete raw.r2;
44
- }
45
- if ("syncIntervalMs" in raw) {
46
- delete raw.syncIntervalMs;
47
- }
48
- return raw;
49
- }
50
- function migrateConfig(raw) {
51
- const fromVersion = typeof raw.config_version === "number" ? raw.config_version : 0;
52
- let currentVersion = fromVersion;
53
- let migrated = false;
54
- if (currentVersion > CURRENT_CONFIG_VERSION) {
55
- return { config: raw, migrated: false, fromVersion };
56
- }
57
- for (const migration of CONFIG_MIGRATIONS) {
58
- if (currentVersion === migration.from && migration.to <= CURRENT_CONFIG_VERSION) {
59
- raw = migration.migrate(raw);
60
- currentVersion = migration.to;
61
- migrated = true;
62
- }
63
- }
64
- return { config: raw, migrated, fromVersion };
65
- }
66
- function normalizeScalingRoadmap(raw) {
67
- const defaultAuto = DEFAULT_CONFIG.scalingRoadmap.rerankerAutoTrigger;
68
- const userRoadmap = raw.scalingRoadmap ?? {};
69
- const userAuto = userRoadmap.rerankerAutoTrigger ?? {};
70
- if (userAuto.enabled === void 0 && raw.rerankerEnabled !== void 0) {
71
- userAuto.enabled = raw.rerankerEnabled;
72
- }
73
- raw.scalingRoadmap = {
74
- ...userRoadmap,
75
- rerankerAutoTrigger: { ...defaultAuto, ...userAuto }
76
- };
77
- }
78
- function normalizeSessionLifecycle(raw) {
79
- const defaultSL = DEFAULT_CONFIG.sessionLifecycle;
80
- const userSL = raw.sessionLifecycle ?? {};
81
- raw.sessionLifecycle = { ...defaultSL, ...userSL };
82
- }
83
- function normalizeAutoUpdate(raw) {
84
- const defaultAU = DEFAULT_CONFIG.autoUpdate;
85
- const userAU = raw.autoUpdate ?? {};
86
- raw.autoUpdate = { ...defaultAU, ...userAU };
87
- }
88
- async function loadConfig() {
89
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
90
- await mkdir(dir, { recursive: true });
91
- const configPath = path.join(dir, "config.json");
92
- if (!existsSync(configPath)) {
93
- return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
94
- }
95
- const raw = await readFile(configPath, "utf-8");
96
- try {
97
- let parsed = JSON.parse(raw);
98
- parsed = migrateLegacyConfig(parsed);
99
- const { config: migratedCfg, migrated, fromVersion } = migrateConfig(parsed);
100
- if (migrated) {
101
- process.stderr.write(`[exe-os] Config migrated from v${fromVersion} to v${migratedCfg.config_version}
102
- `);
103
- try {
104
- await writeFile(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
105
- } catch {
106
- }
107
- }
108
- normalizeScalingRoadmap(migratedCfg);
109
- normalizeSessionLifecycle(migratedCfg);
110
- normalizeAutoUpdate(migratedCfg);
111
- const config = { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db"), ...migratedCfg };
112
- if (config.dbPath.startsWith("~")) {
113
- config.dbPath = config.dbPath.replace(/^~/, os.homedir());
114
- }
115
- return config;
116
- } catch {
117
- return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
118
- }
119
- }
120
- var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
121
- var init_config = __esm({
122
- "src/lib/config.ts"() {
123
- "use strict";
124
- EXE_AI_DIR = resolveDataDir();
125
- DB_PATH = path.join(EXE_AI_DIR, "memories.db");
126
- MODELS_DIR = path.join(EXE_AI_DIR, "models");
127
- CONFIG_PATH = path.join(EXE_AI_DIR, "config.json");
128
- LEGACY_LANCE_PATH = path.join(EXE_AI_DIR, "local.lance");
129
- CURRENT_CONFIG_VERSION = 1;
130
- DEFAULT_CONFIG = {
131
- config_version: CURRENT_CONFIG_VERSION,
132
- dbPath: DB_PATH,
133
- modelFile: "jina-embeddings-v5-small-q4_k_m.gguf",
134
- embeddingDim: 1024,
135
- batchSize: 20,
136
- flushIntervalMs: 1e4,
137
- autoIngestion: true,
138
- autoRetrieval: true,
139
- searchMode: "hybrid",
140
- hookSearchMode: "hybrid",
141
- fileGrepEnabled: true,
142
- splashEffect: true,
143
- consolidationEnabled: true,
144
- consolidationIntervalMs: 6 * 60 * 60 * 1e3,
145
- consolidationModel: "claude-haiku-4-5-20251001",
146
- consolidationMaxCallsPerRun: 20,
147
- selfQueryRouter: true,
148
- selfQueryModel: "claude-haiku-4-5-20251001",
149
- rerankerEnabled: true,
150
- scalingRoadmap: {
151
- rerankerAutoTrigger: {
152
- enabled: true,
153
- broadQueryMinCardinality: 5e4,
154
- fetchTopK: 150,
155
- returnTopK: 5
156
- }
157
- },
158
- graphRagEnabled: true,
159
- wikiEnabled: false,
160
- wikiUrl: "",
161
- wikiApiKey: "",
162
- wikiSyncIntervalMs: 30 * 60 * 1e3,
163
- wikiWorkspaceMapping: {
164
- exe: "Executive",
165
- yoshi: "Engineering",
166
- mari: "Marketing",
167
- tom: "Engineering",
168
- sasha: "Production"
169
- },
170
- wikiAutoUpdate: true,
171
- wikiAutoUpdateThreshold: 0.5,
172
- wikiAutoUpdateCreateNew: true,
173
- skillLearning: true,
174
- skillThreshold: 3,
175
- skillModel: "claude-haiku-4-5-20251001",
176
- exeHeartbeat: {
177
- enabled: true,
178
- intervalSeconds: 60,
179
- staleInProgressThresholdHours: 2
180
- },
181
- sessionLifecycle: {
182
- idleKillEnabled: true,
183
- idleKillTicksRequired: 3,
184
- idleKillIntercomAckWindowMs: 1e4,
185
- maxAutoInstances: 10
186
- },
187
- autoUpdate: {
188
- checkOnBoot: true,
189
- autoInstall: false,
190
- checkIntervalMs: 24 * 60 * 60 * 1e3
191
- }
192
- };
193
- CONFIG_MIGRATIONS = [
194
- {
195
- from: 0,
196
- to: 1,
197
- migrate: (cfg) => {
198
- cfg.config_version = 1;
199
- return cfg;
200
- }
201
- }
202
- ];
203
- }
204
- });
205
-
206
- // src/types/memory.ts
207
- var EMBEDDING_DIM;
208
- var init_memory = __esm({
209
- "src/types/memory.ts"() {
210
- "use strict";
211
- EMBEDDING_DIM = 1024;
212
- }
213
- });
214
-
215
- // src/lib/database.ts
216
- var database_exports = {};
217
- __export(database_exports, {
218
- disposeDatabase: () => disposeDatabase,
219
- disposeTurso: () => disposeTurso,
220
- ensureSchema: () => ensureSchema,
221
- getClient: () => getClient,
222
- initDatabase: () => initDatabase,
223
- initTurso: () => initTurso,
224
- isInitialized: () => isInitialized
225
- });
226
- import { createClient } from "@libsql/client";
227
- async function initDatabase(config) {
228
- if (_client) {
229
- _client.close();
230
- _client = null;
231
- }
232
- const opts = {
233
- url: `file:${config.dbPath}`
234
- };
235
- if (config.encryptionKey) {
236
- opts.encryptionKey = config.encryptionKey;
237
- }
238
- _client = createClient(opts);
239
- }
240
- function isInitialized() {
241
- return _client !== null;
242
- }
243
- function getClient() {
244
- if (!_client) {
245
- throw new Error("Database client not initialized. Call initDatabase() first.");
246
- }
247
- return _client;
248
- }
249
- async function ensureSchema() {
250
- const client = getClient();
251
- await client.execute("PRAGMA journal_mode = WAL");
252
- await client.execute("PRAGMA busy_timeout = 5000");
253
- try {
254
- await client.execute("PRAGMA libsql_vector_search_ef = 128");
255
- } catch {
256
- }
257
- await client.executeMultiple(`
258
- CREATE TABLE IF NOT EXISTS memories (
259
- id TEXT PRIMARY KEY,
260
- agent_id TEXT NOT NULL,
261
- agent_role TEXT NOT NULL,
262
- session_id TEXT NOT NULL,
263
- timestamp TEXT NOT NULL,
264
- tool_name TEXT NOT NULL,
265
- project_name TEXT NOT NULL,
266
- has_error INTEGER NOT NULL DEFAULT 0,
267
- raw_text TEXT NOT NULL,
268
- vector F32_BLOB(1024),
269
- version INTEGER NOT NULL DEFAULT 0
270
- );
271
-
272
- CREATE INDEX IF NOT EXISTS idx_memories_agent
273
- ON memories(agent_id);
274
-
275
- CREATE INDEX IF NOT EXISTS idx_memories_timestamp
276
- ON memories(timestamp);
277
-
278
- CREATE INDEX IF NOT EXISTS idx_memories_session
279
- ON memories(session_id);
280
-
281
- CREATE INDEX IF NOT EXISTS idx_memories_project
282
- ON memories(project_name);
283
-
284
- CREATE INDEX IF NOT EXISTS idx_memories_tool
285
- ON memories(tool_name);
286
-
287
- CREATE INDEX IF NOT EXISTS idx_memories_version
288
- ON memories(version);
289
-
290
- CREATE INDEX IF NOT EXISTS idx_memories_agent_project
291
- ON memories(agent_id, project_name);
292
- `);
293
- await client.executeMultiple(`
294
- CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
295
- raw_text,
296
- content='memories',
297
- content_rowid='rowid'
298
- );
299
-
300
- CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
301
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
302
- END;
303
-
304
- CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
305
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
306
- END;
307
-
308
- CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
309
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
310
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
311
- END;
312
- `);
313
- await client.executeMultiple(`
314
- CREATE TABLE IF NOT EXISTS sync_meta (
315
- key TEXT PRIMARY KEY,
316
- value TEXT NOT NULL
317
- );
318
- `);
319
- await client.executeMultiple(`
320
- CREATE TABLE IF NOT EXISTS tasks (
321
- id TEXT PRIMARY KEY,
322
- title TEXT NOT NULL,
323
- assigned_to TEXT NOT NULL,
324
- assigned_by TEXT NOT NULL,
325
- project_name TEXT NOT NULL,
326
- priority TEXT NOT NULL DEFAULT 'p1',
327
- status TEXT NOT NULL DEFAULT 'open',
328
- task_file TEXT,
329
- created_at TEXT NOT NULL,
330
- updated_at TEXT NOT NULL
331
- );
332
-
333
- CREATE INDEX IF NOT EXISTS idx_tasks_assignee_status
334
- ON tasks(assigned_to, status);
335
- `);
336
- await client.executeMultiple(`
337
- CREATE TABLE IF NOT EXISTS behaviors (
338
- id TEXT PRIMARY KEY,
339
- agent_id TEXT NOT NULL,
340
- project_name TEXT,
341
- domain TEXT,
342
- content TEXT NOT NULL,
343
- active INTEGER NOT NULL DEFAULT 1,
344
- created_at TEXT NOT NULL,
345
- updated_at TEXT NOT NULL
346
- );
347
-
348
- CREATE INDEX IF NOT EXISTS idx_behaviors_agent
349
- ON behaviors(agent_id, active);
350
- `);
351
- try {
352
- const existing = await client.execute({
353
- sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = 'exe'",
354
- args: []
355
- });
356
- if (Number(existing.rows[0]?.cnt) === 0) {
357
- await client.executeMultiple(`
358
- INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
359
- VALUES
360
- (hex(randomblob(16)), 'exe', NULL, 'workflow', 'Don''t ask "keep going?" \u2014 just keep executing phases/plans autonomously', 1, '2026-03-25T00:00:00Z', '2026-03-25T00:00:00Z');
361
- INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
362
- VALUES
363
- (hex(randomblob(16)), 'exe', NULL, 'tool-use', 'Always use create_task MCP tool, never write .md files directly for task creation', 1, '2026-03-25T00:00:00Z', '2026-03-25T00:00:00Z');
364
- INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
365
- VALUES
366
- (hex(randomblob(16)), 'exe', NULL, 'workflow', 'Auto-start reviewing when idle and reviews are pending \u2014 never ask founder for permission', 1, '2026-03-25T00:00:00Z', '2026-03-25T00:00:00Z');
367
- `);
368
- }
369
- } catch {
370
- }
371
- try {
372
- await client.execute({
373
- sql: `ALTER TABLE behaviors ADD COLUMN priority TEXT DEFAULT 'p1'`,
374
- args: []
375
- });
376
- } catch {
377
- }
378
- try {
379
- await client.execute({
380
- sql: `ALTER TABLE tasks ADD COLUMN blocked_by TEXT`,
381
- args: []
382
- });
383
- } catch {
384
- }
385
- try {
386
- await client.execute({
387
- sql: `ALTER TABLE tasks ADD COLUMN parent_task_id TEXT`,
388
- args: []
389
- });
390
- } catch {
391
- }
392
- try {
393
- await client.execute({
394
- sql: `CREATE INDEX IF NOT EXISTS idx_tasks_parent_task_id
395
- ON tasks(parent_task_id)
396
- WHERE parent_task_id IS NOT NULL`,
397
- args: []
398
- });
399
- } catch {
400
- }
401
- try {
402
- await client.execute({
403
- sql: `UPDATE tasks SET status = 'done' WHERE status = 'completed'`,
404
- args: []
405
- });
406
- } catch {
407
- }
408
- try {
409
- await client.execute({
410
- sql: `ALTER TABLE tasks ADD COLUMN reviewer TEXT`,
411
- args: []
412
- });
413
- } catch {
414
- }
415
- try {
416
- await client.execute({
417
- sql: `ALTER TABLE tasks ADD COLUMN context TEXT`,
418
- args: []
419
- });
420
- } catch {
421
- }
422
- try {
423
- await client.execute({
424
- sql: `ALTER TABLE tasks ADD COLUMN result TEXT`,
425
- args: []
426
- });
427
- } catch {
428
- }
429
- try {
430
- await client.execute({
431
- sql: `ALTER TABLE tasks ADD COLUMN assigned_tmux TEXT`,
432
- args: []
433
- });
434
- } catch {
435
- }
436
- try {
437
- await client.execute({
438
- sql: `ALTER TABLE tasks ADD COLUMN checkpoint TEXT`,
439
- args: []
440
- });
441
- } catch {
442
- }
443
- try {
444
- await client.execute({
445
- sql: `ALTER TABLE tasks ADD COLUMN checkpoint_count INTEGER NOT NULL DEFAULT 0`,
446
- args: []
447
- });
448
- } catch {
449
- }
450
- try {
451
- await client.execute({
452
- sql: `ALTER TABLE tasks ADD COLUMN complexity TEXT NOT NULL DEFAULT 'standard'`,
453
- args: []
454
- });
455
- } catch {
456
- }
457
- try {
458
- await client.execute({
459
- sql: `ALTER TABLE memories ADD COLUMN task_id TEXT`,
460
- args: []
461
- });
462
- } catch {
463
- }
464
- try {
465
- await client.execute({
466
- sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
467
- args: []
468
- });
469
- } catch {
470
- }
471
- try {
472
- await client.execute({
473
- sql: `ALTER TABLE memories ADD COLUMN author_device_id TEXT`,
474
- args: []
475
- });
476
- } catch {
477
- }
478
- try {
479
- await client.execute({
480
- sql: `ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'`,
481
- args: []
482
- });
483
- } catch {
484
- }
485
- await client.executeMultiple(`
486
- CREATE TABLE IF NOT EXISTS consolidations (
487
- id TEXT PRIMARY KEY,
488
- consolidated_memory_id TEXT NOT NULL,
489
- source_memory_id TEXT NOT NULL,
490
- created_at TEXT NOT NULL
491
- );
492
-
493
- CREATE INDEX IF NOT EXISTS idx_consolidations_source
494
- ON consolidations(source_memory_id);
495
-
496
- CREATE INDEX IF NOT EXISTS idx_consolidations_consolidated
497
- ON consolidations(consolidated_memory_id);
498
- `);
499
- await client.executeMultiple(`
500
- CREATE TABLE IF NOT EXISTS reminders (
501
- id TEXT PRIMARY KEY,
502
- text TEXT NOT NULL,
503
- created_at TEXT NOT NULL,
504
- due_date TEXT,
505
- completed_at TEXT
506
- );
507
- `);
508
- await client.executeMultiple(`
509
- CREATE TABLE IF NOT EXISTS notifications (
510
- id TEXT PRIMARY KEY,
511
- agent_id TEXT NOT NULL,
512
- agent_role TEXT NOT NULL,
513
- event TEXT NOT NULL,
514
- project TEXT NOT NULL,
515
- summary TEXT NOT NULL,
516
- task_file TEXT,
517
- read INTEGER NOT NULL DEFAULT 0,
518
- created_at TEXT NOT NULL
519
- );
520
-
521
- CREATE INDEX IF NOT EXISTS idx_notifications_read
522
- ON notifications(read);
523
-
524
- CREATE INDEX IF NOT EXISTS idx_notifications_agent
525
- ON notifications(agent_id);
526
-
527
- CREATE INDEX IF NOT EXISTS idx_notifications_task_file
528
- ON notifications(task_file);
529
- `);
530
- await client.executeMultiple(`
531
- CREATE TABLE IF NOT EXISTS schedules (
532
- id TEXT PRIMARY KEY,
533
- cron TEXT NOT NULL,
534
- description TEXT NOT NULL,
535
- job_type TEXT NOT NULL DEFAULT 'report',
536
- prompt TEXT,
537
- assigned_to TEXT,
538
- project_name TEXT,
539
- active INTEGER NOT NULL DEFAULT 1,
540
- use_crontab INTEGER NOT NULL DEFAULT 0,
541
- created_at TEXT NOT NULL
542
- );
543
- `);
544
- await client.executeMultiple(`
545
- CREATE TABLE IF NOT EXISTS device_registry (
546
- device_id TEXT PRIMARY KEY,
547
- friendly_name TEXT NOT NULL,
548
- hostname TEXT NOT NULL,
549
- projects TEXT NOT NULL DEFAULT '[]',
550
- agents TEXT NOT NULL DEFAULT '[]',
551
- connected INTEGER DEFAULT 0,
552
- last_seen TEXT NOT NULL
553
- );
554
- `);
555
- await client.executeMultiple(`
556
- CREATE TABLE IF NOT EXISTS messages (
557
- id TEXT PRIMARY KEY,
558
- from_agent TEXT NOT NULL,
559
- from_device TEXT NOT NULL DEFAULT 'local',
560
- target_agent TEXT NOT NULL,
561
- target_project TEXT,
562
- target_device TEXT NOT NULL DEFAULT 'local',
563
- content TEXT NOT NULL,
564
- priority TEXT DEFAULT 'normal',
565
- status TEXT DEFAULT 'pending',
566
- server_seq INTEGER,
567
- retry_count INTEGER DEFAULT 0,
568
- created_at TEXT NOT NULL,
569
- delivered_at TEXT,
570
- processed_at TEXT,
571
- failed_at TEXT,
572
- failure_reason TEXT
573
- );
574
-
575
- CREATE INDEX IF NOT EXISTS idx_messages_target
576
- ON messages(target_agent, status);
577
-
578
- CREATE INDEX IF NOT EXISTS idx_messages_conversation_order
579
- ON messages(target_agent, from_agent, server_seq);
580
- `);
581
- try {
582
- await client.execute({
583
- sql: `UPDATE memories SET project_name = 'exe-create' WHERE project_name = 'web'`,
584
- args: []
585
- });
586
- await client.execute({
587
- sql: `UPDATE memories SET project_name = 'exe-os' WHERE project_name = 'worker'`,
588
- args: []
589
- });
590
- await client.execute({
591
- sql: `UPDATE tasks SET project_name = 'exe-create' WHERE project_name = 'web'`,
592
- args: []
593
- });
594
- await client.execute({
595
- sql: `UPDATE tasks SET project_name = 'exe-os' WHERE project_name = 'worker'`,
596
- args: []
597
- });
598
- } catch {
599
- }
600
- await client.executeMultiple(`
601
- CREATE TABLE IF NOT EXISTS trajectories (
602
- id TEXT PRIMARY KEY,
603
- task_id TEXT NOT NULL,
604
- agent_id TEXT NOT NULL,
605
- project_name TEXT NOT NULL,
606
- task_title TEXT NOT NULL,
607
- signature TEXT NOT NULL,
608
- signature_hash TEXT NOT NULL,
609
- tool_count INTEGER NOT NULL,
610
- skill_id TEXT,
611
- created_at TEXT NOT NULL
612
- );
613
-
614
- CREATE INDEX IF NOT EXISTS idx_trajectories_hash
615
- ON trajectories(signature_hash);
616
-
617
- CREATE INDEX IF NOT EXISTS idx_trajectories_agent
618
- ON trajectories(agent_id);
619
- `);
620
- try {
621
- await client.execute("ALTER TABLE trajectories ADD COLUMN skill_id TEXT");
622
- } catch {
623
- }
624
- await client.executeMultiple(`
625
- CREATE TABLE IF NOT EXISTS consolidations (
626
- id TEXT PRIMARY KEY,
627
- consolidated_memory_id TEXT NOT NULL,
628
- source_memory_id TEXT NOT NULL,
629
- created_at TEXT NOT NULL
630
- );
631
-
632
- CREATE INDEX IF NOT EXISTS idx_consolidations_source
633
- ON consolidations(source_memory_id);
634
- `);
635
- await client.executeMultiple(`
636
- CREATE TABLE IF NOT EXISTS audit_trail (
637
- id INTEGER PRIMARY KEY AUTOINCREMENT,
638
- timestamp TEXT NOT NULL,
639
- session_id TEXT NOT NULL,
640
- agent_id TEXT NOT NULL,
641
- tool TEXT NOT NULL,
642
- input TEXT,
643
- decision TEXT NOT NULL,
644
- reason TEXT,
645
- is_customer_facing INTEGER NOT NULL DEFAULT 0
646
- );
647
-
648
- CREATE INDEX IF NOT EXISTS idx_audit_trail_agent
649
- ON audit_trail(agent_id, timestamp);
650
-
651
- CREATE INDEX IF NOT EXISTS idx_audit_trail_session
652
- ON audit_trail(session_id);
653
- `);
654
- try {
655
- await client.execute({
656
- sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
657
- args: []
658
- });
659
- } catch {
660
- }
661
- try {
662
- await client.execute({
663
- sql: `ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5`,
664
- args: []
665
- });
666
- } catch {
667
- }
668
- try {
669
- await client.execute({
670
- sql: `ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'`,
671
- args: []
672
- });
673
- } catch {
674
- }
675
- try {
676
- await client.execute({
677
- sql: `ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7`,
678
- args: []
679
- });
680
- } catch {
681
- }
682
- try {
683
- await client.execute({
684
- sql: `ALTER TABLE memories ADD COLUMN last_accessed TEXT`,
685
- args: []
686
- });
687
- } catch {
688
- }
689
- try {
690
- await client.execute({
691
- sql: `UPDATE memories SET last_accessed = timestamp WHERE last_accessed IS NULL`,
692
- args: []
693
- });
694
- } catch {
695
- }
696
- try {
697
- await client.execute({
698
- sql: `ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0`,
699
- args: []
700
- });
701
- } catch {
702
- }
703
- try {
704
- await client.execute({
705
- sql: `ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0`,
706
- args: []
707
- });
708
- } catch {
709
- }
710
- for (const col of [
711
- "ALTER TABLE memories ADD COLUMN content_hash TEXT",
712
- "ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT"
713
- ]) {
714
- try {
715
- await client.execute(col);
716
- } catch {
717
- }
718
- }
719
- await client.executeMultiple(`
720
- CREATE TABLE IF NOT EXISTS entities (
721
- id TEXT PRIMARY KEY,
722
- name TEXT NOT NULL,
723
- type TEXT NOT NULL,
724
- first_seen TEXT NOT NULL,
725
- last_seen TEXT NOT NULL,
726
- properties TEXT DEFAULT '{}',
727
- UNIQUE(name, type)
728
- );
729
-
730
- CREATE TABLE IF NOT EXISTS relationships (
731
- id TEXT PRIMARY KEY,
732
- source_entity_id TEXT NOT NULL,
733
- target_entity_id TEXT NOT NULL,
734
- type TEXT NOT NULL,
735
- weight REAL DEFAULT 1.0,
736
- timestamp TEXT NOT NULL,
737
- properties TEXT DEFAULT '{}',
738
- UNIQUE(source_entity_id, target_entity_id, type)
739
- );
740
-
741
- CREATE TABLE IF NOT EXISTS entity_memories (
742
- entity_id TEXT NOT NULL,
743
- memory_id TEXT NOT NULL,
744
- PRIMARY KEY (entity_id, memory_id)
745
- );
746
-
747
- CREATE TABLE IF NOT EXISTS relationship_memories (
748
- relationship_id TEXT NOT NULL,
749
- memory_id TEXT NOT NULL,
750
- PRIMARY KEY (relationship_id, memory_id)
751
- );
752
-
753
- CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
754
- CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type);
755
- CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_entity_id);
756
- CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_entity_id);
757
-
758
- CREATE TABLE IF NOT EXISTS hyperedges (
759
- id TEXT PRIMARY KEY,
760
- label TEXT NOT NULL,
761
- relation TEXT NOT NULL,
762
- confidence REAL DEFAULT 1.0,
763
- timestamp TEXT NOT NULL
764
- );
765
-
766
- CREATE TABLE IF NOT EXISTS hyperedge_nodes (
767
- hyperedge_id TEXT NOT NULL,
768
- entity_id TEXT NOT NULL,
769
- PRIMARY KEY (hyperedge_id, entity_id)
770
- );
771
- `);
772
- await client.executeMultiple(`
773
- CREATE TABLE IF NOT EXISTS entity_aliases (
774
- alias TEXT NOT NULL PRIMARY KEY,
775
- canonical_entity_id TEXT NOT NULL
776
- );
777
- CREATE INDEX IF NOT EXISTS idx_entity_aliases_canonical ON entity_aliases(canonical_entity_id);
778
- `);
779
- for (const col of [
780
- "ALTER TABLE relationships ADD COLUMN confidence REAL DEFAULT 1.0",
781
- "ALTER TABLE relationships ADD COLUMN confidence_label TEXT DEFAULT 'extracted'"
782
- ]) {
783
- try {
784
- await client.execute(col);
785
- } catch {
786
- }
787
- }
788
- try {
789
- await client.execute(
790
- `CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)`
791
- );
792
- } catch {
793
- }
794
- await client.executeMultiple(`
795
- CREATE TABLE IF NOT EXISTS identity (
796
- id INTEGER PRIMARY KEY AUTOINCREMENT,
797
- agent_id TEXT NOT NULL UNIQUE,
798
- content_hash TEXT NOT NULL,
799
- updated_at TEXT NOT NULL,
800
- updated_by TEXT NOT NULL
801
- );
802
-
803
- CREATE INDEX IF NOT EXISTS idx_identity_agent ON identity(agent_id);
804
- `);
805
- await client.executeMultiple(`
806
- CREATE TABLE IF NOT EXISTS chat_history (
807
- id INTEGER PRIMARY KEY AUTOINCREMENT,
808
- session_id TEXT NOT NULL,
809
- role TEXT NOT NULL,
810
- content TEXT NOT NULL,
811
- tool_name TEXT,
812
- tool_id TEXT,
813
- is_error INTEGER NOT NULL DEFAULT 0,
814
- timestamp INTEGER NOT NULL
815
- );
816
-
817
- CREATE INDEX IF NOT EXISTS idx_chat_history_session
818
- ON chat_history(session_id, id);
819
- `);
820
- await client.executeMultiple(`
821
- CREATE TABLE IF NOT EXISTS workspaces (
822
- id TEXT PRIMARY KEY,
823
- slug TEXT NOT NULL UNIQUE,
824
- name TEXT NOT NULL,
825
- owner_agent_id TEXT,
826
- created_at TEXT NOT NULL,
827
- metadata TEXT
828
- );
829
-
830
- CREATE INDEX IF NOT EXISTS idx_workspaces_slug
831
- ON workspaces(slug);
832
- `);
833
- await client.executeMultiple(`
834
- CREATE TABLE IF NOT EXISTS documents (
835
- id TEXT PRIMARY KEY,
836
- workspace_id TEXT NOT NULL,
837
- filename TEXT NOT NULL,
838
- mime TEXT,
839
- source_type TEXT,
840
- user_id TEXT,
841
- uploaded_at TEXT NOT NULL,
842
- metadata TEXT,
843
- FOREIGN KEY (workspace_id) REFERENCES workspaces(id)
844
- );
845
-
846
- CREATE INDEX IF NOT EXISTS idx_documents_workspace
847
- ON documents(workspace_id);
848
-
849
- CREATE INDEX IF NOT EXISTS idx_documents_user
850
- ON documents(user_id);
851
- `);
852
- for (const column of [
853
- "workspace_id TEXT",
854
- "document_id TEXT",
855
- "user_id TEXT",
856
- "char_offset INTEGER",
857
- "page_number INTEGER"
858
- ]) {
859
- try {
860
- await client.execute({
861
- sql: `ALTER TABLE memories ADD COLUMN ${column}`,
862
- args: []
863
- });
864
- } catch {
865
- }
866
- }
867
- for (const col of [
868
- "ALTER TABLE memories ADD COLUMN source_path TEXT",
869
- "ALTER TABLE memories ADD COLUMN source_type TEXT DEFAULT 'text'"
870
- ]) {
871
- try {
872
- await client.execute(col);
873
- } catch {
874
- }
875
- }
876
- await client.executeMultiple(`
877
- CREATE INDEX IF NOT EXISTS idx_memories_workspace
878
- ON memories(workspace_id);
879
-
880
- CREATE INDEX IF NOT EXISTS idx_memories_document
881
- ON memories(document_id);
882
-
883
- CREATE INDEX IF NOT EXISTS idx_memories_user
884
- ON memories(user_id);
885
- `);
886
- await client.executeMultiple(`
887
- CREATE TABLE IF NOT EXISTS session_kills (
888
- id TEXT PRIMARY KEY,
889
- session_name TEXT NOT NULL,
890
- agent_id TEXT NOT NULL,
891
- killed_at TIMESTAMP NOT NULL,
892
- reason TEXT NOT NULL,
893
- ticks_idle INTEGER,
894
- estimated_tokens_saved INTEGER
895
- );
896
-
897
- CREATE INDEX IF NOT EXISTS idx_session_kills_killed_at
898
- ON session_kills(killed_at);
899
-
900
- CREATE INDEX IF NOT EXISTS idx_session_kills_agent
901
- ON session_kills(agent_id);
902
- `);
903
- await client.executeMultiple(`
904
- CREATE TABLE IF NOT EXISTS conversations (
905
- id TEXT PRIMARY KEY,
906
- platform TEXT NOT NULL,
907
- external_id TEXT,
908
- sender_id TEXT NOT NULL,
909
- sender_name TEXT,
910
- sender_phone TEXT,
911
- sender_email TEXT,
912
- recipient_id TEXT,
913
- channel_id TEXT NOT NULL,
914
- thread_id TEXT,
915
- reply_to_id TEXT,
916
- content_text TEXT,
917
- content_media TEXT,
918
- content_metadata TEXT,
919
- agent_response TEXT,
920
- agent_name TEXT,
921
- timestamp TEXT NOT NULL,
922
- ingested_at TEXT NOT NULL
923
- );
924
-
925
- CREATE INDEX IF NOT EXISTS idx_conversations_platform
926
- ON conversations(platform);
927
-
928
- CREATE INDEX IF NOT EXISTS idx_conversations_sender
929
- ON conversations(sender_id);
930
-
931
- CREATE INDEX IF NOT EXISTS idx_conversations_timestamp
932
- ON conversations(timestamp);
933
-
934
- CREATE INDEX IF NOT EXISTS idx_conversations_thread
935
- ON conversations(thread_id);
936
-
937
- CREATE INDEX IF NOT EXISTS idx_conversations_channel
938
- ON conversations(channel_id);
939
- `);
940
- try {
941
- await client.execute({
942
- sql: `ALTER TABLE tasks ADD COLUMN budget_tokens INTEGER`,
943
- args: []
944
- });
945
- } catch {
946
- }
947
- try {
948
- await client.execute({
949
- sql: `ALTER TABLE tasks ADD COLUMN budget_fallback_model TEXT`,
950
- args: []
951
- });
952
- } catch {
953
- }
954
- try {
955
- await client.execute({
956
- sql: `ALTER TABLE tasks ADD COLUMN tokens_used INTEGER DEFAULT 0`,
957
- args: []
958
- });
959
- } catch {
960
- }
961
- try {
962
- await client.execute({
963
- sql: `ALTER TABLE tasks ADD COLUMN tokens_warned_at INTEGER`,
964
- args: []
965
- });
966
- } catch {
967
- }
968
- await client.executeMultiple(`
969
- CREATE VIRTUAL TABLE IF NOT EXISTS conversations_fts USING fts5(
970
- content_text,
971
- sender_name,
972
- agent_response,
973
- content='conversations',
974
- content_rowid='rowid'
975
- );
976
-
977
- CREATE TRIGGER IF NOT EXISTS conversations_fts_ai AFTER INSERT ON conversations BEGIN
978
- INSERT INTO conversations_fts(rowid, content_text, sender_name, agent_response)
979
- VALUES (new.rowid, new.content_text, new.sender_name, new.agent_response);
980
- END;
981
-
982
- CREATE TRIGGER IF NOT EXISTS conversations_fts_ad AFTER DELETE ON conversations BEGIN
983
- INSERT INTO conversations_fts(conversations_fts, rowid, content_text, sender_name, agent_response)
984
- VALUES('delete', old.rowid, old.content_text, old.sender_name, old.agent_response);
985
- END;
986
-
987
- CREATE TRIGGER IF NOT EXISTS conversations_fts_au AFTER UPDATE ON conversations BEGIN
988
- INSERT INTO conversations_fts(conversations_fts, rowid, content_text, sender_name, agent_response)
989
- VALUES('delete', old.rowid, old.content_text, old.sender_name, old.agent_response);
990
- INSERT INTO conversations_fts(rowid, content_text, sender_name, agent_response)
991
- VALUES (new.rowid, new.content_text, new.sender_name, new.agent_response);
992
- END;
993
- `);
994
- try {
995
- await client.execute({
996
- sql: `ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3`,
997
- args: []
998
- });
999
- } catch {
1000
- }
1001
- try {
1002
- await client.execute(
1003
- `CREATE INDEX IF NOT EXISTS idx_memories_tier ON memories(tier)`
1004
- );
1005
- } catch {
1006
- }
1007
- try {
1008
- await client.execute({
1009
- sql: `UPDATE memories SET tier = 1 WHERE tool_name = 'commit_to_long_term_memory' AND importance >= 8 AND tier = 3`,
1010
- args: []
1011
- });
1012
- await client.execute({
1013
- sql: `UPDATE memories SET tier = 2 WHERE tool_name IN ('store_memory', 'manual') AND importance >= 5 AND tier = 3`,
1014
- args: []
1015
- });
1016
- } catch {
1017
- }
1018
- try {
1019
- await client.execute({
1020
- sql: `ALTER TABLE memories ADD COLUMN supersedes_id TEXT`,
1021
- args: []
1022
- });
1023
- } catch {
1024
- }
1025
- try {
1026
- await client.execute(
1027
- `CREATE INDEX IF NOT EXISTS idx_memories_supersedes ON memories(supersedes_id) WHERE supersedes_id IS NOT NULL`
1028
- );
1029
- } catch {
1030
- }
1031
- for (const col of [
1032
- "ALTER TABLE tasks ADD COLUMN checkpoint TEXT",
1033
- "ALTER TABLE tasks ADD COLUMN checkpoint_count INTEGER DEFAULT 0"
1034
- ]) {
1035
- try {
1036
- await client.execute(col);
1037
- } catch {
1038
- }
1039
- }
1040
- }
1041
- async function disposeDatabase() {
1042
- if (_client) {
1043
- _client.close();
1044
- _client = null;
1045
- }
1046
- }
1047
- var _client, initTurso, disposeTurso;
1048
- var init_database = __esm({
1049
- "src/lib/database.ts"() {
1050
- "use strict";
1051
- _client = null;
1052
- initTurso = initDatabase;
1053
- disposeTurso = disposeDatabase;
1054
- }
1055
- });
1056
-
1057
- // src/lib/keychain.ts
1058
- import { readFile as readFile2, writeFile as writeFile2, unlink, mkdir as mkdir2, chmod } from "fs/promises";
1059
- import { existsSync as existsSync2 } from "fs";
1060
- import path3 from "path";
1061
- import crypto from "crypto";
1062
- function getKeyDir() {
1063
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path3.join(process.env.HOME ?? "/tmp", ".exe-os");
1064
- }
1065
- function getKeyPath() {
1066
- return path3.join(getKeyDir(), "master.key");
1067
- }
1068
- async function tryKeytar() {
1069
- try {
1070
- return await import("keytar");
1071
- } catch {
1072
- return null;
1073
- }
1074
- }
1075
- async function getMasterKey() {
1076
- const keytar = await tryKeytar();
1077
- if (keytar) {
1078
- try {
1079
- const stored = await keytar.getPassword(SERVICE, ACCOUNT);
1080
- if (stored) {
1081
- return Buffer.from(stored, "base64");
1082
- }
1083
- } catch {
1084
- }
1085
- }
1086
- const keyPath = getKeyPath();
1087
- if (!existsSync2(keyPath)) {
1088
- return null;
1089
- }
1090
- try {
1091
- const content = await readFile2(keyPath, "utf-8");
1092
- return Buffer.from(content.trim(), "base64");
1093
- } catch {
1094
- return null;
1095
- }
1096
- }
1097
- var SERVICE, ACCOUNT;
1098
- var init_keychain = __esm({
1099
- "src/lib/keychain.ts"() {
1100
- "use strict";
1101
- SERVICE = "exe-mem";
1102
- ACCOUNT = "master-key";
1103
- }
1104
- });
1105
-
1106
- // src/lib/shard-manager.ts
1107
- var shard_manager_exports = {};
1108
- __export(shard_manager_exports, {
1109
- disposeShards: () => disposeShards,
1110
- ensureShardSchema: () => ensureShardSchema,
1111
- getReadyShardClient: () => getReadyShardClient,
1112
- getShardClient: () => getShardClient,
1113
- getShardsDir: () => getShardsDir,
1114
- initShardManager: () => initShardManager,
1115
- isShardingEnabled: () => isShardingEnabled,
1116
- listShards: () => listShards,
1117
- shardExists: () => shardExists
1118
- });
1119
- import path4 from "path";
1120
- import { existsSync as existsSync3, mkdirSync as mkdirSync2 } from "fs";
1121
- import { createClient as createClient2 } from "@libsql/client";
1122
- function initShardManager(encryptionKey) {
1123
- _encryptionKey = encryptionKey;
1124
- if (!existsSync3(SHARDS_DIR)) {
1125
- mkdirSync2(SHARDS_DIR, { recursive: true });
1126
- }
1127
- _shardingEnabled = true;
1128
- }
1129
- function isShardingEnabled() {
1130
- return _shardingEnabled;
1131
- }
1132
- function getShardsDir() {
1133
- return SHARDS_DIR;
1134
- }
1135
- function getShardClient(projectName) {
1136
- if (!_encryptionKey) {
1137
- throw new Error("Shard manager not initialized. Call initShardManager() first.");
1138
- }
1139
- const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1140
- if (!safeName) {
1141
- throw new Error(`Invalid project name for shard: "${projectName}"`);
1142
- }
1143
- const cached = _shards.get(safeName);
1144
- if (cached) return cached;
1145
- const dbPath = path4.join(SHARDS_DIR, `${safeName}.db`);
1146
- const client = createClient2({
1147
- url: `file:${dbPath}`,
1148
- encryptionKey: _encryptionKey
1149
- });
1150
- _shards.set(safeName, client);
1151
- return client;
1152
- }
1153
- function shardExists(projectName) {
1154
- const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1155
- return existsSync3(path4.join(SHARDS_DIR, `${safeName}.db`));
1156
- }
1157
- function listShards() {
1158
- if (!existsSync3(SHARDS_DIR)) return [];
1159
- const { readdirSync: readdirSync3 } = __require("fs");
1160
- return readdirSync3(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
1161
- }
1162
- async function ensureShardSchema(client) {
1163
- await client.execute("PRAGMA journal_mode = WAL");
1164
- await client.execute("PRAGMA busy_timeout = 5000");
1165
- try {
1166
- await client.execute("PRAGMA libsql_vector_search_ef = 128");
1167
- } catch {
1168
- }
1169
- await client.executeMultiple(`
1170
- CREATE TABLE IF NOT EXISTS memories (
1171
- id TEXT PRIMARY KEY,
1172
- agent_id TEXT NOT NULL,
1173
- agent_role TEXT NOT NULL,
1174
- session_id TEXT NOT NULL,
1175
- timestamp TEXT NOT NULL,
1176
- tool_name TEXT NOT NULL,
1177
- project_name TEXT NOT NULL,
1178
- has_error INTEGER NOT NULL DEFAULT 0,
1179
- raw_text TEXT NOT NULL,
1180
- vector F32_BLOB(1024),
1181
- version INTEGER NOT NULL DEFAULT 0
1182
- );
1183
-
1184
- CREATE INDEX IF NOT EXISTS idx_memories_agent ON memories(agent_id);
1185
- CREATE INDEX IF NOT EXISTS idx_memories_timestamp ON memories(timestamp);
1186
- CREATE INDEX IF NOT EXISTS idx_memories_agent_project ON memories(agent_id, project_name);
1187
- `);
1188
- await client.executeMultiple(`
1189
- CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
1190
- raw_text,
1191
- content='memories',
1192
- content_rowid='rowid'
1193
- );
1194
-
1195
- CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
1196
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1197
- END;
1198
-
1199
- CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
1200
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1201
- END;
1202
-
1203
- CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
1204
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1205
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1206
- END;
1207
- `);
1208
- for (const col of [
1209
- "ALTER TABLE memories ADD COLUMN task_id TEXT",
1210
- "ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0",
1211
- "ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5",
1212
- "ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'",
1213
- "ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0",
1214
- "ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0",
1215
- "ALTER TABLE memories ADD COLUMN content_hash TEXT",
1216
- "ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT",
1217
- "ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7",
1218
- "ALTER TABLE memories ADD COLUMN last_accessed TEXT",
1219
- // Wiki linkage columns (must match database.ts)
1220
- "ALTER TABLE memories ADD COLUMN workspace_id TEXT",
1221
- "ALTER TABLE memories ADD COLUMN document_id TEXT",
1222
- "ALTER TABLE memories ADD COLUMN user_id TEXT",
1223
- "ALTER TABLE memories ADD COLUMN char_offset INTEGER",
1224
- "ALTER TABLE memories ADD COLUMN page_number INTEGER",
1225
- // Source provenance columns (must match database.ts)
1226
- "ALTER TABLE memories ADD COLUMN source_path TEXT",
1227
- "ALTER TABLE memories ADD COLUMN source_type TEXT DEFAULT 'text'",
1228
- "ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3",
1229
- "ALTER TABLE memories ADD COLUMN supersedes_id TEXT"
1230
- ]) {
1231
- try {
1232
- await client.execute(col);
1233
- } catch {
1234
- }
1235
- }
1236
- for (const idx of [
1237
- "CREATE INDEX IF NOT EXISTS idx_memories_tier ON memories(tier)",
1238
- "CREATE INDEX IF NOT EXISTS idx_memories_supersedes ON memories(supersedes_id) WHERE supersedes_id IS NOT NULL"
1239
- ]) {
1240
- try {
1241
- await client.execute(idx);
1242
- } catch {
1243
- }
1244
- }
1245
- try {
1246
- await client.execute("CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)");
1247
- } catch {
1248
- }
1249
- for (const idx of [
1250
- "CREATE INDEX IF NOT EXISTS idx_memories_workspace ON memories(workspace_id)",
1251
- "CREATE INDEX IF NOT EXISTS idx_memories_document ON memories(document_id)",
1252
- "CREATE INDEX IF NOT EXISTS idx_memories_user ON memories(user_id)"
1253
- ]) {
1254
- try {
1255
- await client.execute(idx);
1256
- } catch {
1257
- }
1258
- }
1259
- await client.executeMultiple(`
1260
- CREATE TABLE IF NOT EXISTS entities (
1261
- id TEXT PRIMARY KEY,
1262
- name TEXT NOT NULL,
1263
- type TEXT NOT NULL,
1264
- first_seen TEXT NOT NULL,
1265
- last_seen TEXT NOT NULL,
1266
- properties TEXT DEFAULT '{}',
1267
- UNIQUE(name, type)
1268
- );
1269
-
1270
- CREATE TABLE IF NOT EXISTS relationships (
1271
- id TEXT PRIMARY KEY,
1272
- source_entity_id TEXT NOT NULL,
1273
- target_entity_id TEXT NOT NULL,
1274
- type TEXT NOT NULL,
1275
- weight REAL DEFAULT 1.0,
1276
- timestamp TEXT NOT NULL,
1277
- properties TEXT DEFAULT '{}',
1278
- UNIQUE(source_entity_id, target_entity_id, type)
1279
- );
1280
-
1281
- CREATE TABLE IF NOT EXISTS entity_memories (
1282
- entity_id TEXT NOT NULL,
1283
- memory_id TEXT NOT NULL,
1284
- PRIMARY KEY (entity_id, memory_id)
1285
- );
1286
-
1287
- CREATE TABLE IF NOT EXISTS relationship_memories (
1288
- relationship_id TEXT NOT NULL,
1289
- memory_id TEXT NOT NULL,
1290
- PRIMARY KEY (relationship_id, memory_id)
1291
- );
1292
-
1293
- CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
1294
- CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type);
1295
- CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_entity_id);
1296
- CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_entity_id);
1297
- CREATE INDEX IF NOT EXISTS idx_relationships_type ON relationships(type);
1298
-
1299
- CREATE TABLE IF NOT EXISTS hyperedges (
1300
- id TEXT PRIMARY KEY,
1301
- label TEXT NOT NULL,
1302
- relation TEXT NOT NULL,
1303
- confidence REAL DEFAULT 1.0,
1304
- timestamp TEXT NOT NULL
1305
- );
1306
-
1307
- CREATE TABLE IF NOT EXISTS hyperedge_nodes (
1308
- hyperedge_id TEXT NOT NULL,
1309
- entity_id TEXT NOT NULL,
1310
- PRIMARY KEY (hyperedge_id, entity_id)
1311
- );
1312
- `);
1313
- for (const col of [
1314
- "ALTER TABLE relationships ADD COLUMN confidence REAL DEFAULT 1.0",
1315
- "ALTER TABLE relationships ADD COLUMN confidence_label TEXT DEFAULT 'extracted'"
1316
- ]) {
1317
- try {
1318
- await client.execute(col);
1319
- } catch {
1320
- }
1321
- }
1322
- }
1323
- async function getReadyShardClient(projectName) {
1324
- const client = getShardClient(projectName);
1325
- await ensureShardSchema(client);
1326
- return client;
1327
- }
1328
- function disposeShards() {
1329
- for (const [, client] of _shards) {
1330
- client.close();
1331
- }
1332
- _shards.clear();
1333
- _shardingEnabled = false;
1334
- _encryptionKey = null;
1335
- }
1336
- var SHARDS_DIR, _shards, _encryptionKey, _shardingEnabled;
1337
- var init_shard_manager = __esm({
1338
- "src/lib/shard-manager.ts"() {
1339
- "use strict";
1340
- init_config();
1341
- SHARDS_DIR = path4.join(EXE_AI_DIR, "shards");
1342
- _shards = /* @__PURE__ */ new Map();
1343
- _encryptionKey = null;
1344
- _shardingEnabled = false;
1345
- }
1346
- });
1347
-
1348
- // src/lib/store.ts
1349
- var store_exports = {};
1350
- __export(store_exports, {
1351
- attachDocumentMetadata: () => attachDocumentMetadata,
1352
- buildWikiScopeFilter: () => buildWikiScopeFilter,
1353
- classifyTier: () => classifyTier,
1354
- disposeStore: () => disposeStore,
1355
- flushBatch: () => flushBatch,
1356
- flushTier3: () => flushTier3,
1357
- getMemoryCardinality: () => getMemoryCardinality,
1358
- initStore: () => initStore,
1359
- reserveVersions: () => reserveVersions,
1360
- searchMemories: () => searchMemories,
1361
- updateMemoryStatus: () => updateMemoryStatus,
1362
- vectorToBlob: () => vectorToBlob,
1363
- writeMemory: () => writeMemory
1364
- });
1365
- async function initStore(options) {
1366
- if (_flushTimer !== null) {
1367
- clearInterval(_flushTimer);
1368
- _flushTimer = null;
1369
- }
1370
- _pendingRecords = [];
1371
- _flushing = false;
1372
- _batchSize = options?.batchSize ?? 20;
1373
- _flushIntervalMs = options?.flushIntervalMs ?? 1e4;
1374
- let dbPath = options?.dbPath;
1375
- if (!dbPath) {
1376
- const config = await loadConfig();
1377
- dbPath = config.dbPath;
1378
- }
1379
- let masterKey = options?.masterKey ?? null;
1380
- if (!masterKey) {
1381
- masterKey = await getMasterKey();
1382
- if (!masterKey) {
1383
- throw new Error(
1384
- "No encryption key found. Run /exe-setup to generate one."
1385
- );
1386
- }
1387
- }
1388
- const hexKey = masterKey.toString("hex");
1389
- await initTurso({
1390
- dbPath,
1391
- encryptionKey: hexKey
1392
- });
1393
- await ensureSchema();
1394
- try {
1395
- const { initShardManager: initShardManager2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
1396
- initShardManager2(hexKey);
1397
- } catch {
1398
- }
1399
- const client = getClient();
1400
- const vResult = await client.execute("SELECT MAX(version) as max_v FROM memories");
1401
- _nextVersion = (Number(vResult.rows[0]?.max_v) || 0) + 1;
1402
- }
1403
- function classifyTier(record) {
1404
- if (record.tool_name === "commit_to_long_term_memory" && (record.importance ?? 0) >= 8) return 1;
1405
- if (["store_memory", "manual"].includes(record.tool_name ?? "") && (record.importance ?? 0) >= 5) return 2;
1406
- return 3;
1407
- }
1408
- async function writeMemory(record) {
1409
- if (record.vector !== null && record.vector.length !== EMBEDDING_DIM) {
1410
- throw new Error(
1411
- `Expected ${EMBEDDING_DIM}-dim vector, got ${record.vector.length}`
1412
- );
1413
- }
1414
- const dbRow = {
1415
- id: record.id,
1416
- agent_id: record.agent_id,
1417
- agent_role: record.agent_role,
1418
- session_id: record.session_id,
1419
- timestamp: record.timestamp,
1420
- tool_name: record.tool_name,
1421
- project_name: record.project_name,
1422
- has_error: record.has_error ? 1 : 0,
1423
- raw_text: record.raw_text,
1424
- vector: record.vector,
1425
- version: _nextVersion++,
1426
- task_id: record.task_id ?? null,
1427
- importance: record.importance ?? 5,
1428
- status: record.status ?? "active",
1429
- confidence: record.confidence ?? 0.7,
1430
- last_accessed: record.last_accessed ?? record.timestamp,
1431
- workspace_id: record.workspace_id ?? null,
1432
- document_id: record.document_id ?? null,
1433
- user_id: record.user_id ?? null,
1434
- char_offset: record.char_offset ?? null,
1435
- page_number: record.page_number ?? null,
1436
- source_path: record.source_path ?? null,
1437
- source_type: record.source_type ?? null,
1438
- tier: record.tier ?? classifyTier(record),
1439
- supersedes_id: record.supersedes_id ?? null
1440
- };
1441
- _pendingRecords.push(dbRow);
1442
- if (_flushTimer === null) {
1443
- _flushTimer = setInterval(() => {
1444
- void flushBatch();
1445
- }, _flushIntervalMs);
1446
- if (_flushTimer && typeof _flushTimer === "object" && "unref" in _flushTimer) {
1447
- _flushTimer.unref();
1448
- }
1449
- }
1450
- if (_pendingRecords.length >= _batchSize) {
1451
- await flushBatch();
1452
- }
1453
- }
1454
- async function flushBatch() {
1455
- if (_flushing || _pendingRecords.length === 0) return 0;
1456
- _flushing = true;
1457
- try {
1458
- const batch = _pendingRecords.slice(0);
1459
- const buildStmt = (row) => {
1460
- const hasVector = row.vector !== null;
1461
- const taskId = row.task_id ?? null;
1462
- const importance = row.importance ?? 5;
1463
- const status = row.status ?? "active";
1464
- const confidence = row.confidence ?? 0.7;
1465
- const lastAccessed = row.last_accessed ?? row.timestamp;
1466
- const workspaceId = row.workspace_id ?? null;
1467
- const documentId = row.document_id ?? null;
1468
- const userId = row.user_id ?? null;
1469
- const charOffset = row.char_offset ?? null;
1470
- const pageNumber = row.page_number ?? null;
1471
- const sourcePath = row.source_path ?? null;
1472
- const sourceType = row.source_type ?? null;
1473
- const tier = row.tier ?? 3;
1474
- const supersedesId = row.supersedes_id ?? null;
1475
- return {
1476
- sql: hasVector ? `INSERT OR IGNORE INTO memories
1477
- (id, agent_id, agent_role, session_id, timestamp,
1478
- tool_name, project_name,
1479
- has_error, raw_text, vector, version, task_id, importance, status,
1480
- confidence, last_accessed,
1481
- workspace_id, document_id, user_id, char_offset, page_number,
1482
- source_path, source_type, tier, supersedes_id)
1483
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, vector32(?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` : `INSERT OR IGNORE INTO memories
1484
- (id, agent_id, agent_role, session_id, timestamp,
1485
- tool_name, project_name,
1486
- has_error, raw_text, vector, version, task_id, importance, status,
1487
- confidence, last_accessed,
1488
- workspace_id, document_id, user_id, char_offset, page_number,
1489
- source_path, source_type, tier, supersedes_id)
1490
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1491
- args: hasVector ? [
1492
- row.id,
1493
- row.agent_id,
1494
- row.agent_role,
1495
- row.session_id,
1496
- row.timestamp,
1497
- row.tool_name,
1498
- row.project_name,
1499
- row.has_error,
1500
- row.raw_text,
1501
- vectorToBlob(row.vector),
1502
- row.version,
1503
- taskId,
1504
- importance,
1505
- status,
1506
- confidence,
1507
- lastAccessed,
1508
- workspaceId,
1509
- documentId,
1510
- userId,
1511
- charOffset,
1512
- pageNumber,
1513
- sourcePath,
1514
- sourceType,
1515
- tier,
1516
- supersedesId
1517
- ] : [
1518
- row.id,
1519
- row.agent_id,
1520
- row.agent_role,
1521
- row.session_id,
1522
- row.timestamp,
1523
- row.tool_name,
1524
- row.project_name,
1525
- row.has_error,
1526
- row.raw_text,
1527
- row.version,
1528
- taskId,
1529
- importance,
1530
- status,
1531
- confidence,
1532
- lastAccessed,
1533
- workspaceId,
1534
- documentId,
1535
- userId,
1536
- charOffset,
1537
- pageNumber,
1538
- sourcePath,
1539
- sourceType,
1540
- tier,
1541
- supersedesId
1542
- ]
1543
- };
1544
- };
1545
- const globalClient = getClient();
1546
- const globalStmts = batch.map(buildStmt);
1547
- await globalClient.batch(globalStmts, "write");
1548
- _pendingRecords.splice(0, batch.length);
1549
- try {
1550
- const { isShardingEnabled: isShardingEnabled2, getReadyShardClient: getReadyShardClient2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
1551
- if (isShardingEnabled2()) {
1552
- const byProject = /* @__PURE__ */ new Map();
1553
- for (const row of batch) {
1554
- const proj = row.project_name || "unknown";
1555
- if (!byProject.has(proj)) byProject.set(proj, []);
1556
- byProject.get(proj).push(row);
1557
- }
1558
- for (const [project, rows] of byProject) {
1559
- try {
1560
- const shardClient = await getReadyShardClient2(project);
1561
- const shardStmts = rows.map(buildStmt);
1562
- await shardClient.batch(shardStmts, "write");
1563
- } catch (err) {
1564
- process.stderr.write(
1565
- `[store] Shard write failed for ${project}: ${err instanceof Error ? err.message : String(err)}
1566
- `
1567
- );
1568
- }
1569
- }
1570
- }
1571
- } catch {
1572
- }
1573
- return batch.length;
1574
- } finally {
1575
- _flushing = false;
1576
- }
1577
- }
1578
- function buildWikiScopeFilter(options, columnPrefix) {
1579
- const args = [];
1580
- let clause = "";
1581
- if (options?.workspaceId !== void 0) {
1582
- clause += ` AND ${columnPrefix}workspace_id = ?`;
1583
- args.push(options.workspaceId);
1584
- }
1585
- if (options?.userId === void 0) {
1586
- clause += ` AND ${columnPrefix}user_id IS NULL`;
1587
- } else if (options.userId === null) {
1588
- clause += ` AND ${columnPrefix}user_id IS NULL`;
1589
- } else {
1590
- clause += ` AND (${columnPrefix}user_id = ? OR ${columnPrefix}user_id IS NULL)`;
1591
- args.push(options.userId);
1592
- }
1593
- return { clause, args };
1594
- }
1595
- async function searchMemories(queryVector, agentId, options) {
1596
- let client;
1597
- try {
1598
- const { isShardingEnabled: isShardingEnabled2, shardExists: shardExists2, getReadyShardClient: getReadyShardClient2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
1599
- if (isShardingEnabled2() && options?.projectName && shardExists2(options.projectName)) {
1600
- client = await getReadyShardClient2(options.projectName);
1601
- } else {
1602
- client = getClient();
1603
- }
1604
- } catch {
1605
- client = getClient();
1606
- }
1607
- const limit = options?.limit ?? 10;
1608
- const statusFilter = options?.includeArchived ? "" : `
1609
- AND COALESCE(status, 'active') = 'active'`;
1610
- let sql = `SELECT id, agent_id, agent_role, session_id, timestamp,
1611
- tool_name, project_name,
1612
- has_error, raw_text, vector, importance, status,
1613
- confidence, last_accessed,
1614
- workspace_id, document_id, user_id,
1615
- char_offset, page_number,
1616
- source_path, source_type
1617
- FROM memories
1618
- WHERE agent_id = ?
1619
- AND vector IS NOT NULL${statusFilter}
1620
- AND COALESCE(confidence, 0.7) >= 0.3`;
1621
- const args = [agentId];
1622
- const scope = buildWikiScopeFilter(options, "");
1623
- sql += scope.clause;
1624
- args.push(...scope.args);
1625
- if (options?.projectName) {
1626
- sql += ` AND project_name = ?`;
1627
- args.push(options.projectName);
1628
- }
1629
- if (options?.toolName) {
1630
- sql += ` AND tool_name = ?`;
1631
- args.push(options.toolName);
1632
- }
1633
- if (options?.hasError !== void 0) {
1634
- sql += ` AND has_error = ?`;
1635
- args.push(options.hasError ? 1 : 0);
1636
- }
1637
- if (options?.since) {
1638
- sql += ` AND timestamp >= ?`;
1639
- args.push(options.since);
1640
- }
1641
- sql += ` ORDER BY vector_distance_cos(vector, vector32(?))`;
1642
- args.push(vectorToBlob(queryVector));
1643
- sql += ` LIMIT ?`;
1644
- args.push(limit);
1645
- const result = await client.execute({ sql, args });
1646
- return result.rows.map((row) => ({
1647
- id: row.id,
1648
- agent_id: row.agent_id,
1649
- agent_role: row.agent_role,
1650
- session_id: row.session_id,
1651
- timestamp: row.timestamp,
1652
- tool_name: row.tool_name,
1653
- project_name: row.project_name,
1654
- has_error: row.has_error === 1,
1655
- raw_text: row.raw_text,
1656
- vector: row.vector == null ? [] : Array.isArray(row.vector) ? row.vector : Array.from(row.vector),
1657
- importance: row.importance ?? 5,
1658
- status: row.status ?? "active",
1659
- confidence: row.confidence ?? 0.7,
1660
- last_accessed: row.last_accessed ?? row.timestamp,
1661
- workspace_id: row.workspace_id ?? null,
1662
- document_id: row.document_id ?? null,
1663
- user_id: row.user_id ?? null,
1664
- char_offset: row.char_offset ?? null,
1665
- page_number: row.page_number ?? null,
1666
- source_path: row.source_path ?? null,
1667
- source_type: row.source_type ?? null
1668
- }));
1669
- }
1670
- async function attachDocumentMetadata(records) {
1671
- const docIds = [
1672
- ...new Set(
1673
- records.map((r) => r.document_id).filter((id) => typeof id === "string" && id.length > 0)
1674
- )
1675
- ];
1676
- if (docIds.length === 0) return records;
1677
- try {
1678
- const client = getClient();
1679
- const placeholders = docIds.map(() => "?").join(",");
1680
- const result = await client.execute({
1681
- sql: `SELECT id, filename, mime, source_type, uploaded_at
1682
- FROM documents
1683
- WHERE id IN (${placeholders})`,
1684
- args: docIds
1685
- });
1686
- const byId = /* @__PURE__ */ new Map();
1687
- for (const row of result.rows) {
1688
- const id = row.id;
1689
- byId.set(id, {
1690
- document_id: id,
1691
- filename: row.filename,
1692
- mime: row.mime ?? null,
1693
- source_type: row.source_type ?? null,
1694
- uploaded_at: row.uploaded_at
1695
- });
1696
- }
1697
- for (const record of records) {
1698
- if (!record.document_id) continue;
1699
- record.document_metadata = byId.get(record.document_id) ?? null;
1700
- }
1701
- } catch {
1702
- }
1703
- return records;
1704
- }
1705
- async function flushTier3(agentId, options) {
1706
- const client = getClient();
1707
- const maxAge = options?.maxAgeHours ?? 72;
1708
- const cutoff = new Date(Date.now() - maxAge * 36e5).toISOString();
1709
- if (options?.dryRun) {
1710
- const result2 = await client.execute({
1711
- sql: `SELECT COUNT(*) as cnt FROM memories
1712
- WHERE agent_id = ? AND tier = 3 AND status = 'active' AND timestamp < ?`,
1713
- args: [agentId, cutoff]
1714
- });
1715
- return { archived: Number(result2.rows[0]?.cnt ?? 0) };
1716
- }
1717
- const result = await client.execute({
1718
- sql: `UPDATE memories SET status = 'archived'
1719
- WHERE agent_id = ? AND tier = 3 AND status = 'active' AND timestamp < ?`,
1720
- args: [agentId, cutoff]
1721
- });
1722
- return { archived: result.rowsAffected };
1723
- }
1724
- async function disposeStore() {
1725
- if (_flushTimer !== null) {
1726
- clearInterval(_flushTimer);
1727
- _flushTimer = null;
1728
- }
1729
- if (_pendingRecords.length > 0) {
1730
- await flushBatch();
1731
- }
1732
- await disposeTurso();
1733
- _pendingRecords = [];
1734
- _nextVersion = 1;
1735
- }
1736
- function vectorToBlob(vector) {
1737
- const f32 = vector instanceof Float32Array ? vector : new Float32Array(vector);
1738
- return JSON.stringify(Array.from(f32));
1739
- }
1740
- async function updateMemoryStatus(id, status) {
1741
- const client = getClient();
1742
- await client.execute({
1743
- sql: `UPDATE memories SET status = ? WHERE id = ?`,
1744
- args: [status, id]
1745
- });
1746
- }
1747
- function reserveVersions(count) {
1748
- const reserved = [];
1749
- for (let i = 0; i < count; i++) {
1750
- reserved.push(_nextVersion++);
1751
- }
1752
- return reserved;
1753
- }
1754
- async function getMemoryCardinality(agentId) {
1755
- try {
1756
- const client = getClient();
1757
- const result = await client.execute({
1758
- sql: `SELECT COUNT(*) as cnt FROM memories WHERE agent_id = ? AND COALESCE(status, 'active') = 'active'`,
1759
- args: [agentId]
1760
- });
1761
- return Number(result.rows[0]?.cnt) || 0;
1762
- } catch {
1763
- return 0;
1764
- }
1765
- }
1766
- var _pendingRecords, _batchSize, _flushIntervalMs, _flushTimer, _flushing, _nextVersion;
1767
- var init_store = __esm({
1768
- "src/lib/store.ts"() {
1769
- "use strict";
1770
- init_memory();
1771
- init_database();
1772
- init_keychain();
1773
- init_config();
1774
- _pendingRecords = [];
1775
- _batchSize = 20;
1776
- _flushIntervalMs = 1e4;
1777
- _flushTimer = null;
1778
- _flushing = false;
1779
- _nextVersion = 1;
1780
- }
1781
- });
1782
-
1783
- // src/lib/notifications.ts
1784
- var notifications_exports = {};
1785
- __export(notifications_exports, {
1786
- cleanupOldNotifications: () => cleanupOldNotifications,
1787
- formatNotifications: () => formatNotifications,
1788
- markAsRead: () => markAsRead,
1789
- markAsReadByTaskFile: () => markAsReadByTaskFile,
1790
- markDoneTaskNotificationsAsRead: () => markDoneTaskNotificationsAsRead,
1791
- migrateJsonNotifications: () => migrateJsonNotifications,
1792
- readUnreadNotifications: () => readUnreadNotifications,
1793
- writeNotification: () => writeNotification
1794
- });
1795
- import crypto2 from "crypto";
1796
- import path5 from "path";
1797
- import os2 from "os";
1798
- import {
1799
- readFileSync as readFileSync3,
1800
- readdirSync as readdirSync2,
1801
- unlinkSync as unlinkSync2,
1802
- existsSync as existsSync4,
1803
- rmdirSync
1804
- } from "fs";
1805
- async function writeNotification(notification) {
1806
- try {
1807
- const client = getClient();
1808
- const id = crypto2.randomUUID();
1809
- const now = (/* @__PURE__ */ new Date()).toISOString();
1810
- await client.execute({
1811
- sql: `INSERT INTO notifications (id, agent_id, agent_role, event, project, summary, task_file, read, created_at)
1812
- VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?)`,
1813
- args: [
1814
- id,
1815
- notification.agentId,
1816
- notification.agentRole,
1817
- notification.event,
1818
- notification.project,
1819
- notification.summary,
1820
- notification.taskFile ?? null,
1821
- now
1822
- ]
1823
- });
1824
- } catch (err) {
1825
- process.stderr.write(`[notifications] WRITE FAILED: ${err instanceof Error ? err.message : String(err)}
1826
- `);
1827
- }
1828
- }
1829
- async function readUnreadNotifications(agentFilter) {
1830
- try {
1831
- const client = getClient();
1832
- const conditions = ["read = 0"];
1833
- const args = [];
1834
- if (agentFilter) {
1835
- conditions.push("agent_id = ?");
1836
- args.push(agentFilter);
1837
- }
1838
- const result = await client.execute({
1839
- sql: `SELECT id, agent_id, agent_role, event, project, summary, task_file, created_at
1840
- FROM notifications
1841
- WHERE ${conditions.join(" AND ")}
1842
- ORDER BY created_at ASC`,
1843
- args
1844
- });
1845
- return result.rows.map((r) => ({
1846
- id: String(r.id),
1847
- agentId: String(r.agent_id),
1848
- agentRole: String(r.agent_role),
1849
- event: String(r.event),
1850
- project: String(r.project),
1851
- summary: String(r.summary),
1852
- taskFile: r.task_file ? String(r.task_file) : void 0,
1853
- timestamp: String(r.created_at),
1854
- read: false
1855
- }));
1856
- } catch {
1857
- return [];
1858
- }
1859
- }
1860
- async function markAsRead(ids) {
1861
- if (ids.length === 0) return;
1862
- try {
1863
- const client = getClient();
1864
- const placeholders = ids.map(() => "?").join(", ");
1865
- await client.execute({
1866
- sql: `UPDATE notifications SET read = 1 WHERE id IN (${placeholders})`,
1867
- args: ids
1868
- });
1869
- } catch {
1870
- }
1871
- }
1872
- async function markAsReadByTaskFile(taskFile) {
1873
- try {
1874
- const client = getClient();
1875
- await client.execute({
1876
- sql: "UPDATE notifications SET read = 1 WHERE task_file = ? AND read = 0",
1877
- args: [taskFile]
1878
- });
1879
- } catch {
1880
- }
1881
- }
1882
- async function cleanupOldNotifications(daysOld = CLEANUP_DAYS) {
1883
- try {
1884
- const client = getClient();
1885
- const cutoff = new Date(
1886
- Date.now() - daysOld * 24 * 60 * 60 * 1e3
1887
- ).toISOString();
1888
- const result = await client.execute({
1889
- sql: "DELETE FROM notifications WHERE created_at < ?",
1890
- args: [cutoff]
1891
- });
1892
- return result.rowsAffected;
1893
- } catch {
1894
- return 0;
1895
- }
1896
- }
1897
- async function markDoneTaskNotificationsAsRead() {
1898
- try {
1899
- const client = getClient();
1900
- const result = await client.execute({
1901
- sql: `UPDATE notifications SET read = 1
1902
- WHERE read = 0
1903
- AND task_file IS NOT NULL
1904
- AND task_file IN (
1905
- SELECT task_file FROM tasks WHERE status = 'done'
1906
- )`,
1907
- args: []
1908
- });
1909
- return result.rowsAffected;
1910
- } catch {
1911
- return 0;
1912
- }
1913
- }
1914
- function formatNotifications(notifications) {
1915
- if (notifications.length === 0) return "";
1916
- const grouped = /* @__PURE__ */ new Map();
1917
- for (const n of notifications) {
1918
- const key = `${n.agentId}|${n.agentRole}`;
1919
- if (!grouped.has(key)) grouped.set(key, []);
1920
- grouped.get(key).push(n);
1921
- }
1922
- const lines = [];
1923
- lines.push(`## Notifications (${notifications.length} unread)
1924
- `);
1925
- for (const [key, items] of grouped) {
1926
- const [agentId, agentRole] = key.split("|");
1927
- lines.push(`**${agentId}** (${agentRole}):`);
1928
- for (const item of items) {
1929
- const ago = formatTimeAgo(item.timestamp);
1930
- const icon = eventIcon(item.event);
1931
- lines.push(`- ${icon} ${item.summary} (${item.project}) \u2014 ${ago}`);
1932
- }
1933
- lines.push("");
1934
- }
1935
- return lines.join("\n");
1936
- }
1937
- async function migrateJsonNotifications() {
1938
- const base = process.env.EXE_OS_DIR || process.env.EXE_MEM_DIR || path5.join(os2.homedir(), ".exe-os");
1939
- const notifDir = path5.join(base, "notifications");
1940
- if (!existsSync4(notifDir)) return 0;
1941
- let migrated = 0;
1942
- try {
1943
- const files = readdirSync2(notifDir).filter((f) => f.endsWith(".json"));
1944
- if (files.length === 0) return 0;
1945
- const client = getClient();
1946
- for (const file of files) {
1947
- try {
1948
- const filePath = path5.join(notifDir, file);
1949
- const data = JSON.parse(readFileSync3(filePath, "utf8"));
1950
- await client.execute({
1951
- sql: `INSERT OR IGNORE INTO notifications (id, agent_id, agent_role, event, project, summary, task_file, read, created_at)
1952
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1953
- args: [
1954
- crypto2.randomUUID(),
1955
- data.agentId ?? "unknown",
1956
- data.agentRole ?? "unknown",
1957
- data.event ?? "session_summary",
1958
- data.project ?? "unknown",
1959
- data.summary ?? "",
1960
- data.taskFile ?? null,
1961
- data.read ? 1 : 0,
1962
- data.timestamp ?? (/* @__PURE__ */ new Date()).toISOString()
1963
- ]
1964
- });
1965
- unlinkSync2(filePath);
1966
- migrated++;
1967
- } catch {
1968
- }
1969
- }
1970
- try {
1971
- const remaining = readdirSync2(notifDir);
1972
- if (remaining.length === 0) {
1973
- rmdirSync(notifDir);
1974
- }
1975
- } catch {
1976
- }
1977
- } catch {
1978
- }
1979
- return migrated;
1980
- }
1981
- function eventIcon(event) {
1982
- switch (event) {
1983
- case "task_complete":
1984
- return "Completed:";
1985
- case "task_needs_fix":
1986
- return "Needs fix:";
1987
- case "session_summary":
1988
- return "Session:";
1989
- case "error_spike":
1990
- return "Errors:";
1991
- case "orphan_task":
1992
- return "Orphan:";
1993
- case "subtasks_complete":
1994
- return "Subtasks done:";
1995
- case "capacity_relaunch":
1996
- return "Relaunched:";
1997
- }
1998
- }
1999
- function formatTimeAgo(timestamp) {
2000
- const diffMs = Date.now() - new Date(timestamp).getTime();
2001
- const mins = Math.floor(diffMs / 6e4);
2002
- if (mins < 1) return "just now";
2003
- if (mins < 60) return `${mins}m ago`;
2004
- const hours = Math.floor(mins / 60);
2005
- if (hours < 24) return `${hours}h ago`;
2006
- const days = Math.floor(hours / 24);
2007
- return `${days}d ago`;
2008
- }
2009
- var CLEANUP_DAYS;
2010
- var init_notifications = __esm({
2011
- "src/lib/notifications.ts"() {
2012
- "use strict";
2013
- init_database();
2014
- CLEANUP_DAYS = 7;
2015
- }
2016
- });
2017
-
2018
- // src/adapters/claude/active-agent.ts
2019
- init_config();
2020
- import { readFileSync as readFileSync2, writeFileSync, mkdirSync, unlinkSync, readdirSync } from "fs";
2021
- import { execSync as execSync2 } from "child_process";
2022
- import path2 from "path";
2023
-
2024
- // src/lib/session-key.ts
2025
- import { execSync } from "child_process";
2026
- var _cached = null;
2027
- function getSessionKey() {
2028
- if (_cached) return _cached;
2029
- let pid = process.ppid;
2030
- for (let i = 0; i < 10; i++) {
2031
- try {
2032
- const info = execSync(`ps -p ${pid} -o ppid=,comm=`, {
2033
- encoding: "utf8",
2034
- timeout: 2e3
2035
- }).trim();
2036
- const match = info.match(/^\s*(\d+)\s+(.+)$/);
2037
- if (!match) break;
2038
- const [, ppid, cmd] = match;
2039
- if (cmd === "claude" || cmd.endsWith("/claude")) {
2040
- _cached = String(pid);
2041
- return _cached;
2042
- }
2043
- pid = parseInt(ppid, 10);
2044
- if (pid <= 1) break;
2045
- } catch {
2046
- break;
2047
- }
2048
- }
2049
- _cached = process.env.CLAUDE_CODE_SSE_PORT ?? String(process.ppid);
2050
- return _cached;
2051
- }
2052
-
2053
- // src/adapters/claude/active-agent.ts
2054
- var CACHE_DIR = path2.join(EXE_AI_DIR, "session-cache");
2055
- var STALE_MS = 24 * 60 * 60 * 1e3;
2056
- function getMarkerPath() {
2057
- return path2.join(CACHE_DIR, `active-agent-${getSessionKey()}.json`);
2058
- }
2059
- function clearActiveAgent() {
2060
- try {
2061
- unlinkSync(getMarkerPath());
2062
- } catch {
2063
- }
2064
- }
2065
- function getActiveAgent() {
2066
- try {
2067
- const markerPath = getMarkerPath();
2068
- const raw = readFileSync2(markerPath, "utf8");
2069
- const data = JSON.parse(raw);
2070
- if (data.agentId) {
2071
- if (data.startedAt) {
2072
- const age = Date.now() - new Date(data.startedAt).getTime();
2073
- if (age > STALE_MS) {
2074
- try {
2075
- unlinkSync(markerPath);
2076
- } catch {
2077
- }
2078
- } else {
2079
- return {
2080
- agentId: data.agentId,
2081
- agentRole: data.agentRole || "employee"
2082
- };
2083
- }
2084
- } else {
2085
- return {
2086
- agentId: data.agentId,
2087
- agentRole: data.agentRole || "employee"
2088
- };
2089
- }
2090
- }
2091
- } catch {
2092
- }
2093
- try {
2094
- const sessionName = execSync2(
2095
- "tmux display-message -p '#{session_name}' 2>/dev/null",
2096
- { encoding: "utf8", timeout: 2e3 }
2097
- ).trim();
2098
- const empMatch = sessionName.match(/^(\w+)-exe\d+$/);
2099
- if (empMatch && empMatch[1] !== "exe") {
2100
- return { agentId: empMatch[1], agentRole: "employee" };
2101
- }
2102
- if (/^exe\d+$/.test(sessionName)) {
2103
- return { agentId: "exe", agentRole: "COO" };
2104
- }
2105
- } catch {
2106
- }
2107
- return {
2108
- agentId: process.env.AGENT_ID || "default",
2109
- agentRole: process.env.AGENT_ROLE || "employee"
2110
- };
2111
- }
2112
-
2113
- // src/adapters/claude/hooks/session-end.ts
2114
- if (!process.env.AGENT_ID) {
2115
- process.env.AGENT_ID = "default";
2116
- process.env.AGENT_ROLE = "employee";
2117
- }
2118
- var timeout = setTimeout(() => {
2119
- process.exit(0);
2120
- }, 5e3);
2121
- timeout.unref();
2122
- var input = "";
2123
- process.stdin.setEncoding("utf8");
2124
- process.stdin.on("data", (chunk) => {
2125
- input += chunk;
2126
- });
2127
- process.stdin.on("end", async () => {
2128
- try {
2129
- const data = JSON.parse(input);
2130
- const agent = getActiveAgent();
2131
- if (agent.agentId !== "default") {
2132
- try {
2133
- const { initStore: initStore2 } = await Promise.resolve().then(() => (init_store(), store_exports));
2134
- await initStore2();
2135
- const { writeMemory: writeMemory2, flushBatch: flushBatch2 } = await Promise.resolve().then(() => (init_store(), store_exports));
2136
- const { getClient: getClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
2137
- const { randomUUID } = await import("crypto");
2138
- const client = getClient2();
2139
- const orphanResult = await client.execute({
2140
- sql: "SELECT title, status FROM tasks WHERE assigned_to = ? AND status IN ('open', 'in_progress')",
2141
- args: [agent.agentId]
2142
- });
2143
- const orphanInfo = orphanResult.rows.length > 0 ? `
2144
- Orphaned tasks at session end: ${orphanResult.rows.map((r) => `"${String(r.title)}" (${String(r.status)})`).join(", ")}` : "";
2145
- await writeMemory2({
2146
- id: randomUUID(),
2147
- agent_id: agent.agentId,
2148
- agent_role: agent.agentRole,
2149
- session_id: data.session_id,
2150
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2151
- tool_name: "SessionEnd",
2152
- project_name: process.env.EXE_PROJECT_NAME ?? process.cwd().split("/").pop() ?? "unknown",
2153
- has_error: false,
2154
- raw_text: `Session ended for ${agent.agentId}.${orphanInfo}`,
2155
- vector: null
2156
- });
2157
- await flushBatch2();
2158
- if (agent.agentId !== "exe") {
2159
- const inProgress = orphanResult.rows.filter((r) => String(r.status) === "in_progress");
2160
- if (inProgress.length > 0) {
2161
- const titles = inProgress.map((r) => `"${String(r.title)}"`).join(", ");
2162
- process.stderr.write(
2163
- `[session-end] WARNING: ${agent.agentId} ended with ${inProgress.length} in_progress task(s): ${titles}
2164
- `
2165
- );
2166
- for (const row of inProgress) {
2167
- try {
2168
- await client.execute({
2169
- sql: "UPDATE tasks SET status = 'blocked', updated_at = ? WHERE title = ? AND assigned_to = ? AND status = 'in_progress'",
2170
- args: [(/* @__PURE__ */ new Date()).toISOString(), String(row.title), agent.agentId]
2171
- });
2172
- } catch {
2173
- }
2174
- }
2175
- try {
2176
- const { writeNotification: writeNotification2 } = await Promise.resolve().then(() => (init_notifications(), notifications_exports));
2177
- await writeNotification2({
2178
- agentId: agent.agentId,
2179
- agentRole: agent.agentRole,
2180
- event: "orphan_task",
2181
- project: process.env.EXE_PROJECT_NAME ?? "unknown",
2182
- summary: `${agent.agentId} session ended with ${inProgress.length} in_progress task(s): ${titles}. Tasks marked blocked.`
2183
- });
2184
- } catch {
2185
- }
2186
- }
2187
- }
2188
- } catch {
2189
- }
2190
- }
2191
- clearActiveAgent();
2192
- } catch {
2193
- }
2194
- clearTimeout(timeout);
2195
- process.exit(0);
2196
- });