@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.
@@ -323,26 +323,931 @@ var init_crypto = __esm({
323
323
  });
324
324
 
325
325
  // src/lib/db-retry.ts
326
+ function isBusyError(err) {
327
+ if (err instanceof Error) {
328
+ const msg = err.message.toLowerCase();
329
+ return msg.includes("sqlite_busy") || msg.includes("database is locked");
330
+ }
331
+ return false;
332
+ }
333
+ function delay(ms) {
334
+ return new Promise((resolve) => setTimeout(resolve, ms));
335
+ }
336
+ async function retryOnBusy(fn, label) {
337
+ let lastError;
338
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
339
+ try {
340
+ return await fn();
341
+ } catch (err) {
342
+ lastError = err;
343
+ if (!isBusyError(err) || attempt === MAX_RETRIES) {
344
+ throw err;
345
+ }
346
+ const backoff = BASE_DELAY_MS * Math.pow(2, attempt);
347
+ const jitter = Math.floor(Math.random() * MAX_JITTER_MS);
348
+ process.stderr.write(
349
+ `[exe-os] SQLITE_BUSY ${label} retry ${attempt + 1}/${MAX_RETRIES} \u2014 waiting ${backoff + jitter}ms
350
+ `
351
+ );
352
+ await delay(backoff + jitter);
353
+ }
354
+ }
355
+ throw lastError;
356
+ }
357
+ function wrapWithRetry(client) {
358
+ return new Proxy(client, {
359
+ get(target, prop, receiver) {
360
+ if (prop === "execute") {
361
+ return (sql) => retryOnBusy(() => target.execute(sql), "execute");
362
+ }
363
+ if (prop === "batch") {
364
+ return (stmts) => retryOnBusy(() => target.batch(stmts), "batch");
365
+ }
366
+ return Reflect.get(target, prop, receiver);
367
+ }
368
+ });
369
+ }
370
+ var MAX_RETRIES, BASE_DELAY_MS, MAX_JITTER_MS;
326
371
  var init_db_retry = __esm({
327
372
  "src/lib/db-retry.ts"() {
328
373
  "use strict";
374
+ MAX_RETRIES = 3;
375
+ BASE_DELAY_MS = 200;
376
+ MAX_JITTER_MS = 300;
329
377
  }
330
378
  });
331
379
 
332
380
  // src/lib/database.ts
381
+ var database_exports = {};
382
+ __export(database_exports, {
383
+ disposeDatabase: () => disposeDatabase,
384
+ disposeTurso: () => disposeTurso,
385
+ ensureSchema: () => ensureSchema,
386
+ getClient: () => getClient,
387
+ getRawClient: () => getRawClient,
388
+ initDatabase: () => initDatabase,
389
+ initTurso: () => initTurso,
390
+ isInitialized: () => isInitialized
391
+ });
333
392
  import { createClient } from "@libsql/client";
393
+ async function initDatabase(config) {
394
+ if (_client) {
395
+ _client.close();
396
+ _client = null;
397
+ _resilientClient = null;
398
+ }
399
+ const opts = {
400
+ url: `file:${config.dbPath}`
401
+ };
402
+ if (config.encryptionKey) {
403
+ opts.encryptionKey = config.encryptionKey;
404
+ }
405
+ _client = createClient(opts);
406
+ _resilientClient = wrapWithRetry(_client);
407
+ }
408
+ function isInitialized() {
409
+ return _client !== null;
410
+ }
334
411
  function getClient() {
335
412
  if (!_resilientClient) {
336
413
  throw new Error("Database client not initialized. Call initDatabase() first.");
337
414
  }
338
415
  return _resilientClient;
339
416
  }
