@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,2931 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropNames = Object.getOwnPropertyNames;
3
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
- }) : x)(function(x) {
6
- if (typeof require !== "undefined") return require.apply(this, arguments);
7
- throw Error('Dynamic require of "' + x + '" is not supported');
8
- });
9
- var __esm = (fn, res) => function __init() {
10
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
- };
12
- var __export = (target, all) => {
13
- for (var name in all)
14
- __defProp(target, name, { get: all[name], enumerable: true });
15
- };
16
-
17
- // src/types/memory.ts
18
- var EMBEDDING_DIM;
19
- var init_memory = __esm({
20
- "src/types/memory.ts"() {
21
- "use strict";
22
- EMBEDDING_DIM = 1024;
23
- }
24
- });
25
-
26
- // src/lib/database.ts
27
- import { createClient } from "@libsql/client";
28
- async function initDatabase(config) {
29
- if (_client) {
30
- _client.close();
31
- _client = null;
32
- }
33
- const opts = {
34
- url: `file:${config.dbPath}`
35
- };
36
- if (config.encryptionKey) {
37
- opts.encryptionKey = config.encryptionKey;
38
- }
39
- _client = createClient(opts);
40
- }
41
- function isInitialized() {
42
- return _client !== null;
43
- }
44
- function getClient() {
45
- if (!_client) {
46
- throw new Error("Database client not initialized. Call initDatabase() first.");
47
- }
48
- return _client;
49
- }
50
- async function ensureSchema() {
51
- const client = getClient();
52
- await client.execute("PRAGMA journal_mode = WAL");
53
- await client.execute("PRAGMA busy_timeout = 5000");
54
- try {
55
- await client.execute("PRAGMA libsql_vector_search_ef = 128");
56
- } catch {
57
- }
58
- await client.executeMultiple(`
59
- CREATE TABLE IF NOT EXISTS memories (
60
- id TEXT PRIMARY KEY,
61
- agent_id TEXT NOT NULL,
62
- agent_role TEXT NOT NULL,
63
- session_id TEXT NOT NULL,
64
- timestamp TEXT NOT NULL,
65
- tool_name TEXT NOT NULL,
66
- project_name TEXT NOT NULL,
67
- has_error INTEGER NOT NULL DEFAULT 0,
68
- raw_text TEXT NOT NULL,
69
- vector F32_BLOB(1024),
70
- version INTEGER NOT NULL DEFAULT 0
71
- );
72
-
73
- CREATE INDEX IF NOT EXISTS idx_memories_agent
74
- ON memories(agent_id);
75
-
76
- CREATE INDEX IF NOT EXISTS idx_memories_timestamp
77
- ON memories(timestamp);
78
-
79
- CREATE INDEX IF NOT EXISTS idx_memories_session
80
- ON memories(session_id);
81
-
82
- CREATE INDEX IF NOT EXISTS idx_memories_project
83
- ON memories(project_name);
84
-
85
- CREATE INDEX IF NOT EXISTS idx_memories_tool
86
- ON memories(tool_name);
87
-
88
- CREATE INDEX IF NOT EXISTS idx_memories_version
89
- ON memories(version);
90
-
91
- CREATE INDEX IF NOT EXISTS idx_memories_agent_project
92
- ON memories(agent_id, project_name);
93
- `);
94
- await client.executeMultiple(`
95
- CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
96
- raw_text,
97
- content='memories',
98
- content_rowid='rowid'
99
- );
100
-
101
- CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
102
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
103
- END;
104
-
105
- CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
106
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
107
- END;
108
-
109
- CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
110
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
111
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
112
- END;
113
- `);
114
- await client.executeMultiple(`
115
- CREATE TABLE IF NOT EXISTS sync_meta (
116
- key TEXT PRIMARY KEY,
117
- value TEXT NOT NULL
118
- );
119
- `);
120
- await client.executeMultiple(`
121
- CREATE TABLE IF NOT EXISTS tasks (
122
- id TEXT PRIMARY KEY,
123
- title TEXT NOT NULL,
124
- assigned_to TEXT NOT NULL,
125
- assigned_by TEXT NOT NULL,
126
- project_name TEXT NOT NULL,
127
- priority TEXT NOT NULL DEFAULT 'p1',
128
- status TEXT NOT NULL DEFAULT 'open',
129
- task_file TEXT,
130
- created_at TEXT NOT NULL,
131
- updated_at TEXT NOT NULL
132
- );
133
-
134
- CREATE INDEX IF NOT EXISTS idx_tasks_assignee_status
135
- ON tasks(assigned_to, status);
136
- `);
137
- await client.executeMultiple(`
138
- CREATE TABLE IF NOT EXISTS behaviors (
139
- id TEXT PRIMARY KEY,
140
- agent_id TEXT NOT NULL,
141
- project_name TEXT,
142
- domain TEXT,
143
- content TEXT NOT NULL,
144
- active INTEGER NOT NULL DEFAULT 1,
145
- created_at TEXT NOT NULL,
146
- updated_at TEXT NOT NULL
147
- );
148
-
149
- CREATE INDEX IF NOT EXISTS idx_behaviors_agent
150
- ON behaviors(agent_id, active);
151
- `);
152
- try {
153
- const existing = await client.execute({
154
- sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = 'exe'",
155
- args: []
156
- });
157
- if (Number(existing.rows[0]?.cnt) === 0) {
158
- await client.executeMultiple(`
159
- INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
160
- VALUES
161
- (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');
162
- INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
163
- VALUES
164
- (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');
165
- INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
166
- VALUES
167
- (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');
168
- `);
169
- }
170
- } catch {
171
- }
172
- try {
173
- await client.execute({
174
- sql: `ALTER TABLE behaviors ADD COLUMN priority TEXT DEFAULT 'p1'`,
175
- args: []
176
- });
177
- } catch {
178
- }
179
- try {
180
- await client.execute({
181
- sql: `ALTER TABLE tasks ADD COLUMN blocked_by TEXT`,
182
- args: []
183
- });
184
- } catch {
185
- }
186
- try {
187
- await client.execute({
188
- sql: `ALTER TABLE tasks ADD COLUMN parent_task_id TEXT`,
189
- args: []
190
- });
191
- } catch {
192
- }
193
- try {
194
- await client.execute({
195
- sql: `CREATE INDEX IF NOT EXISTS idx_tasks_parent_task_id
196
- ON tasks(parent_task_id)
197
- WHERE parent_task_id IS NOT NULL`,
198
- args: []
199
- });
200
- } catch {
201
- }
202
- try {
203
- await client.execute({
204
- sql: `UPDATE tasks SET status = 'done' WHERE status = 'completed'`,
205
- args: []
206
- });
207
- } catch {
208
- }
209
- try {
210
- await client.execute({
211
- sql: `ALTER TABLE tasks ADD COLUMN reviewer TEXT`,
212
- args: []
213
- });
214
- } catch {
215
- }
216
- try {
217
- await client.execute({
218
- sql: `ALTER TABLE tasks ADD COLUMN context TEXT`,
219
- args: []
220
- });
221
- } catch {
222
- }
223
- try {
224
- await client.execute({
225
- sql: `ALTER TABLE tasks ADD COLUMN result TEXT`,
226
- args: []
227
- });
228
- } catch {
229
- }
230
- try {
231
- await client.execute({
232
- sql: `ALTER TABLE tasks ADD COLUMN assigned_tmux TEXT`,
233
- args: []
234
- });
235
- } catch {
236
- }
237
- try {
238
- await client.execute({
239
- sql: `ALTER TABLE tasks ADD COLUMN checkpoint TEXT`,
240
- args: []
241
- });
242
- } catch {
243
- }
244
- try {
245
- await client.execute({
246
- sql: `ALTER TABLE tasks ADD COLUMN checkpoint_count INTEGER NOT NULL DEFAULT 0`,
247
- args: []
248
- });
249
- } catch {
250
- }
251
- try {
252
- await client.execute({
253
- sql: `ALTER TABLE tasks ADD COLUMN complexity TEXT NOT NULL DEFAULT 'standard'`,
254
- args: []
255
- });
256
- } catch {
257
- }
258
- try {
259
- await client.execute({
260
- sql: `ALTER TABLE memories ADD COLUMN task_id TEXT`,
261
- args: []
262
- });
263
- } catch {
264
- }
265
- try {
266
- await client.execute({
267
- sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
268
- args: []
269
- });
270
- } catch {
271
- }
272
- try {
273
- await client.execute({
274
- sql: `ALTER TABLE memories ADD COLUMN author_device_id TEXT`,
275
- args: []
276
- });
277
- } catch {
278
- }
279
- try {
280
- await client.execute({
281
- sql: `ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'`,
282
- args: []
283
- });
284
- } catch {
285
- }
286
- await client.executeMultiple(`
287
- CREATE TABLE IF NOT EXISTS consolidations (
288
- id TEXT PRIMARY KEY,
289
- consolidated_memory_id TEXT NOT NULL,
290
- source_memory_id TEXT NOT NULL,
291
- created_at TEXT NOT NULL
292
- );
293
-
294
- CREATE INDEX IF NOT EXISTS idx_consolidations_source
295
- ON consolidations(source_memory_id);
296
-
297
- CREATE INDEX IF NOT EXISTS idx_consolidations_consolidated
298
- ON consolidations(consolidated_memory_id);
299
- `);
300
- await client.executeMultiple(`
301
- CREATE TABLE IF NOT EXISTS reminders (
302
- id TEXT PRIMARY KEY,
303
- text TEXT NOT NULL,
304
- created_at TEXT NOT NULL,
305
- due_date TEXT,
306
- completed_at TEXT
307
- );
308
- `);
309
- await client.executeMultiple(`
310
- CREATE TABLE IF NOT EXISTS notifications (
311
- id TEXT PRIMARY KEY,
312
- agent_id TEXT NOT NULL,
313
- agent_role TEXT NOT NULL,
314
- event TEXT NOT NULL,
315
- project TEXT NOT NULL,
316
- summary TEXT NOT NULL,
317
- task_file TEXT,
318
- read INTEGER NOT NULL DEFAULT 0,
319
- created_at TEXT NOT NULL
320
- );
321
-
322
- CREATE INDEX IF NOT EXISTS idx_notifications_read
323
- ON notifications(read);
324
-
325
- CREATE INDEX IF NOT EXISTS idx_notifications_agent
326
- ON notifications(agent_id);
327
-
328
- CREATE INDEX IF NOT EXISTS idx_notifications_task_file
329
- ON notifications(task_file);
330
- `);
331
- await client.executeMultiple(`
332
- CREATE TABLE IF NOT EXISTS schedules (
333
- id TEXT PRIMARY KEY,
334
- cron TEXT NOT NULL,
335
- description TEXT NOT NULL,
336
- job_type TEXT NOT NULL DEFAULT 'report',
337
- prompt TEXT,
338
- assigned_to TEXT,
339
- project_name TEXT,
340
- active INTEGER NOT NULL DEFAULT 1,
341
- use_crontab INTEGER NOT NULL DEFAULT 0,
342
- created_at TEXT NOT NULL
343
- );
344
- `);
345
- await client.executeMultiple(`
346
- CREATE TABLE IF NOT EXISTS device_registry (
347
- device_id TEXT PRIMARY KEY,
348
- friendly_name TEXT NOT NULL,
349
- hostname TEXT NOT NULL,
350
- projects TEXT NOT NULL DEFAULT '[]',
351
- agents TEXT NOT NULL DEFAULT '[]',
352
- connected INTEGER DEFAULT 0,
353
- last_seen TEXT NOT NULL
354
- );
355
- `);
356
- await client.executeMultiple(`
357
- CREATE TABLE IF NOT EXISTS messages (
358
- id TEXT PRIMARY KEY,
359
- from_agent TEXT NOT NULL,
360
- from_device TEXT NOT NULL DEFAULT 'local',
361
- target_agent TEXT NOT NULL,
362
- target_project TEXT,
363
- target_device TEXT NOT NULL DEFAULT 'local',
364
- content TEXT NOT NULL,
365
- priority TEXT DEFAULT 'normal',
366
- status TEXT DEFAULT 'pending',
367
- server_seq INTEGER,
368
- retry_count INTEGER DEFAULT 0,
369
- created_at TEXT NOT NULL,
370
- delivered_at TEXT,
371
- processed_at TEXT,
372
- failed_at TEXT,
373
- failure_reason TEXT
374
- );
375
-
376
- CREATE INDEX IF NOT EXISTS idx_messages_target
377
- ON messages(target_agent, status);
378
-
379
- CREATE INDEX IF NOT EXISTS idx_messages_conversation_order
380
- ON messages(target_agent, from_agent, server_seq);
381
- `);
382
- try {
383
- await client.execute({
384
- sql: `UPDATE memories SET project_name = 'exe-create' WHERE project_name = 'web'`,
385
- args: []
386
- });
387
- await client.execute({
388
- sql: `UPDATE memories SET project_name = 'exe-os' WHERE project_name = 'worker'`,
389
- args: []
390
- });
391
- await client.execute({
392
- sql: `UPDATE tasks SET project_name = 'exe-create' WHERE project_name = 'web'`,
393
- args: []
394
- });
395
- await client.execute({
396
- sql: `UPDATE tasks SET project_name = 'exe-os' WHERE project_name = 'worker'`,
397
- args: []
398
- });
399
- } catch {
400
- }
401
- await client.executeMultiple(`
402
- CREATE TABLE IF NOT EXISTS trajectories (
403
- id TEXT PRIMARY KEY,
404
- task_id TEXT NOT NULL,
405
- agent_id TEXT NOT NULL,
406
- project_name TEXT NOT NULL,
407
- task_title TEXT NOT NULL,
408
- signature TEXT NOT NULL,
409
- signature_hash TEXT NOT NULL,
410
- tool_count INTEGER NOT NULL,
411
- skill_id TEXT,
412
- created_at TEXT NOT NULL
413
- );
414
-
415
- CREATE INDEX IF NOT EXISTS idx_trajectories_hash
416
- ON trajectories(signature_hash);
417
-
418
- CREATE INDEX IF NOT EXISTS idx_trajectories_agent
419
- ON trajectories(agent_id);
420
- `);
421
- try {
422
- await client.execute("ALTER TABLE trajectories ADD COLUMN skill_id TEXT");
423
- } catch {
424
- }
425
- await client.executeMultiple(`
426
- CREATE TABLE IF NOT EXISTS consolidations (
427
- id TEXT PRIMARY KEY,
428
- consolidated_memory_id TEXT NOT NULL,
429
- source_memory_id TEXT NOT NULL,
430
- created_at TEXT NOT NULL
431
- );
432
-
433
- CREATE INDEX IF NOT EXISTS idx_consolidations_source
434
- ON consolidations(source_memory_id);
435
- `);
436
- await client.executeMultiple(`
437
- CREATE TABLE IF NOT EXISTS audit_trail (
438
- id INTEGER PRIMARY KEY AUTOINCREMENT,
439
- timestamp TEXT NOT NULL,
440
- session_id TEXT NOT NULL,
441
- agent_id TEXT NOT NULL,
442
- tool TEXT NOT NULL,
443
- input TEXT,
444
- decision TEXT NOT NULL,
445
- reason TEXT,
446
- is_customer_facing INTEGER NOT NULL DEFAULT 0
447
- );
448
-
449
- CREATE INDEX IF NOT EXISTS idx_audit_trail_agent
450
- ON audit_trail(agent_id, timestamp);
451
-
452
- CREATE INDEX IF NOT EXISTS idx_audit_trail_session
453
- ON audit_trail(session_id);
454
- `);
455
- try {
456
- await client.execute({
457
- sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
458
- args: []
459
- });
460
- } catch {
461
- }
462
- try {
463
- await client.execute({
464
- sql: `ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5`,
465
- args: []
466
- });
467
- } catch {
468
- }
469
- try {
470
- await client.execute({
471
- sql: `ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'`,
472
- args: []
473
- });
474
- } catch {
475
- }
476
- try {
477
- await client.execute({
478
- sql: `ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7`,
479
- args: []
480
- });
481
- } catch {
482
- }
483
- try {
484
- await client.execute({
485
- sql: `ALTER TABLE memories ADD COLUMN last_accessed TEXT`,
486
- args: []
487
- });
488
- } catch {
489
- }
490
- try {
491
- await client.execute({
492
- sql: `UPDATE memories SET last_accessed = timestamp WHERE last_accessed IS NULL`,
493
- args: []
494
- });
495
- } catch {
496
- }
497
- try {
498
- await client.execute({
499
- sql: `ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0`,
500
- args: []
501
- });
502
- } catch {
503
- }
504
- try {
505
- await client.execute({
506
- sql: `ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0`,
507
- args: []
508
- });
509
- } catch {
510
- }
511
- for (const col of [
512
- "ALTER TABLE memories ADD COLUMN content_hash TEXT",
513
- "ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT"
514
- ]) {
515
- try {
516
- await client.execute(col);
517
- } catch {
518
- }
519
- }
520
- await client.executeMultiple(`
521
- CREATE TABLE IF NOT EXISTS entities (
522
- id TEXT PRIMARY KEY,
523
- name TEXT NOT NULL,
524
- type TEXT NOT NULL,
525
- first_seen TEXT NOT NULL,
526
- last_seen TEXT NOT NULL,
527
- properties TEXT DEFAULT '{}',
528
- UNIQUE(name, type)
529
- );
530
-
531
- CREATE TABLE IF NOT EXISTS relationships (
532
- id TEXT PRIMARY KEY,
533
- source_entity_id TEXT NOT NULL,
534
- target_entity_id TEXT NOT NULL,
535
- type TEXT NOT NULL,
536
- weight REAL DEFAULT 1.0,
537
- timestamp TEXT NOT NULL,
538
- properties TEXT DEFAULT '{}',
539
- UNIQUE(source_entity_id, target_entity_id, type)
540
- );
541
-
542
- CREATE TABLE IF NOT EXISTS entity_memories (
543
- entity_id TEXT NOT NULL,
544
- memory_id TEXT NOT NULL,
545
- PRIMARY KEY (entity_id, memory_id)
546
- );
547
-
548
- CREATE TABLE IF NOT EXISTS relationship_memories (
549
- relationship_id TEXT NOT NULL,
550
- memory_id TEXT NOT NULL,
551
- PRIMARY KEY (relationship_id, memory_id)
552
- );
553
-
554
- CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
555
- CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type);
556
- CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_entity_id);
557
- CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_entity_id);
558
-
559
- CREATE TABLE IF NOT EXISTS hyperedges (
560
- id TEXT PRIMARY KEY,
561
- label TEXT NOT NULL,
562
- relation TEXT NOT NULL,
563
- confidence REAL DEFAULT 1.0,
564
- timestamp TEXT NOT NULL
565
- );
566
-
567
- CREATE TABLE IF NOT EXISTS hyperedge_nodes (
568
- hyperedge_id TEXT NOT NULL,
569
- entity_id TEXT NOT NULL,
570
- PRIMARY KEY (hyperedge_id, entity_id)
571
- );
572
- `);
573
- await client.executeMultiple(`
574
- CREATE TABLE IF NOT EXISTS entity_aliases (
575
- alias TEXT NOT NULL PRIMARY KEY,
576
- canonical_entity_id TEXT NOT NULL
577
- );
578
- CREATE INDEX IF NOT EXISTS idx_entity_aliases_canonical ON entity_aliases(canonical_entity_id);
579
- `);
580
- for (const col of [
581
- "ALTER TABLE relationships ADD COLUMN confidence REAL DEFAULT 1.0",
582
- "ALTER TABLE relationships ADD COLUMN confidence_label TEXT DEFAULT 'extracted'"
583
- ]) {
584
- try {
585
- await client.execute(col);
586
- } catch {
587
- }
588
- }
589
- try {
590
- await client.execute(
591
- `CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)`
592
- );
593
- } catch {
594
- }
595
- await client.executeMultiple(`
596
- CREATE TABLE IF NOT EXISTS identity (
597
- id INTEGER PRIMARY KEY AUTOINCREMENT,
598
- agent_id TEXT NOT NULL UNIQUE,
599
- content_hash TEXT NOT NULL,
600
- updated_at TEXT NOT NULL,
601
- updated_by TEXT NOT NULL
602
- );
603
-
604
- CREATE INDEX IF NOT EXISTS idx_identity_agent ON identity(agent_id);
605
- `);
606
- await client.executeMultiple(`
607
- CREATE TABLE IF NOT EXISTS chat_history (
608
- id INTEGER PRIMARY KEY AUTOINCREMENT,
609
- session_id TEXT NOT NULL,
610
- role TEXT NOT NULL,
611
- content TEXT NOT NULL,
612
- tool_name TEXT,
613
- tool_id TEXT,
614
- is_error INTEGER NOT NULL DEFAULT 0,
615
- timestamp INTEGER NOT NULL
616
- );
617
-
618
- CREATE INDEX IF NOT EXISTS idx_chat_history_session
619
- ON chat_history(session_id, id);
620
- `);
621
- await client.executeMultiple(`
622
- CREATE TABLE IF NOT EXISTS workspaces (
623
- id TEXT PRIMARY KEY,
624
- slug TEXT NOT NULL UNIQUE,
625
- name TEXT NOT NULL,
626
- owner_agent_id TEXT,
627
- created_at TEXT NOT NULL,
628
- metadata TEXT
629
- );
630
-
631
- CREATE INDEX IF NOT EXISTS idx_workspaces_slug
632
- ON workspaces(slug);
633
- `);
634
- await client.executeMultiple(`
635
- CREATE TABLE IF NOT EXISTS documents (
636
- id TEXT PRIMARY KEY,
637
- workspace_id TEXT NOT NULL,
638
- filename TEXT NOT NULL,
639
- mime TEXT,
640
- source_type TEXT,
641
- user_id TEXT,
642
- uploaded_at TEXT NOT NULL,
643
- metadata TEXT,
644
- FOREIGN KEY (workspace_id) REFERENCES workspaces(id)
645
- );
646
-
647
- CREATE INDEX IF NOT EXISTS idx_documents_workspace
648
- ON documents(workspace_id);
649
-
650
- CREATE INDEX IF NOT EXISTS idx_documents_user
651
- ON documents(user_id);
652
- `);
653
- for (const column of [
654
- "workspace_id TEXT",
655
- "document_id TEXT",
656
- "user_id TEXT",
657
- "char_offset INTEGER",
658
- "page_number INTEGER"
659
- ]) {
660
- try {
661
- await client.execute({
662
- sql: `ALTER TABLE memories ADD COLUMN ${column}`,
663
- args: []
664
- });
665
- } catch {
666
- }
667
- }
668
- for (const col of [
669
- "ALTER TABLE memories ADD COLUMN source_path TEXT",
670
- "ALTER TABLE memories ADD COLUMN source_type TEXT DEFAULT 'text'"
671
- ]) {
672
- try {
673
- await client.execute(col);
674
- } catch {
675
- }
676
- }
677
- await client.executeMultiple(`
678
- CREATE INDEX IF NOT EXISTS idx_memories_workspace
679
- ON memories(workspace_id);
680
-
681
- CREATE INDEX IF NOT EXISTS idx_memories_document
682
- ON memories(document_id);
683
-
684
- CREATE INDEX IF NOT EXISTS idx_memories_user
685
- ON memories(user_id);
686
- `);
687
- await client.executeMultiple(`
688
- CREATE TABLE IF NOT EXISTS session_kills (
689
- id TEXT PRIMARY KEY,
690
- session_name TEXT NOT NULL,
691
- agent_id TEXT NOT NULL,
692
- killed_at TIMESTAMP NOT NULL,
693
- reason TEXT NOT NULL,
694
- ticks_idle INTEGER,
695
- estimated_tokens_saved INTEGER
696
- );
697
-
698
- CREATE INDEX IF NOT EXISTS idx_session_kills_killed_at
699
- ON session_kills(killed_at);
700
-
701
- CREATE INDEX IF NOT EXISTS idx_session_kills_agent
702
- ON session_kills(agent_id);
703
- `);
704
- await client.executeMultiple(`
705
- CREATE TABLE IF NOT EXISTS conversations (
706
- id TEXT PRIMARY KEY,
707
- platform TEXT NOT NULL,
708
- external_id TEXT,
709
- sender_id TEXT NOT NULL,
710
- sender_name TEXT,
711
- sender_phone TEXT,
712
- sender_email TEXT,
713
- recipient_id TEXT,
714
- channel_id TEXT NOT NULL,
715
- thread_id TEXT,
716
- reply_to_id TEXT,
717
- content_text TEXT,
718
- content_media TEXT,
719
- content_metadata TEXT,
720
- agent_response TEXT,
721
- agent_name TEXT,
722
- timestamp TEXT NOT NULL,
723
- ingested_at TEXT NOT NULL
724
- );
725
-
726
- CREATE INDEX IF NOT EXISTS idx_conversations_platform
727
- ON conversations(platform);
728
-
729
- CREATE INDEX IF NOT EXISTS idx_conversations_sender
730
- ON conversations(sender_id);
731
-
732
- CREATE INDEX IF NOT EXISTS idx_conversations_timestamp
733
- ON conversations(timestamp);
734
-
735
- CREATE INDEX IF NOT EXISTS idx_conversations_thread
736
- ON conversations(thread_id);
737
-
738
- CREATE INDEX IF NOT EXISTS idx_conversations_channel
739
- ON conversations(channel_id);
740
- `);
741
- try {
742
- await client.execute({
743
- sql: `ALTER TABLE tasks ADD COLUMN budget_tokens INTEGER`,
744
- args: []
745
- });
746
- } catch {
747
- }
748
- try {
749
- await client.execute({
750
- sql: `ALTER TABLE tasks ADD COLUMN budget_fallback_model TEXT`,
751
- args: []
752
- });
753
- } catch {
754
- }
755
- try {
756
- await client.execute({
757
- sql: `ALTER TABLE tasks ADD COLUMN tokens_used INTEGER DEFAULT 0`,
758
- args: []
759
- });
760
- } catch {
761
- }
762
- try {
763
- await client.execute({
764
- sql: `ALTER TABLE tasks ADD COLUMN tokens_warned_at INTEGER`,
765
- args: []
766
- });
767
- } catch {
768
- }
769
- await client.executeMultiple(`
770
- CREATE VIRTUAL TABLE IF NOT EXISTS conversations_fts USING fts5(
771
- content_text,
772
- sender_name,
773
- agent_response,
774
- content='conversations',
775
- content_rowid='rowid'
776
- );
777
-
778
- CREATE TRIGGER IF NOT EXISTS conversations_fts_ai AFTER INSERT ON conversations BEGIN
779
- INSERT INTO conversations_fts(rowid, content_text, sender_name, agent_response)
780
- VALUES (new.rowid, new.content_text, new.sender_name, new.agent_response);
781
- END;
782
-
783
- CREATE TRIGGER IF NOT EXISTS conversations_fts_ad AFTER DELETE ON conversations BEGIN
784
- INSERT INTO conversations_fts(conversations_fts, rowid, content_text, sender_name, agent_response)
785
- VALUES('delete', old.rowid, old.content_text, old.sender_name, old.agent_response);
786
- END;
787
-
788
- CREATE TRIGGER IF NOT EXISTS conversations_fts_au AFTER UPDATE ON conversations BEGIN
789
- INSERT INTO conversations_fts(conversations_fts, rowid, content_text, sender_name, agent_response)
790
- VALUES('delete', old.rowid, old.content_text, old.sender_name, old.agent_response);
791
- INSERT INTO conversations_fts(rowid, content_text, sender_name, agent_response)
792
- VALUES (new.rowid, new.content_text, new.sender_name, new.agent_response);
793
- END;
794
- `);
795
- try {
796
- await client.execute({
797
- sql: `ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3`,
798
- args: []
799
- });
800
- } catch {
801
- }
802
- try {
803
- await client.execute(
804
- `CREATE INDEX IF NOT EXISTS idx_memories_tier ON memories(tier)`
805
- );
806
- } catch {
807
- }
808
- try {
809
- await client.execute({
810
- sql: `UPDATE memories SET tier = 1 WHERE tool_name = 'commit_to_long_term_memory' AND importance >= 8 AND tier = 3`,
811
- args: []
812
- });
813
- await client.execute({
814
- sql: `UPDATE memories SET tier = 2 WHERE tool_name IN ('store_memory', 'manual') AND importance >= 5 AND tier = 3`,
815
- args: []
816
- });
817
- } catch {
818
- }
819
- try {
820
- await client.execute({
821
- sql: `ALTER TABLE memories ADD COLUMN supersedes_id TEXT`,
822
- args: []
823
- });
824
- } catch {
825
- }
826
- try {
827
- await client.execute(
828
- `CREATE INDEX IF NOT EXISTS idx_memories_supersedes ON memories(supersedes_id) WHERE supersedes_id IS NOT NULL`
829
- );
830
- } catch {
831
- }
832
- for (const col of [
833
- "ALTER TABLE tasks ADD COLUMN checkpoint TEXT",
834
- "ALTER TABLE tasks ADD COLUMN checkpoint_count INTEGER DEFAULT 0"
835
- ]) {
836
- try {
837
- await client.execute(col);
838
- } catch {
839
- }
840
- }
841
- }
842
- var _client, initTurso;
843
- var init_database = __esm({
844
- "src/lib/database.ts"() {
845
- "use strict";
846
- _client = null;
847
- initTurso = initDatabase;
848
- }
849
- });
850
-
851
- // src/lib/keychain.ts
852
- var keychain_exports = {};
853
- __export(keychain_exports, {
854
- deleteMasterKey: () => deleteMasterKey,
855
- exportMnemonic: () => exportMnemonic,
856
- getMasterKey: () => getMasterKey,
857
- importMnemonic: () => importMnemonic,
858
- setMasterKey: () => setMasterKey
859
- });
860
- import { readFile, writeFile, unlink, mkdir, chmod } from "fs/promises";
861
- import { existsSync } from "fs";
862
- import path from "path";
863
- import crypto from "crypto";
864
- function getKeyDir() {
865
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path.join(process.env.HOME ?? "/tmp", ".exe-os");
866
- }
867
- function getKeyPath() {
868
- return path.join(getKeyDir(), "master.key");
869
- }
870
- async function tryKeytar() {
871
- try {
872
- return await import("keytar");
873
- } catch {
874
- return null;
875
- }
876
- }
877
- async function getMasterKey() {
878
- const keytar = await tryKeytar();
879
- if (keytar) {
880
- try {
881
- const stored = await keytar.getPassword(SERVICE, ACCOUNT);
882
- if (stored) {
883
- return Buffer.from(stored, "base64");
884
- }
885
- } catch {
886
- }
887
- }
888
- const keyPath = getKeyPath();
889
- if (!existsSync(keyPath)) {
890
- return null;
891
- }
892
- try {
893
- const content = await readFile(keyPath, "utf-8");
894
- return Buffer.from(content.trim(), "base64");
895
- } catch {
896
- return null;
897
- }
898
- }
899
- async function setMasterKey(key) {
900
- const b64 = key.toString("base64");
901
- const keytar = await tryKeytar();
902
- if (keytar) {
903
- try {
904
- await keytar.setPassword(SERVICE, ACCOUNT, b64);
905
- return;
906
- } catch {
907
- }
908
- }
909
- const dir = getKeyDir();
910
- await mkdir(dir, { recursive: true });
911
- const keyPath = getKeyPath();
912
- await writeFile(keyPath, b64 + "\n", "utf-8");
913
- await chmod(keyPath, 384);
914
- }
915
- async function deleteMasterKey() {
916
- const keytar = await tryKeytar();
917
- if (keytar) {
918
- try {
919
- await keytar.deletePassword(SERVICE, ACCOUNT);
920
- } catch {
921
- }
922
- }
923
- const keyPath = getKeyPath();
924
- if (existsSync(keyPath)) {
925
- await unlink(keyPath);
926
- }
927
- }
928
- function exportMnemonic(key) {
929
- if (key.length !== 32) {
930
- throw new Error(`Key must be 32 bytes, got ${key.length}`);
931
- }
932
- const hash = crypto.createHash("sha256").update(key).digest();
933
- const checksumByte = hash[0];
934
- let bits = "";
935
- for (const byte of key) {
936
- bits += byte.toString(2).padStart(8, "0");
937
- }
938
- bits += checksumByte.toString(2).padStart(8, "0");
939
- const words = [];
940
- let wordlist;
941
- try {
942
- const bip39 = __require("bip39");
943
- wordlist = bip39.wordlists?.english ?? bip39.default?.wordlists?.english;
944
- if (!wordlist) throw new Error("no wordlist");
945
- } catch {
946
- throw new Error("bip39 package required. Install with: npm install bip39");
947
- }
948
- for (let i = 0; i < 264; i += 11) {
949
- const index = parseInt(bits.slice(i, i + 11), 2);
950
- words.push(wordlist[index]);
951
- }
952
- return words.join(" ");
953
- }
954
- function importMnemonic(mnemonic) {
955
- const words = mnemonic.trim().split(/\s+/);
956
- if (words.length !== 24) {
957
- throw new Error(`Expected 24 words, got ${words.length}`);
958
- }
959
- let wordlist;
960
- try {
961
- const bip39 = __require("bip39");
962
- wordlist = bip39.wordlists?.english ?? bip39.default?.wordlists?.english;
963
- if (!wordlist) throw new Error("no wordlist");
964
- } catch {
965
- throw new Error("bip39 package required. Install with: npm install bip39");
966
- }
967
- let bits = "";
968
- for (const word of words) {
969
- const index = wordlist.indexOf(word.toLowerCase());
970
- if (index === -1) {
971
- throw new Error(`Invalid BIP39 word: "${word}"`);
972
- }
973
- bits += index.toString(2).padStart(11, "0");
974
- }
975
- const entropyBits = bits.slice(0, 256);
976
- const checksumBits = bits.slice(256, 264);
977
- const key = Buffer.alloc(32);
978
- for (let i = 0; i < 32; i++) {
979
- key[i] = parseInt(entropyBits.slice(i * 8, (i + 1) * 8), 2);
980
- }
981
- const hash = crypto.createHash("sha256").update(key).digest();
982
- const expectedChecksum = hash[0].toString(2).padStart(8, "0");
983
- if (checksumBits !== expectedChecksum) {
984
- throw new Error("Invalid mnemonic checksum");
985
- }
986
- return key;
987
- }
988
- var SERVICE, ACCOUNT;
989
- var init_keychain = __esm({
990
- "src/lib/keychain.ts"() {
991
- "use strict";
992
- SERVICE = "exe-mem";
993
- ACCOUNT = "master-key";
994
- }
995
- });
996
-
997
- // src/lib/config.ts
998
- var config_exports = {};
999
- __export(config_exports, {
1000
- CONFIG_MIGRATIONS: () => CONFIG_MIGRATIONS,
1001
- CONFIG_PATH: () => CONFIG_PATH,
1002
- CURRENT_CONFIG_VERSION: () => CURRENT_CONFIG_VERSION,
1003
- DB_PATH: () => DB_PATH,
1004
- EXE_AI_DIR: () => EXE_AI_DIR,
1005
- LEGACY_LANCE_PATH: () => LEGACY_LANCE_PATH,
1006
- MODELS_DIR: () => MODELS_DIR,
1007
- loadConfig: () => loadConfig,
1008
- loadConfigFrom: () => loadConfigFrom,
1009
- loadConfigSync: () => loadConfigSync,
1010
- migrateConfig: () => migrateConfig,
1011
- saveConfig: () => saveConfig
1012
- });
1013
- import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
1014
- import { readFileSync, existsSync as existsSync2, renameSync } from "fs";
1015
- import path2 from "path";
1016
- import os from "os";
1017
- function resolveDataDir() {
1018
- if (process.env.EXE_OS_DIR) return process.env.EXE_OS_DIR;
1019
- if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
1020
- const newDir = path2.join(os.homedir(), ".exe-os");
1021
- const legacyDir = path2.join(os.homedir(), ".exe-mem");
1022
- if (!existsSync2(newDir) && existsSync2(legacyDir)) {
1023
- try {
1024
- renameSync(legacyDir, newDir);
1025
- process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
1026
- `);
1027
- } catch {
1028
- return legacyDir;
1029
- }
1030
- }
1031
- return newDir;
1032
- }
1033
- function migrateLegacyConfig(raw) {
1034
- if ("r2" in raw) {
1035
- process.stderr.write(
1036
- "[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"
1037
- );
1038
- delete raw.r2;
1039
- }
1040
- if ("syncIntervalMs" in raw) {
1041
- delete raw.syncIntervalMs;
1042
- }
1043
- return raw;
1044
- }
1045
- function migrateConfig(raw) {
1046
- const fromVersion = typeof raw.config_version === "number" ? raw.config_version : 0;
1047
- let currentVersion = fromVersion;
1048
- let migrated = false;
1049
- if (currentVersion > CURRENT_CONFIG_VERSION) {
1050
- return { config: raw, migrated: false, fromVersion };
1051
- }
1052
- for (const migration of CONFIG_MIGRATIONS) {
1053
- if (currentVersion === migration.from && migration.to <= CURRENT_CONFIG_VERSION) {
1054
- raw = migration.migrate(raw);
1055
- currentVersion = migration.to;
1056
- migrated = true;
1057
- }
1058
- }
1059
- return { config: raw, migrated, fromVersion };
1060
- }
1061
- function normalizeScalingRoadmap(raw) {
1062
- const defaultAuto = DEFAULT_CONFIG.scalingRoadmap.rerankerAutoTrigger;
1063
- const userRoadmap = raw.scalingRoadmap ?? {};
1064
- const userAuto = userRoadmap.rerankerAutoTrigger ?? {};
1065
- if (userAuto.enabled === void 0 && raw.rerankerEnabled !== void 0) {
1066
- userAuto.enabled = raw.rerankerEnabled;
1067
- }
1068
- raw.scalingRoadmap = {
1069
- ...userRoadmap,
1070
- rerankerAutoTrigger: { ...defaultAuto, ...userAuto }
1071
- };
1072
- }
1073
- function normalizeSessionLifecycle(raw) {
1074
- const defaultSL = DEFAULT_CONFIG.sessionLifecycle;
1075
- const userSL = raw.sessionLifecycle ?? {};
1076
- raw.sessionLifecycle = { ...defaultSL, ...userSL };
1077
- }
1078
- function normalizeAutoUpdate(raw) {
1079
- const defaultAU = DEFAULT_CONFIG.autoUpdate;
1080
- const userAU = raw.autoUpdate ?? {};
1081
- raw.autoUpdate = { ...defaultAU, ...userAU };
1082
- }
1083
- async function loadConfig() {
1084
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
1085
- await mkdir2(dir, { recursive: true });
1086
- const configPath = path2.join(dir, "config.json");
1087
- if (!existsSync2(configPath)) {
1088
- return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
1089
- }
1090
- const raw = await readFile2(configPath, "utf-8");
1091
- try {
1092
- let parsed = JSON.parse(raw);
1093
- parsed = migrateLegacyConfig(parsed);
1094
- const { config: migratedCfg, migrated, fromVersion } = migrateConfig(parsed);
1095
- if (migrated) {
1096
- process.stderr.write(`[exe-os] Config migrated from v${fromVersion} to v${migratedCfg.config_version}
1097
- `);
1098
- try {
1099
- await writeFile2(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
1100
- } catch {
1101
- }
1102
- }
1103
- normalizeScalingRoadmap(migratedCfg);
1104
- normalizeSessionLifecycle(migratedCfg);
1105
- normalizeAutoUpdate(migratedCfg);
1106
- const config = { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db"), ...migratedCfg };
1107
- if (config.dbPath.startsWith("~")) {
1108
- config.dbPath = config.dbPath.replace(/^~/, os.homedir());
1109
- }
1110
- return config;
1111
- } catch {
1112
- return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
1113
- }
1114
- }
1115
- function loadConfigSync() {
1116
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
1117
- const configPath = path2.join(dir, "config.json");
1118
- if (!existsSync2(configPath)) {
1119
- return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
1120
- }
1121
- try {
1122
- const raw = readFileSync(configPath, "utf-8");
1123
- let parsed = JSON.parse(raw);
1124
- parsed = migrateLegacyConfig(parsed);
1125
- const { config: migratedCfg } = migrateConfig(parsed);
1126
- normalizeScalingRoadmap(migratedCfg);
1127
- normalizeSessionLifecycle(migratedCfg);
1128
- normalizeAutoUpdate(migratedCfg);
1129
- return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db"), ...migratedCfg };
1130
- } catch {
1131
- return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
1132
- }
1133
- }
1134
- async function saveConfig(config) {
1135
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
1136
- await mkdir2(dir, { recursive: true });
1137
- const configPath = path2.join(dir, "config.json");
1138
- await writeFile2(configPath, JSON.stringify(config, null, 2) + "\n");
1139
- }
1140
- async function loadConfigFrom(configPath) {
1141
- const raw = await readFile2(configPath, "utf-8");
1142
- try {
1143
- let parsed = JSON.parse(raw);
1144
- parsed = migrateLegacyConfig(parsed);
1145
- const { config: migratedCfg } = migrateConfig(parsed);
1146
- normalizeScalingRoadmap(migratedCfg);
1147
- normalizeSessionLifecycle(migratedCfg);
1148
- normalizeAutoUpdate(migratedCfg);
1149
- return { ...DEFAULT_CONFIG, ...migratedCfg };
1150
- } catch {
1151
- return { ...DEFAULT_CONFIG };
1152
- }
1153
- }
1154
- var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
1155
- var init_config = __esm({
1156
- "src/lib/config.ts"() {
1157
- "use strict";
1158
- EXE_AI_DIR = resolveDataDir();
1159
- DB_PATH = path2.join(EXE_AI_DIR, "memories.db");
1160
- MODELS_DIR = path2.join(EXE_AI_DIR, "models");
1161
- CONFIG_PATH = path2.join(EXE_AI_DIR, "config.json");
1162
- LEGACY_LANCE_PATH = path2.join(EXE_AI_DIR, "local.lance");
1163
- CURRENT_CONFIG_VERSION = 1;
1164
- DEFAULT_CONFIG = {
1165
- config_version: CURRENT_CONFIG_VERSION,
1166
- dbPath: DB_PATH,
1167
- modelFile: "jina-embeddings-v5-small-q4_k_m.gguf",
1168
- embeddingDim: 1024,
1169
- batchSize: 20,
1170
- flushIntervalMs: 1e4,
1171
- autoIngestion: true,
1172
- autoRetrieval: true,
1173
- searchMode: "hybrid",
1174
- hookSearchMode: "hybrid",
1175
- fileGrepEnabled: true,
1176
- splashEffect: true,
1177
- consolidationEnabled: true,
1178
- consolidationIntervalMs: 6 * 60 * 60 * 1e3,
1179
- consolidationModel: "claude-haiku-4-5-20251001",
1180
- consolidationMaxCallsPerRun: 20,
1181
- selfQueryRouter: true,
1182
- selfQueryModel: "claude-haiku-4-5-20251001",
1183
- rerankerEnabled: true,
1184
- scalingRoadmap: {
1185
- rerankerAutoTrigger: {
1186
- enabled: true,
1187
- broadQueryMinCardinality: 5e4,
1188
- fetchTopK: 150,
1189
- returnTopK: 5
1190
- }
1191
- },
1192
- graphRagEnabled: true,
1193
- wikiEnabled: false,
1194
- wikiUrl: "",
1195
- wikiApiKey: "",
1196
- wikiSyncIntervalMs: 30 * 60 * 1e3,
1197
- wikiWorkspaceMapping: {
1198
- exe: "Executive",
1199
- yoshi: "Engineering",
1200
- mari: "Marketing",
1201
- tom: "Engineering",
1202
- sasha: "Production"
1203
- },
1204
- wikiAutoUpdate: true,
1205
- wikiAutoUpdateThreshold: 0.5,
1206
- wikiAutoUpdateCreateNew: true,
1207
- skillLearning: true,
1208
- skillThreshold: 3,
1209
- skillModel: "claude-haiku-4-5-20251001",
1210
- exeHeartbeat: {
1211
- enabled: true,
1212
- intervalSeconds: 60,
1213
- staleInProgressThresholdHours: 2
1214
- },
1215
- sessionLifecycle: {
1216
- idleKillEnabled: true,
1217
- idleKillTicksRequired: 3,
1218
- idleKillIntercomAckWindowMs: 1e4,
1219
- maxAutoInstances: 10
1220
- },
1221
- autoUpdate: {
1222
- checkOnBoot: true,
1223
- autoInstall: false,
1224
- checkIntervalMs: 24 * 60 * 60 * 1e3
1225
- }
1226
- };
1227
- CONFIG_MIGRATIONS = [
1228
- {
1229
- from: 0,
1230
- to: 1,
1231
- migrate: (cfg) => {
1232
- cfg.config_version = 1;
1233
- return cfg;
1234
- }
1235
- }
1236
- ];
1237
- }
1238
- });
1239
-
1240
- // src/lib/shard-manager.ts
1241
- var shard_manager_exports = {};
1242
- __export(shard_manager_exports, {
1243
- disposeShards: () => disposeShards,
1244
- ensureShardSchema: () => ensureShardSchema,
1245
- getReadyShardClient: () => getReadyShardClient,
1246
- getShardClient: () => getShardClient,
1247
- getShardsDir: () => getShardsDir,
1248
- initShardManager: () => initShardManager,
1249
- isShardingEnabled: () => isShardingEnabled,
1250
- listShards: () => listShards,
1251
- shardExists: () => shardExists
1252
- });
1253
- import path3 from "path";
1254
- import { existsSync as existsSync3, mkdirSync } from "fs";
1255
- import { createClient as createClient2 } from "@libsql/client";
1256
- function initShardManager(encryptionKey) {
1257
- _encryptionKey = encryptionKey;
1258
- if (!existsSync3(SHARDS_DIR)) {
1259
- mkdirSync(SHARDS_DIR, { recursive: true });
1260
- }
1261
- _shardingEnabled = true;
1262
- }
1263
- function isShardingEnabled() {
1264
- return _shardingEnabled;
1265
- }
1266
- function getShardsDir() {
1267
- return SHARDS_DIR;
1268
- }
1269
- function getShardClient(projectName) {
1270
- if (!_encryptionKey) {
1271
- throw new Error("Shard manager not initialized. Call initShardManager() first.");
1272
- }
1273
- const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1274
- if (!safeName) {
1275
- throw new Error(`Invalid project name for shard: "${projectName}"`);
1276
- }
1277
- const cached = _shards.get(safeName);
1278
- if (cached) return cached;
1279
- const dbPath = path3.join(SHARDS_DIR, `${safeName}.db`);
1280
- const client = createClient2({
1281
- url: `file:${dbPath}`,
1282
- encryptionKey: _encryptionKey
1283
- });
1284
- _shards.set(safeName, client);
1285
- return client;
1286
- }
1287
- function shardExists(projectName) {
1288
- const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1289
- return existsSync3(path3.join(SHARDS_DIR, `${safeName}.db`));
1290
- }
1291
- function listShards() {
1292
- if (!existsSync3(SHARDS_DIR)) return [];
1293
- const { readdirSync: readdirSync2 } = __require("fs");
1294
- return readdirSync2(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
1295
- }
1296
- async function ensureShardSchema(client) {
1297
- await client.execute("PRAGMA journal_mode = WAL");
1298
- await client.execute("PRAGMA busy_timeout = 5000");
1299
- try {
1300
- await client.execute("PRAGMA libsql_vector_search_ef = 128");
1301
- } catch {
1302
- }
1303
- await client.executeMultiple(`
1304
- CREATE TABLE IF NOT EXISTS memories (
1305
- id TEXT PRIMARY KEY,
1306
- agent_id TEXT NOT NULL,
1307
- agent_role TEXT NOT NULL,
1308
- session_id TEXT NOT NULL,
1309
- timestamp TEXT NOT NULL,
1310
- tool_name TEXT NOT NULL,
1311
- project_name TEXT NOT NULL,
1312
- has_error INTEGER NOT NULL DEFAULT 0,
1313
- raw_text TEXT NOT NULL,
1314
- vector F32_BLOB(1024),
1315
- version INTEGER NOT NULL DEFAULT 0
1316
- );
1317
-
1318
- CREATE INDEX IF NOT EXISTS idx_memories_agent ON memories(agent_id);
1319
- CREATE INDEX IF NOT EXISTS idx_memories_timestamp ON memories(timestamp);
1320
- CREATE INDEX IF NOT EXISTS idx_memories_agent_project ON memories(agent_id, project_name);
1321
- `);
1322
- await client.executeMultiple(`
1323
- CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
1324
- raw_text,
1325
- content='memories',
1326
- content_rowid='rowid'
1327
- );
1328
-
1329
- CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
1330
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1331
- END;
1332
-
1333
- CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
1334
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1335
- END;
1336
-
1337
- CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
1338
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1339
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1340
- END;
1341
- `);
1342
- for (const col of [
1343
- "ALTER TABLE memories ADD COLUMN task_id TEXT",
1344
- "ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0",
1345
- "ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5",
1346
- "ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'",
1347
- "ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0",
1348
- "ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0",
1349
- "ALTER TABLE memories ADD COLUMN content_hash TEXT",
1350
- "ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT",
1351
- "ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7",
1352
- "ALTER TABLE memories ADD COLUMN last_accessed TEXT",
1353
- // Wiki linkage columns (must match database.ts)
1354
- "ALTER TABLE memories ADD COLUMN workspace_id TEXT",
1355
- "ALTER TABLE memories ADD COLUMN document_id TEXT",
1356
- "ALTER TABLE memories ADD COLUMN user_id TEXT",
1357
- "ALTER TABLE memories ADD COLUMN char_offset INTEGER",
1358
- "ALTER TABLE memories ADD COLUMN page_number INTEGER",
1359
- // Source provenance columns (must match database.ts)
1360
- "ALTER TABLE memories ADD COLUMN source_path TEXT",
1361
- "ALTER TABLE memories ADD COLUMN source_type TEXT DEFAULT 'text'",
1362
- "ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3",
1363
- "ALTER TABLE memories ADD COLUMN supersedes_id TEXT"
1364
- ]) {
1365
- try {
1366
- await client.execute(col);
1367
- } catch {
1368
- }
1369
- }
1370
- for (const idx of [
1371
- "CREATE INDEX IF NOT EXISTS idx_memories_tier ON memories(tier)",
1372
- "CREATE INDEX IF NOT EXISTS idx_memories_supersedes ON memories(supersedes_id) WHERE supersedes_id IS NOT NULL"
1373
- ]) {
1374
- try {
1375
- await client.execute(idx);
1376
- } catch {
1377
- }
1378
- }
1379
- try {
1380
- await client.execute("CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)");
1381
- } catch {
1382
- }
1383
- for (const idx of [
1384
- "CREATE INDEX IF NOT EXISTS idx_memories_workspace ON memories(workspace_id)",
1385
- "CREATE INDEX IF NOT EXISTS idx_memories_document ON memories(document_id)",
1386
- "CREATE INDEX IF NOT EXISTS idx_memories_user ON memories(user_id)"
1387
- ]) {
1388
- try {
1389
- await client.execute(idx);
1390
- } catch {
1391
- }
1392
- }
1393
- await client.executeMultiple(`
1394
- CREATE TABLE IF NOT EXISTS entities (
1395
- id TEXT PRIMARY KEY,
1396
- name TEXT NOT NULL,
1397
- type TEXT NOT NULL,
1398
- first_seen TEXT NOT NULL,
1399
- last_seen TEXT NOT NULL,
1400
- properties TEXT DEFAULT '{}',
1401
- UNIQUE(name, type)
1402
- );
1403
-
1404
- CREATE TABLE IF NOT EXISTS relationships (
1405
- id TEXT PRIMARY KEY,
1406
- source_entity_id TEXT NOT NULL,
1407
- target_entity_id TEXT NOT NULL,
1408
- type TEXT NOT NULL,
1409
- weight REAL DEFAULT 1.0,
1410
- timestamp TEXT NOT NULL,
1411
- properties TEXT DEFAULT '{}',
1412
- UNIQUE(source_entity_id, target_entity_id, type)
1413
- );
1414
-
1415
- CREATE TABLE IF NOT EXISTS entity_memories (
1416
- entity_id TEXT NOT NULL,
1417
- memory_id TEXT NOT NULL,
1418
- PRIMARY KEY (entity_id, memory_id)
1419
- );
1420
-
1421
- CREATE TABLE IF NOT EXISTS relationship_memories (
1422
- relationship_id TEXT NOT NULL,
1423
- memory_id TEXT NOT NULL,
1424
- PRIMARY KEY (relationship_id, memory_id)
1425
- );
1426
-
1427
- CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
1428
- CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type);
1429
- CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_entity_id);
1430
- CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_entity_id);
1431
- CREATE INDEX IF NOT EXISTS idx_relationships_type ON relationships(type);
1432
-
1433
- CREATE TABLE IF NOT EXISTS hyperedges (
1434
- id TEXT PRIMARY KEY,
1435
- label TEXT NOT NULL,
1436
- relation TEXT NOT NULL,
1437
- confidence REAL DEFAULT 1.0,
1438
- timestamp TEXT NOT NULL
1439
- );
1440
-
1441
- CREATE TABLE IF NOT EXISTS hyperedge_nodes (
1442
- hyperedge_id TEXT NOT NULL,
1443
- entity_id TEXT NOT NULL,
1444
- PRIMARY KEY (hyperedge_id, entity_id)
1445
- );
1446
- `);
1447
- for (const col of [
1448
- "ALTER TABLE relationships ADD COLUMN confidence REAL DEFAULT 1.0",
1449
- "ALTER TABLE relationships ADD COLUMN confidence_label TEXT DEFAULT 'extracted'"
1450
- ]) {
1451
- try {
1452
- await client.execute(col);
1453
- } catch {
1454
- }
1455
- }
1456
- }
1457
- async function getReadyShardClient(projectName) {
1458
- const client = getShardClient(projectName);
1459
- await ensureShardSchema(client);
1460
- return client;
1461
- }
1462
- function disposeShards() {
1463
- for (const [, client] of _shards) {
1464
- client.close();
1465
- }
1466
- _shards.clear();
1467
- _shardingEnabled = false;
1468
- _encryptionKey = null;
1469
- }
1470
- var SHARDS_DIR, _shards, _encryptionKey, _shardingEnabled;
1471
- var init_shard_manager = __esm({
1472
- "src/lib/shard-manager.ts"() {
1473
- "use strict";
1474
- init_config();
1475
- SHARDS_DIR = path3.join(EXE_AI_DIR, "shards");
1476
- _shards = /* @__PURE__ */ new Map();
1477
- _encryptionKey = null;
1478
- _shardingEnabled = false;
1479
- }
1480
- });
1481
-
1482
- // src/lib/employees.ts
1483
- import { readFile as readFile3, writeFile as writeFile3, mkdir as mkdir3 } from "fs/promises";
1484
- import { existsSync as existsSync5, symlinkSync, readlinkSync } from "fs";
1485
- import { execSync } from "child_process";
1486
- import path5 from "path";
1487
- async function loadEmployees(employeesPath = EMPLOYEES_PATH) {
1488
- if (!existsSync5(employeesPath)) {
1489
- return [];
1490
- }
1491
- const raw = await readFile3(employeesPath, "utf-8");
1492
- try {
1493
- return JSON.parse(raw);
1494
- } catch {
1495
- return [];
1496
- }
1497
- }
1498
- var EMPLOYEES_PATH;
1499
- var init_employees = __esm({
1500
- "src/lib/employees.ts"() {
1501
- "use strict";
1502
- init_config();
1503
- EMPLOYEES_PATH = path5.join(EXE_AI_DIR, "exe-employees.json");
1504
- }
1505
- });
1506
-
1507
- // src/lib/license.ts
1508
- import { readFileSync as readFileSync3, writeFileSync, existsSync as existsSync6, mkdirSync as mkdirSync2 } from "fs";
1509
- import { randomUUID } from "crypto";
1510
- import path6 from "path";
1511
- import { jwtVerify, importSPKI } from "jose";
1512
- function loadDeviceId() {
1513
- const deviceJsonPath = path6.join(EXE_AI_DIR, "device.json");
1514
- try {
1515
- if (existsSync6(deviceJsonPath)) {
1516
- const data = JSON.parse(readFileSync3(deviceJsonPath, "utf8"));
1517
- if (data.deviceId) return data.deviceId;
1518
- }
1519
- } catch {
1520
- }
1521
- try {
1522
- if (existsSync6(DEVICE_ID_PATH)) {
1523
- const id2 = readFileSync3(DEVICE_ID_PATH, "utf8").trim();
1524
- if (id2) return id2;
1525
- }
1526
- } catch {
1527
- }
1528
- const id = randomUUID();
1529
- mkdirSync2(EXE_AI_DIR, { recursive: true });
1530
- writeFileSync(DEVICE_ID_PATH, id, "utf8");
1531
- return id;
1532
- }
1533
- function loadLicense() {
1534
- try {
1535
- if (!existsSync6(LICENSE_PATH)) return null;
1536
- return readFileSync3(LICENSE_PATH, "utf8").trim();
1537
- } catch {
1538
- return null;
1539
- }
1540
- }
1541
- async function verifyLicenseJwt(token) {
1542
- try {
1543
- const key = await importSPKI(LICENSE_PUBLIC_KEY_PEM, LICENSE_JWT_ALG);
1544
- const { payload } = await jwtVerify(token, key, {
1545
- algorithms: [LICENSE_JWT_ALG]
1546
- });
1547
- const plan = payload.plan ?? "free";
1548
- const email = payload.sub ?? "";
1549
- const limits = PLAN_LIMITS[plan] ?? PLAN_LIMITS.free;
1550
- return {
1551
- valid: true,
1552
- plan,
1553
- email,
1554
- expiresAt: payload.exp ? new Date(payload.exp * 1e3).toISOString() : null,
1555
- deviceLimit: limits.devices,
1556
- employeeLimit: limits.employees,
1557
- memoryLimit: limits.memories
1558
- };
1559
- } catch {
1560
- return null;
1561
- }
1562
- }
1563
- async function getCachedLicense() {
1564
- try {
1565
- if (!existsSync6(CACHE_PATH)) return null;
1566
- const raw = JSON.parse(readFileSync3(CACHE_PATH, "utf8"));
1567
- if (!raw.token || typeof raw.token !== "string") return null;
1568
- return await verifyLicenseJwt(raw.token);
1569
- } catch {
1570
- return null;
1571
- }
1572
- }
1573
- function cacheResponse(token) {
1574
- try {
1575
- writeFileSync(CACHE_PATH, JSON.stringify({ token }), "utf8");
1576
- } catch {
1577
- }
1578
- }
1579
- async function validateLicense(apiKey, deviceId) {
1580
- const did = deviceId ?? loadDeviceId();
1581
- try {
1582
- const res = await fetch(`${API_BASE}/auth/activate`, {
1583
- method: "POST",
1584
- headers: { "Content-Type": "application/json" },
1585
- body: JSON.stringify({ apiKey, deviceId: did }),
1586
- signal: AbortSignal.timeout(1e4)
1587
- });
1588
- if (res.ok) {
1589
- const data = await res.json();
1590
- if (data.error === "device_limit_exceeded") {
1591
- const cached2 = await getCachedLicense();
1592
- if (cached2) return cached2;
1593
- return { ...FREE_LICENSE, valid: false, plan: "free" };
1594
- }
1595
- if (data.token) {
1596
- cacheResponse(data.token);
1597
- const verified = await verifyLicenseJwt(data.token);
1598
- if (verified) return verified;
1599
- }
1600
- const limits = PLAN_LIMITS[data.plan] ?? PLAN_LIMITS.free;
1601
- return {
1602
- valid: data.valid,
1603
- plan: data.plan,
1604
- email: data.email,
1605
- expiresAt: data.expiresAt,
1606
- deviceLimit: limits.devices,
1607
- employeeLimit: limits.employees,
1608
- memoryLimit: limits.memories
1609
- };
1610
- }
1611
- const cached = await getCachedLicense();
1612
- if (cached) return cached;
1613
- return { ...FREE_LICENSE, valid: false, plan: "free" };
1614
- } catch {
1615
- const cached = await getCachedLicense();
1616
- if (cached) return cached;
1617
- return FREE_LICENSE;
1618
- }
1619
- }
1620
- async function checkLicense() {
1621
- const key = loadLicense();
1622
- if (!key) return FREE_LICENSE;
1623
- const cached = await getCachedLicense();
1624
- if (cached) return cached;
1625
- const deviceId = loadDeviceId();
1626
- return validateLicense(key, deviceId);
1627
- }
1628
- function isFeatureAllowed(license, feature) {
1629
- switch (feature) {
1630
- case "cloud_sync":
1631
- case "external_agents":
1632
- case "wiki":
1633
- return license.plan !== "free";
1634
- case "unlimited_employees":
1635
- return license.plan === "team" || license.plan === "agency" || license.plan === "enterprise";
1636
- }
1637
- }
1638
- var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH, API_BASE, LICENSE_PUBLIC_KEY_PEM, LICENSE_JWT_ALG, PLAN_LIMITS, FREE_LICENSE;
1639
- var init_license = __esm({
1640
- "src/lib/license.ts"() {
1641
- "use strict";
1642
- init_config();
1643
- LICENSE_PATH = path6.join(EXE_AI_DIR, "license.key");
1644
- CACHE_PATH = path6.join(EXE_AI_DIR, "license-cache.json");
1645
- DEVICE_ID_PATH = path6.join(EXE_AI_DIR, "device-id");
1646
- API_BASE = "https://askexe.com/cloud";
1647
- LICENSE_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
1648
- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEeHztAMOpR/ZMh+rWuOASjEZ54CGY
1649
- 4uj+UqeKCcvtgNHKmOK278HJaJcANe9xAeji8AFYu27q3WtzCi04pHudow==
1650
- -----END PUBLIC KEY-----`;
1651
- LICENSE_JWT_ALG = "ES256";
1652
- PLAN_LIMITS = {
1653
- free: { devices: 1, employees: 1, memories: 5e3 },
1654
- pro: { devices: 2, employees: 5, memories: 1e5 },
1655
- team: { devices: 10, employees: 20, memories: 1e6 },
1656
- agency: { devices: 50, employees: 100, memories: 1e7 },
1657
- enterprise: { devices: -1, employees: -1, memories: -1 }
1658
- };
1659
- FREE_LICENSE = {
1660
- valid: true,
1661
- plan: "free",
1662
- email: "",
1663
- expiresAt: null,
1664
- deviceLimit: 1,
1665
- employeeLimit: 1,
1666
- memoryLimit: 5e3
1667
- };
1668
- }
1669
- });
1670
-
1671
- // src/lib/plan-limits.ts
1672
- var plan_limits_exports = {};
1673
- __export(plan_limits_exports, {
1674
- PlanLimitError: () => PlanLimitError,
1675
- assertEmployeeLimit: () => assertEmployeeLimit,
1676
- assertEmployeeLimitSync: () => assertEmployeeLimitSync,
1677
- assertFeature: () => assertFeature,
1678
- assertMemoryLimit: () => assertMemoryLimit,
1679
- countActiveMemories: () => countActiveMemories,
1680
- getLicenseSync: () => getLicenseSync
1681
- });
1682
- import { readFileSync as readFileSync4, existsSync as existsSync7 } from "fs";
1683
- import path7 from "path";
1684
- function getLicenseSync() {
1685
- try {
1686
- if (!existsSync7(CACHE_PATH2)) return freeLicense();
1687
- const raw = JSON.parse(readFileSync4(CACHE_PATH2, "utf8"));
1688
- if (!raw.token || typeof raw.token !== "string") return freeLicense();
1689
- const parts = raw.token.split(".");
1690
- if (parts.length !== 3) return freeLicense();
1691
- const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString());
1692
- const plan = payload.plan ?? "free";
1693
- const limits = PLAN_LIMITS[plan] ?? PLAN_LIMITS.free;
1694
- return {
1695
- valid: true,
1696
- plan,
1697
- email: payload.sub ?? "",
1698
- expiresAt: payload.exp ? new Date(payload.exp * 1e3).toISOString() : null,
1699
- deviceLimit: limits.devices,
1700
- employeeLimit: limits.employees,
1701
- memoryLimit: limits.memories
1702
- };
1703
- } catch {
1704
- return freeLicense();
1705
- }
1706
- }
1707
- function freeLicense() {
1708
- const limits = PLAN_LIMITS.free;
1709
- return {
1710
- valid: true,
1711
- plan: "free",
1712
- email: "",
1713
- expiresAt: null,
1714
- deviceLimit: limits.devices,
1715
- employeeLimit: limits.employees,
1716
- memoryLimit: limits.memories
1717
- };
1718
- }
1719
- async function countActiveMemories() {
1720
- if (!isInitialized()) return 0;
1721
- const client = getClient();
1722
- const result = await client.execute(
1723
- "SELECT COUNT(*) as cnt FROM memories WHERE status = 'active' OR status IS NULL"
1724
- );
1725
- const row = result.rows[0];
1726
- return Number(row?.cnt ?? 0);
1727
- }
1728
- async function assertMemoryLimit() {
1729
- const license = await checkLicense();
1730
- if (license.memoryLimit < 0) return;
1731
- const count = await countActiveMemories();
1732
- if (count >= license.memoryLimit) {
1733
- throw new PlanLimitError(
1734
- `Memory limit reached: ${count}/${license.memoryLimit} active memories on the ${license.plan} plan. Upgrade at https://askexe.com to store more.`
1735
- );
1736
- }
1737
- }
1738
- async function assertEmployeeLimit(license, rosterPath) {
1739
- const lic = license ?? await checkLicense();
1740
- if (lic.employeeLimit < 0) return;
1741
- const employees = await loadEmployees(rosterPath ?? EMPLOYEES_PATH);
1742
- if (employees.length >= lic.employeeLimit) {
1743
- throw new PlanLimitError(
1744
- `Employee limit reached: ${employees.length}/${lic.employeeLimit} employees on the ${lic.plan} plan. Upgrade at https://askexe.com to add more.`
1745
- );
1746
- }
1747
- }
1748
- function assertEmployeeLimitSync(rosterPath) {
1749
- const license = getLicenseSync();
1750
- if (license.employeeLimit < 0) return;
1751
- const filePath = rosterPath ?? EMPLOYEES_PATH;
1752
- let count = 0;
1753
- try {
1754
- if (existsSync7(filePath)) {
1755
- const raw = readFileSync4(filePath, "utf8");
1756
- const employees = JSON.parse(raw);
1757
- count = Array.isArray(employees) ? employees.length : 0;
1758
- }
1759
- } catch {
1760
- throw new PlanLimitError(
1761
- `Cannot verify employee count: roster unreadable at ${filePath}. Refusing to proceed. Check file permissions or upgrade plan.`
1762
- );
1763
- }
1764
- if (count >= license.employeeLimit) {
1765
- throw new PlanLimitError(
1766
- `Employee limit reached: ${count}/${license.employeeLimit} employees on the ${license.plan} plan. Upgrade at https://askexe.com to add more.`
1767
- );
1768
- }
1769
- }
1770
- async function assertFeature(feature) {
1771
- const license = await checkLicense();
1772
- if (!isFeatureAllowed(license, feature)) {
1773
- throw new PlanLimitError(
1774
- `Feature "${feature}" requires a paid plan. Current plan: ${license.plan}. Upgrade at https://askexe.com.`
1775
- );
1776
- }
1777
- }
1778
- var PlanLimitError, CACHE_PATH2;
1779
- var init_plan_limits = __esm({
1780
- "src/lib/plan-limits.ts"() {
1781
- "use strict";
1782
- init_database();
1783
- init_employees();
1784
- init_license();
1785
- init_config();
1786
- PlanLimitError = class extends Error {
1787
- constructor(message) {
1788
- super(message);
1789
- this.name = "PlanLimitError";
1790
- }
1791
- };
1792
- CACHE_PATH2 = path7.join(EXE_AI_DIR, "license-cache.json");
1793
- }
1794
- });
1795
-
1796
- // src/lib/exe-daemon-client.ts
1797
- import net from "net";
1798
- import { spawn } from "child_process";
1799
- import { randomUUID as randomUUID2 } from "crypto";
1800
- import { existsSync as existsSync8, unlinkSync as unlinkSync2, readFileSync as readFileSync5, openSync, closeSync, statSync } from "fs";
1801
- import path8 from "path";
1802
- import { fileURLToPath } from "url";
1803
- function handleData(chunk) {
1804
- _buffer += chunk.toString();
1805
- let newlineIdx;
1806
- while ((newlineIdx = _buffer.indexOf("\n")) !== -1) {
1807
- const line = _buffer.slice(0, newlineIdx).trim();
1808
- _buffer = _buffer.slice(newlineIdx + 1);
1809
- if (!line) continue;
1810
- try {
1811
- const response = JSON.parse(line);
1812
- const entry = _pending.get(response.id);
1813
- if (entry) {
1814
- clearTimeout(entry.timer);
1815
- _pending.delete(response.id);
1816
- entry.resolve(response);
1817
- }
1818
- } catch {
1819
- }
1820
- }
1821
- }
1822
- function cleanupStaleFiles() {
1823
- if (existsSync8(PID_PATH)) {
1824
- try {
1825
- const pid = parseInt(readFileSync5(PID_PATH, "utf8").trim(), 10);
1826
- if (pid > 0) {
1827
- try {
1828
- process.kill(pid, 0);
1829
- return;
1830
- } catch {
1831
- }
1832
- }
1833
- } catch {
1834
- }
1835
- try {
1836
- unlinkSync2(PID_PATH);
1837
- } catch {
1838
- }
1839
- try {
1840
- unlinkSync2(SOCKET_PATH);
1841
- } catch {
1842
- }
1843
- }
1844
- }
1845
- function findPackageRoot() {
1846
- let dir = path8.dirname(fileURLToPath(import.meta.url));
1847
- const { root } = path8.parse(dir);
1848
- while (dir !== root) {
1849
- if (existsSync8(path8.join(dir, "package.json"))) return dir;
1850
- dir = path8.dirname(dir);
1851
- }
1852
- return null;
1853
- }
1854
- function spawnDaemon() {
1855
- const pkgRoot = findPackageRoot();
1856
- if (!pkgRoot) {
1857
- process.stderr.write("[exed-client] WARN: cannot find package root\n");
1858
- return;
1859
- }
1860
- const daemonPath = path8.join(pkgRoot, "dist", "lib", "exe-daemon.js");
1861
- if (!existsSync8(daemonPath)) {
1862
- process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
1863
- `);
1864
- return;
1865
- }
1866
- const resolvedPath = daemonPath;
1867
- process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
1868
- `);
1869
- const logPath = path8.join(path8.dirname(SOCKET_PATH), "exed.log");
1870
- let stderrFd = "ignore";
1871
- try {
1872
- stderrFd = openSync(logPath, "a");
1873
- } catch {
1874
- }
1875
- const child = spawn(process.execPath, [resolvedPath], {
1876
- detached: true,
1877
- stdio: ["ignore", "ignore", stderrFd],
1878
- env: {
1879
- ...process.env,
1880
- EXE_DAEMON_SOCK: SOCKET_PATH,
1881
- EXE_DAEMON_PID: PID_PATH
1882
- }
1883
- });
1884
- child.unref();
1885
- if (typeof stderrFd === "number") {
1886
- try {
1887
- closeSync(stderrFd);
1888
- } catch {
1889
- }
1890
- }
1891
- }
1892
- function acquireSpawnLock() {
1893
- try {
1894
- const fd = openSync(SPAWN_LOCK_PATH, "wx");
1895
- closeSync(fd);
1896
- return true;
1897
- } catch {
1898
- try {
1899
- const stat = statSync(SPAWN_LOCK_PATH);
1900
- if (Date.now() - stat.mtimeMs > SPAWN_LOCK_STALE_MS) {
1901
- try {
1902
- unlinkSync2(SPAWN_LOCK_PATH);
1903
- } catch {
1904
- }
1905
- try {
1906
- const fd = openSync(SPAWN_LOCK_PATH, "wx");
1907
- closeSync(fd);
1908
- return true;
1909
- } catch {
1910
- }
1911
- }
1912
- } catch {
1913
- }
1914
- return false;
1915
- }
1916
- }
1917
- function releaseSpawnLock() {
1918
- try {
1919
- unlinkSync2(SPAWN_LOCK_PATH);
1920
- } catch {
1921
- }
1922
- }
1923
- function connectToSocket() {
1924
- return new Promise((resolve) => {
1925
- if (_socket && _connected) {
1926
- resolve(true);
1927
- return;
1928
- }
1929
- const socket = net.createConnection({ path: SOCKET_PATH });
1930
- const connectTimeout = setTimeout(() => {
1931
- socket.destroy();
1932
- resolve(false);
1933
- }, 2e3);
1934
- socket.on("connect", () => {
1935
- clearTimeout(connectTimeout);
1936
- _socket = socket;
1937
- _connected = true;
1938
- _buffer = "";
1939
- socket.on("data", handleData);
1940
- socket.on("close", () => {
1941
- _connected = false;
1942
- _socket = null;
1943
- for (const [id, entry] of _pending) {
1944
- clearTimeout(entry.timer);
1945
- _pending.delete(id);
1946
- entry.resolve({ error: "Connection closed" });
1947
- }
1948
- });
1949
- socket.on("error", () => {
1950
- _connected = false;
1951
- _socket = null;
1952
- });
1953
- resolve(true);
1954
- });
1955
- socket.on("error", () => {
1956
- clearTimeout(connectTimeout);
1957
- resolve(false);
1958
- });
1959
- });
1960
- }
1961
- async function connectEmbedDaemon() {
1962
- if (_socket && _connected) return true;
1963
- if (await connectToSocket()) return true;
1964
- if (acquireSpawnLock()) {
1965
- try {
1966
- cleanupStaleFiles();
1967
- spawnDaemon();
1968
- } finally {
1969
- releaseSpawnLock();
1970
- }
1971
- }
1972
- const start = Date.now();
1973
- let delay = 100;
1974
- while (Date.now() - start < CONNECT_TIMEOUT_MS) {
1975
- await new Promise((r) => setTimeout(r, delay));
1976
- if (await connectToSocket()) return true;
1977
- delay = Math.min(delay * 2, 3e3);
1978
- }
1979
- return false;
1980
- }
1981
- function sendRequest(texts, priority) {
1982
- return new Promise((resolve) => {
1983
- if (!_socket || !_connected) {
1984
- resolve({ error: "Not connected" });
1985
- return;
1986
- }
1987
- const id = randomUUID2();
1988
- const timer = setTimeout(() => {
1989
- _pending.delete(id);
1990
- resolve({ error: "Request timeout" });
1991
- }, REQUEST_TIMEOUT_MS);
1992
- _pending.set(id, { resolve, timer });
1993
- try {
1994
- _socket.write(JSON.stringify({ id, texts, priority }) + "\n");
1995
- } catch {
1996
- clearTimeout(timer);
1997
- _pending.delete(id);
1998
- resolve({ error: "Write failed" });
1999
- }
2000
- });
2001
- }
2002
- async function pingDaemon() {
2003
- if (!_socket || !_connected) return null;
2004
- return new Promise((resolve) => {
2005
- const id = randomUUID2();
2006
- const timer = setTimeout(() => {
2007
- _pending.delete(id);
2008
- resolve(null);
2009
- }, 5e3);
2010
- _pending.set(id, {
2011
- resolve: (data) => {
2012
- if (data.health) {
2013
- resolve(data.health);
2014
- } else {
2015
- resolve(null);
2016
- }
2017
- },
2018
- timer
2019
- });
2020
- try {
2021
- _socket.write(JSON.stringify({ id, type: "health" }) + "\n");
2022
- } catch {
2023
- clearTimeout(timer);
2024
- _pending.delete(id);
2025
- resolve(null);
2026
- }
2027
- });
2028
- }
2029
- function killAndRespawnDaemon() {
2030
- process.stderr.write("[exed-client] Killing daemon for restart...\n");
2031
- if (existsSync8(PID_PATH)) {
2032
- try {
2033
- const pid = parseInt(readFileSync5(PID_PATH, "utf8").trim(), 10);
2034
- if (pid > 0) {
2035
- try {
2036
- process.kill(pid, "SIGKILL");
2037
- } catch {
2038
- }
2039
- }
2040
- } catch {
2041
- }
2042
- }
2043
- if (_socket) {
2044
- _socket.destroy();
2045
- _socket = null;
2046
- }
2047
- _connected = false;
2048
- _buffer = "";
2049
- try {
2050
- unlinkSync2(PID_PATH);
2051
- } catch {
2052
- }
2053
- try {
2054
- unlinkSync2(SOCKET_PATH);
2055
- } catch {
2056
- }
2057
- spawnDaemon();
2058
- }
2059
- async function embedViaClient(text, priority = "high") {
2060
- if (!_connected && !await connectEmbedDaemon()) return null;
2061
- _requestCount++;
2062
- if (_requestCount % HEALTH_CHECK_INTERVAL === 0) {
2063
- const health = await pingDaemon();
2064
- if (!health) {
2065
- process.stderr.write(`[exed-client] Periodic health check failed at request ${_requestCount} \u2014 restarting daemon
2066
- `);
2067
- killAndRespawnDaemon();
2068
- const start = Date.now();
2069
- let delay = 200;
2070
- while (Date.now() - start < CONNECT_TIMEOUT_MS) {
2071
- await new Promise((r) => setTimeout(r, delay));
2072
- if (await connectToSocket()) break;
2073
- delay = Math.min(delay * 2, 3e3);
2074
- }
2075
- if (!_connected) return null;
2076
- }
2077
- }
2078
- const result = await sendRequest([text], priority);
2079
- if (!result.error && result.vectors?.[0]) return result.vectors[0];
2080
- if (result.error) {
2081
- process.stderr.write(`[exed-client] Embed failed (${result.error}) \u2014 attempting restart
2082
- `);
2083
- killAndRespawnDaemon();
2084
- const start = Date.now();
2085
- let delay = 200;
2086
- while (Date.now() - start < CONNECT_TIMEOUT_MS) {
2087
- await new Promise((r) => setTimeout(r, delay));
2088
- if (await connectToSocket()) break;
2089
- delay = Math.min(delay * 2, 3e3);
2090
- }
2091
- if (!_connected) return null;
2092
- const retry = await sendRequest([text], priority);
2093
- if (!retry.error && retry.vectors?.[0]) return retry.vectors[0];
2094
- process.stderr.write(`[exed-client] Embed retry also failed: ${retry.error ?? "no vector"}
2095
- `);
2096
- }
2097
- return null;
2098
- }
2099
- function disconnectClient() {
2100
- if (_socket) {
2101
- _socket.destroy();
2102
- _socket = null;
2103
- }
2104
- _connected = false;
2105
- _buffer = "";
2106
- for (const [id, entry] of _pending) {
2107
- clearTimeout(entry.timer);
2108
- _pending.delete(id);
2109
- entry.resolve({ error: "Client disconnected" });
2110
- }
2111
- }
2112
- var SOCKET_PATH, PID_PATH, SPAWN_LOCK_PATH, SPAWN_LOCK_STALE_MS, CONNECT_TIMEOUT_MS, REQUEST_TIMEOUT_MS, _socket, _connected, _buffer, _requestCount, HEALTH_CHECK_INTERVAL, _pending;
2113
- var init_exe_daemon_client = __esm({
2114
- "src/lib/exe-daemon-client.ts"() {
2115
- "use strict";
2116
- init_config();
2117
- SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path8.join(EXE_AI_DIR, "exed.sock");
2118
- PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path8.join(EXE_AI_DIR, "exed.pid");
2119
- SPAWN_LOCK_PATH = path8.join(EXE_AI_DIR, "exed-spawn.lock");
2120
- SPAWN_LOCK_STALE_MS = 3e4;
2121
- CONNECT_TIMEOUT_MS = 15e3;
2122
- REQUEST_TIMEOUT_MS = 3e4;
2123
- _socket = null;
2124
- _connected = false;
2125
- _buffer = "";
2126
- _requestCount = 0;
2127
- HEALTH_CHECK_INTERVAL = 100;
2128
- _pending = /* @__PURE__ */ new Map();
2129
- }
2130
- });
2131
-
2132
- // src/lib/embedder.ts
2133
- var embedder_exports = {};
2134
- __export(embedder_exports, {
2135
- disposeEmbedder: () => disposeEmbedder,
2136
- embed: () => embed,
2137
- embedDirect: () => embedDirect,
2138
- getEmbedder: () => getEmbedder
2139
- });
2140
- async function getEmbedder() {
2141
- const ok = await connectEmbedDaemon();
2142
- if (!ok) {
2143
- throw new Error(
2144
- "Could not connect to embedding daemon. Ensure the model is installed (run /exe-setup)."
2145
- );
2146
- }
2147
- }
2148
- async function embed(text) {
2149
- const priority = process.env.EXE_EMBED_PRIORITY === "low" ? "low" : "high";
2150
- const vector = await embedViaClient(text, priority);
2151
- if (!vector) {
2152
- throw new Error(
2153
- "Embedding failed: daemon unavailable. Run /exe-setup to verify model installation."
2154
- );
2155
- }
2156
- if (vector.length !== EMBEDDING_DIM) {
2157
- throw new Error(
2158
- `Embedding dimension mismatch: expected ${EMBEDDING_DIM}, got ${vector.length}. Ensure the correct Jina v5-small Q4_K_M GGUF model is installed.`
2159
- );
2160
- }
2161
- return vector;
2162
- }
2163
- async function disposeEmbedder() {
2164
- disconnectClient();
2165
- }
2166
- async function embedDirect(text) {
2167
- const llamaCpp = await import("node-llama-cpp");
2168
- const { MODELS_DIR: MODELS_DIR2 } = await Promise.resolve().then(() => (init_config(), config_exports));
2169
- const { existsSync: existsSync10 } = await import("fs");
2170
- const path10 = await import("path");
2171
- const modelPath = path10.join(MODELS_DIR2, "jina-embeddings-v5-small-q4_k_m.gguf");
2172
- if (!existsSync10(modelPath)) {
2173
- throw new Error(`Embedding model not found at ${modelPath}. Run '/exe-setup' to download it.`);
2174
- }
2175
- const llama = await llamaCpp.getLlama();
2176
- const model = await llama.loadModel({ modelPath });
2177
- const context = await model.createEmbeddingContext();
2178
- try {
2179
- const embedding = await context.getEmbeddingFor(text);
2180
- const vector = Array.from(embedding.vector);
2181
- if (vector.length !== EMBEDDING_DIM) {
2182
- throw new Error(
2183
- `Embedding dimension mismatch: expected ${EMBEDDING_DIM}, got ${vector.length}.`
2184
- );
2185
- }
2186
- return vector;
2187
- } finally {
2188
- await context.dispose();
2189
- await model.dispose();
2190
- }
2191
- }
2192
- var init_embedder = __esm({
2193
- "src/lib/embedder.ts"() {
2194
- "use strict";
2195
- init_memory();
2196
- init_exe_daemon_client();
2197
- }
2198
- });
2199
-
2200
- // src/lib/crypto.ts
2201
- var crypto_exports = {};
2202
- __export(crypto_exports, {
2203
- decryptSyncBlob: () => decryptSyncBlob,
2204
- encryptSyncBlob: () => encryptSyncBlob,
2205
- initSyncCrypto: () => initSyncCrypto,
2206
- isSyncCryptoInitialized: () => isSyncCryptoInitialized
2207
- });
2208
- import crypto3 from "crypto";
2209
- function initSyncCrypto(masterKey) {
2210
- if (masterKey.length !== 32) {
2211
- throw new Error(`Master key must be 32 bytes, got ${masterKey.length}`);
2212
- }
2213
- _syncKey = Buffer.from(
2214
- crypto3.hkdfSync("sha256", masterKey, "", SYNC_HKDF_INFO, 32)
2215
- );
2216
- }
2217
- function isSyncCryptoInitialized() {
2218
- return _syncKey !== null;
2219
- }
2220
- function requireSyncKey() {
2221
- if (!_syncKey) {
2222
- throw new Error("Sync crypto not initialized. Call initSyncCrypto(masterKey) first.");
2223
- }
2224
- return _syncKey;
2225
- }
2226
- function encryptSyncBlob(data) {
2227
- const key = requireSyncKey();
2228
- const iv = crypto3.randomBytes(IV_LENGTH);
2229
- const cipher = crypto3.createCipheriv(ALGORITHM, key, iv);
2230
- const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);
2231
- const tag = cipher.getAuthTag();
2232
- return Buffer.concat([iv, encrypted, tag]).toString("base64");
2233
- }
2234
- function decryptSyncBlob(ciphertext) {
2235
- const key = requireSyncKey();
2236
- const combined = Buffer.from(ciphertext, "base64");
2237
- if (combined.length < IV_LENGTH + TAG_LENGTH) {
2238
- throw new Error("Sync blob too short to contain IV + tag");
2239
- }
2240
- const iv = combined.subarray(0, IV_LENGTH);
2241
- const tag = combined.subarray(combined.length - TAG_LENGTH);
2242
- const encrypted = combined.subarray(IV_LENGTH, combined.length - TAG_LENGTH);
2243
- const decipher = crypto3.createDecipheriv(ALGORITHM, key, iv);
2244
- decipher.setAuthTag(tag);
2245
- return Buffer.concat([decipher.update(encrypted), decipher.final()]);
2246
- }
2247
- var ALGORITHM, IV_LENGTH, TAG_LENGTH, SYNC_HKDF_INFO, _syncKey;
2248
- var init_crypto = __esm({
2249
- "src/lib/crypto.ts"() {
2250
- "use strict";
2251
- ALGORITHM = "aes-256-gcm";
2252
- IV_LENGTH = 12;
2253
- TAG_LENGTH = 16;
2254
- SYNC_HKDF_INFO = "exe-mem-sync-v2";
2255
- _syncKey = null;
2256
- }
2257
- });
2258
-
2259
- // src/lib/compress.ts
2260
- import { brotliCompressSync, brotliDecompressSync, constants } from "zlib";
2261
- function compress(input) {
2262
- if (input.length === 0) return Buffer.alloc(0);
2263
- return brotliCompressSync(input, {
2264
- params: {
2265
- [constants.BROTLI_PARAM_QUALITY]: 4
2266
- }
2267
- });
2268
- }
2269
- function decompress(input) {
2270
- if (input.length === 0) return Buffer.alloc(0);
2271
- return brotliDecompressSync(input);
2272
- }
2273
- var init_compress = __esm({
2274
- "src/lib/compress.ts"() {
2275
- "use strict";
2276
- }
2277
- });
2278
-
2279
- // src/lib/cloud-sync.ts
2280
- var cloud_sync_exports = {};
2281
- __export(cloud_sync_exports, {
2282
- cloudPull: () => cloudPull,
2283
- cloudPush: () => cloudPush,
2284
- cloudSync: () => cloudSync
2285
- });
2286
- function assertSecureEndpoint(endpoint) {
2287
- if (endpoint.startsWith("https://")) return;
2288
- if (endpoint.startsWith("http://")) {
2289
- try {
2290
- const parsed = new URL(endpoint);
2291
- if (LOCALHOST_PATTERNS.test(parsed.hostname)) return;
2292
- } catch {
2293
- return;
2294
- }
2295
- throw new Error(
2296
- `Insecure cloud endpoint rejected: "${endpoint}". Use https:// for remote hosts. Plain http:// is only allowed for localhost.`
2297
- );
2298
- }
2299
- }
2300
- async function cloudPush(records, maxVersion, config) {
2301
- if (records.length === 0) return true;
2302
- assertSecureEndpoint(config.endpoint);
2303
- try {
2304
- const json = JSON.stringify(records);
2305
- const compressed = compress(Buffer.from(json, "utf8"));
2306
- const blob = encryptSyncBlob(compressed);
2307
- const resp = await fetch(`${config.endpoint}/sync/push`, {
2308
- method: "POST",
2309
- headers: {
2310
- Authorization: `Bearer ${config.apiKey}`,
2311
- "Content-Type": "application/json",
2312
- "X-Device-Id": loadDeviceId()
2313
- },
2314
- body: JSON.stringify({ version: maxVersion, blob })
2315
- });
2316
- return resp.ok;
2317
- } catch (err) {
2318
- process.stderr.write(`[cloud-sync] PUSH FAILED: ${err instanceof Error ? err.message : String(err)}
2319
- `);
2320
- return false;
2321
- }
2322
- }
2323
- async function cloudPull(sinceVersion, config) {
2324
- assertSecureEndpoint(config.endpoint);
2325
- try {
2326
- const response = await fetch(`${config.endpoint}/sync/pull`, {
2327
- method: "POST",
2328
- headers: {
2329
- Authorization: `Bearer ${config.apiKey}`,
2330
- "Content-Type": "application/json",
2331
- "X-Device-Id": loadDeviceId()
2332
- },
2333
- body: JSON.stringify({ since_version: sinceVersion })
2334
- });
2335
- if (!response.ok) return { records: [], maxVersion: sinceVersion };
2336
- const data = await response.json();
2337
- const allRecords = [];
2338
- for (const { blob } of data.blobs ?? []) {
2339
- try {
2340
- const compressed = decryptSyncBlob(blob);
2341
- const json = decompress(compressed).toString("utf8");
2342
- const records = JSON.parse(json);
2343
- allRecords.push(...records);
2344
- } catch {
2345
- continue;
2346
- }
2347
- }
2348
- return { records: allRecords, maxVersion: data.max_version ?? sinceVersion };
2349
- } catch (err) {
2350
- process.stderr.write(`[cloud-sync] PULL FAILED: ${err instanceof Error ? err.message : String(err)}
2351
- `);
2352
- return { records: [], maxVersion: sinceVersion };
2353
- }
2354
- }
2355
- async function cloudSync(config) {
2356
- await assertFeature("cloud_sync");
2357
- let client;
2358
- try {
2359
- client = getClient();
2360
- } catch {
2361
- throw new Error("[cloud-sync] Database not initialized. Call initStore() before cloudSync().");
2362
- }
2363
- const pullMeta = await client.execute(
2364
- "SELECT value FROM sync_meta WHERE key = 'last_cloud_pull_version'"
2365
- );
2366
- const lastPullVersion = pullMeta.rows.length > 0 ? Number(pullMeta.rows[0].value) : 0;
2367
- const pullResult = await cloudPull(lastPullVersion, config);
2368
- let pulled = 0;
2369
- if (pullResult.records.length > 0) {
2370
- const stmts = pullResult.records.map((rec) => ({
2371
- sql: `INSERT OR REPLACE INTO memories
2372
- (id, agent_id, agent_role, session_id, timestamp,
2373
- tool_name, project_name, has_error, raw_text, version,
2374
- author_device_id, scope)
2375
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2376
- args: [
2377
- rec.id,
2378
- rec.agent_id,
2379
- rec.agent_role,
2380
- rec.session_id,
2381
- rec.timestamp,
2382
- rec.tool_name,
2383
- rec.project_name,
2384
- rec.has_error,
2385
- rec.raw_text,
2386
- rec.version,
2387
- rec.author_device_id ?? null,
2388
- rec.scope ?? "business"
2389
- ]
2390
- }));
2391
- await client.batch(stmts, "write");
2392
- pulled = pullResult.records.length;
2393
- }
2394
- if (pullResult.maxVersion > lastPullVersion) {
2395
- await client.execute({
2396
- sql: "INSERT OR REPLACE INTO sync_meta (key, value) VALUES ('last_cloud_pull_version', ?)",
2397
- args: [String(pullResult.maxVersion)]
2398
- });
2399
- }
2400
- const pushMeta = await client.execute(
2401
- "SELECT value FROM sync_meta WHERE key = 'last_cloud_push_version'"
2402
- );
2403
- const lastPushVersion = pushMeta.rows.length > 0 ? Number(pushMeta.rows[0].value) : 0;
2404
- const recordsResult = await client.execute({
2405
- sql: `SELECT id, agent_id, agent_role, session_id, timestamp,
2406
- tool_name, project_name, has_error, raw_text, version,
2407
- author_device_id, scope
2408
- FROM memories
2409
- WHERE version > ?
2410
- AND (scope IS NULL OR scope != 'personal')
2411
- ORDER BY version ASC`,
2412
- args: [lastPushVersion]
2413
- });
2414
- let pushed = 0;
2415
- if (recordsResult.rows.length > 0) {
2416
- const records = recordsResult.rows.map((row) => ({
2417
- id: row.id,
2418
- agent_id: row.agent_id,
2419
- agent_role: row.agent_role,
2420
- session_id: row.session_id,
2421
- timestamp: row.timestamp,
2422
- tool_name: row.tool_name,
2423
- project_name: row.project_name,
2424
- has_error: row.has_error,
2425
- raw_text: row.raw_text,
2426
- version: row.version,
2427
- author_device_id: row.author_device_id,
2428
- scope: row.scope
2429
- }));
2430
- const maxVersion = Number(records[records.length - 1].version);
2431
- const pushOk = await cloudPush(records, maxVersion, config);
2432
- if (pushOk) {
2433
- await client.execute({
2434
- sql: "INSERT OR REPLACE INTO sync_meta (key, value) VALUES ('last_cloud_push_version', ?)",
2435
- args: [String(maxVersion)]
2436
- });
2437
- pushed = records.length;
2438
- }
2439
- }
2440
- return { pushed, pulled };
2441
- }
2442
- var LOCALHOST_PATTERNS;
2443
- var init_cloud_sync = __esm({
2444
- "src/lib/cloud-sync.ts"() {
2445
- "use strict";
2446
- init_database();
2447
- init_crypto();
2448
- init_compress();
2449
- init_plan_limits();
2450
- init_license();
2451
- LOCALHOST_PATTERNS = /^(localhost|127\.0\.0\.1|\[::1\])$/i;
2452
- }
2453
- });
2454
-
2455
- // src/lib/store.ts
2456
- init_memory();
2457
- init_database();
2458
- init_keychain();
2459
- init_config();
2460
- var _pendingRecords = [];
2461
- var _batchSize = 20;
2462
- var _flushIntervalMs = 1e4;
2463
- var _flushTimer = null;
2464
- var _flushing = false;
2465
- var _nextVersion = 1;
2466
- async function initStore(options) {
2467
- if (_flushTimer !== null) {
2468
- clearInterval(_flushTimer);
2469
- _flushTimer = null;
2470
- }
2471
- _pendingRecords = [];
2472
- _flushing = false;
2473
- _batchSize = options?.batchSize ?? 20;
2474
- _flushIntervalMs = options?.flushIntervalMs ?? 1e4;
2475
- let dbPath = options?.dbPath;
2476
- if (!dbPath) {
2477
- const config = await loadConfig();
2478
- dbPath = config.dbPath;
2479
- }
2480
- let masterKey = options?.masterKey ?? null;
2481
- if (!masterKey) {
2482
- masterKey = await getMasterKey();
2483
- if (!masterKey) {
2484
- throw new Error(
2485
- "No encryption key found. Run /exe-setup to generate one."
2486
- );
2487
- }
2488
- }
2489
- const hexKey = masterKey.toString("hex");
2490
- await initTurso({
2491
- dbPath,
2492
- encryptionKey: hexKey
2493
- });
2494
- await ensureSchema();
2495
- try {
2496
- const { initShardManager: initShardManager2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
2497
- initShardManager2(hexKey);
2498
- } catch {
2499
- }
2500
- const client = getClient();
2501
- const vResult = await client.execute("SELECT MAX(version) as max_v FROM memories");
2502
- _nextVersion = (Number(vResult.rows[0]?.max_v) || 0) + 1;
2503
- }
2504
- function classifyTier(record) {
2505
- if (record.tool_name === "commit_to_long_term_memory" && (record.importance ?? 0) >= 8) return 1;
2506
- if (["store_memory", "manual"].includes(record.tool_name ?? "") && (record.importance ?? 0) >= 5) return 2;
2507
- return 3;
2508
- }
2509
- async function writeMemory(record) {
2510
- if (record.vector !== null && record.vector.length !== EMBEDDING_DIM) {
2511
- throw new Error(
2512
- `Expected ${EMBEDDING_DIM}-dim vector, got ${record.vector.length}`
2513
- );
2514
- }
2515
- const dbRow = {
2516
- id: record.id,
2517
- agent_id: record.agent_id,
2518
- agent_role: record.agent_role,
2519
- session_id: record.session_id,
2520
- timestamp: record.timestamp,
2521
- tool_name: record.tool_name,
2522
- project_name: record.project_name,
2523
- has_error: record.has_error ? 1 : 0,
2524
- raw_text: record.raw_text,
2525
- vector: record.vector,
2526
- version: _nextVersion++,
2527
- task_id: record.task_id ?? null,
2528
- importance: record.importance ?? 5,
2529
- status: record.status ?? "active",
2530
- confidence: record.confidence ?? 0.7,
2531
- last_accessed: record.last_accessed ?? record.timestamp,
2532
- workspace_id: record.workspace_id ?? null,
2533
- document_id: record.document_id ?? null,
2534
- user_id: record.user_id ?? null,
2535
- char_offset: record.char_offset ?? null,
2536
- page_number: record.page_number ?? null,
2537
- source_path: record.source_path ?? null,
2538
- source_type: record.source_type ?? null,
2539
- tier: record.tier ?? classifyTier(record),
2540
- supersedes_id: record.supersedes_id ?? null
2541
- };
2542
- _pendingRecords.push(dbRow);
2543
- if (_flushTimer === null) {
2544
- _flushTimer = setInterval(() => {
2545
- void flushBatch();
2546
- }, _flushIntervalMs);
2547
- if (_flushTimer && typeof _flushTimer === "object" && "unref" in _flushTimer) {
2548
- _flushTimer.unref();
2549
- }
2550
- }
2551
- if (_pendingRecords.length >= _batchSize) {
2552
- await flushBatch();
2553
- }
2554
- }
2555
- async function flushBatch() {
2556
- if (_flushing || _pendingRecords.length === 0) return 0;
2557
- _flushing = true;
2558
- try {
2559
- const batch = _pendingRecords.slice(0);
2560
- const buildStmt = (row) => {
2561
- const hasVector = row.vector !== null;
2562
- const taskId = row.task_id ?? null;
2563
- const importance = row.importance ?? 5;
2564
- const status = row.status ?? "active";
2565
- const confidence = row.confidence ?? 0.7;
2566
- const lastAccessed = row.last_accessed ?? row.timestamp;
2567
- const workspaceId = row.workspace_id ?? null;
2568
- const documentId = row.document_id ?? null;
2569
- const userId = row.user_id ?? null;
2570
- const charOffset = row.char_offset ?? null;
2571
- const pageNumber = row.page_number ?? null;
2572
- const sourcePath = row.source_path ?? null;
2573
- const sourceType = row.source_type ?? null;
2574
- const tier = row.tier ?? 3;
2575
- const supersedesId = row.supersedes_id ?? null;
2576
- return {
2577
- sql: hasVector ? `INSERT OR IGNORE INTO memories
2578
- (id, agent_id, agent_role, session_id, timestamp,
2579
- tool_name, project_name,
2580
- has_error, raw_text, vector, version, task_id, importance, status,
2581
- confidence, last_accessed,
2582
- workspace_id, document_id, user_id, char_offset, page_number,
2583
- source_path, source_type, tier, supersedes_id)
2584
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, vector32(?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` : `INSERT OR IGNORE INTO memories
2585
- (id, agent_id, agent_role, session_id, timestamp,
2586
- tool_name, project_name,
2587
- has_error, raw_text, vector, version, task_id, importance, status,
2588
- confidence, last_accessed,
2589
- workspace_id, document_id, user_id, char_offset, page_number,
2590
- source_path, source_type, tier, supersedes_id)
2591
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2592
- args: hasVector ? [
2593
- row.id,
2594
- row.agent_id,
2595
- row.agent_role,
2596
- row.session_id,
2597
- row.timestamp,
2598
- row.tool_name,
2599
- row.project_name,
2600
- row.has_error,
2601
- row.raw_text,
2602
- vectorToBlob(row.vector),
2603
- row.version,
2604
- taskId,
2605
- importance,
2606
- status,
2607
- confidence,
2608
- lastAccessed,
2609
- workspaceId,
2610
- documentId,
2611
- userId,
2612
- charOffset,
2613
- pageNumber,
2614
- sourcePath,
2615
- sourceType,
2616
- tier,
2617
- supersedesId
2618
- ] : [
2619
- row.id,
2620
- row.agent_id,
2621
- row.agent_role,
2622
- row.session_id,
2623
- row.timestamp,
2624
- row.tool_name,
2625
- row.project_name,
2626
- row.has_error,
2627
- row.raw_text,
2628
- row.version,
2629
- taskId,
2630
- importance,
2631
- status,
2632
- confidence,
2633
- lastAccessed,
2634
- workspaceId,
2635
- documentId,
2636
- userId,
2637
- charOffset,
2638
- pageNumber,
2639
- sourcePath,
2640
- sourceType,
2641
- tier,
2642
- supersedesId
2643
- ]
2644
- };
2645
- };
2646
- const globalClient = getClient();
2647
- const globalStmts = batch.map(buildStmt);
2648
- await globalClient.batch(globalStmts, "write");
2649
- _pendingRecords.splice(0, batch.length);
2650
- try {
2651
- const { isShardingEnabled: isShardingEnabled2, getReadyShardClient: getReadyShardClient2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
2652
- if (isShardingEnabled2()) {
2653
- const byProject = /* @__PURE__ */ new Map();
2654
- for (const row of batch) {
2655
- const proj = row.project_name || "unknown";
2656
- if (!byProject.has(proj)) byProject.set(proj, []);
2657
- byProject.get(proj).push(row);
2658
- }
2659
- for (const [project, rows] of byProject) {
2660
- try {
2661
- const shardClient = await getReadyShardClient2(project);
2662
- const shardStmts = rows.map(buildStmt);
2663
- await shardClient.batch(shardStmts, "write");
2664
- } catch (err) {
2665
- process.stderr.write(
2666
- `[store] Shard write failed for ${project}: ${err instanceof Error ? err.message : String(err)}
2667
- `
2668
- );
2669
- }
2670
- }
2671
- }
2672
- } catch {
2673
- }
2674
- return batch.length;
2675
- } finally {
2676
- _flushing = false;
2677
- }
2678
- }
2679
- function vectorToBlob(vector) {
2680
- const f32 = vector instanceof Float32Array ? vector : new Float32Array(vector);
2681
- return JSON.stringify(Array.from(f32));
2682
- }
2683
-
2684
- // src/adapters/claude/hooks/summary-worker.ts
2685
- init_database();
2686
- import crypto4 from "crypto";
2687
-
2688
- // src/lib/notifications.ts
2689
- init_database();
2690
- import crypto2 from "crypto";
2691
- import path4 from "path";
2692
- import os2 from "os";
2693
- import {
2694
- readFileSync as readFileSync2,
2695
- readdirSync,
2696
- unlinkSync,
2697
- existsSync as existsSync4,
2698
- rmdirSync
2699
- } from "fs";
2700
- async function writeNotification(notification) {
2701
- try {
2702
- const client = getClient();
2703
- const id = crypto2.randomUUID();
2704
- const now = (/* @__PURE__ */ new Date()).toISOString();
2705
- await client.execute({
2706
- sql: `INSERT INTO notifications (id, agent_id, agent_role, event, project, summary, task_file, read, created_at)
2707
- VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?)`,
2708
- args: [
2709
- id,
2710
- notification.agentId,
2711
- notification.agentRole,
2712
- notification.event,
2713
- notification.project,
2714
- notification.summary,
2715
- notification.taskFile ?? null,
2716
- now
2717
- ]
2718
- });
2719
- } catch (err) {
2720
- process.stderr.write(`[notifications] WRITE FAILED: ${err instanceof Error ? err.message : String(err)}
2721
- `);
2722
- }
2723
- }
2724
-
2725
- // src/adapters/claude/hooks/summary-worker.ts
2726
- import { execSync as execSync2 } from "child_process";
2727
- import { existsSync as existsSync9, mkdirSync as mkdirSync3, openSync as openSync2, closeSync as closeSync2 } from "fs";
2728
- import path9 from "path";
2729
- async function main() {
2730
- const agentId = process.env.AGENT_ID ?? "default";
2731
- const agentRole = process.env.AGENT_ROLE ?? "employee";
2732
- const totalCalls = process.env.EXE_SUMMARY_TOTAL ?? "25";
2733
- const writeCalls = process.env.EXE_SUMMARY_WRITES ?? "3";
2734
- await initStore();
2735
- const client = getClient();
2736
- const result = await client.execute({
2737
- sql: `SELECT tool_name, project_name, raw_text, has_error, timestamp
2738
- FROM memories
2739
- WHERE agent_id = ?
2740
- ORDER BY timestamp DESC
2741
- LIMIT 30`,
2742
- args: [agentId]
2743
- });
2744
- if (result.rows.length === 0) return;
2745
- const projects = /* @__PURE__ */ new Map();
2746
- for (const row of result.rows) {
2747
- const project = row.project_name || "unknown";
2748
- const tool = row.tool_name || "unknown";
2749
- const rawText = row.raw_text || "";
2750
- const hasError = row.has_error === 1;
2751
- if (!projects.has(project)) {
2752
- projects.set(project, { tools: /* @__PURE__ */ new Set(), errors: 0, samples: [] });
2753
- }
2754
- const entry = projects.get(project);
2755
- entry.tools.add(tool);
2756
- if (hasError) entry.errors++;
2757
- if (entry.samples.length < 3 && rawText.length > 50) {
2758
- entry.samples.push(rawText.slice(0, 150));
2759
- }
2760
- }
2761
- const parts = [];
2762
- parts.push(`Auto-summary: ${totalCalls} tool calls (${writeCalls} writes)`);
2763
- parts.push(`Agent: ${agentId} (${agentRole})`);
2764
- parts.push(`Time: ${(/* @__PURE__ */ new Date()).toISOString()}`);
2765
- parts.push("");
2766
- for (const [project, data] of projects) {
2767
- parts.push(`Project: ${project}`);
2768
- parts.push(` Tools used: ${[...data.tools].join(", ")}`);
2769
- if (data.errors > 0) {
2770
- parts.push(` Errors encountered: ${data.errors}`);
2771
- }
2772
- for (const sample of data.samples) {
2773
- parts.push(` - ${sample}`);
2774
- }
2775
- parts.push("");
2776
- }
2777
- const summaryText = parts.join("\n");
2778
- let primaryProject = "unknown";
2779
- let maxCount = 0;
2780
- const projectCounts = /* @__PURE__ */ new Map();
2781
- for (const row of result.rows) {
2782
- const p = row.project_name || "unknown";
2783
- const c = (projectCounts.get(p) ?? 0) + 1;
2784
- projectCounts.set(p, c);
2785
- if (c > maxCount) {
2786
- maxCount = c;
2787
- primaryProject = p;
2788
- }
2789
- }
2790
- try {
2791
- const { assertMemoryLimit: assertMemoryLimit2 } = await Promise.resolve().then(() => (init_plan_limits(), plan_limits_exports));
2792
- await assertMemoryLimit2();
2793
- } catch {
2794
- process.exit(0);
2795
- }
2796
- await writeMemory({
2797
- id: crypto4.randomUUID(),
2798
- agent_id: agentId,
2799
- agent_role: agentRole,
2800
- session_id: `auto-summary-${Date.now()}`,
2801
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2802
- tool_name: "auto-summary",
2803
- project_name: primaryProject,
2804
- has_error: false,
2805
- raw_text: summaryText,
2806
- vector: null
2807
- });
2808
- await flushBatch();
2809
- if (agentId !== "exe" && agentId !== "default") {
2810
- let totalErrors = 0;
2811
- for (const [, data] of projects) {
2812
- totalErrors += data.errors;
2813
- }
2814
- if (totalErrors >= 3) {
2815
- await writeNotification({
2816
- agentId,
2817
- agentRole,
2818
- event: "error_spike",
2819
- project: primaryProject,
2820
- summary: `${totalErrors} errors in last ${totalCalls} tool calls`
2821
- });
2822
- } else {
2823
- await writeNotification({
2824
- agentId,
2825
- agentRole,
2826
- event: "session_summary",
2827
- project: primaryProject,
2828
- summary: `${totalCalls} tool calls (${writeCalls} writes) on ${primaryProject}`
2829
- });
2830
- }
2831
- }
2832
- try {
2833
- const { embed: embed2 } = await Promise.resolve().then(() => (init_embedder(), embedder_exports));
2834
- const vector = await embed2(summaryText);
2835
- await client.execute({
2836
- sql: "UPDATE memories SET vector = vector32(?) WHERE agent_id = ? AND tool_name = 'auto-summary' ORDER BY timestamp DESC LIMIT 1",
2837
- args: [vectorToBlob(vector), agentId]
2838
- });
2839
- } catch (err) {
2840
- process.stderr.write("[summary-worker] embed failed: " + (err instanceof Error ? err.message : String(err)) + "\n");
2841
- }
2842
- try {
2843
- const { EXE_AI_DIR: EXE_AI_DIR2 } = await Promise.resolve().then(() => (init_config(), config_exports));
2844
- const flagPath = path9.join(EXE_AI_DIR2, "session-cache", "needs-backfill");
2845
- if (existsSync9(flagPath)) {
2846
- const { spawn: spawn2 } = await import("child_process");
2847
- const { fileURLToPath: fileURLToPath2 } = await import("url");
2848
- const thisFile = fileURLToPath2(import.meta.url);
2849
- const backfillPath = path9.resolve(path9.dirname(thisFile), "backfill-vectors.js");
2850
- if (existsSync9(backfillPath)) {
2851
- const { EXE_AI_DIR: exeDir2 } = await Promise.resolve().then(() => (init_config(), config_exports));
2852
- const bLogPath = path9.join(exeDir2, "workers.log");
2853
- mkdirSync3(path9.dirname(bLogPath), { recursive: true });
2854
- const bLogFd = openSync2(bLogPath, "a");
2855
- const child = spawn2(process.execPath, [backfillPath], {
2856
- detached: true,
2857
- stdio: ["ignore", "ignore", bLogFd]
2858
- });
2859
- child.unref();
2860
- try {
2861
- closeSync2(bLogFd);
2862
- } catch {
2863
- }
2864
- process.stderr.write("[summary-worker] Spawned backfill job\n");
2865
- } else {
2866
- process.stderr.write(`[summary-worker] WARN: backfill-vectors not found at ${backfillPath}
2867
- `);
2868
- }
2869
- }
2870
- } catch (err) {
2871
- process.stderr.write("[summary-worker] backfill spawn failed: " + (err instanceof Error ? err.message : String(err)) + "\n");
2872
- }
2873
- try {
2874
- const { loadConfig: loadConfig2 } = await Promise.resolve().then(() => (init_config(), config_exports));
2875
- const cfg = await loadConfig2();
2876
- if (cfg.cloud?.apiKey) {
2877
- const { initSyncCrypto: initSyncCrypto2, isSyncCryptoInitialized: isSyncCryptoInitialized2 } = await Promise.resolve().then(() => (init_crypto(), crypto_exports));
2878
- if (!isSyncCryptoInitialized2()) {
2879
- const { getMasterKey: getMasterKey2 } = await Promise.resolve().then(() => (init_keychain(), keychain_exports));
2880
- const mk = await getMasterKey2();
2881
- if (mk) initSyncCrypto2(mk);
2882
- }
2883
- const { cloudSync: cloudSync2 } = await Promise.resolve().then(() => (init_cloud_sync(), cloud_sync_exports));
2884
- await cloudSync2({ apiKey: cfg.cloud.apiKey, endpoint: cfg.cloud.endpoint });
2885
- }
2886
- } catch (err) {
2887
- process.stderr.write("[summary-worker] cloud sync failed: " + (err instanceof Error ? err.message : String(err)) + "\n");
2888
- }
2889
- if (agentId !== "exe" && agentId !== "default") {
2890
- try {
2891
- const inProgressResult = await client.execute({
2892
- sql: "SELECT id, title, task_file FROM tasks WHERE assigned_to = ? AND status = 'in_progress'",
2893
- args: [agentId]
2894
- });
2895
- for (const taskRow of inProgressResult.rows) {
2896
- const taskFile = String(taskRow.task_file);
2897
- void taskFile.split("/").pop();
2898
- const taskTitle = String(taskRow.title);
2899
- let lastCommit = "";
2900
- try {
2901
- lastCommit = execSync2("git log --oneline -1 --since='30 minutes ago'", {
2902
- encoding: "utf8",
2903
- timeout: 5e3
2904
- }).trim();
2905
- } catch {
2906
- }
2907
- if (!lastCommit) continue;
2908
- const now = (/* @__PURE__ */ new Date()).toISOString();
2909
- void now;
2910
- try {
2911
- await writeNotification({
2912
- agentId,
2913
- agentRole,
2914
- event: "orphan_task",
2915
- project: primaryProject,
2916
- summary: `${agentId} left '${taskTitle}' as in_progress \u2014 session ended with recent commit ${lastCommit}`
2917
- });
2918
- } catch (err) {
2919
- process.stderr.write("[summary-worker] review write failed: " + (err instanceof Error ? err.message : String(err)) + "\n");
2920
- }
2921
- }
2922
- } catch (err) {
2923
- process.stderr.write("[summary-worker] orphan scan failed: " + (err instanceof Error ? err.message : String(err)) + "\n");
2924
- }
2925
- }
2926
- }
2927
- main().catch((err) => {
2928
- process.stderr.write("[summary-worker] FATAL: " + (err instanceof Error ? err.message : String(err)) + "\n");
2929
- }).finally(() => {
2930
- process.exit(0);
2931
- });