adam-agent-server 1.19.0 → 1.19.1

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 (85) hide show
  1. package/dist/approval-handler-GXIVBJ4Z.js +1 -0
  2. package/dist/artifacts-DDHH47IE.js +1 -0
  3. package/dist/audit-diagnostics-HLHS3MHM.js +1 -0
  4. package/dist/audit-manager-PDMOR2MX.js +1 -0
  5. package/dist/bree-engine-6UKRI4UN.js +1 -0
  6. package/dist/{channels-ZHCTFSDA.js → channels-3J6U6GYH.js} +1 -1
  7. package/dist/channels-YOBMSBWV.js +1 -0
  8. package/dist/{chat-tool-calls-4BQWZCJH.js → chat-tool-calls-5Z53IXRF.js} +1 -1
  9. package/dist/{chunk-4ZESWP3J.js → chunk-2BLSA25Q.js} +1 -1
  10. package/dist/{chunk-WG3C43QS.js → chunk-3JTHJ3FZ.js} +1 -1
  11. package/dist/{chunk-PO66F7UQ.js → chunk-4NRIKWSD.js} +1 -1
  12. package/dist/{chunk-VZL2DGC4.js → chunk-5ZL6RHPE.js} +1 -1
  13. package/dist/{chunk-6GYNUTPP.js → chunk-6GVYOHD5.js} +5 -5
  14. package/dist/{chunk-GQS3ED3B.js → chunk-6NIWU43Z.js} +1 -1
  15. package/dist/{chunk-4ZG4UMAK.js → chunk-6SBLFYCU.js} +1 -1
  16. package/dist/{chunk-FN64ZULV.js → chunk-AKQ3AFVI.js} +1 -1
  17. package/dist/{chunk-JXZCQ5XW.js → chunk-CQDOIHPV.js} +1 -1
  18. package/dist/{chunk-QJXV4SQE.js → chunk-EXB2JIBR.js} +1 -1
  19. package/dist/{chunk-ORFLN4BF.js → chunk-G5I76LX2.js} +1 -1
  20. package/dist/{chunk-HEHST2E2.js → chunk-GYOZGA7G.js} +1 -1
  21. package/dist/{chunk-CN5NEJXG.js → chunk-ISTUK7Q6.js} +1 -1
  22. package/dist/chunk-J4JO7O3T.js +182 -0
  23. package/dist/{chunk-2JM3URDG.js → chunk-KO6UB6VW.js} +1 -1
  24. package/dist/chunk-LE5YRP37.js +14 -0
  25. package/dist/{chunk-FQHGIY3E.js → chunk-N4BV2WAU.js} +1 -1
  26. package/dist/{chunk-VOH52UDS.js → chunk-NUTGYMDP.js} +1 -1
  27. package/dist/{chunk-4G4CKAXY.js → chunk-NX3CIEZA.js} +1 -1
  28. package/dist/{chunk-ZGA52HRD.js → chunk-P2EDMFVO.js} +1 -1
  29. package/dist/{chunk-DRS5NOAA.js → chunk-PU2T7HBY.js} +1 -1
  30. package/dist/{chunk-R7Q6FSV4.js → chunk-PZH5NKUL.js} +11 -11
  31. package/dist/{chunk-EPLSB63A.js → chunk-QF3B4OWI.js} +1 -1
  32. package/dist/{chunk-JVYSSJKT.js → chunk-QQWUWGSK.js} +2 -2
  33. package/dist/{chunk-DFTRUOT6.js → chunk-QX65LEYA.js} +1 -1
  34. package/dist/{chunk-IAGTZGGV.js → chunk-R3MSLP6P.js} +2 -2
  35. package/dist/{chunk-KM4EFB4N.js → chunk-SDHMBWVC.js} +1 -1
  36. package/dist/{chunk-A3YUIWLK.js → chunk-SONOE4ZJ.js} +1 -1
  37. package/dist/{chunk-WDMSZS4W.js → chunk-VVPB3TD4.js} +1 -1
  38. package/dist/{chunk-L4APYD5A.js → chunk-X3PJNX2R.js} +1 -1
  39. package/dist/{chunk-EBZCHLYS.js → chunk-XEXSXMWK.js} +1 -1
  40. package/dist/{chunk-7QT2ZX3K.js → chunk-YGR5ZTGT.js} +1 -1
  41. package/dist/{chunk-76MMY2XC.js → chunk-YGZQMZTA.js} +1 -1
  42. package/dist/{chunk-YEGUFMLJ.js → chunk-YI2QQTZE.js} +1 -1
  43. package/dist/{chunk-KQMKRRYW.js → chunk-ZARKPBI2.js} +45 -45
  44. package/dist/{chunk-LMQPGVM7.js → chunk-ZEGZ2I35.js} +4 -4
  45. package/dist/cli.js +1 -1
  46. package/dist/{config-GOJLI3X2.js → config-7Y7I7KX4.js} +1 -1
  47. package/dist/{db-ROXIYW5B.js → db-P7ELD5DS.js} +1 -1
  48. package/dist/{delivery-log-TGJZ5HU7.js → delivery-log-EVRKJ5GD.js} +1 -1
  49. package/dist/engine-FE7NCHOG.js +1 -0
  50. package/dist/{evolution-audit-TFJF666X.js → evolution-audit-XIWF3JIF.js} +1 -1
  51. package/dist/execution-tools-PGURN3N6.js +1 -0
  52. package/dist/index.js +68 -67
  53. package/dist/{learner-ACBX3GI7.js → learner-PWDQUZ5O.js} +1 -1
  54. package/dist/{memories-RAIR5O2F.js → memories-2OJFLLBT.js} +1 -1
  55. package/dist/{memory-extractor-A6CAOFOX.js → memory-extractor-N7M4YSPL.js} +1 -1
  56. package/dist/{memory-gc-W63MGSDH.js → memory-gc-R42SPM52.js} +1 -1
  57. package/dist/memory-service-V7B5MY37.js +1 -0
  58. package/dist/outbound-gateway-NHNHVHF2.js +1 -0
  59. package/dist/presets-H2UV3HIF.js +1 -0
  60. package/dist/{reflection-job-XC2F7GTT.js → reflection-job-ECJX5ERQ.js} +1 -1
  61. package/dist/role-presets-7SWGUPV2.js +1 -0
  62. package/dist/role-workspace-AOYIGLG4.js +1 -0
  63. package/dist/{roles-LZCJ7QFS.js → roles-5TWJBGAQ.js} +1 -1
  64. package/dist/{session-manager-PU4GH3E4.js → session-manager-5P2FAEV3.js} +1 -1
  65. package/dist/skill-registry-XOX4OSHY.js +1 -0
  66. package/dist/{task-templates-52LAC6OA.js → task-templates-CTQHB6TA.js} +1 -1
  67. package/dist/template-dispatch-Z2TKWOMY.js +1 -0
  68. package/package.json +1 -1
  69. package/dist/approval-handler-S3NV7OPO.js +0 -1
  70. package/dist/artifacts-NFMM3ORE.js +0 -1
  71. package/dist/audit-diagnostics-IHU3CJYZ.js +0 -1
  72. package/dist/audit-manager-MUMEEP3C.js +0 -1
  73. package/dist/bree-engine-EEKUQA3U.js +0 -1
  74. package/dist/channels-IDBWHLLE.js +0 -1
  75. package/dist/chunk-MMVDXKYS.js +0 -14
  76. package/dist/chunk-NKS7LEA7.js +0 -182
  77. package/dist/engine-GN7PJPGQ.js +0 -1
  78. package/dist/execution-tools-BQD2O25X.js +0 -1
  79. package/dist/memory-service-H4OFUNCF.js +0 -1
  80. package/dist/outbound-gateway-LKRQYPA2.js +0 -1
  81. package/dist/presets-FO6RSGDN.js +0 -1
  82. package/dist/role-presets-SDA664QG.js +0 -1
  83. package/dist/role-workspace-NGJEJG3H.js +0 -1
  84. package/dist/skill-registry-XKLE2LXU.js +0 -1
  85. package/dist/template-dispatch-PJFSWEO2.js +0 -1
