@askexenow/exe-os 0.8.44 → 0.8.46

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.
@@ -1,25 +1,948 @@
1
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
- }) : x)(function(x) {
4
- if (typeof require !== "undefined") return require.apply(this, arguments);
5
- throw Error('Dynamic require of "' + x + '" is not supported');
6
- });
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
7
10
 
8
- // src/lib/cloud-sync.ts
9
- import { readFileSync as readFileSync5, writeFileSync as writeFileSync2, existsSync as existsSync5, readdirSync, mkdirSync as mkdirSync2, appendFileSync, unlinkSync, openSync, closeSync } from "fs";
10
- import crypto2 from "crypto";
11
- import path5 from "path";
12
- import { homedir } from "os";
11
+ // src/lib/db-retry.ts
12
+ function isBusyError(err) {
13
+ if (err instanceof Error) {
14
+ const msg = err.message.toLowerCase();
15
+ return msg.includes("sqlite_busy") || msg.includes("database is locked");
16
+ }
17
+ return false;
18
+ }
19
+ function delay(ms) {
20
+ return new Promise((resolve) => setTimeout(resolve, ms));
21
+ }
22
+ async function retryOnBusy(fn, label) {
23
+ let lastError;
24
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
25
+ try {
26
+ return await fn();
27
+ } catch (err) {
28
+ lastError = err;
29
+ if (!isBusyError(err) || attempt === MAX_RETRIES) {
30
+ throw err;
31
+ }
32
+ const backoff = BASE_DELAY_MS * Math.pow(2, attempt);
33
+ const jitter = Math.floor(Math.random() * MAX_JITTER_MS);
34
+ process.stderr.write(
35
+ `[exe-os] SQLITE_BUSY ${label} retry ${attempt + 1}/${MAX_RETRIES} \u2014 waiting ${backoff + jitter}ms
36
+ `
37
+ );
38
+ await delay(backoff + jitter);
39
+ }
40
+ }
41
+ throw lastError;
42
+ }
43
+ function wrapWithRetry(client) {
44
+ return new Proxy(client, {
45
+ get(target, prop, receiver) {
46
+ if (prop === "execute") {
47
+ return (sql) => retryOnBusy(() => target.execute(sql), "execute");
48
+ }
49
+ if (prop === "batch") {
50
+ return (stmts) => retryOnBusy(() => target.batch(stmts), "batch");
51
+ }
52
+ return Reflect.get(target, prop, receiver);
53
+ }
54
+ });
55
+ }
56
+ var MAX_RETRIES, BASE_DELAY_MS, MAX_JITTER_MS;
57
+ var init_db_retry = __esm({
58
+ "src/lib/db-retry.ts"() {
59
+ "use strict";
60
+ MAX_RETRIES = 3;
61
+ BASE_DELAY_MS = 200;
62
+ MAX_JITTER_MS = 300;
63
+ }
64
+ });
13
65
 
14
66
  // src/lib/database.ts
67
+ var database_exports = {};
68
+ __export(database_exports, {
69
+ disposeDatabase: () => disposeDatabase,
70
+ disposeTurso: () => disposeTurso,
71
+ ensureSchema: () => ensureSchema,
72
+ getClient: () => getClient,
73
+ getRawClient: () => getRawClient,
74
+ initDatabase: () => initDatabase,
75
+ initTurso: () => initTurso,
76
+ isInitialized: () => isInitialized
77
+ });
15
78
  import { createClient } from "@libsql/client";
16
- var _resilientClient = null;
79
+ async function initDatabase(config) {
80
+ if (_client) {
81
+ _client.close();
82
+ _client = null;
83
+ _resilientClient = null;
84
+ }
85
+ const opts = {
86
+ url: `file:${config.dbPath}`
87
+ };
88
+ if (config.encryptionKey) {
89
+ opts.encryptionKey = config.encryptionKey;
90
+ }
91
+ _client = createClient(opts);
92
+ _resilientClient = wrapWithRetry(_client);
93
+ }
94
+ function isInitialized() {
95
+ return _client !== null;
96
+ }
17
97
  function getClient() {
18
98
  if (!_resilientClient) {
19
99
  throw new Error("Database client not initialized. Call initDatabase() first.");
20
100
  }
21
101
  return _resilientClient;
22
102
  }
