adam-agent-server 1.5.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/dist/App-ZRCRM7WR.js +13 -0
  2. package/dist/adam-automator-skills-EZGBICHT.js +18 -0
  3. package/dist/adam-tools-V5LPU47X.js +1 -0
  4. package/dist/approval-handler-PB7PSLUS.js +1 -0
  5. package/dist/audit-manager-BSBBDUER.js +1 -0
  6. package/dist/bree-engine-7S33CWS7.js +1 -0
  7. package/dist/channels-SITUUC4J.js +1 -0
  8. package/dist/{channels-HYSB2EEK.js → channels-ULFUCUUZ.js} +1 -1
  9. package/dist/{chunk-Y3AMO6WC.js → chunk-2L2347UQ.js} +1 -1
  10. package/dist/{chunk-2DLVAKH7.js → chunk-2YTDCR6A.js} +1 -1
  11. package/dist/chunk-4PQHGLZH.js +99 -0
  12. package/dist/{chunk-JAS3TUZX.js → chunk-5EPG2US5.js} +26 -7
  13. package/dist/{chunk-BR2JY5X2.js → chunk-5QZXYKMS.js} +1 -1
  14. package/dist/chunk-5XOTPEAK.js +6 -0
  15. package/dist/{chunk-6775OYXA.js → chunk-6KF7OO2B.js} +1 -1
  16. package/dist/{chunk-5S6BMWD2.js → chunk-A5OCDYTW.js} +1 -1
  17. package/dist/{chunk-5XUR3M23.js → chunk-AQ3ASS4B.js} +1 -1
  18. package/dist/{chunk-HDP7A4XY.js → chunk-B6LOT5CG.js} +1 -1
  19. package/dist/chunk-BCH2HAIM.js +23 -0
  20. package/dist/{chunk-YVS565QY.js → chunk-BQ3ZAYHC.js} +1 -1
  21. package/dist/{chunk-C6BOQJJF.js → chunk-DVN3BFPP.js} +1 -1
  22. package/dist/{chunk-H7VDC6FY.js → chunk-EQZFOBAJ.js} +1 -1
  23. package/dist/{chunk-7L2WQM7N.js → chunk-FPZEZYUB.js} +1 -1
  24. package/dist/{chunk-23VZKIB6.js → chunk-GSFLLRS7.js} +1 -1
  25. package/dist/{chunk-GBTG5B5R.js → chunk-HQRUJQN7.js} +1 -1
  26. package/dist/{chunk-R4GIIQ7G.js → chunk-IKPYPZ64.js} +1 -1
  27. package/dist/{chunk-5V36ACKZ.js → chunk-IZNEOYRP.js} +1 -1
  28. package/dist/{chunk-6FXNB7NE.js → chunk-JJH2RCVC.js} +1 -1
  29. package/dist/chunk-K4C43YDD.js +7 -0
  30. package/dist/{chunk-Z4D3L2HR.js → chunk-M4YI4WVX.js} +1 -1
  31. package/dist/{chunk-INNDBLZE.js → chunk-MRTJFYPR.js} +1 -1
  32. package/dist/{chunk-YHVFZB6Q.js → chunk-N4ES7TCL.js} +1 -1
  33. package/dist/{chunk-HTPUEIFT.js → chunk-NASJH4NT.js} +5 -5
  34. package/dist/{chunk-H54ZXA26.js → chunk-NUITL62I.js} +1 -1
  35. package/dist/{chunk-VRJ7R766.js → chunk-NWMOV23A.js} +1 -1
  36. package/dist/{chunk-7K4AQBDD.js → chunk-PG6LMSX6.js} +1 -1
  37. package/dist/chunk-PHT24MOV.js +1 -0
  38. package/dist/chunk-QGYDGZSC.js +49 -0
  39. package/dist/{chunk-XL46AGRZ.js → chunk-RI3V72RP.js} +2 -2
  40. package/dist/{chunk-QVKI7H7W.js → chunk-RZ7LCZVK.js} +1 -1
  41. package/dist/{chunk-2CMR5AG7.js → chunk-SWP2JC54.js} +1 -1
  42. package/dist/chunk-TAF2DBBC.js +79 -0
  43. package/dist/chunk-ULTK7RD6.js +27 -0
  44. package/dist/{chunk-QWCRZDZS.js → chunk-WMB7P64J.js} +2 -2
  45. package/dist/cli.js +2 -2
  46. package/dist/{config-EMNKHR3W.js → config-HBQPBIWL.js} +1 -1
  47. package/dist/config-ZBNGRASI.js +1 -0
  48. package/dist/db-QEWTZGU3.js +1 -0
  49. package/dist/delivery-log-AC476GX7.js +1 -0
  50. package/dist/engine-6K4RG644.js +1 -0
  51. package/dist/{evolution-audit-LZSQPDHH.js → evolution-audit-XMBDUN3T.js} +1 -1
  52. package/dist/{external-api-7XV2PXPC.js → external-api-V74YTLBY.js} +1 -1
  53. package/dist/index.js +19 -13
  54. package/dist/{learner-IJN6B7KV.js → learner-VCS3Q7BR.js} +1 -1
  55. package/dist/{logger-QCJUU7GV.js → logger-WEXZORHP.js} +1 -1
  56. package/dist/{memories-ZII5QSTJ.js → memories-VMOGFVPU.js} +1 -1
  57. package/dist/{memory-extractor-DIYJFBCI.js → memory-extractor-4WJNHYWR.js} +2 -2
  58. package/dist/memory-service-ZS6MBUIC.js +1 -0
  59. package/dist/outbound-gateway-H7RFG6D2.js +1 -0
  60. package/dist/role-presets-XAEOYEAW.js +1 -0
  61. package/dist/role-workspace-NKGAH6J6.js +1 -0
  62. package/dist/roles-ZYCFQMAY.js +1 -0
  63. package/dist/session-manager-COLCNIB7.js +1 -0
  64. package/dist/task-templates-4KCZOUN5.js +1 -0
  65. package/dist/workflow-executor-Z7JFMR56.js +1 -0
  66. package/package.json +25 -25
  67. package/web/dist/assets/{AlertDialog-r3y6IhpW.js → AlertDialog-CfeiyMrc.js} +1 -1
  68. package/web/dist/assets/{Button-BjXgrQ95.js → Button-DuQctNms.js} +1 -1
  69. package/web/dist/assets/{Card-C153tGfJ.js → Card-rKfViPS2.js} +1 -1
  70. package/web/dist/assets/{ChannelDetail-C2uAZv1u.js → ChannelDetail-DnL0_h8q.js} +1 -1
  71. package/web/dist/assets/{Channels-C62Qrg-n.js → Channels-dod8Q4oq.js} +2 -2
  72. package/web/dist/assets/{Chat-kH2owmB_.js → Chat-Dv_Izjx3.js} +1 -1
  73. package/web/dist/assets/{Dashboard-BhD8SpFb.js → Dashboard-Dl0vA6Ky.js} +1 -1
  74. package/web/dist/assets/{EmptyState-CXwJFCDQ.js → EmptyState-CIdIlMbn.js} +1 -1
  75. package/web/dist/assets/{EnvVarEditor-GSapLD96.js → EnvVarEditor-C-gErAzC.js} +1 -1
  76. package/web/dist/assets/EventDefDetail-BhJZGNlX.js +1 -0
  77. package/web/dist/assets/Events-DnNZ9-BN.js +1 -0
  78. package/web/dist/assets/{Evolution-BO5hysLD.js → Evolution-BBWmrrnr.js} +1 -1
  79. package/web/dist/assets/{GoalDetail-cxa8OvEi.js → GoalDetail-uqWQCOj3.js} +1 -1
  80. package/web/dist/assets/{Goals-Dz3qqp_l.js → Goals-CylKmR9j.js} +1 -1
  81. package/web/dist/assets/{Logs-Ckp3-hYV.js → Logs-6rf0KT0z.js} +1 -1
  82. package/web/dist/assets/{Memories-DEuSRoP3.js → Memories-CrBTujU7.js} +1 -1
  83. package/web/dist/assets/{NotFound-Bvn39vSk.js → NotFound-DitXhq_y.js} +1 -1
  84. package/web/dist/assets/{PageHeader-BMvN0xiB.js → PageHeader-CHSgtxPw.js} +1 -1
  85. package/web/dist/assets/Plugins-VKUSUcSE.js +1 -0
  86. package/web/dist/assets/{RoleDetail-BWMjP9aZ.js → RoleDetail-DJc4CWFN.js} +2 -2
  87. package/web/dist/assets/{Roles-DD7NBDku.js → Roles-6pmjn04G.js} +1 -1
  88. package/web/dist/assets/{SectionHeader-CiCj3Is0.js → SectionHeader-C2WpiwJ5.js} +1 -1
  89. package/web/dist/assets/{Settings-BlU19KuR.js → Settings-DW1jmrNj.js} +1 -1
  90. package/web/dist/assets/{Strategies-CJ_q94-v.js → Strategies-Bmke6qZo.js} +1 -1
  91. package/web/dist/assets/{Switch-CoUUy5jr.js → Switch-CfTpXW9_.js} +1 -1
  92. package/web/dist/assets/{Table-CaFJieh_.js → Table-DuOLbyJQ.js} +1 -1
  93. package/web/dist/assets/{TaskDetail-DVrjU-E6.js → TaskDetail-CwJ_UKgt.js} +2 -2
  94. package/web/dist/assets/Work-DVdWNBEm.js +1 -0
  95. package/web/dist/assets/index-D4IubNPI.css +2 -0
  96. package/web/dist/assets/index-DYsO5Awn.js +2 -0
  97. package/web/dist/assets/{useIsMobileLayout-Bwrm84kJ.js → useIsMobileLayout-C6KIQjuh.js} +1 -1
  98. package/web/dist/assets/{vendor-icons-BlMaTTx3.js → vendor-icons-Dk0hMuJz.js} +1 -1
  99. package/web/dist/assets/{vendor-react-7e01TWy7.js → vendor-react-C6faO6LO.js} +1 -1
  100. package/web/dist/assets/{vendor-state-Bj70wnRm.js → vendor-state-DahK0J-G.js} +1 -1
  101. package/web/dist/index.html +7 -7
  102. package/dist/App-JGH6G5US.js +0 -13
  103. package/dist/adam-tools-W5AOIGEQ.js +0 -1
  104. package/dist/approval-handler-ORD4MUVM.js +0 -1
  105. package/dist/audit-manager-YCJT2WP5.js +0 -1
  106. package/dist/bree-engine-R5YLSDCL.js +0 -1
  107. package/dist/channels-JCMPPQED.js +0 -1
  108. package/dist/chunk-2YAP4YJV.js +0 -57
  109. package/dist/chunk-DZEVMYPB.js +0 -19
  110. package/dist/chunk-GY52JA5I.js +0 -10
  111. package/dist/chunk-ISZJV72D.js +0 -7
  112. package/dist/chunk-MTWLLE26.js +0 -49
  113. package/dist/chunk-RAW263MQ.js +0 -99
  114. package/dist/chunk-S3BAIZ4Q.js +0 -6
  115. package/dist/chunk-VRP4LTHY.js +0 -1
  116. package/dist/config-XMQS2NPT.js +0 -1
  117. package/dist/db-YUYXVV3A.js +0 -1
  118. package/dist/delivery-log-VKONLSVD.js +0 -1
  119. package/dist/engine-BM5BMPIC.js +0 -1
  120. package/dist/memory-service-QMYJPBAE.js +0 -1
  121. package/dist/outbound-gateway-6K6P2BEH.js +0 -1
  122. package/dist/role-presets-K2BDRZBS.js +0 -1
  123. package/dist/roles-L34L5MK3.js +0 -1
  124. package/dist/session-manager-GRJ3FV3L.js +0 -1
  125. package/dist/task-templates-23YOAF3E.js +0 -1
  126. package/dist/workflow-executor-JTUWX5DC.js +0 -1
  127. package/web/dist/assets/Plugins-CRym22JF.js +0 -1
  128. package/web/dist/assets/Work-BMl61RRi.js +0 -1
  129. package/web/dist/assets/index-DcXMQByM.css +0 -2
  130. package/web/dist/assets/index-pF--tN9F.js +0 -2
