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