adam-agent-server 1.18.0 → 1.19.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 (131) hide show
  1. package/dist/{App-SIQUVFJY.js → App-522DTURQ.js} +10 -10
  2. package/dist/approval-handler-S3NV7OPO.js +1 -0
  3. package/dist/{artifacts-MAYKOTA2.js → artifacts-NFMM3ORE.js} +1 -1
  4. package/dist/audit-diagnostics-IHU3CJYZ.js +1 -0
  5. package/dist/audit-manager-MUMEEP3C.js +1 -0
  6. package/dist/bree-engine-EEKUQA3U.js +1 -0
  7. package/dist/channels-IDBWHLLE.js +1 -0
  8. package/dist/{channels-2TWTBE6Y.js → channels-ZHCTFSDA.js} +1 -1
  9. package/dist/chat-tool-calls-4BQWZCJH.js +1 -0
  10. package/dist/{chunk-Z2APBKIT.js → chunk-2JM3URDG.js} +1 -1
  11. package/dist/{chunk-OBD4245G.js → chunk-4G4CKAXY.js} +1 -1
  12. package/dist/{chunk-2CE2WUUZ.js → chunk-4ZESWP3J.js} +1 -1
  13. package/dist/{chunk-QYI44EP6.js → chunk-4ZG4UMAK.js} +1 -1
  14. package/dist/{chunk-BE653A45.js → chunk-6GYNUTPP.js} +1 -1
  15. package/dist/{chunk-JROGEBP5.js → chunk-76MMY2XC.js} +1 -1
  16. package/dist/{chunk-BMCNQGUH.js → chunk-7QT2ZX3K.js} +1 -1
  17. package/dist/{chunk-SGLZAIVL.js → chunk-A3YUIWLK.js} +1 -1
  18. package/dist/{chunk-HL373H4P.js → chunk-AMJJ2WGU.js} +1 -1
  19. package/dist/{chunk-NUOTFUNF.js → chunk-CN5NEJXG.js} +1 -1
  20. package/dist/{chunk-O6L4UVLV.js → chunk-DFTRUOT6.js} +1 -1
  21. package/dist/{chunk-JYZTIE2J.js → chunk-DRS5NOAA.js} +1 -1
  22. package/dist/{chunk-6WQFYV3N.js → chunk-EBZCHLYS.js} +1 -1
  23. package/dist/{chunk-SKHMWKJT.js → chunk-EPLSB63A.js} +1 -1
  24. package/dist/{chunk-V2MMQ3SH.js → chunk-FN64ZULV.js} +1 -1
  25. package/dist/chunk-FQHGIY3E.js +1 -0
  26. package/dist/{chunk-NSUXJ2VA.js → chunk-GQS3ED3B.js} +1 -1
  27. package/dist/{chunk-LKGYQJMS.js → chunk-HEHST2E2.js} +1 -1
  28. package/dist/chunk-IAGTZGGV.js +32 -0
  29. package/dist/chunk-ITVCPC7G.js +1 -0
  30. package/dist/{chunk-NXGR3PRY.js → chunk-J2VSAXVU.js} +1 -1
  31. package/dist/{chunk-5G64P4KE.js → chunk-JRRNGKDK.js} +1 -1
  32. package/dist/{chunk-KS24764D.js → chunk-JVYSSJKT.js} +2 -2
  33. package/dist/chunk-JXZCQ5XW.js +1 -0
  34. package/dist/{chunk-LCD5DVS6.js → chunk-KM4EFB4N.js} +1 -1
  35. package/dist/chunk-KQMKRRYW.js +143 -0
  36. package/dist/{chunk-4JHACUZY.js → chunk-L4APYD5A.js} +1 -1
  37. package/dist/{chunk-WY5BOCQP.js → chunk-LMQPGVM7.js} +16 -16
  38. package/dist/chunk-MMVDXKYS.js +14 -0
  39. package/dist/chunk-NKS7LEA7.js +182 -0
  40. package/dist/{chunk-VWX2B6OM.js → chunk-ORFLN4BF.js} +1 -1
  41. package/dist/{chunk-2JIQT2CI.js → chunk-PO66F7UQ.js} +1 -1
  42. package/dist/{chunk-XAPJJAJQ.js → chunk-QJXV4SQE.js} +1 -1
  43. package/dist/{chunk-UCUELFCS.js → chunk-R7Q6FSV4.js} +1 -1
  44. package/dist/{chunk-47HJPIUA.js → chunk-T7EKW3B7.js} +1 -1
  45. package/dist/{chunk-JZBXLN7M.js → chunk-VOH52UDS.js} +1 -1
  46. package/dist/{chunk-HRPMRWHD.js → chunk-VZL2DGC4.js} +1 -1
  47. package/dist/{chunk-IEBAOZED.js → chunk-WDMSZS4W.js} +1 -1
  48. package/dist/{chunk-2A2TXYT3.js → chunk-WG3C43QS.js} +3 -3
  49. package/dist/{chunk-TA5PFK5C.js → chunk-YEGUFMLJ.js} +1 -1
  50. package/dist/{chunk-ZQN6JZIJ.js → chunk-ZGA52HRD.js} +1 -1
  51. package/dist/cli.js +2 -2
  52. package/dist/{config-U624HJKI.js → config-GOJLI3X2.js} +1 -1
  53. package/dist/config-Z6KFEFJO.js +1 -0
  54. package/dist/db-ROXIYW5B.js +1 -0
  55. package/dist/{delivery-log-QMQQHES4.js → delivery-log-TGJZ5HU7.js} +1 -1
  56. package/dist/engine-GN7PJPGQ.js +1 -0
  57. package/dist/{evolution-audit-XF4KZZMP.js → evolution-audit-TFJF666X.js} +1 -1
  58. package/dist/execution-tools-BQD2O25X.js +1 -0
  59. package/dist/{external-api-435WH6V3.js → external-api-DSLQDRZ2.js} +1 -1
  60. package/dist/index.js +41 -39
  61. package/dist/{learner-4CJ7BSCN.js → learner-ACBX3GI7.js} +1 -1
  62. package/dist/{memories-NJFKSOL5.js → memories-RAIR5O2F.js} +1 -1
  63. package/dist/{memory-extractor-UQI75BBK.js → memory-extractor-A6CAOFOX.js} +1 -1
  64. package/dist/{memory-gc-NTZVUGJX.js → memory-gc-W63MGSDH.js} +1 -1
  65. package/dist/memory-service-H4OFUNCF.js +1 -0
  66. package/dist/outbound-gateway-LKRQYPA2.js +1 -0
  67. package/dist/presets-FO6RSGDN.js +1 -0
  68. package/dist/{reflection-job-F4BZA2E3.js → reflection-job-XC2F7GTT.js} +1 -1
  69. package/dist/role-presets-SDA664QG.js +1 -0
  70. package/dist/role-workspace-NGJEJG3H.js +1 -0
  71. package/dist/{roles-WDMUBWQP.js → roles-LZCJ7QFS.js} +1 -1
  72. package/dist/{session-manager-XFUKWEC7.js → session-manager-PU4GH3E4.js} +1 -1
  73. package/dist/skill-registry-XKLE2LXU.js +1 -0
  74. package/dist/{task-templates-BIVCRNXA.js → task-templates-52LAC6OA.js} +1 -1
  75. package/dist/template-dispatch-PJFSWEO2.js +1 -0
  76. package/package.json +1 -1
  77. package/web/dist/assets/{ChannelDetail-D0FBZoAX.js → ChannelDetail-CSq9o5fq.js} +1 -1
  78. package/web/dist/assets/{Channels-Cztxvsa2.js → Channels-CAxTh1Bp.js} +1 -1
  79. package/web/dist/assets/Chat-PUz41HFr.js +2 -0
  80. package/web/dist/assets/{Cost-K8-4xqBe.js → Cost-BHcsPz5T.js} +1 -1
  81. package/web/dist/assets/{Dashboard-BXqFb_Vr.js → Dashboard-BT39_iWc.js} +1 -1
  82. package/web/dist/assets/{EnvVarEditor-FiiJazzp.js → EnvVarEditor-D_1d7bTJ.js} +1 -1
  83. package/web/dist/assets/{EventDefDetail-C3S1G0K8.js → EventDefDetail-jKN3gO_7.js} +1 -1
  84. package/web/dist/assets/{Events-BKxqZ9j6.js → Events-CpeHg3fh.js} +1 -1
  85. package/web/dist/assets/{Evolution-DFcSm6Rw.js → Evolution-DsWyv2_a.js} +1 -1
  86. package/web/dist/assets/{ExtensionDetail-C8aPpyLv.js → ExtensionDetail-CJHNaNii.js} +1 -1
  87. package/web/dist/assets/{Extensions-MLZk05j0.js → Extensions-Pg2vx_ZK.js} +1 -1
  88. package/web/dist/assets/{FeatureRequests-D_4XaQ7F.js → FeatureRequests-3Yl8wTNT.js} +1 -1
  89. package/web/dist/assets/{GoalDetail-DVU7c0aR.js → GoalDetail-L3T1zqqs.js} +1 -1
  90. package/web/dist/assets/{Goals-D3h4WMjU.js → Goals-B-__r-Yq.js} +1 -1
  91. package/web/dist/assets/{Logs-D5MQv6Yw.js → Logs-CMkjUkmu.js} +1 -1
  92. package/web/dist/assets/{Memories-Dls71I2i.js → Memories-Q1eKfPQ2.js} +1 -1
  93. package/web/dist/assets/{Mistakes-BZcTg0vP.js → Mistakes-BROkixt_.js} +1 -1
  94. package/web/dist/assets/{Plugins-CwCHGzI6.js → Plugins-v17MyPVe.js} +1 -1
  95. package/web/dist/assets/{RoleDetail-B2M6ALSl.js → RoleDetail-DCGFBLP1.js} +2 -2
  96. package/web/dist/assets/{Roles-FEHqm_Jf.js → Roles-C7SNebvY.js} +1 -1
  97. package/web/dist/assets/{Settings-rdVQMfqX.js → Settings-QuKwKbKg.js} +1 -1
  98. package/web/dist/assets/{Strategies-CwJ9JQ-X.js → Strategies-CXQYvCkc.js} +1 -1
  99. package/web/dist/assets/{Switch-1JjR4Imr.js → Switch--h1rqagh.js} +1 -1
  100. package/web/dist/assets/{TaskDetail-h12WxjfG.js → TaskDetail-B0G5ZjDD.js} +1 -1
  101. package/web/dist/assets/{Work-CfzFRSZX.js → Work-DbFst_9-.js} +1 -1
  102. package/web/dist/assets/index-D35OGE0z.css +2 -0
  103. package/web/dist/assets/{index-CXEJd-0s.js → index-Dd3NDYZR.js} +2 -2
  104. package/web/dist/assets/{usePluginsWithUsage-4iLJAPjH.js → usePluginsWithUsage-DpTxJuFQ.js} +1 -1
  105. package/web/dist/index.html +2 -2
  106. package/dist/approval-handler-BWA7UIKN.js +0 -1
  107. package/dist/audit-diagnostics-K3LUWXTI.js +0 -1
  108. package/dist/audit-manager-6WL2V6JG.js +0 -1
  109. package/dist/bree-engine-KYD4GKQK.js +0 -1
  110. package/dist/channels-PWDSTYNR.js +0 -1
  111. package/dist/chat-tool-calls-WJDFQ54U.js +0 -1
  112. package/dist/chunk-3UFEOB6P.js +0 -143
  113. package/dist/chunk-MTRLUW7Z.js +0 -1
  114. package/dist/chunk-QTGAK62Z.js +0 -14
  115. package/dist/chunk-TWOJVEO7.js +0 -32
  116. package/dist/chunk-VO24C673.js +0 -1
  117. package/dist/chunk-VPMHZJS2.js +0 -1
  118. package/dist/chunk-ZJ3TS4FL.js +0 -182
  119. package/dist/config-X7A6NA73.js +0 -1
  120. package/dist/db-XODNIJSJ.js +0 -1
  121. package/dist/engine-OQXDHA2R.js +0 -1
  122. package/dist/execution-tools-BR4T4MMW.js +0 -1
  123. package/dist/memory-service-3RLVOF2C.js +0 -1
  124. package/dist/outbound-gateway-NJNSN2ZX.js +0 -1
  125. package/dist/presets-SUJRFRJC.js +0 -1
  126. package/dist/role-presets-VEYTGYA4.js +0 -1
  127. package/dist/role-workspace-AIVHPX5P.js +0 -1
  128. package/dist/skill-registry-LARMNUT5.js +0 -1
  129. package/dist/template-dispatch-6FPJQN6A.js +0 -1
  130. package/web/dist/assets/Chat-Ce72TtUi.js +0 -2
  131. package/web/dist/assets/index-CarTGiGO.css +0 -2
