agentix-cli 0.16.0 → 0.17.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 (131) hide show
  1. package/dist/agent-4AOMVXRJ.js +2 -0
  2. package/dist/board-dashboard-CXIVJKDP.js +7282 -0
  3. package/dist/board-dashboard-CXIVJKDP.js.map +1 -0
  4. package/dist/chunk-34NG7UDX.js +11 -0
  5. package/dist/chunk-34NG7UDX.js.map +1 -0
  6. package/dist/chunk-4HP6UC2X.js +13 -0
  7. package/dist/chunk-4HP6UC2X.js.map +1 -0
  8. package/dist/chunk-5WNGHDFC.js +164 -0
  9. package/dist/chunk-5WNGHDFC.js.map +1 -0
  10. package/dist/{chunk-7MBTMCKY.js → chunk-63UYRJIC.js} +2 -2
  11. package/dist/chunk-6PPIFDOQ.js +1742 -0
  12. package/dist/chunk-6PPIFDOQ.js.map +1 -0
  13. package/dist/chunk-ABCHHNG6.js +625 -0
  14. package/dist/chunk-ABCHHNG6.js.map +1 -0
  15. package/dist/chunk-AFRHKA7B.js +2 -0
  16. package/dist/chunk-AFRHKA7B.js.map +1 -0
  17. package/dist/chunk-CDNWCYF7.js +2 -0
  18. package/dist/chunk-CDNWCYF7.js.map +1 -0
  19. package/dist/{chunk-6MKAXEE5.js → chunk-EKTPCSN4.js} +2 -2
  20. package/dist/{chunk-6MKAXEE5.js.map → chunk-EKTPCSN4.js.map} +1 -1
  21. package/dist/chunk-EW27SCCC.js +2 -0
  22. package/dist/chunk-EW27SCCC.js.map +1 -0
  23. package/dist/chunk-HCFSHGK4.js +46 -0
  24. package/dist/chunk-HCFSHGK4.js.map +1 -0
  25. package/dist/chunk-HHJGKD5B.js +71 -0
  26. package/dist/chunk-HHJGKD5B.js.map +1 -0
  27. package/dist/{chunk-YI2T5QYB.js → chunk-MBEQASP3.js} +2 -2
  28. package/dist/chunk-N67JZAXU.js +2 -0
  29. package/dist/chunk-N67JZAXU.js.map +1 -0
  30. package/dist/{chunk-FLOGK2U7.js → chunk-SRHLXZRF.js} +2 -2
  31. package/dist/chunk-TT2Q7YMZ.js +118 -0
  32. package/dist/chunk-TT2Q7YMZ.js.map +1 -0
  33. package/dist/{chunk-HI24KAEY.js → chunk-WJXU5F4Z.js} +3 -4
  34. package/dist/{chunk-HI24KAEY.js.map → chunk-WJXU5F4Z.js.map} +1 -1
  35. package/dist/chunk-XDJSYQST.js +6 -0
  36. package/dist/chunk-XDJSYQST.js.map +1 -0
  37. package/dist/chunk-YPOELN6Z.js +798 -0
  38. package/dist/chunk-YPOELN6Z.js.map +1 -0
  39. package/dist/{chunk-QZP65I2H.js → chunk-ZE2YFX4K.js} +2 -2
  40. package/dist/cli.js +1 -320
  41. package/dist/cli.js.map +1 -1
  42. package/dist/{compaction-JBZZ7I7Y.js → compaction-X46EQEPS.js} +6 -6
  43. package/dist/compaction-X46EQEPS.js.map +1 -0
  44. package/dist/{config-LN6JEHMF.js → config-KCYHMKCT.js} +2 -2
  45. package/dist/config-mutator-QP4GLBOE.js +2 -0
  46. package/dist/context-planner-G2J7FNNU.js +17 -0
  47. package/dist/context-planner-G2J7FNNU.js.map +1 -0
  48. package/dist/editor-chat-R54E65W5.js +137 -0
  49. package/dist/editor-chat-R54E65W5.js.map +1 -0
  50. package/dist/heal-JDXUPRET.js +2 -0
  51. package/dist/inbox-L5ZZ623Y.js +315 -0
  52. package/dist/inbox-L5ZZ623Y.js.map +1 -0
  53. package/dist/index.d.ts +2917 -1781
  54. package/dist/index.js +23 -53
  55. package/dist/index.js.map +1 -1
  56. package/dist/ingest-whatsapp-NS4OWDOU.js +6 -0
  57. package/dist/ingest-whatsapp-NS4OWDOU.js.map +1 -0
  58. package/dist/memory-extract-WH4FZ456.js +2 -0
  59. package/dist/processes-XF5CV4LK.js +256 -0
  60. package/dist/processes-XF5CV4LK.js.map +1 -0
  61. package/dist/program-FFWEILAS.js +2 -0
  62. package/dist/providers-AKQ4HTB4.js +2 -0
  63. package/dist/registry-IFMDJWQ7.js +2 -0
  64. package/dist/scheduler-63D5KFO7.js +2 -0
  65. package/dist/slack-PSQLVTGB.js +3 -0
  66. package/dist/slack-PSQLVTGB.js.map +1 -0
  67. package/dist/store-5MJOO74U.js +2 -0
  68. package/dist/store-5MJOO74U.js.map +1 -0
  69. package/dist/task-store-NM7VKNLE.js +2 -0
  70. package/dist/task-store-NM7VKNLE.js.map +1 -0
  71. package/dist/telegram-W4SLFMNY.js +3 -0
  72. package/dist/telegram-W4SLFMNY.js.map +1 -0
  73. package/dist/timers-PCB4ZIBD.js +2 -0
  74. package/dist/timers-PCB4ZIBD.js.map +1 -0
  75. package/dist/types-C7IFH42Z.js +2 -0
  76. package/dist/types-C7IFH42Z.js.map +1 -0
  77. package/dist/usage-dashboard-AXPXB2KP.js +803 -0
  78. package/dist/usage-dashboard-AXPXB2KP.js.map +1 -0
  79. package/dist/web/workflow-editor.global.js +1427 -0
  80. package/dist/web/workflow-editor.global.js.map +1 -0
  81. package/dist/whatsapp-DCHRBRVV.js +3 -0
  82. package/dist/whatsapp-DCHRBRVV.js.map +1 -0
  83. package/dist/workspace-setup-C4VB3QZV.js +2 -0
  84. package/dist/workspace-setup-C4VB3QZV.js.map +1 -0
  85. package/package.json +9 -2
  86. package/dist/agent-BCDPSPKU.js +0 -2
  87. package/dist/board-dashboard-LA7WW56M.js +0 -5668
  88. package/dist/board-dashboard-LA7WW56M.js.map +0 -1
  89. package/dist/chunk-6U2XOQHU.js +0 -7
  90. package/dist/chunk-6U2XOQHU.js.map +0 -1
  91. package/dist/chunk-7FJQGD6U.js +0 -6
  92. package/dist/chunk-7FJQGD6U.js.map +0 -1
  93. package/dist/chunk-ABDP7TDL.js +0 -71
  94. package/dist/chunk-ABDP7TDL.js.map +0 -1
  95. package/dist/chunk-CXY2RYNI.js +0 -11
  96. package/dist/chunk-CXY2RYNI.js.map +0 -1
  97. package/dist/chunk-HVC6FJNP.js +0 -108
  98. package/dist/chunk-HVC6FJNP.js.map +0 -1
  99. package/dist/chunk-K7BE4E35.js +0 -138
  100. package/dist/chunk-K7BE4E35.js.map +0 -1
  101. package/dist/chunk-KXJSLLSQ.js +0 -199
  102. package/dist/chunk-KXJSLLSQ.js.map +0 -1
  103. package/dist/chunk-KXZMYLHQ.js +0 -46
  104. package/dist/chunk-KXZMYLHQ.js.map +0 -1
  105. package/dist/chunk-M7HKBG3V.js +0 -2
  106. package/dist/chunk-M7HKBG3V.js.map +0 -1
  107. package/dist/chunk-RB7265LO.js +0 -12
  108. package/dist/chunk-RB7265LO.js.map +0 -1
  109. package/dist/compaction-JBZZ7I7Y.js.map +0 -1
  110. package/dist/config-mutator-24TH7PHM.js +0 -2
  111. package/dist/heal-WKY5I4KB.js +0 -2
  112. package/dist/memory-extract-AD7KMRPC.js +0 -2
  113. package/dist/providers-VUIWO3ZK.js +0 -2
  114. package/dist/registry-ASC2QS5K.js +0 -2
  115. package/dist/scheduler-A3TQOCKT.js +0 -2
  116. package/dist/usage-dashboard-QX3CF6KK.js +0 -404
  117. package/dist/usage-dashboard-QX3CF6KK.js.map +0 -1
  118. package/dist/workspace-setup-ZWTT42XT.js +0 -2
  119. /package/dist/{agent-BCDPSPKU.js.map → agent-4AOMVXRJ.js.map} +0 -0
  120. /package/dist/{chunk-7MBTMCKY.js.map → chunk-63UYRJIC.js.map} +0 -0
  121. /package/dist/{chunk-YI2T5QYB.js.map → chunk-MBEQASP3.js.map} +0 -0
  122. /package/dist/{chunk-FLOGK2U7.js.map → chunk-SRHLXZRF.js.map} +0 -0
  123. /package/dist/{chunk-QZP65I2H.js.map → chunk-ZE2YFX4K.js.map} +0 -0
  124. /package/dist/{config-LN6JEHMF.js.map → config-KCYHMKCT.js.map} +0 -0
  125. /package/dist/{config-mutator-24TH7PHM.js.map → config-mutator-QP4GLBOE.js.map} +0 -0
  126. /package/dist/{heal-WKY5I4KB.js.map → heal-JDXUPRET.js.map} +0 -0
  127. /package/dist/{memory-extract-AD7KMRPC.js.map → memory-extract-WH4FZ456.js.map} +0 -0
  128. /package/dist/{providers-VUIWO3ZK.js.map → program-FFWEILAS.js.map} +0 -0
  129. /package/dist/{registry-ASC2QS5K.js.map → providers-AKQ4HTB4.js.map} +0 -0
  130. /package/dist/{scheduler-A3TQOCKT.js.map → registry-IFMDJWQ7.js.map} +0 -0
  131. /package/dist/{workspace-setup-ZWTT42XT.js.map → scheduler-63D5KFO7.js.map} +0 -0
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import{a as B}from"./chunk-6MKAXEE5.js";import{a as _e,b as Ge,c as De,d as Ve,e as Ye,f as Qe,g as Ze,h as ie,i as q,j as lt,k as dt,l as pt,m as M,n as ae,o as gt,p as mt,q as ut,r as bt,s as I,t as C,u as N}from"./chunk-HVC6FJNP.js";import{a as se,b as $,c as W}from"./chunk-SFQUP3BP.js";import{a as ue,b as he,c as Rt,d as At,e as Mt,f as Et,g as Ot}from"./chunk-K7BE4E35.js";import{b as It}from"./chunk-FLOGK2U7.js";import"./chunk-QZP65I2H.js";import"./chunk-6U2XOQHU.js";import{a as ht,b as ft,c as yt,d as kt,g as vt}from"./chunk-ABDP7TDL.js";import"./chunk-HI24KAEY.js";import"./chunk-CXY2RYNI.js";import"./chunk-5F3J55LG.js";import{a as xt}from"./chunk-LEIYC3BF.js";import{a as wt,b as St}from"./chunk-WZEYII2S.js";import"./chunk-64P4QHSZ.js";import"./chunk-BFZUG66X.js";import{a as et,b as tt,c as st,d as K,e as re,f as rt,g as at,h as ct}from"./chunk-RB7265LO.js";import"./chunk-YI2T5QYB.js";import{d as $t,f as Ct,g as Pt,i as Tt}from"./chunk-7FJQGD6U.js";import{a as He,b as Ke,c as qe,d as We,e as Be,f as ze,g as L}from"./chunk-KXZMYLHQ.js";import{a as m,b as Le,c as Ne,d as Fe,e as Je,f as Ue}from"./chunk-M7HKBG3V.js";import{a as ne,b as Xe,c as H,d as oe}from"./chunk-MCJUAE6V.js";import{a as nt,b as ot,e as it}from"./chunk-DSYKYZMT.js";import"./chunk-7MBTMCKY.js";import"./chunk-QOYAX2FT.js";import"./chunk-FIOB3MEX.js";import{execa as jt}from"execa";import{existsSync as fe,promises as ce}from"fs";import P from"path";import we from"node-fetch";async function _t(i,e){let t=i.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${i}. Expected format: owner/repo`);let s=t[0],n=t[1],o=t[2];try{let r=o?`${s}/${n}/${o}`:`${s}/${n}`;await jt("npx",["-y","skills","add",r],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${i}`);let a=P.resolve(e,".skills",`${s}_${n}`);if(fe(a))return await ke(a,i);let c=P.resolve(e,".skills");return fe(c)?await ke(c,i):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${n}`),await Gt(s,n,o,e)}}async function Gt(i,e,t,s){let n=[];try{let o=`https://api.github.com/repos/${i}/${e}/git/trees/main?recursive=1`,r=await we(o);if(!r.ok)throw new Error(`GitHub API error: ${r.status}`);let c=(await r.json()).tree.filter(l=>l.type==="blob"&&l.path.endsWith("SKILL.md"));if(t){let l=c.find(p=>p.path.includes(`/${t}/`)||p.path===`${t}/SKILL.md`);if(l){let p=await ye(i,e,l.path,s);p&&n.push(p)}}else for(let l of c){let p=await ye(i,e,l.path,s);p&&n.push(p)}}catch(o){m.error(`Failed to fetch skills from GitHub: ${o.message}`)}return n}async function ye(i,e,t,s){try{let n=`https://raw.githubusercontent.com/${i}/${e}/main/${t}`,o=await we(n);if(!o.ok)return null;let r=await o.text(),a=H(r);if(a){a.source="remote",a.packageId=`${i}/${e}`;let c=P.dirname(t),l=P.resolve(s,".skills",`${i}_${e}`,c);await ce.mkdir(l,{recursive:!0}),await ce.writeFile(P.resolve(l,"SKILL.md"),r),a.path=P.resolve(l,"SKILL.md")}return a}catch{return null}}async function ke(i,e){let t=[],{default:s}=await import("fast-glob"),n=await s.glob("**/SKILL.md",{cwd:i,deep:5});for(let o of n)try{let r=P.resolve(i,o),a=await ce.readFile(r,"utf8"),c=H(a);c&&(c.source="remote",c.path=r,c.packageId=e,t.push(c))}catch{}return t}async function Dt(i,e,t,s,n){let o=["---",`name: ${i}`,`description: ${e}`];if(s?.length){o.push("tags:");for(let r of s)o.push(` - ${r}`)}if(n?.length){o.push("globs:");for(let r of n)o.push(` - ${r}`)}return o.push("---"),`${o.join(`
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(`
2
2
  `)}