340
- var _resilientClient;
417
+ function getRawClient() {
418
+ if (!_client) {
419
+ throw new Error("Database client not initialized. Call initDatabase() first.");
420
+ }
421
+ return _client;
422
+ }
423
+ async function ensureSchema() {
424
+ const client = getRawClient();
425
+ await client.execute("PRAGMA journal_mode = WAL");
426
+ await client.execute("PRAGMA busy_timeout = 30000");
427
+ await client.execute("PRAGMA wal_autocheckpoint = 1000");
428
+ try {
429
+ await client.execute("PRAGMA libsql_vector_search_ef = 128");
430
+ } catch {
431
+ }
432
+ await client.executeMultiple(`
433
+ CREATE TABLE IF NOT EXISTS memories (
434
+ id TEXT PRIMARY KEY,
435
+ agent_id TEXT NOT NULL,
436
+ agent_role TEXT NOT NULL,
437
+ session_id TEXT NOT NULL,
438
+ timestamp TEXT NOT NULL,
439
+ tool_name TEXT NOT NULL,
440
+ project_name TEXT NOT NULL,
441
+ has_error INTEGER NOT NULL DEFAULT 0,
442
+ raw_text TEXT NOT NULL,
443
+ vector F32_BLOB(1024),
444
+ version INTEGER NOT NULL DEFAULT 0
445
+ );
446
+
447
+ CREATE INDEX IF NOT EXISTS idx_memories_agent
448
+ ON memories(agent_id);
449
+
450
+ CREATE INDEX IF NOT EXISTS idx_memories_timestamp
451
+ ON memories(timestamp);
452
+
453
+ CREATE INDEX IF NOT EXISTS idx_memories_session
454
+ ON memories(session_id);
455
+
456
+ CREATE INDEX IF NOT EXISTS idx_memories_project
457
+ ON memories(project_name);
458
+
459
+ CREATE INDEX IF NOT EXISTS idx_memories_tool
460
+ ON memories(tool_name);
461
+
462
+ CREATE INDEX IF NOT EXISTS idx_memories_version
463
+ ON memories(version);
464
+
465
+ CREATE INDEX IF NOT EXISTS idx_memories_agent_project
466
+ ON memories(agent_id, project_name);
467
+ `);
468
+ await client.executeMultiple(`
469
+ CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
470
+ raw_text,
471
+ content='memories',
472
+ content_rowid='rowid'
473
+ );
474
+
475
+ CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
476
+ INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
477
+ END;
478
+
479
+ CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
480
+ INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
481
+ END;
482
+
483
+ CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
484
+ INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
485
+ INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
486
+ END;
487
+ `);
488
+ await client.executeMultiple(`
489
+ CREATE TABLE IF NOT EXISTS sync_meta (
490
+ key TEXT PRIMARY KEY,
491
+ value TEXT NOT NULL
492
+ );
493
+ `);
494
+ await client.executeMultiple(`
495
+ CREATE TABLE IF NOT EXISTS tasks (
496
+ id TEXT PRIMARY KEY,
497
+ title TEXT NOT NULL,
498
+ assigned_to TEXT NOT NULL,
499
+ assigned_by TEXT NOT NULL,
500
+ project_name TEXT NOT NULL,
501
+ priority TEXT NOT NULL DEFAULT 'p1',
502
+ status TEXT NOT NULL DEFAULT 'open',
503
+ task_file TEXT,
504
+ created_at TEXT NOT NULL,
505
+ updated_at TEXT NOT NULL
506
+ );
507
+
508
+ CREATE INDEX IF NOT EXISTS idx_tasks_assignee_status
509
+ ON tasks(assigned_to, status);
510
+ `);
511
+ await client.executeMultiple(`
512
+ CREATE TABLE IF NOT EXISTS behaviors (
513
+ id TEXT PRIMARY KEY,
514
+ agent_id TEXT NOT NULL,
515
+ project_name TEXT,
516
+ domain TEXT,
517
+ content TEXT NOT NULL,
518
+ active INTEGER NOT NULL DEFAULT 1,
519
+ created_at TEXT NOT NULL,
520
+ updated_at TEXT NOT NULL
521
+ );
522
+
523
+ CREATE INDEX IF NOT EXISTS idx_behaviors_agent
524
+ ON behaviors(agent_id, active);
525
+ `);
526
+ try {
527
+ const existing = await client.execute({
528
+ sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = 'exe'",
529
+ args: []
530
+ });
531
+ if (Number(existing.rows[0]?.cnt) === 0) {
532
+ await client.executeMultiple(`
533
+ INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
534
+ VALUES
535
+ (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');
536
+ INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
537
+ VALUES
538
+ (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');
539
+ INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
540
+ VALUES
541
+ (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');
542
+ `);
543
+ }
544
+ } catch {
545
+ }
546
+ try {
547
+ await client.execute({
548
+ sql: `ALTER TABLE behaviors ADD COLUMN priority TEXT DEFAULT 'p1'`,
549
+ args: []
550
+ });
551
+ } catch {
552
+ }
553
+ try {
554
+ await client.execute({
555
+ sql: `ALTER TABLE tasks ADD COLUMN blocked_by TEXT`,
556
+ args: []
557
+ });
558
+ } catch {
559
+ }
560
+ try {
561
+ await client.execute({
562
+ sql: `ALTER TABLE tasks ADD COLUMN parent_task_id TEXT`,
563
+ args: []
564
+ });
565
+ } catch {
566
+ }
567
+ try {
568
+ await client.execute({
569
+ sql: `CREATE INDEX IF NOT EXISTS idx_tasks_parent_task_id
570
+ ON tasks(parent_task_id)
571
+ WHERE parent_task_id IS NOT NULL`,
572
+ args: []
573
+ });
574
+ } catch {
575
+ }
576
+ try {
577
+ await client.execute({
578
+ sql: `UPDATE tasks SET status = 'done' WHERE status = 'completed'`,
579
+ args: []
580
+ });
581
+ } catch {
582
+ }
583
+ try {
584
+ await client.execute({
585
+ sql: `ALTER TABLE tasks ADD COLUMN reviewer TEXT`,
586
+ args: []
587
+ });
588
+ } catch {
589
+ }
590
+ try {
591
+ await client.execute({
592
+ sql: `ALTER TABLE tasks ADD COLUMN context TEXT`,
593
+ args: []
594
+ });
595
+ } catch {
596
+ }
597
+ try {
598
+ await client.execute({
599
+ sql: `ALTER TABLE tasks ADD COLUMN result TEXT`,
600
+ args: []
601
+ });
602
+ } catch {
603
+ }
604
+ try {
605
+ await client.execute({
606
+ sql: `ALTER TABLE tasks ADD COLUMN assigned_tmux TEXT`,
607
+ args: []
608
+ });
609
+ } catch {
610
+ }
611
+ try {
612
+ await client.execute({
613
+ sql: `ALTER TABLE tasks ADD COLUMN checkpoint TEXT`,
614
+ args: []
615
+ });
616
+ } catch {
617
+ }
618
+ try {
619
+ await client.execute({
620
+ sql: `ALTER TABLE tasks ADD COLUMN checkpoint_count INTEGER NOT NULL DEFAULT 0`,
621
+ args: []
622
+ });
623
+ } catch {
624
+ }
625
+ try {
626
+ await client.execute({
627
+ sql: `ALTER TABLE tasks ADD COLUMN complexity TEXT NOT NULL DEFAULT 'standard'`,
628
+ args: []
629
+ });
630
+ } catch {
631
+ }
632
+ try {
633
+ await client.execute({
634
+ sql: `ALTER TABLE tasks ADD COLUMN session_scope TEXT`,
635
+ args: []
636
+ });
637
+ } catch {
638
+ }
639
+ try {
640
+ await client.execute({
641
+ sql: `ALTER TABLE memories ADD COLUMN task_id TEXT`,
642
+ args: []
643
+ });
644
+ } catch {
645
+ }
646
+ try {
647
+ await client.execute({
648
+ sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
649
+ args: []
650
+ });
651
+ } catch {
652
+ }
653
+ try {
654
+ await client.execute({
655
+ sql: `ALTER TABLE memories ADD COLUMN author_device_id TEXT`,
656
+ args: []
657
+ });
658
+ } catch {
659
+ }
660
+ try {
661
+ await client.execute({
662
+ sql: `ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'`,
663
+ args: []
664
+ });
665
+ } catch {
666
+ }
667
+ await client.executeMultiple(`
668
+ CREATE TABLE IF NOT EXISTS consolidations (
669
+ id TEXT PRIMARY KEY,
670
+ consolidated_memory_id TEXT NOT NULL,
671
+ source_memory_id TEXT NOT NULL,
672
+ created_at TEXT NOT NULL
673
+ );
674
+
675
+ CREATE INDEX IF NOT EXISTS idx_consolidations_source
676
+ ON consolidations(source_memory_id);
677
+
678
+ CREATE INDEX IF NOT EXISTS idx_consolidations_consolidated
679
+ ON consolidations(consolidated_memory_id);
680
+ `);
681
+ await client.executeMultiple(`
682
+ CREATE TABLE IF NOT EXISTS reminders (
683
+ id TEXT PRIMARY KEY,
684
+ text TEXT NOT NULL,
685
+ created_at TEXT NOT NULL,
686
+ due_date TEXT,
687
+ completed_at TEXT
688
+ );
689
+ `);
690
+ await client.executeMultiple(`
691
+ CREATE TABLE IF NOT EXISTS notifications (
692
+ id TEXT PRIMARY KEY,
693
+ agent_id TEXT NOT NULL,
694
+ agent_role TEXT NOT NULL,
695
+ event TEXT NOT NULL,
696
+ project TEXT NOT NULL,
697
+ summary TEXT NOT NULL,
698
+ task_file TEXT,
699
+ read INTEGER NOT NULL DEFAULT 0,
700
+ created_at TEXT NOT NULL
701
+ );
702
+
703
+ CREATE INDEX IF NOT EXISTS idx_notifications_read
704
+ ON notifications(read);
705
+
706
+ CREATE INDEX IF NOT EXISTS idx_notifications_agent
707
+ ON notifications(agent_id);
708
+
709
+ CREATE INDEX IF NOT EXISTS idx_notifications_task_file
710
+ ON notifications(task_file);
711
+ `);
712
+ await client.executeMultiple(`
713
+ CREATE TABLE IF NOT EXISTS schedules (
714
+ id TEXT PRIMARY KEY,
715
+ cron TEXT NOT NULL,
716
+ description TEXT NOT NULL,
717
+ job_type TEXT NOT NULL DEFAULT 'report',
718
+ prompt TEXT,
719
+ assigned_to TEXT,
720
+ project_name TEXT,
721
+ active INTEGER NOT NULL DEFAULT 1,
722
+ use_crontab INTEGER NOT NULL DEFAULT 0,
723
+ created_at TEXT NOT NULL
724
+ );
725
+ `);
726
+ await client.executeMultiple(`
727
+ CREATE TABLE IF NOT EXISTS device_registry (
728
+ device_id TEXT PRIMARY KEY,
729
+ friendly_name TEXT NOT NULL,
730
+ hostname TEXT NOT NULL,
731
+ projects TEXT NOT NULL DEFAULT '[]',
732
+ agents TEXT NOT NULL DEFAULT '[]',
733
+ connected INTEGER DEFAULT 0,
734
+ last_seen TEXT NOT NULL
735
+ );
736
+ `);
737
+ await client.executeMultiple(`
738
+ CREATE TABLE IF NOT EXISTS messages (
739
+ id TEXT PRIMARY KEY,
740
+ from_agent TEXT NOT NULL,
741
+ from_device TEXT NOT NULL DEFAULT 'local',
742
+ target_agent TEXT NOT NULL,
743
+ target_project TEXT,
744
+ target_device TEXT NOT NULL DEFAULT 'local',
745
+ content TEXT NOT NULL,
746
+ priority TEXT DEFAULT 'normal',
747
+ status TEXT DEFAULT 'pending',
748
+ server_seq INTEGER,
749
+ retry_count INTEGER DEFAULT 0,
750
+ created_at TEXT NOT NULL,
751
+ delivered_at TEXT,
752
+ processed_at TEXT,
753
+ failed_at TEXT,
754
+ failure_reason TEXT
755
+ );
756
+
757
+ CREATE INDEX IF NOT EXISTS idx_messages_target
758
+ ON messages(target_agent, status);
759
+
760
+ CREATE INDEX IF NOT EXISTS idx_messages_conversation_order
761
+ ON messages(target_agent, from_agent, server_seq);
762
+ `);
763
+ try {
764
+ await client.execute({
765
+ sql: `UPDATE memories SET project_name = 'exe-create' WHERE project_name = 'web'`,
766
+ args: []
767
+ });
768
+ await client.execute({
769
+ sql: `UPDATE memories SET project_name = 'exe-os' WHERE project_name = 'worker'`,
770
+ args: []
771
+ });
772
+ await client.execute({
773
+ sql: `UPDATE tasks SET project_name = 'exe-create' WHERE project_name = 'web'`,
774
+ args: []
775
+ });
776
+ await client.execute({
777
+ sql: `UPDATE tasks SET project_name = 'exe-os' WHERE project_name = 'worker'`,
778
+ args: []
779
+ });
780
+ } catch {
781
+ }
782
+ await client.executeMultiple(`
783
+ CREATE TABLE IF NOT EXISTS trajectories (
784
+ id TEXT PRIMARY KEY,
785
+ task_id TEXT NOT NULL,
786
+ agent_id TEXT NOT NULL,
787
+ project_name TEXT NOT NULL,
788
+ task_title TEXT NOT NULL,
789
+ signature TEXT NOT NULL,
790
+ signature_hash TEXT NOT NULL,
791
+ tool_count INTEGER NOT NULL,
792
+ skill_id TEXT,
793
+ created_at TEXT NOT NULL
794
+ );
795
+
796
+ CREATE INDEX IF NOT EXISTS idx_trajectories_hash
797
+ ON trajectories(signature_hash);
798
+
799
+ CREATE INDEX IF NOT EXISTS idx_trajectories_agent
800
+ ON trajectories(agent_id);
801
+ `);
802
+ try {
803
+ await client.execute("ALTER TABLE trajectories ADD COLUMN skill_id TEXT");
804
+ } catch {
805
+ }
806
+ await client.executeMultiple(`
807
+ CREATE TABLE IF NOT EXISTS consolidations (
808
+ id TEXT PRIMARY KEY,
809
+ consolidated_memory_id TEXT NOT NULL,
810
+ source_memory_id TEXT NOT NULL,
811
+ created_at TEXT NOT NULL
812
+ );
813
+
814
+ CREATE INDEX IF NOT EXISTS idx_consolidations_source
815
+ ON consolidations(source_memory_id);
816
+ `);
817
+ await client.executeMultiple(`
818
+ CREATE TABLE IF NOT EXISTS audit_trail (
819
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
820
+ timestamp TEXT NOT NULL,
821
+ session_id TEXT NOT NULL,
822
+ agent_id TEXT NOT NULL,
823
+ tool TEXT NOT NULL,
824
+ input TEXT,
825
+ decision TEXT NOT NULL,
826
+ reason TEXT,
827
+ is_customer_facing INTEGER NOT NULL DEFAULT 0
828
+ );
829
+
830
+ CREATE INDEX IF NOT EXISTS idx_audit_trail_agent
831
+ ON audit_trail(agent_id, timestamp);
832
+
833
+ CREATE INDEX IF NOT EXISTS idx_audit_trail_session
834
+ ON audit_trail(session_id);
835
+ `);
836
+ try {
837
+ await client.execute({
838
+ sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
839
+ args: []
840
+ });
841
+ } catch {
842
+ }
843
+ try {
844
+ await client.execute({
845
+ sql: `ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5`,
846
+ args: []
847
+ });
848
+ } catch {
849
+ }
850
+ try {
851
+ await client.execute({
852
+ sql: `ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'`,
853
+ args: []
854
+ });
855
+ } catch {
856
+ }
857
+ try {
858
+ await client.execute({
859
+ sql: `ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7`,
860
+ args: []
861
+ });
862
+ } catch {
863
+ }
864
+ try {
865
+ await client.execute({
866
+ sql: `ALTER TABLE memories ADD COLUMN last_accessed TEXT`,
867
+ args: []
868
+ });
869
+ } catch {
870
+ }
871
+ try {
872
+ await client.execute({
873
+ sql: `UPDATE memories SET last_accessed = timestamp WHERE last_accessed IS NULL`,
874
+ args: []
875
+ });
876
+ } catch {
877
+ }
878
+ try {
879
+ await client.execute({
880
+ sql: `ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0`,
881
+ args: []
882
+ });
883
+ } catch {
884
+ }
885
+ try {
886
+ await client.execute({
887
+ sql: `ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0`,
888
+ args: []
889
+ });
890
+ } catch {
891
+ }
892
+ for (const col of [
893
+ "ALTER TABLE memories ADD COLUMN content_hash TEXT",
894
+ "ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT"
895
+ ]) {
896
+ try {
897
+ await client.execute(col);
898
+ } catch {
899
+ }
900
+ }
901
+ await client.executeMultiple(`
902
+ CREATE TABLE IF NOT EXISTS entities (
903
+ id TEXT PRIMARY KEY,
904
+ name TEXT NOT NULL,
905
+ type TEXT NOT NULL,
906
+ first_seen TEXT NOT NULL,
907
+ last_seen TEXT NOT NULL,
908
+ properties TEXT DEFAULT '{}',
909
+ UNIQUE(name, type)
910
+ );
911
+
912
+ CREATE TABLE IF NOT EXISTS relationships (
913
+ id TEXT PRIMARY KEY,
914
+ source_entity_id TEXT NOT NULL,
915
+ target_entity_id TEXT NOT NULL,
916
+ type TEXT NOT NULL,
917
+ weight REAL DEFAULT 1.0,
918
+ timestamp TEXT NOT NULL,
919
+ properties TEXT DEFAULT '{}',
920
+ UNIQUE(source_entity_id, target_entity_id, type)
921
+ );
922
+
923
+ CREATE TABLE IF NOT EXISTS entity_memories (
924
+ entity_id TEXT NOT NULL,
925
+ memory_id TEXT NOT NULL,
926
+ PRIMARY KEY (entity_id, memory_id)
927
+ );
928
+
929
+ CREATE TABLE IF NOT EXISTS relationship_memories (
930
+ relationship_id TEXT NOT NULL,
931
+ memory_id TEXT NOT NULL,
932
+ PRIMARY KEY (relationship_id, memory_id)
933
+ );
934
+
935
+ CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
936
+ CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type);
937
+ CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_entity_id);
938
+ CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_entity_id);
939
+
940
+ CREATE TABLE IF NOT EXISTS hyperedges (
941
+ id TEXT PRIMARY KEY,
942
+ label TEXT NOT NULL,
943
+ relation TEXT NOT NULL,
944
+ confidence REAL DEFAULT 1.0,
945
+ timestamp TEXT NOT NULL
946
+ );
947
+
948
+ CREATE TABLE IF NOT EXISTS hyperedge_nodes (
949
+ hyperedge_id TEXT NOT NULL,
950
+ entity_id TEXT NOT NULL,
951
+ PRIMARY KEY (hyperedge_id, entity_id)
952
+ );
953
+ `);
954
+ await client.executeMultiple(`
955
+ CREATE TABLE IF NOT EXISTS entity_aliases (
956
+ alias TEXT NOT NULL PRIMARY KEY,
957
+ canonical_entity_id TEXT NOT NULL
958
+ );
959
+ CREATE INDEX IF NOT EXISTS idx_entity_aliases_canonical ON entity_aliases(canonical_entity_id);
960
+ `);
961
+ for (const col of [
962
+ "ALTER TABLE relationships ADD COLUMN confidence REAL DEFAULT 1.0",
963
+ "ALTER TABLE relationships ADD COLUMN confidence_label TEXT DEFAULT 'extracted'"
964
+ ]) {
965
+ try {
966
+ await client.execute(col);
967
+ } catch {
968
+ }
969
+ }
970
+ try {
971
+ await client.execute(
972
+ `CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)`
973
+ );
974
+ } catch {
975
+ }
976
+ await client.executeMultiple(`
977
+ CREATE TABLE IF NOT EXISTS identity (
978
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
979
+ agent_id TEXT NOT NULL UNIQUE,
980
+ content_hash TEXT NOT NULL,
981
+ updated_at TEXT NOT NULL,
982
+ updated_by TEXT NOT NULL
983
+ );
984
+
985
+ CREATE INDEX IF NOT EXISTS idx_identity_agent ON identity(agent_id);
986
+ `);
987
+ await client.executeMultiple(`
988
+ CREATE TABLE IF NOT EXISTS chat_history (
989
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
990
+ session_id TEXT NOT NULL,
991
+ role TEXT NOT NULL,
992
+ content TEXT NOT NULL,
993
+ tool_name TEXT,
994
+ tool_id TEXT,
995
+ is_error INTEGER NOT NULL DEFAULT 0,
996
+ timestamp INTEGER NOT NULL
997
+ );
998
+
999
+ CREATE INDEX IF NOT EXISTS idx_chat_history_session
1000
+ ON chat_history(session_id, id);
1001
+ `);
1002
+ await client.executeMultiple(`
1003
+ CREATE TABLE IF NOT EXISTS workspaces (
1004
+ id TEXT PRIMARY KEY,
1005
+ slug TEXT NOT NULL UNIQUE,
1006
+ name TEXT NOT NULL,
1007
+ owner_agent_id TEXT,
1008
+ created_at TEXT NOT NULL,
1009
+ metadata TEXT
1010
+ );
1011
+
1012
+ CREATE INDEX IF NOT EXISTS idx_workspaces_slug
1013
+ ON workspaces(slug);
1014
+ `);
1015
+ await client.executeMultiple(`
1016
+ CREATE TABLE IF NOT EXISTS documents (
1017
+ id TEXT PRIMARY KEY,
1018
+ workspace_id TEXT NOT NULL,
1019
+ filename TEXT NOT NULL,
1020
+ mime TEXT,
1021
+ source_type TEXT,
1022
+ user_id TEXT,
1023
+ uploaded_at TEXT NOT NULL,
1024
+ metadata TEXT,
1025
+ FOREIGN KEY (workspace_id) REFERENCES workspaces(id)
1026
+ );
1027
+
1028
+ CREATE INDEX IF NOT EXISTS idx_documents_workspace
1029
+ ON documents(workspace_id);
1030
+
1031
+ CREATE INDEX IF NOT EXISTS idx_documents_user
1032
+ ON documents(user_id);
1033
+ `);
1034
+ for (const column of [
1035
+ "workspace_id TEXT",
1036
+ "document_id TEXT",
1037
+ "user_id TEXT",
1038
+ "char_offset INTEGER",
1039
+ "page_number INTEGER"
1040
+ ]) {
1041
+ try {
1042
+ await client.execute({
1043
+ sql: `ALTER TABLE memories ADD COLUMN ${column}`,
1044
+ args: []
1045
+ });
1046
+ } catch {
1047
+ }
1048
+ }
1049
+ for (const col of [
1050
+ "ALTER TABLE memories ADD COLUMN source_path TEXT",
1051
+ "ALTER TABLE memories ADD COLUMN source_type TEXT DEFAULT 'text'"
1052
+ ]) {
1053
+ try {
1054
+ await client.execute(col);
1055
+ } catch {
1056
+ }
1057
+ }
1058
+ await client.executeMultiple(`
1059
+ CREATE INDEX IF NOT EXISTS idx_memories_workspace
1060
+ ON memories(workspace_id);
1061
+
1062
+ CREATE INDEX IF NOT EXISTS idx_memories_document
1063
+ ON memories(document_id);
1064
+
1065
+ CREATE INDEX IF NOT EXISTS idx_memories_user
1066
+ ON memories(user_id);
1067
+ `);
1068
+ await client.executeMultiple(`
1069
+ CREATE TABLE IF NOT EXISTS session_kills (
1070
+ id TEXT PRIMARY KEY,
1071
+ session_name TEXT NOT NULL,
1072
+ agent_id TEXT NOT NULL,
1073
+ killed_at TIMESTAMP NOT NULL,
1074
+ reason TEXT NOT NULL,
1075
+ ticks_idle INTEGER,
1076
+ estimated_tokens_saved INTEGER
1077
+ );
1078
+
1079
+ CREATE INDEX IF NOT EXISTS idx_session_kills_killed_at
1080
+ ON session_kills(killed_at);
1081
+
1082
+ CREATE INDEX IF NOT EXISTS idx_session_kills_agent
1083
+ ON session_kills(agent_id);
1084
+ `);
1085
+ await client.execute(`
1086
+ CREATE TABLE IF NOT EXISTS global_procedures (
1087
+ id TEXT PRIMARY KEY,
1088
+ title TEXT NOT NULL,
1089
+ content TEXT NOT NULL,
1090
+ priority TEXT NOT NULL DEFAULT 'p0',
1091
+ domain TEXT,
1092
+ active INTEGER NOT NULL DEFAULT 1,
1093
+ created_at TEXT NOT NULL,
1094
+ updated_at TEXT NOT NULL
1095
+ )
1096
+ `);
1097
+ await client.executeMultiple(`
1098
+ CREATE TABLE IF NOT EXISTS conversations (
1099
+ id TEXT PRIMARY KEY,
1100
+ platform TEXT NOT NULL,
1101
+ external_id TEXT,
1102
+ sender_id TEXT NOT NULL,
1103
+ sender_name TEXT,
1104
+ sender_phone TEXT,
1105
+ sender_email TEXT,
1106
+ recipient_id TEXT,
1107
+ channel_id TEXT NOT NULL,
1108
+ thread_id TEXT,
1109
+ reply_to_id TEXT,
1110
+ content_text TEXT,
1111
+ content_media TEXT,
1112
+ content_metadata TEXT,
1113
+ agent_response TEXT,
1114
+ agent_name TEXT,
1115
+ timestamp TEXT NOT NULL,
1116
+ ingested_at TEXT NOT NULL
1117
+ );
1118
+
1119
+ CREATE INDEX IF NOT EXISTS idx_conversations_platform
1120
+ ON conversations(platform);
1121
+
1122
+ CREATE INDEX IF NOT EXISTS idx_conversations_sender
1123
+ ON conversations(sender_id);
1124
+
1125
+ CREATE INDEX IF NOT EXISTS idx_conversations_timestamp
1126
+ ON conversations(timestamp);
1127
+
1128
+ CREATE INDEX IF NOT EXISTS idx_conversations_thread
1129
+ ON conversations(thread_id);
1130
+
1131
+ CREATE INDEX IF NOT EXISTS idx_conversations_channel
1132
+ ON conversations(channel_id);
1133
+ `);
1134
+ try {
1135
+ await client.execute({
1136
+ sql: `ALTER TABLE tasks ADD COLUMN budget_tokens INTEGER`,
1137
+ args: []
1138
+ });
1139
+ } catch {
1140
+ }
1141
+ try {
1142
+ await client.execute({
1143
+ sql: `ALTER TABLE tasks ADD COLUMN budget_fallback_model TEXT`,
1144
+ args: []
1145
+ });
1146
+ } catch {
1147
+ }
1148
+ try {
1149
+ await client.execute({
1150
+ sql: `ALTER TABLE tasks ADD COLUMN tokens_used INTEGER DEFAULT 0`,
1151
+ args: []
1152
+ });
1153
+ } catch {
1154
+ }
1155
+ try {
1156
+ await client.execute({
1157
+ sql: `ALTER TABLE tasks ADD COLUMN tokens_warned_at INTEGER`,
1158
+ args: []
1159
+ });
1160
+ } catch {
1161
+ }
1162
+ await client.executeMultiple(`
1163
+ CREATE VIRTUAL TABLE IF NOT EXISTS conversations_fts USING fts5(
1164
+ content_text,
1165
+ sender_name,
1166
+ agent_response,
1167
+ content='conversations',
1168
+ content_rowid='rowid'
1169
+ );
1170
+
1171
+ CREATE TRIGGER IF NOT EXISTS conversations_fts_ai AFTER INSERT ON conversations BEGIN
1172
+ INSERT INTO conversations_fts(rowid, content_text, sender_name, agent_response)
1173
+ VALUES (new.rowid, new.content_text, new.sender_name, new.agent_response);
1174
+ END;
1175
+
1176
+ CREATE TRIGGER IF NOT EXISTS conversations_fts_ad AFTER DELETE ON conversations BEGIN
1177
+ INSERT INTO conversations_fts(conversations_fts, rowid, content_text, sender_name, agent_response)
1178
+ VALUES('delete', old.rowid, old.content_text, old.sender_name, old.agent_response);
1179
+ END;
1180
+
1181
+ CREATE TRIGGER IF NOT EXISTS conversations_fts_au AFTER UPDATE ON conversations BEGIN
1182
+ INSERT INTO conversations_fts(conversations_fts, rowid, content_text, sender_name, agent_response)
1183
+ VALUES('delete', old.rowid, old.content_text, old.sender_name, old.agent_response);
1184
+ INSERT INTO conversations_fts(rowid, content_text, sender_name, agent_response)
1185
+ VALUES (new.rowid, new.content_text, new.sender_name, new.agent_response);
1186
+ END;
1187
+ `);
1188
+ try {
1189
+ await client.execute({
1190
+ sql: `ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3`,
1191
+ args: []
1192
+ });
1193
+ } catch {
1194
+ }
1195
+ try {
1196
+ await client.execute(
1197
+ `CREATE INDEX IF NOT EXISTS idx_memories_tier ON memories(tier)`
1198
+ );
1199
+ } catch {
1200
+ }
1201
+ try {
1202
+ await client.execute({
1203
+ sql: `UPDATE memories SET tier = 1 WHERE tool_name = 'commit_to_long_term_memory' AND importance >= 8 AND tier = 3`,
1204
+ args: []
1205
+ });
1206
+ await client.execute({
1207
+ sql: `UPDATE memories SET tier = 2 WHERE tool_name IN ('store_memory', 'manual') AND importance >= 5 AND tier = 3`,
1208
+ args: []
1209
+ });
1210
+ } catch {
1211
+ }
1212
+ try {
1213
+ await client.execute({
1214
+ sql: `ALTER TABLE memories ADD COLUMN supersedes_id TEXT`,
1215
+ args: []
1216
+ });
1217
+ } catch {
1218
+ }
1219
+ try {
1220
+ await client.execute(
1221
+ `CREATE INDEX IF NOT EXISTS idx_memories_supersedes ON memories(supersedes_id) WHERE supersedes_id IS NOT NULL`
1222
+ );
1223
+ } catch {
1224
+ }
1225
+ for (const col of [
1226
+ "ALTER TABLE tasks ADD COLUMN checkpoint TEXT",
1227
+ "ALTER TABLE tasks ADD COLUMN checkpoint_count INTEGER DEFAULT 0"
1228
+ ]) {
1229
+ try {
1230
+ await client.execute(col);
1231
+ } catch {
1232
+ }
1233
+ }
1234
+ }
1235
+ async function disposeDatabase() {
1236
+ if (_client) {
1237
+ _client.close();
1238
+ _client = null;
1239
+ _resilientClient = null;
1240
+ }
1241
+ }
1242
+ var _client, _resilientClient, initTurso, disposeTurso;
341
1243
  var init_database = __esm({
342
1244
  "src/lib/database.ts"() {
343
1245
  "use strict";
344
1246
  init_db_retry();
1247
+ _client = null;
345
1248
  _resilientClient = null;
1249
+ initTurso = initDatabase;
1250
+ disposeTurso = disposeDatabase;
346
1251
  }
347
1252
  });
