adam-agent-server 0.4.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-PQC7EI3J.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-ETQ7KC73.js +0 -1
- package/dist/chunk-FYDFMYUP.js +0 -1
- package/dist/chunk-HICJBGGJ.js +0 -86
- package/dist/chunk-JXD6ZPV7.js +0 -2
- package/dist/chunk-MX6AZ7WD.js +0 -1
- 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-DEBMZJBM.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
package/dist/chunk-FYDFMYUP.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var l=["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"],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 T(t){i=JSON.parse(JSON.stringify(t))}function u(){if(!i)throw new Error("Runtime config not initialized. Call initRuntimeConfig first.");return i}function k(t){let o=u(),s=t();for(let[e,n]of Object.entries(s))c(o,e,n)}function v(){let t=u(),o={};for(let[s,e]of Object.entries(d)){let n=g(t,s);n&&typeof n=="string"&&n.length>0?o[e]=n:process.env[e]&&(o[e]=process.env[e])}return o}function A(t,o){let s=u(),e=[],n=[];for(let[r,a]of Object.entries(t)){if(!p(r)){h(r)?n.push(`"${r}" requires restart. Cannot modify at runtime.`):n.push(`"${r}" is not a recognized config path.`);continue}c(s,r,a)&&(e.push(r),o?.(r,a))}return{success:n.length===0,updated:e,errors:n}}function c(t,o,s){let e=o.split("."),n=t;for(let r=0;r<e.length-1;r++)if(n&&typeof n=="object")n=n[e[r]];else return!1;return n&&typeof n=="object"?(n[e[e.length-1]]=s,!0):!1}function g(t,o){let s=o.split("."),e=t;for(let n of s)if(e&&typeof e=="object")e=e[n];else return;return e}function p(t){return l.includes(t)}function h(t){return f.includes(t)}export{l as a,f as b,T as c,u as d,k as e,v as f,A as g,g as h,p as i,h as j};
|
package/dist/chunk-HICJBGGJ.js
DELETED
|
@@ -1,86 +0,0 @@
|
|
|
1
|
-
import{a as ue}from"./chunk-5JLMSNIW.js";import{b as Ge,c as Se,e as Ve}from"./chunk-IXF3XBGX.js";import{b as ie}from"./chunk-AXMXXUPO.js";import{a as tt,c as Me,e as rt}from"./chunk-KICPHTI2.js";import{j as _e}from"./chunk-FUGJMHY4.js";import{d as Re}from"./chunk-PQ7KPALO.js";import{a as Ke}from"./chunk-2GXYBWLS.js";import{a as Be}from"./chunk-WZOMGJSY.js";import{a as ce,b as _,c as de,d as Ze,e as et}from"./chunk-WXN3PSVX.js";import{a as se,b as v,c as U,d as A}from"./chunk-L7426WNY.js";import{a as ke}from"./chunk-L7JP7DUO.js";import{a as We,b as Te,c as Je,g as qe,j as He}from"./chunk-HAWA62R2.js";import{a as Ye,b as B,c as ze,f as Qe,g as Xe}from"./chunk-VF6GJGD6.js";import{d as k,g as je}from"./chunk-FYDFMYUP.js";import{a as Ue,b as le,e as Ie,f as V}from"./chunk-U36NBCR3.js";import{e as $e,f as T,h as F,i as G,j as Oe,k as we,l as ae}from"./chunk-XNWZZYAV.js";import{b,d as oe}from"./chunk-PCSZW2PE.js";import{c as I,d as Fe}from"./chunk-3DAK2XWP.js";import{c as Dt,e as At,f as x}from"./chunk-FCV2DPZQ.js";var wt={};At(wt,{getGlobalEnabledState:()=>z,getInstalledPlugin:()=>Le,getPluginManifest:()=>Q,listInstalledPlugins:()=>C,listMarketplaceSources:()=>Ce,resolvePluginPaths:()=>Ee,scanDirectoryConfig:()=>X});import{existsSync as E,readFileSync as K,readdirSync as yt}from"fs";import{join as y}from"path";import vt from"os";function j(e){try{if(!E(e))return null;let t=K(e,"utf-8");return JSON.parse(t)}catch{return null}}function z(){return j(Xt())?.enabledPlugins??{}}function Q(e){let t=e;function r(n,o){let s={};try{if(!E(n))return s;let l=K(n,"utf-8").replace(/^```yaml\r?\n/,"").replace(/^```\r?\n/,"");for(let u of o){let d=new RegExp(`^${u}:\\s*(.+)$`,"m"),p=l.match(d);p&&(s[u]=p[1].trim())}}catch{}return s}try{let n={name:"",skills:[],agents:[],mcpServers:[],hooks:[],lspServers:[]},o=y(t,".claude-plugin","plugin.json");if(E(o))try{let d=JSON.parse(K(o,"utf-8"));n.name=d.name??"",n.version=d.version,n.description=d.description,Array.isArray(d.lspServers)&&(n.lspServers=d.lspServers),Array.isArray(d.mcpServers)&&(n.mcpServers=d.mcpServers),Array.isArray(d.hooks)&&(n.hooks=d.hooks)}catch{}let s=y(t,"skills");if(E(s)){let d=yt(s,{withFileTypes:!0});for(let p of d){if(!p.isDirectory()&&!p.isSymbolicLink())continue;let g=y(s,p.name,"SKILL.md"),f=r(g,["name","description"]);f.name&&n.skills.push({name:f.name,description:f.description??""})}}let a=y(t,"agents");if(E(a)){let d=yt(a,{withFileTypes:!0});for(let p of d){if(!p.isFile()||!p.name.endsWith(".md"))continue;let g=r(y(a,p.name),["name","description"]);g.name&&n.agents.push({name:g.name,description:g.description??""})}}let l=y(t,".mcp.json");if(E(l))try{let d=JSON.parse(K(l,"utf-8"));d.mcpServers&&typeof d.mcpServers=="object"&&(n.mcpServers=Object.keys(d.mcpServers))}catch{}let u=y(t,"hooks","hooks.json");if(E(u))try{let d=JSON.parse(K(u,"utf-8"));Array.isArray(d)&&(n.hooks=d.map(p=>typeof p=="object"&&p!==null&&"event"in p?String(p.event):String(p)))}catch{}return n}catch{return null}}function C(e){let t=j(xe());if(!t?.plugins)return[];let r=z(),n=[];for(let[o,s]of Object.entries(t.plugins))if(!(!Array.isArray(s)||s.length===0))for(let a of s){let l=a.scope??"user";e?.scope&&l!==e.scope||e?.projectPath&&a.projectPath!==e.projectPath||n.push({id:o,name:o.split("@")[0],version:a.version??"",scope:l,projectPath:a.projectPath,installPath:a.installPath??y(Y(),o),enabled:r[o]??a.enabled??!0,installedAt:a.installedAt??"",lastUpdated:a.lastUpdated??""})}return n}function Le(e){let t=j(xe());if(!t?.plugins?.[e])return null;let r=t.plugins[e];if(!Array.isArray(r)||r.length===0)return null;let n=r[0],o=z();return{id:e,name:e.split("@")[0],version:n.version??"",scope:n.scope??"user",projectPath:n.projectPath,installPath:n.installPath??y(Y(),e),enabled:o[e]??n.enabled??!0,installedAt:n.installedAt??"",lastUpdated:n.lastUpdated??""}}function Ee(e){let t=j(xe()),r=new Map;for(let n of e){let o=t?.plugins?.[n];Array.isArray(o)&&o.length>0&&r.set(n,o[0].installPath??y(Y(),n))}return r}function Ce(){return j(Qt())?.marketplaces??[]}function X(e){let t=y(e,".claude","settings.json"),r=j(t);return{enabledPlugins:r?.enabledPlugins??{},mcpServers:r?.mcpServers??{},allowedTools:r?.allowedTools??[],disallowedTools:r?.disallowedTools??[]}}var Y,xe,Qt,Xt,ye=Dt(()=>{"use strict";Y=()=>y(vt.homedir(),".claude","plugins"),xe=()=>y(Y(),"installed_plugins.json"),Qt=()=>y(Y(),"known_marketplaces.json"),Xt=()=>y(vt.homedir(),".claude","settings.json")});import{createSdkMcpServer as cr,tool as m}from"@anthropic-ai/claude-agent-sdk";import{z as i}from"zod";ae();V();import{v4 as J}from"uuid";oe();function Nt(e){return{id:e.id,goalId:e.goal_id,level:e.level,parentId:e.parent_id??void 0,name:e.name,description:e.description??void 0,weight:e.weight,calibrationFactor:e.calibration_factor,createdAt:e.created_at}}function W(e){b().prepare(`
|
|
2
|
-
INSERT INTO metric_tree (id, goal_id, level, parent_id, name, description,
|
|
3
|
-
weight, calibration_factor, created_at)
|
|
4
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
5
|
-
`).run(e.id,e.goalId,e.level,e.parentId??null,e.name,e.description??null,e.weight,e.calibrationFactor,e.createdAt)}function nt(e){return b().prepare("SELECT * FROM metric_tree WHERE goal_id = ? ORDER BY level, created_at").all(e).map(Nt)}var jt=I("goal-manager");async function un(e){let t;try{let n=JSON.parse(e);t={name:n.name??"",description:n.description,metric:n.metric??"",targetValue:n.targetValue??0,currentValue:n.currentValue??0,deadline:n.deadline??0,budget:n.budget??0,roleId:n.roleId??"engineer",status:"active"}}catch{t=await $t(e)}let r=Ot(t);return{goalState:t,validationResult:r,rawInput:e}}async function $t(e){let t=`Extract SMART goal fields from this natural language input.
|
|
6
|
-
|
|
7
|
-
Input: "${e}"
|
|
8
|
-
|
|
9
|
-
Respond ONLY with a JSON object:
|
|
10
|
-
{
|
|
11
|
-
"name": "short goal name (max 100 chars)",
|
|
12
|
-
"description": "detailed description of what the goal aims to achieve",
|
|
13
|
-
"metric": "measurable metric name (e.g. completion, reports_written, accuracy_score)",
|
|
14
|
-
"targetValue": <number, the target to reach>,
|
|
15
|
-
"deadline_days": <number, days from now to complete>,
|
|
16
|
-
"budget": <number, estimated budget in USD>,
|
|
17
|
-
"role": "<best matching role: engineer | analyst | content_creator | reviewer>"
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
Rules:
|
|
21
|
-
- name: concise, actionable title
|
|
22
|
-
- metric: quantifiable measure of success; use "completion" if the goal is binary (done/not done)
|
|
23
|
-
- targetValue: realistic target for the metric; use 1 for binary goals
|
|
24
|
-
- deadline_days: reasonable timeframe; default 7 if unclear
|
|
25
|
-
- budget: estimated cost in USD; default 5 if unclear
|
|
26
|
-
- role: match to the nature of work (research=analyst, writing=content_creator, coding=engineer, review=reviewer)`;try{let n=(await ue(t,"You extract structured SMART goal fields from natural language. Reply with only valid JSON.")).match(/\{[\s\S]*\}/);if(n){let o=JSON.parse(n[0]),s=o.deadline_days??7;return{name:(o.name??e.slice(0,100)).slice(0,100),description:o.description??e,metric:o.metric??"completion",targetValue:o.targetValue??1,currentValue:0,deadline:Date.now()+s*24*60*60*1e3,budget:o.budget??5,roleId:o.roleId??"engineer",status:"active"}}}catch(r){jt.warn({error:r},"LLM goal parsing failed, using fallback")}return{name:e.trim().slice(0,100),description:e.trim(),metric:"completion",targetValue:1,currentValue:0,deadline:Date.now()+10080*60*1e3,budget:5,roleId:"engineer",status:"active"}}function Ot(e){let t=[],r=[];return(!e.name||e.name.trim().length===0)&&t.push("S: name must be non-empty"),(!e.description||e.description.trim().length===0)&&t.push("S: description must be non-empty"),(!e.metric||e.metric.trim().length===0)&&t.push("M: metric must be specified"),e.targetValue<=0&&t.push("A: targetValue must be > 0"),(!e.roleId||e.roleId.trim().length===0)&&t.push("R: roleId must be non-empty"),e.deadline<=Date.now()&&t.push("T: deadline must be in the future"),e.budget<=0&&r.push("budget is zero or negative; goal will have no spending limit"),{isValid:t.length===0,errors:t,warnings:r}}function pn(e,t,r){let n=J(),o=Date.now(),s={id:n,name:e.name,description:e.description,roleId:e.roleId,metricType:e.metric,targetValue:e.targetValue,currentValue:e.currentValue,deadline:e.deadline,budgetUsd:e.budget,status:e.status,createdAt:o,deliverTo:t,reportTo:r};return ce(s),s}function ot(e,t){let r=Date.now(),n=[],o={id:J(),goalId:e,level:"L0",name:`${t}_goal_progress`,description:`Goal-level ${t} progress (monthly)`,weight:1,calibrationFactor:1,createdAt:r};n.push(o),W(o);let s={id:J(),goalId:e,level:"L1",parentId:o.id,name:`${t}_weekly_trend`,description:`Weekly trend for ${t}`,weight:.8,calibrationFactor:1,createdAt:r};n.push(s),W(s);let a={id:J(),goalId:e,level:"L2",parentId:s.id,name:`${t}_daily_process`,description:`Daily process metric for ${t}`,weight:.6,calibrationFactor:1,createdAt:r};n.push(a),W(a);let l={id:J(),goalId:e,level:"L3",parentId:a.id,name:`${t}_per_task`,description:`Per-task instant metric for ${t}`,weight:.4,calibrationFactor:1,createdAt:r};return n.push(l),W(l),n}var pe=class{static collect(t,r){let n=v(t);if(!n)return this.emptyMetrics(t,r);let o=ie(t,500,0),s=n.completedAt&&n.startedAt?n.completedAt-n.startedAt:0,a=new Set,l=0,u=0;for(let p of o)p.type==="tool_call"&&p.toolName&&a.add(p.toolName),p.type==="error"&&l++,p.type==="approval_request"&&u++;let d={taskId:t,goalId:r,timestamp:Date.now(),durationMs:s,costUsd:n.costUsd??0,turns:n.numTurns??0,toolCount:a.size,errorCount:l,approvalCount:u,rawScore:0,isComplete:n.status==="completed"};return d.rawScore=this.computeRawScore(d),d}static computeRawScore(t){let n=1-Math.min(t.durationMs/6e5,1),s=1-Math.min(t.costUsd/5,1),l=1-Math.min(t.turns/50,1),u;t.toolCount>=3&&t.toolCount<=15?u=1:t.toolCount<3?u=t.toolCount/3:u=Math.max(0,1-(t.toolCount-15)/15);let d=t.errorCount===0?1:Math.max(0,1-t.errorCount*.2),p=Math.min(1,.5+t.approvalCount*.25);return .3*n+.2*s+.2*l+.1*u+.15*d+.05*p}static cache=new Map;static persist(t){this.cache.set(t.taskId,t)}static getCached(t){return this.cache.get(t)}static clearCache(){this.cache.clear()}static emptyMetrics(t,r){return{taskId:t,goalId:r,timestamp:Date.now(),durationMs:0,costUsd:0,turns:0,toolCount:0,errorCount:0,approvalCount:0,rawScore:0,isComplete:!1}}};oe();function Ut(e){return{id:e.id,strategyId:e.strategy_id,goalId:e.goal_id,taskId:e.task_id??void 0,reward:e.reward??void 0,metricL2Score:e.metric_l2_score??void 0,metricL3Score:e.metric_l3_score??void 0,context:e.context??void 0,completedAt:e.completed_at}}function st(e){b().prepare(`
|
|
27
|
-
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 it(e,t=100){return b().prepare("SELECT * FROM trials WHERE goal_id = ? ORDER BY completed_at DESC LIMIT ?").all(e,t).map(Ut)}var me=class{static collect(t){let r=_(t);if(!r)return this.emptyMetrics(t);let n=Date.now(),o=r.targetValue>0?Math.min(r.currentValue/r.targetValue,1):0,s=Math.max(0,(r.deadline-n)/(1e3*60*60*24)),a=this.calculateBudgetSpent(t),l=r.budgetUsd>0?Math.max(0,1-a/r.budgetUsd):1,u=this.calculateExpectedCompletion(r),d={goalId:t,metricType:r.metricType,targetValue:r.targetValue,currentValue:r.currentValue,progressPct:o,deadlineRemainingDays:s,budgetRemainingPct:l,expectedCompletionPct:u,rawScore:0};return d.rawScore=this.computeRawScore(d),d}static computeRawScore(t){let r=Math.min(t.progressPct,1),n;t.expectedCompletionPct>=1?n=1:t.expectedCompletionPct>=.8?n=.5+(t.expectedCompletionPct-.8)*2.5:n=t.expectedCompletionPct*.625;let o=t.budgetRemainingPct;return .5*r+.3*n+.2*o}static calculateExpectedCompletion(t){let r=Date.now(),n=t.deadline-t.createdAt,o=r-t.createdAt;if(n<=0)return 0;let s=o/n;if(s<.1)return .5;let a=t.targetValue>0?t.currentValue/t.targetValue:0;return s>0?a/s:0}static calculateBudgetSpent(t){let r=it(t,1e3),n=0,o=new Set;for(let s of r)if(s.taskId&&!o.has(s.taskId)){o.add(s.taskId);let a=v(s.taskId);a?.costUsd&&(n+=a.costUsd)}return n}static emptyMetrics(t){return{goalId:t,metricType:"",targetValue:0,currentValue:0,progressPct:0,deadlineRemainingDays:0,budgetRemainingPct:0,expectedCompletionPct:0,rawScore:0}}};var Ft=I("agent"),q=class{static cache=new Map;static CACHE_TTL=1440*60*1e3;static async callClaude(t){let o=(await ue(t,'You are an AI quality evaluator. Respond with JSON: {"score": 0-1, "confidence": 0-1, "reasoning": "..."}')).match(/\{[\s\S]*\}/);if(!o)throw new Error("Failed to parse LLM Judge response as JSON");let s=JSON.parse(o[0]);return{score:Math.max(0,Math.min(1,s.score??0)),confidence:Math.max(.3,Math.min(.95,s.confidence??.5)),reasoning:s.reasoning??"No reasoning provided"}}static async evaluate(t,r){let n=`${t}:${r}`,o=this.cache.get(n);if(o&&Date.now()-o.evaluatedAt<this.CACHE_TTL)return o;let s=v(t);if(!s){let g={taskId:t,criteria:r,score:0,confidence:.3,reasoning:"Task not found",evaluatedAt:Date.now()};return this.cache.set(n,g),g}let a=this.getPromptTemplate(s.prompt??"",s.result??s.error??"",r),l,u,d;try{let g=await this.callClaude(a);l=g.score,u=g.confidence,d=g.reasoning}catch(g){Ft.warn({error:g,taskId:t},"LLM Judge Claude API call failed, using heuristic fallback"),s.status==="failed"?(l=.1,u=.6,d=`Task failed: ${s.error??"unknown error"} (heuristic fallback)`):s.status==="completed"&&s.result?(l=.7,u=.5,d="Task completed with result (heuristic fallback due to API error)"):s.status==="completed"?(l=.5,u=.4,d="Task completed without explicit result (heuristic fallback)"):(l=.3,u=.3,d=`Task in status: ${s.status} (heuristic fallback)`)}let p={taskId:t,criteria:r,score:l,confidence:u,reasoning:d,evaluatedAt:Date.now()};return this.cache.set(n,p),p}static shouldUseObjective(t){let r=v(t);return r?r.status==="completed"&&r.costUsd!==void 0&&r.numTurns!==void 0:!1}static clearCache(){this.cache.clear()}static getPromptTemplate(t,r,n){return`You are an expert evaluator. Evaluate the following task result against these criteria:
|
|
31
|
-
|
|
32
|
-
Task: ${t}
|
|
33
|
-
Result: ${r}
|
|
34
|
-
Criteria: ${n}
|
|
35
|
-
|
|
36
|
-
Provide:
|
|
37
|
-
1. Score (0-1): How well did the task meet the criteria?
|
|
38
|
-
2. Confidence (0-1): How confident are you in this evaluation?
|
|
39
|
-
3. Reasoning: Brief explanation of your scoring
|
|
40
|
-
|
|
41
|
-
Respond in JSON: {"score": number, "confidence": number, "reasoning": "string"}`}};var Gt={L0:.2,L1:.15,L2:.35,L3:.3},ge=class e{goalId;nodes;children;constructor(t,r){this.goalId=t,this.nodes=new Map(r.map(n=>[n.id,n])),this.children=new Map;for(let n of r){let o=n.parentId,s=this.children.get(o)??[];s.push(n),this.children.set(o,s)}this.validateAcyclicity()}validateAcyclicity(){for(let t of this.nodes.values()){if(t.parentId&&!this.nodes.has(t.parentId))continue;let r=new Set,n=t.id;for(;n;){if(r.has(n))throw new Error(`Cycle detected in metric tree at node ${n}`);r.add(n),n=this.nodes.get(n)?.parentId}}}static buildFromGoal(t){let r=nt(t);return new e(t,r)}static fromNodes(t,r){return new e(t,r)}queryPath(t){let r=[];for(let n of this.nodes.values())n.level===t&&r.push(n);return r.sort((n,o)=>o.weight-n.weight)}aggregateScores(t,r){let n=this.queryPath(t);if(n.length===0)return 0;let o=0,s=0;for(let a of n){let l=r.get(a.id)??0,u=a.weight*a.calibrationFactor;o+=l*u,s+=u}return s>0?o/s:0}getWeightedScore(t){let r=0;for(let[n,o]of Object.entries(Gt)){let s=this.aggregateScores(n,t);r+=s*o}return Math.max(0,Math.min(1,r))}getNodeCount(){return this.nodes.size}getChildren(t){return this.children.get(t)??[]}};var An=I("agent");function fe(e,t){let r=Date.now(),n=ge.buildFromGoal(e),o=new Map,s=me.collect(e);for(let u of n.queryPath("L0"))o.set(u.id,s.rawScore);let a=Vt(n);if(t){let u=pe.collect(t,e);if(u.isComplete){for(let p of n.queryPath("L3"))o.set(p.id,u.rawScore);let d=n.getNodeCount()>0?n.getWeightedScore(o):Math.max(0,Math.min(1,u.rawScore*.65+s.rawScore*.35));return{goalId:e,taskId:t,reward:d,breakdown:{L0:s.rawScore,L1:0,L2:0,L3:u.rawScore},calibrationFactors:a,source:"objective",confidence:.9,computedAt:r}}}if(t&&!q.shouldUseObjective(t)){let d=q.evaluate(t,"general_quality"),p=s.rawScore*.5+.5*.5;return{goalId:e,taskId:t,reward:s.rawScore,breakdown:{L0:s.rawScore,L1:0,L2:0,L3:0,llmJudge:.5},calibrationFactors:a,source:"llm_judge",confidence:.4,computedAt:r}}let l=n.getNodeCount()>0?n.getWeightedScore(o):s.rawScore;return{goalId:e,reward:l,breakdown:{L0:s.rawScore,L1:0,L2:0,L3:0},calibrationFactors:a,source:"fallback",confidence:.3,computedAt:r}}function Vt(e){let t={L0:1,L1:1,L2:1,L3:1};for(let r of["L0","L1","L2","L3"]){let n=e.queryPath(r);n.length>0&&(t[r]=n[0].calibrationFactor)}return t}import{v4 as ut}from"uuid";oe();function he(e){return{id:e.id,roleId:e.role_id,taskType:e.task_type,name:e.name,promptTemplate:e.prompt_template,alpha:e.alpha,beta:e.beta,totalTrials:e.total_trials,avgReward:e.avg_reward??void 0,createdAt:e.created_at,updatedAt:e.updated_at??void 0}}function at(e){b().prepare(`
|
|
42
|
-
INSERT INTO strategies (id, role_id, task_type, name, prompt_template,
|
|
43
|
-
alpha, beta, total_trials, avg_reward, created_at, updated_at)
|
|
44
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
45
|
-
`).run(e.id,e.roleId,e.taskType,e.name,e.promptTemplate,e.alpha,e.beta,e.totalTrials,e.avgReward??null,e.createdAt,e.updatedAt??null)}function lt(e){let r=b().prepare("SELECT * FROM strategies WHERE id = ?").get(e);return r?he(r):void 0}function $n(e=100){return b().prepare("SELECT * FROM strategies ORDER BY created_at LIMIT ?").all(e).map(he)}function ct(e){return b().prepare("SELECT * FROM strategies WHERE role_id = ? ORDER BY created_at").all(e).map(he)}function L(e,t){return b().prepare("SELECT * FROM strategies WHERE role_id = ? AND task_type = ? ORDER BY created_at").all(e,t).map(he)}function dt(e,t){b().prepare(`
|
|
46
|
-
UPDATE strategies
|
|
47
|
-
SET alpha = alpha + ?,
|
|
48
|
-
beta = beta + ?,
|
|
49
|
-
total_trials = total_trials + 1,
|
|
50
|
-
avg_reward = CASE
|
|
51
|
-
WHEN total_trials = 0 THEN ?
|
|
52
|
-
ELSE (avg_reward * total_trials + ?) / (total_trials + 1)
|
|
53
|
-
END,
|
|
54
|
-
updated_at = ?
|
|
55
|
-
WHERE id = ?
|
|
56
|
-
`).run(t,1-t,t,t,Date.now(),e)}var H=class{static sampleBeta(t,r){let n=this.sampleGamma(t,1),o=this.sampleGamma(r,1);return n/(n+o)}static sampleGamma(t,r){if(t<1)return this.sampleGamma(t+1,r)*Math.pow(Math.random(),1/t);let n=t-1/3,o=1/Math.sqrt(9*n);for(;;){let s,a;do s=this.randn(),a=1+o*s;while(a<=0);a=a*a*a;let l=Math.random();if(l<1-.0331*s*s*s*s||Math.log(l)<.5*s*s+n*(1-a+Math.log(a)))return n*a/r}}static randn(){let t=Math.random(),r=Math.random();return Math.sqrt(-2*Math.log(t))*Math.cos(2*Math.PI*r)}static sample(t){if(t.length===0)return null;let r=null,n=-1;for(let o of t){let s=this.sampleBeta(o.alpha,o.beta);s>n&&(n=s,r=o)}return r}static getProbabilities(t,r=1e4){let n=new Map;for(let s=0;s<r;s++){let a=this.sample(t);a&&n.set(a.id,(n.get(a.id)||0)+1)}let o=new Map;for(let[s,a]of n)o.set(s,a/r);return o}};var Bt=5,Pe=20,pt=.5,S=class{static selectStrategy(t,r){let n=L(t,r);return H.sample(n)}static recordTrial(t,r,n,o,s,a,l){dt(t,o),st({id:ut(),strategyId:t,goalId:r,taskId:n,reward:o,metricL2Score:s,metricL3Score:a,context:l,completedAt:Date.now()})}static getStrategies(t,r){return L(t,r)}static getStrategyById(t){return lt(t)}static getPopulationStats(t,r){let n=L(t,r);if(n.length===0)return{count:0,avgTrials:0,avgReward:0,minTrials:0,maxTrials:0};let s=n.reduce((u,d)=>u+d.totalTrials,0)/n.length,a=n.filter(u=>u.avgReward!==void 0).map(u=>u.avgReward),l=a.length>0?a.reduce((u,d)=>u+d,0)/a.length:0;return{count:n.length,avgTrials:s,avgReward:l,minTrials:Math.min(...n.map(u=>u.totalTrials)),maxTrials:Math.max(...n.map(u=>u.totalTrials))}}static shouldEvolve(t,r){let n=this.getPopulationStats(t,r);return n.count<Bt?!0:n.count<Pe&&n.maxTrials>0}static addStrategy(t,r,n,o){if(L(t,r).length>=Pe)throw new Error(`Strategy population at maximum (${Pe}) for ${t}/${r}`);let a={id:`strat-${ut().slice(0,8)}`,roleId:t,taskType:r,name:n,promptTemplate:o,alpha:pt,beta:pt,totalTrials:0,createdAt:Date.now()};return at(a),a}static getTopStrategies(t,r,n=3){let s=L(t,r).filter(a=>a.totalTrials>0);return s.sort((a,l)=>(l.avgReward??0)-(a.avgReward??0)),s.slice(0,n)}static getSamplingProbabilities(t,r){let n=L(t,r);return H.getProbabilities(n)}static evaluateAndRecord(t,r,n,o,s,a){let l=fe(r,n);return this.recordTrial(t,r,n,l.reward,o,s,a),l.reward}};var Wt=3,Jt=2,be=class{static async generateVariants(t,r,n=Wt,o=Jt){let s=S.getTopStrategies(t,r,n);if(s.length===0){let l=`baseline-${r}-v1`;return S.addStrategy(t,r,l,this.generateBaselinePrompt(t,r)),[l]}let a=[];for(let l=0;l<o;l++){let u=s[0].totalTrials+l+1,d=`${r}-evolved-v${u}`,p=s[0].promptTemplate,g=this.mutateTemplate(p);S.addStrategy(t,r,d,g),a.push(d)}return a}static generateBaselinePrompt(t,r){return`You are a ${t} agent specializing in ${r}.
|
|
57
|
-
|
|
58
|
-
## Core Focus
|
|
59
|
-
Complete tasks with high quality.
|
|
60
|
-
|
|
61
|
-
## Approach
|
|
62
|
-
1. Understand the task requirements thoroughly
|
|
63
|
-
2. Plan your approach before executing
|
|
64
|
-
3. Execute systematically, checking your work
|
|
65
|
-
4. Verify completion against requirements`}static mutateTemplate(t){let r=[this.addProcessEmphasis(),this.addQualityFocus(),this.addVerificationStep()],n=r[Math.floor(Math.random()*r.length)];return`${t}
|
|
66
|
-
|
|
67
|
-
## Evolution
|
|
68
|
-
${n}`}static addProcessEmphasis(){let t=["Break down complex tasks into smaller steps","Iterate on solutions, testing each component","Document your reasoning at each step"];return`**Process:** ${t[Math.floor(Math.random()*t.length)]}`}static addQualityFocus(){let t=["Double-check all outputs before completing","Consider edge cases and error conditions","Optimize for correctness over speed"];return`**Quality:** ${t[Math.floor(Math.random()*t.length)]}`}static addVerificationStep(){return"**Verification:** After completing, verify your work meets all requirements."}static async generateWithLLM(t,r,n){return{promptTemplate:this.generateBaselinePrompt(t,r),rationale:"Generated baseline - LLM integration in Phase 5"}}};import{tool as N}from"@anthropic-ai/claude-agent-sdk";import{z as h}from"zod";import{v4 as qt}from"uuid";function M(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}var Ht={query:h.string().describe("Search query for memory retrieval"),roleId:h.string().optional().describe("Role ID to scope search (omit for cross-role)"),topK:h.number().optional().describe("Max results to return (default 5)")},Kt={query:h.string().describe("Search query for memory retrieval"),topK:h.number().optional().describe("Max results to return (default 5)")},Yt={id:h.string().optional().describe("Memory ID to update. Omit to create new."),roleId:h.string().describe("Role ID to save memory under"),content:h.string().describe("Memory content text"),type:h.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:h.array(h.string()).optional().describe("Keywords for BM25 search"),importance:h.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:h.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},zt={id:h.string().optional().describe("Memory ID to update. Omit to create new."),content:h.string().describe("Memory content text"),type:h.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:h.array(h.string()).optional().describe("Keywords for BM25 search"),importance:h.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:h.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},mt={id:h.string().describe("Memory ID to delete")};async function gt(e,t){let r=e??t.roleId,n=t.topK??5,o=await Ke(r,t.query,{topK:n});return M({results:o.map(s=>({id:s.id,type:s.type,content:s.content,keywords:s.keywords,importance:s.importance,score:s.score}))})}async function ft(e,t){let r=e??t.roleId;if(!r)return M({error:"roleId is required"});let n,o=!0;try{n=await Be(t.content)}catch{o=!1}if(t.id){if(!Te(t.id))return M({error:`Memory ${t.id} not found`});let u=Je(t.id,{content:t.content,embedding:n,keywords:t.keywords,importance:t.importance,type:t.type});return M({id:t.id,action:"updated",success:u,embeddingUpdated:o})}let s=`mem-${qt().slice(0,8)}`,a=Date.now();return We({id:s,roleId:r,type:t.type??"thought",content:t.content,embedding:n,keywords:t.keywords??[],importance:t.importance??3,sourceType:"manual",createdAt:a,lastAccessed:a,retrievedCount:0,tier:t.tier??"episodic"}),M({id:s,action:"created",success:!0,embeddingUpdated:o})}async function ht(e,t){if(e){let r=Te(t.id);if(!r)return M({error:`Memory ${t.id} not found`});if(r.roleId!==e)return M({error:`Memory ${t.id} does not belong to this role`})}return He(t.id),M({id:t.id,deleted:!0})}function bt(e){return e?[N("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",Kt,async t=>gt(e,t)),N("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",zt,async t=>ft(e,t)),N("delete_memory","Delete a memory by ID.",mt,async t=>ht(e,t))]:[N("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",Ht,async t=>gt(void 0,t)),N("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",Yt,async t=>ft(void 0,t)),N("delete_memory","Delete a memory by ID.",mt,async t=>ht(void 0,t))]}import{v4 as w}from"uuid";ye();import{spawnSync as It}from"child_process";import{createRequire as Zt}from"module";import{dirname as er,join as St}from"path";import{openSync as tr,readFileSync as rr,unlinkSync as nr}from"fs";var or=3e4,kt=12e4;function Tt(){let t=Zt(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk");return St(er(t),"cli.js")}function Z(e,t){let r=Tt(),n=t?.timeout??or;if(t?.json){let s=St("/tmp",`adam-cli-stdout-${process.pid}-${Date.now()}.txt`),a=tr(s,"w");try{let l=It("node",[r,...e],{cwd:t.cwd,timeout:n,stdio:["ignore",a,"pipe"],encoding:"utf-8"});if(l.status!==0)throw new Error(l.stderr?.trim()||`CLI exited with status ${l.status}`);return rr(s,"utf-8")}finally{try{nr(s)}catch{}}}let o=It("node",[r,...e],{cwd:t?.cwd,timeout:n,encoding:"utf-8"});if(o.status!==0)throw new Error(o.stderr?.trim()||`CLI exited with status ${o.status}`);return o.stdout}function Rt(){let e=Z(["plugin","list","--available","--json"],{json:!0});return JSON.parse(e)}function De(e,t="user",r){return Z(["plugin","install",e,"--scope",t],{cwd:r,timeout:kt})}function Ae(e,t,r){return Z(["plugin","uninstall",e],{cwd:r,timeout:kt})}function _t(e,t){return Z(["plugin","enable",e])}function Mt(e,t){return Z(["plugin","disable",e])}function co(){try{return!!Tt()}catch{return!1}}ye();V();var ir={Read:{category:"File",label:"read"},Write:{category:"File",label:"write"},Edit:{category:"File",label:"edit"},Glob:{category:"Search",label:"find files"},Grep:{category:"Search",label:"search content"},Bash:{category:"Execution",label:"shell commands"},WebSearch:{category:"Web",label:"web search"},WebFetch:{category:"Web",label:"fetch pages"},NotebookEdit:{category:"Execution",label:"Jupyter notebooks"}};function ee(e,t){let r=e.allowedTools??[];if(r.length===0)return"No tool permissions";let n=new Map,o=[];for(let d of r){let p=ir[d];if(p){let g=n.get(p.category)??[];g.push(p.label),n.set(p.category,g)}else o.push(d)}let s=[];for(let[d,p]of n)s.push(`${d} (${p.join(", ")})`);o.length>0&&s.push(o.join(", "));let a=s.join(" \xB7 "),l=Object.keys(e.mcpServers??{});l.length>0&&(a+=` \xB7 MCP: ${l.join(", ")}`);let u=e.additionalDirectories??[];if(u.length>0&&(a+=` \xB7 Dirs: ${u.map(d=>d.path).join(", ")}`),t&&t.plugins.length>0){let d=t.plugins.map(p=>{let g=[];return p.skills.length>0&&g.push(`skills: ${p.skills.map(f=>f.name).join(", ")}`),p.agents.length>0&&g.push(`agents: ${p.agents.map(f=>f.name).join(", ")}`),g.length>0?`${p.name} (${g.join("; ")})`:p.name});a+=` \xB7 Plugins: ${d.join(", ")}`}return a}function ar(e){let t=[],r=e.additionalDirectories??[];for(let n of r){if(!n.inheritPlugins&&!n.inheritMcp)continue;let o=X(n.path),s=Object.entries(o.enabledPlugins).filter(([,l])=>l).map(([l])=>l),a=Ee(s);for(let[,l]of a)t.includes(l)||t.push(l)}try{let n=Ue(e.name),o=C({scope:"project",projectPath:n});for(let s of o)s.installPath&&!t.includes(s.installPath)&&t.push(s.installPath)}catch{}return t}function Ne(e){let t=ar(e),r=[];for(let n of t){let o=Q(n);o&&r.push({name:o.name||n.split("/").pop()||"unknown",description:o.description,skills:o.skills,agents:o.agents,mcpServers:o.mcpServers,hooks:o.hooks})}return{plugins:r}}oe();function lr(e){return{id:e.id,roleId:e.role_id??void 0,taskPattern:e.task_pattern,maxRiskLevel:e.max_risk_level,createdAt:e.created_at,createdByTaskId:e.created_by_task_id??void 0}}var Pt={low:1,medium:2,high:3};function xt(e){b().prepare(`
|
|
69
|
-
INSERT INTO approval_rules (id, role_id, task_pattern, max_risk_level, created_at, created_by_task_id)
|
|
70
|
-
VALUES (?, ?, ?, ?, ?, ?)
|
|
71
|
-
`).run(e.id,e.roleId??null,e.taskPattern,e.maxRiskLevel,e.createdAt,e.createdByTaskId??null)}function fo(e,t,r){let o=b().prepare("SELECT * FROM approval_rules ORDER BY created_at DESC").all();for(let s of o)if(!(s.role_id&&s.role_id!==e)&&!(Pt[r]>Pt[s.max_risk_level]))try{if(new RegExp(s.task_pattern,"i").test(t))return lr(s)}catch{}}import*as Lt from"crypto";var te=I("api"),re=class{cancelTask(t){let r=v(t);r&&(U(t,{status:"cancelled",completedAt:Date.now()}),ke.emit({type:"task_status_change",taskId:t,oldStatus:r.status,newStatus:"cancelled"}),te.debug({taskId:t,oldStatus:r.status},"Task cancelled"))}resolveApproval(t,r,n){return te.debug({approvalId:t,action:r,reason:n},"Approval resolved (no-op in Pure C)"),!0}resolvePlanApproval(t,r,n,o){let s=Ge(t);if(!s)return te.warn({planId:t},"Plan not found or already resolved"),!1;let a=v(s.taskId);return a?(Ve(t,r==="allow"?"approved":"denied",n),r==="allow"&&n==="permanent"&&xt({id:Lt.randomUUID(),roleId:s.roleId,taskPattern:a.prompt.slice(0,100).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),maxRiskLevel:s.plan.overallRisk,createdAt:Date.now(),createdByTaskId:a.id}),ke.emit({type:"plan_approval_decision",taskId:a.id,planId:t,decision:r,approvalType:n,reason:o}),te.debug({planId:t,decision:r,approvalType:n},"Plan approval resolved"),!0):(te.warn({planId:t},"Task not found for plan"),!1)}};var ve=I("manager");function c(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}async function P(e){let{listChannels:t}=await import("./channels-VEUBY2NZ.js"),r=t(),{listSessions:n}=await import("./session-manager-45LFTPBA.js"),o=[...n("active"),...n("archived")],s=[];for(let a of e)if(a.type==="session"&&a.sessionId)s.push({type:"session",sessionId:a.sessionId});else if(a.type==="channel"){let l=a.channelId,u=a.chatId;if(!l&&a.channelName){let d=r.find(p=>p.name.toLowerCase().includes(a.channelName.toLowerCase()));d&&(l=d.id)}if(l&&!u){let d=o.find(p=>p.source.type==="channel"&&p.source.channelId===l&&p.source.chatId);d?.source.chatId?u=d.source.chatId:u=r.find(g=>g.id===l)?.config?.userId}l&&u?s.push({type:"channel",channelId:l,chatId:u}):ve.warn({channelName:a.channelName,channelId:l,chatId:u},"Could not resolve channel notify target")}return s}async function dr(e){let{listRoles:t}=await import("./roles-SG2YAR64.js"),r=t(void 0,100,0);for(let n of r)if(n.name.toLowerCase().includes(e.toLowerCase()))return n.id}var ur={goalId:i.string()},pr={goalId:i.string(),status:i.string().optional(),currentValue:i.number().optional(),budgetUsd:i.number().optional(),notes:i.string().optional()},mr={goalId:i.string(),goalDescription:i.string(),maxSubtasks:i.number().optional()},D=i.union([i.object({type:i.literal("session"),sessionId:i.string()}),i.object({type:i.literal("channel"),channelName:i.string()}),i.object({type:i.literal("channel"),channelId:i.string(),chatId:i.string().optional()})]),gr={prompt:i.string(),roleId:i.string().describe("Role ID. Call list_roles first to find the best role for the task."),deliverTo:i.array(D).optional().describe("Where to deliver the task output (result full text). E.g., send result to a specific channel."),reportTo:i.array(D).optional().describe("Where to send status reports (completion summary). Defaults to the originating channel/session."),toolOverrides:i.object({allowedTools:i.array(i.string()).optional(),disallowedTools:i.array(i.string()).optional()}).optional()},fr={taskId:i.string(),goalId:i.string().optional(),strategyId:i.string().optional()},hr={roleId:i.string(),taskType:i.string(),name:i.string().optional()},br={status:i.string().optional(),limit:i.number().optional()},yr={taskId:i.string(),roleId:i.string()},vr={taskId:i.string().optional(),status:i.string().optional(),limit:i.number().optional()},wr={roleId:i.string(),allowedPaths:i.array(i.string()).optional(),deniedPaths:i.array(i.string()).optional(),allowedTools:i.array(i.string()).optional(),disallowedTools:i.array(i.string()).optional(),additionalDirectories:i.array(i.object({path:i.string(),inheritPlugins:i.boolean().optional(),inheritMcp:i.boolean().optional(),inheritPermissions:i.boolean().optional()})).optional(),allowedChannels:i.array(i.string()).optional(),inheritUserSettings:i.boolean().optional().describe("Enable/disable inheriting user-level settings (global plugins, MCP servers). Default: false (isolated).")},Ir={roleId:i.string().optional(),limit:i.number().optional()},Sr={name:i.string(),cagPrompt:i.string(),traits:i.array(i.string()).optional(),allowedTools:i.array(i.string()).optional(),disallowedTools:i.array(i.string()).optional(),additionalDirectories:i.array(i.object({path:i.string(),inheritPlugins:i.boolean().optional(),inheritMcp:i.boolean().optional(),inheritPermissions:i.boolean().optional()})).optional()},kr={roleId:i.string(),reason:i.string().optional()},Tr={name:i.string(),description:i.string().optional(),roleId:i.string().optional(),metric:i.string().optional(),targetValue:i.number().optional(),deadline:i.number().optional(),budgetUsd:i.number().optional(),deliverTo:i.array(D).optional().describe("Where to deliver goal completion notifications.")},Rr={name:i.string(),description:i.string().optional(),triggerType:i.enum(["cron","event"]),triggerCron:i.string().optional(),triggerEvent:i.string().optional(),prompt:i.string(),roleId:i.string().optional(),enabled:i.boolean().optional(),goalIds:i.array(i.string()).optional(),deliverTo:i.array(D).optional().describe("Where to deliver the task output (result full text)."),reportTo:i.array(D).optional().describe("Where to send status reports (completion summary).")},_r={status:i.enum(["active","retired","probation"]).optional(),limit:i.number().optional()},Mr={enabled:i.boolean().optional()},Pr={},xr={},Lr={prompt:i.string().describe("The task prompt to execute after the delay"),delayMinutes:i.number().optional().describe("Minutes from now to execute (e.g., 30 for 'half an hour later')"),runAt:i.string().optional().describe("ISO 8601 timestamp to execute at (e.g., '2026-04-01T15:00:00+08:00')"),roleId:i.string().describe("Role ID to assign the task to. Call list_roles first."),deliverTo:i.array(D).optional().describe("Where to deliver the task output (result full text)."),reportTo:i.array(D).optional().describe("Where to send status reports (completion summary).")},Er={roleId:i.string().optional().describe("If provided, shows which plugins are installed in that role's workspace.")},Cr={roleId:i.string().describe("Role ID to install the plugin under (project-scope)."),pluginId:i.string().describe("Plugin ID (e.g. 'github@anthropic'). Use list_available_plugins to discover available plugins.")},Dr={roleId:i.string().describe("Role ID to uninstall the plugin from."),pluginId:i.string().describe("Plugin ID to uninstall.")},Ar={roleId:i.string().describe("Role ID to bind the MCP server to."),mcpName:i.string().describe("Name for this MCP server (e.g., 'github', 'filesystem')."),mcpConfig:i.record(i.string(),i.unknown()).describe("MCP server configuration object.")},Nr={roleId:i.string().describe("Role ID to unbind the MCP server from."),mcpName:i.string().describe("Name of the MCP server to remove.")},jr={pluginId:i.string().describe("Plugin ID (e.g., 'github@anthropic').")},$r={pluginId:i.string().describe("Plugin ID (e.g., 'github@anthropic').")},Or={pluginId:i.string().describe("Plugin ID (e.g., 'github@anthropic').")},Ur={pluginId:i.string().describe("Plugin ID (e.g., 'github@anthropic').")},Fr={},Gr={},Vr={pluginId:i.string().describe("Plugin ID (e.g., 'github@anthropic').")},Br={roleId:i.string().describe("Role ID to associate scanned plugins with."),path:i.string().describe("Directory path to scan for .claude/settings.json.")},Wr={taskId:i.string().describe("Task ID to cancel.")},Jr={taskId:i.string().describe("Task ID to get logs for."),limit:i.number().optional().describe("Max log entries (default 20).")},qr={roleId:i.string().describe("Role ID to delete.")},Hr={},Kr={updates:i.record(i.string(),i.unknown()).describe("Config key-value pairs to update. Example: { 'defaults.maxTurns': 50, 'logging.level': 'debug' }")},Yr={roleId:i.string().describe("Role ID to list memories for."),limit:i.number().optional().describe("Max results (default 20).")},zr={templateId:i.string().describe("Template ID to update."),name:i.string().optional(),enabled:i.boolean().optional(),prompt:i.string().optional(),triggerCron:i.string().optional(),triggerEvent:i.string().optional(),roleId:i.string().optional()},Qr={templateId:i.string().describe("Template ID to delete.")},Xr={templateId:i.string().describe("Template ID to run immediately.")},Zr={enabled:i.boolean().optional().describe("Filter by enabled status.")},en={eventType:i.string().describe("Event type that triggers this rule (e.g., 'task_complete')."),channelId:i.string().describe("Channel ID to deliver to."),format:i.string().optional().describe("Format template (e.g., 'summary', 'full'). Default: 'summary'."),matchCriteria:i.record(i.string(),i.unknown()).optional().describe("JSON match criteria for event fields."),enabled:i.boolean().optional().describe("Enable this rule immediately (default true).")},tn={ruleId:i.string().describe("Delivery rule ID to delete.")},rn={roleId:i.string().optional().describe("Role ID to filter strategies by.")},Et=[m("read_goal_state","Read a single goal's detailed state: progress percentage, time remaining, budget spent, and current value. Use this for deep-dive on one goal; use list_goals for an overview of all goals.",ur,async e=>{let t=_(e.goalId);if(!t)return c({error:"Goal not found"});let r=Date.now(),n=t.targetValue>0?t.currentValue/t.targetValue:0;return c({id:t.id,name:t.name,description:t.description,roleId:t.roleId,metricType:t.metricType,targetValue:t.targetValue,currentValue:t.currentValue,deadline:t.deadline,budgetUsd:t.budgetUsd,status:t.status,progress:n,timeRemainingMs:Math.max(0,t.deadline-r),budgetRemainingUsd:t.budgetUsd})}),m("update_goal_state","Update a goal's status, current value, or budget.",pr,async e=>{let t={};return e.status&&(t.status=e.status),e.currentValue!==void 0&&(t.currentValue=e.currentValue),e.budgetUsd!==void 0&&(t.budgetUsd=e.budgetUsd),Object.keys(t).length>0&&(t.updatedAt=Date.now(),de(e.goalId,t)),c({success:!0})}),m("decompose_goal","Decompose a goal into actionable subtasks using LLM reasoning.",mr,async e=>{let t=k(),r=Math.min(e.maxSubtasks??5,10);try{let{query:o}=await import("@anthropic-ai/claude-agent-sdk"),s=`Decompose this goal into ${r} actionable subtasks.
|
|
72
|
-
|
|
73
|
-
Goal: ${e.goalDescription}
|
|
74
|
-
|
|
75
|
-
Respond ONLY with a JSON array. Each item: {"description": "...", "prompt": "detailed task instruction", "complexity": "low|medium|high", "role": "engineer|analyst|content_creator|reviewer"}
|
|
76
|
-
|
|
77
|
-
Rules:
|
|
78
|
-
- Each subtask must be independently executable
|
|
79
|
-
- Order from foundational to dependent
|
|
80
|
-
- Be specific about what each subtask should accomplish
|
|
81
|
-
- For each subtask, specify the best role from: 'engineer', 'analyst', 'content_creator', 'reviewer'. Match role to the nature of the work.`,a=o({prompt:s,options:{cwd:process.cwd(),maxTurns:1,maxBudgetUsd:.02}}),l="";for await(let d of a){let p=d;p.type==="result"&&typeof p.result=="string"&&(l=p.result)}let u=l.match(/\[[\s\S]*\]/);if(u){let d=JSON.parse(u[0]),p=[];for(let g=0;g<Math.min(d.length,r);g++){let f=d[g],ne=`subtask-${w().slice(0,8)}`,$=f.role,O=$?await dr($):void 0;se({id:ne,status:"pending",prompt:f.prompt,parentId:e.goalId,roleId:O,config:t.defaults,createdAt:Date.now()}),p.push({id:ne,description:f.description,prompt:f.prompt,dependencies:g>0?[p[g-1].id]:[],estimatedComplexity:f.complexity??"medium",role:$})}if(p.length>0)return c({subtasks:p})}}catch(o){ve.error({error:o},"LLM decomposition failed, using fallback")}let n=[];for(let o=0;o<r;o++){let s=`subtask-${w().slice(0,8)}`,a=`Subtask ${o+1} of goal: ${e.goalDescription.slice(0,100)}`,l=`${e.goalDescription}
|
|
82
|
-
|
|
83
|
-
Subtask ${o+1}/${r}`;se({id:s,status:"pending",prompt:l,parentId:e.goalId,config:t.defaults,createdAt:Date.now()}),n.push({id:s,description:a,prompt:l,dependencies:o>0?[n[o-1].id]:[],estimatedComplexity:"medium"})}return c({subtasks:n})}),m("dispatch_task","Create and immediately dispatch a task to the execution pool. roleId is required \u2014 call list_roles first to find the best role. The assigned role determines which tools the worker can use. Pass deliverTo (result delivery) and/or reportTo (status reports) to route output when the task completes.",gr,async e=>{let t=T(e.roleId);if(!t||t.status!=="active"){let O=G("active",20,0).filter(R=>R.source!=="system").map(R=>({id:R.id,name:R.name,allowedTools:R.allowedTools??[],capabilitySummary:ee(R)}));return c({error:`Role not found or not active: ${e.roleId}. Pick a roleId from the list below.`,availableRoles:O})}let r=w(),n=k(),o=e.prompt.toLowerCase(),s={coding:["code","implement","fix","debug","refactor","build"],analysis:["analyze","data","report","statistics","investigate"],content:["write","translate","summarize","content","draft"],review:["review","check","audit","evaluate","assess"],admin:["config","permission","deploy","manage"]},a="general";for(let[O,R]of Object.entries(s))if(R.some(Ct=>o.includes(Ct))){a=O;break}let l,u=e.prompt,d=S.selectStrategy(e.roleId,a);d?.promptTemplate&&(u=`${d.promptTemplate}
|
|
84
|
-
|
|
85
|
-
## Task
|
|
86
|
-
${e.prompt}`,l=d.id);let p=[...n.defaults.allowedTools];e.toolOverrides?.allowedTools&&(p=[...e.toolOverrides.allowedTools]);let g={...n.defaults,allowedTools:p,disallowedTools:e.toolOverrides?.disallowedTools??n.defaults.disallowedTools},f=e.deliverTo?await P(e.deliverTo):void 0,ne=e.reportTo?await P(e.reportTo):void 0;se({id:r,status:"pending",prompt:u,roleId:e.roleId,deliverTo:f,reportTo:ne,config:g,createdAt:Date.now()});let{serverBus:$}=await import("./server-bus-GEGVMSCA.js");return $.emit({type:"task_created",taskId:r}),c({taskId:r,roleId:e.roleId,strategyId:l})}),m("evaluate_result","Evaluate a completed task's result and record a trial for Thompson Sampling.",fr,async e=>{let{goalId:t,taskId:r,strategyId:n}=e,o=fe(t??"",r);return n&&t&&S.recordTrial(n,t,r,o.reward,o.breakdown.L2||void 0,o.breakdown.L3||void 0,"Evaluated via adam-tools"),c({reward:o.reward,metricL2Score:o.breakdown.L2||void 0,metricL3Score:o.breakdown.L3||void 0,source:o.source,reasoning:`Evaluated via ${o.source} with confidence ${o.confidence.toFixed(2)}`})}),m("create_strategy","Create a new strategy variant for a role/taskType using LLM evolution.",hr,async e=>{let{roleId:t,taskType:r}=e;await be.generateVariants(t,r,3,1);let n=S.getStrategies(t,r),o=n[n.length-1];return c(o?{id:o.id,name:o.name,promptTemplate:o.promptTemplate}:{error:`Failed to create strategy for ${t}/${r}`})}),m("list_goals","List all goals with progress percentage, budget, deadline, and time remaining. Goal statuses: active (in progress), paused, completed, failed. Use this to check current goal status before making decisions.",br,async e=>{let t=e.status;return c(Ze(t,e.limit??10,0))}),m("delete_goal","Delete a goal by ID.",{goalId:i.string()},async e=>_(e.goalId)?(et(e.goalId),c({success:!0,goalId:e.goalId})):c({error:"Goal not found"})),m("pause_goal","Pause an active goal.",{goalId:i.string()},async e=>_(e.goalId)?(de(e.goalId,{status:"paused",updatedAt:Date.now()}),c({success:!0,goalId:e.goalId,status:"paused"})):c({error:"Goal not found"})),m("assign_role","Assign a role to a pending task.",yr,async e=>{let{taskId:t,roleId:r}=e;if(!v(t))return c({error:`Task not found: ${t}`});let o=T(r);return o?(U(t,{roleId:r}),ve.debug({taskId:t,roleId:r,roleName:o.name},"Role assigned to task"),c({success:!0,taskId:t,roleId:r})):c({error:`Role not found: ${r}`})}),...bt(),m("read_task_status","Read a single task's details (prompt, status, result, roleId) by ID, or list all tasks filtered by status (pending, running, completed, failed). Use this to check task progress and results.",vr,async e=>{if(e.taskId){let r=v(e.taskId);return c(r??{error:"Task not found"})}let t=e.status;return c(A(t,e.limit??100,0))}),m("modify_role_permissions","Update a role's RBAC permissions (paths, tools).",wr,async e=>{let t=T(e.roleId);if(!t)return c({error:`Role not found: ${e.roleId}`});let r={};if(e.allowedTools&&(r.allowedTools=e.allowedTools),e.disallowedTools&&(r.disallowedTools=e.disallowedTools),e.additionalDirectories!==void 0&&(r.additionalDirectories=e.additionalDirectories),e.allowedChannels!==void 0&&(r.allowedChannels=e.allowedChannels),"inheritUserSettings"in e&&(r.inheritUserSettings=e.inheritUserSettings),e.allowedPaths||e.deniedPaths){let n=t.preferences??{},o=n.permissions??{};r.preferences={...n,permissions:{...o,allowedPaths:e.allowedPaths??o.allowedPaths,deniedPaths:e.deniedPaths??o.deniedPaths}}}return F(e.roleId,r),c({success:!0})}),m("view_audit_log","View the evolution audit log for role changes.",Ir,async e=>{let{listEvolutionAudit:t}=await import("./evolution-audit-B7WKMOVR.js"),r=t(e.limit??50);return c({entries:r})}),m("list_roles","List all roles with their capabilities including bound plugins (skills/agents). Use this to discover available roles before dispatching tasks.",_r,async e=>{let r=G(e.status,e.limit??50,0).map(n=>{let o=Ne(n);return{id:n.id,name:n.name,status:n.status,allowedTools:n.allowedTools??[],disallowedTools:n.disallowedTools??[],additionalDirectories:n.additionalDirectories??[],cagPrompt:n.cagPrompt.slice(0,500)+(n.cagPrompt.length>500?"...":""),capabilitySummary:ee(n,o),plugins:o.plugins.map(s=>({name:s.name,skills:s.skills.map(a=>a.name),agents:s.agents.map(a=>a.name)}))}});return c({roles:r})}),m("create_role","Create a new role with a name, CAG prompt, and optional tool permissions.",Sr,async e=>{let t=`role-${w().slice(0,8)}`,r={id:t,name:e.name,cagPrompt:e.cagPrompt,learnedRules:[],memoryStreamId:`mem-${w().slice(0,8)}`,status:"active",preferences:{},createdAt:Date.now(),allowedTools:e.allowedTools,disallowedTools:e.disallowedTools,additionalDirectories:e.additionalDirectories};return $e(r),le(r),c({roleId:t,name:e.name,allowedTools:e.allowedTools,additionalDirectories:e.additionalDirectories??[]})}),m("retire_role","Retire a role (marks as retired, stops receiving tasks).",kr,async e=>T(e.roleId)?(F(e.roleId,{status:"retired"}),ve.info({roleId:e.roleId,reason:e.reason},"Role retired"),c({success:!0})):c({error:`Role not found: ${e.roleId}`})),m("create_goal","Create a new goal with optional budget, deadline, and metric tracking.",Tr,async e=>{let t=w(),r=Date.now(),n=r+10080*60*1e3,o={id:t,name:e.name,description:e.description,roleId:e.roleId??"engineer",metricType:e.metric??"completion",targetValue:e.targetValue??1,currentValue:0,deadline:e.deadline??n,budgetUsd:e.budgetUsd??5,status:"active",createdAt:r,deliverTo:e.deliverTo?await P(e.deliverTo):void 0};ce(o),ot(t,o.metricType);let s=_(t);return c({goalId:s.id,name:s.name,status:s.status})}),m("create_template","Create a recurring scheduled task using cron expressions (e.g., 'every hour', 'daily at 9am', 'weekly'). For one-shot delayed tasks ('in 30 minutes', 'tomorrow at 3pm'), use schedule_task instead.",Rr,async e=>{let{createTaskTemplate:t}=await import("./task-templates-7LSQ6OST.js"),r=w(),n=w(),o=e.deliverTo?await P(e.deliverTo):void 0,s=e.reportTo?await P(e.reportTo):void 0,a={id:r,name:e.name,description:e.description,trigger:{type:e.triggerType,cron:e.triggerCron,event:e.triggerEvent},steps:[{id:n,prompt:e.prompt}],rolePreference:e.roleId,enabled:e.enabled??!0,createdAt:Date.now(),goalIds:e.goalIds,deliverTo:o,reportTo:s};return t(a),c({templateId:r,name:a.name,trigger:a.trigger})}),m("list_templates","List task templates (automations). Use this to check existing scheduled/recurring tasks before creating new ones.",{enabled:i.boolean().optional().describe("Filter by enabled status. Omit to list all."),limit:i.number().optional().describe("Max results (default 50)")},async e=>{let{listTaskTemplates:t}=await import("./task-templates-7LSQ6OST.js"),r=t(e.enabled,e.limit??50,0);return c(r.map(n=>({id:n.id,name:n.name,description:n.description,trigger:n.trigger,enabled:n.enabled,rolePreference:n.rolePreference,deliverTo:n.deliverTo,createdAt:n.createdAt})))}),m("send_to_channel","Send a message (text, image, voice, video, file) to a connected channel by name. Use this to deliver task results, media, or notifications to a specific channel (e.g., WeChat on iPad). For media: provide mediaUrl pointing to the file and mediaType.",{channelName:i.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:i.string().describe("The message content to send (text caption when sending media)"),mediaUrl:i.string().optional().describe("Local file path or remote URL of media to send. Local paths (e.g. /Users/.../file.mp3) and http(s) URLs both work."),mediaType:i.enum(["image","audio","video","file"]).optional().describe("Type of the media file. Required when mediaUrl is provided")},async e=>{let t=await P([{type:"channel",channelName:e.channelName}]);if(t.length===0)return c({error:`Channel "${e.channelName}" not found or no chatId available`});let r=t[0];if(r.type!=="channel")return c({error:"Resolved target is not a channel"});let{getOutboundGateway:n}=await import("./outbound-gateway-DZTXBUTP.js"),s=await n().send({channelId:r.channelId,chatId:r.chatId,content:e.message,messageType:"deliver",mediaUrl:e.mediaUrl,mediaType:e.mediaType});return c({success:s.success,channelName:e.channelName})}),m("list_channels","List all connected channels with their platform, status, and chatId for message delivery. Use this to discover available channels before sending messages or setting up notifications.",Mr,async e=>{let t=Re(e.enabled),r=[..._e("active"),..._e("archived")],n=t.map(o=>{let s,a=r.find(l=>l.source.type==="channel"&&l.source.channelId===o.id&&l.source.chatId);return a?.source.chatId?s=a.source.chatId:s=o.config?.userId,{id:o.id,name:o.name,platform:o.platform,status:o.status,chatId:s}});return c({channels:n})}),m("get_system_status","Get current system status: execution pool capacity (active/max/queued slots), running task count, and system health. Use this to check if the system has capacity before dispatching tasks.",Pr,async()=>{let e=k(),t=A("running"),r=A("pending");return c({executionPool:{active:t.length,max:e.execution?.maxConcurrent??5,queued:r.length},timestamp:new Date().toISOString()})}),m("schedule_task","Schedule a one-shot delayed task. roleId is required \u2014 call list_roles first. Use this when the user wants something done later (e.g., '\u534A\u5C0F\u65F6\u540E', 'in 30 minutes', 'tomorrow at 3pm'). For recurring schedules ('every day', 'weekly'), use create_template instead.",Lr,async e=>{let t=T(e.roleId);if(!t||t.status!=="active"){let g=G("active",20,0).filter(f=>f.source!=="system").map(f=>({id:f.id,name:f.name,allowedTools:f.allowedTools??[],capabilitySummary:ee(f)}));return c({error:`Role not found or not active: ${e.roleId}. Pick a roleId from the list below.`,availableRoles:g})}let r=Date.now(),n;if(e.delayMinutes!==void 0&&e.runAt!==void 0)return c({error:"Provide exactly one of delayMinutes or runAt, not both"});if(e.delayMinutes!==void 0)n=r+e.delayMinutes*60*1e3;else if(e.runAt!==void 0){if(n=new Date(e.runAt).getTime(),isNaN(n))return c({error:"Invalid ISO 8601 timestamp in runAt"})}else return c({error:"Provide either delayMinutes or runAt"});if(n<=r)return c({error:"Scheduled time must be in the future"});let o=10080*60*1e3;if(n-r>o)return c({error:"Schedule exceeds maximum of 7 days"});let s=w(),a=new Date(n).toISOString(),l=e.deliverTo?await P(e.deliverTo):void 0,u=e.reportTo?await P(e.reportTo):void 0;Ye({id:s,name:e.prompt.slice(0,80),description:`One-shot scheduled task: ${e.prompt.slice(0,200)}`,trigger:{type:"once",runAt:a},steps:[{id:"main",prompt:e.prompt}],rolePreference:e.roleId,config:{...k().defaults},tags:["scheduled","once"],enabled:!0,createdAt:r,deliverTo:l,reportTo:u});let{getBreeEngine:d}=await import("./bree-engine-25VACELK.js"),p=d();return p&&p.scheduleOnceJob(s),c({templateId:s,executeAt:a,prompt:e.prompt})}),m("cancel_scheduled_task","Cancel a previously scheduled one-shot task by its template ID. The task will not execute.",{templateId:i.string().describe("The template ID returned by schedule_task")},async e=>{let t=B(e.templateId);if(!t)return c({error:`Template not found: ${e.templateId}`});if(t.trigger.type!=="once")return c({error:"This is not a one-shot scheduled task. Use disable_template for recurring automations."});Qe(e.templateId);let{getBreeEngine:r}=await import("./bree-engine-25VACELK.js"),n=r();return n&&await n.unscheduleJob(e.templateId),c({cancelled:!0,templateId:e.templateId})}),m("list_available_plugins","List all installed plugins with their scope and global enabled state. If roleId is provided, shows which plugins are installed in that role's workspace.",Er,async e=>{let t=z(),r=C(),n=e.roleId?(()=>{let{getRoleWorkspacePath:o}=(V(),x(Ie)),{getRole:s}=(ae(),x(we)),{listInstalledPlugins:a}=(ye(),x(wt)),l=s(e.roleId);if(!l)return[];let u=o(l.name);return a({scope:"project",projectPath:u}).map(d=>d.id)})():[];return c({plugins:r.map(o=>({id:o.id,name:o.name,scope:o.scope,projectPath:o.projectPath,enabled:o.enabled,globalEnabled:t[o.id]??o.enabled,isInstalledInRole:n.includes(o.id),description:o.version?`v${o.version}`:void 0}))})}),m("install_plugin_for_role","Install a plugin into a role's workspace (project-scope). The plugin will be available when that role executes tasks.",Cr,async e=>{let{getRole:t}=(ae(),x(we)),{getRoleWorkspacePath:r}=(V(),x(Ie)),n=t(e.roleId);if(!n)return c({error:`Role not found: ${e.roleId}`});let o=r(n.name);try{return De(e.pluginId,"project",o),c({success:!0,roleId:e.roleId,pluginId:e.pluginId,scope:"project",cwd:o})}catch(s){return c({error:`Failed to install plugin: ${s}`})}}),m("uninstall_plugin_from_role","Uninstall a plugin from a role's workspace.",Dr,async e=>{let{getRole:t}=(ae(),x(we)),{getRoleWorkspacePath:r}=(V(),x(Ie)),n=t(e.roleId);if(!n)return c({error:`Role not found: ${e.roleId}`});let o=r(n.name);try{return Ae(e.pluginId,"project",o),c({success:!0,roleId:e.roleId,pluginId:e.pluginId})}catch(s){return c({error:`Failed to uninstall plugin: ${s}`})}}),m("bind_mcp_to_role","Bind an MCP server configuration to a role. The MCP server will be available to the role during task execution.",Ar,async e=>{let t=T(e.roleId);if(!t)return c({error:`Role not found: ${e.roleId}`});let n={...t.mcpServers??{},[e.mcpName]:e.mcpConfig};try{return F(e.roleId,{mcpServers:n}),le(t),c({success:!0,roleId:e.roleId,mcpName:e.mcpName,mcpServers:n})}catch(o){return c({error:`Failed to bind MCP server: ${o}`})}}),m("unbind_mcp_from_role","Remove an MCP server binding from a role.",Nr,async e=>{let t=T(e.roleId);if(!t)return c({error:`Role not found: ${e.roleId}`});let r={...t.mcpServers??{}};if(!(e.mcpName in r))return c({error:`MCP server "${e.mcpName}" not bound to this role`});delete r[e.mcpName];try{return F(e.roleId,{mcpServers:r}),le(t),c({success:!0,roleId:e.roleId,mcpName:e.mcpName})}catch(n){return c({error:`Failed to unbind MCP server: ${n}`})}}),m("get_capabilities","Get a comprehensive overview of Adam's current capabilities: available roles and their tools, connected channels, installed plugins, active automations, and execution capacity. Call this when the user asks what you can do, or asks for help.",xr,async()=>{let{listTaskTemplates:e}=await import("./task-templates-7LSQ6OST.js"),t=k(),r=G(void 0,100,0),n=Re(),o=e(!0,100,0),s=A("running"),a=A("pending");return c({roles:{description:"Specialized worker identities \u2014 each has its own tools, MCP servers, plugins (skills/agents), and learned rules",active:r.filter(l=>l.status==="active"&&l.source!=="system").map(l=>{let u=Ne(l);return{name:l.name,tools:l.allowedTools??[],mcpServers:Object.keys(l.mcpServers??{}),channels:l.allowedChannels??[],capabilitySummary:ee(l,u),plugins:u.plugins.map(d=>({name:d.name,skills:d.skills.map(p=>p.name),agents:d.agents.map(p=>p.name)}))}}),retired:r.filter(l=>l.status==="retired").length,probation:r.filter(l=>l.status==="probation").length},channels:{description:"Send/receive messages via connected platforms",connected:n.filter(l=>l.enabled).map(l=>({name:l.name,platform:l.platform,status:l.status}))},plugins:{description:"Extensions that add capabilities to roles",installed:C().filter(l=>l.enabled).map(l=>({name:l.name,scope:l.scope,description:l.version?`v${l.version}`:void 0}))},automations:{description:"Recurring cron tasks and event-triggered templates",active:o.map(l=>({name:l.name,trigger:l.trigger}))},execution:{description:"Parallel task execution pool",maxConcurrent:t.execution?.maxConcurrent??5,running:s.length,queued:a.length},coreFeatures:["Goal management \u2014 SMART goals with budget/deadline/metric, auto-decomposition into subtasks","Memory \u2014 per-Role vector + keyword searchable memory across tasks","Strategy evolution \u2014 Thompson Sampling optimizes task approaches over time","Monitor \u2014 automatic quality scoring, role retirement/reinstatement","Delivery engine \u2014 event-driven result routing to channels/webhooks","Schedule \u2014 cron recurring templates + one-shot delayed tasks"]})}),m("enable_plugin","Enable a globally installed plugin (makes it available to all roles).",jr,async e=>{try{return _t(e.pluginId),c({success:!0,pluginId:e.pluginId})}catch(t){return c({error:`Failed to enable plugin: ${t}`})}}),m("disable_plugin","Disable a globally installed plugin (removes it from all roles).",$r,async e=>{try{return Mt(e.pluginId),c({success:!0,pluginId:e.pluginId})}catch(t){return c({error:`Failed to disable plugin: ${t}`})}}),m("install_plugin_for_user","Install a plugin globally for the current user (user-scope).",Or,async e=>{try{return De(e.pluginId,"user"),c({success:!0,pluginId:e.pluginId,scope:"user"})}catch(t){return c({error:`Failed to install plugin: ${t}`})}}),m("uninstall_plugin_for_user","Uninstall a globally installed plugin from the current user.",Ur,async e=>{try{return Ae(e.pluginId,"user"),c({success:!0,pluginId:e.pluginId})}catch(t){return c({error:`Failed to uninstall plugin: ${t}`})}}),m("browse_marketplace","Browse all available plugins from configured marketplaces (shows installed and available).",Fr,async()=>{try{let e=Rt(),t=C();return c({available:e,installed:t})}catch(e){return c({error:`Failed to browse marketplace: ${e}`})}}),m("list_marketplace_sources","List configured plugin marketplace sources.",Gr,async()=>{let e=Ce();return c({sources:e})}),m("get_plugin_detail","Get detailed manifest for an installed plugin (skills, agents, MCP servers, hooks).",Vr,async e=>{let t=Le(e.pluginId);if(!t)return c({error:`Plugin not found: ${e.pluginId}`});let r=Q(t.installPath);return c({id:t.id,name:t.name,version:t.version,scope:t.scope,projectPath:t.projectPath,enabled:t.enabled,manifest:r})}),m("scan_directory","Scan a directory for .claude/settings.json and return its plugin/MCP configuration.",Br,async e=>{let{getRole:t}=await import("./roles-SG2YAR64.js");if(!t(e.roleId))return c({error:`Role not found: ${e.roleId}`});try{let n=X(e.path);return c({roleId:e.roleId,path:e.path,config:n})}catch(n){return c({error:`Failed to scan directory: ${n}`})}}),m("cancel_task","Cancel a running or pending task by setting its status to 'cancelled'. Emits a task_status_change event.",Wr,async e=>{let t=v(e.taskId);if(!t)return c({error:`Task not found: ${e.taskId}`});let r=t.status;U(e.taskId,{status:"cancelled"});let{serverBus:n}=await import("./server-bus-GEGVMSCA.js");return n.emit({type:"task_status_change",taskId:e.taskId,oldStatus:r,newStatus:"cancelled"}),c({success:!0,taskId:e.taskId,status:"cancelled"})}),m("view_task_logs","Retrieve step-by-step execution logs for a task.",Jr,async e=>{let t=ie(e.taskId,e.limit??20);return c({taskId:e.taskId,count:t.length,logs:t})}),m("delete_role","Delete a role by ID. This removes the role and its workspace.",qr,async e=>T(e.roleId)?(Oe(e.roleId),c({success:!0,roleId:e.roleId})):c({error:`Role not found: ${e.roleId}`})),m("view_config","Get the current runtime configuration (mutable fields and restart-required fields).",Hr,async()=>{let{MUTABLE_PATHS:e,RESTART_REQUIRED_PATHS:t}=await import("./runtime-6UTYEONR.js"),r=k(),n={};try{let l=k().server?.port??7100,u=await fetch(`http://127.0.0.1:${l}/config`);u.ok&&(n=await u.json())}catch{}let o=[...e,...t],s=[...t],a={};for(let l of o){let u=l.split("."),d=r;for(let p of u)if(d&&typeof d=="object")d=d[p];else{d=void 0;break}a[l]={value:d,mutable:!t.includes(l)}}return c({config:a,mutable:[...e],restartRequired:[...t]})}),m("update_config","Update mutable runtime configuration fields. Returns partial-success: some fields may update while others return errors.",Kr,async e=>{let{isRestartRequiredPath:t}=await import("./runtime-6UTYEONR.js"),{setConfigValue:r}=await import("./config-WHXCZCI4.js"),n=je(e.updates,r);if(e.updates["logging.level"]&&Fe(e.updates["logging.level"]),n.updated.length>0){let{serverBus:o}=await import("./server-bus-GEGVMSCA.js");o.emit({type:"config_changed",changes:n.updated.map(s=>({path:s,value:e.updates[s]}))})}return c(n)}),m("list_memories","List memories stored under a specific role.",Yr,async e=>{let t=qe(e.roleId,e.limit??20);return c({roleId:e.roleId,count:t.length,memories:t})}),m("update_template","Update a task template's fields (name, prompt, cron, enabled, etc.).",zr,async e=>{let t=B(e.templateId);if(!t)return c({error:`Template not found: ${e.templateId}`});let r={};if(e.name!==void 0&&(r.name=e.name),e.enabled!==void 0&&(r.enabled=e.enabled),e.prompt!==void 0){let n=t.steps?.length?[...t.steps]:[];n.length===0?n.push({id:w(),prompt:e.prompt}):n[0]={...n[0],prompt:e.prompt},r.steps=n}return(e.triggerCron!==void 0||e.triggerEvent!==void 0)&&(r.trigger={type:e.triggerEvent?"event":"cron",cron:e.triggerCron,event:e.triggerEvent}),e.roleId!==void 0&&(r.rolePreference=e.roleId),ze(e.templateId,r),c({success:!0,templateId:e.templateId,updated:Object.keys(r)})}),m("delete_template","Delete a task template by ID.",Qr,async e=>B(e.templateId)?(Xe(e.templateId),c({success:!0,templateId:e.templateId})):c({error:`Template not found: ${e.templateId}`})),m("run_template","Trigger a template immediately (runs the webhook endpoint for its name).",Xr,async e=>{let t=B(e.templateId);if(!t)return c({error:`Template not found: ${e.templateId}`});try{let r=k().server?.port??7100,n=await fetch(`http://127.0.0.1:${r}/webhooks/${t.name}`,{method:"POST"}),o=await n.json();return n.ok?c({success:!0,templateId:e.templateId,templateName:t.name,response:o}):c({error:`Webhook failed: ${o.code??n.status} \u2014 ${o.message??""}`})}catch(r){return c({error:`Failed to trigger template: ${r}`})}}),m("list_delivery_rules","List delivery rules, optionally filtered by enabled status.",Zr,async e=>{let t=Me(e.enabled);return c({count:t.length,rules:t})}),m("create_delivery_rule","Create a new delivery rule for event-driven result routing.",en,async e=>{let t=w(),r={id:t,eventType:e.eventType,matchCriteria:e.matchCriteria??{},target:{type:"channel",channelId:e.channelId},formatTemplate:e.format,maxPerMinute:10,skipOriginChannel:!1,enabled:e.enabled??!0,createdAt:Date.now()};return tt(r),c({success:!0,ruleId:t,rule:r})}),m("delete_delivery_rule","Delete a delivery rule by ID.",tn,async e=>Me().find(n=>n.id===e.ruleId)?(rt(e.ruleId),c({success:!0,ruleId:e.ruleId})):c({error:`Delivery rule not found: ${e.ruleId}`})),m("list_strategies","List Thompson Sampling strategy populations for a role, or all strategies if roleId omitted.",rn,async e=>{let t;if(e.roleId)t=ct(e.roleId);else{let{getDb:r}=await import("./db-PNZ3UJOE.js");t=r().prepare("SELECT * FROM strategies ORDER BY created_at").all().map(o=>({id:o.id,roleId:o.role_id,name:o.name,taskType:o.task_type,createdAt:o.created_at,updatedAt:o.updated_at??void 0,promptTemplate:o.prompt_template??"",alpha:o.alpha,beta:o.beta,totalTrials:o.trials,avgReward:o.total_reward&&o.trials>0?o.total_reward/o.trials:void 0,enabled:o.enabled===1}))}return c({roleId:e.roleId??null,count:t.length,strategies:t})}),m("authorize_task_operation","Authorize a pending privilege escalation for a task. The paused operation will proceed.",{taskId:i.string(),operationId:i.string().optional().describe("ID of the specific operation. If omitted, authorizes the most recent pending operation."),scope:i.enum(["once","permanent"]).default("once").describe("'once' = this operation only. 'permanent' = auto-authorize matching patterns in the future.")},async e=>{let t=Se(e.taskId),r=e.operationId?t.find(o=>o.id===e.operationId):t.find(o=>o.status==="pending");return r?(new re().resolvePlanApproval(r.id,"allow",e.scope),c({success:!0,operationId:r.id,decision:"allow",scope:e.scope})):c({error:"No pending operation found for this task"})}),m("deny_task_operation","Deny a pending privilege escalation for a task. The paused operation will be rejected.",{taskId:i.string(),operationId:i.string().optional(),reason:i.string().optional().describe("Reason for denial, provided to the executor as feedback.")},async e=>{let t=Se(e.taskId),r=e.operationId?t.find(o=>o.id===e.operationId):t.find(o=>o.status==="pending");return r?(new re().resolvePlanApproval(r.id,"deny","once",e.reason),c({success:!0,operationId:r.id,decision:"deny"})):c({error:"No pending operation found for this task"})})];function Yo(){return Et.map(e=>e.name).sort().join(",")}function zo(){return cr({name:"adam-tools",version:"1.0.0",tools:Et})}export{fo as a,re as b,z as c,Q as d,C as e,Le as f,Ce as g,X as h,ye as i,un as j,pn as k,ot as l,$n as m,ct as n,S as o,bt as p,Rt as q,De as r,Ae as s,_t as t,Mt as u,co as v,ar as w,Yo as x,zo as y};
|
package/dist/chunk-JXD6ZPV7.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{b as r,d as i}from"./chunk-PCSZW2PE.js";i();function l(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 g(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 p(){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 E(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 k(){return r().prepare("SELECT COUNT(*) as count FROM config").get().count===0}function b(e){return r().prepare("DELETE FROM config WHERE key = ?").run(e).changes>0}export{l as a,g as b,p as c,E as d,k as e,b as f};
|
package/dist/chunk-MX6AZ7WD.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as R}from"./chunk-NXTTKAQX.js";import{f as E}from"./chunk-KICPHTI2.js";import{b as v}from"./chunk-5ASEAZCR.js";import{e as m}from"./chunk-742NWPTQ.js";import{b as x}from"./chunk-PQ7KPALO.js";import{a as w,b as k,c as o,d as h,e as T,f as P,g as S}from"./chunk-FDWW245P.js";import{b as g}from"./chunk-L7426WNY.js";import{a as f}from"./chunk-L7JP7DUO.js";import{c as D}from"./chunk-3DAK2XWP.js";import{v4 as C}from"uuid";var s=D("admin"),y=new Map,u=null,p=null,c=null,I=class{constructor(){f.on("task_status_change",e=>{(e.newStatus==="completed"||e.newStatus==="failed")&&this.handleTaskStatusChange(e.taskId,e.newStatus).catch(n=>{s.error({taskId:e.taskId,error:n},"Delivery processing failed")})}),f.on("plan_approval_request",e=>{this.handlePlanApprovalRequest(e.taskId,e.planId,e.plan).catch(n=>{s.error({taskId:e.taskId,error:n},"Delivery processing failed (plan_approval)")})}),s.info("DeliveryEngine initialized")}async handlePlanApprovalRequest(e,n,r){let t=g(e),i=this.getSourceChannelForTask(e);if(i){let d=JSON.stringify(r).slice(0,500),{sendApprovalToChannel:b}=await import("./approval-handler-HK7GQPHU.js");await b(i.channelId,i.chatId,n,e,d)}let a=`Plan approval requested for task ${e}: ${JSON.stringify(r).slice(0,500)}`;await this.matchAndDeliver("plan_approval_request",{templateId:t?.templateId,roleId:t?.roleId,prompt:t?.prompt,taskStatus:"pending"},a,e)}getSourceChannelForTask(e){try{let n=m(e);if(!n)return null;let r=v(n.sessionId);return!r||r.source.type!=="channel"||!r.source.channelId||!r.source.chatId?null:{channelId:r.source.channelId,chatId:r.source.chatId}}catch{return null}}async handleTaskStatusChange(e,n){let r=g(e);if(!r)return;let t={templateId:r.templateId,roleId:r.roleId,prompt:r.prompt,taskStatus:n},i=n==="completed"?"task_complete":"task_error",a=r.result??r.error??"";await this.matchAndDeliver(i,t,a,e)}async matchAndDeliver(e,n,r,t){let i=E(e,n);if(i.length!==0){s.debug({eventType:e,ruleCount:i.length,taskId:t},"Matched delivery rules");for(let a of i){if(!this.checkRateLimit(a)){s.warn({ruleId:a.id,maxPerMinute:a.maxPerMinute},"Delivery rate limit exceeded, skipping");continue}if(a.skipOriginChannel&&a.target.type==="channel"&&t&&this.isOriginChannel(t,a.target))continue;let d={id:C(),ruleId:a.id,taskId:t,status:"pending",target:a.target,content:r,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+w,source:"rule"};k(d),await this.attemptDelivery(d,a)}}}async attemptDeliveryPublic(e,n){return this.attemptDelivery(e,n)}async attemptDelivery(e,n){let r=R();try{if(e.target.type==="channel"){let t=e.target.chatId;!t&&e.target.channelId&&(t=x(e.target.channelId)?.config?.userId);let i=await r.send({taskId:e.taskId,channelId:e.target.channelId,chatId:t,content:e.content,messageType:"deliver"});i.success?(h(e.id),s.info({entryId:e.id,ruleId:n.id,targetType:"channel"},"Delivery successful")):o(e.id,"failed",i.error??"Gateway returned failure")}else if(e.target.type==="webhook"){let t=await r.send({taskId:e.taskId,webhookUrl:e.target.webhookUrl,content:e.content,messageType:"deliver"});t.success?(h(e.id),s.info({entryId:e.id,ruleId:n.id,targetType:"webhook"},"Webhook delivery successful")):o(e.id,"failed",t.error??"Gateway returned failure")}}catch(t){let i=t instanceof Error?t.message:String(t);o(e.id,"failed",i),s.warn({entryId:e.id,error:i},"Delivery attempt failed")}}checkRateLimit(e){let n=Date.now(),r=6e4,t=y.get(e.id);t||(t=[],y.set(e.id,t));let i=n-r;for(;t.length>0&&t[0]<i;)t.shift();return t.length>=e.maxPerMinute?!1:(t.push(n),!0)}isOriginChannel(e,n){try{if(n.type!=="channel"||!n.channelId)return!1;let r=m(e);if(!r)return!1;let t=v(r.sessionId);return t?t.source.type==="channel"&&t.source.channelId===n.channelId&&t.source.chatId===n.chatId:!1}catch{return!1}}async retryPending(){let e=T("rule",50),n=P("rule",50),r=[...e,...n];if(r.length!==0){s.debug({count:r.length},"Retrying pending/failed deliveries");for(let t of r){if(t.attempts>=3){o(t.id,"failed","Max retries (3) exceeded");continue}let i={id:t.ruleId??"retry-synthetic",eventType:"*",matchCriteria:{},target:t.target,maxPerMinute:5,skipOriginChannel:!0,enabled:!0,createdAt:0};await this.attemptDelivery(t,i)}}}};function N(){return c}function U(){c||(c=new I,u=setInterval(()=>{c?.retryPending().catch(l=>{s.error({error:l},"Delivery retry scan failed")})},6e4),p=setInterval(()=>{try{let l=S();l>0&&s.info({cleaned:l},"Expired delivery log entries cleaned up")}catch(l){s.error({error:l},"Delivery cleanup failed")}},36e5),s.info("DeliveryEngine started with retry (60s) and cleanup (1h) timers"))}function W(){u&&(clearInterval(u),u=null),p&&(clearInterval(p),p=null),c=null,y.clear(),s.info("DeliveryEngine stopped")}export{I as a,N as b,U as c,W as d};
|
package/dist/chunk-NSJAV7IH.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as w,g as S}from"./chunk-SFUS33SO.js";import{c as g}from"./chunk-3DAK2XWP.js";import{readFileSync as v,existsSync as E}from"fs";import{join as p}from"path";import{homedir as P}from"os";S();var T=g("ws"),R=p(P(),".adam"),f=p(R,"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 x(){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 C(n,t={}){let s=`${x()}${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 _(){return C("/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,C as b,_ as c,k as d,y as e};
|
package/dist/chunk-NXTTKAQX.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{b as C}from"./chunk-PQ7KPALO.js";import{b as D,c as f,d as w}from"./chunk-FDWW245P.js";import{a as p}from"./chunk-L7JP7DUO.js";import{c as M}from"./chunk-3DAK2XWP.js";function O(s,c,n){switch(c){case"wechat":return $(s);case"telegram":return s;case"slack":return U(s);case"webhook":return JSON.stringify({result:s,taskId:n,timestamp:new Date().toISOString()});default:return $(s)}}function $(s){return s.replace(/^#{1,6}\s+/gm,"").replace(/\*\*(.+?)\*\*/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/_(.+?)_/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/```[\s\S]*?```/g,c=>c.replace(/```\w*\n?/g,"").trim()).replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\n{3,}/g,`
|
|
2
|
-
|
|
3
|
-
`).trim()}function U(s){return s.replace(/\*\*(.+?)\*\*/g,"*$1*").replace(/\[([^\]]+)\]\(([^)]+)\)/g,"<$2|$1>")}import{v4 as T}from"uuid";var x=M("adam"),v=class{_dedupCache=new Map;_rateLimitWindows=new Map;_recentlySentIds=new Set;isRecentlySent(c){return this._recentlySentIds.has(c)}async send(c){let{taskId:n,channelId:a,chatId:m,content:y,messageType:d,platform:E,webhookUrl:h,replyMarkup:I,mediaUrl:S,mediaType:b}=c,R=d!=="reply"&&!!n,r;if(R){r=`${n}:${a??"none"}:${m??"none"}:${d}`;let t=this._dedupCache.get(r);if(t&&Date.now()-t.timestamp<300*1e3)return x.debug({dedupKey:r},"Dedup hit, returning cached log entry"),{success:!0,logEntryId:t.logEntryId}}if(a){let t=Date.now(),i=6e4,o=this._rateLimitWindows.get(a);o||(o=[],this._rateLimitWindows.set(a,o));let u=t-i;for(;o.length>0&&o[0]<u;)o.shift();if(o.length>=60){let l=T();return x.warn({channelId:a,count:o.length},"Rate limited, not sending"),{success:!1,logEntryId:l,error:"rate_limited"}}o.push(t)}let L=E??(a?C(a)?.platform:void 0)??"unknown",k=h?y:O(y,L,n),e=T(),g={id:e,ruleId:void 0,taskId:n??void 0,status:"pending",target:a&&m?{type:"channel",channelId:a,chatId:m}:h?{type:"webhook",webhookUrl:h}:{type:"channel",channelId:a??"",chatId:m??""},content:k,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+1440*60*1e3,source:"direct",messageType:d};D(g),r&&this._dedupCache.set(r,{logEntryId:e,timestamp:Date.now()});try{if(h){let t=await fetch(h,{method:"POST",body:JSON.stringify({result:y,taskId:n,timestamp:new Date().toISOString()}),signal:AbortSignal.timeout(1e4)});if(t.ok)return w(e),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"delivered",messageType:d}),{success:!0,logEntryId:e};{let i=`Webhook returned ${t.status}`;return f(e,"failed",i),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:i,messageType:d}),{success:!1,logEntryId:e,error:i}}}else if(a&&m){let{getChannelManager:t}=await import("./channels-JEBBMFUQ.js"),i=t();if(!i){let l="ChannelManager not available";return f(e,"failed",l),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:l,messageType:d}),{success:!1,logEntryId:e,error:l}}let o={content:k,...I?{replyMarkup:I}:{},...S?{mediaUrl:S}:{},...b?{mediaType:b}:{}},u=await i.sendMessage(a,m,o);if(u===null){let l="Channel adapter send failed (returned null)";return f(e,"failed",l),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:l,messageType:d}),{success:!1,logEntryId:e,error:l}}return u&&(this._recentlySentIds.add(u),setTimeout(()=>this._recentlySentIds.delete(u),300*1e3)),w(e),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"delivered",messageType:d}),{success:!0,messageId:u??void 0,logEntryId:e}}else{let t="No channelId/chatId or webhookUrl provided";return f(e,"failed",t),r&&this._dedupCache.delete(r),{success:!1,logEntryId:e,error:t}}}catch(t){let i=t instanceof Error?t.message:String(t);return f(e,"failed",i),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:i,messageType:d}),{success:!1,logEntryId:e,error:i}}}},_=null;function P(){return _||(_=new v),_}function K(s){return P().isRecentlySent(s)}export{v as a,P as b,K as c};
|
package/dist/chunk-SFUS33SO.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as s}from"./chunk-FCV2DPZQ.js";import{join as o}from"path";import{homedir as e}from"os";var c,n,t,p,_,a,E,D,i,r=s(()=>{"use strict";c=["Read","Write","Edit","Bash","Grep","Glob","WebSearch","WebFetch","LSP","NotebookEdit","Agent"],n=["~/.ssh","~/.aws","~/.gnupg","/etc/shadow"],t=o(e(),".adam"),p=o(t,"adam.db"),_=o(t,"adam.config.yaml"),a=o(t,".env"),E=o(t,"CLAUDE.md"),D=o(t,"logs"),i=10*1024});export{c as a,n as b,t as c,p as d,_ as e,a as f,r as g};
|
package/dist/chunk-T25NLVMY.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as i}from"./chunk-ETQ7KC73.js";import{d as a}from"./chunk-FYDFMYUP.js";import{e as u,g as C}from"./chunk-SFUS33SO.js";C();import{readFileSync as m,existsSync as v}from"fs";import{resolve as y}from"path";import{homedir as _}from"os";import{parse as R}from"yaml";function O(e){return e.replace(/\$\{(\w+)}/g,(r,t)=>process.env[t]??"")}function l(e){return e.startsWith("~/")?y(_(),e.slice(2)):e}function f(e){if(typeof e=="string")return O(e);if(Array.isArray(e))return e.map(f);if(e!==null&&typeof e=="object"){let r={};for(let[t,n]of Object.entries(e))r[t]=f(n);return r}return e}function p(e,r){let t={...e};for(let n of Object.keys(r)){let o=r[n],s=e[n];o!==null&&typeof o=="object"&&!Array.isArray(o)&&s!==null&&typeof s=="object"&&!Array.isArray(s)?t[n]=p(s,o):t[n]=o}return t}function d(e){return e.defaults.fileAccess.allowedPaths=e.defaults.fileAccess.allowedPaths.map(l),e.defaults.fileAccess.deniedPaths=e.defaults.fileAccess.deniedPaths.map(l),e}function P(){let e={};for(let r of process.argv.slice(2)){let t=r.match(/^--([a-z-]+)=(.+)$/);t&&(e[t[1]]=t[2])}return e}function g(e){let r=process.env.ADAM_PORT;r&&(e.server.port=parseInt(r,10));let t=process.env.ANTHROPIC_MODEL;t&&(e.defaults.model=t);let n=process.env.ADAM_API_KEY;return n&&(e.server.apiKey=n),e}function h(e){let r=P();return r.port&&(e.server.port=parseInt(r.port,10)),r.host&&(e.server.host=r.host),r.timeout&&(e.defaults.timeout=parseInt(r.timeout,10)),r["api-key"]&&(e.server.apiKey=r["api-key"]),e}function w(e){let r=e??u,t={};if(v(r)){let A=m(r,"utf-8"),c=R(A);c&&(t=f(c))}let n=p(i,t),o=g(n),s=h(o);return d(s)}function E(){let e=JSON.parse(JSON.stringify(i)),r=g(e),t=h(r);return d(t)}function L(){let e={},r={ANTHROPIC_API_KEY:"anthropic.apiKey",ANTHROPIC_BASE_URL:"anthropic.baseUrl",ANTHROPIC_MODEL:"anthropic.model",ANTHROPIC_DEFAULT_OPUS_MODEL:"anthropic.defaultOpusModel",ANTHROPIC_DEFAULT_SONNET_MODEL:"anthropic.defaultSonnetModel",ANTHROPIC_DEFAULT_HAIKU_MODEL:"anthropic.defaultHaikuModel",ANTHROPIC_SMALL_FAST_MODEL:"anthropic.smallFastModel",ADAM_PORT:"server.port",ADAM_API_KEY:"server.apiKey"};for(let[t,n]of Object.entries(r)){let o=process.env[t];if(o&&o.length>0)if(n==="server.port"){let s=parseInt(o,10);isNaN(s)||(e[n]=s)}else e[n]=o}return e}function x(){try{return a().defaults}catch{return i.defaults}}function K(){try{return a().chat??i.chat}catch{return i.chat}}export{w as a,E as b,L as c,x as d,K as e};
|
package/dist/chunk-URW2DJQF.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{f as se}from"./chunk-742NWPTQ.js";import{a as oe,b as _,c as G,d as ae,e as de}from"./chunk-PQ7KPALO.js";import{c as f}from"./chunk-3DAK2XWP.js";import{z as g}from"zod/v4";import{v4 as St}from"uuid";import{randomUUID as me}from"crypto";import Ge from"crypto";var ce="1.0.0",A="";function Qe(e){let t=e.split(".").map(i=>parseInt(i,10)),r=t[0]??0,s=t[1]??0,n=t[2]??0;return(r&255)<<16|(s&255)<<8|n&255}var K=Qe(ce),Ke=35e3,le=15e3,He=1e4;function v(){return{channel_version:ce}}function Xe(e){return e.endsWith("/")?e:`${e}/`}function Je(){let e=Ge.randomBytes(4).readUInt32BE(0);return Buffer.from(String(e),"utf-8").toString("base64")}function Ye(e){let t={"Content-Type":"application/json",AuthorizationType:"ilink_bot_token","Content-Length":String(Buffer.byteLength(e.body,"utf-8")),"X-WECHAT-UIN":Je(),"iLink-App-Id":A,"iLink-App-ClientVersion":String(K)};return e.token?.trim()&&(t.Authorization=`Bearer ${e.token.trim()}`),e.routeTag&&(t.SKRouteTag=e.routeTag),t}async function O(e){let t=Xe(e.baseUrl),r=new URL(e.endpoint,t),s=Ye({token:e.token,routeTag:e.routeTag,body:e.body}),n=new AbortController,i=setTimeout(()=>n.abort(),e.timeoutMs);try{let o=await fetch(r.toString(),{method:"POST",headers:s,body:e.body,signal:n.signal});clearTimeout(i);let a=await o.text();if(!o.ok)throw new Error(`${e.label} ${o.status}: ${a}`);return a}catch(o){throw clearTimeout(i),o}}async function ue(e){let t=e.timeoutMs??Ke;try{let r=await O({baseUrl:e.baseUrl,endpoint:"ilink/bot/getupdates",body:JSON.stringify({get_updates_buf:e.get_updates_buf??"",base_info:v()}),token:e.token,routeTag:e.routeTag,timeoutMs:t,label:"getUpdates"});return JSON.parse(r)}catch(r){if(r instanceof Error&&r.name==="AbortError")return{ret:0,msgs:[],get_updates_buf:e.get_updates_buf};throw r}}var Ze=new Set([-2,-3]),Q=3,et=1e3;async function N(e){let t=(await import("./logger-BEG4WFIM.js")).getLogger("channels");for(let r=1;r<=Q;r++){let s=await O({baseUrl:e.baseUrl,endpoint:"ilink/bot/sendmessage",body:JSON.stringify({...e.body,base_info:v()}),token:e.token,routeTag:e.routeTag,timeoutMs:e.timeoutMs??le,label:"sendMessage"});t.info({status:200,responseBody:s.slice(0,300)},"apiFetch sendMessage response");try{let n=JSON.parse(s);if(n.ret&&n.ret!==0){if(Ze.has(n.ret)&&r<Q){t.warn({ret:n.ret,attempt:r,maxRetries:Q},"sendMessage: transient iLink error, retrying"),await new Promise(i=>setTimeout(i,et*r));continue}throw t.error({ret:n.ret,errmsg:n.errmsg,attempt:r},"sendMessage: iLink API returned non-zero ret"),new Error(`sendMessage failed: iLink ret=${n.ret}${n.errmsg?` errmsg=${n.errmsg}`:""}`)}}catch(n){if(n instanceof SyntaxError)t.warn({rawText:s.slice(0,200),attempt:r},"sendMessage: non-JSON response, treating as success");else throw n}return}}async function ge(e){await O({baseUrl:e.baseUrl,endpoint:"ilink/bot/sendtyping",body:JSON.stringify({...e.body,base_info:v()}),token:e.token,routeTag:e.routeTag,timeoutMs:e.timeoutMs??He,label:"sendTyping"})}async function pe(e){let t=await O({baseUrl:e.baseUrl,endpoint:"ilink/bot/getuploadurl",body:JSON.stringify({filekey:e.filekey,media_type:e.media_type,to_user_id:e.to_user_id,rawsize:e.rawsize,rawfilemd5:e.rawfilemd5,filesize:e.filesize,thumb_rawsize:e.thumb_rawsize,thumb_rawfilemd5:e.thumb_rawfilemd5,thumb_filesize:e.thumb_filesize,no_need_thumb:e.no_need_thumb,aeskey:e.aeskey,base_info:v()}),token:e.token,routeTag:e.routeTag,timeoutMs:e.timeoutMs??le,label:"getUploadUrl"});return JSON.parse(t)}var tt=5*6e4,nt=35e3,fe="3",h=new Map;function H(e){return Date.now()-e.startedAt<tt}function rt(){for(let[e,t]of h)H(t)||h.delete(e)}async function ye(e,t,r){let s=e.endsWith("/")?e:`${e}/`,n=new URL(`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(t)}`,s),i={"iLink-App-Id":A};r&&(i.SKRouteTag=r);let o=await fetch(n.toString(),{headers:i});if(!o.ok){let a=await o.text().catch(()=>"(unreadable)");throw new Error(`Failed to fetch QR code: ${o.status} ${o.statusText} body=${a}`)}return await o.json()}async function it(e,t,r){let s=e.endsWith("/")?e:`${e}/`,n=new URL(`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(t)}`,s),i={"iLink-App-Id":A,"iLink-App-ClientVersion":String(K)};r&&(i.SKRouteTag=r);let o=new AbortController,a=setTimeout(()=>o.abort(),nt);try{let c=await fetch(n.toString(),{headers:i,signal:o.signal});clearTimeout(a);let l=await c.text();if(!c.ok)throw new Error(`Failed to poll QR status: ${c.status} ${c.statusText}`);return JSON.parse(l)}catch(c){if(clearTimeout(a),c instanceof Error&&c.name==="AbortError")return{status:"wait"};throw c}}async function he(e){let t=e.accountId||me();rt();let r=h.get(t);if(!e.force&&r&&H(r)&&r.qrcodeUrl)return{qrcodeUrl:r.qrcodeUrl,message:"QR code ready. Scan with WeChat.",sessionKey:t};if(!e.apiBaseUrl)return{message:"No baseUrl configured for this WeChat channel.",sessionKey:t};try{let s=e.botType||fe,n=await ye(e.apiBaseUrl,s,e.routeTag),i={sessionKey:t,id:me(),qrcode:n.qrcode,qrcodeUrl:n.qrcode_img_content,startedAt:Date.now()};return h.set(t,i),{qrcodeUrl:n.qrcode_img_content,message:"Scan the QR code with WeChat to connect.",sessionKey:t}}catch(s){return{message:`Failed to start login: ${String(s)}`,sessionKey:t}}}var st=3;async function be(e){let t=h.get(e.sessionKey);if(!t)return{connected:!1,message:"No active login session. Start QR login first."};if(!H(t))return h.delete(e.sessionKey),{connected:!1,message:"QR code expired. Please start again."};let r=Math.max(e.timeoutMs??48e4,1e3),s=Date.now()+r,n=1;for(;Date.now()<s;){try{let i=await it(e.apiBaseUrl,t.qrcode,e.routeTag);switch(t.status=i.status,i.status){case"wait":break;case"scaned":break;case"expired":{if(n++,n>st)return h.delete(e.sessionKey),{connected:!1,message:"Login timeout: QR expired multiple times."};try{let o=e.botType||fe,a=await ye(e.apiBaseUrl,o,e.routeTag);t.qrcode=a.qrcode,t.qrcodeUrl=a.qrcode_img_content,t.startedAt=Date.now()}catch(o){return h.delete(e.sessionKey),{connected:!1,message:`QR refresh failed: ${String(o)}`}}break}case"confirmed":return i.ilink_bot_id?(h.delete(e.sessionKey),{connected:!0,botToken:i.bot_token,accountId:i.ilink_bot_id,baseUrl:i.baseurl,userId:i.ilink_user_id,message:"Connected to WeChat successfully!"}):(h.delete(e.sessionKey),{connected:!1,message:"Login failed: server did not return bot ID."})}}catch(i){return h.delete(e.sessionKey),{connected:!1,message:`Login failed: ${String(i)}`}}await new Promise(i=>setTimeout(i,1e3))}return h.delete(e.sessionKey),{connected:!1,message:"Login timeout. Please try again."}}import C,{promises as P}from"fs";import x from"path";import{homedir as ne}from"os";var F={IMAGE:1,VIDEO:2,FILE:3,VOICE:4},$={NONE:0,USER:1,BOT:2},m={NONE:0,TEXT:1,IMAGE:2,VOICE:3,FILE:4,VIDEO:5},L={NEW:0,GENERATING:1,FINISH:2},_e={TYPING:1,CANCEL:2};var ot=f("channels"),X=-14,D=3600*1e3,M=new Map;function we(e){let t=Date.now()+D;M.set(e,t),ot.info({channelId:e},`Session paused until ${new Date(t).toISOString()} (${D/1e3}s)`)}function B(e){let t=M.get(e);return t===void 0?!1:Date.now()>=t?(M.delete(e),!1):!0}function xe(e){let t=M.get(e);if(t===void 0)return 0;let r=t-Date.now();return r<=0?(M.delete(e),0):r}function Ie(e){M.delete(e)}import Ae from"fs";import ve from"path";import{homedir as mt}from"os";import{createCipheriv as at,createDecipheriv as dt}from"crypto";function Te(e,t){let r=at("aes-128-ecb",t,null);return Buffer.concat([r.update(e),r.final()])}function Ue(e,t){let r=dt("aes-128-ecb",t,null);return Buffer.concat([r.update(e),r.final()])}function ke(e){return Math.ceil((e+1)/16)*16}function J(e,t){return`${t}/download?encrypted_query_param=${encodeURIComponent(e)}`}function Ce(e){return`${e.cdnBaseUrl}/upload?encrypted_query_param=${encodeURIComponent(e.uploadParam)}&filekey=${encodeURIComponent(e.filekey)}`}var Qt=f("channels");function ct(e){let t=Buffer.from(e,"base64");if(t.length===16)return t;if(t.length===32&&/^[0-9a-fA-F]{32}$/.test(t.toString("ascii")))return Buffer.from(t.toString("ascii"),"hex");throw new Error(`aes_key must decode to 16 raw bytes or 32-char hex, got ${t.length} bytes`)}async function Me(e){let t=await fetch(e);if(!t.ok)throw new Error(`CDN download ${t.status} ${t.statusText}`);return Buffer.from(await t.arrayBuffer())}async function R(e){let{encryptQueryParam:t,aesKeyBase64:r,cdnBaseUrl:s,fullUrl:n}=e,i=ct(r),o=n?.trim()||(t?J(t,s):null);if(!o)throw new Error("CDN download: need full_url or encrypt_query_param");let a=await Me(o);return Ue(a,i)}async function Re(e){let{encryptQueryParam:t,cdnBaseUrl:r,fullUrl:s}=e,n=s?.trim()||(t?J(t,r):null);if(!n)throw new Error("CDN download: need full_url or encrypt_query_param");return Me(n)}var W=f("channels"),Ee=24e3;function lt(e,t){let r=e.byteLength,s=44+r,n=Buffer.allocUnsafe(s),i=0;return n.write("RIFF",i),i+=4,n.writeUInt32LE(s-8,i),i+=4,n.write("WAVE",i),i+=4,n.write("fmt ",i),i+=4,n.writeUInt32LE(16,i),i+=4,n.writeUInt16LE(1,i),i+=2,n.writeUInt16LE(1,i),i+=2,n.writeUInt32LE(t,i),i+=4,n.writeUInt32LE(t*2,i),i+=4,n.writeUInt16LE(2,i),i+=2,n.writeUInt16LE(16,i),i+=2,n.write("data",i),i+=4,n.writeUInt32LE(r,i),i+=4,Buffer.from(e.buffer,e.byteOffset,e.byteLength).copy(n,i),n}async function Se(e){try{let{decode:t}=await import("silk-wasm");W.debug(`silkToWav: decoding ${e.length} bytes of SILK`);let r=await t(e,Ee);W.debug(`silkToWav: decoded duration=${r.duration}ms pcmBytes=${r.data.byteLength}`);let s=lt(r.data,Ee);return W.debug(`silkToWav: WAV size=${s.length}`),s}catch(t){return W.warn(`silkToWav: transcode failed, will use raw silk err=${String(t)}`),null}}import ut from"path";var gt={".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".csv":"text/csv",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".mp3":"audio/mpeg",".ogg":"audio/ogg",".wav":"audio/wav",".amr":"audio/amr",".silk":"audio/x-silk",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm",".mkv":"video/x-matroska",".avi":"video/x-msvideo",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp"},pt={"image/jpeg":".jpg","image/jpg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/bmp":".bmp","video/mp4":".mp4","video/quicktime":".mov","video/webm":".webm","video/x-matroska":".mkv","video/x-msvideo":".avi","audio/mpeg":".mp3","audio/ogg":".ogg","audio/wav":".wav","audio/amr":".amr","audio/x-silk":".silk","application/pdf":".pdf","application/zip":".zip","application/x-tar":".tar","application/gzip":".gz","text/plain":".txt","text/csv":".csv"};function q(e){let t=ut.extname(e).toLowerCase();return gt[t]??"application/octet-stream"}function Pe(e){let t=e.split(";")[0].trim().toLowerCase();return pt[t]??".bin"}var k=f("channels"),Oe=100*1024*1024;function ft(e){return Pe(e)??".bin"}async function E(e,t,r,s,n=Oe,i){if(e.length>n)throw new Error(`Media too large: ${e.length} bytes exceeds ${n} bytes`);let o=ve.join(mt(),".adam","wechat","media",s,r);await Ae.promises.mkdir(o,{recursive:!0});let a;if(i&&/^[a-zA-Z0-9._-]+$/.test(i))a=i;else{let l=t?ft(t):".bin",d=Date.now(),u=Math.random().toString(36).slice(2,7);a=`${d}-${u}${l}`}let c=ve.join(o,a);return await Ae.promises.writeFile(c,e),k.debug(`saveMedia: saved ${e.length} bytes to ${c}`),c}async function Ne(e,t){let{cdnBaseUrl:r,channelId:s}=t;if(e.type===m.IMAGE){let n=e.image_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url)return null;let i=n.aeskey?Buffer.from(n.aeskey,"hex").toString("base64"):n.media?.aes_key;try{let o=i?await R({encryptQueryParam:n.media?.encrypt_query_param,aesKeyBase64:i,cdnBaseUrl:r,fullUrl:n.media?.full_url}):await Re({encryptQueryParam:n.media?.encrypt_query_param,cdnBaseUrl:r,fullUrl:n.media?.full_url});return{path:await E(o,"image/png","inbound",s),mimeType:"image/png",type:"image"}}catch(o){return k.error({channelId:s},`Image download/decrypt failed: ${String(o)}`),null}}if(e.type===m.VOICE){let n=e.voice_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let i=await R({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:r,fullUrl:n.media.full_url}),o=await Se(i);if(o){let a=await E(o,"audio/wav","inbound",s);return k.debug(`Voice: saved WAV to ${a}`),{path:a,mimeType:"audio/wav",type:"audio"}}else{let a=await E(i,"audio/silk","inbound",s);return k.debug(`Voice: silk transcode unavailable, saved raw SILK to ${a}`),{path:a,mimeType:"audio/silk",type:"audio"}}}catch(i){return k.error({channelId:s},`Voice download/transcode failed: ${String(i)}`),null}}if(e.type===m.FILE){let n=e.file_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let i=await R({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:r,fullUrl:n.media.full_url}),o=q(n.file_name??"file.bin");return{path:await E(i,o,"inbound",s,Oe,n.file_name),mimeType:o,type:"file"}}catch(i){return k.error({channelId:s},`File download failed: ${String(i)}`),null}}if(e.type===m.VIDEO){let n=e.video_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let i=await R({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:r,fullUrl:n.media.full_url});return{path:await E(i,"video/mp4","inbound",s),mimeType:"video/mp4",type:"video"}}catch(i){return k.error({channelId:s},`Video download failed: ${String(i)}`),null}}return null}import Le from"path";import Y from"crypto";import yt from"fs/promises";var T=f("channels"),j=3;async function ht(e){let{buf:t,uploadFullUrl:r,uploadParam:s,filekey:n,cdnBaseUrl:i,label:o,aeskey:a}=e,c=Te(t,a),l=r?.trim(),d;if(l)d=l;else if(s)d=Ce({cdnBaseUrl:i,uploadParam:s,filekey:n});else throw new Error(`${o}: CDN upload URL missing (need upload_full_url or upload_param)`);T.debug(`${o}: CDN POST url=${d} ciphertextSize=${c.length}`);let u,y;for(let b=1;b<=j;b++)try{let p=await fetch(d,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:new Uint8Array(c)});if(p.status>=400&&p.status<500){let I=p.headers.get("x-error-message")??await p.text();throw T.error(`${o}: CDN client error attempt=${b} status=${p.status} errMsg=${I}`),new Error(`CDN upload client error ${p.status}: ${I}`)}if(p.status!==200){let I=p.headers.get("x-error-message")??`status ${p.status}`;throw T.error(`${o}: CDN server error attempt=${b} status=${p.status} errMsg=${I}`),new Error(`CDN upload server error: ${I}`)}if(u=p.headers.get("x-encrypted-param")??void 0,!u)throw T.error(`${o}: CDN response missing x-encrypted-param header attempt=${b}`),new Error("CDN upload response missing x-encrypted-param header");T.debug(`${o}: CDN upload success attempt=${b}`);break}catch(p){if(y=p,p instanceof Error&&p.message.includes("client error"))throw p;b<j?T.warn(`${o}: attempt ${b} failed, retrying... err=${String(p)}`):T.error(`${o}: all ${j} attempts failed err=${String(p)}`)}if(!u)throw y instanceof Error?y:new Error(`CDN upload failed after ${j} attempts`);return{downloadParam:u}}async function Z(e){let{filePath:t,toUserId:r,opts:s,cdnBaseUrl:n,mediaType:i,label:o}=e,a=await yt.readFile(t),c=a.length,l=Y.createHash("md5").update(a).digest("hex"),d=ke(c),u=Y.randomBytes(16).toString("hex"),y=Y.randomBytes(16);T.debug(`${o}: file=${t} rawsize=${c} filesize=${d} md5=${l} filekey=${u}`);let b=await pe({...s,filekey:u,media_type:i,to_user_id:r,rawsize:c,rawfilemd5:l,filesize:d,no_need_thumb:!0,aeskey:y.toString("hex")}),p=b.upload_full_url?.trim(),I=b.upload_param;if(!p&&!I)throw new Error(`${o}: getUploadUrl returned no upload URL (need upload_full_url or upload_param)`);let{downloadParam:ze}=await ht({buf:a,uploadFullUrl:p||void 0,uploadParam:I??void 0,filekey:u,cdnBaseUrl:n,aeskey:y,label:`${o}[orig filekey=${u}]`});return{filekey:u,downloadEncryptedQueryParam:ze,aeskey:y.toString("hex"),fileSize:c,fileSizeCiphertext:d}}async function Fe(e){return Z({...e,mediaType:F.IMAGE,label:"uploadImageToWeixin"})}async function $e(e){return Z({...e,mediaType:F.VIDEO,label:"uploadVideoToWeixin"})}async function ee(e){return Z({...e,mediaType:F.FILE,label:"uploadFileAttachmentToWeixin"})}var S=f("channels");function bt(){return`adam-wechat-${Date.now()}-${Math.random().toString(36).slice(2,7)}`}function _t(e){let t=e;return t=t.replace(/```[^\n]*\n?([\s\S]*?)```/g,(r,s)=>s.trim()),t=t.replace(/!\[[^\]]*\]\([^)]*\)/g,""),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/^\|[\s:|-]+\|$/gm,""),t=t.replace(/^\|(.+)\|$/gm,(r,s)=>s.split("|").map(n=>n.trim()).join(" ")),t}async function te(e){let{to:t,text:r,mediaItem:s,opts:n,label:i}=e,o=[],a=_t(r);a&&o.push({type:m.TEXT,text_item:{text:a}}),o.push(s);let c="";for(let l of o){c=bt();let d={msg:{from_user_id:"",to_user_id:t,client_id:c,message_type:$.BOT,message_state:L.FINISH,item_list:[l],context_token:n.contextToken}};await N({baseUrl:n.baseUrl,token:n.token,routeTag:n.routeTag,body:d})}return S.debug(`${i}: sent to=${t} messageId=${c}`),{messageId:c}}async function wt(e){let{to:t,text:r,uploaded:s,opts:n}=e,i={type:m.IMAGE,image_item:{media:{encrypt_query_param:s.downloadEncryptedQueryParam,aes_key:Buffer.from(s.aeskey).toString("base64"),encrypt_type:1},mid_size:s.fileSizeCiphertext}};return te({to:t,text:r,mediaItem:i,opts:n,label:"sendImageMessage"})}async function xt(e){let{to:t,text:r,uploaded:s,opts:n}=e,i={type:m.VIDEO,video_item:{media:{encrypt_query_param:s.downloadEncryptedQueryParam,aes_key:Buffer.from(s.aeskey).toString("base64"),encrypt_type:1},video_size:s.fileSizeCiphertext}};return te({to:t,text:r,mediaItem:i,opts:n,label:"sendVideoMessage"})}async function De(e){let{to:t,text:r,fileName:s,uploaded:n,opts:i}=e,o={type:m.FILE,file_item:{media:{encrypt_query_param:n.downloadEncryptedQueryParam,aes_key:Buffer.from(n.aeskey).toString("base64"),encrypt_type:1},file_name:s,len:String(n.fileSize)}};return te({to:t,text:r,mediaItem:o,opts:i,label:"sendFileMessage"})}async function Be(e){let{filePath:t,to:r,text:s,opts:n,cdnBaseUrl:i}=e,o=q(t),a={baseUrl:n.baseUrl,token:n.token,routeTag:n.routeTag};if(o.startsWith("video/")){S.debug(`sendWeixinMediaFile: uploading video filePath=${t} to=${r}`);let d=await $e({filePath:t,toUserId:r,opts:a,cdnBaseUrl:i});return xt({to:r,text:s,uploaded:d,opts:n})}if(o.startsWith("image/")){S.debug(`sendWeixinMediaFile: uploading image filePath=${t} to=${r}`);let d=await Fe({filePath:t,toUserId:r,opts:a,cdnBaseUrl:i});return wt({to:r,text:s,uploaded:d,opts:n})}if(o.startsWith("audio/")){let d=Le.basename(t);S.debug(`sendWeixinMediaFile: uploading audio as file filePath=${t} name=${d} to=${r}`);let u=await ee({filePath:t,fileName:d,toUserId:r,opts:a,cdnBaseUrl:i});return De({to:r,text:s,fileName:d,uploaded:u,opts:n})}let c=Le.basename(t);S.debug(`sendWeixinMediaFile: uploading file attachment filePath=${t} name=${c} to=${r}`);let l=await ee({filePath:t,fileName:c,toUserId:r,opts:a,cdnBaseUrl:i});return De({to:r,text:s,fileName:c,uploaded:l,opts:n})}var w=f("channels"),We="https://novac2c.cdn.weixin.qq.com/c2c",re=new Map;function je(e){return x.join(ne(),".adam","wechat",`${e}.context-tokens.json`)}function It(e){let t=je(e);try{let r=C.readFileSync(t,"utf-8"),s=JSON.parse(r);for(let[n,i]of Object.entries(s))typeof i=="string"&&i&&re.set(`${e}:${n}`,i);w.debug({channelId:e,count:Object.keys(s).length},"Restored context tokens from disk")}catch{}}function Tt(e,t,r){let s=je(e);try{let n={};try{let o=C.readFileSync(s,"utf-8");n=JSON.parse(o)}catch{}n[t]=r;let i=x.dirname(s);C.mkdirSync(i,{recursive:!0}),C.writeFileSync(s,JSON.stringify(n),"utf-8")}catch(n){w.warn({channelId:e,userId:t},`Failed to persist context token: ${String(n)}`)}}function Ut(e,t,r){re.set(`${e}:${t}`,r),Tt(e,t,r)}function qe(e,t){return re.get(`${e}:${t}`)}function Ve(e){return x.join(ne(),".adam","wechat",`${e}.sync`)}function kt(e){try{return C.readFileSync(Ve(e),"utf-8")}catch{return""}}function Ct(e,t){let r=Ve(e);C.mkdirSync(x.dirname(r),{recursive:!0}),C.writeFileSync(r,t,"utf-8")}var Mt=0;function Rt(){return`adam-wechat-${Date.now()}-${++Mt}`}var V=class{platform="wechat";id;config;status="disconnected";messageHandler=null;pollAbort=null;getUpdatesBuf="";constructor(t,r){if(this.id=t,!r.baseUrl)throw new Error("WeChat adapter requires baseUrl");this.config=r}async connect(){if(!this.config.botToken)throw new Error("WeChat adapter requires botToken. Complete QR login first.");this.status="connecting",this.getUpdatesBuf=kt(this.id),It(this.id),this.pollAbort=new AbortController,this.status="connected",w.info({channelId:this.id},"WeChat adapter connected, starting long-poll"),this.startLongPoll()}async disconnect(){this.pollAbort&&(this.pollAbort.abort(),this.pollAbort=null),this.status="disconnected",w.info({channelId:this.id},"WeChat adapter disconnected")}getStatus(){return this.status==="connected"&&B(this.id)?"error":this.status}async sendMessage(t,r){if(B(this.id)){let o=Math.ceil(xe(this.id)/6e4);throw new Error(`WeChat session paused, ${o} min remaining. Re-scan QR to reconnect.`)}let s=Rt(),n=qe(this.id,t),i=this.config.cdnBaseUrl??We;if(r.mediaUrl)try{let o=!r.mediaUrl.includes("://")||r.mediaUrl.startsWith("file://"),a=x.join(ne(),".adam","wechat","media","outbound-tmp");await P.mkdir(a,{recursive:!0});let c=this.getExtensionFromMediaType(r.mediaType),l;if(o){let u=r.mediaUrl.startsWith("file://")?new URL(r.mediaUrl).pathname:x.isAbsolute(r.mediaUrl)?r.mediaUrl:x.resolve(r.mediaUrl),y=await P.readFile(u);l=x.join(a,`${Date.now()}-${Math.random().toString(36).slice(2,7)}${c}`),await P.writeFile(l,y)}else{let u=await fetch(r.mediaUrl);if(!u.ok)throw new Error(`Failed to fetch media: ${u.status}`);let y=Buffer.from(await u.arrayBuffer());l=x.join(a,`${Date.now()}-${Math.random().toString(36).slice(2,7)}${c}`),await P.writeFile(l,y)}let d=await Be({filePath:l,to:t,text:r.content??"",opts:{baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,contextToken:n},cdnBaseUrl:i});return await P.unlink(l).catch(()=>{}),d.messageId}catch(o){throw w.error({channelId:this.id},`sendMessage media handling failed: ${String(o)}`),o}return await N({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{msg:{from_user_id:"",to_user_id:t,client_id:s,message_type:$.BOT,message_state:L.FINISH,item_list:r.content?[{type:m.TEXT,text_item:{text:r.content}}]:void 0,context_token:n}}}),s}onMessage(t){this.messageHandler=t}async sendTypingIndicator(t){if(B(this.id))return;let r=qe(this.id,t);try{await ge({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{ilink_user_id:t,status:_e.TYPING}})}catch{}}updateConfig(t){Object.assign(this.config,t)}async startLongPoll(){let t=this.pollAbort?.signal,r=0,s=3,n=3e4,i=2e3;for(;!t?.aborted;)try{let o=await ue({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,get_updates_buf:this.getUpdatesBuf});if(o.ret===X||o.errcode===X){we(this.id),this.status="error",w.error({channelId:this.id},"Session expired (errcode=-14), pausing for 1 hour"),await this.sleep(D,t),Ie(this.id),this.status="connected";continue}if(o.ret!==void 0&&o.ret!==0||o.errcode!==void 0&&o.errcode!==0){r++,w.error({channelId:this.id,ret:o.ret,errcode:o.errcode},"getUpdates API error"),r>=s?(r=0,await this.sleep(n,t)):await this.sleep(i,t);continue}r=0,o.get_updates_buf&&(this.getUpdatesBuf=o.get_updates_buf,Ct(this.id,o.get_updates_buf));for(let c of o.msgs??[])await this.processInbound(c)}catch(o){if(t?.aborted)return;r++,w.error({channelId:this.id,error:o},"getUpdates error"),r>=s?(r=0,await this.sleep(n,t)):await this.sleep(i,t)}}async processInbound(t){if(!this.messageHandler)return;let r=!!t.group_id,s=r?t.group_id:t.from_user_id??"",n=t.from_user_id??"";t.context_token&&s&&Ut(this.id,s,t.context_token);let i="",o,a=[];for(let d of t.item_list??[])d.type===m.TEXT&&d.text_item?.text&&(i+=d.text_item.text),d.type===m.IMAGE&&(o="image",a.push(d)),d.type===m.VOICE&&(o="audio",a.push(d),d.voice_item?.text&&!i&&(i=d.voice_item.text)),d.type===m.FILE&&(o="file",a.push(d)),d.type===m.VIDEO&&(o="video",a.push(d));if(!i&&!o)return;let c;if(a.length>0){let d=this.config.cdnBaseUrl??We;try{let u=await Ne(a[0],{cdnBaseUrl:d,channelId:this.id});u&&(c=u.path,o=u.type)}catch(u){w.error({channelId:this.id},`Media download failed: ${String(u)}`)}}let l={channelId:this.id,platform:"wechat",chatId:s,senderId:n,content:i,mediaType:o,mediaPath:c,isGroup:r,timestamp:t.create_time_ms??Date.now(),raw:t};this.messageHandler(l)}getExtensionFromMediaType(t){switch(t){case"image":return".png";case"video":return".mp4";case"audio":return".mp3";default:return".bin"}}sleep(t,r){return new Promise((s,n)=>{let i=setTimeout(s,t);r?.addEventListener("abort",()=>{clearTimeout(i),n(new Error("aborted"))},{once:!0})})}};var Et=f("channels"),z=class{platform="discord";id;config;status="disconnected";messageHandler=null;client=null;constructor(t,r){if(this.id=t,!r.botToken)throw new Error("Discord adapter requires botToken");this.config=r}async connect(){this.status="connecting";try{let{Client:t,GatewayIntentBits:r}=await import("discord.js");this.client=new t({intents:[r.Guilds,r.GuildMessages,r.MessageContent,r.DirectMessages]});let s=this.client;s.on("messageCreate",n=>{if(!this.messageHandler||n.author.bot||this.config.allowedGuildIds?.length&&n.guildId&&!this.config.allowedGuildIds.includes(n.guildId))return;let i={channelId:this.id,platform:"discord",chatId:n.channelId,senderId:n.author.id,senderName:n.author.displayName??n.author.username,content:n.content,isGroup:!!n.guildId,timestamp:n.createdTimestamp,raw:n};this.messageHandler(i)}),await s.login(this.config.botToken),this.status="connected",Et.info({channelId:this.id},"Discord bot connected")}catch(t){throw this.status="error",t}}async disconnect(){this.client&&await this.client.destroy(),this.client=null,this.status="disconnected"}getStatus(){return this.status}async sendMessage(t,r){if(!this.client)throw new Error("Discord client not connected");let n=await this.client.channels.fetch(t);if(!n||!("send"in n))throw new Error(`Channel ${t} not found or not text channel`);return(await n.send({content:r.content,reply:r.replyToMessageId?{messageReference:r.replyToMessageId}:void 0})).id}onMessage(t){this.messageHandler=t}async sendTypingIndicator(t){if(!this.client)return;let s=await this.client.channels.fetch(t);s&&"sendTyping"in s&&await s.sendTyping()}};var U=g.object({id:g.string().uuid()}),Pt=g.object({name:g.string().min(1,"name is required"),platform:g.string().min(1,"platform is required"),config:g.record(g.string(),g.unknown()),enabled:g.boolean().optional().default(!0),linkedRoleId:g.string().optional(),allowedChatIds:g.array(g.string()).optional()}),At=g.object({name:g.string().min(1).optional(),enabled:g.boolean().optional(),config:g.record(g.string(),g.unknown()).optional(),linkedRoleId:g.string().optional(),allowedChatIds:g.array(g.string()).optional()}),ie;function Vn(e){ie=e}function zn(){return ie}async function Gn(e){let t=ie;e.get("/channels",{schema:{tags:["Channels"],summary:"List channels",querystring:{type:"object",properties:{enabled:{type:"boolean"}}}}},async(r,s)=>({channels:ae(r.query.enabled)})),e.post("/channels",{schema:{tags:["Channels"],summary:"Create a channel",body:{type:"object",required:["name","platform","config"],properties:{name:{type:"string",minLength:1},platform:{type:"string",minLength:1},config:{type:"object"},enabled:{type:"boolean"},linkedRoleId:{type:"string"},allowedChatIds:{type:"array",items:{type:"string"}}}}}},async(r,s)=>{let n=Pt.safeParse(r.body);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let{name:i,platform:o,config:a,enabled:c,linkedRoleId:l,allowedChatIds:d}=n.data,u={id:St(),name:i,platform:o,enabled:c,status:"disconnected",config:a,linkedRoleId:l,allowedChatIds:d,createdAt:Date.now(),messageCount:0};return oe(u),s.status(201).send({channel:u})}),e.get("/channels/:id",{schema:{tags:["Channels"],summary:"Get channel by ID",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let n=U.safeParse(r.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let i=_(n.data.id);return i?{channel:i}:s.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),e.patch("/channels/:id",{schema:{tags:["Channels"],summary:"Update channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",properties:{name:{type:"string"},enabled:{type:"boolean"},config:{type:"object"},linkedRoleId:{type:"string"},allowedChatIds:{type:"array",items:{type:"string"}}}}}},async(r,s)=>{let n=U.safeParse(r.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let i=_(n.data.id);if(!i)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let o=At.safeParse(r.body);return o.success?(G(i.id,o.data),{channel:_(i.id)}):s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(o.error)})}),e.delete("/channels/:id",{schema:{tags:["Channels"],summary:"Delete channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let n=U.safeParse(r.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let i=_(n.data.id);return i?(de(i.id),s.status(204).send()):s.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),e.post("/channels/:id/connect",{schema:{tags:["Channels"],summary:"Connect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let n=U.safeParse(r.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});if(!t)return s.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let i=_(n.data.id);if(!i)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(!t.hasAdapter(i.id)&&i.platform==="discord"){let o=i.config;if(!o.botToken)return s.status(400).send({code:"MISSING_CONFIG",message:"Discord channel requires botToken in config"});let a=new z(i.id,{botToken:o.botToken});await t.addChannel(i,a)}if(!t.hasAdapter(i.id))return s.status(400).send({code:"NO_ADAPTER",message:"No adapter registered for this channel. Install the appropriate adapter first."});try{return await t.connectChannel(i.id),{channelId:i.id,status:"connected"}}catch(o){return s.status(500).send({code:"CONNECT_FAILED",message:String(o)})}}),e.post("/channels/:id/disconnect",{schema:{tags:["Channels"],summary:"Disconnect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let n=U.safeParse(r.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});if(!t)return s.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let i=_(n.data.id);return i?(await t.disconnectChannel(i.id),{channelId:i.id,status:"disconnected"}):s.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),e.get("/channels/:id/messages",{schema:{tags:["Channels"],summary:"Get channel message history",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50},offset:{type:"integer",minimum:0,default:0}}}}},async(r,s)=>{let n=U.safeParse(r.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let i=_(n.data.id);if(!i)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let{limit:o=50,offset:a=0}=r.query;return{messages:se(i.id,o,a)}}),e.post("/channels/:id/wechat/qr-start",{schema:{tags:["WeChat"],summary:"Start WeChat QR login",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(r,s)=>{let n=U.safeParse(r.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let i=_(n.data.id);if(!i)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(i.platform!=="wechat")return s.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=i.config;return await he({apiBaseUrl:o.baseUrl,routeTag:o.routeTag})}),e.post("/channels/:id/wechat/qr-wait",{schema:{tags:["WeChat"],summary:"Wait for WeChat QR scan",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",properties:{sessionKey:{type:"string"},timeoutMs:{type:"number"}}}}},async(r,s)=>{let n=U.safeParse(r.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let i=_(n.data.id);if(!i)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(i.platform!=="wechat")return s.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=i.config,{sessionKey:a,timeoutMs:c}=r.body??{},l=await be({sessionKey:a??"",apiBaseUrl:o.baseUrl,timeoutMs:c??12e4,routeTag:o.routeTag});if(l.connected&&l.botToken){let d={...o,botToken:l.botToken,accountId:l.accountId,baseUrl:l.baseUrl??o.baseUrl,userId:l.userId};if(G(i.id,{config:d}),t){let u=new V(i.id,d),y=_(i.id);y&&await t.addChannel(y,u)}}return{connected:l.connected,accountId:l.accountId,message:l.message}})}export{V as a,z as b,Vn as c,zn as d,Gn as e};
|
package/dist/chunk-WZOMGJSY.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as S}from"./chunk-3DAK2XWP.js";import*as s from"fs";import*as l from"path";import{homedir as x}from"os";var v=S("embedding"),M=null,A=!1;async function L(){if(A)throw new Error("onnxruntime-node native binding not available. Embedding disabled.");if(!M)try{M=await import("./dist-CDWBOTZS.js")}catch(e){throw A=!0,v.warn({error:e.message},"onnxruntime-node not available"),new Error("onnxruntime-node native binding not available. Embedding disabled.")}return M}var F=l.join(x(),".adam","models"),P="all-MiniLM-L6-v2",T="model.onnx",B="tokenizer.json",N="https://huggingface.co/Xenova/all-MiniLM-L6-v2/resolve/main/onnx/model_quantized.onnx",O="https://huggingface.co/Xenova/all-MiniLM-L6-v2/resolve/main/tokenizer.json",j=384,y=null,k=null;function z(){let e=l.join(F,P);return s.existsSync(e)||s.mkdirSync(e,{recursive:!0}),e}async function _(e,t){if(s.existsSync(t))return;v.info({file:l.basename(t)},"Downloading model file");let f=await fetch(e);if(!f.ok)throw new Error(`Failed to download ${e}: ${f.status}`);let i=Buffer.from(await f.arrayBuffer());s.writeFileSync(t,i),v.info({file:l.basename(t),sizeMb:(i.length/1024/1024).toFixed(1)},"Model file downloaded")}async function R(){let e=z(),t=l.join(e,T),f=l.join(e,B);return await _(N,t),await _(O,f),t}function U(){if(k)return k;let e=l.join(z(),B);if(!s.existsSync(e))throw new Error("Tokenizer not found. Run generateEmbedding first to download.");return k=JSON.parse(s.readFileSync(e,"utf-8")),k}function $(e,t=128){let i=U().model.vocab,w=i["[CLS]"]??101,I=i["[SEP]"]??102,u=i["[UNK]"]??100,E=i["[PAD]"]??0,p=e.toLowerCase().replace(/[^\w\s\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff]/g," ").split(/\s+/).filter(Boolean),r=[w];for(let o of p){if(r.length>=t-1)break;if(i[o]!==void 0){r.push(i[o]);continue}let d=!1,n=o,m=!0;for(;n.length>0&&r.length<t-1;){let D=!1;for(let g=n.length;g>0;g--){let b=m?n.slice(0,g):`##${n.slice(0,g)}`;if(i[b]!==void 0){r.push(i[b]),n=n.slice(g),m=!1,D=!0,d=!0;break}}if(!D)if(n.length>=2){let g=n.slice(0,2),b=i[g]??i[`##${g}`]??u;r.push(b),n=n.slice(2),d=!0}else r.push(u),n=""}d||r.push(u)}r.push(I);let h=new BigInt64Array(t),a=new BigInt64Array(t),c=new BigInt64Array(t);for(let o=0;o<t;o++)o<r.length?(h[o]=BigInt(r[o]),a[o]=1n):(h[o]=BigInt(E),a[o]=0n),c[o]=0n;return{inputIds:h,attentionMask:a,tokenTypeIds:c}}async function q(){if(y)return y;let e=await L(),t=await R();return y=await e.InferenceSession.create(t,{executionProviders:["cpu"]}),y}async function X(e){let t=await L(),f=await q(),{inputIds:i,attentionMask:w,tokenTypeIds:I}=$(e),u=i.length,E={input_ids:new t.Tensor("int64",i,[1,u]),attention_mask:new t.Tensor("int64",w,[1,u]),token_type_ids:new t.Tensor("int64",I,[1,u])},p=await f.run(E),h=(p.last_hidden_state??p[Object.keys(p)[0]]).data,a=j,c=new Float32Array(a),o=0;for(let n=0;n<u;n++)if(w[n]===1n){o++;for(let m=0;m<a;m++)c[m]+=h[n*a+m]}if(o>0)for(let n=0;n<a;n++)c[n]/=o;let d=0;for(let n=0;n<a;n++)d+=c[n]*c[n];if(d=Math.sqrt(d),d>0)for(let n=0;n<a;n++)c[n]/=d;return c}function Z(){let e=l.join(z(),T);return s.existsSync(e)}export{X as a,Z as b};
|
package/dist/chunk-XNWZZYAV.js
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{b as l,d as v}from"./chunk-PCSZW2PE.js";import{b as d,g as m}from"./chunk-SFUS33SO.js";import{c as h,e as R}from"./chunk-FCV2DPZQ.js";import*as g from"os";import*as o from"path";function a(e){return e.startsWith("~/")||e==="~"?o.join(g.homedir(),e.slice(1)):e}function u(e){return a(e)}function P(e,n){let t=[];if(typeof n.file_path=="string"&&t.push(n.file_path),typeof n.path=="string"&&t.push(n.path),typeof n.pattern=="string"&&e==="Glob"){let i=n.pattern,r=o.dirname(i);r!=="."&&t.push(r)}if(e==="Bash"&&typeof n.command=="string"){let r=n.command.match(/(?:~\/|\/)[^\s;|&><"']+/g);r&&t.push(...r)}return t}function I(e,n,t){let i=o.resolve(n,a(e));for(let r of d){let s=a(r);if(i.startsWith(s))return{allowed:!1,reason:`Access to ${r} is always denied (hardcoded security rule)`}}for(let r of t.deniedPaths){let s=o.resolve(n,a(r));if(i.startsWith(s))return{allowed:!1,reason:`Access to ${r} is denied by agent permission`}}return t.allowedPaths.length>0&&!t.allowedPaths.some(s=>{let p=o.resolve(n,a(s));return i.startsWith(p)})?{allowed:!1,reason:`Path ${e} is outside allowed paths: ${t.allowedPaths.join(", ")}`}:{allowed:!0}}var _=h(()=>{"use strict";m()});var N={};R(N,{createRole:()=>E,deleteRole:()=>x,getRole:()=>O,getRoleByName:()=>w,listRoles:()=>T,updateRole:()=>D,validateAdditionalDirectories:()=>c});import{existsSync as y}from"fs";import{resolve as S}from"path";function c(e){for(let n of e){let t=typeof n=="string"?n:n.path;if(!t.startsWith("/")&&!t.startsWith("~/")&&t!=="~")throw new Error(`additionalDirectories must be absolute paths: '${t}' is not absolute`);let i=S(u(t));if(!i.startsWith("/"))throw new Error(`additionalDirectories must be absolute paths: '${t}' is not absolute`);for(let r of d){let s=S(u(r));if(i.startsWith(s))throw new Error(`additionalDirectories cannot include hardcoded denied path: '${t}' matches '${r}'`)}if(!y(i))throw new Error(`additionalDirectories path does not exist: '${t}'`)}}function f(e){return{id:e.id,name:e.name,cagPrompt:e.cag_prompt,learnedRules:e.learned_rules?JSON.parse(e.learned_rules):[],memoryStreamId:e.memory_stream_id,status:e.status,performanceScore:e.performance_score??void 0,preferences:e.preferences?JSON.parse(e.preferences):{},createdAt:e.created_at,updatedAt:e.updated_at??void 0,allowedTools:e.allowed_tools?JSON.parse(e.allowed_tools):void 0,disallowedTools:e.disallowed_tools?JSON.parse(e.disallowed_tools):void 0,evaluationCriteria:e.evaluation_criteria?JSON.parse(e.evaluation_criteria):void 0,executionMode:e.execution_mode??void 0,model:e.model??void 0,maxBudgetUsd:e.max_budget_usd??void 0,approvalRequired:e.approval_required?JSON.parse(e.approval_required):void 0,source:e.source??void 0,additionalDirectories:(()=>{if(e.additional_directories!==null)try{let n=JSON.parse(e.additional_directories);return Array.isArray(n)?n.map(t=>typeof t=="string"?{path:t}:t):void 0}catch{return}})(),allowedChannels:e.allowed_channels?JSON.parse(e.allowed_channels):void 0,mcpServers:e.mcp_servers?JSON.parse(e.mcp_servers):void 0,inheritUserSettings:e.inherit_user_settings===1?!0:void 0}}function E(e){e.additionalDirectories&&c(e.additionalDirectories),l().prepare(`
|
|
2
|
-
INSERT INTO roles (id, name, cag_prompt, learned_rules, memory_stream_id, status,
|
|
3
|
-
performance_score, preferences, created_at, updated_at,
|
|
4
|
-
allowed_tools, disallowed_tools, evaluation_criteria, execution_mode, model,
|
|
5
|
-
max_budget_usd, approval_required, source, additional_directories, allowed_channels, mcp_servers, inherit_user_settings)
|
|
6
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
7
|
-
`).run(e.id,e.name,e.cagPrompt,JSON.stringify(e.learnedRules),e.memoryStreamId,e.status,e.performanceScore??null,e.preferences?JSON.stringify(e.preferences):null,e.createdAt,e.updatedAt??null,e.allowedTools?JSON.stringify(e.allowedTools):null,e.disallowedTools?JSON.stringify(e.disallowedTools):null,e.evaluationCriteria?JSON.stringify(e.evaluationCriteria):null,e.executionMode??null,e.model??null,e.maxBudgetUsd??null,e.approvalRequired?JSON.stringify(e.approvalRequired):null,e.source??null,e.additionalDirectories?JSON.stringify(e.additionalDirectories):null,e.allowedChannels?JSON.stringify(e.allowedChannels):null,e.mcpServers?JSON.stringify(e.mcpServers):null,e.inheritUserSettings?1:0)}function O(e){let t=l().prepare("SELECT * FROM roles WHERE id = ?").get(e);return t?f(t):void 0}function w(e){let t=l().prepare("SELECT * FROM roles WHERE name = ?").get(e);return t?f(t):void 0}function D(e,n){let t=l(),i=[],r=[];"name"in n&&(i.push("name = ?"),r.push(n.name)),"cagPrompt"in n&&(i.push("cag_prompt = ?"),r.push(n.cagPrompt)),"learnedRules"in n&&(i.push("learned_rules = ?"),r.push(JSON.stringify(n.learnedRules))),"memoryStreamId"in n&&(i.push("memory_stream_id = ?"),r.push(n.memoryStreamId)),"status"in n&&(i.push("status = ?"),r.push(n.status)),"performanceScore"in n&&(i.push("performance_score = ?"),r.push(n.performanceScore??null)),"preferences"in n&&(i.push("preferences = ?"),r.push(n.preferences?JSON.stringify(n.preferences):null)),"updatedAt"in n&&(i.push("updated_at = ?"),r.push(n.updatedAt??null)),"allowedTools"in n&&(i.push("allowed_tools = ?"),r.push(n.allowedTools?JSON.stringify(n.allowedTools):null)),"disallowedTools"in n&&(i.push("disallowed_tools = ?"),r.push(n.disallowedTools?JSON.stringify(n.disallowedTools):null)),"evaluationCriteria"in n&&(i.push("evaluation_criteria = ?"),r.push(n.evaluationCriteria?JSON.stringify(n.evaluationCriteria):null)),"executionMode"in n&&(i.push("execution_mode = ?"),r.push(n.executionMode??null)),"model"in n&&(i.push("model = ?"),r.push(n.model??null)),"maxBudgetUsd"in n&&(i.push("max_budget_usd = ?"),r.push(n.maxBudgetUsd??null)),"approvalRequired"in n&&(i.push("approval_required = ?"),r.push(n.approvalRequired?JSON.stringify(n.approvalRequired):null)),"source"in n&&(i.push("source = ?"),r.push(n.source??null)),"additionalDirectories"in n&&(n.additionalDirectories&&c(n.additionalDirectories),i.push("additional_directories = ?"),r.push(n.additionalDirectories?JSON.stringify(n.additionalDirectories):null)),"allowedChannels"in n&&(i.push("allowed_channels = ?"),r.push(n.allowedChannels?JSON.stringify(n.allowedChannels):null)),"mcpServers"in n&&(i.push("mcp_servers = ?"),r.push(n.mcpServers?JSON.stringify(n.mcpServers):null)),"inheritUserSettings"in n&&(i.push("inherit_user_settings = ?"),r.push(n.inheritUserSettings?1:0)),i.length!==0&&(r.push(e),t.prepare(`UPDATE roles SET ${i.join(", ")} WHERE id = ?`).run(...r))}function T(e,n=100,t=0){let i=l(),r="SELECT * FROM roles",s=[];return e&&(r+=" WHERE status = ?",s.push(e)),r+=" ORDER BY created_at ASC LIMIT ? OFFSET ?",s.push(n,t),i.prepare(r).all(...s).map(f)}function x(e){l().prepare("DELETE FROM roles WHERE id = ?").run(e)}var b=h(()=>{v();m();_()});export{P as a,I as b,_ as c,c as d,E as e,O as f,w as g,D as h,T as i,x as j,N as k,b as l};
|
package/dist/config-WHXCZCI4.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d,e,f}from"./chunk-JXD6ZPV7.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-FCV2DPZQ.js";export{f as deleteConfigValue,c as getAllConfig,a as getConfigValue,e as isConfigEmpty,d as seedConfig,b as setConfigValue};
|
package/dist/config-Y4QWELO3.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as b,b as c,d,e}from"./chunk-T25NLVMY.js";import{a}from"./chunk-ETQ7KC73.js";import"./chunk-FYDFMYUP.js";import"./chunk-SFUS33SO.js";import"./chunk-FCV2DPZQ.js";export{a as DEFAULT_CONFIG,e as getChatConfig,d as getDefaults,b as loadConfig,c as loadDefaultConfig};
|
package/dist/db-PNZ3UJOE.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d}from"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-FCV2DPZQ.js";d();export{c as closeDb,b as getDb,a as runMigrations};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i}from"./chunk-FDWW245P.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.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};
|
package/dist/engine-DEBMZJBM.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d}from"./chunk-MX6AZ7WD.js";import"./chunk-NXTTKAQX.js";import"./chunk-KICPHTI2.js";import"./chunk-5ASEAZCR.js";import"./chunk-742NWPTQ.js";import"./chunk-PQ7KPALO.js";import"./chunk-FDWW245P.js";import"./chunk-L7426WNY.js";import"./chunk-L7JP7DUO.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{a as DeliveryEngine,b as getDeliveryEngine,c as initDeliveryEngine,d as stopDeliveryEngine};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d,e}from"./chunk-B6S2AEOD.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-FCV2DPZQ.js";export{a as createEvolutionAudit,e as generateDiff,d as getLatestRoleEvolution,b as listEvolutionAudit,c as listEvolutionAuditByRole};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as i}from"./chunk-ETQ7KC73.js";import"./chunk-SFUS33SO.js";import{c as a}from"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";var c=a("agent");async function g(n){let e=p();if(e.length===0)return{scores:[],errors:[]};let s=[],r=[];for(let t of e)try{let o=await u(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)}`),c.warn({endpoint:t.name,error:o},"External API fetch failed")}return{scores:s,errors:r}}async function u(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=l(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 l(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 p(){return i.externalApis??[]}export{g as collectExternalApiScores};
|
package/dist/learner-VMD5NQCD.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as l,e as T,f as D,g as S}from"./chunk-IXF3XBGX.js";import{b as y}from"./chunk-AXMXXUPO.js";import{b as u}from"./chunk-L7426WNY.js";import{a as x,c as R,f as N}from"./chunk-U36NBCR3.js";import{f as h,h as k,l as E}from"./chunk-XNWZZYAV.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import{c as d}from"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";var $=d("agent");function w(n){let o=l(n);if(!o){$.debug({taskId:n},"No plan found for task, skipping review");return}let i=y(n,1e3),s=o.plan.steps,a=i.filter(e=>e.type==="tool_result"||e.type==="permission_denied").map(e=>({toolName:e.toolName??"unknown",output:e.content,planStepIndex:e.planStepIndex,permissionDenied:e.type==="permission_denied"})),t=[],r=new Set(a.map(e=>e.planStepIndex).filter(e=>e!==void 0));for(let e of s)r.has(e.index)||t.push({stepIndex:e.index,planned:e.description,actual:"Not executed",deviationType:"skipped"});let c=a.filter(e=>e.planStepIndex===void 0);for(let e of c)t.push({stepIndex:-1,planned:"",actual:`${e.toolName}: ${e.output.slice(0,200)}`,deviationType:"added"});let P=a.filter(e=>e.permissionDenied);for(let e of P)t.push({stepIndex:e.planStepIndex??-1,planned:e.planStepIndex!==void 0?s.find(b=>b.index===e.planStepIndex)?.description??"Unknown":"",actual:`PERMISSION DENIED: ${e.toolName}`,deviationType:"failed"});let p=s.length,m=a.length,g=p>0?Math.max(0,1-t.filter(e=>e.deviationType!=="added").length/p):1,v={stepsPlanned:p,stepsExecuted:m,deviations:t,overallAccuracy:g};return D(o.id,v),$.info({taskId:n,planId:o.id,stepsPlanned:p,stepsExecuted:m,deviationCount:t.length,accuracy:g},"Deviation report generated"),v}function I(n){return n.deviations.filter(i=>i.deviationType==="failed"||i.deviationType==="skipped").length===0&&n.overallAccuracy>=.7}E();N();var f=d("agent");function C(n,o){let i=[],a=u(n)?.prompt.slice(0,100)??"unknown task";I(o)&&i.push(`[+] Task "${a}" completed successfully with ${o.overallAccuracy*100}% plan accuracy (${o.stepsExecuted} steps). [sourceTaskId:${n}]`);for(let t of o.deviations)switch(t.deviationType){case"skipped":i.push(`[-] Planned step "${t.planned}" was skipped during "${a}". Consider if this step is necessary for similar tasks. [sourceTaskId:${n}]`);break;case"failed":i.push(`[-] Step failed: "${t.actual}" during "${a}". Check permissions and tool availability. [sourceTaskId:${n}]`);break;case"added":i.push(`[~] Unplanned action: "${t.actual}" during "${a}". Consider adding to plan for similar tasks. [sourceTaskId:${n}]`);break;case"modified":i.push(`[~] Step modified: planned "${t.planned}" but did "${t.actual}" during "${a}". [sourceTaskId:${n}]`);break}return i}async function q(n){let o=l(n);if(!o){f.debug({taskId:n},"No plan for task, skipping review/learn");return}let i=w(n);if(!i)return;let s=C(n,i);if(s.length===0)return;S(o.id,s);let a=u(n);if(a?.roleId){let t=h(a.roleId);if(t){let r=[...t.learnedRules,...s];k(a.roleId,{learnedRules:r});let c=x(t.name);R(c,{...t,learnedRules:r}),f.info({roleId:a.roleId,newRulesCount:s.length},"Role learnedRules updated and CLAUDE.md written")}}T(o.id,"completed"),f.info({taskId:n,planId:o.id,rulesExtracted:s.length,accuracy:i.overallAccuracy},"Task review and learning completed")}export{C as extractRulesFromDeviation,q as processTaskReview};
|
package/dist/logger-BEG4WFIM.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g}from"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{g as getComponentFilter,e as getLogLevel,c as getLogger,b as logger,a as onLogEvent,f as setComponentFilter,d as setLogLevel};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q}from"./chunk-HAWA62R2.js";import"./chunk-XNWZZYAV.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-FCV2DPZQ.js";export{o as DEFAULT_HYBRID_CONFIG,k as DEFAULT_SCORING_WEIGHTS,l as calculateRecency,m as calculateSmallvilleScore,p as cleanupMemories,f as countMemoriesByRole,a as createMemory,j as deleteMemory,b as getMemory,n as getRoleScoringWeights,g as listMemoriesByRole,e as markSuperseded,i as searchByBM25,h as searchByVector,q as searchHybrid,c as updateMemory,d as updateMemoryRetrievalCount};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c}from"./chunk-2GXYBWLS.js";import"./chunk-WZOMGJSY.js";import"./chunk-HAWA62R2.js";import"./chunk-XNWZZYAV.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{b as getRelevantMemoryContext,a as queryMemory,c as queryMemoryByTier};
|
package/dist/monitor-K7CGTLA6.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as a,d as b,e as c}from"./chunk-7SPKRIMZ.js";import"./chunk-B6S2AEOD.js";import"./chunk-IXF3XBGX.js";import"./chunk-AXMXXUPO.js";import"./chunk-L7426WNY.js";import"./chunk-XNWZZYAV.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{a as evaluateTaskCompletion,b as initMonitor,c as stopMonitor};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c}from"./chunk-NXTTKAQX.js";import"./chunk-PQ7KPALO.js";import"./chunk-FDWW245P.js";import"./chunk-L7JP7DUO.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{a as OutboundGateway,b as getOutboundGateway,c as isRecentlySent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b}from"./chunk-TN6H2WM2.js";import"./chunk-U36NBCR3.js";import"./chunk-XNWZZYAV.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{a as CHAT_MANAGER_ROLE_ID,b as initializeDefaultRoles};
|
package/dist/roles-SG2YAR64.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as a,e as b,f as c,g as d,h as e,i as f,j as g,l as h}from"./chunk-XNWZZYAV.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-FCV2DPZQ.js";h();export{b as createRole,g as deleteRole,c as getRole,d as getRoleByName,f as listRoles,e as updateRole,a as validateAdditionalDirectories};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p}from"./chunk-FUGJMHY4.js";import"./chunk-5ASEAZCR.js";import"./chunk-742NWPTQ.js";import"./chunk-WZOMGJSY.js";import"./chunk-L7JP7DUO.js";import"./chunk-HAWA62R2.js";import"./chunk-T25NLVMY.js";import"./chunk-ETQ7KC73.js";import"./chunk-FYDFMYUP.js";import"./chunk-XNWZZYAV.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{p as _resetForTest,e as archiveSession,b as createSession,g as deleteSession,c as getActiveSession,d as getSession,m as getTimeoutPollerInterval,i as incrementMessageCount,n as initSessionManager,j as listSessions,f as restoreSession,o as shutdownSessionManager,k as startTimeoutPoller,l as stopTimeoutPoller,h as touchSession,a as warmCache};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g}from"./chunk-VF6GJGD6.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-FCV2DPZQ.js";export{a as createTaskTemplate,g as deleteTaskTemplate,f as disableTaskTemplate,e as enableTaskTemplate,b as getTaskTemplate,d as listTaskTemplates,c as updateTaskTemplate};
|