103
+ function getRawClient() {
104
+ if (!_client) {
105
+ throw new Error("Database client not initialized. Call initDatabase() first.");
106
+ }
107
+ return _client;
108
+ }
109
+ async function ensureSchema() {
110
+ const client = getRawClient();
111
+ await client.execute("PRAGMA journal_mode = WAL");
112
+ await client.execute("PRAGMA busy_timeout = 30000");
113
+ await client.execute("PRAGMA wal_autocheckpoint = 1000");
114
+ try {
115
+ await client.execute("PRAGMA libsql_vector_search_ef = 128");
116
+ } catch {
117
+ }
118
+ await client.executeMultiple(`
119
+ CREATE TABLE IF NOT EXISTS memories (
120
+ id TEXT PRIMARY KEY,
121
+ agent_id TEXT NOT NULL,
122
+ agent_role TEXT NOT NULL,
123
+ session_id TEXT NOT NULL,
124
+ timestamp TEXT NOT NULL,
125
+ tool_name TEXT NOT NULL,
126
+ project_name TEXT NOT NULL,
127
+ has_error INTEGER NOT NULL DEFAULT 0,
128
+ raw_text TEXT NOT NULL,
129
+ vector F32_BLOB(1024),
130
+ version INTEGER NOT NULL DEFAULT 0
131
+ );
132
+
133
+ CREATE INDEX IF NOT EXISTS idx_memories_agent
134
+ ON memories(agent_id);
135
+
136
+ CREATE INDEX IF NOT EXISTS idx_memories_timestamp
137
+ ON memories(timestamp);
138
+
139
+ CREATE INDEX IF NOT EXISTS idx_memories_session
140
+ ON memories(session_id);
141
+
142
+ CREATE INDEX IF NOT EXISTS idx_memories_project
143
+ ON memories(project_name);
144
+
145
+ CREATE INDEX IF NOT EXISTS idx_memories_tool
146
+ ON memories(tool_name);
147
+
148
+ CREATE INDEX IF NOT EXISTS idx_memories_version
149
+ ON memories(version);
150
+
151
+ CREATE INDEX IF NOT EXISTS idx_memories_agent_project
152
+ ON memories(agent_id, project_name);
153
+ `);
154
+ await client.executeMultiple(`
155
+ CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
156
+ raw_text,
157
+ content='memories',
158
+ content_rowid='rowid'
159
+ );
160
+
161
+ CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
162
+ INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
163
+ END;
164
+
165
+ CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
166
+ INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
167
+ END;
168
+
169
+ CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
170
+ INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
171
+ INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
172
+ END;
173
+ `);
174
+ await client.executeMultiple(`
175
+ CREATE TABLE IF NOT EXISTS sync_meta (
176
+ key TEXT PRIMARY KEY,
177
+ value TEXT NOT NULL
178
+ );
179
+ `);
180
+ await client.executeMultiple(`
181
+ CREATE TABLE IF NOT EXISTS tasks (
182
+ id TEXT PRIMARY KEY,
183
+ title TEXT NOT NULL,
184
+ assigned_to TEXT NOT NULL,
185
+ assigned_by TEXT NOT NULL,
186
+ project_name TEXT NOT NULL,
187
+ priority TEXT NOT NULL DEFAULT 'p1',
188
+ status TEXT NOT NULL DEFAULT 'open',
189
+ task_file TEXT,
190
+ created_at TEXT NOT NULL,
191
+ updated_at TEXT NOT NULL
192
+ );
193
+
194
+ CREATE INDEX IF NOT EXISTS idx_tasks_assignee_status
195
+ ON tasks(assigned_to, status);
196
+ `);
197
+ await client.executeMultiple(`
198
+ CREATE TABLE IF NOT EXISTS behaviors (
199
+ id TEXT PRIMARY KEY,
200
+ agent_id TEXT NOT NULL,
201
+ project_name TEXT,
202
+ domain TEXT,
203
+ content TEXT NOT NULL,
204
+ active INTEGER NOT NULL DEFAULT 1,
205
+ created_at TEXT NOT NULL,
206
+ updated_at TEXT NOT NULL
207
+ );
208
+
209
+ CREATE INDEX IF NOT EXISTS idx_behaviors_agent
210
+ ON behaviors(agent_id, active);
211
+ `);
212
+ try {
213
+ const existing = await client.execute({
214
+ sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = 'exe'",
215
+ args: []
216
+ });
217
+ if (Number(existing.rows[0]?.cnt) === 0) {
218
+ await client.executeMultiple(`
219
+ INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
220
+ VALUES
221
+ (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');
222
+ INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
223
+ VALUES
224
+ (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');
225
+ INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
226
+ VALUES
227
+ (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');
228
+ `);
229
+ }
230
+ } catch {
231
+ }
232
+ try {
233
+ await client.execute({
234
+ sql: `ALTER TABLE behaviors ADD COLUMN priority TEXT DEFAULT 'p1'`,
235
+ args: []
236
+ });
237
+ } catch {
238
+ }
239
+ try {
240
+ await client.execute({
241
+ sql: `ALTER TABLE tasks ADD COLUMN blocked_by TEXT`,
242
+ args: []
243
+ });
244
+ } catch {
245
+ }
246
+ try {
247
+ await client.execute({
248
+ sql: `ALTER TABLE tasks ADD COLUMN parent_task_id TEXT`,
249
+ args: []
250
+ });
251
+ } catch {
252
+ }
253
+ try {
254
+ await client.execute({
255
+ sql: `CREATE INDEX IF NOT EXISTS idx_tasks_parent_task_id
256
+ ON tasks(parent_task_id)
257
+ WHERE parent_task_id IS NOT NULL`,
258
+ args: []
259
+ });
260
+ } catch {
261
+ }
262
+ try {
263
+ await client.execute({
264
+ sql: `UPDATE tasks SET status = 'done' WHERE status = 'completed'`,
265
+ args: []
266
+ });
267
+ } catch {
268
+ }
269
+ try {
270
+ await client.execute({
271
+ sql: `ALTER TABLE tasks ADD COLUMN reviewer TEXT`,
272
+ args: []
273
+ });
274
+ } catch {
275
+ }
276
+ try {
277
+ await client.execute({
278
+ sql: `ALTER TABLE tasks ADD COLUMN context TEXT`,
279
+ args: []
280
+ });
281
+ } catch {
282
+ }
283
+ try {
284
+ await client.execute({
285
+ sql: `ALTER TABLE tasks ADD COLUMN result TEXT`,
286
+ args: []
287
+ });
288
+ } catch {
289
+ }
290
+ try {
291
+ await client.execute({
292
+ sql: `ALTER TABLE tasks ADD COLUMN assigned_tmux TEXT`,
293
+ args: []
294
+ });
295
+ } catch {
296
+ }
297
+ try {
298
+ await client.execute({
299
+ sql: `ALTER TABLE tasks ADD COLUMN checkpoint TEXT`,
300
+ args: []
301
+ });
302
+ } catch {
303
+ }
304
+ try {
305
+ await client.execute({
306
+ sql: `ALTER TABLE tasks ADD COLUMN checkpoint_count INTEGER NOT NULL DEFAULT 0`,
307
+ args: []
308
+ });
309
+ } catch {
310
+ }
311
+ try {
312
+ await client.execute({
313
+ sql: `ALTER TABLE tasks ADD COLUMN complexity TEXT NOT NULL DEFAULT 'standard'`,
314
+ args: []
315
+ });
316
+ } catch {
317
+ }
318
+ try {
319
+ await client.execute({
320
+ sql: `ALTER TABLE tasks ADD COLUMN session_scope TEXT`,
321
+ args: []
322
+ });
323
+ } catch {
324
+ }
325
+ try {
326
+ await client.execute({
327
+ sql: `ALTER TABLE memories ADD COLUMN task_id TEXT`,
328
+ args: []
329
+ });
330
+ } catch {
331
+ }
332
+ try {
333
+ await client.execute({
334
+ sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
335
+ args: []
336
+ });
337
+ } catch {
338
+ }
339
+ try {
340
+ await client.execute({
341
+ sql: `ALTER TABLE memories ADD COLUMN author_device_id TEXT`,
342
+ args: []
343
+ });
344
+ } catch {
345
+ }
346
+ try {
347
+ await client.execute({
348
+ sql: `ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'`,
349
+ args: []
350
+ });
351
+ } catch {
352
+ }
353
+ await client.executeMultiple(`
354
+ CREATE TABLE IF NOT EXISTS consolidations (
355
+ id TEXT PRIMARY KEY,
356
+ consolidated_memory_id TEXT NOT NULL,
357
+ source_memory_id TEXT NOT NULL,
358
+ created_at TEXT NOT NULL
359
+ );
360
+
361
+ CREATE INDEX IF NOT EXISTS idx_consolidations_source
362
+ ON consolidations(source_memory_id);
363
+
364
+ CREATE INDEX IF NOT EXISTS idx_consolidations_consolidated
365
+ ON consolidations(consolidated_memory_id);
366
+ `);
367
+ await client.executeMultiple(`
368
+ CREATE TABLE IF NOT EXISTS reminders (
369
+ id TEXT PRIMARY KEY,
370
+ text TEXT NOT NULL,
371
+ created_at TEXT NOT NULL,
372
+ due_date TEXT,
373
+ completed_at TEXT
374
+ );
375
+ `);
376
+ await client.executeMultiple(`
377
+ CREATE TABLE IF NOT EXISTS notifications (
378
+ id TEXT PRIMARY KEY,
379
+ agent_id TEXT NOT NULL,
380
+ agent_role TEXT NOT NULL,
381
+ event TEXT NOT NULL,
382
+ project TEXT NOT NULL,
383
+ summary TEXT NOT NULL,
384
+ task_file TEXT,
385
+ read INTEGER NOT NULL DEFAULT 0,
386
+ created_at TEXT NOT NULL
387
+ );
388
+
389
+ CREATE INDEX IF NOT EXISTS idx_notifications_read
390
+ ON notifications(read);
391
+
392
+ CREATE INDEX IF NOT EXISTS idx_notifications_agent
393
+ ON notifications(agent_id);
394
+
395
+ CREATE INDEX IF NOT EXISTS idx_notifications_task_file
396
+ ON notifications(task_file);
397
+ `);
398
+ await client.executeMultiple(`
399
+ CREATE TABLE IF NOT EXISTS schedules (
400
+ id TEXT PRIMARY KEY,
401
+ cron TEXT NOT NULL,
402
+ description TEXT NOT NULL,
403
+ job_type TEXT NOT NULL DEFAULT 'report',
404
+ prompt TEXT,
405
+ assigned_to TEXT,
406
+ project_name TEXT,
407
+ active INTEGER NOT NULL DEFAULT 1,
408
+ use_crontab INTEGER NOT NULL DEFAULT 0,
409
+ created_at TEXT NOT NULL
410
+ );
411
+ `);
412
+ await client.executeMultiple(`
413
+ CREATE TABLE IF NOT EXISTS device_registry (
414
+ device_id TEXT PRIMARY KEY,
415
+ friendly_name TEXT NOT NULL,
416
+ hostname TEXT NOT NULL,
417
+ projects TEXT NOT NULL DEFAULT '[]',
418
+ agents TEXT NOT NULL DEFAULT '[]',
419
+ connected INTEGER DEFAULT 0,
420
+ last_seen TEXT NOT NULL
421
+ );
422
+ `);
423
+ await client.executeMultiple(`
424
+ CREATE TABLE IF NOT EXISTS messages (
425
+ id TEXT PRIMARY KEY,
426
+ from_agent TEXT NOT NULL,
427
+ from_device TEXT NOT NULL DEFAULT 'local',
428
+ target_agent TEXT NOT NULL,
429
+ target_project TEXT,
430
+ target_device TEXT NOT NULL DEFAULT 'local',
431
+ content TEXT NOT NULL,
432
+ priority TEXT DEFAULT 'normal',
433
+ status TEXT DEFAULT 'pending',
434
+ server_seq INTEGER,
435
+ retry_count INTEGER DEFAULT 0,
436
+ created_at TEXT NOT NULL,
437
+ delivered_at TEXT,
438
+ processed_at TEXT,
439
+ failed_at TEXT,
440
+ failure_reason TEXT
441
+ );
442
+
443
+ CREATE INDEX IF NOT EXISTS idx_messages_target
444
+ ON messages(target_agent, status);
445
+
446
+ CREATE INDEX IF NOT EXISTS idx_messages_conversation_order
447
+ ON messages(target_agent, from_agent, server_seq);
448
+ `);
449
+ try {
450
+ await client.execute({
451
+ sql: `UPDATE memories SET project_name = 'exe-create' WHERE project_name = 'web'`,
452
+ args: []
453
+ });
454
+ await client.execute({
455
+ sql: `UPDATE memories SET project_name = 'exe-os' WHERE project_name = 'worker'`,
456
+ args: []
457
+ });
458
+ await client.execute({
459
+ sql: `UPDATE tasks SET project_name = 'exe-create' WHERE project_name = 'web'`,
460
+ args: []
461
+ });
462
+ await client.execute({
463
+ sql: `UPDATE tasks SET project_name = 'exe-os' WHERE project_name = 'worker'`,
464
+ args: []
465
+ });
466
+ } catch {
467
+ }
468
+ await client.executeMultiple(`
469
+ CREATE TABLE IF NOT EXISTS trajectories (
470
+ id TEXT PRIMARY KEY,
471
+ task_id TEXT NOT NULL,
472
+ agent_id TEXT NOT NULL,
473
+ project_name TEXT NOT NULL,
474
+ task_title TEXT NOT NULL,
475
+ signature TEXT NOT NULL,
476
+ signature_hash TEXT NOT NULL,
477
+ tool_count INTEGER NOT NULL,
478
+ skill_id TEXT,
479
+ created_at TEXT NOT NULL
480
+ );
481
+
482
+ CREATE INDEX IF NOT EXISTS idx_trajectories_hash
483
+ ON trajectories(signature_hash);
484
+
485
+ CREATE INDEX IF NOT EXISTS idx_trajectories_agent
486
+ ON trajectories(agent_id);
487
+ `);
488
+ try {
489
+ await client.execute("ALTER TABLE trajectories ADD COLUMN skill_id TEXT");
490
+ } catch {
491
+ }
492
+ await client.executeMultiple(`
493
+ CREATE TABLE IF NOT EXISTS consolidations (
494
+ id TEXT PRIMARY KEY,
495
+ consolidated_memory_id TEXT NOT NULL,
496
+ source_memory_id TEXT NOT NULL,
497
+ created_at TEXT NOT NULL
498
+ );
499
+
500
+ CREATE INDEX IF NOT EXISTS idx_consolidations_source
501
+ ON consolidations(source_memory_id);
502
+ `);
503
+ await client.executeMultiple(`
504
+ CREATE TABLE IF NOT EXISTS audit_trail (
505
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
506
+ timestamp TEXT NOT NULL,
507
+ session_id TEXT NOT NULL,
508
+ agent_id TEXT NOT NULL,
509
+ tool TEXT NOT NULL,
510
+ input TEXT,
511
+ decision TEXT NOT NULL,
512
+ reason TEXT,
513
+ is_customer_facing INTEGER NOT NULL DEFAULT 0
514
+ );
515
+
516
+ CREATE INDEX IF NOT EXISTS idx_audit_trail_agent
517
+ ON audit_trail(agent_id, timestamp);
518
+
519
+ CREATE INDEX IF NOT EXISTS idx_audit_trail_session
520
+ ON audit_trail(session_id);
521
+ `);
522
+ try {
523
+ await client.execute({
524
+ sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
525
+ args: []
526
+ });
527
+ } catch {
528
+ }
529
+ try {
530
+ await client.execute({
531
+ sql: `ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5`,
532
+ args: []
533
+ });
534
+ } catch {
535
+ }
536
+ try {
537
+ await client.execute({
538
+ sql: `ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'`,
539
+ args: []
540
+ });
541
+ } catch {
542
+ }
543
+ try {
544
+ await client.execute({
545
+ sql: `ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7`,
546
+ args: []
547
+ });
548
+ } catch {
549
+ }
550
+ try {
551
+ await client.execute({
552
+ sql: `ALTER TABLE memories ADD COLUMN last_accessed TEXT`,
553
+ args: []
554
+ });
555
+ } catch {
556
+ }
557
+ try {
558
+ await client.execute({
559
+ sql: `UPDATE memories SET last_accessed = timestamp WHERE last_accessed IS NULL`,
560
+ args: []
561
+ });
562
+ } catch {
563
+ }
564
+ try {
565
+ await client.execute({
566
+ sql: `ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0`,
567
+ args: []
568
+ });
569
+ } catch {
570
+ }
571
+ try {
572
+ await client.execute({
573
+ sql: `ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0`,
574
+ args: []
575
+ });
576
+ } catch {
577
+ }
578
+ for (const col of [
579
+ "ALTER TABLE memories ADD COLUMN content_hash TEXT",
580
+ "ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT"
581
+ ]) {
582
+ try {
583
+ await client.execute(col);
584
+ } catch {
585
+ }
586
+ }
587
+ await client.executeMultiple(`
588
+ CREATE TABLE IF NOT EXISTS entities (
589
+ id TEXT PRIMARY KEY,
590
+ name TEXT NOT NULL,
591
+ type TEXT NOT NULL,
592
+ first_seen TEXT NOT NULL,
593
+ last_seen TEXT NOT NULL,
594
+ properties TEXT DEFAULT '{}',
595
+ UNIQUE(name, type)
596
+ );
597
+
598
+ CREATE TABLE IF NOT EXISTS relationships (
599
+ id TEXT PRIMARY KEY,
600
+ source_entity_id TEXT NOT NULL,
601
+ target_entity_id TEXT NOT NULL,
602
+ type TEXT NOT NULL,
603
+ weight REAL DEFAULT 1.0,
604
+ timestamp TEXT NOT NULL,
605
+ properties TEXT DEFAULT '{}',
606
+ UNIQUE(source_entity_id, target_entity_id, type)
607
+ );
608
+
609
+ CREATE TABLE IF NOT EXISTS entity_memories (
610
+ entity_id TEXT NOT NULL,
611
+ memory_id TEXT NOT NULL,
612
+ PRIMARY KEY (entity_id, memory_id)
613
+ );
614
+
615
+ CREATE TABLE IF NOT EXISTS relationship_memories (
616
+ relationship_id TEXT NOT NULL,
617
+ memory_id TEXT NOT NULL,
618
+ PRIMARY KEY (relationship_id, memory_id)
619
+ );
620
+
621
+ CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
622
+ CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type);
623
+ CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_entity_id);
624
+ CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_entity_id);
625
+
626
+ CREATE TABLE IF NOT EXISTS hyperedges (
627
+ id TEXT PRIMARY KEY,
628
+ label TEXT NOT NULL,
629
+ relation TEXT NOT NULL,
630
+ confidence REAL DEFAULT 1.0,
631
+ timestamp TEXT NOT NULL
632
+ );
633
+
634
+ CREATE TABLE IF NOT EXISTS hyperedge_nodes (
635
+ hyperedge_id TEXT NOT NULL,
636
+ entity_id TEXT NOT NULL,
637
+ PRIMARY KEY (hyperedge_id, entity_id)
638
+ );
639
+ `);
640
+ await client.executeMultiple(`
641
+ CREATE TABLE IF NOT EXISTS entity_aliases (
642
+ alias TEXT NOT NULL PRIMARY KEY,
643
+ canonical_entity_id TEXT NOT NULL
644
+ );
645
+ CREATE INDEX IF NOT EXISTS idx_entity_aliases_canonical ON entity_aliases(canonical_entity_id);
646
+ `);
647
+ for (const col of [
648
+ "ALTER TABLE relationships ADD COLUMN confidence REAL DEFAULT 1.0",
649
+ "ALTER TABLE relationships ADD COLUMN confidence_label TEXT DEFAULT 'extracted'"
650
+ ]) {
651
+ try {
652
+ await client.execute(col);
653
+ } catch {
654
+ }
655
+ }
656
+ try {
657
+ await client.execute(
658
+ `CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)`
659
+ );
660
+ } catch {
661
+ }
662
+ await client.executeMultiple(`
663
+ CREATE TABLE IF NOT EXISTS identity (
664
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
665
+ agent_id TEXT NOT NULL UNIQUE,
666
+ content_hash TEXT NOT NULL,
667
+ updated_at TEXT NOT NULL,
668
+ updated_by TEXT NOT NULL
669
+ );
670
+
671
+ CREATE INDEX IF NOT EXISTS idx_identity_agent ON identity(agent_id);
672
+ `);
673
+ await client.executeMultiple(`
674
+ CREATE TABLE IF NOT EXISTS chat_history (
675
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
676
+ session_id TEXT NOT NULL,
677
+ role TEXT NOT NULL,
678
+ content TEXT NOT NULL,
679
+ tool_name TEXT,
680
+ tool_id TEXT,
681
+ is_error INTEGER NOT NULL DEFAULT 0,
682
+ timestamp INTEGER NOT NULL
683
+ );
684
+
685
+ CREATE INDEX IF NOT EXISTS idx_chat_history_session
686
+ ON chat_history(session_id, id);
687
+ `);
688
+ await client.executeMultiple(`
689
+ CREATE TABLE IF NOT EXISTS workspaces (
690
+ id TEXT PRIMARY KEY,
691
+ slug TEXT NOT NULL UNIQUE,
692
+ name TEXT NOT NULL,
693
+ owner_agent_id TEXT,
694
+ created_at TEXT NOT NULL,
695
+ metadata TEXT
696
+ );
697
+
698
+ CREATE INDEX IF NOT EXISTS idx_workspaces_slug
699
+ ON workspaces(slug);
700
+ `);
701
+ await client.executeMultiple(`
702
+ CREATE TABLE IF NOT EXISTS documents (
703
+ id TEXT PRIMARY KEY,
704
+ workspace_id TEXT NOT NULL,
705
+ filename TEXT NOT NULL,
706
+ mime TEXT,
707
+ source_type TEXT,
708
+ user_id TEXT,
709
+ uploaded_at TEXT NOT NULL,
710
+ metadata TEXT,
711
+ FOREIGN KEY (workspace_id) REFERENCES workspaces(id)
712
+ );
713
+
714
+ CREATE INDEX IF NOT EXISTS idx_documents_workspace
715
+ ON documents(workspace_id);
716
+
717
+ CREATE INDEX IF NOT EXISTS idx_documents_user
718
+ ON documents(user_id);
719
+ `);
720
+ for (const column of [
721
+ "workspace_id TEXT",
722
+ "document_id TEXT",
723
+ "user_id TEXT",
724
+ "char_offset INTEGER",
725
+ "page_number INTEGER"
726
+ ]) {
727
+ try {
728
+ await client.execute({
729
+ sql: `ALTER TABLE memories ADD COLUMN ${column}`,
730
+ args: []
731
+ });
732
+ } catch {
733
+ }
734
+ }
735
+ for (const col of [
736
+ "ALTER TABLE memories ADD COLUMN source_path TEXT",
737
+ "ALTER TABLE memories ADD COLUMN source_type TEXT DEFAULT 'text'"
738
+ ]) {
739
+ try {
740
+ await client.execute(col);
741
+ } catch {
742
+ }
743
+ }
744
+ await client.executeMultiple(`
745
+ CREATE INDEX IF NOT EXISTS idx_memories_workspace
746
+ ON memories(workspace_id);
747
+
748
+ CREATE INDEX IF NOT EXISTS idx_memories_document
749
+ ON memories(document_id);
750
+
751
+ CREATE INDEX IF NOT EXISTS idx_memories_user
752
+ ON memories(user_id);
753
+ `);
754
+ await client.executeMultiple(`
755
+ CREATE TABLE IF NOT EXISTS session_kills (
756
+ id TEXT PRIMARY KEY,
757
+ session_name TEXT NOT NULL,
758
+ agent_id TEXT NOT NULL,
759
+ killed_at TIMESTAMP NOT NULL,
760
+ reason TEXT NOT NULL,
761
+ ticks_idle INTEGER,
762
+ estimated_tokens_saved INTEGER
763
+ );
764
+
765
+ CREATE INDEX IF NOT EXISTS idx_session_kills_killed_at
766
+ ON session_kills(killed_at);
767
+
768
+ CREATE INDEX IF NOT EXISTS idx_session_kills_agent
769
+ ON session_kills(agent_id);
770
+ `);
771
+ await client.execute(`
772
+ CREATE TABLE IF NOT EXISTS global_procedures (
773
+ id TEXT PRIMARY KEY,
774
+ title TEXT NOT NULL,
775
+ content TEXT NOT NULL,
776
+ priority TEXT NOT NULL DEFAULT 'p0',
777
+ domain TEXT,
778
+ active INTEGER NOT NULL DEFAULT 1,
779
+ created_at TEXT NOT NULL,
780
+ updated_at TEXT NOT NULL
781
+ )
782
+ `);
783
+ await client.executeMultiple(`
784
+ CREATE TABLE IF NOT EXISTS conversations (
785
+ id TEXT PRIMARY KEY,
786
+ platform TEXT NOT NULL,
787
+ external_id TEXT,
788
+ sender_id TEXT NOT NULL,
789
+ sender_name TEXT,
790
+ sender_phone TEXT,
791
+ sender_email TEXT,
792
+ recipient_id TEXT,
793
+ channel_id TEXT NOT NULL,
794
+ thread_id TEXT,
795
+ reply_to_id TEXT,
796
+ content_text TEXT,
797
+ content_media TEXT,
798
+ content_metadata TEXT,
799
+ agent_response TEXT,
800
+ agent_name TEXT,
801
+ timestamp TEXT NOT NULL,
802
+ ingested_at TEXT NOT NULL
803
+ );
804
+
805
+ CREATE INDEX IF NOT EXISTS idx_conversations_platform
806
+ ON conversations(platform);
807
+
808
+ CREATE INDEX IF NOT EXISTS idx_conversations_sender
809
+ ON conversations(sender_id);
810
+
811
+ CREATE INDEX IF NOT EXISTS idx_conversations_timestamp
812
+ ON conversations(timestamp);
813
+
814
+ CREATE INDEX IF NOT EXISTS idx_conversations_thread
815
+ ON conversations(thread_id);
816
+
817
+ CREATE INDEX IF NOT EXISTS idx_conversations_channel
818
+ ON conversations(channel_id);
819
+ `);
820
+ try {
821
+ await client.execute({
822
+ sql: `ALTER TABLE tasks ADD COLUMN budget_tokens INTEGER`,
823
+ args: []
824
+ });
825
+ } catch {
826
+ }
827
+ try {
828
+ await client.execute({
829
+ sql: `ALTER TABLE tasks ADD COLUMN budget_fallback_model TEXT`,
830
+ args: []
831
+ });
832
+ } catch {
833
+ }
834
+ try {
835
+ await client.execute({
836
+ sql: `ALTER TABLE tasks ADD COLUMN tokens_used INTEGER DEFAULT 0`,
837
+ args: []
838
+ });
839
+ } catch {
840
+ }
841
+ try {
842
+ await client.execute({
843
+ sql: `ALTER TABLE tasks ADD COLUMN tokens_warned_at INTEGER`,
844
+ args: []
845
+ });
846
+ } catch {
847
+ }
848
+ await client.executeMultiple(`
849
+ CREATE VIRTUAL TABLE IF NOT EXISTS conversations_fts USING fts5(
850
+ content_text,
851
+ sender_name,
852
+ agent_response,
853
+ content='conversations',
854
+ content_rowid='rowid'
855
+ );
856
+
857
+ CREATE TRIGGER IF NOT EXISTS conversations_fts_ai AFTER INSERT ON conversations BEGIN
858
+ INSERT INTO conversations_fts(rowid, content_text, sender_name, agent_response)
859
+ VALUES (new.rowid, new.content_text, new.sender_name, new.agent_response);
860
+ END;
861
+
862
+ CREATE TRIGGER IF NOT EXISTS conversations_fts_ad AFTER DELETE ON conversations BEGIN
863
+ INSERT INTO conversations_fts(conversations_fts, rowid, content_text, sender_name, agent_response)
864
+ VALUES('delete', old.rowid, old.content_text, old.sender_name, old.agent_response);
865
+ END;
866
+
867
+ CREATE TRIGGER IF NOT EXISTS conversations_fts_au AFTER UPDATE ON conversations BEGIN
868
+ INSERT INTO conversations_fts(conversations_fts, rowid, content_text, sender_name, agent_response)
869
+ VALUES('delete', old.rowid, old.content_text, old.sender_name, old.agent_response);
870
+ INSERT INTO conversations_fts(rowid, content_text, sender_name, agent_response)
871
+ VALUES (new.rowid, new.content_text, new.sender_name, new.agent_response);
872
+ END;
873
+ `);
874
+ try {
875
+ await client.execute({
876
+ sql: `ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3`,
877
+ args: []
878
+ });
879
+ } catch {
880
+ }
881
+ try {
882
+ await client.execute(
883
+ `CREATE INDEX IF NOT EXISTS idx_memories_tier ON memories(tier)`
884
+ );
885
+ } catch {
886
+ }
887
+ try {
888
+ await client.execute({
889
+ sql: `UPDATE memories SET tier = 1 WHERE tool_name = 'commit_to_long_term_memory' AND importance >= 8 AND tier = 3`,
890
+ args: []
891
+ });
892
+ await client.execute({
893
+ sql: `UPDATE memories SET tier = 2 WHERE tool_name IN ('store_memory', 'manual') AND importance >= 5 AND tier = 3`,
894
+ args: []
895
+ });
896
+ } catch {
897
+ }
898
+ try {
899
+ await client.execute({
900
+ sql: `ALTER TABLE memories ADD COLUMN supersedes_id TEXT`,
901
+ args: []
902
+ });
903
+ } catch {
904
+ }
905
+ try {
906
+ await client.execute(
907
+ `CREATE INDEX IF NOT EXISTS idx_memories_supersedes ON memories(supersedes_id) WHERE supersedes_id IS NOT NULL`
908
+ );
909
+ } catch {
910
+ }
911
+ for (const col of [
912
+ "ALTER TABLE tasks ADD COLUMN checkpoint TEXT",
913
+ "ALTER TABLE tasks ADD COLUMN checkpoint_count INTEGER DEFAULT 0"
914
+ ]) {
915
+ try {
916
+ await client.execute(col);
917
+ } catch {
918
+ }
919
+ }
920
+ }
921
+ async function disposeDatabase() {
922
+ if (_client) {
923
+ _client.close();
924
+ _client = null;
925
+ _resilientClient = null;
926
+ }
927
+ }
928
+ var _client, _resilientClient, initTurso, disposeTurso;
929
+ var init_database = __esm({
930
+ "src/lib/database.ts"() {
931
+ "use strict";
932
+ init_db_retry();
933
+ _client = null;
934
+ _resilientClient = null;
935
+ initTurso = initDatabase;
936
+ disposeTurso = disposeDatabase;
937
+ }
938
+ });
939
+
940
+ // src/lib/cloud-sync.ts
941
+ init_database();
942
+ import { readFileSync as readFileSync4, writeFileSync as writeFileSync2, existsSync as existsSync4, readdirSync, mkdirSync as mkdirSync2, appendFileSync, unlinkSync, openSync, closeSync } from "fs";
943
+ import crypto2 from "crypto";
944
+ import path4 from "path";
945
+ import { homedir } from "os";
23
946
 