@@ -0,0 +1 @@
1
+ import{c as a,d as b,e as c,f as d,g as e}from"./chunk-76MMY2XC.js";import"./chunk-IAGTZGGV.js";import"./chunk-DRS5NOAA.js";import"./chunk-VZL2DGC4.js";import"./chunk-YEGUFMLJ.js";import"./chunk-4G4CKAXY.js";import"./chunk-L4APYD5A.js";import"./chunk-ORFLN4BF.js";import"./chunk-L7JP7DUO.js";import"./chunk-WG3C43QS.js";import"./chunk-EBZCHLYS.js";import"./chunk-CN5NEJXG.js";import"./chunk-J2VSAXVU.js";import"./chunk-3MROEPGR.js";import"./chunk-6GYNUTPP.js";import"./chunk-LMQPGVM7.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";export{b as formatPlanForChannel,e as getPendingApprovalRequestIds,d as handleInboundForApproval,a as parseApprovalReply,c as sendApprovalToChannel};
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r}from"./chunk-BE653A45.js";import"./chunk-WY5BOCQP.js";import"./chunk-VO24C673.js";import"./chunk-EZLBMUQD.js";import"./chunk-5PELJRUQ.js";r();export{n as appendArtifactToCollection,o as convertPrimaryFileToCollectionInTransaction,a as createArtifact,j as deleteArtifactById,h as deleteArtifactsByExecution,i as deleteArtifactsByExecutionAndStep,m as ensureUniqueArtifactKey,b as getArtifact,c as getArtifactById,l as isArtifactCollectionManifest,q as listArtifacts,f as listArtifactsByChatSession,d as listArtifactsByExecution,g as listArtifactsByRole,e as listArtifactsByTask,p as listExpiredExecutions,k as removeArtifact};
1
+ import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r}from"./chunk-6GYNUTPP.js";import"./chunk-LMQPGVM7.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5PELJRUQ.js";r();export{n as appendArtifactToCollection,o as convertPrimaryFileToCollectionInTransaction,a as createArtifact,j as deleteArtifactById,h as deleteArtifactsByExecution,i as deleteArtifactsByExecutionAndStep,m as ensureUniqueArtifactKey,b as getArtifact,c as getArtifactById,l as isArtifactCollectionManifest,q as listArtifacts,f as listArtifactsByChatSession,d as listArtifactsByExecution,g as listArtifactsByRole,e as listArtifactsByTask,p as listExpiredExecutions,k as removeArtifact};
@@ -0,0 +1 @@
1
+ import{a,b,d as c}from"./chunk-4G4CKAXY.js";import"./chunk-LMQPGVM7.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";c();export{b as listAuditDiagnostics,a as recordAuditDiagnostic};
@@ -0,0 +1 @@
1
+ import{M as a,N as b,O as c,P as d,Q as e,R as f,S as g}from"./chunk-NKS7LEA7.js";import"./chunk-QMW7VEPC.js";import"./chunk-R7Q6FSV4.js";import"./chunk-QJXV4SQE.js";import"./chunk-EPLSB63A.js";import"./chunk-KM4EFB4N.js";import"./chunk-A3YUIWLK.js";import"./chunk-WDMSZS4W.js";import"./chunk-DRS5NOAA.js";import"./chunk-DFTRUOT6.js";import"./chunk-MMVDXKYS.js";import"./chunk-FQHGIY3E.js";import"./chunk-2JM3URDG.js";import"./chunk-L4APYD5A.js";import"./chunk-GQS3ED3B.js";import"./chunk-ORFLN4BF.js";import"./chunk-L7JP7DUO.js";import"./chunk-HEHST2E2.js";import"./chunk-PO66F7UQ.js";import"./chunk-4ZG4UMAK.js";import"./chunk-T2Z2JDPY.js";import"./chunk-FN64ZULV.js";import"./chunk-WG3C43QS.js";import"./chunk-AUSR5JYV.js";import"./chunk-CN5NEJXG.js";import"./chunk-J2VSAXVU.js";import"./chunk-3MROEPGR.js";import"./chunk-6GYNUTPP.js";import"./chunk-LMQPGVM7.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";export{e as auditAssistantCommitment,f as auditDeliveryClaims,a as evaluateTaskCompletion,g as getSecurityPosture,d as reportViolation,b as startAuditManager,c as stopAuditManager};
@@ -0,0 +1 @@
1
+ import{a,b,c}from"./chunk-7QT2ZX3K.js";import"./chunk-KQMKRRYW.js";import"./chunk-R7Q6FSV4.js";import"./chunk-QJXV4SQE.js";import"./chunk-EPLSB63A.js";import"./chunk-KM4EFB4N.js";import"./chunk-4ZESWP3J.js";import"./chunk-4N5G7ND2.js";import"./chunk-WDMSZS4W.js";import"./chunk-NNMQGISW.js";import"./chunk-IAGTZGGV.js";import"./chunk-DRS5NOAA.js";import"./chunk-VZL2DGC4.js";import"./chunk-YEGUFMLJ.js";import"./chunk-4G4CKAXY.js";import"./chunk-FQHGIY3E.js";import"./chunk-2JM3URDG.js";import"./chunk-L4APYD5A.js";import"./chunk-GQS3ED3B.js";import"./chunk-ORFLN4BF.js";import"./chunk-L7JP7DUO.js";import"./chunk-T2Z2JDPY.js";import"./chunk-FN64ZULV.js";import"./chunk-WG3C43QS.js";import"./chunk-EBZCHLYS.js";import"./chunk-CN5NEJXG.js";import"./chunk-T7EKW3B7.js";import"./chunk-J2VSAXVU.js";import"./chunk-JRRNGKDK.js";import"./chunk-3MROEPGR.js";import"./chunk-6GYNUTPP.js";import"./chunk-LMQPGVM7.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";export{a as BreeEngine,b as getBreeEngine,c as setBreeEngine};
@@ -0,0 +1 @@
1
+ import{i as a,j as b,k as c}from"./chunk-JXZCQ5XW.js";import"./chunk-WDMSZS4W.js";import"./chunk-NNMQGISW.js";import"./chunk-VZL2DGC4.js";import"./chunk-YEGUFMLJ.js";import"./chunk-4G4CKAXY.js";import"./chunk-EBZCHLYS.js";import"./chunk-J2VSAXVU.js";import"./chunk-3MROEPGR.js";import"./chunk-LMQPGVM7.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";export{c as channelRoutes,b as getChannelManager,a as setChannelManager};
@@ -1 +1 @@
1
- import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h}from"./chunk-6WQFYV3N.js";import"./chunk-WY5BOCQP.js";import"./chunk-VO24C673.js";import"./chunk-EZLBMUQD.js";import"./chunk-5PELJRUQ.js";export{a as createChannel,e as deleteChannel,b as getChannel,g as getRecipientCap,d as listChannels,h as setRecipientCap,c as updateChannel,f as updateChannelStatus};
1
+ import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h}from"./chunk-EBZCHLYS.js";import"./chunk-LMQPGVM7.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5PELJRUQ.js";export{a as createChannel,e as deleteChannel,b as getChannel,g as getRecipientCap,d as listChannels,h as setRecipientCap,c as updateChannel,f as updateChannelStatus};
@@ -0,0 +1 @@
1
+ import{a,b,c}from"./chunk-VOH52UDS.js";import"./chunk-LMQPGVM7.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5PELJRUQ.js";export{c as hasAnyToolCallInTurn,b as listChatToolCallsByTrace,a as recordChatToolCall};
@@ -1,4 +1,4 @@
1
- import{n as e,p as i}from"./chunk-WY5BOCQP.js";import{c as o,e as d}from"./chunk-5M6IGE5G.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(`
1
+ import{o as e,q as i}from"./chunk-LMQPGVM7.js";import{c as o,e as d}from"./chunk-5M6IGE5G.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
2
  INSERT INTO step_logs (id, task_id, "index", type, content, tool_name,
3
3
  tool_input, tool_output, truncated, timestamp, token_usage, plan_step_index, trace_id)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -1,4 +1,4 @@
