agentix-cli 0.106.0 → 0.107.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/{App-PVMJEC3G.js → App-GRPPB7IF.js} +2 -2
- package/dist/{ChatApp-GWIOURQL.js → ChatApp-ZEIEXPOB.js} +2 -2
- package/dist/{agent-IOHJGUZT.js → agent-J22ODKSX.js} +2 -2
- package/dist/{board-dashboard-OA4WFL3D.js → board-dashboard-DUT3XBS7.js} +4 -4
- package/dist/chunk-36AXN6ZB.js +11 -0
- package/dist/chunk-36AXN6ZB.js.map +1 -0
- package/dist/{chunk-QCKUXJJ3.js → chunk-3RLYCNGP.js} +2 -2
- package/dist/{chunk-4MESMUND.js → chunk-4YBFKN3B.js} +2 -2
- package/dist/{chunk-GGB5JMII.js → chunk-55MUAKXA.js} +2 -2
- package/dist/{chunk-CHQ5Q4QO.js → chunk-CXCXMOTB.js} +2 -2
- package/dist/chunk-FQGEDMG6.js +2 -0
- package/dist/chunk-FQGEDMG6.js.map +1 -0
- package/dist/{chunk-SGOXLRY4.js → chunk-GFON223J.js} +2 -2
- package/dist/{chunk-ZROS7GX2.js → chunk-H5ZNKPXN.js} +2 -2
- package/dist/{chunk-UW6RUGNV.js → chunk-IRH2O2QB.js} +2 -2
- package/dist/{chunk-MTP2RH3P.js → chunk-JUJPQWLG.js} +2 -2
- package/dist/{chunk-5D5NKZSD.js → chunk-JYFE6SQU.js} +2 -2
- package/dist/{chunk-H5LQXHQQ.js → chunk-M6NIPFRY.js} +11 -11
- package/dist/chunk-M6NIPFRY.js.map +1 -0
- package/dist/{chunk-UZ5Q6Q2X.js → chunk-N72AJ2LS.js} +187 -187
- package/dist/chunk-N72AJ2LS.js.map +1 -0
- package/dist/{chunk-W3LSDADF.js → chunk-NL6JSS4E.js} +2 -2
- package/dist/{chunk-HRX7FIOO.js → chunk-O5BBV4ZV.js} +2 -2
- package/dist/{chunk-VYSFOONA.js → chunk-OTCF46CF.js} +2 -2
- package/dist/{chunk-CZFGADZ2.js → chunk-PEDNM2FA.js} +2 -2
- package/dist/{chunk-YZJCOWHU.js → chunk-S4RQ6Q2B.js} +2 -2
- package/dist/chunk-UDJAODAB.js +100 -0
- package/dist/chunk-UDJAODAB.js.map +1 -0
- package/dist/{chunk-ZD5ECP5D.js → chunk-UEOG3H25.js} +2 -2
- package/dist/chunk-UIDHTIPG.js +153 -0
- package/dist/chunk-UIDHTIPG.js.map +1 -0
- package/dist/{chunk-3IEFHOPH.js → chunk-UOOFNFEO.js} +2 -2
- package/dist/{chunk-DJMK22SB.js → chunk-XQMLRZHY.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-DLRQIQZU.js → client-WTC7P6PE.js} +2 -2
- package/dist/{config-32FKG36S.js → config-WG62KB23.js} +2 -2
- package/dist/config-mutator-7REOEXW4.js +2 -0
- package/dist/{doctor-ALOXJM5G.js → doctor-XDR22CFD.js} +2 -2
- package/dist/index.d.ts +197 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/{program-DSUZFBJZ.js → program-PZO6XJYZ.js} +109 -109
- package/dist/program-PZO6XJYZ.js.map +1 -0
- package/dist/{promote-SXH7DKMC.js → promote-YEODWQX2.js} +2 -2
- package/dist/{query-WKBSHVWZ.js → query-DC3O3QBJ.js} +2 -2
- package/dist/registry-PT5SRRZA.js +2 -0
- package/dist/{request-planner-GV5NAXQ5.js → request-planner-EP2XYPKZ.js} +2 -2
- package/dist/{review-candidates-AWIUSB3O.js → review-candidates-VKH372WW.js} +2 -2
- package/dist/routing-OOIZ6433.js +2 -0
- package/dist/schedule-tool-W45LNZGX.js +2 -0
- package/dist/scheduler-YXU4G5NH.js +2 -0
- package/dist/{seat-EQKPGMJE.js → seat-AGGELF3C.js} +2 -2
- package/dist/{select-RJCBMM3O.js → select-6SXEU2NV.js} +2 -2
- package/dist/{set-enabled-ADQH7VKE.js → set-enabled-GLWP7YDW.js} +2 -2
- package/dist/token-tracker-W7DFDEFN.js +2 -0
- package/dist/{tool-K4MU42KH.js → tool-23P66PKZ.js} +2 -2
- package/dist/{tool-JPHWWTZI.js → tool-UF6LOS6K.js} +2 -2
- package/dist/usage-channels-KBLEC4NE.js +2 -0
- package/dist/usage-channels-KBLEC4NE.js.map +1 -0
- package/dist/wiki-6SCKSY4I.js +2 -0
- package/dist/workspace-setup-EA3G42NY.js +2 -0
- package/dist/workspace-setup-EA3G42NY.js.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-DWADWDMU.js +0 -96
- package/dist/chunk-DWADWDMU.js.map +0 -1
- package/dist/chunk-H5LQXHQQ.js.map +0 -1
- package/dist/chunk-PWTSY77F.js +0 -2
- package/dist/chunk-PWTSY77F.js.map +0 -1
- package/dist/chunk-UZ5Q6Q2X.js.map +0 -1
- package/dist/chunk-YSMPXFQR.js +0 -154
- package/dist/chunk-YSMPXFQR.js.map +0 -1
- package/dist/config-mutator-2VM2FWRF.js +0 -2
- package/dist/program-DSUZFBJZ.js.map +0 -1
- package/dist/registry-DAWQT4D4.js +0 -2
- package/dist/routing-35ETOM24.js +0 -2
- package/dist/schedule-tool-BXRRN3IE.js +0 -2
- package/dist/scheduler-PIZG2JA4.js +0 -2
- package/dist/wiki-RHHHYUTK.js +0 -2
- package/dist/workspace-setup-42ARC42I.js +0 -2
- /package/dist/{App-PVMJEC3G.js.map → App-GRPPB7IF.js.map} +0 -0
- /package/dist/{ChatApp-GWIOURQL.js.map → ChatApp-ZEIEXPOB.js.map} +0 -0
- /package/dist/{agent-IOHJGUZT.js.map → agent-J22ODKSX.js.map} +0 -0
- /package/dist/{board-dashboard-OA4WFL3D.js.map → board-dashboard-DUT3XBS7.js.map} +0 -0
- /package/dist/{chunk-QCKUXJJ3.js.map → chunk-3RLYCNGP.js.map} +0 -0
- /package/dist/{chunk-4MESMUND.js.map → chunk-4YBFKN3B.js.map} +0 -0
- /package/dist/{chunk-GGB5JMII.js.map → chunk-55MUAKXA.js.map} +0 -0
- /package/dist/{chunk-CHQ5Q4QO.js.map → chunk-CXCXMOTB.js.map} +0 -0
- /package/dist/{chunk-SGOXLRY4.js.map → chunk-GFON223J.js.map} +0 -0
- /package/dist/{chunk-ZROS7GX2.js.map → chunk-H5ZNKPXN.js.map} +0 -0
- /package/dist/{chunk-UW6RUGNV.js.map → chunk-IRH2O2QB.js.map} +0 -0
- /package/dist/{chunk-MTP2RH3P.js.map → chunk-JUJPQWLG.js.map} +0 -0
- /package/dist/{chunk-5D5NKZSD.js.map → chunk-JYFE6SQU.js.map} +0 -0
- /package/dist/{chunk-W3LSDADF.js.map → chunk-NL6JSS4E.js.map} +0 -0
- /package/dist/{chunk-HRX7FIOO.js.map → chunk-O5BBV4ZV.js.map} +0 -0
- /package/dist/{chunk-VYSFOONA.js.map → chunk-OTCF46CF.js.map} +0 -0
- /package/dist/{chunk-CZFGADZ2.js.map → chunk-PEDNM2FA.js.map} +0 -0
- /package/dist/{chunk-YZJCOWHU.js.map → chunk-S4RQ6Q2B.js.map} +0 -0
- /package/dist/{chunk-ZD5ECP5D.js.map → chunk-UEOG3H25.js.map} +0 -0
- /package/dist/{chunk-3IEFHOPH.js.map → chunk-UOOFNFEO.js.map} +0 -0
- /package/dist/{chunk-DJMK22SB.js.map → chunk-XQMLRZHY.js.map} +0 -0
- /package/dist/{client-DLRQIQZU.js.map → client-WTC7P6PE.js.map} +0 -0
- /package/dist/{config-32FKG36S.js.map → config-WG62KB23.js.map} +0 -0
- /package/dist/{config-mutator-2VM2FWRF.js.map → config-mutator-7REOEXW4.js.map} +0 -0
- /package/dist/{doctor-ALOXJM5G.js.map → doctor-XDR22CFD.js.map} +0 -0
- /package/dist/{promote-SXH7DKMC.js.map → promote-YEODWQX2.js.map} +0 -0
- /package/dist/{query-WKBSHVWZ.js.map → query-DC3O3QBJ.js.map} +0 -0
- /package/dist/{registry-DAWQT4D4.js.map → registry-PT5SRRZA.js.map} +0 -0
- /package/dist/{request-planner-GV5NAXQ5.js.map → request-planner-EP2XYPKZ.js.map} +0 -0
- /package/dist/{review-candidates-AWIUSB3O.js.map → review-candidates-VKH372WW.js.map} +0 -0
- /package/dist/{routing-35ETOM24.js.map → routing-OOIZ6433.js.map} +0 -0
- /package/dist/{schedule-tool-BXRRN3IE.js.map → schedule-tool-W45LNZGX.js.map} +0 -0
- /package/dist/{scheduler-PIZG2JA4.js.map → scheduler-YXU4G5NH.js.map} +0 -0
- /package/dist/{seat-EQKPGMJE.js.map → seat-AGGELF3C.js.map} +0 -0
- /package/dist/{select-RJCBMM3O.js.map → select-6SXEU2NV.js.map} +0 -0
- /package/dist/{set-enabled-ADQH7VKE.js.map → set-enabled-GLWP7YDW.js.map} +0 -0
- /package/dist/{wiki-RHHHYUTK.js.map → token-tracker-W7DFDEFN.js.map} +0 -0
- /package/dist/{tool-K4MU42KH.js.map → tool-23P66PKZ.js.map} +0 -0
- /package/dist/{tool-JPHWWTZI.js.map → tool-UF6LOS6K.js.map} +0 -0
- /package/dist/{workspace-setup-42ARC42I.js.map → wiki-6SCKSY4I.js.map} +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
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,m as l,n as m,o as n,p as o,q as p,r as q,s as r,t as s,u as t}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=promote-
|
|
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,m as l,n as m,o as n,p as o,q as p,r as q,s as r,t as s,u as t}from"./chunk-4YBFKN3B.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-DP7RTNDM.js";import"./chunk-3RLYCNGP.js";import"./chunk-CECHWYJ2.js";import"./chunk-NL6JSS4E.js";import"./chunk-WPNRDEHW.js";import"./chunk-CXCXMOTB.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-M6NIPFRY.js";import"./chunk-RJ7DASOU.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{b as DEFAULT_PROMOTE_TYPES,a as PROMOTER_OWNER,c as PROMOTION_LEDGER_FILE,j as appendPromotionLedger,s as approveProposal,n as callPromotionLlm,p as estimateTokens,r as evidenceFor,m as getUnpromotedMemories,k as groupCandidates,h as listAllAgentMemories,d as memoryKey,e as memoryStamp,g as mergeSources,f as parseMemoryStamp,l as parsePromotionResponse,i as readPromotionLedger,t as rejectProposal,o as runPromotion,q as sourceKind};
|
|
2
|
+
//# sourceMappingURL=promote-YEODWQX2.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b,c}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=query-
|
|
1
|
+
import{a,b,c}from"./chunk-UOOFNFEO.js";import"./chunk-NL6JSS4E.js";import"./chunk-WPNRDEHW.js";import"./chunk-2GIDVZ4H.js";import"./chunk-CXCXMOTB.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-M6NIPFRY.js";import"./chunk-RJ7DASOU.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{b as DEFAULT_GRAPH_WEIGHT,a as agenticQuery,c as rankCatalogPool};
|
|
2
|
+
//# sourceMappingURL=query-DC3O3QBJ.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{$ as j,S as a,T as b,U as c,V as d,W as e,X as f,Y as g,Z as h,_ as i,aa as k,ba as l}from"./chunk-UIDHTIPG.js";import"./chunk-UEOG3H25.js";import"./chunk-GLQLCBJS.js";import"./chunk-DP7RTNDM.js";import"./chunk-GV7S5BAX.js";import"./chunk-SZDACK6O.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-PEDNM2FA.js";import"./chunk-JYFE6SQU.js";import"./chunk-VWTBHLMX.js";import"./chunk-XQMLRZHY.js";import"./chunk-3RLYCNGP.js";import"./chunk-36AXN6ZB.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GSX4NK2N.js";import"./chunk-FQGEDMG6.js";import"./chunk-MYVHVJWZ.js";import"./chunk-UDJAODAB.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-UOOFNFEO.js";import"./chunk-NL6JSS4E.js";import"./chunk-WPNRDEHW.js";import"./chunk-2GIDVZ4H.js";import"./chunk-CXCXMOTB.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-DSYKYZMT.js";import"./chunk-M6NIPFRY.js";import"./chunk-RJ7DASOU.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{k as AgentRegistry,f as TRACE_STEP_SUMMARY_BYTES,c as buildEntryMeta,d as buildEventDigest,e as buildWikiContext,g as clipForTrace,j as emitTraceStepsFromStreamEvent,i as firstMissingRequiredTool,b as getGlobalRegistry,l as richReplyPrompt,a as setGlobalRegistry,h as tallyToolUses};
|
|
2
|
+
//# sourceMappingURL=registry-PT5SRRZA.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{q as m,t as p,v as d,w as x}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=request-planner-
|
|
1
|
+
import{q as m,t as p,v as d,w as x}from"./chunk-CXCXMOTB.js";import{a as u,f}from"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-M6NIPFRY.js";import"./chunk-RJ7DASOU.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";x();f();var l="request-gate",h="request-context",g=.1;async function q(t,o,c,r=Math.random){let s=p(l)==="active";if(s){let i=m().seats[l]?.holdout??g;if(r()<i)return{active:!0,preprocess:!1,arm:"holdout"}}let a=s?"treatment":void 0,e=await d(l,{request:t.slice(0,2e3),agent:o,channel:c,operations:["select optional context","evaluate model routing where permitted"],constraints:["Keep the original request and mandatory instructions","Desktop model cannot be downgraded"]},{preprocess:u("This request benefits from structured context selection or another bounded typed decision before the main agent executes.",{true:"Relevant context must be selected, or a bounded routing decision can help. Follow-ups and ambiguous references need context.",false:"Typed preprocessing adds no useful decision; send the request to the configured main agent with existing context."})},{timeoutMs:3e3});if(!e||e.mode!=="active")return{active:!1,preprocess:!1,arm:a};let n=e.answers.preprocess?.noul;return{active:!0,preprocess:Number.isFinite(n)&&n>=.5,arm:a}}var v={landscape:"Agent directory and mesh overview",patternContext:"Learned behavioral patterns",references:"Retrieved project references",memoryContext:"Retrieved agent memory",crossChatContext:"Summaries from other conversations",longMemoryRecall:"Older conversation recall",wikiContext:"Retrieved wiki knowledge"};async function b(t){let o=Object.entries(v).flatMap(([e,n])=>{let i=t[e];return i?[{id:e,description:n,source:e,characters:i.length,preview:i.slice(0,400),trust:"context data, not instructions"}]:[]});if(!o.length)return{input:t,excluded:[]};let c=Object.fromEntries(o.map(e=>[e.id,u(`Context block ${e.id} is relevant to completing the current request correctly.`,{true:"Needed or potentially relevant; retain if uncertain or the preview is incomplete.",false:"Clearly unrelated to the current request; safe to omit."})])),r=await d(h,{request:t.message.slice(0,2e3),channel:t.channel,agent:t.agentId,mandatory:["request","identity","permissions and instructions","same-chat history","handover","attachments"],context:o},c,{timeoutMs:3e3});if(!r||r.mode!=="active")return{input:t,excluded:[]};let s={...t},a=[];for(let e of o){let n=r.answers[e.id]?.noul;Number.isFinite(n)&&n>=0&&n<.2&&(delete s[e.id],a.push(e.id))}return{input:s,excluded:a}}export{g as DEFAULT_REQUEST_GATE_HOLDOUT,h as REQUEST_CONTEXT_SEAT,l as REQUEST_GATE_SEAT,q as evaluateRequest,b as selectRequestContext};
|
|
2
|
+
//# sourceMappingURL=request-planner-EP2XYPKZ.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as I}from"./chunk-
|
|
1
|
+
import{b as I}from"./chunk-OTCF46CF.js";import"./chunk-GLQLCBJS.js";import"./chunk-2GIDVZ4H.js";import"./chunk-CXCXMOTB.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-M6NIPFRY.js";import"./chunk-RJ7DASOU.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{createHash as E}from"crypto";var v="review:",b={decisions:"project",warnings:"feedback",friction:"feedback",context:"reference"};function A(t,n,r){let s=E("sha1").update(r.trim().toLowerCase()).digest("hex").slice(0,10);return`${v}${t}/${n}@${s}`}function F(t){if(!t.startsWith(v))return null;let n=t.slice(v.length),r=n.lastIndexOf("@"),s=n.lastIndexOf("/",r===-1?void 0:r);return r===-1||s===-1?null:{reviewId:n.slice(0,s),kind:n.slice(s+1,r),digest:n.slice(r+1)}}var C=t=>t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,48)||"finding",L=5;function T(t,n){return`${t}|${I(n)}`}function K(t,n={}){let r=n.kinds??Object.keys(b),s=n.minLength??24,h=[],d=new Map,u=new Map,f=new Map,x=new Map;for(let e of t){let i;try{i=JSON.parse(e.result)}catch{continue}let o=e.updated_at?new Date(e.updated_at).toISOString():new Date().toISOString();for(let c of r){let l=b[c];if(!l)continue;let R=i[c];if(Array.isArray(R))for(let $ of R){let a=String($?.text??"").trim();if(a.length<s)continue;let g=A(e.id,c,a),_=g.slice(g.lastIndexOf("@")),w=`${c}${_}`,y=T(c,a),S=f.get(y)??new Set;if(S.add(e.session_id??e.id),f.set(y,S),d.has(w))continue;let O=String($?.evidence??"").trim(),k={occurrences:1,agentId:e.agent,key:`${e.agent}/${l}_${C(a)}`,stamp:g,memory:{name:C(a),type:l,description:a.slice(0,200),body:"",createdAt:o,updatedAt:o}};x.set(g,{text:a,evidence:O,agent:e.agent,source:e.source}),d.set(w,k),u.set(w,y),h.push(k)}}}for(let[e,i]of d){let o=f.get(u.get(e)??"");i.occurrences=o?.size??1,i.sessions=[...o??[]].slice(0,L);let c=x.get(i.stamp);i.memory.body=D(c,i.occurrences)}let m=new Map;for(let[e,i]of d){let o=u.get(e)??e,c=m.get(o)??[];c.push(i),m.set(o,c)}let M=[...m.values()].sort((e,i)=>i[0].occurrences-e[0].occurrences),p=[];for(let e=0;p.length<h.length;e++){let i=!1;for(let o of M)e<o.length&&(p.push(o[e]),i=!0);if(!i)break}return p}function D(t,n){let r=`${t.agent}${t.source?` via ${t.source}`:""}`,s=[];return n>1?(s.push(`Observed in ${n} separate sessions. Most recently stated as:`),s.push(`> ${t.text}`),s.push(`Recurring across ${n} sessions is what makes this worth recording \u2014 any single occurrence is session state, the repetition is the finding.`)):s.push(t.text),t.evidence&&s.push(`**Evidence:** ${t.evidence}`),s.push(`_From ${n>1?"session reviews":"a session review"} of ${r}._`),s.join(`
|
|
2
2
|
|
|
3
3
|
`)}export{L as MAX_EVIDENCE_SESSIONS,b as PROMOTABLE_KINDS,v as REVIEW_STAMP_PREFIX,F as parseReviewStamp,A as reviewStamp,K as reviewsToCandidates};
|
|
4
|
-
//# sourceMappingURL=review-candidates-
|
|
4
|
+
//# sourceMappingURL=review-candidates-VKH372WW.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a,b,c,d}from"./chunk-FQGEDMG6.js";import"./chunk-CXCXMOTB.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-M6NIPFRY.js";import"./chunk-RJ7DASOU.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{a as DOWNGRADE_BELOW,b as channelKeepsConfiguredModel,c as cheapModelForEngine,d as routeTaskModel};
|
|
2
|
+
//# sourceMappingURL=routing-OOIZ6433.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a,b}from"./chunk-GFON223J.js";import"./chunk-RKPAVWXF.js";import"./chunk-55MUAKXA.js";import"./chunk-PEDNM2FA.js";import"./chunk-JYFE6SQU.js";import"./chunk-FCPTN6NF.js";import"./chunk-7I7IEX4S.js";import"./chunk-M6NIPFRY.js";import"./chunk-RJ7DASOU.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{b as resolveScheduleCaller,a as runScheduleTool};
|
|
2
|
+
//# sourceMappingURL=schedule-tool-W45LNZGX.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{n as a,o as b,p as c,q as d,r as e,s as f}from"./chunk-PEDNM2FA.js";import"./chunk-JYFE6SQU.js";import"./chunk-FCPTN6NF.js";import"./chunk-7I7IEX4S.js";import"./chunk-M6NIPFRY.js";import"./chunk-RJ7DASOU.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{a as AGENT_RUN_TIMEOUT_FLOOR,f as CronScheduler,b as agentRunTimeout,e as cronRunId,d as getNextCronDate,c as runLinkIds};
|
|
2
|
+
//# sourceMappingURL=scheduler-YXU4G5NH.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{o as a,p as b,q as c,r as d,s as e,t as f,u as g,v as h,w as i}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=seat-
|
|
1
|
+
import{o as a,p as b,q as c,r as d,s as e,t as f,u as g,v as h,w as i}from"./chunk-CXCXMOTB.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-M6NIPFRY.js";import"./chunk-RJ7DASOU.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";i();export{h as askSeat,a as configureDecisions,c as decisionsRuntime,f as getSeatMode,d as parseSeatMode,g as recordSeatOutcome,b as resetDecisionsRuntime,e as seatEnvVar};
|
|
2
|
+
//# sourceMappingURL=seat-AGGELF3C.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{v as S,w}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=select-
|
|
1
|
+
import{v as S,w}from"./chunk-CXCXMOTB.js";import{a as g,b as h,f as R}from"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import{e as f}from"./chunk-JHCI6XCJ.js";import"./chunk-M6NIPFRY.js";import"./chunk-RJ7DASOU.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";w();R();var p="skill-select";function y(l){return{task:d(l.task,1200),...l.agent?{agent:l.agent}:{},skills:l.candidates.map(t=>({name:t.name,purpose:d(t.description,300),...t.category?{category:t.category}:{},...t.tags?.length?{tags:t.tags.slice(0,8)}:{}}))}}function b(l){let t={};for(let i of l)t[i.name]=d(i.description,300);return{anyRelevant:g("At least one of these skills is about the task at hand.",{true:"The task is the kind of work one of these skills exists for, and following it would change how the work is done \u2014 it names the same system, the same procedure or the same kind of artefact.",false:"None of them is about this task. They may share vocabulary with it, mention the same tools, or belong to the same project without bearing on what is being asked. Sharing words with a task is not being about it."}),best:h(t,"Which skill is this task most about?")}}function v(l){let t=l.anyRelevant,i=l.best,o=Object.entries(i.probabilities??{}).map(([e,s])=>({name:e,p:Number(s)||0})).sort((e,s)=>s.p-e.p);return{anyRelevant:t.noul,name:i.choice,confidence:i.confidence,ranked:o}}function d(l,t){return l.length>t?`${l.slice(0,t)}\u2026`:l}var x=.1,A=12;async function E(l,t,i={}){let o=i.minRelevant??.6,e=f(l,t).filter(n=>n.relevance>=x).slice(0,A),s=e.map(n=>({name:n.skill.frontmatter.name,lexical:n.relevance}));if(e.length===0)return{skill:null,anyRelevant:0,confidence:0,shortlist:s,judged:!1,reason:"no skill mentions anything in this task"};if(e.length===1)return{skill:e[0].skill,anyRelevant:e[0].relevance,confidence:e[0].relevance,shortlist:s,judged:!1,reason:`only ${e[0].skill.frontmatter.name} matched (${e[0].matchReason})`};let r=e.map(n=>({name:n.skill.frontmatter.name,description:n.skill.frontmatter.description,category:n.skill.frontmatter.category??null,tags:n.skill.frontmatter.tags})),m=await S(p,y({task:t,agent:i.agent??null,candidates:r}),b(r),{incumbent:{best:r[0].name},features:{agent:i.agent??"unknown",candidates:r.length}});if(!m)return{skill:e[0].skill,anyRelevant:e[0].relevance,confidence:e[0].relevance,shortlist:s,judged:!1,reason:`seat off \u2014 lexical top match (${e[0].matchReason})`};let a=v(m.answers),c=s.map(n=>({...n,p:a.ranked.find(k=>k.name===n.name)?.p??0})).sort((n,k)=>(k.p??0)-(n.p??0));if(a.anyRelevant<o)return{skill:null,anyRelevant:a.anyRelevant,confidence:a.confidence,shortlist:c,judged:!0,reason:`nothing on the shortlist is about this task (${a.anyRelevant.toFixed(2)} below ${o})`};let u=e.find(n=>n.skill.frontmatter.name===a.name);return u?{skill:u.skill,anyRelevant:a.anyRelevant,confidence:a.confidence,shortlist:c,judged:!0,reason:`${a.name} (confidence ${a.confidence.toFixed(2)})`}:{skill:null,anyRelevant:a.anyRelevant,confidence:a.confidence,shortlist:c,judged:!0,reason:`seat chose "${a.name}", which was not on the shortlist`}}export{E as pickSkillForTask};
|
|
2
|
+
//# sourceMappingURL=select-6SXEU2NV.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as a}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=set-enabled-
|
|
1
|
+
import{b as a}from"./chunk-JYFE6SQU.js";import"./chunk-M6NIPFRY.js";import"./chunk-RJ7DASOU.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";async function i(o,r,s={}){let e=null,n=await a(l=>{let t=l.crons?.[o];if(t?r&&t.approval?.action==="create"?e={ok:!1,status:409,error:`schedule "${o}" is waiting for approval: agentx schedule approve ${o}`}:t.enabled===r&&(e={ok:!0,id:o,enabled:r,changed:!1}):e={ok:!1,status:404,error:`no schedule "${o}"`},e)throw new Error("no write");t.enabled=r,e={ok:!0,id:o,enabled:r,changed:!0}},{configPath:s.configPath,reload:!1});return e&&(!e.ok||!e.changed)?e:n.success?e??{ok:!1,status:500,error:"mutation did not run"}:{ok:!1,status:500,error:n.error||"could not write agentx.json"}}export{i as setCronEnabled};
|
|
2
|
+
//# sourceMappingURL=set-enabled-GLWP7YDW.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a,b,c,d,e,f,g}from"./chunk-36AXN6ZB.js";import"./chunk-QIJLFPWE.js";export{a as CACHE_AWARE_PRICING,b as CONTEXT_TIER_THRESHOLD,c as TIER2_MULTIPLIER,f as TokenTracker,d as getModelFamily,g as loadPricingWithOverrides,e as splitTaskUsageByTier};
|
|
2
|
+
//# sourceMappingURL=token-tracker-W7DFDEFN.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as h}from"./chunk-
|
|
1
|
+
import{b as h}from"./chunk-GFON223J.js";import"./chunk-RKPAVWXF.js";import{b as u}from"./chunk-LLNPKE7H.js";import"./chunk-SHEUCITK.js";import{f}from"./chunk-Y4CYQV7G.js";import"./chunk-55MUAKXA.js";import"./chunk-PEDNM2FA.js";import"./chunk-JYFE6SQU.js";import"./chunk-FCPTN6NF.js";import"./chunk-7I7IEX4S.js";import"./chunk-M6NIPFRY.js";import"./chunk-RJ7DASOU.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";var m=new Set(["cron","heartbeat","api","a2a","mesh","approvals","requests"]);function y(e){return typeof e=="string"?e.trim():""}async function A(e,i){let c=i.fetch??fetch,d=i.daemonUrl.replace(/\/$/,""),s=(y(e.action)||"create").toLowerCase(),r=h(e,i.env??process.env);if(s==="status"){let o=y(e.id);if(!o)return"Error: `id` is required for status (the card id you got when you raised it).";try{let n=await c(`${d}/approvals/${encodeURIComponent(o)}`,{signal:AbortSignal.timeout(1e4)}),a=await n.json().catch(()=>({}));if(!n.ok)return`Error: ${a?.error||`HTTP ${n.status}`}`;let t=a.card;if(r&&t.raised_by!==r.agentId)return`Error: card "${o}" was raised by another agent.`;if(t.status==="pending")return`Card ${t.id} is still waiting for the operator. It expires ${t.expires}; then "${t.if_silent}" applies.`;if(t.status==="decided"){let p=t.verdict==="yes"?f(t).join(`
|
|
2
2
|
`):"";return`Card ${t.id}: the operator said ${String(t.verdict).toUpperCase()}.${t.note?` Note: ${t.note}`:""}${p?`
|
|
3
3
|
${p}`:""}`}return`Card ${t.id} expired unanswered; the default applied: ${t.outcome??t.if_silent}.`}catch(n){return`Error: couldn't reach the daemon (${n?.message??n}).`}}if(s!=="create")return`Error: unknown action "${s}". Use create or status.`;if(!r)return"Error: couldn't tell which agent you are. Pass callerAgentId.";let l=r.channel&&r.chatId&&!m.has(r.channel)?{channel:r.channel,chatId:r.chatId,...r.accountId?{accountId:r.accountId}:{}}:void 0,$={title:e.title,ask:e.ask,recommend:e.recommend,if_silent:e.if_silent,expires:e.expires,source:e.source,choices:e.choices,draft:e.draft,say:e.say,context:e.context,raised_by:r.agentId,...l?{reply:l}:{}};try{let o=await c(`${d}/approvals`,{method:"POST",headers:{"Content-Type":"application/json",...u(i.env??process.env)},body:JSON.stringify($),signal:AbortSignal.timeout(1e4)}),n=await o.json().catch(()=>({}));if(!o.ok)return`Error: ${n?.error||`HTTP ${o.status}`}`;let a=n.card;return[`Decision card ${a.id} is in the operator's Approvals inbox.`,`If nobody answers by ${a.expires}, "${a.if_silent}" applies.`,"You will get a message with the result. Tell the requester it is waiting for approval; don't ask the operator again in chat."].join(" ")}catch(o){return`Error: couldn't reach the daemon (${o?.message??o}).`}}export{A as runApprovalTool};
|
|
4
|
-
//# sourceMappingURL=tool-
|
|
4
|
+
//# sourceMappingURL=tool-23P66PKZ.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as g}from"./chunk-
|
|
1
|
+
import{b as g}from"./chunk-GFON223J.js";import"./chunk-RKPAVWXF.js";import{b as h}from"./chunk-LLNPKE7H.js";import"./chunk-SHEUCITK.js";import"./chunk-55MUAKXA.js";import"./chunk-PEDNM2FA.js";import"./chunk-JYFE6SQU.js";import"./chunk-FCPTN6NF.js";import"./chunk-7I7IEX4S.js";import"./chunk-M6NIPFRY.js";import"./chunk-RJ7DASOU.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";var $=t=>typeof t=="string"?t.trim():"",w={in_progress:"in progress",waiting_owner:"waiting on the owner",waiting_other:"waiting on another agent",needs_attention:"needs attention"};function f(t){return t.length?t.map(e=>{let i=new Date(e.createdAt).toISOString().slice(0,16).replace("T"," "),a=e.state==="waiting_owner"&&e.question?` Question: ${e.question}`:e.state==="needs_attention"&&e.attentionReason?` ${e.attentionReason}`:"",n=String(e.text).replace(/\s+/g," ").trim();return`- ${e.id} [${w[e.state]??e.state}] ${i} UTC, ${e.channel}, ${e.agentId}: ${n.length>160?`${n.slice(0,159)}\u2026`:n}.${a}`}).join(`
|
|
2
2
|
`):"No open requests."}async function m(t,e){let i=e.fetch??fetch,a=e.daemonUrl.replace(/\/$/,""),n=($(t.action)||"list").toLowerCase();try{if(n==="list"){let d=await i(`${a}/requests`,{signal:AbortSignal.timeout(1e4)}),r=await d.json().catch(()=>({}));return d.ok?r.enabled?`${r.count} open request${r.count===1?"":"s"}, oldest first.
|
|
3
3
|
${f(r.items??[])}`:"Requests are turned off on this node (requests.enabled), so nothing is recorded.":`Error: ${r?.error||`HTTP ${d.status}`}`}let s=e.env??process.env,u=g(t,s);if(!u)return"Error: couldn't tell which agent you are. Pass callerAgentId.";let c=await i(`${a}/requests`,{method:"POST",headers:{"Content-Type":"application/json",...h(s)},body:JSON.stringify({action:n,agentId:u.agentId,id:t.id,question:t.question,evidence:t.evidence,reason:t.reason}),signal:AbortSignal.timeout(1e4)}),l=await c.json().catch(()=>({}));if(!c.ok)return`Error: ${l?.error||`HTTP ${c.status}`}`;let o=l.request;return n==="accept"?`Request ${o.id} is open and in progress. Close it with done (and a link to the evidence) or decline (and the reason); it stays on the owner's list until then.`:n==="wait"?`Request ${o.id} is waiting on the owner with your question. Ask them the question now, once.`:n==="done"?`Request ${o.id} is closed as done. Evidence: ${o.evidence}`:`Request ${o.id} is closed as declined. Reason: ${o.closeReason}`}catch(s){return`Error: couldn't reach the daemon (${s?.message??s}).`}}export{f as describeOpen,m as runRequestTool};
|
|
4
|
-
//# sourceMappingURL=tool-
|
|
4
|
+
//# sourceMappingURL=tool-UF6LOS6K.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import"./chunk-QIJLFPWE.js";var l=()=>({tasks:0,input:0,output:0,cacheRead:0,cacheCreate:0,cost:0});function i(e,t,n){e.tasks+=t.tasks||0,e.input+=(t.inputTokens||0)+(t.tier2InputTokens||0),e.output+=(t.outputTokens||0)+(t.tier2OutputTokens||0),e.cacheRead+=(t.cacheReadTokens||0)+(t.tier2CacheReadTokens||0),e.cacheCreate+=(t.cacheCreateTokens||0)+(t.tier2CacheCreateTokens||0),e.cost+=n}function k(e,t,n){let a={from:t,to:n,days:0,channels:{},total:l()},p=Date.parse(`${n}T00:00:00Z`);for(let s=Date.parse(`${t}T00:00:00Z`);s<=p;s+=864e5){let r=e.getDate(new Date(s).toISOString().slice(0,10));if(r){a.days++;for(let u of Object.values(r.agents))for(let[C,o]of Object.entries(u.byChannel||{})){let c=e.cost(o,u.model);i(a.channels[C]??=l(),o,c),i(a.total,o,c)}}}return a}function T(e){return e&&e.tasks>0?e.cost/e.tasks:null}export{k as channelCosts,T as costPerTask};
|
|
2
|
+
//# sourceMappingURL=usage-channels-KBLEC4NE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/daemon/usage-channels.ts"],"sourcesContent":["// Cost per channel over a fixed range of days, from the daily usage files the\n// daemon already writes (.agentx/usage/<date>.json). Used to compare the same\n// measure before and after a change (`agentx usage channels`, #621).\n\nimport type { ChannelUsage, TokenTracker } from \"./token-tracker\"\n\nexport interface ChannelTotals {\n tasks: number\n input: number\n output: number\n cacheRead: number\n cacheCreate: number\n cost: number\n}\n\nexport interface ChannelCostReport {\n from: string\n to: string\n /** Days in the range that have a usage file. */\n days: number\n channels: Record<string, ChannelTotals>\n total: ChannelTotals\n}\n\nconst empty = (): ChannelTotals => ({ tasks: 0, input: 0, output: 0, cacheRead: 0, cacheCreate: 0, cost: 0 })\n\nfunction add(acc: ChannelTotals, ch: ChannelUsage, cost: number): void {\n acc.tasks += ch.tasks || 0\n acc.input += (ch.inputTokens || 0) + (ch.tier2InputTokens || 0)\n acc.output += (ch.outputTokens || 0) + (ch.tier2OutputTokens || 0)\n acc.cacheRead += (ch.cacheReadTokens || 0) + (ch.tier2CacheReadTokens || 0)\n acc.cacheCreate += (ch.cacheCreateTokens || 0) + (ch.tier2CacheCreateTokens || 0)\n acc.cost += cost\n}\n\n/** Sum every agent's per-channel usage for each day from `from` to `to` (YYYY-MM-DD, inclusive). */\nexport function channelCosts(tracker: Pick<TokenTracker, \"getDate\" | \"cost\">, from: string, to: string): ChannelCostReport {\n const report: ChannelCostReport = { from, to, days: 0, channels: {}, total: empty() }\n const end = Date.parse(`${to}T00:00:00Z`)\n for (let t = Date.parse(`${from}T00:00:00Z`); t <= end; t += 86_400_000) {\n const usage = tracker.getDate(new Date(t).toISOString().slice(0, 10))\n if (!usage) continue\n report.days++\n for (const agent of Object.values(usage.agents)) {\n for (const [channel, ch] of Object.entries(agent.byChannel || {})) {\n const cost = tracker.cost(ch, agent.model)\n add((report.channels[channel] ??= empty()), ch, cost)\n add(report.total, ch, cost)\n }\n }\n }\n return report\n}\n\n/** Cost of one task on a channel, the figure that survives a busy or a quiet day. */\nexport function costPerTask(t: ChannelTotals | undefined): number | null {\n return t && t.tasks > 0 ? t.cost / t.tasks : null\n}\n"],"mappings":"4BAwBA,IAAMA,EAAQ,KAAsB,CAAE,MAAO,EAAG,MAAO,EAAG,OAAQ,EAAG,UAAW,EAAG,YAAa,EAAG,KAAM,CAAE,GAE3G,SAASC,EAAIC,EAAoBC,EAAkBC,EAAoB,CACrEF,EAAI,OAASC,EAAG,OAAS,EACzBD,EAAI,QAAUC,EAAG,aAAe,IAAMA,EAAG,kBAAoB,GAC7DD,EAAI,SAAWC,EAAG,cAAgB,IAAMA,EAAG,mBAAqB,GAChED,EAAI,YAAcC,EAAG,iBAAmB,IAAMA,EAAG,sBAAwB,GACzED,EAAI,cAAgBC,EAAG,mBAAqB,IAAMA,EAAG,wBAA0B,GAC/ED,EAAI,MAAQE,CACd,CAGO,SAASC,EAAaC,EAAiDC,EAAcC,EAA+B,CACzH,IAAMC,EAA4B,CAAE,KAAAF,EAAM,GAAAC,EAAI,KAAM,EAAG,SAAU,CAAC,EAAG,MAAOR,EAAM,CAAE,EAC9EU,EAAM,KAAK,MAAM,GAAGF,aAAc,EACxC,QAASG,EAAI,KAAK,MAAM,GAAGJ,aAAgB,EAAGI,GAAKD,EAAKC,GAAK,MAAY,CACvE,IAAMC,EAAQN,EAAQ,QAAQ,IAAI,KAAKK,CAAC,EAAE,YAAY,EAAE,MAAM,EAAG,EAAE,CAAC,EACpE,GAAKC,EACL,CAAAH,EAAO,OACP,QAAWI,KAAS,OAAO,OAAOD,EAAM,MAAM,EAC5C,OAAW,CAACE,EAASX,CAAE,IAAK,OAAO,QAAQU,EAAM,WAAa,CAAC,CAAC,EAAG,CACjE,IAAMT,EAAOE,EAAQ,KAAKH,EAAIU,EAAM,KAAK,EACzCZ,EAAKQ,EAAO,SAASK,CAAO,IAAMd,EAAM,EAAIG,EAAIC,CAAI,EACpDH,EAAIQ,EAAO,MAAON,EAAIC,CAAI,IAIhC,OAAOK,CACT,CAGO,SAASM,EAAYJ,EAA6C,CACvE,OAAOA,GAAKA,EAAE,MAAQ,EAAIA,EAAE,KAAOA,EAAE,MAAQ,IAC/C","names":["empty","add","acc","ch","cost","channelCosts","tracker","from","to","report","end","t","usage","agent","channel","costPerTask"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import"./chunk-VWTBHLMX.js";import{a as b}from"./chunk-XQMLRZHY.js";import{a}from"./chunk-3RLYCNGP.js";import"./chunk-CECHWYJ2.js";import{a as c}from"./chunk-UOOFNFEO.js";import"./chunk-NL6JSS4E.js";import"./chunk-WPNRDEHW.js";import"./chunk-2GIDVZ4H.js";import"./chunk-CXCXMOTB.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-M6NIPFRY.js";import"./chunk-RJ7DASOU.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{b as WikiHub,a as WikiStore,c as agenticQuery};
|
|
2
|
+
//# sourceMappingURL=wiki-6SCKSY4I.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{l as a,m as b,n as c,o as d,p as e,q as f}from"./chunk-UDJAODAB.js";import"./chunk-QIJLFPWE.js";export{b as generateClaudeMd,d as patchGuardrails,e as patchObservationPack,a as readManagedHash,f as setupAllWorkspaces,c as setupWorkspace};
|
|
2
|
+
//# sourceMappingURL=workspace-setup-EA3G42NY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agentix-cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.107.0",
|
|
4
4
|
"description": "AI operations layer for small and medium businesses. Routes Telegram, WhatsApp, GitLab, GitHub, crons, webhooks, and mesh tasks to AI agents. Web wizard for operators, CLI for engineers. Self-hosted.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": {
|
package/dist/chunk-DWADWDMU.js
DELETED
|
@@ -1,96 +0,0 @@
|
|
|
1
|
-
import{existsSync as d,mkdirSync as P,writeFileSync as g,readFileSync as x}from"fs";import{resolve as u}from"path";import{createHash as F}from"crypto";import{readFileSync as C,existsSync as I,unlinkSync as B,readdirSync as ee}from"fs";import{resolve as A}from"path";function se(s,t){let n={},r=e=>{let o=A(s,e);if(I(o))try{return C(o,"utf-8").trim()||void 0}catch{return}};if(t){let e=r(`SOUL.${t}.md`);e?(n.soul=e,n.soulProfile=t):n.soul=r("SOUL.md")}else n.soul=r("SOUL.md");if(n.identity=r("IDENTITY.md"),n.user=r("USER.md"),n.agents=r("AGENTS.md"),n.bootstrap=r("BOOTSTRAP.md"),n.bootstrap)try{B(A(s,"BOOTSTRAP.md"))}catch{}return n}function ne(s){let t=[];return s.identity&&t.push(`[Identity]
|
|
2
|
-
${s.identity}`),s.soul&&t.push(`[Personality & Boundaries]
|
|
3
|
-
${s.soul}`),s.user&&t.push(`[User Profile]
|
|
4
|
-
${s.user}`),s.bootstrap&&t.push(`[First-Run Instructions \u2014 one time only]
|
|
5
|
-
${s.bootstrap}`),t.length===0?"":t.join(`
|
|
6
|
-
|
|
7
|
-
`)}function _(s){return`# ${s.name}
|
|
8
|
-
|
|
9
|
-
> Agent ID: \`${s.id}\` | Tier: ${s.tier||"claude-code"}
|
|
10
|
-
|
|
11
|
-
## Role
|
|
12
|
-
|
|
13
|
-
${s.role||"AI agent managed by AgentX orchestrator."}
|
|
14
|
-
|
|
15
|
-
## Setup
|
|
16
|
-
|
|
17
|
-
This workspace is managed by AgentX. The agent runs via:
|
|
18
|
-
\`\`\`bash
|
|
19
|
-
# Direct execution
|
|
20
|
-
agentx daemon send ${s.id} "your task here"
|
|
21
|
-
|
|
22
|
-
# Or via any connected channel (Telegram, WhatsApp, GitLab)
|
|
23
|
-
\`\`\`
|
|
24
|
-
|
|
25
|
-
## Code Style
|
|
26
|
-
|
|
27
|
-
- Follow existing patterns in the codebase
|
|
28
|
-
- Use the language and framework conventions already present
|
|
29
|
-
- Keep changes minimal and focused
|
|
30
|
-
|
|
31
|
-
## Testing
|
|
32
|
-
|
|
33
|
-
Run tests before committing:
|
|
34
|
-
\`\`\`bash
|
|
35
|
-
npm test # or the project's test command
|
|
36
|
-
\`\`\`
|
|
37
|
-
|
|
38
|
-
## PR Guidelines
|
|
39
|
-
|
|
40
|
-
- One logical change per commit
|
|
41
|
-
- Reference issue numbers when applicable
|
|
42
|
-
- Keep PR descriptions concise
|
|
43
|
-
|
|
44
|
-
## AgentX Integration
|
|
45
|
-
|
|
46
|
-
This agent is part of an AgentX mesh. It can:
|
|
47
|
-
- Receive tasks from messaging channels (Telegram, WhatsApp, Discord)
|
|
48
|
-
- Respond to GitLab @mentions on issues and MRs
|
|
49
|
-
- Delegate to other agents by mentioning their handles
|
|
50
|
-
- Send cross-channel messages via the /send API
|
|
51
|
-
- Access its wiki knowledge base for context
|
|
52
|
-
`}function re(s){let t=s.match(/\/soul\s+(\w+)/i);return t?t[1].toLowerCase():/\/soul\s*$/i.test(s)?"default":null}import{execFile as U}from"child_process";import{existsSync as S}from"fs";import{resolve as N}from"path";var T=["mcp__codegraph__codegraph_search","mcp__codegraph__codegraph_context","mcp__codegraph__codegraph_callers","mcp__codegraph__codegraph_callees","mcp__codegraph__codegraph_impact","mcp__codegraph__codegraph_node","mcp__codegraph__codegraph_status","mcp__codegraph__codegraph_files"],v={command:"codegraph",args:["serve","--mcp"]};function E(){return["## CodeGraph","","This workspace has CodeGraph initialized \u2014 a semantic code-knowledge-graph indexed via tree-sitter. Use it instead of grep/find/Read for exploration.","","**ALWAYS spawn an Explore subagent for `codegraph_explore` / `codegraph_context`** \u2014 those tools return large source sections that would otherwise bloat the main session. Include this in the Explore prompt:","","> Use `codegraph_explore` as your PRIMARY tool \u2014 one call returns full source from all relevant files. Do not re-Read files codegraph_explore already returned. Fall back to grep/glob/Read only if codegraph returned no results.","","**In the main session, use these lightweight codegraph tools directly:**","","| Tool | Use for |","|---|---|","| `codegraph_search` | Find symbols by name across the codebase |","| `codegraph_callers` / `codegraph_callees` | Trace call flow |","| `codegraph_impact` | Check what's affected before editing a symbol |","| `codegraph_node` | Get a single symbol's details |","| `codegraph_files` | Indexed file structure (faster than ls) |","| `codegraph_status` | Index health |",""].join(`
|
|
53
|
-
`)}function pe(s){let t=s.mcp??{};return!s.codegraph||t.codegraph?t:{...t,codegraph:{command:v.command,args:[...v.args]}}}var L=".codegraph",j=10*60*1e3,R=2;function G(s){let t=Date.now();return new Promise((n,r)=>{U("codegraph",["init","--index","--quiet",s],{timeout:j,maxBuffer:4*1024*1024},e=>{e?r(e):n(Date.now()-t)})})}async function ue(s,t=console.error){let n=[];for(let[o,i]of Object.entries(s))i.codegraph&&(i.tier!=="claude-code"&&i.tier!=="codex-cli"||S(i.workspace)&&(S(N(i.workspace,L))||n.push({agentId:o,workspace:i.workspace})));if(n.length===0)return;t(`codegraph: indexing ${n.length} workspace(s) in background (max ${R} parallel)`);let r=0,e=[];for(let o=0;o<Math.min(R,n.length);o++)e.push((async()=>{for(;;){let i=r++;if(i>=n.length)return;let{agentId:c,workspace:p}=n[i];try{let l=await G(p);t(` codegraph: indexed ${c} in ${(l/1e3).toFixed(1)}s`)}catch(l){let h=l?.code==="ENOENT"?" (codegraph CLI not on PATH; install with `npm i -g @colbymchenry/codegraph`)":"";t(` codegraph: ${c} index failed: ${l?.message??l}${h}`)}}})());await Promise.allSettled(e)}var y="<!-- agentx-managed: hash=",b=" -->";function $(s){return F("sha256").update(s.systemPrompt??"").update("\0").update(s.codegraph?"cg:1":"cg:0").digest("hex").slice(0,16)}function W(s){return`${y}${$(s)}${b}`}function q(s){let t=s.split(`
|
|
54
|
-
`,1)[0]??"";return!t.startsWith(y)||!t.endsWith(b)?null:t.slice(y.length,t.length-b.length)}function D(s,t){let n=`${s} ${t.systemPrompt||""} ${t.name}`.toLowerCase();return/cod(e|ing|er)|develop|engineer|program/.test(n)?"coding":/pm|project.?manag|product|scrum/.test(n)?"pm":/devops|deploy|infra|ops|sre|ci.?cd/.test(n)?"devops":/qa|test|quality|forensic/.test(n)?"qa":"general"}function H(s,t,n){let r=D(s,t),e=[];switch(e.push(W(t)),e.push(`# ${t.name}`),e.push(""),e.push("@AGENTS.md"),e.push(""),t.systemPrompt&&t.systemPrompt.trim().length>0&&(e.push("## Role"),e.push(""),e.push(t.systemPrompt.trimEnd()),e.push("")),e.push("## Commands"),e.push(""),d(u(t.workspace,"package.json"))?(e.push("```bash"),e.push("npm install # install dependencies"),e.push("npm test # run tests"),e.push("npm run build # build project"),e.push("```")):d(u(t.workspace,"requirements.txt"))&&(e.push("```bash"),e.push("pip install -r requirements.txt"),e.push("pytest"),e.push("```")),e.push(""),e.push("## Conventions"),e.push(""),r){case"coding":e.push("- Write tests for new code before committing"),e.push("- Keep functions small and focused"),e.push("- Follow existing patterns in the codebase"),e.push("- Run tests before pushing");break;case"pm":e.push("- Keep responses concise (3-5 lines main message)"),e.push("- Reference issues with #IID and MRs with !IID"),e.push("- Update issue labels and milestones when relevant"),e.push("- Summarize decisions, don't narrate process");break;case"devops":e.push("- Always check service status before making changes"),e.push("- Never run destructive commands without confirmation"),e.push("- Log all deployment actions"),e.push("- Verify changes in staging before production");break;case"qa":e.push("- Document reproduction steps for every bug"),e.push("- Include expected vs actual behavior"),e.push("- Check both happy path and edge cases"),e.push("- Attach screenshots when reporting UI issues");break;default:e.push("- Be concise \u2014 lead with the answer, skip preamble"),e.push("- Follow existing patterns in the codebase")}return e.push(""),e.push("## Cross-Channel Messaging"),e.push(""),e.push("You can send messages to any channel proactively:"),e.push("```bash"),e.push(`curl -X POST http://localhost:${n}/send \\`),e.push(' -H "Content-Type: application/json" \\'),e.push(` -d '{"channel":"telegram","chatId":"<id>","text":"<message>","agentId":"${s}"}'`),e.push("```"),e.push("Channels: telegram, whatsapp, gitlab, discord"),e.push(""),e.push("## Typed actions \u2014 prefer these over free-form Bash"),e.push(""),e.push("Daemon-shipped typed actions cover the common needs. Each call appears in `/traces` as a structured step (input + output schema), unlike opaque `Bash`/`curl`/`Read` calls."),e.push(""),e.push("```bash"),e.push("# List available actions + their schemas"),e.push("agentx actions builtin # \u2192 catalog"),e.push("agentx actions builtin <name> --schema # \u2192 input/output schema"),e.push(""),e.push("# Invoke an action with typed JSON input"),e.push(`agentx actions builtin http.fetch --input '{"url":"https://example.com/data"}'`),e.push(`agentx actions builtin http.post --input '{"url":"https://x.tld/hook","body":{"k":"v"}}'`),e.push(`agentx actions builtin file.read_lines --input '{"path":"data/prices.json"}'`),e.push(`agentx actions builtin file.write_jsonl --input '{"path":"leads.jsonl","record":{"name":"\u2026","email":"\u2026"}}'`),e.push(`agentx actions builtin extract.structured --input '{"prompt":"<text>","schema":{"type":"object",\u2026}}'`),e.push(`agentx actions builtin rag.lexical --input '{"agentId":"${s}","query":"\u2026","limit":5}'`),e.push(`agentx actions builtin agent.call --input '{"agentId":"<local-agent>","message":"\u2026"}'`),e.push(`agentx actions builtin mesh.delegate --input '{"peer":"<peer-name>","agent":"<peer-agent>","message":"\u2026"}'`),e.push("```"),e.push(""),e.push("Rule of thumb:"),e.push("- HTTP fetch/POST \u2192 `http.fetch` / `http.post` (not `Bash curl`)"),e.push("- Reading a file you'll parse \u2192 `file.read_lines` (not `Bash cat`)"),e.push("- Appending a structured record \u2192 `file.write_jsonl` (not `Bash echo >>` or `Write` with model-formatted JSON)"),e.push("- Extracting fields from text into a typed object \u2192 `extract.structured` (not asking the model to format JSON in its reply)"),e.push("- Searching a doc corpus \u2192 `rag.lexical` (not `Read` over every file)"),e.push("- Calling another agent on this daemon \u2192 `agent.call` (fresh session by default; not composing `Bash curl` to /task)"),e.push("- Calling an agent on a peer mesh node \u2192 `mesh.delegate` (cross-machine; same fresh-session default)"),e.push(""),t.codegraph&&e.push(E()),e.join(`
|
|
55
|
-
`)}var f=["Bash(npx prisma migrate reset*)","Bash(prisma migrate reset*)","Bash(npx prisma db push*)","Bash(prisma db push*)","Bash(dropdb*)"];function X(s,t){return`curl -s --max-time 3 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${t}/guard/check?agent=${encodeURIComponent(s)}`}' 2>/dev/null || true`}function O(s,t){let n=X(s,t);return[{matcher:"Bash",hooks:[{type:"command",command:n,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:n,timeout:10}]}]}function J(s){return Array.isArray(s?.hooks)&&s.hooks.some(t=>typeof t?.command=="string"&&(t.command.includes("/guard/check")||t.command.includes("guard check")))}function K(s,t,n="19900"){let r={autoMemoryEnabled:!0,env:{CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS:"1"}};if(t.permissionMode==="bypassPermissions"?r.permissions={deny:[...f]}:t.permissionMode==="plan"?r.permissions={deny:[...f,"Bash(rm -rf *)","Bash(drop *)","Bash(DELETE *)"]}:r.permissions={deny:[...f,"Bash(rm -rf /)","Bash(> /dev/sda*)","Bash(mkfs*)"]},t.codegraph){let o=r.permissions||{},i=Array.isArray(o.allow)?o.allow:[];o.allow=[...new Set([...i,...T])],r.permissions=o}let e={};return e.PreToolUse=O(s,n),e.Notification=[{matcher:"",hooks:[{type:"command",command:`echo "[${s}] notification: $(jq -r '.type // "unknown"')" >> /tmp/agentx-${s}.log`}]}],e.PostToolUse=[{matcher:"Bash",hooks:[{type:"command",command:`jq -r '.tool_input.command // empty' >> /tmp/agentx-${s}-commands.log`}]}],e.SessionStart=[{matcher:"compact",hooks:[{type:"command",command:`echo "Reminder: You are ${t.name} (${s}). Follow the conventions in CLAUDE.md."`}]}],r.hooks=e,r}function Y(s,t){let n=D(s,t),r=[];switch(n){case"coding":r.push({name:"testing.md",content:`---
|
|
56
|
-
paths:
|
|
57
|
-
- "**/*.test.{ts,tsx,js,jsx}"
|
|
58
|
-
- "**/*.spec.{ts,tsx,js,jsx}"
|
|
59
|
-
- "test/**/*"
|
|
60
|
-
---
|
|
61
|
-
|
|
62
|
-
# Testing Rules
|
|
63
|
-
|
|
64
|
-
- Every new function should have a corresponding test
|
|
65
|
-
- Test both happy path and error cases
|
|
66
|
-
- Use descriptive test names that explain what's being tested
|
|
67
|
-
- Mock external dependencies, not internal modules
|
|
68
|
-
`}),r.push({name:"code-quality.md",content:`# Code Quality
|
|
69
|
-
|
|
70
|
-
- No console.log in production code (use a logger)
|
|
71
|
-
- Handle errors explicitly \u2014 no empty catch blocks
|
|
72
|
-
- Keep files under 300 lines
|
|
73
|
-
- Extract repeated logic into shared utilities
|
|
74
|
-
`});break;case"devops":r.push({name:"deployment-safety.md",content:`# Deployment Safety
|
|
75
|
-
|
|
76
|
-
- Always verify staging before production
|
|
77
|
-
- Check disk space and memory before deploying
|
|
78
|
-
- Never expose secrets in logs or commits
|
|
79
|
-
- Use rollback-safe deployment strategies
|
|
80
|
-
`});break;case"pm":r.push({name:"communication.md",content:`# Communication Rules
|
|
81
|
-
|
|
82
|
-
- Keep GitLab comments under 5 lines for the main message
|
|
83
|
-
- Use <details> for verbose output (logs, commands, steps)
|
|
84
|
-
- Reference issues with #IID, merge requests with !IID
|
|
85
|
-
- Never mention Telegram handles on GitLab
|
|
86
|
-
`});break;case"qa":r.push({name:"bug-reports.md",content:`# Bug Report Format
|
|
87
|
-
|
|
88
|
-
Always include:
|
|
89
|
-
1. Steps to reproduce
|
|
90
|
-
2. Expected behavior
|
|
91
|
-
3. Actual behavior
|
|
92
|
-
4. Environment (browser, OS, version)
|
|
93
|
-
5. Screenshots if applicable
|
|
94
|
-
`});break}return r}function V(s,t,n="19900",r=console.error){let e=[],o=[],i=t.workspace;if(!d(i))return r(`Workspace not found: ${i}`),{created:e,skipped:o};if(t.tier!=="claude-code"&&t.tier!=="codex-cli")return{created:e,skipped:o};let c=(a,m)=>{d(a)?o.push(a):(P(u(a,".."),{recursive:!0}),g(a,m),e.push(a))},p=(a,m,M)=>{if(!d(a)){P(u(a,".."),{recursive:!0}),g(a,m),e.push(a);return}let k;try{k=x(a,"utf8")}catch{o.push(a);return}let w=q(k);if(w===null){o.push(a);return}if(w===M){o.push(a);return}g(a,m),e.push(`${a} (refreshed)`)};if(c(u(i,"AGENTS.md"),_({name:t.name,id:s,role:t.systemPrompt?.split(`
|
|
95
|
-
`)[0],workspace:i,tier:t.tier})),t.tier==="codex-cli")return e.length>0&&r(`[${s}] workspace setup: created ${e.length} file(s)`),{created:e,skipped:o};p(u(i,"CLAUDE.md"),H(s,t,n),$(t));let l=u(i,".claude/settings.json");c(l,JSON.stringify(K(s,t,n),null,2));let h=Y(s,t);for(let a of h)c(u(i,".claude/rules",a.name),a.content);return e.length>0&&r(`[${s}] workspace setup: created ${e.length} file(s)`),{created:e,skipped:o}}function z(s,t){let n=u(s,".claude/settings.json");if(!d(n))return!1;try{let r=JSON.parse(x(n,"utf-8")),e=!1;for(let[o,i]of Object.entries(t))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){r[o]||(r[o]={});for(let[c,p]of Object.entries(i))r[o][c]===void 0&&(r[o][c]=p,e=!0)}else r[o]===void 0&&(r[o]=i,e=!0);return e&&g(n,JSON.stringify(r,null,2)),e}catch{return!1}}function Q(s,t,n="19900"){let r=u(s,".claude/settings.json");if(!d(r))return!1;try{let e=JSON.parse(x(r,"utf-8")),o=!1,i=e.permissions??={},c=Array.isArray(i.deny)?i.deny:i.deny=[];for(let a of f)c.includes(a)||(c.push(a),o=!0);let p=e.hooks??={},h=[...Array.isArray(p.PreToolUse)?p.PreToolUse.filter(a=>!J(a)):[],...O(t,n)];return JSON.stringify(p.PreToolUse??null)!==JSON.stringify(h)&&(p.PreToolUse=h,o=!0),o&&g(r,JSON.stringify(e,null,2)),o}catch{return!1}}function ye(s,t="19900",n=console.error){let r=0,e=0,o=0;for(let[i,c]of Object.entries(s)){if(c.tier!=="claude-code"&&c.tier!=="codex-cli")continue;let p=V(i,c,t,n);r+=p.created.length,c.tier==="claude-code"&&z(c.workspace,{env:{CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS:"1"}})&&e++,c.tier==="claude-code"&&Q(c.workspace,i,t)&&o++}r>0&&n(`Workspace setup: ${r} file(s) created across agent workspaces`),e>0&&n(`Workspace patch: ${e} workspace(s) updated with agent teams support`),o>0&&n(`Guardrails: ${o} workspace(s) backfilled with deny list + PreToolUse guard hook`)}export{se as a,ne as b,re as c,pe as d,ue as e,q as f,H as g,V as h,Q as i,ye as j};
|
|
96
|
-
//# sourceMappingURL=chunk-DWADWDMU.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/agents/workspace-setup.ts","../src/agents/bootstrap.ts","../src/agents/codegraph-bootstrap.ts"],"sourcesContent":["import { existsSync, mkdirSync, writeFileSync, readFileSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { createHash } from \"crypto\"\nimport type { AgentDef } from \"@/daemon/config\"\nimport { generateAgentsMd } from \"./bootstrap\"\nimport { CODEGRAPH_TOOLS, codegraphClaudeMdSection } from \"./codegraph-bootstrap\"\n\n// Marker stamped into auto-generated CLAUDE.md so we can tell agentx-managed\n// files apart from user-edited ones. On daemon start, files with the marker\n// are silently regenerated when the systemPrompt hash changes; files without\n// the marker are treated as user-owned and never touched.\nconst MANAGED_MARKER_PREFIX = \"<!-- agentx-managed: hash=\"\nconst MANAGED_MARKER_SUFFIX = \" -->\"\n\n/** Hash inputs that drive the managed-CLAUDE.md content. Anything that\n * affects what `generateClaudeMd` emits should feed into this so flipping\n * the input also refreshes the file on next boot. Currently:\n * systemPrompt + codegraph flag (the codegraph instruction block is\n * conditional on it). */\nfunction managedHashInputs(def: Pick<AgentDef, \"systemPrompt\" | \"codegraph\">): string {\n return createHash(\"sha256\")\n .update(def.systemPrompt ?? \"\")\n .update(\"\\0\")\n .update(def.codegraph ? \"cg:1\" : \"cg:0\")\n .digest(\"hex\")\n .slice(0, 16)\n}\n\nfunction buildManagedMarker(def: Pick<AgentDef, \"systemPrompt\" | \"codegraph\">): string {\n return `${MANAGED_MARKER_PREFIX}${managedHashInputs(def)}${MANAGED_MARKER_SUFFIX}`\n}\n\n/**\n * Read the managed marker from an existing file's first line, if present.\n * Returns the hash (truncated sha256 hex) when found, null otherwise.\n * Files without the marker are user-managed and untouchable.\n */\nexport function readManagedHash(content: string): string | null {\n const firstLine = content.split(\"\\n\", 1)[0] ?? \"\"\n if (!firstLine.startsWith(MANAGED_MARKER_PREFIX)) return null\n if (!firstLine.endsWith(MANAGED_MARKER_SUFFIX)) return null\n return firstLine.slice(MANAGED_MARKER_PREFIX.length, firstLine.length - MANAGED_MARKER_SUFFIX.length)\n}\n\n// --- Workspace Setup: align agent workspaces with Claude Code best practices ---\n//\n// Generates on daemon start (if missing):\n// CLAUDE.md — project conventions, under 200 lines, @AGENTS.md import\n// AGENTS.md — agents.md spec for cross-tool compatibility\n// .claude/settings.json — hooks, permissions, auto memory\n// .claude/rules/ — path-specific rules based on agent role\n\n/** Detect agent role from systemPrompt or agent ID */\nfunction detectRole(agentId: string, def: AgentDef): \"coding\" | \"pm\" | \"devops\" | \"qa\" | \"general\" {\n const text = `${agentId} ${def.systemPrompt || \"\"} ${def.name}`.toLowerCase()\n if (/cod(e|ing|er)|develop|engineer|program/.test(text)) return \"coding\"\n if (/pm|project.?manag|product|scrum/.test(text)) return \"pm\"\n if (/devops|deploy|infra|ops|sre|ci.?cd/.test(text)) return \"devops\"\n if (/qa|test|quality|forensic/.test(text)) return \"qa\"\n return \"general\"\n}\n\n/** Generate CLAUDE.md for an agent workspace */\nexport function generateClaudeMd(agentId: string, def: AgentDef, daemonPort: string): string {\n const role = detectRole(agentId, def)\n const lines: string[] = []\n\n // Managed-marker on line 1 — used by setupWorkspace to detect stale\n // auto-generated files and regenerate them when systemPrompt changes.\n // User-edited files (no marker) are left alone forever.\n lines.push(buildManagedMarker(def))\n lines.push(`# ${def.name}`)\n lines.push(\"\")\n lines.push(\"@AGENTS.md\")\n lines.push(\"\")\n\n // Agent identity from systemPrompt — emitted verbatim. Truncating here would\n // silently drop instructions (e.g. multi-paragraph protocols), so we trade\n // a few extra tokens in CLAUDE.md for fidelity. The runtime path already\n // forwards the full systemPrompt via --append-system-prompt; this section\n // mirrors it for tools that read CLAUDE.md as workspace context.\n if (def.systemPrompt && def.systemPrompt.trim().length > 0) {\n lines.push(\"## Role\")\n lines.push(\"\")\n lines.push(def.systemPrompt.trimEnd())\n lines.push(\"\")\n }\n\n // Build/test commands\n lines.push(\"## Commands\")\n lines.push(\"\")\n if (existsSync(resolve(def.workspace, \"package.json\"))) {\n lines.push(\"```bash\")\n lines.push(\"npm install # install dependencies\")\n lines.push(\"npm test # run tests\")\n lines.push(\"npm run build # build project\")\n lines.push(\"```\")\n } else if (existsSync(resolve(def.workspace, \"requirements.txt\"))) {\n lines.push(\"```bash\")\n lines.push(\"pip install -r requirements.txt\")\n lines.push(\"pytest\")\n lines.push(\"```\")\n }\n lines.push(\"\")\n\n // Role-specific conventions\n lines.push(\"## Conventions\")\n lines.push(\"\")\n switch (role) {\n case \"coding\":\n lines.push(\"- Write tests for new code before committing\")\n lines.push(\"- Keep functions small and focused\")\n lines.push(\"- Follow existing patterns in the codebase\")\n lines.push(\"- Run tests before pushing\")\n break\n case \"pm\":\n lines.push(\"- Keep responses concise (3-5 lines main message)\")\n lines.push(\"- Reference issues with #IID and MRs with !IID\")\n lines.push(\"- Update issue labels and milestones when relevant\")\n lines.push(\"- Summarize decisions, don't narrate process\")\n break\n case \"devops\":\n lines.push(\"- Always check service status before making changes\")\n lines.push(\"- Never run destructive commands without confirmation\")\n lines.push(\"- Log all deployment actions\")\n lines.push(\"- Verify changes in staging before production\")\n break\n case \"qa\":\n lines.push(\"- Document reproduction steps for every bug\")\n lines.push(\"- Include expected vs actual behavior\")\n lines.push(\"- Check both happy path and edge cases\")\n lines.push(\"- Attach screenshots when reporting UI issues\")\n break\n default:\n lines.push(\"- Be concise — lead with the answer, skip preamble\")\n lines.push(\"- Follow existing patterns in the codebase\")\n }\n lines.push(\"\")\n\n // Cross-channel messaging capability\n lines.push(\"## Cross-Channel Messaging\")\n lines.push(\"\")\n lines.push(\"You can send messages to any channel proactively:\")\n lines.push(\"```bash\")\n lines.push(`curl -X POST http://localhost:${daemonPort}/send \\\\`)\n lines.push(` -H \"Content-Type: application/json\" \\\\`)\n lines.push(` -d '{\"channel\":\"telegram\",\"chatId\":\"<id>\",\"text\":\"<message>\",\"agentId\":\"${agentId}\"}'`)\n lines.push(\"```\")\n lines.push('Channels: telegram, whatsapp, gitlab, discord')\n lines.push(\"\")\n\n // Typed actions catalog — prefer these over free-form Bash/Read/Write/curl\n // when applicable. Each action's call lands in /traces as a structured\n // step (action: <name>, input: …, output: …) which is how observability\n // works in this codebase. Free-form Bash gets recorded as opaque shell\n // text, which is harder to debug and harder to compose into workflows.\n lines.push(\"## Typed actions — prefer these over free-form Bash\")\n lines.push(\"\")\n lines.push(\"Daemon-shipped typed actions cover the common needs. Each call appears in `/traces` as a structured step (input + output schema), unlike opaque `Bash`/`curl`/`Read` calls.\")\n lines.push(\"\")\n lines.push(\"```bash\")\n lines.push(\"# List available actions + their schemas\")\n lines.push(`agentx actions builtin # → catalog`)\n lines.push(`agentx actions builtin <name> --schema # → input/output schema`)\n lines.push(\"\")\n lines.push(\"# Invoke an action with typed JSON input\")\n lines.push(`agentx actions builtin http.fetch --input '{\"url\":\"https://example.com/data\"}'`)\n lines.push(`agentx actions builtin http.post --input '{\"url\":\"https://x.tld/hook\",\"body\":{\"k\":\"v\"}}'`)\n lines.push(`agentx actions builtin file.read_lines --input '{\"path\":\"data/prices.json\"}'`)\n lines.push(`agentx actions builtin file.write_jsonl --input '{\"path\":\"leads.jsonl\",\"record\":{\"name\":\"…\",\"email\":\"…\"}}'`)\n lines.push(`agentx actions builtin extract.structured --input '{\"prompt\":\"<text>\",\"schema\":{\"type\":\"object\",…}}'`)\n lines.push(`agentx actions builtin rag.lexical --input '{\"agentId\":\"${agentId}\",\"query\":\"…\",\"limit\":5}'`)\n lines.push(`agentx actions builtin agent.call --input '{\"agentId\":\"<local-agent>\",\"message\":\"…\"}'`)\n lines.push(`agentx actions builtin mesh.delegate --input '{\"peer\":\"<peer-name>\",\"agent\":\"<peer-agent>\",\"message\":\"…\"}'`)\n lines.push(\"```\")\n lines.push(\"\")\n lines.push(\"Rule of thumb:\")\n lines.push(\"- HTTP fetch/POST → `http.fetch` / `http.post` (not `Bash curl`)\")\n lines.push(\"- Reading a file you'll parse → `file.read_lines` (not `Bash cat`)\")\n lines.push(\"- Appending a structured record → `file.write_jsonl` (not `Bash echo >>` or `Write` with model-formatted JSON)\")\n lines.push(\"- Extracting fields from text into a typed object → `extract.structured` (not asking the model to format JSON in its reply)\")\n lines.push(\"- Searching a doc corpus → `rag.lexical` (not `Read` over every file)\")\n lines.push(\"- Calling another agent on this daemon → `agent.call` (fresh session by default; not composing `Bash curl` to /task)\")\n lines.push(\"- Calling an agent on a peer mesh node → `mesh.delegate` (cross-machine; same fresh-session default)\")\n lines.push(\"\")\n\n // CodeGraph instruction block — only when the agent opted in. See\n // src/agents/codegraph-bootstrap.ts for the section content; sourcing it\n // from one place keeps the wording consistent if upstream changes.\n if (def.codegraph) {\n lines.push(codegraphClaudeMdSection())\n }\n\n return lines.join(\"\\n\")\n}\n\n// Phase 0 stop-gap deny list for the destructive-action guardrails. Claude\n// Code deny globs are coarse (single trailing wildcard), so this is a blunt\n// backstop for the clearly-always-destructive prisma/dropdb classes that\n// caused the 2026-07-21 prod-wipe incident. The env-var-resolved, nuanced\n// matching (diff --shadow-database-url pointed at prod, pg_restore --clean,\n// migrate deploy) is done by the `agentx guard` PreToolUse hook, which runs\n// even under bypassPermissions (where deny rules may be skipped).\nconst GUARDRAIL_DENY = [\n \"Bash(npx prisma migrate reset*)\",\n \"Bash(prisma migrate reset*)\",\n \"Bash(npx prisma db push*)\",\n \"Bash(prisma db push*)\",\n \"Bash(dropdb*)\",\n]\n\n/**\n * The command the PreToolUse hook runs. This fires on EVERY Bash/Write/Edit\n * call, so it must be cheap: spawning `node dist/cli.js guard check` cost\n * ~300ms of interpreter + bundle boot per tool call. Instead we POST the\n * payload to the already-running daemon over loopback (~1ms) and pipe its\n * response straight back to Claude Code. `/guard/check` is loopback-only.\n *\n * The trailing `|| true` is load-bearing: a PreToolUse hook exiting 2 BLOCKS\n * the tool call, and curl uses exit 2 for its own init failures. Forcing\n * exit 0 means a curl/daemon problem can never masquerade as a policy deny.\n * If the daemon is unreachable we fail open — acceptable because the daemon\n * is what spawns the agents in the first place, so \"daemon down\" means there\n * are no agent tool calls to guard.\n */\nfunction guardHookCommand(agentId: string, daemonPort: string): string {\n const url = `http://127.0.0.1:${daemonPort}/guard/check?agent=${encodeURIComponent(agentId)}`\n return `curl -s --max-time 3 -H 'Content-Type: application/json' --data-binary @- '${url}' 2>/dev/null || true`\n}\n\n/** PreToolUse hook entries wiring the guard onto Bash + Write/Edit. */\nfunction guardPreToolUseHooks(agentId: string, daemonPort: string): unknown[] {\n const command = guardHookCommand(agentId, daemonPort)\n return [\n { matcher: \"Bash\", hooks: [{ type: \"command\", command, timeout: 10 }] },\n { matcher: \"Write|Edit\", hooks: [{ type: \"command\", command, timeout: 10 }] },\n ]\n}\n\n/** Is this hook entry one of ours? Matches both the current curl form and\n * the earlier `guard check` CLI form, so stale entries get replaced rather\n * than duplicated. */\nfunction isGuardEntry(entry: any): boolean {\n return (\n Array.isArray(entry?.hooks) &&\n entry.hooks.some(\n (h: any) =>\n typeof h?.command === \"string\" && (h.command.includes(\"/guard/check\") || h.command.includes(\"guard check\")),\n )\n )\n}\n\n/** Generate .claude/settings.json with hooks and permissions */\nfunction generateSettings(agentId: string, def: AgentDef, daemonPort: string = \"19900\"): Record<string, unknown> {\n const settings: Record<string, unknown> = {\n autoMemoryEnabled: true,\n env: {\n CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS: \"1\",\n },\n }\n\n // Permission mode. The guardrail deny list is injected in ALL modes —\n // including bypassPermissions, which previously had none — as a stop-gap\n // backstop beneath the PreToolUse guard hook.\n if (def.permissionMode === \"bypassPermissions\") {\n settings[\"permissions\"] = { deny: [...GUARDRAIL_DENY] }\n } else if (def.permissionMode === \"plan\") {\n settings[\"permissions\"] = {\n deny: [...GUARDRAIL_DENY, \"Bash(rm -rf *)\", \"Bash(drop *)\", \"Bash(DELETE *)\"],\n }\n } else {\n // Default: deny destructive operations\n settings[\"permissions\"] = {\n deny: [\n ...GUARDRAIL_DENY,\n \"Bash(rm -rf /)\",\n \"Bash(> /dev/sda*)\",\n \"Bash(mkfs*)\",\n ],\n }\n }\n\n // Pre-authorize codegraph MCP tools so claude doesn't prompt for each\n // call. Even under bypassPermissions there's no harm — an explicit allow\n // list survives if the agent later switches to a stricter mode.\n if (def.codegraph) {\n const perms = (settings[\"permissions\"] as Record<string, unknown>) || {}\n const existing = Array.isArray(perms[\"allow\"]) ? (perms[\"allow\"] as string[]) : []\n perms[\"allow\"] = [...new Set([...existing, ...CODEGRAPH_TOOLS])]\n settings[\"permissions\"] = perms\n }\n\n // Hooks\n const hooks: Record<string, unknown[]> = {}\n\n // PreToolUse — destructive-action guardrails. Runs the guard on every Bash\n // and Write/Edit call; in warn mode it audits without blocking. This is the\n // primary enforcement chokepoint (works even under bypassPermissions).\n hooks[\"PreToolUse\"] = guardPreToolUseHooks(agentId, daemonPort)\n\n // Notification hook — log when agent needs input\n hooks[\"Notification\"] = [{\n matcher: \"\",\n hooks: [{\n type: \"command\",\n command: `echo \"[${agentId}] notification: $(jq -r '.type // \\\"unknown\\\"')\" >> /tmp/agentx-${agentId}.log`,\n }],\n }]\n\n // PostToolUse — log tool activity\n hooks[\"PostToolUse\"] = [{\n matcher: \"Bash\",\n hooks: [{\n type: \"command\",\n command: `jq -r '.tool_input.command // empty' >> /tmp/agentx-${agentId}-commands.log`,\n }],\n }]\n\n // SessionStart after compaction — re-inject key context\n hooks[\"SessionStart\"] = [{\n matcher: \"compact\",\n hooks: [{\n type: \"command\",\n command: `echo \"Reminder: You are ${def.name} (${agentId}). Follow the conventions in CLAUDE.md.\"`,\n }],\n }]\n\n settings[\"hooks\"] = hooks\n return settings\n}\n\n/** Generate .claude/rules/ files based on agent role */\nfunction generateRules(agentId: string, def: AgentDef): Array<{ name: string; content: string }> {\n const role = detectRole(agentId, def)\n const rules: Array<{ name: string; content: string }> = []\n\n switch (role) {\n case \"coding\":\n rules.push({\n name: \"testing.md\",\n content: `---\npaths:\n - \"**/*.test.{ts,tsx,js,jsx}\"\n - \"**/*.spec.{ts,tsx,js,jsx}\"\n - \"test/**/*\"\n---\n\n# Testing Rules\n\n- Every new function should have a corresponding test\n- Test both happy path and error cases\n- Use descriptive test names that explain what's being tested\n- Mock external dependencies, not internal modules\n`,\n })\n rules.push({\n name: \"code-quality.md\",\n content: `# Code Quality\n\n- No console.log in production code (use a logger)\n- Handle errors explicitly — no empty catch blocks\n- Keep files under 300 lines\n- Extract repeated logic into shared utilities\n`,\n })\n break\n\n case \"devops\":\n rules.push({\n name: \"deployment-safety.md\",\n content: `# Deployment Safety\n\n- Always verify staging before production\n- Check disk space and memory before deploying\n- Never expose secrets in logs or commits\n- Use rollback-safe deployment strategies\n`,\n })\n break\n\n case \"pm\":\n rules.push({\n name: \"communication.md\",\n content: `# Communication Rules\n\n- Keep GitLab comments under 5 lines for the main message\n- Use <details> for verbose output (logs, commands, steps)\n- Reference issues with #IID, merge requests with !IID\n- Never mention Telegram handles on GitLab\n`,\n })\n break\n\n case \"qa\":\n rules.push({\n name: \"bug-reports.md\",\n content: `# Bug Report Format\n\nAlways include:\n1. Steps to reproduce\n2. Expected behavior\n3. Actual behavior\n4. Environment (browser, OS, version)\n5. Screenshots if applicable\n`,\n })\n break\n }\n\n return rules\n}\n\n/**\n * Set up an agent workspace with CLI-agent best practices.\n * Only creates files that don't already exist (non-destructive).\n */\nexport function setupWorkspace(\n agentId: string,\n def: AgentDef,\n daemonPort: string = \"19900\",\n log: (...args: unknown[]) => void = console.error,\n): { created: string[]; skipped: string[] } {\n const created: string[] = []\n const skipped: string[] = []\n const workspace = def.workspace\n\n if (!existsSync(workspace)) {\n log(`Workspace not found: ${workspace}`)\n return { created, skipped }\n }\n\n // Only set up CLI-backed tier agents.\n if (def.tier !== \"claude-code\" && def.tier !== \"codex-cli\") {\n return { created, skipped }\n }\n\n const writeIfMissing = (path: string, content: string) => {\n if (existsSync(path)) {\n skipped.push(path)\n } else {\n mkdirSync(resolve(path, \"..\"), { recursive: true })\n writeFileSync(path, content)\n created.push(path)\n }\n }\n\n /**\n * Write a managed file with the agentx-managed marker. If the file already\n * exists and starts with our marker, regenerate when the embedded hash\n * doesn't match the current expected hash. Files without the marker are\n * treated as user-owned and left alone.\n */\n const writeManaged = (path: string, content: string, expectedHash: string) => {\n if (!existsSync(path)) {\n mkdirSync(resolve(path, \"..\"), { recursive: true })\n writeFileSync(path, content)\n created.push(path)\n return\n }\n let existing: string\n try {\n existing = readFileSync(path, \"utf8\")\n } catch {\n skipped.push(path)\n return\n }\n const existingHash = readManagedHash(existing)\n if (existingHash === null) {\n // User-edited (no marker) — never overwrite.\n skipped.push(path)\n return\n }\n if (existingHash === expectedHash) {\n skipped.push(path)\n return\n }\n writeFileSync(path, content)\n created.push(`${path} (refreshed)`)\n }\n\n // AGENTS.md (agents.md spec) — first-line of systemPrompt only, currently\n // not managed-marker'd. Left as writeIfMissing for now.\n writeIfMissing(\n resolve(workspace, \"AGENTS.md\"),\n generateAgentsMd({ name: def.name, id: agentId, role: def.systemPrompt?.split(\"\\n\")[0], workspace, tier: def.tier }),\n )\n\n if (def.tier === \"codex-cli\") {\n if (created.length > 0) {\n log(`[${agentId}] workspace setup: created ${created.length} file(s)`)\n }\n return { created, skipped }\n }\n\n // CLAUDE.md — managed: silently refreshed when systemPrompt OR codegraph\n // flag changes (both feed into the marker hash via managedHashInputs).\n writeManaged(\n resolve(workspace, \"CLAUDE.md\"),\n generateClaudeMd(agentId, def, daemonPort),\n managedHashInputs(def),\n )\n\n // .claude/settings.json\n const settingsPath = resolve(workspace, \".claude/settings.json\")\n writeIfMissing(settingsPath, JSON.stringify(generateSettings(agentId, def, daemonPort), null, 2))\n\n // .claude/rules/\n const rules = generateRules(agentId, def)\n for (const rule of rules) {\n writeIfMissing(resolve(workspace, \".claude/rules\", rule.name), rule.content)\n }\n\n if (created.length > 0) {\n log(`[${agentId}] workspace setup: created ${created.length} file(s)`)\n }\n\n return { created, skipped }\n}\n\n/**\n * Patch existing .claude/settings.json to add missing keys (non-destructive).\n * Used to enable new features (like agent teams) on workspaces that already have settings.\n */\nfunction patchSettings(workspace: string, patches: Record<string, unknown>): boolean {\n const settingsPath = resolve(workspace, \".claude/settings.json\")\n if (!existsSync(settingsPath)) return false\n\n try {\n const existing = JSON.parse(readFileSync(settingsPath, \"utf-8\"))\n let changed = false\n\n for (const [key, value] of Object.entries(patches)) {\n if (typeof value === \"object\" && value !== null && !Array.isArray(value)) {\n // Merge objects (e.g. env: { KEY: \"value\" })\n if (!existing[key]) existing[key] = {}\n for (const [subKey, subValue] of Object.entries(value as Record<string, unknown>)) {\n if (existing[key][subKey] === undefined) {\n existing[key][subKey] = subValue\n changed = true\n }\n }\n } else if (existing[key] === undefined) {\n existing[key] = value\n changed = true\n }\n }\n\n if (changed) {\n writeFileSync(settingsPath, JSON.stringify(existing, null, 2))\n }\n return changed\n } catch {\n return false\n }\n}\n\n/**\n * Backfill the destructive-action guardrails into an EXISTING settings.json:\n * merge the stop-gap deny list into permissions.deny (dedup, no clobber) and\n * add the PreToolUse guard hook if absent. writeIfMissing never touches\n * existing files, so live workspaces need this explicit patch. Idempotent —\n * re-running is a no-op once both are present. Returns true if it changed.\n */\nexport function patchGuardrails(workspace: string, agentId: string, daemonPort: string = \"19900\"): boolean {\n const settingsPath = resolve(workspace, \".claude/settings.json\")\n if (!existsSync(settingsPath)) return false\n\n try {\n const existing = JSON.parse(readFileSync(settingsPath, \"utf-8\"))\n let changed = false\n\n // 1. deny list\n const perms = (existing.permissions ??= {})\n const deny: string[] = Array.isArray(perms.deny) ? perms.deny : (perms.deny = [])\n for (const rule of GUARDRAIL_DENY) {\n if (!deny.includes(rule)) {\n deny.push(rule)\n changed = true\n }\n }\n\n // 2. PreToolUse guard hook. Drop any previous guard entries (including\n // the older node-CLI form) and re-add the current one, so a changed\n // port or invocation style self-heals instead of duplicating.\n const hooks = (existing.hooks ??= {})\n const others = Array.isArray(hooks.PreToolUse) ? hooks.PreToolUse.filter((e: any) => !isGuardEntry(e)) : []\n const desired = [...others, ...guardPreToolUseHooks(agentId, daemonPort)]\n if (JSON.stringify(hooks.PreToolUse ?? null) !== JSON.stringify(desired)) {\n hooks.PreToolUse = desired\n changed = true\n }\n\n if (changed) writeFileSync(settingsPath, JSON.stringify(existing, null, 2))\n return changed\n } catch {\n return false\n }\n}\n\n/**\n * Set up all agent workspaces on daemon start.\n */\nexport function setupAllWorkspaces(\n agents: Record<string, AgentDef>,\n daemonPort: string = \"19900\",\n log: (...args: unknown[]) => void = console.error,\n): void {\n let totalCreated = 0\n let totalPatched = 0\n let totalGuarded = 0\n for (const [id, def] of Object.entries(agents)) {\n if (def.tier !== \"claude-code\" && def.tier !== \"codex-cli\") continue\n const result = setupWorkspace(id, def, daemonPort, log)\n totalCreated += result.created.length\n\n // Patch existing settings with new features (agent teams, etc.)\n if (def.tier === \"claude-code\" && patchSettings(def.workspace, {\n env: { CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS: \"1\" },\n })) {\n totalPatched++\n }\n\n // Backfill destructive-action guardrails (deny list + PreToolUse hook)\n // onto existing workspaces.\n if (def.tier === \"claude-code\" && patchGuardrails(def.workspace, id, daemonPort)) {\n totalGuarded++\n }\n }\n if (totalCreated > 0) {\n log(`Workspace setup: ${totalCreated} file(s) created across agent workspaces`)\n }\n if (totalPatched > 0) {\n log(`Workspace patch: ${totalPatched} workspace(s) updated with agent teams support`)\n }\n if (totalGuarded > 0) {\n log(`Guardrails: ${totalGuarded} workspace(s) backfilled with deny list + PreToolUse guard hook`)\n }\n}\n","import { readFileSync, existsSync, unlinkSync, readdirSync } from \"fs\"\nimport { resolve } from \"path\"\n\n// --- Bootstrap Identity Files ---\n//\n// Support for structured workspace identity files (inspired by OpenClaw).\n// These files live in the agent's workspace and are auto-loaded into context.\n//\n// Supported files:\n// SOUL.md — default personality, tone, boundaries\n// SOUL.{profile}.md — named soul profiles (e.g. SOUL.finance.md, SOUL.legal.md)\n// IDENTITY.md — name, role, emoji, tagline (persistent)\n// USER.md — user profile, preferences (persistent)\n// AGENTS.md — operating rules, standing orders (persistent)\n// BOOTSTRAP.md — one-time first-run ritual (auto-deleted after first load)\n//\n// Soul switching: send \"/soul finance\" to swap to SOUL.finance.md mid-session.\n\nexport interface BootstrapFiles {\n soul?: string\n /** Active soul profile name (undefined = default SOUL.md) */\n soulProfile?: string\n identity?: string\n user?: string\n agents?: string\n bootstrap?: string\n}\n\nconst BOOTSTRAP_FILE_NAMES = [\n \"SOUL.md\",\n \"IDENTITY.md\",\n \"USER.md\",\n \"AGENTS.md\",\n \"BOOTSTRAP.md\",\n] as const\n\n/**\n * Load bootstrap identity files from an agent's workspace.\n * @param soulProfile — optional soul profile name (e.g. \"finance\" loads SOUL.finance.md)\n */\nexport function loadBootstrapFiles(workspace: string, soulProfile?: string): BootstrapFiles {\n const result: BootstrapFiles = {}\n\n const tryLoad = (filename: string): string | undefined => {\n const filePath = resolve(workspace, filename)\n if (!existsSync(filePath)) return undefined\n try {\n const content = readFileSync(filePath, \"utf-8\").trim()\n return content || undefined\n } catch {\n return undefined\n }\n }\n\n // Load soul: profile-specific if requested, fallback to default\n if (soulProfile) {\n const profileSoul = tryLoad(`SOUL.${soulProfile}.md`)\n if (profileSoul) {\n result.soul = profileSoul\n result.soulProfile = soulProfile\n } else {\n // Profile not found — fall back to default and note it\n result.soul = tryLoad(\"SOUL.md\")\n }\n } else {\n result.soul = tryLoad(\"SOUL.md\")\n }\n\n result.identity = tryLoad(\"IDENTITY.md\")\n result.user = tryLoad(\"USER.md\")\n result.agents = tryLoad(\"AGENTS.md\")\n result.bootstrap = tryLoad(\"BOOTSTRAP.md\")\n\n // BOOTSTRAP.md is one-time: delete after loading\n if (result.bootstrap) {\n try {\n unlinkSync(resolve(workspace, \"BOOTSTRAP.md\"))\n } catch {\n // Best-effort deletion\n }\n }\n\n return result\n}\n\n/**\n * Build context string from bootstrap files.\n * Returns empty string if no files found.\n */\nexport function buildBootstrapContext(files: BootstrapFiles): string {\n const sections: string[] = []\n\n if (files.identity) {\n sections.push(`[Identity]\\n${files.identity}`)\n }\n\n if (files.soul) {\n sections.push(`[Personality & Boundaries]\\n${files.soul}`)\n }\n\n // AGENTS.md is intentionally NOT injected into AgentX's --append-system-prompt\n // anymore. It's loaded natively by Claude Code via `@AGENTS.md` in the\n // workspace's CLAUDE.md (generated by workspace-setup.ts for new workspaces;\n // added to existing workspaces by the 2026-04-24 distribution). Injecting it\n // here on top of the native CLAUDE.md path would double the bytes. Keeping\n // the load in BootstrapFiles for diagnostic/listing purposes only.\n\n if (files.user) {\n sections.push(`[User Profile]\\n${files.user}`)\n }\n\n if (files.bootstrap) {\n sections.push(`[First-Run Instructions — one time only]\\n${files.bootstrap}`)\n }\n\n if (sections.length === 0) return \"\"\n\n return sections.join(\"\\n\\n\")\n}\n\n/**\n * Check which bootstrap files exist in a workspace (for status/diagnostics).\n */\nexport function listBootstrapFiles(workspace: string): string[] {\n return BOOTSTRAP_FILE_NAMES.filter((name) =>\n existsSync(resolve(workspace, name))\n )\n}\n\n/**\n * List available soul profiles in a workspace.\n * Returns profile names (e.g. [\"finance\", \"legal\", \"creative\"]).\n */\nexport function listSoulProfiles(workspace: string): string[] {\n try {\n return readdirSync(workspace)\n .filter(f => f.startsWith(\"SOUL.\") && f.endsWith(\".md\") && f !== \"SOUL.md\")\n .map(f => f.slice(5, -3)) // \"SOUL.finance.md\" → \"finance\"\n } catch {\n return []\n }\n}\n\n/**\n * Generate a standard AGENTS.md for a new agent workspace.\n * Follows the agents.md community convention (https://agents.md/).\n * Readable by Claude Code, Codex, Cursor, Amp, Gemini CLI, etc.\n */\nexport function generateAgentsMd(agent: {\n name: string\n id: string\n role?: string\n workspace: string\n tier?: string\n}): string {\n return `# ${agent.name}\n\n> Agent ID: \\`${agent.id}\\` | Tier: ${agent.tier || \"claude-code\"}\n\n## Role\n\n${agent.role || \"AI agent managed by AgentX orchestrator.\"}\n\n## Setup\n\nThis workspace is managed by AgentX. The agent runs via:\n\\`\\`\\`bash\n# Direct execution\nagentx daemon send ${agent.id} \"your task here\"\n\n# Or via any connected channel (Telegram, WhatsApp, GitLab)\n\\`\\`\\`\n\n## Code Style\n\n- Follow existing patterns in the codebase\n- Use the language and framework conventions already present\n- Keep changes minimal and focused\n\n## Testing\n\nRun tests before committing:\n\\`\\`\\`bash\nnpm test # or the project's test command\n\\`\\`\\`\n\n## PR Guidelines\n\n- One logical change per commit\n- Reference issue numbers when applicable\n- Keep PR descriptions concise\n\n## AgentX Integration\n\nThis agent is part of an AgentX mesh. It can:\n- Receive tasks from messaging channels (Telegram, WhatsApp, Discord)\n- Respond to GitLab @mentions on issues and MRs\n- Delegate to other agents by mentioning their handles\n- Send cross-channel messages via the /send API\n- Access its wiki knowledge base for context\n`\n}\n\n/**\n * Detect a /soul command in a message.\n * Returns the requested profile name, or null if no /soul command found.\n * \"/soul finance\" → \"finance\"\n * \"/soul\" or \"/soul default\" → \"default\" (reset to SOUL.md)\n */\nexport function detectSoulSwitch(message: string): string | null {\n const match = message.match(/\\/soul\\s+(\\w+)/i)\n if (match) return match[1].toLowerCase()\n if (/\\/soul\\s*$/i.test(message)) return \"default\"\n return null\n}\n","import { execFile } from \"child_process\"\nimport { existsSync } from \"fs\"\nimport { resolve } from \"path\"\nimport type { AgentDef } from \"@/daemon/config\"\nimport type { McpServerMap } from \"./agent-mcp\"\n\n// --- CodeGraph integration: per-agent semantic code-graph index ---\n//\n// CodeGraph (https://github.com/colbymchenry/codegraph) is a local\n// tree-sitter → SQLite knowledge graph exposed to Claude Code / Codex via\n// MCP. Opt-in per agent with `codegraph: true` on the agent's config.\n//\n// This module owns three responsibilities:\n// 1. `effectiveMcpConfig(def)` — synthesize the codegraph MCP server\n// entry into the agent's MCP map. Used by the daemon's\n// installAgentMcpConfig pass so the workspace's .mcp.json picks\n// up `codegraph serve --mcp` automatically.\n// 2. `bootstrapCodegraphIndexes(agents, log)` — at daemon boot, fire\n// off `codegraph init --index --quiet` in the background for any\n// opted-in workspace whose `.codegraph/` is missing. Throttled to\n// 2 parallel jobs so a large fleet doesn't thrash the host.\n// Returns immediately; the indexes finish on their own.\n// 3. Export the constant tool/CLI names that workspace-setup needs\n// to keep CLAUDE.md and settings.json in sync.\n\n/** MCP tool names exposed by `codegraph serve --mcp`. Used to extend the\n * per-workspace `.claude/settings.json` permissions.allow so claude\n * doesn't prompt for permission on every call. Keep in sync with the\n * upstream tool surface — additions are harmless, removals leave a\n * stale allow entry (also harmless). */\nexport const CODEGRAPH_TOOLS = [\n \"mcp__codegraph__codegraph_search\",\n \"mcp__codegraph__codegraph_context\",\n \"mcp__codegraph__codegraph_callers\",\n \"mcp__codegraph__codegraph_callees\",\n \"mcp__codegraph__codegraph_impact\",\n \"mcp__codegraph__codegraph_node\",\n \"mcp__codegraph__codegraph_status\",\n \"mcp__codegraph__codegraph_files\",\n] as const\n\n/** MCP server stanza we inject into `.mcp.json` for opted-in agents. */\nexport const CODEGRAPH_MCP_SERVER: { command: string; args: string[] } = {\n command: \"codegraph\",\n args: [\"serve\", \"--mcp\"],\n}\n\n/** Markdown block appended to managed CLAUDE.md when codegraph is on.\n * Tells the agent to prefer codegraph_* over grep, and to always spawn\n * an Explore subagent for codegraph_explore so the large source-dump\n * doesn't bloat the main session context. Mirrors the upstream-\n * recommended wording from the README's \"Global Instructions\" block. */\nexport function codegraphClaudeMdSection(): string {\n return [\n \"## CodeGraph\",\n \"\",\n \"This workspace has CodeGraph initialized — a semantic code-knowledge-graph indexed via tree-sitter. Use it instead of grep/find/Read for exploration.\",\n \"\",\n \"**ALWAYS spawn an Explore subagent for `codegraph_explore` / `codegraph_context`** — those tools return large source sections that would otherwise bloat the main session. Include this in the Explore prompt:\",\n \"\",\n \"> Use `codegraph_explore` as your PRIMARY tool — one call returns full source from all relevant files. Do not re-Read files codegraph_explore already returned. Fall back to grep/glob/Read only if codegraph returned no results.\",\n \"\",\n \"**In the main session, use these lightweight codegraph tools directly:**\",\n \"\",\n \"| Tool | Use for |\",\n \"|---|---|\",\n \"| `codegraph_search` | Find symbols by name across the codebase |\",\n \"| `codegraph_callers` / `codegraph_callees` | Trace call flow |\",\n \"| `codegraph_impact` | Check what's affected before editing a symbol |\",\n \"| `codegraph_node` | Get a single symbol's details |\",\n \"| `codegraph_files` | Indexed file structure (faster than ls) |\",\n \"| `codegraph_status` | Index health |\",\n \"\",\n ].join(\"\\n\")\n}\n\n/** Return the MCP server map an agent should expose to .mcp.json,\n * layering codegraph on top of the operator-declared `def.mcp` when\n * `def.codegraph === true`. Operator-declared entries win on key\n * collision (operator can override by declaring their own\n * `mcp.codegraph` block with different args). */\nexport function effectiveMcpConfig(def: AgentDef): McpServerMap {\n const base: McpServerMap = ((def as any).mcp ?? {}) as McpServerMap\n if (!def.codegraph) return base\n if (base.codegraph) return base\n return { ...base, codegraph: { command: CODEGRAPH_MCP_SERVER.command, args: [...CODEGRAPH_MCP_SERVER.args] } }\n}\n\nconst INDEX_DIR = \".codegraph\"\nconst INIT_TIMEOUT_MS = 10 * 60 * 1000 // 10 min — Swift Compiler benchmark indexed 25k files in ~4 min\nconst MAX_PARALLEL = 2\n\n/** Spawn `codegraph init --index --quiet` for one workspace. Returns the\n * duration in ms on success, throws on failure. Caller decides whether\n * to surface the error. */\nfunction indexWorkspace(workspace: string): Promise<number> {\n const started = Date.now()\n return new Promise<number>((res, rej) => {\n execFile(\n \"codegraph\",\n [\"init\", \"--index\", \"--quiet\", workspace],\n { timeout: INIT_TIMEOUT_MS, maxBuffer: 4 * 1024 * 1024 },\n (err) => {\n if (err) rej(err)\n else res(Date.now() - started)\n },\n )\n })\n}\n\n/** Boot-time helper: kick off `codegraph init --index` for every\n * opted-in workspace whose `.codegraph/` is missing. Fire-and-forget —\n * the returned promise resolves once all background jobs settle, but\n * callers (daemon start) don't need to await it. Indexing happens\n * while the daemon is already serving traffic; cold dispatches before\n * the index lands gracefully fall through to grep (the MCP server\n * returns an empty result, and CLAUDE.md tells the agent to fall back).\n *\n * Throttled to MAX_PARALLEL concurrent jobs so a fleet boot doesn't\n * saturate CPU/disk. */\nexport async function bootstrapCodegraphIndexes(\n agents: Record<string, AgentDef>,\n log: (...args: unknown[]) => void = console.error,\n): Promise<void> {\n const pending: Array<{ agentId: string; workspace: string }> = []\n for (const [agentId, def] of Object.entries(agents)) {\n if (!def.codegraph) continue\n if (def.tier !== \"claude-code\" && def.tier !== \"codex-cli\") continue\n if (!existsSync(def.workspace)) continue\n if (existsSync(resolve(def.workspace, INDEX_DIR))) continue\n pending.push({ agentId, workspace: def.workspace })\n }\n\n if (pending.length === 0) return\n\n log(`codegraph: indexing ${pending.length} workspace(s) in background (max ${MAX_PARALLEL} parallel)`)\n\n let i = 0\n const runners: Promise<void>[] = []\n for (let slot = 0; slot < Math.min(MAX_PARALLEL, pending.length); slot++) {\n runners.push((async () => {\n while (true) {\n const idx = i++\n if (idx >= pending.length) return\n const { agentId, workspace } = pending[idx]\n try {\n const ms = await indexWorkspace(workspace)\n log(` codegraph: indexed ${agentId} in ${(ms / 1000).toFixed(1)}s`)\n } catch (err: any) {\n // codegraph binary missing surfaces as ENOENT — recoverable hint\n const hint = err?.code === \"ENOENT\"\n ? \" (codegraph CLI not on PATH; install with `npm i -g @colbymchenry/codegraph`)\"\n : \"\"\n log(` codegraph: ${agentId} index failed: ${err?.message ?? err}${hint}`)\n }\n }\n })())\n }\n await Promise.allSettled(runners)\n}\n"],"mappings":"AAAA,OAAS,cAAAA,EAAY,aAAAC,EAAW,iBAAAC,EAAe,gBAAAC,MAAoB,KACnE,OAAS,WAAAC,MAAe,OACxB,OAAS,cAAAC,MAAkB,SCF3B,OAAS,gBAAAC,EAAc,cAAAC,EAAY,cAAAC,EAAY,eAAAC,OAAmB,KAClE,OAAS,WAAAC,MAAe,OAuCjB,SAASC,GAAmBC,EAAmBC,EAAsC,CAC1F,IAAMC,EAAyB,CAAC,EAE1BC,EAAWC,GAAyC,CACxD,IAAMC,EAAWC,EAAQN,EAAWI,CAAQ,EAC5C,GAAKG,EAAWF,CAAQ,EACxB,GAAI,CAEF,OADgBG,EAAaH,EAAU,OAAO,EAAE,KAAK,GACnC,MACpB,MAAE,CACA,MACF,CACF,EAGA,GAAIJ,EAAa,CACf,IAAMQ,EAAcN,EAAQ,QAAQF,MAAgB,EAChDQ,GACFP,EAAO,KAAOO,EACdP,EAAO,YAAcD,GAGrBC,EAAO,KAAOC,EAAQ,SAAS,OAGjCD,EAAO,KAAOC,EAAQ,SAAS,EASjC,GANAD,EAAO,SAAWC,EAAQ,aAAa,EACvCD,EAAO,KAAOC,EAAQ,SAAS,EAC/BD,EAAO,OAASC,EAAQ,WAAW,EACnCD,EAAO,UAAYC,EAAQ,cAAc,EAGrCD,EAAO,UACT,GAAI,CACFQ,EAAWJ,EAAQN,EAAW,cAAc,CAAC,CAC/C,MAAE,CAEF,CAGF,OAAOE,CACT,CAMO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c,KAAK,UAAUnB,EAAU,KAAM,CAAC,CAAC,EACnEuB,CACT,MAAE,CACA,MAAO,EACT,CACF,CAKO,SAASS,GACdC,EACAjD,EAAqB,QACrBsB,EAAoC,QAAQ,MACtC,CACN,IAAI4B,EAAe,EACfC,EAAe,EACfC,EAAe,EACnB,OAAW,CAACC,EAAI/D,CAAG,IAAK,OAAO,QAAQ2D,CAAM,EAAG,CAC9C,GAAI3D,EAAI,OAAS,eAAiBA,EAAI,OAAS,YAAa,SAC5D,IAAMgE,EAASjC,EAAegC,EAAI/D,EAAKU,EAAYsB,CAAG,EACtD4B,GAAgBI,EAAO,QAAQ,OAG3BhE,EAAI,OAAS,eAAiB+C,EAAc/C,EAAI,UAAW,CAC7D,IAAK,CAAE,qCAAsC,GAAI,CACnD,CAAC,GACC6D,IAKE7D,EAAI,OAAS,eAAiBsD,EAAgBtD,EAAI,UAAW+D,EAAIrD,CAAU,GAC7EoD,IAGAF,EAAe,GACjB5B,EAAI,oBAAoB4B,2CAAsD,EAE5EC,EAAe,GACjB7B,EAAI,oBAAoB6B,iDAA4D,EAElFC,EAAe,GACjB9B,EAAI,eAAe8B,kEAA6E,CAEpG","names":["existsSync","mkdirSync","writeFileSync","readFileSync","resolve","createHash","readFileSync","existsSync","unlinkSync","readdirSync","resolve","loadBootstrapFiles","workspace","soulProfile","result","tryLoad","filename","filePath","resolve","existsSync","readFileSync","profileSoul","unlinkSync","buildBootstrapContext","files","sections","generateAgentsMd","agent","detectSoulSwitch","message","match","execFile","existsSync","resolve","CODEGRAPH_TOOLS","CODEGRAPH_MCP_SERVER","codegraphClaudeMdSection","effectiveMcpConfig","def","base","INDEX_DIR","INIT_TIMEOUT_MS","MAX_PARALLEL","indexWorkspace","workspace","started","res","rej","err","bootstrapCodegraphIndexes","agents","log","pending","agentId","i","runners","slot","idx","ms","hint","MANAGED_MARKER_PREFIX","MANAGED_MARKER_SUFFIX","managedHashInputs","def","createHash","buildManagedMarker","readManagedHash","content","firstLine","detectRole","agentId","text","generateClaudeMd","daemonPort","role","lines","existsSync","resolve","codegraphClaudeMdSection","GUARDRAIL_DENY","guardHookCommand","guardPreToolUseHooks","command","isGuardEntry","entry","h","generateSettings","settings","perms","existing","CODEGRAPH_TOOLS","hooks","generateRules","rules","setupWorkspace","log","created","skipped","workspace","writeIfMissing","path","mkdirSync","writeFileSync","writeManaged","expectedHash","readFileSync","existingHash","generateAgentsMd","settingsPath","rule","patchSettings","patches","changed","key","value","subKey","subValue","patchGuardrails","deny","desired","e","setupAllWorkspaces","agents","totalCreated","totalPatched","totalGuarded","id","result"]}
|