adam-agent-server 0.5.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -4
- package/dist/App-SCPYTYGQ.js +9 -0
- package/dist/adam-tools-FNJJT7AA.js +1 -0
- package/dist/{approval-handler-HK7GQPHU.js → approval-handler-UDWAC5MF.js} +2 -2
- package/dist/audit-manager-SCX53YJT.js +1 -0
- package/dist/bree-engine-2DB2QECM.js +1 -0
- package/dist/channels-NAPXRIOX.js +1 -0
- package/dist/channels-PQCV74ZI.js +1 -0
- package/dist/{chunk-2GXYBWLS.js → chunk-2C5U3CNX.js} +1 -1
- package/dist/chunk-2CMR5AG7.js +1 -0
- package/dist/chunk-35DBEYMG.js +49 -0
- package/dist/chunk-3TIHZZMK.js +1 -0
- package/dist/{chunk-VF6GJGD6.js → chunk-42RHY3Q3.js} +1 -1
- package/dist/{chunk-742NWPTQ.js → chunk-4TBGFHYX.js} +1 -1
- package/dist/chunk-5V36ACKZ.js +1 -0
- package/dist/{chunk-PQ7KPALO.js → chunk-64FIXWFL.js} +1 -1
- package/dist/chunk-6KLG4APZ.js +1 -0
- package/dist/chunk-6VPL5CXB.js +4 -0
- package/dist/{chunk-T7WVM27S.js → chunk-7KCBFM2C.js} +6 -6
- package/dist/chunk-BCELBB5Q.js +3 -0
- package/dist/{chunk-5ASEAZCR.js → chunk-BONI2HUN.js} +1 -1
- package/dist/chunk-CFTWJZVX.js +67 -0
- package/dist/{chunk-PCSZW2PE.js → chunk-CREHL4BN.js} +7 -7
- package/dist/chunk-FXFHGIY6.js +8 -0
- package/dist/{chunk-KICPHTI2.js → chunk-GA7GEIXB.js} +1 -1
- package/dist/{chunk-HAWA62R2.js → chunk-I5RUEOSQ.js} +1 -1
- package/dist/chunk-INNDBLZE.js +1 -0
- package/dist/chunk-IZQI6QQ7.js +1 -0
- package/dist/{chunk-WXN3PSVX.js → chunk-KHPXEUSY.js} +1 -1
- package/dist/{chunk-IXF3XBGX.js → chunk-NFSXJNPD.js} +1 -1
- package/dist/chunk-NQHTOFQP.js +1 -0
- package/dist/{chunk-B6S2AEOD.js → chunk-PT55643Q.js} +1 -1
- package/dist/chunk-QC6QVNKP.js +83 -0
- package/dist/chunk-QMKQBU3R.js +2 -0
- package/dist/chunk-REKCZ3GY.js +1 -0
- package/dist/{chunk-L7426WNY.js → chunk-ROSOI75V.js} +1 -1
- package/dist/{chunk-FDWW245P.js → chunk-TEMWI6U5.js} +1 -1
- package/dist/{chunk-U36NBCR3.js → chunk-U3XVAAXA.js} +1 -1
- package/dist/chunk-VRP4LTHY.js +1 -0
- package/dist/chunk-WBAPIPST.js +1 -0
- package/dist/{chunk-AXMXXUPO.js → chunk-X26NKAXY.js} +1 -1
- package/dist/{chunk-TN6H2WM2.js → chunk-XFTRKHH2.js} +3 -3
- package/dist/{chunk-FUGJMHY4.js → chunk-YEV5YTS3.js} +1 -1
- package/dist/cli.js +4 -4
- package/dist/config-L4R273R3.js +1 -0
- package/dist/config-N2GMLTPU.js +1 -0
- package/dist/db-S6HDMJ3B.js +1 -0
- package/dist/delivery-log-VAI35G5V.js +1 -0
- package/dist/engine-E67UAI3G.js +1 -0
- package/dist/evolution-audit-KCFDGNSM.js +1 -0
- package/dist/external-api-I6CENLIS.js +1 -0
- package/dist/index.js +12 -57
- package/dist/learner-ABYVK33T.js +1 -0
- package/dist/logger-QCJUU7GV.js +1 -0
- package/dist/memories-3ZAV55YZ.js +1 -0
- package/dist/{memory-extractor-GOISDQTO.js → memory-extractor-BHHKD7X7.js} +2 -2
- package/dist/memory-service-5QHTKIUU.js +1 -0
- package/dist/outbound-gateway-ZFKSN2UT.js +1 -0
- package/dist/role-presets-OTU2M37Y.js +1 -0
- package/dist/roles-LXRHEVUK.js +1 -0
- package/dist/{runtime-6UTYEONR.js → runtime-UCOE6LNN.js} +1 -1
- package/dist/session-manager-RPXFZKMY.js +1 -0
- package/dist/task-templates-XQNKAA4U.js +1 -0
- package/package.json +1 -1
- package/web/dist/assets/{ChannelDetail-dZfZlLgQ.js → ChannelDetail-BajTUEU0.js} +1 -1
- package/web/dist/assets/{Channels-Cw04c7YJ.js → Channels-Bhy6rP_t.js} +1 -1
- package/web/dist/assets/{Chat-D4PHqHPE.js → Chat-Dvt_Oo7d.js} +1 -1
- package/web/dist/assets/{Dashboard-BFewwmAg.js → Dashboard-DlrAor-C.js} +1 -1
- package/web/dist/assets/{Evolution-DY1OC6Oc.js → Evolution-Dlsnnr4G.js} +1 -1
- package/web/dist/assets/{GoalDetail-DZIEpHs2.js → GoalDetail-BuUxwYdd.js} +1 -1
- package/web/dist/assets/{Goals-COCCVLnp.js → Goals-CkPQOev6.js} +1 -1
- package/web/dist/assets/{Logs-DsDeimLt.js → Logs-D33PqDAd.js} +1 -1
- package/web/dist/assets/{Memories-D5IEEI1u.js → Memories-D31dbUM6.js} +1 -1
- package/web/dist/assets/{Plugins-DUwZVjPc.js → Plugins-XlBr07x8.js} +1 -1
- package/web/dist/assets/RoleDetail-rZFlgXzh.js +33 -0
- package/web/dist/assets/{Roles-JeVjD0Ew.js → Roles-d29AC6Kh.js} +1 -1
- package/web/dist/assets/Settings-Bjh_RXYf.js +1 -0
- package/web/dist/assets/{Strategies-KAmpqrcQ.js → Strategies-Cf4ghknk.js} +1 -1
- package/web/dist/assets/{Switch-Jpdn6Yux.js → Switch-CxzUYL49.js} +1 -1
- package/web/dist/assets/{TaskDetail-C4NpqwNT.js → TaskDetail-jMBJbaRU.js} +1 -1
- package/web/dist/assets/{Work-DhaxNYnd.js → Work-CCLTkitf.js} +1 -1
- package/web/dist/assets/index-CVubgAlC.css +2 -0
- package/web/dist/assets/{index-CfKqiQIe.js → index-Ds41VvOC.js} +2 -2
- package/web/dist/index.html +2 -2
- package/dist/App-XZABZ2AF.js +0 -9
- package/dist/adam-tools-BB7WQGVT.js +0 -1
- package/dist/bree-engine-25VACELK.js +0 -1
- package/dist/channels-JEBBMFUQ.js +0 -1
- package/dist/channels-VEUBY2NZ.js +0 -1
- package/dist/chunk-3DAK2XWP.js +0 -1
- package/dist/chunk-5JLMSNIW.js +0 -1
- package/dist/chunk-7SPKRIMZ.js +0 -15
- package/dist/chunk-BREBCBG4.js +0 -49
- package/dist/chunk-D6WM2OQS.js +0 -86
- package/dist/chunk-DWMMWYLD.js +0 -1
- package/dist/chunk-ETQ7KC73.js +0 -1
- package/dist/chunk-FYDFMYUP.js +0 -1
- package/dist/chunk-JXD6ZPV7.js +0 -2
- package/dist/chunk-NSJAV7IH.js +0 -1
- package/dist/chunk-NXTTKAQX.js +0 -3
- package/dist/chunk-SFUS33SO.js +0 -1
- package/dist/chunk-T25NLVMY.js +0 -1
- package/dist/chunk-URW2DJQF.js +0 -1
- package/dist/chunk-WZOMGJSY.js +0 -1
- package/dist/chunk-XNWZZYAV.js +0 -7
- package/dist/config-WHXCZCI4.js +0 -1
- package/dist/config-Y4QWELO3.js +0 -1
- package/dist/db-PNZ3UJOE.js +0 -1
- package/dist/delivery-log-VYTYUFCK.js +0 -1
- package/dist/engine-3PNNEZNK.js +0 -1
- package/dist/evolution-audit-B7WKMOVR.js +0 -1
- package/dist/external-api-XGEOKAWR.js +0 -1
- package/dist/learner-VMD5NQCD.js +0 -1
- package/dist/logger-BEG4WFIM.js +0 -1
- package/dist/memories-EFQ4SFZG.js +0 -1
- package/dist/memory-service-BKLZIRK6.js +0 -1
- package/dist/monitor-K7CGTLA6.js +0 -1
- package/dist/outbound-gateway-DZTXBUTP.js +0 -1
- package/dist/role-presets-FN2RWUCP.js +0 -1
- package/dist/roles-SG2YAR64.js +0 -1
- package/dist/session-manager-45LFTPBA.js +0 -1
- package/dist/task-templates-7LSQ6OST.js +0 -1
- package/web/dist/assets/RoleDetail-B-GKMfMG.js +0 -33
- package/web/dist/assets/Settings-CvEyZp5t.js +0 -1
- package/web/dist/assets/index-LDFr0VVR.css +0 -2
|
@@ -0,0 +1,83 @@
|
|
|
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-6VPL5CXB.js";import{b as ke,c as ue,e as Re}from"./chunk-NFSXJNPD.js";import{b as H}from"./chunk-X26NKAXY.js";import{a as Ge,c as he,e as Ve}from"./chunk-GA7GEIXB.js";import{a as X,b as k,c as Z,d as je,e as Oe}from"./chunk-KHPXEUSY.js";import{a as J,b as h,c as D,d as P}from"./chunk-ROSOI75V.js";import{j as ge}from"./chunk-YEV5YTS3.js";import{d as me}from"./chunk-64FIXWFL.js";import{b as z,e as de,f as K}from"./chunk-U3XVAAXA.js";import{a as pe}from"./chunk-L7JP7DUO.js";import{g as De}from"./chunk-I5RUEOSQ.js";import{a as Ae,b as $,c as Ne,f as $e,g as Ue}from"./chunk-42RHY3Q3.js";import{d as I,g as ve}from"./chunk-REKCZ3GY.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-FXFHGIY6.js";import{b,d as le}from"./chunk-CREHL4BN.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-NAPXRIOX.js"),r=t(),{listSessions:n}=await import("./session-manager-RPXFZKMY.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-LXRHEVUK.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-KCFDGNSM.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-XQNKAA4U.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-XQNKAA4U.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-ZFKSN2UT.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-2DB2QECM.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-2DB2QECM.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-XQNKAA4U.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-LXRHEVUK.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-UCOE6LNN.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-UCOE6LNN.js"),{setConfigValue:r}=await import("./config-N2GMLTPU.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-S6HDMJ3B.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};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{b as r,d as s}from"./chunk-CREHL4BN.js";import{c as i}from"./chunk-FCV2DPZQ.js";function p(e){let n=r().prepare("SELECT value FROM config WHERE key = ?").get(e);if(n)try{return JSON.parse(n.value)}catch{return n.value}}function E(e,t){let n=r(),o=JSON.stringify(t),u=Date.now();n.prepare(`INSERT INTO config (key, value, updated_at) VALUES (?, ?, ?)
|
|
2
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`).run(e,o,u)}function k(){let t=r().prepare("SELECT key, value FROM config").all(),n={};for(let o of t)try{n[o.key]=JSON.parse(o.value)}catch{n[o.key]=o.value}return n}function b(e){let t=r(),n=t.prepare("INSERT OR IGNORE INTO config (key, value, updated_at) VALUES (?, ?, ?)"),o=Date.now(),u=0;return t.transaction(()=>{for(let[c,a]of Object.entries(e)){if(a==null||a==="")continue;n.run(c,JSON.stringify(a),o).changes>0&&u++}})(),u}function w(){return r().prepare("SELECT COUNT(*) as count FROM config").get().count===0}function O(e){return r().prepare("DELETE FROM config WHERE key = ?").run(e).changes>0}var d=i(()=>{s()});export{p as a,E as b,k as c,b as d,w as e,O as f,d as g};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var c=["defaults.model","defaults.effort","defaults.maxTurns","defaults.maxBudgetUsd","defaults.timeout","logging.level","roles.evolution.triggerEvery","roles.evolution.reflectionThreshold","chat.sessionTimeoutMinutes","chat.maxSessionTurns","chat.autoTitle","chat.archiveExtractMemory","server.timezone","anthropic.apiKey","anthropic.baseUrl","anthropic.model","anthropic.defaultOpusModel","anthropic.defaultSonnetModel","anthropic.defaultHaikuModel","anthropic.smallFastModel","defaults.approvalTimeout","defaults.deniedReadPaths","defaults.approvalRequired"],f=["server.port","server.host","server.apiKey"],d={"anthropic.apiKey":"ANTHROPIC_API_KEY","anthropic.baseUrl":"ANTHROPIC_BASE_URL","anthropic.model":"ANTHROPIC_MODEL","anthropic.defaultOpusModel":"ANTHROPIC_DEFAULT_OPUS_MODEL","anthropic.defaultSonnetModel":"ANTHROPIC_DEFAULT_SONNET_MODEL","anthropic.defaultHaikuModel":"ANTHROPIC_DEFAULT_HAIKU_MODEL","anthropic.smallFastModel":"ANTHROPIC_SMALL_FAST_MODEL"},i=null;function v(t){i=JSON.parse(JSON.stringify(t))}function a(){if(!i)throw new Error("Runtime config not initialized. Call initRuntimeConfig first.");return i}function T(t){let o=a(),s=t();for(let[n,e]of Object.entries(s))l(o,n,e)}function k(){let t=a(),o={};for(let[s,n]of Object.entries(d)){let e=g(t,s);e&&typeof e=="string"&&e.length>0?o[n]=e:process.env[n]&&(o[n]=process.env[n])}return o}function A(t,o){let s=a(),n=[],e=[];for(let[r,u]of Object.entries(t)){if(!p(r)){h(r)?e.push(`"${r}" requires restart. Cannot modify at runtime.`):e.push(`"${r}" is not a recognized config path.`);continue}l(s,r,u)&&(n.push(r),o?.(r,u))}return{success:e.length===0,updated:n,errors:e}}function l(t,o,s){let n=o.split("."),e=t;for(let r=0;r<n.length-1;r++)if(e&&typeof e=="object")e=e[n[r]];else return!1;return e&&typeof e=="object"?(e[n[n.length-1]]=s,!0):!1}function g(t,o){let s=o.split("."),n=t;for(let e of s)if(n&&typeof n=="object")n=n[e];else return;return n}function p(t){return c.includes(t)}function h(t){return f.includes(t)}export{c as a,f as b,v as c,a as d,T as e,k as f,A as g,g as h,p as i,h as j};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as u,d as a}from"./chunk-
|
|
1
|
+
import{b as u,d as a}from"./chunk-CREHL4BN.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
2
|
INSERT INTO tasks (id, parent_id, status, prompt, original_prompt, config, result, error,
|
|
3
3
|
sdk_session_id, template_id, role_id, source_session_id, notify_targets, deliver_to, report_to,
|
|
4
4
|
created_at, started_at, completed_at,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as s,d as o}from"./chunk-
|
|
1
|
+
import{b as s,d as o}from"./chunk-CREHL4BN.js";o();function i(e){return{id:e.id,ruleId:e.rule_id??void 0,taskId:e.task_id??void 0,status:e.status,target:JSON.parse(e.target),content:e.content,attempts:e.attempts,error:e.error??void 0,createdAt:e.created_at,deliveredAt:e.delivered_at??void 0,expiresAt:e.expires_at,source:e.source,messageType:e.message_type??void 0}}var u=1440*60*1e3;function p(e){s().prepare(`
|
|
2
2
|
INSERT INTO delivery_log (id, rule_id, task_id, status, target, content,
|
|
3
3
|
attempts, error, created_at, delivered_at, expires_at, source, message_type)
|
|
4
4
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{d as o,h as p}from"./chunk-WBAPIPST.js";import{c as m,e as g}from"./chunk-FCV2DPZQ.js";var y={};g(y,{ensureRoleWorkspace:()=>h,getRoleWorkspacePath:()=>c,syncRoleSettings:()=>d,writeRoleCLAUDEmd:()=>u});import{mkdirSync as i,writeFileSync as a}from"fs";import{join as s,basename as f}from"path";function c(n){let e=f(n);if(e!==n||!n)throw new Error(`Invalid role name for workspace: ${n}`);return s(R,"roles",e)}function h(n){let e=c(n.name);return i(e,{recursive:!0}),i(s(e,".claude"),{recursive:!0}),u(e,n),d(n.id,n.allowedTools,e),e}function u(n,e){let r=e.learnedRules&&e.learnedRules.length>0?e.learnedRules.map(l=>`- ${l}`).join(`
|
|
2
2
|
`):"(no learned rules yet)",t=`# ${e.name}
|
|
3
3
|
|
|
4
4
|
${e.cagPrompt}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as w,h as S}from"./chunk-WBAPIPST.js";import{c as g,h as P}from"./chunk-INNDBLZE.js";P();S();import{readFileSync as v,existsSync as E}from"fs";import{join as p}from"path";import{homedir as R}from"os";var T=g("ws"),x=p(R(),".adam"),f=p(x,"adam.port"),b=p(w,"adam.key");function d(){let n=process.env.ADAM_API_KEY;if(n)return n;if(E(b))return v(b,"utf-8").trim()||void 0}function m(){if(!E(f))return null;let n=parseInt(v(f,"utf-8").trim(),10);return isNaN(n)?null:n}function C(){let n=m();if(!n)throw new Error("Server not running. Run: adam server start");return`http://localhost:${n}`}var u=class extends Error{constructor(e,s){super(s);this.status=e;this.name="ApiError"}};async function A(n,t={}){let s=`${C()}${n}`,r=d(),o=await fetch(s,{method:t.method||"GET",headers:{"Content-Type":"application/json",...r?{"x-api-key":r}:{},...t.headers},body:t.body?JSON.stringify(t.body):void 0});if(!o.ok){let a=await o.text().catch(()=>"Unknown error");throw new u(o.status,a)}return o.headers.get("content-type")?.includes("application/json")?o.json():o.text()}function D(){return A("/healthz")}var k=class{ws=null;callbacks=new Map;reconnectAttempts=0;reconnectTimer=null;url;constructor(t="/events"){let e=m();if(!e)throw new Error("Server not running. Run: adam server start");let s=d(),r=new URL(`ws://localhost:${e}${t}`);s&&r.searchParams.set("api_key",s),this.url=r.toString()}connect(){return new Promise((t,e)=>{try{this.ws=new WebSocket(this.url),this.ws.onopen=()=>{this.reconnectAttempts=0,t()},this.ws.onmessage=s=>{try{let r=JSON.parse(s.data),{type:o,data:c,...a}=r,i=this.callbacks.get(o);i&&i.forEach(l=>l(c??a))}catch(r){T.error({error:r},"Failed to parse WebSocket message")}},this.ws.onclose=()=>{this.scheduleReconnect()},this.ws.onerror=s=>{e(s)}}catch(s){e(s)}})}scheduleReconnect(){let t=[1e3,2e3,4e3,8e3,15e3],e=t[Math.min(this.reconnectAttempts,t.length-1)];this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>{this.connect().catch(()=>{})},e)}on(t,e){this.callbacks.has(t)||this.callbacks.set(t,new Set),this.callbacks.get(t).add(e)}off(t,e){this.callbacks.get(t)?.delete(e)}close(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.ws?.close()}isConnected(){return this.ws?.readyState===WebSocket.OPEN}},y=class{ws=null;callbacks=new Map;url;constructor(t){let e=m();if(!e)throw new Error("Server not running. Run: adam server start");let s=d(),r=new URL(`ws://localhost:${e}/tasks/${t}/stream`);s&&r.searchParams.set("api_key",s),this.url=r.toString()}connect(){return new Promise((t,e)=>{try{this.ws=new WebSocket(this.url),this.ws.onopen=()=>{t()},this.ws.onmessage=s=>{try{let r=JSON.parse(s.data),{type:o,data:c,...a}=r,i=this.callbacks.get(o);i&&i.forEach(h=>h(c??a));let l=this.callbacks.get("*");l&&l.forEach(h=>h(r))}catch(r){T.error({error:r},"Failed to parse task stream message")}},this.ws.onerror=s=>{e(s)},this.ws.onclose=()=>{}}catch(s){e(s)}})}on(t,e){this.callbacks.has(t)||this.callbacks.set(t,new Set),this.callbacks.get(t).add(e)}off(t,e){this.callbacks.get(t)?.delete(e)}close(){this.ws?.close()}isConnected(){return this.ws?.readyState===WebSocket.OPEN}};export{d as a,A as b,D as c,k as d,y as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as s}from"./chunk-FCV2DPZQ.js";import{join as o}from"path";import{homedir as r}from"os";var c,e,A,t,p,E,a,S,D,P,T=s(()=>{"use strict";c=["Read","Write","Edit","Bash","Grep","Glob","WebSearch","WebFetch","LSP","NotebookEdit","Agent"],e=["~/.ssh","~/.aws","~/.gnupg","/etc/shadow"],A=e,t=o(r(),".adam"),p=o(t,"adam.db"),E=o(t,"adam.config.yaml"),a=o(t,".env"),S=o(t,"CLAUDE.md"),D=o(t,"logs"),P=10*1024});export{c as a,e as b,A as c,t as d,p as e,E as f,a as g,T as h};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as e,d as p}from"./chunk-
|
|
1
|
+
import{b as e,d as p}from"./chunk-CREHL4BN.js";p();function i(t){return{id:t.id,taskId:t.task_id,index:t.index,type:t.type,content:t.content,toolName:t.tool_name??void 0,toolInput:t.tool_input?JSON.parse(t.tool_input):void 0,toolOutput:t.tool_output??void 0,truncated:t.truncated===1,timestamp:t.timestamp,tokenUsage:t.token_usage?JSON.parse(t.token_usage):void 0,planStepIndex:t.plan_step_index??void 0}}function a(t){e().prepare(`
|
|
2
2
|
INSERT INTO step_logs (id, task_id, "index", type, content, tool_name,
|
|
3
3
|
tool_input, tool_output, truncated, timestamp, token_usage, plan_step_index)
|
|
4
4
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as s,f as
|
|
1
|
+
import{b as s,f as w}from"./chunk-U3XVAAXA.js";import{d as i,e as f,h as g,k as y}from"./chunk-FXFHGIY6.js";import{c as p,h}from"./chunk-INNDBLZE.js";y();w();h();import{v4 as c}from"uuid";var t=p("store"),a="role-chat-manager",l=[{name:"Engineer",cagPrompt:`Role: General-purpose software engineer.
|
|
2
2
|
Capabilities: Read, write, and edit code; run shell commands; search codebases.
|
|
3
3
|
Approach: Analyze requirements \u2192 implement \u2192 test \u2192 verify. Write tests for new code. Follow existing code patterns.
|
|
4
4
|
Best for: Feature implementation, bug fixes, refactoring, build/deploy scripts.
|
|
@@ -14,6 +14,6 @@ Constraints: No file write/edit permissions. Cannot modify the codebase \u2014 o
|
|
|
14
14
|
Capabilities: Create and edit text files, read reference material, search for context.
|
|
15
15
|
Approach: Understand the target audience and format \u2192 draft \u2192 refine. Match the project's existing tone and terminology.
|
|
16
16
|
Best for: Documentation, reports, emails, translations, summaries, changelog entries.
|
|
17
|
-
Constraints: No shell command execution. No web access. Works only with file read/write operations.`,allowedTools:["Read","Write","Edit","Grep","Glob"],evaluationCriteria:{content_quality:5,engagement:4},executionMode:"isolated"}];function
|
|
17
|
+
Constraints: No shell command execution. No web access. Works only with file read/write operations.`,allowedTools:["Read","Write","Edit","Grep","Glob"],evaluationCriteria:{content_quality:5,engagement:4},executionMode:"isolated"}];function M(){R();let r=g(void 0,1e3,0),o=new Set(l.map(e=>e.name)),d=r.filter(e=>o.has(e.name));if(d.length>0)return t.info({count:d.length},"Default roles already exist, skipping"),r;t.info({count:l.length},"Creating default roles");let u=[];for(let e of l){let m=`role-${c().slice(0,8)}`,n={id:m,name:e.name,cagPrompt:e.cagPrompt,learnedRules:[],memoryStreamId:`mem-${c().slice(0,8)}`,status:"active",preferences:{},createdAt:Date.now(),allowedTools:e.allowedTools,evaluationCriteria:e.evaluationCriteria,executionMode:e.executionMode};i(n),u.push(n),s(n),t.info({roleId:m,name:e.name},"Created default role")}return u}function R(){if(f(a)){t.debug({roleId:a},"ChatManager system role already exists");return}let o={id:a,name:"Chat Manager",cagPrompt:`You are the Chat Manager \u2014 orchestrating conversations and managing agent interactions.
|
|
18
18
|
You coordinate between user requests and agent execution, maintaining conversation context
|
|
19
|
-
and routing tasks to the appropriate roles. You have broad memory access across all roles.`,learnedRules:[],memoryStreamId:`mem-${c().slice(0,8)}`,status:"active",preferences:{},createdAt:Date.now()};i(o),s(o),t.info({roleId:a},"Created ChatManager system role")}export{a,
|
|
19
|
+
and routing tasks to the appropriate roles. You have broad memory access across all roles.`,learnedRules:[],memoryStreamId:`mem-${c().slice(0,8)}`,status:"active",preferences:{},createdAt:Date.now()};i(o),s(o),t.info({roleId:a},"Created ChatManager system role")}export{a,M as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as h,b as u,c,d as m,e as v,f as x}from"./chunk-
|
|
1
|
+
import{a as h,b as u,c,d as m,e as v,f as x}from"./chunk-BONI2HUN.js";import{b as S,d as y}from"./chunk-4TBGFHYX.js";import{a as i}from"./chunk-L7JP7DUO.js";import{a as l}from"./chunk-2CMR5AG7.js";import{a as C}from"./chunk-I5RUEOSQ.js";import{e as p}from"./chunk-3TIHZZMK.js";import{v4 as D}from"uuid";import{v4 as I}from"uuid";function _(e){if(e.length<20)return null;let t=e.trim();return t.length>300?{content:`User request: ${t.slice(0,280)}...`,importance:3,type:"thought"}:{content:`User request: ${t}`,importance:3,type:"thought"}}function b(e){if(e.length<20)return null;let t=e.trim();return t.length>400?{content:`Assistant response: ${t.slice(0,370)}...`,importance:2,type:"event"}:{content:`Assistant response: ${t}`,importance:2,type:"event"}}function N(e){let t=S(e,200,0),s=[];for(let o of t){let r=o.role==="user"?_(o.content):b(o.content);r&&s.push(r)}return{facts:s}}function $(e){let t=e.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(s=>s.length>2);return[...new Set(t)].slice(0,20)}async function A(e,t){let{facts:s}=N(e),o=0;for(let r of s){let f=r.content.slice(0,500),g;try{g=await l(f)}catch{}let M=$(f),T={id:I(),roleId:t,type:r.type,content:f,embedding:g,keywords:M,importance:r.importance,sourceType:"session_archive",createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"episodic"};C(T),o++}return o}var n=new Map,a;function w(e){return`${e.type}:${e.channelId??""}:${e.chatId??""}`}function F(){n.clear();let e=m("active",1e3);for(let t of e)n.set(t.id,t)}function Q(e,t){let s=Date.now(),o={id:D(),status:"active",source:e,createdAt:s,lastActiveAt:s,messageCount:0};return h(o),n.set(o.id,o),i.emit({type:"session_created",session:o}),o}function V(e){for(let s of n.values())if(w(s.source)===w(e))return s;let t=v(e);return t&&n.set(t.id,t),t}function B(e){let t=n.get(e);return t||u(e)}function E(e){let t=Date.now();c(e,{status:"archived",archivedAt:t}),p().archiveExtractMemory&&u(e)&&A(e,"role-chat-manager").catch(()=>{}),n.delete(e),i.emit({type:"session_archived",sessionId:e})}function W(e){c(e,{status:"active",archivedAt:void 0});let t=u(e);return t&&(n.set(t.id,t),i.emit({type:"session_restored",session:t})),t}function X(e){y(e),x(e),n.delete(e),i.emit({type:"session_deleted",sessionId:e})}function Y(e){let t=Date.now();c(e,{lastActiveAt:t});let s=n.get(e);s&&(s.lastActiveAt=t)}function Z(e){let t=B(e);if(t){let s=t.messageCount+1;c(e,{messageCount:s});let o=n.get(e);o&&(o.messageCount=s)}}function ee(e){return m(e)}function P(){let t=p().sessionTimeoutMinutes*60*1e3,s=Date.now();for(let o of n.values())if(s-o.lastActiveAt>t)try{E(o.id)}catch{}}function R(e=6e4){d(),a=setInterval(P,e)}function d(){a&&(clearInterval(a),a=void 0)}function te(){return a}function se(){F(),R()}function oe(){d(),n.clear()}function ne(){d(),n.clear()}export{F as a,Q as b,V as c,B as d,E as e,W as f,X as g,Y as h,Z as i,ee as j,R as k,d as l,te as m,se as n,oe as o,ne as p};
|
package/dist/cli.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as G,b as h,c as W,e as V}from"./chunk-
|
|
2
|
+
import{a as G,b as h,c as W,e as V}from"./chunk-VRP4LTHY.js";import{a as z,b as B,e as J,h as q}from"./chunk-7KCBFM2C.js";import"./chunk-42RHY3Q3.js";import{d as _}from"./chunk-REKCZ3GY.js";import{c as R,e as K,g as ue}from"./chunk-QMKQBU3R.js";import{b as H,c as j,d as de}from"./chunk-CREHL4BN.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";import{Command as Te}from"commander";import{fork as me}from"child_process";import{readFileSync as M,writeFileSync as ge,existsSync as v,unlinkSync as $,mkdirSync as pe,openSync as fe}from"fs";import{join as D}from"path";import{homedir as he}from"os";var P=D(he(),".adam"),S=D(P,"adam.pid"),k=D(P,"adam.port"),b=D(P,"server.log");function ve(){v(P)||pe(P,{recursive:!0})}function C(){if(!v(S))return null;let e=parseInt(M(S,"utf-8").trim(),10);return isNaN(e)?null:e}function ye(){if(!v(k))return null;let e=parseInt(M(k,"utf-8").trim(),10);return isNaN(e)?null:e}function A(e){try{return process.kill(e,0),!0}catch{return!1}}async function N(){ve();let e=C();if(e&&A(e))throw new Error(`Server already running (PID ${e})`);v(S)&&$(S),v(k)&&$(k);let o=fe(b,"a"),t=D(z,"dist/index.js"),n=me(t,[],{detached:!0,stdio:["ignore",o,o,"ipc"]}),l=await new Promise((i,c)=>{let p=setTimeout(()=>{n.kill(),c(new Error(`Server start timeout. Check logs: ${b}`))},1e4);n.on("message",a=>{if(a&&typeof a=="object"&&a.type==="ready"){clearTimeout(p);let s=a.port;s?i(s):c(new Error("Ready signal received but missing port"))}}),n.on("exit",a=>{clearTimeout(p);let s=v(b)?M(b,"utf-8").split(`
|
|
3
3
|
`).slice(-10).join(`
|
|
4
4
|
`):"";c(new Error(`Server exited with code ${a}.
|
|
5
5
|
${s?`Last log lines:
|
|
6
|
-
${s}`:`Check logs: ${b}`}`))}),n.on("error",a=>{clearTimeout(p),c(a)})});return
|
|
6
|
+
${s}`:`Check logs: ${b}`}`))}),n.on("error",a=>{clearTimeout(p),c(a)})});return ge(S,String(n.pid)),n.disconnect(),n.unref(),{pid:n.pid,port:l}}async function U(){let e=C();if(!e)throw new Error("No PID file found \u2014 server not running?");if(!A(e))throw v(S)&&$(S),v(k)&&$(k),new Error("Server not running (stale PID file)");process.kill(e,"SIGTERM"),await new Promise(o=>{let t=0,n=setInterval(()=>{A(e)?(t++,t>=10&&(clearInterval(n),process.kill(e,"SIGKILL"),o())):(clearInterval(n),o())},500)}),v(S)&&$(S),v(k)&&$(k)}function I(){let e=C(),o=e?A(e):!1,t=ye();return{running:o,pid:e,port:t}}function Y(){return b}import{readFileSync as be,existsSync as $e,createReadStream as Ie}from"fs";import Pe from"react";import{render as De}from"ink";import d from"chalk";import*as Z from"readline";async function Q(e,o){try{let t={};o.model&&(t.model=o.model),o.timeout&&(t.timeout=o.timeout),o.budget&&(t.maxBudgetUsd=o.budget),o.workspace&&(t.workspacePath=o.workspace);let{taskId:n}=await h("/tasks",{method:"POST",body:{prompt:e,config:Object.keys(t).length>0?t:void 0}});o.json?console.log(JSON.stringify({taskId:n,status:"submitted"})):console.log(d.dim(`Task ${n} submitted`));let l=()=>{h(`/tasks/${n}/cancel`,{method:"POST"}).catch(()=>{}),o.json||console.log(d.yellow(`
|
|
7
7
|
Task cancelled.`)),process.exit(130)};process.on("SIGINT",l);let i=new V(n);await i.connect();let c=[];await new Promise(a=>{i.on("reasoning",s=>{let r=s;o.json?c.push({type:"reasoning",...r}):process.stdout.write(d.gray(r.content??""))}),i.on("tool_call",s=>{let r=s;o.json?c.push({type:"tool_call",...r}):console.log(d.blue(`
|
|
8
8
|
[tool] ${r.toolName??"unknown"}`))}),i.on("tool_result",s=>{let r=s;if(o.json)c.push({type:"tool_result",...r});else{let m=r.content??"",f=m.split(`
|
|
9
9
|
`);f.length>5?console.log(d.green(`[result] (${f.length} lines) \u25B8 truncated`)):console.log(d.green(`[result] ${m}`))}}),i.on("error",s=>{let r=s;o.json?c.push({type:"error",...r}):console.error(d.red(`
|
|
10
10
|
[error] ${r.error??"unknown error"}`))}),i.on("approval_needed",s=>{let r=s;if(o.approval===!1){h(`/tasks/${n}/approve`,{method:"POST",body:{approvalId:r.approvalId,reason:"auto-approved via --no-approval"}}).catch(()=>{});return}if(o.json){c.push({type:"approval_needed",...r}),h(`/tasks/${n}/approve`,{method:"POST",body:{approvalId:r.approvalId}}).catch(()=>{});return}console.log(d.yellow(`
|
|
11
11
|
\u26A0 Approval needed: ${r.toolName}`)),console.log(d.yellow(` Pattern: ${r.matchedPattern}`)),console.log(d.yellow(` Input: ${JSON.stringify(r.toolInput)}`));let m=Z.createInterface({input:process.stdin,output:process.stdout});m.question(d.yellow(" [a]pprove / [r]eject: "),f=>{m.close();let x=f.toLowerCase().startsWith("a")?"approve":"reject";h(`/tasks/${n}/${x}`,{method:"POST",body:{approvalId:r.approvalId}}).catch(()=>{})})}),i.on("complete",s=>{let r=s;o.json?console.log(JSON.stringify({taskId:n,status:"completed",events:c,result:r})):(console.log(d.dim(`
|
|
12
|
-
\u2500\u2500\u2500 Task complete \u2500\u2500\u2500`)),r.costUsd!==void 0&&console.log(d.dim(`Cost: $${r.costUsd.toFixed(4)}`)),r.numTurns!==void 0&&console.log(d.dim(`Turns: ${r.numTurns}`))),i.close(),a()}),i.on("*",s=>{s.type})});let p=await h(`/tasks/${n}`);(p.task.status==="failed"||p.task.status==="cancelled")&&process.exit(1),process.exit(0)}catch(t){o.json?console.log(JSON.stringify({error:t.message})):console.error(d.red(t.message)),process.exit(1)}}import u from"chalk";var
|
|
12
|
+
\u2500\u2500\u2500 Task complete \u2500\u2500\u2500`)),r.costUsd!==void 0&&console.log(d.dim(`Cost: $${r.costUsd.toFixed(4)}`)),r.numTurns!==void 0&&console.log(d.dim(`Turns: ${r.numTurns}`))),i.close(),a()}),i.on("*",s=>{s.type})});let p=await h(`/tasks/${n}`);(p.task.status==="failed"||p.task.status==="cancelled")&&process.exit(1),process.exit(0)}catch(t){o.json?console.log(JSON.stringify({error:t.message})):console.error(d.red(t.message)),process.exit(1)}}import u from"chalk";var Se={pending:u.gray,queued:u.gray,running:u.yellow,paused:u.yellow,completed:u.green,failed:u.red,cancelled:u.gray};function X(e){return(Se[e]??u.white)(e)}function ee(e,o){return e.length<=o?e:e.slice(0,o-3)+"..."}function oe(e){if(e<1e3)return`${e}ms`;let o=Math.floor(e/1e3);if(o<60)return`${o}s`;let t=Math.floor(o/60),n=o%60;return`${t}m ${n}s`}async function te(e){try{let o=new URLSearchParams;e.status&&o.set("status",e.status),e.limit&&o.set("limit",e.limit);let t=o.toString(),{tasks:n}=await h(`/tasks${t?`?${t}`:""}`);if(n.length===0){console.log(u.dim("No tasks found"));return}console.log(u.bold(T("ID",10)+T("STATUS",12)+T("PROMPT",40)+T("DURATION",10)+"COST"));for(let l of n){let i=l.totalDurationMs?oe(l.totalDurationMs):"\u2014",c=l.costUsd!==void 0?`$${l.costUsd.toFixed(4)}`:"\u2014";console.log(T(l.id.slice(0,8),10)+T(X(l.status),22)+T(ee(l.prompt,38),40)+T(i,10)+c)}}catch(o){console.error(u.red(o.message)),process.exit(1)}}async function re(e){try{let{task:o}=await h(`/tasks/${e}`);console.log(u.bold("Task Details")),console.log(` ID: ${o.id}`),console.log(` Status: ${X(o.status)}`),console.log(` Prompt: ${o.prompt}`),console.log(` Created: ${new Date(o.createdAt).toLocaleString()}`),o.startedAt&&console.log(` Started: ${new Date(o.startedAt).toLocaleString()}`),o.completedAt&&console.log(` Finished: ${new Date(o.completedAt).toLocaleString()}`),o.totalDurationMs&&console.log(` Duration: ${oe(o.totalDurationMs)}`),o.costUsd!==void 0&&console.log(` Cost: $${o.costUsd.toFixed(4)}`),o.result&&console.log(` Result: ${ee(o.result,200)}`),o.error&&console.log(` Error: ${u.red(o.error)}`)}catch(o){console.error(u.red(o.message)),process.exit(1)}}async function ne(e){try{await h(`/tasks/${e}/cancel`,{method:"POST"}),console.log(`Task ${e} cancelled`)}catch(o){console.error(u.red(o.message)),process.exit(1)}}function T(e,o){return e.length>=o?e:e+" ".repeat(o-e.length)}de();ue();import O from"chalk";async function ie(e){try{let o=H();if(e.json){let t=R();console.log(JSON.stringify(t,null,2))}else{let t=R(),n=J(),l=K();console.log(O.bold(`Adam Configuration
|
|
13
13
|
`)),l&&console.log(O.yellow(`No configuration saved. Use Settings UI or create ~/.adam/.env
|
|
14
14
|
`));let i={Anthropic:[["anthropic.apiKey",t["anthropic.apiKey"]],["anthropic.baseUrl",t["anthropic.baseUrl"]],["anthropic.model",t["anthropic.model"]],["anthropic.defaultOpusModel",t["anthropic.defaultOpusModel"]],["anthropic.defaultSonnetModel",t["anthropic.defaultSonnetModel"]],["anthropic.defaultHaikuModel",t["anthropic.defaultHaikuModel"]],["anthropic.smallFastModel",t["anthropic.smallFastModel"]]],Defaults:[["defaults.model",t["defaults.model"]],["defaults.effort",t["defaults.effort"]],["defaults.maxTurns",t["defaults.maxTurns"]],["defaults.maxBudgetUsd",t["defaults.maxBudgetUsd"]],["defaults.timeout",t["defaults.timeout"]]],Server:[["server.port",t["server.port"]],["server.host",t["server.host"]],["server.apiKey",t["server.apiKey"]],["server.timezone",t["server.timezone"]]],Logging:[["logging.level",t["logging.level"]]],Evolution:[["roles.evolution.triggerEvery",t["roles.evolution.triggerEvery"]],["roles.evolution.reflectionThreshold",t["roles.evolution.reflectionThreshold"]]],Chat:[["chat.sessionTimeoutMinutes",t["chat.sessionTimeoutMinutes"]],["chat.maxSessionTurns",t["chat.maxSessionTurns"]],["chat.autoTitle",t["chat.autoTitle"]],["chat.archiveExtractMemory",t["chat.archiveExtractMemory"]]]},c={"anthropic.apiKey":"API Key","anthropic.baseUrl":"Base URL","anthropic.model":"Model","anthropic.defaultOpusModel":"Default Opus","anthropic.defaultSonnetModel":"Default Sonnet","anthropic.defaultHaikuModel":"Default Haiku","anthropic.smallFastModel":"Small Fast","defaults.model":"Default Model","defaults.effort":"Effort","defaults.maxTurns":"Max Turns","defaults.maxBudgetUsd":"Max Budget (USD)","defaults.timeout":"Timeout (sec)","server.port":"Port","server.host":"Host","server.apiKey":"API Key","server.timezone":"Timezone","logging.level":"Log Level","roles.evolution.triggerEvery":"Evolution Trigger Every","chat.sessionTimeoutMinutes":"Session Timeout (min)","chat.maxSessionTurns":"Max Session Turns","chat.autoTitle":"Auto Title","chat.archiveExtractMemory":"Archive Extract Memory","roles.evolution.reflectionThreshold":"Reflection Threshold"};for(let[p,a]of Object.entries(i)){let s=a.filter(([,r])=>r!=null&&r!=="");if(s.length!==0){console.log(O.cyan(`${p}:`));for(let[r,m]of s){let f=c[r]??r,L=r.includes("apiKey")||r.includes("token")||r.includes("secret")?se(String(m)):String(m);console.log(` ${f}: ${L}`)}console.log("")}}if(n){console.log(O.bold(`.env File Values:
|
|
15
15
|
`));let p=["ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_SMALL_FAST_MODEL"];for(let a of p)if(a in n){let s=a.includes("API_KEY");console.log(` ${a}: ${s?se(n[a]):n[a]}`)}console.log("")}}}finally{j()}}function se(e){return!e||e.length<8?"****":e.slice(0,4)+"****"}import w from"chalk";async function ae(e){try{let o=e.limit??"20",t=await h(`/evolution-audit?limit=${o}`);if(t.length===0){console.log(w.dim("No evolution records yet"));return}console.log(w.bold(`Evolution Audit Log (${t.length} records)
|
|
16
16
|
`));for(let n of t){let l=new Date(n.timestamp).toLocaleString();console.log(w.bold(`[${l}]`)+(n.triggerTaskId?w.dim(` task: ${n.triggerTaskId.slice(0,8)}`):"")),console.log(w.dim(" Diff:"));for(let i of n.diff.split(`
|
|
17
|
-
`))i.startsWith("+")?console.log(w.green(` ${i}`)):i.startsWith("-")?console.log(w.red(` ${i}`)):console.log(w.dim(` ${i}`));console.log()}}catch(o){console.error(w.red(o.message)),process.exit(1)}}import g from"chalk";import{WebSocket as
|
|
17
|
+
`))i.startsWith("+")?console.log(w.green(` ${i}`)):i.startsWith("-")?console.log(w.red(` ${i}`)):console.log(w.dim(` ${i}`));console.log()}}catch(o){console.error(w.red(o.message)),process.exit(1)}}import g from"chalk";import{WebSocket as ke}from"ws";function we(){try{let e=_().server?.timezone;return e==="system"||!e?void 0:e}catch{return}}function le(e){let o=we();return new Date(e).toLocaleTimeString(void 0,o?{timeZone:o}:void 0)}async function ce(e){let o=I(),t=e.port?Number(e.port):o.port??7100,n=G(),l=new URL(`ws://localhost:${t}/events`);n&&l.searchParams.set("api_key",n);let i=l.toString(),c=e.component,p=e.level;function a(){let r=new ke(i);r.on("open",()=>{console.log(g.dim(`Connected to ${i}`)),e.follow&&console.log(g.dim("Following logs... (Ctrl+C to exit)"))}),r.on("message",m=>{try{let f=JSON.parse(m.toString());if(f.type==="log_event"&&f.msg){if(c&&f.component!==c||p&&f.level!==p)return;s(f)}}catch{}}),r.on("error",m=>{console.error(g.red(`WebSocket error: ${m.message}`))}),r.on("close",()=>{e.follow&&(console.log(g.yellow("Connection closed, reconnecting...")),setTimeout(a,1e3))})}function s(r){let m=le(r.timestamp),x={debug:g.gray,info:g.blue,warn:g.yellow,error:g.red,fatal:g.bgRed.white}[r.level]||g.white,L=g.cyan(`[${r.component}]`);console.log(`${g.dim(m)} ${x(r.level.toUpperCase().padEnd(5))} ${L} ${r.msg}`),r.metadata&&typeof r.metadata=="object"&&Object.keys(r.metadata).length>0&&console.log(g.dim(" ")+g.dim(JSON.stringify(r.metadata)))}a(),await new Promise(r=>{process.on("SIGINT",()=>r()),process.on("SIGTERM",()=>r()),e.follow||setTimeout(r,3e3)})}var y=new Te;y.name("adam").description("Adam Agent Server CLI").version(B());var E=y.command("server").description("Server management");E.command("start").description("Start the server daemon").action(async()=>{try{let{pid:e,port:o}=await N();console.log(`Server started (PID ${e}, port ${o})`)}catch(e){console.error("Failed to start server:",e.message),process.exit(1)}});E.command("stop").description("Stop the server daemon").action(async()=>{try{await U(),console.log("Server stopped")}catch(e){console.error("Failed to stop server:",e.message),process.exit(1)}});E.command("restart").description("Restart the server daemon").action(async()=>{try{I().running&&(await U(),console.log("Server stopped"));let{pid:o,port:t}=await N();console.log(`Server restarted (PID ${o}, port ${t})`)}catch(e){console.error("Failed to restart server:",e.message),process.exit(1)}});E.command("status").description("Show server status").action(()=>{let e=I();e.running?console.log(`Server is running (PID ${e.pid}, port ${e.port})`):e.pid?console.log("Server not running (stale PID file)"):console.log("Server not running")});E.command("logs").description("Show server logs").option("-f, --follow","Follow log output").action(async e=>{let o=Y();if(!$e(o)){console.log("No log file found");return}if(e.follow){let t=Ie(o,{encoding:"utf-8"});for await(let n of t)process.stdout.write(n)}else console.log(be(o,"utf-8"))});y.command("run <prompt>").description("Submit a task and stream output").option("--model <model>","Model to use").option("--timeout <seconds>","Task timeout",parseInt).option("--budget <usd>","Max budget in USD",parseFloat).option("--template <name>","Task template to use").option("--workspace <path>","Workspace directory").option("--no-approval","Auto-approve all approval requests").option("--json","Output as JSON").option("--server <url>","Server URL").action(Q);var F=y.command("tasks").description("Task management");F.command("list").description("List recent tasks").option("-s, --status <status>","Filter by status").option("-l, --limit <number>","Limit results","20").action(te);F.command("show <id>").description("Show task details").action(re);F.command("cancel <id>").description("Cancel a running task").action(ne);y.command("config").description("Display current configuration").option("--json","Output as JSON").action(ie);y.command("evolution").description("Show self-evolution audit log").option("-l, --limit <number>","Limit results","20").action(ae);y.command("logs").description("Stream server logs in real-time via WebSocket").option("-f, --follow","Follow logs continuously").option("-c, --component <component>","Filter by component (manager, worker, scheduler, api, ws)").option("-l, --level <level>","Filter by level (debug, info, warn, error)").option("-p, --port <port>","Server port").action(ce);y.command("register-ai-digest").description("Register the AI Hourly Digest task template (cron: every hour)").action(()=>{try{q(),console.log("AI Digest template registered successfully")}catch(e){console.error("Failed to register AI Digest template:",e.message),process.exit(1)}});y.action(async()=>{try{await W()}catch{I().running?console.error("Server is running but not responding. Check: adam server logs"):console.error("Server not running. Run: adam server start"),process.exit(1)}let e=(await import("./App-SCPYTYGQ.js")).default,{waitUntilExit:o}=De(Pe.createElement(e));await o()});y.parse();
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as b,b as c,d,e}from"./chunk-3TIHZZMK.js";import{a}from"./chunk-6KLG4APZ.js";import"./chunk-REKCZ3GY.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as DEFAULT_CONFIG,e as getChatConfig,d as getDefaults,b as loadConfig,c as loadDefaultConfig};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c,d,e,f,g}from"./chunk-QMKQBU3R.js";import"./chunk-CREHL4BN.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";g();export{f as deleteConfigValue,c as getAllConfig,a as getConfigValue,e as isConfigEmpty,d as seedConfig,b as setConfigValue};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c,d}from"./chunk-CREHL4BN.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";d();export{c as closeDb,b as getDb,a as runMigrations};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i}from"./chunk-TEMWI6U5.js";import"./chunk-CREHL4BN.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as TTL_MS,g as cleanupExpired,b as createDeliveryLog,i as getDeliveryLogByRule,h as getDeliveryLogByTask,f as getFailedDeliveries,e as getPendingDeliveries,d as markDelivered,c as updateDeliveryLogStatus};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c,d}from"./chunk-NQHTOFQP.js";import"./chunk-BCELBB5Q.js";import"./chunk-GA7GEIXB.js";import"./chunk-ROSOI75V.js";import"./chunk-BONI2HUN.js";import"./chunk-4TBGFHYX.js";import"./chunk-64FIXWFL.js";import"./chunk-TEMWI6U5.js";import"./chunk-L7JP7DUO.js";import"./chunk-CREHL4BN.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as DeliveryEngine,b as getDeliveryEngine,c as initDeliveryEngine,d as stopDeliveryEngine};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c,d,e}from"./chunk-PT55643Q.js";import"./chunk-CREHL4BN.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as createEvolutionAudit,e as generateDiff,d as getLatestRoleEvolution,b as listEvolutionAudit,c as listEvolutionAuditByRole};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as i}from"./chunk-6KLG4APZ.js";import"./chunk-WBAPIPST.js";import{c as a,h as c}from"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";c();var u=a("agent");async function m(n){let e=f();if(e.length===0)return{scores:[],errors:[]};let s=[],r=[];for(let t of e)try{let o=await l(t);o!==null&&s.push({nodeId:n,score:o,source:t.name,fetchedAt:Date.now()})}catch(o){r.push(`External API "${t.name}" (${t.url}): ${o instanceof Error?o.message:String(o)}`),u.warn({endpoint:t.name,error:o},"External API fetch failed")}return{scores:s,errors:r}}async function l(n){let e=await fetch(n.url,{signal:AbortSignal.timeout(5e3),headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`HTTP ${e.status} ${e.statusText}`);let s=await e.json(),r=p(s,n.scorePath);if(typeof r!="number"||isNaN(r))throw new Error(`Score at "${n.scorePath}" is not a number: ${JSON.stringify(r)}`);return Math.max(0,Math.min(1,r))}function p(n,e){let s=e.replace(/^\$\.?/,""),r=n;for(let t of s.split(".")){if(r==null||typeof r!="object")return;r=r[t]}return r}function f(){return i.externalApis??[]}export{m as collectExternalApiScores};
|