1
- import{n as r,p as n}from"./chunk-WY5BOCQP.js";import{c,e as u}from"./chunk-5M6IGE5G.js";import{b as d,c as o}from"./chunk-5PELJRUQ.js";var D={};o(D,{listAuditDiagnostics:()=>A,recordAuditDiagnostic:()=>g});import{v4 as a}from"uuid";function g(e){let t={id:a(),source:e.source,severity:e.severity,traceId:e.traceId??c()??void 0,sourceId:e.sourceId,message:e.message,createdAt:e.createdAt??Date.now()};return r().prepare(`
1
+ import{o as r,q as n}from"./chunk-LMQPGVM7.js";import{c,e as u}from"./chunk-5M6IGE5G.js";import{b as d,c as o}from"./chunk-5PELJRUQ.js";var D={};o(D,{listAuditDiagnostics:()=>A,recordAuditDiagnostic:()=>g});import{v4 as a}from"uuid";function g(e){let t={id:a(),source:e.source,severity:e.severity,traceId:e.traceId??c()??void 0,sourceId:e.sourceId,message:e.message,createdAt:e.createdAt??Date.now()};return r().prepare(`
2
2
  INSERT INTO audit_diagnostics (id, source, severity, trace_id, source_id, message, created_at)
3
3
  VALUES (?, ?, ?, ?, ?, ?, ?)
4
4
  `).run(t.id,t.source,t.severity,t.traceId??null,t.sourceId??null,t.message,t.createdAt),t}function A(e={}){let t=[],i=[];e.source&&(t.push("source = ?"),i.push(e.source)),e.traceId&&(t.push("trace_id = ?"),i.push(e.traceId));let s="SELECT * FROM audit_diagnostics";return t.length>0&&(s+=` WHERE ${t.join(" AND ")}`),s+=" ORDER BY created_at DESC",e.limit!==void 0&&(s+=" LIMIT ?",i.push(e.limit)),r().prepare(s).all(...i).map(m)}function m(e){return{id:e.id,source:e.source,severity:e.severity,traceId:e.trace_id??void 0,sourceId:e.source_id??void 0,message:e.message,createdAt:e.created_at}}var I=d(()=>{n();u()});export{g as a,A as b,D as c,I as d};
@@ -1 +1 @@
1
- import{c as x,e as C}from"./chunk-IEBAOZED.js";import{a as y,b as u,c,d as m,e as h,g as v}from"./chunk-TA5PFK5C.js";import{a as i}from"./chunk-L7JP7DUO.js";import{b as l}from"./chunk-T2Z2JDPY.js";import{a as g}from"./chunk-V2MMQ3SH.js";import{e as f}from"./chunk-47HJPIUA.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=x(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 p=r.content.slice(0,500),S;try{S=await l(p)}catch{}let M=$(p),T={id:I(),roleId:t,type:r.type,content:p,embedding:S,keywords:M,importance:r.importance,sourceType:"session_archive",createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"episodic"};g(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 V(e,t){let s=Date.now(),o={id:D(),status:"active",source:e,createdAt:s,lastActiveAt:s,messageCount:0};return y(o),n.set(o.id,o),i.emit({type:"session_created",session:o}),o}function W(e){for(let s of n.values())if(w(s.source)===w(e))return s;let t=h(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}),f().archiveExtractMemory&&u(e)&&A(e,"role-chat-manager").catch(()=>{}),n.delete(e),i.emit({type:"session_archived",sessionId:e})}function X(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 Y(e){C(e),v(e),n.delete(e),i.emit({type:"session_deleted",sessionId:e})}function Z(e){let t=Date.now();c(e,{lastActiveAt:t});let s=n.get(e);s&&(s.lastActiveAt=t)}function ee(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 te(e){return m(e)}function P(){let t=f().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 se(){return a}function oe(){F(),R()}function ne(){d(),n.clear()}function re(){d(),n.clear()}export{F as a,V as b,W as c,B as d,E as e,X as f,Y as g,Z as h,ee as i,te as j,R as k,d as l,se as m,oe as n,ne as o,re as p};
1
+ import{c as x,e as C}from"./chunk-WDMSZS4W.js";import{a as y,b as u,c,d as m,e as h,g as v}from"./chunk-YEGUFMLJ.js";import{a as i}from"./chunk-L7JP7DUO.js";import{b as l}from"./chunk-T2Z2JDPY.js";import{a as g}from"./chunk-FN64ZULV.js";import{e as f}from"./chunk-T7EKW3B7.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=x(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 p=r.content.slice(0,500),S;try{S=await l(p)}catch{}let M=$(p),T={id:I(),roleId:t,type:r.type,content:p,embedding:S,keywords:M,importance:r.importance,sourceType:"session_archive",createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"episodic"};g(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 V(e,t){let s=Date.now(),o={id:D(),status:"active",source:e,createdAt:s,lastActiveAt:s,messageCount:0};return y(o),n.set(o.id,o),i.emit({type:"session_created",session:o}),o}function W(e){for(let s of n.values())if(w(s.source)===w(e))return s;let t=h(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}),f().archiveExtractMemory&&u(e)&&A(e,"role-chat-manager").catch(()=>{}),n.delete(e),i.emit({type:"session_archived",sessionId:e})}function X(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 Y(e){C(e),v(e),n.delete(e),i.emit({type:"session_deleted",sessionId:e})}function Z(e){let t=Date.now();c(e,{lastActiveAt:t});let s=n.get(e);s&&(s.lastActiveAt=t)}function ee(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 te(e){return m(e)}function P(){let t=f().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 se(){return a}function oe(){F(),R()}function ne(){d(),n.clear()}function re(){d(),n.clear()}export{F as a,V as b,W as c,B as d,E as e,X as f,Y as g,Z as h,ee as i,te as j,R as k,d as l,se as m,oe as n,ne as o,re as p};
@@ -1,4 +1,4 @@
1
- import{h as c}from"./chunk-V2MMQ3SH.js";import{K as u,L as p}from"./chunk-2A2TXYT3.js";import{n as s,p as f}from"./chunk-WY5BOCQP.js";f();p();function r(e){return{id:e.id,roleId:e.role_id,content:e.content,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,scopeKey:e.scope_key??void 0,status:e.status,successEma:e.success_ema??void 0,injectCount:e.inject_count??0}}function _(e){return Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function g(e){let t=s(),n=e.lastUsedAt??u(e.roleId);t.prepare(`
1
+ import{h as c}from"./chunk-FN64ZULV.js";import{K as u,L as p}from"./chunk-WG3C43QS.js";import{o as s,q as f}from"./chunk-LMQPGVM7.js";f();p();function r(e){return{id:e.id,roleId:e.role_id,content:e.content,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,scopeKey:e.scope_key??void 0,status:e.status,successEma:e.success_ema??void 0,injectCount:e.inject_count??0}}function _(e){return Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function g(e){let t=s(),n=e.lastUsedAt??u(e.roleId);t.prepare(`
2
2
  INSERT INTO beliefs (id, role_id, content,
3
3
  is_anti, evidence_obs_ids, embedding, superseded_by,
4
4
  created_at, last_used_at, last_validated_at,
@@ -1,4 +1,4 @@
1
- import{n as o,p as k}from"./chunk-WY5BOCQP.js";import{b}from"./chunk-5PELJRUQ.js";import{basename as S}from"path";import{v4 as x}from"uuid";function u(t){return{id:t.id,sourceKind:t.source_kind,executionId:t.execution_id??void 0,taskId:t.task_id??void 0,chatSessionId:t.chat_session_id??void 0,stepId:t.step_id??void 0,roleId:t.role_id??void 0,key:t.key??void 0,kind:t.kind,value:t.value_json?JSON.parse(t.value_json):void 0,blobPath:t.blob_path??void 0,mime:t.mime??void 0,originalFilename:t.original_filename??void 0,sizeBytes:t.size_bytes,createdAt:t.created_at,locator:t.locator??void 0,contentHash:t.content_hash??void 0,retentionHint:t.retention_hint??void 0,encryptionClass:t.encryption_class??void 0,purpose:t.purpose??void 0,replaces:t.replaces??void 0,producedByRole:t.produced_by_role??void 0,access:t.access??void 0,priority:t.priority??void 0,artifactRole:t.artifact_role??void 0}}function w(t){if(!t.roleId||t.roleId.trim()==="")throw new Error("createArtifact: roleId required (application-layer enforcement)");p(o(),t)}function p(t,e){t.prepare(`
1
+ import{o,q as k}from"./chunk-LMQPGVM7.js";import{b}from"./chunk-5PELJRUQ.js";import{basename as S}from"path";import{v4 as x}from"uuid";function u(t){return{id:t.id,sourceKind:t.source_kind,executionId:t.execution_id??void 0,taskId:t.task_id??void 0,chatSessionId:t.chat_session_id??void 0,stepId:t.step_id??void 0,roleId:t.role_id??void 0,key:t.key??void 0,kind:t.kind,value:t.value_json?JSON.parse(t.value_json):void 0,blobPath:t.blob_path??void 0,mime:t.mime??void 0,originalFilename:t.original_filename??void 0,sizeBytes:t.size_bytes,createdAt:t.created_at,locator:t.locator??void 0,contentHash:t.content_hash??void 0,retentionHint:t.retention_hint??void 0,encryptionClass:t.encryption_class??void 0,purpose:t.purpose??void 0,replaces:t.replaces??void 0,producedByRole:t.produced_by_role??void 0,access:t.access??void 0,priority:t.priority??void 0,artifactRole:t.artifact_role??void 0}}function w(t){if(!t.roleId||t.roleId.trim()==="")throw new Error("createArtifact: roleId required (application-layer enforcement)");p(o(),t)}function p(t,e){t.prepare(`
2
2
  INSERT INTO artifacts (
3
3
  id, source_kind, execution_id, task_id, chat_session_id, step_id, role_id,
4
4
  key, kind, value_json, blob_path, mime, original_filename, size_bytes, created_at,
@@ -1,4 +1,4 @@
1
- import{g as y}from"./chunk-TWOJVEO7.js";import{c as m}from"./chunk-6WQFYV3N.js";import{c as h,h as w}from"./chunk-EZLBMUQD.js";w();var v="",I=Buffer.alloc(0);function O(o){v=o,I=Buffer.from(o)}function g(){return v}function C(){return I}var p=h("channels"),u=new Map,x=3e5,$=new Set(["telegram"]);function T(o){let e=o.trim().toLowerCase().match(/^(yes|y|是|允许|no|n|否|拒绝)\s+(\S+)$/);if(!e)return null;let[,c,l]=e,r=["yes","y","\u662F","\u5141\u8BB8"].includes(c);return{requestId:l,decision:r?"allow":"deny"}}function P(o){let n=m(o);return n?$.has(n.platform):!1}var b={low:"\u{1F7E2}",medium:"\u{1F7E1}",high:"\u{1F534}"},k={low:"\u4F4E",medium:"\u4E2D",high:"\u9AD8"};function _(o){let n=["\u{1F512} \u9700\u8981\u5BA1\u6279",""];for(let e of o.steps){if(e.description.startsWith("Execute task without OS sandbox"))n.push("\u26A0\uFE0F \u65E0\u6C99\u7BB1\u6267\u884C \u2014 \u6587\u4EF6\u7CFB\u7EDF\u9694\u79BB\u672A\u542F\u7528");else{let r=e.description.indexOf(": "),s=r>0?e.description.slice(0,r):"Operation";if(n.push(`\u64CD\u4F5C: ${s}`),s==="Bash"&&r>0)try{let t=JSON.parse(e.description.slice(r+2));if(t.command){let i=String(t.command).trim();n.push(`\u547D\u4EE4: ${i.length>120?i.slice(0,117)+"...":i}`)}}catch{let t=e.description.slice(r+2,r+122);n.push(`\u8BE6\u60C5: ${t}${e.description.length>r+122?"...":""}`)}else if(r>0){let t=e.description.slice(r+2,r+122);n.push(`\u8BE6\u60C5: ${t}${e.description.length>r+122?"...":""}`)}}let c=b[e.riskLevel]??"\u{1F7E1}",l=k[e.riskLevel]??e.riskLevel;n.push(`\u98CE\u9669: ${c} ${l}`),n.push("")}return n.join(`
1
+ import{j as y}from"./chunk-IAGTZGGV.js";import{c as m}from"./chunk-EBZCHLYS.js";import{c as h,h as w}from"./chunk-EZLBMUQD.js";w();var v="",I=Buffer.alloc(0);function O(o){v=o,I=Buffer.from(o)}function g(){return v}function C(){return I}var p=h("channels"),u=new Map,x=3e5,$=new Set(["telegram"]);function T(o){let e=o.trim().toLowerCase().match(/^(yes|y|是|允许|no|n|否|拒绝)\s+(\S+)$/);if(!e)return null;let[,c,l]=e,r=["yes","y","\u662F","\u5141\u8BB8"].includes(c);return{requestId:l,decision:r?"allow":"deny"}}function P(o){let n=m(o);return n?$.has(n.platform):!1}var b={low:"\u{1F7E2}",medium:"\u{1F7E1}",high:"\u{1F534}"},k={low:"\u4F4E",medium:"\u4E2D",high:"\u9AD8"};function _(o){let n=["\u{1F512} \u9700\u8981\u5BA1\u6279",""];for(let e of o.steps){if(e.description.startsWith("Execute task without OS sandbox"))n.push("\u26A0\uFE0F \u65E0\u6C99\u7BB1\u6267\u884C \u2014 \u6587\u4EF6\u7CFB\u7EDF\u9694\u79BB\u672A\u542F\u7528");else{let r=e.description.indexOf(": "),s=r>0?e.description.slice(0,r):"Operation";if(n.push(`\u64CD\u4F5C: ${s}`),s==="Bash"&&r>0)try{let t=JSON.parse(e.description.slice(r+2));if(t.command){let i=String(t.command).trim();n.push(`\u547D\u4EE4: ${i.length>120?i.slice(0,117)+"...":i}`)}}catch{let t=e.description.slice(r+2,r+122);n.push(`\u8BE6\u60C5: ${t}${e.description.length>r+122?"...":""}`)}else if(r>0){let t=e.description.slice(r+2,r+122);n.push(`\u8BE6\u60C5: ${t}${e.description.length>r+122?"...":""}`)}}let c=b[e.riskLevel]??"\u{1F7E1}",l=k[e.riskLevel]??e.riskLevel;n.push(`\u98CE\u9669: ${c} ${l}`),n.push("")}return n.join(`
2
2
  `).trimEnd()}async function q(o,n,e,c,l,r=x){let s=e,t=s.slice(0,8);u.set(t,{planId:e,taskId:c,channelId:o,chatId:n,requestId:s,timestamp:Date.now(),timeoutMs:r});let i=y(),d=P(o);if(d){let a=`${l}
3
3
 
4
4
  `;await i.send({channelId:o,chatId:n,content:a,messageType:"approval",replyMarkup:{inlineKeyboard:[[{text:"\u2705 Allow",callbackData:`yes ${t}`},{text:"\u274C Deny",callbackData:`no ${t}`}]]}})}else{let a=[l,"",`Reply 'yes ${t}' or 'no ${t}'`].join(`
@@ -1 +1 @@
1
- import{s as b}from"./chunk-3UFEOB6P.js";import{s,u as m,w as x}from"./chunk-VWX2B6OM.js";import{a as p}from"./chunk-L7JP7DUO.js";import{q as T}from"./chunk-V2MMQ3SH.js";import{G as f,L as J}from"./chunk-2A2TXYT3.js";import{c as h,h as C}from"./chunk-EZLBMUQD.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};
1
+ import{t as b}from"./chunk-KQMKRRYW.js";import{s,u as m,w as x}from"./chunk-ORFLN4BF.js";import{a as p}from"./chunk-L7JP7DUO.js";import{q as T}from"./chunk-FN64ZULV.js";import{G as f,L as J}from"./chunk-WG3C43QS.js";import{c as h,h as C}from"./chunk-EZLBMUQD.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};
@@ -1,4 +1,4 @@
1
- import{n as o,p as a}from"./chunk-WY5BOCQP.js";import{c as u,e as c}from"./chunk-5M6IGE5G.js";a();c();import{v4 as p}from"uuid";function R(t){o().prepare(`
1
+ import{o,q as a}from"./chunk-LMQPGVM7.js";import{c as u,e as c}from"./chunk-5M6IGE5G.js";a();c();import{v4 as p}from"uuid";function R(t){o().prepare(`
2
2
  INSERT INTO evolution_audit (id, timestamp, old_rules, new_rules, diff, trigger_task_id, role_id, source, trace_id)
3
3
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
4
4
  `).run(p(),t.timestamp,t.oldRules,t.newRules,t.diff,t.triggerTaskId??null,t.roleId??null,t.source??"reflection",t.traceId??u()??null)}function _(t=100,e=0){return o().prepare(`
@@ -1 +1 @@
1
- import{d as w,h as S}from"./chunk-VO24C673.js";import{c as g,h as P}from"./chunk-EZLBMUQD.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,i as S}from"./chunk-ITVCPC7G.js";import{c as g,h as P}from"./chunk-EZLBMUQD.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,2 +1,2 @@
1
- import{n as r,p as s}from"./chunk-WY5BOCQP.js";import{b as i}from"./chunk-5PELJRUQ.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{o as r,q as s}from"./chunk-LMQPGVM7.js";import{b as i}from"./chunk-5PELJRUQ.js";function p(e){let n=r().prepare("SELECT value FROM config WHERE key = ?").get(e);if(n)try{return JSON.parse(n.value)}catch{return n.value}}function E(e,t){let n=r(),o=JSON.stringify(t),u=Date.now();n.prepare(`INSERT INTO config (key, value, updated_at) VALUES (?, ?, ?)
2
2
  ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`).run(e,o,u)}function k(){let t=r().prepare("SELECT key, value FROM config").all(),n={};for(let o of t)try{n[o.key]=JSON.parse(o.value)}catch{n[o.key]=o.value}return n}function b(e){let t=r(),n=t.prepare("INSERT OR IGNORE INTO config (key, value, updated_at) VALUES (?, ?, ?)"),o=Date.now(),u=0;return t.transaction(()=>{for(let[c,a]of Object.entries(e)){if(a==null||a==="")continue;n.run(c,JSON.stringify(a),o).changes>0&&u++}})(),u}function w(){return r().prepare("SELECT COUNT(*) as count FROM config").get().count===0}function O(e){return r().prepare("DELETE FROM config WHERE key = ?").run(e).changes>0}var d=i(()=>{s()});export{p as a,E as b,k as c,b as d,w as e,O as f,d as g};
@@ -1,4 +1,4 @@
1
- import{g}from"./chunk-QTGAK62Z.js";import{f as T,i as K}from"./chunk-NSUXJ2VA.js";import{r as _,t as E,u as f}from"./chunk-VWX2B6OM.js";import{C as R,D as A,E as c,F as x,G as C,L as z}from"./chunk-2A2TXYT3.js";import{b as U,c as Y,d as H}from"./chunk-5PELJRUQ.js";var L={};Y(L,{seedAdamAutomatorSkills:()=>J});async function J(t){let{ensureRoleWorkspace:r}=await import("./role-workspace-AIVHPX5P.js"),{getRole:e}=await import("./roles-WDMUBWQP.js"),{mkdir:a,readFile:n,writeFile:o,access:s}=await import("fs/promises"),{join:l}=await import("path"),d=e(t);if(!d)throw new Error(`Role '${t}' not found`);let u=r(d),m=l(u,".claude","skills");await a(m,{recursive:!0});let i=[{name:"aggregate_feature",description:"Aggregate a feature value over a window",inputs:[{name:"feature_name",desc:"Name of the feature to aggregate"},{name:"aggregation",desc:"Aggregation type: sum | avg | count | latest"},{name:"window_days",desc:"Number of days to look back"},{name:"field",desc:"Event payload field to aggregate"}],body:"Query events via sqlite3, compute aggregation, print numeric result."},{name:"check_threshold",description:"Compare a value vs threshold, emit breach if exceeded",inputs:[{name:"feature",desc:"Feature value (number)"},{name:"operator",desc:"Comparison operator: gt | gte | lt | lte | eq"},{name:"threshold",desc:"Threshold value"},{name:"on_breach_type",desc:"Event type to emit on breach"},{name:"on_breach_payload",desc:"JSON payload for breach event"}],body:"Read feature value, compare against threshold using the operator. On breach, emit new event via emit_event Skill."},{name:"query_events",description:"Range-query events table",inputs:[{name:"type_pattern",desc:"Event type pattern (e.g. 'scheduler.tick')"},{name:"window",desc:"Lookback window in hours"},{name:"limit",desc:"Maximum number of events to return"}],body:"sqlite3 parameterized query against the events table, returning matching rows as JSON."},{name:"query_state",description:"Read latest state_snapshot (not yet available)",inputs:[{name:"select",desc:"Dot-notation path to select (e.g. 'goals.active')"}],body:`Returns { state: null, available: false } \u2014 state_snapshot table not yet built (deferred to Phase 2).
1
+ import{g}from"./chunk-MMVDXKYS.js";import{f as T,i as K}from"./chunk-GQS3ED3B.js";import{r as _,t as E,u as f}from"./chunk-ORFLN4BF.js";import{C as R,D as A,E as c,F as x,G as C,L as z}from"./chunk-WG3C43QS.js";import{b as U,c as Y,d as H}from"./chunk-5PELJRUQ.js";var L={};Y(L,{seedAdamAutomatorSkills:()=>J});async function J(t){let{ensureRoleWorkspace:r}=await import("./role-workspace-NGJEJG3H.js"),{getRole:e}=await import("./roles-LZCJ7QFS.js"),{mkdir:a,readFile:n,writeFile:o,access:s}=await import("fs/promises"),{join:l}=await import("path"),d=e(t);if(!d)throw new Error(`Role '${t}' not found`);let u=r(d),m=l(u,".claude","skills");await a(m,{recursive:!0});let i=[{name:"aggregate_feature",description:"Aggregate a feature value over a window",inputs:[{name:"feature_name",desc:"Name of the feature to aggregate"},{name:"aggregation",desc:"Aggregation type: sum | avg | count | latest"},{name:"window_days",desc:"Number of days to look back"},{name:"field",desc:"Event payload field to aggregate"}],body:"Query events via sqlite3, compute aggregation, print numeric result."},{name:"check_threshold",description:"Compare a value vs threshold, emit breach if exceeded",inputs:[{name:"feature",desc:"Feature value (number)"},{name:"operator",desc:"Comparison operator: gt | gte | lt | lte | eq"},{name:"threshold",desc:"Threshold value"},{name:"on_breach_type",desc:"Event type to emit on breach"},{name:"on_breach_payload",desc:"JSON payload for breach event"}],body:"Read feature value, compare against threshold using the operator. On breach, emit new event via emit_event Skill."},{name:"query_events",description:"Range-query events table",inputs:[{name:"type_pattern",desc:"Event type pattern (e.g. 'scheduler.tick')"},{name:"window",desc:"Lookback window in hours"},{name:"limit",desc:"Maximum number of events to return"}],body:"sqlite3 parameterized query against the events table, returning matching rows as JSON."},{name:"query_state",description:"Read latest state_snapshot (not yet available)",inputs:[{name:"select",desc:"Dot-notation path to select (e.g. 'goals.active')"}],body:`Returns { state: null, available: false } \u2014 state_snapshot table not yet built (deferred to Phase 2).
2
2
 
3
3
  When the state_snapshot table is available, this Skill will query it for the latest snapshot matching the select path and return the value.`},{name:"query_goals",description:"Read active goals (goal_graph_nodes not built)",inputs:[{name:"types",desc:"Goal type filter (e.g. 'daily|weekly')"},{name:"status",desc:"Goal status filter: active | completed | paused"}],body:`Returns { goals: [], available: false } \u2014 goal_graph_nodes table not yet built (deferred to Phase 2).
4
4
 
@@ -1,4 +1,4 @@
1
- import{n as s,p as d}from"./chunk-WY5BOCQP.js";import{c as l,e as u}from"./chunk-5M6IGE5G.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(`
1
+ import{o as s,q as d}from"./chunk-LMQPGVM7.js";import{c as l,e as u}from"./chunk-5M6IGE5G.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
2
  INSERT INTO delivery_log (id, rule_id, task_id, execution_id, status, target, content,
3
3
  attempts, error, created_at, delivered_at, expires_at, source, message_type, trace_id)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -1,4 +1,4 @@
1
- import{n as s,p as m}from"./chunk-WY5BOCQP.js";import{c as d,h as f}from"./chunk-EZLBMUQD.js";m();f();var p=/^[a-z0-9.-]+$/;var u=d("store");function r(e){let n;if(e.recipient_cap_map_json)try{n=JSON.parse(e.recipient_cap_map_json)}catch(i){u.warn({channelId:e.id,err:i},"Malformed recipient_cap_map_json; using empty map"),n=void 0}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,recipientCapMap:n,defaultRecipientCapBytes:e.default_recipient_cap_bytes??void 0}}function R(e){s().prepare(`
1
+ import{o as s,q as m}from"./chunk-LMQPGVM7.js";import{c as d,h as f}from"./chunk-EZLBMUQD.js";m();f();var p=/^[a-z0-9.-]+$/;var u=d("store");function r(e){let n;if(e.recipient_cap_map_json)try{n=JSON.parse(e.recipient_cap_map_json)}catch(i){u.warn({channelId:e.id,err:i},"Malformed recipient_cap_map_json; using empty map"),n=void 0}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,recipientCapMap:n,defaultRecipientCapBytes:e.default_recipient_cap_bytes??void 0}}function R(e){s().prepare(`
2
2
  INSERT INTO channels (id, name, platform, enabled, status, config, linked_role_id,
3
3
  allowed_chat_ids, viewer_key, created_at, updated_at, last_message_at, message_count,
4
4
  recipient_cap_map_json, default_recipient_cap_bytes)
@@ -1,4 +1,4 @@
1
- import{k as D}from"./chunk-IEBAOZED.js";import{c as L,p as K}from"./chunk-2A2TXYT3.js";import{a as M,e as E}from"./chunk-3MROEPGR.js";import{n as y,p as W}from"./chunk-WY5BOCQP.js";import{c as b,h as w}from"./chunk-EZLBMUQD.js";W();function N(m){if(m.length===0)return;let s=y(),e=s.prepare(`
1
+ import{k as D}from"./chunk-WDMSZS4W.js";import{c as L,p as K}from"./chunk-WG3C43QS.js";import{a as M,e as E}from"./chunk-3MROEPGR.js";import{o as y,q as W}from"./chunk-LMQPGVM7.js";import{c as b,h as w}from"./chunk-EZLBMUQD.js";W();function N(m){if(m.length===0)return;let s=y(),e=s.prepare(`
2
2
  INSERT OR IGNORE INTO llm_costs
3
3
  (id, call_id, source, model, role_id, task_id, session_id, message_id,
4
4
  input_tokens, output_tokens, cache_read_tokens, cache_creation_tokens,
@@ -1,4 +1,4 @@
1
- import{D as M,L as D}from"./chunk-2A2TXYT3.js";import{n as u,p as O}from"./chunk-WY5BOCQP.js";O();D();function E(e){return{id:e.id,roleId:e.role_id,type:e.type,content:e.content,embedding:e.embedding?new Float32Array(e.embedding.buffer,e.embedding.byteOffset,e.embedding.byteLength/4):void 0,keywords:e.keywords?JSON.parse(e.keywords):[],importance:e.importance,sourceType:e.source_type,sourceTaskId:e.source_task_id??void 0,evidence:e.evidence?JSON.parse(e.evidence):void 0,createdAt:e.created_at,lastAccessed:e.last_accessed,retrievedCount:e.retrieved_count,tier:e.tier,supersededBy:e.superseded_by??void 0}}function _(e){return Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function I(e){u().prepare(`
1
+ import{D as M,L as D}from"./chunk-WG3C43QS.js";import{o as u,q as O}from"./chunk-LMQPGVM7.js";O();D();function E(e){return{id:e.id,roleId:e.role_id,type:e.type,content:e.content,embedding:e.embedding?new Float32Array(e.embedding.buffer,e.embedding.byteOffset,e.embedding.byteLength/4):void 0,keywords:e.keywords?JSON.parse(e.keywords):[],importance:e.importance,sourceType:e.source_type,sourceTaskId:e.source_task_id??void 0,evidence:e.evidence?JSON.parse(e.evidence):void 0,createdAt:e.created_at,lastAccessed:e.last_accessed,retrievedCount:e.retrieved_count,tier:e.tier,supersededBy:e.superseded_by??void 0}}function _(e){return Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function I(e){u().prepare(`
2
2
  INSERT INTO memories (id, role_id, type, content, embedding, keywords,
3
3
  importance, source_type, source_task_id, evidence,
4
4
  created_at, last_accessed, retrieved_count, tier, superseded_by)
@@ -0,0 +1 @@
1
+ import{h as m,i as d}from"./chunk-L4APYD5A.js";import{c as s,h as u}from"./chunk-EZLBMUQD.js";import{c,e as f}from"./chunk-5M6IGE5G.js";f();u();var r=s("adam");function w(e){let n=e.traceIdOverride??c();if(!n){r.debug({toolName:e.toolName,entityType:e.entityType,verb:e.verb},"Mutation receipt skipped: no active trace context");return}let i={traceId:n,toolName:e.toolName,taskId:e.taskId,roleId:e.roleId};try{d({traceId:n,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:i,outcome:"success"})}catch(o){o instanceof m?r.warn({errors:o.errors,toolName:e.toolName,entityType:e.entityType},"Mutation receipt validation failed"):r.warn({error:o instanceof Error?o.message:String(o),toolName:e.toolName},"Mutation receipt write failed")}}import{z as t}from"zod";var p=t.object({kind:t.literal("lengthTarget"),min:t.number().int().nonnegative(),max:t.number().int().positive(),unit:t.enum(["characters","words","bytes"])}).refine(e=>e.min<=e.max,{message:"min must be <= max"}),g=t.object({kind:t.literal("format"),value:t.enum(["markdown","json","text"])}),k=t.object({kind:t.literal("requireHeading"),value:t.boolean()}),y=t.object({kind:t.literal("mime"),declared:t.string().regex(/^[a-z]+\/[a-z0-9.+-]+(\/)?$/i,{message:"declared must be a valid MIME type (e.g. audio/mpeg, application/json)"})}),b=t.object({kind:t.literal("fileSizeBytes"),min:t.number().int().nonnegative().optional(),max:t.number().int().positive().optional()}).refine(e=>e.min!==void 0||e.max!==void 0,{message:"at least one of min/max required"}).refine(e=>e.min===void 0||e.max===void 0||e.min<=e.max,{message:"min must be <= max"}),x=t.object({kind:t.literal("audioZeroCrossingRatePerS"),max:t.number().positive()}),I=t.object({kind:t.literal("audioDurationMs"),min:t.number().int().nonnegative().optional(),max:t.number().int().positive().optional()}).refine(e=>e.min!==void 0||e.max!==void 0,{message:"at least one of min/max required"}).refine(e=>e.min===void 0||e.max===void 0||e.min<=e.max,{message:"min must be <= max"}),C=t.discriminatedUnion("kind",[p,g,k,y,b,x,I]),M=t.array(C);function l(e){return e.kind==="lengthTarget"||e.kind==="format"||e.kind==="requireHeading"||e.kind==="mime"}function a(e){return e.outputContract?.contractRules??[]}function S(e){return a(e).some(n=>!l(n)||n.kind==="mime"&&n.declared.toLowerCase()!=="application/json")}function B(e,n){return typeof n!="string"?!1:a(e).some(i=>i.kind==="format"&&(i.value==="markdown"||i.value==="text"))}var R="ExecutionManager: SDK loop force-closed after activity timeout";function h(e){return e===R}function q(e){if(e.kind==="json"){let n=e.value;return typeof n=="object"&&n!==null&&n.status==="no_content"?!0:!(typeof n=="string"&&(n.trim().length===0||h(n)))}return e.sizeBytes>0}function P(e){return S(e)?!1:!a(e).some(n=>n.kind==="format"&&n.value==="json"||n.kind==="mime"&&n.declared.toLowerCase()==="application/json")}export{w as a,C as b,M as c,l as d,a as e,S as f,B as g,R as h,h as i,q as j,P as k};
@@ -1,4 +1,4 @@
1
- import{F as R,L as E}from"./chunk-2A2TXYT3.js";import{d as h,h as A}from"./chunk-VO24C673.js";import{c as y,h as V}from"./chunk-EZLBMUQD.js";import{b as v}from"./chunk-5PELJRUQ.js";import{readFileSync as P,writeFileSync as I,existsSync as b}from"fs";import{join as x}from"path";function k(n){let e=x(m(n),".env");if(!b(e))return null;let s=P(e,"utf-8"),r={};for(let c of s.split(`
1
+ import{F as R,L as E}from"./chunk-WG3C43QS.js";import{d as h,i as A}from"./chunk-ITVCPC7G.js";import{c as y,h as V}from"./chunk-EZLBMUQD.js";import{b as v}from"./chunk-5PELJRUQ.js";import{readFileSync as P,writeFileSync as I,existsSync as b}from"fs";import{join as x}from"path";function k(n){let e=x(m(n),".env");if(!b(e))return null;let s=P(e,"utf-8"),r={};for(let c of s.split(`
2
2
  `)){let t=c.trim();if(!t||t.startsWith("#"))continue;let i=t.startsWith("export ")?t.slice(7).trim():t,a=i.indexOf("=");if(a===-1)continue;let d=i.slice(0,a).trim(),o=i.slice(a+1).trim();(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),!(o.includes("$")&&(o=o.replace(/\$\{(\w+)\}|\$(\w+)/g,(f,l,u)=>{let g=l??u;return r[g]??process.env[g]??""}),!o))&&(r[d]=o)}return r}function W(n,e){let s=k(n);if(!s)return e;let r={...e},c=0;for(let[t,i]of Object.entries(s)){if(t.startsWith("ANTHROPIC_")){$.warn({roleName:n,key:t},"Role .env contains ANTHROPIC_* key; ignored (managed globally)");continue}t in r||(r[t]=i,c++)}return c>0&&$.info({roleName:n,seeded:c},"Seeded role envVars from .env file"),Object.keys(r).length>0?r:void 0}function U(n,e){let s=k(n);if(!s)return[];let r=e??{},c=[];for(let[t,i]of Object.entries(s)){if(t.startsWith("ANTHROPIC_"))continue;let a=r[t]??"";a!==i&&c.push({envKey:t,dbValue:a,envValue:i})}for(let[t,i]of Object.entries(r))t in s||c.push({envKey:t,dbValue:i,envValue:""});return c}function q(n,e){let s=x(m(n),".env"),r=e??{},c=[],t=new Set;if(b(s)){let a=P(s,"utf-8");for(let d of a.split(`
3
3
  `)){let o=d.trim();if(!o||o.startsWith("#")){c.push(d);continue}let f=o.startsWith("export ")?o.slice(7).trim():o,l=f.indexOf("=");if(l===-1){c.push(d);continue}let u=f.slice(0,l).trim(),g=o.startsWith("export ")?"export ":"";u in r&&(c.push(`${g}${u}=${r[u]}`),t.add(u))}}let i=0;for(let[a,d]of Object.entries(r)){if(t.has(a)){i++;continue}d&&d.length>0&&(c.push(`${a}=${d}`),i++)}return I(s,c.join(`
4
4
  `)+`
@@ -1,4 +1,4 @@
1
- import{a as A,b as E}from"./chunk-2JIQT2CI.js";import{c as p,d as j,i as v}from"./chunk-QYI44EP6.js";import{a as B,b as d}from"./chunk-T2Z2JDPY.js";import{d as h,l as M,n as b,o as S,p as C,r as x}from"./chunk-V2MMQ3SH.js";import{K as g,L as w}from"./chunk-2A2TXYT3.js";w();var f=5;async function R(t,o,s){let c=g(t),i=o?`${t}::${o}`:void 0,r;if(s){if(r=j(t,s,f*4).map(a=>a.node).filter(a=>a.status==="active"),r.length<f*4){let a=new Set(r.map(n=>n.id)),u=p(t,{onlyActive:!0}).slice(0,f*4);for(let n of u)if(!a.has(n.id)&&(r.push(n),r.length>=f*4))break}}else r=p(t,{onlyActive:!0}).slice(0,f*4);i&&(r=r.filter(e=>e.scopeKey===i||e.scopeKey==null));let m=r.map(e=>({belief:e,score:A(e,c)??.5}));m.sort((e,a)=>a.score-e.score);let l=m.slice(0,f).map(e=>e.belief);for(let e of l)E(e,c),v(e.id),e.injectCount=(e.injectCount??0)+1;return l}function O(t,o){if(t.length===0)return"";let s=o==="initial"?"[Memory Context \u2014 retrieved from prior interactions]":"[Memory Refresh \u2014 \u8FC7\u5F80\u89C2\u5BDF,\u53EF\u80FD\u8FC7\u65F6;Step \u6307\u4EE4\u4E3A\u6743\u5A01,\u51B2\u7A81\u5219\u5FFD\u7565]",c=t.map(i=>i.isAnti?`- [anti-pattern] \u274C ${i.content}`:`- [belief] ${i.content}`);return`${s}
1
+ import{a as A,b as E}from"./chunk-PO66F7UQ.js";import{c as p,d as j,i as v}from"./chunk-4ZG4UMAK.js";import{a as B,b as d}from"./chunk-T2Z2JDPY.js";import{d as h,l as M,n as b,o as S,p as C,r as x}from"./chunk-FN64ZULV.js";import{K as g,L as w}from"./chunk-WG3C43QS.js";w();var f=5;async function R(t,o,s){let c=g(t),i=o?`${t}::${o}`:void 0,r;if(s){if(r=j(t,s,f*4).map(a=>a.node).filter(a=>a.status==="active"),r.length<f*4){let a=new Set(r.map(n=>n.id)),u=p(t,{onlyActive:!0}).slice(0,f*4);for(let n of u)if(!a.has(n.id)&&(r.push(n),r.length>=f*4))break}}else r=p(t,{onlyActive:!0}).slice(0,f*4);i&&(r=r.filter(e=>e.scopeKey===i||e.scopeKey==null));let m=r.map(e=>({belief:e,score:A(e,c)??.5}));m.sort((e,a)=>a.score-e.score);let l=m.slice(0,f).map(e=>e.belief);for(let e of l)E(e,c),v(e.id),e.injectCount=(e.injectCount??0)+1;return l}function O(t,o){if(t.length===0)return"";let s=o==="initial"?"[Memory Context \u2014 retrieved from prior interactions]":"[Memory Refresh \u2014 \u8FC7\u5F80\u89C2\u5BDF,\u53EF\u80FD\u8FC7\u65F6;Step \u6307\u4EE4\u4E3A\u6743\u5A01,\u51B2\u7A81\u5219\u5FFD\u7565]",c=t.map(i=>i.isAnti?`- [anti-pattern] \u274C ${i.content}`:`- [belief] ${i.content}`);return`${s}
2
2
  ${c.join(`
3
3
  `)}
4
4
 
@@ -0,0 +1,32 @@
1
+ import{b as K,c as A,d as L}from"./chunk-DRS5NOAA.js";import{a as te,e as re,g as ne}from"./chunk-VZL2DGC4.js";import{a as N,d as be}from"./chunk-4G4CKAXY.js";import{b as X,h as Q,i as Z}from"./chunk-L4APYD5A.js";import{s as G}from"./chunk-ORFLN4BF.js";import{a as w}from"./chunk-L7JP7DUO.js";import{c as R,h as ee}from"./chunk-EBZCHLYS.js";import{d as Y,r as ve}from"./chunk-6GYNUTPP.js";import{o as D,q as _e}from"./chunk-LMQPGVM7.js";import{c as q,h as Ie}from"./chunk-EZLBMUQD.js";import{c as O,e as J}from"./chunk-5M6IGE5G.js";import{existsSync as Ue}from"fs";import{createHash as Ve}from"crypto";import{isAbsolute as Pe}from"path";be();_e();J();import{v4 as Te}from"uuid";function oe(e){return{id:e.id,eventKey:e.event_key,sourceType:e.source_type,sourceId:e.source_id,taskId:e.task_id??void 0,templateId:e.template_id??void 0,templateName:e.template_name??void 0,messageType:e.message_type,viewerKey:e.viewer_key,title:e.title??void 0,contentPreview:e.content_preview,attachments:C(e.attachments_json),targets:C(e.targets_json),firstDeliveredAt:e.first_delivered_at,lastDeliveredAt:e.last_delivered_at,createdAt:e.created_at,traceId:e.trace_id??void 0}}function C(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function de(e){if(!e.viewerKey||e.viewerKey.trim().length===0)throw new Error("recordUserVisibleDeliveryEvent requires viewerKey");if(!e.eventKey||e.eventKey.trim().length===0)throw new Error("recordUserVisibleDeliveryEvent requires eventKey");if(!e.sourceId||e.sourceId.trim().length===0)throw new Error("recordUserVisibleDeliveryEvent requires sourceId");let t=D(),r=Date.now(),n=e.deliveredAt??r,a=t.prepare("SELECT * FROM user_visible_events WHERE event_key = ?").get(e.eventKey);if(!a){let d=Te();return t.prepare(`
2
+ INSERT INTO user_visible_events (
3
+ id, event_key, source_type, source_id, task_id, template_id, template_name,
4
+ message_type, viewer_key, title, content_preview, attachments_json,
5
+ targets_json, first_delivered_at, last_delivered_at, created_at, trace_id
6
+ )
7
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
8
+ `).run(d,e.eventKey,e.sourceType,e.sourceId,e.taskId??null,e.templateId??null,e.templateName??null,e.messageType,e.viewerKey,e.title??null,e.contentPreview,JSON.stringify(e.attachments??[]),JSON.stringify(e.targets??[]),n,n,r,e.traceId??O()??null),ie(e.eventKey)}let i=we(C(a.targets_json),e.targets??[]),o=Ae(C(a.attachments_json),e.attachments??[]);return t.prepare(`
9
+ UPDATE user_visible_events
10
+ SET task_id = COALESCE(task_id, ?),
11
+ template_id = COALESCE(template_id, ?),
12
+ template_name = COALESCE(template_name, ?),
13
+ title = COALESCE(title, ?),
14
+ content_preview = CASE WHEN content_preview = '' THEN ? ELSE content_preview END,
15
+ attachments_json = ?,
16
+ targets_json = ?,
17
+ last_delivered_at = MAX(last_delivered_at, ?),
18
+ trace_id = COALESCE(trace_id, ?)
19
+ WHERE event_key = ?
20
+ `).run(e.taskId??null,e.templateId??null,e.templateName??null,e.title??null,e.contentPreview,JSON.stringify(o),JSON.stringify(i),n,e.traceId??O()??null,e.eventKey),ie(e.eventKey)}function ie(e){let t=D().prepare("SELECT * FROM user_visible_events WHERE event_key = ?").get(e);return t?oe(t):void 0}function Je(e){let t=D(),r=e.excludeSourceIds??[],n=[e.viewerKey,e.since,e.until],a=`
21
+ SELECT * FROM user_visible_events
22
+ WHERE viewer_key = ?
23
+ AND last_delivered_at >= ?
24
+ AND last_delivered_at <= ?
25
+ `;return r.length>0&&(a+=` AND source_id NOT IN (${r.map(()=>"?").join(",")})`,n.push(...r)),a+=" ORDER BY last_delivered_at ASC",e.limit!==void 0&&(a+=" LIMIT ?",n.push(e.limit)),t.prepare(a).all(...n).map(oe)}function we(e,t){let r=[...e];for(let n of t){let a=se(n);r.some(i=>se(i)===a)||r.push(n)}return r}function se(e){return[e.type,e.channelId??"",e.webhookUrl??"",e.chatId??"",e.sessionId??""].join("|")}function Ae(e,t){let r=[...e];for(let n of t){let a=ae(n),i=r.findIndex(o=>ae(o)===a);i>=0?r[i]={...r[i],...n}:r.push(n)}return r}function ae(e){return e.artifactId?`artifact:${e.artifactId}`:["file",e.filename??"",e.sizeBytes??"",e.mimeType??""].join("|")}Ie();import{v4 as B}from"uuid";J();ve();import{basename as U,extname as ce}from"path";import{readFileSync as ke}from"fs";function le(e){return Y(e).filter(t=>t.kind==="file"&&!!t.blobPath)}function tt(e){return e.replace(/[\\/:*?"<>|]/g,"").replace(/\s+/g,"").replace(/^\.+/,"").trim()}function rt(e){if(e.kind!=="file"||!e.blobPath)return;let t;try{t=ke(e.blobPath,"utf-8")}catch{return}let n=t.match(/^#\s+(.+?)\s*$/m)?.[1]?.trim();return n&&n.length>0?n:void 0}function Ee(e){let t=e.mime??"";return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"file"}function Oe(e){let t=U(e.key??"").replace(/[\\/]/g,"-");if(e.originalFilename){let r=U(e.originalFilename).replace(/[\\/]/g,"-");if(ce(r))return r}if(ce(t))return t;if(e.mime){let r=ne(e.mime);if(r&&r!==".bin"&&t)return`${t}${r}`}return e.originalFilename?U(e.originalFilename).replace(/[\\/]/g,"-"):t||(e.blobPath?U(e.blobPath):e.id)}function ue(e){return e.map(t=>xe(t))}function xe(e,t){return{path:e.blobPath,mediaType:t?.mediaType??Ee(e),filename:t?.filename??Oe(e),contentType:e.mime,mimeType:e.mime,artifactId:e.id,locator:e.locator,sizeBytes:e.sizeBytes,purpose:e.purpose,contentHash:e.contentHash}}function $(e){if(e.priority!==void 0&&e.priority!==null)return e.priority;let t=e.mime??"";return t.startsWith("audio/")||t.startsWith("video/")?10:t==="text/markdown"||t==="text/plain"?50:t.startsWith("image/")?100:200}var x=1.33;function me(e,t){if(e.length===0)return{included:[],dropped:[]};let r=[...e].sort((d,s)=>{let g=$(d),y=$(s);return g!==y?g-y:s.sizeBytes-d.sizeBytes}),n=r[0];if(n.sizeBytes*x>t){if(r.length===1)return{firstItemOverflow:n};let d=r.slice(1),s=[],g=[],y=0;for(let _ of d){let l=_.sizeBytes*x;y+l<=t?(s.push(_),y+=l):g.push(_)}return s.length===0?{firstItemOverflow:n}:{included:s,dropped:[n,...g],firstOverflowWarning:!0}}let a=[],i=[],o=0;for(let d of r){let s=d.sizeBytes*x;o+s<=t?(a.push(d),o+=s):i.push(d)}return{included:a,dropped:i}}function pe(e,t,r,n){if(t.length===0)return e;let a=(r/(1024*1024)).toFixed(1),i=t.map(d=>`- ${d.filename} (${Se(d.sizeBytes)})`),o=e.endsWith(`---
26
+ `)||e.endsWith("---")?"":`
27
+
28
+ ---`;return`${e}${o}
29
+ \u26A0\uFE0F \u56E0 ${n} \u90AE\u7BB1 ${a}MB \u4E0A\u9650\uFF0C\u4EE5\u4E0B\u4EA7\u7269\u672A\u9644\uFF1A
30
+ ${i.join(`
31
+ `)}
32
+ `}function Se(e){return e<1024?`${e} bytes`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}var F=class extends Error{constructor(r,n,a,i,o){super(`OutboundFirstAttachmentExceedsCap: artifactKey=${r} sizeBytes=${n} effectiveSizeBytes=${a} capBytes=${i} recipientDomain=${o}`);this.artifactKey=r;this.sizeBytes=n;this.effectiveSizeBytes=a;this.capBytes=i;this.recipientDomain=o;this.name="OutboundFirstAttachmentExceedsCap"}artifactKey;sizeBytes;effectiveSizeBytes;capBytes;recipientDomain};function De(e){if(!e)return"";let t=e.lastIndexOf("@");return t<0||t===e.length-1?"":e.slice(t+1).toLowerCase().trim()}function Re(e,t){return t.find(r=>r.id===e)?.key??e}function Ce(e,t){return t.find(r=>r.artifactId===e)?.filename??e}function fe(e,t,r,n,a){let i=De(t),o=ee(e,i),d=r.map(l=>({id:l.id,sizeBytes:l.sizeBytes??0,priority:l.priority??void 0,mime:l.mime??void 0})),s=me(d,o);if("firstItemOverflow"in s){let l=s.firstItemOverflow,h=Re(l.id,r);return{ok:!1,error:new F(h,l.sizeBytes,Math.floor(l.sizeBytes*x),o,i).message}}let g=new Set(s.included.map(l=>l.id)),y=n.filter(l=>l.artifactId&&g.has(l.artifactId)),_=a;if(s.dropped.length>0){let l=s.dropped.map(h=>({filename:Ce(h.id,n),sizeBytes:h.sizeBytes}));_=pe(a,l,o,i)}return{ok:!0,result:{perTargetAttachments:y,perTargetContent:_}}}var E=q("adam"),z=class{_dedupCache=new Map;_rateLimitWindows=new Map;_recentlySentIds=new Set;_laneTails=new Map;async _acquireLane(t,r){let n=`${t}:${r}`,a=this._laneTails.get(n)??Promise.resolve(),i,o=new Promise(d=>{i=d});return this._laneTails.set(n,o),o.then(()=>{this._laneTails.get(n)===o&&this._laneTails.delete(n)}),await a,i}isRecentlySent(t){return this._recentlySentIds.has(t)}async send(t){let{taskId:r,channelId:n,chatId:a,content:i,messageType:o,platform:d,webhookUrl:s,replyMarkup:g,replyToMessageId:y,quoteExcerpt:_,quoteTitle:l,mediaUrl:h,mediaType:k,attachments:S,dedupDiscriminator:W}=t,I=ge(o),ye=I!=="reply"&&!!r,u;if(ye){u=`${r}:${n??"none"}:${a??"none"}:${I}${W?`:${W}`:""}`;let f=this._dedupCache.get(u);if(f&&Date.now()-f.timestamp<300*1e3)return E.debug({dedupKey:u},"Dedup hit, returning cached log entry"),{success:!0,logEntryId:f.logEntryId}}if(n){let f=Date.now(),v=6e4,p=this._rateLimitWindows.get(n);p||(p=[],this._rateLimitWindows.set(n,p));let P=f-v;for(;p.length>0&&p[0]<P;)p.shift();if(p.length>=60){let M=B();E.warn({channelId:n,count:p.length},"Rate limited, not sending");let b={type:"channel",channelId:n,chatId:a??""};return this._writeOutboundReceipt(t,b,i,"failure"),{success:!1,logEntryId:M,error:"rate_limited"}}p.push(f)}let he=d??(n?R(n)?.platform:void 0)??"unknown",H=s?i:te(i,he,r),c=B(),m={id:c,ruleId:void 0,taskId:r??void 0,status:"pending",target:n&&a?{type:"channel",channelId:n,chatId:a}:s?{type:"webhook",webhookUrl:s}:{type:"channel",channelId:n??"",chatId:a??""},content:H,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+1440*60*1e3,source:"direct",messageType:I};K(m),u&&this._dedupCache.set(u,{logEntryId:c,timestamp:Date.now()});try{let f=je(h);if(f)return A(c,"failed",f),u&&this._dedupCache.delete(u),w.emit({type:"delivery_status_change",logEntryId:c,taskId:r,target:m.target,status:"failed",error:f,messageType:I}),this._writeOutboundReceipt(t,m.target,i,"failure"),{success:!1,logEntryId:c,error:f};if(s){let v=await fetch(s,{method:"POST",body:JSON.stringify({result:i,taskId:r,timestamp:new Date().toISOString()}),signal:AbortSignal.timeout(1e4)});if(v.ok)return L(c),this._recordDeliveryLedgerAfterSuccess(t,m.target,I,i),w.emit({type:"delivery_status_change",logEntryId:c,taskId:r,target:m.target,status:"delivered",messageType:I}),{success:!0,logEntryId:c};{let p=`Webhook returned ${v.status}`;return A(c,"failed",p),u&&this._dedupCache.delete(u),w.emit({type:"delivery_status_change",logEntryId:c,taskId:r,target:m.target,status:"failed",error:p,messageType:I}),{success:!1,logEntryId:c,error:p}}}else if(n&&a){let{getChannelManager:v}=await Be(),p=v();if(!p){let T="ChannelManager not available";return A(c,"failed",T),u&&this._dedupCache.delete(u),w.emit({type:"delivery_status_change",logEntryId:c,taskId:r,target:m.target,status:"failed",error:T,messageType:I}),this._writeOutboundReceipt(t,m.target,i,"failure"),{success:!1,logEntryId:c,error:T}}let P={content:H,messageType:I,...g?{replyMarkup:g}:{},...y?{replyToMessageId:y}:{},..._?{quoteExcerpt:_}:{},...l?{quoteTitle:l}:{},...h?{mediaUrl:h}:{},...k?{mediaType:k}:{},...S?{attachments:S}:{}},M=await this._acquireLane(n,a),b;try{b=await p.sendMessage(n,a,P)}finally{M()}if(b===null){let T="Channel adapter send failed (returned null)";return A(c,"failed",T),u&&this._dedupCache.delete(u),w.emit({type:"delivery_status_change",logEntryId:c,taskId:r,target:m.target,status:"failed",error:T,messageType:I}),this._writeOutboundReceipt(t,m.target,i,"failure"),{success:!1,logEntryId:c,error:T}}if(b&&(this._recentlySentIds.add(b),setTimeout(()=>this._recentlySentIds.delete(b),300*1e3)),b?.startsWith("queued-")){let T="queued_not_delivered";return u&&this._dedupCache.delete(u),w.emit({type:"delivery_status_change",logEntryId:c,taskId:r,target:m.target,status:"pending",error:T,messageType:I}),{success:!1,messageId:b,logEntryId:c,error:T}}return L(c),this._recordDeliveryLedgerAfterSuccess(t,m.target,I,i),this._writeOutboundReceipt(t,m.target,i,"success"),w.emit({type:"delivery_status_change",logEntryId:c,taskId:r,target:m.target,status:"delivered",messageType:I}),{success:!0,messageId:b??void 0,logEntryId:c}}else{let v="No channelId/chatId or webhookUrl provided";return A(c,"failed",v),u&&this._dedupCache.delete(u),{success:!1,logEntryId:c,error:v}}}catch(f){let v=f instanceof Error?f.message:String(f);return A(c,"failed",v),u&&this._dedupCache.delete(u),w.emit({type:"delivery_status_change",logEntryId:c,taskId:r,target:m.target,status:"failed",error:v,messageType:I}),this._writeOutboundReceipt(t,m.target,i,"failure"),{success:!1,logEntryId:c,error:v}}}_writeOutboundReceipt(t,r,n,a){if(r.type!=="channel"||!r.channelId)return;let i=O();if(!i){E.debug({taskId:t.taskId,channelId:r.channelId,outcome:a},"Outbound receipt skipped: no active trace context");return}let o=(t.attachments??[]).map(s=>s.artifactId).filter(s=>typeof s=="string"&&s.length>0),d=t.actorToolName??"OutboundGateway.send";try{Z({traceId:i,taskId:t.taskId,sessionId:t.sessionId,effectCategory:"outbound_message",verb:"send",entityType:"channel_message",target:{channelId:r.channelId,chatId:r.chatId,platform:t.platform},payload:{textChars:n.length,attachmentCount:t.attachments?.length??0,attachmentRefs:o.length>0?o:void 0},actor:{traceId:i,toolName:d,taskId:t.taskId},outcome:a})}catch(s){s instanceof Q?E.warn({errors:s.errors,taskId:t.taskId,channelId:r.channelId},"Outbound receipt validation failed"):E.warn({error:s instanceof Error?s.message:String(s),taskId:t.taskId},"Outbound receipt write failed")}}async redeliverExecutionTo(t){let r=t.includeArtifacts??!0,n=t.messageType??"result_delivery",a=t.dedupDiscriminator??`redelivery:${Date.now()}`,i=r?t.fileArtifacts??le(t.executionId):[],o=t.attachments??(i.length>0?ue(i):void 0),d=[];for(let s of t.targets){let g=R(s.channelId);if(!g){d.push({target:{channelId:s.channelId,chatId:s.chatId},deliveryLogId:"",status:"failed",attachmentCount:0,error:`Channel not found: ${s.channelId}`});continue}let y=o,_=t.content;if(g.platform==="email"&&o&&o.length>0){let h=fe(s.channelId,s.chatId,i,o,t.content);if(!h.ok){let k=B(),S={type:"channel",channelId:s.channelId,chatId:s.chatId??""};K({id:k,ruleId:void 0,taskId:t.executionId,status:"pending",target:S,content:t.content,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+1440*60*1e3,source:"direct",messageType:ge(n)}),A(k,"failed",h.error),d.push({target:{channelId:s.channelId,chatId:s.chatId},deliveryLogId:k,status:"failed",attachmentCount:0,error:h.error});continue}y=h.result.perTargetAttachments,_=h.result.perTargetContent}let l=await this.send({taskId:t.executionId,sessionId:t.sessionId,channelId:s.channelId,chatId:s.chatId,content:_,messageType:n,platform:g.platform,attachments:y,dedupDiscriminator:a,actorToolName:t.actorToolName});d.push({target:{channelId:s.channelId,chatId:s.chatId},deliveryLogId:l.logEntryId,status:l.success?"delivered":"failed",attachmentCount:y?.length??0,...l.error?{error:l.error}:{}})}return{deliveries:d}}_recordDeliveryLedgerAfterSuccess(t,r,n,a){if(Me(n,t.taskId))try{let i=Ke(t,r);if(!i){N({source:"delivery_ledger",severity:"warning",sourceId:t.taskId,message:`Skipped user-visible delivery ledger write for ${n}: viewer identity unresolved`});return}let o=Le(t.taskId),d=Fe(a);de({eventKey:`${i}|${o.sourceId}|${n}|${d}`,sourceType:o.sourceType,sourceId:o.sourceId,taskId:t.taskId,templateId:o.templateId,templateName:o.templateName,messageType:n,viewerKey:i,title:o.templateName,contentPreview:a,attachments:(t.attachments??[]).map(Ne),targets:[$e(r)]})}catch(i){let o=i instanceof Error?i.message:String(i);E.warn({error:o,taskId:t.taskId,messageType:n},"User-visible delivery ledger write failed");try{N({source:"delivery_ledger",severity:"error",sourceId:t.taskId,message:o})}catch{}}}};function Me(e,t){return t?!["reply","assistant_text","user_message","approval","approval_prompt"].includes(e):!1}function Ke(e,t){if(e.viewerKey)return e.viewerKey;if(t.type==="channel"&&t.channelId)return re({type:"channel",channelId:t.channelId,chatId:t.chatId})}function Le(e){let t=X(e);if(!t)return{sourceType:"task",sourceId:e};let r=G(t.templateId);return{sourceType:"template_execution",sourceId:t.id,templateId:t.templateId,templateName:r?.name}}function Ne(e){return{artifactId:e.artifactId,locator:e.locator,filename:e.filename,mimeType:e.mimeType??e.contentType,sizeBytes:e.sizeBytes,purpose:e.purpose,contentHash:e.contentHash}}function $e(e){if(e.type==="webhook")return{type:"webhook",webhookUrl:e.webhookUrl};let t=e.channelId?R(e.channelId):void 0;return{type:"channel",channelId:e.channelId,chatId:e.chatId,label:t?.name}}function Fe(e){return Ve("sha256").update(e).digest("hex")}var V=null;function Be(){return V||(V=import("./channels-IDBWHLLE.js")),V}function Dt(){V=null}function je(e){if(!e)return;if(e.includes("://")&&!e.startsWith("file://"))return"mediaUrl must be a local file path";let t=e.startsWith("file://")?new URL(e).pathname:e;if(!Pe(t))return"mediaUrl must be absolute";if(!Ue(t))return"mediaUrl file does not exist"}function ge(e){return e==="report"?"status_report":e==="deliver"?"result_delivery":e}var j=null;function ze(){return j||(j=new z),j}function Rt(e){return ze().isRecentlySent(e)}export{Je as a,le as b,tt as c,rt as d,Ee as e,Oe as f,xe as g,z as h,Dt as i,ze as j,Rt as k};
@@ -0,0 +1 @@
1
+ import{b as s}from"./chunk-5PELJRUQ.js";import{join as o}from"path";import{homedir as r}from"os";var T,e,c,t,E,p,a,S,D,x,L,A=s(()=>{"use strict";T=["Read","Write","Edit","Bash","Grep","Glob","WebSearch","WebFetch","LSP","NotebookEdit","Agent"],e=["~/.ssh","~/.aws","~/.gnupg","/etc/shadow"],c=e,t=o(r(),".adam"),E=o(t,"adam.db"),p=o(t,"adam.config.yaml"),a=o(t,".env"),S=o(t,"CLAUDE.md"),D=o(t,"logs"),x=10*1024,L="\u81EA\u68C0 \xB7 \u5BA1\u8BA1\u8FB9\u8F66"});export{T as a,e as b,c,t as d,E as e,p as f,a as g,L as h,A as i};
@@ -1 +1 @@
1
- import{b as e,d as t,h as a}from"./chunk-VO24C673.js";a();var i={defaults:{timeout:600,maxTurns:400,maxBudgetUsd:5,effort:"high",model:"",settingSources:["user","project"],allowedTools:[],disallowedTools:[],approvalRequired:["rm -rf *","git push*","git reset*","curl * -X POST*","curl * --request POST*"],approvalTimeout:600,env:{},plugins:[],workspacePath:t,workspaceRetention:"immediate",deniedReadPaths:[...e]},externalApis:[],server:{port:7100,host:"0.0.0.0",timezone:"system"},identity:{ownerViewerKey:"local-owner"},logging:{level:"info"},roles:{presets:[],evolution:{triggerEvery:5,reflectionThreshold:150,retirementThreshold:.4,probationTasks:5}},chat:{sessionTimeoutMinutes:30,maxSessionTurns:20,autoTitle:!0,archiveExtractMemory:!0,contextBudgetTokens:2e4,artifactThresholdChars:4e3,maxConcurrentLiveSessions:3,liveSessionIdleMinutes:30,commitmentDetection:{locales:["zh","en"],blockedText:{zh:"\u4EFB\u52A1\u5DF2\u63D0\u4EA4\uFF0C\u5B8C\u6210\u540E\u6211\u4F1A\u66F4\u65B0\u7ED3\u679C\u3002",en:"Task dispatched; I will update you when it completes."},unsupportedSuccessText:{zh:"\u56FE\u7247\u5DF2\u751F\u6210\uFF0C\u53D1\u9001\u72B6\u6001\u8FD8\u6CA1\u6709\u5B8C\u6210\u9A8C\u8BC1\u3002",en:"Result is ready; delivery status is not yet verified."},unsupportedFailureText:{zh:"\u56FE\u7247\u5DF2\u751F\u6210\uFF0C\u4F46\u8FD8\u6CA1\u6709\u6267\u884C\u53D1\u9001\u3002",en:"Result is ready, but delivery has not been attempted."},unsupportedMutationText:{zh:"\u6211\u6CA1\u6709\u5B8C\u6210\u8FD9\u6B21\u8BB0\u5F55\uFF0C\u4E0D\u80FD\u8BF4\u5DF2\u8BB0\u5F55\u3002\u9700\u8981\u5148\u66F4\u65B0\u5BF9\u5E94\u6A21\u677F\u6216\u914D\u7F6E\u540E\u518D\u786E\u8BA4\u3002",en:"I did not actually record this. The template or config has not been updated yet."}}},memory:{midTaskInjection:{enabled:!0,toolCallThreshold:10,cooldownMs:6e4,topK:3,maxTokens:1e3},retrievalWeights:{cosSim:.4,recency:.2,tokenCost:.05},globalBudgetTokens:1500,retrievalDecayDays:30,attributionThresholds:{high:.7,low:.4},antiFlipMinUses:5,antiFlipSuccessEmaThreshold:.25,reflection:{maxBudgetUsd:5},scope:{emaAlpha:.3,humanFeedbackWeight:3,reflectionPoolMax:100,decayBase:.995,archiveThreshold:.2},embeddingModel:"bge-small-zh-v1.5"},watchdog:{enabled:!0,intervalMinutes:5,rules:{managerHealthCheck:{enabled:!0,action:"restart",staleDurationMinutes:15},staleTasks:{enabled:!0,action:"notify",maxPendingMinutes:30},staleRunningTasks:{enabled:!0,action:"notify",maxRunningMinutes:15},staleTemplateExecutions:{enabled:!0,action:"notify",maxOrphanMinutes:60},dbMaintenance:{enabled:!0,action:"ignore",walCheckpointThresholdMB:100},artifactCleanup:{enabled:!0,action:"ignore",ttlDays:7,orphanGcMinAgeHours:1},sandboxViolation:{enabled:!0,action:"alert"},reflectionJob:{enabled:!0,intervalMinutes:30},memoryGc:{enabled:!0,intervalHours:24,observationTtlDays:14}}},execution:{maxConcurrent:5,pollIntervalMs:3e4},anthropic:{apiKey:"",baseUrl:"",model:"",defaultOpusModel:"",defaultSonnetModel:"",defaultHaikuModel:"",smallFastModel:""},emailGateway:{enabled:!1,address:"",displayName:"Adam",imap:{host:"",port:993,secure:!0,auth:{user:"",pass:""},mailbox:"INBOX"},smtp:{host:"",port:465,secure:!0,auth:{user:"",pass:""},from:""},subjectPrefix:"Adam"},audit:{intentEval:{maxBudgetUsd:1,timeoutMs:3e4}},evaluation:{},delivery:{cronDefaultReportTo:null},storage:{localProfile:"default"},pricing:{models:{"claude-opus-4-7":{input:5,output:25,cacheRead:.5,cacheCreation:6.25,estimated:!0},"claude-sonnet-4-6":{input:3,output:15,cacheRead:.3,cacheCreation:3.75,estimated:!0},"claude-haiku-4-5":{input:1,output:5,cacheRead:.1,cacheCreation:1.25,estimated:!0},"deepseek-v4-flash":{input:.14,output:.28,cacheRead:.0028,cacheCreation:.14,estimated:!0},"deepseek-v4-pro":{input:1.74,output:3.48,cacheRead:.0145,cacheCreation:1.74,estimated:!0},"doubao-seed-2.0-pro":{input:.47,output:2.37,cacheRead:.094,cacheCreation:.47,estimated:!0},"minimax-m2":{input:.26,output:1,cacheRead:.26,cacheCreation:.26,estimated:!0},"gpt-4.1":{input:2,output:8,cacheRead:.5,cacheCreation:2,estimated:!0},"gpt-4o":{input:2.5,output:10,cacheRead:1.25,cacheCreation:2.5,estimated:!0},"gemini-2.5-pro":{input:1.25,output:10,cacheRead:.3125,cacheCreation:1.25,estimated:!0},"gemini-2.5-flash":{input:.3,output:2.5,cacheRead:.075,cacheCreation:.3,estimated:!0}}},cost:{dailyThresholdUsd:0}};export{i as a};
1
+ import{b as e,d as t,i as a}from"./chunk-ITVCPC7G.js";a();var i={defaults:{timeout:600,maxTurns:400,maxBudgetUsd:5,effort:"high",model:"",settingSources:["user","project"],allowedTools:[],disallowedTools:[],approvalRequired:["rm -rf *","git push*","git reset*","curl * -X POST*","curl * --request POST*"],approvalTimeout:600,env:{},plugins:[],workspacePath:t,workspaceRetention:"immediate",deniedReadPaths:[...e]},externalApis:[],server:{port:7100,host:"0.0.0.0",timezone:"system"},identity:{ownerViewerKey:"local-owner"},logging:{level:"info"},roles:{presets:[],evolution:{triggerEvery:5,reflectionThreshold:150,retirementThreshold:.4,probationTasks:5}},chat:{sessionTimeoutMinutes:30,maxSessionTurns:20,autoTitle:!0,archiveExtractMemory:!0,contextBudgetTokens:2e4,artifactThresholdChars:4e3,maxConcurrentLiveSessions:3,liveSessionIdleMinutes:30,commitmentDetection:{locales:["zh","en"],blockedText:{zh:"\u4EFB\u52A1\u5DF2\u63D0\u4EA4\uFF0C\u5B8C\u6210\u540E\u6211\u4F1A\u66F4\u65B0\u7ED3\u679C\u3002",en:"Task dispatched; I will update you when it completes."},unsupportedSuccessText:{zh:"\u56FE\u7247\u5DF2\u751F\u6210\uFF0C\u53D1\u9001\u72B6\u6001\u8FD8\u6CA1\u6709\u5B8C\u6210\u9A8C\u8BC1\u3002",en:"Result is ready; delivery status is not yet verified."},unsupportedFailureText:{zh:"\u56FE\u7247\u5DF2\u751F\u6210\uFF0C\u4F46\u8FD8\u6CA1\u6709\u6267\u884C\u53D1\u9001\u3002",en:"Result is ready, but delivery has not been attempted."},unsupportedMutationText:{zh:"\u6211\u6CA1\u6709\u5B8C\u6210\u8FD9\u6B21\u8BB0\u5F55\uFF0C\u4E0D\u80FD\u8BF4\u5DF2\u8BB0\u5F55\u3002\u9700\u8981\u5148\u66F4\u65B0\u5BF9\u5E94\u6A21\u677F\u6216\u914D\u7F6E\u540E\u518D\u786E\u8BA4\u3002",en:"I did not actually record this. The template or config has not been updated yet."}}},memory:{midTaskInjection:{enabled:!0,toolCallThreshold:10,cooldownMs:6e4,topK:3,maxTokens:1e3},retrievalWeights:{cosSim:.4,recency:.2,tokenCost:.05},globalBudgetTokens:1500,retrievalDecayDays:30,attributionThresholds:{high:.7,low:.4},antiFlipMinUses:5,antiFlipSuccessEmaThreshold:.25,reflection:{maxBudgetUsd:5},scope:{emaAlpha:.3,humanFeedbackWeight:3,reflectionPoolMax:100,decayBase:.995,archiveThreshold:.2},embeddingModel:"bge-small-zh-v1.5"},watchdog:{enabled:!0,intervalMinutes:5,rules:{managerHealthCheck:{enabled:!0,action:"restart",staleDurationMinutes:15},staleTasks:{enabled:!0,action:"notify",maxPendingMinutes:30},staleRunningTasks:{enabled:!0,action:"notify",maxRunningMinutes:15},staleTemplateExecutions:{enabled:!0,action:"notify",maxOrphanMinutes:60},dbMaintenance:{enabled:!0,action:"ignore",walCheckpointThresholdMB:100},artifactCleanup:{enabled:!0,action:"ignore",ttlDays:7,orphanGcMinAgeHours:1},sandboxViolation:{enabled:!0,action:"alert"},reflectionJob:{enabled:!0,intervalMinutes:30},memoryGc:{enabled:!0,intervalHours:24,observationTtlDays:14}}},execution:{maxConcurrent:5,pollIntervalMs:3e4},anthropic:{apiKey:"",baseUrl:"",model:"",defaultOpusModel:"",defaultSonnetModel:"",defaultHaikuModel:"",smallFastModel:""},emailGateway:{enabled:!1,address:"",displayName:"Adam",imap:{host:"",port:993,secure:!0,auth:{user:"",pass:""},mailbox:"INBOX"},smtp:{host:"",port:465,secure:!0,auth:{user:"",pass:""},from:""},subjectPrefix:"Adam"},audit:{intentEval:{maxBudgetUsd:1,timeoutMs:3e4}},evaluation:{},delivery:{cronDefaultReportTo:null},storage:{localProfile:"default"},pricing:{models:{"claude-opus-4-7":{input:5,output:25,cacheRead:.5,cacheCreation:6.25,estimated:!0},"claude-sonnet-4-6":{input:3,output:15,cacheRead:.3,cacheCreation:3.75,estimated:!0},"claude-haiku-4-5":{input:1,output:5,cacheRead:.1,cacheCreation:1.25,estimated:!0},"deepseek-v4-flash":{input:.14,output:.28,cacheRead:.0028,cacheCreation:.14,estimated:!0},"deepseek-v4-pro":{input:1.74,output:3.48,cacheRead:.0145,cacheCreation:1.74,estimated:!0},"doubao-seed-2.0-pro":{input:.47,output:2.37,cacheRead:.094,cacheCreation:.47,estimated:!0},"minimax-m2":{input:.26,output:1,cacheRead:.26,cacheCreation:.26,estimated:!0},"gpt-4.1":{input:2,output:8,cacheRead:.5,cacheCreation:2,estimated:!0},"gpt-4o":{input:2.5,output:10,cacheRead:1.25,cacheCreation:2.5,estimated:!0},"gemini-2.5-pro":{input:1.25,output:10,cacheRead:.3125,cacheCreation:1.25,estimated:!0},"gemini-2.5-flash":{input:.3,output:2.5,cacheRead:.075,cacheCreation:.3,estimated:!0}}},cost:{dailyThresholdUsd:0}};export{i as a};
@@ -1,4 +1,4 @@
1
- import{g as u,h as g}from"./chunk-VO24C673.js";g();import{readFileSync as p,writeFileSync as h,existsSync as m}from"fs";var f={ANTHROPIC_API_KEY:"anthropic.apiKey",ANTHROPIC_BASE_URL:"anthropic.baseUrl",ANTHROPIC_MODEL:"anthropic.model",ANTHROPIC_DEFAULT_OPUS_MODEL:"anthropic.defaultOpusModel",ANTHROPIC_DEFAULT_SONNET_MODEL:"anthropic.defaultSonnetModel",ANTHROPIC_DEFAULT_HAIKU_MODEL:"anthropic.defaultHaikuModel",ANTHROPIC_SMALL_FAST_MODEL:"anthropic.smallFastModel",ADAM_EMAIL_ADDRESS:"emailGateway.address",ADAM_EMAIL_IMAP_HOST:"emailGateway.imap.host",ADAM_EMAIL_IMAP_PORT:"emailGateway.imap.port",ADAM_EMAIL_IMAP_SECURE:"emailGateway.imap.secure",ADAM_EMAIL_IMAP_USER:"emailGateway.imap.auth.user",ADAM_EMAIL_IMAP_PASS:"emailGateway.imap.auth.pass",ADAM_EMAIL_IMAP_MAILBOX:"emailGateway.imap.mailbox",ADAM_EMAIL_SMTP_HOST:"emailGateway.smtp.host",ADAM_EMAIL_SMTP_PORT:"emailGateway.smtp.port",ADAM_EMAIL_SMTP_SECURE:"emailGateway.smtp.secure",ADAM_EMAIL_SMTP_USER:"emailGateway.smtp.auth.user",ADAM_EMAIL_SMTP_PASS:"emailGateway.smtp.auth.pass",ADAM_EMAIL_SMTP_FROM:"emailGateway.smtp.from",ADAM_EMAIL_SUBJECT_PREFIX:"emailGateway.subjectPrefix"},y=Object.fromEntries(Object.entries(f).map(([r,e])=>[e,r]));function P(r){return r in f}function v(r,e){if(r==="server.port"||r.endsWith(".port")){let n=parseInt(e,10);return Number.isNaN(n)?e:n}return r.endsWith(".secure")||r.endsWith(".enabled")?e==="true"||e==="1":e}function E(r){let e={};for(let n of r.split(`
1
+ import{g as u,i as g}from"./chunk-ITVCPC7G.js";g();import{readFileSync as p,writeFileSync as h,existsSync as m}from"fs";var f={ANTHROPIC_API_KEY:"anthropic.apiKey",ANTHROPIC_BASE_URL:"anthropic.baseUrl",ANTHROPIC_MODEL:"anthropic.model",ANTHROPIC_DEFAULT_OPUS_MODEL:"anthropic.defaultOpusModel",ANTHROPIC_DEFAULT_SONNET_MODEL:"anthropic.defaultSonnetModel",ANTHROPIC_DEFAULT_HAIKU_MODEL:"anthropic.defaultHaikuModel",ANTHROPIC_SMALL_FAST_MODEL:"anthropic.smallFastModel",ADAM_EMAIL_ADDRESS:"emailGateway.address",ADAM_EMAIL_IMAP_HOST:"emailGateway.imap.host",ADAM_EMAIL_IMAP_PORT:"emailGateway.imap.port",ADAM_EMAIL_IMAP_SECURE:"emailGateway.imap.secure",ADAM_EMAIL_IMAP_USER:"emailGateway.imap.auth.user",ADAM_EMAIL_IMAP_PASS:"emailGateway.imap.auth.pass",ADAM_EMAIL_IMAP_MAILBOX:"emailGateway.imap.mailbox",ADAM_EMAIL_SMTP_HOST:"emailGateway.smtp.host",ADAM_EMAIL_SMTP_PORT:"emailGateway.smtp.port",ADAM_EMAIL_SMTP_SECURE:"emailGateway.smtp.secure",ADAM_EMAIL_SMTP_USER:"emailGateway.smtp.auth.user",ADAM_EMAIL_SMTP_PASS:"emailGateway.smtp.auth.pass",ADAM_EMAIL_SMTP_FROM:"emailGateway.smtp.from",ADAM_EMAIL_SUBJECT_PREFIX:"emailGateway.subjectPrefix"},y=Object.fromEntries(Object.entries(f).map(([r,e])=>[e,r]));function P(r){return r in f}function v(r,e){if(r==="server.port"||r.endsWith(".port")){let n=parseInt(e,10);return Number.isNaN(n)?e:n}return r.endsWith(".secure")||r.endsWith(".enabled")?e==="true"||e==="1":e}function E(r){let e={};for(let n of r.split(`
2
2
  `)){let o=n.trim();if(!o||o.startsWith("#"))continue;let i=o.startsWith("export ")?o.slice(7).trim():o,a=i.indexOf("=");if(a===-1)continue;let s=i.slice(0,a).trim(),t=i.slice(a+1).trim();(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))&&(t=t.slice(1,-1)),!(t.includes("$")&&(t=t.replace(/\$\{(\w+)\}|\$(\w+)/g,(c,_,l)=>{let A=_??l;return e[A]??process.env[A]??""}),!t))&&(e[s]=t)}return e}function R(){if(!m(u))return null;let r=E(p(u,"utf-8")),e={};for(let[n,o]of Object.entries(r))n in f&&(e[n]=o);return e}function O(){return m(u)?E(p(u,"utf-8")):null}function b(r){let e=O();if(!e)return[];let n=[];for(let[i,a]of Object.entries(f)){let s=r[a],t=e[i];if(t===void 0)continue;let c=s?String(s):"";c!==t&&n.push({configPath:a,envKey:i,dbValue:c,envValue:t})}let o=r["defaults.env"]??{};for(let[i,a]of Object.entries(e)){if(i in f)continue;let s=o[i]??"";s!==a&&n.push({configPath:`defaults.env.${i}`,envKey:i,dbValue:s,envValue:a})}for(let[i,a]of Object.entries(o))i in e||n.push({configPath:`defaults.env.${i}`,envKey:i,dbValue:a,envValue:""});return n}function T(r){if(!m(u))return 0;let n=p(u,"utf-8").split(`
3
3
  `),o=0,i=new Set,a=r["defaults.env"]??{};for(let s=0;s<n.length;s++){let t=n[s].trim();if(!t||t.startsWith("#"))continue;let c=t.startsWith("export ")?t.slice(7).trim():t,_=c.indexOf("=");if(_===-1)continue;let l=c.slice(0,_).trim(),A=t.startsWith("export ")?"export ":"",M=f[l];if(M){let d=r[M];d!=null&&String(d).length>0&&(n[s]=`${A}${l}=${String(d)}`,i.add(l),o++);continue}l in a&&(n[s]=`${A}${l}=${a[l]}`,i.add(l),o++)}for(let[s,t]of Object.entries(f)){if(i.has(s))continue;let c=r[t];c&&String(c).length>0&&(n.push(`${s}=${String(c)}`),o++)}for(let[s,t]of Object.entries(a))i.has(s)||t&&t.length>0&&(n.push(`${s}=${t}`),o++);return o>0&&h(u,n.join(`
4
4
  `)),o}export{f as a,P as b,v as c,R as d,O as e,b as f,T as g};
@@ -1,8 +1,8 @@
1
- import{d as D}from"./chunk-JROGEBP5.js";import{a as b}from"./chunk-4N5G7ND2.js";import{f as v}from"./chunk-IEBAOZED.js";import{g as O}from"./chunk-TWOJVEO7.js";import{a as S,b as P,c,d as I,e as w,f as C,g as M}from"./chunk-JYZTIE2J.js";import{b as y}from"./chunk-TA5PFK5C.js";import{b as R}from"./chunk-4JHACUZY.js";import{s as k}from"./chunk-VWX2B6OM.js";import{a as f}from"./chunk-L7JP7DUO.js";import{b as h,p as B}from"./chunk-2A2TXYT3.js";import{c as x}from"./chunk-6WQFYV3N.js";import{n as d,p as j}from"./chunk-WY5BOCQP.js";import{c as E,h as N}from"./chunk-EZLBMUQD.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(`
1
+ import{d as D}from"./chunk-76MMY2XC.js";import{a as b}from"./chunk-4N5G7ND2.js";import{f as v}from"./chunk-WDMSZS4W.js";import{j as O}from"./chunk-IAGTZGGV.js";import{a as S,b as P,c,d as I,e as w,f as C,g as M}from"./chunk-DRS5NOAA.js";import{b as y}from"./chunk-YEGUFMLJ.js";import{b as R}from"./chunk-L4APYD5A.js";import{s as k}from"./chunk-ORFLN4BF.js";import{a as f}from"./chunk-L7JP7DUO.js";import{b as h,p as B}from"./chunk-WG3C43QS.js";import{c as x}from"./chunk-EBZCHLYS.js";import{o as d,q as j}from"./chunk-LMQPGVM7.js";import{c as E,h as N}from"./chunk-EZLBMUQD.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
2
  INSERT INTO delivery_rules (id, event_type, match_criteria, target, format_template,
3
3
  max_per_minute, skip_origin_channel, enabled, created_at, created_by)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
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-BWA7UIKN.js");await p(a.channelId,a.chatId,n,e,o)}let s=D(r)+`
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-S3NV7OPO.js");await p(a.channelId,a.chatId,n,e,o)}let s=D(r)+`
6
6
 
7
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=R(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
8
  First error: ${a[0][1].error.slice(0,300)}`:""].filter(Boolean).join(`