adam-agent-server 1.13.0 → 1.15.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 (210) hide show
  1. package/README.md +4 -5
  2. package/dist/App-6TRGTNZ7.js +13 -0
  3. package/dist/approval-handler-YLO3V75T.js +1 -0
  4. package/dist/audit-diagnostics-MASYIEGZ.js +1 -0
  5. package/dist/audit-manager-LYBXP7U4.js +1 -0
  6. package/dist/bree-engine-AA7EVKTG.js +1 -0
  7. package/dist/{channels-WFC26TED.js → channels-2IL6USWL.js} +1 -1
  8. package/dist/channels-6BEGHNOK.js +1 -0
  9. package/dist/chat-tool-calls-KARPW7PE.js +1 -0
  10. package/dist/chunk-245WE5AF.js +1 -0
  11. package/dist/chunk-2N4EOZZ4.js +9 -0
  12. package/dist/chunk-3BRHWRZ5.js +2 -0
  13. package/dist/chunk-3KNR2F6H.js +3 -0
  14. package/dist/chunk-42V6ZPCS.js +5 -0
  15. package/dist/chunk-6NWIZ3BH.js +220 -0
  16. package/dist/chunk-APAOIZN4.js +114 -0
  17. package/dist/chunk-ASPPM7TQ.js +1 -0
  18. package/dist/chunk-BKNXRSJU.js +4 -0
  19. package/dist/{chunk-MRTJFYPR.js → chunk-BLCNUT53.js} +1 -1
  20. package/dist/chunk-BPXS4QEO.js +1006 -0
  21. package/dist/chunk-CLNYHWZ6.js +5 -0
  22. package/dist/chunk-D3SPXZZY.js +6 -0
  23. package/dist/{chunk-SWP2JC54.js → chunk-DRO3DG7X.js} +1 -1
  24. package/dist/chunk-EVUZ5LH2.js +1 -0
  25. package/dist/chunk-F6U5TMM3.js +5 -0
  26. package/dist/chunk-FD4IKMXV.js +1 -0
  27. package/dist/chunk-GXWB47NF.js +9 -0
  28. package/dist/{chunk-PXGK5H5C.js → chunk-I7LJ4432.js} +1 -1
  29. package/dist/chunk-ICAM2GUU.js +1 -0
  30. package/dist/{chunk-B44X7JAJ.js → chunk-IRUR4DVD.js} +1 -1
  31. package/dist/chunk-ISKCTUI7.js +9 -0
  32. package/dist/{chunk-7T4B2MZ7.js → chunk-J3VYLSJI.js} +1 -1
  33. package/dist/chunk-KJNAORKM.js +15 -0
  34. package/dist/chunk-L47LZYVG.js +21 -0
  35. package/dist/chunk-LU3D53ZV.js +34 -0
  36. package/dist/{chunk-YKYRNTPV.js → chunk-N2OLEUAQ.js} +1 -1
  37. package/dist/{chunk-PHT24MOV.js → chunk-NLTYJUQG.js} +1 -1
  38. package/dist/chunk-NNMQGISW.js +1 -0
  39. package/dist/chunk-NPGZRSGL.js +5 -0
  40. package/dist/chunk-NTVLV7NI.js +1 -0
  41. package/dist/chunk-NUJSTEV4.js +1 -0
  42. package/dist/{chunk-FUWPDXXG.js → chunk-NWGRLNUM.js} +1 -1
  43. package/dist/chunk-OQ3JOTPK.js +1 -0
  44. package/dist/chunk-RBJPQYV3.js +6 -0
  45. package/dist/chunk-SVUP3F4V.js +14 -0
  46. package/dist/chunk-TLMG5W3L.js +4 -0
  47. package/dist/chunk-TLP4ZMJB.js +19 -0
  48. package/dist/{chunk-WQFNB2MQ.js → chunk-TZCMK3UG.js} +6 -6
  49. package/dist/chunk-UFWMUBFH.js +25 -0
  50. package/dist/chunk-VKKDSXMR.js +1 -0
  51. package/dist/chunk-VNXTBIPI.js +31 -0
  52. package/dist/chunk-XF7YHFVR.js +15 -0
  53. package/dist/{chunk-X5V4VMET.js → chunk-XIVFVKMB.js} +2 -2
  54. package/dist/chunk-XYZVMTNN.js +1 -0
  55. package/dist/{chunk-Q2JQFDAK.js → chunk-XZEBYOFR.js} +3 -3
  56. package/dist/chunk-Z6LHGA27.js +1 -0
  57. package/dist/cli.js +10 -10
  58. package/dist/config-VHWLMFIN.js +1 -0
  59. package/dist/{config-GKVOAMY2.js → config-XO7TGH27.js} +1 -1
  60. package/dist/db-WCTOLFAZ.js +1 -0
  61. package/dist/delivery-log-ML4RJOBM.js +1 -0
  62. package/dist/dist-HCSYRPJU.js +1 -0
  63. package/dist/engine-XLH4VL6Y.js +1 -0
  64. package/dist/evolution-audit-HLU7LQL6.js +1 -0
  65. package/dist/execution-tools-SYP3GR6T.js +1 -0
  66. package/dist/{external-api-DOVGA3ML.js → external-api-YMEFVZGG.js} +1 -1
  67. package/dist/index.js +240 -36
  68. package/dist/learner-NJXX2RUL.js +1 -0
  69. package/dist/{logger-WEXZORHP.js → logger-PAMNFWI3.js} +1 -1
  70. package/dist/memories-JDTQM3UN.js +1 -0
  71. package/dist/memory-extractor-5PTMCSOX.js +1 -0
  72. package/dist/memory-gc-BCHTOSXK.js +1 -0
  73. package/dist/memory-service-66EMRJXO.js +1 -0
  74. package/dist/onnxruntime_binding-2BPLI7ZQ.node +0 -0
  75. package/dist/onnxruntime_binding-5J67DTMJ.node +0 -0
  76. package/dist/onnxruntime_binding-7ZZLEQ2F.node +0 -0
  77. package/dist/onnxruntime_binding-KDCXAPN5.node +0 -0
  78. package/dist/onnxruntime_binding-R73P2IQW.node +0 -0
  79. package/dist/outbound-gateway-3INYZDOR.js +1 -0
  80. package/dist/presets-DT3J2ON4.js +1 -0
  81. package/dist/reflection-job-ST4ANCGB.js +23 -0
  82. package/dist/role-presets-3IQKCSVQ.js +1 -0
  83. package/dist/role-workspace-SIHNI6HO.js +1 -0
  84. package/dist/roles-F6AEM6B5.js +1 -0
  85. package/dist/{runtime-QA2DCZYQ.js → runtime-TWLGJSL6.js} +1 -1
  86. package/dist/session-manager-JTQRJI7R.js +1 -0
  87. package/dist/skill-registry-4JT62GEF.js +1 -0
  88. package/dist/target-resolution-PSSBM4LX.js +1 -0
  89. package/dist/task-templates-6G46OVYT.js +1 -0
  90. package/dist/template-dispatch-2K7KV7YS.js +1 -0
  91. package/dist/template-execution-artifacts-NEPSVD2B.js +1 -0
  92. package/dist/trace-context-UR7DI5ME.js +1 -0
  93. package/package.json +34 -14
  94. package/web/dist/assets/{Button-VPwTNGpF.js → Button-fLMsJd5o.js} +1 -1
  95. package/web/dist/assets/{Card-C2N6k4gh.js → Card-cy-gHU0O.js} +1 -1
  96. package/web/dist/assets/{ChannelDetail-DktmpO0A.js → ChannelDetail-CsKBPHkT.js} +1 -1
  97. package/web/dist/assets/Channels-DMutLV9r.js +14 -0
  98. package/web/dist/assets/Chat-DWTs-iOw.js +2 -0
  99. package/web/dist/assets/Dashboard-CoatfhW8.js +1 -0
  100. package/web/dist/assets/{EmptyState-CWS9PJND.js → EmptyState-C5kVDHc7.js} +1 -1
  101. package/web/dist/assets/{EnvVarEditor-D0kGIBcl.js → EnvVarEditor-BvRsHayG.js} +1 -1
  102. package/web/dist/assets/{EventDefDetail-BiXTA6LF.js → EventDefDetail-zuJydp12.js} +1 -1
  103. package/web/dist/assets/Events-nCImjXyr.js +1 -0
  104. package/web/dist/assets/{Evolution-C884p_CE.js → Evolution-Br41g99g.js} +1 -1
  105. package/web/dist/assets/ExtensionDetail-BXlphIkn.js +1 -0
  106. package/web/dist/assets/Extensions-3lhbw0A2.js +1 -0
  107. package/web/dist/assets/{FeatureRequests-Ck0WQnXX.js → FeatureRequests-oaXQNu43.js} +1 -1
  108. package/web/dist/assets/{GoalDetail-DJOyf7By.js → GoalDetail-DRDg1JDv.js} +1 -1
  109. package/web/dist/assets/Goals-DGmKvtGA.js +1 -0
  110. package/web/dist/assets/{Logs-6r7fnBn7.js → Logs-BZKxhdnb.js} +1 -1
  111. package/web/dist/assets/{Memories-CvPaqv5r.js → Memories-DhJJk-KB.js} +1 -1
  112. package/web/dist/assets/{Mistakes-aUhkqHDC.js → Mistakes-DxThj9as.js} +1 -1
  113. package/web/dist/assets/{NotFound-R6tIzhL0.js → NotFound-buXr2gl7.js} +1 -1
  114. package/web/dist/assets/{PageHeader-D9lLjo0N.js → PageHeader-BgNbz3JV.js} +1 -1
  115. package/web/dist/assets/Plugins-BXrsGsXs.js +1 -0
  116. package/web/dist/assets/RoleDetail-rClUsHwS.js +35 -0
  117. package/web/dist/assets/Roles-DH9cRv8h.js +1 -0
  118. package/web/dist/assets/{SectionHeader-BB3H3F_P.js → SectionHeader-CwX6m1f6.js} +1 -1
  119. package/web/dist/assets/Settings-My2lOEWv.js +1 -0
  120. package/web/dist/assets/{Strategies-DUps-2I9.js → Strategies-YLMryJlG.js} +1 -1
  121. package/web/dist/assets/{Switch-B_R_EX9s.js → Switch-PNpjNoGn.js} +1 -1
  122. package/web/dist/assets/{Table-D4lT5uHx.js → Table-BrERwl-F.js} +1 -1
  123. package/web/dist/assets/{Tabs-CwzWpI-7.js → Tabs-CGHmpUAD.js} +1 -1
  124. package/web/dist/assets/TaskDetail-Bkaq0NwW.js +2 -0
  125. package/web/dist/assets/Work-4OcGMu_a.js +1 -0
  126. package/web/dist/assets/api-BkdixMz9.js +1 -0
  127. package/web/dist/assets/{es2015-DCW7LI8d.js → es2015-JqLIWAgH.js} +1 -1
  128. package/web/dist/assets/index-C-e-qpXc.js +12 -0
  129. package/web/dist/assets/index-DGTVc0qD.css +2 -0
  130. package/web/dist/assets/{useIsMobileLayout-D6Tz5o5h.js → useIsMobileLayout-Blj4Mk4K.js} +1 -1
  131. package/web/dist/assets/{usePluginsWithUsage-CSQr03vZ.js → usePluginsWithUsage-Ch9WCFTb.js} +1 -1
  132. package/web/dist/assets/vendor-icons-U4igmrUq.js +1 -0
  133. package/web/dist/assets/{vendor-react-CIkiuNDu.js → vendor-react-Bp_V-Hsf.js} +1 -1
  134. package/web/dist/assets/{vendor-state-CEOsUh-T.js → vendor-state-Zjl_6-V3.js} +1 -1
  135. package/web/dist/index.html +8 -8
  136. package/dist/App-5QZKMPRM.js +0 -13
  137. package/dist/adam-tools-SQD2V4RJ.js +0 -1
  138. package/dist/approval-handler-J6RUTICJ.js +0 -1
  139. package/dist/audit-manager-CWVHQAUI.js +0 -1
  140. package/dist/bree-engine-VGEYMVNP.js +0 -1
  141. package/dist/channels-OOIM62BX.js +0 -1
  142. package/dist/chunk-2BXTT4P2.js +0 -6
  143. package/dist/chunk-47COBMRF.js +0 -1
  144. package/dist/chunk-6JBSBSCL.js +0 -1
  145. package/dist/chunk-6WRZJVQ2.js +0 -1
  146. package/dist/chunk-7IFLU3CY.js +0 -4
  147. package/dist/chunk-AQO6IIHV.js +0 -684
  148. package/dist/chunk-AVM3O74V.js +0 -5
  149. package/dist/chunk-B544JOZM.js +0 -3
  150. package/dist/chunk-DZIEY4CH.js +0 -47
  151. package/dist/chunk-E4WIUUL4.js +0 -27
  152. package/dist/chunk-HDHMNT6D.js +0 -1
  153. package/dist/chunk-JYHOGBCP.js +0 -12
  154. package/dist/chunk-M3RZWIW3.js +0 -50
  155. package/dist/chunk-N4ES7TCL.js +0 -1
  156. package/dist/chunk-NPIXYK5G.js +0 -5
  157. package/dist/chunk-O7XQSONJ.js +0 -5
  158. package/dist/chunk-OZL6VNOR.js +0 -146
  159. package/dist/chunk-Q2ISNOBQ.js +0 -1
  160. package/dist/chunk-QYRI4HYA.js +0 -1
  161. package/dist/chunk-R2WB5BKF.js +0 -7
  162. package/dist/chunk-RMGBR3XZ.js +0 -21
  163. package/dist/chunk-S6OV7Z6K.js +0 -1
  164. package/dist/chunk-SC2DDRYB.js +0 -5
  165. package/dist/chunk-SGIKNIC5.js +0 -49
  166. package/dist/chunk-TI3AKKWZ.js +0 -80
  167. package/dist/chunk-U2LBBBWO.js +0 -8
  168. package/dist/chunk-UXDTFTG5.js +0 -10
  169. package/dist/chunk-Y5FFL6UO.js +0 -5
  170. package/dist/chunk-ZFDULJGB.js +0 -3
  171. package/dist/chunk-ZQ4PNKMQ.js +0 -10
  172. package/dist/config-DRFRLIVN.js +0 -1
  173. package/dist/db-FACSMWEY.js +0 -1
  174. package/dist/delivery-log-JIQMHBJ5.js +0 -1
  175. package/dist/dist-CDWBOTZS.js +0 -1
  176. package/dist/engine-OHYWUUMJ.js +0 -1
  177. package/dist/evolution-audit-M7FSYRQR.js +0 -1
  178. package/dist/learner-OUNQSWN7.js +0 -1
  179. package/dist/memories-ABE7PMQL.js +0 -1
  180. package/dist/memory-extractor-ZX2NJIBV.js +0 -6
  181. package/dist/memory-service-UWER3T2S.js +0 -1
  182. package/dist/onnxruntime_binding-6Q6HXASN.node +0 -0
  183. package/dist/onnxruntime_binding-EKZT2NRK.node +0 -0
  184. package/dist/onnxruntime_binding-P6S7V3CI.node +0 -0
  185. package/dist/onnxruntime_binding-PJNNIIUO.node +0 -0
  186. package/dist/onnxruntime_binding-UN6SPTQK.node +0 -0
  187. package/dist/outbound-gateway-XDCGAXXW.js +0 -1
  188. package/dist/presets-RMW3WO5P.js +0 -1
  189. package/dist/role-presets-FAXQRBII.js +0 -1
  190. package/dist/role-workspace-ISGPO25D.js +0 -1
  191. package/dist/roles-WNKRM6FD.js +0 -1
  192. package/dist/session-manager-SOJXQHHY.js +0 -1
  193. package/dist/task-templates-IS3DJCZB.js +0 -1
  194. package/dist/token-estimator-HMPVGDCN.js +0 -1
  195. package/dist/workflow-executor-LOMKVFPV.js +0 -1
  196. package/web/dist/assets/Channels-ozCXdZMq.js +0 -12
  197. package/web/dist/assets/Chat-CggvtidD.js +0 -2
  198. package/web/dist/assets/Dashboard-z37ZVhzH.js +0 -1
  199. package/web/dist/assets/Events-C4P3jjZd.js +0 -1
  200. package/web/dist/assets/Goals-CDZWDuXR.js +0 -1
  201. package/web/dist/assets/Plugins-CtwoMUoj.js +0 -1
  202. package/web/dist/assets/RoleDetail-B32225ae.js +0 -33
  203. package/web/dist/assets/Roles-CGYsxuq8.js +0 -1
  204. package/web/dist/assets/Settings-D2jrO8-G.js +0 -1
  205. package/web/dist/assets/TaskDetail-DKminIM_.js +0 -2
  206. package/web/dist/assets/Work-uD_6IieV.js +0 -1
  207. package/web/dist/assets/api-D-UzHSDq.js +0 -1
  208. package/web/dist/assets/index-6f2jcj0h.css +0 -2
  209. package/web/dist/assets/index-Bl-2p6d8.js +0 -12
  210. package/web/dist/assets/vendor-icons-jzPiR6xl.js +0 -1
