adam-agent-server 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -188,7 +188,6 @@ defaults:
188
188
 
189
189
  execution:
190
190
  maxConcurrent: 5
191
- maxBudgetPerTaskUsd: 5.0
192
191
  pollIntervalMs: 30000
193
192
 
194
193
  server:
@@ -1 +1 @@
1
- import{n as a,o as b}from"./chunk-UW3OJG7U.js";import"./chunk-5V36ACKZ.js";import"./chunk-OEKM2W3K.js";import"./chunk-EJVUUIAV.js";import"./chunk-GMCIKDTC.js";import"./chunk-6YURWVQG.js";import"./chunk-CDVIT7L5.js";import"./chunk-3RAFA6QK.js";import"./chunk-MPRAVJUO.js";import"./chunk-AJVN3KPM.js";import"./chunk-AR2IZMM2.js";import"./chunk-SWPXG2CY.js";import"./chunk-KLQOILIJ.js";import"./chunk-L7JP7DUO.js";import"./chunk-GUQAIWCQ.js";import"./chunk-2CMR5AG7.js";import"./chunk-4TCP2AT7.js";import"./chunk-6DXNXLYG.js";import"./chunk-JTMFEUDA.js";import"./chunk-6KLG4APZ.js";import"./chunk-7IFLU3CY.js";import"./chunk-6HD6NYIB.js";import"./chunk-B4WHT7DX.js";import"./chunk-7LBDLAUQ.js";import"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{b as createAdamTools,a as getToolsFingerprint};
1
+ import{n as a,o as b}from"./chunk-XTGWQUO4.js";import"./chunk-5V36ACKZ.js";import"./chunk-OEKM2W3K.js";import"./chunk-EJVUUIAV.js";import"./chunk-GMCIKDTC.js";import"./chunk-6YURWVQG.js";import"./chunk-CDVIT7L5.js";import"./chunk-W3554FQ7.js";import"./chunk-RPTHFQX7.js";import"./chunk-AJVN3KPM.js";import"./chunk-AR2IZMM2.js";import"./chunk-SWPXG2CY.js";import"./chunk-KLQOILIJ.js";import"./chunk-L7JP7DUO.js";import"./chunk-GUQAIWCQ.js";import"./chunk-2CMR5AG7.js";import"./chunk-4TCP2AT7.js";import"./chunk-6DXNXLYG.js";import"./chunk-SBX3HMDA.js";import"./chunk-ZM6YED5F.js";import"./chunk-7IFLU3CY.js";import"./chunk-6HD6NYIB.js";import"./chunk-B4WHT7DX.js";import"./chunk-7LBDLAUQ.js";import"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{b as createAdamTools,a as getToolsFingerprint};
@@ -0,0 +1 @@
1
+ import{i as a,j as b,k as c,l as d,m as e}from"./chunk-ITUBFUJQ.js";import"./chunk-QN6BEJF5.js";import"./chunk-OEKM2W3K.js";import"./chunk-EJVUUIAV.js";import"./chunk-GMCIKDTC.js";import"./chunk-W3554FQ7.js";import"./chunk-BIIP363C.js";import"./chunk-KLQOILIJ.js";import"./chunk-OFOVSC72.js";import"./chunk-L7JP7DUO.js";import"./chunk-GUQAIWCQ.js";import"./chunk-2CMR5AG7.js";import"./chunk-4TCP2AT7.js";import"./chunk-Z5ET7WW2.js";import"./chunk-6HD6NYIB.js";import"./chunk-B4WHT7DX.js";import"./chunk-7LBDLAUQ.js";import"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as evaluateTaskCompletion,e as getSecurityPosture,d as reportViolation,b as startAuditManager,c as stopAuditManager};
@@ -1 +1 @@
1
- import{a,b,c}from"./chunk-Q4YE5BU7.js";import"./chunk-CDVIT7L5.js";import"./chunk-3RAFA6QK.js";import"./chunk-L7JP7DUO.js";import"./chunk-4TCP2AT7.js";import"./chunk-6DXNXLYG.js";import"./chunk-JTMFEUDA.js";import"./chunk-6KLG4APZ.js";import"./chunk-7IFLU3CY.js";import"./chunk-6HD6NYIB.js";import"./chunk-B4WHT7DX.js";import"./chunk-7LBDLAUQ.js";import"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as BreeEngine,b as getBreeEngine,c as setBreeEngine};
1
+ import{a,b,c}from"./chunk-JNRCXAW3.js";import"./chunk-CDVIT7L5.js";import"./chunk-W3554FQ7.js";import"./chunk-L7JP7DUO.js";import"./chunk-4TCP2AT7.js";import"./chunk-6DXNXLYG.js";import"./chunk-SBX3HMDA.js";import"./chunk-ZM6YED5F.js";import"./chunk-7IFLU3CY.js";import"./chunk-6HD6NYIB.js";import"./chunk-B4WHT7DX.js";import"./chunk-7LBDLAUQ.js";import"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as BreeEngine,b as getBreeEngine,c as setBreeEngine};
@@ -0,0 +1,67 @@
1
+ import{a as $,e as Ke}from"./chunk-QN6BEJF5.js";import{b as We,k as Je,m as Ye}from"./chunk-OEKM2W3K.js";import{a as me,d as Fe,e as ge}from"./chunk-EJVUUIAV.js";import{a as Le,b as $e}from"./chunk-GMCIKDTC.js";import{b as Me,c as V,d as K,f as Oe}from"./chunk-W3554FQ7.js";import{a as je}from"./chunk-BIIP363C.js";import{e as Ue,f as Ve,j as qt}from"./chunk-KLQOILIJ.js";import{b as He}from"./chunk-OFOVSC72.js";import{a as m}from"./chunk-L7JP7DUO.js";import{b as Ge}from"./chunk-GUQAIWCQ.js";import{b as qe}from"./chunk-Z5ET7WW2.js";import{d as U,i as De}from"./chunk-6HD6NYIB.js";import{a as j,b as Be,e as x,g as O,h as pe,k as L}from"./chunk-B4WHT7DX.js";import{a as Ne,g as Wt}from"./chunk-7LBDLAUQ.js";import{b as I,d as Ae}from"./chunk-KVSO3KGZ.js";import{d as ue,h as Ft}from"./chunk-WBAPIPST.js";import{c as h,h as _}from"./chunk-INNDBLZE.js";Ae();function Gt(t){return{id:t.id,roleId:t.role_id,taskId:t.task_id,scores:JSON.parse(t.score_json),emaScore:t.ema_score,createdAt:t.created_at}}function Xe(t){I().prepare(`
2
+ INSERT INTO role_scores (id, role_id, task_id, score_json, ema_score, created_at)
3
+ VALUES (?, ?, ?, ?, ?, ?)
4
+ `).run(t.id,t.roleId,t.taskId,JSON.stringify(t.scores),t.emaScore,t.createdAt)}function X(t,e=50){return I().prepare("SELECT * FROM role_scores WHERE role_id = ? ORDER BY created_at DESC LIMIT ?").all(t,e).map(Gt)}function ze(t){return I().prepare("SELECT ema_score FROM role_scores WHERE role_id = ? ORDER BY created_at DESC LIMIT 1").get(t)?.ema_score}function Qe(t){let o=I().prepare(`
5
+ SELECT token_usage FROM tasks
6
+ WHERE role_id = ? AND status = 'completed' AND token_usage IS NOT NULL
7
+ ORDER BY completed_at DESC LIMIT 50
8
+ `).all(t);if(o.length===0)return 1e4;let n=o.map(r=>{let s=JSON.parse(r.token_usage);return(s.input??0)+(s.output??0)}).sort((r,s)=>r-s);return n[Math.floor(n.length/2)]}_();import{v4 as Jt}from"uuid";var Yt=h("audit"),z={taskSuccess:.3,planAccuracy:.25,permissionCompliance:.25,efficiency:.2},Ze=.3;function Kt(t,e){let o=Me(t),n=o?.status==="completed"?1:0,r=1,s=Fe(t);s?.deviationReport&&(r=s.deviationReport.overallAccuracy);let a=1,i=$e(t,1e3),l=i.filter(y=>y.type==="tool_result"||y.type==="permission_denied").length,c=i.filter(y=>y.type==="permission_denied").length;l>0&&(a=1-c/l);let f=1;if(o?.tokenUsage){let y=o.tokenUsage.input+o.tokenUsage.output,S=e?Qe(e):1e4;y>S&&(f=Math.max(0,1-(y-S)/S))}let k=n*z.taskSuccess+r*z.planAccuracy+a*z.permissionCompliance+f*z.efficiency;return{taskSuccess:n,planAccuracy:r,permissionCompliance:a,efficiency:f,weighted:k}}function et(t,e){let o=Kt(e,t),n=ze(t),r=n!==void 0?Ze*o.weighted+(1-Ze)*n:o.weighted;return Xe({id:Jt(),roleId:t,taskId:e,scores:o,emaScore:r,createdAt:Date.now()}),Yt.debug({roleId:t,taskId:e,scores:{...o,weighted:o.weighted.toFixed(3)},ema:r.toFixed(3)},"Task score recorded"),r}L();L();_();var Xt=h("audit");function Q(t,e=7){let o=x(t),n=X(t,100),r=Date.now(),s=r-e*24*60*60*1e3,a=n.filter(d=>d.createdAt>=s),i=a.map(d=>d.emaScore),l=a.length>0?a.reduce((d,E)=>d+E.scores.weighted,0)/a.length:1,c=[],f=a.filter(d=>d.scores.taskSuccess<.5);f.length>0&&c.push({category:"task_failures",count:f.length,examples:f.slice(0,3).map(d=>d.taskId)});let k=a.filter(d=>d.scores.planAccuracy<.5);k.length>0&&c.push({category:"plan_deviations",count:k.length,examples:k.slice(0,3).map(d=>d.taskId)});let y=a.filter(d=>d.scores.permissionCompliance<.8);y.length>0&&c.push({category:"permission_violations",count:y.length,examples:y.slice(0,3).map(d=>d.taskId)});let S=a.filter(d=>d.scores.efficiency<.3);S.length>0&&c.push({category:"inefficiency",count:S.length,examples:S.slice(0,3).map(d=>d.taskId)});let T=[],R=[];return f.length>a.length*.3&&(T.push("High task failure rate"),R.push({action:"add_rule",detail:"Add rule: verify task feasibility before execution"})),y.length>0&&(T.push("Permission boundary violations"),R.push({action:"adjust_permission",detail:"Review and expand allowedTools if tasks legitimately need wider access"})),k.length>a.length*.5&&(T.push("Frequent plan deviations"),R.push({action:"add_rule",detail:"Add rule: follow execution plan steps more closely, request plan revision if steps are unclear"})),Xt.info({roleId:t,taskCount:a.length,avgScore:l.toFixed(3),failureCategories:c.map(d=>d.category)},"Diagnostic report generated"),{roleId:t,agentName:o?.name??"Unknown",period:{start:s,end:r},taskCount:a.length,avgScore:l,scoreHistory:i,failureBehaviors:c,rootCauses:T,recommendations:R}}_();var Z=h("audit"),tt=.4,zt=5;function ot(t,e,o=tt){if(e>=o)return;let n=x(t);if(!n||n.status==="retired"||n.status==="dead")return;Z.warn({roleId:t,emaScore:e,threshold:o},"Agent EMA below threshold, retiring");let r=Q(t),s=JSON.stringify(n.learnedRules),a=Qt(n.learnedRules,r);O(t,{status:"retired",learnedRules:a});let i=[...r.failureBehaviors.map(c=>`${c.category}: ${c.count} occurrences`),...r.rootCauses.map(c=>`Root cause: ${c}`),...r.recommendations.map(c=>`Recommendation [${c.action}]: ${c.detail}`)].join(`
9
+ `),l=Ke(s,JSON.stringify(a));return $({timestamp:Date.now(),oldRules:s,newRules:JSON.stringify(a),diff:i?`--- Diagnostic Report ---
10
+ ${i}
11
+
12
+ --- Rules Diff ---
13
+ ${l}`:l,roleId:t,source:"audit"}),Z.info({roleId:t,oldRulesCount:n.learnedRules.length,newRulesCount:a.length,recommendations:r.recommendations.length},"Agent retired with targeted learnedRules modification"),r}function nt(t){let e=x(t);return!e||e.status!=="retired"?!1:(O(t,{status:"probation"}),$({timestamp:Date.now(),oldRules:"status: retired",newRules:"status: probation",diff:`- status: retired
14
+ + status: probation`,roleId:t,source:"audit"}),Z.info({roleId:t},"Agent reinstated to probation"),!0)}function rt(t,e,o=tt,n=zt){let r=x(t);return!r||r.status!=="probation"||X(t,n+1).length<n?!1:e>=o?(O(t,{status:"active"}),$({timestamp:Date.now(),oldRules:"status: probation",newRules:"status: idle",diff:`- status: probation
15
+ + status: idle (graduated, EMA: ${e.toFixed(3)})`,roleId:t,source:"audit"}),Z.info({roleId:t,emaScore:e},"Agent graduated from probation to active"),!0):!1}function Qt(t,e){let o=[...t];for(let n of e.recommendations){let r=`[audit:${n.action}] ${n.detail}`;o.includes(r)||o.push(r)}if(e.failureBehaviors.length>0){let r=`[audit:diagnostic] Failure patterns detected: ${e.failureBehaviors.map(s=>`${s.category}(${s.count})`).join(", ")}. Review and adjust behavior accordingly.`;o.includes(r)||o.push(r)}return o}import{spawn as It}from"child_process";L();import{accessSync as it,constants as at}from"fs";import{accessSync as Zt,constants as eo,existsSync as st,realpathSync as to}from"fs";import{join as fe}from"path";import{spawn as oo}from"child_process";import{execFileSync as no}from"child_process";var H=null;function F(){if(H)return H;let t=typeof import.meta.dirname=="string"?import.meta.dirname:__dirname??".",e=fe(t,"landlock-exec","landlock-exec");if(st(e))return H=e,e;let o=process.env.PATH?.split(":").find(n=>st(fe(n,"landlock-exec")));return o?(H=fe(o,"landlock-exec"),H):e}var ee=class{platform="landlock";async isAvailable(){if(process.platform!=="linux")return!1;try{Zt(F(),eo.X_OK)}catch{return!1}try{return no(F(),["--check"],{timeout:5e3,stdio:["ignore","pipe","pipe"]}),!0}catch{return!1}}spawn(e){let o=e.command??"node",n=e.args??[],r=[];for(let s of e.visiblePaths??[]){let a=s.mode==="rw"?"--rw":"--ro",i;try{i=to(s.path)}catch{i=s.path}r.push(a,i),i!==s.path&&r.push(a,s.path)}return r.push("--",o,...n),oo(F(),r,{cwd:e.cwd,env:e.env,stdio:"pipe",signal:e.signal})}};function lt(){if(process.platform==="linux")try{return it(F(),at.X_OK),"landlock"}catch{return"none"}if(process.platform==="darwin")try{return it("/usr/bin/sandbox-exec",at.X_OK),"sandbox-exec"}catch{return"none"}return"none"}_();import{spawn as ro}from"child_process";import{readFileSync as dt,writeFileSync as so,mkdtempSync as io,realpathSync as he,rmSync as ao}from"fs";import{join as C}from"path";import{tmpdir as lo}from"os";var ut=h("sandbox-macos"),ct="/usr/bin/sandbox-exec";function co(){let t=[C(typeof import.meta.dirname=="string"?import.meta.dirname:".","profiles","role-sandbox.sb"),C(typeof import.meta.dirname=="string"?import.meta.dirname:".","..","src","sandbox","profiles","role-sandbox.sb"),C(process.cwd(),"src","sandbox","profiles","role-sandbox.sb")];for(let e of t)try{return dt(e,"utf-8"),e}catch{}return t[t.length-1]}var uo=co();function te(t){if(!t.startsWith("/"))throw new Error(`Sandbox path must be absolute: ${t}`);if(t.includes('"')||t.includes(")")||t.includes("(")||t.includes("$"))throw new Error(`Sandbox path contains invalid characters for SBPL: ${t}`)}function po(t){let e=[`
16
+ ; ===== Per-Role writable paths =====`];for(let o of t){if(o.mode!=="rw")continue;let n;try{n=he(o.path)}catch{n=o.path}te(n),e.push(`(allow file-write* (subpath "${n}"))`),n!==o.path&&(te(o.path),e.push(`(allow file-write* (subpath "${o.path}"))`))}return e.join(`
17
+ `)}function mo(t){if(!t.length)return"";let e=[`
18
+ ; ===== Global read blacklist (deniedReadPaths) =====`];for(let o of t){let n;try{n=he(o)}catch{n=o}try{te(n),e.push(`(deny file-read-data (subpath "${n}"))`),e.push(`(deny file-read-metadata (subpath "${n}"))`),n!==o&&(te(o),e.push(`(deny file-read-data (subpath "${o}"))`),e.push(`(deny file-read-metadata (subpath "${o}"))`))}catch(r){ut.warn({path:o,error:r.message},"Skipping deniedReadPath: invalid for SBPL")}}return e.join(`
19
+ `)}var oe=class{platform="sandbox-exec";async isAvailable(){try{let{existsSync:e}=await import("fs");return e(ct)}catch{return!1}}spawn(e){let{command:o,args:n,cwd:r,env:s,signal:a,visiblePaths:i,deniedReadPaths:l}=e,c=dt(uo,"utf-8"),f=po(i),k=mo(l??[]),y=c+f+k+`
20
+ `,S=he(io(C(lo(),"adam-sandbox-"))),T=C(S,"role.sb");so(T,y,"utf-8");let R=S,d=s?.HOME??process.env.HOME??"/tmp",E={...s,TMPDIR:R,CLAUDE_CODE_TMPDIR:R,CLAUDE_CONFIG_DIR:C(d,".claude")};ut.debug({command:o,visiblePaths:i.length,profilePath:T},"Spawning sandboxed process");let N=ro(ct,["-f",T,"-D",`TMPDIR=${R}`,"-D",`CLAUDE_CONFIG=${C(d,".claude")}`,"-D",`HOME_CACHE=${C(d,"Library","Caches")}`,o,...n],{cwd:r,env:E,stdio:"pipe",signal:a});return N.on("exit",()=>{try{ao(S,{recursive:!0,force:!0})}catch{}}),N}};import{spawn as go}from"child_process";var B=null,pt=null,ne=null;function D(){if(B)return B;let t=pt??lt();return pt=t,t==="sandbox-exec"?B=new oe:t==="landlock"?B=new ee:B=new be(t),B}async function mt(){return ne!==null||(ne=await D().isAvailable()),ne}var be=class{platform;constructor(e){this.platform=e}async isAvailable(){return!1}spawn(e){let o=e.command??"node",n=e.args??[];return go(o,n,{cwd:e.cwd,env:e.env,stdio:"pipe",signal:e.signal})}};import{query as So}from"@anthropic-ai/claude-agent-sdk";import{v4 as kt}from"uuid";function gt(t){let e=t.roleName?`## Role Context
21
+ - Role: ${t.roleName}
22
+ ${t.roleCagPrompt?`- CAG Prompt: ${t.roleCagPrompt}`:""}`:"",o=t.allowedTools&&t.allowedTools.length>0?`## Available Tools
23
+ You have access to: ${t.allowedTools.join(", ")}. Use them as needed to complete the task.`:"";return`# Execution Agent \u2014 Task Focus
24
+
25
+ You are executing a specific task assigned to you. Your job is to complete the work, not manage goals or strategies.
26
+
27
+ ## Task
28
+ - Task ID: ${t.taskId}
29
+ - Prompt: ${t.prompt}
30
+
31
+ ${e}
32
+
33
+ ${o}
34
+
35
+ ## Focus
36
+ - Focus entirely on completing the task
37
+ - Use the standard SDK tools to do the work
38
+ - Do NOT attempt strategic decisions \u2014 just execute
39
+
40
+ ## Constraints
41
+ - You have standard SDK tools only (no adam-tools MCP)
42
+ - Stay within your assigned permissions and allowed paths
43
+ - Report completion with a clear result summary
44
+ - If WebSearch or WebFetch fails (network error, invalid params), report the failure honestly \u2014 do not fabricate data
45
+ - If a tool is unavailable, state it clearly in the result rather than guessing
46
+ `}Be();_();var fo=new Set(["Read","Glob","Grep","LSP"]),ho=new Set(["Edit","Write","NotebookEdit"]);function ye(t){let e=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${e}$`)}function ft(t,e,o){return async(n,r,{agentID:s,blockedPath:a})=>{if(a){let l=j(a);if(o?.deniedReadPaths?.length)for(let c of o.deniedReadPaths){let f=j(c);if(l.startsWith(f))return bo.warn({toolName:n,blockedPath:a,agentID:s,deniedPath:c},"Denied: path in deniedReadPaths (absolute blacklist)"),{behavior:"deny",message:`Access denied: ${a} is in the global denied read paths list. This restriction is configured in Settings > Advanced and cannot be overridden by privilege escalation.`}}return e?await e(n,r,`blockedPath:${a}`,s):{behavior:"deny",message:`Access denied: ${a} is outside this role's allowed scope (cwd + additionalDirectories). Configure additionalDirectories to expand access.`}}if(fo.has(n))return{behavior:"allow",updatedInput:r};if(ho.has(n))return{behavior:"allow",updatedInput:r};let i=t(s??"");if(n==="Bash"&&i){let l=r.command??"";if(i.allowedBashPatterns?.length)for(let c of i.allowedBashPatterns)try{if(ye(c).test(l))return{behavior:"allow",updatedInput:r}}catch{}if(i.deniedBashPatterns?.length)for(let c of i.deniedBashPatterns)try{if(ye(c).test(l))return{behavior:"deny",message:`Bash command denied by pattern: ${c}`}}catch{}}if(i?.disallowedTools?.includes(n))return{behavior:"deny",message:`Tool ${n} is not allowed for this role.`};if(e&&i?.approvalRequired?.length){let l=n==="Bash"?r.command??"":`${n} ${JSON.stringify(r)}`;for(let c of i.approvalRequired)try{if(ye(c).test(l))return await e(n,r,c,s)}catch{}}return{behavior:"allow",updatedInput:r}}}var bo=h("manager");function ht(t){return{SessionStart:[{hooks:[async e=>{if(!t.roleId)return{};let o=e.source,n=t.roleId==="role-chat-manager";if(!n&&o!=="startup"&&o!=="resume")return{};try{let{queryMemoryByTier:r}=await import("./memory-service-ANR67OPY.js"),s=t.taskPrompt||"role context and recent interactions",a=n?["semantic","working"]:["semantic","episodic"],i=await r(t.roleId,s,a,{topK:5});if(i.length>0)return{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:`[Memory Context]
47
+ ${i.map(f=>`- [${f.tier??"episodic"}] ${f.content}`).join(`
48
+ `)}
49
+
50
+ `}}}catch{}return{}}]}],SubagentStart:[{hooks:[async e=>{let o=t.roleId??e.agent_id;if(!o)return{};try{let n=t.taskPrompt||"role context",r=await Ge(n,o,5);if(r)return{hookSpecificOutput:{hookEventName:"SubagentStart",additionalContext:r}}}catch{}return{}}]}],SubagentStop:[{hooks:[async e=>{let o=e.agent_id;if(!o||!t.currentTaskId)return{};try{let{createMemory:n}=await import("./memories-FQCRKMK6.js"),{getDb:r}=await import("./db-4NY7ZOS2.js"),s=e.transcript;if(!s||s.length<=100)return{};if(r().prepare("SELECT 1 FROM memories WHERE source_task_id = ? AND type = 'thought' LIMIT 1").get(t.currentTaskId))return{};let i=`[Task ${t.currentTaskId} reasoning] ${s.slice(0,3e3)}`;n({id:`session-${Date.now()}`,roleId:t.roleId??o,type:"thought",content:i,keywords:[],importance:3,sourceType:"task_complete",sourceTaskId:t.currentTaskId,createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"episodic"})}catch{}return{}}]}],PostToolUse:[{hooks:[async e=>{if(!t.currentTaskId)return{};let o=e.tool_name,n=e.tool_input,r=e.tool_response,s=typeof r=="string"?r:JSON.stringify(r??"");try{Le({id:`step-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,taskId:t.currentTaskId,index:0,type:"tool_call",content:`${o}: ${JSON.stringify(n??{})} \u2192 ${s.slice(0,200)}`,toolName:o,toolInput:n,toolOutput:s,timestamp:Date.now()})}catch{}return{}}]}],PreCompact:[{hooks:[async e=>{let o=e.compact_summary;if(!o)return{};try{let{createMemory:n}=await import("./memories-FQCRKMK6.js");n({id:`compact-${Date.now()}`,roleId:t.roleId??"role-chat-manager",type:"thought",content:o.slice(0,5e3),keywords:["compaction","context","decisions"],importance:4,sourceType:"pre_compact",createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"working"})}catch{}return{}}]}]}}L();qt();Ft();_();Ae();import{randomUUID as yo}from"crypto";function bt(t,e,o){let r=I().prepare(`
51
+ INSERT INTO task_plugins (id, task_id, plugin_path, plugin_name, role_id, used_at)
52
+ VALUES (?, ?, ?, ?, ?, ?)
53
+ `),s=Date.now();for(let a of e){let i=a.split("/").pop()??a;r.run(yo(),t,a,i,o??null,s)}}function Rn(t){return I().prepare(`
54
+ SELECT plugin_name as pluginName, COUNT(*) as usageCount
55
+ FROM task_plugins
56
+ WHERE role_id = ?
57
+ GROUP BY plugin_path
58
+ ORDER BY usageCount DESC
59
+ `).all(t)}function Tn(t=50){return I().prepare(`
60
+ SELECT plugin_path as pluginPath, plugin_name as pluginName, COUNT(*) as usageCount, MAX(used_at) as lastUsed
61
+ FROM task_plugins
62
+ GROUP BY plugin_path
63
+ ORDER BY usageCount DESC
64
+ LIMIT ?
65
+ `).all(t)}L();import{createSdkMcpServer as wo,tool as yt}from"@anthropic-ai/claude-agent-sdk";import{z as wt}from"zod";async function xo(t){let{listChannels:e}=await import("./channels-WZOYE4O4.js"),o=e(),{listSessions:n}=await import("./session-manager-Z6MIYRD3.js"),r=[...n("active"),...n("archived")],s=o.find(l=>l.name.toLowerCase().includes(t.toLowerCase()));if(!s)return null;let i=r.find(l=>l.source.type==="channel"&&l.source.channelId===s.id&&l.source.chatId)?.source.chatId??s.config?.userId??"";return{channelId:s.id,chatId:i}}function W(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}function xt(t){let e=t?x(t):void 0,o=[...Je(t),yt("list_channels","List all available channels. Use this to discover what channels can be used with send_to_channel.",{},async()=>{let{listChannels:n}=await import("./channels-WZOYE4O4.js"),r=n();return W({channels:r.map(s=>({id:s.id,name:s.name,enabled:s.enabled,type:s.config?.type??"unknown"}))})}),yt("send_to_channel","Send a message to a connected channel by name. This role can only send to channels in its allowedChannels list (if configured).",{channelName:wt.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:wt.string().describe("The message content to send")},async n=>{if(e?.allowedChannels!==void 0){if(e.allowedChannels.length===0)return W({error:"This role is not allowed to send to any channels"});if(!e.allowedChannels.some(c=>c.toLowerCase()===n.channelName.toLowerCase()))return W({error:`Channel "${n.channelName}" is not in the allowed channels list for this role`})}let r=await xo(n.channelName);if(!r)return W({error:`Channel "${n.channelName}" not found or has no chatId available`});let{getOutboundGateway:s}=await import("./outbound-gateway-6FQRWYFF.js"),i=await s().send({channelId:r.channelId,chatId:r.chatId,content:n.message,messageType:"reply"});return W({success:i.success,channelName:n.channelName})})];return wo({name:"execution-tools",version:"1.0.0",tools:o})}Wt();Be();import{realpathSync as ko}from"fs";var b=h("execution"),St=new Set;async function vo(t,e){if(e&&St.has(e))return b.info({taskId:t,roleName:e},"Sandbox bypass: approved from session cache"),!0;let o=kt(),n={steps:[{index:0,description:"Execute task without OS sandbox \u2014 filesystem isolation not enforced",toolsNeeded:[],expectedOutput:"Task result or denial message",riskLevel:"high"}],requiredPermissions:{allowedTools:[],disallowedTools:[],approvalRequired:[],maxBudgetUsd:0,plugins:[]},overallRisk:"high"};return me({id:o,taskId:t,plan:n,status:"pending",createdAt:Date.now()}),m.emit({type:"plan_approval_request",taskId:t,planId:o,plan:n}),b.info({taskId:t,operationId:o,roleName:e},"Sandbox unavailable: awaiting privilege escalation decision"),new Promise(r=>{let a=setTimeout(()=>{l(),ge(o,"denied"),b.warn({taskId:t,operationId:o},"Sandbox bypass timed out, auto-denied"),r(!1)},12e4),i=c=>{c.planId===o&&(l(),c.decision==="allow"?(b.info({taskId:t,operationId:o},"Sandbox bypass approved by user"),e&&St.add(e),r(!0)):(b.info({taskId:t,operationId:o},"Sandbox bypass denied by user"),r(!1)))},l=()=>{clearTimeout(a),m.off("plan_approval_decision",i)};m.on("plan_approval_decision",i)})}var re=class{async execute(e,o){let n=Date.now(),r,s,a;V(e.id,{status:"running",startedAt:Date.now()}),m.emit({type:"task_status_change",taskId:e.id,oldStatus:e.status,newStatus:"running"}),b.info({taskId:e.id,roleId:e.roleId},"ExecutionManager: starting task");try{let i=e.roleId?x(e.roleId):void 0,l=ue;i&&(Ve(i),l=Ue(i.name));let c={taskId:e.id,prompt:e.prompt,roleName:i?.name,roleCagPrompt:i?.cagPrompt,allowedTools:i?.allowedTools},f=gt(c),k=ht({currentTaskId:e.id,roleId:e.roleId,taskPrompt:e.prompt}),y=e.config.approvalTimeout??300,S=async(u,p,g,A)=>{let w=kt(),_e=We(A??e.roleId,e.prompt,"medium");if(_e)return b.info({operationId:w,ruleId:_e.id,taskId:e.id},"Auto-approved by permanent rule"),{behavior:"allow",updatedInput:p};let Ie={steps:[{index:0,description:`${u}: ${JSON.stringify(p).slice(0,300)}`,toolsNeeded:[u],expectedOutput:"",riskLevel:"medium"}],requiredPermissions:{},overallRisk:"medium"};return me({id:w,taskId:e.id,roleId:A??e.roleId,plan:Ie,status:"pending",createdAt:Date.now()}),m.emit({type:"plan_approval_request",taskId:e.id,planId:w,plan:Ie}),b.info({taskId:e.id,operationId:w,toolName:u,matchedPattern:g},"Privilege escalation: awaiting user decision"),new Promise(de=>{let jt=setTimeout(()=>{Ee(),ge(w,"denied"),b.warn({taskId:e.id,operationId:w},"Privilege escalation timed out, auto-denied"),de({behavior:"deny",message:`Operation timed out after ${y}s. Auto-denied. Try a safer alternative that does not require approval.`})},y*1e3),Ce=M=>{if(M.planId===w)if(Ee(),M.decision==="allow")b.info({taskId:e.id,operationId:w,approvalType:M.approvalType},"Operation authorized by user"),de({behavior:"allow",updatedInput:p});else{let Ht=M.reason?`Operation denied by user: ${M.reason}. Try a safer alternative.`:"Operation denied by user. Try a safer alternative approach.";b.info({taskId:e.id,operationId:w,reason:M.reason??"no reason given"},"Operation denied by user"),de({behavior:"deny",message:Ht})}},Ee=()=>{clearTimeout(jt),m.off("plan_approval_decision",Ce)};m.on("plan_approval_decision",Ce)})},R=(Ne("defaults.deniedReadPaths")??[]).map(u=>{let p=j(u);try{return ko(p)}catch{return p}}),d=i?.additionalDirectories??[],E=i?Ye(i):[],N=[...d.map(u=>u.path)].filter((u,p,g)=>g.indexOf(u)===p),At=ft(u=>({disallowedTools:i?.disallowedTools,approvalRequired:i?.approvalRequired??e.config.approvalRequired,allowedBashPatterns:i?.allowedBashPatterns,deniedBashPatterns:i?.deniedBashPatterns}),S,{deniedReadPaths:R,roleScope:[l,...N]}),Mt=De({roleEnvVars:i?.envVars,taskEnv:e.config.env}),Ot=e.config.maxBudgetUsd??U().defaults.maxBudgetUsd,Lt=e.config.maxTurns??100,$t=xt(e.roleId??""),Bt=i?.mcpServers??{},Nt=e.config.mcpServers??{},Ut={...Bt,...Nt,"execution-tools":$t},le=[{path:l,mode:"rw"}];e.roleId===je&&le.push({path:ue,mode:"ro"});for(let u of d)le.push({path:u.path,mode:u.mode??"rw"});let ve=D();if(ve.platform==="none"&&!await vo(e.id,i?.name))return V(e.id,{status:"failed",error:"Sandbox unavailable; execution denied by user"}),{taskId:e.id,status:"failed",error:"Sandbox bypass denied"};let Pe=i?.permissionMode??"default",Vt=So({prompt:e.prompt,options:{cwd:l,additionalDirectories:N,systemPrompt:f,maxTurns:Lt,maxBudgetUsd:Ot,allowedTools:i?.allowedTools,model:i?.model,mcpServers:Ut,settingSources:i?.inheritUserSettings?["project","user"]:["project"],hooks:k,canUseTool:At,env:Mt,plugins:E.map(u=>({type:"local",path:u})),permissionMode:Pe,...Pe==="bypassPermissions"?{allowDangerouslySkipPermissions:!0}:{},spawnClaudeCodeProcess:u=>{let p=ve.spawn({command:u.command,args:u.args,cwd:u.cwd,env:u.env,signal:u.signal,visiblePaths:le,deniedReadPaths:R}),g=p;g.pid&&(vt(g.pid,e.roleId??"unknown",e.id),g.on("exit",()=>Pt(g.pid)));let A="";return g.stderr?.on("data",w=>{A+=w.toString()}),g.on("exit",w=>{w!==null&&w!==0&&A.includes("sandbox")&&(b.error({taskId:e.id,roleId:e.roleId,exitCode:w,stderr:A.slice(0,500)},"Sandbox wrapper failed \u2014 task process exited before execution"),se({roleId:e.roleId??"unknown",taskId:e.id,path:l,operation:`sandbox_init_failure:exit_${w}`,timestamp:Date.now()}))}),p},stderr:u=>{u.trim()&&b.debug({stderr:u.trim().slice(0,500)},"ExecutionManager SDK stderr")}}}),Y="",Re=0,Te=()=>{b.warn({taskId:e.id},"ExecutionManager: abort signal received")};o&&o.addEventListener("abort",Te);try{for await(let u of Vt){let p=u;if(b.debug({eventType:p.type,taskId:e.id},"ExecutionManager SDK event"),p.type==="result"&&typeof p.result=="string"&&(Y=p.result),p.type==="result"){Re++,typeof p.total_cost_usd=="number"&&(s=p.total_cost_usd);let g=p.usage;g?.input_tokens!==void 0&&g?.output_tokens!==void 0&&(r={input:g.input_tokens,output:g.output_tokens})}if(p.token_usage){let g=p.token_usage;g.input_tokens!==void 0&&g.output_tokens!==void 0&&(r={input:g.input_tokens,output:g.output_tokens})}}}finally{o&&o.removeEventListener("abort",Te)}a=Re;let ce=Date.now()-n;return V(e.id,{status:"completed",result:Y,completedAt:Date.now(),costUsd:s,tokenUsage:r,numTurns:a,totalDurationMs:ce}),m.emit({type:"task_status_change",taskId:e.id,oldStatus:"running",newStatus:"completed"}),m.emit({type:"task_complete_event",taskId:e.id,result:Y}),E.length>0&&bt(e.id,E,e.roleId),b.info({taskId:e.id,durationMs:ce,costUsd:s},"ExecutionManager: task completed"),{taskId:e.id,status:"completed",result:Y,costUsd:s,tokenUsage:r,numTurns:a,durationMs:ce}}catch(i){let l=i instanceof Error?i.message:String(i),c=Date.now()-n;return(l.includes("Prompt is too long")||l.includes("prompt is too long"))&&b.warn({taskId:e.id,error:l},"Task prompt exceeds model context window \u2014 task failed"),V(e.id,{status:"failed",error:l,completedAt:Date.now(),totalDurationMs:c}),m.emit({type:"task_status_change",taskId:e.id,oldStatus:"running",newStatus:"failed"}),m.emit({type:"task_complete_event",taskId:e.id,error:l}),b.error({taskId:e.id,error:i},"ExecutionManager: task failed"),{taskId:e.id,status:"failed",error:l,durationMs:c}}}};_();var v=h("execution-pool"),we=new Map;function vt(t,e,o){we.set(t,{roleId:e,taskId:o})}function Pt(t){we.delete(t)}function xe(t){return we.get(t)}var Rt=class{slots;running=!1;pollTimeoutId=null;executor;constructor(e,o){this.slots=Array.from({length:e},(n,r)=>({index:r,taskId:null,abortController:null})),this.executor=o??new re}async start(){if(this.running)return;this.running=!0,m.on("task_created",n=>{this.onTaskCreated(n.taskId)}),m.on("task_status_change",n=>{n.newStatus==="pending"&&this.pickupPendingTasks()});let o=U().execution?.pollIntervalMs??3e4;this.pollTimeoutId=setTimeout(this.poll,o),v.info({maxConcurrent:this.slots.length},"ExecutionPool started")}stop(){this.running=!1,this.pollTimeoutId&&(clearTimeout(this.pollTimeoutId),this.pollTimeoutId=null);for(let e of this.slots)e.abortController&&(e.abortController.abort(),e.taskId=null,e.abortController=null);v.info("ExecutionPool stopped")}poll=()=>{if(!this.running)return;this.pickupPendingTasks();let o=U().execution?.pollIntervalMs??3e4;this.pollTimeoutId=setTimeout(this.poll,o)};async onTaskCreated(e){this.running&&await this.pickupPendingTasks()}async pickupPendingTasks(){if(!this.running)return;let e=this.slots.find(i=>i.taskId===null);if(!e){v.debug("No free slots available");return}let o=K("pending");if(o.length===0)return;let r=[...o].sort((i,l)=>i.createdAt-l.createdAt)[0];e.taskId=r.id,e.abortController=new AbortController;let s=e.index,a=r.id;v.info({slotIndex:s,taskId:a},"ExecutionPool: claimed slot for task"),this.emitSlotChange(),this.executeTask(r,s).catch(i=>{v.error({taskId:a,error:i},"ExecutionPool: executeTask failed unexpectedly")})}async executeTask(e,o){let n=this.slots[o];if(!n)return;let r="completed";try{m.emit({type:"execution_task_start",taskId:e.id,slotIndex:o});let s=await this.executor.execute(e,n.abortController?.signal);r=s.status,v.info({taskId:e.id,status:s.status,slotIndex:o},"ExecutionPool: task finished")}finally{n.taskId=null,n.abortController=null,m.emit({type:"execution_task_end",taskId:e.id,slotIndex:o,status:r}),this.emitSlotChange(),this.runPostCompletion(e.id,e.roleId).catch(s=>{v.error({taskId:e.id,error:s},"Post-completion processing failed (non-fatal)")}),this.running&&this.pickupPendingTasks()}}emitSlotChange(){let e=this.slots.filter(r=>r.taskId!==null).length,o=K("pending");m.emit({type:"execution_slot_change",active:e,max:this.slots.length,queued:o.length});let n=qe();m.emit({type:"stats_update",activeTasks:e,queuedTasks:o.length,totalCostToday:Oe(n)})}async runPostCompletion(e,o){if(o){try{let{processTaskCompletion:n}=await import("./memory-extractor-FUOJ5D77.js"),r=await n(e,o);r>0&&v.debug({taskId:e,roleId:o,memoriesStored:r},"Post-completion: memories extracted")}catch(n){v.error({taskId:e,roleId:o,error:n},"Post-completion: memory extraction failed")}try{let{processTaskReview:n}=await import("./learner-B6XVQKBF.js");await n(e)}catch(n){v.error({taskId:e,roleId:o,error:n},"Post-completion: task review failed")}try{let{evaluateTaskCompletion:n}=await import("./audit-manager-QDFDBK4E.js");n(e,o)}catch(n){v.error({taskId:e,roleId:o,error:n},"Post-completion: audit evaluation failed")}}}getStatus(){let e=this.slots.filter(n=>n.taskId!==null).length,o=K("pending");return{active:e,max:this.slots.length,queued:o.length}}isHealthy(){return this.running}releaseSlot(e){let o=this.slots.find(n=>n.taskId===e);o&&(v.warn({taskId:e,slotIndex:o.index},"ExecutionPool: force-releasing slot"),o.abortController&&o.abortController.abort(),o.taskId=null,o.abortController=null,this.emitSlotChange(),this.running&&this.pickupPendingTasks())}};_();var P=h("audit"),Po="sandbox_violation",q=new Map,Se=1440*60*1e3,ie=[],Ro=100;function ke(t){let e=t.roleId,o=q.get(e)??{count:0,timestamps:[]};o.count++,o.timestamps.push(t.timestamp);let n=Date.now()-Se;if(o.timestamps=o.timestamps.filter(r=>r>=n),q.set(e,o),o.count%100===0)for(let[r,s]of q.entries()){let a=Date.now()-Se;s.timestamps.filter(i=>i>=a).length===0&&q.delete(r)}ie.push(t),ie.length>Ro&&ie.shift();try{He({id:`sv-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,ruleId:void 0,taskId:t.taskId,status:"delivered",target:{type:"channel",channelId:"audit"},content:"",attempts:1,messageType:Po,source:"audit",createdAt:t.timestamp,deliveredAt:t.timestamp,expiresAt:t.timestamp+864e5,error:`${t.operation} on ${t.path}`})}catch(r){P.error({error:r},"Failed to record violation to delivery_log")}try{let r=x(t.roleId);$({timestamp:t.timestamp,oldRules:"sandbox_violation",newRules:`${t.operation} on ${t.path}`,diff:`Sandbox violation: ${t.operation} on ${t.path} (taskId=${t.taskId??"unknown"})`,roleId:t.roleId,source:"audit"})}catch(r){P.error({error:r},"Failed to record violation to evolution_audit")}m.emit({type:"sandbox_violation",roleId:t.roleId,taskId:t.taskId,path:t.path,operation:t.operation,timestamp:t.timestamp})}async function Ct(){let t=D();if(t.platform==="none")return P.info("Sandbox platform is 'none'; violation watcher not started"),()=>{};if(!await t.isAvailable())return P.warn({platform:t.platform},"Sandbox platform detected but not available; violation watcher not started"),()=>{};let o=null;return t.platform==="sandbox-exec"?o=To():t.platform==="landlock"&&(o=await _o()),()=>{if(o){let n=o;o=null,n.kill("SIGTERM");let r=setTimeout(()=>{try{n.kill("SIGKILL")}catch{}},2e3);n.on("exit",()=>clearTimeout(r))}P.info("Violation watcher stopped")}}function To(){let t=It("log",["stream","--predicate",'subsystem == "com.apple.sandbox"',"--style","ndjson","--signal","exit"],{stdio:["ignore","pipe","pipe"]});return t.stdout?.on("data",e=>{let o=e.toString().split(`
66
+ `).filter(Boolean);for(let n of o)try{let r=JSON.parse(n),s=r.eventMessage??r.message??"";if(s.includes("deny")&&(s.includes("file-read")||s.includes("file-write"))){let a=Io(r,s);a&&ke(a)}}catch{}}),t.stderr?.on("data",e=>{P.debug({msg:e.toString()},"log stream stderr")}),t.on("error",e=>{P.warn({error:e},"macOS violation watcher failed to start")}),P.info("macOS sandbox violation watcher started (log stream)"),t}async function _o(){let t=await Tt("journalctl",["-kf","--no-pager","-o","short","--grep","landlock"]);if(t)return _t(t),P.info("Linux violation watcher started (journalctl -kf)"),t;let e=await Tt("dmesg",["-w","-t"]);return e?(_t(e),P.info("Linux violation watcher started (dmesg -w)"),e):(P.warn("Linux violation watcher unavailable: neither journalctl nor dmesg accessible. Sandbox enforcement still active; monitoring disabled."),null)}async function Tt(t,e){return new Promise(o=>{let n=It(t,e,{stdio:["ignore","pipe","pipe"]}),r=setTimeout(()=>o(n),500);n.on("error",()=>{clearTimeout(r),o(null)}),n.on("exit",s=>{s!==0&&(clearTimeout(r),o(null))})})}function _t(t){t.stdout?.on("data",e=>{let o=e.toString().split(`
67
+ `).filter(Boolean);for(let n of o)if(n.includes("landlock")&&n.includes("denied")){let r=Co(n);r&&ke(r)}}),t.stderr?.on("data",e=>{P.debug({msg:e.toString().trim()},"Linux watcher stderr")})}function Io(t,e){let o=e.match(/(?:path|file)=["']([^"']+)["']/),n=e.match(/deny\s+(file-read|file-write|file-[^\s]+)/),r=o?.[1],s=n?.[1]??"unknown";if(!r)return null;let a=typeof t.processID=="number"?t.processID:void 0,i=a?xe(a):void 0;return{roleId:i?.roleId??"unknown",taskId:i?.taskId,path:r,operation:s,timestamp:Date.now(),count:1}}function Co(t){let e=t.match(/path="([^"]+)"/)??t.match(/\/[\w\-\.\/\+ ]+/g),o=t.match(/deny\s+(\w+)/),n=t.match(/pid=(\d+)/),r=Array.isArray(e)?e[e.length-1]:e?.[1],s=o?.[1]??"unknown";if(!r)return null;let a=n?parseInt(n[1],10):void 0,i=a?xe(a):void 0;return{roleId:i?.roleId??"unknown",taskId:i?.taskId,path:r,operation:s,timestamp:Date.now(),count:1}}function se(t){ke({roleId:t.roleId,taskId:t.taskId,path:t.path,operation:t.operation,timestamp:t.timestamp,count:1})}function Et(t){let e=q.get(t);if(!e)return 0;let o=Date.now()-Se;return e.timestamps.filter(n=>n>=o).length}function Dt(){return[...ie]}L();_();var G=h("audit"),Eo=.4,Do=1440*60*1e3,J=null,ae=null;function Tr(t,e,o=Eo){let n=x(e);if(!n||n.status==="retired"||n.status==="inactive"||n.status==="dead")return;let r=et(e,t);O(e,{performanceScore:r}),rt(e,r,o)?G.info({roleId:e,emaScore:r},"Probation role graduated"):r<o&&ot(e,r,o)&&nt(e)}async function _r(){J===null&&(J=setInterval(()=>{G.info("Running daily diagnostic reports");let t=pe(void 0,1e3);for(let e of t)if(!(e.status==="retired"||e.status==="inactive"))try{Q(e.id)}catch(o){G.error({roleId:e.id,error:o},"Daily diagnostic failed")}},Do),ae=await Ct(),G.info("AuditManager started"))}function Ir(){J!==null&&(clearInterval(J),J=null),ae!==null&&(ae(),ae=null),G.info("AuditManager stopped")}function Cr(t){se(t)}async function Er(){let t=D(),e=pe(void 0,1e3),n=Date.now()-1440*60*1e3,r=Dt(),s=r.filter(l=>l.timestamp>=n).length,a=e.map(l=>{let c=r.filter(k=>k.roleId===l.id),f=c[c.length-1];return{roleId:l.id,roleName:l.name,sandboxed:t.platform!=="none",violationCount:Et(l.id),lastViolation:f?.timestamp}}),i=await mt();return{platform:t.platform,available:i,violationCount24h:s,rolePostures:a}}export{X as a,ze as b,ft as c,ht as d,D as e,mt as f,Rn as g,Tn as h,Tr as i,_r as j,Ir as k,Cr as l,Er as m,Rt as n};
@@ -1,4 +1,4 @@
1
- import{a as S,b as P}from"./chunk-CDVIT7L5.js";import{a as k,b as m}from"./chunk-3RAFA6QK.js";import{a as u}from"./chunk-L7JP7DUO.js";import{p as I}from"./chunk-4TCP2AT7.js";import{a as C,b as c,d as y,f as R}from"./chunk-6DXNXLYG.js";import{d as T}from"./chunk-JTMFEUDA.js";import{h as x,k as J}from"./chunk-B4WHT7DX.js";import{c as h,h as b}from"./chunk-INNDBLZE.js";b();J();import{v4 as l}from"uuid";import{CronExpressionParser as D}from"cron-parser";b();import{v4 as M}from"uuid";var g=h("scheduler"),v=class{maxRetries=3;baseDelayMs=1e3;async execute(e,t){let o=T(),r={timeout:e.config?.timeout??o.timeout,approvalRequired:o.approvalRequired,approvalTimeout:o.approvalTimeout,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:r,rolePreference:e.rolePreference,deliverTo:e.deliverTo,reportTo:e.reportTo},i=this.sortSteps(e.steps);for(let a of i){try{await this.executeStep(a,s)}catch(p){g.error({stepId:a.id,error:p},"Workflow step failed");break}if(s.stepResults.get(a.id)?.status==="failed"){g.warn({stepId:a.id},"Workflow step failed, workflow aborted");break}}g.info({executionId:t,completedSteps:s.stepResults.size,totalSteps:i.length},"Workflow completed")}sortSteps(e){let t=new Set,o=[],r=new Map(e.map(i=>[i.id,i])),s=i=>{if(!t.has(i.id)){if(t.add(i.id),i.dependsOn)for(let a of i.dependsOn){let d=r.get(a);d&&s(d)}o.push(i)}};for(let i of e)s(i);return o}async executeStep(e,t){let o=this.resolveVariables(e.prompt,t.stepResults),r=M();k({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}),g.debug({stepId:e.id,taskId:r},"Created workflow step as task"),u.emit({type:"task_created",taskId:r});let s=await this.executeWithRetry(r,e.id),i=m(r);t.stepResults.set(e.id,{stepId:e.id,taskId:r,status:s==="completed"?"completed":"failed",result:i?.result,error:i?.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 s=this.baseDelayMs*Math.pow(2,o-1);g.info({stepId:t,attempt:o,maxRetries:this.maxRetries,delayMs:s},"Workflow step failed, retrying"),await this.sleep(s)}}return"failed"}waitForTaskCompletion(e,t=6e5){return new Promise(o=>{let r=Date.now(),s=()=>{if(Date.now()-r>t){o("failed");return}let i=m(e);if(!i){o("failed");return}if(i.status==="completed"){o("completed");return}if(i.status==="failed"||i.status==="cancelled"){o("failed");return}setTimeout(s,500)};s()})}sleep(e){return new Promise(t=>setTimeout(t,e))}};var n=h("scheduler"),w="ai-hourly-digest";function O(){if(c(w)){n.debug({templateId:w},"Built-in template already exists");return}let e={id:w,name:"AI Hourly Digest",description:"\u6BCF\u5C0F\u65F6\u641C\u7D22 AI \u524D\u6CBF\u6587\u7AE0\uFF0C\u603B\u7ED3\u540E\u4FDD\u5B58\u5230 Omnifocus",trigger:{type:"cron",cron:"0 * * * *"},enabled:!0,steps:[{id:"search_ai_news",prompt:`\u641C\u7D22\u8FC7\u53BB 24 \u5C0F\u65F6\u5185\u5173\u4E8E AI/\u4EBA\u5DE5\u667A\u80FD\u7684\u6700\u65B0\u524D\u6CBF\u6587\u7AE0\u3002
1
+ import{a as S,b as P}from"./chunk-CDVIT7L5.js";import{a as k,b as m}from"./chunk-W3554FQ7.js";import{a as u}from"./chunk-L7JP7DUO.js";import{p as I}from"./chunk-4TCP2AT7.js";import{a as C,b as c,d as y,f as R}from"./chunk-6DXNXLYG.js";import{d as T}from"./chunk-SBX3HMDA.js";import{h as x,k as J}from"./chunk-B4WHT7DX.js";import{c as h,h as b}from"./chunk-INNDBLZE.js";b();J();import{v4 as l}from"uuid";import{CronExpressionParser as D}from"cron-parser";b();import{v4 as M}from"uuid";var g=h("scheduler"),v=class{maxRetries=3;baseDelayMs=1e3;async execute(e,t){let o=T(),r={timeout:e.config?.timeout??o.timeout,approvalRequired:o.approvalRequired,approvalTimeout:o.approvalTimeout,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:r,rolePreference:e.rolePreference,deliverTo:e.deliverTo,reportTo:e.reportTo},i=this.sortSteps(e.steps);for(let a of i){try{await this.executeStep(a,s)}catch(p){g.error({stepId:a.id,error:p},"Workflow step failed");break}if(s.stepResults.get(a.id)?.status==="failed"){g.warn({stepId:a.id},"Workflow step failed, workflow aborted");break}}g.info({executionId:t,completedSteps:s.stepResults.size,totalSteps:i.length},"Workflow completed")}sortSteps(e){let t=new Set,o=[],r=new Map(e.map(i=>[i.id,i])),s=i=>{if(!t.has(i.id)){if(t.add(i.id),i.dependsOn)for(let a of i.dependsOn){let d=r.get(a);d&&s(d)}o.push(i)}};for(let i of e)s(i);return o}async executeStep(e,t){let o=this.resolveVariables(e.prompt,t.stepResults),r=M();k({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}),g.debug({stepId:e.id,taskId:r},"Created workflow step as task"),u.emit({type:"task_created",taskId:r});let s=await this.executeWithRetry(r,e.id),i=m(r);t.stepResults.set(e.id,{stepId:e.id,taskId:r,status:s==="completed"?"completed":"failed",result:i?.result,error:i?.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 s=this.baseDelayMs*Math.pow(2,o-1);g.info({stepId:t,attempt:o,maxRetries:this.maxRetries,delayMs:s},"Workflow step failed, retrying"),await this.sleep(s)}}return"failed"}waitForTaskCompletion(e,t=6e5){return new Promise(o=>{let r=Date.now(),s=()=>{if(Date.now()-r>t){o("failed");return}let i=m(e);if(!i){o("failed");return}if(i.status==="completed"){o("completed");return}if(i.status==="failed"||i.status==="cancelled"){o("failed");return}setTimeout(s,500)};s()})}sleep(e){return new Promise(t=>setTimeout(t,e))}};var n=h("scheduler"),w="ai-hourly-digest";function O(){if(c(w)){n.debug({templateId:w},"Built-in template already exists");return}let e={id:w,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
2
 
3
3
  \u641C\u7D22\u6765\u6E90:
4
4
  1. Hacker News AI \u677F\u5757 (https://news.ycombinator.com/front?day=1)
@@ -1,3 +1,3 @@
1
- import{b as y}from"./chunk-2HN2TSP6.js";import{b as S}from"./chunk-EGS6U3V5.js";import{f as C}from"./chunk-6YURWVQG.js";import{b as g}from"./chunk-3RAFA6QK.js";import{b as v}from"./chunk-AJVN3KPM.js";import{e as m}from"./chunk-AR2IZMM2.js";import{b as R}from"./chunk-SWPXG2CY.js";import{a as k,b as P,c as o,d as h,e as T,f as x,g as E}from"./chunk-OFOVSC72.js";import{a as f}from"./chunk-L7JP7DUO.js";import{c as w,h as _}from"./chunk-INNDBLZE.js";_();import{v4 as M}from"uuid";var l=w("admin"),I=new Map,u=null,p=null,c=null,D=class{constructor(){f.on("task_status_change",e=>{(e.newStatus==="completed"||e.newStatus==="failed")&&this.handleTaskStatusChange(e.taskId,e.newStatus).catch(n=>{l.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=>{l.error({taskId:e.taskId,error:n},"Delivery processing failed (plan_approval)")})}),l.info("DeliveryEngine initialized")}async handlePlanApprovalRequest(e,n,r){let t=g(e),i=this.getSourceChannelForTask(e);if(i){let d=y(r),{sendApprovalToChannel:b}=await import("./approval-handler-JYIS2PKQ.js");await b(i.channelId,i.chatId,n,e,d)}let a=y(r)+`
1
+ import{b as y}from"./chunk-2HN2TSP6.js";import{b as S}from"./chunk-EGS6U3V5.js";import{f as C}from"./chunk-6YURWVQG.js";import{b as g}from"./chunk-W3554FQ7.js";import{b as v}from"./chunk-AJVN3KPM.js";import{e as m}from"./chunk-AR2IZMM2.js";import{b as R}from"./chunk-SWPXG2CY.js";import{a as k,b as P,c as o,d as h,e as T,f as x,g as E}from"./chunk-OFOVSC72.js";import{a as f}from"./chunk-L7JP7DUO.js";import{c as w,h as _}from"./chunk-INNDBLZE.js";_();import{v4 as M}from"uuid";var l=w("admin"),I=new Map,u=null,p=null,c=null,D=class{constructor(){f.on("task_status_change",e=>{(e.newStatus==="completed"||e.newStatus==="failed")&&this.handleTaskStatusChange(e.taskId,e.newStatus).catch(n=>{l.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=>{l.error({taskId:e.taskId,error:n},"Delivery processing failed (plan_approval)")})}),l.info("DeliveryEngine initialized")}async handlePlanApprovalRequest(e,n,r){let t=g(e),i=this.getSourceChannelForTask(e);if(i){let d=y(r),{sendApprovalToChannel:b}=await import("./approval-handler-JYIS2PKQ.js");await b(i.channelId,i.chatId,n,e,d)}let a=y(r)+`
2
2
 
3
3
  Task: ${e}`;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=C(e,n);if(i.length!==0){l.debug({eventType:e,ruleCount:i.length,taskId:t},"Matched delivery rules");for(let a of i){if(!this.checkRateLimit(a)){l.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:M(),ruleId:a.id,taskId:t,status:"pending",target:a.target,content:r,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+k,source:"rule"};P(d),await this.attemptDelivery(d,a)}}}async attemptDeliveryPublic(e,n){return this.attemptDelivery(e,n)}async attemptDelivery(e,n){let r=S();try{if(e.target.type==="channel"){let t=e.target.chatId;!t&&e.target.channelId&&(t=R(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),l.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),l.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),l.warn({entryId:e.id,error:i},"Delivery attempt failed")}}checkRateLimit(e){let n=Date.now(),r=6e4,t=I.get(e.id);t||(t=[],I.set(e.id,t));let i=n-r;for(;t.length>0&&t[0]<i;)t.shift();return t.length>=e.maxPerMinute?!1:(t.push(n),!0)}isOriginChannel(e,n){try{if(n.type!=="channel"||!n.channelId)return!1;let r=m(e);if(!r)return!1;let t=v(r.sessionId);return t?t.source.type==="channel"&&t.source.channelId===n.channelId&&(!n.chatId||t.source.chatId===n.chatId):!1}catch{return!1}}async retryPending(){let e=T("rule",50),n=x("rule",50),r=[...e,...n];if(r.length!==0){l.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 $(){return c}function H(){c||(c=new D,u=setInterval(()=>{c?.retryPending().catch(s=>{l.error({error:s},"Delivery retry scan failed")})},6e4),p=setInterval(()=>{try{let s=E();s>0&&l.info({cleaned:s},"Expired delivery log entries cleaned up")}catch(s){l.error({error:s},"Delivery cleanup failed")}},36e5),l.info("DeliveryEngine started with retry (60s) and cleanup (1h) timers"))}function J(){u&&(clearInterval(u),u=null),p&&(clearInterval(p),p=null),c=null,I.clear(),l.info("DeliveryEngine stopped")}export{D as a,$ as b,H as c,J as d};
@@ -1 +1 @@
1
- import{a as h,b as u,c,d as m,e as v,f as x}from"./chunk-AJVN3KPM.js";import{b as S,d as y}from"./chunk-AR2IZMM2.js";import{a as i}from"./chunk-L7JP7DUO.js";import{a as l}from"./chunk-2CMR5AG7.js";import{a as C}from"./chunk-4TCP2AT7.js";import{e as p}from"./chunk-JTMFEUDA.js";import{v4 as D}from"uuid";import{v4 as I}from"uuid";function _(e){if(e.length<20)return null;let t=e.trim();return t.length>300?{content:`User request: ${t.slice(0,280)}...`,importance:3,type:"thought"}:{content:`User request: ${t}`,importance:3,type:"thought"}}function b(e){if(e.length<20)return null;let t=e.trim();return t.length>400?{content:`Assistant response: ${t.slice(0,370)}...`,importance:2,type:"event"}:{content:`Assistant response: ${t}`,importance:2,type:"event"}}function N(e){let t=S(e,200,0),s=[];for(let o of t){let r=o.role==="user"?_(o.content):b(o.content);r&&s.push(r)}return{facts:s}}function $(e){let t=e.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(s=>s.length>2);return[...new Set(t)].slice(0,20)}async function A(e,t){let{facts:s}=N(e),o=0;for(let r of s){let f=r.content.slice(0,500),g;try{g=await l(f)}catch{}let M=$(f),T={id:I(),roleId:t,type:r.type,content:f,embedding:g,keywords:M,importance:r.importance,sourceType:"session_archive",createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"episodic"};C(T),o++}return o}var n=new Map,a;function w(e){return`${e.type}:${e.channelId??""}:${e.chatId??""}`}function F(){n.clear();let e=m("active",1e3);for(let t of e)n.set(t.id,t)}function Q(e,t){let s=Date.now(),o={id:D(),status:"active",source:e,createdAt:s,lastActiveAt:s,messageCount:0};return h(o),n.set(o.id,o),i.emit({type:"session_created",session:o}),o}function V(e){for(let s of n.values())if(w(s.source)===w(e))return s;let t=v(e);return t&&n.set(t.id,t),t}function B(e){let t=n.get(e);return t||u(e)}function E(e){let t=Date.now();c(e,{status:"archived",archivedAt:t}),p().archiveExtractMemory&&u(e)&&A(e,"role-chat-manager").catch(()=>{}),n.delete(e),i.emit({type:"session_archived",sessionId:e})}function W(e){c(e,{status:"active",archivedAt:void 0});let t=u(e);return t&&(n.set(t.id,t),i.emit({type:"session_restored",session:t})),t}function X(e){y(e),x(e),n.delete(e),i.emit({type:"session_deleted",sessionId:e})}function Y(e){let t=Date.now();c(e,{lastActiveAt:t});let s=n.get(e);s&&(s.lastActiveAt=t)}function Z(e){let t=B(e);if(t){let s=t.messageCount+1;c(e,{messageCount:s});let o=n.get(e);o&&(o.messageCount=s)}}function ee(e){return m(e)}function P(){let t=p().sessionTimeoutMinutes*60*1e3,s=Date.now();for(let o of n.values())if(s-o.lastActiveAt>t)try{E(o.id)}catch{}}function R(e=6e4){d(),a=setInterval(P,e)}function d(){a&&(clearInterval(a),a=void 0)}function te(){return a}function se(){F(),R()}function oe(){d(),n.clear()}function ne(){d(),n.clear()}export{F as a,Q as b,V as c,B as d,E as e,W as f,X as g,Y as h,Z as i,ee as j,R as k,d as l,te as m,se as n,oe as o,ne as p};
1
+ import{a as h,b as u,c,d as m,e as v,f as x}from"./chunk-AJVN3KPM.js";import{b as S,d as y}from"./chunk-AR2IZMM2.js";import{a as i}from"./chunk-L7JP7DUO.js";import{a as l}from"./chunk-2CMR5AG7.js";import{a as C}from"./chunk-4TCP2AT7.js";import{e as p}from"./chunk-SBX3HMDA.js";import{v4 as D}from"uuid";import{v4 as I}from"uuid";function _(e){if(e.length<20)return null;let t=e.trim();return t.length>300?{content:`User request: ${t.slice(0,280)}...`,importance:3,type:"thought"}:{content:`User request: ${t}`,importance:3,type:"thought"}}function b(e){if(e.length<20)return null;let t=e.trim();return t.length>400?{content:`Assistant response: ${t.slice(0,370)}...`,importance:2,type:"event"}:{content:`Assistant response: ${t}`,importance:2,type:"event"}}function N(e){let t=S(e,200,0),s=[];for(let o of t){let r=o.role==="user"?_(o.content):b(o.content);r&&s.push(r)}return{facts:s}}function $(e){let t=e.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(s=>s.length>2);return[...new Set(t)].slice(0,20)}async function A(e,t){let{facts:s}=N(e),o=0;for(let r of s){let f=r.content.slice(0,500),g;try{g=await l(f)}catch{}let M=$(f),T={id:I(),roleId:t,type:r.type,content:f,embedding:g,keywords:M,importance:r.importance,sourceType:"session_archive",createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"episodic"};C(T),o++}return o}var n=new Map,a;function w(e){return`${e.type}:${e.channelId??""}:${e.chatId??""}`}function F(){n.clear();let e=m("active",1e3);for(let t of e)n.set(t.id,t)}function Q(e,t){let s=Date.now(),o={id:D(),status:"active",source:e,createdAt:s,lastActiveAt:s,messageCount:0};return h(o),n.set(o.id,o),i.emit({type:"session_created",session:o}),o}function V(e){for(let s of n.values())if(w(s.source)===w(e))return s;let t=v(e);return t&&n.set(t.id,t),t}function B(e){let t=n.get(e);return t||u(e)}function E(e){let t=Date.now();c(e,{status:"archived",archivedAt:t}),p().archiveExtractMemory&&u(e)&&A(e,"role-chat-manager").catch(()=>{}),n.delete(e),i.emit({type:"session_archived",sessionId:e})}function W(e){c(e,{status:"active",archivedAt:void 0});let t=u(e);return t&&(n.set(t.id,t),i.emit({type:"session_restored",session:t})),t}function X(e){y(e),x(e),n.delete(e),i.emit({type:"session_deleted",sessionId:e})}function Y(e){let t=Date.now();c(e,{lastActiveAt:t});let s=n.get(e);s&&(s.lastActiveAt=t)}function Z(e){let t=B(e);if(t){let s=t.messageCount+1;c(e,{messageCount:s});let o=n.get(e);o&&(o.messageCount=s)}}function ee(e){return m(e)}function P(){let t=p().sessionTimeoutMinutes*60*1e3,s=Date.now();for(let o of n.values())if(s-o.lastActiveAt>t)try{E(o.id)}catch{}}function R(e=6e4){d(),a=setInterval(P,e)}function d(){a&&(clearInterval(a),a=void 0)}function te(){return a}function se(){F(),R()}function oe(){d(),n.clear()}function ne(){d(),n.clear()}export{F as a,Q as b,V as c,B as d,E as e,W as f,X as g,Y as h,Z as i,ee as j,R as k,d as l,te as m,se as n,oe as o,ne as p};
@@ -1 +1 @@
1
- import{a as i}from"./chunk-6KLG4APZ.js";import{c as p}from"./chunk-7IFLU3CY.js";import{d as c}from"./chunk-6HD6NYIB.js";import{f as d,h as R}from"./chunk-WBAPIPST.js";import{c as g,h as y}from"./chunk-INNDBLZE.js";R();import{readFileSync as P,existsSync as _}from"fs";import{resolve as O}from"path";import{homedir as E}from"os";import{parse as w}from"yaml";y();var T=g("config");function S(e){return e.replace(/\$\{(\w+)}/g,(t,r)=>process.env[r]??"")}function h(e){return e.startsWith("~/")?O(E(),e.slice(2)):e}function u(e){if(typeof e=="string")return S(e);if(Array.isArray(e))return e.map(u);if(e!==null&&typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))t[r]=u(n);return t}return e}function m(e,t){let r={...e};for(let n of Object.keys(t)){let s=t[n],o=e[n];s!==null&&typeof s=="object"&&!Array.isArray(s)&&o!==null&&typeof o=="object"&&!Array.isArray(o)?r[n]=m(o,s):r[n]=s}return r}function v(e){return e.defaults.deniedReadPaths&&(e.defaults.deniedReadPaths=e.defaults.deniedReadPaths.map(h)),e.defaults.sensitivePaths&&!e.defaults.deniedReadPaths&&(T.warn("config.defaults.sensitivePaths is deprecated \u2014 use config.defaults.deniedReadPaths instead. Values have been migrated automatically."),e.defaults.deniedReadPaths=e.defaults.sensitivePaths.map(h)),e}function k(){let e={};for(let t of process.argv.slice(2)){let r=t.match(/^--([a-z-]+)=(.+)$/);r&&(e[r[1]]=r[2])}return e}function A(e){let t=process.env.ADAM_PORT;t&&(e.server.port=parseInt(t,10));let r=process.env.ANTHROPIC_MODEL;r&&(e.defaults.model=r);let n=process.env.ADAM_API_KEY;return n&&(e.server.apiKey=n),e}function C(e){let t=k();return t.port&&(e.server.port=parseInt(t.port,10)),t.host&&(e.server.host=t.host),t.timeout&&(e.defaults.timeout=parseInt(t.timeout,10)),t["api-key"]&&(e.server.apiKey=t["api-key"]),e}function D(e){let t=e??d,r={};if(_(t)){let f=P(t,"utf-8"),l=w(f);l&&(r=u(l))}let n=m(i,r),s=A(n),o=C(s);return v(o)}function I(){let e=JSON.parse(JSON.stringify(i)),t=A(e),r=C(t);return v(r)}function V(){let e={},t={ANTHROPIC_API_KEY:"anthropic.apiKey",ANTHROPIC_BASE_URL:"anthropic.baseUrl",ANTHROPIC_MODEL:"anthropic.model",ANTHROPIC_DEFAULT_OPUS_MODEL:"anthropic.defaultOpusModel",ANTHROPIC_DEFAULT_SONNET_MODEL:"anthropic.defaultSonnetModel",ANTHROPIC_DEFAULT_HAIKU_MODEL:"anthropic.defaultHaikuModel",ANTHROPIC_SMALL_FAST_MODEL:"anthropic.smallFastModel",ADAM_PORT:"server.port",ADAM_API_KEY:"server.apiKey"},r={};for(let[s,o]of Object.entries(t)){let a=process.env[s];if(a&&a.length>0)if(o==="server.port"){let f=parseInt(a,10);isNaN(f)||(e[o]=f)}else e[o]=a}let n=p();if(n)for(let[s,o]of Object.entries(n))s in t||s.startsWith("ANTHROPIC_")||s.startsWith("ADAM_")||(r[s]=o);return Object.keys(r).length>0&&(e["defaults.env"]=r),e}function j(){try{return c().defaults}catch{return i.defaults}}function W(){try{return c().chat??i.chat}catch{return i.chat}}export{D as a,I as b,V as c,j as d,W as e};
1
+ import{a as i}from"./chunk-ZM6YED5F.js";import{c as p}from"./chunk-7IFLU3CY.js";import{d as c}from"./chunk-6HD6NYIB.js";import{f as d,h as R}from"./chunk-WBAPIPST.js";import{c as g,h as y}from"./chunk-INNDBLZE.js";R();import{readFileSync as P,existsSync as _}from"fs";import{resolve as O}from"path";import{homedir as E}from"os";import{parse as w}from"yaml";y();var T=g("config");function S(e){return e.replace(/\$\{(\w+)}/g,(t,r)=>process.env[r]??"")}function h(e){return e.startsWith("~/")?O(E(),e.slice(2)):e}function u(e){if(typeof e=="string")return S(e);if(Array.isArray(e))return e.map(u);if(e!==null&&typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))t[r]=u(n);return t}return e}function m(e,t){let r={...e};for(let n of Object.keys(t)){let s=t[n],o=e[n];s!==null&&typeof s=="object"&&!Array.isArray(s)&&o!==null&&typeof o=="object"&&!Array.isArray(o)?r[n]=m(o,s):r[n]=s}return r}function v(e){return e.defaults.deniedReadPaths&&(e.defaults.deniedReadPaths=e.defaults.deniedReadPaths.map(h)),e.defaults.sensitivePaths&&!e.defaults.deniedReadPaths&&(T.warn("config.defaults.sensitivePaths is deprecated \u2014 use config.defaults.deniedReadPaths instead. Values have been migrated automatically."),e.defaults.deniedReadPaths=e.defaults.sensitivePaths.map(h)),e}function k(){let e={};for(let t of process.argv.slice(2)){let r=t.match(/^--([a-z-]+)=(.+)$/);r&&(e[r[1]]=r[2])}return e}function A(e){let t=process.env.ADAM_PORT;t&&(e.server.port=parseInt(t,10));let r=process.env.ANTHROPIC_MODEL;r&&(e.defaults.model=r);let n=process.env.ADAM_API_KEY;return n&&(e.server.apiKey=n),e}function C(e){let t=k();return t.port&&(e.server.port=parseInt(t.port,10)),t.host&&(e.server.host=t.host),t.timeout&&(e.defaults.timeout=parseInt(t.timeout,10)),t["api-key"]&&(e.server.apiKey=t["api-key"]),e}function D(e){let t=e??d,r={};if(_(t)){let f=P(t,"utf-8"),l=w(f);l&&(r=u(l))}let n=m(i,r),s=A(n),o=C(s);return v(o)}function I(){let e=JSON.parse(JSON.stringify(i)),t=A(e),r=C(t);return v(r)}function V(){let e={},t={ANTHROPIC_API_KEY:"anthropic.apiKey",ANTHROPIC_BASE_URL:"anthropic.baseUrl",ANTHROPIC_MODEL:"anthropic.model",ANTHROPIC_DEFAULT_OPUS_MODEL:"anthropic.defaultOpusModel",ANTHROPIC_DEFAULT_SONNET_MODEL:"anthropic.defaultSonnetModel",ANTHROPIC_DEFAULT_HAIKU_MODEL:"anthropic.defaultHaikuModel",ANTHROPIC_SMALL_FAST_MODEL:"anthropic.smallFastModel",ADAM_PORT:"server.port",ADAM_API_KEY:"server.apiKey"},r={};for(let[s,o]of Object.entries(t)){let a=process.env[s];if(a&&a.length>0)if(o==="server.port"){let f=parseInt(a,10);isNaN(f)||(e[o]=f)}else e[o]=a}let n=p();if(n)for(let[s,o]of Object.entries(n))s in t||s.startsWith("ANTHROPIC_")||s.startsWith("ADAM_")||(r[s]=o);return Object.keys(r).length>0&&(e["defaults.env"]=r),e}function j(){try{return c().defaults}catch{return i.defaults}}function W(){try{return c().chat??i.chat}catch{return i.chat}}export{D as a,I as b,V as c,j as d,W as e};
@@ -0,0 +1,7 @@
1
+ import{b as i,d as a}from"./chunk-KVSO3KGZ.js";a();function d(t){return{id:t.id,parentId:t.parent_id??void 0,status:t.status,prompt:t.prompt,originalPrompt:t.original_prompt??void 0,config:JSON.parse(t.config),result:t.result??void 0,error:t.error??void 0,sdkSessionId:t.sdk_session_id??void 0,templateId:t.template_id??void 0,roleId:t.role_id??void 0,sourceSessionId:t.source_session_id??void 0,deliverTo:t.deliver_to?JSON.parse(t.deliver_to):void 0,reportTo:t.report_to?JSON.parse(t.report_to):void 0,createdAt:t.created_at,startedAt:t.started_at??void 0,completedAt:t.completed_at??void 0,costUsd:t.cost_usd??void 0,tokenUsage:t.token_usage?JSON.parse(t.token_usage):void 0,numTurns:t.num_turns??void 0,totalDurationMs:t.total_duration_ms??void 0}}function c(t){i().prepare(`
2
+ INSERT INTO tasks (id, parent_id, status, prompt, original_prompt, config, result, error,
3
+ sdk_session_id, template_id, role_id, source_session_id, notify_targets, deliver_to, report_to,
4
+ created_at, started_at, completed_at,
5
+ cost_usd, token_usage, num_turns, total_duration_ms)
6
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
7
+ `).run(t.id,t.parentId??null,t.status,t.prompt,t.originalPrompt??null,JSON.stringify(t.config),t.result??null,t.error??null,t.sdkSessionId??null,t.templateId??null,t.roleId??null,t.sourceSessionId??null,null,t.deliverTo?JSON.stringify(t.deliverTo):null,t.reportTo?JSON.stringify(t.reportTo):null,t.createdAt,t.startedAt??null,t.completedAt??null,t.costUsd??null,t.tokenUsage?JSON.stringify(t.tokenUsage):null,t.numTurns??null,t.totalDurationMs??null)}function g(t){let r=i().prepare("SELECT * FROM tasks WHERE id = ?").get(t);return r?d(r):void 0}function m(t,e){let r=i(),n=[],s=[],l={parentId:"parent_id",status:"status",prompt:"prompt",result:"result",error:"error",sdkSessionId:"sdk_session_id",templateId:"template_id",roleId:"role_id",sourceSessionId:"source_session_id",originalPrompt:"original_prompt",startedAt:"started_at",completedAt:"completed_at",costUsd:"cost_usd",numTurns:"num_turns",totalDurationMs:"total_duration_ms"};for(let[o,u]of Object.entries(l))o in e&&(n.push(`${u} = ?`),s.push(e[o]??null));"config"in e&&(n.push("config = ?"),s.push(JSON.stringify(e.config))),"tokenUsage"in e&&(n.push("token_usage = ?"),s.push(e.tokenUsage?JSON.stringify(e.tokenUsage):null)),"deliverTo"in e&&(n.push("deliver_to = ?"),s.push(e.deliverTo?JSON.stringify(e.deliverTo):null)),"reportTo"in e&&(n.push("report_to = ?"),s.push(e.reportTo?JSON.stringify(e.reportTo):null)),n.length!==0&&(s.push(t),r.prepare(`UPDATE tasks SET ${n.join(", ")} WHERE id = ?`).run(...s))}function f(t,e=100,r=0,n){let s=i(),l="SELECT * FROM tasks",o=[],u=[];return t&&(o.push("status = ?"),u.push(t)),n&&(o.push("role_id = ?"),u.push(n)),o.length>0&&(l+=" WHERE "+o.join(" AND ")),l+=" ORDER BY created_at DESC LIMIT ? OFFSET ?",u.push(e,r),s.prepare(l).all(...u).map(d)}function T(t){return i().prepare("SELECT * FROM tasks WHERE parent_id = ? ORDER BY created_at ASC").all(t).map(d)}function E(t){return i().prepare("SELECT COALESCE(SUM(cost_usd), 0) as total FROM tasks WHERE completed_at >= ? AND cost_usd IS NOT NULL").get(t).total}export{c as a,g as b,m as c,f as d,T as e,E as f};
@@ -0,0 +1,83 @@
1
+ import{a as Z}from"./chunk-5V36ACKZ.js";import{a as xe,c as Le,d as Pe,e as K,f as Ce,g as Ee,h as De,i as mt,j as Ae,k as Ve,l as U,n as he}from"./chunk-OEKM2W3K.js";import{b as _e,c as pe,e as Me}from"./chunk-EJVUUIAV.js";import{b as J}from"./chunk-GMCIKDTC.js";import{a as Be,c as be,e as qe}from"./chunk-6YURWVQG.js";import{a as Q,b as k,c as X,d as Fe,e as Ge}from"./chunk-CDVIT7L5.js";import{a as W,b as h,c as E,d as L}from"./chunk-W3554FQ7.js";import{j as fe}from"./chunk-RPTHFQX7.js";import{d as ge}from"./chunk-SWPXG2CY.js";import{f as Y,i as ue,j as z}from"./chunk-KLQOILIJ.js";import{a as me}from"./chunk-L7JP7DUO.js";import{g as Ne}from"./chunk-4TCP2AT7.js";import{a as Ue,b as N,c as $e,f as je,g as Oe}from"./chunk-6DXNXLYG.js";import{d as I,j as Te}from"./chunk-6HD6NYIB.js";import{d as ke,e as T,g as D,h as A,i as Re,j as de,k as H}from"./chunk-B4WHT7DX.js";import{b,d as ce}from"./chunk-KVSO3KGZ.js";import{c as w,d as Se,h as C}from"./chunk-INNDBLZE.js";import{f as _}from"./chunk-FCV2DPZQ.js";import{createSdkMcpServer as Dt,tool as p}from"@anthropic-ai/claude-agent-sdk";import{z as a}from"zod";H();z();import{v4 as j}from"uuid";ce();function gt(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 $(e){b().prepare(`
2
+ INSERT INTO metric_tree (id, goal_id, level, parent_id, name, description,
3
+ weight, calibration_factor, created_at)
4
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
5
+ `).run(e.id,e.goalId,e.level,e.parentId??null,e.name,e.description??null,e.weight,e.calibrationFactor,e.createdAt)}function We(e){return b().prepare("SELECT * FROM metric_tree WHERE goal_id = ? ORDER BY level, created_at").all(e).map(gt)}C();var ft=w("goal-manager");async function Nr(e){let t;try{let n=JSON.parse(e);t={name:n.name??"",description:n.description,metric:n.metric??"",targetValue:n.targetValue??0,currentValue:n.currentValue??0,deadline:n.deadline??0,budget:n.budget??0,roleId:n.roleId??"engineer",status:"active"}}catch{t=await ht(e)}let r=bt(t);return{goalState:t,validationResult:r,rawInput:e}}async function ht(e){let t=`Extract SMART goal fields from this natural language input.
6
+
7
+ Input: "${e}"
8
+
9
+ Respond ONLY with a JSON object:
10
+ {
11
+ "name": "short goal name (max 100 chars)",
12
+ "description": "detailed description of what the goal aims to achieve",
13
+ "metric": "measurable metric name (e.g. completion, reports_written, accuracy_score)",
14
+ "targetValue": <number, the target to reach>,
15
+ "deadline_days": <number, days from now to complete>,
16
+ "budget": <number, estimated budget in USD>,
17
+ "role": "<best matching role: engineer | analyst | content_creator | reviewer>"
18
+ }
19
+
20
+ Rules:
21
+ - name: concise, actionable title
22
+ - metric: quantifiable measure of success; use "completion" if the goal is binary (done/not done)
23
+ - targetValue: realistic target for the metric; use 1 for binary goals
24
+ - deadline_days: reasonable timeframe; default 7 if unclear
25
+ - budget: estimated cost in USD; default 5 if unclear
26
+ - role: match to the nature of work (research=analyst, writing=content_creator, coding=engineer, review=reviewer)`;try{let n=(await Z(t,"You extract structured SMART goal fields from natural language. Reply with only valid JSON.")).match(/\{[\s\S]*\}/);if(n){let o=JSON.parse(n[0]),i=o.deadline_days??7;return{name:(o.name??e.slice(0,100)).slice(0,100),description:o.description??e,metric:o.metric??"completion",targetValue:o.targetValue??1,currentValue:0,deadline:Date.now()+i*24*60*60*1e3,budget:o.budget??5,roleId:o.roleId??"engineer",status:"active"}}}catch(r){ft.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 bt(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 Ur(e,t,r){let n=j(),o=Date.now(),i={id:n,name:e.name,description:e.description,roleId:e.roleId,metricType:e.metric,targetValue:e.targetValue,currentValue:e.currentValue,deadline:e.deadline,budgetUsd:e.budget,status:e.status,createdAt:o,deliverTo:t,reportTo:r};return Q(i),i}function Je(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),$(o);let i={id:j(),goalId:e,level:"L1",parentId:o.id,name:`${t}_weekly_trend`,description:`Weekly trend for ${t}`,weight:.8,calibrationFactor:1,createdAt:r};n.push(i),$(i);let s={id:j(),goalId:e,level:"L2",parentId:i.id,name:`${t}_daily_process`,description:`Daily process metric for ${t}`,weight:.6,calibrationFactor:1,createdAt:r};n.push(s),$(s);let l={id:j(),goalId:e,level:"L3",parentId:s.id,name:`${t}_per_task`,description:`Per-task instant metric for ${t}`,weight:.4,calibrationFactor:1,createdAt:r};return n.push(l),$(l),n}var ee=class{static collect(t,r){let n=h(t);if(!n)return this.emptyMetrics(t,r);let o=J(t,500,0),i=n.completedAt&&n.startedAt?n.completedAt-n.startedAt:0,s=new Set,l=0,d=0;for(let m of o)m.type==="tool_call"&&m.toolName&&s.add(m.toolName),m.type==="error"&&l++,m.type==="approval_request"&&d++;let u={taskId:t,goalId:r,timestamp:Date.now(),durationMs:i,costUsd:n.costUsd??0,turns:n.numTurns??0,toolCount:s.size,errorCount:l,approvalCount:d,rawScore:0,isComplete:n.status==="completed"};return u.rawScore=this.computeRawScore(u),u}static computeRawScore(t){let n=1-Math.min(t.durationMs/6e5,1),i=1-Math.min(t.costUsd/5,1),l=1-Math.min(t.turns/50,1),d;t.toolCount>=3&&t.toolCount<=15?d=1:t.toolCount<3?d=t.toolCount/3:d=Math.max(0,1-(t.toolCount-15)/15);let u=t.errorCount===0?1:Math.max(0,1-t.errorCount*.2),m=Math.min(1,.5+t.approvalCount*.25);return .3*n+.2*i+.2*l+.1*d+.15*u+.05*m}static cache=new Map;static persist(t){this.cache.set(t.taskId,t)}static getCached(t){return this.cache.get(t)}static clearCache(){this.cache.clear()}static emptyMetrics(t,r){return{taskId:t,goalId:r,timestamp:Date.now(),durationMs:0,costUsd:0,turns:0,toolCount:0,errorCount:0,approvalCount:0,rawScore:0,isComplete:!1}}};ce();function yt(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 He(e){b().prepare(`
27
+ INSERT INTO trials (id, strategy_id, goal_id, task_id, reward,
28
+ metric_l2_score, metric_l3_score, context, completed_at)
29
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
30
+ `).run(e.id,e.strategyId,e.goalId,e.taskId??null,e.reward??null,e.metricL2Score??null,e.metricL3Score??null,e.context??null,e.completedAt)}function Ye(e,t=100){return b().prepare("SELECT * FROM trials WHERE goal_id = ? ORDER BY completed_at DESC LIMIT ?").all(e,t).map(yt)}var te=class{static collect(t){let r=k(t);if(!r)return this.emptyMetrics(t);let n=Date.now(),o=r.targetValue>0?Math.min(r.currentValue/r.targetValue,1):0,i=Math.max(0,(r.deadline-n)/(1e3*60*60*24)),s=this.calculateBudgetSpent(t),l=r.budgetUsd>0?Math.max(0,1-s/r.budgetUsd):1,d=this.calculateExpectedCompletion(r),u={goalId:t,metricType:r.metricType,targetValue:r.targetValue,currentValue:r.currentValue,progressPct:o,deadlineRemainingDays:i,budgetRemainingPct:l,expectedCompletionPct:d,rawScore:0};return u.rawScore=this.computeRawScore(u),u}static computeRawScore(t){let r=Math.min(t.progressPct,1),n;t.expectedCompletionPct>=1?n=1:t.expectedCompletionPct>=.8?n=.5+(t.expectedCompletionPct-.8)*2.5:n=t.expectedCompletionPct*.625;let o=t.budgetRemainingPct;return .5*r+.3*n+.2*o}static calculateExpectedCompletion(t){let r=Date.now(),n=t.deadline-t.createdAt,o=r-t.createdAt;if(n<=0)return 0;let i=o/n;if(i<.1)return .5;let s=t.targetValue>0?t.currentValue/t.targetValue:0;return i>0?s/i:0}static calculateBudgetSpent(t){let r=Ye(t,1e3),n=0,o=new Set;for(let i of r)if(i.taskId&&!o.has(i.taskId)){o.add(i.taskId);let s=h(i.taskId);s?.costUsd&&(n+=s.costUsd)}return n}static emptyMetrics(t){return{goalId:t,metricType:"",targetValue:0,currentValue:0,progressPct:0,deadlineRemainingDays:0,budgetRemainingPct:0,expectedCompletionPct:0,rawScore:0}}};C();var wt=w("agent"),O=class{static cache=new Map;static CACHE_TTL=1440*60*1e3;static async callClaude(t){let o=(await Z(t,'You are an AI quality evaluator. Respond with JSON: {"score": 0-1, "confidence": 0-1, "reasoning": "..."}')).match(/\{[\s\S]*\}/);if(!o)throw new Error("Failed to parse LLM Judge response as JSON");let i=JSON.parse(o[0]);return{score:Math.max(0,Math.min(1,i.score??0)),confidence:Math.max(.3,Math.min(.95,i.confidence??.5)),reasoning:i.reasoning??"No reasoning provided"}}static async evaluate(t,r){let n=`${t}:${r}`,o=this.cache.get(n);if(o&&Date.now()-o.evaluatedAt<this.CACHE_TTL)return o;let i=h(t);if(!i){let g={taskId:t,criteria:r,score:0,confidence:.3,reasoning:"Task not found",evaluatedAt:Date.now()};return this.cache.set(n,g),g}let s=this.getPromptTemplate(i.prompt??"",i.result??i.error??"",r),l,d,u;try{let g=await this.callClaude(s);l=g.score,d=g.confidence,u=g.reasoning}catch(g){wt.warn({error:g,taskId:t},"LLM Judge Claude API call failed, using heuristic fallback"),i.status==="failed"?(l=.1,d=.6,u=`Task failed: ${i.error??"unknown error"} (heuristic fallback)`):i.status==="completed"&&i.result?(l=.7,d=.5,u="Task completed with result (heuristic fallback due to API error)"):i.status==="completed"?(l=.5,d=.4,u="Task completed without explicit result (heuristic fallback)"):(l=.3,d=.3,u=`Task in status: ${i.status} (heuristic fallback)`)}let m={taskId:t,criteria:r,score:l,confidence:d,reasoning:u,evaluatedAt:Date.now()};return this.cache.set(n,m),m}static shouldUseObjective(t){let r=h(t);return r?r.status==="completed"&&r.costUsd!==void 0&&r.numTurns!==void 0:!1}static clearCache(){this.cache.clear()}static getPromptTemplate(t,r,n){return`You are an expert evaluator. Evaluate the following task result against these criteria:
31
+
32
+ Task: ${t}
33
+ Result: ${r}
34
+ Criteria: ${n}
35
+
36
+ Provide:
37
+ 1. Score (0-1): How well did the task meet the criteria?
38
+ 2. Confidence (0-1): How confident are you in this evaluation?
39
+ 3. Reasoning: Brief explanation of your scoring
40
+
41
+ Respond in JSON: {"score": number, "confidence": number, "reasoning": "string"}`}};var vt={L0:.2,L1:.15,L2:.35,L3:.3},re=class e{goalId;nodes;children;constructor(t,r){this.goalId=t,this.nodes=new Map(r.map(n=>[n.id,n])),this.children=new Map;for(let n of r){let o=n.parentId,i=this.children.get(o)??[];i.push(n),this.children.set(o,i)}this.validateAcyclicity()}validateAcyclicity(){for(let t of this.nodes.values()){if(t.parentId&&!this.nodes.has(t.parentId))continue;let r=new Set,n=t.id;for(;n;){if(r.has(n))throw new Error(`Cycle detected in metric tree at node ${n}`);r.add(n),n=this.nodes.get(n)?.parentId}}}static buildFromGoal(t){let r=We(t);return new e(t,r)}static fromNodes(t,r){return new e(t,r)}queryPath(t){let r=[];for(let n of this.nodes.values())n.level===t&&r.push(n);return r.sort((n,o)=>o.weight-n.weight)}aggregateScores(t,r){let n=this.queryPath(t);if(n.length===0)return 0;let o=0,i=0;for(let s of n){let l=r.get(s.id)??0,d=s.weight*s.calibrationFactor;o+=l*d,i+=d}return i>0?o/i:0}getWeightedScore(t){let r=0;for(let[n,o]of Object.entries(vt)){let i=this.aggregateScores(n,t);r+=i*o}return Math.max(0,Math.min(1,r))}getNodeCount(){return this.nodes.size}getChildren(t){return this.children.get(t)??[]}};C();var on=w("agent");function ne(e,t){let r=Date.now(),n=re.buildFromGoal(e),o=new Map,i=te.collect(e);for(let d of n.queryPath("L0"))o.set(d.id,i.rawScore);let s=It(n);if(t){let d=ee.collect(t,e);if(d.isComplete){for(let m of n.queryPath("L3"))o.set(m.id,d.rawScore);let u=n.getNodeCount()>0?n.getWeightedScore(o):Math.max(0,Math.min(1,d.rawScore*.65+i.rawScore*.35));return{goalId:e,taskId:t,reward:u,breakdown:{L0:i.rawScore,L1:0,L2:0,L3:d.rawScore},calibrationFactors:s,source:"objective",confidence:.9,computedAt:r}}}if(t&&!O.shouldUseObjective(t)){let u=O.evaluate(t,"general_quality"),m=i.rawScore*.5+.5*.5;return{goalId:e,taskId:t,reward:i.rawScore,breakdown:{L0:i.rawScore,L1:0,L2:0,L3:0,llmJudge:.5},calibrationFactors:s,source:"llm_judge",confidence:.4,computedAt:r}}let l=n.getNodeCount()>0?n.getWeightedScore(o):i.rawScore;return{goalId:e,reward:l,breakdown:{L0:i.rawScore,L1:0,L2:0,L3:0},calibrationFactors:s,source:"fallback",confidence:.3,computedAt:r}}function It(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 Ze}from"uuid";ce();function oe(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 ze(e){b().prepare(`
42
+ INSERT INTO strategies (id, role_id, task_type, name, prompt_template,
43
+ alpha, beta, total_trials, avg_reward, created_at, updated_at)
44
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
45
+ `).run(e.id,e.roleId,e.taskType,e.name,e.promptTemplate,e.alpha,e.beta,e.totalTrials,e.avgReward??null,e.createdAt,e.updatedAt??null)}function Ke(e){let r=b().prepare("SELECT * FROM strategies WHERE id = ?").get(e);return r?oe(r):void 0}function ln(e=100){return b().prepare("SELECT * FROM strategies ORDER BY created_at LIMIT ?").all(e).map(oe)}function Qe(e){return b().prepare("SELECT * FROM strategies WHERE role_id = ? ORDER BY created_at").all(e).map(oe)}function M(e,t){return b().prepare("SELECT * FROM strategies WHERE role_id = ? AND task_type = ? ORDER BY created_at").all(e,t).map(oe)}function Xe(e,t){b().prepare(`
46
+ UPDATE strategies
47
+ SET alpha = alpha + ?,
48
+ beta = beta + ?,
49
+ total_trials = total_trials + 1,
50
+ avg_reward = CASE
51
+ WHEN total_trials = 0 THEN ?
52
+ ELSE (avg_reward * total_trials + ?) / (total_trials + 1)
53
+ END,
54
+ updated_at = ?
55
+ WHERE id = ?
56
+ `).run(t,1-t,t,t,Date.now(),e)}var F=class{static sampleBeta(t,r){let n=this.sampleGamma(t,1),o=this.sampleGamma(r,1);return n/(n+o)}static sampleGamma(t,r){if(t<1)return this.sampleGamma(t+1,r)*Math.pow(Math.random(),1/t);let n=t-1/3,o=1/Math.sqrt(9*n);for(;;){let i,s;do i=this.randn(),s=1+o*i;while(s<=0);s=s*s*s;let l=Math.random();if(l<1-.0331*i*i*i*i||Math.log(l)<.5*i*i+n*(1-s+Math.log(s)))return n*s/r}}static randn(){let t=Math.random(),r=Math.random();return Math.sqrt(-2*Math.log(t))*Math.cos(2*Math.PI*r)}static sample(t){if(t.length===0)return null;let r=null,n=-1;for(let o of t){let i=this.sampleBeta(o.alpha,o.beta);i>n&&(n=i,r=o)}return r}static getProbabilities(t,r=1e4){let n=new Map;for(let i=0;i<r;i++){let s=this.sample(t);s&&n.set(s.id,(n.get(s.id)||0)+1)}let o=new Map;for(let[i,s]of n)o.set(i,s/r);return o}};var Tt=5,ye=20,et=.5,v=class{static selectStrategy(t,r){let n=M(t,r);return F.sample(n)}static recordTrial(t,r,n,o,i,s,l){Xe(t,o),He({id:Ze(),strategyId:t,goalId:r,taskId:n,reward:o,metricL2Score:i,metricL3Score:s,context:l,completedAt:Date.now()})}static getStrategies(t,r){return M(t,r)}static getStrategyById(t){return Ke(t)}static getPopulationStats(t,r){let n=M(t,r);if(n.length===0)return{count:0,avgTrials:0,avgReward:0,minTrials:0,maxTrials:0};let i=n.reduce((d,u)=>d+u.totalTrials,0)/n.length,s=n.filter(d=>d.avgReward!==void 0).map(d=>d.avgReward),l=s.length>0?s.reduce((d,u)=>d+u,0)/s.length:0;return{count:n.length,avgTrials:i,avgReward:l,minTrials:Math.min(...n.map(d=>d.totalTrials)),maxTrials:Math.max(...n.map(d=>d.totalTrials))}}static shouldEvolve(t,r){let n=this.getPopulationStats(t,r);return n.count<Tt?!0:n.count<ye&&n.maxTrials>0}static addStrategy(t,r,n,o){if(M(t,r).length>=ye)throw new Error(`Strategy population at maximum (${ye}) for ${t}/${r}`);let s={id:`strat-${Ze().slice(0,8)}`,roleId:t,taskType:r,name:n,promptTemplate:o,alpha:et,beta:et,totalTrials:0,createdAt:Date.now()};return ze(s),s}static getTopStrategies(t,r,n=3){let i=M(t,r).filter(s=>s.totalTrials>0);return i.sort((s,l)=>(l.avgReward??0)-(s.avgReward??0)),i.slice(0,n)}static getSamplingProbabilities(t,r){let n=M(t,r);return F.getProbabilities(n)}static evaluateAndRecord(t,r,n,o,i,s){let l=ne(r,n);return this.recordTrial(t,r,n,l.reward,o,i,s),l.reward}};var St=3,kt=2,ae=class{static async generateVariants(t,r,n=St,o=kt){let i=v.getTopStrategies(t,r,n);if(i.length===0){let l=`baseline-${r}-v1`;return v.addStrategy(t,r,l,this.generateBaselinePrompt(t,r)),[l]}let s=[];for(let l=0;l<o;l++){let d=i[0].totalTrials+l+1,u=`${r}-evolved-v${d}`,m=i[0].promptTemplate,g=this.mutateTemplate(m);v.addStrategy(t,r,u,g),s.push(u)}return s}static generateBaselinePrompt(t,r){return`You are a ${t} agent specializing in ${r}.
57
+
58
+ ## Core Focus
59
+ Complete tasks with high quality.
60
+
61
+ ## Approach
62
+ 1. Understand the task requirements thoroughly
63
+ 2. Plan your approach before executing
64
+ 3. Execute systematically, checking your work
65
+ 4. Verify completion against requirements`}static mutateTemplate(t){let r=[this.addProcessEmphasis(),this.addQualityFocus(),this.addVerificationStep()],n=r[Math.floor(Math.random()*r.length)];return`${t}
66
+
67
+ ## Evolution
68
+ ${n}`}static addProcessEmphasis(){let t=["Break down complex tasks into smaller steps","Iterate on solutions, testing each component","Document your reasoning at each step"];return`**Process:** ${t[Math.floor(Math.random()*t.length)]}`}static addQualityFocus(){let t=["Double-check all outputs before completing","Consider edge cases and error conditions","Optimize for correctness over speed"];return`**Quality:** ${t[Math.floor(Math.random()*t.length)]}`}static addVerificationStep(){return"**Verification:** After completing, verify your work meets all requirements."}static async generateWithLLM(t,r,n){return{promptTemplate:this.generateBaselinePrompt(t,r),rationale:"Generated baseline - LLM integration in Phase 5"}}};C();Ae();import{v4 as y}from"uuid";import{spawnSync as tt}from"child_process";import{createRequire as Rt}from"module";import{dirname as _t,join as rt}from"path";import{openSync as Mt,readFileSync as xt,unlinkSync as Lt}from"fs";var Pt=3e4,nt=12e4;function ot(){let t=Rt(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk");return rt(_t(t),"cli.js")}function G(e,t){let r=ot(),n=t?.timeout??Pt;if(t?.json){let i=rt("/tmp",`adam-cli-stdout-${process.pid}-${Date.now()}.txt`),s=Mt(i,"w");try{let l=tt("node",[r,...e],{cwd:t.cwd,timeout:n,stdio:["ignore",s,"pipe"],encoding:"utf-8"});if(l.status!==0)throw new Error(l.stderr?.trim()||`CLI exited with status ${l.status}`);return xt(i,"utf-8")}finally{try{Lt(i)}catch{}}}let o=tt("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 at(){let e=G(["plugin","list","--available","--json"],{json:!0});return JSON.parse(e)}function we(e,t="user",r){return G(["plugin","install",e,"--scope",t],{cwd:r,timeout:nt})}function ve(e,t,r){return G(["plugin","uninstall",e],{cwd:r,timeout:nt})}function it(e,t){return G(["plugin","enable",e])}function st(e,t){return G(["plugin","disable",e])}function Sn(){try{return!!ot()}catch{return!1}}C();import*as lt from"crypto";var V=w("api"),B=class{cancelTask(t){let r=h(t);r&&(E(t,{status:"cancelled",completedAt:Date.now()}),me.emit({type:"task_status_change",taskId:t,oldStatus:r.status,newStatus:"cancelled"}),V.debug({taskId:t,oldStatus:r.status},"Task cancelled"))}resolveApproval(t,r,n){return V.debug({approvalId:t,action:r,reason:n},"Approval resolved (no-op in Pure C)"),!0}resolvePlanApproval(t,r,n,o){let i=_e(t);if(!i)return V.warn({planId:t},"Plan not found or already resolved"),!1;let s=h(i.taskId);return s?(Me(t,r==="allow"?"approved":"denied",n),r==="allow"&&n==="permanent"&&xe({id:lt.randomUUID(),roleId:i.roleId,taskPattern:s.prompt.slice(0,100).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),maxRiskLevel:i.plan.overallRisk,createdAt:Date.now(),createdByTaskId:s.id}),me.emit({type:"plan_approval_decision",taskId:s.id,planId:t,decision:r,approvalType:n,reason:o}),V.debug({planId:t,decision:r,approvalType:n},"Plan approval resolved"),!0):(V.warn({planId:t},"Task not found for plan"),!1)}};import{existsSync as At}from"fs";function ct(e,t){return t?{allowedTools:Et(t.allowedTools,e.allowedTools),disallowedTools:Ie(e.disallowedTools,t.disallowedTools),approvalRequired:Ie(e.approvalRequired,t.approvalRequired),maxBudgetUsd:t.maxBudgetUsd!==void 0&&t.maxBudgetUsd>0?Math.min(t.maxBudgetUsd,e.maxBudgetUsd):e.maxBudgetUsd,plugins:Ie(e.plugins??[],t.plugins)}:{allowedTools:e.allowedTools,disallowedTools:e.disallowedTools,approvalRequired:e.approvalRequired,maxBudgetUsd:e.maxBudgetUsd,plugins:e.plugins??[]}}function Et(e,t){if(e===void 0)return t;if(e.length===0)return[];if(t.length===0)return e;let r=new Set(t);return e.filter(n=>r.has(n))}function Ie(e,t){return t===void 0?e:[...new Set([...e,...t])]}var ie=w("manager");function c(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}async function R(e){let{listChannels:t}=await import("./channels-WZOYE4O4.js"),r=t(),{listSessions:n}=await import("./session-manager-Z6MIYRD3.js"),o=[...n("active"),...n("archived")],i=[];for(let s of e)if(s.type==="session"&&s.sessionId)i.push({type:"session",sessionId:s.sessionId});else if(s.type==="channel"){let l=s.channelId,d=s.chatId;if(!l&&s.channelName){let u=r.find(m=>m.name.toLowerCase().includes(s.channelName.toLowerCase()));u&&(l=u.id)}if(l&&!d){let u=o.find(m=>m.source.type==="channel"&&m.source.channelId===l&&m.source.chatId);u?.source.chatId?d=u.source.chatId:d=r.find(g=>g.id===l)?.config?.userId}l&&d?i.push({type:"channel",channelId:l,chatId:d}):ie.warn({channelName:s.channelName,channelId:l,chatId:d},"Could not resolve channel notify target")}return i}async function Nt(e){let{listRoles:t}=await import("./roles-3UTFKSHI.js"),r=t(void 0,100,0);for(let n of r)if(n.name.toLowerCase().includes(e.toLowerCase()))return n.id}var Ut={goalId:a.string()},$t={goalId:a.string(),status:a.string().optional(),currentValue:a.number().optional(),budgetUsd:a.number().optional(),notes:a.string().optional()},jt={goalId:a.string(),goalDescription:a.string(),maxSubtasks:a.number().optional()},x=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()})]),Ot={prompt:a.string(),roleId:a.string().describe("Role ID. Call list_roles first to find the best role for the task."),deliverTo:a.array(x).optional().describe("Where to deliver the task output (result full text). E.g., send result to a specific channel."),reportTo:a.array(x).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()},Ft={taskId:a.string(),goalId:a.string().optional(),strategyId:a.string().optional()},Gt={roleId:a.string(),taskType:a.string(),name:a.string().optional()},Vt={status:a.string().optional(),limit:a.number().optional()},Bt={taskId:a.string(),roleId:a.string()},qt={taskId:a.string().optional(),status:a.string().optional(),limit:a.number().optional()},Wt={roleId:a.string(),allowedTools:a.array(a.string()).optional(),disallowedTools:a.array(a.string()).optional(),additionalDirectories:a.array(a.object({path:a.string(),mode:a.enum(["ro","rw"]).optional().describe("Read-only or read-write access. Default: rw. Enforced by OS sandbox."),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).")},Jt={roleId:a.string().optional(),limit:a.number().optional()},Ht={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(),mode:a.enum(["ro","rw"]).optional().describe("Read-only or read-write access. Default: rw. Enforced by OS sandbox."),inheritPlugins:a.boolean().optional(),inheritMcp:a.boolean().optional(),inheritPermissions:a.boolean().optional()})).optional()},Yt={roleId:a.string(),reason:a.string().optional()},zt={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(x).optional().describe("Where to deliver goal completion notifications.")},Kt={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(x).optional().describe("Where to deliver the task output (result full text)."),reportTo:a.array(x).optional().describe("Where to send status reports (completion summary).")},Qt={status:a.enum(["active","retired","probation"]).optional(),limit:a.number().optional()},Xt={enabled:a.boolean().optional()},Zt={},er={},tr={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(x).optional().describe("Where to deliver the task output (result full text)."),reportTo:a.array(x).optional().describe("Where to send status reports (completion summary).")},rr={roleId:a.string().optional().describe("If provided, shows which plugins are installed in that role's workspace.")},nr={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.")},or={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.")},ir={roleId:a.string().describe("Role ID to unbind the MCP server from."),mcpName:a.string().describe("Name of the MCP server to remove.")},sr={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},lr={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},cr={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},dr={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},ur={},pr={},mr={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},gr={roleId:a.string().describe("Role ID to associate scanned plugins with."),path:a.string().describe("Directory path to scan for .claude/settings.json.")},fr={taskId:a.string().describe("Task ID to cancel.")},hr={taskId:a.string().describe("Task ID to get logs for."),limit:a.number().optional().describe("Max log entries (default 20).")},br={roleId:a.string().describe("Role ID to delete.")},yr={},wr={updates:a.record(a.string(),a.unknown()).describe("Config key-value pairs to update. Example: { 'defaults.maxTurns': 50, 'logging.level': 'debug' }")},vr={roleId:a.string().describe("Role ID to list memories for."),limit:a.number().optional().describe("Max results (default 20).")},Ir={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()},Tr={templateId:a.string().describe("Template ID to delete.")},Sr={templateId:a.string().describe("Template ID to run immediately.")},kr={enabled:a.boolean().optional().describe("Filter by enabled status.")},Rr={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).")},_r={ruleId:a.string().describe("Delivery rule ID to delete.")},Mr={roleId:a.string().optional().describe("Role ID to filter strategies by.")},dt=[p("read_goal_state","Read a single goal's detailed state: progress percentage, time remaining, budget spent, and current value. Use this for deep-dive on one goal; use list_goals for an overview of all goals.",Ut,async e=>{let t=k(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})}),p("update_goal_state","Update a goal's status, current value, or budget.",$t,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(),X(e.goalId,t)),c({success:!0})}),p("decompose_goal","Decompose a goal into actionable subtasks using LLM reasoning.",jt,async e=>{let t=I(),r=Math.min(e.maxSubtasks??5,10);try{let{query:o}=await import("@anthropic-ai/claude-agent-sdk"),i=`Decompose this goal into ${r} actionable subtasks.
69
+
70
+ Goal: ${e.goalDescription}
71
+
72
+ Respond ONLY with a JSON array. Each item: {"description": "...", "prompt": "detailed task instruction", "complexity": "low|medium|high", "role": "engineer|analyst|content_creator|reviewer"}
73
+
74
+ Rules:
75
+ - Each subtask must be independently executable
76
+ - Order from foundational to dependent
77
+ - Be specific about what each subtask should accomplish
78
+ - For each subtask, specify the best role from: 'engineer', 'analyst', 'content_creator', 'reviewer'. Match role to the nature of the work.`,s=o({prompt:i,options:{cwd:process.cwd(),maxTurns:1,maxBudgetUsd:.02}}),l="";for await(let u of s){let m=u;m.type==="result"&&typeof m.result=="string"&&(l=m.result)}let d=l.match(/\[[\s\S]*\]/);if(d){let u=JSON.parse(d[0]),m=[];for(let g=0;g<Math.min(u.length,r);g++){let f=u[g],q=`subtask-${y().slice(0,8)}`,P=f.role,se=P?await Nt(P):void 0;W({id:q,status:"pending",prompt:f.prompt,parentId:e.goalId,roleId:se,config:t.defaults,createdAt:Date.now()}),m.push({id:q,description:f.description,prompt:f.prompt,dependencies:g>0?[m[g-1].id]:[],estimatedComplexity:f.complexity??"medium",role:P})}if(m.length>0)return c({subtasks:m})}}catch(o){ie.error({error:o},"LLM decomposition failed, using fallback")}let n=[];for(let o=0;o<r;o++){let i=`subtask-${y().slice(0,8)}`,s=`Subtask ${o+1} of goal: ${e.goalDescription.slice(0,100)}`,l=`${e.goalDescription}
79
+
80
+ Subtask ${o+1}/${r}`;W({id:i,status:"pending",prompt:l,parentId:e.goalId,config:t.defaults,createdAt:Date.now()}),n.push({id:i,description:s,prompt:l,dependencies:o>0?[n[o-1].id]:[],estimatedComplexity:"medium"})}return c({subtasks:n})}),p("dispatch_task","Create and immediately dispatch a task to the execution pool. roleId is required \u2014 call list_roles first to find the best role. The assigned role determines which tools the worker can use. Pass deliverTo (result delivery) and/or reportTo (status reports) to route output when the task completes.",Ot,async e=>{let t=T(e.roleId);if(!t||t.status!=="active"){let le=A("active",20,0).filter(S=>S.source!=="system").map(S=>({id:S.id,name:S.name,allowedTools:S.allowedTools??[],capabilitySummary:U(S)}));return c({error:`Role not found or not active: ${e.roleId}. Pick a roleId from the list below.`,availableRoles:le})}let r=y(),n=I(),o=e.prompt.toLowerCase(),i={coding:["code","implement","fix","debug","refactor","build"],analysis:["analyze","data","report","statistics","investigate"],content:["write","translate","summarize","content","draft"],review:["review","check","audit","evaluate","assess"],admin:["config","permission","deploy","manage"]},s="general";for(let[le,S]of Object.entries(i))if(S.some(pt=>o.includes(pt))){s=le;break}let l,d=e.prompt,u=v.selectStrategy(e.roleId,s);u?.promptTemplate&&(d=`${u.promptTemplate}
81
+
82
+ ## Task
83
+ ${e.prompt}`,l=u.id);let m=t?{allowedTools:t.allowedTools,disallowedTools:t.disallowedTools,approvalRequired:t.approvalRequired,maxBudgetUsd:t.maxBudgetUsd,plugins:void 0}:void 0,g=ct(n.defaults,m),f=g.allowedTools;e.toolOverrides?.allowedTools&&(f=[...e.toolOverrides.allowedTools]);let q={...n.defaults,...g,allowedTools:f,disallowedTools:e.toolOverrides?.disallowedTools??g.disallowedTools},P=e.deliverTo?await R(e.deliverTo):void 0,se=e.reportTo?await R(e.reportTo):void 0;W({id:r,status:"pending",prompt:d,roleId:e.roleId,deliverTo:P,reportTo:se,config:q,createdAt:Date.now()});let{serverBus:ut}=await import("./server-bus-GEGVMSCA.js");return ut.emit({type:"task_created",taskId:r}),c({taskId:r,roleId:e.roleId,strategyId:l})}),p("evaluate_result","Evaluate a completed task's result and record a trial for Thompson Sampling.",Ft,async e=>{let{goalId:t,taskId:r,strategyId:n}=e,o=ne(t??"",r);return n&&t&&v.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)}`})}),p("create_strategy","Create a new strategy variant for a role/taskType using LLM evolution.",Gt,async e=>{let{roleId:t,taskType:r}=e;await ae.generateVariants(t,r,3,1);let n=v.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}`})}),p("list_goals","List all goals with progress percentage, budget, deadline, and time remaining. Goal statuses: active (in progress), paused, completed, failed. Use this to check current goal status before making decisions.",Vt,async e=>{let t=e.status;return c(Fe(t,e.limit??10,0))}),p("delete_goal","Delete a goal by ID.",{goalId:a.string()},async e=>k(e.goalId)?(Ge(e.goalId),c({success:!0,goalId:e.goalId})):c({error:"Goal not found"})),p("pause_goal","Pause an active goal.",{goalId:a.string()},async e=>k(e.goalId)?(X(e.goalId,{status:"paused",updatedAt:Date.now()}),c({success:!0,goalId:e.goalId,status:"paused"})):c({error:"Goal not found"})),p("assign_role","Assign a role to a pending task.",Bt,async e=>{let{taskId:t,roleId:r}=e;if(!h(t))return c({error:`Task not found: ${t}`});let o=T(r);return o?(E(t,{roleId:r}),ie.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}`})}),...Ve(),p("read_task_status","Read a single task's details (prompt, status, result, roleId) by ID, or list all tasks filtered by status (pending, running, completed, failed). Use this to check task progress and results.",qt,async e=>{if(e.taskId){let r=h(e.taskId);return c(r??{error:"Task not found"})}let t=e.status;return c(L(t,e.limit??100,0))}),p("modify_role_permissions","Update a role's RBAC permissions (paths, tools).",Wt,async e=>{if(!T(e.roleId))return c({error:`Role not found: ${e.roleId}`});let r={};return 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),D(e.roleId,r),c({success:!0})}),p("view_audit_log","View the evolution audit log for role changes.",Jt,async e=>{let{listEvolutionAudit:t}=await import("./evolution-audit-KUBXFUHI.js"),r=t(e.limit??50);return c({entries:r})}),p("list_roles","List all roles with their capabilities including bound plugins (skills/agents). Use this to discover available roles before dispatching tasks.",Qt,async e=>{let r=A(e.status,e.limit??50,0).map(n=>{let o=he(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:U(n,o),plugins:o.plugins.map(i=>({name:i.name,skills:i.skills.map(s=>s.name),agents:i.agents.map(s=>s.name)}))}});return c({roles:r})}),p("create_role","Create a new role with a name, CAG prompt, and optional tool permissions.",Ht,async e=>{let t=`role-${y().slice(0,8)}`,r={id:t,name:e.name,cagPrompt:e.cagPrompt,learnedRules:[],memoryStreamId:`mem-${y().slice(0,8)}`,status:"active",preferences:{},createdAt:Date.now(),allowedTools:e.allowedTools,disallowedTools:e.disallowedTools,additionalDirectories:e.additionalDirectories};return ke(r),Y(r),c({roleId:t,name:e.name,allowedTools:e.allowedTools,additionalDirectories:e.additionalDirectories??[]})}),p("retire_role","Retire a role (marks as retired, stops receiving tasks).",Yt,async e=>T(e.roleId)?(D(e.roleId,{status:"retired"}),ie.info({roleId:e.roleId,reason:e.reason},"Role retired"),c({success:!0})):c({error:`Role not found: ${e.roleId}`})),p("create_goal","Create a new goal with optional budget, deadline, and metric tracking.",zt,async e=>{let t=y(),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 R(e.deliverTo):void 0};Q(o),Je(t,o.metricType);let i=k(t);return c({goalId:i.id,name:i.name,status:i.status})}),p("create_template","Create a recurring scheduled task using cron expressions (e.g., 'every hour', 'daily at 9am', 'weekly'). For one-shot delayed tasks ('in 30 minutes', 'tomorrow at 3pm'), use schedule_task instead.",Kt,async e=>{let{createTaskTemplate:t}=await import("./task-templates-PSP7GOJJ.js"),r=y(),n=y(),o=e.deliverTo?await R(e.deliverTo):void 0,i=e.reportTo?await R(e.reportTo):void 0,s={id:r,name:e.name,description:e.description,trigger:{type:e.triggerType,cron:e.triggerCron,event:e.triggerEvent},steps:[{id:n,prompt:e.prompt}],rolePreference:e.roleId,enabled:e.enabled??!0,createdAt:Date.now(),goalIds:e.goalIds,deliverTo:o,reportTo:i};return t(s),c({templateId:r,name:s.name,trigger:s.trigger})}),p("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-PSP7GOJJ.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})))}),p("send_to_channel","Send a message (text, image, voice, video, file) to a connected channel by name. Use this to deliver task results, media, or notifications to a specific channel (e.g., WeChat on iPad). For media: provide mediaUrl as an absolute local file path and mediaType. Do NOT use remote URLs \u2014 download files locally first.",{channelName:a.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:a.string().describe("The message content to send (text caption when sending media)"),mediaUrl:a.string().optional().describe("Absolute local file path to the media file (e.g. /Users/.../file.png). Must exist on disk. Do NOT use remote URLs \u2014 download files locally first."),mediaType:a.enum(["image","audio","video","file"]).optional().describe("Type of the media file. Required when mediaUrl is provided")},async e=>{if(e.mediaUrl){if(e.mediaUrl.includes("://")&&!e.mediaUrl.startsWith("file://"))return c({error:`mediaUrl must be a local file path, not a remote URL. Got: ${e.mediaUrl.slice(0,80)}. Download the file to a local path first, then pass the local path.`});let s=e.mediaUrl.startsWith("file://")?new URL(e.mediaUrl).pathname:e.mediaUrl;if(!At(s))return c({error:`Media file not found: ${s}. Verify the file exists before sending.`});if(!e.mediaType)return c({error:"mediaType is required when mediaUrl is provided. Specify one of: image, audio, video, file."})}let t=await R([{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-6FQRWYFF.js"),i=await n().send({channelId:r.channelId,chatId:r.chatId,content:e.message,messageType:"deliver",mediaUrl:e.mediaUrl,mediaType:e.mediaType});return c({success:i.success,channelName:e.channelName,...i.error?{error:i.error}:{}})}),p("list_channels","List all connected channels with their platform, status, and chatId for message delivery. Use this to discover available channels before sending messages or setting up notifications.",Xt,async e=>{let t=ge(e.enabled),r=[...fe("active"),...fe("archived")],n=t.map(o=>{let i,s=r.find(l=>l.source.type==="channel"&&l.source.channelId===o.id&&l.source.chatId);return s?.source.chatId?i=s.source.chatId:i=o.config?.userId,{id:o.id,name:o.name,platform:o.platform,status:o.status,chatId:i}});return c({channels:n})}),p("get_system_status","Get current system status: execution pool capacity (active/max/queued slots), running task count, and system health. Use this to check if the system has capacity before dispatching tasks.",Zt,async()=>{let e=I(),t=L("running"),r=L("pending");return c({executionPool:{active:t.length,max:e.execution?.maxConcurrent??5,queued:r.length},timestamp:new Date().toISOString()})}),p("schedule_task","Schedule a one-shot delayed task. roleId is required \u2014 call list_roles first. Use this when the user wants something done later (e.g., '\u534A\u5C0F\u65F6\u540E', 'in 30 minutes', 'tomorrow at 3pm'). For recurring schedules ('every day', 'weekly'), use create_template instead.",tr,async e=>{let t=T(e.roleId);if(!t||t.status!=="active"){let g=A("active",20,0).filter(f=>f.source!=="system").map(f=>({id:f.id,name:f.name,allowedTools:f.allowedTools??[],capabilitySummary:U(f)}));return c({error:`Role not found or not active: ${e.roleId}. Pick a roleId from the list below.`,availableRoles:g})}let r=Date.now(),n;if(e.delayMinutes!==void 0&&e.runAt!==void 0)return c({error:"Provide exactly one of delayMinutes or runAt, not both"});if(e.delayMinutes!==void 0)n=r+e.delayMinutes*60*1e3;else if(e.runAt!==void 0){if(n=new Date(e.runAt).getTime(),isNaN(n))return c({error:"Invalid ISO 8601 timestamp in runAt"})}else return c({error:"Provide either delayMinutes or runAt"});if(n<=r)return c({error:"Scheduled time must be in the future"});let o=10080*60*1e3;if(n-r>o)return c({error:"Schedule exceeds maximum of 7 days"});let i=y(),s=new Date(n).toISOString(),l=e.deliverTo?await R(e.deliverTo):void 0,d=e.reportTo?await R(e.reportTo):void 0;Ue({id:i,name:e.prompt.slice(0,80),description:`One-shot scheduled task: ${e.prompt.slice(0,200)}`,trigger:{type:"once",runAt:s},steps:[{id:"main",prompt:e.prompt}],rolePreference:e.roleId,config:{...I().defaults},tags:["scheduled","once"],enabled:!0,createdAt:r,deliverTo:l,reportTo:d});let{getBreeEngine:u}=await import("./bree-engine-EKZFCS4Q.js"),m=u();return m&&m.scheduleOnceJob(i),c({templateId:i,executeAt:s,prompt:e.prompt})}),p("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=N(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."});je(e.templateId);let{getBreeEngine:r}=await import("./bree-engine-EKZFCS4Q.js"),n=r();return n&&await n.unscheduleJob(e.templateId),c({cancelled:!0,templateId:e.templateId})}),p("list_available_plugins","List all installed plugins with their scope and global enabled state. If roleId is provided, shows which plugins are installed in that role's workspace.",rr,async e=>{let t=Le(),r=K(),n=e.roleId?(()=>{let{getRoleWorkspacePath:o}=(z(),_(ue)),{getRole:i}=(H(),_(de)),{listInstalledPlugins:s}=(Ae(),_(mt)),l=i(e.roleId);if(!l)return[];let d=o(l.name);return s({scope:"project",projectPath:d}).map(u=>u.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}))})}),p("install_plugin_for_role","Install a plugin into a role's workspace (project-scope). The plugin will be available when that role executes tasks.",nr,async e=>{let{getRole:t}=(H(),_(de)),{getRoleWorkspacePath:r}=(z(),_(ue)),n=t(e.roleId);if(!n)return c({error:`Role not found: ${e.roleId}`});let o=r(n.name);try{return we(e.pluginId,"project",o),c({success:!0,roleId:e.roleId,pluginId:e.pluginId,scope:"project",cwd:o})}catch(i){return c({error:`Failed to install plugin: ${i}`})}}),p("uninstall_plugin_from_role","Uninstall a plugin from a role's workspace.",or,async e=>{let{getRole:t}=(H(),_(de)),{getRoleWorkspacePath:r}=(z(),_(ue)),n=t(e.roleId);if(!n)return c({error:`Role not found: ${e.roleId}`});let o=r(n.name);try{return ve(e.pluginId,"project",o),c({success:!0,roleId:e.roleId,pluginId:e.pluginId})}catch(i){return c({error:`Failed to uninstall plugin: ${i}`})}}),p("bind_mcp_to_role","Bind an MCP server configuration to a role. The MCP server will be available to the role during task execution.",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 D(e.roleId,{mcpServers:n}),Y(t),c({success:!0,roleId:e.roleId,mcpName:e.mcpName,mcpServers:n})}catch(o){return c({error:`Failed to bind MCP server: ${o}`})}}),p("unbind_mcp_from_role","Remove an MCP server binding from a role.",ir,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 D(e.roleId,{mcpServers:r}),Y(t),c({success:!0,roleId:e.roleId,mcpName:e.mcpName})}catch(n){return c({error:`Failed to unbind MCP server: ${n}`})}}),p("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.",er,async()=>{let{listTaskTemplates:e}=await import("./task-templates-PSP7GOJJ.js"),t=I(),r=A(void 0,100,0),n=ge(),o=e(!0,100,0),i=L("running"),s=L("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 d=he(l);return{name:l.name,tools:l.allowedTools??[],mcpServers:Object.keys(l.mcpServers??{}),channels:l.allowedChannels??[],capabilitySummary:U(l,d),plugins:d.plugins.map(u=>({name:u.name,skills:u.skills.map(m=>m.name),agents:u.agents.map(m=>m.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:K().filter(l=>l.enabled).map(l=>({name:l.name,scope:l.scope,description:l.version?`v${l.version}`:void 0}))},automations:{description:"Recurring cron tasks and event-triggered templates",active:o.map(l=>({name:l.name,trigger:l.trigger}))},execution:{description:"Parallel task execution pool",maxConcurrent:t.execution?.maxConcurrent??5,running:i.length,queued:s.length},coreFeatures:["Goal management \u2014 SMART goals with budget/deadline/metric, auto-decomposition into subtasks","Memory \u2014 per-Role vector + keyword searchable memory across tasks","Strategy evolution \u2014 Thompson Sampling optimizes task approaches over time","Monitor \u2014 automatic quality scoring, role retirement/reinstatement","Delivery engine \u2014 event-driven result routing to channels/webhooks","Schedule \u2014 cron recurring templates + one-shot delayed tasks"]})}),p("enable_plugin","Enable a globally installed plugin (makes it available to all roles).",sr,async e=>{try{return it(e.pluginId),c({success:!0,pluginId:e.pluginId})}catch(t){return c({error:`Failed to enable plugin: ${t}`})}}),p("disable_plugin","Disable a globally installed plugin (removes it from all roles).",lr,async e=>{try{return st(e.pluginId),c({success:!0,pluginId:e.pluginId})}catch(t){return c({error:`Failed to disable plugin: ${t}`})}}),p("install_plugin_for_user","Install a plugin globally for the current user (user-scope).",cr,async e=>{try{return we(e.pluginId,"user"),c({success:!0,pluginId:e.pluginId,scope:"user"})}catch(t){return c({error:`Failed to install plugin: ${t}`})}}),p("uninstall_plugin_for_user","Uninstall a globally installed plugin from the current user.",dr,async e=>{try{return ve(e.pluginId,"user"),c({success:!0,pluginId:e.pluginId})}catch(t){return c({error:`Failed to uninstall plugin: ${t}`})}}),p("browse_marketplace","Browse all available plugins from configured marketplaces (shows installed and available).",ur,async()=>{try{let e=at(),t=K();return c({available:e,installed:t})}catch(e){return c({error:`Failed to browse marketplace: ${e}`})}}),p("list_marketplace_sources","List configured plugin marketplace sources.",pr,async()=>{let e=Ee();return c({sources:e})}),p("get_plugin_detail","Get detailed manifest for an installed plugin (skills, agents, MCP servers, hooks).",mr,async e=>{let t=Ce(e.pluginId);if(!t)return c({error:`Plugin not found: ${e.pluginId}`});let r=Pe(t.installPath);return c({id:t.id,name:t.name,version:t.version,scope:t.scope,projectPath:t.projectPath,enabled:t.enabled,manifest:r})}),p("scan_directory","Scan a directory for .claude/settings.json and return its plugin/MCP configuration.",gr,async e=>{let{getRole:t}=await import("./roles-3UTFKSHI.js");if(!t(e.roleId))return c({error:`Role not found: ${e.roleId}`});try{let n=De(e.path);return c({roleId:e.roleId,path:e.path,config:n})}catch(n){return c({error:`Failed to scan directory: ${n}`})}}),p("cancel_task","Cancel a running or pending task by setting its status to 'cancelled'. Emits a task_status_change event.",fr,async e=>{let t=h(e.taskId);if(!t)return c({error:`Task not found: ${e.taskId}`});let r=t.status;E(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"})}),p("view_task_logs","Retrieve step-by-step execution logs for a task.",hr,async e=>{let t=J(e.taskId,e.limit??20);return c({taskId:e.taskId,count:t.length,logs:t})}),p("delete_role","Delete a role by ID. This removes the role and its workspace.",br,async e=>T(e.roleId)?(Re(e.roleId),c({success:!0,roleId:e.roleId})):c({error:`Role not found: ${e.roleId}`})),p("view_config","Get the current runtime configuration (mutable fields and restart-required fields).",yr,async()=>{let{MUTABLE_PATHS:e,RESTART_REQUIRED_PATHS:t}=await import("./runtime-B2DP3JNB.js"),r=I(),n={};try{let l=I().server?.port??7100,d=await fetch(`http://127.0.0.1:${l}/config`);d.ok&&(n=await d.json())}catch{}let o=[...e,...t],i=[...t],s={};for(let l of o){let d=l.split("."),u=r;for(let m of d)if(u&&typeof u=="object")u=u[m];else{u=void 0;break}s[l]={value:u,mutable:!t.includes(l)}}return c({config:s,mutable:[...e],restartRequired:[...t]})}),p("update_config","Update mutable runtime configuration fields. Returns partial-success: some fields may update while others return errors.",wr,async e=>{let{isRestartRequiredPath:t}=await import("./runtime-B2DP3JNB.js"),{setConfigValue:r}=await import("./config-EI3SCA4W.js"),n=Te(e.updates,r);if(e.updates["logging.level"]&&Se(e.updates["logging.level"]),n.updated.length>0){let{serverBus:o}=await import("./server-bus-GEGVMSCA.js");o.emit({type:"config_changed",changes:n.updated.map(i=>({path:i,value:e.updates[i]}))})}return c(n)}),p("list_memories","List memories stored under a specific role.",vr,async e=>{let t=Ne(e.roleId,e.limit??20);return c({roleId:e.roleId,count:t.length,memories:t})}),p("update_template","Update a task template's fields (name, prompt, cron, enabled, etc.).",Ir,async e=>{let t=N(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:y(),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),$e(e.templateId,r),c({success:!0,templateId:e.templateId,updated:Object.keys(r)})}),p("delete_template","Delete a task template by ID.",Tr,async e=>N(e.templateId)?(Oe(e.templateId),c({success:!0,templateId:e.templateId})):c({error:`Template not found: ${e.templateId}`})),p("run_template","Trigger a template immediately (runs the webhook endpoint for its name).",Sr,async e=>{let t=N(e.templateId);if(!t)return c({error:`Template not found: ${e.templateId}`});try{let r=I().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}`})}}),p("list_delivery_rules","List delivery rules, optionally filtered by enabled status.",kr,async e=>{let t=be(e.enabled);return c({count:t.length,rules:t})}),p("create_delivery_rule","Create a new delivery rule for event-driven result routing.",Rr,async e=>{let t=y(),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 Be(r),c({success:!0,ruleId:t,rule:r})}),p("delete_delivery_rule","Delete a delivery rule by ID.",_r,async e=>be().find(n=>n.id===e.ruleId)?(qe(e.ruleId),c({success:!0,ruleId:e.ruleId})):c({error:`Delivery rule not found: ${e.ruleId}`})),p("list_strategies","List Thompson Sampling strategy populations for a role, or all strategies if roleId omitted.",Mr,async e=>{let t;if(e.roleId)t=Qe(e.roleId);else{let{getDb:r}=await import("./db-4NY7ZOS2.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})}),p("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=pe(e.taskId),r=e.operationId?t.find(o=>o.id===e.operationId):t.find(o=>o.status==="pending");return r?(new B().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"})}),p("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=pe(e.taskId),r=e.operationId?t.find(o=>o.id===e.operationId):t.find(o=>o.status==="pending");return r?(new B().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 ao(){return dt.map(e=>e.name).sort().join(",")}function io(){return Dt({name:"adam-tools",version:"1.0.0",tools:dt})}export{B as a,Nr as b,Ur as c,Je as d,ln as e,Qe as f,v as g,at as h,we as i,ve as j,it as k,st as l,Sn as m,ao as n,io as o};
@@ -0,0 +1 @@
1
+ import{d as a}from"./chunk-6HD6NYIB.js";function s(){try{let t=a().server?.timezone;return t==="system"||!t?void 0:t}catch{return}}function p(t){let e=s();return new Date(t).toLocaleTimeString(void 0,e?{timeZone:e}:void 0)}function l(t){let e=t??s(),r=new Date,i=r.toLocaleDateString("en-CA",e?{timeZone:e}:void 0);if(e){let n=(new Intl.DateTimeFormat("en-US",{timeZone:e,timeZoneName:"shortOffset"}).formatToParts(r).find(o=>o.type==="timeZoneName")?.value??"").match(/GMT([+-]?)(\d+)(?::(\d+))?/);if(n){let o=n[1]==="-"?-1:1,m=parseInt(n[2],10),c=parseInt(n[3]??"0",10),f=o*(m*60+c)*6e4;return new Date(`${i}T00:00:00Z`).getTime()-f}}return new Date(`${i}T00:00:00`).getTime()}export{p as a,l as b};
@@ -1 +1 @@
1
- import{b as e,d as t,h as a}from"./chunk-WBAPIPST.js";a();var r={defaults:{timeout:600,maxTurns:100,maxBudgetUsd:5,effort:"high",model:"",settingSources:["user","project"],allowedTools:[],disallowedTools:[],approvalRequired:["rm -rf *","git push*","git reset*","curl * -X POST*","curl * --request POST*"],approvalTimeout:600,env:{},plugins:[],workspacePath:t,workspaceRetention:"immediate",deniedReadPaths:[...e]},externalApis:[],server:{port:7100,host:"0.0.0.0",timezone:"system"},logging:{level:"info"},roles:{presets:[],evolution:{triggerEvery:5,reflectionThreshold:150,retirementThreshold:.4,probationTasks:5}},chat:{sessionTimeoutMinutes:30,maxSessionTurns:20,autoTitle:!0,archiveExtractMemory:!0},watchdog:{enabled:!0,intervalMinutes:5,rules:{managerHealthCheck:{enabled:!0,action:"notify",staleDurationMinutes:15},staleTasks:{enabled:!0,action:"notify",maxPendingMinutes:30},staleRunningTasks:{enabled:!0,action:"notify",maxRunningMinutes:15},dbMaintenance:{enabled:!0,action:"ignore",walCheckpointThresholdMB:100},sandboxViolation:{enabled:!0,action:"alert"}}},execution:{maxConcurrent:5,maxBudgetPerTaskUsd:5,pollIntervalMs:3e4},anthropic:{apiKey:"",baseUrl:"",model:"",defaultOpusModel:"",defaultSonnetModel:"",defaultHaikuModel:"",smallFastModel:""}};export{r as a};
1
+ import{b as e,d as t,h as o}from"./chunk-WBAPIPST.js";o();var r={defaults:{timeout:600,maxTurns:100,maxBudgetUsd:5,effort:"high",model:"",settingSources:["user","project"],allowedTools:[],disallowedTools:[],approvalRequired:["rm -rf *","git push*","git reset*","curl * -X POST*","curl * --request POST*"],approvalTimeout:600,env:{},plugins:[],workspacePath:t,workspaceRetention:"immediate",deniedReadPaths:[...e]},externalApis:[],server:{port:7100,host:"0.0.0.0",timezone:"system"},logging:{level:"info"},roles:{presets:[],evolution:{triggerEvery:5,reflectionThreshold:150,retirementThreshold:.4,probationTasks:5}},chat:{sessionTimeoutMinutes:30,maxSessionTurns:20,autoTitle:!0,archiveExtractMemory:!0},watchdog:{enabled:!0,intervalMinutes:5,rules:{managerHealthCheck:{enabled:!0,action:"notify",staleDurationMinutes:15},staleTasks:{enabled:!0,action:"notify",maxPendingMinutes:30},staleRunningTasks:{enabled:!0,action:"notify",maxRunningMinutes:15},dbMaintenance:{enabled:!0,action:"ignore",walCheckpointThresholdMB:100},sandboxViolation:{enabled:!0,action:"alert"}}},execution:{maxConcurrent:5,pollIntervalMs:3e4},anthropic:{apiKey:"",baseUrl:"",model:"",defaultOpusModel:"",defaultSonnetModel:"",defaultHaikuModel:"",smallFastModel:""}};export{r as a};