agentix-cli 0.13.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +65 -478
- package/dist/agent-LRSSVFDR.js +2 -0
- package/dist/board-dashboard-DAPHL6W2.js +4508 -0
- package/dist/board-dashboard-DAPHL6W2.js.map +1 -0
- package/dist/chunk-3XULOWYB.js +199 -0
- package/dist/chunk-3XULOWYB.js.map +1 -0
- package/dist/chunk-6U2XOQHU.js +7 -0
- package/dist/chunk-6U2XOQHU.js.map +1 -0
- package/dist/{chunk-ZRYBSI5G.js → chunk-7MBTMCKY.js} +2 -2
- package/dist/{chunk-D6EDMQRV.js → chunk-AU37OREL.js} +5 -5
- package/dist/chunk-B4Q4X7D5.js +6 -0
- package/dist/chunk-B4Q4X7D5.js.map +1 -0
- package/dist/chunk-CXY2RYNI.js +11 -0
- package/dist/chunk-CXY2RYNI.js.map +1 -0
- package/dist/chunk-FIOB3MEX.js +2 -0
- package/dist/chunk-HLRVDCNH.js +5 -0
- package/dist/chunk-HLRVDCNH.js.map +1 -0
- package/dist/chunk-IEVEMKAI.js +168 -0
- package/dist/chunk-IEVEMKAI.js.map +1 -0
- package/dist/chunk-RB7265LO.js +12 -0
- package/dist/chunk-RB7265LO.js.map +1 -0
- package/dist/chunk-RGUYBH77.js +7 -0
- package/dist/chunk-RGUYBH77.js.map +1 -0
- package/dist/chunk-WVNSWBCU.js +138 -0
- package/dist/chunk-WVNSWBCU.js.map +1 -0
- package/dist/cli.js +64 -48
- package/dist/cli.js.map +1 -1
- package/dist/{compaction-7I3E5QUO.js → compaction-JBZZ7I7Y.js} +4 -4
- package/dist/config-DCJYECL4.js +2 -0
- package/dist/config-mutator-6EJHSP3Y.js +2 -0
- package/dist/debug-3MEUO2P2.js +2 -0
- package/dist/{heal-OTGT5HHJ.js → heal-WKY5I4KB.js} +2 -2
- package/dist/index.d.ts +894 -70
- package/dist/index.js +11 -11
- package/dist/index.js.map +1 -1
- package/dist/loader-PTCXLJEX.js +2 -0
- package/dist/memory-extract-AD7KMRPC.js +2 -0
- package/dist/{providers-G3WZ4RVJ.js → providers-VUIWO3ZK.js} +2 -2
- package/dist/registry-5ND7GLFJ.js +2 -0
- package/dist/scheduler-FCXOXCN5.js +2 -0
- package/dist/scheduler-FCXOXCN5.js.map +1 -0
- package/dist/{subagent-WV7QKQ3L.js → subagent-2SJHSSJS.js} +2 -2
- package/dist/{usage-dashboard-2TJQBFSH.js → usage-dashboard-QX3CF6KK.js} +8 -8
- package/dist/usage-dashboard-QX3CF6KK.js.map +1 -0
- package/dist/whatsapp-state-6D6FHHD2.js +2 -0
- package/dist/whatsapp-state-6D6FHHD2.js.map +1 -0
- package/dist/workspace-setup-ZWTT42XT.js +2 -0
- package/dist/workspace-setup-ZWTT42XT.js.map +1 -0
- package/package.json +10 -1
- package/dist/agent-5KIMJI3F.js +0 -2
- package/dist/chunk-34UAFPK4.js +0 -10
- package/dist/chunk-34UAFPK4.js.map +0 -1
- package/dist/chunk-4YCH6IZV.js +0 -2
- package/dist/chunk-CJ45Y2IR.js +0 -12
- package/dist/chunk-CJ45Y2IR.js.map +0 -1
- package/dist/chunk-T25UEXVK.js +0 -126
- package/dist/chunk-T25UEXVK.js.map +0 -1
- package/dist/chunk-VH23CDHL.js +0 -157
- package/dist/chunk-VH23CDHL.js.map +0 -1
- package/dist/chunk-WJ6ZF6EZ.js +0 -6
- package/dist/chunk-WJ6ZF6EZ.js.map +0 -1
- package/dist/config-HAD5E4YX.js +0 -2
- package/dist/debug-N3B5NVJU.js +0 -2
- package/dist/loader-YQE6XJBT.js +0 -2
- package/dist/memory-extract-RGPUPMKU.js +0 -2
- package/dist/registry-CDWY7CLL.js +0 -2
- package/dist/usage-dashboard-2TJQBFSH.js.map +0 -1
- package/dist/workspace-setup-QQTCJY4B.js +0 -2
- /package/dist/{agent-5KIMJI3F.js.map → agent-LRSSVFDR.js.map} +0 -0
- /package/dist/{chunk-ZRYBSI5G.js.map → chunk-7MBTMCKY.js.map} +0 -0
- /package/dist/{chunk-D6EDMQRV.js.map → chunk-AU37OREL.js.map} +0 -0
- /package/dist/{chunk-4YCH6IZV.js.map → chunk-FIOB3MEX.js.map} +0 -0
- /package/dist/{compaction-7I3E5QUO.js.map → compaction-JBZZ7I7Y.js.map} +0 -0
- /package/dist/{config-HAD5E4YX.js.map → config-DCJYECL4.js.map} +0 -0
- /package/dist/{debug-N3B5NVJU.js.map → config-mutator-6EJHSP3Y.js.map} +0 -0
- /package/dist/{heal-OTGT5HHJ.js.map → debug-3MEUO2P2.js.map} +0 -0
- /package/dist/{loader-YQE6XJBT.js.map → heal-WKY5I4KB.js.map} +0 -0
- /package/dist/{memory-extract-RGPUPMKU.js.map → loader-PTCXLJEX.js.map} +0 -0
- /package/dist/{providers-G3WZ4RVJ.js.map → memory-extract-AD7KMRPC.js.map} +0 -0
- /package/dist/{registry-CDWY7CLL.js.map → providers-VUIWO3ZK.js.map} +0 -0
- /package/dist/{workspace-setup-QQTCJY4B.js.map → registry-5ND7GLFJ.js.map} +0 -0
- /package/dist/{subagent-WV7QKQ3L.js.map → subagent-2SJHSSJS.js.map} +0 -0
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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-
|
|
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-AU37OREL.js";import{a as ee,b,c as K}from"./chunk-SFQUP3BP.js";import{a as ge,b as me,c as $t,d as Ct,e as Pt,f as Rt,g as At}from"./chunk-WVNSWBCU.js";import"./chunk-6U2XOQHU.js";import{a as mt,b as ut,c as ht,d as ft,e as yt,i as kt}from"./chunk-IEVEMKAI.js";import"./chunk-CXY2RYNI.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-RB7265LO.js";import{b as Tt}from"./chunk-RGUYBH77.js";import"./chunk-HLRVDCNH.js";import{d as St,f as xt,g as vt,i as bt}from"./chunk-B4Q4X7D5.js";import"./chunk-QZP65I2H.js";import"./chunk-HI24KAEY.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-7MBTMCKY.js";import"./chunk-QOYAX2FT.js";import"./chunk-FIOB3MEX.js";import{execa as Mt}from"execa";import{existsSync as ue,promises as re}from"fs";import C from"path";import ye from"node-fetch";async function It(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 Mt("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 Ot(s,o,n,e)}}async function Ot(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 Et(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
|
|
4
|
+
${t}`}async function jt(i){let{loadLocalSkills:e}=await import("./loader-PTCXLJEX.js");return e(i)}async function Gt(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.
|
|
@@ -23,7 +23,7 @@ The skill should contain detailed instructions for an AI agent to follow when pe
|
|
|
23
23
|
1. Step-by-step instructions
|
|
24
24
|
2. Code patterns and conventions to follow
|
|
25
25
|
3. Common pitfalls to avoid
|
|
26
|
-
4. Examples where helpful`}],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
|
|
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 _t,promises as ke}from"fs";import ae from"path";var Dt={enabled:!0,autoSkills:!0,minFrequency:3,provider:"claude-code"},I=class{constructor(e,t,s){this.cwd=e;this.memory=t;this.config={...Dt,...s}}config;async enhance(){if(!this.config.enabled)return{skillsCreated:[],skillsUpdated:[],insights:[]};let e={skillsCreated:[],skillsUpdated:[],insights:[]};if(this.config.autoSkills){let 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=Lt(n),r=ae.resolve(o,a,"SKILL.md");if(!_t(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
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
|
|
|
@@ -36,10 +36,10 @@ ${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),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
|
|
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 Lt(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 Nt}from"http";var Ft={port:3170,host:"0.0.0.0",provider:"claude-code",cwd:process.cwd(),memory:{enabled:!0},heal:{enabled:!0},enhance:{enabled:!0,autoSkills:!0},cors:!0},B=class{config;memory;healEngine;enhanceEngine;pipeline;requestCount=0;log;constructor(e){this.config={...Ft,...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(),Nt(async(t,s)=>{if(this.config.cors&&(s.setHeader("Access-Control-Allow-Origin","*"),s.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),s.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),t.method==="OPTIONS")){s.writeHead(204),s.end();return}await this.handleRequest(t,s)}).listen(this.config.port,this.config.host,()=>{this.log(`
|
|
40
40
|
agentx runtime v0.1.0`),this.log(` Listening on http://${this.config.host}:${this.config.port}`),this.log(` Provider: ${this.config.provider}`),this.log(` Memory: ${this.config.memory.enabled?"enabled":"disabled"}`),this.log(` Auto-heal: ${this.config.heal.enabled?"enabled":"disabled"}`),this.log(` Self-enhance: ${this.config.enhance.enabled?"enabled":"disabled"}`),this.log(` Pipeline: ${this.pipeline.getMiddlewareNames().join(" \u2192 ")}`),this.log(` Working dir: ${this.config.cwd}`),this.log(""),this.log(" Endpoints:"),this.log(" POST /generate \u2014 generate code/content"),this.log(" POST /evolve \u2014 transform existing code"),this.log(" GET /inspect \u2014 project analysis"),this.log(" GET /memory \u2014 view learning history"),this.log(" POST /feedback \u2014 provide feedback on a generation"),this.log(" GET /health \u2014 health check"),this.log(" POST /enhance \u2014 trigger self-enhancement"),this.log("")})}async handleRequest(e,t){let s=new URL(e.url||"/",`http://${e.headers.host||"localhost"}`),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 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
|
|
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 Jt={name:"agentx",version:"0.1.0"},Ut="2024-11-05",Ht={tools:{},elicitation:{form:{}}},Kt=0;async function we(i,e){let t=++Kt;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",Wt=[{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 Bt(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
45
|
`)}`),a.files.skipped.length&&r.push(`
|
|
@@ -61,12 +61,12 @@ ${n.map(r=>`- **${r.skill.frontmatter.name}** (relevance: ${(r.relevance*100).to
|
|
|
61
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
62
|
`);return{content:[{type:"text",text:`${n}
|
|
63
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
|
|
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 qt(){let i=(...t)=>console.error("[agentx-mcp]",...t);i("Starting MCP server (stdio transport)...");let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{for(e+=t;;){let s=e.indexOf(`\r
|
|
65
65
|
\r
|
|
66
66
|
`);if(s===-1)break;let n=e.slice(0,s).match(/Content-Length:\s*(\d+)/);if(!n){let d=e.indexOf(`
|
|
67
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
|
|
68
68
|
\r
|
|
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:
|
|
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:Ut,capabilities:Ht,serverInfo:Jt}});break}case"notifications/initialized":{e("Client initialized.");break}case"tools/list":{P({jsonrpc:"2.0",id:s,result:{tools:Wt}});break}case"tools/call":{let n=o?.name,a=o?.arguments||{};try{let r=await Bt(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
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
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
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.
|
|
@@ -78,13 +78,13 @@ Rules:
|
|
|
78
78
|
|
|
79
79
|
${t.slice(0,4e3)}`}])).content.trim().split(`
|
|
80
80
|
`)[0]:this.fallbackCommitMessage(t)}fallbackCommitMessage(e){let t=e.split(`
|
|
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
|
|
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
|
|
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 ts}from"readline";import v from"chalk";import ss from"ora";import{existsSync as xe,mkdirSync as zt,readFileSync as le,readdirSync as ve,writeFileSync as Vt}from"fs";import L from"path";import Yt from"os";var x=L.join(Yt.homedir(),".agentx","sessions");function de(){xe(x)||zt(x,{recursive:!0})}function E(i){return{id:Xt(),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(),Vt(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 Xt(){return Math.random().toString(36).slice(2,10)+Date.now().toString(36).slice(-4)}import g from"chalk";import{writeFileSync as Qt}from"fs";import Zt 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 es 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 es({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=Zt.resolve(e.cwd,o);return Qt(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=ts({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=ss({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 ns}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 os={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={...os,...e},this.log=console.error.bind(console,"[a2a]")}async start(){ns(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 is(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
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:`
|
|
85
85
|
|
|
86
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
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)}
|
|
88
88
|
|
|
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
|
|
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 is(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)})}bt();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 rs(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 as(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,Rt as AgentXDaemon,B as AgentXRuntime,Ze as BLOCKING_EVENTS,Be as ClaudeCodeProvider,We as ClaudeProvider,gt as ContextBuilder,Tt as CronScheduler,I as EnhanceEngine,S as GitManager,Qe as HOOK_EVENTS,W as HealEngine,ot as HookRegistry,K as Memory,ie as MemoryHierarchy,$t 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,Ct as TelegramAdapter,wt as ToolExecutor,et as UsageTracker,Pt as WhatsAppAdapter,yt as WikiStore,Ee as agentConfigSchema,rs 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,Gt as generateSkill,Et as generateSkillMd,_ as generateStream,Je as getAnthropicTools,V as getCommand,Ue as getLegacyTools,At as getPackageInfo,rt as globalHooks,A as globalPermissions,U as globalTracker,as as handleError,It as installSkillPackage,Y as isCommand,st as isDebug,jt 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,qt as startMcpServer,vt as validateWorkspaces};
|
|
90
90
|
//# sourceMappingURL=index.js.map
|