adam-agent-server 0.3.0 → 0.5.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.
@@ -1 +1 @@
1
- import{x as a,y as b}from"./chunk-BQE7XAMQ.js";import"./chunk-5JLMSNIW.js";import"./chunk-IXF3XBGX.js";import"./chunk-AXMXXUPO.js";import"./chunk-KICPHTI2.js";import"./chunk-FUGJMHY4.js";import"./chunk-5ASEAZCR.js";import"./chunk-742NWPTQ.js";import"./chunk-PQ7KPALO.js";import"./chunk-2GXYBWLS.js";import"./chunk-WZOMGJSY.js";import"./chunk-WXN3PSVX.js";import"./chunk-L7426WNY.js";import"./chunk-L7JP7DUO.js";import"./chunk-HAWA62R2.js";import"./chunk-VF6GJGD6.js";import"./chunk-T25NLVMY.js";import"./chunk-ETQ7KC73.js";import"./chunk-FYDFMYUP.js";import"./chunk-U36NBCR3.js";import"./chunk-XNWZZYAV.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{b as createAdamTools,a as getToolsFingerprint};
1
+ import{x as a,y as b}from"./chunk-D6WM2OQS.js";import"./chunk-5JLMSNIW.js";import"./chunk-IXF3XBGX.js";import"./chunk-AXMXXUPO.js";import"./chunk-KICPHTI2.js";import"./chunk-FUGJMHY4.js";import"./chunk-5ASEAZCR.js";import"./chunk-742NWPTQ.js";import"./chunk-PQ7KPALO.js";import"./chunk-2GXYBWLS.js";import"./chunk-WZOMGJSY.js";import"./chunk-WXN3PSVX.js";import"./chunk-L7426WNY.js";import"./chunk-L7JP7DUO.js";import"./chunk-HAWA62R2.js";import"./chunk-VF6GJGD6.js";import"./chunk-T25NLVMY.js";import"./chunk-ETQ7KC73.js";import"./chunk-FYDFMYUP.js";import"./chunk-U36NBCR3.js";import"./chunk-XNWZZYAV.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{b as createAdamTools,a as getToolsFingerprint};
@@ -1,4 +1,4 @@
1
- import{b as y}from"./chunk-LBLERTM4.js";import{b as m}from"./chunk-PQ7KPALO.js";import"./chunk-FDWW245P.js";import"./chunk-L7JP7DUO.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import{c as f}from"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";var s=f("channels"),c=new Map,h=3e5,v=new Set(["telegram"]);function A(n){let a=n.trim().toLowerCase().match(/^(yes|y|是|允许|no|n|否|拒绝)\s+(\S+)$/);if(!a)return null;let[,p,d]=a,i=["yes","y","\u662F","\u5141\u8BB8"].includes(p);return{requestId:d,decision:i?"allow":"deny"}}function I(n){let r=m(n);return r?v.has(r.platform):!1}async function b(n,r,a,p,d,i=h){let e=a;c.set(e,{planId:a,taskId:p,channelId:n,chatId:r,requestId:e,timestamp:Date.now(),timeoutMs:i});let l=y(),o=I(n);if(o){let t=`\u{1F510} Plan approval requested
1
+ import{b as y}from"./chunk-NXTTKAQX.js";import{b as m}from"./chunk-PQ7KPALO.js";import"./chunk-FDWW245P.js";import"./chunk-L7JP7DUO.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import{c as f}from"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";var s=f("channels"),c=new Map,h=3e5,v=new Set(["telegram"]);function A(n){let a=n.trim().toLowerCase().match(/^(yes|y|是|允许|no|n|否|拒绝)\s+(\S+)$/);if(!a)return null;let[,p,d]=a,i=["yes","y","\u662F","\u5141\u8BB8"].includes(p);return{requestId:d,decision:i?"allow":"deny"}}function I(n){let r=m(n);return r?v.has(r.platform):!1}async function b(n,r,a,p,d,i=h){let e=a;c.set(e,{planId:a,taskId:p,channelId:n,chatId:r,requestId:e,timestamp:Date.now(),timeoutMs:i});let l=y(),o=I(n);if(o){let t=`\u{1F510} Plan approval requested
2
2
 
3
3
  ${d.slice(0,200)}`;await l.send({channelId:n,chatId:r,content:t,messageType:"approval",replyMarkup:{inlineKeyboard:[[{text:"\u2705 Allow",callbackData:`yes ${e}`},{text:"\u274C Deny",callbackData:`no ${e}`}]]}})}else{let t=["\u{1F510} Plan approval requested",d.slice(0,200),"",`Reply 'yes ${e}' or 'no ${e}'`].join(`
4
4
  `);await l.send({channelId:n,chatId:r,content:t,messageType:"approval"})}setTimeout(()=>{let t=c.get(e);if(t&&Date.now()-t.timestamp>=t.timeoutMs){c.delete(e),s.warn({requestId:e,taskId:p},"Approval timed out, auto-denying"),l.send({channelId:t.channelId,chatId:t.chatId,content:`\u23F0 Approval ${e} timed out (5 min). Plan denied.`,messageType:"approval"}).catch(u=>s.error({requestId:e,error:u},"Failed to notify timeout"));let g=process.env.ADAM_PORT??"7100";fetch(`http://localhost:${g}/tasks/${t.taskId}/approve-plan`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planId:t.planId,decision:"deny"})}).catch(u=>s.error({requestId:e,error:u},"Failed to auto-deny"))}},i+1e3),s.info({channelId:n,chatId:r,planId:a,requestId:e,interactive:o},"Interactive approval sent to channel")}async function C(n,r,a,p){let i=A(p??a);if(!i)return!1;let{requestId:e,decision:l}=i,o=c.get(e);if(!o)return!1;if(o.channelId!==n||o.chatId!==r)return s.debug({requestId:e,expectedChannel:o.channelId,gotChannel:n},"Approval reply from different channel"),!1;c.delete(e),s.info({requestId:e,decision:l},"Channel approval reply received");try{let t=process.env.ADAM_PORT??"7100",g=await fetch(`http://localhost:${t}/tasks/${o.taskId}/approve-plan`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planId:o.planId,decision:l}),signal:AbortSignal.timeout(1e4)});g.ok||s.error({requestId:e,status:g.status},"Failed to forward approval to API")}catch(t){s.error({requestId:e,error:t},"Error forwarding approval to API")}return!0}function $(){return[...c.keys()]}export{$ as getPendingApprovalRequestIds,C as handleInboundForApproval,A as parseApprovalReply,b as sendApprovalToChannel};