3
3
 
4
- ${t}`}async function Lt(i){let{loadLocalSkills:e}=await import("./loader-PTCXLJEX.js");return e(i)}async function Nt(i,e,t,s,n){let r=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).
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).
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.
@@ -13,18 +13,18 @@ Skills should be:
13
13
  - Follow the Agent Skills specification
14
14
 
15
15
  The project's tech stack:
16
- ${$(s)}
16
+ ${M(s)}
17
17
 
18
- Output ONLY the SKILL.md content (frontmatter + markdown instructions). Do not wrap in code fences.`},{role:"user",content:`Create a skill called "${e}" with this description: "${t}"${n?.tags?.length?`
19
- Tags: ${n.tags.join(", ")}`:""}${n?.outputType?`
20
- Primary output type: ${n.outputType}`:""}
18
+ Output ONLY the SKILL.md content (frontmatter + markdown instructions). Do not wrap in code fences.`},{role:"user",content:`Create a skill called "${e}" with this description: "${t}"${i?.tags?.length?`
19
+ Tags: ${i.tags.join(", ")}`:""}${i?.outputType?`
20
+ Primary output type: ${i.outputType}`:""}
21
21
 
22
22
  The skill should contain detailed instructions for an AI agent to follow when performing this task in a project with the above tech stack. Include:
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`}],c=(await i.generate(r,{temperature:.7,maxTokens:4096})).content.trim(),l={frontmatter:{name:e,description:t},instructions:c,source:"generated"},p=c.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);return p&&(l.instructions=p[2].trim()),{skill:l,content:c}}import{existsSync as Ft,promises as Se}from"fs";import le from"path";var Jt={enabled:!0,autoSkills:!0,minFrequency:3,provider:"claude-code"},E=class{constructor(e,t,s){this.cwd=e;this.memory=t;this.config={...Jt,...s}}config;async enhance(){if(!this.config.enabled)return{skillsCreated:[],skillsUpdated:[],insights:[]};let e={skillsCreated:[],skillsUpdated:[],insights:[]};if(this.config.autoSkills){let n=await this.createSkillsFromPatterns();e.skillsCreated.push(...n)}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=[],n=le.resolve(this.cwd,".skills","_auto");for(let o of t.slice(0,3)){let r=Ut(o),a=le.resolve(n,r,"SKILL.md");if(!Ft(a))try{let c=await this.generateSkillFromPattern(o);c&&(await Se.mkdir(le.dirname(a),{recursive:!0}),await Se.writeFile(a,c,"utf8"),s.push(r))}catch{}}return s}async generateSkillFromPattern(e){let t=this.memory.getRecentGenerations(20).filter(a=>a.success&&a.userFeedback!=="negative").slice(0,3);if(!t.length)return null;let s=L(this.config.provider,this.config.apiKey),n=await se(this.cwd),o=[{role:"system",content:`You are a skill author. Create a SKILL.md file that captures a successful pattern.
27
- Tech stack: ${$(n)}
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.
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
 
30
30
  Pattern: ${e.description}
@@ -32,47 +32,17 @@ Frequency: used ${e.frequency} times
32
32
  Tech stack: ${e.techStack.join(", ")||"general"}
33
33
 
34
34
  Successful examples:
35
- ${t.map(a=>`- "${a.task}" \u2192 ${a.files.join(", ")}`).join(`
35
+ ${t.map(r=>`- "${r.task}" \u2192 ${r.files.join(", ")}`).join(`
36
36
  `)}
37
37
 
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 r=(o.error||"unknown").split(`
39
- `)[0].slice(0,80),a=s.get(r)||[];a.push(o),s.set(r,a)}for(let[o,r]of s)r.length>=2&&e.push(`Recurring error (${r.length}x): "${o}" \u2014 consider creating a skill to prevent this`);let n=this.memory.getStats();return n.successRate<.7&&n.totalGenerations>5&&e.push(`Success rate is ${(n.successRate*100).toFixed(0)}% \u2014 review recent failures and update skills`),e}analyzePreferences(){let e=[],s=this.memory.getPreferences().filter(n=>n.confidence>.8);return s.length&&e.push(`Strong preferences detected: ${s.map(n=>`${n.key}=${n.value}`).join(", ")}`),e}};function Ut(i){return i.description.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").slice(0,40).replace(/-+$/,"")}var O=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()},n=0,o=async()=>{if(n>=this.middleware.length)return;await this.middleware[n++].fn(e,t,s,o)};try{await o(),t.duration=Date.now()-s.startTime}catch(r){t.success=!1,t.error=r.message,t.duration=Date.now()-s.startTime}return t}getMiddlewareNames(){return this.middleware.map(e=>e.name)}};import{createServer as Ht}from"http";var Kt={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},z=class{config;memory;healEngine;enhanceEngine;pipeline;requestCount=0;log;constructor(e){this.config={...Kt,...e},this.memory=new W(this.config.cwd),this.healEngine=new B(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 E(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 O;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(),Ht(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
- 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"}`),n=e.method||"GET",o=s.pathname;this.log(`${n} ${o}`);try{switch(`${n} ${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(r){this.log("Error:",r.message),this.sendJson(t,500,{error:r.message})}this.requestCount++}async handleGenerate(e,t){let s=await de(e);if(!s.task){this.sendJson(t,400,{error:"Missing required field: task"});return}let n={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(n);this.sendJson(t,o.success?200:500,o)}async handleEvolve(e,t){let s=await de(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 I(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 de(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,n,o)=>{n.memory=e;let r=e.buildMemoryContext(t.task);r&&(n.memoryContext=r),await o()}}contextMiddleware(){return async(e,t,s,n)=>{s.agentContext=await I(e.cwd,e.task,{provider:e.provider,context7:{enabled:!0}}),await n()}}generateMiddleware(){return async(e,t,s,n)=>{let o=await C({task:s.memoryContext?`${e.task}
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(`
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
- ${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(r=>({path:r})),t.content=o.content,t.outputType=o.outputType,t.tokensUsed=o.tokensUsed,await n()}}healMiddleware(){let e=this.healEngine;return async(t,s,n,o)=>{if(this.config.heal.enabled&&s.files.length>0){let r=await e.detectAndHeal(s.files.map(a=>a.path),t.task,s.memoryEntryId);r.attempts>0&&(s.healed=r.healed,s.healAttempts=r.attempts,r.healed&&(s.success=!0))}await o()}}recordMiddleware(){let e=this.memory;return async(t,s,n,o)=>{if(this.config.memory.enabled){let r=await e.recordGeneration({task:t.task,outputType:s.outputType,files:s.files.map(a=>a.path),success:s.success,error:s.error,context:{techStack:n.agentContext?.techStack.languages.map(a=>a.name),frameworks:n.agentContext?.techStack.frameworks.map(a=>a.name)}});s.memoryEntryId=r,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,n,o)=>{this.config.enhance.enabled&&this.requestCount%10===0&&this.requestCount>0&&e.enhance().then(r=>{if(r.skillsCreated.length&&this.log(`Auto-created ${r.skillsCreated.length} skill(s): ${r.skillsCreated.join(", ")}`),r.insights.length)for(let a of r.insights)this.log(`Insight: ${a}`)}).catch(()=>{}),await o()}}sendJson(e,t,s){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(s,null,2))}};async function de(i){return new Promise((e,t)=>{let s="";i.on("data",n=>s+=n),i.on("end",()=>{try{e(s?JSON.parse(s):{})}catch{e({})}}),i.on("error",t)})}var qt={name:"agentx",version:"0.1.0"},Wt="2024-11-05",Bt={tools:{},elicitation:{form:{}}},zt=0;async function xe(i,e){let t=++zt;return T({jsonrpc:"2.0",id:`elicit-${t}`,method:"elicitation/create",params:{mode:"form",message:i,requestedSchema:e}}),new Promise(s=>{F.set(`elicit-${t}`,n=>{n?.action==="accept"&&n.content?s(n.content):s(null)}),setTimeout(()=>{F.has(`elicit-${t}`)&&(F.delete(`elicit-${t}`),s(null))},6e4)})}var F=new Map,k=process.env.AGENTX_DAEMON_URL||"http://localhost:19900",Vt=[{name:"agentx_generate",description:"Generate code, components, pages, APIs, documents, tests, workflows, schemas, emails, diagrams, and more using AI. Understands the project's tech stack, schemas, and skills automatically.",inputSchema:{type:"object",properties:{task:{type:"string",description:"Describe what to generate (e.g., 'a responsive pricing card', 'REST API for users', 'GitHub Actions CI pipeline')"},type:{type:"string",description:"Output type: component, page, api, website, document, script, config, skill, media, report, test, workflow, schema, email, diagram, auto",default:"auto"},output_dir:{type:"string",description:"Optional output directory (relative to project root)"},cwd:{type:"string",description:"Project working directory (defaults to current directory)"}},required:["task"]}},{name:"agentx_inspect",description:"Analyze a project and return its tech stack, frameworks, databases, schemas, installed skills, and dependencies. Use this to understand a project before generating code.",inputSchema:{type:"object",properties:{cwd:{type:"string",description:"Project working directory (defaults to current directory)"}}}},{name:"agentx_skill_match",description:"Find installed skills that are relevant to a given task description. Returns matched skills with relevance scores.",inputSchema:{type:"object",properties:{task:{type:"string",description:"The task to match skills against"},cwd:{type:"string",description:"Project working directory"}},required:["task"]}},{name:"agentx_detect_output_type",description:"Auto-detect the best output type for a given task description based on keyword analysis.",inputSchema:{type:"object",properties:{task:{type:"string",description:"The task description to analyze"}},required:["task"]}},{name:"agentx_send",description:"Send a message to any channel (Telegram, WhatsApp, GitLab, Discord). Use for cross-channel notifications, proactive outbound messages, or relaying information between channels.",inputSchema:{type:"object",properties:{channel:{type:"string",description:"Target channel: telegram, whatsapp, gitlab, discord"},chatId:{type:"string",description:'Chat ID. Telegram: numeric ("-1001234567890"). GitLab: "group/project:issue:123". WhatsApp: "+phone@s.whatsapp.net".'},text:{type:"string",description:"Message text to send"},agentId:{type:"string",description:"Agent ID to send as (determines bot account on Telegram, GitLab token, etc.)"}},required:["channel","chatId","text"]}},{name:"agentx_task",description:"Send a task to a specific agent on the daemon. The agent processes it and returns a response. Use to delegate work to specialized agents.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to send the task to"},message:{type:"string",description:"Task message for the agent"}},required:["agent","message"]}},{name:"agentx_agents",description:"List all agents registered on the daemon with their status (active tasks, total tasks, errors, tier).",inputSchema:{type:"object",properties:{}}},{name:"agentx_health",description:"Get the daemon health status including node info, agents, crons, mesh peers, and uptime.",inputSchema:{type:"object",properties:{}}},{name:"agentx_crons",description:"List cron jobs and their health. Shows healthy, failing, disabled counts and per-job status with consecutive error counts.",inputSchema:{type:"object",properties:{}}},{name:"agentx_debug",description:"Toggle debug mode on the daemon. Enable verbose logging for specific categories (webhook, agent, channel, cron, mesh, context, memory, all) or disable it.",inputSchema:{type:"object",properties:{action:{type:"string",description:'"on", "off", or "status"',default:"status"},categories:{type:"string",description:'Comma-separated categories to enable (e.g. "webhook,agent"). Only used with action=on.'}}}},{name:"agentx_wiki_query",description:"Query the agentx institutional wiki: a cross-agent knowledge base organized by article type (person, project, place, concept, event, decision, pattern). Use this BEFORE grep/memory-search when the question is about who / what happened / what we decided / how we do something. The query walks the catalog + wikilink graph and returns a synthesized answer with citations.",inputSchema:{type:"object",properties:{question:{type:"string",description:"The question to answer from the wiki, in natural language."},agent:{type:"string",description:"Which agent's wiki to query (default: first agent with a catalog). Each agent has its own wiki dir under .agentx/wiki/agents/<id>/"},wiki_dir:{type:"string",description:"Wiki root dir (default: <cwd>/.agentx/wiki)."},max_hops:{type:"number",description:"Wikilink hops from candidates (default 2, max 3).",default:2}},required:["question"]}}];async function Yt(i,e){let t=e.cwd||process.cwd();switch(i){case"agentx_generate":{let s=e.task,n=e.type||"auto",o=e.output_dir,r=await C({task:s,outputType:n,outputDir:o,cwd:t,overwrite:!0,dryRun:!1,context7:!0,interactive:!1,maxSteps:5}),a=[];return r.content&&a.push(r.content),r.files.written.length&&a.push(`
43
- Created ${r.files.written.length} file(s):
44
- ${r.files.written.map(c=>` - ${c}`).join(`
45
- `)}`),r.files.skipped.length&&a.push(`
46
- Skipped ${r.files.skipped.length} existing file(s):
47
- ${r.files.skipped.map(c=>` - ${c}`).join(`
48
- `)}`),r.followUp&&a.push(`
49
- Needs clarification: ${r.followUp}`),{content:[{type:"text",text:a.join(`
50
- `)||"Generation complete."}]}}case"agentx_inspect":{let s=await I(t,"inspect",{context7:{enabled:!1}}),n={languages:s.techStack.languages,frameworks:s.techStack.frameworks,packageManager:s.techStack.packageManager,databases:s.techStack.databases,styling:s.techStack.styling,testing:s.techStack.testing,deployment:s.techStack.deployment,monorepo:s.techStack.monorepo,srcDir:s.techStack.srcDir,dependencyCount:Object.keys(s.techStack.dependencies).length,devDependencyCount:Object.keys(s.techStack.devDependencies).length,schemas:{database:s.schemas.database?{type:s.schemas.database.type,tables:s.schemas.database.tables}:null,api:s.schemas.api?{type:s.schemas.api.type}:null,env:s.schemas.env?{variableCount:s.schemas.env.variables.length}:null,models:s.schemas.models?.map(o=>o.path)||[]},skills:s.skills.map(o=>({name:o.frontmatter.name,description:o.frontmatter.description,source:o.source}))};return{content:[{type:"text",text:`Project analysis:
51
-
52
- ${$(s.techStack)}
53
-
54
- ${JSON.stringify(n,null,2)}`}]}}case"agentx_skill_match":{let s=e.task,n=await ne(t),o=oe(n,s);return o.length?{content:[{type:"text",text:`Matching skills:
55
-
56
- ${o.map(a=>`- **${a.skill.frontmatter.name}** (relevance: ${(a.relevance*100).toFixed(0)}%)
57
- ${a.skill.frontmatter.description}
58
- Match: ${a.matchReason}`).join(`
59
-
60
- `)}`}]}:{content:[{type:"text",text:"No matching skills found. Install skills with: agentx skill install <owner/repo>"}]}}case"agentx_detect_output_type":{let s=e.task;return{content:[{type:"text",text:`Detected output type: ${ie(void 0,s)}`}]}}case"agentx_send":{let s=e.channel,n=e.chatId,o=e.text;if(!s||!n||!o){let c=await fetch(`${k}/channels`).catch(()=>null),l=c?await c.json():["telegram","whatsapp","gitlab","discord"],p=await xe("Please provide the message details:",{type:"object",properties:{channel:{type:"string",title:"Channel",description:"Target channel",enum:l,default:s||l[0]},chatId:{type:"string",title:"Chat ID",description:"Telegram: numeric ID. GitLab: group/project:issue:123",default:n||""},text:{type:"string",title:"Message",description:"Message text to send",default:o||""}},required:["channel","chatId","text"]});if(!p)return{content:[{type:"text",text:"Send cancelled."}]};s=p.channel,n=p.chatId,o=p.text}let r=await fetch(`${k}/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:s,chatId:n,text:o,agentId:e.agentId})}),a=await r.json();return r.ok?{content:[{type:"text",text:`Message sent. ID: ${a.messageId||"ok"}`}]}:{content:[{type:"text",text:`Error: ${a.error||r.statusText}`}]}}case"agentx_task":{let s=e.agent,n=e.message;if(!s||!n){let a=await fetch(`${k}/agents`).catch(()=>null),c=a?(await a.json()).map(p=>p.id):[],l=await xe("Which agent should handle this task?",{type:"object",properties:{agent:{type:"string",title:"Agent",description:"Agent ID",...c.length?{enum:c}:{},default:s||""},message:{type:"string",title:"Task",description:"Task message for the agent",default:n||""}},required:["agent","message"]});if(!l)return{content:[{type:"text",text:"Task cancelled."}]};s=l.agent,n=l.message}let r=await(await fetch(`${k}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:s,message:n})})).json();return r.error?{content:[{type:"text",text:`Agent error: ${r.error}`}]}:{content:[{type:"text",text:r.content||"Task completed."}]}}case"agentx_agents":return{content:[{type:"text",text:(await(await fetch(`${k}/agents`)).json()).map(r=>`${r.id} (${r.name}) \u2014 ${r.tier}, active: ${r.active}/${r.total}, errors: ${r.errors}`).join(`
61
- `)||"No agents."}]};case"agentx_health":{let n=await(await fetch(`${k}/health`)).json();return{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}case"agentx_crons":{let n=await(await fetch(`${k}/crons/health`)).json(),o=`Healthy: ${n.healthy}, Failing: ${n.failing}, Disabled: ${n.disabled}, Missed: ${n.missed}`,r=(n.jobs||[]).map(a=>` ${a.id}: ${a.status}${a.consecutiveErrors?` (${a.consecutiveErrors} errors)`:""}${a.lastError?` \u2014 ${a.lastError.slice(0,100)}`:""}`).join(`
62
- `);return{content:[{type:"text",text:`${o}
63
-
64
- ${r}`}]}}case"agentx_wiki_query":{let s=String(e.question||"").trim();if(!s)return{content:[{type:"text",text:"Error: `question` is required."}]};let{WikiHub:n}=await import("./wiki-UDPYFJBL.js"),{agenticQuery:o}=await import("./query-PKGYE5HR.js"),{resolve:r}=await import("path"),a=e.wiki_dir||r(process.cwd(),".agentx/wiki"),c=new n(a,void 0,"graph"),l=e.agent||"";if(!l){let{existsSync:b}=await import("fs");for(let me of c.listAgents()){let je=r(c.getAgentWiki(me).baseDir,"_index.md");if(b(je)){l=me;break}}}if(!l)return{content:[{type:"text",text:"Error: no agent has a wiki catalog yet. Run `agentx wiki absorb` first."}]};let p=c.getAgentWiki(l),f=typeof e.max_hops=="number"?Math.min(3,Math.max(0,e.max_hops)):2,h=await o(s,p,l,{maxHops:f});if(h.status!=="ok")return{content:[{type:"text",text:`Query returned status "${h.status}"${h.error?`: ${h.error}`:""}`}]};let A=h.citations.map(b=>` - ${b.title} [${b.type||"?"}] (${b.path})`).join(`
65
- `),G=h.walked.length;return{content:[{type:"text",text:`${h.answer}
66
-
67
- Citations (${G} article${G===1?"":"s"} walked):
68
- ${A}`}]}}case"agentx_debug":{let s=e.action||"status";if(s==="on"){let n=e.categories||"all";return await fetch(`${k}/debug/on?categories=${n}`,{method:"POST"}),{content:[{type:"text",text:`Debug enabled: ${n}`}]}}else{if(s==="off")return await fetch(`${k}/debug/off`,{method:"POST"}),{content:[{type:"text",text:"Debug disabled."}]};{let o=await(await fetch(`${k}/debug`)).json();return{content:[{type:"text",text:JSON.stringify(o,null,2)}]}}}}default:throw new Error(`Unknown tool: ${i}`)}}function ve(i,e){let t;try{t=JSON.parse(i)}catch(s){e("Failed to parse message:",s);return}if(t.id&&typeof t.id=="string"&&t.id.startsWith("elicit-")&&t.result){let s=F.get(t.id);s&&(F.delete(t.id),s(t.result));return}Xt(t,e).catch(s=>e("Error:",s))}async function Qt(){let i=(...t)=>console.error("[agentx-mcp]",...t);i("Starting MCP server (stdio transport)...");let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{for(e+=t;e.length>0;)if(e.startsWith("Content-Length:")){let n=e.indexOf(`\r
69
- \r
70
- `);if(n===-1)break;let r=e.slice(0,n).match(/Content-Length:\s*(\d+)/);if(!r){e=e.slice(n+4);continue}let a=parseInt(r[1],10),c=n+4,l=c+a;if(e.length<l)break;let p=e.slice(c,l);e=e.slice(l),ve(p,i)}else{let n=e.indexOf(`
71
- `);if(n===-1)break;let o=e.slice(0,n).trim();e=e.slice(n+1),o&&ve(o,i)}}),process.stdin.on("end",()=>{i("stdin closed, shutting down."),process.exit(0)})}function T(i){process.stdout.write(JSON.stringify(i)+`
72
- `)}async function Xt(i,e){let{method:t,id:s,params:n}=i;switch(e(`Received: ${t}`),t){case"initialize":{T({jsonrpc:"2.0",id:s,result:{protocolVersion:Wt,capabilities:Bt,serverInfo:qt}});break}case"notifications/initialized":{e("Client initialized.");break}case"tools/list":{T({jsonrpc:"2.0",id:s,result:{tools:Vt}});break}case"tools/call":{let o=n?.name,r=n?.arguments||{};try{let a=await Yt(o,r);T({jsonrpc:"2.0",id:s,result:a})}catch(a){T({jsonrpc:"2.0",id:s,result:{content:[{type:"text",text:`Error: ${a.message}`}],isError:!0}})}break}case"ping":{T({jsonrpc:"2.0",id:s,result:{}});break}default:s!==void 0&&T({jsonrpc:"2.0",id:s,error:{code:-32601,message:`Method not found: ${t}`}})}}import{execa as y}from"execa";var S=class{constructor(e){this.cwd=e}async isRepo(){try{return await y("git",["rev-parse","--is-inside-work-tree"],{cwd:this.cwd,reject:!1}),!0}catch{return!1}}async status(){let t=(await y("git",["status","--porcelain","-b"],{cwd:this.cwd,reject:!1})).stdout.trim().split(`
73
- `).filter(Boolean),s="unknown",n=[],o=[],r=[],a=[];for(let c of t){if(c.startsWith("## ")){s=c.slice(3).split("...")[0];continue}let l=c[0],p=c[1],f=c.slice(3).trim();(l==="A"||l==="M"||l==="R")&&n.push(f),l==="D"&&(a.push(f),n.push(f)),p==="M"&&o.push(f),p==="D"&&a.push(f),l==="?"&&p==="?"&&r.push(f)}return{staged:n,modified:o,untracked:r,deleted:[...new Set(a)],branch:s,isClean:n.length===0&&o.length===0&&r.length===0}}async diff(e=!1){return(await y("git",e?["diff","--cached"]:["diff"],{cwd:this.cwd,reject:!1})).stdout}async diffStat(e=!1){let s=await y("git",e?["diff","--cached","--numstat"]:["diff","--numstat"],{cwd:this.cwd,reject:!1}),n=[];for(let o of s.stdout.trim().split(`
74
- `).filter(Boolean)){let[r,a,c]=o.split(" ");if(!c)continue;let l="modified";r==="-"&&a==="-"&&(l="renamed"),n.push({path:c,status:l,additions:parseInt(r)||0,deletions:parseInt(a)||0})}return n}async log(e=10){let t=await y("git",["log",`--max-count=${e}`,"--format=%H|%h|%s|%an|%ai"],{cwd:this.cwd,reject:!1});return t.stdout.trim()?t.stdout.trim().split(`
75
- `).filter(Boolean).map(s=>{let[n,o,r,a,c]=s.split("|");return{hash:n,shortHash:o,message:r,author:a,date:c}}):[]}async add(e){e.length&&await y("git",["add",...e],{cwd:this.cwd})}async addAll(){await y("git",["add","-A"],{cwd:this.cwd})}async commit(e){let t=await y("git",["commit","-m",e],{cwd:this.cwd,reject:!1});if(t.exitCode!==0)throw new Error(t.stderr||t.stdout||"Git commit failed");let n=t.stdout.match(/\[[\w/.-]+\s+(\w+)\]/)?.[1]||"unknown",o=t.stdout.match(/(\d+)\s+files?\s+changed/),r=parseInt(o?.[1]||"0");return{hash:n,message:e,filesChanged:r}}async currentBranch(){return(await y("git",["branch","--show-current"],{cwd:this.cwd,reject:!1})).stdout.trim()}async createBranch(e){await y("git",["checkout","-b",e],{cwd:this.cwd})}async checkout(e){await y("git",["checkout",e],{cwd:this.cwd})}async stash(e){let t=["stash","push"];e&&t.push("-m",e),await y("git",t,{cwd:this.cwd})}async stashPop(){await y("git",["stash","pop"],{cwd:this.cwd})}async generateCommitMessage(e){let t=await this.diff(!0);if(!t.trim())throw new Error("No staged changes to commit");return e?(await e.generate([{role:"system",content:`You are a git commit message generator. Generate a conventional commit message (type(scope): subject) from the given diff.
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(`
43
+ `).filter(Boolean),s="unknown",i=[],o=[],a=[],r=[];for(let l of t){if(l.startsWith("## ")){s=l.slice(3).split("...")[0];continue}let c=l[0],g=l[1],h=l.slice(3).trim();(c==="A"||c==="M"||c==="R")&&i.push(h),c==="D"&&(r.push(h),i.push(h)),g==="M"&&o.push(h),g==="D"&&r.push(h),c==="?"&&g==="?"&&a.push(h)}return{staged:i,modified:o,untracked:a,deleted:[...new Set(r)],branch:s,isClean:i.length===0&&o.length===0&&a.length===0}}async diff(e=!1){return(await u("git",e?["diff","--cached"]:["diff"],{cwd:this.cwd,reject:!1})).stdout}async diffStat(e=!1){let s=await u("git",e?["diff","--cached","--numstat"]:["diff","--numstat"],{cwd:this.cwd,reject:!1}),i=[];for(let o of s.stdout.trim().split(`
44
+ `).filter(Boolean)){let[a,r,l]=o.split(" ");if(!l)continue;let c="modified";a==="-"&&r==="-"&&(c="renamed"),i.push({path:l,status:c,additions:parseInt(a)||0,deletions:parseInt(r)||0})}return i}async log(e=10){let t=await u("git",["log",`--max-count=${e}`,"--format=%H|%h|%s|%an|%ai"],{cwd:this.cwd,reject:!1});return t.stdout.trim()?t.stdout.trim().split(`
45
+ `).filter(Boolean).map(s=>{let[i,o,a,r,l]=s.split("|");return{hash:i,shortHash:o,message:a,author:r,date:l}}):[]}async add(e){e.length&&await u("git",["add",...e],{cwd:this.cwd})}async addAll(){await u("git",["add","-A"],{cwd:this.cwd})}async commit(e){let t=await u("git",["commit","-m",e],{cwd:this.cwd,reject:!1});if(t.exitCode!==0)throw new Error(t.stderr||t.stdout||"Git commit failed");let i=t.stdout.match(/\[[\w/.-]+\s+(\w+)\]/)?.[1]||"unknown",o=t.stdout.match(/(\d+)\s+files?\s+changed/),a=parseInt(o?.[1]||"0");return{hash:i,message:e,filesChanged:a}}async currentBranch(){return(await u("git",["branch","--show-current"],{cwd:this.cwd,reject:!1})).stdout.trim()}async createBranch(e){await u("git",["checkout","-b",e],{cwd:this.cwd})}async checkout(e){await u("git",["checkout",e],{cwd:this.cwd})}async stash(e){let t=["stash","push"];e&&t.push("-m",e),await u("git",t,{cwd:this.cwd})}async stashPop(){await u("git",["stash","pop"],{cwd:this.cwd})}async generateCommitMessage(e){let t=await this.diff(!0);if(!t.trim())throw new Error("No staged changes to commit");return e?(await e.generate([{role:"system",content:`You are a git commit message generator. Generate a conventional commit message (type(scope): subject) from the given diff.
76
46
  Rules:
77
47
  - Use conventional commit format: feat|fix|refactor|docs|test|chore|style(scope): message
78
48
  - Keep the subject line under 72 characters
@@ -81,13 +51,13 @@ Rules:
81
51
 
82
52
  ${t.slice(0,4e3)}`}])).content.trim().split(`
83
53
  `)[0]:this.fallbackCommitMessage(t)}fallbackCommitMessage(e){let t=e.split(`
84
- `),s=[];for(let n of t)if(n.startsWith("diff --git")){let o=n.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 rs}from"readline";import v from"chalk";import as from"ora";import{existsSync as be,mkdirSync as Zt,readFileSync as pe,readdirSync as $e,writeFileSync as es}from"fs";import J from"path";import ts from"os";var x=J.join(ts.homedir(),".agentx","sessions");function ge(){be(x)||Zt(x,{recursive:!0})}function j(i){return{id:ss(),createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),cwd:i,messages:[],tokensUsed:0,filesGenerated:[]}}function _(i){ge();let e=J.join(x,`${i.id}.json`);i.updatedAt=new Date().toISOString(),es(e,JSON.stringify(i,null,2),"utf8")}function R(i){let e=J.join(x,`${i}.json`);if(!be(e))return null;try{return JSON.parse(pe(e,"utf8"))}catch{return null}}function V(){ge();let i=$e(x).filter(t=>t.endsWith(".json")).map(t=>({name:t,path:J.join(x,t)}));if(!i.length)return null;let e=null;for(let t of i)try{let s=JSON.parse(pe(t.path,"utf8"));(!e||s.updatedAt>e.session.updatedAt)&&(e={name:t.name,session:s})}catch{}return e?.session??null}function Y(){ge();let i=$e(x).filter(t=>t.endsWith(".json")),e=[];for(let t of i)try{let s=JSON.parse(pe(J.join(x,t),"utf8"));e.push(s)}catch{}return e.sort((t,s)=>s.updatedAt.localeCompare(t.updatedAt)),e}function ss(){return Math.random().toString(36).slice(2,10)+Date.now().toString(36).slice(-4)}import g from"chalk";import{writeFileSync as ns}from"fs";import os from"path";import d from"chalk";function Ce(i,e){console.log(),console.log(d.bold.cyan(" agentx")+d.dim(` v${i}`)),console.log(d.dim(` Session: ${e}`)),console.log(d.dim(" Type /help for commands, /quit to exit")),console.log()}function Pe(i){if(i.written.length){console.log(),console.log(d.green(` Created ${i.written.length} file(s):`));for(let e of i.written)console.log(` ${d.green("+")} ${e}`)}if(i.skipped.length){console.log(),console.log(d.yellow(` Skipped ${i.skipped.length} file(s):`));for(let e of i.skipped)console.log(` ${d.yellow("~")} ${e}`)}if(i.errors.length){console.log(),console.log(d.red(` Failed ${i.errors.length} file(s):`));for(let e of i.errors)console.log(` ${d.red("x")} ${e}`)}}function U(i){let e=i/1e6*9;console.log(),console.log(d.dim(` Tokens: ${i.toLocaleString()} | Est. cost: $${e.toFixed(4)}`))}function Te(i){process.stdout.write(i)}function Re(){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 Ae(i){if(console.log(),console.log(d.dim(` Branch: ${i.branch}`)),i.isClean){console.log(d.green(" Working tree clean"));return}i.staged.length&&console.log(d.green(` Staged: ${i.staged.length}`)),i.modified.length&&console.log(d.yellow(` Modified: ${i.modified.length}`)),i.untracked.length&&console.log(d.dim(` Untracked: ${i.untracked.length}`)),console.log()}function Me(i){if(console.log(),console.log(d.bold(" Cost Breakdown")),console.log(),console.log(d.dim(` Total: ${i.totalTokens.toLocaleString()} tokens ($${i.totalCost.toFixed(4)})`)),console.log(d.dim(` Input: ${i.totalInputTokens.toLocaleString()} | Output: ${i.totalOutputTokens.toLocaleString()}`)),Object.keys(i.models).length){console.log(),console.log(d.dim(" Per model:"));for(let[e,t]of Object.entries(i.models))console.log(` ${d.cyan(e)}: ${(t.inputTokens+t.outputTokens).toLocaleString()} tokens, $${t.cost.toFixed(4)} (${t.steps} step${t.steps!==1?"s":""})`)}if(i.steps.length>1){console.log(),console.log(d.dim(" Per step:"));for(let e of i.steps)console.log(` Step ${e.step}: ${(e.inputTokens+e.outputTokens).toLocaleString()} tokens ($${e.cost.toFixed(4)})`)}console.log()}function Ie(i){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 i){let t=e.action==="create"?d.green("+"):d.yellow("~");console.log(` ${t} ${e.path} (${e.action})`)}console.log()}import is from"prompts";var Ee={};function u(i,e){Ee[i]=e}function Q(i){return Ee[i]}function X(i){return i.startsWith("/")}function Z(i){let e=i.trim(),t=e.indexOf(" ");return t===-1?{name:e.slice(1),args:""}:{name:e.slice(1,t),args:e.slice(t+1).trim()}}u("help",async()=>(Re(),!0));u("quit",async()=>!1);u("exit",async()=>!1);u("q",async()=>!1);u("clear",async(i,e)=>(e.session.messages=[],console.log(g.dim(" Conversation cleared")),!0));u("save",async(i,e)=>(_(e.session),console.log(g.dim(` Session saved: ${e.session.id}`)),!0));u("load",async(i,e)=>{let t=null;if(i){if(t=R(i),!t)return m.warn(`Session not found: ${i}`),!0}else{let s=Y();if(!s.length)return m.info("No saved sessions"),!0;let{sessionId:n}=await is({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(!n)return!0;t=R(n)}return t&&(e.onSessionChange(t),console.log(g.dim(` Loaded session: ${t.id} (${t.messages.length} messages)`))),!0});u("undo",async(i,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(g.dim(" Undid last exchange")),!0)});u("cost",async(i,e)=>{let t=K.getSummary();return t.steps.length>0?Me(t):U(e.session.tokensUsed),!0});u("export",async(i,e)=>{let t=K.getSummary(),s=re(e.session,t.steps.length?t:void 0),n=i||`session-${e.session.id}.md`,o=os.resolve(e.cwd,n);return ns(o,s,"utf8"),m.success(` Session exported to ${o}`),!0});u("files",async(i,e)=>{let t=e.session.filesGenerated;if(!t.length)return m.info("No files generated in this session"),!0;console.log(),console.log(g.dim(` Files generated (${t.length}):`));for(let s of t)console.log(` ${g.green("+")} ${s}`);return console.log(),!0});u("context",async(i,e)=>(console.log(),console.log(g.dim(` Session: ${e.session.id}`)),console.log(g.dim(` CWD: ${e.session.cwd}`)),console.log(g.dim(` Messages: ${e.session.messages.length}`)),console.log(g.dim(` Tokens: ${e.session.tokensUsed.toLocaleString()}`)),console.log(g.dim(` Files: ${e.session.filesGenerated.length}`)),console.log(g.dim(` Created: ${new Date(e.session.createdAt).toLocaleString()}`)),console.log(),!0));u("memory",async(i,e)=>{try{let t=new ae(e.cwd);await t.load();let s=t.getStats(),n=t.getPreferences(),o=t.getPatterns(),r=t.getRecentGenerations(5);if(console.log(),console.log(g.bold(" Memory")),console.log(),console.log(g.dim(" Project:")),console.log(g.dim(` Generations: ${s.project.totalGenerations}`)),console.log(g.dim(` Success rate: ${(s.project.successRate*100).toFixed(0)}%`)),console.log(g.dim(` Heals: ${s.project.totalHeals}`)),console.log(),console.log(g.dim(" Global:")),console.log(g.dim(` Generations: ${s.user.totalGenerations}`)),console.log(g.dim(` Success rate: ${(s.user.successRate*100).toFixed(0)}%`)),n.length){console.log(),console.log(g.dim(" Preferences:"));for(let a of n.slice(0,10))console.log(g.dim(` ${a.key}: ${a.value} (${(a.confidence*100).toFixed(0)}%)`))}if(o.length){console.log(),console.log(g.dim(" Patterns:"));for(let a of o.slice(0,5))console.log(g.dim(` ${a.description} (${a.frequency}x)`))}if(r.length){console.log(),console.log(g.dim(" Recent:"));for(let a of r){let c=a.success?g.green("ok"):g.red("fail");console.log(g.dim(` [${c}] ${a.task.slice(0,60)}`))}}console.log()}catch(t){m.error(` ${t.message}`)}return!0});u("mode",async(i,e)=>{if(i&&q.includes(i))M.setMode(i),m.success(` Permission mode: ${i}`);else if(i)m.warn(` Unknown mode: ${i}. Valid modes: ${q.join(", ")}`);else{let t=M.getMode();console.log(),console.log(g.dim(` Current mode: ${g.bold(t)}`)),console.log(),console.log(g.dim(" Available modes:")),console.log(g.dim(" default \u2014 confirm each file write")),console.log(g.dim(" acceptEdits \u2014 auto-allow writes, confirm destructive ops")),console.log(g.dim(" plan \u2014 show plan without writing")),console.log(g.dim(" yolo \u2014 auto-allow everything")),console.log(),console.log(g.dim(" Usage: /mode <mode>")),console.log()}return!0});u("commit",async(i,e)=>{try{let t=new S(e.cwd);if(!await t.isRepo())return m.warn("Not a git repository"),!0;let s=e.session.filesGenerated.filter(a=>a);if(s.length&&(await t.add(s),console.log(g.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 a=L();o=await t.generateCommitMessage(a)}catch{o=await t.generateCommitMessage()}console.log(g.dim(` Message: ${o}`));let r=await t.commit(o);m.success(` [${r.hash}] ${r.message}`)}catch(t){m.error(` ${t.message}`)}return!0});u("diff",async(i,e)=>{try{let s=await new S(e.cwd).diff();s.trim()?console.log(s):m.info("No changes")}catch(t){m.error(` ${t.message}`)}return!0});u("status",async(i,e)=>{try{let t=new S(e.cwd);if(!await t.isRepo())return m.warn("Not a git repository"),!0;let s=await t.status();Ae(s)}catch(t){m.error(` ${t.message}`)}return!0});var ee=class{rl=null;session;options;running=!1;constructor(e){if(this.options=e,e.sessionId){let t=R(e.sessionId);t?this.session=t:(m.warn(`Session ${e.sessionId} not found, starting new session`),this.session=j(e.cwd))}else if(e.resume){let t=V();t?(this.session=t,m.info(`Resumed session: ${t.id}`)):(m.info("No previous session found, starting new session"),this.session=j(e.cwd))}else this.session=j(e.cwd)}async start(){this.running=!0,Ce(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=rs({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(X(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,_(this.session),console.log(),console.log(v.dim(` Session saved: ${this.session.id}`)),U(this.session.tokensUsed),console.log(),this.rl?.close(),process.exit(0)}async handleCommand(e){let{name:t,args:s}=Z(e),n=Q(t);if(!n)return m.warn(` Unknown command: /${t}. Type /help for available commands.`),!0;let o={session:this.session,cwd:this.options.cwd,onSessionChange:r=>{this.session=r}};return n(s,o)}async handleGeneration(e){let t=as({text:"Thinking...",color:"cyan"}).start();try{let s=this.session.messages.filter(a=>a.role!=="system").map(a=>({role:a.role,content:a.content})),n={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,r=!1;for await(let a of N(n)){if(a.type==="context_ready"){t.stop(),console.log(),r=!0;continue}if(a.type==="text_delta"){Te(a.text);continue}if(a.type==="done"){console.log();continue}if(a.type==="error")throw new Error(a.error);if(a.type==="step_complete"){a.step>1&&console.log(v.dim(` Step ${a.step}: ${a.filesCount} file(s)`));continue}a.type==="generate_result"&&(o=a.result)}if(r||t.stop(),!o)return;(o.files.written.length||o.files.skipped.length||o.files.errors.length)&&(M.getMode()==="plan"?Ie(o.files.written.map(a=>({path:a,action:"create"}))):Pe(o.files)),o.tokensUsed&&U(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(`
85
- `)[0]}`))))}catch(s){throw t.stop(),s}}};import{createServer as cs}from"http";var w={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 ls={port:3171,host:"0.0.0.0",provider:"claude-code",cwd:process.cwd(),cors:!0},te=class{config;tasks=new Map;activeCancellations=new Set;log;constructor(e){this.config={...ls,...e},this.log=console.error.bind(console,"[a2a]")}async start(){cs(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(`
86
- 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"}`),n=e.method||"GET",o=s.pathname;this.log(`${n} ${o}`);try{if(n==="GET"&&o==="/.well-known/agent-card.json"){this.sendJson(t,200,this.getAgentCard());return}if(n==="POST"&&o==="/"){let r=await ds(e);await this.handleJsonRpc(r,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(r){this.log("Error:",r.message),this.sendJson(t,500,{error:r.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:w.PARSE_ERROR});return}let s=e,n=s.params||{};switch(s.method){case"tasks/send":await this.handleTaskSend(s.id,n,t);break;case"tasks/sendSubscribe":await this.handleTaskSendSubscribe(s.id,n,t);break;case"tasks/get":this.handleTaskGet(s.id,n,t);break;case"tasks/cancel":this.handleTaskCancel(s.id,n,t);break;default:this.sendJsonRpc(t,{jsonrpc:"2.0",id:s.id,error:w.METHOD_NOT_FOUND})}}async handleTaskSend(e,t,s){let n=String(t.id||`task-${Date.now().toString(36)}`),o=t.message;if(!o?.parts?.length){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:{...w.INVALID_PARAMS,data:"message with parts is required"}});return}let a=o.parts.filter(l=>l.type==="text").map(l=>l.text).join(`
87
- `);if(!a){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:{...w.INVALID_PARAMS,data:"No text content in message parts"}});return}let c={id:n,state:"submitted",messages:[{role:"user",parts:o.parts}],artifacts:[],metadata:t.metadata,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};this.tasks.set(n,c),c.state="working",c.updatedAt=new Date().toISOString();try{let l=await C({task:a,cwd:this.config.cwd,provider:this.config.provider,model:this.config.model,apiKey:this.config.apiKey,overwrite:!0,interactive:!1,context7:!0}),p=l.files.written.map((h,A)=>({name:h,description:"Generated file",parts:[{type:"text",text:h}],index:A})),f={role:"agent",parts:[{type:"text",text:l.content||"Generation complete."}]};l.followUp?(c.state="input-required",f.parts.push({type:"text",text:`
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(`
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:`
88
58
 
89
- Question: ${l.followUp}`})):c.state="completed",c.messages.push(f),c.artifacts=p,c.updatedAt=new Date().toISOString()}catch(l){c.state="failed",c.messages.push({role:"agent",parts:[{type:"text",text:`Error: ${l.message}`}]}),c.updatedAt=new Date().toISOString()}this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,result:c})}async handleTaskSendSubscribe(e,t,s){let n=String(t.id||`task-${Date.now().toString(36)}`),o=t.message;if(!o?.parts?.length){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:{...w.INVALID_PARAMS,data:"message with parts is required"}});return}let a=o.parts.filter(p=>p.type==="text").map(p=>p.text).join(`
90
- `);if(!a){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:{...w.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 c={id:n,state:"submitted",messages:[{role:"user",parts:o.parts}],artifacts:[],metadata:t.metadata,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};this.tasks.set(n,c);let l=p=>{s.write(`data: ${JSON.stringify(p)}
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
+ `);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)}
91
61
 
92
- `)};l({id:n,state:"submitted",final:!1}),c.state="working",c.updatedAt=new Date().toISOString(),l({id:n,state:"working",final:!1});try{let p="",f=[];for await(let h of N({task:a,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(n)){this.activeCancellations.delete(n),c.state="canceled",c.updatedAt=new Date().toISOString(),l({id:n,state:"canceled",final:!0}),s.end();return}if(h.type==="text_delta"&&(p+=h.text,l({id:n,state:"working",message:{role:"agent",parts:[{type:"text",text:h.text}]},final:!1})),h.type==="generate_result"){let A=h.result,G=A.files.written.map((D,b)=>({name:D,parts:[{type:"text",text:D}],index:b}));f.push(...G);for(let D of G)l({id:n,state:"working",artifact:D,final:!1});A.followUp?c.state="input-required":c.state="completed"}}c.messages.push({role:"agent",parts:[{type:"text",text:p||"Generation complete."}]}),c.artifacts=f,c.updatedAt=new Date().toISOString(),l({id:n,state:c.state,final:!0})}catch(p){c.state="failed",c.messages.push({role:"agent",parts:[{type:"text",text:`Error: ${p.message}`}]}),c.updatedAt=new Date().toISOString(),l({id:n,state:"failed",message:{role:"agent",parts:[{type:"text",text:`Error: ${p.message}`}]},final:!0})}s.end()}handleTaskGet(e,t,s){let n=String(t.id||""),o=this.tasks.get(n);if(!o){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:w.TASK_NOT_FOUND});return}this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,result:o})}handleTaskCancel(e,t,s){let n=String(t.id||""),o=this.tasks.get(n);if(!o){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:w.TASK_NOT_FOUND});return}if(o.state!=="working"&&o.state!=="submitted"){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:w.TASK_NOT_CANCELABLE});return}this.activeCancellations.add(n),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 ds(i){return new Promise((e,t)=>{let s="";i.on("data",n=>s+=n),i.on("end",()=>{try{e(s?JSON.parse(s):{})}catch{e({})}}),i.on("error",t)})}Tt();var Oe={"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 ps(i,e){let t=Oe[i];if(!t)return[`Unknown provider "${i}" \u2014 capabilities unknown`];if(!e?.length)return[];let s=[],n=[];for(let o of e)o in t&&!t[o]&&n.push(o);return n.length&&s.push(`Provider "${i}" lacks: ${n.join(", ")}. Some features will be degraded.`),s}function gs(i){typeof i=="string"&&(m.error(i),process.exit(1)),i instanceof Error&&(m.error(i.message),process.exit(1)),m.error("Something went wrong. Please try again."),process.exit(1)}export{ue as A2AClient,he as A2AMesh,te as A2AServer,We as ALL_TOOL_NAMES,vt as AgentRegistry,Et as AgentXDaemon,z as AgentXRuntime,tt as BLOCKING_EVENTS,ze as ClaudeCodeProvider,Be as ClaudeProvider,ut as ContextBuilder,It as CronScheduler,E as EnhanceEngine,S as GitManager,St as GraphStore,et as HOOK_EVENTS,B as HealEngine,rt as HookRegistry,W as Memory,ae as MemoryHierarchy,Rt as MessageRouter,Ze as OUTPUT_CONFIGS,Ge as OUTPUT_TYPES,q as PERMISSION_MODES,Oe as PROVIDER_CAPABILITIES,pt as PermissionManager,O as Pipeline,ee as ReplEngine,wt as STARTER_SCHEMA,At as TelegramAdapter,bt as ToolExecutor,st as UsageTracker,Mt as WhatsAppAdapter,xt as WikiStore,_e as agentConfigSchema,ps as checkCapabilities,I as createAgentContext,L as createProvider,j as createSession,$t as daemonConfigSchema,it as debug,Ve as detectSchemas,se as detectTechStack,Ue as ensureCredentials,ht as executeClaudeCode,yt as executeOrchestrator,ft as executeSdk,kt as executeTask,re as exportSession,Ye as formatSchemas,$ as formatTechStack,qe as formatToolsForSystemPrompt,Qe as gatherContext7Docs,C as generate,Nt as generateSkill,Dt as generateSkillMd,N as generateStream,He as getAnthropicTools,Q as getCommand,Ke as getLegacyTools,Ot as getPackageInfo,ct as globalHooks,M as globalPermissions,K as globalTracker,gs as handleError,_t as installSkillPackage,X as isCommand,ot as isDebug,Lt as listInstalledSkills,Y as listSessions,Le as loadAuthConfig,Ct as loadDaemonConfig,at as loadHooks,V as loadLatestSession,ne as loadLocalSkills,mt as loadProjectInstructions,R as loadSession,m as logger,oe as matchSkillsToTask,De as outputTypeDescriptions,Z as parseCommand,H as parseSkillContent,Xe as parseSkillFile,dt as permissionConfigSchema,lt as permissionModeSchema,u as registerCommand,gt as resolveAtImports,ie as resolveOutputType,Fe as resolveToken,Je as runModelSetup,Ne as saveAuthConfig,_ as saveSession,nt as setDebug,Qt as startMcpServer,Pt 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 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};
93
63
  //# sourceMappingURL=index.js.map