adam-agent-server 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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};
@@ -1,4 +1,4 @@
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 ae}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 Be}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 se,b as v,c as F,d as A}from"./chunk-L7426WNY.js";import{a as ke}from"./chunk-L7JP7DUO.js";import{a as We,b as Te,c as Je,g as qe,j as He}from"./chunk-HAWA62R2.js";import{a as Ye,b as B,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 Fe,b as le,e as Ie,f as V}from"./chunk-U36NBCR3.js";import{e as $e,f as T,h as U,i as G,j as Oe,k as we,l as ie}from"./chunk-XNWZZYAV.js";import{b,d as oe}from"./chunk-PCSZW2PE.js";import{c as I,d as Ue}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 s={};try{if(!E(n))return s;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&&(s[u]=p[1].trim())}}catch{}return s}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 s=y(t,"skills");if(E(s)){let d=yt(s,{withFileTypes:!0});for(let p of d){if(!p.isDirectory()&&!p.isSymbolicLink())continue;let g=y(s,p.name,"SKILL.md"),f=r(g,["name","description"]);f.name&&n.skills.push({name:f.name,description:f.description??""})}}let i=y(t,"agents");if(E(i)){let d=yt(i,{withFileTypes:!0});for(let p of d){if(!p.isFile()||!p.name.endsWith(".md"))continue;let g=r(y(i,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,s]of Object.entries(t.plugins))if(!(!Array.isArray(s)||s.length===0))for(let i of s){let l=i.scope??"user";e?.scope&&l!==e.scope||e?.projectPath&&i.projectPath!==e.projectPath||n.push({id:o,name:o.split("@")[0],version:i.version??"",scope:l,projectPath:i.projectPath,installPath:i.installPath??y(Y(),o),enabled:r[o]??i.enabled??!0,installedAt:i.installedAt??"",lastUpdated:i.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 a}from"zod";ie();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 W(e){b().prepare(`
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 ie}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 Be}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 se,b as v,c as U,d as A}from"./chunk-L7426WNY.js";import{a as ke}from"./chunk-L7JP7DUO.js";import{a as We,b as Te,c as Je,g as qe,j as He}from"./chunk-HAWA62R2.js";import{a as Ye,b as B,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 Ue,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 Oe,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 s={};try{if(!E(n))return s;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&&(s[u]=p[1].trim())}}catch{}return s}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 s=y(t,"skills");if(E(s)){let d=yt(s,{withFileTypes:!0});for(let p of d){if(!p.isDirectory()&&!p.isSymbolicLink())continue;let g=y(s,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,s]of Object.entries(t.plugins))if(!(!Array.isArray(s)||s.length===0))for(let a of s){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 i}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 W(e){b().prepare(`
2
2
  INSERT INTO metric_tree (id, goal_id, level, parent_id, name, description,
3
3
  weight, calibration_factor, created_at)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -23,11 +23,11 @@ Rules:
23
23
  - targetValue: realistic target for the metric; use 1 for binary goals
24
24
  - deadline_days: reasonable timeframe; default 7 if unclear
25
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]),s=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()+s*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 Ot(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 pn(e,t,r){let n=J(),o=Date.now(),s={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(s),s}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),W(o);let s={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(s),W(s);let i={id:J(),goalId:e,level:"L2",parentId:s.id,name:`${t}_daily_process`,description:`Daily process metric for ${t}`,weight:.6,calibrationFactor:1,createdAt:r};n.push(i),W(i);let l={id:J(),goalId:e,level:"L3",parentId:i.id,name:`${t}_per_task`,description:`Per-task instant metric for ${t}`,weight:.4,calibrationFactor:1,createdAt:r};return n.push(l),W(l),n}var pe=class{static collect(t,r){let n=v(t);if(!n)return this.emptyMetrics(t,r);let o=ae(t,500,0),s=n.completedAt&&n.startedAt?n.completedAt-n.startedAt:0,i=new Set,l=0,u=0;for(let p of o)p.type==="tool_call"&&p.toolName&&i.add(p.toolName),p.type==="error"&&l++,p.type==="approval_request"&&u++;let d={taskId:t,goalId:r,timestamp:Date.now(),durationMs:s,costUsd:n.costUsd??0,turns:n.numTurns??0,toolCount:i.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),s=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*s+.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 Ft(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 st(e){b().prepare(`
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]),s=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()+s*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 Ot(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 pn(e,t,r){let n=J(),o=Date.now(),s={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(s),s}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),W(o);let s={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(s),W(s);let a={id:J(),goalId:e,level:"L2",parentId:s.id,name:`${t}_daily_process`,description:`Daily process metric for ${t}`,weight:.6,calibrationFactor:1,createdAt:r};n.push(a),W(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),W(l),n}var pe=class{static collect(t,r){let n=v(t);if(!n)return this.emptyMetrics(t,r);let o=ie(t,500,0),s=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:s,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),s=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*s+.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 Ut(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 st(e){b().prepare(`
27
27
  INSERT INTO trials (id, strategy_id, goal_id, task_id, reward,
28
28
  metric_l2_score, metric_l3_score, context, completed_at)
29
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 at(e,t=100){return b().prepare("SELECT * FROM trials WHERE goal_id = ? ORDER BY completed_at DESC LIMIT ?").all(e,t).map(Ft)}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,s=Math.max(0,(r.deadline-n)/(1e3*60*60*24)),i=this.calculateBudgetSpent(t),l=r.budgetUsd>0?Math.max(0,1-i/r.budgetUsd):1,u=this.calculateExpectedCompletion(r),d={goalId:t,metricType:r.metricType,targetValue:r.targetValue,currentValue:r.currentValue,progressPct:o,deadlineRemainingDays:s,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 s=o/n;if(s<.1)return .5;let i=t.targetValue>0?t.currentValue/t.targetValue:0;return s>0?i/s:0}static calculateBudgetSpent(t){let r=at(t,1e3),n=0,o=new Set;for(let s of r)if(s.taskId&&!o.has(s.taskId)){o.add(s.taskId);let i=v(s.taskId);i?.costUsd&&(n+=i.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 Ut=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 s=JSON.parse(o[0]);return{score:Math.max(0,Math.min(1,s.score??0)),confidence:Math.max(.3,Math.min(.95,s.confidence??.5)),reasoning:s.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 s=v(t);if(!s){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 i=this.getPromptTemplate(s.prompt??"",s.result??s.error??"",r),l,u,d;try{let g=await this.callClaude(i);l=g.score,u=g.confidence,d=g.reasoning}catch(g){Ut.warn({error:g,taskId:t},"LLM Judge Claude API call failed, using heuristic fallback"),s.status==="failed"?(l=.1,u=.6,d=`Task failed: ${s.error??"unknown error"} (heuristic fallback)`):s.status==="completed"&&s.result?(l=.7,u=.5,d="Task completed with result (heuristic fallback due to API error)"):s.status==="completed"?(l=.5,u=.4,d="Task completed without explicit result (heuristic fallback)"):(l=.3,u=.3,d=`Task in status: ${s.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:
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 it(e,t=100){return b().prepare("SELECT * FROM trials WHERE goal_id = ? ORDER BY completed_at DESC LIMIT ?").all(e,t).map(Ut)}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,s=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:s,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 s=o/n;if(s<.1)return .5;let a=t.targetValue>0?t.currentValue/t.targetValue:0;return s>0?a/s:0}static calculateBudgetSpent(t){let r=it(t,1e3),n=0,o=new Set;for(let s of r)if(s.taskId&&!o.has(s.taskId)){o.add(s.taskId);let a=v(s.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 s=JSON.parse(o[0]);return{score:Math.max(0,Math.min(1,s.score??0)),confidence:Math.max(.3,Math.min(.95,s.confidence??.5)),reasoning:s.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 s=v(t);if(!s){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(s.prompt??"",s.result??s.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"),s.status==="failed"?(l=.1,u=.6,d=`Task failed: ${s.error??"unknown error"} (heuristic fallback)`):s.status==="completed"&&s.result?(l=.7,u=.5,d="Task completed with result (heuristic fallback due to API error)"):s.status==="completed"?(l=.5,u=.4,d="Task completed without explicit result (heuristic fallback)"):(l=.3,u=.3,d=`Task in status: ${s.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
31
 
32
32
  Task: ${t}
33
33
  Result: ${r}
@@ -38,7 +38,7 @@ Provide:
38
38
  2. Confidence (0-1): How confident are you in this evaluation?
39
39
  3. Reasoning: Brief explanation of your scoring
40
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,s=this.children.get(o)??[];s.push(n),this.children.set(o,s)}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,s=0;for(let i of n){let l=r.get(i.id)??0,u=i.weight*i.calibrationFactor;o+=l*u,s+=u}return s>0?o/s:0}getWeightedScore(t){let r=0;for(let[n,o]of Object.entries(Gt)){let s=this.aggregateScores(n,t);r+=s*o}return Math.max(0,Math.min(1,r))}getNodeCount(){return this.nodes.size}getChildren(t){return this.children.get(t)??[]}};var An=I("agent");function fe(e,t){let r=Date.now(),n=ge.buildFromGoal(e),o=new Map,s=me.collect(e);for(let u of n.queryPath("L0"))o.set(u.id,s.rawScore);let i=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+s.rawScore*.35));return{goalId:e,taskId:t,reward:d,breakdown:{L0:s.rawScore,L1:0,L2:0,L3:u.rawScore},calibrationFactors:i,source:"objective",confidence:.9,computedAt:r}}}if(t&&!q.shouldUseObjective(t)){let d=q.evaluate(t,"general_quality"),p=s.rawScore*.5+.5*.5;return{goalId:e,taskId:t,reward:s.rawScore,breakdown:{L0:s.rawScore,L1:0,L2:0,L3:0,llmJudge:.5},calibrationFactors:i,source:"llm_judge",confidence:.4,computedAt:r}}let l=n.getNodeCount()>0?n.getWeightedScore(o):s.rawScore;return{goalId:e,reward:l,breakdown:{L0:s.rawScore,L1:0,L2:0,L3:0},calibrationFactors:i,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 it(e){b().prepare(`
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,s=this.children.get(o)??[];s.push(n),this.children.set(o,s)}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,s=0;for(let a of n){let l=r.get(a.id)??0,u=a.weight*a.calibrationFactor;o+=l*u,s+=u}return s>0?o/s:0}getWeightedScore(t){let r=0;for(let[n,o]of Object.entries(Gt)){let s=this.aggregateScores(n,t);r+=s*o}return Math.max(0,Math.min(1,r))}getNodeCount(){return this.nodes.size}getChildren(t){return this.children.get(t)??[]}};var An=I("agent");function fe(e,t){let r=Date.now(),n=ge.buildFromGoal(e),o=new Map,s=me.collect(e);for(let u of n.queryPath("L0"))o.set(u.id,s.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+s.rawScore*.35));return{goalId:e,taskId:t,reward:d,breakdown:{L0:s.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=s.rawScore*.5+.5*.5;return{goalId:e,taskId:t,reward:s.rawScore,breakdown:{L0:s.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):s.rawScore;return{goalId:e,reward:l,breakdown:{L0:s.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
42
  INSERT INTO strategies (id, role_id, task_type, name, prompt_template,
43
43
  alpha, beta, total_trials, avg_reward, created_at, updated_at)
44
44
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -53,7 +53,7 @@ Respond in JSON: {"score": number, "confidence": number, "reasoning": "string"}`
53
53
  END,
54
54
  updated_at = ?
55
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 s,i;do s=this.randn(),i=1+o*s;while(i<=0);i=i*i*i;let l=Math.random();if(l<1-.0331*s*s*s*s||Math.log(l)<.5*s*s+n*(1-i+Math.log(i)))return n*i/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 s=this.sampleBeta(o.alpha,o.beta);s>n&&(n=s,r=o)}return r}static getProbabilities(t,r=1e4){let n=new Map;for(let s=0;s<r;s++){let i=this.sample(t);i&&n.set(i.id,(n.get(i.id)||0)+1)}let o=new Map;for(let[s,i]of n)o.set(s,i/r);return o}};var Bt=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,s,i,l){dt(t,o),st({id:ut(),strategyId:t,goalId:r,taskId:n,reward:o,metricL2Score:s,metricL3Score:i,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 s=n.reduce((u,d)=>u+d.totalTrials,0)/n.length,i=n.filter(u=>u.avgReward!==void 0).map(u=>u.avgReward),l=i.length>0?i.reduce((u,d)=>u+d,0)/i.length:0;return{count:n.length,avgTrials:s,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<Bt?!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 i={id:`strat-${ut().slice(0,8)}`,roleId:t,taskType:r,name:n,promptTemplate:o,alpha:pt,beta:pt,totalTrials:0,createdAt:Date.now()};return it(i),i}static getTopStrategies(t,r,n=3){let s=L(t,r).filter(i=>i.totalTrials>0);return s.sort((i,l)=>(l.avgReward??0)-(i.avgReward??0)),s.slice(0,n)}static getSamplingProbabilities(t,r){let n=L(t,r);return H.getProbabilities(n)}static evaluateAndRecord(t,r,n,o,s,i){let l=fe(r,n);return this.recordTrial(t,r,n,l.reward,o,s,i),l.reward}};var Wt=3,Jt=2,be=class{static async generateVariants(t,r,n=Wt,o=Jt){let s=S.getTopStrategies(t,r,n);if(s.length===0){let l=`baseline-${r}-v1`;return S.addStrategy(t,r,l,this.generateBaselinePrompt(t,r)),[l]}let i=[];for(let l=0;l<o;l++){let u=s[0].totalTrials+l+1,d=`${r}-evolved-v${u}`,p=s[0].promptTemplate,g=this.mutateTemplate(p);S.addStrategy(t,r,d,g),i.push(d)}return i}static generateBaselinePrompt(t,r){return`You are a ${t} agent specializing in ${r}.
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 s,a;do s=this.randn(),a=1+o*s;while(a<=0);a=a*a*a;let l=Math.random();if(l<1-.0331*s*s*s*s||Math.log(l)<.5*s*s+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 s=this.sampleBeta(o.alpha,o.beta);s>n&&(n=s,r=o)}return r}static getProbabilities(t,r=1e4){let n=new Map;for(let s=0;s<r;s++){let a=this.sample(t);a&&n.set(a.id,(n.get(a.id)||0)+1)}let o=new Map;for(let[s,a]of n)o.set(s,a/r);return o}};var Bt=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,s,a,l){dt(t,o),st({id:ut(),strategyId:t,goalId:r,taskId:n,reward:o,metricL2Score:s,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 s=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:s,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<Bt?!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 s=L(t,r).filter(a=>a.totalTrials>0);return s.sort((a,l)=>(l.avgReward??0)-(a.avgReward??0)),s.slice(0,n)}static getSamplingProbabilities(t,r){let n=L(t,r);return H.getProbabilities(n)}static evaluateAndRecord(t,r,n,o,s,a){let l=fe(r,n);return this.recordTrial(t,r,n,l.reward,o,s,a),l.reward}};var Wt=3,Jt=2,be=class{static async generateVariants(t,r,n=Wt,o=Jt){let s=S.getTopStrategies(t,r,n);if(s.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=s[0].totalTrials+l+1,d=`${r}-evolved-v${u}`,p=s[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
57
 
58
58
  ## Core Focus
59
59
  Complete tasks with high quality.
@@ -65,10 +65,10 @@ Complete tasks with high quality.
65
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
66
 
67
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(s=>({id:s.id,type:s.type,content:s.content,keywords:s.keywords,importance:s.importance,score:s.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 Be(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 s=`mem-${qt().slice(0,8)}`,i=Date.now();return We({id:s,roleId:r,type:t.type??"thought",content:t.content,embedding:n,keywords:t.keywords??[],importance:t.importance??3,sourceType:"manual",createdAt:i,lastAccessed:i,retrievedCount:0,tier:t.tier??"episodic"}),M({id:s,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 s=St("/tmp",`adam-cli-stdout-${process.pid}-${Date.now()}.txt`),i=tr(s,"w");try{let l=It("node",[r,...e],{cwd:t.cwd,timeout:n,stdio:["ignore",i,"pipe"],encoding:"utf-8"});if(l.status!==0)throw new Error(l.stderr?.trim()||`CLI exited with status ${l.status}`);return rr(s,"utf-8")}finally{try{nr(s)}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 co(){try{return!!Tt()}catch{return!1}}ye();V();var ar={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=ar[d];if(p){let g=n.get(p.category)??[];g.push(p.label),n.set(p.category,g)}else o.push(d)}let s=[];for(let[d,p]of n)s.push(`${d} (${p.join(", ")})`);o.length>0&&s.push(o.join(", "));let i=s.join(" \xB7 "),l=Object.keys(e.mcpServers??{});l.length>0&&(i+=` \xB7 MCP: ${l.join(", ")}`);let u=e.additionalDirectories??[];if(u.length>0&&(i+=` \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});i+=` \xB7 Plugins: ${d.join(", ")}`}return i}function ir(e){let t=[],r=e.additionalDirectories??[];for(let n of r){if(!n.inheritPlugins&&!n.inheritMcp)continue;let o=X(n.path),s=Object.entries(o.enabledPlugins).filter(([,l])=>l).map(([l])=>l),i=Ee(s);for(let[,l]of i)t.includes(l)||t.push(l)}try{let n=Fe(e.name),o=C({scope:"project",projectPath:n});for(let s of o)s.installPath&&!t.includes(s.installPath)&&t.push(s.installPath)}catch{}return t}function Ne(e){let t=ir(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(`
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(s=>({id:s.id,type:s.type,content:s.content,keywords:s.keywords,importance:s.importance,score:s.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 Be(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 s=`mem-${qt().slice(0,8)}`,a=Date.now();return We({id:s,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:s,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 s=St("/tmp",`adam-cli-stdout-${process.pid}-${Date.now()}.txt`),a=tr(s,"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(s,"utf-8")}finally{try{nr(s)}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 co(){try{return!!Tt()}catch{return!1}}ye();V();var ir={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=ir[d];if(p){let g=n.get(p.category)??[];g.push(p.label),n.set(p.category,g)}else o.push(d)}let s=[];for(let[d,p]of n)s.push(`${d} (${p.join(", ")})`);o.length>0&&s.push(o.join(", "));let a=s.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),s=Object.entries(o.enabledPlugins).filter(([,l])=>l).map(([l])=>l),a=Ee(s);for(let[,l]of a)t.includes(l)||t.push(l)}try{let n=Ue(e.name),o=C({scope:"project",projectPath:n});for(let s of o)s.installPath&&!t.includes(s.installPath)&&t.push(s.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
69
  INSERT INTO approval_rules (id, role_id, task_pattern, max_risk_level, created_at, created_by_task_id)
70
70
  VALUES (?, ?, ?, ?, ?, ?)
71
- `).run(e.id,e.roleId??null,e.taskPattern,e.maxRiskLevel,e.createdAt,e.createdByTaskId??null)}function fo(e,t,r){let o=b().prepare("SELECT * FROM approval_rules ORDER BY created_at DESC").all();for(let s of o)if(!(s.role_id&&s.role_id!==e)&&!(Pt[r]>Pt[s.max_risk_level]))try{if(new RegExp(s.task_pattern,"i").test(t))return lr(s)}catch{}}import*as Lt from"crypto";var te=I("api"),re=class{cancelTask(t){let r=v(t);r&&(F(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 s=Ge(t);if(!s)return te.warn({planId:t},"Plan not found or already resolved"),!1;let i=v(s.taskId);return i?(Ve(t,r==="allow"?"approved":"denied",n),r==="allow"&&n==="permanent"&&xt({id:Lt.randomUUID(),roleId:s.roleId,taskPattern:i.prompt.slice(0,100).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),maxRiskLevel:s.plan.overallRisk,createdAt:Date.now(),createdByTaskId:i.id}),ke.emit({type:"plan_approval_decision",taskId:i.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)}};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")],s=[];for(let i of e)if(i.type==="session"&&i.sessionId)s.push({type:"session",sessionId:i.sessionId});else if(i.type==="channel"){let l=i.channelId,u=i.chatId;if(!l&&i.channelName){let d=r.find(p=>p.name.toLowerCase().includes(i.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?s.push({type:"channel",channelId:l,chatId:u}):ve.warn({channelName:i.channelName,channelId:l,chatId:u},"Could not resolve channel notify target")}return s}async function dr(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 ur={goalId:a.string()},pr={goalId:a.string(),status:a.string().optional(),currentValue:a.number().optional(),budgetUsd:a.number().optional(),notes:a.string().optional()},mr={goalId:a.string(),goalDescription:a.string(),maxSubtasks:a.number().optional()},D=a.union([a.object({type:a.literal("session"),sessionId:a.string()}),a.object({type:a.literal("channel"),channelName:a.string()}),a.object({type:a.literal("channel"),channelId:a.string(),chatId:a.string().optional()})]),gr={prompt:a.string(),roleId:a.string().describe("Role ID. Call list_roles first to find the best role for the task."),deliverTo:a.array(D).optional().describe("Where to deliver the task output (result full text). E.g., send result to a specific channel."),reportTo:a.array(D).optional().describe("Where to send status reports (completion summary). Defaults to the originating channel/session."),toolOverrides:a.object({allowedTools:a.array(a.string()).optional(),disallowedTools:a.array(a.string()).optional()}).optional()},fr={taskId:a.string(),goalId:a.string().optional(),strategyId:a.string().optional()},hr={roleId:a.string(),taskType:a.string(),name:a.string().optional()},br={status:a.string().optional(),limit:a.number().optional()},yr={taskId:a.string(),roleId:a.string()},vr={taskId:a.string().optional(),status:a.string().optional(),limit:a.number().optional()},wr={roleId:a.string(),allowedPaths:a.array(a.string()).optional(),deniedPaths:a.array(a.string()).optional(),allowedTools:a.array(a.string()).optional(),disallowedTools:a.array(a.string()).optional(),additionalDirectories:a.array(a.object({path:a.string(),inheritPlugins:a.boolean().optional(),inheritMcp:a.boolean().optional(),inheritPermissions:a.boolean().optional()})).optional(),allowedChannels:a.array(a.string()).optional(),inheritUserSettings:a.boolean().optional().describe("Enable/disable inheriting user-level settings (global plugins, MCP servers). Default: false (isolated).")},Ir={roleId:a.string().optional(),limit:a.number().optional()},Sr={name:a.string(),cagPrompt:a.string(),traits:a.array(a.string()).optional(),allowedTools:a.array(a.string()).optional(),disallowedTools:a.array(a.string()).optional(),additionalDirectories:a.array(a.object({path:a.string(),inheritPlugins:a.boolean().optional(),inheritMcp:a.boolean().optional(),inheritPermissions:a.boolean().optional()})).optional()},kr={roleId:a.string(),reason:a.string().optional()},Tr={name:a.string(),description:a.string().optional(),roleId:a.string().optional(),metric:a.string().optional(),targetValue:a.number().optional(),deadline:a.number().optional(),budgetUsd:a.number().optional(),deliverTo:a.array(D).optional().describe("Where to deliver goal completion notifications.")},Rr={name:a.string(),description:a.string().optional(),triggerType:a.enum(["cron","event"]),triggerCron:a.string().optional(),triggerEvent:a.string().optional(),prompt:a.string(),roleId:a.string().optional(),enabled:a.boolean().optional(),goalIds:a.array(a.string()).optional(),deliverTo:a.array(D).optional().describe("Where to deliver the task output (result full text)."),reportTo:a.array(D).optional().describe("Where to send status reports (completion summary).")},_r={status:a.enum(["active","retired","probation"]).optional(),limit:a.number().optional()},Mr={enabled:a.boolean().optional()},Pr={},xr={},Lr={prompt:a.string().describe("The task prompt to execute after the delay"),delayMinutes:a.number().optional().describe("Minutes from now to execute (e.g., 30 for 'half an hour later')"),runAt:a.string().optional().describe("ISO 8601 timestamp to execute at (e.g., '2026-04-01T15:00:00+08:00')"),roleId:a.string().describe("Role ID to assign the task to. Call list_roles first."),deliverTo:a.array(D).optional().describe("Where to deliver the task output (result full text)."),reportTo:a.array(D).optional().describe("Where to send status reports (completion summary).")},Er={roleId:a.string().optional().describe("If provided, shows which plugins are installed in that role's workspace.")},Cr={roleId:a.string().describe("Role ID to install the plugin under (project-scope)."),pluginId:a.string().describe("Plugin ID (e.g. 'github@anthropic'). Use list_available_plugins to discover available plugins.")},Dr={roleId:a.string().describe("Role ID to uninstall the plugin from."),pluginId:a.string().describe("Plugin ID to uninstall.")},Ar={roleId:a.string().describe("Role ID to bind the MCP server to."),mcpName:a.string().describe("Name for this MCP server (e.g., 'github', 'filesystem')."),mcpConfig:a.record(a.string(),a.unknown()).describe("MCP server configuration object.")},Nr={roleId:a.string().describe("Role ID to unbind the MCP server from."),mcpName:a.string().describe("Name of the MCP server to remove.")},jr={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},$r={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},Or={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},Fr={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},Ur={},Gr={},Vr={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},Br={roleId:a.string().describe("Role ID to associate scanned plugins with."),path:a.string().describe("Directory path to scan for .claude/settings.json.")},Wr={taskId:a.string().describe("Task ID to cancel.")},Jr={taskId:a.string().describe("Task ID to get logs for."),limit:a.number().optional().describe("Max log entries (default 20).")},qr={roleId:a.string().describe("Role ID to delete.")},Hr={},Kr={updates:a.record(a.string(),a.unknown()).describe("Config key-value pairs to update. Example: { 'defaults.maxTurns': 50, 'logging.level': 'debug' }")},Yr={roleId:a.string().describe("Role ID to list memories for."),limit:a.number().optional().describe("Max results (default 20).")},zr={templateId:a.string().describe("Template ID to update."),name:a.string().optional(),enabled:a.boolean().optional(),prompt:a.string().optional(),triggerCron:a.string().optional(),triggerEvent:a.string().optional(),roleId:a.string().optional()},Qr={templateId:a.string().describe("Template ID to delete.")},Xr={templateId:a.string().describe("Template ID to run immediately.")},Zr={enabled:a.boolean().optional().describe("Filter by enabled status.")},en={eventType:a.string().describe("Event type that triggers this rule (e.g., 'task_complete')."),channelId:a.string().describe("Channel ID to deliver to."),format:a.string().optional().describe("Format template (e.g., 'summary', 'full'). Default: 'summary'."),matchCriteria:a.record(a.string(),a.unknown()).optional().describe("JSON match criteria for event fields."),enabled:a.boolean().optional().describe("Enable this rule immediately (default true).")},tn={ruleId:a.string().describe("Delivery rule ID to delete.")},rn={roleId:a.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.",ur,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.",pr,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.",mr,async e=>{let t=k(),r=Math.min(e.maxSubtasks??5,10);try{let{query:o}=await import("@anthropic-ai/claude-agent-sdk"),s=`Decompose this goal into ${r} actionable subtasks.
71
+ `).run(e.id,e.roleId??null,e.taskPattern,e.maxRiskLevel,e.createdAt,e.createdByTaskId??null)}function fo(e,t,r){let o=b().prepare("SELECT * FROM approval_rules ORDER BY created_at DESC").all();for(let s of o)if(!(s.role_id&&s.role_id!==e)&&!(Pt[r]>Pt[s.max_risk_level]))try{if(new RegExp(s.task_pattern,"i").test(t))return lr(s)}catch{}}import*as Lt from"crypto";var te=I("api"),re=class{cancelTask(t){let r=v(t);r&&(U(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 s=Ge(t);if(!s)return te.warn({planId:t},"Plan not found or already resolved"),!1;let a=v(s.taskId);return a?(Ve(t,r==="allow"?"approved":"denied",n),r==="allow"&&n==="permanent"&&xt({id:Lt.randomUUID(),roleId:s.roleId,taskPattern:a.prompt.slice(0,100).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),maxRiskLevel:s.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)}};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")],s=[];for(let a of e)if(a.type==="session"&&a.sessionId)s.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?s.push({type:"channel",channelId:l,chatId:u}):ve.warn({channelName:a.channelName,channelId:l,chatId:u},"Could not resolve channel notify target")}return s}async function dr(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 ur={goalId:i.string()},pr={goalId:i.string(),status:i.string().optional(),currentValue:i.number().optional(),budgetUsd:i.number().optional(),notes:i.string().optional()},mr={goalId:i.string(),goalDescription:i.string(),maxSubtasks:i.number().optional()},D=i.union([i.object({type:i.literal("session"),sessionId:i.string()}),i.object({type:i.literal("channel"),channelName:i.string()}),i.object({type:i.literal("channel"),channelId:i.string(),chatId:i.string().optional()})]),gr={prompt:i.string(),roleId:i.string().describe("Role ID. Call list_roles first to find the best role for the task."),deliverTo:i.array(D).optional().describe("Where to deliver the task output (result full text). E.g., send result to a specific channel."),reportTo:i.array(D).optional().describe("Where to send status reports (completion summary). Defaults to the originating channel/session."),toolOverrides:i.object({allowedTools:i.array(i.string()).optional(),disallowedTools:i.array(i.string()).optional()}).optional()},fr={taskId:i.string(),goalId:i.string().optional(),strategyId:i.string().optional()},hr={roleId:i.string(),taskType:i.string(),name:i.string().optional()},br={status:i.string().optional(),limit:i.number().optional()},yr={taskId:i.string(),roleId:i.string()},vr={taskId:i.string().optional(),status:i.string().optional(),limit:i.number().optional()},wr={roleId:i.string(),allowedPaths:i.array(i.string()).optional(),deniedPaths:i.array(i.string()).optional(),allowedTools:i.array(i.string()).optional(),disallowedTools:i.array(i.string()).optional(),additionalDirectories:i.array(i.object({path:i.string(),inheritPlugins:i.boolean().optional(),inheritMcp:i.boolean().optional(),inheritPermissions:i.boolean().optional()})).optional(),allowedChannels:i.array(i.string()).optional(),inheritUserSettings:i.boolean().optional().describe("Enable/disable inheriting user-level settings (global plugins, MCP servers). Default: false (isolated).")},Ir={roleId:i.string().optional(),limit:i.number().optional()},Sr={name:i.string(),cagPrompt:i.string(),traits:i.array(i.string()).optional(),allowedTools:i.array(i.string()).optional(),disallowedTools:i.array(i.string()).optional(),additionalDirectories:i.array(i.object({path:i.string(),inheritPlugins:i.boolean().optional(),inheritMcp:i.boolean().optional(),inheritPermissions:i.boolean().optional()})).optional()},kr={roleId:i.string(),reason:i.string().optional()},Tr={name:i.string(),description:i.string().optional(),roleId:i.string().optional(),metric:i.string().optional(),targetValue:i.number().optional(),deadline:i.number().optional(),budgetUsd:i.number().optional(),deliverTo:i.array(D).optional().describe("Where to deliver goal completion notifications.")},Rr={name:i.string(),description:i.string().optional(),triggerType:i.enum(["cron","event"]),triggerCron:i.string().optional(),triggerEvent:i.string().optional(),prompt:i.string(),roleId:i.string().optional(),enabled:i.boolean().optional(),goalIds:i.array(i.string()).optional(),deliverTo:i.array(D).optional().describe("Where to deliver the task output (result full text)."),reportTo:i.array(D).optional().describe("Where to send status reports (completion summary).")},_r={status:i.enum(["active","retired","probation"]).optional(),limit:i.number().optional()},Mr={enabled:i.boolean().optional()},Pr={},xr={},Lr={prompt:i.string().describe("The task prompt to execute after the delay"),delayMinutes:i.number().optional().describe("Minutes from now to execute (e.g., 30 for 'half an hour later')"),runAt:i.string().optional().describe("ISO 8601 timestamp to execute at (e.g., '2026-04-01T15:00:00+08:00')"),roleId:i.string().describe("Role ID to assign the task to. Call list_roles first."),deliverTo:i.array(D).optional().describe("Where to deliver the task output (result full text)."),reportTo:i.array(D).optional().describe("Where to send status reports (completion summary).")},Er={roleId:i.string().optional().describe("If provided, shows which plugins are installed in that role's workspace.")},Cr={roleId:i.string().describe("Role ID to install the plugin under (project-scope)."),pluginId:i.string().describe("Plugin ID (e.g. 'github@anthropic'). Use list_available_plugins to discover available plugins.")},Dr={roleId:i.string().describe("Role ID to uninstall the plugin from."),pluginId:i.string().describe("Plugin ID to uninstall.")},Ar={roleId:i.string().describe("Role ID to bind the MCP server to."),mcpName:i.string().describe("Name for this MCP server (e.g., 'github', 'filesystem')."),mcpConfig:i.record(i.string(),i.unknown()).describe("MCP server configuration object.")},Nr={roleId:i.string().describe("Role ID to unbind the MCP server from."),mcpName:i.string().describe("Name of the MCP server to remove.")},jr={pluginId:i.string().describe("Plugin ID (e.g., 'github@anthropic').")},$r={pluginId:i.string().describe("Plugin ID (e.g., 'github@anthropic').")},Or={pluginId:i.string().describe("Plugin ID (e.g., 'github@anthropic').")},Ur={pluginId:i.string().describe("Plugin ID (e.g., 'github@anthropic').")},Fr={},Gr={},Vr={pluginId:i.string().describe("Plugin ID (e.g., 'github@anthropic').")},Br={roleId:i.string().describe("Role ID to associate scanned plugins with."),path:i.string().describe("Directory path to scan for .claude/settings.json.")},Wr={taskId:i.string().describe("Task ID to cancel.")},Jr={taskId:i.string().describe("Task ID to get logs for."),limit:i.number().optional().describe("Max log entries (default 20).")},qr={roleId:i.string().describe("Role ID to delete.")},Hr={},Kr={updates:i.record(i.string(),i.unknown()).describe("Config key-value pairs to update. Example: { 'defaults.maxTurns': 50, 'logging.level': 'debug' }")},Yr={roleId:i.string().describe("Role ID to list memories for."),limit:i.number().optional().describe("Max results (default 20).")},zr={templateId:i.string().describe("Template ID to update."),name:i.string().optional(),enabled:i.boolean().optional(),prompt:i.string().optional(),triggerCron:i.string().optional(),triggerEvent:i.string().optional(),roleId:i.string().optional()},Qr={templateId:i.string().describe("Template ID to delete.")},Xr={templateId:i.string().describe("Template ID to run immediately.")},Zr={enabled:i.boolean().optional().describe("Filter by enabled status.")},en={eventType:i.string().describe("Event type that triggers this rule (e.g., 'task_complete')."),channelId:i.string().describe("Channel ID to deliver to."),format:i.string().optional().describe("Format template (e.g., 'summary', 'full'). Default: 'summary'."),matchCriteria:i.record(i.string(),i.unknown()).optional().describe("JSON match criteria for event fields."),enabled:i.boolean().optional().describe("Enable this rule immediately (default true).")},tn={ruleId:i.string().describe("Delivery rule ID to delete.")},rn={roleId:i.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.",ur,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.",pr,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.",mr,async e=>{let t=k(),r=Math.min(e.maxSubtasks??5,10);try{let{query:o}=await import("@anthropic-ai/claude-agent-sdk"),s=`Decompose this goal into ${r} actionable subtasks.
72
72
 
73
73
  Goal: ${e.goalDescription}
74
74
 
@@ -78,9 +78,9 @@ Rules:
78
78
  - Each subtask must be independently executable
79
79
  - Order from foundational to dependent
80
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.`,i=o({prompt:s,options:{cwd:process.cwd(),maxTurns:1,maxBudgetUsd:.02}}),l="";for await(let d of i){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,O=$?await dr($):void 0;se({id:ne,status:"pending",prompt:f.prompt,parentId:e.goalId,roleId:O,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 s=`subtask-${w().slice(0,8)}`,i=`Subtask ${o+1} of goal: ${e.goalDescription.slice(0,100)}`,l=`${e.goalDescription}
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:s,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,O=$?await dr($):void 0;se({id:ne,status:"pending",prompt:f.prompt,parentId:e.goalId,roleId:O,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 s=`subtask-${w().slice(0,8)}`,a=`Subtask ${o+1} of goal: ${e.goalDescription.slice(0,100)}`,l=`${e.goalDescription}
82
82
 
83
- Subtask ${o+1}/${r}`;se({id:s,status:"pending",prompt:l,parentId:e.goalId,config:t.defaults,createdAt:Date.now()}),n.push({id:s,description:i,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.",gr,async e=>{let t=T(e.roleId);if(!t||t.status!=="active"){let O=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:O})}let r=w(),n=k(),o=e.prompt.toLowerCase(),s={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"]},i="general";for(let[O,R]of Object.entries(s))if(R.some(Ct=>o.includes(Ct))){i=O;break}let l,u=e.prompt,d=S.selectStrategy(e.roleId,i);d?.promptTemplate&&(u=`${d.promptTemplate}
83
+ Subtask ${o+1}/${r}`;se({id:s,status:"pending",prompt:l,parentId:e.goalId,config:t.defaults,createdAt:Date.now()}),n.push({id:s,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.",gr,async e=>{let t=T(e.roleId);if(!t||t.status!=="active"){let O=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:O})}let r=w(),n=k(),o=e.prompt.toLowerCase(),s={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[O,R]of Object.entries(s))if(R.some(Ct=>o.includes(Ct))){a=O;break}let l,u=e.prompt,d=S.selectStrategy(e.roleId,a);d?.promptTemplate&&(u=`${d.promptTemplate}
84
84
 
85
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;se({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.",fr,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.",hr,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.",br,async e=>{let t=e.status;return c(Ze(t,e.limit??10,0))}),m("delete_goal","Delete a goal by ID.",{goalId:a.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:a.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.",yr,async e=>{let{taskId:t,roleId:r}=e;if(!v(t))return c({error:`Task not found: ${t}`});let o=T(r);return o?(F(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.",vr,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).",wr,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 U(e.roleId,r),c({success:!0})}),m("view_audit_log","View the evolution audit log for role changes.",Ir,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.",_r,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(s=>({name:s.name,skills:s.skills.map(i=>i.name),agents:s.agents.map(i=>i.name)}))}});return c({roles:r})}),m("create_role","Create a new role with a name, CAG prompt, and optional tool permissions.",Sr,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).",kr,async e=>T(e.roleId)?(U(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.",Tr,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 s=_(t);return c({goalId:s.id,name:s.name,status:s.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.",Rr,async e=>{let{createTaskTemplate:t}=await import("./task-templates-7LSQ6OST.js"),r=w(),n=w(),o=e.deliverTo?await P(e.deliverTo):void 0,s=e.reportTo?await P(e.reportTo):void 0,i={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:s};return t(i),c({templateId:r,name:i.name,trigger:i.trigger})}),m("list_templates","List task templates (automations). Use this to check existing scheduled/recurring tasks before creating new ones.",{enabled:a.boolean().optional().describe("Filter by enabled status. Omit to list all."),limit:a.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 to a connected channel by name. Use this to deliver task results or notifications to a specific channel (e.g., WeChat on iPad).",{channelName:a.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:a.string().describe("The message content to send")},async e=>{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-FIPC4BZO.js"),s=await n().send({channelId:r.channelId,chatId:r.chatId,content:e.message,messageType:"deliver"});return c({success:s.success,channelName:e.channelName})}),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.",Mr,async e=>{let t=Re(e.enabled),r=[..._e("active"),..._e("archived")],n=t.map(o=>{let s,i=r.find(l=>l.source.type==="channel"&&l.source.channelId===o.id&&l.source.chatId);return i?.source.chatId?s=i.source.chatId:s=o.config?.userId,{id:o.id,name:o.name,platform:o.platform,status:o.status,chatId:s}});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.",Pr,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.",Lr,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 s=w(),i=new Date(n).toISOString(),l=e.deliverTo?await P(e.deliverTo):void 0,u=e.reportTo?await P(e.reportTo):void 0;Ye({id:s,name:e.prompt.slice(0,80),description:`One-shot scheduled task: ${e.prompt.slice(0,200)}`,trigger:{type:"once",runAt:i},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-SQMSKGAP.js"),p=d();return p&&p.scheduleOnceJob(s),c({templateId:s,executeAt:i,prompt:e.prompt})}),m("cancel_scheduled_task","Cancel a previously scheduled one-shot task by its template ID. The task will not execute.",{templateId:a.string().describe("The template ID returned by schedule_task")},async e=>{let t=B(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-SQMSKGAP.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.",Er,async e=>{let t=z(),r=C(),n=e.roleId?(()=>{let{getRoleWorkspacePath:o}=(V(),x(Ie)),{getRole:s}=(ie(),x(we)),{listInstalledPlugins:i}=(ye(),x(wt)),l=s(e.roleId);if(!l)return[];let u=o(l.name);return i({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.",Cr,async e=>{let{getRole:t}=(ie(),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(s){return c({error:`Failed to install plugin: ${s}`})}}),m("uninstall_plugin_from_role","Uninstall a plugin from a role's workspace.",Dr,async e=>{let{getRole:t}=(ie(),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(s){return c({error:`Failed to uninstall plugin: ${s}`})}}),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.",Ar,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 U(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.",Nr,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 U(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.",xr,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),s=A("running"),i=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:s.length,queued:i.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).",jr,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).",$r,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).",Ur,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.",Gr,async()=>{let e=Ce();return c({sources:e})}),m("get_plugin_detail","Get detailed manifest for an installed plugin (skills, agents, MCP servers, hooks).",Vr,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.",Wr,async e=>{let t=v(e.taskId);if(!t)return c({error:`Task not found: ${e.taskId}`});let r=t.status;F(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.",Jr,async e=>{let t=ae(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.",qr,async e=>T(e.roleId)?(Oe(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).",Hr,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],s=[...t],i={};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}i[l]={value:d,mutable:!t.includes(l)}}return c({config:i,mutable:[...e],restartRequired:[...t]})}),m("update_config","Update mutable runtime configuration fields. Returns partial-success: some fields may update while others return errors.",Kr,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"]&&Ue(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(s=>({path:s,value:e.updates[s]}))})}return c(n)}),m("list_memories","List memories stored under a specific role.",Yr,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.).",zr,async e=>{let t=B(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.",Qr,async e=>B(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).",Xr,async e=>{let t=B(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.",Zr,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.",en,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.",tn,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.",rn,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:a.string(),operationId:a.string().optional().describe("ID of the specific operation. If omitted, authorizes the most recent pending operation."),scope:a.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:a.string(),operationId:a.string().optional(),reason:a.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 Yo(){return Et.map(e=>e.name).sort().join(",")}function zo(){return cr({name:"adam-tools",version:"1.0.0",tools:Et})}export{fo 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,un as j,pn as k,ot as l,$n 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,co as v,ir as w,Yo as x,zo as y};
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;se({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.",fr,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.",hr,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.",br,async e=>{let t=e.status;return c(Ze(t,e.limit??10,0))}),m("delete_goal","Delete a goal by ID.",{goalId:i.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:i.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.",yr,async e=>{let{taskId:t,roleId:r}=e;if(!v(t))return c({error:`Task not found: ${t}`});let o=T(r);return o?(U(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.",vr,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).",wr,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.",Ir,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.",_r,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(s=>({name:s.name,skills:s.skills.map(a=>a.name),agents:s.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.",Sr,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).",kr,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.",Tr,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 s=_(t);return c({goalId:s.id,name:s.name,status:s.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.",Rr,async e=>{let{createTaskTemplate:t}=await import("./task-templates-7LSQ6OST.js"),r=w(),n=w(),o=e.deliverTo?await P(e.deliverTo):void 0,s=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:s};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:i.boolean().optional().describe("Filter by enabled status. Omit to list all."),limit:i.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 pointing to the file and mediaType.",{channelName:i.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:i.string().describe("The message content to send (text caption when sending media)"),mediaUrl:i.string().optional().describe("Local file path or remote URL of media to send. Local paths (e.g. /Users/.../file.mp3) and http(s) URLs both work."),mediaType:i.enum(["image","audio","video","file"]).optional().describe("Type of the media file. Required when mediaUrl is provided")},async e=>{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"),s=await n().send({channelId:r.channelId,chatId:r.chatId,content:e.message,messageType:"deliver",mediaUrl:e.mediaUrl,mediaType:e.mediaType});return c({success:s.success,channelName:e.channelName})}),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.",Mr,async e=>{let t=Re(e.enabled),r=[..._e("active"),..._e("archived")],n=t.map(o=>{let s,a=r.find(l=>l.source.type==="channel"&&l.source.channelId===o.id&&l.source.chatId);return a?.source.chatId?s=a.source.chatId:s=o.config?.userId,{id:o.id,name:o.name,platform:o.platform,status:o.status,chatId:s}});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.",Pr,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.",Lr,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 s=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:s,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(s),c({templateId:s,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:i.string().describe("The template ID returned by schedule_task")},async e=>{let t=B(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.",Er,async e=>{let t=z(),r=C(),n=e.roleId?(()=>{let{getRoleWorkspacePath:o}=(V(),x(Ie)),{getRole:s}=(ae(),x(we)),{listInstalledPlugins:a}=(ye(),x(wt)),l=s(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.",Cr,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(s){return c({error:`Failed to install plugin: ${s}`})}}),m("uninstall_plugin_from_role","Uninstall a plugin from a role's workspace.",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 Ae(e.pluginId,"project",o),c({success:!0,roleId:e.roleId,pluginId:e.pluginId})}catch(s){return c({error:`Failed to uninstall plugin: ${s}`})}}),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.",Ar,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.",Nr,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.",xr,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),s=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:s.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).",jr,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).",$r,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.",Ur,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).",Fr,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.",Gr,async()=>{let e=Ce();return c({sources:e})}),m("get_plugin_detail","Get detailed manifest for an installed plugin (skills, agents, MCP servers, hooks).",Vr,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.",Wr,async e=>{let t=v(e.taskId);if(!t)return c({error:`Task not found: ${e.taskId}`});let r=t.status;U(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.",Jr,async e=>{let t=ie(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.",qr,async e=>T(e.roleId)?(Oe(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).",Hr,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],s=[...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.",Kr,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(s=>({path:s,value:e.updates[s]}))})}return c(n)}),m("list_memories","List memories stored under a specific role.",Yr,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.).",zr,async e=>{let t=B(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.",Qr,async e=>B(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).",Xr,async e=>{let t=B(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.",Zr,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.",en,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.",tn,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.",rn,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:i.string(),operationId:i.string().optional().describe("ID of the specific operation. If omitted, authorizes the most recent pending operation."),scope:i.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:i.string(),operationId:i.string().optional(),reason:i.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 Yo(){return Et.map(e=>e.name).sort().join(",")}function zo(){return cr({name:"adam-tools",version:"1.0.0",tools:Et})}export{fo 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,un as j,pn as k,ot as l,$n 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,co as v,ar as w,Yo as x,zo as y};
@@ -0,0 +1 @@
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&&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,52 @@
1
+ import{a as T,b as I}from"./chunk-VF6GJGD6.js";import{b as O,d as L}from"./chunk-PCSZW2PE.js";import{f as l,g as D}from"./chunk-SFUS33SO.js";import{c as A}from"./chunk-3DAK2XWP.js";import{readFileSync as R,existsSync as y}from"fs";import{fileURLToPath as k}from"url";import{dirname as F,join as d}from"path";var w=k(import.meta.url),P=F(w),_,h;function v(){let e=d(P,"..","package.json");if(y(e))return e;let r=d(P,"..","..","package.json");return y(r)?r:d(process.cwd(),"package.json")}function z(){if(_===void 0){let e=v();_=JSON.parse(R(e,"utf-8")).version}return _}function J(){if(h===void 0){let e=v();h=JSON.parse(R(e,"utf-8")).name}return h}L();import{dirname as V,join as H}from"path";import{fileURLToPath as C}from"url";var M=V(C(import.meta.url)),E=H(M,"..");var x=E,it=A("cli:register-ai-digest"),m="ai-hourly-digest";function $(){try{if(I(m)){console.log(`[INFO] AI Digest template already exists (${m})`);return}}catch{}let e={id:m,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 ${x}/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/",x],deniedPaths:[]}},tags:["ai","digest","hourly","automation"],createdAt:Date.now()};T(e),console.log(`[INFO] Registered AI Hourly Digest task template (${m})`),console.log("[INFO] Cron schedule: 0 * * * * (every hour at minute 0)")}import.meta.url===`file://${process.argv[1]}`&&(console.log("Initializing database..."),O(),console.log("Registering AI Digest template..."),$(),console.log("Done."),process.exit(0));D();import{readFileSync as N,writeFileSync as U,existsSync as S}from"fs";var u={ANTHROPIC_API_KEY:"anthropic.apiKey",ANTHROPIC_BASE_URL:"anthropic.baseUrl",ANTHROPIC_MODEL:"anthropic.model",ANTHROPIC_DEFAULT_OPUS_MODEL:"anthropic.defaultOpusModel",ANTHROPIC_DEFAULT_SONNET_MODEL:"anthropic.defaultSonnetModel",ANTHROPIC_DEFAULT_HAIKU_MODEL:"anthropic.defaultHaikuModel",ANTHROPIC_SMALL_FAST_MODEL:"anthropic.smallFastModel"},ct=Object.fromEntries(Object.entries(u).map(([e,r])=>[r,e]));function j(){if(!S(l))return null;let e=N(l,"utf-8"),r={};for(let s of e.split(`
50
+ `)){let o=s.trim();if(!o||o.startsWith("#"))continue;let c=o.startsWith("export ")?o.slice(7).trim():o,i=c.indexOf("=");if(i===-1)continue;let n=c.slice(0,i).trim();if(!(n in u))continue;let t=c.slice(i+1).trim();(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))&&(t=t.slice(1,-1)),!(t.includes("$")&&(t=t.replace(/\$\{(\w+)\}|\$(\w+)/g,(p,f,g)=>{let a=f??g;return r[a]??process.env[a]??""}),!t))&&(r[n]=t)}return r}function at(e){let r=j();if(!r)return[];let s=[];for(let[o,c]of Object.entries(u)){let i=e[c],n=r[o];if(n===void 0)continue;let t=i?String(i):"";t!==n&&s.push({configPath:c,envKey:o,dbValue:t,envValue:n})}return s}function lt(e){if(!S(l))return 0;let s=N(l,"utf-8").split(`
51
+ `),o=0,c=new Set;for(let i=0;i<s.length;i++){let n=s[i].trim();if(!n||n.startsWith("#"))continue;let t=n.startsWith("export ")?n.slice(7).trim():n,p=t.indexOf("=");if(p===-1)continue;let f=t.slice(0,p).trim(),g=u[f];if(!g)continue;let a=e[g];if(a!=null&&String(a).length>0){let b=n.startsWith("export ")?"export ":"";s[i]=`${b}${f}=${String(a)}`,c.add(f),o++}}for(let[i,n]of Object.entries(u)){if(c.has(i))continue;let t=e[n];t&&String(t).length>0&&(s.push(`${i}=${String(t)}`),o++)}return o>0&&U(l,s.join(`
52
+ `)),o}export{E as a,z as b,J as c,ct as d,j as e,at as f,lt as g,$ as h};