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
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/daemon/token-tracker.ts"],"sourcesContent":["import { readFileSync, writeFileSync, appendFileSync, existsSync, mkdirSync } from \"fs\"\nimport { resolve } from \"path\"\n\n// --- Token usage tracker ---\n// Tracks token usage per agent per day with cache-aware cost calculation.\n// Persisted to .agentx/usage/{YYYY-MM-DD}.json\n\n// Anthropic pricing per million tokens (as of April 2026)\nexport const CACHE_AWARE_PRICING: Record<string, { input: number; output: number; cacheRead: number; cacheCreate: number }> = {\n \"claude-opus\": { input: 15, output: 75, cacheRead: 1.5, cacheCreate: 18.75 },\n \"claude-sonnet\": { input: 3, output: 15, cacheRead: 0.3, cacheCreate: 3.75 },\n \"claude-haiku\": { input: 0.25, output: 1.25, cacheRead: 0.025, cacheCreate: 0.3125 },\n}\n\nexport function getModelFamily(model: string): string {\n const lower = model.toLowerCase()\n if (lower.includes(\"opus\")) return \"claude-opus\"\n if (lower.includes(\"haiku\")) return \"claude-haiku\"\n return \"claude-sonnet\"\n}\n\nexport interface DailyUsage {\n date: string\n agents: Record<string, AgentUsage>\n}\n\nexport interface AgentUsage {\n tasks: number\n inputTokens: number\n outputTokens: number\n cacheReadTokens: number\n cacheCreateTokens: number\n totalDuration: number\n errors: number\n model?: string\n}\n\nexport interface DailyReport {\n date: string\n totalTasks: number\n totalInput: number\n totalOutput: number\n totalCacheRead: number\n totalCacheCreate: number\n totalCost: number\n topAgent: string\n topCost: number\n agentCosts: Record<string, number>\n}\n\nexport class TokenTracker {\n private dir: string\n private cache: DailyUsage | null = null\n\n constructor(baseDir: string = resolve(process.cwd(), \".agentx/usage\")) {\n this.dir = baseDir\n mkdirSync(this.dir, { recursive: true })\n }\n\n /**\n * Calculate cost for an agent's usage with cache-aware pricing.\n */\n static calculateCost(usage: AgentUsage): number {\n const family = getModelFamily(usage.model || \"claude-sonnet\")\n const pricing = CACHE_AWARE_PRICING[family] || CACHE_AWARE_PRICING[\"claude-sonnet\"]\n\n return (\n ((usage.inputTokens || 0) / 1_000_000) * pricing.input +\n ((usage.outputTokens || 0) / 1_000_000) * pricing.output +\n ((usage.cacheReadTokens || 0) / 1_000_000) * pricing.cacheRead +\n ((usage.cacheCreateTokens || 0) / 1_000_000) * pricing.cacheCreate\n )\n }\n\n /**\n * Record a task execution with real or estimated token counts.\n */\n record(\n agentId: string,\n duration: number,\n realUsage?: { inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheCreateTokens: number },\n messageLength?: number,\n responseLength?: number,\n error?: boolean,\n model?: string,\n ): void {\n const daily = this.today()\n const agent = daily.agents[agentId] || {\n tasks: 0, inputTokens: 0, outputTokens: 0,\n cacheReadTokens: 0, cacheCreateTokens: 0, totalDuration: 0, errors: 0,\n }\n\n agent.tasks++\n agent.totalDuration += duration\n if (model) agent.model = model\n\n if (realUsage) {\n agent.inputTokens += realUsage.inputTokens\n agent.outputTokens += realUsage.outputTokens\n agent.cacheReadTokens += realUsage.cacheReadTokens\n agent.cacheCreateTokens += realUsage.cacheCreateTokens\n } else if (messageLength !== undefined && responseLength !== undefined) {\n agent.inputTokens += Math.ceil(messageLength / 4)\n agent.outputTokens += Math.ceil(responseLength / 4)\n }\n\n if (error) agent.errors++\n\n daily.agents[agentId] = agent\n this.save(daily)\n }\n\n /**\n * Get today's usage summary.\n */\n today(): DailyUsage {\n const date = new Date().toISOString().slice(0, 10)\n\n if (this.cache?.date === date) return this.cache\n\n const path = this.filePath(date)\n if (existsSync(path)) {\n try {\n this.cache = JSON.parse(readFileSync(path, \"utf-8\"))\n return this.cache!\n } catch {}\n }\n\n this.cache = { date, agents: {} }\n return this.cache\n }\n\n /**\n * Get usage for a specific date.\n */\n getDate(date: string): DailyUsage | null {\n const path = this.filePath(date)\n if (!existsSync(path)) return null\n try {\n return JSON.parse(readFileSync(path, \"utf-8\"))\n } catch {\n return null\n }\n }\n\n /**\n * Generate a daily cost report for a given date.\n */\n generateDailyReport(date?: string): DailyReport | null {\n const targetDate = date || new Date().toISOString().slice(0, 10)\n const usage = this.getDate(targetDate)\n if (!usage) return null\n\n let totalTasks = 0, totalInput = 0, totalOutput = 0\n let totalCacheRead = 0, totalCacheCreate = 0, totalCost = 0\n let topAgent = \"\", topCost = 0\n const agentCosts: Record<string, number> = {}\n\n for (const [id, agent] of Object.entries(usage.agents)) {\n const cost = TokenTracker.calculateCost(agent)\n agentCosts[id] = cost\n totalTasks += agent.tasks\n totalInput += agent.inputTokens || 0\n totalOutput += agent.outputTokens || 0\n totalCacheRead += agent.cacheReadTokens || 0\n totalCacheCreate += agent.cacheCreateTokens || 0\n totalCost += cost\n if (cost > topCost) { topCost = cost; topAgent = id }\n }\n\n return {\n date: targetDate, totalTasks, totalInput, totalOutput,\n totalCacheRead, totalCacheCreate, totalCost, topAgent, topCost, agentCosts,\n }\n }\n\n /**\n * Append a daily report row to TOKEN_COSTS.md.\n */\n appendToTokenCosts(report: DailyReport, filePath?: string): void {\n const file = filePath || resolve(process.cwd(), \".agentx/TOKEN_COSTS.md\")\n const fmt = (n: number) => n < 0.01 ? n.toFixed(4) : n.toFixed(2)\n const fmtTok = (n: number) =>\n n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` :\n n >= 1_000 ? `${(n / 1_000).toFixed(0)}K` :\n String(n)\n\n const agentBreakdown = Object.entries(report.agentCosts)\n .sort(([, a], [, b]) => b - a)\n .map(([id, cost]) => `${id}: $${fmt(cost)}`)\n .join(\", \")\n\n const row = `| ${report.date} | ${report.totalTasks} | ${fmtTok(report.totalInput)} | ${fmtTok(report.totalOutput)} | ${fmtTok(report.totalCacheRead)} | ${fmtTok(report.totalCacheCreate)} | $${fmt(report.totalCost)} | ${agentBreakdown} |`\n\n if (!existsSync(file)) {\n const header =\n \"# Token Costs\\n\\n\" +\n \"Daily token cost tracking. Auto-appended at midnight (Africa/Tunis).\\n\\n\" +\n \"| Date | Tasks | Input | Output | Cache R | Cache W | Cost | Per Agent |\\n\" +\n \"|------|-------|-------|--------|---------|---------|------|-----------|\\n\"\n writeFileSync(file, header + row + \"\\n\")\n } else {\n appendFileSync(file, row + \"\\n\")\n }\n }\n\n /**\n * Get summary across last N days.\n */\n summary(days: number = 7): {\n totalTasks: number\n totalTokens: number\n totalInput: number\n totalOutput: number\n totalCacheRead: number\n totalCacheCreate: number\n cacheHitRatio: number\n totalErrors: number\n totalCost: number\n byAgent: Record<string, { tasks: number; input: number; output: number; cacheRead: number; cacheCreate: number; total: number; avgDuration: number; cost: number }>\n } {\n let totalTasks = 0\n let totalInput = 0\n let totalOutput = 0\n let totalCacheRead = 0\n let totalCacheCreate = 0\n let totalErrors = 0\n let totalCost = 0\n const byAgent: Record<string, { tasks: number; input: number; output: number; cacheRead: number; cacheCreate: number; total: number; avgDuration: number; totalDuration: number; cost: number; model?: string }> = {}\n\n for (let i = 0; i < days; i++) {\n const date = new Date(Date.now() - i * 86400_000).toISOString().slice(0, 10)\n const usage = this.getDate(date)\n if (!usage) continue\n\n for (const [id, agent] of Object.entries(usage.agents)) {\n const cost = TokenTracker.calculateCost(agent)\n totalTasks += agent.tasks\n totalInput += agent.inputTokens || 0\n totalOutput += agent.outputTokens || 0\n totalCacheRead += agent.cacheReadTokens || 0\n totalCacheCreate += agent.cacheCreateTokens || 0\n totalErrors += agent.errors\n totalCost += cost\n\n const existing = byAgent[id] || { tasks: 0, input: 0, output: 0, cacheRead: 0, cacheCreate: 0, total: 0, avgDuration: 0, totalDuration: 0, cost: 0 }\n existing.tasks += agent.tasks\n existing.input += agent.inputTokens || 0\n existing.output += agent.outputTokens || 0\n existing.cacheRead += agent.cacheReadTokens || 0\n existing.cacheCreate += agent.cacheCreateTokens || 0\n existing.total = existing.input + existing.output + existing.cacheRead + existing.cacheCreate\n existing.totalDuration += agent.totalDuration\n existing.avgDuration = existing.totalDuration / existing.tasks\n existing.cost += cost\n if (agent.model) existing.model = agent.model\n byAgent[id] = existing\n }\n }\n\n const totalTokens = totalInput + totalOutput + totalCacheRead + totalCacheCreate\n const cacheHitRatio = (totalCacheRead + totalCacheCreate) > 0\n ? totalCacheRead / (totalCacheRead + totalCacheCreate)\n : 0\n\n return { totalTasks, totalTokens, totalInput, totalOutput, totalCacheRead, totalCacheCreate, cacheHitRatio, totalErrors, totalCost, byAgent }\n }\n\n private filePath(date: string): string {\n return resolve(this.dir, `${date}.json`)\n }\n\n private save(usage: DailyUsage): void {\n try {\n writeFileSync(this.filePath(usage.date), JSON.stringify(usage, null, 2))\n } catch {}\n }\n}\n"],"mappings":"AAAA,OAAS,gBAAAA,EAAc,iBAAAC,EAAe,kBAAAC,EAAgB,cAAAC,EAAY,aAAAC,MAAiB,KACnF,OAAS,WAAAC,MAAe,OAOjB,IAAMC,EAAiH,CAC5H,cAAiB,CAAE,MAAO,GAAM,OAAQ,GAAM,UAAW,IAAQ,YAAa,KAAM,EACpF,gBAAiB,CAAE,MAAO,EAAM,OAAQ,GAAM,UAAW,GAAQ,YAAa,IAAK,EACnF,eAAiB,CAAE,MAAO,IAAM,OAAQ,KAAM,UAAW,KAAQ,YAAa,KAAO,CACvF,EAEO,SAASC,EAAeC,EAAuB,CACpD,IAAMC,EAAQD,EAAM,YAAY,EAChC,OAAIC,EAAM,SAAS,MAAM,EAAU,cAC/BA,EAAM,SAAS,OAAO,EAAU,eAC7B,eACT,CA+BO,IAAMC,EAAN,KAAmB,CAChB,IACA,MAA2B,KAEnC,YAAYC,EAAkBN,EAAQ,QAAQ,IAAI,EAAG,eAAe,EAAG,CACrE,KAAK,IAAMM,EACXP,EAAU,KAAK,IAAK,CAAE,UAAW,EAAK,CAAC,CACzC,CAKA,OAAO,cAAcQ,EAA2B,CAC9C,IAAMC,EAASN,EAAeK,EAAM,OA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AqB,EAC/C0B,GAAe1B,EAAM,OACrBS,GAAaK,EAEb,IAAMe,EAAWF,EAAQd,CAAE,GAAK,CAAE,MAAO,EAAG,MAAO,EAAG,OAAQ,EAAG,UAAW,EAAG,YAAa,EAAG,MAAO,EAAG,YAAa,EAAG,cAAe,EAAG,KAAM,CAAE,EACnJgB,EAAS,OAAS7B,EAAM,MACxB6B,EAAS,OAAS7B,EAAM,aAAe,EACvC6B,EAAS,QAAU7B,EAAM,cAAgB,EACzC6B,EAAS,WAAa7B,EAAM,iBAAmB,EAC/C6B,EAAS,aAAe7B,EAAM,mBAAqB,EACnD6B,EAAS,MAAQA,EAAS,MAAQA,EAAS,OAASA,EAAS,UAAYA,EAAS,YAClFA,EAAS,eAAiB7B,EAAM,cAChC6B,EAAS,YAAcA,EAAS,cAAgBA,EAAS,MACzDA,EAAS,MAAQf,EACbd,EAAM,QAAO6B,EAAS,MAAQ7B,EAAM,OACxC2B,EAAQd,CAAE,EAAIgB,GAIlB,IAAMC,EAAczB,EAAaC,EAAcC,EAAiBC,EAC1DuB,EAAiBxB,EAAiBC,EAAoB,EACxDD,GAAkBA,EAAiBC,GACnC,EAEJ,MAAO,CAAE,WAAAJ,EAAY,YAAA0B,EAAa,WAAAzB,EAAY,YAAAC,EAAa,eAAAC,EAAgB,iBAAAC,EAAkB,cAAAuB,EAAe,YAAAL,EAAa,UAAAjB,EAAW,QAAAkB,CAAQ,CAC9I,CAEQ,SAAS1B,EAAsB,CACrC,OAAOlB,EAAQ,KAAK,IAAK,GAAGkB,QAAW,CACzC,CAEQ,KAAKX,EAAyB,CACpC,GAAI,CACFX,EAAc,KAAK,SAASW,EAAM,IAAI,EAAG,KAAK,UAAUA,EAAO,KAAM,CAAC,CAAC,CACzE,MAAE,CAAO,CACX,CACF","names":["readFileSync","writeFileSync","appendFileSync","existsSync","mkdirSync","resolve","CACHE_AWARE_PRICING","getModelFamily","model","lower","TokenTracker","baseDir","usage","family","pricing","agentId","duration","realUsage","messageLength","responseLength","error","daily","agent","date","path","targetDate","totalTasks","totalInput","totalOutput","totalCacheRead","totalCacheCreate","totalCost","topAgent","topCost","agentCosts","id","cost","report","filePath","file","fmt","n","fmtTok","agentBreakdown","a","b","row","days","totalErrors","byAgent","i","existing","totalTokens","cacheHitRatio"]}
@@ -1,4 +1,4 @@
1
- import{a as w,b as y,c as x}from"./chunk-SFQUP3BP.js";import{g}from"./chunk-MGMZNJCE.js";import{existsSync as d,promises as h}from"fs";import c from"path";import{execa as C}from"execa";var b={enabled:!0,maxAttempts:3,provider:"claude-code"},v=class{constructor(e,r,i){this.cwd=e;this.config={...b,...r},this.memory=i||new x(e)}config;memory;async detectAndHeal(e,r,i){if(!this.config.enabled)return{healed:!1,attempts:0,error:"Heal disabled",filesChanged:[]};let t=await this.runVerification();if(!t)return{healed:!0,attempts:0,error:"",filesChanged:[]};let n=0,s=t,a=[];for(;n<this.config.maxAttempts;){n++;let l=await this.generateFix(s,e,r,n);if(!l.files.length)break;for(let o of l.files){let m=c.isAbsolute(o.path)?o.path:c.resolve(this.cwd,o.path),p=c.dirname(m);await h.mkdir(p,{recursive:!0}),await h.writeFile(m,o.content,"utf8"),a.push(o.path)}let f=await this.runVerification();if(!f)return i&&await this.memory.recordHeal(i,t,!0,a),{healed:!0,attempts:n,error:t,fix:l.explanation,filesChanged:a};s=f}return i&&await this.memory.recordHeal(i,t,!1,a),{healed:!1,attempts:n,error:s,filesChanged:a}}async runVerification(){let e=[this.config.buildCommand,this.config.lintCommand,this.config.testCommand].filter(Boolean);if(!e.length){let r=await this.detectCommands();e.push(...r)}for(let r of e)try{let[i,...t]=r.split(" ");await C(i,t,{cwd:this.cwd,timeout:6e4,reject:!0})}catch(i){let t=i.stderr||"",n=i.stdout||"",s=i.message||"";return k(`Command failed: ${r}
1
+ import{a as w,b as y,c as x}from"./chunk-SFQUP3BP.js";import{g}from"./chunk-KXZMYLHQ.js";import{existsSync as d,promises as h}from"fs";import c from"path";import{execa as C}from"execa";var b={enabled:!0,maxAttempts:3,provider:"claude-code"},v=class{constructor(e,r,i){this.cwd=e;this.config={...b,...r},this.memory=i||new x(e)}config;memory;async detectAndHeal(e,r,i){if(!this.config.enabled)return{healed:!1,attempts:0,error:"Heal disabled",filesChanged:[]};let t=await this.runVerification();if(!t)return{healed:!0,attempts:0,error:"",filesChanged:[]};let n=0,s=t,a=[];for(;n<this.config.maxAttempts;){n++;let l=await this.generateFix(s,e,r,n);if(!l.files.length)break;for(let o of l.files){let m=c.isAbsolute(o.path)?o.path:c.resolve(this.cwd,o.path),p=c.dirname(m);await h.mkdir(p,{recursive:!0}),await h.writeFile(m,o.content,"utf8"),a.push(o.path)}let f=await this.runVerification();if(!f)return i&&await this.memory.recordHeal(i,t,!0,a),{healed:!0,attempts:n,error:t,fix:l.explanation,filesChanged:a};s=f}return i&&await this.memory.recordHeal(i,t,!1,a),{healed:!1,attempts:n,error:s,filesChanged:a}}async runVerification(){let e=[this.config.buildCommand,this.config.lintCommand,this.config.testCommand].filter(Boolean);if(!e.length){let r=await this.detectCommands();e.push(...r)}for(let r of e)try{let[i,...t]=r.split(" ");await C(i,t,{cwd:this.cwd,timeout:6e4,reject:!0})}catch(i){let t=i.stderr||"",n=i.stdout||"",s=i.message||"";return k(`Command failed: ${r}
2
2
  ${t}
3
3
  ${n}
4
4
  ${s}`)}return null}async detectCommands(){let e=[],r=c.resolve(this.cwd,"package.json");if(d(r))try{let t=JSON.parse(await h.readFile(r,"utf8")).scripts||{};t.build&&e.push("npm run build"),t.typecheck&&e.push("npm run typecheck"),t.lint&&e.push("npm run lint"),t.test&&e.push("npm run test")}catch{}return d(c.resolve(this.cwd,"pyproject.toml"))&&d(c.resolve(this.cwd,"conftest.py"))&&e.push("python -m pytest --tb=short -q"),e}async generateFix(e,r,i,t){let n=g(this.config.provider,this.config.apiKey),s=[];for(let o of r.slice(0,5)){let m=c.resolve(this.cwd,o);if(d(m)){let p=await h.readFile(m,"utf8");s.push(`## ${o}
@@ -29,4 +29,4 @@ Fix the error. Use create_files with the corrected file content.`}],f=await n.ge
29
29
  `)+`
30
30
  ... (truncated)`:e.join(`
31
31
  `)}export{v as a};
32
- //# sourceMappingURL=chunk-X7UN6JAA.js.map
32
+ //# sourceMappingURL=chunk-6MKAXEE5.js.map
@@ -0,0 +1,12 @@
1
+ import{a as c,b,d as w}from"./chunk-M7HKBG3V.js";import{e as m}from"./chunk-DSYKYZMT.js";import{z as l}from"zod";var d=["pre:generate","post:generate","pre:file-write","post:file-write","pre:prompt","post:response","pre:command","on:error","pre:tool-call","post:tool-call","pre:channel-message","post:channel-message","pre:a2a-task","pre:cron-run","post:cron-run"],H=["pre:generate","pre:file-write","pre:prompt","post:response","pre:command","pre:tool-call","pre:channel-message","post:channel-message","pre:a2a-task","pre:cron-run"],v=l.object({name:l.string(),type:l.enum(["command","prompt","script"]),command:l.string().optional(),prompt:l.string().optional(),provider:l.enum(["claude-code","claude","openai","ollama","custom"]).optional(),model:l.string().optional(),script:l.string().optional(),priority:l.number().default(100),enabled:l.boolean().default(!0)});var x={"claude-sonnet":{input:3,output:15},"claude-opus":{input:15,output:75},"claude-haiku":{input:.25,output:1.25}};function T(i){let o=i.toLowerCase();return o.includes("opus")?"claude-opus":o.includes("haiku")?"claude-haiku":"claude-sonnet"}var h=class{steps=[];models=new Map;recordStep(o,e,t,r){let n=T(e),s=x[n]||x["claude-sonnet"],p=t/1e6*s.input+r/1e6*s.output;this.steps.push({step:o,model:e,inputTokens:t,outputTokens:r,cost:p,timestamp:Date.now()});let a=this.models.get(e)||{inputTokens:0,outputTokens:0,cost:0,steps:0};a.inputTokens+=t,a.outputTokens+=r,a.cost+=p,a.steps++,this.models.set(e,a)}getSummary(){let o=0,e=0,t=0;for(let n of this.steps)o+=n.inputTokens,e+=n.outputTokens,t+=n.cost;let r={};for(let[n,s]of this.models)r[n]={...s};return{totalInputTokens:o,totalOutputTokens:e,totalTokens:o+e,totalCost:t,steps:[...this.steps],models:r}}reset(){this.steps=[],this.models.clear()}},E=new h;function C(i,o){let e=[];if(e.push(`# Session: ${i.id}`),e.push(""),e.push(`- **Created**: ${i.createdAt}`),e.push(`- **Updated**: ${i.updatedAt}`),e.push(`- **CWD**: ${i.cwd}`),e.push(`- **Messages**: ${i.messages.length}`),e.push(`- **Tokens**: ${i.tokensUsed.toLocaleString()}`),e.push(""),i.filesGenerated.length){e.push("## Files Generated"),e.push("");for(let t of i.filesGenerated)e.push(`- \`${t}\``);e.push("")}if(i.messages.length){e.push("## Conversation"),e.push("");for(let t of i.messages){if(t.role==="system")continue;let r=t.role==="user"?"**User**":"**Assistant**";e.push(`### ${r}`),e.push(""),t.role,e.push(t.content),e.push("")}}if(o){if(e.push("## Cost Summary"),e.push(""),e.push(`- **Total tokens**: ${o.totalTokens.toLocaleString()}`),e.push(` - Input: ${o.totalInputTokens.toLocaleString()}`),e.push(` - Output: ${o.totalOutputTokens.toLocaleString()}`),e.push(`- **Total cost**: $${o.totalCost.toFixed(4)}`),e.push(""),Object.keys(o.models).length){e.push("### Per Model"),e.push(""),e.push("| Model | Input | Output | Cost | Steps |"),e.push("|-------|-------|--------|------|-------|");for(let[t,r]of Object.entries(o.models))e.push(`| ${t} | ${r.inputTokens.toLocaleString()} | ${r.outputTokens.toLocaleString()} | $${r.cost.toFixed(4)} | ${r.steps} |`);e.push("")}if(o.steps.length){e.push("### Per Step"),e.push(""),e.push("| Step | Model | Input | Output | Cost |"),e.push("|------|-------|-------|--------|------|");for(let t of o.steps)e.push(`| ${t.step} | ${t.model} | ${t.inputTokens.toLocaleString()} | ${t.outputTokens.toLocaleString()} | $${t.cost.toFixed(4)} |`);e.push("")}}return e.join(`
2
+ `)}import{execa as O}from"execa";var k=class{hooks=new Map;register(o,e){if(!e.enabled)return;let t=this.createHandler(e),r={event:o,definition:e,handler:t},n=this.hooks.get(o)||[];n.push(r),n.sort((s,p)=>s.definition.priority-p.definition.priority),this.hooks.set(o,n)}async execute(o,e){let t=this.hooks.get(o);if(!t?.length)return{};let r=H.includes(o),n={};for(let s of t){let p=Date.now();try{let a=await s.handler({...e,...n}),u=Date.now()-p;if(a.modified&&(n={...n,...a.modified}),r&&a.blocked)return m.hook(s.definition.name,u,"blocked"),{blocked:!0,message:a.message||`Blocked by hook: ${s.definition.name}`,modified:n};m.hook(s.definition.name,u,"ok")}catch(a){let u=Date.now()-p;if(m.hook(s.definition.name,u,`error: ${a.message}`),c.warn(`Hook "${s.definition.name}" failed: ${a.message}`),r)return{blocked:!0,message:`Hook "${s.definition.name}" errored: ${a.message}`}}}return{modified:Object.keys(n).length?n:void 0}}has(o){return!!this.hooks.get(o)?.length}clear(){this.hooks.clear()}createHandler(o){switch(o.type){case"command":return this.createCommandHandler(o);case"script":return this.createScriptHandler(o);case"prompt":return this.createPromptHandler(o);default:throw new Error(`Unknown hook type: ${o.type}`)}}createCommandHandler(o){return async e=>{if(!o.command)return{};let t=o.command;t=t.replace(/\{\{(\w+)\}\}/g,(n,s)=>String(e[s]??""));let r=await O("sh",["-c",t],{cwd:e.cwd||process.cwd(),reject:!1,timeout:6e4,env:process.env});return r.exitCode!==0?{blocked:!0,message:r.stderr||r.stdout||`Command hook "${o.name}" failed`}:{}}}createScriptHandler(o){return async e=>{if(!o.script)return{};let r=await import(o.script.startsWith("/")?o.script:`${e.cwd||process.cwd()}/${o.script}`),n=r.default||r.handler||r;return typeof n=="function"?await n(e):{}}}createPromptHandler(o){return async e=>{if(!o.prompt)return{};let t=o.provider||b()?.provider||"claude-code",r=w();if(!r&&t!=="claude-code")return c.warn(`Prompt hook "${o.name}" skipped: no credentials available for provider "${t}"`),{};try{let{createProvider:n}=await import("./providers-G3WZ4RVJ.js"),s=n(t,r?.token),p=o.prompt;p=p.replace(/\{\{(\w+)\}\}/g,(M,$)=>String(e[$]??""));let a=`You are a hook validator for agentx. Analyze the following context and respond with ONLY a JSON object (no markdown, no code fences).
3
+
4
+ Response format:
5
+ {"action": "allow", "message": "optional explanation"}
6
+ OR
7
+ {"action": "block", "message": "reason for blocking"}
8
+ OR
9
+ {"action": "allow", "message": "optional", "modified": {"key": "new value"}}
10
+
11
+ The "modified" field is optional and can contain updated values to pass forward.`,y=(await s.generate([{role:"system",content:a},{role:"user",content:p}],{model:o.model,maxTokens:1024})).content.trim().match(/\{[\s\S]*\}/);if(!y)return c.warn(`Prompt hook "${o.name}": LLM response was not valid JSON, allowing`),{};let f=JSON.parse(y[0]);return f.action==="block"?{blocked:!0,message:f.message||`Blocked by prompt hook: ${o.name}`}:f.modified?{modified:f.modified}:{}}catch(n){return c.warn(`Prompt hook "${o.name}" failed: ${n.message}`),{}}}}};import{existsSync as S,readFileSync as R,readdirSync as D}from"fs";import g from"path";function U(i,o){j(i,o),N(i,o)}function j(i,o){let e=g.join(i,"agentx.config.json");if(S(e))try{let t=JSON.parse(R(e,"utf8"));if(!t.hooks)return;for(let[r,n]of Object.entries(t.hooks)){if(!d.includes(r)){c.warn(`Unknown hook event in config: ${r}`);continue}let s=r;if(Array.isArray(n))for(let p of n)try{let a=v.parse(p);o.register(s,a)}catch(a){c.warn(`Invalid hook definition for ${s}: ${a.message}`)}}}catch(t){c.warn(`Failed to load hooks from config: ${t.message}`)}}function N(i,o){let e=g.join(i,".agentx","hooks");if(S(e))try{let t=D(e).filter(r=>r.endsWith(".ts")||r.endsWith(".js")||r.endsWith(".mjs"));for(let r of t){let n=r.replace(/\.(ts|js|mjs)$/,"").split(".");if(n.length<2){c.warn(`Hook file "${r}" should be named <event>.<name>.<ext>`);continue}let s=n[0],p=n.slice(1).join("."),a=s.replace(/-/g,":");if(!d.includes(a)){let u=s.replace("-",":");if(!d.includes(u)){c.warn(`Unknown hook event in filename: ${r}`);continue}o.register(u,{name:p,type:"script",script:g.join(e,r),priority:100,enabled:!0});continue}o.register(a,{name:p,type:"script",script:g.join(e,r),priority:100,enabled:!0})}}catch(t){c.warn(`Failed to load hooks from directory: ${t.message}`)}}var se=new k;export{d as a,H as b,h as c,E as d,C as e,k as f,U as g,se as h};
12
+ //# sourceMappingURL=chunk-CJ45Y2IR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/types.ts","../src/observability/tracker.ts","../src/observability/export.ts","../src/hooks/registry.ts","../src/hooks/loader.ts","../src/hooks/index.ts"],"sourcesContent":["import { z } from \"zod\"\n\n// --- Hook system types ---\n\nexport const HOOK_EVENTS = [\n \"pre:generate\",\n \"post:generate\",\n \"pre:file-write\",\n \"post:file-write\",\n \"pre:prompt\",\n \"post:response\",\n \"pre:command\",\n \"on:error\",\n \"pre:tool-call\",\n \"post:tool-call\",\n // Daemon events\n \"pre:channel-message\",\n \"post:channel-message\",\n \"pre:a2a-task\",\n \"pre:cron-run\",\n \"post:cron-run\",\n] as const\n\nexport type HookEvent = (typeof HOOK_EVENTS)[number]\n\n// Which hooks can block (return { blocked: true } to cancel the operation)\nexport const BLOCKING_EVENTS: HookEvent[] = [\n \"pre:generate\",\n \"pre:file-write\",\n \"pre:prompt\",\n \"post:response\",\n \"pre:command\",\n \"pre:tool-call\",\n // Daemon blocking events\n \"pre:channel-message\",\n \"post:channel-message\",\n \"pre:a2a-task\",\n \"pre:cron-run\",\n]\n\nexport type HookType = \"command\" | \"prompt\" | \"script\"\n\nexport const hookDefinitionSchema = z.object({\n name: z.string(),\n type: z.enum([\"command\", \"prompt\", \"script\"]),\n // For \"command\" type: shell command with {{variable}} interpolation\n command: z.string().optional(),\n // For \"prompt\" type: LLM prompt template\n prompt: z.string().optional(),\n // For \"prompt\" type: override provider/model for this hook\n provider: z.enum([\"claude-code\", \"claude\", \"openai\", \"ollama\", \"custom\"]).optional(),\n model: z.string().optional(),\n // For \"script\" type: path to JS/TS file exporting a handler\n script: z.string().optional(),\n // Hook priority (lower runs first, default 100)\n priority: z.number().default(100),\n // Whether this hook is enabled\n enabled: z.boolean().default(true),\n})\n\nexport type HookDefinition = z.infer<typeof hookDefinitionSchema>\n\nexport interface HookContext {\n event: HookEvent\n // Data varies by event\n task?: string\n file?: string\n fileContent?: string\n content?: string\n command?: string\n error?: Error\n cwd?: string\n [key: string]: unknown\n}\n\nexport interface HookResult {\n // If true, the operation is blocked/cancelled\n blocked?: boolean\n // Optional message explaining why it was blocked\n message?: string\n // Modified data to pass forward (e.g., modified file content)\n modified?: Record<string, unknown>\n}\n\nexport type HookHandler = (context: HookContext) => Promise<HookResult>\n","// --- Usage tracking: tokens, cost, per-step and per-model breakdown ---\n\nexport interface StepUsage {\n step: number\n model: string\n inputTokens: number\n outputTokens: number\n cost: number\n timestamp: number\n}\n\nexport interface ModelUsage {\n inputTokens: number\n outputTokens: number\n cost: number\n steps: number\n}\n\nexport interface UsageSummary {\n totalInputTokens: number\n totalOutputTokens: number\n totalTokens: number\n totalCost: number\n steps: StepUsage[]\n models: Record<string, ModelUsage>\n}\n\n// Cost per million tokens (input / output)\nconst MODEL_PRICING: Record<string, { input: number; output: number }> = {\n \"claude-sonnet\": { input: 3, output: 15 },\n \"claude-opus\": { input: 15, output: 75 },\n \"claude-haiku\": { input: 0.25, output: 1.25 },\n}\n\nfunction getModelFamily(model: string): string {\n const lower = model.toLowerCase()\n if (lower.includes(\"opus\")) return \"claude-opus\"\n if (lower.includes(\"haiku\")) return \"claude-haiku\"\n return \"claude-sonnet\" // default\n}\n\nexport class UsageTracker {\n private steps: StepUsage[] = []\n private models: Map<string, ModelUsage> = new Map()\n\n recordStep(\n step: number,\n model: string,\n inputTokens: number,\n outputTokens: number\n ): void {\n const family = getModelFamily(model)\n const pricing = MODEL_PRICING[family] || MODEL_PRICING[\"claude-sonnet\"]\n const cost =\n (inputTokens / 1_000_000) * pricing.input +\n (outputTokens / 1_000_000) * pricing.output\n\n this.steps.push({\n step,\n model,\n inputTokens,\n outputTokens,\n cost,\n timestamp: Date.now(),\n })\n\n const existing = this.models.get(model) || {\n inputTokens: 0,\n outputTokens: 0,\n cost: 0,\n steps: 0,\n }\n existing.inputTokens += inputTokens\n existing.outputTokens += outputTokens\n existing.cost += cost\n existing.steps++\n this.models.set(model, existing)\n }\n\n getSummary(): UsageSummary {\n let totalInputTokens = 0\n let totalOutputTokens = 0\n let totalCost = 0\n\n for (const step of this.steps) {\n totalInputTokens += step.inputTokens\n totalOutputTokens += step.outputTokens\n totalCost += step.cost\n }\n\n const models: Record<string, ModelUsage> = {}\n for (const [name, usage] of this.models) {\n models[name] = { ...usage }\n }\n\n return {\n totalInputTokens,\n totalOutputTokens,\n totalTokens: totalInputTokens + totalOutputTokens,\n totalCost,\n steps: [...this.steps],\n models,\n }\n }\n\n reset(): void {\n this.steps = []\n this.models.clear()\n }\n}\n\nexport const globalTracker = new UsageTracker()\n","// --- Session export: convert a session to readable markdown ---\n\nimport type { Session } from \"@/repl/session\"\nimport type { UsageSummary } from \"./tracker\"\n\nexport function exportSession(session: Session, usage?: UsageSummary): string {\n const lines: string[] = []\n\n // Header\n lines.push(`# Session: ${session.id}`)\n lines.push(\"\")\n lines.push(`- **Created**: ${session.createdAt}`)\n lines.push(`- **Updated**: ${session.updatedAt}`)\n lines.push(`- **CWD**: ${session.cwd}`)\n lines.push(`- **Messages**: ${session.messages.length}`)\n lines.push(`- **Tokens**: ${session.tokensUsed.toLocaleString()}`)\n lines.push(\"\")\n\n // Files generated\n if (session.filesGenerated.length) {\n lines.push(\"## Files Generated\")\n lines.push(\"\")\n for (const file of session.filesGenerated) {\n lines.push(`- \\`${file}\\``)\n }\n lines.push(\"\")\n }\n\n // Conversation\n if (session.messages.length) {\n lines.push(\"## Conversation\")\n lines.push(\"\")\n for (const msg of session.messages) {\n if (msg.role === \"system\") continue\n const label = msg.role === \"user\" ? \"**User**\" : \"**Assistant**\"\n lines.push(`### ${label}`)\n lines.push(\"\")\n if (msg.role === \"assistant\") {\n lines.push(msg.content)\n } else {\n lines.push(msg.content)\n }\n lines.push(\"\")\n }\n }\n\n // Cost summary\n if (usage) {\n lines.push(\"## Cost Summary\")\n lines.push(\"\")\n lines.push(`- **Total tokens**: ${usage.totalTokens.toLocaleString()}`)\n lines.push(` - Input: ${usage.totalInputTokens.toLocaleString()}`)\n lines.push(` - Output: ${usage.totalOutputTokens.toLocaleString()}`)\n lines.push(`- **Total cost**: $${usage.totalCost.toFixed(4)}`)\n lines.push(\"\")\n\n if (Object.keys(usage.models).length) {\n lines.push(\"### Per Model\")\n lines.push(\"\")\n lines.push(\"| Model | Input | Output | Cost | Steps |\")\n lines.push(\"|-------|-------|--------|------|-------|\")\n for (const [model, mu] of Object.entries(usage.models)) {\n lines.push(\n `| ${model} | ${mu.inputTokens.toLocaleString()} | ${mu.outputTokens.toLocaleString()} | $${mu.cost.toFixed(4)} | ${mu.steps} |`\n )\n }\n lines.push(\"\")\n }\n\n if (usage.steps.length) {\n lines.push(\"### Per Step\")\n lines.push(\"\")\n lines.push(\"| Step | Model | Input | Output | Cost |\")\n lines.push(\"|------|-------|-------|--------|------|\")\n for (const step of usage.steps) {\n lines.push(\n `| ${step.step} | ${step.model} | ${step.inputTokens.toLocaleString()} | ${step.outputTokens.toLocaleString()} | $${step.cost.toFixed(4)} |`\n )\n }\n lines.push(\"\")\n }\n }\n\n return lines.join(\"\\n\")\n}\n","import { execa } from \"execa\"\nimport type { HookEvent, HookDefinition, HookContext, HookResult, HookHandler } from \"./types\"\nimport { BLOCKING_EVENTS } from \"./types\"\nimport { logger } from \"@/utils/logger\"\nimport { debug } from \"@/observability\"\nimport { loadAuthConfig, resolveToken } from \"@/utils/auth-store\"\n\n// --- Hook Registry: registration, priority ordering, execution ---\n\ninterface RegisteredHook {\n event: HookEvent\n definition: HookDefinition\n handler: HookHandler\n}\n\nexport class HookRegistry {\n private hooks: Map<HookEvent, RegisteredHook[]> = new Map()\n\n /**\n * Register a hook for an event.\n */\n register(event: HookEvent, definition: HookDefinition): void {\n if (!definition.enabled) return\n\n const handler = this.createHandler(definition)\n const entry: RegisteredHook = { event, definition, handler }\n\n const existing = this.hooks.get(event) || []\n existing.push(entry)\n // Sort by priority (lower number = runs first)\n existing.sort((a, b) => a.definition.priority - b.definition.priority)\n this.hooks.set(event, existing)\n }\n\n /**\n * Execute all hooks for an event. Returns combined result.\n * For blocking events, stops at the first hook that returns { blocked: true }.\n */\n async execute(event: HookEvent, context: HookContext): Promise<HookResult> {\n const registered = this.hooks.get(event)\n if (!registered?.length) {\n return {}\n }\n\n const canBlock = BLOCKING_EVENTS.includes(event)\n let combinedModified: Record<string, unknown> = {}\n\n for (const hook of registered) {\n const start = Date.now()\n try {\n const result = await hook.handler({ ...context, ...combinedModified })\n const duration = Date.now() - start\n\n if (result.modified) {\n combinedModified = { ...combinedModified, ...result.modified }\n }\n\n if (canBlock && result.blocked) {\n debug.hook(hook.definition.name, duration, \"blocked\")\n return {\n blocked: true,\n message: result.message || `Blocked by hook: ${hook.definition.name}`,\n modified: combinedModified,\n }\n }\n\n debug.hook(hook.definition.name, duration, \"ok\")\n } catch (error: any) {\n const duration = Date.now() - start\n debug.hook(hook.definition.name, duration, `error: ${error.message}`)\n logger.warn(`Hook \"${hook.definition.name}\" failed: ${error.message}`)\n // Non-blocking hooks swallow errors; blocking hooks propagate\n if (canBlock) {\n return {\n blocked: true,\n message: `Hook \"${hook.definition.name}\" errored: ${error.message}`,\n }\n }\n }\n }\n\n return { modified: Object.keys(combinedModified).length ? combinedModified : undefined }\n }\n\n /**\n * Check if any hooks are registered for an event.\n */\n has(event: HookEvent): boolean {\n const registered = this.hooks.get(event)\n return !!registered?.length\n }\n\n /**\n * Clear all hooks (useful for testing).\n */\n clear(): void {\n this.hooks.clear()\n }\n\n /**\n * Create a HookHandler from a HookDefinition.\n */\n private createHandler(definition: HookDefinition): HookHandler {\n switch (definition.type) {\n case \"command\":\n return this.createCommandHandler(definition)\n case \"script\":\n return this.createScriptHandler(definition)\n case \"prompt\":\n return this.createPromptHandler(definition)\n default:\n throw new Error(`Unknown hook type: ${definition.type}`)\n }\n }\n\n /**\n * Command hook: runs a shell command with {{variable}} interpolation.\n * Exit code 0 = success, non-zero = blocked (for blocking events).\n */\n private createCommandHandler(definition: HookDefinition): HookHandler {\n return async (context: HookContext): Promise<HookResult> => {\n if (!definition.command) {\n return {}\n }\n\n // Interpolate {{variable}} placeholders\n let cmd = definition.command\n cmd = cmd.replace(/\\{\\{(\\w+)\\}\\}/g, (_match, key) => {\n return String(context[key] ?? \"\")\n })\n\n const result = await execa(\"sh\", [\"-c\", cmd], {\n cwd: context.cwd || process.cwd(),\n reject: false,\n timeout: 60_000,\n env: process.env,\n })\n\n if (result.exitCode !== 0) {\n return {\n blocked: true,\n message: result.stderr || result.stdout || `Command hook \"${definition.name}\" failed`,\n }\n }\n\n return {}\n }\n }\n\n /**\n * Script hook: imports and runs a JS/TS module that exports a handler function.\n */\n private createScriptHandler(definition: HookDefinition): HookHandler {\n return async (context: HookContext): Promise<HookResult> => {\n if (!definition.script) {\n return {}\n }\n\n const scriptPath = definition.script.startsWith(\"/\")\n ? definition.script\n : `${context.cwd || process.cwd()}/${definition.script}`\n\n const mod = await import(scriptPath)\n const handler = mod.default || mod.handler || mod\n\n if (typeof handler === \"function\") {\n return await handler(context)\n }\n\n return {}\n }\n }\n\n /**\n * Prompt hook: single-turn LLM call that can block or modify the operation.\n * The prompt template supports {{variable}} interpolation from hook context.\n * The LLM must respond with JSON: { \"action\": \"allow\"|\"block\", \"message\": \"...\", \"modified\": {...} }\n */\n private createPromptHandler(definition: HookDefinition): HookHandler {\n return async (context: HookContext): Promise<HookResult> => {\n if (!definition.prompt) {\n return {}\n }\n\n // Check credentials are available (don't prompt interactively)\n const providerName = definition.provider || loadAuthConfig()?.provider || \"claude-code\"\n const resolved = resolveToken()\n if (!resolved && providerName !== \"claude-code\") {\n logger.warn(\n `Prompt hook \"${definition.name}\" skipped: no credentials available for provider \"${providerName}\"`\n )\n return {}\n }\n\n try {\n // Lazy import to avoid circular deps\n const { createProvider } = await import(\"@/agent/providers\")\n const provider = createProvider(providerName as any, resolved?.token)\n\n // Interpolate {{variable}} placeholders in the prompt template\n let prompt = definition.prompt\n prompt = prompt.replace(/\\{\\{(\\w+)\\}\\}/g, (_match, key) => {\n return String(context[key] ?? \"\")\n })\n\n const systemPrompt = `You are a hook validator for agentx. Analyze the following context and respond with ONLY a JSON object (no markdown, no code fences).\n\nResponse format:\n{\"action\": \"allow\", \"message\": \"optional explanation\"}\nOR\n{\"action\": \"block\", \"message\": \"reason for blocking\"}\nOR\n{\"action\": \"allow\", \"message\": \"optional\", \"modified\": {\"key\": \"new value\"}}\n\nThe \"modified\" field is optional and can contain updated values to pass forward.`\n\n const result = await provider.generate(\n [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: prompt },\n ],\n {\n model: definition.model,\n maxTokens: 1024,\n }\n )\n\n // Parse the LLM response as JSON\n const content = result.content.trim()\n // Try to extract JSON from the response (handle markdown fences)\n const jsonMatch = content.match(/\\{[\\s\\S]*\\}/)\n if (!jsonMatch) {\n logger.warn(`Prompt hook \"${definition.name}\": LLM response was not valid JSON, allowing`)\n return {}\n }\n\n const parsed = JSON.parse(jsonMatch[0])\n\n if (parsed.action === \"block\") {\n return {\n blocked: true,\n message: parsed.message || `Blocked by prompt hook: ${definition.name}`,\n }\n }\n\n if (parsed.modified) {\n return { modified: parsed.modified }\n }\n\n return {}\n } catch (error: any) {\n // Don't block on hook failures — log and continue\n logger.warn(`Prompt hook \"${definition.name}\" failed: ${error.message}`)\n return {}\n }\n }\n }\n}\n","import { existsSync, readFileSync, readdirSync } from \"fs\"\nimport path from \"path\"\nimport type { HookEvent, HookDefinition } from \"./types\"\nimport { HOOK_EVENTS, hookDefinitionSchema } from \"./types\"\nimport { HookRegistry } from \"./registry\"\nimport { logger } from \"@/utils/logger\"\n\n// --- Hook Loader: load hooks from config and .agentx/hooks/ ---\n\ninterface HooksConfig {\n hooks?: Partial<Record<HookEvent, HookDefinition[]>>\n}\n\n/**\n * Load hooks from agentx.config.json and .agentx/hooks/ directory.\n */\nexport function loadHooks(cwd: string, registry: HookRegistry): void {\n loadHooksFromConfig(cwd, registry)\n loadHooksFromDirectory(cwd, registry)\n}\n\n/**\n * Load hook definitions from agentx.config.json.\n */\nfunction loadHooksFromConfig(cwd: string, registry: HookRegistry): void {\n const configPath = path.join(cwd, \"agentx.config.json\")\n if (!existsSync(configPath)) return\n\n try {\n const raw = JSON.parse(readFileSync(configPath, \"utf8\")) as HooksConfig\n if (!raw.hooks) return\n\n for (const [eventName, definitions] of Object.entries(raw.hooks)) {\n if (!HOOK_EVENTS.includes(eventName as HookEvent)) {\n logger.warn(`Unknown hook event in config: ${eventName}`)\n continue\n }\n\n const event = eventName as HookEvent\n if (!Array.isArray(definitions)) continue\n\n for (const def of definitions) {\n try {\n const parsed = hookDefinitionSchema.parse(def)\n registry.register(event, parsed)\n } catch (error: any) {\n logger.warn(`Invalid hook definition for ${event}: ${error.message}`)\n }\n }\n }\n } catch (error: any) {\n logger.warn(`Failed to load hooks from config: ${error.message}`)\n }\n}\n\n/**\n * Load hook scripts from .agentx/hooks/ directory.\n * Files are named <event>.<name>.ts (e.g., pre-file-write.format.ts).\n */\nfunction loadHooksFromDirectory(cwd: string, registry: HookRegistry): void {\n const hooksDir = path.join(cwd, \".agentx\", \"hooks\")\n if (!existsSync(hooksDir)) return\n\n try {\n const files = readdirSync(hooksDir).filter(\n (f) => f.endsWith(\".ts\") || f.endsWith(\".js\") || f.endsWith(\".mjs\")\n )\n\n for (const file of files) {\n // Parse filename: <event>.<name>.<ext>\n // Event uses dashes in filename: pre-file-write → pre:file-write\n const parts = file.replace(/\\.(ts|js|mjs)$/, \"\").split(\".\")\n if (parts.length < 2) {\n logger.warn(`Hook file \"${file}\" should be named <event>.<name>.<ext>`)\n continue\n }\n\n const eventSlug = parts[0]\n const name = parts.slice(1).join(\".\")\n\n // Convert slug to event name: pre-file-write → pre:file-write\n const eventName = eventSlug.replace(/-/g, \":\") as HookEvent\n if (!HOOK_EVENTS.includes(eventName)) {\n // Try replacing first dash only: pre-generate → pre:generate\n const altEvent = eventSlug.replace(\"-\", \":\") as HookEvent\n if (!HOOK_EVENTS.includes(altEvent)) {\n logger.warn(`Unknown hook event in filename: ${file}`)\n continue\n }\n registry.register(altEvent, {\n name,\n type: \"script\",\n script: path.join(hooksDir, file),\n priority: 100,\n enabled: true,\n })\n continue\n }\n\n registry.register(eventName, {\n name,\n type: \"script\",\n script: path.join(hooksDir, file),\n priority: 100,\n enabled: true,\n })\n }\n } catch (error: any) {\n logger.warn(`Failed to load hooks from directory: ${error.message}`)\n }\n}\n","export { HookRegistry } from \"./registry\"\nexport { loadHooks } from \"./loader\"\nexport type { HookEvent, HookDefinition, HookContext, HookResult, HookHandler } from \"./types\"\nexport { HOOK_EVENTS, BLOCKING_EVENTS } from \"./types\"\n\nimport { HookRegistry } from \"./registry\"\n\n// Singleton hook registry for the CLI process\nexport const globalHooks = new HookRegistry()\n"],"mappings":"yFAAA,OAAS,KAAAA,MAAS,MAIX,IAAMC,EAAc,CACzB,eACA,gBACA,iBACA,kBACA,aACA,gBACA,cACA,WACA,gBACA,iBAEA,sBACA,uBACA,eACA,eACA,eACF,EAKaC,EAA+B,CAC1C,eACA,iBACA,aACA,gBACA,cACA,gBAEA,sBACA,uBACA,eACA,cACF,EAIaC,EAAuBH,EAAE,OAAO,CAC3C,KAAMA,EAAE,OAAO,EACf,KAAMA,EAAE,KAAK,CAAC,UAAW,SAAU,QAAQ,CAAC,EAE5C,QAASA,EAAE,OAAO,EAAE,SAAS,EAE7B,OAAQA,EAAE,OAAO,EAAE,SAAS,EAE5B,SAAUA,EAAE,KAAK,CAAC,cAAe,SAAU,SAAU,SAAU,QAAQ,CAAC,EAAE,SAAS,EACnF,MAAOA,EAAE,OAAO,EAAE,SAAS,EAE3B,OAAQA,EAAE,OAAO,EAAE,SAAS,EAE5B,SAAUA,EAAE,OAAO,EAAE,QAAQ,GAAG,EAEhC,QAASA,EAAE,QAAQ,EAAE,QAAQ,EAAI,CACnC,CAAC,EC9BD,IAAMI,EAAmE,CACvE,gBAAiB,CAAE,MAAO,EAAG,OAAQ,EAAG,EACxC,cAAe,CAAE,MAAO,GAAI,OAAQ,EAAG,EACvC,eAAgB,CAAE,MAAO,IAAM,OAAQ,IAAK,CAC9C,EAEA,S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AI,EAChC,SAAU,IACV,QAAS,EACX,CAAC,EACD,SAGFrB,EAAS,SAASQ,EAAW,CAC3B,KAAAgB,EACA,KAAM,SACN,OAAQpB,EAAK,KAAKa,EAAUI,CAAI,EAChC,SAAU,IACV,QAAS,EACX,CAAC,EAEL,OAASL,EAAP,CACAL,EAAO,KAAK,wCAAwCK,EAAM,SAAS,CACrE,CACF,CCtGO,IAAMU,GAAc,IAAIC","names":["z","HOOK_EVENTS","BLOCKING_EVENTS","hookDefinitionSchema","MODEL_PRICING","getModelFamily","model","lower","UsageTracker","step","inputTokens","outputTokens","family","pricing","cost","existing","totalInputTokens","totalOutputTokens","totalCost","models","name","usage","globalTracker","exportSession","session","usage","lines","file","msg","label","model","mu","step","execa","HookRegistry","event","definition","handler","entry","existing","a","b","context","registered","canBlock","BLOCKING_EVENTS","combinedModified","hook","start","result","duration","debug","error","logger","cmd","_match","key","execa","mod","providerName","loadAuthConfig","resolved","resolveToken","createProvider","provider","prompt","systemPrompt","jsonMatch","parsed","existsSync","readFileSync","readdirSync","path","loadHooks","cwd","registry","loadHooksFromConfig","loadHooksFromDirectory","configPath","path","existsSync","raw","readFileSync","eventName","definitions","HOOK_EVENTS","logger","event","def","parsed","hookDefinitionSchema","error","hooksDir","files","readdirSync","f","file","parts","eventSlug","name","altEvent","globalHooks","HookRegistry"]}
@@ -0,0 +1,108 @@
1
+ import{a as Ce,b as Se,c as ge}from"./chunk-SFQUP3BP.js";import{d as X,h as p}from"./chunk-CJ45Y2IR.js";import{a as de,c as ue,g as me}from"./chunk-KXZMYLHQ.js";import{a as F,b as ce,f as pe}from"./chunk-M7HKBG3V.js";import{a as Te,d as fe}from"./chunk-MCJUAE6V.js";import{e as v}from"./chunk-DSYKYZMT.js";import{b as he,c as ye}from"./chunk-QOYAX2FT.js";import{z as R}from"zod";var Re=R.object({provider:R.enum(["claude-code","claude","openai","ollama","custom"]).default("claude-code"),model:R.string().optional(),apiKey:R.string().optional(),skills:R.array(R.string()).default([]),output:R.object({dir:R.string().default("./generated")}).default({}),context7:R.object({enabled:R.boolean().default(!0),apiKey:R.string().optional()}).default({}),agentic:R.object({maxIterations:R.number().default(20),enabledTools:R.array(R.string()).default(["create_files","ask_user","read_file","search_files","list_directory","run_command","edit_file"]),disabledTools:R.array(R.string()).default([])}).default({})}),dt=["component","page","api","website","document","script","config","skill","media","report","test","workflow","schema","email","diagram","auto"],ut={component:"UI component (any framework)",page:"Full page or screen",api:"API endpoint, route handler, or service",website:"Multi-page website or app",document:"Markdown, documentation, or specification",script:"Standalone script or utility",config:"Configuration file or setup",skill:"Agent skill (SKILL.md format for skills.sh)",media:"Media generation prompt (image/audio/video description)",report:"Analysis report or audit",test:"Test suite, test fixtures, or test data",workflow:"CI/CD pipeline, GitHub Actions, or automation",schema:"Database schema, Zod validators, or GraphQL types",email:"Email template (React Email, MJML, HTML)",diagram:"Mermaid, D2, or PlantUML diagram",auto:"Auto-detect the best output type"};import{existsSync as Ye,promises as Je}from"fs";import B from"path";import Qe from"fast-glob";var Ae={"prisma/schema.prisma":{type:"prisma",category:"database"},"drizzle/schema.ts":{type:"drizzle",category:"database"},"schema.graphql":{type:"graphql",category:"api"},"schema.gql":{type:"graphql",category:"api"},"openapi.yaml":{type:"openapi",category:"api"},"openapi.json":{type:"openapi",category:"api"},"swagger.yaml":{type:"openapi",category:"api"},"swagger.json":{type:"openapi",category:"api"}};async function Me(o){let e={},t=await Qe.glob("**/*",{cwd:o,deep:4,ignore:["**/node_modules/**","**/dist/**","**/build/**","**/.next/**","**/target/**","**/__pycache__/**","**/vendor/**","**/.git/**"],onlyFiles:!0});for(let[s,i]of Object.entries(Ae)){let l=t.find(a=>a.endsWith(s)||a===s);if(l&&i.category==="database"){let a=await K(B.resolve(o,l));if(a){e.database={type:i.type,content:Z(a,3e3),tables:Ve(a,i.type)};break}}}for(let[s,i]of Object.entries(Ae)){let l=t.find(a=>a.endsWith(s)||a===s);if(l&&i.category==="api"){let a=await K(B.resolve(o,l));if(a){e.api={type:i.type,content:Z(a,3e3)};break}}}if(!e.api){let s=t.find(i=>i.includes("trpc")&&(i.endsWith("router.ts")||i.endsWith("router.js")));if(s){let i=await K(B.resolve(o,s));i&&(e.api={type:"trpc",content:Z(i,3e3)})}}let n=t.find(s=>s===".env.example"||s===".env.local.example"||s===".env.template");if(n){let s=await K(B.resolve(o,n));s&&(e.env=Xe(s))}let r=t.filter(s=>(s.includes("models")||s.includes("types")||s.includes("schemas"))&&(s.endsWith(".ts")||s.endsWith(".py")||s.endsWith(".rs")||s.endsWith(".go")));if(r.length){e.models=[];for(let s of r.slice(0,5)){let i=await K(B.resolve(o,s));i&&e.models.push({path:s,content:Z(i,2e3),type:B.extname(s).slice(1)})}}return e}function Ve(o,e){if(e==="prisma"){let t=o.match(/model\s+(\w+)\s*\{/g);return t?t.map(n=>n.replace(/model\s+/,"").replace(/\s*\{/,"")):[]}return[]}function Xe(o){return{variables:o.split(`
2
+ `).filter(n=>n.trim()&&!n.trim().startsWith("#")).map(n=>{let[r]=n.split("="),s=r.trim(),i=n.includes("=")&&n.split("=")[1]?.trim().length>0;return{key:s,required:!i}})}}async function K(o){try{return Ye(o)?await Je.readFile(o,"utf8"):null}catch{return null}}function Z(o,e){return o.length<=e?o:o.slice(0,e)+`
3
+ ... (truncated)`}function Ie(o){let e=[];if(o.database&&e.push(`## Database Schema (${o.database.type})
4
+ `+(o.database.tables?.length?`Tables: ${o.database.tables.join(", ")}
5
+ `:"")+"```\n"+o.database.content+"\n```"),o.api&&e.push(`## API Schema (${o.api.type})
6
+ \`\`\`
7
+ `+o.api.content+"\n```"),o.env&&e.push(`## Environment Variables
8
+ `+o.env.variables.map(t=>`- ${t.key}${t.required?" (required)":""}`).join(`
9
+ `)),o.models?.length)for(let t of o.models)e.push(`## Model: ${t.path}
10
+ \`\`\``+t.type+`
11
+ `+t.content+"\n```");return e.join(`
12
+
13
+ `)}import $e from"node-fetch";var je="https://api.context7.com/v1";async function Ze(o,e){try{let t={"Content-Type":"application/json"};e&&(t.Authorization=`Bearer ${e}`);let n=await $e(`${je}/libraries/resolve`,{method:"POST",headers:t,body:JSON.stringify({name:o})});if(!n.ok)return null;let r=await n.json();return r?.libraries?.length?r.libraries[0]:null}catch{return null}}async function et(o,e,t=5e3,n){try{let r={"Content-Type":"application/json"};n&&(r.Authorization=`Bearer ${n}`);let s=await $e(`${je}/libraries/${encodeURIComponent(o)}/docs`,{method:"POST",headers:r,body:JSON.stringify({topic:e,maxTokens:t})});return s.ok&&(await s.json())?.content||null}catch{return null}}async function Oe(o,e,t){let n=[];for(let i of o.frameworks.slice(0,3))n.push(i.name);let r=["react","vue","svelte","angular","next","nuxt","express","fastify","hono","prisma","drizzle-orm","tailwindcss","shadcn","@tanstack/react-query","zod","trpc"];for(let i of r)(o.dependencies[i]||o.devDependencies[i])&&(n.includes(i)||n.push(i));let s=[];for(let i of n.slice(0,5)){let l=await Ze(i,t);if(l){let a=await et(l.id,e,3e3,t);a&&s.push(`## ${l.name} Documentation
14
+ ${a}`)}}return s.length?`# Relevant Library Documentation (via Context7)
15
+
16
+ ${s.join(`
17
+
18
+ ---
19
+
20
+ `)}`:""}var Ue={component:{type:"component",baseDir:"src/components",filePatterns:["*.tsx","*.vue","*.svelte","*.jsx","*.ts"],description:"UI component"},page:{type:"page",baseDir:"src/app",filePatterns:["*.tsx","*.vue","*.svelte","*.jsx","*.astro"],description:"Page or screen"},api:{type:"api",baseDir:"src/api",filePatterns:["*.ts","*.js","*.py","*.go","*.rs"],description:"API route or endpoint"},website:{type:"website",baseDir:".",filePatterns:["*"],description:"Multi-file website"},document:{type:"document",baseDir:"docs",filePatterns:["*.md","*.mdx","*.txt","*.rst"],description:"Documentation"},script:{type:"script",baseDir:"scripts",filePatterns:["*.ts","*.js","*.py","*.sh","*.go"],description:"Standalone script"},config:{type:"config",baseDir:".",filePatterns:["*.json","*.yaml","*.yml","*.toml","*.env"],description:"Configuration file"},skill:{type:"skill",baseDir:".skills",filePatterns:["SKILL.md"],description:"Agent skill (SKILL.md)"},media:{type:"media",baseDir:"media",filePatterns:["*.md","*.json","*.txt"],description:"Media generation prompt/description"},report:{type:"report",baseDir:"reports",filePatterns:["*.md","*.html","*.json"],description:"Analysis report"},test:{type:"test",baseDir:"src",filePatterns:["*.test.ts","*.test.tsx","*.spec.ts","*.test.js","*.test.py","*.test.go"],description:"Test suite or fixture"},workflow:{type:"workflow",baseDir:".github/workflows",filePatterns:["*.yml","*.yaml"],description:"CI/CD pipeline or automation"},schema:{type:"schema",baseDir:"src",filePatterns:["*.ts","*.prisma","*.graphql","*.gql","*.py"],description:"Database schema, validators, or types"},email:{type:"email",baseDir:"src/emails",filePatterns:["*.tsx","*.jsx","*.html","*.mjml"],description:"Email template"},diagram:{type:"diagram",baseDir:"docs",filePatterns:["*.md","*.mmd","*.d2","*.puml"],description:"Architecture or data diagram"}};function we(o,e){if(o&&o!=="auto")return o;let t=e.toLowerCase(),n=[[/\b(component|button|card|modal|dialog|form|input|dropdown|nav|sidebar|header|footer|widget|ui)\b/i,"component"],[/\b(page|screen|view|route|layout|dashboard|landing)\b/i,"page"],[/\b(api|endpoint|route handler|rest|graphql|webhook|middleware|server)\b/i,"api"],[/\b(website|site|web app|landing page|portfolio|blog)\b/i,"website"],[/\b(document|doc|readme|guide|tutorial|specification|spec|changelog)\b/i,"document"],[/\b(script|cli|command|tool|utility|migration|seed|cron)\b/i,"script"],[/\b(config|configuration|setup|env|settings)\b/i,"config"],[/\b(skill|agent skill|skill\.md)\b/i,"skill"],[/\b(video|audio|image|media|animation|thumbnail|podcast)\b/i,"media"],[/\b(report|audit|analysis|review|assessment|benchmark)\b/i,"report"],[/\b(test|spec|unit test|integration test|e2e|coverage|fixture|mock)\b/i,"test"],[/\b(workflow|ci|cd|pipeline|github action|deploy|automation|ci\/cd)\b/i,"workflow"],[/\b(schema|model|migration|prisma|drizzle|zod|validator|graphql type)\b/i,"schema"],[/\b(email|newsletter|transactional|invite|welcome email|notification email)\b/i,"email"],[/\b(diagram|erd|flowchart|architecture diagram|sequence diagram|mermaid|plantuml|d2)\b/i,"diagram"]];for(let[r,s]of n)if(r.test(t))return s;return"component"}import{existsSync as rt,promises as Ge}from"fs";import te from"path";import tt from"prompts";import ot from"chalk";import{z as D}from"zod";var Ee=["default","acceptEdits","plan","yolo"],De=D.enum(Ee),be=D.object({mode:De.default("default"),allow:D.array(D.string()).default([]),deny:D.array(D.string()).default([]),confirm:D.array(D.string()).default([])});function nt(o,e){let t=e.replace(/\./g,"\\.").replace(/\*\*/g,"{{GLOBSTAR}}").replace(/\*/g,"[^/]*").replace(/\{\{GLOBSTAR\}\}/g,".*").replace(/\?/g,"[^/]");return new RegExp(`^${t}$`).test(o)}var ee=class{mode;allowPatterns;denyPatterns;confirmPatterns;autoAllowAll=!1;constructor(e){let t=be.parse(e||{});this.mode=t.mode,this.allowPatterns=t.allow,this.denyPatterns=t.deny,this.confirmPatterns=t.confirm}getMode(){return this.mode}setMode(e){this.mode=e,this.autoAllowAll=!1,v.context("permissions",`mode set to ${e}`)}async checkFileWrite(e){if(v.context("permissions",`checking write: ${e} (mode: ${this.mode})`),this.matchesAny(e,this.denyPatterns))return v.context("permissions",`denied by pattern: ${e}`),"deny";switch(this.mode){case"yolo":return"allow";case"plan":return"skip";case"acceptEdits":return"allow";case"default":return this.autoAllowAll||this.matchesAny(e,this.allowPatterns)?"allow":this.promptUser(e);default:return"allow"}}async checkCommand(e){return this.mode==="yolo"?"allow":this.mode==="plan"?"deny":"allow"}matchesAny(e,t){return t.some(n=>nt(e,n))}async promptUser(e){let{action:t}=await tt({type:"select",name:"action",message:`Write file ${ot.cyan(e)}?`,choices:[{title:"Yes",value:"allow"},{title:"No",value:"deny"},{title:"All (allow remaining)",value:"all"},{title:"Skip",value:"skip"}],initial:0});return t==="all"?(this.autoAllowAll=!0,"allow"):t||"deny"}},N=new ee;async function oe(o,e){let t={written:[],skipped:[],errors:[]};for(let n of o){let r=te.isAbsolute(n.path)?n.path:te.resolve(e.cwd,e.outputDir||"",n.path);try{let s=n.content;if(p.has("pre:file-write")){let h=await p.execute("pre:file-write",{event:"pre:file-write",file:r,fileContent:s,cwd:e.cwd});if(h.blocked){t.skipped.push(r);continue}h.modified?.fileContent&&(s=String(h.modified.fileContent))}let i=te.relative(e.cwd,r),l=await N.checkFileWrite(i);if(l==="deny"){t.skipped.push(r);continue}if(l==="skip"){t.written.push(r);continue}if(rt(r)&&!e.overwrite){t.skipped.push(r);continue}if(e.dryRun){t.written.push(r);continue}let a=te.dirname(r);await Ge.mkdir(a,{recursive:!0}),await Ge.writeFile(r,s,"utf8"),t.written.push(r),p.has("post:file-write")&&await p.execute("post:file-write",{event:"post:file-write",file:r,fileContent:s,cwd:e.cwd})}catch(s){t.errors.push(`${r}: ${s.message}`)}}return t}function ne(o,e,t){if(t)return t;let n=Ue[o];if(!n)return"generated";let r=n.baseDir;return o==="component"&&(e.srcDir?r=`${e.srcDir}/components`:r="components"),o==="page"&&e.frameworks.find(i=>i.name==="nextjs")&&e.srcDir&&(r=`${e.srcDir}/app`),o==="api"&&e.frameworks.find(i=>i.name==="nextjs")&&(r=e.srcDir?`${e.srcDir}/app/api`:"app/api"),o==="test"&&(e.testing.includes("vitest")||e.testing.includes("jest"))&&(r=e.srcDir||"src"),o==="workflow"&&(r=".github/workflows"),o==="schema"&&(e.databases.includes("prisma")?r="prisma":e.srcDir&&(r=`${e.srcDir}/schemas`)),o==="email"&&(r=e.srcDir?`${e.srcDir}/emails`:"emails"),r}import st from"os";var it=st.homedir(),Y=class{constructor(e){this.cwd=e;this.userMemory=new ge(it),this.projectMemory=new ge(e)}userMemory;projectMemory;async load(){await Promise.all([this.userMemory.load(),this.projectMemory.load()])}async save(){await Promise.all([this.userMemory.save(),this.projectMemory.save()])}buildMemoryContext(e){let t=this.userMemory.buildMemoryContext(e),n=this.projectMemory.buildMemoryContext(e);if(!t&&!n)return"";let r=[];return n&&r.push(n),t&&r.push(t.replace("# Memory (learned from past interactions)","# Global Memory (cross-project patterns)")),r.join(`
21
+
22
+ `)}async learnPreference(e,t,n){await this.userMemory.learnPreference(e,t,n)}async recordGeneration(e){return this.projectMemory.recordGeneration(e)}getPreferences(){let e=this.userMemory.getPreferences(),t=this.projectMemory.getPreferences(),n=new Map;for(let r of e)n.set(r.key,r);for(let r of t)n.set(r.key,r);return Array.from(n.values())}getPatterns(){let e=this.userMemory.getPatterns();return[...this.projectMemory.getPatterns(),...e]}getStats(){return{user:this.userMemory.getStats(),project:this.projectMemory.getStats()}}getRecentGenerations(e=10){return this.projectMemory.getRecentGenerations(e)}};import{existsSync as Fe,readFileSync as Ne}from"fs";import Le from"path";function qe(o,e){return o.replace(/@([\w./-]+)/g,(t,n)=>{let r=Le.resolve(e,n);if(Fe(r))try{return Ne(r,"utf8")}catch{return t}return t})}function ke(o){let e=["SHADXN.md","CLAUDE.md"];for(let t of e){let n=Le.join(o,t);if(Fe(n))try{let r=Ne(n,"utf8");return r=qe(r,o),r}catch{}}return""}function at(o){return Math.ceil(o.length/4)}var xe=class{sections=[];addSection(e,t,n=50){t.trim()&&this.sections.push({label:e,content:t,priority:n})}buildContext(e,t=12e3){if(this.sections.length===0)return"";let n=this.sections.map(c=>c.content),r=he(n),s=ye(e,r),i=new Map(s.map(c=>[c.docIndex,c.score])),l=this.sections.map((c,f)=>({...c,relevance:i.get(f)??0,tokens:at(c.content)}));l.sort((c,f)=>f.priority+f.relevance*100-(c.priority+c.relevance*100));let a=[],h=0;for(let c of l)h+c.tokens>t&&a.length>0||(a.push(c),h+=c.tokens);return a.map(c=>c.content).join(`
23
+
24
+ `)}};import{promises as J}from"fs";import re from"path";import{execa as lt}from"execa";import Be from"fast-glob";var Q=class{cwd;options;constructor(e,t={}){this.cwd=e,this.options=t}async execute(e){if(v.context("tool-executor",`executing: ${e.name}`),p.has("pre:tool-call")){let n=await p.execute("pre:tool-call",{event:"pre:tool-call",toolName:e.name,toolInput:e.input,cwd:this.cwd});if(n.blocked)return{tool_use_id:e.id,content:n.message||`Tool ${e.name} blocked by pre:tool-call hook`,is_error:!0}}let t;try{switch(e.name){case"read_file":t=await this.readFile(e);break;case"search_files":t=await this.searchFiles(e);break;case"list_directory":t=await this.listDirectory(e);break;case"run_command":t=await this.runCommand(e);break;case"edit_file":t=await this.editFile(e);break;case"create_files":t=await this.createFiles(e);break;case"ask_user":t=await this.askUser(e);break;case"spawn_agent":t=await this.spawnAgent(e);break;default:t={tool_use_id:e.id,content:`Unknown tool: ${e.name}`,is_error:!0}}}catch(n){t={tool_use_id:e.id,content:`Error executing ${e.name}: ${n.message}`,is_error:!0}}return p.has("post:tool-call")&&await p.execute("post:tool-call",{event:"post:tool-call",toolName:e.name,toolInput:e.input,toolResult:t.content,cwd:this.cwd}),t}async readFile(e){let t=String(e.input.path||""),n=Number(e.input.max_lines)||500,r=re.resolve(this.cwd,t),s=await J.readFile(r,"utf8"),i=s.split(`
25
+ `),a=i.length>n?i.slice(0,n).join(`
26
+ `)+`
27
+
28
+ ... (truncated, ${i.length-n} more lines)`:s;return{tool_use_id:e.id,content:a}}async searchFiles(e){let t=String(e.input.pattern||"**/*"),n=e.input.content_regex?String(e.input.content_regex):void 0,r=Number(e.input.max_results)||50,s=await Be(t,{cwd:this.cwd,ignore:["node_modules/**",".git/**","dist/**",".next/**"],dot:!1});if(!n){let a=s.slice(0,r);return{tool_use_id:e.id,content:a.length?a.join(`
29
+ `)+(s.length>r?`
30
+
31
+ ... (${s.length-r} more files)`:""):"No files matched the pattern."}}let i=new RegExp(n,"gm"),l=[];for(let a of s){if(l.length>=r)break;try{let c=(await J.readFile(re.resolve(this.cwd,a),"utf8")).split(`
32
+ `);for(let f=0;f<c.length&&!(l.length>=r);f++)i.test(c[f])&&l.push(`${a}:${f+1}: ${c[f]}`),i.lastIndex=0}catch{}}return{tool_use_id:e.id,content:l.length?l.join(`
33
+ `):"No matches found."}}async listDirectory(e){let t=String(e.input.path||"."),n=!!e.input.recursive,r=Number(e.input.max_depth)||3,s=re.resolve(this.cwd,t);if(n){let h=await Be("**/*",{cwd:s,onlyFiles:!1,markDirectories:!0,deep:r,ignore:["node_modules/**",".git/**","dist/**",".next/**"]});return{tool_use_id:e.id,content:h.length?h.join(`
34
+ `):"Empty directory."}}let l=(await J.readdir(s,{withFileTypes:!0})).map(a=>a.isDirectory()?`${a.name}/`:a.name);return{tool_use_id:e.id,content:l.length?l.join(`
35
+ `):"Empty directory."}}async runCommand(e){let t=String(e.input.command||""),n=Number(e.input.timeout)||3e4;if(await N.checkCommand(t)==="deny")return{tool_use_id:e.id,content:`Command blocked by permissions (mode: ${N.getMode()}): ${t}`,is_error:!0};if(p.has("pre:command")){let a=await p.execute("pre:command",{event:"pre:command",command:t,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`Command blocked by pre:command hook: ${t}`,is_error:!0}}let s=await lt("sh",["-c",t],{cwd:this.cwd,timeout:n,reject:!1,stdin:"ignore"}),i=[s.stdout,s.stderr].filter(Boolean).join(`
36
+ `),l=i.length>1e4?i.slice(0,1e4)+`
37
+
38
+ ... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
39
+ ${l}`,is_error:!0}:{tool_use_id:e.id,content:l||"(no output)"}}async editFile(e){let t=String(e.input.path||""),n=e.input.edits,r=re.resolve(this.cwd,t);if(!n||n.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await N.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(p.has("pre:file-write")){let a=await p.execute("pre:file-write",{event:"pre:file-write",file:r,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await J.readFile(r,"utf8"),l=[];for(let a of n)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),l.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):l.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await J.writeFile(r,i,"utf8"),p.has("post:file-write")&&await p.execute("post:file-write",{event:"post:file-write",file:r,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
40
+ ${l.join(`
41
+ `)}`}}async createFiles(e){let t=e.input,n=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${n.length} file(s) for creation.`,files:n}}async spawnAgent(e){let t=String(e.input.agent_id||""),n=String(e.input.prompt||""),r=Number(e.input.timeout_seconds)||300;if(!t||!n)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-WV7QKQ3L.js"),{getGlobalRegistry:i}=await import("./registry-CDWY7CLL.js"),l=i();if(!l)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let h=await new s(l).spawn({targetAgentId:t,prompt:n,parentAgentId:"orchestrator",timeout:r*1e3});return h.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(h.duration/1e3)}s):
42
+
43
+ ${h.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${h.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),n=e.input.options,r=t;return n?.length&&(r+=`
44
+ Options: ${n.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:r}}};async function ve(o){let{provider:e,systemPrompt:t,messages:n,providerOptions:r,cwd:s,maxIterations:i=20,enabledTools:l,interactive:a=!0,overwrite:h=!1,dryRun:c=!1,onProgress:f}=o;if(!e.generateRaw)return We(o);let x=new Q(s,{interactive:a,overwrite:h,dryRun:c}),b=de(l),$=n.filter(k=>k.role!=="system").map(k=>({role:k.role,content:k.content})),G=[],C=0,S="",O,M=0;for(;M<i;){M++,f?.({type:"iteration_start",iteration:M}),v.step(M,`Agentic loop iteration (${b.length} tools available)`);let k;try{k=await e.generateRaw($,t,b,r)}catch(y){if(y.message?.includes("not available"))return We(o);throw y}C+=k.usage.input_tokens+k.usage.output_tokens;for(let y of k.content)y.type==="text"&&(S+=y.text,f?.({type:"text_delta",text:y.text}));if(k.stop_reason==="end_turn"||k.stop_reason==="max_tokens")break;if(k.stop_reason==="tool_use"){let y=k.content.filter(_=>_.type==="tool_use");if(y.length===0)break;$.push({role:"assistant",content:k.content});let I=[];for(let _ of y){f?.({type:"tool_call",name:_.name,id:_.id,input:_.input}),v.step(M,`Tool call: ${_.name}`);let w=await x.execute({name:_.name,id:_.id,input:_.input});f?.({type:"tool_result",name:_.name,id:_.id,content:w.content.slice(0,200),is_error:w.is_error}),w.files?.length&&(G.push(...w.files),f?.({type:"files_created",files:w.files})),w.followUp&&(O=w.followUp),I.push({type:"tool_result",tool_use_id:w.tool_use_id,content:w.content,is_error:w.is_error})}if($.push({role:"user",content:I}),O)break;continue}break}return f?.({type:"complete",iterations:M,totalTokens:C}),{files:G,content:S,followUp:O,tokensUsed:C,iterations:M}}async function We(o){let{provider:e,systemPrompt:t,messages:n,providerOptions:r,maxIterations:s=5}=o,l=[{role:"system",content:t+`
45
+
46
+ `+ue()},...n.filter(b=>b.role!=="system")],a=[],h=0,c="",f,x=0;for(;x<s;){x++,v.step(x,`Legacy loop step (model: ${r.model||"default"})`);let b=await e.generate(l,r);if(h+=b.tokensUsed||0,c=b.content,b.files.length&&a.push(...b.files),b.followUp){f=b.followUp;break}if(b.files.length===0&&x>1||!(b.content.includes("[CONTINUE]")||b.content.includes("Next, I'll")||b.content.includes("Now let me")||b.content.includes("I'll also generate")))break;let G=b.files.map(C=>`Created: ${C.path}${C.description?` \u2014 ${C.description}`:""}`).join(`
47
+ `);l.push({role:"assistant",content:b.content+(G?`
48
+
49
+ Files created:
50
+ ${G}`:"")}),l.push({role:"user",content:"Continue generating the remaining files. Build on what you've already created. When finished, do not include [CONTINUE] in your response."})}return{files:a,content:c,followUp:f,tokensUsed:h,iterations:x}}function _e(o){return typeof o.generateRaw=="function"}var se=class{queue=[];resolvers=[];closed=!1;push(e){if(this.closed)return;let t=this.resolvers.shift();if(t){t({value:e,done:!1});return}this.queue.push(e)}close(){if(!this.closed){this.closed=!0;for(let e of this.resolvers.splice(0))e({value:void 0,done:!0})}}async next(){return this.queue.length?{value:this.queue.shift(),done:!1}:this.closed?{value:void 0,done:!0}:new Promise(e=>{this.resolvers.push(e)})}async*[Symbol.asyncIterator](){for(;;){let{value:e,done:t}=await this.next();if(t)return;yield e}}};async function ze(o,e,t){let n=Re.parse(t||{}),r=new Y(o);await r.load();let[s,i,l]=await Promise.all([Ce(o),Me(o),Te(o)]),a="";if(n.context7.enabled)try{a=await Oe(s,e,n.context7.apiKey)}catch{}let h=r.buildMemoryContext(e),c=ke(o);return v.context("memory",h?"loaded":"empty"),v.context("instructions",c?"loaded from project":"none"),{techStack:s,schemas:i,skills:l,docs:a,config:n,memoryContext:h,projectInstructions:c}}async function Uo(o){let{task:e,cwd:t,overwrite:n=!1,dryRun:r=!1,provider:s="claude-code",model:i,apiKey:l,context7:a=!0,interactive:h=!0}=o,c=e;if(p.has("pre:prompt")){let u=await p.execute("pre:prompt",{event:"pre:prompt",task:e,cwd:t});if(u.blocked)throw new Error(u.message||"Blocked by pre:prompt hook");u.modified?.task&&(c=String(u.modified.task))}if(p.has("pre:generate")){let u=await p.execute("pre:generate",{event:"pre:generate",task:c,cwd:t});if(u.blocked)throw new Error(u.message||"Blocked by pre:generate hook")}F.info("Analyzing project...");let f=await ze(t,c,{provider:s,context7:{enabled:a,apiKey:l}}),x=we(o.outputType,c);F.info(`Output type: ${x}`);let b=fe(f.skills,c,x);b.length&&F.info(`Loaded ${b.length} relevant skill(s): ${b.map(u=>u.skill.frontmatter.name).join(", ")}`);let $=He(f,x,b.map(u=>u.skill));if(!await pe(l))throw new Error("No credentials configured. Run `agentx model` to set up.");let C=me(s,l),S=i||ce()?.model,O=[...o.sessionMessages||[],{role:"user",content:c}];F.info("Generating...");let M=_e(C),k=o.maxSteps??(M?20:5),y=await ve({provider:C,systemPrompt:$,messages:[{role:"system",content:$},...O],providerOptions:{model:S,maxTokens:8192},cwd:t,maxIterations:k,enabledTools:f.config.agentic.enabledTools.filter(u=>!f.config.agentic.disabledTools.includes(u)),interactive:h,overwrite:n,dryRun:r,onProgress:u=>{u.type==="iteration_start"&&u.iteration>1&&F.info(`Step ${u.iteration}/${k}...`),u.type==="tool_call"&&v.step(0,`Tool: ${u.name}`)}});if(y.tokensUsed){let u=S||"claude-sonnet-4-20250514",L=Math.round(y.tokensUsed*.3),ie=y.tokensUsed-L;X.recordStep(1,u,L,ie)}let{content:I}=y,{followUp:_,tokensUsed:w}=y;if(y.iterations>1&&F.info(`Completed in ${y.iterations} step(s)`),p.has("post:response")){let u=await p.execute("post:response",{event:"post:response",content:I,task:c,cwd:t});if(u.blocked)throw new Error(u.message||"Blocked by post:response hook");u.modified?.content&&(I=String(u.modified.content))}if(_&&h)return{files:{written:[],skipped:[],errors:[]},content:I,outputType:x,followUp:_,tokensUsed:w};let U=new Map;for(let u of y.files)U.set(u.path,u);let A=ne(x,f.techStack,o.outputDir),T=await oe(Array.from(U.values()),{cwd:t,overwrite:n,dryRun:r,outputDir:A}),j;if(o.heal!==!1&&!r&&T.written.length>0){let{HealEngine:u}=await import("./heal-OTGT5HHJ.js");j=await new u(t,{enabled:!0,testCommand:o.healConfig?.testCommand,buildCommand:o.healConfig?.buildCommand,lintCommand:o.healConfig?.lintCommand,maxAttempts:o.healConfig?.maxAttempts??3,provider:s,model:S,apiKey:l}).detectAndHeal(T.written,c),!j.healed&&j.error&&await p.execute("on:error",{event:"on:error",error:new Error(j.error),task:c,cwd:t})}return p.has("post:generate")&&await p.execute("post:generate",{event:"post:generate",task:c,content:I,cwd:t}),{files:T,content:I,outputType:x,tokensUsed:w,healResult:j}}async function*Eo(o){let{task:e,cwd:t,overwrite:n=!1,dryRun:r=!1,provider:s="claude-code",model:i,apiKey:l,context7:a=!0,interactive:h=!0}=o,c=e;if(p.has("pre:prompt")){let d=await p.execute("pre:prompt",{event:"pre:prompt",task:e,cwd:t});if(d.blocked){yield{type:"error",error:d.message||"Blocked by pre:prompt hook"};return}d.modified?.task&&(c=String(d.modified.task))}if(p.has("pre:generate")){let d=await p.execute("pre:generate",{event:"pre:generate",task:c,cwd:t});if(d.blocked){yield{type:"error",error:d.message||"Blocked by pre:generate hook"};return}}let f=await ze(t,c,{provider:s,context7:{enabled:a,apiKey:l}}),x=we(o.outputType,c);yield{type:"context_ready",outputType:x};let b=fe(f.skills,c,x),$=He(f,x,b.map(d=>d.skill));if(!await pe(l)){yield{type:"error",error:"No credentials configured. Run `agentx model` to set up."};return}let C=me(s,l),S=i||ce()?.model,O=_e(C),M=o.maxSteps??(O?20:5),k=[...o.sessionMessages||[],{role:"user",content:c}];if(O){let d=new se,P,g,q=(async()=>{try{P=await ve({provider:C,systemPrompt:$,messages:[{role:"system",content:$},...k],providerOptions:{model:S,maxTokens:8192},cwd:t,maxIterations:M,enabledTools:f.config.agentic.enabledTools.filter(m=>!f.config.agentic.disabledTools.includes(m)),interactive:h,overwrite:n,dryRun:r,onProgress:m=>{m.type==="text_delta"&&d.push({type:"text_delta",text:m.text}),m.type==="iteration_start"&&d.push({type:"iteration",iteration:m.iteration}),m.type==="tool_call"&&d.push({type:"tool_call",name:m.name,id:m.id}),m.type==="tool_result"&&d.push({type:"tool_result",name:m.name,id:m.id,is_error:m.is_error}),m.type==="files_created"&&d.push({type:"step_complete",step:0,filesCount:m.files.length})}})}catch(m){g=m}finally{d.close()}})();for await(let m of d)yield m;if(await q,g){yield{type:"error",error:g instanceof Error?g.message:String(g)};return}if(!P){yield{type:"error",error:"Agentic loop failed without a result"};return}yield{type:"done",result:{content:P.content,files:P.files,tokensUsed:P.tokensUsed,followUp:P.followUp}};let{content:E}=P;if(p.has("post:response")){let m=await p.execute("post:response",{event:"post:response",content:E,task:c,cwd:t});if(m.blocked){yield{type:"error",error:m.message||"Blocked by post:response hook"};return}m.modified?.content&&(E=String(m.modified.content))}if(P.followUp&&h){yield{type:"generate_result",result:{files:{written:[],skipped:[],errors:[]},content:E,outputType:x,followUp:P.followUp,tokensUsed:P.tokensUsed}};return}let z=new Map;for(let m of P.files)z.set(m.path,m);let le=ne(x,f.techStack,o.outputDir),V=await oe(Array.from(z.values()),{cwd:t,overwrite:n,dryRun:r,outputDir:le}),H;if(o.heal!==!1&&!r&&V.written.length>0){let{HealEngine:m}=await import("./heal-OTGT5HHJ.js");H=await new m(t,{enabled:!0,testCommand:o.healConfig?.testCommand,buildCommand:o.healConfig?.buildCommand,lintCommand:o.healConfig?.lintCommand,maxAttempts:o.healConfig?.maxAttempts??3,provider:s,model:S,apiKey:l}).detectAndHeal(V.written,c)}p.has("post:generate")&&await p.execute("post:generate",{event:"post:generate",task:c,content:E,cwd:t}),yield{type:"generate_result",result:{files:V,content:E,outputType:x,tokensUsed:P.tokensUsed,healResult:H}};return}let y=[{role:"system",content:$},...k],I=[],_=0,w="",U,A=0;A++,v.step(A,`Starting generation (model: ${S||"default"})`);let T;if(C.stream){let d="",P;for await(let g of C.stream(y,{model:S,maxTokens:8192}))yield g,g.type==="text_delta"&&(d+=g.text),g.type==="done"&&(P=g.result);T=P||{content:d,files:[],tokensUsed:0}}else{let d=await C.generate(y,{model:S,maxTokens:8192});d.content&&(yield{type:"text_delta",text:d.content}),yield{type:"done",result:d},T=d}_+=T.tokensUsed||0,w=T.content;let j=T.tokensUsed||0,u=S||"claude-sonnet-4-20250514",L=Math.round(j*.3),ie=j-L;if(X.recordStep(A,u,L,ie),v.api("generate",u,j),v.step(A,`Generated ${T.files.length} file(s), ${j} tokens`),T.files.length&&I.push(...T.files),T.followUp&&(U=T.followUp),yield{type:"step_complete",step:A,filesCount:T.files.length},!U&&(w.includes("[CONTINUE]")||w.includes("Next, I'll")||w.includes("Now let me")||w.includes("I'll also generate"))&&T.files.length>0){let P=T.files.map(g=>`Created: ${g.path}${g.description?` \u2014 ${g.description}`:""}`).join(`
51
+ `);for(y.push({role:"assistant",content:w+(P?`
52
+
53
+ Files created:
54
+ ${P}`:"")}),y.push({role:"user",content:"Continue generating the remaining files. Build on what you've already created. When finished, do not include [CONTINUE] in your response."});A<M;){A++,v.step(A,`Starting generation (model: ${S||"default"})`);let g=await C.generate(y,{model:S,maxTokens:8192});_+=g.tokensUsed||0,w=g.content;let q=g.tokensUsed||0,E=S||"claude-sonnet-4-20250514",z=Math.round(q*.3),le=q-z;if(X.recordStep(A,E,z,le),v.api("generate",E,q),v.step(A,`Generated ${g.files.length} file(s), ${q} tokens`),g.files.length&&I.push(...g.files),yield{type:"step_complete",step:A,filesCount:g.files.length},g.followUp){U=g.followUp;break}if(g.files.length===0&&A>1||!(g.content.includes("[CONTINUE]")||g.content.includes("Next, I'll")||g.content.includes("Now let me")||g.content.includes("I'll also generate")))break;let H=g.files.map(m=>`Created: ${m.path}${m.description?` \u2014 ${m.description}`:""}`).join(`
55
+ `);y.push({role:"assistant",content:g.content+(H?`
56
+
57
+ Files created:
58
+ ${H}`:"")}),y.push({role:"user",content:"Continue generating the remaining files. Build on what you've already created. When finished, do not include [CONTINUE] in your response."})}}if(p.has("post:response")){let d=await p.execute("post:response",{event:"post:response",content:w,task:c,cwd:t});if(d.blocked){yield{type:"error",error:d.message||"Blocked by post:response hook"};return}d.modified?.content&&(w=String(d.modified.content))}if(U&&h){yield{type:"generate_result",result:{files:{written:[],skipped:[],errors:[]},content:w,outputType:x,followUp:U,tokensUsed:_}};return}let Pe=new Map;for(let d of I)Pe.set(d.path,d);let Ke=ne(x,f.techStack,o.outputDir),ae=await oe(Array.from(Pe.values()),{cwd:t,overwrite:n,dryRun:r,outputDir:Ke}),W;if(o.heal!==!1&&!r&&ae.written.length>0){let{HealEngine:d}=await import("./heal-OTGT5HHJ.js");W=await new d(t,{enabled:!0,testCommand:o.healConfig?.testCommand,buildCommand:o.healConfig?.buildCommand,lintCommand:o.healConfig?.lintCommand,maxAttempts:o.healConfig?.maxAttempts??3,provider:s,model:S,apiKey:l}).detectAndHeal(ae.written,c),!W.healed&&W.error&&await p.execute("on:error",{event:"on:error",error:new Error(W.error),task:c,cwd:t})}p.has("post:generate")&&await p.execute("post:generate",{event:"post:generate",task:c,content:w,cwd:t}),yield{type:"generate_result",result:{files:ae,content:w,outputType:x,tokensUsed:_,healResult:W}}}function He(o,e,t){let n=[];n.push(`You are agentx, an agentic code generation tool. You generate high-quality, production-ready output for any tech stack.
59
+
60
+ Your primary tool is \`create_files\` \u2014 use it to output all generated code, documents, and configs as files.
61
+ If the request is ambiguous or you need critical information to proceed correctly, use \`ask_user\` to ask a clarifying question.
62
+
63
+ You also have tools to inspect the codebase before generating code:
64
+ - \`read_file\` \u2014 read existing files to understand patterns, styles, and implementations
65
+ - \`search_files\` \u2014 search for files by glob pattern, optionally grep content with regex
66
+ - \`list_directory\` \u2014 explore the project structure
67
+ - \`run_command\` \u2014 run shell commands (build, test, lint, etc.)
68
+ - \`edit_file\` \u2014 apply targeted search/replace edits to existing files
69
+
70
+ AGENTIC WORKFLOW:
71
+ - Before generating code, use \`read_file\` and \`search_files\` to understand the existing codebase
72
+ - Match the project's existing patterns, naming conventions, and code style
73
+ - After creating files, consider running tests or build commands to verify correctness
74
+ - Use \`edit_file\` for small, targeted changes instead of rewriting entire files
75
+
76
+ IMPORTANT RULES:
77
+ - Generate complete, working code \u2014 not stubs or placeholders
78
+ - Follow the project's existing patterns and conventions
79
+ - Use the detected tech stack to choose the right language, framework, and patterns
80
+ - File paths should be relative to the project root
81
+ - Include all necessary imports
82
+ - Do NOT add unnecessary dependencies
83
+
84
+ MULTI-STEP GENERATION:
85
+ For complex tasks that require multiple related files (e.g., schema + API + UI + tests), you can chain steps:
86
+ - Generate the foundational files first (schemas, types, configs)
87
+ - Include "[CONTINUE]" in your response text when there are more files to generate
88
+ - In subsequent steps, you'll see what was already created \u2014 build on it
89
+ - When all files are generated, do NOT include "[CONTINUE]"
90
+ - This enables you to generate a schema first, then an API that references it, then a UI that calls the API`),n.push(`# Project Tech Stack
91
+ ${Se(o.techStack)}`);let r=Object.keys(o.techStack.dependencies).slice(0,30);r.length&&n.push(`# Key Dependencies
92
+ ${r.join(", ")}`);let s=Ie(o.schemas);return s&&n.push(`# Project Schemas
93
+ ${s}`),t.length&&n.push(`# Active Skills
94
+ Follow these skill instructions when applicable:
95
+
96
+ `+t.map(i=>`## Skill: ${i.frontmatter.name}
97
+ ${i.frontmatter.description}
98
+
99
+ ${i.instructions}`).join(`
100
+
101
+ ---
102
+
103
+ `)),o.docs&&n.push(o.docs),o.projectInstructions&&n.push(`# Project Instructions
104
+ ${o.projectInstructions}`),o.memoryContext&&n.push(o.memoryContext),n.push(`# Output Type: ${e}
105
+ Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),n.join(`
106
+
107
+ `)}export{Re as a,dt as b,ut as c,Me as d,Ie as e,Oe as f,Ue as g,we as h,Ee as i,De as j,be as k,ee as l,N as m,Y as n,qe as o,ke as p,xe as q,Q as r,ze as s,Uo as t,Eo as u};
108
+ //# sourceMappingURL=chunk-D6EDMQRV.js.map