adam-agent-server 1.2.2 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -9
- package/dist/App-JGH6G5US.js +13 -0
- package/dist/adam-tools-KTLBI4PA.js +1 -0
- package/dist/{approval-handler-JYIS2PKQ.js → approval-handler-JZSXM4AD.js} +1 -1
- package/dist/audit-manager-BPJEAX22.js +1 -0
- package/dist/bree-engine-CRK73AI4.js +1 -0
- package/dist/{channels-WZOYE4O4.js → channels-PUOPR5Y2.js} +1 -1
- package/dist/channels-WMTZJAO4.js +1 -0
- package/dist/{chunk-KLQOILIJ.js → chunk-24GTCFEV.js} +1 -1
- package/dist/{chunk-KKLZIXBN.js → chunk-3567PCEJ.js} +2 -2
- package/dist/{chunk-KVSO3KGZ.js → chunk-4VHBKJD5.js} +56 -6
- package/dist/{chunk-GMCIKDTC.js → chunk-6THDALGC.js} +1 -1
- package/dist/{chunk-4TCP2AT7.js → chunk-7BSWC62F.js} +1 -1
- package/dist/{chunk-SBX3HMDA.js → chunk-7K4AQBDD.js} +1 -1
- package/dist/{chunk-EGS6U3V5.js → chunk-CKIVKM5T.js} +2 -2
- package/dist/chunk-DBI36EGR.js +83 -0
- package/dist/{chunk-BIIP363C.js → chunk-DMZM7RU6.js} +1 -1
- package/dist/{chunk-OFOVSC72.js → chunk-EZGMA3VV.js} +1 -1
- package/dist/chunk-GSMC3VUM.js +1 -0
- package/dist/{chunk-AJVN3KPM.js → chunk-GYHOPV4Q.js} +1 -1
- package/dist/chunk-HQ66TFYI.js +12 -0
- package/dist/{chunk-QN6BEJF5.js → chunk-HYDCXE5K.js} +1 -1
- package/dist/{chunk-AR2IZMM2.js → chunk-I5IUTZA3.js} +1 -1
- package/dist/chunk-I67UMGJM.js +10 -0
- package/dist/chunk-J3NIPZ73.js +8 -0
- package/dist/{chunk-RPTHFQX7.js → chunk-JKPSEMUZ.js} +1 -1
- package/dist/{chunk-SWPXG2CY.js → chunk-KO5AFX5U.js} +1 -1
- package/dist/chunk-KOWFPY2J.js +1 -0
- package/dist/{chunk-6YURWVQG.js → chunk-L4Y3GR6W.js} +1 -1
- package/dist/{chunk-CDVIT7L5.js → chunk-NOUSHXGX.js} +1 -1
- package/dist/{chunk-GUQAIWCQ.js → chunk-NZEDILAK.js} +1 -1
- package/dist/{chunk-7LBDLAUQ.js → chunk-QQWRV23T.js} +1 -1
- package/dist/{chunk-2HN2TSP6.js → chunk-RUY23IJK.js} +1 -1
- package/dist/{chunk-Z5ET7WW2.js → chunk-T33BLZV2.js} +1 -1
- package/dist/{chunk-6DXNXLYG.js → chunk-T7GEINGZ.js} +2 -2
- package/dist/{chunk-ZM6YED5F.js → chunk-UQJZU3R5.js} +1 -1
- package/dist/chunk-WRETNOC3.js +99 -0
- package/dist/chunk-XAMLLKKA.js +7 -0
- package/dist/{chunk-PMHNW5IL.js → chunk-XF4IERYF.js} +1 -1
- package/dist/{chunk-EJVUUIAV.js → chunk-YHH3QMLL.js} +1 -1
- package/dist/chunk-YHVFZB6Q.js +1 -0
- package/dist/chunk-ZRUVORAJ.js +49 -0
- package/dist/cli.js +2 -2
- package/dist/{config-EI3SCA4W.js → config-CBNOT66B.js} +1 -1
- package/dist/config-XMQS2NPT.js +1 -0
- package/dist/{db-4NY7ZOS2.js → db-XQUI4IBL.js} +1 -1
- package/dist/{delivery-log-SC2ULFCK.js → delivery-log-T56ZYDWO.js} +1 -1
- package/dist/engine-7DFJOADQ.js +1 -0
- package/dist/{evolution-audit-KUBXFUHI.js → evolution-audit-JZ2U7J4C.js} +1 -1
- package/dist/{external-api-A4JXX4ZE.js → external-api-7XV2PXPC.js} +1 -1
- package/dist/index.js +12 -11
- package/dist/learner-4EO7ZKK4.js +1 -0
- package/dist/{memories-FQCRKMK6.js → memories-EKREXLT6.js} +1 -1
- package/dist/{memory-extractor-FUOJ5D77.js → memory-extractor-JO7OHBZP.js} +2 -2
- package/dist/memory-service-Y3HVQYHM.js +1 -0
- package/dist/outbound-gateway-U5LP54JG.js +1 -0
- package/dist/role-presets-HWZHXBBA.js +1 -0
- package/dist/roles-3AEHVOEW.js +1 -0
- package/dist/{runtime-B2DP3JNB.js → runtime-VDBZZ4KG.js} +1 -1
- package/dist/{session-manager-Z6MIYRD3.js → session-manager-PWJLU6KZ.js} +1 -1
- package/dist/{task-templates-PSP7GOJJ.js → task-templates-ED2UCUPE.js} +1 -1
- package/dist/workflow-executor-XFTTJQNE.js +1 -0
- package/package.json +2 -2
- package/web/dist/assets/AlertDialog-r3y6IhpW.js +51 -0
- package/web/dist/assets/Button-BjXgrQ95.js +1 -0
- package/web/dist/assets/Card-C153tGfJ.js +1 -0
- package/web/dist/assets/ChannelDetail-C2uAZv1u.js +1 -0
- package/web/dist/assets/Channels-C62Qrg-n.js +12 -0
- package/web/dist/assets/Chat-kH2owmB_.js +1 -0
- package/web/dist/assets/Dashboard-BhD8SpFb.js +1 -0
- package/web/dist/assets/EmptyState-CXwJFCDQ.js +1 -0
- package/web/dist/assets/EnvVarEditor-GSapLD96.js +1 -0
- package/web/dist/assets/Evolution-BO5hysLD.js +6 -0
- package/web/dist/assets/GoalDetail-cxa8OvEi.js +1 -0
- package/web/dist/assets/Goals-Dz3qqp_l.js +1 -0
- package/web/dist/assets/Logs-Ckp3-hYV.js +1 -0
- package/web/dist/assets/Memories-DEuSRoP3.js +1 -0
- package/web/dist/assets/NotFound-Bvn39vSk.js +1 -0
- package/web/dist/assets/PageHeader-BMvN0xiB.js +1 -0
- package/web/dist/assets/Plugins-CRym22JF.js +1 -0
- package/web/dist/assets/RoleDetail-BWMjP9aZ.js +33 -0
- package/web/dist/assets/Roles-DD7NBDku.js +1 -0
- package/web/dist/assets/SectionHeader-CiCj3Is0.js +1 -0
- package/web/dist/assets/Settings-BlU19KuR.js +1 -0
- package/web/dist/assets/Strategies-CJ_q94-v.js +1 -0
- package/web/dist/assets/Switch-CoUUy5jr.js +1 -0
- package/web/dist/assets/Table-CaFJieh_.js +1 -0
- package/web/dist/assets/TaskDetail-DVrjU-E6.js +2 -0
- package/web/dist/assets/Work-BMl61RRi.js +1 -0
- package/web/dist/assets/dist-Bdqp1ixJ.js +1 -0
- package/web/dist/assets/index-DcXMQByM.css +2 -0
- package/web/dist/assets/index-pF--tN9F.js +2 -0
- package/web/dist/assets/ui-B_uMx2Fy.js +1 -0
- package/web/dist/assets/useIsMobileLayout-Bwrm84kJ.js +1 -0
- package/web/dist/assets/vendor-icons-BlMaTTx3.js +1 -0
- package/web/dist/assets/{vendor-react-DLRtONKt.js → vendor-react-7e01TWy7.js} +2 -2
- package/web/dist/assets/vendor-state-Bj70wnRm.js +1 -0
- package/web/dist/index.html +8 -6
- package/dist/App-RIYRYLKD.js +0 -9
- package/dist/adam-tools-V22LRDCP.js +0 -1
- package/dist/audit-manager-QDFDBK4E.js +0 -1
- package/dist/bree-engine-EKZFCS4Q.js +0 -1
- package/dist/channels-WMCY4QC3.js +0 -1
- package/dist/chunk-6HD6NYIB.js +0 -1
- package/dist/chunk-B4WHT7DX.js +0 -8
- package/dist/chunk-IHP7JV6J.js +0 -1
- package/dist/chunk-ITUBFUJQ.js +0 -67
- package/dist/chunk-IZWULGUS.js +0 -83
- package/dist/chunk-JNRCXAW3.js +0 -49
- package/dist/chunk-OEKM2W3K.js +0 -4
- package/dist/chunk-W3554FQ7.js +0 -7
- package/dist/config-7HYICF5P.js +0 -1
- package/dist/engine-5RJ7NJSM.js +0 -1
- package/dist/learner-B6XVQKBF.js +0 -1
- package/dist/memory-service-ANR67OPY.js +0 -1
- package/dist/outbound-gateway-6FQRWYFF.js +0 -1
- package/dist/role-presets-LRP6P5O2.js +0 -1
- package/dist/roles-3UTFKSHI.js +0 -1
- package/web/dist/assets/Card-4mOZntHG.js +0 -1
- package/web/dist/assets/ChannelDetail-eWtIGhAd.js +0 -1
- package/web/dist/assets/Channels-2veauYsm.js +0 -12
- package/web/dist/assets/Chat-Bha4vXwT.js +0 -1
- package/web/dist/assets/Dashboard-cDHpOWnY.js +0 -1
- package/web/dist/assets/EmptyState-BlgMMAr-.js +0 -1
- package/web/dist/assets/EnvVarEditor-CaCpNT3y.js +0 -1
- package/web/dist/assets/Evolution-Ao-gdHbS.js +0 -6
- package/web/dist/assets/GoalDetail-CX2i9A5a.js +0 -1
- package/web/dist/assets/Goals-DdM0tFus.js +0 -1
- package/web/dist/assets/Logs-DJhpDtCA.js +0 -1
- package/web/dist/assets/Memories-CYN99g2T.js +0 -1
- package/web/dist/assets/NotFound-CSjhzSGa.js +0 -1
- package/web/dist/assets/Plugins-gcMpBdyq.js +0 -1
- package/web/dist/assets/RoleDetail-s7u-Shk3.js +0 -33
- package/web/dist/assets/Roles-CCy1H7PY.js +0 -1
- package/web/dist/assets/Settings-JbgBxBeo.js +0 -1
- package/web/dist/assets/Strategies-CO4LwZjS.js +0 -1
- package/web/dist/assets/Switch-CTAIxUd_.js +0 -1
- package/web/dist/assets/Table-BxbnOSbq.js +0 -1
- package/web/dist/assets/TaskDetail-DEg_oUwx.js +0 -2
- package/web/dist/assets/Work-BpKK_uXA.js +0 -1
- package/web/dist/assets/dist-HyCSN_hp.js +0 -1
- package/web/dist/assets/index-CaocwyO8.css +0 -2
- package/web/dist/assets/index-rvaixveh.js +0 -52
- package/web/dist/assets/vendor-icons-CkI4-NxL.js +0 -1
- package/web/dist/assets/vendor-state-B_-GdGNJ.js +0 -1
- /package/web/dist/assets/{format-DvtQjPZn.js → format-CHfBBLog.js} +0 -0
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{b as C}from"./chunk-
|
|
1
|
+
import{b as C}from"./chunk-KO5AFX5U.js";import{b as D,c as f,d as w}from"./chunk-EZGMA3VV.js";import{a as p}from"./chunk-L7JP7DUO.js";import{c as M,h as U}from"./chunk-INNDBLZE.js";function O(s,c,n){switch(c){case"wechat":return $(s);case"telegram":return s;case"slack":return P(s);case"webhook":return JSON.stringify({result:s,taskId:n,timestamp:new Date().toISOString()});default:return $(s)}}function $(s){return s.replace(/^#{1,6}\s+/gm,"").replace(/\*\*(.+?)\*\*/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/_(.+?)_/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/```[\s\S]*?```/g,c=>c.replace(/```\w*\n?/g,"").trim()).replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\n{3,}/g,`
|
|
2
2
|
|
|
3
|
-
`).trim()}function P(s){return s.replace(/\*\*(.+?)\*\*/g,"*$1*").replace(/\[([^\]]+)\]\(([^)]+)\)/g,"<$2|$1>")}U();import{v4 as T}from"uuid";var x=M("adam"),v=class{_dedupCache=new Map;_rateLimitWindows=new Map;_recentlySentIds=new Set;isRecentlySent(c){return this._recentlySentIds.has(c)}async send(c){let{taskId:n,channelId:a,chatId:m,content:y,messageType:d,platform:E,webhookUrl:h,replyMarkup:I,mediaUrl:S,mediaType:b}=c,R=d!=="reply"&&!!n,r;if(R){r=`${n}:${a??"none"}:${m??"none"}:${d}`;let t=this._dedupCache.get(r);if(t&&Date.now()-t.timestamp<300*1e3)return x.debug({dedupKey:r},"Dedup hit, returning cached log entry"),{success:!0,logEntryId:t.logEntryId}}if(a){let t=Date.now(),i=6e4,o=this._rateLimitWindows.get(a);o||(o=[],this._rateLimitWindows.set(a,o));let u=t-i;for(;o.length>0&&o[0]<u;)o.shift();if(o.length>=60){let l=T();return x.warn({channelId:a,count:o.length},"Rate limited, not sending"),{success:!1,logEntryId:l,error:"rate_limited"}}o.push(t)}let L=E??(a?C(a)?.platform:void 0)??"unknown",k=h?y:O(y,L,n),e=T(),g={id:e,ruleId:void 0,taskId:n??void 0,status:"pending",target:a&&m?{type:"channel",channelId:a,chatId:m}:h?{type:"webhook",webhookUrl:h}:{type:"channel",channelId:a??"",chatId:m??""},content:k,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+1440*60*1e3,source:"direct",messageType:d};D(g),r&&this._dedupCache.set(r,{logEntryId:e,timestamp:Date.now()});try{if(h){let t=await fetch(h,{method:"POST",body:JSON.stringify({result:y,taskId:n,timestamp:new Date().toISOString()}),signal:AbortSignal.timeout(1e4)});if(t.ok)return w(e),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"delivered",messageType:d}),{success:!0,logEntryId:e};{let i=`Webhook returned ${t.status}`;return f(e,"failed",i),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:i,messageType:d}),{success:!1,logEntryId:e,error:i}}}else if(a&&m){let{getChannelManager:t}=await import("./channels-
|
|
3
|
+
`).trim()}function P(s){return s.replace(/\*\*(.+?)\*\*/g,"*$1*").replace(/\[([^\]]+)\]\(([^)]+)\)/g,"<$2|$1>")}U();import{v4 as T}from"uuid";var x=M("adam"),v=class{_dedupCache=new Map;_rateLimitWindows=new Map;_recentlySentIds=new Set;isRecentlySent(c){return this._recentlySentIds.has(c)}async send(c){let{taskId:n,channelId:a,chatId:m,content:y,messageType:d,platform:E,webhookUrl:h,replyMarkup:I,mediaUrl:S,mediaType:b}=c,R=d!=="reply"&&!!n,r;if(R){r=`${n}:${a??"none"}:${m??"none"}:${d}`;let t=this._dedupCache.get(r);if(t&&Date.now()-t.timestamp<300*1e3)return x.debug({dedupKey:r},"Dedup hit, returning cached log entry"),{success:!0,logEntryId:t.logEntryId}}if(a){let t=Date.now(),i=6e4,o=this._rateLimitWindows.get(a);o||(o=[],this._rateLimitWindows.set(a,o));let u=t-i;for(;o.length>0&&o[0]<u;)o.shift();if(o.length>=60){let l=T();return x.warn({channelId:a,count:o.length},"Rate limited, not sending"),{success:!1,logEntryId:l,error:"rate_limited"}}o.push(t)}let L=E??(a?C(a)?.platform:void 0)??"unknown",k=h?y:O(y,L,n),e=T(),g={id:e,ruleId:void 0,taskId:n??void 0,status:"pending",target:a&&m?{type:"channel",channelId:a,chatId:m}:h?{type:"webhook",webhookUrl:h}:{type:"channel",channelId:a??"",chatId:m??""},content:k,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+1440*60*1e3,source:"direct",messageType:d};D(g),r&&this._dedupCache.set(r,{logEntryId:e,timestamp:Date.now()});try{if(h){let t=await fetch(h,{method:"POST",body:JSON.stringify({result:y,taskId:n,timestamp:new Date().toISOString()}),signal:AbortSignal.timeout(1e4)});if(t.ok)return w(e),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"delivered",messageType:d}),{success:!0,logEntryId:e};{let i=`Webhook returned ${t.status}`;return f(e,"failed",i),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:i,messageType:d}),{success:!1,logEntryId:e,error:i}}}else if(a&&m){let{getChannelManager:t}=await import("./channels-WMTZJAO4.js"),i=t();if(!i){let l="ChannelManager not available";return f(e,"failed",l),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:l,messageType:d}),{success:!1,logEntryId:e,error:l}}let o={content:k,...I?{replyMarkup:I}:{},...S?{mediaUrl:S}:{},...b?{mediaType:b}:{}},u=await i.sendMessage(a,m,o);if(u===null){let l="Channel adapter send failed (returned null)";return f(e,"failed",l),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:l,messageType:d}),{success:!1,logEntryId:e,error:l}}return u&&(this._recentlySentIds.add(u),setTimeout(()=>this._recentlySentIds.delete(u),300*1e3)),w(e),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"delivered",messageType:d}),{success:!0,messageId:u??void 0,logEntryId:e}}else{let t="No channelId/chatId or webhookUrl provided";return f(e,"failed",t),r&&this._dedupCache.delete(r),{success:!1,logEntryId:e,error:t}}}catch(t){let i=t instanceof Error?t.message:String(t);return f(e,"failed",i),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:i,messageType:d}),{success:!1,logEntryId:e,error:i}}}},_=null;function W(){return _||(_=new v),_}function q(s){return W().isRecentlySent(s)}export{v as a,W as b,q as c};
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import{a as re}from"./chunk-5V36ACKZ.js";import{a as Ae,c as Ne,d as Ue,e as Z,f as $e,g as Oe,h as je,i as It,j as Fe,k as He,l as N,n as we,o as Ke,p as Qe}from"./chunk-HQ66TFYI.js";import{b as Ee,c as ge,e as De}from"./chunk-YHH3QMLL.js";import{b as z}from"./chunk-6THDALGC.js";import{a as Ye,c as ve,e as ze}from"./chunk-L4Y3GR6W.js";import{a as ee,b as x,c as te,d as We,e as Je}from"./chunk-NOUSHXGX.js";import{a as Y,b as y,c as O,d as E}from"./chunk-XAMLLKKA.js";import{d as be}from"./chunk-KO5AFX5U.js";import{j as ye}from"./chunk-JKPSEMUZ.js";import{e as Pe,f as Q,g as Le,i as me,j as X}from"./chunk-24GTCFEV.js";import{a as fe}from"./chunk-L7JP7DUO.js";import{g as Ge}from"./chunk-7BSWC62F.js";import{a as he,b as j,c as Ve,f as Be,g as qe}from"./chunk-T7GEINGZ.js";import{d as T,j as Re}from"./chunk-GSMC3VUM.js";import{e as Me,f as ue,h as vt,j as xe,k as v,m as D,n as A,o as Ce,p as pe,q as K}from"./chunk-J3NIPZ73.js";import{b as w,d as de}from"./chunk-4VHBKJD5.js";import{c as S,d as _e,h as $}from"./chunk-INNDBLZE.js";import{f as P}from"./chunk-FCV2DPZQ.js";import{createSdkMcpServer as Gt,tool as p}from"@anthropic-ai/claude-agent-sdk";import{z as o}from"zod";K();X();import{v4 as G}from"uuid";de();function Tt(e){return{id:e.id,goalId:e.goal_id,level:e.level,parentId:e.parent_id??void 0,name:e.name,description:e.description??void 0,weight:e.weight,calibrationFactor:e.calibration_factor,createdAt:e.created_at}}function F(e){w().prepare(`
|
|
2
|
+
INSERT INTO metric_tree (id, goal_id, level, parent_id, name, description,
|
|
3
|
+
weight, calibration_factor, created_at)
|
|
4
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
5
|
+
`).run(e.id,e.goalId,e.level,e.parentId??null,e.name,e.description??null,e.weight,e.calibrationFactor,e.createdAt)}function Xe(e){return w().prepare("SELECT * FROM metric_tree WHERE goal_id = ? ORDER BY level, created_at").all(e).map(Tt)}$();var St=S("goal-manager");async function Br(e){let t;try{let n=JSON.parse(e);t={name:n.name??"",description:n.description,metric:n.metric??"",targetValue:n.targetValue??0,currentValue:n.currentValue??0,deadline:n.deadline??0,budget:n.budget??0,roleId:n.roleId??"engineer",status:"active"}}catch{t=await kt(e)}let r=Rt(t);return{goalState:t,validationResult:r,rawInput:e}}async function kt(e){let t=`Extract SMART goal fields from this natural language input.
|
|
6
|
+
|
|
7
|
+
Input: "${e}"
|
|
8
|
+
|
|
9
|
+
Respond ONLY with a JSON object:
|
|
10
|
+
{
|
|
11
|
+
"name": "short goal name (max 100 chars)",
|
|
12
|
+
"description": "detailed description of what the goal aims to achieve",
|
|
13
|
+
"metric": "measurable metric name (e.g. completion, reports_written, accuracy_score)",
|
|
14
|
+
"targetValue": <number, the target to reach>,
|
|
15
|
+
"deadline_days": <number, days from now to complete>,
|
|
16
|
+
"budget": <number, estimated budget in USD>,
|
|
17
|
+
"role": "<best matching role: engineer | analyst | content_creator | reviewer>"
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
Rules:
|
|
21
|
+
- name: concise, actionable title
|
|
22
|
+
- metric: quantifiable measure of success; use "completion" if the goal is binary (done/not done)
|
|
23
|
+
- targetValue: realistic target for the metric; use 1 for binary goals
|
|
24
|
+
- deadline_days: reasonable timeframe; default 7 if unclear
|
|
25
|
+
- budget: estimated cost in USD; default 5 if unclear
|
|
26
|
+
- role: match to the nature of work (research=analyst, writing=content_creator, coding=engineer, review=reviewer)`;try{let n=(await re(t,"You extract structured SMART goal fields from natural language. Reply with only valid JSON.")).match(/\{[\s\S]*\}/);if(n){let a=JSON.parse(n[0]),i=a.deadline_days??7;return{name:(a.name??e.slice(0,100)).slice(0,100),description:a.description??e,metric:a.metric??"completion",targetValue:a.targetValue??1,currentValue:0,deadline:Date.now()+i*24*60*60*1e3,budget:a.budget??5,roleId:a.roleId??"engineer",status:"active"}}}catch(r){St.warn({error:r},"LLM goal parsing failed, using fallback")}return{name:e.trim().slice(0,100),description:e.trim(),metric:"completion",targetValue:1,currentValue:0,deadline:Date.now()+10080*60*1e3,budget:5,roleId:"engineer",status:"active"}}function Rt(e){let t=[],r=[];return(!e.name||e.name.trim().length===0)&&t.push("S: name must be non-empty"),(!e.description||e.description.trim().length===0)&&t.push("S: description must be non-empty"),(!e.metric||e.metric.trim().length===0)&&t.push("M: metric must be specified"),e.targetValue<=0&&t.push("A: targetValue must be > 0"),(!e.roleId||e.roleId.trim().length===0)&&t.push("R: roleId must be non-empty"),e.deadline<=Date.now()&&t.push("T: deadline must be in the future"),e.budget<=0&&r.push("budget is zero or negative; goal will have no spending limit"),{isValid:t.length===0,errors:t,warnings:r}}function qr(e,t,r){let n=G(),a=Date.now(),i={id:n,name:e.name,description:e.description,roleId:e.roleId,metricType:e.metric,targetValue:e.targetValue,currentValue:e.currentValue,deadline:e.deadline,budgetUsd:e.budget,status:e.status,createdAt:a,deliverTo:t,reportTo:r};return ee(i),i}function Ze(e,t){let r=Date.now(),n=[],a={id:G(),goalId:e,level:"L0",name:`${t}_goal_progress`,description:`Goal-level ${t} progress (monthly)`,weight:1,calibrationFactor:1,createdAt:r};n.push(a),F(a);let i={id:G(),goalId:e,level:"L1",parentId:a.id,name:`${t}_weekly_trend`,description:`Weekly trend for ${t}`,weight:.8,calibrationFactor:1,createdAt:r};n.push(i),F(i);let l={id:G(),goalId:e,level:"L2",parentId:i.id,name:`${t}_daily_process`,description:`Daily process metric for ${t}`,weight:.6,calibrationFactor:1,createdAt:r};n.push(l),F(l);let d={id:G(),goalId:e,level:"L3",parentId:l.id,name:`${t}_per_task`,description:`Per-task instant metric for ${t}`,weight:.4,calibrationFactor:1,createdAt:r};return n.push(d),F(d),n}var ne=class{static collect(t,r){let n=y(t);if(!n)return this.emptyMetrics(t,r);let a=z(t,500,0),i=n.completedAt&&n.startedAt?n.completedAt-n.startedAt:0,l=new Set,d=0,u=0;for(let m of a)m.type==="tool_call"&&m.toolName&&l.add(m.toolName),m.type==="error"&&d++,m.type==="approval_request"&&u++;let c={taskId:t,goalId:r,timestamp:Date.now(),durationMs:i,costUsd:n.costUsd??0,turns:n.numTurns??0,toolCount:l.size,errorCount:d,approvalCount:u,rawScore:0,isComplete:n.status==="completed"};return c.rawScore=this.computeRawScore(c),c}static computeRawScore(t){let n=1-Math.min(t.durationMs/6e5,1),i=1-Math.min(t.costUsd/5,1),d=1-Math.min(t.turns/50,1),u;t.toolCount>=3&&t.toolCount<=15?u=1:t.toolCount<3?u=t.toolCount/3:u=Math.max(0,1-(t.toolCount-15)/15);let c=t.errorCount===0?1:Math.max(0,1-t.errorCount*.2),m=Math.min(1,.5+t.approvalCount*.25);return .3*n+.2*i+.2*d+.1*u+.15*c+.05*m}static cache=new Map;static persist(t){this.cache.set(t.taskId,t)}static getCached(t){return this.cache.get(t)}static clearCache(){this.cache.clear()}static emptyMetrics(t,r){return{taskId:t,goalId:r,timestamp:Date.now(),durationMs:0,costUsd:0,turns:0,toolCount:0,errorCount:0,approvalCount:0,rawScore:0,isComplete:!1}}};de();function _t(e){return{id:e.id,strategyId:e.strategy_id,goalId:e.goal_id,taskId:e.task_id??void 0,reward:e.reward??void 0,metricL2Score:e.metric_l2_score??void 0,metricL3Score:e.metric_l3_score??void 0,context:e.context??void 0,completedAt:e.completed_at}}function et(e){w().prepare(`
|
|
27
|
+
INSERT INTO trials (id, strategy_id, goal_id, task_id, reward,
|
|
28
|
+
metric_l2_score, metric_l3_score, context, completed_at)
|
|
29
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
30
|
+
`).run(e.id,e.strategyId,e.goalId,e.taskId??null,e.reward??null,e.metricL2Score??null,e.metricL3Score??null,e.context??null,e.completedAt)}function tt(e,t=100){return w().prepare("SELECT * FROM trials WHERE goal_id = ? ORDER BY completed_at DESC LIMIT ?").all(e,t).map(_t)}var oe=class{static collect(t){let r=x(t);if(!r)return this.emptyMetrics(t);let n=Date.now(),a=r.targetValue>0?Math.min(r.currentValue/r.targetValue,1):0,i=Math.max(0,(r.deadline-n)/(1e3*60*60*24)),l=this.calculateBudgetSpent(t),d=r.budgetUsd>0?Math.max(0,1-l/r.budgetUsd):1,u=this.calculateExpectedCompletion(r),c={goalId:t,metricType:r.metricType,targetValue:r.targetValue,currentValue:r.currentValue,progressPct:a,deadlineRemainingDays:i,budgetRemainingPct:d,expectedCompletionPct:u,rawScore:0};return c.rawScore=this.computeRawScore(c),c}static computeRawScore(t){let r=Math.min(t.progressPct,1),n;t.expectedCompletionPct>=1?n=1:t.expectedCompletionPct>=.8?n=.5+(t.expectedCompletionPct-.8)*2.5:n=t.expectedCompletionPct*.625;let a=t.budgetRemainingPct;return .5*r+.3*n+.2*a}static calculateExpectedCompletion(t){let r=Date.now(),n=t.deadline-t.createdAt,a=r-t.createdAt;if(n<=0)return 0;let i=a/n;if(i<.1)return .5;let l=t.targetValue>0?t.currentValue/t.targetValue:0;return i>0?l/i:0}static calculateBudgetSpent(t){let r=tt(t,1e3),n=0,a=new Set;for(let i of r)if(i.taskId&&!a.has(i.taskId)){a.add(i.taskId);let l=y(i.taskId);l?.costUsd&&(n+=l.costUsd)}return n}static emptyMetrics(t){return{goalId:t,metricType:"",targetValue:0,currentValue:0,progressPct:0,deadlineRemainingDays:0,budgetRemainingPct:0,expectedCompletionPct:0,rawScore:0}}};$();var Mt=S("agent"),V=class{static cache=new Map;static CACHE_TTL=1440*60*1e3;static async callClaude(t){let a=(await re(t,'You are an AI quality evaluator. Respond with JSON: {"score": 0-1, "confidence": 0-1, "reasoning": "..."}')).match(/\{[\s\S]*\}/);if(!a)throw new Error("Failed to parse LLM Judge response as JSON");let i=JSON.parse(a[0]);return{score:Math.max(0,Math.min(1,i.score??0)),confidence:Math.max(.3,Math.min(.95,i.confidence??.5)),reasoning:i.reasoning??"No reasoning provided"}}static async evaluate(t,r){let n=`${t}:${r}`,a=this.cache.get(n);if(a&&Date.now()-a.evaluatedAt<this.CACHE_TTL)return a;let i=y(t);if(!i){let f={taskId:t,criteria:r,score:0,confidence:.3,reasoning:"Task not found",evaluatedAt:Date.now()};return this.cache.set(n,f),f}let l=this.getPromptTemplate(i.prompt??"",i.result??i.error??"",r),d,u,c;try{let f=await this.callClaude(l);d=f.score,u=f.confidence,c=f.reasoning}catch(f){Mt.warn({error:f,taskId:t},"LLM Judge Claude API call failed, using heuristic fallback"),i.status==="failed"?(d=.1,u=.6,c=`Task failed: ${i.error??"unknown error"} (heuristic fallback)`):i.status==="completed"&&i.result?(d=.7,u=.5,c="Task completed with result (heuristic fallback due to API error)"):i.status==="completed"?(d=.5,u=.4,c="Task completed without explicit result (heuristic fallback)"):(d=.3,u=.3,c=`Task in status: ${i.status} (heuristic fallback)`)}let m={taskId:t,criteria:r,score:d,confidence:u,reasoning:c,evaluatedAt:Date.now()};return this.cache.set(n,m),m}static shouldUseObjective(t){let r=y(t);return r?r.status==="completed"&&r.costUsd!==void 0&&r.numTurns!==void 0:!1}static clearCache(){this.cache.clear()}static getPromptTemplate(t,r,n){return`You are an expert evaluator. Evaluate the following task result against these criteria:
|
|
31
|
+
|
|
32
|
+
Task: ${t}
|
|
33
|
+
Result: ${r}
|
|
34
|
+
Criteria: ${n}
|
|
35
|
+
|
|
36
|
+
Provide:
|
|
37
|
+
1. Score (0-1): How well did the task meet the criteria?
|
|
38
|
+
2. Confidence (0-1): How confident are you in this evaluation?
|
|
39
|
+
3. Reasoning: Brief explanation of your scoring
|
|
40
|
+
|
|
41
|
+
Respond in JSON: {"score": number, "confidence": number, "reasoning": "string"}`}};var xt={L0:.2,L1:.15,L2:.35,L3:.3},ae=class e{goalId;nodes;children;constructor(t,r){this.goalId=t,this.nodes=new Map(r.map(n=>[n.id,n])),this.children=new Map;for(let n of r){let a=n.parentId,i=this.children.get(a)??[];i.push(n),this.children.set(a,i)}this.validateAcyclicity()}validateAcyclicity(){for(let t of this.nodes.values()){if(t.parentId&&!this.nodes.has(t.parentId))continue;let r=new Set,n=t.id;for(;n;){if(r.has(n))throw new Error(`Cycle detected in metric tree at node ${n}`);r.add(n),n=this.nodes.get(n)?.parentId}}}static buildFromGoal(t){let r=Xe(t);return new e(t,r)}static fromNodes(t,r){return new e(t,r)}queryPath(t){let r=[];for(let n of this.nodes.values())n.level===t&&r.push(n);return r.sort((n,a)=>a.weight-n.weight)}aggregateScores(t,r){let n=this.queryPath(t);if(n.length===0)return 0;let a=0,i=0;for(let l of n){let d=r.get(l.id)??0,u=l.weight*l.calibrationFactor;a+=d*u,i+=u}return i>0?a/i:0}getWeightedScore(t){let r=0;for(let[n,a]of Object.entries(xt)){let i=this.aggregateScores(n,t);r+=i*a}return Math.max(0,Math.min(1,r))}getNodeCount(){return this.nodes.size}getChildren(t){return this.children.get(t)??[]}};$();var mn=S("agent");function ie(e,t){let r=Date.now(),n=ae.buildFromGoal(e),a=new Map,i=oe.collect(e);for(let u of n.queryPath("L0"))a.set(u.id,i.rawScore);let l=Ct(n);if(t){let u=ne.collect(t,e);if(u.isComplete){for(let m of n.queryPath("L3"))a.set(m.id,u.rawScore);let c=n.getNodeCount()>0?n.getWeightedScore(a):Math.max(0,Math.min(1,u.rawScore*.65+i.rawScore*.35));return{goalId:e,taskId:t,reward:c,breakdown:{L0:i.rawScore,L1:0,L2:0,L3:u.rawScore},calibrationFactors:l,source:"objective",confidence:.9,computedAt:r}}}if(t&&!V.shouldUseObjective(t)){let c=V.evaluate(t,"general_quality"),m=i.rawScore*.5+.5*.5;return{goalId:e,taskId:t,reward:i.rawScore,breakdown:{L0:i.rawScore,L1:0,L2:0,L3:0,llmJudge:.5},calibrationFactors:l,source:"llm_judge",confidence:.4,computedAt:r}}let d=n.getNodeCount()>0?n.getWeightedScore(a):i.rawScore;return{goalId:e,reward:d,breakdown:{L0:i.rawScore,L1:0,L2:0,L3:0},calibrationFactors:l,source:"fallback",confidence:.3,computedAt:r}}function Ct(e){let t={L0:1,L1:1,L2:1,L3:1};for(let r of["L0","L1","L2","L3"]){let n=e.queryPath(r);n.length>0&&(t[r]=n[0].calibrationFactor)}return t}import{v4 as it}from"uuid";de();function se(e){return{id:e.id,roleId:e.role_id,taskType:e.task_type,name:e.name,promptTemplate:e.prompt_template,alpha:e.alpha,beta:e.beta,totalTrials:e.total_trials,avgReward:e.avg_reward??void 0,createdAt:e.created_at,updatedAt:e.updated_at??void 0}}function rt(e){w().prepare(`
|
|
42
|
+
INSERT INTO strategies (id, role_id, task_type, name, prompt_template,
|
|
43
|
+
alpha, beta, total_trials, avg_reward, created_at, updated_at)
|
|
44
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
45
|
+
`).run(e.id,e.roleId,e.taskType,e.name,e.promptTemplate,e.alpha,e.beta,e.totalTrials,e.avgReward??null,e.createdAt,e.updatedAt??null)}function nt(e){let r=w().prepare("SELECT * FROM strategies WHERE id = ?").get(e);return r?se(r):void 0}function hn(e=100){return w().prepare("SELECT * FROM strategies ORDER BY created_at LIMIT ?").all(e).map(se)}function ot(e){return w().prepare("SELECT * FROM strategies WHERE role_id = ? ORDER BY created_at").all(e).map(se)}function L(e,t){return w().prepare("SELECT * FROM strategies WHERE role_id = ? AND task_type = ? ORDER BY created_at").all(e,t).map(se)}function at(e,t){w().prepare(`
|
|
46
|
+
UPDATE strategies
|
|
47
|
+
SET alpha = alpha + ?,
|
|
48
|
+
beta = beta + ?,
|
|
49
|
+
total_trials = total_trials + 1,
|
|
50
|
+
avg_reward = CASE
|
|
51
|
+
WHEN total_trials = 0 THEN ?
|
|
52
|
+
ELSE (avg_reward * total_trials + ?) / (total_trials + 1)
|
|
53
|
+
END,
|
|
54
|
+
updated_at = ?
|
|
55
|
+
WHERE id = ?
|
|
56
|
+
`).run(t,1-t,t,t,Date.now(),e)}var B=class{static sampleBeta(t,r){let n=this.sampleGamma(t,1),a=this.sampleGamma(r,1);return n/(n+a)}static sampleGamma(t,r){if(t<1)return this.sampleGamma(t+1,r)*Math.pow(Math.random(),1/t);let n=t-1/3,a=1/Math.sqrt(9*n);for(;;){let i,l;do i=this.randn(),l=1+a*i;while(l<=0);l=l*l*l;let d=Math.random();if(d<1-.0331*i*i*i*i||Math.log(d)<.5*i*i+n*(1-l+Math.log(l)))return n*l/r}}static randn(){let t=Math.random(),r=Math.random();return Math.sqrt(-2*Math.log(t))*Math.cos(2*Math.PI*r)}static sample(t){if(t.length===0)return null;let r=null,n=-1;for(let a of t){let i=this.sampleBeta(a.alpha,a.beta);i>n&&(n=i,r=a)}return r}static getProbabilities(t,r=1e4){let n=new Map;for(let i=0;i<r;i++){let l=this.sample(t);l&&n.set(l.id,(n.get(l.id)||0)+1)}let a=new Map;for(let[i,l]of n)a.set(i,l/r);return a}};var Pt=5,Ie=20,st=.5,k=class{static selectStrategy(t,r){let n=L(t,r);return B.sample(n)}static recordTrial(t,r,n,a,i,l,d){at(t,a),et({id:it(),strategyId:t,goalId:r,taskId:n,reward:a,metricL2Score:i,metricL3Score:l,context:d,completedAt:Date.now()})}static getStrategies(t,r){return L(t,r)}static getStrategyById(t){return nt(t)}static getPopulationStats(t,r){let n=L(t,r);if(n.length===0)return{count:0,avgTrials:0,avgReward:0,minTrials:0,maxTrials:0};let i=n.reduce((u,c)=>u+c.totalTrials,0)/n.length,l=n.filter(u=>u.avgReward!==void 0).map(u=>u.avgReward),d=l.length>0?l.reduce((u,c)=>u+c,0)/l.length:0;return{count:n.length,avgTrials:i,avgReward:d,minTrials:Math.min(...n.map(u=>u.totalTrials)),maxTrials:Math.max(...n.map(u=>u.totalTrials))}}static shouldEvolve(t,r){let n=this.getPopulationStats(t,r);return n.count<Pt?!0:n.count<Ie&&n.maxTrials>0}static addStrategy(t,r,n,a){if(L(t,r).length>=Ie)throw new Error(`Strategy population at maximum (${Ie}) for ${t}/${r}`);let l={id:`strat-${it().slice(0,8)}`,roleId:t,taskType:r,name:n,promptTemplate:a,alpha:st,beta:st,totalTrials:0,createdAt:Date.now()};return rt(l),l}static getTopStrategies(t,r,n=3){let i=L(t,r).filter(l=>l.totalTrials>0);return i.sort((l,d)=>(d.avgReward??0)-(l.avgReward??0)),i.slice(0,n)}static getSamplingProbabilities(t,r){let n=L(t,r);return B.getProbabilities(n)}static evaluateAndRecord(t,r,n,a,i,l){let d=ie(r,n);return this.recordTrial(t,r,n,d.reward,a,i,l),d.reward}};var Lt=3,Et=2,le=class{static async generateVariants(t,r,n=Lt,a=Et){let i=k.getTopStrategies(t,r,n);if(i.length===0){let d=`baseline-${r}-v1`;return k.addStrategy(t,r,d,this.generateBaselinePrompt(t,r)),[d]}let l=[];for(let d=0;d<a;d++){let u=i[0].totalTrials+d+1,c=`${r}-evolved-v${u}`,m=i[0].promptTemplate,f=this.mutateTemplate(m);k.addStrategy(t,r,c,f),l.push(c)}return l}static generateBaselinePrompt(t,r){return`You are a ${t} agent specializing in ${r}.
|
|
57
|
+
|
|
58
|
+
## Core Focus
|
|
59
|
+
Complete tasks with high quality.
|
|
60
|
+
|
|
61
|
+
## Approach
|
|
62
|
+
1. Understand the task requirements thoroughly
|
|
63
|
+
2. Plan your approach before executing
|
|
64
|
+
3. Execute systematically, checking your work
|
|
65
|
+
4. Verify completion against requirements`}static mutateTemplate(t){let r=[this.addProcessEmphasis(),this.addQualityFocus(),this.addVerificationStep()],n=r[Math.floor(Math.random()*r.length)];return`${t}
|
|
66
|
+
|
|
67
|
+
## Evolution
|
|
68
|
+
${n}`}static addProcessEmphasis(){let t=["Break down complex tasks into smaller steps","Iterate on solutions, testing each component","Document your reasoning at each step"];return`**Process:** ${t[Math.floor(Math.random()*t.length)]}`}static addQualityFocus(){let t=["Double-check all outputs before completing","Consider edge cases and error conditions","Optimize for correctness over speed"];return`**Quality:** ${t[Math.floor(Math.random()*t.length)]}`}static addVerificationStep(){return"**Verification:** After completing, verify your work meets all requirements."}static async generateWithLLM(t,r,n){return{promptTemplate:this.generateBaselinePrompt(t,r),rationale:"Generated baseline - LLM integration in Phase 5"}}};$();Fe();import{v4 as I}from"uuid";import{spawnSync as lt}from"child_process";import{createRequire as Dt}from"module";import{dirname as At,join as ct}from"path";import{openSync as Nt,readFileSync as Ut,unlinkSync as $t}from"fs";var Ot=3e4,dt=12e4;function ut(){let t=Dt(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk");return ct(At(t),"cli.js")}function q(e,t){let r=ut(),n=t?.timeout??Ot;if(t?.json){let i=ct("/tmp",`adam-cli-stdout-${process.pid}-${Date.now()}.txt`),l=Nt(i,"w");try{let d=lt("node",[r,...e],{cwd:t.cwd,timeout:n,stdio:["ignore",l,"pipe"],encoding:"utf-8"});if(d.status!==0)throw new Error(d.stderr?.trim()||`CLI exited with status ${d.status}`);return Ut(i,"utf-8")}finally{try{$t(i)}catch{}}}let a=lt("node",[r,...e],{cwd:t?.cwd,timeout:n,encoding:"utf-8"});if(a.status!==0)throw new Error(a.stderr?.trim()||`CLI exited with status ${a.status}`);return a.stdout}function pt(){let e=q(["plugin","list","--available","--json"],{json:!0});return JSON.parse(e)}function Te(e,t="user",r){return q(["plugin","install",e,"--scope",t],{cwd:r,timeout:dt})}function Se(e,t,r){let n=["plugin","uninstall",e];return t&&n.push("--scope",t),q(n,{cwd:r,timeout:dt})}function mt(e,t){return q(["plugin","enable",e])}function gt(e,t){return q(["plugin","disable",e])}function Ln(){try{return!!ut()}catch{return!1}}$();import*as ft from"crypto";var W=S("api"),J=class{cancelTask(t){let r=y(t);r&&(O(t,{status:"cancelled",completedAt:Date.now()}),fe.emit({type:"task_status_change",taskId:t,oldStatus:r.status,newStatus:"cancelled"}),W.debug({taskId:t,oldStatus:r.status},"Task cancelled"))}resolveApproval(t,r,n){return W.debug({approvalId:t,action:r,reason:n},"Approval resolved (no-op in Pure C)"),!0}resolvePlanApproval(t,r,n,a){let i=Ee(t);if(!i)return W.warn({planId:t},"Plan not found or already resolved"),!1;let l=y(i.taskId);return l?(De(t,r==="allow"?"approved":"denied",n),r==="allow"&&n==="permanent"&&Ae({id:ft.randomUUID(),roleId:i.roleId,taskPattern:l.prompt.slice(0,100).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),maxRiskLevel:i.plan.overallRisk,createdAt:Date.now(),createdByTaskId:l.id}),fe.emit({type:"plan_approval_decision",taskId:l.id,planId:t,decision:r,approvalType:n,reason:a}),W.debug({planId:t,decision:r,approvalType:n},"Plan approval resolved"),!0):(W.warn({planId:t},"Task not found for plan"),!1)}};import{existsSync as bt}from"fs";function ht(e,t){return t?{allowedTools:Ft(t.allowedTools,e.allowedTools),disallowedTools:ke(e.disallowedTools,t.disallowedTools),approvalRequired:ke(e.approvalRequired,t.approvalRequired),maxBudgetUsd:t.maxBudgetUsd!==void 0&&t.maxBudgetUsd>0?Math.min(t.maxBudgetUsd,e.maxBudgetUsd):e.maxBudgetUsd,plugins:ke(e.plugins??[],t.plugins)}:{allowedTools:e.allowedTools,disallowedTools:e.disallowedTools,approvalRequired:e.approvalRequired,maxBudgetUsd:e.maxBudgetUsd,plugins:e.plugins??[]}}function Ft(e,t){if(e===void 0)return t;if(e.length===0)return[];if(t.length===0)return e;let r=new Set(t);return e.filter(n=>r.has(n))}function ke(e,t){return t===void 0?e:[...new Set([...e,...t])]}vt();var H=S("manager");function s(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}async function R(e){let{listChannels:t}=await import("./channels-PUOPR5Y2.js"),r=t(),{listSessions:n}=await import("./session-manager-PWJLU6KZ.js"),a=[...n("active"),...n("archived")],i=[];for(let l of e)if(l.type==="session"&&l.sessionId)i.push({type:"session",sessionId:l.sessionId});else if(l.type==="channel"){let d=l.channelId,u=l.chatId;if(!d&&l.channelName){let c=r.find(m=>m.name.toLowerCase().includes(l.channelName.toLowerCase()));c&&(d=c.id)}if(d&&!u){let c=a.find(m=>m.source.type==="channel"&&m.source.channelId===d&&m.source.chatId);c?.source.chatId?u=c.source.chatId:u=r.find(f=>f.id===d)?.config?.userId}d&&u?i.push({type:"channel",channelId:d,chatId:u}):H.warn({channelName:l.channelName,channelId:d,chatId:u},"Could not resolve channel notify target")}return i}async function Vt(e){let{listRoles:t}=await import("./roles-3AEHVOEW.js"),r=t(void 0,100,0);for(let n of r)if(n.name.toLowerCase().includes(e.toLowerCase()))return n.id}var Bt={goalId:o.string()},qt={goalId:o.string(),status:o.string().optional(),currentValue:o.number().optional(),budgetUsd:o.number().optional(),notes:o.string().optional()},Wt={goalId:o.string(),goalDescription:o.string(),maxSubtasks:o.number().optional()},_=o.union([o.object({type:o.literal("session"),sessionId:o.string()}),o.object({type:o.literal("channel"),channelName:o.string()}),o.object({type:o.literal("channel"),channelId:o.string(),chatId:o.string().optional()})]),Jt={prompt:o.string(),roleId:o.string().describe("Role ID. Call list_roles first to find the best role for the task."),deliverTo:o.array(_).optional().describe("Where to deliver the task output (result full text). E.g., send result to a specific channel."),reportTo:o.array(_).optional().describe("Where to send status reports (completion summary). Defaults to the originating channel/session."),toolOverrides:o.object({allowedTools:o.array(o.string()).optional(),disallowedTools:o.array(o.string()).optional()}).optional()},Ht={taskId:o.string(),goalId:o.string().optional(),strategyId:o.string().optional()},Yt={roleId:o.string(),taskType:o.string(),name:o.string().optional()},zt={status:o.string().optional(),limit:o.number().optional()},Kt={taskId:o.string(),roleId:o.string()},Qt={taskId:o.string().optional(),status:o.string().optional(),limit:o.number().optional()},Xt={roleId:o.string(),allowedTools:o.array(o.string()).optional(),disallowedTools:o.array(o.string()).optional(),osCapabilities:o.array(o.object({id:o.string().min(1),targets:o.array(o.string().min(1)).optional()})).optional().describe("Role-level OS capability grants. Use get_capabilities to inspect the runtime registry and valid target-scoped entries."),additionalDirectories:o.array(o.object({path:o.string(),mode:o.enum(["ro","rw"]).optional().describe("Read-only or read-write access. Default: rw. Enforced by OS sandbox."),inheritPlugins:o.boolean().optional(),inheritMcp:o.boolean().optional(),inheritPermissions:o.boolean().optional()})).optional(),allowedChannels:o.array(o.string()).optional(),inheritUserSettings:o.boolean().optional().describe("Enable/disable inheriting user-level settings (global plugins, MCP servers). Default: false (isolated).")},Zt={roleId:o.string().describe("Role ID to update."),name:o.string().min(1).optional(),cagPrompt:o.string().optional(),learnedRules:o.array(o.string()).optional(),status:o.enum(["active","inactive","retired"]).optional(),executionMode:o.enum(["isolated","inline"]).optional(),model:o.string().optional(),maxBudgetUsd:o.number().optional(),approvalRequired:o.array(o.string()).optional(),preferences:o.object({model:o.string().optional(),effort:o.enum(["low","medium","high","max"]).optional(),maxTurns:o.number().optional()}).optional(),permissionMode:o.enum(["default","acceptEdits","dontAsk","bypassPermissions","plan","auto"]).optional(),allowedBashPatterns:o.array(o.string()).optional(),deniedBashPatterns:o.array(o.string()).optional(),evaluationCriteria:o.record(o.string(),o.number()).optional(),envVars:o.record(o.string(),o.string()).optional()},er={roleId:o.string().optional(),limit:o.number().optional()},tr={name:o.string(),cagPrompt:o.string(),traits:o.array(o.string()).optional(),allowedTools:o.array(o.string()).optional(),disallowedTools:o.array(o.string()).optional(),osCapabilities:o.array(o.object({id:o.string().min(1),targets:o.array(o.string().min(1)).optional()})).optional().describe("Initial Role-level OS capability grants. Use get_capabilities to discover editable capability ids and target rules."),additionalDirectories:o.array(o.object({path:o.string(),mode:o.enum(["ro","rw"]).optional().describe("Read-only or read-write access. Default: rw. Enforced by OS sandbox."),inheritPlugins:o.boolean().optional(),inheritMcp:o.boolean().optional(),inheritPermissions:o.boolean().optional()})).optional()},rr={roleId:o.string(),reason:o.string().optional()},nr={name:o.string(),description:o.string().optional(),roleId:o.string().optional(),metric:o.string().optional(),targetValue:o.number().optional(),deadline:o.number().optional(),budgetUsd:o.number().optional(),deliverTo:o.array(_).optional().describe("Where to deliver goal completion notifications.")},or={name:o.string(),description:o.string().optional(),triggerType:o.enum(["cron","event"]),triggerCron:o.string().optional(),triggerEvent:o.string().optional(),prompt:o.string(),roleId:o.string().optional(),enabled:o.boolean().optional(),goalIds:o.array(o.string()).optional(),deliverTo:o.array(_).optional().describe("Where to deliver the task output (result full text)."),reportTo:o.array(_).optional().describe("Where to send status reports (completion summary).")},ar={status:o.enum(["active","retired","probation"]).optional(),limit:o.number().optional()},ir={enabled:o.boolean().optional()},sr={},lr={},cr={prompt:o.string().describe("The task prompt to execute after the delay"),delayMinutes:o.number().optional().describe("Minutes from now to execute (e.g., 30 for 'half an hour later')"),runAt:o.string().optional().describe("ISO 8601 timestamp to execute at (e.g., '2026-04-01T15:00:00+08:00')"),roleId:o.string().describe("Role ID to assign the task to. Call list_roles first."),deliverTo:o.array(_).optional().describe("Where to deliver the task output (result full text)."),reportTo:o.array(_).optional().describe("Where to send status reports (completion summary).")},dr={roleId:o.string().optional().describe("If provided, shows which plugins are installed in that role's workspace.")},ur={roleId:o.string().describe("Role ID to install the plugin under (project-scope)."),pluginId:o.string().describe("Plugin ID (e.g. 'github@anthropic'). Use list_available_plugins to discover available plugins.")},pr={roleId:o.string().describe("Role ID to uninstall the plugin from."),pluginId:o.string().describe("Plugin ID to uninstall.")},mr={roleId:o.string().describe("Role ID to bind the MCP server to."),mcpName:o.string().describe("Name for this MCP server (e.g., 'github', 'filesystem')."),mcpConfig:o.record(o.string(),o.unknown()).describe("MCP server configuration object.")},gr={roleId:o.string().describe("Role ID to unbind the MCP server from."),mcpName:o.string().describe("Name of the MCP server to remove.")},fr={pluginId:o.string().describe("Plugin ID (e.g., 'github@anthropic').")},hr={pluginId:o.string().describe("Plugin ID (e.g., 'github@anthropic').")},br={pluginId:o.string().describe("Plugin ID (e.g., 'github@anthropic').")},yr={pluginId:o.string().describe("Plugin ID (e.g., 'github@anthropic').")},wr={},vr={},Ir={pluginId:o.string().describe("Plugin ID (e.g., 'github@anthropic').")},Tr={roleId:o.string().describe("Role ID to associate scanned plugins with."),path:o.string().describe("Directory path to scan for .claude/settings.json.")},Sr={taskId:o.string().describe("Task ID to cancel.")},kr={taskId:o.string().describe("Task ID to get logs for."),limit:o.number().optional().describe("Max log entries (default 20).")},Rr={roleId:o.string().describe("Role ID to delete.")},_r={},Mr={updates:o.record(o.string(),o.unknown()).describe("Config key-value pairs to update. Example: { 'defaults.maxTurns': 50, 'logging.level': 'debug' }")},xr={roleId:o.string().describe("Role ID to list memories for."),limit:o.number().optional().describe("Max results (default 20).")},Cr={templateId:o.string().describe("Template ID to update."),name:o.string().optional(),enabled:o.boolean().optional(),prompt:o.string().optional(),triggerCron:o.string().optional(),triggerEvent:o.string().optional(),roleId:o.string().optional()},Pr={templateId:o.string().describe("Template ID to delete.")},Lr={templateId:o.string().describe("Template ID to run immediately.")},Er={enabled:o.boolean().optional().describe("Filter by enabled status.")},Dr={eventType:o.string().describe("Event type that triggers this rule (e.g., 'task_complete')."),channelId:o.string().describe("Channel ID to deliver to."),format:o.string().optional().describe("Format template (e.g., 'summary', 'full'). Default: 'summary'."),matchCriteria:o.record(o.string(),o.unknown()).optional().describe("JSON match criteria for event fields."),enabled:o.boolean().optional().describe("Enable this rule immediately (default true).")},Ar={ruleId:o.string().describe("Delivery rule ID to delete.")},Nr={roleId:o.string().optional().describe("Role ID to filter strategies by.")},yt=[p("read_goal_state","Read a single goal's detailed state: progress percentage, time remaining, budget spent, and current value. Use this for deep-dive on one goal; use list_goals for an overview of all goals.",Bt,async e=>{let t=x(e.goalId);if(!t)return s({error:"Goal not found"});let r=Date.now(),n=t.targetValue>0?t.currentValue/t.targetValue:0;return s({id:t.id,name:t.name,description:t.description,roleId:t.roleId,metricType:t.metricType,targetValue:t.targetValue,currentValue:t.currentValue,deadline:t.deadline,budgetUsd:t.budgetUsd,status:t.status,progress:n,timeRemainingMs:Math.max(0,t.deadline-r),budgetRemainingUsd:t.budgetUsd})}),p("update_goal_state","Update a goal's status, current value, or budget.",qt,async e=>{let t={};return e.status&&(t.status=e.status),e.currentValue!==void 0&&(t.currentValue=e.currentValue),e.budgetUsd!==void 0&&(t.budgetUsd=e.budgetUsd),Object.keys(t).length>0&&(t.updatedAt=Date.now(),te(e.goalId,t)),s({success:!0})}),p("decompose_goal","Decompose a goal into actionable subtasks using LLM reasoning.",Wt,async e=>{let t=T(),r=Math.min(e.maxSubtasks??5,10);try{let{query:a}=await import("@anthropic-ai/claude-agent-sdk"),i=`Decompose this goal into ${r} actionable subtasks.
|
|
69
|
+
|
|
70
|
+
Goal: ${e.goalDescription}
|
|
71
|
+
|
|
72
|
+
Respond ONLY with a JSON array. Each item: {"description": "...", "prompt": "detailed task instruction", "complexity": "low|medium|high", "role": "engineer|analyst|content_creator|reviewer"}
|
|
73
|
+
|
|
74
|
+
Rules:
|
|
75
|
+
- Each subtask must be independently executable
|
|
76
|
+
- Order from foundational to dependent
|
|
77
|
+
- Be specific about what each subtask should accomplish
|
|
78
|
+
- For each subtask, specify the best role from: 'engineer', 'analyst', 'content_creator', 'reviewer'. Match role to the nature of the work.`,l=a({prompt:i,options:{cwd:process.cwd(),maxTurns:1,maxBudgetUsd:.02}}),d="";for await(let c of l){let m=c;m.type==="result"&&typeof m.result=="string"&&(d=m.result)}let u=d.match(/\[[\s\S]*\]/);if(u){let c=JSON.parse(u[0]),m=[];for(let f=0;f<Math.min(c.length,r);f++){let h=c[f],U=`subtask-${I().slice(0,8)}`,C=h.role,g=C?await Vt(C):void 0;Y({id:U,status:"pending",prompt:h.prompt,parentId:e.goalId,roleId:g,config:t.defaults,createdAt:Date.now()}),m.push({id:U,description:h.description,prompt:h.prompt,dependencies:f>0?[m[f-1].id]:[],estimatedComplexity:h.complexity??"medium",role:C})}if(m.length>0)return s({subtasks:m})}}catch(a){H.error({error:a},"LLM decomposition failed, using fallback")}let n=[];for(let a=0;a<r;a++){let i=`subtask-${I().slice(0,8)}`,l=`Subtask ${a+1} of goal: ${e.goalDescription.slice(0,100)}`,d=`${e.goalDescription}
|
|
79
|
+
|
|
80
|
+
Subtask ${a+1}/${r}`;Y({id:i,status:"pending",prompt:d,parentId:e.goalId,config:t.defaults,createdAt:Date.now()}),n.push({id:i,description:l,prompt:d,dependencies:a>0?[n[a-1].id]:[],estimatedComplexity:"medium"})}return s({subtasks:n})}),p("dispatch_task","Create and immediately dispatch a task to the execution pool. roleId is required \u2014 call list_roles first to find the best role. The assigned role determines which tools the worker can use. Pass deliverTo (result delivery) and/or reportTo (status reports) to route output when the task completes.",Jt,async e=>{let t=v(e.roleId);if(!t||t.status!=="active"){let ce=A("active",20,0).filter(M=>M.source!=="system").map(M=>({id:M.id,name:M.name,allowedTools:M.allowedTools??[],capabilitySummary:N(M)}));return s({error:`Role not found or not active: ${e.roleId}. Pick a roleId from the list below.`,availableRoles:ce})}let r=I(),n=T(),a=e.prompt.toLowerCase(),i={coding:["code","implement","fix","debug","refactor","build"],analysis:["analyze","data","report","statistics","investigate"],content:["write","translate","summarize","content","draft"],review:["review","check","audit","evaluate","assess"],admin:["config","permission","deploy","manage"]},l="general";for(let[ce,M]of Object.entries(i))if(M.some(wt=>a.includes(wt))){l=ce;break}let d,u=e.prompt,c=k.selectStrategy(e.roleId,l);c?.promptTemplate&&(u=`${c.promptTemplate}
|
|
81
|
+
|
|
82
|
+
## Task
|
|
83
|
+
${e.prompt}`,d=c.id);let m=t?{allowedTools:t.allowedTools,disallowedTools:t.disallowedTools,approvalRequired:t.approvalRequired,maxBudgetUsd:t.maxBudgetUsd,plugins:void 0}:void 0,f=ht(n.defaults,m),h=f.allowedTools;e.toolOverrides?.allowedTools&&(h=[...e.toolOverrides.allowedTools]);let U={...n.defaults,...f,allowedTools:h,disallowedTools:e.toolOverrides?.disallowedTools??f.disallowedTools},C=e.deliverTo?await R(e.deliverTo):void 0,g=e.reportTo?await R(e.reportTo):void 0;Y({id:r,status:"pending",prompt:u,roleId:e.roleId,deliverTo:C,reportTo:g,config:U,createdAt:Date.now()});let{serverBus:b}=await import("./server-bus-GEGVMSCA.js");return b.emit({type:"task_created",taskId:r}),s({taskId:r,roleId:e.roleId,strategyId:d})}),p("dispatch_workflow","Create and execute a multi-role workflow. Use when the user's request decomposes into sequential or parallel steps handled by different roles. Each step is a complete task; roles handle conditions and decisions internally. Use {{stepId.result}} in prompts to reference prior step outputs. Minimum 2 steps.",{steps:o.array(o.object({id:o.string().describe("Unique step identifier"),prompt:o.string().describe("Task prompt for this step"),roleId:o.string().describe("Role ID for this step. Call list_roles first to find roles."),dependsOn:o.array(o.string()).optional().describe("Step IDs this step depends on"),config:o.object({timeout:o.number().optional(),maxTurns:o.number().optional()}).optional()})).min(2).describe("Workflow steps (min 2)"),name:o.string().optional().describe("Workflow name for tracking"),deliverTo:o.array(_).optional().describe("Where to deliver the aggregated workflow output"),reportTo:o.array(_).optional().describe("Where to send workflow status reports"),continueOnError:o.boolean().optional().describe("Continue remaining steps if one fails (default false)")},async e=>{let t=[];for(let g of e.steps){let b=v(g.roleId);(!b||b.status!=="active")&&t.push(g.roleId)}if(t.length>0){let g=A("active",20,0).filter(b=>b.source!=="system").map(b=>({id:b.id,name:b.name,capabilitySummary:N(b)}));return s({error:`Invalid or inactive roles: ${t.join(", ")}. Pick from available roles.`,availableRoles:g})}let r=new Set(e.steps.map(g=>g.id));for(let g of e.steps)if(g.dependsOn)for(let b of g.dependsOn){if(!r.has(b))return s({error:`Step "${g.id}" depends on unknown step "${b}"`});if(b===g.id)return s({error:`Step "${g.id}" cannot depend on itself`})}let n=new Set,a=new Set,i=new Map(e.steps.map(g=>[g.id,g.dependsOn??[]])),l=g=>{if(a.has(g))return!0;if(n.has(g))return!1;n.add(g),a.add(g);for(let b of i.get(g)??[])if(l(b))return!0;return a.delete(g),!1};for(let g of e.steps)if(l(g.id))return s({error:"Circular dependency detected in workflow steps"});let d=e.deliverTo?await R(e.deliverTo):void 0,u=e.reportTo?await R(e.reportTo):void 0,c=I(),m=T(),f={id:`workflow-${c}`,name:e.name??"Ad-hoc workflow",trigger:{type:"manual"},steps:e.steps.map(g=>({id:g.id,prompt:g.prompt,roleId:g.roleId,dependsOn:g.dependsOn,config:g.config})),enabled:!0,createdAt:Date.now(),config:{...m.defaults,continueOnError:e.continueOnError??!1},deliverTo:d,reportTo:u};he(f);let{WorkflowExecutor:h}=await import("./workflow-executor-XFTTJQNE.js");new h().execute(f,c).catch(g=>{H.error({executionId:c,error:g},"dispatch_workflow execution failed")});let C=e.steps.map(g=>v(g.roleId)?.name??g.roleId);return s({executionId:c,templateId:f.id,stepCount:e.steps.length,roles:[...new Set(C)],status:"started"})}),p("evaluate_result","Evaluate a completed task's result and record a trial for Thompson Sampling.",Ht,async e=>{let{goalId:t,taskId:r,strategyId:n}=e,a=ie(t??"",r);return n&&t&&k.recordTrial(n,t,r,a.reward,a.breakdown.L2||void 0,a.breakdown.L3||void 0,"Evaluated via adam-tools"),s({reward:a.reward,metricL2Score:a.breakdown.L2||void 0,metricL3Score:a.breakdown.L3||void 0,source:a.source,reasoning:`Evaluated via ${a.source} with confidence ${a.confidence.toFixed(2)}`})}),p("create_strategy","Create a new strategy variant for a role/taskType using LLM evolution.",Yt,async e=>{let{roleId:t,taskType:r}=e;await le.generateVariants(t,r,3,1);let n=k.getStrategies(t,r),a=n[n.length-1];return s(a?{id:a.id,name:a.name,promptTemplate:a.promptTemplate}:{error:`Failed to create strategy for ${t}/${r}`})}),p("list_goals","List all goals with progress percentage, budget, deadline, and time remaining. Goal statuses: active (in progress), paused, completed, failed. Use this to check current goal status before making decisions.",zt,async e=>{let t=e.status;return s(We(t,e.limit??10,0))}),p("delete_goal","Delete a goal by ID.",{goalId:o.string()},async e=>x(e.goalId)?(Je(e.goalId),s({success:!0,goalId:e.goalId})):s({error:"Goal not found"})),p("pause_goal","Pause an active goal.",{goalId:o.string()},async e=>x(e.goalId)?(te(e.goalId,{status:"paused",updatedAt:Date.now()}),s({success:!0,goalId:e.goalId,status:"paused"})):s({error:"Goal not found"})),p("assign_role","Assign a role to a pending task.",Kt,async e=>{let{taskId:t,roleId:r}=e;if(!y(t))return s({error:`Task not found: ${t}`});let a=v(r);return a?(O(t,{roleId:r}),H.debug({taskId:t,roleId:r,roleName:a.name},"Role assigned to task"),s({success:!0,taskId:t,roleId:r})):s({error:`Role not found: ${r}`})}),...He(),p("read_task_status","Read a single task's details (prompt, status, result, roleId) by ID, or list all tasks filtered by status (pending, running, completed, failed). Use this to check task progress and results.",Qt,async e=>{if(e.taskId){let r=y(e.taskId);return s(r??{error:"Task not found"})}let t=e.status;return s(E(t,e.limit??100,0))}),p("modify_role_permissions","Update a role's RBAC permissions (paths, tools, OS capabilities).",Xt,async e=>{if(!v(e.roleId))return s({error:`Role not found: ${e.roleId}`});let r={};if(e.allowedTools&&(r.allowedTools=e.allowedTools),e.disallowedTools&&(r.disallowedTools=e.disallowedTools),e.osCapabilities!==void 0)try{r.osCapabilities=ue(e.osCapabilities)}catch(n){return s({error:n instanceof Error?n.message:String(n)})}return e.additionalDirectories!==void 0&&(r.additionalDirectories=e.additionalDirectories),e.allowedChannels!==void 0&&(r.allowedChannels=e.allowedChannels),"inheritUserSettings"in e&&(r.inheritUserSettings=e.inheritUserSettings),D(e.roleId,r),s({success:!0})}),p("update_role","Update a role's identity and config fields (name, CAG prompt, learned rules, status, model, execution mode, preferences, permission mode, bash patterns, evaluation criteria, env vars). For permission fields (allowedTools, disallowedTools, osCapabilities, additionalDirectories, allowedChannels, inheritUserSettings) use modify_role_permissions instead.",Zt,async e=>{if(!v(e.roleId))return s({error:`Role not found: ${e.roleId}`});let{roleId:r,...n}=e,a={...n,updatedAt:Date.now()};D(r,a);let i=v(r);if(!i)return s({error:"Role disappeared after update"});if(e.cagPrompt!==void 0||e.learnedRules!==void 0){let l=Pe(i.name);bt(l)&&Le(l,i)}return s({success:!0,role:i})}),p("view_audit_log","View the evolution audit log for role changes.",er,async e=>{let{listEvolutionAudit:t}=await import("./evolution-audit-JZ2U7J4C.js"),r=t(e.limit??50);return s({entries:r})}),p("list_roles","List all roles with their capabilities including bound plugins (skills/agents). Use this to discover available roles before dispatching tasks.",ar,async e=>{let r=A(e.status,e.limit??50,0).map(n=>{let a=we(n);return{id:n.id,name:n.name,status:n.status,allowedTools:n.allowedTools??[],disallowedTools:n.disallowedTools??[],osCapabilities:n.osCapabilities??[],additionalDirectories:n.additionalDirectories??[],cagPrompt:n.cagPrompt.slice(0,500)+(n.cagPrompt.length>500?"...":""),capabilitySummary:N(n,a),plugins:a.plugins.map(i=>({name:i.name,skills:i.skills.map(l=>l.name),agents:i.agents.map(l=>l.name)}))}});return s({roles:r})}),p("create_role","Create a new role with a name, CAG prompt, and optional tool permissions or OS capabilities.",tr,async e=>{let t;try{t=ue(e.osCapabilities)}catch(a){return s({error:a instanceof Error?a.message:String(a)})}let r=`role-${I().slice(0,8)}`,n={id:r,name:e.name,cagPrompt:e.cagPrompt,learnedRules:[],memoryStreamId:`mem-${I().slice(0,8)}`,status:"active",preferences:{},createdAt:Date.now(),allowedTools:e.allowedTools,disallowedTools:e.disallowedTools,osCapabilities:t,additionalDirectories:e.additionalDirectories};return xe(n),Q(n),s({roleId:r,name:e.name,allowedTools:e.allowedTools,osCapabilities:n.osCapabilities,additionalDirectories:e.additionalDirectories??[]})}),p("retire_role","Retire a role (marks as retired, stops receiving tasks).",rr,async e=>v(e.roleId)?(D(e.roleId,{status:"retired"}),H.info({roleId:e.roleId,reason:e.reason},"Role retired"),s({success:!0})):s({error:`Role not found: ${e.roleId}`})),p("create_goal","Create a new goal with optional budget, deadline, and metric tracking.",nr,async e=>{let t=I(),r=Date.now(),n=r+10080*60*1e3,a={id:t,name:e.name,description:e.description,roleId:e.roleId??"engineer",metricType:e.metric??"completion",targetValue:e.targetValue??1,currentValue:0,deadline:e.deadline??n,budgetUsd:e.budgetUsd??5,status:"active",createdAt:r,deliverTo:e.deliverTo?await R(e.deliverTo):void 0};ee(a),Ze(t,a.metricType);let i=x(t);return s({goalId:i.id,name:i.name,status:i.status})}),p("create_template","Create a recurring scheduled task using cron expressions (e.g., 'every hour', 'daily at 9am', 'weekly'). For one-shot delayed tasks ('in 30 minutes', 'tomorrow at 3pm'), use schedule_task instead.",or,async e=>{let{createTaskTemplate:t}=await import("./task-templates-ED2UCUPE.js"),r=I(),n=I(),a=e.deliverTo?await R(e.deliverTo):void 0,i=e.reportTo?await R(e.reportTo):void 0,l={id:r,name:e.name,description:e.description,trigger:{type:e.triggerType,cron:e.triggerCron,event:e.triggerEvent},steps:[{id:n,prompt:e.prompt}],rolePreference:e.roleId,enabled:e.enabled??!0,createdAt:Date.now(),goalIds:e.goalIds,deliverTo:a,reportTo:i};return t(l),s({templateId:r,name:l.name,trigger:l.trigger})}),p("list_templates","List task templates (automations). Use this to check existing scheduled/recurring tasks before creating new ones.",{enabled:o.boolean().optional().describe("Filter by enabled status. Omit to list all."),limit:o.number().optional().describe("Max results (default 50)")},async e=>{let{listTaskTemplates:t}=await import("./task-templates-ED2UCUPE.js"),r=t(e.enabled,e.limit??50,0);return s(r.map(n=>({id:n.id,name:n.name,description:n.description,trigger:n.trigger,enabled:n.enabled,rolePreference:n.rolePreference,deliverTo:n.deliverTo,createdAt:n.createdAt})))}),p("send_to_channel","Send a message (text, image, voice, video, file) to a connected channel by name. Use this to deliver task results, media, or notifications to a specific channel (e.g., WeChat on iPad). For media: provide mediaUrl as an absolute local file path and mediaType. Do NOT use remote URLs \u2014 download files locally first.",{channelName:o.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:o.string().describe("The message content to send (text caption when sending media)"),mediaUrl:o.string().optional().describe("Absolute local file path to the media file (e.g. /Users/.../file.png). Must exist on disk. Do NOT use remote URLs \u2014 download files locally first."),mediaType:o.enum(["image","audio","video","file"]).optional().describe("Type of the media file. Required when mediaUrl is provided")},async e=>{if(e.mediaUrl){if(e.mediaUrl.includes("://")&&!e.mediaUrl.startsWith("file://"))return s({error:`mediaUrl must be a local file path, not a remote URL. Got: ${e.mediaUrl.slice(0,80)}. Download the file to a local path first, then pass the local path.`});let l=e.mediaUrl.startsWith("file://")?new URL(e.mediaUrl).pathname:e.mediaUrl;if(!bt(l))return s({error:`Media file not found: ${l}. Verify the file exists before sending.`});if(!e.mediaType)return s({error:"mediaType is required when mediaUrl is provided. Specify one of: image, audio, video, file."})}let t=await R([{type:"channel",channelName:e.channelName}]);if(t.length===0)return s({error:`Channel "${e.channelName}" not found or no chatId available`});let r=t[0];if(r.type!=="channel")return s({error:"Resolved target is not a channel"});let{getOutboundGateway:n}=await import("./outbound-gateway-U5LP54JG.js"),i=await n().send({channelId:r.channelId,chatId:r.chatId,content:e.message,messageType:"deliver",mediaUrl:e.mediaUrl,mediaType:e.mediaType});return s({success:i.success,channelName:e.channelName,...i.error?{error:i.error}:{}})}),p("list_channels","List all connected channels with their platform, status, and chatId for message delivery. Use this to discover available channels before sending messages or setting up notifications.",ir,async e=>{let t=be(e.enabled),r=[...ye("active"),...ye("archived")],n=t.map(a=>{let i,l=r.find(d=>d.source.type==="channel"&&d.source.channelId===a.id&&d.source.chatId);return l?.source.chatId?i=l.source.chatId:i=a.config?.userId,{id:a.id,name:a.name,platform:a.platform,status:a.status,chatId:i}});return s({channels:n})}),p("get_system_status","Get current system status: execution pool capacity (active/max/queued slots), running task count, and system health. Use this to check if the system has capacity before dispatching tasks.",sr,async()=>{let e=T(),t=E("running"),r=E("pending");return s({executionPool:{active:t.length,max:e.execution?.maxConcurrent??5,queued:r.length},timestamp:new Date().toISOString()})}),p("schedule_task","Schedule a one-shot delayed task. roleId is required \u2014 call list_roles first. Use this when the user wants something done later (e.g., '\u534A\u5C0F\u65F6\u540E', 'in 30 minutes', 'tomorrow at 3pm'). For recurring schedules ('every day', 'weekly'), use create_template instead.",cr,async e=>{let t=v(e.roleId);if(!t||t.status!=="active"){let f=A("active",20,0).filter(h=>h.source!=="system").map(h=>({id:h.id,name:h.name,allowedTools:h.allowedTools??[],capabilitySummary:N(h)}));return s({error:`Role not found or not active: ${e.roleId}. Pick a roleId from the list below.`,availableRoles:f})}let r=Date.now(),n;if(e.delayMinutes!==void 0&&e.runAt!==void 0)return s({error:"Provide exactly one of delayMinutes or runAt, not both"});if(e.delayMinutes!==void 0)n=r+e.delayMinutes*60*1e3;else if(e.runAt!==void 0){if(n=new Date(e.runAt).getTime(),isNaN(n))return s({error:"Invalid ISO 8601 timestamp in runAt"})}else return s({error:"Provide either delayMinutes or runAt"});if(n<=r)return s({error:"Scheduled time must be in the future"});let a=10080*60*1e3;if(n-r>a)return s({error:"Schedule exceeds maximum of 7 days"});let i=I(),l=new Date(n).toISOString(),d=e.deliverTo?await R(e.deliverTo):void 0,u=e.reportTo?await R(e.reportTo):void 0;he({id:i,name:e.prompt.slice(0,80),description:`One-shot scheduled task: ${e.prompt.slice(0,200)}`,trigger:{type:"once",runAt:l},steps:[{id:"main",prompt:e.prompt}],rolePreference:e.roleId,config:{...T().defaults},tags:["scheduled","once"],enabled:!0,createdAt:r,deliverTo:d,reportTo:u});let{getBreeEngine:c}=await import("./bree-engine-CRK73AI4.js"),m=c();return m&&m.scheduleOnceJob(i),s({templateId:i,executeAt:l,prompt:e.prompt})}),p("cancel_scheduled_task","Cancel a previously scheduled one-shot task by its template ID. The task will not execute.",{templateId:o.string().describe("The template ID returned by schedule_task")},async e=>{let t=j(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});if(t.trigger.type!=="once")return s({error:"This is not a one-shot scheduled task. Use disable_template for recurring automations."});Be(e.templateId);let{getBreeEngine:r}=await import("./bree-engine-CRK73AI4.js"),n=r();return n&&await n.unscheduleJob(e.templateId),s({cancelled:!0,templateId:e.templateId})}),p("list_available_plugins","List all installed plugins with their scope and global enabled state. If roleId is provided, shows which plugins are installed in that role's workspace.",dr,async e=>{let t=Ne(),r=Z(),n=e.roleId?(()=>{let{getRoleWorkspacePath:a}=(X(),P(me)),{getRole:i}=(K(),P(pe)),{listInstalledPlugins:l}=(Fe(),P(It)),d=i(e.roleId);if(!d)return[];let u=a(d.name);return l({scope:"project",projectPath:u}).map(c=>c.id)})():[];return s({plugins:r.map(a=>({id:a.id,name:a.name,scope:a.scope,projectPath:a.projectPath,enabled:a.enabled,globalEnabled:t[a.id]??a.enabled,isInstalledInRole:n.includes(a.id),description:a.version?`v${a.version}`:void 0}))})}),p("install_plugin_for_role","Install a plugin into a role's workspace (project-scope). The plugin will be available when that role executes tasks.",ur,async e=>{let{getRole:t}=(K(),P(pe)),{getRoleWorkspacePath:r}=(X(),P(me)),n=t(e.roleId);if(!n)return s({error:`Role not found: ${e.roleId}`});let a=r(n.name);try{return Te(e.pluginId,"project",a),s({success:!0,roleId:e.roleId,pluginId:e.pluginId,scope:"project",cwd:a})}catch(i){return s({error:`Failed to install plugin: ${i}`})}}),p("uninstall_plugin_from_role","Uninstall a plugin from a role's workspace.",pr,async e=>{let{getRole:t}=(K(),P(pe)),{getRoleWorkspacePath:r}=(X(),P(me)),n=t(e.roleId);if(!n)return s({error:`Role not found: ${e.roleId}`});let a=r(n.name);try{return Se(e.pluginId,"project",a),s({success:!0,roleId:e.roleId,pluginId:e.pluginId})}catch(i){return s({error:`Failed to uninstall plugin: ${i}`})}}),p("bind_mcp_to_role","Bind an MCP server configuration to a role. The MCP server will be available to the role during task execution.",mr,async e=>{let t=v(e.roleId);if(!t)return s({error:`Role not found: ${e.roleId}`});let n={...t.mcpServers??{},[e.mcpName]:e.mcpConfig};try{return D(e.roleId,{mcpServers:n}),Q(t),s({success:!0,roleId:e.roleId,mcpName:e.mcpName,mcpServers:n})}catch(a){return s({error:`Failed to bind MCP server: ${a}`})}}),p("unbind_mcp_from_role","Remove an MCP server binding from a role.",gr,async e=>{let t=v(e.roleId);if(!t)return s({error:`Role not found: ${e.roleId}`});let r={...t.mcpServers??{}};if(!(e.mcpName in r))return s({error:`MCP server "${e.mcpName}" not bound to this role`});delete r[e.mcpName];try{return D(e.roleId,{mcpServers:r}),Q(t),s({success:!0,roleId:e.roleId,mcpName:e.mcpName})}catch(n){return s({error:`Failed to unbind MCP server: ${n}`})}}),p("get_capabilities","Get a comprehensive overview of Adam's current capabilities: available roles and their tools, OS capability registry, connected channels, installed plugins, active automations, and execution capacity. Call this when the user asks what you can do, or asks for help.",lr,async()=>{let{listTaskTemplates:e}=await import("./task-templates-ED2UCUPE.js"),t=T(),r=A(void 0,100,0),n=be(),a=e(!0,100,0),i=E("running"),l=E("pending"),d=Ke(),u=await Qe();return s({roles:{description:"Specialized worker identities \u2014 each has its own tools, MCP servers, plugins (skills/agents), and learned rules",active:r.filter(c=>c.status==="active"&&c.source!=="system").map(c=>{let m=we(c);return{name:c.name,tools:c.allowedTools??[],osCapabilities:c.osCapabilities??[],mcpServers:Object.keys(c.mcpServers??{}),channels:c.allowedChannels??[],capabilitySummary:N(c,m),plugins:m.plugins.map(f=>({name:f.name,skills:f.skills.map(h=>h.name),agents:f.agents.map(h=>h.name)}))}}),retired:r.filter(c=>c.status==="retired").length,probation:r.filter(c=>c.status==="probation").length},osCapabilities:{description:"Role-level OS capability registry. Only editable entries can be assigned to roles on this runtime.",sandbox:{platform:d.platform,available:u},registry:Me(d.platform,u)},channels:{description:"Send/receive messages via connected platforms",connected:n.filter(c=>c.enabled).map(c=>({name:c.name,platform:c.platform,status:c.status}))},plugins:{description:"Extensions that add capabilities to roles",installed:Z().filter(c=>c.enabled).map(c=>({name:c.name,scope:c.scope,description:c.version?`v${c.version}`:void 0}))},automations:{description:"Recurring cron tasks and event-triggered templates",active:a.map(c=>({name:c.name,trigger:c.trigger}))},execution:{description:"Parallel task execution pool",maxConcurrent:t.execution?.maxConcurrent??5,running:i.length,queued:l.length},coreFeatures:["Goal management \u2014 SMART goals with budget/deadline/metric, auto-decomposition into subtasks","Memory \u2014 per-Role vector + keyword searchable memory across tasks","Strategy evolution \u2014 Thompson Sampling optimizes task approaches over time","Monitor \u2014 automatic quality scoring, role retirement/reinstatement","Delivery engine \u2014 event-driven result routing to channels/webhooks","Schedule \u2014 cron recurring templates + one-shot delayed tasks"]})}),p("enable_plugin","Enable a globally installed plugin (makes it available to all roles).",fr,async e=>{try{return mt(e.pluginId),s({success:!0,pluginId:e.pluginId})}catch(t){return s({error:`Failed to enable plugin: ${t}`})}}),p("disable_plugin","Disable a globally installed plugin (removes it from all roles).",hr,async e=>{try{return gt(e.pluginId),s({success:!0,pluginId:e.pluginId})}catch(t){return s({error:`Failed to disable plugin: ${t}`})}}),p("install_plugin_for_user","Install a plugin globally for the current user (user-scope).",br,async e=>{try{return Te(e.pluginId,"user"),s({success:!0,pluginId:e.pluginId,scope:"user"})}catch(t){return s({error:`Failed to install plugin: ${t}`})}}),p("uninstall_plugin_for_user","Uninstall a globally installed plugin from the current user.",yr,async e=>{try{return Se(e.pluginId,"user"),s({success:!0,pluginId:e.pluginId})}catch(t){return s({error:`Failed to uninstall plugin: ${t}`})}}),p("browse_marketplace","Browse all available plugins from configured marketplaces (shows installed and available).",wr,async()=>{try{let e=pt(),t=Z();return s({available:e,installed:t})}catch(e){return s({error:`Failed to browse marketplace: ${e}`})}}),p("list_marketplace_sources","List configured plugin marketplace sources.",vr,async()=>{let e=Oe();return s({sources:e})}),p("get_plugin_detail","Get detailed manifest for an installed plugin (skills, agents, MCP servers, hooks).",Ir,async e=>{let t=$e(e.pluginId);if(!t)return s({error:`Plugin not found: ${e.pluginId}`});let r=Ue(t.installPath);return s({id:t.id,name:t.name,version:t.version,scope:t.scope,projectPath:t.projectPath,enabled:t.enabled,manifest:r})}),p("scan_directory","Scan a directory for .claude/settings.json and return its plugin/MCP configuration.",Tr,async e=>{let{getRole:t}=await import("./roles-3AEHVOEW.js");if(!t(e.roleId))return s({error:`Role not found: ${e.roleId}`});try{let n=je(e.path);return s({roleId:e.roleId,path:e.path,config:n})}catch(n){return s({error:`Failed to scan directory: ${n}`})}}),p("cancel_task","Cancel a running or pending task by setting its status to 'cancelled'. Emits a task_status_change event.",Sr,async e=>{let t=y(e.taskId);if(!t)return s({error:`Task not found: ${e.taskId}`});let r=t.status;O(e.taskId,{status:"cancelled"});let{serverBus:n}=await import("./server-bus-GEGVMSCA.js");return n.emit({type:"task_status_change",taskId:e.taskId,oldStatus:r,newStatus:"cancelled"}),s({success:!0,taskId:e.taskId,status:"cancelled"})}),p("view_task_logs","Retrieve step-by-step execution logs for a task.",kr,async e=>{let t=z(e.taskId,e.limit??20);return s({taskId:e.taskId,count:t.length,logs:t})}),p("delete_role","Delete a role by ID. This removes the role and its workspace.",Rr,async e=>v(e.roleId)?(Ce(e.roleId),s({success:!0,roleId:e.roleId})):s({error:`Role not found: ${e.roleId}`})),p("view_config","Get the current runtime configuration (mutable fields and restart-required fields).",_r,async()=>{let{MUTABLE_PATHS:e,RESTART_REQUIRED_PATHS:t}=await import("./runtime-VDBZZ4KG.js"),r=T(),n={};try{let d=T().server?.port??7100,u=await fetch(`http://127.0.0.1:${d}/config`);u.ok&&(n=await u.json())}catch{}let a=[...e,...t],i=[...t],l={};for(let d of a){let u=d.split("."),c=r;for(let m of u)if(c&&typeof c=="object")c=c[m];else{c=void 0;break}l[d]={value:c,mutable:!t.includes(d)}}return s({config:l,mutable:[...e],restartRequired:[...t]})}),p("update_config","Update mutable runtime configuration fields. Returns partial-success: some fields may update while others return errors.",Mr,async e=>{let{isRestartRequiredPath:t}=await import("./runtime-VDBZZ4KG.js"),{setConfigValue:r}=await import("./config-CBNOT66B.js"),n=Re(e.updates,r);if(e.updates["logging.level"]&&_e(e.updates["logging.level"]),n.updated.length>0){let{serverBus:a}=await import("./server-bus-GEGVMSCA.js");a.emit({type:"config_changed",changes:n.updated.map(i=>({path:i,value:e.updates[i]}))})}return s(n)}),p("list_memories","List memories stored under a specific role.",xr,async e=>{let t=Ge(e.roleId,e.limit??20);return s({roleId:e.roleId,count:t.length,memories:t})}),p("update_template","Update a task template's fields (name, prompt, cron, enabled, etc.).",Cr,async e=>{let t=j(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});let r={};if(e.name!==void 0&&(r.name=e.name),e.enabled!==void 0&&(r.enabled=e.enabled),e.prompt!==void 0){let n=t.steps?.length?[...t.steps]:[];n.length===0?n.push({id:I(),prompt:e.prompt}):n[0]={...n[0],prompt:e.prompt},r.steps=n}return(e.triggerCron!==void 0||e.triggerEvent!==void 0)&&(r.trigger={type:e.triggerEvent?"event":"cron",cron:e.triggerCron,event:e.triggerEvent}),e.roleId!==void 0&&(r.rolePreference=e.roleId),Ve(e.templateId,r),s({success:!0,templateId:e.templateId,updated:Object.keys(r)})}),p("delete_template","Delete a task template by ID.",Pr,async e=>j(e.templateId)?(qe(e.templateId),s({success:!0,templateId:e.templateId})):s({error:`Template not found: ${e.templateId}`})),p("run_template","Trigger a template immediately (runs the webhook endpoint for its name).",Lr,async e=>{let t=j(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});try{let r=T().server?.port??7100,n=await fetch(`http://127.0.0.1:${r}/webhooks/${t.name}`,{method:"POST"}),a=await n.json();return n.ok?s({success:!0,templateId:e.templateId,templateName:t.name,response:a}):s({error:`Webhook failed: ${a.code??n.status} \u2014 ${a.message??""}`})}catch(r){return s({error:`Failed to trigger template: ${r}`})}}),p("list_delivery_rules","List delivery rules, optionally filtered by enabled status.",Er,async e=>{let t=ve(e.enabled);return s({count:t.length,rules:t})}),p("create_delivery_rule","Create a new delivery rule for event-driven result routing.",Dr,async e=>{let t=I(),r={id:t,eventType:e.eventType,matchCriteria:e.matchCriteria??{},target:{type:"channel",channelId:e.channelId},formatTemplate:e.format,maxPerMinute:10,skipOriginChannel:!1,enabled:e.enabled??!0,createdAt:Date.now()};return Ye(r),s({success:!0,ruleId:t,rule:r})}),p("delete_delivery_rule","Delete a delivery rule by ID.",Ar,async e=>ve().find(n=>n.id===e.ruleId)?(ze(e.ruleId),s({success:!0,ruleId:e.ruleId})):s({error:`Delivery rule not found: ${e.ruleId}`})),p("list_strategies","List Thompson Sampling strategy populations for a role, or all strategies if roleId omitted.",Nr,async e=>{let t;if(e.roleId)t=ot(e.roleId);else{let{getDb:r}=await import("./db-XQUI4IBL.js");t=r().prepare("SELECT * FROM strategies ORDER BY created_at").all().map(a=>({id:a.id,roleId:a.role_id,name:a.name,taskType:a.task_type,createdAt:a.created_at,updatedAt:a.updated_at??void 0,promptTemplate:a.prompt_template??"",alpha:a.alpha,beta:a.beta,totalTrials:a.trials,avgReward:a.total_reward&&a.trials>0?a.total_reward/a.trials:void 0,enabled:a.enabled===1}))}return s({roleId:e.roleId??null,count:t.length,strategies:t})}),p("authorize_task_operation","Authorize a pending privilege escalation for a task. The paused operation will proceed.",{taskId:o.string(),operationId:o.string().optional().describe("ID of the specific operation. If omitted, authorizes the most recent pending operation."),scope:o.enum(["once","permanent"]).default("once").describe("'once' = this operation only. 'permanent' = auto-authorize matching patterns in the future.")},async e=>{let t=ge(e.taskId),r=e.operationId?t.find(a=>a.id===e.operationId):t.find(a=>a.status==="pending");return r?(new J().resolvePlanApproval(r.id,"allow",e.scope),s({success:!0,operationId:r.id,decision:"allow",scope:e.scope})):s({error:"No pending operation found for this task"})}),p("deny_task_operation","Deny a pending privilege escalation for a task. The paused operation will be rejected.",{taskId:o.string(),operationId:o.string().optional(),reason:o.string().optional().describe("Reason for denial, provided to the executor as feedback.")},async e=>{let t=ge(e.taskId),r=e.operationId?t.find(a=>a.id===e.operationId):t.find(a=>a.status==="pending");return r?(new J().resolvePlanApproval(r.id,"deny","once",e.reason),s({success:!0,operationId:r.id,decision:"deny"})):s({error:"No pending operation found for this task"})})];function fo(){return yt.map(e=>e.name).sort().join(",")}function ho(){return Gt({name:"adam-tools",version:"1.0.0",tools:yt})}export{J as a,Br as b,qr as c,Ze as d,hn as e,ot as f,k as g,pt as h,Te as i,Se as j,mt as k,gt as l,Ln as m,fo as n,ho as o};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{f as s,j as w}from"./chunk-
|
|
1
|
+
import{f as s,j as w}from"./chunk-24GTCFEV.js";import{j as i,k as f,n as g,q as y}from"./chunk-J3NIPZ73.js";import{c as p,h}from"./chunk-INNDBLZE.js";y();w();h();import{v4 as c}from"uuid";var t=p("store"),a="role-chat-manager",l=[{name:"Engineer",cagPrompt:`Role: General-purpose software engineer.
|
|
2
2
|
Capabilities: Read, write, and edit code; run shell commands; search codebases.
|
|
3
3
|
Approach: Analyze requirements \u2192 implement \u2192 test \u2192 verify. Write tests for new code. Follow existing code patterns.
|
|
4
4
|
Best for: Feature implementation, bug fixes, refactoring, build/deploy scripts.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as s,d as o}from"./chunk-
|
|
1
|
+
import{b as s,d as o}from"./chunk-4VHBKJD5.js";o();function i(e){return{id:e.id,ruleId:e.rule_id??void 0,taskId:e.task_id??void 0,status:e.status,target:JSON.parse(e.target),content:e.content,attempts:e.attempts,error:e.error??void 0,createdAt:e.created_at,deliveredAt:e.delivered_at??void 0,expiresAt:e.expires_at,source:e.source,messageType:e.message_type??void 0}}var u=1440*60*1e3;function p(e){s().prepare(`
|
|
2
2
|
INSERT INTO delivery_log (id, rule_id, task_id, status, target, content,
|
|
3
3
|
attempts, error, created_at, delivered_at, expires_at, source, message_type)
|
|
4
4
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var f=["defaults.model","defaults.effort","defaults.maxTurns","defaults.maxBudgetUsd","defaults.timeout","logging.level","roles.evolution.triggerEvery","roles.evolution.reflectionThreshold","chat.sessionTimeoutMinutes","chat.maxSessionTurns","chat.autoTitle","chat.archiveExtractMemory","server.timezone","anthropic.apiKey","anthropic.baseUrl","anthropic.model","anthropic.defaultOpusModel","anthropic.defaultSonnetModel","anthropic.defaultHaikuModel","anthropic.smallFastModel","defaults.approvalTimeout","defaults.deniedReadPaths","defaults.approvalRequired","watchdog.rules.artifactCleanup.enabled","watchdog.rules.artifactCleanup.ttlDays","watchdog.rules.artifactCleanup.orphanGcMinAgeHours"],g=["server.port","server.host","server.apiKey"],p={"anthropic.apiKey":"ANTHROPIC_API_KEY","anthropic.baseUrl":"ANTHROPIC_BASE_URL","anthropic.model":"ANTHROPIC_MODEL","anthropic.defaultOpusModel":"ANTHROPIC_DEFAULT_OPUS_MODEL","anthropic.defaultSonnetModel":"ANTHROPIC_DEFAULT_SONNET_MODEL","anthropic.defaultHaikuModel":"ANTHROPIC_DEFAULT_HAIKU_MODEL","anthropic.smallFastModel":"ANTHROPIC_SMALL_FAST_MODEL"},a=null;function T(e){a=JSON.parse(JSON.stringify(e))}function i(){if(!a)throw new Error("Runtime config not initialized. Call initRuntimeConfig first.");return a}function _(e){let r=i(),o=e();for(let[t,n]of Object.entries(o))d(r,t,n)}function R(){let e=i(),r={};for(let[o,t]of Object.entries(p)){let n=h(e,o);n&&typeof n=="string"&&n.length>0?r[t]=n:process.env[t]&&(r[t]=process.env[t])}return r}function c(e){let r={};for(let[o,t]of Object.entries(e))o.startsWith("ANTHROPIC_")||(r[o]=t);return r}var l=/key|token|secret|password|credential/i;function k(e){let r={};for(let[o,t]of Object.entries(e))r[o]=l.test(o)&&t.length>4?t.slice(0,4)+"****":l.test(o)&&t.length>0?"****":t;return r}function O(e){let o=i().defaults?.env??{};return{...process.env,...o,...R(),...c(e?.roleEnvVars??{}),...c(e?.taskEnv??{}),DISABLE_TELEMETRY:"1",DISABLE_ERROR_REPORTING:"1",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1",DISABLE_AUTOUPDATER:"1"}}function C(e,r){let o=i(),t=[],n=[];for(let[s,u]of Object.entries(e)){if(!E(s)){v(s)?n.push(`"${s}" requires restart. Cannot modify at runtime.`):n.push(`"${s}" is not a recognized config path.`);continue}d(o,s,u)&&(t.push(s),r?.(s,u))}return{success:n.length===0,updated:t,errors:n}}function d(e,r,o){let t=r.split("."),n=e;for(let s=0;s<t.length-1;s++)if(n&&typeof n=="object")n=n[t[s]];else return!1;return n&&typeof n=="object"?(n[t[t.length-1]]=o,!0):!1}function h(e,r){let o=r.split("."),t=e;for(let n of o)if(t&&typeof t=="object")t=t[n];else return;return t}function E(e){return f.includes(e)}function v(e){return g.includes(e)}export{f as a,g as b,T as c,i as d,_ as e,R as f,c as g,k as h,O as i,C as j,h as k,E as l,v as m};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as i,d as u}from"./chunk-
|
|
1
|
+
import{b as i,d as u}from"./chunk-4VHBKJD5.js";u();function c(t){return{id:t.id,status:t.status,source:{type:t.source_type,channelId:t.source_channel_id??void 0,chatId:t.source_chat_id??void 0},title:t.title??void 0,createdAt:t.created_at,lastActiveAt:t.last_active_at,archivedAt:t.archived_at??void 0,messageCount:t.message_count}}function d(t){i().prepare(`
|
|
2
2
|
INSERT INTO chat_sessions (id, status, source_type, source_channel_id, source_chat_id,
|
|
3
3
|
title, created_at, last_active_at, archived_at, message_count)
|
|
4
4
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import{e as Q,j as Ae}from"./chunk-24GTCFEV.js";import{a as re}from"./chunk-NZEDILAK.js";import{a as Z}from"./chunk-2CMR5AG7.js";import{a as ee,b as $,c as te,j as ne}from"./chunk-7BSWC62F.js";import{c as X,d as Y,g as L,h as z}from"./chunk-J3NIPZ73.js";import{b as T,d as _e}from"./chunk-4VHBKJD5.js";import{c as V,h as Re}from"./chunk-INNDBLZE.js";import{c as xe,e as ke}from"./chunk-FCV2DPZQ.js";var Oe={};ke(Oe,{getGlobalEnabledState:()=>J,getInstalledPlugin:()=>De,getPluginManifest:()=>F,listInstalledPlugins:()=>B,listMarketplaceSources:()=>Ie,resolvePluginPaths:()=>K,scanDirectoryConfig:()=>U});import{existsSync as b,readFileSync as x,readdirSync as oe}from"fs";import{join as m}from"path";import se from"os";function S(t){try{if(!b(t))return null;let e=x(t,"utf-8");return JSON.parse(e)}catch{return null}}function J(){return S(Me())?.enabledPlugins??{}}function F(t){let e=t;function r(n,o){let s={};try{if(!b(n))return s;let a=x(n,"utf-8").replace(/^```yaml\r?\n/,"").replace(/^```\r?\n/,"");for(let f of o){let l=new RegExp(`^${f}:\\s*(.+)$`,"m"),d=a.match(l);d&&(s[f]=d[1].trim())}}catch{}return s}try{let n={name:"",skills:[],agents:[],mcpServers:[],hooks:[],lspServers:[]},o=m(e,".claude-plugin","plugin.json");if(b(o))try{let l=JSON.parse(x(o,"utf-8"));n.name=l.name??"",n.version=l.version,n.description=l.description,Array.isArray(l.lspServers)&&(n.lspServers=l.lspServers),Array.isArray(l.mcpServers)&&(n.mcpServers=l.mcpServers),Array.isArray(l.hooks)&&(n.hooks=l.hooks)}catch{}let s=m(e,"skills");if(b(s)){let l=oe(s,{withFileTypes:!0});for(let d of l){if(!d.isDirectory()&&!d.isSymbolicLink())continue;let p=m(s,d.name,"SKILL.md"),c=r(p,["name","description"]);c.name&&n.skills.push({name:c.name,description:c.description??""})}}let i=m(e,"agents");if(b(i)){let l=oe(i,{withFileTypes:!0});for(let d of l){if(!d.isFile()||!d.name.endsWith(".md"))continue;let p=r(m(i,d.name),["name","description"]);p.name&&n.agents.push({name:p.name,description:p.description??""})}}let a=m(e,".mcp.json");if(b(a))try{let l=JSON.parse(x(a,"utf-8"));l.mcpServers&&typeof l.mcpServers=="object"&&(n.mcpServers=Object.keys(l.mcpServers))}catch{}let f=m(e,"hooks","hooks.json");if(b(f))try{let l=JSON.parse(x(f,"utf-8"));Array.isArray(l)&&(n.hooks=l.map(d=>typeof d=="object"&&d!==null&&"event"in d?String(d.event):String(d)))}catch{}return n}catch{return null}}function B(t){let e=S(N());if(!e?.plugins)return[];let r=J(),n=[];for(let[o,s]of Object.entries(e.plugins))if(!(!Array.isArray(s)||s.length===0))for(let i of s){let a=i.scope??"user";t?.scope&&a!==t.scope||t?.projectPath&&i.projectPath!==t.projectPath||n.push({id:o,name:o.split("@")[0],version:i.version??"",scope:a,projectPath:i.projectPath,installPath:i.installPath??m(k(),o),enabled:r[o]??i.enabled??!0,installedAt:i.installedAt??"",lastUpdated:i.lastUpdated??""})}return n}function De(t){let e=S(N());if(!e?.plugins?.[t])return null;let r=e.plugins[t];if(!Array.isArray(r)||r.length===0)return null;let n=r[0],o=J();return{id:t,name:t.split("@")[0],version:n.version??"",scope:n.scope??"user",projectPath:n.projectPath,installPath:n.installPath??m(k(),t),enabled:o[t]??n.enabled??!0,installedAt:n.installedAt??"",lastUpdated:n.lastUpdated??""}}function K(t){let e=S(N()),r=new Map;for(let n of t){let o=e?.plugins?.[n];Array.isArray(o)&&o.length>0&&r.set(n,o[0].installPath??m(k(),n))}return r}function Ie(){return S(Ee())?.marketplaces??[]}function U(t){let e=m(t,".claude","settings.json"),r=S(e);return{enabledPlugins:r?.enabledPlugins??{},mcpServers:r?.mcpServers??{},allowedTools:r?.allowedTools??[],disallowedTools:r?.disallowedTools??[]}}var k,N,Ee,Me,ie=xe(()=>{"use strict";k=()=>m(se.homedir(),".claude","plugins"),N=()=>m(k(),"installed_plugins.json"),Ee=()=>m(k(),"known_marketplaces.json"),Me=()=>m(se.homedir(),".claude","settings.json")});import{tool as P}from"@anthropic-ai/claude-agent-sdk";import{z as u}from"zod";import{v4 as je}from"uuid";function y(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}var Ce={query:u.string().describe("Search query for memory retrieval"),roleId:u.string().optional().describe("Role ID to scope search (omit for cross-role)"),topK:u.number().optional().describe("Max results to return (default 5)")},Te={query:u.string().describe("Search query for memory retrieval"),topK:u.number().optional().describe("Max results to return (default 5)")},Le={id:u.string().optional().describe("Memory ID to update. Omit to create new."),roleId:u.string().describe("Role ID to save memory under"),content:u.string().describe("Memory content text"),type:u.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:u.array(u.string()).optional().describe("Keywords for BM25 search"),importance:u.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:u.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},$e={id:u.string().optional().describe("Memory ID to update. Omit to create new."),content:u.string().describe("Memory content text"),type:u.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:u.array(u.string()).optional().describe("Keywords for BM25 search"),importance:u.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:u.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},ae={id:u.string().describe("Memory ID to delete")};async function le(t,e){let r=t??e.roleId,n=e.topK??5,o=await re(r,e.query,{topK:n});return y({results:o.map(s=>({id:s.id,type:s.type,content:s.content,keywords:s.keywords,importance:s.importance,score:s.score}))})}async function ce(t,e){let r=t??e.roleId;if(!r)return y({error:"roleId is required"});let n,o=!0;try{n=await Z(e.content)}catch{o=!1}if(e.id){if(!$(e.id))return y({error:`Memory ${e.id} not found`});let f=te(e.id,{content:e.content,embedding:n,keywords:e.keywords,importance:e.importance,type:e.type});return y({id:e.id,action:"updated",success:f,embeddingUpdated:o})}let s=`mem-${je().slice(0,8)}`,i=Date.now();return ee({id:s,roleId:r,type:e.type??"thought",content:e.content,embedding:n,keywords:e.keywords??[],importance:e.importance??3,sourceType:"manual",createdAt:i,lastAccessed:i,retrievedCount:0,tier:e.tier??"episodic"}),y({id:s,action:"created",success:!0,embeddingUpdated:o})}async function de(t,e){if(t){let r=$(e.id);if(!r)return y({error:`Memory ${e.id} not found`});if(r.roleId!==t)return y({error:`Memory ${e.id} does not belong to this role`})}return ne(e.id),y({id:e.id,deleted:!0})}function bt(t){return t?[P("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",Te,async e=>le(t,e)),P("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",$e,async e=>ce(t,e)),P("delete_memory","Delete a memory by ID.",ae,async e=>de(t,e))]:[P("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",Ce,async e=>le(void 0,e)),P("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",Le,async e=>ce(void 0,e)),P("delete_memory","Delete a memory by ID.",ae,async e=>de(void 0,e))]}ie();Ae();z();var Ne={Read:{category:"File",label:"read"},Write:{category:"File",label:"write"},Edit:{category:"File",label:"edit"},Glob:{category:"Search",label:"find files"},Grep:{category:"Search",label:"search content"},Bash:{category:"Execution",label:"shell commands"},WebSearch:{category:"Web",label:"web search"},WebFetch:{category:"Web",label:"fetch pages"},NotebookEdit:{category:"Execution",label:"Jupyter notebooks"}};function xt(t,e){let r=t.allowedTools??[],n=t.osCapabilities??[];if(r.length===0&&n.length===0&&Object.keys(t.mcpServers??{}).length===0&&(t.additionalDirectories?.length??0)===0&&(!e||e.plugins.length===0))return"No tool permissions";let o=new Map,s=[];for(let p of r){let c=Ne[p];if(c){let g=o.get(c.category)??[];g.push(c.label),o.set(c.category,g)}else s.push(p)}let i=[];for(let[p,c]of o)i.push(`${p} (${c.join(", ")})`);s.length>0&&i.push(s.join(", "));let a=i.join(" \xB7 "),f=p=>{a=a?`${a} \xB7 ${p}`:p},l=Object.keys(t.mcpServers??{});l.length>0&&f(`MCP: ${l.join(", ")}`);let d=t.additionalDirectories??[];if(d.length>0&&f(`Dirs: ${d.map(p=>p.path).join(", ")}`),n.length>0){let p=n.map(c=>{let g=Y(c.id);return c.id==="automation"&&c.targets?.length?`${g.label} (${c.targets.join(", ")})`:g.label});f(`OS: ${p.join(", ")}`)}if(e&&e.plugins.length>0){let p=e.plugins.map(c=>{let g=[];return c.skills.length>0&&g.push(`skills: ${c.skills.map(w=>w.name).join(", ")}`),c.agents.length>0&&g.push(`agents: ${c.agents.map(w=>w.name).join(", ")}`),g.length>0?`${c.name} (${g.join("; ")})`:c.name});f(`Plugins: ${p.join(", ")}`)}return a}function Je(t){let e=[],r=t.additionalDirectories??[];for(let n of r){if(!n.inheritPlugins&&!n.inheritMcp)continue;let o=U(n.path),s=Object.entries(o.enabledPlugins).filter(([,a])=>a).map(([a])=>a),i=K(s);for(let[,a]of i)e.includes(a)||e.push(a)}try{let n=Q(t.name),o=B({scope:"project",projectPath:n});for(let s of o)s.installPath&&!e.includes(s.installPath)&&e.push(s.installPath)}catch{}return e}function kt(t){let e=Je(t),r=[];for(let n of e){let o=F(n);o&&r.push({name:o.name||n.split("/").pop()||"unknown",description:o.description,skills:o.skills,agents:o.agents,mcpServers:o.mcpServers,hooks:o.hooks})}return{plugins:r}}import{accessSync as ue,constants as me}from"fs";import{accessSync as Fe,constants as Be,existsSync as pe,realpathSync as Ke}from"fs";import{join as G}from"path";import{spawn as Ue}from"child_process";import{execFileSync as Ge}from"child_process";var R=null;function _(){if(R)return R;let t=typeof import.meta.dirname=="string"?import.meta.dirname:__dirname??".",e=G(t,"landlock-exec","landlock-exec");if(pe(e))return R=e,e;let r=process.env.PATH?.split(":").find(n=>pe(G(n,"landlock-exec")));return r?(R=G(r,"landlock-exec"),R):e}var A=class{platform="landlock";async isAvailable(){if(process.platform!=="linux")return!1;try{Fe(_(),Be.X_OK)}catch{return!1}try{return Ge(_(),["--check"],{timeout:5e3,stdio:["ignore","pipe","pipe"]}),!0}catch{return!1}}spawn(e){let r=e.command??"node",n=e.args??[],o=[];for(let s of e.visiblePaths??[]){let i=s.mode==="rw"?"--rw":"--ro",a;try{a=Ke(s.path)}catch{a=s.path}o.push(i,a),a!==s.path&&o.push(i,s.path)}return o.push("--",r,...n),Ue(_(),o,{cwd:e.cwd,env:e.env,stdio:"pipe",signal:e.signal})}};function fe(){if(process.platform==="linux")try{return ue(_(),me.X_OK),"landlock"}catch{return"none"}if(process.platform==="darwin")try{return ue("/usr/bin/sandbox-exec",me.X_OK),"sandbox-exec"}catch{return"none"}return"none"}Re();import{spawn as Ye}from"child_process";import{readFileSync as be,writeFileSync as ze,mkdtempSync as Qe,realpathSync as H,rmSync as Ze}from"fs";import{join as h}from"path";import{tmpdir as et}from"os";z();var He=["com.apple.Accessibility","com.apple.CoreGraphics","com.apple.SpeakSelection","com.apple.TimeMachine","com.apple.assistant","com.apple.assistant.backedup","com.apple.assistant.support"],We=["com.apple.coreservices.appleevents"];function qe(t){if(!X.test(t))throw new Error(`Invalid bundle id for SBPL appleevent destination: ${t}`)}function ge(t,e){return L(t)?.find(r=>r.id===e)}function Ve(t){if(!t)return"";let e=["","; ===== Role OS capability: Automation =====","(allow lsopen)","(allow mach-lookup",...We.map(n=>` (global-name "${n}")`),")"],r=t.targets??[];for(let n of r)qe(n),e.push(`(allow appleevent-send (appleevent-destination "${n}"))`);return e.join(`
|
|
2
|
+
`)}function Xe(t){return t?["","; ===== Role OS capability: Accessibility =====","(allow signal)","(allow mach-priv-host-port)","(allow mach-task-name)",'(allow mach-lookup (local-name "com.apple.axserver"))',"(allow user-preference-read",...He.map(r=>` (preference-domain "${r}")`),")"].join(`
|
|
3
|
+
`):""}function ye(t){let e=L(t);return e?.length?[Ve(ge(e,"automation")),Xe(ge(e,"accessibility"))].filter(Boolean).join(`
|
|
4
|
+
`):""}var Se=V("sandbox-macos"),he="/usr/bin/sandbox-exec";function tt(){let t=[h(typeof import.meta.dirname=="string"?import.meta.dirname:".","profiles","role-sandbox.sb"),h(typeof import.meta.dirname=="string"?import.meta.dirname:".","..","src","sandbox","profiles","role-sandbox.sb"),h(process.cwd(),"src","sandbox","profiles","role-sandbox.sb")];for(let e of t)try{return be(e,"utf-8"),e}catch{}return t[t.length-1]}var nt=tt();function E(t){if(!t.startsWith("/"))throw new Error(`Sandbox path must be absolute: ${t}`);if(t.includes('"')||t.includes(")")||t.includes("(")||t.includes("$"))throw new Error(`Sandbox path contains invalid characters for SBPL: ${t}`)}function rt(t){let e=[`
|
|
5
|
+
; ===== Per-Role writable paths =====`];for(let r of t){if(r.mode!=="rw")continue;let n;try{n=H(r.path)}catch{n=r.path}E(n),e.push(`(allow file-write* (subpath "${n}"))`),n!==r.path&&(E(r.path),e.push(`(allow file-write* (subpath "${r.path}"))`))}return e.join(`
|
|
6
|
+
`)}function ot(t){if(!t.length)return"";let e=[`
|
|
7
|
+
; ===== Global read blacklist (deniedReadPaths) =====`];for(let r of t){let n;try{n=H(r)}catch{n=r}try{E(n),e.push(`(deny file-read-data (subpath "${n}"))`),e.push(`(deny file-read-metadata (subpath "${n}"))`),n!==r&&(E(r),e.push(`(deny file-read-data (subpath "${r}"))`),e.push(`(deny file-read-metadata (subpath "${r}"))`))}catch(o){Se.warn({path:r,error:o.message},"Skipping deniedReadPath: invalid for SBPL")}}return e.join(`
|
|
8
|
+
`)}var M=class{platform="sandbox-exec";async isAvailable(){try{let{existsSync:e}=await import("fs");return e(he)}catch{return!1}}spawn(e){let{command:r,args:n,cwd:o,env:s,signal:i,visiblePaths:a,deniedReadPaths:f,osCapabilities:l}=e,d=be(nt,"utf-8"),p=rt(a),c=ot(f??[]),g=ye(l),w=d+p+c+g+`
|
|
9
|
+
`,I=H(Qe(h(et(),"adam-sandbox-"))),O=h(I,"role.sb");ze(O,w,"utf-8");let j=I,C=s?.HOME??process.env.HOME??"/tmp",we={...s,TMPDIR:j,CLAUDE_CODE_TMPDIR:j,CLAUDE_CONFIG_DIR:h(C,".claude")};Se.debug({command:r,visiblePaths:a.length,profilePath:O},"Spawning sandboxed process");let q=Ye(he,["-f",O,"-D",`TMPDIR=${j}`,"-D",`CLAUDE_CONFIG=${h(C,".claude")}`,"-D",`HOME_CACHE=${h(C,"Library","Caches")}`,r,...n],{cwd:o,env:we,stdio:"pipe",signal:i});return q.on("exit",()=>{try{Ze(I,{recursive:!0,force:!0})}catch{}}),q}};import{spawn as st}from"child_process";var v=null,Pe=null,D=null;function it(){if(v)return v;let t=Pe??fe();return Pe=t,t==="sandbox-exec"?v=new M:t==="landlock"?v=new A:v=new W(t),v}async function qt(){return D!==null||(D=await it().isAvailable()),D}var W=class{platform;constructor(e){this.platform=e}async isAvailable(){return!1}spawn(e){let r=e.command??"node",n=e.args??[];return st(r,n,{cwd:e.cwd,env:e.env,stdio:"pipe",signal:e.signal})}};_e();function at(t){return{id:t.id,roleId:t.role_id??void 0,taskPattern:t.task_pattern,maxRiskLevel:t.max_risk_level,createdAt:t.created_at,createdByTaskId:t.created_by_task_id??void 0}}var ve={low:1,medium:2,high:3};function Yt(t){T().prepare(`
|
|
10
|
+
INSERT INTO approval_rules (id, role_id, task_pattern, max_risk_level, created_at, created_by_task_id)
|
|
11
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
12
|
+
`).run(t.id,t.roleId??null,t.taskPattern,t.maxRiskLevel,t.createdAt,t.createdByTaskId??null)}function zt(t,e,r){let o=T().prepare("SELECT * FROM approval_rules ORDER BY created_at DESC").all();for(let s of o)if(!(s.role_id&&s.role_id!==t)&&!(ve[r]>ve[s.max_risk_level]))try{if(new RegExp(s.task_pattern,"i").test(e))return at(s)}catch{}}export{Yt as a,zt as b,J as c,F as d,B as e,De as f,Ie as g,U as h,Oe as i,ie as j,bt as k,xt as l,Je as m,kt as n,it as o,qt as p};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as o,d as u}from"./chunk-
|
|
1
|
+
import{b as o,d as u}from"./chunk-4VHBKJD5.js";u();import{v4 as a}from"uuid";function R(t){o().prepare(`
|
|
2
2
|
INSERT INTO evolution_audit (id, timestamp, old_rules, new_rules, diff, trigger_task_id, role_id, source)
|
|
3
3
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
4
4
|
`).run(a(),t.timestamp,t.oldRules,t.newRules,t.diff,t.triggerTaskId??null,t.roleId??null,t.source??"reflection")}function f(t=100,e=0){return o().prepare(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as n,d as o}from"./chunk-
|
|
1
|
+
import{b as n,d as o}from"./chunk-4VHBKJD5.js";o();function a(e){return{id:e.id,sessionId:e.session_id,role:e.role,content:e.content,source:{type:e.source_type},taskId:e.task_id??void 0,channelMessageId:e.channel_message_id??void 0,metadata:e.metadata?JSON.parse(e.metadata):void 0,createdAt:e.created_at}}function c(e){n().prepare(`
|
|
2
2
|
INSERT INTO chat_messages (id, session_id, role, content, source_type, task_id,
|
|
3
3
|
channel_message_id, metadata, created_at)
|
|
4
4
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import{a as D}from"./chunk-YHVFZB6Q.js";import{a as x,b as y}from"./chunk-XAMLLKKA.js";import{b as _}from"./chunk-CKIVKM5T.js";import{b}from"./chunk-KO5AFX5U.js";import{a as g}from"./chunk-L7JP7DUO.js";import{d as v}from"./chunk-7K4AQBDD.js";import{k as C,q as z}from"./chunk-J3NIPZ73.js";import{b as h,d as $}from"./chunk-4VHBKJD5.js";import{c as E,h as A}from"./chunk-INNDBLZE.js";A();z();$();function M(u){return{id:u.id,templateId:u.template_id,status:u.status,stepStatuses:JSON.parse(u.step_statuses),startedAt:u.started_at,completedAt:u.completed_at??void 0,error:u.error??void 0}}function P(u,e){h().prepare(`
|
|
2
|
+
INSERT INTO workflow_executions (id, template_id, status, step_statuses, started_at)
|
|
3
|
+
VALUES (?, ?, 'running', '{}', ?)
|
|
4
|
+
`).run(u,e,Date.now())}function I(u){let t=h().prepare("SELECT * FROM workflow_executions WHERE id = ?").get(u);return t?M(t):void 0}function R(u,e){let t=h(),s=[],r=[];e.status!==void 0&&(s.push("status = ?"),r.push(e.status)),e.stepStatuses!==void 0&&(s.push("step_statuses = ?"),r.push(JSON.stringify(e.stepStatuses))),e.completedAt!==void 0&&(s.push("completed_at = ?"),r.push(e.completedAt)),e.error!==void 0&&(s.push("error = ?"),r.push(e.error)),s.length!==0&&(r.push(u),t.prepare(`UPDATE workflow_executions SET ${s.join(", ")} WHERE id = ?`).run(...r))}function F(u,e=50,t=0){let s=h(),r="SELECT * FROM workflow_executions",o=[];return u&&(r+=" WHERE template_id = ?",o.push(u)),r+=" ORDER BY started_at DESC LIMIT ? OFFSET ?",o.push(e,t),s.prepare(r).all(...o).map(M)}import{v4 as N}from"uuid";var m=E("scheduler"),O=class{maxRetries;baseDelayMs;constructor(e){this.maxRetries=e?.maxRetries??3,this.baseDelayMs=e?.baseDelayMs??1e3}async execute(e,t){let s=v(),r={timeout:e.config?.timeout??s.timeout,approvalRequired:s.approvalRequired,approvalTimeout:s.approvalTimeout,plugins:e.config?.plugins,mcpServers:e.config?.mcpServers,model:e.config?.model??s.model,maxTurns:e.config?.maxTurns??s.maxTurns,maxBudgetUsd:e.config?.maxBudgetUsd??s.maxBudgetUsd,env:{...s.env,...e.config?.env},claudeCodePath:s.claudeCodePath},o={templateId:e.id,executionId:t,stepResults:new Map,stepStatuses:{},config:r,continueOnError:e.config?.continueOnError??!1,failedStepIds:new Set,rolePreference:e.rolePreference,deliverTo:e.deliverTo,reportTo:e.reportTo};P(t,e.id),D(t),g.emit({type:"workflow_status_change",executionId:t,templateId:e.id,status:"running"});let i=this.groupIntoLayers(e.steps);for(let f of i){if(this.syncExternalState(o)==="cancelled")return this.finalizeCancelledWorkflow(e,o);let k=f.filter(d=>!this.shouldSkip(d,o)),W=f.filter(d=>this.shouldSkip(d,o));for(let d of W){let p={stepId:d.id,taskId:"",status:"skipped",error:"Skipped: dependency failed"};o.stepResults.set(d.id,p),o.stepStatuses[d.id]={taskId:"",status:"skipped",error:"Skipped: dependency failed"},m.info({stepId:d.id,executionId:t},"Step skipped due to failed dependency")}if(k.length===0)continue;let T=await Promise.allSettled(k.map(d=>this.executeStep(d,o)));if(this.syncExternalState(o)==="cancelled")return this.finalizeCancelledWorkflow(e,o);for(let d=0;d<k.length;d++){let p=k[d],c=T[d];if(c.status==="rejected"){m.error({stepId:p.id,error:c.reason},"Workflow step threw");let S={stepId:p.id,taskId:"",status:"failed",error:String(c.reason)};o.stepResults.set(p.id,S),o.failedStepIds.add(p.id),o.stepStatuses[p.id]={taskId:"",status:"failed",error:String(c.reason)}}let w=o.stepResults.get(p.id);if(w?.status==="failed"&&(o.failedStepIds.add(p.id),!o.continueOnError)){if(this.isWorkflowCancelled(o.executionId))return this.finalizeCancelledWorkflow(e,o);let S="failed";return R(t,{status:S,stepStatuses:o.stepStatuses,completedAt:Date.now(),error:w.error}),g.emit({type:"workflow_status_change",executionId:t,templateId:e.id,status:S}),m.warn({stepId:p.id,executionId:t},"Workflow step failed, workflow aborted"),{executionId:t,status:S,stepResults:o.stepResults}}}if(this.isWorkflowCancelled(o.executionId))return this.finalizeCancelledWorkflow(e,o);R(t,{stepStatuses:o.stepStatuses})}if(this.isWorkflowCancelled(o.executionId))return this.finalizeCancelledWorkflow(e,o);let a=o.failedStepIds.size>0,l=[...o.stepResults.values()].some(f=>f.status==="skipped"||f.status==="cancelled"),n=a||l?"partial":"completed";return R(t,{status:n,stepStatuses:o.stepStatuses,completedAt:Date.now()}),g.emit({type:"workflow_status_change",executionId:t,templateId:e.id,status:n}),m.info({executionId:t,status:n,completedSteps:o.stepResults.size,totalSteps:e.steps.length,failedSteps:o.failedStepIds.size},"Workflow completed"),await this.deliverWorkflowResult(o,n),{executionId:t,status:n,stepResults:o.stepResults}}groupIntoLayers(e){let t=new Map(e.map(a=>[a.id,a])),s=new Map,r=new Map;for(let a of e)s.set(a.id,0),r.set(a.id,[]);for(let a of e)if(a.dependsOn)for(let l of a.dependsOn)t.has(l)&&(s.set(a.id,(s.get(a.id)??0)+1),r.get(l)?.push(a.id));let o=[],i=new Set(e.map(a=>a.id));for(;i.size>0;){let a=[];for(let l of i)if((s.get(l)??0)===0){let n=t.get(l);n&&a.push(n)}if(a.length===0){m.warn({remaining:[...i]},"Cycle detected in step dependencies");for(let l of i){let n=t.get(l);n&&o.push([n])}break}o.push(a);for(let l of a){i.delete(l.id);for(let n of r.get(l.id)??[])s.set(n,(s.get(n)??0)-1)}}return o}syncExternalState(e){let t=I(e.executionId);if(t){for(let[s,r]of Object.entries(t.stepStatuses))(r.status==="skipped"||r.status==="failed"||r.status==="cancelled")&&!e.stepResults.has(s)&&!e.failedStepIds.has(s)&&(r.status==="skipped"?e.stepResults.set(s,{stepId:s,taskId:r.taskId,status:"skipped",error:r.error??"Manually skipped via API"}):r.status==="cancelled"?e.stepResults.set(s,{stepId:s,taskId:r.taskId,status:"cancelled",error:r.error??"Cancelled"}):(e.failedStepIds.add(s),e.stepResults.set(s,{stepId:s,taskId:r.taskId,status:"failed",error:r.error})),e.stepStatuses[s]=r,m.info({stepId:s,status:r.status,executionId:e.executionId},"Synced external step status from DB"));return t.status==="cancelled"?"cancelled":void 0}}shouldSkip(e,t){return e.dependsOn?e.dependsOn.some(s=>t.failedStepIds.has(s)?!0:t.stepResults.get(s)?.status==="skipped"):!1}async executeStep(e,t){let s=this.resolveVariables(e.prompt,t.stepResults),r=e.roleId??t.rolePreference,o=r?C(r):void 0,i={...t.config,...e.config?.timeout!==void 0?{timeout:e.config.timeout}:{},...e.config?.maxTurns!==void 0?{maxTurns:e.config.maxTurns}:{}},a=(i.timeout??600)*1e3,l="",n="failed";for(let p=1;p<=this.maxRetries;p++){let c=N();if(l=c,x({id:c,status:"pending",prompt:s,config:i,createdAt:Date.now(),parentId:t.executionId,templateId:t.templateId,roleId:r,stepId:e.id}),t.stepStatuses[e.id]={taskId:c,status:"running",roleId:r},m.debug({stepId:e.id,taskId:c,roleId:r,attempt:p},"Created workflow step as task"),g.emit({type:"task_created",taskId:c}),n=await this.waitForTaskCompletion(c,a),n==="completed"||n==="cancelled")break;if(p<this.maxRetries){let w=this.baseDelayMs*Math.pow(2,p-1);m.info({stepId:e.id,attempt:p,maxRetries:this.maxRetries,delayMs:w},"Workflow step failed, retrying with new task"),await this.sleep(w)}}let f=y(l),k=I(t.executionId),W=k?.stepStatuses[e.id],T=n==="completed"?"completed":W?.status==="skipped"?"skipped":W?.status==="cancelled"||k?.status==="cancelled"?"cancelled":"failed",d={stepId:e.id,taskId:l,status:T,roleId:r,roleName:o?.name,result:f?.result,error:f?.error};t.stepResults.set(e.id,d),t.stepStatuses[e.id]={taskId:l,status:d.status,roleId:r,result:f?.result,error:f?.error}}async deliverWorkflowResult(e,t){let s=_();if(e.deliverTo&&e.deliverTo.length>0){let r=this.assembleWorkflowSummary(e);for(let o of e.deliverTo)if(o.type==="channel"){let i=b(o.channelId);try{await s.send({taskId:e.executionId,channelId:o.channelId,chatId:o.chatId,platform:i?.platform,content:r,messageType:"deliver"})}catch(a){m.error({executionId:e.executionId,channelId:o.channelId,error:a},"Workflow delivery failed")}}}if(e.reportTo&&e.reportTo.length>0){let r=[...e.stepResults.values()].filter(n=>n.status==="completed").length,o=e.failedStepIds.size,i=[...e.stepResults.values()].filter(n=>n.status==="skipped").length,a=e.stepResults.size,l=`Workflow ${t}: ${r}/${a} steps completed${o>0?`, ${o} failed`:""}${i>0?`, ${i} skipped`:""}`;for(let n of e.reportTo)if(n.type==="channel"){let f=b(n.channelId);try{await s.send({taskId:e.executionId,channelId:n.channelId,chatId:n.chatId,platform:f?.platform,content:l,messageType:"report"})}catch(k){m.error({executionId:e.executionId,channelId:n.channelId,error:k},"Workflow report delivery failed")}}}}assembleWorkflowSummary(e){let t=[];for(let[s,r]of e.stepResults){let o=r.status==="completed"?"OK":r.status==="skipped"?"SKIP":"FAIL",i=r.roleName?` (${r.roleName})`:"",a=r.result??r.error??"No output";t.push(`## [${o}] Step: ${s}${i}
|
|
5
|
+
|
|
6
|
+
${a}`)}return t.join(`
|
|
7
|
+
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
`)}resolveVariables(e,t){return e.replace(/\{\{([^}]+)\.result\}\}/g,(s,r)=>t.get(r)?.result??`[no result from ${r}]`)}waitForTaskCompletion(e,t=6e5){return new Promise(s=>{let r=!1,o=Date.now(),i=()=>{r=!0,g.off("task_status_change",a)},a=n=>{r||n.taskId!==e||(n.newStatus==="completed"?(i(),s("completed")):n.newStatus==="failed"?(i(),s("failed")):n.newStatus==="cancelled"&&(i(),s("cancelled")))};g.on("task_status_change",a);let l=()=>{if(r)return;if(Date.now()-o>t){i(),s("failed");return}let n=y(e);if(!n){i(),s("failed");return}if(n.status==="completed"){i(),s("completed");return}if(n.status==="failed"){i(),s("failed");return}if(n.status==="cancelled"){i(),s("cancelled");return}setTimeout(l,5e3)};setTimeout(l,100)})}sleep(e){return new Promise(t=>setTimeout(t,e))}isWorkflowCancelled(e){return I(e)?.status==="cancelled"}finalizeCancelledWorkflow(e,t){let s=I(t.executionId);return R(t.executionId,{status:"cancelled",stepStatuses:s?.stepStatuses??t.stepStatuses,completedAt:s?.completedAt??Date.now(),error:s?.error}),m.info({executionId:t.executionId,templateId:e.id},"Workflow cancelled"),{executionId:t.executionId,status:"cancelled",stepResults:t.stepResults}}};export{I as a,R as b,F as c,O as d};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{a as p,g as N}from"./chunk-QQWRV23T.js";import{b as o,d as C}from"./chunk-4VHBKJD5.js";import{b as l,h as g}from"./chunk-WBAPIPST.js";import{c,e as A}from"./chunk-FCV2DPZQ.js";import*as h from"os";import*as y from"path";function u(e){return e.startsWith("~/")||e==="~"?y.join(h.homedir(),e.slice(1)):e}var _=c(()=>{"use strict";g()});function R(e){return w.includes(e)}function S(e){return v[e]}function E(){return w.map(e=>v[e])}function V(e,i=e!=="none"){return E().map(s=>T(s,e,i))}function T(e,i,s=i!=="none"){return process.platform==="darwin"?e.status==="runtime-enforced"&&(i!=="sandbox-exec"||!s)?{...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 z(e){if(!e?.length)return;for(let s of e)if(!R(s.id))throw new Error(`Unknown OS capability: ${s.id}`);let i=d(e);if(i?.length){for(let s of i){let t=S(s.id);if(t.status!=="runtime-enforced")throw new Error(`OS capability '${t.label}' is not editable in Role settings`);if(t.supportsTargets){if(!s.targets?.length)throw new Error(`OS capability '${t.label}' requires at least one target bundle id`);for(let n of s.targets)if(!D(n))throw new Error(`Invalid automation target bundle id: ${n}`)}else if(s.targets?.length)throw new Error(`OS capability '${t.label}' does not accept targets`)}return i}}function d(e){if(!e||e.length===0)return;let i=new Set,s=[];for(let t of e){if(!R(t.id))throw new Error(`Unknown OS capability: ${t.id}`);if(i.has(t.id))continue;i.add(t.id);let n=S(t.id),a={id:t.id};n.supportsTargets&&t.targets?.length&&(a.targets=[...new Set(t.targets.map(r=>r.trim()).filter(Boolean))]),s.push(a)}return s.length>0?s.sort((t,n)=>t.id.localeCompare(n.id)):void 0}function D(e){return x.test(e)}var w,v,x,O=c(()=>{"use strict";w=["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"],v={"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."}},x=/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/});var L={};A(L,{createRole:()=>J,deleteRole:()=>U,getRole:()=>P,getRoleByName:()=>I,listRoles:()=>B,updateRole:()=>k,validateAdditionalDirectories:()=>f});import{existsSync as M}from"fs";import{resolve as m}from"path";function f(e,i){for(let s of e){let t=typeof s=="string"?s:s.path;if(!t.startsWith("/")&&!t.startsWith("~/")&&t!=="~")throw new Error(`additionalDirectories must be absolute paths: '${t}' is not absolute`);let n=m(u(t));if(!n.startsWith("/"))throw new Error(`additionalDirectories must be absolute paths: '${t}' is not absolute`);for(let a of l){let r=m(u(a));if(n.startsWith(r))throw new Error(`additionalDirectories cannot include hardcoded denied path: '${t}' matches '${a}'`)}if(i?.length)for(let a of i){let r=m(u(a));if(n.startsWith(r)||r.startsWith(n))throw new Error(`additionalDirectories cannot overlap with deniedReadPaths: '${t}' conflicts with '${a}'`)}if(!M(n))throw new Error(`additionalDirectories path does not exist: '${t}'`)}}function b(e){return{id:e.id,name:e.name,cagPrompt:e.cag_prompt,learnedRules:e.learned_rules?JSON.parse(e.learned_rules):[],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 i=JSON.parse(e.additional_directories);return Array.isArray(i)?i.map(s=>typeof s=="string"?{path:s}:s):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?d(JSON.parse(e.os_capabilities)):void 0}}function J(e){let i=p("defaults.deniedReadPaths")??[...l];e.additionalDirectories&&f(e.additionalDirectories,i),o().prepare(`
|
|
2
|
+
INSERT INTO roles (id, name, cag_prompt, learned_rules, memory_stream_id, status,
|
|
3
|
+
performance_score, preferences, created_at, updated_at,
|
|
4
|
+
allowed_tools, disallowed_tools, evaluation_criteria, execution_mode, model,
|
|
5
|
+
max_budget_usd, approval_required, source, additional_directories, allowed_channels, mcp_servers, inherit_user_settings,
|
|
6
|
+
permission_mode, allowed_bash_patterns, denied_bash_patterns, env_vars, os_capabilities)
|
|
7
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
8
|
+
`).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(d(e.osCapabilities)):null)}function P(e){let s=o().prepare("SELECT * FROM roles WHERE id = ?").get(e);return s?b(s):void 0}function I(e){let s=o().prepare("SELECT * FROM roles WHERE name = ?").get(e);return s?b(s):void 0}function k(e,i){let s=o(),t=[],n=[];if("name"in i&&(t.push("name = ?"),n.push(i.name)),"cagPrompt"in i&&(t.push("cag_prompt = ?"),n.push(i.cagPrompt)),"learnedRules"in i&&(t.push("learned_rules = ?"),n.push(JSON.stringify(i.learnedRules))),"memoryStreamId"in i&&(t.push("memory_stream_id = ?"),n.push(i.memoryStreamId)),"status"in i&&(t.push("status = ?"),n.push(i.status)),"performanceScore"in i&&(t.push("performance_score = ?"),n.push(i.performanceScore??null)),"preferences"in i&&(t.push("preferences = ?"),n.push(i.preferences?JSON.stringify(i.preferences):null)),"updatedAt"in i&&(t.push("updated_at = ?"),n.push(i.updatedAt??null)),"allowedTools"in i&&(t.push("allowed_tools = ?"),n.push(i.allowedTools?JSON.stringify(i.allowedTools):null)),"disallowedTools"in i&&(t.push("disallowed_tools = ?"),n.push(i.disallowedTools?JSON.stringify(i.disallowedTools):null)),"evaluationCriteria"in i&&(t.push("evaluation_criteria = ?"),n.push(i.evaluationCriteria?JSON.stringify(i.evaluationCriteria):null)),"executionMode"in i&&(t.push("execution_mode = ?"),n.push(i.executionMode??null)),"model"in i&&(t.push("model = ?"),n.push(i.model??null)),"maxBudgetUsd"in i&&(t.push("max_budget_usd = ?"),n.push(i.maxBudgetUsd??null)),"approvalRequired"in i&&(t.push("approval_required = ?"),n.push(i.approvalRequired?JSON.stringify(i.approvalRequired):null)),"source"in i&&(t.push("source = ?"),n.push(i.source??null)),"additionalDirectories"in i){let a=p("defaults.deniedReadPaths")??[...l];i.additionalDirectories&&f(i.additionalDirectories,a),t.push("additional_directories = ?"),n.push(i.additionalDirectories?JSON.stringify(i.additionalDirectories):null)}"allowedChannels"in i&&(t.push("allowed_channels = ?"),n.push(i.allowedChannels?JSON.stringify(i.allowedChannels):null)),"mcpServers"in i&&(t.push("mcp_servers = ?"),n.push(i.mcpServers?JSON.stringify(i.mcpServers):null)),"inheritUserSettings"in i&&(t.push("inherit_user_settings = ?"),n.push(i.inheritUserSettings?1:0)),"permissionMode"in i&&(t.push("permission_mode = ?"),n.push(i.permissionMode??null)),"allowedBashPatterns"in i&&(t.push("allowed_bash_patterns = ?"),n.push(i.allowedBashPatterns?JSON.stringify(i.allowedBashPatterns):null)),"deniedBashPatterns"in i&&(t.push("denied_bash_patterns = ?"),n.push(i.deniedBashPatterns?JSON.stringify(i.deniedBashPatterns):null)),"envVars"in i&&(t.push("env_vars = ?"),n.push(i.envVars?JSON.stringify(i.envVars):null)),"osCapabilities"in i&&(t.push("os_capabilities = ?"),n.push(i.osCapabilities?JSON.stringify(d(i.osCapabilities)):null)),t.length!==0&&(n.push(e),s.prepare(`UPDATE roles SET ${t.join(", ")} WHERE id = ?`).run(...n))}function B(e,i,s=0){let t=o(),n="SELECT * FROM roles",a=[];return e&&(n+=" WHERE status = ?",a.push(e)),n+=" ORDER BY COALESCE(updated_at, created_at) DESC",typeof i=="number"&&(n+=" LIMIT ? OFFSET ?",a.push(i,s)),t.prepare(n).all(...a).map(b)}function U(e){o().prepare("DELETE FROM roles WHERE id = ?").run(e)}var F=c(()=>{C();g();_();N();O()});export{u as a,_ as b,x as c,S as d,V as e,z as f,d as g,O as h,f as i,J as j,P as k,I as l,k as m,B as n,U as o,L as p,F as q};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as h,b as u,c,d as m,e as v,f as x}from"./chunk-
|
|
1
|
+
import{a as h,b as u,c,d as m,e as v,f as x}from"./chunk-GYHOPV4Q.js";import{b as S,d as y}from"./chunk-I5IUTZA3.js";import{a as i}from"./chunk-L7JP7DUO.js";import{a as l}from"./chunk-2CMR5AG7.js";import{a as C}from"./chunk-7BSWC62F.js";import{e as p}from"./chunk-7K4AQBDD.js";import{v4 as D}from"uuid";import{v4 as I}from"uuid";function _(e){if(e.length<20)return null;let t=e.trim();return t.length>300?{content:`User request: ${t.slice(0,280)}...`,importance:3,type:"thought"}:{content:`User request: ${t}`,importance:3,type:"thought"}}function b(e){if(e.length<20)return null;let t=e.trim();return t.length>400?{content:`Assistant response: ${t.slice(0,370)}...`,importance:2,type:"event"}:{content:`Assistant response: ${t}`,importance:2,type:"event"}}function N(e){let t=S(e,200,0),s=[];for(let o of t){let r=o.role==="user"?_(o.content):b(o.content);r&&s.push(r)}return{facts:s}}function $(e){let t=e.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(s=>s.length>2);return[...new Set(t)].slice(0,20)}async function A(e,t){let{facts:s}=N(e),o=0;for(let r of s){let f=r.content.slice(0,500),g;try{g=await l(f)}catch{}let M=$(f),T={id:I(),roleId:t,type:r.type,content:f,embedding:g,keywords:M,importance:r.importance,sourceType:"session_archive",createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"episodic"};C(T),o++}return o}var n=new Map,a;function w(e){return`${e.type}:${e.channelId??""}:${e.chatId??""}`}function F(){n.clear();let e=m("active",1e3);for(let t of e)n.set(t.id,t)}function Q(e,t){let s=Date.now(),o={id:D(),status:"active",source:e,createdAt:s,lastActiveAt:s,messageCount:0};return h(o),n.set(o.id,o),i.emit({type:"session_created",session:o}),o}function V(e){for(let s of n.values())if(w(s.source)===w(e))return s;let t=v(e);return t&&n.set(t.id,t),t}function B(e){let t=n.get(e);return t||u(e)}function E(e){let t=Date.now();c(e,{status:"archived",archivedAt:t}),p().archiveExtractMemory&&u(e)&&A(e,"role-chat-manager").catch(()=>{}),n.delete(e),i.emit({type:"session_archived",sessionId:e})}function W(e){c(e,{status:"active",archivedAt:void 0});let t=u(e);return t&&(n.set(t.id,t),i.emit({type:"session_restored",session:t})),t}function X(e){y(e),x(e),n.delete(e),i.emit({type:"session_deleted",sessionId:e})}function Y(e){let t=Date.now();c(e,{lastActiveAt:t});let s=n.get(e);s&&(s.lastActiveAt=t)}function Z(e){let t=B(e);if(t){let s=t.messageCount+1;c(e,{messageCount:s});let o=n.get(e);o&&(o.messageCount=s)}}function ee(e){return m(e)}function P(){let t=p().sessionTimeoutMinutes*60*1e3,s=Date.now();for(let o of n.values())if(s-o.lastActiveAt>t)try{E(o.id)}catch{}}function R(e=6e4){d(),a=setInterval(P,e)}function d(){a&&(clearInterval(a),a=void 0)}function te(){return a}function se(){F(),R()}function oe(){d(),n.clear()}function ne(){d(),n.clear()}export{F as a,Q as b,V as c,B as d,E as e,W as f,X as g,Y as h,Z as i,ee as j,R as k,d as l,te as m,se as n,oe as o,ne as p};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as s,d as i}from"./chunk-
|
|
1
|
+
import{b as s,d as i}from"./chunk-4VHBKJD5.js";i();function l(e){return{id:e.id,name:e.name,platform:e.platform,enabled:e.enabled===1,status:e.status,config:JSON.parse(e.config),linkedRoleId:e.linked_role_id??void 0,allowedChatIds:e.allowed_chat_ids?JSON.parse(e.allowed_chat_ids):void 0,createdAt:e.created_at,updatedAt:e.updated_at??void 0,lastMessageAt:e.last_message_at??void 0,messageCount:e.message_count}}function o(e){s().prepare(`
|
|
2
2
|
INSERT INTO channels (id, name, platform, enabled, status, config, linked_role_id,
|
|
3
3
|
allowed_chat_ids, created_at, updated_at, last_message_at, message_count)
|
|
4
4
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as le,b as x,c as J,d as ge,e as me}from"./chunk-KO5AFX5U.js";import{f as ue}from"./chunk-I5IUTZA3.js";import{c as _,h as M}from"./chunk-INNDBLZE.js";import{z as g}from"zod/v4";import{v4 as Dt}from"uuid";import{randomUUID as be}from"crypto";import Ye from"crypto";var pe="2.1.7",F="bot";function Ze(t){let e=t.split(".").map(r=>parseInt(r,10)),s=e[0]??0,i=e[1]??0,n=e[2]??0;return(s&255)<<16|(i&255)<<8|n&255}var Y=Ze(pe),et=35e3,fe=15e3,tt=1e4;function L(){return{channel_version:pe}}function nt(t){return t.endsWith("/")?t:`${t}/`}function st(){let t=Ye.randomBytes(4).readUInt32BE(0);return Buffer.from(String(t),"utf-8").toString("base64")}function it(t){let e={"Content-Type":"application/json",AuthorizationType:"ilink_bot_token","Content-Length":String(Buffer.byteLength(t.body,"utf-8")),"X-WECHAT-UIN":st(),"iLink-App-Id":F,"iLink-App-ClientVersion":String(Y)};return t.token?.trim()&&(e.Authorization=`Bearer ${t.token.trim()}`),t.routeTag&&(e.SKRouteTag=t.routeTag),e}async function D(t){let e=nt(t.baseUrl),s=new URL(t.endpoint,e),i=it({token:t.token,routeTag:t.routeTag,body:t.body}),n=new AbortController,r=setTimeout(()=>n.abort(),t.timeoutMs);try{let o=await fetch(s.toString(),{method:"POST",headers:i,body:t.body,signal:n.signal});clearTimeout(r);let a=await o.text();if(!o.ok)throw new Error(`${t.label} ${o.status}: ${a}`);return a}catch(o){throw clearTimeout(r),o}}async function he(t){let e=t.timeoutMs??et;try{let s=await D({baseUrl:t.baseUrl,endpoint:"ilink/bot/getupdates",body:JSON.stringify({get_updates_buf:t.get_updates_buf??"",base_info:L()}),token:t.token,routeTag:t.routeTag,timeoutMs:e,label:"getUpdates"});return JSON.parse(s)}catch(s){if(s instanceof Error&&s.name==="AbortError")return{ret:0,msgs:[],get_updates_buf:t.get_updates_buf};throw s}}var rt={[-2]:2,[-3]:3},ot=1e3;async function E(t){let e=(await import("./logger-QCJUU7GV.js")).getLogger("channels"),s=new Map;for(;;){let i=await D({baseUrl:t.baseUrl,endpoint:"ilink/bot/sendmessage",body:JSON.stringify({...t.body,base_info:L()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??fe,label:"sendMessage"});e.info({status:200,responseBody:i.slice(0,300)},"apiFetch sendMessage response");try{let n=JSON.parse(i);if(n.ret&&n.ret!==0){let r=rt[n.ret],o=(s.get(n.ret)??0)+1;if(s.set(n.ret,o),r!==void 0&&o<r){e.warn({ret:n.ret,attempt:o,maxRetries:r},"sendMessage: retriable iLink error, retrying"),await new Promise(a=>setTimeout(a,ot*o));continue}throw e.error({ret:n.ret,errmsg:n.errmsg,attempt:o},"sendMessage: iLink API error, no more retries"),new Error(`sendMessage failed: iLink ret=${n.ret}${n.errmsg?` errmsg=${n.errmsg}`:""}`)}}catch(n){if(n instanceof SyntaxError)e.warn({rawText:i.slice(0,200)},"sendMessage: non-JSON response, treating as success");else throw n}return}}async function ye(t){await D({baseUrl:t.baseUrl,endpoint:"ilink/bot/sendtyping",body:JSON.stringify({...t.body,base_info:L()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??tt,label:"sendTyping"})}async function _e(t){let e=await D({baseUrl:t.baseUrl,endpoint:"ilink/bot/getuploadurl",body:JSON.stringify({filekey:t.filekey,media_type:t.media_type,to_user_id:t.to_user_id,rawsize:t.rawsize,rawfilemd5:t.rawfilemd5,filesize:t.filesize,thumb_rawsize:t.thumb_rawsize,thumb_rawfilemd5:t.thumb_rawfilemd5,thumb_filesize:t.thumb_filesize,no_need_thumb:t.no_need_thumb,aeskey:t.aeskey,base_info:L()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??fe,label:"getUploadUrl"});return JSON.parse(e)}var at=5*6e4,dt=35e3,we="3",w=new Map;function Z(t){return Date.now()-t.startedAt<at}function ct(){for(let[t,e]of w)Z(e)||w.delete(t)}async function xe(t,e,s){let i=t.endsWith("/")?t:`${t}/`,n=new URL(`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(e)}`,i),r={"iLink-App-Id":F};s&&(r.SKRouteTag=s);let o=await fetch(n.toString(),{headers:r});if(!o.ok){let a=await o.text().catch(()=>"(unreadable)");throw new Error(`Failed to fetch QR code: ${o.status} ${o.statusText} body=${a}`)}return await o.json()}async function ut(t,e,s){let i=t.endsWith("/")?t:`${t}/`,n=new URL(`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(e)}`,i),r={"iLink-App-Id":F,"iLink-App-ClientVersion":String(Y)};s&&(r.SKRouteTag=s);let o=new AbortController,a=setTimeout(()=>o.abort(),dt);try{let d=await fetch(n.toString(),{headers:r,signal:o.signal});clearTimeout(a);let c=await d.text();if(!d.ok)throw new Error(`Failed to poll QR status: ${d.status} ${d.statusText}`);return JSON.parse(c)}catch(d){if(clearTimeout(a),d instanceof Error&&d.name==="AbortError")return{status:"wait"};throw d}}async function Ie(t){let e=t.accountId||be();ct();let s=w.get(e);if(!t.force&&s&&Z(s)&&s.qrcodeUrl)return{qrcodeUrl:s.qrcodeUrl,message:"QR code ready. Scan with WeChat.",sessionKey:e};if(!t.apiBaseUrl)return{message:"No baseUrl configured for this WeChat channel.",sessionKey:e};try{let i=t.botType||we,n=await xe(t.apiBaseUrl,i,t.routeTag),r={sessionKey:e,id:be(),qrcode:n.qrcode,qrcodeUrl:n.qrcode_img_content,startedAt:Date.now()};return w.set(e,r),{qrcodeUrl:n.qrcode_img_content,message:"Scan the QR code with WeChat to connect.",sessionKey:e}}catch(i){return{message:`Failed to start login: ${String(i)}`,sessionKey:e}}}var lt=3;async function Te(t){let e=w.get(t.sessionKey);if(!e)return{connected:!1,message:"No active login session. Start QR login first."};if(!Z(e))return w.delete(t.sessionKey),{connected:!1,message:"QR code expired. Please start again."};let s=Math.max(t.timeoutMs??48e4,1e3),i=Date.now()+s,n=1;for(;Date.now()<i;){try{let r=await ut(t.apiBaseUrl,e.qrcode,t.routeTag);switch(e.status=r.status,r.status){case"wait":break;case"scaned":break;case"expired":{if(n++,n>lt)return w.delete(t.sessionKey),{connected:!1,message:"Login timeout: QR expired multiple times."};try{let o=t.botType||we,a=await xe(t.apiBaseUrl,o,t.routeTag);e.qrcode=a.qrcode,e.qrcodeUrl=a.qrcode_img_content,e.startedAt=Date.now()}catch(o){return w.delete(t.sessionKey),{connected:!1,message:`QR refresh failed: ${String(o)}`}}break}case"confirmed":return r.ilink_bot_id?(w.delete(t.sessionKey),{connected:!0,botToken:r.bot_token,accountId:r.ilink_bot_id,baseUrl:r.baseurl,userId:r.ilink_user_id,message:"Connected to WeChat successfully!"}):(w.delete(t.sessionKey),{connected:!1,message:"Login failed: server did not return bot ID."})}}catch(r){return w.delete(t.sessionKey),{connected:!1,message:`Login failed: ${String(r)}`}}await new Promise(r=>setTimeout(r,1e3))}return w.delete(t.sessionKey),{connected:!1,message:"Login timeout. Please try again."}}import T from"fs";import*as R from"fs/promises";import I from"path";import{homedir as H}from"os";var W={IMAGE:1,VIDEO:2,FILE:3,VOICE:4},A={NONE:0,USER:1,BOT:2},y={NONE:0,TEXT:1,IMAGE:2,VOICE:3,FILE:4,VIDEO:5},P={NEW:0,GENERATING:1,FINISH:2},Re={TYPING:1,CANCEL:2};M();var gt=_("channels"),ee=-14,B=3600*1e3,C=new Map;function Me(t){let e=Date.now()+B;C.set(t,e),gt.info({channelId:t},`Session paused until ${new Date(e).toISOString()} (${B/1e3}s)`)}function j(t){let e=C.get(t);return e===void 0?!1:Date.now()>=e?(C.delete(t),!1):!0}function Ue(t){let e=C.get(t);if(e===void 0)return 0;let s=e-Date.now();return s<=0?(C.delete(t),0):s}function ke(t){C.delete(t)}M();import*as z from"fs/promises";import $e from"path";import{homedir as wt}from"os";import{createCipheriv as mt,createDecipheriv as pt}from"crypto";function Se(t,e){let s=mt("aes-128-ecb",e,null);return Buffer.concat([s.update(t),s.final()])}function Ce(t,e){let s=pt("aes-128-ecb",e,null);return Buffer.concat([s.update(t),s.final()])}function Ee(t){return Math.ceil((t+1)/16)*16}function te(t,e){return`${e}/download?encrypted_query_param=${encodeURIComponent(t)}`}function Ae(t){return`${t.cdnBaseUrl}/upload?encrypted_query_param=${encodeURIComponent(t.uploadParam)}&filekey=${encodeURIComponent(t.filekey)}`}M();var sn=_("channels");function ft(t){let e=Buffer.from(t,"base64");if(e.length===16)return e;if(e.length===32&&/^[0-9a-fA-F]{32}$/.test(e.toString("ascii")))return Buffer.from(e.toString("ascii"),"hex");throw new Error(`aes_key must decode to 16 raw bytes or 32-char hex, got ${e.length} bytes`)}async function Pe(t){let e=await fetch(t);if(!e.ok)throw new Error(`CDN download ${e.status} ${e.statusText}`);return Buffer.from(await e.arrayBuffer())}async function v(t){let{encryptQueryParam:e,aesKeyBase64:s,cdnBaseUrl:i,fullUrl:n}=t,r=ft(s),o=n?.trim()||(e?te(e,i):null);if(!o)throw new Error("CDN download: need full_url or encrypt_query_param");let a=await Pe(o);return Ce(a,r)}async function ve(t){let{encryptQueryParam:e,cdnBaseUrl:s,fullUrl:i}=t,n=i?.trim()||(e?te(e,s):null);if(!n)throw new Error("CDN download: need full_url or encrypt_query_param");return Pe(n)}M();var Q=_("channels"),Oe=24e3;function ht(t,e){let s=t.byteLength,i=44+s,n=Buffer.allocUnsafe(i),r=0;return n.write("RIFF",r),r+=4,n.writeUInt32LE(i-8,r),r+=4,n.write("WAVE",r),r+=4,n.write("fmt ",r),r+=4,n.writeUInt32LE(16,r),r+=4,n.writeUInt16LE(1,r),r+=2,n.writeUInt16LE(1,r),r+=2,n.writeUInt32LE(e,r),r+=4,n.writeUInt32LE(e*2,r),r+=4,n.writeUInt16LE(2,r),r+=2,n.writeUInt16LE(16,r),r+=2,n.write("data",r),r+=4,n.writeUInt32LE(s,r),r+=4,Buffer.from(t.buffer,t.byteOffset,t.byteLength).copy(n,r),n}async function qe(t){try{let{decode:e}=await import("silk-wasm");Q.debug(`silkToWav: decoding ${t.length} bytes of SILK`);let s=await e(t,Oe);Q.debug(`silkToWav: decoded duration=${s.duration}ms pcmBytes=${s.data.byteLength}`);let i=ht(s.data,Oe);return Q.debug(`silkToWav: WAV size=${i.length}`),i}catch(e){return Q.warn(`silkToWav: transcode failed, will use raw silk err=${String(e)}`),null}}import yt from"path";var _t={".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".csv":"text/csv",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".mp3":"audio/mpeg",".ogg":"audio/ogg",".wav":"audio/wav",".amr":"audio/amr",".silk":"audio/x-silk",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm",".mkv":"video/x-matroska",".avi":"video/x-msvideo",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp"},bt={"image/jpeg":".jpg","image/jpg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/bmp":".bmp","video/mp4":".mp4","video/quicktime":".mov","video/webm":".webm","video/x-matroska":".mkv","video/x-msvideo":".avi","audio/mpeg":".mp3","audio/ogg":".ogg","audio/wav":".wav","audio/amr":".amr","audio/x-silk":".silk","application/pdf":".pdf","application/zip":".zip","application/x-tar":".tar","application/gzip":".gz","text/plain":".txt","text/csv":".csv"};function V(t){let e=yt.extname(t).toLowerCase();return _t[e]??"application/octet-stream"}function Ne(t){let e=t.split(";")[0].trim().toLowerCase();return bt[e]??".bin"}var S=_("channels"),Fe=100*1024*1024;function xt(t){return Ne(t)??".bin"}async function O(t,e,s,i,n=Fe,r){if(t.length>n)throw new Error(`Media too large: ${t.length} bytes exceeds ${n} bytes`);let o=$e.join(wt(),".adam","wechat","media",i,s);await z.mkdir(o,{recursive:!0});let a;if(r&&/^[a-zA-Z0-9._-]+$/.test(r))a=r;else{let c=e?xt(e):".bin",u=Date.now(),p=Math.random().toString(36).slice(2,7);a=`${u}-${p}${c}`}let d=$e.join(o,a);return await z.writeFile(d,t),S.debug(`saveMedia: saved ${t.length} bytes to ${d}`),d}async function Le(t,e){let{cdnBaseUrl:s,channelId:i}=e;if(t.type===y.IMAGE){let n=t.image_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url)return null;let r=n.aeskey?Buffer.from(n.aeskey,"hex").toString("base64"):n.media?.aes_key;try{let o=r?await v({encryptQueryParam:n.media?.encrypt_query_param,aesKeyBase64:r,cdnBaseUrl:s,fullUrl:n.media?.full_url}):await ve({encryptQueryParam:n.media?.encrypt_query_param,cdnBaseUrl:s,fullUrl:n.media?.full_url});return{path:await O(o,"image/png","inbound",i),mimeType:"image/png",type:"image"}}catch(o){return S.error({channelId:i},`Image download/decrypt failed: ${String(o)}`),null}}if(t.type===y.VOICE){let n=t.voice_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let r=await v({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:s,fullUrl:n.media.full_url}),o=await qe(r);if(o){let a=await O(o,"audio/wav","inbound",i);return S.debug(`Voice: saved WAV to ${a}`),{path:a,mimeType:"audio/wav",type:"audio"}}else{let a=await O(r,"audio/silk","inbound",i);return S.debug(`Voice: silk transcode unavailable, saved raw SILK to ${a}`),{path:a,mimeType:"audio/silk",type:"audio"}}}catch(r){return S.error({channelId:i},`Voice download/transcode failed: ${String(r)}`),null}}if(t.type===y.FILE){let n=t.file_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let r=await v({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:s,fullUrl:n.media.full_url}),o=V(n.file_name??"file.bin");return{path:await O(r,o,"inbound",i,Fe,n.file_name),mimeType:o,type:"file"}}catch(r){return S.error({channelId:i},`File download failed: ${String(r)}`),null}}if(t.type===y.VIDEO){let n=t.video_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let r=await v({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:s,fullUrl:n.media.full_url});return{path:await O(r,"video/mp4","inbound",i),mimeType:"video/mp4",type:"video"}}catch(r){return S.error({channelId:i},`Video download failed: ${String(r)}`),null}}return null}import Be from"path";import ne from"crypto";import It from"fs/promises";M();var U=_("channels"),G=3;async function Tt(t){let{buf:e,uploadFullUrl:s,uploadParam:i,filekey:n,cdnBaseUrl:r,label:o,aeskey:a}=t,d=Se(e,a),c=s?.trim(),u;if(c)u=c;else if(i)u=Ae({cdnBaseUrl:r,uploadParam:i,filekey:n});else throw new Error(`${o}: CDN upload URL missing (need upload_full_url or upload_param)`);U.debug(`${o}: CDN POST url=${u} ciphertextSize=${d.length}`);let p,l;for(let h=1;h<=G;h++)try{let m=await fetch(u,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:new Uint8Array(d)});if(m.status>=400&&m.status<500){let b=m.headers.get("x-error-message")??await m.text();throw U.error(`${o}: CDN client error attempt=${h} status=${m.status} errMsg=${b}`),new Error(`CDN upload client error ${m.status}: ${b}`)}if(m.status!==200){let b=m.headers.get("x-error-message")??`status ${m.status}`;throw U.error(`${o}: CDN server error attempt=${h} status=${m.status} errMsg=${b}`),new Error(`CDN upload server error: ${b}`)}if(p=m.headers.get("x-encrypted-param")??void 0,!p)throw U.error(`${o}: CDN response missing x-encrypted-param header attempt=${h}`),new Error("CDN upload response missing x-encrypted-param header");U.debug(`${o}: CDN upload success attempt=${h}`);break}catch(m){if(l=m,m instanceof Error&&m.message.includes("client error"))throw m;h<G?U.warn(`${o}: attempt ${h} failed, retrying... err=${String(m)}`):U.error(`${o}: all ${G} attempts failed err=${String(m)}`)}if(!p)throw l instanceof Error?l:new Error(`CDN upload failed after ${G} attempts`);return{downloadParam:p}}async function se(t){let{filePath:e,toUserId:s,opts:i,cdnBaseUrl:n,mediaType:r,label:o}=t,a=await It.readFile(e),d=a.length,c=ne.createHash("md5").update(a).digest("hex"),u=Ee(d),p=ne.randomBytes(16).toString("hex"),l=ne.randomBytes(16);U.debug(`${o}: file=${e} rawsize=${d} filesize=${u} md5=${c} filekey=${p}`);let h=await _e({...i,filekey:p,media_type:r,to_user_id:s,rawsize:d,rawfilemd5:c,filesize:u,no_need_thumb:!0,aeskey:l.toString("hex")}),m=h.upload_full_url?.trim(),b=h.upload_param;if(!m&&!b)throw new Error(`${o}: getUploadUrl returned no upload URL (need upload_full_url or upload_param)`);let{downloadParam:Je}=await Tt({buf:a,uploadFullUrl:m||void 0,uploadParam:b??void 0,filekey:p,cdnBaseUrl:n,aeskey:l,label:`${o}[orig filekey=${p}]`});return{filekey:p,downloadEncryptedQueryParam:Je,aeskey:l.toString("hex"),fileSize:d,fileSizeCiphertext:u}}async function De(t){return se({...t,mediaType:W.IMAGE,label:"uploadImageToWeixin"})}async function We(t){return se({...t,mediaType:W.VIDEO,label:"uploadVideoToWeixin"})}async function ie(t){return se({...t,mediaType:W.FILE,label:"uploadFileAttachmentToWeixin"})}M();var q=_("channels");function Rt(){return`adam-wechat-${Date.now()}-${Math.random().toString(36).slice(2,7)}`}function Mt(t){let e=t;return e=e.replace(/```[^\n]*\n?([\s\S]*?)```/g,(s,i)=>i.trim()),e=e.replace(/!\[[^\]]*\]\([^)]*\)/g,""),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/^\|[\s:|-]+\|$/gm,""),e=e.replace(/^\|(.+)\|$/gm,(s,i)=>i.split("|").map(n=>n.trim()).join(" ")),e}async function re(t){let{to:e,text:s,mediaItem:i,opts:n,label:r}=t,o=[],a=Mt(s);a&&o.push({type:y.TEXT,text_item:{text:a}}),o.push(i);let d="";for(let c of o){d=Rt();let u={msg:{from_user_id:"",to_user_id:e,client_id:d,message_type:A.BOT,message_state:P.FINISH,item_list:[c],context_token:n.contextToken}};await E({baseUrl:n.baseUrl,token:n.token,routeTag:n.routeTag,body:u})}return q.debug(`${r}: sent to=${e} messageId=${d}`),{messageId:d}}async function Ut(t){let{to:e,text:s,uploaded:i,opts:n}=t,r={type:y.IMAGE,image_item:{media:{encrypt_query_param:i.downloadEncryptedQueryParam,aes_key:Buffer.from(i.aeskey).toString("base64"),encrypt_type:1},mid_size:i.fileSizeCiphertext}};return re({to:e,text:s,mediaItem:r,opts:n,label:"sendImageMessage"})}async function kt(t){let{to:e,text:s,uploaded:i,opts:n}=t,r={type:y.VIDEO,video_item:{media:{encrypt_query_param:i.downloadEncryptedQueryParam,aes_key:Buffer.from(i.aeskey).toString("base64"),encrypt_type:1},video_size:i.fileSizeCiphertext}};return re({to:e,text:s,mediaItem:r,opts:n,label:"sendVideoMessage"})}async function je(t){let{to:e,text:s,fileName:i,uploaded:n,opts:r}=t,o={type:y.FILE,file_item:{media:{encrypt_query_param:n.downloadEncryptedQueryParam,aes_key:Buffer.from(n.aeskey).toString("base64"),encrypt_type:1},file_name:i,len:String(n.fileSize)}};return re({to:e,text:s,mediaItem:o,opts:r,label:"sendFileMessage"})}async function Qe(t){let{filePath:e,to:s,text:i,opts:n,cdnBaseUrl:r}=t,o=V(e),a={baseUrl:n.baseUrl,token:n.token,routeTag:n.routeTag};if(o.startsWith("video/")){q.debug(`sendWeixinMediaFile: uploading video filePath=${e} to=${s}`);let u=await We({filePath:e,toUserId:s,opts:a,cdnBaseUrl:r});return kt({to:s,text:i,uploaded:u,opts:n})}if(o.startsWith("image/")){q.debug(`sendWeixinMediaFile: uploading image filePath=${e} to=${s}`);let u=await De({filePath:e,toUserId:s,opts:a,cdnBaseUrl:r});return Ut({to:s,text:i,uploaded:u,opts:n})}if(o.startsWith("audio/")){let u=Be.basename(e);q.debug(`sendWeixinMediaFile: uploading audio as file filePath=${e} name=${u} to=${s}`);let p=await ie({filePath:e,fileName:u,toUserId:s,opts:a,cdnBaseUrl:r});return je({to:s,text:i,fileName:u,uploaded:p,opts:n})}let d=Be.basename(e);q.debug(`sendWeixinMediaFile: uploading file attachment filePath=${e} name=${d} to=${s}`);let c=await ie({filePath:e,fileName:d,toUserId:s,opts:a,cdnBaseUrl:r});return je({to:s,text:i,fileName:d,uploaded:c,opts:n})}M();var f=_("channels"),Ve="https://novac2c.cdn.weixin.qq.com/c2c",de=new Map;function Ke(t){return I.join(H(),".adam","wechat",`${t}.context-tokens.json`)}function St(t){let e=Ke(t);try{let s=T.readFileSync(e,"utf-8"),i=JSON.parse(s);for(let[n,r]of Object.entries(i))typeof r=="string"&&r&&de.set(`${t}:${n}`,r);f.debug({channelId:t,count:Object.keys(i).length},"Restored context tokens from disk")}catch{}}function Ct(t,e,s){let i=Ke(t);try{let n={};try{let o=T.readFileSync(i,"utf-8");n=JSON.parse(o)}catch{}n[e]=s;let r=I.dirname(i);T.mkdirSync(r,{recursive:!0}),T.writeFileSync(i,JSON.stringify(n),"utf-8")}catch(n){f.warn({channelId:t,userId:e},`Failed to persist context token: ${String(n)}`)}}function Et(t,e,s){de.set(`${t}:${e}`,s),Ct(t,e,s)}function oe(t,e){return de.get(`${t}:${e}`)}function He(t){return I.join(H(),".adam","wechat",`${t}.sync`)}function At(t){try{return T.readFileSync(He(t),"utf-8")}catch{return""}}function Pt(t,e){let s=He(t);T.mkdirSync(I.dirname(s),{recursive:!0}),T.writeFileSync(s,e,"utf-8")}var ae=1440*60*1e3,ze=10,vt=20,Ge=1440*60*1e3,Ot=1320*60*1e3,qt=1,Nt=7200*1e3;function Xe(t){return I.join(H(),".adam","wechat",`${t}.session.json`)}function $t(t){let e=new Map,s=Xe(t);try{let i=T.readFileSync(s,"utf-8"),n=JSON.parse(i);for(let[r,o]of Object.entries(n))o&&typeof o.lastUserMessageAt=="number"&&e.set(r,o);f.debug({channelId:t,count:e.size},"Restored sessions from disk")}catch{}return e}function N(t,e){let s=Xe(t);try{let i={};for(let[r,o]of e)i[r]=o;let n=I.dirname(s);T.mkdirSync(n,{recursive:!0}),T.writeFileSync(s,JSON.stringify(i),"utf-8")}catch(i){f.warn({channelId:t},`Failed to persist sessions: ${String(i)}`)}}var Ft=0;function $(){return`adam-wechat-${Date.now()}-${++Ft}`}var K=class{platform="wechat";id;config;status="disconnected";messageHandler=null;pollAbort=null;getUpdatesBuf="";sessions=new Map;pendingQueue=new Map;lastReminderAt=new Map;constructor(e,s){if(this.id=e,!s.baseUrl)throw new Error("WeChat adapter requires baseUrl");this.config=s}async connect(){if(!this.config.botToken)throw new Error("WeChat adapter requires botToken. Complete QR login first.");this.status="connecting",this.getUpdatesBuf=At(this.id),St(this.id),this.sessions=$t(this.id),this.pollAbort=new AbortController,this.status="connected",f.info({channelId:this.id},"WeChat adapter connected, starting long-poll"),this.startLongPoll()}async disconnect(){this.pollAbort&&(this.pollAbort.abort(),this.pollAbort=null),this.status="disconnected",f.info({channelId:this.id},"WeChat adapter disconnected")}getStatus(){if(this.status==="connected"&&j(this.id))return"error";if(this.status==="connected"){for(let[,e]of this.sessions)if(this.isSessionActive(e)&&e.quotaRemaining<=0)return"degraded"}return this.status}async sendMessage(e,s){if(j(this.id)){let c=Math.ceil(Ue(this.id)/6e4);throw new Error(`WeChat session paused, ${c} min remaining. Re-scan QR to reconnect.`)}let i=this.getOrCreateSession(e),r=this.getSessionRemainingMs(i)/36e5;if(!this.isSessionActive(i))return f.warn({channelId:this.id,chatId:e.slice(0,12),lastUserMessageAt:i.lastUserMessageAt,sessionExpired:!0},"iLink session expired (>24h), message queued"),this.enqueueMessage(e,s),`queued-${$()}`;if(i.quotaRemaining<=0)return f.warn({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:0,remainingHours:r.toFixed(1)},"iLink quota exhausted, message queued"),this.enqueueMessage(e,s),`queued-${$()}`;let o=$(),a=oe(this.id,e),d=this.config.cdnBaseUrl??Ve;try{if(s.mediaUrl){let c=!s.mediaUrl.includes("://")||s.mediaUrl.startsWith("file://"),u=I.join(H(),".adam","wechat","media","outbound-tmp");await R.mkdir(u,{recursive:!0});let p=this.getExtensionFromMediaType(s.mediaType),l;if(c){let m=s.mediaUrl.startsWith("file://")?new URL(s.mediaUrl).pathname:I.isAbsolute(s.mediaUrl)?s.mediaUrl:I.resolve(s.mediaUrl),b=await R.readFile(m);l=I.join(u,`${Date.now()}-${Math.random().toString(36).slice(2,7)}${p}`),await R.writeFile(l,b)}else{let m=await fetch(s.mediaUrl);if(!m.ok)throw new Error(`Failed to fetch media: ${m.status}`);let b=Buffer.from(await m.arrayBuffer());l=I.join(u,`${Date.now()}-${Math.random().toString(36).slice(2,7)}${p}`),await R.writeFile(l,b)}let h=await Qe({filePath:l,to:e,text:s.content??"",opts:{baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,contextToken:a},cdnBaseUrl:d});return await R.unlink(l).catch(()=>{}),i.quotaRemaining--,N(this.id,this.sessions),f.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:i.quotaRemaining,sessionRemainingHours:(this.getSessionRemainingMs(i)/36e5).toFixed(1)},"iLink send success: quota decremented"),this.checkAndSendReminder(e,i).catch(m=>{f.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(m)}`)}),h.messageId}return await E({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{msg:{from_user_id:"",to_user_id:e,client_id:o,message_type:A.BOT,message_state:P.FINISH,item_list:s.content?[{type:y.TEXT,text_item:{text:s.content}}]:void 0,context_token:a}}}),i.quotaRemaining--,N(this.id,this.sessions),f.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:i.quotaRemaining,sessionRemainingHours:(this.getSessionRemainingMs(i)/36e5).toFixed(1)},"iLink send success: quota decremented"),this.checkAndSendReminder(e,i).catch(c=>{f.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(c)}`)}),o}catch(c){if(c instanceof Error&&c.message.includes("ret=-2"))return i.quotaRemaining=0,N(this.id,this.sessions),f.warn({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:0},"iLink quota exhausted (ret=-2 confirmed), message queued"),this.enqueueMessage(e,s),`queued-${$()}`;throw c}}onMessage(e){this.messageHandler=e}async sendTypingIndicator(e){if(j(this.id))return;let s=oe(this.id,e);try{await ye({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{ilink_user_id:e,status:Re.TYPING}})}catch{}}updateConfig(e){Object.assign(this.config,e)}getOrCreateSession(e){let s=this.sessions.get(e);return s||(s={lastUserMessageAt:0,quotaRemaining:0},this.sessions.set(e,s)),s}isSessionActive(e){return e.lastUserMessageAt>0&&Date.now()-e.lastUserMessageAt<=ae}getSessionRemainingMs(e){return e.lastUserMessageAt===0?0:Math.max(0,ae-(Date.now()-e.lastUserMessageAt))}enqueueMessage(e,s){let i=this.pendingQueue.get(e);i||(i=[],this.pendingQueue.set(e,i));let n=Date.now();i=i.filter(r=>n-r.queuedAt<Ge),i.length>=vt&&(i.shift(),f.warn({channelId:this.id,chatId:e.slice(0,12)},"Queue full, dropping oldest message")),i.push({message:s,queuedAt:n}),this.pendingQueue.set(e,i),f.info({channelId:this.id,chatId:e.slice(0,12),queueDepth:i.length},"Message enqueued")}async flushQueue(e){let s=this.pendingQueue.get(e);if(!s||s.length===0)return;let i=this.getOrCreateSession(e),n=Math.min(s.length,Math.max(0,i.quotaRemaining-2));if(n<=0){f.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:i.quotaRemaining},"Queue flush skipped: insufficient quota (reserving 2 for conversation)");return}f.info({channelId:this.id,chatId:e.slice(0,12),queueDepth:s.length,sending:n,quotaRemaining:i.quotaRemaining},"Flushing queued messages");let r=0;for(;r<n&&s.length>0;){let o=s[0];if(Date.now()-o.queuedAt>Ge){s.shift();continue}try{if(await this.sendMessage(e,o.message),s.shift(),r++,i.quotaRemaining<=0)break}catch{f.warn({channelId:this.id,chatId:e.slice(0,12)},"Queue flush: send failed, stopping");break}}s.length===0&&this.pendingQueue.delete(e),f.info({channelId:this.id,chatId:e.slice(0,12),sent:r,remaining:s.length},"Queue flush complete")}async checkAndSendReminder(e,s){let i=Date.now(),n=this.lastReminderAt.get(e)??0;if(i-n<Nt)return;let r=this.getSessionRemainingMs(s),a=i-s.lastUserMessageAt>=Ot,d=s.quotaRemaining<=qt;if(!a&&!d)return;let c=(r/36e5).toFixed(1),u;a&&d?u=`[\u7CFB\u7EDF\u63D0\u9192] \u6D88\u606F\u7A97\u53E3\u5373\u5C06\u5173\u95ED\uFF08\u5269\u4F59${c}\u5C0F\u65F6/${s.quotaRemaining}\u6761\u914D\u989D\uFF09\u3002\u8BF7\u56DE\u590D\u4EFB\u610F\u6D88\u606F\u4EE5\u4FDD\u6301\u8FDE\u63A5\u3002`:a?u=`[\u7CFB\u7EDF\u63D0\u9192] \u6D88\u606F\u7A97\u53E3\u5373\u5C06\u5173\u95ED\uFF08\u5269\u4F59${c}\u5C0F\u65F6\uFF09\u3002\u8BF7\u56DE\u590D\u4EFB\u610F\u6D88\u606F\u4EE5\u4FDD\u6301\u8FDE\u63A5\u3002`:u=`[\u7CFB\u7EDF\u63D0\u9192] \u6D88\u606F\u914D\u989D\u5373\u5C06\u7528\u5B8C\uFF08\u5269\u4F59${s.quotaRemaining}\u6761\uFF09\u3002\u8BF7\u56DE\u590D\u4EFB\u610F\u6D88\u606F\u4EE5\u91CD\u7F6E\u914D\u989D\u3002`;let p=oe(this.id,e);try{await E({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{msg:{from_user_id:"",to_user_id:e,client_id:$(),message_type:A.BOT,message_state:P.FINISH,item_list:[{type:y.TEXT,text_item:{text:u}}],context_token:p}}}),s.quotaRemaining--,this.lastReminderAt.set(e,i),N(this.id,this.sessions),f.info({channelId:this.id,chatId:e.slice(0,12),remainingHours:c,quotaRemaining:s.quotaRemaining,trigger:a?"time":"quota"},"iLink session reminder sent")}catch(l){f.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(l)}`)}}async startLongPoll(){let e=this.pollAbort?.signal,s=0,i=3,n=3e4,r=2e3;for(;!e?.aborted;)try{let o=await he({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,get_updates_buf:this.getUpdatesBuf});if(o.ret===ee||o.errcode===ee){Me(this.id),this.status="error",f.error({channelId:this.id},"Session expired (errcode=-14), pausing for 1 hour"),await this.sleep(B,e),ke(this.id),this.status="connected";continue}if(o.ret!==void 0&&o.ret!==0||o.errcode!==void 0&&o.errcode!==0){s++,f.error({channelId:this.id,ret:o.ret,errcode:o.errcode},"getUpdates API error"),s>=i?(s=0,await this.sleep(n,e)):await this.sleep(r,e);continue}s=0,o.get_updates_buf&&(this.getUpdatesBuf=o.get_updates_buf,Pt(this.id,o.get_updates_buf));for(let d of o.msgs??[])await this.processInbound(d)}catch(o){if(e?.aborted)return;s++,f.error({channelId:this.id,error:o},"getUpdates error"),s>=i?(s=0,await this.sleep(n,e)):await this.sleep(r,e)}}async processInbound(e){if(!this.messageHandler)return;let s=!!e.group_id,i=s?e.group_id:e.from_user_id??"",n=e.from_user_id??"";e.context_token&&i&&Et(this.id,i,e.context_token);let r=this.getOrCreateSession(i),o=r.quotaRemaining;r.lastUserMessageAt=Date.now(),r.quotaRemaining=ze,N(this.id,this.sessions),f.info({channelId:this.id,chatId:i.slice(0,12),quotaReset:!0,prevQuota:o,newQuota:ze,sessionWindowMs:ae},"iLink session reset: user message received, quota restored"),this.flushQueue(i);let a="",d,c=[];for(let l of e.item_list??[])l.type===y.TEXT&&l.text_item?.text&&(a+=l.text_item.text),l.type===y.IMAGE&&(d="image",c.push(l)),l.type===y.VOICE&&(d="audio",c.push(l),l.voice_item?.text&&!a&&(a=l.voice_item.text)),l.type===y.FILE&&(d="file",c.push(l)),l.type===y.VIDEO&&(d="video",c.push(l));if(!a&&!d)return;let u;if(c.length>0){let l=this.config.cdnBaseUrl??Ve;try{let h=await Le(c[0],{cdnBaseUrl:l,channelId:this.id});h&&(u=h.path,d=h.type)}catch(h){f.error({channelId:this.id},`Media download failed: ${String(h)}`)}}let p={channelId:this.id,platform:"wechat",chatId:i,senderId:n,content:a,mediaType:d,mediaPath:u,isGroup:s,timestamp:e.create_time_ms??Date.now(),raw:e};this.messageHandler(p)}getExtensionFromMediaType(e){switch(e){case"image":return".png";case"video":return".mp4";case"audio":return".mp3";default:return".bin"}}sleep(e,s){return new Promise((i,n)=>{let r=setTimeout(i,e);s?.addEventListener("abort",()=>{clearTimeout(r),n(new Error("aborted"))},{once:!0})})}};M();var Lt=_("channels"),X=class{platform="discord";id;config;status="disconnected";messageHandler=null;client=null;constructor(e,s){if(this.id=e,!s.botToken)throw new Error("Discord adapter requires botToken");this.config=s}async connect(){this.status="connecting";try{let{Client:e,GatewayIntentBits:s}=await import("discord.js");this.client=new e({intents:[s.Guilds,s.GuildMessages,s.MessageContent,s.DirectMessages]});let i=this.client;i.on("messageCreate",n=>{if(!this.messageHandler||n.author.bot||this.config.allowedGuildIds?.length&&n.guildId&&!this.config.allowedGuildIds.includes(n.guildId))return;let r={channelId:this.id,platform:"discord",chatId:n.channelId,senderId:n.author.id,senderName:n.author.displayName??n.author.username,content:n.content,isGroup:!!n.guildId,timestamp:n.createdTimestamp,raw:n};this.messageHandler(r)}),await i.login(this.config.botToken),this.status="connected",Lt.info({channelId:this.id},"Discord bot connected")}catch(e){throw this.status="error",e}}async disconnect(){this.client&&await this.client.destroy(),this.client=null,this.status="disconnected"}getStatus(){return this.status}async sendMessage(e,s){if(!this.client)throw new Error("Discord client not connected");let n=await this.client.channels.fetch(e);if(!n||!("send"in n))throw new Error(`Channel ${e} not found or not text channel`);return(await n.send({content:s.content,reply:s.replyToMessageId?{messageReference:s.replyToMessageId}:void 0})).id}onMessage(e){this.messageHandler=e}async sendTypingIndicator(e){if(!this.client)return;let i=await this.client.channels.fetch(e);i&&"sendTyping"in i&&await i.sendTyping()}};var k=g.object({id:g.string().uuid()}),Wt=g.object({name:g.string().min(1,"name is required"),platform:g.string().min(1,"platform is required"),config:g.record(g.string(),g.unknown()),enabled:g.boolean().optional().default(!0),linkedRoleId:g.string().optional(),allowedChatIds:g.array(g.string()).optional()}),Bt=g.object({name:g.string().min(1).optional(),enabled:g.boolean().optional(),config:g.record(g.string(),g.unknown()).optional(),linkedRoleId:g.string().optional(),allowedChatIds:g.array(g.string()).optional()}),ce;function Zn(t){ce=t}function es(){return ce}async function ts(t){let e=ce;t.get("/channels",{schema:{tags:["Channels"],summary:"List channels",querystring:{type:"object",properties:{enabled:{type:"boolean"}}}}},async(s,i)=>({channels:ge(s.query.enabled)})),t.post("/channels",{schema:{tags:["Channels"],summary:"Create a channel",body:{type:"object",required:["name","platform","config"],properties:{name:{type:"string",minLength:1},platform:{type:"string",minLength:1},config:{type:"object"},enabled:{type:"boolean"},linkedRoleId:{type:"string"},allowedChatIds:{type:"array",items:{type:"string"}}}}}},async(s,i)=>{let n=Wt.safeParse(s.body);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let{name:r,platform:o,config:a,enabled:d,linkedRoleId:c,allowedChatIds:u}=n.data,p={id:Dt(),name:r,platform:o,enabled:d,status:"disconnected",config:a,linkedRoleId:c,allowedChatIds:u,createdAt:Date.now(),messageCount:0};return le(p),i.status(201).send({channel:p})}),t.get("/channels/:id",{schema:{tags:["Channels"],summary:"Get channel by ID",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(s,i)=>{let n=k.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);return r?{channel:r}:i.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),t.patch("/channels/:id",{schema:{tags:["Channels"],summary:"Update channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",properties:{name:{type:"string"},enabled:{type:"boolean"},config:{type:"object"},linkedRoleId:{type:"string"},allowedChatIds:{type:"array",items:{type:"string"}}}}}},async(s,i)=>{let n=k.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);if(!r)return i.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let o=Bt.safeParse(s.body);return o.success?(J(r.id,o.data),{channel:x(r.id)}):i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(o.error)})}),t.delete("/channels/:id",{schema:{tags:["Channels"],summary:"Delete channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(s,i)=>{let n=k.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);return r?(me(r.id),i.status(204).send()):i.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),t.post("/channels/:id/connect",{schema:{tags:["Channels"],summary:"Connect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(s,i)=>{let n=k.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});if(!e)return i.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let r=x(n.data.id);if(!r)return i.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(!e.hasAdapter(r.id)&&r.platform==="discord"){let o=r.config;if(!o.botToken)return i.status(400).send({code:"MISSING_CONFIG",message:"Discord channel requires botToken in config"});let a=new X(r.id,{botToken:o.botToken});await e.addChannel(r,a)}if(!e.hasAdapter(r.id))return i.status(400).send({code:"NO_ADAPTER",message:"No adapter registered for this channel. Install the appropriate adapter first."});try{return await e.connectChannel(r.id),{channelId:r.id,status:"connected"}}catch(o){return i.status(500).send({code:"CONNECT_FAILED",message:String(o)})}}),t.post("/channels/:id/disconnect",{schema:{tags:["Channels"],summary:"Disconnect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(s,i)=>{let n=k.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});if(!e)return i.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let r=x(n.data.id);return r?(await e.disconnectChannel(r.id),{channelId:r.id,status:"disconnected"}):i.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),t.get("/channels/:id/messages",{schema:{tags:["Channels"],summary:"Get channel message history",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50},offset:{type:"integer",minimum:0,default:0}}}}},async(s,i)=>{let n=k.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);if(!r)return i.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let{limit:o=50,offset:a=0}=s.query;return{messages:ue(r.id,o,a)}}),t.post("/channels/:id/wechat/qr-start",{schema:{tags:["WeChat"],summary:"Start WeChat QR login",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(s,i)=>{let n=k.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);if(!r)return i.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(r.platform!=="wechat")return i.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=r.config;return await Ie({apiBaseUrl:o.baseUrl,routeTag:o.routeTag})}),t.post("/channels/:id/wechat/qr-wait",{schema:{tags:["WeChat"],summary:"Wait for WeChat QR scan",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",properties:{sessionKey:{type:"string"},timeoutMs:{type:"number"}}}}},async(s,i)=>{let n=k.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);if(!r)return i.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(r.platform!=="wechat")return i.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=r.config,{sessionKey:a,timeoutMs:d}=s.body??{},c=await Te({sessionKey:a??"",apiBaseUrl:o.baseUrl,timeoutMs:d??12e4,routeTag:o.routeTag});if(c.connected&&c.botToken){let u={...o,botToken:c.botToken,accountId:c.accountId,baseUrl:c.baseUrl??o.baseUrl,userId:c.userId};if(J(r.id,{config:u}),e){let p=new K(r.id,u),l=x(r.id);l&&await e.addChannel(l,p)}}return{connected:c.connected,accountId:c.accountId,message:c.message}})}export{K as a,X as b,Zn as c,es as d,ts as e};
|