adam-agent-server 1.18.0 → 1.19.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{App-SIQUVFJY.js → App-522DTURQ.js} +10 -10
- package/dist/approval-handler-GXIVBJ4Z.js +1 -0
- package/dist/artifacts-DDHH47IE.js +1 -0
- package/dist/audit-diagnostics-HLHS3MHM.js +1 -0
- package/dist/audit-manager-PDMOR2MX.js +1 -0
- package/dist/bree-engine-6UKRI4UN.js +1 -0
- package/dist/{channels-2TWTBE6Y.js → channels-3J6U6GYH.js} +1 -1
- package/dist/channels-YOBMSBWV.js +1 -0
- package/dist/chat-tool-calls-5Z53IXRF.js +1 -0
- package/dist/{chunk-2CE2WUUZ.js → chunk-2BLSA25Q.js} +1 -1
- package/dist/{chunk-2A2TXYT3.js → chunk-3JTHJ3FZ.js} +3 -3
- package/dist/{chunk-2JIQT2CI.js → chunk-4NRIKWSD.js} +1 -1
- package/dist/{chunk-HRPMRWHD.js → chunk-5ZL6RHPE.js} +1 -1
- package/dist/{chunk-BE653A45.js → chunk-6GVYOHD5.js} +5 -5
- package/dist/{chunk-NSUXJ2VA.js → chunk-6NIWU43Z.js} +1 -1
- package/dist/{chunk-QYI44EP6.js → chunk-6SBLFYCU.js} +1 -1
- package/dist/{chunk-V2MMQ3SH.js → chunk-AKQ3AFVI.js} +1 -1
- package/dist/{chunk-HL373H4P.js → chunk-AMJJ2WGU.js} +1 -1
- package/dist/chunk-CQDOIHPV.js +1 -0
- package/dist/{chunk-XAPJJAJQ.js → chunk-EXB2JIBR.js} +1 -1
- package/dist/{chunk-VWX2B6OM.js → chunk-G5I76LX2.js} +1 -1
- package/dist/{chunk-LKGYQJMS.js → chunk-GYOZGA7G.js} +1 -1
- package/dist/{chunk-NUOTFUNF.js → chunk-ISTUK7Q6.js} +1 -1
- package/dist/chunk-ITVCPC7G.js +1 -0
- package/dist/{chunk-NXGR3PRY.js → chunk-J2VSAXVU.js} +1 -1
- package/dist/chunk-J4JO7O3T.js +182 -0
- package/dist/{chunk-5G64P4KE.js → chunk-JRRNGKDK.js} +1 -1
- package/dist/{chunk-Z2APBKIT.js → chunk-KO6UB6VW.js} +1 -1
- package/dist/chunk-LE5YRP37.js +14 -0
- package/dist/chunk-N4BV2WAU.js +1 -0
- package/dist/{chunk-JZBXLN7M.js → chunk-NUTGYMDP.js} +1 -1
- package/dist/{chunk-OBD4245G.js → chunk-NX3CIEZA.js} +1 -1
- package/dist/{chunk-ZQN6JZIJ.js → chunk-P2EDMFVO.js} +1 -1
- package/dist/{chunk-JYZTIE2J.js → chunk-PU2T7HBY.js} +1 -1
- package/dist/{chunk-UCUELFCS.js → chunk-PZH5NKUL.js} +11 -11
- package/dist/{chunk-SKHMWKJT.js → chunk-QF3B4OWI.js} +1 -1
- package/dist/{chunk-KS24764D.js → chunk-QQWUWGSK.js} +2 -2
- package/dist/{chunk-O6L4UVLV.js → chunk-QX65LEYA.js} +1 -1
- package/dist/chunk-R3MSLP6P.js +32 -0
- package/dist/{chunk-LCD5DVS6.js → chunk-SDHMBWVC.js} +1 -1
- package/dist/{chunk-SGLZAIVL.js → chunk-SONOE4ZJ.js} +1 -1
- package/dist/{chunk-47HJPIUA.js → chunk-T7EKW3B7.js} +1 -1
- package/dist/{chunk-IEBAOZED.js → chunk-VVPB3TD4.js} +1 -1
- package/dist/{chunk-4JHACUZY.js → chunk-X3PJNX2R.js} +1 -1
- package/dist/{chunk-6WQFYV3N.js → chunk-XEXSXMWK.js} +1 -1
- package/dist/{chunk-BMCNQGUH.js → chunk-YGR5ZTGT.js} +1 -1
- package/dist/{chunk-JROGEBP5.js → chunk-YGZQMZTA.js} +1 -1
- package/dist/{chunk-TA5PFK5C.js → chunk-YI2QQTZE.js} +1 -1
- package/dist/chunk-ZARKPBI2.js +143 -0
- package/dist/{chunk-WY5BOCQP.js → chunk-ZEGZ2I35.js} +16 -16
- package/dist/cli.js +2 -2
- package/dist/{config-U624HJKI.js → config-7Y7I7KX4.js} +1 -1
- package/dist/config-Z6KFEFJO.js +1 -0
- package/dist/db-P7ELD5DS.js +1 -0
- package/dist/{delivery-log-QMQQHES4.js → delivery-log-EVRKJ5GD.js} +1 -1
- package/dist/engine-FE7NCHOG.js +1 -0
- package/dist/{evolution-audit-XF4KZZMP.js → evolution-audit-XIWF3JIF.js} +1 -1
- package/dist/execution-tools-PGURN3N6.js +1 -0
- package/dist/{external-api-435WH6V3.js → external-api-DSLQDRZ2.js} +1 -1
- package/dist/index.js +70 -67
- package/dist/{learner-4CJ7BSCN.js → learner-PWDQUZ5O.js} +1 -1
- package/dist/{memories-NJFKSOL5.js → memories-2OJFLLBT.js} +1 -1
- package/dist/{memory-extractor-UQI75BBK.js → memory-extractor-N7M4YSPL.js} +1 -1
- package/dist/{memory-gc-NTZVUGJX.js → memory-gc-R42SPM52.js} +1 -1
- package/dist/memory-service-V7B5MY37.js +1 -0
- package/dist/outbound-gateway-NHNHVHF2.js +1 -0
- package/dist/presets-H2UV3HIF.js +1 -0
- package/dist/{reflection-job-F4BZA2E3.js → reflection-job-ECJX5ERQ.js} +1 -1
- package/dist/role-presets-7SWGUPV2.js +1 -0
- package/dist/role-workspace-AOYIGLG4.js +1 -0
- package/dist/{roles-WDMUBWQP.js → roles-5TWJBGAQ.js} +1 -1
- package/dist/{session-manager-XFUKWEC7.js → session-manager-5P2FAEV3.js} +1 -1
- package/dist/skill-registry-XOX4OSHY.js +1 -0
- package/dist/{task-templates-BIVCRNXA.js → task-templates-CTQHB6TA.js} +1 -1
- package/dist/template-dispatch-Z2TKWOMY.js +1 -0
- package/package.json +1 -1
- package/web/dist/assets/{ChannelDetail-D0FBZoAX.js → ChannelDetail-CSq9o5fq.js} +1 -1
- package/web/dist/assets/{Channels-Cztxvsa2.js → Channels-CAxTh1Bp.js} +1 -1
- package/web/dist/assets/Chat-PUz41HFr.js +2 -0
- package/web/dist/assets/{Cost-K8-4xqBe.js → Cost-BHcsPz5T.js} +1 -1
- package/web/dist/assets/{Dashboard-BXqFb_Vr.js → Dashboard-BT39_iWc.js} +1 -1
- package/web/dist/assets/{EnvVarEditor-FiiJazzp.js → EnvVarEditor-D_1d7bTJ.js} +1 -1
- package/web/dist/assets/{EventDefDetail-C3S1G0K8.js → EventDefDetail-jKN3gO_7.js} +1 -1
- package/web/dist/assets/{Events-BKxqZ9j6.js → Events-CpeHg3fh.js} +1 -1
- package/web/dist/assets/{Evolution-DFcSm6Rw.js → Evolution-DsWyv2_a.js} +1 -1
- package/web/dist/assets/{ExtensionDetail-C8aPpyLv.js → ExtensionDetail-CJHNaNii.js} +1 -1
- package/web/dist/assets/{Extensions-MLZk05j0.js → Extensions-Pg2vx_ZK.js} +1 -1
- package/web/dist/assets/{FeatureRequests-D_4XaQ7F.js → FeatureRequests-3Yl8wTNT.js} +1 -1
- package/web/dist/assets/{GoalDetail-DVU7c0aR.js → GoalDetail-L3T1zqqs.js} +1 -1
- package/web/dist/assets/{Goals-D3h4WMjU.js → Goals-B-__r-Yq.js} +1 -1
- package/web/dist/assets/{Logs-D5MQv6Yw.js → Logs-CMkjUkmu.js} +1 -1
- package/web/dist/assets/{Memories-Dls71I2i.js → Memories-Q1eKfPQ2.js} +1 -1
- package/web/dist/assets/{Mistakes-BZcTg0vP.js → Mistakes-BROkixt_.js} +1 -1
- package/web/dist/assets/{Plugins-CwCHGzI6.js → Plugins-v17MyPVe.js} +1 -1
- package/web/dist/assets/{RoleDetail-B2M6ALSl.js → RoleDetail-DCGFBLP1.js} +2 -2
- package/web/dist/assets/{Roles-FEHqm_Jf.js → Roles-C7SNebvY.js} +1 -1
- package/web/dist/assets/{Settings-rdVQMfqX.js → Settings-QuKwKbKg.js} +1 -1
- package/web/dist/assets/{Strategies-CwJ9JQ-X.js → Strategies-CXQYvCkc.js} +1 -1
- package/web/dist/assets/{Switch-1JjR4Imr.js → Switch--h1rqagh.js} +1 -1
- package/web/dist/assets/{TaskDetail-h12WxjfG.js → TaskDetail-B0G5ZjDD.js} +1 -1
- package/web/dist/assets/{Work-CfzFRSZX.js → Work-DbFst_9-.js} +1 -1
- package/web/dist/assets/index-D35OGE0z.css +2 -0
- package/web/dist/assets/{index-CXEJd-0s.js → index-Dd3NDYZR.js} +2 -2
- package/web/dist/assets/{usePluginsWithUsage-4iLJAPjH.js → usePluginsWithUsage-DpTxJuFQ.js} +1 -1
- package/web/dist/index.html +2 -2
- package/dist/approval-handler-BWA7UIKN.js +0 -1
- package/dist/artifacts-MAYKOTA2.js +0 -1
- package/dist/audit-diagnostics-K3LUWXTI.js +0 -1
- package/dist/audit-manager-6WL2V6JG.js +0 -1
- package/dist/bree-engine-KYD4GKQK.js +0 -1
- package/dist/channels-PWDSTYNR.js +0 -1
- package/dist/chat-tool-calls-WJDFQ54U.js +0 -1
- package/dist/chunk-3UFEOB6P.js +0 -143
- package/dist/chunk-MTRLUW7Z.js +0 -1
- package/dist/chunk-QTGAK62Z.js +0 -14
- package/dist/chunk-TWOJVEO7.js +0 -32
- package/dist/chunk-VO24C673.js +0 -1
- package/dist/chunk-VPMHZJS2.js +0 -1
- package/dist/chunk-ZJ3TS4FL.js +0 -182
- package/dist/config-X7A6NA73.js +0 -1
- package/dist/db-XODNIJSJ.js +0 -1
- package/dist/engine-OQXDHA2R.js +0 -1
- package/dist/execution-tools-BR4T4MMW.js +0 -1
- package/dist/memory-service-3RLVOF2C.js +0 -1
- package/dist/outbound-gateway-NJNSN2ZX.js +0 -1
- package/dist/presets-SUJRFRJC.js +0 -1
- package/dist/role-presets-VEYTGYA4.js +0 -1
- package/dist/role-workspace-AIVHPX5P.js +0 -1
- package/dist/skill-registry-LARMNUT5.js +0 -1
- package/dist/template-dispatch-6FPJQN6A.js +0 -1
- package/web/dist/assets/Chat-Ce72TtUi.js +0 -2
- package/web/dist/assets/index-CarTGiGO.css +0 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as a,d as b,e as c,f as d,g as e}from"./chunk-YGZQMZTA.js";import"./chunk-R3MSLP6P.js";import"./chunk-PU2T7HBY.js";import"./chunk-5ZL6RHPE.js";import"./chunk-YI2QQTZE.js";import"./chunk-NX3CIEZA.js";import"./chunk-X3PJNX2R.js";import"./chunk-G5I76LX2.js";import"./chunk-L7JP7DUO.js";import"./chunk-3JTHJ3FZ.js";import"./chunk-XEXSXMWK.js";import"./chunk-ISTUK7Q6.js";import"./chunk-J2VSAXVU.js";import"./chunk-3MROEPGR.js";import"./chunk-6GVYOHD5.js";import"./chunk-ZEGZ2I35.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";export{b as formatPlanForChannel,e as getPendingApprovalRequestIds,d as handleInboundForApproval,a as parseApprovalReply,c as sendApprovalToChannel};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s}from"./chunk-6GVYOHD5.js";import"./chunk-ZEGZ2I35.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5PELJRUQ.js";s();export{o as appendArtifactToCollection,p as convertPrimaryFileToCollectionInTransaction,b as createArtifact,k as deleteArtifactById,i as deleteArtifactsByExecution,j as deleteArtifactsByExecutionAndStep,n as ensureUniqueArtifactKey,c as getArtifact,d as getArtifactById,m as isArtifactCollectionManifest,r as listArtifacts,g as listArtifactsByChatSession,e as listArtifactsByExecution,h as listArtifactsByRole,f as listArtifactsByTask,q as listExpiredExecutions,a as normalizeJsonArtifactValue,l as removeArtifact};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,d as c}from"./chunk-NX3CIEZA.js";import"./chunk-ZEGZ2I35.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";c();export{b as listAuditDiagnostics,a as recordAuditDiagnostic};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{M as a,N as b,O as c,P as d,Q as e,R as f,S as g}from"./chunk-J4JO7O3T.js";import"./chunk-QMW7VEPC.js";import"./chunk-PZH5NKUL.js";import"./chunk-EXB2JIBR.js";import"./chunk-QF3B4OWI.js";import"./chunk-SDHMBWVC.js";import"./chunk-SONOE4ZJ.js";import"./chunk-VVPB3TD4.js";import"./chunk-PU2T7HBY.js";import"./chunk-QX65LEYA.js";import"./chunk-LE5YRP37.js";import"./chunk-N4BV2WAU.js";import"./chunk-KO6UB6VW.js";import"./chunk-X3PJNX2R.js";import"./chunk-6NIWU43Z.js";import"./chunk-G5I76LX2.js";import"./chunk-L7JP7DUO.js";import"./chunk-GYOZGA7G.js";import"./chunk-4NRIKWSD.js";import"./chunk-6SBLFYCU.js";import"./chunk-T2Z2JDPY.js";import"./chunk-AKQ3AFVI.js";import"./chunk-3JTHJ3FZ.js";import"./chunk-AUSR5JYV.js";import"./chunk-ISTUK7Q6.js";import"./chunk-J2VSAXVU.js";import"./chunk-3MROEPGR.js";import"./chunk-6GVYOHD5.js";import"./chunk-ZEGZ2I35.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";export{e as auditAssistantCommitment,f as auditDeliveryClaims,a as evaluateTaskCompletion,g as getSecurityPosture,d as reportViolation,b as startAuditManager,c as stopAuditManager};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c}from"./chunk-YGR5ZTGT.js";import"./chunk-ZARKPBI2.js";import"./chunk-PZH5NKUL.js";import"./chunk-EXB2JIBR.js";import"./chunk-QF3B4OWI.js";import"./chunk-SDHMBWVC.js";import"./chunk-2BLSA25Q.js";import"./chunk-4N5G7ND2.js";import"./chunk-VVPB3TD4.js";import"./chunk-NNMQGISW.js";import"./chunk-R3MSLP6P.js";import"./chunk-PU2T7HBY.js";import"./chunk-5ZL6RHPE.js";import"./chunk-YI2QQTZE.js";import"./chunk-NX3CIEZA.js";import"./chunk-N4BV2WAU.js";import"./chunk-KO6UB6VW.js";import"./chunk-X3PJNX2R.js";import"./chunk-6NIWU43Z.js";import"./chunk-G5I76LX2.js";import"./chunk-L7JP7DUO.js";import"./chunk-T2Z2JDPY.js";import"./chunk-AKQ3AFVI.js";import"./chunk-3JTHJ3FZ.js";import"./chunk-XEXSXMWK.js";import"./chunk-ISTUK7Q6.js";import"./chunk-T7EKW3B7.js";import"./chunk-J2VSAXVU.js";import"./chunk-JRRNGKDK.js";import"./chunk-3MROEPGR.js";import"./chunk-6GVYOHD5.js";import"./chunk-ZEGZ2I35.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";export{a as BreeEngine,b as getBreeEngine,c as setBreeEngine};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h}from"./chunk-
|
|
1
|
+
import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h}from"./chunk-XEXSXMWK.js";import"./chunk-ZEGZ2I35.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5PELJRUQ.js";export{a as createChannel,e as deleteChannel,b as getChannel,g as getRecipientCap,d as listChannels,h as setRecipientCap,c as updateChannel,f as updateChannelStatus};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as a,j as b,k as c}from"./chunk-CQDOIHPV.js";import"./chunk-VVPB3TD4.js";import"./chunk-NNMQGISW.js";import"./chunk-5ZL6RHPE.js";import"./chunk-YI2QQTZE.js";import"./chunk-NX3CIEZA.js";import"./chunk-XEXSXMWK.js";import"./chunk-J2VSAXVU.js";import"./chunk-3MROEPGR.js";import"./chunk-ZEGZ2I35.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";export{c as channelRoutes,b as getChannelManager,a as setChannelManager};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c}from"./chunk-NUTGYMDP.js";import"./chunk-ZEGZ2I35.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5PELJRUQ.js";export{c as hasAnyToolCallInTurn,b as listChatToolCallsByTrace,a as recordChatToolCall};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as x,e as C}from"./chunk-
|
|
1
|
+
import{c as x,e as C}from"./chunk-VVPB3TD4.js";import{a as y,b as u,c,d as m,e as h,g as v}from"./chunk-YI2QQTZE.js";import{a as i}from"./chunk-L7JP7DUO.js";import{b as l}from"./chunk-T2Z2JDPY.js";import{a as g}from"./chunk-AKQ3AFVI.js";import{e as f}from"./chunk-T7EKW3B7.js";import{v4 as D}from"uuid";import{v4 as I}from"uuid";function _(e){if(e.length<20)return null;let t=e.trim();return t.length>300?{content:`User request: ${t.slice(0,280)}...`,importance:3,type:"thought"}:{content:`User request: ${t}`,importance:3,type:"thought"}}function b(e){if(e.length<20)return null;let t=e.trim();return t.length>400?{content:`Assistant response: ${t.slice(0,370)}...`,importance:2,type:"event"}:{content:`Assistant response: ${t}`,importance:2,type:"event"}}function N(e){let t=x(e,200,0),s=[];for(let o of t){let r=o.role==="user"?_(o.content):b(o.content);r&&s.push(r)}return{facts:s}}function $(e){let t=e.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(s=>s.length>2);return[...new Set(t)].slice(0,20)}async function A(e,t){let{facts:s}=N(e),o=0;for(let r of s){let p=r.content.slice(0,500),S;try{S=await l(p)}catch{}let M=$(p),T={id:I(),roleId:t,type:r.type,content:p,embedding:S,keywords:M,importance:r.importance,sourceType:"session_archive",createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"episodic"};g(T),o++}return o}var n=new Map,a;function w(e){return`${e.type}:${e.channelId??""}:${e.chatId??""}`}function F(){n.clear();let e=m("active",1e3);for(let t of e)n.set(t.id,t)}function V(e,t){let s=Date.now(),o={id:D(),status:"active",source:e,createdAt:s,lastActiveAt:s,messageCount:0};return y(o),n.set(o.id,o),i.emit({type:"session_created",session:o}),o}function W(e){for(let s of n.values())if(w(s.source)===w(e))return s;let t=h(e);return t&&n.set(t.id,t),t}function B(e){let t=n.get(e);return t||u(e)}function E(e){let t=Date.now();c(e,{status:"archived",archivedAt:t}),f().archiveExtractMemory&&u(e)&&A(e,"role-chat-manager").catch(()=>{}),n.delete(e),i.emit({type:"session_archived",sessionId:e})}function X(e){c(e,{status:"active",archivedAt:void 0});let t=u(e);return t&&(n.set(t.id,t),i.emit({type:"session_restored",session:t})),t}function Y(e){C(e),v(e),n.delete(e),i.emit({type:"session_deleted",sessionId:e})}function Z(e){let t=Date.now();c(e,{lastActiveAt:t});let s=n.get(e);s&&(s.lastActiveAt=t)}function ee(e){let t=B(e);if(t){let s=t.messageCount+1;c(e,{messageCount:s});let o=n.get(e);o&&(o.messageCount=s)}}function te(e){return m(e)}function P(){let t=f().sessionTimeoutMinutes*60*1e3,s=Date.now();for(let o of n.values())if(s-o.lastActiveAt>t)try{E(o.id)}catch{}}function R(e=6e4){d(),a=setInterval(P,e)}function d(){a&&(clearInterval(a),a=void 0)}function se(){return a}function oe(){F(),R()}function ne(){d(),n.clear()}function re(){d(),n.clear()}export{F as a,V as b,W as c,B as d,E as e,X as f,Y as g,Z as h,ee as i,te as j,R as k,d as l,se as m,oe as n,ne as o,re as p};
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{a as m,g as L}from"./chunk-
|
|
1
|
+
import{a as m,g as L}from"./chunk-ISTUK7Q6.js";import{o as a,q as x}from"./chunk-ZEGZ2I35.js";import{b as u,i as _}from"./chunk-ITVCPC7G.js";import{c as v,e as N}from"./chunk-5M6IGE5G.js";import{b as l}from"./chunk-5PELJRUQ.js";var f,p,T=l(()=>{"use strict";f={stylePreferences:[],avoidedActions:[],pinnedParameters:[]},p=class extends Error{constructor(n,r,i,s){super(`Role '${r}' has ${i} active task(s) (${s.join(", ")}) and cannot be deleted without the force flag.`);this.roleId=n;this.roleName=r;this.activeTaskCount=i;this.taskStatuses=s;this.name="RoleHasActiveTasksError"}roleId;roleName;activeTaskCount;taskStatuses;code="ROLE_HAS_ACTIVE_TASKS"}});import*as R from"os";import*as C from"path";function g(e){return e.startsWith("~/")||e==="~"?C.join(R.homedir(),e.slice(1)):e}var S=l(()=>{"use strict";_()});function E(e){return k.includes(e)}function I(e){return A[e]}function B(){return k.map(e=>A[e])}function te(e,t=e!=="none"){return B().map(n=>J(n,e,t))}function J(e,t,n=t!=="none"){return process.platform==="darwin"?e.status==="runtime-enforced"&&(t!=="sandbox-exec"||!n)?{...e,availability:"runtime-unavailable",editable:!1,effectiveDisabledReason:"Current runtime has no macOS sandbox backend; Adam cannot enforce this capability on Roles."}:e.status==="runtime-enforced"?{...e,availability:"editable",editable:!0}:{...e,availability:e.status,editable:!1,effectiveDisabledReason:e.disabledReason}:{...e,availability:"platform-unsupported",editable:!1,effectiveDisabledReason:"macOS only"}}function re(e){if(!e?.length)return;for(let n of e)if(!E(n.id))throw new Error(`Unknown OS capability: ${n.id}`);let t=c(e);if(t?.length){for(let n of t){let r=I(n.id);if(r.status!=="runtime-enforced")throw new Error(`OS capability '${r.label}' is not editable in Role settings`);if(r.supportsTargets){if(!n.targets?.length)throw new Error(`OS capability '${r.label}' requires at least one target bundle id`);for(let i of n.targets)if(!F(i))throw new Error(`Invalid automation target bundle id: ${i}`)}else if(n.targets?.length)throw new Error(`OS capability '${r.label}' does not accept targets`)}return t}}function c(e){if(!e||e.length===0)return;let t=new Set,n=[];for(let r of e){if(!E(r.id))throw new Error(`Unknown OS capability: ${r.id}`);if(t.has(r.id))continue;t.add(r.id);let i=I(r.id),s={id:r.id};i.supportsTargets&&r.targets?.length&&(s.targets=[...new Set(r.targets.map(o=>o.trim()).filter(Boolean))]),n.push(s)}return n.length>0?n.sort((r,i)=>r.id.localeCompare(i.id)):void 0}function F(e){return U.test(e)}var k,A,U,w=l(()=>{"use strict";k=["location-services","calendars","contacts","files-and-folders","full-disk-access","homekit","media-and-apple-music","passkeys-access-for-web-browsers","photos","reminders","accessibility","app-management","automation","bluetooth","camera","developer-tools","focus","input-monitoring","local-network","microphone","motion-and-fitness","remote-desktop","screen-and-system-audio-recording","speech-recognition"],A={"location-services":{id:"location-services",label:"Location Services",description:"Access device location and region context.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},calendars:{id:"calendars",label:"Calendars",description:"Access Calendar data via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},contacts:{id:"contacts",label:"Contacts",description:"Access Contacts data via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"files-and-folders":{id:"files-and-folders",label:"Files & Folders",description:"Host-level file access categories managed outside Role sandboxing.",platform:"darwin",status:"host-only",disabledReason:"Role file boundaries are already controlled by visiblePaths and deniedReadPaths."},"full-disk-access":{id:"full-disk-access",label:"Full Disk Access",description:"Host-level macOS grant for protected storage locations.",platform:"darwin",status:"host-only",disabledReason:"This is a host app permission, not a Role-level control."},homekit:{id:"homekit",label:"HomeKit",description:"Access HomeKit devices and home automation data.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"media-and-apple-music":{id:"media-and-apple-music",label:"Media & Apple Music",description:"Access Apple Music and media library data.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"passkeys-access-for-web-browsers":{id:"passkeys-access-for-web-browsers",label:"Passkeys Access for Web Browsers",description:"Access passkeys for browser-integrated authentication.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},photos:{id:"photos",label:"Photos",description:"Access the Photos library via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},reminders:{id:"reminders",label:"Reminders",description:"Access Reminder data via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},accessibility:{id:"accessibility",label:"Accessibility",description:"Control desktop UI and accessibility automation surfaces.",platform:"darwin",status:"runtime-enforced"},"app-management":{id:"app-management",label:"App Management",description:"Manage or inspect other installed applications.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},automation:{id:"automation",label:"Automation",description:"Launch and control other apps via Apple Events.",platform:"darwin",status:"runtime-enforced",supportsTargets:!0},bluetooth:{id:"bluetooth",label:"Bluetooth",description:"Access nearby Bluetooth devices.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},camera:{id:"camera",label:"Camera",description:"Capture camera input.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"developer-tools":{id:"developer-tools",label:"Developer Tools",description:"Use system developer tooling privileges.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},focus:{id:"focus",label:"Focus",description:"Access Focus state and related automation.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"input-monitoring":{id:"input-monitoring",label:"Input Monitoring",description:"Observe keyboard and input device activity.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"local-network":{id:"local-network",label:"Local Network",description:"Discover and communicate with devices on the local network.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},microphone:{id:"microphone",label:"Microphone",description:"Capture microphone input.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"motion-and-fitness":{id:"motion-and-fitness",label:"Motion & Fitness",description:"Access motion and fitness sensor data.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"remote-desktop":{id:"remote-desktop",label:"Remote Desktop",description:"Control or observe remote desktop sessions.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"screen-and-system-audio-recording":{id:"screen-and-system-audio-recording",label:"Screen & System Audio Recording",description:"Capture the screen and system audio.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"speech-recognition":{id:"speech-recognition",label:"Speech Recognition",description:"Use system speech recognition services.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."}},U=/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/});function b(e){return{id:e.id,parentId:e.parent_id??void 0,status:e.status,prompt:e.prompt,originalPrompt:e.original_prompt??void 0,config:JSON.parse(e.config),result:e.result??void 0,error:e.error??void 0,sdkSessionId:e.sdk_session_id??void 0,templateId:e.template_id??void 0,roleId:e.role_id??void 0,stepId:e.step_id??void 0,sourceSessionId:e.source_session_id??void 0,deliverTo:e.deliver_to?JSON.parse(e.deliver_to):void 0,reportTo:e.report_to?JSON.parse(e.report_to):void 0,createdAt:e.created_at,startedAt:e.started_at??void 0,completedAt:e.completed_at??void 0,costUsd:e.cost_usd??void 0,costBreakdown:e.cost_breakdown?JSON.parse(e.cost_breakdown):void 0,tokenUsage:e.token_usage?JSON.parse(e.token_usage):void 0,numTurns:e.num_turns??void 0,totalDurationMs:e.total_duration_ms??void 0,blockReason:e.block_reason_json?JSON.parse(e.block_reason_json):void 0,traceId:e.trace_id??void 0,errorCategory:e.error_category??void 0,retryCount:e.retry_count}}function ae(e){a().prepare(`
|
|
2
2
|
INSERT INTO tasks (id, parent_id, status, prompt, original_prompt, config, result, error,
|
|
3
3
|
sdk_session_id, template_id, role_id, step_id, source_session_id, notify_targets, deliver_to, report_to,
|
|
4
4
|
created_at, started_at, completed_at,
|
|
5
5
|
cost_usd, token_usage, num_turns, total_duration_ms, trace_id, error_category, retry_count, cost_breakdown)
|
|
6
6
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
7
|
-
`).run(e.id,e.parentId??null,e.status,e.prompt,e.originalPrompt??null,JSON.stringify(e.config),e.result??null,e.error??null,e.sdkSessionId??null,e.templateId??null,e.roleId??null,e.stepId??null,e.sourceSessionId??null,null,e.deliverTo?JSON.stringify(e.deliverTo):null,e.reportTo?JSON.stringify(e.reportTo):null,e.createdAt,e.startedAt??null,e.completedAt??null,e.costUsd??null,e.tokenUsage?JSON.stringify(e.tokenUsage):null,e.numTurns??null,e.totalDurationMs??null,e.traceId??v()??null,e.errorCategory??null,e.retryCount??0,e.costBreakdown?JSON.stringify(e.costBreakdown):null)}function W(e){let n=
|
|
7
|
+
`).run(e.id,e.parentId??null,e.status,e.prompt,e.originalPrompt??null,JSON.stringify(e.config),e.result??null,e.error??null,e.sdkSessionId??null,e.templateId??null,e.roleId??null,e.stepId??null,e.sourceSessionId??null,null,e.deliverTo?JSON.stringify(e.deliverTo):null,e.reportTo?JSON.stringify(e.reportTo):null,e.createdAt,e.startedAt??null,e.completedAt??null,e.costUsd??null,e.tokenUsage?JSON.stringify(e.tokenUsage):null,e.numTurns??null,e.totalDurationMs??null,e.traceId??v()??null,e.errorCategory??null,e.retryCount??0,e.costBreakdown?JSON.stringify(e.costBreakdown):null)}function W(e){let n=a().prepare("SELECT * FROM tasks WHERE id = ?").get(e);return n?b(n):void 0}function H(e,t){let n=a(),r=[],i=[],s={parentId:"parent_id",status:"status",prompt:"prompt",result:"result",error:"error",sdkSessionId:"sdk_session_id",templateId:"template_id",roleId:"role_id",stepId:"step_id",sourceSessionId:"source_session_id",originalPrompt:"original_prompt",startedAt:"started_at",completedAt:"completed_at",costUsd:"cost_usd",numTurns:"num_turns",totalDurationMs:"total_duration_ms",errorCategory:"error_category",retryCount:"retry_count"};for(let[o,d]of Object.entries(s))o in t&&(r.push(`${d} = ?`),i.push(t[o]??null));"config"in t&&(r.push("config = ?"),i.push(JSON.stringify(t.config))),"tokenUsage"in t&&(r.push("token_usage = ?"),i.push(t.tokenUsage?JSON.stringify(t.tokenUsage):null)),"costBreakdown"in t&&(r.push("cost_breakdown = ?"),i.push(t.costBreakdown?JSON.stringify(t.costBreakdown):null)),"deliverTo"in t&&(r.push("deliver_to = ?"),i.push(t.deliverTo?JSON.stringify(t.deliverTo):null)),"reportTo"in t&&(r.push("report_to = ?"),i.push(t.reportTo?JSON.stringify(t.reportTo):null)),"blockReason"in t&&(r.push("block_reason_json = ?"),i.push(t.blockReason?JSON.stringify(t.blockReason):null)),"contextMeta"in t&&(r.push("context_meta = ?"),i.push(t.contextMeta?JSON.stringify(t.contextMeta):null)),r.length!==0&&(i.push(e),n.prepare(`UPDATE tasks SET ${r.join(", ")} WHERE id = ?`).run(...i))}function oe(e,t){let n=W(e);if(!n)return;let r={...n.config??{},...t};H(e,{config:r})}function P(e,t=100,n=0,r){let i=a(),s="SELECT * FROM tasks",o=[],d=[];return e&&(o.push("status = ?"),d.push(e)),r&&(o.push("role_id = ?"),d.push(r)),o.length>0&&(s+=" WHERE "+o.join(" AND ")),s+=" ORDER BY created_at DESC LIMIT ? OFFSET ?",d.push(t,n),i.prepare(s).all(...d).map(b)}function de(e){return a().prepare("SELECT * FROM tasks WHERE parent_id = ? ORDER BY created_at ASC").all(e).map(b)}function le(e){return a().prepare("SELECT COALESCE(SUM(cost_usd), 0) as total FROM tasks WHERE completed_at >= ? AND cost_usd IS NOT NULL").get(e).total}function ce(e){return a().prepare("SELECT trace_id FROM tasks WHERE id = ?").get(e)?.trace_id??void 0}function ue(e){let t=a();return t.prepare("UPDATE tasks SET retry_count = retry_count + 1 WHERE id = ?").run(e),t.prepare("SELECT retry_count FROM tasks WHERE id = ?").get(e)?.retry_count??1}function q(e){return{id:e.id,taskId:e.task_id,retryAt:e.retry_at,createdAt:e.created_at}}function pe(e){a().prepare("INSERT INTO delayed_retries (id, task_id, retry_at, created_at) VALUES (?, ?, ?, ?)").run(e.id,e.taskId,e.retryAt,e.createdAt)}function ge(e){return a().prepare("SELECT * FROM delayed_retries WHERE retry_at <= ? ORDER BY retry_at ASC").all(e).map(q)}function me(e){a().prepare("DELETE FROM delayed_retries WHERE id = ?").run(e)}function V(e,t){let n=a();n.transaction(()=>{let r=n.prepare("SELECT context_meta FROM tasks WHERE id = ?").get(e),i=(()=>{if(r?.context_meta)try{return JSON.parse(r.context_meta)}catch{return{}}return{}})();t(i),n.prepare("UPDATE tasks SET context_meta = ? WHERE id = ?").run(JSON.stringify(i),e)})()}function fe(e){let n=a().prepare("SELECT context_meta FROM tasks WHERE id = ?").get(e);if(!n||n.context_meta===null)return null;try{return JSON.parse(n.context_meta)}catch{return null}}function be(e,t){t.length!==0&&V(e,n=>{let r=Array.isArray(n.usedMemoryIds)?n.usedMemoryIds:[];n.usedMemoryIds=Array.from(new Set([...r,...t]))})}var O=l(()=>{"use strict";x();N()});import{existsSync as K}from"fs";import{resolve as y}from"path";function M(e){if(e==null)return{...f};if(Array.isArray(e))return{stylePreferences:e.filter(t=>typeof t=="string"),avoidedActions:[],pinnedParameters:[]};if(typeof e=="object"){let t=e;return{stylePreferences:Array.isArray(t.stylePreferences)?t.stylePreferences.filter(n=>typeof n=="string"):[],avoidedActions:Array.isArray(t.avoidedActions)?t.avoidedActions.filter(n=>typeof n=="string"):[],pinnedParameters:Array.isArray(t.pinnedParameters)?t.pinnedParameters.filter(n=>n!==null&&typeof n=="object"&&typeof n.tool=="string"):[]}}return{...f}}function D(e,t){for(let n of e){let r=typeof n=="string"?n:n.path;if(!r.startsWith("/")&&!r.startsWith("~/")&&r!=="~")throw new Error(`additionalDirectories must be absolute paths: '${r}' is not absolute`);let i=y(g(r));if(!i.startsWith("/"))throw new Error(`additionalDirectories must be absolute paths: '${r}' is not absolute`);for(let s of u){let o=y(g(s));if(i.startsWith(o))throw new Error(`additionalDirectories cannot include hardcoded denied path: '${r}' matches '${s}'`)}if(t?.length)for(let s of t){let o=y(g(s));if(i.startsWith(o)||o.startsWith(i))throw new Error(`additionalDirectories cannot overlap with deniedReadPaths: '${r}' conflicts with '${s}'`)}if(!K(i))throw new Error(`additionalDirectories path does not exist: '${r}'`)}}function h(e){return{id:e.id,name:e.name,cagPrompt:e.cag_prompt,learnedRules:M(e.learned_rules?JSON.parse(e.learned_rules):null),memoryStreamId:e.memory_stream_id,status:e.status,performanceScore:e.performance_score??void 0,preferences:e.preferences?JSON.parse(e.preferences):{},createdAt:e.created_at,updatedAt:e.updated_at??void 0,allowedTools:e.allowed_tools?JSON.parse(e.allowed_tools):void 0,disallowedTools:e.disallowed_tools?JSON.parse(e.disallowed_tools):void 0,evaluationCriteria:e.evaluation_criteria?JSON.parse(e.evaluation_criteria):void 0,executionMode:e.execution_mode??void 0,model:e.model??void 0,maxBudgetUsd:e.max_budget_usd??void 0,approvalRequired:e.approval_required?JSON.parse(e.approval_required):void 0,source:e.source??void 0,additionalDirectories:(()=>{if(e.additional_directories!==null)try{let t=JSON.parse(e.additional_directories);return Array.isArray(t)?t.map(n=>typeof n=="string"?{path:n}:n):void 0}catch{return}})(),allowedChannels:e.allowed_channels?JSON.parse(e.allowed_channels):void 0,mcpServers:e.mcp_servers?JSON.parse(e.mcp_servers):void 0,inheritUserSettings:e.inherit_user_settings===1?!0:void 0,permissionMode:e.permission_mode??void 0,allowedBashPatterns:e.allowed_bash_patterns?JSON.parse(e.allowed_bash_patterns):void 0,deniedBashPatterns:e.denied_bash_patterns?JSON.parse(e.denied_bash_patterns):void 0,envVars:e.env_vars?JSON.parse(e.env_vars):void 0,osCapabilities:e.os_capabilities?c(JSON.parse(e.os_capabilities)):void 0,presetId:e.preset_id??void 0,effortTier:e.effort_tier??void 0,skills:e.skills?JSON.parse(e.skills):void 0}}function Ae(e){let t=m("defaults.deniedReadPaths")??[...u];e.additionalDirectories&&D(e.additionalDirectories,t),a().prepare(`
|
|
8
8
|
INSERT INTO roles (id, name, cag_prompt, learned_rules, memory_stream_id, status,
|
|
9
9
|
performance_score, preferences, created_at, updated_at,
|
|
10
10
|
allowed_tools, disallowed_tools, evaluation_criteria, execution_mode, model,
|
|
@@ -12,4 +12,4 @@ import{a as m,g as L}from"./chunk-NUOTFUNF.js";import{n as o,p as x}from"./chunk
|
|
|
12
12
|
permission_mode, allowed_bash_patterns, denied_bash_patterns, env_vars, os_capabilities, preset_id,
|
|
13
13
|
effort_tier, skills)
|
|
14
14
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
15
|
-
`).run(e.id,e.name,e.cagPrompt,JSON.stringify(e.learnedRules),e.memoryStreamId,e.status,e.performanceScore??null,e.preferences?JSON.stringify(e.preferences):null,e.createdAt,e.updatedAt??null,e.allowedTools?JSON.stringify(e.allowedTools):null,e.disallowedTools?JSON.stringify(e.disallowedTools):null,e.evaluationCriteria?JSON.stringify(e.evaluationCriteria):null,e.executionMode??null,e.model??null,e.maxBudgetUsd??null,e.approvalRequired?JSON.stringify(e.approvalRequired):null,e.source??null,e.additionalDirectories?JSON.stringify(e.additionalDirectories):null,e.allowedChannels?JSON.stringify(e.allowedChannels):null,e.mcpServers?JSON.stringify(e.mcpServers):null,e.inheritUserSettings?1:0,e.permissionMode??null,e.allowedBashPatterns?JSON.stringify(e.allowedBashPatterns):null,e.deniedBashPatterns?JSON.stringify(e.deniedBashPatterns):null,e.envVars?JSON.stringify(e.envVars):null,e.osCapabilities?JSON.stringify(c(e.osCapabilities)):null,e.presetId??null,e.effortTier??null,e.skills?JSON.stringify(e.skills):null)}function j(e){let n=
|
|
15
|
+
`).run(e.id,e.name,e.cagPrompt,JSON.stringify(e.learnedRules),e.memoryStreamId,e.status,e.performanceScore??null,e.preferences?JSON.stringify(e.preferences):null,e.createdAt,e.updatedAt??null,e.allowedTools?JSON.stringify(e.allowedTools):null,e.disallowedTools?JSON.stringify(e.disallowedTools):null,e.evaluationCriteria?JSON.stringify(e.evaluationCriteria):null,e.executionMode??null,e.model??null,e.maxBudgetUsd??null,e.approvalRequired?JSON.stringify(e.approvalRequired):null,e.source??null,e.additionalDirectories?JSON.stringify(e.additionalDirectories):null,e.allowedChannels?JSON.stringify(e.allowedChannels):null,e.mcpServers?JSON.stringify(e.mcpServers):null,e.inheritUserSettings?1:0,e.permissionMode??null,e.allowedBashPatterns?JSON.stringify(e.allowedBashPatterns):null,e.deniedBashPatterns?JSON.stringify(e.deniedBashPatterns):null,e.envVars?JSON.stringify(e.envVars):null,e.osCapabilities?JSON.stringify(c(e.osCapabilities)):null,e.presetId??null,e.effortTier??null,e.skills?JSON.stringify(e.skills):null)}function j(e){let n=a().prepare("SELECT * FROM roles WHERE id = ?").get(e);return n?h(n):void 0}function Ee(e){let n=a().prepare("SELECT * FROM roles WHERE name = ?").get(e);return n?h(n):void 0}function Ie(e,t){let n=a(),r=[],i=[];if("name"in t&&(r.push("name = ?"),i.push(t.name)),"cagPrompt"in t&&(r.push("cag_prompt = ?"),i.push(t.cagPrompt)),"learnedRules"in t&&(r.push("learned_rules = ?"),i.push(JSON.stringify(M(t.learnedRules)))),"memoryStreamId"in t&&(r.push("memory_stream_id = ?"),i.push(t.memoryStreamId)),"status"in t&&(r.push("status = ?"),i.push(t.status)),"performanceScore"in t&&(r.push("performance_score = ?"),i.push(t.performanceScore??null)),"preferences"in t&&(r.push("preferences = ?"),i.push(t.preferences?JSON.stringify(t.preferences):null)),"updatedAt"in t&&(r.push("updated_at = ?"),i.push(t.updatedAt??null)),"allowedTools"in t&&(r.push("allowed_tools = ?"),i.push(t.allowedTools?JSON.stringify(t.allowedTools):null)),"disallowedTools"in t&&(r.push("disallowed_tools = ?"),i.push(t.disallowedTools?JSON.stringify(t.disallowedTools):null)),"evaluationCriteria"in t&&(r.push("evaluation_criteria = ?"),i.push(t.evaluationCriteria?JSON.stringify(t.evaluationCriteria):null)),"executionMode"in t&&(r.push("execution_mode = ?"),i.push(t.executionMode??null)),"model"in t&&(r.push("model = ?"),i.push(t.model??null)),"maxBudgetUsd"in t&&(r.push("max_budget_usd = ?"),i.push(t.maxBudgetUsd??null)),"approvalRequired"in t&&(r.push("approval_required = ?"),i.push(t.approvalRequired?JSON.stringify(t.approvalRequired):null)),"source"in t&&(r.push("source = ?"),i.push(t.source??null)),"additionalDirectories"in t){let s=m("defaults.deniedReadPaths")??[...u];t.additionalDirectories&&D(t.additionalDirectories,s),r.push("additional_directories = ?"),i.push(t.additionalDirectories?JSON.stringify(t.additionalDirectories):null)}"allowedChannels"in t&&(r.push("allowed_channels = ?"),i.push(t.allowedChannels?JSON.stringify(t.allowedChannels):null)),"mcpServers"in t&&(r.push("mcp_servers = ?"),i.push(t.mcpServers?JSON.stringify(t.mcpServers):null)),"inheritUserSettings"in t&&(r.push("inherit_user_settings = ?"),i.push(t.inheritUserSettings?1:0)),"permissionMode"in t&&(r.push("permission_mode = ?"),i.push(t.permissionMode??null)),"allowedBashPatterns"in t&&(r.push("allowed_bash_patterns = ?"),i.push(t.allowedBashPatterns?JSON.stringify(t.allowedBashPatterns):null)),"deniedBashPatterns"in t&&(r.push("denied_bash_patterns = ?"),i.push(t.deniedBashPatterns?JSON.stringify(t.deniedBashPatterns):null)),"envVars"in t&&(r.push("env_vars = ?"),i.push(t.envVars?JSON.stringify(t.envVars):null)),"osCapabilities"in t&&(r.push("os_capabilities = ?"),i.push(t.osCapabilities?JSON.stringify(c(t.osCapabilities)):null)),"presetId"in t&&(r.push("preset_id = ?"),i.push(t.presetId??null)),"effortTier"in t&&(r.push("effort_tier = ?"),i.push(t.effortTier??null)),"skills"in t&&(r.push("skills = ?"),i.push(t.skills?JSON.stringify(t.skills):null)),r.length!==0&&(i.push(e),n.prepare(`UPDATE roles SET ${r.join(", ")} WHERE id = ?`).run(...i))}function we(e,t,n=0){let r=a(),i="SELECT * FROM roles",s=[];return e&&(i+=" WHERE status = ?",s.push(e)),i+=" ORDER BY COALESCE(updated_at, created_at) DESC",typeof t=="number"&&(i+=" LIMIT ? OFFSET ?",s.push(t,n)),r.prepare(i).all(...s).map(h)}function G(e){let t=["pending","queued","running"],r=P(void 0,1e3,0,e).filter(s=>t.includes(s.status)),i=[...new Set(r.map(s=>s.status))];return{hasActive:r.length>0,count:r.length,statuses:i}}function Pe(e,t=!1){if(!t){let{hasActive:r,count:i,statuses:s}=G(e);if(r){let o=j(e);throw new p(e,o?.name??e,i,s)}}a().prepare("DELETE FROM roles WHERE id = ?").run(e)}function Oe(e){a().prepare("UPDATE roles SET task_seq = task_seq + 1 WHERE id = ?").run(e)}function Me(e){return a().prepare("SELECT task_seq FROM roles WHERE id = ?").get(e)?.task_seq??0}var $=l(()=>{x();T();_();S();L();w();O()});export{ae as a,W as b,H as c,oe as d,P as e,de as f,le as g,ce as h,ue as i,pe as j,ge as k,me as l,V as m,fe as n,be as o,O as p,p as q,T as r,g as s,S as t,k as u,U as v,I as w,te as x,re as y,c as z,w as A,D as B,Ae as C,j as D,Ee as E,Ie as F,we as G,G as H,Pe as I,Oe as J,Me as K,$ as L};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{g as u,h as n}from"./chunk-
|
|
1
|
+
import{g as u,h as n}from"./chunk-6SBLFYCU.js";import{e as r}from"./chunk-3MROEPGR.js";var m=.995,i=.2,d=.3;function c(){try{let e=r().memory?.scope;return{decayBase:e?.decayBase??m,archiveThreshold:e?.archiveThreshold??i,emaAlpha:e?.emaAlpha??d}}catch{return{decayBase:m,archiveThreshold:i,emaAlpha:d}}}function l(e,s){if(e.successEma==null)return null;let a=Math.max(0,s-e.lastUsedAt),{decayBase:t}=c();return e.successEma*Math.pow(t,a)}function h(e,s){if(e.successEma==null)e.successEma=.5;else{let a=Math.max(0,s-e.lastUsedAt),{decayBase:t}=c();e.successEma=e.successEma*Math.pow(t,a)}e.lastUsedAt=s}function E(e,s){h(e,s),n(e.id,e.successEma,s)}function A(e,s,a){h(e,a);let{emaAlpha:t}=c(),o=(1-t)*e.successEma+t*s;e.successEma=o,n(e.id,o,a)}function B(e,s){let a=l(e,s);return a==null?!1:a<c().archiveThreshold}function v(e){u(e,"archived")}export{l as a,E as b,A as c,B as d,v as e};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{b as m}from"./chunk-
|
|
1
|
+
import{b as m}from"./chunk-YI2QQTZE.js";import{a as d,d as f}from"./chunk-NX3CIEZA.js";import{c as a}from"./chunk-XEXSXMWK.js";import{a as s}from"./chunk-J2VSAXVU.js";import{e as p}from"./chunk-3MROEPGR.js";import{c,h as g}from"./chunk-EZLBMUQD.js";function k(e,n,i){switch(n){case"wechat":return l(e);case"telegram":return e;case"slack":return w(e);case"email":return e;case"webhook":return JSON.stringify({result:e,taskId:i,timestamp:new Date().toISOString()});default:return l(e)}}function l(e){return e.replace(/^#{1,6}\s+/gm,"").replace(/\*\*(.+?)\*\*/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/_(.+?)_/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/```[\s\S]*?```/g,n=>n.replace(/```\w*\n?/g,"").trim()).replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\n{3,}/g,`
|
|
2
2
|
|
|
3
3
|
`).trim()}function w(e){return e.replace(/\*\*(.+?)\*\*/g,"*$1*").replace(/\[([^\]]+)\]\(([^)]+)\)/g,"<$2|$1>")}f();g();var t=c("message-handler");function x(){try{let e=p().identity?.ownerViewerKey;if(typeof e=="string"&&e.trim().length>0)return e}catch{}return s.identity?.ownerViewerKey??"local-owner"}function u(e){if(e.type==="web"||e.type==="tui"||e.type==="api")return x();if(e.type!=="channel"||!e.channelId){t.warn({source:e},"Viewer identity unavailable for chat source"),r("chat source has no resolvable viewer identity",void 0);return}let i=a(e.channelId)?.viewerKey;if(typeof i=="string"&&i.trim().length>0)return i;t.warn({channelId:e.channelId},"Channel viewerKey missing; recent delivery context disabled"),r("channel viewerKey missing; recent delivery context disabled",e.channelId)}function E(e){if(e.type==="channel"){let o=a(e.channelId)?.viewerKey;if(typeof o=="string"&&o.trim().length>0)return o;t.warn({channelId:e.channelId},"Channel viewerKey missing; ledger recording skipped"),r("channel viewerKey missing; ledger recording skipped",e.channelId);return}let n=m(e.sessionId);if(!n){t.warn({sessionId:e.sessionId},"Session target missing; ledger recording skipped"),r("session target missing; ledger recording skipped",e.sessionId);return}return u(n.source)}function r(e,n){try{d({source:"viewer_identity",severity:"warning",sourceId:n,message:e})}catch{}}import v from"path";var h={".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".csv":"text/csv",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".mp3":"audio/mpeg",".ogg":"audio/ogg",".wav":"audio/wav",".amr":"audio/amr",".silk":"audio/x-silk",".md":"text/markdown",".html":"text/html",".json":"application/json",".xml":"text/xml",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm",".mkv":"video/x-matroska",".avi":"video/x-msvideo",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp"},y={"image/jpeg":".jpg","image/jpg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/bmp":".bmp","video/mp4":".mp4","video/quicktime":".mov","video/webm":".webm","video/x-matroska":".mkv","video/x-msvideo":".avi","audio/mpeg":".mp3","audio/ogg":".ogg","audio/wav":".wav","audio/amr":".amr","audio/x-silk":".silk","application/pdf":".pdf","application/zip":".zip","application/x-tar":".tar","application/gzip":".gz","text/plain":".txt","text/csv":".csv","text/markdown":".md","audio/mp3":".mp3","text/html":".html","application/json":".json","application/xml":".xml","text/xml":".xml","application/vnd.openxmlformats-officedocument.wordprocessingml.document":".docx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":".xlsx","application/vnd.openxmlformats-officedocument.presentationml.presentation":".pptx","application/msword":".doc","application/vnd.ms-excel":".xls","application/vnd.ms-powerpoint":".ppt"};function $(e){let n=v.extname(e).toLowerCase();return h[n]??"application/octet-stream"}function F(e){let n=e.split(";")[0].trim().toLowerCase();return y[n]??".bin"}export{k as a,l as b,x as c,u as d,E as e,$ as f,F as g};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{o,q as k}from"./chunk-ZEGZ2I35.js";import{b as R}from"./chunk-5PELJRUQ.js";import{basename as S}from"path";import{v4 as x}from"uuid";function u(t){return{id:t.id,sourceKind:t.source_kind,executionId:t.execution_id??void 0,taskId:t.task_id??void 0,chatSessionId:t.chat_session_id??void 0,stepId:t.step_id??void 0,roleId:t.role_id??void 0,key:t.key??void 0,kind:t.kind,value:t.value_json?JSON.parse(t.value_json):void 0,blobPath:t.blob_path??void 0,mime:t.mime??void 0,originalFilename:t.original_filename??void 0,sizeBytes:t.size_bytes,createdAt:t.created_at,locator:t.locator??void 0,contentHash:t.content_hash??void 0,retentionHint:t.retention_hint??void 0,encryptionClass:t.encryption_class??void 0,purpose:t.purpose??void 0,replaces:t.replaces??void 0,producedByRole:t.produced_by_role??void 0,access:t.access??void 0,priority:t.priority??void 0,artifactRole:t.artifact_role??void 0}}function T(t,e){if(t!=="json"||typeof e!="string")return e;try{let n=JSON.parse(e);return n!==null&&typeof n=="object"?n:e}catch{return e}}function H(t){if(!t.roleId||t.roleId.trim()==="")throw new Error("createArtifact: roleId required (application-layer enforcement)");p(o(),t)}function p(t,e){let n=T(e.kind,e.value);t.prepare(`
|
|
2
2
|
INSERT INTO artifacts (
|
|
3
3
|
id, source_kind, execution_id, task_id, chat_session_id, step_id, role_id,
|
|
4
4
|
key, kind, value_json, blob_path, mime, original_filename, size_bytes, created_at,
|
|
@@ -6,18 +6,18 @@ import{n as o,p as k}from"./chunk-WY5BOCQP.js";import{b}from"./chunk-5PELJRUQ.js
|
|
|
6
6
|
artifact_role
|
|
7
7
|
)
|
|
8
8
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
9
|
-
`).run(e.id,e.sourceKind,e.executionId??null,e.taskId??null,e.chatSessionId??null,e.stepId??null,e.roleId??null,e.key??null,e.kind,
|
|
9
|
+
`).run(e.id,e.sourceKind,e.executionId??null,e.taskId??null,e.chatSessionId??null,e.stepId??null,e.roleId??null,e.key??null,e.kind,n!==void 0?JSON.stringify(n):null,e.blobPath??null,e.mime??null,e.originalFilename??null,e.sizeBytes,e.createdAt,e.locator??null,e.contentHash??null,e.retentionHint??null,e.encryptionClass??null,e.purpose??null,e.replaces??null,e.producedByRole??null,e.access??null,e.priority??null,e.artifactRole??null)}function y(t,e,n,i){let r=t.prepare(`
|
|
10
10
|
SELECT * FROM artifacts
|
|
11
11
|
WHERE source_kind = 'template_step' AND execution_id = ? AND step_id = ? AND key = ?
|
|
12
|
-
`).get(e,n,i);return r?u(r):void 0}function
|
|
12
|
+
`).get(e,n,i);return r?u(r):void 0}function L(t,e,n){return y(o(),t,e,n)}function P(t){let e=o().prepare("SELECT * FROM artifacts WHERE id = ?").get(t);return e?u(e):void 0}function h(t,e){let n=o(),i="SELECT * FROM artifacts WHERE execution_id = ?",r=[t];return e&&(i+=" AND step_id = ?",r.push(e)),i+=" ORDER BY created_at ASC",n.prepare(i).all(...r).map(u)}function v(t){return o().prepare("SELECT * FROM artifacts WHERE task_id = ? ORDER BY created_at ASC").all(t).map(u)}function K(t){return o().prepare("SELECT * FROM artifacts WHERE chat_session_id = ? ORDER BY created_at ASC").all(t).map(u)}function z(t,e){let n=o(),i="SELECT * FROM artifacts WHERE role_id = ?",r=[t];e?.sourceKind&&(i+=" AND source_kind = ?",r.push(e.sourceKind)),i+=" ORDER BY created_at ASC";let s=n.prepare(i).all(...r).map(u);return e?.mimePrefix&&(s=s.filter(a=>a.mime?.startsWith(e.mimePrefix))),s}function N(t){let e=o(),n=h(t);return e.prepare("DELETE FROM artifacts WHERE execution_id = ?").run(t),n}function W(t,e){let n=o(),i=h(t).filter(r=>r.stepId===e);return n.prepare("DELETE FROM artifacts WHERE execution_id = ? AND step_id = ?").run(t,e),i}function $(t){o().prepare("DELETE FROM artifacts WHERE id = ?").run(t)}function j(t){return o().prepare("DELETE FROM artifacts WHERE id = ?").run(t).changes>0}function B(t){if(!t||typeof t!="object")return!1;let e=t;return e.type!=="artifact_collection"||typeof e.outputAs!="string"||e.outputAs.length===0||!Array.isArray(e.items)?!1:e.items.every(n=>n!=null&&typeof n=="object"&&typeof n.artifactId=="string"&&n.artifactId.length>0&&typeof n.key=="string"&&n.key.length>0&&typeof n.sizeBytes=="number"&&Number.isFinite(n.sizeBytes)&&(n.filename===void 0||typeof n.filename=="string")&&(n.mime===void 0||typeof n.mime=="string")&&(n.purpose===void 0||typeof n.purpose=="string"))}function q(t,e,n){return g(o(),t,e,n)}function U(t,e,n,i){let r=o();return r.transaction(()=>{let s=y(r,t,e,n);if(!s||s.kind!=="json"||!B(s.value))throw new Error(`Artifact collection manifest not found at ${e}/${n}`);let a=g(r,t,e,i.key??"",new Set([n])),l={...i,key:a};p(r,l);let d={...s.value,items:[...s.value.items,m(l)]};return{manifestArtifact:M(r,s,d),childArtifact:l}})()}function J(t,e,n,i,r){let c=o();return c.transaction(()=>{let a=y(c,t,e,n);if(!a||a.id!==i.id)throw new Error(`Primary artifact changed before collection conversion at ${e}/${n}`);if(a.kind!=="file"||!a.blobPath)throw new Error(`Primary artifact at ${e}/${n} is not a file`);let l=g(c,t,e,a.originalFilename??a.key??n,new Set([n]));c.prepare("UPDATE artifacts SET key = ? WHERE id = ?").run(l,a.id);let d={...a,key:l},A=g(c,t,e,r.key??"",new Set([n,l])),f={...r,key:A};p(c,f);let _={type:"artifact_collection",outputAs:n,items:[m(d),m(f)]},E={id:x(),sourceKind:i.sourceKind,executionId:t,stepId:e,key:n,kind:"json",value:_,sizeBytes:b(_),createdAt:Date.now(),purpose:"data",roleId:i.roleId};return p(c,E),{manifestArtifact:E,childArtifact:f,rekeyedPrimaryArtifact:d}})()}function Y(t){return o().prepare(`
|
|
13
13
|
SELECT id
|
|
14
14
|
FROM template_executions
|
|
15
15
|
WHERE status != 'running' AND COALESCE(completed_at, started_at) < ?
|
|
16
16
|
`).all(t).map(i=>i.id)}function g(t,e,n,i,r=new Set){let c=t.prepare(`
|
|
17
17
|
SELECT key FROM artifacts
|
|
18
18
|
WHERE execution_id = ? AND step_id = ?
|
|
19
|
-
`).all(e,n),s=new Set(c.map(l=>l.key));for(let l of r)s.add(l);let a=
|
|
19
|
+
`).all(e,n),s=new Set(c.map(l=>l.key));for(let l of r)s.add(l);let a=I(i);if(!s.has(a))return a;for(let l=2;l<1e4;l++){let d=`-${l}`,f=`${a.slice(0,Math.max(1,256-d.length))}${d}`;if(!s.has(f))return f}throw new Error(`Unable to allocate unique artifact key for ${n}/${i}`)}function I(t){let e=t.replace(/\\/g,"/"),i=S(e).replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,256);return!i||i==="."||i===".."?"artifact":C.test(i)?i:"artifact"}function m(t){return{artifactId:t.id,key:t.key??"",...t.originalFilename?{filename:t.originalFilename}:{},...t.mime?{mime:t.mime}:{},sizeBytes:t.sizeBytes,...t.purpose?{purpose:t.purpose}:{},...t.artifactRole?{role:t.artifactRole}:{}}}function M(t,e,n){let i=b(n);return t.prepare(`
|
|
20
20
|
UPDATE artifacts
|
|
21
21
|
SET value_json = ?, size_bytes = ?
|
|
22
22
|
WHERE id = ?
|
|
23
|
-
`).run(JSON.stringify(n),i,e.id),{...e,value:n,sizeBytes:i}}function
|
|
23
|
+
`).run(JSON.stringify(n),i,e.id),{...e,value:n,sizeBytes:i}}function b(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function V(t,e){let n=[],i=[];t.sourceKind&&(n.push("source_kind = ?"),i.push(t.sourceKind)),t.mimePrefix&&(n.push("mime LIKE ? ESCAPE '\\'"),i.push(t.mimePrefix.replace(/[\\%_]/g,"\\$&")+"%")),t.roleId&&(n.push("role_id = ?"),i.push(t.roleId)),t.taskId&&(n.push("task_id = ?"),i.push(t.taskId)),t.executionId&&(n.push("execution_id = ?"),i.push(t.executionId)),t.chatSessionId&&(n.push("chat_session_id = ?"),i.push(t.chatSessionId)),t.from!==void 0&&(n.push("created_at >= ?"),i.push(t.from)),t.to!==void 0&&(n.push("created_at <= ?"),i.push(t.to)),t.deliveryStatus&&(n.push("(EXISTS (SELECT 1 FROM delivery_log dl WHERE dl.status = ? AND (dl.task_id = artifacts.task_id OR dl.task_id = artifacts.execution_id)))"),i.push(t.deliveryStatus));let r=n.length?"WHERE "+n.join(" AND "):"",c=o(),s=c.prepare(`SELECT COUNT(*) AS n FROM artifacts ${r}`).get(...i);return{artifacts:c.prepare(`SELECT * FROM artifacts ${r} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...i,e.limit,e.offset).map(u),total:s.n}}var C,w=R(()=>{k();C=/^[\p{L}0-9._-]{1,256}$/u});export{T as a,H as b,L as c,P as d,h as e,v as f,K as g,z as h,N as i,W as j,$ as k,j as l,B as m,q as n,U as o,J as p,Y as q,V as r,w as s};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{F as R,L as E}from"./chunk-
|
|
1
|
+
import{F as R,L as E}from"./chunk-3JTHJ3FZ.js";import{d as h,i as A}from"./chunk-ITVCPC7G.js";import{c as y,h as V}from"./chunk-EZLBMUQD.js";import{b as v}from"./chunk-5PELJRUQ.js";import{readFileSync as P,writeFileSync as I,existsSync as b}from"fs";import{join as x}from"path";function k(n){let e=x(m(n),".env");if(!b(e))return null;let s=P(e,"utf-8"),r={};for(let c of s.split(`
|
|
2
2
|
`)){let t=c.trim();if(!t||t.startsWith("#"))continue;let i=t.startsWith("export ")?t.slice(7).trim():t,a=i.indexOf("=");if(a===-1)continue;let d=i.slice(0,a).trim(),o=i.slice(a+1).trim();(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),!(o.includes("$")&&(o=o.replace(/\$\{(\w+)\}|\$(\w+)/g,(f,l,u)=>{let g=l??u;return r[g]??process.env[g]??""}),!o))&&(r[d]=o)}return r}function W(n,e){let s=k(n);if(!s)return e;let r={...e},c=0;for(let[t,i]of Object.entries(s)){if(t.startsWith("ANTHROPIC_")){$.warn({roleName:n,key:t},"Role .env contains ANTHROPIC_* key; ignored (managed globally)");continue}t in r||(r[t]=i,c++)}return c>0&&$.info({roleName:n,seeded:c},"Seeded role envVars from .env file"),Object.keys(r).length>0?r:void 0}function U(n,e){let s=k(n);if(!s)return[];let r=e??{},c=[];for(let[t,i]of Object.entries(s)){if(t.startsWith("ANTHROPIC_"))continue;let a=r[t]??"";a!==i&&c.push({envKey:t,dbValue:a,envValue:i})}for(let[t,i]of Object.entries(r))t in s||c.push({envKey:t,dbValue:i,envValue:""});return c}function q(n,e){let s=x(m(n),".env"),r=e??{},c=[],t=new Set;if(b(s)){let a=P(s,"utf-8");for(let d of a.split(`
|
|
3
3
|
`)){let o=d.trim();if(!o||o.startsWith("#")){c.push(d);continue}let f=o.startsWith("export ")?o.slice(7).trim():o,l=f.indexOf("=");if(l===-1){c.push(d);continue}let u=f.slice(0,l).trim(),g=o.startsWith("export ")?"export ":"";u in r&&(c.push(`${g}${u}=${r[u]}`),t.add(u))}}let i=0;for(let[a,d]of Object.entries(r)){if(t.has(a)){i++;continue}d&&d.length>0&&(c.push(`${a}=${d}`),i++)}return I(s,c.join(`
|
|
4
4
|
`)+`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{h as c}from"./chunk-
|
|
1
|
+
import{h as c}from"./chunk-AKQ3AFVI.js";import{K as u,L as p}from"./chunk-3JTHJ3FZ.js";import{o as s,q as f}from"./chunk-ZEGZ2I35.js";f();p();function r(e){return{id:e.id,roleId:e.role_id,content:e.content,isAnti:e.is_anti===1,evidenceObsIds:e.evidence_obs_ids?JSON.parse(e.evidence_obs_ids):[],embedding:e.embedding?new Float32Array(e.embedding.buffer,e.embedding.byteOffset,e.embedding.byteLength/4):void 0,supersededBy:e.superseded_by??void 0,createdAt:e.created_at,lastUsedAt:e.last_used_at,lastValidatedAt:e.last_validated_at,scopeKey:e.scope_key??void 0,status:e.status,successEma:e.success_ema??void 0,injectCount:e.inject_count??0}}function _(e){return Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function g(e){let t=s(),n=e.lastUsedAt??u(e.roleId);t.prepare(`
|
|
2
2
|
INSERT INTO beliefs (id, role_id, content,
|
|
3
3
|
is_anti, evidence_obs_ids, embedding, superseded_by,
|
|
4
4
|
created_at, last_used_at, last_validated_at,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{D as M,L as D}from"./chunk-
|
|
1
|
+
import{D as M,L as D}from"./chunk-3JTHJ3FZ.js";import{o as u,q as O}from"./chunk-ZEGZ2I35.js";O();D();function E(e){return{id:e.id,roleId:e.role_id,type:e.type,content:e.content,embedding:e.embedding?new Float32Array(e.embedding.buffer,e.embedding.byteOffset,e.embedding.byteLength/4):void 0,keywords:e.keywords?JSON.parse(e.keywords):[],importance:e.importance,sourceType:e.source_type,sourceTaskId:e.source_task_id??void 0,evidence:e.evidence?JSON.parse(e.evidence):void 0,createdAt:e.created_at,lastAccessed:e.last_accessed,retrievedCount:e.retrieved_count,tier:e.tier,supersededBy:e.superseded_by??void 0}}function _(e){return Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function I(e){u().prepare(`
|
|
2
2
|
INSERT INTO memories (id, role_id, type, content, embedding, keywords,
|
|
3
3
|
importance, source_type, source_task_id, evidence,
|
|
4
4
|
created_at, last_accessed, retrieved_count, tier, superseded_by)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as w,
|
|
1
|
+
import{d as w,i as S}from"./chunk-ITVCPC7G.js";import{c as g,h as P}from"./chunk-EZLBMUQD.js";P();S();import{readFileSync as v,existsSync as E}from"fs";import{join as p}from"path";import{homedir as R}from"os";var T=g("ws"),x=p(R(),".adam"),f=p(x,"adam.port"),b=p(w,"adam.key");function d(){let n=process.env.ADAM_API_KEY;if(n)return n;if(E(b))return v(b,"utf-8").trim()||void 0}function m(){if(!E(f))return null;let n=parseInt(v(f,"utf-8").trim(),10);return isNaN(n)?null:n}function C(){let n=m();if(!n)throw new Error("Server not running. Run: adam server start");return`http://localhost:${n}`}var u=class extends Error{constructor(e,s){super(s);this.status=e;this.name="ApiError"}status};async function A(n,t={}){let s=`${C()}${n}`,r=d(),o=await fetch(s,{method:t.method||"GET",headers:{"Content-Type":"application/json",...r?{"x-api-key":r}:{},...t.headers},body:t.body?JSON.stringify(t.body):void 0});if(!o.ok){let a=await o.text().catch(()=>"Unknown error");throw new u(o.status,a)}return o.headers.get("content-type")?.includes("application/json")?o.json():o.text()}function D(){return A("/healthz")}var k=class{ws=null;callbacks=new Map;reconnectAttempts=0;reconnectTimer=null;url;constructor(t="/events"){let e=m();if(!e)throw new Error("Server not running. Run: adam server start");let s=d(),r=new URL(`ws://localhost:${e}${t}`);s&&r.searchParams.set("api_key",s),this.url=r.toString()}connect(){return new Promise((t,e)=>{try{this.ws=new WebSocket(this.url),this.ws.onopen=()=>{this.reconnectAttempts=0,t()},this.ws.onmessage=s=>{try{let r=JSON.parse(s.data),{type:o,data:c,...a}=r,i=this.callbacks.get(o);i&&i.forEach(l=>l(c??a))}catch(r){T.error({error:r},"Failed to parse WebSocket message")}},this.ws.onclose=()=>{this.scheduleReconnect()},this.ws.onerror=s=>{e(s)}}catch(s){e(s)}})}scheduleReconnect(){let t=[1e3,2e3,4e3,8e3,15e3],e=t[Math.min(this.reconnectAttempts,t.length-1)];this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>{this.connect().catch(()=>{})},e)}on(t,e){this.callbacks.has(t)||this.callbacks.set(t,new Set),this.callbacks.get(t).add(e)}off(t,e){this.callbacks.get(t)?.delete(e)}close(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.ws?.close()}isConnected(){return this.ws?.readyState===WebSocket.OPEN}},y=class{ws=null;callbacks=new Map;url;constructor(t){let e=m();if(!e)throw new Error("Server not running. Run: adam server start");let s=d(),r=new URL(`ws://localhost:${e}/tasks/${t}/stream`);s&&r.searchParams.set("api_key",s),this.url=r.toString()}connect(){return new Promise((t,e)=>{try{this.ws=new WebSocket(this.url),this.ws.onopen=()=>{t()},this.ws.onmessage=s=>{try{let r=JSON.parse(s.data),{type:o,data:c,...a}=r,i=this.callbacks.get(o);i&&i.forEach(h=>h(c??a));let l=this.callbacks.get("*");l&&l.forEach(h=>h(r))}catch(r){T.error({error:r},"Failed to parse task stream message")}},this.ws.onerror=s=>{e(s)},this.ws.onclose=()=>{}}catch(s){e(s)}})}on(t,e){this.callbacks.has(t)||this.callbacks.set(t,new Set),this.callbacks.get(t).add(e)}off(t,e){this.callbacks.get(t)?.delete(e)}close(){this.ws?.close()}isConnected(){return this.ws?.readyState===WebSocket.OPEN}};export{d as a,A as b,D as c,k as d,y as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{g as He}from"./chunk-VVPB3TD4.js";import{a as Ke,b as k,c as Me,d as B,e as Xe}from"./chunk-NNMQGISW.js";import{b as Je,c as Ye,f as re,g as ie}from"./chunk-5ZL6RHPE.js";import{a as Ve,b as ze,c as E,d as se,e as F,f as xe,g as z,i as Qe}from"./chunk-XEXSXMWK.js";import{e as V}from"./chunk-3MROEPGR.js";import{c as y,h as S}from"./chunk-EZLBMUQD.js";import{z as g}from"zod/v4";import{v4 as Ps}from"uuid";var Ze="__redacted__",rn=/token|secret|password|passwd|api[-_]?key|credential|private[-_]?key|access[-_]?key/i;function an(t){return rn.test(t)}function on(t){if(!t)return{};let e={};for(let[n,r]of Object.entries(t))an(n)&&typeof r=="string"&&r.length>0?e[n]=Ze:e[n]=r;return e}function Q(t){return{...t,config:on(t.config)}}function et(t,e){let n={...t};for(let[r,s]of Object.entries(t))s===Ze&&(e&&r in e?n[r]=e[r]:delete n[r]);return n}import{randomUUID as at}from"crypto";import dn from"crypto";var tt="2.1.7",ae="bot";function un(t){let e=t.split(".").map(i=>parseInt(i,10)),n=e[0]??0,r=e[1]??0,s=e[2]??0;return(n&255)<<16|(r&255)<<8|s&255}var Ce=un(tt),cn=35e3,nt=15e3,ln=1e4;function oe(){return{channel_version:tt}}function mn(t){return t.endsWith("/")?t:`${t}/`}function gn(){let t=dn.randomBytes(4).readUInt32BE(0);return Buffer.from(String(t),"utf-8").toString("base64")}function pn(t){let e={"Content-Type":"application/json",AuthorizationType:"ilink_bot_token","Content-Length":String(Buffer.byteLength(t.body,"utf-8")),"X-WECHAT-UIN":gn(),"iLink-App-Id":ae,"iLink-App-ClientVersion":String(Ce)};return t.token?.trim()&&(e.Authorization=`Bearer ${t.token.trim()}`),t.routeTag&&(e.SKRouteTag=t.routeTag),e}async function de(t){let e=mn(t.baseUrl),n=new URL(t.endpoint,e),r=pn({token:t.token,routeTag:t.routeTag,body:t.body}),s=new AbortController,i=setTimeout(()=>s.abort(),t.timeoutMs);try{let a=await fetch(n.toString(),{method:"POST",headers:r,body:t.body,signal:s.signal});clearTimeout(i);let o=await a.text();if(!a.ok)throw new Error(`${t.label} ${a.status}: ${o}`);return o}catch(a){throw clearTimeout(i),a}}async function st(t){let e=t.timeoutMs??cn;try{let n=await de({baseUrl:t.baseUrl,endpoint:"ilink/bot/getupdates",body:JSON.stringify({get_updates_buf:t.get_updates_buf??"",base_info:oe()}),token:t.token,routeTag:t.routeTag,timeoutMs:e,label:"getUpdates"});return JSON.parse(n)}catch(n){if(n instanceof Error&&n.name==="AbortError")return{ret:0,msgs:[],get_updates_buf:t.get_updates_buf};throw n}}var fn={[-2]:2,[-3]:3},hn=1e3;async function H(t){let e=(await import("./logger-TEZSHFTZ.js")).getLogger("channels"),n=new Map;for(;;){let r=await de({baseUrl:t.baseUrl,endpoint:"ilink/bot/sendmessage",body:JSON.stringify({...t.body,base_info:oe()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??nt,label:"sendMessage"});e.info({status:200,responseBody:r.slice(0,300)},"apiFetch sendMessage response");try{let s=JSON.parse(r);if(s.ret&&s.ret!==0){let i=fn[s.ret],a=(n.get(s.ret)??0)+1;if(n.set(s.ret,a),i!==void 0&&a<i){e.warn({ret:s.ret,attempt:a,maxRetries:i},"sendMessage: retriable iLink error, retrying"),await new Promise(o=>setTimeout(o,hn*a));continue}throw e.error({ret:s.ret,errmsg:s.errmsg,attempt:a},"sendMessage: iLink API error, no more retries"),new Error(`sendMessage failed: iLink ret=${s.ret}${s.errmsg?` errmsg=${s.errmsg}`:""}`)}}catch(s){if(s instanceof SyntaxError)e.warn({rawText:r.slice(0,200)},"sendMessage: non-JSON response, treating as success");else throw s}return}}async function rt(t){await de({baseUrl:t.baseUrl,endpoint:"ilink/bot/sendtyping",body:JSON.stringify({...t.body,base_info:oe()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??ln,label:"sendTyping"})}async function it(t){let e=await de({baseUrl:t.baseUrl,endpoint:"ilink/bot/getuploadurl",body:JSON.stringify({filekey:t.filekey,media_type:t.media_type,to_user_id:t.to_user_id,rawsize:t.rawsize,rawfilemd5:t.rawfilemd5,filesize:t.filesize,thumb_rawsize:t.thumb_rawsize,thumb_rawfilemd5:t.thumb_rawfilemd5,thumb_filesize:t.thumb_filesize,no_need_thumb:t.no_need_thumb,aeskey:t.aeskey,base_info:oe()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??nt,label:"getUploadUrl"});return JSON.parse(e)}var yn=5*6e4,bn=35e3,ot="3",T=new Map;function Se(t){return Date.now()-t.startedAt<yn}function wn(){for(let[t,e]of T)Se(e)||T.delete(t)}async function dt(t,e,n){let r=t.endsWith("/")?t:`${t}/`,s=new URL(`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(e)}`,r),i={"iLink-App-Id":ae};n&&(i.SKRouteTag=n);let a=await fetch(s.toString(),{headers:i});if(!a.ok){let o=await a.text().catch(()=>"(unreadable)");throw new Error(`Failed to fetch QR code: ${a.status} ${a.statusText} body=${o}`)}return await a.json()}async function _n(t,e,n){let r=t.endsWith("/")?t:`${t}/`,s=new URL(`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(e)}`,r),i={"iLink-App-Id":ae,"iLink-App-ClientVersion":String(Ce)};n&&(i.SKRouteTag=n);let a=new AbortController,o=setTimeout(()=>a.abort(),bn);try{let d=await fetch(s.toString(),{headers:i,signal:a.signal});clearTimeout(o);let c=await d.text();if(!d.ok)throw new Error(`Failed to poll QR status: ${d.status} ${d.statusText}`);return JSON.parse(c)}catch(d){if(clearTimeout(o),d instanceof Error&&d.name==="AbortError")return{status:"wait"};throw d}}async function ut(t){let e=t.accountId||at();wn();let n=T.get(e);if(!t.force&&n&&Se(n)&&n.qrcodeUrl)return{qrcodeUrl:n.qrcodeUrl,message:"QR code ready. Scan with WeChat.",sessionKey:e};if(!t.apiBaseUrl)return{message:"No baseUrl configured for this WeChat channel.",sessionKey:e};try{let r=t.botType||ot,s=await dt(t.apiBaseUrl,r,t.routeTag),i={sessionKey:e,id:at(),qrcode:s.qrcode,qrcodeUrl:s.qrcode_img_content,startedAt:Date.now()};return T.set(e,i),{qrcodeUrl:s.qrcode_img_content,message:"Scan the QR code with WeChat to connect.",sessionKey:e}}catch(r){return{message:`Failed to start login: ${String(r)}`,sessionKey:e}}}var In=3;async function ct(t){let e=T.get(t.sessionKey);if(!e)return{connected:!1,message:"No active login session. Start QR login first."};if(!Se(e))return T.delete(t.sessionKey),{connected:!1,message:"QR code expired. Please start again."};let n=Math.max(t.timeoutMs??48e4,1e3),r=Date.now()+n,s=1;for(;Date.now()<r;){try{let i=await _n(t.apiBaseUrl,e.qrcode,t.routeTag);switch(e.status=i.status,i.status){case"wait":break;case"scaned":break;case"expired":{if(s++,s>In)return T.delete(t.sessionKey),{connected:!1,message:"Login timeout: QR expired multiple times."};try{let a=t.botType||ot,o=await dt(t.apiBaseUrl,a,t.routeTag);e.qrcode=o.qrcode,e.qrcodeUrl=o.qrcode_img_content,e.startedAt=Date.now()}catch(a){return T.delete(t.sessionKey),{connected:!1,message:`QR refresh failed: ${String(a)}`}}break}case"confirmed":return i.ilink_bot_id?(T.delete(t.sessionKey),{connected:!0,botToken:i.bot_token,accountId:i.ilink_bot_id,baseUrl:i.baseurl,userId:i.ilink_user_id,message:"Connected to WeChat successfully!"}):(T.delete(t.sessionKey),{connected:!1,message:"Login failed: server did not return bot ID."})}}catch(i){return T.delete(t.sessionKey),{connected:!1,message:`Login failed: ${String(i)}`}}await new Promise(i=>setTimeout(i,1e3))}return T.delete(t.sessionKey),{connected:!1,message:"Login timeout. Please try again."}}import R from"fs";import*as M from"fs/promises";import x from"path";import{homedir as fe}from"os";var ue={IMAGE:1,VIDEO:2,FILE:3,VOICE:4},K={NONE:0,USER:1,BOT:2},_={NONE:0,TEXT:1,IMAGE:2,VOICE:3,FILE:4,VIDEO:5},X={NEW:0,GENERATING:1,FINISH:2},lt={TYPING:1,CANCEL:2};S();var En=y("channels"),Re=-14,ce=3600*1e3,$=new Map;function mt(t){let e=Date.now()+ce;$.set(t,e),En.info({channelId:t},`Session paused until ${new Date(e).toISOString()} (${ce/1e3}s)`)}function le(t){let e=$.get(t);return e===void 0?!1:Date.now()>=e?($.delete(t),!1):!0}function gt(t){let e=$.get(t);if(e===void 0)return 0;let n=e-Date.now();return n<=0?($.delete(t),0):n}function pt(t){$.delete(t)}S();import*as ge from"fs/promises";import Tt from"path";import{homedir as Sn}from"os";import{createCipheriv as Tn,createDecipheriv as xn}from"crypto";function ft(t,e){let n=Tn("aes-128-ecb",e,null);return Buffer.concat([n.update(t),n.final()])}function ht(t,e){let n=xn("aes-128-ecb",e,null);return Buffer.concat([n.update(t),n.final()])}function yt(t){return Math.ceil((t+1)/16)*16}function Ae(t,e){return`${e}/download?encrypted_query_param=${encodeURIComponent(t)}`}function bt(t){return`${t.cdnBaseUrl}/upload?encrypted_query_param=${encodeURIComponent(t.uploadParam)}&filekey=${encodeURIComponent(t.filekey)}`}S();var Xs=y("channels");function Mn(t){let e=Buffer.from(t,"base64");if(e.length===16)return e;if(e.length===32&&/^[0-9a-fA-F]{32}$/.test(e.toString("ascii")))return Buffer.from(e.toString("ascii"),"hex");throw new Error(`aes_key must decode to 16 raw bytes or 32-char hex, got ${e.length} bytes`)}async function wt(t){let e=await fetch(t);if(!e.ok)throw new Error(`CDN download ${e.status} ${e.statusText}`);return Buffer.from(await e.arrayBuffer())}async function J(t){let{encryptQueryParam:e,aesKeyBase64:n,cdnBaseUrl:r,fullUrl:s}=t,i=Mn(n),a=s?.trim()||(e?Ae(e,r):null);if(!a)throw new Error("CDN download: need full_url or encrypt_query_param");let o=await wt(a);return ht(o,i)}async function _t(t){let{encryptQueryParam:e,cdnBaseUrl:n,fullUrl:r}=t,s=r?.trim()||(e?Ae(e,n):null);if(!s)throw new Error("CDN download: need full_url or encrypt_query_param");return wt(s)}S();var me=y("channels"),It=24e3;function Cn(t,e){let n=t.byteLength,r=44+n,s=Buffer.allocUnsafe(r),i=0;return s.write("RIFF",i),i+=4,s.writeUInt32LE(r-8,i),i+=4,s.write("WAVE",i),i+=4,s.write("fmt ",i),i+=4,s.writeUInt32LE(16,i),i+=4,s.writeUInt16LE(1,i),i+=2,s.writeUInt16LE(1,i),i+=2,s.writeUInt32LE(e,i),i+=4,s.writeUInt32LE(e*2,i),i+=4,s.writeUInt16LE(2,i),i+=2,s.writeUInt16LE(16,i),i+=2,s.write("data",i),i+=4,s.writeUInt32LE(n,i),i+=4,Buffer.from(t.buffer,t.byteOffset,t.byteLength).copy(s,i),s}async function Et(t){try{let{decode:e}=await import("silk-wasm");me.debug(`silkToWav: decoding ${t.length} bytes of SILK`);let n=await e(t,It);me.debug(`silkToWav: decoded duration=${n.duration}ms pcmBytes=${n.data.byteLength}`);let r=Cn(n.data,It);return me.debug(`silkToWav: WAV size=${r.length}`),r}catch(e){return me.warn(`silkToWav: transcode failed, will use raw silk err=${String(e)}`),null}}var N=y("channels"),xt=100*1024*1024;function Rn(t){return ie(t)??".bin"}async function Y(t,e,n,r,s=xt,i){if(t.length>s)throw new Error(`Media too large: ${t.length} bytes exceeds ${s} bytes`);let a=Tt.join(Sn(),".adam","wechat","media",r,n);await ge.mkdir(a,{recursive:!0});let o;if(i&&/^[a-zA-Z0-9._-]+$/.test(i))o=i;else{let c=e?Rn(e):".bin",u=Date.now(),p=Math.random().toString(36).slice(2,7);o=`${u}-${p}${c}`}let d=Tt.join(a,o);return await ge.writeFile(d,t),N.debug(`saveMedia: saved ${t.length} bytes to ${d}`),d}async function Mt(t,e){let{cdnBaseUrl:n,channelId:r}=e;if(t.type===_.IMAGE){let s=t.image_item;if(!s?.media?.encrypt_query_param&&!s?.media?.full_url)return null;let i=s.aeskey?Buffer.from(s.aeskey,"hex").toString("base64"):s.media?.aes_key;try{let a=i?await J({encryptQueryParam:s.media?.encrypt_query_param,aesKeyBase64:i,cdnBaseUrl:n,fullUrl:s.media?.full_url}):await _t({encryptQueryParam:s.media?.encrypt_query_param,cdnBaseUrl:n,fullUrl:s.media?.full_url});return{path:await Y(a,"image/png","inbound",r),mimeType:"image/png",type:"image"}}catch(a){return N.error({channelId:r},`Image download/decrypt failed: ${String(a)}`),null}}if(t.type===_.VOICE){let s=t.voice_item;if(!s?.media?.encrypt_query_param&&!s?.media?.full_url||!s?.media?.aes_key)return null;try{let i=await J({encryptQueryParam:s.media.encrypt_query_param,aesKeyBase64:s.media.aes_key,cdnBaseUrl:n,fullUrl:s.media.full_url}),a=await Et(i);if(a){let o=await Y(a,"audio/wav","inbound",r);return N.debug(`Voice: saved WAV to ${o}`),{path:o,mimeType:"audio/wav",type:"audio"}}else{let o=await Y(i,"audio/silk","inbound",r);return N.debug(`Voice: silk transcode unavailable, saved raw SILK to ${o}`),{path:o,mimeType:"audio/silk",type:"audio"}}}catch(i){return N.error({channelId:r},`Voice download/transcode failed: ${String(i)}`),null}}if(t.type===_.FILE){let s=t.file_item;if(!s?.media?.encrypt_query_param&&!s?.media?.full_url||!s?.media?.aes_key)return null;try{let i=await J({encryptQueryParam:s.media.encrypt_query_param,aesKeyBase64:s.media.aes_key,cdnBaseUrl:n,fullUrl:s.media.full_url}),a=re(s.file_name??"file.bin");return{path:await Y(i,a,"inbound",r,xt,s.file_name),mimeType:a,type:"file"}}catch(i){return N.error({channelId:r},`File download failed: ${String(i)}`),null}}if(t.type===_.VIDEO){let s=t.video_item;if(!s?.media?.encrypt_query_param&&!s?.media?.full_url||!s?.media?.aes_key)return null;try{let i=await J({encryptQueryParam:s.media.encrypt_query_param,aesKeyBase64:s.media.aes_key,cdnBaseUrl:n,fullUrl:s.media.full_url});return{path:await Y(i,"video/mp4","inbound",r),mimeType:"video/mp4",type:"video"}}catch(i){return N.error({channelId:r},`Video download failed: ${String(i)}`),null}}return null}import Rt from"path";import ke from"crypto";import An from"fs/promises";S();var O=y("channels"),pe=3;async function kn(t){let{buf:e,uploadFullUrl:n,uploadParam:r,filekey:s,cdnBaseUrl:i,label:a,aeskey:o}=t,d=ft(e,o),c=n?.trim(),u;if(c)u=c;else if(r)u=bt({cdnBaseUrl:i,uploadParam:r,filekey:s});else throw new Error(`${a}: CDN upload URL missing (need upload_full_url or upload_param)`);O.debug(`${a}: CDN POST url=${u} ciphertextSize=${d.length}`);let p,f;for(let m=1;m<=pe;m++)try{let l=await fetch(u,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:new Uint8Array(d)});if(l.status>=400&&l.status<500){let b=l.headers.get("x-error-message")??await l.text();throw O.error(`${a}: CDN client error attempt=${m} status=${l.status} errMsg=${b}`),new Error(`CDN upload client error ${l.status}: ${b}`)}if(l.status!==200){let b=l.headers.get("x-error-message")??`status ${l.status}`;throw O.error(`${a}: CDN server error attempt=${m} status=${l.status} errMsg=${b}`),new Error(`CDN upload server error: ${b}`)}if(p=l.headers.get("x-encrypted-param")??void 0,!p)throw O.error(`${a}: CDN response missing x-encrypted-param header attempt=${m}`),new Error("CDN upload response missing x-encrypted-param header");O.debug(`${a}: CDN upload success attempt=${m}`);break}catch(l){if(f=l,l instanceof Error&&l.message.includes("client error"))throw l;m<pe?O.warn(`${a}: attempt ${m} failed, retrying... err=${String(l)}`):O.error(`${a}: all ${pe} attempts failed err=${String(l)}`)}if(!p)throw f instanceof Error?f:new Error(`CDN upload failed after ${pe} attempts`);return{downloadParam:p}}async function Pe(t){let{filePath:e,toUserId:n,opts:r,cdnBaseUrl:s,mediaType:i,label:a}=t,o=await An.readFile(e),d=o.length,c=ke.createHash("md5").update(o).digest("hex"),u=yt(d),p=ke.randomBytes(16).toString("hex"),f=ke.randomBytes(16);O.debug(`${a}: file=${e} rawsize=${d} filesize=${u} md5=${c} filekey=${p}`);let m=await it({...r,filekey:p,media_type:i,to_user_id:n,rawsize:d,rawfilemd5:c,filesize:u,no_need_thumb:!0,aeskey:f.toString("hex")}),l=m.upload_full_url?.trim(),b=m.upload_param;if(!l&&!b)throw new Error(`${a}: getUploadUrl returned no upload URL (need upload_full_url or upload_param)`);let{downloadParam:L}=await kn({buf:o,uploadFullUrl:l||void 0,uploadParam:b??void 0,filekey:p,cdnBaseUrl:s,aeskey:f,label:`${a}[orig filekey=${p}]`});return{filekey:p,downloadEncryptedQueryParam:L,aeskey:f.toString("hex"),fileSize:d,fileSizeCiphertext:u}}async function Ct(t){return Pe({...t,mediaType:ue.IMAGE,label:"uploadImageToWeixin"})}async function St(t){return Pe({...t,mediaType:ue.VIDEO,label:"uploadVideoToWeixin"})}async function Ue(t){return Pe({...t,mediaType:ue.FILE,label:"uploadFileAttachmentToWeixin"})}S();var Z=y("channels");function Pn(){return`adam-wechat-${Date.now()}-${Math.random().toString(36).slice(2,7)}`}function Un(t){let e=t;return e=e.replace(/```[^\n]*\n?([\s\S]*?)```/g,(n,r)=>r.trim()),e=e.replace(/!\[[^\]]*\]\([^)]*\)/g,""),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/^\|[\s:|-]+\|$/gm,""),e=e.replace(/^\|(.+)\|$/gm,(n,r)=>r.split("|").map(s=>s.trim()).join(" ")),e}async function ve(t){let{to:e,text:n,mediaItem:r,opts:s,label:i}=t,a=[],o=Un(n);o&&a.push({type:_.TEXT,text_item:{text:o}}),a.push(r);let d="";for(let c of a){d=Pn();let u={msg:{from_user_id:"",to_user_id:e,client_id:d,message_type:K.BOT,message_state:X.FINISH,item_list:[c],context_token:s.contextToken}};await H({baseUrl:s.baseUrl,token:s.token,routeTag:s.routeTag,body:u})}return Z.debug(`${i}: sent to=${e} messageId=${d}`),{messageId:d}}async function vn(t){let{to:e,text:n,uploaded:r,opts:s}=t,i={type:_.IMAGE,image_item:{media:{encrypt_query_param:r.downloadEncryptedQueryParam,aes_key:Buffer.from(r.aeskey).toString("base64"),encrypt_type:1},mid_size:r.fileSizeCiphertext}};return ve({to:e,text:n,mediaItem:i,opts:s,label:"sendImageMessage"})}async function On(t){let{to:e,text:n,uploaded:r,opts:s}=t,i={type:_.VIDEO,video_item:{media:{encrypt_query_param:r.downloadEncryptedQueryParam,aes_key:Buffer.from(r.aeskey).toString("base64"),encrypt_type:1},video_size:r.fileSizeCiphertext}};return ve({to:e,text:n,mediaItem:i,opts:s,label:"sendVideoMessage"})}async function At(t){let{to:e,text:n,fileName:r,uploaded:s,opts:i}=t,a={type:_.FILE,file_item:{media:{encrypt_query_param:s.downloadEncryptedQueryParam,aes_key:Buffer.from(s.aeskey).toString("base64"),encrypt_type:1},file_name:r,len:String(s.fileSize)}};return ve({to:e,text:n,mediaItem:a,opts:i,label:"sendFileMessage"})}async function kt(t){let{filePath:e,to:n,text:r,opts:s,cdnBaseUrl:i}=t,a=re(e),o={baseUrl:s.baseUrl,token:s.token,routeTag:s.routeTag};if(a.startsWith("video/")){Z.debug(`sendWeixinMediaFile: uploading video filePath=${e} to=${n}`);let u=await St({filePath:e,toUserId:n,opts:o,cdnBaseUrl:i});return On({to:n,text:r,uploaded:u,opts:s})}if(a.startsWith("image/")){Z.debug(`sendWeixinMediaFile: uploading image filePath=${e} to=${n}`);let u=await Ct({filePath:e,toUserId:n,opts:o,cdnBaseUrl:i});return vn({to:n,text:r,uploaded:u,opts:s})}if(a.startsWith("audio/")){let u=Rt.basename(e);Z.debug(`sendWeixinMediaFile: uploading audio as file filePath=${e} name=${u} to=${n}`);let p=await Ue({filePath:e,fileName:u,toUserId:n,opts:o,cdnBaseUrl:i});return At({to:n,text:r,fileName:u,uploaded:p,opts:s})}let d=Rt.basename(e);Z.debug(`sendWeixinMediaFile: uploading file attachment filePath=${e} name=${d} to=${n}`);let c=await Ue({filePath:e,fileName:d,toUserId:n,opts:o,cdnBaseUrl:i});return At({to:n,text:r,fileName:d,uploaded:c,opts:s})}S();var h=y("channels"),Pt="https://novac2c.cdn.weixin.qq.com/c2c",De=new Map;function Ot(t){return x.join(fe(),".adam","wechat",`${t}.context-tokens.json`)}function Nn(t){let e=Ot(t);try{let n=R.readFileSync(e,"utf-8"),r=JSON.parse(n);for(let[s,i]of Object.entries(r))typeof i=="string"&&i&&De.set(`${t}:${s}`,i);h.debug({channelId:t,count:Object.keys(r).length},"Restored context tokens from disk")}catch{}}function Dn(t,e,n){let r=Ot(t);try{let s={};try{let a=R.readFileSync(r,"utf-8");s=JSON.parse(a)}catch{}s[e]=n;let i=x.dirname(r);R.mkdirSync(i,{recursive:!0}),R.writeFileSync(r,JSON.stringify(s),"utf-8")}catch(s){h.warn({channelId:t,userId:e},`Failed to persist context token: ${String(s)}`)}}function Ln(t,e,n){De.set(`${t}:${e}`,n),Dn(t,e,n)}function Oe(t,e){return De.get(`${t}:${e}`)}function Nt(t){return x.join(fe(),".adam","wechat",`${t}.sync`)}function Fn(t){try{return R.readFileSync(Nt(t),"utf-8")}catch{return""}}function Bn(t,e){let n=Nt(t);R.mkdirSync(x.dirname(n),{recursive:!0}),R.writeFileSync(n,e,"utf-8")}var Ne=1440*60*1e3,Ut=10,$n=20,vt=1440*60*1e3,qn=1320*60*1e3,Gn=1,Wn=7200*1e3;function Dt(t){return x.join(fe(),".adam","wechat",`${t}.session.json`)}function jn(t){let e=new Map,n=Dt(t);try{let r=R.readFileSync(n,"utf-8"),s=JSON.parse(r);for(let[i,a]of Object.entries(s))a&&typeof a.lastUserMessageAt=="number"&&e.set(i,a);h.debug({channelId:t,count:e.size},"Restored sessions from disk")}catch{}return e}function ee(t,e){let n=Dt(t);try{let r={};for(let[i,a]of e)r[i]=a;let s=x.dirname(n);R.mkdirSync(s,{recursive:!0}),R.writeFileSync(n,JSON.stringify(r),"utf-8")}catch(r){h.warn({channelId:t},`Failed to persist sessions: ${String(r)}`)}}var Vn=0;function te(){return`adam-wechat-${Date.now()}-${++Vn}`}var q=class{platform="wechat";id;config;status="disconnected";messageHandler=null;pollAbort=null;getUpdatesBuf="";sessions=new Map;pendingQueue=new Map;lastReminderAt=new Map;constructor(e,n){if(this.id=e,!n.baseUrl)throw new Error("WeChat adapter requires baseUrl");this.config=n}async connect(){if(!this.config.botToken)throw new Error("WeChat adapter requires botToken. Complete QR login first.");this.status="connecting",this.getUpdatesBuf=Fn(this.id),Nn(this.id),this.sessions=jn(this.id),this.pollAbort=new AbortController,this.status="connected",h.info({channelId:this.id},"WeChat adapter connected, starting long-poll"),this.startLongPoll()}async disconnect(){this.pollAbort&&(this.pollAbort.abort(),this.pollAbort=null),this.status="disconnected",h.info({channelId:this.id},"WeChat adapter disconnected")}getStatus(){if(this.status==="connected"&&le(this.id))return"error";if(this.status==="connected"){for(let[,e]of this.sessions)if(this.isSessionActive(e)&&e.quotaRemaining<=0)return"degraded"}return this.status}getCapabilities(){return{canEdit:!1,canQuote:!0,canParseQuote:!0,canInlineButtons:!1,maxTextLength:4e3,supportsAttachments:!0,maxAttachmentsPerMessage:1}}async sendMessage(e,n){if(le(this.id)){let c=Math.ceil(gt(this.id)/6e4);throw new Error(`WeChat session paused, ${c} min remaining. Re-scan QR to reconnect.`)}let r=this.getOrCreateSession(e),i=this.getSessionRemainingMs(r)/36e5;if(!this.isSessionActive(r))return h.warn({channelId:this.id,chatId:e.slice(0,12),lastUserMessageAt:r.lastUserMessageAt,sessionExpired:!0},"iLink session expired (>24h), message queued"),this.enqueueMessage(e,n),`queued-${te()}`;if(r.quotaRemaining<=0)return h.warn({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:0,remainingHours:i.toFixed(1)},"iLink quota exhausted, message queued"),this.enqueueMessage(e,n),`queued-${te()}`;let a=te(),o=Oe(this.id,e),d=this.config.cdnBaseUrl??Pt;try{let c=n.attachments?.[0],u=c?.path??n.mediaUrl,p=c?.contentType,f=c?.filename,m=c?.mediaType??n.mediaType;if(u){let l=!u.includes("://")||u.startsWith("file://"),b=x.join(fe(),".adam","wechat","media","outbound-tmp");await M.mkdir(b,{recursive:!0});let L=this.getExtensionFromMediaType(m,p),A;if(l){let I=u.startsWith("file://")?new URL(u).pathname:x.isAbsolute(u)?u:x.resolve(u),v=await M.readFile(I);A=x.join(b,`${Date.now()}-${Math.random().toString(36).slice(2,7)}${L}`),await M.writeFile(A,v)}else{let I=await fetch(u);if(!I.ok)throw new Error(`Failed to fetch media: ${I.status}`);let v=Buffer.from(await I.arrayBuffer());A=x.join(b,`${Date.now()}-${Math.random().toString(36).slice(2,7)}${L}`),await M.writeFile(A,v)}let w=A;if(f){let I=f.replace(/[\\/]/g,"-").replace(/\.\./g,"-").replace(/[\x00-\x1f]/g,"");if(I.length>0&&I.length<200){let v=x.join(b,`${Date.now()}-${I}`);await M.copyFile(A,v),await M.unlink(A).catch(()=>{}),w=v}}let U=await kt({filePath:w,to:e,text:n.content??"",opts:{baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,contextToken:o},cdnBaseUrl:d});return await M.unlink(w).catch(()=>{}),r.quotaRemaining--,ee(this.id,this.sessions),h.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:r.quotaRemaining,sessionRemainingHours:(this.getSessionRemainingMs(r)/36e5).toFixed(1)},"iLink send success: quota decremented"),this.checkAndSendReminder(e,r).catch(I=>{h.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(I)}`)}),U.messageId}return await H({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{msg:{from_user_id:"",to_user_id:e,client_id:a,message_type:K.BOT,message_state:X.FINISH,item_list:this.buildItemList(n),context_token:o}}}),r.quotaRemaining--,ee(this.id,this.sessions),h.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:r.quotaRemaining,sessionRemainingHours:(this.getSessionRemainingMs(r)/36e5).toFixed(1)},"iLink send success: quota decremented"),this.checkAndSendReminder(e,r).catch(l=>{h.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(l)}`)}),a}catch(c){if(c instanceof Error&&c.message.includes("ret=-2"))return r.quotaRemaining=0,ee(this.id,this.sessions),h.warn({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:0},"iLink quota exhausted (ret=-2 confirmed), message queued"),this.enqueueMessage(e,n),`queued-${te()}`;throw c}}onMessage(e){this.messageHandler=e}async sendTypingIndicator(e){if(le(this.id))return;let n=Oe(this.id,e);try{await rt({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{ilink_user_id:e,status:lt.TYPING}})}catch{}}updateConfig(e){Object.assign(this.config,e)}buildItemList(e){if(!e.content)return;let n={type:_.TEXT,text_item:{text:e.content}};if(e.replyToMessageId){let r=(e.quoteExcerpt??"").slice(0,80);n.ref_msg={message_item:{msg_id:e.replyToMessageId,text_item:{text:r}},title:e.quoteTitle}}return[n]}getOrCreateSession(e){let n=this.sessions.get(e);return n||(n={lastUserMessageAt:0,quotaRemaining:0},this.sessions.set(e,n)),n}isSessionActive(e){return e.lastUserMessageAt>0&&Date.now()-e.lastUserMessageAt<=Ne}getSessionRemainingMs(e){return e.lastUserMessageAt===0?0:Math.max(0,Ne-(Date.now()-e.lastUserMessageAt))}enqueueMessage(e,n){let r=this.pendingQueue.get(e);r||(r=[],this.pendingQueue.set(e,r));let s=Date.now();r=r.filter(i=>s-i.queuedAt<vt),r.length>=$n&&(r.shift(),h.warn({channelId:this.id,chatId:e.slice(0,12)},"Queue full, dropping oldest message")),r.push({message:n,queuedAt:s}),this.pendingQueue.set(e,r),h.info({channelId:this.id,chatId:e.slice(0,12),queueDepth:r.length},"Message enqueued")}async flushQueue(e){let n=this.pendingQueue.get(e);if(!n||n.length===0)return;let r=this.getOrCreateSession(e),s=Math.min(n.length,Math.max(0,r.quotaRemaining-2));if(s<=0){h.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:r.quotaRemaining},"Queue flush skipped: insufficient quota (reserving 2 for conversation)");return}h.info({channelId:this.id,chatId:e.slice(0,12),queueDepth:n.length,sending:s,quotaRemaining:r.quotaRemaining},"Flushing queued messages");let i=0;for(;i<s&&n.length>0;){let a=n[0];if(Date.now()-a.queuedAt>vt){n.shift();continue}try{if(await this.sendMessage(e,a.message),n.shift(),i++,r.quotaRemaining<=0)break}catch{h.warn({channelId:this.id,chatId:e.slice(0,12)},"Queue flush: send failed, stopping");break}}n.length===0&&this.pendingQueue.delete(e),h.info({channelId:this.id,chatId:e.slice(0,12),sent:i,remaining:n.length},"Queue flush complete")}async checkAndSendReminder(e,n){let r=Date.now(),s=this.lastReminderAt.get(e)??0;if(r-s<Wn)return;let i=this.getSessionRemainingMs(n),o=r-n.lastUserMessageAt>=qn,d=n.quotaRemaining<=Gn;if(!o&&!d)return;let c=(i/36e5).toFixed(1),u;o&&d?u=`[\u7CFB\u7EDF\u63D0\u9192] \u6D88\u606F\u7A97\u53E3\u5373\u5C06\u5173\u95ED\uFF08\u5269\u4F59${c}\u5C0F\u65F6/${n.quotaRemaining}\u6761\u914D\u989D\uFF09\u3002\u8BF7\u56DE\u590D\u4EFB\u610F\u6D88\u606F\u4EE5\u4FDD\u6301\u8FDE\u63A5\u3002`:o?u=`[\u7CFB\u7EDF\u63D0\u9192] \u6D88\u606F\u7A97\u53E3\u5373\u5C06\u5173\u95ED\uFF08\u5269\u4F59${c}\u5C0F\u65F6\uFF09\u3002\u8BF7\u56DE\u590D\u4EFB\u610F\u6D88\u606F\u4EE5\u4FDD\u6301\u8FDE\u63A5\u3002`:u=`[\u7CFB\u7EDF\u63D0\u9192] \u6D88\u606F\u914D\u989D\u5373\u5C06\u7528\u5B8C\uFF08\u5269\u4F59${n.quotaRemaining}\u6761\uFF09\u3002\u8BF7\u56DE\u590D\u4EFB\u610F\u6D88\u606F\u4EE5\u91CD\u7F6E\u914D\u989D\u3002`;let p=Oe(this.id,e);try{await H({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{msg:{from_user_id:"",to_user_id:e,client_id:te(),message_type:K.BOT,message_state:X.FINISH,item_list:[{type:_.TEXT,text_item:{text:u}}],context_token:p}}}),n.quotaRemaining--,this.lastReminderAt.set(e,r),ee(this.id,this.sessions),h.info({channelId:this.id,chatId:e.slice(0,12),remainingHours:c,quotaRemaining:n.quotaRemaining,trigger:o?"time":"quota"},"iLink session reminder sent")}catch(f){h.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(f)}`)}}async startLongPoll(){let e=this.pollAbort?.signal,n=0,r=3,s=3e4,i=2e3;for(;!e?.aborted;)try{let a=await st({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,get_updates_buf:this.getUpdatesBuf});if(a.ret===Re||a.errcode===Re){mt(this.id),this.status="error",h.error({channelId:this.id},"Session expired (errcode=-14), pausing for 1 hour"),await this.sleep(ce,e),pt(this.id),this.status="connected";continue}if(a.ret!==void 0&&a.ret!==0||a.errcode!==void 0&&a.errcode!==0){n++,h.error({channelId:this.id,ret:a.ret,errcode:a.errcode},"getUpdates API error"),n>=r?(n=0,await this.sleep(s,e)):await this.sleep(i,e);continue}n=0,a.get_updates_buf&&(this.getUpdatesBuf=a.get_updates_buf,Bn(this.id,a.get_updates_buf));for(let d of a.msgs??[])await this.processInbound(d)}catch(a){if(e?.aborted)return;n++,h.error({channelId:this.id,error:a},"getUpdates error"),n>=r?(n=0,await this.sleep(s,e)):await this.sleep(i,e)}}async processInbound(e){if(!this.messageHandler)return;let n=!!e.group_id,r=n?e.group_id:e.from_user_id??"",s=e.from_user_id??"";e.context_token&&r&&Ln(this.id,r,e.context_token);let i=this.getOrCreateSession(r),a=i.quotaRemaining;i.lastUserMessageAt=Date.now(),i.quotaRemaining=Ut,ee(this.id,this.sessions),h.info({channelId:this.id,chatId:r.slice(0,12),quotaReset:!0,prevQuota:a,newQuota:Ut,sessionWindowMs:Ne},"iLink session reset: user message received, quota restored"),this.flushQueue(r);let o="",d,c=[],u;for(let m of e.item_list??[]){let l=m.ref_msg?.message_item?.msg_id;if(l){u=l;break}}for(let m of e.item_list??[])m.type===_.TEXT&&m.text_item?.text&&(o+=m.text_item.text),m.type===_.IMAGE&&(d="image",c.push(m)),m.type===_.VOICE&&(d="audio",c.push(m),m.voice_item?.text&&!o&&(o=m.voice_item.text)),m.type===_.FILE&&(d="file",c.push(m)),m.type===_.VIDEO&&(d="video",c.push(m));if(!o&&!d)return;let p;if(c.length>0){let m=this.config.cdnBaseUrl??Pt;try{let l=await Mt(c[0],{cdnBaseUrl:m,channelId:this.id});l&&(p=l.path,d=l.type)}catch(l){h.error({channelId:this.id},`Media download failed: ${String(l)}`)}}let f={channelId:this.id,platform:"wechat",chatId:r,senderId:s,content:o,mediaType:d,mediaPath:p,isGroup:n,timestamp:e.create_time_ms??Date.now(),raw:e,...u?{quotedPlatformMessageId:u}:{}};this.messageHandler(f)}getExtensionFromMediaType(e,n){if(n){let r=ie(n);if(r&&r!==".bin")return r}switch(e){case"image":return".png";case"video":return".mp4";case"audio":return".mp3";default:return".bin"}}sleep(e,n){return new Promise((r,s)=>{let i=setTimeout(r,e);n?.addEventListener("abort",()=>{clearTimeout(i),s(new Error("aborted"))},{once:!0})})}};S();S();var zn=y("channels"),he=class{platform="discord";id;config;status="disconnected";messageHandler=null;client=null;constructor(e,n){if(this.id=e,!n.botToken)throw new Error("Discord adapter requires botToken");this.config=n}async connect(){this.status="connecting";try{let{Client:e,GatewayIntentBits:n}=await import("discord.js");this.client=new e({intents:[n.Guilds,n.GuildMessages,n.MessageContent,n.DirectMessages]});let r=this.client;r.on("messageCreate",s=>{if(!this.messageHandler||s.author.bot||this.config.allowedGuildIds?.length&&s.guildId&&!this.config.allowedGuildIds.includes(s.guildId))return;let i={channelId:this.id,platform:"discord",chatId:s.channelId,senderId:s.author.id,senderName:s.author.displayName??s.author.username,content:s.content,isGroup:!!s.guildId,timestamp:s.createdTimestamp,raw:s};this.messageHandler(i)}),await r.login(this.config.botToken),this.status="connected",zn.info({channelId:this.id},"Discord bot connected")}catch(e){throw this.status="error",e}}async disconnect(){this.client&&await this.client.destroy(),this.client=null,this.status="disconnected"}getStatus(){return this.status}getCapabilities(){return{canEdit:!0,canQuote:!0,canParseQuote:!0,canInlineButtons:!0,maxTextLength:2e3,supportsAttachments:!0}}async sendMessage(e,n){if(!this.client)throw new Error("Discord client not connected");let s=await this.client.channels.fetch(e);if(!s||!("send"in s))throw new Error(`Channel ${e} not found or not text channel`);return(await s.send({content:n.content,reply:n.replyToMessageId?{messageReference:n.replyToMessageId}:void 0})).id}onMessage(e){this.messageHandler=e}async sendTypingIndicator(e){if(!this.client)return;let r=await this.client.channels.fetch(e);r&&"sendTyping"in r&&await r.sendTyping()}};import{statSync as as}from"fs";import{ImapFlow as os}from"imapflow";import ds from"nodemailer";import{existsSync as Qn,mkdirSync as Hn,readFileSync as Kn,writeFileSync as Xn}from"fs";import{dirname as Jn,join as Lt}from"path";import{homedir as Yn}from"os";var Zn={lastUid:0,seenMessageIds:[],sentMessageIds:[],updatedAt:0};function Le(t=process.env.ADAM_TEST_DIR??Lt(Yn(),".adam")){return Lt(t,"email-gateway","state.json")}function ye(t=Le()){if(!Qn(t))return{...Zn};let e=JSON.parse(Kn(t,"utf-8"));return{uidValidity:e.uidValidity,lastUid:Number.isInteger(e.lastUid)?e.lastUid:0,seenMessageIds:Array.isArray(e.seenMessageIds)?e.seenMessageIds.filter(Ft):[],sentMessageIds:Array.isArray(e.sentMessageIds)?e.sentMessageIds.filter(Ft):[],updatedAt:typeof e.updatedAt=="number"?e.updatedAt:0}}function ne(t,e=Le()){Hn(Jn(e),{recursive:!0}),Xn(e,JSON.stringify({...t,updatedAt:Date.now()},null,2),"utf-8")}function Bt(t,e){let n=G(e);return n?{...t,seenMessageIds:t.seenMessageIds.includes(n)?t.seenMessageIds:[...t.seenMessageIds,n]}:t}function es(t,e){let n=G(e);return n?{...t,sentMessageIds:t.sentMessageIds.includes(n)?t.sentMessageIds:[...t.sentMessageIds,n]}:t}function $t(t,e=Le()){let n=es(ye(e),t);return ne(n,e),n}function G(t){return typeof t=="string"?t.trim():""}function Ft(t){return typeof t=="string"}import{Readable as ts}from"stream";import{MailParser as ns}from"mailparser";import{convert as ss}from"html-to-text";async function Gt(t){let e=new ns({skipImageLinks:!0,skipTextToHtml:!0}),n={},r,s,i,a=[],o,d="",c="",u="",p,f=0,m;if(await new Promise((L,A)=>{e.on("headers",w=>{try{for(let[I,v]of w.entries())n[I.toLowerCase()]=is(v);r=qt(w.get("message-id")),o=qt(w.get("subject")),u=Vt(w.get("content-type"))??"";let U=w.get("date");U instanceof Date&&(p=U.getTime()),s=Wt(w.get("from"),"from"),i=rs(w.get("reply-to"),"reply-to"),a=jt(w.get("to"))}catch(U){m=U instanceof Error?U:new Error(String(U))}}),e.on("data",w=>{if(w.type==="attachment"){f+=1,w.release?.(),w.content?.resume?.();return}d=w.text??"",c=typeof w.html=="string"?w.html:""}),e.on("error",A),e.on("end",L),ts.from([t]).pipe(e)}),m)throw m;if(!s)throw new Error("Inbound email must contain exactly one valid From address");let l=u.toLowerCase()==="text/html",b=d.trim();return(l||!b)&&c.trim()&&(b=ss(c,{wordwrap:!1,selectors:[{selector:"h1",format:"heading",options:{uppercase:!1}},{selector:"h2",format:"heading",options:{uppercase:!1}},{selector:"h3",format:"heading",options:{uppercase:!1}},{selector:"h4",format:"heading",options:{uppercase:!1}},{selector:"h5",format:"heading",options:{uppercase:!1}},{selector:"h6",format:"heading",options:{uppercase:!1}}]}).trim()),!b&&o&&(b=o.trim()),{messageId:r,from:s,replyTo:i,to:a,subject:o,text:b,date:p,rawHeaders:n,attachmentCount:f}}function Wt(t,e){let n=jt(t);if(n.length!==1){if(n.length===0)return;throw new Error(`Inbound email ${e} must contain exactly one mailbox address`)}return n[0]}function rs(t,e){if(t)return Wt(t,e)}function jt(t){return t?typeof t=="string"?[k(t)]:(t.value??[]).map(r=>r.address).filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>k(r)):[]}function qt(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(String).join(", ")}function is(t){if(t instanceof Date)return t.toISOString();if(typeof t=="string")return t;if(Array.isArray(t))return t.map(String).join(", ");let e=Vt(t);return e||(t&&typeof t=="object"&&"text"in t?String(t.text??""):String(t??""))}function Vt(t){if(typeof t=="string")return t;if(t&&typeof t=="object"&&"value"in t){let e=t.value;if(typeof e=="string")return e}}var zt=3e4,us=5e3,cs=3e5,ls=1.33,ms=3e4;function gs(t){if(!t||t.length===0)return zt;let e=0;for(let r of t)try{e+=as(r.path).size}catch{}let n=e*ls/(1024*1024);return Math.min(cs,zt+Math.ceil(n*us))}var Be=class{imapClient;smtpTransporter;pollTimer;handlers=[];status={status:"stopped"};state=ye();async start(e){if(await this.stop(),!e.enabled){this.status={status:"stopped",details:{reason:"disabled"}};return}this.status={status:"starting",lastStartedAt:Date.now()};try{this.imapClient=new os({host:e.imap.host,port:e.imap.port,secure:e.imap.secure,auth:{user:e.imap.auth.user,pass:e.imap.auth.pass}}),await this.imapClient.connect();let n=await this.imapClient.mailboxOpen(e.imap.mailbox),r=n?.uidValidity?Number(n.uidValidity):void 0;r&&this.state.uidValidity&&r!==this.state.uidValidity?(this.state={...this.state,uidValidity:r,lastUid:0,seenMessageIds:[]},ne(this.state)):r&&(this.state={...this.state,uidValidity:r},ne(this.state)),this.smtpTransporter=ds.createTransport({host:e.smtp.host,port:e.smtp.port,secure:e.smtp.secure,auth:{user:e.smtp.auth.user,pass:e.smtp.auth.pass}}),await this.smtpTransporter.verify(),this.status={status:"connected",lastStartedAt:Date.now(),lastCheckedAt:Date.now()},this.schedulePoll(e)}catch(n){throw await this.cleanupResources(),this.status={status:"error",lastError:$e(n),details:{stage:this.smtpTransporter?"smtp":"imap"}},n}}async stop(){await this.cleanupResources(),this.status={status:"stopped"}}getStatus(){return{...this.status}}onInbound(e){this.handlers.push(e)}async send(e){if(!this.smtpTransporter)throw new Error("EmailGateway SMTP transporter is not started");let n=gs(e.attachments),r=await ps(this.smtpTransporter.sendMail({from:e.from,to:e.to,subject:e.subject,text:e.text,html:e.html,attachments:e.attachments}),n,`SMTP send timed out after ${Math.round(n/1e3)}s`),s=G(r.messageId);if(!s)throw new Error("SMTP send returned no Message-ID");return this.state=$t(s),s}isSentByAdam(e){let n=G(e);return n.length>0&&this.state.sentMessageIds.includes(n)}schedulePoll(e){this.pollTimer=setInterval(()=>{this.poll(e)},ms)}async poll(e){if(this.imapClient)try{this.state=ye();let n=`${this.state.lastUid+1}:*`,r=this.imapClient.fetch?.(n,{uid:!0,source:!0,envelope:!0},{uid:!0});if(!r||!r[Symbol.asyncIterator])return;let s=!1;for await(let i of r){let a=Number(i.uid);if(!Number.isInteger(a)||a<=this.state.lastUid)continue;if(!i.source){this.markDegraded(new Error(`IMAP fetch item ${a} is missing source`)),s=!0;break}let o;try{o=await Gt(i.source)}catch(u){this.markDegraded(u),s=!0;break}let d=o.rawHeaders["x-adam-probe-id"],c=G(o.messageId);if(d?.startsWith("adam-probe-")){this.advanceCursor(a);continue}if(c&&this.state.sentMessageIds.includes(c)){this.advanceCursor(a);continue}if(c&&this.state.seenMessageIds.includes(c)){this.advanceCursor(a);continue}try{await Promise.all(this.handlers.map(u=>u(o)))}catch(u){this.markDegraded(u),s=!0;break}this.state=Bt(this.state,c),this.advanceCursor(a)}s||(this.status={...this.status,status:"connected",lastCheckedAt:Date.now(),lastError:void 0})}catch(n){this.markDegraded(n)}}advanceCursor(e){this.state={...this.state,lastUid:e},ne(this.state)}markDegraded(e){this.status={...this.status,status:"degraded",lastError:$e(e),lastCheckedAt:Date.now()}}async cleanupResources(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=void 0);let e=this.imapClient,n=this.smtpTransporter;this.imapClient=void 0,this.smtpTransporter=void 0,e&&(await Fe(e.logout?.()),await Fe(e.close?.())),await Fe(n?.close?.())}},Qt;function C(){return Qt??=new Be,Qt}async function be(t){await C().start(t)}async function Jr(t,e){await C().stop(),await C().start(t)}async function Yr(t){await C().stop()}async function ps(t,e,n){let r;try{return await Promise.race([t,new Promise((s,i)=>{r=setTimeout(()=>i(new Error(n)),e)})])}catch(s){throw new Error($e(s))}finally{r&&clearTimeout(r)}}function $e(t){return t instanceof Error?t.message.replace(/pass(word)?=[^\s]+/gi,"password=****"):"Email gateway operation failed"}async function Fe(t){t&&typeof t.then=="function"&&await t.catch(()=>{})}S();var ys=/\b55[234]\b/,bs=/(?:size|too large|exceeds|maximum|over.*?limit)/i,ws=/\b(\d{6,11})\b/,_s=/Final-Recipient:\s*rfc822;\s*([^\s>]+@([^\s>;]+))/i,Is=/To:[\s<]*([^\s>;]+@([^\s>;]+))/i;function Ht(t){let e=t.text??"",n=e.split(/\r?\n/).filter(a=>ys.test(a)&&bs.test(a));if(n.length===0)return null;let r=e.match(_s)??e.match(Is);if(!r)return null;let s=r[2].toLowerCase().trim();if(!Ve.test(s))return null;let i=null;for(let a of n){let o=a.match(ws);if(o){let d=parseInt(o[1],10);if(Number.isFinite(d)&&d>=1048576&&d<=209715200){i=d;break}}}return i===null?null:{recipientDomain:s,capBytes:i}}var we=y("channels"),Kt=!1;function Xt(t){if(Kt){we.debug("Bounce handler already registered; skipping duplicate registration");return}Kt=!0,t.onInbound(async e=>{let n=Ht(e);if(!n){(/MAILER-DAEMON/i.test(e.from??"")||/^no-reply@mailsupport\.aliyun\.com$/i.test(e.from??"")||/Mail Delivery|Undeliverable|Returned mail|Delivery Status Notification|退信|无法投递|投递失败/i.test(e.subject??""))&&we.warn({from:e.from,subject:e.subject},"Inbound looks like bounce but parser did not recognize a size-limit cap");return}let{recipientDomain:r,capBytes:s}=n;we.info({recipientDomain:r,capBytes:s},"Bounce-learning: detected SMTP size-limit bounce");let i=F().filter(a=>a.platform==="email");for(let a of i)try{Qe(a.id,r,s)}catch(o){we.warn({channelId:a.id,recipientDomain:r,capBytes:s,err:o},"Bounce-learning: setRecipientCap failed (out of range or DB error); skipping")}})}S();var _e=y("channels"),qe=class{constructor(e){this.gateway=e}gateway;adaptersByAddress=new Map;channelAddressById=new Map;registerAdapter(e,n){if(!Ke(e)||!e.enabled)return;let r=B(e);this.unregisterAdapter(e.id),this.adaptersByAddress.set(r,n),this.channelAddressById.set(e.id,r)}unregisterAdapter(e){let n=this.channelAddressById.get(e);n&&(this.adaptersByAddress.delete(n),this.channelAddressById.delete(e))}refreshFromChannels(e,n){this.adaptersByAddress.clear(),this.channelAddressById.clear();for(let r of e){let s=n.get(r.id);if(s)try{this.registerAdapter(r,s)}catch(i){_e.warn({channelId:r.id,error:i},"Invalid email channel skipped during router refresh")}}}async handle(e){if(e.messageId&&this.gateway.isSentByAdam(e.messageId)){_e.debug({messageId:e.messageId},"Skipping Adam-sent email");return}let n;try{n=k(e.from)}catch(s){_e.warn({from:e.from,error:s},"Skipping email with invalid sender address");return}let r=this.adaptersByAddress.get(n);if(!r){_e.info({from:n},"Skipping unmatched inbound email");return}await r.acceptInbound(e)}hasAddress(e){return this.adaptersByAddress.has(k(e))}},Ie,Jt;function Ge(t){return(!Ie||Jt!==t)&&(Ie=new qe(t),Jt=t,t.onInbound(e=>Ie?.handle(e)??Promise.resolve())),Ie}import{existsSync as Es}from"fs";import{basename as Ts,isAbsolute as xs}from"path";function Yt(t){let e=[];return t.mediaUrl&&e.push({path:t.mediaUrl,mediaType:t.mediaType}),t.attachments&&e.push(...t.attachments),e.map(Ms)}function Ms(t){let e=t.path.startsWith("file://")?new URL(t.path).pathname:t.path;if(!xs(e)||e.includes("://"))throw new Error("Email attachment path must be an absolute local file path");if(!Es(e))throw new Error(`Email attachment file not found: ${e}`);return{filename:t.filename??Ts(e),path:e,...t.contentType?{contentType:t.contentType}:t.mediaType?{contentType:Cs(t.mediaType)}:{}}}function Cs(t){return"application/octet-stream"}import Ss from"markdown-it";var Rs=new Ss({html:!1,linkify:!0});function Zt(t){return{text:Je(t),html:Rs.render(t)}}function en(t){let e=t.prefix.trim()||"Adam";return t.messageType==="report"||t.messageType==="status_report"?`[${e} Report]`:t.messageType==="deliver"||t.messageType==="result_delivery"?`[${e} Deliver]`:`[${e}]`}var Ee=class{platform="email";id;channel;gateway;handler;inboundDispatchHandler;status="disconnected";identity;constructor(e,n,r={}){this.channel=e,this.gateway=n,this.id=e.id,this.identity=r}async connect(){let e=this.gateway.getStatus();this.status=Te(e.status)}async disconnect(){this.status="disconnected"}getStatus(){return this.status}getCapabilities(){return{canEdit:!1,canQuote:!1,canParseQuote:!1,canInlineButtons:!1,maxTextLength:Number.POSITIVE_INFINITY,supportsAttachments:!0}}async sendMessage(e,n){let r=k(e),s=B(this.channel);if(r!==s)throw new Error("Email channel recipient does not match configured address");let i=Zt(n.content);return this.gateway.send({from:this.identity.from?Xe(this.identity.from,this.identity.displayName):void 0,to:r,subject:en({prefix:this.identity.subjectPrefix??"Adam",messageType:n.messageType??"reply"}),text:i.text,html:i.html,attachments:Yt(n)})}onMessage(e){this.handler=e}onInboundDispatch(e){this.inboundDispatchHandler=e}syncGatewayStatus(){this.status=Te(this.gateway.getStatus().status)}async acceptInbound(e){let n=k(e.from),r={channelId:this.channel.id,platform:"email",chatId:n,senderId:n,senderName:e.from,content:e.text,replyToMessageId:e.messageId,isGroup:!1,timestamp:e.date??Date.now(),raw:{messageId:e.messageId,subject:e.subject,attachmentCount:e.attachmentCount,headers:e.rawHeaders}};this.handler?.(r),this.inboundDispatchHandler&&await this.inboundDispatchHandler(r)}};function Te(t){switch(t){case"connected":return"connected";case"starting":return"connecting";case"degraded":case"error":return"degraded";case"stopped":return"disconnected";default:return"disconnected"}}var tn=y("channels"),We=new Map;async function W(t,e){if(t.hasAdapter(e.id))return!0;if(e.platform==="wechat"){let n=e.config;return n.botToken?(await t.addChannel(e,new q(e.id,n)),!0):!1}if(e.platform==="discord"){let n=e.config;return n.botToken?(await t.addChannel(e,new he(e.id,{botToken:n.botToken})),!0):!1}if(e.platform==="email"){B(e);let n=C(),r=V().emailGateway,s=new Ee(e,n,{from:r?.smtp?.from||r?.address,displayName:r?.displayName,subjectPrefix:r?.subjectPrefix??"Adam"});We.set(e.id,s),Ge(n).registerAdapter(e,s);try{await As(),await t.addChannel(e,s)}catch(i){throw await j(t,e),i}return!0}return!1}async function Ai(t){for(let e of F(!0))try{await W(t,e)}catch(n){z(e.id,"error"),tn.warn({channelId:e.id,platform:e.platform,error:n},"Failed to register built-in channel adapter")}}async function nn(t,e){e.platform==="email"&&(await j(t,e),e.enabled&&await W(t,e))}async function sn(t,e){await j(t,e)}async function j(t,e){e.platform==="email"&&(Ge(C()).unregisterAdapter(e.id),We.delete(e.id),t?.hasAdapter(e.id)&&await t.removeChannel(e.id))}function ki(t){for(let[e,n]of We.entries())n.syncGatewayStatus(),z(e,n.getStatus())}async function As(){let t=V().emailGateway;if(!t?.enabled)return;let e=C().getStatus().status;if(!(e!=="stopped"&&e!=="error"))try{await be(t),Xt(C())}catch(n){tn.warn({error:ks(n)},"EmailGateway start failed during built-in adapter registration")}}function ks(t){return t instanceof Error?t.message.replace(/pass(word)?=[^\s]+/gi,"password=****"):"Email gateway operation failed"}var P=g.object({id:g.string().uuid()}),Us=g.object({name:g.string().min(1,"name is required"),platform:g.string().min(1,"platform is required"),config:g.record(g.string(),g.unknown()),enabled:g.boolean().optional().default(!0),linkedRoleId:g.string().optional(),allowedChatIds:g.array(g.string()).optional()}),vs=g.object({name:g.string().min(1).optional(),enabled:g.boolean().optional(),config:g.record(g.string(),g.unknown()).optional(),linkedRoleId:g.string().optional(),allowedChatIds:g.array(g.string()).optional(),viewerKey:g.string().min(1).max(100).regex(/^[a-zA-Z0-9_.@:-]+$/,"viewerKey must be alphanumeric or one of _ . @ : -").optional(),defaultRecipientCapBytes:g.number().int().min(1048576).max(209715200).optional(),recipientCapMap:g.record(g.string().regex(/^[a-z0-9.-]+$/),g.number().int().min(1048576).max(209715200)).optional()}),je;function Vi(t){je=t}function zi(){return je}async function Qi(t){let e=je;async function n(r){ze(r);try{return e&&r.enabled&&await W(e,r),r}catch(s){throw await j(e,r),xe(r.id),s}}t.get("/channels",{schema:{tags:["Channels"],summary:"List channels",querystring:{type:"object",properties:{enabled:{type:"boolean"}}}}},async(r,s)=>({channels:F(r.query.enabled).map(Q)})),t.post("/channels",{schema:{tags:["Channels"],summary:"Create a channel",body:{type:"object",required:["name","platform","config"],properties:{name:{type:"string",minLength:1},platform:{type:"string",minLength:1},config:{type:"object"},enabled:{type:"boolean"},linkedRoleId:{type:"string"},allowedChatIds:{type:"array",items:{type:"string"}}}}}},async(r,s)=>{let i=Us.safeParse(r.body);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});let{name:a,platform:o,config:d,enabled:c,linkedRoleId:u,allowedChatIds:p}=i.data,f=d;if(o==="email")try{f={...Me(d)}}catch(l){return s.status(400).send({code:"VALIDATION_ERROR",message:l instanceof Error?l.message:String(l)})}let m={id:Ps(),name:a,platform:o,enabled:c,status:"disconnected",config:f,linkedRoleId:u,allowedChatIds:p,viewerKey:Ye(),createdAt:Date.now(),messageCount:0};try{await n(m)}catch(l){return s.status(400).send({code:"VALIDATION_ERROR",message:D(l)})}return s.status(201).send({channel:Q(m)})}),t.get("/channels/:id",{schema:{tags:["Channels"],summary:"Get channel by ID",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});let a=E(i.data.id);return a?{channel:Q(a)}:s.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),t.patch("/channels/:id",{schema:{tags:["Channels"],summary:"Update channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",properties:{name:{type:"string"},enabled:{type:"boolean"},config:{type:"object"},linkedRoleId:{type:"string"},allowedChatIds:{type:"array",items:{type:"string"}},viewerKey:{type:"string",minLength:1,maxLength:100}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});let a=E(i.data.id);if(!a)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let o=vs.safeParse(r.body);if(!o.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(o.error)});let d={...o.data};if(d.config&&(d.config=et(d.config,a.config)),(a.platform==="email"||d.config)&&(d.config||a.config)){let p=d.config??a.config;if(a.platform==="email")try{d.config={...Me(p)}}catch(f){return s.status(400).send({code:"VALIDATION_ERROR",message:f instanceof Error?f.message:String(f)})}}let c=a.platform==="email"&&(d.enabled!==void 0||d.config!==void 0);se(a.id,d);let u=E(a.id);if(e&&u&&c)try{await nn(e,u)}catch(p){if(se(a.id,{name:a.name,enabled:a.enabled,status:a.status,config:a.config,linkedRoleId:a.linkedRoleId,allowedChatIds:a.allowedChatIds,lastMessageAt:a.lastMessageAt,messageCount:a.messageCount}),await j(e,u),a.enabled)try{await W(e,a)}catch(f){return s.status(500).send({code:"RESTORE_FAILED",message:D(f)})}return s.status(400).send({code:"VALIDATION_ERROR",message:D(p)})}return{channel:u&&Q(u)}}),t.delete("/channels/:id",{schema:{tags:["Channels"],summary:"Delete channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});let a=E(i.data.id);if(!a)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(xe(a.id),e)try{await sn(e,a)}catch(o){t.log.warn({channelId:a.id,error:D(o)},"Failed to clean up built-in channel runtime")}return s.status(204).send()}),t.post("/channels/:id/connect",{schema:{tags:["Channels"],summary:"Connect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});if(!e)return s.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let a=E(i.data.id);if(!a)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(a.platform==="email")try{await Os()}catch(o){let d=C().getStatus();return z(a.id,Te(d.status)),s.status(409).send({code:"EMAIL_GATEWAY_NOT_READY",message:D(o),gatewayStatus:d})}if(!e.hasAdapter(a.id))try{await W(e,a)}catch(o){return s.status(400).send({code:"VALIDATION_ERROR",message:D(o)})}if(!e.hasAdapter(a.id))return s.status(400).send({code:"NO_ADAPTER",message:"No adapter registered for this channel. Install the appropriate adapter first."});try{await e.connectChannel(a.id);let o=E(a.id)?.status??e.getChannelStatus(a.id);return o!=="connected"?s.status(409).send({code:"CONNECT_INCOMPLETE",message:`Channel connect finished with status "${o}"`,status:o}):{channelId:a.id,status:o}}catch(o){return s.status(500).send({code:"CONNECT_FAILED",message:D(o)})}}),t.post("/channels/:id/disconnect",{schema:{tags:["Channels"],summary:"Disconnect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});if(!e)return s.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let a=E(i.data.id);return a?(await e.disconnectChannel(a.id),{channelId:a.id,status:"disconnected"}):s.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),t.get("/channels/:id/capabilities",{schema:{tags:["Channels"],summary:"Get channel adapter capabilities",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});if(!E(i.data.id))return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(!e)return s.status(503).send({code:"MANAGER_UNAVAILABLE",message:"ChannelManager not initialized"});let o=e.getCapabilities(i.data.id);return o?{capabilities:o}:s.status(404).send({code:"ADAPTER_NOT_REGISTERED",message:"Channel adapter not active"})}),t.get("/channels/:id/messages",{schema:{tags:["Channels"],summary:"Get channel message history",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50},offset:{type:"integer",minimum:0,default:0}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});let a=E(i.data.id);if(!a)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let{limit:o=50,offset:d=0}=r.query;return{messages:He(a.id,o,d)}}),t.post("/channels/:id/wechat/qr-start",{schema:{tags:["WeChat"],summary:"Start WeChat QR login",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});let a=E(i.data.id);if(!a)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(a.platform!=="wechat")return s.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=a.config;return await ut({apiBaseUrl:o.baseUrl,routeTag:o.routeTag})}),t.post("/channels/:id/wechat/qr-wait",{schema:{tags:["WeChat"],summary:"Wait for WeChat QR scan",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",properties:{sessionKey:{type:"string"},timeoutMs:{type:"number"}}}}},async(r,s)=>{let i=P.safeParse(r.params);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(i.error)});let a=E(i.data.id);if(!a)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(a.platform!=="wechat")return s.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=a.config,{sessionKey:d,timeoutMs:c}=r.body??{},u=await ct({sessionKey:d??"",apiBaseUrl:o.baseUrl,timeoutMs:c??12e4,routeTag:o.routeTag});if(u.connected&&u.botToken){let p={...o,botToken:u.botToken,accountId:u.accountId,baseUrl:u.baseUrl??o.baseUrl,userId:u.userId};if(se(a.id,{config:p}),e){let f=new q(a.id,p),m=E(a.id);m&&await e.addChannel(m,f)}}return{connected:u.connected,accountId:u.accountId,message:u.message}})}function D(t){return t instanceof Error?t.message.replace(/pass(word)?=[^\s]+/gi,"password=****"):String(t)}async function Os(){let t=V().emailGateway;if(!t?.enabled)throw new Error("Email Gateway is disabled. Enable Email Gateway in Settings before connecting Mail channels.");let e=C();e.getStatus().status!=="connected"&&await be(t);let n=e.getStatus();if(n.status!=="connected"){let r=n.lastError?`: ${n.lastError}`:"";throw new Error(`Email Gateway status is ${n.status}${r}`)}}export{$t as a,G as b,Gt as c,C as d,Jr as e,Yr as f,Ai as g,ki as h,Vi as i,zi as j,Qi as k};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{o as t,q as d}from"./chunk-ZEGZ2I35.js";d();function s(e){return{id:e.id,taskId:e.task_id,roleId:void 0,plan:JSON.parse(e.plan_json),status:e.status,approvalType:e.approval_type??void 0,deviationReport:e.deviation_report_json?JSON.parse(e.deviation_report_json):void 0,learnedRules:e.learned_rules_json?JSON.parse(e.learned_rules_json):void 0,createdAt:e.created_at,approvedAt:e.approved_at??void 0,reviewedAt:e.reviewed_at??void 0}}function p(e){t().prepare(`
|
|
2
2
|
INSERT INTO task_plans (id, task_id, plan_json, status, approval_type,
|
|
3
3
|
deviation_report_json, learned_rules_json, created_at, approved_at, reviewed_at)
|
|
4
4
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{D as m,L as b}from"./chunk-
|
|
1
|
+
import{D as m,L as b}from"./chunk-3JTHJ3FZ.js";import{h as I,m as N,o as g,q as y}from"./chunk-ZEGZ2I35.js";y();b();import{z as a}from"zod";var u=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,U=/^role-[a-z0-9][a-z0-9-]*$/,P=/^tmpl-[a-f0-9]+$/,R=/^workflow-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,x=/^[a-z][a-z0-9]+-[a-z][a-z0-9-]+$/,k=/^[a-zA-Z][\w-]*@[a-zA-Z][\w-]*$/,O=/^(?:\/|~\/)/,_=/^[\p{L}0-9._-]+$/u,F=a.string().regex(u,"taskId must be a UUID (e.g., 'a1b2c3d4-...'). Use list_tasks to find existing IDs.").describe("Task ID (UUID). Use list_tasks or read_task_status to find existing IDs."),J=a.string().refine(e=>u.test(e)||U.test(e),{message:"roleId must be a UUID or a system role ID like 'role-chat-manager'. Use list_roles to find IDs (do NOT pass the Role's display name)."}).describe("Role ID (UUID or 'role-<name>' for presets). Use list_roles to find IDs \u2014 NOT the human-readable name."),W=a.string().regex(u,"goalId must be a UUID. Use list_goals to find existing IDs.").describe("Goal ID (UUID). Use list_goals to find existing IDs."),H=a.string().regex(u,"channelId must be a UUID. Use list_channels to find IDs (do NOT pass the channel's display name).").describe("Channel ID (UUID). Use list_channels to find IDs \u2014 NOT the channel's display name."),G=a.string().regex(u,"sessionId must be a UUID.").describe("Chat session ID (UUID)."),V=a.string().refine(e=>u.test(e)||P.test(e)||R.test(e)||x.test(e),{message:"templateId must be a UUID, 'tmpl-<hex>', 'workflow-<uuid>', or a friendly ID (e.g., 'pkos-scan-and-sync'). Use list_templates to find IDs."}).describe("Task template ID. Use list_templates to find IDs."),Y=a.string().regex(k,"pluginId must be '<name>@<scope>' (e.g., 'github@anthropic'). Use list_available_plugins to discover.").describe("Plugin ID in '<name>@<scope>' format (e.g., 'github@anthropic'). Use list_available_plugins to discover."),j=a.string().regex(u,"eventDefId must be a UUID. Use list_event_defs to find IDs.").describe("Event definition ID (UUID). Use list_event_defs to find IDs."),z=a.string().regex(u,"ruleId must be a UUID. Use list_delivery_rules to find IDs.").describe("Delivery rule ID (UUID). Use list_delivery_rules to find IDs."),K=a.string().regex(u,"strategyId must be a UUID. Use list_strategies to find IDs.").describe("Strategy ID (UUID). Use list_strategies to find IDs."),q=a.string().regex(O,"Path must be absolute ('/Users/.../file' or '~/...'). Do NOT use relative paths or remote URLs.").describe("Absolute local file path (e.g., '/Users/me/file.txt' or '~/Documents/file.txt'). Remote URLs are NOT accepted \u2014 download files locally first."),Q=a.string().regex(/^[A-Za-z0-9_-]{1,64}$/,"executionId must be 1-64 chars: letters, digits, dashes, underscores. Use list_template_executions or query_execution_status to find existing IDs.").describe("TemplateExecution ID. Use list_template_executions or query_execution_status to find existing IDs."),X=a.string().min(1).max(128).regex(_,"stepId must be 1-128 chars: letters (any script), digits, dots, underscores, or dashes.").describe("Template step ID \u2014 a human-readable identifier for a template step.");N();function L(e){if(e)return e.startsWith("event:")?e.slice(6):void 0}var c=class extends Error{constructor(n,r,i=[]){super(r);this.code=n;this.failingStepIds=i;this.name="TemplateValidationError"}code;failingStepIds},f=class extends Error{constructor(n,r){super(A(n,r));this.code=n;this.failingStepIds=r;this.name="TemplateRoleConfigError"}code;failingStepIds};function A(e,t){return e==="STEP_AUTOSELECT_NEEDS_REQUIREMENTS"?`Template has ${t.length} step(s) with autoSelectRole=true but no requirements object. Failing step ids: ${t.join(", ")}`:e==="STEP_ROLE_NOT_FOUND"?`Template has ${t.length} step(s) with a roleId that does not resolve to an active role. Failing step ids: ${t.join(", ")}`:`Template has ${t.length} step(s) without executable role config. Set template.rolePreference, OR set each failing step's roleId, OR set autoSelectRole=true. Failing step ids: ${t.join(", ")}`}function v(e){let t=typeof e.roleId=="string"&&e.roleId.length>0,n=e.autoSelectRole===!0;return t||n}function C(e){if(typeof e.roleId=="string"&&e.roleId.length>0){let t=m(e.roleId);if(!t||t.status!=="active")return{code:"STEP_ROLE_NOT_FOUND",stepId:e.id}}return e.autoSelectRole===!0&&e.requirements==null?{code:"STEP_AUTOSELECT_NEEDS_REQUIREMENTS",stepId:e.id}:null}function M(e){if(!e.rolePreference){let n=[];for(let r of e.steps)v(r)||n.push(r.id);if(n.length>0)throw new f("TEMPLATE_INVALID_ROLE_CONFIG",n)}let t=e.steps.map(n=>C(n)).filter(n=>n!==null);if(t.length>0){let n=t[0].code,r=t.filter(i=>i.code===n).map(i=>i.stepId);throw new f(n,r)}}function D(e){if(!Array.isArray(e.steps)||e.steps.length<1)throw new c("TEMPLATE_STEPS_REQUIRED","Template must contain at least one step.");let t=new Set,n=[],r=[];for(let s of e.steps)(typeof s.id!="string"||s.id.length<1||s.id.length>128||!_.test(s.id))&&r.push(s.id),t.has(s.id)&&n.push(s.id),t.add(s.id);if(r.length>0)throw new c("TEMPLATE_STEP_ID_INVALID",`Template has invalid step id(s): ${r.join(", ")}. Step ids must be 1-128 chars: letters, digits, dots, underscores, or dashes.`,r);if(n.length>0)throw new c("TEMPLATE_STEP_ID_DUPLICATE",`Template has duplicate step id(s): ${n.join(", ")}.`,n);let i=new Map;for(let s of e.steps){let o=s.dependsOn??[];i.set(s.id,o);for(let l of o){if(l===s.id)throw new c("TEMPLATE_DEPENDENCY_SELF",`Template step "${s.id}" cannot depend on itself.`,[s.id]);if(!t.has(l))throw new c("TEMPLATE_DEPENDENCY_UNKNOWN",`Template step "${s.id}" depends on unknown step "${l}".`,[s.id])}if(s.minDependencies!==void 0){if(!Number.isInteger(s.minDependencies)||s.minDependencies<1)throw new c("TEMPLATE_MIN_DEPENDENCIES_INVALID",`Step "${s.id}": minDependencies must be a positive integer`,[s.id]);let l=s.dependsOn?.length??0;if(s.minDependencies>l)throw new c("TEMPLATE_MIN_DEPENDENCIES_EXCEEDS",`Step "${s.id}": minDependencies (${s.minDependencies}) exceeds dependsOn length (${l})`,[s.id])}}let d=new Set,p=new Set,E=(s,o)=>{if(p.has(s))return[...o,s];if(d.has(s))return null;p.add(s);for(let l of i.get(s)??[]){let T=E(l,[...o,s]);if(T)return T}return p.delete(s),d.add(s),null};for(let s of e.steps){let o=E(s.id,[]);if(o)throw new c("TEMPLATE_DEPENDENCY_CYCLE",`Template step dependencies contain a cycle: ${o.join(" -> ")}.`,[...new Set(o)])}M(e)}function h(e){if(e.type!=="cron"&&e.type!=="manual"&&e.type!=="once"&&e.type!=="template_complete"&&e.type!=="event")throw new c("TEMPLATE_TRIGGER_INVALID",`Template trigger type is not supported: ${String(e.type)}.`);if(e.type==="template_complete"&&!/^template_complete:[\w-]+$/.test(e.event??""))throw new c("TEMPLATE_TRIGGER_INVALID","Template completion trigger event must use 'template_complete:<templateId>'.")}function S(e){let t=e.trigger_type,n={type:t,cron:t==="event"?void 0:e.trigger_cron??void 0,event:t==="event"?void 0:e.trigger_event??void 0,eventDefId:t==="event"?L(e.trigger_event):void 0,runAt:t==="once"?e.trigger_cron??void 0:void 0};return{id:e.id,name:e.name,description:e.description??void 0,trigger:n,steps:JSON.parse(e.steps),rolePreference:e.role_preference??void 0,config:e.config?JSON.parse(e.config):void 0,tags:e.tags?JSON.parse(e.tags):void 0,enabled:e.enabled===1,createdAt:e.created_at,updatedAt:e.updated_at??void 0,sourceSessionId:e.source_session_id??void 0,deliverTo:e.deliver_to?JSON.parse(e.deliver_to):void 0,reportTo:e.report_to?JSON.parse(e.report_to):void 0,goalIds:e.goal_ids?JSON.parse(e.goal_ids):void 0,isPreset:e.is_preset===1?!0:void 0,presetId:e.preset_id??void 0,retryPolicy:e.retry_policy?JSON.parse(e.retry_policy):void 0}}function se(e){D(e),h(e.trigger);let n=g().prepare(`
|
|
2
2
|
INSERT OR IGNORE INTO task_templates (id, name, description, trigger_type, trigger_cron,
|
|
3
3
|
trigger_event, steps, role_preference, config, tags, enabled, created_at, updated_at,
|
|
4
4
|
source_session_id, deliver_to, report_to, goal_ids, is_preset, preset_id, retry_policy)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as A,b as E}from"./chunk-
|
|
1
|
+
import{a as A,b as E}from"./chunk-4NRIKWSD.js";import{c as p,d as j,i as v}from"./chunk-6SBLFYCU.js";import{a as B,b as d}from"./chunk-T2Z2JDPY.js";import{d as h,l as M,n as b,o as S,p as C,r as x}from"./chunk-AKQ3AFVI.js";import{K as g,L as w}from"./chunk-3JTHJ3FZ.js";w();var f=5;async function R(t,o,s){let c=g(t),i=o?`${t}::${o}`:void 0,r;if(s){if(r=j(t,s,f*4).map(a=>a.node).filter(a=>a.status==="active"),r.length<f*4){let a=new Set(r.map(n=>n.id)),u=p(t,{onlyActive:!0}).slice(0,f*4);for(let n of u)if(!a.has(n.id)&&(r.push(n),r.length>=f*4))break}}else r=p(t,{onlyActive:!0}).slice(0,f*4);i&&(r=r.filter(e=>e.scopeKey===i||e.scopeKey==null));let m=r.map(e=>({belief:e,score:A(e,c)??.5}));m.sort((e,a)=>a.score-e.score);let l=m.slice(0,f).map(e=>e.belief);for(let e of l)E(e,c),v(e.id),e.injectCount=(e.injectCount??0)+1;return l}function O(t,o){if(t.length===0)return"";let s=o==="initial"?"[Memory Context \u2014 retrieved from prior interactions]":"[Memory Refresh \u2014 \u8FC7\u5F80\u89C2\u5BDF,\u53EF\u80FD\u8FC7\u65F6;Step \u6307\u4EE4\u4E3A\u6743\u5A01,\u51B2\u7A81\u5219\u5FFD\u7565]",c=t.map(i=>i.isAnti?`- [anti-pattern] \u274C ${i.content}`:`- [belief] ${i.content}`);return`${s}
|
|
2
2
|
${c.join(`
|
|
3
3
|
`)}
|
|
4
4
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{o as r,q as s}from"./chunk-ZEGZ2I35.js";import{b as i}from"./chunk-5PELJRUQ.js";function p(e){let n=r().prepare("SELECT value FROM config WHERE key = ?").get(e);if(n)try{return JSON.parse(n.value)}catch{return n.value}}function E(e,t){let n=r(),o=JSON.stringify(t),u=Date.now();n.prepare(`INSERT INTO config (key, value, updated_at) VALUES (?, ?, ?)
|
|
2
2
|
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`).run(e,o,u)}function k(){let t=r().prepare("SELECT key, value FROM config").all(),n={};for(let o of t)try{n[o.key]=JSON.parse(o.value)}catch{n[o.key]=o.value}return n}function b(e){let t=r(),n=t.prepare("INSERT OR IGNORE INTO config (key, value, updated_at) VALUES (?, ?, ?)"),o=Date.now(),u=0;return t.transaction(()=>{for(let[c,a]of Object.entries(e)){if(a==null||a==="")continue;n.run(c,JSON.stringify(a),o).changes>0&&u++}})(),u}function w(){return r().prepare("SELECT COUNT(*) as count FROM config").get().count===0}function O(e){return r().prepare("DELETE FROM config WHERE key = ?").run(e).changes>0}var d=i(()=>{s()});export{p as a,E as b,k as c,b as d,w as e,O as f,d as g};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as s}from"./chunk-5PELJRUQ.js";import{join as o}from"path";import{homedir as r}from"os";var T,e,c,t,E,p,a,S,D,x,L,A=s(()=>{"use strict";T=["Read","Write","Edit","Bash","Grep","Glob","WebSearch","WebFetch","LSP","NotebookEdit","Agent"],e=["~/.ssh","~/.aws","~/.gnupg","/etc/shadow"],c=e,t=o(r(),".adam"),E=o(t,"adam.db"),p=o(t,"adam.config.yaml"),a=o(t,".env"),S=o(t,"CLAUDE.md"),D=o(t,"logs"),x=10*1024,L="\u81EA\u68C0 \xB7 \u5BA1\u8BA1\u8FB9\u8F66"});export{T as a,e as b,c,t as d,E as e,p as f,a as g,L as h,A as i};
|