@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.
@@ -323,931 +323,26 @@ 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;
371
326
  var init_db_retry = __esm({
372
327
  "src/lib/db-retry.ts"() {
373
328
  "use strict";
374
- MAX_RETRIES = 3;
375
- BASE_DELAY_MS = 200;
376
- MAX_JITTER_MS = 300;
377
329
  }
378
330
  });
379
331
 
380
332
  // 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
- });
392
333
  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
- }
411
334
  function getClient() {
412
335
  if (!_resilientClient) {
413
336
  throw new Error("Database client not initialized. Call initDatabase() first.");
414
337
  }
415
338
  return _resilientClient;
416
339
  }
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;
340
+ var _resilientClient;
1243
341
  var init_database = __esm({
1244
342
  "src/lib/database.ts"() {
1245
343
  "use strict";
1246
344
  init_db_retry();
1247
- _client = null;
1248
345
  _resilientClient = null;
1249
- initTurso = initDatabase;
1250
- disposeTurso = disposeDatabase;
1251
346
  }
1252
347
  });
1253
348
 
@@ -1271,13 +366,50 @@ var init_compress = __esm({
1271
366
  }
1272
367
  });
1273
368
 
369
+ // src/lib/license.ts
370
+ import { readFileSync as readFileSync2, writeFileSync, existsSync as existsSync3, mkdirSync } from "fs";
371
+ import { randomUUID } from "crypto";
372
+ import path3 from "path";
373
+ import { jwtVerify, importSPKI } from "jose";
374
+ function loadDeviceId() {
375
+ const deviceJsonPath = path3.join(EXE_AI_DIR, "device.json");
376
+ try {
377
+ if (existsSync3(deviceJsonPath)) {
378
+ const data = JSON.parse(readFileSync2(deviceJsonPath, "utf8"));
379
+ if (data.deviceId) return data.deviceId;
380
+ }
381
+ } catch {
382
+ }
383
+ try {
384
+ if (existsSync3(DEVICE_ID_PATH)) {
385
+ const id2 = readFileSync2(DEVICE_ID_PATH, "utf8").trim();
386
+ if (id2) return id2;
387
+ }
388
+ } catch {
389
+ }
390
+ const id = randomUUID();
391
+ mkdirSync(EXE_AI_DIR, { recursive: true });
392
+ writeFileSync(DEVICE_ID_PATH, id, "utf8");
393
+ return id;
394
+ }
395
+ var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH;
396
+ var init_license = __esm({
397
+ "src/lib/license.ts"() {
398
+ "use strict";
399
+ init_config();
400
+ LICENSE_PATH = path3.join(EXE_AI_DIR, "license.key");
401
+ CACHE_PATH = path3.join(EXE_AI_DIR, "license-cache.json");
402
+ DEVICE_ID_PATH = path3.join(EXE_AI_DIR, "device-id");
403
+ }
404
+ });
405
+
1274
406
  // src/lib/employees.ts
1275
407
  import { readFile as readFile3, writeFile as writeFile3, mkdir as mkdir3 } from "fs/promises";
1276
- import { existsSync as existsSync3, symlinkSync, readlinkSync, readFileSync as readFileSync2 } from "fs";
408
+ import { existsSync as existsSync4, symlinkSync, readlinkSync, readFileSync as readFileSync3 } from "fs";
1277
409
  import { execSync } from "child_process";
