@askexenow/exe-os 0.8.45 → 0.8.47

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