agentix-cli 0.17.0 → 0.18.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.
Files changed (149) hide show
  1. package/dist/agent-RDVGL2TW.js +2 -0
  2. package/dist/audit-Z47AQFFD.js +3 -0
  3. package/dist/audit-Z47AQFFD.js.map +1 -0
  4. package/dist/{board-dashboard-CXIVJKDP.js → board-dashboard-KX2CNOSY.js} +44 -44
  5. package/dist/board-dashboard-KX2CNOSY.js.map +1 -0
  6. package/dist/{chunk-EKTPCSN4.js → chunk-4ITQP3XL.js} +2 -2
  7. package/dist/chunk-53NRX2NA.js +2 -0
  8. package/dist/chunk-53NRX2NA.js.map +1 -0
  9. package/dist/{chunk-5WNGHDFC.js → chunk-ASSJ4Z6Z.js} +11 -11
  10. package/dist/{chunk-5WNGHDFC.js.map → chunk-ASSJ4Z6Z.js.map} +1 -1
  11. package/dist/chunk-BLUXL6HR.js +854 -0
  12. package/dist/chunk-BLUXL6HR.js.map +1 -0
  13. package/dist/chunk-BTAEYL3P.js +72 -0
  14. package/dist/chunk-BTAEYL3P.js.map +1 -0
  15. package/dist/chunk-DJEZ2HVU.js +5 -0
  16. package/dist/chunk-DJEZ2HVU.js.map +1 -0
  17. package/dist/{chunk-SRHLXZRF.js → chunk-DSCMCVTV.js} +3 -3
  18. package/dist/chunk-DSCMCVTV.js.map +1 -0
  19. package/dist/chunk-HPDHNIA3.js +2 -0
  20. package/dist/chunk-IM376SD6.js +13 -0
  21. package/dist/chunk-IM376SD6.js.map +1 -0
  22. package/dist/chunk-J4WKMKTP.js +5 -0
  23. package/dist/{chunk-MBEQASP3.js.map → chunk-J4WKMKTP.js.map} +1 -1
  24. package/dist/chunk-JGXE2YNV.js +46 -0
  25. package/dist/chunk-JGXE2YNV.js.map +1 -0
  26. package/dist/{chunk-TT2Q7YMZ.js → chunk-JXEPJ3YD.js} +6 -6
  27. package/dist/{chunk-TT2Q7YMZ.js.map → chunk-JXEPJ3YD.js.map} +1 -1
  28. package/dist/chunk-LY7JGDV7.js +6 -0
  29. package/dist/chunk-LY7JGDV7.js.map +1 -0
  30. package/dist/chunk-SR3X25TN.js +3 -0
  31. package/dist/chunk-SR3X25TN.js.map +1 -0
  32. package/dist/{chunk-63UYRJIC.js → chunk-TRQSP67X.js} +2 -2
  33. package/dist/chunk-U364GNQX.js +719 -0
  34. package/dist/chunk-U364GNQX.js.map +1 -0
  35. package/dist/chunk-VJUTQAPJ.js +2 -0
  36. package/dist/chunk-VJUTQAPJ.js.map +1 -0
  37. package/dist/cli.js +1 -1
  38. package/dist/cli.js.map +1 -1
  39. package/dist/{compaction-X46EQEPS.js → compaction-S5H6DTOR.js} +4 -4
  40. package/dist/config-UOHEG4BW.js +2 -0
  41. package/dist/config-mutator-KSEBWKJH.js +2 -0
  42. package/dist/{context-planner-G2J7FNNU.js → context-planner-2RGHJHSO.js} +3 -3
  43. package/dist/debug-TGAP7E7W.js +2 -0
  44. package/dist/discover-OATU7SHI.js +4 -0
  45. package/dist/discover-OATU7SHI.js.map +1 -0
  46. package/dist/{editor-chat-R54E65W5.js → editor-chat-FUBQLMAQ.js} +2 -2
  47. package/dist/heal-YP7QI7D3.js +2 -0
  48. package/dist/{inbox-L5ZZ623Y.js → inbox-O5UB3YQN.js} +2 -2
  49. package/dist/index.d.ts +462 -22
  50. package/dist/index.js +8 -8
  51. package/dist/index.js.map +1 -1
  52. package/dist/{ingest-whatsapp-NS4OWDOU.js → ingest-whatsapp-C3O5UPBX.js} +2 -2
  53. package/dist/loader-BGWA7IRY.js +2 -0
  54. package/dist/loader-LBHKSXBK.js +2 -0
  55. package/dist/memory-extract-KKPKAOPH.js +2 -0
  56. package/dist/{processes-XF5CV4LK.js → processes-7W27G3J3.js} +2 -2
  57. package/dist/program-2MDELQLX.js +2 -0
  58. package/dist/providers-WCQSKTNP.js +2 -0
  59. package/dist/query-FZAL7AQD.js +2 -0
  60. package/dist/recipes-LZ56TA3X.js +2 -0
  61. package/dist/registry-ONJSILH4.js +2 -0
  62. package/dist/scheduler-XRM2RJIV.js +2 -0
  63. package/dist/{slack-PSQLVTGB.js → slack-D27BE37Q.js} +2 -2
  64. package/dist/store-4UCO56K2.js +2 -0
  65. package/dist/{subagent-2SJHSSJS.js → subagent-EPOT3QDM.js} +2 -2
  66. package/dist/{task-store-NM7VKNLE.js → task-store-3NUWLYRY.js} +2 -2
  67. package/dist/{telegram-W4SLFMNY.js → telegram-UWV67KWG.js} +2 -2
  68. package/dist/timers-QB4KYNAE.js +2 -0
  69. package/dist/types-ECMEC5BZ.js +2 -0
  70. package/dist/types-TTB6DJUE.js +2 -0
  71. package/dist/{usage-dashboard-AXPXB2KP.js → usage-dashboard-FQGPPABD.js} +2 -2
  72. package/dist/web/workflow-editor.global.js +35 -12
  73. package/dist/web/workflow-editor.global.js.map +1 -1
  74. package/dist/{whatsapp-DCHRBRVV.js → whatsapp-KJ2NRKKQ.js} +2 -2
  75. package/dist/{whatsapp-state-6D6FHHD2.js → whatsapp-state-3ZVQ6MQD.js} +2 -2
  76. package/dist/{wiki-UDPYFJBL.js → wiki-OUYKM7MB.js} +2 -2
  77. package/dist/wiki-OUYKM7MB.js.map +1 -0
  78. package/dist/workspace-setup-6GDBEORT.js +2 -0
  79. package/dist/workspace-setup-6GDBEORT.js.map +1 -0
  80. package/package.json +11 -1
  81. package/dist/agent-4AOMVXRJ.js +0 -2
  82. package/dist/board-dashboard-CXIVJKDP.js.map +0 -1
  83. package/dist/chunk-4HP6UC2X.js +0 -13
  84. package/dist/chunk-4HP6UC2X.js.map +0 -1
  85. package/dist/chunk-ABCHHNG6.js +0 -625
  86. package/dist/chunk-ABCHHNG6.js.map +0 -1
  87. package/dist/chunk-FIOB3MEX.js +0 -2
  88. package/dist/chunk-HCFSHGK4.js +0 -46
  89. package/dist/chunk-HCFSHGK4.js.map +0 -1
  90. package/dist/chunk-HHJGKD5B.js +0 -71
  91. package/dist/chunk-HHJGKD5B.js.map +0 -1
  92. package/dist/chunk-MBEQASP3.js +0 -5
  93. package/dist/chunk-MCJUAE6V.js +0 -6
  94. package/dist/chunk-MCJUAE6V.js.map +0 -1
  95. package/dist/chunk-SRHLXZRF.js.map +0 -1
  96. package/dist/chunk-XDJSYQST.js +0 -6
  97. package/dist/chunk-XDJSYQST.js.map +0 -1
  98. package/dist/chunk-YPOELN6Z.js +0 -798
  99. package/dist/chunk-YPOELN6Z.js.map +0 -1
  100. package/dist/config-KCYHMKCT.js +0 -2
  101. package/dist/config-mutator-QP4GLBOE.js +0 -2
  102. package/dist/debug-3MEUO2P2.js +0 -2
  103. package/dist/heal-JDXUPRET.js +0 -2
  104. package/dist/loader-PTCXLJEX.js +0 -2
  105. package/dist/memory-extract-WH4FZ456.js +0 -2
  106. package/dist/program-FFWEILAS.js +0 -2
  107. package/dist/providers-AKQ4HTB4.js +0 -2
  108. package/dist/query-PKGYE5HR.js +0 -2
  109. package/dist/registry-IFMDJWQ7.js +0 -2
  110. package/dist/scheduler-63D5KFO7.js +0 -2
  111. package/dist/store-5MJOO74U.js +0 -2
  112. package/dist/timers-PCB4ZIBD.js +0 -2
  113. package/dist/types-C7IFH42Z.js +0 -2
  114. package/dist/types-OIFU3KSQ.js +0 -2
  115. package/dist/workspace-setup-C4VB3QZV.js +0 -2
  116. /package/dist/{agent-4AOMVXRJ.js.map → agent-RDVGL2TW.js.map} +0 -0
  117. /package/dist/{chunk-EKTPCSN4.js.map → chunk-4ITQP3XL.js.map} +0 -0
  118. /package/dist/{chunk-FIOB3MEX.js.map → chunk-HPDHNIA3.js.map} +0 -0
  119. /package/dist/{chunk-63UYRJIC.js.map → chunk-TRQSP67X.js.map} +0 -0
  120. /package/dist/{compaction-X46EQEPS.js.map → compaction-S5H6DTOR.js.map} +0 -0
  121. /package/dist/{config-KCYHMKCT.js.map → config-UOHEG4BW.js.map} +0 -0
  122. /package/dist/{config-mutator-QP4GLBOE.js.map → config-mutator-KSEBWKJH.js.map} +0 -0
  123. /package/dist/{context-planner-G2J7FNNU.js.map → context-planner-2RGHJHSO.js.map} +0 -0
  124. /package/dist/{debug-3MEUO2P2.js.map → debug-TGAP7E7W.js.map} +0 -0
  125. /package/dist/{editor-chat-R54E65W5.js.map → editor-chat-FUBQLMAQ.js.map} +0 -0
  126. /package/dist/{heal-JDXUPRET.js.map → heal-YP7QI7D3.js.map} +0 -0
  127. /package/dist/{inbox-L5ZZ623Y.js.map → inbox-O5UB3YQN.js.map} +0 -0
  128. /package/dist/{ingest-whatsapp-NS4OWDOU.js.map → ingest-whatsapp-C3O5UPBX.js.map} +0 -0
  129. /package/dist/{loader-PTCXLJEX.js.map → loader-BGWA7IRY.js.map} +0 -0
  130. /package/dist/{memory-extract-WH4FZ456.js.map → loader-LBHKSXBK.js.map} +0 -0
  131. /package/dist/{program-FFWEILAS.js.map → memory-extract-KKPKAOPH.js.map} +0 -0
  132. /package/dist/{processes-XF5CV4LK.js.map → processes-7W27G3J3.js.map} +0 -0
  133. /package/dist/{providers-AKQ4HTB4.js.map → program-2MDELQLX.js.map} +0 -0
  134. /package/dist/{query-PKGYE5HR.js.map → providers-WCQSKTNP.js.map} +0 -0
  135. /package/dist/{registry-IFMDJWQ7.js.map → query-FZAL7AQD.js.map} +0 -0
  136. /package/dist/{scheduler-63D5KFO7.js.map → recipes-LZ56TA3X.js.map} +0 -0
  137. /package/dist/{store-5MJOO74U.js.map → registry-ONJSILH4.js.map} +0 -0
  138. /package/dist/{task-store-NM7VKNLE.js.map → scheduler-XRM2RJIV.js.map} +0 -0
  139. /package/dist/{slack-PSQLVTGB.js.map → slack-D27BE37Q.js.map} +0 -0
  140. /package/dist/{timers-PCB4ZIBD.js.map → store-4UCO56K2.js.map} +0 -0
  141. /package/dist/{subagent-2SJHSSJS.js.map → subagent-EPOT3QDM.js.map} +0 -0
  142. /package/dist/{types-C7IFH42Z.js.map → task-store-3NUWLYRY.js.map} +0 -0
  143. /package/dist/{telegram-W4SLFMNY.js.map → telegram-UWV67KWG.js.map} +0 -0
  144. /package/dist/{types-OIFU3KSQ.js.map → timers-QB4KYNAE.js.map} +0 -0
  145. /package/dist/{wiki-UDPYFJBL.js.map → types-ECMEC5BZ.js.map} +0 -0
  146. /package/dist/{workspace-setup-C4VB3QZV.js.map → types-TTB6DJUE.js.map} +0 -0
  147. /package/dist/{usage-dashboard-AXPXB2KP.js.map → usage-dashboard-FQGPPABD.js.map} +0 -0
  148. /package/dist/{whatsapp-DCHRBRVV.js.map → whatsapp-KJ2NRKKQ.js.map} +0 -0
  149. /package/dist/{whatsapp-state-6D6FHHD2.js.map → whatsapp-state-3ZVQ6MQD.js.map} +0 -0
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import{a as U}from"./chunk-EKTPCSN4.js";import{a as yt,b as re,c as ae,d as xt,e as Ct,f as Pt,g as $t,h as Tt,i as Rt}from"./chunk-ABCHHNG6.js";import"./chunk-4HP6UC2X.js";import{b as bt}from"./chunk-SRHLXZRF.js";import"./chunk-MBEQASP3.js";import"./chunk-N67JZAXU.js";import"./chunk-CDNWCYF7.js";import"./chunk-AFRHKA7B.js";import"./chunk-EW27SCCC.js";import"./chunk-ZE2YFX4K.js";import{a as lt,b as ct,c as dt,d as pt,g as ut}from"./chunk-HHJGKD5B.js";import"./chunk-5F3J55LG.js";import"./chunk-34NG7UDX.js";import"./chunk-WJXU5F4Z.js";import{a as ft}from"./chunk-LEIYC3BF.js";import{a as gt,b as mt}from"./chunk-WZEYII2S.js";import"./chunk-64P4QHSZ.js";import"./chunk-BFZUG66X.js";import{A as H,B as E,C as I,a as be,b as $e,c as Te,d as je,e as _e,f as Ue,g as Be,h as We,i as qe,j as Ve,k as Ye,l as F,m as Q,n as Ze,o as et,p as tt,q as j,r as st,s as ot,t as nt,u as P,v as Z,w as it,x as rt,y as at,z as ht}from"./chunk-TT2Q7YMZ.js";import{a as X,b as M,c as _}from"./chunk-SFQUP3BP.js";import{d as kt,f as wt,g as St,i as vt}from"./chunk-XDJSYQST.js";import{a as m,b as Re,c as Ae,d as Me,e as Ee,f as Ie,g as Oe,h as Ge,i as De,j as Le,k as Ne,l as Fe,m as A}from"./chunk-HCFSHGK4.js";import{a as He,b as Je,c as N,d as Ke}from"./chunk-MCJUAE6V.js";import{a as ze,b as Xe,e as Qe}from"./chunk-DSYKYZMT.js";import"./chunk-63UYRJIC.js";import"./chunk-QOYAX2FT.js";import"./chunk-FIOB3MEX.js";import{execa as At}from"execa";import{existsSync as le,promises as ee}from"fs";import x from"path";import pe from"node-fetch";async function Mt(n,e){let t=n.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${n}. Expected format: owner/repo`);let s=t[0],i=t[1],o=t[2];try{let a=o?`${s}/${i}/${o}`:`${s}/${i}`;await At("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${n}`);let r=x.resolve(e,".skills",`${s}_${i}`);if(le(r))return await de(r,n);let l=x.resolve(e,".skills");return le(l)?await de(l,n):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Et(s,i,o,e)}}async function Et(n,e,t,s){let i=[];try{let o=`https://api.github.com/repos/${n}/${e}/git/trees/main?recursive=1`,a=await pe(o);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let l=(await a.json()).tree.filter(c=>c.type==="blob"&&c.path.endsWith("SKILL.md"));if(t){let c=l.find(g=>g.path.includes(`/${t}/`)||g.path===`${t}/SKILL.md`);if(c){let g=await ce(n,e,c.path,s);g&&i.push(g)}}else for(let c of l){let g=await ce(n,e,c.path,s);g&&i.push(g)}}catch(o){m.error(`Failed to fetch skills from GitHub: ${o.message}`)}return i}async function ce(n,e,t,s){try{let i=`https://raw.githubusercontent.com/${n}/${e}/main/${t}`,o=await pe(i);if(!o.ok)return null;let a=await o.text(),r=N(a);if(r){r.source="remote",r.packageId=`${n}/${e}`;let l=x.dirname(t),c=x.resolve(s,".skills",`${n}_${e}`,l);await ee.mkdir(c,{recursive:!0}),await ee.writeFile(x.resolve(c,"SKILL.md"),a),r.path=x.resolve(c,"SKILL.md")}return r}catch{return null}}async function de(n,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:n,deep:5});for(let o of i)try{let a=x.resolve(n,o),r=await ee.readFile(a,"utf8"),l=N(r);l&&(l.source="remote",l.path=a,l.packageId=e,t.push(l))}catch{}return t}async function It(n,e,t,s,i){let o=["---",`name: ${n}`,`description: ${e}`];if(s?.length){o.push("tags:");for(let a of s)o.push(` - ${a}`)}if(i?.length){o.push("globs:");for(let a of i)o.push(` - ${a}`)}return o.push("---"),`${o.join(`
1
+ import{a as U}from"./chunk-4ITQP3XL.js";import{a as yt,b as re,c as ae,d as vt,e as xt,f as Ct,h as bt,i as $t,j as Tt}from"./chunk-U364GNQX.js";import"./chunk-IM376SD6.js";import"./chunk-ZE2YFX4K.js";import{A as H,B as E,C as I,a as be,b as $e,c as Te,d as je,e as _e,f as Ue,g as Be,h as We,i as qe,j as Ve,k as Ye,l as F,m as Q,n as Ze,o as et,p as tt,q as j,r as st,s as ot,t as nt,u as P,v as Z,w as it,x as rt,y as at,z as ht}from"./chunk-JXEPJ3YD.js";import{b as Pt}from"./chunk-DSCMCVTV.js";import"./chunk-J4WKMKTP.js";import{c as kt,e as wt,f as St}from"./chunk-LY7JGDV7.js";import"./chunk-N67JZAXU.js";import"./chunk-CDNWCYF7.js";import"./chunk-AFRHKA7B.js";import"./chunk-EW27SCCC.js";import{a as lt,b as ct,c as dt,d as pt,h as ut}from"./chunk-BTAEYL3P.js";import"./chunk-34NG7UDX.js";import"./chunk-5F3J55LG.js";import"./chunk-WJXU5F4Z.js";import{a as ft}from"./chunk-LEIYC3BF.js";import{a as gt,b as mt}from"./chunk-WZEYII2S.js";import"./chunk-64P4QHSZ.js";import"./chunk-BFZUG66X.js";import"./chunk-SR3X25TN.js";import"./chunk-53NRX2NA.js";import{a as X,b as M,c as _}from"./chunk-SFQUP3BP.js";import{a as Re,b as Ae,c as Me,d as Ee,e as Ie,f as Oe,g as Ge,h as De,i as Le,j as Ne,k as Fe,l as A}from"./chunk-JGXE2YNV.js";import{a as m}from"./chunk-VJUTQAPJ.js";import{a as He,b as Je,c as N,d as Ke}from"./chunk-DJEZ2HVU.js";import{a as ze,b as Xe,e as Qe}from"./chunk-DSYKYZMT.js";import"./chunk-TRQSP67X.js";import"./chunk-QOYAX2FT.js";import"./chunk-HPDHNIA3.js";import{execa as Rt}from"execa";import{existsSync as le,promises as ee}from"fs";import x from"path";import pe from"node-fetch";async function At(n,e){let t=n.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${n}. Expected format: owner/repo`);let s=t[0],i=t[1],o=t[2];try{let a=o?`${s}/${i}/${o}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${n}`);let r=x.resolve(e,".skills",`${s}_${i}`);if(le(r))return await de(r,n);let l=x.resolve(e,".skills");return le(l)?await de(l,n):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Mt(s,i,o,e)}}async function Mt(n,e,t,s){let i=[];try{let o=`https://api.github.com/repos/${n}/${e}/git/trees/main?recursive=1`,a=await pe(o);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let l=(await a.json()).tree.filter(c=>c.type==="blob"&&c.path.endsWith("SKILL.md"));if(t){let c=l.find(g=>g.path.includes(`/${t}/`)||g.path===`${t}/SKILL.md`);if(c){let g=await ce(n,e,c.path,s);g&&i.push(g)}}else for(let c of l){let g=await ce(n,e,c.path,s);g&&i.push(g)}}catch(o){m.error(`Failed to fetch skills from GitHub: ${o.message}`)}return i}async function ce(n,e,t,s){try{let i=`https://raw.githubusercontent.com/${n}/${e}/main/${t}`,o=await pe(i);if(!o.ok)return null;let a=await o.text(),r=N(a);if(r){r.source="remote",r.packageId=`${n}/${e}`;let l=x.dirname(t),c=x.resolve(s,".skills",`${n}_${e}`,l);await ee.mkdir(c,{recursive:!0}),await ee.writeFile(x.resolve(c,"SKILL.md"),a),r.path=x.resolve(c,"SKILL.md")}return r}catch{return null}}async function de(n,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:n,deep:5});for(let o of i)try{let a=x.resolve(n,o),r=await ee.readFile(a,"utf8"),l=N(r);l&&(l.source="remote",l.path=a,l.packageId=e,t.push(l))}catch{}return t}async function Et(n,e,t,s,i){let o=["---",`name: ${n}`,`description: ${e}`];if(s?.length){o.push("tags:");for(let a of s)o.push(` - ${a}`)}if(i?.length){o.push("globs:");for(let a of i)o.push(` - ${a}`)}return o.push("---"),`${o.join(`
2
2
  `)}
3
3
 
4
- ${t}`}async function Ot(n){let{loadLocalSkills:e}=await import("./loader-PTCXLJEX.js");return e(n)}async function Gt(n,e,t,s,i){let a=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).
4
+ ${t}`}async function It(n){let{loadLocalSkills:e}=await import("./loader-LBHKSXBK.js");return e(n)}async function Ot(n,e,t,s,i){let a=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).
5
5
  You create high-quality SKILL.md files that provide reusable instructions for AI coding agents.
6
6
 
7
7
  A skill is a markdown document with YAML frontmatter that teaches an agent how to perform a specific task.
@@ -23,7 +23,7 @@ The skill should contain detailed instructions for an AI agent to follow when pe
23
23
  1. Step-by-step instructions
24
24
  2. Code patterns and conventions to follow
25
25
  3. Common pitfalls to avoid
26
- 4. Examples where helpful`}],l=(await n.generate(a,{temperature:.7,maxTokens:4096})).content.trim(),c={frontmatter:{name:e,description:t},instructions:l,source:"generated"},g=l.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);return g&&(c.instructions=g[2].trim()),{skill:c,content:l}}import{existsSync as Dt,promises as ge}from"fs";import te from"path";var Lt={enabled:!0,autoSkills:!0,minFrequency:3,provider:"claude-code"},b=class{constructor(e,t,s){this.cwd=e;this.memory=t;this.config={...Lt,...s}}config;async enhance(){if(!this.config.enabled)return{skillsCreated:[],skillsUpdated:[],insights:[]};let e={skillsCreated:[],skillsUpdated:[],insights:[]};if(this.config.autoSkills){let i=await this.createSkillsFromPatterns();e.skillsCreated.push(...i)}let t=this.analyzeFailures();e.insights.push(...t);let s=this.analyzePreferences();return e.insights.push(...s),e}async createSkillsFromPatterns(){let t=this.memory.getPatterns().filter(o=>o.frequency>=this.config.minFrequency);if(!t.length)return[];let s=[],i=te.resolve(this.cwd,".skills","_auto");for(let o of t.slice(0,3)){let a=Nt(o),r=te.resolve(i,a,"SKILL.md");if(!Dt(r))try{let l=await this.generateSkillFromPattern(o);l&&(await ge.mkdir(te.dirname(r),{recursive:!0}),await ge.writeFile(r,l,"utf8"),s.push(a))}catch{}}return s}async generateSkillFromPattern(e){let t=this.memory.getRecentGenerations(20).filter(r=>r.success&&r.userFeedback!=="negative").slice(0,3);if(!t.length)return null;let s=A(this.config.provider,this.config.apiKey),i=await X(this.cwd),o=[{role:"system",content:`You are a skill author. Create a SKILL.md file that captures a successful pattern.
26
+ 4. Examples where helpful`}],l=(await n.generate(a,{temperature:.7,maxTokens:4096})).content.trim(),c={frontmatter:{name:e,description:t},instructions:l,source:"generated"},g=l.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);return g&&(c.instructions=g[2].trim()),{skill:c,content:l}}import{existsSync as Gt,promises as ge}from"fs";import te from"path";var Dt={enabled:!0,autoSkills:!0,minFrequency:3,provider:"claude-code"},b=class{constructor(e,t,s){this.cwd=e;this.memory=t;this.config={...Dt,...s}}config;async enhance(){if(!this.config.enabled)return{skillsCreated:[],skillsUpdated:[],insights:[]};let e={skillsCreated:[],skillsUpdated:[],insights:[]};if(this.config.autoSkills){let i=await this.createSkillsFromPatterns();e.skillsCreated.push(...i)}let t=this.analyzeFailures();e.insights.push(...t);let s=this.analyzePreferences();return e.insights.push(...s),e}async createSkillsFromPatterns(){let t=this.memory.getPatterns().filter(o=>o.frequency>=this.config.minFrequency);if(!t.length)return[];let s=[],i=te.resolve(this.cwd,".skills","_auto");for(let o of t.slice(0,3)){let a=Lt(o),r=te.resolve(i,a,"SKILL.md");if(!Gt(r))try{let l=await this.generateSkillFromPattern(o);l&&(await ge.mkdir(te.dirname(r),{recursive:!0}),await ge.writeFile(r,l,"utf8"),s.push(a))}catch{}}return s}async generateSkillFromPattern(e){let t=this.memory.getRecentGenerations(20).filter(r=>r.success&&r.userFeedback!=="negative").slice(0,3);if(!t.length)return null;let s=A(this.config.provider,this.config.apiKey),i=await X(this.cwd),o=[{role:"system",content:`You are a skill author. Create a SKILL.md file that captures a successful pattern.
27
27
  Tech stack: ${M(i)}
28
28
  Output ONLY the SKILL.md content with YAML frontmatter. No code fences.`},{role:"user",content:`Create a skill from this recurring pattern:
29
29
 
@@ -36,7 +36,7 @@ ${t.map(r=>`- "${r.task}" \u2192 ${r.files.join(", ")}`).join(`
36
36
  `)}
37
37
 
38
38
  Create a concise, reusable skill that captures what worked.`}];return(await s.generate(o,{maxTokens:2048,temperature:.7})).content.trim()||null}analyzeFailures(){let e=[],t=this.memory.getFailedGenerations(20);if(t.length<2)return e;let s=new Map;for(let o of t){let a=(o.error||"unknown").split(`
39
- `)[0].slice(0,80),r=s.get(a)||[];r.push(o),s.set(a,r)}for(let[o,a]of s)a.length>=2&&e.push(`Recurring error (${a.length}x): "${o}" \u2014 consider creating a skill to prevent this`);let i=this.memory.getStats();return i.successRate<.7&&i.totalGenerations>5&&e.push(`Success rate is ${(i.successRate*100).toFixed(0)}% \u2014 review recent failures and update skills`),e}analyzePreferences(){let e=[],s=this.memory.getPreferences().filter(i=>i.confidence>.8);return s.length&&e.push(`Strong preferences detected: ${s.map(i=>`${i.key}=${i.value}`).join(", ")}`),e}};function Nt(n){return n.description.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").slice(0,40).replace(/-+$/,"")}var $=class{middleware=[];use(e,t){return this.middleware.push({name:e,fn:t}),this}async execute(e){let t={id:e.id,success:!1,files:[],content:"",outputType:e.outputType||"auto",duration:0},s={startTime:Date.now()},i=0,o=async()=>{if(i>=this.middleware.length)return;await this.middleware[i++].fn(e,t,s,o)};try{await o(),t.duration=Date.now()-s.startTime}catch(a){t.success=!1,t.error=a.message,t.duration=Date.now()-s.startTime}return t}getMiddlewareNames(){return this.middleware.map(e=>e.name)}};import{createServer as Ft}from"http";var jt={port:3170,host:"0.0.0.0",provider:"claude-code",cwd:process.cwd(),memory:{enabled:!0},heal:{enabled:!0},enhance:{enabled:!0,autoSkills:!0},cors:!0},J=class{config;memory;healEngine;enhanceEngine;pipeline;requestCount=0;log;constructor(e){this.config={...jt,...e},this.memory=new _(this.config.cwd),this.healEngine=new U(this.config.cwd,{enabled:this.config.heal.enabled,testCommand:this.config.heal.testCommand,buildCommand:this.config.heal.buildCommand,provider:this.config.provider,model:this.config.model,apiKey:this.config.apiKey}),this.enhanceEngine=new b(this.config.cwd,this.memory,{enabled:this.config.enhance.enabled,autoSkills:this.config.enhance.autoSkills,provider:this.config.provider,model:this.config.model,apiKey:this.config.apiKey}),this.pipeline=this.buildPipeline(),this.log=console.error.bind(console,"[agentx]")}buildPipeline(){let e=new $;return e.use("memory",this.memoryMiddleware()),e.use("context",this.contextMiddleware()),e.use("generate",this.generateMiddleware()),e.use("heal",this.healMiddleware()),e.use("record",this.recordMiddleware()),e.use("enhance",this.enhanceMiddleware()),e}async start(){await this.memory.load(),Ft(async(t,s)=>{if(this.config.cors&&(s.setHeader("Access-Control-Allow-Origin","*"),s.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),s.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),t.method==="OPTIONS")){s.writeHead(204),s.end();return}await this.handleRequest(t,s)}).listen(this.config.port,this.config.host,()=>{this.log(`
39
+ `)[0].slice(0,80),r=s.get(a)||[];r.push(o),s.set(a,r)}for(let[o,a]of s)a.length>=2&&e.push(`Recurring error (${a.length}x): "${o}" \u2014 consider creating a skill to prevent this`);let i=this.memory.getStats();return i.successRate<.7&&i.totalGenerations>5&&e.push(`Success rate is ${(i.successRate*100).toFixed(0)}% \u2014 review recent failures and update skills`),e}analyzePreferences(){let e=[],s=this.memory.getPreferences().filter(i=>i.confidence>.8);return s.length&&e.push(`Strong preferences detected: ${s.map(i=>`${i.key}=${i.value}`).join(", ")}`),e}};function Lt(n){return n.description.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").slice(0,40).replace(/-+$/,"")}var $=class{middleware=[];use(e,t){return this.middleware.push({name:e,fn:t}),this}async execute(e){let t={id:e.id,success:!1,files:[],content:"",outputType:e.outputType||"auto",duration:0},s={startTime:Date.now()},i=0,o=async()=>{if(i>=this.middleware.length)return;await this.middleware[i++].fn(e,t,s,o)};try{await o(),t.duration=Date.now()-s.startTime}catch(a){t.success=!1,t.error=a.message,t.duration=Date.now()-s.startTime}return t}getMiddlewareNames(){return this.middleware.map(e=>e.name)}};import{createServer as Nt}from"http";var Ft={port:3170,host:"0.0.0.0",provider:"claude-code",cwd:process.cwd(),memory:{enabled:!0},heal:{enabled:!0},enhance:{enabled:!0,autoSkills:!0},cors:!0},J=class{config;memory;healEngine;enhanceEngine;pipeline;requestCount=0;log;constructor(e){this.config={...Ft,...e},this.memory=new _(this.config.cwd),this.healEngine=new U(this.config.cwd,{enabled:this.config.heal.enabled,testCommand:this.config.heal.testCommand,buildCommand:this.config.heal.buildCommand,provider:this.config.provider,model:this.config.model,apiKey:this.config.apiKey}),this.enhanceEngine=new b(this.config.cwd,this.memory,{enabled:this.config.enhance.enabled,autoSkills:this.config.enhance.autoSkills,provider:this.config.provider,model:this.config.model,apiKey:this.config.apiKey}),this.pipeline=this.buildPipeline(),this.log=console.error.bind(console,"[agentx]")}buildPipeline(){let e=new $;return e.use("memory",this.memoryMiddleware()),e.use("context",this.contextMiddleware()),e.use("generate",this.generateMiddleware()),e.use("heal",this.healMiddleware()),e.use("record",this.recordMiddleware()),e.use("enhance",this.enhanceMiddleware()),e}async start(){await this.memory.load(),Nt(async(t,s)=>{if(this.config.cors&&(s.setHeader("Access-Control-Allow-Origin","*"),s.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),s.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),t.method==="OPTIONS")){s.writeHead(204),s.end();return}await this.handleRequest(t,s)}).listen(this.config.port,this.config.host,()=>{this.log(`
40
40
  agentx runtime v0.1.0`),this.log(` Listening on http://${this.config.host}:${this.config.port}`),this.log(` Provider: ${this.config.provider}`),this.log(` Memory: ${this.config.memory.enabled?"enabled":"disabled"}`),this.log(` Auto-heal: ${this.config.heal.enabled?"enabled":"disabled"}`),this.log(` Self-enhance: ${this.config.enhance.enabled?"enabled":"disabled"}`),this.log(` Pipeline: ${this.pipeline.getMiddlewareNames().join(" \u2192 ")}`),this.log(` Working dir: ${this.config.cwd}`),this.log(""),this.log(" Endpoints:"),this.log(" POST /generate \u2014 generate code/content"),this.log(" POST /evolve \u2014 transform existing code"),this.log(" GET /inspect \u2014 project analysis"),this.log(" GET /memory \u2014 view learning history"),this.log(" POST /feedback \u2014 provide feedback on a generation"),this.log(" GET /health \u2014 health check"),this.log(" POST /enhance \u2014 trigger self-enhancement"),this.log("")})}async handleRequest(e,t){let s=new URL(e.url||"/",`http://${e.headers.host||"localhost"}`),i=e.method||"GET",o=s.pathname;this.log(`${i} ${o}`);try{switch(`${i} ${o}`){case"POST /generate":await this.handleGenerate(e,t);break;case"POST /evolve":await this.handleEvolve(e,t);break;case"GET /inspect":await this.handleInspect(t);break;case"GET /memory":await this.handleMemory(t);break;case"POST /feedback":await this.handleFeedback(e,t);break;case"GET /health":this.sendJson(t,200,{status:"ok",uptime:process.uptime(),requests:this.requestCount,stats:this.memory.getStats(),pipeline:this.pipeline.getMiddlewareNames()});break;case"POST /enhance":await this.handleEnhance(t);break;default:this.sendJson(t,404,{error:"Not found",endpoints:["POST /generate","POST /evolve","GET /inspect","GET /memory","POST /feedback","GET /health","POST /enhance"]})}}catch(a){this.log("Error:",a.message),this.sendJson(t,500,{error:a.message})}this.requestCount++}async handleGenerate(e,t){let s=await se(e);if(!s.task){this.sendJson(t,400,{error:"Missing required field: task"});return}let i={id:`req-${Date.now().toString(36)}`,task:s.task,outputType:s.type||s.outputType||"auto",outputDir:s.outputDir||s.output_dir,provider:s.provider||this.config.provider,model:s.model||this.config.model,apiKey:s.apiKey||s.api_key||this.config.apiKey,cwd:this.config.cwd,overwrite:s.overwrite??!0,metadata:s.metadata},o=await this.pipeline.execute(i);this.sendJson(t,o.success?200:500,o)}async handleEvolve(e,t){let s=await se(e);if(!s.task||!s.glob){this.sendJson(t,400,{error:"Missing required fields: task, glob"});return}this.sendJson(t,200,{message:'Use the CLI for evolve: agentx evolve "'+s.task+'" --glob "'+s.glob+'"',hint:"The evolve endpoint requires interactive diff review. Use the CLI for full functionality."})}async handleInspect(e){let t=await H(this.config.cwd,"inspect",{context7:{enabled:!1}});this.sendJson(e,200,{techStack:{languages:t.techStack.languages,frameworks:t.techStack.frameworks,packageManager:t.techStack.packageManager,databases:t.techStack.databases,styling:t.techStack.styling,testing:t.techStack.testing,deployment:t.techStack.deployment,monorepo:t.techStack.monorepo},schemas:{database:t.schemas.database?{type:t.schemas.database.type,tables:t.schemas.database.tables}:null,api:t.schemas.api?{type:t.schemas.api.type}:null,env:t.schemas.env,models:t.schemas.models?.map(s=>({path:s.path,type:s.type}))},skills:t.skills.map(s=>({name:s.frontmatter.name,description:s.frontmatter.description,source:s.source,tags:s.frontmatter.tags})),dependencies:Object.keys(t.techStack.dependencies).length,devDependencies:Object.keys(t.techStack.devDependencies).length})}async handleMemory(e){this.sendJson(e,200,{stats:this.memory.getStats(),recent:this.memory.getRecentGenerations(10),patterns:this.memory.getPatterns().slice(0,10),preferences:this.memory.getPreferences()})}async handleFeedback(e,t){let s=await se(e);if(!s.entryId||!s.feedback){this.sendJson(t,400,{error:"Missing required fields: entryId, feedback (positive/negative/neutral)"});return}await this.memory.recordFeedback(s.entryId,s.feedback),this.sendJson(t,200,{recorded:!0})}async handleEnhance(e){let t=await this.enhanceEngine.enhance();this.sendJson(e,200,t)}memoryMiddleware(){let e=this.memory;return async(t,s,i,o)=>{i.memory=e;let a=e.buildMemoryContext(t.task);a&&(i.memoryContext=a),await o()}}contextMiddleware(){return async(e,t,s,i)=>{s.agentContext=await H(e.cwd,e.task,{provider:e.provider,context7:{enabled:!0}}),await i()}}generateMiddleware(){return async(e,t,s,i)=>{let o=await E({task:s.memoryContext?`${e.task}
41
41
 
42
42
  ${s.memoryContext}`:e.task,outputType:e.outputType,outputDir:e.outputDir,overwrite:e.overwrite??!0,cwd:e.cwd,provider:e.provider||this.config.provider,model:e.model||this.config.model,apiKey:e.apiKey||this.config.apiKey,context7:!0,interactive:!1,maxSteps:5});t.success=o.files.errors.length===0,t.files=o.files.written.map(a=>({path:a})),t.content=o.content,t.outputType=o.outputType,t.tokensUsed=o.tokensUsed,await i()}}healMiddleware(){let e=this.healEngine;return async(t,s,i,o)=>{if(this.config.heal.enabled&&s.files.length>0){let a=await e.detectAndHeal(s.files.map(r=>r.path),t.task,s.memoryEntryId);a.attempts>0&&(s.healed=a.healed,s.healAttempts=a.attempts,a.healed&&(s.success=!0))}await o()}}recordMiddleware(){let e=this.memory;return async(t,s,i,o)=>{if(this.config.memory.enabled){let a=await e.recordGeneration({task:t.task,outputType:s.outputType,files:s.files.map(r=>r.path),success:s.success,error:s.error,context:{techStack:i.agentContext?.techStack.languages.map(r=>r.name),frameworks:i.agentContext?.techStack.frameworks.map(r=>r.name)}});s.memoryEntryId=a,t.outputType&&t.outputType!=="auto"&&await e.learnPreference("preferred-output-type",t.outputType,`generation request: ${t.task.slice(0,50)}`)}await o()}}enhanceMiddleware(){let e=this.enhanceEngine;return async(t,s,i,o)=>{this.config.enhance.enabled&&this.requestCount%10===0&&this.requestCount>0&&e.enhance().then(a=>{if(a.skillsCreated.length&&this.log(`Auto-created ${a.skillsCreated.length} skill(s): ${a.skillsCreated.join(", ")}`),a.insights.length)for(let r of a.insights)this.log(`Insight: ${r}`)}).catch(()=>{}),await o()}}sendJson(e,t,s){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(s,null,2))}};async function se(n){return new Promise((e,t)=>{let s="";n.on("data",i=>s+=i),n.on("end",()=>{try{e(s?JSON.parse(s):{})}catch{e({})}}),n.on("error",t)})}import{execa as u}from"execa";var w=class{constructor(e){this.cwd=e}async isRepo(){try{return await u("git",["rev-parse","--is-inside-work-tree"],{cwd:this.cwd,reject:!1}),!0}catch{return!1}}async status(){let t=(await u("git",["status","--porcelain","-b"],{cwd:this.cwd,reject:!1})).stdout.trim().split(`
@@ -51,13 +51,13 @@ Rules:
51
51
 
52
52
  ${t.slice(0,4e3)}`}])).content.trim().split(`
53
53
  `)[0]:this.fallbackCommitMessage(t)}fallbackCommitMessage(e){let t=e.split(`
54
- `),s=[];for(let i of t)if(i.startsWith("diff --git")){let o=i.match(/b\/(.+)$/);o&&s.push(o[1])}return s.length===0?"chore: update files":s.length===1?`chore: update ${s[0]}`:`chore: update ${s.length} files`}};import{createInterface as qt}from"readline";import v from"chalk";import Vt from"ora";import{existsSync as me,mkdirSync as _t,readFileSync as oe,readdirSync as fe,writeFileSync as Ut}from"fs";import O from"path";import Ht from"os";var S=O.join(Ht.homedir(),".agentx","sessions");function ne(){me(S)||_t(S,{recursive:!0})}function T(n){return{id:Jt(),createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),cwd:n,messages:[],tokensUsed:0,filesGenerated:[]}}function R(n){ne();let e=O.join(S,`${n.id}.json`);n.updatedAt=new Date().toISOString(),Ut(e,JSON.stringify(n,null,2),"utf8")}function C(n){let e=O.join(S,`${n}.json`);if(!me(e))return null;try{return JSON.parse(oe(e,"utf8"))}catch{return null}}function K(){ne();let n=fe(S).filter(t=>t.endsWith(".json")).map(t=>({name:t,path:O.join(S,t)}));if(!n.length)return null;let e=null;for(let t of n)try{let s=JSON.parse(oe(t.path,"utf8"));(!e||s.updatedAt>e.session.updatedAt)&&(e={name:t.name,session:s})}catch{}return e?.session??null}function B(){ne();let n=fe(S).filter(t=>t.endsWith(".json")),e=[];for(let t of n)try{let s=JSON.parse(oe(O.join(S,t),"utf8"));e.push(s)}catch{}return e.sort((t,s)=>s.updatedAt.localeCompare(t.updatedAt)),e}function Jt(){return Math.random().toString(36).slice(2,10)+Date.now().toString(36).slice(-4)}import p from"chalk";import{writeFileSync as Kt}from"fs";import Bt from"path";import d from"chalk";function ue(n,e){console.log(),console.log(d.bold.cyan(" agentx")+d.dim(` v${n}`)),console.log(d.dim(` Session: ${e}`)),console.log(d.dim(" Type /help for commands, /quit to exit")),console.log()}function he(n){if(n.written.length){console.log(),console.log(d.green(` Created ${n.written.length} file(s):`));for(let e of n.written)console.log(` ${d.green("+")} ${e}`)}if(n.skipped.length){console.log(),console.log(d.yellow(` Skipped ${n.skipped.length} file(s):`));for(let e of n.skipped)console.log(` ${d.yellow("~")} ${e}`)}if(n.errors.length){console.log(),console.log(d.red(` Failed ${n.errors.length} file(s):`));for(let e of n.errors)console.log(` ${d.red("x")} ${e}`)}}function G(n){let e=n/1e6*9;console.log(),console.log(d.dim(` Tokens: ${n.toLocaleString()} | Est. cost: $${e.toFixed(4)}`))}function ye(n){process.stdout.write(n)}function ke(){console.log(),console.log(d.bold(" Commands:")),console.log(),console.log(` ${d.cyan("/help")} Show this help`),console.log(` ${d.cyan("/clear")} Clear conversation history`),console.log(` ${d.cyan("/save")} Save current session`),console.log(` ${d.cyan("/load")} Load a saved session`),console.log(` ${d.cyan("/undo")} Undo last generation`),console.log(` ${d.cyan("/cost")} Show token usage and cost breakdown`),console.log(` ${d.cyan("/export")} Export session as markdown`),console.log(` ${d.cyan("/files")} List generated files`),console.log(` ${d.cyan("/context")} Show session context info`),console.log(` ${d.cyan("/memory")} Show memory stats and preferences`),console.log(` ${d.cyan("/mode")} Switch permission mode`),console.log(` ${d.cyan("/commit")} Commit generated files with AI message`),console.log(` ${d.cyan("/diff")} Show git diff`),console.log(` ${d.cyan("/status")} Show git status`),console.log(` ${d.cyan("/quit")} Exit the REPL`),console.log()}function we(n){if(console.log(),console.log(d.dim(` Branch: ${n.branch}`)),n.isClean){console.log(d.green(" Working tree clean"));return}n.staged.length&&console.log(d.green(` Staged: ${n.staged.length}`)),n.modified.length&&console.log(d.yellow(` Modified: ${n.modified.length}`)),n.untracked.length&&console.log(d.dim(` Untracked: ${n.untracked.length}`)),console.log()}function Se(n){if(console.log(),console.log(d.bold(" Cost Breakdown")),console.log(),console.log(d.dim(` Total: ${n.totalTokens.toLocaleString()} tokens ($${n.totalCost.toFixed(4)})`)),console.log(d.dim(` Input: ${n.totalInputTokens.toLocaleString()} | Output: ${n.totalOutputTokens.toLocaleString()}`)),Object.keys(n.models).length){console.log(),console.log(d.dim(" Per model:"));for(let[e,t]of Object.entries(n.models))console.log(` ${d.cyan(e)}: ${(t.inputTokens+t.outputTokens).toLocaleString()} tokens, $${t.cost.toFixed(4)} (${t.steps} step${t.steps!==1?"s":""})`)}if(n.steps.length>1){console.log(),console.log(d.dim(" Per step:"));for(let e of n.steps)console.log(` Step ${e.step}: ${(e.inputTokens+e.outputTokens).toLocaleString()} tokens ($${e.cost.toFixed(4)})`)}console.log()}function ve(n){console.log(),console.log(d.bold(" Plan Preview")),console.log(d.dim(" No files will be written in plan mode.")),console.log();for(let e of n){let t=e.action==="create"?d.green("+"):d.yellow("~");console.log(` ${t} ${e.path} (${e.action})`)}console.log()}import Wt from"prompts";var xe={};function f(n,e){xe[n]=e}function W(n){return xe[n]}function q(n){return n.startsWith("/")}function V(n){let e=n.trim(),t=e.indexOf(" ");return t===-1?{name:e.slice(1),args:""}:{name:e.slice(1,t),args:e.slice(t+1).trim()}}f("help",async()=>(ke(),!0));f("quit",async()=>!1);f("exit",async()=>!1);f("q",async()=>!1);f("clear",async(n,e)=>(e.session.messages=[],console.log(p.dim(" Conversation cleared")),!0));f("save",async(n,e)=>(R(e.session),console.log(p.dim(` Session saved: ${e.session.id}`)),!0));f("load",async(n,e)=>{let t=null;if(n){if(t=C(n),!t)return m.warn(`Session not found: ${n}`),!0}else{let s=B();if(!s.length)return m.info("No saved sessions"),!0;let{sessionId:i}=await Wt({type:"select",name:"sessionId",message:"Select a session",choices:s.slice(0,10).map(o=>({title:`${o.id} \u2014 ${new Date(o.updatedAt).toLocaleDateString()} (${o.messages.length} messages)`,value:o.id}))});if(!i)return!0;t=C(i)}return t&&(e.onSessionChange(t),console.log(p.dim(` Loaded session: ${t.id} (${t.messages.length} messages)`))),!0});f("undo",async(n,e)=>{let t=e.session.messages;return t.length<2?(m.info("Nothing to undo"),!0):(t[t.length-1]?.role==="assistant"&&t.pop(),t[t.length-1]?.role==="user"&&t.pop(),console.log(p.dim(" Undid last exchange")),!0)});f("cost",async(n,e)=>{let t=F.getSummary();return t.steps.length>0?Se(t):G(e.session.tokensUsed),!0});f("export",async(n,e)=>{let t=F.getSummary(),s=Q(e.session,t.steps.length?t:void 0),i=n||`session-${e.session.id}.md`,o=Bt.resolve(e.cwd,i);return Kt(o,s,"utf8"),m.success(` Session exported to ${o}`),!0});f("files",async(n,e)=>{let t=e.session.filesGenerated;if(!t.length)return m.info("No files generated in this session"),!0;console.log(),console.log(p.dim(` Files generated (${t.length}):`));for(let s of t)console.log(` ${p.green("+")} ${s}`);return console.log(),!0});f("context",async(n,e)=>(console.log(),console.log(p.dim(` Session: ${e.session.id}`)),console.log(p.dim(` CWD: ${e.session.cwd}`)),console.log(p.dim(` Messages: ${e.session.messages.length}`)),console.log(p.dim(` Tokens: ${e.session.tokensUsed.toLocaleString()}`)),console.log(p.dim(` Files: ${e.session.filesGenerated.length}`)),console.log(p.dim(` Created: ${new Date(e.session.createdAt).toLocaleString()}`)),console.log(),!0));f("memory",async(n,e)=>{try{let t=new Z(e.cwd);await t.load();let s=t.getStats(),i=t.getPreferences(),o=t.getPatterns(),a=t.getRecentGenerations(5);if(console.log(),console.log(p.bold(" Memory")),console.log(),console.log(p.dim(" Project:")),console.log(p.dim(` Generations: ${s.project.totalGenerations}`)),console.log(p.dim(` Success rate: ${(s.project.successRate*100).toFixed(0)}%`)),console.log(p.dim(` Heals: ${s.project.totalHeals}`)),console.log(),console.log(p.dim(" Global:")),console.log(p.dim(` Generations: ${s.user.totalGenerations}`)),console.log(p.dim(` Success rate: ${(s.user.successRate*100).toFixed(0)}%`)),i.length){console.log(),console.log(p.dim(" Preferences:"));for(let r of i.slice(0,10))console.log(p.dim(` ${r.key}: ${r.value} (${(r.confidence*100).toFixed(0)}%)`))}if(o.length){console.log(),console.log(p.dim(" Patterns:"));for(let r of o.slice(0,5))console.log(p.dim(` ${r.description} (${r.frequency}x)`))}if(a.length){console.log(),console.log(p.dim(" Recent:"));for(let r of a){let l=r.success?p.green("ok"):p.red("fail");console.log(p.dim(` [${l}] ${r.task.slice(0,60)}`))}}console.log()}catch(t){m.error(` ${t.message}`)}return!0});f("mode",async(n,e)=>{if(n&&j.includes(n))P.setMode(n),m.success(` Permission mode: ${n}`);else if(n)m.warn(` Unknown mode: ${n}. Valid modes: ${j.join(", ")}`);else{let t=P.getMode();console.log(),console.log(p.dim(` Current mode: ${p.bold(t)}`)),console.log(),console.log(p.dim(" Available modes:")),console.log(p.dim(" default \u2014 confirm each file write")),console.log(p.dim(" acceptEdits \u2014 auto-allow writes, confirm destructive ops")),console.log(p.dim(" plan \u2014 show plan without writing")),console.log(p.dim(" yolo \u2014 auto-allow everything")),console.log(),console.log(p.dim(" Usage: /mode <mode>")),console.log()}return!0});f("commit",async(n,e)=>{try{let t=new w(e.cwd);if(!await t.isRepo())return m.warn("Not a git repository"),!0;let s=e.session.filesGenerated.filter(r=>r);if(s.length&&(await t.add(s),console.log(p.dim(` Staged ${s.length} generated file(s)`))),(await t.status()).staged.length===0)return m.warn("Nothing staged to commit"),!0;let o;try{let r=A();o=await t.generateCommitMessage(r)}catch{o=await t.generateCommitMessage()}console.log(p.dim(` Message: ${o}`));let a=await t.commit(o);m.success(` [${a.hash}] ${a.message}`)}catch(t){m.error(` ${t.message}`)}return!0});f("diff",async(n,e)=>{try{let s=await new w(e.cwd).diff();s.trim()?console.log(s):m.info("No changes")}catch(t){m.error(` ${t.message}`)}return!0});f("status",async(n,e)=>{try{let t=new w(e.cwd);if(!await t.isRepo())return m.warn("Not a git repository"),!0;let s=await t.status();we(s)}catch(t){m.error(` ${t.message}`)}return!0});var Y=class{rl=null;session;options;running=!1;constructor(e){if(this.options=e,e.sessionId){let t=C(e.sessionId);t?this.session=t:(m.warn(`Session ${e.sessionId} not found, starting new session`),this.session=T(e.cwd))}else if(e.resume){let t=K();t?(this.session=t,m.info(`Resumed session: ${t.id}`)):(m.info("No previous session found, starting new session"),this.session=T(e.cwd))}else this.session=T(e.cwd)}async start(){this.running=!0,ue(this.options.version,this.session.id),this.session.messages.length>0&&(console.log(v.dim(` Resumed with ${this.session.messages.length} messages, ${this.session.tokensUsed.toLocaleString()} tokens`)),console.log()),this.rl=qt({input:process.stdin,output:process.stdout,prompt:v.cyan("agentx > "),terminal:!0}),this.rl.prompt(),this.rl.on("line",async e=>{let t=e.trim();if(!t){this.rl?.prompt();return}try{if(q(t)){if(!await this.handleCommand(t)){this.stop();return}}else await this.handleGeneration(t)}catch(s){m.error(` Error: ${s.message}`)}this.running&&this.rl?.prompt()}),this.rl.on("close",()=>{this.stop()}),this.rl.on("SIGINT",()=>{console.log(),this.stop()})}stop(){this.running=!1,R(this.session),console.log(),console.log(v.dim(` Session saved: ${this.session.id}`)),G(this.session.tokensUsed),console.log(),this.rl?.close(),process.exit(0)}async handleCommand(e){let{name:t,args:s}=V(e),i=W(t);if(!i)return m.warn(` Unknown command: /${t}. Type /help for available commands.`),!0;let o={session:this.session,cwd:this.options.cwd,onSessionChange:a=>{this.session=a}};return i(s,o)}async handleGeneration(e){let t=Vt({text:"Thinking...",color:"cyan"}).start();try{let s=this.session.messages.filter(r=>r.role!=="system").map(r=>({role:r.role,content:r.content})),i={task:e,cwd:this.options.cwd,provider:this.options.provider||"claude-code",model:this.options.model,apiKey:this.options.apiKey,overwrite:!0,dryRun:!1,interactive:!1,context7:!0,sessionMessages:s},o,a=!1;for await(let r of I(i)){if(r.type==="context_ready"){t.stop(),console.log(),a=!0;continue}if(r.type==="text_delta"){ye(r.text);continue}if(r.type==="done"){console.log();continue}if(r.type==="error")throw new Error(r.error);if(r.type==="step_complete"){r.step>1&&console.log(v.dim(` Step ${r.step}: ${r.filesCount} file(s)`));continue}r.type==="generate_result"&&(o=r.result)}if(a||t.stop(),!o)return;(o.files.written.length||o.files.skipped.length||o.files.errors.length)&&(P.getMode()==="plan"?ve(o.files.written.map(r=>({path:r,action:"create"}))):he(o.files)),o.tokensUsed&&G(o.tokensUsed),this.session.messages.push({role:"user",content:e}),this.session.messages.push({role:"assistant",content:o.content||""}),this.session.tokensUsed+=o.tokensUsed||0,this.session.filesGenerated.push(...o.files.written),o.followUp&&(console.log(),console.log(v.yellow(` ${o.followUp}`))),o.healResult&&(console.log(),o.healResult.healed?console.log(v.green(` Heal: passed verification${o.healResult.attempts>0?` (fixed in ${o.healResult.attempts} attempt(s))`:""}`)):o.healResult.error&&(console.log(v.red(` Heal: verification failed after ${o.healResult.attempts} attempt(s)`)),console.log(v.dim(` ${o.healResult.error.split(`
55
- `)[0]}`))))}catch(s){throw t.stop(),s}}};import{createServer as Yt}from"http";var y={TASK_NOT_FOUND:{code:-32001,message:"Task not found"},TASK_NOT_CANCELABLE:{code:-32002,message:"Task cannot be canceled"},INVALID_PARAMS:{code:-32602,message:"Invalid params"},INTERNAL_ERROR:{code:-32603,message:"Internal error"},METHOD_NOT_FOUND:{code:-32601,message:"Method not found"},PARSE_ERROR:{code:-32700,message:"Parse error"}};var zt={port:3171,host:"0.0.0.0",provider:"claude-code",cwd:process.cwd(),cors:!0},z=class{config;tasks=new Map;activeCancellations=new Set;log;constructor(e){this.config={...zt,...e},this.log=console.error.bind(console,"[a2a]")}async start(){Yt(async(t,s)=>{if(this.config.cors&&(s.setHeader("Access-Control-Allow-Origin","*"),s.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),s.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),t.method==="OPTIONS")){s.writeHead(204),s.end();return}await this.handleRequest(t,s)}).listen(this.config.port,this.config.host,()=>{this.log(`
56
- agentx A2A server v0.1.0`),this.log(` Listening on http://${this.config.host}:${this.config.port}`),this.log(` Provider: ${this.config.provider}`),this.log(` Working dir: ${this.config.cwd}`),this.log(""),this.log(" Discovery:"),this.log(" GET /.well-known/agent-card.json"),this.log(""),this.log(" JSON-RPC 2.0 methods:"),this.log(" tasks/send \u2014 synchronous task execution"),this.log(" tasks/sendSubscribe \u2014 streaming task execution (SSE)"),this.log(" tasks/get \u2014 retrieve task state"),this.log(" tasks/cancel \u2014 cancel running task"),this.log("")})}getAgentCard(){return{name:"agentx",description:"AI-powered agentic code generation agent. Generates components, pages, APIs, documents, skills, and more for any tech stack.",url:`http://${this.config.host}:${this.config.port}`,version:"0.1.0",capabilities:{streaming:!0,pushNotifications:!1,stateTransitionHistory:!0},skills:[{id:"generate",name:"Code Generation",description:"Generate code files from natural language descriptions. Supports components, pages, APIs, tests, schemas, and more.",tags:["code-generation","ai","multi-framework"],examples:["Create a React login form with email and password validation","Generate a REST API for user management with CRUD operations","Build a dashboard page with charts and data tables"]},{id:"evolve",name:"Code Transformation",description:"Transform existing code files based on natural language instructions. Applies targeted edits with diff preview.",tags:["code-transformation","refactoring","ai"],examples:["Add dark mode support to this component","Refactor this API to use async/await instead of callbacks"]},{id:"inspect",name:"Project Analysis",description:"Analyze a project's tech stack, schemas, dependencies, and structure.",tags:["analysis","project-inspection"],examples:["What tech stack does this project use?","List all API schemas in the project"]}],defaultInputModes:["text"],defaultOutputModes:["text","file"]}}async handleRequest(e,t){let s=new URL(e.url||"/",`http://${e.headers.host||"localhost"}`),i=e.method||"GET",o=s.pathname;this.log(`${i} ${o}`);try{if(i==="GET"&&o==="/.well-known/agent-card.json"){this.sendJson(t,200,this.getAgentCard());return}if(i==="POST"&&o==="/"){let a=await Xt(e);await this.handleJsonRpc(a,t);return}this.sendJson(t,404,{error:"Not found",hint:"Use GET /.well-known/agent-card.json for discovery or POST / for JSON-RPC"})}catch(a){this.log("Error:",a.message),this.sendJson(t,500,{error:a.message})}}async handleJsonRpc(e,t){if(e.jsonrpc!=="2.0"||!e.method||!e.id){this.sendJsonRpc(t,{jsonrpc:"2.0",id:e.id||0,error:y.PARSE_ERROR});return}let s=e,i=s.params||{};switch(s.method){case"tasks/send":await this.handleTaskSend(s.id,i,t);break;case"tasks/sendSubscribe":await this.handleTaskSendSubscribe(s.id,i,t);break;case"tasks/get":this.handleTaskGet(s.id,i,t);break;case"tasks/cancel":this.handleTaskCancel(s.id,i,t);break;default:this.sendJsonRpc(t,{jsonrpc:"2.0",id:s.id,error:y.METHOD_NOT_FOUND})}}async handleTaskSend(e,t,s){let i=String(t.id||`task-${Date.now().toString(36)}`),o=t.message;if(!o?.parts?.length){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:{...y.INVALID_PARAMS,data:"message with parts is required"}});return}let r=o.parts.filter(c=>c.type==="text").map(c=>c.text).join(`
54
+ `),s=[];for(let i of t)if(i.startsWith("diff --git")){let o=i.match(/b\/(.+)$/);o&&s.push(o[1])}return s.length===0?"chore: update files":s.length===1?`chore: update ${s[0]}`:`chore: update ${s.length} files`}};import{createInterface as Wt}from"readline";import v from"chalk";import qt from"ora";import{existsSync as me,mkdirSync as jt,readFileSync as oe,readdirSync as fe,writeFileSync as _t}from"fs";import O from"path";import Ut from"os";var S=O.join(Ut.homedir(),".agentx","sessions");function ne(){me(S)||jt(S,{recursive:!0})}function T(n){return{id:Ht(),createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),cwd:n,messages:[],tokensUsed:0,filesGenerated:[]}}function R(n){ne();let e=O.join(S,`${n.id}.json`);n.updatedAt=new Date().toISOString(),_t(e,JSON.stringify(n,null,2),"utf8")}function C(n){let e=O.join(S,`${n}.json`);if(!me(e))return null;try{return JSON.parse(oe(e,"utf8"))}catch{return null}}function K(){ne();let n=fe(S).filter(t=>t.endsWith(".json")).map(t=>({name:t,path:O.join(S,t)}));if(!n.length)return null;let e=null;for(let t of n)try{let s=JSON.parse(oe(t.path,"utf8"));(!e||s.updatedAt>e.session.updatedAt)&&(e={name:t.name,session:s})}catch{}return e?.session??null}function B(){ne();let n=fe(S).filter(t=>t.endsWith(".json")),e=[];for(let t of n)try{let s=JSON.parse(oe(O.join(S,t),"utf8"));e.push(s)}catch{}return e.sort((t,s)=>s.updatedAt.localeCompare(t.updatedAt)),e}function Ht(){return Math.random().toString(36).slice(2,10)+Date.now().toString(36).slice(-4)}import p from"chalk";import{writeFileSync as Jt}from"fs";import Kt from"path";import d from"chalk";function ue(n,e){console.log(),console.log(d.bold.cyan(" agentx")+d.dim(` v${n}`)),console.log(d.dim(` Session: ${e}`)),console.log(d.dim(" Type /help for commands, /quit to exit")),console.log()}function he(n){if(n.written.length){console.log(),console.log(d.green(` Created ${n.written.length} file(s):`));for(let e of n.written)console.log(` ${d.green("+")} ${e}`)}if(n.skipped.length){console.log(),console.log(d.yellow(` Skipped ${n.skipped.length} file(s):`));for(let e of n.skipped)console.log(` ${d.yellow("~")} ${e}`)}if(n.errors.length){console.log(),console.log(d.red(` Failed ${n.errors.length} file(s):`));for(let e of n.errors)console.log(` ${d.red("x")} ${e}`)}}function G(n){let e=n/1e6*9;console.log(),console.log(d.dim(` Tokens: ${n.toLocaleString()} | Est. cost: $${e.toFixed(4)}`))}function ye(n){process.stdout.write(n)}function ke(){console.log(),console.log(d.bold(" Commands:")),console.log(),console.log(` ${d.cyan("/help")} Show this help`),console.log(` ${d.cyan("/clear")} Clear conversation history`),console.log(` ${d.cyan("/save")} Save current session`),console.log(` ${d.cyan("/load")} Load a saved session`),console.log(` ${d.cyan("/undo")} Undo last generation`),console.log(` ${d.cyan("/cost")} Show token usage and cost breakdown`),console.log(` ${d.cyan("/export")} Export session as markdown`),console.log(` ${d.cyan("/files")} List generated files`),console.log(` ${d.cyan("/context")} Show session context info`),console.log(` ${d.cyan("/memory")} Show memory stats and preferences`),console.log(` ${d.cyan("/mode")} Switch permission mode`),console.log(` ${d.cyan("/commit")} Commit generated files with AI message`),console.log(` ${d.cyan("/diff")} Show git diff`),console.log(` ${d.cyan("/status")} Show git status`),console.log(` ${d.cyan("/quit")} Exit the REPL`),console.log()}function we(n){if(console.log(),console.log(d.dim(` Branch: ${n.branch}`)),n.isClean){console.log(d.green(" Working tree clean"));return}n.staged.length&&console.log(d.green(` Staged: ${n.staged.length}`)),n.modified.length&&console.log(d.yellow(` Modified: ${n.modified.length}`)),n.untracked.length&&console.log(d.dim(` Untracked: ${n.untracked.length}`)),console.log()}function Se(n){if(console.log(),console.log(d.bold(" Cost Breakdown")),console.log(),console.log(d.dim(` Total: ${n.totalTokens.toLocaleString()} tokens ($${n.totalCost.toFixed(4)})`)),console.log(d.dim(` Input: ${n.totalInputTokens.toLocaleString()} | Output: ${n.totalOutputTokens.toLocaleString()}`)),Object.keys(n.models).length){console.log(),console.log(d.dim(" Per model:"));for(let[e,t]of Object.entries(n.models))console.log(` ${d.cyan(e)}: ${(t.inputTokens+t.outputTokens).toLocaleString()} tokens, $${t.cost.toFixed(4)} (${t.steps} step${t.steps!==1?"s":""})`)}if(n.steps.length>1){console.log(),console.log(d.dim(" Per step:"));for(let e of n.steps)console.log(` Step ${e.step}: ${(e.inputTokens+e.outputTokens).toLocaleString()} tokens ($${e.cost.toFixed(4)})`)}console.log()}function ve(n){console.log(),console.log(d.bold(" Plan Preview")),console.log(d.dim(" No files will be written in plan mode.")),console.log();for(let e of n){let t=e.action==="create"?d.green("+"):d.yellow("~");console.log(` ${t} ${e.path} (${e.action})`)}console.log()}import Bt from"prompts";var xe={};function f(n,e){xe[n]=e}function W(n){return xe[n]}function q(n){return n.startsWith("/")}function V(n){let e=n.trim(),t=e.indexOf(" ");return t===-1?{name:e.slice(1),args:""}:{name:e.slice(1,t),args:e.slice(t+1).trim()}}f("help",async()=>(ke(),!0));f("quit",async()=>!1);f("exit",async()=>!1);f("q",async()=>!1);f("clear",async(n,e)=>(e.session.messages=[],console.log(p.dim(" Conversation cleared")),!0));f("save",async(n,e)=>(R(e.session),console.log(p.dim(` Session saved: ${e.session.id}`)),!0));f("load",async(n,e)=>{let t=null;if(n){if(t=C(n),!t)return m.warn(`Session not found: ${n}`),!0}else{let s=B();if(!s.length)return m.info("No saved sessions"),!0;let{sessionId:i}=await Bt({type:"select",name:"sessionId",message:"Select a session",choices:s.slice(0,10).map(o=>({title:`${o.id} \u2014 ${new Date(o.updatedAt).toLocaleDateString()} (${o.messages.length} messages)`,value:o.id}))});if(!i)return!0;t=C(i)}return t&&(e.onSessionChange(t),console.log(p.dim(` Loaded session: ${t.id} (${t.messages.length} messages)`))),!0});f("undo",async(n,e)=>{let t=e.session.messages;return t.length<2?(m.info("Nothing to undo"),!0):(t[t.length-1]?.role==="assistant"&&t.pop(),t[t.length-1]?.role==="user"&&t.pop(),console.log(p.dim(" Undid last exchange")),!0)});f("cost",async(n,e)=>{let t=F.getSummary();return t.steps.length>0?Se(t):G(e.session.tokensUsed),!0});f("export",async(n,e)=>{let t=F.getSummary(),s=Q(e.session,t.steps.length?t:void 0),i=n||`session-${e.session.id}.md`,o=Kt.resolve(e.cwd,i);return Jt(o,s,"utf8"),m.success(` Session exported to ${o}`),!0});f("files",async(n,e)=>{let t=e.session.filesGenerated;if(!t.length)return m.info("No files generated in this session"),!0;console.log(),console.log(p.dim(` Files generated (${t.length}):`));for(let s of t)console.log(` ${p.green("+")} ${s}`);return console.log(),!0});f("context",async(n,e)=>(console.log(),console.log(p.dim(` Session: ${e.session.id}`)),console.log(p.dim(` CWD: ${e.session.cwd}`)),console.log(p.dim(` Messages: ${e.session.messages.length}`)),console.log(p.dim(` Tokens: ${e.session.tokensUsed.toLocaleString()}`)),console.log(p.dim(` Files: ${e.session.filesGenerated.length}`)),console.log(p.dim(` Created: ${new Date(e.session.createdAt).toLocaleString()}`)),console.log(),!0));f("memory",async(n,e)=>{try{let t=new Z(e.cwd);await t.load();let s=t.getStats(),i=t.getPreferences(),o=t.getPatterns(),a=t.getRecentGenerations(5);if(console.log(),console.log(p.bold(" Memory")),console.log(),console.log(p.dim(" Project:")),console.log(p.dim(` Generations: ${s.project.totalGenerations}`)),console.log(p.dim(` Success rate: ${(s.project.successRate*100).toFixed(0)}%`)),console.log(p.dim(` Heals: ${s.project.totalHeals}`)),console.log(),console.log(p.dim(" Global:")),console.log(p.dim(` Generations: ${s.user.totalGenerations}`)),console.log(p.dim(` Success rate: ${(s.user.successRate*100).toFixed(0)}%`)),i.length){console.log(),console.log(p.dim(" Preferences:"));for(let r of i.slice(0,10))console.log(p.dim(` ${r.key}: ${r.value} (${(r.confidence*100).toFixed(0)}%)`))}if(o.length){console.log(),console.log(p.dim(" Patterns:"));for(let r of o.slice(0,5))console.log(p.dim(` ${r.description} (${r.frequency}x)`))}if(a.length){console.log(),console.log(p.dim(" Recent:"));for(let r of a){let l=r.success?p.green("ok"):p.red("fail");console.log(p.dim(` [${l}] ${r.task.slice(0,60)}`))}}console.log()}catch(t){m.error(` ${t.message}`)}return!0});f("mode",async(n,e)=>{if(n&&j.includes(n))P.setMode(n),m.success(` Permission mode: ${n}`);else if(n)m.warn(` Unknown mode: ${n}. Valid modes: ${j.join(", ")}`);else{let t=P.getMode();console.log(),console.log(p.dim(` Current mode: ${p.bold(t)}`)),console.log(),console.log(p.dim(" Available modes:")),console.log(p.dim(" default \u2014 confirm each file write")),console.log(p.dim(" acceptEdits \u2014 auto-allow writes, confirm destructive ops")),console.log(p.dim(" plan \u2014 show plan without writing")),console.log(p.dim(" yolo \u2014 auto-allow everything")),console.log(),console.log(p.dim(" Usage: /mode <mode>")),console.log()}return!0});f("commit",async(n,e)=>{try{let t=new w(e.cwd);if(!await t.isRepo())return m.warn("Not a git repository"),!0;let s=e.session.filesGenerated.filter(r=>r);if(s.length&&(await t.add(s),console.log(p.dim(` Staged ${s.length} generated file(s)`))),(await t.status()).staged.length===0)return m.warn("Nothing staged to commit"),!0;let o;try{let r=A();o=await t.generateCommitMessage(r)}catch{o=await t.generateCommitMessage()}console.log(p.dim(` Message: ${o}`));let a=await t.commit(o);m.success(` [${a.hash}] ${a.message}`)}catch(t){m.error(` ${t.message}`)}return!0});f("diff",async(n,e)=>{try{let s=await new w(e.cwd).diff();s.trim()?console.log(s):m.info("No changes")}catch(t){m.error(` ${t.message}`)}return!0});f("status",async(n,e)=>{try{let t=new w(e.cwd);if(!await t.isRepo())return m.warn("Not a git repository"),!0;let s=await t.status();we(s)}catch(t){m.error(` ${t.message}`)}return!0});var Y=class{rl=null;session;options;running=!1;constructor(e){if(this.options=e,e.sessionId){let t=C(e.sessionId);t?this.session=t:(m.warn(`Session ${e.sessionId} not found, starting new session`),this.session=T(e.cwd))}else if(e.resume){let t=K();t?(this.session=t,m.info(`Resumed session: ${t.id}`)):(m.info("No previous session found, starting new session"),this.session=T(e.cwd))}else this.session=T(e.cwd)}async start(){this.running=!0,ue(this.options.version,this.session.id),this.session.messages.length>0&&(console.log(v.dim(` Resumed with ${this.session.messages.length} messages, ${this.session.tokensUsed.toLocaleString()} tokens`)),console.log()),this.rl=Wt({input:process.stdin,output:process.stdout,prompt:v.cyan("agentx > "),terminal:!0}),this.rl.prompt(),this.rl.on("line",async e=>{let t=e.trim();if(!t){this.rl?.prompt();return}try{if(q(t)){if(!await this.handleCommand(t)){this.stop();return}}else await this.handleGeneration(t)}catch(s){m.error(` Error: ${s.message}`)}this.running&&this.rl?.prompt()}),this.rl.on("close",()=>{this.stop()}),this.rl.on("SIGINT",()=>{console.log(),this.stop()})}stop(){this.running=!1,R(this.session),console.log(),console.log(v.dim(` Session saved: ${this.session.id}`)),G(this.session.tokensUsed),console.log(),this.rl?.close(),process.exit(0)}async handleCommand(e){let{name:t,args:s}=V(e),i=W(t);if(!i)return m.warn(` Unknown command: /${t}. Type /help for available commands.`),!0;let o={session:this.session,cwd:this.options.cwd,onSessionChange:a=>{this.session=a}};return i(s,o)}async handleGeneration(e){let t=qt({text:"Thinking...",color:"cyan"}).start();try{let s=this.session.messages.filter(r=>r.role!=="system").map(r=>({role:r.role,content:r.content})),i={task:e,cwd:this.options.cwd,provider:this.options.provider||"claude-code",model:this.options.model,apiKey:this.options.apiKey,overwrite:!0,dryRun:!1,interactive:!1,context7:!0,sessionMessages:s},o,a=!1;for await(let r of I(i)){if(r.type==="context_ready"){t.stop(),console.log(),a=!0;continue}if(r.type==="text_delta"){ye(r.text);continue}if(r.type==="done"){console.log();continue}if(r.type==="error")throw new Error(r.error);if(r.type==="step_complete"){r.step>1&&console.log(v.dim(` Step ${r.step}: ${r.filesCount} file(s)`));continue}r.type==="generate_result"&&(o=r.result)}if(a||t.stop(),!o)return;(o.files.written.length||o.files.skipped.length||o.files.errors.length)&&(P.getMode()==="plan"?ve(o.files.written.map(r=>({path:r,action:"create"}))):he(o.files)),o.tokensUsed&&G(o.tokensUsed),this.session.messages.push({role:"user",content:e}),this.session.messages.push({role:"assistant",content:o.content||""}),this.session.tokensUsed+=o.tokensUsed||0,this.session.filesGenerated.push(...o.files.written),o.followUp&&(console.log(),console.log(v.yellow(` ${o.followUp}`))),o.healResult&&(console.log(),o.healResult.healed?console.log(v.green(` Heal: passed verification${o.healResult.attempts>0?` (fixed in ${o.healResult.attempts} attempt(s))`:""}`)):o.healResult.error&&(console.log(v.red(` Heal: verification failed after ${o.healResult.attempts} attempt(s)`)),console.log(v.dim(` ${o.healResult.error.split(`
55
+ `)[0]}`))))}catch(s){throw t.stop(),s}}};import{createServer as Vt}from"http";var y={TASK_NOT_FOUND:{code:-32001,message:"Task not found"},TASK_NOT_CANCELABLE:{code:-32002,message:"Task cannot be canceled"},INVALID_PARAMS:{code:-32602,message:"Invalid params"},INTERNAL_ERROR:{code:-32603,message:"Internal error"},METHOD_NOT_FOUND:{code:-32601,message:"Method not found"},PARSE_ERROR:{code:-32700,message:"Parse error"}};var Yt={port:3171,host:"0.0.0.0",provider:"claude-code",cwd:process.cwd(),cors:!0},z=class{config;tasks=new Map;activeCancellations=new Set;log;constructor(e){this.config={...Yt,...e},this.log=console.error.bind(console,"[a2a]")}async start(){Vt(async(t,s)=>{if(this.config.cors&&(s.setHeader("Access-Control-Allow-Origin","*"),s.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),s.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),t.method==="OPTIONS")){s.writeHead(204),s.end();return}await this.handleRequest(t,s)}).listen(this.config.port,this.config.host,()=>{this.log(`
56
+ agentx A2A server v0.1.0`),this.log(` Listening on http://${this.config.host}:${this.config.port}`),this.log(` Provider: ${this.config.provider}`),this.log(` Working dir: ${this.config.cwd}`),this.log(""),this.log(" Discovery:"),this.log(" GET /.well-known/agent-card.json"),this.log(""),this.log(" JSON-RPC 2.0 methods:"),this.log(" tasks/send \u2014 synchronous task execution"),this.log(" tasks/sendSubscribe \u2014 streaming task execution (SSE)"),this.log(" tasks/get \u2014 retrieve task state"),this.log(" tasks/cancel \u2014 cancel running task"),this.log("")})}getAgentCard(){return{name:"agentx",description:"AI-powered agentic code generation agent. Generates components, pages, APIs, documents, skills, and more for any tech stack.",url:`http://${this.config.host}:${this.config.port}`,version:"0.1.0",capabilities:{streaming:!0,pushNotifications:!1,stateTransitionHistory:!0},skills:[{id:"generate",name:"Code Generation",description:"Generate code files from natural language descriptions. Supports components, pages, APIs, tests, schemas, and more.",tags:["code-generation","ai","multi-framework"],examples:["Create a React login form with email and password validation","Generate a REST API for user management with CRUD operations","Build a dashboard page with charts and data tables"]},{id:"evolve",name:"Code Transformation",description:"Transform existing code files based on natural language instructions. Applies targeted edits with diff preview.",tags:["code-transformation","refactoring","ai"],examples:["Add dark mode support to this component","Refactor this API to use async/await instead of callbacks"]},{id:"inspect",name:"Project Analysis",description:"Analyze a project's tech stack, schemas, dependencies, and structure.",tags:["analysis","project-inspection"],examples:["What tech stack does this project use?","List all API schemas in the project"]}],defaultInputModes:["text"],defaultOutputModes:["text","file"]}}async handleRequest(e,t){let s=new URL(e.url||"/",`http://${e.headers.host||"localhost"}`),i=e.method||"GET",o=s.pathname;this.log(`${i} ${o}`);try{if(i==="GET"&&o==="/.well-known/agent-card.json"){this.sendJson(t,200,this.getAgentCard());return}if(i==="POST"&&o==="/"){let a=await zt(e);await this.handleJsonRpc(a,t);return}this.sendJson(t,404,{error:"Not found",hint:"Use GET /.well-known/agent-card.json for discovery or POST / for JSON-RPC"})}catch(a){this.log("Error:",a.message),this.sendJson(t,500,{error:a.message})}}async handleJsonRpc(e,t){if(e.jsonrpc!=="2.0"||!e.method||!e.id){this.sendJsonRpc(t,{jsonrpc:"2.0",id:e.id||0,error:y.PARSE_ERROR});return}let s=e,i=s.params||{};switch(s.method){case"tasks/send":await this.handleTaskSend(s.id,i,t);break;case"tasks/sendSubscribe":await this.handleTaskSendSubscribe(s.id,i,t);break;case"tasks/get":this.handleTaskGet(s.id,i,t);break;case"tasks/cancel":this.handleTaskCancel(s.id,i,t);break;default:this.sendJsonRpc(t,{jsonrpc:"2.0",id:s.id,error:y.METHOD_NOT_FOUND})}}async handleTaskSend(e,t,s){let i=String(t.id||`task-${Date.now().toString(36)}`),o=t.message;if(!o?.parts?.length){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:{...y.INVALID_PARAMS,data:"message with parts is required"}});return}let r=o.parts.filter(c=>c.type==="text").map(c=>c.text).join(`
57
57
  `);if(!r){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:{...y.INVALID_PARAMS,data:"No text content in message parts"}});return}let l={id:i,state:"submitted",messages:[{role:"user",parts:o.parts}],artifacts:[],metadata:t.metadata,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};this.tasks.set(i,l),l.state="working",l.updatedAt=new Date().toISOString();try{let c=await E({task:r,cwd:this.config.cwd,provider:this.config.provider,model:this.config.model,apiKey:this.config.apiKey,overwrite:!0,interactive:!1,context7:!0}),g=c.files.written.map((k,D)=>({name:k,description:"Generated file",parts:[{type:"text",text:k}],index:D})),h={role:"agent",parts:[{type:"text",text:c.content||"Generation complete."}]};c.followUp?(l.state="input-required",h.parts.push({type:"text",text:`
58
58
 
59
59
  Question: ${c.followUp}`})):l.state="completed",l.messages.push(h),l.artifacts=g,l.updatedAt=new Date().toISOString()}catch(c){l.state="failed",l.messages.push({role:"agent",parts:[{type:"text",text:`Error: ${c.message}`}]}),l.updatedAt=new Date().toISOString()}this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,result:l})}async handleTaskSendSubscribe(e,t,s){let i=String(t.id||`task-${Date.now().toString(36)}`),o=t.message;if(!o?.parts?.length){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:{...y.INVALID_PARAMS,data:"message with parts is required"}});return}let r=o.parts.filter(g=>g.type==="text").map(g=>g.text).join(`
60
60
  `);if(!r){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:{...y.INVALID_PARAMS,data:"No text content in message parts"}});return}s.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});let l={id:i,state:"submitted",messages:[{role:"user",parts:o.parts}],artifacts:[],metadata:t.metadata,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};this.tasks.set(i,l);let c=g=>{s.write(`data: ${JSON.stringify(g)}
61
61
 
62
- `)};c({id:i,state:"submitted",final:!1}),l.state="working",l.updatedAt=new Date().toISOString(),c({id:i,state:"working",final:!1});try{let g="",h=[];for await(let k of I({task:r,cwd:this.config.cwd,provider:this.config.provider,model:this.config.model,apiKey:this.config.apiKey,overwrite:!0,interactive:!1,context7:!0})){if(this.activeCancellations.has(i)){this.activeCancellations.delete(i),l.state="canceled",l.updatedAt=new Date().toISOString(),c({id:i,state:"canceled",final:!0}),s.end();return}if(k.type==="text_delta"&&(g+=k.text,c({id:i,state:"working",message:{role:"agent",parts:[{type:"text",text:k.text}]},final:!1})),k.type==="generate_result"){let D=k.result,ie=D.files.written.map((L,Pe)=>({name:L,parts:[{type:"text",text:L}],index:Pe}));h.push(...ie);for(let L of ie)c({id:i,state:"working",artifact:L,final:!1});D.followUp?l.state="input-required":l.state="completed"}}l.messages.push({role:"agent",parts:[{type:"text",text:g||"Generation complete."}]}),l.artifacts=h,l.updatedAt=new Date().toISOString(),c({id:i,state:l.state,final:!0})}catch(g){l.state="failed",l.messages.push({role:"agent",parts:[{type:"text",text:`Error: ${g.message}`}]}),l.updatedAt=new Date().toISOString(),c({id:i,state:"failed",message:{role:"agent",parts:[{type:"text",text:`Error: ${g.message}`}]},final:!0})}s.end()}handleTaskGet(e,t,s){let i=String(t.id||""),o=this.tasks.get(i);if(!o){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:y.TASK_NOT_FOUND});return}this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,result:o})}handleTaskCancel(e,t,s){let i=String(t.id||""),o=this.tasks.get(i);if(!o){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:y.TASK_NOT_FOUND});return}if(o.state!=="working"&&o.state!=="submitted"){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:y.TASK_NOT_CANCELABLE});return}this.activeCancellations.add(i),o.state="canceled",o.updatedAt=new Date().toISOString(),this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,result:o})}sendJson(e,t,s){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(s,null,2))}sendJsonRpc(e,t){e.headersSent||e.writeHead(200,{"Content-Type":"application/json"}),e.end(JSON.stringify(t))}};async function Xt(n){return new Promise((e,t)=>{let s="";n.on("data",i=>s+=i),n.on("end",()=>{try{e(s?JSON.parse(s):{})}catch{e({})}}),n.on("error",t)})}vt();var Ce={"claude-code":{streaming:!0,tools:!0,vision:!0,thinking:!0,maxContext:1e6},claude:{streaming:!0,tools:!0,vision:!0,thinking:!0,maxContext:1e6},openai:{streaming:!0,tools:!0,vision:!0,thinking:!1,maxContext:128e3},ollama:{streaming:!0,tools:!1,vision:!1,thinking:!1,maxContext:32e3}};function Qt(n,e){let t=Ce[n];if(!t)return[`Unknown provider "${n}" \u2014 capabilities unknown`];if(!e?.length)return[];let s=[],i=[];for(let o of e)o in t&&!t[o]&&i.push(o);return i.length&&s.push(`Provider "${n}" lacks: ${i.join(", ")}. Some features will be degraded.`),s}export{re as A2AClient,ae as A2AMesh,z as A2AServer,Le as ALL_TOOL_NAMES,ut as AgentRegistry,$t as AgentXDaemon,J as AgentXRuntime,Ve as BLOCKING_EVENTS,Fe as ClaudeCodeProvider,Ne as ClaudeProvider,at as ContextBuilder,bt as CronScheduler,b as EnhanceEngine,w as GitManager,mt as GraphStore,qe as HOOK_EVENTS,U as HealEngine,Ze as HookRegistry,_ as Memory,Z as MemoryHierarchy,xt as MessageRouter,Be as OUTPUT_CONFIGS,$e as OUTPUT_TYPES,j as PERMISSION_MODES,Ce as PROVIDER_CAPABILITIES,nt as PermissionManager,$ as Pipeline,Y as ReplEngine,gt as STARTER_SCHEMA,Ct as TelegramAdapter,ht as ToolExecutor,Ye as UsageTracker,Pt as WhatsAppAdapter,ft as WikiStore,be as agentConfigSchema,Qt as checkCapabilities,H as createAgentContext,A as createProvider,T as createSession,kt as daemonConfigSchema,Qe as debug,je as detectSchemas,X as detectTechStack,Ie as ensureCredentials,lt as executeClaudeCode,dt as executeOrchestrator,ct as executeSdk,pt as executeTask,Q as exportSession,_e as formatSchemas,M as formatTechStack,De as formatToolsForSystemPrompt,Ue as gatherContext7Docs,E as generate,Gt as generateSkill,It as generateSkillMd,I as generateStream,Oe as getAnthropicTools,W as getCommand,Ge as getLegacyTools,Rt as getPackageInfo,tt as globalHooks,P as globalPermissions,F as globalTracker,Tt as handleError,Mt as installSkillPackage,q as isCommand,Xe as isDebug,Ot as listInstalledSkills,B as listSessions,Re as loadAuthConfig,wt as loadDaemonConfig,et as loadHooks,K as loadLatestSession,He as loadLocalSkills,rt as loadProjectInstructions,C as loadSession,m as logger,Ke as matchSkillsToTask,Te as outputTypeDescriptions,V as parseCommand,N as parseSkillContent,Je as parseSkillFile,ot as permissionConfigSchema,st as permissionModeSchema,f as registerCommand,it as resolveAtImports,We as resolveOutputType,Me as resolveToken,Ee as runModelSetup,Ae as saveAuthConfig,R as saveSession,ze as setDebug,yt as startMcpServer,St as validateWorkspaces};
62
+ `)};c({id:i,state:"submitted",final:!1}),l.state="working",l.updatedAt=new Date().toISOString(),c({id:i,state:"working",final:!1});try{let g="",h=[];for await(let k of I({task:r,cwd:this.config.cwd,provider:this.config.provider,model:this.config.model,apiKey:this.config.apiKey,overwrite:!0,interactive:!1,context7:!0})){if(this.activeCancellations.has(i)){this.activeCancellations.delete(i),l.state="canceled",l.updatedAt=new Date().toISOString(),c({id:i,state:"canceled",final:!0}),s.end();return}if(k.type==="text_delta"&&(g+=k.text,c({id:i,state:"working",message:{role:"agent",parts:[{type:"text",text:k.text}]},final:!1})),k.type==="generate_result"){let D=k.result,ie=D.files.written.map((L,Pe)=>({name:L,parts:[{type:"text",text:L}],index:Pe}));h.push(...ie);for(let L of ie)c({id:i,state:"working",artifact:L,final:!1});D.followUp?l.state="input-required":l.state="completed"}}l.messages.push({role:"agent",parts:[{type:"text",text:g||"Generation complete."}]}),l.artifacts=h,l.updatedAt=new Date().toISOString(),c({id:i,state:l.state,final:!0})}catch(g){l.state="failed",l.messages.push({role:"agent",parts:[{type:"text",text:`Error: ${g.message}`}]}),l.updatedAt=new Date().toISOString(),c({id:i,state:"failed",message:{role:"agent",parts:[{type:"text",text:`Error: ${g.message}`}]},final:!0})}s.end()}handleTaskGet(e,t,s){let i=String(t.id||""),o=this.tasks.get(i);if(!o){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:y.TASK_NOT_FOUND});return}this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,result:o})}handleTaskCancel(e,t,s){let i=String(t.id||""),o=this.tasks.get(i);if(!o){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:y.TASK_NOT_FOUND});return}if(o.state!=="working"&&o.state!=="submitted"){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:y.TASK_NOT_CANCELABLE});return}this.activeCancellations.add(i),o.state="canceled",o.updatedAt=new Date().toISOString(),this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,result:o})}sendJson(e,t,s){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(s,null,2))}sendJsonRpc(e,t){e.headersSent||e.writeHead(200,{"Content-Type":"application/json"}),e.end(JSON.stringify(t))}};async function zt(n){return new Promise((e,t)=>{let s="";n.on("data",i=>s+=i),n.on("end",()=>{try{e(s?JSON.parse(s):{})}catch{e({})}}),n.on("error",t)})}var Ce={"claude-code":{streaming:!0,tools:!0,vision:!0,thinking:!0,maxContext:1e6},claude:{streaming:!0,tools:!0,vision:!0,thinking:!0,maxContext:1e6},openai:{streaming:!0,tools:!0,vision:!0,thinking:!1,maxContext:128e3},ollama:{streaming:!0,tools:!1,vision:!1,thinking:!1,maxContext:32e3}};function Xt(n,e){let t=Ce[n];if(!t)return[`Unknown provider "${n}" \u2014 capabilities unknown`];if(!e?.length)return[];let s=[],i=[];for(let o of e)o in t&&!t[o]&&i.push(o);return i.length&&s.push(`Provider "${n}" lacks: ${i.join(", ")}. Some features will be degraded.`),s}export{re as A2AClient,ae as A2AMesh,z as A2AServer,Le as ALL_TOOL_NAMES,ut as AgentRegistry,bt as AgentXDaemon,J as AgentXRuntime,Ve as BLOCKING_EVENTS,Fe as ClaudeCodeProvider,Ne as ClaudeProvider,at as ContextBuilder,Pt as CronScheduler,b as EnhanceEngine,w as GitManager,mt as GraphStore,qe as HOOK_EVENTS,U as HealEngine,Ze as HookRegistry,_ as Memory,Z as MemoryHierarchy,vt as MessageRouter,Be as OUTPUT_CONFIGS,$e as OUTPUT_TYPES,j as PERMISSION_MODES,Ce as PROVIDER_CAPABILITIES,nt as PermissionManager,$ as Pipeline,Y as ReplEngine,gt as STARTER_SCHEMA,xt as TelegramAdapter,ht as ToolExecutor,Ye as UsageTracker,Ct as WhatsAppAdapter,ft as WikiStore,be as agentConfigSchema,Xt as checkCapabilities,H as createAgentContext,A as createProvider,T as createSession,kt as daemonConfigSchema,Qe as debug,je as detectSchemas,X as detectTechStack,Ie as ensureCredentials,lt as executeClaudeCode,dt as executeOrchestrator,ct as executeSdk,pt as executeTask,Q as exportSession,_e as formatSchemas,M as formatTechStack,De as formatToolsForSystemPrompt,Ue as gatherContext7Docs,E as generate,Ot as generateSkill,Et as generateSkillMd,I as generateStream,Oe as getAnthropicTools,W as getCommand,Ge as getLegacyTools,Tt as getPackageInfo,tt as globalHooks,P as globalPermissions,F as globalTracker,$t as handleError,At as installSkillPackage,q as isCommand,Xe as isDebug,It as listInstalledSkills,B as listSessions,Re as loadAuthConfig,wt as loadDaemonConfig,et as loadHooks,K as loadLatestSession,He as loadLocalSkills,rt as loadProjectInstructions,C as loadSession,m as logger,Ke as matchSkillsToTask,Te as outputTypeDescriptions,V as parseCommand,N as parseSkillContent,Je as parseSkillFile,ot as permissionConfigSchema,st as permissionModeSchema,f as registerCommand,it as resolveAtImports,We as resolveOutputType,Me as resolveToken,Ee as runModelSetup,Ae as saveAuthConfig,R as saveSession,ze as setDebug,yt as startMcpServer,St as validateWorkspaces};
63
63
  //# sourceMappingURL=index.js.map