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.
@@ -1 +1 @@
1
- import{d as l,e as D,f as S,g as $}from"./chunk-EJVUUIAV.js";import{b as h}from"./chunk-GMCIKDTC.js";import{b as u}from"./chunk-3RAFA6QK.js";import{e as R,g as T,j as C}from"./chunk-KLQOILIJ.js";import{e as k,g as x,k as N}from"./chunk-B4WHT7DX.js";import"./chunk-7LBDLAUQ.js";import"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import{c as d,h as y}from"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";y();var w=d("agent");function I(n){let o=l(n);if(!o){w.debug({taskId:n},"No plan found for task, skipping review");return}let i=h(n,1e3),s=o.plan.steps,a=i.filter(e=>e.type==="tool_result"||e.type==="permission_denied").map(e=>({toolName:e.toolName??"unknown",output:e.content,planStepIndex:e.planStepIndex,permissionDenied:e.type==="permission_denied"})),t=[],r=new Set(a.map(e=>e.planStepIndex).filter(e=>e!==void 0));for(let e of s)r.has(e.index)||t.push({stepIndex:e.index,planned:e.description,actual:"Not executed",deviationType:"skipped"});let c=a.filter(e=>e.planStepIndex===void 0);for(let e of c)t.push({stepIndex:-1,planned:"",actual:`${e.toolName}: ${e.output.slice(0,200)}`,deviationType:"added"});let b=a.filter(e=>e.permissionDenied);for(let e of b)t.push({stepIndex:e.planStepIndex??-1,planned:e.planStepIndex!==void 0?s.find(E=>E.index===e.planStepIndex)?.description??"Unknown":"",actual:`PERMISSION DENIED: ${e.toolName}`,deviationType:"failed"});let p=s.length,m=a.length,g=p>0?Math.max(0,1-t.filter(e=>e.deviationType!=="added").length/p):1,v={stepsPlanned:p,stepsExecuted:m,deviations:t,overallAccuracy:g};return S(o.id,v),w.info({taskId:n,planId:o.id,stepsPlanned:p,stepsExecuted:m,deviationCount:t.length,accuracy:g},"Deviation report generated"),v}function P(n){return n.deviations.filter(i=>i.deviationType==="failed"||i.deviationType==="skipped").length===0&&n.overallAccuracy>=.7}N();C();y();var f=d("agent");function L(n,o){let i=[],a=u(n)?.prompt.slice(0,100)??"unknown task";P(o)&&i.push(`[+] Task "${a}" completed successfully with ${o.overallAccuracy*100}% plan accuracy (${o.stepsExecuted} steps). [sourceTaskId:${n}]`);for(let t of o.deviations)switch(t.deviationType){case"skipped":i.push(`[-] Planned step "${t.planned}" was skipped during "${a}". Consider if this step is necessary for similar tasks. [sourceTaskId:${n}]`);break;case"failed":i.push(`[-] Step failed: "${t.actual}" during "${a}". Check permissions and tool availability. [sourceTaskId:${n}]`);break;case"added":i.push(`[~] Unplanned action: "${t.actual}" during "${a}". Consider adding to plan for similar tasks. [sourceTaskId:${n}]`);break;case"modified":i.push(`[~] Step modified: planned "${t.planned}" but did "${t.actual}" during "${a}". [sourceTaskId:${n}]`);break}return i}async function z(n){let o=l(n);if(!o){f.debug({taskId:n},"No plan for task, skipping review/learn");return}let i=I(n);if(!i)return;let s=L(n,i);if(s.length===0)return;$(o.id,s);let a=u(n);if(a?.roleId){let t=k(a.roleId);if(t){let r=[...t.learnedRules,...s];x(a.roleId,{learnedRules:r});let c=R(t.name);T(c,{...t,learnedRules:r}),f.info({roleId:a.roleId,newRulesCount:s.length},"Role learnedRules updated and CLAUDE.md written")}}D(o.id,"completed"),f.info({taskId:n,planId:o.id,rulesExtracted:s.length,accuracy:i.overallAccuracy},"Task review and learning completed")}export{L as extractRulesFromDeviation,z as processTaskReview};
1
+ import{d as l,e as D,f as S,g as $}from"./chunk-EJVUUIAV.js";import{b as h}from"./chunk-GMCIKDTC.js";import{b as u}from"./chunk-W3554FQ7.js";import{e as R,g as T,j as C}from"./chunk-KLQOILIJ.js";import{e as k,g as x,k as N}from"./chunk-B4WHT7DX.js";import"./chunk-7LBDLAUQ.js";import"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import{c as d,h as y}from"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";y();var w=d("agent");function I(n){let o=l(n);if(!o){w.debug({taskId:n},"No plan found for task, skipping review");return}let i=h(n,1e3),s=o.plan.steps,a=i.filter(e=>e.type==="tool_result"||e.type==="permission_denied").map(e=>({toolName:e.toolName??"unknown",output:e.content,planStepIndex:e.planStepIndex,permissionDenied:e.type==="permission_denied"})),t=[],r=new Set(a.map(e=>e.planStepIndex).filter(e=>e!==void 0));for(let e of s)r.has(e.index)||t.push({stepIndex:e.index,planned:e.description,actual:"Not executed",deviationType:"skipped"});let c=a.filter(e=>e.planStepIndex===void 0);for(let e of c)t.push({stepIndex:-1,planned:"",actual:`${e.toolName}: ${e.output.slice(0,200)}`,deviationType:"added"});let b=a.filter(e=>e.permissionDenied);for(let e of b)t.push({stepIndex:e.planStepIndex??-1,planned:e.planStepIndex!==void 0?s.find(E=>E.index===e.planStepIndex)?.description??"Unknown":"",actual:`PERMISSION DENIED: ${e.toolName}`,deviationType:"failed"});let p=s.length,m=a.length,g=p>0?Math.max(0,1-t.filter(e=>e.deviationType!=="added").length/p):1,v={stepsPlanned:p,stepsExecuted:m,deviations:t,overallAccuracy:g};return S(o.id,v),w.info({taskId:n,planId:o.id,stepsPlanned:p,stepsExecuted:m,deviationCount:t.length,accuracy:g},"Deviation report generated"),v}function P(n){return n.deviations.filter(i=>i.deviationType==="failed"||i.deviationType==="skipped").length===0&&n.overallAccuracy>=.7}N();C();y();var f=d("agent");function L(n,o){let i=[],a=u(n)?.prompt.slice(0,100)??"unknown task";P(o)&&i.push(`[+] Task "${a}" completed successfully with ${o.overallAccuracy*100}% plan accuracy (${o.stepsExecuted} steps). [sourceTaskId:${n}]`);for(let t of o.deviations)switch(t.deviationType){case"skipped":i.push(`[-] Planned step "${t.planned}" was skipped during "${a}". Consider if this step is necessary for similar tasks. [sourceTaskId:${n}]`);break;case"failed":i.push(`[-] Step failed: "${t.actual}" during "${a}". Check permissions and tool availability. [sourceTaskId:${n}]`);break;case"added":i.push(`[~] Unplanned action: "${t.actual}" during "${a}". Consider adding to plan for similar tasks. [sourceTaskId:${n}]`);break;case"modified":i.push(`[~] Step modified: planned "${t.planned}" but did "${t.actual}" during "${a}". [sourceTaskId:${n}]`);break}return i}async function z(n){let o=l(n);if(!o){f.debug({taskId:n},"No plan for task, skipping review/learn");return}let i=I(n);if(!i)return;let s=L(n,i);if(s.length===0)return;$(o.id,s);let a=u(n);if(a?.roleId){let t=k(a.roleId);if(t){let r=[...t.learnedRules,...s];x(a.roleId,{learnedRules:r});let c=R(t.name);T(c,{...t,learnedRules:r}),f.info({roleId:a.roleId,newRulesCount:s.length},"Role learnedRules updated and CLAUDE.md written")}}D(o.id,"completed"),f.info({taskId:n,planId:o.id,rulesExtracted:s.length,accuracy:i.overallAccuracy},"Task review and learning completed")}export{L as extractRulesFromDeviation,z as processTaskReview};
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p}from"./chunk-MPRAVJUO.js";import"./chunk-AJVN3KPM.js";import"./chunk-AR2IZMM2.js";import"./chunk-L7JP7DUO.js";import"./chunk-2CMR5AG7.js";import"./chunk-4TCP2AT7.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{p as _resetForTest,e as archiveSession,b as createSession,g as deleteSession,c as getActiveSession,d as getSession,m as getTimeoutPollerInterval,i as incrementMessageCount,n as initSessionManager,j as listSessions,f as restoreSession,o as shutdownSessionManager,k as startTimeoutPoller,l as stopTimeoutPoller,h as touchSession,a as warmCache};
1
+ import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p}from"./chunk-RPTHFQX7.js";import"./chunk-AJVN3KPM.js";import"./chunk-AR2IZMM2.js";import"./chunk-L7JP7DUO.js";import"./chunk-2CMR5AG7.js";import"./chunk-4TCP2AT7.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{p as _resetForTest,e as archiveSession,b as createSession,g as deleteSession,c as getActiveSession,d as getSession,m as getTimeoutPollerInterval,i as incrementMessageCount,n as initSessionManager,j as listSessions,f as restoreSession,o as shutdownSessionManager,k as startTimeoutPoller,l as stopTimeoutPoller,h as touchSession,a as warmCache};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "adam-agent-server",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Goal-driven AI agent orchestration server with Role+Skill model, real-time streaming, and multi-channel delivery",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1 +0,0 @@
1
- import{i as a,j as b,k as c,l as d,m as e}from"./chunk-U5NRQNBB.js";import"./chunk-QN6BEJF5.js";import"./chunk-OEKM2W3K.js";import"./chunk-EJVUUIAV.js";import"./chunk-GMCIKDTC.js";import"./chunk-3RAFA6QK.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-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,7 +0,0 @@
1
- import{b as u,d as a}from"./chunk-KVSO3KGZ.js";a();function d(e){return{id:e.id,parentId:e.parent_id??void 0,status:e.status,prompt:e.prompt,originalPrompt:e.original_prompt??void 0,config:JSON.parse(e.config),result:e.result??void 0,error:e.error??void 0,sdkSessionId:e.sdk_session_id??void 0,templateId:e.template_id??void 0,roleId:e.role_id??void 0,sourceSessionId:e.source_session_id??void 0,deliverTo:e.deliver_to?JSON.parse(e.deliver_to):void 0,reportTo:e.report_to?JSON.parse(e.report_to):void 0,createdAt:e.created_at,startedAt:e.started_at??void 0,completedAt:e.completed_at??void 0,costUsd:e.cost_usd??void 0,tokenUsage:e.token_usage?JSON.parse(e.token_usage):void 0,numTurns:e.num_turns??void 0,totalDurationMs:e.total_duration_ms??void 0}}function c(e){u().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(e.id,e.parentId??null,e.status,e.prompt,e.originalPrompt??null,JSON.stringify(e.config),e.result??null,e.error??null,e.sdkSessionId??null,e.templateId??null,e.roleId??null,e.sourceSessionId??null,null,e.deliverTo?JSON.stringify(e.deliverTo):null,e.reportTo?JSON.stringify(e.reportTo):null,e.createdAt,e.startedAt??null,e.completedAt??null,e.costUsd??null,e.tokenUsage?JSON.stringify(e.tokenUsage):null,e.numTurns??null,e.totalDurationMs??null)}function g(e){let r=u().prepare("SELECT * FROM tasks WHERE id = ?").get(e);return r?d(r):void 0}function f(e,t){let r=u(),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[i,o]of Object.entries(l))i in t&&(n.push(`${o} = ?`),s.push(t[i]??null));"config"in t&&(n.push("config = ?"),s.push(JSON.stringify(t.config))),"tokenUsage"in t&&(n.push("token_usage = ?"),s.push(t.tokenUsage?JSON.stringify(t.tokenUsage):null)),"deliverTo"in t&&(n.push("deliver_to = ?"),s.push(t.deliverTo?JSON.stringify(t.deliverTo):null)),"reportTo"in t&&(n.push("report_to = ?"),s.push(t.reportTo?JSON.stringify(t.reportTo):null)),n.length!==0&&(s.push(e),r.prepare(`UPDATE tasks SET ${n.join(", ")} WHERE id = ?`).run(...s))}function m(e,t=100,r=0,n){let s=u(),l="SELECT * FROM tasks",i=[],o=[];return e&&(i.push("status = ?"),o.push(e)),n&&(i.push("role_id = ?"),o.push(n)),i.length>0&&(l+=" WHERE "+i.join(" AND ")),l+=" ORDER BY created_at DESC LIMIT ? OFFSET ?",o.push(t,r),s.prepare(l).all(...o).map(d)}function T(e){return u().prepare("SELECT * FROM tasks WHERE parent_id = ? ORDER BY created_at ASC").all(e).map(d)}export{c as a,g as b,f as c,m as d,T as e};
@@ -1,67 +0,0 @@
1
- import{a as $,e as Je}from"./chunk-QN6BEJF5.js";import{b as Fe,k as qe,m as Ge}from"./chunk-OEKM2W3K.js";import{a as me,d as He,e as ge}from"./chunk-EJVUUIAV.js";import{a as Oe,b as Le}from"./chunk-GMCIKDTC.js";import{b as Me,c as U,d as Y}from"./chunk-3RAFA6QK.js";import{a as Ve}from"./chunk-BIIP363C.js";import{e as Ne,f as Ue,j as Ft}from"./chunk-KLQOILIJ.js";import{b as je}from"./chunk-OFOVSC72.js";import{a as p}from"./chunk-L7JP7DUO.js";import{b as We}from"./chunk-GUQAIWCQ.js";import{d as de,i as De}from"./chunk-6HD6NYIB.js";import{a as V,b as $e,e as x,g as O,h as pe,k as L}from"./chunk-B4WHT7DX.js";import{a as Be,g as Ht}from"./chunk-7LBDLAUQ.js";import{b as I,d as Ae}from"./chunk-KVSO3KGZ.js";import{d as ue,h as jt}from"./chunk-WBAPIPST.js";import{c as f,h as _}from"./chunk-INNDBLZE.js";Ae();function Wt(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 Ye(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 K(t,e=50){return I().prepare("SELECT * FROM role_scores WHERE role_id = ? ORDER BY created_at DESC LIMIT ?").all(t,e).map(Wt)}function Ke(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 Xe(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 qt}from"uuid";var Gt=f("audit"),X={taskSuccess:.3,planAccuracy:.25,permissionCompliance:.25,efficiency:.2},ze=.3;function Jt(t,e){let o=Me(t),n=o?.status==="completed"?1:0,r=1,s=He(t);s?.deviationReport&&(r=s.deviationReport.overallAccuracy);let a=1,i=Le(t,1e3),l=i.filter(b=>b.type==="tool_result"||b.type==="permission_denied").length,c=i.filter(b=>b.type==="permission_denied").length;l>0&&(a=1-c/l);let m=1;if(o?.tokenUsage){let b=o.tokenUsage.input+o.tokenUsage.output,S=e?Xe(e):1e4;b>S&&(m=Math.max(0,1-(b-S)/S))}let v=n*X.taskSuccess+r*X.planAccuracy+a*X.permissionCompliance+m*X.efficiency;return{taskSuccess:n,planAccuracy:r,permissionCompliance:a,efficiency:m,weighted:v}}function Qe(t,e){let o=Jt(e,t),n=Ke(t),r=n!==void 0?ze*o.weighted+(1-ze)*n:o.weighted;return Ye({id:qt(),roleId:t,taskId:e,scores:o,emaScore:r,createdAt:Date.now()}),Gt.debug({roleId:t,taskId:e,scores:{...o,weighted:o.weighted.toFixed(3)},ema:r.toFixed(3)},"Task score recorded"),r}L();L();_();var Yt=f("audit");function z(t,e=7){let o=x(t),n=K(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=[],m=a.filter(d=>d.scores.taskSuccess<.5);m.length>0&&c.push({category:"task_failures",count:m.length,examples:m.slice(0,3).map(d=>d.taskId)});let v=a.filter(d=>d.scores.planAccuracy<.5);v.length>0&&c.push({category:"plan_deviations",count:v.length,examples:v.slice(0,3).map(d=>d.taskId)});let b=a.filter(d=>d.scores.permissionCompliance<.8);b.length>0&&c.push({category:"permission_violations",count:b.length,examples:b.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 m.length>a.length*.3&&(T.push("High task failure rate"),R.push({action:"add_rule",detail:"Add rule: verify task feasibility before execution"})),b.length>0&&(T.push("Permission boundary violations"),R.push({action:"adjust_permission",detail:"Review and expand allowedTools if tasks legitimately need wider access"})),v.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"})),Yt.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 Q=f("audit"),Ze=.4,Kt=5;function et(t,e,o=Ze){if(e>=o)return;let n=x(t);if(!n||n.status==="retired"||n.status==="dead")return;Q.warn({roleId:t,emaScore:e,threshold:o},"Agent EMA below threshold, retiring");let r=z(t),s=JSON.stringify(n.learnedRules),a=Xt(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=Je(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"}),Q.info({roleId:t,oldRulesCount:n.learnedRules.length,newRulesCount:a.length,recommendations:r.recommendations.length},"Agent retired with targeted learnedRules modification"),r}function tt(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"}),Q.info({roleId:t},"Agent reinstated to probation"),!0)}function ot(t,e,o=Ze,n=Kt){let r=x(t);return!r||r.status!=="probation"||K(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"}),Q.info({roleId:t,emaScore:e},"Agent graduated from probation to active"),!0):!1}function Xt(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 Tt}from"child_process";L();import{accessSync as rt,constants as st}from"fs";import{accessSync as zt,constants as Qt,existsSync as nt,realpathSync as Zt}from"fs";import{join as fe}from"path";import{spawn as eo}from"child_process";import{execFileSync as to}from"child_process";var j=null;function H(){if(j)return j;let t=typeof import.meta.dirname=="string"?import.meta.dirname:__dirname??".",e=fe(t,"landlock-exec","landlock-exec");if(nt(e))return j=e,e;let o=process.env.PATH?.split(":").find(n=>nt(fe(n,"landlock-exec")));return o?(j=fe(o,"landlock-exec"),j):e}var Z=class{platform="landlock";async isAvailable(){if(process.platform!=="linux")return!1;try{zt(H(),Qt.X_OK)}catch{return!1}try{return to(H(),["--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=Zt(s.path)}catch{i=s.path}r.push(a,i),i!==s.path&&r.push(a,s.path)}return r.push("--",o,...n),eo(H(),r,{cwd:e.cwd,env:e.env,stdio:"pipe",signal:e.signal})}};function it(){if(process.platform==="linux")try{return rt(H(),st.X_OK),"landlock"}catch{return"none"}if(process.platform==="darwin")try{return rt("/usr/bin/sandbox-exec",st.X_OK),"sandbox-exec"}catch{return"none"}return"none"}_();import{spawn as oo}from"child_process";import{readFileSync as lt,writeFileSync as no,mkdtempSync as ro,realpathSync as he,rmSync as so}from"fs";import{join as C}from"path";import{tmpdir as io}from"os";var ct=f("sandbox-macos"),at="/usr/bin/sandbox-exec";function ao(){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 lt(e,"utf-8"),e}catch{}return t[t.length-1]}var lo=ao();function ee(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 co(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}ee(n),e.push(`(allow file-write* (subpath "${n}"))`),n!==o.path&&(ee(o.path),e.push(`(allow file-write* (subpath "${o.path}"))`))}return e.join(`
17
- `)}function uo(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{ee(n),e.push(`(deny file-read-data (subpath "${n}"))`),e.push(`(deny file-read-metadata (subpath "${n}"))`),n!==o&&(ee(o),e.push(`(deny file-read-data (subpath "${o}"))`),e.push(`(deny file-read-metadata (subpath "${o}"))`))}catch(r){ct.warn({path:o,error:r.message},"Skipping deniedReadPath: invalid for SBPL")}}return e.join(`
19
- `)}var te=class{platform="sandbox-exec";async isAvailable(){try{let{existsSync:e}=await import("fs");return e(at)}catch{return!1}}spawn(e){let{command:o,args:n,cwd:r,env:s,signal:a,visiblePaths:i,deniedReadPaths:l}=e,c=lt(lo,"utf-8"),m=co(i),v=uo(l??[]),b=c+m+v+`
20
- `,S=he(ro(C(io(),"adam-sandbox-"))),T=C(S,"role.sb");no(T,b,"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")};ct.debug({command:o,visiblePaths:i.length,profilePath:T},"Spawning sandboxed process");let N=oo(at,["-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{so(S,{recursive:!0,force:!0})}catch{}}),N}};import{spawn as po}from"child_process";var B=null,dt=null,oe=null;function D(){if(B)return B;let t=dt??it();return dt=t,t==="sandbox-exec"?B=new te:t==="landlock"?B=new Z:B=new be(t),B}async function ut(){return oe!==null||(oe=await D().isAvailable()),oe}var be=class{platform;constructor(e){this.platform=e}async isAvailable(){return!1}spawn(e){let o=e.command??"node",n=e.args??[];return po(o,n,{cwd:e.cwd,env:e.env,stdio:"pipe",signal:e.signal})}};import{query as wo}from"@anthropic-ai/claude-agent-sdk";import{v4 as xt}from"uuid";function pt(t){let e=t.roleName?`## Role Context
21
- - Role: ${t.roleName}
22
- ${t.roleCagPrompt?`- CAG Prompt: ${t.roleCagPrompt.slice(0,200)}`:""}`:"",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
- `}$e();_();var mo=new Set(["Read","Glob","Grep","LSP"]),go=new Set(["Edit","Write","NotebookEdit"]);function ye(t){let e=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${e}$`)}function mt(t,e,o){return async(n,r,{agentID:s,blockedPath:a})=>{if(a){let l=V(a);if(o?.deniedReadPaths?.length)for(let c of o.deniedReadPaths){let m=V(c);if(l.startsWith(m))return fo.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(mo.has(n))return{behavior:"allow",updatedInput:r};if(go.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 fo=f("manager");function gt(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(m=>`- [${m.tier??"episodic"}] ${m.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 We(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,800)}`;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{Oe({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,2e3),keywords:["compaction","context","decisions"],importance:4,sourceType:"pre_compact",createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"working"})}catch{}return{}}]}]}}L();Ft();jt();_();Ae();import{randomUUID as ho}from"crypto";function ft(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(ho(),t,a,i,o??null,s)}}function kn(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 Pn(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 bo,tool as ht}from"@anthropic-ai/claude-agent-sdk";import{z as bt}from"zod";async function yo(t){let{listChannels:e}=await import("./channels-WZOYE4O4.js"),o=e(),{listSessions:n}=await import("./session-manager-VYKNKQ46.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 F(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}function yt(t){let e=t?x(t):void 0,o=[...qe(t),ht("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 F({channels:r.map(s=>({id:s.id,name:s.name,enabled:s.enabled,type:s.config?.type??"unknown"}))})}),ht("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:bt.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:bt.string().describe("The message content to send")},async n=>{if(e?.allowedChannels!==void 0){if(e.allowedChannels.length===0)return F({error:"This role is not allowed to send to any channels"});if(!e.allowedChannels.some(c=>c.toLowerCase()===n.channelName.toLowerCase()))return F({error:`Channel "${n.channelName}" is not in the allowed channels list for this role`})}let r=await yo(n.channelName);if(!r)return F({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 F({success:i.success,channelName:n.channelName})})];return bo({name:"execution-tools",version:"1.0.0",tools:o})}Ht();$e();import{realpathSync as xo}from"fs";var h=f("execution"),wt=new Set;async function So(t,e){if(e&&wt.has(e))return h.info({taskId:t,roleName:e},"Sandbox bypass: approved from session cache"),!0;let o=xt(),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()}),p.emit({type:"plan_approval_request",taskId:t,planId:o,plan:n}),h.info({taskId:t,operationId:o,roleName:e},"Sandbox unavailable: awaiting privilege escalation decision"),new Promise(r=>{let a=setTimeout(()=>{l(),ge(o,"denied"),h.warn({taskId:t,operationId:o},"Sandbox bypass timed out, auto-denied"),r(!1)},12e4),i=c=>{c.planId===o&&(l(),c.decision==="allow"?(h.info({taskId:t,operationId:o},"Sandbox bypass approved by user"),e&&wt.add(e),r(!0)):(h.info({taskId:t,operationId:o},"Sandbox bypass denied by user"),r(!1)))},l=()=>{clearTimeout(a),p.off("plan_approval_decision",i)};p.on("plan_approval_decision",i)})}var ne=class{async execute(e,o){let n=Date.now(),r,s,a;U(e.id,{status:"running",startedAt:Date.now()}),p.emit({type:"task_status_change",taskId:e.id,oldStatus:e.status,newStatus:"running"}),h.info({taskId:e.id,roleId:e.roleId},"ExecutionManager: starting task");try{let i=e.roleId?x(e.roleId):void 0,l=ue;i&&(Ue(i),l=Ne(i.name));let c={taskId:e.id,prompt:e.prompt,roleName:i?.name,roleCagPrompt:i?.cagPrompt,allowedTools:i?.allowedTools},m=pt(c),v=gt({currentTaskId:e.id,roleId:e.roleId,taskPrompt:e.prompt}),b=e.config.approvalTimeout??300,S=async(u,g,y,A)=>{let w=xt(),_e=Fe(A??e.roleId,e.prompt,"medium");if(_e)return h.info({operationId:w,ruleId:_e.id,taskId:e.id},"Auto-approved by permanent rule"),{behavior:"allow",updatedInput:g};let Ie={steps:[{index:0,description:`${u}: ${JSON.stringify(g).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()}),p.emit({type:"plan_approval_request",taskId:e.id,planId:w,plan:Ie}),h.info({taskId:e.id,operationId:w,toolName:u,matchedPattern:y},"Privilege escalation: awaiting user decision"),new Promise(ce=>{let Ut=setTimeout(()=>{Ee(),ge(w,"denied"),h.warn({taskId:e.id,operationId:w},"Privilege escalation timed out, auto-denied"),ce({behavior:"deny",message:`Operation timed out after ${b}s. Auto-denied. Try a safer alternative that does not require approval.`})},b*1e3),Ce=M=>{if(M.planId===w)if(Ee(),M.decision==="allow")h.info({taskId:e.id,operationId:w,approvalType:M.approvalType},"Operation authorized by user"),ce({behavior:"allow",updatedInput:g});else{let Vt=M.reason?`Operation denied by user: ${M.reason}. Try a safer alternative.`:"Operation denied by user. Try a safer alternative approach.";h.info({taskId:e.id,operationId:w,reason:M.reason??"no reason given"},"Operation denied by user"),ce({behavior:"deny",message:Vt})}},Ee=()=>{clearTimeout(Ut),p.off("plan_approval_decision",Ce)};p.on("plan_approval_decision",Ce)})},R=(Be("defaults.deniedReadPaths")??[]).map(u=>{let g=V(u);try{return xo(g)}catch{return g}}),d=i?.additionalDirectories??[],E=i?Ge(i):[],N=[...d.map(u=>u.path)].filter((u,g,y)=>y.indexOf(u)===g),Et=mt(u=>({disallowedTools:i?.disallowedTools,approvalRequired:i?.approvalRequired??e.config.approvalRequired,allowedBashPatterns:i?.allowedBashPatterns,deniedBashPatterns:i?.deniedBashPatterns}),S,{deniedReadPaths:R,roleScope:[l,...N]}),Dt=De({roleEnvVars:i?.envVars,taskEnv:e.config.env}),At=e.config.maxBudgetUsd??5,Mt=e.config.maxTurns??100,Ot=yt(e.roleId??""),Lt=i?.mcpServers??{},$t=e.config.mcpServers??{},Bt={...Lt,...$t,"execution-tools":Ot},ae=[{path:l,mode:"rw"}];e.roleId===Ve&&ae.push({path:ue,mode:"ro"});for(let u of d)ae.push({path:u.path,mode:u.mode??"rw"});let ke=D();if(ke.platform==="none"&&!await So(e.id,i?.name))return U(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",Nt=wo({prompt:e.prompt,options:{cwd:l,additionalDirectories:N,systemPrompt:m,maxTurns:Mt,maxBudgetUsd:At,allowedTools:i?.allowedTools,model:i?.model,mcpServers:Bt,settingSources:i?.inheritUserSettings?["project","user"]:["project"],hooks:v,canUseTool:Et,env:Dt,plugins:E.map(u=>({type:"local",path:u})),permissionMode:Pe,...Pe==="bypassPermissions"?{allowDangerouslySkipPermissions:!0}:{},spawnClaudeCodeProcess:u=>{let g=ke.spawn({command:u.command,args:u.args,cwd:u.cwd,env:u.env,signal:u.signal,visiblePaths:ae,deniedReadPaths:R}),y=g;y.pid&&(St(y.pid,e.roleId??"unknown",e.id),y.on("exit",()=>vt(y.pid)));let A="";return y.stderr?.on("data",w=>{A+=w.toString()}),y.on("exit",w=>{w!==null&&w!==0&&A.includes("sandbox")&&(h.error({taskId:e.id,roleId:e.roleId,exitCode:w,stderr:A.slice(0,500)},"Sandbox wrapper failed \u2014 task process exited before execution"),re({roleId:e.roleId??"unknown",taskId:e.id,path:l,operation:`sandbox_init_failure:exit_${w}`,timestamp:Date.now()}))}),g},stderr:u=>{u.trim()&&h.debug({stderr:u.trim().slice(0,500)},"ExecutionManager SDK stderr")}}}),J="",Re=0,Te=()=>{h.warn({taskId:e.id},"ExecutionManager: abort signal received")};o&&o.addEventListener("abort",Te);try{for await(let u of Nt){let g=u;if(h.debug({eventType:g.type,taskId:e.id},"ExecutionManager SDK event"),g.type==="result"&&typeof g.result=="string"&&(J=g.result),g.type==="result"&&Re++,g.token_usage){let y=g.token_usage;y.input_tokens!==void 0&&y.output_tokens!==void 0&&(r={input:y.input_tokens,output:y.output_tokens}),y.cost_usd!==void 0&&(s=y.cost_usd)}}}finally{o&&o.removeEventListener("abort",Te)}a=Re;let le=Date.now()-n;return U(e.id,{status:"completed",result:J,completedAt:Date.now(),costUsd:s,tokenUsage:r,numTurns:a,totalDurationMs:le}),p.emit({type:"task_status_change",taskId:e.id,oldStatus:"running",newStatus:"completed"}),p.emit({type:"task_complete_event",taskId:e.id,result:J}),E.length>0&&ft(e.id,E,e.roleId),h.info({taskId:e.id,durationMs:le,costUsd:s},"ExecutionManager: task completed"),{taskId:e.id,status:"completed",result:J,costUsd:s,tokenUsage:r,numTurns:a,durationMs:le}}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"))&&h.warn({taskId:e.id,error:l},"Task prompt exceeds model context window \u2014 task failed"),U(e.id,{status:"failed",error:l,completedAt:Date.now(),totalDurationMs:c}),p.emit({type:"task_status_change",taskId:e.id,oldStatus:"running",newStatus:"failed"}),p.emit({type:"task_complete_event",taskId:e.id,error:l}),h.error({taskId:e.id,error:i},"ExecutionManager: task failed"),{taskId:e.id,status:"failed",error:l,durationMs:c}}}};_();var k=f("execution-pool"),we=new Map;function St(t,e,o){we.set(t,{roleId:e,taskId:o})}function vt(t){we.delete(t)}function xe(t){return we.get(t)}var kt=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 ne}async start(){if(this.running)return;this.running=!0,p.on("task_created",n=>{this.onTaskCreated(n.taskId)}),p.on("task_status_change",n=>{n.newStatus==="pending"&&this.pickupPendingTasks()});let o=de().execution?.pollIntervalMs??3e4;this.pollTimeoutId=setTimeout(this.poll,o),k.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);k.info("ExecutionPool stopped")}poll=()=>{if(!this.running)return;this.pickupPendingTasks();let o=de().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){k.debug("No free slots available");return}let o=Y("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;k.info({slotIndex:s,taskId:a},"ExecutionPool: claimed slot for task"),this.emitSlotChange(),this.executeTask(r,s).catch(i=>{k.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{p.emit({type:"execution_task_start",taskId:e.id,slotIndex:o});let s=await this.executor.execute(e,n.abortController?.signal);r=s.status,k.info({taskId:e.id,status:s.status,slotIndex:o},"ExecutionPool: task finished")}finally{n.taskId=null,n.abortController=null,p.emit({type:"execution_task_end",taskId:e.id,slotIndex:o,status:r}),this.emitSlotChange(),this.runPostCompletion(e.id,e.roleId).catch(s=>{k.error({taskId:e.id,error:s},"Post-completion processing failed (non-fatal)")}),this.running&&this.pickupPendingTasks()}}emitSlotChange(){let e=this.slots.filter(n=>n.taskId!==null).length,o=Y("pending");p.emit({type:"execution_slot_change",active:e,max:this.slots.length,queued:o.length})}async runPostCompletion(e,o){if(o){try{let{processTaskCompletion:n}=await import("./memory-extractor-FUOJ5D77.js"),r=await n(e,o);r>0&&k.debug({taskId:e,roleId:o,memoriesStored:r},"Post-completion: memories extracted")}catch(n){k.error({taskId:e,roleId:o,error:n},"Post-completion: memory extraction failed")}try{let{processTaskReview:n}=await import("./learner-UYDFNURD.js");await n(e)}catch(n){k.error({taskId:e,roleId:o,error:n},"Post-completion: task review failed")}try{let{evaluateTaskCompletion:n}=await import("./audit-manager-7M2CDMP5.js");n(e,o)}catch(n){k.error({taskId:e,roleId:o,error:n},"Post-completion: audit evaluation failed")}}}getStatus(){let e=this.slots.filter(n=>n.taskId!==null).length,o=Y("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&&(k.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=f("audit"),vo="sandbox_violation",W=new Map,Se=1440*60*1e3,se=[],ko=100;function ve(t){let e=t.roleId,o=W.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),W.set(e,o),o.count%100===0)for(let[r,s]of W.entries()){let a=Date.now()-Se;s.timestamps.filter(i=>i>=a).length===0&&W.delete(r)}se.push(t),se.length>ko&&se.shift();try{je({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:vo,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")}p.emit({type:"sandbox_violation",roleId:t.roleId,taskId:t.taskId,path:t.path,operation:t.operation,timestamp:t.timestamp})}async function _t(){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=Po():t.platform==="landlock"&&(o=await Ro()),()=>{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 Po(){let t=Tt("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=To(r,s);a&&ve(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 Ro(){let t=await Pt("journalctl",["-kf","--no-pager","-o","short","--grep","landlock"]);if(t)return Rt(t),P.info("Linux violation watcher started (journalctl -kf)"),t;let e=await Pt("dmesg",["-w","-t"]);return e?(Rt(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 Pt(t,e){return new Promise(o=>{let n=Tt(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 Rt(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=_o(n);r&&ve(r)}}),t.stderr?.on("data",e=>{P.debug({msg:e.toString().trim()},"Linux watcher stderr")})}function To(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 _o(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 re(t){ve({roleId:t.roleId,taskId:t.taskId,path:t.path,operation:t.operation,timestamp:t.timestamp,count:1})}function It(t){let e=W.get(t);if(!e)return 0;let o=Date.now()-Se;return e.timestamps.filter(n=>n>=o).length}function Ct(){return[...se]}L();_();var q=f("audit"),Io=.4,Co=1440*60*1e3,G=null,ie=null;function kr(t,e,o=Io){let n=x(e);if(!n||n.status==="retired"||n.status==="inactive"||n.status==="dead")return;let r=Qe(e,t);O(e,{performanceScore:r}),ot(e,r,o)?q.info({roleId:e,emaScore:r},"Probation role graduated"):r<o&&et(e,r,o)&&tt(e)}async function Pr(){G===null&&(G=setInterval(()=>{q.info("Running daily diagnostic reports");let t=pe(void 0,1e3);for(let e of t)if(!(e.status==="retired"||e.status==="inactive"))try{z(e.id)}catch(o){q.error({roleId:e.id,error:o},"Daily diagnostic failed")}},Co),ie=await _t(),q.info("AuditManager started"))}function Rr(){G!==null&&(clearInterval(G),G=null),ie!==null&&(ie(),ie=null),q.info("AuditManager stopped")}function Tr(t){re(t)}async function _r(){let t=D(),e=pe(void 0,1e3),n=Date.now()-1440*60*1e3,r=Ct(),s=r.filter(l=>l.timestamp>=n).length,a=e.map(l=>{let c=r.filter(v=>v.roleId===l.id),m=c[c.length-1];return{roleId:l.id,roleName:l.name,sandboxed:t.platform!=="none",violationCount:It(l.id),lastViolation:m?.timestamp}}),i=await ut();return{platform:t.platform,available:i,violationCount24h:s,rolePostures:a}}export{K as a,Ke as b,mt as c,gt as d,D as e,ut as f,kn as g,Pn as h,kr as i,Pr as j,Rr as k,Tr as l,_r as m,kt as n};
@@ -1,83 +0,0 @@
1
- import{a as ee}from"./chunk-5V36ACKZ.js";import{a as _e,c as Me,d as Le,e as Q,f as Pe,g as xe,h as Ce,i as ct,j as Ee,k as Fe,l as U,n as fe}from"./chunk-OEKM2W3K.js";import{b as ke,c as ue,e as Re}from"./chunk-EJVUUIAV.js";import{b as H}from"./chunk-GMCIKDTC.js";import{a as Ge,c as he,e as Ve}from"./chunk-6YURWVQG.js";import{a as X,b as k,c as Z,d as je,e as Oe}from"./chunk-CDVIT7L5.js";import{a as J,b as h,c as D,d as P}from"./chunk-3RAFA6QK.js";import{j as ge}from"./chunk-MPRAVJUO.js";import{d as me}from"./chunk-SWPXG2CY.js";import{f as z,i as de,j as K}from"./chunk-KLQOILIJ.js";import{a as pe}from"./chunk-L7JP7DUO.js";import{g as De}from"./chunk-4TCP2AT7.js";import{a as Ae,b as $,c as Ne,f as $e,g as Ue}from"./chunk-6DXNXLYG.js";import{d as I,j as ve}from"./chunk-6HD6NYIB.js";import{d as Te,e as T,g as A,h as N,i as Se,j as ce,k as Y}from"./chunk-B4WHT7DX.js";import{b,d as le}from"./chunk-KVSO3KGZ.js";import{c as w,d as Ie,h as E}from"./chunk-INNDBLZE.js";import{f as _}from"./chunk-FCV2DPZQ.js";import{createSdkMcpServer as Lt,tool as p}from"@anthropic-ai/claude-agent-sdk";import{z as a}from"zod";Y();K();import{v4 as O}from"uuid";le();function dt(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 j(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 Be(e){return b().prepare("SELECT * FROM metric_tree WHERE goal_id = ? ORDER BY level, created_at").all(e).map(dt)}E();var ut=w("goal-manager");async function xr(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 pt(e)}let r=mt(t);return{goalState:t,validationResult:r,rawInput:e}}async function pt(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 ee(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){ut.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 mt(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 Cr(e,t,r){let n=O(),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 X(i),i}function We(e,t){let r=Date.now(),n=[],o={id:O(),goalId:e,level:"L0",name:`${t}_goal_progress`,description:`Goal-level ${t} progress (monthly)`,weight:1,calibrationFactor:1,createdAt:r};n.push(o),j(o);let i={id:O(),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),j(i);let s={id:O(),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),j(s);let l={id:O(),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),j(l),n}var te=class{static collect(t,r){let n=h(t);if(!n)return this.emptyMetrics(t,r);let o=H(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}}};le();function gt(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 qe(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 Je(e,t=100){return b().prepare("SELECT * FROM trials WHERE goal_id = ? ORDER BY completed_at DESC LIMIT ?").all(e,t).map(gt)}var re=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=Je(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}}};E();var ft=w("agent"),F=class{static cache=new Map;static CACHE_TTL=1440*60*1e3;static async callClaude(t){let o=(await ee(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){ft.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 ht={L0:.2,L1:.15,L2:.35,L3:.3},ne=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=Be(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(ht)){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)??[]}};E();var Zr=w("agent");function oe(e,t){let r=Date.now(),n=ne.buildFromGoal(e),o=new Map,i=re.collect(e);for(let d of n.queryPath("L0"))o.set(d.id,i.rawScore);let s=bt(n);if(t){let d=te.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&&!F.shouldUseObjective(t)){let u=F.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 bt(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 Qe}from"uuid";le();function ae(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 He(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 Ye(e){let r=b().prepare("SELECT * FROM strategies WHERE id = ?").get(e);return r?ae(r):void 0}function rn(e=100){return b().prepare("SELECT * FROM strategies ORDER BY created_at LIMIT ?").all(e).map(ae)}function ze(e){return b().prepare("SELECT * FROM strategies WHERE role_id = ? ORDER BY created_at").all(e).map(ae)}function M(e,t){return b().prepare("SELECT * FROM strategies WHERE role_id = ? AND task_type = ? ORDER BY created_at").all(e,t).map(ae)}function Ke(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 G=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 yt=5,be=20,Xe=.5,v=class{static selectStrategy(t,r){let n=M(t,r);return G.sample(n)}static recordTrial(t,r,n,o,i,s,l){Ke(t,o),qe({id:Qe(),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 Ye(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<yt?!0:n.count<be&&n.maxTrials>0}static addStrategy(t,r,n,o){if(M(t,r).length>=be)throw new Error(`Strategy population at maximum (${be}) for ${t}/${r}`);let s={id:`strat-${Qe().slice(0,8)}`,roleId:t,taskType:r,name:n,promptTemplate:o,alpha:Xe,beta:Xe,totalTrials:0,createdAt:Date.now()};return He(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 G.getProbabilities(n)}static evaluateAndRecord(t,r,n,o,i,s){let l=oe(r,n);return this.recordTrial(t,r,n,l.reward,o,i,s),l.reward}};var wt=3,vt=2,ie=class{static async generateVariants(t,r,n=wt,o=vt){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"}}};E();Ee();import{v4 as y}from"uuid";import{spawnSync as Ze}from"child_process";import{createRequire as It}from"module";import{dirname as Tt,join as et}from"path";import{openSync as St,readFileSync as kt,unlinkSync as Rt}from"fs";var _t=3e4,tt=12e4;function rt(){let t=It(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk");return et(Tt(t),"cli.js")}function V(e,t){let r=rt(),n=t?.timeout??_t;if(t?.json){let i=et("/tmp",`adam-cli-stdout-${process.pid}-${Date.now()}.txt`),s=St(i,"w");try{let l=Ze("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 kt(i,"utf-8")}finally{try{Rt(i)}catch{}}}let o=Ze("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 nt(){let e=V(["plugin","list","--available","--json"],{json:!0});return JSON.parse(e)}function ye(e,t="user",r){return V(["plugin","install",e,"--scope",t],{cwd:r,timeout:tt})}function we(e,t,r){return V(["plugin","uninstall",e],{cwd:r,timeout:tt})}function ot(e,t){return V(["plugin","enable",e])}function at(e,t){return V(["plugin","disable",e])}function yn(){try{return!!rt()}catch{return!1}}E();import*as it from"crypto";var B=w("api"),W=class{cancelTask(t){let r=h(t);r&&(D(t,{status:"cancelled",completedAt:Date.now()}),pe.emit({type:"task_status_change",taskId:t,oldStatus:r.status,newStatus:"cancelled"}),B.debug({taskId:t,oldStatus:r.status},"Task cancelled"))}resolveApproval(t,r,n){return B.debug({approvalId:t,action:r,reason:n},"Approval resolved (no-op in Pure C)"),!0}resolvePlanApproval(t,r,n,o){let i=ke(t);if(!i)return B.warn({planId:t},"Plan not found or already resolved"),!1;let s=h(i.taskId);return s?(Re(t,r==="allow"?"approved":"denied",n),r==="allow"&&n==="permanent"&&_e({id:it.randomUUID(),roleId:i.roleId,taskPattern:s.prompt.slice(0,100).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),maxRiskLevel:i.plan.overallRisk,createdAt:Date.now(),createdByTaskId:s.id}),pe.emit({type:"plan_approval_decision",taskId:s.id,planId:t,decision:r,approvalType:n,reason:o}),B.debug({planId:t,decision:r,approvalType:n},"Plan approval resolved"),!0):(B.warn({planId:t},"Task not found for plan"),!1)}};import{existsSync as Pt}from"fs";var se=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-VYKNKQ46.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}):se.warn({channelName:s.channelName,channelId:l,chatId:d},"Could not resolve channel notify target")}return i}async function xt(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 Ct={goalId:a.string()},Et={goalId:a.string(),status:a.string().optional(),currentValue:a.number().optional(),budgetUsd:a.number().optional(),notes:a.string().optional()},Dt={goalId:a.string(),goalDescription:a.string(),maxSubtasks:a.number().optional()},L=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()})]),At={prompt:a.string(),roleId:a.string().describe("Role ID. Call list_roles first to find the best role for the task."),deliverTo:a.array(L).optional().describe("Where to deliver the task output (result full text). E.g., send result to a specific channel."),reportTo:a.array(L).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()},Nt={taskId:a.string(),goalId:a.string().optional(),strategyId:a.string().optional()},$t={roleId:a.string(),taskType:a.string(),name:a.string().optional()},Ut={status:a.string().optional(),limit:a.number().optional()},jt={taskId:a.string(),roleId:a.string()},Ot={taskId:a.string().optional(),status:a.string().optional(),limit:a.number().optional()},Ft={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).")},Gt={roleId:a.string().optional(),limit:a.number().optional()},Vt={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()},Bt={roleId:a.string(),reason:a.string().optional()},Wt={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(L).optional().describe("Where to deliver goal completion notifications.")},qt={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(L).optional().describe("Where to deliver the task output (result full text)."),reportTo:a.array(L).optional().describe("Where to send status reports (completion summary).")},Jt={status:a.enum(["active","retired","probation"]).optional(),limit:a.number().optional()},Ht={enabled:a.boolean().optional()},Yt={},zt={},Kt={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(L).optional().describe("Where to deliver the task output (result full text)."),reportTo:a.array(L).optional().describe("Where to send status reports (completion summary).")},Qt={roleId:a.string().optional().describe("If provided, shows which plugins are installed in that role's workspace.")},Xt={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.")},Zt={roleId:a.string().describe("Role ID to uninstall the plugin from."),pluginId:a.string().describe("Plugin ID to uninstall.")},er={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.")},tr={roleId:a.string().describe("Role ID to unbind the MCP server from."),mcpName:a.string().describe("Name of the MCP server to remove.")},rr={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},nr={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},or={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},ar={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},ir={},sr={},lr={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},cr={roleId:a.string().describe("Role ID to associate scanned plugins with."),path:a.string().describe("Directory path to scan for .claude/settings.json.")},dr={taskId:a.string().describe("Task ID to cancel.")},ur={taskId:a.string().describe("Task ID to get logs for."),limit:a.number().optional().describe("Max log entries (default 20).")},pr={roleId:a.string().describe("Role ID to delete.")},mr={},gr={updates:a.record(a.string(),a.unknown()).describe("Config key-value pairs to update. Example: { 'defaults.maxTurns': 50, 'logging.level': 'debug' }")},fr={roleId:a.string().describe("Role ID to list memories for."),limit:a.number().optional().describe("Max results (default 20).")},hr={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()},br={templateId:a.string().describe("Template ID to delete.")},yr={templateId:a.string().describe("Template ID to run immediately.")},wr={enabled:a.boolean().optional().describe("Filter by enabled status.")},vr={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).")},Ir={ruleId:a.string().describe("Delivery rule ID to delete.")},Tr={roleId:a.string().optional().describe("Role ID to filter strategies by.")},st=[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.",Ct,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.",Et,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(),Z(e.goalId,t)),c({success:!0})}),p("decompose_goal","Decompose a goal into actionable subtasks using LLM reasoning.",Dt,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)}`,x=f.role,C=x?await xt(x):void 0;J({id:q,status:"pending",prompt:f.prompt,parentId:e.goalId,roleId:C,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:x})}if(m.length>0)return c({subtasks:m})}}catch(o){se.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}`;J({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.",At,async e=>{let t=T(e.roleId);if(!t||t.status!=="active"){let C=N("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:C})}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[C,S]of Object.entries(i))if(S.some(lt=>o.includes(lt))){s=C;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=[...n.defaults.allowedTools];e.toolOverrides?.allowedTools&&(m=[...e.toolOverrides.allowedTools]);let g={...n.defaults,allowedTools:m,disallowedTools:e.toolOverrides?.disallowedTools??n.defaults.disallowedTools},f=e.deliverTo?await R(e.deliverTo):void 0,q=e.reportTo?await R(e.reportTo):void 0;J({id:r,status:"pending",prompt:d,roleId:e.roleId,deliverTo:f,reportTo:q,config:g,createdAt:Date.now()});let{serverBus:x}=await import("./server-bus-GEGVMSCA.js");return x.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.",Nt,async e=>{let{goalId:t,taskId:r,strategyId:n}=e,o=oe(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.",$t,async e=>{let{roleId:t,taskType:r}=e;await ie.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.",Ut,async e=>{let t=e.status;return c(je(t,e.limit??10,0))}),p("delete_goal","Delete a goal by ID.",{goalId:a.string()},async e=>k(e.goalId)?(Oe(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)?(Z(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.",jt,async e=>{let{taskId:t,roleId:r}=e;if(!h(t))return c({error:`Task not found: ${t}`});let o=T(r);return o?(D(t,{roleId:r}),se.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}`})}),...Fe(),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.",Ot,async e=>{if(e.taskId){let r=h(e.taskId);return c(r??{error:"Task not found"})}let t=e.status;return c(P(t,e.limit??100,0))}),p("modify_role_permissions","Update a role's RBAC permissions (paths, tools).",Ft,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),A(e.roleId,r),c({success:!0})}),p("view_audit_log","View the evolution audit log for role changes.",Gt,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.",Jt,async e=>{let r=N(e.status,e.limit??50,0).map(n=>{let o=fe(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.",Vt,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 Te(r),z(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).",Bt,async e=>T(e.roleId)?(A(e.roleId,{status:"retired"}),se.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.",Wt,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};X(o),We(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.",qt,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(!Pt(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.",Ht,async e=>{let t=me(e.enabled),r=[...ge("active"),...ge("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.",Yt,async()=>{let e=I(),t=P("running"),r=P("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.",Kt,async e=>{let t=T(e.roleId);if(!t||t.status!=="active"){let g=N("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;Ae({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-Y24K4PXN.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=$(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."});$e(e.templateId);let{getBreeEngine:r}=await import("./bree-engine-Y24K4PXN.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.",Qt,async e=>{let t=Me(),r=Q(),n=e.roleId?(()=>{let{getRoleWorkspacePath:o}=(K(),_(de)),{getRole:i}=(Y(),_(ce)),{listInstalledPlugins:s}=(Ee(),_(ct)),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.",Xt,async e=>{let{getRole:t}=(Y(),_(ce)),{getRoleWorkspacePath:r}=(K(),_(de)),n=t(e.roleId);if(!n)return c({error:`Role not found: ${e.roleId}`});let o=r(n.name);try{return ye(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.",Zt,async e=>{let{getRole:t}=(Y(),_(ce)),{getRoleWorkspacePath:r}=(K(),_(de)),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})}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.",er,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 A(e.roleId,{mcpServers:n}),z(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.",tr,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 A(e.roleId,{mcpServers:r}),z(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.",zt,async()=>{let{listTaskTemplates:e}=await import("./task-templates-PSP7GOJJ.js"),t=I(),r=N(void 0,100,0),n=me(),o=e(!0,100,0),i=P("running"),s=P("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=fe(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:Q().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).",rr,async e=>{try{return ot(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).",nr,async e=>{try{return at(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).",or,async e=>{try{return ye(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.",ar,async e=>{try{return we(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).",ir,async()=>{try{let e=nt(),t=Q();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.",sr,async()=>{let e=xe();return c({sources:e})}),p("get_plugin_detail","Get detailed manifest for an installed plugin (skills, agents, MCP servers, hooks).",lr,async e=>{let t=Pe(e.pluginId);if(!t)return c({error:`Plugin not found: ${e.pluginId}`});let r=Le(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.",cr,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=Ce(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.",dr,async e=>{let t=h(e.taskId);if(!t)return c({error:`Task not found: ${e.taskId}`});let r=t.status;D(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.",ur,async e=>{let t=H(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.",pr,async e=>T(e.roleId)?(Se(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).",mr,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.",gr,async e=>{let{isRestartRequiredPath:t}=await import("./runtime-B2DP3JNB.js"),{setConfigValue:r}=await import("./config-EI3SCA4W.js"),n=ve(e.updates,r);if(e.updates["logging.level"]&&Ie(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.",fr,async e=>{let t=De(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.).",hr,async e=>{let t=$(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),Ne(e.templateId,r),c({success:!0,templateId:e.templateId,updated:Object.keys(r)})}),p("delete_template","Delete a task template by ID.",br,async e=>$(e.templateId)?(Ue(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).",yr,async e=>{let t=$(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.",wr,async e=>{let t=he(e.enabled);return c({count:t.length,rules:t})}),p("create_delivery_rule","Create a new delivery rule for event-driven result routing.",vr,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 Ge(r),c({success:!0,ruleId:t,rule:r})}),p("delete_delivery_rule","Delete a delivery rule by ID.",Ir,async e=>he().find(n=>n.id===e.ruleId)?(Ve(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.",Tr,async e=>{let t;if(e.roleId)t=ze(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=ue(e.taskId),r=e.operationId?t.find(o=>o.id===e.operationId):t.find(o=>o.status==="pending");return r?(new W().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=ue(e.taskId),r=e.operationId?t.find(o=>o.id===e.operationId):t.find(o=>o.status==="pending");return r?(new W().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 Xn(){return st.map(e=>e.name).sort().join(",")}function Zn(){return Lt({name:"adam-tools",version:"1.0.0",tools:st})}export{W as a,xr as b,Cr as c,We as d,rn as e,ze as f,v as g,nt as h,ye as i,we as j,ot as k,at as l,yn as m,Xn as n,Zn as o};