@@ -1 +1 @@
1
- import{a,b,c}from"./chunk-DT2LX4XI.js";import"./chunk-WXN3PSVX.js";import"./chunk-L7426WNY.js";import"./chunk-L7JP7DUO.js";import"./chunk-HAWA62R2.js";import"./chunk-VF6GJGD6.js";import"./chunk-T25NLVMY.js";import"./chunk-ETQ7KC73.js";import"./chunk-FYDFMYUP.js";import"./chunk-XNWZZYAV.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{a as BreeEngine,b as getBreeEngine,c as setBreeEngine};
1
+ import{a,b,c}from"./chunk-BREBCBG4.js";import"./chunk-WXN3PSVX.js";import"./chunk-L7426WNY.js";import"./chunk-L7JP7DUO.js";import"./chunk-HAWA62R2.js";import"./chunk-VF6GJGD6.js";import"./chunk-T25NLVMY.js";import"./chunk-ETQ7KC73.js";import"./chunk-FYDFMYUP.js";import"./chunk-XNWZZYAV.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{a as BreeEngine,b as getBreeEngine,c as setBreeEngine};
@@ -1 +1 @@
1
- import{b as a,c as b,d as c}from"./chunk-2EP27EGS.js";import"./chunk-742NWPTQ.js";import"./chunk-PQ7KPALO.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{c as channelRoutes,b as getChannelManager,a as setChannelManager};
1
+ import{c as a,d as b,e as c}from"./chunk-URW2DJQF.js";import"./chunk-742NWPTQ.js";import"./chunk-PQ7KPALO.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{c as channelRoutes,b as getChannelManager,a as setChannelManager};
@@ -0,0 +1,49 @@
1
+ import{a as C,b as A}from"./chunk-WXN3PSVX.js";import{a as T,b as p}from"./chunk-L7426WNY.js";import{a as u}from"./chunk-L7JP7DUO.js";import{p as x}from"./chunk-HAWA62R2.js";import{a as I,b as d,d as y,f as P}from"./chunk-VF6GJGD6.js";import{d as h}from"./chunk-T25NLVMY.js";import{i as b,l as J}from"./chunk-XNWZZYAV.js";import{c as k}from"./chunk-3DAK2XWP.js";J();import{v4 as l}from"uuid";import{CronExpressionParser as D}from"cron-parser";import{v4 as M}from"uuid";var m=k("scheduler"),w=class{maxRetries=3;baseDelayMs=1e3;async execute(e,t){let o=h(),r=e.config?.fileAccess,i={timeout:e.config?.timeout??o.timeout,approvalRequired:o.approvalRequired,approvalTimeout:o.approvalTimeout,fileAccess:{allowedPaths:[...o.fileAccess.allowedPaths,...r?.allowedPaths??[]],deniedPaths:[...o.fileAccess.deniedPaths,...r?.deniedPaths??[]]},plugins:e.config?.plugins,mcpServers:e.config?.mcpServers,model:e.config?.model??o.model,maxTurns:e.config?.maxTurns??o.maxTurns,maxBudgetUsd:e.config?.maxBudgetUsd??o.maxBudgetUsd,env:{...o.env,...e.config?.env},claudeCodePath:o.claudeCodePath},s={templateId:e.id,executionId:t,stepResults:new Map,config:i,rolePreference:e.rolePreference,deliverTo:e.deliverTo,reportTo:e.reportTo},a=this.sortSteps(e.steps);for(let c of a){try{await this.executeStep(c,s)}catch(_){m.error({stepId:c.id,error:_},"Workflow step failed");break}if(s.stepResults.get(c.id)?.status==="failed"){m.warn({stepId:c.id},"Workflow step failed, workflow aborted");break}}m.info({executionId:t,completedSteps:s.stepResults.size,totalSteps:a.length},"Workflow completed")}sortSteps(e){let t=new Set,o=[],r=new Map(e.map(s=>[s.id,s])),i=s=>{if(!t.has(s.id)){if(t.add(s.id),s.dependsOn)for(let a of s.dependsOn){let c=r.get(a);c&&i(c)}o.push(s)}};for(let s of e)i(s);return o}async executeStep(e,t){let o=this.resolveVariables(e.prompt,t.stepResults),r=M();T({id:r,status:"pending",prompt:o,config:t.config,createdAt:Date.now(),parentId:t.executionId,templateId:t.templateId,roleId:t.rolePreference,deliverTo:t.deliverTo,reportTo:t.reportTo}),m.debug({stepId:e.id,taskId:r},"Created workflow step as task"),u.emit({type:"task_created",taskId:r});let i=await this.executeWithRetry(r,e.id),s=p(r);t.stepResults.set(e.id,{stepId:e.id,taskId:r,status:i==="completed"?"completed":"failed",result:s?.result,error:s?.error})}resolveVariables(e,t){return e.replace(/\{\{([^}]+)\.result\}\}/g,(o,r)=>t.get(r)?.result??`[no result from ${r}]`)}async executeWithRetry(e,t){let o=0;for(;o<this.maxRetries;){if(o++,await this.waitForTaskCompletion(e)==="completed")return"completed";if(o<this.maxRetries){let i=this.baseDelayMs*Math.pow(2,o-1);m.info({stepId:t,attempt:o,maxRetries:this.maxRetries,delayMs:i},"Workflow step failed, retrying"),await this.sleep(i)}}return"failed"}waitForTaskCompletion(e,t=6e5){return new Promise(o=>{let r=Date.now(),i=()=>{if(Date.now()-r>t){o("failed");return}let s=p(e);if(!s){o("failed");return}if(s.status==="completed"){o("completed");return}if(s.status==="failed"||s.status==="cancelled"){o("failed");return}setTimeout(i,500)};i()})}sleep(e){return new Promise(t=>setTimeout(t,e))}};var n=k("scheduler"),v="ai-hourly-digest";function O(){if(d(v)){n.debug({templateId:v},"Built-in template already exists");return}let e={id:v,name:"AI Hourly Digest",description:"\u6BCF\u5C0F\u65F6\u641C\u7D22 AI \u524D\u6CBF\u6587\u7AE0\uFF0C\u603B\u7ED3\u540E\u4FDD\u5B58\u5230 Omnifocus",trigger:{type:"cron",cron:"0 * * * *"},enabled:!0,steps:[{id:"search_ai_news",prompt:`\u641C\u7D22\u8FC7\u53BB 24 \u5C0F\u65F6\u5185\u5173\u4E8E AI/\u4EBA\u5DE5\u667A\u80FD\u7684\u6700\u65B0\u524D\u6CBF\u6587\u7AE0\u3002
2
+
3
+ \u641C\u7D22\u6765\u6E90:
4
+ 1. Hacker News AI \u677F\u5757 (https://news.ycombinator.com/front?day=1)
5
+ 2. ArXiv cs.AI \u6700\u65B0\u8BBA\u6587 (https://arxiv.org/list/cs.AI/recent)
6
+ 3. Reddit r/MachineLearning \u70ED\u95E8\u5E16\u5B50
7
+
8
+ \u627E\u51FA\u4E00\u7BC7\u6700\u6709\u4EF7\u503C\u3001\u6700\u6709\u6280\u672F\u6DF1\u5EA6\u7684\u6587\u7AE0\u3002
9
+
10
+ \u8F93\u51FA\u683C\u5F0F:
11
+ - \u6807\u9898\uFF1A[\u6587\u7AE0\u6807\u9898]
12
+ - \u6765\u6E90\uFF1A[\u7F51\u7AD9/\u5E73\u53F0\u540D\u79F0]
13
+ - \u94FE\u63A5\uFF1A[\u5B8C\u6574 URL]
14
+ - \u6838\u5FC3\u4EF7\u503C\uFF1A[1-2 \u53E5\u8BDD\u8BF4\u660E\u4E3A\u4EC0\u4E48\u8FD9\u7BC7\u6587\u7AE0\u503C\u5F97\u770B]`},{id:"summarize_article",dependsOn:["search_ai_news"],prompt:`\u9605\u8BFB\u5E76\u603B\u7ED3\u8FD9\u7BC7\u6587\u7AE0\u3002
15
+
16
+ \u6587\u7AE0\u4FE1\u606F:
17
+ {{search_ai_news.result}}
18
+
19
+ \u8BF7:
20
+ 1. \u7528 WebFetch \u83B7\u53D6\u6587\u7AE0\u5B8C\u6574\u5185\u5BB9
21
+ 2. \u63D0\u53D6\u6838\u5FC3\u89C2\u70B9\u548C\u6280\u672F\u7EC6\u8282
22
+ 3. \u7528\u4E2D\u6587\u5199\u51FA 300-500 \u5B57\u7684\u603B\u7ED3
23
+
24
+ \u603B\u7ED3\u7ED3\u6784:
25
+ ## \u6838\u5FC3\u53D1\u73B0
26
+ [\u6587\u7AE0\u6700\u91CD\u8981\u7684\u53D1\u73B0/\u521B\u65B0\u70B9]
27
+
28
+ ## \u6280\u672F\u7EC6\u8282
29
+ [\u5173\u952E\u7684\u6280\u672F\u65B9\u6CD5/\u5B9E\u73B0\u7EC6\u8282]
30
+
31
+ ## \u5F71\u54CD/\u610F\u4E49
32
+ [\u8FD9\u9879\u5DE5\u4F5C\u7684\u610F\u4E49\u6216\u5BF9\u884C\u4E1A\u7684\u5F71\u54CD]
33
+
34
+ ## \u539F\u6587\u94FE\u63A5
35
+ [\u6587\u7AE0 URL]`},{id:"save_to_omnifocus",dependsOn:["summarize_article"],prompt:`\u5C06\u6587\u7AE0\u603B\u7ED3\u4FDD\u5B58\u5230 Omnifocus\u3002
36
+
37
+ \u603B\u7ED3\u5185\u5BB9:
38
+ {{summarize_article.result}}
39
+
40
+ \u63D0\u53D6\u6587\u7AE0\u6807\u9898\u548C\u5B8C\u6574\u603B\u7ED3\uFF0C\u7136\u540E\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u6DFB\u52A0\u5230 Omnifocus Inbox\uFF1A
41
+
42
+ osascript /Users/norvyn/Code/Projects/Adam/scripts/add-to-omnifocus.applescript "[\u6587\u7AE0\u6807\u9898] AI \u524D\u6CBF\u901F\u9012" "[\u5B8C\u6574\u603B\u7ED3\u5185\u5BB9]"
43
+
44
+ \u6CE8\u610F\uFF1A
45
+ - \u5C06 [\u6587\u7AE0\u6807\u9898] \u66FF\u6362\u4E3A\u5B9E\u9645\u6807\u9898
46
+ - \u5C06 [\u5B8C\u6574\u603B\u7ED3\u5185\u5BB9] \u66FF\u6362\u4E3A\u5B8C\u6574\u7684\u603B\u7ED3\u6587\u672C\uFF08\u5305\u542B\u6838\u5FC3\u53D1\u73B0\u3001\u6280\u672F\u7EC6\u8282\u3001\u5F71\u54CD/\u610F\u4E49\u548C\u539F\u6587\u94FE\u63A5\uFF09
47
+ - \u603B\u7ED3\u5185\u5BB9\u4F7F\u7528\u6362\u884C\u7B26\u5206\u9694\u5404\u90E8\u5206
48
+
49
+ \u5B8C\u6210\u540E\u8F93\u51FA\uFF1A\u5DF2\u4FDD\u5B58\u5230 Omnifocus\uFF1A[\u4EFB\u52A1\u6807\u9898]`}],config:{timeout:300,fileAccess:{allowedPaths:["~/.adam/","/Users/norvyn/Code/Projects/Adam/scripts/"],deniedPaths:[]}},tags:["ai","digest","hourly","automation"],createdAt:Date.now()};I(e),n.info({templateId:v,cron:"0 * * * *"},"Registered built-in AI Hourly Digest template")}var R=class{cronJobs=new Map;workflowExecutor=new w;started=!1;taskCompletionHandler=null;async start(){if(this.started)return;this.started=!0,O();let e=y(!0),t=0;for(let r of e)r.trigger.type==="cron"&&r.trigger.cron&&(this.scheduleCronJob(r),t++);let o=0;for(let r of e)r.trigger.type==="once"&&r.trigger.runAt&&(this.scheduleOnceJob(r.id),o++);this.taskCompletionHandler=r=>{r.newStatus==="completed"&&this.checkEventTriggers(r.taskId).catch(i=>{n.error({taskId:r.taskId,error:i},"Event trigger check failed")})},u.on("task_status_change",this.taskCompletionHandler),this.cronJobs.set("memory-cleanup",setInterval(()=>{this.runMemoryCleanup()},36e5)),n.info({cronCount:t,onceCount:o},"Bree engine started with cron jobs + memory cleanup")}runMemoryCleanup(){try{let e=b(void 0,1e3,0),t=0;for(let o of e)t+=x(o.id);t>0&&n.info({totalCleaned:t},"Memory cleanup completed")}catch(e){n.warn({error:e},"Memory cleanup failed")}}async stop(){for(let[,e]of this.cronJobs)clearTimeout(e),clearInterval(e);this.cronJobs.clear(),this.taskCompletionHandler&&(u.off("task_status_change",this.taskCompletionHandler),this.taskCompletionHandler=null),this.started=!1,n.info("Bree engine stopped")}scheduleCronJob(e){let t=`template-${e.id}`;this.cronJobs.has(t)&&(clearTimeout(this.cronJobs.get(t)),this.cronJobs.delete(t));let o;try{o=D.parse(e.trigger.cron)}catch{n.warn({templateId:e.id,cron:e.trigger.cron},"Invalid cron expression");return}let r=()=>{let f=o.next().getTime()-Date.now();return Math.max(f,1e3)},i=()=>{this.executeCronTrigger(e.id).catch(f=>{n.error({templateId:e.id,error:f},"Cron trigger failed")});let c=setTimeout(i,r());this.cronJobs.set(t,c)},s=r(),a=setTimeout(i,s);this.cronJobs.set(t,a),n.debug({jobName:t,nextRun:new Date(Date.now()+s).toISOString()},"Scheduled cron job")}async executeCronTrigger(e){let t=d(e);!t||!t.enabled||(n.info({templateName:t.name},"Cron triggered"),await this.executeWorkflow(t,l()))}async scheduleJob(e){let t=d(e);t&&t.trigger.type==="cron"&&t.trigger.cron&&this.scheduleCronJob(t)}async unscheduleJob(e){let t=`template-${e}`,o=this.cronJobs.get(t);o&&(clearTimeout(o),this.cronJobs.delete(t))}async runNow(e){let t=d(e);if(!t)throw new Error(`Template ${e} not found`);let o=l();return this.executeWorkflow(t,o).catch(r=>{n.error({templateId:e,error:r},"Workflow execution failed")}),o}async checkEventTriggers(e){let t=p(e);if(!t)return;let o=y(!0),r=o.filter(i=>i.trigger.type==="event"&&i.trigger.event==="task_complete");for(let i of r)n.debug({templateName:i.name},"Event trigger matched"),await this.executeWorkflow(i,l());if(t.templateId){let i=o.filter(s=>s.trigger.type!=="event"||!s.trigger.event?!1:s.trigger.event===`template_complete:${t.templateId}`);for(let s of i)n.info({templateName:s.name,sourceTemplateId:t.templateId},"Template complete trigger matched"),await this.executeWorkflow(s,l())}}async executeWorkflow(e,t){if(n.info({templateName:e.name,executionId:t},"Executing workflow"),e.goalIds&&e.goalIds.length>0){for(let o of e.goalIds){let r=A(o);if(!r){n.warn({goalId:o,templateId:e.id},"Goal reference not found, skipping");continue}let i=l();C({id:i,name:r.name,description:r.description,roleId:r.roleId,metricType:r.metricType,targetValue:r.targetValue,currentValue:0,deadline:r.deadline,budgetUsd:r.budgetUsd,status:"active",createdAt:Date.now(),sourceSessionId:e.sourceSessionId,deliverTo:e.deliverTo,reportTo:e.reportTo});let s=l();T({id:s,status:"pending",prompt:`Decompose and execute goal: ${r.name}. ${r.description??""}`,parentId:i,config:h(),createdAt:Date.now(),templateId:e.id,roleId:e.rolePreference,deliverTo:e.deliverTo,reportTo:e.reportTo}),u.emit({type:"task_created",taskId:s}),n.info({templateId:e.id,sourceGoalId:o,newGoalId:i,taskId:s},"Goal reference triggered, dispatched decomposition task")}return}await this.workflowExecutor.execute(e,t)}scheduleOnceJob(e){let t=d(e);if(!t||!t.enabled||t.trigger.type!=="once")return;let r=(t.trigger.runAt?new Date(t.trigger.runAt).getTime():0)-Date.now();if(r<=0){n.info({templateId:e,runAt:t.trigger.runAt},"Once-shot template past due, executing immediately"),this.executeOnceTrigger(e).catch(a=>{n.error({templateId:e,error:a},"Once trigger execution failed")});return}let i=`template-${e}`;this.cronJobs.has(i)&&clearTimeout(this.cronJobs.get(i));let s=setTimeout(()=>{this.cronJobs.delete(i),this.executeOnceTrigger(e).catch(a=>{n.error({templateId:e,error:a},"Once trigger execution failed")})},r);this.cronJobs.set(i,s),n.info({templateId:e,runAt:t.trigger.runAt,delayMs:r},"Scheduled once-shot job")}async executeOnceTrigger(e){let t=d(e);!t||!t.enabled||(n.info({templateName:t.name},"Once-shot triggered"),await this.executeWorkflow(t,l()),P(e),n.info({templateId:e},"Once-shot template auto-disabled after execution"))}},S=null;function Y(){return S}function Z(g){S=g}export{R as a,Y as b,Z as c};
@@ -0,0 +1,86 @@
1
+ import{a as ue}from"./chunk-5JLMSNIW.js";import{b as Ge,c as Se,e as Ve}from"./chunk-IXF3XBGX.js";import{b as se}from"./chunk-AXMXXUPO.js";import{a as tt,c as Me,e as rt}from"./chunk-KICPHTI2.js";import{j as _e}from"./chunk-FUGJMHY4.js";import{d as Re}from"./chunk-PQ7KPALO.js";import{a as Ke}from"./chunk-2GXYBWLS.js";import{a as We}from"./chunk-WZOMGJSY.js";import{a as ce,b as _,c as de,d as Ze,e as et}from"./chunk-WXN3PSVX.js";import{a as ie,b as v,c as O,d as A}from"./chunk-L7426WNY.js";import{a as ke}from"./chunk-L7JP7DUO.js";import{a as Be,b as Te,c as Je,g as qe,j as He}from"./chunk-HAWA62R2.js";import{a as Ye,b as W,c as ze,f as Qe,g as Xe}from"./chunk-VF6GJGD6.js";import{d as k,g as je}from"./chunk-FYDFMYUP.js";import{a as Oe,b as le,e as Ie,f as V}from"./chunk-U36NBCR3.js";import{e as $e,f as T,h as F,i as G,j as Ue,k as we,l as ae}from"./chunk-XNWZZYAV.js";import{b,d as oe}from"./chunk-PCSZW2PE.js";import{c as I,d as Fe}from"./chunk-3DAK2XWP.js";import{c as Dt,e as At,f as x}from"./chunk-FCV2DPZQ.js";var wt={};At(wt,{getGlobalEnabledState:()=>z,getInstalledPlugin:()=>Le,getPluginManifest:()=>Q,listInstalledPlugins:()=>C,listMarketplaceSources:()=>Ce,resolvePluginPaths:()=>Ee,scanDirectoryConfig:()=>X});import{existsSync as E,readFileSync as K,readdirSync as yt}from"fs";import{join as y}from"path";import vt from"os";function j(e){try{if(!E(e))return null;let t=K(e,"utf-8");return JSON.parse(t)}catch{return null}}function z(){return j(Xt())?.enabledPlugins??{}}function Q(e){let t=e;function r(n,o){let i={};try{if(!E(n))return i;let l=K(n,"utf-8").replace(/^```yaml\r?\n/,"").replace(/^```\r?\n/,"");for(let u of o){let d=new RegExp(`^${u}:\\s*(.+)$`,"m"),p=l.match(d);p&&(i[u]=p[1].trim())}}catch{}return i}try{let n={name:"",skills:[],agents:[],mcpServers:[],hooks:[],lspServers:[]},o=y(t,".claude-plugin","plugin.json");if(E(o))try{let d=JSON.parse(K(o,"utf-8"));n.name=d.name??"",n.version=d.version,n.description=d.description,Array.isArray(d.lspServers)&&(n.lspServers=d.lspServers),Array.isArray(d.mcpServers)&&(n.mcpServers=d.mcpServers),Array.isArray(d.hooks)&&(n.hooks=d.hooks)}catch{}let i=y(t,"skills");if(E(i)){let d=yt(i,{withFileTypes:!0});for(let p of d){if(!p.isDirectory()&&!p.isSymbolicLink())continue;let g=y(i,p.name,"SKILL.md"),f=r(g,["name","description"]);f.name&&n.skills.push({name:f.name,description:f.description??""})}}let a=y(t,"agents");if(E(a)){let d=yt(a,{withFileTypes:!0});for(let p of d){if(!p.isFile()||!p.name.endsWith(".md"))continue;let g=r(y(a,p.name),["name","description"]);g.name&&n.agents.push({name:g.name,description:g.description??""})}}let l=y(t,".mcp.json");if(E(l))try{let d=JSON.parse(K(l,"utf-8"));d.mcpServers&&typeof d.mcpServers=="object"&&(n.mcpServers=Object.keys(d.mcpServers))}catch{}let u=y(t,"hooks","hooks.json");if(E(u))try{let d=JSON.parse(K(u,"utf-8"));Array.isArray(d)&&(n.hooks=d.map(p=>typeof p=="object"&&p!==null&&"event"in p?String(p.event):String(p)))}catch{}return n}catch{return null}}function C(e){let t=j(xe());if(!t?.plugins)return[];let r=z(),n=[];for(let[o,i]of Object.entries(t.plugins))if(!(!Array.isArray(i)||i.length===0))for(let a of i){let l=a.scope??"user";e?.scope&&l!==e.scope||e?.projectPath&&a.projectPath!==e.projectPath||n.push({id:o,name:o.split("@")[0],version:a.version??"",scope:l,projectPath:a.projectPath,installPath:a.installPath??y(Y(),o),enabled:r[o]??a.enabled??!0,installedAt:a.installedAt??"",lastUpdated:a.lastUpdated??""})}return n}function Le(e){let t=j(xe());if(!t?.plugins?.[e])return null;let r=t.plugins[e];if(!Array.isArray(r)||r.length===0)return null;let n=r[0],o=z();return{id:e,name:e.split("@")[0],version:n.version??"",scope:n.scope??"user",projectPath:n.projectPath,installPath:n.installPath??y(Y(),e),enabled:o[e]??n.enabled??!0,installedAt:n.installedAt??"",lastUpdated:n.lastUpdated??""}}function Ee(e){let t=j(xe()),r=new Map;for(let n of e){let o=t?.plugins?.[n];Array.isArray(o)&&o.length>0&&r.set(n,o[0].installPath??y(Y(),n))}return r}function Ce(){return j(Qt())?.marketplaces??[]}function X(e){let t=y(e,".claude","settings.json"),r=j(t);return{enabledPlugins:r?.enabledPlugins??{},mcpServers:r?.mcpServers??{},allowedTools:r?.allowedTools??[],disallowedTools:r?.disallowedTools??[]}}var Y,xe,Qt,Xt,ye=Dt(()=>{"use strict";Y=()=>y(vt.homedir(),".claude","plugins"),xe=()=>y(Y(),"installed_plugins.json"),Qt=()=>y(Y(),"known_marketplaces.json"),Xt=()=>y(vt.homedir(),".claude","settings.json")});import{createSdkMcpServer as cr,tool as m}from"@anthropic-ai/claude-agent-sdk";import{z as s}from"zod";ae();V();import{v4 as J}from"uuid";oe();function Nt(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 B(e){b().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 nt(e){return b().prepare("SELECT * FROM metric_tree WHERE goal_id = ? ORDER BY level, created_at").all(e).map(Nt)}var jt=I("goal-manager");async function pn(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 $t(e)}let r=Ut(t);return{goalState:t,validationResult:r,rawInput:e}}async function $t(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 ue(t,"You extract structured SMART goal fields from natural language. Reply with only valid JSON.")).match(/\{[\s\S]*\}/);if(n){let o=JSON.parse(n[0]),i=o.deadline_days??7;return{name:(o.name??e.slice(0,100)).slice(0,100),description:o.description??e,metric:o.metric??"completion",targetValue:o.targetValue??1,currentValue:0,deadline:Date.now()+i*24*60*60*1e3,budget:o.budget??5,roleId:o.roleId??"engineer",status:"active"}}}catch(r){jt.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 Ut(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 mn(e,t,r){let n=J(),o=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:o,deliverTo:t,reportTo:r};return ce(i),i}function ot(e,t){let r=Date.now(),n=[],o={id:J(),goalId:e,level:"L0",name:`${t}_goal_progress`,description:`Goal-level ${t} progress (monthly)`,weight:1,calibrationFactor:1,createdAt:r};n.push(o),B(o);let i={id:J(),goalId:e,level:"L1",parentId:o.id,name:`${t}_weekly_trend`,description:`Weekly trend for ${t}`,weight:.8,calibrationFactor:1,createdAt:r};n.push(i),B(i);let a={id:J(),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(a),B(a);let l={id:J(),goalId:e,level:"L3",parentId:a.id,name:`${t}_per_task`,description:`Per-task instant metric for ${t}`,weight:.4,calibrationFactor:1,createdAt:r};return n.push(l),B(l),n}var pe=class{static collect(t,r){let n=v(t);if(!n)return this.emptyMetrics(t,r);let o=se(t,500,0),i=n.completedAt&&n.startedAt?n.completedAt-n.startedAt:0,a=new Set,l=0,u=0;for(let p of o)p.type==="tool_call"&&p.toolName&&a.add(p.toolName),p.type==="error"&&l++,p.type==="approval_request"&&u++;let d={taskId:t,goalId:r,timestamp:Date.now(),durationMs:i,costUsd:n.costUsd??0,turns:n.numTurns??0,toolCount:a.size,errorCount:l,approvalCount:u,rawScore:0,isComplete:n.status==="completed"};return d.rawScore=this.computeRawScore(d),d}static computeRawScore(t){let n=1-Math.min(t.durationMs/6e5,1),i=1-Math.min(t.costUsd/5,1),l=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 d=t.errorCount===0?1:Math.max(0,1-t.errorCount*.2),p=Math.min(1,.5+t.approvalCount*.25);return .3*n+.2*i+.2*l+.1*u+.15*d+.05*p}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}}};oe();function Ot(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 it(e){b().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 st(e,t=100){return b().prepare("SELECT * FROM trials WHERE goal_id = ? ORDER BY completed_at DESC LIMIT ?").all(e,t).map(Ot)}var me=class{static collect(t){let r=_(t);if(!r)return this.emptyMetrics(t);let n=Date.now(),o=r.targetValue>0?Math.min(r.currentValue/r.targetValue,1):0,i=Math.max(0,(r.deadline-n)/(1e3*60*60*24)),a=this.calculateBudgetSpent(t),l=r.budgetUsd>0?Math.max(0,1-a/r.budgetUsd):1,u=this.calculateExpectedCompletion(r),d={goalId:t,metricType:r.metricType,targetValue:r.targetValue,currentValue:r.currentValue,progressPct:o,deadlineRemainingDays:i,budgetRemainingPct:l,expectedCompletionPct:u,rawScore:0};return d.rawScore=this.computeRawScore(d),d}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 o=t.budgetRemainingPct;return .5*r+.3*n+.2*o}static calculateExpectedCompletion(t){let r=Date.now(),n=t.deadline-t.createdAt,o=r-t.createdAt;if(n<=0)return 0;let i=o/n;if(i<.1)return .5;let a=t.targetValue>0?t.currentValue/t.targetValue:0;return i>0?a/i:0}static calculateBudgetSpent(t){let r=st(t,1e3),n=0,o=new Set;for(let i of r)if(i.taskId&&!o.has(i.taskId)){o.add(i.taskId);let a=v(i.taskId);a?.costUsd&&(n+=a.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 Ft=I("agent"),q=class{static cache=new Map;static CACHE_TTL=1440*60*1e3;static async callClaude(t){let o=(await ue(t,'You are an AI quality evaluator. Respond with JSON: {"score": 0-1, "confidence": 0-1, "reasoning": "..."}')).match(/\{[\s\S]*\}/);if(!o)throw new Error("Failed to parse LLM Judge response as JSON");let i=JSON.parse(o[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}`,o=this.cache.get(n);if(o&&Date.now()-o.evaluatedAt<this.CACHE_TTL)return o;let i=v(t);if(!i){let g={taskId:t,criteria:r,score:0,confidence:.3,reasoning:"Task not found",evaluatedAt:Date.now()};return this.cache.set(n,g),g}let a=this.getPromptTemplate(i.prompt??"",i.result??i.error??"",r),l,u,d;try{let g=await this.callClaude(a);l=g.score,u=g.confidence,d=g.reasoning}catch(g){Ft.warn({error:g,taskId:t},"LLM Judge Claude API call failed, using heuristic fallback"),i.status==="failed"?(l=.1,u=.6,d=`Task failed: ${i.error??"unknown error"} (heuristic fallback)`):i.status==="completed"&&i.result?(l=.7,u=.5,d="Task completed with result (heuristic fallback due to API error)"):i.status==="completed"?(l=.5,u=.4,d="Task completed without explicit result (heuristic fallback)"):(l=.3,u=.3,d=`Task in status: ${i.status} (heuristic fallback)`)}let p={taskId:t,criteria:r,score:l,confidence:u,reasoning:d,evaluatedAt:Date.now()};return this.cache.set(n,p),p}static shouldUseObjective(t){let r=v(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 Gt={L0:.2,L1:.15,L2:.35,L3:.3},ge=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 o=n.parentId,i=this.children.get(o)??[];i.push(n),this.children.set(o,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=nt(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,o)=>o.weight-n.weight)}aggregateScores(t,r){let n=this.queryPath(t);if(n.length===0)return 0;let o=0,i=0;for(let a of n){let l=r.get(a.id)??0,u=a.weight*a.calibrationFactor;o+=l*u,i+=u}return i>0?o/i:0}getWeightedScore(t){let r=0;for(let[n,o]of Object.entries(Gt)){let i=this.aggregateScores(n,t);r+=i*o}return Math.max(0,Math.min(1,r))}getNodeCount(){return this.nodes.size}getChildren(t){return this.children.get(t)??[]}};var Nn=I("agent");function fe(e,t){let r=Date.now(),n=ge.buildFromGoal(e),o=new Map,i=me.collect(e);for(let u of n.queryPath("L0"))o.set(u.id,i.rawScore);let a=Vt(n);if(t){let u=pe.collect(t,e);if(u.isComplete){for(let p of n.queryPath("L3"))o.set(p.id,u.rawScore);let d=n.getNodeCount()>0?n.getWeightedScore(o):Math.max(0,Math.min(1,u.rawScore*.65+i.rawScore*.35));return{goalId:e,taskId:t,reward:d,breakdown:{L0:i.rawScore,L1:0,L2:0,L3:u.rawScore},calibrationFactors:a,source:"objective",confidence:.9,computedAt:r}}}if(t&&!q.shouldUseObjective(t)){let d=q.evaluate(t,"general_quality"),p=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:a,source:"llm_judge",confidence:.4,computedAt:r}}let l=n.getNodeCount()>0?n.getWeightedScore(o):i.rawScore;return{goalId:e,reward:l,breakdown:{L0:i.rawScore,L1:0,L2:0,L3:0},calibrationFactors:a,source:"fallback",confidence:.3,computedAt:r}}function Vt(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 ut}from"uuid";oe();function he(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 at(e){b().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 lt(e){let r=b().prepare("SELECT * FROM strategies WHERE id = ?").get(e);return r?he(r):void 0}function Un(e=100){return b().prepare("SELECT * FROM strategies ORDER BY created_at LIMIT ?").all(e).map(he)}function ct(e){return b().prepare("SELECT * FROM strategies WHERE role_id = ? ORDER BY created_at").all(e).map(he)}function L(e,t){return b().prepare("SELECT * FROM strategies WHERE role_id = ? AND task_type = ? ORDER BY created_at").all(e,t).map(he)}function dt(e,t){b().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 H=class{static sampleBeta(t,r){let n=this.sampleGamma(t,1),o=this.sampleGamma(r,1);return n/(n+o)}static sampleGamma(t,r){if(t<1)return this.sampleGamma(t+1,r)*Math.pow(Math.random(),1/t);let n=t-1/3,o=1/Math.sqrt(9*n);for(;;){let i,a;do i=this.randn(),a=1+o*i;while(a<=0);a=a*a*a;let l=Math.random();if(l<1-.0331*i*i*i*i||Math.log(l)<.5*i*i+n*(1-a+Math.log(a)))return n*a/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 o of t){let i=this.sampleBeta(o.alpha,o.beta);i>n&&(n=i,r=o)}return r}static getProbabilities(t,r=1e4){let n=new Map;for(let i=0;i<r;i++){let a=this.sample(t);a&&n.set(a.id,(n.get(a.id)||0)+1)}let o=new Map;for(let[i,a]of n)o.set(i,a/r);return o}};var Wt=5,Pe=20,pt=.5,S=class{static selectStrategy(t,r){let n=L(t,r);return H.sample(n)}static recordTrial(t,r,n,o,i,a,l){dt(t,o),it({id:ut(),strategyId:t,goalId:r,taskId:n,reward:o,metricL2Score:i,metricL3Score:a,context:l,completedAt:Date.now()})}static getStrategies(t,r){return L(t,r)}static getStrategyById(t){return lt(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,d)=>u+d.totalTrials,0)/n.length,a=n.filter(u=>u.avgReward!==void 0).map(u=>u.avgReward),l=a.length>0?a.reduce((u,d)=>u+d,0)/a.length:0;return{count:n.length,avgTrials:i,avgReward:l,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<Wt?!0:n.count<Pe&&n.maxTrials>0}static addStrategy(t,r,n,o){if(L(t,r).length>=Pe)throw new Error(`Strategy population at maximum (${Pe}) for ${t}/${r}`);let a={id:`strat-${ut().slice(0,8)}`,roleId:t,taskType:r,name:n,promptTemplate:o,alpha:pt,beta:pt,totalTrials:0,createdAt:Date.now()};return at(a),a}static getTopStrategies(t,r,n=3){let i=L(t,r).filter(a=>a.totalTrials>0);return i.sort((a,l)=>(l.avgReward??0)-(a.avgReward??0)),i.slice(0,n)}static getSamplingProbabilities(t,r){let n=L(t,r);return H.getProbabilities(n)}static evaluateAndRecord(t,r,n,o,i,a){let l=fe(r,n);return this.recordTrial(t,r,n,l.reward,o,i,a),l.reward}};var Bt=3,Jt=2,be=class{static async generateVariants(t,r,n=Bt,o=Jt){let i=S.getTopStrategies(t,r,n);if(i.length===0){let l=`baseline-${r}-v1`;return S.addStrategy(t,r,l,this.generateBaselinePrompt(t,r)),[l]}let a=[];for(let l=0;l<o;l++){let u=i[0].totalTrials+l+1,d=`${r}-evolved-v${u}`,p=i[0].promptTemplate,g=this.mutateTemplate(p);S.addStrategy(t,r,d,g),a.push(d)}return a}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"}}};import{tool as N}from"@anthropic-ai/claude-agent-sdk";import{z as h}from"zod";import{v4 as qt}from"uuid";function M(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}var Ht={query:h.string().describe("Search query for memory retrieval"),roleId:h.string().optional().describe("Role ID to scope search (omit for cross-role)"),topK:h.number().optional().describe("Max results to return (default 5)")},Kt={query:h.string().describe("Search query for memory retrieval"),topK:h.number().optional().describe("Max results to return (default 5)")},Yt={id:h.string().optional().describe("Memory ID to update. Omit to create new."),roleId:h.string().describe("Role ID to save memory under"),content:h.string().describe("Memory content text"),type:h.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:h.array(h.string()).optional().describe("Keywords for BM25 search"),importance:h.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:h.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},zt={id:h.string().optional().describe("Memory ID to update. Omit to create new."),content:h.string().describe("Memory content text"),type:h.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:h.array(h.string()).optional().describe("Keywords for BM25 search"),importance:h.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:h.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},mt={id:h.string().describe("Memory ID to delete")};async function gt(e,t){let r=e??t.roleId,n=t.topK??5,o=await Ke(r,t.query,{topK:n});return M({results:o.map(i=>({id:i.id,type:i.type,content:i.content,keywords:i.keywords,importance:i.importance,score:i.score}))})}async function ft(e,t){let r=e??t.roleId;if(!r)return M({error:"roleId is required"});let n,o=!0;try{n=await We(t.content)}catch{o=!1}if(t.id){if(!Te(t.id))return M({error:`Memory ${t.id} not found`});let u=Je(t.id,{content:t.content,embedding:n,keywords:t.keywords,importance:t.importance,type:t.type});return M({id:t.id,action:"updated",success:u,embeddingUpdated:o})}let i=`mem-${qt().slice(0,8)}`,a=Date.now();return Be({id:i,roleId:r,type:t.type??"thought",content:t.content,embedding:n,keywords:t.keywords??[],importance:t.importance??3,sourceType:"manual",createdAt:a,lastAccessed:a,retrievedCount:0,tier:t.tier??"episodic"}),M({id:i,action:"created",success:!0,embeddingUpdated:o})}async function ht(e,t){if(e){let r=Te(t.id);if(!r)return M({error:`Memory ${t.id} not found`});if(r.roleId!==e)return M({error:`Memory ${t.id} does not belong to this role`})}return He(t.id),M({id:t.id,deleted:!0})}function bt(e){return e?[N("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",Kt,async t=>gt(e,t)),N("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",zt,async t=>ft(e,t)),N("delete_memory","Delete a memory by ID.",mt,async t=>ht(e,t))]:[N("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",Ht,async t=>gt(void 0,t)),N("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",Yt,async t=>ft(void 0,t)),N("delete_memory","Delete a memory by ID.",mt,async t=>ht(void 0,t))]}import{v4 as w}from"uuid";ye();import{spawnSync as It}from"child_process";import{createRequire as Zt}from"module";import{dirname as er,join as St}from"path";import{openSync as tr,readFileSync as rr,unlinkSync as nr}from"fs";var or=3e4,kt=12e4;function Tt(){let t=Zt(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk");return St(er(t),"cli.js")}function Z(e,t){let r=Tt(),n=t?.timeout??or;if(t?.json){let i=St("/tmp",`adam-cli-stdout-${process.pid}-${Date.now()}.txt`),a=tr(i,"w");try{let l=It("node",[r,...e],{cwd:t.cwd,timeout:n,stdio:["ignore",a,"pipe"],encoding:"utf-8"});if(l.status!==0)throw new Error(l.stderr?.trim()||`CLI exited with status ${l.status}`);return rr(i,"utf-8")}finally{try{nr(i)}catch{}}}let o=It("node",[r,...e],{cwd:t?.cwd,timeout:n,encoding:"utf-8"});if(o.status!==0)throw new Error(o.stderr?.trim()||`CLI exited with status ${o.status}`);return o.stdout}function Rt(){let e=Z(["plugin","list","--available","--json"],{json:!0});return JSON.parse(e)}function De(e,t="user",r){return Z(["plugin","install",e,"--scope",t],{cwd:r,timeout:kt})}function Ae(e,t,r){return Z(["plugin","uninstall",e],{cwd:r,timeout:kt})}function _t(e,t){return Z(["plugin","enable",e])}function Mt(e,t){return Z(["plugin","disable",e])}function uo(){try{return!!Tt()}catch{return!1}}ye();V();var sr={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 ee(e,t){let r=e.allowedTools??[];if(r.length===0)return"No tool permissions";let n=new Map,o=[];for(let d of r){let p=sr[d];if(p){let g=n.get(p.category)??[];g.push(p.label),n.set(p.category,g)}else o.push(d)}let i=[];for(let[d,p]of n)i.push(`${d} (${p.join(", ")})`);o.length>0&&i.push(o.join(", "));let a=i.join(" \xB7 "),l=Object.keys(e.mcpServers??{});l.length>0&&(a+=` \xB7 MCP: ${l.join(", ")}`);let u=e.additionalDirectories??[];if(u.length>0&&(a+=` \xB7 Dirs: ${u.map(d=>d.path).join(", ")}`),t&&t.plugins.length>0){let d=t.plugins.map(p=>{let g=[];return p.skills.length>0&&g.push(`skills: ${p.skills.map(f=>f.name).join(", ")}`),p.agents.length>0&&g.push(`agents: ${p.agents.map(f=>f.name).join(", ")}`),g.length>0?`${p.name} (${g.join("; ")})`:p.name});a+=` \xB7 Plugins: ${d.join(", ")}`}return a}function ar(e){let t=[],r=e.additionalDirectories??[];for(let n of r){if(!n.inheritPlugins&&!n.inheritMcp)continue;let o=X(n.path),i=Object.entries(o.enabledPlugins).filter(([,l])=>l).map(([l])=>l),a=Ee(i);for(let[,l]of a)t.includes(l)||t.push(l)}try{let n=Oe(e.name),o=C({scope:"project",projectPath:n});for(let i of o)i.installPath&&!t.includes(i.installPath)&&t.push(i.installPath)}catch{}return t}function Ne(e){let t=ar(e),r=[];for(let n of t){let o=Q(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}}oe();function lr(e){return{id:e.id,roleId:e.role_id??void 0,taskPattern:e.task_pattern,maxRiskLevel:e.max_risk_level,createdAt:e.created_at,createdByTaskId:e.created_by_task_id??void 0}}var Pt={low:1,medium:2,high:3};function xt(e){b().prepare(`
69
+ INSERT INTO approval_rules (id, role_id, task_pattern, max_risk_level, created_at, created_by_task_id)
70
+ VALUES (?, ?, ?, ?, ?, ?)
71
+ `).run(e.id,e.roleId??null,e.taskPattern,e.maxRiskLevel,e.createdAt,e.createdByTaskId??null)}function ho(e,t,r){let o=b().prepare("SELECT * FROM approval_rules ORDER BY created_at DESC").all();for(let i of o)if(!(i.role_id&&i.role_id!==e)&&!(Pt[r]>Pt[i.max_risk_level]))try{if(new RegExp(i.task_pattern,"i").test(t))return lr(i)}catch{}}import*as Lt from"crypto";var te=I("api"),re=class{cancelTask(t){let r=v(t);r&&(O(t,{status:"cancelled",completedAt:Date.now()}),ke.emit({type:"task_status_change",taskId:t,oldStatus:r.status,newStatus:"cancelled"}),te.debug({taskId:t,oldStatus:r.status},"Task cancelled"))}resolveApproval(t,r,n){return te.debug({approvalId:t,action:r,reason:n},"Approval resolved (no-op in Pure C)"),!0}resolvePlanApproval(t,r,n,o){let i=Ge(t);if(!i)return te.warn({planId:t},"Plan not found or already resolved"),!1;let a=v(i.taskId);return a?(Ve(t,r==="allow"?"approved":"denied",n),r==="allow"&&n==="permanent"&&xt({id:Lt.randomUUID(),roleId:i.roleId,taskPattern:a.prompt.slice(0,100).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),maxRiskLevel:i.plan.overallRisk,createdAt:Date.now(),createdByTaskId:a.id}),ke.emit({type:"plan_approval_decision",taskId:a.id,planId:t,decision:r,approvalType:n,reason:o}),te.debug({planId:t,decision:r,approvalType:n},"Plan approval resolved"),!0):(te.warn({planId:t},"Task not found for plan"),!1)}};import{existsSync as dr}from"fs";var ve=I("manager");function c(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}async function P(e){let{listChannels:t}=await import("./channels-VEUBY2NZ.js"),r=t(),{listSessions:n}=await import("./session-manager-45LFTPBA.js"),o=[...n("active"),...n("archived")],i=[];for(let a of e)if(a.type==="session"&&a.sessionId)i.push({type:"session",sessionId:a.sessionId});else if(a.type==="channel"){let l=a.channelId,u=a.chatId;if(!l&&a.channelName){let d=r.find(p=>p.name.toLowerCase().includes(a.channelName.toLowerCase()));d&&(l=d.id)}if(l&&!u){let d=o.find(p=>p.source.type==="channel"&&p.source.channelId===l&&p.source.chatId);d?.source.chatId?u=d.source.chatId:u=r.find(g=>g.id===l)?.config?.userId}l&&u?i.push({type:"channel",channelId:l,chatId:u}):ve.warn({channelName:a.channelName,channelId:l,chatId:u},"Could not resolve channel notify target")}return i}async function ur(e){let{listRoles:t}=await import("./roles-SG2YAR64.js"),r=t(void 0,100,0);for(let n of r)if(n.name.toLowerCase().includes(e.toLowerCase()))return n.id}var pr={goalId:s.string()},mr={goalId:s.string(),status:s.string().optional(),currentValue:s.number().optional(),budgetUsd:s.number().optional(),notes:s.string().optional()},gr={goalId:s.string(),goalDescription:s.string(),maxSubtasks:s.number().optional()},D=s.union([s.object({type:s.literal("session"),sessionId:s.string()}),s.object({type:s.literal("channel"),channelName:s.string()}),s.object({type:s.literal("channel"),channelId:s.string(),chatId:s.string().optional()})]),fr={prompt:s.string(),roleId:s.string().describe("Role ID. Call list_roles first to find the best role for the task."),deliverTo:s.array(D).optional().describe("Where to deliver the task output (result full text). E.g., send result to a specific channel."),reportTo:s.array(D).optional().describe("Where to send status reports (completion summary). Defaults to the originating channel/session."),toolOverrides:s.object({allowedTools:s.array(s.string()).optional(),disallowedTools:s.array(s.string()).optional()}).optional()},hr={taskId:s.string(),goalId:s.string().optional(),strategyId:s.string().optional()},br={roleId:s.string(),taskType:s.string(),name:s.string().optional()},yr={status:s.string().optional(),limit:s.number().optional()},vr={taskId:s.string(),roleId:s.string()},wr={taskId:s.string().optional(),status:s.string().optional(),limit:s.number().optional()},Ir={roleId:s.string(),allowedPaths:s.array(s.string()).optional(),deniedPaths:s.array(s.string()).optional(),allowedTools:s.array(s.string()).optional(),disallowedTools:s.array(s.string()).optional(),additionalDirectories:s.array(s.object({path:s.string(),inheritPlugins:s.boolean().optional(),inheritMcp:s.boolean().optional(),inheritPermissions:s.boolean().optional()})).optional(),allowedChannels:s.array(s.string()).optional(),inheritUserSettings:s.boolean().optional().describe("Enable/disable inheriting user-level settings (global plugins, MCP servers). Default: false (isolated).")},Sr={roleId:s.string().optional(),limit:s.number().optional()},kr={name:s.string(),cagPrompt:s.string(),traits:s.array(s.string()).optional(),allowedTools:s.array(s.string()).optional(),disallowedTools:s.array(s.string()).optional(),additionalDirectories:s.array(s.object({path:s.string(),inheritPlugins:s.boolean().optional(),inheritMcp:s.boolean().optional(),inheritPermissions:s.boolean().optional()})).optional()},Tr={roleId:s.string(),reason:s.string().optional()},Rr={name:s.string(),description:s.string().optional(),roleId:s.string().optional(),metric:s.string().optional(),targetValue:s.number().optional(),deadline:s.number().optional(),budgetUsd:s.number().optional(),deliverTo:s.array(D).optional().describe("Where to deliver goal completion notifications.")},_r={name:s.string(),description:s.string().optional(),triggerType:s.enum(["cron","event"]),triggerCron:s.string().optional(),triggerEvent:s.string().optional(),prompt:s.string(),roleId:s.string().optional(),enabled:s.boolean().optional(),goalIds:s.array(s.string()).optional(),deliverTo:s.array(D).optional().describe("Where to deliver the task output (result full text)."),reportTo:s.array(D).optional().describe("Where to send status reports (completion summary).")},Mr={status:s.enum(["active","retired","probation"]).optional(),limit:s.number().optional()},Pr={enabled:s.boolean().optional()},xr={},Lr={},Er={prompt:s.string().describe("The task prompt to execute after the delay"),delayMinutes:s.number().optional().describe("Minutes from now to execute (e.g., 30 for 'half an hour later')"),runAt:s.string().optional().describe("ISO 8601 timestamp to execute at (e.g., '2026-04-01T15:00:00+08:00')"),roleId:s.string().describe("Role ID to assign the task to. Call list_roles first."),deliverTo:s.array(D).optional().describe("Where to deliver the task output (result full text)."),reportTo:s.array(D).optional().describe("Where to send status reports (completion summary).")},Cr={roleId:s.string().optional().describe("If provided, shows which plugins are installed in that role's workspace.")},Dr={roleId:s.string().describe("Role ID to install the plugin under (project-scope)."),pluginId:s.string().describe("Plugin ID (e.g. 'github@anthropic'). Use list_available_plugins to discover available plugins.")},Ar={roleId:s.string().describe("Role ID to uninstall the plugin from."),pluginId:s.string().describe("Plugin ID to uninstall.")},Nr={roleId:s.string().describe("Role ID to bind the MCP server to."),mcpName:s.string().describe("Name for this MCP server (e.g., 'github', 'filesystem')."),mcpConfig:s.record(s.string(),s.unknown()).describe("MCP server configuration object.")},jr={roleId:s.string().describe("Role ID to unbind the MCP server from."),mcpName:s.string().describe("Name of the MCP server to remove.")},$r={pluginId:s.string().describe("Plugin ID (e.g., 'github@anthropic').")},Ur={pluginId:s.string().describe("Plugin ID (e.g., 'github@anthropic').")},Or={pluginId:s.string().describe("Plugin ID (e.g., 'github@anthropic').")},Fr={pluginId:s.string().describe("Plugin ID (e.g., 'github@anthropic').")},Gr={},Vr={},Wr={pluginId:s.string().describe("Plugin ID (e.g., 'github@anthropic').")},Br={roleId:s.string().describe("Role ID to associate scanned plugins with."),path:s.string().describe("Directory path to scan for .claude/settings.json.")},Jr={taskId:s.string().describe("Task ID to cancel.")},qr={taskId:s.string().describe("Task ID to get logs for."),limit:s.number().optional().describe("Max log entries (default 20).")},Hr={roleId:s.string().describe("Role ID to delete.")},Kr={},Yr={updates:s.record(s.string(),s.unknown()).describe("Config key-value pairs to update. Example: { 'defaults.maxTurns': 50, 'logging.level': 'debug' }")},zr={roleId:s.string().describe("Role ID to list memories for."),limit:s.number().optional().describe("Max results (default 20).")},Qr={templateId:s.string().describe("Template ID to update."),name:s.string().optional(),enabled:s.boolean().optional(),prompt:s.string().optional(),triggerCron:s.string().optional(),triggerEvent:s.string().optional(),roleId:s.string().optional()},Xr={templateId:s.string().describe("Template ID to delete.")},Zr={templateId:s.string().describe("Template ID to run immediately.")},en={enabled:s.boolean().optional().describe("Filter by enabled status.")},tn={eventType:s.string().describe("Event type that triggers this rule (e.g., 'task_complete')."),channelId:s.string().describe("Channel ID to deliver to."),format:s.string().optional().describe("Format template (e.g., 'summary', 'full'). Default: 'summary'."),matchCriteria:s.record(s.string(),s.unknown()).optional().describe("JSON match criteria for event fields."),enabled:s.boolean().optional().describe("Enable this rule immediately (default true).")},rn={ruleId:s.string().describe("Delivery rule ID to delete.")},nn={roleId:s.string().optional().describe("Role ID to filter strategies by.")},Et=[m("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.",pr,async e=>{let t=_(e.goalId);if(!t)return c({error:"Goal not found"});let r=Date.now(),n=t.targetValue>0?t.currentValue/t.targetValue:0;return c({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})}),m("update_goal_state","Update a goal's status, current value, or budget.",mr,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(),de(e.goalId,t)),c({success:!0})}),m("decompose_goal","Decompose a goal into actionable subtasks using LLM reasoning.",gr,async e=>{let t=k(),r=Math.min(e.maxSubtasks??5,10);try{let{query:o}=await import("@anthropic-ai/claude-agent-sdk"),i=`Decompose this goal into ${r} actionable subtasks.
72
+
73
+ Goal: ${e.goalDescription}
74
+
75
+ Respond ONLY with a JSON array. Each item: {"description": "...", "prompt": "detailed task instruction", "complexity": "low|medium|high", "role": "engineer|analyst|content_creator|reviewer"}
76
+
77
+ Rules:
78
+ - Each subtask must be independently executable
79
+ - Order from foundational to dependent
80
+ - Be specific about what each subtask should accomplish
81
+ - For each subtask, specify the best role from: 'engineer', 'analyst', 'content_creator', 'reviewer'. Match role to the nature of the work.`,a=o({prompt:i,options:{cwd:process.cwd(),maxTurns:1,maxBudgetUsd:.02}}),l="";for await(let d of a){let p=d;p.type==="result"&&typeof p.result=="string"&&(l=p.result)}let u=l.match(/\[[\s\S]*\]/);if(u){let d=JSON.parse(u[0]),p=[];for(let g=0;g<Math.min(d.length,r);g++){let f=d[g],ne=`subtask-${w().slice(0,8)}`,$=f.role,U=$?await ur($):void 0;ie({id:ne,status:"pending",prompt:f.prompt,parentId:e.goalId,roleId:U,config:t.defaults,createdAt:Date.now()}),p.push({id:ne,description:f.description,prompt:f.prompt,dependencies:g>0?[p[g-1].id]:[],estimatedComplexity:f.complexity??"medium",role:$})}if(p.length>0)return c({subtasks:p})}}catch(o){ve.error({error:o},"LLM decomposition failed, using fallback")}let n=[];for(let o=0;o<r;o++){let i=`subtask-${w().slice(0,8)}`,a=`Subtask ${o+1} of goal: ${e.goalDescription.slice(0,100)}`,l=`${e.goalDescription}
82
+
83
+ Subtask ${o+1}/${r}`;ie({id:i,status:"pending",prompt:l,parentId:e.goalId,config:t.defaults,createdAt:Date.now()}),n.push({id:i,description:a,prompt:l,dependencies:o>0?[n[o-1].id]:[],estimatedComplexity:"medium"})}return c({subtasks:n})}),m("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.",fr,async e=>{let t=T(e.roleId);if(!t||t.status!=="active"){let U=G("active",20,0).filter(R=>R.source!=="system").map(R=>({id:R.id,name:R.name,allowedTools:R.allowedTools??[],capabilitySummary:ee(R)}));return c({error:`Role not found or not active: ${e.roleId}. Pick a roleId from the list below.`,availableRoles:U})}let r=w(),n=k(),o=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"]},a="general";for(let[U,R]of Object.entries(i))if(R.some(Ct=>o.includes(Ct))){a=U;break}let l,u=e.prompt,d=S.selectStrategy(e.roleId,a);d?.promptTemplate&&(u=`${d.promptTemplate}
84
+
85
+ ## Task
86
+ ${e.prompt}`,l=d.id);let p=[...n.defaults.allowedTools];e.toolOverrides?.allowedTools&&(p=[...e.toolOverrides.allowedTools]);let g={...n.defaults,allowedTools:p,disallowedTools:e.toolOverrides?.disallowedTools??n.defaults.disallowedTools},f=e.deliverTo?await P(e.deliverTo):void 0,ne=e.reportTo?await P(e.reportTo):void 0;ie({id:r,status:"pending",prompt:u,roleId:e.roleId,deliverTo:f,reportTo:ne,config:g,createdAt:Date.now()});let{serverBus:$}=await import("./server-bus-GEGVMSCA.js");return $.emit({type:"task_created",taskId:r}),c({taskId:r,roleId:e.roleId,strategyId:l})}),m("evaluate_result","Evaluate a completed task's result and record a trial for Thompson Sampling.",hr,async e=>{let{goalId:t,taskId:r,strategyId:n}=e,o=fe(t??"",r);return n&&t&&S.recordTrial(n,t,r,o.reward,o.breakdown.L2||void 0,o.breakdown.L3||void 0,"Evaluated via adam-tools"),c({reward:o.reward,metricL2Score:o.breakdown.L2||void 0,metricL3Score:o.breakdown.L3||void 0,source:o.source,reasoning:`Evaluated via ${o.source} with confidence ${o.confidence.toFixed(2)}`})}),m("create_strategy","Create a new strategy variant for a role/taskType using LLM evolution.",br,async e=>{let{roleId:t,taskType:r}=e;await be.generateVariants(t,r,3,1);let n=S.getStrategies(t,r),o=n[n.length-1];return c(o?{id:o.id,name:o.name,promptTemplate:o.promptTemplate}:{error:`Failed to create strategy for ${t}/${r}`})}),m("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.",yr,async e=>{let t=e.status;return c(Ze(t,e.limit??10,0))}),m("delete_goal","Delete a goal by ID.",{goalId:s.string()},async e=>_(e.goalId)?(et(e.goalId),c({success:!0,goalId:e.goalId})):c({error:"Goal not found"})),m("pause_goal","Pause an active goal.",{goalId:s.string()},async e=>_(e.goalId)?(de(e.goalId,{status:"paused",updatedAt:Date.now()}),c({success:!0,goalId:e.goalId,status:"paused"})):c({error:"Goal not found"})),m("assign_role","Assign a role to a pending task.",vr,async e=>{let{taskId:t,roleId:r}=e;if(!v(t))return c({error:`Task not found: ${t}`});let o=T(r);return o?(O(t,{roleId:r}),ve.debug({taskId:t,roleId:r,roleName:o.name},"Role assigned to task"),c({success:!0,taskId:t,roleId:r})):c({error:`Role not found: ${r}`})}),...bt(),m("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.",wr,async e=>{if(e.taskId){let r=v(e.taskId);return c(r??{error:"Task not found"})}let t=e.status;return c(A(t,e.limit??100,0))}),m("modify_role_permissions","Update a role's RBAC permissions (paths, tools).",Ir,async e=>{let t=T(e.roleId);if(!t)return c({error:`Role not found: ${e.roleId}`});let r={};if(e.allowedTools&&(r.allowedTools=e.allowedTools),e.disallowedTools&&(r.disallowedTools=e.disallowedTools),e.additionalDirectories!==void 0&&(r.additionalDirectories=e.additionalDirectories),e.allowedChannels!==void 0&&(r.allowedChannels=e.allowedChannels),"inheritUserSettings"in e&&(r.inheritUserSettings=e.inheritUserSettings),e.allowedPaths||e.deniedPaths){let n=t.preferences??{},o=n.permissions??{};r.preferences={...n,permissions:{...o,allowedPaths:e.allowedPaths??o.allowedPaths,deniedPaths:e.deniedPaths??o.deniedPaths}}}return F(e.roleId,r),c({success:!0})}),m("view_audit_log","View the evolution audit log for role changes.",Sr,async e=>{let{listEvolutionAudit:t}=await import("./evolution-audit-B7WKMOVR.js"),r=t(e.limit??50);return c({entries:r})}),m("list_roles","List all roles with their capabilities including bound plugins (skills/agents). Use this to discover available roles before dispatching tasks.",Mr,async e=>{let r=G(e.status,e.limit??50,0).map(n=>{let o=Ne(n);return{id:n.id,name:n.name,status:n.status,allowedTools:n.allowedTools??[],disallowedTools:n.disallowedTools??[],additionalDirectories:n.additionalDirectories??[],cagPrompt:n.cagPrompt.slice(0,500)+(n.cagPrompt.length>500?"...":""),capabilitySummary:ee(n,o),plugins:o.plugins.map(i=>({name:i.name,skills:i.skills.map(a=>a.name),agents:i.agents.map(a=>a.name)}))}});return c({roles:r})}),m("create_role","Create a new role with a name, CAG prompt, and optional tool permissions.",kr,async e=>{let t=`role-${w().slice(0,8)}`,r={id:t,name:e.name,cagPrompt:e.cagPrompt,learnedRules:[],memoryStreamId:`mem-${w().slice(0,8)}`,status:"active",preferences:{},createdAt:Date.now(),allowedTools:e.allowedTools,disallowedTools:e.disallowedTools,additionalDirectories:e.additionalDirectories};return $e(r),le(r),c({roleId:t,name:e.name,allowedTools:e.allowedTools,additionalDirectories:e.additionalDirectories??[]})}),m("retire_role","Retire a role (marks as retired, stops receiving tasks).",Tr,async e=>T(e.roleId)?(F(e.roleId,{status:"retired"}),ve.info({roleId:e.roleId,reason:e.reason},"Role retired"),c({success:!0})):c({error:`Role not found: ${e.roleId}`})),m("create_goal","Create a new goal with optional budget, deadline, and metric tracking.",Rr,async e=>{let t=w(),r=Date.now(),n=r+10080*60*1e3,o={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 P(e.deliverTo):void 0};ce(o),ot(t,o.metricType);let i=_(t);return c({goalId:i.id,name:i.name,status:i.status})}),m("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.",_r,async e=>{let{createTaskTemplate:t}=await import("./task-templates-7LSQ6OST.js"),r=w(),n=w(),o=e.deliverTo?await P(e.deliverTo):void 0,i=e.reportTo?await P(e.reportTo):void 0,a={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:o,reportTo:i};return t(a),c({templateId:r,name:a.name,trigger:a.trigger})}),m("list_templates","List task templates (automations). Use this to check existing scheduled/recurring tasks before creating new ones.",{enabled:s.boolean().optional().describe("Filter by enabled status. Omit to list all."),limit:s.number().optional().describe("Max results (default 50)")},async e=>{let{listTaskTemplates:t}=await import("./task-templates-7LSQ6OST.js"),r=t(e.enabled,e.limit??50,0);return c(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})))}),m("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:s.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:s.string().describe("The message content to send (text caption when sending media)"),mediaUrl:s.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:s.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 c({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 a=e.mediaUrl.startsWith("file://")?new URL(e.mediaUrl).pathname:e.mediaUrl;if(!dr(a))return c({error:`Media file not found: ${a}. Verify the file exists before sending.`});if(!e.mediaType)return c({error:"mediaType is required when mediaUrl is provided. Specify one of: image, audio, video, file."})}let t=await P([{type:"channel",channelName:e.channelName}]);if(t.length===0)return c({error:`Channel "${e.channelName}" not found or no chatId available`});let r=t[0];if(r.type!=="channel")return c({error:"Resolved target is not a channel"});let{getOutboundGateway:n}=await import("./outbound-gateway-DZTXBUTP.js"),i=await n().send({channelId:r.channelId,chatId:r.chatId,content:e.message,messageType:"deliver",mediaUrl:e.mediaUrl,mediaType:e.mediaType});return c({success:i.success,channelName:e.channelName,...i.error?{error:i.error}:{}})}),m("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.",Pr,async e=>{let t=Re(e.enabled),r=[..._e("active"),..._e("archived")],n=t.map(o=>{let i,a=r.find(l=>l.source.type==="channel"&&l.source.channelId===o.id&&l.source.chatId);return a?.source.chatId?i=a.source.chatId:i=o.config?.userId,{id:o.id,name:o.name,platform:o.platform,status:o.status,chatId:i}});return c({channels:n})}),m("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.",xr,async()=>{let e=k(),t=A("running"),r=A("pending");return c({executionPool:{active:t.length,max:e.execution?.maxConcurrent??5,queued:r.length},timestamp:new Date().toISOString()})}),m("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.",Er,async e=>{let t=T(e.roleId);if(!t||t.status!=="active"){let g=G("active",20,0).filter(f=>f.source!=="system").map(f=>({id:f.id,name:f.name,allowedTools:f.allowedTools??[],capabilitySummary:ee(f)}));return c({error:`Role not found or not active: ${e.roleId}. Pick a roleId from the list below.`,availableRoles:g})}let r=Date.now(),n;if(e.delayMinutes!==void 0&&e.runAt!==void 0)return c({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 c({error:"Invalid ISO 8601 timestamp in runAt"})}else return c({error:"Provide either delayMinutes or runAt"});if(n<=r)return c({error:"Scheduled time must be in the future"});let o=10080*60*1e3;if(n-r>o)return c({error:"Schedule exceeds maximum of 7 days"});let i=w(),a=new Date(n).toISOString(),l=e.deliverTo?await P(e.deliverTo):void 0,u=e.reportTo?await P(e.reportTo):void 0;Ye({id:i,name:e.prompt.slice(0,80),description:`One-shot scheduled task: ${e.prompt.slice(0,200)}`,trigger:{type:"once",runAt:a},steps:[{id:"main",prompt:e.prompt}],rolePreference:e.roleId,config:{...k().defaults},tags:["scheduled","once"],enabled:!0,createdAt:r,deliverTo:l,reportTo:u});let{getBreeEngine:d}=await import("./bree-engine-25VACELK.js"),p=d();return p&&p.scheduleOnceJob(i),c({templateId:i,executeAt:a,prompt:e.prompt})}),m("cancel_scheduled_task","Cancel a previously scheduled one-shot task by its template ID. The task will not execute.",{templateId:s.string().describe("The template ID returned by schedule_task")},async e=>{let t=W(e.templateId);if(!t)return c({error:`Template not found: ${e.templateId}`});if(t.trigger.type!=="once")return c({error:"This is not a one-shot scheduled task. Use disable_template for recurring automations."});Qe(e.templateId);let{getBreeEngine:r}=await import("./bree-engine-25VACELK.js"),n=r();return n&&await n.unscheduleJob(e.templateId),c({cancelled:!0,templateId:e.templateId})}),m("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.",Cr,async e=>{let t=z(),r=C(),n=e.roleId?(()=>{let{getRoleWorkspacePath:o}=(V(),x(Ie)),{getRole:i}=(ae(),x(we)),{listInstalledPlugins:a}=(ye(),x(wt)),l=i(e.roleId);if(!l)return[];let u=o(l.name);return a({scope:"project",projectPath:u}).map(d=>d.id)})():[];return c({plugins:r.map(o=>({id:o.id,name:o.name,scope:o.scope,projectPath:o.projectPath,enabled:o.enabled,globalEnabled:t[o.id]??o.enabled,isInstalledInRole:n.includes(o.id),description:o.version?`v${o.version}`:void 0}))})}),m("install_plugin_for_role","Install a plugin into a role's workspace (project-scope). The plugin will be available when that role executes tasks.",Dr,async e=>{let{getRole:t}=(ae(),x(we)),{getRoleWorkspacePath:r}=(V(),x(Ie)),n=t(e.roleId);if(!n)return c({error:`Role not found: ${e.roleId}`});let o=r(n.name);try{return De(e.pluginId,"project",o),c({success:!0,roleId:e.roleId,pluginId:e.pluginId,scope:"project",cwd:o})}catch(i){return c({error:`Failed to install plugin: ${i}`})}}),m("uninstall_plugin_from_role","Uninstall a plugin from a role's workspace.",Ar,async e=>{let{getRole:t}=(ae(),x(we)),{getRoleWorkspacePath:r}=(V(),x(Ie)),n=t(e.roleId);if(!n)return c({error:`Role not found: ${e.roleId}`});let o=r(n.name);try{return Ae(e.pluginId,"project",o),c({success:!0,roleId:e.roleId,pluginId:e.pluginId})}catch(i){return c({error:`Failed to uninstall plugin: ${i}`})}}),m("bind_mcp_to_role","Bind an MCP server configuration to a role. The MCP server will be available to the role during task execution.",Nr,async e=>{let t=T(e.roleId);if(!t)return c({error:`Role not found: ${e.roleId}`});let n={...t.mcpServers??{},[e.mcpName]:e.mcpConfig};try{return F(e.roleId,{mcpServers:n}),le(t),c({success:!0,roleId:e.roleId,mcpName:e.mcpName,mcpServers:n})}catch(o){return c({error:`Failed to bind MCP server: ${o}`})}}),m("unbind_mcp_from_role","Remove an MCP server binding from a role.",jr,async e=>{let t=T(e.roleId);if(!t)return c({error:`Role not found: ${e.roleId}`});let r={...t.mcpServers??{}};if(!(e.mcpName in r))return c({error:`MCP server "${e.mcpName}" not bound to this role`});delete r[e.mcpName];try{return F(e.roleId,{mcpServers:r}),le(t),c({success:!0,roleId:e.roleId,mcpName:e.mcpName})}catch(n){return c({error:`Failed to unbind MCP server: ${n}`})}}),m("get_capabilities","Get a comprehensive overview of Adam's current capabilities: available roles and their tools, 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-7LSQ6OST.js"),t=k(),r=G(void 0,100,0),n=Re(),o=e(!0,100,0),i=A("running"),a=A("pending");return c({roles:{description:"Specialized worker identities \u2014 each has its own tools, MCP servers, plugins (skills/agents), and learned rules",active:r.filter(l=>l.status==="active"&&l.source!=="system").map(l=>{let u=Ne(l);return{name:l.name,tools:l.allowedTools??[],mcpServers:Object.keys(l.mcpServers??{}),channels:l.allowedChannels??[],capabilitySummary:ee(l,u),plugins:u.plugins.map(d=>({name:d.name,skills:d.skills.map(p=>p.name),agents:d.agents.map(p=>p.name)}))}}),retired:r.filter(l=>l.status==="retired").length,probation:r.filter(l=>l.status==="probation").length},channels:{description:"Send/receive messages via connected platforms",connected:n.filter(l=>l.enabled).map(l=>({name:l.name,platform:l.platform,status:l.status}))},plugins:{description:"Extensions that add capabilities to roles",installed:C().filter(l=>l.enabled).map(l=>({name:l.name,scope:l.scope,description:l.version?`v${l.version}`:void 0}))},automations:{description:"Recurring cron tasks and event-triggered templates",active:o.map(l=>({name:l.name,trigger:l.trigger}))},execution:{description:"Parallel task execution pool",maxConcurrent:t.execution?.maxConcurrent??5,running:i.length,queued:a.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"]})}),m("enable_plugin","Enable a globally installed plugin (makes it available to all roles).",$r,async e=>{try{return _t(e.pluginId),c({success:!0,pluginId:e.pluginId})}catch(t){return c({error:`Failed to enable plugin: ${t}`})}}),m("disable_plugin","Disable a globally installed plugin (removes it from all roles).",Ur,async e=>{try{return Mt(e.pluginId),c({success:!0,pluginId:e.pluginId})}catch(t){return c({error:`Failed to disable plugin: ${t}`})}}),m("install_plugin_for_user","Install a plugin globally for the current user (user-scope).",Or,async e=>{try{return De(e.pluginId,"user"),c({success:!0,pluginId:e.pluginId,scope:"user"})}catch(t){return c({error:`Failed to install plugin: ${t}`})}}),m("uninstall_plugin_for_user","Uninstall a globally installed plugin from the current user.",Fr,async e=>{try{return Ae(e.pluginId,"user"),c({success:!0,pluginId:e.pluginId})}catch(t){return c({error:`Failed to uninstall plugin: ${t}`})}}),m("browse_marketplace","Browse all available plugins from configured marketplaces (shows installed and available).",Gr,async()=>{try{let e=Rt(),t=C();return c({available:e,installed:t})}catch(e){return c({error:`Failed to browse marketplace: ${e}`})}}),m("list_marketplace_sources","List configured plugin marketplace sources.",Vr,async()=>{let e=Ce();return c({sources:e})}),m("get_plugin_detail","Get detailed manifest for an installed plugin (skills, agents, MCP servers, hooks).",Wr,async e=>{let t=Le(e.pluginId);if(!t)return c({error:`Plugin not found: ${e.pluginId}`});let r=Q(t.installPath);return c({id:t.id,name:t.name,version:t.version,scope:t.scope,projectPath:t.projectPath,enabled:t.enabled,manifest:r})}),m("scan_directory","Scan a directory for .claude/settings.json and return its plugin/MCP configuration.",Br,async e=>{let{getRole:t}=await import("./roles-SG2YAR64.js");if(!t(e.roleId))return c({error:`Role not found: ${e.roleId}`});try{let n=X(e.path);return c({roleId:e.roleId,path:e.path,config:n})}catch(n){return c({error:`Failed to scan directory: ${n}`})}}),m("cancel_task","Cancel a running or pending task by setting its status to 'cancelled'. Emits a task_status_change event.",Jr,async e=>{let t=v(e.taskId);if(!t)return c({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"}),c({success:!0,taskId:e.taskId,status:"cancelled"})}),m("view_task_logs","Retrieve step-by-step execution logs for a task.",qr,async e=>{let t=se(e.taskId,e.limit??20);return c({taskId:e.taskId,count:t.length,logs:t})}),m("delete_role","Delete a role by ID. This removes the role and its workspace.",Hr,async e=>T(e.roleId)?(Ue(e.roleId),c({success:!0,roleId:e.roleId})):c({error:`Role not found: ${e.roleId}`})),m("view_config","Get the current runtime configuration (mutable fields and restart-required fields).",Kr,async()=>{let{MUTABLE_PATHS:e,RESTART_REQUIRED_PATHS:t}=await import("./runtime-6UTYEONR.js"),r=k(),n={};try{let l=k().server?.port??7100,u=await fetch(`http://127.0.0.1:${l}/config`);u.ok&&(n=await u.json())}catch{}let o=[...e,...t],i=[...t],a={};for(let l of o){let u=l.split("."),d=r;for(let p of u)if(d&&typeof d=="object")d=d[p];else{d=void 0;break}a[l]={value:d,mutable:!t.includes(l)}}return c({config:a,mutable:[...e],restartRequired:[...t]})}),m("update_config","Update mutable runtime configuration fields. Returns partial-success: some fields may update while others return errors.",Yr,async e=>{let{isRestartRequiredPath:t}=await import("./runtime-6UTYEONR.js"),{setConfigValue:r}=await import("./config-WHXCZCI4.js"),n=je(e.updates,r);if(e.updates["logging.level"]&&Fe(e.updates["logging.level"]),n.updated.length>0){let{serverBus:o}=await import("./server-bus-GEGVMSCA.js");o.emit({type:"config_changed",changes:n.updated.map(i=>({path:i,value:e.updates[i]}))})}return c(n)}),m("list_memories","List memories stored under a specific role.",zr,async e=>{let t=qe(e.roleId,e.limit??20);return c({roleId:e.roleId,count:t.length,memories:t})}),m("update_template","Update a task template's fields (name, prompt, cron, enabled, etc.).",Qr,async e=>{let t=W(e.templateId);if(!t)return c({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:w(),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),ze(e.templateId,r),c({success:!0,templateId:e.templateId,updated:Object.keys(r)})}),m("delete_template","Delete a task template by ID.",Xr,async e=>W(e.templateId)?(Xe(e.templateId),c({success:!0,templateId:e.templateId})):c({error:`Template not found: ${e.templateId}`})),m("run_template","Trigger a template immediately (runs the webhook endpoint for its name).",Zr,async e=>{let t=W(e.templateId);if(!t)return c({error:`Template not found: ${e.templateId}`});try{let r=k().server?.port??7100,n=await fetch(`http://127.0.0.1:${r}/webhooks/${t.name}`,{method:"POST"}),o=await n.json();return n.ok?c({success:!0,templateId:e.templateId,templateName:t.name,response:o}):c({error:`Webhook failed: ${o.code??n.status} \u2014 ${o.message??""}`})}catch(r){return c({error:`Failed to trigger template: ${r}`})}}),m("list_delivery_rules","List delivery rules, optionally filtered by enabled status.",en,async e=>{let t=Me(e.enabled);return c({count:t.length,rules:t})}),m("create_delivery_rule","Create a new delivery rule for event-driven result routing.",tn,async e=>{let t=w(),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 tt(r),c({success:!0,ruleId:t,rule:r})}),m("delete_delivery_rule","Delete a delivery rule by ID.",rn,async e=>Me().find(n=>n.id===e.ruleId)?(rt(e.ruleId),c({success:!0,ruleId:e.ruleId})):c({error:`Delivery rule not found: ${e.ruleId}`})),m("list_strategies","List Thompson Sampling strategy populations for a role, or all strategies if roleId omitted.",nn,async e=>{let t;if(e.roleId)t=ct(e.roleId);else{let{getDb:r}=await import("./db-PNZ3UJOE.js");t=r().prepare("SELECT * FROM strategies ORDER BY created_at").all().map(o=>({id:o.id,roleId:o.role_id,name:o.name,taskType:o.task_type,createdAt:o.created_at,updatedAt:o.updated_at??void 0,promptTemplate:o.prompt_template??"",alpha:o.alpha,beta:o.beta,totalTrials:o.trials,avgReward:o.total_reward&&o.trials>0?o.total_reward/o.trials:void 0,enabled:o.enabled===1}))}return c({roleId:e.roleId??null,count:t.length,strategies:t})}),m("authorize_task_operation","Authorize a pending privilege escalation for a task. The paused operation will proceed.",{taskId:s.string(),operationId:s.string().optional().describe("ID of the specific operation. If omitted, authorizes the most recent pending operation."),scope:s.enum(["once","permanent"]).default("once").describe("'once' = this operation only. 'permanent' = auto-authorize matching patterns in the future.")},async e=>{let t=Se(e.taskId),r=e.operationId?t.find(o=>o.id===e.operationId):t.find(o=>o.status==="pending");return r?(new re().resolvePlanApproval(r.id,"allow",e.scope),c({success:!0,operationId:r.id,decision:"allow",scope:e.scope})):c({error:"No pending operation found for this task"})}),m("deny_task_operation","Deny a pending privilege escalation for a task. The paused operation will be rejected.",{taskId:s.string(),operationId:s.string().optional(),reason:s.string().optional().describe("Reason for denial, provided to the executor as feedback.")},async e=>{let t=Se(e.taskId),r=e.operationId?t.find(o=>o.id===e.operationId):t.find(o=>o.status==="pending");return r?(new re().resolvePlanApproval(r.id,"deny","once",e.reason),c({success:!0,operationId:r.id,decision:"deny"})):c({error:"No pending operation found for this task"})})];function Qo(){return Et.map(e=>e.name).sort().join(",")}function Xo(){return cr({name:"adam-tools",version:"1.0.0",tools:Et})}export{ho as a,re as b,z as c,Q as d,C as e,Le as f,Ce as g,X as h,ye as i,pn as j,mn as k,ot as l,Un as m,ct as n,S as o,bt as p,Rt as q,De as r,Ae as s,_t as t,Mt as u,uo as v,ar as w,Qo as x,Xo as y};
@@ -1 +1 @@
1
- import{b as R}from"./chunk-LBLERTM4.js";import{f as E}from"./chunk-KICPHTI2.js";import{b as v}from"./chunk-5ASEAZCR.js";import{e as m}from"./chunk-742NWPTQ.js";import{b as x}from"./chunk-PQ7KPALO.js";import{a as w,b as k,c as o,d as h,e as T,f as P,g as S}from"./chunk-FDWW245P.js";import{b as g}from"./chunk-L7426WNY.js";import{a as f}from"./chunk-L7JP7DUO.js";import{c as D}from"./chunk-3DAK2XWP.js";import{v4 as C}from"uuid";var s=D("admin"),y=new Map,u=null,p=null,c=null,I=class{constructor(){f.on("task_status_change",e=>{(e.newStatus==="completed"||e.newStatus==="failed")&&this.handleTaskStatusChange(e.taskId,e.newStatus).catch(n=>{s.error({taskId:e.taskId,error:n},"Delivery processing failed")})}),f.on("plan_approval_request",e=>{this.handlePlanApprovalRequest(e.taskId,e.planId,e.plan).catch(n=>{s.error({taskId:e.taskId,error:n},"Delivery processing failed (plan_approval)")})}),s.info("DeliveryEngine initialized")}async handlePlanApprovalRequest(e,n,r){let t=g(e),i=this.getSourceChannelForTask(e);if(i){let d=JSON.stringify(r).slice(0,500),{sendApprovalToChannel:b}=await import("./approval-handler-SSKO2IGC.js");await b(i.channelId,i.chatId,n,e,d)}let a=`Plan approval requested for task ${e}: ${JSON.stringify(r).slice(0,500)}`;await this.matchAndDeliver("plan_approval_request",{templateId:t?.templateId,roleId:t?.roleId,prompt:t?.prompt,taskStatus:"pending"},a,e)}getSourceChannelForTask(e){try{let n=m(e);if(!n)return null;let r=v(n.sessionId);return!r||r.source.type!=="channel"||!r.source.channelId||!r.source.chatId?null:{channelId:r.source.channelId,chatId:r.source.chatId}}catch{return null}}async handleTaskStatusChange(e,n){let r=g(e);if(!r)return;let t={templateId:r.templateId,roleId:r.roleId,prompt:r.prompt,taskStatus:n},i=n==="completed"?"task_complete":"task_error",a=r.result??r.error??"";await this.matchAndDeliver(i,t,a,e)}async matchAndDeliver(e,n,r,t){let i=E(e,n);if(i.length!==0){s.debug({eventType:e,ruleCount:i.length,taskId:t},"Matched delivery rules");for(let a of i){if(!this.checkRateLimit(a)){s.warn({ruleId:a.id,maxPerMinute:a.maxPerMinute},"Delivery rate limit exceeded, skipping");continue}if(a.skipOriginChannel&&a.target.type==="channel"&&t&&this.isOriginChannel(t,a.target))continue;let d={id:C(),ruleId:a.id,taskId:t,status:"pending",target:a.target,content:r,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+w,source:"rule"};k(d),await this.attemptDelivery(d,a)}}}async attemptDeliveryPublic(e,n){return this.attemptDelivery(e,n)}async attemptDelivery(e,n){let r=R();try{if(e.target.type==="channel"){let t=e.target.chatId;!t&&e.target.channelId&&(t=x(e.target.channelId)?.config?.userId);let i=await r.send({taskId:e.taskId,channelId:e.target.channelId,chatId:t,content:e.content,messageType:"deliver"});i.success?(h(e.id),s.info({entryId:e.id,ruleId:n.id,targetType:"channel"},"Delivery successful")):o(e.id,"failed",i.error??"Gateway returned failure")}else if(e.target.type==="webhook"){let t=await r.send({taskId:e.taskId,webhookUrl:e.target.webhookUrl,content:e.content,messageType:"deliver"});t.success?(h(e.id),s.info({entryId:e.id,ruleId:n.id,targetType:"webhook"},"Webhook delivery successful")):o(e.id,"failed",t.error??"Gateway returned failure")}}catch(t){let i=t instanceof Error?t.message:String(t);o(e.id,"failed",i),s.warn({entryId:e.id,error:i},"Delivery attempt failed")}}checkRateLimit(e){let n=Date.now(),r=6e4,t=y.get(e.id);t||(t=[],y.set(e.id,t));let i=n-r;for(;t.length>0&&t[0]<i;)t.shift();return t.length>=e.maxPerMinute?!1:(t.push(n),!0)}isOriginChannel(e,n){try{if(n.type!=="channel"||!n.channelId)return!1;let r=m(e);if(!r)return!1;let t=v(r.sessionId);return t?t.source.type==="channel"&&t.source.channelId===n.channelId&&t.source.chatId===n.chatId:!1}catch{return!1}}async retryPending(){let e=T("rule",50),n=P("rule",50),r=[...e,...n];if(r.length!==0){s.debug({count:r.length},"Retrying pending/failed deliveries");for(let t of r){if(t.attempts>=3){o(t.id,"failed","Max retries (3) exceeded");continue}let i={id:t.ruleId??"retry-synthetic",eventType:"*",matchCriteria:{},target:t.target,maxPerMinute:5,skipOriginChannel:!0,enabled:!0,createdAt:0};await this.attemptDelivery(t,i)}}}};function N(){return c}function U(){c||(c=new I,u=setInterval(()=>{c?.retryPending().catch(l=>{s.error({error:l},"Delivery retry scan failed")})},6e4),p=setInterval(()=>{try{let l=S();l>0&&s.info({cleaned:l},"Expired delivery log entries cleaned up")}catch(l){s.error({error:l},"Delivery cleanup failed")}},36e5),s.info("DeliveryEngine started with retry (60s) and cleanup (1h) timers"))}function W(){u&&(clearInterval(u),u=null),p&&(clearInterval(p),p=null),c=null,y.clear(),s.info("DeliveryEngine stopped")}export{I as a,N as b,U as c,W as d};
1
+ import{b as R}from"./chunk-NXTTKAQX.js";import{f as E}from"./chunk-KICPHTI2.js";import{b as v}from"./chunk-5ASEAZCR.js";import{e as m}from"./chunk-742NWPTQ.js";import{b as x}from"./chunk-PQ7KPALO.js";import{a as w,b as k,c as o,d as h,e as T,f as P,g as S}from"./chunk-FDWW245P.js";import{b as g}from"./chunk-L7426WNY.js";import{a as f}from"./chunk-L7JP7DUO.js";import{c as D}from"./chunk-3DAK2XWP.js";import{v4 as C}from"uuid";var s=D("admin"),y=new Map,u=null,p=null,c=null,I=class{constructor(){f.on("task_status_change",e=>{(e.newStatus==="completed"||e.newStatus==="failed")&&this.handleTaskStatusChange(e.taskId,e.newStatus).catch(n=>{s.error({taskId:e.taskId,error:n},"Delivery processing failed")})}),f.on("plan_approval_request",e=>{this.handlePlanApprovalRequest(e.taskId,e.planId,e.plan).catch(n=>{s.error({taskId:e.taskId,error:n},"Delivery processing failed (plan_approval)")})}),s.info("DeliveryEngine initialized")}async handlePlanApprovalRequest(e,n,r){let t=g(e),i=this.getSourceChannelForTask(e);if(i){let d=JSON.stringify(r).slice(0,500),{sendApprovalToChannel:b}=await import("./approval-handler-HK7GQPHU.js");await b(i.channelId,i.chatId,n,e,d)}let a=`Plan approval requested for task ${e}: ${JSON.stringify(r).slice(0,500)}`;await this.matchAndDeliver("plan_approval_request",{templateId:t?.templateId,roleId:t?.roleId,prompt:t?.prompt,taskStatus:"pending"},a,e)}getSourceChannelForTask(e){try{let n=m(e);if(!n)return null;let r=v(n.sessionId);return!r||r.source.type!=="channel"||!r.source.channelId||!r.source.chatId?null:{channelId:r.source.channelId,chatId:r.source.chatId}}catch{return null}}async handleTaskStatusChange(e,n){let r=g(e);if(!r)return;let t={templateId:r.templateId,roleId:r.roleId,prompt:r.prompt,taskStatus:n},i=n==="completed"?"task_complete":"task_error",a=r.result??r.error??"";await this.matchAndDeliver(i,t,a,e)}async matchAndDeliver(e,n,r,t){let i=E(e,n);if(i.length!==0){s.debug({eventType:e,ruleCount:i.length,taskId:t},"Matched delivery rules");for(let a of i){if(!this.checkRateLimit(a)){s.warn({ruleId:a.id,maxPerMinute:a.maxPerMinute},"Delivery rate limit exceeded, skipping");continue}if(a.skipOriginChannel&&a.target.type==="channel"&&t&&this.isOriginChannel(t,a.target))continue;let d={id:C(),ruleId:a.id,taskId:t,status:"pending",target:a.target,content:r,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+w,source:"rule"};k(d),await this.attemptDelivery(d,a)}}}async attemptDeliveryPublic(e,n){return this.attemptDelivery(e,n)}async attemptDelivery(e,n){let r=R();try{if(e.target.type==="channel"){let t=e.target.chatId;!t&&e.target.channelId&&(t=x(e.target.channelId)?.config?.userId);let i=await r.send({taskId:e.taskId,channelId:e.target.channelId,chatId:t,content:e.content,messageType:"deliver"});i.success?(h(e.id),s.info({entryId:e.id,ruleId:n.id,targetType:"channel"},"Delivery successful")):o(e.id,"failed",i.error??"Gateway returned failure")}else if(e.target.type==="webhook"){let t=await r.send({taskId:e.taskId,webhookUrl:e.target.webhookUrl,content:e.content,messageType:"deliver"});t.success?(h(e.id),s.info({entryId:e.id,ruleId:n.id,targetType:"webhook"},"Webhook delivery successful")):o(e.id,"failed",t.error??"Gateway returned failure")}}catch(t){let i=t instanceof Error?t.message:String(t);o(e.id,"failed",i),s.warn({entryId:e.id,error:i},"Delivery attempt failed")}}checkRateLimit(e){let n=Date.now(),r=6e4,t=y.get(e.id);t||(t=[],y.set(e.id,t));let i=n-r;for(;t.length>0&&t[0]<i;)t.shift();return t.length>=e.maxPerMinute?!1:(t.push(n),!0)}isOriginChannel(e,n){try{if(n.type!=="channel"||!n.channelId)return!1;let r=m(e);if(!r)return!1;let t=v(r.sessionId);return t?t.source.type==="channel"&&t.source.channelId===n.channelId&&(!n.chatId||t.source.chatId===n.chatId):!1}catch{return!1}}async retryPending(){let e=T("rule",50),n=P("rule",50),r=[...e,...n];if(r.length!==0){s.debug({count:r.length},"Retrying pending/failed deliveries");for(let t of r){if(t.attempts>=3){o(t.id,"failed","Max retries (3) exceeded");continue}let i={id:t.ruleId??"retry-synthetic",eventType:"*",matchCriteria:{},target:t.target,maxPerMinute:5,skipOriginChannel:!0,enabled:!0,createdAt:0};await this.attemptDelivery(t,i)}}}};function N(){return c}function U(){c||(c=new I,u=setInterval(()=>{c?.retryPending().catch(l=>{s.error({error:l},"Delivery retry scan failed")})},6e4),p=setInterval(()=>{try{let l=S();l>0&&s.info({cleaned:l},"Expired delivery log entries cleaned up")}catch(l){s.error({error:l},"Delivery cleanup failed")}},36e5),s.info("DeliveryEngine started with retry (60s) and cleanup (1h) timers"))}function W(){u&&(clearInterval(u),u=null),p&&(clearInterval(p),p=null),c=null,y.clear(),s.info("DeliveryEngine stopped")}export{I as a,N as b,U as c,W as d};
@@ -0,0 +1,3 @@
1
+ import{b as C}from"./chunk-PQ7KPALO.js";import{b as D,c as f,d as w}from"./chunk-FDWW245P.js";import{a as p}from"./chunk-L7JP7DUO.js";import{c as M}from"./chunk-3DAK2XWP.js";function O(s,c,n){switch(c){case"wechat":return $(s);case"telegram":return s;case"slack":return U(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
+
3
+ `).trim()}function U(s){return s.replace(/\*\*(.+?)\*\*/g,"*$1*").replace(/\[([^\]]+)\]\(([^)]+)\)/g,"<$2|$1>")}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-JEBBMFUQ.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 P(){return _||(_=new v),_}function K(s){return P().isRecentlySent(s)}export{v as a,P as b,K as c};
@@ -0,0 +1 @@
1
+ import{f as se}from"./chunk-742NWPTQ.js";import{a as oe,b as _,c as G,d as ae,e as de}from"./chunk-PQ7KPALO.js";import{c as f}from"./chunk-3DAK2XWP.js";import{z as g}from"zod/v4";import{v4 as St}from"uuid";import{randomUUID as me}from"crypto";import Ge from"crypto";var ce="1.0.0",A="";function Qe(e){let t=e.split(".").map(i=>parseInt(i,10)),r=t[0]??0,s=t[1]??0,n=t[2]??0;return(r&255)<<16|(s&255)<<8|n&255}var K=Qe(ce),Ke=35e3,le=15e3,He=1e4;function v(){return{channel_version:ce}}function Xe(e){return e.endsWith("/")?e:`${e}/`}function Je(){let e=Ge.randomBytes(4).readUInt32BE(0);return Buffer.from(String(e),"utf-8").toString("base64")}function Ye(e){let t={"Content-Type":"application/json",AuthorizationType:"ilink_bot_token","Content-Length":String(Buffer.byteLength(e.body,"utf-8")),"X-WECHAT-UIN":Je(),"iLink-App-Id":A,"iLink-App-ClientVersion":String(K)};return e.token?.trim()&&(t.Authorization=`Bearer ${e.token.trim()}`),e.routeTag&&(t.SKRouteTag=e.routeTag),t}async function O(e){let t=Xe(e.baseUrl),r=new URL(e.endpoint,t),s=Ye({token:e.token,routeTag:e.routeTag,body:e.body}),n=new AbortController,i=setTimeout(()=>n.abort(),e.timeoutMs);try{let o=await fetch(r.toString(),{method:"POST",headers:s,body:e.body,signal:n.signal});clearTimeout(i);let a=await o.text();if(!o.ok)throw new Error(`${e.label} ${o.status}: ${a}`);return a}catch(o){throw clearTimeout(i),o}}async function ue(e){let t=e.timeoutMs??Ke;try{let r=await O({baseUrl:e.baseUrl,endpoint:"ilink/bot/getupdates",body:JSON.stringify({get_updates_buf:e.get_updates_buf??"",base_info:v()}),token:e.token,routeTag:e.routeTag,timeoutMs:t,label:"getUpdates"});return JSON.parse(r)}catch(r){if(r instanceof Error&&r.name==="AbortError")return{ret:0,msgs:[],get_updates_buf:e.get_updates_buf};throw r}}var Ze=new Set([-2,-3]),Q=3,et=1e3;async function N(e){let t=(await import("./logger-BEG4WFIM.js")).getLogger("channels");for(let r=1;r<=Q;r++){let s=await O({baseUrl:e.baseUrl,endpoint:"ilink/bot/sendmessage",body:JSON.stringify({...e.body,base_info:v()}),token:e.token,routeTag:e.routeTag,timeoutMs:e.timeoutMs??le,label:"sendMessage"});t.info({status:200,responseBody:s.slice(0,300)},"apiFetch sendMessage response");try{let n=JSON.parse(s);if(n.ret&&n.ret!==0){if(Ze.has(n.ret)&&r<Q){t.warn({ret:n.ret,attempt:r,maxRetries:Q},"sendMessage: transient iLink error, retrying"),await new Promise(i=>setTimeout(i,et*r));continue}throw t.error({ret:n.ret,errmsg:n.errmsg,attempt:r},"sendMessage: iLink API returned non-zero ret"),new Error(`sendMessage failed: iLink ret=${n.ret}${n.errmsg?` errmsg=${n.errmsg}`:""}`)}}catch(n){if(n instanceof SyntaxError)t.warn({rawText:s.slice(0,200),attempt:r},"sendMessage: non-JSON response, treating as success");else throw n}return}}async function ge(e){await O({baseUrl:e.baseUrl,endpoint:"ilink/bot/sendtyping",body:JSON.stringify({...e.body,base_info:v()}),token:e.token,routeTag:e.routeTag,timeoutMs:e.timeoutMs??He,label:"sendTyping"})}async function pe(e){let t=await O({baseUrl:e.baseUrl,endpoint:"ilink/bot/getuploadurl",body:JSON.stringify({filekey:e.filekey,media_type:e.media_type,to_user_id:e.to_user_id,rawsize:e.rawsize,rawfilemd5:e.rawfilemd5,filesize:e.filesize,thumb_rawsize:e.thumb_rawsize,thumb_rawfilemd5:e.thumb_rawfilemd5,thumb_filesize:e.thumb_filesize,no_need_thumb:e.no_need_thumb,aeskey:e.aeskey,base_info:v()}),token:e.token,routeTag:e.routeTag,timeoutMs:e.timeoutMs??le,label:"getUploadUrl"});return JSON.parse(t)}var tt=5*6e4,nt=35e3,fe="3",h=new Map;function H(e){return Date.now()-e.startedAt<tt}function rt(){for(let[e,t]of h)H(t)||h.delete(e)}async function ye(e,t,r){let s=e.endsWith("/")?e:`${e}/`,n=new URL(`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(t)}`,s),i={"iLink-App-Id":A};r&&(i.SKRouteTag=r);let o=await fetch(n.toString(),{headers:i});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 it(e,t,r){let s=e.endsWith("/")?e:`${e}/`,n=new URL(`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(t)}`,s),i={"iLink-App-Id":A,"iLink-App-ClientVersion":String(K)};r&&(i.SKRouteTag=r);let o=new AbortController,a=setTimeout(()=>o.abort(),nt);try{let c=await fetch(n.toString(),{headers:i,signal:o.signal});clearTimeout(a);let l=await c.text();if(!c.ok)throw new Error(`Failed to poll QR status: ${c.status} ${c.statusText}`);return JSON.parse(l)}catch(c){if(clearTimeout(a),c instanceof Error&&c.name==="AbortError")return{status:"wait"};throw c}}async function he(e){let t=e.accountId||me();rt();let r=h.get(t);if(!e.force&&r&&H(r)&&r.qrcodeUrl)return{qrcodeUrl:r.qrcodeUrl,message:"QR code ready. Scan with WeChat.",sessionKey:t};if(!e.apiBaseUrl)return{message:"No baseUrl configured for this WeChat channel.",sessionKey:t};try{let s=e.botType||fe,n=await ye(e.apiBaseUrl,s,e.routeTag),i={sessionKey:t,id:me(),qrcode:n.qrcode,qrcodeUrl:n.qrcode_img_content,startedAt:Date.now()};return h.set(t,i),{qrcodeUrl:n.qrcode_img_content,message:"Scan the QR code with WeChat to connect.",sessionKey:t}}catch(s){return{message:`Failed to start login: ${String(s)}`,sessionKey:t}}}var st=3;async function be(e){let t=h.get(e.sessionKey);if(!t)return{connected:!1,message:"No active login session. Start QR login first."};if(!H(t))return h.delete(e.sessionKey),{connected:!1,message:"QR code expired. Please start again."};let r=Math.max(e.timeoutMs??48e4,1e3),s=Date.now()+r,n=1;for(;Date.now()<s;){try{let i=await it(e.apiBaseUrl,t.qrcode,e.routeTag);switch(t.status=i.status,i.status){case"wait":break;case"scaned":break;case"expired":{if(n++,n>st)return h.delete(e.sessionKey),{connected:!1,message:"Login timeout: QR expired multiple times."};try{let o=e.botType||fe,a=await ye(e.apiBaseUrl,o,e.routeTag);t.qrcode=a.qrcode,t.qrcodeUrl=a.qrcode_img_content,t.startedAt=Date.now()}catch(o){return h.delete(e.sessionKey),{connected:!1,message:`QR refresh failed: ${String(o)}`}}break}case"confirmed":return i.ilink_bot_id?(h.delete(e.sessionKey),{connected:!0,botToken:i.bot_token,accountId:i.ilink_bot_id,baseUrl:i.baseurl,userId:i.ilink_user_id,message:"Connected to WeChat successfully!"}):(h.delete(e.sessionKey),{connected:!1,message:"Login failed: server did not return bot ID."})}}catch(i){return h.delete(e.sessionKey),{connected:!1,message:`Login failed: ${String(i)}`}}await new Promise(i=>setTimeout(i,1e3))}return h.delete(e.sessionKey),{connected:!1,message:"Login timeout. Please try again."}}import C,{promises as P}from"fs";import x from"path";import{homedir as ne}from"os";var F={IMAGE:1,VIDEO:2,FILE:3,VOICE:4},$={NONE:0,USER:1,BOT:2},m={NONE:0,TEXT:1,IMAGE:2,VOICE:3,FILE:4,VIDEO:5},L={NEW:0,GENERATING:1,FINISH:2},_e={TYPING:1,CANCEL:2};var ot=f("channels"),X=-14,D=3600*1e3,M=new Map;function we(e){let t=Date.now()+D;M.set(e,t),ot.info({channelId:e},`Session paused until ${new Date(t).toISOString()} (${D/1e3}s)`)}function B(e){let t=M.get(e);return t===void 0?!1:Date.now()>=t?(M.delete(e),!1):!0}function xe(e){let t=M.get(e);if(t===void 0)return 0;let r=t-Date.now();return r<=0?(M.delete(e),0):r}function Ie(e){M.delete(e)}import Ae from"fs";import ve from"path";import{homedir as mt}from"os";import{createCipheriv as at,createDecipheriv as dt}from"crypto";function Te(e,t){let r=at("aes-128-ecb",t,null);return Buffer.concat([r.update(e),r.final()])}function Ue(e,t){let r=dt("aes-128-ecb",t,null);return Buffer.concat([r.update(e),r.final()])}function ke(e){return Math.ceil((e+1)/16)*16}function J(e,t){return`${t}/download?encrypted_query_param=${encodeURIComponent(e)}`}function Ce(e){return`${e.cdnBaseUrl}/upload?encrypted_query_param=${encodeURIComponent(e.uploadParam)}&filekey=${encodeURIComponent(e.filekey)}`}var Qt=f("channels");function ct(e){let t=Buffer.from(e,"base64");if(t.length===16)return t;if(t.length===32&&/^[0-9a-fA-F]{32}$/.test(t.toString("ascii")))return Buffer.from(t.toString("ascii"),"hex");throw new Error(`aes_key must decode to 16 raw bytes or 32-char hex, got ${t.length} bytes`)}async function Me(e){let t=await fetch(e);if(!t.ok)throw new Error(`CDN download ${t.status} ${t.statusText}`);return Buffer.from(await t.arrayBuffer())}async function R(e){let{encryptQueryParam:t,aesKeyBase64:r,cdnBaseUrl:s,fullUrl:n}=e,i=ct(r),o=n?.trim()||(t?J(t,s):null);if(!o)throw new Error("CDN download: need full_url or encrypt_query_param");let a=await Me(o);return Ue(a,i)}async function Re(e){let{encryptQueryParam:t,cdnBaseUrl:r,fullUrl:s}=e,n=s?.trim()||(t?J(t,r):null);if(!n)throw new Error("CDN download: need full_url or encrypt_query_param");return Me(n)}var W=f("channels"),Ee=24e3;function lt(e,t){let r=e.byteLength,s=44+r,n=Buffer.allocUnsafe(s),i=0;return n.write("RIFF",i),i+=4,n.writeUInt32LE(s-8,i),i+=4,n.write("WAVE",i),i+=4,n.write("fmt ",i),i+=4,n.writeUInt32LE(16,i),i+=4,n.writeUInt16LE(1,i),i+=2,n.writeUInt16LE(1,i),i+=2,n.writeUInt32LE(t,i),i+=4,n.writeUInt32LE(t*2,i),i+=4,n.writeUInt16LE(2,i),i+=2,n.writeUInt16LE(16,i),i+=2,n.write("data",i),i+=4,n.writeUInt32LE(r,i),i+=4,Buffer.from(e.buffer,e.byteOffset,e.byteLength).copy(n,i),n}async function Se(e){try{let{decode:t}=await import("silk-wasm");W.debug(`silkToWav: decoding ${e.length} bytes of SILK`);let r=await t(e,Ee);W.debug(`silkToWav: decoded duration=${r.duration}ms pcmBytes=${r.data.byteLength}`);let s=lt(r.data,Ee);return W.debug(`silkToWav: WAV size=${s.length}`),s}catch(t){return W.warn(`silkToWav: transcode failed, will use raw silk err=${String(t)}`),null}}import ut from"path";var gt={".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"},pt={"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 q(e){let t=ut.extname(e).toLowerCase();return gt[t]??"application/octet-stream"}function Pe(e){let t=e.split(";")[0].trim().toLowerCase();return pt[t]??".bin"}var k=f("channels"),Oe=100*1024*1024;function ft(e){return Pe(e)??".bin"}async function E(e,t,r,s,n=Oe,i){if(e.length>n)throw new Error(`Media too large: ${e.length} bytes exceeds ${n} bytes`);let o=ve.join(mt(),".adam","wechat","media",s,r);await Ae.promises.mkdir(o,{recursive:!0});let a;if(i&&/^[a-zA-Z0-9._-]+$/.test(i))a=i;else{let l=t?ft(t):".bin",d=Date.now(),u=Math.random().toString(36).slice(2,7);a=`${d}-${u}${l}`}let c=ve.join(o,a);return await Ae.promises.writeFile(c,e),k.debug(`saveMedia: saved ${e.length} bytes to ${c}`),c}async function Ne(e,t){let{cdnBaseUrl:r,channelId:s}=t;if(e.type===m.IMAGE){let n=e.image_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url)return null;let i=n.aeskey?Buffer.from(n.aeskey,"hex").toString("base64"):n.media?.aes_key;try{let o=i?await R({encryptQueryParam:n.media?.encrypt_query_param,aesKeyBase64:i,cdnBaseUrl:r,fullUrl:n.media?.full_url}):await Re({encryptQueryParam:n.media?.encrypt_query_param,cdnBaseUrl:r,fullUrl:n.media?.full_url});return{path:await E(o,"image/png","inbound",s),mimeType:"image/png",type:"image"}}catch(o){return k.error({channelId:s},`Image download/decrypt failed: ${String(o)}`),null}}if(e.type===m.VOICE){let n=e.voice_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let i=await R({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:r,fullUrl:n.media.full_url}),o=await Se(i);if(o){let a=await E(o,"audio/wav","inbound",s);return k.debug(`Voice: saved WAV to ${a}`),{path:a,mimeType:"audio/wav",type:"audio"}}else{let a=await E(i,"audio/silk","inbound",s);return k.debug(`Voice: silk transcode unavailable, saved raw SILK to ${a}`),{path:a,mimeType:"audio/silk",type:"audio"}}}catch(i){return k.error({channelId:s},`Voice download/transcode failed: ${String(i)}`),null}}if(e.type===m.FILE){let n=e.file_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let i=await R({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:r,fullUrl:n.media.full_url}),o=q(n.file_name??"file.bin");return{path:await E(i,o,"inbound",s,Oe,n.file_name),mimeType:o,type:"file"}}catch(i){return k.error({channelId:s},`File download failed: ${String(i)}`),null}}if(e.type===m.VIDEO){let n=e.video_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let i=await R({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:r,fullUrl:n.media.full_url});return{path:await E(i,"video/mp4","inbound",s),mimeType:"video/mp4",type:"video"}}catch(i){return k.error({channelId:s},`Video download failed: ${String(i)}`),null}}return null}import Le from"path";import Y from"crypto";import yt from"fs/promises";var T=f("channels"),j=3;async function ht(e){let{buf:t,uploadFullUrl:r,uploadParam:s,filekey:n,cdnBaseUrl:i,label:o,aeskey:a}=e,c=Te(t,a),l=r?.trim(),d;if(l)d=l;else if(s)d=Ce({cdnBaseUrl:i,uploadParam:s,filekey:n});else throw new Error(`${o}: CDN upload URL missing (need upload_full_url or upload_param)`);T.debug(`${o}: CDN POST url=${d} ciphertextSize=${c.length}`);let u,y;for(let b=1;b<=j;b++)try{let p=await fetch(d,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:new Uint8Array(c)});if(p.status>=400&&p.status<500){let I=p.headers.get("x-error-message")??await p.text();throw T.error(`${o}: CDN client error attempt=${b} status=${p.status} errMsg=${I}`),new Error(`CDN upload client error ${p.status}: ${I}`)}if(p.status!==200){let I=p.headers.get("x-error-message")??`status ${p.status}`;throw T.error(`${o}: CDN server error attempt=${b} status=${p.status} errMsg=${I}`),new Error(`CDN upload server error: ${I}`)}if(u=p.headers.get("x-encrypted-param")??void 0,!u)throw T.error(`${o}: CDN response missing x-encrypted-param header attempt=${b}`),new Error("CDN upload response missing x-encrypted-param header");T.debug(`${o}: CDN upload success attempt=${b}`);break}catch(p){if(y=p,p instanceof Error&&p.message.includes("client error"))throw p;b<j?T.warn(`${o}: attempt ${b} failed, retrying... err=${String(p)}`):T.error(`${o}: all ${j} attempts failed err=${String(p)}`)}if(!u)throw y instanceof Error?y:new Error(`CDN upload failed after ${j} attempts`);return{downloadParam:u}}async function Z(e){let{filePath:t,toUserId:r,opts:s,cdnBaseUrl:n,mediaType:i,label:o}=e,a=await yt.readFile(t),c=a.length,l=Y.createHash("md5").update(a).digest("hex"),d=ke(c),u=Y.randomBytes(16).toString("hex"),y=Y.randomBytes(16);T.debug(`${o}: file=${t} rawsize=${c} filesize=${d} md5=${l} filekey=${u}`);let b=await pe({...s,filekey:u,media_type:i,to_user_id:r,rawsize:c,rawfilemd5:l,filesize:d,no_need_thumb:!0,aeskey:y.toString("hex")}),p=b.upload_full_url?.trim(),I=b.upload_param;if(!p&&!I)throw new Error(`${o}: getUploadUrl returned no upload URL (need upload_full_url or upload_param)`);let{downloadParam:ze}=await ht({buf:a,uploadFullUrl:p||void 0,uploadParam:I??void 0,filekey:u,cdnBaseUrl:n,aeskey:y,label:`${o}[orig filekey=${u}]`});return{filekey:u,downloadEncryptedQueryParam:ze,aeskey:y.toString("hex"),fileSize:c,fileSizeCiphertext:d}}async function Fe(e){return Z({...e,mediaType:F.IMAGE,label:"uploadImageToWeixin"})}async function $e(e){return Z({...e,mediaType:F.VIDEO,label:"uploadVideoToWeixin"})}async function ee(e){return Z({...e,mediaType:F.FILE,label:"uploadFileAttachmentToWeixin"})}var S=f("channels");function bt(){return`adam-wechat-${Date.now()}-${Math.random().toString(36).slice(2,7)}`}function _t(e){let t=e;return t=t.replace(/```[^\n]*\n?([\s\S]*?)```/g,(r,s)=>s.trim()),t=t.replace(/!\[[^\]]*\]\([^)]*\)/g,""),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/^\|[\s:|-]+\|$/gm,""),t=t.replace(/^\|(.+)\|$/gm,(r,s)=>s.split("|").map(n=>n.trim()).join(" ")),t}async function te(e){let{to:t,text:r,mediaItem:s,opts:n,label:i}=e,o=[],a=_t(r);a&&o.push({type:m.TEXT,text_item:{text:a}}),o.push(s);let c="";for(let l of o){c=bt();let d={msg:{from_user_id:"",to_user_id:t,client_id:c,message_type:$.BOT,message_state:L.FINISH,item_list:[l],context_token:n.contextToken}};await N({baseUrl:n.baseUrl,token:n.token,routeTag:n.routeTag,body:d})}return S.debug(`${i}: sent to=${t} messageId=${c}`),{messageId:c}}async function wt(e){let{to:t,text:r,uploaded:s,opts:n}=e,i={type:m.IMAGE,image_item:{media:{encrypt_query_param:s.downloadEncryptedQueryParam,aes_key:Buffer.from(s.aeskey).toString("base64"),encrypt_type:1},mid_size:s.fileSizeCiphertext}};return te({to:t,text:r,mediaItem:i,opts:n,label:"sendImageMessage"})}async function xt(e){let{to:t,text:r,uploaded:s,opts:n}=e,i={type:m.VIDEO,video_item:{media:{encrypt_query_param:s.downloadEncryptedQueryParam,aes_key:Buffer.from(s.aeskey).toString("base64"),encrypt_type:1},video_size:s.fileSizeCiphertext}};return te({to:t,text:r,mediaItem:i,opts:n,label:"sendVideoMessage"})}async function De(e){let{to:t,text:r,fileName:s,uploaded:n,opts:i}=e,o={type:m.FILE,file_item:{media:{encrypt_query_param:n.downloadEncryptedQueryParam,aes_key:Buffer.from(n.aeskey).toString("base64"),encrypt_type:1},file_name:s,len:String(n.fileSize)}};return te({to:t,text:r,mediaItem:o,opts:i,label:"sendFileMessage"})}async function Be(e){let{filePath:t,to:r,text:s,opts:n,cdnBaseUrl:i}=e,o=q(t),a={baseUrl:n.baseUrl,token:n.token,routeTag:n.routeTag};if(o.startsWith("video/")){S.debug(`sendWeixinMediaFile: uploading video filePath=${t} to=${r}`);let d=await $e({filePath:t,toUserId:r,opts:a,cdnBaseUrl:i});return xt({to:r,text:s,uploaded:d,opts:n})}if(o.startsWith("image/")){S.debug(`sendWeixinMediaFile: uploading image filePath=${t} to=${r}`);let d=await Fe({filePath:t,toUserId:r,opts:a,cdnBaseUrl:i});return wt({to:r,text:s,uploaded:d,opts:n})}if(o.startsWith("audio/")){let d=Le.basename(t);S.debug(`sendWeixinMediaFile: uploading audio as file filePath=${t} name=${d} to=${r}`);let u=await ee({filePath:t,fileName:d,toUserId:r,opts:a,cdnBaseUrl:i});return De({to:r,text:s,fileName:d,uploaded:u,opts:n})}let c=Le.basename(t);S.debug(`sendWeixinMediaFile: uploading file attachment filePath=${t} name=${c} to=${r}`);let l=await ee({filePath:t,fileName:c,toUserId:r,opts:a,cdnBaseUrl:i});return De({to:r,text:s,fileName:c,uploaded:l,opts:n})}var w=f("channels"),We="https://novac2c.cdn.weixin.qq.com/c2c",re=new Map;function je(e){return x.join(ne(),".adam","wechat",`${e}.context-tokens.json`)}function It(e){let t=je(e);try{let r=C.readFileSync(t,"utf-8"),s=JSON.parse(r);for(let[n,i]of Object.entries(s))typeof i=="string"&&i&&re.set(`${e}:${n}`,i);w.debug({channelId:e,count:Object.keys(s).length},"Restored context tokens from disk")}catch{}}function Tt(e,t,r){let s=je(e);try{let n={};try{let o=C.readFileSync(s,"utf-8");n=JSON.parse(o)}catch{}n[t]=r;let i=x.dirname(s);C.mkdirSync(i,{recursive:!0}),C.writeFileSync(s,JSON.stringify(n),"utf-8")}catch(n){w.warn({channelId:e,userId:t},`Failed to persist context token: ${String(n)}`)}}function Ut(e,t,r){re.set(`${e}:${t}`,r),Tt(e,t,r)}function qe(e,t){return re.get(`${e}:${t}`)}function Ve(e){return x.join(ne(),".adam","wechat",`${e}.sync`)}function kt(e){try{return C.readFileSync(Ve(e),"utf-8")}catch{return""}}function Ct(e,t){let r=Ve(e);C.mkdirSync(x.dirname(r),{recursive:!0}),C.writeFileSync(r,t,"utf-8")}var Mt=0;function Rt(){return`adam-wechat-${Date.now()}-${++Mt}`}var V=class{platform="wechat";id;config;status="disconnected";messageHandler=null;pollAbort=null;getUpdatesBuf="";constructor(t,r){if(this.id=t,!r.baseUrl)throw new Error("WeChat adapter requires baseUrl");this.config=r}async connect(){if(!this.config.botToken)throw new Error("WeChat adapter requires botToken. Complete QR login first.");this.status="connecting",this.getUpdatesBuf=kt(this.id),It(this.id),this.pollAbort=new AbortController,this.status="connected",w.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",w.info({channelId:this.id},"WeChat adapter disconnected")}getStatus(){return this.status==="connected"&&B(this.id)?"error":this.status}async sendMessage(t,r){if(B(this.id)){let o=Math.ceil(xe(this.id)/6e4);throw new Error(`WeChat session paused, ${o} min remaining. Re-scan QR to reconnect.`)}let s=Rt(),n=qe(this.id,t),i=this.config.cdnBaseUrl??We;if(r.mediaUrl)try{let o=!r.mediaUrl.includes("://")||r.mediaUrl.startsWith("file://"),a=x.join(ne(),".adam","wechat","media","outbound-tmp");await P.mkdir(a,{recursive:!0});let c=this.getExtensionFromMediaType(r.mediaType),l;if(o){let u=r.mediaUrl.startsWith("file://")?new URL(r.mediaUrl).pathname:x.isAbsolute(r.mediaUrl)?r.mediaUrl:x.resolve(r.mediaUrl),y=await P.readFile(u);l=x.join(a,`${Date.now()}-${Math.random().toString(36).slice(2,7)}${c}`),await P.writeFile(l,y)}else{let u=await fetch(r.mediaUrl);if(!u.ok)throw new Error(`Failed to fetch media: ${u.status}`);let y=Buffer.from(await u.arrayBuffer());l=x.join(a,`${Date.now()}-${Math.random().toString(36).slice(2,7)}${c}`),await P.writeFile(l,y)}let d=await Be({filePath:l,to:t,text:r.content??"",opts:{baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,contextToken:n},cdnBaseUrl:i});return await P.unlink(l).catch(()=>{}),d.messageId}catch(o){throw w.error({channelId:this.id},`sendMessage media handling failed: ${String(o)}`),o}return await N({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{msg:{from_user_id:"",to_user_id:t,client_id:s,message_type:$.BOT,message_state:L.FINISH,item_list:r.content?[{type:m.TEXT,text_item:{text:r.content}}]:void 0,context_token:n}}}),s}onMessage(t){this.messageHandler=t}async sendTypingIndicator(t){if(B(this.id))return;let r=qe(this.id,t);try{await ge({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{ilink_user_id:t,status:_e.TYPING}})}catch{}}updateConfig(t){Object.assign(this.config,t)}async startLongPoll(){let t=this.pollAbort?.signal,r=0,s=3,n=3e4,i=2e3;for(;!t?.aborted;)try{let o=await ue({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,get_updates_buf:this.getUpdatesBuf});if(o.ret===X||o.errcode===X){we(this.id),this.status="error",w.error({channelId:this.id},"Session expired (errcode=-14), pausing for 1 hour"),await this.sleep(D,t),Ie(this.id),this.status="connected";continue}if(o.ret!==void 0&&o.ret!==0||o.errcode!==void 0&&o.errcode!==0){r++,w.error({channelId:this.id,ret:o.ret,errcode:o.errcode},"getUpdates API error"),r>=s?(r=0,await this.sleep(n,t)):await this.sleep(i,t);continue}r=0,o.get_updates_buf&&(this.getUpdatesBuf=o.get_updates_buf,Ct(this.id,o.get_updates_buf));for(let c of o.msgs??[])await this.processInbound(c)}catch(o){if(t?.aborted)return;r++,w.error({channelId:this.id,error:o},"getUpdates error"),r>=s?(r=0,await this.sleep(n,t)):await this.sleep(i,t)}}async processInbound(t){if(!this.messageHandler)return;let r=!!t.group_id,s=r?t.group_id:t.from_user_id??"",n=t.from_user_id??"";t.context_token&&s&&Ut(this.id,s,t.context_token);let i="",o,a=[];for(let d of t.item_list??[])d.type===m.TEXT&&d.text_item?.text&&(i+=d.text_item.text),d.type===m.IMAGE&&(o="image",a.push(d)),d.type===m.VOICE&&(o="audio",a.push(d),d.voice_item?.text&&!i&&(i=d.voice_item.text)),d.type===m.FILE&&(o="file",a.push(d)),d.type===m.VIDEO&&(o="video",a.push(d));if(!i&&!o)return;let c;if(a.length>0){let d=this.config.cdnBaseUrl??We;try{let u=await Ne(a[0],{cdnBaseUrl:d,channelId:this.id});u&&(c=u.path,o=u.type)}catch(u){w.error({channelId:this.id},`Media download failed: ${String(u)}`)}}let l={channelId:this.id,platform:"wechat",chatId:s,senderId:n,content:i,mediaType:o,mediaPath:c,isGroup:r,timestamp:t.create_time_ms??Date.now(),raw:t};this.messageHandler(l)}getExtensionFromMediaType(t){switch(t){case"image":return".png";case"video":return".mp4";case"audio":return".mp3";default:return".bin"}}sleep(t,r){return new Promise((s,n)=>{let i=setTimeout(s,t);r?.addEventListener("abort",()=>{clearTimeout(i),n(new Error("aborted"))},{once:!0})})}};var Et=f("channels"),z=class{platform="discord";id;config;status="disconnected";messageHandler=null;client=null;constructor(t,r){if(this.id=t,!r.botToken)throw new Error("Discord adapter requires botToken");this.config=r}async connect(){this.status="connecting";try{let{Client:t,GatewayIntentBits:r}=await import("discord.js");this.client=new t({intents:[r.Guilds,r.GuildMessages,r.MessageContent,r.DirectMessages]});let s=this.client;s.on("messageCreate",n=>{if(!this.messageHandler||n.author.bot||this.config.allowedGuildIds?.length&&n.guildId&&!this.config.allowedGuildIds.includes(n.guildId))return;let i={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(i)}),await s.login(this.config.botToken),this.status="connected",Et.info({channelId:this.id},"Discord bot connected")}catch(t){throw this.status="error",t}}async disconnect(){this.client&&await this.client.destroy(),this.client=null,this.status="disconnected"}getStatus(){return this.status}async sendMessage(t,r){if(!this.client)throw new Error("Discord client not connected");let n=await this.client.channels.fetch(t);if(!n||!("send"in n))throw new Error(`Channel ${t} not found or not text channel`);return(await n.send({content:r.content,reply:r.replyToMessageId?{messageReference:r.replyToMessageId}:void 0})).id}onMessage(t){this.messageHandler=t}async sendTypingIndicator(t){if(!this.client)return;let s=await this.client.channels.fetch(t);s&&"sendTyping"in s&&await s.sendTyping()}};var U=g.object({id:g.string().uuid()}),Pt=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()}),At=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()}),ie;function Vn(e){ie=e}function zn(){return ie}async function Gn(e){let t=ie;e.get("/channels",{schema:{tags:["Channels"],summary:"List channels",querystring:{type:"object",properties:{enabled:{type:"boolean"}}}}},async(r,s)=>({channels:ae(r.query.enabled)})),e.post("/channels",{schema:{tags:["Channels"],summary:"Create a channel",body:{type:"object",required:["name","platform","config"],properties:{name:{type:"string",minLength:1},platform:{type:"string",minLength:1},config:{type:"object"},enabled:{type:"boolean"},linkedRoleId:{type:"string"},allowedChatIds:{type:"array",items:{type:"string"}}}}}},async(r,s)=>{let n=Pt.safeParse(r.body);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let{name:i,platform:o,config:a,enabled:c,linkedRoleId:l,allowedChatIds:d}=n.data,u={id:St(),name:i,platform:o,enabled:c,status:"disconnected",config:a,linkedRoleId:l,allowedChatIds:d,createdAt:Date.now(),messageCount:0};return oe(u),s.status(201).send({channel:u})}),e.get("/channels/:id",{schema:{tags:["Channels"],summary:"Get channel by ID",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let n=U.safeParse(r.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let i=_(n.data.id);return i?{channel:i}:s.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),e.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(r,s)=>{let n=U.safeParse(r.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let i=_(n.data.id);if(!i)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let o=At.safeParse(r.body);return o.success?(G(i.id,o.data),{channel:_(i.id)}):s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(o.error)})}),e.delete("/channels/:id",{schema:{tags:["Channels"],summary:"Delete channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let n=U.safeParse(r.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let i=_(n.data.id);return i?(de(i.id),s.status(204).send()):s.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),e.post("/channels/:id/connect",{schema:{tags:["Channels"],summary:"Connect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let n=U.safeParse(r.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});if(!t)return s.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let i=_(n.data.id);if(!i)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(!t.hasAdapter(i.id)&&i.platform==="discord"){let o=i.config;if(!o.botToken)return s.status(400).send({code:"MISSING_CONFIG",message:"Discord channel requires botToken in config"});let a=new z(i.id,{botToken:o.botToken});await t.addChannel(i,a)}if(!t.hasAdapter(i.id))return s.status(400).send({code:"NO_ADAPTER",message:"No adapter registered for this channel. Install the appropriate adapter first."});try{return await t.connectChannel(i.id),{channelId:i.id,status:"connected"}}catch(o){return s.status(500).send({code:"CONNECT_FAILED",message:String(o)})}}),e.post("/channels/:id/disconnect",{schema:{tags:["Channels"],summary:"Disconnect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let n=U.safeParse(r.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});if(!t)return s.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let i=_(n.data.id);return i?(await t.disconnectChannel(i.id),{channelId:i.id,status:"disconnected"}):s.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),e.get("/channels/:id/messages",{schema:{tags:["Channels"],summary:"Get channel message history",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50},offset:{type:"integer",minimum:0,default:0}}}}},async(r,s)=>{let n=U.safeParse(r.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let i=_(n.data.id);if(!i)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let{limit:o=50,offset:a=0}=r.query;return{messages:se(i.id,o,a)}}),e.post("/channels/:id/wechat/qr-start",{schema:{tags:["WeChat"],summary:"Start WeChat QR login",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let n=U.safeParse(r.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let i=_(n.data.id);if(!i)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(i.platform!=="wechat")return s.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=i.config;return await he({apiBaseUrl:o.baseUrl,routeTag:o.routeTag})}),e.post("/channels/:id/wechat/qr-wait",{schema:{tags:["WeChat"],summary:"Wait for WeChat QR scan",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",properties:{sessionKey:{type:"string"},timeoutMs:{type:"number"}}}}},async(r,s)=>{let n=U.safeParse(r.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let i=_(n.data.id);if(!i)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(i.platform!=="wechat")return s.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=i.config,{sessionKey:a,timeoutMs:c}=r.body??{},l=await be({sessionKey:a??"",apiBaseUrl:o.baseUrl,timeoutMs:c??12e4,routeTag:o.routeTag});if(l.connected&&l.botToken){let d={...o,botToken:l.botToken,accountId:l.accountId,baseUrl:l.baseUrl??o.baseUrl,userId:l.userId};if(G(i.id,{config:d}),t){let u=new V(i.id,d),y=_(i.id);y&&await t.addChannel(y,u)}}return{connected:l.connected,accountId:l.accountId,message:l.message}})}export{V as a,z as b,Vn as c,zn as d,Gn as e};
@@ -1 +1 @@
1
- import{a,b,c,d}from"./chunk-KMMC7BEF.js";import"./chunk-LBLERTM4.js";import"./chunk-KICPHTI2.js";import"./chunk-5ASEAZCR.js";import"./chunk-742NWPTQ.js";import"./chunk-PQ7KPALO.js";import"./chunk-FDWW245P.js";import"./chunk-L7426WNY.js";import"./chunk-L7JP7DUO.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{a as DeliveryEngine,b as getDeliveryEngine,c as initDeliveryEngine,d as stopDeliveryEngine};
1
+ import{a,b,c,d}from"./chunk-DWMMWYLD.js";import"./chunk-NXTTKAQX.js";import"./chunk-KICPHTI2.js";import"./chunk-5ASEAZCR.js";import"./chunk-742NWPTQ.js";import"./chunk-PQ7KPALO.js";import"./chunk-FDWW245P.js";import"./chunk-L7426WNY.js";import"./chunk-L7JP7DUO.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{a as DeliveryEngine,b as getDeliveryEngine,c as initDeliveryEngine,d as stopDeliveryEngine};