adam-agent-server 1.5.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/dist/App-ZRCRM7WR.js +13 -0
  2. package/dist/adam-automator-skills-EZGBICHT.js +18 -0
  3. package/dist/adam-tools-V5LPU47X.js +1 -0
  4. package/dist/approval-handler-PB7PSLUS.js +1 -0
  5. package/dist/audit-manager-BSBBDUER.js +1 -0
  6. package/dist/bree-engine-7S33CWS7.js +1 -0
  7. package/dist/channels-SITUUC4J.js +1 -0
  8. package/dist/{channels-HYSB2EEK.js → channels-ULFUCUUZ.js} +1 -1
  9. package/dist/{chunk-Y3AMO6WC.js → chunk-2L2347UQ.js} +1 -1
  10. package/dist/{chunk-2DLVAKH7.js → chunk-2YTDCR6A.js} +1 -1
  11. package/dist/chunk-4PQHGLZH.js +99 -0
  12. package/dist/{chunk-JAS3TUZX.js → chunk-5EPG2US5.js} +26 -7
  13. package/dist/{chunk-BR2JY5X2.js → chunk-5QZXYKMS.js} +1 -1
  14. package/dist/chunk-5XOTPEAK.js +6 -0
  15. package/dist/{chunk-6775OYXA.js → chunk-6KF7OO2B.js} +1 -1
  16. package/dist/{chunk-5S6BMWD2.js → chunk-A5OCDYTW.js} +1 -1
  17. package/dist/{chunk-5XUR3M23.js → chunk-AQ3ASS4B.js} +1 -1
  18. package/dist/{chunk-HDP7A4XY.js → chunk-B6LOT5CG.js} +1 -1
  19. package/dist/chunk-BCH2HAIM.js +23 -0
  20. package/dist/{chunk-YVS565QY.js → chunk-BQ3ZAYHC.js} +1 -1
  21. package/dist/{chunk-C6BOQJJF.js → chunk-DVN3BFPP.js} +1 -1
  22. package/dist/{chunk-H7VDC6FY.js → chunk-EQZFOBAJ.js} +1 -1
  23. package/dist/{chunk-7L2WQM7N.js → chunk-FPZEZYUB.js} +1 -1
  24. package/dist/{chunk-23VZKIB6.js → chunk-GSFLLRS7.js} +1 -1
  25. package/dist/{chunk-GBTG5B5R.js → chunk-HQRUJQN7.js} +1 -1
  26. package/dist/{chunk-R4GIIQ7G.js → chunk-IKPYPZ64.js} +1 -1
  27. package/dist/{chunk-5V36ACKZ.js → chunk-IZNEOYRP.js} +1 -1
  28. package/dist/{chunk-6FXNB7NE.js → chunk-JJH2RCVC.js} +1 -1
  29. package/dist/chunk-K4C43YDD.js +7 -0
  30. package/dist/{chunk-Z4D3L2HR.js → chunk-M4YI4WVX.js} +1 -1
  31. package/dist/{chunk-INNDBLZE.js → chunk-MRTJFYPR.js} +1 -1
  32. package/dist/{chunk-YHVFZB6Q.js → chunk-N4ES7TCL.js} +1 -1
  33. package/dist/{chunk-HTPUEIFT.js → chunk-NASJH4NT.js} +5 -5
  34. package/dist/{chunk-H54ZXA26.js → chunk-NUITL62I.js} +1 -1
  35. package/dist/{chunk-VRJ7R766.js → chunk-NWMOV23A.js} +1 -1
  36. package/dist/{chunk-7K4AQBDD.js → chunk-PG6LMSX6.js} +1 -1
  37. package/dist/chunk-PHT24MOV.js +1 -0
  38. package/dist/chunk-QGYDGZSC.js +49 -0
  39. package/dist/{chunk-XL46AGRZ.js → chunk-RI3V72RP.js} +2 -2
  40. package/dist/{chunk-QVKI7H7W.js → chunk-RZ7LCZVK.js} +1 -1
  41. package/dist/{chunk-2CMR5AG7.js → chunk-SWP2JC54.js} +1 -1
  42. package/dist/chunk-TAF2DBBC.js +79 -0
  43. package/dist/chunk-ULTK7RD6.js +27 -0
  44. package/dist/{chunk-QWCRZDZS.js → chunk-WMB7P64J.js} +2 -2
  45. package/dist/cli.js +2 -2
  46. package/dist/{config-EMNKHR3W.js → config-HBQPBIWL.js} +1 -1
  47. package/dist/config-ZBNGRASI.js +1 -0
  48. package/dist/db-QEWTZGU3.js +1 -0
  49. package/dist/delivery-log-AC476GX7.js +1 -0
  50. package/dist/engine-6K4RG644.js +1 -0
  51. package/dist/{evolution-audit-LZSQPDHH.js → evolution-audit-XMBDUN3T.js} +1 -1
  52. package/dist/{external-api-7XV2PXPC.js → external-api-V74YTLBY.js} +1 -1
  53. package/dist/index.js +19 -13
  54. package/dist/{learner-IJN6B7KV.js → learner-VCS3Q7BR.js} +1 -1
  55. package/dist/{logger-QCJUU7GV.js → logger-WEXZORHP.js} +1 -1
  56. package/dist/{memories-ZII5QSTJ.js → memories-VMOGFVPU.js} +1 -1
  57. package/dist/{memory-extractor-DIYJFBCI.js → memory-extractor-4WJNHYWR.js} +2 -2
  58. package/dist/memory-service-ZS6MBUIC.js +1 -0
  59. package/dist/outbound-gateway-H7RFG6D2.js +1 -0
  60. package/dist/role-presets-XAEOYEAW.js +1 -0
  61. package/dist/role-workspace-NKGAH6J6.js +1 -0
  62. package/dist/roles-ZYCFQMAY.js +1 -0
  63. package/dist/session-manager-COLCNIB7.js +1 -0
  64. package/dist/task-templates-4KCZOUN5.js +1 -0
  65. package/dist/workflow-executor-Z7JFMR56.js +1 -0
  66. package/package.json +25 -25
  67. package/web/dist/assets/{AlertDialog-r3y6IhpW.js → AlertDialog-CfeiyMrc.js} +1 -1
  68. package/web/dist/assets/{Button-BjXgrQ95.js → Button-DuQctNms.js} +1 -1
  69. package/web/dist/assets/{Card-C153tGfJ.js → Card-rKfViPS2.js} +1 -1
  70. package/web/dist/assets/{ChannelDetail-C2uAZv1u.js → ChannelDetail-DnL0_h8q.js} +1 -1
  71. package/web/dist/assets/{Channels-C62Qrg-n.js → Channels-dod8Q4oq.js} +2 -2
  72. package/web/dist/assets/{Chat-kH2owmB_.js → Chat-Dv_Izjx3.js} +1 -1
  73. package/web/dist/assets/{Dashboard-BhD8SpFb.js → Dashboard-Dl0vA6Ky.js} +1 -1
  74. package/web/dist/assets/{EmptyState-CXwJFCDQ.js → EmptyState-CIdIlMbn.js} +1 -1
  75. package/web/dist/assets/{EnvVarEditor-GSapLD96.js → EnvVarEditor-C-gErAzC.js} +1 -1
  76. package/web/dist/assets/EventDefDetail-BhJZGNlX.js +1 -0
  77. package/web/dist/assets/Events-DnNZ9-BN.js +1 -0
  78. package/web/dist/assets/{Evolution-BO5hysLD.js → Evolution-BBWmrrnr.js} +1 -1
  79. package/web/dist/assets/{GoalDetail-cxa8OvEi.js → GoalDetail-uqWQCOj3.js} +1 -1
  80. package/web/dist/assets/{Goals-Dz3qqp_l.js → Goals-CylKmR9j.js} +1 -1
  81. package/web/dist/assets/{Logs-Ckp3-hYV.js → Logs-6rf0KT0z.js} +1 -1
  82. package/web/dist/assets/{Memories-DEuSRoP3.js → Memories-CrBTujU7.js} +1 -1
  83. package/web/dist/assets/{NotFound-Bvn39vSk.js → NotFound-DitXhq_y.js} +1 -1
  84. package/web/dist/assets/{PageHeader-BMvN0xiB.js → PageHeader-CHSgtxPw.js} +1 -1
  85. package/web/dist/assets/Plugins-VKUSUcSE.js +1 -0
  86. package/web/dist/assets/{RoleDetail-BWMjP9aZ.js → RoleDetail-DJc4CWFN.js} +2 -2
  87. package/web/dist/assets/{Roles-DD7NBDku.js → Roles-6pmjn04G.js} +1 -1
  88. package/web/dist/assets/{SectionHeader-CiCj3Is0.js → SectionHeader-C2WpiwJ5.js} +1 -1
  89. package/web/dist/assets/{Settings-BlU19KuR.js → Settings-DW1jmrNj.js} +1 -1
  90. package/web/dist/assets/{Strategies-CJ_q94-v.js → Strategies-Bmke6qZo.js} +1 -1
  91. package/web/dist/assets/{Switch-CoUUy5jr.js → Switch-CfTpXW9_.js} +1 -1
  92. package/web/dist/assets/{Table-CaFJieh_.js → Table-DuOLbyJQ.js} +1 -1
  93. package/web/dist/assets/{TaskDetail-DVrjU-E6.js → TaskDetail-CwJ_UKgt.js} +2 -2
  94. package/web/dist/assets/Work-DVdWNBEm.js +1 -0
  95. package/web/dist/assets/index-D4IubNPI.css +2 -0
  96. package/web/dist/assets/index-DYsO5Awn.js +2 -0
  97. package/web/dist/assets/{useIsMobileLayout-Bwrm84kJ.js → useIsMobileLayout-C6KIQjuh.js} +1 -1
  98. package/web/dist/assets/{vendor-icons-BlMaTTx3.js → vendor-icons-Dk0hMuJz.js} +1 -1
  99. package/web/dist/assets/{vendor-react-7e01TWy7.js → vendor-react-C6faO6LO.js} +1 -1
  100. package/web/dist/assets/{vendor-state-Bj70wnRm.js → vendor-state-DahK0J-G.js} +1 -1
  101. package/web/dist/index.html +7 -7
  102. package/dist/App-JGH6G5US.js +0 -13
  103. package/dist/adam-tools-W5AOIGEQ.js +0 -1
  104. package/dist/approval-handler-ORD4MUVM.js +0 -1
  105. package/dist/audit-manager-YCJT2WP5.js +0 -1
  106. package/dist/bree-engine-R5YLSDCL.js +0 -1
  107. package/dist/channels-JCMPPQED.js +0 -1
  108. package/dist/chunk-2YAP4YJV.js +0 -57
  109. package/dist/chunk-DZEVMYPB.js +0 -19
  110. package/dist/chunk-GY52JA5I.js +0 -10
  111. package/dist/chunk-ISZJV72D.js +0 -7
  112. package/dist/chunk-MTWLLE26.js +0 -49
  113. package/dist/chunk-RAW263MQ.js +0 -99
  114. package/dist/chunk-S3BAIZ4Q.js +0 -6
  115. package/dist/chunk-VRP4LTHY.js +0 -1
  116. package/dist/config-XMQS2NPT.js +0 -1
  117. package/dist/db-YUYXVV3A.js +0 -1
  118. package/dist/delivery-log-VKONLSVD.js +0 -1
  119. package/dist/engine-BM5BMPIC.js +0 -1
  120. package/dist/memory-service-QMYJPBAE.js +0 -1
  121. package/dist/outbound-gateway-6K6P2BEH.js +0 -1
  122. package/dist/role-presets-K2BDRZBS.js +0 -1
  123. package/dist/roles-L34L5MK3.js +0 -1
  124. package/dist/session-manager-GRJ3FV3L.js +0 -1
  125. package/dist/task-templates-23YOAF3E.js +0 -1
  126. package/dist/workflow-executor-JTUWX5DC.js +0 -1
  127. package/web/dist/assets/Plugins-CRym22JF.js +0 -1
  128. package/web/dist/assets/Work-BMl61RRi.js +0 -1
  129. package/web/dist/assets/index-DcXMQByM.css +0 -2
  130. package/web/dist/assets/index-pF--tN9F.js +0 -2