1278
- import path3 from "path";
410
+ import path4 from "path";
1279
411
  async function loadEmployees(employeesPath = EMPLOYEES_PATH) {
1280
- if (!existsSync3(employeesPath)) {
412
+ if (!existsSync4(employeesPath)) {
1281
413
  return [];
1282
414
  }
1283
415
  const raw = await readFile3(employeesPath, "utf-8");
@@ -1288,7 +420,7 @@ async function loadEmployees(employeesPath = EMPLOYEES_PATH) {
1288
420
  }
1289
421
  }
1290
422
  async function saveEmployees(employees, employeesPath = EMPLOYEES_PATH) {
1291
- await mkdir3(path3.dirname(employeesPath), { recursive: true });
423
+ await mkdir3(path4.dirname(employeesPath), { recursive: true });
1292
424
  await writeFile3(employeesPath, JSON.stringify(employees, null, 2) + "\n", "utf-8");
1293
425
  }
1294
426
  function findExeBin() {
@@ -1307,7 +439,7 @@ function registerBinSymlinks(name) {
1307
439
  errors.push("Could not find 'exe-os' in PATH");
1308
440
  return { created, skipped, errors };
1309
441
  }
1310
- const binDir = path3.dirname(exeBinPath);
442
+ const binDir = path4.dirname(exeBinPath);
1311
443
  let target;
1312
444
  try {
1313
445
  target = readlinkSync(exeBinPath);
@@ -1317,8 +449,8 @@ function registerBinSymlinks(name) {
1317
449
  }
1318
450
  for (const suffix of ["", "-opencode"]) {
1319
451
  const linkName = `${name}${suffix}`;
1320
- const linkPath = path3.join(binDir, linkName);
1321
- if (existsSync3(linkPath)) {
452
+ const linkPath = path4.join(binDir, linkName);
453
+ if (existsSync4(linkPath)) {
1322
454
  skipped.push(linkName);
1323
455
  continue;
1324
456
  }
@@ -1336,237 +468,7 @@ var init_employees = __esm({
1336
468
  "src/lib/employees.ts"() {
1337
469
  "use strict";
1338
470
  init_config();
1339
- EMPLOYEES_PATH = path3.join(EXE_AI_DIR, "exe-employees.json");
1340
- }
1341
- });
1342
-
1343
- // src/lib/license.ts
1344
- import { readFileSync as readFileSync3, writeFileSync, existsSync as existsSync4, mkdirSync } from "fs";
1345
- import { randomUUID } from "crypto";
1346
- import path4 from "path";
1347
- import { jwtVerify, importSPKI } from "jose";
1348
- async function fetchRetry(url, init) {
1349
- try {
1350
- return await fetch(url, init);
1351
- } catch {
1352
- await new Promise((r) => setTimeout(r, RETRY_DELAY_MS));
1353
- return fetch(url, { ...init, signal: AbortSignal.timeout(1e4) });
1354
- }
1355
- }
1356
- function loadDeviceId() {
1357
- const deviceJsonPath = path4.join(EXE_AI_DIR, "device.json");
1358
- try {
1359
- if (existsSync4(deviceJsonPath)) {
1360
- const data = JSON.parse(readFileSync3(deviceJsonPath, "utf8"));
1361
- if (data.deviceId) return data.deviceId;
1362
- }
1363
- } catch {
1364
- }
1365
- try {
1366
- if (existsSync4(DEVICE_ID_PATH)) {
1367
- const id2 = readFileSync3(DEVICE_ID_PATH, "utf8").trim();
1368
- if (id2) return id2;
1369
- }
1370
- } catch {
1371
- }
1372
- const id = randomUUID();
1373
- mkdirSync(EXE_AI_DIR, { recursive: true });
1374
- writeFileSync(DEVICE_ID_PATH, id, "utf8");
1375
- return id;
1376
- }
1377
- function loadLicense() {
1378
- try {
1379
- if (!existsSync4(LICENSE_PATH)) return null;
1380
- return readFileSync3(LICENSE_PATH, "utf8").trim();
1381
- } catch {
1382
- return null;
1383
- }
1384
- }
1385
- function saveLicense(apiKey) {
1386
- mkdirSync(EXE_AI_DIR, { recursive: true });
1387
- writeFileSync(LICENSE_PATH, apiKey.trim(), { encoding: "utf8", mode: 384 });
1388
- }
1389
- async function verifyLicenseJwt(token) {
1390
- try {
1391
- const key = await importSPKI(LICENSE_PUBLIC_KEY_PEM, LICENSE_JWT_ALG);
1392
- const { payload } = await jwtVerify(token, key, {
1393
- algorithms: [LICENSE_JWT_ALG]
1394
- });
1395
- const plan = payload.plan ?? "free";
1396
- const email = payload.sub ?? "";
1397
- const limits = PLAN_LIMITS[plan] ?? PLAN_LIMITS.free;
1398
- return {
1399
- valid: true,
1400
- plan,
1401
- email,
1402
- expiresAt: payload.exp ? new Date(payload.exp * 1e3).toISOString() : null,
1403
- deviceLimit: limits.devices,
1404
- employeeLimit: limits.employees,
1405
- memoryLimit: limits.memories
1406
- };
1407
- } catch {
1408
- return null;
1409
- }
1410
- }
1411
- async function getCachedLicense() {
1412
- try {
1413
- if (!existsSync4(CACHE_PATH)) return null;
1414
- const raw = JSON.parse(readFileSync3(CACHE_PATH, "utf8"));
1415
- if (!raw.token || typeof raw.token !== "string") return null;
1416
- return await verifyLicenseJwt(raw.token);
1417
- } catch {
1418
- return null;
1419
- }
1420
- }
1421
- function cacheResponse(token) {
1422
- try {
1423
- writeFileSync(CACHE_PATH, JSON.stringify({ token }), "utf8");
1424
- } catch {
1425
- }
1426
- }
1427
- async function validateLicense(apiKey, deviceId) {
1428
- const did = deviceId ?? loadDeviceId();
1429
- try {
1430
- const res = await fetchRetry(`${API_BASE}/auth/activate`, {
1431
- method: "POST",
1432
- headers: { "Content-Type": "application/json" },
1433
- body: JSON.stringify({ apiKey, deviceId: did }),
1434
- signal: AbortSignal.timeout(1e4)
1435
- });
1436
- if (res.ok) {
1437
- const data = await res.json();
1438
- if (data.error === "device_limit_exceeded") {
1439
- const cached2 = await getCachedLicense();
1440
- if (cached2) return cached2;
1441
- return { ...FREE_LICENSE, valid: false, plan: "free" };
1442
- }
1443
- if (data.token) {
1444
- cacheResponse(data.token);
1445
- const verified = await verifyLicenseJwt(data.token);
1446
- if (verified) return verified;
1447
- }
1448
- const limits = PLAN_LIMITS[data.plan] ?? PLAN_LIMITS.free;
1449
- return {
1450
- valid: data.valid,
1451
- plan: data.plan,
1452
- email: data.email,
1453
- expiresAt: data.expiresAt,
1454
- deviceLimit: limits.devices,
1455
- employeeLimit: limits.employees,
1456
- memoryLimit: limits.memories
1457
- };
1458
- }
1459
- const cached = await getCachedLicense();
1460
- if (cached) return cached;
1461
- return { ...FREE_LICENSE, valid: false, plan: "free" };
1462
- } catch {
1463
- const cached = await getCachedLicense();
1464
- if (cached) return cached;
1465
- return { ...FREE_LICENSE, valid: false, error: "offline" };
1466
- }
1467
- }
1468
- function getCacheAgeMs() {
1469
- try {
1470
- const { statSync } = __require("fs");
1471
- const s = statSync(CACHE_PATH);
1472
- return Date.now() - s.mtimeMs;
1473
- } catch {
1474
- return Infinity;
1475
- }
1476
- }
1477
- async function checkLicense() {
1478
- let key = loadLicense();
1479
- if (!key) {
1480
- try {
1481
- const configPath = path4.join(EXE_AI_DIR, "config.json");
1482
- if (existsSync4(configPath)) {
1483
- const raw = JSON.parse(readFileSync3(configPath, "utf8"));
1484
- const cloud = raw.cloud;
1485
- if (cloud?.apiKey) {
1486
- key = cloud.apiKey;
1487
- saveLicense(key);
1488
- }
1489
- }
1490
- } catch {
1491
- }
1492
- }
1493
- if (!key) return FREE_LICENSE;
1494
- const cached = await getCachedLicense();
1495
- if (cached && getCacheAgeMs() < CACHE_MAX_AGE_MS) return cached;
1496
- const deviceId = loadDeviceId();
1497
- return validateLicense(key, deviceId);
1498
- }
1499
- function isFeatureAllowed(license, feature) {
1500
- switch (feature) {
1501
- case "cloud_sync":
1502
- case "external_agents":
1503
- case "wiki":
1504
- return license.plan !== "free";
1505
- case "unlimited_employees":
1506
- return license.plan === "team" || license.plan === "agency" || license.plan === "enterprise";
1507
- }
1508
- }
1509
- 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;
1510
- var init_license = __esm({
1511
- "src/lib/license.ts"() {
1512
- "use strict";
1513
- init_config();
1514
- LICENSE_PATH = path4.join(EXE_AI_DIR, "license.key");
1515
- CACHE_PATH = path4.join(EXE_AI_DIR, "license-cache.json");
1516
- DEVICE_ID_PATH = path4.join(EXE_AI_DIR, "device-id");
1517
- API_BASE = "https://askexe.com/cloud";
1518
- RETRY_DELAY_MS = 500;
1519
- LICENSE_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
1520
- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEeHztAMOpR/ZMh+rWuOASjEZ54CGY
1521
- 4uj+UqeKCcvtgNHKmOK278HJaJcANe9xAeji8AFYu27q3WtzCi04pHudow==
1522
- -----END PUBLIC KEY-----`;
1523
- LICENSE_JWT_ALG = "ES256";
1524
- PLAN_LIMITS = {
1525
- free: { devices: 1, employees: 1, memories: 5e3 },
1526
- pro: { devices: 2, employees: 5, memories: 1e5 },
1527
- team: { devices: 10, employees: 20, memories: 1e6 },
1528
- agency: { devices: 50, employees: 100, memories: 1e7 },
1529
- enterprise: { devices: -1, employees: -1, memories: -1 }
1530
- };
1531
- FREE_LICENSE = {
1532
- valid: true,
1533
- plan: "free",
1534
- email: "",
1535
- expiresAt: null,
1536
- deviceLimit: 1,
1537
- employeeLimit: 1,
1538
- memoryLimit: 5e3
1539
- };
1540
- CACHE_MAX_AGE_MS = 36e5;
1541
- }
1542
- });
1543
-
1544
- // src/lib/plan-limits.ts
1545
- import { readFileSync as readFileSync4, existsSync as existsSync5 } from "fs";
1546
- import path5 from "path";
1547
- async function assertFeature(feature) {
1548
- const license = await checkLicense();
1549
- if (!isFeatureAllowed(license, feature)) {
1550
- throw new PlanLimitError(
1551
- `Feature "${feature}" requires a paid plan. Current plan: ${license.plan}. Upgrade at https://askexe.com.`
1552
- );
1553
- }
1554
- }
1555
- var PlanLimitError, CACHE_PATH2;
1556
- var init_plan_limits = __esm({
1557
- "src/lib/plan-limits.ts"() {
1558
- "use strict";
1559
- init_database();
1560
- init_employees();
1561
- init_license();
1562
- init_config();
1563
- PlanLimitError = class extends Error {
1564
- constructor(message) {
1565
- super(message);
1566
- this.name = "PlanLimitError";
1567
- }
1568
- };
1569
- CACHE_PATH2 = path5.join(EXE_AI_DIR, "license-cache.json");
471
+ EMPLOYEES_PATH = path4.join(EXE_AI_DIR, "exe-employees.json");
1570
472
  }
1571
473
  });
1572
474
 
@@ -1596,13 +498,13 @@ __export(cloud_sync_exports, {
1596
498
  mergeRosterFromRemote: () => mergeRosterFromRemote,
1597
499
  recordRosterDeletion: () => recordRosterDeletion
1598
500
  });
1599
- import { readFileSync as readFileSync5, writeFileSync as writeFileSync2, existsSync as existsSync6, readdirSync, mkdirSync as mkdirSync2, appendFileSync, unlinkSync, openSync, closeSync } from "fs";
501
+ import { readFileSync as readFileSync4, writeFileSync as writeFileSync2, existsSync as existsSync5, readdirSync, mkdirSync as mkdirSync2, appendFileSync, unlinkSync, openSync, closeSync } from "fs";
1600
502
  import crypto3 from "crypto";
1601
- import path6 from "path";
503
+ import path5 from "path";
1602
504
  import { homedir } from "os";
1603
505
  function logError(msg) {
1604
506
  try {
1605
- const logPath = path6.join(homedir(), ".exe-os", "workers.log");
507
+ const logPath = path5.join(homedir(), ".exe-os", "workers.log");
1606
508
  appendFileSync(logPath, `${(/* @__PURE__ */ new Date()).toISOString()} ${msg}
1607
509
  `);
1608
510
  } catch {
@@ -1616,7 +518,7 @@ async function withRosterLock(fn) {
1616
518
  } catch (err) {
1617
519
  if (err.code === "EEXIST") {
1618
520
  try {
1619
- const ts = parseInt(readFileSync5(ROSTER_LOCK_PATH, "utf-8"), 10);
521
+ const ts = parseInt(readFileSync4(ROSTER_LOCK_PATH, "utf-8"), 10);
1620
522
  if (Date.now() - ts < LOCK_STALE_MS) {
1621
523
  throw new Error("Roster merge already in progress \u2014 another sync is running");
1622
524
  }
@@ -1642,22 +544,22 @@ async function withRosterLock(fn) {
1642
544
  }
1643
545
  }
1644
546
  async function fetchWithRetry(url, init) {
1645
- const MAX_RETRIES2 = 3;
1646
- const BASE_DELAY_MS2 = 200;
547
+ const MAX_RETRIES = 3;
548
+ const BASE_DELAY_MS = 200;
1647
549
  let lastError;
1648
- for (let attempt = 0; attempt <= MAX_RETRIES2; attempt++) {
550
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
1649
551
  try {
1650
552
  const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS);
1651
553
  const resp = await fetch(url, { ...init, signal });
1652
- if (resp && resp.status >= 500 && attempt < MAX_RETRIES2) {
1653
- await new Promise((r) => setTimeout(r, BASE_DELAY_MS2 * Math.pow(2, attempt)));
554
+ if (resp && resp.status >= 500 && attempt < MAX_RETRIES) {
555
+ await new Promise((r) => setTimeout(r, BASE_DELAY_MS * Math.pow(2, attempt)));
1654
556
  continue;
1655
557
  }
1656
558
  return resp;
1657
559
  } catch (err) {
1658
560
  lastError = err;
1659
- if (attempt === MAX_RETRIES2) throw err;
1660
- await new Promise((r) => setTimeout(r, BASE_DELAY_MS2 * Math.pow(2, attempt)));
561
+ if (attempt === MAX_RETRIES) throw err;
562
+ await new Promise((r) => setTimeout(r, BASE_DELAY_MS * Math.pow(2, attempt)));
1661
563
  }
1662
564
  }
1663
565
  throw lastError;
@@ -1743,26 +645,22 @@ async function cloudPull(sinceVersion, config) {
1743
645
  }
1744
646
  }
1745
647
  async function cloudSync(config) {
1746
- await assertFeature("cloud_sync");
1747
648
  let client;
1748
649
  try {
1749
650
  client = getClient();
1750
651
  } catch {
1751
652
  throw new Error("[cloud-sync] Database not initialized. Call initStore() before cloudSync().");
1752
653
  }
1753
- let pullMeta;
1754
654
  try {
1755
- pullMeta = await client.execute(
1756
- "SELECT value FROM sync_meta WHERE key = 'last_cloud_pull_version'"
655
+ await client.execute(
656
+ "CREATE TABLE IF NOT EXISTS sync_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)"
1757
657
  );
1758
658
  } catch (e) {
1759
- logError(`[cloud-sync] sync_meta read failed (${e instanceof Error ? e.message : String(e)}), attempting ensureSchema`);
1760
- const { ensureSchema: ensureSchema2 } = await Promise.resolve().then(() => (init_database(), database_exports));
1761
- await ensureSchema2();
1762
- pullMeta = await client.execute(
1763
- "SELECT value FROM sync_meta WHERE key = 'last_cloud_pull_version'"
1764
- );
659
+ logError(`[cloud-sync] sync_meta CREATE failed: ${e instanceof Error ? e.message : String(e)}`);
1765
660
  }
661
+ const pullMeta = await client.execute(
662
+ "SELECT value FROM sync_meta WHERE key = 'last_cloud_pull_version'"
663
+ );
1766
664
  const lastPullVersion = pullMeta.rows.length > 0 ? Number(pullMeta.rows[0].value) : 0;
1767
665
  const pullResult = await cloudPull(lastPullVersion, config);
1768
666
  let pulled = 0;
@@ -1924,8 +822,8 @@ async function cloudSync(config) {
1924
822
  function recordRosterDeletion(name) {
1925
823
  let deletions = [];
1926
824
  try {
1927
- if (existsSync6(ROSTER_DELETIONS_PATH)) {
1928
- deletions = JSON.parse(readFileSync5(ROSTER_DELETIONS_PATH, "utf-8"));
825
+ if (existsSync5(ROSTER_DELETIONS_PATH)) {
826
+ deletions = JSON.parse(readFileSync4(ROSTER_DELETIONS_PATH, "utf-8"));
1929
827
  }
1930
828
  } catch {
1931
829
  }
@@ -1934,8 +832,8 @@ function recordRosterDeletion(name) {
1934
832
  }
1935
833
  function consumeRosterDeletions() {
1936
834
  try {
1937
- if (!existsSync6(ROSTER_DELETIONS_PATH)) return [];
1938
- const deletions = JSON.parse(readFileSync5(ROSTER_DELETIONS_PATH, "utf-8"));
835
+ if (!existsSync5(ROSTER_DELETIONS_PATH)) return [];
836
+ const deletions = JSON.parse(readFileSync4(ROSTER_DELETIONS_PATH, "utf-8"));
1939
837
  writeFileSync2(ROSTER_DELETIONS_PATH, "[]");
1940
838
  return deletions;
1941
839
  } catch {
@@ -1943,29 +841,29 @@ function consumeRosterDeletions() {
1943
841
  }
1944
842
  }
1945
843
  function buildRosterBlob(paths) {
1946
- const rosterPath = paths?.rosterPath ?? path6.join(EXE_AI_DIR, "exe-employees.json");
1947
- const identityDir = paths?.identityDir ?? path6.join(EXE_AI_DIR, "identity");
1948
- const configPath = paths?.configPath ?? path6.join(EXE_AI_DIR, "config.json");
844
+ const rosterPath = paths?.rosterPath ?? path5.join(EXE_AI_DIR, "exe-employees.json");
845
+ const identityDir = paths?.identityDir ?? path5.join(EXE_AI_DIR, "identity");
846
+ const configPath = paths?.configPath ?? path5.join(EXE_AI_DIR, "config.json");
1949
847
  let roster = [];
1950
- if (existsSync6(rosterPath)) {
848
+ if (existsSync5(rosterPath)) {
1951
849
  try {
1952
- roster = JSON.parse(readFileSync5(rosterPath, "utf-8"));
850
+ roster = JSON.parse(readFileSync4(rosterPath, "utf-8"));
1953
851
  } catch {
1954
852
  }
1955
853
  }
1956
854
  const identities = {};
1957
- if (existsSync6(identityDir)) {
855
+ if (existsSync5(identityDir)) {
1958
856
  for (const file of readdirSync(identityDir).filter((f) => f.endsWith(".md"))) {
1959
857
  try {
1960
- identities[file] = readFileSync5(path6.join(identityDir, file), "utf-8");
858
+ identities[file] = readFileSync4(path5.join(identityDir, file), "utf-8");
1961
859
  } catch {
1962
860
  }
1963
861
  }
1964
862
  }
1965
863
  let config;
1966
- if (existsSync6(configPath)) {
864
+ if (existsSync5(configPath)) {
1967
865
  try {
1968
- config = JSON.parse(readFileSync5(configPath, "utf-8"));
866
+ config = JSON.parse(readFileSync4(configPath, "utf-8"));
1969
867
  } catch {
1970
868
  }
1971
869
  }
@@ -2041,23 +939,23 @@ async function cloudPullRoster(config) {
2041
939
  }
2042
940
  }
2043
941
  function mergeConfig(remoteConfig, configPath) {
2044
- const cfgPath = configPath ?? path6.join(EXE_AI_DIR, "config.json");
942
+ const cfgPath = configPath ?? path5.join(EXE_AI_DIR, "config.json");
2045
943
  let local = {};
2046
- if (existsSync6(cfgPath)) {
944
+ if (existsSync5(cfgPath)) {
2047
945
  try {
2048
- local = JSON.parse(readFileSync5(cfgPath, "utf-8"));
946
+ local = JSON.parse(readFileSync4(cfgPath, "utf-8"));
2049
947
  } catch {
2050
948
  }
2051
949
  }
2052
950
  const merged = { ...remoteConfig, ...local };
2053
- const dir = path6.dirname(cfgPath);
2054
- if (!existsSync6(dir)) mkdirSync2(dir, { recursive: true });
951
+ const dir = path5.dirname(cfgPath);
952
+ if (!existsSync5(dir)) mkdirSync2(dir, { recursive: true });
2055
953
  writeFileSync2(cfgPath, JSON.stringify(merged, null, 2), "utf-8");
2056
954
  }
2057
955
  async function mergeRosterFromRemote(remote, paths) {
2058
956
  return withRosterLock(async () => {
2059
957
  const rosterPath = paths?.rosterPath ?? void 0;
2060
- const identityDir = paths?.identityDir ?? path6.join(EXE_AI_DIR, "identity");
958
+ const identityDir = paths?.identityDir ?? path5.join(EXE_AI_DIR, "identity");
2061
959
  const localEmployees = await loadEmployees(rosterPath);
2062
960
  const localNames = new Set(localEmployees.map((e) => e.name));
2063
961
  let added = 0;
@@ -2067,9 +965,9 @@ async function mergeRosterFromRemote(remote, paths) {
2067
965
  localNames.add(remoteEmp.name);
2068
966
  added++;
2069
967
  if (remote.identities[`${remoteEmp.name}.md`]) {
2070
- if (!existsSync6(identityDir)) mkdirSync2(identityDir, { recursive: true });
2071
- const idPath = path6.join(identityDir, `${remoteEmp.name}.md`);
2072
- if (!existsSync6(idPath)) {
968
+ if (!existsSync5(identityDir)) mkdirSync2(identityDir, { recursive: true });
969
+ const idPath = path5.join(identityDir, `${remoteEmp.name}.md`);
970
+ if (!existsSync5(idPath)) {
2073
971
  writeFileSync2(idPath, remote.identities[`${remoteEmp.name}.md`], "utf-8");
2074
972
  }
2075
973
  }
@@ -2479,16 +1377,15 @@ var init_cloud_sync = __esm({
2479
1377
  init_database();
2480
1378
  init_crypto();
2481
1379
  init_compress();
2482
- init_plan_limits();
2483
1380
  init_license();
2484
1381
  init_config();
2485
1382
  init_employees();
2486
1383
  LOCALHOST_PATTERNS = /^(localhost|127\.0\.0\.1|\[::1\])$/i;
2487
1384
  FETCH_TIMEOUT_MS = 3e4;
2488
1385
  PUSH_BATCH_SIZE = 5e3;
2489
- ROSTER_LOCK_PATH = path6.join(EXE_AI_DIR, "roster-merge.lock");
1386
+ ROSTER_LOCK_PATH = path5.join(EXE_AI_DIR, "roster-merge.lock");
2490
1387
  LOCK_STALE_MS = 3e4;
2491
- ROSTER_DELETIONS_PATH = path6.join(EXE_AI_DIR, "roster-deletions.json");
1388
+ ROSTER_DELETIONS_PATH = path5.join(EXE_AI_DIR, "roster-deletions.json");
2492
1389
  }
2493
1390
  });
2494
1391