24
947
  // src/lib/crypto.ts
25
948
  import crypto from "crypto";
@@ -70,15 +993,11 @@ function decompress(input) {
70
993
  return brotliDecompressSync(input);
71
994
  }
72
995
 
73
- // src/lib/plan-limits.ts
74
- import { readFileSync as readFileSync4, existsSync as existsSync4 } from "fs";
75
- import path4 from "path";
76
-
77
- // src/lib/employees.ts
78
- import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
79
- import { existsSync as existsSync2, symlinkSync, readlinkSync, readFileSync as readFileSync2 } from "fs";
80
- import { execSync } from "child_process";
996
+ // src/lib/license.ts
997
+ import { readFileSync as readFileSync2, writeFileSync, existsSync as existsSync2, mkdirSync } from "fs";
998
+ import { randomUUID } from "crypto";
81
999
  import path2 from "path";
1000
+ import { jwtVerify, importSPKI } from "jose";
82
1001
 
83
1002
  // src/lib/config.ts
84
1003
  import { readFile, writeFile, mkdir, chmod } from "fs/promises";
@@ -171,10 +1090,40 @@ var DEFAULT_CONFIG = {
171
1090
  }
172
1091
  };
173
1092
 
1093
+ // src/lib/license.ts
1094
+ var LICENSE_PATH = path2.join(EXE_AI_DIR, "license.key");
1095
+ var CACHE_PATH = path2.join(EXE_AI_DIR, "license-cache.json");
1096
+ var DEVICE_ID_PATH = path2.join(EXE_AI_DIR, "device-id");
1097
+ function loadDeviceId() {
1098
+ const deviceJsonPath = path2.join(EXE_AI_DIR, "device.json");
1099
+ try {
1100
+ if (existsSync2(deviceJsonPath)) {
1101
+ const data = JSON.parse(readFileSync2(deviceJsonPath, "utf8"));
1102
+ if (data.deviceId) return data.deviceId;
1103
+ }
1104
+ } catch {
1105
+ }
1106
+ try {
1107
+ if (existsSync2(DEVICE_ID_PATH)) {
1108
+ const id2 = readFileSync2(DEVICE_ID_PATH, "utf8").trim();
1109
+ if (id2) return id2;
1110
+ }
1111
+ } catch {
1112
+ }
1113
+ const id = randomUUID();
1114
+ mkdirSync(EXE_AI_DIR, { recursive: true });
1115
+ writeFileSync(DEVICE_ID_PATH, id, "utf8");
1116
+ return id;
1117
+ }
1118
+
174
1119
  // src/lib/employees.ts