348
1253
 
@@ -366,13 +1271,50 @@ var init_compress = __esm({
366
1271
  }
367
1272
  });
368
1273
 
1274
+ // src/lib/license.ts
1275
+ import { readFileSync as readFileSync2, writeFileSync, existsSync as existsSync3, mkdirSync } from "fs";
1276
+ import { randomUUID } from "crypto";
1277
+ import path3 from "path";
1278
+ import { jwtVerify, importSPKI } from "jose";
1279
+ function loadDeviceId() {
1280
+ const deviceJsonPath = path3.join(EXE_AI_DIR, "device.json");
1281
+ try {
1282
+ if (existsSync3(deviceJsonPath)) {
1283
+ const data = JSON.parse(readFileSync2(deviceJsonPath, "utf8"));
1284
+ if (data.deviceId) return data.deviceId;
1285
+ }
1286
+ } catch {
1287
+ }
1288
+ try {
1289
+ if (existsSync3(DEVICE_ID_PATH)) {
1290
+ const id2 = readFileSync2(DEVICE_ID_PATH, "utf8").trim();
1291
+ if (id2) return id2;
1292
+ }
1293
+ } catch {
1294
+ }
1295
+ const id = randomUUID();
1296
+ mkdirSync(EXE_AI_DIR, { recursive: true });
1297
+ writeFileSync(DEVICE_ID_PATH, id, "utf8");
1298
+ return id;
1299
+ }
1300
+ var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH;
1301
+ var init_license = __esm({
1302
+ "src/lib/license.ts"() {
1303
+ "use strict";
1304
+ init_config();
1305
+ LICENSE_PATH = path3.join(EXE_AI_DIR, "license.key");
1306
+ CACHE_PATH = path3.join(EXE_AI_DIR, "license-cache.json");
1307
+ DEVICE_ID_PATH = path3.join(EXE_AI_DIR, "device-id");
1308
+ }
1309
+ });
1310
+
369
1311
  // src/lib/employees.ts