@@ -1 +1 @@
1
- import{a as le,b as x,c as J,d as ge,e as me}from"./chunk-23VZKIB6.js";import{f as ue}from"./chunk-HDP7A4XY.js";import{c as _,h as M}from"./chunk-INNDBLZE.js";import{z as g}from"zod/v4";import{v4 as Dt}from"uuid";import{randomUUID as be}from"crypto";import Ye from"crypto";var pe="2.1.7",F="bot";function Ze(t){let e=t.split(".").map(r=>parseInt(r,10)),s=e[0]??0,i=e[1]??0,n=e[2]??0;return(s&255)<<16|(i&255)<<8|n&255}var Y=Ze(pe),et=35e3,fe=15e3,tt=1e4;function L(){return{channel_version:pe}}function nt(t){return t.endsWith("/")?t:`${t}/`}function st(){let t=Ye.randomBytes(4).readUInt32BE(0);return Buffer.from(String(t),"utf-8").toString("base64")}function it(t){let e={"Content-Type":"application/json",AuthorizationType:"ilink_bot_token","Content-Length":String(Buffer.byteLength(t.body,"utf-8")),"X-WECHAT-UIN":st(),"iLink-App-Id":F,"iLink-App-ClientVersion":String(Y)};return t.token?.trim()&&(e.Authorization=`Bearer ${t.token.trim()}`),t.routeTag&&(e.SKRouteTag=t.routeTag),e}async function D(t){let e=nt(t.baseUrl),s=new URL(t.endpoint,e),i=it({token:t.token,routeTag:t.routeTag,body:t.body}),n=new AbortController,r=setTimeout(()=>n.abort(),t.timeoutMs);try{let o=await fetch(s.toString(),{method:"POST",headers:i,body:t.body,signal:n.signal});clearTimeout(r);let a=await o.text();if(!o.ok)throw new Error(`${t.label} ${o.status}: ${a}`);return a}catch(o){throw clearTimeout(r),o}}async function he(t){let e=t.timeoutMs??et;try{let s=await D({baseUrl:t.baseUrl,endpoint:"ilink/bot/getupdates",body:JSON.stringify({get_updates_buf:t.get_updates_buf??"",base_info:L()}),token:t.token,routeTag:t.routeTag,timeoutMs:e,label:"getUpdates"});return JSON.parse(s)}catch(s){if(s instanceof Error&&s.name==="AbortError")return{ret:0,msgs:[],get_updates_buf:t.get_updates_buf};throw s}}var rt={[-2]:2,[-3]:3},ot=1e3;async function E(t){let e=(await import("./logger-QCJUU7GV.js")).getLogger("channels"),s=new Map;for(;;){let i=await D({baseUrl:t.baseUrl,endpoint:"ilink/bot/sendmessage",body:JSON.stringify({...t.body,base_info:L()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??fe,label:"sendMessage"});e.info({status:200,responseBody:i.slice(0,300)},"apiFetch sendMessage response");try{let n=JSON.parse(i);if(n.ret&&n.ret!==0){let r=rt[n.ret],o=(s.get(n.ret)??0)+1;if(s.set(n.ret,o),r!==void 0&&o<r){e.warn({ret:n.ret,attempt:o,maxRetries:r},"sendMessage: retriable iLink error, retrying"),await new Promise(a=>setTimeout(a,ot*o));continue}throw e.error({ret:n.ret,errmsg:n.errmsg,attempt:o},"sendMessage: iLink API error, no more retries"),new Error(`sendMessage failed: iLink ret=${n.ret}${n.errmsg?` errmsg=${n.errmsg}`:""}`)}}catch(n){if(n instanceof SyntaxError)e.warn({rawText:i.slice(0,200)},"sendMessage: non-JSON response, treating as success");else throw n}return}}async function ye(t){await D({baseUrl:t.baseUrl,endpoint:"ilink/bot/sendtyping",body:JSON.stringify({...t.body,base_info:L()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??tt,label:"sendTyping"})}async function _e(t){let e=await D({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:L()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??fe,label:"getUploadUrl"});return JSON.parse(e)}var at=5*6e4,dt=35e3,we="3",w=new Map;function Z(t){return Date.now()-t.startedAt<at}function ct(){for(let[t,e]of w)Z(e)||w.delete(t)}async function xe(t,e,s){let i=t.endsWith("/")?t:`${t}/`,n=new URL(`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(e)}`,i),r={"iLink-App-Id":F};s&&(r.SKRouteTag=s);let o=await fetch(n.toString(),{headers:r});if(!o.ok){let a=await o.text().catch(()=>"(unreadable)");throw new Error(`Failed to fetch QR code: ${o.status} ${o.statusText} body=${a}`)}return await o.json()}async function ut(t,e,s){let i=t.endsWith("/")?t:`${t}/`,n=new URL(`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(e)}`,i),r={"iLink-App-Id":F,"iLink-App-ClientVersion":String(Y)};s&&(r.SKRouteTag=s);let o=new AbortController,a=setTimeout(()=>o.abort(),dt);try{let d=await fetch(n.toString(),{headers:r,signal:o.signal});clearTimeout(a);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(a),d instanceof Error&&d.name==="AbortError")return{status:"wait"};throw d}}async function Ie(t){let e=t.accountId||be();ct();let s=w.get(e);if(!t.force&&s&&Z(s)&&s.qrcodeUrl)return{qrcodeUrl:s.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 i=t.botType||we,n=await xe(t.apiBaseUrl,i,t.routeTag),r={sessionKey:e,id:be(),qrcode:n.qrcode,qrcodeUrl:n.qrcode_img_content,startedAt:Date.now()};return w.set(e,r),{qrcodeUrl:n.qrcode_img_content,message:"Scan the QR code with WeChat to connect.",sessionKey:e}}catch(i){return{message:`Failed to start login: ${String(i)}`,sessionKey:e}}}var lt=3;async function Te(t){let e=w.get(t.sessionKey);if(!e)return{connected:!1,message:"No active login session. Start QR login first."};if(!Z(e))return w.delete(t.sessionKey),{connected:!1,message:"QR code expired. Please start again."};let s=Math.max(t.timeoutMs??48e4,1e3),i=Date.now()+s,n=1;for(;Date.now()<i;){try{let r=await ut(t.apiBaseUrl,e.qrcode,t.routeTag);switch(e.status=r.status,r.status){case"wait":break;case"scaned":break;case"expired":{if(n++,n>lt)return w.delete(t.sessionKey),{connected:!1,message:"Login timeout: QR expired multiple times."};try{let o=t.botType||we,a=await xe(t.apiBaseUrl,o,t.routeTag);e.qrcode=a.qrcode,e.qrcodeUrl=a.qrcode_img_content,e.startedAt=Date.now()}catch(o){return w.delete(t.sessionKey),{connected:!1,message:`QR refresh failed: ${String(o)}`}}break}case"confirmed":return r.ilink_bot_id?(w.delete(t.sessionKey),{connected:!0,botToken:r.bot_token,accountId:r.ilink_bot_id,baseUrl:r.baseurl,userId:r.ilink_user_id,message:"Connected to WeChat successfully!"}):(w.delete(t.sessionKey),{connected:!1,message:"Login failed: server did not return bot ID."})}}catch(r){return w.delete(t.sessionKey),{connected:!1,message:`Login failed: ${String(r)}`}}await new Promise(r=>setTimeout(r,1e3))}return w.delete(t.sessionKey),{connected:!1,message:"Login timeout. Please try again."}}import T from"fs";import*as R from"fs/promises";import I from"path";import{homedir as H}from"os";var W={IMAGE:1,VIDEO:2,FILE:3,VOICE:4},A={NONE:0,USER:1,BOT:2},y={NONE:0,TEXT:1,IMAGE:2,VOICE:3,FILE:4,VIDEO:5},P={NEW:0,GENERATING:1,FINISH:2},Re={TYPING:1,CANCEL:2};M();var gt=_("channels"),ee=-14,B=3600*1e3,C=new Map;function Me(t){let e=Date.now()+B;C.set(t,e),gt.info({channelId:t},`Session paused until ${new Date(e).toISOString()} (${B/1e3}s)`)}function j(t){let e=C.get(t);return e===void 0?!1:Date.now()>=e?(C.delete(t),!1):!0}function Ue(t){let e=C.get(t);if(e===void 0)return 0;let s=e-Date.now();return s<=0?(C.delete(t),0):s}function ke(t){C.delete(t)}M();import*as z from"fs/promises";import $e from"path";import{homedir as wt}from"os";import{createCipheriv as mt,createDecipheriv as pt}from"crypto";function Se(t,e){let s=mt("aes-128-ecb",e,null);return Buffer.concat([s.update(t),s.final()])}function Ce(t,e){let s=pt("aes-128-ecb",e,null);return Buffer.concat([s.update(t),s.final()])}function Ee(t){return Math.ceil((t+1)/16)*16}function te(t,e){return`${e}/download?encrypted_query_param=${encodeURIComponent(t)}`}function Ae(t){return`${t.cdnBaseUrl}/upload?encrypted_query_param=${encodeURIComponent(t.uploadParam)}&filekey=${encodeURIComponent(t.filekey)}`}M();var sn=_("channels");function ft(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 Pe(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 v(t){let{encryptQueryParam:e,aesKeyBase64:s,cdnBaseUrl:i,fullUrl:n}=t,r=ft(s),o=n?.trim()||(e?te(e,i):null);if(!o)throw new Error("CDN download: need full_url or encrypt_query_param");let a=await Pe(o);return Ce(a,r)}async function ve(t){let{encryptQueryParam:e,cdnBaseUrl:s,fullUrl:i}=t,n=i?.trim()||(e?te(e,s):null);if(!n)throw new Error("CDN download: need full_url or encrypt_query_param");return Pe(n)}M();var Q=_("channels"),Oe=24e3;function ht(t,e){let s=t.byteLength,i=44+s,n=Buffer.allocUnsafe(i),r=0;return n.write("RIFF",r),r+=4,n.writeUInt32LE(i-8,r),r+=4,n.write("WAVE",r),r+=4,n.write("fmt ",r),r+=4,n.writeUInt32LE(16,r),r+=4,n.writeUInt16LE(1,r),r+=2,n.writeUInt16LE(1,r),r+=2,n.writeUInt32LE(e,r),r+=4,n.writeUInt32LE(e*2,r),r+=4,n.writeUInt16LE(2,r),r+=2,n.writeUInt16LE(16,r),r+=2,n.write("data",r),r+=4,n.writeUInt32LE(s,r),r+=4,Buffer.from(t.buffer,t.byteOffset,t.byteLength).copy(n,r),n}async function qe(t){try{let{decode:e}=await import("silk-wasm");Q.debug(`silkToWav: decoding ${t.length} bytes of SILK`);let s=await e(t,Oe);Q.debug(`silkToWav: decoded duration=${s.duration}ms pcmBytes=${s.data.byteLength}`);let i=ht(s.data,Oe);return Q.debug(`silkToWav: WAV size=${i.length}`),i}catch(e){return Q.warn(`silkToWav: transcode failed, will use raw silk err=${String(e)}`),null}}import yt from"path";var _t={".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",".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"},bt={"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"};function V(t){let e=yt.extname(t).toLowerCase();return _t[e]??"application/octet-stream"}function Ne(t){let e=t.split(";")[0].trim().toLowerCase();return bt[e]??".bin"}var S=_("channels"),Fe=100*1024*1024;function xt(t){return Ne(t)??".bin"}async function O(t,e,s,i,n=Fe,r){if(t.length>n)throw new Error(`Media too large: ${t.length} bytes exceeds ${n} bytes`);let o=$e.join(wt(),".adam","wechat","media",i,s);await z.mkdir(o,{recursive:!0});let a;if(r&&/^[a-zA-Z0-9._-]+$/.test(r))a=r;else{let c=e?xt(e):".bin",u=Date.now(),p=Math.random().toString(36).slice(2,7);a=`${u}-${p}${c}`}let d=$e.join(o,a);return await z.writeFile(d,t),S.debug(`saveMedia: saved ${t.length} bytes to ${d}`),d}async function Le(t,e){let{cdnBaseUrl:s,channelId:i}=e;if(t.type===y.IMAGE){let n=t.image_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url)return null;let r=n.aeskey?Buffer.from(n.aeskey,"hex").toString("base64"):n.media?.aes_key;try{let o=r?await v({encryptQueryParam:n.media?.encrypt_query_param,aesKeyBase64:r,cdnBaseUrl:s,fullUrl:n.media?.full_url}):await ve({encryptQueryParam:n.media?.encrypt_query_param,cdnBaseUrl:s,fullUrl:n.media?.full_url});return{path:await O(o,"image/png","inbound",i),mimeType:"image/png",type:"image"}}catch(o){return S.error({channelId:i},`Image download/decrypt failed: ${String(o)}`),null}}if(t.type===y.VOICE){let n=t.voice_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let r=await v({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:s,fullUrl:n.media.full_url}),o=await qe(r);if(o){let a=await O(o,"audio/wav","inbound",i);return S.debug(`Voice: saved WAV to ${a}`),{path:a,mimeType:"audio/wav",type:"audio"}}else{let a=await O(r,"audio/silk","inbound",i);return S.debug(`Voice: silk transcode unavailable, saved raw SILK to ${a}`),{path:a,mimeType:"audio/silk",type:"audio"}}}catch(r){return S.error({channelId:i},`Voice download/transcode failed: ${String(r)}`),null}}if(t.type===y.FILE){let n=t.file_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let r=await v({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:s,fullUrl:n.media.full_url}),o=V(n.file_name??"file.bin");return{path:await O(r,o,"inbound",i,Fe,n.file_name),mimeType:o,type:"file"}}catch(r){return S.error({channelId:i},`File download failed: ${String(r)}`),null}}if(t.type===y.VIDEO){let n=t.video_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let r=await v({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:s,fullUrl:n.media.full_url});return{path:await O(r,"video/mp4","inbound",i),mimeType:"video/mp4",type:"video"}}catch(r){return S.error({channelId:i},`Video download failed: ${String(r)}`),null}}return null}import Be from"path";import ne from"crypto";import It from"fs/promises";M();var U=_("channels"),G=3;async function Tt(t){let{buf:e,uploadFullUrl:s,uploadParam:i,filekey:n,cdnBaseUrl:r,label:o,aeskey:a}=t,d=Se(e,a),c=s?.trim(),u;if(c)u=c;else if(i)u=Ae({cdnBaseUrl:r,uploadParam:i,filekey:n});else throw new Error(`${o}: CDN upload URL missing (need upload_full_url or upload_param)`);U.debug(`${o}: CDN POST url=${u} ciphertextSize=${d.length}`);let p,l;for(let h=1;h<=G;h++)try{let m=await fetch(u,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:new Uint8Array(d)});if(m.status>=400&&m.status<500){let b=m.headers.get("x-error-message")??await m.text();throw U.error(`${o}: CDN client error attempt=${h} status=${m.status} errMsg=${b}`),new Error(`CDN upload client error ${m.status}: ${b}`)}if(m.status!==200){let b=m.headers.get("x-error-message")??`status ${m.status}`;throw U.error(`${o}: CDN server error attempt=${h} status=${m.status} errMsg=${b}`),new Error(`CDN upload server error: ${b}`)}if(p=m.headers.get("x-encrypted-param")??void 0,!p)throw U.error(`${o}: CDN response missing x-encrypted-param header attempt=${h}`),new Error("CDN upload response missing x-encrypted-param header");U.debug(`${o}: CDN upload success attempt=${h}`);break}catch(m){if(l=m,m instanceof Error&&m.message.includes("client error"))throw m;h<G?U.warn(`${o}: attempt ${h} failed, retrying... err=${String(m)}`):U.error(`${o}: all ${G} attempts failed err=${String(m)}`)}if(!p)throw l instanceof Error?l:new Error(`CDN upload failed after ${G} attempts`);return{downloadParam:p}}async function se(t){let{filePath:e,toUserId:s,opts:i,cdnBaseUrl:n,mediaType:r,label:o}=t,a=await It.readFile(e),d=a.length,c=ne.createHash("md5").update(a).digest("hex"),u=Ee(d),p=ne.randomBytes(16).toString("hex"),l=ne.randomBytes(16);U.debug(`${o}: file=${e} rawsize=${d} filesize=${u} md5=${c} filekey=${p}`);let h=await _e({...i,filekey:p,media_type:r,to_user_id:s,rawsize:d,rawfilemd5:c,filesize:u,no_need_thumb:!0,aeskey:l.toString("hex")}),m=h.upload_full_url?.trim(),b=h.upload_param;if(!m&&!b)throw new Error(`${o}: getUploadUrl returned no upload URL (need upload_full_url or upload_param)`);let{downloadParam:Je}=await Tt({buf:a,uploadFullUrl:m||void 0,uploadParam:b??void 0,filekey:p,cdnBaseUrl:n,aeskey:l,label:`${o}[orig filekey=${p}]`});return{filekey:p,downloadEncryptedQueryParam:Je,aeskey:l.toString("hex"),fileSize:d,fileSizeCiphertext:u}}async function De(t){return se({...t,mediaType:W.IMAGE,label:"uploadImageToWeixin"})}async function We(t){return se({...t,mediaType:W.VIDEO,label:"uploadVideoToWeixin"})}async function ie(t){return se({...t,mediaType:W.FILE,label:"uploadFileAttachmentToWeixin"})}M();var q=_("channels");function Rt(){return`adam-wechat-${Date.now()}-${Math.random().toString(36).slice(2,7)}`}function Mt(t){let e=t;return e=e.replace(/```[^\n]*\n?([\s\S]*?)```/g,(s,i)=>i.trim()),e=e.replace(/!\[[^\]]*\]\([^)]*\)/g,""),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/^\|[\s:|-]+\|$/gm,""),e=e.replace(/^\|(.+)\|$/gm,(s,i)=>i.split("|").map(n=>n.trim()).join(" ")),e}async function re(t){let{to:e,text:s,mediaItem:i,opts:n,label:r}=t,o=[],a=Mt(s);a&&o.push({type:y.TEXT,text_item:{text:a}}),o.push(i);let d="";for(let c of o){d=Rt();let u={msg:{from_user_id:"",to_user_id:e,client_id:d,message_type:A.BOT,message_state:P.FINISH,item_list:[c],context_token:n.contextToken}};await E({baseUrl:n.baseUrl,token:n.token,routeTag:n.routeTag,body:u})}return q.debug(`${r}: sent to=${e} messageId=${d}`),{messageId:d}}async function Ut(t){let{to:e,text:s,uploaded:i,opts:n}=t,r={type:y.IMAGE,image_item:{media:{encrypt_query_param:i.downloadEncryptedQueryParam,aes_key:Buffer.from(i.aeskey).toString("base64"),encrypt_type:1},mid_size:i.fileSizeCiphertext}};return re({to:e,text:s,mediaItem:r,opts:n,label:"sendImageMessage"})}async function kt(t){let{to:e,text:s,uploaded:i,opts:n}=t,r={type:y.VIDEO,video_item:{media:{encrypt_query_param:i.downloadEncryptedQueryParam,aes_key:Buffer.from(i.aeskey).toString("base64"),encrypt_type:1},video_size:i.fileSizeCiphertext}};return re({to:e,text:s,mediaItem:r,opts:n,label:"sendVideoMessage"})}async function je(t){let{to:e,text:s,fileName:i,uploaded:n,opts:r}=t,o={type:y.FILE,file_item:{media:{encrypt_query_param:n.downloadEncryptedQueryParam,aes_key:Buffer.from(n.aeskey).toString("base64"),encrypt_type:1},file_name:i,len:String(n.fileSize)}};return re({to:e,text:s,mediaItem:o,opts:r,label:"sendFileMessage"})}async function Qe(t){let{filePath:e,to:s,text:i,opts:n,cdnBaseUrl:r}=t,o=V(e),a={baseUrl:n.baseUrl,token:n.token,routeTag:n.routeTag};if(o.startsWith("video/")){q.debug(`sendWeixinMediaFile: uploading video filePath=${e} to=${s}`);let u=await We({filePath:e,toUserId:s,opts:a,cdnBaseUrl:r});return kt({to:s,text:i,uploaded:u,opts:n})}if(o.startsWith("image/")){q.debug(`sendWeixinMediaFile: uploading image filePath=${e} to=${s}`);let u=await De({filePath:e,toUserId:s,opts:a,cdnBaseUrl:r});return Ut({to:s,text:i,uploaded:u,opts:n})}if(o.startsWith("audio/")){let u=Be.basename(e);q.debug(`sendWeixinMediaFile: uploading audio as file filePath=${e} name=${u} to=${s}`);let p=await ie({filePath:e,fileName:u,toUserId:s,opts:a,cdnBaseUrl:r});return je({to:s,text:i,fileName:u,uploaded:p,opts:n})}let d=Be.basename(e);q.debug(`sendWeixinMediaFile: uploading file attachment filePath=${e} name=${d} to=${s}`);let c=await ie({filePath:e,fileName:d,toUserId:s,opts:a,cdnBaseUrl:r});return je({to:s,text:i,fileName:d,uploaded:c,opts:n})}M();var f=_("channels"),Ve="https://novac2c.cdn.weixin.qq.com/c2c",de=new Map;function Ke(t){return I.join(H(),".adam","wechat",`${t}.context-tokens.json`)}function St(t){let e=Ke(t);try{let s=T.readFileSync(e,"utf-8"),i=JSON.parse(s);for(let[n,r]of Object.entries(i))typeof r=="string"&&r&&de.set(`${t}:${n}`,r);f.debug({channelId:t,count:Object.keys(i).length},"Restored context tokens from disk")}catch{}}function Ct(t,e,s){let i=Ke(t);try{let n={};try{let o=T.readFileSync(i,"utf-8");n=JSON.parse(o)}catch{}n[e]=s;let r=I.dirname(i);T.mkdirSync(r,{recursive:!0}),T.writeFileSync(i,JSON.stringify(n),"utf-8")}catch(n){f.warn({channelId:t,userId:e},`Failed to persist context token: ${String(n)}`)}}function Et(t,e,s){de.set(`${t}:${e}`,s),Ct(t,e,s)}function oe(t,e){return de.get(`${t}:${e}`)}function He(t){return I.join(H(),".adam","wechat",`${t}.sync`)}function At(t){try{return T.readFileSync(He(t),"utf-8")}catch{return""}}function Pt(t,e){let s=He(t);T.mkdirSync(I.dirname(s),{recursive:!0}),T.writeFileSync(s,e,"utf-8")}var ae=1440*60*1e3,ze=10,vt=20,Ge=1440*60*1e3,Ot=1320*60*1e3,qt=1,Nt=7200*1e3;function Xe(t){return I.join(H(),".adam","wechat",`${t}.session.json`)}function $t(t){let e=new Map,s=Xe(t);try{let i=T.readFileSync(s,"utf-8"),n=JSON.parse(i);for(let[r,o]of Object.entries(n))o&&typeof o.lastUserMessageAt=="number"&&e.set(r,o);f.debug({channelId:t,count:e.size},"Restored sessions from disk")}catch{}return e}function N(t,e){let s=Xe(t);try{let i={};for(let[r,o]of e)i[r]=o;let n=I.dirname(s);T.mkdirSync(n,{recursive:!0}),T.writeFileSync(s,JSON.stringify(i),"utf-8")}catch(i){f.warn({channelId:t},`Failed to persist sessions: ${String(i)}`)}}var Ft=0;function $(){return`adam-wechat-${Date.now()}-${++Ft}`}var K=class{platform="wechat";id;config;status="disconnected";messageHandler=null;pollAbort=null;getUpdatesBuf="";sessions=new Map;pendingQueue=new Map;lastReminderAt=new Map;constructor(e,s){if(this.id=e,!s.baseUrl)throw new Error("WeChat adapter requires baseUrl");this.config=s}async connect(){if(!this.config.botToken)throw new Error("WeChat adapter requires botToken. Complete QR login first.");this.status="connecting",this.getUpdatesBuf=At(this.id),St(this.id),this.sessions=$t(this.id),this.pollAbort=new AbortController,this.status="connected",f.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",f.info({channelId:this.id},"WeChat adapter disconnected")}getStatus(){if(this.status==="connected"&&j(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}async sendMessage(e,s){if(j(this.id)){let c=Math.ceil(Ue(this.id)/6e4);throw new Error(`WeChat session paused, ${c} min remaining. Re-scan QR to reconnect.`)}let i=this.getOrCreateSession(e),r=this.getSessionRemainingMs(i)/36e5;if(!this.isSessionActive(i))return f.warn({channelId:this.id,chatId:e.slice(0,12),lastUserMessageAt:i.lastUserMessageAt,sessionExpired:!0},"iLink session expired (>24h), message queued"),this.enqueueMessage(e,s),`queued-${$()}`;if(i.quotaRemaining<=0)return f.warn({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:0,remainingHours:r.toFixed(1)},"iLink quota exhausted, message queued"),this.enqueueMessage(e,s),`queued-${$()}`;let o=$(),a=oe(this.id,e),d=this.config.cdnBaseUrl??Ve;try{if(s.mediaUrl){let c=!s.mediaUrl.includes("://")||s.mediaUrl.startsWith("file://"),u=I.join(H(),".adam","wechat","media","outbound-tmp");await R.mkdir(u,{recursive:!0});let p=this.getExtensionFromMediaType(s.mediaType),l;if(c){let m=s.mediaUrl.startsWith("file://")?new URL(s.mediaUrl).pathname:I.isAbsolute(s.mediaUrl)?s.mediaUrl:I.resolve(s.mediaUrl),b=await R.readFile(m);l=I.join(u,`${Date.now()}-${Math.random().toString(36).slice(2,7)}${p}`),await R.writeFile(l,b)}else{let m=await fetch(s.mediaUrl);if(!m.ok)throw new Error(`Failed to fetch media: ${m.status}`);let b=Buffer.from(await m.arrayBuffer());l=I.join(u,`${Date.now()}-${Math.random().toString(36).slice(2,7)}${p}`),await R.writeFile(l,b)}let h=await Qe({filePath:l,to:e,text:s.content??"",opts:{baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,contextToken:a},cdnBaseUrl:d});return await R.unlink(l).catch(()=>{}),i.quotaRemaining--,N(this.id,this.sessions),f.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:i.quotaRemaining,sessionRemainingHours:(this.getSessionRemainingMs(i)/36e5).toFixed(1)},"iLink send success: quota decremented"),this.checkAndSendReminder(e,i).catch(m=>{f.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(m)}`)}),h.messageId}return await E({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{msg:{from_user_id:"",to_user_id:e,client_id:o,message_type:A.BOT,message_state:P.FINISH,item_list:s.content?[{type:y.TEXT,text_item:{text:s.content}}]:void 0,context_token:a}}}),i.quotaRemaining--,N(this.id,this.sessions),f.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:i.quotaRemaining,sessionRemainingHours:(this.getSessionRemainingMs(i)/36e5).toFixed(1)},"iLink send success: quota decremented"),this.checkAndSendReminder(e,i).catch(c=>{f.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(c)}`)}),o}catch(c){if(c instanceof Error&&c.message.includes("ret=-2"))return i.quotaRemaining=0,N(this.id,this.sessions),f.warn({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:0},"iLink quota exhausted (ret=-2 confirmed), message queued"),this.enqueueMessage(e,s),`queued-${$()}`;throw c}}onMessage(e){this.messageHandler=e}async sendTypingIndicator(e){if(j(this.id))return;let s=oe(this.id,e);try{await ye({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{ilink_user_id:e,status:Re.TYPING}})}catch{}}updateConfig(e){Object.assign(this.config,e)}getOrCreateSession(e){let s=this.sessions.get(e);return s||(s={lastUserMessageAt:0,quotaRemaining:0},this.sessions.set(e,s)),s}isSessionActive(e){return e.lastUserMessageAt>0&&Date.now()-e.lastUserMessageAt<=ae}getSessionRemainingMs(e){return e.lastUserMessageAt===0?0:Math.max(0,ae-(Date.now()-e.lastUserMessageAt))}enqueueMessage(e,s){let i=this.pendingQueue.get(e);i||(i=[],this.pendingQueue.set(e,i));let n=Date.now();i=i.filter(r=>n-r.queuedAt<Ge),i.length>=vt&&(i.shift(),f.warn({channelId:this.id,chatId:e.slice(0,12)},"Queue full, dropping oldest message")),i.push({message:s,queuedAt:n}),this.pendingQueue.set(e,i),f.info({channelId:this.id,chatId:e.slice(0,12),queueDepth:i.length},"Message enqueued")}async flushQueue(e){let s=this.pendingQueue.get(e);if(!s||s.length===0)return;let i=this.getOrCreateSession(e),n=Math.min(s.length,Math.max(0,i.quotaRemaining-2));if(n<=0){f.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:i.quotaRemaining},"Queue flush skipped: insufficient quota (reserving 2 for conversation)");return}f.info({channelId:this.id,chatId:e.slice(0,12),queueDepth:s.length,sending:n,quotaRemaining:i.quotaRemaining},"Flushing queued messages");let r=0;for(;r<n&&s.length>0;){let o=s[0];if(Date.now()-o.queuedAt>Ge){s.shift();continue}try{if(await this.sendMessage(e,o.message),s.shift(),r++,i.quotaRemaining<=0)break}catch{f.warn({channelId:this.id,chatId:e.slice(0,12)},"Queue flush: send failed, stopping");break}}s.length===0&&this.pendingQueue.delete(e),f.info({channelId:this.id,chatId:e.slice(0,12),sent:r,remaining:s.length},"Queue flush complete")}async checkAndSendReminder(e,s){let i=Date.now(),n=this.lastReminderAt.get(e)??0;if(i-n<Nt)return;let r=this.getSessionRemainingMs(s),a=i-s.lastUserMessageAt>=Ot,d=s.quotaRemaining<=qt;if(!a&&!d)return;let c=(r/36e5).toFixed(1),u;a&&d?u=`[\u7CFB\u7EDF\u63D0\u9192] \u6D88\u606F\u7A97\u53E3\u5373\u5C06\u5173\u95ED\uFF08\u5269\u4F59${c}\u5C0F\u65F6/${s.quotaRemaining}\u6761\u914D\u989D\uFF09\u3002\u8BF7\u56DE\u590D\u4EFB\u610F\u6D88\u606F\u4EE5\u4FDD\u6301\u8FDE\u63A5\u3002`:a?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${s.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 E({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{msg:{from_user_id:"",to_user_id:e,client_id:$(),message_type:A.BOT,message_state:P.FINISH,item_list:[{type:y.TEXT,text_item:{text:u}}],context_token:p}}}),s.quotaRemaining--,this.lastReminderAt.set(e,i),N(this.id,this.sessions),f.info({channelId:this.id,chatId:e.slice(0,12),remainingHours:c,quotaRemaining:s.quotaRemaining,trigger:a?"time":"quota"},"iLink session reminder sent")}catch(l){f.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(l)}`)}}async startLongPoll(){let e=this.pollAbort?.signal,s=0,i=3,n=3e4,r=2e3;for(;!e?.aborted;)try{let o=await he({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,get_updates_buf:this.getUpdatesBuf});if(o.ret===ee||o.errcode===ee){Me(this.id),this.status="error",f.error({channelId:this.id},"Session expired (errcode=-14), pausing for 1 hour"),await this.sleep(B,e),ke(this.id),this.status="connected";continue}if(o.ret!==void 0&&o.ret!==0||o.errcode!==void 0&&o.errcode!==0){s++,f.error({channelId:this.id,ret:o.ret,errcode:o.errcode},"getUpdates API error"),s>=i?(s=0,await this.sleep(n,e)):await this.sleep(r,e);continue}s=0,o.get_updates_buf&&(this.getUpdatesBuf=o.get_updates_buf,Pt(this.id,o.get_updates_buf));for(let d of o.msgs??[])await this.processInbound(d)}catch(o){if(e?.aborted)return;s++,f.error({channelId:this.id,error:o},"getUpdates error"),s>=i?(s=0,await this.sleep(n,e)):await this.sleep(r,e)}}async processInbound(e){if(!this.messageHandler)return;let s=!!e.group_id,i=s?e.group_id:e.from_user_id??"",n=e.from_user_id??"";e.context_token&&i&&Et(this.id,i,e.context_token);let r=this.getOrCreateSession(i),o=r.quotaRemaining;r.lastUserMessageAt=Date.now(),r.quotaRemaining=ze,N(this.id,this.sessions),f.info({channelId:this.id,chatId:i.slice(0,12),quotaReset:!0,prevQuota:o,newQuota:ze,sessionWindowMs:ae},"iLink session reset: user message received, quota restored"),this.flushQueue(i);let a="",d,c=[];for(let l of e.item_list??[])l.type===y.TEXT&&l.text_item?.text&&(a+=l.text_item.text),l.type===y.IMAGE&&(d="image",c.push(l)),l.type===y.VOICE&&(d="audio",c.push(l),l.voice_item?.text&&!a&&(a=l.voice_item.text)),l.type===y.FILE&&(d="file",c.push(l)),l.type===y.VIDEO&&(d="video",c.push(l));if(!a&&!d)return;let u;if(c.length>0){let l=this.config.cdnBaseUrl??Ve;try{let h=await Le(c[0],{cdnBaseUrl:l,channelId:this.id});h&&(u=h.path,d=h.type)}catch(h){f.error({channelId:this.id},`Media download failed: ${String(h)}`)}}let p={channelId:this.id,platform:"wechat",chatId:i,senderId:n,content:a,mediaType:d,mediaPath:u,isGroup:s,timestamp:e.create_time_ms??Date.now(),raw:e};this.messageHandler(p)}getExtensionFromMediaType(e){switch(e){case"image":return".png";case"video":return".mp4";case"audio":return".mp3";default:return".bin"}}sleep(e,s){return new Promise((i,n)=>{let r=setTimeout(i,e);s?.addEventListener("abort",()=>{clearTimeout(r),n(new Error("aborted"))},{once:!0})})}};M();var Lt=_("channels"),X=class{platform="discord";id;config;status="disconnected";messageHandler=null;client=null;constructor(e,s){if(this.id=e,!s.botToken)throw new Error("Discord adapter requires botToken");this.config=s}async connect(){this.status="connecting";try{let{Client:e,GatewayIntentBits:s}=await import("discord.js");this.client=new e({intents:[s.Guilds,s.GuildMessages,s.MessageContent,s.DirectMessages]});let i=this.client;i.on("messageCreate",n=>{if(!this.messageHandler||n.author.bot||this.config.allowedGuildIds?.length&&n.guildId&&!this.config.allowedGuildIds.includes(n.guildId))return;let r={channelId:this.id,platform:"discord",chatId:n.channelId,senderId:n.author.id,senderName:n.author.displayName??n.author.username,content:n.content,isGroup:!!n.guildId,timestamp:n.createdTimestamp,raw:n};this.messageHandler(r)}),await i.login(this.config.botToken),this.status="connected",Lt.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}async sendMessage(e,s){if(!this.client)throw new Error("Discord client not connected");let n=await this.client.channels.fetch(e);if(!n||!("send"in n))throw new Error(`Channel ${e} not found or not text channel`);return(await n.send({content:s.content,reply:s.replyToMessageId?{messageReference:s.replyToMessageId}:void 0})).id}onMessage(e){this.messageHandler=e}async sendTypingIndicator(e){if(!this.client)return;let i=await this.client.channels.fetch(e);i&&"sendTyping"in i&&await i.sendTyping()}};var k=g.object({id:g.string().uuid()}),Wt=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()}),Bt=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()}),ce;function Zn(t){ce=t}function es(){return ce}async function ts(t){let e=ce;t.get("/channels",{schema:{tags:["Channels"],summary:"List channels",querystring:{type:"object",properties:{enabled:{type:"boolean"}}}}},async(s,i)=>({channels:ge(s.query.enabled)})),t.post("/channels",{schema:{tags:["Channels"],summary:"Create a channel",body:{type:"object",required:["name","platform","config"],properties:{name:{type:"string",minLength:1},platform:{type:"string",minLength:1},config:{type:"object"},enabled:{type:"boolean"},linkedRoleId:{type:"string"},allowedChatIds:{type:"array",items:{type:"string"}}}}}},async(s,i)=>{let n=Wt.safeParse(s.body);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let{name:r,platform:o,config:a,enabled:d,linkedRoleId:c,allowedChatIds:u}=n.data,p={id:Dt(),name:r,platform:o,enabled:d,status:"disconnected",config:a,linkedRoleId:c,allowedChatIds:u,createdAt:Date.now(),messageCount:0};return le(p),i.status(201).send({channel:p})}),t.get("/channels/:id",{schema:{tags:["Channels"],summary:"Get channel by ID",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(s,i)=>{let n=k.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);return r?{channel:r}:i.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"}}}}}},async(s,i)=>{let n=k.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);if(!r)return i.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let o=Bt.safeParse(s.body);return o.success?(J(r.id,o.data),{channel:x(r.id)}):i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(o.error)})}),t.delete("/channels/:id",{schema:{tags:["Channels"],summary:"Delete channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(s,i)=>{let n=k.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);return r?(me(r.id),i.status(204).send()):i.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),t.post("/channels/:id/connect",{schema:{tags:["Channels"],summary:"Connect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(s,i)=>{let n=k.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});if(!e)return i.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let r=x(n.data.id);if(!r)return i.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(!e.hasAdapter(r.id)&&r.platform==="discord"){let o=r.config;if(!o.botToken)return i.status(400).send({code:"MISSING_CONFIG",message:"Discord channel requires botToken in config"});let a=new X(r.id,{botToken:o.botToken});await e.addChannel(r,a)}if(!e.hasAdapter(r.id))return i.status(400).send({code:"NO_ADAPTER",message:"No adapter registered for this channel. Install the appropriate adapter first."});try{return await e.connectChannel(r.id),{channelId:r.id,status:"connected"}}catch(o){return i.status(500).send({code:"CONNECT_FAILED",message:String(o)})}}),t.post("/channels/:id/disconnect",{schema:{tags:["Channels"],summary:"Disconnect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(s,i)=>{let n=k.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});if(!e)return i.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let r=x(n.data.id);return r?(await e.disconnectChannel(r.id),{channelId:r.id,status:"disconnected"}):i.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),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(s,i)=>{let n=k.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);if(!r)return i.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let{limit:o=50,offset:a=0}=s.query;return{messages:ue(r.id,o,a)}}),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(s,i)=>{let n=k.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);if(!r)return i.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(r.platform!=="wechat")return i.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=r.config;return await Ie({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(s,i)=>{let n=k.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);if(!r)return i.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(r.platform!=="wechat")return i.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=r.config,{sessionKey:a,timeoutMs:d}=s.body??{},c=await Te({sessionKey:a??"",apiBaseUrl:o.baseUrl,timeoutMs:d??12e4,routeTag:o.routeTag});if(c.connected&&c.botToken){let u={...o,botToken:c.botToken,accountId:c.accountId,baseUrl:c.baseUrl??o.baseUrl,userId:c.userId};if(J(r.id,{config:u}),e){let p=new K(r.id,u),l=x(r.id);l&&await e.addChannel(l,p)}}return{connected:c.connected,accountId:c.accountId,message:c.message}})}export{K as a,X as b,Zn as c,es as d,ts as e};
1
+ import{f as ue}from"./chunk-B6LOT5CG.js";import{a as le,b as x,c as J,d as ge,e as me}from"./chunk-GSFLLRS7.js";import{c as _,h as M}from"./chunk-MRTJFYPR.js";import{z as g}from"zod/v4";import{v4 as Dt}from"uuid";import{randomUUID as be}from"crypto";import Ye from"crypto";var pe="2.1.7",F="bot";function Ze(t){let e=t.split(".").map(r=>parseInt(r,10)),s=e[0]??0,i=e[1]??0,n=e[2]??0;return(s&255)<<16|(i&255)<<8|n&255}var Y=Ze(pe),et=35e3,fe=15e3,tt=1e4;function L(){return{channel_version:pe}}function nt(t){return t.endsWith("/")?t:`${t}/`}function st(){let t=Ye.randomBytes(4).readUInt32BE(0);return Buffer.from(String(t),"utf-8").toString("base64")}function it(t){let e={"Content-Type":"application/json",AuthorizationType:"ilink_bot_token","Content-Length":String(Buffer.byteLength(t.body,"utf-8")),"X-WECHAT-UIN":st(),"iLink-App-Id":F,"iLink-App-ClientVersion":String(Y)};return t.token?.trim()&&(e.Authorization=`Bearer ${t.token.trim()}`),t.routeTag&&(e.SKRouteTag=t.routeTag),e}async function D(t){let e=nt(t.baseUrl),s=new URL(t.endpoint,e),i=it({token:t.token,routeTag:t.routeTag,body:t.body}),n=new AbortController,r=setTimeout(()=>n.abort(),t.timeoutMs);try{let o=await fetch(s.toString(),{method:"POST",headers:i,body:t.body,signal:n.signal});clearTimeout(r);let a=await o.text();if(!o.ok)throw new Error(`${t.label} ${o.status}: ${a}`);return a}catch(o){throw clearTimeout(r),o}}async function he(t){let e=t.timeoutMs??et;try{let s=await D({baseUrl:t.baseUrl,endpoint:"ilink/bot/getupdates",body:JSON.stringify({get_updates_buf:t.get_updates_buf??"",base_info:L()}),token:t.token,routeTag:t.routeTag,timeoutMs:e,label:"getUpdates"});return JSON.parse(s)}catch(s){if(s instanceof Error&&s.name==="AbortError")return{ret:0,msgs:[],get_updates_buf:t.get_updates_buf};throw s}}var rt={[-2]:2,[-3]:3},ot=1e3;async function E(t){let e=(await import("./logger-WEXZORHP.js")).getLogger("channels"),s=new Map;for(;;){let i=await D({baseUrl:t.baseUrl,endpoint:"ilink/bot/sendmessage",body:JSON.stringify({...t.body,base_info:L()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??fe,label:"sendMessage"});e.info({status:200,responseBody:i.slice(0,300)},"apiFetch sendMessage response");try{let n=JSON.parse(i);if(n.ret&&n.ret!==0){let r=rt[n.ret],o=(s.get(n.ret)??0)+1;if(s.set(n.ret,o),r!==void 0&&o<r){e.warn({ret:n.ret,attempt:o,maxRetries:r},"sendMessage: retriable iLink error, retrying"),await new Promise(a=>setTimeout(a,ot*o));continue}throw e.error({ret:n.ret,errmsg:n.errmsg,attempt:o},"sendMessage: iLink API error, no more retries"),new Error(`sendMessage failed: iLink ret=${n.ret}${n.errmsg?` errmsg=${n.errmsg}`:""}`)}}catch(n){if(n instanceof SyntaxError)e.warn({rawText:i.slice(0,200)},"sendMessage: non-JSON response, treating as success");else throw n}return}}async function ye(t){await D({baseUrl:t.baseUrl,endpoint:"ilink/bot/sendtyping",body:JSON.stringify({...t.body,base_info:L()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??tt,label:"sendTyping"})}async function _e(t){let e=await D({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:L()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??fe,label:"getUploadUrl"});return JSON.parse(e)}var at=5*6e4,dt=35e3,we="3",w=new Map;function Z(t){return Date.now()-t.startedAt<at}function ct(){for(let[t,e]of w)Z(e)||w.delete(t)}async function xe(t,e,s){let i=t.endsWith("/")?t:`${t}/`,n=new URL(`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(e)}`,i),r={"iLink-App-Id":F};s&&(r.SKRouteTag=s);let o=await fetch(n.toString(),{headers:r});if(!o.ok){let a=await o.text().catch(()=>"(unreadable)");throw new Error(`Failed to fetch QR code: ${o.status} ${o.statusText} body=${a}`)}return await o.json()}async function ut(t,e,s){let i=t.endsWith("/")?t:`${t}/`,n=new URL(`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(e)}`,i),r={"iLink-App-Id":F,"iLink-App-ClientVersion":String(Y)};s&&(r.SKRouteTag=s);let o=new AbortController,a=setTimeout(()=>o.abort(),dt);try{let d=await fetch(n.toString(),{headers:r,signal:o.signal});clearTimeout(a);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(a),d instanceof Error&&d.name==="AbortError")return{status:"wait"};throw d}}async function Ie(t){let e=t.accountId||be();ct();let s=w.get(e);if(!t.force&&s&&Z(s)&&s.qrcodeUrl)return{qrcodeUrl:s.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 i=t.botType||we,n=await xe(t.apiBaseUrl,i,t.routeTag),r={sessionKey:e,id:be(),qrcode:n.qrcode,qrcodeUrl:n.qrcode_img_content,startedAt:Date.now()};return w.set(e,r),{qrcodeUrl:n.qrcode_img_content,message:"Scan the QR code with WeChat to connect.",sessionKey:e}}catch(i){return{message:`Failed to start login: ${String(i)}`,sessionKey:e}}}var lt=3;async function Te(t){let e=w.get(t.sessionKey);if(!e)return{connected:!1,message:"No active login session. Start QR login first."};if(!Z(e))return w.delete(t.sessionKey),{connected:!1,message:"QR code expired. Please start again."};let s=Math.max(t.timeoutMs??48e4,1e3),i=Date.now()+s,n=1;for(;Date.now()<i;){try{let r=await ut(t.apiBaseUrl,e.qrcode,t.routeTag);switch(e.status=r.status,r.status){case"wait":break;case"scaned":break;case"expired":{if(n++,n>lt)return w.delete(t.sessionKey),{connected:!1,message:"Login timeout: QR expired multiple times."};try{let o=t.botType||we,a=await xe(t.apiBaseUrl,o,t.routeTag);e.qrcode=a.qrcode,e.qrcodeUrl=a.qrcode_img_content,e.startedAt=Date.now()}catch(o){return w.delete(t.sessionKey),{connected:!1,message:`QR refresh failed: ${String(o)}`}}break}case"confirmed":return r.ilink_bot_id?(w.delete(t.sessionKey),{connected:!0,botToken:r.bot_token,accountId:r.ilink_bot_id,baseUrl:r.baseurl,userId:r.ilink_user_id,message:"Connected to WeChat successfully!"}):(w.delete(t.sessionKey),{connected:!1,message:"Login failed: server did not return bot ID."})}}catch(r){return w.delete(t.sessionKey),{connected:!1,message:`Login failed: ${String(r)}`}}await new Promise(r=>setTimeout(r,1e3))}return w.delete(t.sessionKey),{connected:!1,message:"Login timeout. Please try again."}}import T from"fs";import*as R from"fs/promises";import I from"path";import{homedir as H}from"os";var W={IMAGE:1,VIDEO:2,FILE:3,VOICE:4},A={NONE:0,USER:1,BOT:2},y={NONE:0,TEXT:1,IMAGE:2,VOICE:3,FILE:4,VIDEO:5},P={NEW:0,GENERATING:1,FINISH:2},Re={TYPING:1,CANCEL:2};M();var gt=_("channels"),ee=-14,B=3600*1e3,C=new Map;function Me(t){let e=Date.now()+B;C.set(t,e),gt.info({channelId:t},`Session paused until ${new Date(e).toISOString()} (${B/1e3}s)`)}function j(t){let e=C.get(t);return e===void 0?!1:Date.now()>=e?(C.delete(t),!1):!0}function Ue(t){let e=C.get(t);if(e===void 0)return 0;let s=e-Date.now();return s<=0?(C.delete(t),0):s}function ke(t){C.delete(t)}M();import*as z from"fs/promises";import $e from"path";import{homedir as wt}from"os";import{createCipheriv as mt,createDecipheriv as pt}from"crypto";function Se(t,e){let s=mt("aes-128-ecb",e,null);return Buffer.concat([s.update(t),s.final()])}function Ce(t,e){let s=pt("aes-128-ecb",e,null);return Buffer.concat([s.update(t),s.final()])}function Ee(t){return Math.ceil((t+1)/16)*16}function te(t,e){return`${e}/download?encrypted_query_param=${encodeURIComponent(t)}`}function Ae(t){return`${t.cdnBaseUrl}/upload?encrypted_query_param=${encodeURIComponent(t.uploadParam)}&filekey=${encodeURIComponent(t.filekey)}`}M();var sn=_("channels");function ft(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 Pe(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 v(t){let{encryptQueryParam:e,aesKeyBase64:s,cdnBaseUrl:i,fullUrl:n}=t,r=ft(s),o=n?.trim()||(e?te(e,i):null);if(!o)throw new Error("CDN download: need full_url or encrypt_query_param");let a=await Pe(o);return Ce(a,r)}async function ve(t){let{encryptQueryParam:e,cdnBaseUrl:s,fullUrl:i}=t,n=i?.trim()||(e?te(e,s):null);if(!n)throw new Error("CDN download: need full_url or encrypt_query_param");return Pe(n)}M();var Q=_("channels"),Oe=24e3;function ht(t,e){let s=t.byteLength,i=44+s,n=Buffer.allocUnsafe(i),r=0;return n.write("RIFF",r),r+=4,n.writeUInt32LE(i-8,r),r+=4,n.write("WAVE",r),r+=4,n.write("fmt ",r),r+=4,n.writeUInt32LE(16,r),r+=4,n.writeUInt16LE(1,r),r+=2,n.writeUInt16LE(1,r),r+=2,n.writeUInt32LE(e,r),r+=4,n.writeUInt32LE(e*2,r),r+=4,n.writeUInt16LE(2,r),r+=2,n.writeUInt16LE(16,r),r+=2,n.write("data",r),r+=4,n.writeUInt32LE(s,r),r+=4,Buffer.from(t.buffer,t.byteOffset,t.byteLength).copy(n,r),n}async function qe(t){try{let{decode:e}=await import("silk-wasm");Q.debug(`silkToWav: decoding ${t.length} bytes of SILK`);let s=await e(t,Oe);Q.debug(`silkToWav: decoded duration=${s.duration}ms pcmBytes=${s.data.byteLength}`);let i=ht(s.data,Oe);return Q.debug(`silkToWav: WAV size=${i.length}`),i}catch(e){return Q.warn(`silkToWav: transcode failed, will use raw silk err=${String(e)}`),null}}import yt from"path";var _t={".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",".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"},bt={"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"};function V(t){let e=yt.extname(t).toLowerCase();return _t[e]??"application/octet-stream"}function Ne(t){let e=t.split(";")[0].trim().toLowerCase();return bt[e]??".bin"}var S=_("channels"),Fe=100*1024*1024;function xt(t){return Ne(t)??".bin"}async function O(t,e,s,i,n=Fe,r){if(t.length>n)throw new Error(`Media too large: ${t.length} bytes exceeds ${n} bytes`);let o=$e.join(wt(),".adam","wechat","media",i,s);await z.mkdir(o,{recursive:!0});let a;if(r&&/^[a-zA-Z0-9._-]+$/.test(r))a=r;else{let c=e?xt(e):".bin",u=Date.now(),p=Math.random().toString(36).slice(2,7);a=`${u}-${p}${c}`}let d=$e.join(o,a);return await z.writeFile(d,t),S.debug(`saveMedia: saved ${t.length} bytes to ${d}`),d}async function Le(t,e){let{cdnBaseUrl:s,channelId:i}=e;if(t.type===y.IMAGE){let n=t.image_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url)return null;let r=n.aeskey?Buffer.from(n.aeskey,"hex").toString("base64"):n.media?.aes_key;try{let o=r?await v({encryptQueryParam:n.media?.encrypt_query_param,aesKeyBase64:r,cdnBaseUrl:s,fullUrl:n.media?.full_url}):await ve({encryptQueryParam:n.media?.encrypt_query_param,cdnBaseUrl:s,fullUrl:n.media?.full_url});return{path:await O(o,"image/png","inbound",i),mimeType:"image/png",type:"image"}}catch(o){return S.error({channelId:i},`Image download/decrypt failed: ${String(o)}`),null}}if(t.type===y.VOICE){let n=t.voice_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let r=await v({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:s,fullUrl:n.media.full_url}),o=await qe(r);if(o){let a=await O(o,"audio/wav","inbound",i);return S.debug(`Voice: saved WAV to ${a}`),{path:a,mimeType:"audio/wav",type:"audio"}}else{let a=await O(r,"audio/silk","inbound",i);return S.debug(`Voice: silk transcode unavailable, saved raw SILK to ${a}`),{path:a,mimeType:"audio/silk",type:"audio"}}}catch(r){return S.error({channelId:i},`Voice download/transcode failed: ${String(r)}`),null}}if(t.type===y.FILE){let n=t.file_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let r=await v({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:s,fullUrl:n.media.full_url}),o=V(n.file_name??"file.bin");return{path:await O(r,o,"inbound",i,Fe,n.file_name),mimeType:o,type:"file"}}catch(r){return S.error({channelId:i},`File download failed: ${String(r)}`),null}}if(t.type===y.VIDEO){let n=t.video_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let r=await v({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:s,fullUrl:n.media.full_url});return{path:await O(r,"video/mp4","inbound",i),mimeType:"video/mp4",type:"video"}}catch(r){return S.error({channelId:i},`Video download failed: ${String(r)}`),null}}return null}import Be from"path";import ne from"crypto";import It from"fs/promises";M();var U=_("channels"),G=3;async function Tt(t){let{buf:e,uploadFullUrl:s,uploadParam:i,filekey:n,cdnBaseUrl:r,label:o,aeskey:a}=t,d=Se(e,a),c=s?.trim(),u;if(c)u=c;else if(i)u=Ae({cdnBaseUrl:r,uploadParam:i,filekey:n});else throw new Error(`${o}: CDN upload URL missing (need upload_full_url or upload_param)`);U.debug(`${o}: CDN POST url=${u} ciphertextSize=${d.length}`);let p,l;for(let h=1;h<=G;h++)try{let m=await fetch(u,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:new Uint8Array(d)});if(m.status>=400&&m.status<500){let b=m.headers.get("x-error-message")??await m.text();throw U.error(`${o}: CDN client error attempt=${h} status=${m.status} errMsg=${b}`),new Error(`CDN upload client error ${m.status}: ${b}`)}if(m.status!==200){let b=m.headers.get("x-error-message")??`status ${m.status}`;throw U.error(`${o}: CDN server error attempt=${h} status=${m.status} errMsg=${b}`),new Error(`CDN upload server error: ${b}`)}if(p=m.headers.get("x-encrypted-param")??void 0,!p)throw U.error(`${o}: CDN response missing x-encrypted-param header attempt=${h}`),new Error("CDN upload response missing x-encrypted-param header");U.debug(`${o}: CDN upload success attempt=${h}`);break}catch(m){if(l=m,m instanceof Error&&m.message.includes("client error"))throw m;h<G?U.warn(`${o}: attempt ${h} failed, retrying... err=${String(m)}`):U.error(`${o}: all ${G} attempts failed err=${String(m)}`)}if(!p)throw l instanceof Error?l:new Error(`CDN upload failed after ${G} attempts`);return{downloadParam:p}}async function se(t){let{filePath:e,toUserId:s,opts:i,cdnBaseUrl:n,mediaType:r,label:o}=t,a=await It.readFile(e),d=a.length,c=ne.createHash("md5").update(a).digest("hex"),u=Ee(d),p=ne.randomBytes(16).toString("hex"),l=ne.randomBytes(16);U.debug(`${o}: file=${e} rawsize=${d} filesize=${u} md5=${c} filekey=${p}`);let h=await _e({...i,filekey:p,media_type:r,to_user_id:s,rawsize:d,rawfilemd5:c,filesize:u,no_need_thumb:!0,aeskey:l.toString("hex")}),m=h.upload_full_url?.trim(),b=h.upload_param;if(!m&&!b)throw new Error(`${o}: getUploadUrl returned no upload URL (need upload_full_url or upload_param)`);let{downloadParam:Je}=await Tt({buf:a,uploadFullUrl:m||void 0,uploadParam:b??void 0,filekey:p,cdnBaseUrl:n,aeskey:l,label:`${o}[orig filekey=${p}]`});return{filekey:p,downloadEncryptedQueryParam:Je,aeskey:l.toString("hex"),fileSize:d,fileSizeCiphertext:u}}async function De(t){return se({...t,mediaType:W.IMAGE,label:"uploadImageToWeixin"})}async function We(t){return se({...t,mediaType:W.VIDEO,label:"uploadVideoToWeixin"})}async function ie(t){return se({...t,mediaType:W.FILE,label:"uploadFileAttachmentToWeixin"})}M();var q=_("channels");function Rt(){return`adam-wechat-${Date.now()}-${Math.random().toString(36).slice(2,7)}`}function Mt(t){let e=t;return e=e.replace(/```[^\n]*\n?([\s\S]*?)```/g,(s,i)=>i.trim()),e=e.replace(/!\[[^\]]*\]\([^)]*\)/g,""),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/^\|[\s:|-]+\|$/gm,""),e=e.replace(/^\|(.+)\|$/gm,(s,i)=>i.split("|").map(n=>n.trim()).join(" ")),e}async function re(t){let{to:e,text:s,mediaItem:i,opts:n,label:r}=t,o=[],a=Mt(s);a&&o.push({type:y.TEXT,text_item:{text:a}}),o.push(i);let d="";for(let c of o){d=Rt();let u={msg:{from_user_id:"",to_user_id:e,client_id:d,message_type:A.BOT,message_state:P.FINISH,item_list:[c],context_token:n.contextToken}};await E({baseUrl:n.baseUrl,token:n.token,routeTag:n.routeTag,body:u})}return q.debug(`${r}: sent to=${e} messageId=${d}`),{messageId:d}}async function Ut(t){let{to:e,text:s,uploaded:i,opts:n}=t,r={type:y.IMAGE,image_item:{media:{encrypt_query_param:i.downloadEncryptedQueryParam,aes_key:Buffer.from(i.aeskey).toString("base64"),encrypt_type:1},mid_size:i.fileSizeCiphertext}};return re({to:e,text:s,mediaItem:r,opts:n,label:"sendImageMessage"})}async function kt(t){let{to:e,text:s,uploaded:i,opts:n}=t,r={type:y.VIDEO,video_item:{media:{encrypt_query_param:i.downloadEncryptedQueryParam,aes_key:Buffer.from(i.aeskey).toString("base64"),encrypt_type:1},video_size:i.fileSizeCiphertext}};return re({to:e,text:s,mediaItem:r,opts:n,label:"sendVideoMessage"})}async function je(t){let{to:e,text:s,fileName:i,uploaded:n,opts:r}=t,o={type:y.FILE,file_item:{media:{encrypt_query_param:n.downloadEncryptedQueryParam,aes_key:Buffer.from(n.aeskey).toString("base64"),encrypt_type:1},file_name:i,len:String(n.fileSize)}};return re({to:e,text:s,mediaItem:o,opts:r,label:"sendFileMessage"})}async function Qe(t){let{filePath:e,to:s,text:i,opts:n,cdnBaseUrl:r}=t,o=V(e),a={baseUrl:n.baseUrl,token:n.token,routeTag:n.routeTag};if(o.startsWith("video/")){q.debug(`sendWeixinMediaFile: uploading video filePath=${e} to=${s}`);let u=await We({filePath:e,toUserId:s,opts:a,cdnBaseUrl:r});return kt({to:s,text:i,uploaded:u,opts:n})}if(o.startsWith("image/")){q.debug(`sendWeixinMediaFile: uploading image filePath=${e} to=${s}`);let u=await De({filePath:e,toUserId:s,opts:a,cdnBaseUrl:r});return Ut({to:s,text:i,uploaded:u,opts:n})}if(o.startsWith("audio/")){let u=Be.basename(e);q.debug(`sendWeixinMediaFile: uploading audio as file filePath=${e} name=${u} to=${s}`);let p=await ie({filePath:e,fileName:u,toUserId:s,opts:a,cdnBaseUrl:r});return je({to:s,text:i,fileName:u,uploaded:p,opts:n})}let d=Be.basename(e);q.debug(`sendWeixinMediaFile: uploading file attachment filePath=${e} name=${d} to=${s}`);let c=await ie({filePath:e,fileName:d,toUserId:s,opts:a,cdnBaseUrl:r});return je({to:s,text:i,fileName:d,uploaded:c,opts:n})}M();var f=_("channels"),Ve="https://novac2c.cdn.weixin.qq.com/c2c",de=new Map;function Ke(t){return I.join(H(),".adam","wechat",`${t}.context-tokens.json`)}function St(t){let e=Ke(t);try{let s=T.readFileSync(e,"utf-8"),i=JSON.parse(s);for(let[n,r]of Object.entries(i))typeof r=="string"&&r&&de.set(`${t}:${n}`,r);f.debug({channelId:t,count:Object.keys(i).length},"Restored context tokens from disk")}catch{}}function Ct(t,e,s){let i=Ke(t);try{let n={};try{let o=T.readFileSync(i,"utf-8");n=JSON.parse(o)}catch{}n[e]=s;let r=I.dirname(i);T.mkdirSync(r,{recursive:!0}),T.writeFileSync(i,JSON.stringify(n),"utf-8")}catch(n){f.warn({channelId:t,userId:e},`Failed to persist context token: ${String(n)}`)}}function Et(t,e,s){de.set(`${t}:${e}`,s),Ct(t,e,s)}function oe(t,e){return de.get(`${t}:${e}`)}function He(t){return I.join(H(),".adam","wechat",`${t}.sync`)}function At(t){try{return T.readFileSync(He(t),"utf-8")}catch{return""}}function Pt(t,e){let s=He(t);T.mkdirSync(I.dirname(s),{recursive:!0}),T.writeFileSync(s,e,"utf-8")}var ae=1440*60*1e3,ze=10,vt=20,Ge=1440*60*1e3,Ot=1320*60*1e3,qt=1,Nt=7200*1e3;function Xe(t){return I.join(H(),".adam","wechat",`${t}.session.json`)}function $t(t){let e=new Map,s=Xe(t);try{let i=T.readFileSync(s,"utf-8"),n=JSON.parse(i);for(let[r,o]of Object.entries(n))o&&typeof o.lastUserMessageAt=="number"&&e.set(r,o);f.debug({channelId:t,count:e.size},"Restored sessions from disk")}catch{}return e}function N(t,e){let s=Xe(t);try{let i={};for(let[r,o]of e)i[r]=o;let n=I.dirname(s);T.mkdirSync(n,{recursive:!0}),T.writeFileSync(s,JSON.stringify(i),"utf-8")}catch(i){f.warn({channelId:t},`Failed to persist sessions: ${String(i)}`)}}var Ft=0;function $(){return`adam-wechat-${Date.now()}-${++Ft}`}var K=class{platform="wechat";id;config;status="disconnected";messageHandler=null;pollAbort=null;getUpdatesBuf="";sessions=new Map;pendingQueue=new Map;lastReminderAt=new Map;constructor(e,s){if(this.id=e,!s.baseUrl)throw new Error("WeChat adapter requires baseUrl");this.config=s}async connect(){if(!this.config.botToken)throw new Error("WeChat adapter requires botToken. Complete QR login first.");this.status="connecting",this.getUpdatesBuf=At(this.id),St(this.id),this.sessions=$t(this.id),this.pollAbort=new AbortController,this.status="connected",f.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",f.info({channelId:this.id},"WeChat adapter disconnected")}getStatus(){if(this.status==="connected"&&j(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}async sendMessage(e,s){if(j(this.id)){let c=Math.ceil(Ue(this.id)/6e4);throw new Error(`WeChat session paused, ${c} min remaining. Re-scan QR to reconnect.`)}let i=this.getOrCreateSession(e),r=this.getSessionRemainingMs(i)/36e5;if(!this.isSessionActive(i))return f.warn({channelId:this.id,chatId:e.slice(0,12),lastUserMessageAt:i.lastUserMessageAt,sessionExpired:!0},"iLink session expired (>24h), message queued"),this.enqueueMessage(e,s),`queued-${$()}`;if(i.quotaRemaining<=0)return f.warn({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:0,remainingHours:r.toFixed(1)},"iLink quota exhausted, message queued"),this.enqueueMessage(e,s),`queued-${$()}`;let o=$(),a=oe(this.id,e),d=this.config.cdnBaseUrl??Ve;try{if(s.mediaUrl){let c=!s.mediaUrl.includes("://")||s.mediaUrl.startsWith("file://"),u=I.join(H(),".adam","wechat","media","outbound-tmp");await R.mkdir(u,{recursive:!0});let p=this.getExtensionFromMediaType(s.mediaType),l;if(c){let m=s.mediaUrl.startsWith("file://")?new URL(s.mediaUrl).pathname:I.isAbsolute(s.mediaUrl)?s.mediaUrl:I.resolve(s.mediaUrl),b=await R.readFile(m);l=I.join(u,`${Date.now()}-${Math.random().toString(36).slice(2,7)}${p}`),await R.writeFile(l,b)}else{let m=await fetch(s.mediaUrl);if(!m.ok)throw new Error(`Failed to fetch media: ${m.status}`);let b=Buffer.from(await m.arrayBuffer());l=I.join(u,`${Date.now()}-${Math.random().toString(36).slice(2,7)}${p}`),await R.writeFile(l,b)}let h=await Qe({filePath:l,to:e,text:s.content??"",opts:{baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,contextToken:a},cdnBaseUrl:d});return await R.unlink(l).catch(()=>{}),i.quotaRemaining--,N(this.id,this.sessions),f.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:i.quotaRemaining,sessionRemainingHours:(this.getSessionRemainingMs(i)/36e5).toFixed(1)},"iLink send success: quota decremented"),this.checkAndSendReminder(e,i).catch(m=>{f.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(m)}`)}),h.messageId}return await E({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{msg:{from_user_id:"",to_user_id:e,client_id:o,message_type:A.BOT,message_state:P.FINISH,item_list:s.content?[{type:y.TEXT,text_item:{text:s.content}}]:void 0,context_token:a}}}),i.quotaRemaining--,N(this.id,this.sessions),f.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:i.quotaRemaining,sessionRemainingHours:(this.getSessionRemainingMs(i)/36e5).toFixed(1)},"iLink send success: quota decremented"),this.checkAndSendReminder(e,i).catch(c=>{f.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(c)}`)}),o}catch(c){if(c instanceof Error&&c.message.includes("ret=-2"))return i.quotaRemaining=0,N(this.id,this.sessions),f.warn({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:0},"iLink quota exhausted (ret=-2 confirmed), message queued"),this.enqueueMessage(e,s),`queued-${$()}`;throw c}}onMessage(e){this.messageHandler=e}async sendTypingIndicator(e){if(j(this.id))return;let s=oe(this.id,e);try{await ye({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{ilink_user_id:e,status:Re.TYPING}})}catch{}}updateConfig(e){Object.assign(this.config,e)}getOrCreateSession(e){let s=this.sessions.get(e);return s||(s={lastUserMessageAt:0,quotaRemaining:0},this.sessions.set(e,s)),s}isSessionActive(e){return e.lastUserMessageAt>0&&Date.now()-e.lastUserMessageAt<=ae}getSessionRemainingMs(e){return e.lastUserMessageAt===0?0:Math.max(0,ae-(Date.now()-e.lastUserMessageAt))}enqueueMessage(e,s){let i=this.pendingQueue.get(e);i||(i=[],this.pendingQueue.set(e,i));let n=Date.now();i=i.filter(r=>n-r.queuedAt<Ge),i.length>=vt&&(i.shift(),f.warn({channelId:this.id,chatId:e.slice(0,12)},"Queue full, dropping oldest message")),i.push({message:s,queuedAt:n}),this.pendingQueue.set(e,i),f.info({channelId:this.id,chatId:e.slice(0,12),queueDepth:i.length},"Message enqueued")}async flushQueue(e){let s=this.pendingQueue.get(e);if(!s||s.length===0)return;let i=this.getOrCreateSession(e),n=Math.min(s.length,Math.max(0,i.quotaRemaining-2));if(n<=0){f.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:i.quotaRemaining},"Queue flush skipped: insufficient quota (reserving 2 for conversation)");return}f.info({channelId:this.id,chatId:e.slice(0,12),queueDepth:s.length,sending:n,quotaRemaining:i.quotaRemaining},"Flushing queued messages");let r=0;for(;r<n&&s.length>0;){let o=s[0];if(Date.now()-o.queuedAt>Ge){s.shift();continue}try{if(await this.sendMessage(e,o.message),s.shift(),r++,i.quotaRemaining<=0)break}catch{f.warn({channelId:this.id,chatId:e.slice(0,12)},"Queue flush: send failed, stopping");break}}s.length===0&&this.pendingQueue.delete(e),f.info({channelId:this.id,chatId:e.slice(0,12),sent:r,remaining:s.length},"Queue flush complete")}async checkAndSendReminder(e,s){let i=Date.now(),n=this.lastReminderAt.get(e)??0;if(i-n<Nt)return;let r=this.getSessionRemainingMs(s),a=i-s.lastUserMessageAt>=Ot,d=s.quotaRemaining<=qt;if(!a&&!d)return;let c=(r/36e5).toFixed(1),u;a&&d?u=`[\u7CFB\u7EDF\u63D0\u9192] \u6D88\u606F\u7A97\u53E3\u5373\u5C06\u5173\u95ED\uFF08\u5269\u4F59${c}\u5C0F\u65F6/${s.quotaRemaining}\u6761\u914D\u989D\uFF09\u3002\u8BF7\u56DE\u590D\u4EFB\u610F\u6D88\u606F\u4EE5\u4FDD\u6301\u8FDE\u63A5\u3002`:a?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${s.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 E({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{msg:{from_user_id:"",to_user_id:e,client_id:$(),message_type:A.BOT,message_state:P.FINISH,item_list:[{type:y.TEXT,text_item:{text:u}}],context_token:p}}}),s.quotaRemaining--,this.lastReminderAt.set(e,i),N(this.id,this.sessions),f.info({channelId:this.id,chatId:e.slice(0,12),remainingHours:c,quotaRemaining:s.quotaRemaining,trigger:a?"time":"quota"},"iLink session reminder sent")}catch(l){f.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(l)}`)}}async startLongPoll(){let e=this.pollAbort?.signal,s=0,i=3,n=3e4,r=2e3;for(;!e?.aborted;)try{let o=await he({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,get_updates_buf:this.getUpdatesBuf});if(o.ret===ee||o.errcode===ee){Me(this.id),this.status="error",f.error({channelId:this.id},"Session expired (errcode=-14), pausing for 1 hour"),await this.sleep(B,e),ke(this.id),this.status="connected";continue}if(o.ret!==void 0&&o.ret!==0||o.errcode!==void 0&&o.errcode!==0){s++,f.error({channelId:this.id,ret:o.ret,errcode:o.errcode},"getUpdates API error"),s>=i?(s=0,await this.sleep(n,e)):await this.sleep(r,e);continue}s=0,o.get_updates_buf&&(this.getUpdatesBuf=o.get_updates_buf,Pt(this.id,o.get_updates_buf));for(let d of o.msgs??[])await this.processInbound(d)}catch(o){if(e?.aborted)return;s++,f.error({channelId:this.id,error:o},"getUpdates error"),s>=i?(s=0,await this.sleep(n,e)):await this.sleep(r,e)}}async processInbound(e){if(!this.messageHandler)return;let s=!!e.group_id,i=s?e.group_id:e.from_user_id??"",n=e.from_user_id??"";e.context_token&&i&&Et(this.id,i,e.context_token);let r=this.getOrCreateSession(i),o=r.quotaRemaining;r.lastUserMessageAt=Date.now(),r.quotaRemaining=ze,N(this.id,this.sessions),f.info({channelId:this.id,chatId:i.slice(0,12),quotaReset:!0,prevQuota:o,newQuota:ze,sessionWindowMs:ae},"iLink session reset: user message received, quota restored"),this.flushQueue(i);let a="",d,c=[];for(let l of e.item_list??[])l.type===y.TEXT&&l.text_item?.text&&(a+=l.text_item.text),l.type===y.IMAGE&&(d="image",c.push(l)),l.type===y.VOICE&&(d="audio",c.push(l),l.voice_item?.text&&!a&&(a=l.voice_item.text)),l.type===y.FILE&&(d="file",c.push(l)),l.type===y.VIDEO&&(d="video",c.push(l));if(!a&&!d)return;let u;if(c.length>0){let l=this.config.cdnBaseUrl??Ve;try{let h=await Le(c[0],{cdnBaseUrl:l,channelId:this.id});h&&(u=h.path,d=h.type)}catch(h){f.error({channelId:this.id},`Media download failed: ${String(h)}`)}}let p={channelId:this.id,platform:"wechat",chatId:i,senderId:n,content:a,mediaType:d,mediaPath:u,isGroup:s,timestamp:e.create_time_ms??Date.now(),raw:e};this.messageHandler(p)}getExtensionFromMediaType(e){switch(e){case"image":return".png";case"video":return".mp4";case"audio":return".mp3";default:return".bin"}}sleep(e,s){return new Promise((i,n)=>{let r=setTimeout(i,e);s?.addEventListener("abort",()=>{clearTimeout(r),n(new Error("aborted"))},{once:!0})})}};M();var Lt=_("channels"),X=class{platform="discord";id;config;status="disconnected";messageHandler=null;client=null;constructor(e,s){if(this.id=e,!s.botToken)throw new Error("Discord adapter requires botToken");this.config=s}async connect(){this.status="connecting";try{let{Client:e,GatewayIntentBits:s}=await import("discord.js");this.client=new e({intents:[s.Guilds,s.GuildMessages,s.MessageContent,s.DirectMessages]});let i=this.client;i.on("messageCreate",n=>{if(!this.messageHandler||n.author.bot||this.config.allowedGuildIds?.length&&n.guildId&&!this.config.allowedGuildIds.includes(n.guildId))return;let r={channelId:this.id,platform:"discord",chatId:n.channelId,senderId:n.author.id,senderName:n.author.displayName??n.author.username,content:n.content,isGroup:!!n.guildId,timestamp:n.createdTimestamp,raw:n};this.messageHandler(r)}),await i.login(this.config.botToken),this.status="connected",Lt.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}async sendMessage(e,s){if(!this.client)throw new Error("Discord client not connected");let n=await this.client.channels.fetch(e);if(!n||!("send"in n))throw new Error(`Channel ${e} not found or not text channel`);return(await n.send({content:s.content,reply:s.replyToMessageId?{messageReference:s.replyToMessageId}:void 0})).id}onMessage(e){this.messageHandler=e}async sendTypingIndicator(e){if(!this.client)return;let i=await this.client.channels.fetch(e);i&&"sendTyping"in i&&await i.sendTyping()}};var k=g.object({id:g.string().uuid()}),Wt=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()}),Bt=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()}),ce;function Zn(t){ce=t}function es(){return ce}async function ts(t){let e=ce;t.get("/channels",{schema:{tags:["Channels"],summary:"List channels",querystring:{type:"object",properties:{enabled:{type:"boolean"}}}}},async(s,i)=>({channels:ge(s.query.enabled)})),t.post("/channels",{schema:{tags:["Channels"],summary:"Create a channel",body:{type:"object",required:["name","platform","config"],properties:{name:{type:"string",minLength:1},platform:{type:"string",minLength:1},config:{type:"object"},enabled:{type:"boolean"},linkedRoleId:{type:"string"},allowedChatIds:{type:"array",items:{type:"string"}}}}}},async(s,i)=>{let n=Wt.safeParse(s.body);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let{name:r,platform:o,config:a,enabled:d,linkedRoleId:c,allowedChatIds:u}=n.data,p={id:Dt(),name:r,platform:o,enabled:d,status:"disconnected",config:a,linkedRoleId:c,allowedChatIds:u,createdAt:Date.now(),messageCount:0};return le(p),i.status(201).send({channel:p})}),t.get("/channels/:id",{schema:{tags:["Channels"],summary:"Get channel by ID",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(s,i)=>{let n=k.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);return r?{channel:r}:i.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"}}}}}},async(s,i)=>{let n=k.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);if(!r)return i.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let o=Bt.safeParse(s.body);return o.success?(J(r.id,o.data),{channel:x(r.id)}):i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(o.error)})}),t.delete("/channels/:id",{schema:{tags:["Channels"],summary:"Delete channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(s,i)=>{let n=k.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);return r?(me(r.id),i.status(204).send()):i.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),t.post("/channels/:id/connect",{schema:{tags:["Channels"],summary:"Connect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(s,i)=>{let n=k.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});if(!e)return i.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let r=x(n.data.id);if(!r)return i.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(!e.hasAdapter(r.id)&&r.platform==="discord"){let o=r.config;if(!o.botToken)return i.status(400).send({code:"MISSING_CONFIG",message:"Discord channel requires botToken in config"});let a=new X(r.id,{botToken:o.botToken});await e.addChannel(r,a)}if(!e.hasAdapter(r.id))return i.status(400).send({code:"NO_ADAPTER",message:"No adapter registered for this channel. Install the appropriate adapter first."});try{return await e.connectChannel(r.id),{channelId:r.id,status:"connected"}}catch(o){return i.status(500).send({code:"CONNECT_FAILED",message:String(o)})}}),t.post("/channels/:id/disconnect",{schema:{tags:["Channels"],summary:"Disconnect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(s,i)=>{let n=k.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});if(!e)return i.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let r=x(n.data.id);return r?(await e.disconnectChannel(r.id),{channelId:r.id,status:"disconnected"}):i.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),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(s,i)=>{let n=k.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);if(!r)return i.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let{limit:o=50,offset:a=0}=s.query;return{messages:ue(r.id,o,a)}}),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(s,i)=>{let n=k.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);if(!r)return i.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(r.platform!=="wechat")return i.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=r.config;return await Ie({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(s,i)=>{let n=k.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);if(!r)return i.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(r.platform!=="wechat")return i.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=r.config,{sessionKey:a,timeoutMs:d}=s.body??{},c=await Te({sessionKey:a??"",apiBaseUrl:o.baseUrl,timeoutMs:d??12e4,routeTag:o.routeTag});if(c.connected&&c.botToken){let u={...o,botToken:c.botToken,accountId:c.accountId,baseUrl:c.baseUrl??o.baseUrl,userId:c.userId};if(J(r.id,{config:u}),e){let p=new K(r.id,u),l=x(r.id);l&&await e.addChannel(l,p)}}return{connected:c.connected,accountId:c.accountId,message:c.message}})}export{K as a,X as b,Zn as c,es as d,ts as e};
@@ -0,0 +1,7 @@
1
+ import{b as i,d as a}from"./chunk-5EPG2US5.js";a();function d(e){return{id:e.id,parentId:e.parent_id??void 0,status:e.status,prompt:e.prompt,originalPrompt:e.original_prompt??void 0,config:JSON.parse(e.config),result:e.result??void 0,error:e.error??void 0,sdkSessionId:e.sdk_session_id??void 0,templateId:e.template_id??void 0,roleId:e.role_id??void 0,stepId:e.step_id??void 0,sourceSessionId:e.source_session_id??void 0,deliverTo:e.deliver_to?JSON.parse(e.deliver_to):void 0,reportTo:e.report_to?JSON.parse(e.report_to):void 0,createdAt:e.created_at,startedAt:e.started_at??void 0,completedAt:e.completed_at??void 0,costUsd:e.cost_usd??void 0,tokenUsage:e.token_usage?JSON.parse(e.token_usage):void 0,numTurns:e.num_turns??void 0,totalDurationMs:e.total_duration_ms??void 0,blockReason:e.block_reason_json?JSON.parse(e.block_reason_json):void 0}}function c(e){i().prepare(`
2
+ INSERT INTO tasks (id, parent_id, status, prompt, original_prompt, config, result, error,
3
+ sdk_session_id, template_id, role_id, step_id, source_session_id, notify_targets, deliver_to, report_to,
4
+ created_at, started_at, completed_at,
5
+ cost_usd, token_usage, num_turns, total_duration_ms)
6
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
7
+ `).run(e.id,e.parentId??null,e.status,e.prompt,e.originalPrompt??null,JSON.stringify(e.config),e.result??null,e.error??null,e.sdkSessionId??null,e.templateId??null,e.roleId??null,e.stepId??null,e.sourceSessionId??null,null,e.deliverTo?JSON.stringify(e.deliverTo):null,e.reportTo?JSON.stringify(e.reportTo):null,e.createdAt,e.startedAt??null,e.completedAt??null,e.costUsd??null,e.tokenUsage?JSON.stringify(e.tokenUsage):null,e.numTurns??null,e.totalDurationMs??null)}function g(e){let r=i().prepare("SELECT * FROM tasks WHERE id = ?").get(e);return r?d(r):void 0}function f(e,n){let r=i(),t=[],s=[],u={parentId:"parent_id",status:"status",prompt:"prompt",result:"result",error:"error",sdkSessionId:"sdk_session_id",templateId:"template_id",roleId:"role_id",stepId:"step_id",sourceSessionId:"source_session_id",originalPrompt:"original_prompt",startedAt:"started_at",completedAt:"completed_at",costUsd:"cost_usd",numTurns:"num_turns",totalDurationMs:"total_duration_ms"};for(let[o,l]of Object.entries(u))o in n&&(t.push(`${l} = ?`),s.push(n[o]??null));"config"in n&&(t.push("config = ?"),s.push(JSON.stringify(n.config))),"tokenUsage"in n&&(t.push("token_usage = ?"),s.push(n.tokenUsage?JSON.stringify(n.tokenUsage):null)),"deliverTo"in n&&(t.push("deliver_to = ?"),s.push(n.deliverTo?JSON.stringify(n.deliverTo):null)),"reportTo"in n&&(t.push("report_to = ?"),s.push(n.reportTo?JSON.stringify(n.reportTo):null)),"blockReason"in n&&(t.push("block_reason_json = ?"),s.push(n.blockReason?JSON.stringify(n.blockReason):null)),t.length!==0&&(s.push(e),r.prepare(`UPDATE tasks SET ${t.join(", ")} WHERE id = ?`).run(...s))}function m(e,n=100,r=0,t){let s=i(),u="SELECT * FROM tasks",o=[],l=[];return e&&(o.push("status = ?"),l.push(e)),t&&(o.push("role_id = ?"),l.push(t)),o.length>0&&(u+=" WHERE "+o.join(" AND ")),u+=" ORDER BY created_at DESC LIMIT ? OFFSET ?",l.push(n,r),s.prepare(u).all(...l).map(d)}function T(e){return i().prepare("SELECT * FROM tasks WHERE parent_id = ? ORDER BY created_at ASC").all(e).map(d)}function k(e){return i().prepare("SELECT COALESCE(SUM(cost_usd), 0) as total FROM tasks WHERE completed_at >= ? AND cost_usd IS NOT NULL").get(e).total}export{c as a,g as b,f as c,m as d,T as e,k as f};
@@ -1 +1 @@
1
- import{a as h,b as u,c,d as m,e as v,f as x}from"./chunk-2DLVAKH7.js";import{b as S,d as y}from"./chunk-HDP7A4XY.js";import{a as i}from"./chunk-L7JP7DUO.js";import{a as l}from"./chunk-2CMR5AG7.js";import{a as C}from"./chunk-C6BOQJJF.js";import{e as p}from"./chunk-7K4AQBDD.js";import{v4 as D}from"uuid";import{v4 as I}from"uuid";function _(e){if(e.length<20)return null;let t=e.trim();return t.length>300?{content:`User request: ${t.slice(0,280)}...`,importance:3,type:"thought"}:{content:`User request: ${t}`,importance:3,type:"thought"}}function b(e){if(e.length<20)return null;let t=e.trim();return t.length>400?{content:`Assistant response: ${t.slice(0,370)}...`,importance:2,type:"event"}:{content:`Assistant response: ${t}`,importance:2,type:"event"}}function N(e){let t=S(e,200,0),s=[];for(let o of t){let r=o.role==="user"?_(o.content):b(o.content);r&&s.push(r)}return{facts:s}}function $(e){let t=e.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(s=>s.length>2);return[...new Set(t)].slice(0,20)}async function A(e,t){let{facts:s}=N(e),o=0;for(let r of s){let f=r.content.slice(0,500),g;try{g=await l(f)}catch{}let M=$(f),T={id:I(),roleId:t,type:r.type,content:f,embedding:g,keywords:M,importance:r.importance,sourceType:"session_archive",createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"episodic"};C(T),o++}return o}var n=new Map,a;function w(e){return`${e.type}:${e.channelId??""}:${e.chatId??""}`}function F(){n.clear();let e=m("active",1e3);for(let t of e)n.set(t.id,t)}function Q(e,t){let s=Date.now(),o={id:D(),status:"active",source:e,createdAt:s,lastActiveAt:s,messageCount:0};return h(o),n.set(o.id,o),i.emit({type:"session_created",session:o}),o}function V(e){for(let s of n.values())if(w(s.source)===w(e))return s;let t=v(e);return t&&n.set(t.id,t),t}function B(e){let t=n.get(e);return t||u(e)}function E(e){let t=Date.now();c(e,{status:"archived",archivedAt:t}),p().archiveExtractMemory&&u(e)&&A(e,"role-chat-manager").catch(()=>{}),n.delete(e),i.emit({type:"session_archived",sessionId:e})}function W(e){c(e,{status:"active",archivedAt:void 0});let t=u(e);return t&&(n.set(t.id,t),i.emit({type:"session_restored",session:t})),t}function X(e){y(e),x(e),n.delete(e),i.emit({type:"session_deleted",sessionId:e})}function Y(e){let t=Date.now();c(e,{lastActiveAt:t});let s=n.get(e);s&&(s.lastActiveAt=t)}function Z(e){let t=B(e);if(t){let s=t.messageCount+1;c(e,{messageCount:s});let o=n.get(e);o&&(o.messageCount=s)}}function ee(e){return m(e)}function P(){let t=p().sessionTimeoutMinutes*60*1e3,s=Date.now();for(let o of n.values())if(s-o.lastActiveAt>t)try{E(o.id)}catch{}}function R(e=6e4){d(),a=setInterval(P,e)}function d(){a&&(clearInterval(a),a=void 0)}function te(){return a}function se(){F(),R()}function oe(){d(),n.clear()}function ne(){d(),n.clear()}export{F as a,Q as b,V as c,B as d,E as e,W as f,X as g,Y as h,Z as i,ee as j,R as k,d as l,te as m,se as n,oe as o,ne as p};
1
+ import{a as h,b as u,c,d as m,e as v,f as x}from"./chunk-2YTDCR6A.js";import{a as l}from"./chunk-SWP2JC54.js";import{b as S,d as y}from"./chunk-B6LOT5CG.js";import{a as i}from"./chunk-L7JP7DUO.js";import{a as C}from"./chunk-DVN3BFPP.js";import{e as p}from"./chunk-PG6LMSX6.js";import{v4 as D}from"uuid";import{v4 as I}from"uuid";function _(e){if(e.length<20)return null;let t=e.trim();return t.length>300?{content:`User request: ${t.slice(0,280)}...`,importance:3,type:"thought"}:{content:`User request: ${t}`,importance:3,type:"thought"}}function b(e){if(e.length<20)return null;let t=e.trim();return t.length>400?{content:`Assistant response: ${t.slice(0,370)}...`,importance:2,type:"event"}:{content:`Assistant response: ${t}`,importance:2,type:"event"}}function N(e){let t=S(e,200,0),s=[];for(let o of t){let r=o.role==="user"?_(o.content):b(o.content);r&&s.push(r)}return{facts:s}}function $(e){let t=e.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(s=>s.length>2);return[...new Set(t)].slice(0,20)}async function A(e,t){let{facts:s}=N(e),o=0;for(let r of s){let f=r.content.slice(0,500),g;try{g=await l(f)}catch{}let M=$(f),T={id:I(),roleId:t,type:r.type,content:f,embedding:g,keywords:M,importance:r.importance,sourceType:"session_archive",createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"episodic"};C(T),o++}return o}var n=new Map,a;function w(e){return`${e.type}:${e.channelId??""}:${e.chatId??""}`}function F(){n.clear();let e=m("active",1e3);for(let t of e)n.set(t.id,t)}function Q(e,t){let s=Date.now(),o={id:D(),status:"active",source:e,createdAt:s,lastActiveAt:s,messageCount:0};return h(o),n.set(o.id,o),i.emit({type:"session_created",session:o}),o}function V(e){for(let s of n.values())if(w(s.source)===w(e))return s;let t=v(e);return t&&n.set(t.id,t),t}function B(e){let t=n.get(e);return t||u(e)}function E(e){let t=Date.now();c(e,{status:"archived",archivedAt:t}),p().archiveExtractMemory&&u(e)&&A(e,"role-chat-manager").catch(()=>{}),n.delete(e),i.emit({type:"session_archived",sessionId:e})}function W(e){c(e,{status:"active",archivedAt:void 0});let t=u(e);return t&&(n.set(t.id,t),i.emit({type:"session_restored",session:t})),t}function X(e){y(e),x(e),n.delete(e),i.emit({type:"session_deleted",sessionId:e})}function Y(e){let t=Date.now();c(e,{lastActiveAt:t});let s=n.get(e);s&&(s.lastActiveAt=t)}function Z(e){let t=B(e);if(t){let s=t.messageCount+1;c(e,{messageCount:s});let o=n.get(e);o&&(o.messageCount=s)}}function ee(e){return m(e)}function P(){let t=p().sessionTimeoutMinutes*60*1e3,s=Date.now();for(let o of n.values())if(s-o.lastActiveAt>t)try{E(o.id)}catch{}}function R(e=6e4){d(),a=setInterval(P,e)}function d(){a&&(clearInterval(a),a=void 0)}function te(){return a}function se(){F(),R()}function oe(){d(),n.clear()}function ne(){d(),n.clear()}export{F as a,Q as b,V as c,B as d,E as e,W as f,X as g,Y as h,Z as i,ee as j,R as k,d as l,te as m,se as n,oe as o,ne as p};
@@ -1 +1 @@
1
- import{a as m,c as d}from"./chunk-FCV2DPZQ.js";import o from"pino";import{Writable as g}from"stream";function b(n){i.push(n)}function L(){if(h)try{return m("pino-pretty")({colorize:!0,translateTime:"HH:MM:ss.l",ignore:"pid,hostname"})}catch{}return process.stdout}function y(n){return r[n]||e}function E(n){e.level=n;for(let t of Object.values(r))t.level=n}function S(){return e.level}function w(n){a=n}function C(){return a}var p,i,u,h,e,r,a,v=d(()=>{p=process.env.ADAM_LOG_LEVEL||"info",i=[];u=new g({write(n,t,l){try{let s=JSON.parse(n.toString());for(let c of i)c(s)}catch{}l()}}),h=process.env.NODE_ENV!=="production";e=o({level:p,timestamp:o.stdTimeFunctions.epochTime,formatters:{level:n=>({level:n}),bindings:n=>({component:n.name})},serializers:{error:o.stdSerializers.err}},o.multistream([{stream:L()},{stream:u}])),r={adam:e.child({name:"adam"}),manager:e.child({name:"manager"}),scheduler:e.child({name:"scheduler"}),api:e.child({name:"api"}),ws:e.child({name:"ws"}),cli:e.child({name:"cli"}),store:e.child({name:"store"}),embedding:e.child({name:"embedding"}),admin:e.child({name:"admin"}),agent:e.child({name:"agent"}),channels:e.child({name:"channels"}),"plugin-sync":e.child({name:"plugin-sync"}),watchdog:e.child({name:"watchdog"}),"chat-manager":e.child({name:"chat-manager"}),execution:e.child({name:"execution"}),"execution-pool":e.child({name:"execution-pool"}),"message-handler":e.child({name:"message-handler"}),"goal-manager":e.child({name:"goal-manager"}),"cli:register-ai-digest":e.child({name:"cli:register-ai-digest"}),"sandbox-macos":e.child({name:"sandbox-macos"}),"sandbox-linux":e.child({name:"sandbox-linux"}),sandbox:e.child({name:"sandbox"}),audit:e.child({name:"audit"}),config:e.child({name:"config"})};a=null});export{b as a,e as b,y as c,E as d,S as e,w as f,C as g,v as h};
1
+ import{a as m,c as d}from"./chunk-FCV2DPZQ.js";import o from"pino";import{Writable as g}from"stream";function b(n){i.push(n)}function L(){if(u)try{return m("pino-pretty")({colorize:!0,translateTime:"HH:MM:ss.l",ignore:"pid,hostname"})}catch{}return process.stdout}function y(n){return r[n]||e}function E(n){e.level=n;for(let t of Object.values(r))t.level=n}function S(){return e.level}function w(n){a=n}function C(){return a}var p,i,h,u,e,r,a,v=d(()=>{p=process.env.ADAM_LOG_LEVEL||"info",i=[];h=new g({write(n,t,l){try{let c=JSON.parse(n.toString());for(let s of i)s(c)}catch{}l()}}),u=process.env.NODE_ENV!=="production";e=o({level:p,timestamp:o.stdTimeFunctions.epochTime,formatters:{level:n=>({level:n}),bindings:n=>({component:n.name})},serializers:{error:o.stdSerializers.err}},o.multistream([{stream:L()},{stream:h}])),r={adam:e.child({name:"adam"}),manager:e.child({name:"manager"}),scheduler:e.child({name:"scheduler"}),api:e.child({name:"api"}),ws:e.child({name:"ws"}),cli:e.child({name:"cli"}),store:e.child({name:"store"}),embedding:e.child({name:"embedding"}),admin:e.child({name:"admin"}),agent:e.child({name:"agent"}),channels:e.child({name:"channels"}),"plugin-sync":e.child({name:"plugin-sync"}),watchdog:e.child({name:"watchdog"}),"chat-manager":e.child({name:"chat-manager"}),execution:e.child({name:"execution"}),"execution-pool":e.child({name:"execution-pool"}),"message-handler":e.child({name:"message-handler"}),"goal-manager":e.child({name:"goal-manager"}),"cli:register-ai-digest":e.child({name:"cli:register-ai-digest"}),"sandbox-macos":e.child({name:"sandbox-macos"}),"sandbox-linux":e.child({name:"sandbox-linux"}),sandbox:e.child({name:"sandbox"}),audit:e.child({name:"audit"}),config:e.child({name:"config"}),"event-dispatcher":e.child({name:"event-dispatcher"})};a=null});export{b as a,e as b,y as c,E as d,S as e,w as f,C as g,v as h};
@@ -1 +1 @@
1
- import{d as b,h as k}from"./chunk-WBAPIPST.js";import{c as w,h as x}from"./chunk-INNDBLZE.js";k();x();import{constants as S,copyFileSync as g,existsSync as d,lstatSync as P,mkdirSync as $,readdirSync as E,realpathSync as u,rmSync as z,statSync as m,unlinkSync as h}from"fs";import{dirname as I,extname as R,isAbsolute as B,join as a,sep as c}from"path";var y=w("watchdog");function W(){return process.env.ADAM_TEST_DIR||b}function p(){return a(W(),"workflows")}function v(t){return a(p(),t,"artifacts")}function D(t){let r=v(t);return $(r,{recursive:!0}),r}function T(t,r,i){if(!B(t))throw new Error(`path must be absolute: ${t}`);let o=u(r),s=o.endsWith(c)?o:o+c;if(i){let n=u(t),f=n.endsWith(c)?n:n+c;if(f===s||f.startsWith(s))return;throw new Error(`path escapes workspace: ${t} (resolved=${n}, root=${o})`)}if(d(t))throw P(t).isSymbolicLink()?new Error(`destination already exists and is a symlink: ${t}`):new Error(`destination already exists: ${t}`);let e=u(I(t)),l=e.endsWith(c)?e:e+c;if(!(l===s||l.startsWith(s)))throw new Error(`destination escapes workspace: ${t} (parent resolved=${e}, root=${o})`)}function C(t){let r=D(t.executionId),i=a(r,`${t.artifactId}.bin`);return g(t.sourcePath,i),{blobPath:i,sizeBytes:m(i).size}}function O(t){h(t)}function j(t){if(!d(t.blobPath))throw new Error(`blob file missing on disk: ${t.blobPath}`);return g(t.blobPath,t.destPath,S.COPYFILE_EXCL),{sizeBytes:m(t.destPath).size}}function F(t){try{h(t)}catch(r){y.warn({err:r,blobPath:t},"Failed to remove workflow artifact blob")}}function N(t){try{z(a(p(),t),{recursive:!0,force:!0})}catch(r){y.warn({err:r,executionId:t},"Failed to remove workflow artifacts directory")}}function U(t,r,i){let o=v(t);if(!d(o))return 0;let s=0;for(let e of E(o)){if(R(e)!==".bin")continue;let l=e.slice(0,-4);if(r.has(l))continue;let n=a(o,e),f=m(n);Date.now()-f.mtimeMs<i||(F(n),s++)}return s}export{D as a,T as b,C as c,O as d,j as e,F as f,N as g,U as h};
1
+ import{d as b,h as k}from"./chunk-WBAPIPST.js";import{c as w,h as x}from"./chunk-MRTJFYPR.js";k();x();import{constants as S,copyFileSync as g,existsSync as d,lstatSync as P,mkdirSync as $,readdirSync as E,realpathSync as u,rmSync as z,statSync as m,unlinkSync as h}from"fs";import{dirname as I,extname as R,isAbsolute as B,join as a,sep as c}from"path";var y=w("watchdog");function W(){return process.env.ADAM_TEST_DIR||b}function p(){return a(W(),"workflows")}function v(t){return a(p(),t,"artifacts")}function D(t){let r=v(t);return $(r,{recursive:!0}),r}function T(t,r,i){if(!B(t))throw new Error(`path must be absolute: ${t}`);let o=u(r),s=o.endsWith(c)?o:o+c;if(i){let n=u(t),f=n.endsWith(c)?n:n+c;if(f===s||f.startsWith(s))return;throw new Error(`path escapes workspace: ${t} (resolved=${n}, root=${o})`)}if(d(t))throw P(t).isSymbolicLink()?new Error(`destination already exists and is a symlink: ${t}`):new Error(`destination already exists: ${t}`);let e=u(I(t)),l=e.endsWith(c)?e:e+c;if(!(l===s||l.startsWith(s)))throw new Error(`destination escapes workspace: ${t} (parent resolved=${e}, root=${o})`)}function C(t){let r=D(t.executionId),i=a(r,`${t.artifactId}.bin`);return g(t.sourcePath,i),{blobPath:i,sizeBytes:m(i).size}}function O(t){h(t)}function j(t){if(!d(t.blobPath))throw new Error(`blob file missing on disk: ${t.blobPath}`);return g(t.blobPath,t.destPath,S.COPYFILE_EXCL),{sizeBytes:m(t.destPath).size}}function F(t){try{h(t)}catch(r){y.warn({err:r,blobPath:t},"Failed to remove workflow artifact blob")}}function N(t){try{z(a(p(),t),{recursive:!0,force:!0})}catch(r){y.warn({err:r,executionId:t},"Failed to remove workflow artifacts directory")}}function U(t,r,i){let o=v(t);if(!d(o))return 0;let s=0;for(let e of E(o)){if(R(e)!==".bin")continue;let l=e.slice(0,-4);if(r.has(l))continue;let n=a(o,e),f=m(n);Date.now()-f.mtimeMs<i||(F(n),s++)}return s}export{D as a,T as b,C as c,O as d,j as e,F as f,N as g,U as h};
@@ -1,4 +1,4 @@
1
- import{a as c,b as m}from"./chunk-S3BAIZ4Q.js";import{b as a,d as _}from"./chunk-JAS3TUZX.js";import{c as s,h as f}from"./chunk-INNDBLZE.js";import{readFileSync as p,existsSync as g}from"fs";import{fileURLToPath as A}from"url";import{dirname as I,join as o}from"path";var O=A(import.meta.url),l=I(O),r,n;function u(){let e=o(l,"..","package.json");if(g(e))return e;let i=o(l,"..","..","package.json");return g(i)?i:o(process.cwd(),"package.json")}function P(){if(r===void 0){let e=u();r=JSON.parse(p(e,"utf-8")).version}return r}function b(){if(n===void 0){let e=u();n=JSON.parse(p(e,"utf-8")).name}return n}_();f();import{dirname as h,join as T}from"path";import{fileURLToPath as y}from"url";var k=h(y(import.meta.url)),d=T(k,"..");var x=d,U=s("cli:register-ai-digest"),t="ai-hourly-digest";function R(){try{if(m(t)){console.log(`[INFO] AI Digest template already exists (${t})`);return}}catch{}let e={id:t,name:"AI Hourly Digest",description:"\u6BCF\u5C0F\u65F6\u641C\u7D22 AI \u524D\u6CBF\u6587\u7AE0\uFF0C\u603B\u7ED3\u540E\u4FDD\u5B58\u5230 Omnifocus",trigger:{type:"cron",cron:"0 * * * *"},enabled:!0,steps:[{id:"search_ai_news",prompt:`\u641C\u7D22\u8FC7\u53BB 24 \u5C0F\u65F6\u5185\u5173\u4E8E AI/\u4EBA\u5DE5\u667A\u80FD\u7684\u6700\u65B0\u524D\u6CBF\u6587\u7AE0\u3002
1
+ import{c,d as m}from"./chunk-5XOTPEAK.js";import{b as a,d as _}from"./chunk-5EPG2US5.js";import{c as s,h as f}from"./chunk-MRTJFYPR.js";import{readFileSync as p,existsSync as l}from"fs";import{fileURLToPath as A}from"url";import{dirname as I,join as r}from"path";var O=A(import.meta.url),g=I(O),i,n;function u(){let e=r(g,"..","package.json");if(l(e))return e;let o=r(g,"..","..","package.json");return l(o)?o:r(process.cwd(),"package.json")}function P(){if(i===void 0){let e=u();i=JSON.parse(p(e,"utf-8")).version}return i}function S(){if(n===void 0){let e=u();n=JSON.parse(p(e,"utf-8")).name}return n}_();f();import{dirname as h,join as R}from"path";import{fileURLToPath as T}from"url";var y=h(T(import.meta.url)),d=R(y,"..");var k=d,U=s("cli:register-ai-digest"),t="ai-hourly-digest";function x(){try{if(m(t)){console.log(`[INFO] AI Digest template already exists (${t})`);return}}catch{}let e={id:t,name:"AI Hourly Digest",description:"\u6BCF\u5C0F\u65F6\u641C\u7D22 AI \u524D\u6CBF\u6587\u7AE0\uFF0C\u603B\u7ED3\u540E\u4FDD\u5B58\u5230 Omnifocus",trigger:{type:"cron",cron:"0 * * * *"},enabled:!0,steps:[{id:"search_ai_news",autoSelectRole:!0,requirements:{},prompt:`\u641C\u7D22\u8FC7\u53BB 24 \u5C0F\u65F6\u5185\u5173\u4E8E AI/\u4EBA\u5DE5\u667A\u80FD\u7684\u6700\u65B0\u524D\u6CBF\u6587\u7AE0\u3002
2
2
 
3
3
  \u641C\u7D22\u6765\u6E90:
4
4
  1. Hacker News AI \u677F\u5757 (https://news.ycombinator.com/front?day=1)
@@ -11,7 +11,7 @@ import{a as c,b as m}from"./chunk-S3BAIZ4Q.js";import{b as a,d as _}from"./chunk
11
11
  - \u6807\u9898\uFF1A[\u6587\u7AE0\u6807\u9898]
12
12
  - \u6765\u6E90\uFF1A[\u7F51\u7AD9/\u5E73\u53F0\u540D\u79F0]
13
13
  - \u94FE\u63A5\uFF1A[\u5B8C\u6574 URL]
14
- - \u6838\u5FC3\u4EF7\u503C\uFF1A[1-2 \u53E5\u8BDD\u8BF4\u660E\u4E3A\u4EC0\u4E48\u8FD9\u7BC7\u6587\u7AE0\u503C\u5F97\u770B]`},{id:"summarize_article",dependsOn:["search_ai_news"],prompt:`\u9605\u8BFB\u5E76\u603B\u7ED3\u8FD9\u7BC7\u6587\u7AE0\u3002
14
+ - \u6838\u5FC3\u4EF7\u503C\uFF1A[1-2 \u53E5\u8BDD\u8BF4\u660E\u4E3A\u4EC0\u4E48\u8FD9\u7BC7\u6587\u7AE0\u503C\u5F97\u770B]`},{id:"summarize_article",dependsOn:["search_ai_news"],autoSelectRole:!0,requirements:{},prompt:`\u9605\u8BFB\u5E76\u603B\u7ED3\u8FD9\u7BC7\u6587\u7AE0\u3002
15
15
 
16
16
  \u6587\u7AE0\u4FE1\u606F:
17
17
  {{search_ai_news.result}}
@@ -32,18 +32,18 @@ import{a as c,b as m}from"./chunk-S3BAIZ4Q.js";import{b as a,d as _}from"./chunk
32
32
  [\u8FD9\u9879\u5DE5\u4F5C\u7684\u610F\u4E49\u6216\u5BF9\u884C\u4E1A\u7684\u5F71\u54CD]
33
33
 
34
34
  ## \u539F\u6587\u94FE\u63A5
35
- [\u6587\u7AE0 URL]`},{id:"save_to_omnifocus",dependsOn:["summarize_article"],prompt:`\u5C06\u6587\u7AE0\u603B\u7ED3\u4FDD\u5B58\u5230 Omnifocus\u3002
35
+ [\u6587\u7AE0 URL]`},{id:"save_to_omnifocus",dependsOn:["summarize_article"],autoSelectRole:!0,requirements:{},prompt:`\u5C06\u6587\u7AE0\u603B\u7ED3\u4FDD\u5B58\u5230 Omnifocus\u3002
36
36
 
37
37
  \u603B\u7ED3\u5185\u5BB9:
38
38
  {{summarize_article.result}}
39
39
 
40
40
  \u63D0\u53D6\u6587\u7AE0\u6807\u9898\u548C\u5B8C\u6574\u603B\u7ED3\uFF0C\u7136\u540E\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u6DFB\u52A0\u5230 Omnifocus Inbox\uFF1A
41
41
 
42
- osascript ${x}/scripts/add-to-omnifocus.applescript "[\u6587\u7AE0\u6807\u9898] AI \u524D\u6CBF\u901F\u9012" "[\u5B8C\u6574\u603B\u7ED3\u5185\u5BB9]"
42
+ osascript ${k}/scripts/add-to-omnifocus.applescript "[\u6587\u7AE0\u6807\u9898] AI \u524D\u6CBF\u901F\u9012" "[\u5B8C\u6574\u603B\u7ED3\u5185\u5BB9]"
43
43
 
44
44
  \u6CE8\u610F\uFF1A
45
45
  - \u5C06 [\u6587\u7AE0\u6807\u9898] \u66FF\u6362\u4E3A\u5B9E\u9645\u6807\u9898
46
46
  - \u5C06 [\u5B8C\u6574\u603B\u7ED3\u5185\u5BB9] \u66FF\u6362\u4E3A\u5B8C\u6574\u7684\u603B\u7ED3\u6587\u672C\uFF08\u5305\u542B\u6838\u5FC3\u53D1\u73B0\u3001\u6280\u672F\u7EC6\u8282\u3001\u5F71\u54CD/\u610F\u4E49\u548C\u539F\u6587\u94FE\u63A5\uFF09
47
47
  - \u603B\u7ED3\u5185\u5BB9\u4F7F\u7528\u6362\u884C\u7B26\u5206\u9694\u5404\u90E8\u5206
48
48
 
49
- \u5B8C\u6210\u540E\u8F93\u51FA\uFF1A\u5DF2\u4FDD\u5B58\u5230 Omnifocus\uFF1A[\u4EFB\u52A1\u6807\u9898]`}],config:{timeout:300},tags:["ai","digest","hourly","automation"],createdAt:Date.now()};c(e),console.log(`[INFO] Registered AI Hourly Digest task template (${t})`),console.log("[INFO] Cron schedule: 0 * * * * (every hour at minute 0)")}import.meta.url===`file://${process.argv[1]}`&&(console.log("Initializing database..."),a(),console.log("Registering AI Digest template..."),R(),console.log("Done."),process.exit(0));export{d as a,P as b,b as c,R as d};
49
+ \u5B8C\u6210\u540E\u8F93\u51FA\uFF1A\u5DF2\u4FDD\u5B58\u5230 Omnifocus\uFF1A[\u4EFB\u52A1\u6807\u9898]`}],config:{timeout:300},tags:["ai","digest","hourly","automation"],createdAt:Date.now()};c(e),console.log(`[INFO] Registered AI Hourly Digest task template (${t})`),console.log("[INFO] Cron schedule: 0 * * * * (every hour at minute 0)")}import.meta.url===`file://${process.argv[1]}`&&(console.log("Initializing database..."),a(),console.log("Registering AI Digest template..."),x(),console.log("Done."),process.exit(0));export{d as a,P as b,S as c,x as d};
@@ -1,4 +1,4 @@
1
- import{b as t,d}from"./chunk-JAS3TUZX.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{b as t,d}from"./chunk-5EPG2US5.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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -1 +1 @@
1
- import{e as T,j as $}from"./chunk-QWCRZDZS.js";import{e as R,i as x}from"./chunk-GBTG5B5R.js";import{c as J,e as E}from"./chunk-FCV2DPZQ.js";var F={};E(F,{getGlobalEnabledState:()=>k,getInstalledPlugin:()=>N,getPluginManifest:()=>j,listInstalledPlugins:()=>v,listMarketplaceSources:()=>L,resolvePluginPaths:()=>A,scanDirectoryConfig:()=>w});import{existsSync as m,readFileSync as y,readdirSync as I}from"fs";import{join as u}from"path";import M from"os";function h(n){try{if(!m(n))return null;let t=y(n,"utf-8");return JSON.parse(t)}catch{return null}}function k(){return h(O())?.enabledPlugins??{}}function j(n){let t=n;function o(e,s){let l={};try{if(!m(e))return l;let c=y(e,"utf-8").replace(/^```yaml\r?\n/,"").replace(/^```\r?\n/,"");for(let d of s){let r=new RegExp(`^${d}:\\s*(.+)$`,"m"),g=c.match(r);g&&(l[d]=g[1].trim())}}catch{}return l}try{let e={name:"",skills:[],agents:[],mcpServers:[],hooks:[],lspServers:[]},s=u(t,".claude-plugin","plugin.json");if(m(s))try{let r=JSON.parse(y(s,"utf-8"));e.name=r.name??"",e.version=r.version,e.description=r.description,Array.isArray(r.lspServers)&&(e.lspServers=r.lspServers),Array.isArray(r.mcpServers)&&(e.mcpServers=r.mcpServers),Array.isArray(r.hooks)&&(e.hooks=r.hooks)}catch{}let l=u(t,"skills");if(m(l)){let r=I(l,{withFileTypes:!0});for(let g of r){if(!g.isDirectory()&&!g.isSymbolicLink())continue;let p=u(l,g.name,"SKILL.md"),i=o(p,["name","description"]);i.name&&e.skills.push({name:i.name,description:i.description??""})}}let a=u(t,"agents");if(m(a)){let r=I(a,{withFileTypes:!0});for(let g of r){if(!g.isFile()||!g.name.endsWith(".md"))continue;let p=o(u(a,g.name),["name","description"]);p.name&&e.agents.push({name:p.name,description:p.description??""})}}let c=u(t,".mcp.json");if(m(c))try{let r=JSON.parse(y(c,"utf-8"));r.mcpServers&&typeof r.mcpServers=="object"&&(e.mcpServers=Object.keys(r.mcpServers))}catch{}let d=u(t,"hooks","hooks.json");if(m(d))try{let r=JSON.parse(y(d,"utf-8"));Array.isArray(r)&&(e.hooks=r.map(g=>typeof g=="object"&&g!==null&&"event"in g?String(g.event):String(g)))}catch{}return e}catch{return null}}function v(n){let t=h(S());if(!t?.plugins)return[];let o=k(),e=[];for(let[s,l]of Object.entries(t.plugins))if(!(!Array.isArray(l)||l.length===0))for(let a of l){let c=a.scope??"user";n?.scope&&c!==n.scope||n?.projectPath&&a.projectPath!==n.projectPath||e.push({id:s,name:s.split("@")[0],version:a.version??"",scope:c,projectPath:a.projectPath,installPath:a.installPath??u(P(),s),enabled:o[s]??a.enabled??!0,installedAt:a.installedAt??"",lastUpdated:a.lastUpdated??""})}return e}function N(n){let t=h(S());if(!t?.plugins?.[n])return null;let o=t.plugins[n];if(!Array.isArray(o)||o.length===0)return null;let e=o[0],s=k();return{id:n,name:n.split("@")[0],version:e.version??"",scope:e.scope??"user",projectPath:e.projectPath,installPath:e.installPath??u(P(),n),enabled:s[n]??e.enabled??!0,installedAt:e.installedAt??"",lastUpdated:e.lastUpdated??""}}function A(n){let t=h(S()),o=new Map;for(let e of n){let s=t?.plugins?.[e];Array.isArray(s)&&s.length>0&&o.set(e,s[0].installPath??u(P(),e))}return o}function L(){return h(C())?.marketplaces??[]}function w(n){let t=u(n,".claude","settings.json"),o=h(t);return{enabledPlugins:o?.enabledPlugins??{},mcpServers:o?.mcpServers??{},allowedTools:o?.allowedTools??[],disallowedTools:o?.disallowedTools??[]}}var P,S,C,O,D=J(()=>{"use strict";P=()=>u(M.homedir(),".claude","plugins"),S=()=>u(P(),"installed_plugins.json"),C=()=>u(P(),"known_marketplaces.json"),O=()=>u(M.homedir(),".claude","settings.json")});D();$();x();var _={Read:{category:"File",label:"read"},Write:{category:"File",label:"write"},Edit:{category:"File",label:"edit"},Glob:{category:"Search",label:"find files"},Grep:{category:"Search",label:"search content"},Bash:{category:"Execution",label:"shell commands"},WebSearch:{category:"Web",label:"web search"},WebFetch:{category:"Web",label:"fetch pages"},NotebookEdit:{category:"Execution",label:"Jupyter notebooks"}};function z(n,t){let o=n.allowedTools??[],e=n.osCapabilities??[];if(o.length===0&&e.length===0&&Object.keys(n.mcpServers??{}).length===0&&(n.additionalDirectories?.length??0)===0&&(!t||t.plugins.length===0))return"No tool permissions";let s=new Map,l=[];for(let p of o){let i=_[p];if(i){let f=s.get(i.category)??[];f.push(i.label),s.set(i.category,f)}else l.push(p)}let a=[];for(let[p,i]of s)a.push(`${p} (${i.join(", ")})`);l.length>0&&a.push(l.join(", "));let c=a.join(" \xB7 "),d=p=>{c=c?`${c} \xB7 ${p}`:p},r=Object.keys(n.mcpServers??{});r.length>0&&d(`MCP: ${r.join(", ")}`);let g=n.additionalDirectories??[];if(g.length>0&&d(`Dirs: ${g.map(p=>p.path).join(", ")}`),e.length>0){let p=e.map(i=>{let f=R(i.id);return i.id==="automation"&&i.targets?.length?`${f.label} (${i.targets.join(", ")})`:f.label});d(`OS: ${p.join(", ")}`)}if(t&&t.plugins.length>0){let p=t.plugins.map(i=>{let f=[];return i.skills.length>0&&f.push(`skills: ${i.skills.map(b=>b.name).join(", ")}`),i.agents.length>0&&f.push(`agents: ${i.agents.map(b=>b.name).join(", ")}`),f.length>0?`${i.name} (${f.join("; ")})`:i.name});d(`Plugins: ${p.join(", ")}`)}return c}function W(n){let t=[],o=n.additionalDirectories??[];for(let e of o){if(!e.inheritPlugins&&!e.inheritMcp)continue;let s=w(e.path),l=Object.entries(s.enabledPlugins).filter(([,c])=>c).map(([c])=>c),a=A(l);for(let[,c]of a)t.includes(c)||t.push(c)}try{let e=T(n.name),s=v({scope:"project",projectPath:e});for(let l of s)l.installPath&&!t.includes(l.installPath)&&t.push(l.installPath)}catch{}return t}function Q(n){let t=W(n),o=[];for(let e of t){let s=j(e);s&&o.push({name:s.name||e.split("/").pop()||"unknown",description:s.description,skills:s.skills,agents:s.agents,mcpServers:s.mcpServers,hooks:s.hooks})}return{plugins:o}}export{k as a,j as b,v as c,N as d,L as e,w as f,F as g,D as h,z as i,W as j,Q as k};
1
+ import{e as T,j as $}from"./chunk-WMB7P64J.js";import{e as R,i as x}from"./chunk-HQRUJQN7.js";import{c as J,e as E}from"./chunk-FCV2DPZQ.js";var F={};E(F,{getGlobalEnabledState:()=>k,getInstalledPlugin:()=>N,getPluginManifest:()=>j,listInstalledPlugins:()=>v,listMarketplaceSources:()=>L,resolvePluginPaths:()=>A,scanDirectoryConfig:()=>w});import{existsSync as m,readFileSync as y,readdirSync as I}from"fs";import{join as u}from"path";import M from"os";function h(n){try{if(!m(n))return null;let t=y(n,"utf-8");return JSON.parse(t)}catch{return null}}function k(){return h(O())?.enabledPlugins??{}}function j(n){let t=n;function o(e,s){let l={};try{if(!m(e))return l;let c=y(e,"utf-8").replace(/^```yaml\r?\n/,"").replace(/^```\r?\n/,"");for(let d of s){let r=new RegExp(`^${d}:\\s*(.+)$`,"m"),g=c.match(r);g&&(l[d]=g[1].trim())}}catch{}return l}try{let e={name:"",skills:[],agents:[],mcpServers:[],hooks:[],lspServers:[]},s=u(t,".claude-plugin","plugin.json");if(m(s))try{let r=JSON.parse(y(s,"utf-8"));e.name=r.name??"",e.version=r.version,e.description=r.description,Array.isArray(r.lspServers)&&(e.lspServers=r.lspServers),Array.isArray(r.mcpServers)&&(e.mcpServers=r.mcpServers),Array.isArray(r.hooks)&&(e.hooks=r.hooks)}catch{}let l=u(t,"skills");if(m(l)){let r=I(l,{withFileTypes:!0});for(let g of r){if(!g.isDirectory()&&!g.isSymbolicLink())continue;let p=u(l,g.name,"SKILL.md"),i=o(p,["name","description"]);i.name&&e.skills.push({name:i.name,description:i.description??""})}}let a=u(t,"agents");if(m(a)){let r=I(a,{withFileTypes:!0});for(let g of r){if(!g.isFile()||!g.name.endsWith(".md"))continue;let p=o(u(a,g.name),["name","description"]);p.name&&e.agents.push({name:p.name,description:p.description??""})}}let c=u(t,".mcp.json");if(m(c))try{let r=JSON.parse(y(c,"utf-8"));r.mcpServers&&typeof r.mcpServers=="object"&&(e.mcpServers=Object.keys(r.mcpServers))}catch{}let d=u(t,"hooks","hooks.json");if(m(d))try{let r=JSON.parse(y(d,"utf-8"));Array.isArray(r)&&(e.hooks=r.map(g=>typeof g=="object"&&g!==null&&"event"in g?String(g.event):String(g)))}catch{}return e}catch{return null}}function v(n){let t=h(S());if(!t?.plugins)return[];let o=k(),e=[];for(let[s,l]of Object.entries(t.plugins))if(!(!Array.isArray(l)||l.length===0))for(let a of l){let c=a.scope??"user";n?.scope&&c!==n.scope||n?.projectPath&&a.projectPath!==n.projectPath||e.push({id:s,name:s.split("@")[0],version:a.version??"",scope:c,projectPath:a.projectPath,installPath:a.installPath??u(P(),s),enabled:o[s]??a.enabled??!0,installedAt:a.installedAt??"",lastUpdated:a.lastUpdated??""})}return e}function N(n){let t=h(S());if(!t?.plugins?.[n])return null;let o=t.plugins[n];if(!Array.isArray(o)||o.length===0)return null;let e=o[0],s=k();return{id:n,name:n.split("@")[0],version:e.version??"",scope:e.scope??"user",projectPath:e.projectPath,installPath:e.installPath??u(P(),n),enabled:s[n]??e.enabled??!0,installedAt:e.installedAt??"",lastUpdated:e.lastUpdated??""}}function A(n){let t=h(S()),o=new Map;for(let e of n){let s=t?.plugins?.[e];Array.isArray(s)&&s.length>0&&o.set(e,s[0].installPath??u(P(),e))}return o}function L(){return h(C())?.marketplaces??[]}function w(n){let t=u(n,".claude","settings.json"),o=h(t);return{enabledPlugins:o?.enabledPlugins??{},mcpServers:o?.mcpServers??{},allowedTools:o?.allowedTools??[],disallowedTools:o?.disallowedTools??[]}}var P,S,C,O,D=J(()=>{"use strict";P=()=>u(M.homedir(),".claude","plugins"),S=()=>u(P(),"installed_plugins.json"),C=()=>u(P(),"known_marketplaces.json"),O=()=>u(M.homedir(),".claude","settings.json")});D();$();x();var _={Read:{category:"File",label:"read"},Write:{category:"File",label:"write"},Edit:{category:"File",label:"edit"},Glob:{category:"Search",label:"find files"},Grep:{category:"Search",label:"search content"},Bash:{category:"Execution",label:"shell commands"},WebSearch:{category:"Web",label:"web search"},WebFetch:{category:"Web",label:"fetch pages"},NotebookEdit:{category:"Execution",label:"Jupyter notebooks"}};function z(n,t){let o=n.allowedTools??[],e=n.osCapabilities??[];if(o.length===0&&e.length===0&&Object.keys(n.mcpServers??{}).length===0&&(n.additionalDirectories?.length??0)===0&&(!t||t.plugins.length===0))return"No tool permissions";let s=new Map,l=[];for(let p of o){let i=_[p];if(i){let f=s.get(i.category)??[];f.push(i.label),s.set(i.category,f)}else l.push(p)}let a=[];for(let[p,i]of s)a.push(`${p} (${i.join(", ")})`);l.length>0&&a.push(l.join(", "));let c=a.join(" \xB7 "),d=p=>{c=c?`${c} \xB7 ${p}`:p},r=Object.keys(n.mcpServers??{});r.length>0&&d(`MCP: ${r.join(", ")}`);let g=n.additionalDirectories??[];if(g.length>0&&d(`Dirs: ${g.map(p=>p.path).join(", ")}`),e.length>0){let p=e.map(i=>{let f=R(i.id);return i.id==="automation"&&i.targets?.length?`${f.label} (${i.targets.join(", ")})`:f.label});d(`OS: ${p.join(", ")}`)}if(t&&t.plugins.length>0){let p=t.plugins.map(i=>{let f=[];return i.skills.length>0&&f.push(`skills: ${i.skills.map(b=>b.name).join(", ")}`),i.agents.length>0&&f.push(`agents: ${i.agents.map(b=>b.name).join(", ")}`),f.length>0?`${i.name} (${f.join("; ")})`:i.name});d(`Plugins: ${p.join(", ")}`)}return c}function W(n){let t=[],o=n.additionalDirectories??[];for(let e of o){if(!e.inheritPlugins&&!e.inheritMcp)continue;let s=w(e.path),l=Object.entries(s.enabledPlugins).filter(([,c])=>c).map(([c])=>c),a=A(l);for(let[,c]of a)t.includes(c)||t.push(c)}try{let e=T(n.name),s=v({scope:"project",projectPath:e});for(let l of s)l.installPath&&!t.includes(l.installPath)&&t.push(l.installPath)}catch{}return t}function Q(n){let t=W(n),o=[];for(let e of t){let s=j(e);s&&o.push({name:s.name||e.split("/").pop()||"unknown",description:s.description,skills:s.skills,agents:s.agents,mcpServers:s.mcpServers,hooks:s.hooks})}return{plugins:o}}export{k as a,j as b,v as c,N as d,L as e,w as f,F as g,D as h,z as i,W as j,Q as k};
@@ -1 +1 @@
1
- import{a as i}from"./chunk-UQJZU3R5.js";import{c as p}from"./chunk-7IFLU3CY.js";import{d as c}from"./chunk-GSMC3VUM.js";import{f as d,h as R}from"./chunk-WBAPIPST.js";import{c as g,h as y}from"./chunk-INNDBLZE.js";R();import{readFileSync as P,existsSync as _}from"fs";import{resolve as O}from"path";import{homedir as E}from"os";import{parse as w}from"yaml";y();var T=g("config");function S(e){return e.replace(/\$\{(\w+)}/g,(t,r)=>process.env[r]??"")}function h(e){return e.startsWith("~/")?O(E(),e.slice(2)):e}function u(e){if(typeof e=="string")return S(e);if(Array.isArray(e))return e.map(u);if(e!==null&&typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))t[r]=u(n);return t}return e}function m(e,t){let r={...e};for(let n of Object.keys(t)){let s=t[n],o=e[n];s!==null&&typeof s=="object"&&!Array.isArray(s)&&o!==null&&typeof o=="object"&&!Array.isArray(o)?r[n]=m(o,s):r[n]=s}return r}function v(e){return e.defaults.deniedReadPaths&&(e.defaults.deniedReadPaths=e.defaults.deniedReadPaths.map(h)),e.defaults.sensitivePaths&&!e.defaults.deniedReadPaths&&(T.warn("config.defaults.sensitivePaths is deprecated \u2014 use config.defaults.deniedReadPaths instead. Values have been migrated automatically."),e.defaults.deniedReadPaths=e.defaults.sensitivePaths.map(h)),e}function k(){let e={};for(let t of process.argv.slice(2)){let r=t.match(/^--([a-z-]+)=(.+)$/);r&&(e[r[1]]=r[2])}return e}function A(e){let t=process.env.ADAM_PORT;t&&(e.server.port=parseInt(t,10));let r=process.env.ANTHROPIC_MODEL;r&&(e.defaults.model=r);let n=process.env.ADAM_API_KEY;return n&&(e.server.apiKey=n),e}function C(e){let t=k();return t.port&&(e.server.port=parseInt(t.port,10)),t.host&&(e.server.host=t.host),t.timeout&&(e.defaults.timeout=parseInt(t.timeout,10)),t["api-key"]&&(e.server.apiKey=t["api-key"]),e}function D(e){let t=e??d,r={};if(_(t)){let f=P(t,"utf-8"),l=w(f);l&&(r=u(l))}let n=m(i,r),s=A(n),o=C(s);return v(o)}function I(){let e=JSON.parse(JSON.stringify(i)),t=A(e),r=C(t);return v(r)}function V(){let e={},t={ANTHROPIC_API_KEY:"anthropic.apiKey",ANTHROPIC_BASE_URL:"anthropic.baseUrl",ANTHROPIC_MODEL:"anthropic.model",ANTHROPIC_DEFAULT_OPUS_MODEL:"anthropic.defaultOpusModel",ANTHROPIC_DEFAULT_SONNET_MODEL:"anthropic.defaultSonnetModel",ANTHROPIC_DEFAULT_HAIKU_MODEL:"anthropic.defaultHaikuModel",ANTHROPIC_SMALL_FAST_MODEL:"anthropic.smallFastModel",ADAM_PORT:"server.port",ADAM_API_KEY:"server.apiKey"},r={};for(let[s,o]of Object.entries(t)){let a=process.env[s];if(a&&a.length>0)if(o==="server.port"){let f=parseInt(a,10);isNaN(f)||(e[o]=f)}else e[o]=a}let n=p();if(n)for(let[s,o]of Object.entries(n))s in t||s.startsWith("ANTHROPIC_")||s.startsWith("ADAM_")||(r[s]=o);return Object.keys(r).length>0&&(e["defaults.env"]=r),e}function j(){try{return c().defaults}catch{return i.defaults}}function W(){try{return c().chat??i.chat}catch{return i.chat}}export{D as a,I as b,V as c,j as d,W as e};
1
+ import{a as i}from"./chunk-UQJZU3R5.js";import{c as p}from"./chunk-7IFLU3CY.js";import{d as c}from"./chunk-GSMC3VUM.js";import{f as d,h as R}from"./chunk-WBAPIPST.js";import{c as g,h as y}from"./chunk-MRTJFYPR.js";R();import{readFileSync as P,existsSync as _}from"fs";import{resolve as O}from"path";import{homedir as E}from"os";import{parse as w}from"yaml";y();var T=g("config");function S(e){return e.replace(/\$\{(\w+)}/g,(t,r)=>process.env[r]??"")}function h(e){return e.startsWith("~/")?O(E(),e.slice(2)):e}function u(e){if(typeof e=="string")return S(e);if(Array.isArray(e))return e.map(u);if(e!==null&&typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))t[r]=u(n);return t}return e}function m(e,t){let r={...e};for(let n of Object.keys(t)){let s=t[n],o=e[n];s!==null&&typeof s=="object"&&!Array.isArray(s)&&o!==null&&typeof o=="object"&&!Array.isArray(o)?r[n]=m(o,s):r[n]=s}return r}function v(e){return e.defaults.deniedReadPaths&&(e.defaults.deniedReadPaths=e.defaults.deniedReadPaths.map(h)),e.defaults.sensitivePaths&&!e.defaults.deniedReadPaths&&(T.warn("config.defaults.sensitivePaths is deprecated \u2014 use config.defaults.deniedReadPaths instead. Values have been migrated automatically."),e.defaults.deniedReadPaths=e.defaults.sensitivePaths.map(h)),e}function k(){let e={};for(let t of process.argv.slice(2)){let r=t.match(/^--([a-z-]+)=(.+)$/);r&&(e[r[1]]=r[2])}return e}function A(e){let t=process.env.ADAM_PORT;t&&(e.server.port=parseInt(t,10));let r=process.env.ANTHROPIC_MODEL;r&&(e.defaults.model=r);let n=process.env.ADAM_API_KEY;return n&&(e.server.apiKey=n),e}function C(e){let t=k();return t.port&&(e.server.port=parseInt(t.port,10)),t.host&&(e.server.host=t.host),t.timeout&&(e.defaults.timeout=parseInt(t.timeout,10)),t["api-key"]&&(e.server.apiKey=t["api-key"]),e}function D(e){let t=e??d,r={};if(_(t)){let f=P(t,"utf-8"),l=w(f);l&&(r=u(l))}let n=m(i,r),s=A(n),o=C(s);return v(o)}function I(){let e=JSON.parse(JSON.stringify(i)),t=A(e),r=C(t);return v(r)}function V(){let e={},t={ANTHROPIC_API_KEY:"anthropic.apiKey",ANTHROPIC_BASE_URL:"anthropic.baseUrl",ANTHROPIC_MODEL:"anthropic.model",ANTHROPIC_DEFAULT_OPUS_MODEL:"anthropic.defaultOpusModel",ANTHROPIC_DEFAULT_SONNET_MODEL:"anthropic.defaultSonnetModel",ANTHROPIC_DEFAULT_HAIKU_MODEL:"anthropic.defaultHaikuModel",ANTHROPIC_SMALL_FAST_MODEL:"anthropic.smallFastModel",ADAM_PORT:"server.port",ADAM_API_KEY:"server.apiKey"},r={};for(let[s,o]of Object.entries(t)){let a=process.env[s];if(a&&a.length>0)if(o==="server.port"){let f=parseInt(a,10);isNaN(f)||(e[o]=f)}else e[o]=a}let n=p();if(n)for(let[s,o]of Object.entries(n))s in t||s.startsWith("ANTHROPIC_")||s.startsWith("ADAM_")||(r[s]=o);return Object.keys(r).length>0&&(e["defaults.env"]=r),e}function j(){try{return c().defaults}catch{return i.defaults}}function W(){try{return c().chat??i.chat}catch{return i.chat}}export{D as a,I as b,V as c,j as d,W as e};
@@ -0,0 +1 @@
1
+ import{d as w,h as S}from"./chunk-WBAPIPST.js";import{c as g,h as P}from"./chunk-MRTJFYPR.js";P();S();import{readFileSync as v,existsSync as E}from"fs";import{join as p}from"path";import{homedir as R}from"os";var T=g("ws"),x=p(R(),".adam"),f=p(x,"adam.port"),b=p(w,"adam.key");function d(){let n=process.env.ADAM_API_KEY;if(n)return n;if(E(b))return v(b,"utf-8").trim()||void 0}function m(){if(!E(f))return null;let n=parseInt(v(f,"utf-8").trim(),10);return isNaN(n)?null:n}function C(){let n=m();if(!n)throw new Error("Server not running. Run: adam server start");return`http://localhost:${n}`}var u=class extends Error{constructor(e,s){super(s);this.status=e;this.name="ApiError"}status};async function A(n,t={}){let s=`${C()}${n}`,r=d(),o=await fetch(s,{method:t.method||"GET",headers:{"Content-Type":"application/json",...r?{"x-api-key":r}:{},...t.headers},body:t.body?JSON.stringify(t.body):void 0});if(!o.ok){let a=await o.text().catch(()=>"Unknown error");throw new u(o.status,a)}return o.headers.get("content-type")?.includes("application/json")?o.json():o.text()}function D(){return A("/healthz")}var k=class{ws=null;callbacks=new Map;reconnectAttempts=0;reconnectTimer=null;url;constructor(t="/events"){let e=m();if(!e)throw new Error("Server not running. Run: adam server start");let s=d(),r=new URL(`ws://localhost:${e}${t}`);s&&r.searchParams.set("api_key",s),this.url=r.toString()}connect(){return new Promise((t,e)=>{try{this.ws=new WebSocket(this.url),this.ws.onopen=()=>{this.reconnectAttempts=0,t()},this.ws.onmessage=s=>{try{let r=JSON.parse(s.data),{type:o,data:c,...a}=r,i=this.callbacks.get(o);i&&i.forEach(l=>l(c??a))}catch(r){T.error({error:r},"Failed to parse WebSocket message")}},this.ws.onclose=()=>{this.scheduleReconnect()},this.ws.onerror=s=>{e(s)}}catch(s){e(s)}})}scheduleReconnect(){let t=[1e3,2e3,4e3,8e3,15e3],e=t[Math.min(this.reconnectAttempts,t.length-1)];this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>{this.connect().catch(()=>{})},e)}on(t,e){this.callbacks.has(t)||this.callbacks.set(t,new Set),this.callbacks.get(t).add(e)}off(t,e){this.callbacks.get(t)?.delete(e)}close(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.ws?.close()}isConnected(){return this.ws?.readyState===WebSocket.OPEN}},y=class{ws=null;callbacks=new Map;url;constructor(t){let e=m();if(!e)throw new Error("Server not running. Run: adam server start");let s=d(),r=new URL(`ws://localhost:${e}/tasks/${t}/stream`);s&&r.searchParams.set("api_key",s),this.url=r.toString()}connect(){return new Promise((t,e)=>{try{this.ws=new WebSocket(this.url),this.ws.onopen=()=>{t()},this.ws.onmessage=s=>{try{let r=JSON.parse(s.data),{type:o,data:c,...a}=r,i=this.callbacks.get(o);i&&i.forEach(h=>h(c??a));let l=this.callbacks.get("*");l&&l.forEach(h=>h(r))}catch(r){T.error({error:r},"Failed to parse task stream message")}},this.ws.onerror=s=>{e(s)},this.ws.onclose=()=>{}}catch(s){e(s)}})}on(t,e){this.callbacks.has(t)||this.callbacks.set(t,new Set),this.callbacks.get(t).add(e)}off(t,e){this.callbacks.get(t)?.delete(e)}close(){this.ws?.close()}isConnected(){return this.ws?.readyState===WebSocket.OPEN}};export{d as a,A as b,D as c,k as d,y as e};
@@ -0,0 +1,49 @@
1
+ import{e as J}from"./chunk-ULTK7RD6.js";import{i as x,j as v,q as b}from"./chunk-6KF7OO2B.js";import{b as y}from"./chunk-K4C43YDD.js";import{a as u}from"./chunk-L7JP7DUO.js";import{p as C}from"./chunk-DVN3BFPP.js";import{c as _,d as l,f as g,h as A}from"./chunk-5XOTPEAK.js";import{d as k}from"./chunk-PG6LMSX6.js";import{o as I,r as W}from"./chunk-HQRUJQN7.js";import{c as p,h as T}from"./chunk-MRTJFYPR.js";T();W();import{v4 as m}from"uuid";import{CronExpressionParser as S}from"cron-parser";T();import{v4 as D}from"uuid";var d=p("scheduler"),R=new J;async function O(n,t={}){let e=t.executionId??D();if(d.info({templateName:n.name,executionId:e,trigger:t.triggerContext},"Dispatching template"),n.goalIds&&n.goalIds.length>0){for(let r of n.goalIds){let o=v(r);if(!o){d.warn({goalId:r,templateId:n.id},"Goal reference not found, skipping");continue}let c=D();x({id:c,name:o.name,description:o.description,roleId:o.roleId,metricType:o.metricType,targetValue:o.targetValue,currentValue:0,deadline:o.deadline,budgetUsd:o.budgetUsd,status:"active",createdAt:Date.now(),sourceSessionId:n.sourceSessionId,deliverTo:n.deliverTo,reportTo:n.reportTo});let a=await b({prompt:`Decompose and execute goal: ${o.name}. ${o.description??""}`,roleId:n.rolePreference??o.roleId,config:{...k()},deliverTo:n.deliverTo,reportTo:n.reportTo,sourceSessionId:n.sourceSessionId,parentId:c,templateId:n.id});if(!a.ok){d.error({templateId:n.id,sourceGoalId:r,newGoalId:c,code:a.code,reason:a.reason},"Decomposition task admission failed");continue}d.info({templateId:n.id,sourceGoalId:r,newGoalId:c,taskId:a.taskId},"Goal reference triggered, dispatched decomposition task")}return}let s=await R.execute(n,e,{eventId:t.triggerContext?.eventId});d.info({templateName:n.name,executionId:e,status:s.status,steps:s.stepResults.size},"Workflow execution finished")}var i=p("scheduler"),f="ai-hourly-digest";function E(){if(l(f)){i.debug({templateId:f},"Built-in template already exists");return}let t={id:f,name:"AI Hourly Digest",description:"\u6BCF\u5C0F\u65F6\u641C\u7D22 AI \u524D\u6CBF\u6587\u7AE0\uFF0C\u603B\u7ED3\u540E\u4FDD\u5B58\u5230 Omnifocus",trigger:{type:"cron",cron:"0 * * * *"},enabled:!0,steps:[{id:"search_ai_news",autoSelectRole:!0,requirements:{},prompt:`\u641C\u7D22\u8FC7\u53BB 24 \u5C0F\u65F6\u5185\u5173\u4E8E AI/\u4EBA\u5DE5\u667A\u80FD\u7684\u6700\u65B0\u524D\u6CBF\u6587\u7AE0\u3002
2
+
3
+ \u641C\u7D22\u6765\u6E90:
4
+ 1. Hacker News AI \u677F\u5757 (https://news.ycombinator.com/front?day=1)
5
+ 2. ArXiv cs.AI \u6700\u65B0\u8BBA\u6587 (https://arxiv.org/list/cs.AI/recent)
6
+ 3. Reddit r/MachineLearning \u70ED\u95E8\u5E16\u5B50
7
+
8
+ \u627E\u51FA\u4E00\u7BC7\u6700\u6709\u4EF7\u503C\u3001\u6700\u6709\u6280\u672F\u6DF1\u5EA6\u7684\u6587\u7AE0\u3002
9
+
10
+ \u8F93\u51FA\u683C\u5F0F:
11
+ - \u6807\u9898\uFF1A[\u6587\u7AE0\u6807\u9898]
12
+ - \u6765\u6E90\uFF1A[\u7F51\u7AD9/\u5E73\u53F0\u540D\u79F0]
13
+ - \u94FE\u63A5\uFF1A[\u5B8C\u6574 URL]
14
+ - \u6838\u5FC3\u4EF7\u503C\uFF1A[1-2 \u53E5\u8BDD\u8BF4\u660E\u4E3A\u4EC0\u4E48\u8FD9\u7BC7\u6587\u7AE0\u503C\u5F97\u770B]`},{id:"summarize_article",dependsOn:["search_ai_news"],autoSelectRole:!0,requirements:{},prompt:`\u9605\u8BFB\u5E76\u603B\u7ED3\u8FD9\u7BC7\u6587\u7AE0\u3002
15
+
16
+ \u6587\u7AE0\u4FE1\u606F:
17
+ {{search_ai_news.result}}
18
+
19
+ \u8BF7:
20
+ 1. \u7528 WebFetch \u83B7\u53D6\u6587\u7AE0\u5B8C\u6574\u5185\u5BB9
21
+ 2. \u63D0\u53D6\u6838\u5FC3\u89C2\u70B9\u548C\u6280\u672F\u7EC6\u8282
22
+ 3. \u7528\u4E2D\u6587\u5199\u51FA 300-500 \u5B57\u7684\u603B\u7ED3
23
+
24
+ \u603B\u7ED3\u7ED3\u6784:
25
+ ## \u6838\u5FC3\u53D1\u73B0
26
+ [\u6587\u7AE0\u6700\u91CD\u8981\u7684\u53D1\u73B0/\u521B\u65B0\u70B9]
27
+
28
+ ## \u6280\u672F\u7EC6\u8282
29
+ [\u5173\u952E\u7684\u6280\u672F\u65B9\u6CD5/\u5B9E\u73B0\u7EC6\u8282]
30
+
31
+ ## \u5F71\u54CD/\u610F\u4E49
32
+ [\u8FD9\u9879\u5DE5\u4F5C\u7684\u610F\u4E49\u6216\u5BF9\u884C\u4E1A\u7684\u5F71\u54CD]
33
+
34
+ ## \u539F\u6587\u94FE\u63A5
35
+ [\u6587\u7AE0 URL]`},{id:"save_to_omnifocus",dependsOn:["summarize_article"],autoSelectRole:!0,requirements:{},prompt:`\u5C06\u6587\u7AE0\u603B\u7ED3\u4FDD\u5B58\u5230 Omnifocus\u3002
36
+
37
+ \u603B\u7ED3\u5185\u5BB9:
38
+ {{summarize_article.result}}
39
+
40
+ \u63D0\u53D6\u6587\u7AE0\u6807\u9898\u548C\u5B8C\u6574\u603B\u7ED3\uFF0C\u7136\u540E\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u6DFB\u52A0\u5230 Omnifocus Inbox\uFF1A
41
+
42
+ osascript /Users/norvyn/Code/Projects/Adam/scripts/add-to-omnifocus.applescript "[\u6587\u7AE0\u6807\u9898] AI \u524D\u6CBF\u901F\u9012" "[\u5B8C\u6574\u603B\u7ED3\u5185\u5BB9]"
43
+
44
+ \u6CE8\u610F\uFF1A
45
+ - \u5C06 [\u6587\u7AE0\u6807\u9898] \u66FF\u6362\u4E3A\u5B9E\u9645\u6807\u9898
46
+ - \u5C06 [\u5B8C\u6574\u603B\u7ED3\u5185\u5BB9] \u66FF\u6362\u4E3A\u5B8C\u6574\u7684\u603B\u7ED3\u6587\u672C\uFF08\u5305\u542B\u6838\u5FC3\u53D1\u73B0\u3001\u6280\u672F\u7EC6\u8282\u3001\u5F71\u54CD/\u610F\u4E49\u548C\u539F\u6587\u94FE\u63A5\uFF09
47
+ - \u603B\u7ED3\u5185\u5BB9\u4F7F\u7528\u6362\u884C\u7B26\u5206\u9694\u5404\u90E8\u5206
48
+
49
+ \u5B8C\u6210\u540E\u8F93\u51FA\uFF1A\u5DF2\u4FDD\u5B58\u5230 Omnifocus\uFF1A[\u4EFB\u52A1\u6807\u9898]`}],config:{timeout:300},tags:["ai","digest","hourly","automation"],createdAt:Date.now()};_(t),i.info({templateId:f,cron:"0 * * * *"},"Registered built-in AI Hourly Digest template")}var P=class{cronJobs=new Map;started=!1;taskCompletionHandler=null;workflowCompletionHandler=null;async start(){if(this.started)return;this.started=!0,E();let t=g(!0),e=0;for(let r of t)r.trigger.type==="cron"&&r.trigger.cron&&(this.scheduleCronJob(r),e++);let s=0;for(let r of t)r.trigger.type==="once"&&r.trigger.runAt&&(this.scheduleOnceJob(r.id),s++);this.taskCompletionHandler=r=>{r.newStatus==="completed"&&this.checkTemplateCompleteTriggers(r.taskId).catch(o=>{i.error({taskId:r.taskId,error:o},"Template-complete trigger check failed")})},u.on("task_status_change",this.taskCompletionHandler),this.workflowCompletionHandler=r=>{(r.status==="completed"||r.status==="partial")&&this.checkWorkflowCompleteTriggers(r.templateId).catch(o=>{i.error({templateId:r.templateId,error:o},"Workflow-complete trigger check failed")})},u.on("workflow_status_change",this.workflowCompletionHandler),this.cronJobs.set("memory-cleanup",setInterval(()=>{this.runMemoryCleanup()},36e5)),i.info({cronCount:e,onceCount:s},"Bree engine started with cron jobs + memory cleanup")}runMemoryCleanup(){try{let t=I(void 0,1e3,0),e=0;for(let s of t)e+=C(s.id);e>0&&i.info({totalCleaned:e},"Memory cleanup completed")}catch(t){i.warn({error:t},"Memory cleanup failed")}}async stop(){for(let[,t]of this.cronJobs)clearTimeout(t),clearInterval(t);this.cronJobs.clear(),this.taskCompletionHandler&&(u.off("task_status_change",this.taskCompletionHandler),this.taskCompletionHandler=null),this.workflowCompletionHandler&&(u.off("workflow_status_change",this.workflowCompletionHandler),this.workflowCompletionHandler=null),this.started=!1,i.info("Bree engine stopped")}scheduleCronJob(t){let e=`template-${t.id}`;this.cronJobs.has(e)&&(clearTimeout(this.cronJobs.get(e)),this.cronJobs.delete(e));let s;try{s=S.parse(t.trigger.cron)}catch{i.warn({templateId:t.id,cron:t.trigger.cron},"Invalid cron expression");return}let r=()=>{let h=s.next().getTime()-Date.now();return Math.max(h,1e3)},o=()=>{this.executeCronTrigger(t.id).catch(h=>{i.error({templateId:t.id,error:h},"Cron trigger failed")});let w=setTimeout(o,r());this.cronJobs.set(e,w)},c=r(),a=setTimeout(o,c);this.cronJobs.set(e,a),i.debug({jobName:e,nextRun:new Date(Date.now()+c).toISOString()},"Scheduled cron job")}async executeCronTrigger(t){let e=l(t);!e||!e.enabled||(i.info({templateName:e.name},"Cron triggered"),await this.executeWorkflow(e,m()))}async scheduleJob(t){let e=l(t);e&&e.trigger.type==="cron"&&e.trigger.cron&&this.scheduleCronJob(e)}async unscheduleJob(t){let e=`template-${t}`,s=this.cronJobs.get(e);s&&(clearTimeout(s),this.cronJobs.delete(e))}async runNow(t){let e=l(t);if(!e)throw new Error(`Template ${t} not found`);let s=m();return this.executeWorkflow(e,s).catch(r=>{i.error({templateId:t,error:r},"Workflow execution failed")}),s}async checkTemplateCompleteTriggers(t){let e=y(t);if(!e||!e.templateId)return;let r=g(!0).filter(o=>o.trigger.type!=="template_complete"||!o.trigger.event?!1:o.trigger.event===`template_complete:${e.templateId}`);for(let o of r)i.info({templateName:o.name,sourceTemplateId:e.templateId},"Template-complete trigger matched"),await this.executeWorkflow(o,m())}async executeWorkflow(t,e){await O(t,{executionId:e,triggerContext:{source:"bree"}})}async checkWorkflowCompleteTriggers(t){let s=g(!0).filter(r=>r.trigger.type!=="workflow_complete"||!r.trigger.event?!1:r.trigger.event===`workflow_complete:${t}`);for(let r of s)i.info({templateName:r.name,sourceTemplateId:t},"Workflow-complete trigger matched"),await this.executeWorkflow(r,m())}scheduleOnceJob(t){let e=l(t);if(!e||!e.enabled||e.trigger.type!=="once")return;let r=(e.trigger.runAt?new Date(e.trigger.runAt).getTime():0)-Date.now();if(r<=0){i.info({templateId:t,runAt:e.trigger.runAt},"Once-shot template past due, executing immediately"),this.executeOnceTrigger(t).catch(a=>{i.error({templateId:t,error:a},"Once trigger execution failed")});return}let o=`template-${t}`;this.cronJobs.has(o)&&clearTimeout(this.cronJobs.get(o));let c=setTimeout(()=>{this.cronJobs.delete(o),this.executeOnceTrigger(t).catch(a=>{i.error({templateId:t,error:a},"Once trigger execution failed")})},r);this.cronJobs.set(o,c),i.info({templateId:t,runAt:e.trigger.runAt,delayMs:r},"Scheduled once-shot job")}async executeOnceTrigger(t){let e=l(t);!e||!e.enabled||(i.info({templateName:e.name},"Once-shot triggered"),await this.executeWorkflow(e,m()),A(t),i.info({templateId:t},"Once-shot template auto-disabled after execution"))}},H=null;function ee(){return H}function te(n){H=n}export{O as a,P as b,ee as c,te as d};
@@ -1,3 +1,3 @@
1
- import{b as C}from"./chunk-23VZKIB6.js";import{a as p}from"./chunk-L7JP7DUO.js";import{b as D,c as f,d as w}from"./chunk-QVKI7H7W.js";import{c as M,h as U}from"./chunk-INNDBLZE.js";function O(s,c,n){switch(c){case"wechat":return $(s);case"telegram":return s;case"slack":return P(s);case"webhook":return JSON.stringify({result:s,taskId:n,timestamp:new Date().toISOString()});default:return $(s)}}function $(s){return s.replace(/^#{1,6}\s+/gm,"").replace(/\*\*(.+?)\*\*/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/_(.+?)_/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/```[\s\S]*?```/g,c=>c.replace(/```\w*\n?/g,"").trim()).replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\n{3,}/g,`
1
+ import{b as C}from"./chunk-GSFLLRS7.js";import{a as p}from"./chunk-L7JP7DUO.js";import{b as D,c as f,d as w}from"./chunk-RZ7LCZVK.js";import{c as M,h as U}from"./chunk-MRTJFYPR.js";function O(s,c,n){switch(c){case"wechat":return $(s);case"telegram":return s;case"slack":return P(s);case"webhook":return JSON.stringify({result:s,taskId:n,timestamp:new Date().toISOString()});default:return $(s)}}function $(s){return s.replace(/^#{1,6}\s+/gm,"").replace(/\*\*(.+?)\*\*/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/_(.+?)_/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/```[\s\S]*?```/g,c=>c.replace(/```\w*\n?/g,"").trim()).replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\n{3,}/g,`
2
2
 
3
- `).trim()}function P(s){return s.replace(/\*\*(.+?)\*\*/g,"*$1*").replace(/\[([^\]]+)\]\(([^)]+)\)/g,"<$2|$1>")}U();import{v4 as T}from"uuid";var x=M("adam"),v=class{_dedupCache=new Map;_rateLimitWindows=new Map;_recentlySentIds=new Set;isRecentlySent(c){return this._recentlySentIds.has(c)}async send(c){let{taskId:n,channelId:a,chatId:m,content:y,messageType:d,platform:E,webhookUrl:h,replyMarkup:I,mediaUrl:S,mediaType:b}=c,R=d!=="reply"&&!!n,r;if(R){r=`${n}:${a??"none"}:${m??"none"}:${d}`;let t=this._dedupCache.get(r);if(t&&Date.now()-t.timestamp<300*1e3)return x.debug({dedupKey:r},"Dedup hit, returning cached log entry"),{success:!0,logEntryId:t.logEntryId}}if(a){let t=Date.now(),i=6e4,o=this._rateLimitWindows.get(a);o||(o=[],this._rateLimitWindows.set(a,o));let u=t-i;for(;o.length>0&&o[0]<u;)o.shift();if(o.length>=60){let l=T();return x.warn({channelId:a,count:o.length},"Rate limited, not sending"),{success:!1,logEntryId:l,error:"rate_limited"}}o.push(t)}let L=E??(a?C(a)?.platform:void 0)??"unknown",k=h?y:O(y,L,n),e=T(),g={id:e,ruleId:void 0,taskId:n??void 0,status:"pending",target:a&&m?{type:"channel",channelId:a,chatId:m}:h?{type:"webhook",webhookUrl:h}:{type:"channel",channelId:a??"",chatId:m??""},content:k,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+1440*60*1e3,source:"direct",messageType:d};D(g),r&&this._dedupCache.set(r,{logEntryId:e,timestamp:Date.now()});try{if(h){let t=await fetch(h,{method:"POST",body:JSON.stringify({result:y,taskId:n,timestamp:new Date().toISOString()}),signal:AbortSignal.timeout(1e4)});if(t.ok)return w(e),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"delivered",messageType:d}),{success:!0,logEntryId:e};{let i=`Webhook returned ${t.status}`;return f(e,"failed",i),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:i,messageType:d}),{success:!1,logEntryId:e,error:i}}}else if(a&&m){let{getChannelManager:t}=await import("./channels-JCMPPQED.js"),i=t();if(!i){let l="ChannelManager not available";return f(e,"failed",l),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:l,messageType:d}),{success:!1,logEntryId:e,error:l}}let o={content:k,...I?{replyMarkup:I}:{},...S?{mediaUrl:S}:{},...b?{mediaType:b}:{}},u=await i.sendMessage(a,m,o);if(u===null){let l="Channel adapter send failed (returned null)";return f(e,"failed",l),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:l,messageType:d}),{success:!1,logEntryId:e,error:l}}return u&&(this._recentlySentIds.add(u),setTimeout(()=>this._recentlySentIds.delete(u),300*1e3)),w(e),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"delivered",messageType:d}),{success:!0,messageId:u??void 0,logEntryId:e}}else{let t="No channelId/chatId or webhookUrl provided";return f(e,"failed",t),r&&this._dedupCache.delete(r),{success:!1,logEntryId:e,error:t}}}catch(t){let i=t instanceof Error?t.message:String(t);return f(e,"failed",i),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:i,messageType:d}),{success:!1,logEntryId:e,error:i}}}},_=null;function W(){return _||(_=new v),_}function q(s){return W().isRecentlySent(s)}export{v as a,W as b,q as c};
3
+ `).trim()}function P(s){return s.replace(/\*\*(.+?)\*\*/g,"*$1*").replace(/\[([^\]]+)\]\(([^)]+)\)/g,"<$2|$1>")}U();import{v4 as T}from"uuid";var x=M("adam"),v=class{_dedupCache=new Map;_rateLimitWindows=new Map;_recentlySentIds=new Set;isRecentlySent(c){return this._recentlySentIds.has(c)}async send(c){let{taskId:n,channelId:a,chatId:m,content:y,messageType:d,platform:E,webhookUrl:h,replyMarkup:I,mediaUrl:S,mediaType:b}=c,R=d!=="reply"&&!!n,r;if(R){r=`${n}:${a??"none"}:${m??"none"}:${d}`;let t=this._dedupCache.get(r);if(t&&Date.now()-t.timestamp<300*1e3)return x.debug({dedupKey:r},"Dedup hit, returning cached log entry"),{success:!0,logEntryId:t.logEntryId}}if(a){let t=Date.now(),i=6e4,o=this._rateLimitWindows.get(a);o||(o=[],this._rateLimitWindows.set(a,o));let u=t-i;for(;o.length>0&&o[0]<u;)o.shift();if(o.length>=60){let l=T();return x.warn({channelId:a,count:o.length},"Rate limited, not sending"),{success:!1,logEntryId:l,error:"rate_limited"}}o.push(t)}let L=E??(a?C(a)?.platform:void 0)??"unknown",k=h?y:O(y,L,n),e=T(),g={id:e,ruleId:void 0,taskId:n??void 0,status:"pending",target:a&&m?{type:"channel",channelId:a,chatId:m}:h?{type:"webhook",webhookUrl:h}:{type:"channel",channelId:a??"",chatId:m??""},content:k,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+1440*60*1e3,source:"direct",messageType:d};D(g),r&&this._dedupCache.set(r,{logEntryId:e,timestamp:Date.now()});try{if(h){let t=await fetch(h,{method:"POST",body:JSON.stringify({result:y,taskId:n,timestamp:new Date().toISOString()}),signal:AbortSignal.timeout(1e4)});if(t.ok)return w(e),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"delivered",messageType:d}),{success:!0,logEntryId:e};{let i=`Webhook returned ${t.status}`;return f(e,"failed",i),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:i,messageType:d}),{success:!1,logEntryId:e,error:i}}}else if(a&&m){let{getChannelManager:t}=await import("./channels-SITUUC4J.js"),i=t();if(!i){let l="ChannelManager not available";return f(e,"failed",l),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:l,messageType:d}),{success:!1,logEntryId:e,error:l}}let o={content:k,...I?{replyMarkup:I}:{},...S?{mediaUrl:S}:{},...b?{mediaType:b}:{}},u=await i.sendMessage(a,m,o);if(u===null){let l="Channel adapter send failed (returned null)";return f(e,"failed",l),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:l,messageType:d}),{success:!1,logEntryId:e,error:l}}return u&&(this._recentlySentIds.add(u),setTimeout(()=>this._recentlySentIds.delete(u),300*1e3)),w(e),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"delivered",messageType:d}),{success:!0,messageId:u??void 0,logEntryId:e}}else{let t="No channelId/chatId or webhookUrl provided";return f(e,"failed",t),r&&this._dedupCache.delete(r),{success:!1,logEntryId:e,error:t}}}catch(t){let i=t instanceof Error?t.message:String(t);return f(e,"failed",i),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:i,messageType:d}),{success:!1,logEntryId:e,error:i}}}},_=null;function W(){return _||(_=new v),_}function q(s){return W().isRecentlySent(s)}export{v as a,W as b,q as c};
@@ -1,4 +1,4 @@
1
- import{b as s,d as o}from"./chunk-JAS3TUZX.js";o();function i(e){return{id:e.id,ruleId:e.rule_id??void 0,taskId:e.task_id??void 0,status:e.status,target:JSON.parse(e.target),content:e.content,attempts:e.attempts,error:e.error??void 0,createdAt:e.created_at,deliveredAt:e.delivered_at??void 0,expiresAt:e.expires_at,source:e.source,messageType:e.message_type??void 0}}var u=1440*60*1e3;function p(e){s().prepare(`
1
+ import{b as s,d as o}from"./chunk-5EPG2US5.js";o();function i(e){return{id:e.id,ruleId:e.rule_id??void 0,taskId:e.task_id??void 0,status:e.status,target:JSON.parse(e.target),content:e.content,attempts:e.attempts,error:e.error??void 0,createdAt:e.created_at,deliveredAt:e.delivered_at??void 0,expiresAt:e.expires_at,source:e.source,messageType:e.message_type??void 0}}var u=1440*60*1e3;function p(e){s().prepare(`
2
2
  INSERT INTO delivery_log (id, rule_id, task_id, status, target, content,
3
3
  attempts, error, created_at, delivered_at, expires_at, source, message_type)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -1 +1 @@
1
- import{c as S,h as x}from"./chunk-INNDBLZE.js";x();import*as s from"fs";import*as l from"path";import{homedir as F}from"os";var v=S("embedding"),M=null,A=!1;async function L(){if(A)throw new Error("onnxruntime-node native binding not available. Embedding disabled.");if(!M)try{M=await import("./dist-CDWBOTZS.js")}catch(e){throw A=!0,v.warn({error:e.message},"onnxruntime-node not available"),new Error("onnxruntime-node native binding not available. Embedding disabled.")}return M}var P=l.join(F(),".adam","models"),N="all-MiniLM-L6-v2",T="model.onnx",B="tokenizer.json",O="https://huggingface.co/Xenova/all-MiniLM-L6-v2/resolve/main/onnx/model_quantized.onnx",j="https://huggingface.co/Xenova/all-MiniLM-L6-v2/resolve/main/tokenizer.json",R=384,y=null,k=null;function z(){let e=l.join(P,N);return s.existsSync(e)||s.mkdirSync(e,{recursive:!0}),e}async function _(e,t){if(s.existsSync(t))return;v.info({file:l.basename(t)},"Downloading model file");let f=await fetch(e);if(!f.ok)throw new Error(`Failed to download ${e}: ${f.status}`);let i=Buffer.from(await f.arrayBuffer());s.writeFileSync(t,i),v.info({file:l.basename(t),sizeMb:(i.length/1024/1024).toFixed(1)},"Model file downloaded")}async function U(){let e=z(),t=l.join(e,T),f=l.join(e,B);return await _(O,t),await _(j,f),t}function $(){if(k)return k;let e=l.join(z(),B);if(!s.existsSync(e))throw new Error("Tokenizer not found. Run generateEmbedding first to download.");return k=JSON.parse(s.readFileSync(e,"utf-8")),k}function q(e,t=128){let i=$().model.vocab,w=i["[CLS]"]??101,I=i["[SEP]"]??102,u=i["[UNK]"]??100,E=i["[PAD]"]??0,p=e.toLowerCase().replace(/[^\w\s\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff]/g," ").split(/\s+/).filter(Boolean),r=[w];for(let o of p){if(r.length>=t-1)break;if(i[o]!==void 0){r.push(i[o]);continue}let d=!1,n=o,m=!0;for(;n.length>0&&r.length<t-1;){let D=!1;for(let g=n.length;g>0;g--){let b=m?n.slice(0,g):`##${n.slice(0,g)}`;if(i[b]!==void 0){r.push(i[b]),n=n.slice(g),m=!1,D=!0,d=!0;break}}if(!D)if(n.length>=2){let g=n.slice(0,2),b=i[g]??i[`##${g}`]??u;r.push(b),n=n.slice(2),d=!0}else r.push(u),n=""}d||r.push(u)}r.push(I);let h=new BigInt64Array(t),a=new BigInt64Array(t),c=new BigInt64Array(t);for(let o=0;o<t;o++)o<r.length?(h[o]=BigInt(r[o]),a[o]=1n):(h[o]=BigInt(E),a[o]=0n),c[o]=0n;return{inputIds:h,attentionMask:a,tokenTypeIds:c}}async function C(){if(y)return y;let e=await L(),t=await U();return y=await e.InferenceSession.create(t,{executionProviders:["cpu"]}),y}async function Z(e){let t=await L(),f=await C(),{inputIds:i,attentionMask:w,tokenTypeIds:I}=q(e),u=i.length,E={input_ids:new t.Tensor("int64",i,[1,u]),attention_mask:new t.Tensor("int64",w,[1,u]),token_type_ids:new t.Tensor("int64",I,[1,u])},p=await f.run(E),h=(p.last_hidden_state??p[Object.keys(p)[0]]).data,a=R,c=new Float32Array(a),o=0;for(let n=0;n<u;n++)if(w[n]===1n){o++;for(let m=0;m<a;m++)c[m]+=h[n*a+m]}if(o>0)for(let n=0;n<a;n++)c[n]/=o;let d=0;for(let n=0;n<a;n++)d+=c[n]*c[n];if(d=Math.sqrt(d),d>0)for(let n=0;n<a;n++)c[n]/=d;return c}function G(){let e=l.join(z(),T);return s.existsSync(e)}export{Z as a,G as b};
1
+ import{c as S,h as x}from"./chunk-MRTJFYPR.js";x();import*as s from"fs";import*as l from"path";import{homedir as F}from"os";var v=S("embedding"),M=null,A=!1;async function L(){if(A)throw new Error("onnxruntime-node native binding not available. Embedding disabled.");if(!M)try{M=await import("./dist-CDWBOTZS.js")}catch(e){throw A=!0,v.warn({error:e.message},"onnxruntime-node not available"),new Error("onnxruntime-node native binding not available. Embedding disabled.")}return M}var P=l.join(F(),".adam","models"),N="all-MiniLM-L6-v2",T="model.onnx",B="tokenizer.json",O="https://huggingface.co/Xenova/all-MiniLM-L6-v2/resolve/main/onnx/model_quantized.onnx",j="https://huggingface.co/Xenova/all-MiniLM-L6-v2/resolve/main/tokenizer.json",R=384,y=null,k=null;function z(){let e=l.join(P,N);return s.existsSync(e)||s.mkdirSync(e,{recursive:!0}),e}async function _(e,t){if(s.existsSync(t))return;v.info({file:l.basename(t)},"Downloading model file");let f=await fetch(e);if(!f.ok)throw new Error(`Failed to download ${e}: ${f.status}`);let i=Buffer.from(await f.arrayBuffer());s.writeFileSync(t,i),v.info({file:l.basename(t),sizeMb:(i.length/1024/1024).toFixed(1)},"Model file downloaded")}async function U(){let e=z(),t=l.join(e,T),f=l.join(e,B);return await _(O,t),await _(j,f),t}function $(){if(k)return k;let e=l.join(z(),B);if(!s.existsSync(e))throw new Error("Tokenizer not found. Run generateEmbedding first to download.");return k=JSON.parse(s.readFileSync(e,"utf-8")),k}function q(e,t=128){let i=$().model.vocab,w=i["[CLS]"]??101,I=i["[SEP]"]??102,u=i["[UNK]"]??100,E=i["[PAD]"]??0,p=e.toLowerCase().replace(/[^\w\s\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff]/g," ").split(/\s+/).filter(Boolean),r=[w];for(let o of p){if(r.length>=t-1)break;if(i[o]!==void 0){r.push(i[o]);continue}let d=!1,n=o,m=!0;for(;n.length>0&&r.length<t-1;){let D=!1;for(let g=n.length;g>0;g--){let b=m?n.slice(0,g):`##${n.slice(0,g)}`;if(i[b]!==void 0){r.push(i[b]),n=n.slice(g),m=!1,D=!0,d=!0;break}}if(!D)if(n.length>=2){let g=n.slice(0,2),b=i[g]??i[`##${g}`]??u;r.push(b),n=n.slice(2),d=!0}else r.push(u),n=""}d||r.push(u)}r.push(I);let h=new BigInt64Array(t),a=new BigInt64Array(t),c=new BigInt64Array(t);for(let o=0;o<t;o++)o<r.length?(h[o]=BigInt(r[o]),a[o]=1n):(h[o]=BigInt(E),a[o]=0n),c[o]=0n;return{inputIds:h,attentionMask:a,tokenTypeIds:c}}async function C(){if(y)return y;let e=await L(),t=await U();return y=await e.InferenceSession.create(t,{executionProviders:["cpu"]}),y}async function Z(e){let t=await L(),f=await C(),{inputIds:i,attentionMask:w,tokenTypeIds:I}=q(e),u=i.length,E={input_ids:new t.Tensor("int64",i,[1,u]),attention_mask:new t.Tensor("int64",w,[1,u]),token_type_ids:new t.Tensor("int64",I,[1,u])},p=await f.run(E),h=(p.last_hidden_state??p[Object.keys(p)[0]]).data,a=R,c=new Float32Array(a),o=0;for(let n=0;n<u;n++)if(w[n]===1n){o++;for(let m=0;m<a;m++)c[m]+=h[n*a+m]}if(o>0)for(let n=0;n<a;n++)c[n]/=o;let d=0;for(let n=0;n<a;n++)d+=c[n]*c[n];if(d=Math.sqrt(d),d>0)for(let n=0;n<a;n++)c[n]/=d;return c}function G(){let e=l.join(z(),T);return s.existsSync(e)}export{Z as a,G as b};