agentix-cli 0.151.0 → 0.152.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{App-WAWZFD66.js → App-NCB3Y5DS.js} +2 -2
- package/dist/{ChatApp-TRJIS3O4.js → ChatApp-HOWN5H7Y.js} +2 -2
- package/dist/{absorb-eval-CFWLHUTB.js → absorb-eval-JXRNSZII.js} +2 -2
- package/dist/agent-DMXUUMEU.js +2 -0
- package/dist/{board-dashboard-5V6RHW3E.js → board-dashboard-POWARL34.js} +402 -241
- package/dist/board-dashboard-POWARL34.js.map +1 -0
- package/dist/{chunk-X6C6U4GL.js → chunk-24QMHUU2.js} +5 -5
- package/dist/{chunk-X6C6U4GL.js.map → chunk-24QMHUU2.js.map} +1 -1
- package/dist/{chunk-ALE354ZC.js → chunk-7UH3DXAG.js} +2 -2
- package/dist/chunk-ADG6NBZY.js +862 -0
- package/dist/chunk-ADG6NBZY.js.map +1 -0
- package/dist/{chunk-IMITYHBT.js → chunk-CZEBLLZQ.js} +2 -2
- package/dist/{chunk-XD7HTMOP.js → chunk-DZUJP6L7.js} +2 -2
- package/dist/{chunk-TZZBGWLX.js → chunk-E4V5EADX.js} +6 -6
- package/dist/{chunk-XVJXXELY.js → chunk-GI5CY27P.js} +2 -2
- package/dist/{chunk-LVS5ESTS.js → chunk-HS7ATV4Z.js} +2 -2
- package/dist/{chunk-RGJZV5RY.js → chunk-ILZRO6SN.js} +2 -2
- package/dist/{chunk-UG2OF2EI.js → chunk-IVBCCSDR.js} +2 -2
- package/dist/{chunk-V3VWYIJ3.js → chunk-JDX7AYIB.js} +2 -2
- package/dist/{chunk-PUSBK2OQ.js → chunk-JHAQE46R.js} +46 -46
- package/dist/chunk-JHAQE46R.js.map +1 -0
- package/dist/chunk-JJOLZPUY.js +35 -0
- package/dist/chunk-JJOLZPUY.js.map +1 -0
- package/dist/{chunk-2PJKGZWP.js → chunk-JNG3P5V2.js} +2 -2
- package/dist/chunk-JNG3P5V2.js.map +1 -0
- package/dist/{chunk-2GJQDJBF.js → chunk-LDLRDBAD.js} +2 -2
- package/dist/{chunk-DJQIJF4R.js → chunk-LOTCKF22.js} +2 -2
- package/dist/{chunk-O7SYQXKS.js → chunk-MTBY46CL.js} +8 -8
- package/dist/{chunk-FGJNSYHM.js → chunk-P25TJ4XN.js} +3 -3
- package/dist/{chunk-6LFOX6Q5.js → chunk-P4EZJIQ4.js} +257 -256
- package/dist/chunk-P4EZJIQ4.js.map +1 -0
- package/dist/{chunk-X3T2GCSI.js → chunk-PC24JMEH.js} +2 -2
- package/dist/{chunk-EJTKLVIW.js → chunk-PGLTBNGZ.js} +2 -2
- package/dist/{chunk-4GXJMHSA.js → chunk-QSNKF5VD.js} +2 -2
- package/dist/{chunk-DFGANY25.js → chunk-R4R7EYY3.js} +2 -2
- package/dist/{chunk-Q5NLNLD5.js → chunk-RNAKP7WY.js} +2 -2
- package/dist/{chunk-L6IW6HWE.js → chunk-SQUTRMKH.js} +23 -20
- package/dist/chunk-SQUTRMKH.js.map +1 -0
- package/dist/{chunk-C5UTFHPB.js → chunk-TNZBQAUR.js} +2 -2
- package/dist/{chunk-Y5MFVVTM.js → chunk-U23LVMMZ.js} +2 -2
- package/dist/{chunk-YGDJV4ZZ.js → chunk-UFYKUC4E.js} +2 -2
- package/dist/{chunk-CTQ25CUL.js → chunk-VIZVF6KH.js} +2 -2
- package/dist/{chunk-ETBDN5WX.js → chunk-XE3CGJV4.js} +2 -2
- package/dist/{chunk-UALK4F3W.js → chunk-YBUCVI45.js} +2 -2
- package/dist/{chunk-DWXCZRBJ.js → chunk-YJZQRFET.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-VT7GT3SK.js → client-6IOWB5AT.js} +2 -2
- package/dist/{compaction-FS6XNRLM.js → compaction-PFXWL4H7.js} +3 -3
- package/dist/{config-NZS2UTHI.js → config-SHIT5WJE.js} +2 -2
- package/dist/{config-mutate-LINLC354.js → config-mutate-6ACI5COM.js} +2 -2
- package/dist/config-mutator-LAEX6HOH.js +2 -0
- package/dist/{context-planner-3JDA7FNR.js → context-planner-DJB6CKY6.js} +2 -2
- package/dist/{contributions-67B3BYLV.js → contributions-N7K6LNL7.js} +2 -2
- package/dist/{doctor-FOKX4K2G.js → doctor-T7QAQRCJ.js} +2 -2
- package/dist/{follow-up-tool-JOIOYOON.js → follow-up-tool-HQ2GWF4K.js} +2 -2
- package/dist/{grants-QXF7N6SS.js → grants-HSLB62EG.js} +2 -2
- package/dist/heal-RGM7X2ZG.js +2 -0
- package/dist/hub-53IMEYGX.js +2 -0
- package/dist/index.d.ts +125 -6
- package/dist/index.js +1 -1
- package/dist/memory-extract-GHLBXV4H.js +2 -0
- package/dist/{program-XFZBG3EI.js → program-LSXONKPW.js} +225 -219
- package/dist/program-LSXONKPW.js.map +1 -0
- package/dist/{promote-WNYNTGKC.js → promote-626PE5VM.js} +2 -2
- package/dist/{providers-55NC2SFN.js → providers-BDJXGHEY.js} +2 -2
- package/dist/{query-ZU2DDCEH.js → query-GR3SOD6A.js} +2 -2
- package/dist/{query-settings-BXRIJWWO.js → query-settings-6XZHNFXE.js} +2 -2
- package/dist/{registry-7BITIEQ2.js → registry-SAY7ROZV.js} +2 -2
- package/dist/{request-planner-DLQP2NV6.js → request-planner-DWYXUVF4.js} +2 -2
- package/dist/{review-candidates-3BMHLIBW.js → review-candidates-GXWMKZKA.js} +2 -2
- package/dist/routing-TB6BBRH4.js +2 -0
- package/dist/schedule-tool-EI2SRMZM.js +2 -0
- package/dist/{scheduler-SYI5MZ3H.js → scheduler-VOZIMG5F.js} +2 -2
- package/dist/{seat-6JF7BYM7.js → seat-H6F6H55Y.js} +2 -2
- package/dist/{select-JT4I3JOH.js → select-OUBL6EMZ.js} +2 -2
- package/dist/{set-enabled-JRGFKA3S.js → set-enabled-NYJHFXHY.js} +2 -2
- package/dist/tool-FWATXW5Q.js +6 -0
- package/dist/tool-FWATXW5Q.js.map +1 -0
- package/dist/{tool-P6GVYNDO.js → tool-HXFGNBLS.js} +2 -2
- package/dist/wiki-PG5ZBOMH.js +2 -0
- package/dist/wiki-enrich-BIQZWJRB.js +2 -0
- package/package.json +1 -1
- package/dist/agent-6KCTPI7E.js +0 -2
- package/dist/board-dashboard-5V6RHW3E.js.map +0 -1
- package/dist/chunk-2PJKGZWP.js.map +0 -1
- package/dist/chunk-5I7NJMK6.js +0 -35
- package/dist/chunk-5I7NJMK6.js.map +0 -1
- package/dist/chunk-6LFOX6Q5.js.map +0 -1
- package/dist/chunk-CBML7UCP.js +0 -861
- package/dist/chunk-CBML7UCP.js.map +0 -1
- package/dist/chunk-L6IW6HWE.js.map +0 -1
- package/dist/chunk-PUSBK2OQ.js.map +0 -1
- package/dist/config-mutator-FUMSW5HD.js +0 -2
- package/dist/heal-U67X6NIN.js +0 -2
- package/dist/hub-QETWDYPD.js +0 -2
- package/dist/memory-extract-ATD6YLRK.js +0 -2
- package/dist/program-XFZBG3EI.js.map +0 -1
- package/dist/routing-FVZCQJ6T.js +0 -2
- package/dist/schedule-tool-TDVJHRQX.js +0 -2
- package/dist/tool-UDOUNWQT.js +0 -6
- package/dist/tool-UDOUNWQT.js.map +0 -1
- package/dist/wiki-MTZHDFHK.js +0 -2
- package/dist/wiki-enrich-CHR4RCRE.js +0 -2
- /package/dist/{App-WAWZFD66.js.map → App-NCB3Y5DS.js.map} +0 -0
- /package/dist/{ChatApp-TRJIS3O4.js.map → ChatApp-HOWN5H7Y.js.map} +0 -0
- /package/dist/{absorb-eval-CFWLHUTB.js.map → absorb-eval-JXRNSZII.js.map} +0 -0
- /package/dist/{agent-6KCTPI7E.js.map → agent-DMXUUMEU.js.map} +0 -0
- /package/dist/{chunk-ALE354ZC.js.map → chunk-7UH3DXAG.js.map} +0 -0
- /package/dist/{chunk-IMITYHBT.js.map → chunk-CZEBLLZQ.js.map} +0 -0
- /package/dist/{chunk-XD7HTMOP.js.map → chunk-DZUJP6L7.js.map} +0 -0
- /package/dist/{chunk-TZZBGWLX.js.map → chunk-E4V5EADX.js.map} +0 -0
- /package/dist/{chunk-XVJXXELY.js.map → chunk-GI5CY27P.js.map} +0 -0
- /package/dist/{chunk-LVS5ESTS.js.map → chunk-HS7ATV4Z.js.map} +0 -0
- /package/dist/{chunk-RGJZV5RY.js.map → chunk-ILZRO6SN.js.map} +0 -0
- /package/dist/{chunk-UG2OF2EI.js.map → chunk-IVBCCSDR.js.map} +0 -0
- /package/dist/{chunk-V3VWYIJ3.js.map → chunk-JDX7AYIB.js.map} +0 -0
- /package/dist/{chunk-2GJQDJBF.js.map → chunk-LDLRDBAD.js.map} +0 -0
- /package/dist/{chunk-DJQIJF4R.js.map → chunk-LOTCKF22.js.map} +0 -0
- /package/dist/{chunk-O7SYQXKS.js.map → chunk-MTBY46CL.js.map} +0 -0
- /package/dist/{chunk-FGJNSYHM.js.map → chunk-P25TJ4XN.js.map} +0 -0
- /package/dist/{chunk-X3T2GCSI.js.map → chunk-PC24JMEH.js.map} +0 -0
- /package/dist/{chunk-EJTKLVIW.js.map → chunk-PGLTBNGZ.js.map} +0 -0
- /package/dist/{chunk-4GXJMHSA.js.map → chunk-QSNKF5VD.js.map} +0 -0
- /package/dist/{chunk-DFGANY25.js.map → chunk-R4R7EYY3.js.map} +0 -0
- /package/dist/{chunk-Q5NLNLD5.js.map → chunk-RNAKP7WY.js.map} +0 -0
- /package/dist/{chunk-C5UTFHPB.js.map → chunk-TNZBQAUR.js.map} +0 -0
- /package/dist/{chunk-Y5MFVVTM.js.map → chunk-U23LVMMZ.js.map} +0 -0
- /package/dist/{chunk-YGDJV4ZZ.js.map → chunk-UFYKUC4E.js.map} +0 -0
- /package/dist/{chunk-CTQ25CUL.js.map → chunk-VIZVF6KH.js.map} +0 -0
- /package/dist/{chunk-ETBDN5WX.js.map → chunk-XE3CGJV4.js.map} +0 -0
- /package/dist/{chunk-UALK4F3W.js.map → chunk-YBUCVI45.js.map} +0 -0
- /package/dist/{chunk-DWXCZRBJ.js.map → chunk-YJZQRFET.js.map} +0 -0
- /package/dist/{client-VT7GT3SK.js.map → client-6IOWB5AT.js.map} +0 -0
- /package/dist/{compaction-FS6XNRLM.js.map → compaction-PFXWL4H7.js.map} +0 -0
- /package/dist/{config-NZS2UTHI.js.map → config-SHIT5WJE.js.map} +0 -0
- /package/dist/{config-mutate-LINLC354.js.map → config-mutate-6ACI5COM.js.map} +0 -0
- /package/dist/{config-mutator-FUMSW5HD.js.map → config-mutator-LAEX6HOH.js.map} +0 -0
- /package/dist/{context-planner-3JDA7FNR.js.map → context-planner-DJB6CKY6.js.map} +0 -0
- /package/dist/{contributions-67B3BYLV.js.map → contributions-N7K6LNL7.js.map} +0 -0
- /package/dist/{doctor-FOKX4K2G.js.map → doctor-T7QAQRCJ.js.map} +0 -0
- /package/dist/{follow-up-tool-JOIOYOON.js.map → follow-up-tool-HQ2GWF4K.js.map} +0 -0
- /package/dist/{grants-QXF7N6SS.js.map → grants-HSLB62EG.js.map} +0 -0
- /package/dist/{heal-U67X6NIN.js.map → heal-RGM7X2ZG.js.map} +0 -0
- /package/dist/{hub-QETWDYPD.js.map → hub-53IMEYGX.js.map} +0 -0
- /package/dist/{memory-extract-ATD6YLRK.js.map → memory-extract-GHLBXV4H.js.map} +0 -0
- /package/dist/{promote-WNYNTGKC.js.map → promote-626PE5VM.js.map} +0 -0
- /package/dist/{providers-55NC2SFN.js.map → providers-BDJXGHEY.js.map} +0 -0
- /package/dist/{query-ZU2DDCEH.js.map → query-GR3SOD6A.js.map} +0 -0
- /package/dist/{query-settings-BXRIJWWO.js.map → query-settings-6XZHNFXE.js.map} +0 -0
- /package/dist/{registry-7BITIEQ2.js.map → registry-SAY7ROZV.js.map} +0 -0
- /package/dist/{request-planner-DLQP2NV6.js.map → request-planner-DWYXUVF4.js.map} +0 -0
- /package/dist/{review-candidates-3BMHLIBW.js.map → review-candidates-GXWMKZKA.js.map} +0 -0
- /package/dist/{routing-FVZCQJ6T.js.map → routing-TB6BBRH4.js.map} +0 -0
- /package/dist/{schedule-tool-TDVJHRQX.js.map → schedule-tool-EI2SRMZM.js.map} +0 -0
- /package/dist/{scheduler-SYI5MZ3H.js.map → scheduler-VOZIMG5F.js.map} +0 -0
- /package/dist/{seat-6JF7BYM7.js.map → seat-H6F6H55Y.js.map} +0 -0
- /package/dist/{select-JT4I3JOH.js.map → select-OUBL6EMZ.js.map} +0 -0
- /package/dist/{set-enabled-JRGFKA3S.js.map → set-enabled-NYJHFXHY.js.map} +0 -0
- /package/dist/{tool-P6GVYNDO.js.map → tool-HXFGNBLS.js.map} +0 -0
- /package/dist/{wiki-MTZHDFHK.js.map → wiki-PG5ZBOMH.js.map} +0 -0
- /package/dist/{wiki-enrich-CHR4RCRE.js.map → wiki-enrich-BIQZWJRB.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{La as m,Ua as b}from"./chunk-
|
|
1
|
+
import{La as m,Ua as b}from"./chunk-SQUTRMKH.js";b();function w(t){let e=typeof t.node=="string"?t.node:"",n=typeof t.token=="string"?t.token:"";if(!e||!n)try{let o=m(t.config);e||(e=o.dashboard?.daemonUrl||""),n||(n=o.dashboard?.token||"")}catch{}return e||(e="http://localhost:18800"),{baseUrl:e.replace(/\/+$/,""),token:n}}async function d(t,e,n){let o={Accept:"application/json"};t.token&&(o.Authorization=`Bearer ${t.token}`);let r=await fetch(`${t.baseUrl}${e}`,{headers:o,signal:n});if(!r.ok)throw new Error(`GET ${e} \u2192 HTTP ${r.status}`);return await r.json()}function R(t,e){return d(t,"/agents",e)}async function S(t,e){return(await d(t,"/api/processes",e)).processes??[]}function P(t,e){return d(t,"/crons",e)}async function h(t,e,n,o){let r={Accept:"application/json","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(n),signal:o}),a=await s.text(),i;try{i=a?JSON.parse(a):{}}catch{i={raw:a}}if(!s.ok)throw new Error(i?.error||`POST ${e} \u2192 HTTP ${s.status}`);return i}function A(t,e,n="tui"){return h(t,"/api/processes/kill",{...e,reason:n})}function C(t,e,n,o){return h(t,"/task",{agent:e,message:n,context:o??{channel:"tui",chatId:"tui:operator"}})}async function $(t,e,n,o={}){let r={Accept:"text/event-stream","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}/task`,{method:"POST",headers:r,body:JSON.stringify({agent:e,message:n,stream:!0,context:{channel:o.channel??"chat-cli",chatId:o.chatId??"chat-cli:operator"}}),signal:o.signal});if(!s.ok||!s.body){let g=await s.text().catch(()=>"");throw new Error(`POST /task (stream) \u2192 HTTP ${s.status}${g?`: ${g.slice(0,200)}`:""}`)}let a=s.body.getReader(),i=new TextDecoder,u={content:""},c="";try{for(;;){let{done:g,value:p}=await a.read();if(g)break;c+=i.decode(p,{stream:!0});let l;for(;(l=c.indexOf(`
|
|
2
2
|
|
|
3
3
|
`))>=0;){let k=c.slice(0,l);c=c.slice(l+2);let f=x(k);f&&T(f,o,u)}}}finally{try{a.releaseLock()}catch{}}return u}function T(t,e,n){let{event:o,data:r}=t;switch(o){case"text":r?.text&&(n.content+=r.text,e.onText?.(r.text));break;case"thinking":r?.text&&e.onThinking?.(r.text);break;case"tool":e.onTool?.(r);break;case"done":typeof r?.content=="string"&&(n.content=r.content),n.usage=r?.usage,n.duration=r?.duration;break;case"error":n.error=r?.error,n.errorKind=r?.errorKind;break}}function x(t){let e="message",n="";for(let r of t.split(`
|
|
4
4
|
`))r.startsWith("event: ")?e=r.slice(7).trim():r.startsWith("data: ")&&(n=r.slice(6));if(!n)return null;let o;try{o=JSON.parse(n)}catch{o=n}return{event:e,data:o}}export{w as a,R as b,S as c,P as d,A as e,C as f,$ as g};
|
|
5
|
-
//# sourceMappingURL=chunk-
|
|
5
|
+
//# sourceMappingURL=chunk-CZEBLLZQ.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as h}from"./chunk-
|
|
1
|
+
import{a as h}from"./chunk-YJZQRFET.js";import{resolve as n}from"path";import{existsSync as c,readdirSync as u,mkdirSync as l,readFileSync as p,writeFileSync as f,renameSync as S}from"fs";var m=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(e=n(process.cwd(),".agentx/wiki"),r=console.error.bind(console,"[wiki-hub]"),t="graph"){this.baseDir=e,this.agentsDir=n(e,"agents"),this.mode=t,this.log=r,l(this.agentsDir,{recursive:!0}),this.sharedStore=new h(e,r)}getMode(){return this.mode}getAgentWiki(e){let r=`${e}:${this.mode}`;if(this.agentStores.has(r))return this.agentStores.get(r);let t=n(this.agentsDir,e,this.mode),s=new h(t,this.log);return this.agentStores.set(r,s),s}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}sharedScope(e){return[...this.listAgentDirs().filter(t=>t!==e).map(t=>({id:t,store:this.getAgentWiki(t)})),{id:"shared",store:this.sharedStore,skip:t=>t.startsWith("agents/")}]}listAgentDirs(){return c(this.agentsDir)?u(this.agentsDir).filter(e=>!e.startsWith("_")&&!e.startsWith(".")&&c(n(this.agentsDir,e,this.mode))).sort():[]}listAgents(e=this.sharedStore.listEntries()){let r=new Set;for(let t of e)r.add(t.agentId);if(c(this.agentsDir))for(let t of u(this.agentsDir))!t.startsWith("_")&&!t.startsWith(".")&&r.add(t);return[...r].sort()}getAgentEntries(e){return this.sharedStore.listEntries({agentId:e})}getUnabsorbedEntries(e){return this.classifyEntries(e).pending}markProcessed(e,r,t){let s=new Set(t),g=this.readLedger(e),d=new Date().toISOString();for(let i of r)g.entries[i]={at:d,cited:s.has(i)};let o=this.ledgerPath(e);l(n(o,".."),{recursive:!0});let a=`${o}.tmp`;f(a,`${JSON.stringify(g,null,2)}
|
|
2
2
|
`),S(a,o)}summary(){let e=this.sharedStore.listEntries(),r=new Map;for(let t of e){let s=r.get(t.agentId);s?s.push(t):r.set(t.agentId,[t])}return this.listAgents(e).map(t=>{let{all:s,cited:g,read:d,pending:o,articles:a}=this.classifyEntries(t,r.get(t)??[]);return{agentId:t,totalEntries:s.length,totalArticles:a.length,cited:g.length,readNotCited:d.length,unabsorbed:o.length,articles:a}})}classifyEntries(e,r=this.getAgentEntries(e)){let t=this.getAgentWiki(e).rebuildIndex().articles,s=new Set;for(let i of t)if(i.sources)for(let y of i.sources)s.add(y);let g=this.readLedger(e).entries,d=[],o=[],a=[];for(let i of r)s.has(i.id)?d.push(i):g[i.id]?o.push(i):a.push(i);return{all:r,cited:d,read:o,pending:a,articles:t}}syncedFrom(e){let r=n(this.agentsDir,e,"_synced.json");if(!c(r))return null;try{return JSON.parse(p(r,"utf-8"))}catch(t){return this.log(`synced marker ${r} is not valid JSON: ${t.message}`),{node:"unknown",peerUrl:"",at:""}}}markSynced(e,r){let t=n(this.agentsDir,e,"_synced.json");l(n(t,".."),{recursive:!0});let s=`${t}.tmp`;f(s,`${JSON.stringify(r,null,2)}
|
|
3
3
|
`),S(s,t)}ledgerPath(e){return n(this.agentsDir,e,"_absorbed.json")}readLedger(e){let r=this.ledgerPath(e);if(!c(r))return{entries:{}};try{return{entries:JSON.parse(p(r,"utf-8")).entries??{}}}catch(t){throw new Error(`absorb ledger ${r} is not valid JSON: ${t.message}`)}}};export{m as a};
|
|
4
|
-
//# sourceMappingURL=chunk-
|
|
4
|
+
//# sourceMappingURL=chunk-DZUJP6L7.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Ge,b as Fe,c as Se}from"./chunk-SFQUP3BP.js";import{b as Te,c as Ce}from"./chunk-QOYAX2FT.js";import{a as Q,c as Ne,e as we,f as ke,g as be,i as xe,k as gt,o as ve,p as ht}from"./chunk-
|
|
1
|
+
import{a as Ge,b as Fe,c as Se}from"./chunk-SFQUP3BP.js";import{b as Te,c as Ce}from"./chunk-QOYAX2FT.js";import{a as Q,c as Ne,e as we,f as ke,g as be,i as xe,k as gt,o as ve,p as ht}from"./chunk-JNG3P5V2.js";import{a as R,b as ye}from"./chunk-7I7IEX4S.js";import{b as Le,e as _e}from"./chunk-JHCI6XCJ.js";import{e as b}from"./chunk-DSYKYZMT.js";import{z as $}from"zod";var qe=$.object({provider:$.enum(["claude-code","claude","openai","deepseek","ollama","demo","custom"]).default("claude-code"),model:$.string().optional(),apiKey:$.string().optional(),skills:$.array($.string()).default([]),output:$.object({dir:$.string().default("./generated")}).default({}),context7:$.object({enabled:$.boolean().default(!0),apiKey:$.string().optional()}).default({}),agentic:$.object({maxIterations:$.number().default(20),enabledTools:$.array($.string()).default(["create_files","ask_user","read_file","search_files","list_directory","run_command","edit_file"]),disabledTools:$.array($.string()).default([])}).default({})}),Vt=["component","page","api","website","document","script","config","skill","media","report","test","workflow","schema","email","diagram","auto"],Yt={component:"UI component (any framework)",page:"Full page or screen",api:"API endpoint, route handler, or service",website:"Multi-page website or app",document:"Markdown, documentation, or specification",script:"Standalone script or utility",config:"Configuration file or setup",skill:"Agent skill (SKILL.md format for skills.sh)",media:"Media generation prompt (image/audio/video description)",report:"Analysis report or audit",test:"Test suite, test fixtures, or test data",workflow:"CI/CD pipeline, GitHub Actions, or automation",schema:"Database schema, Zod validators, or GraphQL types",email:"Email template (React Email, MJML, HTML)",diagram:"Mermaid, D2, or PlantUML diagram",auto:"Auto-detect the best output type"};ht();ke();ke();import{existsSync as yt,promises as wt}from"fs";import K from"path";import kt from"fast-glob";var Be={"prisma/schema.prisma":{type:"prisma",category:"database"},"drizzle/schema.ts":{type:"drizzle",category:"database"},"schema.graphql":{type:"graphql",category:"api"},"schema.gql":{type:"graphql",category:"api"},"openapi.yaml":{type:"openapi",category:"api"},"openapi.json":{type:"openapi",category:"api"},"swagger.yaml":{type:"openapi",category:"api"},"swagger.json":{type:"openapi",category:"api"}};async function We(r){let e={},t=await kt.glob("**/*",{cwd:r,deep:4,ignore:["**/node_modules/**","**/dist/**","**/build/**","**/.next/**","**/target/**","**/__pycache__/**","**/vendor/**","**/.git/**"],onlyFiles:!0});for(let[s,i]of Object.entries(Be)){let c=t.find(a=>a.endsWith(s)||a===s);if(c&&i.category==="database"){let a=await Z(K.resolve(r,c));if(a){e.database={type:i.type,content:ce(a,3e3),tables:bt(a,i.type)};break}}}for(let[s,i]of Object.entries(Be)){let c=t.find(a=>a.endsWith(s)||a===s);if(c&&i.category==="api"){let a=await Z(K.resolve(r,c));if(a){e.api={type:i.type,content:ce(a,3e3)};break}}}if(!e.api){let s=t.find(i=>i.includes("trpc")&&(i.endsWith("router.ts")||i.endsWith("router.js")));if(s){let i=await Z(K.resolve(r,s));i&&(e.api={type:"trpc",content:ce(i,3e3)})}}let o=t.find(s=>s===".env.example"||s===".env.local.example"||s===".env.template");if(o){let s=await Z(K.resolve(r,o));s&&(e.env=xt(s))}let n=t.filter(s=>(s.includes("models")||s.includes("types")||s.includes("schemas"))&&(s.endsWith(".ts")||s.endsWith(".py")||s.endsWith(".rs")||s.endsWith(".go")));if(n.length){e.models=[];for(let s of n.slice(0,5)){let i=await Z(K.resolve(r,s));i&&e.models.push({path:s,content:ce(i,2e3),type:K.extname(s).slice(1)})}}return e}function bt(r,e){if(e==="prisma"){let t=r.match(/model\s+(\w+)\s*\{/g);return t?t.map(o=>o.replace(/model\s+/,"").replace(/\s*\{/,"")):[]}return[]}function xt(r){return{variables:r.split(`
|
|
2
2
|
`).filter(o=>o.trim()&&!o.trim().startsWith("#")).map(o=>{let[n]=o.split("="),s=n.trim(),i=o.includes("=")&&o.split("=")[1]?.trim().length>0;return{key:s,required:!i}})}}async function Z(r){try{return yt(r)?await wt.readFile(r,"utf8"):null}catch{return null}}function ce(r,e){return r.length<=e?r:r.slice(0,e)+`
|
|
3
3
|
... (truncated)`}function ze(r){let e=[];if(r.database&&e.push(`## Database Schema (${r.database.type})
|
|
4
4
|
`+(r.database.tables?.length?`Tables: ${r.database.tables.join(", ")}
|
|
@@ -18,7 +18,7 @@ ${s.join(`
|
|
|
18
18
|
---
|
|
19
19
|
|
|
20
20
|
`)}`:""}var Ye={component:{type:"component",baseDir:"src/components",filePatterns:["*.tsx","*.vue","*.svelte","*.jsx","*.ts"],description:"UI component"},page:{type:"page",baseDir:"src/app",filePatterns:["*.tsx","*.vue","*.svelte","*.jsx","*.astro"],description:"Page or screen"},api:{type:"api",baseDir:"src/api",filePatterns:["*.ts","*.js","*.py","*.go","*.rs"],description:"API route or endpoint"},website:{type:"website",baseDir:".",filePatterns:["*"],description:"Multi-file website"},document:{type:"document",baseDir:"docs",filePatterns:["*.md","*.mdx","*.txt","*.rst"],description:"Documentation"},script:{type:"script",baseDir:"scripts",filePatterns:["*.ts","*.js","*.py","*.sh","*.go"],description:"Standalone script"},config:{type:"config",baseDir:".",filePatterns:["*.json","*.yaml","*.yml","*.toml","*.env"],description:"Configuration file"},skill:{type:"skill",baseDir:".skills",filePatterns:["SKILL.md"],description:"Agent skill (SKILL.md)"},media:{type:"media",baseDir:"media",filePatterns:["*.md","*.json","*.txt"],description:"Media generation prompt/description"},report:{type:"report",baseDir:"reports",filePatterns:["*.md","*.html","*.json"],description:"Analysis report"},test:{type:"test",baseDir:"src",filePatterns:["*.test.ts","*.test.tsx","*.spec.ts","*.test.js","*.test.py","*.test.go"],description:"Test suite or fixture"},workflow:{type:"workflow",baseDir:".github/workflows",filePatterns:["*.yml","*.yaml"],description:"CI/CD pipeline or automation"},schema:{type:"schema",baseDir:"src",filePatterns:["*.ts","*.prisma","*.graphql","*.gql","*.py"],description:"Database schema, validators, or types"},email:{type:"email",baseDir:"src/emails",filePatterns:["*.tsx","*.jsx","*.html","*.mjml"],description:"Email template"},diagram:{type:"diagram",baseDir:"docs",filePatterns:["*.md","*.mmd","*.d2","*.puml"],description:"Architecture or data diagram"}};function Pe(r,e){if(r&&r!=="auto")return r;let t=e.toLowerCase(),o=[[/\b(component|button|card|modal|dialog|form|input|dropdown|nav|sidebar|header|footer|widget|ui)\b/i,"component"],[/\b(page|screen|view|route|layout|dashboard|landing)\b/i,"page"],[/\b(api|endpoint|route handler|rest|graphql|webhook|middleware|server)\b/i,"api"],[/\b(website|site|web app|landing page|portfolio|blog)\b/i,"website"],[/\b(document|doc|readme|guide|tutorial|specification|spec|changelog)\b/i,"document"],[/\b(script|cli|command|tool|utility|migration|seed|cron)\b/i,"script"],[/\b(config|configuration|setup|env|settings)\b/i,"config"],[/\b(skill|agent skill|skill\.md)\b/i,"skill"],[/\b(video|audio|image|media|animation|thumbnail|podcast)\b/i,"media"],[/\b(report|audit|analysis|review|assessment|benchmark)\b/i,"report"],[/\b(test|spec|unit test|integration test|e2e|coverage|fixture|mock)\b/i,"test"],[/\b(workflow|ci|cd|pipeline|github action|deploy|automation|ci\/cd)\b/i,"workflow"],[/\b(schema|model|migration|prisma|drizzle|zod|validator|graphql type)\b/i,"schema"],[/\b(email|newsletter|transactional|invite|welcome email|notification email)\b/i,"email"],[/\b(diagram|erd|flowchart|architecture diagram|sequence diagram|mermaid|plantuml|d2)\b/i,"diagram"]];for(let[n,s]of o)if(n.test(t))return s;return"component"}import{existsSync as It,promises as ot}from"fs";import ue from"path";import{execa as Ct}from"execa";import{z as N}from"zod";var ee=["pre:generate","post:generate","pre:file-write","post:file-write","pre:prompt","post:response","pre:command","on:error","pre:tool-call","post:tool-call","pre:channel-message","post:channel-message","pre:a2a-task","pre:cron-run","post:cron-run","on:gitlab-pipeline","on:gitlab-issue","on:gitlab-mr","on:gitlab-note","on:github-issue","on:github-pr","on:github-push","on:n8n","on:stripe-event","on:sentry-issue","on:vercel-deployment","on:odoo-event","on:hubspot-event"],Re=["pre:generate","pre:file-write","pre:prompt","post:response","pre:command","pre:tool-call","pre:channel-message","post:channel-message","pre:a2a-task","pre:cron-run"],Xe=N.object({name:N.string(),type:N.enum(["command","prompt","script"]),command:N.string().optional(),prompt:N.string().optional(),provider:N.enum(["claude-code","claude","openai","deepseek","ollama","custom"]).optional(),model:N.string().optional(),script:N.string().optional(),priority:N.number().default(100),enabled:N.boolean().default(!0)});ye();var Qe={"claude-sonnet":{input:3,output:15},"claude-opus":{input:15,output:75},"claude-haiku":{input:.25,output:1.25}};function St(r){let e=r.toLowerCase();return e.includes("opus")?"claude-opus":e.includes("haiku")?"claude-haiku":"claude-sonnet"}var le=class{steps=[];models=new Map;recordStep(e,t,o,n){let s=St(t),i=Qe[s]||Qe["claude-sonnet"],c=o/1e6*i.input+n/1e6*i.output;this.steps.push({step:e,model:t,inputTokens:o,outputTokens:n,cost:c,timestamp:Date.now()});let a=this.models.get(t)||{inputTokens:0,outputTokens:0,cost:0,steps:0};a.inputTokens+=o,a.outputTokens+=n,a.cost+=c,a.steps++,this.models.set(t,a)}getSummary(){let e=0,t=0,o=0;for(let s of this.steps)e+=s.inputTokens,t+=s.outputTokens,o+=s.cost;let n={};for(let[s,i]of this.models)n[s]={...i};return{totalInputTokens:e,totalOutputTokens:t,totalTokens:e+t,totalCost:o,steps:[...this.steps],models:n}}reset(){this.steps=[],this.models.clear()}},te=new le;function Tt(r,e){let t=[];if(t.push(`# Session: ${r.id}`),t.push(""),t.push(`- **Created**: ${r.createdAt}`),t.push(`- **Updated**: ${r.updatedAt}`),t.push(`- **CWD**: ${r.cwd}`),t.push(`- **Messages**: ${r.messages.length}`),t.push(`- **Tokens**: ${r.tokensUsed.toLocaleString()}`),t.push(""),r.filesGenerated.length){t.push("## Files Generated"),t.push("");for(let o of r.filesGenerated)t.push(`- \`${o}\``);t.push("")}if(r.messages.length){t.push("## Conversation"),t.push("");for(let o of r.messages){if(o.role==="system")continue;let n=o.role==="user"?"**User**":"**Assistant**";t.push(`### ${n}`),t.push(""),o.role,t.push(o.content),t.push("")}}if(e){if(t.push("## Cost Summary"),t.push(""),t.push(`- **Total tokens**: ${e.totalTokens.toLocaleString()}`),t.push(` - Input: ${e.totalInputTokens.toLocaleString()}`),t.push(` - Output: ${e.totalOutputTokens.toLocaleString()}`),t.push(`- **Total cost**: $${e.totalCost.toFixed(4)}`),t.push(""),Object.keys(e.models).length){t.push("### Per Model"),t.push(""),t.push("| Model | Input | Output | Cost | Steps |"),t.push("|-------|-------|--------|------|-------|");for(let[o,n]of Object.entries(e.models))t.push(`| ${o} | ${n.inputTokens.toLocaleString()} | ${n.outputTokens.toLocaleString()} | $${n.cost.toFixed(4)} | ${n.steps} |`);t.push("")}if(e.steps.length){t.push("### Per Step"),t.push(""),t.push("| Step | Model | Input | Output | Cost |"),t.push("|------|-------|-------|--------|------|");for(let o of e.steps)t.push(`| ${o.step} | ${o.model} | ${o.inputTokens.toLocaleString()} | ${o.outputTokens.toLocaleString()} | $${o.cost.toFixed(4)} |`);t.push("")}}return t.join(`
|
|
21
|
-
`)}ke();var oe=class{hooks=new Map;register(e,t){if(!t.enabled)return;let o=this.createHandler(t),n={event:e,definition:t,handler:o},s=this.hooks.get(e)||[];s.push(n),s.sort((i,c)=>i.definition.priority-c.definition.priority),this.hooks.set(e,s)}async execute(e,t){let o=this.hooks.get(e);if(!o?.length)return{};let n=Re.includes(e),s={};for(let i of o){let c=Date.now();try{let a=await i.handler({...t,...s}),p=Date.now()-c;if(a.modified&&(s={...s,...a.modified}),n&&a.blocked)return b.hook(i.definition.name,p,"blocked"),{blocked:!0,message:a.message||`Blocked by hook: ${i.definition.name}`,modified:s};b.hook(i.definition.name,p,"ok")}catch(a){let p=Date.now()-c;if(b.hook(i.definition.name,p,`error: ${a.message}`),R.warn(`Hook "${i.definition.name}" failed: ${a.message}`),n)return{blocked:!0,message:`Hook "${i.definition.name}" errored: ${a.message}`}}}return{modified:Object.keys(s).length?s:void 0}}registerHandler(e,t,o,n=100){let i={event:e,definition:{name:t,type:"script",priority:n,enabled:!0},handler:o},c=this.hooks.get(e)||[];c.push(i),c.sort((a,p)=>a.definition.priority-p.definition.priority),this.hooks.set(e,c)}has(e){return!!this.hooks.get(e)?.length}clear(){this.hooks.clear()}size(){let e=0;for(let t of this.hooks.values())e+=t.length;return e}createHandler(e){switch(e.type){case"command":return this.createCommandHandler(e);case"script":return this.createScriptHandler(e);case"prompt":return this.createPromptHandler(e);default:throw new Error(`Unknown hook type: ${e.type}`)}}createCommandHandler(e){return async t=>{if(!e.command)return{};let o=e.command;o=o.replace(/\{\{(\w+)\}\}/g,(s,i)=>String(t[i]??""));let n=await Ct("sh",["-c",o],{cwd:t.cwd||process.cwd(),reject:!1,timeout:6e4,env:process.env});return n.exitCode!==0?{blocked:!0,message:n.stderr||n.stdout||`Command hook "${e.name}" failed`}:{}}}createScriptHandler(e){return async t=>{if(!e.script)return{};let n=await import(e.script.startsWith("/")?e.script:`${t.cwd||process.cwd()}/${e.script}`),s=n.default||n.handler||n;return typeof s=="function"?await s(t):{}}}createPromptHandler(e){return async t=>{if(!e.prompt)return{};let o=e.provider||Q()?.provider||"claude-code",n=Ne();if(!n&&o!=="claude-code")return R.warn(`Prompt hook "${e.name}" skipped: no credentials available for provider "${o}"`),{};try{let{createProvider:s}=await import("./providers-
|
|
21
|
+
`)}ke();var oe=class{hooks=new Map;register(e,t){if(!t.enabled)return;let o=this.createHandler(t),n={event:e,definition:t,handler:o},s=this.hooks.get(e)||[];s.push(n),s.sort((i,c)=>i.definition.priority-c.definition.priority),this.hooks.set(e,s)}async execute(e,t){let o=this.hooks.get(e);if(!o?.length)return{};let n=Re.includes(e),s={};for(let i of o){let c=Date.now();try{let a=await i.handler({...t,...s}),p=Date.now()-c;if(a.modified&&(s={...s,...a.modified}),n&&a.blocked)return b.hook(i.definition.name,p,"blocked"),{blocked:!0,message:a.message||`Blocked by hook: ${i.definition.name}`,modified:s};b.hook(i.definition.name,p,"ok")}catch(a){let p=Date.now()-c;if(b.hook(i.definition.name,p,`error: ${a.message}`),R.warn(`Hook "${i.definition.name}" failed: ${a.message}`),n)return{blocked:!0,message:`Hook "${i.definition.name}" errored: ${a.message}`}}}return{modified:Object.keys(s).length?s:void 0}}registerHandler(e,t,o,n=100){let i={event:e,definition:{name:t,type:"script",priority:n,enabled:!0},handler:o},c=this.hooks.get(e)||[];c.push(i),c.sort((a,p)=>a.definition.priority-p.definition.priority),this.hooks.set(e,c)}has(e){return!!this.hooks.get(e)?.length}clear(){this.hooks.clear()}size(){let e=0;for(let t of this.hooks.values())e+=t.length;return e}createHandler(e){switch(e.type){case"command":return this.createCommandHandler(e);case"script":return this.createScriptHandler(e);case"prompt":return this.createPromptHandler(e);default:throw new Error(`Unknown hook type: ${e.type}`)}}createCommandHandler(e){return async t=>{if(!e.command)return{};let o=e.command;o=o.replace(/\{\{(\w+)\}\}/g,(s,i)=>String(t[i]??""));let n=await Ct("sh",["-c",o],{cwd:t.cwd||process.cwd(),reject:!1,timeout:6e4,env:process.env});return n.exitCode!==0?{blocked:!0,message:n.stderr||n.stdout||`Command hook "${e.name}" failed`}:{}}}createScriptHandler(e){return async t=>{if(!e.script)return{};let n=await import(e.script.startsWith("/")?e.script:`${t.cwd||process.cwd()}/${e.script}`),s=n.default||n.handler||n;return typeof s=="function"?await s(t):{}}}createPromptHandler(e){return async t=>{if(!e.prompt)return{};let o=e.provider||Q()?.provider||"claude-code",n=Ne();if(!n&&o!=="claude-code")return R.warn(`Prompt hook "${e.name}" skipped: no credentials available for provider "${o}"`),{};try{let{createProvider:s}=await import("./providers-BDJXGHEY.js"),i=s(o,n?.token),c=e.prompt;c=c.replace(/\{\{(\w+)\}\}/g,(m,I)=>String(t[I]??""));let a=`You are a hook validator for agentx. Analyze the following context and respond with ONLY a JSON object (no markdown, no code fences).
|
|
22
22
|
|
|
23
23
|
Response format:
|
|
24
24
|
{"action": "allow", "message": "optional explanation"}
|
|
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
|
|
|
48
48
|
... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
|
|
49
49
|
${c}`,is_error:!0}:{tool_use_id:e.id,content:c||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,n=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:n,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await re.readFile(n,"utf8"),c=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),c.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):c.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await re.writeFile(n,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:n,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
|
|
50
50
|
${c.join(`
|
|
51
|
-
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-
|
|
51
|
+
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-SAY7ROZV.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
|
|
52
52
|
|
|
53
53
|
${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),o=e.input.options,n=t;return o?.length&&(n+=`
|
|
54
54
|
Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:n}}};async function Ae(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,cwd:s,maxIterations:i=20,enabledTools:c,interactive:a=!0,overwrite:p=!1,dryRun:l=!1,onProgress:d,abortSignal:u}=r,m=u?{...n,abortSignal:u}:n;if(!e.generateRaw)return dt(r);let I=new se(s,{interactive:a,overwrite:p,dryRun:l,acmeContext:r.acmeContext,abortSignal:u}),D=be(c);if(r.acmeContext)for(let g of at)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(r.mcpTools?.length)for(let g of r.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,A=0,O="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),b.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let T=null,U=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?T=x.result:x.type==="error"&&(U=x.error);if(U&&!T)throw new Error(U);if(!T)throw new Error("generateRawStream returned no raw_result event");g=T,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(T){if(T.message?.includes("not available"))return dt(r);throw T}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,A+=g.usage.output_tokens;let P=g._streamedText;for(let T of g.content)T.type==="text"&&(O+=T.text,P===void 0&&d?.({type:"text_delta",text:T.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let T=g.content.filter(v=>v.type==="tool_use");if(T.length===0)break;C.push({role:"assistant",content:g.content});let U=[];for(let v of T){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),b.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&r.mcpDispatch){let h=await r.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),U.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:U}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:O,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:A||void 0,iterations:_}}async function dt(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,maxIterations:s=5}=r,c=[{role:"system",content:t+`
|
|
@@ -65,7 +65,7 @@ ${D}`:"")}),c.push({role:"user",content:"Continue generating the remaining files
|
|
|
65
65
|
`))>=0;){let a=n.slice(0,c);n=n.slice(c+2);let p=[];for(let u of a.split(`
|
|
66
66
|
`)){let m=u.replace(/\r$/,"");m.startsWith("data:")&&p.push(m.slice(5).trim())}if(!p.length)continue;let l=p.join(`
|
|
67
67
|
`);if(!l||l==="[DONE]")continue;let d;try{d=JSON.parse(l)}catch{continue}if(d&&d.id===e)return d}}}finally{try{t.cancel().catch(()=>{})}catch{}}throw new Error(`SSE stream ended without a response for id=${e}`)}var Ue=class{constructor(e,t){this.name=e;this.transport=Wt(t)?new Ie(e,t):new je(e,t)}transport;async initialize(){await this.transport.request("initialize",{protocolVersion:Lt,capabilities:{},clientInfo:{name:"agentx-orchestrator",version:"0.1.0"}},ut),this.transport.notify("notifications/initialized")}async listTools(){return((await this.transport.request("tools/list",{},ut)).tools??[]).map(t=>({name:t.name,description:t.description??"",input_schema:t.inputSchema??{type:"object",properties:{}}}))}async callTool(e,t){let o=await this.transport.request("tools/call",{name:e,arguments:t??{}},qt),n=[];for(let s of o.content??[])s?.type==="text"&&typeof s.text=="string"?n.push(s.text):n.push(JSON.stringify(s));return{content:n.join(`
|
|
68
|
-
`)||"(no output)",isError:o.isError}}close(){this.transport.close()}};async function He(r){let e=new Map,t=[],o=new Map;for(let[n,s]of Object.entries(r)){let i=new Ue(n,s);try{await i.initialize();let c=await i.listTools();for(let a of c){let p=`${Bt}${n}__${a.name}`;t.push({name:p,description:a.description||`${n}.${a.name}`,input_schema:a.input_schema}),o.set(p,{client:i,remote:a.name})}e.set(n,i)}catch(c){b.context("mcp",`${n}: skipped \u2014 ${c.message}`),i.close()}}return{tools:t,async dispatch(n,s){let i=o.get(n);if(!i)return{content:`Unknown MCP tool: ${n}`,isError:!0};try{return await i.client.callTool(i.remote,s)}catch(c){return{content:`MCP call failed: ${c.message}`,isError:!0}}},close(){for(let n of e.values())n.close()}}}var he=class{queue=[];resolvers=[];closed=!1;push(e){if(this.closed)return;let t=this.resolvers.shift();if(t){t({value:e,done:!1});return}this.queue.push(e)}close(){if(!this.closed){this.closed=!0;for(let e of this.resolvers.splice(0))e({value:void 0,done:!0})}}async next(){return this.queue.length?{value:this.queue.shift(),done:!1}:this.closed?{value:void 0,done:!0}:new Promise(e=>{this.resolvers.push(e)})}async*[Symbol.asyncIterator](){for(;;){let{value:e,done:t}=await this.next();if(t)return;yield e}}};async function mt(r,e,t){let o=qe.parse(t||{}),n=new ne(r);await n.load();let[s,i,c]=await Promise.all([Ge(r),We(r),Le(r)]),a="";if(o.context7.enabled)try{a=await Ve(s,e,o.context7.apiKey)}catch{}let p=n.buildMemoryContext(e),l=Ee(r);return b.context("memory",p?"loaded":"empty"),b.context("instructions",l?"loaded from project":"none"),{techStack:s,schemas:i,skills:c,docs:a,config:o,memoryContext:p,projectInstructions:l}}async function Zn(r){let{task:e,cwd:t,overwrite:o=!1,dryRun:n=!1,provider:s="claude-code",model:i,apiKey:c,context7:a=!0,interactive:p=!0}=r,l=e;if(f.has("pre:prompt")){let h=await f.execute("pre:prompt",{event:"pre:prompt",task:e,cwd:t});if(h.blocked)throw new Error(h.message||"Blocked by pre:prompt hook");h.modified?.task&&(l=String(h.modified.task))}if(f.has("pre:generate")){let h=await f.execute("pre:generate",{event:"pre:generate",task:l,cwd:t});if(h.blocked)throw new Error(h.message||"Blocked by pre:generate hook")}R.info("Analyzing project...");let d=await mt(t,l,{provider:s,context7:{enabled:a,apiKey:c}}),u=Pe(r.outputType,l);R.info(`Output type: ${u}`);let m=_e(d.skills,l,u);m.length&&R.info(`Loaded ${m.length} relevant skill(s): ${m.map(h=>h.skill.frontmatter.name).join(", ")}`);let I=ft(d,u,m.map(h=>h.skill));if(!await we(c))throw new Error("No credentials configured. Run `agentx model` to set up.");let E=ve(s,c,r.providerOpts||{}),C=i||Q()?.model,B=[...r.sessionMessages||[],{role:"user",content:l}];R.info("Generating...");let G=Oe(E),F=r.maxSteps??(G?20:5),A=r.mcpServers&&Object.keys(r.mcpServers).length>0?await He(r.mcpServers):void 0,O;try{O=await Ae({provider:E,systemPrompt:I,messages:[{role:"system",content:I},...B],providerOptions:{model:C,maxTokens:8192},cwd:t,maxIterations:F,enabledTools:d.config.agentic.enabledTools.filter(h=>!d.config.agentic.disabledTools.includes(h)),interactive:p,overwrite:o,dryRun:n,acmeContext:r.acmeContext,abortSignal:r.abortSignal,mcpTools:A?.tools,mcpDispatch:A?A.dispatch.bind(A):void 0,onProgress:h=>{h.type==="iteration_start"&&h.iteration>1&&R.info(`Step ${h.iteration}/${F}...`),h.type==="tool_call"&&b.step(0,`Tool: ${h.name}`)}})}finally{A?.close()}if(O.tokensUsed){let h=C||"claude-sonnet-4-20250514",V=Math.round(O.tokensUsed*.3),Y=O.tokensUsed-V;te.recordStep(1,h,V,Y)}let{content:j}=O,{followUp:_,tokensUsed:g,inputTokens:M,outputTokens:P}=O;if(O.iterations>1&&R.info(`Completed in ${O.iterations} step(s)`),f.has("post:response")){let h=await f.execute("post:response",{event:"post:response",content:j,task:l,cwd:t});if(h.blocked)throw new Error(h.message||"Blocked by post:response hook");h.modified?.content&&(j=String(h.modified.content))}if(_&&p)return{files:{written:[],skipped:[],errors:[]},content:j,outputType:u,followUp:_,tokensUsed:g,inputTokens:M,outputTokens:P};let T=new Map;for(let h of O.files)T.set(h.path,h);let U=fe(u,d.techStack,r.outputDir),v=await me(Array.from(T.values()),{cwd:t,overwrite:o,dryRun:n,outputDir:U}),x;if(r.heal!==!1&&!n&&v.written.length>0){let{HealEngine:h}=await import("./heal-
|
|
68
|
+
`)||"(no output)",isError:o.isError}}close(){this.transport.close()}};async function He(r){let e=new Map,t=[],o=new Map;for(let[n,s]of Object.entries(r)){let i=new Ue(n,s);try{await i.initialize();let c=await i.listTools();for(let a of c){let p=`${Bt}${n}__${a.name}`;t.push({name:p,description:a.description||`${n}.${a.name}`,input_schema:a.input_schema}),o.set(p,{client:i,remote:a.name})}e.set(n,i)}catch(c){b.context("mcp",`${n}: skipped \u2014 ${c.message}`),i.close()}}return{tools:t,async dispatch(n,s){let i=o.get(n);if(!i)return{content:`Unknown MCP tool: ${n}`,isError:!0};try{return await i.client.callTool(i.remote,s)}catch(c){return{content:`MCP call failed: ${c.message}`,isError:!0}}},close(){for(let n of e.values())n.close()}}}var he=class{queue=[];resolvers=[];closed=!1;push(e){if(this.closed)return;let t=this.resolvers.shift();if(t){t({value:e,done:!1});return}this.queue.push(e)}close(){if(!this.closed){this.closed=!0;for(let e of this.resolvers.splice(0))e({value:void 0,done:!0})}}async next(){return this.queue.length?{value:this.queue.shift(),done:!1}:this.closed?{value:void 0,done:!0}:new Promise(e=>{this.resolvers.push(e)})}async*[Symbol.asyncIterator](){for(;;){let{value:e,done:t}=await this.next();if(t)return;yield e}}};async function mt(r,e,t){let o=qe.parse(t||{}),n=new ne(r);await n.load();let[s,i,c]=await Promise.all([Ge(r),We(r),Le(r)]),a="";if(o.context7.enabled)try{a=await Ve(s,e,o.context7.apiKey)}catch{}let p=n.buildMemoryContext(e),l=Ee(r);return b.context("memory",p?"loaded":"empty"),b.context("instructions",l?"loaded from project":"none"),{techStack:s,schemas:i,skills:c,docs:a,config:o,memoryContext:p,projectInstructions:l}}async function Zn(r){let{task:e,cwd:t,overwrite:o=!1,dryRun:n=!1,provider:s="claude-code",model:i,apiKey:c,context7:a=!0,interactive:p=!0}=r,l=e;if(f.has("pre:prompt")){let h=await f.execute("pre:prompt",{event:"pre:prompt",task:e,cwd:t});if(h.blocked)throw new Error(h.message||"Blocked by pre:prompt hook");h.modified?.task&&(l=String(h.modified.task))}if(f.has("pre:generate")){let h=await f.execute("pre:generate",{event:"pre:generate",task:l,cwd:t});if(h.blocked)throw new Error(h.message||"Blocked by pre:generate hook")}R.info("Analyzing project...");let d=await mt(t,l,{provider:s,context7:{enabled:a,apiKey:c}}),u=Pe(r.outputType,l);R.info(`Output type: ${u}`);let m=_e(d.skills,l,u);m.length&&R.info(`Loaded ${m.length} relevant skill(s): ${m.map(h=>h.skill.frontmatter.name).join(", ")}`);let I=ft(d,u,m.map(h=>h.skill));if(!await we(c))throw new Error("No credentials configured. Run `agentx model` to set up.");let E=ve(s,c,r.providerOpts||{}),C=i||Q()?.model,B=[...r.sessionMessages||[],{role:"user",content:l}];R.info("Generating...");let G=Oe(E),F=r.maxSteps??(G?20:5),A=r.mcpServers&&Object.keys(r.mcpServers).length>0?await He(r.mcpServers):void 0,O;try{O=await Ae({provider:E,systemPrompt:I,messages:[{role:"system",content:I},...B],providerOptions:{model:C,maxTokens:8192},cwd:t,maxIterations:F,enabledTools:d.config.agentic.enabledTools.filter(h=>!d.config.agentic.disabledTools.includes(h)),interactive:p,overwrite:o,dryRun:n,acmeContext:r.acmeContext,abortSignal:r.abortSignal,mcpTools:A?.tools,mcpDispatch:A?A.dispatch.bind(A):void 0,onProgress:h=>{h.type==="iteration_start"&&h.iteration>1&&R.info(`Step ${h.iteration}/${F}...`),h.type==="tool_call"&&b.step(0,`Tool: ${h.name}`)}})}finally{A?.close()}if(O.tokensUsed){let h=C||"claude-sonnet-4-20250514",V=Math.round(O.tokensUsed*.3),Y=O.tokensUsed-V;te.recordStep(1,h,V,Y)}let{content:j}=O,{followUp:_,tokensUsed:g,inputTokens:M,outputTokens:P}=O;if(O.iterations>1&&R.info(`Completed in ${O.iterations} step(s)`),f.has("post:response")){let h=await f.execute("post:response",{event:"post:response",content:j,task:l,cwd:t});if(h.blocked)throw new Error(h.message||"Blocked by post:response hook");h.modified?.content&&(j=String(h.modified.content))}if(_&&p)return{files:{written:[],skipped:[],errors:[]},content:j,outputType:u,followUp:_,tokensUsed:g,inputTokens:M,outputTokens:P};let T=new Map;for(let h of O.files)T.set(h.path,h);let U=fe(u,d.techStack,r.outputDir),v=await me(Array.from(T.values()),{cwd:t,overwrite:o,dryRun:n,outputDir:U}),x;if(r.heal!==!1&&!n&&v.written.length>0){let{HealEngine:h}=await import("./heal-RGM7X2ZG.js");x=await new h(t,{enabled:!0,testCommand:r.healConfig?.testCommand,buildCommand:r.healConfig?.buildCommand,lintCommand:r.healConfig?.lintCommand,maxAttempts:r.healConfig?.maxAttempts??3,provider:s,model:C,apiKey:c}).detectAndHeal(v.written,l),!x.healed&&x.error&&await f.execute("on:error",{event:"on:error",error:new Error(x.error),task:l,cwd:t})}return f.has("post:generate")&&await f.execute("post:generate",{event:"post:generate",task:l,content:j,cwd:t}),{files:v,content:j,outputType:u,tokensUsed:g,inputTokens:M,outputTokens:P,healResult:x}}async function*er(r){let{task:e,cwd:t,overwrite:o=!1,dryRun:n=!1,provider:s="claude-code",model:i,apiKey:c,context7:a=!0,interactive:p=!0}=r,l=e;if(f.has("pre:prompt")){let y=await f.execute("pre:prompt",{event:"pre:prompt",task:e,cwd:t});if(y.blocked){yield{type:"error",error:y.message||"Blocked by pre:prompt hook"};return}y.modified?.task&&(l=String(y.modified.task))}if(f.has("pre:generate")){let y=await f.execute("pre:generate",{event:"pre:generate",task:l,cwd:t});if(y.blocked){yield{type:"error",error:y.message||"Blocked by pre:generate hook"};return}}let d=await mt(t,l,{provider:s,context7:{enabled:a,apiKey:c}}),u=Pe(r.outputType,l);yield{type:"context_ready",outputType:u};let m=_e(d.skills,l,u),I=ft(d,u,m.map(y=>y.skill));if(!await we(c)){yield{type:"error",error:"No credentials configured. Run `agentx model` to set up."};return}let E=ve(s,c,r.providerOpts||{}),C=i||Q()?.model,B=Oe(E),G=r.maxSteps??(B?20:5),F=[...r.sessionMessages||[],{role:"user",content:l}];if(B){let y=new he,S,k,H;if(r.mcpServers&&Object.keys(r.mcpServers).length>0)try{H=await He(r.mcpServers)}catch(w){yield{type:"error",error:`MCP pool startup failed: ${w.message}`};return}let ie=(async()=>{try{S=await Ae({provider:E,systemPrompt:I,messages:[{role:"system",content:I},...F],providerOptions:{model:C,maxTokens:8192},cwd:t,maxIterations:G,abortSignal:r.abortSignal,enabledTools:d.config.agentic.enabledTools.filter(w=>!d.config.agentic.disabledTools.includes(w)),interactive:p,overwrite:o,dryRun:n,acmeContext:r.acmeContext,mcpTools:H?.tools,mcpDispatch:H?H.dispatch.bind(H):void 0,onProgress:w=>{w.type==="text_delta"&&y.push({type:"text_delta",text:w.text}),w.type==="thinking_delta"&&y.push({type:"thinking_delta",text:w.text}),w.type==="iteration_start"&&y.push({type:"iteration",iteration:w.iteration}),w.type==="tool_call"&&y.push({type:"tool_call",name:w.name,id:w.id}),w.type==="tool_result"&&y.push({type:"tool_result",name:w.name,id:w.id,is_error:w.is_error}),w.type==="files_created"&&y.push({type:"step_complete",step:0,filesCount:w.files.length})}})}catch(w){k=w}finally{H?.close(),y.close()}})();for await(let w of y)yield w;if(await ie,k){yield{type:"error",error:k instanceof Error?k.message:String(k)};return}if(!S){yield{type:"error",error:"Agentic loop failed without a result"};return}yield{type:"done",result:{content:S.content,files:S.files,tokensUsed:S.tokensUsed,followUp:S.followUp}};let{content:L}=S;if(f.has("post:response")){let w=await f.execute("post:response",{event:"post:response",content:L,task:l,cwd:t});if(w.blocked){yield{type:"error",error:w.message||"Blocked by post:response hook"};return}w.modified?.content&&(L=String(w.modified.content))}if(S.followUp&&p){yield{type:"generate_result",result:{files:{written:[],skipped:[],errors:[]},content:L,outputType:u,followUp:S.followUp,tokensUsed:S.tokensUsed,inputTokens:S.inputTokens,outputTokens:S.outputTokens}};return}let ae=new Map;for(let w of S.files)ae.set(w.path,w);let De=fe(u,d.techStack,r.outputDir),z=await me(Array.from(ae.values()),{cwd:t,overwrite:o,dryRun:n,outputDir:De}),J;if(r.heal!==!1&&!n&&z.written.length>0){let{HealEngine:w}=await import("./heal-RGM7X2ZG.js");J=await new w(t,{enabled:!0,testCommand:r.healConfig?.testCommand,buildCommand:r.healConfig?.buildCommand,lintCommand:r.healConfig?.lintCommand,maxAttempts:r.healConfig?.maxAttempts??3,provider:s,model:C,apiKey:c}).detectAndHeal(z.written,l)}f.has("post:generate")&&await f.execute("post:generate",{event:"post:generate",task:l,content:L,cwd:t}),yield{type:"generate_result",result:{files:z,content:L,outputType:u,tokensUsed:S.tokensUsed,inputTokens:S.inputTokens,outputTokens:S.outputTokens,healResult:J}};return}let A=[{role:"system",content:I},...F],O=[],j=0,_="",g,M=0;M++,b.step(M,`Starting generation (model: ${C||"default"})`);let P;if(E.stream){let y="",S;for await(let k of E.stream(A,{model:C,maxTokens:8192}))yield k,k.type==="text_delta"&&(y+=k.text),k.type==="done"&&(S=k.result);P=S||{content:y,files:[],tokensUsed:0}}else{let y=await E.generate(A,{model:C,maxTokens:8192});y.content&&(yield{type:"text_delta",text:y.content}),yield{type:"done",result:y},P=y}j+=P.tokensUsed||0,_=P.content;let T=P.tokensUsed||0,U=C||"claude-sonnet-4-20250514",v=Math.round(T*.3),x=T-v;if(te.recordStep(M,U,v,x),b.api("generate",U,T),b.step(M,`Generated ${P.files.length} file(s), ${T} tokens`),P.files.length&&O.push(...P.files),P.followUp&&(g=P.followUp),yield{type:"step_complete",step:M,filesCount:P.files.length},!g&&(_.includes("[CONTINUE]")||_.includes("Next, I'll")||_.includes("Now let me")||_.includes("I'll also generate"))&&P.files.length>0){let S=P.files.map(k=>`Created: ${k.path}${k.description?` \u2014 ${k.description}`:""}`).join(`
|
|
69
69
|
`);for(A.push({role:"assistant",content:_+(S?`
|
|
70
70
|
|
|
71
71
|
Files created:
|
|
@@ -73,7 +73,7 @@ ${S}`:"")}),A.push({role:"user",content:"Continue generating the remaining files
|
|
|
73
73
|
`);A.push({role:"assistant",content:k.content+(z?`
|
|
74
74
|
|
|
75
75
|
Files created:
|
|
76
|
-
${z}`:"")}),A.push({role:"user",content:"Continue generating the remaining files. Build on what you've already created. When finished, do not include [CONTINUE] in your response."})}}if(f.has("post:response")){let y=await f.execute("post:response",{event:"post:response",content:_,task:l,cwd:t});if(y.blocked){yield{type:"error",error:y.message||"Blocked by post:response hook"};return}y.modified?.content&&(_=String(y.modified.content))}if(g&&p){yield{type:"generate_result",result:{files:{written:[],skipped:[],errors:[]},content:_,outputType:u,followUp:g,tokensUsed:j}};return}let h=new Map;for(let y of O)h.set(y.path,y);let V=fe(u,d.techStack,r.outputDir),Y=await me(Array.from(h.values()),{cwd:t,overwrite:o,dryRun:n,outputDir:V}),X;if(r.heal!==!1&&!n&&Y.written.length>0){let{HealEngine:y}=await import("./heal-
|
|
76
|
+
${z}`:"")}),A.push({role:"user",content:"Continue generating the remaining files. Build on what you've already created. When finished, do not include [CONTINUE] in your response."})}}if(f.has("post:response")){let y=await f.execute("post:response",{event:"post:response",content:_,task:l,cwd:t});if(y.blocked){yield{type:"error",error:y.message||"Blocked by post:response hook"};return}y.modified?.content&&(_=String(y.modified.content))}if(g&&p){yield{type:"generate_result",result:{files:{written:[],skipped:[],errors:[]},content:_,outputType:u,followUp:g,tokensUsed:j}};return}let h=new Map;for(let y of O)h.set(y.path,y);let V=fe(u,d.techStack,r.outputDir),Y=await me(Array.from(h.values()),{cwd:t,overwrite:o,dryRun:n,outputDir:V}),X;if(r.heal!==!1&&!n&&Y.written.length>0){let{HealEngine:y}=await import("./heal-RGM7X2ZG.js");X=await new y(t,{enabled:!0,testCommand:r.healConfig?.testCommand,buildCommand:r.healConfig?.buildCommand,lintCommand:r.healConfig?.lintCommand,maxAttempts:r.healConfig?.maxAttempts??3,provider:s,model:C,apiKey:c}).detectAndHeal(Y.written,l),!X.healed&&X.error&&await f.execute("on:error",{event:"on:error",error:new Error(X.error),task:l,cwd:t})}f.has("post:generate")&&await f.execute("post:generate",{event:"post:generate",task:l,content:_,cwd:t}),yield{type:"generate_result",result:{files:Y,content:_,outputType:u,tokensUsed:j,healResult:X}}}function ft(r,e,t){let o=[];o.push(`You are agentx, an agentic code generation tool. You generate high-quality, production-ready output for any tech stack.
|
|
77
77
|
|
|
78
78
|
Your primary tool is \`create_files\` \u2014 use it to output all generated code, documents, and configs as files.
|
|
79
79
|
If the request is ambiguous or you need critical information to proceed correctly, use \`ask_user\` to ask a clarifying question.
|
|
@@ -123,4 +123,4 @@ ${r.projectInstructions}`),r.memoryContext&&o.push(r.memoryContext),o.push(`# Ou
|
|
|
123
123
|
Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
|
|
124
124
|
|
|
125
125
|
`)}export{qe as a,Vt as b,Yt as c,We as d,ze as e,Ve as f,Ye as g,Pe as h,ee as i,Re as j,le as k,te as l,Tt as m,oe as n,Mt as o,f as p,et as q,tt as r,Me as s,de as t,W as u,ne as v,it as w,Ee as x,$e as y,se as z,mt as A,Zn as B,er as C};
|
|
126
|
-
//# sourceMappingURL=chunk-
|
|
126
|
+
//# sourceMappingURL=chunk-E4V5EADX.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as S,c as O}from"./chunk-
|
|
1
|
+
import{b as S,c as O}from"./chunk-XE3CGJV4.js";import{h as B,j as J}from"./chunk-3UOTLMXD.js";import{a as I,b as P}from"./chunk-FCPTN6NF.js";import{a as X,b as le}from"./chunk-7I7IEX4S.js";import{d as F}from"./chunk-QIJLFPWE.js";import{execFile as ke}from"child_process";import{writeFileSync as ie,mkdirSync as x,existsSync as b,readFileSync as Ce}from"fs";import{resolve as v}from"path";var ge=["off","shadow","authoritative"],me={telegram:"INTENT_LEDGER_MODE_TELEGRAM",slack:"INTENT_LEDGER_MODE_SLACK",whatsapp:"INTENT_LEDGER_MODE_WHATSAPP",discord:"INTENT_LEDGER_MODE_DISCORD",gitlab:"INTENT_LEDGER_MODE_GITLAB",github:"INTENT_LEDGER_MODE_GITHUB",workflow:"INTENT_LEDGER_MODE_WORKFLOW",cron:"INTENT_LEDGER_MODE_CRON",mesh:"INTENT_LEDGER_MODE_MESH"},he="INTENT_LEDGER_MODE";function G(i,e=process.env){let t=U(e[me[i]]);if(t)return t;let n=U(e[he]);return n||"off"}function U(i){if(typeof i!="string")return null;let e=i.trim().toLowerCase();return ge.includes(e)?e:null}P();import fe from"better-sqlite3";import{existsSync as Ge,mkdirSync as pe}from"fs";import{dirname as Ee,resolve as ve}from"path";var T=class{db;path;constructor(e={}){this.path=ve(process.cwd(),e.path??".agentx/intent/ledger.sqlite"),pe(Ee(this.path),{recursive:!0}),this.db=new fe(this.path),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),Ie(this.db)}close(){this.db.close()}schemaVersion(){return this.db.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0}recordEvent(e){if(e.sourceEventId!==null){let n=this.findEventBySourceId(e.source,e.sourceEventId);if(n)return n}let t={id:e.id??I(e.ts),ts:e.ts,source:e.source,sourceEventId:e.sourceEventId,project:e.project,subject:e.subject,intent:e.intent,rawJson:e.rawJson};return this.db.prepare(`INSERT INTO intent_events (id, ts, source, source_event_id, project, subject, intent, raw_json)
|
|
2
2
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(t.id,t.ts,t.source,t.sourceEventId,t.project,t.subject,t.intent,t.rawJson),t}findEventBySourceId(e,t){let n=this.db.prepare(`SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
|
|
3
3
|
FROM intent_events WHERE source = ? AND source_event_id = ?`).get(e,t);return n?Y(n):null}getEventById(e){let t=this.db.prepare(`SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
|
|
4
4
|
FROM intent_events WHERE id = ?`).get(e);return t?Y(t):null}recordDecision(e){this.db.prepare(`INSERT INTO intent_decisions (event_id, decided_at, decided_by, agent_id, outcome, reason)
|
|
@@ -125,4 +125,4 @@ ${oe(a.block,r.prompt)}`,r.maxOutputTokens),agentId:r.agent,autonomy:r.autonomy,
|
|
|
125
125
|
`);return t.length<=e?t.join(`
|
|
126
126
|
`):t.slice(-e).join(`
|
|
127
127
|
`)}function Pe(i,e,t){return new Promise((n,r)=>{ke("/bin/sh",["-c",i],{timeout:e,maxBuffer:8*1024*1024,...t?{env:t}:{}},(s,o,a)=>{if(s&&s.killed){r(new Error(`command timed out after ${Math.round(e/1e3)}s`));return}n({stdout:String(o??""),stderr:String(a??""),code:s?typeof s.code=="number"?s.code:1:0})})})}export{T as a,V as b,at as c,Le as d,ct as e,dt as f,L as g,ee as h,G as i,ze as j,z as k,Q as l,gt as m,Me as n,ae as o,ce as p,de as q,C as r,M as s};
|
|
128
|
-
//# sourceMappingURL=chunk-
|
|
128
|
+
//# sourceMappingURL=chunk-GI5CY27P.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{q as _,r as W}from"./chunk-2AXFYDWF.js";import{b as Y,c as I,d as O}from"./chunk-AQASR6KR.js";import{b as F}from"./chunk-MEFPXHQJ.js";import{a as E}from"./chunk-
|
|
1
|
+
import{q as _,r as W}from"./chunk-2AXFYDWF.js";import{b as Y,c as I,d as O}from"./chunk-AQASR6KR.js";import{b as F}from"./chunk-MEFPXHQJ.js";import{a as E}from"./chunk-YJZQRFET.js";import{b as L}from"./chunk-KEXBEUSU.js";import{createHash as ee}from"crypto";import{existsSync as H,readdirSync as te,readFileSync as re,writeFileSync as ne}from"fs";import{resolve as P}from"path";function be(n,r,s,t,o,i,c="",p="",m=""){return Z(r,s,t,o,i,c,p,m)}function Z(n,r,s,t,o,i="",c="",p=""){let m=r?`
|
|
2
2
|
## Worldview
|
|
3
3
|
|
|
4
4
|
${r}
|
|
@@ -249,4 +249,4 @@ ${u}`}var x="memory-promoter",oe=["project","reference","feedback"],K="_memory-p
|
|
|
249
249
|
Re-emit the FULL corrected JSON object \u2014 same structure, fixed issues, valid JSON only.`:n,y=await t(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:r.viaAgent,message:h,freshSession:s===null,context:{channel:"api",chatId:r.chatId??"memory-promote"}}),signal:i.signal});if(!y.ok){let f=await y.text().catch(()=>"");throw new Error(`agent /task ${y.status}: ${f.slice(0,500)}`)}let w=await y.json();if(w.error)throw new Error(`agent reported error: ${w.error}`);let b=String(w.content??"").trim();if(!b)throw new Error("agent returned empty content");return b}if(!r.model)throw new Error("callPromotionLlm: viaAgent or model is required");let p=process.env.ANTHROPIC_API_KEY;if(!p)throw new Error("ANTHROPIC_API_KEY not set; use --via <agentId> instead");let m=[{role:"user",content:n}];s&&(m.push({role:"assistant",content:"(previous attempt; will retry with corrections)"}),m.push({role:"user",content:`Your previous response failed validation: ${s}
|
|
250
250
|
Re-emit the FULL corrected JSON object.`}));let u=await t(me,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":p,"anthropic-version":ge},body:JSON.stringify({model:r.model,max_tokens:8e3,messages:m}),signal:i.signal});if(!u.ok){let a=await u.text().catch(()=>"");throw new Error(`anthropic API ${u.status}: ${a.slice(0,500)}`)}let d=await u.json(),e=(Array.isArray(d.content)?d.content:[]).filter(a=>a?.type==="text").map(a=>a.text).join(`
|
|
251
251
|
`).trim();if(!e)throw new Error("anthropic API returned no text content");return e}finally{clearTimeout(c)}}async function Se(n={}){let r=n.wikiDir??P(process.cwd(),".agentx","wiki"),s=n.memoryRoot??P(process.cwd(),".agentx"),t=n.log??(()=>{}),o=n.now??Date.now(),i={candidates:[],clusters:[],proposed:[],skipped:[],gaps:[],warnings:[],errors:[],dryRun:!n.commit},c=new E(r,(...l)=>t(l.map(String).join(" "))),p=c.rebuildIndex(),m=z(r),u=[...ce(s),...n.extraCandidates??[]];if(i.candidates=de(u,p,m,{types:n.types,sinceMs:n.sinceMs,agentFilter:n.agentFilter,now:o,max:n.max}),i.candidates.length===0)return t("no unpromoted memories in window"),i;if(i.clusters=le(i.candidates),i.dryRun)return i;let d=p.articles.map(l=>({title:l.title,path:l.path,type:l.type})),g=c.getWorldview()??"",e=n.budgetTokens??ue,a=i.clusters,h=D(x,a,d,g);for(;R(h)>e&&a.length>1;)a=a.slice(0,-1),h=D(x,a,d,g);if(R(h)>e)return i.errors.push(`judge prompt (~${R(h)} tokens) exceeds the ${e}-token budget even with one cluster`),i;a.length<i.clusters.length&&i.warnings.push(`token budget: judged ${a.length} of ${i.clusters.length} clusters; the rest wait for the next run`);let y=a.flatMap(l=>l.candidates),w=new Set(y.map(l=>l.stamp)),b=n.chatId??`memory-promote-${new Date(o).toISOString().slice(0,10)}`,f=B(await G(h,{...n,chatId:b}),w);if("error"in f&&(t(`parse failed (${f.error}) \u2014 retrying with feedback`),f=B(await G(h,{...n,chatId:b},f.error),w)),"error"in f)return i.errors.push(`LLM response unusable after retry: ${f.error}`),i;i.warnings.push(...f.warnings),i.gaps=f.gaps;let v=new Date(o).toISOString(),k=[],T=new Map(y.map(l=>[l.stamp,l]));for(let l of f.articles){let A=c.readArticle(l.path);if(A&&!c.canWrite(A.meta,x)){i.errors.push(`write denied for "${l.path}" (owned by ${A.meta.owner??"?"})`);continue}let M=fe(l.promotedFrom,T),S={id:Y(o,l.path),createdAt:v,status:"pending",article:l,evidence:M,...A?{replaces:{lastUpdated:A.meta.lastUpdated,contentHash:V(A.content)}}:{}};I(r,S),i.proposed.push({id:S.id,path:l.path,title:l.title,type:l.type,stamps:l.promotedFrom,agents:M.agents,occurrences:M.occurrences});for(let X of l.promotedFrom)k.push({stamp:X,decision:"proposed",article:l.path,proposal:S.id,at:v})}for(let l of f.skipped)k.push({stamp:l.stamp,decision:"skipped",reason:l.reason,at:v}),i.skipped.push(l);return k.length&&C(r,k),i}var ue=6e4;function R(n){return Math.ceil(n.length/4)}function V(n){return ee("sha256").update(n).digest("hex").slice(0,16)}var he=600;function ye(n){return n.startsWith("review:")?"review":n.startsWith(j)?"failure":"memory"}function fe(n,r){let s=[];for(let t of n){let o=r.get(t);o&&s.push({stamp:t,kind:ye(t),agentId:o.agentId,type:o.memory.type,name:o.memory.name,description:o.memory.description,...o.occurrences?{occurrences:o.occurrences}:{},...o.sessions?.length?{sessions:o.sessions}:{},...o.tasks?.length?{tasks:o.tasks}:{},...o.failure?{failure:o.failure}:{},...o.memory.author?{author:o.memory.author}:{},...o.memory.taskId?{taskId:o.memory.taskId}:{},updatedAt:o.memory.updatedAt,excerpt:o.memory.body.slice(0,he)})}return{agents:[...new Set(s.map(t=>t.agentId))].sort(),occurrences:Math.max(1,...s.map(t=>t.occurrences??1)),sources:s}}function Ee(n,r,s={}){let t=O(n,r);if(!t)return{ok:!1,error:`no proposal "${r}"`};if(t.status!=="pending")return{ok:!1,error:`proposal "${r}" is already ${t.status}`};let o=s.log??(()=>{}),i=new E(n,(...a)=>o(a.map(String).join(" "))),{article:c}=t,p=i.readArticle(c.path);if(!s.force){if(p&&!t.replaces)return{ok:!1,error:`"${c.path}" was created after this proposal; review it, then approve with --force`};if(p&&t.replaces&&V(p.content)!==t.replaces.contentHash)return{ok:!1,error:`"${c.path}" changed since this proposal; review it, then approve with --force`}}let m=s.now??Date.now(),u=new Date(m).toISOString().slice(0,10);if(!i.writeArticle(c.path,{title:c.title,type:L(c.type)?c.type:void 0,related:c.related,tags:c.tags,owner:x,access:"public",created:p?.meta.created??u,lastUpdated:u,sources:ae(p?.meta.sources,c.promotedFrom)},c.content,x))return{ok:!1,error:`write denied for "${c.path}" (owned by ${p?.meta.owner??"?"})`};let g=new Date(m).toISOString();C(n,c.promotedFrom.map(a=>({stamp:a,decision:"promoted",article:c.path,proposal:r,at:g}))),i.rebuildIndex();let e={...t,status:"approved",decidedBy:s.by??"operator",decidedAt:g};return I(n,e),{ok:!0,proposal:e}}function Oe(n,r,s={}){let t=O(n,r);if(!t)return{ok:!1,error:`no proposal "${r}"`};if(t.status!=="pending")return{ok:!1,error:`proposal "${r}" is already ${t.status}`};let o=new Date(s.now??Date.now()).toISOString();C(n,t.article.promotedFrom.map(c=>({stamp:c,decision:"rejected",article:t.article.path,proposal:r,reason:s.reason,at:o})));let i={...t,status:"rejected",decidedBy:s.by??"operator",decidedAt:o,...s.reason?{reason:s.reason}:{}};return I(n,i),{ok:!0,proposal:i}}export{be as a,x as b,oe as c,K as d,q as e,ie as f,$ as g,ae as h,ce as i,z as j,C as k,le as l,B as m,de as n,G as o,Se as p,R as q,ye as r,fe as s,Ee as t,Oe as u};
|
|
252
|
-
//# sourceMappingURL=chunk-
|
|
252
|
+
//# sourceMappingURL=chunk-HS7ATV4Z.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{d as h}from"./chunk-
|
|
1
|
+
import{d as h}from"./chunk-PGLTBNGZ.js";var d=["main contact","primary contact","point of contact","billing contact","technical contact","decision maker"],f=/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g,w=/\b(role|title|position|job)\s*\**\s*[::]\s*\**\s*([^\n;|]+)/gi;function L(t,c,e=[]){let l=[c,...e].join(`
|
|
2
2
|
`),a=l.toLowerCase(),i=h(t,l);for(let s of p(t.match(f)??[]))a.includes(s.toLowerCase())||i.push(`email ${s}`);let m=t.toLowerCase();for(let s of d)m.includes(s)&&!a.includes(s)&&i.push(`marker "${s}"`);for(let s of t.matchAll(w)){let n=s[2].replace(/\*+/g,"").trim();n&&!a.includes(n.toLowerCase())&&i.push(`${s[1].toLowerCase()} "${n}"`)}return p(i)}function p(t){return[...new Set(t)]}var $=.9,g=/^\s*(?:wait\b|here(?:'s| is) the (?:updated|modified|patched|revised)|i (?:must|need to|will|should) (?:output|return|write)|(?:okay|ok|sure)[,.!]\s|let me\b|as requested\b)/im;function k(t,c){let e=[],l=t.split(`
|
|
3
3
|
`).filter(o=>o.trim()).length,a=c.split(`
|
|
4
4
|
`).filter(o=>o.trim()).length;l>=5&&a<Math.floor(l*$)&&e.push(`the article shrinks from ${l} to ${a} lines`);let i=c.match(g);i&&!t.match(g)&&e.push(`it contains the model's own commentary ("${i[0].trim().slice(0,40)}")`);let m=o=>{let r=new Map;for(let u of o.split(`
|
|
5
5
|
`))/^#{1,6} /.test(u)&&r.set(u.trim(),(r.get(u.trim())??0)+1);return r},s=m(t);for(let[o,r]of m(c))r>1&&r>(s.get(o)??0)&&e.push(`the heading "${o}" appears ${r} times`);let n=L(t,c);return n.length&&e.push(`it drops ${n.length} fact(s): ${n.slice(0,6).join(", ")}${n.length>6?", \u2026":""}`),e}export{L as a,k as b};
|
|
6
|
-
//# sourceMappingURL=chunk-
|
|
6
|
+
//# sourceMappingURL=chunk-ILZRO6SN.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as w,b as y,c as x}from"./chunk-SFQUP3BP.js";import{o as g,p as C}from"./chunk-
|
|
1
|
+
import{a as w,b as y,c as x}from"./chunk-SFQUP3BP.js";import{o as g,p as C}from"./chunk-JNG3P5V2.js";C();import{existsSync as d,promises as h}from"fs";import c from"path";import{execa as b}from"execa";var k={enabled:!0,maxAttempts:3,provider:"claude-code"},v=class{constructor(e,r,i){this.cwd=e;this.config={...k,...r},this.memory=i||new x(e)}config;memory;async detectAndHeal(e,r,i){if(!this.config.enabled)return{healed:!1,attempts:0,error:"Heal disabled",filesChanged:[]};let t=await this.runVerification();if(!t)return{healed:!0,attempts:0,error:"",filesChanged:[]};let n=0,s=t,a=[];for(;n<this.config.maxAttempts;){n++;let l=await this.generateFix(s,e,r,n);if(!l.files.length)break;for(let o of l.files){let m=c.isAbsolute(o.path)?o.path:c.resolve(this.cwd,o.path),p=c.dirname(m);await h.mkdir(p,{recursive:!0}),await h.writeFile(m,o.content,"utf8"),a.push(o.path)}let f=await this.runVerification();if(!f)return i&&await this.memory.recordHeal(i,t,!0,a),{healed:!0,attempts:n,error:t,fix:l.explanation,filesChanged:a};s=f}return i&&await this.memory.recordHeal(i,t,!1,a),{healed:!1,attempts:n,error:s,filesChanged:a}}async runVerification(){let e=[this.config.buildCommand,this.config.lintCommand,this.config.testCommand].filter(Boolean);if(!e.length){let r=await this.detectCommands();e.push(...r)}for(let r of e)try{let[i,...t]=r.split(" ");await b(i,t,{cwd:this.cwd,timeout:6e4,reject:!0})}catch(i){let t=i.stderr||"",n=i.stdout||"",s=i.message||"";return F(`Command failed: ${r}
|
|
2
2
|
${t}
|
|
3
3
|
${n}
|
|
4
4
|
${s}`)}return null}async detectCommands(){let e=[],r=c.resolve(this.cwd,"package.json");if(d(r))try{let t=JSON.parse(await h.readFile(r,"utf8")).scripts||{};t.build&&e.push("npm run build"),t.typecheck&&e.push("npm run typecheck"),t.lint&&e.push("npm run lint"),t.test&&e.push("npm run test")}catch{}return d(c.resolve(this.cwd,"pyproject.toml"))&&d(c.resolve(this.cwd,"conftest.py"))&&e.push("python -m pytest --tb=short -q"),e}async generateFix(e,r,i,t){let n=g(this.config.provider,this.config.apiKey),s=[];for(let o of r.slice(0,5)){let m=c.resolve(this.cwd,o);if(d(m)){let p=await h.readFile(m,"utf8");s.push(`## ${o}
|
|
@@ -29,4 +29,4 @@ Fix the error. Use create_files with the corrected file content.`}],f=await n.ge
|
|
|
29
29
|
`)+`
|
|
30
30
|
... (truncated)`:e.join(`
|
|
31
31
|
`)}export{v as a};
|
|
32
|
-
//# sourceMappingURL=chunk-
|
|
32
|
+
//# sourceMappingURL=chunk-IVBCCSDR.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{B as k,D as O,G as I,q as R,t as x,z as N}from"./chunk-
|
|
1
|
+
import{B as k,D as O,G as I,q as R,t as x,z as N}from"./chunk-JJOLZPUY.js";import{a as E}from"./chunk-OSH2PEBH.js";import{La as j,Ua as F}from"./chunk-SQUTRMKH.js";F();import{Command as X}from"commander";import f from"chalk";import{execFileSync as m}from"child_process";import{accessSync as W,constants as M,existsSync as w,readFileSync as b,readdirSync as C,statSync as B}from"fs";import{join as H,resolve as y}from"path";import{homedir as z}from"os";import{createRequire as G}from"module";var T="Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.";async function P(t={}){let n=t.helper===void 0?N():t.helper,e=k({},{platform:t.platform,io:{capture:t.run,helper:n}}).banner;if(!e)return{state:"unsupported",message:"Desktop banners are only shown on a Mac."};let i=await e.status();return i==="missing"?{state:"missing",message:"AgentX Helper is not installed, so banners come from Script Editor and show its icon.",fix:'Run agentx desktop install, then run agentx notify "Hello" --title "Test" and click Allow.'}:i==="outdated"?{state:"outdated",path:n,message:"AgentX Helper is too old to report whether it may notify.",fix:"Run agentx desktop install to update it."}:i==="not-asked"?{state:"not-asked",path:n,message:"macOS has not asked yet whether AgentX Helper may notify; banners show the Script Editor icon until it does.",fix:'Run agentx notify "Hello" --title "Test" and click Allow when macOS asks.'}:i==="not-allowed"?{state:"not-allowed",path:n,message:"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.",fix:T}:i==="hidden"?{state:"hidden",path:n,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:T}:{state:"ready",path:n,message:"AgentX Helper posts banners with the AgentX icon."}}async function Z(t={}){let n=[];await Q(n),Y(n);let e=ee(n);return e&&te(n,e),e&&se(n,e),e&&re(n,e),e&&ae(n,e),e&&ie(n,e),e&&ce(n,e),e&&await J(n,e),e&&U(n,e),e&&await K(n,e),e&&V(n,e),t.running!==!1&&e&&await de(n,e),{checks:n,summary:D(n)}}var Ne=new X().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 Z({running:t.running!==!1});t.json?process.stdout.write(JSON.stringify({checks:n,summary:e},null,2)+`
|
|
2
2
|
`):ue(n),process.exit(e.errors>0?1:0)});async function J(t,n,e=P){if(!O(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 K(t,n,e){let i;try{i=await(e??k(n)).describe()}catch(s){t.push({severity:"warn",group:"Native",title:"Native apps: could not be read",detail:s?.message??String(s)});return}let o=["tasks","notes","banner","sound","focus"].filter(s=>i[s]);t.push({severity:"ok",group:"Native",title:i.os==="none"?"Native apps: none on this machine":`Native apps (${i.os}): ${o.join(", ")||"nothing available"}`,detail:i.problems.join(" ")||void 0})}function V(t,n,e=process.cwd(),i=k(n)){let o=n.native?.mirror;if(!o?.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 s=I(e),a=Object.values(s.items),l=a.filter(g=>g.state==="open").length,u=a.filter(g=>g.state==="failed").length;t.push({severity:s.lastError||u?"warn":"ok",group:"Native",title:`Reminders mirror: ${l} open in "${o.list}"${u?`, ${u} could not be added`:""}`,detail:s.lastError?`Last error ${s.lastError.at}: ${s.lastError.message}`:void 0,fix:s.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 U(t,n,e=process.platform,i=o=>{try{return W(o,M.X_OK),!0}catch{return!1}}){let o=n.reminders;if(!o?.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 s=o.command||"remindctl",a=s.includes("/")?i(s)?s:null:x(s,process.env.PATH||"",i);t.push(a?{severity:"ok",group:"Reminders",title:`Watching ${(o.lists||[]).join(", ")} for due reminders`,detail:a}:{severity:"fail",group:"Reminders",title:`${s} 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 Q(t){let n=E(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 o=e("claude");if(o){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:o})}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 s=e("codex");if(s){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:s})}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{G(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 Y(t){if(process.platform!=="darwin")return;let n=H(z(),"Library/LaunchAgents"),e=[];try{e=C(n).filter(o=>/agentx\.voice.*\.plist$/.test(o))}catch{return}let i=o=>{try{return W(o,M.X_OK),!0}catch{return!1}};for(let o of e){let s=R(b(H(n,o),"utf-8")),a=x("ffmpeg",s,i);t.push(a?{severity:"ok",group:"Desktop",title:"ffmpeg reachable by the desktop app",detail:`${a} (${o})`}:{severity:"warn",group:"Desktop",title:"ffmpeg not reachable by the desktop app",detail:`Local Whisper transcription fails without it. ${o} sets PATH to ${s}.`,fix:"Install ffmpeg (brew install ffmpeg), then rerun agentx desktop install."})}}function ee(t){let n=y(process.cwd(),"agentx.json");if(!w(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(b(n,"utf-8"))}catch(a){return t.push({severity:"fail",group:"Config",title:"agentx.json is not valid JSON",detail:a.message}),null}try{j(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 o=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="codex-cli");o.length>0&&((()=>{try{return m(process.platform==="win32"?"where":"which",["codex"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${o.length} agent(s) use codex-cli tier but codex CLI is missing`,detail:o.map(([l])=>l).join(", "),fix:"Install Codex CLI with `npm i -g @openai/codex` or switch these agents to tier=claude-code."}));let s=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="opencode");return s.length>0&&((()=>{try{return m(process.platform==="win32"?"where":"which",["opencode"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${s.length} agent(s) use opencode tier but OpenCode CLI is missing`,detail:s.map(([l])=>l).join(", "),fix:"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier."})),e}function te(t,n){let e=new Set;if(A(n,e),e.size===0){t.push({severity:"ok",group:"Secrets",title:"No ${VAR} references in agentx.json"});return}let i=_(),o=[],s=[];for(let a of e){let l=process.env[a]??i[a];l===void 0?o.push(a):(!l.trim()||/^["']?\s*["']?$/.test(l))&&s.push(a)}o.length===0&&s.length===0?t.push({severity:"ok",group:"Secrets",title:`${e.size} env reference(s) resolved`}):(o.length>0&&t.push({severity:"fail",group:"Secrets",title:`${o.length} env var(s) referenced in agentx.json but missing`,detail:o.join(", "),fix:`Add to .env \u2014 e.g. ${o[0]}=<value>`}),s.length>0&&t.push({severity:"warn",group:"Secrets",title:`${s.length} env var(s) set but empty`,detail:s.join(", ")}))}function _(){let t=y(process.cwd(),".env"),n={};if(w(t))for(let e of b(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 ne(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.",o=[];for(let s of t){let a=(s.token??"").trim();a?n&&a===n&&o.push({severity:"warn",group:"Mesh",title:`mesh peer "${s.name}" uses this node's own MESH_TOKEN`,detail:e,fix:i}):o.push({severity:"warn",group:"Mesh",title:`mesh peer "${s.name}" has no token; calls to it use the shared MESH_TOKEN`,detail:e,fix:i})}return t.length>0&&o.length===0&&o.push({severity:"ok",group:"Mesh",title:`${t.length} mesh peer(s), each with a token of its own`}),o}function ie(t,n){t.push(...oe(n))}function oe(t,n=process.env,e=_()){let i=a=>(n[a]||e[a]||"").trim(),o=a=>typeof a=="string"?a.replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,(l,u)=>i(u)):void 0,s=(t.mesh?.peers??[]).filter(a=>typeof a?.name=="string").map(a=>({name:a.name,token:o(a.token)}));return ne(s,i("MESH_TOKEN")||void 0)}function A(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)A(e,n);else if(t&&typeof t=="object")for(let e of Object.values(t))A(e,n)}function se(t,n){let e=[];for(let[i,o]of Object.entries(n.agents||{})){if(!o.workspace)continue;let s=o.workspace.startsWith("/")?o.workspace:y(process.cwd(),o.workspace);try{B(s).isDirectory()||e.push(`${i}: ${s} (exists but not a directory)`)}catch{e.push(`${i}: ${s}`)}}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 re(t,n){let e=/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g,i=[];for(let[o,s]of Object.entries(n.agents||{})){if(!s.workspace)continue;let a=s.workspace.startsWith("/")?s.workspace:y(process.cwd(),s.workspace);for(let l of["settings.json","settings.local.json"]){let u=y(a,".claude",l);if(!w(u))continue;let g;try{g=JSON.parse(b(u,"utf-8"))}catch(c){i.push({severity:"fail",agent:o,msg:`${l}: JSON parse error \u2014 ${c.message}`});continue}let $=g.env||{};for(let[c,h]of Object.entries($)){if(typeof h!="string")continue;let p=h.match(e);p&&i.push({severity:"fail",agent:o,msg:`${l} env.${c} contains unexpanded ${[...new Set(p)].join(",")} \u2014 Claude Code does NOT expand \${VAR} in settings.json (use a fully-literal value)`})}let r=$.PATH;if(typeof r=="string"){let c=r.split(":").filter(Boolean);c.includes("/usr/bin")||i.push({severity:"fail",agent:o,msg:`${l} env.PATH missing /usr/bin \u2014 cat/head/sh/which will fail`}),c.includes("/bin")||i.push({severity:"fail",agent:o,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 c=d.allow,h=d.deny;Array.isArray(c)&&c.length===0&&Array.isArray(h)&&h.length>0&&i.push({severity:"warn",agent:o,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 o of i)t.push({severity:o.severity,group:"Workspace settings",title:`${o.agent}: ${o.msg}`,fix:o.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 ae(t,n){let e=n.webhooks??[],i=[],o=y(process.cwd(),n.workflows?.dir||".agentx/workflows"),s=new Set;try{if(w(o))for(let r of C(o))r.endsWith(".json")&&!r.startsWith("_")&&!r.endsWith(".disabled.json")&&s.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,c]of Object.entries(r.triggers))s.size>0&&!s.has(c)&&i.push({severity:"fail",title:`webhook "${r.id}".triggers["${d}"] -> "${c}" \u2014 no such workflow under ${n.workflows?.dir||".agentx/workflows"}`,fix:"Create the workflow file or fix the id in agentx.json"});r.defaultWorkflow&&s.size>0&&!s.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(w(o)){for(let r of C(o))if(!(!r.endsWith(".json")||r.startsWith("_")||r.endsWith(".disabled.json")))try{let d=JSON.parse(b(y(o,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 u=new Map;for(let r of e){if(!r.enabled)continue;let d=`${r.source}:${r.agentId}`,c=u.get(d);c?i.push({severity:"warn",title:`webhook entries "${c}" 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."}):u.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 $=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"]);for(let[r,d]of Object.entries(n.agents??{})){let c=d.integrations??[];if(!c.length)continue;let h=new Set;for(let p of c){let S=`${p.kind}::${p.label}`;h.has(S)&&i.push({severity:"warn",title:`agents.${r}.integrations: duplicate (${p.kind}, ${p.label})`,fix:"Remove the duplicate or rename one. (kind, label) must be unique per agent."}),h.add(S),$.has(p.kind)||i.push({severity:"warn",title:`agents.${r}.integrations: unknown kind "${p.kind}" on integration "${p.label}"`,fix:'Use a canonical kind from INTEGRATION_KINDS, or "custom" for ad-hoc services.'});let L=p.credentials||{};for(let[q,v]of Object.entries(L))typeof v=="string"&&/^[A-Z][A-Z0-9_]*$/.test(v)&&!process.env[v]&&i.push({severity:"warn",title:`agents.${r}.integrations[${p.kind}/${p.label}].${q} -> $${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.`})}}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 le(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 de(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 o=new AbortController,s=setTimeout(()=>o.abort(),2e3),a=await fetch(e+"/health",{headers:i,signal:o.signal});if(clearTimeout(s),!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 u=le(l.voice);u&&t.push(u)}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 ce(t,n){let e=Object.entries(n.agents||{}).filter(([,o])=>o?.codegraph===!0&&(o.tier==="claude-code"||o.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 o;try{o=m("codegraph",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"CodeGraph",title:`codegraph CLI ${o||"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[o,s]of e){if(!s.workspace||!w(s.workspace)){t.push({severity:"warn",group:"CodeGraph",title:`${o}: workspace missing`,detail:`Workspace path ${s.workspace} does not exist \u2014 codegraph will skip this agent.`});continue}let a=y(s.workspace,".codegraph","codegraph.db");w(a)?t.push({severity:"ok",group:"CodeGraph",title:`${o}: index present`,detail:a}):t.push({severity:"warn",group:"CodeGraph",title:`${o}: index not built yet`,detail:".codegraph/ missing \u2014 daemon will background-index this workspace on next boot.",fix:`Run \`codegraph init --index ${s.workspace}\` to build it now.`})}}function D(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 ue(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,o]of n){console.log(f.bold(" "+i));for(let s of o){let a=s.severity==="ok"?f.green("\u2713"):s.severity==="warn"?f.yellow("!"):f.red("\u2717");console.log(` ${a} ${s.title}`),s.detail&&console.log(f.dim(" "+s.detail.replace(/\n/g,`
|
|
6
6
|
`))),s.fix&&console.log(f.dim(" \u2192 "+s.fix))}console.log()}let e=D(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{P as a,Z as b,Ne as c,J as d,K as e,V as f,U as g,ne as h,oe as i,le as j};
|
|
7
|
-
//# sourceMappingURL=chunk-
|
|
7
|
+
//# sourceMappingURL=chunk-JDX7AYIB.js.map
|