370
1312
  import { readFile as readFile3, writeFile as writeFile3, mkdir as mkdir3 } from "fs/promises";
371
- import { existsSync as existsSync3, symlinkSync, readlinkSync, readFileSync as readFileSync2 } from "fs";
1313
+ import { existsSync as existsSync4, symlinkSync, readlinkSync, readFileSync as readFileSync3 } from "fs";
372
1314
  import { execSync } from "child_process";
373
- import path3 from "path";
1315
+ import path4 from "path";
374
1316
  async function loadEmployees(employeesPath = EMPLOYEES_PATH) {
375
- if (!existsSync3(employeesPath)) {
1317
+ if (!existsSync4(employeesPath)) {
376
1318
  return [];
377
1319
  }
378
1320
  const raw = await readFile3(employeesPath, "utf-8");
@@ -383,7 +1325,7 @@ async function loadEmployees(employeesPath = EMPLOYEES_PATH) {
383
1325
  }
384
1326
  }
385
1327
  async function saveEmployees(employees, employeesPath = EMPLOYEES_PATH) {
386
- await mkdir3(path3.dirname(employeesPath), { recursive: true });
1328
+ await mkdir3(path4.dirname(employeesPath), { recursive: true });
387
1329
  await writeFile3(employeesPath, JSON.stringify(employees, null, 2) + "\n", "utf-8");
388
1330
  }
389
1331
  function findExeBin() {
@@ -402,7 +1344,7 @@ function registerBinSymlinks(name) {
402
1344
  errors.push("Could not find 'exe-os' in PATH");
403
1345
  return { created, skipped, errors };
404
1346
  }
405
- const binDir = path3.dirname(exeBinPath);
1347
+ const binDir = path4.dirname(exeBinPath);
406
1348
  let target;
407
1349
  try {
408
1350
  target = readlinkSync(exeBinPath);
@@ -412,8 +1354,8 @@ function registerBinSymlinks(name) {
412
1354
  }
413
1355
  for (const suffix of ["", "-opencode"]) {
414
1356
  const linkName = `${name}${suffix}`;
415
- const linkPath = path3.join(binDir, linkName);
416
- if (existsSync3(linkPath)) {
1357
+ const linkPath = path4.join(binDir, linkName);
1358
+ if (existsSync4(linkPath)) {
417
1359
  skipped.push(linkName);
418
1360
  continue;
419
1361
  }
@@ -431,237 +1373,7 @@ var init_employees = __esm({
431
1373
  "src/lib/employees.ts"() {
432
1374
  "use strict";
433
1375
  init_config();
434
- EMPLOYEES_PATH = path3.join(EXE_AI_DIR, "exe-employees.json");
435
- }
436
- });
437
-
438
- // src/lib/license.ts
439
- import { readFileSync as readFileSync3, writeFileSync, existsSync as existsSync4, mkdirSync } from "fs";
440
- import { randomUUID } from "crypto";
441
- import path4 from "path";
442
- import { jwtVerify, importSPKI } from "jose";
443
- async function fetchRetry(url, init) {
444
- try {
445
- return await fetch(url, init);
446
- } catch {
447
- await new Promise((r) => setTimeout(r, RETRY_DELAY_MS));
448
- return fetch(url, { ...init, signal: AbortSignal.timeout(1e4) });
449
- }
450
- }
451
- function loadDeviceId() {
452
- const deviceJsonPath = path4.join(EXE_AI_DIR, "device.json");
453
- try {
454
- if (existsSync4(deviceJsonPath)) {
455
- const data = JSON.parse(readFileSync3(deviceJsonPath, "utf8"));
456
- if (data.deviceId) return data.deviceId;
457
- }
458
- } catch {
459
- }
460
- try {
461
- if (existsSync4(DEVICE_ID_PATH)) {
462
- const id2 = readFileSync3(DEVICE_ID_PATH, "utf8").trim();
463
- if (id2) return id2;
464
- }
465
- } catch {
466
- }
467
- const id = randomUUID();
468
- mkdirSync(EXE_AI_DIR, { recursive: true });
469
- writeFileSync(DEVICE_ID_PATH, id, "utf8");
470
- return id;
471
- }
472
- function loadLicense() {
473
- try {
474
- if (!existsSync4(LICENSE_PATH)) return null;
475
- return readFileSync3(LICENSE_PATH, "utf8").trim();
476
- } catch {
477
- return null;
478
- }
479
- }
480
- function saveLicense(apiKey) {
481
- mkdirSync(EXE_AI_DIR, { recursive: true });
482
- writeFileSync(LICENSE_PATH, apiKey.trim(), { encoding: "utf8", mode: 384 });
483
- }
484
- async function verifyLicenseJwt(token) {
485
- try {
486
- const key = await importSPKI(LICENSE_PUBLIC_KEY_PEM, LICENSE_JWT_ALG);
487
- const { payload } = await jwtVerify(token, key, {
488
- algorithms: [LICENSE_JWT_ALG]
489
- });
490
- const plan = payload.plan ?? "free";
491
- const email = payload.sub ?? "";
492
- const limits = PLAN_LIMITS[plan] ?? PLAN_LIMITS.free;
493
- return {
494
- valid: true,
495
- plan,
496
- email,
497
- expiresAt: payload.exp ? new Date(payload.exp * 1e3).toISOString() : null,
498
- deviceLimit: limits.devices,
499
- employeeLimit: limits.employees,
500
- memoryLimit: limits.memories
501
- };
502
- } catch {
503
- return null;
504
- }
505
- }
506
- async function getCachedLicense() {
507
- try {
508
- if (!existsSync4(CACHE_PATH)) return null;
509
- const raw = JSON.parse(readFileSync3(CACHE_PATH, "utf8"));
510
- if (!raw.token || typeof raw.token !== "string") return null;
511
- return await verifyLicenseJwt(raw.token);
512
- } catch {
513
- return null;
514
- }
515
- }
516
- function cacheResponse(token) {
517
- try {
518
- writeFileSync(CACHE_PATH, JSON.stringify({ token }), "utf8");
519
- } catch {
520
- }
521
- }
522
- async function validateLicense(apiKey, deviceId) {
523
- const did = deviceId ?? loadDeviceId();
524
- try {
525
- const res = await fetchRetry(`${API_BASE}/auth/activate`, {
526
- method: "POST",
527
- headers: { "Content-Type": "application/json" },
528
- body: JSON.stringify({ apiKey, deviceId: did }),
529
- signal: AbortSignal.timeout(1e4)
530
- });
531
- if (res.ok) {
532
- const data = await res.json();
533
- if (data.error === "device_limit_exceeded") {
534
- const cached2 = await getCachedLicense();
535
- if (cached2) return cached2;
536
- return { ...FREE_LICENSE, valid: false, plan: "free" };
537
- }
538
- if (data.token) {
539
- cacheResponse(data.token);
540
- const verified = await verifyLicenseJwt(data.token);
541
- if (verified) return verified;
542
- }
543
- const limits = PLAN_LIMITS[data.plan] ?? PLAN_LIMITS.free;
544
- return {
545
- valid: data.valid,
546
- plan: data.plan,
547
- email: data.email,
548
- expiresAt: data.expiresAt,
549
- deviceLimit: limits.devices,
550
- employeeLimit: limits.employees,
551
- memoryLimit: limits.memories
552
- };
553
- }
554
- const cached = await getCachedLicense();
555
- if (cached) return cached;
556
- return { ...FREE_LICENSE, valid: false, plan: "free" };
557
- } catch {
558
- const cached = await getCachedLicense();
559
- if (cached) return cached;
560
- return { ...FREE_LICENSE, valid: false, error: "offline" };
561
- }
562
- }
563
- function getCacheAgeMs() {
564
- try {
565
- const { statSync } = __require("fs");
566
- const s = statSync(CACHE_PATH);
567
- return Date.now() - s.mtimeMs;
568
- } catch {
569
- return Infinity;
570
- }
571
- }
572
- async function checkLicense() {
573
- let key = loadLicense();
574
- if (!key) {
575
- try {
576
- const configPath = path4.join(EXE_AI_DIR, "config.json");
577
- if (existsSync4(configPath)) {
578
- const raw = JSON.parse(readFileSync3(configPath, "utf8"));
579
- const cloud = raw.cloud;
580
- if (cloud?.apiKey) {
581
- key = cloud.apiKey;
582
- saveLicense(key);
583
- }
584
- }
585
- } catch {
586
- }
587
- }
588
- if (!key) return FREE_LICENSE;
589
- const cached = await getCachedLicense();
590
- if (cached && getCacheAgeMs() < CACHE_MAX_AGE_MS) return cached;
591
- const deviceId = loadDeviceId();
592
- return validateLicense(key, deviceId);
593
- }
594
- function isFeatureAllowed(license, feature) {
595
- switch (feature) {
596
- case "cloud_sync":
597
- case "external_agents":
598
- case "wiki":
599
- return license.plan !== "free";
600
- case "unlimited_employees":
601
- return license.plan === "team" || license.plan === "agency" || license.plan === "enterprise";
602
- }
603
- }
604
- var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH, API_BASE, RETRY_DELAY_MS, LICENSE_PUBLIC_KEY_PEM, LICENSE_JWT_ALG, PLAN_LIMITS, FREE_LICENSE, CACHE_MAX_AGE_MS;
605
- var init_license = __esm({
606
- "src/lib/license.ts"() {
607
- "use strict";
608
- init_config();
609
- LICENSE_PATH = path4.join(EXE_AI_DIR, "license.key");
610
- CACHE_PATH = path4.join(EXE_AI_DIR, "license-cache.json");
611
- DEVICE_ID_PATH = path4.join(EXE_AI_DIR, "device-id");
612
- API_BASE = "https://askexe.com/cloud";
613
- RETRY_DELAY_MS = 500;
614
- LICENSE_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
615
- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEeHztAMOpR/ZMh+rWuOASjEZ54CGY
616
- 4uj+UqeKCcvtgNHKmOK278HJaJcANe9xAeji8AFYu27q3WtzCi04pHudow==
617
- -----END PUBLIC KEY-----`;
618
- LICENSE_JWT_ALG = "ES256";
619
- PLAN_LIMITS = {
620
- free: { devices: 1, employees: 1, memories: 5e3 },
621
- pro: { devices: 2, employees: 5, memories: 1e5 },
622
- team: { devices: 10, employees: 20, memories: 1e6 },
623
- agency: { devices: 50, employees: 100, memories: 1e7 },
624
- enterprise: { devices: -1, employees: -1, memories: -1 }
625
- };
626
- FREE_LICENSE = {
627
- valid: true,
628
- plan: "free",
629
- email: "",
630
- expiresAt: null,
631
- deviceLimit: 1,
632
- employeeLimit: 1,
633
- memoryLimit: 5e3
634
- };
635
- CACHE_MAX_AGE_MS = 36e5;
636
- }
637
- });
638
-
639
- // src/lib/plan-limits.ts
640
- import { readFileSync as readFileSync4, existsSync as existsSync5 } from "fs";
641
- import path5 from "path";
642
- async function assertFeature(feature) {
643
- const license = await checkLicense();
644
- if (!isFeatureAllowed(license, feature)) {
645
- throw new PlanLimitError(
646
- `Feature "${feature}" requires a paid plan. Current plan: ${license.plan}. Upgrade at https://askexe.com.`
647
- );
648
- }
649
- }
650
- var PlanLimitError, CACHE_PATH2;
651
- var init_plan_limits = __esm({
652
- "src/lib/plan-limits.ts"() {
653
- "use strict";
654
- init_database();
655
- init_employees();
656
- init_license();
657
- init_config();
658
- PlanLimitError = class extends Error {
659
- constructor(message) {
660
- super(message);
661
- this.name = "PlanLimitError";
662
- }
663
- };
664
- CACHE_PATH2 = path5.join(EXE_AI_DIR, "license-cache.json");
1376
+ EMPLOYEES_PATH = path4.join(EXE_AI_DIR, "exe-employees.json");
665
1377
  }
666
1378
  });
667
1379
 
@@ -691,13 +1403,13 @@ __export(cloud_sync_exports, {
691
1403
  mergeRosterFromRemote: () => mergeRosterFromRemote,
692
1404
  recordRosterDeletion: () => recordRosterDeletion
693
1405
  });
694
- import { readFileSync as readFileSync5, writeFileSync as writeFileSync2, existsSync as existsSync6, readdirSync, mkdirSync as mkdirSync2, appendFileSync, unlinkSync, openSync, closeSync } from "fs";
1406
+ import { readFileSync as readFileSync4, writeFileSync as writeFileSync2, existsSync as existsSync5, readdirSync, mkdirSync as mkdirSync2, appendFileSync, unlinkSync, openSync, closeSync } from "fs";
695
1407
  import crypto3 from "crypto";
696
- import path6 from "path";
1408
+ import path5 from "path";
697
1409
  import { homedir } from "os";
698
1410
  function logError(msg) {
699
1411
  try {
700
- const logPath = path6.join(homedir(), ".exe-os", "workers.log");
1412
+ const logPath = path5.join(homedir(), ".exe-os", "workers.log");
701
1413
  appendFileSync(logPath, `${(/* @__PURE__ */ new Date()).toISOString()} ${msg}
702
1414
  `);
703
1415
  } catch {
@@ -711,7 +1423,7 @@ async function withRosterLock(fn) {
711
1423
  } catch (err) {
712
1424
  if (err.code === "EEXIST") {
713
1425
  try {
714
- const ts = parseInt(readFileSync5(ROSTER_LOCK_PATH, "utf-8"), 10);
1426
+ const ts = parseInt(readFileSync4(ROSTER_LOCK_PATH, "utf-8"), 10);
715
1427
  if (Date.now() - ts < LOCK_STALE_MS) {
716
1428
  throw new Error("Roster merge already in progress \u2014 another sync is running");
717
1429
  }
@@ -737,22 +1449,22 @@ async function withRosterLock(fn) {
737
1449
  }
738
1450
  }
739
1451
  async function fetchWithRetry(url, init) {
740
- const MAX_RETRIES = 3;
741
- const BASE_DELAY_MS = 200;
1452
+ const MAX_RETRIES2 = 3;
1453
+ const BASE_DELAY_MS2 = 200;
742
1454
  let lastError;
743
- for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
1455
+ for (let attempt = 0; attempt <= MAX_RETRIES2; attempt++) {
744
1456
  try {
745
1457
  const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS);
746
1458
  const resp = await fetch(url, { ...init, signal });
747
- if (resp && resp.status >= 500 && attempt < MAX_RETRIES) {
748
- await new Promise((r) => setTimeout(r, BASE_DELAY_MS * Math.pow(2, attempt)));
1459
+ if (resp && resp.status >= 500 && attempt < MAX_RETRIES2) {
1460
+ await new Promise((r) => setTimeout(r, BASE_DELAY_MS2 * Math.pow(2, attempt)));
749
1461
  continue;
750
1462
  }
751
1463
  return resp;
752
1464
  } catch (err) {
753
1465
  lastError = err;
754
- if (attempt === MAX_RETRIES) throw err;
755
- await new Promise((r) => setTimeout(r, BASE_DELAY_MS * Math.pow(2, attempt)));
1466
+ if (attempt === MAX_RETRIES2) throw err;
1467
+ await new Promise((r) => setTimeout(r, BASE_DELAY_MS2 * Math.pow(2, attempt)));
756
1468
  }
757
1469
  }
758
1470
  throw lastError;
@@ -838,16 +1550,25 @@ async function cloudPull(sinceVersion, config) {
838
1550
  }
839
1551
  }
840
1552
  async function cloudSync(config) {
841
- await assertFeature("cloud_sync");
842
1553
  let client;
843
1554
  try {
844
1555
  client = getClient();
845
1556
  } catch {
846
1557
  throw new Error("[cloud-sync] Database not initialized. Call initStore() before cloudSync().");
847
1558
  }
848
- const pullMeta = await client.execute(
849
- "SELECT value FROM sync_meta WHERE key = 'last_cloud_pull_version'"
850
- );
1559
+ let pullMeta;
1560
+ try {
1561
+ pullMeta = await client.execute(
1562
+ "SELECT value FROM sync_meta WHERE key = 'last_cloud_pull_version'"
1563
+ );
1564
+ } catch (e) {
1565
+ logError(`[cloud-sync] sync_meta read failed (${e instanceof Error ? e.message : String(e)}), attempting ensureSchema`);
1566
+ const { ensureSchema: ensureSchema2 } = await Promise.resolve().then(() => (init_database(), database_exports));
1567
+ await ensureSchema2();
1568
+ pullMeta = await client.execute(
1569
+ "SELECT value FROM sync_meta WHERE key = 'last_cloud_pull_version'"
1570
+ );
1571
+ }
851
1572
  const lastPullVersion = pullMeta.rows.length > 0 ? Number(pullMeta.rows[0].value) : 0;
852
1573
  const pullResult = await cloudPull(lastPullVersion, config);
853
1574
  let pulled = 0;
@@ -1009,8 +1730,8 @@ async function cloudSync(config) {
1009
1730
  function recordRosterDeletion(name) {
1010
1731
  let deletions = [];
1011
1732
  try {
1012
- if (existsSync6(ROSTER_DELETIONS_PATH)) {
1013
- deletions = JSON.parse(readFileSync5(ROSTER_DELETIONS_PATH, "utf-8"));
1733
+ if (existsSync5(ROSTER_DELETIONS_PATH)) {
1734
+ deletions = JSON.parse(readFileSync4(ROSTER_DELETIONS_PATH, "utf-8"));
1014
1735
  }
1015
1736
  } catch {
1016
1737
  }
@@ -1019,8 +1740,8 @@ function recordRosterDeletion(name) {
1019
1740
  }
1020
1741
  function consumeRosterDeletions() {
1021
1742
  try {
1022
- if (!existsSync6(ROSTER_DELETIONS_PATH)) return [];
1023
- const deletions = JSON.parse(readFileSync5(ROSTER_DELETIONS_PATH, "utf-8"));
1743
+ if (!existsSync5(ROSTER_DELETIONS_PATH)) return [];
1744
+ const deletions = JSON.parse(readFileSync4(ROSTER_DELETIONS_PATH, "utf-8"));
1024
1745
  writeFileSync2(ROSTER_DELETIONS_PATH, "[]");
1025
1746
  return deletions;
1026
1747
  } catch {
@@ -1028,29 +1749,29 @@ function consumeRosterDeletions() {
1028
1749
  }
1029
1750
  }
1030
1751
  function buildRosterBlob(paths) {
1031
- const rosterPath = paths?.rosterPath ?? path6.join(EXE_AI_DIR, "exe-employees.json");
1032
- const identityDir = paths?.identityDir ?? path6.join(EXE_AI_DIR, "identity");
1033
- const configPath = paths?.configPath ?? path6.join(EXE_AI_DIR, "config.json");
1752
+ const rosterPath = paths?.rosterPath ?? path5.join(EXE_AI_DIR, "exe-employees.json");
1753
+ const identityDir = paths?.identityDir ?? path5.join(EXE_AI_DIR, "identity");
1754
+ const configPath = paths?.configPath ?? path5.join(EXE_AI_DIR, "config.json");
1034
1755
  let roster = [];
1035
- if (existsSync6(rosterPath)) {
1756
+ if (existsSync5(rosterPath)) {
1036
1757
  try {
1037
- roster = JSON.parse(readFileSync5(rosterPath, "utf-8"));
1758
+ roster = JSON.parse(readFileSync4(rosterPath, "utf-8"));
1038
1759
  } catch {
1039
1760
  }
1040
1761
  }
1041
1762
  const identities = {};
1042
- if (existsSync6(identityDir)) {
1763
+ if (existsSync5(identityDir)) {
1043
1764
  for (const file of readdirSync(identityDir).filter((f) => f.endsWith(".md"))) {
1044
1765
  try {
1045
- identities[file] = readFileSync5(path6.join(identityDir, file), "utf-8");
1766
+ identities[file] = readFileSync4(path5.join(identityDir, file), "utf-8");
1046
1767
  } catch {
1047
1768
  }
1048
1769
  }
1049
1770
  }
1050
1771
  let config;
1051
- if (existsSync6(configPath)) {
1772
+ if (existsSync5(configPath)) {
1052
1773
  try {
1053
- config = JSON.parse(readFileSync5(configPath, "utf-8"));
1774
+ config = JSON.parse(readFileSync4(configPath, "utf-8"));
1054
1775
  } catch {
1055
1776
  }
1056
1777
  }
@@ -1126,23 +1847,23 @@ async function cloudPullRoster(config) {
1126
1847
  }
1127
1848
  }
1128
1849
  function mergeConfig(remoteConfig, configPath) {
1129
- const cfgPath = configPath ?? path6.join(EXE_AI_DIR, "config.json");
1850
+ const cfgPath = configPath ?? path5.join(EXE_AI_DIR, "config.json");
1130
1851
  let local = {};
1131
- if (existsSync6(cfgPath)) {
1852
+ if (existsSync5(cfgPath)) {
1132
1853
  try {
1133
- local = JSON.parse(readFileSync5(cfgPath, "utf-8"));
1854
+ local = JSON.parse(readFileSync4(cfgPath, "utf-8"));
1134
1855
  } catch {
1135
1856
  }
1136
1857
  }
1137
1858
  const merged = { ...remoteConfig, ...local };
1138
- const dir = path6.dirname(cfgPath);
1139
- if (!existsSync6(dir)) mkdirSync2(dir, { recursive: true });
1859
+ const dir = path5.dirname(cfgPath);
1860
+ if (!existsSync5(dir)) mkdirSync2(dir, { recursive: true });
1140
1861
  writeFileSync2(cfgPath, JSON.stringify(merged, null, 2), "utf-8");
1141
1862
  }
1142
1863
  async function mergeRosterFromRemote(remote, paths) {
1143
1864
  return withRosterLock(async () => {
1144
1865
  const rosterPath = paths?.rosterPath ?? void 0;
1145
- const identityDir = paths?.identityDir ?? path6.join(EXE_AI_DIR, "identity");
1866
+ const identityDir = paths?.identityDir ?? path5.join(EXE_AI_DIR, "identity");
1146
1867
  const localEmployees = await loadEmployees(rosterPath);
1147
1868
  const localNames = new Set(localEmployees.map((e) => e.name));
1148
1869
  let added = 0;
@@ -1152,9 +1873,9 @@ async function mergeRosterFromRemote(remote, paths) {
1152
1873
  localNames.add(remoteEmp.name);
1153
1874
  added++;
1154
1875
  if (remote.identities[`${remoteEmp.name}.md`]) {
1155
- if (!existsSync6(identityDir)) mkdirSync2(identityDir, { recursive: true });
1156
- const idPath = path6.join(identityDir, `${remoteEmp.name}.md`);
1157
- if (!existsSync6(idPath)) {
1876
+ if (!existsSync5(identityDir)) mkdirSync2(identityDir, { recursive: true });
1877
+ const idPath = path5.join(identityDir, `${remoteEmp.name}.md`);
1878
+ if (!existsSync5(idPath)) {
1158
1879
  writeFileSync2(idPath, remote.identities[`${remoteEmp.name}.md`], "utf-8");
1159
1880
  }
1160
1881
  }
@@ -1564,16 +2285,15 @@ var init_cloud_sync = __esm({
1564
2285
  init_database();
1565
2286
  init_crypto();
1566
2287
  init_compress();
1567
- init_plan_limits();
1568
2288
  init_license();
1569
2289
  init_config();
1570
2290
  init_employees();
1571
2291
  LOCALHOST_PATTERNS = /^(localhost|127\.0\.0\.1|\[::1\])$/i;
1572
2292
  FETCH_TIMEOUT_MS = 3e4;
1573
2293
  PUSH_BATCH_SIZE = 5e3;
1574
- ROSTER_LOCK_PATH = path6.join(EXE_AI_DIR, "roster-merge.lock");
2294
+ ROSTER_LOCK_PATH = path5.join(EXE_AI_DIR, "roster-merge.lock");
1575
2295
  LOCK_STALE_MS = 3e4;
1576
- ROSTER_DELETIONS_PATH = path6.join(EXE_AI_DIR, "roster-deletions.json");
2296
+ ROSTER_DELETIONS_PATH = path5.join(EXE_AI_DIR, "roster-deletions.json");
1577
2297
  }
1578
2298
  });
1579
2299