@@ -0,0 +1 @@
1
+ import{c as a,d as b,e as c,f as d,g as e}from"./chunk-YGZQMZTA.js";import"./chunk-R3MSLP6P.js";import"./chunk-PU2T7HBY.js";import"./chunk-5ZL6RHPE.js";import"./chunk-YI2QQTZE.js";import"./chunk-NX3CIEZA.js";import"./chunk-X3PJNX2R.js";import"./chunk-G5I76LX2.js";import"./chunk-L7JP7DUO.js";import"./chunk-3JTHJ3FZ.js";import"./chunk-XEXSXMWK.js";import"./chunk-ISTUK7Q6.js";import"./chunk-J2VSAXVU.js";import"./chunk-3MROEPGR.js";import"./chunk-6GVYOHD5.js";import"./chunk-ZEGZ2I35.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};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s}from"./chunk-6GVYOHD5.js";import"./chunk-ZEGZ2I35.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5PELJRUQ.js";s();export{o as appendArtifactToCollection,p as convertPrimaryFileToCollectionInTransaction,b as createArtifact,k as deleteArtifactById,i as deleteArtifactsByExecution,j as deleteArtifactsByExecutionAndStep,n as ensureUniqueArtifactKey,c as getArtifact,d as getArtifactById,m as isArtifactCollectionManifest,r as listArtifacts,g as listArtifactsByChatSession,e as listArtifactsByExecution,h as listArtifactsByRole,f as listArtifactsByTask,q as listExpiredExecutions,a as normalizeJsonArtifactValue,l as removeArtifact};
@@ -0,0 +1 @@
1
+ import{a,b,d as c}from"./chunk-NX3CIEZA.js";import"./chunk-ZEGZ2I35.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-J4JO7O3T.js";import"./chunk-QMW7VEPC.js";import"./chunk-PZH5NKUL.js";import"./chunk-EXB2JIBR.js";import"./chunk-QF3B4OWI.js";import"./chunk-SDHMBWVC.js";import"./chunk-SONOE4ZJ.js";import"./chunk-VVPB3TD4.js";import"./chunk-PU2T7HBY.js";import"./chunk-QX65LEYA.js";import"./chunk-LE5YRP37.js";import"./chunk-N4BV2WAU.js";import"./chunk-KO6UB6VW.js";import"./chunk-X3PJNX2R.js";import"./chunk-6NIWU43Z.js";import"./chunk-G5I76LX2.js";import"./chunk-L7JP7DUO.js";import"./chunk-GYOZGA7G.js";import"./chunk-4NRIKWSD.js";import"./chunk-6SBLFYCU.js";import"./chunk-T2Z2JDPY.js";import"./chunk-AKQ3AFVI.js";import"./chunk-3JTHJ3FZ.js";import"./chunk-AUSR5JYV.js";import"./chunk-ISTUK7Q6.js";import"./chunk-J2VSAXVU.js";import"./chunk-3MROEPGR.js";import"./chunk-6GVYOHD5.js";import"./chunk-ZEGZ2I35.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-YGR5ZTGT.js";import"./chunk-ZARKPBI2.js";import"./chunk-PZH5NKUL.js";import"./chunk-EXB2JIBR.js";import"./chunk-QF3B4OWI.js";import"./chunk-SDHMBWVC.js";import"./chunk-2BLSA25Q.js";import"./chunk-4N5G7ND2.js";import"./chunk-VVPB3TD4.js";import"./chunk-NNMQGISW.js";import"./chunk-R3MSLP6P.js";import"./chunk-PU2T7HBY.js";import"./chunk-5ZL6RHPE.js";import"./chunk-YI2QQTZE.js";import"./chunk-NX3CIEZA.js";import"./chunk-N4BV2WAU.js";import"./chunk-KO6UB6VW.js";import"./chunk-X3PJNX2R.js";import"./chunk-6NIWU43Z.js";import"./chunk-G5I76LX2.js";import"./chunk-L7JP7DUO.js";import"./chunk-T2Z2JDPY.js";import"./chunk-AKQ3AFVI.js";import"./chunk-3JTHJ3FZ.js";import"./chunk-XEXSXMWK.js";import"./chunk-ISTUK7Q6.js";import"./chunk-T7EKW3B7.js";import"./chunk-J2VSAXVU.js";import"./chunk-JRRNGKDK.js";import"./chunk-3MROEPGR.js";import"./chunk-6GVYOHD5.js";import"./chunk-ZEGZ2I35.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};
@@ -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-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};
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-XEXSXMWK.js";import"./chunk-ZEGZ2I35.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{i as a,j as b,k as c}from"./chunk-CQDOIHPV.js";import"./chunk-VVPB3TD4.js";import"./chunk-NNMQGISW.js";import"./chunk-5ZL6RHPE.js";import"./chunk-YI2QQTZE.js";import"./chunk-NX3CIEZA.js";import"./chunk-XEXSXMWK.js";import"./chunk-J2VSAXVU.js";import"./chunk-3MROEPGR.js";import"./chunk-ZEGZ2I35.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{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
+ import{a,b,c}from"./chunk-NUTGYMDP.js";import"./chunk-ZEGZ2I35.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5PELJRUQ.js";export{c as hasAnyToolCallInTurn,b as listChatToolCallsByTrace,a as recordChatToolCall};
@@ -1 +1 @@
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
+ import{c as x,e as C}from"./chunk-VVPB3TD4.js";import{a as y,b as u,c,d as m,e as h,g as v}from"./chunk-YI2QQTZE.js";import{a as i}from"./chunk-L7JP7DUO.js";import{b as l}from"./chunk-T2Z2JDPY.js";import{a as g}from"./chunk-AKQ3AFVI.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{a as m,g as L}from"./chunk-CN5NEJXG.js";import{o as a,q as x}from"./chunk-LMQPGVM7.js";import{b as u,i as _}from"./chunk-ITVCPC7G.js";import{c as v,e as N}from"./chunk-5M6IGE5G.js";import{b as l}from"./chunk-5PELJRUQ.js";var f,p,T=l(()=>{"use strict";f={stylePreferences:[],avoidedActions:[],pinnedParameters:[]},p=class extends Error{constructor(n,r,i,s){super(`Role '${r}' has ${i} active task(s) (${s.join(", ")}) and cannot be deleted without the force flag.`);this.roleId=n;this.roleName=r;this.activeTaskCount=i;this.taskStatuses=s;this.name="RoleHasActiveTasksError"}roleId;roleName;activeTaskCount;taskStatuses;code="ROLE_HAS_ACTIVE_TASKS"}});import*as R from"os";import*as C from"path";function g(e){return e.startsWith("~/")||e==="~"?C.join(R.homedir(),e.slice(1)):e}var S=l(()=>{"use strict";_()});function E(e){return k.includes(e)}function I(e){return A[e]}function B(){return k.map(e=>A[e])}function te(e,t=e!=="none"){return B().map(n=>J(n,e,t))}function J(e,t,n=t!=="none"){return process.platform==="darwin"?e.status==="runtime-enforced"&&(t!=="sandbox-exec"||!n)?{...e,availability:"runtime-unavailable",editable:!1,effectiveDisabledReason:"Current runtime has no macOS sandbox backend; Adam cannot enforce this capability on Roles."}:e.status==="runtime-enforced"?{...e,availability:"editable",editable:!0}:{...e,availability:e.status,editable:!1,effectiveDisabledReason:e.disabledReason}:{...e,availability:"platform-unsupported",editable:!1,effectiveDisabledReason:"macOS only"}}function re(e){if(!e?.length)return;for(let n of e)if(!E(n.id))throw new Error(`Unknown OS capability: ${n.id}`);let t=c(e);if(t?.length){for(let n of t){let r=I(n.id);if(r.status!=="runtime-enforced")throw new Error(`OS capability '${r.label}' is not editable in Role settings`);if(r.supportsTargets){if(!n.targets?.length)throw new Error(`OS capability '${r.label}' requires at least one target bundle id`);for(let i of n.targets)if(!F(i))throw new Error(`Invalid automation target bundle id: ${i}`)}else if(n.targets?.length)throw new Error(`OS capability '${r.label}' does not accept targets`)}return t}}function c(e){if(!e||e.length===0)return;let t=new Set,n=[];for(let r of e){if(!E(r.id))throw new Error(`Unknown OS capability: ${r.id}`);if(t.has(r.id))continue;t.add(r.id);let i=I(r.id),s={id:r.id};i.supportsTargets&&r.targets?.length&&(s.targets=[...new Set(r.targets.map(o=>o.trim()).filter(Boolean))]),n.push(s)}return n.length>0?n.sort((r,i)=>r.id.localeCompare(i.id)):void 0}function F(e){return U.test(e)}var k,A,U,w=l(()=>{"use strict";k=["location-services","calendars","contacts","files-and-folders","full-disk-access","homekit","media-and-apple-music","passkeys-access-for-web-browsers","photos","reminders","accessibility","app-management","automation","bluetooth","camera","developer-tools","focus","input-monitoring","local-network","microphone","motion-and-fitness","remote-desktop","screen-and-system-audio-recording","speech-recognition"],A={"location-services":{id:"location-services",label:"Location Services",description:"Access device location and region context.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},calendars:{id:"calendars",label:"Calendars",description:"Access Calendar data via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},contacts:{id:"contacts",label:"Contacts",description:"Access Contacts data via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"files-and-folders":{id:"files-and-folders",label:"Files & Folders",description:"Host-level file access categories managed outside Role sandboxing.",platform:"darwin",status:"host-only",disabledReason:"Role file boundaries are already controlled by visiblePaths and deniedReadPaths."},"full-disk-access":{id:"full-disk-access",label:"Full Disk Access",description:"Host-level macOS grant for protected storage locations.",platform:"darwin",status:"host-only",disabledReason:"This is a host app permission, not a Role-level control."},homekit:{id:"homekit",label:"HomeKit",description:"Access HomeKit devices and home automation data.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"media-and-apple-music":{id:"media-and-apple-music",label:"Media & Apple Music",description:"Access Apple Music and media library data.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"passkeys-access-for-web-browsers":{id:"passkeys-access-for-web-browsers",label:"Passkeys Access for Web Browsers",description:"Access passkeys for browser-integrated authentication.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},photos:{id:"photos",label:"Photos",description:"Access the Photos library via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},reminders:{id:"reminders",label:"Reminders",description:"Access Reminder data via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},accessibility:{id:"accessibility",label:"Accessibility",description:"Control desktop UI and accessibility automation surfaces.",platform:"darwin",status:"runtime-enforced"},"app-management":{id:"app-management",label:"App Management",description:"Manage or inspect other installed applications.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},automation:{id:"automation",label:"Automation",description:"Launch and control other apps via Apple Events.",platform:"darwin",status:"runtime-enforced",supportsTargets:!0},bluetooth:{id:"bluetooth",label:"Bluetooth",description:"Access nearby Bluetooth devices.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},camera:{id:"camera",label:"Camera",description:"Capture camera input.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"developer-tools":{id:"developer-tools",label:"Developer Tools",description:"Use system developer tooling privileges.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},focus:{id:"focus",label:"Focus",description:"Access Focus state and related automation.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"input-monitoring":{id:"input-monitoring",label:"Input Monitoring",description:"Observe keyboard and input device activity.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"local-network":{id:"local-network",label:"Local Network",description:"Discover and communicate with devices on the local network.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},microphone:{id:"microphone",label:"Microphone",description:"Capture microphone input.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"motion-and-fitness":{id:"motion-and-fitness",label:"Motion & Fitness",description:"Access motion and fitness sensor data.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"remote-desktop":{id:"remote-desktop",label:"Remote Desktop",description:"Control or observe remote desktop sessions.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"screen-and-system-audio-recording":{id:"screen-and-system-audio-recording",label:"Screen & System Audio Recording",description:"Capture the screen and system audio.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"speech-recognition":{id:"speech-recognition",label:"Speech Recognition",description:"Use system speech recognition services.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."}},U=/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/});function b(e){return{id:e.id,parentId:e.parent_id??void 0,status:e.status,prompt:e.prompt,originalPrompt:e.original_prompt??void 0,config:JSON.parse(e.config),result:e.result??void 0,error:e.error??void 0,sdkSessionId:e.sdk_session_id??void 0,templateId:e.template_id??void 0,roleId:e.role_id??void 0,stepId:e.step_id??void 0,sourceSessionId:e.source_session_id??void 0,deliverTo:e.deliver_to?JSON.parse(e.deliver_to):void 0,reportTo:e.report_to?JSON.parse(e.report_to):void 0,createdAt:e.created_at,startedAt:e.started_at??void 0,completedAt:e.completed_at??void 0,costUsd:e.cost_usd??void 0,costBreakdown:e.cost_breakdown?JSON.parse(e.cost_breakdown):void 0,tokenUsage:e.token_usage?JSON.parse(e.token_usage):void 0,numTurns:e.num_turns??void 0,totalDurationMs:e.total_duration_ms??void 0,blockReason:e.block_reason_json?JSON.parse(e.block_reason_json):void 0,traceId:e.trace_id??void 0,errorCategory:e.error_category??void 0,retryCount:e.retry_count}}function ae(e){a().prepare(`
1
+ import{a as m,g as L}from"./chunk-ISTUK7Q6.js";import{o as a,q as x}from"./chunk-ZEGZ2I35.js";import{b as u,i as _}from"./chunk-ITVCPC7G.js";import{c as v,e as N}from"./chunk-5M6IGE5G.js";import{b as l}from"./chunk-5PELJRUQ.js";var f,p,T=l(()=>{"use strict";f={stylePreferences:[],avoidedActions:[],pinnedParameters:[]},p=class extends Error{constructor(n,r,i,s){super(`Role '${r}' has ${i} active task(s) (${s.join(", ")}) and cannot be deleted without the force flag.`);this.roleId=n;this.roleName=r;this.activeTaskCount=i;this.taskStatuses=s;this.name="RoleHasActiveTasksError"}roleId;roleName;activeTaskCount;taskStatuses;code="ROLE_HAS_ACTIVE_TASKS"}});import*as R from"os";import*as C from"path";function g(e){return e.startsWith("~/")||e==="~"?C.join(R.homedir(),e.slice(1)):e}var S=l(()=>{"use strict";_()});function E(e){return k.includes(e)}function I(e){return A[e]}function B(){return k.map(e=>A[e])}function te(e,t=e!=="none"){return B().map(n=>J(n,e,t))}function J(e,t,n=t!=="none"){return process.platform==="darwin"?e.status==="runtime-enforced"&&(t!=="sandbox-exec"||!n)?{...e,availability:"runtime-unavailable",editable:!1,effectiveDisabledReason:"Current runtime has no macOS sandbox backend; Adam cannot enforce this capability on Roles."}:e.status==="runtime-enforced"?{...e,availability:"editable",editable:!0}:{...e,availability:e.status,editable:!1,effectiveDisabledReason:e.disabledReason}:{...e,availability:"platform-unsupported",editable:!1,effectiveDisabledReason:"macOS only"}}function re(e){if(!e?.length)return;for(let n of e)if(!E(n.id))throw new Error(`Unknown OS capability: ${n.id}`);let t=c(e);if(t?.length){for(let n of t){let r=I(n.id);if(r.status!=="runtime-enforced")throw new Error(`OS capability '${r.label}' is not editable in Role settings`);if(r.supportsTargets){if(!n.targets?.length)throw new Error(`OS capability '${r.label}' requires at least one target bundle id`);for(let i of n.targets)if(!F(i))throw new Error(`Invalid automation target bundle id: ${i}`)}else if(n.targets?.length)throw new Error(`OS capability '${r.label}' does not accept targets`)}return t}}function c(e){if(!e||e.length===0)return;let t=new Set,n=[];for(let r of e){if(!E(r.id))throw new Error(`Unknown OS capability: ${r.id}`);if(t.has(r.id))continue;t.add(r.id);let i=I(r.id),s={id:r.id};i.supportsTargets&&r.targets?.length&&(s.targets=[...new Set(r.targets.map(o=>o.trim()).filter(Boolean))]),n.push(s)}return n.length>0?n.sort((r,i)=>r.id.localeCompare(i.id)):void 0}function F(e){return U.test(e)}var k,A,U,w=l(()=>{"use strict";k=["location-services","calendars","contacts","files-and-folders","full-disk-access","homekit","media-and-apple-music","passkeys-access-for-web-browsers","photos","reminders","accessibility","app-management","automation","bluetooth","camera","developer-tools","focus","input-monitoring","local-network","microphone","motion-and-fitness","remote-desktop","screen-and-system-audio-recording","speech-recognition"],A={"location-services":{id:"location-services",label:"Location Services",description:"Access device location and region context.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},calendars:{id:"calendars",label:"Calendars",description:"Access Calendar data via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},contacts:{id:"contacts",label:"Contacts",description:"Access Contacts data via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"files-and-folders":{id:"files-and-folders",label:"Files & Folders",description:"Host-level file access categories managed outside Role sandboxing.",platform:"darwin",status:"host-only",disabledReason:"Role file boundaries are already controlled by visiblePaths and deniedReadPaths."},"full-disk-access":{id:"full-disk-access",label:"Full Disk Access",description:"Host-level macOS grant for protected storage locations.",platform:"darwin",status:"host-only",disabledReason:"This is a host app permission, not a Role-level control."},homekit:{id:"homekit",label:"HomeKit",description:"Access HomeKit devices and home automation data.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"media-and-apple-music":{id:"media-and-apple-music",label:"Media & Apple Music",description:"Access Apple Music and media library data.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"passkeys-access-for-web-browsers":{id:"passkeys-access-for-web-browsers",label:"Passkeys Access for Web Browsers",description:"Access passkeys for browser-integrated authentication.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},photos:{id:"photos",label:"Photos",description:"Access the Photos library via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},reminders:{id:"reminders",label:"Reminders",description:"Access Reminder data via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},accessibility:{id:"accessibility",label:"Accessibility",description:"Control desktop UI and accessibility automation surfaces.",platform:"darwin",status:"runtime-enforced"},"app-management":{id:"app-management",label:"App Management",description:"Manage or inspect other installed applications.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},automation:{id:"automation",label:"Automation",description:"Launch and control other apps via Apple Events.",platform:"darwin",status:"runtime-enforced",supportsTargets:!0},bluetooth:{id:"bluetooth",label:"Bluetooth",description:"Access nearby Bluetooth devices.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},camera:{id:"camera",label:"Camera",description:"Capture camera input.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"developer-tools":{id:"developer-tools",label:"Developer Tools",description:"Use system developer tooling privileges.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},focus:{id:"focus",label:"Focus",description:"Access Focus state and related automation.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"input-monitoring":{id:"input-monitoring",label:"Input Monitoring",description:"Observe keyboard and input device activity.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"local-network":{id:"local-network",label:"Local Network",description:"Discover and communicate with devices on the local network.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},microphone:{id:"microphone",label:"Microphone",description:"Capture microphone input.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"motion-and-fitness":{id:"motion-and-fitness",label:"Motion & Fitness",description:"Access motion and fitness sensor data.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"remote-desktop":{id:"remote-desktop",label:"Remote Desktop",description:"Control or observe remote desktop sessions.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"screen-and-system-audio-recording":{id:"screen-and-system-audio-recording",label:"Screen & System Audio Recording",description:"Capture the screen and system audio.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"speech-recognition":{id:"speech-recognition",label:"Speech Recognition",description:"Use system speech recognition services.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."}},U=/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/});function b(e){return{id:e.id,parentId:e.parent_id??void 0,status:e.status,prompt:e.prompt,originalPrompt:e.original_prompt??void 0,config:JSON.parse(e.config),result:e.result??void 0,error:e.error??void 0,sdkSessionId:e.sdk_session_id??void 0,templateId:e.template_id??void 0,roleId:e.role_id??void 0,stepId:e.step_id??void 0,sourceSessionId:e.source_session_id??void 0,deliverTo:e.deliver_to?JSON.parse(e.deliver_to):void 0,reportTo:e.report_to?JSON.parse(e.report_to):void 0,createdAt:e.created_at,startedAt:e.started_at??void 0,completedAt:e.completed_at??void 0,costUsd:e.cost_usd??void 0,costBreakdown:e.cost_breakdown?JSON.parse(e.cost_breakdown):void 0,tokenUsage:e.token_usage?JSON.parse(e.token_usage):void 0,numTurns:e.num_turns??void 0,totalDurationMs:e.total_duration_ms??void 0,blockReason:e.block_reason_json?JSON.parse(e.block_reason_json):void 0,traceId:e.trace_id??void 0,errorCategory:e.error_category??void 0,retryCount:e.retry_count}}function ae(e){a().prepare(`
2
2
  INSERT INTO tasks (id, parent_id, status, prompt, original_prompt, config, result, error,
3
3
  sdk_session_id, template_id, role_id, step_id, source_session_id, notify_targets, deliver_to, report_to,
4
4
  created_at, started_at, completed_at,
@@ -1 +1 @@
1
- import{g as u,h as n}from"./chunk-4ZG4UMAK.js";import{e as r}from"./chunk-3MROEPGR.js";var m=.995,i=.2,d=.3;function c(){try{let e=r().memory?.scope;return{decayBase:e?.decayBase??m,archiveThreshold:e?.archiveThreshold??i,emaAlpha:e?.emaAlpha??d}}catch{return{decayBase:m,archiveThreshold:i,emaAlpha:d}}}function l(e,s){if(e.successEma==null)return null;let a=Math.max(0,s-e.lastUsedAt),{decayBase:t}=c();return e.successEma*Math.pow(t,a)}function h(e,s){if(e.successEma==null)e.successEma=.5;else{let a=Math.max(0,s-e.lastUsedAt),{decayBase:t}=c();e.successEma=e.successEma*Math.pow(t,a)}e.lastUsedAt=s}function E(e,s){h(e,s),n(e.id,e.successEma,s)}function A(e,s,a){h(e,a);let{emaAlpha:t}=c(),o=(1-t)*e.successEma+t*s;e.successEma=o,n(e.id,o,a)}function B(e,s){let a=l(e,s);return a==null?!1:a<c().archiveThreshold}function v(e){u(e,"archived")}export{l as a,E as b,A as c,B as d,v as e};
1
+ import{g as u,h as n}from"./chunk-6SBLFYCU.js";import{e as r}from"./chunk-3MROEPGR.js";var m=.995,i=.2,d=.3;function c(){try{let e=r().memory?.scope;return{decayBase:e?.decayBase??m,archiveThreshold:e?.archiveThreshold??i,emaAlpha:e?.emaAlpha??d}}catch{return{decayBase:m,archiveThreshold:i,emaAlpha:d}}}function l(e,s){if(e.successEma==null)return null;let a=Math.max(0,s-e.lastUsedAt),{decayBase:t}=c();return e.successEma*Math.pow(t,a)}function h(e,s){if(e.successEma==null)e.successEma=.5;else{let a=Math.max(0,s-e.lastUsedAt),{decayBase:t}=c();e.successEma=e.successEma*Math.pow(t,a)}e.lastUsedAt=s}function E(e,s){h(e,s),n(e.id,e.successEma,s)}function A(e,s,a){h(e,a);let{emaAlpha:t}=c(),o=(1-t)*e.successEma+t*s;e.successEma=o,n(e.id,o,a)}function B(e,s){let a=l(e,s);return a==null?!1:a<c().archiveThreshold}function v(e){u(e,"archived")}export{l as a,E as b,A as c,B as d,v as e};
@@ -1,3 +1,3 @@
1
- import{b as m}from"./chunk-YEGUFMLJ.js";import{a as d,d as f}from"./chunk-4G4CKAXY.js";import{c as a}from"./chunk-EBZCHLYS.js";import{a as s}from"./chunk-J2VSAXVU.js";import{e as p}from"./chunk-3MROEPGR.js";import{c,h as g}from"./chunk-EZLBMUQD.js";function k(e,n,i){switch(n){case"wechat":return l(e);case"telegram":return e;case"slack":return w(e);case"email":return e;case"webhook":return JSON.stringify({result:e,taskId:i,timestamp:new Date().toISOString()});default:return l(e)}}function l(e){return e.replace(/^#{1,6}\s+/gm,"").replace(/\*\*(.+?)\*\*/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/_(.+?)_/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/```[\s\S]*?```/g,n=>n.replace(/```\w*\n?/g,"").trim()).replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\n{3,}/g,`
1
+ import{b as m}from"./chunk-YI2QQTZE.js";import{a as d,d as f}from"./chunk-NX3CIEZA.js";import{c as a}from"./chunk-XEXSXMWK.js";import{a as s}from"./chunk-J2VSAXVU.js";import{e as p}from"./chunk-3MROEPGR.js";import{c,h as g}from"./chunk-EZLBMUQD.js";function k(e,n,i){switch(n){case"wechat":return l(e);case"telegram":return e;case"slack":return w(e);case"email":return e;case"webhook":return JSON.stringify({result:e,taskId:i,timestamp:new Date().toISOString()});default:return l(e)}}function l(e){return e.replace(/^#{1,6}\s+/gm,"").replace(/\*\*(.+?)\*\*/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/_(.+?)_/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/```[\s\S]*?```/g,n=>n.replace(/```\w*\n?/g,"").trim()).replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\n{3,}/g,`
2
2
 
3
3
  `).trim()}function w(e){return e.replace(/\*\*(.+?)\*\*/g,"*$1*").replace(/\[([^\]]+)\]\(([^)]+)\)/g,"<$2|$1>")}f();g();var t=c("message-handler");function x(){try{let e=p().identity?.ownerViewerKey;if(typeof e=="string"&&e.trim().length>0)return e}catch{}return s.identity?.ownerViewerKey??"local-owner"}function u(e){if(e.type==="web"||e.type==="tui"||e.type==="api")return x();if(e.type!=="channel"||!e.channelId){t.warn({source:e},"Viewer identity unavailable for chat source"),r("chat source has no resolvable viewer identity",void 0);return}let i=a(e.channelId)?.viewerKey;if(typeof i=="string"&&i.trim().length>0)return i;t.warn({channelId:e.channelId},"Channel viewerKey missing; recent delivery context disabled"),r("channel viewerKey missing; recent delivery context disabled",e.channelId)}function E(e){if(e.type==="channel"){let o=a(e.channelId)?.viewerKey;if(typeof o=="string"&&o.trim().length>0)return o;t.warn({channelId:e.channelId},"Channel viewerKey missing; ledger recording skipped"),r("channel viewerKey missing; ledger recording skipped",e.channelId);return}let n=m(e.sessionId);if(!n){t.warn({sessionId:e.sessionId},"Session target missing; ledger recording skipped"),r("session target missing; ledger recording skipped",e.sessionId);return}return u(n.source)}function r(e,n){try{d({source:"viewer_identity",severity:"warning",sourceId:n,message:e})}catch{}}import v from"path";var h={".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".csv":"text/csv",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".mp3":"audio/mpeg",".ogg":"audio/ogg",".wav":"audio/wav",".amr":"audio/amr",".silk":"audio/x-silk",".md":"text/markdown",".html":"text/html",".json":"application/json",".xml":"text/xml",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm",".mkv":"video/x-matroska",".avi":"video/x-msvideo",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp"},y={"image/jpeg":".jpg","image/jpg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/bmp":".bmp","video/mp4":".mp4","video/quicktime":".mov","video/webm":".webm","video/x-matroska":".mkv","video/x-msvideo":".avi","audio/mpeg":".mp3","audio/ogg":".ogg","audio/wav":".wav","audio/amr":".amr","audio/x-silk":".silk","application/pdf":".pdf","application/zip":".zip","application/x-tar":".tar","application/gzip":".gz","text/plain":".txt","text/csv":".csv","text/markdown":".md","audio/mp3":".mp3","text/html":".html","application/json":".json","application/xml":".xml","text/xml":".xml","application/vnd.openxmlformats-officedocument.wordprocessingml.document":".docx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":".xlsx","application/vnd.openxmlformats-officedocument.presentationml.presentation":".pptx","application/msword":".doc","application/vnd.ms-excel":".xls","application/vnd.ms-powerpoint":".ppt"};function $(e){let n=v.extname(e).toLowerCase();return h[n]??"application/octet-stream"}function F(e){let n=e.split(";")[0].trim().toLowerCase();return y[n]??".bin"}export{k as a,l as b,x as c,u as d,E as e,$ as f,F as g};
@@ -1,4 +1,4 @@
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(`
1
+ import{o,q as k}from"./chunk-ZEGZ2I35.js";import{b as R}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 T(t,e){if(t!=="json"||typeof e!="string")return e;try{let n=JSON.parse(e);return n!==null&&typeof n=="object"?n:e}catch{return e}}function H(t){if(!t.roleId||t.roleId.trim()==="")throw new Error("createArtifact: roleId required (application-layer enforcement)");p(o(),t)}function p(t,e){let n=T(e.kind,e.value);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,
@@ -6,18 +6,18 @@ import{o,q as k}from"./chunk-LMQPGVM7.js";import{b}from"./chunk-5PELJRUQ.js";imp
6
6
  artifact_role
7
7
  )
8
8
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
9
- `).run(e.id,e.sourceKind,e.executionId??null,e.taskId??null,e.chatSessionId??null,e.stepId??null,e.roleId??null,e.key??null,e.kind,e.value!==void 0?JSON.stringify(e.value):null,e.blobPath??null,e.mime??null,e.originalFilename??null,e.sizeBytes,e.createdAt,e.locator??null,e.contentHash??null,e.retentionHint??null,e.encryptionClass??null,e.purpose??null,e.replaces??null,e.producedByRole??null,e.access??null,e.priority??null,e.artifactRole??null)}function y(t,e,n,i){let r=t.prepare(`
9
+ `).run(e.id,e.sourceKind,e.executionId??null,e.taskId??null,e.chatSessionId??null,e.stepId??null,e.roleId??null,e.key??null,e.kind,n!==void 0?JSON.stringify(n):null,e.blobPath??null,e.mime??null,e.originalFilename??null,e.sizeBytes,e.createdAt,e.locator??null,e.contentHash??null,e.retentionHint??null,e.encryptionClass??null,e.purpose??null,e.replaces??null,e.producedByRole??null,e.access??null,e.priority??null,e.artifactRole??null)}function y(t,e,n,i){let r=t.prepare(`
10
10
  SELECT * FROM artifacts
11
11
  WHERE source_kind = 'template_step' AND execution_id = ? AND step_id = ? AND key = ?
12
- `).get(e,n,i);return r?u(r):void 0}function v(t,e,n){return y(o(),t,e,n)}function H(t){let e=o().prepare("SELECT * FROM artifacts WHERE id = ?").get(t);return e?u(e):void 0}function h(t,e){let n=o(),i="SELECT * FROM artifacts WHERE execution_id = ?",r=[t];return e&&(i+=" AND step_id = ?",r.push(e)),i+=" ORDER BY created_at ASC",n.prepare(i).all(...r).map(u)}function L(t){return o().prepare("SELECT * FROM artifacts WHERE task_id = ? ORDER BY created_at ASC").all(t).map(u)}function P(t){return o().prepare("SELECT * FROM artifacts WHERE chat_session_id = ? ORDER BY created_at ASC").all(t).map(u)}function K(t,e){let n=o(),i="SELECT * FROM artifacts WHERE role_id = ?",r=[t];e?.sourceKind&&(i+=" AND source_kind = ?",r.push(e.sourceKind)),i+=" ORDER BY created_at ASC";let s=n.prepare(i).all(...r).map(u);return e?.mimePrefix&&(s=s.filter(a=>a.mime?.startsWith(e.mimePrefix))),s}function W(t){let e=o(),n=h(t);return e.prepare("DELETE FROM artifacts WHERE execution_id = ?").run(t),n}function z(t,e){let n=o(),i=h(t).filter(r=>r.stepId===e);return n.prepare("DELETE FROM artifacts WHERE execution_id = ? AND step_id = ?").run(t,e),i}function N(t){o().prepare("DELETE FROM artifacts WHERE id = ?").run(t)}function $(t){return o().prepare("DELETE FROM artifacts WHERE id = ?").run(t).changes>0}function T(t){if(!t||typeof t!="object")return!1;let e=t;return e.type!=="artifact_collection"||typeof e.outputAs!="string"||e.outputAs.length===0||!Array.isArray(e.items)?!1:e.items.every(n=>n!=null&&typeof n=="object"&&typeof n.artifactId=="string"&&n.artifactId.length>0&&typeof n.key=="string"&&n.key.length>0&&typeof n.sizeBytes=="number"&&Number.isFinite(n.sizeBytes)&&(n.filename===void 0||typeof n.filename=="string")&&(n.mime===void 0||typeof n.mime=="string")&&(n.purpose===void 0||typeof n.purpose=="string"))}function j(t,e,n){return g(o(),t,e,n)}function q(t,e,n,i){let r=o();return r.transaction(()=>{let s=y(r,t,e,n);if(!s||s.kind!=="json"||!T(s.value))throw new Error(`Artifact collection manifest not found at ${e}/${n}`);let a=g(r,t,e,i.key??"",new Set([n])),l={...i,key:a};p(r,l);let d={...s.value,items:[...s.value.items,m(l)]};return{manifestArtifact:I(r,s,d),childArtifact:l}})()}function U(t,e,n,i,r){let c=o();return c.transaction(()=>{let a=y(c,t,e,n);if(!a||a.id!==i.id)throw new Error(`Primary artifact changed before collection conversion at ${e}/${n}`);if(a.kind!=="file"||!a.blobPath)throw new Error(`Primary artifact at ${e}/${n} is not a file`);let l=g(c,t,e,a.originalFilename??a.key??n,new Set([n]));c.prepare("UPDATE artifacts SET key = ? WHERE id = ?").run(l,a.id);let d={...a,key:l},A=g(c,t,e,r.key??"",new Set([n,l])),f={...r,key:A};p(c,f);let _={type:"artifact_collection",outputAs:n,items:[m(d),m(f)]},E={id:x(),sourceKind:i.sourceKind,executionId:t,stepId:e,key:n,kind:"json",value:_,sizeBytes:R(_),createdAt:Date.now(),purpose:"data",roleId:i.roleId};return p(c,E),{manifestArtifact:E,childArtifact:f,rekeyedPrimaryArtifact:d}})()}function Y(t){return o().prepare(`
12
+ `).get(e,n,i);return r?u(r):void 0}function L(t,e,n){return y(o(),t,e,n)}function P(t){let e=o().prepare("SELECT * FROM artifacts WHERE id = ?").get(t);return e?u(e):void 0}function h(t,e){let n=o(),i="SELECT * FROM artifacts WHERE execution_id = ?",r=[t];return e&&(i+=" AND step_id = ?",r.push(e)),i+=" ORDER BY created_at ASC",n.prepare(i).all(...r).map(u)}function v(t){return o().prepare("SELECT * FROM artifacts WHERE task_id = ? ORDER BY created_at ASC").all(t).map(u)}function K(t){return o().prepare("SELECT * FROM artifacts WHERE chat_session_id = ? ORDER BY created_at ASC").all(t).map(u)}function z(t,e){let n=o(),i="SELECT * FROM artifacts WHERE role_id = ?",r=[t];e?.sourceKind&&(i+=" AND source_kind = ?",r.push(e.sourceKind)),i+=" ORDER BY created_at ASC";let s=n.prepare(i).all(...r).map(u);return e?.mimePrefix&&(s=s.filter(a=>a.mime?.startsWith(e.mimePrefix))),s}function N(t){let e=o(),n=h(t);return e.prepare("DELETE FROM artifacts WHERE execution_id = ?").run(t),n}function W(t,e){let n=o(),i=h(t).filter(r=>r.stepId===e);return n.prepare("DELETE FROM artifacts WHERE execution_id = ? AND step_id = ?").run(t,e),i}function $(t){o().prepare("DELETE FROM artifacts WHERE id = ?").run(t)}function j(t){return o().prepare("DELETE FROM artifacts WHERE id = ?").run(t).changes>0}function B(t){if(!t||typeof t!="object")return!1;let e=t;return e.type!=="artifact_collection"||typeof e.outputAs!="string"||e.outputAs.length===0||!Array.isArray(e.items)?!1:e.items.every(n=>n!=null&&typeof n=="object"&&typeof n.artifactId=="string"&&n.artifactId.length>0&&typeof n.key=="string"&&n.key.length>0&&typeof n.sizeBytes=="number"&&Number.isFinite(n.sizeBytes)&&(n.filename===void 0||typeof n.filename=="string")&&(n.mime===void 0||typeof n.mime=="string")&&(n.purpose===void 0||typeof n.purpose=="string"))}function q(t,e,n){return g(o(),t,e,n)}function U(t,e,n,i){let r=o();return r.transaction(()=>{let s=y(r,t,e,n);if(!s||s.kind!=="json"||!B(s.value))throw new Error(`Artifact collection manifest not found at ${e}/${n}`);let a=g(r,t,e,i.key??"",new Set([n])),l={...i,key:a};p(r,l);let d={...s.value,items:[...s.value.items,m(l)]};return{manifestArtifact:M(r,s,d),childArtifact:l}})()}function J(t,e,n,i,r){let c=o();return c.transaction(()=>{let a=y(c,t,e,n);if(!a||a.id!==i.id)throw new Error(`Primary artifact changed before collection conversion at ${e}/${n}`);if(a.kind!=="file"||!a.blobPath)throw new Error(`Primary artifact at ${e}/${n} is not a file`);let l=g(c,t,e,a.originalFilename??a.key??n,new Set([n]));c.prepare("UPDATE artifacts SET key = ? WHERE id = ?").run(l,a.id);let d={...a,key:l},A=g(c,t,e,r.key??"",new Set([n,l])),f={...r,key:A};p(c,f);let _={type:"artifact_collection",outputAs:n,items:[m(d),m(f)]},E={id:x(),sourceKind:i.sourceKind,executionId:t,stepId:e,key:n,kind:"json",value:_,sizeBytes:b(_),createdAt:Date.now(),purpose:"data",roleId:i.roleId};return p(c,E),{manifestArtifact:E,childArtifact:f,rekeyedPrimaryArtifact:d}})()}function Y(t){return o().prepare(`
13
13
  SELECT id
14
14
  FROM template_executions
15
15
  WHERE status != 'running' AND COALESCE(completed_at, started_at) < ?
16
16
  `).all(t).map(i=>i.id)}function g(t,e,n,i,r=new Set){let c=t.prepare(`
17
17
  SELECT key FROM artifacts
18
18
  WHERE execution_id = ? AND step_id = ?
19
- `).all(e,n),s=new Set(c.map(l=>l.key));for(let l of r)s.add(l);let a=B(i);if(!s.has(a))return a;for(let l=2;l<1e4;l++){let d=`-${l}`,f=`${a.slice(0,Math.max(1,256-d.length))}${d}`;if(!s.has(f))return f}throw new Error(`Unable to allocate unique artifact key for ${n}/${i}`)}function B(t){let e=t.replace(/\\/g,"/"),i=S(e).replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,256);return!i||i==="."||i===".."?"artifact":C.test(i)?i:"artifact"}function m(t){return{artifactId:t.id,key:t.key??"",...t.originalFilename?{filename:t.originalFilename}:{},...t.mime?{mime:t.mime}:{},sizeBytes:t.sizeBytes,...t.purpose?{purpose:t.purpose}:{},...t.artifactRole?{role:t.artifactRole}:{}}}function I(t,e,n){let i=R(n);return t.prepare(`
19
+ `).all(e,n),s=new Set(c.map(l=>l.key));for(let l of r)s.add(l);let a=I(i);if(!s.has(a))return a;for(let l=2;l<1e4;l++){let d=`-${l}`,f=`${a.slice(0,Math.max(1,256-d.length))}${d}`;if(!s.has(f))return f}throw new Error(`Unable to allocate unique artifact key for ${n}/${i}`)}function I(t){let e=t.replace(/\\/g,"/"),i=S(e).replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,256);return!i||i==="."||i===".."?"artifact":C.test(i)?i:"artifact"}function m(t){return{artifactId:t.id,key:t.key??"",...t.originalFilename?{filename:t.originalFilename}:{},...t.mime?{mime:t.mime}:{},sizeBytes:t.sizeBytes,...t.purpose?{purpose:t.purpose}:{},...t.artifactRole?{role:t.artifactRole}:{}}}function M(t,e,n){let i=b(n);return t.prepare(`
20
20
  UPDATE artifacts
21
21
  SET value_json = ?, size_bytes = ?
22
22
  WHERE id = ?
23
- `).run(JSON.stringify(n),i,e.id),{...e,value:n,sizeBytes:i}}function R(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function J(t,e){let n=[],i=[];t.sourceKind&&(n.push("source_kind = ?"),i.push(t.sourceKind)),t.mimePrefix&&(n.push("mime LIKE ? ESCAPE '\\'"),i.push(t.mimePrefix.replace(/[\\%_]/g,"\\$&")+"%")),t.roleId&&(n.push("role_id = ?"),i.push(t.roleId)),t.taskId&&(n.push("task_id = ?"),i.push(t.taskId)),t.executionId&&(n.push("execution_id = ?"),i.push(t.executionId)),t.chatSessionId&&(n.push("chat_session_id = ?"),i.push(t.chatSessionId)),t.from!==void 0&&(n.push("created_at >= ?"),i.push(t.from)),t.to!==void 0&&(n.push("created_at <= ?"),i.push(t.to)),t.deliveryStatus&&(n.push("(EXISTS (SELECT 1 FROM delivery_log dl WHERE dl.status = ? AND (dl.task_id = artifacts.task_id OR dl.task_id = artifacts.execution_id)))"),i.push(t.deliveryStatus));let r=n.length?"WHERE "+n.join(" AND "):"",c=o(),s=c.prepare(`SELECT COUNT(*) AS n FROM artifacts ${r}`).get(...i);return{artifacts:c.prepare(`SELECT * FROM artifacts ${r} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...i,e.limit,e.offset).map(u),total:s.n}}var C,M=b(()=>{k();C=/^[\p{L}0-9._-]{1,256}$/u});export{w as a,v as b,H as c,h as d,L as e,P as f,K as g,W as h,z as i,N as j,$ as k,T as l,j as m,q as n,U as o,Y as p,J as q,M as r};
23
+ `).run(JSON.stringify(n),i,e.id),{...e,value:n,sizeBytes:i}}function b(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function V(t,e){let n=[],i=[];t.sourceKind&&(n.push("source_kind = ?"),i.push(t.sourceKind)),t.mimePrefix&&(n.push("mime LIKE ? ESCAPE '\\'"),i.push(t.mimePrefix.replace(/[\\%_]/g,"\\$&")+"%")),t.roleId&&(n.push("role_id = ?"),i.push(t.roleId)),t.taskId&&(n.push("task_id = ?"),i.push(t.taskId)),t.executionId&&(n.push("execution_id = ?"),i.push(t.executionId)),t.chatSessionId&&(n.push("chat_session_id = ?"),i.push(t.chatSessionId)),t.from!==void 0&&(n.push("created_at >= ?"),i.push(t.from)),t.to!==void 0&&(n.push("created_at <= ?"),i.push(t.to)),t.deliveryStatus&&(n.push("(EXISTS (SELECT 1 FROM delivery_log dl WHERE dl.status = ? AND (dl.task_id = artifacts.task_id OR dl.task_id = artifacts.execution_id)))"),i.push(t.deliveryStatus));let r=n.length?"WHERE "+n.join(" AND "):"",c=o(),s=c.prepare(`SELECT COUNT(*) AS n FROM artifacts ${r}`).get(...i);return{artifacts:c.prepare(`SELECT * FROM artifacts ${r} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...i,e.limit,e.offset).map(u),total:s.n}}var C,w=R(()=>{k();C=/^[\p{L}0-9._-]{1,256}$/u});export{T as a,H as b,L as c,P as d,h as e,v as f,K as g,z as h,N as i,W as j,$ as k,j as l,B as m,q as n,U as o,J as p,Y as q,V as r,w as s};
@@ -1,4 +1,4 @@
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(`
1
+ import{F as R,L as E}from"./chunk-3JTHJ3FZ.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{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(`
1
+ import{h as c}from"./chunk-AKQ3AFVI.js";import{K as u,L as p}from"./chunk-3JTHJ3FZ.js";import{o as s,q as f}from"./chunk-ZEGZ2I35.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{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(`
1
+ import{D as M,L as D}from"./chunk-3JTHJ3FZ.js";import{o as u,q as O}from"./chunk-ZEGZ2I35.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)
@@ -1 +1 @@
1
- import{g as He}from"./chunk-WDMSZS4W.js";import{a as Ke,b as k,c as Me,d as B,e as Xe}from"./chunk-NNMQGISW.js";import{b as Je,c as Ye,f as re,g as ie}from"./chunk-VZL2DGC4.js";import{a as Ve,b as ze,c as E,d as se,e as F,f as xe,g as z,i as Qe}from"./chunk-EBZCHLYS.js";import{e as V}from"./chunk-3MROEPGR.js";import{c as y,h as S}from"./chunk-EZLBMUQD.js";import{z as g}from"zod/v4";import{v4 as Ps}from"uuid";var Ze="__redacted__",rn=/token|secret|password|passwd|api[-_]?key|credential|private[-_]?key|access[-_]?key/i;function an(t){return rn.test(t)}function on(t){if(!t)return{};let e={};for(let[n,r]of Object.entries(t))an(n)&&typeof r=="string"&&r.length>0?e[n]=Ze:e[n]=r;return e}function Q(t){return{...t,config:on(t.config)}}function et(t,e){let n={...t};for(let[r,s]of Object.entries(t))s===Ze&&(e&&r in e?n[r]=e[r]:delete n[r]);return n}import{randomUUID as at}from"crypto";import dn from"crypto";var tt="2.1.7",ae="bot";function un(t){let e=t.split(".").map(i=>parseInt(i,10)),n=e[0]??0,r=e[1]??0,s=e[2]??0;return(n&255)<<16|(r&255)<<8|s&255}var Ce=un(tt),cn=35e3,nt=15e3,ln=1e4;function oe(){return{channel_version:tt}}function mn(t){return t.endsWith("/")?t:`${t}/`}function gn(){let t=dn.randomBytes(4).readUInt32BE(0);return Buffer.from(String(t),"utf-8").toString("base64")}function pn(t){let e={"Content-Type":"application/json",AuthorizationType:"ilink_bot_token","Content-Length":String(Buffer.byteLength(t.body,"utf-8")),"X-WECHAT-UIN":gn(),"iLink-App-Id":ae,"iLink-App-ClientVersion":String(Ce)};return t.token?.trim()&&(e.Authorization=`Bearer ${t.token.trim()}`),t.routeTag&&(e.SKRouteTag=t.routeTag),e}async function de(t){let e=mn(t.baseUrl),n=new URL(t.endpoint,e),r=pn({token:t.token,routeTag:t.routeTag,body:t.body}),s=new AbortController,i=setTimeout(()=>s.abort(),t.timeoutMs);try{let a=await fetch(n.toString(),{method:"POST",headers:r,body:t.body,signal:s.signal});clearTimeout(i);let o=await a.text();if(!a.ok)throw new Error(`${t.label} ${a.status}: ${o}`);return o}catch(a){throw clearTimeout(i),a}}async function st(t){let e=t.timeoutMs??cn;try{let n=await de({baseUrl:t.baseUrl,endpoint:"ilink/bot/getupdates",body:JSON.stringify({get_updates_buf:t.get_updates_buf??"",base_info:oe()}),token:t.token,routeTag:t.routeTag,timeoutMs:e,label:"getUpdates"});return JSON.parse(n)}catch(n){if(n instanceof Error&&n.name==="AbortError")return{ret:0,msgs:[],get_updates_buf:t.get_updates_buf};throw n}}var fn={[-2]:2,[-3]:3},hn=1e3;async function H(t){let e=(await import("./logger-TEZSHFTZ.js")).getLogger("channels"),n=new Map;for(;;){let r=await de({baseUrl:t.baseUrl,endpoint:"ilink/bot/sendmessage",body:JSON.stringify({...t.body,base_info:oe()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??nt,label:"sendMessage"});e.info({status:200,responseBody:r.slice(0,300)},"apiFetch sendMessage response");try{let s=JSON.parse(r);if(s.ret&&s.ret!==0){let i=fn[s.ret],a=(n.get(s.ret)??0)+1;if(n.set(s.ret,a),i!==void 0&&a<i){e.warn({ret:s.ret,attempt:a,maxRetries:i},"sendMessage: retriable iLink error, retrying"),await new Promise(o=>setTimeout(o,hn*a));continue}throw e.error({ret:s.ret,errmsg:s.errmsg,attempt:a},"sendMessage: iLink API error, no more retries"),new Error(`sendMessage failed: iLink ret=${s.ret}${s.errmsg?` errmsg=${s.errmsg}`:""}`)}}catch(s){if(s instanceof SyntaxError)e.warn({rawText:r.slice(0,200)},"sendMessage: non-JSON response, treating as success");else throw s}return}}async function rt(t){await de({baseUrl:t.baseUrl,endpoint:"ilink/bot/sendtyping",body:JSON.stringify({...t.body,base_info:oe()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??ln,label:"sendTyping"})}async function it(t){let e=await de({baseUrl:t.baseUrl,endpoint:"ilink/bot/getuploadurl",body:JSON.stringify({filekey:t.filekey,media_type:t.media_type,to_user_id:t.to_user_id,rawsize:t.rawsize,rawfilemd5:t.rawfilemd5,filesize:t.filesize,thumb_rawsize:t.thumb_rawsize,thumb_rawfilemd5:t.thumb_rawfilemd5,thumb_filesize:t.thumb_filesize,no_need_thumb:t.no_need_thumb,aeskey:t.aeskey,base_info:oe()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??nt,label:"getUploadUrl"});return JSON.parse(e)}var yn=5*6e4,bn=35e3,ot="3",T=new Map;function Se(t){return Date.now()-t.startedAt<yn}function wn(){for(let[t,e]of T)Se(e)||T.delete(t)}async function dt(t,e,n){let r=t.endsWith("/")?t:`${t}/`,s=new URL(`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(e)}`,r),i={"iLink-App-Id":ae};n&&(i.SKRouteTag=n);let a=await fetch(s.toString(),{headers:i});if(!a.ok){let o=await a.text().catch(()=>"(unreadable)");throw new Error(`Failed to fetch QR code: ${a.status} ${a.statusText} body=${o}`)}return await a.json()}async function _n(t,e,n){let r=t.endsWith("/")?t:`${t}/`,s=new URL(`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(e)}`,r),i={"iLink-App-Id":ae,"iLink-App-ClientVersion":String(Ce)};n&&(i.SKRouteTag=n);let a=new AbortController,o=setTimeout(()=>a.abort(),bn);try{let d=await fetch(s.toString(),{headers:i,signal:a.signal});clearTimeout(o);let c=await d.text();if(!d.ok)throw new Error(`Failed to poll QR status: ${d.status} ${d.statusText}`);return JSON.parse(c)}catch(d){if(clearTimeout(o),d instanceof Error&&d.name==="AbortError")return{status:"wait"};throw d}}async function ut(t){let e=t.accountId||at();wn();let n=T.get(e);if(!t.force&&n&&Se(n)&&n.qrcodeUrl)return{qrcodeUrl:n.qrcodeUrl,message:"QR code ready. Scan with WeChat.",sessionKey:e};if(!t.apiBaseUrl)return{message:"No baseUrl configured for this WeChat channel.",sessionKey:e};try{let r=t.botType||ot,s=await dt(t.apiBaseUrl,r,t.routeTag),i={sessionKey:e,id:at(),qrcode:s.qrcode,qrcodeUrl:s.qrcode_img_content,startedAt:Date.now()};return T.set(e,i),{qrcodeUrl:s.qrcode_img_content,message:"Scan the QR code with WeChat to connect.",sessionKey:e}}catch(r){return{message:`Failed to start login: ${String(r)}`,sessionKey:e}}}var In=3;async function ct(t){let e=T.get(t.sessionKey);if(!e)return{connected:!1,message:"No active login session. Start QR login first."};if(!Se(e))return T.delete(t.sessionKey),{connected:!1,message:"QR code expired. Please start again."};let n=Math.max(t.timeoutMs??48e4,1e3),r=Date.now()+n,s=1;for(;Date.now()<r;){try{let i=await _n(t.apiBaseUrl,e.qrcode,t.routeTag);switch(e.status=i.status,i.status){case"wait":break;case"scaned":break;case"expired":{if(s++,s>In)return T.delete(t.sessionKey),{connected:!1,message:"Login timeout: QR expired multiple times."};try{let a=t.botType||ot,o=await dt(t.apiBaseUrl,a,t.routeTag);e.qrcode=o.qrcode,e.qrcodeUrl=o.qrcode_img_content,e.startedAt=Date.now()}catch(a){return T.delete(t.sessionKey),{connected:!1,message:`QR refresh failed: ${String(a)}`}}break}case"confirmed":return i.ilink_bot_id?(T.delete(t.sessionKey),{connected:!0,botToken:i.bot_token,accountId:i.ilink_bot_id,baseUrl:i.baseurl,userId:i.ilink_user_id,message:"Connected to WeChat successfully!"}):(T.delete(t.sessionKey),{connected:!1,message:"Login failed: server did not return bot ID."})}}catch(i){return T.delete(t.sessionKey),{connected:!1,message:`Login failed: ${String(i)}`}}await new Promise(i=>setTimeout(i,1e3))}return T.delete(t.sessionKey),{connected:!1,message:"Login timeout. Please try again."}}import R from"fs";import*as M from"fs/promises";import x from"path";import{homedir as fe}from"os";var ue={IMAGE:1,VIDEO:2,FILE:3,VOICE:4},K={NONE:0,USER:1,BOT:2},_={NONE:0,TEXT:1,IMAGE:2,VOICE:3,FILE:4,VIDEO:5},X={NEW:0,GENERATING:1,FINISH:2},lt={TYPING:1,CANCEL:2};S();var En=y("channels"),Re=-14,ce=3600*1e3,$=new Map;function mt(t){let e=Date.now()+ce;$.set(t,e),En.info({channelId:t},`Session paused until ${new Date(e).toISOString()} (${ce/1e3}s)`)}function le(t){let e=$.get(t);return e===void 0?!1:Date.now()>=e?($.delete(t),!1):!0}function gt(t){let e=$.get(t);if(e===void 0)return 0;let n=e-Date.now();return n<=0?($.delete(t),0):n}function pt(t){$.delete(t)}S();import*as ge from"fs/promises";import Tt from"path";import{homedir as Sn}from"os";import{createCipheriv as Tn,createDecipheriv as xn}from"crypto";function ft(t,e){let n=Tn("aes-128-ecb",e,null);return Buffer.concat([n.update(t),n.final()])}function ht(t,e){let n=xn("aes-128-ecb",e,null);return Buffer.concat([n.update(t),n.final()])}function yt(t){return Math.ceil((t+1)/16)*16}function Ae(t,e){return`${e}/download?encrypted_query_param=${encodeURIComponent(t)}`}function bt(t){return`${t.cdnBaseUrl}/upload?encrypted_query_param=${encodeURIComponent(t.uploadParam)}&filekey=${encodeURIComponent(t.filekey)}`}S();var Xs=y("channels");function Mn(t){let e=Buffer.from(t,"base64");if(e.length===16)return e;if(e.length===32&&/^[0-9a-fA-F]{32}$/.test(e.toString("ascii")))return Buffer.from(e.toString("ascii"),"hex");throw new Error(`aes_key must decode to 16 raw bytes or 32-char hex, got ${e.length} bytes`)}async function wt(t){let e=await fetch(t);if(!e.ok)throw new Error(`CDN download ${e.status} ${e.statusText}`);return Buffer.from(await e.arrayBuffer())}async function J(t){let{encryptQueryParam:e,aesKeyBase64:n,cdnBaseUrl:r,fullUrl:s}=t,i=Mn(n),a=s?.trim()||(e?Ae(e,r):null);if(!a)throw new Error("CDN download: need full_url or encrypt_query_param");let o=await wt(a);return ht(o,i)}async function _t(t){let{encryptQueryParam:e,cdnBaseUrl:n,fullUrl:r}=t,s=r?.trim()||(e?Ae(e,n):null);if(!s)throw new Error("CDN download: need full_url or encrypt_query_param");return wt(s)}S();var me=y("channels"),It=24e3;function Cn(t,e){let n=t.byteLength,r=44+n,s=Buffer.allocUnsafe(r),i=0;return s.write("RIFF",i),i+=4,s.writeUInt32LE(r-8,i),i+=4,s.write("WAVE",i),i+=4,s.write("fmt ",i),i+=4,s.writeUInt32LE(16,i),i+=4,s.writeUInt16LE(1,i),i+=2,s.writeUInt16LE(1,i),i+=2,s.writeUInt32LE(e,i),i+=4,s.writeUInt32LE(e*2,i),i+=4,s.writeUInt16LE(2,i),i+=2,s.writeUInt16LE(16,i),i+=2,s.write("data",i),i+=4,s.writeUInt32LE(n,i),i+=4,Buffer.from(t.buffer,t.byteOffset,t.byteLength).copy(s,i),s}async function Et(t){try{let{decode:e}=await import("silk-wasm");me.debug(`silkToWav: decoding ${t.length} bytes of SILK`);let n=await e(t,It);me.debug(`silkToWav: decoded duration=${n.duration}ms pcmBytes=${n.data.byteLength}`);let r=Cn(n.data,It);return me.debug(`silkToWav: WAV size=${r.length}`),r}catch(e){return me.warn(`silkToWav: transcode failed, will use raw silk err=${String(e)}`),null}}var N=y("channels"),xt=100*1024*1024;function Rn(t){return ie(t)??".bin"}async function Y(t,e,n,r,s=xt,i){if(t.length>s)throw new Error(`Media too large: ${t.length} bytes exceeds ${s} bytes`);let a=Tt.join(Sn(),".adam","wechat","media",r,n);await ge.mkdir(a,{recursive:!0});let o;if(i&&/^[a-zA-Z0-9._-]+$/.test(i))o=i;else{let c=e?Rn(e):".bin",u=Date.now(),p=Math.random().toString(36).slice(2,7);o=`${u}-${p}${c}`}let d=Tt.join(a,o);return await ge.writeFile(d,t),N.debug(`saveMedia: saved ${t.length} bytes to ${d}`),d}async function Mt(t,e){let{cdnBaseUrl:n,channelId:r}=e;if(t.type===_.IMAGE){let s=t.image_item;if(!s?.media?.encrypt_query_param&&!s?.media?.full_url)return null;let i=s.aeskey?Buffer.from(s.aeskey,"hex").toString("base64"):s.media?.aes_key;try{let a=i?await J({encryptQueryParam:s.media?.encrypt_query_param,aesKeyBase64:i,cdnBaseUrl:n,fullUrl:s.media?.full_url}):await _t({encryptQueryParam:s.media?.encrypt_query_param,cdnBaseUrl:n,fullUrl:s.media?.full_url});return{path:await Y(a,"image/png","inbound",r),mimeType:"image/png",type:"image"}}catch(a){return N.error({channelId:r},`Image download/decrypt failed: ${String(a)}`),null}}if(t.type===_.VOICE){let s=t.voice_item;if(!s?.media?.encrypt_query_param&&!s?.media?.full_url||!s?.media?.aes_key)return null;try{let i=await J({encryptQueryParam:s.media.encrypt_query_param,aesKeyBase64:s.media.aes_key,cdnBaseUrl:n,fullUrl:s.media.full_url}),a=await Et(i);if(a){let o=await Y(a,"audio/wav","inbound",r);return N.debug(`Voice: saved WAV to ${o}`),{path:o,mimeType:"audio/wav",type:"audio"}}else{let o=await Y(i,"audio/silk","inbound",r);return N.debug(`Voice: silk transcode unavailable, saved raw SILK to ${o}`),{path:o,mimeType:"audio/silk",type:"audio"}}}catch(i){return N.error({channelId:r},`Voice download/transcode failed: ${String(i)}`),null}}if(t.type===_.FILE){let s=t.file_item;if(!s?.media?.encrypt_query_param&&!s?.media?.full_url||!s?.media?.aes_key)return null;try{let i=await J({encryptQueryParam:s.media.encrypt_query_param,aesKeyBase64:s.media.aes_key,cdnBaseUrl:n,fullUrl:s.media.full_url}),a=re(s.file_name??"file.bin");return{path:await Y(i,a,"inbound",r,xt,s.file_name),mimeType:a,type:"file"}}catch(i){return N.error({channelId:r},`File download failed: ${String(i)}`),null}}if(t.type===_.VIDEO){let s=t.video_item;if(!s?.media?.encrypt_query_param&&!s?.media?.full_url||!s?.media?.aes_key)return null;try{let i=await J({encryptQueryParam:s.media.encrypt_query_param,aesKeyBase64:s.media.aes_key,cdnBaseUrl:n,fullUrl:s.media.full_url});return{path:await Y(i,"video/mp4","inbound",r),mimeType:"video/mp4",type:"video"}}catch(i){return N.error({channelId:r},`Video download failed: ${String(i)}`),null}}return null}import Rt from"path";import ke from"crypto";import An from"fs/promises";S();var O=y("channels"),pe=3;async function kn(t){let{buf:e,uploadFullUrl:n,uploadParam:r,filekey:s,cdnBaseUrl:i,label:a,aeskey:o}=t,d=ft(e,o),c=n?.trim(),u;if(c)u=c;else if(r)u=bt({cdnBaseUrl:i,uploadParam:r,filekey:s});else throw new Error(`${a}: CDN upload URL missing (need upload_full_url or upload_param)`);O.debug(`${a}: CDN POST url=${u} ciphertextSize=${d.length}`);let p,f;for(let m=1;m<=pe;m++)try{let l=await fetch(u,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:new Uint8Array(d)});if(l.status>=400&&l.status<500){let b=l.headers.get("x-error-message")??await l.text();throw O.error(`${a}: CDN client error attempt=${m} status=${l.status} errMsg=${b}`),new Error(`CDN upload client error ${l.status}: ${b}`)}if(l.status!==200){let b=l.headers.get("x-error-message")??`status ${l.status}`;throw O.error(`${a}: CDN server error attempt=${m} status=${l.status} errMsg=${b}`),new Error(`CDN upload server error: ${b}`)}if(p=l.headers.get("x-encrypted-param")??void 0,!p)throw O.error(`${a}: CDN response missing x-encrypted-param header attempt=${m}`),new Error("CDN upload response missing x-encrypted-param header");O.debug(`${a}: CDN upload success attempt=${m}`);break}catch(l){if(f=l,l instanceof Error&&l.message.includes("client error"))throw l;m<pe?O.warn(`${a}: attempt ${m} failed, retrying... err=${String(l)}`):O.error(`${a}: all ${pe} attempts failed err=${String(l)}`)}if(!p)throw f instanceof Error?f:new Error(`CDN upload failed after ${pe} attempts`);return{downloadParam:p}}async function Pe(t){let{filePath:e,toUserId:n,opts:r,cdnBaseUrl:s,mediaType:i,label:a}=t,o=await An.readFile(e),d=o.length,c=ke.createHash("md5").update(o).digest("hex"),u=yt(d),p=ke.randomBytes(16).toString("hex"),f=ke.randomBytes(16);O.debug(`${a}: file=${e} rawsize=${d} filesize=${u} md5=${c} filekey=${p}`);let m=await it({...r,filekey:p,media_type:i,to_user_id:n,rawsize:d,rawfilemd5:c,filesize:u,no_need_thumb:!0,aeskey:f.toString("hex")}),l=m.upload_full_url?.trim(),b=m.upload_param;if(!l&&!b)throw new Error(`${a}: getUploadUrl returned no upload URL (need upload_full_url or upload_param)`);let{downloadParam:L}=await kn({buf:o,uploadFullUrl:l||void 0,uploadParam:b??void 0,filekey:p,cdnBaseUrl:s,aeskey:f,label:`${a}[orig filekey=${p}]`});return{filekey:p,downloadEncryptedQueryParam:L,aeskey:f.toString("hex"),fileSize:d,fileSizeCiphertext:u}}async function Ct(t){return Pe({...t,mediaType:ue.IMAGE,label:"uploadImageToWeixin"})}async function St(t){return Pe({...t,mediaType:ue.VIDEO,label:"uploadVideoToWeixin"})}async function Ue(t){return Pe({...t,mediaType:ue.FILE,label:"uploadFileAttachmentToWeixin"})}S();var Z=y("channels");function Pn(){return`adam-wechat-${Date.now()}-${Math.random().toString(36).slice(2,7)}`}function Un(t){let e=t;return e=e.replace(/```[^\n]*\n?([\s\S]*?)```/g,(n,r)=>r.trim()),e=e.replace(/!\[[^\]]*\]\([^)]*\)/g,""),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/^\|[\s:|-]+\|$/gm,""),e=e.replace(/^\|(.+)\|$/gm,(n,r)=>r.split("|").map(s=>s.trim()).join(" ")),e}async function ve(t){let{to:e,text:n,mediaItem:r,opts:s,label:i}=t,a=[],o=Un(n);o&&a.push({type:_.TEXT,text_item:{text:o}}),a.push(r);let d="";for(let c of a){d=Pn();let u={msg:{from_user_id:"",to_user_id:e,client_id:d,message_type:K.BOT,message_state:X.FINISH,item_list:[c],context_token:s.contextToken}};await H({baseUrl:s.baseUrl,token:s.token,routeTag:s.routeTag,body:u})}return Z.debug(`${i}: sent to=${e} messageId=${d}`),{messageId:d}}async function vn(t){let{to:e,text:n,uploaded:r,opts:s}=t,i={type:_.IMAGE,image_item:{media:{encrypt_query_param:r.downloadEncryptedQueryParam,aes_key:Buffer.from(r.aeskey).toString("base64"),encrypt_type:1},mid_size:r.fileSizeCiphertext}};return ve({to:e,text:n,mediaItem:i,opts:s,label:"sendImageMessage"})}async function On(t){let{to:e,text:n,uploaded:r,opts:s}=t,i={type:_.VIDEO,video_item:{media:{encrypt_query_param:r.downloadEncryptedQueryParam,aes_key:Buffer.from(r.aeskey).toString("base64"),encrypt_type:1},video_size:r.fileSizeCiphertext}};return ve({to:e,text:n,mediaItem:i,opts:s,label:"sendVideoMessage"})}async function At(t){let{to:e,text:n,fileName:r,uploaded:s,opts:i}=t,a={type:_.FILE,file_item:{media:{encrypt_query_param:s.downloadEncryptedQueryParam,aes_key:Buffer.from(s.aeskey).toString("base64"),encrypt_type:1},file_name:r,len:String(s.fileSize)}};return ve({to:e,text:n,mediaItem:a,opts:i,label:"sendFileMessage"})}async function kt(t){let{filePath:e,to:n,text:r,opts:s,cdnBaseUrl:i}=t,a=re(e),o={baseUrl:s.baseUrl,token:s.token,routeTag:s.routeTag};if(a.startsWith("video/")){Z.debug(`sendWeixinMediaFile: uploading video filePath=${e} to=${n}`);let u=await St({filePath:e,toUserId:n,opts:o,cdnBaseUrl:i});return On({to:n,text:r,uploaded:u,opts:s})}if(a.startsWith("image/")){Z.debug(`sendWeixinMediaFile: uploading image filePath=${e} to=${n}`);let u=await Ct({filePath:e,toUserId:n,opts:o,cdnBaseUrl:i});return vn({to:n,text:r,uploaded:u,opts:s})}if(a.startsWith("audio/")){let u=Rt.basename(e);Z.debug(`sendWeixinMediaFile: uploading audio as file filePath=${e} name=${u} to=${n}`);let p=await Ue({filePath:e,fileName:u,toUserId:n,opts:o,cdnBaseUrl:i});return At({to:n,text:r,fileName:u,uploaded:p,opts:s})}let d=Rt.basename(e);Z.debug(`sendWeixinMediaFile: uploading file attachment filePath=${e} name=${d} to=${n}`);let c=await Ue({filePath:e,fileName:d,toUserId:n,opts:o,cdnBaseUrl:i});return At({to:n,text:r,fileName:d,uploaded:c,opts:s})}S();var h=y("channels"),Pt="https://novac2c.cdn.weixin.qq.com/c2c",De=new Map;function Ot(t){return x.join(fe(),".adam","wechat",`${t}.context-tokens.json`)}function Nn(t){let e=Ot(t);try{let n=R.readFileSync(e,"utf-8"),r=JSON.parse(n);for(let[s,i]of Object.entries(r))typeof i=="string"&&i&&De.set(`${t}:${s}`,i);h.debug({channelId:t,count:Object.keys(r).length},"Restored context tokens from disk")}catch{}}function Dn(t,e,n){let r=Ot(t);try{let s={};try{let a=R.readFileSync(r,"utf-8");s=JSON.parse(a)}catch{}s[e]=n;let i=x.dirname(r);R.mkdirSync(i,{recursive:!0}),R.writeFileSync(r,JSON.stringify(s),"utf-8")}catch(s){h.warn({channelId:t,userId:e},`Failed to persist context token: ${String(s)}`)}}function Ln(t,e,n){De.set(`${t}:${e}`,n),Dn(t,e,n)}function Oe(t,e){return De.get(`${t}:${e}`)}function Nt(t){return x.join(fe(),".adam","wechat",`${t}.sync`)}function Fn(t){try{return R.readFileSync(Nt(t),"utf-8")}catch{return""}}function Bn(t,e){let n=Nt(t);R.mkdirSync(x.dirname(n),{recursive:!0}),R.writeFileSync(n,e,"utf-8")}var Ne=1440*60*1e3,Ut=10,$n=20,vt=1440*60*1e3,qn=1320*60*1e3,Gn=1,Wn=7200*1e3;function Dt(t){return x.join(fe(),".adam","wechat",`${t}.session.json`)}function jn(t){let e=new Map,n=Dt(t);try{let r=R.readFileSync(n,"utf-8"),s=JSON.parse(r);for(let[i,a]of Object.entries(s))a&&typeof a.lastUserMessageAt=="number"&&e.set(i,a);h.debug({channelId:t,count:e.size},"Restored sessions from disk")}catch{}return e}function ee(t,e){let n=Dt(t);try{let r={};for(let[i,a]of e)r[i]=a;let s=x.dirname(n);R.mkdirSync(s,{recursive:!0}),R.writeFileSync(n,JSON.stringify(r),"utf-8")}catch(r){h.warn({channelId:t},`Failed to persist sessions: ${String(r)}`)}}var Vn=0;function te(){return`adam-wechat-${Date.now()}-${++Vn}`}var q=class{platform="wechat";id;config;status="disconnected";messageHandler=null;pollAbort=null;getUpdatesBuf="";sessions=new Map;pendingQueue=new Map;lastReminderAt=new Map;constructor(e,n){if(this.id=e,!n.baseUrl)throw new Error("WeChat adapter requires baseUrl");this.config=n}async connect(){if(!this.config.botToken)throw new Error("WeChat adapter requires botToken. Complete QR login first.");this.status="connecting",this.getUpdatesBuf=Fn(this.id),Nn(this.id),this.sessions=jn(this.id),this.pollAbort=new AbortController,this.status="connected",h.info({channelId:this.id},"WeChat adapter connected, starting long-poll"),this.startLongPoll()}async disconnect(){this.pollAbort&&(this.pollAbort.abort(),this.pollAbort=null),this.status="disconnected",h.info({channelId:this.id},"WeChat adapter disconnected")}getStatus(){if(this.status==="connected"&&le(this.id))return"error";if(this.status==="connected"){for(let[,e]of this.sessions)if(this.isSessionActive(e)&&e.quotaRemaining<=0)return"degraded"}return this.status}getCapabilities(){return{canEdit:!1,canQuote:!0,canParseQuote:!0,canInlineButtons:!1,maxTextLength:4e3,supportsAttachments:!0,maxAttachmentsPerMessage:1}}async sendMessage(e,n){if(le(this.id)){let c=Math.ceil(gt(this.id)/6e4);throw new Error(`WeChat session paused, ${c} min remaining. Re-scan QR to reconnect.`)}let r=this.getOrCreateSession(e),i=this.getSessionRemainingMs(r)/36e5;if(!this.isSessionActive(r))return h.warn({channelId:this.id,chatId:e.slice(0,12),lastUserMessageAt:r.lastUserMessageAt,sessionExpired:!0},"iLink session expired (>24h), message queued"),this.enqueueMessage(e,n),`queued-${te()}`;if(r.quotaRemaining<=0)return h.warn({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:0,remainingHours:i.toFixed(1)},"iLink quota exhausted, message queued"),this.enqueueMessage(e,n),`queued-${te()}`;let a=te(),o=Oe(this.id,e),d=this.config.cdnBaseUrl??Pt;try{let c=n.attachments?.[0],u=c?.path??n.mediaUrl,p=c?.contentType,f=c?.filename,m=c?.mediaType??n.mediaType;if(u){let l=!u.includes("://")||u.startsWith("file://"),b=x.join(fe(),".adam","wechat","media","outbound-tmp");await M.mkdir(b,{recursive:!0});let L=this.getExtensionFromMediaType(m,p),A;if(l){let I=u.startsWith("file://")?new URL(u).pathname:x.isAbsolute(u)?u:x.resolve(u),v=await M.readFile(I);A=x.join(b,`${Date.now()}-${Math.random().toString(36).slice(2,7)}${L}`),await M.writeFile(A,v)}else{let I=await fetch(u);if(!I.ok)throw new Error(`Failed to fetch media: ${I.status}`);let v=Buffer.from(await I.arrayBuffer());A=x.join(b,`${Date.now()}-${Math.random().toString(36).slice(2,7)}${L}`),await M.writeFile(A,v)}let w=A;if(f){let I=f.replace(/[\\/]/g,"-").replace(/\.\./g,"-").replace(/[\x00-\x1f]/g,"");if(I.length>0&&I.length<200){let v=x.join(b,`${Date.now()}-${I}`);await M.copyFile(A,v),await M.unlink(A).catch(()=>{}),w=v}}let U=await kt({filePath:w,to:e,text:n.content??"",opts:{baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,contextToken:o},cdnBaseUrl:d});return await M.unlink(w).catch(()=>{}),r.quotaRemaining--,ee(this.id,this.sessions),h.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:r.quotaRemaining,sessionRemainingHours:(this.getSessionRemainingMs(r)/36e5).toFixed(1)},"iLink send success: quota decremented"),this.checkAndSendReminder(e,r).catch(I=>{h.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(I)}`)}),U.messageId}return await H({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{msg:{from_user_id:"",to_user_id:e,client_id:a,message_type:K.BOT,message_state:X.FINISH,item_list:this.buildItemList(n),context_token:o}}}),r.quotaRemaining--,ee(this.id,this.sessions),h.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:r.quotaRemaining,sessionRemainingHours:(this.getSessionRemainingMs(r)/36e5).toFixed(1)},"iLink send success: quota decremented"),this.checkAndSendReminder(e,r).catch(l=>{h.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(l)}`)}),a}catch(c){if(c instanceof Error&&c.message.includes("ret=-2"))return r.quotaRemaining=0,ee(this.id,this.sessions),h.warn({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:0},"iLink quota exhausted (ret=-2 confirmed), message queued"),this.enqueueMessage(e,n),`queued-${te()}`;throw c}}onMessage(e){this.messageHandler=e}async sendTypingIndicator(e){if(le(this.id))return;let n=Oe(this.id,e);try{await rt({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{ilink_user_id:e,status:lt.TYPING}})}catch{}}updateConfig(e){Object.assign(this.config,e)}buildItemList(e){if(!e.content)return;let n={type:_.TEXT,text_item:{text:e.content}};if(e.replyToMessageId){let r=(e.quoteExcerpt??"").slice(0,80);n.ref_msg={message_item:{msg_id:e.replyToMessageId,text_item:{text:r}},title:e.quoteTitle}}return[n]}getOrCreateSession(e){let n=this.sessions.get(e);return n||(n={lastUserMessageAt:0,quotaRemaining:0},this.sessions.set(e,n)),n}isSessionActive(e){return e.lastUserMessageAt>0&&Date.now()-e.lastUserMessageAt<=Ne}getSessionRemainingMs(e){return e.lastUserMessageAt===0?0:Math.max(0,Ne-(Date.now()-e.lastUserMessageAt))}enqueueMessage(e,n){let r=this.pendingQueue.get(e);r||(r=[],this.pendingQueue.set(e,r));let s=Date.now();r=r.filter(i=>s-i.queuedAt<vt),r.length>=$n&&(r.shift(),h.warn({channelId:this.id,chatId:e.slice(0,12)},"Queue full, dropping oldest message")),r.push({message:n,queuedAt:s}),this.pendingQueue.set(e,r),h.info({channelId:this.id,chatId:e.slice(0,12),queueDepth:r.length},"Message enqueued")}async flushQueue(e){let n=this.pendingQueue.get(e);if(!n||n.length===0)return;let r=this.getOrCreateSession(e),s=Math.min(n.length,Math.max(0,r.quotaRemaining-2));if(s<=0){h.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:r.quotaRemaining},"Queue flush skipped: insufficient quota (reserving 2 for conversation)");return}h.info({channelId:this.id,chatId:e.slice(0,12),queueDepth:n.length,sending:s,quotaRemaining:r.quotaRemaining},"Flushing queued messages");let i=0;for(;i<s&&n.length>0;){let a=n[0];if(Date.now()-a.queuedAt>vt){n.shift();continue}try{if(await this.sendMessage(e,a.message),n.shift(),i++,r.quotaRemaining<=0)break}catch{h.warn({channelId:this.id,chatId:e.slice(0,12)},"Queue flush: send failed, stopping");break}}n.length===0&&this.pendingQueue.delete(e),h.info({channelId:this.id,chatId:e.slice(0,12),sent:i,remaining:n.length},"Queue flush complete")}async checkAndSendReminder(e,n){let r=Date.now(),s=this.lastReminderAt.get(e)??0;if(r-s<Wn)return;let i=this.getSessionRemainingMs(n),o=r-n.lastUserMessageAt>=qn,d=n.quotaRemaining<=Gn;if(!o&&!d)return;let c=(i/36e5).toFixed(1),u;o&&d?u=`[\u7CFB\u7EDF\u63D0\u9192] \u6D88\u606F\u7A97\u53E3\u5373\u5C06\u5173\u95ED\uFF08\u5269\u4F59${c}\u5C0F\u65F6/${n.quotaRemaining}\u6761\u914D\u989D\uFF09\u3002\u8BF7\u56DE\u590D\u4EFB\u610F\u6D88\u606F\u4EE5\u4FDD\u6301\u8FDE\u63A5\u3002`:o?u=`[\u7CFB\u7EDF\u63D0\u9192] \u6D88\u606F\u7A97\u53E3\u5373\u5C06\u5173\u95ED\uFF08\u5269\u4F59${c}\u5C0F\u65F6\uFF09\u3002\u8BF7\u56DE\u590D\u4EFB\u610F\u6D88\u606F\u4EE5\u4FDD\u6301\u8FDE\u63A5\u3002`:u=`[\u7CFB\u7EDF\u63D0\u9192] \u6D88\u606F\u914D\u989D\u5373\u5C06\u7528\u5B8C\uFF08\u5269\u4F59${n.quotaRemaining}\u6761\uFF09\u3002\u8BF7\u56DE\u590D\u4EFB\u610F\u6D88\u606F\u4EE5\u91CD\u7F6E\u914D\u989D\u3002`;let p=Oe(this.id,e);try{await H({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{msg:{from_user_id:"",to_user_id:e,client_id:te(),message_type:K.BOT,message_state:X.FINISH,item_list:[{type:_.TEXT,text_item:{text:u}}],context_token:p}}}),n.quotaRemaining--,this.lastReminderAt.set(e,r),ee(this.id,this.sessions),h.info({channelId:this.id,chatId:e.slice(0,12),remainingHours:c,quotaRemaining:n.quotaRemaining,trigger:o?"time":"quota"},"iLink session reminder sent")}catch(f){h.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(f)}`)}}async startLongPoll(){let e=this.pollAbort?.signal,n=0,r=3,s=3e4,i=2e3;for(;!e?.aborted;)try{let a=await st({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,get_updates_buf:this.getUpdatesBuf});if(a.ret===Re||a.errcode===Re){mt(this.id),this.status="error",h.error({channelId:this.id},"Session expired (errcode=-14), pausing for 1 hour"),await this.sleep(ce,e),pt(this.id),this.status="connected";continue}if(a.ret!==void 0&&a.ret!==0||a.errcode!==void 0&&a.errcode!==0){n++,h.error({channelId:this.id,ret:a.ret,errcode:a.errcode},"getUpdates API error"),n>=r?(n=0,await this.sleep(s,e)):await this.sleep(i,e);continue}n=0,a.get_updates_buf&&(this.getUpdatesBuf=a.get_updates_buf,Bn(this.id,a.get_updates_buf));for(let d of a.msgs??[])await this.processInbound(d)}catch(a){if(e?.aborted)return;n++,h.error({channelId:this.id,error:a},"getUpdates error"),n>=r?(n=0,await this.sleep(s,e)):await this.sleep(i,e)}}async processInbound(e){if(!this.messageHandler)return;let n=!!e.group_id,r=n?e.group_id:e.from_user_id??"",s=e.from_user_id??"";e.context_token&&r&&Ln(this.id,r,e.context_token);let i=this.getOrCreateSession(r),a=i.quotaRemaining;i.lastUserMessageAt=Date.now(),i.quotaRemaining=Ut,ee(this.id,this.sessions),h.info({channelId:this.id,chatId:r.slice(0,12),quotaReset:!0,prevQuota:a,newQuota:Ut,sessionWindowMs:Ne},"iLink session reset: user message received, quota restored"),this.flushQueue(r);let o="",d,c=[],u;for(let m of e.item_list??[]){let l=m.ref_msg?.message_item?.msg_id;if(l){u=l;break}}for(let m of e.item_list??[])m.type===_.TEXT&&m.text_item?.text&&(o+=m.text_item.text),m.type===_.IMAGE&&(d="image",c.push(m)),m.type===_.VOICE&&(d="audio",c.push(m),m.voice_item?.text&&!o&&(o=m.voice_item.text)),m.type===_.FILE&&(d="file",c.push(m)),m.type===_.VIDEO&&(d="video",c.push(m));if(!o&&!d)return;let p;if(c.length>0){let m=this.config.cdnBaseUrl??Pt;try{let l=await Mt(c[0],{cdnBaseUrl:m,channelId:this.id});l&&(p=l.path,d=l.type)}catch(l){h.error({channelId:this.id},`Media download failed: ${String(l)}`)}}let f={channelId:this.id,platform:"wechat",chatId:r,senderId:s,content:o,mediaType:d,mediaPath:p,isGroup:n,timestamp:e.create_time_ms??Date.now(),raw:e,...u?{quotedPlatformMessageId:u}:{}};this.messageHandler(f)}getExtensionFromMediaType(e,n){if(n){let r=ie(n);if(r&&r!==".bin")return r}switch(e){case"image":return".png";case"video":return".mp4";case"audio":return".mp3";default:return".bin"}}sleep(e,n){return new Promise((r,s)=>{let i=setTimeout(r,e);n?.addEventListener("abort",()=>{clearTimeout(i),s(new Error("aborted"))},{once:!0})})}};S();S();var zn=y("channels"),he=class{platform="discord";id;config;status="disconnected";messageHandler=null;client=null;constructor(e,n){if(this.id=e,!n.botToken)throw new Error("Discord adapter requires botToken");this.config=n}async connect(){this.status="connecting";try{let{Client:e,GatewayIntentBits:n}=await import("discord.js");this.client=new e({intents:[n.Guilds,n.GuildMessages,n.MessageContent,n.DirectMessages]});let r=this.client;r.on("messageCreate",s=>{if(!this.messageHandler||s.author.bot||this.config.allowedGuildIds?.length&&s.guildId&&!this.config.allowedGuildIds.includes(s.guildId))return;let i={channelId:this.id,platform:"discord",chatId:s.channelId,senderId:s.author.id,senderName:s.author.displayName??s.author.username,content:s.content,isGroup:!!s.guildId,timestamp:s.createdTimestamp,raw:s};this.messageHandler(i)}),await r.login(this.config.botToken),this.status="connected",zn.info({channelId:this.id},"Discord bot connected")}catch(e){throw this.status="error",e}}async disconnect(){this.client&&await this.client.destroy(),this.client=null,this.status="disconnected"}getStatus(){return this.status}getCapabilities(){return{canEdit:!0,canQuote:!0,canParseQuote:!0,canInlineButtons:!0,maxTextLength:2e3,supportsAttachments:!0}}async sendMessage(e,n){if(!this.client)throw new Error("Discord client not connected");let s=await this.client.channels.fetch(e);if(!s||!("send"in s))throw new Error(`Channel ${e} not found or not text channel`);return(await s.send({content:n.content,reply:n.replyToMessageId?{messageReference:n.replyToMessageId}:void 0})).id}onMessage(e){this.messageHandler=e}async sendTypingIndicator(e){if(!this.client)return;let r=await this.client.channels.fetch(e);r&&"sendTyping"in r&&await r.sendTyping()}};import{statSync as as}from"fs";import{ImapFlow as os}from"imapflow";import ds from"nodemailer";import{existsSync as Qn,mkdirSync as Hn,readFileSync as Kn,writeFileSync as Xn}from"fs";import{dirname as Jn,join as Lt}from"path";import{homedir as Yn}from"os";var Zn={lastUid:0,seenMessageIds:[],sentMessageIds:[],updatedAt:0};function Le(t=process.env.ADAM_TEST_DIR??Lt(Yn(),".adam")){return Lt(t,"email-gateway","state.json")}function ye(t=Le()){if(!Qn(t))return{...Zn};let e=JSON.parse(Kn(t,"utf-8"));return{uidValidity:e.uidValidity,lastUid:Number.isInteger(e.lastUid)?e.lastUid:0,seenMessageIds:Array.isArray(e.seenMessageIds)?e.seenMessageIds.filter(Ft):[],sentMessageIds:Array.isArray(e.sentMessageIds)?e.sentMessageIds.filter(Ft):[],updatedAt:typeof e.updatedAt=="number"?e.updatedAt:0}}function ne(t,e=Le()){Hn(Jn(e),{recursive:!0}),Xn(e,JSON.stringify({...t,updatedAt:Date.now()},null,2),"utf-8")}function Bt(t,e){let n=G(e);return n?{...t,seenMessageIds:t.seenMessageIds.includes(n)?t.seenMessageIds:[...t.seenMessageIds,n]}:t}function es(t,e){let n=G(e);return n?{...t,sentMessageIds:t.sentMessageIds.includes(n)?t.sentMessageIds:[...t.sentMessageIds,n]}:t}function $t(t,e=Le()){let n=es(ye(e),t);return ne(n,e),n}function G(t){return typeof t=="string"?t.trim():""}function Ft(t){return typeof t=="string"}import{Readable as ts}from"stream";import{MailParser as ns}from"mailparser";import{convert as ss}from"html-to-text";async function Gt(t){let e=new ns({skipImageLinks:!0,skipTextToHtml:!0}),n={},r,s,i,a=[],o,d="",c="",u="",p,f=0,m;if(await new Promise((L,A)=>{e.on("headers",w=>{try{for(let[I,v]of w.entries())n[I.toLowerCase()]=is(v);r=qt(w.get("message-id")),o=qt(w.get("subject")),u=Vt(w.get("content-type"))??"";let U=w.get("date");U instanceof Date&&(p=U.getTime()),s=Wt(w.get("from"),"from"),i=rs(w.get("reply-to"),"reply-to"),a=jt(w.get("to"))}catch(U){m=U instanceof Error?U:new Error(String(U))}}),e.on("data",w=>{if(w.type==="attachment"){f+=1,w.release?.(),w.content?.resume?.();return}d=w.text??"",c=typeof w.html=="string"?w.html:""}),e.on("error",A),e.on("end",L),ts.from([t]).pipe(e)}),m)throw m;if(!s)throw new Error("Inbound email must contain exactly one valid From address");let l=u.toLowerCase()==="text/html",b=d.trim();return(l||!b)&&c.trim()&&(b=ss(c,{wordwrap:!1,selectors:[{selector:"h1",format:"heading",options:{uppercase:!1}},{selector:"h2",format:"heading",options:{uppercase:!1}},{selector:"h3",format:"heading",options:{uppercase:!1}},{selector:"h4",format:"heading",options:{uppercase:!1}},{selector:"h5",format:"heading",options:{uppercase:!1}},{selector:"h6",format:"heading",options:{uppercase:!1}}]}).trim()),!b&&o&&(b=o.trim()),{messageId:r,from:s,replyTo:i,to:a,subject:o,text:b,date:p,rawHeaders:n,attachmentCount:f}}function Wt(t,e){let n=jt(t);if(n.length!==1){if(n.length===0)return;throw new Error(`Inbound email ${e} must contain exactly one mailbox address`)}return n[0]}function rs(t,e){if(t)return Wt(t,e)}function jt(t){return t?typeof t=="string"?[k(t)]:(t.value??[]).map(r=>r.address).filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>k(r)):[]}function qt(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(String).join(", ")}function is(t){if(t instanceof Date)return t.toISOString();if(typeof t=="string")return t;if(Array.isArray(t))return t.map(String).join(", ");let e=Vt(t);return e||(t&&typeof t=="object"&&"text"in t?String(t.text??""):String(t??""))}function Vt(t){if(typeof t=="string")return t;if(t&&typeof t=="object"&&"value"in t){let e=t.value;if(typeof e=="string")return e}}var zt=3e4,us=5e3,cs=3e5,ls=1.33,ms=3e4;function gs(t){if(!t||t.length===0)return zt;let e=0;for(let r of t)try{e+=as(r.path).size}catch{}let n=e*ls/(1024*1024);return Math.min(cs,zt+Math.ceil(n*us))}var Be=class{imapClient;smtpTransporter;pollTimer;handlers=[];status={status:"stopped"};state=ye();async start(e){if(await this.stop(),!e.enabled){this.status={status:"stopped",details:{reason:"disabled"}};return}this.status={status:"starting",lastStartedAt:Date.now()};try{this.imapClient=new os({host:e.imap.host,port:e.imap.port,secure:e.imap.secure,auth:{user:e.imap.auth.user,pass:e.imap.auth.pass}}),await this.imapClient.connect();let n=await this.imapClient.mailboxOpen(e.imap.mailbox),r=n?.uidValidity?Number(n.uidValidity):void 0;r&&this.state.uidValidity&&r!==this.state.uidValidity?(this.state={...this.state,uidValidity:r,lastUid:0,seenMessageIds:[]},ne(this.state)):r&&(this.state={...this.state,uidValidity:r},ne(this.state)),this.smtpTransporter=ds.createTransport({host:e.smtp.host,port:e.smtp.port,secure:e.smtp.secure,auth:{user:e.smtp.auth.user,pass:e.smtp.auth.pass}}),await this.smtpTransporter.verify(),this.status={status:"connected",lastStartedAt:Date.now(),lastCheckedAt:Date.now()},this.schedulePoll(e)}catch(n){throw await this.cleanupResources(),this.status={status:"error",lastError:$e(n),details:{stage:this.smtpTransporter?"smtp":"imap"}},n}}async stop(){await this.cleanupResources(),this.status={status:"stopped"}}getStatus(){return{...this.status}}onInbound(e){this.handlers.push(e)}async send(e){if(!this.smtpTransporter)throw new Error("EmailGateway SMTP transporter is not started");let n=gs(e.attachments),r=await ps(this.smtpTransporter.sendMail({from:e.from,to:e.to,subject:e.subject,text:e.text,html:e.html,attachments:e.attachments}),n,`SMTP send timed out after ${Math.round(n/1e3)}s`),s=G(r.messageId);if(!s)throw new Error("SMTP send returned no Message-ID");return this.state=$t(s),s}isSentByAdam(e){let n=G(e);return n.length>0&&this.state.sentMessageIds.includes(n)}schedulePoll(e){this.pollTimer=setInterval(()=>{this.poll(e)},ms)}async poll(e){if(this.imapClient)try{this.state=ye();let n=`${this.state.lastUid+1}:*`,r=this.imapClient.fetch?.(n,{uid:!0,source:!0,envelope:!0},{uid:!0});if(!r||!r[Symbol.asyncIterator])return;let s=!1;for await(let i of r){let a=Number(i.uid);if(!Number.isInteger(a)||a<=this.state.lastUid)continue;if(!i.source){this.markDegraded(new Error(`IMAP fetch item ${a} is missing source`)),s=!0;break}let o;try{o=await Gt(i.source)}catch(u){this.markDegraded(u),s=!0;break}let d=o.rawHeaders["x-adam-probe-id"],c=G(o.messageId);if(d?.startsWith("adam-probe-")){this.advanceCursor(a);continue}if(c&&this.state.sentMessageIds.includes(c)){this.advanceCursor(a);continue}if(c&&this.state.seenMessageIds.includes(c)){this.advanceCursor(a);continue}try{await Promise.all(this.handlers.map(u=>u(o)))}catch(u){this.markDegraded(u),s=!0;break}this.state=Bt(this.state,c),this.advanceCursor(a)}s||(this.status={...this.status,status:"connected",lastCheckedAt:Date.now(),lastError:void 0})}catch(n){this.markDegraded(n)}}advanceCursor(e){this.state={...this.state,lastUid:e},ne(this.state)}markDegraded(e){this.status={...this.status,status:"degraded",lastError:$e(e),lastCheckedAt:Date.now()}}async cleanupResources(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=void 0);let e=this.imapClient,n=this.smtpTransporter;this.imapClient=void 0,this.smtpTransporter=void 0,e&&(await Fe(e.logout?.()),await Fe(e.close?.())),await Fe(n?.close?.())}},Qt;function C(){return Qt??=new Be,Qt}async function be(t){await C().start(t)}async function Jr(t,e){await C().stop(),await C().start(t)}async function Yr(t){await C().stop()}async function ps(t,e,n){let r;try{return await Promise.race([t,new Promise((s,i)=>{r=setTimeout(()=>i(new Error(n)),e)})])}catch(s){throw new Error($e(s))}finally{r&&clearTimeout(r)}}function $e(t){return t instanceof Error?t.message.replace(/pass(word)?=[^\s]+/gi,"password=****"):"Email gateway operation failed"}async function Fe(t){t&&typeof t.then=="function"&&await t.catch(()=>{})}S();var ys=/\b55[234]\b/,bs=/(?:size|too large|exceeds|maximum|over.*?limit)/i,ws=/\b(\d{6,11})\b/,_s=/Final-Recipient:\s*rfc822;\s*([^\s>]+@([^\s>;]+))/i,Is=/To:[\s<]*([^\s>;]+@([^\s>;]+))/i;function Ht(t){let e=t.text??"",n=e.split(/\r?\n/).filter(a=>ys.test(a)&&bs.test(a));if(n.length===0)return null;let r=e.match(_s)??e.match(Is);if(!r)return null;let s=r[2].toLowerCase().trim();if(!Ve.test(s))return null;let i=null;for(let a of n){let o=a.match(ws);if(o){let d=parseInt(o[1],10);if(Number.isFinite(d)&&d>=1048576&&d<=209715200){i=d;break}}}return i===null?null:{recipientDomain:s,capBytes:i}}var we=y("channels"),Kt=!1;function Xt(t){if(Kt){we.debug("Bounce handler already registered; skipping duplicate registration");return}Kt=!0,t.onInbound(async e=>{let n=Ht(e);if(!n){(/MAILER-DAEMON/i.test(e.from??"")||/^no-reply@mailsupport\.aliyun\.com$/i.test(e.from??"")||/Mail Delivery|Undeliverable|Returned mail|Delivery Status Notification|退信|无法投递|投递失败/i.test(e.subject??""))&&we.warn({from:e.from,subject:e.subject},"Inbound looks like bounce but parser did not recognize a size-limit cap");return}let{recipientDomain:r,capBytes:s}=n;we.info({recipientDomain:r,capBytes:s},"Bounce-learning: detected SMTP size-limit bounce");let i=F().filter(a=>a.platform==="email");for(let a of i)try{Qe(a.id,r,s)}catch(o){we.warn({channelId:a.id,recipientDomain:r,capBytes:s,err:o},"Bounce-learning: setRecipientCap failed (out of range or DB error); skipping")}})}S();var _e=y("channels"),qe=class{constructor(e){this.gateway=e}gateway;adaptersByAddress=new Map;channelAddressById=new Map;registerAdapter(e,n){if(!Ke(e)||!e.enabled)return;let r=B(e);this.unregisterAdapter(e.id),this.adaptersByAddress.set(r,n),this.channelAddressById.set(e.id,r)}unregisterAdapter(e){let n=this.channelAddressById.get(e);n&&(this.adaptersByAddress.delete(n),this.channelAddressById.delete(e))}refreshFromChannels(e,n){this.adaptersByAddress.clear(),this.channelAddressById.clear();for(let r of e){let s=n.get(r.id);if(s)try{this.registerAdapter(r,s)}catch(i){_e.warn({channelId:r.id,error:i},"Invalid email channel skipped during router refresh")}}}async handle(e){if(e.messageId&&this.gateway.isSentByAdam(e.messageId)){_e.debug({messageId:e.messageId},"Skipping Adam-sent email");return}let n;try{n=k(e.from)}catch(s){_e.warn({from:e.from,error:s},"Skipping email with invalid sender address");return}let r=this.adaptersByAddress.get(n);if(!r){_e.info({from:n},"Skipping unmatched inbound email");return}await r.acceptInbound(e)}hasAddress(e){return this.adaptersByAddress.has(k(e))}},Ie,Jt;function Ge(t){return(!Ie||Jt!==t)&&(Ie=new qe(t),Jt=t,t.onInbound(e=>Ie?.handle(e)??Promise.resolve())),Ie}import{existsSync as Es}from"fs";import{basename as Ts,isAbsolute as xs}from"path";function Yt(t){let e=[];return t.mediaUrl&&e.push({path:t.mediaUrl,mediaType:t.mediaType}),t.attachments&&e.push(...t.attachments),e.map(Ms)}function Ms(t){let e=t.path.startsWith("file://")?new URL(t.path).pathname:t.path;if(!xs(e)||e.includes("://"))throw new Error("Email attachment path must be an absolute local file path");if(!Es(e))throw new Error(`Email attachment file not found: ${e}`);return{filename:t.filename??Ts(e),path:e,...t.contentType?{contentType:t.contentType}:t.mediaType?{contentType:Cs(t.mediaType)}:{}}}function Cs(t){return"application/octet-stream"}import Ss from"markdown-it";var Rs=new Ss({html:!1,linkify:!0});function Zt(t){return{text:Je(t),html:Rs.render(t)}}function en(t){let e=t.prefix.trim()||"Adam";return t.messageType==="report"||t.messageType==="status_report"?`[${e} Report]`:t.messageType==="deliver"||t.messageType==="result_delivery"?`[${e} Deliver]`:`[${e}]`}var Ee=class{platform="email";id;channel;gateway;handler;inboundDispatchHandler;status="disconnected";identity;constructor(e,n,r={}){this.channel=e,this.gateway=n,this.id=e.id,this.identity=r}async connect(){let e=this.gateway.getStatus();this.status=Te(e.status)}async disconnect(){this.status="disconnected"}getStatus(){return this.status}getCapabilities(){return{canEdit:!1,canQuote:!1,canParseQuote:!1,canInlineButtons:!1,maxTextLength:Number.POSITIVE_INFINITY,supportsAttachments:!0}}async sendMessage(e,n){let r=k(e),s=B(this.channel);if(r!==s)throw new Error("Email channel recipient does not match configured address");let i=Zt(n.content);return this.gateway.send({from:this.identity.from?Xe(this.identity.from,this.identity.displayName):void 0,to:r,subject:en({prefix:this.identity.subjectPrefix??"Adam",messageType:n.messageType??"reply"}),text:i.text,html:i.html,attachments:Yt(n)})}onMessage(e){this.handler=e}onInboundDispatch(e){this.inboundDispatchHandler=e}syncGatewayStatus(){this.status=Te(this.gateway.getStatus().status)}async acceptInbound(e){let n=k(e.from),r={channelId:this.channel.id,platform:"email",chatId:n,senderId:n,senderName:e.from,content:e.text,replyToMessageId:e.messageId,isGroup:!1,timestamp:e.date??Date.now(),raw:{messageId:e.messageId,subject:e.subject,attachmentCount:e.attachmentCount,headers:e.rawHeaders}};this.handler?.(r),this.inboundDispatchHandler&&await this.inboundDispatchHandler(r)}};function Te(t){switch(t){case"connected":return"connected";case"starting":return"connecting";case"degraded":case"error":return"degraded";case"stopped":return"disconnected";default:return"disconnected"}}var tn=y("channels"),We=new Map;async function W(t,e){if(t.hasAdapter(e.id))return!0;if(e.platform==="wechat"){let n=e.config;return n.botToken?(await t.addChannel(e,new q(e.id,n)),!0):!1}if(e.platform==="discord"){let n=e.config;return n.botToken?(await t.addChannel(e,new he(e.id,{botToken:n.botToken})),!0):!1}if(e.platform==="email"){B(e);let n=C(),r=V().emailGateway,s=new Ee(e,n,{from:r?.smtp?.from||r?.address,displayName:r?.displayName,subjectPrefix:r?.subjectPrefix??"Adam"});We.set(e.id,s),Ge(n).registerAdapter(e,s);try{await As(),await t.addChannel(e,s)}catch(i){throw await j(t,e),i}return!0}return!1}async function Ai(t){for(let e of F(!0))try{await W(t,e)}catch(n){z(e.id,"error"),tn.warn({channelId:e.id,platform:e.platform,error:n},"Failed to register built-in channel adapter")}}async function nn(t,e){e.platform==="email"&&(await j(t,e),e.enabled&&await W(t,e))}async function sn(t,e){await j(t,e)}async function j(t,e){e.platform==="email"&&(Ge(C()).unregisterAdapter(e.id),We.delete(e.id),t?.hasAdapter(e.id)&&await t.removeChannel(e.id))}function ki(t){for(let[e,n]of We.entries())n.syncGatewayStatus(),z(e,n.getStatus())}async function As(){let t=V().emailGateway;if(!t?.enabled)return;let e=C().getStatus().status;if(!(e!=="stopped"&&e!=="error"))try{await be(t),Xt(C())}catch(n){tn.warn({error:ks(n)},"EmailGateway start failed during built-in adapter registration")}}function ks(t){return t instanceof Error?t.message.replace(/pass(word)?=[^\s]+/gi,"password=****"):"Email gateway operation failed"}var P=g.object({id:g.string().uuid()}),Us=g.object({name:g.string().min(1,"name is required"),platform:g.string().min(1,"platform is required"),config:g.record(g.string(),g.unknown()),enabled:g.boolean().optional().default(!0),linkedRoleId:g.string().optional(),allowedChatIds:g.array(g.string()).optional()}),vs=g.object({name:g.string().min(1).optional(),enabled:g.boolean().optional(),config:g.record(g.string(),g.unknown()).optional(),linkedRoleId:g.string().optional(),allowedChatIds:g.array(g.string()).optional(),viewerKey:g.string().min(1).max(100).regex(/^[a-zA-Z0-9_.@:-]+$/,"viewerKey must be alphanumeric or one of _ . @ : -").optional(),defaultRecipientCapBytes:g.number().int().min(1048576).max(209715200).optional(),recipientCapMap:g.record(g.string().regex(/^[a-z0-9.-]+$/),g.number().int().min(1048576).max(209715200)).optional()}),je;function Vi(t){je=t}function zi(){return je}async function Qi(t){let e=je;async function n(r){ze(r);try{return e&&r.enabled&&await W(e,r),r}catch(s){throw await j(e,r),xe(r.id),s}}t.get("/channels",{schema:{tags:["Channels"],summary:"List channels",querystring:{type:"object",properties:{enabled:{type:"boolean"}}}}},async(r,s)=>({channels:F(r.query.enabled).map(Q)})),t.post("/channels",{schema:{tags:["Channels"],summary:"Create a channel",body:{type:"object",required:["name","platform","config"],properties:{name:{type:"string",minLength:1},platform:{type:"string",minLength:1},config:{type:"object"},enabled:{type:"boolean"},linkedRoleId:{type:"string"},allowedChatIds:{type:"array",items:{type:"string"}}}}}},async(r,s)=>{let i=Us.safeParse(r.body);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});let{name:a,platform:o,config:d,enabled:c,linkedRoleId:u,allowedChatIds:p}=i.data,f=d;if(o==="email")try{f={...Me(d)}}catch(l){return s.status(400).send({code:"VALIDATION_ERROR",message:l instanceof Error?l.message:String(l)})}let m={id:Ps(),name:a,platform:o,enabled:c,status:"disconnected",config:f,linkedRoleId:u,allowedChatIds:p,viewerKey:Ye(),createdAt:Date.now(),messageCount:0};try{await n(m)}catch(l){return s.status(400).send({code:"VALIDATION_ERROR",message:D(l)})}return s.status(201).send({channel:Q(m)})}),t.get("/channels/:id",{schema:{tags:["Channels"],summary:"Get channel by ID",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});let a=E(i.data.id);return a?{channel:Q(a)}:s.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),t.patch("/channels/:id",{schema:{tags:["Channels"],summary:"Update channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",properties:{name:{type:"string"},enabled:{type:"boolean"},config:{type:"object"},linkedRoleId:{type:"string"},allowedChatIds:{type:"array",items:{type:"string"}},viewerKey:{type:"string",minLength:1,maxLength:100}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});let a=E(i.data.id);if(!a)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let o=vs.safeParse(r.body);if(!o.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(o.error)});let d={...o.data};if(d.config&&(d.config=et(d.config,a.config)),(a.platform==="email"||d.config)&&(d.config||a.config)){let p=d.config??a.config;if(a.platform==="email")try{d.config={...Me(p)}}catch(f){return s.status(400).send({code:"VALIDATION_ERROR",message:f instanceof Error?f.message:String(f)})}}let c=a.platform==="email"&&(d.enabled!==void 0||d.config!==void 0);se(a.id,d);let u=E(a.id);if(e&&u&&c)try{await nn(e,u)}catch(p){if(se(a.id,{name:a.name,enabled:a.enabled,status:a.status,config:a.config,linkedRoleId:a.linkedRoleId,allowedChatIds:a.allowedChatIds,lastMessageAt:a.lastMessageAt,messageCount:a.messageCount}),await j(e,u),a.enabled)try{await W(e,a)}catch(f){return s.status(500).send({code:"RESTORE_FAILED",message:D(f)})}return s.status(400).send({code:"VALIDATION_ERROR",message:D(p)})}return{channel:u&&Q(u)}}),t.delete("/channels/:id",{schema:{tags:["Channels"],summary:"Delete channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});let a=E(i.data.id);if(!a)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(xe(a.id),e)try{await sn(e,a)}catch(o){t.log.warn({channelId:a.id,error:D(o)},"Failed to clean up built-in channel runtime")}return s.status(204).send()}),t.post("/channels/:id/connect",{schema:{tags:["Channels"],summary:"Connect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});if(!e)return s.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let a=E(i.data.id);if(!a)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(a.platform==="email")try{await Os()}catch(o){let d=C().getStatus();return z(a.id,Te(d.status)),s.status(409).send({code:"EMAIL_GATEWAY_NOT_READY",message:D(o),gatewayStatus:d})}if(!e.hasAdapter(a.id))try{await W(e,a)}catch(o){return s.status(400).send({code:"VALIDATION_ERROR",message:D(o)})}if(!e.hasAdapter(a.id))return s.status(400).send({code:"NO_ADAPTER",message:"No adapter registered for this channel. Install the appropriate adapter first."});try{await e.connectChannel(a.id);let o=E(a.id)?.status??e.getChannelStatus(a.id);return o!=="connected"?s.status(409).send({code:"CONNECT_INCOMPLETE",message:`Channel connect finished with status "${o}"`,status:o}):{channelId:a.id,status:o}}catch(o){return s.status(500).send({code:"CONNECT_FAILED",message:D(o)})}}),t.post("/channels/:id/disconnect",{schema:{tags:["Channels"],summary:"Disconnect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});if(!e)return s.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let a=E(i.data.id);return a?(await e.disconnectChannel(a.id),{channelId:a.id,status:"disconnected"}):s.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),t.get("/channels/:id/capabilities",{schema:{tags:["Channels"],summary:"Get channel adapter capabilities",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});if(!E(i.data.id))return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(!e)return s.status(503).send({code:"MANAGER_UNAVAILABLE",message:"ChannelManager not initialized"});let o=e.getCapabilities(i.data.id);return o?{capabilities:o}:s.status(404).send({code:"ADAPTER_NOT_REGISTERED",message:"Channel adapter not active"})}),t.get("/channels/:id/messages",{schema:{tags:["Channels"],summary:"Get channel message history",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50},offset:{type:"integer",minimum:0,default:0}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});let a=E(i.data.id);if(!a)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let{limit:o=50,offset:d=0}=r.query;return{messages:He(a.id,o,d)}}),t.post("/channels/:id/wechat/qr-start",{schema:{tags:["WeChat"],summary:"Start WeChat QR login",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});let a=E(i.data.id);if(!a)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(a.platform!=="wechat")return s.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=a.config;return await ut({apiBaseUrl:o.baseUrl,routeTag:o.routeTag})}),t.post("/channels/:id/wechat/qr-wait",{schema:{tags:["WeChat"],summary:"Wait for WeChat QR scan",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",properties:{sessionKey:{type:"string"},timeoutMs:{type:"number"}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});let a=E(i.data.id);if(!a)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(a.platform!=="wechat")return s.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=a.config,{sessionKey:d,timeoutMs:c}=r.body??{},u=await ct({sessionKey:d??"",apiBaseUrl:o.baseUrl,timeoutMs:c??12e4,routeTag:o.routeTag});if(u.connected&&u.botToken){let p={...o,botToken:u.botToken,accountId:u.accountId,baseUrl:u.baseUrl??o.baseUrl,userId:u.userId};if(se(a.id,{config:p}),e){let f=new q(a.id,p),m=E(a.id);m&&await e.addChannel(m,f)}}return{connected:u.connected,accountId:u.accountId,message:u.message}})}function D(t){return t instanceof Error?t.message.replace(/pass(word)?=[^\s]+/gi,"password=****"):String(t)}async function Os(){let t=V().emailGateway;if(!t?.enabled)throw new Error("Email Gateway is disabled. Enable Email Gateway in Settings before connecting Mail channels.");let e=C();e.getStatus().status!=="connected"&&await be(t);let n=e.getStatus();if(n.status!=="connected"){let r=n.lastError?`: ${n.lastError}`:"";throw new Error(`Email Gateway status is ${n.status}${r}`)}}export{$t as a,G as b,Gt as c,C as d,Jr as e,Yr as f,Ai as g,ki as h,Vi as i,zi as j,Qi as k};
1
+ import{g as He}from"./chunk-VVPB3TD4.js";import{a as Ke,b as k,c as Me,d as B,e as Xe}from"./chunk-NNMQGISW.js";import{b as Je,c as Ye,f as re,g as ie}from"./chunk-5ZL6RHPE.js";import{a as Ve,b as ze,c as E,d as se,e as F,f as xe,g as z,i as Qe}from"./chunk-XEXSXMWK.js";import{e as V}from"./chunk-3MROEPGR.js";import{c as y,h as S}from"./chunk-EZLBMUQD.js";import{z as g}from"zod/v4";import{v4 as Ps}from"uuid";var Ze="__redacted__",rn=/token|secret|password|passwd|api[-_]?key|credential|private[-_]?key|access[-_]?key/i;function an(t){return rn.test(t)}function on(t){if(!t)return{};let e={};for(let[n,r]of Object.entries(t))an(n)&&typeof r=="string"&&r.length>0?e[n]=Ze:e[n]=r;return e}function Q(t){return{...t,config:on(t.config)}}function et(t,e){let n={...t};for(let[r,s]of Object.entries(t))s===Ze&&(e&&r in e?n[r]=e[r]:delete n[r]);return n}import{randomUUID as at}from"crypto";import dn from"crypto";var tt="2.1.7",ae="bot";function un(t){let e=t.split(".").map(i=>parseInt(i,10)),n=e[0]??0,r=e[1]??0,s=e[2]??0;return(n&255)<<16|(r&255)<<8|s&255}var Ce=un(tt),cn=35e3,nt=15e3,ln=1e4;function oe(){return{channel_version:tt}}function mn(t){return t.endsWith("/")?t:`${t}/`}function gn(){let t=dn.randomBytes(4).readUInt32BE(0);return Buffer.from(String(t),"utf-8").toString("base64")}function pn(t){let e={"Content-Type":"application/json",AuthorizationType:"ilink_bot_token","Content-Length":String(Buffer.byteLength(t.body,"utf-8")),"X-WECHAT-UIN":gn(),"iLink-App-Id":ae,"iLink-App-ClientVersion":String(Ce)};return t.token?.trim()&&(e.Authorization=`Bearer ${t.token.trim()}`),t.routeTag&&(e.SKRouteTag=t.routeTag),e}async function de(t){let e=mn(t.baseUrl),n=new URL(t.endpoint,e),r=pn({token:t.token,routeTag:t.routeTag,body:t.body}),s=new AbortController,i=setTimeout(()=>s.abort(),t.timeoutMs);try{let a=await fetch(n.toString(),{method:"POST",headers:r,body:t.body,signal:s.signal});clearTimeout(i);let o=await a.text();if(!a.ok)throw new Error(`${t.label} ${a.status}: ${o}`);return o}catch(a){throw clearTimeout(i),a}}async function st(t){let e=t.timeoutMs??cn;try{let n=await de({baseUrl:t.baseUrl,endpoint:"ilink/bot/getupdates",body:JSON.stringify({get_updates_buf:t.get_updates_buf??"",base_info:oe()}),token:t.token,routeTag:t.routeTag,timeoutMs:e,label:"getUpdates"});return JSON.parse(n)}catch(n){if(n instanceof Error&&n.name==="AbortError")return{ret:0,msgs:[],get_updates_buf:t.get_updates_buf};throw n}}var fn={[-2]:2,[-3]:3},hn=1e3;async function H(t){let e=(await import("./logger-TEZSHFTZ.js")).getLogger("channels"),n=new Map;for(;;){let r=await de({baseUrl:t.baseUrl,endpoint:"ilink/bot/sendmessage",body:JSON.stringify({...t.body,base_info:oe()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??nt,label:"sendMessage"});e.info({status:200,responseBody:r.slice(0,300)},"apiFetch sendMessage response");try{let s=JSON.parse(r);if(s.ret&&s.ret!==0){let i=fn[s.ret],a=(n.get(s.ret)??0)+1;if(n.set(s.ret,a),i!==void 0&&a<i){e.warn({ret:s.ret,attempt:a,maxRetries:i},"sendMessage: retriable iLink error, retrying"),await new Promise(o=>setTimeout(o,hn*a));continue}throw e.error({ret:s.ret,errmsg:s.errmsg,attempt:a},"sendMessage: iLink API error, no more retries"),new Error(`sendMessage failed: iLink ret=${s.ret}${s.errmsg?` errmsg=${s.errmsg}`:""}`)}}catch(s){if(s instanceof SyntaxError)e.warn({rawText:r.slice(0,200)},"sendMessage: non-JSON response, treating as success");else throw s}return}}async function rt(t){await de({baseUrl:t.baseUrl,endpoint:"ilink/bot/sendtyping",body:JSON.stringify({...t.body,base_info:oe()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??ln,label:"sendTyping"})}async function it(t){let e=await de({baseUrl:t.baseUrl,endpoint:"ilink/bot/getuploadurl",body:JSON.stringify({filekey:t.filekey,media_type:t.media_type,to_user_id:t.to_user_id,rawsize:t.rawsize,rawfilemd5:t.rawfilemd5,filesize:t.filesize,thumb_rawsize:t.thumb_rawsize,thumb_rawfilemd5:t.thumb_rawfilemd5,thumb_filesize:t.thumb_filesize,no_need_thumb:t.no_need_thumb,aeskey:t.aeskey,base_info:oe()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??nt,label:"getUploadUrl"});return JSON.parse(e)}var yn=5*6e4,bn=35e3,ot="3",T=new Map;function Se(t){return Date.now()-t.startedAt<yn}function wn(){for(let[t,e]of T)Se(e)||T.delete(t)}async function dt(t,e,n){let r=t.endsWith("/")?t:`${t}/`,s=new URL(`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(e)}`,r),i={"iLink-App-Id":ae};n&&(i.SKRouteTag=n);let a=await fetch(s.toString(),{headers:i});if(!a.ok){let o=await a.text().catch(()=>"(unreadable)");throw new Error(`Failed to fetch QR code: ${a.status} ${a.statusText} body=${o}`)}return await a.json()}async function _n(t,e,n){let r=t.endsWith("/")?t:`${t}/`,s=new URL(`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(e)}`,r),i={"iLink-App-Id":ae,"iLink-App-ClientVersion":String(Ce)};n&&(i.SKRouteTag=n);let a=new AbortController,o=setTimeout(()=>a.abort(),bn);try{let d=await fetch(s.toString(),{headers:i,signal:a.signal});clearTimeout(o);let c=await d.text();if(!d.ok)throw new Error(`Failed to poll QR status: ${d.status} ${d.statusText}`);return JSON.parse(c)}catch(d){if(clearTimeout(o),d instanceof Error&&d.name==="AbortError")return{status:"wait"};throw d}}async function ut(t){let e=t.accountId||at();wn();let n=T.get(e);if(!t.force&&n&&Se(n)&&n.qrcodeUrl)return{qrcodeUrl:n.qrcodeUrl,message:"QR code ready. Scan with WeChat.",sessionKey:e};if(!t.apiBaseUrl)return{message:"No baseUrl configured for this WeChat channel.",sessionKey:e};try{let r=t.botType||ot,s=await dt(t.apiBaseUrl,r,t.routeTag),i={sessionKey:e,id:at(),qrcode:s.qrcode,qrcodeUrl:s.qrcode_img_content,startedAt:Date.now()};return T.set(e,i),{qrcodeUrl:s.qrcode_img_content,message:"Scan the QR code with WeChat to connect.",sessionKey:e}}catch(r){return{message:`Failed to start login: ${String(r)}`,sessionKey:e}}}var In=3;async function ct(t){let e=T.get(t.sessionKey);if(!e)return{connected:!1,message:"No active login session. Start QR login first."};if(!Se(e))return T.delete(t.sessionKey),{connected:!1,message:"QR code expired. Please start again."};let n=Math.max(t.timeoutMs??48e4,1e3),r=Date.now()+n,s=1;for(;Date.now()<r;){try{let i=await _n(t.apiBaseUrl,e.qrcode,t.routeTag);switch(e.status=i.status,i.status){case"wait":break;case"scaned":break;case"expired":{if(s++,s>In)return T.delete(t.sessionKey),{connected:!1,message:"Login timeout: QR expired multiple times."};try{let a=t.botType||ot,o=await dt(t.apiBaseUrl,a,t.routeTag);e.qrcode=o.qrcode,e.qrcodeUrl=o.qrcode_img_content,e.startedAt=Date.now()}catch(a){return T.delete(t.sessionKey),{connected:!1,message:`QR refresh failed: ${String(a)}`}}break}case"confirmed":return i.ilink_bot_id?(T.delete(t.sessionKey),{connected:!0,botToken:i.bot_token,accountId:i.ilink_bot_id,baseUrl:i.baseurl,userId:i.ilink_user_id,message:"Connected to WeChat successfully!"}):(T.delete(t.sessionKey),{connected:!1,message:"Login failed: server did not return bot ID."})}}catch(i){return T.delete(t.sessionKey),{connected:!1,message:`Login failed: ${String(i)}`}}await new Promise(i=>setTimeout(i,1e3))}return T.delete(t.sessionKey),{connected:!1,message:"Login timeout. Please try again."}}import R from"fs";import*as M from"fs/promises";import x from"path";import{homedir as fe}from"os";var ue={IMAGE:1,VIDEO:2,FILE:3,VOICE:4},K={NONE:0,USER:1,BOT:2},_={NONE:0,TEXT:1,IMAGE:2,VOICE:3,FILE:4,VIDEO:5},X={NEW:0,GENERATING:1,FINISH:2},lt={TYPING:1,CANCEL:2};S();var En=y("channels"),Re=-14,ce=3600*1e3,$=new Map;function mt(t){let e=Date.now()+ce;$.set(t,e),En.info({channelId:t},`Session paused until ${new Date(e).toISOString()} (${ce/1e3}s)`)}function le(t){let e=$.get(t);return e===void 0?!1:Date.now()>=e?($.delete(t),!1):!0}function gt(t){let e=$.get(t);if(e===void 0)return 0;let n=e-Date.now();return n<=0?($.delete(t),0):n}function pt(t){$.delete(t)}S();import*as ge from"fs/promises";import Tt from"path";import{homedir as Sn}from"os";import{createCipheriv as Tn,createDecipheriv as xn}from"crypto";function ft(t,e){let n=Tn("aes-128-ecb",e,null);return Buffer.concat([n.update(t),n.final()])}function ht(t,e){let n=xn("aes-128-ecb",e,null);return Buffer.concat([n.update(t),n.final()])}function yt(t){return Math.ceil((t+1)/16)*16}function Ae(t,e){return`${e}/download?encrypted_query_param=${encodeURIComponent(t)}`}function bt(t){return`${t.cdnBaseUrl}/upload?encrypted_query_param=${encodeURIComponent(t.uploadParam)}&filekey=${encodeURIComponent(t.filekey)}`}S();var Xs=y("channels");function Mn(t){let e=Buffer.from(t,"base64");if(e.length===16)return e;if(e.length===32&&/^[0-9a-fA-F]{32}$/.test(e.toString("ascii")))return Buffer.from(e.toString("ascii"),"hex");throw new Error(`aes_key must decode to 16 raw bytes or 32-char hex, got ${e.length} bytes`)}async function wt(t){let e=await fetch(t);if(!e.ok)throw new Error(`CDN download ${e.status} ${e.statusText}`);return Buffer.from(await e.arrayBuffer())}async function J(t){let{encryptQueryParam:e,aesKeyBase64:n,cdnBaseUrl:r,fullUrl:s}=t,i=Mn(n),a=s?.trim()||(e?Ae(e,r):null);if(!a)throw new Error("CDN download: need full_url or encrypt_query_param");let o=await wt(a);return ht(o,i)}async function _t(t){let{encryptQueryParam:e,cdnBaseUrl:n,fullUrl:r}=t,s=r?.trim()||(e?Ae(e,n):null);if(!s)throw new Error("CDN download: need full_url or encrypt_query_param");return wt(s)}S();var me=y("channels"),It=24e3;function Cn(t,e){let n=t.byteLength,r=44+n,s=Buffer.allocUnsafe(r),i=0;return s.write("RIFF",i),i+=4,s.writeUInt32LE(r-8,i),i+=4,s.write("WAVE",i),i+=4,s.write("fmt ",i),i+=4,s.writeUInt32LE(16,i),i+=4,s.writeUInt16LE(1,i),i+=2,s.writeUInt16LE(1,i),i+=2,s.writeUInt32LE(e,i),i+=4,s.writeUInt32LE(e*2,i),i+=4,s.writeUInt16LE(2,i),i+=2,s.writeUInt16LE(16,i),i+=2,s.write("data",i),i+=4,s.writeUInt32LE(n,i),i+=4,Buffer.from(t.buffer,t.byteOffset,t.byteLength).copy(s,i),s}async function Et(t){try{let{decode:e}=await import("silk-wasm");me.debug(`silkToWav: decoding ${t.length} bytes of SILK`);let n=await e(t,It);me.debug(`silkToWav: decoded duration=${n.duration}ms pcmBytes=${n.data.byteLength}`);let r=Cn(n.data,It);return me.debug(`silkToWav: WAV size=${r.length}`),r}catch(e){return me.warn(`silkToWav: transcode failed, will use raw silk err=${String(e)}`),null}}var N=y("channels"),xt=100*1024*1024;function Rn(t){return ie(t)??".bin"}async function Y(t,e,n,r,s=xt,i){if(t.length>s)throw new Error(`Media too large: ${t.length} bytes exceeds ${s} bytes`);let a=Tt.join(Sn(),".adam","wechat","media",r,n);await ge.mkdir(a,{recursive:!0});let o;if(i&&/^[a-zA-Z0-9._-]+$/.test(i))o=i;else{let c=e?Rn(e):".bin",u=Date.now(),p=Math.random().toString(36).slice(2,7);o=`${u}-${p}${c}`}let d=Tt.join(a,o);return await ge.writeFile(d,t),N.debug(`saveMedia: saved ${t.length} bytes to ${d}`),d}async function Mt(t,e){let{cdnBaseUrl:n,channelId:r}=e;if(t.type===_.IMAGE){let s=t.image_item;if(!s?.media?.encrypt_query_param&&!s?.media?.full_url)return null;let i=s.aeskey?Buffer.from(s.aeskey,"hex").toString("base64"):s.media?.aes_key;try{let a=i?await J({encryptQueryParam:s.media?.encrypt_query_param,aesKeyBase64:i,cdnBaseUrl:n,fullUrl:s.media?.full_url}):await _t({encryptQueryParam:s.media?.encrypt_query_param,cdnBaseUrl:n,fullUrl:s.media?.full_url});return{path:await Y(a,"image/png","inbound",r),mimeType:"image/png",type:"image"}}catch(a){return N.error({channelId:r},`Image download/decrypt failed: ${String(a)}`),null}}if(t.type===_.VOICE){let s=t.voice_item;if(!s?.media?.encrypt_query_param&&!s?.media?.full_url||!s?.media?.aes_key)return null;try{let i=await J({encryptQueryParam:s.media.encrypt_query_param,aesKeyBase64:s.media.aes_key,cdnBaseUrl:n,fullUrl:s.media.full_url}),a=await Et(i);if(a){let o=await Y(a,"audio/wav","inbound",r);return N.debug(`Voice: saved WAV to ${o}`),{path:o,mimeType:"audio/wav",type:"audio"}}else{let o=await Y(i,"audio/silk","inbound",r);return N.debug(`Voice: silk transcode unavailable, saved raw SILK to ${o}`),{path:o,mimeType:"audio/silk",type:"audio"}}}catch(i){return N.error({channelId:r},`Voice download/transcode failed: ${String(i)}`),null}}if(t.type===_.FILE){let s=t.file_item;if(!s?.media?.encrypt_query_param&&!s?.media?.full_url||!s?.media?.aes_key)return null;try{let i=await J({encryptQueryParam:s.media.encrypt_query_param,aesKeyBase64:s.media.aes_key,cdnBaseUrl:n,fullUrl:s.media.full_url}),a=re(s.file_name??"file.bin");return{path:await Y(i,a,"inbound",r,xt,s.file_name),mimeType:a,type:"file"}}catch(i){return N.error({channelId:r},`File download failed: ${String(i)}`),null}}if(t.type===_.VIDEO){let s=t.video_item;if(!s?.media?.encrypt_query_param&&!s?.media?.full_url||!s?.media?.aes_key)return null;try{let i=await J({encryptQueryParam:s.media.encrypt_query_param,aesKeyBase64:s.media.aes_key,cdnBaseUrl:n,fullUrl:s.media.full_url});return{path:await Y(i,"video/mp4","inbound",r),mimeType:"video/mp4",type:"video"}}catch(i){return N.error({channelId:r},`Video download failed: ${String(i)}`),null}}return null}import Rt from"path";import ke from"crypto";import An from"fs/promises";S();var O=y("channels"),pe=3;async function kn(t){let{buf:e,uploadFullUrl:n,uploadParam:r,filekey:s,cdnBaseUrl:i,label:a,aeskey:o}=t,d=ft(e,o),c=n?.trim(),u;if(c)u=c;else if(r)u=bt({cdnBaseUrl:i,uploadParam:r,filekey:s});else throw new Error(`${a}: CDN upload URL missing (need upload_full_url or upload_param)`);O.debug(`${a}: CDN POST url=${u} ciphertextSize=${d.length}`);let p,f;for(let m=1;m<=pe;m++)try{let l=await fetch(u,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:new Uint8Array(d)});if(l.status>=400&&l.status<500){let b=l.headers.get("x-error-message")??await l.text();throw O.error(`${a}: CDN client error attempt=${m} status=${l.status} errMsg=${b}`),new Error(`CDN upload client error ${l.status}: ${b}`)}if(l.status!==200){let b=l.headers.get("x-error-message")??`status ${l.status}`;throw O.error(`${a}: CDN server error attempt=${m} status=${l.status} errMsg=${b}`),new Error(`CDN upload server error: ${b}`)}if(p=l.headers.get("x-encrypted-param")??void 0,!p)throw O.error(`${a}: CDN response missing x-encrypted-param header attempt=${m}`),new Error("CDN upload response missing x-encrypted-param header");O.debug(`${a}: CDN upload success attempt=${m}`);break}catch(l){if(f=l,l instanceof Error&&l.message.includes("client error"))throw l;m<pe?O.warn(`${a}: attempt ${m} failed, retrying... err=${String(l)}`):O.error(`${a}: all ${pe} attempts failed err=${String(l)}`)}if(!p)throw f instanceof Error?f:new Error(`CDN upload failed after ${pe} attempts`);return{downloadParam:p}}async function Pe(t){let{filePath:e,toUserId:n,opts:r,cdnBaseUrl:s,mediaType:i,label:a}=t,o=await An.readFile(e),d=o.length,c=ke.createHash("md5").update(o).digest("hex"),u=yt(d),p=ke.randomBytes(16).toString("hex"),f=ke.randomBytes(16);O.debug(`${a}: file=${e} rawsize=${d} filesize=${u} md5=${c} filekey=${p}`);let m=await it({...r,filekey:p,media_type:i,to_user_id:n,rawsize:d,rawfilemd5:c,filesize:u,no_need_thumb:!0,aeskey:f.toString("hex")}),l=m.upload_full_url?.trim(),b=m.upload_param;if(!l&&!b)throw new Error(`${a}: getUploadUrl returned no upload URL (need upload_full_url or upload_param)`);let{downloadParam:L}=await kn({buf:o,uploadFullUrl:l||void 0,uploadParam:b??void 0,filekey:p,cdnBaseUrl:s,aeskey:f,label:`${a}[orig filekey=${p}]`});return{filekey:p,downloadEncryptedQueryParam:L,aeskey:f.toString("hex"),fileSize:d,fileSizeCiphertext:u}}async function Ct(t){return Pe({...t,mediaType:ue.IMAGE,label:"uploadImageToWeixin"})}async function St(t){return Pe({...t,mediaType:ue.VIDEO,label:"uploadVideoToWeixin"})}async function Ue(t){return Pe({...t,mediaType:ue.FILE,label:"uploadFileAttachmentToWeixin"})}S();var Z=y("channels");function Pn(){return`adam-wechat-${Date.now()}-${Math.random().toString(36).slice(2,7)}`}function Un(t){let e=t;return e=e.replace(/```[^\n]*\n?([\s\S]*?)```/g,(n,r)=>r.trim()),e=e.replace(/!\[[^\]]*\]\([^)]*\)/g,""),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/^\|[\s:|-]+\|$/gm,""),e=e.replace(/^\|(.+)\|$/gm,(n,r)=>r.split("|").map(s=>s.trim()).join(" ")),e}async function ve(t){let{to:e,text:n,mediaItem:r,opts:s,label:i}=t,a=[],o=Un(n);o&&a.push({type:_.TEXT,text_item:{text:o}}),a.push(r);let d="";for(let c of a){d=Pn();let u={msg:{from_user_id:"",to_user_id:e,client_id:d,message_type:K.BOT,message_state:X.FINISH,item_list:[c],context_token:s.contextToken}};await H({baseUrl:s.baseUrl,token:s.token,routeTag:s.routeTag,body:u})}return Z.debug(`${i}: sent to=${e} messageId=${d}`),{messageId:d}}async function vn(t){let{to:e,text:n,uploaded:r,opts:s}=t,i={type:_.IMAGE,image_item:{media:{encrypt_query_param:r.downloadEncryptedQueryParam,aes_key:Buffer.from(r.aeskey).toString("base64"),encrypt_type:1},mid_size:r.fileSizeCiphertext}};return ve({to:e,text:n,mediaItem:i,opts:s,label:"sendImageMessage"})}async function On(t){let{to:e,text:n,uploaded:r,opts:s}=t,i={type:_.VIDEO,video_item:{media:{encrypt_query_param:r.downloadEncryptedQueryParam,aes_key:Buffer.from(r.aeskey).toString("base64"),encrypt_type:1},video_size:r.fileSizeCiphertext}};return ve({to:e,text:n,mediaItem:i,opts:s,label:"sendVideoMessage"})}async function At(t){let{to:e,text:n,fileName:r,uploaded:s,opts:i}=t,a={type:_.FILE,file_item:{media:{encrypt_query_param:s.downloadEncryptedQueryParam,aes_key:Buffer.from(s.aeskey).toString("base64"),encrypt_type:1},file_name:r,len:String(s.fileSize)}};return ve({to:e,text:n,mediaItem:a,opts:i,label:"sendFileMessage"})}async function kt(t){let{filePath:e,to:n,text:r,opts:s,cdnBaseUrl:i}=t,a=re(e),o={baseUrl:s.baseUrl,token:s.token,routeTag:s.routeTag};if(a.startsWith("video/")){Z.debug(`sendWeixinMediaFile: uploading video filePath=${e} to=${n}`);let u=await St({filePath:e,toUserId:n,opts:o,cdnBaseUrl:i});return On({to:n,text:r,uploaded:u,opts:s})}if(a.startsWith("image/")){Z.debug(`sendWeixinMediaFile: uploading image filePath=${e} to=${n}`);let u=await Ct({filePath:e,toUserId:n,opts:o,cdnBaseUrl:i});return vn({to:n,text:r,uploaded:u,opts:s})}if(a.startsWith("audio/")){let u=Rt.basename(e);Z.debug(`sendWeixinMediaFile: uploading audio as file filePath=${e} name=${u} to=${n}`);let p=await Ue({filePath:e,fileName:u,toUserId:n,opts:o,cdnBaseUrl:i});return At({to:n,text:r,fileName:u,uploaded:p,opts:s})}let d=Rt.basename(e);Z.debug(`sendWeixinMediaFile: uploading file attachment filePath=${e} name=${d} to=${n}`);let c=await Ue({filePath:e,fileName:d,toUserId:n,opts:o,cdnBaseUrl:i});return At({to:n,text:r,fileName:d,uploaded:c,opts:s})}S();var h=y("channels"),Pt="https://novac2c.cdn.weixin.qq.com/c2c",De=new Map;function Ot(t){return x.join(fe(),".adam","wechat",`${t}.context-tokens.json`)}function Nn(t){let e=Ot(t);try{let n=R.readFileSync(e,"utf-8"),r=JSON.parse(n);for(let[s,i]of Object.entries(r))typeof i=="string"&&i&&De.set(`${t}:${s}`,i);h.debug({channelId:t,count:Object.keys(r).length},"Restored context tokens from disk")}catch{}}function Dn(t,e,n){let r=Ot(t);try{let s={};try{let a=R.readFileSync(r,"utf-8");s=JSON.parse(a)}catch{}s[e]=n;let i=x.dirname(r);R.mkdirSync(i,{recursive:!0}),R.writeFileSync(r,JSON.stringify(s),"utf-8")}catch(s){h.warn({channelId:t,userId:e},`Failed to persist context token: ${String(s)}`)}}function Ln(t,e,n){De.set(`${t}:${e}`,n),Dn(t,e,n)}function Oe(t,e){return De.get(`${t}:${e}`)}function Nt(t){return x.join(fe(),".adam","wechat",`${t}.sync`)}function Fn(t){try{return R.readFileSync(Nt(t),"utf-8")}catch{return""}}function Bn(t,e){let n=Nt(t);R.mkdirSync(x.dirname(n),{recursive:!0}),R.writeFileSync(n,e,"utf-8")}var Ne=1440*60*1e3,Ut=10,$n=20,vt=1440*60*1e3,qn=1320*60*1e3,Gn=1,Wn=7200*1e3;function Dt(t){return x.join(fe(),".adam","wechat",`${t}.session.json`)}function jn(t){let e=new Map,n=Dt(t);try{let r=R.readFileSync(n,"utf-8"),s=JSON.parse(r);for(let[i,a]of Object.entries(s))a&&typeof a.lastUserMessageAt=="number"&&e.set(i,a);h.debug({channelId:t,count:e.size},"Restored sessions from disk")}catch{}return e}function ee(t,e){let n=Dt(t);try{let r={};for(let[i,a]of e)r[i]=a;let s=x.dirname(n);R.mkdirSync(s,{recursive:!0}),R.writeFileSync(n,JSON.stringify(r),"utf-8")}catch(r){h.warn({channelId:t},`Failed to persist sessions: ${String(r)}`)}}var Vn=0;function te(){return`adam-wechat-${Date.now()}-${++Vn}`}var q=class{platform="wechat";id;config;status="disconnected";messageHandler=null;pollAbort=null;getUpdatesBuf="";sessions=new Map;pendingQueue=new Map;lastReminderAt=new Map;constructor(e,n){if(this.id=e,!n.baseUrl)throw new Error("WeChat adapter requires baseUrl");this.config=n}async connect(){if(!this.config.botToken)throw new Error("WeChat adapter requires botToken. Complete QR login first.");this.status="connecting",this.getUpdatesBuf=Fn(this.id),Nn(this.id),this.sessions=jn(this.id),this.pollAbort=new AbortController,this.status="connected",h.info({channelId:this.id},"WeChat adapter connected, starting long-poll"),this.startLongPoll()}async disconnect(){this.pollAbort&&(this.pollAbort.abort(),this.pollAbort=null),this.status="disconnected",h.info({channelId:this.id},"WeChat adapter disconnected")}getStatus(){if(this.status==="connected"&&le(this.id))return"error";if(this.status==="connected"){for(let[,e]of this.sessions)if(this.isSessionActive(e)&&e.quotaRemaining<=0)return"degraded"}return this.status}getCapabilities(){return{canEdit:!1,canQuote:!0,canParseQuote:!0,canInlineButtons:!1,maxTextLength:4e3,supportsAttachments:!0,maxAttachmentsPerMessage:1}}async sendMessage(e,n){if(le(this.id)){let c=Math.ceil(gt(this.id)/6e4);throw new Error(`WeChat session paused, ${c} min remaining. Re-scan QR to reconnect.`)}let r=this.getOrCreateSession(e),i=this.getSessionRemainingMs(r)/36e5;if(!this.isSessionActive(r))return h.warn({channelId:this.id,chatId:e.slice(0,12),lastUserMessageAt:r.lastUserMessageAt,sessionExpired:!0},"iLink session expired (>24h), message queued"),this.enqueueMessage(e,n),`queued-${te()}`;if(r.quotaRemaining<=0)return h.warn({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:0,remainingHours:i.toFixed(1)},"iLink quota exhausted, message queued"),this.enqueueMessage(e,n),`queued-${te()}`;let a=te(),o=Oe(this.id,e),d=this.config.cdnBaseUrl??Pt;try{let c=n.attachments?.[0],u=c?.path??n.mediaUrl,p=c?.contentType,f=c?.filename,m=c?.mediaType??n.mediaType;if(u){let l=!u.includes("://")||u.startsWith("file://"),b=x.join(fe(),".adam","wechat","media","outbound-tmp");await M.mkdir(b,{recursive:!0});let L=this.getExtensionFromMediaType(m,p),A;if(l){let I=u.startsWith("file://")?new URL(u).pathname:x.isAbsolute(u)?u:x.resolve(u),v=await M.readFile(I);A=x.join(b,`${Date.now()}-${Math.random().toString(36).slice(2,7)}${L}`),await M.writeFile(A,v)}else{let I=await fetch(u);if(!I.ok)throw new Error(`Failed to fetch media: ${I.status}`);let v=Buffer.from(await I.arrayBuffer());A=x.join(b,`${Date.now()}-${Math.random().toString(36).slice(2,7)}${L}`),await M.writeFile(A,v)}let w=A;if(f){let I=f.replace(/[\\/]/g,"-").replace(/\.\./g,"-").replace(/[\x00-\x1f]/g,"");if(I.length>0&&I.length<200){let v=x.join(b,`${Date.now()}-${I}`);await M.copyFile(A,v),await M.unlink(A).catch(()=>{}),w=v}}let U=await kt({filePath:w,to:e,text:n.content??"",opts:{baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,contextToken:o},cdnBaseUrl:d});return await M.unlink(w).catch(()=>{}),r.quotaRemaining--,ee(this.id,this.sessions),h.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:r.quotaRemaining,sessionRemainingHours:(this.getSessionRemainingMs(r)/36e5).toFixed(1)},"iLink send success: quota decremented"),this.checkAndSendReminder(e,r).catch(I=>{h.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(I)}`)}),U.messageId}return await H({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{msg:{from_user_id:"",to_user_id:e,client_id:a,message_type:K.BOT,message_state:X.FINISH,item_list:this.buildItemList(n),context_token:o}}}),r.quotaRemaining--,ee(this.id,this.sessions),h.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:r.quotaRemaining,sessionRemainingHours:(this.getSessionRemainingMs(r)/36e5).toFixed(1)},"iLink send success: quota decremented"),this.checkAndSendReminder(e,r).catch(l=>{h.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(l)}`)}),a}catch(c){if(c instanceof Error&&c.message.includes("ret=-2"))return r.quotaRemaining=0,ee(this.id,this.sessions),h.warn({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:0},"iLink quota exhausted (ret=-2 confirmed), message queued"),this.enqueueMessage(e,n),`queued-${te()}`;throw c}}onMessage(e){this.messageHandler=e}async sendTypingIndicator(e){if(le(this.id))return;let n=Oe(this.id,e);try{await rt({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{ilink_user_id:e,status:lt.TYPING}})}catch{}}updateConfig(e){Object.assign(this.config,e)}buildItemList(e){if(!e.content)return;let n={type:_.TEXT,text_item:{text:e.content}};if(e.replyToMessageId){let r=(e.quoteExcerpt??"").slice(0,80);n.ref_msg={message_item:{msg_id:e.replyToMessageId,text_item:{text:r}},title:e.quoteTitle}}return[n]}getOrCreateSession(e){let n=this.sessions.get(e);return n||(n={lastUserMessageAt:0,quotaRemaining:0},this.sessions.set(e,n)),n}isSessionActive(e){return e.lastUserMessageAt>0&&Date.now()-e.lastUserMessageAt<=Ne}getSessionRemainingMs(e){return e.lastUserMessageAt===0?0:Math.max(0,Ne-(Date.now()-e.lastUserMessageAt))}enqueueMessage(e,n){let r=this.pendingQueue.get(e);r||(r=[],this.pendingQueue.set(e,r));let s=Date.now();r=r.filter(i=>s-i.queuedAt<vt),r.length>=$n&&(r.shift(),h.warn({channelId:this.id,chatId:e.slice(0,12)},"Queue full, dropping oldest message")),r.push({message:n,queuedAt:s}),this.pendingQueue.set(e,r),h.info({channelId:this.id,chatId:e.slice(0,12),queueDepth:r.length},"Message enqueued")}async flushQueue(e){let n=this.pendingQueue.get(e);if(!n||n.length===0)return;let r=this.getOrCreateSession(e),s=Math.min(n.length,Math.max(0,r.quotaRemaining-2));if(s<=0){h.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:r.quotaRemaining},"Queue flush skipped: insufficient quota (reserving 2 for conversation)");return}h.info({channelId:this.id,chatId:e.slice(0,12),queueDepth:n.length,sending:s,quotaRemaining:r.quotaRemaining},"Flushing queued messages");let i=0;for(;i<s&&n.length>0;){let a=n[0];if(Date.now()-a.queuedAt>vt){n.shift();continue}try{if(await this.sendMessage(e,a.message),n.shift(),i++,r.quotaRemaining<=0)break}catch{h.warn({channelId:this.id,chatId:e.slice(0,12)},"Queue flush: send failed, stopping");break}}n.length===0&&this.pendingQueue.delete(e),h.info({channelId:this.id,chatId:e.slice(0,12),sent:i,remaining:n.length},"Queue flush complete")}async checkAndSendReminder(e,n){let r=Date.now(),s=this.lastReminderAt.get(e)??0;if(r-s<Wn)return;let i=this.getSessionRemainingMs(n),o=r-n.lastUserMessageAt>=qn,d=n.quotaRemaining<=Gn;if(!o&&!d)return;let c=(i/36e5).toFixed(1),u;o&&d?u=`[\u7CFB\u7EDF\u63D0\u9192] \u6D88\u606F\u7A97\u53E3\u5373\u5C06\u5173\u95ED\uFF08\u5269\u4F59${c}\u5C0F\u65F6/${n.quotaRemaining}\u6761\u914D\u989D\uFF09\u3002\u8BF7\u56DE\u590D\u4EFB\u610F\u6D88\u606F\u4EE5\u4FDD\u6301\u8FDE\u63A5\u3002`:o?u=`[\u7CFB\u7EDF\u63D0\u9192] \u6D88\u606F\u7A97\u53E3\u5373\u5C06\u5173\u95ED\uFF08\u5269\u4F59${c}\u5C0F\u65F6\uFF09\u3002\u8BF7\u56DE\u590D\u4EFB\u610F\u6D88\u606F\u4EE5\u4FDD\u6301\u8FDE\u63A5\u3002`:u=`[\u7CFB\u7EDF\u63D0\u9192] \u6D88\u606F\u914D\u989D\u5373\u5C06\u7528\u5B8C\uFF08\u5269\u4F59${n.quotaRemaining}\u6761\uFF09\u3002\u8BF7\u56DE\u590D\u4EFB\u610F\u6D88\u606F\u4EE5\u91CD\u7F6E\u914D\u989D\u3002`;let p=Oe(this.id,e);try{await H({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{msg:{from_user_id:"",to_user_id:e,client_id:te(),message_type:K.BOT,message_state:X.FINISH,item_list:[{type:_.TEXT,text_item:{text:u}}],context_token:p}}}),n.quotaRemaining--,this.lastReminderAt.set(e,r),ee(this.id,this.sessions),h.info({channelId:this.id,chatId:e.slice(0,12),remainingHours:c,quotaRemaining:n.quotaRemaining,trigger:o?"time":"quota"},"iLink session reminder sent")}catch(f){h.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(f)}`)}}async startLongPoll(){let e=this.pollAbort?.signal,n=0,r=3,s=3e4,i=2e3;for(;!e?.aborted;)try{let a=await st({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,get_updates_buf:this.getUpdatesBuf});if(a.ret===Re||a.errcode===Re){mt(this.id),this.status="error",h.error({channelId:this.id},"Session expired (errcode=-14), pausing for 1 hour"),await this.sleep(ce,e),pt(this.id),this.status="connected";continue}if(a.ret!==void 0&&a.ret!==0||a.errcode!==void 0&&a.errcode!==0){n++,h.error({channelId:this.id,ret:a.ret,errcode:a.errcode},"getUpdates API error"),n>=r?(n=0,await this.sleep(s,e)):await this.sleep(i,e);continue}n=0,a.get_updates_buf&&(this.getUpdatesBuf=a.get_updates_buf,Bn(this.id,a.get_updates_buf));for(let d of a.msgs??[])await this.processInbound(d)}catch(a){if(e?.aborted)return;n++,h.error({channelId:this.id,error:a},"getUpdates error"),n>=r?(n=0,await this.sleep(s,e)):await this.sleep(i,e)}}async processInbound(e){if(!this.messageHandler)return;let n=!!e.group_id,r=n?e.group_id:e.from_user_id??"",s=e.from_user_id??"";e.context_token&&r&&Ln(this.id,r,e.context_token);let i=this.getOrCreateSession(r),a=i.quotaRemaining;i.lastUserMessageAt=Date.now(),i.quotaRemaining=Ut,ee(this.id,this.sessions),h.info({channelId:this.id,chatId:r.slice(0,12),quotaReset:!0,prevQuota:a,newQuota:Ut,sessionWindowMs:Ne},"iLink session reset: user message received, quota restored"),this.flushQueue(r);let o="",d,c=[],u;for(let m of e.item_list??[]){let l=m.ref_msg?.message_item?.msg_id;if(l){u=l;break}}for(let m of e.item_list??[])m.type===_.TEXT&&m.text_item?.text&&(o+=m.text_item.text),m.type===_.IMAGE&&(d="image",c.push(m)),m.type===_.VOICE&&(d="audio",c.push(m),m.voice_item?.text&&!o&&(o=m.voice_item.text)),m.type===_.FILE&&(d="file",c.push(m)),m.type===_.VIDEO&&(d="video",c.push(m));if(!o&&!d)return;let p;if(c.length>0){let m=this.config.cdnBaseUrl??Pt;try{let l=await Mt(c[0],{cdnBaseUrl:m,channelId:this.id});l&&(p=l.path,d=l.type)}catch(l){h.error({channelId:this.id},`Media download failed: ${String(l)}`)}}let f={channelId:this.id,platform:"wechat",chatId:r,senderId:s,content:o,mediaType:d,mediaPath:p,isGroup:n,timestamp:e.create_time_ms??Date.now(),raw:e,...u?{quotedPlatformMessageId:u}:{}};this.messageHandler(f)}getExtensionFromMediaType(e,n){if(n){let r=ie(n);if(r&&r!==".bin")return r}switch(e){case"image":return".png";case"video":return".mp4";case"audio":return".mp3";default:return".bin"}}sleep(e,n){return new Promise((r,s)=>{let i=setTimeout(r,e);n?.addEventListener("abort",()=>{clearTimeout(i),s(new Error("aborted"))},{once:!0})})}};S();S();var zn=y("channels"),he=class{platform="discord";id;config;status="disconnected";messageHandler=null;client=null;constructor(e,n){if(this.id=e,!n.botToken)throw new Error("Discord adapter requires botToken");this.config=n}async connect(){this.status="connecting";try{let{Client:e,GatewayIntentBits:n}=await import("discord.js");this.client=new e({intents:[n.Guilds,n.GuildMessages,n.MessageContent,n.DirectMessages]});let r=this.client;r.on("messageCreate",s=>{if(!this.messageHandler||s.author.bot||this.config.allowedGuildIds?.length&&s.guildId&&!this.config.allowedGuildIds.includes(s.guildId))return;let i={channelId:this.id,platform:"discord",chatId:s.channelId,senderId:s.author.id,senderName:s.author.displayName??s.author.username,content:s.content,isGroup:!!s.guildId,timestamp:s.createdTimestamp,raw:s};this.messageHandler(i)}),await r.login(this.config.botToken),this.status="connected",zn.info({channelId:this.id},"Discord bot connected")}catch(e){throw this.status="error",e}}async disconnect(){this.client&&await this.client.destroy(),this.client=null,this.status="disconnected"}getStatus(){return this.status}getCapabilities(){return{canEdit:!0,canQuote:!0,canParseQuote:!0,canInlineButtons:!0,maxTextLength:2e3,supportsAttachments:!0}}async sendMessage(e,n){if(!this.client)throw new Error("Discord client not connected");let s=await this.client.channels.fetch(e);if(!s||!("send"in s))throw new Error(`Channel ${e} not found or not text channel`);return(await s.send({content:n.content,reply:n.replyToMessageId?{messageReference:n.replyToMessageId}:void 0})).id}onMessage(e){this.messageHandler=e}async sendTypingIndicator(e){if(!this.client)return;let r=await this.client.channels.fetch(e);r&&"sendTyping"in r&&await r.sendTyping()}};import{statSync as as}from"fs";import{ImapFlow as os}from"imapflow";import ds from"nodemailer";import{existsSync as Qn,mkdirSync as Hn,readFileSync as Kn,writeFileSync as Xn}from"fs";import{dirname as Jn,join as Lt}from"path";import{homedir as Yn}from"os";var Zn={lastUid:0,seenMessageIds:[],sentMessageIds:[],updatedAt:0};function Le(t=process.env.ADAM_TEST_DIR??Lt(Yn(),".adam")){return Lt(t,"email-gateway","state.json")}function ye(t=Le()){if(!Qn(t))return{...Zn};let e=JSON.parse(Kn(t,"utf-8"));return{uidValidity:e.uidValidity,lastUid:Number.isInteger(e.lastUid)?e.lastUid:0,seenMessageIds:Array.isArray(e.seenMessageIds)?e.seenMessageIds.filter(Ft):[],sentMessageIds:Array.isArray(e.sentMessageIds)?e.sentMessageIds.filter(Ft):[],updatedAt:typeof e.updatedAt=="number"?e.updatedAt:0}}function ne(t,e=Le()){Hn(Jn(e),{recursive:!0}),Xn(e,JSON.stringify({...t,updatedAt:Date.now()},null,2),"utf-8")}function Bt(t,e){let n=G(e);return n?{...t,seenMessageIds:t.seenMessageIds.includes(n)?t.seenMessageIds:[...t.seenMessageIds,n]}:t}function es(t,e){let n=G(e);return n?{...t,sentMessageIds:t.sentMessageIds.includes(n)?t.sentMessageIds:[...t.sentMessageIds,n]}:t}function $t(t,e=Le()){let n=es(ye(e),t);return ne(n,e),n}function G(t){return typeof t=="string"?t.trim():""}function Ft(t){return typeof t=="string"}import{Readable as ts}from"stream";import{MailParser as ns}from"mailparser";import{convert as ss}from"html-to-text";async function Gt(t){let e=new ns({skipImageLinks:!0,skipTextToHtml:!0}),n={},r,s,i,a=[],o,d="",c="",u="",p,f=0,m;if(await new Promise((L,A)=>{e.on("headers",w=>{try{for(let[I,v]of w.entries())n[I.toLowerCase()]=is(v);r=qt(w.get("message-id")),o=qt(w.get("subject")),u=Vt(w.get("content-type"))??"";let U=w.get("date");U instanceof Date&&(p=U.getTime()),s=Wt(w.get("from"),"from"),i=rs(w.get("reply-to"),"reply-to"),a=jt(w.get("to"))}catch(U){m=U instanceof Error?U:new Error(String(U))}}),e.on("data",w=>{if(w.type==="attachment"){f+=1,w.release?.(),w.content?.resume?.();return}d=w.text??"",c=typeof w.html=="string"?w.html:""}),e.on("error",A),e.on("end",L),ts.from([t]).pipe(e)}),m)throw m;if(!s)throw new Error("Inbound email must contain exactly one valid From address");let l=u.toLowerCase()==="text/html",b=d.trim();return(l||!b)&&c.trim()&&(b=ss(c,{wordwrap:!1,selectors:[{selector:"h1",format:"heading",options:{uppercase:!1}},{selector:"h2",format:"heading",options:{uppercase:!1}},{selector:"h3",format:"heading",options:{uppercase:!1}},{selector:"h4",format:"heading",options:{uppercase:!1}},{selector:"h5",format:"heading",options:{uppercase:!1}},{selector:"h6",format:"heading",options:{uppercase:!1}}]}).trim()),!b&&o&&(b=o.trim()),{messageId:r,from:s,replyTo:i,to:a,subject:o,text:b,date:p,rawHeaders:n,attachmentCount:f}}function Wt(t,e){let n=jt(t);if(n.length!==1){if(n.length===0)return;throw new Error(`Inbound email ${e} must contain exactly one mailbox address`)}return n[0]}function rs(t,e){if(t)return Wt(t,e)}function jt(t){return t?typeof t=="string"?[k(t)]:(t.value??[]).map(r=>r.address).filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>k(r)):[]}function qt(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(String).join(", ")}function is(t){if(t instanceof Date)return t.toISOString();if(typeof t=="string")return t;if(Array.isArray(t))return t.map(String).join(", ");let e=Vt(t);return e||(t&&typeof t=="object"&&"text"in t?String(t.text??""):String(t??""))}function Vt(t){if(typeof t=="string")return t;if(t&&typeof t=="object"&&"value"in t){let e=t.value;if(typeof e=="string")return e}}var zt=3e4,us=5e3,cs=3e5,ls=1.33,ms=3e4;function gs(t){if(!t||t.length===0)return zt;let e=0;for(let r of t)try{e+=as(r.path).size}catch{}let n=e*ls/(1024*1024);return Math.min(cs,zt+Math.ceil(n*us))}var Be=class{imapClient;smtpTransporter;pollTimer;handlers=[];status={status:"stopped"};state=ye();async start(e){if(await this.stop(),!e.enabled){this.status={status:"stopped",details:{reason:"disabled"}};return}this.status={status:"starting",lastStartedAt:Date.now()};try{this.imapClient=new os({host:e.imap.host,port:e.imap.port,secure:e.imap.secure,auth:{user:e.imap.auth.user,pass:e.imap.auth.pass}}),await this.imapClient.connect();let n=await this.imapClient.mailboxOpen(e.imap.mailbox),r=n?.uidValidity?Number(n.uidValidity):void 0;r&&this.state.uidValidity&&r!==this.state.uidValidity?(this.state={...this.state,uidValidity:r,lastUid:0,seenMessageIds:[]},ne(this.state)):r&&(this.state={...this.state,uidValidity:r},ne(this.state)),this.smtpTransporter=ds.createTransport({host:e.smtp.host,port:e.smtp.port,secure:e.smtp.secure,auth:{user:e.smtp.auth.user,pass:e.smtp.auth.pass}}),await this.smtpTransporter.verify(),this.status={status:"connected",lastStartedAt:Date.now(),lastCheckedAt:Date.now()},this.schedulePoll(e)}catch(n){throw await this.cleanupResources(),this.status={status:"error",lastError:$e(n),details:{stage:this.smtpTransporter?"smtp":"imap"}},n}}async stop(){await this.cleanupResources(),this.status={status:"stopped"}}getStatus(){return{...this.status}}onInbound(e){this.handlers.push(e)}async send(e){if(!this.smtpTransporter)throw new Error("EmailGateway SMTP transporter is not started");let n=gs(e.attachments),r=await ps(this.smtpTransporter.sendMail({from:e.from,to:e.to,subject:e.subject,text:e.text,html:e.html,attachments:e.attachments}),n,`SMTP send timed out after ${Math.round(n/1e3)}s`),s=G(r.messageId);if(!s)throw new Error("SMTP send returned no Message-ID");return this.state=$t(s),s}isSentByAdam(e){let n=G(e);return n.length>0&&this.state.sentMessageIds.includes(n)}schedulePoll(e){this.pollTimer=setInterval(()=>{this.poll(e)},ms)}async poll(e){if(this.imapClient)try{this.state=ye();let n=`${this.state.lastUid+1}:*`,r=this.imapClient.fetch?.(n,{uid:!0,source:!0,envelope:!0},{uid:!0});if(!r||!r[Symbol.asyncIterator])return;let s=!1;for await(let i of r){let a=Number(i.uid);if(!Number.isInteger(a)||a<=this.state.lastUid)continue;if(!i.source){this.markDegraded(new Error(`IMAP fetch item ${a} is missing source`)),s=!0;break}let o;try{o=await Gt(i.source)}catch(u){this.markDegraded(u),s=!0;break}let d=o.rawHeaders["x-adam-probe-id"],c=G(o.messageId);if(d?.startsWith("adam-probe-")){this.advanceCursor(a);continue}if(c&&this.state.sentMessageIds.includes(c)){this.advanceCursor(a);continue}if(c&&this.state.seenMessageIds.includes(c)){this.advanceCursor(a);continue}try{await Promise.all(this.handlers.map(u=>u(o)))}catch(u){this.markDegraded(u),s=!0;break}this.state=Bt(this.state,c),this.advanceCursor(a)}s||(this.status={...this.status,status:"connected",lastCheckedAt:Date.now(),lastError:void 0})}catch(n){this.markDegraded(n)}}advanceCursor(e){this.state={...this.state,lastUid:e},ne(this.state)}markDegraded(e){this.status={...this.status,status:"degraded",lastError:$e(e),lastCheckedAt:Date.now()}}async cleanupResources(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=void 0);let e=this.imapClient,n=this.smtpTransporter;this.imapClient=void 0,this.smtpTransporter=void 0,e&&(await Fe(e.logout?.()),await Fe(e.close?.())),await Fe(n?.close?.())}},Qt;function C(){return Qt??=new Be,Qt}async function be(t){await C().start(t)}async function Jr(t,e){await C().stop(),await C().start(t)}async function Yr(t){await C().stop()}async function ps(t,e,n){let r;try{return await Promise.race([t,new Promise((s,i)=>{r=setTimeout(()=>i(new Error(n)),e)})])}catch(s){throw new Error($e(s))}finally{r&&clearTimeout(r)}}function $e(t){return t instanceof Error?t.message.replace(/pass(word)?=[^\s]+/gi,"password=****"):"Email gateway operation failed"}async function Fe(t){t&&typeof t.then=="function"&&await t.catch(()=>{})}S();var ys=/\b55[234]\b/,bs=/(?:size|too large|exceeds|maximum|over.*?limit)/i,ws=/\b(\d{6,11})\b/,_s=/Final-Recipient:\s*rfc822;\s*([^\s>]+@([^\s>;]+))/i,Is=/To:[\s<]*([^\s>;]+@([^\s>;]+))/i;function Ht(t){let e=t.text??"",n=e.split(/\r?\n/).filter(a=>ys.test(a)&&bs.test(a));if(n.length===0)return null;let r=e.match(_s)??e.match(Is);if(!r)return null;let s=r[2].toLowerCase().trim();if(!Ve.test(s))return null;let i=null;for(let a of n){let o=a.match(ws);if(o){let d=parseInt(o[1],10);if(Number.isFinite(d)&&d>=1048576&&d<=209715200){i=d;break}}}return i===null?null:{recipientDomain:s,capBytes:i}}var we=y("channels"),Kt=!1;function Xt(t){if(Kt){we.debug("Bounce handler already registered; skipping duplicate registration");return}Kt=!0,t.onInbound(async e=>{let n=Ht(e);if(!n){(/MAILER-DAEMON/i.test(e.from??"")||/^no-reply@mailsupport\.aliyun\.com$/i.test(e.from??"")||/Mail Delivery|Undeliverable|Returned mail|Delivery Status Notification|退信|无法投递|投递失败/i.test(e.subject??""))&&we.warn({from:e.from,subject:e.subject},"Inbound looks like bounce but parser did not recognize a size-limit cap");return}let{recipientDomain:r,capBytes:s}=n;we.info({recipientDomain:r,capBytes:s},"Bounce-learning: detected SMTP size-limit bounce");let i=F().filter(a=>a.platform==="email");for(let a of i)try{Qe(a.id,r,s)}catch(o){we.warn({channelId:a.id,recipientDomain:r,capBytes:s,err:o},"Bounce-learning: setRecipientCap failed (out of range or DB error); skipping")}})}S();var _e=y("channels"),qe=class{constructor(e){this.gateway=e}gateway;adaptersByAddress=new Map;channelAddressById=new Map;registerAdapter(e,n){if(!Ke(e)||!e.enabled)return;let r=B(e);this.unregisterAdapter(e.id),this.adaptersByAddress.set(r,n),this.channelAddressById.set(e.id,r)}unregisterAdapter(e){let n=this.channelAddressById.get(e);n&&(this.adaptersByAddress.delete(n),this.channelAddressById.delete(e))}refreshFromChannels(e,n){this.adaptersByAddress.clear(),this.channelAddressById.clear();for(let r of e){let s=n.get(r.id);if(s)try{this.registerAdapter(r,s)}catch(i){_e.warn({channelId:r.id,error:i},"Invalid email channel skipped during router refresh")}}}async handle(e){if(e.messageId&&this.gateway.isSentByAdam(e.messageId)){_e.debug({messageId:e.messageId},"Skipping Adam-sent email");return}let n;try{n=k(e.from)}catch(s){_e.warn({from:e.from,error:s},"Skipping email with invalid sender address");return}let r=this.adaptersByAddress.get(n);if(!r){_e.info({from:n},"Skipping unmatched inbound email");return}await r.acceptInbound(e)}hasAddress(e){return this.adaptersByAddress.has(k(e))}},Ie,Jt;function Ge(t){return(!Ie||Jt!==t)&&(Ie=new qe(t),Jt=t,t.onInbound(e=>Ie?.handle(e)??Promise.resolve())),Ie}import{existsSync as Es}from"fs";import{basename as Ts,isAbsolute as xs}from"path";function Yt(t){let e=[];return t.mediaUrl&&e.push({path:t.mediaUrl,mediaType:t.mediaType}),t.attachments&&e.push(...t.attachments),e.map(Ms)}function Ms(t){let e=t.path.startsWith("file://")?new URL(t.path).pathname:t.path;if(!xs(e)||e.includes("://"))throw new Error("Email attachment path must be an absolute local file path");if(!Es(e))throw new Error(`Email attachment file not found: ${e}`);return{filename:t.filename??Ts(e),path:e,...t.contentType?{contentType:t.contentType}:t.mediaType?{contentType:Cs(t.mediaType)}:{}}}function Cs(t){return"application/octet-stream"}import Ss from"markdown-it";var Rs=new Ss({html:!1,linkify:!0});function Zt(t){return{text:Je(t),html:Rs.render(t)}}function en(t){let e=t.prefix.trim()||"Adam";return t.messageType==="report"||t.messageType==="status_report"?`[${e} Report]`:t.messageType==="deliver"||t.messageType==="result_delivery"?`[${e} Deliver]`:`[${e}]`}var Ee=class{platform="email";id;channel;gateway;handler;inboundDispatchHandler;status="disconnected";identity;constructor(e,n,r={}){this.channel=e,this.gateway=n,this.id=e.id,this.identity=r}async connect(){let e=this.gateway.getStatus();this.status=Te(e.status)}async disconnect(){this.status="disconnected"}getStatus(){return this.status}getCapabilities(){return{canEdit:!1,canQuote:!1,canParseQuote:!1,canInlineButtons:!1,maxTextLength:Number.POSITIVE_INFINITY,supportsAttachments:!0}}async sendMessage(e,n){let r=k(e),s=B(this.channel);if(r!==s)throw new Error("Email channel recipient does not match configured address");let i=Zt(n.content);return this.gateway.send({from:this.identity.from?Xe(this.identity.from,this.identity.displayName):void 0,to:r,subject:en({prefix:this.identity.subjectPrefix??"Adam",messageType:n.messageType??"reply"}),text:i.text,html:i.html,attachments:Yt(n)})}onMessage(e){this.handler=e}onInboundDispatch(e){this.inboundDispatchHandler=e}syncGatewayStatus(){this.status=Te(this.gateway.getStatus().status)}async acceptInbound(e){let n=k(e.from),r={channelId:this.channel.id,platform:"email",chatId:n,senderId:n,senderName:e.from,content:e.text,replyToMessageId:e.messageId,isGroup:!1,timestamp:e.date??Date.now(),raw:{messageId:e.messageId,subject:e.subject,attachmentCount:e.attachmentCount,headers:e.rawHeaders}};this.handler?.(r),this.inboundDispatchHandler&&await this.inboundDispatchHandler(r)}};function Te(t){switch(t){case"connected":return"connected";case"starting":return"connecting";case"degraded":case"error":return"degraded";case"stopped":return"disconnected";default:return"disconnected"}}var tn=y("channels"),We=new Map;async function W(t,e){if(t.hasAdapter(e.id))return!0;if(e.platform==="wechat"){let n=e.config;return n.botToken?(await t.addChannel(e,new q(e.id,n)),!0):!1}if(e.platform==="discord"){let n=e.config;return n.botToken?(await t.addChannel(e,new he(e.id,{botToken:n.botToken})),!0):!1}if(e.platform==="email"){B(e);let n=C(),r=V().emailGateway,s=new Ee(e,n,{from:r?.smtp?.from||r?.address,displayName:r?.displayName,subjectPrefix:r?.subjectPrefix??"Adam"});We.set(e.id,s),Ge(n).registerAdapter(e,s);try{await As(),await t.addChannel(e,s)}catch(i){throw await j(t,e),i}return!0}return!1}async function Ai(t){for(let e of F(!0))try{await W(t,e)}catch(n){z(e.id,"error"),tn.warn({channelId:e.id,platform:e.platform,error:n},"Failed to register built-in channel adapter")}}async function nn(t,e){e.platform==="email"&&(await j(t,e),e.enabled&&await W(t,e))}async function sn(t,e){await j(t,e)}async function j(t,e){e.platform==="email"&&(Ge(C()).unregisterAdapter(e.id),We.delete(e.id),t?.hasAdapter(e.id)&&await t.removeChannel(e.id))}function ki(t){for(let[e,n]of We.entries())n.syncGatewayStatus(),z(e,n.getStatus())}async function As(){let t=V().emailGateway;if(!t?.enabled)return;let e=C().getStatus().status;if(!(e!=="stopped"&&e!=="error"))try{await be(t),Xt(C())}catch(n){tn.warn({error:ks(n)},"EmailGateway start failed during built-in adapter registration")}}function ks(t){return t instanceof Error?t.message.replace(/pass(word)?=[^\s]+/gi,"password=****"):"Email gateway operation failed"}var P=g.object({id:g.string().uuid()}),Us=g.object({name:g.string().min(1,"name is required"),platform:g.string().min(1,"platform is required"),config:g.record(g.string(),g.unknown()),enabled:g.boolean().optional().default(!0),linkedRoleId:g.string().optional(),allowedChatIds:g.array(g.string()).optional()}),vs=g.object({name:g.string().min(1).optional(),enabled:g.boolean().optional(),config:g.record(g.string(),g.unknown()).optional(),linkedRoleId:g.string().optional(),allowedChatIds:g.array(g.string()).optional(),viewerKey:g.string().min(1).max(100).regex(/^[a-zA-Z0-9_.@:-]+$/,"viewerKey must be alphanumeric or one of _ . @ : -").optional(),defaultRecipientCapBytes:g.number().int().min(1048576).max(209715200).optional(),recipientCapMap:g.record(g.string().regex(/^[a-z0-9.-]+$/),g.number().int().min(1048576).max(209715200)).optional()}),je;function Vi(t){je=t}function zi(){return je}async function Qi(t){let e=je;async function n(r){ze(r);try{return e&&r.enabled&&await W(e,r),r}catch(s){throw await j(e,r),xe(r.id),s}}t.get("/channels",{schema:{tags:["Channels"],summary:"List channels",querystring:{type:"object",properties:{enabled:{type:"boolean"}}}}},async(r,s)=>({channels:F(r.query.enabled).map(Q)})),t.post("/channels",{schema:{tags:["Channels"],summary:"Create a channel",body:{type:"object",required:["name","platform","config"],properties:{name:{type:"string",minLength:1},platform:{type:"string",minLength:1},config:{type:"object"},enabled:{type:"boolean"},linkedRoleId:{type:"string"},allowedChatIds:{type:"array",items:{type:"string"}}}}}},async(r,s)=>{let i=Us.safeParse(r.body);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});let{name:a,platform:o,config:d,enabled:c,linkedRoleId:u,allowedChatIds:p}=i.data,f=d;if(o==="email")try{f={...Me(d)}}catch(l){return s.status(400).send({code:"VALIDATION_ERROR",message:l instanceof Error?l.message:String(l)})}let m={id:Ps(),name:a,platform:o,enabled:c,status:"disconnected",config:f,linkedRoleId:u,allowedChatIds:p,viewerKey:Ye(),createdAt:Date.now(),messageCount:0};try{await n(m)}catch(l){return s.status(400).send({code:"VALIDATION_ERROR",message:D(l)})}return s.status(201).send({channel:Q(m)})}),t.get("/channels/:id",{schema:{tags:["Channels"],summary:"Get channel by ID",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});let a=E(i.data.id);return a?{channel:Q(a)}:s.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),t.patch("/channels/:id",{schema:{tags:["Channels"],summary:"Update channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",properties:{name:{type:"string"},enabled:{type:"boolean"},config:{type:"object"},linkedRoleId:{type:"string"},allowedChatIds:{type:"array",items:{type:"string"}},viewerKey:{type:"string",minLength:1,maxLength:100}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});let a=E(i.data.id);if(!a)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let o=vs.safeParse(r.body);if(!o.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(o.error)});let d={...o.data};if(d.config&&(d.config=et(d.config,a.config)),(a.platform==="email"||d.config)&&(d.config||a.config)){let p=d.config??a.config;if(a.platform==="email")try{d.config={...Me(p)}}catch(f){return s.status(400).send({code:"VALIDATION_ERROR",message:f instanceof Error?f.message:String(f)})}}let c=a.platform==="email"&&(d.enabled!==void 0||d.config!==void 0);se(a.id,d);let u=E(a.id);if(e&&u&&c)try{await nn(e,u)}catch(p){if(se(a.id,{name:a.name,enabled:a.enabled,status:a.status,config:a.config,linkedRoleId:a.linkedRoleId,allowedChatIds:a.allowedChatIds,lastMessageAt:a.lastMessageAt,messageCount:a.messageCount}),await j(e,u),a.enabled)try{await W(e,a)}catch(f){return s.status(500).send({code:"RESTORE_FAILED",message:D(f)})}return s.status(400).send({code:"VALIDATION_ERROR",message:D(p)})}return{channel:u&&Q(u)}}),t.delete("/channels/:id",{schema:{tags:["Channels"],summary:"Delete channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});let a=E(i.data.id);if(!a)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(xe(a.id),e)try{await sn(e,a)}catch(o){t.log.warn({channelId:a.id,error:D(o)},"Failed to clean up built-in channel runtime")}return s.status(204).send()}),t.post("/channels/:id/connect",{schema:{tags:["Channels"],summary:"Connect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});if(!e)return s.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let a=E(i.data.id);if(!a)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(a.platform==="email")try{await Os()}catch(o){let d=C().getStatus();return z(a.id,Te(d.status)),s.status(409).send({code:"EMAIL_GATEWAY_NOT_READY",message:D(o),gatewayStatus:d})}if(!e.hasAdapter(a.id))try{await W(e,a)}catch(o){return s.status(400).send({code:"VALIDATION_ERROR",message:D(o)})}if(!e.hasAdapter(a.id))return s.status(400).send({code:"NO_ADAPTER",message:"No adapter registered for this channel. Install the appropriate adapter first."});try{await e.connectChannel(a.id);let o=E(a.id)?.status??e.getChannelStatus(a.id);return o!=="connected"?s.status(409).send({code:"CONNECT_INCOMPLETE",message:`Channel connect finished with status "${o}"`,status:o}):{channelId:a.id,status:o}}catch(o){return s.status(500).send({code:"CONNECT_FAILED",message:D(o)})}}),t.post("/channels/:id/disconnect",{schema:{tags:["Channels"],summary:"Disconnect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});if(!e)return s.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let a=E(i.data.id);return a?(await e.disconnectChannel(a.id),{channelId:a.id,status:"disconnected"}):s.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),t.get("/channels/:id/capabilities",{schema:{tags:["Channels"],summary:"Get channel adapter capabilities",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});if(!E(i.data.id))return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(!e)return s.status(503).send({code:"MANAGER_UNAVAILABLE",message:"ChannelManager not initialized"});let o=e.getCapabilities(i.data.id);return o?{capabilities:o}:s.status(404).send({code:"ADAPTER_NOT_REGISTERED",message:"Channel adapter not active"})}),t.get("/channels/:id/messages",{schema:{tags:["Channels"],summary:"Get channel message history",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50},offset:{type:"integer",minimum:0,default:0}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});let a=E(i.data.id);if(!a)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let{limit:o=50,offset:d=0}=r.query;return{messages:He(a.id,o,d)}}),t.post("/channels/:id/wechat/qr-start",{schema:{tags:["WeChat"],summary:"Start WeChat QR login",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});let a=E(i.data.id);if(!a)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(a.platform!=="wechat")return s.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=a.config;return await ut({apiBaseUrl:o.baseUrl,routeTag:o.routeTag})}),t.post("/channels/:id/wechat/qr-wait",{schema:{tags:["WeChat"],summary:"Wait for WeChat QR scan",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",properties:{sessionKey:{type:"string"},timeoutMs:{type:"number"}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});let a=E(i.data.id);if(!a)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(a.platform!=="wechat")return s.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=a.config,{sessionKey:d,timeoutMs:c}=r.body??{},u=await ct({sessionKey:d??"",apiBaseUrl:o.baseUrl,timeoutMs:c??12e4,routeTag:o.routeTag});if(u.connected&&u.botToken){let p={...o,botToken:u.botToken,accountId:u.accountId,baseUrl:u.baseUrl??o.baseUrl,userId:u.userId};if(se(a.id,{config:p}),e){let f=new q(a.id,p),m=E(a.id);m&&await e.addChannel(m,f)}}return{connected:u.connected,accountId:u.accountId,message:u.message}})}function D(t){return t instanceof Error?t.message.replace(/pass(word)?=[^\s]+/gi,"password=****"):String(t)}async function Os(){let t=V().emailGateway;if(!t?.enabled)throw new Error("Email Gateway is disabled. Enable Email Gateway in Settings before connecting Mail channels.");let e=C();e.getStatus().status!=="connected"&&await be(t);let n=e.getStatus();if(n.status!=="connected"){let r=n.lastError?`: ${n.lastError}`:"";throw new Error(`Email Gateway status is ${n.status}${r}`)}}export{$t as a,G as b,Gt as c,C as d,Jr as e,Yr as f,Ai as g,ki as h,Vi as i,zi as j,Qi as k};
@@ -1,4 +1,4 @@
1
- import{o as t,q as d}from"./chunk-LMQPGVM7.js";d();function s(e){return{id:e.id,taskId:e.task_id,roleId:void 0,plan:JSON.parse(e.plan_json),status:e.status,approvalType:e.approval_type??void 0,deviationReport:e.deviation_report_json?JSON.parse(e.deviation_report_json):void 0,learnedRules:e.learned_rules_json?JSON.parse(e.learned_rules_json):void 0,createdAt:e.created_at,approvedAt:e.approved_at??void 0,reviewedAt:e.reviewed_at??void 0}}function p(e){t().prepare(`
1
+ import{o as t,q as d}from"./chunk-ZEGZ2I35.js";d();function s(e){return{id:e.id,taskId:e.task_id,roleId:void 0,plan:JSON.parse(e.plan_json),status:e.status,approvalType:e.approval_type??void 0,deviationReport:e.deviation_report_json?JSON.parse(e.deviation_report_json):void 0,learnedRules:e.learned_rules_json?JSON.parse(e.learned_rules_json):void 0,createdAt:e.created_at,approvedAt:e.approved_at??void 0,reviewedAt:e.reviewed_at??void 0}}function p(e){t().prepare(`
2
2
  INSERT INTO task_plans (id, task_id, plan_json, status, approval_type,
3
3
  deviation_report_json, learned_rules_json, created_at, approved_at, reviewed_at)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)