@@ -0,0 +1,5 @@
1
+ import{l as s,n as l}from"./chunk-BPXS4QEO.js";l();function i(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,viewerKey:e.viewer_key??void 0,createdAt:e.created_at,updatedAt:e.updated_at??void 0,lastMessageAt:e.last_message_at??void 0,messageCount:e.message_count}}function r(e){s().prepare(`
2
+ INSERT INTO channels (id, name, platform, enabled, status, config, linked_role_id,
3
+ allowed_chat_ids, viewer_key, created_at, updated_at, last_message_at, message_count)
4
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
5
+ `).run(e.id,e.name,e.platform,e.enabled?1:0,e.status,JSON.stringify(e.config),e.linkedRoleId??null,e.allowedChatIds?JSON.stringify(e.allowedChatIds):null,e.viewerKey??null,e.createdAt,e.updatedAt??null,e.lastMessageAt??null,e.messageCount)}function o(e){let d=s().prepare("SELECT * FROM channels WHERE id = ?").get(e);return d?i(d):void 0}function f(e,n){let d=s(),t=[],a=[];n.name!==void 0&&(t.push("name = ?"),a.push(n.name)),n.enabled!==void 0&&(t.push("enabled = ?"),a.push(n.enabled?1:0)),n.status!==void 0&&(t.push("status = ?"),a.push(n.status)),n.config!==void 0&&(t.push("config = ?"),a.push(JSON.stringify(n.config))),n.linkedRoleId!==void 0&&(t.push("linked_role_id = ?"),a.push(n.linkedRoleId)),n.allowedChatIds!==void 0&&(t.push("allowed_chat_ids = ?"),a.push(JSON.stringify(n.allowedChatIds))),n.viewerKey!==void 0&&(t.push("viewer_key = ?"),a.push(n.viewerKey)),n.lastMessageAt!==void 0&&(t.push("last_message_at = ?"),a.push(n.lastMessageAt)),n.messageCount!==void 0&&(t.push("message_count = ?"),a.push(n.messageCount)),t.length!==0&&(t.push("updated_at = ?"),a.push(Date.now()),a.push(e),d.prepare(`UPDATE channels SET ${t.join(", ")} WHERE id = ?`).run(...a))}function h(e){let n=s();return e!==void 0?n.prepare("SELECT * FROM channels WHERE enabled = ? ORDER BY created_at DESC").all(e?1:0).map(i):n.prepare("SELECT * FROM channels ORDER BY created_at DESC").all().map(i)}function g(e){s().prepare("DELETE FROM channels WHERE id = ?").run(e)}function p(e,n){s().prepare("UPDATE channels SET status = ?, updated_at = ? WHERE id = ?").run(n,Date.now(),e)}export{r as a,o as b,f as c,h as d,g as e,p as f};
@@ -0,0 +1,6 @@
1
+ import{c as T,d as w}from"./chunk-ISKCTUI7.js";import{a as b}from"./chunk-DRO3DG7X.js";import{d as C,l as S,n as k,o as M,p as x,r as B}from"./chunk-XIVFVKMB.js";import{d as g}from"./chunk-Z6LHGA27.js";function R(e){let t=(e.match(/[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff]/g)||[]).length,n=e.length-t;return t+Math.ceil(n/4)}function F(e,t,n){let o=Math.max(0,t-e)/864e5;return Math.pow(.5,o/n)}function E(e){return e.useCount<=0?.5:e.successCount/e.useCount}function v(e,t,n){let s=g().memory,o=s.retrievalWeights,u=s.retrievalDecayDays,d=F(e.lastUsedAt,n,u),f=e.confidence,l=E(e),a=R(e.content),i=Math.min(1,a/s.globalBudgetTokens);return{score:o.cosSim*t+o.recency*d+o.confidence*f+o.successRate*l-o.tokenCost*i,tokenCost:a}}async function H(e,t,n={}){let s=n.topK??10,o=n.hybridConfig??x,u;try{u=await b(t)}catch{}let d=u??new Float32Array(384),f=B(e,d,t,s*2,o,{excludeSuperseded:!0}),l=e?M(e):S,a=f.map(({node:c,combinedRelevance:y})=>{let h=Math.min(.3,(c.retrievedCount??0)*.05),p=k(c.createdAt,y,c.importance,l)+h;return{...c,score:p}});a.sort((c,y)=>y.score-c.score);let i=a.slice(0,s);for(let c of i)C(c.id);return i}async function K(e,t,n){let s=g().memory,o=n?.topK??10,u=n?.budgetTokens??s.globalBudgetTokens,d;try{d=await b(e)}catch{d=new Float32Array(384)}let f=w(t,d,o);f.length===0&&(f=T(t,{includeSuperseded:!1}).slice(0,o).map(m=>({node:m,cosine:0})));let l=Date.now(),a=f.map(({node:r,cosine:m})=>{let{score:A,tokenCost:D}=v(r,m,l);return{belief:r,cosSim:m,score:A,tokenCost:D}});a.sort((r,m)=>m.score-r.score);let i=[],c=0,y=9;for(let r of a){let m=r.tokenCost+y;if(c+m>u)break;i.push(r),c+=r.tokenCost}if(i.length===0)return{selected:i,usedIds:[],contextString:""};let p=`[Memory Context \u2014 retrieved from prior interactions]
2
+ ${i.map(r=>r.belief.isAnti?`- [anti-pattern] \u274C ${r.belief.content}`:`- [belief] ${r.belief.content}`).join(`
3
+ `)}
4
+
5
+ [User Request]
6
+ `;return{selected:i,usedIds:i.map(r=>r.belief.id),contextString:p}}async function Q(e,t,n=5,s){try{if(!t)return"";let{contextString:o}=await K(e,t,{topK:n,budgetTokens:s});return o}catch{return""}}async function W(e,t,n,s={}){return(await H(e,t,s)).filter(u=>n.includes(u.tier??"episodic"))}export{H as a,K as b,Q as c,W as d};
@@ -1 +1 @@
1
- import{c as S,h as x}from"./chunk-MRTJFYPR.js";x();import*as s from"fs";import*as l from"path";import{homedir as F}from"os";var v=S("embedding"),M=null,A=!1;async function L(){if(A)throw new Error("onnxruntime-node native binding not available. Embedding disabled.");if(!M)try{M=await import("./dist-CDWBOTZS.js")}catch(e){throw A=!0,v.warn({error:e.message},"onnxruntime-node not available"),new Error("onnxruntime-node native binding not available. Embedding disabled.")}return M}var P=l.join(F(),".adam","models"),N="all-MiniLM-L6-v2",T="model.onnx",B="tokenizer.json",O="https://huggingface.co/Xenova/all-MiniLM-L6-v2/resolve/main/onnx/model_quantized.onnx",j="https://huggingface.co/Xenova/all-MiniLM-L6-v2/resolve/main/tokenizer.json",R=384,y=null,k=null;function z(){let e=l.join(P,N);return s.existsSync(e)||s.mkdirSync(e,{recursive:!0}),e}async function _(e,t){if(s.existsSync(t))return;v.info({file:l.basename(t)},"Downloading model file");let f=await fetch(e);if(!f.ok)throw new Error(`Failed to download ${e}: ${f.status}`);let i=Buffer.from(await f.arrayBuffer());s.writeFileSync(t,i),v.info({file:l.basename(t),sizeMb:(i.length/1024/1024).toFixed(1)},"Model file downloaded")}async function U(){let e=z(),t=l.join(e,T),f=l.join(e,B);return await _(O,t),await _(j,f),t}function $(){if(k)return k;let e=l.join(z(),B);if(!s.existsSync(e))throw new Error("Tokenizer not found. Run generateEmbedding first to download.");return k=JSON.parse(s.readFileSync(e,"utf-8")),k}function q(e,t=128){let i=$().model.vocab,w=i["[CLS]"]??101,I=i["[SEP]"]??102,u=i["[UNK]"]??100,E=i["[PAD]"]??0,p=e.toLowerCase().replace(/[^\w\s\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff]/g," ").split(/\s+/).filter(Boolean),r=[w];for(let o of p){if(r.length>=t-1)break;if(i[o]!==void 0){r.push(i[o]);continue}let d=!1,n=o,m=!0;for(;n.length>0&&r.length<t-1;){let D=!1;for(let g=n.length;g>0;g--){let b=m?n.slice(0,g):`##${n.slice(0,g)}`;if(i[b]!==void 0){r.push(i[b]),n=n.slice(g),m=!1,D=!0,d=!0;break}}if(!D)if(n.length>=2){let g=n.slice(0,2),b=i[g]??i[`##${g}`]??u;r.push(b),n=n.slice(2),d=!0}else r.push(u),n=""}d||r.push(u)}r.push(I);let h=new BigInt64Array(t),a=new BigInt64Array(t),c=new BigInt64Array(t);for(let o=0;o<t;o++)o<r.length?(h[o]=BigInt(r[o]),a[o]=1n):(h[o]=BigInt(E),a[o]=0n),c[o]=0n;return{inputIds:h,attentionMask:a,tokenTypeIds:c}}async function C(){if(y)return y;let e=await L(),t=await U();return y=await e.InferenceSession.create(t,{executionProviders:["cpu"]}),y}async function Z(e){let t=await L(),f=await C(),{inputIds:i,attentionMask:w,tokenTypeIds:I}=q(e),u=i.length,E={input_ids:new t.Tensor("int64",i,[1,u]),attention_mask:new t.Tensor("int64",w,[1,u]),token_type_ids:new t.Tensor("int64",I,[1,u])},p=await f.run(E),h=(p.last_hidden_state??p[Object.keys(p)[0]]).data,a=R,c=new Float32Array(a),o=0;for(let n=0;n<u;n++)if(w[n]===1n){o++;for(let m=0;m<a;m++)c[m]+=h[n*a+m]}if(o>0)for(let n=0;n<a;n++)c[n]/=o;let d=0;for(let n=0;n<a;n++)d+=c[n]*c[n];if(d=Math.sqrt(d),d>0)for(let n=0;n<a;n++)c[n]/=d;return c}function G(){let e=l.join(z(),T);return s.existsSync(e)}export{Z as a,G as b};
1
+ import{c as S,h as x}from"./chunk-BLCNUT53.js";x();import*as s from"fs";import*as l from"path";import{homedir as F}from"os";var v=S("embedding"),M=null,A=!1;async function L(){if(A)throw new Error("onnxruntime-node native binding not available. Embedding disabled.");if(!M)try{M=await import("./dist-HCSYRPJU.js")}catch(e){throw A=!0,v.warn({error:e.message},"onnxruntime-node not available"),new Error("onnxruntime-node native binding not available. Embedding disabled.")}return M}var P=l.join(F(),".adam","models"),N="all-MiniLM-L6-v2",T="model.onnx",B="tokenizer.json",O="https://huggingface.co/Xenova/all-MiniLM-L6-v2/resolve/main/onnx/model_quantized.onnx",j="https://huggingface.co/Xenova/all-MiniLM-L6-v2/resolve/main/tokenizer.json",R=384,y=null,k=null;function z(){let e=l.join(P,N);return s.existsSync(e)||s.mkdirSync(e,{recursive:!0}),e}async function _(e,t){if(s.existsSync(t))return;v.info({file:l.basename(t)},"Downloading model file");let f=await fetch(e);if(!f.ok)throw new Error(`Failed to download ${e}: ${f.status}`);let i=Buffer.from(await f.arrayBuffer());s.writeFileSync(t,i),v.info({file:l.basename(t),sizeMb:(i.length/1024/1024).toFixed(1)},"Model file downloaded")}async function U(){let e=z(),t=l.join(e,T),f=l.join(e,B);return await _(O,t),await _(j,f),t}function $(){if(k)return k;let e=l.join(z(),B);if(!s.existsSync(e))throw new Error("Tokenizer not found. Run generateEmbedding first to download.");return k=JSON.parse(s.readFileSync(e,"utf-8")),k}function q(e,t=128){let i=$().model.vocab,w=i["[CLS]"]??101,I=i["[SEP]"]??102,u=i["[UNK]"]??100,E=i["[PAD]"]??0,p=e.toLowerCase().replace(/[^\w\s\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff]/g," ").split(/\s+/).filter(Boolean),r=[w];for(let o of p){if(r.length>=t-1)break;if(i[o]!==void 0){r.push(i[o]);continue}let d=!1,n=o,m=!0;for(;n.length>0&&r.length<t-1;){let D=!1;for(let g=n.length;g>0;g--){let b=m?n.slice(0,g):`##${n.slice(0,g)}`;if(i[b]!==void 0){r.push(i[b]),n=n.slice(g),m=!1,D=!0,d=!0;break}}if(!D)if(n.length>=2){let g=n.slice(0,2),b=i[g]??i[`##${g}`]??u;r.push(b),n=n.slice(2),d=!0}else r.push(u),n=""}d||r.push(u)}r.push(I);let h=new BigInt64Array(t),a=new BigInt64Array(t),c=new BigInt64Array(t);for(let o=0;o<t;o++)o<r.length?(h[o]=BigInt(r[o]),a[o]=1n):(h[o]=BigInt(E),a[o]=0n),c[o]=0n;return{inputIds:h,attentionMask:a,tokenTypeIds:c}}async function C(){if(y)return y;let e=await L(),t=await U();return y=await e.InferenceSession.create(t,{executionProviders:["cpu"]}),y}async function Z(e){let t=await L(),f=await C(),{inputIds:i,attentionMask:w,tokenTypeIds:I}=q(e),u=i.length,E={input_ids:new t.Tensor("int64",i,[1,u]),attention_mask:new t.Tensor("int64",w,[1,u]),token_type_ids:new t.Tensor("int64",I,[1,u])},p=await f.run(E),h=(p.last_hidden_state??p[Object.keys(p)[0]]).data,a=R,c=new Float32Array(a),o=0;for(let n=0;n<u;n++)if(w[n]===1n){o++;for(let m=0;m<a;m++)c[m]+=h[n*a+m]}if(o>0)for(let n=0;n<a;n++)c[n]/=o;let d=0;for(let n=0;n<a;n++)d+=c[n]*c[n];if(d=Math.sqrt(d),d>0)for(let n=0;n<a;n++)c[n]/=d;return c}function G(){let e=l.join(z(),T);return s.existsSync(e)}export{Z as a,G as b};
@@ -0,0 +1 @@
1
+ import{g as We}from"./chunk-XF7YHFVR.js";import{a as ze,b as k,c as Ee,d as L,e as He}from"./chunk-NNMQGISW.js";import{b as Ve,c as Qe,f as se,g as re}from"./chunk-3KNR2F6H.js";import{a as je,b as T,c as te,d as ne,e as Te,f as V}from"./chunk-CLNYHWZ6.js";import{d as j}from"./chunk-Z6LHGA27.js";import{c as y,h as C}from"./chunk-BLCNUT53.js";import{z as p}from"zod/v4";import{v4 as os}from"uuid";import{randomUUID as et}from"crypto";import Ht from"crypto";var Ke="2.1.7",ie="bot";function Kt(t){let e=t.split(".").map(i=>parseInt(i,10)),n=e[0]??0,r=e[1]??0,s=e[2]??0;return(n&255)<<16|(r&255)<<8|s&255}var xe=Kt(Ke),Jt=35e3,Je=15e3,Xt=1e4;function ae(){return{channel_version:Ke}}function Yt(t){return t.endsWith("/")?t:`${t}/`}function Zt(){let t=Ht.randomBytes(4).readUInt32BE(0);return Buffer.from(String(t),"utf-8").toString("base64")}function en(t){let e={"Content-Type":"application/json",AuthorizationType:"ilink_bot_token","Content-Length":String(Buffer.byteLength(t.body,"utf-8")),"X-WECHAT-UIN":Zt(),"iLink-App-Id":ie,"iLink-App-ClientVersion":String(xe)};return t.token?.trim()&&(e.Authorization=`Bearer ${t.token.trim()}`),t.routeTag&&(e.SKRouteTag=t.routeTag),e}async function oe(t){let e=Yt(t.baseUrl),n=new URL(t.endpoint,e),r=en({token:t.token,routeTag:t.routeTag,body:t.body}),s=new AbortController,i=setTimeout(()=>s.abort(),t.timeoutMs);try{let a=await fetch(n.toString(),{method:"POST",headers:r,body:t.body,signal:s.signal});clearTimeout(i);let o=await a.text();if(!a.ok)throw new Error(`${t.label} ${a.status}: ${o}`);return o}catch(a){throw clearTimeout(i),a}}async function Xe(t){let e=t.timeoutMs??Jt;try{let n=await oe({baseUrl:t.baseUrl,endpoint:"ilink/bot/getupdates",body:JSON.stringify({get_updates_buf:t.get_updates_buf??"",base_info:ae()}),token:t.token,routeTag:t.routeTag,timeoutMs:e,label:"getUpdates"});return JSON.parse(n)}catch(n){if(n instanceof Error&&n.name==="AbortError")return{ret:0,msgs:[],get_updates_buf:t.get_updates_buf};throw n}}var tn={[-2]:2,[-3]:3},nn=1e3;async function Q(t){let e=(await import("./logger-PAMNFWI3.js")).getLogger("channels"),n=new Map;for(;;){let r=await oe({baseUrl:t.baseUrl,endpoint:"ilink/bot/sendmessage",body:JSON.stringify({...t.body,base_info:ae()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??Je,label:"sendMessage"});e.info({status:200,responseBody:r.slice(0,300)},"apiFetch sendMessage response");try{let s=JSON.parse(r);if(s.ret&&s.ret!==0){let i=tn[s.ret],a=(n.get(s.ret)??0)+1;if(n.set(s.ret,a),i!==void 0&&a<i){e.warn({ret:s.ret,attempt:a,maxRetries:i},"sendMessage: retriable iLink error, retrying"),await new Promise(o=>setTimeout(o,nn*a));continue}throw e.error({ret:s.ret,errmsg:s.errmsg,attempt:a},"sendMessage: iLink API error, no more retries"),new Error(`sendMessage failed: iLink ret=${s.ret}${s.errmsg?` errmsg=${s.errmsg}`:""}`)}}catch(s){if(s instanceof SyntaxError)e.warn({rawText:r.slice(0,200)},"sendMessage: non-JSON response, treating as success");else throw s}return}}async function Ye(t){await oe({baseUrl:t.baseUrl,endpoint:"ilink/bot/sendtyping",body:JSON.stringify({...t.body,base_info:ae()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??Xt,label:"sendTyping"})}async function Ze(t){let e=await oe({baseUrl:t.baseUrl,endpoint:"ilink/bot/getuploadurl",body:JSON.stringify({filekey:t.filekey,media_type:t.media_type,to_user_id:t.to_user_id,rawsize:t.rawsize,rawfilemd5:t.rawfilemd5,filesize:t.filesize,thumb_rawsize:t.thumb_rawsize,thumb_rawfilemd5:t.thumb_rawfilemd5,thumb_filesize:t.thumb_filesize,no_need_thumb:t.no_need_thumb,aeskey:t.aeskey,base_info:ae()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??Je,label:"getUploadUrl"});return JSON.parse(e)}var sn=5*6e4,rn=35e3,tt="3",E=new Map;function Me(t){return Date.now()-t.startedAt<sn}function an(){for(let[t,e]of E)Me(e)||E.delete(t)}async function nt(t,e,n){let r=t.endsWith("/")?t:`${t}/`,s=new URL(`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(e)}`,r),i={"iLink-App-Id":ie};n&&(i.SKRouteTag=n);let a=await fetch(s.toString(),{headers:i});if(!a.ok){let o=await a.text().catch(()=>"(unreadable)");throw new Error(`Failed to fetch QR code: ${a.status} ${a.statusText} body=${o}`)}return await a.json()}async function on(t,e,n){let r=t.endsWith("/")?t:`${t}/`,s=new URL(`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(e)}`,r),i={"iLink-App-Id":ie,"iLink-App-ClientVersion":String(xe)};n&&(i.SKRouteTag=n);let a=new AbortController,o=setTimeout(()=>a.abort(),rn);try{let d=await fetch(s.toString(),{headers:i,signal:a.signal});clearTimeout(o);let c=await d.text();if(!d.ok)throw new Error(`Failed to poll QR status: ${d.status} ${d.statusText}`);return JSON.parse(c)}catch(d){if(clearTimeout(o),d instanceof Error&&d.name==="AbortError")return{status:"wait"};throw d}}async function st(t){let e=t.accountId||et();an();let n=E.get(e);if(!t.force&&n&&Me(n)&&n.qrcodeUrl)return{qrcodeUrl:n.qrcodeUrl,message:"QR code ready. Scan with WeChat.",sessionKey:e};if(!t.apiBaseUrl)return{message:"No baseUrl configured for this WeChat channel.",sessionKey:e};try{let r=t.botType||tt,s=await nt(t.apiBaseUrl,r,t.routeTag),i={sessionKey:e,id:et(),qrcode:s.qrcode,qrcodeUrl:s.qrcode_img_content,startedAt:Date.now()};return E.set(e,i),{qrcodeUrl:s.qrcode_img_content,message:"Scan the QR code with WeChat to connect.",sessionKey:e}}catch(r){return{message:`Failed to start login: ${String(r)}`,sessionKey:e}}}var dn=3;async function rt(t){let e=E.get(t.sessionKey);if(!e)return{connected:!1,message:"No active login session. Start QR login first."};if(!Me(e))return E.delete(t.sessionKey),{connected:!1,message:"QR code expired. Please start again."};let n=Math.max(t.timeoutMs??48e4,1e3),r=Date.now()+n,s=1;for(;Date.now()<r;){try{let i=await on(t.apiBaseUrl,e.qrcode,t.routeTag);switch(e.status=i.status,i.status){case"wait":break;case"scaned":break;case"expired":{if(s++,s>dn)return E.delete(t.sessionKey),{connected:!1,message:"Login timeout: QR expired multiple times."};try{let a=t.botType||tt,o=await nt(t.apiBaseUrl,a,t.routeTag);e.qrcode=o.qrcode,e.qrcodeUrl=o.qrcode_img_content,e.startedAt=Date.now()}catch(a){return E.delete(t.sessionKey),{connected:!1,message:`QR refresh failed: ${String(a)}`}}break}case"confirmed":return i.ilink_bot_id?(E.delete(t.sessionKey),{connected:!0,botToken:i.bot_token,accountId:i.ilink_bot_id,baseUrl:i.baseurl,userId:i.ilink_user_id,message:"Connected to WeChat successfully!"}):(E.delete(t.sessionKey),{connected:!1,message:"Login failed: server did not return bot ID."})}}catch(i){return E.delete(t.sessionKey),{connected:!1,message:`Login failed: ${String(i)}`}}await new Promise(i=>setTimeout(i,1e3))}return E.delete(t.sessionKey),{connected:!1,message:"Login timeout. Please try again."}}import A from"fs";import*as M from"fs/promises";import x from"path";import{homedir as pe}from"os";var de={IMAGE:1,VIDEO:2,FILE:3,VOICE:4},z={NONE:0,USER:1,BOT:2},_={NONE:0,TEXT:1,IMAGE:2,VOICE:3,FILE:4,VIDEO:5},H={NEW:0,GENERATING:1,FINISH:2},it={TYPING:1,CANCEL:2};C();var un=y("channels"),Se=-14,ue=3600*1e3,q=new Map;function at(t){let e=Date.now()+ue;q.set(t,e),un.info({channelId:t},`Session paused until ${new Date(e).toISOString()} (${ue/1e3}s)`)}function ce(t){let e=q.get(t);return e===void 0?!1:Date.now()>=e?(q.delete(t),!1):!0}function ot(t){let e=q.get(t);if(e===void 0)return 0;let n=e-Date.now();return n<=0?(q.delete(t),0):n}function dt(t){q.delete(t)}C();import*as me from"fs/promises";import yt from"path";import{homedir as pn}from"os";import{createCipheriv as cn,createDecipheriv as ln}from"crypto";function ut(t,e){let n=cn("aes-128-ecb",e,null);return Buffer.concat([n.update(t),n.final()])}function ct(t,e){let n=ln("aes-128-ecb",e,null);return Buffer.concat([n.update(t),n.final()])}function lt(t){return Math.ceil((t+1)/16)*16}function Ce(t,e){return`${e}/download?encrypted_query_param=${encodeURIComponent(t)}`}function mt(t){return`${t.cdnBaseUrl}/upload?encrypted_query_param=${encodeURIComponent(t.uploadParam)}&filekey=${encodeURIComponent(t.filekey)}`}C();var Ms=y("channels");function mn(t){let e=Buffer.from(t,"base64");if(e.length===16)return e;if(e.length===32&&/^[0-9a-fA-F]{32}$/.test(e.toString("ascii")))return Buffer.from(e.toString("ascii"),"hex");throw new Error(`aes_key must decode to 16 raw bytes or 32-char hex, got ${e.length} bytes`)}async function gt(t){let e=await fetch(t);if(!e.ok)throw new Error(`CDN download ${e.status} ${e.statusText}`);return Buffer.from(await e.arrayBuffer())}async function K(t){let{encryptQueryParam:e,aesKeyBase64:n,cdnBaseUrl:r,fullUrl:s}=t,i=mn(n),a=s?.trim()||(e?Ce(e,r):null);if(!a)throw new Error("CDN download: need full_url or encrypt_query_param");let o=await gt(a);return ct(o,i)}async function pt(t){let{encryptQueryParam:e,cdnBaseUrl:n,fullUrl:r}=t,s=r?.trim()||(e?Ce(e,n):null);if(!s)throw new Error("CDN download: need full_url or encrypt_query_param");return gt(s)}C();var le=y("channels"),ft=24e3;function gn(t,e){let n=t.byteLength,r=44+n,s=Buffer.allocUnsafe(r),i=0;return s.write("RIFF",i),i+=4,s.writeUInt32LE(r-8,i),i+=4,s.write("WAVE",i),i+=4,s.write("fmt ",i),i+=4,s.writeUInt32LE(16,i),i+=4,s.writeUInt16LE(1,i),i+=2,s.writeUInt16LE(1,i),i+=2,s.writeUInt32LE(e,i),i+=4,s.writeUInt32LE(e*2,i),i+=4,s.writeUInt16LE(2,i),i+=2,s.writeUInt16LE(16,i),i+=2,s.write("data",i),i+=4,s.writeUInt32LE(n,i),i+=4,Buffer.from(t.buffer,t.byteOffset,t.byteLength).copy(s,i),s}async function ht(t){try{let{decode:e}=await import("silk-wasm");le.debug(`silkToWav: decoding ${t.length} bytes of SILK`);let n=await e(t,ft);le.debug(`silkToWav: decoded duration=${n.duration}ms pcmBytes=${n.data.byteLength}`);let r=gn(n.data,ft);return le.debug(`silkToWav: WAV size=${r.length}`),r}catch(e){return le.warn(`silkToWav: transcode failed, will use raw silk err=${String(e)}`),null}}var N=y("channels"),wt=100*1024*1024;function fn(t){return re(t)??".bin"}async function J(t,e,n,r,s=wt,i){if(t.length>s)throw new Error(`Media too large: ${t.length} bytes exceeds ${s} bytes`);let a=yt.join(pn(),".adam","wechat","media",r,n);await me.mkdir(a,{recursive:!0});let o;if(i&&/^[a-zA-Z0-9._-]+$/.test(i))o=i;else{let c=e?fn(e):".bin",u=Date.now(),g=Math.random().toString(36).slice(2,7);o=`${u}-${g}${c}`}let d=yt.join(a,o);return await me.writeFile(d,t),N.debug(`saveMedia: saved ${t.length} bytes to ${d}`),d}async function bt(t,e){let{cdnBaseUrl:n,channelId:r}=e;if(t.type===_.IMAGE){let s=t.image_item;if(!s?.media?.encrypt_query_param&&!s?.media?.full_url)return null;let i=s.aeskey?Buffer.from(s.aeskey,"hex").toString("base64"):s.media?.aes_key;try{let a=i?await K({encryptQueryParam:s.media?.encrypt_query_param,aesKeyBase64:i,cdnBaseUrl:n,fullUrl:s.media?.full_url}):await pt({encryptQueryParam:s.media?.encrypt_query_param,cdnBaseUrl:n,fullUrl:s.media?.full_url});return{path:await J(a,"image/png","inbound",r),mimeType:"image/png",type:"image"}}catch(a){return N.error({channelId:r},`Image download/decrypt failed: ${String(a)}`),null}}if(t.type===_.VOICE){let s=t.voice_item;if(!s?.media?.encrypt_query_param&&!s?.media?.full_url||!s?.media?.aes_key)return null;try{let i=await K({encryptQueryParam:s.media.encrypt_query_param,aesKeyBase64:s.media.aes_key,cdnBaseUrl:n,fullUrl:s.media.full_url}),a=await ht(i);if(a){let o=await J(a,"audio/wav","inbound",r);return N.debug(`Voice: saved WAV to ${o}`),{path:o,mimeType:"audio/wav",type:"audio"}}else{let o=await J(i,"audio/silk","inbound",r);return N.debug(`Voice: silk transcode unavailable, saved raw SILK to ${o}`),{path:o,mimeType:"audio/silk",type:"audio"}}}catch(i){return N.error({channelId:r},`Voice download/transcode failed: ${String(i)}`),null}}if(t.type===_.FILE){let s=t.file_item;if(!s?.media?.encrypt_query_param&&!s?.media?.full_url||!s?.media?.aes_key)return null;try{let i=await K({encryptQueryParam:s.media.encrypt_query_param,aesKeyBase64:s.media.aes_key,cdnBaseUrl:n,fullUrl:s.media.full_url}),a=se(s.file_name??"file.bin");return{path:await J(i,a,"inbound",r,wt,s.file_name),mimeType:a,type:"file"}}catch(i){return N.error({channelId:r},`File download failed: ${String(i)}`),null}}if(t.type===_.VIDEO){let s=t.video_item;if(!s?.media?.encrypt_query_param&&!s?.media?.full_url||!s?.media?.aes_key)return null;try{let i=await K({encryptQueryParam:s.media.encrypt_query_param,aesKeyBase64:s.media.aes_key,cdnBaseUrl:n,fullUrl:s.media.full_url});return{path:await J(i,"video/mp4","inbound",r),mimeType:"video/mp4",type:"video"}}catch(i){return N.error({channelId:r},`Video download failed: ${String(i)}`),null}}return null}import Tt from"path";import Ae from"crypto";import hn from"fs/promises";C();var O=y("channels"),ge=3;async function yn(t){let{buf:e,uploadFullUrl:n,uploadParam:r,filekey:s,cdnBaseUrl:i,label:a,aeskey:o}=t,d=ut(e,o),c=n?.trim(),u;if(c)u=c;else if(r)u=mt({cdnBaseUrl:i,uploadParam:r,filekey:s});else throw new Error(`${a}: CDN upload URL missing (need upload_full_url or upload_param)`);O.debug(`${a}: CDN POST url=${u} ciphertextSize=${d.length}`);let g,f;for(let m=1;m<=ge;m++)try{let l=await fetch(u,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:new Uint8Array(d)});if(l.status>=400&&l.status<500){let w=l.headers.get("x-error-message")??await l.text();throw O.error(`${a}: CDN client error attempt=${m} status=${l.status} errMsg=${w}`),new Error(`CDN upload client error ${l.status}: ${w}`)}if(l.status!==200){let w=l.headers.get("x-error-message")??`status ${l.status}`;throw O.error(`${a}: CDN server error attempt=${m} status=${l.status} errMsg=${w}`),new Error(`CDN upload server error: ${w}`)}if(g=l.headers.get("x-encrypted-param")??void 0,!g)throw O.error(`${a}: CDN response missing x-encrypted-param header attempt=${m}`),new Error("CDN upload response missing x-encrypted-param header");O.debug(`${a}: CDN upload success attempt=${m}`);break}catch(l){if(f=l,l instanceof Error&&l.message.includes("client error"))throw l;m<ge?O.warn(`${a}: attempt ${m} failed, retrying... err=${String(l)}`):O.error(`${a}: all ${ge} attempts failed err=${String(l)}`)}if(!g)throw f instanceof Error?f:new Error(`CDN upload failed after ${ge} attempts`);return{downloadParam:g}}async function Re(t){let{filePath:e,toUserId:n,opts:r,cdnBaseUrl:s,mediaType:i,label:a}=t,o=await hn.readFile(e),d=o.length,c=Ae.createHash("md5").update(o).digest("hex"),u=lt(d),g=Ae.randomBytes(16).toString("hex"),f=Ae.randomBytes(16);O.debug(`${a}: file=${e} rawsize=${d} filesize=${u} md5=${c} filekey=${g}`);let m=await Ze({...r,filekey:g,media_type:i,to_user_id:n,rawsize:d,rawfilemd5:c,filesize:u,no_need_thumb:!0,aeskey:f.toString("hex")}),l=m.upload_full_url?.trim(),w=m.upload_param;if(!l&&!w)throw new Error(`${a}: getUploadUrl returned no upload URL (need upload_full_url or upload_param)`);let{downloadParam:F}=await yn({buf:o,uploadFullUrl:l||void 0,uploadParam:w??void 0,filekey:g,cdnBaseUrl:s,aeskey:f,label:`${a}[orig filekey=${g}]`});return{filekey:g,downloadEncryptedQueryParam:F,aeskey:f.toString("hex"),fileSize:d,fileSizeCiphertext:u}}async function _t(t){return Re({...t,mediaType:de.IMAGE,label:"uploadImageToWeixin"})}async function It(t){return Re({...t,mediaType:de.VIDEO,label:"uploadVideoToWeixin"})}async function ke(t){return Re({...t,mediaType:de.FILE,label:"uploadFileAttachmentToWeixin"})}C();var X=y("channels");function wn(){return`adam-wechat-${Date.now()}-${Math.random().toString(36).slice(2,7)}`}function bn(t){let e=t;return e=e.replace(/```[^\n]*\n?([\s\S]*?)```/g,(n,r)=>r.trim()),e=e.replace(/!\[[^\]]*\]\([^)]*\)/g,""),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/^\|[\s:|-]+\|$/gm,""),e=e.replace(/^\|(.+)\|$/gm,(n,r)=>r.split("|").map(s=>s.trim()).join(" ")),e}async function Ue(t){let{to:e,text:n,mediaItem:r,opts:s,label:i}=t,a=[],o=bn(n);o&&a.push({type:_.TEXT,text_item:{text:o}}),a.push(r);let d="";for(let c of a){d=wn();let u={msg:{from_user_id:"",to_user_id:e,client_id:d,message_type:z.BOT,message_state:H.FINISH,item_list:[c],context_token:s.contextToken}};await Q({baseUrl:s.baseUrl,token:s.token,routeTag:s.routeTag,body:u})}return X.debug(`${i}: sent to=${e} messageId=${d}`),{messageId:d}}async function _n(t){let{to:e,text:n,uploaded:r,opts:s}=t,i={type:_.IMAGE,image_item:{media:{encrypt_query_param:r.downloadEncryptedQueryParam,aes_key:Buffer.from(r.aeskey).toString("base64"),encrypt_type:1},mid_size:r.fileSizeCiphertext}};return Ue({to:e,text:n,mediaItem:i,opts:s,label:"sendImageMessage"})}async function In(t){let{to:e,text:n,uploaded:r,opts:s}=t,i={type:_.VIDEO,video_item:{media:{encrypt_query_param:r.downloadEncryptedQueryParam,aes_key:Buffer.from(r.aeskey).toString("base64"),encrypt_type:1},video_size:r.fileSizeCiphertext}};return Ue({to:e,text:n,mediaItem:i,opts:s,label:"sendVideoMessage"})}async function Et(t){let{to:e,text:n,fileName:r,uploaded:s,opts:i}=t,a={type:_.FILE,file_item:{media:{encrypt_query_param:s.downloadEncryptedQueryParam,aes_key:Buffer.from(s.aeskey).toString("base64"),encrypt_type:1},file_name:r,len:String(s.fileSize)}};return Ue({to:e,text:n,mediaItem:a,opts:i,label:"sendFileMessage"})}async function xt(t){let{filePath:e,to:n,text:r,opts:s,cdnBaseUrl:i}=t,a=se(e),o={baseUrl:s.baseUrl,token:s.token,routeTag:s.routeTag};if(a.startsWith("video/")){X.debug(`sendWeixinMediaFile: uploading video filePath=${e} to=${n}`);let u=await It({filePath:e,toUserId:n,opts:o,cdnBaseUrl:i});return In({to:n,text:r,uploaded:u,opts:s})}if(a.startsWith("image/")){X.debug(`sendWeixinMediaFile: uploading image filePath=${e} to=${n}`);let u=await _t({filePath:e,toUserId:n,opts:o,cdnBaseUrl:i});return _n({to:n,text:r,uploaded:u,opts:s})}if(a.startsWith("audio/")){let u=Tt.basename(e);X.debug(`sendWeixinMediaFile: uploading audio as file filePath=${e} name=${u} to=${n}`);let g=await ke({filePath:e,fileName:u,toUserId:n,opts:o,cdnBaseUrl:i});return Et({to:n,text:r,fileName:u,uploaded:g,opts:s})}let d=Tt.basename(e);X.debug(`sendWeixinMediaFile: uploading file attachment filePath=${e} name=${d} to=${n}`);let c=await ke({filePath:e,fileName:d,toUserId:n,opts:o,cdnBaseUrl:i});return Et({to:n,text:r,fileName:d,uploaded:c,opts:s})}C();var h=y("channels"),Mt="https://novac2c.cdn.weixin.qq.com/c2c",Oe=new Map;function At(t){return x.join(pe(),".adam","wechat",`${t}.context-tokens.json`)}function Tn(t){let e=At(t);try{let n=A.readFileSync(e,"utf-8"),r=JSON.parse(n);for(let[s,i]of Object.entries(r))typeof i=="string"&&i&&Oe.set(`${t}:${s}`,i);h.debug({channelId:t,count:Object.keys(r).length},"Restored context tokens from disk")}catch{}}function En(t,e,n){let r=At(t);try{let s={};try{let a=A.readFileSync(r,"utf-8");s=JSON.parse(a)}catch{}s[e]=n;let i=x.dirname(r);A.mkdirSync(i,{recursive:!0}),A.writeFileSync(r,JSON.stringify(s),"utf-8")}catch(s){h.warn({channelId:t,userId:e},`Failed to persist context token: ${String(s)}`)}}function xn(t,e,n){Oe.set(`${t}:${e}`,n),En(t,e,n)}function Pe(t,e){return Oe.get(`${t}:${e}`)}function Rt(t){return x.join(pe(),".adam","wechat",`${t}.sync`)}function Mn(t){try{return A.readFileSync(Rt(t),"utf-8")}catch{return""}}function Sn(t,e){let n=Rt(t);A.mkdirSync(x.dirname(n),{recursive:!0}),A.writeFileSync(n,e,"utf-8")}var ve=1440*60*1e3,St=10,Cn=20,Ct=1440*60*1e3,An=1320*60*1e3,Rn=1,kn=7200*1e3;function kt(t){return x.join(pe(),".adam","wechat",`${t}.session.json`)}function Un(t){let e=new Map,n=kt(t);try{let r=A.readFileSync(n,"utf-8"),s=JSON.parse(r);for(let[i,a]of Object.entries(s))a&&typeof a.lastUserMessageAt=="number"&&e.set(i,a);h.debug({channelId:t,count:e.size},"Restored sessions from disk")}catch{}return e}function Y(t,e){let n=kt(t);try{let r={};for(let[i,a]of e)r[i]=a;let s=x.dirname(n);A.mkdirSync(s,{recursive:!0}),A.writeFileSync(n,JSON.stringify(r),"utf-8")}catch(r){h.warn({channelId:t},`Failed to persist sessions: ${String(r)}`)}}var Pn=0;function Z(){return`adam-wechat-${Date.now()}-${++Pn}`}var $=class{platform="wechat";id;config;status="disconnected";messageHandler=null;pollAbort=null;getUpdatesBuf="";sessions=new Map;pendingQueue=new Map;lastReminderAt=new Map;constructor(e,n){if(this.id=e,!n.baseUrl)throw new Error("WeChat adapter requires baseUrl");this.config=n}async connect(){if(!this.config.botToken)throw new Error("WeChat adapter requires botToken. Complete QR login first.");this.status="connecting",this.getUpdatesBuf=Mn(this.id),Tn(this.id),this.sessions=Un(this.id),this.pollAbort=new AbortController,this.status="connected",h.info({channelId:this.id},"WeChat adapter connected, starting long-poll"),this.startLongPoll()}async disconnect(){this.pollAbort&&(this.pollAbort.abort(),this.pollAbort=null),this.status="disconnected",h.info({channelId:this.id},"WeChat adapter disconnected")}getStatus(){if(this.status==="connected"&&ce(this.id))return"error";if(this.status==="connected"){for(let[,e]of this.sessions)if(this.isSessionActive(e)&&e.quotaRemaining<=0)return"degraded"}return this.status}getCapabilities(){return{canEdit:!1,canQuote:!0,canParseQuote:!0,canInlineButtons:!1,maxTextLength:4e3,supportsAttachments:!0,maxAttachmentsPerMessage:1}}async sendMessage(e,n){if(ce(this.id)){let c=Math.ceil(ot(this.id)/6e4);throw new Error(`WeChat session paused, ${c} min remaining. Re-scan QR to reconnect.`)}let r=this.getOrCreateSession(e),i=this.getSessionRemainingMs(r)/36e5;if(!this.isSessionActive(r))return h.warn({channelId:this.id,chatId:e.slice(0,12),lastUserMessageAt:r.lastUserMessageAt,sessionExpired:!0},"iLink session expired (>24h), message queued"),this.enqueueMessage(e,n),`queued-${Z()}`;if(r.quotaRemaining<=0)return h.warn({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:0,remainingHours:i.toFixed(1)},"iLink quota exhausted, message queued"),this.enqueueMessage(e,n),`queued-${Z()}`;let a=Z(),o=Pe(this.id,e),d=this.config.cdnBaseUrl??Mt;try{let c=n.attachments?.[0],u=c?.path??n.mediaUrl,g=c?.contentType,f=c?.filename,m=c?.mediaType??n.mediaType;if(u){let l=!u.includes("://")||u.startsWith("file://"),w=x.join(pe(),".adam","wechat","media","outbound-tmp");await M.mkdir(w,{recursive:!0});let F=this.getExtensionFromMediaType(m,g),R;if(l){let I=u.startsWith("file://")?new URL(u).pathname:x.isAbsolute(u)?u:x.resolve(u),v=await M.readFile(I);R=x.join(w,`${Date.now()}-${Math.random().toString(36).slice(2,7)}${F}`),await M.writeFile(R,v)}else{let I=await fetch(u);if(!I.ok)throw new Error(`Failed to fetch media: ${I.status}`);let v=Buffer.from(await I.arrayBuffer());R=x.join(w,`${Date.now()}-${Math.random().toString(36).slice(2,7)}${F}`),await M.writeFile(R,v)}let b=R;if(f){let I=f.replace(/[\\/]/g,"-").replace(/\.\./g,"-").replace(/[\x00-\x1f]/g,"");if(I.length>0&&I.length<200){let v=x.join(w,`${Date.now()}-${I}`);await M.copyFile(R,v),await M.unlink(R).catch(()=>{}),b=v}}let P=await xt({filePath:b,to:e,text:n.content??"",opts:{baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,contextToken:o},cdnBaseUrl:d});return await M.unlink(b).catch(()=>{}),r.quotaRemaining--,Y(this.id,this.sessions),h.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:r.quotaRemaining,sessionRemainingHours:(this.getSessionRemainingMs(r)/36e5).toFixed(1)},"iLink send success: quota decremented"),this.checkAndSendReminder(e,r).catch(I=>{h.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(I)}`)}),P.messageId}return await Q({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{msg:{from_user_id:"",to_user_id:e,client_id:a,message_type:z.BOT,message_state:H.FINISH,item_list:this.buildItemList(n),context_token:o}}}),r.quotaRemaining--,Y(this.id,this.sessions),h.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:r.quotaRemaining,sessionRemainingHours:(this.getSessionRemainingMs(r)/36e5).toFixed(1)},"iLink send success: quota decremented"),this.checkAndSendReminder(e,r).catch(l=>{h.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(l)}`)}),a}catch(c){if(c instanceof Error&&c.message.includes("ret=-2"))return r.quotaRemaining=0,Y(this.id,this.sessions),h.warn({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:0},"iLink quota exhausted (ret=-2 confirmed), message queued"),this.enqueueMessage(e,n),`queued-${Z()}`;throw c}}onMessage(e){this.messageHandler=e}async sendTypingIndicator(e){if(ce(this.id))return;let n=Pe(this.id,e);try{await Ye({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{ilink_user_id:e,status:it.TYPING}})}catch{}}updateConfig(e){Object.assign(this.config,e)}buildItemList(e){if(!e.content)return;let n={type:_.TEXT,text_item:{text:e.content}};if(e.replyToMessageId){let r=(e.quoteExcerpt??"").slice(0,80);n.ref_msg={message_item:{msg_id:e.replyToMessageId,text_item:{text:r}},title:e.quoteTitle}}return[n]}getOrCreateSession(e){let n=this.sessions.get(e);return n||(n={lastUserMessageAt:0,quotaRemaining:0},this.sessions.set(e,n)),n}isSessionActive(e){return e.lastUserMessageAt>0&&Date.now()-e.lastUserMessageAt<=ve}getSessionRemainingMs(e){return e.lastUserMessageAt===0?0:Math.max(0,ve-(Date.now()-e.lastUserMessageAt))}enqueueMessage(e,n){let r=this.pendingQueue.get(e);r||(r=[],this.pendingQueue.set(e,r));let s=Date.now();r=r.filter(i=>s-i.queuedAt<Ct),r.length>=Cn&&(r.shift(),h.warn({channelId:this.id,chatId:e.slice(0,12)},"Queue full, dropping oldest message")),r.push({message:n,queuedAt:s}),this.pendingQueue.set(e,r),h.info({channelId:this.id,chatId:e.slice(0,12),queueDepth:r.length},"Message enqueued")}async flushQueue(e){let n=this.pendingQueue.get(e);if(!n||n.length===0)return;let r=this.getOrCreateSession(e),s=Math.min(n.length,Math.max(0,r.quotaRemaining-2));if(s<=0){h.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:r.quotaRemaining},"Queue flush skipped: insufficient quota (reserving 2 for conversation)");return}h.info({channelId:this.id,chatId:e.slice(0,12),queueDepth:n.length,sending:s,quotaRemaining:r.quotaRemaining},"Flushing queued messages");let i=0;for(;i<s&&n.length>0;){let a=n[0];if(Date.now()-a.queuedAt>Ct){n.shift();continue}try{if(await this.sendMessage(e,a.message),n.shift(),i++,r.quotaRemaining<=0)break}catch{h.warn({channelId:this.id,chatId:e.slice(0,12)},"Queue flush: send failed, stopping");break}}n.length===0&&this.pendingQueue.delete(e),h.info({channelId:this.id,chatId:e.slice(0,12),sent:i,remaining:n.length},"Queue flush complete")}async checkAndSendReminder(e,n){let r=Date.now(),s=this.lastReminderAt.get(e)??0;if(r-s<kn)return;let i=this.getSessionRemainingMs(n),o=r-n.lastUserMessageAt>=An,d=n.quotaRemaining<=Rn;if(!o&&!d)return;let c=(i/36e5).toFixed(1),u;o&&d?u=`[\u7CFB\u7EDF\u63D0\u9192] \u6D88\u606F\u7A97\u53E3\u5373\u5C06\u5173\u95ED\uFF08\u5269\u4F59${c}\u5C0F\u65F6/${n.quotaRemaining}\u6761\u914D\u989D\uFF09\u3002\u8BF7\u56DE\u590D\u4EFB\u610F\u6D88\u606F\u4EE5\u4FDD\u6301\u8FDE\u63A5\u3002`:o?u=`[\u7CFB\u7EDF\u63D0\u9192] \u6D88\u606F\u7A97\u53E3\u5373\u5C06\u5173\u95ED\uFF08\u5269\u4F59${c}\u5C0F\u65F6\uFF09\u3002\u8BF7\u56DE\u590D\u4EFB\u610F\u6D88\u606F\u4EE5\u4FDD\u6301\u8FDE\u63A5\u3002`:u=`[\u7CFB\u7EDF\u63D0\u9192] \u6D88\u606F\u914D\u989D\u5373\u5C06\u7528\u5B8C\uFF08\u5269\u4F59${n.quotaRemaining}\u6761\uFF09\u3002\u8BF7\u56DE\u590D\u4EFB\u610F\u6D88\u606F\u4EE5\u91CD\u7F6E\u914D\u989D\u3002`;let g=Pe(this.id,e);try{await Q({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{msg:{from_user_id:"",to_user_id:e,client_id:Z(),message_type:z.BOT,message_state:H.FINISH,item_list:[{type:_.TEXT,text_item:{text:u}}],context_token:g}}}),n.quotaRemaining--,this.lastReminderAt.set(e,r),Y(this.id,this.sessions),h.info({channelId:this.id,chatId:e.slice(0,12),remainingHours:c,quotaRemaining:n.quotaRemaining,trigger:o?"time":"quota"},"iLink session reminder sent")}catch(f){h.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(f)}`)}}async startLongPoll(){let e=this.pollAbort?.signal,n=0,r=3,s=3e4,i=2e3;for(;!e?.aborted;)try{let a=await Xe({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,get_updates_buf:this.getUpdatesBuf});if(a.ret===Se||a.errcode===Se){at(this.id),this.status="error",h.error({channelId:this.id},"Session expired (errcode=-14), pausing for 1 hour"),await this.sleep(ue,e),dt(this.id),this.status="connected";continue}if(a.ret!==void 0&&a.ret!==0||a.errcode!==void 0&&a.errcode!==0){n++,h.error({channelId:this.id,ret:a.ret,errcode:a.errcode},"getUpdates API error"),n>=r?(n=0,await this.sleep(s,e)):await this.sleep(i,e);continue}n=0,a.get_updates_buf&&(this.getUpdatesBuf=a.get_updates_buf,Sn(this.id,a.get_updates_buf));for(let d of a.msgs??[])await this.processInbound(d)}catch(a){if(e?.aborted)return;n++,h.error({channelId:this.id,error:a},"getUpdates error"),n>=r?(n=0,await this.sleep(s,e)):await this.sleep(i,e)}}async processInbound(e){if(!this.messageHandler)return;let n=!!e.group_id,r=n?e.group_id:e.from_user_id??"",s=e.from_user_id??"";e.context_token&&r&&xn(this.id,r,e.context_token);let i=this.getOrCreateSession(r),a=i.quotaRemaining;i.lastUserMessageAt=Date.now(),i.quotaRemaining=St,Y(this.id,this.sessions),h.info({channelId:this.id,chatId:r.slice(0,12),quotaReset:!0,prevQuota:a,newQuota:St,sessionWindowMs:ve},"iLink session reset: user message received, quota restored"),this.flushQueue(r);let o="",d,c=[],u;for(let m of e.item_list??[]){let l=m.ref_msg?.message_item?.msg_id;if(l){u=l;break}}for(let m of e.item_list??[])m.type===_.TEXT&&m.text_item?.text&&(o+=m.text_item.text),m.type===_.IMAGE&&(d="image",c.push(m)),m.type===_.VOICE&&(d="audio",c.push(m),m.voice_item?.text&&!o&&(o=m.voice_item.text)),m.type===_.FILE&&(d="file",c.push(m)),m.type===_.VIDEO&&(d="video",c.push(m));if(!o&&!d)return;let g;if(c.length>0){let m=this.config.cdnBaseUrl??Mt;try{let l=await bt(c[0],{cdnBaseUrl:m,channelId:this.id});l&&(g=l.path,d=l.type)}catch(l){h.error({channelId:this.id},`Media download failed: ${String(l)}`)}}let f={channelId:this.id,platform:"wechat",chatId:r,senderId:s,content:o,mediaType:d,mediaPath:g,isGroup:n,timestamp:e.create_time_ms??Date.now(),raw:e,...u?{quotedPlatformMessageId:u}:{}};this.messageHandler(f)}getExtensionFromMediaType(e,n){if(n){let r=re(n);if(r&&r!==".bin")return r}switch(e){case"image":return".png";case"video":return".mp4";case"audio":return".mp3";default:return".bin"}}sleep(e,n){return new Promise((r,s)=>{let i=setTimeout(r,e);n?.addEventListener("abort",()=>{clearTimeout(i),s(new Error("aborted"))},{once:!0})})}};C();C();var vn=y("channels"),fe=class{platform="discord";id;config;status="disconnected";messageHandler=null;client=null;constructor(e,n){if(this.id=e,!n.botToken)throw new Error("Discord adapter requires botToken");this.config=n}async connect(){this.status="connecting";try{let{Client:e,GatewayIntentBits:n}=await import("discord.js");this.client=new e({intents:[n.Guilds,n.GuildMessages,n.MessageContent,n.DirectMessages]});let r=this.client;r.on("messageCreate",s=>{if(!this.messageHandler||s.author.bot||this.config.allowedGuildIds?.length&&s.guildId&&!this.config.allowedGuildIds.includes(s.guildId))return;let i={channelId:this.id,platform:"discord",chatId:s.channelId,senderId:s.author.id,senderName:s.author.displayName??s.author.username,content:s.content,isGroup:!!s.guildId,timestamp:s.createdTimestamp,raw:s};this.messageHandler(i)}),await r.login(this.config.botToken),this.status="connected",vn.info({channelId:this.id},"Discord bot connected")}catch(e){throw this.status="error",e}}async disconnect(){this.client&&await this.client.destroy(),this.client=null,this.status="disconnected"}getStatus(){return this.status}getCapabilities(){return{canEdit:!0,canQuote:!0,canParseQuote:!0,canInlineButtons:!0,maxTextLength:2e3,supportsAttachments:!0}}async sendMessage(e,n){if(!this.client)throw new Error("Discord client not connected");let s=await this.client.channels.fetch(e);if(!s||!("send"in s))throw new Error(`Channel ${e} not found or not text channel`);return(await s.send({content:n.content,reply:n.replyToMessageId?{messageReference:n.replyToMessageId}:void 0})).id}onMessage(e){this.messageHandler=e}async sendTypingIndicator(e){if(!this.client)return;let r=await this.client.channels.fetch(e);r&&"sendTyping"in r&&await r.sendTyping()}};import{ImapFlow as zn}from"imapflow";import Hn from"nodemailer";import{existsSync as On,mkdirSync as Nn,readFileSync as Dn,writeFileSync as Fn}from"fs";import{dirname as Ln,join as Ut}from"path";import{homedir as qn}from"os";var $n={lastUid:0,seenMessageIds:[],sentMessageIds:[],updatedAt:0};function Ne(t=process.env.ADAM_TEST_DIR??Ut(qn(),".adam")){return Ut(t,"email-gateway","state.json")}function he(t=Ne()){if(!On(t))return{...$n};let e=JSON.parse(Dn(t,"utf-8"));return{uidValidity:e.uidValidity,lastUid:Number.isInteger(e.lastUid)?e.lastUid:0,seenMessageIds:Array.isArray(e.seenMessageIds)?e.seenMessageIds.filter(Pt):[],sentMessageIds:Array.isArray(e.sentMessageIds)?e.sentMessageIds.filter(Pt):[],updatedAt:typeof e.updatedAt=="number"?e.updatedAt:0}}function ee(t,e=Ne()){Nn(Ln(e),{recursive:!0}),Fn(e,JSON.stringify({...t,updatedAt:Date.now()},null,2),"utf-8")}function vt(t,e){let n=B(e);return n?{...t,seenMessageIds:t.seenMessageIds.includes(n)?t.seenMessageIds:[...t.seenMessageIds,n]}:t}function Bn(t,e){let n=B(e);return n?{...t,sentMessageIds:t.sentMessageIds.includes(n)?t.sentMessageIds:[...t.sentMessageIds,n]}:t}function Ot(t,e=Ne()){let n=Bn(he(e),t);return ee(n,e),n}function B(t){return typeof t=="string"?t.trim():""}function Pt(t){return typeof t=="string"}import{Readable as Gn}from"stream";import{MailParser as Wn}from"mailparser";import{convert as jn}from"html-to-text";async function Dt(t){let e=new Wn({skipImageLinks:!0,skipTextToHtml:!0}),n={},r,s,i,a=[],o,d="",c="",u="",g,f=0,m;if(await new Promise((F,R)=>{e.on("headers",b=>{try{for(let[I,v]of b.entries())n[I.toLowerCase()]=Qn(v);r=Nt(b.get("message-id")),o=Nt(b.get("subject")),u=qt(b.get("content-type"))??"";let P=b.get("date");P instanceof Date&&(g=P.getTime()),s=Ft(b.get("from"),"from"),i=Vn(b.get("reply-to"),"reply-to"),a=Lt(b.get("to"))}catch(P){m=P instanceof Error?P:new Error(String(P))}}),e.on("data",b=>{if(b.type==="attachment"){f+=1,b.release?.(),b.content?.resume?.();return}d=b.text??"",c=typeof b.html=="string"?b.html:""}),e.on("error",R),e.on("end",F),Gn.from([t]).pipe(e)}),m)throw m;if(!s)throw new Error("Inbound email must contain exactly one valid From address");let l=u.toLowerCase()==="text/html",w=d.trim();return(l||!w)&&c.trim()&&(w=jn(c,{wordwrap:!1,selectors:[{selector:"h1",format:"heading",options:{uppercase:!1}},{selector:"h2",format:"heading",options:{uppercase:!1}},{selector:"h3",format:"heading",options:{uppercase:!1}},{selector:"h4",format:"heading",options:{uppercase:!1}},{selector:"h5",format:"heading",options:{uppercase:!1}},{selector:"h6",format:"heading",options:{uppercase:!1}}]}).trim()),!w&&o&&(w=o.trim()),{messageId:r,from:s,replyTo:i,to:a,subject:o,text:w,date:g,rawHeaders:n,attachmentCount:f}}function Ft(t,e){let n=Lt(t);if(n.length!==1){if(n.length===0)return;throw new Error(`Inbound email ${e} must contain exactly one mailbox address`)}return n[0]}function Vn(t,e){if(t)return Ft(t,e)}function Lt(t){return t?typeof t=="string"?[k(t)]:(t.value??[]).map(r=>r.address).filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>k(r)):[]}function Nt(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(String).join(", ")}function Qn(t){if(t instanceof Date)return t.toISOString();if(typeof t=="string")return t;if(Array.isArray(t))return t.map(String).join(", ");let e=qt(t);return e||(t&&typeof t=="object"&&"text"in t?String(t.text??""):String(t??""))}function qt(t){if(typeof t=="string")return t;if(t&&typeof t=="object"&&"value"in t){let e=t.value;if(typeof e=="string")return e}}var Kn=1e4,Jn=3e4,Fe=class{imapClient;smtpTransporter;pollTimer;handlers=[];status={status:"stopped"};state=he();async start(e){if(await this.stop(),!e.enabled){this.status={status:"stopped",details:{reason:"disabled"}};return}this.status={status:"starting",lastStartedAt:Date.now()};try{this.imapClient=new zn({host:e.imap.host,port:e.imap.port,secure:e.imap.secure,auth:{user:e.imap.auth.user,pass:e.imap.auth.pass}}),await this.imapClient.connect();let n=await this.imapClient.mailboxOpen(e.imap.mailbox),r=n?.uidValidity?Number(n.uidValidity):void 0;r&&this.state.uidValidity&&r!==this.state.uidValidity?(this.state={...this.state,uidValidity:r,lastUid:0,seenMessageIds:[]},ee(this.state)):r&&(this.state={...this.state,uidValidity:r},ee(this.state)),this.smtpTransporter=Hn.createTransport({host:e.smtp.host,port:e.smtp.port,secure:e.smtp.secure,auth:{user:e.smtp.auth.user,pass:e.smtp.auth.pass}}),await this.smtpTransporter.verify(),this.status={status:"connected",lastStartedAt:Date.now(),lastCheckedAt:Date.now()},this.schedulePoll(e)}catch(n){throw await this.cleanupResources(),this.status={status:"error",lastError:Le(n),details:{stage:this.smtpTransporter?"smtp":"imap"}},n}}async stop(){await this.cleanupResources(),this.status={status:"stopped"}}getStatus(){return{...this.status}}onInbound(e){this.handlers.push(e)}async send(e){if(!this.smtpTransporter)throw new Error("EmailGateway SMTP transporter is not started");let n=await Xn(this.smtpTransporter.sendMail({from:e.from,to:e.to,subject:e.subject,text:e.text,html:e.html,attachments:e.attachments}),Kn,"SMTP send timed out"),r=B(n.messageId);if(!r)throw new Error("SMTP send returned no Message-ID");return this.state=Ot(r),r}isSentByAdam(e){let n=B(e);return n.length>0&&this.state.sentMessageIds.includes(n)}schedulePoll(e){this.pollTimer=setInterval(()=>{this.poll(e)},Jn)}async poll(e){if(this.imapClient)try{this.state=he();let n=`${this.state.lastUid+1}:*`,r=this.imapClient.fetch?.(n,{uid:!0,source:!0,envelope:!0},{uid:!0});if(!r||!r[Symbol.asyncIterator])return;let s=!1;for await(let i of r){let a=Number(i.uid);if(!Number.isInteger(a)||a<=this.state.lastUid)continue;if(!i.source){this.markDegraded(new Error(`IMAP fetch item ${a} is missing source`)),s=!0;break}let o;try{o=await Dt(i.source)}catch(u){this.markDegraded(u),s=!0;break}let d=o.rawHeaders["x-adam-probe-id"],c=B(o.messageId);if(d?.startsWith("adam-probe-")){this.advanceCursor(a);continue}if(c&&this.state.sentMessageIds.includes(c)){this.advanceCursor(a);continue}if(c&&this.state.seenMessageIds.includes(c)){this.advanceCursor(a);continue}try{await Promise.all(this.handlers.map(u=>u(o)))}catch(u){this.markDegraded(u),s=!0;break}this.state=vt(this.state,c),this.advanceCursor(a)}s||(this.status={...this.status,status:"connected",lastCheckedAt:Date.now(),lastError:void 0})}catch(n){this.markDegraded(n)}}advanceCursor(e){this.state={...this.state,lastUid:e},ee(this.state)}markDegraded(e){this.status={...this.status,status:"degraded",lastError:Le(e),lastCheckedAt:Date.now()}}async cleanupResources(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=void 0);let e=this.imapClient,n=this.smtpTransporter;this.imapClient=void 0,this.smtpTransporter=void 0,e&&(await De(e.logout?.()),await De(e.close?.())),await De(n?.close?.())}},$t;function S(){return $t??=new Fe,$t}async function ye(t){await S().start(t)}async function Mr(t,e){await S().stop(),await S().start(t)}async function Sr(t){await S().stop()}async function Xn(t,e,n){let r;try{return await Promise.race([t,new Promise((s,i)=>{r=setTimeout(()=>i(new Error(n)),e)})])}catch(s){throw new Error(Le(s))}finally{r&&clearTimeout(r)}}function Le(t){return t instanceof Error?t.message.replace(/pass(word)?=[^\s]+/gi,"password=****"):"Email gateway operation failed"}async function De(t){t&&typeof t.then=="function"&&await t.catch(()=>{})}C();var we=y("channels"),qe=class{constructor(e){this.gateway=e}gateway;adaptersByAddress=new Map;channelAddressById=new Map;registerAdapter(e,n){if(!ze(e)||!e.enabled)return;let r=L(e);this.unregisterAdapter(e.id),this.adaptersByAddress.set(r,n),this.channelAddressById.set(e.id,r)}unregisterAdapter(e){let n=this.channelAddressById.get(e);n&&(this.adaptersByAddress.delete(n),this.channelAddressById.delete(e))}refreshFromChannels(e,n){this.adaptersByAddress.clear(),this.channelAddressById.clear();for(let r of e){let s=n.get(r.id);if(s)try{this.registerAdapter(r,s)}catch(i){we.warn({channelId:r.id,error:i},"Invalid email channel skipped during router refresh")}}}async handle(e){if(e.messageId&&this.gateway.isSentByAdam(e.messageId)){we.debug({messageId:e.messageId},"Skipping Adam-sent email");return}let n;try{n=k(e.from)}catch(s){we.warn({from:e.from,error:s},"Skipping email with invalid sender address");return}let r=this.adaptersByAddress.get(n);if(!r){we.info({from:n},"Skipping unmatched inbound email");return}await r.acceptInbound(e)}hasAddress(e){return this.adaptersByAddress.has(k(e))}},be,Bt;function $e(t){return(!be||Bt!==t)&&(be=new qe(t),Bt=t,t.onInbound(e=>be?.handle(e)??Promise.resolve())),be}import{existsSync as Yn}from"fs";import{basename as Zn,isAbsolute as es}from"path";function Gt(t){let e=[];return t.mediaUrl&&e.push({path:t.mediaUrl,mediaType:t.mediaType}),t.attachments&&e.push(...t.attachments),e.map(ts)}function ts(t){let e=t.path.startsWith("file://")?new URL(t.path).pathname:t.path;if(!es(e)||e.includes("://"))throw new Error("Email attachment path must be an absolute local file path");if(!Yn(e))throw new Error(`Email attachment file not found: ${e}`);return{filename:t.filename??Zn(e),path:e,...t.contentType?{contentType:t.contentType}:t.mediaType?{contentType:ns(t.mediaType)}:{}}}function ns(t){return"application/octet-stream"}import ss from"markdown-it";var rs=new ss({html:!1,linkify:!0});function Wt(t){return{text:Ve(t),html:rs.render(t)}}function jt(t){let e=t.prefix.trim()||"Adam";return t.messageType==="report"||t.messageType==="status_report"?`[${e} Report]`:t.messageType==="deliver"||t.messageType==="result_delivery"?`[${e} Deliver]`:`[${e}]`}var _e=class{platform="email";id;channel;gateway;handler;inboundDispatchHandler;status="disconnected";identity;constructor(e,n,r={}){this.channel=e,this.gateway=n,this.id=e.id,this.identity=r}async connect(){let e=this.gateway.getStatus();this.status=Ie(e.status)}async disconnect(){this.status="disconnected"}getStatus(){return this.status}getCapabilities(){return{canEdit:!1,canQuote:!1,canParseQuote:!1,canInlineButtons:!1,maxTextLength:Number.POSITIVE_INFINITY,supportsAttachments:!0}}async sendMessage(e,n){let r=k(e),s=L(this.channel);if(r!==s)throw new Error("Email channel recipient does not match configured address");let i=Wt(n.content);return this.gateway.send({from:this.identity.from?He(this.identity.from,this.identity.displayName):void 0,to:r,subject:jt({prefix:this.identity.subjectPrefix??"Adam",messageType:n.messageType??"reply"}),text:i.text,html:i.html,attachments:Gt(n)})}onMessage(e){this.handler=e}onInboundDispatch(e){this.inboundDispatchHandler=e}syncGatewayStatus(){this.status=Ie(this.gateway.getStatus().status)}async acceptInbound(e){let n=k(e.from),r={channelId:this.channel.id,platform:"email",chatId:n,senderId:n,senderName:e.from,content:e.text,replyToMessageId:e.messageId,isGroup:!1,timestamp:e.date??Date.now(),raw:{messageId:e.messageId,subject:e.subject,attachmentCount:e.attachmentCount,headers:e.rawHeaders}};this.handler?.(r),this.inboundDispatchHandler&&await this.inboundDispatchHandler(r)}};function Ie(t){switch(t){case"connected":return"connected";case"starting":return"connecting";case"degraded":case"error":return"degraded";case"stopped":return"disconnected";default:return"disconnected"}}var Vt=y("channels"),Be=new Map;async function G(t,e){if(t.hasAdapter(e.id))return!0;if(e.platform==="wechat"){let n=e.config;return n.botToken?(await t.addChannel(e,new $(e.id,n)),!0):!1}if(e.platform==="discord"){let n=e.config;return n.botToken?(await t.addChannel(e,new fe(e.id,{botToken:n.botToken})),!0):!1}if(e.platform==="email"){L(e);let n=S(),r=j().emailGateway,s=new _e(e,n,{from:r?.smtp?.from||r?.address,displayName:r?.displayName,subjectPrefix:r?.subjectPrefix??"Adam"});Be.set(e.id,s),$e(n).registerAdapter(e,s);try{await is(),await t.addChannel(e,s)}catch(i){throw await W(t,e),i}return!0}return!1}async function Jr(t){for(let e of ne(!0))try{await G(t,e)}catch(n){V(e.id,"error"),Vt.warn({channelId:e.id,platform:e.platform,error:n},"Failed to register built-in channel adapter")}}async function Qt(t,e){e.platform==="email"&&(await W(t,e),e.enabled&&await G(t,e))}async function zt(t,e){await W(t,e)}async function W(t,e){e.platform==="email"&&($e(S()).unregisterAdapter(e.id),Be.delete(e.id),t?.hasAdapter(e.id)&&await t.removeChannel(e.id))}function Xr(t){for(let[e,n]of Be.entries())n.syncGatewayStatus(),V(e,n.getStatus())}async function is(){let t=j().emailGateway;if(!t?.enabled)return;let e=S().getStatus().status;if(!(e!=="stopped"&&e!=="error"))try{await ye(t)}catch(n){Vt.warn({error:as(n)},"EmailGateway start failed during built-in adapter registration")}}function as(t){return t instanceof Error?t.message.replace(/pass(word)?=[^\s]+/gi,"password=****"):"Email gateway operation failed"}var U=p.object({id:p.string().uuid()}),ds=p.object({name:p.string().min(1,"name is required"),platform:p.string().min(1,"platform is required"),config:p.record(p.string(),p.unknown()),enabled:p.boolean().optional().default(!0),linkedRoleId:p.string().optional(),allowedChatIds:p.array(p.string()).optional()}),us=p.object({name:p.string().min(1).optional(),enabled:p.boolean().optional(),config:p.record(p.string(),p.unknown()).optional(),linkedRoleId:p.string().optional(),allowedChatIds:p.array(p.string()).optional(),viewerKey:p.string().min(1).max(100).regex(/^[a-zA-Z0-9_.@:-]+$/,"viewerKey must be alphanumeric or one of _ . @ : -").optional()}),Ge;function li(t){Ge=t}function mi(){return Ge}async function gi(t){let e=Ge;async function n(r){je(r);try{return e&&r.enabled&&await G(e,r),r}catch(s){throw await W(e,r),Te(r.id),s}}t.get("/channels",{schema:{tags:["Channels"],summary:"List channels",querystring:{type:"object",properties:{enabled:{type:"boolean"}}}}},async(r,s)=>({channels:ne(r.query.enabled)})),t.post("/channels",{schema:{tags:["Channels"],summary:"Create a channel",body:{type:"object",required:["name","platform","config"],properties:{name:{type:"string",minLength:1},platform:{type:"string",minLength:1},config:{type:"object"},enabled:{type:"boolean"},linkedRoleId:{type:"string"},allowedChatIds:{type:"array",items:{type:"string"}}}}}},async(r,s)=>{let i=ds.safeParse(r.body);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let{name:a,platform:o,config:d,enabled:c,linkedRoleId:u,allowedChatIds:g}=i.data,f=d;if(o==="email")try{f={...Ee(d)}}catch(l){return s.status(400).send({code:"VALIDATION_ERROR",message:l instanceof Error?l.message:String(l)})}let m={id:os(),name:a,platform:o,enabled:c,status:"disconnected",config:f,linkedRoleId:u,allowedChatIds:g,viewerKey:Qe(),createdAt:Date.now(),messageCount:0};try{await n(m)}catch(l){return s.status(400).send({code:"VALIDATION_ERROR",message:D(l)})}return s.status(201).send({channel:m})}),t.get("/channels/:id",{schema:{tags:["Channels"],summary:"Get channel by ID",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let i=U.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let a=T(i.data.id);return a?{channel:a}:s.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),t.patch("/channels/:id",{schema:{tags:["Channels"],summary:"Update channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",properties:{name:{type:"string"},enabled:{type:"boolean"},config:{type:"object"},linkedRoleId:{type:"string"},allowedChatIds:{type:"array",items:{type:"string"}},viewerKey:{type:"string",minLength:1,maxLength:100}}}}},async(r,s)=>{let i=U.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let a=T(i.data.id);if(!a)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let o=us.safeParse(r.body);if(!o.success)return s.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(o.error)});let d={...o.data};if((a.platform==="email"||d.config)&&(d.config||a.config)){let g=d.config??a.config;if(a.platform==="email")try{d.config={...Ee(g)}}catch(f){return s.status(400).send({code:"VALIDATION_ERROR",message:f instanceof Error?f.message:String(f)})}}let c=a.platform==="email"&&(d.enabled!==void 0||d.config!==void 0);te(a.id,d);let u=T(a.id);if(e&&u&&c)try{await Qt(e,u)}catch(g){if(te(a.id,{name:a.name,enabled:a.enabled,status:a.status,config:a.config,linkedRoleId:a.linkedRoleId,allowedChatIds:a.allowedChatIds,lastMessageAt:a.lastMessageAt,messageCount:a.messageCount}),await W(e,u),a.enabled)try{await G(e,a)}catch(f){return s.status(500).send({code:"RESTORE_FAILED",message:D(f)})}return s.status(400).send({code:"VALIDATION_ERROR",message:D(g)})}return{channel:u}}),t.delete("/channels/:id",{schema:{tags:["Channels"],summary:"Delete channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let i=U.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let a=T(i.data.id);if(!a)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(Te(a.id),e)try{await zt(e,a)}catch(o){t.log.warn({channelId:a.id,error:D(o)},"Failed to clean up built-in channel runtime")}return s.status(204).send()}),t.post("/channels/:id/connect",{schema:{tags:["Channels"],summary:"Connect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let i=U.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});if(!e)return s.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let a=T(i.data.id);if(!a)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(a.platform==="email")try{await cs()}catch(o){let d=S().getStatus();return V(a.id,Ie(d.status)),s.status(409).send({code:"EMAIL_GATEWAY_NOT_READY",message:D(o),gatewayStatus:d})}if(!e.hasAdapter(a.id))try{await G(e,a)}catch(o){return s.status(400).send({code:"VALIDATION_ERROR",message:D(o)})}if(!e.hasAdapter(a.id))return s.status(400).send({code:"NO_ADAPTER",message:"No adapter registered for this channel. Install the appropriate adapter first."});try{await e.connectChannel(a.id);let o=T(a.id)?.status??e.getChannelStatus(a.id);return o!=="connected"?s.status(409).send({code:"CONNECT_INCOMPLETE",message:`Channel connect finished with status "${o}"`,status:o}):{channelId:a.id,status:o}}catch(o){return s.status(500).send({code:"CONNECT_FAILED",message:D(o)})}}),t.post("/channels/:id/disconnect",{schema:{tags:["Channels"],summary:"Disconnect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let i=U.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});if(!e)return s.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let a=T(i.data.id);return a?(await e.disconnectChannel(a.id),{channelId:a.id,status:"disconnected"}):s.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),t.get("/channels/:id/capabilities",{schema:{tags:["Channels"],summary:"Get channel adapter capabilities",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let i=U.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});if(!T(i.data.id))return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(!e)return s.status(503).send({code:"MANAGER_UNAVAILABLE",message:"ChannelManager not initialized"});let o=e.getCapabilities(i.data.id);return o?{capabilities:o}:s.status(404).send({code:"ADAPTER_NOT_REGISTERED",message:"Channel adapter not active"})}),t.get("/channels/:id/messages",{schema:{tags:["Channels"],summary:"Get channel message history",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50},offset:{type:"integer",minimum:0,default:0}}}}},async(r,s)=>{let i=U.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let a=T(i.data.id);if(!a)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let{limit:o=50,offset:d=0}=r.query;return{messages:We(a.id,o,d)}}),t.post("/channels/:id/wechat/qr-start",{schema:{tags:["WeChat"],summary:"Start WeChat QR login",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let i=U.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let a=T(i.data.id);if(!a)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(a.platform!=="wechat")return s.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=a.config;return await st({apiBaseUrl:o.baseUrl,routeTag:o.routeTag})}),t.post("/channels/:id/wechat/qr-wait",{schema:{tags:["WeChat"],summary:"Wait for WeChat QR scan",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",properties:{sessionKey:{type:"string"},timeoutMs:{type:"number"}}}}},async(r,s)=>{let i=U.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let a=T(i.data.id);if(!a)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(a.platform!=="wechat")return s.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=a.config,{sessionKey:d,timeoutMs:c}=r.body??{},u=await rt({sessionKey:d??"",apiBaseUrl:o.baseUrl,timeoutMs:c??12e4,routeTag:o.routeTag});if(u.connected&&u.botToken){let g={...o,botToken:u.botToken,accountId:u.accountId,baseUrl:u.baseUrl??o.baseUrl,userId:u.userId};if(te(a.id,{config:g}),e){let f=new $(a.id,g),m=T(a.id);m&&await e.addChannel(m,f)}}return{connected:u.connected,accountId:u.accountId,message:u.message}})}function D(t){return t instanceof Error?t.message.replace(/pass(word)?=[^\s]+/gi,"password=****"):String(t)}async function cs(){let t=j().emailGateway;if(!t?.enabled)throw new Error("Email Gateway is disabled. Enable Email Gateway in Settings before connecting Mail channels.");let e=S();e.getStatus().status!=="connected"&&await ye(t);let n=e.getStatus();if(n.status!=="connected"){let r=n.lastError?`: ${n.lastError}`:"";throw new Error(`Email Gateway status is ${n.status}${r}`)}}export{Ot as a,B as b,Dt as c,S as d,Mr as e,Sr as f,Jr as g,Xr as h,li as i,mi as j,gi as k};
@@ -0,0 +1,5 @@
1
+ import{l as e,n as i}from"./chunk-BPXS4QEO.js";import{c as o,e as d}from"./chunk-245WE5AF.js";i();d();function s(t){return{id:t.id,taskId:t.task_id,index:t.index,type:t.type,content:t.content,toolName:t.tool_name??void 0,toolInput:t.tool_input?JSON.parse(t.tool_input):void 0,toolOutput:t.tool_output??void 0,truncated:t.truncated===1,timestamp:t.timestamp,tokenUsage:t.token_usage?JSON.parse(t.token_usage):void 0,planStepIndex:t.plan_step_index??void 0,traceId:t.trace_id??void 0}}function _(t){e().prepare(`
2
+ INSERT INTO step_logs (id, task_id, "index", type, content, tool_name,
3
+ tool_input, tool_output, truncated, timestamp, token_usage, plan_step_index, trace_id)
4
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
5
+ `).run(t.id,t.taskId,t.index,t.type,t.content,t.toolName??null,t.toolInput?JSON.stringify(t.toolInput):null,t.toolOutput??null,t.truncated?1:0,t.timestamp,t.tokenUsage?JSON.stringify(t.tokenUsage):null,t.planStepIndex??null,t.traceId??o()??null)}function g(t,n=100,p=0){return e().prepare('SELECT * FROM step_logs WHERE task_id = ? ORDER BY "index" ASC LIMIT ? OFFSET ?').all(t,n,p).map(s)}export{_ as a,g as b};
@@ -0,0 +1 @@
1
+ import{a as c,b as s}from"./chunk-LU3D53ZV.js";import{c as i,h as d}from"./chunk-BLCNUT53.js";import{c as a,e as f}from"./chunk-245WE5AF.js";f();d();var o=i("adam");function l(e){let r=e.traceIdOverride??a();if(!r){o.debug({toolName:e.toolName,entityType:e.entityType,verb:e.verb},"Mutation receipt skipped: no active trace context");return}let n={traceId:r,toolName:e.toolName,taskId:e.taskId,roleId:e.roleId};try{s({traceId:r,taskId:e.taskId,sessionId:e.sessionId,effectCategory:"entity_mutation",verb:e.verb,entityType:e.entityType,entityId:e.entityId,entityIds:e.entityIds,fieldChanges:e.fieldChanges,scope:e.scope,actor:n,outcome:"success"})}catch(t){t instanceof c?o.warn({errors:t.errors,toolName:e.toolName,entityType:e.entityType},"Mutation receipt validation failed"):o.warn({error:t instanceof Error?t.message:String(t),toolName:e.toolName},"Mutation receipt write failed")}}export{l as a};
@@ -0,0 +1,9 @@
1
+ import{d as D}from"./chunk-42V6ZPCS.js";import{a as O}from"./chunk-NUJSTEV4.js";import{f as v}from"./chunk-XF7YHFVR.js";import{e as M}from"./chunk-UFWMUBFH.js";import{e as C}from"./chunk-LU3D53ZV.js";import{a as R,b as x,c,d as y,e as b,f as S,g as P}from"./chunk-NPGZRSGL.js";import{b as I}from"./chunk-NWGRLNUM.js";import{b as w}from"./chunk-CLNYHWZ6.js";import{s as k}from"./chunk-RBJPQYV3.js";import{b as h,o as B}from"./chunk-KJNAORKM.js";import{a as f}from"./chunk-L7JP7DUO.js";import{l as d,n as j}from"./chunk-BPXS4QEO.js";import{c as E,h as N}from"./chunk-BLCNUT53.js";j();function L(i){return{id:i.id,eventType:i.event_type,matchCriteria:JSON.parse(i.match_criteria),target:JSON.parse(i.target),formatTemplate:i.format_template??void 0,maxPerMinute:i.max_per_minute,skipOriginChannel:i.skip_origin_channel===1,enabled:i.enabled===1,createdAt:i.created_at,createdBy:i.created_by??void 0}}function q(i){d().prepare(`
2
+ INSERT INTO delivery_rules (id, event_type, match_criteria, target, format_template,
3
+ max_per_minute, skip_origin_channel, enabled, created_at, created_by)
4
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
5
+ `).run(i.id,i.eventType,JSON.stringify(i.matchCriteria),JSON.stringify(i.target),i.formatTemplate??null,i.maxPerMinute,i.skipOriginChannel?1:0,i.enabled?1:0,i.createdAt,i.createdBy??null)}function H(i){let n=d().prepare("SELECT * FROM delivery_rules WHERE id = ?").get(i);return n?L(n):void 0}function W(i){let e=d(),n="SELECT * FROM delivery_rules",r=[];return i!==void 0&&(n+=" WHERE enabled = ?",r.push(i?1:0)),n+=" ORDER BY created_at DESC",e.prepare(n).all(...r).map(L)}function U(i,e){let n=d(),r=[],t=[];e.eventType!==void 0&&(r.push("event_type = ?"),t.push(e.eventType)),e.matchCriteria!==void 0&&(r.push("match_criteria = ?"),t.push(JSON.stringify(e.matchCriteria))),e.target!==void 0&&(r.push("target = ?"),t.push(JSON.stringify(e.target))),e.formatTemplate!==void 0&&(r.push("format_template = ?"),t.push(e.formatTemplate)),e.maxPerMinute!==void 0&&(r.push("max_per_minute = ?"),t.push(e.maxPerMinute)),e.skipOriginChannel!==void 0&&(r.push("skip_origin_channel = ?"),t.push(e.skipOriginChannel?1:0)),e.enabled!==void 0&&(r.push("enabled = ?"),t.push(e.enabled?1:0)),r.length!==0&&(t.push(i),n.prepare(`UPDATE delivery_rules SET ${r.join(", ")} WHERE id = ?`).run(...t))}function G(i){let e=d();e.prepare("DELETE FROM delivery_log WHERE rule_id = ?").run(i),e.prepare("DELETE FROM delivery_rules WHERE id = ?").run(i)}function A(i,e){return W(!0).filter(r=>{if(r.eventType!=="*"&&r.eventType!==i)return!1;let t=r.matchCriteria;if(t.templateId&&t.templateId!==e.templateId||t.roleId&&t.roleId!==e.roleId||t.taskStatus&&t.taskStatus!==e.taskStatus)return!1;if(t.promptPattern)try{if(!new RegExp(t.promptPattern,"i").test(e.prompt??""))return!1}catch{return!1}if(t.excludePromptPatterns&&t.excludePromptPatterns.length>0){let a=e.prompt??"";for(let s of t.excludePromptPatterns)if(!(typeof s!="string"||s.length>200))try{if(new RegExp(s,"i").test(a))return!1}catch{continue}}return!0})}B();N();import{v4 as J}from"uuid";function F(i){return!!(i.templateId&&i.stepId&&i.parentId)}var l=E("admin"),_=new Map,m=null,g=null,u=null,T=class{constructor(){f.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")})}),f.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)")})}),f.on("template_execution_status_change",e=>{e.status==="failed"&&this.handleTemplateExecutionFailure(e.executionId,e.templateId).catch(n=>{l.error({executionId:e.executionId,error:n},"Template failure delivery processing failed")})}),l.info("DeliveryEngine initialized")}async handlePlanApprovalRequest(e,n,r){let t=h(e),a=this.getSourceChannelForTask(e);if(a){let o=D(r),{sendApprovalToChannel:p}=await import("./approval-handler-YLO3V75T.js");await p(a.channelId,a.chatId,n,e,o)}let s=D(r)+`
6
+
7
+ Task: ${e}`;await this.matchAndDeliver("plan_approval_request",{templateId:t?.templateId,roleId:t?.roleId,prompt:t?.prompt,taskStatus:"pending"},s,e)}async handleTemplateExecutionFailure(e,n){let r=C(e),t=n?k(n):null,a=r?Object.entries(r.stepStatuses).filter(([,o])=>o.status==="failed"):[],s=["\u26A0\uFE0F TemplateExecution failed",`Template: ${t?.name??n}`,`Execution: ${e}`,`Failed steps: ${a.map(([o])=>o).join(", ")||"(unknown \u2014 no failed step recorded)"}`,a[0]?.[1]?.error?`
8
+ First error: ${a[0][1].error.slice(0,300)}`:""].filter(Boolean).join(`
9
+ `);await this.matchAndDeliver("template_execution_failed",{templateId:n,roleId:void 0,prompt:void 0,taskStatus:"failed"},s,void 0,e)}getSourceChannelForTask(e){try{let n=v(e);if(!n)return null;let r=I(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=h(e);if(!r)return;if(F(r)){l.debug({taskId:e,templateId:r.templateId,stepId:r.stepId},"Skipping delivery for TemplateExecution step task");return}if(r.config?.taskType==="contract-verifier"){l.debug({taskId:e},"Skipping delivery for contract-verifier task");return}let t={templateId:r.templateId,roleId:r.roleId,prompt:r.prompt,taskStatus:n},a=n==="completed"?"task_complete":"task_error",s=r.result??r.error??"";await this.matchAndDeliver(a,t,s,e)}async matchAndDeliver(e,n,r,t,a){let s=A(e,n);if(s.length!==0){l.debug({eventType:e,ruleCount:s.length,taskId:t},"Matched delivery rules");for(let o of s){if(!this.checkRateLimit(o)){l.warn({ruleId:o.id,maxPerMinute:o.maxPerMinute},"Delivery rate limit exceeded, skipping");continue}if(o.skipOriginChannel&&o.target.type==="channel"&&t&&this.isOriginChannel(t,o.target))continue;let p={id:J(),ruleId:o.id,taskId:t,executionId:a,status:"pending",target:o.target,content:r,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+R,source:"rule"};x(p),await this.attemptDelivery(p,o)}}}async attemptDeliveryPublic(e,n){return this.attemptDelivery(e,n)}async attemptDelivery(e,n){let r=M();try{if(e.target.type==="channel"){let t=e.target.chatId;if(!t&&e.target.channelId){let s=w(e.target.channelId);t=s?O(s):void 0}let a=await r.send({taskId:e.taskId,channelId:e.target.channelId,chatId:t,content:e.content,messageType:"deliver"});a.success?(y(e.id),l.info({entryId:e.id,ruleId:n.id,targetType:"channel"},"Delivery successful")):c(e.id,"failed",a.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?(y(e.id),l.info({entryId:e.id,ruleId:n.id,targetType:"webhook"},"Webhook delivery successful")):c(e.id,"failed",t.error??"Gateway returned failure")}}catch(t){let a=t instanceof Error?t.message:String(t);c(e.id,"failed",a),l.warn({entryId:e.id,error:a},"Delivery attempt failed")}}checkRateLimit(e){let n=Date.now(),r=6e4,t=_.get(e.id);t||(t=[],_.set(e.id,t));let a=n-r;for(;t.length>0&&t[0]<a;)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=v(e);if(!r)return!1;let t=I(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=b("rule",50),n=S("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){c(t.id,"failed","Max retries (3) exceeded");continue}let a={id:t.ruleId??"retry-synthetic",eventType:"*",matchCriteria:{},target:t.target,maxPerMinute:5,skipOriginChannel:!0,enabled:!0,createdAt:0};await this.attemptDelivery(t,a)}}}};function ce(){return u}function ue(){u||(u=new T,m=setInterval(()=>{u?.retryPending().catch(i=>{l.error({error:i},"Delivery retry scan failed")})},6e4),g=setInterval(()=>{try{let i=P();i>0&&l.info({cleaned:i},"Expired delivery log entries cleaned up")}catch(i){l.error({error:i},"Delivery cleanup failed")}},36e5),l.info("DeliveryEngine started with retry (60s) and cleanup (1h) timers"))}function pe(){m&&(clearInterval(m),m=null),g&&(clearInterval(g),g=null),u=null,_.clear(),l.info("DeliveryEngine stopped")}export{q as a,H as b,W as c,U as d,G as e,F as f,T as g,ce as h,ue as i,pe as j};
@@ -1 +1 @@
1
- import{a as l}from"./chunk-SWP2JC54.js";import{a as h,b as u,c,d as m,e as v,f as x}from"./chunk-FUWPDXXG.js";import{a as C}from"./chunk-X5V4VMET.js";import{b as S,d as y}from"./chunk-ZQ4PNKMQ.js";import{a as i}from"./chunk-L7JP7DUO.js";import{e as p}from"./chunk-HDHMNT6D.js";import{v4 as D}from"uuid";import{v4 as I}from"uuid";function _(e){if(e.length<20)return null;let t=e.trim();return t.length>300?{content:`User request: ${t.slice(0,280)}...`,importance:3,type:"thought"}:{content:`User request: ${t}`,importance:3,type:"thought"}}function b(e){if(e.length<20)return null;let t=e.trim();return t.length>400?{content:`Assistant response: ${t.slice(0,370)}...`,importance:2,type:"event"}:{content:`Assistant response: ${t}`,importance:2,type:"event"}}function N(e){let t=S(e,200,0),s=[];for(let o of t){let r=o.role==="user"?_(o.content):b(o.content);r&&s.push(r)}return{facts:s}}function $(e){let t=e.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(s=>s.length>2);return[...new Set(t)].slice(0,20)}async function A(e,t){let{facts:s}=N(e),o=0;for(let r of s){let f=r.content.slice(0,500),g;try{g=await l(f)}catch{}let M=$(f),T={id:I(),roleId:t,type:r.type,content:f,embedding:g,keywords:M,importance:r.importance,sourceType:"session_archive",createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"episodic"};C(T),o++}return o}var n=new Map,a;function w(e){return`${e.type}:${e.channelId??""}:${e.chatId??""}`}function F(){n.clear();let e=m("active",1e3);for(let t of e)n.set(t.id,t)}function Q(e,t){let s=Date.now(),o={id:D(),status:"active",source:e,createdAt:s,lastActiveAt:s,messageCount:0};return h(o),n.set(o.id,o),i.emit({type:"session_created",session:o}),o}function V(e){for(let s of n.values())if(w(s.source)===w(e))return s;let t=v(e);return t&&n.set(t.id,t),t}function B(e){let t=n.get(e);return t||u(e)}function E(e){let t=Date.now();c(e,{status:"archived",archivedAt:t}),p().archiveExtractMemory&&u(e)&&A(e,"role-chat-manager").catch(()=>{}),n.delete(e),i.emit({type:"session_archived",sessionId:e})}function W(e){c(e,{status:"active",archivedAt:void 0});let t=u(e);return t&&(n.set(t.id,t),i.emit({type:"session_restored",session:t})),t}function X(e){y(e),x(e),n.delete(e),i.emit({type:"session_deleted",sessionId:e})}function Y(e){let t=Date.now();c(e,{lastActiveAt:t});let s=n.get(e);s&&(s.lastActiveAt=t)}function Z(e){let t=B(e);if(t){let s=t.messageCount+1;c(e,{messageCount:s});let o=n.get(e);o&&(o.messageCount=s)}}function ee(e){return m(e)}function P(){let t=p().sessionTimeoutMinutes*60*1e3,s=Date.now();for(let o of n.values())if(s-o.lastActiveAt>t)try{E(o.id)}catch{}}function R(e=6e4){d(),a=setInterval(P,e)}function d(){a&&(clearInterval(a),a=void 0)}function te(){return a}function se(){F(),R()}function oe(){d(),n.clear()}function ne(){d(),n.clear()}export{F as a,Q as b,V as c,B as d,E as e,W as f,X as g,Y as h,Z as i,ee as j,R as k,d as l,te as m,se as n,oe as o,ne as p};
1
+ import{a as l}from"./chunk-DRO3DG7X.js";import{a as C}from"./chunk-XIVFVKMB.js";import{c as S,e as y}from"./chunk-XF7YHFVR.js";import{a as h,b as u,c,d as m,e as v,f as x}from"./chunk-NWGRLNUM.js";import{a as i}from"./chunk-L7JP7DUO.js";import{e as p}from"./chunk-VKKDSXMR.js";import{v4 as D}from"uuid";import{v4 as I}from"uuid";function _(e){if(e.length<20)return null;let t=e.trim();return t.length>300?{content:`User request: ${t.slice(0,280)}...`,importance:3,type:"thought"}:{content:`User request: ${t}`,importance:3,type:"thought"}}function b(e){if(e.length<20)return null;let t=e.trim();return t.length>400?{content:`Assistant response: ${t.slice(0,370)}...`,importance:2,type:"event"}:{content:`Assistant response: ${t}`,importance:2,type:"event"}}function N(e){let t=S(e,200,0),s=[];for(let o of t){let r=o.role==="user"?_(o.content):b(o.content);r&&s.push(r)}return{facts:s}}function $(e){let t=e.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(s=>s.length>2);return[...new Set(t)].slice(0,20)}async function A(e,t){let{facts:s}=N(e),o=0;for(let r of s){let f=r.content.slice(0,500),g;try{g=await l(f)}catch{}let M=$(f),T={id:I(),roleId:t,type:r.type,content:f,embedding:g,keywords:M,importance:r.importance,sourceType:"session_archive",createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"episodic"};C(T),o++}return o}var n=new Map,a;function w(e){return`${e.type}:${e.channelId??""}:${e.chatId??""}`}function F(){n.clear();let e=m("active",1e3);for(let t of e)n.set(t.id,t)}function Q(e,t){let s=Date.now(),o={id:D(),status:"active",source:e,createdAt:s,lastActiveAt:s,messageCount:0};return h(o),n.set(o.id,o),i.emit({type:"session_created",session:o}),o}function V(e){for(let s of n.values())if(w(s.source)===w(e))return s;let t=v(e);return t&&n.set(t.id,t),t}function B(e){let t=n.get(e);return t||u(e)}function E(e){let t=Date.now();c(e,{status:"archived",archivedAt:t}),p().archiveExtractMemory&&u(e)&&A(e,"role-chat-manager").catch(()=>{}),n.delete(e),i.emit({type:"session_archived",sessionId:e})}function W(e){c(e,{status:"active",archivedAt:void 0});let t=u(e);return t&&(n.set(t.id,t),i.emit({type:"session_restored",session:t})),t}function X(e){y(e),x(e),n.delete(e),i.emit({type:"session_deleted",sessionId:e})}function Y(e){let t=Date.now();c(e,{lastActiveAt:t});let s=n.get(e);s&&(s.lastActiveAt=t)}function Z(e){let t=B(e);if(t){let s=t.messageCount+1;c(e,{messageCount:s});let o=n.get(e);o&&(o.messageCount=s)}}function ee(e){return m(e)}function P(){let t=p().sessionTimeoutMinutes*60*1e3,s=Date.now();for(let o of n.values())if(s-o.lastActiveAt>t)try{E(o.id)}catch{}}function R(e=6e4){d(),a=setInterval(P,e)}function d(){a&&(clearInterval(a),a=void 0)}function te(){return a}function se(){F(),R()}function oe(){d(),n.clear()}function ne(){d(),n.clear()}export{F as a,Q as b,V as c,B as d,E as e,W as f,X as g,Y as h,Z as i,ee as j,R as k,d as l,te as m,se as n,oe as o,ne as p};
@@ -0,0 +1 @@
1
+ import{e as A,i as J}from"./chunk-VNXTBIPI.js";import{v,z as D}from"./chunk-KJNAORKM.js";import{existsSync as m,readFileSync as P,readdirSync as w}from"fs";import{join as d}from"path";import E from"os";var b=()=>d(E.homedir(),".claude","plugins"),S=()=>d(b(),"installed_plugins.json"),_=()=>d(b(),"known_marketplaces.json"),x=()=>d(E.homedir(),".claude","settings.json");function y(s){try{if(!m(s))return null;let i=P(s,"utf-8");return JSON.parse(i)}catch{return null}}function R(){return y(x())?.enabledPlugins??{}}function T(s){let i=s;function l(t,p){let a={};try{if(!m(t))return a;let u=P(t,"utf-8").replace(/^```yaml\r?\n/,"").replace(/^```\r?\n/,"");for(let f of p){let r=new RegExp(`^${f}:\\s*(.+)$`,"m"),e=u.match(r);e&&(a[f]=e[1].trim())}}catch{}return a}function o(t){try{if(!m(t))return{};let p=P(t,"utf-8"),a=p.match(/^```yaml\r?\n([\s\S]*?)\r?\n```\r?\n/);if(!a){let r={};for(let e of p.split(/\r?\n/)){let n=e.match(/^(\w+):\s*(.+)$/);n&&(r[n[1]]=n[2])}return{name:r.name,description:r.description}}let c=a[1],u={};for(let r of c.split(/\r?\n/)){let e=r.match(/^(\w+):\s*(.*)$/);if(e){let[,n,g]=e;g.trim()&&(u[n]=g.trim())}}let f=c.match(/error_patterns:\r?\n([\s\S]*?)(?=\n\w|\n$)/);if(f){let r=f[1],e=[],n={};for(let g of r.split(/\r?\n/)){let h=g.match(/^\s*-\s*pattern:\s*(.+)$/);if(h){n.pattern&&e.push(n),n={pattern:h[1].replace(/^["']|["']$/g,"")};continue}let k=g.match(/^\s*category:\s*(.+)$/);if(k){n.category=k[1].trim();continue}let j=g.match(/^\s*user_action:\s*(.+)$/);if(j){n.user_action=j[1].replace(/^["']|["']$/g,""),n.pattern&&n.category&&n.user_action&&(e.push(n),n={});continue}}n.pattern&&e.push(n),e.length>0&&(u.error_patterns=e)}return{name:u.name,description:u.description,error_patterns:u.error_patterns}}catch{}return{}}try{let t={name:"",skills:[],agents:[],mcpServers:[],hooks:[],lspServers:[]},p=d(i,".claude-plugin","plugin.json");if(m(p))try{let r=JSON.parse(P(p,"utf-8"));t.name=r.name??"",t.version=r.version,t.description=r.description,Array.isArray(r.lspServers)&&(t.lspServers=r.lspServers),Array.isArray(r.mcpServers)&&(t.mcpServers=r.mcpServers),Array.isArray(r.hooks)&&(t.hooks=r.hooks)}catch{}let a=d(i,"skills");if(m(a)){let r=w(a,{withFileTypes:!0});for(let e of r){if(!e.isDirectory()&&!e.isSymbolicLink())continue;let n=d(a,e.name,"SKILL.md"),g=o(n);g.name&&t.skills.push({name:g.name,description:g.description??"",error_patterns:g.error_patterns})}}let c=d(i,"agents");if(m(c)){let r=w(c,{withFileTypes:!0});for(let e of r){if(!e.isFile()||!e.name.endsWith(".md"))continue;let n=l(d(c,e.name),["name","description"]);n.name&&t.agents.push({name:n.name,description:n.description??""})}}let u=d(i,".mcp.json");if(m(u))try{let r=JSON.parse(P(u,"utf-8"));r.mcpServers&&typeof r.mcpServers=="object"&&(t.mcpServers=Object.keys(r.mcpServers))}catch{}let f=d(i,"hooks","hooks.json");if(m(f))try{let r=JSON.parse(P(f,"utf-8"));Array.isArray(r)&&(t.hooks=r.map(e=>typeof e=="object"&&e!==null&&"event"in e?String(e.event):String(e)))}catch{}return t}catch{return null}}function $(s){let i=y(S());if(!i?.plugins)return[];let l=R(),o=[];for(let[t,p]of Object.entries(i.plugins))if(!(!Array.isArray(p)||p.length===0))for(let a of p){let c=a.scope??"user";s?.scope&&c!==s.scope||s?.projectPath&&a.projectPath!==s.projectPath||o.push({id:t,name:t.split("@")[0],version:a.version??"",scope:c,projectPath:a.projectPath,installPath:a.installPath??d(b(),t),enabled:l[t]??a.enabled??!0,installedAt:a.installedAt??"",lastUpdated:a.lastUpdated??""})}return o}function G(s){let i=y(S());if(!i?.plugins?.[s])return null;let l=i.plugins[s];if(!Array.isArray(l)||l.length===0)return null;let o=l[0],t=R();return{id:s,name:s.split("@")[0],version:o.version??"",scope:o.scope??"user",projectPath:o.projectPath,installPath:o.installPath??d(b(),s),enabled:t[s]??o.enabled??!0,installedAt:o.installedAt??"",lastUpdated:o.lastUpdated??""}}function M(s){let i=y(S()),l=new Map;for(let o of s){let t=i?.plugins?.[o];Array.isArray(t)&&t.length>0&&l.set(o,t[0].installPath??d(b(),o))}return l}function U(){return y(_())?.marketplaces??[]}function I(s){let i=d(s,".claude","settings.json"),l=y(i);return{enabledPlugins:l?.enabledPlugins??{},mcpServers:l?.mcpServers??{},allowedTools:l?.allowedTools??[],disallowedTools:l?.disallowedTools??[]}}J();D();var C={Read:{category:"File",label:"read"},Write:{category:"File",label:"write"},Edit:{category:"File",label:"edit"},Glob:{category:"Search",label:"find files"},Grep:{category:"Search",label:"search content"},Bash:{category:"Execution",label:"shell commands"},WebSearch:{category:"Web",label:"web search"},WebFetch:{category:"Web",label:"fetch pages"},NotebookEdit:{category:"Execution",label:"Jupyter notebooks"}};function q(s,i){let l=s.allowedTools??[],o=s.osCapabilities??[];if(l.length===0&&o.length===0&&Object.keys(s.mcpServers??{}).length===0&&(s.additionalDirectories?.length??0)===0&&(!i||i.plugins.length===0))return"No tool permissions";let t=new Map,p=[];for(let e of l){let n=C[e];if(n){let g=t.get(n.category)??[];g.push(n.label),t.set(n.category,g)}else p.push(e)}let a=[];for(let[e,n]of t)a.push(`${e} (${n.join(", ")})`);p.length>0&&a.push(p.join(", "));let c=a.join(" \xB7 "),u=e=>{c=c?`${c} \xB7 ${e}`:e},f=Object.keys(s.mcpServers??{});f.length>0&&u(`MCP: ${f.join(", ")}`);let r=s.additionalDirectories??[];if(r.length>0&&u(`Dirs: ${r.map(e=>e.path).join(", ")}`),o.length>0){let e=o.map(n=>{let g=v(n.id);return n.id==="automation"&&n.targets?.length?`${g.label} (${n.targets.join(", ")})`:g.label});u(`OS: ${e.join(", ")}`)}if(i&&i.plugins.length>0){let e=i.plugins.map(n=>{let g=[];return n.skills.length>0&&g.push(`skills: ${n.skills.map(h=>h.name).join(", ")}`),n.agents.length>0&&g.push(`agents: ${n.agents.map(h=>h.name).join(", ")}`),g.length>0?`${n.name} (${g.join("; ")})`:n.name});u(`Plugins: ${e.join(", ")}`)}return c}function O(s){let i=[],l=s.additionalDirectories??[];for(let o of l){if(!o.inheritPlugins&&!o.inheritMcp)continue;let t=I(o.path),p=Object.entries(t.enabledPlugins).filter(([,c])=>c).map(([c])=>c),a=M(p);for(let[,c]of a)i.includes(c)||i.push(c)}try{let o=A(s.name),t=$({scope:"project",projectPath:o});for(let p of t)p.installPath&&!i.includes(p.installPath)&&i.push(p.installPath)}catch{}return i}function z(s){let i=O(s),l=[];for(let o of i){let t=T(o);t&&l.push({name:t.name||o.split("/").pop()||"unknown",description:t.description,skills:t.skills,agents:t.agents,mcpServers:t.mcpServers,hooks:t.hooks})}return{plugins:l}}export{R as a,T as b,$ as c,G as d,U as e,I as f,q as g,O as h,z as i};
@@ -1,2 +1,2 @@
1
- import{b as r,d as s}from"./chunk-AQO6IIHV.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{l as r,n as s}from"./chunk-BPXS4QEO.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};
@@ -0,0 +1,9 @@
1
+ import{h as u}from"./chunk-XIVFVKMB.js";import{l as d,n as l}from"./chunk-BPXS4QEO.js";l();function r(e){return{id:e.id,roleId:e.role_id,content:e.content,confidence:e.confidence,useCount:e.use_count,successCount:e.success_count,isAnti:e.is_anti===1,evidenceObsIds:e.evidence_obs_ids?JSON.parse(e.evidence_obs_ids):[],embedding:e.embedding?new Float32Array(e.embedding.buffer,e.embedding.byteOffset,e.embedding.byteLength/4):void 0,supersededBy:e.superseded_by??void 0,createdAt:e.created_at,lastUsedAt:e.last_used_at,lastValidatedAt:e.last_validated_at}}function f(e){return Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function p(e){d().prepare(`
2
+ INSERT INTO beliefs (id, role_id, content, confidence, use_count, success_count,
3
+ is_anti, evidence_obs_ids, embedding, superseded_by,
4
+ created_at, last_used_at, last_validated_at)
5
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
6
+ `).run(e.id,e.roleId,e.content,e.confidence,e.useCount,e.successCount,e.isAnti?1:0,JSON.stringify(e.evidenceObsIds),e.embedding?f(e.embedding):null,e.supersededBy??null,e.createdAt,e.lastUsedAt,e.lastValidatedAt)}function E(e){let t=d().prepare("SELECT * FROM beliefs WHERE id = ?").get(e);return t?r(t):void 0}function m(e,n){let t=d(),i=["role_id = ?"],o=[e];return n?.includeSuperseded||i.push("superseded_by IS NULL"),n?.includeAnti===!1&&i.push("is_anti = 0"),t.prepare(`SELECT * FROM beliefs WHERE ${i.join(" AND ")} ORDER BY last_used_at DESC`).all(...o).map(r)}function g(e,n,t){let c=d().prepare(`SELECT * FROM beliefs
7
+ WHERE role_id = ? AND embedding IS NOT NULL AND superseded_by IS NULL
8
+ ORDER BY confidence DESC, last_used_at DESC
9
+ LIMIT ?`).all(e,Math.min(t*10,1e3)).map(s=>({node:r(s),cosine:s.embedding?u(n,new Float32Array(s.embedding.buffer,s.embedding.byteOffset,s.embedding.byteLength/4)):0})).filter(s=>s.cosine>=0);return c.sort((s,a)=>a.cosine-s.cosine),c.slice(0,t)}function B(e,n){d().prepare("UPDATE beliefs SET superseded_by = ? WHERE id = ?").run(n,e)}function R(e,n){let t=d(),i=t.prepare("SELECT confidence, use_count, success_count FROM beliefs WHERE id = ?").get(e);if(!i)return;let o=Date.now(),c=i.confidence,s=i.success_count;n==="high"?(c=Math.min(1,i.confidence*1.1),s+=1):n==="low"&&(c=Math.max(0,i.confidence*.8)),t.prepare("UPDATE beliefs SET confidence = ?, use_count = use_count + 1, success_count = ?, last_used_at = ?, last_validated_at = ? WHERE id = ?").run(c,s,o,o,e)}function A(e,n){d().prepare("UPDATE beliefs SET content = ?, is_anti = 1, last_validated_at = ? WHERE id = ?").run(n,Date.now(),e)}export{p as a,E as b,m as c,g as d,B as e,R as f,A as g};
@@ -1,4 +1,4 @@
1
- import{b as t,d}from"./chunk-AQO6IIHV.js";d();function s(e){return{id:e.id,taskId:e.task_id,roleId:void 0,plan:JSON.parse(e.plan_json),status:e.status,approvalType:e.approval_type??void 0,deviationReport:e.deviation_report_json?JSON.parse(e.deviation_report_json):void 0,learnedRules:e.learned_rules_json?JSON.parse(e.learned_rules_json):void 0,createdAt:e.created_at,approvedAt:e.approved_at??void 0,reviewedAt:e.reviewed_at??void 0}}function p(e){t().prepare(`
1
+ import{l as t,n as d}from"./chunk-BPXS4QEO.js";d();function s(e){return{id:e.id,taskId:e.task_id,roleId:void 0,plan:JSON.parse(e.plan_json),status:e.status,approvalType:e.approval_type??void 0,deviationReport:e.deviation_report_json?JSON.parse(e.deviation_report_json):void 0,learnedRules:e.learned_rules_json?JSON.parse(e.learned_rules_json):void 0,createdAt:e.created_at,approvedAt:e.approved_at??void 0,reviewedAt:e.reviewed_at??void 0}}function p(e){t().prepare(`
2
2
  INSERT INTO task_plans (id, task_id, plan_json, status, approval_type,
3
3
  deviation_report_json, learned_rules_json, created_at, approved_at, reviewed_at)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -0,0 +1,15 @@
1
+ import{a as m,g as L}from"./chunk-IRUR4DVD.js";import{l as a,n as x}from"./chunk-BPXS4QEO.js";import{b as u,h as _}from"./chunk-WBAPIPST.js";import{c as v,e as N}from"./chunk-245WE5AF.js";import{c as l}from"./chunk-FCV2DPZQ.js";var f,p,T=l(()=>{"use strict";f={stylePreferences:[],avoidedActions:[],pinnedParameters:[]},p=class extends Error{constructor(i,r,n,s){super(`Role '${r}' has ${n} active task(s) (${s.join(", ")}) and cannot be deleted without the force flag.`);this.roleId=i;this.roleName=r;this.activeTaskCount=n;this.taskStatuses=s;this.name="RoleHasActiveTasksError"}roleId;roleName;activeTaskCount;taskStatuses;code="ROLE_HAS_ACTIVE_TASKS"}});import*as R from"os";import*as S from"path";function g(e){return e.startsWith("~/")||e==="~"?S.join(R.homedir(),e.slice(1)):e}var C=l(()=>{"use strict";_()});function E(e){return A.includes(e)}function I(e){return k[e]}function B(){return A.map(e=>k[e])}function ee(e,t=e!=="none"){return B().map(i=>J(i,e,t))}function J(e,t,i=t!=="none"){return process.platform==="darwin"?e.status==="runtime-enforced"&&(t!=="sandbox-exec"||!i)?{...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 te(e){if(!e?.length)return;for(let i of e)if(!E(i.id))throw new Error(`Unknown OS capability: ${i.id}`);let t=c(e);if(t?.length){for(let i of t){let r=I(i.id);if(r.status!=="runtime-enforced")throw new Error(`OS capability '${r.label}' is not editable in Role settings`);if(r.supportsTargets){if(!i.targets?.length)throw new Error(`OS capability '${r.label}' requires at least one target bundle id`);for(let n of i.targets)if(!F(n))throw new Error(`Invalid automation target bundle id: ${n}`)}else if(i.targets?.length)throw new Error(`OS capability '${r.label}' does not accept targets`)}return t}}function c(e){if(!e||e.length===0)return;let t=new Set,i=[];for(let r of e){if(!E(r.id))throw new Error(`Unknown OS capability: ${r.id}`);if(t.has(r.id))continue;t.add(r.id);let n=I(r.id),s={id:r.id};n.supportsTargets&&r.targets?.length&&(s.targets=[...new Set(r.targets.map(o=>o.trim()).filter(Boolean))]),i.push(s)}return i.length>0?i.sort((r,n)=>r.id.localeCompare(n.id)):void 0}function F(e){return U.test(e)}var A,k,U,w=l(()=>{"use strict";A=["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"],k={"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."}},U=/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/});function b(e){return{id:e.id,parentId:e.parent_id??void 0,status:e.status,prompt:e.prompt,originalPrompt:e.original_prompt??void 0,config:JSON.parse(e.config),result:e.result??void 0,error:e.error??void 0,sdkSessionId:e.sdk_session_id??void 0,templateId:e.template_id??void 0,roleId:e.role_id??void 0,stepId:e.step_id??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,createdAt:e.created_at,startedAt:e.started_at??void 0,completedAt:e.completed_at??void 0,costUsd:e.cost_usd??void 0,tokenUsage:e.token_usage?JSON.parse(e.token_usage):void 0,numTurns:e.num_turns??void 0,totalDurationMs:e.total_duration_ms??void 0,blockReason:e.block_reason_json?JSON.parse(e.block_reason_json):void 0,traceId:e.trace_id??void 0,errorCategory:e.error_category??void 0,retryCount:e.retry_count}}function se(e){a().prepare(`
2
+ INSERT INTO tasks (id, parent_id, status, prompt, original_prompt, config, result, error,
3
+ sdk_session_id, template_id, role_id, step_id, source_session_id, notify_targets, deliver_to, report_to,
4
+ created_at, started_at, completed_at,
5
+ cost_usd, token_usage, num_turns, total_duration_ms, trace_id, error_category, retry_count)
6
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
7
+ `).run(e.id,e.parentId??null,e.status,e.prompt,e.originalPrompt??null,JSON.stringify(e.config),e.result??null,e.error??null,e.sdkSessionId??null,e.templateId??null,e.roleId??null,e.stepId??null,e.sourceSessionId??null,null,e.deliverTo?JSON.stringify(e.deliverTo):null,e.reportTo?JSON.stringify(e.reportTo):null,e.createdAt,e.startedAt??null,e.completedAt??null,e.costUsd??null,e.tokenUsage?JSON.stringify(e.tokenUsage):null,e.numTurns??null,e.totalDurationMs??null,e.traceId??v()??null,e.errorCategory??null,e.retryCount??0)}function H(e){let i=a().prepare("SELECT * FROM tasks WHERE id = ?").get(e);return i?b(i):void 0}function W(e,t){let i=a(),r=[],n=[],s={parentId:"parent_id",status:"status",prompt:"prompt",result:"result",error:"error",sdkSessionId:"sdk_session_id",templateId:"template_id",roleId:"role_id",stepId:"step_id",sourceSessionId:"source_session_id",originalPrompt:"original_prompt",startedAt:"started_at",completedAt:"completed_at",costUsd:"cost_usd",numTurns:"num_turns",totalDurationMs:"total_duration_ms",errorCategory:"error_category",retryCount:"retry_count"};for(let[o,d]of Object.entries(s))o in t&&(r.push(`${d} = ?`),n.push(t[o]??null));"config"in t&&(r.push("config = ?"),n.push(JSON.stringify(t.config))),"tokenUsage"in t&&(r.push("token_usage = ?"),n.push(t.tokenUsage?JSON.stringify(t.tokenUsage):null)),"deliverTo"in t&&(r.push("deliver_to = ?"),n.push(t.deliverTo?JSON.stringify(t.deliverTo):null)),"reportTo"in t&&(r.push("report_to = ?"),n.push(t.reportTo?JSON.stringify(t.reportTo):null)),"blockReason"in t&&(r.push("block_reason_json = ?"),n.push(t.blockReason?JSON.stringify(t.blockReason):null)),"contextMeta"in t&&(r.push("context_meta = ?"),n.push(t.contextMeta?JSON.stringify(t.contextMeta):null)),r.length!==0&&(n.push(e),i.prepare(`UPDATE tasks SET ${r.join(", ")} WHERE id = ?`).run(...n))}function ae(e,t){let i=H(e);if(!i)return;let r={...i.config??{},...t};W(e,{config:r})}function O(e,t=100,i=0,r){let n=a(),s="SELECT * FROM tasks",o=[],d=[];return e&&(o.push("status = ?"),d.push(e)),r&&(o.push("role_id = ?"),d.push(r)),o.length>0&&(s+=" WHERE "+o.join(" AND ")),s+=" ORDER BY created_at DESC LIMIT ? OFFSET ?",d.push(t,i),n.prepare(s).all(...d).map(b)}function oe(e){return a().prepare("SELECT * FROM tasks WHERE parent_id = ? ORDER BY created_at ASC").all(e).map(b)}function de(e){return a().prepare("SELECT COALESCE(SUM(cost_usd), 0) as total FROM tasks WHERE completed_at >= ? AND cost_usd IS NOT NULL").get(e).total}function le(e){return a().prepare("SELECT trace_id FROM tasks WHERE id = ?").get(e)?.trace_id??void 0}function ce(e){let t=a();return t.prepare("UPDATE tasks SET retry_count = retry_count + 1 WHERE id = ?").run(e),t.prepare("SELECT retry_count FROM tasks WHERE id = ?").get(e)?.retry_count??1}function q(e){return{id:e.id,taskId:e.task_id,retryAt:e.retry_at,createdAt:e.created_at}}function ue(e){a().prepare("INSERT INTO delayed_retries (id, task_id, retry_at, created_at) VALUES (?, ?, ?, ?)").run(e.id,e.taskId,e.retryAt,e.createdAt)}function pe(e){return a().prepare("SELECT * FROM delayed_retries WHERE retry_at <= ? ORDER BY retry_at ASC").all(e).map(q)}function ge(e){a().prepare("DELETE FROM delayed_retries WHERE id = ?").run(e)}function me(e){let i=a().prepare("SELECT context_meta FROM tasks WHERE id = ?").get(e);if(!i||i.context_meta===null)return null;try{return JSON.parse(i.context_meta)}catch{return null}}function fe(e,t){if(t.length===0)return;let i=a(),r=i.prepare("SELECT context_meta FROM tasks WHERE id = ?").get(e),n={usedMemoryIds:[]};if(r?.context_meta!==null&&r?.context_meta!==void 0)try{let o=JSON.parse(r.context_meta);Array.isArray(o.usedMemoryIds)&&(n.usedMemoryIds=o.usedMemoryIds)}catch{}let s=Array.from(new Set([...n.usedMemoryIds,...t]));i.prepare("UPDATE tasks SET context_meta = ? WHERE id = ?").run(JSON.stringify({usedMemoryIds:s}),e)}var P=l(()=>{"use strict";x();N()});import{existsSync as V}from"fs";import{resolve as y}from"path";function M(e){if(e==null)return{...f};if(Array.isArray(e))return{stylePreferences:e.filter(t=>typeof t=="string"),avoidedActions:[],pinnedParameters:[]};if(typeof e=="object"){let t=e;return{stylePreferences:Array.isArray(t.stylePreferences)?t.stylePreferences.filter(i=>typeof i=="string"):[],avoidedActions:Array.isArray(t.avoidedActions)?t.avoidedActions.filter(i=>typeof i=="string"):[],pinnedParameters:Array.isArray(t.pinnedParameters)?t.pinnedParameters.filter(i=>i!==null&&typeof i=="object"&&typeof i.tool=="string"):[]}}return{...f}}function D(e,t){for(let i of e){let r=typeof i=="string"?i:i.path;if(!r.startsWith("/")&&!r.startsWith("~/")&&r!=="~")throw new Error(`additionalDirectories must be absolute paths: '${r}' is not absolute`);let n=y(g(r));if(!n.startsWith("/"))throw new Error(`additionalDirectories must be absolute paths: '${r}' is not absolute`);for(let s of u){let o=y(g(s));if(n.startsWith(o))throw new Error(`additionalDirectories cannot include hardcoded denied path: '${r}' matches '${s}'`)}if(t?.length)for(let s of t){let o=y(g(s));if(n.startsWith(o)||o.startsWith(n))throw new Error(`additionalDirectories cannot overlap with deniedReadPaths: '${r}' conflicts with '${s}'`)}if(!V(n))throw new Error(`additionalDirectories path does not exist: '${r}'`)}}function h(e){return{id:e.id,name:e.name,cagPrompt:e.cag_prompt,learnedRules:M(e.learned_rules?JSON.parse(e.learned_rules):null),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 t=JSON.parse(e.additional_directories);return Array.isArray(t)?t.map(i=>typeof i=="string"?{path:i}:i):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?c(JSON.parse(e.os_capabilities)):void 0,presetId:e.preset_id??void 0,effortTier:e.effort_tier??void 0,skills:e.skills?JSON.parse(e.skills):void 0}}function Ae(e){let t=m("defaults.deniedReadPaths")??[...u];e.additionalDirectories&&D(e.additionalDirectories,t),a().prepare(`
8
+ INSERT INTO roles (id, name, cag_prompt, learned_rules, memory_stream_id, status,
9
+ performance_score, preferences, created_at, updated_at,
10
+ allowed_tools, disallowed_tools, evaluation_criteria, execution_mode, model,
11
+ max_budget_usd, approval_required, source, additional_directories, allowed_channels, mcp_servers, inherit_user_settings,
12
+ permission_mode, allowed_bash_patterns, denied_bash_patterns, env_vars, os_capabilities, preset_id,
13
+ effort_tier, skills)
14
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
15
+ `).run(e.id,e.name,e.cagPrompt,JSON.stringify(e.learnedRules),e.memoryStreamId,e.status,e.performanceScore??null,e.preferences?JSON.stringify(e.preferences):null,e.createdAt,e.updatedAt??null,e.allowedTools?JSON.stringify(e.allowedTools):null,e.disallowedTools?JSON.stringify(e.disallowedTools):null,e.evaluationCriteria?JSON.stringify(e.evaluationCriteria):null,e.executionMode??null,e.model??null,e.maxBudgetUsd??null,e.approvalRequired?JSON.stringify(e.approvalRequired):null,e.source??null,e.additionalDirectories?JSON.stringify(e.additionalDirectories):null,e.allowedChannels?JSON.stringify(e.allowedChannels):null,e.mcpServers?JSON.stringify(e.mcpServers):null,e.inheritUserSettings?1:0,e.permissionMode??null,e.allowedBashPatterns?JSON.stringify(e.allowedBashPatterns):null,e.deniedBashPatterns?JSON.stringify(e.deniedBashPatterns):null,e.envVars?JSON.stringify(e.envVars):null,e.osCapabilities?JSON.stringify(c(e.osCapabilities)):null,e.presetId??null,e.effortTier??null,e.skills?JSON.stringify(e.skills):null)}function j(e){let i=a().prepare("SELECT * FROM roles WHERE id = ?").get(e);return i?h(i):void 0}function ke(e){let i=a().prepare("SELECT * FROM roles WHERE name = ?").get(e);return i?h(i):void 0}function Ee(e,t){let i=a(),r=[],n=[];if("name"in t&&(r.push("name = ?"),n.push(t.name)),"cagPrompt"in t&&(r.push("cag_prompt = ?"),n.push(t.cagPrompt)),"learnedRules"in t&&(r.push("learned_rules = ?"),n.push(JSON.stringify(M(t.learnedRules)))),"memoryStreamId"in t&&(r.push("memory_stream_id = ?"),n.push(t.memoryStreamId)),"status"in t&&(r.push("status = ?"),n.push(t.status)),"performanceScore"in t&&(r.push("performance_score = ?"),n.push(t.performanceScore??null)),"preferences"in t&&(r.push("preferences = ?"),n.push(t.preferences?JSON.stringify(t.preferences):null)),"updatedAt"in t&&(r.push("updated_at = ?"),n.push(t.updatedAt??null)),"allowedTools"in t&&(r.push("allowed_tools = ?"),n.push(t.allowedTools?JSON.stringify(t.allowedTools):null)),"disallowedTools"in t&&(r.push("disallowed_tools = ?"),n.push(t.disallowedTools?JSON.stringify(t.disallowedTools):null)),"evaluationCriteria"in t&&(r.push("evaluation_criteria = ?"),n.push(t.evaluationCriteria?JSON.stringify(t.evaluationCriteria):null)),"executionMode"in t&&(r.push("execution_mode = ?"),n.push(t.executionMode??null)),"model"in t&&(r.push("model = ?"),n.push(t.model??null)),"maxBudgetUsd"in t&&(r.push("max_budget_usd = ?"),n.push(t.maxBudgetUsd??null)),"approvalRequired"in t&&(r.push("approval_required = ?"),n.push(t.approvalRequired?JSON.stringify(t.approvalRequired):null)),"source"in t&&(r.push("source = ?"),n.push(t.source??null)),"additionalDirectories"in t){let s=m("defaults.deniedReadPaths")??[...u];t.additionalDirectories&&D(t.additionalDirectories,s),r.push("additional_directories = ?"),n.push(t.additionalDirectories?JSON.stringify(t.additionalDirectories):null)}"allowedChannels"in t&&(r.push("allowed_channels = ?"),n.push(t.allowedChannels?JSON.stringify(t.allowedChannels):null)),"mcpServers"in t&&(r.push("mcp_servers = ?"),n.push(t.mcpServers?JSON.stringify(t.mcpServers):null)),"inheritUserSettings"in t&&(r.push("inherit_user_settings = ?"),n.push(t.inheritUserSettings?1:0)),"permissionMode"in t&&(r.push("permission_mode = ?"),n.push(t.permissionMode??null)),"allowedBashPatterns"in t&&(r.push("allowed_bash_patterns = ?"),n.push(t.allowedBashPatterns?JSON.stringify(t.allowedBashPatterns):null)),"deniedBashPatterns"in t&&(r.push("denied_bash_patterns = ?"),n.push(t.deniedBashPatterns?JSON.stringify(t.deniedBashPatterns):null)),"envVars"in t&&(r.push("env_vars = ?"),n.push(t.envVars?JSON.stringify(t.envVars):null)),"osCapabilities"in t&&(r.push("os_capabilities = ?"),n.push(t.osCapabilities?JSON.stringify(c(t.osCapabilities)):null)),"presetId"in t&&(r.push("preset_id = ?"),n.push(t.presetId??null)),"effortTier"in t&&(r.push("effort_tier = ?"),n.push(t.effortTier??null)),"skills"in t&&(r.push("skills = ?"),n.push(t.skills?JSON.stringify(t.skills):null)),r.length!==0&&(n.push(e),i.prepare(`UPDATE roles SET ${r.join(", ")} WHERE id = ?`).run(...n))}function Ie(e,t,i=0){let r=a(),n="SELECT * FROM roles",s=[];return e&&(n+=" WHERE status = ?",s.push(e)),n+=" ORDER BY COALESCE(updated_at, created_at) DESC",typeof t=="number"&&(n+=" LIMIT ? OFFSET ?",s.push(t,i)),r.prepare(n).all(...s).map(h)}function G(e){let t=["pending","queued","running"],r=O(void 0,1e3,0,e).filter(s=>t.includes(s.status)),n=[...new Set(r.map(s=>s.status))];return{hasActive:r.length>0,count:r.length,statuses:n}}function we(e,t=!1){if(!t){let{hasActive:r,count:n,statuses:s}=G(e);if(r){let o=j(e);throw new p(e,o?.name??e,n,s)}}a().prepare("DELETE FROM roles WHERE id = ?").run(e)}var K=l(()=>{x();T();_();C();L();w();P()});export{se as a,H as b,W as c,ae as d,O as e,oe as f,de as g,le as h,ce as i,ue as j,pe as k,ge as l,me as m,fe as n,P as o,p,T as q,g as r,C as s,A as t,U as u,I as v,ee as w,te as x,c as y,w as z,D as A,Ae as B,j as C,ke as D,Ee as E,Ie as F,G,we as H,K as I};
@@ -0,0 +1,21 @@
1
+ import{l,n as T}from"./chunk-BPXS4QEO.js";import{c as h}from"./chunk-FCV2DPZQ.js";import{basename as k}from"path";import{v4 as R}from"uuid";function _(e){return{id:e.id,executionId:e.execution_id,stepId:e.step_id,key:e.key,kind:e.kind,value:e.value_json?JSON.parse(e.value_json):void 0,blobPath:e.blob_path??void 0,mime:e.mime??void 0,originalFilename:e.original_filename??void 0,sizeBytes:e.size_bytes,createdAt:e.created_at,locator:e.locator??void 0,contentHash:e.content_hash??void 0,retentionHint:e.retention_hint??void 0,encryptionClass:e.encryption_class??void 0,purpose:e.purpose??void 0,replaces:e.replaces??void 0,producedByRole:e.produced_by_role??void 0,access:e.access??void 0}}function F(e){d(l(),e)}function d(e,t){e.prepare(`
2
+ INSERT INTO template_execution_artifacts (
3
+ id, execution_id, step_id, key, kind, value_json, blob_path, mime, original_filename, size_bytes, created_at,
4
+ locator, content_hash, retention_hint, encryption_class, purpose, replaces, produced_by_role, access
5
+ )
6
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
7
+ `).run(t.id,t.executionId,t.stepId,t.key,t.kind,t.value!==void 0?JSON.stringify(t.value):null,t.blobPath??null,t.mime??null,t.originalFilename??null,t.sizeBytes,t.createdAt,t.locator??null,t.contentHash??null,t.retentionHint??null,t.encryptionClass??null,t.purpose??null,t.replaces??null,t.producedByRole??null,t.access??null)}function y(e,t,n,i){let r=e.prepare(`
8
+ SELECT * FROM template_execution_artifacts
9
+ WHERE execution_id = ? AND step_id = ? AND key = ?
10
+ `).get(t,n,i);return r?_(r):void 0}function P(e,t,n){return y(l(),e,t,n)}function x(e,t){let n=l(),i="SELECT * FROM template_execution_artifacts WHERE execution_id = ?",r=[e];return t&&(i+=" AND step_id = ?",r.push(t)),i+=" ORDER BY created_at ASC",n.prepare(i).all(...r).map(_)}function O(e){let t=l(),n=x(e);return t.prepare("DELETE FROM template_execution_artifacts WHERE execution_id = ?").run(e),n}function w(e,t){let n=l(),i=x(e).filter(r=>r.stepId===t);return n.prepare("DELETE FROM template_execution_artifacts WHERE execution_id = ? AND step_id = ?").run(e,t),i}function N(e){l().prepare("DELETE FROM template_execution_artifacts WHERE id = ?").run(e)}function S(e){if(!e||typeof e!="object")return!1;let t=e;return t.type!=="artifact_collection"||typeof t.outputAs!="string"||t.outputAs.length===0||!Array.isArray(t.items)?!1:t.items.every(n=>n!=null&&typeof n=="object"&&typeof n.artifactId=="string"&&n.artifactId.length>0&&typeof n.key=="string"&&n.key.length>0&&typeof n.sizeBytes=="number"&&Number.isFinite(n.sizeBytes)&&(n.filename===void 0||typeof n.filename=="string")&&(n.mime===void 0||typeof n.mime=="string")&&(n.purpose===void 0||typeof n.purpose=="string"))}function $(e,t,n){return p(l(),e,t,n)}function j(e,t,n,i){let r=l();return r.transaction(()=>{let c=y(r,e,t,n);if(!c||c.kind!=="json"||!S(c.value))throw new Error(`Artifact collection manifest not found at ${t}/${n}`);let a=p(r,e,t,i.key,new Set([n])),s={...i,key:a};d(r,s);let u={...c.value,items:[...c.value.items,g(s)]};return{manifestArtifact:M(r,c,u),childArtifact:s}})()}function L(e,t,n,i,r){let o=l();return o.transaction(()=>{let a=y(o,e,t,n);if(!a||a.id!==i.id)throw new Error(`Primary artifact changed before collection conversion at ${t}/${n}`);if(a.kind!=="file"||!a.blobPath)throw new Error(`Primary artifact at ${t}/${n} is not a file`);let s=p(o,e,t,a.originalFilename??a.key,new Set([n]));o.prepare("UPDATE template_execution_artifacts SET key = ? WHERE id = ?").run(s,a.id);let u={...a,key:s},m=p(o,e,t,r.key,new Set([n,s])),f={...r,key:m};d(o,f);let A={type:"artifact_collection",outputAs:n,items:[g(u),g(f)]},E={id:R(),executionId:e,stepId:t,key:n,kind:"json",value:A,sizeBytes:b(A),createdAt:Date.now(),purpose:"data"};return d(o,E),{manifestArtifact:E,childArtifact:f,rekeyedPrimaryArtifact:u}})()}function W(e){return l().prepare(`
11
+ SELECT id
12
+ FROM template_executions
13
+ WHERE status != 'running' AND COALESCE(completed_at, started_at) < ?
14
+ `).all(e).map(i=>i.id)}function p(e,t,n,i,r=new Set){let o=e.prepare(`
15
+ SELECT key FROM template_execution_artifacts
16
+ WHERE execution_id = ? AND step_id = ?
17
+ `).all(t,n),c=new Set(o.map(s=>s.key));for(let s of r)c.add(s);let a=B(i);if(!c.has(a))return a;for(let s=2;s<1e4;s++){let u=`-${s}`,f=`${a.slice(0,Math.max(1,256-u.length))}${u}`;if(!c.has(f))return f}throw new Error(`Unable to allocate unique artifact key for ${n}/${i}`)}function B(e){let t=e.replace(/\\/g,"/"),i=k(t).replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,256);return!i||i==="."||i===".."?"artifact":C.test(i)?i:"artifact"}function g(e){return{artifactId:e.id,key:e.key,...e.originalFilename?{filename:e.originalFilename}:{},...e.mime?{mime:e.mime}:{},sizeBytes:e.sizeBytes,...e.purpose?{purpose:e.purpose}:{}}}function M(e,t,n){let i=b(n);return e.prepare(`
18
+ UPDATE template_execution_artifacts
19
+ SET value_json = ?, size_bytes = ?
20
+ WHERE id = ?
21
+ `).run(JSON.stringify(n),i,t.id),{...t,value:n,sizeBytes:i}}function b(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}var C,v=h(()=>{T();C=/^[\p{L}0-9._-]{1,256}$/u});export{F as a,P as b,x as c,O as d,w as e,N as f,S as g,$ as h,j as i,L as j,W as k,v as l};
@@ -0,0 +1,34 @@
1
+ import{l as a,n as l}from"./chunk-BPXS4QEO.js";l();import{v4 as p}from"uuid";function u(e){let t=[];e.traceId||t.push("traceId is required"),e.actor?(e.actor.traceId||t.push("actor.traceId is required"),e.actor.toolName||t.push("actor.toolName is required"),e.traceId&&e.actor.traceId&&e.actor.traceId!==e.traceId&&t.push(`actor.traceId ('${e.actor.traceId}') must equal top-level traceId ('${e.traceId}')`)):t.push("actor is required"),e.effectCategory!=="outbound_message"&&e.effectCategory!=="entity_mutation"&&t.push(`effectCategory must be 'outbound_message' or 'entity_mutation', got '${e.effectCategory}'`),e.verb||t.push("verb is required"),e.entityType||t.push("entityType is required");let n=e.entityId!==void 0&&e.entityId!==null,r=Array.isArray(e.entityIds)&&e.entityIds.length>0;if(n&&r&&t.push("entityId and entityIds are mutually exclusive \u2014 provide one only"),e.effectCategory==="outbound_message"&&(e.target?.channelId||t.push("outbound_message receipts require target.channelId"),(!e.payload||typeof e.payload.textChars!="number"||typeof e.payload.attachmentCount!="number")&&t.push("outbound_message receipts require payload with textChars and attachmentCount (numbers)")),e.outcome!==void 0&&e.outcome!=="success"&&e.outcome!=="failure"&&t.push(`outcome must be 'success' or 'failure', got '${String(e.outcome)}'`),e.effectCategory==="entity_mutation"){!n&&!r&&t.push("entity_mutation receipts require entityId or entityIds (verifier needs an entity to anchor the change)");let i=Array.isArray(e.fieldChanges)&&e.fieldChanges.length>0,s=!!e.scope&&typeof e.scope.matchedCount=="number"&&!!e.scope.filter;!i&&!s&&t.push("entity_mutation receipts require either fieldChanges (non-empty) or scope (with filter+matchedCount)"),r&&!s&&t.push("batch entity_mutation receipts (entityIds set) require scope to describe the matched set")}return{valid:t.length===0,errors:t}}var c=class extends Error{constructor(n){super(`Invalid effect receipt: ${n.join("; ")}`);this.errors=n;this.name="InvalidReceiptError"}errors};function R(e){let t=u(e);if(!t.valid)throw new c(t.errors);let n={id:e.id??p(),traceId:e.traceId,taskId:e.taskId,sessionId:e.sessionId,effectCategory:e.effectCategory,verb:e.verb,entityType:e.entityType,entityId:e.entityId,entityIds:e.entityIds,target:e.target,payload:e.payload,fieldChanges:e.fieldChanges,scope:e.scope,actor:e.actor,outcome:e.outcome??"success",createdAt:e.createdAt??Date.now()};return a().prepare(`
2
+ INSERT INTO effect_receipts (
3
+ id, trace_id, task_id, session_id,
4
+ effect_category, verb, entity_type,
5
+ entity_id, entity_ids_json,
6
+ target_json, payload_json, field_changes_json, scope_json,
7
+ actor_json, outcome, created_at
8
+ )
9
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
10
+ `).run(n.id,n.traceId,n.taskId??null,n.sessionId??null,n.effectCategory,n.verb,n.entityType,n.entityId??null,n.entityIds?JSON.stringify(n.entityIds):null,n.target?JSON.stringify(n.target):null,n.payload?JSON.stringify(n.payload):null,n.fieldChanges?JSON.stringify(n.fieldChanges):null,n.scope?JSON.stringify(n.scope):null,JSON.stringify(n.actor),n.outcome,n.createdAt),n}function I(e){return a().prepare(`
11
+ SELECT * FROM effect_receipts
12
+ WHERE trace_id = ?
13
+ ORDER BY created_at ASC
14
+ `).all(e).map(f)}function f(e){return{id:e.id,traceId:e.trace_id,taskId:e.task_id??void 0,sessionId:e.session_id??void 0,effectCategory:e.effect_category,verb:e.verb,entityType:e.entity_type,entityId:e.entity_id??void 0,entityIds:o(e.entity_ids_json)??void 0,target:o(e.target_json)??void 0,payload:o(e.payload_json)??void 0,fieldChanges:o(e.field_changes_json)??void 0,scope:o(e.scope_json)??void 0,actor:JSON.parse(e.actor_json),outcome:e.outcome??"success",createdAt:e.created_at}}function o(e){if(e!==null)try{return JSON.parse(e)}catch{return}}l();function d(e){return{id:e.id,templateId:e.template_id,status:e.status,stepStatuses:JSON.parse(e.step_statuses),startedAt:e.started_at,completedAt:e.completed_at??void 0,error:e.error??void 0,eventId:e.event_id??void 0,stepResultsJson:e.step_results_json??void 0}}function x(e,t,n){a().prepare(`
15
+ INSERT INTO template_executions (id, template_id, status, step_statuses, started_at, event_id)
16
+ VALUES (?, ?, 'running', '{}', ?, ?)
17
+ `).run(e,t,Date.now(),n??null)}function S(e){let n=a().prepare("SELECT * FROM template_executions WHERE id = ?").get(e);return n?d(n):void 0}function v(e,t){let n=a(),r=[],i=[];t.status!==void 0&&(r.push("status = ?"),i.push(t.status)),t.stepStatuses!==void 0&&(r.push("step_statuses = ?"),i.push(JSON.stringify(t.stepStatuses))),t.completedAt!==void 0&&(r.push("completed_at = ?"),i.push(t.completedAt)),t.error!==void 0&&(r.push("error = ?"),i.push(t.error)),r.length!==0&&(i.push(e),n.prepare(`UPDATE template_executions SET ${r.join(", ")} WHERE id = ?`).run(...i))}function b(e){let t=a(),n=Date.now()-e;return t.prepare("SELECT * FROM template_executions WHERE status = 'running' AND started_at < ?").all(n).map(d)}function C(e,t=50,n=0){let r=a(),i="SELECT * FROM template_executions",s=[];return e&&(i+=" WHERE template_id = ?",s.push(e)),i+=" ORDER BY started_at DESC LIMIT ? OFFSET ?",s.push(t,n),r.prepare(i).all(...s).map(d)}function A(e,t=20,n=0){return a().prepare(`
18
+ SELECT te.id AS execution_id,
19
+ te.template_id,
20
+ tt.name AS template_name,
21
+ te.status,
22
+ te.started_at,
23
+ te.completed_at,
24
+ te.error,
25
+ te.event_id,
26
+ e.occurred_at AS event_occurred_at,
27
+ e.payload AS event_payload
28
+ FROM template_executions te
29
+ LEFT JOIN task_templates tt ON tt.id = te.template_id
30
+ INNER JOIN events e ON e.id = te.event_id
31
+ WHERE e.event_def_id = ?
32
+ ORDER BY te.started_at DESC
33
+ LIMIT ? OFFSET ?
34
+ `).all(e,t,n).map(s=>({executionId:s.execution_id,templateId:s.template_id,templateName:s.template_name,status:s.status,startedAt:s.started_at,completedAt:s.completed_at,error:s.error,eventId:s.event_id,eventOccurredAt:s.event_occurred_at,eventPayload:s.event_payload?JSON.parse(s.event_payload):null}))}function O(e,t){let n=JSON.stringify(Array.from(t.entries()));a().prepare("UPDATE template_executions SET step_results_json = ? WHERE id = ?").run(n,e)}export{c as a,R as b,I as c,x as d,S as e,v as f,b as g,C as h,A as i,O as j};
@@ -1 +1 @@
1
- import{d as a}from"./chunk-6WRZJVQ2.js";function s(){try{let t=a().server?.timezone;return t==="system"||!t?void 0:t}catch{return}}function p(t){let e=s();return new Date(t).toLocaleTimeString(void 0,e?{timeZone:e}:void 0)}function l(t){let e=t??s(),r=new Date,i=r.toLocaleDateString("en-CA",e?{timeZone:e}:void 0);if(e){let n=(new Intl.DateTimeFormat("en-US",{timeZone:e,timeZoneName:"shortOffset"}).formatToParts(r).find(o=>o.type==="timeZoneName")?.value??"").match(/GMT([+-]?)(\d+)(?::(\d+))?/);if(n){let o=n[1]==="-"?-1:1,m=parseInt(n[2],10),c=parseInt(n[3]??"0",10),f=o*(m*60+c)*6e4;return new Date(`${i}T00:00:00Z`).getTime()-f}}return new Date(`${i}T00:00:00`).getTime()}export{p as a,l as b};
1
+ import{d as a}from"./chunk-Z6LHGA27.js";function s(){try{let t=a().server?.timezone;return t==="system"||!t?void 0:t}catch{return}}function p(t){let e=s();return new Date(t).toLocaleTimeString(void 0,e?{timeZone:e}:void 0)}function l(t){let e=t??s(),r=new Date,i=r.toLocaleDateString("en-CA",e?{timeZone:e}:void 0);if(e){let n=(new Intl.DateTimeFormat("en-US",{timeZone:e,timeZoneName:"shortOffset"}).formatToParts(r).find(o=>o.type==="timeZoneName")?.value??"").match(/GMT([+-]?)(\d+)(?::(\d+))?/);if(n){let o=n[1]==="-"?-1:1,m=parseInt(n[2],10),c=parseInt(n[3]??"0",10),f=o*(m*60+c)*6e4;return new Date(`${i}T00:00:00Z`).getTime()-f}}return new Date(`${i}T00:00:00`).getTime()}export{p as a,l as b};
@@ -1 +1 @@
1
- import{d as w,h as S}from"./chunk-WBAPIPST.js";import{c as g,h as P}from"./chunk-MRTJFYPR.js";P();S();import{readFileSync as v,existsSync as E}from"fs";import{join as p}from"path";import{homedir as R}from"os";var T=g("ws"),x=p(R(),".adam"),f=p(x,"adam.port"),b=p(w,"adam.key");function d(){let n=process.env.ADAM_API_KEY;if(n)return n;if(E(b))return v(b,"utf-8").trim()||void 0}function m(){if(!E(f))return null;let n=parseInt(v(f,"utf-8").trim(),10);return isNaN(n)?null:n}function C(){let n=m();if(!n)throw new Error("Server not running. Run: adam server start");return`http://localhost:${n}`}var u=class extends Error{constructor(e,s){super(s);this.status=e;this.name="ApiError"}status};async function A(n,t={}){let s=`${C()}${n}`,r=d(),o=await fetch(s,{method:t.method||"GET",headers:{"Content-Type":"application/json",...r?{"x-api-key":r}:{},...t.headers},body:t.body?JSON.stringify(t.body):void 0});if(!o.ok){let a=await o.text().catch(()=>"Unknown error");throw new u(o.status,a)}return o.headers.get("content-type")?.includes("application/json")?o.json():o.text()}function D(){return A("/healthz")}var k=class{ws=null;callbacks=new Map;reconnectAttempts=0;reconnectTimer=null;url;constructor(t="/events"){let e=m();if(!e)throw new Error("Server not running. Run: adam server start");let s=d(),r=new URL(`ws://localhost:${e}${t}`);s&&r.searchParams.set("api_key",s),this.url=r.toString()}connect(){return new Promise((t,e)=>{try{this.ws=new WebSocket(this.url),this.ws.onopen=()=>{this.reconnectAttempts=0,t()},this.ws.onmessage=s=>{try{let r=JSON.parse(s.data),{type:o,data:c,...a}=r,i=this.callbacks.get(o);i&&i.forEach(l=>l(c??a))}catch(r){T.error({error:r},"Failed to parse WebSocket message")}},this.ws.onclose=()=>{this.scheduleReconnect()},this.ws.onerror=s=>{e(s)}}catch(s){e(s)}})}scheduleReconnect(){let t=[1e3,2e3,4e3,8e3,15e3],e=t[Math.min(this.reconnectAttempts,t.length-1)];this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>{this.connect().catch(()=>{})},e)}on(t,e){this.callbacks.has(t)||this.callbacks.set(t,new Set),this.callbacks.get(t).add(e)}off(t,e){this.callbacks.get(t)?.delete(e)}close(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.ws?.close()}isConnected(){return this.ws?.readyState===WebSocket.OPEN}},y=class{ws=null;callbacks=new Map;url;constructor(t){let e=m();if(!e)throw new Error("Server not running. Run: adam server start");let s=d(),r=new URL(`ws://localhost:${e}/tasks/${t}/stream`);s&&r.searchParams.set("api_key",s),this.url=r.toString()}connect(){return new Promise((t,e)=>{try{this.ws=new WebSocket(this.url),this.ws.onopen=()=>{t()},this.ws.onmessage=s=>{try{let r=JSON.parse(s.data),{type:o,data:c,...a}=r,i=this.callbacks.get(o);i&&i.forEach(h=>h(c??a));let l=this.callbacks.get("*");l&&l.forEach(h=>h(r))}catch(r){T.error({error:r},"Failed to parse task stream message")}},this.ws.onerror=s=>{e(s)},this.ws.onclose=()=>{}}catch(s){e(s)}})}on(t,e){this.callbacks.has(t)||this.callbacks.set(t,new Set),this.callbacks.get(t).add(e)}off(t,e){this.callbacks.get(t)?.delete(e)}close(){this.ws?.close()}isConnected(){return this.ws?.readyState===WebSocket.OPEN}};export{d as a,A as b,D as c,k as d,y as e};
1
+ import{d as w,h as S}from"./chunk-WBAPIPST.js";import{c as g,h as P}from"./chunk-BLCNUT53.js";P();S();import{readFileSync as v,existsSync as E}from"fs";import{join as p}from"path";import{homedir as R}from"os";var T=g("ws"),x=p(R(),".adam"),f=p(x,"adam.port"),b=p(w,"adam.key");function d(){let n=process.env.ADAM_API_KEY;if(n)return n;if(E(b))return v(b,"utf-8").trim()||void 0}function m(){if(!E(f))return null;let n=parseInt(v(f,"utf-8").trim(),10);return isNaN(n)?null:n}function C(){let n=m();if(!n)throw new Error("Server not running. Run: adam server start");return`http://localhost:${n}`}var u=class extends Error{constructor(e,s){super(s);this.status=e;this.name="ApiError"}status};async function A(n,t={}){let s=`${C()}${n}`,r=d(),o=await fetch(s,{method:t.method||"GET",headers:{"Content-Type":"application/json",...r?{"x-api-key":r}:{},...t.headers},body:t.body?JSON.stringify(t.body):void 0});if(!o.ok){let a=await o.text().catch(()=>"Unknown error");throw new u(o.status,a)}return o.headers.get("content-type")?.includes("application/json")?o.json():o.text()}function D(){return A("/healthz")}var k=class{ws=null;callbacks=new Map;reconnectAttempts=0;reconnectTimer=null;url;constructor(t="/events"){let e=m();if(!e)throw new Error("Server not running. Run: adam server start");let s=d(),r=new URL(`ws://localhost:${e}${t}`);s&&r.searchParams.set("api_key",s),this.url=r.toString()}connect(){return new Promise((t,e)=>{try{this.ws=new WebSocket(this.url),this.ws.onopen=()=>{this.reconnectAttempts=0,t()},this.ws.onmessage=s=>{try{let r=JSON.parse(s.data),{type:o,data:c,...a}=r,i=this.callbacks.get(o);i&&i.forEach(l=>l(c??a))}catch(r){T.error({error:r},"Failed to parse WebSocket message")}},this.ws.onclose=()=>{this.scheduleReconnect()},this.ws.onerror=s=>{e(s)}}catch(s){e(s)}})}scheduleReconnect(){let t=[1e3,2e3,4e3,8e3,15e3],e=t[Math.min(this.reconnectAttempts,t.length-1)];this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>{this.connect().catch(()=>{})},e)}on(t,e){this.callbacks.has(t)||this.callbacks.set(t,new Set),this.callbacks.get(t).add(e)}off(t,e){this.callbacks.get(t)?.delete(e)}close(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.ws?.close()}isConnected(){return this.ws?.readyState===WebSocket.OPEN}},y=class{ws=null;callbacks=new Map;url;constructor(t){let e=m();if(!e)throw new Error("Server not running. Run: adam server start");let s=d(),r=new URL(`ws://localhost:${e}/tasks/${t}/stream`);s&&r.searchParams.set("api_key",s),this.url=r.toString()}connect(){return new Promise((t,e)=>{try{this.ws=new WebSocket(this.url),this.ws.onopen=()=>{t()},this.ws.onmessage=s=>{try{let r=JSON.parse(s.data),{type:o,data:c,...a}=r,i=this.callbacks.get(o);i&&i.forEach(h=>h(c??a));let l=this.callbacks.get("*");l&&l.forEach(h=>h(r))}catch(r){T.error({error:r},"Failed to parse task stream message")}},this.ws.onerror=s=>{e(s)},this.ws.onclose=()=>{}}catch(s){e(s)}})}on(t,e){this.callbacks.has(t)||this.callbacks.set(t,new Set),this.callbacks.get(t).add(e)}off(t,e){this.callbacks.get(t)?.delete(e)}close(){this.ws?.close()}isConnected(){return this.ws?.readyState===WebSocket.OPEN}};export{d as a,A as b,D as c,k as d,y as e};
@@ -0,0 +1 @@
1
+ function a(r){return r.platform==="email"}var i=/^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)+$/;function s(r){if(typeof r!="string")throw new Error("Email address must be a string");let e=r.trim();if(!e)throw new Error("Email address is required");if(e.includes(",")||/[<>]/.test(e)||/\s/.test(e))throw new Error("Email address must contain exactly one mailbox address");if(!i.test(e))throw new Error("Email address is invalid");let n=e.lastIndexOf("@"),t=e.slice(0,n).toLowerCase(),o=e.slice(n+1).toLowerCase();return`${t}@${o}`}function l(r){if(Object.keys(r).length!==1||!Object.prototype.hasOwnProperty.call(r,"address"))throw new Error("Mail channel config must contain only address");let n=r.address;if(typeof n!="string")throw new Error("Mail channel config address must be a string");return{address:s(n)}}function c(r){let e=r.config&&typeof r.config=="object"?r.config:{};return l(e).address}function m(r,e){let n=s(r),t=(e??"").replace(/[\r\n]+/g," ").replace(/"/g,'\\"').trim();return t?`"${t}" <${n}>`:n}export{a,s as b,l as c,c as d,m as e};
@@ -0,0 +1,5 @@
1
+ import{l as s,n as d}from"./chunk-BPXS4QEO.js";import{c as l,e as u}from"./chunk-245WE5AF.js";d();u();function a(e){return{id:e.id,ruleId:e.rule_id??void 0,taskId:e.task_id??void 0,executionId:e.execution_id??void 0,status:e.status,target:JSON.parse(e.target),content:e.content,attempts:e.attempts,error:e.error??void 0,createdAt:e.created_at,deliveredAt:e.delivered_at??void 0,expiresAt:e.expires_at,source:e.source,messageType:e.message_type??void 0,traceId:e.trace_id??void 0}}var g=1440*60*1e3;function E(e){s().prepare(`
2
+ INSERT INTO delivery_log (id, rule_id, task_id, execution_id, status, target, content,
3
+ attempts, error, created_at, delivered_at, expires_at, source, message_type, trace_id)
4
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
5
+ `).run(e.id,e.ruleId??null,e.taskId??null,e.executionId??null,e.status,JSON.stringify(e.target),e.content,e.attempts,e.error??null,e.createdAt,e.deliveredAt??null,e.expiresAt,e.source??null,e.messageType??null,e.traceId??l()??null)}function D(e,t,r){s().prepare("UPDATE delivery_log SET status = ?, error = ?, attempts = attempts + 1 WHERE id = ?").run(t,r??null,e)}function v(e){s().prepare("UPDATE delivery_log SET status = 'delivered', delivered_at = ?, attempts = attempts + 1 WHERE id = ?").run(Date.now(),e)}function _(e,t=100){let r=s(),n=Date.now(),i=e?"SELECT * FROM delivery_log WHERE status = 'pending' AND expires_at > ? AND source = ? ORDER BY created_at ASC LIMIT ?":"SELECT * FROM delivery_log WHERE status = 'pending' AND expires_at > ? ORDER BY created_at ASC LIMIT ?";return(e?r.prepare(i).all(n,e,t):r.prepare(i).all(n,t)).map(a)}function y(e,t=100){let r=s(),n=Date.now(),i=e?"SELECT * FROM delivery_log WHERE status = 'failed' AND expires_at > ? AND attempts < 3 AND source = ? ORDER BY created_at ASC LIMIT ?":"SELECT * FROM delivery_log WHERE status = 'failed' AND expires_at > ? AND attempts < 3 ORDER BY created_at ASC LIMIT ?";return(e?r.prepare(i).all(n,e,t):r.prepare(i).all(n,t)).map(a)}function R(){let e=s(),t=Date.now();return e.prepare("DELETE FROM delivery_log WHERE expires_at < ? AND status IN ('pending', 'failed')").run(t).changes}function L(e,t=50){return s().prepare("SELECT * FROM delivery_log WHERE task_id = ? ORDER BY created_at DESC LIMIT ?").all(e,t).map(a)}function I(e,t=50){return s().prepare("SELECT * FROM delivery_log WHERE rule_id = ? ORDER BY created_at DESC LIMIT ?").all(e,t).map(a)}function m(e,t=50){return s().prepare("SELECT * FROM delivery_log WHERE execution_id = ? ORDER BY created_at DESC LIMIT ?").all(e,t).map(a)}function T(e){let t=s();if(!e.taskId&&!e.traceId)return null;let r=[],n=[];e.taskId&&(r.push("task_id = ?"),n.push(e.taskId)),e.traceId&&(r.push("trace_id = ?"),n.push(e.traceId));let i=t.prepare(`SELECT * FROM delivery_log WHERE ${r.join(" OR ")} ORDER BY created_at DESC LIMIT 1`).all(...n);return i.length>0?a(i[0]):null}export{g as a,E as b,D as c,v as d,_ as e,y as f,R as g,L as h,I as i,m as j,T as k};
@@ -0,0 +1 @@
1
+ import{readFileSync as a,existsSync as o}from"fs";import{fileURLToPath as m}from"url";import{dirname as c,join as e}from"path";var p=m(import.meta.url),s=c(p),r,t;function f(){let n=e(s,"..","package.json");if(o(n))return n;let i=e(s,"..","..","package.json");return o(i)?i:e(process.cwd(),"package.json")}function j(){if(r===void 0){let n=f();r=JSON.parse(a(n,"utf-8")).version}return r}function h(){if(t===void 0){let n=f();t=JSON.parse(a(n,"utf-8")).name}return t}import{dirname as u,join as d}from"path";import{fileURLToPath as g}from"url";var l=u(g(import.meta.url)),v=d(l,"..");export{v as a,j as b,h as c};
@@ -0,0 +1 @@
1
+ import{b as s}from"./chunk-NNMQGISW.js";import{c as o,h as d}from"./chunk-BLCNUT53.js";d();var a=o("channels");function c(r,i=[]){if(r.platform==="email")try{return s(String(r.config.address??""))}catch(e){a.warn({channelId:r.id,error:e},"Invalid Mail channel address for target resolution");return}let t=i.find(e=>e.source.type==="channel"&&e.source.channelId===r.id&&e.source.chatId);if(t?.source.chatId)return t.source.chatId;let n=r.config.userId;return typeof n=="string"&&n.trim().length>0?n:void 0}export{c as a};
@@ -1,4 +1,4 @@
1
- import{b as i,d as u}from"./chunk-AQO6IIHV.js";u();function c(t){return{id:t.id,status:t.status,source:{type:t.source_type,channelId:t.source_channel_id??void 0,chatId:t.source_chat_id??void 0},title:t.title??void 0,createdAt:t.created_at,lastActiveAt:t.last_active_at,archivedAt:t.archived_at??void 0,messageCount:t.message_count}}function d(t){i().prepare(`
1
+ import{l as i,n as u}from"./chunk-BPXS4QEO.js";u();function c(t){return{id:t.id,status:t.status,source:{type:t.source_type,channelId:t.source_channel_id??void 0,chatId:t.source_chat_id??void 0},title:t.title??void 0,createdAt:t.created_at,lastActiveAt:t.last_active_at,archivedAt:t.archived_at??void 0,messageCount:t.message_count}}function d(t){i().prepare(`
2
2
  INSERT INTO chat_sessions (id, status, source_type, source_channel_id, source_chat_id,
3
3
  title, created_at, last_active_at, archived_at, message_count)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -0,0 +1 @@
1
+ import{s as b}from"./chunk-APAOIZN4.js";import{q as T}from"./chunk-XIVFVKMB.js";import{s,u as m,w as x}from"./chunk-RBJPQYV3.js";import{F as f,I as J}from"./chunk-KJNAORKM.js";import{a as p}from"./chunk-L7JP7DUO.js";import{c as h,h as C}from"./chunk-BLCNUT53.js";C();J();import{v4 as l}from"uuid";import{CronExpressionParser as E}from"cron-parser";var n=h("scheduler"),y=class{cronJobs=new Map;started=!1;templateExecutionCompletionHandler=null;async start(){if(this.started)return;this.started=!0;let e=m(!0),t=0;for(let r of e)r.trigger.type==="cron"&&r.trigger.cron&&(this.scheduleCronJob(r),t++);let o=0;for(let r of e)r.trigger.type==="once"&&r.trigger.runAt&&(this.scheduleOnceJob(r.id),o++);this.templateExecutionCompletionHandler=r=>{(r.status==="completed"||r.status==="partial")&&this.checkTemplateCompleteTriggers(r.templateId).catch(i=>{n.error({templateId:r.templateId,error:i},"Template-complete trigger check failed")})},p.on("template_execution_status_change",this.templateExecutionCompletionHandler),this.cronJobs.set("memory-cleanup",setInterval(()=>{this.runMemoryCleanup()},36e5)),n.info({cronCount:t,onceCount:o},"Bree engine started with cron jobs + memory cleanup")}runMemoryCleanup(){try{let e=f(void 0,1e3,0),t=0;for(let o of e)t+=T(o.id);t>0&&n.info({totalCleaned:t},"Memory cleanup completed")}catch(e){n.warn({error:e},"Memory cleanup failed")}}async stop(){for(let[,e]of this.cronJobs)clearTimeout(e),clearInterval(e);this.cronJobs.clear(),this.templateExecutionCompletionHandler&&(p.off("template_execution_status_change",this.templateExecutionCompletionHandler),this.templateExecutionCompletionHandler=null),this.started=!1,n.info("Bree engine stopped")}scheduleCronJob(e){let t=`template-${e.id}`;this.cronJobs.has(t)&&(clearTimeout(this.cronJobs.get(t)),this.cronJobs.delete(t));let o;try{o=E.parse(e.trigger.cron)}catch{n.warn({templateId:e.id,cron:e.trigger.cron},"Invalid cron expression");return}let r=()=>{let u=o.next().getTime()-Date.now();return Math.max(u,1e3)},i=()=>{this.executeCronTrigger(e.id).catch(u=>{n.error({templateId:e.id,error:u},"Cron trigger failed")});let d=setTimeout(i,r());this.cronJobs.set(t,d)},c=r(),a=setTimeout(i,c);this.cronJobs.set(t,a),n.debug({jobName:t,nextRun:new Date(Date.now()+c).toISOString()},"Scheduled cron job")}async executeCronTrigger(e){let t=s(e);!t||!t.enabled||(n.info({templateName:t.name},"Cron triggered"),await this.executeTemplateExecution(t,l()))}async scheduleJob(e){let t=s(e);t&&t.trigger.type==="cron"&&t.trigger.cron&&this.scheduleCronJob(t)}async unscheduleJob(e){let t=`template-${e}`,o=this.cronJobs.get(t);o&&(clearTimeout(o),this.cronJobs.delete(t))}async runNow(e,t){let o=s(e);if(!o)throw new Error(`Template ${e} not found`);let r=l();return this.executeTemplateExecution(o,r,t).catch(i=>{n.error({templateId:e,error:i},"TemplateExecution failed")}),r}async checkTemplateCompleteTriggers(e){let o=m(!0).filter(r=>r.trigger.type!=="template_complete"||!r.trigger.event?!1:r.trigger.event===`template_complete:${e}`);for(let r of o)n.info({templateName:r.name,sourceTemplateId:e},"Template-complete trigger matched"),await this.executeTemplateExecution(r,l())}async executeTemplateExecution(e,t,o={}){await b(e,{...o,executionId:t,triggerContext:o.triggerContext??{source:"bree"}})}scheduleOnceJob(e){let t=s(e);if(!t||!t.enabled||t.trigger.type!=="once")return;let r=(t.trigger.runAt?new Date(t.trigger.runAt).getTime():0)-Date.now();if(r<=0){n.info({templateId:e,runAt:t.trigger.runAt},"Once-shot template past due, executing immediately"),this.executeOnceTrigger(e).catch(a=>{n.error({templateId:e,error:a},"Once trigger execution failed")});return}let i=`template-${e}`;this.cronJobs.has(i)&&clearTimeout(this.cronJobs.get(i));let c=setTimeout(()=>{this.cronJobs.delete(i),this.executeOnceTrigger(e).catch(a=>{n.error({templateId:e,error:a},"Once trigger execution failed")})},r);this.cronJobs.set(i,c),n.info({templateId:e,runAt:t.trigger.runAt,delayMs:r},"Scheduled once-shot job")}async executeOnceTrigger(e){let t=s(e);!t||!t.enabled||(n.info({templateName:t.name},"Once-shot triggered"),await this.executeTemplateExecution(t,l()),x(e),n.info({templateId:e},"Once-shot template auto-disabled after execution"))}},v=null;function N(){return v}function j(g){v=g}export{y as a,N as b,j as c};
@@ -0,0 +1,6 @@
1
+ import{C as m,I as b}from"./chunk-KJNAORKM.js";import{g as I,j as y,l as g,n as U}from"./chunk-BPXS4QEO.js";U();b();import{z as l}from"zod";var u=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,N=/^role-[a-z0-9][a-z0-9-]*$/,R=/^tmpl-[a-f0-9]+$/,P=/^workflow-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,k=/^[a-z][a-z0-9]+-[a-z][a-z0-9-]+$/,x=/^[a-zA-Z][\w-]*@[a-zA-Z][\w-]*$/,O=/^(?:\/|~\/)/,T=/^[\p{L}0-9._-]+$/u,F=l.string().regex(u,"taskId must be a UUID (e.g., 'a1b2c3d4-...'). Use list_tasks to find existing IDs.").describe("Task ID (UUID). Use list_tasks or read_task_status to find existing IDs."),J=l.string().refine(e=>u.test(e)||N.test(e),{message:"roleId must be a UUID or a system role ID like 'role-chat-manager'. Use list_roles to find IDs (do NOT pass the Role's display name)."}).describe("Role ID (UUID or 'role-<name>' for presets). Use list_roles to find IDs \u2014 NOT the human-readable name."),W=l.string().regex(u,"goalId must be a UUID. Use list_goals to find existing IDs.").describe("Goal ID (UUID). Use list_goals to find existing IDs."),H=l.string().regex(u,"channelId must be a UUID. Use list_channels to find IDs (do NOT pass the channel's display name).").describe("Channel ID (UUID). Use list_channels to find IDs \u2014 NOT the channel's display name."),G=l.string().regex(u,"sessionId must be a UUID.").describe("Chat session ID (UUID)."),V=l.string().refine(e=>u.test(e)||R.test(e)||P.test(e)||k.test(e),{message:"templateId must be a UUID, 'tmpl-<hex>', 'workflow-<uuid>', or a friendly ID (e.g., 'pkos-scan-and-sync'). Use list_templates to find IDs."}).describe("Task template ID. Use list_templates to find IDs."),Y=l.string().regex(x,"pluginId must be '<name>@<scope>' (e.g., 'github@anthropic'). Use list_available_plugins to discover.").describe("Plugin ID in '<name>@<scope>' format (e.g., 'github@anthropic'). Use list_available_plugins to discover."),j=l.string().regex(u,"eventDefId must be a UUID. Use list_event_defs to find IDs.").describe("Event definition ID (UUID). Use list_event_defs to find IDs."),z=l.string().regex(u,"ruleId must be a UUID. Use list_delivery_rules to find IDs.").describe("Delivery rule ID (UUID). Use list_delivery_rules to find IDs."),K=l.string().regex(u,"strategyId must be a UUID. Use list_strategies to find IDs.").describe("Strategy ID (UUID). Use list_strategies to find IDs."),q=l.string().regex(O,"Path must be absolute ('/Users/.../file' or '~/...'). Do NOT use relative paths or remote URLs.").describe("Absolute local file path (e.g., '/Users/me/file.txt' or '~/Documents/file.txt'). Remote URLs are NOT accepted \u2014 download files locally first."),Q=l.string().regex(/^[A-Za-z0-9_-]{1,64}$/,"executionId must be 1-64 chars: letters, digits, dashes, underscores. Use list_template_executions or query_execution_status to find existing IDs.").describe("TemplateExecution ID. Use list_template_executions or query_execution_status to find existing IDs."),X=l.string().min(1).max(128).regex(T,"stepId must be 1-128 chars: letters (any script), digits, dots, underscores, or dashes.").describe("Template step ID \u2014 a human-readable identifier for a template step.");y();function L(e){if(e)return e.startsWith("event:")?e.slice(6):void 0}var p=class extends Error{constructor(n,s,r=[]){super(s);this.code=n;this.failingStepIds=r;this.name="TemplateValidationError"}code;failingStepIds},_=class extends Error{constructor(n,s){super(v(n,s));this.code=n;this.failingStepIds=s;this.name="TemplateRoleConfigError"}code;failingStepIds};function v(e,t){return e==="STEP_AUTOSELECT_NEEDS_REQUIREMENTS"?`Template has ${t.length} step(s) with autoSelectRole=true but no requirements object. Failing step ids: ${t.join(", ")}`:e==="STEP_ROLE_NOT_FOUND"?`Template has ${t.length} step(s) with a roleId that does not resolve to an active role. Failing step ids: ${t.join(", ")}`:`Template has ${t.length} step(s) without executable role config. Set template.rolePreference, OR set each failing step's roleId, OR set autoSelectRole=true. Failing step ids: ${t.join(", ")}`}function A(e){let t=typeof e.roleId=="string"&&e.roleId.length>0,n=e.autoSelectRole===!0;return t||n}function C(e){if(typeof e.roleId=="string"&&e.roleId.length>0){let t=m(e.roleId);if(!t||t.status!=="active")return{code:"STEP_ROLE_NOT_FOUND",stepId:e.id}}return e.autoSelectRole===!0&&e.requirements==null?{code:"STEP_AUTOSELECT_NEEDS_REQUIREMENTS",stepId:e.id}:null}function M(e){if(!e.rolePreference){let n=[];for(let s of e.steps)A(s)||n.push(s.id);if(n.length>0)throw new _("TEMPLATE_INVALID_ROLE_CONFIG",n)}let t=e.steps.map(n=>C(n)).filter(n=>n!==null);if(t.length>0){let n=t[0].code,s=t.filter(r=>r.code===n).map(r=>r.stepId);throw new _(n,s)}}function h(e){if(!Array.isArray(e.steps)||e.steps.length<1)throw new p("TEMPLATE_STEPS_REQUIRED","Template must contain at least one step.");let t=new Set,n=[],s=[];for(let i of e.steps)(typeof i.id!="string"||i.id.length<1||i.id.length>128||!T.test(i.id))&&s.push(i.id),t.has(i.id)&&n.push(i.id),t.add(i.id);if(s.length>0)throw new p("TEMPLATE_STEP_ID_INVALID",`Template has invalid step id(s): ${s.join(", ")}. Step ids must be 1-128 chars: letters, digits, dots, underscores, or dashes.`,s);if(n.length>0)throw new p("TEMPLATE_STEP_ID_DUPLICATE",`Template has duplicate step id(s): ${n.join(", ")}.`,n);let r=new Map;for(let i of e.steps){let o=i.dependsOn??[];r.set(i.id,o);for(let d of o){if(d===i.id)throw new p("TEMPLATE_DEPENDENCY_SELF",`Template step "${i.id}" cannot depend on itself.`,[i.id]);if(!t.has(d))throw new p("TEMPLATE_DEPENDENCY_UNKNOWN",`Template step "${i.id}" depends on unknown step "${d}".`,[i.id])}}let a=new Set,c=new Set,f=(i,o)=>{if(c.has(i))return[...o,i];if(a.has(i))return null;c.add(i);for(let d of r.get(i)??[]){let E=f(d,[...o,i]);if(E)return E}return c.delete(i),a.add(i),null};for(let i of e.steps){let o=f(i.id,[]);if(o)throw new p("TEMPLATE_DEPENDENCY_CYCLE",`Template step dependencies contain a cycle: ${o.join(" -> ")}.`,[...new Set(o)])}M(e)}function D(e){if(e.type!=="cron"&&e.type!=="manual"&&e.type!=="once"&&e.type!=="template_complete"&&e.type!=="event")throw new p("TEMPLATE_TRIGGER_INVALID",`Template trigger type is not supported: ${String(e.type)}.`);if(e.type==="template_complete"&&!/^template_complete:[\w-]+$/.test(e.event??""))throw new p("TEMPLATE_TRIGGER_INVALID","Template completion trigger event must use 'template_complete:<templateId>'.")}function S(e){let t=e.trigger_type,n={type:t,cron:t==="event"?void 0:e.trigger_cron??void 0,event:t==="event"?void 0:e.trigger_event??void 0,eventDefId:t==="event"?L(e.trigger_event):void 0,runAt:t==="once"?e.trigger_cron??void 0:void 0};return{id:e.id,name:e.name,description:e.description??void 0,trigger:n,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,isPreset:e.is_preset===1?!0:void 0,presetId:e.preset_id??void 0,retryPolicy:e.retry_policy?JSON.parse(e.retry_policy):void 0}}function se(e){h(e),D(e.trigger);let n=g().prepare(`
2
+ INSERT OR IGNORE 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, is_preset, preset_id, retry_policy)
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,e.presetId!=null?1:0,e.presetId??null,e.retryPolicy?JSON.stringify(e.retryPolicy):null);return{changes:Number(n.changes)}}function $(e){let n=g().prepare("SELECT * FROM task_templates WHERE id = ?").get(e);return n?S(n):void 0}function re(e,t){let n=g();if("steps"in t||"rolePreference"in t){let a=$(e);if(a){let c={rolePreference:"rolePreference"in t?t.rolePreference:a.rolePreference,steps:"steps"in t&&t.steps?t.steps:a.steps};h(c)}}"trigger"in t&&t.trigger&&D(t.trigger);let s=[],r=[];"name"in t&&(s.push("name = ?"),r.push(t.name)),"description"in t&&(s.push("description = ?"),r.push(t.description??null)),"trigger"in t&&t.trigger&&(s.push("trigger_type = ?"),r.push(t.trigger.type),s.push("trigger_cron = ?"),r.push(t.trigger.type==="once"?t.trigger.runAt??null:t.trigger.cron??null),s.push("trigger_event = ?"),r.push(t.trigger.type==="event"?`event:${t.trigger.eventDefId}`:t.trigger.event??null)),"steps"in t&&(s.push("steps = ?"),r.push(JSON.stringify(t.steps))),"rolePreference"in t&&(s.push("role_preference = ?"),r.push(t.rolePreference??null)),"config"in t&&(s.push("config = ?"),r.push(t.config?JSON.stringify(t.config):null)),"tags"in t&&(s.push("tags = ?"),r.push(t.tags?JSON.stringify(t.tags):null)),"enabled"in t&&(s.push("enabled = ?"),r.push(t.enabled?1:0)),"sourceSessionId"in t&&(s.push("source_session_id = ?"),r.push(t.sourceSessionId??null)),"deliverTo"in t&&(s.push("deliver_to = ?"),r.push(t.deliverTo?JSON.stringify(t.deliverTo):null)),"reportTo"in t&&(s.push("report_to = ?"),r.push(t.reportTo?JSON.stringify(t.reportTo):null)),"goalIds"in t&&(s.push("goal_ids = ?"),r.push(t.goalIds?JSON.stringify(t.goalIds):null)),"isPreset"in t&&(s.push("is_preset = ?"),r.push(t.isPreset?1:0)),"presetId"in t&&(s.push("preset_id = ?"),r.push(t.presetId??null)),"retryPolicy"in t&&(s.push("retry_policy = ?"),r.push(t.retryPolicy?JSON.stringify(t.retryPolicy):null)),s.length!==0&&(s.push("updated_at = ?"),r.push(Date.now()),r.push(e),n.prepare(`UPDATE task_templates SET ${s.join(", ")} WHERE id = ?`).run(...r))}function ie(e=!1,t,n=0){let s=g(),r="SELECT * FROM task_templates",a=[];return e&&(r+=" WHERE enabled = 1"),r+=" ORDER BY COALESCE(updated_at, created_at) DESC",typeof t=="number"&&(r+=" LIMIT ? OFFSET ?",a.push(t,n)),s.prepare(r).all(...a).map(S)}function oe(e){g().prepare("UPDATE task_templates SET enabled = 1, updated_at = ? WHERE id = ?").run(Date.now(),e)}function le(e){g().prepare("UPDATE task_templates SET enabled = 0, updated_at = ? WHERE id = ?").run(Date.now(),e)}function ae(e){let t=g(),n=t.prepare("SELECT COUNT(*) AS n FROM template_executions WHERE template_id = ?").get(e),s=t.prepare("SELECT COUNT(*) AS n FROM tasks WHERE template_id = ?").get(e);return{executionCount:n.n,taskCount:s.n}}function de(e,t="template_only"){let n=g(),s=n.prepare("SELECT id FROM template_executions WHERE template_id = ?").all(e);n.transaction(()=>{if(t==="with_tasks"){let c=n.prepare("SELECT id FROM tasks WHERE template_id = ?").all(e).map(f=>f.id);if(c.length>0)for(let i=0;i<c.length;i+=500){let o=c.slice(i,i+500),d=o.map(()=>"?").join(",");n.prepare(`DELETE FROM role_scores WHERE task_id IN (${d})`).run(...o),n.prepare(`DELETE FROM manager_decisions WHERE task_id IN (${d})`).run(...o),n.prepare(`UPDATE chat_messages SET task_id = NULL WHERE task_id IN (${d})`).run(...o),n.prepare(`UPDATE approval_rules SET created_by_task_id = NULL WHERE created_by_task_id IN (${d})`).run(...o),n.prepare(`DELETE FROM tasks WHERE id IN (${d})`).run(...o)}}n.prepare("DELETE FROM template_executions WHERE template_id = ?").run(e),n.prepare("DELETE FROM task_templates WHERE id = ?").run(e)})();for(let a of s)I(a.id)}export{F as a,J as b,W as c,H as d,G as e,V as f,Y as g,j as h,z as i,K as j,q as k,Q as l,X as m,p as n,_ as o,M as p,h as q,se as r,$ as s,re as t,ie as u,oe as v,le as w,ae as x,de as y};