175
- var EMPLOYEES_PATH = path2.join(EXE_AI_DIR, "exe-employees.json");
1120
+ import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
1121
+ import { existsSync as existsSync3, symlinkSync, readlinkSync, readFileSync as readFileSync3 } from "fs";
1122
+ import { execSync } from "child_process";
1123
+ import path3 from "path";
1124
+ var EMPLOYEES_PATH = path3.join(EXE_AI_DIR, "exe-employees.json");
176
1125
  async function loadEmployees(employeesPath = EMPLOYEES_PATH) {
177
- if (!existsSync2(employeesPath)) {
1126
+ if (!existsSync3(employeesPath)) {
178
1127
  return [];
179
1128
  }
180
1129
  const raw = await readFile2(employeesPath, "utf-8");
@@ -185,7 +1134,7 @@ async function loadEmployees(employeesPath = EMPLOYEES_PATH) {
185
1134
  }
186
1135
  }
187
1136
  async function saveEmployees(employees, employeesPath = EMPLOYEES_PATH) {
188
- await mkdir2(path2.dirname(employeesPath), { recursive: true });
1137
+ await mkdir2(path3.dirname(employeesPath), { recursive: true });
189
1138
  await writeFile2(employeesPath, JSON.stringify(employees, null, 2) + "\n", "utf-8");
190
1139
  }
191
1140
  function findExeBin() {
@@ -204,7 +1153,7 @@ function registerBinSymlinks(name) {
204
1153
  errors.push("Could not find 'exe-os' in PATH");
205
1154
  return { created, skipped, errors };
206
1155
  }
207
- const binDir = path2.dirname(exeBinPath);
1156
+ const binDir = path3.dirname(exeBinPath);
208
1157
  let target;
209
1158
  try {
210
1159
  target = readlinkSync(exeBinPath);
@@ -214,8 +1163,8 @@ function registerBinSymlinks(name) {
214
1163
  }
215
1164
  for (const suffix of ["", "-opencode"]) {
216
1165
  const linkName = `${name}${suffix}`;
217
- const linkPath = path2.join(binDir, linkName);
218
- if (existsSync2(linkPath)) {
1166
+ const linkPath = path3.join(binDir, linkName);
1167
+ if (existsSync3(linkPath)) {
219
1168
  skipped.push(linkName);
220
1169
  continue;
221
1170
  }
@@ -229,221 +1178,10 @@ function registerBinSymlinks(name) {
229
1178
  return { created, skipped, errors };
230
1179
  }
231
1180
 
232
- // src/lib/license.ts
233
- import { readFileSync as readFileSync3, writeFileSync, existsSync as existsSync3, mkdirSync } from "fs";
234
- import { randomUUID } from "crypto";
235
- import path3 from "path";
236
- import { jwtVerify, importSPKI } from "jose";
237
- var LICENSE_PATH = path3.join(EXE_AI_DIR, "license.key");
238
- var CACHE_PATH = path3.join(EXE_AI_DIR, "license-cache.json");
239
- var DEVICE_ID_PATH = path3.join(EXE_AI_DIR, "device-id");
240
- var API_BASE = "https://askexe.com/cloud";
241
- var RETRY_DELAY_MS = 500;
242
- async function fetchRetry(url, init) {
243
- try {
244
- return await fetch(url, init);
245
- } catch {
246
- await new Promise((r) => setTimeout(r, RETRY_DELAY_MS));
247
- return fetch(url, { ...init, signal: AbortSignal.timeout(1e4) });
248
- }
249
- }
250
- var LICENSE_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
251
- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEeHztAMOpR/ZMh+rWuOASjEZ54CGY
252
- 4uj+UqeKCcvtgNHKmOK278HJaJcANe9xAeji8AFYu27q3WtzCi04pHudow==
253
- -----END PUBLIC KEY-----`;
254
- var LICENSE_JWT_ALG = "ES256";
255
- var PLAN_LIMITS = {
256
- free: { devices: 1, employees: 1, memories: 5e3 },
257
- pro: { devices: 2, employees: 5, memories: 1e5 },
258
- team: { devices: 10, employees: 20, memories: 1e6 },
259
- agency: { devices: 50, employees: 100, memories: 1e7 },
260
- enterprise: { devices: -1, employees: -1, memories: -1 }
261
- };
262
- var FREE_LICENSE = {
263
- valid: true,
264
- plan: "free",
265
- email: "",
266
- expiresAt: null,
267
- deviceLimit: 1,
268
- employeeLimit: 1,
269
- memoryLimit: 5e3
270
- };
271
- function loadDeviceId() {
272
- const deviceJsonPath = path3.join(EXE_AI_DIR, "device.json");
273
- try {
274
- if (existsSync3(deviceJsonPath)) {
275
- const data = JSON.parse(readFileSync3(deviceJsonPath, "utf8"));
276
- if (data.deviceId) return data.deviceId;
277
- }
278
- } catch {
279
- }
280
- try {
281
- if (existsSync3(DEVICE_ID_PATH)) {
282
- const id2 = readFileSync3(DEVICE_ID_PATH, "utf8").trim();
283
- if (id2) return id2;
284
- }
285
- } catch {
286
- }
287
- const id = randomUUID();
288
- mkdirSync(EXE_AI_DIR, { recursive: true });
289
- writeFileSync(DEVICE_ID_PATH, id, "utf8");
290
- return id;
291
- }
292
- function loadLicense() {
293
- try {
294
- if (!existsSync3(LICENSE_PATH)) return null;
295
- return readFileSync3(LICENSE_PATH, "utf8").trim();
296
- } catch {
297
- return null;
298
- }
299
- }
300
- function saveLicense(apiKey) {
301
- mkdirSync(EXE_AI_DIR, { recursive: true });
302
- writeFileSync(LICENSE_PATH, apiKey.trim(), { encoding: "utf8", mode: 384 });
303
- }
304
- async function verifyLicenseJwt(token) {
305
- try {
306
- const key = await importSPKI(LICENSE_PUBLIC_KEY_PEM, LICENSE_JWT_ALG);
307
- const { payload } = await jwtVerify(token, key, {
308
- algorithms: [LICENSE_JWT_ALG]
309
- });
310
- const plan = payload.plan ?? "free";
311
- const email = payload.sub ?? "";
312
- const limits = PLAN_LIMITS[plan] ?? PLAN_LIMITS.free;
313
- return {
314
- valid: true,
315
- plan,
316
- email,
317
- expiresAt: payload.exp ? new Date(payload.exp * 1e3).toISOString() : null,
318
- deviceLimit: limits.devices,
319
- employeeLimit: limits.employees,
320
- memoryLimit: limits.memories
321
- };
322
- } catch {
323
- return null;
324
- }
325
- }
326
- async function getCachedLicense() {
327
- try {
328
- if (!existsSync3(CACHE_PATH)) return null;
329
- const raw = JSON.parse(readFileSync3(CACHE_PATH, "utf8"));
330
- if (!raw.token || typeof raw.token !== "string") return null;
331
- return await verifyLicenseJwt(raw.token);
332
- } catch {
333
- return null;
334
- }
335
- }
336
- function cacheResponse(token) {
337
- try {
338
- writeFileSync(CACHE_PATH, JSON.stringify({ token }), "utf8");
339
- } catch {
340
- }
341
- }
342
- async function validateLicense(apiKey, deviceId) {
343
- const did = deviceId ?? loadDeviceId();
344
- try {
345
- const res = await fetchRetry(`${API_BASE}/auth/activate`, {
346
- method: "POST",
347
- headers: { "Content-Type": "application/json" },
348
- body: JSON.stringify({ apiKey, deviceId: did }),
349
- signal: AbortSignal.timeout(1e4)
350
- });
351
- if (res.ok) {
352
- const data = await res.json();
353
- if (data.error === "device_limit_exceeded") {
354
- const cached2 = await getCachedLicense();
355
- if (cached2) return cached2;
356
- return { ...FREE_LICENSE, valid: false, plan: "free" };
357
- }
358
- if (data.token) {
359
- cacheResponse(data.token);
360
- const verified = await verifyLicenseJwt(data.token);
361
- if (verified) return verified;
362
- }
363
- const limits = PLAN_LIMITS[data.plan] ?? PLAN_LIMITS.free;
364
- return {
365
- valid: data.valid,
366
- plan: data.plan,
367
- email: data.email,
368
- expiresAt: data.expiresAt,
369
- deviceLimit: limits.devices,
370
- employeeLimit: limits.employees,
371
- memoryLimit: limits.memories
372
- };
373
- }
374
- const cached = await getCachedLicense();
375
- if (cached) return cached;
376
- return { ...FREE_LICENSE, valid: false, plan: "free" };
377
- } catch {
378
- const cached = await getCachedLicense();
379
- if (cached) return cached;
380
- return { ...FREE_LICENSE, valid: false, error: "offline" };
381
- }
382
- }
383
- var CACHE_MAX_AGE_MS = 36e5;
384
- function getCacheAgeMs() {
385
- try {
386
- const { statSync } = __require("fs");
387
- const s = statSync(CACHE_PATH);
388
- return Date.now() - s.mtimeMs;
389
- } catch {
390
- return Infinity;
391
- }
392
- }
393
- async function checkLicense() {
394
- let key = loadLicense();
395
- if (!key) {
396
- try {
397
- const configPath = path3.join(EXE_AI_DIR, "config.json");
398
- if (existsSync3(configPath)) {
399
- const raw = JSON.parse(readFileSync3(configPath, "utf8"));
400
- const cloud = raw.cloud;
401
- if (cloud?.apiKey) {
402
- key = cloud.apiKey;
403
- saveLicense(key);
404
- }
405
- }
406
- } catch {
407
- }
408
- }
409
- if (!key) return FREE_LICENSE;
410
- const cached = await getCachedLicense();
411
- if (cached && getCacheAgeMs() < CACHE_MAX_AGE_MS) return cached;
412
- const deviceId = loadDeviceId();
413
- return validateLicense(key, deviceId);
414
- }
415
- function isFeatureAllowed(license, feature) {
416
- switch (feature) {
417
- case "cloud_sync":
418
- case "external_agents":
419
- case "wiki":
420
- return license.plan !== "free";
421
- case "unlimited_employees":
422
- return license.plan === "team" || license.plan === "agency" || license.plan === "enterprise";
423
- }
424
- }
425
-
426
- // src/lib/plan-limits.ts
427
- var PlanLimitError = class extends Error {
428
- constructor(message) {
429
- super(message);
430
- this.name = "PlanLimitError";
431
- }
432
- };
433
- var CACHE_PATH2 = path4.join(EXE_AI_DIR, "license-cache.json");
434
- async function assertFeature(feature) {
435
- const license = await checkLicense();
436
- if (!isFeatureAllowed(license, feature)) {
437
- throw new PlanLimitError(
438
- `Feature "${feature}" requires a paid plan. Current plan: ${license.plan}. Upgrade at https://askexe.com.`
439
- );
440
- }
441
- }
442
-
443
1181
  // src/lib/cloud-sync.ts
444
1182
  function logError(msg) {
445
1183
  try {
446
- const logPath = path5.join(homedir(), ".exe-os", "workers.log");
1184
+ const logPath = path4.join(homedir(), ".exe-os", "workers.log");
447
1185
  appendFileSync(logPath, `${(/* @__PURE__ */ new Date()).toISOString()} ${msg}
448
1186
  `);
449
1187
  } catch {
@@ -452,7 +1190,7 @@ function logError(msg) {
452
1190
  var LOCALHOST_PATTERNS = /^(localhost|127\.0\.0\.1|\[::1\])$/i;
453
1191
  var FETCH_TIMEOUT_MS = 3e4;
454
1192
  var PUSH_BATCH_SIZE = 5e3;
455
- var ROSTER_LOCK_PATH = path5.join(EXE_AI_DIR, "roster-merge.lock");
1193
+ var ROSTER_LOCK_PATH = path4.join(EXE_AI_DIR, "roster-merge.lock");
456
1194
  var LOCK_STALE_MS = 3e4;
457
1195
  async function withRosterLock(fn) {
458
1196
  try {
@@ -462,7 +1200,7 @@ async function withRosterLock(fn) {
462
1200
  } catch (err) {
463
1201
  if (err.code === "EEXIST") {
464
1202
  try {
465
- const ts = parseInt(readFileSync5(ROSTER_LOCK_PATH, "utf-8"), 10);
1203
+ const ts = parseInt(readFileSync4(ROSTER_LOCK_PATH, "utf-8"), 10);
466
1204
  if (Date.now() - ts < LOCK_STALE_MS) {
467
1205
  throw new Error("Roster merge already in progress \u2014 another sync is running");
468
1206
  }
@@ -488,22 +1226,22 @@ async function withRosterLock(fn) {
488
1226
  }
489
1227
  }
490
1228
  async function fetchWithRetry(url, init) {
491
- const MAX_RETRIES = 3;
492
- const BASE_DELAY_MS = 200;
1229
+ const MAX_RETRIES2 = 3;
1230
+ const BASE_DELAY_MS2 = 200;
493
1231
  let lastError;
494
- for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
1232
+ for (let attempt = 0; attempt <= MAX_RETRIES2; attempt++) {
495
1233
  try {
496
1234
  const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS);
497
1235
  const resp = await fetch(url, { ...init, signal });
498
- if (resp && resp.status >= 500 && attempt < MAX_RETRIES) {
499
- await new Promise((r) => setTimeout(r, BASE_DELAY_MS * Math.pow(2, attempt)));
1236
+ if (resp && resp.status >= 500 && attempt < MAX_RETRIES2) {
1237
+ await new Promise((r) => setTimeout(r, BASE_DELAY_MS2 * Math.pow(2, attempt)));
500
1238
  continue;
501
1239
  }
502
1240
  return resp;
503
1241
  } catch (err) {
504
1242
  lastError = err;
505
- if (attempt === MAX_RETRIES) throw err;
506
- await new Promise((r) => setTimeout(r, BASE_DELAY_MS * Math.pow(2, attempt)));
1243
+ if (attempt === MAX_RETRIES2) throw err;
1244
+ await new Promise((r) => setTimeout(r, BASE_DELAY_MS2 * Math.pow(2, attempt)));
507
1245
  }
508
1246
  }
509
1247
  throw lastError;
@@ -589,16 +1327,25 @@ async function cloudPull(sinceVersion, config) {
589
1327
  }
590
1328
  }
591
1329
  async function cloudSync(config) {
592
- await assertFeature("cloud_sync");
593
1330
  let client;
594
1331
  try {
595
1332
  client = getClient();
596
1333
  } catch {
597
1334
  throw new Error("[cloud-sync] Database not initialized. Call initStore() before cloudSync().");
598
1335
  }
599
- const pullMeta = await client.execute(
600
- "SELECT value FROM sync_meta WHERE key = 'last_cloud_pull_version'"
601
- );
1336
+ let pullMeta;
1337
+ try {
1338
+ pullMeta = await client.execute(
1339
+ "SELECT value FROM sync_meta WHERE key = 'last_cloud_pull_version'"
1340
+ );
1341
+ } catch (e) {
1342
+ logError(`[cloud-sync] sync_meta read failed (${e instanceof Error ? e.message : String(e)}), attempting ensureSchema`);
1343
+ const { ensureSchema: ensureSchema2 } = await Promise.resolve().then(() => (init_database(), database_exports));
1344
+ await ensureSchema2();
1345
+ pullMeta = await client.execute(
1346
+ "SELECT value FROM sync_meta WHERE key = 'last_cloud_pull_version'"
1347
+ );
1348
+ }
602
1349
  const lastPullVersion = pullMeta.rows.length > 0 ? Number(pullMeta.rows[0].value) : 0;
603
1350
  const pullResult = await cloudPull(lastPullVersion, config);
604
1351
  let pulled = 0;
@@ -757,12 +1504,12 @@ async function cloudSync(config) {
757
1504
  documents: documentsResult
758
1505
  };
759
1506
  }
760
- var ROSTER_DELETIONS_PATH = path5.join(EXE_AI_DIR, "roster-deletions.json");
1507
+ var ROSTER_DELETIONS_PATH = path4.join(EXE_AI_DIR, "roster-deletions.json");
761
1508
  function recordRosterDeletion(name) {
762
1509
  let deletions = [];
763
1510
  try {
764
- if (existsSync5(ROSTER_DELETIONS_PATH)) {
765
- deletions = JSON.parse(readFileSync5(ROSTER_DELETIONS_PATH, "utf-8"));
1511
+ if (existsSync4(ROSTER_DELETIONS_PATH)) {
1512
+ deletions = JSON.parse(readFileSync4(ROSTER_DELETIONS_PATH, "utf-8"));
766
1513
  }
767
1514
  } catch {
768
1515
  }
@@ -771,8 +1518,8 @@ function recordRosterDeletion(name) {
771
1518
  }
772
1519
  function consumeRosterDeletions() {
773
1520
  try {
774
- if (!existsSync5(ROSTER_DELETIONS_PATH)) return [];
775
- const deletions = JSON.parse(readFileSync5(ROSTER_DELETIONS_PATH, "utf-8"));
1521
+ if (!existsSync4(ROSTER_DELETIONS_PATH)) return [];
1522
+ const deletions = JSON.parse(readFileSync4(ROSTER_DELETIONS_PATH, "utf-8"));
776
1523
  writeFileSync2(ROSTER_DELETIONS_PATH, "[]");
777
1524
  return deletions;
778
1525
  } catch {
@@ -780,29 +1527,29 @@ function consumeRosterDeletions() {
780
1527
  }
781
1528
  }
782
1529
  function buildRosterBlob(paths) {
783
- const rosterPath = paths?.rosterPath ?? path5.join(EXE_AI_DIR, "exe-employees.json");
784
- const identityDir = paths?.identityDir ?? path5.join(EXE_AI_DIR, "identity");
785
- const configPath = paths?.configPath ?? path5.join(EXE_AI_DIR, "config.json");
1530
+ const rosterPath = paths?.rosterPath ?? path4.join(EXE_AI_DIR, "exe-employees.json");
1531
+ const identityDir = paths?.identityDir ?? path4.join(EXE_AI_DIR, "identity");
1532
+ const configPath = paths?.configPath ?? path4.join(EXE_AI_DIR, "config.json");
786
1533
  let roster = [];
787
- if (existsSync5(rosterPath)) {
1534
+ if (existsSync4(rosterPath)) {
788
1535
  try {
789
- roster = JSON.parse(readFileSync5(rosterPath, "utf-8"));
1536
+ roster = JSON.parse(readFileSync4(rosterPath, "utf-8"));
790
1537
  } catch {
791
1538
  }
792
1539
  }
793
1540
  const identities = {};
794
- if (existsSync5(identityDir)) {
1541
+ if (existsSync4(identityDir)) {
795
1542
  for (const file of readdirSync(identityDir).filter((f) => f.endsWith(".md"))) {
796
1543
  try {
797
- identities[file] = readFileSync5(path5.join(identityDir, file), "utf-8");
1544
+ identities[file] = readFileSync4(path4.join(identityDir, file), "utf-8");
798
1545
  } catch {
799
1546
  }
800
1547
  }
801
1548
  }
802
1549
  let config;
803
- if (existsSync5(configPath)) {
1550
+ if (existsSync4(configPath)) {
804
1551
  try {
805
- config = JSON.parse(readFileSync5(configPath, "utf-8"));
1552
+ config = JSON.parse(readFileSync4(configPath, "utf-8"));
806
1553
  } catch {
807
1554
  }
808
1555
  }
@@ -878,23 +1625,23 @@ async function cloudPullRoster(config) {
878
1625
  }
879
1626
  }
880
1627
  function mergeConfig(remoteConfig, configPath) {
881
- const cfgPath = configPath ?? path5.join(EXE_AI_DIR, "config.json");
1628
+ const cfgPath = configPath ?? path4.join(EXE_AI_DIR, "config.json");
882
1629
  let local = {};
883
- if (existsSync5(cfgPath)) {
1630
+ if (existsSync4(cfgPath)) {
884
1631
  try {
885
- local = JSON.parse(readFileSync5(cfgPath, "utf-8"));
1632
+ local = JSON.parse(readFileSync4(cfgPath, "utf-8"));
886
1633
  } catch {
887
1634
  }
888
1635
  }
889
1636
  const merged = { ...remoteConfig, ...local };
890
- const dir = path5.dirname(cfgPath);
891
- if (!existsSync5(dir)) mkdirSync2(dir, { recursive: true });
1637
+ const dir = path4.dirname(cfgPath);
1638
+ if (!existsSync4(dir)) mkdirSync2(dir, { recursive: true });
892
1639
  writeFileSync2(cfgPath, JSON.stringify(merged, null, 2), "utf-8");
893
1640
  }
894
1641
  async function mergeRosterFromRemote(remote, paths) {
895
1642
  return withRosterLock(async () => {
896
1643
  const rosterPath = paths?.rosterPath ?? void 0;
897
- const identityDir = paths?.identityDir ?? path5.join(EXE_AI_DIR, "identity");
1644
+ const identityDir = paths?.identityDir ?? path4.join(EXE_AI_DIR, "identity");
898
1645
  const localEmployees = await loadEmployees(rosterPath);
899
1646
  const localNames = new Set(localEmployees.map((e) => e.name));
900
1647
  let added = 0;
@@ -904,9 +1651,9 @@ async function mergeRosterFromRemote(remote, paths) {
904
1651
  localNames.add(remoteEmp.name);
905
1652
  added++;
906
1653
  if (remote.identities[`${remoteEmp.name}.md`]) {
907
- if (!existsSync5(identityDir)) mkdirSync2(identityDir, { recursive: true });
908
- const idPath = path5.join(identityDir, `${remoteEmp.name}.md`);
909
- if (!existsSync5(idPath)) {
1654
+ if (!existsSync4(identityDir)) mkdirSync2(identityDir, { recursive: true });
1655
+ const idPath = path4.join(identityDir, `${remoteEmp.name}.md`);
1656
+ if (!existsSync4(idPath)) {
910
1657
  writeFileSync2(idPath, remote.identities[`${remoteEmp.name}.md`], "utf-8");
911
1658
  }
912
1659
  }