agentix-cli 0.205.0 → 0.206.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{App-JDW5V4HT.js → App-IEUOKINQ.js} +2 -2
- package/dist/{ChatApp-SNM2PORO.js → ChatApp-CCDBG6YZ.js} +2 -2
- package/dist/{absorb-eval-WDAV4AI2.js → absorb-eval-IIF7CY3Q.js} +2 -2
- package/dist/{adapter-C47BTKT6.js → adapter-LTHULD3D.js} +2 -2
- package/dist/{agent-EVMKJXJO.js → agent-TZ3GGNS5.js} +2 -2
- package/dist/{board-dashboard-VSDTP4Y7.js → board-dashboard-JS6OJDH6.js} +365 -351
- package/dist/board-dashboard-JS6OJDH6.js.map +1 -0
- package/dist/{chunk-AK46ORUI.js → chunk-37EABHYL.js} +2 -2
- package/dist/chunk-3AHYZLGE.js +115 -0
- package/dist/chunk-3AHYZLGE.js.map +1 -0
- package/dist/{chunk-PQUK6XEW.js → chunk-6U34GZ7U.js} +2 -2
- package/dist/{chunk-GWBFEVLO.js → chunk-6ZVVAGTR.js} +2 -2
- package/dist/{chunk-IU63JGY3.js → chunk-7GD5GTWC.js} +2 -2
- package/dist/{chunk-X6SXZDTY.js → chunk-7JHB3X5N.js} +16 -16
- package/dist/chunk-7JHB3X5N.js.map +1 -0
- package/dist/{chunk-SKCOIP5R.js → chunk-A2K6C6W3.js} +3 -3
- package/dist/{chunk-OLKYIKAZ.js → chunk-B35GIWMR.js} +2 -2
- package/dist/{chunk-DUCYRNCT.js → chunk-CARVBJB7.js} +20 -20
- package/dist/chunk-CARVBJB7.js.map +1 -0
- package/dist/{chunk-KRHVM26D.js → chunk-E2MW5OCE.js} +2 -2
- package/dist/{chunk-WJMYBRM5.js → chunk-FXA2WIIP.js} +2 -2
- package/dist/{chunk-KWZ6NMXZ.js → chunk-GCBFLU64.js} +10 -10
- package/dist/{chunk-S6YN3IBM.js → chunk-GJOKXP5D.js} +2 -2
- package/dist/{chunk-PQX2VJUA.js → chunk-I4753XPP.js} +45 -45
- package/dist/chunk-I4753XPP.js.map +1 -0
- package/dist/{chunk-2VSK6FAR.js → chunk-I74PTSUQ.js} +2 -2
- package/dist/{chunk-ERVJLPS4.js → chunk-JDU4CXGC.js} +2 -2
- package/dist/{chunk-DV42WUMD.js → chunk-K435U2FC.js} +2 -2
- package/dist/chunk-KEUW6YLL.js +2 -0
- package/dist/{chunk-VJ5HC63R.js.map → chunk-KEUW6YLL.js.map} +1 -1
- package/dist/{chunk-DOO4MUTS.js → chunk-KXMC7Z5X.js} +2 -2
- package/dist/chunk-LY4G7PCW.js +2 -0
- package/dist/chunk-LY4G7PCW.js.map +1 -0
- package/dist/{chunk-5STGF4MI.js → chunk-M37WJANA.js} +88 -88
- package/dist/chunk-M37WJANA.js.map +1 -0
- package/dist/{chunk-CXFVIDJV.js → chunk-R6XJWFMC.js} +2 -2
- package/dist/{chunk-245IOYDJ.js → chunk-RPL2P7EP.js} +2 -2
- package/dist/{chunk-UGRMFQAG.js → chunk-RRLQTU3X.js} +2 -2
- package/dist/{chunk-ZUHUCSGT.js → chunk-TLRTJV2U.js} +311 -303
- package/dist/chunk-TLRTJV2U.js.map +1 -0
- package/dist/{chunk-JT5PIBCM.js → chunk-U3OJO7B7.js} +2 -2
- package/dist/{chunk-RXX4MYFL.js → chunk-UN7D7HWU.js} +2 -2
- package/dist/{chunk-2P3SHT5I.js → chunk-VALKXSXZ.js} +2 -2
- package/dist/{chunk-CZVCT5ZV.js → chunk-WI7J22NL.js} +2 -2
- package/dist/{chunk-PTZNM2JU.js → chunk-WTCMJZW3.js} +2 -2
- package/dist/chunk-XL7UWG36.js +12 -0
- package/dist/chunk-XL7UWG36.js.map +1 -0
- package/dist/{chunk-IDGEDPRJ.js → chunk-XTIPWYW5.js} +2 -2
- package/dist/{chunk-QASIUKZJ.js → chunk-Z6J3RTYJ.js} +2 -2
- package/dist/{chunk-PW3WG6JT.js → chunk-ZOK6VMEP.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-WN7YI7DE.js → client-NPC2JAWL.js} +2 -2
- package/dist/{config-QUXKGIZX.js → config-TIMTRSFH.js} +2 -2
- package/dist/config-mutate-V3DRUCK4.js +2 -0
- package/dist/{config-mutator-OLLQR3ZD.js → config-mutator-HOYYIPNW.js} +2 -2
- package/dist/{contributions-LL7B4BP3.js → contributions-TYVRQG7F.js} +2 -2
- package/dist/doctor-TNQ4Q2OS.js +2 -0
- package/dist/{facts-ALJBF7IA.js → facts-XGZWX6CR.js} +2 -2
- package/dist/{follow-up-tool-I2HTKMP4.js → follow-up-tool-3P2YCRBL.js} +2 -2
- package/dist/{grants-5GIY7347.js → grants-TWDH3Z4K.js} +2 -2
- package/dist/hub-GVTRKPAU.js +2 -0
- package/dist/index.d.ts +107 -45
- package/dist/index.js +1 -1
- package/dist/{org-tool-JCGGJJU6.js → org-tool-EKO7GCPL.js} +2 -2
- package/dist/{program-7VNYZPRO.js → program-Y55FFHIJ.js} +86 -86
- package/dist/{promote-NSPUPPHB.js → promote-JYYV44FK.js} +2 -2
- package/dist/{query-VW63IHDI.js → query-PUWWCFET.js} +2 -2
- package/dist/{query-settings-RS7DJI4H.js → query-settings-IJPG3N6D.js} +2 -2
- package/dist/registry-QJGTPSK2.js +2 -0
- package/dist/{request-planner-HZWQIRZO.js → request-planner-HHJXCWCG.js} +2 -2
- package/dist/{review-candidates-2TXOUASP.js → review-candidates-XZUQELL5.js} +2 -2
- package/dist/rotation-memo-store-ZH6254YR.js +2 -0
- package/dist/rotation-memo-store-ZH6254YR.js.map +1 -0
- package/dist/{routing-ZV4VSZDV.js → routing-HWZHJ4LZ.js} +2 -2
- package/dist/schedule-tool-7W5CRUN4.js +2 -0
- package/dist/{scheduler-SAID6RKQ.js → scheduler-WG3KXJIH.js} +2 -2
- package/dist/{seat-XHBWBSTS.js → seat-5BOBWKBX.js} +2 -2
- package/dist/{select-QUCTTAH3.js → select-FIHHBFNR.js} +2 -2
- package/dist/{set-enabled-CGMXLFC6.js → set-enabled-K7OM7PSO.js} +2 -2
- package/dist/{sprint-tool-SWRYSX3Q.js → sprint-tool-O6TTSWJN.js} +2 -2
- package/dist/{tool-DA25L4ND.js → tool-4KVS2JWC.js} +2 -2
- package/dist/{tool-ELGOVIM5.js → tool-BYU6EZKM.js} +2 -2
- package/dist/{tool-MMH2JNP7.js → tool-HTUSCV22.js} +2 -2
- package/dist/{tool-6G63ZQW4.js → tool-HVCLZGYE.js} +2 -2
- package/dist/{wiki-4ZL4QXA7.js → wiki-ZMEMGR7R.js} +2 -2
- package/dist/wiki-enrich-QZHQV7VZ.js +2 -0
- package/dist/workspace-setup-GTSXWYU4.js +2 -0
- package/package.json +1 -1
- package/dist/board-dashboard-VSDTP4Y7.js.map +0 -1
- package/dist/chunk-36X7D4JA.js +0 -2
- package/dist/chunk-36X7D4JA.js.map +0 -1
- package/dist/chunk-5STGF4MI.js.map +0 -1
- package/dist/chunk-DUCYRNCT.js.map +0 -1
- package/dist/chunk-IFNXMUEG.js +0 -115
- package/dist/chunk-IFNXMUEG.js.map +0 -1
- package/dist/chunk-PQX2VJUA.js.map +0 -1
- package/dist/chunk-VJ5HC63R.js +0 -2
- package/dist/chunk-WDGATQV3.js +0 -12
- package/dist/chunk-WDGATQV3.js.map +0 -1
- package/dist/chunk-X6SXZDTY.js.map +0 -1
- package/dist/chunk-ZUHUCSGT.js.map +0 -1
- package/dist/config-mutate-HJH24ITC.js +0 -2
- package/dist/doctor-WJ5H7QQW.js +0 -2
- package/dist/hub-7ASBN76I.js +0 -2
- package/dist/registry-6KREAROB.js +0 -2
- package/dist/rotation-memo-store-WMDI7NND.js +0 -2
- package/dist/rotation-memo-store-WMDI7NND.js.map +0 -1
- package/dist/schedule-tool-D357NLXS.js +0 -2
- package/dist/wiki-enrich-N5MUKDVW.js +0 -2
- package/dist/workspace-setup-QXFJRNSK.js +0 -2
- /package/dist/{App-JDW5V4HT.js.map → App-IEUOKINQ.js.map} +0 -0
- /package/dist/{ChatApp-SNM2PORO.js.map → ChatApp-CCDBG6YZ.js.map} +0 -0
- /package/dist/{absorb-eval-WDAV4AI2.js.map → absorb-eval-IIF7CY3Q.js.map} +0 -0
- /package/dist/{adapter-C47BTKT6.js.map → adapter-LTHULD3D.js.map} +0 -0
- /package/dist/{agent-EVMKJXJO.js.map → agent-TZ3GGNS5.js.map} +0 -0
- /package/dist/{chunk-AK46ORUI.js.map → chunk-37EABHYL.js.map} +0 -0
- /package/dist/{chunk-PQUK6XEW.js.map → chunk-6U34GZ7U.js.map} +0 -0
- /package/dist/{chunk-GWBFEVLO.js.map → chunk-6ZVVAGTR.js.map} +0 -0
- /package/dist/{chunk-IU63JGY3.js.map → chunk-7GD5GTWC.js.map} +0 -0
- /package/dist/{chunk-SKCOIP5R.js.map → chunk-A2K6C6W3.js.map} +0 -0
- /package/dist/{chunk-OLKYIKAZ.js.map → chunk-B35GIWMR.js.map} +0 -0
- /package/dist/{chunk-KRHVM26D.js.map → chunk-E2MW5OCE.js.map} +0 -0
- /package/dist/{chunk-WJMYBRM5.js.map → chunk-FXA2WIIP.js.map} +0 -0
- /package/dist/{chunk-KWZ6NMXZ.js.map → chunk-GCBFLU64.js.map} +0 -0
- /package/dist/{chunk-S6YN3IBM.js.map → chunk-GJOKXP5D.js.map} +0 -0
- /package/dist/{chunk-2VSK6FAR.js.map → chunk-I74PTSUQ.js.map} +0 -0
- /package/dist/{chunk-ERVJLPS4.js.map → chunk-JDU4CXGC.js.map} +0 -0
- /package/dist/{chunk-DV42WUMD.js.map → chunk-K435U2FC.js.map} +0 -0
- /package/dist/{chunk-DOO4MUTS.js.map → chunk-KXMC7Z5X.js.map} +0 -0
- /package/dist/{chunk-CXFVIDJV.js.map → chunk-R6XJWFMC.js.map} +0 -0
- /package/dist/{chunk-245IOYDJ.js.map → chunk-RPL2P7EP.js.map} +0 -0
- /package/dist/{chunk-UGRMFQAG.js.map → chunk-RRLQTU3X.js.map} +0 -0
- /package/dist/{chunk-JT5PIBCM.js.map → chunk-U3OJO7B7.js.map} +0 -0
- /package/dist/{chunk-RXX4MYFL.js.map → chunk-UN7D7HWU.js.map} +0 -0
- /package/dist/{chunk-2P3SHT5I.js.map → chunk-VALKXSXZ.js.map} +0 -0
- /package/dist/{chunk-CZVCT5ZV.js.map → chunk-WI7J22NL.js.map} +0 -0
- /package/dist/{chunk-PTZNM2JU.js.map → chunk-WTCMJZW3.js.map} +0 -0
- /package/dist/{chunk-IDGEDPRJ.js.map → chunk-XTIPWYW5.js.map} +0 -0
- /package/dist/{chunk-QASIUKZJ.js.map → chunk-Z6J3RTYJ.js.map} +0 -0
- /package/dist/{chunk-PW3WG6JT.js.map → chunk-ZOK6VMEP.js.map} +0 -0
- /package/dist/{client-WN7YI7DE.js.map → client-NPC2JAWL.js.map} +0 -0
- /package/dist/{config-QUXKGIZX.js.map → config-TIMTRSFH.js.map} +0 -0
- /package/dist/{config-mutate-HJH24ITC.js.map → config-mutate-V3DRUCK4.js.map} +0 -0
- /package/dist/{config-mutator-OLLQR3ZD.js.map → config-mutator-HOYYIPNW.js.map} +0 -0
- /package/dist/{contributions-LL7B4BP3.js.map → contributions-TYVRQG7F.js.map} +0 -0
- /package/dist/{doctor-WJ5H7QQW.js.map → doctor-TNQ4Q2OS.js.map} +0 -0
- /package/dist/{facts-ALJBF7IA.js.map → facts-XGZWX6CR.js.map} +0 -0
- /package/dist/{follow-up-tool-I2HTKMP4.js.map → follow-up-tool-3P2YCRBL.js.map} +0 -0
- /package/dist/{grants-5GIY7347.js.map → grants-TWDH3Z4K.js.map} +0 -0
- /package/dist/{hub-7ASBN76I.js.map → hub-GVTRKPAU.js.map} +0 -0
- /package/dist/{org-tool-JCGGJJU6.js.map → org-tool-EKO7GCPL.js.map} +0 -0
- /package/dist/{program-7VNYZPRO.js.map → program-Y55FFHIJ.js.map} +0 -0
- /package/dist/{promote-NSPUPPHB.js.map → promote-JYYV44FK.js.map} +0 -0
- /package/dist/{query-VW63IHDI.js.map → query-PUWWCFET.js.map} +0 -0
- /package/dist/{query-settings-RS7DJI4H.js.map → query-settings-IJPG3N6D.js.map} +0 -0
- /package/dist/{registry-6KREAROB.js.map → registry-QJGTPSK2.js.map} +0 -0
- /package/dist/{request-planner-HZWQIRZO.js.map → request-planner-HHJXCWCG.js.map} +0 -0
- /package/dist/{review-candidates-2TXOUASP.js.map → review-candidates-XZUQELL5.js.map} +0 -0
- /package/dist/{routing-ZV4VSZDV.js.map → routing-HWZHJ4LZ.js.map} +0 -0
- /package/dist/{schedule-tool-D357NLXS.js.map → schedule-tool-7W5CRUN4.js.map} +0 -0
- /package/dist/{scheduler-SAID6RKQ.js.map → scheduler-WG3KXJIH.js.map} +0 -0
- /package/dist/{seat-XHBWBSTS.js.map → seat-5BOBWKBX.js.map} +0 -0
- /package/dist/{select-QUCTTAH3.js.map → select-FIHHBFNR.js.map} +0 -0
- /package/dist/{set-enabled-CGMXLFC6.js.map → set-enabled-K7OM7PSO.js.map} +0 -0
- /package/dist/{sprint-tool-SWRYSX3Q.js.map → sprint-tool-O6TTSWJN.js.map} +0 -0
- /package/dist/{tool-DA25L4ND.js.map → tool-4KVS2JWC.js.map} +0 -0
- /package/dist/{tool-ELGOVIM5.js.map → tool-BYU6EZKM.js.map} +0 -0
- /package/dist/{tool-MMH2JNP7.js.map → tool-HTUSCV22.js.map} +0 -0
- /package/dist/{tool-6G63ZQW4.js.map → tool-HVCLZGYE.js.map} +0 -0
- /package/dist/{wiki-4ZL4QXA7.js.map → wiki-ZMEMGR7R.js.map} +0 -0
- /package/dist/{wiki-enrich-N5MUKDVW.js.map → wiki-enrich-QZHQV7VZ.js.map} +0 -0
- /package/dist/{workspace-setup-QXFJRNSK.js.map → workspace-setup-GTSXWYU4.js.map} +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{a as q}from"./chunk-2LJZHKTY.js";import{a as D,b as F}from"./chunk-2YDG5CSS.js";import{A as S,G as H,I as b,K as _,N as M,q as A,x as W}from"./chunk-
|
|
1
|
+
import{a as q}from"./chunk-2LJZHKTY.js";import{a as D,b as F}from"./chunk-2YDG5CSS.js";import{A as S,G as H,I as b,K as _,N as M,q as A,x as W}from"./chunk-6ZVVAGTR.js";import{c as P}from"./chunk-LY4G7PCW.js";import{a as L}from"./chunk-OSH2PEBH.js";import{Hb as T,Rb as K,mb as E}from"./chunk-CARVBJB7.js";K();import{Command as V}from"commander";import f from"chalk";import{execFileSync as m}from"child_process";import{accessSync as z,constants as G,existsSync as k,readFileSync as $,readdirSync as N,statSync as Q}from"fs";import{join as B,resolve as w}from"path";import{homedir as Y}from"os";import{createRequire as ee}from"module";var C='run agentx notify "Hello" --title "Test"';function U(t,n){return t==="windows"?{fallback:"Windows PowerShell, and show its name",settings:"Open Settings \u203A System \u203A Notifications, turn notifications on, then turn on AgentX Helper and its banners.",missingFix:`${A(n)} Then ${C}.`,updateFix:`${A(n).replace(/^Put /,"Put a newer ")}`,osName:"Windows"}:{fallback:"Script Editor and show its icon",settings:"Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.",missingFix:`Run agentx desktop install, then ${C} and click Allow.`,updateFix:"Run agentx desktop install to update it.",osName:"macOS"}}async function X(t={}){let n=t.platform??process.platform,e=t.helper===void 0?H():t.helper,i=b({},{platform:n,io:{capture:t.run,helper:e}}),s=i.banner;if(!s)return{state:"unsupported",message:"Desktop banners are only shown on macOS and Windows."};let o=U(i.os,n),a=await s.status();return a==="missing"?{state:"missing",message:`AgentX Helper is not installed, so banners come from ${o.fallback}.`,fix:o.missingFix}:a==="outdated"?{state:"outdated",path:e,message:"AgentX Helper is too old to report whether it may notify.",fix:o.updateFix}:a==="not-asked"?{state:"not-asked",path:e,message:`${o.osName} has not asked yet whether AgentX Helper may notify; banners come from ${o.fallback} until it does.`,fix:`${C[0].toUpperCase()}${C.slice(1)} and click Allow when ${o.osName} asks.`}:a==="not-allowed"?{state:"not-allowed",path:e,message:`${o.osName} does not allow AgentX Helper to notify, so banners come from ${o.fallback}.`,fix:o.settings}:a==="hidden"?{state:"hidden",path:e,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:o.settings}:{state:"ready",path:e,message:"AgentX Helper posts banners with the AgentX icon."}}async function te(t={}){let n=[];await re(n),ae(n);let e=le(n);return e&&ce(n,e),e&&fe(n,e),e&&he(n,e),e&&me(n,e),e&&ue(n,e),e&&n.push(...ge(e)),e&&we(n,e),e&&await ne(n,e),e&&oe(n,e),e&&await ie(n,e),e&&se(n,e),t.running!==!1&&e&&await ve(n,e),{checks:n,summary:J(n)}}var qe=new V().name("doctor").description("pre-flight health check: Node, config, credentials, daemon").option("--no-running","skip the live daemon probe").option("--json","emit machine-readable JSON (stable shape for CI)").action(async t=>{let{checks:n,summary:e}=await te({running:t.running!==!1});t.json?process.stdout.write(JSON.stringify({checks:n,summary:e},null,2)+`
|
|
2
2
|
`):ke(n),process.exit(e.errors>0?1:0)});async function ne(t,n,e=X){if(!_(n.notifications?.local).banner)return;let i=await e();i.state!=="unsupported"&&t.push({severity:i.state==="ready"?"ok":"warn",group:"Notifications",title:i.message,detail:i.path,fix:i.fix})}async function ie(t,n,e){let i;try{i=await(e??b(n)).describe()}catch(o){t.push({severity:"warn",group:"Native",title:"Native apps: could not be read",detail:o?.message??String(o)});return}let s=["tasks","notes","banner","sound","focus"].filter(o=>i[o]);t.push({severity:"ok",group:"Native",title:i.os==="none"?"Native apps: none on this machine":`Native apps (${i.os}): ${s.join(", ")||"nothing available"}`,detail:i.problems.join(" ")||void 0})}function se(t,n,e=process.cwd(),i=b(n)){let s=n.native?.mirror;if(!s?.enabled)return;if(!i.tasks){t.push({severity:"warn",group:"Native",title:"Reminders mirror is on, but this machine has no task app",detail:"native.mirror.enabled is set; nothing is mirrored here.",fix:"Turn it on on the machine that holds the owner's cards (the Mac), or set native.mirror.enabled to false here."});return}let o=M(e),a=Object.values(o.items),l=a.filter(g=>g.state==="open").length,p=a.filter(g=>g.state==="failed").length;t.push({severity:o.lastError||p?"warn":"ok",group:"Native",title:`Reminders mirror: ${l} open in "${s.list}"${p?`, ${p} could not be added`:""}`,detail:o.lastError?`Last error ${o.lastError.at}: ${o.lastError.message}`:void 0,fix:o.lastError?"Run remindctl status, and allow Reminders for the app that runs the daemon in System Settings \u203A Privacy & Security \u203A Reminders.":void 0})}function oe(t,n,e=process.platform,i=s=>{try{return z(s,G.X_OK),!0}catch{return!1}}){let s=n.reminders;if(!s?.enabled)return;if(e!=="darwin"){t.push({severity:"warn",group:"Reminders",title:"Reminders hand-back unavailable on this machine",detail:"reminders.enabled is set, but Apple Reminders exists only on macOS. The daemon starts without it.",fix:"Set reminders.enabled to false here, or enable it on the Mac node instead."});return}let o=s.command||"remindctl",a=o.includes("/")?i(o)?o:null:S(o,process.env.PATH||"",i);t.push(a?{severity:"ok",group:"Reminders",title:`Watching ${(s.lists||[]).join(", ")} for due reminders`,detail:a}:{severity:"fail",group:"Reminders",title:`${o} not found`,detail:"The daemon reads Apple Reminders through remindctl.",fix:"brew install steipete/tap/remindctl, or set reminders.command to its full path."})}async function re(t){let n=L(process.versions.node);t.push({severity:n?"ok":"fail",group:"Environment",title:`Node.js ${process.versions.node}`,detail:n?void 0:"AgentX requires Node 22.19 or newer, up to Node 26.",fix:n?void 0:"Install Node 22 (nvm install 22 && nvm use 22)"});let e=l=>{try{return m(process.platform==="win32"?"where":"which",[l],{encoding:"utf-8"}).trim().split(`
|
|
3
3
|
`)[0]}catch{return null}},i=e("npm");t.push({severity:i?"ok":"fail",group:"Environment",title:i?"npm on PATH":"npm not found",detail:i||void 0});let s=e("claude");if(s){let l;try{l=m("claude",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`claude CLI ${l||"installed"}`,detail:s})}else t.push({severity:"warn",group:"Environment",title:"claude CLI not on PATH",detail:"Only required for agents on the claude-code tier.",fix:"See https://docs.anthropic.com/en/docs/claude-code"});let o=e("codex");if(o){let l;try{l=m("codex",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`codex CLI ${l||"installed"}`,detail:o})}else t.push({severity:"warn",group:"Environment",title:"codex CLI not on PATH",detail:"Only required for agents on the codex-cli tier.",fix:"Install with `npm i -g @openai/codex`."});let a=e("opencode");if(a){let l;try{l=m("opencode",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`opencode CLI ${l||"installed"}`,detail:a})}else t.push({severity:"warn",group:"Environment",title:"opencode CLI not on PATH",detail:"Only required for agents on the opencode tier.",fix:"Install from https://opencode.ai/docs/."});try{ee(import.meta.url)("better-sqlite3"),t.push({severity:"ok",group:"Environment",title:`better-sqlite3 loads for Node ${process.version}`,detail:`NODE_MODULE_VERSION ${process.versions.modules}`})}catch(l){t.push({severity:"fail",group:"Environment",title:"better-sqlite3 native binding does not load",detail:l?.message??String(l),fix:`Run "pnpm rebuild better-sqlite3" with the same Node used by the daemon (${process.version}, modules ${process.versions.modules}).`})}}function ae(t){if(process.platform!=="darwin")return;let n=B(Y(),"Library/LaunchAgents"),e=[];try{e=N(n).filter(s=>/agentx\.voice.*\.plist$/.test(s))}catch{return}let i=s=>{try{return z(s,G.X_OK),!0}catch{return!1}};for(let s of e){let o=W($(B(n,s),"utf-8")),a=S("ffmpeg",o,i);t.push(a?{severity:"ok",group:"Desktop",title:"ffmpeg reachable by the desktop app",detail:`${a} (${s})`}:{severity:"warn",group:"Desktop",title:"ffmpeg not reachable by the desktop app",detail:`Local Whisper transcription fails without it. ${s} sets PATH to ${o}.`,fix:"Install ffmpeg (brew install ffmpeg), then rerun agentx desktop install."})}}function le(t){let n=w(process.cwd(),"agentx.json");if(!k(n))return t.push({severity:"fail",group:"Config",title:"agentx.json not found",detail:`Looked in ${n}`,fix:"Run `agentx setup` to create one via the web wizard."}),null;let e;try{e=JSON.parse($(n,"utf-8"))}catch(a){return t.push({severity:"fail",group:"Config",title:"agentx.json is not valid JSON",detail:a.message}),null}try{T(n),t.push({severity:"ok",group:"Config",title:`agentx.json valid (${Object.keys(e.agents||{}).length} agents, ${Object.keys(e.crons||{}).length} schedules)`})}catch(a){t.push({severity:"fail",group:"Config",title:"agentx.json failed schema validation",detail:a.message,fix:"Open /admin \u2192 Advanced tab to edit and re-save."})}let i=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="claude-code");i.length>0&&((()=>{try{return m(process.platform==="win32"?"where":"which",["claude"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${i.length} agent(s) use claude-code tier but claude CLI is missing`,detail:i.map(([l])=>l).join(", "),fix:"Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) or switch these agents to tier=sdk."}));let s=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="codex-cli");s.length>0&&((()=>{try{return m(process.platform==="win32"?"where":"which",["codex"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${s.length} agent(s) use codex-cli tier but codex CLI is missing`,detail:s.map(([l])=>l).join(", "),fix:"Install Codex CLI with `npm i -g @openai/codex` or switch these agents to tier=claude-code."}));let o=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="opencode");return o.length>0&&((()=>{try{return m(process.platform==="win32"?"where":"which",["opencode"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${o.length} agent(s) use opencode tier but OpenCode CLI is missing`,detail:o.map(([l])=>l).join(", "),fix:"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier."})),e}function ce(t,n){let e=new Set;if(j(n,e),e.size===0){t.push({severity:"ok",group:"Secrets",title:"No ${VAR} references in agentx.json"});return}let i=R(),s=[],o=[];for(let a of e){let l=process.env[a]??i[a];l===void 0?s.push(a):(!l.trim()||/^["']?\s*["']?$/.test(l))&&o.push(a)}s.length===0&&o.length===0?t.push({severity:"ok",group:"Secrets",title:`${e.size} env reference(s) resolved`}):(s.length>0&&t.push({severity:"fail",group:"Secrets",title:`${s.length} env var(s) referenced in agentx.json but missing`,detail:s.join(", "),fix:`Add to .env \u2014 e.g. ${s[0]}=<value>`}),o.length>0&&t.push({severity:"warn",group:"Secrets",title:`${o.length} env var(s) set but empty`,detail:o.join(", ")}))}function R(){let t=w(process.cwd(),".env"),n={};if(k(t))for(let e of $(t,"utf-8").split(/\r?\n/)){let i=e.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);i&&(n[i[1]]=i[2])}return n}function de(t,n){let e="With a shared token this node cannot tell which peer is calling. For example, closing an approval card forwarded from that peer is refused, and its stop/resume signals are judged as the owner's.",i="Give this pair a token of its own: set the same new value as mesh.peers[].token here and on the peer.",s=[];for(let o of t){let a=(o.token??"").trim();a?n&&a===n&&s.push({severity:"warn",group:"Mesh",title:`mesh peer "${o.name}" uses this node's own MESH_TOKEN`,detail:e,fix:i}):s.push({severity:"warn",group:"Mesh",title:`mesh peer "${o.name}" has no token; calls to it use the shared MESH_TOKEN`,detail:e,fix:i})}return t.length>0&&s.length===0&&s.push({severity:"ok",group:"Mesh",title:`${t.length} mesh peer(s), each with a token of its own`}),s}function ue(t,n){t.push(...pe(n))}function pe(t,n=process.env,e=R()){let i=a=>(n[a]||e[a]||"").trim(),s=a=>typeof a=="string"?a.replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,(l,p)=>i(p)):void 0,o=(t.mesh?.peers??[]).filter(a=>typeof a?.name=="string").map(a=>({name:a.name,token:s(a.token)}));return de(o,i("MESH_TOKEN")||void 0)}function ge(t,n=process.env,e=R()){let i=[],s=0;for(let[o,a]of Object.entries(t.agents||{}))for(let[l,p]of Object.entries(a?.mcp||{})){let g=P(p??{});if(g.length===0)continue;s++;let y=g.filter(r=>!(n[r]||e[r]||"").trim());y.length>0&&i.push({severity:"fail",group:"Secrets",title:`MCP server "${l}" of ${o}: header variable(s) not set`,detail:y.join(", "),fix:`Add to .env \u2014 e.g. ${y[0]}=<value>, then restart the daemon`})}return s>0&&i.length===0&&i.push({severity:"ok",group:"Secrets",title:`${s} MCP server(s) with header variables, all set`}),i}function j(t,n){if(typeof t=="string")for(let e of t.matchAll(/\$\{([A-Z_][A-Z0-9_]*)\}/g))n.add(e[1]);else if(Array.isArray(t))for(let e of t)j(e,n);else if(t&&typeof t=="object")for(let e of Object.values(t))j(e,n)}function fe(t,n){let e=[];for(let[i,s]of Object.entries(n.agents||{})){if(!s.workspace)continue;let o=s.workspace.startsWith("/")?s.workspace:w(process.cwd(),s.workspace);try{Q(o).isDirectory()||e.push(`${i}: ${o} (exists but not a directory)`)}catch{e.push(`${i}: ${o}`)}}e.length===0?t.push({severity:"ok",group:"Workspaces",title:"All agent workspace folders exist"}):t.push({severity:"warn",group:"Workspaces",title:`${e.length} agent workspace(s) missing`,detail:e.join(`
|
|
4
4
|
`),fix:"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them."})}function he(t,n){let e=/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g,i=[];for(let[s,o]of Object.entries(n.agents||{})){if(!o.workspace)continue;let a=o.workspace.startsWith("/")?o.workspace:w(process.cwd(),o.workspace);for(let l of["settings.json","settings.local.json"]){let p=w(a,".claude",l);if(!k(p))continue;let g;try{g=JSON.parse($(p,"utf-8"))}catch(u){i.push({severity:"fail",agent:s,msg:`${l}: JSON parse error \u2014 ${u.message}`});continue}let y=g.env||{};for(let[u,h]of Object.entries(y)){if(typeof h!="string")continue;let c=h.match(e);c&&i.push({severity:"fail",agent:s,msg:`${l} env.${u} contains unexpanded ${[...new Set(c)].join(",")} \u2014 Claude Code does NOT expand \${VAR} in settings.json (use a fully-literal value)`})}let r=y.PATH;if(typeof r=="string"){let u=r.split(":").filter(Boolean);u.includes("/usr/bin")||i.push({severity:"fail",agent:s,msg:`${l} env.PATH missing /usr/bin \u2014 cat/head/sh/which will fail`}),u.includes("/bin")||i.push({severity:"fail",agent:s,msg:`${l} env.PATH missing /bin \u2014 ls/cp/mv will fail`})}let d=g.permissions;if(d&&typeof d=="object"&&"allow"in d){let u=d.allow,h=d.deny;Array.isArray(u)&&u.length===0&&Array.isArray(h)&&h.length>0&&i.push({severity:"warn",agent:s,msg:`${l} permissions.allow is explicitly [] with ${h.length} deny rules \u2014 agent may be locked out (omit the key to use defaults instead)`})}}}if(i.length===0){t.push({severity:"ok",group:"Workspace settings",title:`All ${Object.keys(n.agents||{}).length} agent .claude/settings.json files clean`});return}for(let s of i)t.push({severity:s.severity,group:"Workspace settings",title:`${s.agent}: ${s.msg}`,fix:s.severity==="fail"?"Edit .claude/settings.json \u2014 replace ${VAR} with the literal value or omit the key to inherit.":"Either remove the empty allow list or populate it."})}function me(t,n){let e=n.webhooks??[],i=[],s=w(process.cwd(),n.workflows?.dir||".agentx/workflows"),o=new Set;try{if(k(s))for(let r of N(s))r.endsWith(".json")&&!r.startsWith("_")&&!r.endsWith(".disabled.json")&&o.add(r.replace(/\.json$/,""))}catch{}let a=new Set(["github","gitlab"]);for(let r of e){if(!r.enabled||!a.has(r.source))continue;!(r.triggers&&Object.keys(r.triggers).length>0)&&!r.defaultWorkflow&&i.push({severity:"warn",title:`webhook "${r.id}" (${r.source} -> ${r.agentId}) has no triggers map; every event-type collapses to the bound agent`,fix:'Add a triggers map: { "issues.opened": "wf-id", "pull_request.synchronize": "wf-id" } \u2014 or set defaultWorkflow.'})}for(let r of e)if(!(!r.enabled||!r.triggers)){for(let[d,u]of Object.entries(r.triggers))o.size>0&&!o.has(u)&&i.push({severity:"fail",title:`webhook "${r.id}".triggers["${d}"] -> "${u}" \u2014 no such workflow under ${n.workflows?.dir||".agentx/workflows"}`,fix:"Create the workflow file or fix the id in agentx.json"});r.defaultWorkflow&&o.size>0&&!o.has(r.defaultWorkflow)&&i.push({severity:"fail",title:`webhook "${r.id}".defaultWorkflow -> "${r.defaultWorkflow}" \u2014 no such workflow`,fix:"Create the workflow file or fix the id in agentx.json"})}try{if(k(s)){for(let r of N(s))if(!(!r.endsWith(".json")||r.startsWith("_")||r.endsWith(".disabled.json")))try{let d=JSON.parse($(w(s,r),"utf-8"));d?.status==="active"&&d?.state==="quarantined"&&i.push({severity:"warn",title:`workflow "${d.id??r}" is status=active but state=quarantined \u2014 it looks live but will never dispatch`,fix:'Resolve the conflict the detector flagged, then set state back to "active" (or set status to "review" while parked).'})}catch{}}}catch{}let l=new Set((n.mesh?.peers??[]).map(r=>r.name));for(let r of e)!r.enabled||!r.node||l.has(r.node)||i.push({severity:"fail",title:`webhook "${r.id}" routes to mesh peer "${r.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or remove the node field on the webhook."});let p=new Map;for(let r of e){if(!r.enabled)continue;let d=`${r.source}:${r.agentId}`,u=p.get(d);u?i.push({severity:"warn",title:`webhook entries "${u}" and "${r.id}" both enabled for ${r.source} -> ${r.agentId}; only the first is dispatched`,fix:"Disable one entry, or merge their triggers maps into a single entry."}):p.set(d,r.id)}let g=new Set(Object.keys(n.agents??{}));for(let r of n.channels?.gitlab?.agentMappings??[])if(r?.agentId){if(r.node){l.has(r.node)||i.push({severity:"fail",title:`gitlab.agentMappings entry agentId="${r.agentId}" routes to mesh peer "${r.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or drop the node field on the mapping."});continue}g.has(r.agentId)||i.push({severity:"warn",title:`gitlab.agentMappings entry agentId="${r.agentId}" \u2014 no such agent in agents.* (and no node field, so it's not a cross-mesh route)`,fix:'Add the agent to agents.*, set node:"<peer>" if the agent lives remotely, or remove the mapping.'})}for(let[r,d]of Object.entries(n.channels?.telegram?.accounts??{}))d.agentBinding?g.has(d.agentBinding)||i.push({severity:"fail",title:`telegram account "${r}".agentBinding -> "${d.agentBinding}" \u2014 no such agent in agents.*`,fix:"Fix the agentBinding or define the agent in agents.*."}):i.push({severity:"fail",title:`telegram account "${r}" has no agentBinding; every DM to this bot will drop`,fix:"Set agentBinding to a valid agent id."});let y=new Set(["telegram-bot","whatsapp","slack-bot","discord-bot","gitlab-user","github-user","gmail","hotmail","smtp","hubspot","salesforce","pipedrive","odoo","trello","linear","asana","jira","notion","stripe","sentry","vercel","twilio","custom",...E,...Object.keys(D)]);for(let[r,d]of Object.entries(n.agents??{})){let u=d.integrations??[];if(!u.length)continue;let h=new Set;for(let c of u){let O=`${c.kind}::${c.label}`;h.has(O)&&i.push({severity:"warn",title:`agents.${r}.integrations: duplicate (${c.kind}, ${c.label})`,fix:"Remove the duplicate or rename one. (kind, label) must be unique per agent."}),h.add(O),y.has(c.kind)||i.push({severity:"warn",title:`agents.${r}.integrations: unknown kind "${c.kind}" on integration "${c.label}"`,fix:'Use a canonical kind from INTEGRATION_KINDS, or "custom" for ad-hoc services.'});let Z=c.credentials||{};for(let[x,v]of Object.entries(Z))typeof v=="string"&&/^[A-Z][A-Z0-9_]*$/.test(v)&&!process.env[v]&&i.push({severity:"warn",title:`agents.${r}.integrations[${c.kind}/${c.label}].${x} -> $${v} but env var is unset (in this shell)`,fix:`Set ${v} on the daemon environment. The daemon's process.env is what matters; this warning fires from your local shell.`});let I=c.enabled===!1?null:F(c.kind);if(I){let x=q(r,c,I);for(let v of x.problems)/env var .* is unset/.test(v)||i.push({severity:"warn",title:`agents.${r}.integrations[${c.kind}/${c.label}]: ${v}`,fix:x.connected?`Run agentx agent integrations status ${r} for details.`:`Run agentx agent integrations connect ${r} ${c.kind}${c.label!==c.kind?` --label "${c.label}"`:""}.`})}}}if(i.length===0){t.push({severity:"ok",group:"Routing",title:`${e.length} webhook(s), ${Object.keys(n.channels?.telegram?.accounts??{}).length} telegram account(s) \u2014 all routing references resolve`});return}for(let r of i)t.push({severity:r.severity,group:"Routing",title:r.title,fix:r.fix})}function ye(t){return typeof t?.canMeasure!="boolean"?null:t.canMeasure?{severity:"ok",group:"Runtime",title:"Daemon finds ffmpeg to measure phone recordings"}:{severity:"warn",group:"Runtime",title:t.allowUnmeasured?"Daemon can't find ffmpeg: phone recordings go unmeasured (voice.allowUnmeasured)":"Daemon can't find ffmpeg: phone voice input is refused",fix:"Install ffmpeg (brew install ffmpeg / sudo apt install ffmpeg), or set AGENTX_FFMPEG in the service's environment. The daemon's PATH is shorter than your shell's."}}async function ve(t,n){let e=n.dashboard?.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800",i={};n.dashboard?.token&&(i.Authorization=`Bearer ${n.dashboard.token}`);try{let s=new AbortController,o=setTimeout(()=>s.abort(),2e3),a=await fetch(e+"/health",{headers:i,signal:s.signal});if(clearTimeout(o),!a.ok){t.push({severity:"warn",group:"Runtime",title:`Daemon responded ${a.status}`,detail:e});return}let l=await a.json();t.push({severity:"ok",group:"Runtime",title:`Daemon healthy \u2014 ${l.agents?.length??0} agents live, uptime ${Math.round((l.uptime??0)/60)}m`,detail:e});let p=ye(l.voice);p&&t.push(p)}catch{t.push({severity:"warn",group:"Runtime",title:"Daemon not reachable (not running?)",detail:e,fix:"Run `agentx daemon start`. Skip this check with `agentx doctor --no-running`."})}}function we(t,n){let e=Object.entries(n.agents||{}).filter(([,s])=>s?.codegraph===!0&&(s.tier==="claude-code"||s.tier==="codex-cli"));if(e.length===0)return;let i=null;try{i=m(process.platform==="win32"?"where":"which",["codegraph"],{encoding:"utf-8"}).trim().split(`
|
|
5
5
|
`)[0]||null}catch{i=null}if(i){let s;try{s=m("codegraph",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"CodeGraph",title:`codegraph CLI ${s||"installed"}`,detail:i})}else t.push({severity:"fail",group:"CodeGraph",title:"codegraph CLI not on PATH",detail:`${e.length} agent(s) have codegraph:true but the binary isn't available.`,fix:"Install with `npm i -g @colbymchenry/codegraph`."});for(let[s,o]of e){if(!o.workspace||!k(o.workspace)){t.push({severity:"warn",group:"CodeGraph",title:`${s}: workspace missing`,detail:`Workspace path ${o.workspace} does not exist \u2014 codegraph will skip this agent.`});continue}let a=w(o.workspace,".codegraph","codegraph.db");k(a)?t.push({severity:"ok",group:"CodeGraph",title:`${s}: index present`,detail:a}):t.push({severity:"warn",group:"CodeGraph",title:`${s}: index not built yet`,detail:".codegraph/ missing \u2014 daemon will background-index this workspace on next boot.",fix:`Run \`codegraph init --index ${o.workspace}\` to build it now.`})}}function J(t){return{errors:t.filter(n=>n.severity==="fail").length,warnings:t.filter(n=>n.severity==="warn").length,ok:t.filter(n=>n.severity==="ok").length}}function ke(t){console.log(),console.log(f.bold(" agentx doctor")),console.log();let n=new Map;for(let i of t)n.has(i.group)||n.set(i.group,[]),n.get(i.group).push(i);for(let[i,s]of n){console.log(f.bold(" "+i));for(let o of s){let a=o.severity==="ok"?f.green("\u2713"):o.severity==="warn"?f.yellow("!"):f.red("\u2717");console.log(` ${a} ${o.title}`),o.detail&&console.log(f.dim(" "+o.detail.replace(/\n/g,`
|
|
6
6
|
`))),o.fix&&console.log(f.dim(" \u2192 "+o.fix))}console.log()}let e=J(t);e.errors>0?console.log(f.red.bold(` ${e.errors} error${e.errors===1?"":"s"}`)+(e.warnings?f.yellow(`, ${e.warnings} warning${e.warnings===1?"":"s"}`):"")+`. Fix the error${e.errors===1?"":"s"} and rerun.`):e.warnings>0?console.log(f.yellow.bold(` ${e.warnings} warning${e.warnings===1?"":"s"}.`)+f.dim(" Review but not blocking.")):console.log(f.green.bold(` All checks passed (${e.ok}).`)),console.log()}export{X as a,te as b,qe as c,ne as d,ie as e,se as f,oe as g,de as h,pe as i,ge as j,ye as k};
|
|
7
|
-
//# sourceMappingURL=chunk-
|
|
7
|
+
//# sourceMappingURL=chunk-37EABHYL.js.map
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import{q as G,r as A,t as F}from"./chunk-XL7UWG36.js";import{f as N,g as j}from"./chunk-LY4G7PCW.js";import{existsSync as y,mkdirSync as ae,writeFileSync as S,readFileSync as R}from"fs";import{resolve as m}from"path";import{createHash as Ke}from"crypto";import{readFileSync as ge,existsSync as me,unlinkSync as fe,readdirSync as pt}from"fs";import{resolve as H}from"path";function ht(t,n){let r={},s=e=>{let o=H(t,e);if(me(o))try{return ge(o,"utf-8").trim()||void 0}catch{return}};if(n){let e=s(`SOUL.${n}.md`);e?(r.soul=e,r.soulProfile=n):r.soul=s("SOUL.md")}else r.soul=s("SOUL.md");if(r.identity=s("IDENTITY.md"),r.user=s("USER.md"),r.agents=s("AGENTS.md"),r.bootstrap=s("BOOTSTRAP.md"),r.bootstrap)try{fe(H(t,"BOOTSTRAP.md"))}catch{}return r}function gt(t){let n=[];return t.identity&&n.push(`[Identity]
|
|
2
|
+
${t.identity}`),t.soul&&n.push(`[Personality & Boundaries]
|
|
3
|
+
${t.soul}`),t.user&&n.push(`[User Profile]
|
|
4
|
+
${t.user}`),t.bootstrap&&n.push(`[First-Run Instructions \u2014 one time only]
|
|
5
|
+
${t.bootstrap}`),n.length===0?"":n.join(`
|
|
6
|
+
|
|
7
|
+
`)}function W(t){return`# ${t.name}
|
|
8
|
+
|
|
9
|
+
> Agent ID: \`${t.id}\` | Tier: ${t.tier||"claude-code"}
|
|
10
|
+
|
|
11
|
+
## Role
|
|
12
|
+
|
|
13
|
+
${t.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 ${t.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 mt(t){let n=t.match(/\/soul\s+(\w+)/i);return n?n[1].toLowerCase():/\/soul\s*$/i.test(t)?"default":null}import{execFile as ye}from"child_process";import{existsSync as q}from"fs";import{resolve as be}from"path";var K=["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"],J={command:"codegraph",args:["serve","--mcp"]};function Y(){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 xt(t){let n=t.mcp??{};return!t.codegraph||n.codegraph?n:{...n,codegraph:{command:J.command,args:[...J.args]}}}var ke=".codegraph",xe=10*60*1e3,X=2;function we(t){let n=Date.now();return new Promise((r,s)=>{ye("codegraph",["init","--index","--quiet",t],{timeout:xe,maxBuffer:4*1024*1024},e=>{e?s(e):r(Date.now()-n)})})}async function wt(t,n=console.error){let r=[];for(let[o,i]of Object.entries(t))i.codegraph&&(i.tier!=="claude-code"&&i.tier!=="codex-cli"||q(i.workspace)&&(q(be(i.workspace,ke))||r.push({agentId:o,workspace:i.workspace})));if(r.length===0)return;n(`codegraph: indexing ${r.length} workspace(s) in background (max ${X} parallel)`);let s=0,e=[];for(let o=0;o<Math.min(X,r.length);o++)e.push((async()=>{for(;;){let i=s++;if(i>=r.length)return;let{agentId:a,workspace:u}=r[i];try{let l=await we(u);n(` codegraph: indexed ${a} in ${(l/1e3).toFixed(1)}s`)}catch(l){let d=l?.code==="ENOENT"?" (codegraph CLI not on PATH; install with `npm i -g @colbymchenry/codegraph`)":"";n(` codegraph: ${a} index failed: ${l?.message??l}${d}`)}}})());await Promise.allSettled(e)}import{appendFileSync as $e,existsSync as Q,mkdirSync as Z,readdirSync as V,realpathSync as _e,statSync as Se,unlinkSync as Re,utimesSync as Oe,writeFileSync as Ae}from"fs";import{createHash as ee}from"crypto";import{resolve as $,sep as Pe}from"path";var D="/observation/pack";function Ot(t=process.cwd()){return $(t,".agentx/observations")}function te(t,n){return $(t,encodeURIComponent(n).replace(/\./g,"%2E"))}function ne(t){return t==="bypassPermissions"}function z(t){try{return _e(t)}catch{return $(t)}}function Te(t,n){return n.some(r=>{try{return new RegExp(`^(?:${r})$`).test(t)}catch{return r===t}})}var ve=2e3;function P(t,n,r){return t.subarray(n,r).toString("utf-8").replace(/^�+|�+$/g,"")}function Ee(t,n,r){let s=Buffer.from(t,"utf-8"),e=P(s,0,r.headBytes),o=r.tailBytes>0?P(s,s.length-r.tailBytes,s.length):"",i=s.length-r.headBytes-r.tailBytes,a=t.split(`
|
|
54
|
+
`).length,l=s.length/a>ve?"Its lines are very long, so read it by byte range (for example head -c or tail -c, or jq for JSON) for the part you need.":"Read that file with offset and limit (line numbers), or grep it, for the part you need. Do not cat it whole: that is packed again.";return[`[ObservationPack: this result is ${s.length} bytes (${a} lines). Only its first ${r.headBytes} and last ${r.tailBytes} bytes are shown.`,`The exact original is saved at ${n}`,`${l} Do not guess at what is not shown.]`,e,`[... ${i} bytes not shown ...]`,o].join(`
|
|
55
|
+
`)}function De(t){let n=t;return!!n&&typeof n=="object"&&n.type==="text"&&typeof n.file?.content=="string"}function E(t){if(t==="")return 0;let n=1;for(let r=t.indexOf(`
|
|
56
|
+
`);r!==-1;r=t.indexOf(`
|
|
57
|
+
`,r+1))n++;return t.endsWith(`
|
|
58
|
+
`)&&n--,n}function Ce(t,n,r){let s=Buffer.from(t,"utf-8"),e=E(t),o=P(s,0,r.headBytes),i=o.lastIndexOf(`
|
|
59
|
+
`);o=i===-1?o:o.slice(0,i+1);let a=r.tailBytes>0?P(s,s.length-r.tailBytes,s.length):"",u=a.indexOf(`
|
|
60
|
+
`);a=u===-1?a:a.slice(u+1);let l=i===-1?0:E(o),d=u===-1?0:E(a),c=n.startLine,p=c+e-1,h=c+l,g=p-d,f=s.length-Buffer.byteLength(o,"utf-8")-Buffer.byteLength(a,"utf-8"),x=typeof n.totalLines=="number"&&n.totalLines>e?` (${n.totalLines} lines in all)`:"",O=h===g?`Line ${h} (${f} bytes) is`:`Lines ${h} to ${g} (${f} bytes) are`,w=[l===0&&o!==""?c:null,d===0&&a!==""?p:null].filter(v=>v!==null),de=w.length===0?"":w.length===1||w[0]===w[1]?` (line ${w[0]} only in part)`:` (lines ${w[0]} and ${w[1]} only in part)`,he=d>0?` Lines ${g+1} to ${p} follow; the numbers beside them are not the file's.`:"";return[o,`[ObservationPack: this read is ${s.length} bytes, lines ${c} to ${p} of ${n.path}${x}.`,`${O} not shown${de}.${he}`,"Read the file again with offset and limit for the lines you need, or Grep it. Do not guess at what is not shown.]",a].filter(v=>v!=="").join(`
|
|
61
|
+
`)}function Be(t,n){let r=ee("sha256").update(n).digest("hex"),s=$(t,`${r}.txt`);if(Q(s)){let e=new Date;Oe(s,e,e)}else Z(t,{recursive:!0,mode:448}),Ae(s,n,{mode:384});return{sha:r,path:s}}function Me(t,n,r){if(!n.enabled)return null;let s=t.tool_name;if(!s||!Te(s,n.tools))return null;let e=t.tool_input?.file_path;if(typeof e=="string"&&z(e).startsWith(z(r)+Pe)||n.limitBytes<=n.headBytes+n.tailBytes)return null;if(s==="Read"){let a=t.tool_response;if(!De(a))return null;let u=a.file.content,l=Buffer.byteLength(u,"utf-8");if(l<=n.limitBytes)return null;let d=typeof e=="string"?e:a.file.filePath??"the file you read",c=t.tool_input?.offset,p=typeof a.file.startLine=="number"&&a.file.startLine>=1?a.file.startLine:typeof c=="number"&&c>=1?c:1,h=Ce(u,{path:d,startLine:p,totalLines:a.file.totalLines},n),g=ee("sha256").update(u).digest("hex");return{updated:{...a,file:{...a.file,content:h}},packs:[{sha:g,path:d,bytes:l,keptBytes:Buffer.byteLength(h,"utf-8")}]}}let o=[],i=a=>{if(typeof a=="string"){let u=Buffer.byteLength(a,"utf-8");if(u<=n.limitBytes)return a;let{sha:l,path:d}=Be(r,a),c=Ee(a,d,n);return o.push({sha:l,path:d,bytes:u,keptBytes:Buffer.byteLength(c,"utf-8")}),c}if(Array.isArray(a))return a.map(i);if(a&&typeof a=="object"){let u=a;return u.type==="image"||u.type==="audio"||u.isImage===!0||typeof u.persistedOutputPath=="string"?a:Object.fromEntries(Object.entries(u).map(([l,d])=>[l,l==="blob"?d:i(d)]))}return a};try{let a=i(t.tool_response);return o.length>0?{updated:a,packs:o}:null}catch{return null}}function At(t,n,r){let s=t&&typeof t=="object"?Me(t,n,r.dir):null;if(!s)return"";try{let e=new Date().toISOString(),o=s.packs.map(i=>JSON.stringify({at:e,agent:r.agentId,session:t.session_id,tool:t.tool_name,sha:i.sha,bytes:i.bytes,keptBytes:i.keptBytes}));Z(r.dir,{recursive:!0,mode:448}),$e($(r.dir,"index.jsonl"),o.join(`
|
|
62
|
+
`)+`
|
|
63
|
+
`,{mode:384})}catch{}return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",updatedToolOutput:s.updated}})}function Pt(t,n,r=Date.now()){if(n<=0||!Q(t))return 0;let s=r-n*864e5,e=0;for(let o of V(t,{withFileTypes:!0})){if(!o.isDirectory())continue;let i=$(t,o.name);for(let a of V(i)){if(!a.endsWith(".txt"))continue;let u=$(i,a);try{Se(u).mtimeMs<s&&(Re(u),e++)}catch{}}}return e}var B=180,Ie=600;function Le(t){let n;try{n=JSON.stringify(t??{})}catch{n=String(t)}n=n.replace(/\s+/g," ").trim();let r="Input: ",s=Ie-r.length;return r+(n.length>s?n.slice(0,s-1)+"\u2026":n)}function se(t,n){return t.length>n?t.slice(0,n-1)+"\u2026":t}function b(t,n,r){return`[agentx-mcp] "${n}" on MCP server "${t}" writes data and was not run: ${r}. Do not retry it or work around it. Say what you were trying to do and wait for instructions.`}function C(t,n,r){return t.verdict==="yes"?null:b(n,r,`the owner said no on card ${t.id}`)}async function Dt(t,n,r,s){let e=j(t,r);if(!e)return null;let{server:o,tool:i}=e,a=s.now??Date.now,u=s.sleep??(p=>new Promise(h=>setTimeout(h,p))),l=s.waitMs??B*1e3,d=s.pollMs??1e3,c=Math.max(1,Math.round(l/6e4));try{let p=a(),h=F(s.root,{title:se(`${s.agentId} wants to write with ${o}: ${i}`,120),ask:se(`Let ${s.agentId} run the "${i}" tool on ${o}? It changes data in that service.`,300),recommend:`Yes only if you asked for this. No, or no answer within ${c} min, and it does not run.`,context:Le(n),if_silent:"discard",expires:new Date(p+l).toISOString(),raised_by:s.agentId},{now:p,settings:s.settings,origin:{kind:"mcp-write",server:o,tool:i}});if(!h.ok)return b(o,i,`the confirmation card could not be raised (${h.error})`);let g=h.card.id;try{s.onCard?.(h.card)}catch{}for(;;){let f=A(s.root,g);if(!f)return b(o,i,"the confirmation card is gone");if(f.status==="decided")return C(f,o,i);if(f.status!=="pending")return b(o,i,`card ${g} was not answered in time`);if(a()-p>=l){let x=A(s.root,g);if(!x)return b(o,i,"the confirmation card is gone");if(x.status==="decided")return C(x,o,i);if(x.status!=="pending")return b(o,i,`card ${g} was not answered in time`);G(s.root,{...x,status:"expired",outcome:"discard",decided_by:"expiry",decided_at:new Date(a()).toISOString()});let O=A(s.root,g);return O?.status==="decided"?C(O,o,i):b(o,i,`card ${g} was not answered within ${c} min`)}await u(d)}}catch(p){return b(o,i,`the confirmation step failed (${p?.message??p})`)}}import{mkdirSync as Ue,renameSync as Ne,writeFileSync as je}from"fs";import{dirname as Ge,resolve as Fe}from"path";var He="AGENTX_GUARD_ERROR",I=75,We={connectS:1,maxTimeS:55,deadlineMs:3e3};function oe(t){return Fe(t,".agentx/bin/agentx-guard")}function It(t,n,r){let s=oe(t);Ue(Ge(s),{recursive:!0});let e=`#!/bin/sh
|
|
64
|
+
[ -f ${k(r)} ] || exit 127
|
|
65
|
+
exec ${k(n)} ${k(r)} "$@"
|
|
66
|
+
`,o=`${s}.${process.pid}.tmp`;return je(o,e,{mode:493}),Ne(o,s),s}function k(t){return`'${t.replace(/'/g,"'\\''")}'`}var _="[A-Za-z0-9_./~@:=-]+",M=`(start|restart|status)( +(-d|--detach|--when-idle|(-c|--config|--port)( +|=)${_}))*`,re="([0-9]+|\\$\\(id -u\\)|\\$UID)",qe=[`agentx +daemon +${M}`,`(node +)?(${_}/)?cli\\.js +daemon +${M}`,`npx +tsx +(${_}/)?cli\\.ts +daemon +${M}`,`launchctl +kickstart( +-k)? +gui/${re}/${_}`,`launchctl +(bootstrap|bootout) +gui/${re} +${_}`,`systemctl +--user +(start|restart|status) +${_}`,`sudo +systemctl +(start|restart|status) +${_}`].map(t=>`(${t})`).join("|");function Je(t){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t}})}var Xe="[agentx-guard] Refused: the AgentX guard could not check this call (the daemon is not answering and the local check failed). Only `agentx daemon start|restart|status` and the launchctl/systemctl forms that start the daemon run until it answers.";function ie(t){let n=t.budget??We,r=t.agentId?`?agent=${encodeURIComponent(t.agentId)}`:"",s=`http://127.0.0.1:${t.port}/guard/check${r}`,e=`guard check --rules-only --deadline-ms ${n.deadlineMs} --root ${k(t.root)}${t.agentId?` --agent ${k(t.agentId)}`:""}`,o=["p=$(cat)",`out=$(printf '%s' "$p" | curl -sf --connect-timeout ${n.connectS} --max-time ${n.maxTimeS} -H 'Content-Type: application/json' --data-binary @- '${s}' 2>/dev/null) && { printf '%s' "$out"; exit 0; }`,`out=$(printf '%s' "$p" | ${k(t.cliPath??oe(t.root))} ${e} 2>/dev/null) || out=$(printf '%s' "$p" | agentx ${e} 2>/dev/null)`,`[ $? -eq 0 ] && [ "$out" != ${He} ] && { printf '%s' "$out"; exit 0; }`];return t.required&&o.push('[ "$AGENTX_GUARD" = required ] || exit 0',`c=$(printf '%s' "$p" | grep -o '"command" *: *"[^"\\\\]*"')`,`if printf '%s' "$p" | grep -q '"tool_name" *: *"Bash"' && [ "$(printf '%s\\n' "$c" | grep -c .)" = 1 ] && printf '%s\\n' "$c" | sed 's/^"command" *: *"//; s/"$//; s/^ *//; s/ *$//' | grep -Eqx ${k(qe)}; then exit 0; fi`,`printf '%s' ${k(Je(Xe))}`),o.push("exit 0"),o.join(`
|
|
67
|
+
`)}var L="<!-- agentx-managed: hash=",U=" -->";function ce(t){return Ke("sha256").update(t.systemPrompt??"").update("\0").update(t.codegraph?"cg:1":"cg:0").digest("hex").slice(0,16)}function Ye(t){return`${L}${ce(t)}${U}`}function Ve(t){let n=t.split(`
|
|
68
|
+
`,1)[0]??"";return!n.startsWith(L)||!n.endsWith(U)?null:n.slice(L.length,n.length-U.length)}function ue(t,n){let r=`${t} ${n.systemPrompt||""} ${n.name}`.toLowerCase();return/cod(e|ing|er)|develop|engineer|program/.test(r)?"coding":/pm|project.?manag|product|scrum/.test(r)?"pm":/devops|deploy|infra|ops|sre|ci.?cd/.test(r)?"devops":/qa|test|quality|forensic/.test(r)?"qa":"general"}function ze(t,n,r){let s=ue(t,n),e=[];switch(e.push(Ye(n)),e.push(`# ${n.name}`),e.push(""),e.push("@AGENTS.md"),e.push(""),n.systemPrompt&&n.systemPrompt.trim().length>0&&(e.push("## Role"),e.push(""),e.push(n.systemPrompt.trimEnd()),e.push("")),e.push("## Commands"),e.push(""),y(m(n.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("```")):y(m(n.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(""),s){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:${r}/send \\`),e.push(' -H "Content-Type: application/json" \\'),e.push(` -d '{"channel":"telegram","chatId":"<id>","text":"<message>","agentId":"${t}"}'`),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":"${t}","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(""),n.codegraph&&e.push(Y()),e.join(`
|
|
69
|
+
`)}var T=["Bash(npx prisma migrate reset*)","Bash(prisma migrate reset*)","Bash(npx prisma db push*)","Bash(prisma db push*)","Bash(dropdb*)"];function Qe(t,n,r=process.cwd()){return ie({port:n,root:r,agentId:t,required:!0})}var le=B+15,Ze=le+15;function et(t,n){let r=`http://127.0.0.1:${n}/guard/check?agent=${encodeURIComponent(t)}`,s=JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"AgentX guard did not answer; tools of an MCP server with an allow list are refused until it does."}});return`out=$(curl -sf --max-time ${le} -H 'Content-Type: application/json' --data-binary @- '${r}' 2>/dev/null) && printf '%s' "$out" || printf '%s' '${s}'`}function pe(t,n,r){let s=Qe(t,n),e=[{matcher:"Bash",hooks:[{type:"command",command:s,timeout:I}]},{matcher:"Write|Edit",hooks:[{type:"command",command:s,timeout:I}]}],o=N(r);return o&&e.push({matcher:o,hooks:[{type:"command",command:et(t,n),timeout:Ze}]}),e}function tt(t){return Array.isArray(t?.hooks)&&t.hooks.some(n=>typeof n?.command=="string"&&(n.command.includes("/guard/check")||n.command.includes("guard check")))}function nt(t,n,r="19900"){let s={autoMemoryEnabled:!0,env:{CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS:"1"}};if(n.permissionMode==="bypassPermissions"?s.permissions={deny:[...T]}:n.permissionMode==="plan"?s.permissions={deny:[...T,"Bash(rm -rf *)","Bash(drop *)","Bash(DELETE *)"]}:s.permissions={deny:[...T,"Bash(rm -rf /)","Bash(> /dev/sda*)","Bash(mkfs*)"]},n.codegraph){let o=s.permissions||{},i=Array.isArray(o.allow)?o.allow:[];o.allow=[...new Set([...i,...K])],s.permissions=o}let e={};return e.PreToolUse=pe(t,r,n.mcp),e.Notification=[{matcher:"",hooks:[{type:"command",command:`echo "[${t}] notification: $(jq -r '.type // "unknown"')" >> /tmp/agentx-${t}.log`}]}],e.PostToolUse=[{matcher:"Bash",hooks:[{type:"command",command:`jq -r '.tool_input.command // empty' >> /tmp/agentx-${t}-commands.log`}]}],e.SessionStart=[{matcher:"compact",hooks:[{type:"command",command:`echo "Reminder: You are ${n.name} (${t}). Follow the conventions in CLAUDE.md."`}]}],s.hooks=e,s}var st=`# Code Quality
|
|
70
|
+
|
|
71
|
+
- No console.log in production code (use a logger)
|
|
72
|
+
- Handle errors explicitly \u2014 no empty catch blocks
|
|
73
|
+
- Keep files under 300 lines
|
|
74
|
+
- Extract repeated logic into shared utilities
|
|
75
|
+
`;function rt(t,n){let r=ue(t,n),s=[];switch(r){case"coding":s.push({name:"testing.md",content:`---
|
|
76
|
+
paths:
|
|
77
|
+
- "**/*.test.{ts,tsx,js,jsx}"
|
|
78
|
+
- "**/*.spec.{ts,tsx,js,jsx}"
|
|
79
|
+
- "test/**/*"
|
|
80
|
+
---
|
|
81
|
+
|
|
82
|
+
# Testing Rules
|
|
83
|
+
|
|
84
|
+
- Every new function should have a corresponding test
|
|
85
|
+
- Test both happy path and error cases
|
|
86
|
+
- Use descriptive test names that explain what's being tested
|
|
87
|
+
- Mock external dependencies, not internal modules
|
|
88
|
+
`}),s.push({name:"code-quality.md",content:`# Code Quality
|
|
89
|
+
|
|
90
|
+
- No console.log in production code (use a logger)
|
|
91
|
+
- Handle errors explicitly \u2014 no empty catch blocks
|
|
92
|
+
- Extract repeated logic into shared utilities
|
|
93
|
+
`,replaces:[st]});break;case"devops":s.push({name:"deployment-safety.md",content:`# Deployment Safety
|
|
94
|
+
|
|
95
|
+
- Always verify staging before production
|
|
96
|
+
- Check disk space and memory before deploying
|
|
97
|
+
- Never expose secrets in logs or commits
|
|
98
|
+
- Use rollback-safe deployment strategies
|
|
99
|
+
`});break;case"pm":s.push({name:"communication.md",content:`# Communication Rules
|
|
100
|
+
|
|
101
|
+
- Keep GitLab comments under 5 lines for the main message
|
|
102
|
+
- Use <details> for verbose output (logs, commands, steps)
|
|
103
|
+
- Reference issues with #IID, merge requests with !IID
|
|
104
|
+
- Never mention Telegram handles on GitLab
|
|
105
|
+
`});break;case"qa":s.push({name:"bug-reports.md",content:`# Bug Report Format
|
|
106
|
+
|
|
107
|
+
Always include:
|
|
108
|
+
1. Steps to reproduce
|
|
109
|
+
2. Expected behavior
|
|
110
|
+
3. Actual behavior
|
|
111
|
+
4. Environment (browser, OS, version)
|
|
112
|
+
5. Screenshots if applicable
|
|
113
|
+
`});break}return s}function ot(t,n,r="19900",s=console.error){let e=[],o=[],i=n.workspace;if(!y(i))return s(`Workspace not found: ${i}`),{created:e,skipped:o};if(n.tier!=="claude-code"&&n.tier!=="codex-cli")return{created:e,skipped:o};let a=(c,p)=>{y(c)?o.push(c):(ae(m(c,".."),{recursive:!0}),S(c,p),e.push(c))},u=(c,p,h)=>{if(!y(c)){ae(m(c,".."),{recursive:!0}),S(c,p),e.push(c);return}let g;try{g=R(c,"utf8")}catch{o.push(c);return}let f=Ve(g);if(f===null){o.push(c);return}if(f===h){o.push(c);return}S(c,p),e.push(`${c} (refreshed)`)};if(a(m(i,"AGENTS.md"),W({name:n.name,id:t,role:n.systemPrompt?.split(`
|
|
114
|
+
`)[0],workspace:i,tier:n.tier})),n.tier==="codex-cli")return e.length>0&&s(`[${t}] workspace setup: created ${e.length} file(s)`),{created:e,skipped:o};u(m(i,"CLAUDE.md"),ze(t,n,r),ce(n));let l=m(i,".claude/settings.json");a(l,JSON.stringify(nt(t,n,r),null,2));let d=rt(t,n);for(let c of d){let p=m(i,".claude/rules",c.name);c.replaces&&y(p)&&c.replaces.includes(R(p,"utf8"))?(S(p,c.content),e.push(p)):a(p,c.content)}return e.length>0&&s(`[${t}] workspace setup: created ${e.length} file(s)`),{created:e,skipped:o}}function it(t,n){let r=m(t,".claude/settings.json");if(!y(r))return!1;try{let s=JSON.parse(R(r,"utf-8")),e=!1;for(let[o,i]of Object.entries(n))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){s[o]||(s[o]={});for(let[a,u]of Object.entries(i))s[o][a]===void 0&&(s[o][a]=u,e=!0)}else s[o]===void 0&&(s[o]=i,e=!0);return e&&S(r,JSON.stringify(s,null,2)),e}catch{return!1}}function at(t,n,r="19900",s){let e=m(t,".claude/settings.json");if(!y(e))return!1;try{let o=JSON.parse(R(e,"utf-8")),i=!1,a=o.permissions??={},u=Array.isArray(a.deny)?a.deny:a.deny=[];for(let p of T)u.includes(p)||(u.push(p),i=!0);let l=o.hooks??={},c=[...Array.isArray(l.PreToolUse)?l.PreToolUse.filter(p=>!tt(p)):[],...pe(n,r,s)];return JSON.stringify(l.PreToolUse??null)!==JSON.stringify(c)&&(l.PreToolUse=c,i=!0),i&&S(e,JSON.stringify(o,null,2)),i}catch{return!1}}function ct(t){return Array.isArray(t?.hooks)&&t.hooks.some(n=>typeof n?.command=="string"&&n.command.includes(D))}function ut(t,n,r,s){let e=m(t,".claude/settings.json");if(!y(e))return!1;try{let o=JSON.parse(R(e,"utf-8")),i=JSON.stringify(o),a=s.enabled&&s.tools.length>0,u=`Read(/${te(s.dir,n)}/**)`,l=Array.isArray(o.hooks?.PostToolUse)?o.hooks.PostToolUse:[],d=l.filter(h=>!ct(h)),c=Array.isArray(o.permissions?.allow)?o.permissions.allow:[],p=c.filter(h=>h!==u);if(a){let g=`curl -s --max-time 5 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${r}${D}?agent=${encodeURIComponent(n)}`}' 2>/dev/null || true`;d.push({matcher:s.tools.join("|"),hooks:[{type:"command",command:g,timeout:10}]}),p.push(u)}return(a||l.length>0)&&((o.hooks??={}).PostToolUse=d),(a||c.length>0)&&((o.permissions??={}).allow=p),JSON.stringify(o)===i?!1:(S(e,JSON.stringify(o,null,2)),!0)}catch{return!1}}function Xt(t,n="19900",r=console.error,s){let e=0,o=0,i=0,a=0,u=0,l=0;for(let[d,c]of Object.entries(t)){if(c.tier!=="claude-code"&&c.tier!=="codex-cli")continue;let p=ot(d,c,n,r);if(e+=p.created.length,c.tier==="claude-code"&&it(c.workspace,{env:{CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS:"1"}})&&o++,c.tier==="claude-code"&&at(c.workspace,d,n,c.mcp)&&i++,c.tier==="claude-code"&&s){let h=ne(c.permissionMode);s.enabled&&!h&&l++;let g=s.enabled&&h;ut(c.workspace,d,n,{...s,enabled:g})&&(g?a++:u++)}}e>0&&r(`Workspace setup: ${e} file(s) created across agent workspaces`),o>0&&r(`Workspace patch: ${o} workspace(s) updated with agent teams support`),i>0&&r(`Guardrails: ${i} workspace(s) backfilled with deny list + PreToolUse guard hook`),a>0&&r(`ObservationPack: PostToolUse hook written to ${a} workspace(s)`),u>0&&r(`ObservationPack: PostToolUse hook removed from ${u} workspace(s)`),l>0&&r(`ObservationPack: ${l} agent(s) not packed: permissionMode is not "bypassPermissions", so they could not read a saved original back`)}export{ht as a,gt as b,mt as c,xt as d,wt as e,D as f,Ot as g,te as h,ne as i,At as j,Pt as k,Dt as l,He as m,I as n,It as o,ie as p,Ve as q,ze as r,le as s,Ze as t,et as u,ot as v,at as w,ut as x,Xt as y};
|
|
115
|
+
//# sourceMappingURL=chunk-3AHYZLGE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agents/workspace-setup.ts","../src/agents/bootstrap.ts","../src/agents/codegraph-bootstrap.ts","../src/agents/observation-pack.ts","../src/agent/mcp-confirm.ts","../src/guard/hook-command.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\"\nimport { OBSERVATION_PACK_ROUTE, agentObservationDir, canReadOriginals } from \"./observation-pack\"\nimport { allowListHookMatcher, type McpPolicyFields } from \"@/agent/mcp-policy\"\nimport { MCP_CONFIRM_WAIT_S } from \"@/agent/mcp-confirm\"\nimport { buildGuardHookCommand, GUARD_HOOK_TIMEOUT_S } from \"@/guard/hook-command\"\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 the usual path is cheap: POST the payload to the running daemon\n * over loopback (~1ms; `/guard/check` is loopback-only). The daemon can be\n * unreachable while an agent still runs (a restart under a warm process or\n * a detached cloud session) or while a person works in this folder. Then the\n * hook checks the rules locally, and if that fails too, refuses the call in\n * sessions the daemon started, except the commands that start the daemon\n * (#1710). See guard/hook-command.ts. `root` is the install root, which is\n * the daemon's working directory.\n */\nfunction guardHookCommand(agentId: string, daemonPort: string, root: string = process.cwd()): string {\n return buildGuardHookCommand({ port: daemonPort, root, agentId, required: true })\n}\n\n/** How long curl waits for /guard/check on an MCP tool: the write card's\n * wait (#1736) plus room for the daemon to answer after it. */\nexport const MCP_GUARD_CURL_S = MCP_CONFIRM_WAIT_S + 15\n/** Claude Code's limit for the whole hook, above curl's: a hook Claude\n * Code times out does not block the call, so curl must give up first. */\nexport const MCP_GUARD_HOOK_TIMEOUT_S = MCP_GUARD_CURL_S + 15\n\n/** The guard command for MCP tools with an `allowTools` list (#1698). Unlike\n * [guardHookCommand] it fails CLOSED: when the daemon cannot answer (down,\n * restarting, HTTP error, slower than [MCP_GUARD_CURL_S]) it prints a\n * deny, so a listed server's tools never run unchecked. The daemon may\n * hold the answer while a write tool's Approvals card waits (#1736). */\nexport function mcpGuardHookCommand(agentId: string, daemonPort: string): string {\n const url = `http://127.0.0.1:${daemonPort}/guard/check?agent=${encodeURIComponent(agentId)}`\n const deny = JSON.stringify({\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: \"AgentX guard did not answer; tools of an MCP server with an allow list are refused until it does.\",\n },\n })\n return `out=$(curl -sf --max-time ${MCP_GUARD_CURL_S} -H 'Content-Type: application/json' --data-binary @- '${url}' 2>/dev/null) && printf '%s' \"$out\" || printf '%s' '${deny}'`\n}\n\n/** PreToolUse hook entries wiring the guard onto Bash + Write/Edit, and\n * onto the tools of every MCP server with an `allowTools` list (#1698):\n * the daemon refuses a call to a tool left off that list. */\nfunction guardPreToolUseHooks(\n agentId: string,\n daemonPort: string,\n mcp?: Record<string, McpPolicyFields>,\n): unknown[] {\n const command = guardHookCommand(agentId, daemonPort)\n const entries: unknown[] = [\n { matcher: \"Bash\", hooks: [{ type: \"command\", command, timeout: GUARD_HOOK_TIMEOUT_S }] },\n { matcher: \"Write|Edit\", hooks: [{ type: \"command\", command, timeout: GUARD_HOOK_TIMEOUT_S }] },\n ]\n const mcpMatcher = allowListHookMatcher(mcp)\n if (mcpMatcher) {\n entries.push({ matcher: mcpMatcher, hooks: [{ type: \"command\", command: mcpGuardHookCommand(agentId, daemonPort), timeout: MCP_GUARD_HOOK_TIMEOUT_S }] })\n }\n return entries\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, (def as any).mcp)\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/** The code-quality rule as written before #455. Its \"Keep files under 300\n * lines\" made a coding agent open a task by counting lines (`wc -l`)\n * instead of reading the files, one extra model call: in a 10-run test on\n * a six-file bug hunt, 10 of 10 first calls counted lines with it and 2 of\n * 10 without it, and median tokens fell from 160k to 124k. */\nconst CODE_QUALITY_RULE_BEFORE_455 = `# 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\ninterface RuleFile {\n name: string\n content: string\n /** Earlier generated versions. A workspace file still identical to one\n * of them was never edited by hand, so it is brought up to date. */\n replaces?: string[]\n}\n\n/** Generate .claude/rules/ files based on agent role */\nfunction generateRules(agentId: string, def: AgentDef): RuleFile[] {\n const role = detectRole(agentId, def)\n const rules: RuleFile[] = []\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- Extract repeated logic into shared utilities\n`,\n replaces: [CODE_QUALITY_RULE_BEFORE_455],\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 const path = resolve(workspace, \".claude/rules\", rule.name)\n if (rule.replaces && existsSync(path) && rule.replaces.includes(readFileSync(path, \"utf8\"))) {\n writeFileSync(path, rule.content)\n created.push(path)\n } else {\n writeIfMissing(path, rule.content)\n }\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(\n workspace: string,\n agentId: string,\n daemonPort: string = \"19900\",\n mcp?: Record<string, McpPolicyFields>,\n): 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, mcp)]\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/** What `patchObservationPack` needs from `session.observationPack`. */\nexport interface ObservationPackHook {\n enabled: boolean\n tools: string[]\n /** The store of saved originals; the agent is allowed to read its own\n * folder in it and no other agent's. */\n dir: string\n}\n\nfunction isObservationPackEntry(entry: any): boolean {\n return (\n Array.isArray(entry?.hooks) &&\n entry.hooks.some((h: any) => typeof h?.command === \"string\" && h.command.includes(OBSERVATION_PACK_ROUTE))\n )\n}\n\n/**\n * Add the ObservationPack PostToolUse hook (#621) to an existing\n * settings.json when the pack is on, and take it out when it is off. The\n * hook pipes the tool result to the daemon's loopback route and hands the\n * answer back to Claude Code; with the daemon down it prints nothing and the\n * result is left as it was. Also lets the agent Read its own saved originals.\n * Idempotent. Returns true if it changed the file.\n */\nexport function patchObservationPack(\n workspace: string,\n agentId: string,\n daemonPort: string,\n pack: ObservationPackHook,\n): 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 const before = JSON.stringify(existing)\n\n const on = pack.enabled && pack.tools.length > 0\n const readRule = `Read(/${agentObservationDir(pack.dir, agentId)}/**)`\n const posted: unknown[] = Array.isArray(existing.hooks?.PostToolUse) ? existing.hooks.PostToolUse : []\n const others = posted.filter((e) => !isObservationPackEntry(e))\n const allowed: string[] = Array.isArray(existing.permissions?.allow) ? existing.permissions.allow : []\n const allow = allowed.filter((r) => r !== readRule)\n\n if (on) {\n const url = `http://127.0.0.1:${daemonPort}${OBSERVATION_PACK_ROUTE}?agent=${encodeURIComponent(agentId)}`\n const command = `curl -s --max-time 5 -H 'Content-Type: application/json' --data-binary @- '${url}' 2>/dev/null || true`\n others.push({ matcher: pack.tools.join(\"|\"), hooks: [{ type: \"command\", command, timeout: 10 }] })\n allow.push(readRule)\n }\n\n // Only touch the keys the pack owns, and only when it has something there.\n if (on || posted.length > 0) (existing.hooks ??= {}).PostToolUse = others\n if (on || allowed.length > 0) (existing.permissions ??= {}).allow = allow\n\n if (JSON.stringify(existing) === before) return false\n writeFileSync(settingsPath, JSON.stringify(existing, null, 2))\n return true\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 observationPack?: ObservationPackHook,\n): void {\n let totalCreated = 0\n let totalPatched = 0\n let totalGuarded = 0\n let packWritten = 0\n let packRemoved = 0\n let packSkipped = 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, (def as any).mcp)) {\n totalGuarded++\n }\n\n if (def.tier === \"claude-code\" && observationPack) {\n // An agent that cannot read an original back is not packed, and loses\n // the hook if an earlier start wrote it.\n const readable = canReadOriginals(def.permissionMode)\n if (observationPack.enabled && !readable) packSkipped++\n const on = observationPack.enabled && readable\n if (patchObservationPack(def.workspace, id, daemonPort, { ...observationPack, enabled: on })) {\n if (on) packWritten++\n else packRemoved++\n }\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 if (packWritten > 0) {\n log(`ObservationPack: PostToolUse hook written to ${packWritten} workspace(s)`)\n }\n if (packRemoved > 0) {\n log(`ObservationPack: PostToolUse hook removed from ${packRemoved} workspace(s)`)\n }\n if (packSkipped > 0) {\n log(`ObservationPack: ${packSkipped} agent(s) not packed: permissionMode is not \"bypassPermissions\", so they could not read a saved original back`)\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","// ObservationPack (#621): keep large tool results out of the conversation.\n//\n// A tool result stays in a session's context and is re-read on every later\n// request. Most of a 40 KB build log is never looked at again. The pack\n// answers Claude Code's PostToolUse hook: a text result over the size limit\n// is written to disk in full and the model is given its first and last bytes\n// plus the path of the file, which it can Read or grep for the exact original.\n//\n// Claude Code does the same on its own for Bash output over 30,000 characters\n// (a 2 KB preview and a saved file); those results are left to it. The pack\n// covers what is between its limit and that one, and the tools Claude Code\n// does not preview.\n//\n// A file read (the Read tool) is packed too, since the owner's decision of\n// 2026-10-05 on #621. The file is its own original, so nothing is copied:\n// the model keeps the first and last lines, with the file's path and the\n// line numbers of what was left out, and reads those again with offset and\n// limit when it needs them.\n//\n// The hook replaces the result before the model sees it for the first time.\n// The paper this follows (arXiv 2609.20519) shows the full result for two\n// requests first; a hook cannot do that, because it runs once per tool call.\n//\n// Nothing here calls a model, and a result is never dropped: if the original\n// cannot be written, the result is left as it was.\n\nimport { appendFileSync, existsSync, mkdirSync, readdirSync, realpathSync, statSync, unlinkSync, utimesSync, writeFileSync } from \"fs\"\nimport { createHash } from \"crypto\"\nimport { resolve, sep } from \"path\"\n\nexport interface ObservationPackConfig {\n enabled: boolean\n /** A text result larger than this many bytes is packed. */\n limitBytes: number\n /** Bytes of the start of the original shown to the model. */\n headBytes: number\n /** Bytes of the end of the original shown to the model. */\n tailBytes: number\n /** Tool names the pack applies to. Each entry is a regular expression that\n * must match the whole name, as in a Claude Code hook matcher. */\n tools: string[]\n /** Days an original is kept on disk. 0 keeps every original. */\n retentionDays: number\n}\n\n/** The part of Claude Code's PostToolUse payload the pack reads. */\nexport interface PostToolUsePayload {\n session_id?: string\n tool_name?: string\n tool_input?: Record<string, unknown>\n tool_response?: unknown\n}\n\nexport interface PackRecord {\n sha: string\n path: string\n bytes: number\n keptBytes: number\n}\n\n/** Path marker that tells one of our hook entries from anybody else's. */\nexport const OBSERVATION_PACK_ROUTE = \"/observation/pack\"\n\n/** The store: one folder per agent under it. */\nexport function observationDir(root: string = process.cwd()): string {\n return resolve(root, \".agentx/observations\")\n}\n\n/**\n * One agent's folder in the store. An agent is allowed to read its own\n * folder only: an original holds whatever its command printed. The id is\n * encoded so that no id can name a folder outside the store.\n */\nexport function agentObservationDir(storeDir: string, agentId: string): string {\n return resolve(storeDir, encodeURIComponent(agentId).replace(/\\./g, \"%2E\"))\n}\n\n/**\n * Whether an agent can read a saved original back. Seen live on Claude Code\n * 2.1.289: outside `bypassPermissions` the Read of an original is refused in\n * a session nobody answers for, the allow rule notwithstanding, and the model\n * then guesses at the part it was not shown. Such an agent is not packed.\n */\nexport function canReadOriginals(permissionMode: string | undefined): boolean {\n return permissionMode === \"bypassPermissions\"\n}\n\n/** The same path with symlinks followed, or as given when it does not exist. */\nfunction realPath(path: string): string {\n try {\n return realpathSync(path)\n } catch {\n return resolve(path)\n }\n}\n\nexport function toolIsPacked(toolName: string, tools: string[]): boolean {\n return tools.some((pattern) => {\n try {\n return new RegExp(`^(?:${pattern})$`).test(toolName)\n } catch {\n return pattern === toolName\n }\n })\n}\n\n/** Average line size above which the excerpt points at byte ranges, not lines. */\nconst LONG_LINE_BYTES = 2000\n\n/** Cut on a byte count without leaving half a character at the cut. */\nfunction decodeSlice(buf: Buffer, start: number, end: number): string {\n return buf.subarray(start, end).toString(\"utf-8\").replace(/^�+|�+$/g, \"\")\n}\n\n/** The text the model gets in place of `text`. */\nexport function buildExcerpt(text: string, path: string, config: Pick<ObservationPackConfig, \"headBytes\" | \"tailBytes\">): string {\n const buf = Buffer.from(text, \"utf-8\")\n const head = decodeSlice(buf, 0, config.headBytes)\n const tail = config.tailBytes > 0 ? decodeSlice(buf, buf.length - config.tailBytes, buf.length) : \"\"\n const withheld = buf.length - config.headBytes - config.tailBytes\n const lines = text.split(\"\\n\").length\n // A line read or a grep match on very long lines (minified JSON) returns\n // as much as the original, which is then packed again.\n const longLines = buf.length / lines > LONG_LINE_BYTES\n const how = longLines\n ? `Its lines are very long, so read it by byte range (for example head -c or tail -c, or jq for JSON) for the part you need.`\n : `Read that file with offset and limit (line numbers), or grep it, for the part you need. Do not cat it whole: that is packed again.`\n return [\n `[ObservationPack: this result is ${buf.length} bytes (${lines} lines). Only its first ${config.headBytes} and last ${config.tailBytes} bytes are shown.`,\n `The exact original is saved at ${path}`,\n `${how} Do not guess at what is not shown.]`,\n head,\n `[... ${withheld} bytes not shown ...]`,\n tail,\n ].join(\"\\n\")\n}\n\n/** The text shape of a Read result in Claude Code's PostToolUse payload. */\ninterface ReadTextResult {\n type: \"text\"\n file: { filePath?: string; content: string; numLines?: number; startLine?: number; totalLines?: number }\n}\n\nfunction isReadTextResult(value: unknown): value is ReadTextResult {\n const obj = value as Partial<ReadTextResult> | null\n return !!obj && typeof obj === \"object\" && obj.type === \"text\" && typeof obj.file?.content === \"string\"\n}\n\n/** How many lines `text` spans, counting a final unterminated line. */\nfunction lineCount(text: string): number {\n if (text === \"\") return 0\n let n = 1\n for (let i = text.indexOf(\"\\n\"); i !== -1; i = text.indexOf(\"\\n\", i + 1)) n++\n if (text.endsWith(\"\\n\")) n--\n return n\n}\n\n/**\n * The text the model gets in place of a file read. The file itself is the\n * original, so nothing is copied: the excerpt keeps whole lines from both\n * ends and names the file and the exact line numbers of what is not shown,\n * so the model asks for the part it needs with offset and limit.\n *\n * Claude Code prints its line numbers beside the content it is given, from\n * `startLine` on. The head comes first and ends on a line break, so its\n * numbers are the file's; the notice and the tail that follow are numbered\n * on from there, so the notice states the tail's real first line.\n */\nexport function buildReadExcerpt(\n content: string,\n file: { path: string; startLine: number; totalLines?: number },\n config: Pick<ObservationPackConfig, \"headBytes\" | \"tailBytes\">,\n): string {\n const buf = Buffer.from(content, \"utf-8\")\n const lines = lineCount(content)\n\n // Whole lines within the budget. A line longer than the budget is cut,\n // and then counts as not shown, since part of it is not.\n let head = decodeSlice(buf, 0, config.headBytes)\n const headBreak = head.lastIndexOf(\"\\n\")\n head = headBreak === -1 ? head : head.slice(0, headBreak + 1)\n let tail = config.tailBytes > 0 ? decodeSlice(buf, buf.length - config.tailBytes, buf.length) : \"\"\n const tailBreak = tail.indexOf(\"\\n\")\n tail = tailBreak === -1 ? tail : tail.slice(tailBreak + 1)\n\n const headLines = headBreak === -1 ? 0 : lineCount(head)\n const tailLines = tailBreak === -1 ? 0 : lineCount(tail)\n const first = file.startLine\n const last = first + lines - 1\n const hiddenFrom = first + headLines\n const hiddenTo = last - tailLines\n const withheld = buf.length - Buffer.byteLength(head, \"utf-8\") - Buffer.byteLength(tail, \"utf-8\")\n const whole = typeof file.totalLines === \"number\" && file.totalLines > lines ? ` (${file.totalLines} lines in all)` : \"\"\n const hidden = hiddenFrom === hiddenTo ? `Line ${hiddenFrom} (${withheld} bytes) is` : `Lines ${hiddenFrom} to ${hiddenTo} (${withheld} bytes) are`\n const cut = [headLines === 0 && head !== \"\" ? first : null, tailLines === 0 && tail !== \"\" ? last : null].filter((n) => n !== null)\n const partly = cut.length === 0 ? \"\" : cut.length === 1 || cut[0] === cut[1] ? ` (line ${cut[0]} only in part)` : ` (lines ${cut[0]} and ${cut[1]} only in part)`\n const tailNote = tailLines > 0 ? ` Lines ${hiddenTo + 1} to ${last} follow; the numbers beside them are not the file's.` : \"\"\n\n return [\n head,\n `[ObservationPack: this read is ${buf.length} bytes, lines ${first} to ${last} of ${file.path}${whole}.`,\n `${hidden} not shown${partly}.${tailNote}`,\n `Read the file again with offset and limit for the lines you need, or Grep it. Do not guess at what is not shown.]`,\n tail,\n ]\n .filter((part) => part !== \"\")\n .join(\"\\n\")\n}\n\n/** Write the original where the model can read it back. Same text, same file. */\nfunction storeOriginal(dir: string, text: string): { sha: string; path: string } {\n const sha = createHash(\"sha256\").update(text).digest(\"hex\")\n const path = resolve(dir, `${sha}.txt`)\n if (existsSync(path)) {\n // Seen again: keep it clear of the retention sweep.\n const now = new Date()\n utimesSync(path, now, now)\n } else {\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n writeFileSync(path, text, { mode: 0o600 })\n }\n return { sha, path }\n}\n\n/**\n * Pack one tool result. Returns the replacement for `tool_response`, in the\n * tool's own shape, and one record per packed text; or null when nothing is\n * to change (pack off, tool not listed, nothing over the limit, a picture,\n * sound or other base64 item, a result Claude Code already saved to a file,\n * or a read of an original we saved ourselves). For a file read the record's\n * `path` is the file itself.\n */\nexport function packToolOutput(\n payload: PostToolUsePayload,\n config: ObservationPackConfig,\n dir: string,\n): { updated: unknown; packs: PackRecord[] } | null {\n if (!config.enabled) return null\n const tool = payload.tool_name\n if (!tool || !toolIsPacked(tool, config.tools)) return null\n\n // Reading a saved original back must return it whole, or it could never be\n // retrieved.\n const filePath = payload.tool_input?.[\"file_path\"]\n if (typeof filePath === \"string\" && realPath(filePath).startsWith(realPath(dir) + sep)) return null\n\n // An excerpt has to be smaller than what it replaces.\n if (config.limitBytes <= config.headBytes + config.tailBytes) return null\n\n // A file read: the file is the original, so none is copied. Only the text\n // shape is cut; a notebook, a PDF or a picture is left whole.\n if (tool === \"Read\") {\n const response = payload.tool_response\n if (!isReadTextResult(response)) return null\n const content = response.file.content\n const bytes = Buffer.byteLength(content, \"utf-8\")\n if (bytes <= config.limitBytes) return null\n const path = typeof filePath === \"string\" ? filePath : (response.file.filePath ?? \"the file you read\")\n const offset = payload.tool_input?.[\"offset\"]\n const startLine =\n typeof response.file.startLine === \"number\" && response.file.startLine >= 1\n ? response.file.startLine\n : typeof offset === \"number\" && offset >= 1\n ? offset\n : 1\n const excerpt = buildReadExcerpt(content, { path, startLine, totalLines: response.file.totalLines }, config)\n const sha = createHash(\"sha256\").update(content).digest(\"hex\")\n return {\n updated: { ...response, file: { ...response.file, content: excerpt } },\n packs: [{ sha, path, bytes, keptBytes: Buffer.byteLength(excerpt, \"utf-8\") }],\n }\n }\n\n const packs: PackRecord[] = []\n const walk = (value: unknown): unknown => {\n if (typeof value === \"string\") {\n const bytes = Buffer.byteLength(value, \"utf-8\")\n if (bytes <= config.limitBytes) return value\n const { sha, path } = storeOriginal(dir, value)\n const excerpt = buildExcerpt(value, path, config)\n packs.push({ sha, path, bytes, keptBytes: Buffer.byteLength(excerpt, \"utf-8\") })\n return excerpt\n }\n if (Array.isArray(value)) return value.map(walk)\n if (value && typeof value === \"object\") {\n const obj = value as Record<string, unknown>\n // Pictures and sound are not text; base64 cut in the middle is noise.\n if (obj[\"type\"] === \"image\" || obj[\"type\"] === \"audio\" || obj[\"isImage\"] === true) return value\n // Claude Code already saved this one to a file and shows a preview\n // (Bash output over 30,000 characters). What we get here is cut short,\n // so it is not the original; leave its own handle in place.\n if (typeof obj[\"persistedOutputPath\"] === \"string\") return value\n // `blob` is the base64 body of an MCP resource; its `text` twin is packed.\n return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, k === \"blob\" ? v : walk(v)]))\n }\n return value\n }\n\n try {\n const updated = walk(payload.tool_response)\n return packs.length > 0 ? { updated, packs } : null\n } catch {\n // Could not save an original: the model keeps the full result.\n return null\n }\n}\n\n/**\n * Answer a PostToolUse hook call. Returns the JSON Claude Code expects on the\n * hook's stdout, or \"\" to leave the result alone. `dir` is the calling\n * agent's own folder. Each pack is appended to `index.jsonl` there, so what\n * was withheld can be counted later.\n */\nexport function answerPackHook(\n payload: PostToolUsePayload,\n config: ObservationPackConfig,\n opts: { dir: string; agentId?: string },\n): string {\n // A body that is not an object (JSON `null`) is no tool result.\n const result = payload && typeof payload === \"object\" ? packToolOutput(payload, config, opts.dir) : null\n if (!result) return \"\"\n try {\n const at = new Date().toISOString()\n const rows = result.packs.map((p) =>\n JSON.stringify({ at, agent: opts.agentId, session: payload.session_id, tool: payload.tool_name, sha: p.sha, bytes: p.bytes, keptBytes: p.keptBytes }),\n )\n // A packed file read copies nothing, so the folder may not exist yet.\n mkdirSync(opts.dir, { recursive: true, mode: 0o700 })\n appendFileSync(resolve(opts.dir, \"index.jsonl\"), rows.join(\"\\n\") + \"\\n\", { mode: 0o600 })\n } catch {\n // The index is a count, not the evidence. The original is already saved.\n }\n return JSON.stringify({\n hookSpecificOutput: { hookEventName: \"PostToolUse\", updatedToolOutput: result.updated },\n })\n}\n\n/**\n * Delete originals not written or seen again for `retentionDays`, in every\n * agent's folder of the store. Returns how many.\n */\nexport function pruneObservations(storeDir: string, retentionDays: number, now: number = Date.now()): number {\n if (retentionDays <= 0 || !existsSync(storeDir)) return 0\n const cutoff = now - retentionDays * 86_400_000\n let removed = 0\n for (const agent of readdirSync(storeDir, { withFileTypes: true })) {\n if (!agent.isDirectory()) continue\n const dir = resolve(storeDir, agent.name)\n for (const name of readdirSync(dir)) {\n if (!name.endsWith(\".txt\")) continue\n const path = resolve(dir, name)\n try {\n if (statSync(path).mtimeMs < cutoff) {\n unlinkSync(path)\n removed++\n }\n } catch {\n // Gone or unreadable: nothing to prune.\n }\n }\n }\n return removed\n}\n","import { createCard, readCard, saveCard, type CardSettings, type DecisionCard } from \"@/approvals/cards\"\nimport { mcpWriteNeedingConfirm, type McpPolicyFields } from \"./mcp-policy\"\n\n// --- A write tool waits for one Approvals card (#1736) ---\n//\n// A call to a tool that writes, on an MCP server with an `allowTools` list\n// (mcp-policy.ts decides which), raises one card and waits for the answer.\n// Yes runs the call. No, no answer before the wait ends, a card that\n// could not be raised, or any error: the call does not run.\n//\n// Both tiers use this: the daemon's /guard/check (claude-code tier, whose\n// hook waits for the answer) and the in-process MCP pool (orchestrator).\n// The card's answer IS the result, so the agent gets no separate result\n// turn for it (approvals/sweep.ts skips origin \"mcp-write\").\n\n/** How long a call waits for the owner. The claude-code hook's own limits\n * sit above this (workspace-setup.ts), so the daemon answers first. */\nexport const MCP_CONFIRM_WAIT_S = 180\n\nexport interface McpConfirmDeps {\n /** The daemon's folder: cards live under <root>/.agentx/approvals. */\n root: string\n agentId: string\n settings?: CardSettings\n waitMs?: number\n pollMs?: number\n now?: () => number\n sleep?: (ms: number) => Promise<void>\n /** Told once the card is saved (logs, the Wall). */\n onCard?: (card: DecisionCard) => void\n}\n\nconst CONTEXT_MAX = 600\n\n/** The call's input as shown on the card: compact JSON, cut to fit. */\nfunction inputPreview(input: unknown): string {\n let text: string\n try { text = JSON.stringify(input ?? {}) } catch { text = String(input) }\n text = text.replace(/\\s+/g, \" \").trim()\n const head = \"Input: \"\n const room = CONTEXT_MAX - head.length\n return head + (text.length > room ? text.slice(0, room - 1) + \"…\" : text)\n}\n\nfunction cut(s: string, n: number): string {\n return s.length > n ? s.slice(0, n - 1) + \"…\" : s\n}\n\nfunction refusal(server: string, tool: string, why: string): string {\n return `[agentx-mcp] \"${tool}\" on MCP server \"${server}\" writes data and was not run: ${why}. ` +\n `Do not retry it or work around it. Say what you were trying to do and wait for instructions.`\n}\n\n/** A decided card's answer: null (run) on yes, else the refusal. */\nfunction verdictOf(card: DecisionCard, server: string, tool: string): string | null {\n return card.verdict === \"yes\" ? null : refusal(server, tool, `the owner said no on card ${card.id}`)\n}\n\n/**\n * Ask before a write tool runs. Resolves to null when the call may run\n * (not a gated write, or the owner said yes), else the refusal the agent\n * reads. Never throws.\n */\nexport async function mcpWriteDenial(\n toolName: string,\n input: unknown,\n servers: Record<string, McpPolicyFields> | undefined,\n deps: McpConfirmDeps,\n): Promise<string | null> {\n const target = mcpWriteNeedingConfirm(toolName, servers)\n if (!target) return null\n const { server, tool } = target\n const now = deps.now ?? Date.now\n const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)))\n const waitMs = deps.waitMs ?? MCP_CONFIRM_WAIT_S * 1000\n const pollMs = deps.pollMs ?? 1000\n const minutes = Math.max(1, Math.round(waitMs / 60_000))\n\n try {\n const start = now()\n const made = createCard(deps.root, {\n title: cut(`${deps.agentId} wants to write with ${server}: ${tool}`, 120),\n ask: cut(`Let ${deps.agentId} run the \"${tool}\" tool on ${server}? It changes data in that service.`, 300),\n recommend: `Yes only if you asked for this. No, or no answer within ${minutes} min, and it does not run.`,\n context: inputPreview(input),\n if_silent: \"discard\",\n expires: new Date(start + waitMs).toISOString(),\n raised_by: deps.agentId,\n }, { now: start, settings: deps.settings, origin: { kind: \"mcp-write\", server, tool } })\n if (!made.ok) return refusal(server, tool, `the confirmation card could not be raised (${made.error})`)\n const id = made.card.id\n try { deps.onCard?.(made.card) } catch { /* a listener never decides */ }\n\n while (true) {\n const card = readCard(deps.root, id)\n if (!card) return refusal(server, tool, \"the confirmation card is gone\")\n if (card.status === \"decided\") return verdictOf(card, server, tool)\n if (card.status !== \"pending\") return refusal(server, tool, `card ${id} was not answered in time`)\n if (now() - start >= waitMs) {\n // Close it, so a late yes cannot look like it ran the call. An\n // answer can land while the wait runs out, so read the card again\n // right before closing it, and once more after: a yes saved on\n // either side of our save is the owner's answer, not lost (#1737).\n const latest = readCard(deps.root, id)\n if (!latest) return refusal(server, tool, \"the confirmation card is gone\")\n if (latest.status === \"decided\") return verdictOf(latest, server, tool)\n if (latest.status !== \"pending\") return refusal(server, tool, `card ${id} was not answered in time`)\n saveCard(deps.root, {\n ...latest,\n status: \"expired\",\n outcome: \"discard\",\n decided_by: \"expiry\",\n decided_at: new Date(now()).toISOString(),\n })\n const after = readCard(deps.root, id)\n if (after?.status === \"decided\") return verdictOf(after, server, tool)\n return refusal(server, tool, `card ${id} was not answered within ${minutes} min`)\n }\n await sleep(pollMs)\n }\n } catch (e: any) {\n // A failure to ask is not a yes.\n return refusal(server, tool, `the confirmation step failed (${e?.message ?? e})`)\n }\n}\n","import { mkdirSync, renameSync, writeFileSync } from \"fs\"\nimport { dirname, resolve } from \"path\"\n\n// --- The PreToolUse guard hook command (#1710) ---\n//\n// One builder for both hook sites: the per-workspace hook\n// (agents/workspace-setup.ts) and the user-scope attach hook\n// (attach/install.ts). Design: notes/design/guard-fail-closed.md.\n//\n// 1. Ask the daemon. `--connect-timeout` is short, so a daemon that is\n// down or restarting refuses at once; `--max-time` is long, so a daemon\n// that is up gets to answer, including a confirmation dialog click.\n// 2. If the daemon gives no answer, run the deterministic rules locally\n// (`agentx guard check --rules-only`) through a stable link the daemon\n// writes on start, then `agentx` on PATH.\n// 3. If that fails too: sessions the daemon started (AGENTX_GUARD=required,\n// workspace hook only) are refused, except for the fixed commands that\n// start or restart the daemon. Everyone else is allowed, as before.\n//\n// The shell always ends in `exit 0`. A hook exiting 2 blocks with no reason,\n// and curl uses exit 2 for its own start-up errors.\n\n/** Printed by `guard check --rules-only` when the check itself failed. */\nexport const GUARD_ERROR_MARKER = \"AGENTX_GUARD_ERROR\"\n\n/** Claude Code's timeout for the guard hook, in seconds. Must outlast the\n * daemon's answer (curl max-time) plus a node start-up of the fallback on a\n * loaded host plus its own deadline. When Claude Code drops a hook, the call\n * runs, so this errs long. */\nexport const GUARD_HOOK_TIMEOUT_S = 75\n\nexport interface GuardHookBudget {\n /** curl --connect-timeout, seconds. */\n connectS: number\n /** curl --max-time, seconds. Outlasts the daemon's 45 s dialog. */\n maxTimeS: number\n /** --deadline-ms for the rules-only fallback. */\n deadlineMs: number\n}\n\nexport const DEFAULT_GUARD_HOOK_BUDGET: GuardHookBudget = { connectS: 1, maxTimeS: 55, deadlineMs: 3000 }\n\n/** The stable path of the fallback CLI. The daemon rewrites it on each start\n * so it survives a release directory being switched or removed. */\nexport function guardCliLinkPath(root: string): string {\n return resolve(root, \".agentx/bin/agentx-guard\")\n}\n\n/** Write the fallback CLI link: a small sh script that runs this daemon's own\n * node on its own cli.js. Exits 127 when cli.js is gone, so the hook moves\n * on to `agentx` on PATH. Replaced in one rename. */\nexport function writeGuardCliLink(root: string, nodePath: string, cliPath: string): string {\n const path = guardCliLinkPath(root)\n mkdirSync(dirname(path), { recursive: true })\n const body = `#!/bin/sh\\n[ -f ${sq(cliPath)} ] || exit 127\\nexec ${sq(nodePath)} ${sq(cliPath)} \"$@\"\\n`\n const tmp = `${path}.${process.pid}.tmp`\n writeFileSync(tmp, body, { mode: 0o755 })\n renameSync(tmp, path)\n return path\n}\n\n/** Single-quote a value for sh. */\nfunction sq(s: string): string {\n return `'${s.replace(/'/g, `'\\\\''`)}'`\n}\n\nconst WORD = \"[A-Za-z0-9_./~@:=-]+\"\nconst STARTS = `(start|restart|status)( +(-d|--detach|--when-idle|(-c|--config|--port)( +|=)${WORD}))*`\nconst UID = \"([0-9]+|\\\\$\\\\(id -u\\\\)|\\\\$UID)\"\n\n/** The commands a daemon-started session may still run when neither check\n * answers: starting, restarting or asking about the daemon. Whole-string\n * match (grep -Ex) after trimming spaces. `$(id -u)` and `$UID` are allowed\n * only as the uid inside `gui/`; every other `$`, backtick, `;`, `&`, `|`,\n * redirect or newline fails the match. Exported for tests. */\nexport const DAEMON_RESTART_ALLOW = [\n `agentx +daemon +${STARTS}`,\n `(node +)?(${WORD}/)?cli\\\\.js +daemon +${STARTS}`,\n `npx +tsx +(${WORD}/)?cli\\\\.ts +daemon +${STARTS}`,\n `launchctl +kickstart( +-k)? +gui/${UID}/${WORD}`,\n `launchctl +(bootstrap|bootout) +gui/${UID} +${WORD}`,\n `systemctl +--user +(start|restart|status) +${WORD}`,\n `sudo +systemctl +(start|restart|status) +${WORD}`,\n].map((r) => `(${r})`).join(\"|\")\n\nfunction denyJson(reason: string): string {\n return JSON.stringify({\n hookSpecificOutput: { hookEventName: \"PreToolUse\", permissionDecision: \"deny\", permissionDecisionReason: reason },\n })\n}\n\nexport const GUARD_DOWN_DENY_REASON =\n \"[agentx-guard] Refused: the AgentX guard could not check this call (the daemon is not answering and the local check failed). \" +\n \"Only `agentx daemon start|restart|status` and the launchctl/systemctl forms that start the daemon run until it answers.\"\n\nexport interface GuardHookOptions {\n port: string\n /** Install root: holds .agentx/guardrails, .agentx/db.sqlite and the CLI link. */\n root: string\n agentId?: string\n /** Add step 3 (deny unless allow-listed when AGENTX_GUARD=required).\n * Only the workspace hook; the attach hook never denies on its own failure. */\n required?: boolean\n budget?: GuardHookBudget\n /** Override the fallback CLI path (tests). */\n cliPath?: string\n}\n\n/** Build the shell command for the guard hook. */\nexport function buildGuardHookCommand(o: GuardHookOptions): string {\n const b = o.budget ?? DEFAULT_GUARD_HOOK_BUDGET\n const query = o.agentId ? `?agent=${encodeURIComponent(o.agentId)}` : \"\"\n const url = `http://127.0.0.1:${o.port}/guard/check${query}`\n const args = `guard check --rules-only --deadline-ms ${b.deadlineMs} --root ${sq(o.root)}${o.agentId ? ` --agent ${sq(o.agentId)}` : \"\"}`\n const lines = [\n `p=$(cat)`,\n // 1. The daemon. -f: a non-2xx answer counts as no answer.\n `out=$(printf '%s' \"$p\" | curl -sf --connect-timeout ${b.connectS} --max-time ${b.maxTimeS} -H 'Content-Type: application/json' --data-binary @- '${url}' 2>/dev/null) && { printf '%s' \"$out\"; exit 0; }`,\n // 2. The rules, locally. The CLI exits 0 on every path it controls, so a\n // non-zero exit means it did not run: try `agentx` on PATH next.\n `out=$(printf '%s' \"$p\" | ${sq(o.cliPath ?? guardCliLinkPath(o.root))} ${args} 2>/dev/null) || out=$(printf '%s' \"$p\" | agentx ${args} 2>/dev/null)`,\n `[ $? -eq 0 ] && [ \"$out\" != ${GUARD_ERROR_MARKER} ] && { printf '%s' \"$out\"; exit 0; }`,\n ]\n if (o.required) {\n // 3. Neither check answered. Only daemon-started sessions are refused.\n // The command is read from the payload with grep, not a JSON parser:\n // an allowed command has no quote or backslash, so an escaped one\n // (`\\\"`, `\\n`) never matches, and an unmatched call is denied.\n lines.push(\n `[ \"$AGENTX_GUARD\" = required ] || exit 0`,\n `c=$(printf '%s' \"$p\" | grep -o '\"command\" *: *\"[^\"\\\\\\\\]*\"')`,\n `if printf '%s' \"$p\" | grep -q '\"tool_name\" *: *\"Bash\"' && [ \"$(printf '%s\\\\n' \"$c\" | grep -c .)\" = 1 ] && printf '%s\\\\n' \"$c\" | sed 's/^\"command\" *: *\"//; s/\"$//; s/^ *//; s/ *$//' | grep -Eqx ${sq(DAEMON_RESTART_ALLOW)}; then exit 0; fi`,\n `printf '%s' ${sq(denyJson(GUARD_DOWN_DENY_REASON))}`,\n )\n }\n lines.push(`exit 0`)\n return lines.join(\"\\n\")\n}\n"],"mappings":"qGAAA,OAAS,cAAAA,EAAY,aAAAC,GAAW,iBAAAC,EAAe,gBAAAC,MAAoB,KACnE,OAAS,WAAAC,MAAe,OACxB,OAAS,cAAAC,OAAkB,SCF3B,OAAS,gBAAAC,GAAc,cAAAC,GAAY,cAAAC,GAAY,eAAAC,OAAmB,KAClE,OAAS,WAAAC,MAAe,OAuCjB,SAASC,GAAmBC,EAAmBC,EAAsC,CAC1F,IAAMC,EAAyB,CAAC,EAE1BC,EAAWC,GAAy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OAAS,YAAa,SAC5D,IAAM8F,EAASjD,GAAegD,EAAI7F,EAAKU,EAAYoC,CAAG,EAgBtD,GAfAyC,GAAgBO,EAAO,QAAQ,OAG3B9F,EAAI,OAAS,eAAiB6D,GAAc7D,EAAI,UAAW,CAC7D,IAAK,CAAE,qCAAsC,GAAI,CACnD,CAAC,GACCwF,IAKExF,EAAI,OAAS,eAAiBoE,GAAgBpE,EAAI,UAAW6F,EAAInF,EAAaV,EAAY,GAAG,GAC/FyF,IAGEzF,EAAI,OAAS,eAAiBsF,EAAiB,CAGjD,IAAMS,EAAWC,GAAiBhG,EAAI,cAAc,EAChDsF,EAAgB,SAAW,CAACS,GAAUH,IAC1C,IAAMhB,EAAKU,EAAgB,SAAWS,EAClCtB,GAAqBzE,EAAI,UAAW6F,EAAInF,EAAY,CAAE,GAAG4E,EAAiB,QAASV,CAAG,CAAC,IACrFA,EAAIc,IACHC,MAIPJ,EAAe,GACjBzC,EAAI,oBAAoByC,2CAAsD,EAE5EC,EAAe,GACjB1C,EAAI,oBAAoB0C,iDAA4D,EAElFC,EAAe,GACjB3C,EAAI,eAAe2C,kEAA6E,EAE9FC,EAAc,GAChB5C,EAAI,gDAAgD4C,gBAA0B,EAE5EC,EAAc,GAChB7C,EAAI,kDAAkD6C,gBAA0B,EAE9EC,EAAc,GAChB9C,EAAI,oBAAoB8C,gHAA0H,CAEtJ","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","appendFileSync","existsSync","mkdirSync","readdirSync","realpathSync","statSync","unlinkSync","utimesSync","writeFileSync","createHash","resolve","sep","OBSERVATION_PACK_ROUTE","observationDir","root","agentObservationDir","storeDir","agentId","canReadOriginals","permissionMode","realPath","path","toolIsPacked","toolName","tools","pattern","LONG_LINE_BYTES","decodeSlice","buf","start","end","buildExcerpt","text","config","head","tail","withheld","lines","how","isReadTextResult","value","obj","lineCount","i","buildReadExcerpt","content","file","headBreak","tailBreak","headLines","tailLines","first","last","hiddenFrom","hiddenTo","whole","hidden","cut","n","partly","tailNote","part","storeOriginal","dir","sha","now","packToolOutput","payload","tool","filePath","response","bytes","offset","startLine","excerpt","packs","walk","k","v","updated","answerPackHook","opts","result","at","rows","p","pruneObservations","retentionDays","cutoff","removed","agent","name","MCP_CONFIRM_WAIT_S","CONTEXT_MAX","inputPreview","input","text","head","room","cut","s","refusal","server","tool","why","verdictOf","card","mcpWriteDenial","toolName","servers","deps","target","mcpWriteNeedingConfirm","now","sleep","ms","r","waitMs","pollMs","minutes","start","made","createCard","id","readCard","latest","saveCard","after","e","mkdirSync","renameSync","writeFileSync","dirname","resolve","GUARD_ERROR_MARKER","GUARD_HOOK_TIMEOUT_S","DEFAULT_GUARD_HOOK_BUDGET","guardCliLinkPath","root","writeGuardCliLink","nodePath","cliPath","path","body","sq","tmp","s","WORD","STARTS","UID","DAEMON_RESTART_ALLOW","r","denyJson","reason","GUARD_DOWN_DENY_REASON","buildGuardHookCommand","o","b","query","url","args","lines","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","root","buildGuardHookCommand","MCP_GUARD_CURL_S","MCP_CONFIRM_WAIT_S","MCP_GUARD_HOOK_TIMEOUT_S","mcpGuardHookCommand","url","deny","guardPreToolUseHooks","mcp","command","entries","GUARD_HOOK_TIMEOUT_S","mcpMatcher","allowListHookMatcher","isGuardEntry","entry","h","generateSettings","settings","perms","existing","CODEGRAPH_TOOLS","hooks","CODE_QUALITY_RULE_BEFORE_455","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","desired","e","isObservationPackEntry","OBSERVATION_PACK_ROUTE","patchObservationPack","pack","before","on","readRule","agentObservationDir","posted","others","allowed","allow","r","setupAllWorkspaces","agents","observationPack","totalCreated","totalPatched","totalGuarded","packWritten","packRemoved","packSkipped","id","result","readable","canReadOriginals"]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{Rb as $,ob as S}from"./chunk-
|
|
1
|
+
import{Rb as $,ob as S}from"./chunk-CARVBJB7.js";import{randomBytes as x}from"crypto";import{existsSync as b,mkdirSync as k,readdirSync as M,readFileSync as j,renameSync as E,unlinkSync as y,writeFileSync as C}from"fs";import{resolve as c}from"path";function m(t){return c(t,".agentx","email")}function u(t,e){k(c(t,".."),{recursive:!0});let r=`${t}.${process.pid}.tmp`;C(r,JSON.stringify(e,null,2)+`
|
|
2
2
|
`,{mode:384}),E(r,t)}function g(t){try{return JSON.parse(j(t,"utf-8"))}catch{return null}}var D=t=>c(m(t),"threads.json");function w(t){return g(D(t))??{}}function I(t,e){return w(t)[e.toLowerCase()]}function L(t,e){let r=w(t);r[e.to.toLowerCase()]=e,u(D(t),r)}var h=(t,e)=>c(m(t),"cursors",`${e}.json`);function z(t,e){return g(h(t,e))}function B(t,e,r){u(h(t,e),r)}var T=2e4,_=t=>c(m(t),"drafts"),N=t=>/^[a-z0-9-]{8,64}$/.test(t),a=(t,e)=>c(_(t),`${e}.json`);function U(t,e,r=Date.now()){let n=e.text.trim().slice(0,T);if(!n)throw new Error("empty reply");let s={...e,text:n,id:`${r.toString(36)}-${x(4).toString("hex")}`,status:"pending",created_at:new Date(r).toISOString()};return u(a(t,s.id),s),s}function v(t,e){return N(e)?g(a(t,e)):null}function V(t,e){let r=_(t);return b(r)?M(r).filter(n=>n.endsWith(".json")).map(n=>v(t,n.slice(0,-5))).filter(n=>!!n&&(!e||n.status===e)).sort((n,s)=>n.created_at.localeCompare(s.created_at)):[]}async function W(t,e,r,n){let s=v(t,e);if(!s||s.status!=="pending")return{ok:!1,error:`no email reply "${e}" is waiting`};let i=`${a(t,e)}.${process.pid}.${x(3).toString("hex")}.claim`;try{E(a(t,e),i)}catch{return{ok:!1,error:`email reply "${e}" is already being decided`}}let d=n.text!==void 0&&n.text.trim()!==""&&n.text.trim()!==s.text,o={...s,...d?{text:n.text.trim().slice(0,T),edited:!0}:{},decided_by:n.by??"operator",decided_at:new Date(n.now??Date.now()).toISOString()};if(r==="no")o.status="rejected";else{let f=await n.send(o).catch(p=>({ok:!1,error:String(p?.message??p)}));if(!f.ok){u(a(t,e),{...s,error:f.error});try{y(i)}catch{}return{ok:!1,error:`not sent: ${f.error}`}}o.status="sent",delete o.error}u(a(t,e),o);try{y(i)}catch{}return{ok:!0,draft:o}}$();function l(t,e){return(t??"").replace(/\$\{(\w+)\}/g,(r,n)=>e[n]??"")}function P(t,e=process.env){let r={host:t.imap.host,port:t.imap.port,secure:t.imap.secure,user:l(t.imap.user,e)||t.address,password:l(t.imap.password,e)},n={host:t.smtp.host,port:t.smtp.port,secure:t.smtp.secure,user:l(t.smtp.user,e)||r.user,password:l(t.smtp.password,e)||r.password};return{imap:r,smtp:n}}async function R(t,e,r,n=process.env){let{smtp:s}=P(t,n);if(!s.password)throw new Error(`no SMTP password for ${t.address}: set it in .env`);return J(s,{name:e,address:t.address},r,{"Auto-Submitted":"auto-replied"})}async function J(t,e,r,n){let{default:s}=await import("nodemailer"),i=s.createTransport({host:t.host,port:t.port,secure:t.secure,auth:{user:t.user,pass:t.password},connectionTimeout:2e4,greetingTimeout:2e4,socketTimeout:6e4});try{return(await i.sendMail({from:e,to:r.toName?{name:r.toName,address:r.to}:r.to,subject:r.subject,text:r.text,...r.inReplyTo?{inReplyTo:r.inReplyTo}:{},...r.references?{references:r.references}:{},headers:n})).messageId}finally{i.close()}}function G(t,e){return async r=>{let n=t?.channels?.email?.accounts?.[r.account];if(!n)return{ok:!1,error:`no email account "${r.account}" in agentx.json`};let s=S.safeParse(n);if(!s.success)return{ok:!1,error:`email account "${r.account}": ${s.error.issues[0]?.message}`};let i=s.data,d=i.name||t?.agents?.[r.agent]?.name||r.agent;return await R(i,d,{to:r.to,toName:r.to_name,subject:r.subject,inReplyTo:r.in_reply_to,references:r.references,text:r.text},e),{ok:!0}}}export{I as a,L as b,z as c,B as d,U as e,v as f,V as g,W as h,P as i,R as j,J as k,G as l};
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
3
|
+
//# sourceMappingURL=chunk-6U34GZ7U.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as E}from"./chunk-IMLAPB7G.js";import{
|
|
1
|
+
import{a as E}from"./chunk-IMLAPB7G.js";import{d as se}from"./chunk-QPABR72X.js";import{b as ae}from"./chunk-KP7KDLZ2.js";import{n as x}from"./chunk-XL7UWG36.js";import{ia as ne,ja as re,la as oe,ma as ie,sa as I,xa as Je}from"./chunk-CARVBJB7.js";import{accessSync as Qe,closeSync as Ye,constants as Ze,existsSync as pe,openSync as et,readFileSync as tt,readSync as nt,statSync as rt}from"node:fs";import{dirname as T,join as C}from"node:path";import{fileURLToPath as ot}from"node:url";import{homedir as it}from"node:os";import{join as ue,win32 as F}from"path";function $(e){return e==="darwin"?"macos":e==="win32"?"windows":null}var j="agentx-helper.exe";function Ke(e){return F.join(e,"Programs","AgentX",j)}var le="AgentX Helper.app";function B(e){return ue(e,"Applications",le,"Contents/MacOS/agentx-mac-helper")}function ze(e,t){let n=t.AGENTX_DESKTOP_HELPER?.trim();if(n)return n;let r=t.AGENTX_MAC_HELPER?.trim();return r&&$(e)==="macos"?r:void 0}function ce(e){let t=ze(e.platform,e.env);if(t)return t;let n=$(e.platform);if(n==="macos"){let r=B(e.home);return e.exists(r)||!e.root?r:ue(e.root,"apps/mac-helper/build",le,"Contents/MacOS/agentx-mac-helper")}if(n==="windows"){let r=e.env.LOCALAPPDATA||F.join(e.home,"AppData","Local"),o=Ke(r);return e.exists(o)||!e.root?o:F.join(e.root,"apps","win-helper","build",j)}return null}function Ve(e){let t=$(e);return t==="macos"?"Run agentx desktop install (or build it with apps/mac-helper/build.sh).":t==="windows"?`Put ${j} in %LOCALAPPDATA%\\Programs\\AgentX, or set AGENTX_DESKTOP_HELPER to its path.`:"AgentX has no desktop helper for this system yet."}function Xt(e){let t=$(e);if(t==="macos")return"helper not built \u2014 run apps/mac-helper/build.sh (or agentx desktop install)";if(t==="windows"){let n=Ve(e);return`Windows helper not found \u2014 ${n[0].toLowerCase()}${n.slice(1,-1)}`}return`computer use (point, teach, act) is not available on ${e} yet \u2014 macOS now, Windows in progress (#1594)`}var X="tn.acme.agentx.voice",Yt="AgentX Desktop.app",Zt="AgentX Helper.app";function en(e,t,n){return e!=="darwin"||t!=="arm64"||Number(n.split(".")[0])<23?"AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.":null}function tn(e,t){if(t&&!Object.hasOwn(e,t))throw new Error(`Unknown agent: ${t}. Run agentx agent list.`);let n=t||Object.keys(e)[0];if(!n)throw new Error("No agents configured. Run agentx setup first.");return n}function U(e){return`'${e.replace(/'/g,"'\\''")}'`}var de="/usr/bin:/bin:/usr/sbin:/sbin";function nn(e,t){return t||[...new Set([...e?[T(e)]:[],...de.split(":")])].join(":")}function O(e){let t={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};return e.replace(/&(amp|lt|gt|quot|apos);/g,(n,r)=>t[r])}function rn(e){let t=e.match(/<key>PATH<\/key>\s*<string>([^<]*)<\/string>/);return t?O(t[1]):de}var on=e=>/agentx\.voice.*\.plist$/.test(e);function sn(e,t){let n=null,r=[];for(let{file:o,plist:i}of[...t].sort((s,l)=>s.file<l.file?-1:1)){let s=i.match(/<key>Label<\/key>\s*<string>([^<]*)<\/string>/)?.[1],l=i.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/)?.[1];!s||!l||!O(l).endsWith("/Contents/MacOS/AgentXVoice")||(n?r.push({file:o,label:O(s)}):n={file:o,label:O(s)})}return{keep:n??{file:C(e,`${X}.plist`),label:X},remove:r}}function me(e,t,n){for(let r of t.split(":"))if(r&&n(C(r,e)))return C(r,e);return null}function an(e){try{if(Qe(e,Ze.X_OK),!rt(e).isFile())return!1;let t=et(e,"r"),n=Buffer.alloc(2);try{nt(t,n,0,2,0)}finally{Ye(t)}return n.toString("latin1")!=="#!"}catch{return!1}}function un(e){let t=r=>r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),n={PATH:e.path,...e.agent?{AGENTX_VOICE_AGENT:e.agent}:{},AGENTX_DAEMON_URL:e.url,AGENTX_MAC_HELPER:e.helper,AGENTX_PASTE_COMMAND:`cd ${U(e.cwd)} && ${U(e.node)} ${U(e.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
2
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
3
3
|
<plist version="1.0"><dict>
|
|
4
4
|
<key>Label</key><string>${t(e.label??X)}</string>
|
|
@@ -35,4 +35,4 @@ function run(argv) {
|
|
|
35
35
|
`),Dt(r,n)}var Ft=5*6e4;function Wr(e,t,n=Date.now()){let r=ee(e),o=r.checkedAt?Date.parse(r.checkedAt):NaN;return!r.cards||!(n-o<=Ft)?!1:r.items[`card:${t}`]?.state!=="failed"}var te=24*36e5;function Ue(e,t,n){let r=e+t.dueAfterMinutes*6e4;return new Date(n!==void 0&&Number.isFinite(n)?Math.max(e,Math.min(r,n)):r)}function jt(e,t,n,r){let o=Date.parse(e.expires),i=[w(e.ask,x.ask)];return e.choices?.length&&i.push(...e.choices.map((s,l)=>`${l+1}. ${s}`)),e.recommend&&i.push(`Recommended: ${w(e.recommend,x.recommend)}`),i.push(`Answer: ${n}`,`agentx: card=${e.id}`),{key:`card:${e.id}`,title:w(e.title,x.title),notes:i.join(`
|
|
36
36
|
`),due:Ue(r,t,o),priority:Number.isFinite(o)&&o-r<=te?"high":"none"}}function Bt(e,t,n,r){let o=[w(e.question||e.text,x.ask),`Asked of ${e.agentId}.`,`Answer: ${n}`,`agentx: request=${e.id}`],i=e.dueAt??void 0;return{key:`request:${e.id}`,title:Y(e,x.title).headline,notes:o.join(`
|
|
37
37
|
`),due:Ue(r,t,i),priority:i!==void 0&&i-r<=te?"high":"none"}}async function qr(e){let{root:t,settings:n,tasks:r,log:o}=e,i=e.now??Date.now(),s=new Date(i).toISOString(),l={created:0,completed:0,dismissed:0,failed:0},a=ee(t);delete a.lastError;let c=u=>{a.lastError={at:s,message:u}},g=new Map;try{if(n.include.includes("card"))for(let u of e.cards())u.status==="pending"&&Date.parse(u.expires)>i&&g.set(`card:${u.id}`,jt(u,n,e.answerUrl,i));if(n.include.includes("request"))for(let u of e.requests())u.state==="waiting_owner"&&g.set(`request:${u.id}`,Bt(u,n,e.answerUrl,i))}catch(u){return o(`[mirror] could not read what is waiting: ${u?.message??u}`),c(String(u?.message??u)),Fe(t,a),l}let D=!0,h=new Map,Xe=async u=>{if(!h.has(u))try{h.set(u,new Set((await r.listOpen(u)).map(p=>p.id)))}catch(p){o(`[mirror] could not read list "${u}": ${p?.message??p}`),c(String(p?.message??p)),h.set(u,null),D=!1}return h.get(u)};for(let[u,p]of Object.entries(a.items)){if(p.state!=="open"||!p.id)continue;let d=await Xe(p.list);if(d)if(g.has(u))d.has(p.id)||(a.items[u]={...p,state:"dismissed",at:s},l.dismissed++,o(`[mirror] ${u}: its task was ticked off or deleted; it stays on the Desk and is not mirrored again`));else{if(d.has(p.id))try{await r.complete(p.id)}catch(S){o(`[mirror] ${u}: could not complete its task: ${S?.message??S}`),c(String(S?.message??S));continue}a.items[u]={...p,state:"completed",at:s},l.completed++}}let R=null,W="",q=0,v=[];for(let[u,p]of g){let d=a.items[u];if(d&&(d.state==="open"||d.state==="dismissed")||d?.state==="failed"&&d.failures>=Z)continue;if(R===null)try{await r.ensureList(n.list),R=!0}catch(f){o(`[mirror] could not make list "${n.list}": ${f?.message??f}`),W=String(f?.message??f),c(W),R=!1}let S=d?.state==="failed"?d.failures:0;try{if(R===!1)throw new Error(W);let{id:f}=await r.add({list:n.list,title:p.title,notes:p.notes,due:p.due,priority:p.priority});a.items[u]={id:f,list:n.list,state:"open",at:s,createdAt:s,failures:0},l.created++}catch(f){let P=String(f?.message??f);u.startsWith("card:")&&q++;let H=S+1;a.items[u]={list:n.list,state:"failed",at:s,failures:H,lastError:P},c(P),l.failed++,o(`[mirror] ${u}: could not add to Reminders (${H}/${Z}): ${P}`),H===Z&&v.push({title:p.title,message:P})}}q&&o(`[mirror] ${q} card(s) could not be added to Reminders; the Mac popup shows them instead`);let Ge=a.failureToldAt?Date.parse(a.failureToldAt):NaN;if(v.length&&!(i-Ge<te)){let u=v[0],p=v.length>1?` (and ${v.length-1} more)`:"";try{await e.notify("Could not add to Reminders",`${u.title}${p}: ${w(u.message,200)}. Still on the Desk.`),a.failureToldAt=s}catch(d){o(`[mirror] could not tell the owner: ${d?.message??d}`)}}D&&(a.checkedAt=s,a.cards=n.include.includes("card"));for(let[u,p]of Object.entries(a.items))p.state!=="open"&&!g.has(u)&&i-Date.parse(p.at)>Ht&&delete a.items[u];return Fe(t,a),l}var je=5*6e4;function Hr(e,t,n,r,o=Date.now()){let i=ee(e),s=a=>{let c=a?Date.parse(a):NaN;return c>=n&&c<r},l={from:new Date(n).toISOString(),to:new Date(r).toISOString(),raised:0,created:{cards:0,requests:0},missed:[],closedFast:0,tooNew:0};for(let[a,c]of Object.entries(i.items))!c.id||!s(c.createdAt)||(a.startsWith("card:")?l.created.cards++:l.created.requests++);for(let a of t){if(!s(a.created_at))continue;l.raised++;let c=i.items[`card:${a.id}`];if(c?.id)continue;let g=Date.parse(a.created_at);if((a.status==="pending"?NaN:Date.parse(a.decided_at??""))-g<=je){l.closedFast++;continue}if(a.status==="pending"&&o-g<=je){l.tooNew++;continue}let h=c?.state==="failed"?`could not be added (${c.failures}x): ${c.lastError??"unknown error"}`:"no pass reached it";l.missed.push({id:a.id,title:a.title,reason:h})}return l}function Fr(e){let t=[e.closedFast?`closed within 5 min: ${e.closedFast}`:"",e.tooNew?`raised in the last 5 min: ${e.tooNew}`:""].filter(Boolean);return`cards raised ${e.raised} / Reminders created ${e.created.cards+e.created.requests} (${e.created.cards} cards, ${e.created.requests} requests) / missed ${e.missed.length}${t.length?` \xB7 ${t.join(" \xB7 ")}`:""}`}export{Nr as a,Me as b,V as c,Q as d,Ar as e,br as f,Tt as g,vr as h,kr as i,Rr as j,Y as k,w as l,Ct as m,Or as n,$ as o,ce as p,Ve as q,Xt as r,Yt as s,Zt as t,en as u,tn as v,nn as w,rn as x,on as y,sn as z,me as A,an as B,un as C,ln as D,cn as E,st as F,k as G,Se as H,z as I,Le as J,fr as K,gr as L,yr as M,ee as N,Wr as O,qr as P,Hr as Q,Fr as R};
|
|
38
|
-
//# sourceMappingURL=chunk-
|
|
38
|
+
//# sourceMappingURL=chunk-6ZVVAGTR.js.map
|