@@ -1,4 +1,4 @@
1
- import{e as A,h as O}from"./chunk-WBAPIPST.js";import{c as R,h as X}from"./chunk-INNDBLZE.js";import{c as m}from"./chunk-FCV2DPZQ.js";import p from"better-sqlite3";import{existsSync as S,mkdirSync as u}from"fs";import{dirname as g}from"path";function D(e){e.exec(`
1
+ import{e as R,h as p}from"./chunk-WBAPIPST.js";import{c as m,h as O}from"./chunk-MRTJFYPR.js";import{c as I}from"./chunk-FCV2DPZQ.js";import X from"better-sqlite3";import{existsSync as S,mkdirSync as u}from"fs";import{dirname as g}from"path";function U(e){e.exec(`
2
2
  CREATE TABLE IF NOT EXISTS server_state (
3
3
  id INTEGER PRIMARY KEY CHECK(id = 1),
4
4
  sdk_session_id TEXT,
@@ -8,7 +8,7 @@ import{e as A,h as O}from"./chunk-WBAPIPST.js";import{c as R,h as X}from"./chunk
8
8
  created_at INTEGER NOT NULL DEFAULT (unixepoch('now') * 1000),
9
9
  last_active_at INTEGER
10
10
  );
11
- `),e.prepare("PRAGMA table_info(server_state)").all().some(E=>E.name==="schema_version")||e.exec("ALTER TABLE server_state ADD COLUMN schema_version INTEGER DEFAULT 0");let _=e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0;if(_<2){let E=["delivery_log","delivery_rules","manager_decisions","skill_scores","approval_rules","task_plans","calibration_history","task_plugins","marketplaces","plugins","trials","strategies","metric_tree","goals","chat_messages","chat_sessions","channels","evolution_audit","step_logs","task_templates","memories","tasks","config","memories_fts","memories_fts_config","memories_fts_data","memories_fts_docsize","memories_fts_idx"];for(let s of E)try{e.exec(`DROP TABLE IF EXISTS ${s}`)}catch{}for(let s of["memories_fts_insert","memories_fts_delete","memories_fts_update"])try{e.exec(`DROP TRIGGER IF EXISTS ${s}`)}catch{}}if(e.exec(`
11
+ `),e.prepare("PRAGMA table_info(server_state)").all().some(E=>E.name==="schema_version")||e.exec("ALTER TABLE server_state ADD COLUMN schema_version INTEGER DEFAULT 0");let o=e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0;if(o<2){let E=["delivery_log","delivery_rules","manager_decisions","skill_scores","approval_rules","task_plans","calibration_history","task_plugins","marketplaces","plugins","trials","strategies","metric_tree","goals","chat_messages","chat_sessions","channels","evolution_audit","step_logs","task_templates","memories","tasks","config","memories_fts","memories_fts_config","memories_fts_data","memories_fts_docsize","memories_fts_idx"];for(let s of E)try{e.exec(`DROP TABLE IF EXISTS ${s}`)}catch{}for(let s of["memories_fts_insert","memories_fts_delete","memories_fts_update"])try{e.exec(`DROP TRIGGER IF EXISTS ${s}`)}catch{}}if(e.exec(`
12
12
  CREATE TABLE IF NOT EXISTS tasks (
13
13
  id TEXT PRIMARY KEY,
14
14
  parent_id TEXT,
@@ -368,7 +368,7 @@ import{e as A,h as O}from"./chunk-WBAPIPST.js";import{c as R,h as X}from"./chunk
368
368
 
369
369
  CREATE INDEX IF NOT EXISTS idx_calibration_goal ON calibration_history(goal_id);
370
370
  CREATE INDEX IF NOT EXISTS idx_calibration_computed ON calibration_history(computed_at);
371
- `),_<2&&e.exec("UPDATE server_state SET schema_version = 2 WHERE id = 1"),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<4&&(e.exec(`
371
+ `),o<2&&e.exec("UPDATE server_state SET schema_version = 2 WHERE id = 1"),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<4&&(e.exec(`
372
372
  CREATE TABLE IF NOT EXISTS roles (
373
373
  id TEXT PRIMARY KEY,
374
374
  name TEXT NOT NULL UNIQUE,
@@ -567,7 +567,7 @@ import{e as A,h as O}from"./chunk-WBAPIPST.js";import{c as R,h as X}from"./chunk
567
567
  bound_at INTEGER NOT NULL,
568
568
  PRIMARY KEY (role_id, plugin_id)
569
569
  );
570
- `),e.exec("UPDATE server_state SET schema_version = 10 WHERE id = 1"),e.exec("PRAGMA foreign_keys = ON")}if(_<11){try{e.exec("ALTER TABLE task_templates RENAME COLUMN skill_preference TO role_preference")}catch(E){let s=e.prepare("PRAGMA table_info(task_templates)").all(),T=s.some(i=>i.name==="role_preference"),t=s.some(i=>i.name==="skill_preference");if(!T&&t)throw E}e.exec("UPDATE server_state SET schema_version = 11 WHERE id = 1")}if(_<12&&(e.prepare("PRAGMA table_info(server_state)").all().some(s=>s.name==="tools_fingerprint")||e.exec("ALTER TABLE server_state ADD COLUMN tools_fingerprint TEXT"),e.exec("UPDATE server_state SET schema_version = 12 WHERE id = 1")),_<13&&(e.prepare("PRAGMA table_info(roles)").all().some(s=>s.name==="additional_directories")||e.exec("ALTER TABLE roles ADD COLUMN additional_directories TEXT"),e.exec("UPDATE server_state SET schema_version = 13 WHERE id = 1")),_<14){let E=e.prepare("PRAGMA table_info(roles)").all();E.some(t=>t.name==="allowed_channels")||e.exec("ALTER TABLE roles ADD COLUMN allowed_channels TEXT"),E.some(t=>t.name==="mcp_servers")||e.exec("ALTER TABLE roles ADD COLUMN mcp_servers TEXT");let s=e.prepare("PRAGMA table_info(tasks)").all();s.some(t=>t.name==="deliver_to")||e.exec("ALTER TABLE tasks ADD COLUMN deliver_to TEXT"),s.some(t=>t.name==="report_to")||e.exec("ALTER TABLE tasks ADD COLUMN report_to TEXT"),e.prepare("PRAGMA table_info(goals)").all().some(t=>t.name==="deliver_to")||e.exec("ALTER TABLE goals ADD COLUMN deliver_to TEXT"),e.exec("UPDATE server_state SET schema_version = 14 WHERE id = 1")}if(_<15&&(e.prepare("PRAGMA table_info(roles)").all().some(s=>s.name==="inherit_user_settings")||e.exec("ALTER TABLE roles ADD COLUMN inherit_user_settings INTEGER DEFAULT 0"),e.exec("UPDATE server_state SET schema_version = 15 WHERE id = 1")),_<16&&(e.prepare("PRAGMA table_info(task_templates)").all().some(s=>s.name==="deliver_to")||e.exec("ALTER TABLE task_templates ADD COLUMN deliver_to TEXT"),e.exec("UPDATE server_state SET schema_version = 16 WHERE id = 1")),_<17){e.exec("PRAGMA foreign_keys = OFF"),e.exec("DROP TABLE IF EXISTS plugins"),e.exec("DROP TABLE IF EXISTS role_plugins"),e.exec("DROP TABLE IF EXISTS marketplaces"),e.exec("DROP INDEX IF EXISTS idx_plugins_source"),e.exec("DROP INDEX IF EXISTS idx_plugins_enabled");try{let T=e.prepare("SELECT id, additional_directories FROM roles WHERE additional_directories IS NOT NULL").all();for(let t of T)try{let i=JSON.parse(t.additional_directories);if(i.length>0&&typeof i[0]=="object"&&i[0]!==null&&"path"in i[0])continue;let N=i.map(n=>typeof n=="string"?{path:n}:n);e.prepare("UPDATE roles SET additional_directories = ? WHERE id = ?").run(JSON.stringify(N),t.id)}catch{}}catch{}let E=e.prepare("PRAGMA table_info(tasks)").all();E.some(T=>T.name==="deliver_to")||e.exec("ALTER TABLE tasks ADD COLUMN deliver_to TEXT"),E.some(T=>T.name==="report_to")||e.exec("ALTER TABLE tasks ADD COLUMN report_to TEXT");let s=e.prepare("PRAGMA table_info(strategies)").all();s.some(T=>T.name==="role")&&!s.some(T=>T.name==="role_id")&&(e.exec("ALTER TABLE strategies RENAME COLUMN role TO role_id"),e.exec("DROP INDEX IF EXISTS idx_strategies_role_task_type"),e.exec("DROP INDEX IF EXISTS idx_strategies_role"),e.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_strategies_role_task_type ON strategies(role_id, task_type, name)"),e.exec("CREATE INDEX IF NOT EXISTS idx_strategies_role ON strategies(role_id)")),e.exec("UPDATE server_state SET schema_version = 17 WHERE id = 1"),e.exec("PRAGMA foreign_keys = ON")}if(_<18){let E=e.prepare("PRAGMA table_info(tasks)").all();E.some(T=>T.name==="deliver_to")||e.exec("ALTER TABLE tasks ADD COLUMN deliver_to TEXT"),E.some(T=>T.name==="report_to")||e.exec("ALTER TABLE tasks ADD COLUMN report_to TEXT");let s=e.prepare("PRAGMA table_info(strategies)").all();s.some(T=>T.name==="role")&&!s.some(T=>T.name==="role_id")&&(e.exec("ALTER TABLE strategies RENAME COLUMN role TO role_id"),e.exec("DROP INDEX IF EXISTS idx_strategies_role_task_type"),e.exec("DROP INDEX IF EXISTS idx_strategies_role"),e.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_strategies_role_task_type ON strategies(role_id, task_type, name)"),e.exec("CREATE INDEX IF NOT EXISTS idx_strategies_role ON strategies(role_id)")),e.exec("UPDATE server_state SET schema_version = 18 WHERE id = 1")}e.prepare("PRAGMA table_info(delivery_log)").all().some(E=>E.name==="source")||(e.exec(`
570
+ `),e.exec("UPDATE server_state SET schema_version = 10 WHERE id = 1"),e.exec("PRAGMA foreign_keys = ON")}if(o<11){try{e.exec("ALTER TABLE task_templates RENAME COLUMN skill_preference TO role_preference")}catch(E){let s=e.prepare("PRAGMA table_info(task_templates)").all(),T=s.some(i=>i.name==="role_preference"),t=s.some(i=>i.name==="skill_preference");if(!T&&t)throw E}e.exec("UPDATE server_state SET schema_version = 11 WHERE id = 1")}if(o<12&&(e.prepare("PRAGMA table_info(server_state)").all().some(s=>s.name==="tools_fingerprint")||e.exec("ALTER TABLE server_state ADD COLUMN tools_fingerprint TEXT"),e.exec("UPDATE server_state SET schema_version = 12 WHERE id = 1")),o<13&&(e.prepare("PRAGMA table_info(roles)").all().some(s=>s.name==="additional_directories")||e.exec("ALTER TABLE roles ADD COLUMN additional_directories TEXT"),e.exec("UPDATE server_state SET schema_version = 13 WHERE id = 1")),o<14){let E=e.prepare("PRAGMA table_info(roles)").all();E.some(t=>t.name==="allowed_channels")||e.exec("ALTER TABLE roles ADD COLUMN allowed_channels TEXT"),E.some(t=>t.name==="mcp_servers")||e.exec("ALTER TABLE roles ADD COLUMN mcp_servers TEXT");let s=e.prepare("PRAGMA table_info(tasks)").all();s.some(t=>t.name==="deliver_to")||e.exec("ALTER TABLE tasks ADD COLUMN deliver_to TEXT"),s.some(t=>t.name==="report_to")||e.exec("ALTER TABLE tasks ADD COLUMN report_to TEXT"),e.prepare("PRAGMA table_info(goals)").all().some(t=>t.name==="deliver_to")||e.exec("ALTER TABLE goals ADD COLUMN deliver_to TEXT"),e.exec("UPDATE server_state SET schema_version = 14 WHERE id = 1")}if(o<15&&(e.prepare("PRAGMA table_info(roles)").all().some(s=>s.name==="inherit_user_settings")||e.exec("ALTER TABLE roles ADD COLUMN inherit_user_settings INTEGER DEFAULT 0"),e.exec("UPDATE server_state SET schema_version = 15 WHERE id = 1")),o<16&&(e.prepare("PRAGMA table_info(task_templates)").all().some(s=>s.name==="deliver_to")||e.exec("ALTER TABLE task_templates ADD COLUMN deliver_to TEXT"),e.exec("UPDATE server_state SET schema_version = 16 WHERE id = 1")),o<17){e.exec("PRAGMA foreign_keys = OFF"),e.exec("DROP TABLE IF EXISTS plugins"),e.exec("DROP TABLE IF EXISTS role_plugins"),e.exec("DROP TABLE IF EXISTS marketplaces"),e.exec("DROP INDEX IF EXISTS idx_plugins_source"),e.exec("DROP INDEX IF EXISTS idx_plugins_enabled");try{let T=e.prepare("SELECT id, additional_directories FROM roles WHERE additional_directories IS NOT NULL").all();for(let t of T)try{let i=JSON.parse(t.additional_directories);if(i.length>0&&typeof i[0]=="object"&&i[0]!==null&&"path"in i[0])continue;let n=i.map(_=>typeof _=="string"?{path:_}:_);e.prepare("UPDATE roles SET additional_directories = ? WHERE id = ?").run(JSON.stringify(n),t.id)}catch{}}catch{}let E=e.prepare("PRAGMA table_info(tasks)").all();E.some(T=>T.name==="deliver_to")||e.exec("ALTER TABLE tasks ADD COLUMN deliver_to TEXT"),E.some(T=>T.name==="report_to")||e.exec("ALTER TABLE tasks ADD COLUMN report_to TEXT");let s=e.prepare("PRAGMA table_info(strategies)").all();s.some(T=>T.name==="role")&&!s.some(T=>T.name==="role_id")&&(e.exec("ALTER TABLE strategies RENAME COLUMN role TO role_id"),e.exec("DROP INDEX IF EXISTS idx_strategies_role_task_type"),e.exec("DROP INDEX IF EXISTS idx_strategies_role"),e.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_strategies_role_task_type ON strategies(role_id, task_type, name)"),e.exec("CREATE INDEX IF NOT EXISTS idx_strategies_role ON strategies(role_id)")),e.exec("UPDATE server_state SET schema_version = 17 WHERE id = 1"),e.exec("PRAGMA foreign_keys = ON")}if(o<18){let E=e.prepare("PRAGMA table_info(tasks)").all();E.some(T=>T.name==="deliver_to")||e.exec("ALTER TABLE tasks ADD COLUMN deliver_to TEXT"),E.some(T=>T.name==="report_to")||e.exec("ALTER TABLE tasks ADD COLUMN report_to TEXT");let s=e.prepare("PRAGMA table_info(strategies)").all();s.some(T=>T.name==="role")&&!s.some(T=>T.name==="role_id")&&(e.exec("ALTER TABLE strategies RENAME COLUMN role TO role_id"),e.exec("DROP INDEX IF EXISTS idx_strategies_role_task_type"),e.exec("DROP INDEX IF EXISTS idx_strategies_role"),e.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_strategies_role_task_type ON strategies(role_id, task_type, name)"),e.exec("CREATE INDEX IF NOT EXISTS idx_strategies_role ON strategies(role_id)")),e.exec("UPDATE server_state SET schema_version = 18 WHERE id = 1")}e.prepare("PRAGMA table_info(delivery_log)").all().some(E=>E.name==="source")||(e.exec(`
571
571
  CREATE TABLE IF NOT EXISTS delivery_log_new (
572
572
  id TEXT PRIMARY KEY,
573
573
  rule_id TEXT REFERENCES delivery_rules(id),
@@ -584,7 +584,7 @@ import{e as A,h as O}from"./chunk-WBAPIPST.js";import{c as R,h as X}from"./chunk
584
584
  message_type TEXT
585
585
  )
586
586
  `),e.exec(`INSERT INTO delivery_log_new (id, rule_id, task_id, status, target, content, attempts, error, created_at, delivered_at, expires_at)
587
- SELECT id, rule_id, task_id, status, target, content, attempts, error, created_at, delivered_at, expires_at FROM delivery_log`),e.exec("DROP TABLE delivery_log"),e.exec("ALTER TABLE delivery_log_new RENAME TO delivery_log"),e.exec("CREATE INDEX IF NOT EXISTS idx_delivery_log_rule ON delivery_log(rule_id)"),e.exec("CREATE INDEX IF NOT EXISTS idx_delivery_log_task ON delivery_log(task_id)")),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<20&&(e.prepare("PRAGMA table_info(goals)").all().some(T=>T.name==="report_to")||e.exec("ALTER TABLE goals ADD COLUMN report_to TEXT"),e.prepare("PRAGMA table_info(task_templates)").all().some(T=>T.name==="report_to")||e.exec("ALTER TABLE task_templates ADD COLUMN report_to TEXT"),e.exec("UPDATE goals SET report_to = notify_targets WHERE notify_targets IS NOT NULL"),e.exec("UPDATE task_templates SET report_to = notify_targets WHERE notify_targets IS NOT NULL"),e.exec("UPDATE server_state SET schema_version = 20 WHERE id = 1")),e.prepare("PRAGMA table_info(config)").all().some(E=>E.name==="updated_at")||(e.exec("ALTER TABLE config ADD COLUMN updated_at INTEGER NOT NULL DEFAULT 0"),e.exec("UPDATE server_state SET schema_version = 21 WHERE id = 1"));let c=e.prepare("PRAGMA table_info(memories)").all();c.some(E=>E.name==="tier")||(e.exec("ALTER TABLE memories ADD COLUMN tier TEXT NOT NULL DEFAULT 'episodic'"),e.exec("CREATE INDEX IF NOT EXISTS idx_memories_tier ON memories(tier)")),c.some(E=>E.name==="superseded_by")||(e.exec("ALTER TABLE memories ADD COLUMN superseded_by TEXT"),e.exec("CREATE INDEX IF NOT EXISTS idx_memories_superseded ON memories(superseded_by)"));let L=e.prepare("PRAGMA table_info(memories)").all();L.some(E=>E.name==="tier")&&L.some(E=>E.name==="superseded_by")&&(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<22&&e.exec("UPDATE server_state SET schema_version = 22 WHERE id = 1");{let E=e.prepare("PRAGMA table_info(roles)").all();E.some(T=>T.name==="permission_mode")||e.exec("ALTER TABLE roles ADD COLUMN permission_mode TEXT DEFAULT NULL"),E.some(T=>T.name==="allowed_bash_patterns")||e.exec("ALTER TABLE roles ADD COLUMN allowed_bash_patterns TEXT DEFAULT NULL"),E.some(T=>T.name==="denied_bash_patterns")||e.exec("ALTER TABLE roles ADD COLUMN denied_bash_patterns TEXT DEFAULT NULL"),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<23&&e.exec("UPDATE server_state SET schema_version = 23 WHERE id = 1")}if(e.prepare("PRAGMA table_info(roles)").all().some(T=>T.name==="env_vars")||e.prepare("ALTER TABLE roles ADD COLUMN env_vars TEXT DEFAULT NULL").run(),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<24&&e.prepare("UPDATE server_state SET schema_version = 24 WHERE id = 1").run(),_<25&&(e.exec(`
587
+ SELECT id, rule_id, task_id, status, target, content, attempts, error, created_at, delivered_at, expires_at FROM delivery_log`),e.exec("DROP TABLE delivery_log"),e.exec("ALTER TABLE delivery_log_new RENAME TO delivery_log"),e.exec("CREATE INDEX IF NOT EXISTS idx_delivery_log_rule ON delivery_log(rule_id)"),e.exec("CREATE INDEX IF NOT EXISTS idx_delivery_log_task ON delivery_log(task_id)")),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<20&&(e.prepare("PRAGMA table_info(goals)").all().some(T=>T.name==="report_to")||e.exec("ALTER TABLE goals ADD COLUMN report_to TEXT"),e.prepare("PRAGMA table_info(task_templates)").all().some(T=>T.name==="report_to")||e.exec("ALTER TABLE task_templates ADD COLUMN report_to TEXT"),e.exec("UPDATE goals SET report_to = notify_targets WHERE notify_targets IS NOT NULL"),e.exec("UPDATE task_templates SET report_to = notify_targets WHERE notify_targets IS NOT NULL"),e.exec("UPDATE server_state SET schema_version = 20 WHERE id = 1")),e.prepare("PRAGMA table_info(config)").all().some(E=>E.name==="updated_at")||(e.exec("ALTER TABLE config ADD COLUMN updated_at INTEGER NOT NULL DEFAULT 0"),e.exec("UPDATE server_state SET schema_version = 21 WHERE id = 1"));let L=e.prepare("PRAGMA table_info(memories)").all();L.some(E=>E.name==="tier")||(e.exec("ALTER TABLE memories ADD COLUMN tier TEXT NOT NULL DEFAULT 'episodic'"),e.exec("CREATE INDEX IF NOT EXISTS idx_memories_tier ON memories(tier)")),L.some(E=>E.name==="superseded_by")||(e.exec("ALTER TABLE memories ADD COLUMN superseded_by TEXT"),e.exec("CREATE INDEX IF NOT EXISTS idx_memories_superseded ON memories(superseded_by)"));let d=e.prepare("PRAGMA table_info(memories)").all();d.some(E=>E.name==="tier")&&d.some(E=>E.name==="superseded_by")&&(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<22&&e.exec("UPDATE server_state SET schema_version = 22 WHERE id = 1");{let E=e.prepare("PRAGMA table_info(roles)").all();E.some(T=>T.name==="permission_mode")||e.exec("ALTER TABLE roles ADD COLUMN permission_mode TEXT DEFAULT NULL"),E.some(T=>T.name==="allowed_bash_patterns")||e.exec("ALTER TABLE roles ADD COLUMN allowed_bash_patterns TEXT DEFAULT NULL"),E.some(T=>T.name==="denied_bash_patterns")||e.exec("ALTER TABLE roles ADD COLUMN denied_bash_patterns TEXT DEFAULT NULL"),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<23&&e.exec("UPDATE server_state SET schema_version = 23 WHERE id = 1")}if(e.prepare("PRAGMA table_info(roles)").all().some(T=>T.name==="env_vars")||e.prepare("ALTER TABLE roles ADD COLUMN env_vars TEXT DEFAULT NULL").run(),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<24&&e.prepare("UPDATE server_state SET schema_version = 24 WHERE id = 1").run(),o<25&&(e.exec(`
588
588
  CREATE TABLE IF NOT EXISTS workflow_executions (
589
589
  id TEXT PRIMARY KEY,
590
590
  template_id TEXT NOT NULL,
@@ -595,7 +595,7 @@ import{e as A,h as O}from"./chunk-WBAPIPST.js";import{c as R,h as X}from"./chunk
595
595
  error TEXT,
596
596
  FOREIGN KEY (template_id) REFERENCES task_templates(id)
597
597
  )
598
- `),e.exec("UPDATE server_state SET schema_version = 25 WHERE id = 1")),_<26){let E=`
598
+ `),e.exec("UPDATE server_state SET schema_version = 25 WHERE id = 1")),o<26){let E=`
599
599
  CREATE TABLE IF NOT EXISTS workflow_artifacts (
600
600
  id TEXT PRIMARY KEY,
601
601
  execution_id TEXT NOT NULL,
@@ -633,4 +633,23 @@ import{e as A,h as O}from"./chunk-WBAPIPST.js";import{c as R,h as X}from"./chunk
633
633
  ON artifact_access_log (execution_id, timestamp);
634
634
  CREATE INDEX IF NOT EXISTS idx_artifact_access_log_role
635
635
  ON artifact_access_log (role_id, timestamp);
636
- `;e.exec(E),e.exec(s),e.prepare("PRAGMA table_info(tasks)").all().some(t=>t.name==="step_id")||e.prepare("ALTER TABLE tasks ADD COLUMN step_id TEXT").run(),e.exec("UPDATE server_state SET schema_version = 26 WHERE id = 1")}e.prepare("PRAGMA table_info(roles)").all().some(T=>T.name==="os_capabilities")||e.prepare("ALTER TABLE roles ADD COLUMN os_capabilities TEXT DEFAULT NULL").run(),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<27&&e.prepare("UPDATE server_state SET schema_version = 27 WHERE id = 1").run();{let E=e.prepare("PRAGMA table_info(manager_decisions)").all();E.some(T=>T.name==="requirements_json")||e.prepare("ALTER TABLE manager_decisions ADD COLUMN requirements_json TEXT").run(),E.some(T=>T.name==="fit_score")||e.prepare("ALTER TABLE manager_decisions ADD COLUMN fit_score REAL").run(),E.some(T=>T.name==="candidates_json")||e.prepare("ALTER TABLE manager_decisions ADD COLUMN candidates_json TEXT").run(),E.some(T=>T.name==="tie_break_reason")||e.prepare("ALTER TABLE manager_decisions ADD COLUMN tie_break_reason TEXT").run(),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<28&&e.prepare("UPDATE server_state SET schema_version = 28 WHERE id = 1").run()}{let E=[[/\brm -rf\b/,["rm -rf *"]],[/^git push/,["git push*"]],[/^git reset/,["git reset*"]],[/\bcurl.*POST\b/i,["curl * -X POST*","curl * --request POST*"]]],s=e.prepare("SELECT key, value FROM config WHERE key = 'defaults.approvalRequired'").all();for(let T of s)try{let t=JSON.parse(T.value),i=[];for(let n of t){let a=!1;for(let[d,r]of E)if(d.test(n)){i.push(...r),a=!0,I.info({from:n,to:r},"Config: migrated approvalRequired pattern from regex to glob");break}a||(/[.+?^${}()|[\]\\]/.test(n)&&I.warn({pattern:n},"Config: approvalRequired pattern contains regex metacharacters that won't work with glob matching; update to glob syntax (use * for wildcards)"),i.push(n))}let N=[...new Set(i)];e.prepare("UPDATE config SET value = ?, updated_at = ? WHERE key = ?").run(JSON.stringify(N),Date.now(),T.key)}catch{}}}function K(){if(o)return o;let e=process.env.ADAM_DB_PATH||A,l=g(e);return S(l)||u(l,{recursive:!0}),o=new p(e),o.pragma("journal_mode = WAL"),o.pragma("foreign_keys = ON"),o.pragma("trusted_schema = ON"),D(o),o}function W(){o&&(o.close(),o=null)}var I,o,C=m(()=>{O();X();I=R("store"),o=null});export{D as a,K as b,W as c,C as d};
636
+ `;e.exec(E),e.exec(s),e.prepare("PRAGMA table_info(tasks)").all().some(t=>t.name==="step_id")||e.prepare("ALTER TABLE tasks ADD COLUMN step_id TEXT").run(),e.exec("UPDATE server_state SET schema_version = 26 WHERE id = 1")}e.prepare("PRAGMA table_info(roles)").all().some(T=>T.name==="os_capabilities")||e.prepare("ALTER TABLE roles ADD COLUMN os_capabilities TEXT DEFAULT NULL").run(),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<27&&e.prepare("UPDATE server_state SET schema_version = 27 WHERE id = 1").run();{let E=e.prepare("PRAGMA table_info(manager_decisions)").all();E.some(T=>T.name==="requirements_json")||e.prepare("ALTER TABLE manager_decisions ADD COLUMN requirements_json TEXT").run(),E.some(T=>T.name==="fit_score")||e.prepare("ALTER TABLE manager_decisions ADD COLUMN fit_score REAL").run(),E.some(T=>T.name==="candidates_json")||e.prepare("ALTER TABLE manager_decisions ADD COLUMN candidates_json TEXT").run(),E.some(T=>T.name==="tie_break_reason")||e.prepare("ALTER TABLE manager_decisions ADD COLUMN tie_break_reason TEXT").run(),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<28&&e.prepare("UPDATE server_state SET schema_version = 28 WHERE id = 1").run()}{let E=[[/\brm -rf\b/,["rm -rf *"]],[/^git push/,["git push*"]],[/^git reset/,["git reset*"]],[/\bcurl.*POST\b/i,["curl * -X POST*","curl * --request POST*"]]],s=e.prepare("SELECT key, value FROM config WHERE key = 'defaults.approvalRequired'").all();for(let T of s)try{let t=JSON.parse(T.value),i=[];for(let _ of t){let l=!1;for(let[A,r]of E)if(A.test(_)){i.push(...r),l=!0,a.info({from:_,to:r},"Config: migrated approvalRequired pattern from regex to glob");break}l||(/[.+?^${}()|[\]\\]/.test(_)&&a.warn({pattern:_},"Config: approvalRequired pattern contains regex metacharacters that won't work with glob matching; update to glob syntax (use * for wildcards)"),i.push(_))}let n=[...new Set(i)];e.prepare("UPDATE config SET value = ?, updated_at = ? WHERE key = ?").run(JSON.stringify(n),Date.now(),T.key)}catch{}}if((e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<31){let s=e.prepare("SELECT count(*) AS n FROM task_templates WHERE trigger_type IN ('event', 'task_complete')").get();s.n>0&&a.info({legacyCount:s.n},"normalizing legacy template trigger types"),e.prepare("UPDATE task_templates SET trigger_type='workflow_complete' WHERE trigger_type='event' AND trigger_event LIKE 'workflow_complete:%'").run(),e.prepare("UPDATE task_templates SET trigger_type='template_complete' WHERE trigger_type='event'").run(),e.prepare("UPDATE task_templates SET trigger_type='manual' WHERE trigger_type='task_complete'").run();let T=e.prepare("SELECT count(*) AS n FROM task_templates WHERE trigger_type IN ('event', 'task_complete')").get();T.n>0&&a.warn({orphan:T.n},"migration left orphan legacy trigger_type rows; manual inspection required"),e.prepare("UPDATE server_state SET schema_version = 31 WHERE id = 1").run()}(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<32&&(e.exec(`
637
+ CREATE TABLE IF NOT EXISTS event_defs (
638
+ id TEXT PRIMARY KEY, name TEXT NOT NULL, source_type TEXT NOT NULL,
639
+ source_config TEXT NOT NULL, enabled INTEGER NOT NULL DEFAULT 1,
640
+ description TEXT, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL
641
+ );
642
+ CREATE INDEX IF NOT EXISTS idx_event_defs_source_type ON event_defs(source_type, enabled);
643
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_event_defs_name ON event_defs(name);
644
+
645
+ CREATE TABLE IF NOT EXISTS events (
646
+ id TEXT PRIMARY KEY, event_def_id TEXT,
647
+ occurred_at TEXT NOT NULL, ingested_at TEXT NOT NULL, user_day TEXT,
648
+ source TEXT NOT NULL, type TEXT NOT NULL, payload TEXT NOT NULL,
649
+ confidence REAL NOT NULL DEFAULT 1.0, dedup_key TEXT NOT NULL,
650
+ related_entities TEXT, trust_level TEXT NOT NULL DEFAULT 'trusted'
651
+ );
652
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_events_dedup ON events(source, dedup_key);
653
+ CREATE INDEX IF NOT EXISTS idx_events_type ON events(type);
654
+ CREATE INDEX IF NOT EXISTS idx_events_def_id ON events(event_def_id, occurred_at);
655
+ `),e.prepare("UPDATE server_state SET schema_version = 32 WHERE id = 1").run()),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<33&&(e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='workflow_executions'").get()&&(e.prepare("PRAGMA table_info(workflow_executions)").all().some(i=>i.name==="event_id")||e.prepare("ALTER TABLE workflow_executions ADD COLUMN event_id TEXT").run(),e.prepare("CREATE INDEX IF NOT EXISTS idx_workflow_executions_event_id ON workflow_executions(event_id)").run()),e.prepare("UPDATE server_state SET schema_version = 33 WHERE id = 1").run()),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<34&&(e.prepare("PRAGMA table_info(tasks)").all().some(t=>t.name==="block_reason_json")||e.prepare("ALTER TABLE tasks ADD COLUMN block_reason_json TEXT").run(),e.prepare("UPDATE server_state SET schema_version = 34 WHERE id = 1").run());try{let E=e.prepare("SELECT id, name, steps, role_preference FROM task_templates WHERE enabled = 1").all(),s=0;for(let T of E){if(T.role_preference)continue;let t;try{t=JSON.parse(T.steps)}catch{continue}if(!Array.isArray(t))continue;let i=!1;for(let n of t){let _=typeof n.roleId=="string"&&n.roleId.length>0,l=n.autoSelectRole===!0;!_&&!l&&(n.autoSelectRole=!0,n.requirements===void 0&&(n.requirements={}),i=!0)}i&&(e.prepare("UPDATE task_templates SET steps = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(t),Date.now(),T.id),s+=1,console.info(`[db migration] template auto-repaired: id=${T.id} name=${T.name}`))}s>0&&console.info(`[db migration] auto-repaired ${s} enabled template(s) with missing role config`)}catch(E){console.error("[db migration] template auto-repair failed:",E)}}function K(){if(N)return N;let e=process.env.ADAM_DB_PATH||R,c=g(e);return S(c)||u(c,{recursive:!0}),N=new X(e),N.pragma("journal_mode = WAL"),N.pragma("foreign_keys = ON"),N.pragma("trusted_schema = ON"),U(N),N}function W(){N&&(N.close(),N=null)}var a,N,D=I(()=>{p();O();a=m("store"),N=null});export{U as a,K as b,W as c,D as d};
@@ -1,4 +1,4 @@
1
- import{b as a,d as u}from"./chunk-JAS3TUZX.js";u();function l(e){return{id:e.id,eventType:e.event_type,matchCriteria:JSON.parse(e.match_criteria),target:JSON.parse(e.target),formatTemplate:e.format_template??void 0,maxPerMinute:e.max_per_minute,skipOriginChannel:e.skip_origin_channel===1,enabled:e.enabled===1,createdAt:e.created_at,createdBy:e.created_by??void 0}}function d(e){a().prepare(`
1
+ import{b as a,d as u}from"./chunk-5EPG2US5.js";u();function l(e){return{id:e.id,eventType:e.event_type,matchCriteria:JSON.parse(e.match_criteria),target:JSON.parse(e.target),formatTemplate:e.format_template??void 0,maxPerMinute:e.max_per_minute,skipOriginChannel:e.skip_origin_channel===1,enabled:e.enabled===1,createdAt:e.created_at,createdBy:e.created_by??void 0}}function d(e){a().prepare(`
2
2
  INSERT INTO delivery_rules (id, event_type, match_criteria, target, format_template,
3
3
  max_per_minute, skip_origin_channel, enabled, created_at, created_by)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -0,0 +1,6 @@
1
+ import{b as o,d as f}from"./chunk-5EPG2US5.js";f();function T(e){if(e)return e.startsWith("event:")?e.slice(6):void 0}var d=class extends Error{constructor(r){super(`Template has ${r.length} step(s) without executable role config. Set template.rolePreference, OR set each failing step's roleId, OR set autoSelectRole=true. Failing step ids: ${r.join(", ")}`);this.failingStepIds=r;this.name="TemplateRoleConfigError"}failingStepIds;code="TEMPLATE_INVALID_ROLE_CONFIG"};function u(e){if(e.rolePreference)return;let n=[];for(let r of e.steps){let s=typeof r.roleId=="string"&&r.roleId.length>0,t=r.autoSelectRole===!0;!s&&!t&&n.push(r.id)}if(n.length>0)throw new d(n)}function c(e){let n=e.trigger_type,r={type:n,cron:n==="event"?void 0:e.trigger_cron??void 0,event:n==="event"?void 0:e.trigger_event??void 0,eventDefId:n==="event"?T(e.trigger_event):void 0,runAt:n==="once"?e.trigger_cron??void 0:void 0};return{id:e.id,name:e.name,description:e.description??void 0,trigger:r,steps:JSON.parse(e.steps),rolePreference:e.role_preference??void 0,config:e.config?JSON.parse(e.config):void 0,tags:e.tags?JSON.parse(e.tags):void 0,enabled:e.enabled===1,createdAt:e.created_at,updatedAt:e.updated_at??void 0,sourceSessionId:e.source_session_id??void 0,deliverTo:e.deliver_to?JSON.parse(e.deliver_to):void 0,reportTo:e.report_to?JSON.parse(e.report_to):void 0,goalIds:e.goal_ids?JSON.parse(e.goal_ids):void 0}}function k(e){u(e),o().prepare(`
2
+ INSERT INTO task_templates (id, name, description, trigger_type, trigger_cron,
3
+ trigger_event, steps, role_preference, config, tags, enabled, created_at, updated_at,
4
+ source_session_id, deliver_to, report_to, goal_ids)
5
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
6
+ `).run(e.id,e.name,e.description??null,e.trigger.type,e.trigger.type==="once"?e.trigger.runAt??null:e.trigger.cron??null,e.trigger.type==="event"?`event:${e.trigger.eventDefId}`:e.trigger.event??null,JSON.stringify(e.steps),e.rolePreference??null,e.config?JSON.stringify(e.config):null,e.tags?JSON.stringify(e.tags):null,e.enabled?1:0,e.createdAt??Date.now(),e.updatedAt??null,e.sourceSessionId??null,e.deliverTo?JSON.stringify(e.deliverTo):null,e.reportTo?JSON.stringify(e.reportTo):null,e.goalIds?JSON.stringify(e.goalIds):null)}function _(e){let r=o().prepare("SELECT * FROM task_templates WHERE id = ?").get(e);return r?c(r):void 0}function h(e,n){let r=o();if("steps"in n||"rolePreference"in n){let i=_(e);if(i){let a={rolePreference:"rolePreference"in n?n.rolePreference:i.rolePreference,steps:"steps"in n&&n.steps?n.steps:i.steps};u(a)}}let s=[],t=[];"name"in n&&(s.push("name = ?"),t.push(n.name)),"description"in n&&(s.push("description = ?"),t.push(n.description??null)),"trigger"in n&&n.trigger&&(s.push("trigger_type = ?"),t.push(n.trigger.type),s.push("trigger_cron = ?"),t.push(n.trigger.type==="once"?n.trigger.runAt??null:n.trigger.cron??null),s.push("trigger_event = ?"),t.push(n.trigger.type==="event"?`event:${n.trigger.eventDefId}`:n.trigger.event??null)),"steps"in n&&(s.push("steps = ?"),t.push(JSON.stringify(n.steps))),"rolePreference"in n&&(s.push("role_preference = ?"),t.push(n.rolePreference??null)),"config"in n&&(s.push("config = ?"),t.push(n.config?JSON.stringify(n.config):null)),"tags"in n&&(s.push("tags = ?"),t.push(n.tags?JSON.stringify(n.tags):null)),"enabled"in n&&(s.push("enabled = ?"),t.push(n.enabled?1:0)),"sourceSessionId"in n&&(s.push("source_session_id = ?"),t.push(n.sourceSessionId??null)),"deliverTo"in n&&(s.push("deliver_to = ?"),t.push(n.deliverTo?JSON.stringify(n.deliverTo):null)),"reportTo"in n&&(s.push("report_to = ?"),t.push(n.reportTo?JSON.stringify(n.reportTo):null)),"goalIds"in n&&(s.push("goal_ids = ?"),t.push(n.goalIds?JSON.stringify(n.goalIds):null)),s.length!==0&&(s.push("updated_at = ?"),t.push(Date.now()),t.push(e),r.prepare(`UPDATE task_templates SET ${s.join(", ")} WHERE id = ?`).run(...t))}function m(e=!1,n,r=0){let s=o(),t="SELECT * FROM task_templates",i=[];return e&&(t+=" WHERE enabled = 1"),t+=" ORDER BY COALESCE(updated_at, created_at) DESC",typeof n=="number"&&(t+=" LIMIT ? OFFSET ?",i.push(n,r)),s.prepare(t).all(...i).map(c)}function S(e){o().prepare("UPDATE task_templates SET enabled = 1, updated_at = ? WHERE id = ?").run(Date.now(),e)}function R(e){o().prepare("UPDATE task_templates SET enabled = 0, updated_at = ? WHERE id = ?").run(Date.now(),e)}function b(e){let n=o(),r=n.prepare("SELECT COUNT(*) AS n FROM workflow_executions WHERE template_id = ?").get(e),s=n.prepare("SELECT COUNT(*) AS n FROM tasks WHERE template_id = ?").get(e);return{executionCount:r.n,taskCount:s.n}}function y(e,n="template_only"){let r=o();r.transaction(()=>{if(n==="with_tasks"){let i=r.prepare("SELECT id FROM tasks WHERE template_id = ?").all(e).map(a=>a.id);if(i.length>0)for(let p=0;p<i.length;p+=500){let l=i.slice(p,p+500),g=l.map(()=>"?").join(",");r.prepare(`DELETE FROM role_scores WHERE task_id IN (${g})`).run(...l),r.prepare(`DELETE FROM manager_decisions WHERE task_id IN (${g})`).run(...l),r.prepare(`UPDATE chat_messages SET task_id = NULL WHERE task_id IN (${g})`).run(...l),r.prepare(`UPDATE approval_rules SET created_by_task_id = NULL WHERE created_by_task_id IN (${g})`).run(...l),r.prepare(`DELETE FROM tasks WHERE id IN (${g})`).run(...l)}}r.prepare("DELETE FROM workflow_executions WHERE template_id = ?").run(e),r.prepare("DELETE FROM task_templates WHERE id = ?").run(e)})()}export{d as a,u as b,k as c,_ as d,h as e,m as f,S as g,R as h,b as i,y as j};
@@ -1,4 +1,4 @@
1
- import{a as oe}from"./chunk-5V36ACKZ.js";import{k as F}from"./chunk-VRJ7R766.js";import{b as ee}from"./chunk-Y3AMO6WC.js";import{a as Z,b as h}from"./chunk-ISZJV72D.js";import{e as N,f as D,j as Ae}from"./chunk-QWCRZDZS.js";import{a as Q}from"./chunk-UQJZU3R5.js";import{d as K}from"./chunk-GSMC3VUM.js";import{c as te,i as Ce,l as re,o as ne,r as xe}from"./chunk-GBTG5B5R.js";import{b as u,d as v}from"./chunk-JAS3TUZX.js";import{a as z,h as Le}from"./chunk-WBAPIPST.js";import{c as k,h as X}from"./chunk-INNDBLZE.js";Ce();import{homedir as Ie}from"os";import{resolve as j}from"path";import{z as g}from"zod";Le();function ie(){return[...z]}xe();Ae();var Oe=new Set(ie()),Pe=g.object({tools:g.array(g.string().refine(t=>Oe.has(t),{message:"Unknown tool"})).optional(),paths:g.array(g.object({path:g.string().refine(t=>t.startsWith("/")||t.startsWith("~"),{message:"path must be absolute or tilde-prefixed"}),access:g.enum(["ro","rw"])})).optional(),osCapabilities:g.array(g.object({id:g.enum(te),targets:g.array(g.string()).optional()})).optional(),network:g.boolean().optional(),plugins:g.array(g.string()).optional()});function ae(t){return t.startsWith("~")?t.replace(/^~/,Ie()):t}function Ne(t){let e=ae(t);return e.startsWith("/")?j(e):null}function ce(t,e){let n=[{path:j(e),access:"rw"}];for(let r of t.additionalDirectories??[])n.push({path:j(ae(r.path)),access:r.mode??"rw"});return n}function U(t,e){let n=Ne(t.path);if(!n)return!1;let r=e.filter(o=>n===o.path||n.startsWith(`${o.path}/`)).sort((o,s)=>s.path.length-o.path.length);if(r.length===0)return!1;let i=r[0];return t.access==="rw"?i.access==="rw":!0}function B(t,e){if(!t?.length)return[];let n=new Set(e??[]);return t.filter(r=>!n.has(r))}function G(t,e){if(!t?.length)return[];let n=new Set((e??[]).map(r=>r.id));return t.filter(r=>!n.has(r.id))}function W(t,e){if(!t?.length)return[];let n=new Set(e);return t.filter(r=>!n.has(r))}function H(t,e){return t?(e??[]).some(n=>n.id==="local-network"):!0}function le(t,e,n,r){let i=[];if(e.tools?.length){let o=B(e.tools,t.allowedTools).length;i.push((e.tools.length-o)/e.tools.length)}if(e.paths?.length){let o=e.paths.filter(s=>U(s,n)).length;i.push(o/e.paths.length)}if(e.osCapabilities?.length){let o=G(e.osCapabilities,t.osCapabilities).length;i.push((e.osCapabilities.length-o)/e.osCapabilities.length)}if(e.plugins?.length){let o=W(e.plugins,r).length;i.push((e.plugins.length-o)/e.plugins.length)}return e.network===!0&&i.push(H(e.network,t.osCapabilities)?1:0),i.length===0?1:i.reduce((o,s)=>o+s,0)/i.length}function De(t,e){if(!e.tools?.length||!t.approvalRequired?.length)return[];let n=new Set(t.approvalRequired),r=e.tools.filter(o=>n.has(o));if(!r.length)return[];let i=e.paths?.filter(o=>o.access==="rw").length??0;return[{code:"APPROVAL_WILL_TRIGGER",tools:r,expectedPromptCount:Math.max(r.length,i||r.length)}]}function Fe(t,e,n,r){let i=B(e.tools,t.allowedTools),o=(e.paths??[]).filter(d=>!U(d,n)),s=G(e.osCapabilities,t.osCapabilities),c=W(e.plugins,r),a={};return i.length&&(a.tools=i),o.length&&(a.paths=o),s.length&&(a.osCapabilities=s),c.length&&(a.plugins=c),e.network===!0&&!H(e.network,t.osCapabilities)&&(a.network=!0),a}function de(t,e){D(t);let n=N(t.name),r=ce(t,n),o=F(t).plugins.map(l=>l.name),s=B(e.tools,t.allowedTools);if(s.length)return{ok:!1,code:"ROLE_TOOL_MISMATCH",reason:`Missing tools: ${s.join(", ")}`,missing:{tools:s}};let c=(e.paths??[]).filter(l=>!U(l,r));if(c.length)return{ok:!1,code:"ROLE_PATH_SCOPE_MISMATCH",reason:`Missing path scope: ${c.map(l=>`${l.path} (${l.access})`).join(", ")}`,missing:{paths:c}};let a=G(e.osCapabilities,t.osCapabilities);if(a.length)return{ok:!1,code:"ROLE_OS_CAPABILITY_MISMATCH",reason:`Missing OS capabilities: ${a.map(l=>l.id).join(", ")}`,missing:{osCapabilities:a}};let d=W(e.plugins,o);return d.length?{ok:!1,code:"ROLE_PLUGIN_MISMATCH",reason:`Missing plugins: ${d.join(", ")}`,missing:{plugins:d}}:e.network===!0&&!H(e.network,t.osCapabilities)?{ok:!1,code:"ROLE_NETWORK_MISMATCH",reason:"Role lacks network capability (local-network)",missing:{network:!0}}:{ok:!0,roleId:t.id,executionProfile:t,fitScore:le(t,e,r,o),warnings:De(t,e)}}function se(t){return ne("active",100,0).filter(e=>e.source!=="system").map(e=>{D(e);let n=ce(e,N(e.name)),i=F(e).plugins.map(s=>s.name),o=de(e,t);return{role:e,evaluation:o,fitScore:le(e,t,n,i),missing:Fe(e,t,n,i)}}).sort((e,n)=>{let r=n.fitScore-e.fitScore;return r!==0?r:(n.role.performanceScore??0)-(e.role.performanceScore??0)})}async function ue(t){let{requirements:e,roleId:n,autoSelectRole:r}=t;if(!n&&!r)return{ok:!1,code:"REQUIREMENTS_MISSING",reason:"Must provide either roleId or autoSelectRole=true"};if(e){let l=Pe.safeParse(e);if(!l.success)return{ok:!1,code:"REQUIREMENTS_MISSING",reason:g.prettifyError(l.error)}}if(r&&!e)return{ok:!1,code:"REQUIREMENTS_MISSING",reason:"autoSelectRole requires a requirements object"};let i=e??{};if(n&&!r){let l=re(n);if(!l||l.status!=="active")return{ok:!1,code:"ROLE_NOT_FOUND",reason:`Role not found or not active: ${n}`};let p=de(l,i);return p.ok?(p.auditCandidates=[{roleId:l.id,name:l.name,fitScore:p.fitScore,fits:!0}],p):(e&&(p.candidates=se(e).map(S=>({roleId:S.role.id,name:S.role.name,fitScore:S.fitScore,missing:S.missing}))),p)}let o=se(e),s=o.filter(l=>l.evaluation.ok);if(!s.length)return{ok:!1,code:"ROLE_SELECTION_AMBIGUOUS",reason:"No role covers the requirements",candidates:o.map(l=>({roleId:l.role.id,name:l.role.name,fitScore:l.fitScore,missing:l.missing}))};let c=s[0],a=c.evaluation,d=s[1];return d&&d.fitScore===c.fitScore&&(a.tieBreakReason=`fitScore tie at ${c.fitScore}; chose ${c.role.name} by performanceScore`),a.auditCandidates=o.map(l=>({roleId:l.role.id,name:l.role.name,fitScore:l.fitScore,fits:l.evaluation.ok})),a}v();function L(t){return{id:t.id,roleId:t.role_id,taskType:t.task_type,name:t.name,promptTemplate:t.prompt_template,alpha:t.alpha,beta:t.beta,totalTrials:t.total_trials,avgReward:t.avg_reward??void 0,createdAt:t.created_at,updatedAt:t.updated_at??void 0}}function pe(t){u().prepare(`
1
+ import{a as oe}from"./chunk-IZNEOYRP.js";import{k as F}from"./chunk-NWMOV23A.js";import{b as ee}from"./chunk-2L2347UQ.js";import{a as Z,b as h}from"./chunk-K4C43YDD.js";import{e as N,f as D,j as Ae}from"./chunk-WMB7P64J.js";import{a as Q}from"./chunk-UQJZU3R5.js";import{d as K}from"./chunk-GSMC3VUM.js";import{c as te,i as Ce,l as re,o as ne,r as xe}from"./chunk-HQRUJQN7.js";import{b as u,d as v}from"./chunk-5EPG2US5.js";import{a as z,h as Le}from"./chunk-WBAPIPST.js";import{c as k,h as X}from"./chunk-MRTJFYPR.js";Ce();import{homedir as Ie}from"os";import{resolve as j}from"path";import{z as g}from"zod";Le();function ie(){return[...z]}xe();Ae();var Oe=new Set(ie()),Pe=g.object({tools:g.array(g.string().refine(t=>Oe.has(t),{message:"Unknown tool"})).optional(),paths:g.array(g.object({path:g.string().refine(t=>t.startsWith("/")||t.startsWith("~"),{message:"path must be absolute or tilde-prefixed"}),access:g.enum(["ro","rw"])})).optional(),osCapabilities:g.array(g.object({id:g.enum(te),targets:g.array(g.string()).optional()})).optional(),network:g.boolean().optional(),plugins:g.array(g.string()).optional()});function ae(t){return t.startsWith("~")?t.replace(/^~/,Ie()):t}function Ne(t){let e=ae(t);return e.startsWith("/")?j(e):null}function ce(t,e){let n=[{path:j(e),access:"rw"}];for(let r of t.additionalDirectories??[])n.push({path:j(ae(r.path)),access:r.mode??"rw"});return n}function U(t,e){let n=Ne(t.path);if(!n)return!1;let r=e.filter(o=>n===o.path||n.startsWith(`${o.path}/`)).sort((o,s)=>s.path.length-o.path.length);if(r.length===0)return!1;let i=r[0];return t.access==="rw"?i.access==="rw":!0}function B(t,e){if(!t?.length)return[];let n=new Set(e??[]);return t.filter(r=>!n.has(r))}function G(t,e){if(!t?.length)return[];let n=new Set((e??[]).map(r=>r.id));return t.filter(r=>!n.has(r.id))}function W(t,e){if(!t?.length)return[];let n=new Set(e);return t.filter(r=>!n.has(r))}function H(t,e){return t?(e??[]).some(n=>n.id==="local-network"):!0}function le(t,e,n,r){let i=[];if(e.tools?.length){let o=B(e.tools,t.allowedTools).length;i.push((e.tools.length-o)/e.tools.length)}if(e.paths?.length){let o=e.paths.filter(s=>U(s,n)).length;i.push(o/e.paths.length)}if(e.osCapabilities?.length){let o=G(e.osCapabilities,t.osCapabilities).length;i.push((e.osCapabilities.length-o)/e.osCapabilities.length)}if(e.plugins?.length){let o=W(e.plugins,r).length;i.push((e.plugins.length-o)/e.plugins.length)}return e.network===!0&&i.push(H(e.network,t.osCapabilities)?1:0),i.length===0?1:i.reduce((o,s)=>o+s,0)/i.length}function De(t,e){if(!e.tools?.length||!t.approvalRequired?.length)return[];let n=new Set(t.approvalRequired),r=e.tools.filter(o=>n.has(o));if(!r.length)return[];let i=e.paths?.filter(o=>o.access==="rw").length??0;return[{code:"APPROVAL_WILL_TRIGGER",tools:r,expectedPromptCount:Math.max(r.length,i||r.length)}]}function Fe(t,e,n,r){let i=B(e.tools,t.allowedTools),o=(e.paths??[]).filter(d=>!U(d,n)),s=G(e.osCapabilities,t.osCapabilities),c=W(e.plugins,r),a={};return i.length&&(a.tools=i),o.length&&(a.paths=o),s.length&&(a.osCapabilities=s),c.length&&(a.plugins=c),e.network===!0&&!H(e.network,t.osCapabilities)&&(a.network=!0),a}function de(t,e){D(t);let n=N(t.name),r=ce(t,n),o=F(t).plugins.map(l=>l.name),s=B(e.tools,t.allowedTools);if(s.length)return{ok:!1,code:"ROLE_TOOL_MISMATCH",reason:`Missing tools: ${s.join(", ")}`,missing:{tools:s}};let c=(e.paths??[]).filter(l=>!U(l,r));if(c.length)return{ok:!1,code:"ROLE_PATH_SCOPE_MISMATCH",reason:`Missing path scope: ${c.map(l=>`${l.path} (${l.access})`).join(", ")}`,missing:{paths:c}};let a=G(e.osCapabilities,t.osCapabilities);if(a.length)return{ok:!1,code:"ROLE_OS_CAPABILITY_MISMATCH",reason:`Missing OS capabilities: ${a.map(l=>l.id).join(", ")}`,missing:{osCapabilities:a}};let d=W(e.plugins,o);return d.length?{ok:!1,code:"ROLE_PLUGIN_MISMATCH",reason:`Missing plugins: ${d.join(", ")}`,missing:{plugins:d}}:e.network===!0&&!H(e.network,t.osCapabilities)?{ok:!1,code:"ROLE_NETWORK_MISMATCH",reason:"Role lacks network capability (local-network)",missing:{network:!0}}:{ok:!0,roleId:t.id,executionProfile:t,fitScore:le(t,e,r,o),warnings:De(t,e)}}function se(t){return ne("active",100,0).filter(e=>e.source!=="system").map(e=>{D(e);let n=ce(e,N(e.name)),i=F(e).plugins.map(s=>s.name),o=de(e,t);return{role:e,evaluation:o,fitScore:le(e,t,n,i),missing:Fe(e,t,n,i)}}).sort((e,n)=>{let r=n.fitScore-e.fitScore;return r!==0?r:(n.role.performanceScore??0)-(e.role.performanceScore??0)})}async function ue(t){let{requirements:e,roleId:n,autoSelectRole:r}=t;if(!n&&!r)return{ok:!1,code:"REQUIREMENTS_MISSING",reason:"Must provide either roleId or autoSelectRole=true"};if(e){let l=Pe.safeParse(e);if(!l.success)return{ok:!1,code:"REQUIREMENTS_MISSING",reason:g.prettifyError(l.error)}}if(r&&!e)return{ok:!1,code:"REQUIREMENTS_MISSING",reason:"autoSelectRole requires a requirements object"};let i=e??{};if(n&&!r){let l=re(n);if(!l||l.status!=="active")return{ok:!1,code:"ROLE_NOT_FOUND",reason:`Role not found or not active: ${n}`};let p=de(l,i);return p.ok?(p.auditCandidates=[{roleId:l.id,name:l.name,fitScore:p.fitScore,fits:!0}],p):(e&&(p.candidates=se(e).map(S=>({roleId:S.role.id,name:S.role.name,fitScore:S.fitScore,missing:S.missing}))),p)}let o=se(e),s=o.filter(l=>l.evaluation.ok);if(!s.length)return{ok:!1,code:"ROLE_SELECTION_AMBIGUOUS",reason:"No role covers the requirements",candidates:o.map(l=>({roleId:l.role.id,name:l.role.name,fitScore:l.fitScore,missing:l.missing}))};let c=s[0],a=c.evaluation,d=s[1];return d&&d.fitScore===c.fitScore&&(a.tieBreakReason=`fitScore tie at ${c.fitScore}; chose ${c.role.name} by performanceScore`),a.auditCandidates=o.map(l=>({roleId:l.role.id,name:l.role.name,fitScore:l.fitScore,fits:l.evaluation.ok})),a}v();function L(t){return{id:t.id,roleId:t.role_id,taskType:t.task_type,name:t.name,promptTemplate:t.prompt_template,alpha:t.alpha,beta:t.beta,totalTrials:t.total_trials,avgReward:t.avg_reward??void 0,createdAt:t.created_at,updatedAt:t.updated_at??void 0}}function pe(t){u().prepare(`
2
2
  INSERT INTO strategies (id, role_id, task_type, name, prompt_template,
3
3
  alpha, beta, total_trials, avg_reward, created_at, updated_at)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -1,4 +1,4 @@
1
- import{b as o,d as u}from"./chunk-JAS3TUZX.js";u();import{v4 as a}from"uuid";function R(t){o().prepare(`
1
+ import{b as o,d as u}from"./chunk-5EPG2US5.js";u();import{v4 as a}from"uuid";function R(t){o().prepare(`
2
2
  INSERT INTO evolution_audit (id, timestamp, old_rules, new_rules, diff, trigger_task_id, role_id, source)
3
3
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
4
4
  `).run(a(),t.timestamp,t.oldRules,t.newRules,t.diff,t.triggerTaskId??null,t.roleId??null,t.source??"reflection")}function f(t=100,e=0){return o().prepare(`
@@ -1,4 +1,4 @@
1
- import{a as B}from"./chunk-R4GIIQ7G.js";import{a as C}from"./chunk-2CMR5AG7.js";import{a as L,b as k,c as T,j as $}from"./chunk-C6BOQJJF.js";import{d as I,h as P,i as de}from"./chunk-GBTG5B5R.js";import{b as _,d as se}from"./chunk-JAS3TUZX.js";import{c as D,h as ie}from"./chunk-INNDBLZE.js";import{tool as p}from"@anthropic-ai/claude-agent-sdk";import{z as a}from"zod";import{v4 as le}from"uuid";function l(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}var ce={query:a.string().describe("Search query for memory retrieval"),roleId:a.string().optional().describe("Role ID to scope search (omit for cross-role)"),topK:a.number().optional().describe("Max results to return (default 5)")},pe={query:a.string().describe("Search query for memory retrieval"),topK:a.number().optional().describe("Max results to return (default 5)")},me={id:a.string().optional().describe("Memory ID to update. Omit to create new."),roleId:a.string().describe("Role ID to save memory under"),content:a.string().describe("Memory content text"),type:a.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:a.array(a.string()).optional().describe("Keywords for BM25 search"),importance:a.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:a.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},ue={id:a.string().optional().describe("Memory ID to update. Omit to create new."),content:a.string().describe("Memory content text"),type:a.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:a.array(a.string()).optional().describe("Keywords for BM25 search"),importance:a.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:a.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},N={id:a.string().describe("Memory ID to delete")};async function j(t,e){let r=t??e.roleId,n=e.topK??5,i=await B(r,e.query,{topK:n});return l({results:i.map(o=>({id:o.id,type:o.type,content:o.content,keywords:o.keywords,importance:o.importance,score:o.score}))})}async function F(t,e){let r=t??e.roleId;if(!r)return l({error:"roleId is required"});let n,i=!0;try{n=await C(e.content)}catch{i=!1}if(e.id){if(!k(e.id))return l({error:`Memory ${e.id} not found`});let v=T(e.id,{content:e.content,embedding:n,keywords:e.keywords,importance:e.importance,type:e.type});return l({id:e.id,action:"updated",success:v,embeddingUpdated:i})}let o=`mem-${le().slice(0,8)}`,s=Date.now();return L({id:o,roleId:r,type:e.type??"thought",content:e.content,embedding:n,keywords:e.keywords??[],importance:e.importance??3,sourceType:"manual",createdAt:s,lastAccessed:s,retrievedCount:0,tier:e.tier??"episodic"}),l({id:o,action:"created",success:!0,embeddingUpdated:i})}async function K(t,e){if(t){let r=k(e.id);if(!r)return l({error:`Memory ${e.id} not found`});if(r.roleId!==t)return l({error:`Memory ${e.id} does not belong to this role`})}return $(e.id),l({id:e.id,deleted:!0})}function Ue(t){return t?[p("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",pe,async e=>j(t,e)),p("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",ue,async e=>F(t,e)),p("delete_memory","Delete a memory by ID.",N,async e=>K(t,e))]:[p("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",ce,async e=>j(void 0,e)),p("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",me,async e=>F(void 0,e)),p("delete_memory","Delete a memory by ID.",N,async e=>K(void 0,e))]}import{accessSync as q,constants as H}from"fs";import{accessSync as fe,constants as ye,existsSync as U,realpathSync as be}from"fs";import{join as E}from"path";import{spawn as he}from"child_process";import{execFileSync as ge}from"child_process";var u=null;function f(){if(u)return u;let t=typeof import.meta.dirname=="string"?import.meta.dirname:__dirname??".",e=E(t,"landlock-exec","landlock-exec");if(U(e))return u=e,e;let r=process.env.PATH?.split(":").find(n=>U(E(n,"landlock-exec")));return r?(u=E(r,"landlock-exec"),u):e}var y=class{platform="landlock";async isAvailable(){if(process.platform!=="linux")return!1;try{fe(f(),ye.X_OK)}catch{return!1}try{return ge(f(),["--check"],{timeout:5e3,stdio:["ignore","pipe","pipe"]}),!0}catch{return!1}}spawn(e){let r=e.command??"node",n=e.args??[],i=[];for(let o of e.visiblePaths??[]){let s=o.mode==="rw"?"--rw":"--ro",d;try{d=be(o.path)}catch{d=o.path}i.push(s,d),d!==o.path&&i.push(s,o.path)}return i.push("--",r,...n),he(f(),i,{cwd:e.cwd,env:e.env,stdio:"pipe",signal:e.signal})}};function G(){if(process.platform==="linux")try{return q(f(),H.X_OK),"landlock"}catch{return"none"}if(process.platform==="darwin")try{return q("/usr/bin/sandbox-exec",H.X_OK),"sandbox-exec"}catch{return"none"}return"none"}ie();import{spawn as _e}from"child_process";import{readFileSync as z,writeFileSync as Pe,mkdtempSync as ke,realpathSync as A,rmSync as Ee}from"fs";import{join as c}from"path";import{tmpdir as Ae}from"os";de();var ve=["com.apple.Accessibility","com.apple.CoreGraphics","com.apple.SpeakSelection","com.apple.TimeMachine","com.apple.assistant","com.apple.assistant.backedup","com.apple.assistant.support"],xe=["com.apple.coreservices.appleevents"];function Se(t){if(!I.test(t))throw new Error(`Invalid bundle id for SBPL appleevent destination: ${t}`)}function V(t,e){return P(t)?.find(r=>r.id===e)}function we(t){if(!t)return"";let e=["","; ===== Role OS capability: Automation =====","(allow lsopen)","(allow mach-lookup",...xe.map(n=>` (global-name "${n}")`),")"],r=t.targets??[];for(let n of r)Se(n),e.push(`(allow appleevent-send (appleevent-destination "${n}"))`);return e.join(`
1
+ import{a as B}from"./chunk-IKPYPZ64.js";import{a as C}from"./chunk-SWP2JC54.js";import{a as L,b as k,c as T,j as $}from"./chunk-DVN3BFPP.js";import{d as I,h as P,i as de}from"./chunk-HQRUJQN7.js";import{b as _,d as se}from"./chunk-5EPG2US5.js";import{c as D,h as ie}from"./chunk-MRTJFYPR.js";import{tool as p}from"@anthropic-ai/claude-agent-sdk";import{z as a}from"zod";import{v4 as le}from"uuid";function l(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}var ce={query:a.string().describe("Search query for memory retrieval"),roleId:a.string().optional().describe("Role ID to scope search (omit for cross-role)"),topK:a.number().optional().describe("Max results to return (default 5)")},pe={query:a.string().describe("Search query for memory retrieval"),topK:a.number().optional().describe("Max results to return (default 5)")},me={id:a.string().optional().describe("Memory ID to update. Omit to create new."),roleId:a.string().describe("Role ID to save memory under"),content:a.string().describe("Memory content text"),type:a.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:a.array(a.string()).optional().describe("Keywords for BM25 search"),importance:a.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:a.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},ue={id:a.string().optional().describe("Memory ID to update. Omit to create new."),content:a.string().describe("Memory content text"),type:a.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:a.array(a.string()).optional().describe("Keywords for BM25 search"),importance:a.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:a.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},N={id:a.string().describe("Memory ID to delete")};async function j(t,e){let r=t??e.roleId,n=e.topK??5,i=await B(r,e.query,{topK:n});return l({results:i.map(o=>({id:o.id,type:o.type,content:o.content,keywords:o.keywords,importance:o.importance,score:o.score}))})}async function F(t,e){let r=t??e.roleId;if(!r)return l({error:"roleId is required"});let n,i=!0;try{n=await C(e.content)}catch{i=!1}if(e.id){if(!k(e.id))return l({error:`Memory ${e.id} not found`});let v=T(e.id,{content:e.content,embedding:n,keywords:e.keywords,importance:e.importance,type:e.type});return l({id:e.id,action:"updated",success:v,embeddingUpdated:i})}let o=`mem-${le().slice(0,8)}`,s=Date.now();return L({id:o,roleId:r,type:e.type??"thought",content:e.content,embedding:n,keywords:e.keywords??[],importance:e.importance??3,sourceType:"manual",createdAt:s,lastAccessed:s,retrievedCount:0,tier:e.tier??"episodic"}),l({id:o,action:"created",success:!0,embeddingUpdated:i})}async function K(t,e){if(t){let r=k(e.id);if(!r)return l({error:`Memory ${e.id} not found`});if(r.roleId!==t)return l({error:`Memory ${e.id} does not belong to this role`})}return $(e.id),l({id:e.id,deleted:!0})}function Ue(t){return t?[p("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",pe,async e=>j(t,e)),p("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",ue,async e=>F(t,e)),p("delete_memory","Delete a memory by ID.",N,async e=>K(t,e))]:[p("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",ce,async e=>j(void 0,e)),p("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",me,async e=>F(void 0,e)),p("delete_memory","Delete a memory by ID.",N,async e=>K(void 0,e))]}import{accessSync as q,constants as H}from"fs";import{accessSync as fe,constants as ye,existsSync as U,realpathSync as be}from"fs";import{join as E}from"path";import{spawn as he}from"child_process";import{execFileSync as ge}from"child_process";var u=null;function f(){if(u)return u;let t=typeof import.meta.dirname=="string"?import.meta.dirname:__dirname??".",e=E(t,"landlock-exec","landlock-exec");if(U(e))return u=e,e;let r=process.env.PATH?.split(":").find(n=>U(E(n,"landlock-exec")));return r?(u=E(r,"landlock-exec"),u):e}var y=class{platform="landlock";async isAvailable(){if(process.platform!=="linux")return!1;try{fe(f(),ye.X_OK)}catch{return!1}try{return ge(f(),["--check"],{timeout:5e3,stdio:["ignore","pipe","pipe"]}),!0}catch{return!1}}spawn(e){let r=e.command??"node",n=e.args??[],i=[];for(let o of e.visiblePaths??[]){let s=o.mode==="rw"?"--rw":"--ro",d;try{d=be(o.path)}catch{d=o.path}i.push(s,d),d!==o.path&&i.push(s,o.path)}return i.push("--",r,...n),he(f(),i,{cwd:e.cwd,env:e.env,stdio:"pipe",signal:e.signal})}};function G(){if(process.platform==="linux")try{return q(f(),H.X_OK),"landlock"}catch{return"none"}if(process.platform==="darwin")try{return q("/usr/bin/sandbox-exec",H.X_OK),"sandbox-exec"}catch{return"none"}return"none"}ie();import{spawn as _e}from"child_process";import{readFileSync as z,writeFileSync as Pe,mkdtempSync as ke,realpathSync as A,rmSync as Ee}from"fs";import{join as c}from"path";import{tmpdir as Ae}from"os";de();var ve=["com.apple.Accessibility","com.apple.CoreGraphics","com.apple.SpeakSelection","com.apple.TimeMachine","com.apple.assistant","com.apple.assistant.backedup","com.apple.assistant.support"],xe=["com.apple.coreservices.appleevents"];function Se(t){if(!I.test(t))throw new Error(`Invalid bundle id for SBPL appleevent destination: ${t}`)}function V(t,e){return P(t)?.find(r=>r.id===e)}function we(t){if(!t)return"";let e=["","; ===== Role OS capability: Automation =====","(allow lsopen)","(allow mach-lookup",...xe.map(n=>` (global-name "${n}")`),")"],r=t.targets??[];for(let n of r)Se(n),e.push(`(allow appleevent-send (appleevent-destination "${n}"))`);return e.join(`
2
2
  `)}function Re(t){return t?["","; ===== Role OS capability: Accessibility =====","(allow signal)","(allow mach-priv-host-port)","(allow mach-task-name)",'(allow mach-lookup (local-name "com.apple.axserver"))',"(allow user-preference-read",...ve.map(r=>` (preference-domain "${r}")`),")"].join(`
3
3
  `):""}function X(t){let e=P(t);return e?.length?[we(V(e,"automation")),Re(V(e,"accessibility"))].filter(Boolean).join(`
4
4
  `):""}var Y=D("sandbox-macos"),J="/usr/bin/sandbox-exec";function Oe(){let t=[c(typeof import.meta.dirname=="string"?import.meta.dirname:".","profiles","role-sandbox.sb"),c(typeof import.meta.dirname=="string"?import.meta.dirname:".","..","src","sandbox","profiles","role-sandbox.sb"),c(process.cwd(),"src","sandbox","profiles","role-sandbox.sb")];for(let e of t)try{return z(e,"utf-8"),e}catch{}return t[t.length-1]}var Me=Oe();function b(t){if(!t.startsWith("/"))throw new Error(`Sandbox path must be absolute: ${t}`);if(t.includes('"')||t.includes(")")||t.includes("(")||t.includes("$"))throw new Error(`Sandbox path contains invalid characters for SBPL: ${t}`)}function De(t){let e=[`
@@ -1,4 +1,4 @@
1
- import{b as n,d as o}from"./chunk-JAS3TUZX.js";o();function a(e){return{id:e.id,sessionId:e.session_id,role:e.role,content:e.content,source:{type:e.source_type},taskId:e.task_id??void 0,channelMessageId:e.channel_message_id??void 0,metadata:e.metadata?JSON.parse(e.metadata):void 0,createdAt:e.created_at}}function c(e){n().prepare(`
1
+ import{b as n,d as o}from"./chunk-5EPG2US5.js";o();function a(e){return{id:e.id,sessionId:e.session_id,role:e.role,content:e.content,source:{type:e.source_type},taskId:e.task_id??void 0,channelMessageId:e.channel_message_id??void 0,metadata:e.metadata?JSON.parse(e.metadata):void 0,createdAt:e.created_at}}function c(e){n().prepare(`
2
2
  INSERT INTO chat_messages (id, session_id, role, content, source_type, task_id,
3
3
  channel_message_id, metadata, created_at)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -0,0 +1,23 @@
1
+ import{f as d,j as v}from"./chunk-WMB7P64J.js";import{k as c,l as f,m as h,o as R,r as w}from"./chunk-HQRUJQN7.js";import{c as p,h as y}from"./chunk-MRTJFYPR.js";w();v();y();import{v4 as i}from"uuid";var n=p("store"),u="role-chat-manager",m=[{name:"Engineer",cagPrompt:`Role: General-purpose software engineer.
2
+ Capabilities: Read, write, and edit code; run shell commands; search codebases.
3
+ Approach: Analyze requirements \u2192 implement \u2192 test \u2192 verify. Write tests for new code. Follow existing code patterns.
4
+ Best for: Feature implementation, bug fixes, refactoring, build/deploy scripts.
5
+ Constraints: No web access. Works only within the assigned workspace directory.`,allowedTools:["Read","Write","Edit","Bash","Grep","Glob"],evaluationCriteria:{code_quality:4,test_pass:4,build_success:3},executionMode:"isolated"},{name:"Reviewer",cagPrompt:`Role: Code reviewer and security auditor. READ-ONLY \u2014 you do not modify files.
6
+ Capabilities: Read files, search code, run analysis commands (linters, type-checkers, test suites).
7
+ Approach: Systematically review code for bugs, security issues, performance problems, and style violations. Output structured findings with file:line references.
8
+ Best for: Code review, security audit, dependency audit, test coverage analysis.
9
+ Constraints: No Write or Edit tools. Cannot modify code \u2014 only report findings.`,allowedTools:["Read","Grep","Glob","Bash"],evaluationCriteria:{bug_detection_rate:5,insight_quality:4},executionMode:"isolated"},{name:"Researcher",cagPrompt:`Role: Information researcher and analyst with web access.
10
+ Capabilities: Search the web, fetch web pages, read local files, run data processing scripts.
11
+ Approach: Gather information from multiple sources \u2192 cross-reference \u2192 synthesize findings into structured reports.
12
+ Best for: Market research, technical investigation, API documentation lookup, competitive analysis, news monitoring.
13
+ Constraints: No file write/edit permissions. Cannot modify the codebase \u2014 only research and report.`,allowedTools:["WebSearch","WebFetch","Read","Grep","Glob","Bash"],evaluationCriteria:{insight_quality:5,data_accuracy:5},executionMode:"isolated"},{name:"Writer",cagPrompt:`Role: Content writer and document generator.
14
+ Capabilities: Create and edit text files, read reference material, search for context.
15
+ Approach: Understand the target audience and format \u2192 draft \u2192 refine. Match the project's existing tone and terminology.
16
+ Best for: Documentation, reports, emails, translations, summaries, changelog entries.
17
+ Constraints: No shell command execution. No web access. Works only with file read/write operations.`,allowedTools:["Read","Write","Edit","Grep","Glob"],evaluationCriteria:{content_quality:5,engagement:4},executionMode:"isolated"}],C=["Chat Manager","adam-automator",...m.map(t=>t.name)];function D(t){return t.source==="system"?!0:t.source==="user"?!1:C.includes(t.name)}function E(){b(),x();let t=R(void 0,1e3,0),o=new Set(m.map(e=>e.name)),r=t.filter(e=>o.has(e.name));if(r.length>0)return n.info({count:r.length},"Default roles already exist, skipping"),t;n.info({count:m.length},"Creating default roles");let s=[];for(let e of m){let l=`role-${i().slice(0,8)}`,g={id:l,name:e.name,cagPrompt:e.cagPrompt,learnedRules:[],memoryStreamId:`mem-${i().slice(0,8)}`,status:"active",preferences:{},createdAt:Date.now(),allowedTools:e.allowedTools,evaluationCriteria:e.evaluationCriteria,executionMode:e.executionMode};c(g),s.push(g),d(g),n.info({roleId:l,name:e.name},"Created default role")}return s}function b(){if(f(u)){n.debug({roleId:u},"ChatManager system role already exists");return}let o={id:u,name:"Chat Manager",cagPrompt:`You are the Chat Manager \u2014 orchestrating conversations and managing agent interactions.
18
+ You coordinate between user requests and agent execution, maintaining conversation context
19
+ and routing tasks to the appropriate roles. You have broad memory access across all roles.`,learnedRules:[],memoryStreamId:`mem-${i().slice(0,8)}`,status:"active",preferences:{},createdAt:Date.now()};c(o),d(o),n.info({roleId:u},"Created ChatManager system role")}var a={name:"adam-automator",cagPrompt:`Role: Deterministic automation executor.
20
+ Capabilities: Run preset Skills under .claude/skills/. Read/write files in the assigned workspace.
21
+ Approach: When given an event and Skill name, invoke that Skill with the provided inputs. Do not interpret, do not deviate from the instruction, do not chain additional Skills unless told.
22
+ Best for: Event-triggered deterministic logic (feature aggregation, threshold checks, artifact persistence, routing classification, event chaining).
23
+ Constraints: Minimize LLM reasoning \u2014 call the specified Skill and return its output. If the instruction is ambiguous, return an error message instead of guessing.`,allowedTools:["Skill","Read","Write","Edit","Bash","Grep","Glob"],evaluationCriteria:{determinism:5,skill_invocation_rate:5},executionMode:"isolated",model:"claude-haiku-4-5-20251001"};function x(){let t=h(a.name);if(t)return t;let o=`role-${i().slice(0,8)}`,r=i(),s=Date.now(),e={id:o,name:a.name,cagPrompt:a.cagPrompt,learnedRules:[],memoryStreamId:r,status:"active",preferences:{},createdAt:s,allowedTools:a.allowedTools,evaluationCriteria:a.evaluationCriteria,executionMode:a.executionMode,model:a.model};return c(e),d(e),A(e.id).catch(l=>{n.warn({roleId:o,err:l},"Failed to seed adam-automator Skills")}),n.info({roleId:o,name:a.name},"Created adam-automator Role"),e}async function A(t){try{let{seedAdamAutomatorSkills:o}=await import("./adam-automator-skills-EZGBICHT.js");await o(t)}catch{}}export{u as a,C as b,D as c,E as d,x as e};
@@ -1,4 +1,4 @@
1
- import{b as f}from"./chunk-XL46AGRZ.js";import{b as m}from"./chunk-23VZKIB6.js";import{c as h,h as v}from"./chunk-INNDBLZE.js";v();var p=h("channels"),u=new Map,I=3e5,A=new Set(["telegram"]);function w(i){let e=i.trim().toLowerCase().match(/^(yes|y|是|允许|no|n|否|拒绝)\s+(\S+)$/);if(!e)return null;let[,c,l]=e,o=["yes","y","\u662F","\u5141\u8BB8"].includes(c);return{requestId:l,decision:o?"allow":"deny"}}function $(i){let n=m(i);return n?A.has(n.platform):!1}var T={low:"\u{1F7E2}",medium:"\u{1F7E1}",high:"\u{1F534}"},P={low:"\u4F4E",medium:"\u4E2D",high:"\u9AD8"};function k(i){let n=["\u{1F512} \u9700\u8981\u5BA1\u6279",""];for(let e of i.steps){if(e.description.startsWith("Execute task without OS sandbox"))n.push("\u26A0\uFE0F \u65E0\u6C99\u7BB1\u6267\u884C \u2014 \u6587\u4EF6\u7CFB\u7EDF\u9694\u79BB\u672A\u542F\u7528");else{let o=e.description.indexOf(": "),r=o>0?e.description.slice(0,o):"Operation";if(n.push(`\u64CD\u4F5C: ${r}`),r==="Bash"&&o>0)try{let t=JSON.parse(e.description.slice(o+2));if(t.command){let s=String(t.command).trim();n.push(`\u547D\u4EE4: ${s.length>120?s.slice(0,117)+"...":s}`)}}catch{let t=e.description.slice(o+2,o+122);n.push(`\u8BE6\u60C5: ${t}${e.description.length>o+122?"...":""}`)}else if(o>0){let t=e.description.slice(o+2,o+122);n.push(`\u8BE6\u60C5: ${t}${e.description.length>o+122?"...":""}`)}}let c=T[e.riskLevel]??"\u{1F7E1}",l=P[e.riskLevel]??e.riskLevel;n.push(`\u98CE\u9669: ${c} ${l}`),n.push("")}return n.join(`
1
+ import{b as f}from"./chunk-RI3V72RP.js";import{b as m}from"./chunk-GSFLLRS7.js";import{c as h,h as v}from"./chunk-MRTJFYPR.js";v();var p=h("channels"),u=new Map,I=3e5,A=new Set(["telegram"]);function w(i){let e=i.trim().toLowerCase().match(/^(yes|y|是|允许|no|n|否|拒绝)\s+(\S+)$/);if(!e)return null;let[,c,l]=e,o=["yes","y","\u662F","\u5141\u8BB8"].includes(c);return{requestId:l,decision:o?"allow":"deny"}}function $(i){let n=m(i);return n?A.has(n.platform):!1}var T={low:"\u{1F7E2}",medium:"\u{1F7E1}",high:"\u{1F534}"},P={low:"\u4F4E",medium:"\u4E2D",high:"\u9AD8"};function k(i){let n=["\u{1F512} \u9700\u8981\u5BA1\u6279",""];for(let e of i.steps){if(e.description.startsWith("Execute task without OS sandbox"))n.push("\u26A0\uFE0F \u65E0\u6C99\u7BB1\u6267\u884C \u2014 \u6587\u4EF6\u7CFB\u7EDF\u9694\u79BB\u672A\u542F\u7528");else{let o=e.description.indexOf(": "),r=o>0?e.description.slice(0,o):"Operation";if(n.push(`\u64CD\u4F5C: ${r}`),r==="Bash"&&o>0)try{let t=JSON.parse(e.description.slice(o+2));if(t.command){let s=String(t.command).trim();n.push(`\u547D\u4EE4: ${s.length>120?s.slice(0,117)+"...":s}`)}}catch{let t=e.description.slice(o+2,o+122);n.push(`\u8BE6\u60C5: ${t}${e.description.length>o+122?"...":""}`)}else if(o>0){let t=e.description.slice(o+2,o+122);n.push(`\u8BE6\u60C5: ${t}${e.description.length>o+122?"...":""}`)}}let c=T[e.riskLevel]??"\u{1F7E1}",l=P[e.riskLevel]??e.riskLevel;n.push(`\u98CE\u9669: ${c} ${l}`),n.push("")}return n.join(`
2
2
  `).trimEnd()}async function C(i,n,e,c,l,o=I){let r=e,t=r.slice(0,8);u.set(t,{planId:e,taskId:c,channelId:i,chatId:n,requestId:r,timestamp:Date.now(),timeoutMs:o});let s=f(),d=$(i);if(d){let a=`${l}
3
3
 
4
4
  `;await s.send({channelId:i,chatId:n,content:a,messageType:"approval",replyMarkup:{inlineKeyboard:[[{text:"\u2705 Allow",callbackData:`yes ${t}`},{text:"\u274C Deny",callbackData:`no ${t}`}]]}})}else{let a=[l,"",`Reply 'yes ${t}' or 'no ${t}'`].join(`
@@ -1,4 +1,4 @@
1
- import{l as f,r as h}from"./chunk-GBTG5B5R.js";import{b as u,d as E}from"./chunk-JAS3TUZX.js";E();h();function l(e){return{id:e.id,roleId:e.role_id,type:e.type,content:e.content,embedding:e.embedding?new Float32Array(e.embedding.buffer,e.embedding.byteOffset,e.embedding.byteLength/4):void 0,keywords:e.keywords?JSON.parse(e.keywords):[],importance:e.importance,sourceType:e.source_type,sourceTaskId:e.source_task_id??void 0,evidence:e.evidence?JSON.parse(e.evidence):void 0,createdAt:e.created_at,lastAccessed:e.last_accessed,retrievedCount:e.retrieved_count,tier:e.tier,supersededBy:e.superseded_by??void 0}}function b(e){return Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function v(e){u().prepare(`
1
+ import{l as f,r as h}from"./chunk-HQRUJQN7.js";import{b as u,d as E}from"./chunk-5EPG2US5.js";E();h();function l(e){return{id:e.id,roleId:e.role_id,type:e.type,content:e.content,embedding:e.embedding?new Float32Array(e.embedding.buffer,e.embedding.byteOffset,e.embedding.byteLength/4):void 0,keywords:e.keywords?JSON.parse(e.keywords):[],importance:e.importance,sourceType:e.source_type,sourceTaskId:e.source_task_id??void 0,evidence:e.evidence?JSON.parse(e.evidence):void 0,createdAt:e.created_at,lastAccessed:e.last_accessed,retrievedCount:e.retrieved_count,tier:e.tier,supersededBy:e.superseded_by??void 0}}function b(e){return Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function v(e){u().prepare(`
2
2
  INSERT INTO memories (id, role_id, type, content, embedding, keywords,
3
3
  importance, source_type, source_task_id, evidence,
4
4
  created_at, last_accessed, retrieved_count, tier, superseded_by)
@@ -1,3 +1,3 @@
1
- import{f as S}from"./chunk-BR2JY5X2.js";import{b as y}from"./chunk-YVS565QY.js";import{b as g}from"./chunk-ISZJV72D.js";import{b as C}from"./chunk-XL46AGRZ.js";import{b as R}from"./chunk-23VZKIB6.js";import{b as v}from"./chunk-2DLVAKH7.js";import{e as m}from"./chunk-HDP7A4XY.js";import{a as h}from"./chunk-L7JP7DUO.js";import{a as k,b as P,c as o,d as f,e as T,f as x,g as E}from"./chunk-QVKI7H7W.js";import{c as w,h as _}from"./chunk-INNDBLZE.js";_();import{v4 as M}from"uuid";var l=w("admin"),I=new Map,u=null,p=null,c=null,D=class{constructor(){h.on("task_status_change",e=>{(e.newStatus==="completed"||e.newStatus==="failed")&&this.handleTaskStatusChange(e.taskId,e.newStatus).catch(n=>{l.error({taskId:e.taskId,error:n},"Delivery processing failed")})}),h.on("plan_approval_request",e=>{this.handlePlanApprovalRequest(e.taskId,e.planId,e.plan).catch(n=>{l.error({taskId:e.taskId,error:n},"Delivery processing failed (plan_approval)")})}),l.info("DeliveryEngine initialized")}async handlePlanApprovalRequest(e,n,r){let t=g(e),i=this.getSourceChannelForTask(e);if(i){let d=y(r),{sendApprovalToChannel:b}=await import("./approval-handler-ORD4MUVM.js");await b(i.channelId,i.chatId,n,e,d)}let a=y(r)+`
1
+ import{f as S}from"./chunk-5QZXYKMS.js";import{b as v}from"./chunk-2YTDCR6A.js";import{b as y}from"./chunk-BQ3ZAYHC.js";import{e as m}from"./chunk-B6LOT5CG.js";import{b as g}from"./chunk-K4C43YDD.js";import{b as C}from"./chunk-RI3V72RP.js";import{b as R}from"./chunk-GSFLLRS7.js";import{a as h}from"./chunk-L7JP7DUO.js";import{a as k,b as P,c as o,d as f,e as T,f as x,g as E}from"./chunk-RZ7LCZVK.js";import{c as w,h as _}from"./chunk-MRTJFYPR.js";_();import{v4 as M}from"uuid";var l=w("admin"),I=new Map,u=null,p=null,c=null,D=class{constructor(){h.on("task_status_change",e=>{(e.newStatus==="completed"||e.newStatus==="failed")&&this.handleTaskStatusChange(e.taskId,e.newStatus).catch(n=>{l.error({taskId:e.taskId,error:n},"Delivery processing failed")})}),h.on("plan_approval_request",e=>{this.handlePlanApprovalRequest(e.taskId,e.planId,e.plan).catch(n=>{l.error({taskId:e.taskId,error:n},"Delivery processing failed (plan_approval)")})}),l.info("DeliveryEngine initialized")}async handlePlanApprovalRequest(e,n,r){let t=g(e),i=this.getSourceChannelForTask(e);if(i){let d=y(r),{sendApprovalToChannel:b}=await import("./approval-handler-PB7PSLUS.js");await b(i.channelId,i.chatId,n,e,d)}let a=y(r)+`
2
2
 
3
3
  Task: ${e}`;await this.matchAndDeliver("plan_approval_request",{templateId:t?.templateId,roleId:t?.roleId,prompt:t?.prompt,taskStatus:"pending"},a,e)}getSourceChannelForTask(e){try{let n=m(e);if(!n)return null;let r=v(n.sessionId);return!r||r.source.type!=="channel"||!r.source.channelId||!r.source.chatId?null:{channelId:r.source.channelId,chatId:r.source.chatId}}catch{return null}}async handleTaskStatusChange(e,n){let r=g(e);if(!r)return;let t={templateId:r.templateId,roleId:r.roleId,prompt:r.prompt,taskStatus:n},i=n==="completed"?"task_complete":"task_error",a=r.result??r.error??"";await this.matchAndDeliver(i,t,a,e)}async matchAndDeliver(e,n,r,t){let i=S(e,n);if(i.length!==0){l.debug({eventType:e,ruleCount:i.length,taskId:t},"Matched delivery rules");for(let a of i){if(!this.checkRateLimit(a)){l.warn({ruleId:a.id,maxPerMinute:a.maxPerMinute},"Delivery rate limit exceeded, skipping");continue}if(a.skipOriginChannel&&a.target.type==="channel"&&t&&this.isOriginChannel(t,a.target))continue;let d={id:M(),ruleId:a.id,taskId:t,status:"pending",target:a.target,content:r,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+k,source:"rule"};P(d),await this.attemptDelivery(d,a)}}}async attemptDeliveryPublic(e,n){return this.attemptDelivery(e,n)}async attemptDelivery(e,n){let r=C();try{if(e.target.type==="channel"){let t=e.target.chatId;!t&&e.target.channelId&&(t=R(e.target.channelId)?.config?.userId);let i=await r.send({taskId:e.taskId,channelId:e.target.channelId,chatId:t,content:e.content,messageType:"deliver"});i.success?(f(e.id),l.info({entryId:e.id,ruleId:n.id,targetType:"channel"},"Delivery successful")):o(e.id,"failed",i.error??"Gateway returned failure")}else if(e.target.type==="webhook"){let t=await r.send({taskId:e.taskId,webhookUrl:e.target.webhookUrl,content:e.content,messageType:"deliver"});t.success?(f(e.id),l.info({entryId:e.id,ruleId:n.id,targetType:"webhook"},"Webhook delivery successful")):o(e.id,"failed",t.error??"Gateway returned failure")}}catch(t){let i=t instanceof Error?t.message:String(t);o(e.id,"failed",i),l.warn({entryId:e.id,error:i},"Delivery attempt failed")}}checkRateLimit(e){let n=Date.now(),r=6e4,t=I.get(e.id);t||(t=[],I.set(e.id,t));let i=n-r;for(;t.length>0&&t[0]<i;)t.shift();return t.length>=e.maxPerMinute?!1:(t.push(n),!0)}isOriginChannel(e,n){try{if(n.type!=="channel"||!n.channelId)return!1;let r=m(e);if(!r)return!1;let t=v(r.sessionId);return t?t.source.type==="channel"&&t.source.channelId===n.channelId&&(!n.chatId||t.source.chatId===n.chatId):!1}catch{return!1}}async retryPending(){let e=T("rule",50),n=x("rule",50),r=[...e,...n];if(r.length!==0){l.debug({count:r.length},"Retrying pending/failed deliveries");for(let t of r){if(t.attempts>=3){o(t.id,"failed","Max retries (3) exceeded");continue}let i={id:t.ruleId??"retry-synthetic",eventType:"*",matchCriteria:{},target:t.target,maxPerMinute:5,skipOriginChannel:!0,enabled:!0,createdAt:0};await this.attemptDelivery(t,i)}}}};function $(){return c}function H(){c||(c=new D,u=setInterval(()=>{c?.retryPending().catch(s=>{l.error({error:s},"Delivery retry scan failed")})},6e4),p=setInterval(()=>{try{let s=E();s>0&&l.info({cleaned:s},"Expired delivery log entries cleaned up")}catch(s){l.error({error:s},"Delivery cleanup failed")}},36e5),l.info("DeliveryEngine started with retry (60s) and cleanup (1h) timers"))}function J(){u&&(clearInterval(u),u=null),p&&(clearInterval(p),p=null),c=null,I.clear(),l.info("DeliveryEngine stopped")}export{D as a,$ as b,H as c,J as d};
@@ -1,2 +1,2 @@
1
- import{b as r,d as s}from"./chunk-JAS3TUZX.js";import{c as i}from"./chunk-FCV2DPZQ.js";function p(e){let n=r().prepare("SELECT value FROM config WHERE key = ?").get(e);if(n)try{return JSON.parse(n.value)}catch{return n.value}}function E(e,t){let n=r(),o=JSON.stringify(t),u=Date.now();n.prepare(`INSERT INTO config (key, value, updated_at) VALUES (?, ?, ?)
1
+ import{b as r,d as s}from"./chunk-5EPG2US5.js";import{c as i}from"./chunk-FCV2DPZQ.js";function p(e){let n=r().prepare("SELECT value FROM config WHERE key = ?").get(e);if(n)try{return JSON.parse(n.value)}catch{return n.value}}function E(e,t){let n=r(),o=JSON.stringify(t),u=Date.now();n.prepare(`INSERT INTO config (key, value, updated_at) VALUES (?, ?, ?)
2
2
  ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`).run(e,o,u)}function k(){let t=r().prepare("SELECT key, value FROM config").all(),n={};for(let o of t)try{n[o.key]=JSON.parse(o.value)}catch{n[o.key]=o.value}return n}function b(e){let t=r(),n=t.prepare("INSERT OR IGNORE INTO config (key, value, updated_at) VALUES (?, ?, ?)"),o=Date.now(),u=0;return t.transaction(()=>{for(let[c,a]of Object.entries(e)){if(a==null||a==="")continue;n.run(c,JSON.stringify(a),o).changes>0&&u++}})(),u}function w(){return r().prepare("SELECT COUNT(*) as count FROM config").get().count===0}function O(e){return r().prepare("DELETE FROM config WHERE key = ?").run(e).changes>0}var d=i(()=>{s()});export{p as a,E as b,k as c,b as d,w as e,O as f,d as g};
@@ -1,4 +1,4 @@
1
- import{b as s,d as i}from"./chunk-JAS3TUZX.js";i();function l(e){return{id:e.id,name:e.name,platform:e.platform,enabled:e.enabled===1,status:e.status,config:JSON.parse(e.config),linkedRoleId:e.linked_role_id??void 0,allowedChatIds:e.allowed_chat_ids?JSON.parse(e.allowed_chat_ids):void 0,createdAt:e.created_at,updatedAt:e.updated_at??void 0,lastMessageAt:e.last_message_at??void 0,messageCount:e.message_count}}function o(e){s().prepare(`
1
+ import{b as s,d as i}from"./chunk-5EPG2US5.js";i();function l(e){return{id:e.id,name:e.name,platform:e.platform,enabled:e.enabled===1,status:e.status,config:JSON.parse(e.config),linkedRoleId:e.linked_role_id??void 0,allowedChatIds:e.allowed_chat_ids?JSON.parse(e.allowed_chat_ids):void 0,createdAt:e.created_at,updatedAt:e.updated_at??void 0,lastMessageAt:e.last_message_at??void 0,messageCount:e.message_count}}function o(e){s().prepare(`
2
2
  INSERT INTO channels (id, name, platform, enabled, status, config, linked_role_id,
3
3
  allowed_chat_ids, created_at, updated_at, last_message_at, message_count)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -1,4 +1,4 @@
1
- import{a as p,g as N}from"./chunk-7L2WQM7N.js";import{b as o,d as C}from"./chunk-JAS3TUZX.js";import{b as l,h as g}from"./chunk-WBAPIPST.js";import{c,e as A}from"./chunk-FCV2DPZQ.js";import*as h from"os";import*as y from"path";function u(e){return e.startsWith("~/")||e==="~"?y.join(h.homedir(),e.slice(1)):e}var _=c(()=>{"use strict";g()});function R(e){return w.includes(e)}function S(e){return v[e]}function E(){return w.map(e=>v[e])}function V(e,i=e!=="none"){return E().map(s=>T(s,e,i))}function T(e,i,s=i!=="none"){return process.platform==="darwin"?e.status==="runtime-enforced"&&(i!=="sandbox-exec"||!s)?{...e,availability:"runtime-unavailable",editable:!1,effectiveDisabledReason:"Current runtime has no macOS sandbox backend; Adam cannot enforce this capability on Roles."}:e.status==="runtime-enforced"?{...e,availability:"editable",editable:!0}:{...e,availability:e.status,editable:!1,effectiveDisabledReason:e.disabledReason}:{...e,availability:"platform-unsupported",editable:!1,effectiveDisabledReason:"macOS only"}}function z(e){if(!e?.length)return;for(let s of e)if(!R(s.id))throw new Error(`Unknown OS capability: ${s.id}`);let i=d(e);if(i?.length){for(let s of i){let t=S(s.id);if(t.status!=="runtime-enforced")throw new Error(`OS capability '${t.label}' is not editable in Role settings`);if(t.supportsTargets){if(!s.targets?.length)throw new Error(`OS capability '${t.label}' requires at least one target bundle id`);for(let n of s.targets)if(!D(n))throw new Error(`Invalid automation target bundle id: ${n}`)}else if(s.targets?.length)throw new Error(`OS capability '${t.label}' does not accept targets`)}return i}}function d(e){if(!e||e.length===0)return;let i=new Set,s=[];for(let t of e){if(!R(t.id))throw new Error(`Unknown OS capability: ${t.id}`);if(i.has(t.id))continue;i.add(t.id);let n=S(t.id),a={id:t.id};n.supportsTargets&&t.targets?.length&&(a.targets=[...new Set(t.targets.map(r=>r.trim()).filter(Boolean))]),s.push(a)}return s.length>0?s.sort((t,n)=>t.id.localeCompare(n.id)):void 0}function D(e){return x.test(e)}var w,v,x,O=c(()=>{"use strict";w=["location-services","calendars","contacts","files-and-folders","full-disk-access","homekit","media-and-apple-music","passkeys-access-for-web-browsers","photos","reminders","accessibility","app-management","automation","bluetooth","camera","developer-tools","focus","input-monitoring","local-network","microphone","motion-and-fitness","remote-desktop","screen-and-system-audio-recording","speech-recognition"],v={"location-services":{id:"location-services",label:"Location Services",description:"Access device location and region context.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},calendars:{id:"calendars",label:"Calendars",description:"Access Calendar data via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},contacts:{id:"contacts",label:"Contacts",description:"Access Contacts data via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"files-and-folders":{id:"files-and-folders",label:"Files & Folders",description:"Host-level file access categories managed outside Role sandboxing.",platform:"darwin",status:"host-only",disabledReason:"Role file boundaries are already controlled by visiblePaths and deniedReadPaths."},"full-disk-access":{id:"full-disk-access",label:"Full Disk Access",description:"Host-level macOS grant for protected storage locations.",platform:"darwin",status:"host-only",disabledReason:"This is a host app permission, not a Role-level control."},homekit:{id:"homekit",label:"HomeKit",description:"Access HomeKit devices and home automation data.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"media-and-apple-music":{id:"media-and-apple-music",label:"Media & Apple Music",description:"Access Apple Music and media library data.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"passkeys-access-for-web-browsers":{id:"passkeys-access-for-web-browsers",label:"Passkeys Access for Web Browsers",description:"Access passkeys for browser-integrated authentication.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},photos:{id:"photos",label:"Photos",description:"Access the Photos library via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},reminders:{id:"reminders",label:"Reminders",description:"Access Reminder data via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},accessibility:{id:"accessibility",label:"Accessibility",description:"Control desktop UI and accessibility automation surfaces.",platform:"darwin",status:"runtime-enforced"},"app-management":{id:"app-management",label:"App Management",description:"Manage or inspect other installed applications.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},automation:{id:"automation",label:"Automation",description:"Launch and control other apps via Apple Events.",platform:"darwin",status:"runtime-enforced",supportsTargets:!0},bluetooth:{id:"bluetooth",label:"Bluetooth",description:"Access nearby Bluetooth devices.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},camera:{id:"camera",label:"Camera",description:"Capture camera input.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"developer-tools":{id:"developer-tools",label:"Developer Tools",description:"Use system developer tooling privileges.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},focus:{id:"focus",label:"Focus",description:"Access Focus state and related automation.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"input-monitoring":{id:"input-monitoring",label:"Input Monitoring",description:"Observe keyboard and input device activity.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"local-network":{id:"local-network",label:"Local Network",description:"Discover and communicate with devices on the local network.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},microphone:{id:"microphone",label:"Microphone",description:"Capture microphone input.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"motion-and-fitness":{id:"motion-and-fitness",label:"Motion & Fitness",description:"Access motion and fitness sensor data.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"remote-desktop":{id:"remote-desktop",label:"Remote Desktop",description:"Control or observe remote desktop sessions.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"screen-and-system-audio-recording":{id:"screen-and-system-audio-recording",label:"Screen & System Audio Recording",description:"Capture the screen and system audio.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"speech-recognition":{id:"speech-recognition",label:"Speech Recognition",description:"Use system speech recognition services.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."}},x=/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/});var L={};A(L,{createRole:()=>J,deleteRole:()=>U,getRole:()=>P,getRoleByName:()=>I,listRoles:()=>B,updateRole:()=>k,validateAdditionalDirectories:()=>f});import{existsSync as M}from"fs";import{resolve as m}from"path";function f(e,i){for(let s of e){let t=typeof s=="string"?s:s.path;if(!t.startsWith("/")&&!t.startsWith("~/")&&t!=="~")throw new Error(`additionalDirectories must be absolute paths: '${t}' is not absolute`);let n=m(u(t));if(!n.startsWith("/"))throw new Error(`additionalDirectories must be absolute paths: '${t}' is not absolute`);for(let a of l){let r=m(u(a));if(n.startsWith(r))throw new Error(`additionalDirectories cannot include hardcoded denied path: '${t}' matches '${a}'`)}if(i?.length)for(let a of i){let r=m(u(a));if(n.startsWith(r)||r.startsWith(n))throw new Error(`additionalDirectories cannot overlap with deniedReadPaths: '${t}' conflicts with '${a}'`)}if(!M(n))throw new Error(`additionalDirectories path does not exist: '${t}'`)}}function b(e){return{id:e.id,name:e.name,cagPrompt:e.cag_prompt,learnedRules:e.learned_rules?JSON.parse(e.learned_rules):[],memoryStreamId:e.memory_stream_id,status:e.status,performanceScore:e.performance_score??void 0,preferences:e.preferences?JSON.parse(e.preferences):{},createdAt:e.created_at,updatedAt:e.updated_at??void 0,allowedTools:e.allowed_tools?JSON.parse(e.allowed_tools):void 0,disallowedTools:e.disallowed_tools?JSON.parse(e.disallowed_tools):void 0,evaluationCriteria:e.evaluation_criteria?JSON.parse(e.evaluation_criteria):void 0,executionMode:e.execution_mode??void 0,model:e.model??void 0,maxBudgetUsd:e.max_budget_usd??void 0,approvalRequired:e.approval_required?JSON.parse(e.approval_required):void 0,source:e.source??void 0,additionalDirectories:(()=>{if(e.additional_directories!==null)try{let i=JSON.parse(e.additional_directories);return Array.isArray(i)?i.map(s=>typeof s=="string"?{path:s}:s):void 0}catch{return}})(),allowedChannels:e.allowed_channels?JSON.parse(e.allowed_channels):void 0,mcpServers:e.mcp_servers?JSON.parse(e.mcp_servers):void 0,inheritUserSettings:e.inherit_user_settings===1?!0:void 0,permissionMode:e.permission_mode??void 0,allowedBashPatterns:e.allowed_bash_patterns?JSON.parse(e.allowed_bash_patterns):void 0,deniedBashPatterns:e.denied_bash_patterns?JSON.parse(e.denied_bash_patterns):void 0,envVars:e.env_vars?JSON.parse(e.env_vars):void 0,osCapabilities:e.os_capabilities?d(JSON.parse(e.os_capabilities)):void 0}}function J(e){let i=p("defaults.deniedReadPaths")??[...l];e.additionalDirectories&&f(e.additionalDirectories,i),o().prepare(`
1
+ import{a as p,g as N}from"./chunk-FPZEZYUB.js";import{b as o,d as C}from"./chunk-5EPG2US5.js";import{b as l,h as g}from"./chunk-WBAPIPST.js";import{c,e as A}from"./chunk-FCV2DPZQ.js";import*as h from"os";import*as y from"path";function u(e){return e.startsWith("~/")||e==="~"?y.join(h.homedir(),e.slice(1)):e}var _=c(()=>{"use strict";g()});function R(e){return w.includes(e)}function S(e){return v[e]}function E(){return w.map(e=>v[e])}function V(e,i=e!=="none"){return E().map(s=>T(s,e,i))}function T(e,i,s=i!=="none"){return process.platform==="darwin"?e.status==="runtime-enforced"&&(i!=="sandbox-exec"||!s)?{...e,availability:"runtime-unavailable",editable:!1,effectiveDisabledReason:"Current runtime has no macOS sandbox backend; Adam cannot enforce this capability on Roles."}:e.status==="runtime-enforced"?{...e,availability:"editable",editable:!0}:{...e,availability:e.status,editable:!1,effectiveDisabledReason:e.disabledReason}:{...e,availability:"platform-unsupported",editable:!1,effectiveDisabledReason:"macOS only"}}function z(e){if(!e?.length)return;for(let s of e)if(!R(s.id))throw new Error(`Unknown OS capability: ${s.id}`);let i=d(e);if(i?.length){for(let s of i){let t=S(s.id);if(t.status!=="runtime-enforced")throw new Error(`OS capability '${t.label}' is not editable in Role settings`);if(t.supportsTargets){if(!s.targets?.length)throw new Error(`OS capability '${t.label}' requires at least one target bundle id`);for(let n of s.targets)if(!D(n))throw new Error(`Invalid automation target bundle id: ${n}`)}else if(s.targets?.length)throw new Error(`OS capability '${t.label}' does not accept targets`)}return i}}function d(e){if(!e||e.length===0)return;let i=new Set,s=[];for(let t of e){if(!R(t.id))throw new Error(`Unknown OS capability: ${t.id}`);if(i.has(t.id))continue;i.add(t.id);let n=S(t.id),a={id:t.id};n.supportsTargets&&t.targets?.length&&(a.targets=[...new Set(t.targets.map(r=>r.trim()).filter(Boolean))]),s.push(a)}return s.length>0?s.sort((t,n)=>t.id.localeCompare(n.id)):void 0}function D(e){return x.test(e)}var w,v,x,O=c(()=>{"use strict";w=["location-services","calendars","contacts","files-and-folders","full-disk-access","homekit","media-and-apple-music","passkeys-access-for-web-browsers","photos","reminders","accessibility","app-management","automation","bluetooth","camera","developer-tools","focus","input-monitoring","local-network","microphone","motion-and-fitness","remote-desktop","screen-and-system-audio-recording","speech-recognition"],v={"location-services":{id:"location-services",label:"Location Services",description:"Access device location and region context.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},calendars:{id:"calendars",label:"Calendars",description:"Access Calendar data via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},contacts:{id:"contacts",label:"Contacts",description:"Access Contacts data via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"files-and-folders":{id:"files-and-folders",label:"Files & Folders",description:"Host-level file access categories managed outside Role sandboxing.",platform:"darwin",status:"host-only",disabledReason:"Role file boundaries are already controlled by visiblePaths and deniedReadPaths."},"full-disk-access":{id:"full-disk-access",label:"Full Disk Access",description:"Host-level macOS grant for protected storage locations.",platform:"darwin",status:"host-only",disabledReason:"This is a host app permission, not a Role-level control."},homekit:{id:"homekit",label:"HomeKit",description:"Access HomeKit devices and home automation data.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"media-and-apple-music":{id:"media-and-apple-music",label:"Media & Apple Music",description:"Access Apple Music and media library data.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"passkeys-access-for-web-browsers":{id:"passkeys-access-for-web-browsers",label:"Passkeys Access for Web Browsers",description:"Access passkeys for browser-integrated authentication.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},photos:{id:"photos",label:"Photos",description:"Access the Photos library via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},reminders:{id:"reminders",label:"Reminders",description:"Access Reminder data via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},accessibility:{id:"accessibility",label:"Accessibility",description:"Control desktop UI and accessibility automation surfaces.",platform:"darwin",status:"runtime-enforced"},"app-management":{id:"app-management",label:"App Management",description:"Manage or inspect other installed applications.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},automation:{id:"automation",label:"Automation",description:"Launch and control other apps via Apple Events.",platform:"darwin",status:"runtime-enforced",supportsTargets:!0},bluetooth:{id:"bluetooth",label:"Bluetooth",description:"Access nearby Bluetooth devices.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},camera:{id:"camera",label:"Camera",description:"Capture camera input.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"developer-tools":{id:"developer-tools",label:"Developer Tools",description:"Use system developer tooling privileges.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},focus:{id:"focus",label:"Focus",description:"Access Focus state and related automation.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"input-monitoring":{id:"input-monitoring",label:"Input Monitoring",description:"Observe keyboard and input device activity.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"local-network":{id:"local-network",label:"Local Network",description:"Discover and communicate with devices on the local network.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},microphone:{id:"microphone",label:"Microphone",description:"Capture microphone input.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"motion-and-fitness":{id:"motion-and-fitness",label:"Motion & Fitness",description:"Access motion and fitness sensor data.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"remote-desktop":{id:"remote-desktop",label:"Remote Desktop",description:"Control or observe remote desktop sessions.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"screen-and-system-audio-recording":{id:"screen-and-system-audio-recording",label:"Screen & System Audio Recording",description:"Capture the screen and system audio.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"speech-recognition":{id:"speech-recognition",label:"Speech Recognition",description:"Use system speech recognition services.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."}},x=/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/});var L={};A(L,{createRole:()=>J,deleteRole:()=>U,getRole:()=>P,getRoleByName:()=>I,listRoles:()=>B,updateRole:()=>k,validateAdditionalDirectories:()=>f});import{existsSync as M}from"fs";import{resolve as m}from"path";function f(e,i){for(let s of e){let t=typeof s=="string"?s:s.path;if(!t.startsWith("/")&&!t.startsWith("~/")&&t!=="~")throw new Error(`additionalDirectories must be absolute paths: '${t}' is not absolute`);let n=m(u(t));if(!n.startsWith("/"))throw new Error(`additionalDirectories must be absolute paths: '${t}' is not absolute`);for(let a of l){let r=m(u(a));if(n.startsWith(r))throw new Error(`additionalDirectories cannot include hardcoded denied path: '${t}' matches '${a}'`)}if(i?.length)for(let a of i){let r=m(u(a));if(n.startsWith(r)||r.startsWith(n))throw new Error(`additionalDirectories cannot overlap with deniedReadPaths: '${t}' conflicts with '${a}'`)}if(!M(n))throw new Error(`additionalDirectories path does not exist: '${t}'`)}}function b(e){return{id:e.id,name:e.name,cagPrompt:e.cag_prompt,learnedRules:e.learned_rules?JSON.parse(e.learned_rules):[],memoryStreamId:e.memory_stream_id,status:e.status,performanceScore:e.performance_score??void 0,preferences:e.preferences?JSON.parse(e.preferences):{},createdAt:e.created_at,updatedAt:e.updated_at??void 0,allowedTools:e.allowed_tools?JSON.parse(e.allowed_tools):void 0,disallowedTools:e.disallowed_tools?JSON.parse(e.disallowed_tools):void 0,evaluationCriteria:e.evaluation_criteria?JSON.parse(e.evaluation_criteria):void 0,executionMode:e.execution_mode??void 0,model:e.model??void 0,maxBudgetUsd:e.max_budget_usd??void 0,approvalRequired:e.approval_required?JSON.parse(e.approval_required):void 0,source:e.source??void 0,additionalDirectories:(()=>{if(e.additional_directories!==null)try{let i=JSON.parse(e.additional_directories);return Array.isArray(i)?i.map(s=>typeof s=="string"?{path:s}:s):void 0}catch{return}})(),allowedChannels:e.allowed_channels?JSON.parse(e.allowed_channels):void 0,mcpServers:e.mcp_servers?JSON.parse(e.mcp_servers):void 0,inheritUserSettings:e.inherit_user_settings===1?!0:void 0,permissionMode:e.permission_mode??void 0,allowedBashPatterns:e.allowed_bash_patterns?JSON.parse(e.allowed_bash_patterns):void 0,deniedBashPatterns:e.denied_bash_patterns?JSON.parse(e.denied_bash_patterns):void 0,envVars:e.env_vars?JSON.parse(e.env_vars):void 0,osCapabilities:e.os_capabilities?d(JSON.parse(e.os_capabilities)):void 0}}function J(e){let i=p("defaults.deniedReadPaths")??[...l];e.additionalDirectories&&f(e.additionalDirectories,i),o().prepare(`
2
2
  INSERT INTO roles (id, name, cag_prompt, learned_rules, memory_stream_id, status,
3
3
  performance_score, preferences, created_at, updated_at,
4
4
  allowed_tools, disallowed_tools, evaluation_criteria, execution_mode, model,
@@ -1,4 +1,4 @@
1
- import{a as l}from"./chunk-2CMR5AG7.js";import{d as f,k as g,m as p,n as h,o as M,q as b}from"./chunk-C6BOQJJF.js";function v(t,n){let i=0,s=0,m=0;for(let e=0;e<t.length;e++)i+=t[e]*n[e],s+=t[e]*t[e],m+=n[e]*n[e];let o=Math.sqrt(s)*Math.sqrt(m);return o===0?0:i/o}async function S(t,n,i={}){let s=i.topK??10,m=i.hybridConfig??M,o;try{o=await l(n)}catch{}let e=o??new Float32Array(384),a=b(t,e,n,s*2,m,{excludeSuperseded:!0}),d=t?h(t):g,y=a.map(r=>{let u=r.embedding?v(e,r.embedding):0,C=Math.min(.3,(r.retrievedCount??0)*.05),x=p(r.createdAt,u,r.importance,d)+C;return{...r,score:x}});y.sort((r,u)=>u.score-r.score);let c=y.slice(0,s);for(let r of c)f(r.id);return c}async function T(t,n,i=5,s=2e3){try{let{estimateTokens:m}=await import("./token-estimator-HMPVGDCN.js"),o=await S(n,t,{topK:i});if(o.length===0)return"";let e=[],a=0,d=m(`[Memory Context \u2014 retrieved from prior interactions]
1
+ import{a as l}from"./chunk-SWP2JC54.js";import{d as f,k as g,m as p,n as h,o as M,q as b}from"./chunk-DVN3BFPP.js";function v(t,n){let i=0,s=0,m=0;for(let e=0;e<t.length;e++)i+=t[e]*n[e],s+=t[e]*t[e],m+=n[e]*n[e];let o=Math.sqrt(s)*Math.sqrt(m);return o===0?0:i/o}async function S(t,n,i={}){let s=i.topK??10,m=i.hybridConfig??M,o;try{o=await l(n)}catch{}let e=o??new Float32Array(384),a=b(t,e,n,s*2,m,{excludeSuperseded:!0}),d=t?h(t):g,y=a.map(r=>{let u=r.embedding?v(e,r.embedding):0,C=Math.min(.3,(r.retrievedCount??0)*.05),x=p(r.createdAt,u,r.importance,d)+C;return{...r,score:x}});y.sort((r,u)=>u.score-r.score);let c=y.slice(0,s);for(let r of c)f(r.id);return c}async function T(t,n,i=5,s=2e3){try{let{estimateTokens:m}=await import("./token-estimator-HMPVGDCN.js"),o=await S(n,t,{topK:i});if(o.length===0)return"";let e=[],a=0,d=m(`[Memory Context \u2014 retrieved from prior interactions]
2
2
 
3
3
  [User Request]
4
4
  `);for(let c of o){let r=m(`- [${c.tier??"episodic"}] ${c.content}
@@ -1 +1 @@
1
- import{c as n,h as g}from"./chunk-INNDBLZE.js";g();import{query as l}from"@anthropic-ai/claude-agent-sdk";import*as i from"fs/promises";import*as a from"path";import*as m from"os";var v=n("manager"),e=a.join(m.homedir(),".adam","llm-eval");async function w(u,t){await i.mkdir(e,{recursive:!0});let o={cwd:e,maxTurns:3,maxBudgetUsd:.05};t&&(o.systemPrompt=t);let c=l({prompt:u,options:o}),s="";for await(let f of c){let r=f;r.type==="result"&&typeof r.result=="string"&&(s=r.result)}return s}export{w as a};
1
+ import{c as n,h as g}from"./chunk-MRTJFYPR.js";g();import{query as l}from"@anthropic-ai/claude-agent-sdk";import*as i from"fs/promises";import*as a from"path";import*as m from"os";var v=n("manager"),e=a.join(m.homedir(),".adam","llm-eval");async function w(u,t){await i.mkdir(e,{recursive:!0});let o={cwd:e,maxTurns:3,maxBudgetUsd:.05};t&&(o.systemPrompt=t);let c=l({prompt:u,options:o}),s="";for await(let f of c){let r=f;r.type==="result"&&typeof r.result=="string"&&(s=r.result)}return s}export{w as a};