adam-agent-server 1.9.0 → 1.10.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/dist/adam-tools-UJKLRMNR.js +1 -0
- package/dist/approval-handler-J6RUTICJ.js +1 -0
- package/dist/audit-manager-PFX36RMN.js +1 -0
- package/dist/bree-engine-445HR6VH.js +1 -0
- package/dist/channels-OOIM62BX.js +1 -0
- package/dist/{channels-ZNMTMMCY.js → channels-WFC26TED.js} +1 -1
- package/dist/{chunk-YKMWAVUH.js → chunk-2VBGTGDK.js} +8 -8
- package/dist/chunk-6JBSBSCL.js +1 -0
- package/dist/{chunk-6M2QCKAS.js → chunk-7T4B2MZ7.js} +1 -1
- package/dist/{chunk-UYOLAFUR.js → chunk-AMHO3ALG.js} +1 -1
- package/dist/{chunk-7F4SZXI2.js → chunk-AQO6IIHV.js} +13 -13
- package/dist/chunk-AVM3O74V.js +5 -0
- package/dist/{chunk-XTOOD44S.js → chunk-B44X7JAJ.js} +1 -1
- package/dist/{chunk-KUJFQDT5.js → chunk-B544JOZM.js} +2 -2
- package/dist/{chunk-VPZSOYE5.js → chunk-D5LZGIJU.js} +1 -1
- package/dist/{chunk-XIQVXRZH.js → chunk-ETK722ZZ.js} +4 -4
- package/dist/{chunk-MYVYH4PQ.js → chunk-ETOTUZPB.js} +1 -1
- package/dist/{chunk-TTP7QRAQ.js → chunk-FUWPDXXG.js} +1 -1
- package/dist/chunk-JRQQLKLU.js +145 -0
- package/dist/chunk-JYHOGBCP.js +12 -0
- package/dist/{chunk-3N7MGASP.js → chunk-MQWYGDNT.js} +1 -1
- package/dist/{chunk-W7U3ASGR.js → chunk-NPIXYK5G.js} +1 -1
- package/dist/chunk-O7XQSONJ.js +5 -0
- package/dist/{chunk-C2SD2NMZ.js → chunk-Q2ISNOBQ.js} +1 -1
- package/dist/{chunk-7WJF65TQ.js → chunk-QYRI4HYA.js} +1 -1
- package/dist/chunk-R2WB5BKF.js +7 -0
- package/dist/{chunk-6XVWIRR2.js → chunk-RMGBR3XZ.js} +1 -1
- package/dist/{chunk-3HZE5DQZ.js → chunk-SC2DDRYB.js} +1 -1
- package/dist/chunk-SZBWLHP6.js +80 -0
- package/dist/{chunk-YWUX3ZTO.js → chunk-U2LBBBWO.js} +1 -1
- package/dist/chunk-UXDTFTG5.js +10 -0
- package/dist/chunk-WQFNB2MQ.js +32 -0
- package/dist/chunk-X5V4VMET.js +26 -0
- package/dist/{chunk-IZ3WZHCM.js → chunk-Y5FFL6UO.js} +1 -1
- package/dist/{chunk-J4Y54LIC.js → chunk-Z434UGTC.js} +3 -3
- package/dist/{chunk-EJBGJLA2.js → chunk-ZFDULJGB.js} +1 -1
- package/dist/chunk-ZQ4PNKMQ.js +10 -0
- package/dist/cli.js +1 -1
- package/dist/{config-CILWJYZB.js → config-GKVOAMY2.js} +1 -1
- package/dist/{db-JO24ZLIN.js → db-FACSMWEY.js} +1 -1
- package/dist/delivery-log-JIQMHBJ5.js +1 -0
- package/dist/engine-OHYWUUMJ.js +1 -0
- package/dist/evolution-audit-M7FSYRQR.js +1 -0
- package/dist/index.js +21 -13
- package/dist/learner-OUNQSWN7.js +1 -0
- package/dist/{memories-LXH4VHCH.js → memories-ABE7PMQL.js} +1 -1
- package/dist/memory-extractor-ZX2NJIBV.js +6 -0
- package/dist/memory-service-UWER3T2S.js +1 -0
- package/dist/outbound-gateway-XDCGAXXW.js +1 -0
- package/dist/{presets-XR2OBXUP.js → presets-R3D4E6SK.js} +1 -1
- package/dist/{role-presets-DYWDEQYU.js → role-presets-7JIX34HF.js} +1 -1
- package/dist/role-workspace-ISGPO25D.js +1 -0
- package/dist/{roles-DRPLO4LY.js → roles-WNKRM6FD.js} +1 -1
- package/dist/session-manager-MTO4OGLM.js +1 -0
- package/dist/{task-templates-4DWXHLFZ.js → task-templates-SNKZJ3DI.js} +1 -1
- package/dist/workflow-executor-3OCSVMM5.js +1 -0
- package/package.json +1 -1
- package/dist/adam-tools-FSI5XKDL.js +0 -1
- package/dist/approval-handler-JYCGXQUE.js +0 -1
- package/dist/audit-manager-CLKTJPLM.js +0 -1
- package/dist/bree-engine-XJR5TKVC.js +0 -1
- package/dist/channels-DY2OW7YQ.js +0 -1
- package/dist/chunk-3IQADR6L.js +0 -144
- package/dist/chunk-56QP5ZHF.js +0 -79
- package/dist/chunk-ARQF52V6.js +0 -5
- package/dist/chunk-DKMF4B33.js +0 -5
- package/dist/chunk-KO7XBNPV.js +0 -12
- package/dist/chunk-LV4XLPCD.js +0 -26
- package/dist/chunk-OY2KVSIX.js +0 -7
- package/dist/chunk-PFYYS7CI.js +0 -10
- package/dist/chunk-QPIWPQWM.js +0 -29
- package/dist/chunk-UQDC3X6O.js +0 -10
- package/dist/delivery-log-QPQM5YU7.js +0 -1
- package/dist/engine-ZAPYG7G4.js +0 -1
- package/dist/evolution-audit-ZLYQ3ZYV.js +0 -1
- package/dist/learner-ACHENH6R.js +0 -1
- package/dist/memory-extractor-URH4YHK3.js +0 -6
- package/dist/memory-service-23P6VNKZ.js +0 -1
- package/dist/outbound-gateway-Y3P3T3VH.js +0 -1
- package/dist/role-workspace-LHW7AWPF.js +0 -1
- package/dist/session-manager-Z6K4U5X7.js +0 -1
- package/dist/workflow-executor-6ZMNL34C.js +0 -1
package/dist/chunk-56QP5ZHF.js
DELETED
|
@@ -1,79 +0,0 @@
|
|
|
1
|
-
import{j as we}from"./chunk-UYOLAFUR.js";import{a as ct,c as pt,d as gt,e as ht}from"./chunk-KO7XBNPV.js";import{b as lt,c as be,e as dt}from"./chunk-6M2QCKAS.js";import{a as mt,c as Ie,e as ft}from"./chunk-W7U3ASGR.js";import{g as ut}from"./chunk-LV4XLPCD.js";import{a as j,b as Ze,c as Xe,d as et,e as tt,f as nt,h as rt,i as re,j as F,k as oe,l as ot,m as it,n as B,o as at,p as $,q as ye}from"./chunk-YKMWAVUH.js";import{a as Ke,b as ze,c as te,d as Je,e as He,f as Ye,g as Bt,h as Qe,i as C,k as ne}from"./chunk-C2SD2NMZ.js";import{a as st}from"./chunk-S6OV7Z6K.js";import{b as Ue}from"./chunk-DKMF4B33.js";import{b as P,c as W,d as U}from"./chunk-OY2KVSIX.js";import{d as ve}from"./chunk-IZ3WZHCM.js";import{f as Be}from"./chunk-MYVYH4PQ.js";import{e as me,f as X,g as Fe,i as fe,j as ee}from"./chunk-6XVWIRR2.js";import{a as K}from"./chunk-L7JP7DUO.js";import{c as ge,d as q,e as Ge,h as Ve,i as he,j as We}from"./chunk-VPZSOYE5.js";import{d as R,j as Me}from"./chunk-OFTIPZTH.js";import{f as Le,g as ue,i as Wt,k as qe,l as I,n as L,o as A,p as je,q as pe,r as Z}from"./chunk-YWUX3ZTO.js";import{b as D,d as Oe}from"./chunk-7F4SZXI2.js";import{d as ce,h as Vt}from"./chunk-WBAPIPST.js";import{c as w,d as Ne,h as O}from"./chunk-MRTJFYPR.js";import{f as x}from"./chunk-FCV2DPZQ.js";import{createSdkMcpServer as bn,tool as u}from"@anthropic-ai/claude-agent-sdk";import{z as n}from"zod";Z();ee();import{v4 as z}from"uuid";O();var Kt=w("goal-manager");async function wr(e){let t;try{let o=JSON.parse(e);t={name:o.name??"",description:o.description,metric:o.metric??"",targetValue:o.targetValue??0,currentValue:o.currentValue??0,deadline:o.deadline??0,budget:o.budget??0,roleId:o.roleId??"engineer",status:"active"}}catch{t=await zt(e)}let r=Jt(t);return{goalState:t,validationResult:r,rawInput:e}}async function zt(e){let t=`Extract SMART goal fields from this natural language input.
|
|
2
|
-
|
|
3
|
-
Input: "${e}"
|
|
4
|
-
|
|
5
|
-
Respond ONLY with a JSON object:
|
|
6
|
-
{
|
|
7
|
-
"name": "short goal name (max 100 chars)",
|
|
8
|
-
"description": "detailed description of what the goal aims to achieve",
|
|
9
|
-
"metric": "measurable metric name (e.g. completion, reports_written, accuracy_score)",
|
|
10
|
-
"targetValue": <number, the target to reach>,
|
|
11
|
-
"deadline_days": <number, days from now to complete>,
|
|
12
|
-
"budget": <number, estimated budget in USD>,
|
|
13
|
-
"role": "<best matching role: engineer | analyst | content_creator | reviewer>"
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
Rules:
|
|
17
|
-
- name: concise, actionable title
|
|
18
|
-
- metric: quantifiable measure of success; use "completion" if the goal is binary (done/not done)
|
|
19
|
-
- targetValue: realistic target for the metric; use 1 for binary goals
|
|
20
|
-
- deadline_days: reasonable timeframe; default 7 if unclear
|
|
21
|
-
- budget: estimated cost in USD; default 5 if unclear
|
|
22
|
-
- role: match to the nature of work (research=analyst, writing=content_creator, coding=engineer, review=reviewer)`;try{let o=(await st(t,"You extract structured SMART goal fields from natural language. Reply with only valid JSON.")).match(/\{[\s\S]*\}/);if(o){let i=JSON.parse(o[0]),a=i.deadline_days??7;return{name:(i.name??e.slice(0,100)).slice(0,100),description:i.description??e,metric:i.metric??"completion",targetValue:i.targetValue??1,currentValue:0,deadline:Date.now()+a*24*60*60*1e3,budget:i.budget??5,roleId:i.roleId??"engineer",status:"active"}}}catch(r){Kt.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 Jt(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 Ir(e,t,r){let o=z(),i=Date.now(),a={id:o,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:i,deliverTo:t,reportTo:r};return re(a),a}function yt(e,t){let r=Date.now(),o=[],i={id:z(),goalId:e,level:"L0",name:`${t}_goal_progress`,description:`Goal-level ${t} progress (monthly)`,weight:1,calibrationFactor:1,createdAt:r};o.push(i),B(i);let a={id:z(),goalId:e,level:"L1",parentId:i.id,name:`${t}_weekly_trend`,description:`Weekly trend for ${t}`,weight:.8,calibrationFactor:1,createdAt:r};o.push(a),B(a);let l={id:z(),goalId:e,level:"L2",parentId:a.id,name:`${t}_daily_process`,description:`Daily process metric for ${t}`,weight:.6,calibrationFactor:1,createdAt:r};o.push(l),B(l);let d={id:z(),goalId:e,level:"L3",parentId:l.id,name:`${t}_per_task`,description:`Per-task instant metric for ${t}`,weight:.4,calibrationFactor:1,createdAt:r};return o.push(d),B(d),o}var Ht=3,Yt=2,ie=class{static async generateVariants(t,r,o=Ht,i=Yt){let a=$.getTopStrategies(t,r,o);if(a.length===0){let d=`baseline-${r}-v1`;return $.addStrategy(t,r,d,this.generateBaselinePrompt(t,r)),[d]}let l=[];for(let d=0;d<i;d++){let m=a[0].totalTrials+d+1,c=`${r}-evolved-v${m}`,h=a[0].promptTemplate,f=this.mutateTemplate(h);$.addStrategy(t,r,c,f),l.push(c)}return l}static generateBaselinePrompt(t,r){return`You are a ${t} agent specializing in ${r}.
|
|
23
|
-
|
|
24
|
-
## Core Focus
|
|
25
|
-
Complete tasks with high quality.
|
|
26
|
-
|
|
27
|
-
## Approach
|
|
28
|
-
1. Understand the task requirements thoroughly
|
|
29
|
-
2. Plan your approach before executing
|
|
30
|
-
3. Execute systematically, checking your work
|
|
31
|
-
4. Verify completion against requirements`}static mutateTemplate(t){let r=[this.addProcessEmphasis(),this.addQualityFocus(),this.addVerificationStep()],o=r[Math.floor(Math.random()*r.length)];return`${t}
|
|
32
|
-
|
|
33
|
-
## Evolution
|
|
34
|
-
${o}`}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,o){return{promptTemplate:this.generateBaselinePrompt(t,r),rationale:"Generated baseline - LLM integration in Phase 5"}}};O();Qe();import{v4 as T}from"uuid";import{spawnSync as bt}from"child_process";import{createRequire as Qt}from"module";import{dirname as Zt,join as vt}from"path";import{openSync as Xt,readFileSync as en,unlinkSync as tn}from"fs";var nn=3e4,wt=12e4;function It(){let t=Qt(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk");return vt(Zt(t),"cli.js")}function M(e,t){let r=It(),o=t?.timeout??nn;if(t?.json){let a=vt("/tmp",`adam-cli-stdout-${process.pid}-${Date.now()}.txt`),l=Xt(a,"w");try{let d=bt("node",[r,...e],{cwd:t.cwd,timeout:o,stdio:["ignore",l,"pipe"],encoding:"utf-8"});if(d.status!==0)throw new Error(d.stderr?.trim()||`CLI exited with status ${d.status}`);return en(a,"utf-8")}finally{try{tn(a)}catch{}}}let i=bt("node",[r,...e],{cwd:t?.cwd,timeout:o,encoding:"utf-8"});if(i.status!==0)throw new Error(i.stderr?.trim()||`CLI exited with status ${i.status}`);return i.stdout}function kt(){let e=M(["plugin","list","--available","--json"],{json:!0});return JSON.parse(e)}function ke(e,t="user",r){return M(["plugin","install",e,"--scope",t],{cwd:r,timeout:wt})}function Te(e,t,r){let o=["plugin","uninstall",e];return t&&o.push("--scope",t),M(o,{cwd:r,timeout:wt})}function Tt(e,t){return M(["plugin","enable",e])}function St(e,t){return M(["plugin","disable",e])}function Cr(e){return M(["plugin","marketplace","add",e])}function xr(e){return M(["plugin","marketplace","remove",e])}function Pr(){try{return!!It()}catch{return!1}}Oe();import{v4 as on}from"uuid";function sn(e){return{id:e.id,eventDefId:e.event_def_id??void 0,occurredAt:e.occurred_at,ingestedAt:e.ingested_at,userDay:e.user_day??void 0,source:e.source,type:e.type,payload:JSON.parse(e.payload),confidence:e.confidence,dedupKey:e.dedup_key,relatedEntities:e.related_entities??void 0,trustLevel:e.trust_level}}function _t(e){let t=D(),r=e.id??on(),o=new Date().toISOString();return t.prepare(`
|
|
35
|
-
INSERT OR IGNORE INTO events
|
|
36
|
-
(id, event_def_id, occurred_at, ingested_at, user_day, source, type, payload, confidence, dedup_key, related_entities, trust_level)
|
|
37
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
38
|
-
`).run(r,e.eventDefId??null,e.occurredAt??o,o,e.userDay??null,e.source,e.type,JSON.stringify(e.payload),e.confidence??1,e.dedupKey,e.relatedEntities??null,e.trustLevel??"trusted").changes===0?{inserted:!1,id:t.prepare("SELECT id FROM events WHERE source = ? AND dedup_key = ?").get(e.source,e.dedupKey)?.id??r}:{inserted:!0,id:r}}function Rt(e={}){let t=D(),r="SELECT * FROM events WHERE 1=1",o=[];e.eventDefId!==void 0&&(r+=" AND event_def_id = ?",o.push(e.eventDefId)),e.typePattern!==void 0&&(r+=" AND type LIKE ?",o.push(e.typePattern)),e.since!==void 0&&(r+=" AND occurred_at >= ?",o.push(e.since)),e.until!==void 0&&(r+=" AND occurred_at <= ?",o.push(e.until)),r+=" ORDER BY occurred_at DESC";let i=Math.min(e.limit??50,500);return r+=` LIMIT ${i}`,e.offset!==void 0&&(r+=` OFFSET ${e.offset}`),t.prepare(r).all(...o).map(sn)}Oe();function Dt(e){return{id:e.id,name:e.name,sourceType:e.source_type,sourceConfig:JSON.parse(e.source_config),enabled:e.enabled===1,description:e.description??void 0,createdAt:e.created_at,updatedAt:e.updated_at}}function Et(e){let t=D(),r=Date.now();return t.prepare(`
|
|
39
|
-
INSERT INTO event_defs (id, name, source_type, source_config, enabled, description, created_at, updated_at)
|
|
40
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
41
|
-
`).run(e.id,e.name,e.sourceType,JSON.stringify(e.sourceConfig),e.enabled?1:0,e.description??null,r,r),{...e,createdAt:r,updatedAt:r}}function G(e){let r=D().prepare("SELECT * FROM event_defs WHERE id = ?").get(e);return r?Dt(r):void 0}function se(e={}){let t=D(),r="SELECT * FROM event_defs WHERE 1=1",o=[];return e.sourceType!==void 0&&(r+=" AND source_type = ?",o.push(e.sourceType)),e.enabled!==void 0&&(r+=" AND enabled = ?",o.push(e.enabled?1:0)),r+=" ORDER BY created_at DESC",t.prepare(r).all(...o).map(Dt)}function Se(e,t){let r=D(),o=G(e);if(!o)return;let i={...o,...t,updatedAt:Date.now()};return r.prepare(`
|
|
42
|
-
UPDATE event_defs
|
|
43
|
-
SET name = ?, source_type = ?, source_config = ?, enabled = ?, description = ?, updated_at = ?
|
|
44
|
-
WHERE id = ?
|
|
45
|
-
`).run(i.name,i.sourceType,JSON.stringify(i.sourceConfig),i.enabled?1:0,i.description??null,i.updatedAt,e),i}function _e(e){return D().prepare("DELETE FROM event_defs WHERE id = ?").run(e).changes>0}import{CronExpressionParser as an}from"cron-parser";import{v4 as ln}from"uuid";function N(e){let{emitPayload:t,...r}=e,o=_t(r);return o.inserted?(e.eventDefId&&K.emit({type:"event_fired",eventDefId:e.eventDefId,eventId:o.id,payload:t??e.payload}),{inserted:!0,id:o.id}):{inserted:!1,id:o.id}}O();var Ct=w("scheduler"),ae=new Map;function xt(e,t){let r=t.next(),o=Math.max(r.getTime()-Date.now(),1e3),i=setTimeout(async()=>{try{let a=ln(),l=e.sourceConfig.payload_template??{},d={triggered_at:new Date().toISOString(),...l};N({id:a,eventDefId:e.id,type:"scheduler.tick",source:"adam-internal",dedupKey:`cron-${e.id}-${Date.now()}`,payload:d,occurredAt:new Date().toISOString(),trustLevel:"trusted"})}catch(a){Ct.error({defId:e.id,err:a},"cron handler failed")}ae.has(e.id)&&xt(e,t)},o);ae.set(e.id,i)}function Pt(e){if(!e.enabled)return;let t=an.parse(e.sourceConfig.cron);xt(e,t),Ct.info({defId:e.id,defName:e.name},"Cron source started")}function At(e){let t=ae.get(e);t&&(clearTimeout(t),ae.delete(e))}Vt();import{watch as dn}from"fs";import{statSync as cn,realpathSync as un}from"fs";import{homedir as pn}from"os";import{join as $t,extname as mn}from"path";import{createHash as fn}from"crypto";O();var J=w("scheduler"),Re=new Map;function gn(e){let t;try{t=un(e)}catch{throw new Error(`Watch path does not exist: ${e}`)}let r=pn();if(!t.startsWith(r)&&!t.startsWith(ce))throw new Error(`Watch path must be within ${r} or ${ce}: ${e}`)}function Mt(e){if(!e.enabled)return;let t=e.sourceConfig;gn(t.path);let r=t.stability_delay_ms??5e3,o=t.glob,i={watcher:null,stopped:!1,stabilityTimer:null,pendingEvents:new Map},a=(l,d)=>{if(!l||i.stopped||o&&!hn(l,o))return;let m=$t(t.path,l),c=0,h=Date.now();try{let f=cn(m);c=f.size,h=f.mtimeMs}catch{return}i.pendingEvents.set(l,{mtime:h,size:c}),i.stabilityTimer&&clearTimeout(i.stabilityTimer),i.stabilityTimer=setTimeout(()=>{if(!i.stopped){for(let[f,g]of i.pendingEvents)try{let b=$t(t.path,f),S=fn("sha256").update(`dir-${e.id}-${b}-${g.mtime}`).digest("hex").slice(0,16);N({id:S,eventDefId:e.id,type:"filesystem.file.created",source:`dir-${e.id}`,dedupKey:`dir-${e.id}-${b}-${g.mtime}`,payload:{file_path:b,mtime:g.mtime,size:g.size},occurredAt:new Date(g.mtime).toISOString(),trustLevel:"trusted"})}catch(b){J.warn({file:f,err:b},"Failed to fire directory watch event")}i.pendingEvents.clear()}},r)};try{i.watcher=dn(t.path,{persistent:!1},(l,d)=>{a(d,l)}),i.watcher.on("error",l=>{J.warn({defId:e.id,err:l},"fs.watch error, removing watcher"),De(e.id)}),Re.set(e.id,i),J.info({defId:e.id,defName:e.name,path:t.path},"Directory watch started")}catch(l){throw J.error({defId:e.id,err:l},"Failed to start directory watch"),l}}function De(e){let t=Re.get(e);if(t){t.stopped=!0,t.stabilityTimer&&clearTimeout(t.stabilityTimer);try{t.watcher.close()}catch{}Re.delete(e),J.info({defId:e},"Directory watch stopped")}}function hn(e,t){if(t.startsWith("*.")){let r=t.slice(1);return mn(e)===r}return e===t}import{v4 as Nt}from"uuid";function Ee(e,t){if(!e.enabled)throw new Error(`Event def '${e.id}' is disabled`);let r=Nt();return N({id:r,eventDefId:e.id,type:"manual.fire",source:"manual",dedupKey:`manual-${e.id}-${Date.now()}`,payload:t??{},occurredAt:new Date().toISOString(),trustLevel:"trusted"}),{eventId:r}}function Ce(e,t){let r=Nt(),o=Date.now(),i=Math.random().toString(36).slice(2,10);return N({id:r,eventDefId:e.id,type:"manual.test.fire",source:`manual-test-${e.id}`,dedupKey:`manual-test-${e.id}-${o}-${i}`,payload:t??{},occurredAt:new Date().toISOString(),trustLevel:"trusted"}),{eventId:r}}O();var xe=w("scheduler");function Pe(e){if(e.enabled)switch(e.sourceType){case"cron":Pt(e);break;case"directory_watch":Mt(e);break;case"webhook":break;case"manual":break;default:xe.warn({defId:e.id,sourceType:e.sourceType},"Unknown source type, skipping")}}function le(e,t){switch(t){case"cron":At(e);break;case"directory_watch":De(e);break;case"webhook":case"manual":break;default:xe.warn({defId:e,sourceType:t},"Unknown source type, nothing to stop")}}async function lo(){let e=se({});for(let t of e)t.enabled&&le(t.id,t.sourceType);xe.info("All event source handlers stopped")}import{z as k}from"zod/v4";var Ot={webhook:k.object({}).strict(),manual:k.object({}).strict(),cron:k.object({cron:k.string().min(1,"cron expression required"),payload_template:k.record(k.string(),k.unknown()).optional()}).strict(),directory_watch:k.object({path:k.string().min(1,"watch path required"),glob:k.string().optional(),stability_delay_ms:k.number().int().positive().optional()}).strict()};function H(){return Object.keys(Ot)}function yn(e){return Ot[e]}function Ae(e,t){let r=yn(e);if(!r)return{ok:!1,error:`Unknown sourceType: '${e}'. Known: ${H().join(", ")}`};let o=r.safeParse(t??{});return o.success?{ok:!0,data:o.data}:{ok:!1,error:k.prettifyError(o.error)}}O();import*as Ut from"crypto";var Y=w("api"),Q=class{cancelTask(t){let r=P(t);r&&(W(t,{status:"cancelled",completedAt:Date.now()}),K.emit({type:"task_status_change",taskId:t,oldStatus:r.status,newStatus:"cancelled"}),Y.debug({taskId:t,oldStatus:r.status},"Task cancelled"))}resolveApproval(t,r,o){return Y.debug({approvalId:t,action:r,reason:o},"Approval resolved (no-op in Pure C)"),!0}resolvePlanApproval(t,r,o,i){let a=lt(t);if(!a)return Y.warn({planId:t},"Plan not found or already resolved"),!1;let l=P(a.taskId);return l?(dt(t,r==="allow"?"approved":"denied",o),r==="allow"&&o==="permanent"&&ct({id:Ut.randomUUID(),roleId:a.roleId,taskPattern:l.prompt.slice(0,100).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),maxRiskLevel:a.plan.overallRisk,createdAt:Date.now(),createdByTaskId:l.id}),K.emit({type:"plan_approval_decision",taskId:l.id,planId:t,decision:r,approvalType:o,reason:i}),Y.debug({planId:t,decision:r,approvalType:o},"Plan approval resolved"),!0):(Y.warn({planId:t},"Task not found for plan"),!1)}};import{existsSync as Lt}from"fs";Wt();var V=w("manager");function s(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}function vn(e){let t=e.parameters?Object.entries(e.parameters).map(([o,i])=>`- ${o}: ${i.description}`).join(`
|
|
46
|
-
`):"",r=t?`
|
|
47
|
-
## Inputs
|
|
48
|
-
${t}
|
|
49
|
-
`:"";return`---
|
|
50
|
-
description: ${e.description}
|
|
51
|
-
---
|
|
52
|
-
# ${e.skillName}
|
|
53
|
-
${r}
|
|
54
|
-
## Instructions
|
|
55
|
-
${e.instructions}
|
|
56
|
-
`}async function _(e){let{listChannels:t}=await import("./channels-ZNMTMMCY.js"),r=t(),{listSessions:o}=await import("./session-manager-Z6K4U5X7.js"),i=[...o("active"),...o("archived")],a=[];for(let l of e)if(l.type==="session"&&l.sessionId)a.push({type:"session",sessionId:l.sessionId});else if(l.type==="channel"){let d=l.channelId,m=l.chatId;if(!d&&l.channelName){let c=r.find(h=>h.name.toLowerCase().includes(l.channelName.toLowerCase()));c&&(d=c.id)}if(d&&!m){let c=i.find(h=>h.source.type==="channel"&&h.source.channelId===d&&h.source.chatId);c?.source.chatId?m=c.source.chatId:m=r.find(f=>f.id===d)?.config?.userId}d&&m?a.push({type:"channel",channelId:d,chatId:m}):V.warn({channelName:l.channelName,channelId:d,chatId:m},"Could not resolve channel notify target")}return a}async function wn(e){let{listRoles:t}=await import("./roles-DRPLO4LY.js"),r=t(void 0,100,0);for(let o of r)if(o.name.toLowerCase().includes(e.toLowerCase()))return o.id}var In={goalId:n.string()},kn={goalId:n.string(),status:n.string().optional(),currentValue:n.number().optional(),budgetUsd:n.number().optional(),notes:n.string().optional()},Tn={goalId:n.string(),goalDescription:n.string(),maxSubtasks:n.number().optional()},E=n.union([n.object({type:n.literal("session"),sessionId:n.string()}),n.object({type:n.literal("channel"),channelName:n.string()}),n.object({type:n.literal("channel"),channelId:n.string(),chatId:n.string().optional()})]),Sn={prompt:n.string(),roleId:n.string().optional().describe("Role ID. Call list_roles(requirements) first to find the best role for the task."),requirements:j.optional(),autoSelectRole:n.boolean().optional(),deliverTo:n.array(E).optional().describe('Where to deliver the task output (result full text). E.g., send result to a specific channel. e.g., [{type:"channel", channelName:"iPad WeChat"}] when user says "\u53D1\u5230 iPad \u5FAE\u4FE1".'),reportTo:n.array(E).optional().describe("Where to send status reports (completion summary). Defaults to the originating channel/session."),toolOverrides:n.object({allowedTools:n.array(n.string()).optional(),disallowedTools:n.array(n.string()).optional()}).optional()},_n={taskId:n.string(),goalId:n.string().optional(),strategyId:n.string().optional()},Rn={roleId:n.string(),taskType:n.string(),name:n.string().optional()},Dn={status:n.string().optional(),limit:n.number().optional()},En={taskId:n.string(),roleId:n.string()},Cn={taskId:n.string().optional(),status:n.string().optional(),limit:n.number().optional()},xn={roleId:n.string(),allowedTools:n.array(n.string()).optional(),disallowedTools:n.array(n.string()).optional(),osCapabilities:n.array(n.object({id:n.string().min(1),targets:n.array(n.string().min(1)).optional()})).optional().describe("Role-level OS capability grants. Use get_capabilities to inspect the runtime registry and valid target-scoped entries."),additionalDirectories:n.array(n.object({path:n.string(),mode:n.enum(["ro","rw"]).optional().describe("Read-only or read-write access. Default: rw. Enforced by OS sandbox."),inheritPlugins:n.boolean().optional(),inheritMcp:n.boolean().optional(),inheritPermissions:n.boolean().optional()})).optional(),allowedChannels:n.array(n.string()).optional(),inheritUserSettings:n.boolean().optional().describe("Enable/disable inheriting user-level settings (global plugins, MCP servers). Default: false (isolated).")},Pn={roleId:n.string().describe("Role ID to update."),name:n.string().min(1).optional(),cagPrompt:n.string().optional(),learnedRules:n.array(n.string()).optional(),status:n.enum(["active","inactive","retired"]).optional(),executionMode:n.enum(["isolated","inline"]).optional(),model:n.string().optional(),maxBudgetUsd:n.number().optional(),approvalRequired:n.array(n.string()).optional(),preferences:n.object({model:n.string().optional(),effort:n.enum(["low","medium","high","max"]).optional(),maxTurns:n.number().optional()}).optional(),permissionMode:n.enum(["default","acceptEdits","dontAsk","bypassPermissions","plan","auto"]).optional(),allowedBashPatterns:n.array(n.string()).optional(),deniedBashPatterns:n.array(n.string()).optional(),evaluationCriteria:n.record(n.string(),n.number()).optional(),envVars:n.record(n.string(),n.string()).optional()},An={roleId:n.string().optional(),limit:n.number().optional()},$n={name:n.string(),cagPrompt:n.string(),traits:n.array(n.string()).optional(),allowedTools:n.array(n.string()).optional(),disallowedTools:n.array(n.string()).optional(),osCapabilities:n.array(n.object({id:n.string().min(1),targets:n.array(n.string().min(1)).optional()})).optional().describe("Initial Role-level OS capability grants. Use get_capabilities to discover editable capability ids and target rules."),additionalDirectories:n.array(n.object({path:n.string(),mode:n.enum(["ro","rw"]).optional().describe("Read-only or read-write access. Default: rw. Enforced by OS sandbox."),inheritPlugins:n.boolean().optional(),inheritMcp:n.boolean().optional(),inheritPermissions:n.boolean().optional()})).optional()},Mn={roleId:n.string(),reason:n.string().optional()},Nn={name:n.string(),description:n.string().optional(),roleId:n.string().optional(),metric:n.string().optional(),targetValue:n.number().optional(),deadline:n.number().optional(),budgetUsd:n.number().optional(),deliverTo:n.array(E).optional().describe("Where to deliver goal completion notifications.")},On={name:n.string(),description:n.string().optional(),triggerType:n.enum(["cron","template_complete","workflow_complete","event"]),triggerCron:n.string().optional(),triggerEvent:n.string().optional().describe("For triggerType=template_complete: 'template_complete:<templateId>'. For workflow_complete: 'workflow_complete:<templateId>'. For cron/event: unused."),eventDefId:n.string().uuid().optional().describe("Required when triggerType='event'. Event def to bind this template to. Use list_event_defs to find or create_event_def to create one."),prompt:n.string(),roleId:n.string().optional(),requirements:j.optional(),autoSelectRole:n.boolean().optional(),enabled:n.boolean().optional(),goalIds:n.array(n.string()).optional(),deliverTo:n.array(E).optional().describe("Where to deliver the task output (result full text)."),reportTo:n.array(E).optional().describe("Where to send status reports (completion summary).")},Un={status:n.enum(["active","retired","probation"]).optional(),limit:n.number().optional(),requirements:j.optional()},Ln={enabled:n.boolean().optional()},qn={},jn={},Fn={prompt:n.string().describe("The task prompt to execute after the delay"),delayMinutes:n.number().optional().describe("Minutes from now to execute (e.g., 30 for 'half an hour later')"),runAt:n.string().optional().describe("ISO 8601 timestamp to execute at (e.g., '2026-04-01T15:00:00+08:00')"),roleId:n.string().describe("Role ID to assign the task to. Call list_roles first."),deliverTo:n.array(E).optional().describe("Where to deliver the task output (result full text)."),reportTo:n.array(E).optional().describe("Where to send status reports (completion summary).")},Gn={roleId:n.string().optional().describe("If provided, shows which plugins are installed in that role's workspace.")},Vn={roleId:n.string().describe("Role ID to install the plugin under (project-scope)."),pluginId:n.string().describe("Plugin ID (e.g. 'github@anthropic'). Use list_available_plugins to discover available plugins.")},Wn={roleId:n.string().describe("Role ID to uninstall the plugin from."),pluginId:n.string().describe("Plugin ID to uninstall.")},Bn={roleId:n.string().describe("Role ID to bind the MCP server to."),mcpName:n.string().describe("Name for this MCP server (e.g., 'github', 'filesystem')."),mcpConfig:n.record(n.string(),n.unknown()).describe("MCP server configuration object.")},Kn={roleId:n.string().describe("Role ID to unbind the MCP server from."),mcpName:n.string().describe("Name of the MCP server to remove.")},zn={pluginId:n.string().describe("Plugin ID (e.g., 'github@anthropic').")},Jn={pluginId:n.string().describe("Plugin ID (e.g., 'github@anthropic').")},Hn={pluginId:n.string().describe("Plugin ID (e.g., 'github@anthropic').")},Yn={pluginId:n.string().describe("Plugin ID (e.g., 'github@anthropic').")},Qn={},Zn={},Xn={pluginId:n.string().describe("Plugin ID (e.g., 'github@anthropic').")},er={roleId:n.string().describe("Role ID to associate scanned plugins with."),path:n.string().describe("Directory path to scan for .claude/settings.json.")},tr={taskId:n.string().describe("Task ID to cancel.")},nr={taskId:n.string().describe("Task ID to get logs for."),limit:n.number().optional().describe("Max log entries (default 20).")},rr={roleId:n.string().describe("Role ID to delete.")},or={},ir={updates:n.record(n.string(),n.unknown()).describe("Config key-value pairs to update. Example: { 'defaults.maxTurns': 50, 'logging.level': 'debug' }")},sr={roleId:n.string().describe("Role ID to list memories for."),limit:n.number().optional().describe("Max results (default 20).")},ar={templateId:n.string().describe("Template ID to update."),name:n.string().optional(),enabled:n.boolean().optional(),prompt:n.string().optional(),triggerType:n.enum(["cron","template_complete","workflow_complete","event"]).optional().describe("Explicit trigger type. Required when updating trigger settings."),triggerCron:n.string().optional(),triggerEvent:n.string().optional().describe("For template_complete: 'template_complete:<templateId>'. For workflow_complete: 'workflow_complete:<templateId>'. Unused for cron/event."),eventDefId:n.string().uuid().optional().describe("Required when triggerType='event'. The event def UUID to bind this template to."),roleId:n.string().optional(),autoSelectRole:n.boolean().optional().describe("Step-level: if true, Adam picks the best-fit role at dispatch time. Write to the single-step template's step."),requirements:j.optional().describe("Step-level: required when autoSelectRole=true. Fields: tools, paths, osCapabilities, network, plugins.")},lr={templateId:n.string().describe("Template ID to delete. Obtain from list_templates."),mode:n.enum(["template_only","with_tasks"]).describe("REQUIRED. Deletion mode chosen by the user after you presented the dependent counts. 'template_only' removes the template + workflow_executions but keeps tasks as orphaned history records under the Tasks tab. 'with_tasks' additionally deletes every task created by this template and their role_scores + manager_decisions (chat_messages.task_id nulled). NEVER guess this value \u2014 the user must explicitly confirm which mode.")},dr={templateId:n.string().describe("Template ID to inspect.")},cr={templateId:n.string().describe("Template ID to run immediately.")},ur={enabled:n.boolean().optional().describe("Filter by enabled status.")},pr={eventType:n.string().describe("Event type that triggers this rule (e.g., 'task_complete')."),channelId:n.string().describe("Channel ID to deliver to."),format:n.string().optional().describe("Format template (e.g., 'summary', 'full'). Default: 'summary'."),matchCriteria:n.record(n.string(),n.unknown()).optional().describe("JSON match criteria for event fields."),enabled:n.boolean().optional().describe("Enable this rule immediately (default true).")},mr={ruleId:n.string().describe("Delivery rule ID to delete.")},fr={roleId:n.string().optional().describe("Role ID to filter strategies by.")},qt=[u("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.",In,async e=>{let t=F(e.goalId);if(!t)return s({error:"Goal not found"});let r=Date.now(),o=t.targetValue>0?t.currentValue/t.targetValue:0;return s({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:o,timeRemainingMs:Math.max(0,t.deadline-r),budgetRemainingUsd:t.budgetUsd})}),u("update_goal_state","Update a goal's status, current value, or budget.",kn,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(),oe(e.goalId,t)),s({success:!0})}),u("decompose_goal","Decompose a goal into actionable subtasks using LLM reasoning.",Tn,async e=>{let t=R(),r=Math.min(e.maxSubtasks??5,10);try{let{query:a}=await import("@anthropic-ai/claude-agent-sdk"),l=`Decompose this goal into ${r} actionable subtasks.
|
|
57
|
-
|
|
58
|
-
Goal: ${e.goalDescription}
|
|
59
|
-
|
|
60
|
-
Respond ONLY with a JSON array. Each item:
|
|
61
|
-
{
|
|
62
|
-
"description": "...",
|
|
63
|
-
"prompt": "detailed task instruction",
|
|
64
|
-
"complexity": "low|medium|high",
|
|
65
|
-
"role": "engineer|analyst|content_creator|reviewer",
|
|
66
|
-
"requirements": {
|
|
67
|
-
"tools": ["Read", "Write"],
|
|
68
|
-
"paths": [{"path": "/abs/path", "access": "ro"}],
|
|
69
|
-
"osCapabilities": [{"id": "automation", "targets": ["bundle.id"]}],
|
|
70
|
-
"network": false
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
Rules:
|
|
75
|
-
- Each subtask must be independently executable
|
|
76
|
-
- Order from foundational to dependent
|
|
77
|
-
- Be specific about what each subtask should accomplish
|
|
78
|
-
- For each subtask, specify the best role from: 'engineer', 'analyst', 'content_creator', 'reviewer'. Match role to the nature of the work.
|
|
79
|
-
- Include tools and paths required for the subtask where known. If unknown, omit the field.`,d=a({prompt:l,options:{cwd:process.cwd(),maxTurns:1,maxBudgetUsd:.02}}),m="";for await(let h of d){let f=h;f.type==="result"&&typeof f.result=="string"&&(m=f.result)}let c=m.match(/\[[\s\S]*\]/);if(c){let h=JSON.parse(c[0]),f=[];for(let g=0;g<Math.min(h.length,r);g++){let b=h[g],S=b.role,p=S?await wn(S):void 0,y=await ye({prompt:b.prompt,roleId:p,requirements:b.requirements,config:t.defaults});if(!y.ok){f.push({id:`admission-failed-${g}`,description:b.description,prompt:b.prompt,dependencies:g>0&&f.length>0?[f[g-1].id]:[],estimatedComplexity:b.complexity??"medium",role:S,admissionError:`${y.code}: ${y.reason}`});continue}f.push({id:y.taskId,description:b.description,prompt:b.prompt,dependencies:g>0?[f[g-1].id]:[],estimatedComplexity:b.complexity??"medium",role:S})}if(f.length>0)return s({subtasks:f})}}catch(a){V.error({error:a},"LLM decomposition failed, using fallback")}let o=await nt({taskId:T(),roleId:void 0,autoSelectRole:!1}),i=[];return o.ok||i.push({id:"admission-blocked",description:`Decomposition fallback blocked: ${o.reason}`,prompt:e.goalDescription,dependencies:[],estimatedComplexity:"medium",admissionError:`${o.code}: ${o.reason}`}),s({subtasks:i})}),u("dispatch_task","Create and dispatch a task. Workflow: (1) call list_roles(requirements) to find candidate roles by fit; (2) call dispatch_task with requirements AND the chosen roleId. requirements is STRONGLY RECOMMENDED \u2014 when present, admission validates role fit before creation and returns structured mismatch diagnostics. If you cannot produce clear requirements from the user's message, ASK THE USER instead of dispatching. Pass deliverTo (result delivery) and/or reportTo (status reports) to route output when the task completes.",Sn,async e=>{if(!e.roleId&&!e.autoSelectRole){let i=A("active",20,0).filter(a=>a.source!=="system").map(a=>({id:a.id,name:a.name,allowedTools:a.allowedTools??[],capabilitySummary:C(a)}));return s({error:"Must provide roleId or autoSelectRole=true with requirements.",availableRoles:i})}let t=e.deliverTo?await _(e.deliverTo):void 0,r=e.reportTo?await _(e.reportTo):void 0,o=await ye({prompt:e.prompt,roleId:e.roleId,requirements:e.requirements,autoSelectRole:e.autoSelectRole,deliverTo:t,reportTo:r,toolOverrides:e.toolOverrides});if(!o.ok){let i=(o.candidates??[]).map(l=>({id:l.roleId,name:l.name,fitScore:l.fitScore,missing:l.missing})),a=i.length>0?i:A("active",20,0).filter(l=>l.source!=="system").map(l=>({id:l.id,name:l.name,allowedTools:l.allowedTools??[],capabilitySummary:C(l)}));return s({error:o.reason,code:o.code,missing:o.missing,availableRoles:a})}return s({taskId:o.taskId,roleId:o.roleId,fitScore:o.fitScore,strategyId:o.strategyId,warnings:o.warnings})}),u("dispatch_workflow","Create and execute a multi-role workflow. Use when the user's request decomposes into sequential or parallel steps handled by different roles. Each step is a complete task; roles handle conditions and decisions internally. Use {{stepId.result}} in prompts to reference prior step outputs. Minimum 2 steps.",{steps:n.array(n.object({id:n.string().describe("Unique step identifier"),prompt:n.string().describe("Task prompt for this step"),roleId:n.string().optional().describe("Role ID for this step. Call list_roles first to find roles."),requirements:j.optional().describe("Task requirements for this step (D-012)."),autoSelectRole:n.boolean().optional().describe("Auto-select best role for this step (D-012)."),dependsOn:n.array(n.string()).optional().describe("Step IDs this step depends on"),config:n.object({timeout:n.number().optional(),maxTurns:n.number().optional()}).optional()})).min(2).describe("Workflow steps (min 2)"),name:n.string().optional().describe("Workflow name for tracking"),deliverTo:n.array(E).optional().describe("Where to deliver the aggregated workflow output"),reportTo:n.array(E).optional().describe("Where to send workflow status reports"),continueOnError:n.boolean().optional().describe("Continue remaining steps if one fails (default false)")},async e=>{let t=[];for(let p of e.steps){if(!p.roleId&&!p.autoSelectRole){t.push(`${p.id} (needs roleId or autoSelectRole)`);continue}if(p.roleId){let y=I(p.roleId);(!y||y.status!=="active")&&t.push(`${p.id} (roleId ${p.roleId} invalid/inactive)`)}}if(t.length>0){let p=A("active",20,0).filter(y=>y.source!=="system").map(y=>({id:y.id,name:y.name,capabilitySummary:C(y)}));return s({error:`Steps missing roleId/autoSelectRole or with invalid roleIds: ${t.join("; ")}.`,availableRoles:p})}let r=new Set(e.steps.map(p=>p.id));for(let p of e.steps)if(p.dependsOn)for(let y of p.dependsOn){if(!r.has(y))return s({error:`Step "${p.id}" depends on unknown step "${y}"`});if(y===p.id)return s({error:`Step "${p.id}" cannot depend on itself`})}let o=new Set,i=new Set,a=new Map(e.steps.map(p=>[p.id,p.dependsOn??[]])),l=p=>{if(i.has(p))return!0;if(o.has(p))return!1;o.add(p),i.add(p);for(let y of a.get(p)??[])if(l(y))return!0;return i.delete(p),!1};for(let p of e.steps)if(l(p.id))return s({error:"Circular dependency detected in workflow steps"});let d=e.deliverTo?await _(e.deliverTo):void 0,m=e.reportTo?await _(e.reportTo):void 0,c=T(),h=R(),f={id:`workflow-${c}`,name:e.name??"Ad-hoc workflow",trigger:{type:"manual"},steps:e.steps.map(p=>({id:p.id,prompt:p.prompt,roleId:p.roleId,requirements:p.requirements,autoSelectRole:p.autoSelectRole,dependsOn:p.dependsOn,config:p.config})),enabled:!0,createdAt:Date.now(),config:{...h.defaults,continueOnError:e.continueOnError??!1},deliverTo:d,reportTo:m};try{ge(f)}catch(p){let{TemplateRoleConfigError:y}=await import("./task-templates-4DWXHLFZ.js");if(p instanceof y)return s({code:p.code,error:p.message,failingStepIds:p.failingStepIds,hint:"Each step must have roleId OR autoSelectRole=true (with requirements). Use list_roles to find an appropriate role."});throw p}let{WorkflowExecutor:g}=await import("./workflow-executor-6ZMNL34C.js");new g().execute(f,c).catch(p=>{V.error({executionId:c,error:p},"dispatch_workflow execution failed")});let S=e.steps.map(p=>{let y=p.roleId??(p.autoSelectRole?"[auto-selected]":"[no role]");return(p.roleId?I(p.roleId):void 0)?.name??y});return s({executionId:c,templateId:f.id,stepCount:e.steps.length,roles:[...new Set(S)],status:"started"})}),u("evaluate_result","Evaluate a completed task's result and record a trial for Thompson Sampling.",_n,async e=>{let{goalId:t,taskId:r,strategyId:o}=e,i=at(t??"",r);return o&&t&&$.recordTrial(o,t,r,i.reward,i.breakdown.L2||void 0,i.breakdown.L3||void 0,"Evaluated via adam-tools"),s({reward:i.reward,metricL2Score:i.breakdown.L2||void 0,metricL3Score:i.breakdown.L3||void 0,source:i.source,reasoning:`Evaluated via ${i.source} with confidence ${i.confidence.toFixed(2)}`})}),u("create_strategy","Create a new strategy variant for a role/taskType using LLM evolution.",Rn,async e=>{let{roleId:t,taskType:r}=e;await ie.generateVariants(t,r,3,1);let o=$.getStrategies(t,r),i=o[o.length-1];return s(i?{id:i.id,name:i.name,promptTemplate:i.promptTemplate}:{error:`Failed to create strategy for ${t}/${r}`})}),u("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.",Dn,async e=>{let t=e.status;return s(ot(t,e.limit??10,0))}),u("delete_goal","Delete a goal by ID.",{goalId:n.string()},async e=>F(e.goalId)?(it(e.goalId),s({success:!0,goalId:e.goalId})):s({error:"Goal not found"})),u("pause_goal","Pause an active goal.",{goalId:n.string()},async e=>F(e.goalId)?(oe(e.goalId,{status:"paused",updatedAt:Date.now()}),s({success:!0,goalId:e.goalId,status:"paused"})):s({error:"Goal not found"})),u("assign_role","Assign a role to a pending task.",En,async e=>{let{taskId:t,roleId:r}=e;if(!P(t))return s({error:`Task not found: ${t}`});let i=I(r);return i?(W(t,{roleId:r}),V.debug({taskId:t,roleId:r,roleName:i.name},"Role assigned to task"),s({success:!0,taskId:t,roleId:r})):s({error:`Role not found: ${r}`})}),...pt(),u("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.",Cn,async e=>{if(e.taskId){let r=P(e.taskId);return s(r??{error:"Task not found"})}let t=e.status;return s(U(t,e.limit??100,0))}),u("modify_role_permissions","Update a role's RBAC permissions (paths, tools, OS capabilities).",xn,async e=>{if(!I(e.roleId))return s({error:`Role not found: ${e.roleId}`});let r={};if(e.allowedTools&&(r.allowedTools=e.allowedTools),e.disallowedTools&&(r.disallowedTools=e.disallowedTools),e.osCapabilities!==void 0)try{r.osCapabilities=ue(e.osCapabilities)}catch(o){return s({error:o instanceof Error?o.message:String(o)})}return e.additionalDirectories!==void 0&&(r.additionalDirectories=e.additionalDirectories),e.allowedChannels!==void 0&&(r.allowedChannels=e.allowedChannels),"inheritUserSettings"in e&&(r.inheritUserSettings=e.inheritUserSettings),L(e.roleId,r),s({success:!0})}),u("update_role","Update a role's identity and config fields (name, CAG prompt, learned rules, status, model, execution mode, preferences, permission mode, bash patterns, evaluation criteria, env vars). For permission fields (allowedTools, disallowedTools, osCapabilities, additionalDirectories, allowedChannels, inheritUserSettings) use modify_role_permissions instead.",Pn,async e=>{if(!I(e.roleId))return s({error:`Role not found: ${e.roleId}`});let{roleId:r,...o}=e,i={...o,updatedAt:Date.now()};L(r,i);let a=I(r);if(!a)return s({error:"Role disappeared after update"});if(e.cagPrompt!==void 0||e.learnedRules!==void 0){let l=me(a.name);Lt(l)&&Fe(l,a)}return s({success:!0,role:a})}),u("view_audit_log","View the evolution audit log for role changes.",An,async e=>{let{listEvolutionAudit:t}=await import("./evolution-audit-ZLYQ3ZYV.js"),r=t(e.limit??50);return s({entries:r})}),u("list_roles","List all roles with their capabilities including bound plugins (skills/agents). Use this to discover available roles before dispatching tasks. Pass requirements to get ranked results with fitScore showing which roles best match the task.",Un,async e=>{if(e.requirements){let o=e.requirements,a=tt(o).slice(0,e.limit??50).map(l=>{let d=l.role,m=ne(d),c=m.plugins.map(v=>v.name),h=me(d.name),f=Ze(d,h),g=o.tools?(d.allowedTools??[]).filter(v=>o.tools.includes(v)):void 0,b=o.paths?o.paths.filter(v=>Xe(v,f)):void 0,S=new Set((d.osCapabilities??[]).map(v=>v.id)),p=o.osCapabilities?o.osCapabilities.filter(v=>S.has(v.id)).map(v=>v.id):void 0,y=new Set(c),$e=o.plugins?o.plugins.filter(v=>y.has(v)):void 0,jt=o.network===!0?(d.osCapabilities??[]).some(v=>v.id==="local-network"):void 0,Ft=l.missing?.osCapabilities,Gt=et(d,o);return{id:d.id,name:d.name,status:d.status,allowedTools:d.allowedTools??[],disallowedTools:d.disallowedTools??[],osCapabilities:d.osCapabilities??[],additionalDirectories:d.additionalDirectories??[],cagPrompt:d.cagPrompt.slice(0,500)+(d.cagPrompt.length>500?"...":""),capabilitySummary:C(d,m),plugins:m.plugins.map(v=>({name:v.name,skills:v.skills.map(de=>de.name),agents:v.agents.map(de=>de.name)})),fitScore:l.fitScore,fits:l.evaluation.ok,matchedTools:g,matchedPaths:b,matchedOsCapabilities:p,matchedPlugins:$e,matchedNetwork:jt,missingCapabilities:l.missing?{tools:l.missing.tools,paths:l.missing.paths,osCapabilities:Ft?.map(v=>v.id),plugins:l.missing.plugins,network:l.missing.network}:void 0,warnings:Gt,why:l.evaluation.ok?`Role '${d.name}' satisfies all requirements (fitScore: ${l.fitScore.toFixed(2)})`:`Role '${d.name}' does not satisfy requirements: ${l.evaluation.ok?"unknown":l.evaluation.reason}`}});return s({roles:a})}let r=A(e.status,e.limit??50,0).map(o=>{let i=ne(o);return{id:o.id,name:o.name,status:o.status,allowedTools:o.allowedTools??[],disallowedTools:o.disallowedTools??[],osCapabilities:o.osCapabilities??[],additionalDirectories:o.additionalDirectories??[],cagPrompt:o.cagPrompt.slice(0,500)+(o.cagPrompt.length>500?"...":""),capabilitySummary:C(o,i),plugins:i.plugins.map(a=>({name:a.name,skills:a.skills.map(l=>l.name),agents:a.agents.map(l=>l.name)}))}});return s({roles:r})}),u("create_role","Create a new role with a name, CAG prompt, and optional tool permissions or OS capabilities.",$n,async e=>{let t;try{t=ue(e.osCapabilities)}catch(i){return s({error:i instanceof Error?i.message:String(i)})}let r=`role-${T().slice(0,8)}`,o={id:r,name:e.name,cagPrompt:e.cagPrompt,learnedRules:[],memoryStreamId:`mem-${T().slice(0,8)}`,status:"active",preferences:{},createdAt:Date.now(),allowedTools:e.allowedTools,disallowedTools:e.disallowedTools,osCapabilities:t,additionalDirectories:e.additionalDirectories};return qe(o),X(o),s({roleId:r,name:e.name,allowedTools:e.allowedTools,osCapabilities:o.osCapabilities,additionalDirectories:e.additionalDirectories??[]})}),u("retire_role","Retire a role (marks as retired, stops receiving tasks).",Mn,async e=>I(e.roleId)?(L(e.roleId,{status:"retired"}),V.info({roleId:e.roleId,reason:e.reason},"Role retired"),s({success:!0})):s({error:`Role not found: ${e.roleId}`})),u("create_goal","Create a new goal with optional budget, deadline, and metric tracking.",Nn,async e=>{let t=T(),r=Date.now(),o=r+10080*60*1e3,i={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??o,budgetUsd:e.budgetUsd??5,status:"active",createdAt:r,deliverTo:e.deliverTo?await _(e.deliverTo):void 0};re(i),yt(t,i.metricType);let a=F(t);return s({goalId:a.id,name:a.name,status:a.status})}),u("create_template","Create a recurring scheduled task. triggerType values: 'cron' (recurring via cron expression), 'template_complete' (fires when a specific template's task completes; set triggerEvent to 'template_complete:<templateId>'), 'workflow_complete' (similar), 'event' (fires when an Event def fires; set eventDefId to the event def UUID \u2014 use list_event_defs or create_event_def first). For one-shot delayed tasks ('in 30 minutes', 'tomorrow at 3pm'), use schedule_task instead.",On,async e=>{let{createTaskTemplate:t}=await import("./task-templates-4DWXHLFZ.js"),r=T(),o=T();if(e.triggerType==="event"&&!e.eventDefId)return s({error:"eventDefId required when triggerType='event'"});if(e.triggerType!=="event"&&e.eventDefId)return s({error:"eventDefId only valid when triggerType='event'"});let i=e.deliverTo?await _(e.deliverTo):void 0,a=e.reportTo?await _(e.reportTo):void 0,l={id:r,name:e.name,description:e.description,trigger:{type:e.triggerType,cron:e.triggerCron,event:e.triggerEvent,eventDefId:e.eventDefId},steps:[{id:o,prompt:e.prompt,...e.autoSelectRole!==void 0?{autoSelectRole:e.autoSelectRole}:{},...e.requirements!==void 0?{requirements:e.requirements}:{}}],rolePreference:e.roleId,enabled:e.enabled??!0,createdAt:Date.now(),goalIds:e.goalIds,deliverTo:i,reportTo:a};try{t(l)}catch(d){let{TemplateRoleConfigError:m}=await import("./task-templates-4DWXHLFZ.js");if(d instanceof m)return s({code:d.code,error:d.message,failingStepIds:d.failingStepIds,hint:"Set roleId (recommended) OR autoSelectRole=true with a requirements object (e.g., {tools:['Read']}) on the template. Use list_roles to find an appropriate role."});throw d}return s({templateId:r,name:l.name,trigger:l.trigger})}),u("create_event_def","Create an Event definition \u2014 a user-configured source that fires on schedule/webhook/directory/manual. Event defs are the trigger half of the Event Slot; pair with create_template(triggerType='event', eventDefId=<returned id>) to bind work to the trigger. sourceType is validated at runtime against the installed source registry (currently: webhook, cron, directory_watch, manual \u2014 additional types may be registered at runtime). sourceConfig is per-type: cron \u2192 {cron: '0 9 * * *'}; directory_watch \u2192 {path: '/abs/path', glob?: '*.md'}; webhook/manual \u2192 {}.",{name:n.string().min(1).max(100).describe("Human-readable name (unique within workspace)."),sourceType:n.string().describe("Source type \u2014 validated against installed registry at call time. Currently: 'webhook' | 'cron' | 'directory_watch' | 'manual'. If the value is rejected, the error message lists the currently-registered types."),sourceConfig:n.record(n.string(),n.unknown()).describe("Per-sourceType configuration. See tool description."),enabled:n.boolean().optional().describe("Default true."),description:n.string().max(500).optional()},async e=>{if(!H().includes(e.sourceType))return s({error:`Unknown sourceType: '${e.sourceType}'. Currently registered: ${H().join(", ")}`});let t=Ae(e.sourceType,e.sourceConfig);if(!t.ok)return s({error:`Invalid sourceConfig: ${t.error}`});let r=T(),o=Et({id:r,name:e.name,sourceType:e.sourceType,sourceConfig:e.sourceConfig,enabled:e.enabled??!0,description:e.description});try{Pe(o)}catch(i){_e(r);let a=i instanceof Error?i.message:String(i);return s({error:`Failed to start source: ${a}. Event def was not created.`})}return s({id:o.id,name:o.name,sourceType:o.sourceType,enabled:o.enabled})}),u("list_event_defs","List Event definitions. Use before create_template(triggerType='event') to find the eventDefId, or before fire_event_def / list_event_firings.",{sourceType:n.string().optional().describe("Filter by source type (e.g., 'cron', 'webhook')."),enabled:n.boolean().optional().describe("Filter by enabled flag.")},async e=>{let t=se({sourceType:e.sourceType,enabled:e.enabled});return s(t.map(r=>({id:r.id,name:r.name,sourceType:r.sourceType,sourceConfig:r.sourceConfig,enabled:r.enabled,description:r.description,createdAt:r.createdAt})))}),u("update_event_def","Update an Event definition. Changing `enabled` or `sourceConfig` on an active def automatically restarts the runtime source handler. Use list_event_defs first to get the id.",{id:n.string().uuid().describe("Event def id."),name:n.string().min(1).max(100).optional(),sourceType:n.string().optional().describe("Only set when migrating to a different source type."),sourceConfig:n.record(n.string(),n.unknown()).optional(),enabled:n.boolean().optional(),description:n.string().max(500).optional()},async e=>{let t=G(e.id);if(!t)return s({error:`Event def '${e.id}' not found`});if(e.sourceType!==void 0||e.sourceConfig!==void 0){let l=e.sourceType??t.sourceType;if(!H().includes(l))return s({error:`Unknown sourceType: '${l}'`});let d=Ae(l,e.sourceConfig??t.sourceConfig);if(!d.ok)return s({error:`Invalid sourceConfig: ${d.error}`})}let r=t.enabled,o=e.enabled??t.enabled,i=e.sourceType!==void 0||e.sourceConfig!==void 0;r&&(!o||i)&&le(t.id,t.sourceType);let a=Se(e.id,{name:e.name,sourceType:e.sourceType,sourceConfig:e.sourceConfig,enabled:e.enabled,description:e.description});if(!a)return s({error:"Update failed"});if(o&&(!r||i))try{Pe(a)}catch(l){Se(e.id,{enabled:!1});let d=l instanceof Error?l.message:String(l);return s({error:`Failed to start source with new config: ${d}. Event def has been marked disabled to match runtime state.`})}return s({id:a.id,name:a.name,sourceType:a.sourceType,enabled:a.enabled})}),u("delete_event_def","Delete an Event definition. Stops the runtime source handler (cron/fswatch) first, then deletes the DB row. Templates bound to this event def become orphaned and will not fire.",{id:n.string().uuid().describe("Event def id.")},async e=>{let t=G(e.id);if(!t)return s({error:`Event def '${e.id}' not found`});try{le(t.id,t.sourceType)}catch(o){V.warn({defId:t.id,err:o},"stopEventDefSource failed during delete \u2014 proceeding with row deletion")}let r=_e(e.id);return s({ok:r,id:e.id})}),u("fire_event_def","Fire an Event definition now. For manual defs: creates a real manual event (same as clicking 'Fire now' in the UI). For any source type: with test=true, creates a synthetic test event (source='manual-test-<defId>') that flows through the EventDispatcher \u2014 useful for debugging why a Template bound to the event didn't fire. Payload is optional.",{id:n.string().uuid().describe("Event def id."),test:n.boolean().optional().describe("Test mode. Required (=true) when source type != 'manual'. Default false. In test mode the event does NOT collide with real firings' dedup keys."),payload:n.record(n.string(),n.unknown()).optional().describe("Optional event payload. Must be < 64 KB when JSON-serialized.")},async e=>{let t=G(e.id);if(!t)return s({error:`Event def '${e.id}' not found`});let r=e.test===!0;if(t.sourceType!=="manual"&&!r)return s({error:`Can only directly fire manual event defs; this def has source type '${t.sourceType}'. Pass test=true to dry-run.`});if(e.payload){let o=Buffer.byteLength(JSON.stringify(e.payload),"utf8");if(o>65536)return s({error:`Payload exceeds 64 KB limit (got ${o} bytes)`})}try{let o=r?Ce(t,e.payload):Ee(t,e.payload);return s({ok:!0,eventId:o.eventId,test:r})}catch(o){let i=o instanceof Error?o.message:String(o);return s({error:i})}}),u("list_event_firings","List recent firings of an Event definition \u2014 for debugging 'why didn't my automation fire' and inspecting event history. Returns id, occurredAt, type, source, dedupKey, confidence, and a truncated payload (500 char cap for display). For full payloads, use REST GET /event-defs/:id/firings.",{eventDefId:n.string().uuid().describe("Event def id. Use list_event_defs to find it."),since:n.string().optional().describe("ISO 8601 start timestamp (inclusive). Omit for unlimited range."),until:n.string().optional().describe("ISO 8601 end timestamp (inclusive)."),limit:n.number().int().positive().max(500).optional().describe("Max rows (default 50, max 500).")},async e=>{let t=G(e.eventDefId);if(!t)return s({error:`Event def '${e.eventDefId}' not found`});let r=Rt({eventDefId:e.eventDefId,since:e.since,until:e.until,limit:e.limit??50}),o=500;return s({eventDefName:t.name,sourceType:t.sourceType,count:r.length,firings:r.map(i=>{let a=JSON.stringify(i.payload);return{id:i.id,occurredAt:i.occurredAt,type:i.type,source:i.source,dedupKey:i.dedupKey,confidence:i.confidence,payloadPreview:a.length>o?a.slice(0,o)+"...[truncated]":a,payloadTruncated:a.length>o}})})}),u("create_skill","Author a Claude Code Skill file under a target Role's workspace. The Skill becomes available next time the Role runs. Preset Roles (Engineer, Reviewer, Researcher, Writer, Chat Manager, adam-automator) require overwrite=true to replace an existing skill \u2014 first-time creation is unrestricted. Returns the written file path.",{roleId:n.string().describe("Role to target. Use list_roles to find it."),skillName:n.string().regex(/^[a-z0-9_][a-z0-9_-]{0,39}$/,"skillName must be 1-40 chars: lowercase letters, digits, underscores, optional hyphen in middle. No leading dot or dash.").describe("Skill directory name (used as the directory under .claude/skills/)."),description:n.string().max(500).describe("One-line description shown to the Role's LLM when choosing a Skill."),instructions:n.string().describe("The skill body: what it does and how to do it."),parameters:n.record(n.string(),n.object({type:n.string().describe("Parameter type name"),description:n.string().describe("Parameter description")})).optional().describe("Named input parameters and their types."),overwrite:n.boolean().optional().describe("Required (=true) to overwrite an existing SKILL.md under a preset Role (Engineer, Reviewer, Researcher, Writer, Chat Manager, adam-automator). First-time skill creation and non-preset Roles do not require this flag.")},async e=>{let{getRole:t}=await import("./roles-DRPLO4LY.js"),{ensureRoleWorkspace:r}=await import("./role-workspace-LHW7AWPF.js"),{mkdir:o,writeFile:i}=await import("fs/promises"),{resolve:a}=await import("path"),l=t(e.roleId);if(!l)return s({error:`Role '${e.roleId}' not found`});let d=r(l),m=a(d,".claude","skills",e.skillName);if(Be(l)){let{existsSync:g}=await import("fs"),b=a(m,"SKILL.md");if(g(b)&&e.overwrite!==!0)return s({error:`Role '${l.name}' is a preset. Skill '${e.skillName}' already exists at ${b}. Pass overwrite=true to replace, or choose a different skillName to add alongside.`,requiresOverwrite:!0,existingPath:b})}let c=a(d,".claude","skills");if(!m.startsWith(c+(process.platform==="win32"?"\\":"/")))return s({error:"Path traversal rejected"});await o(m,{recursive:!0});let h=vn(e),f=a(m,"SKILL.md");return await i(f,h,"utf8"),s({ok:!0,path:f})}),u("list_templates","List task templates (automations). Use this to check existing scheduled/recurring tasks before creating new ones.",{enabled:n.boolean().optional().describe("Filter by enabled status. Omit to list all."),limit:n.number().optional().describe("Max results (default 50)")},async e=>{let{listTaskTemplates:t}=await import("./task-templates-4DWXHLFZ.js"),r=t(e.enabled,e.limit??50,0);return s(r.map(o=>({id:o.id,name:o.name,description:o.description,trigger:o.trigger,enabled:o.enabled,rolePreference:o.rolePreference,deliverTo:o.deliverTo,createdAt:o.createdAt})))}),u("send_to_channel","Send a message (text, image, voice, video, file) to a connected channel by name. Use this to deliver task results, media, or notifications to a specific channel (e.g., WeChat on iPad). For media: provide mediaUrl as an absolute local file path and mediaType. Do NOT use remote URLs \u2014 download files locally first.",{channelName:n.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:n.string().describe("The message content to send (text caption when sending media)"),mediaUrl:n.string().optional().describe("Absolute local file path to the media file (e.g. /Users/.../file.png). Must exist on disk. Do NOT use remote URLs \u2014 download files locally first."),mediaType:n.enum(["image","audio","video","file"]).optional().describe("Type of the media file. Required when mediaUrl is provided")},async e=>{if(e.mediaUrl){if(e.mediaUrl.includes("://")&&!e.mediaUrl.startsWith("file://"))return s({error:`mediaUrl must be a local file path, not a remote URL. Got: ${e.mediaUrl.slice(0,80)}. Download the file to a local path first, then pass the local path.`});let l=e.mediaUrl.startsWith("file://")?new URL(e.mediaUrl).pathname:e.mediaUrl;if(!Lt(l))return s({error:`Media file not found: ${l}. Verify the file exists before sending.`});if(!e.mediaType)return s({error:"mediaType is required when mediaUrl is provided. Specify one of: image, audio, video, file."})}let t=await _([{type:"channel",channelName:e.channelName}]);if(t.length===0)return s({error:`Channel "${e.channelName}" not found or no chatId available`});let r=t[0];if(r.type!=="channel")return s({error:"Resolved target is not a channel"});let{getOutboundGateway:o}=await import("./outbound-gateway-Y3P3T3VH.js"),a=await o().send({channelId:r.channelId,chatId:r.chatId,content:e.message,messageType:"deliver",mediaUrl:e.mediaUrl,mediaType:e.mediaType});return s({success:a.success,channelName:e.channelName,...a.error?{error:a.error}:{}})}),u("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.",Ln,async e=>{let t=ve(e.enabled),r=[...we("active"),...we("archived")],o=t.map(i=>{let a,l=r.find(d=>d.source.type==="channel"&&d.source.channelId===i.id&&d.source.chatId);return l?.source.chatId?a=l.source.chatId:a=i.config?.userId,{id:i.id,name:i.name,platform:i.platform,status:i.status,chatId:a}});return s({channels:o})}),u("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.",qn,async()=>{let e=R(),t=U("running"),r=U("pending");return s({executionPool:{active:t.length,max:e.execution?.maxConcurrent??5,queued:r.length},timestamp:new Date().toISOString()})}),u("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.",Fn,async e=>{let t=I(e.roleId);if(!t||t.status!=="active"){let f=A("active",20,0).filter(g=>g.source!=="system").map(g=>({id:g.id,name:g.name,allowedTools:g.allowedTools??[],capabilitySummary:C(g)}));return s({error:`Role not found or not active: ${e.roleId}. Pick a roleId from the list below.`,availableRoles:f})}let r=Date.now(),o;if(e.delayMinutes!==void 0&&e.runAt!==void 0)return s({error:"Provide exactly one of delayMinutes or runAt, not both"});if(e.delayMinutes!==void 0)o=r+e.delayMinutes*60*1e3;else if(e.runAt!==void 0){if(o=new Date(e.runAt).getTime(),isNaN(o))return s({error:"Invalid ISO 8601 timestamp in runAt"})}else return s({error:"Provide either delayMinutes or runAt"});if(o<=r)return s({error:"Scheduled time must be in the future"});let i=10080*60*1e3;if(o-r>i)return s({error:"Schedule exceeds maximum of 7 days"});let a=T(),l=new Date(o).toISOString(),d=e.deliverTo?await _(e.deliverTo):void 0,m=e.reportTo?await _(e.reportTo):void 0;ge({id:a,name:e.prompt.slice(0,80),description:`One-shot scheduled task: ${e.prompt.slice(0,200)}`,trigger:{type:"once",runAt:l},steps:[{id:"main",prompt:e.prompt}],rolePreference:e.roleId,config:{...R().defaults},tags:["scheduled","once"],enabled:!0,createdAt:r,deliverTo:d,reportTo:m});let{getBreeEngine:c}=await import("./bree-engine-XJR5TKVC.js"),h=c();return h&&h.scheduleOnceJob(a),s({templateId:a,executeAt:l,prompt:e.prompt})}),u("cancel_scheduled_task","Cancel a previously scheduled one-shot task by its template ID. The task will not execute.",{templateId:n.string().describe("The template ID returned by schedule_task")},async e=>{let t=q(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});if(t.trigger.type!=="once")return s({error:"This is not a one-shot scheduled task. Use disable_template for recurring automations."});Ve(e.templateId);let{getBreeEngine:r}=await import("./bree-engine-XJR5TKVC.js"),o=r();return o&&await o.unscheduleJob(e.templateId),s({cancelled:!0,templateId:e.templateId})}),u("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.",Gn,async e=>{let t=Ke(),r=te(),o=e.roleId?(()=>{let{getRoleWorkspacePath:i}=(ee(),x(fe)),{getRole:a}=(Z(),x(pe)),{listInstalledPlugins:l}=(Qe(),x(Bt)),d=a(e.roleId);if(!d)return[];let m=i(d.name);return l({scope:"project",projectPath:m}).map(c=>c.id)})():[];return s({plugins:r.map(i=>({id:i.id,name:i.name,scope:i.scope,projectPath:i.projectPath,enabled:i.enabled,globalEnabled:t[i.id]??i.enabled,isInstalledInRole:o.includes(i.id),description:i.version?`v${i.version}`:void 0}))})}),u("install_plugin_for_role","Install a plugin into a role's workspace (project-scope). The plugin will be available when that role executes tasks.",Vn,async e=>{let{getRole:t}=(Z(),x(pe)),{getRoleWorkspacePath:r}=(ee(),x(fe)),o=t(e.roleId);if(!o)return s({error:`Role not found: ${e.roleId}`});let i=r(o.name);try{return ke(e.pluginId,"project",i),s({success:!0,roleId:e.roleId,pluginId:e.pluginId,scope:"project",cwd:i})}catch(a){return s({error:`Failed to install plugin: ${a}`})}}),u("uninstall_plugin_from_role","Uninstall a plugin from a role's workspace.",Wn,async e=>{let{getRole:t}=(Z(),x(pe)),{getRoleWorkspacePath:r}=(ee(),x(fe)),o=t(e.roleId);if(!o)return s({error:`Role not found: ${e.roleId}`});let i=r(o.name);try{return Te(e.pluginId,"project",i),s({success:!0,roleId:e.roleId,pluginId:e.pluginId})}catch(a){return s({error:`Failed to uninstall plugin: ${a}`})}}),u("bind_mcp_to_role","Bind an MCP server configuration to a role. The MCP server will be available to the role during task execution.",Bn,async e=>{let t=I(e.roleId);if(!t)return s({error:`Role not found: ${e.roleId}`});let o={...t.mcpServers??{},[e.mcpName]:e.mcpConfig};try{return L(e.roleId,{mcpServers:o}),X(t),s({success:!0,roleId:e.roleId,mcpName:e.mcpName,mcpServers:o})}catch(i){return s({error:`Failed to bind MCP server: ${i}`})}}),u("unbind_mcp_from_role","Remove an MCP server binding from a role.",Kn,async e=>{let t=I(e.roleId);if(!t)return s({error:`Role not found: ${e.roleId}`});let r={...t.mcpServers??{}};if(!(e.mcpName in r))return s({error:`MCP server "${e.mcpName}" not bound to this role`});delete r[e.mcpName];try{return L(e.roleId,{mcpServers:r}),X(t),s({success:!0,roleId:e.roleId,mcpName:e.mcpName})}catch(o){return s({error:`Failed to unbind MCP server: ${o}`})}}),u("get_capabilities","Get a comprehensive overview of Adam's current capabilities: available roles and their tools, OS capability registry, connected channels, installed plugins, active automations, and execution capacity. Call this when the user asks what you can do, or asks for help.",jn,async()=>{let{listTaskTemplates:e}=await import("./task-templates-4DWXHLFZ.js"),t=R(),r=A(void 0,100,0),o=ve(),i=e(!0,100,0),a=U("running"),l=U("pending"),d=gt(),m=await ht();return s({roles:{description:"Specialized worker identities \u2014 each has its own tools, MCP servers, plugins (skills/agents), and learned rules",active:r.filter(c=>c.status==="active"&&c.source!=="system").map(c=>{let h=ne(c);return{name:c.name,tools:c.allowedTools??[],osCapabilities:c.osCapabilities??[],mcpServers:Object.keys(c.mcpServers??{}),channels:c.allowedChannels??[],capabilitySummary:C(c,h),plugins:h.plugins.map(f=>({name:f.name,skills:f.skills.map(g=>g.name),agents:f.agents.map(g=>g.name)}))}}),retired:r.filter(c=>c.status==="retired").length,probation:r.filter(c=>c.status==="probation").length},osCapabilities:{description:"Role-level OS capability registry. Only editable entries can be assigned to roles on this runtime.",sandbox:{platform:d.platform,available:m},registry:Le(d.platform,m)},channels:{description:"Send/receive messages via connected platforms",connected:o.filter(c=>c.enabled).map(c=>({name:c.name,platform:c.platform,status:c.status}))},plugins:{description:"Extensions that add capabilities to roles",installed:te().filter(c=>c.enabled).map(c=>({name:c.name,scope:c.scope,description:c.version?`v${c.version}`:void 0}))},automations:{description:"Recurring cron tasks and event-triggered templates",active:i.map(c=>({name:c.name,trigger:c.trigger}))},execution:{description:"Parallel task execution pool",maxConcurrent:t.execution?.maxConcurrent??5,running:a.length,queued:l.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"]})}),u("enable_plugin","Enable a globally installed plugin (makes it available to all roles).",zn,async e=>{try{return Tt(e.pluginId),s({success:!0,pluginId:e.pluginId})}catch(t){return s({error:`Failed to enable plugin: ${t}`})}}),u("disable_plugin","Disable a globally installed plugin (removes it from all roles).",Jn,async e=>{try{return St(e.pluginId),s({success:!0,pluginId:e.pluginId})}catch(t){return s({error:`Failed to disable plugin: ${t}`})}}),u("install_plugin_for_user","Install a plugin globally for the current user (user-scope).",Hn,async e=>{try{return ke(e.pluginId,"user"),s({success:!0,pluginId:e.pluginId,scope:"user"})}catch(t){return s({error:`Failed to install plugin: ${t}`})}}),u("uninstall_plugin_for_user","Uninstall a globally installed plugin from the current user.",Yn,async e=>{try{return Te(e.pluginId,"user"),s({success:!0,pluginId:e.pluginId})}catch(t){return s({error:`Failed to uninstall plugin: ${t}`})}}),u("browse_marketplace","Browse all available plugins from configured marketplaces (shows installed and available).",Qn,async()=>{try{let e=kt(),t=te();return s({available:e,installed:t})}catch(e){return s({error:`Failed to browse marketplace: ${e}`})}}),u("list_marketplace_sources","List configured plugin marketplace sources.",Zn,async()=>{let e=He();return s({sources:e})}),u("get_plugin_detail","Get detailed manifest for an installed plugin (skills, agents, MCP servers, hooks).",Xn,async e=>{let t=Je(e.pluginId);if(!t)return s({error:`Plugin not found: ${e.pluginId}`});let r=ze(t.installPath);return s({id:t.id,name:t.name,version:t.version,scope:t.scope,projectPath:t.projectPath,enabled:t.enabled,manifest:r})}),u("scan_directory","Scan a directory for .claude/settings.json and return its plugin/MCP configuration.",er,async e=>{let{getRole:t}=await import("./roles-DRPLO4LY.js");if(!t(e.roleId))return s({error:`Role not found: ${e.roleId}`});try{let o=Ye(e.path);return s({roleId:e.roleId,path:e.path,config:o})}catch(o){return s({error:`Failed to scan directory: ${o}`})}}),u("cancel_task","Cancel a running or pending task by setting its status to 'cancelled'. Emits a task_status_change event.",tr,async e=>{let t=P(e.taskId);if(!t)return s({error:`Task not found: ${e.taskId}`});let r=t.status;W(e.taskId,{status:"cancelled"});let{serverBus:o}=await import("./server-bus-GEGVMSCA.js");return o.emit({type:"task_status_change",taskId:e.taskId,oldStatus:r,newStatus:"cancelled"}),s({success:!0,taskId:e.taskId,status:"cancelled"})}),u("view_task_logs","Retrieve step-by-step execution logs for a task.",nr,async e=>{let t=Ue(e.taskId,e.limit??20);return s({taskId:e.taskId,count:t.length,logs:t})}),u("delete_role","Delete a role by ID. This removes the role and its workspace.",rr,async e=>I(e.roleId)?(je(e.roleId),s({success:!0,roleId:e.roleId})):s({error:`Role not found: ${e.roleId}`})),u("view_config","Get the current runtime configuration (mutable fields and restart-required fields).",or,async()=>{let{MUTABLE_PATHS:e,RESTART_REQUIRED_PATHS:t}=await import("./runtime-YPBWWMXW.js"),r=R(),o={};try{let d=R().server?.port??7100,m=await fetch(`http://127.0.0.1:${d}/config`);m.ok&&(o=await m.json())}catch{}let i=[...e,...t],a=[...t],l={};for(let d of i){let m=d.split("."),c=r;for(let h of m)if(c&&typeof c=="object")c=c[h];else{c=void 0;break}l[d]={value:c,mutable:!t.includes(d)}}return s({config:l,mutable:[...e],restartRequired:[...t]})}),u("update_config","Update mutable runtime configuration fields. Returns partial-success: some fields may update while others return errors.",ir,async e=>{let{isRestartRequiredPath:t}=await import("./runtime-YPBWWMXW.js"),{setConfigValue:r}=await import("./config-CILWJYZB.js"),o=Me(e.updates,r);if(e.updates["logging.level"]&&Ne(e.updates["logging.level"]),o.updated.length>0){let{serverBus:i}=await import("./server-bus-GEGVMSCA.js");i.emit({type:"config_changed",changes:o.updated.map(a=>({path:a,value:e.updates[a]}))})}return s(o)}),u("list_memories","List memories stored under a specific role.",sr,async e=>{let t=ut(e.roleId,e.limit??20);return s({roleId:e.roleId,count:t.length,memories:t})}),u("update_template","Update a task template's fields (name, prompt, cron, enabled, etc.).",ar,async e=>{let t=q(e.templateId);if(!t)return s({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||e.autoSelectRole!==void 0||e.requirements!==void 0){let i=t.steps?.length?[...t.steps]:[];i.length===0&&i.push({id:T(),prompt:e.prompt??""});let a=i[0];i[0]={...a,...e.prompt!==void 0?{prompt:e.prompt}:{},...e.autoSelectRole!==void 0?{autoSelectRole:e.autoSelectRole}:{},...e.requirements!==void 0?{requirements:e.requirements}:{}},r.steps=i}if(e.triggerCron!==void 0||e.triggerEvent!==void 0||e.triggerType!==void 0||e.eventDefId!==void 0){let i=e.triggerType??(e.triggerEvent?e.triggerEvent.split(":")[0]:e.eventDefId?"event":"cron");if(i==="event"&&!e.eventDefId)return s({error:"eventDefId required when triggerType='event'"});r.trigger={type:i,...e.triggerCron!==void 0?{cron:e.triggerCron}:{},...e.triggerEvent!==void 0?{event:e.triggerEvent}:{},...e.eventDefId!==void 0?{eventDefId:e.eventDefId}:{}}}e.roleId!==void 0&&(r.rolePreference=e.roleId);try{Ge(e.templateId,r)}catch(i){let{TemplateRoleConfigError:a}=await import("./task-templates-4DWXHLFZ.js");if(i instanceof a)return s({code:i.code,error:i.message,failingStepIds:i.failingStepIds,hint:"Set roleId (recommended) OR autoSelectRole=true with a requirements object."});throw i}return s({success:!0,templateId:e.templateId,updated:Object.keys(r)})}),u("get_template_dependents","Count workflow_executions and tasks that depend on a template. Use this BEFORE delete_template to show the user what will be affected. Returns { executionCount, taskCount, hasDependents }. If hasDependents is false, delete_template is safe with mode='template_only'. If true, you MUST ask the user whether to delete the template only (keeps tasks as history) or delete with its tasks (removes tasks and their score history). Never pick the mode yourself.",dr,async e=>{let t=q(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});let r=he(e.templateId);return s({templateId:e.templateId,templateName:t.name,executionCount:r.executionCount,taskCount:r.taskCount,hasDependents:r.executionCount>0||r.taskCount>0})}),u("delete_template","Delete a task template by ID. PRECONDITION: you must have called get_template_dependents first. If executionCount > 0 or taskCount > 0, you must have shown the user those counts and received explicit confirmation of which mode to use. Call this tool only after the user picks 'template_only' or 'with_tasks'. Passing a mode without user confirmation violates the skill's safety contract.",lr,async e=>{let t=q(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});let r=he(e.templateId);return We(e.templateId,e.mode),s({success:!0,templateId:e.templateId,templateName:t.name,mode:e.mode,deleted:{template:1,workflowExecutions:r.executionCount,tasks:e.mode==="with_tasks"?r.taskCount:0}})}),u("run_template","Trigger a template immediately (runs the webhook endpoint for its name).",cr,async e=>{let t=q(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});try{let r=R().server?.port??7100,o=await fetch(`http://127.0.0.1:${r}/webhooks/${t.name}`,{method:"POST"}),i=await o.json();return o.ok?s({success:!0,templateId:e.templateId,templateName:t.name,response:i}):s({error:`Webhook failed: ${i.code??o.status} \u2014 ${i.message??""}`})}catch(r){return s({error:`Failed to trigger template: ${r}`})}}),u("list_delivery_rules","List delivery rules, optionally filtered by enabled status.",ur,async e=>{let t=Ie(e.enabled);return s({count:t.length,rules:t})}),u("create_delivery_rule","Create a new delivery rule for event-driven result routing.",pr,async e=>{let t=T(),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 mt(r),s({success:!0,ruleId:t,rule:r})}),u("delete_delivery_rule","Delete a delivery rule by ID.",mr,async e=>Ie().find(o=>o.id===e.ruleId)?(ft(e.ruleId),s({success:!0,ruleId:e.ruleId})):s({error:`Delivery rule not found: ${e.ruleId}`})),u("list_strategies","List Thompson Sampling strategy populations for a role, or all strategies if roleId omitted.",fr,async e=>{let t;if(e.roleId)t=rt(e.roleId);else{let{getDb:r}=await import("./db-JO24ZLIN.js");t=r().prepare("SELECT * FROM strategies ORDER BY created_at").all().map(i=>({id:i.id,roleId:i.role_id,name:i.name,taskType:i.task_type,createdAt:i.created_at,updatedAt:i.updated_at??void 0,promptTemplate:i.prompt_template??"",alpha:i.alpha,beta:i.beta,totalTrials:i.trials,avgReward:i.total_reward&&i.trials>0?i.total_reward/i.trials:void 0,enabled:i.enabled===1}))}return s({roleId:e.roleId??null,count:t.length,strategies:t})}),u("authorize_task_operation","Authorize a pending privilege escalation for a task. The paused operation will proceed.",{taskId:n.string(),operationId:n.string().optional().describe("ID of the specific operation. If omitted, authorizes the most recent pending operation."),scope:n.enum(["once","permanent"]).default("once").describe("'once' = this operation only. 'permanent' = auto-authorize matching patterns in the future.")},async e=>{let t=be(e.taskId),r=e.operationId?t.find(i=>i.id===e.operationId):t.find(i=>i.status==="pending");return r?(new Q().resolvePlanApproval(r.id,"allow",e.scope),s({success:!0,operationId:r.id,decision:"allow",scope:e.scope})):s({error:"No pending operation found for this task"})}),u("deny_task_operation","Deny a pending privilege escalation for a task. The paused operation will be rejected.",{taskId:n.string(),operationId:n.string().optional(),reason:n.string().optional().describe("Reason for denial, provided to the executor as feedback.")},async e=>{let t=be(e.taskId),r=e.operationId?t.find(i=>i.id===e.operationId):t.find(i=>i.status==="pending");return r?(new Q().resolvePlanApproval(r.id,"deny","once",e.reason),s({success:!0,operationId:r.id,decision:"deny"})):s({error:"No pending operation found for this task"})})];function ti(){return qt.map(e=>e.name).sort().join(",")}function ni(){return bn({name:"adam-tools",version:"1.0.0",tools:qt})}export{Q as a,wr as b,Ir as c,yt as d,kt as e,ke as f,Te as g,Tt as h,St as i,Cr as j,xr as k,Pr as l,Rt as m,Et as n,G as o,se as p,Se as q,_e as r,N as s,Ee as t,Ce as u,Pe as v,le as w,lo as x,H as y,Ae as z,_ as A,ti as B,ni as C};
|
package/dist/chunk-ARQF52V6.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{b as s,d as o}from"./chunk-7F4SZXI2.js";o();function i(e){return{id:e.id,ruleId:e.rule_id??void 0,taskId:e.task_id??void 0,status:e.status,target:JSON.parse(e.target),content:e.content,attempts:e.attempts,error:e.error??void 0,createdAt:e.created_at,deliveredAt:e.delivered_at??void 0,expiresAt:e.expires_at,source:e.source,messageType:e.message_type??void 0}}var u=1440*60*1e3;function p(e){s().prepare(`
|
|
2
|
-
INSERT INTO delivery_log (id, rule_id, task_id, status, target, content,
|
|
3
|
-
attempts, error, created_at, delivered_at, expires_at, source, message_type)
|
|
4
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
5
|
-
`).run(e.id,e.ruleId??null,e.taskId??null,e.status,JSON.stringify(e.target),e.content,e.attempts,e.error??null,e.createdAt,e.deliveredAt??null,e.expiresAt,e.source??null,e.messageType??null)}function g(e,t,r){s().prepare("UPDATE delivery_log SET status = ?, error = ?, attempts = attempts + 1 WHERE id = ?").run(t,r??null,e)}function E(e){s().prepare("UPDATE delivery_log SET status = 'delivered', delivered_at = ?, attempts = attempts + 1 WHERE id = ?").run(Date.now(),e)}function D(e,t=100){let r=s(),a=Date.now(),n=e?"SELECT * FROM delivery_log WHERE status = 'pending' AND expires_at > ? AND source = ? ORDER BY created_at ASC LIMIT ?":"SELECT * FROM delivery_log WHERE status = 'pending' AND expires_at > ? ORDER BY created_at ASC LIMIT ?";return(e?r.prepare(n).all(a,e,t):r.prepare(n).all(a,t)).map(i)}function c(e,t=100){let r=s(),a=Date.now(),n=e?"SELECT * FROM delivery_log WHERE status = 'failed' AND expires_at > ? AND attempts < 3 AND source = ? ORDER BY created_at ASC LIMIT ?":"SELECT * FROM delivery_log WHERE status = 'failed' AND expires_at > ? AND attempts < 3 ORDER BY created_at ASC LIMIT ?";return(e?r.prepare(n).all(a,e,t):r.prepare(n).all(a,t)).map(i)}function v(){let e=s(),t=Date.now();return e.prepare("DELETE FROM delivery_log WHERE expires_at < ? AND status IN ('pending', 'failed')").run(t).changes}function _(e,t=50){return s().prepare("SELECT * FROM delivery_log WHERE task_id = ? ORDER BY created_at DESC LIMIT ?").all(e,t).map(i)}function y(e,t=50){return s().prepare("SELECT * FROM delivery_log WHERE rule_id = ? ORDER BY created_at DESC LIMIT ?").all(e,t).map(i)}export{u as a,p as b,g as c,E as d,D as e,c as f,v as g,_ as h,y as i};
|
package/dist/chunk-DKMF4B33.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{b as e,d as p}from"./chunk-7F4SZXI2.js";p();function i(t){return{id:t.id,taskId:t.task_id,index:t.index,type:t.type,content:t.content,toolName:t.tool_name??void 0,toolInput:t.tool_input?JSON.parse(t.tool_input):void 0,toolOutput:t.tool_output??void 0,truncated:t.truncated===1,timestamp:t.timestamp,tokenUsage:t.token_usage?JSON.parse(t.token_usage):void 0,planStepIndex:t.plan_step_index??void 0}}function a(t){e().prepare(`
|
|
2
|
-
INSERT INTO step_logs (id, task_id, "index", type, content, tool_name,
|
|
3
|
-
tool_input, tool_output, truncated, timestamp, token_usage, plan_step_index)
|
|
4
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
5
|
-
`).run(t.id,t.taskId,t.index,t.type,t.content,t.toolName??null,t.toolInput?JSON.stringify(t.toolInput):null,t.toolOutput??null,t.truncated?1:0,t.timestamp,t.tokenUsage?JSON.stringify(t.tokenUsage):null,t.planStepIndex??null)}function r(t,n=100,o=0){return e().prepare('SELECT * FROM step_logs WHERE task_id = ? ORDER BY "index" ASC LIMIT ? OFFSET ?').all(t,n,o).map(i)}export{a,r as b};
|
package/dist/chunk-KO7XBNPV.js
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import{a as B}from"./chunk-PFYYS7CI.js";import{a as C}from"./chunk-SWP2JC54.js";import{a as L,b as k,c as T,j as $}from"./chunk-LV4XLPCD.js";import{d as I,h as P,i as de}from"./chunk-YWUX3ZTO.js";import{b as _,d as se}from"./chunk-7F4SZXI2.js";import{c as D,h as ie}from"./chunk-MRTJFYPR.js";import{tool as p}from"@anthropic-ai/claude-agent-sdk";import{z as a}from"zod";import{v4 as le}from"uuid";function l(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}var ce={query:a.string().describe("Search query for memory retrieval"),roleId:a.string().optional().describe("Role ID to scope search (omit for cross-role)"),topK:a.number().optional().describe("Max results to return (default 5)")},pe={query:a.string().describe("Search query for memory retrieval"),topK:a.number().optional().describe("Max results to return (default 5)")},me={id:a.string().optional().describe("Memory ID to update. Omit to create new."),roleId:a.string().describe("Role ID to save memory under"),content:a.string().describe("Memory content text"),type:a.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:a.array(a.string()).optional().describe("Keywords for BM25 search"),importance:a.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:a.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},ue={id:a.string().optional().describe("Memory ID to update. Omit to create new."),content:a.string().describe("Memory content text"),type:a.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:a.array(a.string()).optional().describe("Keywords for BM25 search"),importance:a.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:a.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},N={id:a.string().describe("Memory ID to delete")};async function j(t,e){let r=t??e.roleId,n=e.topK??5,i=await B(r,e.query,{topK:n});return l({results:i.map(o=>({id:o.id,type:o.type,content:o.content,keywords:o.keywords,importance:o.importance,score:o.score}))})}async function F(t,e){let r=t??e.roleId;if(!r)return l({error:"roleId is required"});let n,i=!0;try{n=await C(e.content)}catch{i=!1}if(e.id){if(!k(e.id))return l({error:`Memory ${e.id} not found`});let v=T(e.id,{content:e.content,embedding:n,keywords:e.keywords,importance:e.importance,type:e.type});return l({id:e.id,action:"updated",success:v,embeddingUpdated:i})}let o=`mem-${le().slice(0,8)}`,s=Date.now();return L({id:o,roleId:r,type:e.type??"thought",content:e.content,embedding:n,keywords:e.keywords??[],importance:e.importance??3,sourceType:"manual",createdAt:s,lastAccessed:s,retrievedCount:0,tier:e.tier??"episodic"}),l({id:o,action:"created",success:!0,embeddingUpdated:i})}async function K(t,e){if(t){let r=k(e.id);if(!r)return l({error:`Memory ${e.id} not found`});if(r.roleId!==t)return l({error:`Memory ${e.id} does not belong to this role`})}return $(e.id),l({id:e.id,deleted:!0})}function Ue(t){return t?[p("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",pe,async e=>j(t,e)),p("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",ue,async e=>F(t,e)),p("delete_memory","Delete a memory by ID.",N,async e=>K(t,e))]:[p("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",ce,async e=>j(void 0,e)),p("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",me,async e=>F(void 0,e)),p("delete_memory","Delete a memory by ID.",N,async e=>K(void 0,e))]}import{accessSync as q,constants as H}from"fs";import{accessSync as fe,constants as ye,existsSync as U,realpathSync as be}from"fs";import{join as E}from"path";import{spawn as he}from"child_process";import{execFileSync as ge}from"child_process";var u=null;function f(){if(u)return u;let t=typeof import.meta.dirname=="string"?import.meta.dirname:__dirname??".",e=E(t,"landlock-exec","landlock-exec");if(U(e))return u=e,e;let r=process.env.PATH?.split(":").find(n=>U(E(n,"landlock-exec")));return r?(u=E(r,"landlock-exec"),u):e}var y=class{platform="landlock";async isAvailable(){if(process.platform!=="linux")return!1;try{fe(f(),ye.X_OK)}catch{return!1}try{return ge(f(),["--check"],{timeout:5e3,stdio:["ignore","pipe","pipe"]}),!0}catch{return!1}}spawn(e){let r=e.command??"node",n=e.args??[],i=[];for(let o of e.visiblePaths??[]){let s=o.mode==="rw"?"--rw":"--ro",d;try{d=be(o.path)}catch{d=o.path}i.push(s,d),d!==o.path&&i.push(s,o.path)}return i.push("--",r,...n),he(f(),i,{cwd:e.cwd,env:e.env,stdio:"pipe",signal:e.signal})}};function G(){if(process.platform==="linux")try{return q(f(),H.X_OK),"landlock"}catch{return"none"}if(process.platform==="darwin")try{return q("/usr/bin/sandbox-exec",H.X_OK),"sandbox-exec"}catch{return"none"}return"none"}ie();import{spawn as _e}from"child_process";import{readFileSync as z,writeFileSync as Pe,mkdtempSync as ke,realpathSync as A,rmSync as Ee}from"fs";import{join as c}from"path";import{tmpdir as Ae}from"os";de();var ve=["com.apple.Accessibility","com.apple.CoreGraphics","com.apple.SpeakSelection","com.apple.TimeMachine","com.apple.assistant","com.apple.assistant.backedup","com.apple.assistant.support"],xe=["com.apple.coreservices.appleevents"];function Se(t){if(!I.test(t))throw new Error(`Invalid bundle id for SBPL appleevent destination: ${t}`)}function V(t,e){return P(t)?.find(r=>r.id===e)}function we(t){if(!t)return"";let e=["","; ===== Role OS capability: Automation =====","(allow lsopen)","(allow mach-lookup",...xe.map(n=>` (global-name "${n}")`),")"],r=t.targets??[];for(let n of r)Se(n),e.push(`(allow appleevent-send (appleevent-destination "${n}"))`);return e.join(`
|
|
2
|
-
`)}function Re(t){return t?["","; ===== Role OS capability: Accessibility =====","(allow signal)","(allow mach-priv-host-port)","(allow mach-task-name)",'(allow mach-lookup (local-name "com.apple.axserver"))',"(allow user-preference-read",...ve.map(r=>` (preference-domain "${r}")`),")"].join(`
|
|
3
|
-
`):""}function X(t){let e=P(t);return e?.length?[we(V(e,"automation")),Re(V(e,"accessibility"))].filter(Boolean).join(`
|
|
4
|
-
`):""}var Y=D("sandbox-macos"),J="/usr/bin/sandbox-exec";function Oe(){let t=[c(typeof import.meta.dirname=="string"?import.meta.dirname:".","profiles","role-sandbox.sb"),c(typeof import.meta.dirname=="string"?import.meta.dirname:".","..","src","sandbox","profiles","role-sandbox.sb"),c(process.cwd(),"src","sandbox","profiles","role-sandbox.sb")];for(let e of t)try{return z(e,"utf-8"),e}catch{}return t[t.length-1]}var Me=Oe();function b(t){if(!t.startsWith("/"))throw new Error(`Sandbox path must be absolute: ${t}`);if(t.includes('"')||t.includes(")")||t.includes("(")||t.includes("$"))throw new Error(`Sandbox path contains invalid characters for SBPL: ${t}`)}function De(t){let e=[`
|
|
5
|
-
; ===== Per-Role writable paths =====`];for(let r of t){if(r.mode!=="rw")continue;let n;try{n=A(r.path)}catch{n=r.path}b(n),e.push(`(allow file-write* (subpath "${n}"))`),n!==r.path&&(b(r.path),e.push(`(allow file-write* (subpath "${r.path}"))`))}return e.join(`
|
|
6
|
-
`)}function Ie(t){if(!t.length)return"";let e=[`
|
|
7
|
-
; ===== Global read blacklist (deniedReadPaths) =====`];for(let r of t){let n;try{n=A(r)}catch{n=r}try{b(n),e.push(`(deny file-read-data (subpath "${n}"))`),e.push(`(deny file-read-metadata (subpath "${n}"))`),n!==r&&(b(r),e.push(`(deny file-read-data (subpath "${r}"))`),e.push(`(deny file-read-metadata (subpath "${r}"))`))}catch(i){Y.warn({path:r,error:i.message},"Skipping deniedReadPath: invalid for SBPL")}}return e.join(`
|
|
8
|
-
`)}var h=class{platform="sandbox-exec";async isAvailable(){try{let{existsSync:e}=await import("fs");return e(J)}catch{return!1}}spawn(e){let{command:r,args:n,cwd:i,env:o,signal:s,visiblePaths:d,deniedReadPaths:v,osCapabilities:Z}=e,ee=z(Me,"utf-8"),te=De(d),re=Ie(v??[]),ne=X(Z),oe=ee+te+re+ne+`
|
|
9
|
-
`,x=A(ke(c(Ae(),"adam-sandbox-"))),S=c(x,"role.sb");Pe(S,oe,"utf-8");let w=x,R=o?.HOME??process.env.HOME??"/tmp",ae={...o,TMPDIR:w,CLAUDE_CODE_TMPDIR:w,CLAUDE_CONFIG_DIR:c(R,".claude")};Y.debug({command:r,visiblePaths:d.length,profilePath:S},"Spawning sandboxed process");let M=_e(J,["-f",S,"-D",`TMPDIR=${w}`,"-D",`CLAUDE_CONFIG=${c(R,".claude")}`,"-D",`HOME_CACHE=${c(R,"Library","Caches")}`,r,...n],{cwd:i,env:ae,stdio:"pipe",signal:s});return M.on("exit",()=>{try{Ee(x,{recursive:!0,force:!0})}catch{}}),M}};import{spawn as Ce}from"child_process";var m=null,W=null,g=null;function Le(){if(m)return m;let t=W??G();return W=t,t==="sandbox-exec"?m=new h:t==="landlock"?m=new y:m=new O(t),m}async function pt(){return g!==null||(g=await Le().isAvailable()),g}var O=class{platform;constructor(e){this.platform=e}async isAvailable(){return!1}spawn(e){let r=e.command??"node",n=e.args??[];return Ce(r,n,{cwd:e.cwd,env:e.env,stdio:"pipe",signal:e.signal})}};se();function Te(t){return{id:t.id,roleId:t.role_id??void 0,taskPattern:t.task_pattern,maxRiskLevel:t.max_risk_level,createdAt:t.created_at,createdByTaskId:t.created_by_task_id??void 0}}var Q={low:1,medium:2,high:3};function ft(t){_().prepare(`
|
|
10
|
-
INSERT INTO approval_rules (id, role_id, task_pattern, max_risk_level, created_at, created_by_task_id)
|
|
11
|
-
VALUES (?, ?, ?, ?, ?, ?)
|
|
12
|
-
`).run(t.id,t.roleId??null,t.taskPattern,t.maxRiskLevel,t.createdAt,t.createdByTaskId??null)}function yt(t,e,r){let i=_().prepare("SELECT * FROM approval_rules ORDER BY created_at DESC").all();for(let o of i)if(!(o.role_id&&o.role_id!==t)&&!(Q[r]>Q[o.max_risk_level]))try{if(new RegExp(o.task_pattern,"i").test(e))return Te(o)}catch{}}export{ft as a,yt as b,Ue as c,Le as d,pt as e};
|
package/dist/chunk-LV4XLPCD.js
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import{l as f,r as h}from"./chunk-YWUX3ZTO.js";import{b as u,d as E}from"./chunk-7F4SZXI2.js";E();h();function l(e){return{id:e.id,roleId:e.role_id,type:e.type,content:e.content,embedding:e.embedding?new Float32Array(e.embedding.buffer,e.embedding.byteOffset,e.embedding.byteLength/4):void 0,keywords:e.keywords?JSON.parse(e.keywords):[],importance:e.importance,sourceType:e.source_type,sourceTaskId:e.source_task_id??void 0,evidence:e.evidence?JSON.parse(e.evidence):void 0,createdAt:e.created_at,lastAccessed:e.last_accessed,retrievedCount:e.retrieved_count,tier:e.tier,supersededBy:e.superseded_by??void 0}}function b(e){return Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function v(e){u().prepare(`
|
|
2
|
-
INSERT INTO memories (id, role_id, type, content, embedding, keywords,
|
|
3
|
-
importance, source_type, source_task_id, evidence,
|
|
4
|
-
created_at, last_accessed, retrieved_count, tier, superseded_by)
|
|
5
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
6
|
-
`).run(e.id,e.roleId,e.type,e.content,e.embedding?b(e.embedding):null,JSON.stringify(e.keywords),e.importance,e.sourceType,e.sourceTaskId??null,e.evidence?JSON.stringify(e.evidence):null,e.createdAt,e.lastAccessed,e.retrievedCount,e.tier,e.supersededBy??null)}function C(e){let s=u().prepare("SELECT * FROM memories WHERE id = ?").get(e);return s?l(s):void 0}function W(e,r){let s=u(),t=[],n=[];return r.content!==void 0&&(t.push("content = ?"),n.push(r.content)),r.embedding!==void 0&&(t.push("embedding = ?"),n.push(b(r.embedding))),r.keywords!==void 0&&(t.push("keywords = ?"),n.push(JSON.stringify(r.keywords))),r.importance!==void 0&&(t.push("importance = ?"),n.push(r.importance)),r.type!==void 0&&(t.push("type = ?"),n.push(r.type)),t.length===0?!0:(t.push("last_accessed = ?"),n.push(Date.now()),n.push(e),s.prepare(`UPDATE memories SET ${t.join(", ")} WHERE id = ?`).run(...n).changes>0)}function L(e){u().prepare("UPDATE memories SET retrieved_count = retrieved_count + 1, last_accessed = ? WHERE id = ?").run(Date.now(),e)}function F(e,r){let t=u().prepare("UPDATE memories SET superseded_by = ? WHERE id = ?"),n=0;for(let c of e){let i=t.run(r,c);n+=i.changes}return n}function w(e){return u().prepare("SELECT COUNT(*) as count FROM memories WHERE role_id = ?").get(e).count}function x(e,r=100,s=0){return u().prepare("SELECT * FROM memories WHERE role_id = ? ORDER BY created_at DESC LIMIT ? OFFSET ?").all(e,r,s).map(l)}function M(e,r){let s=0,t=0,n=0;for(let i=0;i<e.length;i++)s+=e[i]*r[i],t+=e[i]*e[i],n+=r[i]*r[i];let c=Math.sqrt(t)*Math.sqrt(n);return c===0?0:s/c}function R(e,r,s,t){let n=u(),c=["embedding IS NOT NULL"],i=[];e&&(c.push("role_id = ?"),i.push(e)),t?.excludeSuperseded&&c.push("superseded_by IS NULL"),t?.tiers&&t.tiers.length>0&&(c.push(`tier IN (${t.tiers.map(()=>"?").join(",")})`),i.push(...t.tiers));let a=`SELECT * FROM memories WHERE ${c.join(" AND ")}
|
|
7
|
-
ORDER BY importance DESC, created_at DESC
|
|
8
|
-
LIMIT ?`;return i.push(Math.min(s*10,1e3)),n.prepare(a).all(...i).map(o=>{let d=new Float32Array(o.embedding.buffer,o.embedding.byteOffset,o.embedding.byteLength/4);return{row:o,score:M(r,d)}}).sort((o,d)=>d.score-o.score).slice(0,s).map(o=>l(o.row))}function _(e){let r=e.split(/\s+/).filter(Boolean);return r.length===0?'""':r.map(t=>`"${t.replace(/"/g,'""')}"`).join(" OR ")}function S(e,r,s){let t=u(),n=_(r);return e?t.prepare(`
|
|
9
|
-
SELECT m.* FROM memories m
|
|
10
|
-
JOIN memories_fts fts ON m.rowid = fts.rowid
|
|
11
|
-
WHERE memories_fts MATCH ? AND m.role_id = ?
|
|
12
|
-
ORDER BY rank
|
|
13
|
-
LIMIT ?
|
|
14
|
-
`).all(n,e,s).map(l):t.prepare(`
|
|
15
|
-
SELECT m.* FROM memories m
|
|
16
|
-
JOIN memories_fts fts ON m.rowid = fts.rowid
|
|
17
|
-
WHERE memories_fts MATCH ?
|
|
18
|
-
ORDER BY rank
|
|
19
|
-
LIMIT ?
|
|
20
|
-
`).all(n,s).map(l)}function H(e){u().prepare("DELETE FROM memories WHERE id = ?").run(e)}var y={recency:.5,relevance:3,importance:2},N=.9;function T(e){let s=(Date.now()-e)/(1e3*60*60*24);return Math.min(1,Math.max(0,Math.pow(N,s)))}function k(e,r,s,t=y){let n=T(e),c=Math.min(1,Math.max(0,r)),i=s/5;return t.recency*n+t.relevance*c+t.importance*i}function I(e){return f(e)?.preferences?.scoringWeights??y}var O={vectorWeight:.6,bm25Weight:.4};function B(e,r=1e4,s=90){let t=u(),n=0,c=Date.now()-10080*60*1e3,i=t.prepare("DELETE FROM memories WHERE role_id = ? AND superseded_by IS NOT NULL AND created_at < ?").run(e,c);n+=i.changes;let a=Date.now()-720*60*60*1e3,m=t.prepare("DELETE FROM memories WHERE role_id = ? AND retrieved_count = 0 AND importance <= 2 AND created_at < ?").run(e,a);n+=m.changes;let g=Date.now()-s*24*60*60*1e3,o=t.prepare("DELETE FROM memories WHERE role_id = ? AND importance < 4 AND created_at < ?").run(e,g);n+=o.changes;let d=t.prepare("SELECT COUNT(*) as cnt FROM memories WHERE role_id = ?").get(e);if(d.cnt>r){let p=d.cnt-r;t.prepare(`
|
|
21
|
-
DELETE FROM memories WHERE id IN (
|
|
22
|
-
SELECT id FROM memories WHERE role_id = ? AND tier != 'semantic'
|
|
23
|
-
ORDER BY importance ASC, retrieved_count ASC, created_at ASC
|
|
24
|
-
LIMIT ?
|
|
25
|
-
)
|
|
26
|
-
`).run(e,p),n+=p}return n}function U(e,r,s,t,n=O,c){let i=R(e,r,t*2,c),a=S(e,s,t*2),m=new Map;for(let o=0;o<i.length;o++){let d=i[o];m.set(d.id,{node:d,vectorScore:i.length>1?1-o/(i.length-1):1,bm25Score:0})}for(let o=0;o<a.length;o++){let d=m.get(a[o].id),p=a.length>1?1-o/(a.length-1):1;d?d.bm25Score=p:m.set(a[o].id,{node:a[o],vectorScore:0,bm25Score:p})}return Array.from(m.values()).map(({node:o,vectorScore:d,bm25Score:p})=>({node:o,score:n.vectorWeight*d+n.bm25Weight*p})).sort((o,d)=>d.score-o.score).slice(0,t).map(o=>o.node)}export{v as a,C as b,W as c,L as d,F as e,w as f,x as g,R as h,S as i,H as j,y as k,T as l,k as m,I as n,O as o,B as p,U as q};
|
package/dist/chunk-OY2KVSIX.js
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{b as i,d as a}from"./chunk-7F4SZXI2.js";a();function d(e){return{id:e.id,parentId:e.parent_id??void 0,status:e.status,prompt:e.prompt,originalPrompt:e.original_prompt??void 0,config:JSON.parse(e.config),result:e.result??void 0,error:e.error??void 0,sdkSessionId:e.sdk_session_id??void 0,templateId:e.template_id??void 0,roleId:e.role_id??void 0,stepId:e.step_id??void 0,sourceSessionId:e.source_session_id??void 0,deliverTo:e.deliver_to?JSON.parse(e.deliver_to):void 0,reportTo:e.report_to?JSON.parse(e.report_to):void 0,createdAt:e.created_at,startedAt:e.started_at??void 0,completedAt:e.completed_at??void 0,costUsd:e.cost_usd??void 0,tokenUsage:e.token_usage?JSON.parse(e.token_usage):void 0,numTurns:e.num_turns??void 0,totalDurationMs:e.total_duration_ms??void 0,blockReason:e.block_reason_json?JSON.parse(e.block_reason_json):void 0}}function c(e){i().prepare(`
|
|
2
|
-
INSERT INTO tasks (id, parent_id, status, prompt, original_prompt, config, result, error,
|
|
3
|
-
sdk_session_id, template_id, role_id, step_id, source_session_id, notify_targets, deliver_to, report_to,
|
|
4
|
-
created_at, started_at, completed_at,
|
|
5
|
-
cost_usd, token_usage, num_turns, total_duration_ms)
|
|
6
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
7
|
-
`).run(e.id,e.parentId??null,e.status,e.prompt,e.originalPrompt??null,JSON.stringify(e.config),e.result??null,e.error??null,e.sdkSessionId??null,e.templateId??null,e.roleId??null,e.stepId??null,e.sourceSessionId??null,null,e.deliverTo?JSON.stringify(e.deliverTo):null,e.reportTo?JSON.stringify(e.reportTo):null,e.createdAt,e.startedAt??null,e.completedAt??null,e.costUsd??null,e.tokenUsage?JSON.stringify(e.tokenUsage):null,e.numTurns??null,e.totalDurationMs??null)}function g(e){let r=i().prepare("SELECT * FROM tasks WHERE id = ?").get(e);return r?d(r):void 0}function f(e,n){let r=i(),t=[],s=[],u={parentId:"parent_id",status:"status",prompt:"prompt",result:"result",error:"error",sdkSessionId:"sdk_session_id",templateId:"template_id",roleId:"role_id",stepId:"step_id",sourceSessionId:"source_session_id",originalPrompt:"original_prompt",startedAt:"started_at",completedAt:"completed_at",costUsd:"cost_usd",numTurns:"num_turns",totalDurationMs:"total_duration_ms"};for(let[o,l]of Object.entries(u))o in n&&(t.push(`${l} = ?`),s.push(n[o]??null));"config"in n&&(t.push("config = ?"),s.push(JSON.stringify(n.config))),"tokenUsage"in n&&(t.push("token_usage = ?"),s.push(n.tokenUsage?JSON.stringify(n.tokenUsage):null)),"deliverTo"in n&&(t.push("deliver_to = ?"),s.push(n.deliverTo?JSON.stringify(n.deliverTo):null)),"reportTo"in n&&(t.push("report_to = ?"),s.push(n.reportTo?JSON.stringify(n.reportTo):null)),"blockReason"in n&&(t.push("block_reason_json = ?"),s.push(n.blockReason?JSON.stringify(n.blockReason):null)),t.length!==0&&(s.push(e),r.prepare(`UPDATE tasks SET ${t.join(", ")} WHERE id = ?`).run(...s))}function m(e,n=100,r=0,t){let s=i(),u="SELECT * FROM tasks",o=[],l=[];return e&&(o.push("status = ?"),l.push(e)),t&&(o.push("role_id = ?"),l.push(t)),o.length>0&&(u+=" WHERE "+o.join(" AND ")),u+=" ORDER BY created_at DESC LIMIT ? OFFSET ?",l.push(n,r),s.prepare(u).all(...l).map(d)}function T(e){return i().prepare("SELECT * FROM tasks WHERE parent_id = ? ORDER BY created_at ASC").all(e).map(d)}function k(e){return i().prepare("SELECT COALESCE(SUM(cost_usd), 0) as total FROM tasks WHERE completed_at >= ? AND cost_usd IS NOT NULL").get(e).total}export{c as a,g as b,f as c,m as d,T as e,k as f};
|
package/dist/chunk-PFYYS7CI.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import{a as l}from"./chunk-SWP2JC54.js";import{d as f,k as g,m as p,n as h,o as M,q as b}from"./chunk-LV4XLPCD.js";function v(t,n){let i=0,s=0,m=0;for(let e=0;e<t.length;e++)i+=t[e]*n[e],s+=t[e]*t[e],m+=n[e]*n[e];let o=Math.sqrt(s)*Math.sqrt(m);return o===0?0:i/o}async function S(t,n,i={}){let s=i.topK??10,m=i.hybridConfig??M,o;try{o=await l(n)}catch{}let e=o??new Float32Array(384),a=b(t,e,n,s*2,m,{excludeSuperseded:!0}),d=t?h(t):g,y=a.map(r=>{let u=r.embedding?v(e,r.embedding):0,C=Math.min(.3,(r.retrievedCount??0)*.05),x=p(r.createdAt,u,r.importance,d)+C;return{...r,score:x}});y.sort((r,u)=>u.score-r.score);let c=y.slice(0,s);for(let r of c)f(r.id);return c}async function T(t,n,i=5,s=2e3){try{let{estimateTokens:m}=await import("./token-estimator-HMPVGDCN.js"),o=await S(n,t,{topK:i});if(o.length===0)return"";let e=[],a=0,d=m(`[Memory Context \u2014 retrieved from prior interactions]
|
|
2
|
-
|
|
3
|
-
[User Request]
|
|
4
|
-
`);for(let c of o){let r=m(`- [${c.tier??"episodic"}] ${c.content}
|
|
5
|
-
`);if(a+r+d>s)break;e.push(c),a+=r}return e.length===0?"":`[Memory Context \u2014 retrieved from prior interactions]
|
|
6
|
-
${e.map(c=>`- [${c.tier??"episodic"}] ${c.content}`).join(`
|
|
7
|
-
`)}
|
|
8
|
-
|
|
9
|
-
[User Request]
|
|
10
|
-
`}catch{return""}}async function q(t,n,i,s={}){return(await S(t,n,s)).filter(o=>i.includes(o.tier??"episodic"))}export{S as a,T as b,q as c};
|
package/dist/chunk-QPIWPQWM.js
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import{b as o,d as u}from"./chunk-7F4SZXI2.js";u();import{v4 as a}from"uuid";function R(t){o().prepare(`
|
|
2
|
-
INSERT INTO evolution_audit (id, timestamp, old_rules, new_rules, diff, trigger_task_id, role_id, source)
|
|
3
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
4
|
-
`).run(a(),t.timestamp,t.oldRules,t.newRules,t.diff,t.triggerTaskId??null,t.roleId??null,t.source??"reflection")}function f(t=100,e=0){return o().prepare(`
|
|
5
|
-
SELECT id, timestamp, old_rules as oldRules, new_rules as newRules, diff,
|
|
6
|
-
trigger_task_id as triggerTaskId, role_id as roleId, source
|
|
7
|
-
FROM evolution_audit
|
|
8
|
-
ORDER BY timestamp DESC
|
|
9
|
-
LIMIT ? OFFSET ?
|
|
10
|
-
`).all(t,e)}function g(t,e=100,i=0){return o().prepare(`
|
|
11
|
-
SELECT id, timestamp, old_rules as oldRules, new_rules as newRules, diff,
|
|
12
|
-
trigger_task_id as triggerTaskId, role_id as roleId, source
|
|
13
|
-
FROM evolution_audit
|
|
14
|
-
WHERE role_id = ?
|
|
15
|
-
ORDER BY timestamp DESC
|
|
16
|
-
LIMIT ? OFFSET ?
|
|
17
|
-
`).all(t,e,i)}function c(t){return o().prepare(`
|
|
18
|
-
SELECT id, timestamp, old_rules as oldRules, new_rules as newRules, diff,
|
|
19
|
-
trigger_task_id as triggerTaskId, role_id as roleId, source
|
|
20
|
-
FROM evolution_audit
|
|
21
|
-
WHERE role_id = ?
|
|
22
|
-
ORDER BY timestamp DESC
|
|
23
|
-
LIMIT 1
|
|
24
|
-
`).get(t)}function _(t,e){let i=t.split(`
|
|
25
|
-
`).filter(Boolean),s=e.split(`
|
|
26
|
-
`).filter(Boolean),n=s.filter(l=>!i.includes(l)),d=i.filter(l=>!s.includes(l)),r=[];return n.length>0&&r.push(`+ ${n.join(`
|
|
27
|
-
+ `)}`),d.length>0&&r.push(`- ${d.join(`
|
|
28
|
-
- `)}`),r.join(`
|
|
29
|
-
`)||"(no changes)"}export{R as a,f as b,g as c,c as d,_ as e};
|
package/dist/chunk-UQDC3X6O.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import{b as n,d as o}from"./chunk-7F4SZXI2.js";o();function a(e){return{id:e.id,sessionId:e.session_id,role:e.role,content:e.content,source:{type:e.source_type},taskId:e.task_id??void 0,channelMessageId:e.channel_message_id??void 0,metadata:e.metadata?JSON.parse(e.metadata):void 0,createdAt:e.created_at}}function c(e){n().prepare(`
|
|
2
|
-
INSERT INTO chat_messages (id, session_id, role, content, source_type, task_id,
|
|
3
|
-
channel_message_id, metadata, created_at)
|
|
4
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
5
|
-
`).run(e.id,e.sessionId,e.role,e.content,e.source.type,e.taskId??null,e.channelMessageId??null,e.metadata?JSON.stringify(e.metadata):null,e.createdAt)}function g(e,s=100,t=0){return n().prepare("SELECT * FROM chat_messages WHERE session_id = ? ORDER BY created_at ASC LIMIT ? OFFSET ?").all(e,s,t).map(a)}function u(e,s){return n().prepare("SELECT * FROM chat_messages WHERE session_id = ? ORDER BY created_at DESC LIMIT ?").all(e,s).reverse().map(a)}function E(e){n().prepare("DELETE FROM chat_messages WHERE session_id = ?").run(e)}function p(e){let t=n().prepare("SELECT * FROM chat_messages WHERE task_id = ? LIMIT 1").get(e);return t?a(t):void 0}function _(e,s=50,t=0){return n().prepare(`
|
|
6
|
-
SELECT m.* FROM chat_messages m
|
|
7
|
-
JOIN chat_sessions s ON m.session_id = s.id
|
|
8
|
-
WHERE s.source_type = 'channel' AND s.source_channel_id = ?
|
|
9
|
-
ORDER BY m.created_at DESC LIMIT ? OFFSET ?
|
|
10
|
-
`).all(e,s,t).map(a)}export{c as a,g as b,u as c,E as d,p as e,_ as f};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i}from"./chunk-ARQF52V6.js";import"./chunk-7F4SZXI2.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.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-ZAPYG7G4.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d}from"./chunk-EJBGJLA2.js";import"./chunk-W7U3ASGR.js";import"./chunk-3HZE5DQZ.js";import"./chunk-TTP7QRAQ.js";import"./chunk-UQDC3X6O.js";import"./chunk-OY2KVSIX.js";import"./chunk-KUJFQDT5.js";import"./chunk-IZ3WZHCM.js";import"./chunk-L7JP7DUO.js";import"./chunk-ARQF52V6.js";import"./chunk-7F4SZXI2.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.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-QPIWPQWM.js";import"./chunk-7F4SZXI2.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";export{a as createEvolutionAudit,e as generateDiff,d as getLatestRoleEvolution,b as listEvolutionAudit,c as listEvolutionAuditByRole};
|
package/dist/learner-ACHENH6R.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as l,e as D,f as S,g as $}from"./chunk-6M2QCKAS.js";import{b as h}from"./chunk-DKMF4B33.js";import{b as u}from"./chunk-OY2KVSIX.js";import{e as R,g as T,j as C}from"./chunk-6XVWIRR2.js";import{l as k,n as x,r as N}from"./chunk-YWUX3ZTO.js";import"./chunk-XTOOD44S.js";import"./chunk-7F4SZXI2.js";import"./chunk-WBAPIPST.js";import{c as d,h as y}from"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";y();var w=d("agent");function I(n){let o=l(n);if(!o){w.debug({taskId:n},"No plan found for task, skipping review");return}let i=h(n,1e3),s=o.plan.steps,a=i.filter(e=>e.type==="tool_result"||e.type==="permission_denied").map(e=>({toolName:e.toolName??"unknown",output:e.content,planStepIndex:e.planStepIndex,permissionDenied:e.type==="permission_denied"})),t=[],r=new Set(a.map(e=>e.planStepIndex).filter(e=>e!==void 0));for(let e of s)r.has(e.index)||t.push({stepIndex:e.index,planned:e.description,actual:"Not executed",deviationType:"skipped"});let c=a.filter(e=>e.planStepIndex===void 0);for(let e of c)t.push({stepIndex:-1,planned:"",actual:`${e.toolName}: ${e.output.slice(0,200)}`,deviationType:"added"});let b=a.filter(e=>e.permissionDenied);for(let e of b)t.push({stepIndex:e.planStepIndex??-1,planned:e.planStepIndex!==void 0?s.find(E=>E.index===e.planStepIndex)?.description??"Unknown":"",actual:`PERMISSION DENIED: ${e.toolName}`,deviationType:"failed"});let p=s.length,m=a.length,g=p>0?Math.max(0,1-t.filter(e=>e.deviationType!=="added").length/p):1,v={stepsPlanned:p,stepsExecuted:m,deviations:t,overallAccuracy:g};return S(o.id,v),w.info({taskId:n,planId:o.id,stepsPlanned:p,stepsExecuted:m,deviationCount:t.length,accuracy:g},"Deviation report generated"),v}function P(n){return n.deviations.filter(i=>i.deviationType==="failed"||i.deviationType==="skipped").length===0&&n.overallAccuracy>=.7}N();C();y();var f=d("agent");function L(n,o){let i=[],a=u(n)?.prompt.slice(0,100)??"unknown task";P(o)&&i.push(`[+] Task "${a}" completed successfully with ${o.overallAccuracy*100}% plan accuracy (${o.stepsExecuted} steps). [sourceTaskId:${n}]`);for(let t of o.deviations)switch(t.deviationType){case"skipped":i.push(`[-] Planned step "${t.planned}" was skipped during "${a}". Consider if this step is necessary for similar tasks. [sourceTaskId:${n}]`);break;case"failed":i.push(`[-] Step failed: "${t.actual}" during "${a}". Check permissions and tool availability. [sourceTaskId:${n}]`);break;case"added":i.push(`[~] Unplanned action: "${t.actual}" during "${a}". Consider adding to plan for similar tasks. [sourceTaskId:${n}]`);break;case"modified":i.push(`[~] Step modified: planned "${t.planned}" but did "${t.actual}" during "${a}". [sourceTaskId:${n}]`);break}return i}async function z(n){let o=l(n);if(!o){f.debug({taskId:n},"No plan for task, skipping review/learn");return}let i=I(n);if(!i)return;let s=L(n,i);if(s.length===0)return;$(o.id,s);let a=u(n);if(a?.roleId){let t=k(a.roleId);if(t){let r=[...t.learnedRules,...s];x(a.roleId,{learnedRules:r});let c=R(t.name);T(c,{...t,learnedRules:r}),f.info({roleId:a.roleId,newRulesCount:s.length},"Role learnedRules updated and CLAUDE.md written")}}D(o.id,"completed"),f.info({taskId:n,planId:o.id,rulesExtracted:s.length,accuracy:i.overallAccuracy},"Task review and learning completed")}export{L as extractRulesFromDeviation,z as processTaskReview};
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{a as v}from"./chunk-QPIWPQWM.js";import{a as p}from"./chunk-SWP2JC54.js";import{a as l,g as w}from"./chunk-LV4XLPCD.js";import{a as h}from"./chunk-S6OV7Z6K.js";import{b as g}from"./chunk-DKMF4B33.js";import"./chunk-YWUX3ZTO.js";import"./chunk-XTOOD44S.js";import{b as u,d as M}from"./chunk-7F4SZXI2.js";import"./chunk-WBAPIPST.js";import{c as y,h as b}from"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";b();M();import{v4 as $}from"uuid";var x=y("manager"),d=150,C=50;function N(e){return u().prepare("SELECT importance_trigger_curr FROM roles WHERE id = ?").get(e)?.importance_trigger_curr??d}function f(e,t){u().prepare("UPDATE roles SET importance_trigger_curr = ? WHERE id = ?").run(t,e)}function _(e,t){let r=N(e)-t;return f(e,r),r<=0}async function S(e){let t=w(e,C,0);if(t.length===0){f(e,d);return}let r=`Based on these recent experiences, what are the key insights and patterns?
|
|
2
|
-
|
|
3
|
-
${t.slice(0,20).map((c,m)=>`${m+1}. [${c.type}] (importance: ${c.importance}) ${c.content}`).join(`
|
|
4
|
-
`)}
|
|
5
|
-
|
|
6
|
-
Provide 1-3 high-level insights.`,o;try{o=(await h(r,"You are an agent self-reflection system. Analyze the experiences and produce concise, actionable insights. Respond with 1-3 high-level insights, each on its own line.")).trim()||E(t)}catch{o=E(t)}let i;try{i=await p(o)}catch{}let a=o.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(c=>c.length>2),s={id:$(),roleId:e,type:"reflection",content:o,embedding:i,keywords:[...new Set(a)].slice(0,20),importance:5,sourceType:"reflection",evidence:t.slice(0,10).map(c=>c.id),createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"semantic"};l(s);try{let{markSuperseded:c}=await import("./memories-LXH4VHCH.js"),m=t.slice(0,10).map(T=>T.id);c(m,s.id)}catch{}try{v({timestamp:Date.now(),oldRules:"",newRules:o,diff:o,roleId:e,source:"reflection"})}catch{}f(e,d),x.info({roleId:e,preview:o.slice(0,100)},"Generated reflection")}function E(e){let t=e.filter(i=>i.type==="event"),n=t.filter(i=>i.content.includes("Error")||i.content.includes("failed")),r=t.filter(i=>i.content.includes("Modified file")),o=[];return r.length>0&&o.push(`Made ${r.length} file modifications in recent tasks.`),n.length>0&&o.push(`Encountered ${n.length} errors.`),t.length>0&&o.push(`Total ${t.length} significant events observed.`),o.length>0?`Reflection: ${o.join(" ")}`:"Reflection: No significant patterns observed in recent activity."}async function R(e,t){_(e,t)&&await S(e)}import{v4 as A}from"uuid";function L(e){let t=e.toolName,n=e.toolOutput||e.content;if(t==="Write"||t==="Edit")return{content:`Modified file via ${t}: ${n.slice(0,400)}`,importance:4,type:"event"};if(t==="Bash"){let r=e.toolInput?.command?.slice(0,100)||"Bash";return n.includes("FAIL")||n.includes("error:")||n.includes("Error:")?{content:`Command failed: ${r} ${n.slice(0,300)}`,importance:4,type:"event"}:n.includes("success")||n.includes("done")||n.includes("OK")?{content:`Command succeeded: ${r}`,importance:2,type:"event"}:{content:`Executed: ${r}`,importance:1,type:"event"}}return t==="Read"?{content:`Read file: ${e.toolInput?.file_path||e.toolInput?.path||"unknown"}`,importance:1,type:"thought"}:t==="Glob"||t==="Grep"?{content:`Searched: ${t} - ${e.toolInput?.pattern||"query"}`,importance:2,type:"thought"}:null}function F(e){let t=g(e,500,0),n=[];for(let r of t)if((r.type==="tool_result"||r.type==="tool_call")&&r.toolName){let o=L(r);o&&n.push(o)}else r.type==="error"&&n.push({content:`Error occurred: ${r.content.slice(0,400)}`,importance:4,type:"event"});return{facts:n}}function k(e){let t=e.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(n=>n.length>2);return[...new Set(t)].slice(0,20)}async function V(e,t){let n=!1;try{let{searchByBM25:i}=await import("./memories-LXH4VHCH.js");n=i(t,e,5).filter(s=>s.sourceTaskId===e).some(s=>s.type==="thought")}catch{}let{facts:r}=F(e),o=0;for(let i of r){if(n&&i.importance<=2)continue;let a=i.content.slice(0,500),s;try{s=await p(a)}catch{}let c=k(a),m={id:A(),roleId:t,type:i.type,content:a,embedding:s,keywords:c,importance:i.importance,sourceType:"task_complete",sourceTaskId:e,createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"episodic"};l(m),o++,await R(t,i.importance)}return o}export{F as extractKeyFacts,V as processTaskCompletion};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c}from"./chunk-PFYYS7CI.js";import"./chunk-SWP2JC54.js";import"./chunk-LV4XLPCD.js";import"./chunk-YWUX3ZTO.js";import"./chunk-XTOOD44S.js";import"./chunk-7F4SZXI2.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";export{b as getRelevantMemoryContext,a as queryMemory,c as queryMemoryByTier};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c}from"./chunk-KUJFQDT5.js";import"./chunk-IZ3WZHCM.js";import"./chunk-L7JP7DUO.js";import"./chunk-ARQF52V6.js";import"./chunk-7F4SZXI2.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";export{a as OutboundGateway,b as getOutboundGateway,c as isRecentlySent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{e as a,f as b,g as c,h as d,j as e}from"./chunk-6XVWIRR2.js";import"./chunk-YWUX3ZTO.js";import"./chunk-XTOOD44S.js";import"./chunk-7F4SZXI2.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";e();export{b as ensureRoleWorkspace,a as getRoleWorkspacePath,d as syncRoleSettings,c as writeRoleCLAUDEmd};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p}from"./chunk-UYOLAFUR.js";import"./chunk-SWP2JC54.js";import"./chunk-TTP7QRAQ.js";import"./chunk-LV4XLPCD.js";import"./chunk-UQDC3X6O.js";import"./chunk-L7JP7DUO.js";import"./chunk-5AUQIK3Q.js";import"./chunk-YVVKUPGL.js";import"./chunk-7IFLU3CY.js";import"./chunk-OFTIPZTH.js";import"./chunk-YWUX3ZTO.js";import"./chunk-XTOOD44S.js";import"./chunk-7F4SZXI2.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.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{e as a}from"./chunk-XIQVXRZH.js";import"./chunk-YKMWAVUH.js";import"./chunk-N4ES7TCL.js";import"./chunk-C2SD2NMZ.js";import"./chunk-S6OV7Z6K.js";import"./chunk-DKMF4B33.js";import"./chunk-OY2KVSIX.js";import"./chunk-KUJFQDT5.js";import"./chunk-IZ3WZHCM.js";import"./chunk-6XVWIRR2.js";import"./chunk-L7JP7DUO.js";import"./chunk-ARQF52V6.js";import"./chunk-5AUQIK3Q.js";import"./chunk-YVVKUPGL.js";import"./chunk-7IFLU3CY.js";import"./chunk-OFTIPZTH.js";import"./chunk-YWUX3ZTO.js";import"./chunk-XTOOD44S.js";import"./chunk-7F4SZXI2.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";export{a as WorkflowExecutor};
|