agentix-cli 0.8.0 → 0.13.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 (71) hide show
  1. package/README.md +387 -116
  2. package/dist/agent-5KIMJI3F.js +2 -0
  3. package/dist/chunk-34UAFPK4.js +10 -0
  4. package/dist/chunk-34UAFPK4.js.map +1 -0
  5. package/dist/{chunk-X7UN6JAA.js → chunk-6MKAXEE5.js} +2 -2
  6. package/dist/chunk-CJ45Y2IR.js +12 -0
  7. package/dist/chunk-CJ45Y2IR.js.map +1 -0
  8. package/dist/chunk-D6EDMQRV.js +108 -0
  9. package/dist/chunk-D6EDMQRV.js.map +1 -0
  10. package/dist/chunk-DSYKYZMT.js +2 -0
  11. package/dist/chunk-DSYKYZMT.js.map +1 -0
  12. package/dist/chunk-HI24KAEY.js +54 -0
  13. package/dist/chunk-HI24KAEY.js.map +1 -0
  14. package/dist/{chunk-MGMZNJCE.js → chunk-KXZMYLHQ.js} +27 -27
  15. package/dist/chunk-KXZMYLHQ.js.map +1 -0
  16. package/dist/chunk-MCJUAE6V.js +6 -0
  17. package/dist/chunk-MCJUAE6V.js.map +1 -0
  18. package/dist/chunk-QOYAX2FT.js +2 -0
  19. package/dist/chunk-QOYAX2FT.js.map +1 -0
  20. package/dist/chunk-QZP65I2H.js +45 -0
  21. package/dist/chunk-QZP65I2H.js.map +1 -0
  22. package/dist/chunk-T25UEXVK.js +126 -0
  23. package/dist/chunk-T25UEXVK.js.map +1 -0
  24. package/dist/chunk-VH23CDHL.js +157 -0
  25. package/dist/chunk-VH23CDHL.js.map +1 -0
  26. package/dist/chunk-WJ6ZF6EZ.js +6 -0
  27. package/dist/chunk-WJ6ZF6EZ.js.map +1 -0
  28. package/dist/chunk-ZRYBSI5G.js +23 -0
  29. package/dist/chunk-ZRYBSI5G.js.map +1 -0
  30. package/dist/cli.js +277 -36
  31. package/dist/cli.js.map +1 -1
  32. package/dist/compaction-7I3E5QUO.js +28 -0
  33. package/dist/compaction-7I3E5QUO.js.map +1 -0
  34. package/dist/config-HAD5E4YX.js +2 -0
  35. package/dist/debug-N3B5NVJU.js +2 -0
  36. package/dist/heal-OTGT5HHJ.js +2 -0
  37. package/dist/index.d.ts +1849 -368
  38. package/dist/index.js +39 -35
  39. package/dist/index.js.map +1 -1
  40. package/dist/loader-YQE6XJBT.js +2 -0
  41. package/dist/loader-YQE6XJBT.js.map +1 -0
  42. package/dist/memory-extract-RGPUPMKU.js +2 -0
  43. package/dist/memory-extract-RGPUPMKU.js.map +1 -0
  44. package/dist/{providers-AVYG63KK.js → providers-G3WZ4RVJ.js} +2 -2
  45. package/dist/providers-G3WZ4RVJ.js.map +1 -0
  46. package/dist/registry-CDWY7CLL.js +2 -0
  47. package/dist/registry-CDWY7CLL.js.map +1 -0
  48. package/dist/subagent-WV7QKQ3L.js +3 -0
  49. package/dist/subagent-WV7QKQ3L.js.map +1 -0
  50. package/dist/usage-dashboard-2TJQBFSH.js +404 -0
  51. package/dist/usage-dashboard-2TJQBFSH.js.map +1 -0
  52. package/dist/workspace-setup-QQTCJY4B.js +2 -0
  53. package/dist/workspace-setup-QQTCJY4B.js.map +1 -0
  54. package/package.json +4 -1
  55. package/dist/agent-K2YOEOJ5.js +0 -2
  56. package/dist/chunk-F73GPYCO.js +0 -106
  57. package/dist/chunk-F73GPYCO.js.map +0 -1
  58. package/dist/chunk-FRFR27IN.js +0 -3
  59. package/dist/chunk-FRFR27IN.js.map +0 -1
  60. package/dist/chunk-MGMZNJCE.js.map +0 -1
  61. package/dist/chunk-NGKOM4ZZ.js +0 -137
  62. package/dist/chunk-NGKOM4ZZ.js.map +0 -1
  63. package/dist/chunk-Z4GC5D6D.js +0 -12
  64. package/dist/chunk-Z4GC5D6D.js.map +0 -1
  65. package/dist/heal-UV5A6B5T.js +0 -2
  66. package/dist/loader-6VSM6FSY.js +0 -2
  67. /package/dist/{agent-K2YOEOJ5.js.map → agent-5KIMJI3F.js.map} +0 -0
  68. /package/dist/{chunk-X7UN6JAA.js.map → chunk-6MKAXEE5.js.map} +0 -0
  69. /package/dist/{heal-UV5A6B5T.js.map → config-HAD5E4YX.js.map} +0 -0
  70. /package/dist/{loader-6VSM6FSY.js.map → debug-N3B5NVJU.js.map} +0 -0
  71. /package/dist/{providers-AVYG63KK.js.map → heal-OTGT5HHJ.js.map} +0 -0
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import{a as de,b as pe,c as pt,d as gt,e as mt,f as ut,g as ft,h as ht,i as yt,j as kt,k as wt,l as St,m as vt,n as xt,o as bt,p as Ct,q as Pt}from"./chunk-NGKOM4ZZ.js";import{a as H}from"./chunk-X7UN6JAA.js";import{a as Me,b as Ee,c as Oe,d as Ke,e as Be,f as We,g as ze,h as te,i as J,j as ot,k as rt,l as it,m as R,n as ne,o as at,p as ct,q as lt,r as dt,s as T,t as b,u as j}from"./chunk-F73GPYCO.js";import{a as Ve,b as Ye,c as Xe,d as F,e as Qe,f as Ze,g as et,h as se,i as tt,j as st,k as nt}from"./chunk-Z4GC5D6D.js";import{a as Z,b as qe,c as _,d as ee}from"./chunk-FRFR27IN.js";import{a as Q,b as x,c as U}from"./chunk-SFQUP3BP.js";import{a as Ne,b as _e,c as Fe,d as Je,e as Ue,f as He,g as G}from"./chunk-MGMZNJCE.js";import{a as m,b as Ie,c as Ge,d as je,e as Le,f as De}from"./chunk-M7HKBG3V.js";import"./chunk-4YCH6IZV.js";import{execa as $t}from"execa";import{existsSync as ge,promises as oe}from"fs";import C from"path";import fe from"node-fetch";async function Rt(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],r=t[1],n=t[2];try{let a=n?`${s}/${r}/${n}`:`${s}/${r}`;await $t("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let i=C.resolve(e,".skills",`${s}_${r}`);if(ge(i))return await ue(i,o);let c=C.resolve(e,".skills");return ge(c)?await ue(c,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${r}`),await Tt(s,r,n,e)}}async function Tt(o,e,t,s){let r=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await fe(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let c=(await a.json()).tree.filter(l=>l.type==="blob"&&l.path.endsWith("SKILL.md"));if(t){let l=c.find(g=>g.path.includes(`/${t}/`)||g.path===`${t}/SKILL.md`);if(l){let g=await me(o,e,l.path,s);g&&r.push(g)}}else for(let l of c){let g=await me(o,e,l.path,s);g&&r.push(g)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return r}async function me(o,e,t,s){try{let r=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await fe(r);if(!n.ok)return null;let a=await n.text(),i=_(a);if(i){i.source="remote",i.packageId=`${o}/${e}`;let c=C.dirname(t),l=C.resolve(s,".skills",`${o}_${e}`,c);await oe.mkdir(l,{recursive:!0}),await oe.writeFile(C.resolve(l,"SKILL.md"),a),i.path=C.resolve(l,"SKILL.md")}return i}catch{return null}}async function ue(o,e){let t=[],{default:s}=await import("fast-glob"),r=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of r)try{let a=C.resolve(o,n),i=await oe.readFile(a,"utf8"),c=_(i);c&&(c.source="remote",c.path=a,c.packageId=e,t.push(c))}catch{}return t}async function At(o,e,t,s,r){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(r?.length){n.push("globs:");for(let a of r)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
1
+ import{a as W}from"./chunk-6MKAXEE5.js";import{a as Ee,b as je,c as Ge,d as qe,e as ze,f as Ve,g as Xe,h as ne,i as H,j as at,k as ct,l as lt,m as A,n as ie,o as dt,p as pt,q as gt,r as wt,s as M,t as $,u as _}from"./chunk-D6EDMQRV.js";import{a as ee,b,c as K}from"./chunk-SFQUP3BP.js";import{a as ge,b as me,c as bt,d as $t,e as Ct,f as Pt,g as Tt,h as Rt}from"./chunk-T25UEXVK.js";import{a as mt,b as ut,c as ht,d as ft,e as yt,i as kt}from"./chunk-VH23CDHL.js";import{a as Qe,b as Ze,c as et,d as U,e as oe,f as ot,g as it,h as rt}from"./chunk-CJ45Y2IR.js";import{a as St,b as xt,c as vt}from"./chunk-WJ6ZF6EZ.js";import"./chunk-QZP65I2H.js";import"./chunk-HI24KAEY.js";import"./chunk-34UAFPK4.js";import{a as Je,b as Ue,c as He,d as Ke,e as We,f as Be,g as G}from"./chunk-KXZMYLHQ.js";import{a as m,b as _e,c as De,d as Le,e as Ne,f as Fe}from"./chunk-M7HKBG3V.js";import{a as te,b as Ye,c as J,d as se}from"./chunk-MCJUAE6V.js";import{a as tt,b as st,e as nt}from"./chunk-DSYKYZMT.js";import"./chunk-ZRYBSI5G.js";import"./chunk-QOYAX2FT.js";import"./chunk-4YCH6IZV.js";import{execa as At}from"execa";import{existsSync as ue,promises as re}from"fs";import C from"path";import ye from"node-fetch";async function Mt(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],o=t[1],n=t[2];try{let a=n?`${s}/${o}/${n}`:`${s}/${o}`;await At("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${i}`);let r=C.resolve(e,".skills",`${s}_${o}`);if(ue(r))return await fe(r,i);let c=C.resolve(e,".skills");return ue(c)?await fe(c,i):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${o}`),await It(s,o,n,e)}}async function It(i,e,t,s){let o=[];try{let n=`https://api.github.com/repos/${i}/${e}/git/trees/main?recursive=1`,a=await ye(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let c=(await a.json()).tree.filter(l=>l.type==="blob"&&l.path.endsWith("SKILL.md"));if(t){let l=c.find(d=>d.path.includes(`/${t}/`)||d.path===`${t}/SKILL.md`);if(l){let d=await he(i,e,l.path,s);d&&o.push(d)}}else for(let l of c){let d=await he(i,e,l.path,s);d&&o.push(d)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return o}async function he(i,e,t,s){try{let o=`https://raw.githubusercontent.com/${i}/${e}/main/${t}`,n=await ye(o);if(!n.ok)return null;let a=await n.text(),r=J(a);if(r){r.source="remote",r.packageId=`${i}/${e}`;let c=C.dirname(t),l=C.resolve(s,".skills",`${i}_${e}`,c);await re.mkdir(l,{recursive:!0}),await re.writeFile(C.resolve(l,"SKILL.md"),a),r.path=C.resolve(l,"SKILL.md")}return r}catch{return null}}async function fe(i,e){let t=[],{default:s}=await import("fast-glob"),o=await s.glob("**/SKILL.md",{cwd:i,deep:5});for(let n of o)try{let a=C.resolve(i,n),r=await re.readFile(a,"utf8"),c=J(r);c&&(c.source="remote",c.path=a,c.packageId=e,t.push(c))}catch{}return t}async function Ot(i,e,t,s,o){let n=["---",`name: ${i}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(o?.length){n.push("globs:");for(let a of o)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
2
2
  `)}
3
3
 
4
- ${t}`}async function Mt(o){let{loadLocalSkills:e}=await import("./loader-6VSM6FSY.js");return e(o)}async function Et(o,e,t,s,r){let a=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).
4
+ ${t}`}async function Et(i){let{loadLocalSkills:e}=await import("./loader-YQE6XJBT.js");return e(i)}async function jt(i,e,t,s,o){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
- ${x(s)}
16
+ ${b(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}"${r?.tags?.length?`
19
- Tags: ${r.tags.join(", ")}`:""}${r?.outputType?`
20
- Primary output type: ${r.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}"${o?.tags?.length?`
19
+ Tags: ${o.tags.join(", ")}`:""}${o?.outputType?`
20
+ Primary output type: ${o.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 o.generate(a,{temperature:.7,maxTokens:4096})).content.trim(),l={frontmatter:{name:e,description:t},instructions:c,source:"generated"},g=c.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);return g&&(l.instructions=g[2].trim()),{skill:l,content:c}}import{existsSync as Ot,promises as he}from"fs";import re from"path";var It={enabled:!0,autoSkills:!0,minFrequency:3,provider:"claude-code"},A=class{constructor(e,t,s){this.cwd=e;this.memory=t;this.config={...It,...s}}config;async enhance(){if(!this.config.enabled)return{skillsCreated:[],skillsUpdated:[],insights:[]};let e={skillsCreated:[],skillsUpdated:[],insights:[]};if(this.config.autoSkills){let r=await this.createSkillsFromPatterns();e.skillsCreated.push(...r)}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(n=>n.frequency>=this.config.minFrequency);if(!t.length)return[];let s=[],r=re.resolve(this.cwd,".skills","_auto");for(let n of t.slice(0,3)){let a=Gt(n),i=re.resolve(r,a,"SKILL.md");if(!Ot(i))try{let c=await this.generateSkillFromPattern(n);c&&(await he.mkdir(re.dirname(i),{recursive:!0}),await he.writeFile(i,c,"utf8"),s.push(a))}catch{}}return s}async generateSkillFromPattern(e){let t=this.memory.getRecentGenerations(20).filter(i=>i.success&&i.userFeedback!=="negative").slice(0,3);if(!t.length)return null;let s=G(this.config.provider,this.config.apiKey),r=await Q(this.cwd),n=[{role:"system",content:`You are a skill author. Create a SKILL.md file that captures a successful pattern.
27
- Tech stack: ${x(r)}
26
+ 4. Examples where helpful`}],c=(await i.generate(a,{temperature:.7,maxTokens:4096})).content.trim(),l={frontmatter:{name:e,description:t},instructions:c,source:"generated"},d=c.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);return d&&(l.instructions=d[2].trim()),{skill:l,content:c}}import{existsSync as Gt,promises as ke}from"fs";import ae from"path";var _t={enabled:!0,autoSkills:!0,minFrequency:3,provider:"claude-code"},I=class{constructor(e,t,s){this.cwd=e;this.memory=t;this.config={..._t,...s}}config;async enhance(){if(!this.config.enabled)return{skillsCreated:[],skillsUpdated:[],insights:[]};let e={skillsCreated:[],skillsUpdated:[],insights:[]};if(this.config.autoSkills){let o=await this.createSkillsFromPatterns();e.skillsCreated.push(...o)}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(n=>n.frequency>=this.config.minFrequency);if(!t.length)return[];let s=[],o=ae.resolve(this.cwd,".skills","_auto");for(let n of t.slice(0,3)){let a=Dt(n),r=ae.resolve(o,a,"SKILL.md");if(!Gt(r))try{let c=await this.generateSkillFromPattern(n);c&&(await ke.mkdir(ae.dirname(r),{recursive:!0}),await ke.writeFile(r,c,"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=G(this.config.provider,this.config.apiKey),o=await ee(this.cwd),n=[{role:"system",content:`You are a skill author. Create a SKILL.md file that captures a successful pattern.
27
+ Tech stack: ${b(o)}
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,40 +32,44 @@ Frequency: used ${e.frequency} times
32
32
  Tech stack: ${e.techStack.join(", ")||"general"}
33
33
 
34
34
  Successful examples:
35
- ${t.map(i=>`- "${i.task}" \u2192 ${i.files.join(", ")}`).join(`
35
+ ${t.map(r=>`- "${r.task}" \u2192 ${r.files.join(", ")}`).join(`
36
36
  `)}
37
37
 
38
38
  Create a concise, reusable skill that captures what worked.`}];return(await s.generate(n,{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 n of t){let a=(n.error||"unknown").split(`
39
- `)[0].slice(0,80),i=s.get(a)||[];i.push(n),s.set(a,i)}for(let[n,a]of s)a.length>=2&&e.push(`Recurring error (${a.length}x): "${n}" \u2014 consider creating a skill to prevent this`);let r=this.memory.getStats();return r.successRate<.7&&r.totalGenerations>5&&e.push(`Success rate is ${(r.successRate*100).toFixed(0)}% \u2014 review recent failures and update skills`),e}analyzePreferences(){let e=[],s=this.memory.getPreferences().filter(r=>r.confidence>.8);return s.length&&e.push(`Strong preferences detected: ${s.map(r=>`${r.key}=${r.value}`).join(", ")}`),e}};function Gt(o){return o.description.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").slice(0,40).replace(/-+$/,"")}var M=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()},r=0,n=async()=>{if(r>=this.middleware.length)return;await this.middleware[r++].fn(e,t,s,n)};try{await n(),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 jt}from"http";var Lt={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},K=class{config;memory;healEngine;enhanceEngine;pipeline;requestCount=0;log;constructor(e){this.config={...Lt,...e},this.memory=new U(this.config.cwd),this.healEngine=new H(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 A(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 M;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(),jt(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"}`),r=e.method||"GET",n=s.pathname;this.log(`${r} ${n}`);try{switch(`${r} ${n}`){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 ie(e);if(!s.task){this.sendJson(t,400,{error:"Missing required field: task"});return}let r={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},n=await this.pipeline.execute(r);this.sendJson(t,n.success?200:500,n)}async handleEvolve(e,t){let s=await ie(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 T(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 ie(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,r,n)=>{r.memory=e;let a=e.buildMemoryContext(t.task);a&&(r.memoryContext=a),await n()}}contextMiddleware(){return async(e,t,s,r)=>{s.agentContext=await T(e.cwd,e.task,{provider:e.provider,context7:{enabled:!0}}),await r()}}generateMiddleware(){return async(e,t,s,r)=>{let n=await b({task:s.memoryContext?`${e.task}
39
+ `)[0].slice(0,80),r=s.get(a)||[];r.push(n),s.set(a,r)}for(let[n,a]of s)a.length>=2&&e.push(`Recurring error (${a.length}x): "${n}" \u2014 consider creating a skill to prevent this`);let o=this.memory.getStats();return o.successRate<.7&&o.totalGenerations>5&&e.push(`Success rate is ${(o.successRate*100).toFixed(0)}% \u2014 review recent failures and update skills`),e}analyzePreferences(){let e=[],s=this.memory.getPreferences().filter(o=>o.confidence>.8);return s.length&&e.push(`Strong preferences detected: ${s.map(o=>`${o.key}=${o.value}`).join(", ")}`),e}};function Dt(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()},o=0,n=async()=>{if(o>=this.middleware.length)return;await this.middleware[o++].fn(e,t,s,n)};try{await n(),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 Lt}from"http";var Nt={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},B=class{config;memory;healEngine;enhanceEngine;pipeline;requestCount=0;log;constructor(e){this.config={...Nt,...e},this.memory=new K(this.config.cwd),this.healEngine=new W(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 I(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(),Lt(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"}`),o=e.method||"GET",n=s.pathname;this.log(`${o} ${n}`);try{switch(`${o} ${n}`){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 ce(e);if(!s.task){this.sendJson(t,400,{error:"Missing required field: task"});return}let o={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},n=await this.pipeline.execute(o);this.sendJson(t,n.success?200:500,n)}async handleEvolve(e,t){let s=await ce(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 M(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 ce(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,o,n)=>{o.memory=e;let a=e.buildMemoryContext(t.task);a&&(o.memoryContext=a),await n()}}contextMiddleware(){return async(e,t,s,o)=>{s.agentContext=await M(e.cwd,e.task,{provider:e.provider,context7:{enabled:!0}}),await o()}}generateMiddleware(){return async(e,t,s,o)=>{let n=await $({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=n.files.errors.length===0,t.files=n.files.written.map(a=>({path:a})),t.content=n.content,t.outputType=n.outputType,t.tokensUsed=n.tokensUsed,await r()}}healMiddleware(){let e=this.healEngine;return async(t,s,r,n)=>{if(this.config.heal.enabled&&s.files.length>0){let a=await e.detectAndHeal(s.files.map(i=>i.path),t.task,s.memoryEntryId);a.attempts>0&&(s.healed=a.healed,s.healAttempts=a.attempts,a.healed&&(s.success=!0))}await n()}}recordMiddleware(){let e=this.memory;return async(t,s,r,n)=>{if(this.config.memory.enabled){let a=await e.recordGeneration({task:t.task,outputType:s.outputType,files:s.files.map(i=>i.path),success:s.success,error:s.error,context:{techStack:r.agentContext?.techStack.languages.map(i=>i.name),frameworks:r.agentContext?.techStack.frameworks.map(i=>i.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 n()}}enhanceMiddleware(){let e=this.enhanceEngine;return async(t,s,r,n)=>{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 i of a.insights)this.log(`Insight: ${i}`)}).catch(()=>{}),await n()}}sendJson(e,t,s){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(s,null,2))}};async function ie(o){return new Promise((e,t)=>{let s="";o.on("data",r=>s+=r),o.on("end",()=>{try{e(s?JSON.parse(s):{})}catch{e({})}}),o.on("error",t)})}var Dt={name:"agentx",version:"0.1.0"},Nt="2024-11-05",_t={tools:{}},Ft=[{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"]}}];async function Jt(o,e){let t=e.cwd||process.cwd();switch(o){case"agentx_generate":{let s=e.task,r=e.type||"auto",n=e.output_dir,a=await b({task:s,outputType:r,outputDir:n,cwd:t,overwrite:!0,dryRun:!1,context7:!0,interactive:!1,maxSteps:5}),i=[];return a.content&&i.push(a.content),a.files.written.length&&i.push(`
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=n.files.errors.length===0,t.files=n.files.written.map(a=>({path:a})),t.content=n.content,t.outputType=n.outputType,t.tokensUsed=n.tokensUsed,await o()}}healMiddleware(){let e=this.healEngine;return async(t,s,o,n)=>{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 n()}}recordMiddleware(){let e=this.memory;return async(t,s,o,n)=>{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:o.agentContext?.techStack.languages.map(r=>r.name),frameworks:o.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 n()}}enhanceMiddleware(){let e=this.enhanceEngine;return async(t,s,o,n)=>{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 n()}}sendJson(e,t,s){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(s,null,2))}};async function ce(i){return new Promise((e,t)=>{let s="";i.on("data",o=>s+=o),i.on("end",()=>{try{e(s?JSON.parse(s):{})}catch{e({})}}),i.on("error",t)})}var Ft={name:"agentx",version:"0.1.0"},Jt="2024-11-05",Ut={tools:{},elicitation:{form:{}}},Ht=0;async function we(i,e){let t=++Ht;return P({jsonrpc:"2.0",id:`elicit-${t}`,method:"elicitation/create",params:{mode:"form",message:i,requestedSchema:e}}),new Promise(s=>{D.set(`elicit-${t}`,o=>{o?.action==="accept"&&o.content?s(o.content):s(null)}),setTimeout(()=>{D.has(`elicit-${t}`)&&(D.delete(`elicit-${t}`),s(null))},6e4)})}var D=new Map,k=process.env.AGENTX_DAEMON_URL||"http://localhost:19900",Kt=[{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.'}}}}];async function Wt(i,e){let t=e.cwd||process.cwd();switch(i){case"agentx_generate":{let s=e.task,o=e.type||"auto",n=e.output_dir,a=await $({task:s,outputType:o,outputDir:n,cwd:t,overwrite:!0,dryRun:!1,context7:!0,interactive:!1,maxSteps:5}),r=[];return a.content&&r.push(a.content),a.files.written.length&&r.push(`
43
43
  Created ${a.files.written.length} file(s):
44
44
  ${a.files.written.map(c=>` - ${c}`).join(`
45
- `)}`),a.files.skipped.length&&i.push(`
45
+ `)}`),a.files.skipped.length&&r.push(`
46
46
  Skipped ${a.files.skipped.length} existing file(s):
47
47
  ${a.files.skipped.map(c=>` - ${c}`).join(`
48
- `)}`),a.followUp&&i.push(`
49
- Needs clarification: ${a.followUp}`),{content:[{type:"text",text:i.join(`
50
- `)||"Generation complete."}]}}case"agentx_inspect":{let s=await T(t,"inspect",{context7:{enabled:!1}}),r={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(n=>n.path)||[]},skills:s.skills.map(n=>({name:n.frontmatter.name,description:n.frontmatter.description,source:n.source}))};return{content:[{type:"text",text:`Project analysis:
48
+ `)}`),a.followUp&&r.push(`
49
+ Needs clarification: ${a.followUp}`),{content:[{type:"text",text:r.join(`
50
+ `)||"Generation complete."}]}}case"agentx_inspect":{let s=await M(t,"inspect",{context7:{enabled:!1}}),o={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(n=>n.path)||[]},skills:s.skills.map(n=>({name:n.frontmatter.name,description:n.frontmatter.description,source:n.source}))};return{content:[{type:"text",text:`Project analysis:
51
51
 
52
- ${x(s.techStack)}
52
+ ${b(s.techStack)}
53
53
 
54
- ${JSON.stringify(r,null,2)}`}]}}case"agentx_skill_match":{let s=e.task,r=await Z(t),n=ee(r,s);return n.length?{content:[{type:"text",text:`Matching skills:
54
+ ${JSON.stringify(o,null,2)}`}]}}case"agentx_skill_match":{let s=e.task,o=await te(t),n=se(o,s);return n.length?{content:[{type:"text",text:`Matching skills:
55
55
 
56
- ${n.map(i=>`- **${i.skill.frontmatter.name}** (relevance: ${(i.relevance*100).toFixed(0)}%)
57
- ${i.skill.frontmatter.description}
58
- Match: ${i.matchReason}`).join(`
56
+ ${n.map(r=>`- **${r.skill.frontmatter.name}** (relevance: ${(r.relevance*100).toFixed(0)}%)
57
+ ${r.skill.frontmatter.description}
58
+ Match: ${r.matchReason}`).join(`
59
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: ${te(void 0,s)}`}]}}default:throw new Error(`Unknown tool: ${o}`)}}async function Ut(){let o=(...t)=>console.error("[agentx-mcp]",...t);o("Starting MCP server (stdio transport)...");let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{for(e+=t;;){let s=e.indexOf(`\r
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: ${ne(void 0,s)}`}]}}case"agentx_send":{let s=e.channel,o=e.chatId,n=e.text;if(!s||!o||!n){let c=await fetch(`${k}/channels`).catch(()=>null),l=c?await c.json():["telegram","whatsapp","gitlab","discord"],d=await we("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:o||""},text:{type:"string",title:"Message",description:"Message text to send",default:n||""}},required:["channel","chatId","text"]});if(!d)return{content:[{type:"text",text:"Send cancelled."}]};s=d.channel,o=d.chatId,n=d.text}let a=await fetch(`${k}/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:s,chatId:o,text:n,agentId:e.agentId})}),r=await a.json();return a.ok?{content:[{type:"text",text:`Message sent. ID: ${r.messageId||"ok"}`}]}:{content:[{type:"text",text:`Error: ${r.error||a.statusText}`}]}}case"agentx_task":{let s=e.agent,o=e.message;if(!s||!o){let r=await fetch(`${k}/agents`).catch(()=>null),c=r?(await r.json()).map(d=>d.id):[],l=await we("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:o||""}},required:["agent","message"]});if(!l)return{content:[{type:"text",text:"Task cancelled."}]};s=l.agent,o=l.message}let a=await(await fetch(`${k}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:s,message:o})})).json();return a.error?{content:[{type:"text",text:`Agent error: ${a.error}`}]}:{content:[{type:"text",text:a.content||"Task completed."}]}}case"agentx_agents":return{content:[{type:"text",text:(await(await fetch(`${k}/agents`)).json()).map(a=>`${a.id} (${a.name}) \u2014 ${a.tier}, active: ${a.active}/${a.total}, errors: ${a.errors}`).join(`
61
+ `)||"No agents."}]};case"agentx_health":{let o=await(await fetch(`${k}/health`)).json();return{content:[{type:"text",text:JSON.stringify(o,null,2)}]}}case"agentx_crons":{let o=await(await fetch(`${k}/crons/health`)).json(),n=`Healthy: ${o.healthy}, Failing: ${o.failing}, Disabled: ${o.disabled}, Missed: ${o.missed}`,a=(o.jobs||[]).map(r=>` ${r.id}: ${r.status}${r.consecutiveErrors?` (${r.consecutiveErrors} errors)`:""}${r.lastError?` \u2014 ${r.lastError.slice(0,100)}`:""}`).join(`
62
+ `);return{content:[{type:"text",text:`${n}
63
+
64
+ ${a}`}]}}case"agentx_debug":{let s=e.action||"status";if(s==="on"){let o=e.categories||"all";return await fetch(`${k}/debug/on?categories=${o}`,{method:"POST"}),{content:[{type:"text",text:`Debug enabled: ${o}`}]}}else{if(s==="off")return await fetch(`${k}/debug/off`,{method:"POST"}),{content:[{type:"text",text:"Debug disabled."}]};{let n=await(await fetch(`${k}/debug`)).json();return{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}}}default:throw new Error(`Unknown tool: ${i}`)}}async function Bt(){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;;){let s=e.indexOf(`\r
61
65
  \r
62
- `);if(s===-1)break;let n=e.slice(0,s).match(/Content-Length:\s*(\d+)/);if(!n){let g=e.indexOf(`
63
- `);if(g===-1)break;let f=e.slice(0,g).trim();if(e=e.slice(g+1),f)try{let y=JSON.parse(f);ye(y,o).catch($=>o("Error:",$))}catch{}continue}let a=parseInt(n[1],10),i=s+4,c=i+a;if(e.length<c)break;let l=e.slice(i,c);e=e.slice(c);try{let g=JSON.parse(l);ye(g,o).catch(f=>o("Error:",f))}catch(g){o("Failed to parse message:",g)}}}),process.stdin.on("end",()=>{o("stdin closed, shutting down."),process.exit(0)})}function E(o){let e=JSON.stringify(o),t=`Content-Length: ${Buffer.byteLength(e)}\r
66
+ `);if(s===-1)break;let n=e.slice(0,s).match(/Content-Length:\s*(\d+)/);if(!n){let d=e.indexOf(`
67
+ `);if(d===-1)break;let u=e.slice(0,d).trim();if(e=e.slice(d+1),u)try{let y=JSON.parse(u);Se(y,i).catch(R=>i("Error:",R))}catch{}continue}let a=parseInt(n[1],10),r=s+4,c=r+a;if(e.length<c)break;let l=e.slice(r,c);e=e.slice(c);try{let d=JSON.parse(l);if(d.id&&typeof d.id=="string"&&d.id.startsWith("elicit-")&&d.result){let u=D.get(d.id);u&&(D.delete(d.id),u(d.result))}else Se(d,i).catch(u=>i("Error:",u))}catch(d){i("Failed to parse message:",d)}}}),process.stdin.on("end",()=>{i("stdin closed, shutting down."),process.exit(0)})}function P(i){let e=JSON.stringify(i),t=`Content-Length: ${Buffer.byteLength(e)}\r
64
68
  \r
65
- `;process.stdout.write(t+e)}async function ye(o,e){let{method:t,id:s,params:r}=o;switch(e(`Received: ${t}`),t){case"initialize":{E({jsonrpc:"2.0",id:s,result:{protocolVersion:Nt,capabilities:_t,serverInfo:Dt}});break}case"notifications/initialized":{e("Client initialized.");break}case"tools/list":{E({jsonrpc:"2.0",id:s,result:{tools:Ft}});break}case"tools/call":{let n=r?.name,a=r?.arguments||{};try{let i=await Jt(n,a);E({jsonrpc:"2.0",id:s,result:i})}catch(i){E({jsonrpc:"2.0",id:s,result:{content:[{type:"text",text:`Error: ${i.message}`}],isError:!0}})}break}case"ping":{E({jsonrpc:"2.0",id:s,result:{}});break}default:s!==void 0&&E({jsonrpc:"2.0",id:s,error:{code:-32601,message:`Method not found: ${t}`}})}}import{execa as h}from"execa";var w=class{constructor(e){this.cwd=e}async isRepo(){try{return await h("git",["rev-parse","--is-inside-work-tree"],{cwd:this.cwd,reject:!1}),!0}catch{return!1}}async status(){let t=(await h("git",["status","--porcelain","-b"],{cwd:this.cwd,reject:!1})).stdout.trim().split(`
66
- `).filter(Boolean),s="unknown",r=[],n=[],a=[],i=[];for(let c of t){if(c.startsWith("## ")){s=c.slice(3).split("...")[0];continue}let l=c[0],g=c[1],f=c.slice(3).trim();(l==="A"||l==="M"||l==="R")&&r.push(f),l==="D"&&(i.push(f),r.push(f)),g==="M"&&n.push(f),g==="D"&&i.push(f),l==="?"&&g==="?"&&a.push(f)}return{staged:r,modified:n,untracked:a,deleted:[...new Set(i)],branch:s,isClean:r.length===0&&n.length===0&&a.length===0}}async diff(e=!1){return(await h("git",e?["diff","--cached"]:["diff"],{cwd:this.cwd,reject:!1})).stdout}async diffStat(e=!1){let s=await h("git",e?["diff","--cached","--numstat"]:["diff","--numstat"],{cwd:this.cwd,reject:!1}),r=[];for(let n of s.stdout.trim().split(`
67
- `).filter(Boolean)){let[a,i,c]=n.split(" ");if(!c)continue;let l="modified";a==="-"&&i==="-"&&(l="renamed"),r.push({path:c,status:l,additions:parseInt(a)||0,deletions:parseInt(i)||0})}return r}async log(e=10){let t=await h("git",["log",`--max-count=${e}`,"--format=%H|%h|%s|%an|%ai"],{cwd:this.cwd,reject:!1});return t.stdout.trim()?t.stdout.trim().split(`
68
- `).filter(Boolean).map(s=>{let[r,n,a,i,c]=s.split("|");return{hash:r,shortHash:n,message:a,author:i,date:c}}):[]}async add(e){e.length&&await h("git",["add",...e],{cwd:this.cwd})}async addAll(){await h("git",["add","-A"],{cwd:this.cwd})}async commit(e){let t=await h("git",["commit","-m",e],{cwd:this.cwd,reject:!1});if(t.exitCode!==0)throw new Error(t.stderr||t.stdout||"Git commit failed");let r=t.stdout.match(/\[[\w/.-]+\s+(\w+)\]/)?.[1]||"unknown",n=t.stdout.match(/(\d+)\s+files?\s+changed/),a=parseInt(n?.[1]||"0");return{hash:r,message:e,filesChanged:a}}async currentBranch(){return(await h("git",["branch","--show-current"],{cwd:this.cwd,reject:!1})).stdout.trim()}async createBranch(e){await h("git",["checkout","-b",e],{cwd:this.cwd})}async checkout(e){await h("git",["checkout",e],{cwd:this.cwd})}async stash(e){let t=["stash","push"];e&&t.push("-m",e),await h("git",t,{cwd:this.cwd})}async stashPop(){await h("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.
69
+ `;process.stdout.write(t+e)}async function Se(i,e){let{method:t,id:s,params:o}=i;switch(e(`Received: ${t}`),t){case"initialize":{P({jsonrpc:"2.0",id:s,result:{protocolVersion:Jt,capabilities:Ut,serverInfo:Ft}});break}case"notifications/initialized":{e("Client initialized.");break}case"tools/list":{P({jsonrpc:"2.0",id:s,result:{tools:Kt}});break}case"tools/call":{let n=o?.name,a=o?.arguments||{};try{let r=await Wt(n,a);P({jsonrpc:"2.0",id:s,result:r})}catch(r){P({jsonrpc:"2.0",id:s,result:{content:[{type:"text",text:`Error: ${r.message}`}],isError:!0}})}break}case"ping":{P({jsonrpc:"2.0",id:s,result:{}});break}default:s!==void 0&&P({jsonrpc:"2.0",id:s,error:{code:-32601,message:`Method not found: ${t}`}})}}import{execa as f}from"execa";var S=class{constructor(e){this.cwd=e}async isRepo(){try{return await f("git",["rev-parse","--is-inside-work-tree"],{cwd:this.cwd,reject:!1}),!0}catch{return!1}}async status(){let t=(await f("git",["status","--porcelain","-b"],{cwd:this.cwd,reject:!1})).stdout.trim().split(`
70
+ `).filter(Boolean),s="unknown",o=[],n=[],a=[],r=[];for(let c of t){if(c.startsWith("## ")){s=c.slice(3).split("...")[0];continue}let l=c[0],d=c[1],u=c.slice(3).trim();(l==="A"||l==="M"||l==="R")&&o.push(u),l==="D"&&(r.push(u),o.push(u)),d==="M"&&n.push(u),d==="D"&&r.push(u),l==="?"&&d==="?"&&a.push(u)}return{staged:o,modified:n,untracked:a,deleted:[...new Set(r)],branch:s,isClean:o.length===0&&n.length===0&&a.length===0}}async diff(e=!1){return(await f("git",e?["diff","--cached"]:["diff"],{cwd:this.cwd,reject:!1})).stdout}async diffStat(e=!1){let s=await f("git",e?["diff","--cached","--numstat"]:["diff","--numstat"],{cwd:this.cwd,reject:!1}),o=[];for(let n of s.stdout.trim().split(`
71
+ `).filter(Boolean)){let[a,r,c]=n.split(" ");if(!c)continue;let l="modified";a==="-"&&r==="-"&&(l="renamed"),o.push({path:c,status:l,additions:parseInt(a)||0,deletions:parseInt(r)||0})}return o}async log(e=10){let t=await f("git",["log",`--max-count=${e}`,"--format=%H|%h|%s|%an|%ai"],{cwd:this.cwd,reject:!1});return t.stdout.trim()?t.stdout.trim().split(`
72
+ `).filter(Boolean).map(s=>{let[o,n,a,r,c]=s.split("|");return{hash:o,shortHash:n,message:a,author:r,date:c}}):[]}async add(e){e.length&&await f("git",["add",...e],{cwd:this.cwd})}async addAll(){await f("git",["add","-A"],{cwd:this.cwd})}async commit(e){let t=await f("git",["commit","-m",e],{cwd:this.cwd,reject:!1});if(t.exitCode!==0)throw new Error(t.stderr||t.stdout||"Git commit failed");let o=t.stdout.match(/\[[\w/.-]+\s+(\w+)\]/)?.[1]||"unknown",n=t.stdout.match(/(\d+)\s+files?\s+changed/),a=parseInt(n?.[1]||"0");return{hash:o,message:e,filesChanged:a}}async currentBranch(){return(await f("git",["branch","--show-current"],{cwd:this.cwd,reject:!1})).stdout.trim()}async createBranch(e){await f("git",["checkout","-b",e],{cwd:this.cwd})}async checkout(e){await f("git",["checkout",e],{cwd:this.cwd})}async stash(e){let t=["stash","push"];e&&t.push("-m",e),await f("git",t,{cwd:this.cwd})}async stashPop(){await f("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.
69
73
  Rules:
70
74
  - Use conventional commit format: feat|fix|refactor|docs|test|chore|style(scope): message
71
75
  - Keep the subject line under 72 characters
@@ -74,13 +78,13 @@ Rules:
74
78
 
75
79
  ${t.slice(0,4e3)}`}])).content.trim().split(`
76
80
  `)[0]:this.fallbackCommitMessage(t)}fallbackCommitMessage(e){let t=e.split(`
77
- `),s=[];for(let r of t)if(r.startsWith("diff --git")){let n=r.match(/b\/(.+)$/);n&&s.push(n[1])}return s.length===0?"chore: update files":s.length===1?`chore: update ${s[0]}`:`chore: update ${s.length} files`}};import{createInterface as Yt}from"readline";import v from"chalk";import Xt from"ora";import{existsSync as ke,mkdirSync as Ht,readFileSync as ae,readdirSync as we,writeFileSync as Kt}from"fs";import L from"path";import Bt from"os";var S=L.join(Bt.homedir(),".agentx","sessions");function ce(){ke(S)||Ht(S,{recursive:!0})}function O(o){return{id:Wt(),createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),cwd:o,messages:[],tokensUsed:0,filesGenerated:[]}}function I(o){ce();let e=L.join(S,`${o.id}.json`);o.updatedAt=new Date().toISOString(),Kt(e,JSON.stringify(o,null,2),"utf8")}function P(o){let e=L.join(S,`${o}.json`);if(!ke(e))return null;try{return JSON.parse(ae(e,"utf8"))}catch{return null}}function B(){ce();let o=we(S).filter(t=>t.endsWith(".json")).map(t=>({name:t,path:L.join(S,t)}));if(!o.length)return null;let e=null;for(let t of o)try{let s=JSON.parse(ae(t.path,"utf8"));(!e||s.updatedAt>e.session.updatedAt)&&(e={name:t.name,session:s})}catch{}return e?.session??null}function W(){ce();let o=we(S).filter(t=>t.endsWith(".json")),e=[];for(let t of o)try{let s=JSON.parse(ae(L.join(S,t),"utf8"));e.push(s)}catch{}return e.sort((t,s)=>s.updatedAt.localeCompare(t.updatedAt)),e}function Wt(){return Math.random().toString(36).slice(2,10)+Date.now().toString(36).slice(-4)}import p from"chalk";import{writeFileSync as qt}from"fs";import zt from"path";import d from"chalk";function Se(o,e){console.log(),console.log(d.bold.cyan(" agentx")+d.dim(` v${o}`)),console.log(d.dim(` Session: ${e}`)),console.log(d.dim(" Type /help for commands, /quit to exit")),console.log()}function ve(o){if(o.written.length){console.log(),console.log(d.green(` Created ${o.written.length} file(s):`));for(let e of o.written)console.log(` ${d.green("+")} ${e}`)}if(o.skipped.length){console.log(),console.log(d.yellow(` Skipped ${o.skipped.length} file(s):`));for(let e of o.skipped)console.log(` ${d.yellow("~")} ${e}`)}if(o.errors.length){console.log(),console.log(d.red(` Failed ${o.errors.length} file(s):`));for(let e of o.errors)console.log(` ${d.red("x")} ${e}`)}}function D(o){let e=o/1e6*9;console.log(),console.log(d.dim(` Tokens: ${o.toLocaleString()} | Est. cost: $${e.toFixed(4)}`))}function xe(o){process.stdout.write(o)}function be(){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 Ce(o){if(console.log(),console.log(d.dim(` Branch: ${o.branch}`)),o.isClean){console.log(d.green(" Working tree clean"));return}o.staged.length&&console.log(d.green(` Staged: ${o.staged.length}`)),o.modified.length&&console.log(d.yellow(` Modified: ${o.modified.length}`)),o.untracked.length&&console.log(d.dim(` Untracked: ${o.untracked.length}`)),console.log()}function Pe(o){if(console.log(),console.log(d.bold(" Cost Breakdown")),console.log(),console.log(d.dim(` Total: ${o.totalTokens.toLocaleString()} tokens ($${o.totalCost.toFixed(4)})`)),console.log(d.dim(` Input: ${o.totalInputTokens.toLocaleString()} | Output: ${o.totalOutputTokens.toLocaleString()}`)),Object.keys(o.models).length){console.log(),console.log(d.dim(" Per model:"));for(let[e,t]of Object.entries(o.models))console.log(` ${d.cyan(e)}: ${(t.inputTokens+t.outputTokens).toLocaleString()} tokens, $${t.cost.toFixed(4)} (${t.steps} step${t.steps!==1?"s":""})`)}if(o.steps.length>1){console.log(),console.log(d.dim(" Per step:"));for(let e of o.steps)console.log(` Step ${e.step}: ${(e.inputTokens+e.outputTokens).toLocaleString()} tokens ($${e.cost.toFixed(4)})`)}console.log()}function $e(o){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 o){let t=e.action==="create"?d.green("+"):d.yellow("~");console.log(` ${t} ${e.path} (${e.action})`)}console.log()}import Vt from"prompts";var Re={};function u(o,e){Re[o]=e}function q(o){return Re[o]}function z(o){return o.startsWith("/")}function V(o){let e=o.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()=>(be(),!0));u("quit",async()=>!1);u("exit",async()=>!1);u("q",async()=>!1);u("clear",async(o,e)=>(e.session.messages=[],console.log(p.dim(" Conversation cleared")),!0));u("save",async(o,e)=>(I(e.session),console.log(p.dim(` Session saved: ${e.session.id}`)),!0));u("load",async(o,e)=>{let t=null;if(o){if(t=P(o),!t)return m.warn(`Session not found: ${o}`),!0}else{let s=W();if(!s.length)return m.info("No saved sessions"),!0;let{sessionId:r}=await Vt({type:"select",name:"sessionId",message:"Select a session",choices:s.slice(0,10).map(n=>({title:`${n.id} \u2014 ${new Date(n.updatedAt).toLocaleDateString()} (${n.messages.length} messages)`,value:n.id}))});if(!r)return!0;t=P(r)}return t&&(e.onSessionChange(t),console.log(p.dim(` Loaded session: ${t.id} (${t.messages.length} messages)`))),!0});u("undo",async(o,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)});u("cost",async(o,e)=>{let t=F.getSummary();return t.steps.length>0?Pe(t):D(e.session.tokensUsed),!0});u("export",async(o,e)=>{let t=F.getSummary(),s=se(e.session,t.steps.length?t:void 0),r=o||`session-${e.session.id}.md`,n=zt.resolve(e.cwd,r);return qt(n,s,"utf8"),m.success(` Session exported to ${n}`),!0});u("files",async(o,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});u("context",async(o,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));u("memory",async(o,e)=>{try{let t=new ne(e.cwd);await t.load();let s=t.getStats(),r=t.getPreferences(),n=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)}%`)),r.length){console.log(),console.log(p.dim(" Preferences:"));for(let i of r.slice(0,10))console.log(p.dim(` ${i.key}: ${i.value} (${(i.confidence*100).toFixed(0)}%)`))}if(n.length){console.log(),console.log(p.dim(" Patterns:"));for(let i of n.slice(0,5))console.log(p.dim(` ${i.description} (${i.frequency}x)`))}if(a.length){console.log(),console.log(p.dim(" Recent:"));for(let i of a){let c=i.success?p.green("ok"):p.red("fail");console.log(p.dim(` [${c}] ${i.task.slice(0,60)}`))}}console.log()}catch(t){m.error(` ${t.message}`)}return!0});u("mode",async(o,e)=>{if(o&&J.includes(o))R.setMode(o),m.success(` Permission mode: ${o}`);else if(o)m.warn(` Unknown mode: ${o}. Valid modes: ${J.join(", ")}`);else{let t=R.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});u("commit",async(o,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(i=>i);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 n;try{let i=G();n=await t.generateCommitMessage(i)}catch{n=await t.generateCommitMessage()}console.log(p.dim(` Message: ${n}`));let a=await t.commit(n);m.success(` [${a.hash}] ${a.message}`)}catch(t){m.error(` ${t.message}`)}return!0});u("diff",async(o,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});u("status",async(o,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();Ce(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=P(e.sessionId);t?this.session=t:(m.warn(`Session ${e.sessionId} not found, starting new session`),this.session=O(e.cwd))}else if(e.resume){let t=B();t?(this.session=t,m.info(`Resumed session: ${t.id}`)):(m.info("No previous session found, starting new session"),this.session=O(e.cwd))}else this.session=O(e.cwd)}async start(){this.running=!0,Se(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=Yt({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(z(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,I(this.session),console.log(),console.log(v.dim(` Session saved: ${this.session.id}`)),D(this.session.tokensUsed),console.log(),this.rl?.close(),process.exit(0)}async handleCommand(e){let{name:t,args:s}=V(e),r=q(t);if(!r)return m.warn(` Unknown command: /${t}. Type /help for available commands.`),!0;let n={session:this.session,cwd:this.options.cwd,onSessionChange:a=>{this.session=a}};return r(s,n)}async handleGeneration(e){let t=Xt({text:"Thinking...",color:"cyan"}).start();try{let s=this.session.messages.filter(i=>i.role!=="system").map(i=>({role:i.role,content:i.content})),r={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},n,a=!1;for await(let i of j(r)){if(i.type==="context_ready"){t.stop(),console.log(),a=!0;continue}if(i.type==="text_delta"){xe(i.text);continue}if(i.type==="done"){console.log();continue}if(i.type==="error")throw new Error(i.error);if(i.type==="step_complete"){i.step>1&&console.log(v.dim(` Step ${i.step}: ${i.filesCount} file(s)`));continue}i.type==="generate_result"&&(n=i.result)}if(a||t.stop(),!n)return;(n.files.written.length||n.files.skipped.length||n.files.errors.length)&&(R.getMode()==="plan"?$e(n.files.written.map(i=>({path:i,action:"create"}))):ve(n.files)),n.tokensUsed&&D(n.tokensUsed),this.session.messages.push({role:"user",content:e}),this.session.messages.push({role:"assistant",content:n.content||""}),this.session.tokensUsed+=n.tokensUsed||0,this.session.filesGenerated.push(...n.files.written),n.followUp&&(console.log(),console.log(v.yellow(` ${n.followUp}`))),n.healResult&&(console.log(),n.healResult.healed?console.log(v.green(` Heal: passed verification${n.healResult.attempts>0?` (fixed in ${n.healResult.attempts} attempt(s))`:""}`)):n.healResult.error&&(console.log(v.red(` Heal: verification failed after ${n.healResult.attempts} attempt(s)`)),console.log(v.dim(` ${n.healResult.error.split(`
78
- `)[0]}`))))}catch(s){throw t.stop(),s}}};import{createServer as Qt}from"http";var k={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},X=class{config;tasks=new Map;activeCancellations=new Set;log;constructor(e){this.config={...Zt,...e},this.log=console.error.bind(console,"[a2a]")}async start(){Qt(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(`
79
- 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"}`),r=e.method||"GET",n=s.pathname;this.log(`${r} ${n}`);try{if(r==="GET"&&n==="/.well-known/agent-card.json"){this.sendJson(t,200,this.getAgentCard());return}if(r==="POST"&&n==="/"){let a=await es(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:k.PARSE_ERROR});return}let s=e,r=s.params||{};switch(s.method){case"tasks/send":await this.handleTaskSend(s.id,r,t);break;case"tasks/sendSubscribe":await this.handleTaskSendSubscribe(s.id,r,t);break;case"tasks/get":this.handleTaskGet(s.id,r,t);break;case"tasks/cancel":this.handleTaskCancel(s.id,r,t);break;default:this.sendJsonRpc(t,{jsonrpc:"2.0",id:s.id,error:k.METHOD_NOT_FOUND})}}async handleTaskSend(e,t,s){let r=String(t.id||`task-${Date.now().toString(36)}`),n=t.message;if(!n?.parts?.length){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:{...k.INVALID_PARAMS,data:"message with parts is required"}});return}let i=n.parts.filter(l=>l.type==="text").map(l=>l.text).join(`
80
- `);if(!i){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:{...k.INVALID_PARAMS,data:"No text content in message parts"}});return}let c={id:r,state:"submitted",messages:[{role:"user",parts:n.parts}],artifacts:[],metadata:t.metadata,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};this.tasks.set(r,c),c.state="working",c.updatedAt=new Date().toISOString();try{let l=await b({task:i,cwd:this.config.cwd,provider:this.config.provider,model:this.config.model,apiKey:this.config.apiKey,overwrite:!0,interactive:!1,context7:!0}),g=l.files.written.map((y,$)=>({name:y,description:"Generated file",parts:[{type:"text",text:y}],index:$})),f={role:"agent",parts:[{type:"text",text:l.content||"Generation complete."}]};l.followUp?(c.state="input-required",f.parts.push({type:"text",text:`
81
+ `),s=[];for(let o of t)if(o.startsWith("diff --git")){let n=o.match(/b\/(.+)$/);n&&s.push(n[1])}return s.length===0?"chore: update files":s.length===1?`chore: update ${s[0]}`:`chore: update ${s.length} files`}};import{createInterface as es}from"readline";import v from"chalk";import ts from"ora";import{existsSync as xe,mkdirSync as qt,readFileSync as le,readdirSync as ve,writeFileSync as zt}from"fs";import L from"path";import Vt from"os";var x=L.join(Vt.homedir(),".agentx","sessions");function de(){xe(x)||qt(x,{recursive:!0})}function E(i){return{id:Yt(),createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),cwd:i,messages:[],tokensUsed:0,filesGenerated:[]}}function j(i){de();let e=L.join(x,`${i.id}.json`);i.updatedAt=new Date().toISOString(),zt(e,JSON.stringify(i,null,2),"utf8")}function T(i){let e=L.join(x,`${i}.json`);if(!xe(e))return null;try{return JSON.parse(le(e,"utf8"))}catch{return null}}function q(){de();let i=ve(x).filter(t=>t.endsWith(".json")).map(t=>({name:t,path:L.join(x,t)}));if(!i.length)return null;let e=null;for(let t of i)try{let s=JSON.parse(le(t.path,"utf8"));(!e||s.updatedAt>e.session.updatedAt)&&(e={name:t.name,session:s})}catch{}return e?.session??null}function z(){de();let i=ve(x).filter(t=>t.endsWith(".json")),e=[];for(let t of i)try{let s=JSON.parse(le(L.join(x,t),"utf8"));e.push(s)}catch{}return e.sort((t,s)=>s.updatedAt.localeCompare(t.updatedAt)),e}function Yt(){return Math.random().toString(36).slice(2,10)+Date.now().toString(36).slice(-4)}import g from"chalk";import{writeFileSync as Xt}from"fs";import Qt from"path";import p from"chalk";function be(i,e){console.log(),console.log(p.bold.cyan(" agentx")+p.dim(` v${i}`)),console.log(p.dim(` Session: ${e}`)),console.log(p.dim(" Type /help for commands, /quit to exit")),console.log()}function $e(i){if(i.written.length){console.log(),console.log(p.green(` Created ${i.written.length} file(s):`));for(let e of i.written)console.log(` ${p.green("+")} ${e}`)}if(i.skipped.length){console.log(),console.log(p.yellow(` Skipped ${i.skipped.length} file(s):`));for(let e of i.skipped)console.log(` ${p.yellow("~")} ${e}`)}if(i.errors.length){console.log(),console.log(p.red(` Failed ${i.errors.length} file(s):`));for(let e of i.errors)console.log(` ${p.red("x")} ${e}`)}}function N(i){let e=i/1e6*9;console.log(),console.log(p.dim(` Tokens: ${i.toLocaleString()} | Est. cost: $${e.toFixed(4)}`))}function Ce(i){process.stdout.write(i)}function Pe(){console.log(),console.log(p.bold(" Commands:")),console.log(),console.log(` ${p.cyan("/help")} Show this help`),console.log(` ${p.cyan("/clear")} Clear conversation history`),console.log(` ${p.cyan("/save")} Save current session`),console.log(` ${p.cyan("/load")} Load a saved session`),console.log(` ${p.cyan("/undo")} Undo last generation`),console.log(` ${p.cyan("/cost")} Show token usage and cost breakdown`),console.log(` ${p.cyan("/export")} Export session as markdown`),console.log(` ${p.cyan("/files")} List generated files`),console.log(` ${p.cyan("/context")} Show session context info`),console.log(` ${p.cyan("/memory")} Show memory stats and preferences`),console.log(` ${p.cyan("/mode")} Switch permission mode`),console.log(` ${p.cyan("/commit")} Commit generated files with AI message`),console.log(` ${p.cyan("/diff")} Show git diff`),console.log(` ${p.cyan("/status")} Show git status`),console.log(` ${p.cyan("/quit")} Exit the REPL`),console.log()}function Te(i){if(console.log(),console.log(p.dim(` Branch: ${i.branch}`)),i.isClean){console.log(p.green(" Working tree clean"));return}i.staged.length&&console.log(p.green(` Staged: ${i.staged.length}`)),i.modified.length&&console.log(p.yellow(` Modified: ${i.modified.length}`)),i.untracked.length&&console.log(p.dim(` Untracked: ${i.untracked.length}`)),console.log()}function Re(i){if(console.log(),console.log(p.bold(" Cost Breakdown")),console.log(),console.log(p.dim(` Total: ${i.totalTokens.toLocaleString()} tokens ($${i.totalCost.toFixed(4)})`)),console.log(p.dim(` Input: ${i.totalInputTokens.toLocaleString()} | Output: ${i.totalOutputTokens.toLocaleString()}`)),Object.keys(i.models).length){console.log(),console.log(p.dim(" Per model:"));for(let[e,t]of Object.entries(i.models))console.log(` ${p.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(p.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 Ae(i){console.log(),console.log(p.bold(" Plan Preview")),console.log(p.dim(" No files will be written in plan mode.")),console.log();for(let e of i){let t=e.action==="create"?p.green("+"):p.yellow("~");console.log(` ${t} ${e.path} (${e.action})`)}console.log()}import Zt from"prompts";var Me={};function h(i,e){Me[i]=e}function V(i){return Me[i]}function Y(i){return i.startsWith("/")}function X(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()}}h("help",async()=>(Pe(),!0));h("quit",async()=>!1);h("exit",async()=>!1);h("q",async()=>!1);h("clear",async(i,e)=>(e.session.messages=[],console.log(g.dim(" Conversation cleared")),!0));h("save",async(i,e)=>(j(e.session),console.log(g.dim(` Session saved: ${e.session.id}`)),!0));h("load",async(i,e)=>{let t=null;if(i){if(t=T(i),!t)return m.warn(`Session not found: ${i}`),!0}else{let s=z();if(!s.length)return m.info("No saved sessions"),!0;let{sessionId:o}=await Zt({type:"select",name:"sessionId",message:"Select a session",choices:s.slice(0,10).map(n=>({title:`${n.id} \u2014 ${new Date(n.updatedAt).toLocaleDateString()} (${n.messages.length} messages)`,value:n.id}))});if(!o)return!0;t=T(o)}return t&&(e.onSessionChange(t),console.log(g.dim(` Loaded session: ${t.id} (${t.messages.length} messages)`))),!0});h("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)});h("cost",async(i,e)=>{let t=U.getSummary();return t.steps.length>0?Re(t):N(e.session.tokensUsed),!0});h("export",async(i,e)=>{let t=U.getSummary(),s=oe(e.session,t.steps.length?t:void 0),o=i||`session-${e.session.id}.md`,n=Qt.resolve(e.cwd,o);return Xt(n,s,"utf8"),m.success(` Session exported to ${n}`),!0});h("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});h("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));h("memory",async(i,e)=>{try{let t=new ie(e.cwd);await t.load();let s=t.getStats(),o=t.getPreferences(),n=t.getPatterns(),a=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)}%`)),o.length){console.log(),console.log(g.dim(" Preferences:"));for(let r of o.slice(0,10))console.log(g.dim(` ${r.key}: ${r.value} (${(r.confidence*100).toFixed(0)}%)`))}if(n.length){console.log(),console.log(g.dim(" Patterns:"));for(let r of n.slice(0,5))console.log(g.dim(` ${r.description} (${r.frequency}x)`))}if(a.length){console.log(),console.log(g.dim(" Recent:"));for(let r of a){let c=r.success?g.green("ok"):g.red("fail");console.log(g.dim(` [${c}] ${r.task.slice(0,60)}`))}}console.log()}catch(t){m.error(` ${t.message}`)}return!0});h("mode",async(i,e)=>{if(i&&H.includes(i))A.setMode(i),m.success(` Permission mode: ${i}`);else if(i)m.warn(` Unknown mode: ${i}. Valid modes: ${H.join(", ")}`);else{let t=A.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});h("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(r=>r);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 n;try{let r=G();n=await t.generateCommitMessage(r)}catch{n=await t.generateCommitMessage()}console.log(g.dim(` Message: ${n}`));let a=await t.commit(n);m.success(` [${a.hash}] ${a.message}`)}catch(t){m.error(` ${t.message}`)}return!0});h("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});h("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();Te(s)}catch(t){m.error(` ${t.message}`)}return!0});var Q=class{rl=null;session;options;running=!1;constructor(e){if(this.options=e,e.sessionId){let t=T(e.sessionId);t?this.session=t:(m.warn(`Session ${e.sessionId} not found, starting new session`),this.session=E(e.cwd))}else if(e.resume){let t=q();t?(this.session=t,m.info(`Resumed session: ${t.id}`)):(m.info("No previous session found, starting new session"),this.session=E(e.cwd))}else this.session=E(e.cwd)}async start(){this.running=!0,be(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=es({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(Y(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,j(this.session),console.log(),console.log(v.dim(` Session saved: ${this.session.id}`)),N(this.session.tokensUsed),console.log(),this.rl?.close(),process.exit(0)}async handleCommand(e){let{name:t,args:s}=X(e),o=V(t);if(!o)return m.warn(` Unknown command: /${t}. Type /help for available commands.`),!0;let n={session:this.session,cwd:this.options.cwd,onSessionChange:a=>{this.session=a}};return o(s,n)}async handleGeneration(e){let t=ts({text:"Thinking...",color:"cyan"}).start();try{let s=this.session.messages.filter(r=>r.role!=="system").map(r=>({role:r.role,content:r.content})),o={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},n,a=!1;for await(let r of _(o)){if(r.type==="context_ready"){t.stop(),console.log(),a=!0;continue}if(r.type==="text_delta"){Ce(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"&&(n=r.result)}if(a||t.stop(),!n)return;(n.files.written.length||n.files.skipped.length||n.files.errors.length)&&(A.getMode()==="plan"?Ae(n.files.written.map(r=>({path:r,action:"create"}))):$e(n.files)),n.tokensUsed&&N(n.tokensUsed),this.session.messages.push({role:"user",content:e}),this.session.messages.push({role:"assistant",content:n.content||""}),this.session.tokensUsed+=n.tokensUsed||0,this.session.filesGenerated.push(...n.files.written),n.followUp&&(console.log(),console.log(v.yellow(` ${n.followUp}`))),n.healResult&&(console.log(),n.healResult.healed?console.log(v.green(` Heal: passed verification${n.healResult.attempts>0?` (fixed in ${n.healResult.attempts} attempt(s))`:""}`)):n.healResult.error&&(console.log(v.red(` Heal: verification failed after ${n.healResult.attempts} attempt(s)`)),console.log(v.dim(` ${n.healResult.error.split(`
82
+ `)[0]}`))))}catch(s){throw t.stop(),s}}};import{createServer as ss}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 ns={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={...ns,...e},this.log=console.error.bind(console,"[a2a]")}async start(){ss(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(`
83
+ 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"}`),o=e.method||"GET",n=s.pathname;this.log(`${o} ${n}`);try{if(o==="GET"&&n==="/.well-known/agent-card.json"){this.sendJson(t,200,this.getAgentCard());return}if(o==="POST"&&n==="/"){let a=await os(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:w.PARSE_ERROR});return}let s=e,o=s.params||{};switch(s.method){case"tasks/send":await this.handleTaskSend(s.id,o,t);break;case"tasks/sendSubscribe":await this.handleTaskSendSubscribe(s.id,o,t);break;case"tasks/get":this.handleTaskGet(s.id,o,t);break;case"tasks/cancel":this.handleTaskCancel(s.id,o,t);break;default:this.sendJsonRpc(t,{jsonrpc:"2.0",id:s.id,error:w.METHOD_NOT_FOUND})}}async handleTaskSend(e,t,s){let o=String(t.id||`task-${Date.now().toString(36)}`),n=t.message;if(!n?.parts?.length){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:{...w.INVALID_PARAMS,data:"message with parts is required"}});return}let r=n.parts.filter(l=>l.type==="text").map(l=>l.text).join(`
84
+ `);if(!r){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:{...w.INVALID_PARAMS,data:"No text content in message parts"}});return}let c={id:o,state:"submitted",messages:[{role:"user",parts:n.parts}],artifacts:[],metadata:t.metadata,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};this.tasks.set(o,c),c.state="working",c.updatedAt=new Date().toISOString();try{let l=await $({task:r,cwd:this.config.cwd,provider:this.config.provider,model:this.config.model,apiKey:this.config.apiKey,overwrite:!0,interactive:!1,context7:!0}),d=l.files.written.map((y,R)=>({name:y,description:"Generated file",parts:[{type:"text",text:y}],index:R})),u={role:"agent",parts:[{type:"text",text:l.content||"Generation complete."}]};l.followUp?(c.state="input-required",u.parts.push({type:"text",text:`
81
85
 
82
- Question: ${l.followUp}`})):c.state="completed",c.messages.push(f),c.artifacts=g,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 r=String(t.id||`task-${Date.now().toString(36)}`),n=t.message;if(!n?.parts?.length){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:{...k.INVALID_PARAMS,data:"message with parts is required"}});return}let i=n.parts.filter(g=>g.type==="text").map(g=>g.text).join(`
83
- `);if(!i){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:{...k.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:r,state:"submitted",messages:[{role:"user",parts:n.parts}],artifacts:[],metadata:t.metadata,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};this.tasks.set(r,c);let l=g=>{s.write(`data: ${JSON.stringify(g)}
86
+ Question: ${l.followUp}`})):c.state="completed",c.messages.push(u),c.artifacts=d,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 o=String(t.id||`task-${Date.now().toString(36)}`),n=t.message;if(!n?.parts?.length){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:{...w.INVALID_PARAMS,data:"message with parts is required"}});return}let r=n.parts.filter(d=>d.type==="text").map(d=>d.text).join(`
87
+ `);if(!r){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:o,state:"submitted",messages:[{role:"user",parts:n.parts}],artifacts:[],metadata:t.metadata,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};this.tasks.set(o,c);let l=d=>{s.write(`data: ${JSON.stringify(d)}
84
88
 
85
- `)};l({id:r,state:"submitted",final:!1}),c.state="working",c.updatedAt=new Date().toISOString(),l({id:r,state:"working",final:!1});try{let g="",f=[];for await(let y of j({task:i,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(r)){this.activeCancellations.delete(r),c.state="canceled",c.updatedAt=new Date().toISOString(),l({id:r,state:"canceled",final:!0}),s.end();return}if(y.type==="text_delta"&&(g+=y.text,l({id:r,state:"working",message:{role:"agent",parts:[{type:"text",text:y.text}]},final:!1})),y.type==="generate_result"){let $=y.result,le=$.files.written.map((N,Ae)=>({name:N,parts:[{type:"text",text:N}],index:Ae}));f.push(...le);for(let N of le)l({id:r,state:"working",artifact:N,final:!1});$.followUp?c.state="input-required":c.state="completed"}}c.messages.push({role:"agent",parts:[{type:"text",text:g||"Generation complete."}]}),c.artifacts=f,c.updatedAt=new Date().toISOString(),l({id:r,state:c.state,final:!0})}catch(g){c.state="failed",c.messages.push({role:"agent",parts:[{type:"text",text:`Error: ${g.message}`}]}),c.updatedAt=new Date().toISOString(),l({id:r,state:"failed",message:{role:"agent",parts:[{type:"text",text:`Error: ${g.message}`}]},final:!0})}s.end()}handleTaskGet(e,t,s){let r=String(t.id||""),n=this.tasks.get(r);if(!n){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:k.TASK_NOT_FOUND});return}this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,result:n})}handleTaskCancel(e,t,s){let r=String(t.id||""),n=this.tasks.get(r);if(!n){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:k.TASK_NOT_FOUND});return}if(n.state!=="working"&&n.state!=="submitted"){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:k.TASK_NOT_CANCELABLE});return}this.activeCancellations.add(r),n.state="canceled",n.updatedAt=new Date().toISOString(),this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,result:n})}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 es(o){return new Promise((e,t)=>{let s="";o.on("data",r=>s+=r),o.on("end",()=>{try{e(s?JSON.parse(s):{})}catch{e({})}}),o.on("error",t)})}var Te={"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 ts(o,e){let t=Te[o];if(!t)return[`Unknown provider "${o}" \u2014 capabilities unknown`];if(!e?.length)return[];let s=[],r=[];for(let n of e)n in t&&!t[n]&&r.push(n);return r.length&&s.push(`Provider "${o}" lacks: ${r.join(", ")}. Some features will be degraded.`),s}function ss(o){typeof o=="string"&&(m.error(o),process.exit(1)),o instanceof Error&&(m.error(o.message),process.exit(1)),m.error("Something went wrong. Please try again."),process.exit(1)}export{de as A2AClient,pe as A2AMesh,X as A2AServer,Je as ALL_TOOL_NAMES,wt as AgentRegistry,Ct as AgentXDaemon,K as AgentXRuntime,Ye as BLOCKING_EVENTS,He as ClaudeCodeProvider,Ue as ClaudeProvider,lt as ContextBuilder,bt as CronScheduler,A as EnhanceEngine,w as GitManager,Ve as HOOK_EVENTS,H as HealEngine,tt as HookRegistry,U as Memory,ne as MemoryHierarchy,St as MessageRouter,ze as OUTPUT_CONFIGS,Ee as OUTPUT_TYPES,J as PERMISSION_MODES,Te as PROVIDER_CAPABILITIES,it as PermissionManager,M as Pipeline,Y as ReplEngine,vt as TelegramAdapter,dt as ToolExecutor,Xe as UsageTracker,xt as WhatsAppAdapter,kt as WikiStore,Me as agentConfigSchema,ts as checkCapabilities,T as createAgentContext,G as createProvider,O as createSession,pt as daemonConfigSchema,et as debug,Ke as detectSchemas,Q as detectTechStack,De as ensureCredentials,ut as executeClaudeCode,ht as executeOrchestrator,ft as executeSdk,yt as executeTask,se as exportSession,Be as formatSchemas,x as formatTechStack,Fe as formatToolsForSystemPrompt,We as gatherContext7Docs,b as generate,Et as generateSkill,At as generateSkillMd,j as generateStream,Ne as getAnthropicTools,q as getCommand,_e as getLegacyTools,Pt as getPackageInfo,nt as globalHooks,R as globalPermissions,F as globalTracker,ss as handleError,Rt as installSkillPackage,z as isCommand,Ze as isDebug,Mt as listInstalledSkills,W as listSessions,Ie as loadAuthConfig,gt as loadDaemonConfig,st as loadHooks,B as loadLatestSession,Z as loadLocalSkills,ct as loadProjectInstructions,P as loadSession,m as logger,ee as matchSkillsToTask,Oe as outputTypeDescriptions,V as parseCommand,_ as parseSkillContent,qe as parseSkillFile,rt as permissionConfigSchema,ot as permissionModeSchema,u as registerCommand,at as resolveAtImports,te as resolveOutputType,je as resolveToken,Le as runModelSetup,Ge as saveAuthConfig,I as saveSession,Qe as setDebug,Ut as startMcpServer,mt as validateWorkspaces};
89
+ `)};l({id:o,state:"submitted",final:!1}),c.state="working",c.updatedAt=new Date().toISOString(),l({id:o,state:"working",final:!1});try{let d="",u=[];for await(let y of _({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(o)){this.activeCancellations.delete(o),c.state="canceled",c.updatedAt=new Date().toISOString(),l({id:o,state:"canceled",final:!0}),s.end();return}if(y.type==="text_delta"&&(d+=y.text,l({id:o,state:"working",message:{role:"agent",parts:[{type:"text",text:y.text}]},final:!1})),y.type==="generate_result"){let R=y.result,pe=R.files.written.map((F,Oe)=>({name:F,parts:[{type:"text",text:F}],index:Oe}));u.push(...pe);for(let F of pe)l({id:o,state:"working",artifact:F,final:!1});R.followUp?c.state="input-required":c.state="completed"}}c.messages.push({role:"agent",parts:[{type:"text",text:d||"Generation complete."}]}),c.artifacts=u,c.updatedAt=new Date().toISOString(),l({id:o,state:c.state,final:!0})}catch(d){c.state="failed",c.messages.push({role:"agent",parts:[{type:"text",text:`Error: ${d.message}`}]}),c.updatedAt=new Date().toISOString(),l({id:o,state:"failed",message:{role:"agent",parts:[{type:"text",text:`Error: ${d.message}`}]},final:!0})}s.end()}handleTaskGet(e,t,s){let o=String(t.id||""),n=this.tasks.get(o);if(!n){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:w.TASK_NOT_FOUND});return}this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,result:n})}handleTaskCancel(e,t,s){let o=String(t.id||""),n=this.tasks.get(o);if(!n){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:w.TASK_NOT_FOUND});return}if(n.state!=="working"&&n.state!=="submitted"){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:w.TASK_NOT_CANCELABLE});return}this.activeCancellations.add(o),n.state="canceled",n.updatedAt=new Date().toISOString(),this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,result:n})}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 os(i){return new Promise((e,t)=>{let s="";i.on("data",o=>s+=o),i.on("end",()=>{try{e(s?JSON.parse(s):{})}catch{e({})}}),i.on("error",t)})}var Ie={"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 is(i,e){let t=Ie[i];if(!t)return[`Unknown provider "${i}" \u2014 capabilities unknown`];if(!e?.length)return[];let s=[],o=[];for(let n of e)n in t&&!t[n]&&o.push(n);return o.length&&s.push(`Provider "${i}" lacks: ${o.join(", ")}. Some features will be degraded.`),s}function rs(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{ge as A2AClient,me as A2AMesh,Z as A2AServer,Ke as ALL_TOOL_NAMES,kt as AgentRegistry,Tt as AgentXDaemon,B as AgentXRuntime,Ze as BLOCKING_EVENTS,Be as ClaudeCodeProvider,We as ClaudeProvider,gt as ContextBuilder,Pt as CronScheduler,I as EnhanceEngine,S as GitManager,Qe as HOOK_EVENTS,W as HealEngine,ot as HookRegistry,K as Memory,ie as MemoryHierarchy,bt as MessageRouter,Xe as OUTPUT_CONFIGS,je as OUTPUT_TYPES,H as PERMISSION_MODES,Ie as PROVIDER_CAPABILITIES,lt as PermissionManager,O as Pipeline,Q as ReplEngine,$t as TelegramAdapter,wt as ToolExecutor,et as UsageTracker,Ct as WhatsAppAdapter,yt as WikiStore,Ee as agentConfigSchema,is as checkCapabilities,M as createAgentContext,G as createProvider,E as createSession,St as daemonConfigSchema,nt as debug,qe as detectSchemas,ee as detectTechStack,Fe as ensureCredentials,mt as executeClaudeCode,ht as executeOrchestrator,ut as executeSdk,ft as executeTask,oe as exportSession,ze as formatSchemas,b as formatTechStack,He as formatToolsForSystemPrompt,Ve as gatherContext7Docs,$ as generate,jt as generateSkill,Ot as generateSkillMd,_ as generateStream,Je as getAnthropicTools,V as getCommand,Ue as getLegacyTools,Rt as getPackageInfo,rt as globalHooks,A as globalPermissions,U as globalTracker,rs as handleError,Mt as installSkillPackage,Y as isCommand,st as isDebug,Et as listInstalledSkills,z as listSessions,_e as loadAuthConfig,xt as loadDaemonConfig,it as loadHooks,q as loadLatestSession,te as loadLocalSkills,pt as loadProjectInstructions,T as loadSession,m as logger,se as matchSkillsToTask,Ge as outputTypeDescriptions,X as parseCommand,J as parseSkillContent,Ye as parseSkillFile,ct as permissionConfigSchema,at as permissionModeSchema,h as registerCommand,dt as resolveAtImports,ne as resolveOutputType,Le as resolveToken,Ne as runModelSetup,De as saveAuthConfig,j as saveSession,tt as setDebug,Bt as startMcpServer,vt as validateWorkspaces};
86
90
  //# sourceMappingURL=index.js.map