adam-agent-server 1.19.0 → 1.19.1
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/approval-handler-GXIVBJ4Z.js +1 -0
- package/dist/artifacts-DDHH47IE.js +1 -0
- package/dist/audit-diagnostics-HLHS3MHM.js +1 -0
- package/dist/audit-manager-PDMOR2MX.js +1 -0
- package/dist/bree-engine-6UKRI4UN.js +1 -0
- package/dist/{channels-ZHCTFSDA.js → channels-3J6U6GYH.js} +1 -1
- package/dist/channels-YOBMSBWV.js +1 -0
- package/dist/{chat-tool-calls-4BQWZCJH.js → chat-tool-calls-5Z53IXRF.js} +1 -1
- package/dist/{chunk-4ZESWP3J.js → chunk-2BLSA25Q.js} +1 -1
- package/dist/{chunk-WG3C43QS.js → chunk-3JTHJ3FZ.js} +1 -1
- package/dist/{chunk-PO66F7UQ.js → chunk-4NRIKWSD.js} +1 -1
- package/dist/{chunk-VZL2DGC4.js → chunk-5ZL6RHPE.js} +1 -1
- package/dist/{chunk-6GYNUTPP.js → chunk-6GVYOHD5.js} +5 -5
- package/dist/{chunk-GQS3ED3B.js → chunk-6NIWU43Z.js} +1 -1
- package/dist/{chunk-4ZG4UMAK.js → chunk-6SBLFYCU.js} +1 -1
- package/dist/{chunk-FN64ZULV.js → chunk-AKQ3AFVI.js} +1 -1
- package/dist/{chunk-JXZCQ5XW.js → chunk-CQDOIHPV.js} +1 -1
- package/dist/{chunk-QJXV4SQE.js → chunk-EXB2JIBR.js} +1 -1
- package/dist/{chunk-ORFLN4BF.js → chunk-G5I76LX2.js} +1 -1
- package/dist/{chunk-HEHST2E2.js → chunk-GYOZGA7G.js} +1 -1
- package/dist/{chunk-CN5NEJXG.js → chunk-ISTUK7Q6.js} +1 -1
- package/dist/chunk-J4JO7O3T.js +182 -0
- package/dist/{chunk-2JM3URDG.js → chunk-KO6UB6VW.js} +1 -1
- package/dist/chunk-LE5YRP37.js +14 -0
- package/dist/{chunk-FQHGIY3E.js → chunk-N4BV2WAU.js} +1 -1
- package/dist/{chunk-VOH52UDS.js → chunk-NUTGYMDP.js} +1 -1
- package/dist/{chunk-4G4CKAXY.js → chunk-NX3CIEZA.js} +1 -1
- package/dist/{chunk-ZGA52HRD.js → chunk-P2EDMFVO.js} +1 -1
- package/dist/{chunk-DRS5NOAA.js → chunk-PU2T7HBY.js} +1 -1
- package/dist/{chunk-R7Q6FSV4.js → chunk-PZH5NKUL.js} +11 -11
- package/dist/{chunk-EPLSB63A.js → chunk-QF3B4OWI.js} +1 -1
- package/dist/{chunk-JVYSSJKT.js → chunk-QQWUWGSK.js} +2 -2
- package/dist/{chunk-DFTRUOT6.js → chunk-QX65LEYA.js} +1 -1
- package/dist/{chunk-IAGTZGGV.js → chunk-R3MSLP6P.js} +2 -2
- package/dist/{chunk-KM4EFB4N.js → chunk-SDHMBWVC.js} +1 -1
- package/dist/{chunk-A3YUIWLK.js → chunk-SONOE4ZJ.js} +1 -1
- package/dist/{chunk-WDMSZS4W.js → chunk-VVPB3TD4.js} +1 -1
- package/dist/{chunk-L4APYD5A.js → chunk-X3PJNX2R.js} +1 -1
- package/dist/{chunk-EBZCHLYS.js → chunk-XEXSXMWK.js} +1 -1
- package/dist/{chunk-7QT2ZX3K.js → chunk-YGR5ZTGT.js} +1 -1
- package/dist/{chunk-76MMY2XC.js → chunk-YGZQMZTA.js} +1 -1
- package/dist/{chunk-YEGUFMLJ.js → chunk-YI2QQTZE.js} +1 -1
- package/dist/{chunk-KQMKRRYW.js → chunk-ZARKPBI2.js} +45 -45
- package/dist/{chunk-LMQPGVM7.js → chunk-ZEGZ2I35.js} +4 -4
- package/dist/cli.js +1 -1
- package/dist/{config-GOJLI3X2.js → config-7Y7I7KX4.js} +1 -1
- package/dist/{db-ROXIYW5B.js → db-P7ELD5DS.js} +1 -1
- package/dist/{delivery-log-TGJZ5HU7.js → delivery-log-EVRKJ5GD.js} +1 -1
- package/dist/engine-FE7NCHOG.js +1 -0
- package/dist/{evolution-audit-TFJF666X.js → evolution-audit-XIWF3JIF.js} +1 -1
- package/dist/execution-tools-PGURN3N6.js +1 -0
- package/dist/index.js +68 -67
- package/dist/{learner-ACBX3GI7.js → learner-PWDQUZ5O.js} +1 -1
- package/dist/{memories-RAIR5O2F.js → memories-2OJFLLBT.js} +1 -1
- package/dist/{memory-extractor-A6CAOFOX.js → memory-extractor-N7M4YSPL.js} +1 -1
- package/dist/{memory-gc-W63MGSDH.js → memory-gc-R42SPM52.js} +1 -1
- package/dist/memory-service-V7B5MY37.js +1 -0
- package/dist/outbound-gateway-NHNHVHF2.js +1 -0
- package/dist/presets-H2UV3HIF.js +1 -0
- package/dist/{reflection-job-XC2F7GTT.js → reflection-job-ECJX5ERQ.js} +1 -1
- package/dist/role-presets-7SWGUPV2.js +1 -0
- package/dist/role-workspace-AOYIGLG4.js +1 -0
- package/dist/{roles-LZCJ7QFS.js → roles-5TWJBGAQ.js} +1 -1
- package/dist/{session-manager-PU4GH3E4.js → session-manager-5P2FAEV3.js} +1 -1
- package/dist/skill-registry-XOX4OSHY.js +1 -0
- package/dist/{task-templates-52LAC6OA.js → task-templates-CTQHB6TA.js} +1 -1
- package/dist/template-dispatch-Z2TKWOMY.js +1 -0
- package/package.json +1 -1
- package/dist/approval-handler-S3NV7OPO.js +0 -1
- package/dist/artifacts-NFMM3ORE.js +0 -1
- package/dist/audit-diagnostics-IHU3CJYZ.js +0 -1
- package/dist/audit-manager-MUMEEP3C.js +0 -1
- package/dist/bree-engine-EEKUQA3U.js +0 -1
- package/dist/channels-IDBWHLLE.js +0 -1
- package/dist/chunk-MMVDXKYS.js +0 -14
- package/dist/chunk-NKS7LEA7.js +0 -182
- package/dist/engine-GN7PJPGQ.js +0 -1
- package/dist/execution-tools-BQD2O25X.js +0 -1
- package/dist/memory-service-H4OFUNCF.js +0 -1
- package/dist/outbound-gateway-LKRQYPA2.js +0 -1
- package/dist/presets-FO6RSGDN.js +0 -1
- package/dist/role-presets-SDA664QG.js +0 -1
- package/dist/role-workspace-NGJEJG3H.js +0 -1
- package/dist/skill-registry-XKLE2LXU.js +0 -1
- package/dist/template-dispatch-PJFSWEO2.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as c,e as S,f as $,g as P}from"./chunk-
|
|
1
|
+
import{d as c,e as S,f as $,g as P}from"./chunk-EXB2JIBR.js";import{b as R}from"./chunk-KO6UB6VW.js";import{e as T,g as D,i as N}from"./chunk-6NIWU43Z.js";import{D as x,F as k,L,b as f,p as E}from"./chunk-3JTHJ3FZ.js";import"./chunk-ISTUK7Q6.js";import"./chunk-ZEGZ2I35.js";import"./chunk-ITVCPC7G.js";import{c as p,h}from"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";h();var w=p("agent");function I(n){let o=c(n);if(!o){w.debug({taskId:n},"No plan found for task, skipping review");return}let i=R(n,1e3),a=o.plan.steps,s=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(s.map(e=>e.planStepIndex).filter(e=>e!==void 0));for(let e of a)r.has(e.index)||t.push({stepIndex:e.index,planned:e.description,actual:"Not executed",deviationType:"skipped"});let d=s.filter(e=>e.planStepIndex===void 0);for(let e of d)t.push({stepIndex:-1,planned:"",actual:`${e.toolName}: ${e.output.slice(0,200)}`,deviationType:"added"});let u=s.filter(e=>e.permissionDenied);for(let e of u)t.push({stepIndex:e.planStepIndex??-1,planned:e.planStepIndex!==void 0?a.find(b=>b.index===e.planStepIndex)?.description??"Unknown":"",actual:`PERMISSION DENIED: ${e.toolName}`,deviationType:"failed"});let l=a.length,g=s.length,v=l>0?Math.max(0,1-t.filter(e=>e.deviationType!=="added").length/l):1,y={stepsPlanned:l,stepsExecuted:g,deviations:t,overallAccuracy:v};return $(o.id,y),w.info({taskId:n,planId:o.id,stepsPlanned:l,stepsExecuted:g,deviationCount:t.length,accuracy:v},"Deviation report generated"),y}function A(n){return n.deviations.filter(i=>i.deviationType==="failed"||i.deviationType==="skipped").length===0&&n.overallAccuracy>=.7}E();L();N();h();var m=p("agent");function C(n){let o=[],i=[];for(let a of n)a.startsWith("[-]")?i.push(a):o.push(a);return{stylePreferences:o,avoidedActions:i}}function U(n,o){let i=[],s=f(n)?.prompt.slice(0,100)??"unknown task";A(o)&&i.push(`[+] Task "${s}" 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 "${s}". Consider if this step is necessary for similar tasks. [sourceTaskId:${n}]`);break;case"failed":i.push(`[-] Step failed: "${t.actual}" during "${s}". Check permissions and tool availability. [sourceTaskId:${n}]`);break;case"added":i.push(`[~] Unplanned action: "${t.actual}" during "${s}". Consider adding to plan for similar tasks. [sourceTaskId:${n}]`);break;case"modified":i.push(`[~] Step modified: planned "${t.planned}" but did "${t.actual}" during "${s}". [sourceTaskId:${n}]`);break}return i}async function H(n){let o=c(n);if(!o){m.debug({taskId:n},"No plan for task, skipping review/learn");return}let i=I(n);if(!i)return;let a=U(n,i);if(a.length===0)return;P(o.id,a);let s=f(n);if(s?.roleId){let t=x(s.roleId);if(t){let r=C(a),d={stylePreferences:[...t.learnedRules.stylePreferences,...r.stylePreferences],avoidedActions:[...t.learnedRules.avoidedActions,...r.avoidedActions],pinnedParameters:t.learnedRules.pinnedParameters};k(s.roleId,{learnedRules:d});let u=T(t.name);D(u,{...t,learnedRules:d}),m.info({roleId:s.roleId,newRulesCount:a.length},"Role learnedRules updated and CLAUDE.md written")}}S(o.id,"completed"),m.info({taskId:n,planId:o.id,rulesExtracted:a.length,accuracy:i.overallAccuracy},"Task review and learning completed")}export{U as extractRulesFromDeviation,H as processTaskReview};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r}from"./chunk-
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r}from"./chunk-AKQ3AFVI.js";import"./chunk-3JTHJ3FZ.js";import"./chunk-ISTUK7Q6.js";import"./chunk-ZEGZ2I35.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";export{p as DEFAULT_HYBRID_CONFIG,l as DEFAULT_SCORING_WEIGHTS,m as calculateRecency,n as calculateSmallvilleScore,q as cleanupMemories,h as cosineSimilarity,f as countMemoriesByRole,a as createMemory,k as deleteMemory,b as getMemory,o as getRoleScoringWeights,g as listMemoriesByRole,e as markSuperseded,j as searchByBM25,i as searchByVector,r as searchHybrid,c as updateMemory,d as updateMemoryRetrievalCount};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as i}from"./chunk-
|
|
1
|
+
import{b as i}from"./chunk-KO6UB6VW.js";import{b as p}from"./chunk-T2Z2JDPY.js";import{a}from"./chunk-AKQ3AFVI.js";import"./chunk-3JTHJ3FZ.js";import"./chunk-ISTUK7Q6.js";import"./chunk-3MROEPGR.js";import"./chunk-ZEGZ2I35.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";import{v4 as u}from"uuid";function l(o){let r=o.toolName,e=o.toolOutput||o.content;if(r==="Write"||r==="Edit")return{content:`Modified file via ${r}: ${e.slice(0,400)}`,importance:4,type:"event"};if(r==="Bash"){let t=o.toolInput?.command?.slice(0,100)||"Bash";return e.includes("FAIL")||e.includes("error:")||e.includes("Error:")?{content:`Command failed: ${t} ${e.slice(0,300)}`,importance:4,type:"event"}:e.includes("success")||e.includes("done")||e.includes("OK")?{content:`Command succeeded: ${t}`,importance:2,type:"event"}:{content:`Executed: ${t}`,importance:1,type:"event"}}return null}function y(o){let r=i(o,500,0),e=[];for(let t of r)if((t.type==="tool_result"||t.type==="tool_call")&&t.toolName){let n=l(t);n&&e.push(n)}else t.type==="error"&&e.push({content:`Error occurred: ${t.content.slice(0,400)}`,importance:4,type:"event"});return{facts:e}}function f(o){let r=o.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(e=>e.length>2);return[...new Set(r)].slice(0,20)}async function M(o,r){let{facts:e}=y(o);for(let n of e)if(n.type!=="event")throw new Error(`extractKeyFacts produced non-event fact (type=${n.type}) \u2014 GAP-08 invariant violated`);let t=0;for(let n of e){let c=n.content.slice(0,500),s;try{s=await p(c)}catch{}let m=f(c),d={id:u(),roleId:r,type:n.type,content:c,embedding:s,keywords:m,importance:n.importance,sourceType:"task_complete",sourceTaskId:o,createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"episodic"};a(d),t++}return t}export{y as extractKeyFacts,M as processTaskCompletion};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as f,e as p}from"./chunk-
|
|
1
|
+
import{d as f,e as p}from"./chunk-4NRIKWSD.js";import{c as m}from"./chunk-6SBLFYCU.js";import"./chunk-AKQ3AFVI.js";import{K as l,L as y}from"./chunk-3JTHJ3FZ.js";import"./chunk-ISTUK7Q6.js";import"./chunk-3MROEPGR.js";import{o as a,q as g}from"./chunk-ZEGZ2I35.js";import"./chunk-ITVCPC7G.js";import{c,h as E}from"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";g();y();E();var R=c("manager");function C(b){let o=a(),i=Date.now(),s=i-b.observationTtlDays*864e5,n=o.prepare("DELETE FROM memories WHERE created_at < ? AND kind = 'observation'").run(s).changes,d=o.prepare("SELECT DISTINCT role_id FROM beliefs WHERE status='active'").all().map(e=>e.role_id),r=0;for(let e of d){let u=l(e),v=m(e,{onlyActive:!0});for(let t of v)t.isAnti||f(t,u)&&(p(t.id),r++)}return o.prepare("UPDATE server_state SET last_memory_gc_at = ? WHERE id = 1").run(i),R.info({observationsDeleted:n,beliefsArchived:r,obsCutoff:s},"Memory GC completed"),{observationsDeleted:n,beliefsArchived:r}}export{C as memoryGcTick};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as a,d as b,e as c}from"./chunk-GYOZGA7G.js";import"./chunk-4NRIKWSD.js";import"./chunk-6SBLFYCU.js";import"./chunk-T2Z2JDPY.js";import"./chunk-AKQ3AFVI.js";import"./chunk-3JTHJ3FZ.js";import"./chunk-ISTUK7Q6.js";import"./chunk-3MROEPGR.js";import"./chunk-ZEGZ2I35.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";export{b as getRelevantMemoryContext,a as queryMemory,c as queryMemoryByTier};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{h as a,i as b,j as c,k as d}from"./chunk-R3MSLP6P.js";import"./chunk-PU2T7HBY.js";import"./chunk-5ZL6RHPE.js";import"./chunk-YI2QQTZE.js";import"./chunk-NX3CIEZA.js";import"./chunk-X3PJNX2R.js";import"./chunk-G5I76LX2.js";import"./chunk-L7JP7DUO.js";import"./chunk-3JTHJ3FZ.js";import"./chunk-XEXSXMWK.js";import"./chunk-ISTUK7Q6.js";import"./chunk-J2VSAXVU.js";import"./chunk-3MROEPGR.js";import"./chunk-6GVYOHD5.js";import"./chunk-ZEGZ2I35.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";export{a as OutboundGateway,b as _resetChannelManagerModuleCache,c as getOutboundGateway,d as isRecentlySent};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o}from"./chunk-QX65LEYA.js";import"./chunk-LE5YRP37.js";import"./chunk-N4BV2WAU.js";import"./chunk-KO6UB6VW.js";import"./chunk-X3PJNX2R.js";import"./chunk-6NIWU43Z.js";import"./chunk-G5I76LX2.js";import"./chunk-L7JP7DUO.js";import"./chunk-GYOZGA7G.js";import"./chunk-4NRIKWSD.js";import"./chunk-6SBLFYCU.js";import"./chunk-T2Z2JDPY.js";import"./chunk-AKQ3AFVI.js";import"./chunk-3JTHJ3FZ.js";import"./chunk-ISTUK7Q6.js";import"./chunk-3MROEPGR.js";import"./chunk-6GVYOHD5.js";import"./chunk-ZEGZ2I35.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";export{a as ADAM_AUTOMATOR_PRESET,d as CHAT_MANAGER_ROLE_ID,e as PRESET_ROLE_NAMES,b as ROLE_PRESETS,c as TEMPLATE_PRESETS,h as ensureAdamAutomatorRole,g as ensureChatManagerRole,l as getPresetRole,j as getPresetRoles,m as getPresetTemplate,k as getPresetTemplates,i as initializeDefaultRoles,f as isPresetRole,o as restorePreset,n as seedPresets};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{d as x}from"./chunk-
|
|
1
|
+
import{d as x}from"./chunk-QF3B4OWI.js";import{a as O}from"./chunk-SONOE4ZJ.js";import"./chunk-VVPB3TD4.js";import{a as I}from"./chunk-L7JP7DUO.js";import{a as v,c as N,d as F,e as A}from"./chunk-6SBLFYCU.js";import{b as j}from"./chunk-T2Z2JDPY.js";import{g as U}from"./chunk-AKQ3AFVI.js";import{K as $,L as H}from"./chunk-3JTHJ3FZ.js";import"./chunk-ISTUK7Q6.js";import{e as m}from"./chunk-3MROEPGR.js";import{o as M,q as P}from"./chunk-ZEGZ2I35.js";import"./chunk-ITVCPC7G.js";import{c as b,h as E}from"./chunk-EZLBMUQD.js";import{c as S,e as V}from"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";P();E();V();import{v4 as T}from"uuid";E();var J=5;function C(){try{let e=m().memory?.reflection?.maxBudgetUsd;if(typeof e=="number"&&Number.isFinite(e)&&e>0)return e}catch{}return J}var K=b("manager");function W(e){let t=e.trim(),s=t.match(/^```(\w*)\s*/);return s&&(t=t.slice(s[0].length)),t.endsWith("```")&&(t=t.slice(0,t.length-3)),t.trim()}function Y(e,t){let s=W(e),c;try{c=JSON.parse(s)}catch{return{action:"coexist"}}if(!c||typeof c!="object")return{action:"coexist"};let n=c;if(n.action==="coexist")return{action:"coexist"};if(n.action==="merge"){let o=typeof n.intoBeliefId=="string"?n.intoBeliefId.trim():"",i=typeof n.mergedContent=="string"?n.mergedContent.trim():"";return o.length>0&&i.length>0&&t.some(r=>r.id===o)?{action:"merge",intoBeliefId:o,mergedContent:i}:{action:"coexist"}}if(n.action==="supersede"){let o=typeof n.oldBeliefId=="string"?n.oldBeliefId.trim():"";return o.length>0&&t.some(i=>i.id===o)?{action:"supersede",oldBeliefId:o}:{action:"coexist"}}return{action:"coexist"}}async function L(e,t){if(t.length===0)return{action:"coexist"};let c=m().anthropic?.defaultHaikuModel||"claude-haiku-4-5",o=`You are a belief conflict resolver.
|
|
2
2
|
|
|
3
3
|
Existing beliefs for this role:
|
|
4
4
|
${t.map((i,r)=>`${r+1}. id=${i.id} ${i.content}`).join(`
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./chunk-QMW7VEPC.js";import{a,d as b,e as c,f as d,g as e,h as f,i as g}from"./chunk-QX65LEYA.js";import"./chunk-LE5YRP37.js";import"./chunk-N4BV2WAU.js";import"./chunk-KO6UB6VW.js";import"./chunk-X3PJNX2R.js";import"./chunk-6NIWU43Z.js";import"./chunk-G5I76LX2.js";import"./chunk-L7JP7DUO.js";import"./chunk-GYOZGA7G.js";import"./chunk-4NRIKWSD.js";import"./chunk-6SBLFYCU.js";import"./chunk-T2Z2JDPY.js";import"./chunk-AKQ3AFVI.js";import"./chunk-3JTHJ3FZ.js";import"./chunk-ISTUK7Q6.js";import"./chunk-3MROEPGR.js";import"./chunk-6GVYOHD5.js";import"./chunk-ZEGZ2I35.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";export{a as ADAM_AUTOMATOR_PRESET,b as CHAT_MANAGER_ROLE_ID,c as PRESET_ROLE_NAMES,f as ensureAdamAutomatorRole,e as ensureChatManagerRole,g as initializeDefaultRoles,d as isPresetRole};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{e as a,f as b,g as c,h as d,i as e}from"./chunk-6NIWU43Z.js";import"./chunk-3JTHJ3FZ.js";import"./chunk-ISTUK7Q6.js";import"./chunk-ZEGZ2I35.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";e();export{b as ensureRoleWorkspace,a as getRoleWorkspacePath,d as syncRoleSettings,c as writeRoleCLAUDEmd};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{B as a,C as b,D as c,E as d,F as e,G as f,H as g,I as h,J as i,K as j,L as k}from"./chunk-
|
|
1
|
+
import{B as a,C as b,D as c,E as d,F as e,G as f,H as g,I as h,J as i,K as j,L as k}from"./chunk-3JTHJ3FZ.js";import"./chunk-ISTUK7Q6.js";import"./chunk-ZEGZ2I35.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";k();export{b as createRole,h as deleteRole,c as getRole,d as getRoleByName,j as getRoleTaskSeq,g as hasActiveTasks,i as incrementRoleTaskSeq,f as listRoles,e as updateRole,a as validateAdditionalDirectories};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as b,b as c,c as d,d as e,e as f,f as g,g as h,h as i,i as j,j as k,k as l,l as m,m as n,n as o,o as p,p as q}from"./chunk-
|
|
1
|
+
import{a as b,b as c,c as d,d as e,e as f,f as g,g as h,h as i,i as j,j as k,k as l,l as m,m as n,n as o,o as p,p as q}from"./chunk-2BLSA25Q.js";import"./chunk-VVPB3TD4.js";import{f as a}from"./chunk-YI2QQTZE.js";import"./chunk-L7JP7DUO.js";import"./chunk-T2Z2JDPY.js";import"./chunk-AKQ3AFVI.js";import"./chunk-3JTHJ3FZ.js";import"./chunk-ISTUK7Q6.js";import"./chunk-T7EKW3B7.js";import"./chunk-J2VSAXVU.js";import"./chunk-JRRNGKDK.js";import"./chunk-3MROEPGR.js";import"./chunk-ZEGZ2I35.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";export{q as _resetForTest,f as archiveSession,c as createSession,h as deleteSession,d as getActiveSession,e as getSession,n as getTimeoutPollerInterval,j as incrementMessageCount,o as initSessionManager,k as listSessions,g as restoreSession,p as shutdownSessionManager,l as startTimeoutPoller,m as stopTimeoutPoller,i as touchSession,a as updateSessionSdkId,b as warmCache};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a}from"./chunk-P2EDMFVO.js";import"./chunk-SDHMBWVC.js";import"./chunk-6NIWU43Z.js";import"./chunk-3JTHJ3FZ.js";import"./chunk-ISTUK7Q6.js";import"./chunk-ZEGZ2I35.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";export{a as SkillRegistry};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as a,o as b,p as c,q as d,r as e,s as f,t as g,u as h,v as i,w as j,x as k,y as l}from"./chunk-
|
|
1
|
+
import{n as a,o as b,p as c,q as d,r as e,s as f,t as g,u as h,v as i,w as j,x as k,y as l}from"./chunk-G5I76LX2.js";import"./chunk-3JTHJ3FZ.js";import"./chunk-ISTUK7Q6.js";import"./chunk-ZEGZ2I35.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";export{b as TemplateRoleConfigError,a as TemplateValidationError,e as createTaskTemplate,l as deleteTaskTemplate,j as disableTaskTemplate,i as enableTaskTemplate,f as getTaskTemplate,k as getTaskTemplateDependents,h as listTaskTemplates,g as updateTaskTemplate,d as validateTemplateDefinition,c as validateTemplateRoleConfig};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as a}from"./chunk-ZARKPBI2.js";import"./chunk-PZH5NKUL.js";import"./chunk-EXB2JIBR.js";import"./chunk-QF3B4OWI.js";import"./chunk-SDHMBWVC.js";import"./chunk-2BLSA25Q.js";import"./chunk-4N5G7ND2.js";import"./chunk-VVPB3TD4.js";import"./chunk-NNMQGISW.js";import"./chunk-R3MSLP6P.js";import"./chunk-PU2T7HBY.js";import"./chunk-5ZL6RHPE.js";import"./chunk-YI2QQTZE.js";import"./chunk-NX3CIEZA.js";import"./chunk-N4BV2WAU.js";import"./chunk-KO6UB6VW.js";import"./chunk-X3PJNX2R.js";import"./chunk-6NIWU43Z.js";import"./chunk-G5I76LX2.js";import"./chunk-L7JP7DUO.js";import"./chunk-T2Z2JDPY.js";import"./chunk-AKQ3AFVI.js";import"./chunk-3JTHJ3FZ.js";import"./chunk-XEXSXMWK.js";import"./chunk-ISTUK7Q6.js";import"./chunk-T7EKW3B7.js";import"./chunk-J2VSAXVU.js";import"./chunk-JRRNGKDK.js";import"./chunk-3MROEPGR.js";import"./chunk-6GVYOHD5.js";import"./chunk-ZEGZ2I35.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";export{a as dispatchTemplate};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "adam-agent-server",
|
|
3
|
-
"version": "1.19.
|
|
3
|
+
"version": "1.19.1",
|
|
4
4
|
"description": "Goal-driven AI agent orchestration server with Role+Skill model, real-time streaming, and multi-channel delivery",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "norvyn https://x.com/norvynzhang https://github.com/n0rvyn norvynzhang@gmail.com",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as a,d as b,e as c,f as d,g as e}from"./chunk-76MMY2XC.js";import"./chunk-IAGTZGGV.js";import"./chunk-DRS5NOAA.js";import"./chunk-VZL2DGC4.js";import"./chunk-YEGUFMLJ.js";import"./chunk-4G4CKAXY.js";import"./chunk-L4APYD5A.js";import"./chunk-ORFLN4BF.js";import"./chunk-L7JP7DUO.js";import"./chunk-WG3C43QS.js";import"./chunk-EBZCHLYS.js";import"./chunk-CN5NEJXG.js";import"./chunk-J2VSAXVU.js";import"./chunk-3MROEPGR.js";import"./chunk-6GYNUTPP.js";import"./chunk-LMQPGVM7.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";export{b as formatPlanForChannel,e as getPendingApprovalRequestIds,d as handleInboundForApproval,a as parseApprovalReply,c as sendApprovalToChannel};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r}from"./chunk-6GYNUTPP.js";import"./chunk-LMQPGVM7.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5PELJRUQ.js";r();export{n as appendArtifactToCollection,o as convertPrimaryFileToCollectionInTransaction,a as createArtifact,j as deleteArtifactById,h as deleteArtifactsByExecution,i as deleteArtifactsByExecutionAndStep,m as ensureUniqueArtifactKey,b as getArtifact,c as getArtifactById,l as isArtifactCollectionManifest,q as listArtifacts,f as listArtifactsByChatSession,d as listArtifactsByExecution,g as listArtifactsByRole,e as listArtifactsByTask,p as listExpiredExecutions,k as removeArtifact};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,d as c}from"./chunk-4G4CKAXY.js";import"./chunk-LMQPGVM7.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";c();export{b as listAuditDiagnostics,a as recordAuditDiagnostic};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{M as a,N as b,O as c,P as d,Q as e,R as f,S as g}from"./chunk-NKS7LEA7.js";import"./chunk-QMW7VEPC.js";import"./chunk-R7Q6FSV4.js";import"./chunk-QJXV4SQE.js";import"./chunk-EPLSB63A.js";import"./chunk-KM4EFB4N.js";import"./chunk-A3YUIWLK.js";import"./chunk-WDMSZS4W.js";import"./chunk-DRS5NOAA.js";import"./chunk-DFTRUOT6.js";import"./chunk-MMVDXKYS.js";import"./chunk-FQHGIY3E.js";import"./chunk-2JM3URDG.js";import"./chunk-L4APYD5A.js";import"./chunk-GQS3ED3B.js";import"./chunk-ORFLN4BF.js";import"./chunk-L7JP7DUO.js";import"./chunk-HEHST2E2.js";import"./chunk-PO66F7UQ.js";import"./chunk-4ZG4UMAK.js";import"./chunk-T2Z2JDPY.js";import"./chunk-FN64ZULV.js";import"./chunk-WG3C43QS.js";import"./chunk-AUSR5JYV.js";import"./chunk-CN5NEJXG.js";import"./chunk-J2VSAXVU.js";import"./chunk-3MROEPGR.js";import"./chunk-6GYNUTPP.js";import"./chunk-LMQPGVM7.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";export{e as auditAssistantCommitment,f as auditDeliveryClaims,a as evaluateTaskCompletion,g as getSecurityPosture,d as reportViolation,b as startAuditManager,c as stopAuditManager};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c}from"./chunk-7QT2ZX3K.js";import"./chunk-KQMKRRYW.js";import"./chunk-R7Q6FSV4.js";import"./chunk-QJXV4SQE.js";import"./chunk-EPLSB63A.js";import"./chunk-KM4EFB4N.js";import"./chunk-4ZESWP3J.js";import"./chunk-4N5G7ND2.js";import"./chunk-WDMSZS4W.js";import"./chunk-NNMQGISW.js";import"./chunk-IAGTZGGV.js";import"./chunk-DRS5NOAA.js";import"./chunk-VZL2DGC4.js";import"./chunk-YEGUFMLJ.js";import"./chunk-4G4CKAXY.js";import"./chunk-FQHGIY3E.js";import"./chunk-2JM3URDG.js";import"./chunk-L4APYD5A.js";import"./chunk-GQS3ED3B.js";import"./chunk-ORFLN4BF.js";import"./chunk-L7JP7DUO.js";import"./chunk-T2Z2JDPY.js";import"./chunk-FN64ZULV.js";import"./chunk-WG3C43QS.js";import"./chunk-EBZCHLYS.js";import"./chunk-CN5NEJXG.js";import"./chunk-T7EKW3B7.js";import"./chunk-J2VSAXVU.js";import"./chunk-JRRNGKDK.js";import"./chunk-3MROEPGR.js";import"./chunk-6GYNUTPP.js";import"./chunk-LMQPGVM7.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";export{a as BreeEngine,b as getBreeEngine,c as setBreeEngine};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{i as a,j as b,k as c}from"./chunk-JXZCQ5XW.js";import"./chunk-WDMSZS4W.js";import"./chunk-NNMQGISW.js";import"./chunk-VZL2DGC4.js";import"./chunk-YEGUFMLJ.js";import"./chunk-4G4CKAXY.js";import"./chunk-EBZCHLYS.js";import"./chunk-J2VSAXVU.js";import"./chunk-3MROEPGR.js";import"./chunk-LMQPGVM7.js";import"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";export{c as channelRoutes,b as getChannelManager,a as setChannelManager};
|
package/dist/chunk-MMVDXKYS.js
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
import{a as D,g as Be}from"./chunk-FQHGIY3E.js";import{a as Te}from"./chunk-2JM3URDG.js";import{b as ie}from"./chunk-L4APYD5A.js";import{e as Re,i as st}from"./chunk-GQS3ED3B.js";import{b as pe,k as me,m as re,s as oe}from"./chunk-ORFLN4BF.js";import{a as Oe}from"./chunk-L7JP7DUO.js";import{c as $e}from"./chunk-HEHST2E2.js";import{b as Me}from"./chunk-T2Z2JDPY.js";import{a as Ne,b as fe,c as De,k as Pe}from"./chunk-FN64ZULV.js";import{D as ue,L as nt,b as j,c as Ce,p as it}from"./chunk-WG3C43QS.js";import{a as J,b as ee,d as _e,j as ae,l as ge,n as be,o as ke,r as rt}from"./chunk-6GYNUTPP.js";import{a as xe,b as te,c as we,e as ce,f as ve,g as de,k as Ee,m as Ae,o as K,q as le}from"./chunk-LMQPGVM7.js";import{c as Z,h as Ie}from"./chunk-EZLBMUQD.js";import{c as Se,e as ot}from"./chunk-5M6IGE5G.js";nt();st();it();import{createSdkMcpServer as Kt,tool as M}from"@anthropic-ai/claude-agent-sdk";import{z as d}from"zod";import{v4 as he}from"uuid";rt();Ie();le();var at=Z("audit");function I(t){try{K().prepare(`
|
|
2
|
-
INSERT INTO artifact_access_log (
|
|
3
|
-
timestamp, task_id, role_id, execution_id, step_id, tool, artifact_key, artifact_id,
|
|
4
|
-
size_bytes, outcome, error_reason
|
|
5
|
-
)
|
|
6
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
7
|
-
`).run(t.timestamp,t.taskId??null,t.roleId??null,t.executionId,t.stepId??null,t.tool,t.artifactKey??null,t.artifactId??null,t.sizeBytes??null,t.outcome,t.errorReason??null)}catch(e){at.error({err:e,entry:t},"Failed to write artifact access log")}}Ae();import{tool as q}from"@anthropic-ai/claude-agent-sdk";import{z as k}from"zod";import{v4 as ct}from"uuid";function B(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}var dt={query:k.string().describe("Search query for memory retrieval"),roleId:pe.optional().describe("Role ID to scope search (omit for cross-role)"),topK:k.number().optional().describe("Max results to return (default 5)")},lt={query:k.string().describe("Search query for memory retrieval"),topK:k.number().optional().describe("Max results to return (default 5)")},ut={id:k.string().optional().describe("Memory ID to update. Omit to create new."),roleId:pe.describe("Role ID to save memory under"),content:k.string().describe("Memory content text"),type:k.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:k.array(k.string()).optional().describe("Keywords for BM25 search"),importance:k.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:k.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},pt={id:k.string().optional().describe("Memory ID to update. Omit to create new."),content:k.string().describe("Memory content text"),type:k.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:k.array(k.string()).optional().describe("Keywords for BM25 search"),importance:k.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:k.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},ze={id:k.string().describe("Memory ID to delete")};async function Fe(t,e){let r=t??e.roleId,n=e.topK??5,a=await $e(r,e.query,{topK:n});return B({results:a.map(c=>({id:c.id,type:c.type,content:c.content,keywords:c.keywords,importance:c.importance,score:c.score}))})}async function Ke(t,e){let r=t??e.roleId;if(!r)return B({error:"roleId is required"});let n,a=!0;try{n=await Me(e.content)}catch{a=!1}if(e.id){let y=fe(e.id);if(!y)return B({error:`Memory ${e.id} not found`});let A=De(e.id,{content:e.content,embedding:n,keywords:e.keywords,importance:e.importance,type:e.type});return D({toolName:"save_memory",entityType:"memory",verb:"update",entityId:e.id,fieldChanges:[{path:"content",op:"set",before:y.content,after:e.content}],roleId:r}),B({id:e.id,action:"updated",success:A,embeddingUpdated:a})}let c=`mem-${ct().slice(0,8)}`,m=Date.now();return Ne({id:c,roleId:r,type:e.type??"thought",content:e.content,embedding:n,keywords:e.keywords??[],importance:e.importance??3,sourceType:"manual",createdAt:m,lastAccessed:m,retrievedCount:0,tier:e.tier??"episodic"}),D({toolName:"save_memory",entityType:"memory",verb:"create",entityId:c,fieldChanges:[{path:"_entity",op:"set",before:null,after:{id:c,roleId:r,type:e.type??"thought",content:e.content.length>200?`${e.content.slice(0,200)}\u2026`:e.content,tier:e.tier??"episodic"}}],roleId:r}),B({id:c,action:"created",success:!0,embeddingUpdated:a})}async function Le(t,e){let r=fe(e.id);if(t){if(!r)return B({error:`Memory ${e.id} not found`});if(r.roleId!==t)return B({error:`Memory ${e.id} does not belong to this role`})}return Pe(e.id),D({toolName:"delete_memory",entityType:"memory",verb:"delete",entityId:e.id,fieldChanges:[{path:"_entity",op:"set",before:r?{id:r.id,roleId:r.roleId,content:r.content.length>200?`${r.content.slice(0,200)}\u2026`:r.content}:null,after:null}],roleId:t??r?.roleId}),B({id:e.id,deleted:!0})}function je(t){return t?[q("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",lt,async e=>Fe(t,e)),q("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",pt,async e=>Ke(t,e)),q("delete_memory","Delete a memory by ID.",ze,async e=>Le(t,e))]:[q("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",dt,async e=>Fe(void 0,e)),q("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",ut,async e=>Ke(void 0,e)),q("delete_memory","Delete a memory by ID.",ze,async e=>Le(void 0,e))]}Ae();import{basename as Y,extname as jt,join as qt}from"path";import{writeFileSync as Ht}from"fs";Ie();le();import{v4 as mt}from"uuid";function qe(t){let e=[];if(t.verb||e.push("verb is required"),t.entityType||e.push("entityType is required"),!t.expected)return e.push("expected is required"),{valid:!1,errors:e};let r=t.expected;if(r.kind==="outbound")r.target?.channelId||e.push("expected.target.channelId is required for outbound"),r.attachmentCount!==void 0&&(typeof r.attachmentCount!="number"||r.attachmentCount<0)&&e.push("expected.attachmentCount must be a non-negative number");else if(r.kind==="field_change")r.entityId||e.push("expected.entityId is required for field_change"),r.fieldPath||e.push("expected.fieldPath is required for field_change"),r.op!=="set"&&r.op!=="list_add"&&r.op!=="list_remove"&&e.push("expected.op must be 'set', 'list_add', or 'list_remove'"),r.op==="set"&&(r.after===void 0&&e.push("expected.after is required when op='set'"),(r.added!==void 0||r.removed!==void 0)&&e.push("expected.added/removed must be absent when op='set'")),r.op==="list_add"&&((!Array.isArray(r.added)||r.added.length===0)&&e.push("expected.added (non-empty array) is required when op='list_add'"),(r.after!==void 0||r.removed!==void 0)&&e.push("expected.after/removed must be absent when op='list_add'")),r.op==="list_remove"&&((!Array.isArray(r.removed)||r.removed.length===0)&&e.push("expected.removed (non-empty array) is required when op='list_remove'"),(r.after!==void 0||r.added!==void 0)&&e.push("expected.after/added must be absent when op='list_remove'"));else if(r.kind==="batch"){r.entityType||e.push("expected.entityType is required for batch");let n=Array.isArray(r.entityIds)&&r.entityIds.length>0,a=!!r.scope&&typeof r.scope.expectedCount=="number"&&r.scope.expectedCount>=0&&!!r.scope.filter;!n&&!a&&e.push("batch claims require entityIds (non-empty) or scope (with filter + non-negative expectedCount)")}else e.push(`expected.kind must be 'outbound', 'field_change', or 'batch'; got '${r.kind}'`);return{valid:e.length===0,errors:e}}var H=class extends Error{constructor(r){super(`Invalid claim spec: ${r.join("; ")}`);this.errors=r;this.name="InvalidClaimError"}errors};function He(t){if(!t.traceId)throw new H(["traceId is required"]);if(!Array.isArray(t.claims)||t.claims.length===0)throw new H(["claims must be a non-empty array"]);for(let[r,n]of t.claims.entries()){let a=qe(n);if(!a.valid)throw new H([`claims[${r}]: ${a.errors.join("; ")}`])}let e={id:t.id??mt(),traceId:t.traceId,sessionId:t.sessionId,taskId:t.taskId,sourceMessageId:t.sourceMessageId,claims:t.claims,declaredAt:t.declaredAt??Date.now()};return K().prepare(`
|
|
8
|
-
INSERT INTO assistant_claims (
|
|
9
|
-
id, trace_id, session_id, task_id, source_message_id, claims_json, declared_at
|
|
10
|
-
)
|
|
11
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
12
|
-
`).run(e.id,e.traceId,e.sessionId??null,e.taskId??null,e.sourceMessageId??null,JSON.stringify(e.claims),e.declaredAt),e}function pr(t){return K().prepare(`
|
|
13
|
-
SELECT * FROM assistant_claims WHERE trace_id = ? ORDER BY declared_at ASC
|
|
14
|
-
`).all(t).map(ft)}function ft(t){return{id:t.id,traceId:t.trace_id,sessionId:t.session_id??void 0,taskId:t.task_id??void 0,sourceMessageId:t.source_message_id??void 0,claims:JSON.parse(t.claims_json),declaredAt:t.declared_at}}ot();import{execFile as Nt}from"child_process";import{promisify as Dt}from"util";import{isAbsolute as Pt,basename as Mt}from"path";import Ye from"vm";import{isAbsolute as ht}from"path";var P=class extends Error{constructor(e,r){super(`DSL parse error in "${e}": ${r}`),this.name="DslParseError"}},yt=/^[a-z][a-z0-9_.]*$/i,It=/\.\./;function V(t){if(!yt.test(t))throw new P(t,`invalid handler key format "${t}" \u2014 must match [a-z][a-z0-9_.]*`);if(It.test(t))throw new P(t,'handler key must not contain ".."')}function Ue(t){let e=t.trim();try{let n=JSON.parse(e);if(typeof n=="number"||typeof n=="string"||typeof n=="boolean")return n}catch{}let r=parseFloat(e);return Number.isNaN(r)?e:r}var _t=/^([a-z][a-z0-9_.]*)\s+matches\s+\/(.+)\/([gimsuy]*)$/i,gt=/^([a-z][a-z0-9_.]*)\s*(<=|>=|==|!=)\s*(.+)$/i,bt=/^([a-z][a-z0-9_.]*)\s*(<|>)\s*(.+)$/i,kt=/^([a-z][a-z0-9_.]*)\s+between\s+(-?\d+(?:\.\d+)?)\s+and\s+(-?\d+(?:\.\d+)?)$/i,xt=/^([a-z][a-z0-9_.]*)\s+in\s+\[([^\]]+)\]$/i;function We(t){if(typeof t=="object"&&t!==null&&"script"in t){let r=String(t.script);if(!ht(r))throw new P(`{script: "${r}"}`,"script path must be absolute");return{kind:"script",scriptPath:r}}if(typeof t!="string")throw new P(String(t),"assertion must be a string or {script: string} object");let e=t.trim();if(!e)throw new P(e,"empty assertion string");{let r=_t.exec(e);if(r){let n=r[1];return V(n),{kind:"matches",key:n,regexSource:r[2],regexFlags:r[3]??""}}}{let r=kt.exec(e);if(r){let n=r[1];return V(n),{kind:"between",key:n,min:parseFloat(r[2]),max:parseFloat(r[3])}}}{let r=xt.exec(e);if(r){let n=r[1];V(n);let a=r[2],c=[];for(let m of a.split(",")){let y=m.trim();if(y)try{let A=JSON.parse(y);typeof A=="number"||typeof A=="string"||typeof A=="boolean"?c.push(A):c.push(y)}catch{c.push(y)}}return{kind:"in",key:n,values:c}}}{let r=gt.exec(e);if(r){let n=r[1];return V(n),{kind:"comparison",key:n,op:r[2],value:Ue(r[3])}}}{let r=bt.exec(e);if(r){let n=r[1];return V(n),{kind:"comparison",key:n,op:r[2],value:Ue(r[3])}}}throw new P(e,"unrecognized assertion syntax \u2014 expected key <op> value, between, in [...], matches /.../, or {script: ...}")}import{execFile as vt,spawn as Et}from"child_process";import{promisify as At}from"util";import{readFile as X}from"fs/promises";import{existsSync as St}from"fs";import{createHash as Ct}from"crypto";function wt(t){return typeof t=="number"?Number.isInteger(t)?t.toString():t.toFixed(4):JSON.stringify(t)}var L=class extends Error{constructor(r){super(`NO_HANDLER: ${r}, install relevant capability or remove assertion`);this.handlerKey=r;this.name="NoHandlerError"}handlerKey},C=class extends Error{constructor(r,n,a){super(`ASSERTION_FAILED: ${r}=${wt(n)}, expected ${a}`);this.handlerKey=r;this.measured=n;this.expected=a;this.name="AssertionFailedError"}handlerKey;measured;expected},b=class extends Error{constructor(r,n){super(`HANDLER_RUNTIME_ERROR: ${r}: ${n}`);this.handlerKey=r;this.detail=n;this.name="HandlerRuntimeError"}handlerKey;detail};var Tt=At(vt);function z(t,e){if(!St(e))throw new b(t,`file not found: ${e}`)}async function Rt(t){try{return await Tt("ffprobe",t,{maxBuffer:10*1024*1024})}catch(e){throw e.code==="ENOENT"?new b("audio.*","ffprobe not found on PATH \u2014 install ffmpeg/ffprobe"):new b("audio.*",`ffprobe failed: ${e.message}`)}}async function Je(t,e){return new Promise((r,n)=>{let a=[],c=Et("ffmpeg",["-v","error","-i",t,"-f","s16le","-ar",String(e),"-ac","1","-"]);c.stdout.on("data",y=>a.push(y));let m="";c.stderr.on("data",y=>{m+=y.toString()}),c.on("error",y=>{y.code==="ENOENT"?n(new b("audio.*","ffmpeg not found on PATH \u2014 install ffmpeg/ffprobe")):n(new b("audio.*",`ffmpeg failed: ${y.message}`))}),c.on("close",y=>{y!==0?n(new b("audio.*",`ffmpeg exit ${y}: ${m.trim()}`)):r(Buffer.concat(a))})})}var Ve=new Map;async function Ot(t){let e=JSON.stringify(t);if(/"\$ref"\s*:\s*"https?:\/\//.test(e))throw new b("json.schema_valid","remote $ref not supported in schema");let r=Ct("sha256").update(e).digest("hex"),n=Ve.get(r);if(n)return n;let a=(await import("ajv")).default,m=new a({strict:!1,allErrors:!1}).compile(t);return Ve.set(r,m),m}var Xe={"audio.duration_s":async t=>{z("audio.duration_s",t);let{stdout:e}=await Rt(["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",t]),r=parseFloat(e.trim());if(!Number.isFinite(r))throw new b("audio.duration_s",`ffprobe returned non-numeric duration: ${e.trim()}`);return r},"audio.zc_rate_per_s":async t=>{z("audio.zc_rate_per_s",t);let e=24e3,r=await Je(t,e),n=new Int16Array(r.buffer,r.byteOffset,r.byteLength/2),a=0;for(let m=1;m<n.length;m++)n[m-1]>=0!=n[m]>=0&&a++;let c=n.length/e;return c>0?a/c:0},"audio.rms":async t=>{z("audio.rms",t);let r=await Je(t,24e3),n=new Int16Array(r.buffer,r.byteOffset,r.byteLength/2),a=0;for(let c=0;c<n.length;c++){let m=n[c]/32768;a+=m*m}return n.length>0?Math.sqrt(a/n.length):0},"markdown.word_count":async t=>{z("markdown.word_count",t);let e=await X(t,"utf-8");return e.trim().length===0?0:e.trim().split(/\s+/).length},"image.width_px":async t=>{z("image.width_px",t);let{imageSize:e}=await import("image-size"),r=await X(t),n=e(r);if(typeof n.width!="number")throw new b("image.width_px","could not determine image width");return n.width},"image.height_px":async t=>{z("image.height_px",t);let{imageSize:e}=await import("image-size"),r=await X(t),n=e(r);if(typeof n.height!="number")throw new b("image.height_px","could not determine image height");return n.height},"pdf.page_count":async t=>{z("pdf.page_count",t);let{PDFDocument:e}=await import("pdf-lib"),r=await X(t);return(await e.load(r,{ignoreEncryption:!0})).getPageCount()},"json.schema_valid":async(t,e)=>{if(z("json.schema_valid",t),!e||typeof e!="object"||!("schema"in e))throw new b("json.schema_valid","missing schema arg");let r=await Ot(e.schema),n=await X(t,"utf-8"),a;try{a=JSON.parse(n)}catch(c){throw new b("json.schema_valid",`file is not valid JSON: ${c.message}`)}return r(a)===!0}};var $t=Dt(Nt);async function Ge(t,e,r={}){let n=r.handlerRegistry??Xe;for(let a=0;a<e.length;a++){let c=e[a],m=We(c);if(m.kind==="script"){await zt(m.scriptPath,t);continue}let y=n[m.key];if(!y)throw new L(m.key);let A=r.handlerArgsByIndex?.[a],i=await y(t,A);Bt(m,i)}}function Bt(t,e){switch(t.kind){case"comparison":{let{key:r,op:n,value:a}=t,c=!1;if(n==="<"?c=e<a:n===">"?c=e>a:n==="<="?c=e<=a:n===">="?c=e>=a:n==="=="?c=e==a:n==="!="&&(c=e!=a),!c)throw new C(r,e,`${n} ${a}`);break}case"between":{let{key:r,min:n,max:a}=t;if(e<n||e>a)throw new C(r,e,`between ${n} and ${a}`);break}case"in":{let{key:r,values:n}=t;if(!n.includes(e))throw new C(r,e,`in [${n.join(", ")}]`);break}case"matches":{let{key:r,regexSource:n,regexFlags:a}=t;if(!Ft(String(e),n,a,100))throw new C(r,e,`matches /${n}/${a}`);break}}}async function zt(t,e){if(!Pt(t))throw new b("script",`script path must be absolute: ${t}`);try{await $t(t,[e],{timeout:6e4,maxBuffer:1024*1024})}catch(r){let n=r;if(n.code==="ENOENT")throw new b("script",`script not found: ${t}`);let a=n.exitCode;throw new C("script:"+Mt(t),a??"error",n.stderr?.trim()??n.message)}}function Ft(t,e,r,n){let a={value:t,regex:new RegExp(e,r),result:!1};Ye.createContext(a);try{return Ye.runInContext("result = regex.test(value)",a,{timeout:n}),a.result}catch(c){throw new b("matches",`regex evaluation timeout or error: ${c.message}`)}}le();var Lt="execution-tools",Br="mcp__execution-tools__",zr=["mcp__execution-tools__write_artifact","mcp__execution-tools__publish_artifact_file","mcp__execution-tools__send_to_channel","mcp__execution-tools__report_blocked","mcp__execution-tools__commit_claim","mcp__execution-tools__save_memory","mcp__execution-tools__delete_memory"],Fr=["mcp__execution-tools__list_channels","mcp__execution-tools__read_artifact","mcp__execution-tools__fetch_artifact_file","mcp__execution-tools__list_artifacts","mcp__execution-tools__search_memories"],Kr=["mcp__execution-tools__write_artifact","mcp__execution-tools__publish_artifact_file","mcp__execution-tools__send_to_channel","mcp__execution-tools__report_blocked","mcp__execution-tools__commit_claim","mcp__execution-tools__save_memory","mcp__execution-tools__delete_memory","mcp__execution-tools__list_channels","mcp__execution-tools__read_artifact","mcp__execution-tools__fetch_artifact_file","mcp__execution-tools__list_artifacts","mcp__execution-tools__search_memories"],U=Z("execution"),Ut=/^[\p{L}0-9._-]{1,256}$/u,Wt=/^[\p{L}0-9._-]{1,128}$/u,ne=256*1024,Qe=/^[a-z]+\/[a-z0-9.+-]+$/,Jt={".mp3":"audio/mpeg",".m4a":"audio/mp4",".aac":"audio/aac",".wav":"audio/wav",".ogg":"audio/ogg",".opus":"audio/opus",".flac":"audio/flac",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm",".pdf":"application/pdf",".zip":"application/zip",".json":"application/json",".txt":"text/plain",".md":"text/markdown",".html":"text/html",".csv":"text/csv"};function Ze(t){return Jt[jt(t).toLowerCase()]}async function Vt(t){let{listChannels:e}=await import("./channels-ZHCTFSDA.js"),r=e(),{listSessions:n}=await import("./session-manager-PU4GH3E4.js"),a=[...n("active"),...n("archived")],{getDefaultChatIdForChannel:c}=await import("./target-resolution-RLNUCT6M.js"),m=r.find(A=>A.name.toLowerCase().includes(t.toLowerCase()));if(!m)return null;let y=c(m,a)??"";return{channelId:m.id,chatId:y}}function l(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}function se(t){return Ut.test(t)?null:"Invalid artifact key. Use only letters, numbers, dot, underscore, or dash (1-256 chars)."}function ye(t){return Wt.test(t)?null:"Invalid stepId format. Use only letters, numbers, dot, underscore, or dash (1-128 chars)."}function et(t,e,r){return t!==e?t:Y(r)}function tt(t,e){let r=ie(t);if(!r)return null;let n=oe(r.templateId);return n?n.steps.find(m=>m.id===e)?.outputAs??null:null}var Xt=t=>{if(!t)return!1;let e=j(t);return!!(e?.parentId&&e.templateId&&e.stepId)};function po(t,e,r){let n=t?ue(t):void 0,a=r??(()=>{}),c=async()=>{if(!e)return{error:"artifact tools require a task context"};let i=j(e);if(!i)return{error:`task not found: ${e}`};let o=i.roleId??t;if(!o)return{error:"this template execution task has no role context"};let p=ue(o);return p?{taskId:e,roleId:o,roleWorkspacePath:Re(p.name)}:{error:`role not found: ${o}`}},m=async()=>{let i=await c();if("error"in i)return i;let o=j(i.taskId);return o.parentId?o.stepId?{executionId:o.parentId,stepId:o.stepId,roleId:i.roleId,roleWorkspacePath:i.roleWorkspacePath,taskId:i.taskId}:{error:"this task is not a TemplateExecution step (no step_id)"}:{error:"this task is not a TemplateExecution step (no execution context)"}},y=[...je(t),M("list_channels","List all available channels. Use this to discover what channels can be used with send_to_channel.",{},async()=>{let{listChannels:i}=await import("./channels-ZHCTFSDA.js"),o=i();return l({channels:o.map(p=>({id:p.id,name:p.name,enabled:p.enabled,type:p.config?.type??"unknown"}))})}),M("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:d.string().describe("The channel name, e.g., 'WeChat on iPad' or 'Client Mail'"),message:d.string().describe("The message content to send")},async i=>{if(n?.allowedChannels!==void 0){if(n.allowedChannels.length===0)return l({error:"This role is not allowed to send to any channels"});if(!n.allowedChannels.some(u=>u.toLowerCase()===i.channelName.toLowerCase()))return l({error:`Channel "${i.channelName}" is not in the allowed channels list for this role`})}let o=await Vt(i.channelName);if(!o)return l({error:`Channel "${i.channelName}" not found or has no chatId available`});let{getOutboundGateway:p}=await import("./outbound-gateway-LKRQYPA2.js"),s=await p().send({channelId:o.channelId,chatId:o.chatId,content:i.message,messageType:"reply"});return l({success:s.success,channelName:i.channelName})}),M("write_artifact","Persist a small structured value (JSON <= 256KB) for downstream TemplateExecution 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:d.string().describe("Artifact key \u2014 a unique identifier for this value within the template execution."),value:d.unknown().describe("The JSON value to persist (must be <= 256KB serialized)."),priority:d.number().int().min(0).max(1e3).optional().describe("Lower = higher priority for delivery packing. Use 10 for primary deliverables (audio/video), 50 for text/markdown, 100 for images. Omit to use server-side heuristic.")},async i=>{let o=await m();if("error"in o)return l({error:o.error});if(i.priority!==void 0&&(i.priority<0||i.priority>1e3||!Number.isInteger(i.priority)))return l({error:`Invalid priority: ${i.priority}. Must be an integer between 0 and 1000.`});let p=se(i.key);if(p)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:i.key,outcome:"denied",errorReason:p}),l({error:p});let x=tt(o.executionId,o.stepId),s=ie(o.executionId),h=s?oe(s.templateId):null,u=h?h.steps.some(_=>_.id===o.stepId):!1,w=i.key,$,G=h!=null&&h.steps.some(_=>!!_.outputAs);if(x===null&&u&&G){let _=`Step "${o.stepId}" in template "${s.templateId}" has no outputAs declared. This template must be migrated before its steps can publish artifacts. Operator action required: run \`pnpm tsx scripts/migrate-all-templates-outputAs.ts --apply\` from the project root, or have the operator ask ChatManager in chat to upgrade the template.`;return U.warn({taskId:o.taskId,stepId:o.stepId,templateId:s.templateId},"write_artifact: step has no outputAs in migrated template"),I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:i.key,outcome:"denied",errorReason:_}),l({error:_})}x&&i.key!==x&&(w=x,$=`key '${i.key}' replaced with step.outputAs '${x}'`,U.warn({taskId:o.taskId,llmKey:i.key,outputAs:x},"write_artifact: server key override"));let Q=h?.steps?.find(_=>_.id===o.stepId),T=Q?Be(Q,i.value):!1;try{let _=he(),v,S;if(T){let R=i.value;if(v=Buffer.byteLength(R,"utf8"),v>ne){let O=`Artifact text exceeds ${ne} bytes`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:i.key,sizeBytes:v,outcome:"denied",errorReason:O}),l({error:O})}S=qt(xe(o.executionId),`${_}.bin`),Ht(S,R,"utf8")}else{let R=JSON.stringify(i.value);if(v=Buffer.byteLength(R,"utf8"),v>ne){let O=`Artifact JSON exceeds ${ne} bytes`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:i.key,sizeBytes:v,outcome:"denied",errorReason:O}),l({error:O})}}return J({id:_,sourceKind:"template_step",executionId:o.executionId,stepId:o.stepId,key:w,...T?{kind:"file",blobPath:S,mime:"text/markdown",originalFilename:`${w}.md`}:{kind:"json",value:i.value},sizeBytes:v,createdAt:Date.now(),roleId:o.roleId,priority:i.priority}),D({toolName:"write_artifact",entityType:"artifact",verb:"create",entityId:_,fieldChanges:[{path:"_entity",op:"set",before:null,after:{artifactId:_,key:w,kind:T?"file":"json",taskId:o.taskId}}],taskId:o.taskId,roleId:o.roleId}),I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:w,artifactId:_,sizeBytes:v,outcome:"success"}),l({success:!0,artifactId:_,sizeBytes:v,...$?{note:$}:{}})}catch(_){let v=_ instanceof Error?_.message:String(_);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:i.key,outcome:"error",errorReason:v}),l({error:v})}}),M("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:re.describe("TemplateExecution step ID of the artifact's source step."),key:d.string().describe("Artifact key \u2014 a unique identifier for this value within the template execution.")},async i=>{let o=await m();if("error"in o)return l({error:o.error});let p=ye(i.stepId),x=se(i.key),s=p??x;if(s)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:i.key,outcome:"denied",errorReason:s}),l({error:s});let h=ee(o.executionId,i.stepId,i.key);if(!h){let u=`no artifact at ${i.stepId}/${i.key}`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:i.key,outcome:"error",errorReason:u}),l({error:u})}if(h.kind!=="json"){let u="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:i.key,artifactId:h.id,sizeBytes:h.sizeBytes,outcome:"denied",errorReason:u}),l({error:u})}return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:i.key,artifactId:h.id,sizeBytes:h.sizeBytes,outcome:"success"}),l({value:h.value,sizeBytes:h.sizeBytes})}),M("publish_artifact_file",'REQUIRED final action for any TemplateExecution step that produces a file deliverable. If your step declares outputAs and you finish work (writing audio/video/report/image to disk via Write, Edit, or Bash) WITHOUT calling this tool, the step is marked FAILED \u2014 downstream steps and delivery rules will not see your file, regardless of whether your work succeeded. "I wrote a file to my workspace" is NOT the same as "I published an artifact": the file must be registered through this call to count. Call this AFTER the file is fully written to disk, BEFORE ending your turn. The file is COPIED to template execution shared storage. USE for: generated audio, video, reports, images, large outputs. Do NOT use for small structured JSON values (<=256KB) \u2014 use write_artifact instead. sourcePath must be inside your role workspace (~/.adam/roles/<your-role>/...); if your file was written to an additionalDirectories location (InfoHub/PKOS/Code/etc.), Bash-copy it into the workspace first then publish from there. cleanup=true deletes the source after publish \u2014 only set when you no longer need the source file (the step becomes non-retryable through publish).',{key:d.string().describe("Artifact key \u2014 a unique identifier for this value within the template execution."),sourcePath:me.describe("Source file path in the Role workspace to publish as a TemplateExecution artifact."),mime:d.string().optional().describe("MIME type of the file (e.g., 'image/png', 'audio/mp3'). Auto-detected if omitted."),cleanup:d.boolean().optional().describe("If true, delete the source file after publishing. Only use when the source file is no longer needed."),priority:d.number().int().min(0).max(1e3).optional().describe("Lower = higher priority for delivery packing. Use 10 for primary deliverables (audio/video), 50 for text/markdown, 100 for images. Omit to use server-side heuristic."),role:d.string().optional().describe("Logical artifact role. REQUIRED when the step's outputContract declares expectedArtifacts \u2014 use one of the declared roles (e.g. 'podcast', 'song'). Publishing more than the declared count for a role, or an undeclared role, is rejected.")},async i=>{let o=await c();if("error"in o)return l({error:o.error});if(i.priority!==void 0&&(i.priority<0||i.priority>1e3||!Number.isInteger(i.priority)))return l({error:`Invalid priority: ${i.priority}. Must be an integer between 0 and 1000.`});let p=j(o.taskId);if(!!!(p.parentId&&p.templateId&&p.stepId)){if(i.mime&&!Qe.test(i.mime))return l({error:`Invalid MIME type: ${i.mime}`});try{te(i.sourcePath,o.roleWorkspacePath,!0)}catch(g){return l({error:g instanceof Error?g.message:String(g)})}let f=he(),E=null,N=!1;try{let g=Ee({kind:"task",artifactId:f,sourcePath:i.sourcePath});E=g.blobPath;let W={id:f,sourceKind:"task_published",taskId:o.taskId,roleId:o.roleId,kind:"file",blobPath:E,mime:i.mime??Ze(i.sourcePath),originalFilename:Y(i.sourcePath),sizeBytes:g.sizeBytes,createdAt:Date.now(),priority:i.priority};return J(W),N=!0,i.cleanup===!0&&ce(i.sourcePath),D({toolName:"publish_artifact_file",entityType:"artifact",verb:"create",entityId:f,fieldChanges:[{path:"_entity",op:"set",before:null,after:{artifactId:f,kind:"file",filename:Y(i.sourcePath),taskId:o.taskId,sourceKind:"task_published"}}],taskId:o.taskId,roleId:o.roleId}),U.info({taskId:o.taskId,roleId:o.roleId,artifactId:f,sizeBytes:g.sizeBytes},"publish_artifact_file task_published: success"),l({success:!0,artifactId:f,sizeBytes:g.sizeBytes})}catch(g){if(N)try{ae(f)}catch{}if(E)try{de(E)}catch{}let W=g instanceof Error?g.message:String(g);return U.warn({taskId:o.taskId,roleId:o.roleId,artifactId:f,err:g},"publish_artifact_file task_published: failed"),l({error:W})}}let s={executionId:p.parentId,stepId:p.stepId,roleId:o.roleId,roleWorkspacePath:o.roleWorkspacePath,taskId:o.taskId},h=se(i.key);if(h)return I({timestamp:Date.now(),taskId:s.taskId,roleId:s.roleId,executionId:s.executionId,stepId:s.stepId,tool:"publish_artifact_file",artifactKey:i.key,outcome:"denied",errorReason:h}),l({error:h});if(i.mime&&!Qe.test(i.mime)){let f=`Invalid MIME type: ${i.mime}`;return I({timestamp:Date.now(),taskId:s.taskId,roleId:s.roleId,executionId:s.executionId,stepId:s.stepId,tool:"publish_artifact_file",artifactKey:i.key,outcome:"denied",errorReason:f}),l({error:f})}let u=tt(s.executionId,s.stepId),w=ie(s.executionId),$=w?oe(w.templateId):null,G=$?$.steps.find(f=>f.id===s.stepId)??null:null,Q=G!=null,T=i.key,_,v=$!=null&&$.steps.some(f=>!!f.outputAs);if(u===null&&Q&&v){let f=`Step "${s.stepId}" in template "${w.templateId}" has no outputAs declared. This template must be migrated before its steps can publish artifacts. Operator action required: run \`pnpm tsx scripts/migrate-all-templates-outputAs.ts --apply\` from the project root, or have the operator ask ChatManager in chat to upgrade the template.`;return U.warn({taskId:s.taskId,stepId:s.stepId,templateId:w.templateId},"publish_artifact_file: step has no outputAs in migrated template"),I({timestamp:Date.now(),taskId:s.taskId,roleId:s.roleId,executionId:s.executionId,stepId:s.stepId,tool:"publish_artifact_file",artifactKey:i.key,outcome:"denied",errorReason:f}),l({error:f})}u&&i.key!==u&&(T=u,_=`key '${i.key}' replaced with step.outputAs '${u}'`,U.warn({taskId:s.taskId,llmKey:i.key,outputAs:u},"publish_artifact_file: server key override"));try{te(i.sourcePath,s.roleWorkspacePath,!0)}catch(f){let E=f instanceof Error?f.message:String(f);return I({timestamp:Date.now(),taskId:s.taskId,roleId:s.roleId,executionId:s.executionId,stepId:s.stepId,tool:"publish_artifact_file",artifactKey:T,outcome:"denied",errorReason:E}),l({error:E})}let S=he(),R=null,O=!1,F=null;try{let f=we({executionId:s.executionId,artifactId:S,sourcePath:i.sourcePath});R=f.blobPath;let E=G?.assertions??[];E.length>0&&await Ge(R,E);let N={id:S,sourceKind:"template_step",executionId:s.executionId,stepId:s.stepId,key:T,kind:"file",blobPath:R,mime:i.mime??Ze(i.sourcePath),originalFilename:Y(i.sourcePath),sizeBytes:f.sizeBytes,createdAt:Date.now(),roleId:s.roleId,priority:i.priority,...i.role!==void 0?{artifactRole:i.role}:{}};if(u&&v){let g=ee(s.executionId,s.stepId,u);if(!g)J(N),O=!0,F=N;else if(g.kind==="file")F=ke(s.executionId,s.stepId,u,g,{...N,key:et(i.key,u,i.sourcePath)}).childArtifact;else if(g.kind==="json"&&ge(g.value))F=be(s.executionId,s.stepId,u,{...N,key:et(i.key,u,i.sourcePath)}).childArtifact;else throw new Error(`Artifact key "${u}" already contains a non-collection JSON artifact`)}else J(N),O=!0,F=N;return i.cleanup===!0&&ce(i.sourcePath),D({toolName:"publish_artifact_file",entityType:"artifact",verb:"create",entityId:S,fieldChanges:[{path:"_entity",op:"set",before:null,after:{artifactId:S,key:F?.key??T,kind:"file",filename:Y(i.sourcePath),taskId:s.taskId}}],taskId:s.taskId,roleId:s.roleId}),I({timestamp:Date.now(),taskId:s.taskId,roleId:s.roleId,executionId:s.executionId,stepId:s.stepId,tool:"publish_artifact_file",artifactKey:F?.key??T,artifactId:S,sizeBytes:f.sizeBytes,outcome:"success"}),l({success:!0,artifactId:S,sizeBytes:f.sizeBytes,..._?{note:_}:{}})}catch(f){if(O)try{ae(S)}catch{}if(R&&(!F||O))try{de(R)}catch{}let E=f instanceof Error?f.message:String(f);if(I({timestamp:Date.now(),taskId:s.taskId,roleId:s.roleId,executionId:s.executionId,stepId:s.stepId,tool:"publish_artifact_file",artifactKey:T,artifactId:S,outcome:"error",errorReason:E}),f instanceof C||f instanceof L)try{let g=(K().prepare("SELECT COUNT(*) as n FROM step_logs WHERE task_id = ?").get(s.taskId)?.n??0)+1;Te({id:`step-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,taskId:s.taskId,index:g,type:"validator_error",content:f.message,toolName:"publish_artifact_file",timestamp:Date.now()})}catch{}return l({error:E})}}),M("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:re.describe("TemplateExecution step ID of the artifact's source step."),key:d.string().describe("Artifact key \u2014 a unique identifier for this value within the template execution."),destPath:me.describe("Destination path in the Role workspace where the file will be copied.")},async i=>{let o=await m();if("error"in o)return l({error:o.error});let p=ye(i.stepId),x=se(i.key),s=p??x;if(s)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:i.key,outcome:"denied",errorReason:s}),l({error:s});try{te(i.destPath,o.roleWorkspacePath,!1)}catch(u){let w=u instanceof Error?u.message:String(u);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:i.key,outcome:"denied",errorReason:w}),l({error:w})}let h=ee(o.executionId,i.stepId,i.key);if(!h){let u=`no artifact at ${i.stepId}/${i.key}`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:i.key,outcome:"error",errorReason:u}),l({error:u})}if(h.kind!=="file"||!h.blobPath){let u="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:i.key,artifactId:h.id,outcome:"denied",errorReason:u}),l({error:u})}try{let u=ve({blobPath:h.blobPath,destPath:i.destPath});return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:i.key,artifactId:h.id,sizeBytes:u.sizeBytes,outcome:"success"}),l({success:!0,sizeBytes:u.sizeBytes,mime:h.mime,destPath:i.destPath})}catch(u){let w=u instanceof Error?u.message:String(u);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:i.key,artifactId:h.id,outcome:"error",errorReason:w}),l({error:w})}}),M("list_artifacts","Discover artifacts published by upstream steps in this template execution. 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:re.optional().describe("Filter to a specific TemplateExecution step (omit to list all artifacts in the execution).")},async i=>{let o=await m();if("error"in o)return l({error:o.error});let p=i.stepId?ye(i.stepId):null;if(p)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"list_artifacts",outcome:"denied",errorReason:p}),l({error:p});let x=_e(o.executionId,i.stepId);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"list_artifacts",sizeBytes:x.length,outcome:"success"}),l({artifacts:x.map(s=>({id:s.id,stepId:s.stepId,key:s.key,kind:s.kind,sizeBytes:s.sizeBytes,mime:s.mime,createdAt:s.createdAt}))})}),M("report_blocked","Report that the task cannot proceed due to a missing prerequisite (e.g., missing credential, missing input, missing target). This sets the task status to 'blocked', stores the reason for the UI to display, and aborts the execution loop.",{reason:d.string().describe("Short reason, e.g. 'missing_credential', 'missing_target', 'missing_input'"),missingPrereqs:d.array(d.string()).optional().describe("Specific keys/IDs that are missing, e.g. ['MINIMAX_API_KEY']"),resumeHint:d.string().optional().describe("How the user can unblock, e.g. 'set MINIMAX_API_KEY in role env'")},async i=>{if(!e)return l({error:"report_blocked requires a task context (taskId not available)"});let o=j(e);if(!o)return l({error:`task not found: ${e}`});let p={reason:i.reason,missingPrereqs:i.missingPrereqs,resumeHint:i.resumeHint};return Ce(e,{status:"blocked",blockReason:p,completedAt:Date.now()}),Oe.emit({type:"task_status_change",taskId:e,oldStatus:o.status,newStatus:"blocked"}),D({toolName:"report_blocked",entityType:"task",verb:"update",entityId:e,fieldChanges:[{path:"status",op:"set",before:o.status,after:"blocked"},{path:"blockReason",op:"set",before:void 0,after:i.reason},{path:"completedAt",op:"set",before:void 0,after:Date.now()}],taskId:e,roleId:o.roleId}),a(),l({success:!0,blocked:!0,reason:i.reason})}),M("commit_claim","Declare structured claims about what this worker task just did so the audit engine can verify against effect receipts. Call this in the SAME task turn before reporting completion text. Mirror of the ChatManager tool \u2014 workers may also need to declare claims for actions taken inside template execution steps.",{claims:d.array(d.object({verb:d.string().min(1).describe("What was done: 'send', 'update', 'create', 'delete', 'cancel', 'enable', 'disable', 'bind', 'unbind', etc."),entityType:d.string().min(1).describe("What kind of thing was affected: 'channel_message', 'task_template', 'task', 'goal', 'role', 'delivery_rule', 'plugin', 'mcp_binding', 'config_field', etc."),expected:d.discriminatedUnion("kind",[d.object({kind:d.literal("outbound").describe("Used when verb='send' \u2014 declares a channel message was sent."),target:d.object({channelId:d.string().min(1).describe("Channel that received the message."),chatId:d.string().min(1).optional().describe("Specific chat within the channel; omit for any chat.")}).describe("Where the message went."),attachmentCount:d.number().int().min(0).optional().describe("How many attachments were sent. Verifier requires receipt.attachmentCount >= this."),textPresent:d.boolean().optional().describe("Whether the message body had non-empty text. Verifier requires receipt.textChars > 0 when true.")}),d.object({kind:d.literal("field_change").describe("Used for single-entity updates \u2014 declares a specific field on a specific entity changed."),entityId:d.string().min(1).describe("Identifier of the entity that was changed."),fieldPath:d.string().min(1).describe("Dotted path to the field that changed, e.g. 'deliverTo', 'cron', 'config.timeout'."),op:d.enum(["set","list_add","list_remove"]).describe("How the field changed: scalar set, list append, or list removal."),added:d.array(d.unknown()).min(1).optional().describe("Items appended when op='list_add'. Verifier accepts a superset (receipt may have appended more items)."),removed:d.array(d.unknown()).min(1).optional().describe("Items removed when op='list_remove'. Verifier accepts a superset."),after:d.unknown().optional().describe("New value when op='set'. Verifier requires deep-equal match.")}),d.object({kind:d.literal("batch").describe("Used for batch operations like cancel-many or delete-many."),entityType:d.string().min(1).describe("Restrict matching to this entity type."),entityIds:d.array(d.string()).min(1).optional().describe("Specific entity IDs affected. Verifier checks receipt.entityIds is a superset."),scope:d.object({filter:d.string().min(1).describe("Free-text description of the filter applied (e.g., 'status=running AND role_id=role-x'). Verifier ignores this; human-readable only."),expectedCount:d.number().int().min(0).describe("Minimum number of entities expected to have been affected. Verifier requires receipt.scope.matchedCount >= this.")}).optional().describe("Filter+count for scope-based batches when individual IDs aren't enumerated.")})]).describe("Structured expectation matched against effect_receipts. Pick the kind that fits the action."),note:d.string().optional().describe("Free-text human note kept in the audit log only. Verifier ignores this.")})).min(1).max(20).describe("One or more claims declaring exactly what just happened. Each claim is verified independently against receipts.")},async i=>{let o=Se();if(!o)return l({error:"commit_claim requires an active trace context"});try{let p=He({traceId:o,taskId:e,claims:i.claims});return l({claimRowId:p.id,claimsCount:p.claims.length,declaredAt:p.declaredAt})}catch(p){let x=p instanceof Error?p.message:String(p);return l({error:x})}})],A=Xt(e)?y.filter(i=>i.name!=="list_channels"&&i.name!=="send_to_channel"):y;return Kt({name:Lt,version:"1.0.0",tools:A})}export{je as a,He as b,pr as c,Xe as d,Lt as e,Br as f,zr as g,Fr as h,Kr as i,Ut as j,Ze as k,po as l};
|