adam-agent-server 1.4.0 → 1.5.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-W5AOIGEQ.js +1 -0
- package/dist/{approval-handler-JZSXM4AD.js → approval-handler-ORD4MUVM.js} +1 -1
- package/dist/audit-manager-YCJT2WP5.js +1 -0
- package/dist/bree-engine-R5YLSDCL.js +1 -0
- package/dist/{channels-PUOPR5Y2.js → channels-HYSB2EEK.js} +1 -1
- package/dist/channels-JCMPPQED.js +1 -0
- package/dist/{chunk-KO5AFX5U.js → chunk-23VZKIB6.js} +1 -1
- package/dist/{chunk-GYHOPV4Q.js → chunk-2DLVAKH7.js} +1 -1
- package/dist/chunk-2YAP4YJV.js +57 -0
- package/dist/{chunk-HYDCXE5K.js → chunk-5S6BMWD2.js} +1 -1
- package/dist/chunk-5XUR3M23.js +12 -0
- package/dist/chunk-6775OYXA.js +47 -0
- package/dist/{chunk-KOWFPY2J.js → chunk-6FXNB7NE.js} +1 -1
- package/dist/{chunk-QQWRV23T.js → chunk-7L2WQM7N.js} +1 -1
- package/dist/{chunk-L4Y3GR6W.js → chunk-BR2JY5X2.js} +1 -1
- package/dist/{chunk-7BSWC62F.js → chunk-C6BOQJJF.js} +1 -1
- package/dist/{chunk-DMZM7RU6.js → chunk-DZEVMYPB.js} +1 -1
- package/dist/{chunk-J3NIPZ73.js → chunk-GBTG5B5R.js} +2 -2
- package/dist/chunk-GY52JA5I.js +10 -0
- package/dist/{chunk-YHH3QMLL.js → chunk-H54ZXA26.js} +1 -1
- package/dist/{chunk-3567PCEJ.js → chunk-H7VDC6FY.js} +2 -2
- package/dist/{chunk-I5IUTZA3.js → chunk-HDP7A4XY.js} +1 -1
- package/dist/{chunk-XF4IERYF.js → chunk-HTPUEIFT.js} +1 -1
- package/dist/{chunk-XAMLLKKA.js → chunk-ISZJV72D.js} +1 -1
- package/dist/{chunk-4VHBKJD5.js → chunk-JAS3TUZX.js} +2 -2
- package/dist/chunk-MTWLLE26.js +49 -0
- package/dist/{chunk-EZGMA3VV.js → chunk-QVKI7H7W.js} +1 -1
- package/dist/{chunk-24GTCFEV.js → chunk-QWCRZDZS.js} +1 -1
- package/dist/{chunk-NZEDILAK.js → chunk-R4GIIQ7G.js} +1 -1
- package/dist/chunk-RAW263MQ.js +99 -0
- package/dist/{chunk-T7GEINGZ.js → chunk-S3BAIZ4Q.js} +1 -1
- package/dist/chunk-VRJ7R766.js +1 -0
- package/dist/{chunk-CKIVKM5T.js → chunk-XL46AGRZ.js} +2 -2
- package/dist/{chunk-6THDALGC.js → chunk-Y3AMO6WC.js} +1 -1
- package/dist/{chunk-RUY23IJK.js → chunk-YVS565QY.js} +1 -1
- package/dist/{chunk-JKPSEMUZ.js → chunk-Z4D3L2HR.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/{config-CBNOT66B.js → config-EMNKHR3W.js} +1 -1
- package/dist/{db-XQUI4IBL.js → db-YUYXVV3A.js} +1 -1
- package/dist/{delivery-log-T56ZYDWO.js → delivery-log-VKONLSVD.js} +1 -1
- package/dist/engine-BM5BMPIC.js +1 -0
- package/dist/{evolution-audit-JZ2U7J4C.js → evolution-audit-LZSQPDHH.js} +1 -1
- package/dist/index.js +18 -12
- package/dist/learner-IJN6B7KV.js +1 -0
- package/dist/{memories-EKREXLT6.js → memories-ZII5QSTJ.js} +1 -1
- package/dist/{memory-extractor-JO7OHBZP.js → memory-extractor-DIYJFBCI.js} +2 -2
- package/dist/memory-service-QMYJPBAE.js +1 -0
- package/dist/outbound-gateway-6K6P2BEH.js +1 -0
- package/dist/role-presets-K2BDRZBS.js +1 -0
- package/dist/roles-L34L5MK3.js +1 -0
- package/dist/{session-manager-PWJLU6KZ.js → session-manager-GRJ3FV3L.js} +1 -1
- package/dist/{task-templates-ED2UCUPE.js → task-templates-23YOAF3E.js} +1 -1
- package/dist/workflow-executor-JTUWX5DC.js +1 -0
- package/package.json +1 -1
- package/dist/adam-tools-KTLBI4PA.js +0 -1
- package/dist/audit-manager-BPJEAX22.js +0 -1
- package/dist/bree-engine-CRK73AI4.js +0 -1
- package/dist/channels-WMTZJAO4.js +0 -1
- package/dist/chunk-DBI36EGR.js +0 -83
- package/dist/chunk-HQ66TFYI.js +0 -12
- package/dist/chunk-I67UMGJM.js +0 -10
- package/dist/chunk-NOUSHXGX.js +0 -6
- package/dist/chunk-WRETNOC3.js +0 -99
- package/dist/chunk-ZRUVORAJ.js +0 -49
- package/dist/engine-7DFJOADQ.js +0 -1
- package/dist/learner-4EO7ZKK4.js +0 -1
- package/dist/memory-service-Y3HVQYHM.js +0 -1
- package/dist/outbound-gateway-U5LP54JG.js +0 -1
- package/dist/role-presets-HWZHXBBA.js +0 -1
- package/dist/roles-3AEHVOEW.js +0 -1
- package/dist/workflow-executor-XFTTJQNE.js +0 -1
package/dist/chunk-WRETNOC3.js
DELETED
|
@@ -1,99 +0,0 @@
|
|
|
1
|
-
import{b as Fe,k as Xe,m as Ze,o as L,p as Qe}from"./chunk-HQ66TFYI.js";import{a as ue,d as je,e as pe}from"./chunk-YHH3QMLL.js";import{a as Oe,b as Le}from"./chunk-6THDALGC.js";import{b as me,c as qe,d as Je,e as Ye,f as Ge}from"./chunk-YHVFZB6Q.js";import{b as q,c as z,d as J,f as Be}from"./chunk-XAMLLKKA.js";import{a as $,e as et}from"./chunk-HYDCXE5K.js";import{a as ze}from"./chunk-DMZM7RU6.js";import{e as G,f as Ue,j as We}from"./chunk-24GTCFEV.js";import{b as Ve}from"./chunk-EZGMA3VV.js";import{a as y}from"./chunk-L7JP7DUO.js";import{b as He}from"./chunk-NZEDILAK.js";import{b as Ke}from"./chunk-T33BLZV2.js";import{d as W,i as Me}from"./chunk-GSMC3VUM.js";import{a as Y,b as $e,k as R,m as B,n as le,q as O}from"./chunk-J3NIPZ73.js";import{a as Ne,g as jt}from"./chunk-QQWRV23T.js";import{b,d as H}from"./chunk-4VHBKJD5.js";import{d as ce,h as Vt}from"./chunk-WBAPIPST.js";import{c as w,h as P}from"./chunk-INNDBLZE.js";H();function Ft(e){return{id:e.id,roleId:e.role_id,taskId:e.task_id,scores:JSON.parse(e.score_json),emaScore:e.ema_score,createdAt:e.created_at}}function tt(e){b().prepare(`
|
|
2
|
-
INSERT INTO role_scores (id, role_id, task_id, score_json, ema_score, created_at)
|
|
3
|
-
VALUES (?, ?, ?, ?, ?, ?)
|
|
4
|
-
`).run(e.id,e.roleId,e.taskId,JSON.stringify(e.scores),e.emaScore,e.createdAt)}function X(e,t=50){return b().prepare("SELECT * FROM role_scores WHERE role_id = ? ORDER BY created_at DESC LIMIT ?").all(e,t).map(Ft)}function ot(e){return b().prepare("SELECT ema_score FROM role_scores WHERE role_id = ? ORDER BY created_at DESC LIMIT 1").get(e)?.ema_score}function rt(e){let r=b().prepare(`
|
|
5
|
-
SELECT token_usage FROM tasks
|
|
6
|
-
WHERE role_id = ? AND status = 'completed' AND token_usage IS NOT NULL
|
|
7
|
-
ORDER BY completed_at DESC LIMIT 50
|
|
8
|
-
`).all(e);if(r.length===0)return 1e4;let s=r.map(i=>{let n=JSON.parse(i.token_usage);return(n.input??0)+(n.output??0)}).sort((i,n)=>i-n);return s[Math.floor(s.length/2)]}P();import{v4 as Kt}from"uuid";var Ht=w("audit"),Z={taskSuccess:.3,planAccuracy:.25,permissionCompliance:.25,efficiency:.2},nt=.3;function qt(e,t){let r=q(e),s=r?.status==="completed"?1:0,i=1,n=je(e);n?.deviationReport&&(i=n.deviationReport.overallAccuracy);let o=1,a=Le(e,1e3),c=a.filter(m=>m.type==="tool_result"||m.type==="permission_denied").length,d=a.filter(m=>m.type==="permission_denied").length;c>0&&(o=1-d/c);let u=1;if(r?.tokenUsage){let m=r.tokenUsage.input+r.tokenUsage.output,E=t?rt(t):1e4;m>E&&(u=Math.max(0,1-(m-E)/E))}let l=s*Z.taskSuccess+i*Z.planAccuracy+o*Z.permissionCompliance+u*Z.efficiency;return{taskSuccess:s,planAccuracy:i,permissionCompliance:o,efficiency:u,weighted:l}}function st(e,t){let r=qt(t,e),s=ot(e),i=s!==void 0?nt*r.weighted+(1-nt)*s:r.weighted;return tt({id:Kt(),roleId:e,taskId:t,scores:r,emaScore:i,createdAt:Date.now()}),Ht.debug({roleId:e,taskId:t,scores:{...r,weighted:r.weighted.toFixed(3)},ema:i.toFixed(3)},"Task score recorded"),i}O();O();P();var Jt=w("audit");function Q(e,t=7){let r=R(e),s=X(e,100),i=Date.now(),n=i-t*24*60*60*1e3,o=s.filter(g=>g.createdAt>=n),a=o.map(g=>g.emaScore),c=o.length>0?o.reduce((g,U)=>g+U.scores.weighted,0)/o.length:1,d=[],u=o.filter(g=>g.scores.taskSuccess<.5);u.length>0&&d.push({category:"task_failures",count:u.length,examples:u.slice(0,3).map(g=>g.taskId)});let l=o.filter(g=>g.scores.planAccuracy<.5);l.length>0&&d.push({category:"plan_deviations",count:l.length,examples:l.slice(0,3).map(g=>g.taskId)});let m=o.filter(g=>g.scores.permissionCompliance<.8);m.length>0&&d.push({category:"permission_violations",count:m.length,examples:m.slice(0,3).map(g=>g.taskId)});let E=o.filter(g=>g.scores.efficiency<.3);E.length>0&&d.push({category:"inefficiency",count:E.length,examples:E.slice(0,3).map(g=>g.taskId)});let N=[],C=[];return u.length>o.length*.3&&(N.push("High task failure rate"),C.push({action:"add_rule",detail:"Add rule: verify task feasibility before execution"})),m.length>0&&(N.push("Permission boundary violations"),C.push({action:"adjust_permission",detail:"Review and expand allowedTools if tasks legitimately need wider access"})),l.length>o.length*.5&&(N.push("Frequent plan deviations"),C.push({action:"add_rule",detail:"Add rule: follow execution plan steps more closely, request plan revision if steps are unclear"})),Jt.info({roleId:e,taskCount:o.length,avgScore:c.toFixed(3),failureCategories:d.map(g=>g.category)},"Diagnostic report generated"),{roleId:e,agentName:r?.name??"Unknown",period:{start:n,end:i},taskCount:o.length,avgScore:c,scoreHistory:a,failureBehaviors:d,rootCauses:N,recommendations:C}}P();var ee=w("audit"),it=.4,Yt=5;function at(e,t,r=it){if(t>=r)return;let s=R(e);if(!s||s.status==="retired"||s.status==="dead")return;ee.warn({roleId:e,emaScore:t,threshold:r},"Agent EMA below threshold, retiring");let i=Q(e),n=JSON.stringify(s.learnedRules),o=Gt(s.learnedRules,i);B(e,{status:"retired",learnedRules:o});let a=[...i.failureBehaviors.map(d=>`${d.category}: ${d.count} occurrences`),...i.rootCauses.map(d=>`Root cause: ${d}`),...i.recommendations.map(d=>`Recommendation [${d.action}]: ${d.detail}`)].join(`
|
|
9
|
-
`),c=et(n,JSON.stringify(o));return $({timestamp:Date.now(),oldRules:n,newRules:JSON.stringify(o),diff:a?`--- Diagnostic Report ---
|
|
10
|
-
${a}
|
|
11
|
-
|
|
12
|
-
--- Rules Diff ---
|
|
13
|
-
${c}`:c,roleId:e,source:"audit"}),ee.info({roleId:e,oldRulesCount:s.learnedRules.length,newRulesCount:o.length,recommendations:i.recommendations.length},"Agent retired with targeted learnedRules modification"),i}function dt(e){let t=R(e);return!t||t.status!=="retired"?!1:(B(e,{status:"probation"}),$({timestamp:Date.now(),oldRules:"status: retired",newRules:"status: probation",diff:`- status: retired
|
|
14
|
-
+ status: probation`,roleId:e,source:"audit"}),ee.info({roleId:e},"Agent reinstated to probation"),!0)}function ct(e,t,r=it,s=Yt){let i=R(e);return!i||i.status!=="probation"||X(e,s+1).length<s?!1:t>=r?(B(e,{status:"active"}),$({timestamp:Date.now(),oldRules:"status: probation",newRules:"status: idle",diff:`- status: probation
|
|
15
|
-
+ status: idle (graduated, EMA: ${t.toFixed(3)})`,roleId:e,source:"audit"}),ee.info({roleId:e,emaScore:t},"Agent graduated from probation to active"),!0):!1}function Gt(e,t){let r=[...e];for(let s of t.recommendations){let i=`[audit:${s.action}] ${s.detail}`;r.includes(i)||r.push(i)}if(t.failureBehaviors.length>0){let i=`[audit:diagnostic] Failure patterns detected: ${t.failureBehaviors.map(n=>`${n.category}(${n.count})`).join(", ")}. Review and adjust behavior accordingly.`;r.includes(i)||r.push(i)}return r}import{spawn as Tt}from"child_process";O();import{query as uo}from"@anthropic-ai/claude-agent-sdk";import{v4 as bt}from"uuid";function lt(e){let t=e.roleName?`## Role Context
|
|
16
|
-
- Role: ${e.roleName}
|
|
17
|
-
${e.roleCagPrompt?`- CAG Prompt: ${e.roleCagPrompt}`:""}`:"",r=e.allowedTools&&e.allowedTools.length>0?`## Available Tools
|
|
18
|
-
You have access to: ${e.allowedTools.join(", ")}. Use them as needed to complete the task.`:"",s=e.workflowStep?`## Workflow Step Context
|
|
19
|
-
You are executing step \`${e.workflowStep.stepId}\` of workflow \`${e.workflowStep.executionId}\`.
|
|
20
|
-
Other workflow steps may have already published structured data or files for you to use, and your output may be consumed by downstream steps.
|
|
21
|
-
|
|
22
|
-
### Artifact tools (use these to share data across steps)
|
|
23
|
-
- \`write_artifact\`: Save small structured JSON for downstream steps. Use for fields, flags, URLs, or summaries. Example: save extracted metadata.
|
|
24
|
-
- \`read_artifact\`: Read structured JSON previously written by an upstream step. Use for fields or state, not files.
|
|
25
|
-
- \`publish_artifact_file\`: Publish a file from your workspace into workflow storage. Use for audio, video, reports, images, or other large outputs.
|
|
26
|
-
- \`fetch_artifact_file\`: Copy an upstream file artifact into your current workspace. Use when you need to process a file produced by another step.
|
|
27
|
-
- \`list_artifacts\`: Discover what upstream artifacts exist before choosing a read or fetch call.
|
|
28
|
-
|
|
29
|
-
### When to use which
|
|
30
|
-
- Small JSON, fields, numbers, status, URLs: \`write_artifact\` and \`read_artifact\`
|
|
31
|
-
- Files such as audio, video, reports, images, or large outputs: \`publish_artifact_file\` and \`fetch_artifact_file\`
|
|
32
|
-
- Discover upstream output first: \`list_artifacts\`
|
|
33
|
-
|
|
34
|
-
The artifact tools handle storage and isolation automatically; never write to ~/.adam/ or other shared directories yourself.`:"";return`# Execution Agent \u2014 Task Focus
|
|
35
|
-
|
|
36
|
-
You are executing a specific task assigned to you. Your job is to complete the work, not manage goals or strategies.
|
|
37
|
-
|
|
38
|
-
## Task
|
|
39
|
-
- Task ID: ${e.taskId}
|
|
40
|
-
- Prompt: ${e.prompt}
|
|
41
|
-
|
|
42
|
-
${t}
|
|
43
|
-
|
|
44
|
-
${r}
|
|
45
|
-
|
|
46
|
-
${s}
|
|
47
|
-
|
|
48
|
-
## Focus
|
|
49
|
-
- Focus entirely on completing the task
|
|
50
|
-
- Use the standard SDK tools to do the work
|
|
51
|
-
- Do NOT attempt strategic decisions \u2014 just execute
|
|
52
|
-
|
|
53
|
-
## Constraints
|
|
54
|
-
- You have standard SDK tools only (no adam-tools MCP)
|
|
55
|
-
- Stay within your assigned permissions and allowed paths
|
|
56
|
-
- File writes: persistent outputs go under your working directory${e.cwd?` (\`${e.cwd}\`)`:""}. Temporary files may use \`os.tmpdir()\` (auto-redirected by the sandbox to a per-task dir). Do NOT write to absolute paths like \`/tmp/*\`, \`/var/*\`, \`~/Documents/*\`, or anywhere outside your workspace; the sandbox will reject them.
|
|
57
|
-
- Report completion with a clear result summary
|
|
58
|
-
- If WebSearch or WebFetch fails (network error, invalid params), report the failure honestly \u2014 do not fabricate data
|
|
59
|
-
- If a tool is unavailable, state it clearly in the result rather than guessing
|
|
60
|
-
`}import{isAbsolute as Xt,relative as Zt,resolve as Qt}from"path";$e();P();var eo=new Set(["Read","Glob","Grep","LSP"]),to=new Set(["Edit","Write","NotebookEdit"]);function fe(e){let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${t}$`)}function ge(e){return Qt(Y(e))}function ut(e,t){return t.some(r=>{let s=ge(r),i=Zt(s,e);return i===""||!i.startsWith("..")&&!Xt(i)})}function pt(e,t,r){return async(s,i,{agentID:n,blockedPath:o})=>{if(o){let c=ge(o);if(r?.deniedReadPaths?.length)for(let d of r.deniedReadPaths){let u=ge(d);if(ut(c,[u]))return oo.warn({toolName:s,blockedPath:o,agentID:n,deniedPath:d},"Denied: path in deniedReadPaths (absolute blacklist)"),{behavior:"deny",message:`Access denied: ${o} is in the global denied read paths list. This restriction is configured in Settings > Advanced and cannot be overridden by privilege escalation.`}}return r?.roleScope?.length&&ut(c,r.roleScope)?{behavior:"allow",updatedInput:i}:t?await t(s,i,`blockedPath:${o}`,n):{behavior:"deny",message:`Access denied: ${o} is outside this role's allowed scope (cwd + additionalDirectories). Configure additionalDirectories to expand access.`}}if(eo.has(s))return{behavior:"allow",updatedInput:i};if(to.has(s))return{behavior:"allow",updatedInput:i};let a=e(n??"");if(s==="Bash"&&a){let c=i.command??"";if(a.allowedBashPatterns?.length)for(let d of a.allowedBashPatterns)try{if(fe(d).test(c))return{behavior:"allow",updatedInput:i}}catch{}if(a.deniedBashPatterns?.length)for(let d of a.deniedBashPatterns)try{if(fe(d).test(c))return{behavior:"deny",message:`Bash command denied by pattern: ${d}`}}catch{}}if(a?.disallowedTools?.includes(s))return{behavior:"deny",message:`Tool ${s} is not allowed for this role.`};if(t&&a?.approvalRequired?.length){let c=s==="Bash"?i.command??"":`${s} ${JSON.stringify(i)}`;for(let d of a.approvalRequired)try{if(fe(d).test(c))return await t(s,i,d,n)}catch{}}return{behavior:"allow",updatedInput:i}}}var oo=w("manager");function mt(e){return{SessionStart:[{hooks:[async t=>{if(!e.roleId)return{};let r=t.source,s=e.roleId==="role-chat-manager";if(!s&&r!=="startup"&&r!=="resume")return{};try{let{queryMemoryByTier:i}=await import("./memory-service-Y3HVQYHM.js"),n=e.taskPrompt||"role context and recent interactions",o=s?["semantic","working"]:["semantic","episodic"],a=await i(e.roleId,n,o,{topK:5});if(a.length>0)return{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:`[Memory Context]
|
|
61
|
-
${a.map(u=>`- [${u.tier??"episodic"}] ${u.content}`).join(`
|
|
62
|
-
`)}
|
|
63
|
-
|
|
64
|
-
`}}}catch{}return{}}]}],SubagentStart:[{hooks:[async t=>{let r=e.roleId??t.agent_id;if(!r)return{};try{let s=e.taskPrompt||"role context",i=await He(s,r,5);if(i)return{hookSpecificOutput:{hookEventName:"SubagentStart",additionalContext:i}}}catch{}return{}}]}],SubagentStop:[{hooks:[async t=>{let r=t.agent_id;if(!r||!e.currentTaskId)return{};try{let{createMemory:s}=await import("./memories-EKREXLT6.js"),{getDb:i}=await import("./db-XQUI4IBL.js"),n=t.transcript;if(!n||n.length<=100)return{};if(i().prepare("SELECT 1 FROM memories WHERE source_task_id = ? AND type = 'thought' LIMIT 1").get(e.currentTaskId))return{};let a=`[Task ${e.currentTaskId} reasoning] ${n.slice(0,3e3)}`;s({id:`session-${Date.now()}`,roleId:e.roleId??r,type:"thought",content:a,keywords:[],importance:3,sourceType:"task_complete",sourceTaskId:e.currentTaskId,createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"episodic"})}catch{}return{}}]}],PostToolUse:[{hooks:[async t=>{if(!e.currentTaskId)return{};let r=t.tool_name,s=t.tool_input,i=t.tool_response,n=typeof i=="string"?i:JSON.stringify(i??"");try{Oe({id:`step-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,taskId:e.currentTaskId,index:0,type:"tool_call",content:`${r}: ${JSON.stringify(s??{})} \u2192 ${n.slice(0,200)}`,toolName:r,toolInput:s,toolOutput:n,timestamp:Date.now()})}catch{}return{}}]}],PreCompact:[{hooks:[async t=>{let r=t.compact_summary;if(!r)return{};try{let{createMemory:s}=await import("./memories-EKREXLT6.js");s({id:`compact-${Date.now()}`,roleId:e.roleId??"role-chat-manager",type:"thought",content:r.slice(0,5e3),keywords:["compaction","context","decisions"],importance:4,sourceType:"pre_compact",createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"working"})}catch{}return{}}]}]}}O();We();Vt();P();H();import{randomUUID as ro}from"crypto";function ft(e,t,r){let i=b().prepare(`
|
|
65
|
-
INSERT INTO task_plugins (id, task_id, plugin_path, plugin_name, role_id, used_at)
|
|
66
|
-
VALUES (?, ?, ?, ?, ?, ?)
|
|
67
|
-
`),n=Date.now();for(let o of t){let a=o.split("/").pop()??o;i.run(ro(),e,o,a,r??null,n)}}function Go(e){return b().prepare(`
|
|
68
|
-
SELECT plugin_name as pluginName, COUNT(*) as usageCount
|
|
69
|
-
FROM task_plugins
|
|
70
|
-
WHERE role_id = ?
|
|
71
|
-
GROUP BY plugin_path
|
|
72
|
-
ORDER BY usageCount DESC
|
|
73
|
-
`).all(e)}function Xo(e=50){return b().prepare(`
|
|
74
|
-
SELECT plugin_path as pluginPath, plugin_name as pluginName, COUNT(*) as usageCount, MAX(used_at) as lastUsed
|
|
75
|
-
FROM task_plugins
|
|
76
|
-
GROUP BY plugin_path
|
|
77
|
-
ORDER BY usageCount DESC
|
|
78
|
-
LIMIT ?
|
|
79
|
-
`).all(e)}O();We();import{createSdkMcpServer as so,tool as A}from"@anthropic-ai/claude-agent-sdk";import{z as v}from"zod";import{v4 as It}from"uuid";H();function gt(e){return{id:e.id,executionId:e.execution_id,stepId:e.step_id,key:e.key,kind:e.kind,value:e.value_json?JSON.parse(e.value_json):void 0,blobPath:e.blob_path??void 0,mime:e.mime??void 0,sizeBytes:e.size_bytes,createdAt:e.created_at}}function he(e){b().prepare(`
|
|
80
|
-
INSERT INTO workflow_artifacts (
|
|
81
|
-
id, execution_id, step_id, key, kind, value_json, blob_path, mime, size_bytes, created_at
|
|
82
|
-
)
|
|
83
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
84
|
-
`).run(e.id,e.executionId,e.stepId,e.key,e.kind,e.value!==void 0?JSON.stringify(e.value):null,e.blobPath??null,e.mime??null,e.sizeBytes,e.createdAt)}function Ie(e,t,r){let i=b().prepare(`
|
|
85
|
-
SELECT * FROM workflow_artifacts
|
|
86
|
-
WHERE execution_id = ? AND step_id = ? AND key = ?
|
|
87
|
-
`).get(e,t,r);return i?gt(i):void 0}function ye(e,t){let r=b(),s="SELECT * FROM workflow_artifacts WHERE execution_id = ?",i=[e];return t&&(s+=" AND step_id = ?",i.push(t)),s+=" ORDER BY created_at ASC",r.prepare(s).all(...i).map(gt)}function er(e){let t=b(),r=ye(e);return t.prepare("DELETE FROM workflow_artifacts WHERE execution_id = ?").run(e),r}function ht(e){b().prepare("DELETE FROM workflow_artifacts WHERE id = ?").run(e)}function tr(e){return b().prepare(`
|
|
88
|
-
SELECT id
|
|
89
|
-
FROM workflow_executions
|
|
90
|
-
WHERE status != 'running' AND COALESCE(completed_at, started_at) < ?
|
|
91
|
-
`).all(e).map(s=>s.id)}P();H();var no=w("audit");function I(e){try{b().prepare(`
|
|
92
|
-
INSERT INTO artifact_access_log (
|
|
93
|
-
timestamp, task_id, role_id, execution_id, step_id, tool, artifact_key, artifact_id,
|
|
94
|
-
size_bytes, outcome, error_reason
|
|
95
|
-
)
|
|
96
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
97
|
-
`).run(e.timestamp,e.taskId??null,e.roleId??null,e.executionId,e.stepId??null,e.tool,e.artifactKey??null,e.artifactId??null,e.sizeBytes??null,e.outcome,e.errorReason??null)}catch(t){no.error({err:t,entry:e},"Failed to write artifact access log")}}var io=/^[A-Za-z0-9._-]{1,256}$/,ao=/^[A-Za-z0-9._-]{1,128}$/,yt=256*1024,co=/^[a-z]+\/[a-z0-9.+-]+$/;async function lo(e){let{listChannels:t}=await import("./channels-PUOPR5Y2.js"),r=t(),{listSessions:s}=await import("./session-manager-PWJLU6KZ.js"),i=[...s("active"),...s("archived")],n=r.find(c=>c.name.toLowerCase().includes(e.toLowerCase()));if(!n)return null;let a=i.find(c=>c.source.type==="channel"&&c.source.channelId===n.id&&c.source.chatId)?.source.chatId??n.config?.userId??"";return{channelId:n.id,chatId:a}}function p(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}function te(e){return io.test(e)?null:"Invalid artifact key. Use only letters, numbers, dot, underscore, or dash (1-256 chars)."}function ke(e){return ao.test(e)?null:"Invalid stepId format. Use only letters, numbers, dot, underscore, or dash (1-128 chars)."}function kt(e,t){let r=e?R(e):void 0,s=async()=>{if(!t)return{error:"artifact tools require a task context"};let n=q(t);if(!n)return{error:`task not found: ${t}`};if(!n.parentId)return{error:"this task is not a workflow step (no execution context)"};if(!n.stepId)return{error:"this task is not a workflow step (no step_id)"};let o=n.roleId??e;if(!o)return{error:"this workflow task has no role context"};let a=R(o);return a?{executionId:n.parentId,stepId:n.stepId,roleId:o,roleWorkspacePath:G(a.name),taskId:t}:{error:`role not found: ${o}`}},i=[...Xe(e),A("list_channels","List all available channels. Use this to discover what channels can be used with send_to_channel.",{},async()=>{let{listChannels:n}=await import("./channels-PUOPR5Y2.js"),o=n();return p({channels:o.map(a=>({id:a.id,name:a.name,enabled:a.enabled,type:a.config?.type??"unknown"}))})}),A("send_to_channel","Send a message to a connected channel by name. This role can only send to channels in its allowedChannels list (if configured).",{channelName:v.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:v.string().describe("The message content to send")},async n=>{if(r?.allowedChannels!==void 0){if(r.allowedChannels.length===0)return p({error:"This role is not allowed to send to any channels"});if(!r.allowedChannels.some(l=>l.toLowerCase()===n.channelName.toLowerCase()))return p({error:`Channel "${n.channelName}" is not in the allowed channels list for this role`})}let o=await lo(n.channelName);if(!o)return p({error:`Channel "${n.channelName}" not found or has no chatId available`});let{getOutboundGateway:a}=await import("./outbound-gateway-U5LP54JG.js"),d=await a().send({channelId:o.channelId,chatId:o.chatId,content:n.message,messageType:"reply"});return p({success:d.success,channelName:n.channelName})}),A("write_artifact","Persist a small structured value (JSON <= 256KB) for downstream workflow steps to read. USE THIS for: extracted fields, status flags, URL lists, summaries, structured key-value data. Do NOT use for: files (audio, video, reports). For files use publish_artifact_file instead.",{key:v.string(),value:v.unknown()},async n=>{let o=await s();if("error"in o)return p({error:o.error});let a=te(n.key);if(a)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:n.key,outcome:"denied",errorReason:a}),p({error:a});try{let c=JSON.stringify(n.value),d=Buffer.byteLength(c,"utf8");if(d>yt){let l=`Artifact JSON exceeds ${yt} bytes`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:n.key,sizeBytes:d,outcome:"denied",errorReason:l}),p({error:l})}let u=It();return he({id:u,executionId:o.executionId,stepId:o.stepId,key:n.key,kind:"json",value:n.value,sizeBytes:d,createdAt:Date.now()}),I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:n.key,artifactId:u,sizeBytes:d,outcome:"success"}),p({success:!0,artifactId:u,sizeBytes:d})}catch(c){let d=c instanceof Error?c.message:String(c);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:n.key,outcome:"error",errorReason:d}),p({error:d})}}),A("read_artifact","Read a structured value previously written by an upstream step's write_artifact. Returns the JSON value. For files, use fetch_artifact_file instead.",{stepId:v.string(),key:v.string()},async n=>{let o=await s();if("error"in o)return p({error:o.error});let a=ke(n.stepId),c=te(n.key),d=a??c;if(d)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:n.key,outcome:"denied",errorReason:d}),p({error:d});let u=Ie(o.executionId,n.stepId,n.key);if(!u){let l=`no artifact at ${n.stepId}/${n.key}`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:n.key,outcome:"error",errorReason:l}),p({error:l})}if(u.kind!=="json"){let l="artifact is a file; use fetch_artifact_file";return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:n.key,artifactId:u.id,sizeBytes:u.sizeBytes,outcome:"denied",errorReason:l}),p({error:l})}return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:n.key,artifactId:u.id,sizeBytes:u.sizeBytes,outcome:"success"}),p({value:u.value,sizeBytes:u.sizeBytes})}),A("publish_artifact_file","Publish a file from your workspace as a workflow artifact. The file is COPIED to the workflow's shared storage. USE THIS for: generated audio, video, reports, images, or large outputs. Do NOT use for: small structured values; use write_artifact instead. If you publish with cleanup=true, this step will not be retryable through publish; only choose cleanup=true when you do not need the source file again.",{key:v.string(),sourcePath:v.string(),mime:v.string().optional(),cleanup:v.boolean().optional()},async n=>{let o=await s();if("error"in o)return p({error:o.error});let a=te(n.key);if(a)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:n.key,outcome:"denied",errorReason:a}),p({error:a});if(n.mime&&!co.test(n.mime)){let l=`Invalid MIME type: ${n.mime}`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:n.key,outcome:"denied",errorReason:l}),p({error:l})}try{me(n.sourcePath,o.roleWorkspacePath,!0)}catch(l){let m=l instanceof Error?l.message:String(l);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:n.key,outcome:"denied",errorReason:m}),p({error:m})}let c=It(),d=null,u=!1;try{let l=qe({executionId:o.executionId,artifactId:c,sourcePath:n.sourcePath});return d=l.blobPath,he({id:c,executionId:o.executionId,stepId:o.stepId,key:n.key,kind:"file",blobPath:d,mime:n.mime,sizeBytes:l.sizeBytes,createdAt:Date.now()}),u=!0,n.cleanup===!0&&Je(n.sourcePath),I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:n.key,artifactId:c,sizeBytes:l.sizeBytes,outcome:"success"}),p({success:!0,artifactId:c,sizeBytes:l.sizeBytes})}catch(l){if(u)try{ht(c)}catch{}if(d)try{Ge(d)}catch{}let m=l instanceof Error?l.message:String(l);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:n.key,artifactId:c,outcome:"error",errorReason:m}),p({error:m})}}),A("fetch_artifact_file","Copy an upstream step's published file into your current Role workspace. Use this when an earlier step published audio, video, reports, or other files you need to process.",{stepId:v.string(),key:v.string(),destPath:v.string()},async n=>{let o=await s();if("error"in o)return p({error:o.error});let a=ke(n.stepId),c=te(n.key),d=a??c;if(d)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,outcome:"denied",errorReason:d}),p({error:d});try{me(n.destPath,o.roleWorkspacePath,!1)}catch(l){let m=l instanceof Error?l.message:String(l);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,outcome:"denied",errorReason:m}),p({error:m})}let u=Ie(o.executionId,n.stepId,n.key);if(!u){let l=`no artifact at ${n.stepId}/${n.key}`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,outcome:"error",errorReason:l}),p({error:l})}if(u.kind!=="file"||!u.blobPath){let l="artifact is not a file";return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,artifactId:u.id,outcome:"denied",errorReason:l}),p({error:l})}try{let l=Ye({blobPath:u.blobPath,destPath:n.destPath});return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,artifactId:u.id,sizeBytes:l.sizeBytes,outcome:"success"}),p({success:!0,sizeBytes:l.sizeBytes,mime:u.mime,destPath:n.destPath})}catch(l){let m=l instanceof Error?l.message:String(l);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,artifactId:u.id,outcome:"error",errorReason:m}),p({error:m})}}),A("list_artifacts","Discover artifacts published by upstream steps in this workflow. Returns step_id, key, kind ('json' or 'file'), size, mime. Use this to learn what is available before calling read_artifact or fetch_artifact_file.",{stepId:v.string().optional()},async n=>{let o=await s();if("error"in o)return p({error:o.error});let a=n.stepId?ke(n.stepId):null;if(a)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"list_artifacts",outcome:"denied",errorReason:a}),p({error:a});let c=ye(o.executionId,n.stepId);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"list_artifacts",sizeBytes:c.length,outcome:"success"}),p({artifacts:c.map(d=>({id:d.id,stepId:d.stepId,key:d.key,kind:d.kind,sizeBytes:d.sizeBytes,mime:d.mime,createdAt:d.createdAt}))})})];return so({name:"execution-tools",version:"1.0.0",tools:i})}jt();$e();import{realpathSync as po}from"fs";var _=w("execution"),wt=new Set;async function mo(e,t){if(t&&wt.has(t))return _.info({taskId:e,roleName:t},"Sandbox bypass: approved from session cache"),!0;let r=bt(),s={steps:[{index:0,description:"Execute task without OS sandbox \u2014 filesystem isolation not enforced",toolsNeeded:[],expectedOutput:"Task result or denial message",riskLevel:"high"}],requiredPermissions:{allowedTools:[],disallowedTools:[],approvalRequired:[],maxBudgetUsd:0,plugins:[]},overallRisk:"high"};return ue({id:r,taskId:e,plan:s,status:"pending",createdAt:Date.now()}),y.emit({type:"plan_approval_request",taskId:e,planId:r,plan:s}),_.info({taskId:e,operationId:r,roleName:t},"Sandbox unavailable: awaiting privilege escalation decision"),new Promise(i=>{let o=setTimeout(()=>{c(),pe(r,"denied"),_.warn({taskId:e,operationId:r},"Sandbox bypass timed out, auto-denied"),i(!1)},12e4),a=d=>{d.planId===r&&(c(),d.decision==="allow"?(_.info({taskId:e,operationId:r},"Sandbox bypass approved by user"),t&&wt.add(t),i(!0)):(_.info({taskId:e,operationId:r},"Sandbox bypass denied by user"),i(!1)))},c=()=>{clearTimeout(o),y.off("plan_approval_decision",a)};y.on("plan_approval_decision",a)})}var oe=class{async execute(t,r){let s=Date.now(),i,n,o;z(t.id,{status:"running",startedAt:Date.now()}),y.emit({type:"task_status_change",taskId:t.id,oldStatus:t.status,newStatus:"running"}),_.info({taskId:t.id,roleId:t.roleId},"ExecutionManager: starting task");try{let a=t.roleId?R(t.roleId):void 0,c=ce;a&&(Ue(a),c=G(a.name));let d={taskId:t.id,prompt:t.prompt,roleName:a?.name,roleCagPrompt:a?.cagPrompt,allowedTools:a?.allowedTools,cwd:c,workflowStep:t.parentId&&t.stepId?{executionId:t.parentId,stepId:t.stepId}:void 0},u=lt(d),l=mt({currentTaskId:t.id,roleId:t.roleId,taskPrompt:t.prompt}),m=t.config.approvalTimeout??300,E=async(f,h,k,D)=>{let x=bt(),Pe=Fe(D??t.roleId,t.prompt,"medium");if(Pe)return _.info({operationId:x,ruleId:Pe.id,taskId:t.id},"Auto-approved by permanent rule"),{behavior:"allow",updatedInput:h};let Ce={steps:[{index:0,description:`${f}: ${JSON.stringify(h).slice(0,300)}`,toolsNeeded:[f],expectedOutput:"",riskLevel:"medium"}],requiredPermissions:{},overallRisk:"medium"};return ue({id:x,taskId:t.id,roleId:D??t.roleId,plan:Ce,status:"pending",createdAt:Date.now()}),y.emit({type:"plan_approval_request",taskId:t.id,planId:x,plan:Ce}),_.info({taskId:t.id,operationId:x,toolName:f,matchedPattern:k},"Privilege escalation: awaiting user decision"),new Promise(de=>{let Wt=setTimeout(()=>{De(),pe(x,"denied"),_.warn({taskId:t.id,operationId:x},"Privilege escalation timed out, auto-denied"),de({behavior:"deny",message:`Operation timed out after ${m}s. Auto-denied. Try a safer alternative that does not require approval.`})},m*1e3),Ae=M=>{if(M.planId===x)if(De(),M.decision==="allow")_.info({taskId:t.id,operationId:x,approvalType:M.approvalType},"Operation authorized by user"),de({behavior:"allow",updatedInput:h});else{let zt=M.reason?`Operation denied by user: ${M.reason}. Try a safer alternative.`:"Operation denied by user. Try a safer alternative approach.";_.info({taskId:t.id,operationId:x,reason:M.reason??"no reason given"},"Operation denied by user"),de({behavior:"deny",message:zt})}},De=()=>{clearTimeout(Wt),y.off("plan_approval_decision",Ae)};y.on("plan_approval_decision",Ae)})},C=(Ne("defaults.deniedReadPaths")??[]).map(f=>{let h=Y(f);try{return po(h)}catch{return h}}),g=a?.additionalDirectories??[],U=a?Ze(a):[],Re=[...g.map(f=>f.path)].filter((f,h,k)=>k.indexOf(f)===h),At=pt(f=>({disallowedTools:a?.disallowedTools,approvalRequired:a?.approvalRequired??t.config.approvalRequired,allowedBashPatterns:a?.allowedBashPatterns,deniedBashPatterns:a?.deniedBashPatterns}),E,{deniedReadPaths:C,roleScope:[c,...Re]}),Dt=Me({roleEnvVars:a?.envVars,taskEnv:t.config.env}),Mt=t.config.maxBudgetUsd??W().defaults.maxBudgetUsd,Bt=t.config.maxTurns??100,Ot=kt(t.roleId??"",t.id),Lt=a?.mcpServers??{},$t=t.config.mcpServers??{},Nt={...Lt,...$t,"execution-tools":Ot},ie=[{path:c,mode:"rw"}];t.roleId===ze&&ie.push({path:ce,mode:"ro"});for(let f of g)ie.push({path:f.path,mode:f.mode??"rw"});let ve=L();if(ve.platform==="none"&&!await mo(t.id,a?.name))return z(t.id,{status:"failed",error:"Sandbox unavailable; execution denied by user"}),{taskId:t.id,status:"failed",error:"Sandbox bypass denied"};let Se=a?.permissionMode??"default",Ut=uo({prompt:t.prompt,options:{cwd:c,additionalDirectories:Re,systemPrompt:u,maxTurns:Bt,maxBudgetUsd:Mt,allowedTools:a?.allowedTools,model:a?.model,mcpServers:Nt,settingSources:a?.inheritUserSettings?["project","user"]:["project"],hooks:l,canUseTool:At,env:Dt,plugins:U.map(f=>({type:"local",path:f})),permissionMode:Se,...Se==="bypassPermissions"?{allowDangerouslySkipPermissions:!0}:{},spawnClaudeCodeProcess:f=>{let h=ve.spawn({command:f.command,args:f.args,cwd:f.cwd,env:f.env,signal:f.signal,visiblePaths:ie,deniedReadPaths:C,osCapabilities:a?.osCapabilities}),k=h;k.pid&&(_t(k.pid,t.roleId??"unknown",t.id),k.on("exit",()=>xt(k.pid)));let D="";return k.stderr?.on("data",x=>{D+=x.toString()}),k.on("exit",x=>{x!==null&&x!==0&&D.includes("sandbox")&&(_.error({taskId:t.id,roleId:t.roleId,exitCode:x,stderr:D.slice(0,500)},"Sandbox wrapper failed \u2014 task process exited before execution"),re({roleId:t.roleId??"unknown",taskId:t.id,path:c,operation:`sandbox_init_failure:exit_${x}`,timestamp:Date.now()}))}),h},stderr:f=>{f.trim()&&_.debug({stderr:f.trim().slice(0,500)},"ExecutionManager SDK stderr")}}}),K="",Te=0,Ee=()=>{_.warn({taskId:t.id},"ExecutionManager: abort signal received")};r&&r.addEventListener("abort",Ee);try{for await(let f of Ut){let h=f;if(_.debug({eventType:h.type,taskId:t.id},"ExecutionManager SDK event"),h.type==="result"&&typeof h.result=="string"&&(K=h.result),h.type==="result"){Te++,typeof h.total_cost_usd=="number"&&(n=h.total_cost_usd);let k=h.usage;k?.input_tokens!==void 0&&k?.output_tokens!==void 0&&(i={input:k.input_tokens,output:k.output_tokens})}if(h.token_usage){let k=h.token_usage;k.input_tokens!==void 0&&k.output_tokens!==void 0&&(i={input:k.input_tokens,output:k.output_tokens})}}}finally{r&&r.removeEventListener("abort",Ee)}o=Te;let ae=Date.now()-s;return z(t.id,{status:"completed",result:K,completedAt:Date.now(),costUsd:n,tokenUsage:i,numTurns:o,totalDurationMs:ae}),y.emit({type:"task_status_change",taskId:t.id,oldStatus:"running",newStatus:"completed"}),y.emit({type:"task_complete_event",taskId:t.id,result:K}),U.length>0&&ft(t.id,U,t.roleId),_.info({taskId:t.id,durationMs:ae,costUsd:n},"ExecutionManager: task completed"),{taskId:t.id,status:"completed",result:K,costUsd:n,tokenUsage:i,numTurns:o,durationMs:ae}}catch(a){let c=a instanceof Error?a.message:String(a),d=Date.now()-s;return(c.includes("Prompt is too long")||c.includes("prompt is too long"))&&_.warn({taskId:t.id,error:c},"Task prompt exceeds model context window \u2014 task failed"),z(t.id,{status:"failed",error:c,completedAt:Date.now(),totalDurationMs:d}),y.emit({type:"task_status_change",taskId:t.id,oldStatus:"running",newStatus:"failed"}),y.emit({type:"task_complete_event",taskId:t.id,error:c}),_.error({taskId:t.id,error:a},"ExecutionManager: task failed"),{taskId:t.id,status:"failed",error:c,durationMs:d}}}};P();var S=w("execution-pool"),we=new Map;function _t(e,t,r){we.set(e,{roleId:t,taskId:r})}function xt(e){we.delete(e)}function be(e){return we.get(e)}var Rt=class{slots;running=!1;pollTimeoutId=null;executor;constructor(t,r){this.slots=Array.from({length:t},(s,i)=>({index:i,taskId:null,abortController:null})),this.executor=r??new oe}async start(){if(this.running)return;this.running=!0,y.on("task_created",s=>{this.onTaskCreated(s.taskId)}),y.on("task_status_change",s=>{s.newStatus==="pending"&&this.pickupPendingTasks()});let r=W().execution?.pollIntervalMs??3e4;this.pollTimeoutId=setTimeout(this.poll,r),S.info({maxConcurrent:this.slots.length},"ExecutionPool started")}stop(){this.running=!1,this.pollTimeoutId&&(clearTimeout(this.pollTimeoutId),this.pollTimeoutId=null);for(let t of this.slots)t.abortController&&(t.abortController.abort(),t.taskId=null,t.abortController=null);S.info("ExecutionPool stopped")}poll=()=>{if(!this.running)return;this.pickupPendingTasks();let r=W().execution?.pollIntervalMs??3e4;this.pollTimeoutId=setTimeout(this.poll,r)};async onTaskCreated(t){this.running&&await this.pickupPendingTasks()}async pickupPendingTasks(){if(!this.running)return;let t=this.slots.find(a=>a.taskId===null);if(!t){S.debug("No free slots available");return}let r=J("pending");if(r.length===0)return;let i=[...r].sort((a,c)=>a.createdAt-c.createdAt)[0];t.taskId=i.id,t.abortController=new AbortController;let n=t.index,o=i.id;S.info({slotIndex:n,taskId:o},"ExecutionPool: claimed slot for task"),this.emitSlotChange(),this.executeTask(i,n).catch(a=>{S.error({taskId:o,error:a},"ExecutionPool: executeTask failed unexpectedly")})}async executeTask(t,r){let s=this.slots[r];if(!s)return;let i="completed";try{y.emit({type:"execution_task_start",taskId:t.id,slotIndex:r});let n=await this.executor.execute(t,s.abortController?.signal);i=n.status,S.info({taskId:t.id,status:n.status,slotIndex:r},"ExecutionPool: task finished")}finally{s.taskId=null,s.abortController=null,y.emit({type:"execution_task_end",taskId:t.id,slotIndex:r,status:i}),this.emitSlotChange(),this.runPostCompletion(t.id,t.roleId).catch(n=>{S.error({taskId:t.id,error:n},"Post-completion processing failed (non-fatal)")}),this.running&&this.pickupPendingTasks()}}emitSlotChange(){let t=this.slots.filter(i=>i.taskId!==null).length,r=J("pending");y.emit({type:"execution_slot_change",active:t,max:this.slots.length,queued:r.length});let s=Ke();y.emit({type:"stats_update",activeTasks:t,queuedTasks:r.length,totalCostToday:Be(s)})}async runPostCompletion(t,r){if(r){try{let{processTaskCompletion:s}=await import("./memory-extractor-JO7OHBZP.js"),i=await s(t,r);i>0&&S.debug({taskId:t,roleId:r,memoriesStored:i},"Post-completion: memories extracted")}catch(s){S.error({taskId:t,roleId:r,error:s},"Post-completion: memory extraction failed")}try{let{processTaskReview:s}=await import("./learner-4EO7ZKK4.js");await s(t)}catch(s){S.error({taskId:t,roleId:r,error:s},"Post-completion: task review failed")}try{let{evaluateTaskCompletion:s}=await import("./audit-manager-BPJEAX22.js");s(t,r)}catch(s){S.error({taskId:t,roleId:r,error:s},"Post-completion: audit evaluation failed")}}}getStatus(){let t=this.slots.filter(s=>s.taskId!==null).length,r=J("pending");return{active:t,max:this.slots.length,queued:r.length}}isHealthy(){return this.running}releaseSlot(t){let r=this.slots.find(s=>s.taskId===t);r&&(S.warn({taskId:t,slotIndex:r.index},"ExecutionPool: force-releasing slot"),r.abortController&&r.abortController.abort(),r.taskId=null,r.abortController=null,this.emitSlotChange(),this.running&&this.pickupPendingTasks())}};P();var T=w("audit"),fo="sandbox_violation",V=new Map,_e=1440*60*1e3,ne=[],go=100;function xe(e){let t=e.roleId,r=V.get(t)??{count:0,timestamps:[]};r.count++,r.timestamps.push(e.timestamp);let s=Date.now()-_e;if(r.timestamps=r.timestamps.filter(i=>i>=s),V.set(t,r),r.count%100===0)for(let[i,n]of V.entries()){let o=Date.now()-_e;n.timestamps.filter(a=>a>=o).length===0&&V.delete(i)}ne.push(e),ne.length>go&&ne.shift();try{Ve({id:`sv-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,ruleId:void 0,taskId:e.taskId,status:"delivered",target:{type:"channel",channelId:"audit"},content:"",attempts:1,messageType:fo,source:"audit",createdAt:e.timestamp,deliveredAt:e.timestamp,expiresAt:e.timestamp+864e5,error:`${e.operation} on ${e.path}`})}catch(i){T.error({error:i},"Failed to record violation to delivery_log")}try{let i=R(e.roleId);$({timestamp:e.timestamp,oldRules:"sandbox_violation",newRules:`${e.operation} on ${e.path}`,diff:`Sandbox violation: ${e.operation} on ${e.path} (taskId=${e.taskId??"unknown"})`,roleId:e.roleId,source:"audit"})}catch(i){T.error({error:i},"Failed to record violation to evolution_audit")}y.emit({type:"sandbox_violation",roleId:e.roleId,taskId:e.taskId,path:e.path,operation:e.operation,timestamp:e.timestamp})}async function Et(){let e=L();if(e.platform==="none")return T.info("Sandbox platform is 'none'; violation watcher not started"),()=>{};if(!await e.isAvailable())return T.warn({platform:e.platform},"Sandbox platform detected but not available; violation watcher not started"),()=>{};let r=null;return e.platform==="sandbox-exec"?r=ho():e.platform==="landlock"&&(r=await Io()),()=>{if(r){let s=r;r=null,s.kill("SIGTERM");let i=setTimeout(()=>{try{s.kill("SIGKILL")}catch{}},2e3);s.on("exit",()=>clearTimeout(i))}T.info("Violation watcher stopped")}}function ho(){let e=Tt("log",["stream","--predicate",'subsystem == "com.apple.sandbox"',"--style","ndjson","--signal","exit"],{stdio:["ignore","pipe","pipe"]});return e.stdout?.on("data",t=>{let r=t.toString().split(`
|
|
98
|
-
`).filter(Boolean);for(let s of r)try{let i=JSON.parse(s),n=i.eventMessage??i.message??"";if(n.includes("deny")&&(n.includes("file-read")||n.includes("file-write"))){let o=yo(i,n);o&&xe(o)}}catch{}}),e.stderr?.on("data",t=>{T.debug({msg:t.toString()},"log stream stderr")}),e.on("error",t=>{T.warn({error:t},"macOS violation watcher failed to start")}),T.info("macOS sandbox violation watcher started (log stream)"),e}async function Io(){let e=await vt("journalctl",["-kf","--no-pager","-o","short","--grep","landlock"]);if(e)return St(e),T.info("Linux violation watcher started (journalctl -kf)"),e;let t=await vt("dmesg",["-w","-t"]);return t?(St(t),T.info("Linux violation watcher started (dmesg -w)"),t):(T.warn("Linux violation watcher unavailable: neither journalctl nor dmesg accessible. Sandbox enforcement still active; monitoring disabled."),null)}async function vt(e,t){return new Promise(r=>{let s=Tt(e,t,{stdio:["ignore","pipe","pipe"]}),i=setTimeout(()=>r(s),500);s.on("error",()=>{clearTimeout(i),r(null)}),s.on("exit",n=>{n!==0&&(clearTimeout(i),r(null))})})}function St(e){e.stdout?.on("data",t=>{let r=t.toString().split(`
|
|
99
|
-
`).filter(Boolean);for(let s of r)if(s.includes("landlock")&&s.includes("denied")){let i=ko(s);i&&xe(i)}}),e.stderr?.on("data",t=>{T.debug({msg:t.toString().trim()},"Linux watcher stderr")})}function yo(e,t){let r=t.match(/(?:path|file)=["']([^"']+)["']/),s=t.match(/deny\s+(file-read|file-write|file-[^\s]+)/),i=r?.[1],n=s?.[1]??"unknown";if(!i)return null;let o=typeof e.processID=="number"?e.processID:void 0,a=o?be(o):void 0;return{roleId:a?.roleId??"unknown",taskId:a?.taskId,path:i,operation:n,timestamp:Date.now(),count:1}}function ko(e){let t=e.match(/path="([^"]+)"/)??e.match(/\/[\w\-\.\/\+ ]+/g),r=e.match(/deny\s+(\w+)/),s=e.match(/pid=(\d+)/),i=Array.isArray(t)?t[t.length-1]:t?.[1],n=r?.[1]??"unknown";if(!i)return null;let o=s?parseInt(s[1],10):void 0,a=o?be(o):void 0;return{roleId:a?.roleId??"unknown",taskId:a?.taskId,path:i,operation:n,timestamp:Date.now(),count:1}}function re(e){xe({roleId:e.roleId,taskId:e.taskId,path:e.path,operation:e.operation,timestamp:e.timestamp,count:1})}function Pt(e){let t=V.get(e);if(!t)return 0;let r=Date.now()-_e;return t.timestamps.filter(s=>s>=r).length}function Ct(){return[...ne]}O();P();var j=w("audit"),wo=.4,bo=1440*60*1e3,F=null,se=null;function un(e,t,r=wo){let s=R(t);if(!s||s.status==="retired"||s.status==="inactive"||s.status==="dead")return;let i=st(t,e);B(t,{performanceScore:i}),ct(t,i,r)?j.info({roleId:t,emaScore:i},"Probation role graduated"):i<r&&at(t,i,r)&&dt(t)}async function pn(){F===null&&(F=setInterval(()=>{j.info("Running daily diagnostic reports");let e=le(void 0,1e3);for(let t of e)if(!(t.status==="retired"||t.status==="inactive"))try{Q(t.id)}catch(r){j.error({roleId:t.id,error:r},"Daily diagnostic failed")}},bo),se=await Et(),j.info("AuditManager started"))}function mn(){F!==null&&(clearInterval(F),F=null),se!==null&&(se(),se=null),j.info("AuditManager stopped")}function fn(e){re(e)}async function gn(){let e=L(),t=le(void 0,1e3),s=Date.now()-1440*60*1e3,i=Ct(),n=i.filter(c=>c.timestamp>=s).length,o=t.map(c=>{let d=i.filter(l=>l.roleId===c.id),u=d[d.length-1];return{roleId:c.id,roleName:c.name,sandboxed:e.platform!=="none",violationCount:Pt(c.id),lastViolation:u?.timestamp}}),a=await Qe();return{platform:e.platform,available:a,violationCount24h:n,rolePostures:o}}export{X as a,ot as b,pt as c,mt as d,Go as e,Xo as f,ye as g,er as h,tr as i,un as j,pn as k,mn as l,fn as m,gn as n,Rt as o};
|
package/dist/chunk-ZRUVORAJ.js
DELETED
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
import{a as I,b as C}from"./chunk-NOUSHXGX.js";import{d as _}from"./chunk-I67UMGJM.js";import{a as k,b as T}from"./chunk-XAMLLKKA.js";import{a as u}from"./chunk-L7JP7DUO.js";import{p as y}from"./chunk-7BSWC62F.js";import{a as b,b as l,d,f as x}from"./chunk-T7GEINGZ.js";import{d as w}from"./chunk-7K4AQBDD.js";import{n as v,q as O}from"./chunk-J3NIPZ73.js";import{c as h,h as E}from"./chunk-INNDBLZE.js";E();O();import{v4 as c}from"uuid";import{CronExpressionParser as D}from"cron-parser";var n=h("scheduler"),m="ai-hourly-digest";function H(){if(l(m)){n.debug({templateId:m},"Built-in template already exists");return}let e={id:m,name:"AI Hourly Digest",description:"\u6BCF\u5C0F\u65F6\u641C\u7D22 AI \u524D\u6CBF\u6587\u7AE0\uFF0C\u603B\u7ED3\u540E\u4FDD\u5B58\u5230 Omnifocus",trigger:{type:"cron",cron:"0 * * * *"},enabled:!0,steps:[{id:"search_ai_news",prompt:`\u641C\u7D22\u8FC7\u53BB 24 \u5C0F\u65F6\u5185\u5173\u4E8E AI/\u4EBA\u5DE5\u667A\u80FD\u7684\u6700\u65B0\u524D\u6CBF\u6587\u7AE0\u3002
|
|
2
|
-
|
|
3
|
-
\u641C\u7D22\u6765\u6E90:
|
|
4
|
-
1. Hacker News AI \u677F\u5757 (https://news.ycombinator.com/front?day=1)
|
|
5
|
-
2. ArXiv cs.AI \u6700\u65B0\u8BBA\u6587 (https://arxiv.org/list/cs.AI/recent)
|
|
6
|
-
3. Reddit r/MachineLearning \u70ED\u95E8\u5E16\u5B50
|
|
7
|
-
|
|
8
|
-
\u627E\u51FA\u4E00\u7BC7\u6700\u6709\u4EF7\u503C\u3001\u6700\u6709\u6280\u672F\u6DF1\u5EA6\u7684\u6587\u7AE0\u3002
|
|
9
|
-
|
|
10
|
-
\u8F93\u51FA\u683C\u5F0F:
|
|
11
|
-
- \u6807\u9898\uFF1A[\u6587\u7AE0\u6807\u9898]
|
|
12
|
-
- \u6765\u6E90\uFF1A[\u7F51\u7AD9/\u5E73\u53F0\u540D\u79F0]
|
|
13
|
-
- \u94FE\u63A5\uFF1A[\u5B8C\u6574 URL]
|
|
14
|
-
- \u6838\u5FC3\u4EF7\u503C\uFF1A[1-2 \u53E5\u8BDD\u8BF4\u660E\u4E3A\u4EC0\u4E48\u8FD9\u7BC7\u6587\u7AE0\u503C\u5F97\u770B]`},{id:"summarize_article",dependsOn:["search_ai_news"],prompt:`\u9605\u8BFB\u5E76\u603B\u7ED3\u8FD9\u7BC7\u6587\u7AE0\u3002
|
|
15
|
-
|
|
16
|
-
\u6587\u7AE0\u4FE1\u606F:
|
|
17
|
-
{{search_ai_news.result}}
|
|
18
|
-
|
|
19
|
-
\u8BF7:
|
|
20
|
-
1. \u7528 WebFetch \u83B7\u53D6\u6587\u7AE0\u5B8C\u6574\u5185\u5BB9
|
|
21
|
-
2. \u63D0\u53D6\u6838\u5FC3\u89C2\u70B9\u548C\u6280\u672F\u7EC6\u8282
|
|
22
|
-
3. \u7528\u4E2D\u6587\u5199\u51FA 300-500 \u5B57\u7684\u603B\u7ED3
|
|
23
|
-
|
|
24
|
-
\u603B\u7ED3\u7ED3\u6784:
|
|
25
|
-
## \u6838\u5FC3\u53D1\u73B0
|
|
26
|
-
[\u6587\u7AE0\u6700\u91CD\u8981\u7684\u53D1\u73B0/\u521B\u65B0\u70B9]
|
|
27
|
-
|
|
28
|
-
## \u6280\u672F\u7EC6\u8282
|
|
29
|
-
[\u5173\u952E\u7684\u6280\u672F\u65B9\u6CD5/\u5B9E\u73B0\u7EC6\u8282]
|
|
30
|
-
|
|
31
|
-
## \u5F71\u54CD/\u610F\u4E49
|
|
32
|
-
[\u8FD9\u9879\u5DE5\u4F5C\u7684\u610F\u4E49\u6216\u5BF9\u884C\u4E1A\u7684\u5F71\u54CD]
|
|
33
|
-
|
|
34
|
-
## \u539F\u6587\u94FE\u63A5
|
|
35
|
-
[\u6587\u7AE0 URL]`},{id:"save_to_omnifocus",dependsOn:["summarize_article"],prompt:`\u5C06\u6587\u7AE0\u603B\u7ED3\u4FDD\u5B58\u5230 Omnifocus\u3002
|
|
36
|
-
|
|
37
|
-
\u603B\u7ED3\u5185\u5BB9:
|
|
38
|
-
{{summarize_article.result}}
|
|
39
|
-
|
|
40
|
-
\u63D0\u53D6\u6587\u7AE0\u6807\u9898\u548C\u5B8C\u6574\u603B\u7ED3\uFF0C\u7136\u540E\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u6DFB\u52A0\u5230 Omnifocus Inbox\uFF1A
|
|
41
|
-
|
|
42
|
-
osascript /Users/norvyn/Code/Projects/Adam/scripts/add-to-omnifocus.applescript "[\u6587\u7AE0\u6807\u9898] AI \u524D\u6CBF\u901F\u9012" "[\u5B8C\u6574\u603B\u7ED3\u5185\u5BB9]"
|
|
43
|
-
|
|
44
|
-
\u6CE8\u610F\uFF1A
|
|
45
|
-
- \u5C06 [\u6587\u7AE0\u6807\u9898] \u66FF\u6362\u4E3A\u5B9E\u9645\u6807\u9898
|
|
46
|
-
- \u5C06 [\u5B8C\u6574\u603B\u7ED3\u5185\u5BB9] \u66FF\u6362\u4E3A\u5B8C\u6574\u7684\u603B\u7ED3\u6587\u672C\uFF08\u5305\u542B\u6838\u5FC3\u53D1\u73B0\u3001\u6280\u672F\u7EC6\u8282\u3001\u5F71\u54CD/\u610F\u4E49\u548C\u539F\u6587\u94FE\u63A5\uFF09
|
|
47
|
-
- \u603B\u7ED3\u5185\u5BB9\u4F7F\u7528\u6362\u884C\u7B26\u5206\u9694\u5404\u90E8\u5206
|
|
48
|
-
|
|
49
|
-
\u5B8C\u6210\u540E\u8F93\u51FA\uFF1A\u5DF2\u4FDD\u5B58\u5230 Omnifocus\uFF1A[\u4EFB\u52A1\u6807\u9898]`}],config:{timeout:300},tags:["ai","digest","hourly","automation"],createdAt:Date.now()};b(e),n.info({templateId:m,cron:"0 * * * *"},"Registered built-in AI Hourly Digest template")}var A=class{cronJobs=new Map;workflowExecutor=new _;started=!1;taskCompletionHandler=null;workflowCompletionHandler=null;async start(){if(this.started)return;this.started=!0,H();let e=d(!0),t=0;for(let r of e)r.trigger.type==="cron"&&r.trigger.cron&&(this.scheduleCronJob(r),t++);let i=0;for(let r of e)r.trigger.type==="once"&&r.trigger.runAt&&(this.scheduleOnceJob(r.id),i++);this.taskCompletionHandler=r=>{r.newStatus==="completed"&&this.checkEventTriggers(r.taskId).catch(o=>{n.error({taskId:r.taskId,error:o},"Event trigger check failed")})},u.on("task_status_change",this.taskCompletionHandler),this.workflowCompletionHandler=r=>{(r.status==="completed"||r.status==="partial")&&this.checkWorkflowEventTriggers(r.templateId).catch(o=>{n.error({templateId:r.templateId,error:o},"Workflow event trigger check failed")})},u.on("workflow_status_change",this.workflowCompletionHandler),this.cronJobs.set("memory-cleanup",setInterval(()=>{this.runMemoryCleanup()},36e5)),n.info({cronCount:t,onceCount:i},"Bree engine started with cron jobs + memory cleanup")}runMemoryCleanup(){try{let e=v(void 0,1e3,0),t=0;for(let i of e)t+=y(i.id);t>0&&n.info({totalCleaned:t},"Memory cleanup completed")}catch(e){n.warn({error:e},"Memory cleanup failed")}}async stop(){for(let[,e]of this.cronJobs)clearTimeout(e),clearInterval(e);this.cronJobs.clear(),this.taskCompletionHandler&&(u.off("task_status_change",this.taskCompletionHandler),this.taskCompletionHandler=null),this.workflowCompletionHandler&&(u.off("workflow_status_change",this.workflowCompletionHandler),this.workflowCompletionHandler=null),this.started=!1,n.info("Bree engine stopped")}scheduleCronJob(e){let t=`template-${e.id}`;this.cronJobs.has(t)&&(clearTimeout(this.cronJobs.get(t)),this.cronJobs.delete(t));let i;try{i=D.parse(e.trigger.cron)}catch{n.warn({templateId:e.id,cron:e.trigger.cron},"Invalid cron expression");return}let r=()=>{let p=i.next().getTime()-Date.now();return Math.max(p,1e3)},o=()=>{this.executeCronTrigger(e.id).catch(p=>{n.error({templateId:e.id,error:p},"Cron trigger failed")});let f=setTimeout(o,r());this.cronJobs.set(t,f)},s=r(),a=setTimeout(o,s);this.cronJobs.set(t,a),n.debug({jobName:t,nextRun:new Date(Date.now()+s).toISOString()},"Scheduled cron job")}async executeCronTrigger(e){let t=l(e);!t||!t.enabled||(n.info({templateName:t.name},"Cron triggered"),await this.executeWorkflow(t,c()))}async scheduleJob(e){let t=l(e);t&&t.trigger.type==="cron"&&t.trigger.cron&&this.scheduleCronJob(t)}async unscheduleJob(e){let t=`template-${e}`,i=this.cronJobs.get(t);i&&(clearTimeout(i),this.cronJobs.delete(t))}async runNow(e){let t=l(e);if(!t)throw new Error(`Template ${e} not found`);let i=c();return this.executeWorkflow(t,i).catch(r=>{n.error({templateId:e,error:r},"Workflow execution failed")}),i}async checkEventTriggers(e){let t=T(e);if(!t)return;let i=d(!0),r=i.filter(o=>o.trigger.type==="event"&&o.trigger.event==="task_complete");for(let o of r)n.debug({templateName:o.name},"Event trigger matched"),await this.executeWorkflow(o,c());if(t.templateId){let o=i.filter(s=>s.trigger.type!=="event"||!s.trigger.event?!1:s.trigger.event===`template_complete:${t.templateId}`);for(let s of o)n.info({templateName:s.name,sourceTemplateId:t.templateId},"Template complete trigger matched"),await this.executeWorkflow(s,c())}}async executeWorkflow(e,t){if(n.info({templateName:e.name,executionId:t},"Executing workflow"),e.goalIds&&e.goalIds.length>0){for(let r of e.goalIds){let o=C(r);if(!o){n.warn({goalId:r,templateId:e.id},"Goal reference not found, skipping");continue}let s=c();I({id:s,name:o.name,description:o.description,roleId:o.roleId,metricType:o.metricType,targetValue:o.targetValue,currentValue:0,deadline:o.deadline,budgetUsd:o.budgetUsd,status:"active",createdAt:Date.now(),sourceSessionId:e.sourceSessionId,deliverTo:e.deliverTo,reportTo:e.reportTo});let a=c();k({id:a,status:"pending",prompt:`Decompose and execute goal: ${o.name}. ${o.description??""}`,parentId:s,config:w(),createdAt:Date.now(),templateId:e.id,roleId:e.rolePreference,deliverTo:e.deliverTo,reportTo:e.reportTo}),u.emit({type:"task_created",taskId:a}),n.info({templateId:e.id,sourceGoalId:r,newGoalId:s,taskId:a},"Goal reference triggered, dispatched decomposition task")}return}let i=await this.workflowExecutor.execute(e,t);n.info({templateName:e.name,executionId:t,status:i.status,steps:i.stepResults.size},"Workflow execution finished")}async checkWorkflowEventTriggers(e){let i=d(!0).filter(r=>r.trigger.type!=="event"||!r.trigger.event?!1:r.trigger.event===`workflow_complete:${e}`);for(let r of i)n.info({templateName:r.name,sourceTemplateId:e},"Workflow complete trigger matched"),await this.executeWorkflow(r,c())}scheduleOnceJob(e){let t=l(e);if(!t||!t.enabled||t.trigger.type!=="once")return;let r=(t.trigger.runAt?new Date(t.trigger.runAt).getTime():0)-Date.now();if(r<=0){n.info({templateId:e,runAt:t.trigger.runAt},"Once-shot template past due, executing immediately"),this.executeOnceTrigger(e).catch(a=>{n.error({templateId:e,error:a},"Once trigger execution failed")});return}let o=`template-${e}`;this.cronJobs.has(o)&&clearTimeout(this.cronJobs.get(o));let s=setTimeout(()=>{this.cronJobs.delete(o),this.executeOnceTrigger(e).catch(a=>{n.error({templateId:e,error:a},"Once trigger execution failed")})},r);this.cronJobs.set(o,s),n.info({templateId:e,runAt:t.trigger.runAt,delayMs:r},"Scheduled once-shot job")}async executeOnceTrigger(e){let t=l(e);!t||!t.enabled||(n.info({templateName:t.name},"Once-shot triggered"),await this.executeWorkflow(t,c()),x(e),n.info({templateId:e},"Once-shot template auto-disabled after execution"))}},J=null;function U(){return J}function z(g){J=g}export{A as a,U as b,z as c};
|
package/dist/engine-7DFJOADQ.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d}from"./chunk-3567PCEJ.js";import"./chunk-L4Y3GR6W.js";import"./chunk-RUY23IJK.js";import"./chunk-XAMLLKKA.js";import"./chunk-CKIVKM5T.js";import"./chunk-KO5AFX5U.js";import"./chunk-GYHOPV4Q.js";import"./chunk-I5IUTZA3.js";import"./chunk-EZGMA3VV.js";import"./chunk-L7JP7DUO.js";import"./chunk-4VHBKJD5.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as DeliveryEngine,b as getDeliveryEngine,c as initDeliveryEngine,d as stopDeliveryEngine};
|
package/dist/learner-4EO7ZKK4.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as l,e as D,f as S,g as $}from"./chunk-YHH3QMLL.js";import{b as h}from"./chunk-6THDALGC.js";import{b as u}from"./chunk-XAMLLKKA.js";import{e as R,g as T,j as C}from"./chunk-24GTCFEV.js";import{k,m as x,q as N}from"./chunk-J3NIPZ73.js";import"./chunk-QQWRV23T.js";import"./chunk-4VHBKJD5.js";import"./chunk-WBAPIPST.js";import{c as d,h as y}from"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";y();var w=d("agent");function I(n){let o=l(n);if(!o){w.debug({taskId:n},"No plan found for task, skipping review");return}let i=h(n,1e3),s=o.plan.steps,a=i.filter(e=>e.type==="tool_result"||e.type==="permission_denied").map(e=>({toolName:e.toolName??"unknown",output:e.content,planStepIndex:e.planStepIndex,permissionDenied:e.type==="permission_denied"})),t=[],r=new Set(a.map(e=>e.planStepIndex).filter(e=>e!==void 0));for(let e of s)r.has(e.index)||t.push({stepIndex:e.index,planned:e.description,actual:"Not executed",deviationType:"skipped"});let c=a.filter(e=>e.planStepIndex===void 0);for(let e of c)t.push({stepIndex:-1,planned:"",actual:`${e.toolName}: ${e.output.slice(0,200)}`,deviationType:"added"});let b=a.filter(e=>e.permissionDenied);for(let e of b)t.push({stepIndex:e.planStepIndex??-1,planned:e.planStepIndex!==void 0?s.find(E=>E.index===e.planStepIndex)?.description??"Unknown":"",actual:`PERMISSION DENIED: ${e.toolName}`,deviationType:"failed"});let p=s.length,m=a.length,g=p>0?Math.max(0,1-t.filter(e=>e.deviationType!=="added").length/p):1,v={stepsPlanned:p,stepsExecuted:m,deviations:t,overallAccuracy:g};return S(o.id,v),w.info({taskId:n,planId:o.id,stepsPlanned:p,stepsExecuted:m,deviationCount:t.length,accuracy:g},"Deviation report generated"),v}function P(n){return n.deviations.filter(i=>i.deviationType==="failed"||i.deviationType==="skipped").length===0&&n.overallAccuracy>=.7}N();C();y();var f=d("agent");function L(n,o){let i=[],a=u(n)?.prompt.slice(0,100)??"unknown task";P(o)&&i.push(`[+] Task "${a}" completed successfully with ${o.overallAccuracy*100}% plan accuracy (${o.stepsExecuted} steps). [sourceTaskId:${n}]`);for(let t of o.deviations)switch(t.deviationType){case"skipped":i.push(`[-] Planned step "${t.planned}" was skipped during "${a}". Consider if this step is necessary for similar tasks. [sourceTaskId:${n}]`);break;case"failed":i.push(`[-] Step failed: "${t.actual}" during "${a}". Check permissions and tool availability. [sourceTaskId:${n}]`);break;case"added":i.push(`[~] Unplanned action: "${t.actual}" during "${a}". Consider adding to plan for similar tasks. [sourceTaskId:${n}]`);break;case"modified":i.push(`[~] Step modified: planned "${t.planned}" but did "${t.actual}" during "${a}". [sourceTaskId:${n}]`);break}return i}async function z(n){let o=l(n);if(!o){f.debug({taskId:n},"No plan for task, skipping review/learn");return}let i=I(n);if(!i)return;let s=L(n,i);if(s.length===0)return;$(o.id,s);let a=u(n);if(a?.roleId){let t=k(a.roleId);if(t){let r=[...t.learnedRules,...s];x(a.roleId,{learnedRules:r});let c=R(t.name);T(c,{...t,learnedRules:r}),f.info({roleId:a.roleId,newRulesCount:s.length},"Role learnedRules updated and CLAUDE.md written")}}D(o.id,"completed"),f.info({taskId:n,planId:o.id,rulesExtracted:s.length,accuracy:i.overallAccuracy},"Task review and learning completed")}export{L as extractRulesFromDeviation,z as processTaskReview};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c}from"./chunk-NZEDILAK.js";import"./chunk-2CMR5AG7.js";import"./chunk-7BSWC62F.js";import"./chunk-J3NIPZ73.js";import"./chunk-QQWRV23T.js";import"./chunk-4VHBKJD5.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.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-CKIVKM5T.js";import"./chunk-KO5AFX5U.js";import"./chunk-EZGMA3VV.js";import"./chunk-L7JP7DUO.js";import"./chunk-4VHBKJD5.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as OutboundGateway,b as getOutboundGateway,c as isRecentlySent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b}from"./chunk-DMZM7RU6.js";import"./chunk-24GTCFEV.js";import"./chunk-J3NIPZ73.js";import"./chunk-QQWRV23T.js";import"./chunk-4VHBKJD5.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as CHAT_MANAGER_ROLE_ID,b as initializeDefaultRoles};
|
package/dist/roles-3AEHVOEW.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{i as a,j as b,k as c,l as d,m as e,n as f,o as g,q as h}from"./chunk-J3NIPZ73.js";import"./chunk-QQWRV23T.js";import"./chunk-4VHBKJD5.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";h();export{b as createRole,g as deleteRole,c as getRole,d as getRoleByName,f as listRoles,e as updateRole,a as validateAdditionalDirectories};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as a}from"./chunk-I67UMGJM.js";import"./chunk-YHVFZB6Q.js";import"./chunk-XAMLLKKA.js";import"./chunk-CKIVKM5T.js";import"./chunk-KO5AFX5U.js";import"./chunk-EZGMA3VV.js";import"./chunk-L7JP7DUO.js";import"./chunk-7K4AQBDD.js";import"./chunk-UQJZU3R5.js";import"./chunk-7IFLU3CY.js";import"./chunk-GSMC3VUM.js";import"./chunk-J3NIPZ73.js";import"./chunk-QQWRV23T.js";import"./chunk-4VHBKJD5.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as WorkflowExecutor};
|