agentix-cli 0.166.0 → 0.168.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 +2 -2
- package/dist/{App-UOZT7MWS.js → App-GK5F6QMB.js} +2 -2
- package/dist/{ChatApp-N7REHHH3.js → ChatApp-4HHJB4HM.js} +2 -2
- package/dist/absorb-eval-PO7TUGT2.js +2 -0
- package/dist/agent-6WKET7JZ.js +2 -0
- package/dist/{board-dashboard-4C77NLY5.js → board-dashboard-ESAX2ZFV.js} +436 -403
- package/dist/board-dashboard-ESAX2ZFV.js.map +1 -0
- package/dist/{chunk-NHWYEIET.js → chunk-5PEXL5LD.js} +6 -6
- package/dist/{chunk-L7RPH3T7.js → chunk-5QI7XFTA.js} +2 -2
- package/dist/{chunk-TCC56PYX.js → chunk-BAXGL6TY.js} +2 -2
- package/dist/{chunk-JMZNI257.js → chunk-BRQKV4FC.js} +2 -2
- package/dist/{chunk-B7QHC7N4.js → chunk-CBXPIKPJ.js} +2 -2
- package/dist/{chunk-33KKV3YU.js → chunk-COMJ7R5T.js} +2 -2
- package/dist/{chunk-6QLRRSKU.js → chunk-DCIYOPJF.js} +15 -15
- package/dist/chunk-DCIYOPJF.js.map +1 -0
- package/dist/{chunk-7FH2FEFA.js → chunk-DCJHCUEQ.js} +2 -2
- package/dist/{chunk-QLJ3OMPL.js → chunk-E67Z6OYF.js} +2 -2
- package/dist/chunk-E7Y4G3FK.js +185 -0
- package/dist/chunk-E7Y4G3FK.js.map +1 -0
- package/dist/{chunk-XQ2EFLQW.js → chunk-EEM433JK.js} +28 -28
- package/dist/{chunk-XQ2EFLQW.js.map → chunk-EEM433JK.js.map} +1 -1
- package/dist/chunk-FEA3XMVU.js +580 -0
- package/dist/chunk-FEA3XMVU.js.map +1 -0
- package/dist/chunk-GZIHLADX.js +4 -0
- package/dist/chunk-GZIHLADX.js.map +1 -0
- package/dist/{chunk-G3T73GGF.js → chunk-HFSPH5WM.js} +2 -2
- package/dist/{chunk-XJYGMCAV.js → chunk-HRN4WKSJ.js} +363 -304
- package/dist/chunk-HRN4WKSJ.js.map +1 -0
- package/dist/{chunk-IJZNM5PS.js → chunk-JKMFMW3E.js} +2 -2
- package/dist/chunk-KMPUUH5R.js +137 -0
- package/dist/chunk-KMPUUH5R.js.map +1 -0
- package/dist/{chunk-YKHK47G5.js → chunk-KWY5IBII.js} +2 -2
- package/dist/{chunk-TM2TPQKH.js → chunk-LE3BXIUF.js} +2 -2
- package/dist/chunk-LXW7H4D4.js +2 -0
- package/dist/chunk-LXW7H4D4.js.map +1 -0
- package/dist/chunk-NKCS6EZ7.js +92 -0
- package/dist/chunk-NKCS6EZ7.js.map +1 -0
- package/dist/{chunk-BQXKTQCX.js → chunk-PIJ6ECBC.js} +2 -2
- package/dist/chunk-RX5O5637.js +7 -0
- package/dist/chunk-RX5O5637.js.map +1 -0
- package/dist/{chunk-LQTTLXZY.js → chunk-S34KFBMJ.js} +3 -3
- package/dist/{chunk-XML72AUF.js → chunk-TVGVQABC.js} +2 -2
- package/dist/{chunk-7O43PB6O.js → chunk-U4PICSLC.js} +2 -2
- package/dist/{chunk-AFLZHY5Y.js → chunk-U5SJLLXH.js} +2 -2
- package/dist/{chunk-LM3K7U6H.js → chunk-UF5TWOKL.js} +15 -15
- package/dist/chunk-UF5TWOKL.js.map +1 -0
- package/dist/chunk-UKKOBMOP.js +8 -0
- package/dist/chunk-UKKOBMOP.js.map +1 -0
- package/dist/{chunk-BNOGNRAM.js → chunk-VD2P4GWU.js} +2 -2
- package/dist/{chunk-64POGFQZ.js → chunk-YQM6VR6U.js} +2 -2
- package/dist/{chunk-QGKNDGH5.js → chunk-Z6ZR2ELO.js} +2 -2
- package/dist/{chunk-SXKC2LH7.js → chunk-ZTIOHZIL.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/client-DOIYODET.js +2 -0
- package/dist/{compaction-VN3M5YGZ.js → compaction-26OHHULF.js} +3 -3
- package/dist/config-3UBJRE5R.js +2 -0
- package/dist/config-mutate-ZRPDYJKN.js +2 -0
- package/dist/config-mutator-B5MR3V4B.js +2 -0
- package/dist/{context-planner-2XBAPQ3S.js → context-planner-CVCRW5TV.js} +2 -2
- package/dist/{contributions-MUCJKT73.js → contributions-2CJFYRZ7.js} +2 -2
- package/dist/{doctor-2N2MX5YP.js → doctor-OQZMDL5S.js} +2 -2
- package/dist/{follow-up-tool-W64LMQQN.js → follow-up-tool-PQUPXQQT.js} +2 -2
- package/dist/{grants-YGA654NI.js → grants-4O2VF2YX.js} +2 -2
- package/dist/heal-ZS56MC4A.js +2 -0
- package/dist/hub-LOW7KS5N.js +2 -0
- package/dist/index.d.ts +563 -3
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/memory-extract-NLVLQE7V.js +2 -0
- package/dist/{program-6YMRDLHO.js → program-7W2LJKDN.js} +298 -273
- package/dist/program-7W2LJKDN.js.map +1 -0
- package/dist/{promote-OUSVJZ64.js → promote-ZWQAL3RE.js} +2 -2
- package/dist/{providers-VVT2OBXA.js → providers-F5GDJSYD.js} +2 -2
- package/dist/push-bridge-NR7SLHGX.js +1 -1
- package/dist/query-N4EJ24LW.js +2 -0
- package/dist/{query-settings-2TNLXEL5.js → query-settings-RZV5ELLC.js} +2 -2
- package/dist/registry-EBYOZK3P.js +2 -0
- package/dist/{request-planner-7HEHLPA3.js → request-planner-KCG6QB6M.js} +2 -2
- package/dist/{review-candidates-NJNMSOCX.js → review-candidates-3GHWVJQ3.js} +2 -2
- package/dist/routing-XULOU6BI.js +2 -0
- package/dist/schedule-tool-ALZXDGGC.js +2 -0
- package/dist/scheduler-SCVCNKJC.js +2 -0
- package/dist/{seat-CAYDECW2.js → seat-PD7W3KAN.js} +2 -2
- package/dist/{select-QUVE6RN2.js → select-Z3YXBGUP.js} +2 -2
- package/dist/{set-enabled-BWJN4IVG.js → set-enabled-NJYJWDWH.js} +2 -2
- package/dist/sprint-tool-OLHZZAK3.js +7 -0
- package/dist/sprint-tool-OLHZZAK3.js.map +1 -0
- package/dist/tool-7IKZO33P.js +4 -0
- package/dist/tool-7IKZO33P.js.map +1 -0
- package/dist/{tool-FZ4UXMON.js → tool-EVQBMGJV.js} +2 -2
- package/dist/{tool-UC7OZWIB.js → tool-XH5QN6JM.js} +2 -2
- package/dist/wiki-BPOTYAQV.js +2 -0
- package/dist/wiki-enrich-JCNGRYQZ.js +2 -0
- package/package.json +1 -1
- package/dist/absorb-eval-MT3ZDYBM.js +0 -2
- package/dist/agent-SUAQ7EBM.js +0 -2
- package/dist/board-dashboard-4C77NLY5.js.map +0 -1
- package/dist/chunk-2QNT5JDS.js +0 -4
- package/dist/chunk-2QNT5JDS.js.map +0 -1
- package/dist/chunk-6QLRRSKU.js.map +0 -1
- package/dist/chunk-7UIK4S6T.js +0 -128
- package/dist/chunk-7UIK4S6T.js.map +0 -1
- package/dist/chunk-A2D3PNDA.js +0 -578
- package/dist/chunk-A2D3PNDA.js.map +0 -1
- package/dist/chunk-AE3U4GR6.js +0 -181
- package/dist/chunk-AE3U4GR6.js.map +0 -1
- package/dist/chunk-APPTSTL5.js +0 -2
- package/dist/chunk-APPTSTL5.js.map +0 -1
- package/dist/chunk-B6GVATMI.js +0 -92
- package/dist/chunk-B6GVATMI.js.map +0 -1
- package/dist/chunk-LM3K7U6H.js.map +0 -1
- package/dist/chunk-XJYGMCAV.js.map +0 -1
- package/dist/chunk-YQ25AGX6.js +0 -8
- package/dist/chunk-YQ25AGX6.js.map +0 -1
- package/dist/client-6ZHYSQU6.js +0 -2
- package/dist/config-WCEFYQL4.js +0 -2
- package/dist/config-mutate-LW366SKL.js +0 -2
- package/dist/config-mutator-NRHZ2XH3.js +0 -2
- package/dist/heal-KCM6JYUK.js +0 -2
- package/dist/hub-4ODFNGHL.js +0 -2
- package/dist/memory-extract-4JFORU2K.js +0 -2
- package/dist/program-6YMRDLHO.js.map +0 -1
- package/dist/query-QVK5EN3P.js +0 -2
- package/dist/registry-BYIWNEFL.js +0 -2
- package/dist/routing-HCSXNUOY.js +0 -2
- package/dist/schedule-tool-LJYBLCLV.js +0 -2
- package/dist/scheduler-74MXJLQS.js +0 -2
- package/dist/wiki-KNSPJT2O.js +0 -2
- package/dist/wiki-enrich-RVRTAQQF.js +0 -2
- /package/dist/{App-UOZT7MWS.js.map → App-GK5F6QMB.js.map} +0 -0
- /package/dist/{ChatApp-N7REHHH3.js.map → ChatApp-4HHJB4HM.js.map} +0 -0
- /package/dist/{absorb-eval-MT3ZDYBM.js.map → absorb-eval-PO7TUGT2.js.map} +0 -0
- /package/dist/{agent-SUAQ7EBM.js.map → agent-6WKET7JZ.js.map} +0 -0
- /package/dist/{chunk-NHWYEIET.js.map → chunk-5PEXL5LD.js.map} +0 -0
- /package/dist/{chunk-L7RPH3T7.js.map → chunk-5QI7XFTA.js.map} +0 -0
- /package/dist/{chunk-TCC56PYX.js.map → chunk-BAXGL6TY.js.map} +0 -0
- /package/dist/{chunk-JMZNI257.js.map → chunk-BRQKV4FC.js.map} +0 -0
- /package/dist/{chunk-B7QHC7N4.js.map → chunk-CBXPIKPJ.js.map} +0 -0
- /package/dist/{chunk-33KKV3YU.js.map → chunk-COMJ7R5T.js.map} +0 -0
- /package/dist/{chunk-7FH2FEFA.js.map → chunk-DCJHCUEQ.js.map} +0 -0
- /package/dist/{chunk-QLJ3OMPL.js.map → chunk-E67Z6OYF.js.map} +0 -0
- /package/dist/{chunk-G3T73GGF.js.map → chunk-HFSPH5WM.js.map} +0 -0
- /package/dist/{chunk-IJZNM5PS.js.map → chunk-JKMFMW3E.js.map} +0 -0
- /package/dist/{chunk-YKHK47G5.js.map → chunk-KWY5IBII.js.map} +0 -0
- /package/dist/{chunk-TM2TPQKH.js.map → chunk-LE3BXIUF.js.map} +0 -0
- /package/dist/{chunk-BQXKTQCX.js.map → chunk-PIJ6ECBC.js.map} +0 -0
- /package/dist/{chunk-LQTTLXZY.js.map → chunk-S34KFBMJ.js.map} +0 -0
- /package/dist/{chunk-XML72AUF.js.map → chunk-TVGVQABC.js.map} +0 -0
- /package/dist/{chunk-7O43PB6O.js.map → chunk-U4PICSLC.js.map} +0 -0
- /package/dist/{chunk-AFLZHY5Y.js.map → chunk-U5SJLLXH.js.map} +0 -0
- /package/dist/{chunk-BNOGNRAM.js.map → chunk-VD2P4GWU.js.map} +0 -0
- /package/dist/{chunk-64POGFQZ.js.map → chunk-YQM6VR6U.js.map} +0 -0
- /package/dist/{chunk-QGKNDGH5.js.map → chunk-Z6ZR2ELO.js.map} +0 -0
- /package/dist/{chunk-SXKC2LH7.js.map → chunk-ZTIOHZIL.js.map} +0 -0
- /package/dist/{client-6ZHYSQU6.js.map → client-DOIYODET.js.map} +0 -0
- /package/dist/{compaction-VN3M5YGZ.js.map → compaction-26OHHULF.js.map} +0 -0
- /package/dist/{config-WCEFYQL4.js.map → config-3UBJRE5R.js.map} +0 -0
- /package/dist/{config-mutate-LW366SKL.js.map → config-mutate-ZRPDYJKN.js.map} +0 -0
- /package/dist/{config-mutator-NRHZ2XH3.js.map → config-mutator-B5MR3V4B.js.map} +0 -0
- /package/dist/{context-planner-2XBAPQ3S.js.map → context-planner-CVCRW5TV.js.map} +0 -0
- /package/dist/{contributions-MUCJKT73.js.map → contributions-2CJFYRZ7.js.map} +0 -0
- /package/dist/{doctor-2N2MX5YP.js.map → doctor-OQZMDL5S.js.map} +0 -0
- /package/dist/{follow-up-tool-W64LMQQN.js.map → follow-up-tool-PQUPXQQT.js.map} +0 -0
- /package/dist/{grants-YGA654NI.js.map → grants-4O2VF2YX.js.map} +0 -0
- /package/dist/{heal-KCM6JYUK.js.map → heal-ZS56MC4A.js.map} +0 -0
- /package/dist/{hub-4ODFNGHL.js.map → hub-LOW7KS5N.js.map} +0 -0
- /package/dist/{memory-extract-4JFORU2K.js.map → memory-extract-NLVLQE7V.js.map} +0 -0
- /package/dist/{promote-OUSVJZ64.js.map → promote-ZWQAL3RE.js.map} +0 -0
- /package/dist/{providers-VVT2OBXA.js.map → providers-F5GDJSYD.js.map} +0 -0
- /package/dist/{query-QVK5EN3P.js.map → query-N4EJ24LW.js.map} +0 -0
- /package/dist/{query-settings-2TNLXEL5.js.map → query-settings-RZV5ELLC.js.map} +0 -0
- /package/dist/{registry-BYIWNEFL.js.map → registry-EBYOZK3P.js.map} +0 -0
- /package/dist/{request-planner-7HEHLPA3.js.map → request-planner-KCG6QB6M.js.map} +0 -0
- /package/dist/{review-candidates-NJNMSOCX.js.map → review-candidates-3GHWVJQ3.js.map} +0 -0
- /package/dist/{routing-HCSXNUOY.js.map → routing-XULOU6BI.js.map} +0 -0
- /package/dist/{schedule-tool-LJYBLCLV.js.map → schedule-tool-ALZXDGGC.js.map} +0 -0
- /package/dist/{scheduler-74MXJLQS.js.map → scheduler-SCVCNKJC.js.map} +0 -0
- /package/dist/{seat-CAYDECW2.js.map → seat-PD7W3KAN.js.map} +0 -0
- /package/dist/{select-QUVE6RN2.js.map → select-Z3YXBGUP.js.map} +0 -0
- /package/dist/{set-enabled-BWJN4IVG.js.map → set-enabled-NJYJWDWH.js.map} +0 -0
- /package/dist/{tool-FZ4UXMON.js.map → tool-EVQBMGJV.js.map} +0 -0
- /package/dist/{tool-UC7OZWIB.js.map → tool-XH5QN6JM.js.map} +0 -0
- /package/dist/{wiki-KNSPJT2O.js.map → wiki-BPOTYAQV.js.map} +0 -0
- /package/dist/{wiki-enrich-RVRTAQQF.js.map → wiki-enrich-JCNGRYQZ.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Ge,b as Fe,c as Se}from"./chunk-SFQUP3BP.js";import{b as Te,c as Ce}from"./chunk-QOYAX2FT.js";import{a as Q,c as Ne,e as we,f as ke,g as be,i as xe,k as gt,o as ve,p as ht}from"./chunk-
|
|
1
|
+
import{a as Ge,b as Fe,c as Se}from"./chunk-SFQUP3BP.js";import{b as Te,c as Ce}from"./chunk-QOYAX2FT.js";import{a as Q,c as Ne,e as we,f as ke,g as be,i as xe,k as gt,o as ve,p as ht}from"./chunk-DCIYOPJF.js";import{a as R,b as ye}from"./chunk-7I7IEX4S.js";import{b as Le,e as _e}from"./chunk-JHCI6XCJ.js";import{e as b}from"./chunk-DSYKYZMT.js";import{z as $}from"zod";var qe=$.object({provider:$.enum(["claude-code","claude","openai","deepseek","ollama","demo","custom"]).default("claude-code"),model:$.string().optional(),apiKey:$.string().optional(),skills:$.array($.string()).default([]),output:$.object({dir:$.string().default("./generated")}).default({}),context7:$.object({enabled:$.boolean().default(!0),apiKey:$.string().optional()}).default({}),agentic:$.object({maxIterations:$.number().default(20),enabledTools:$.array($.string()).default(["create_files","ask_user","read_file","search_files","list_directory","run_command","edit_file"]),disabledTools:$.array($.string()).default([])}).default({})}),Vt=["component","page","api","website","document","script","config","skill","media","report","test","workflow","schema","email","diagram","auto"],Yt={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"};ht();ke();ke();import{existsSync as yt,promises as wt}from"fs";import K from"path";import kt from"fast-glob";var Be={"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 We(r){let e={},t=await kt.glob("**/*",{cwd:r,deep:4,ignore:["**/node_modules/**","**/dist/**","**/build/**","**/.next/**","**/target/**","**/__pycache__/**","**/vendor/**","**/.git/**"],onlyFiles:!0});for(let[s,i]of Object.entries(Be)){let c=t.find(a=>a.endsWith(s)||a===s);if(c&&i.category==="database"){let a=await Z(K.resolve(r,c));if(a){e.database={type:i.type,content:ce(a,3e3),tables:bt(a,i.type)};break}}}for(let[s,i]of Object.entries(Be)){let c=t.find(a=>a.endsWith(s)||a===s);if(c&&i.category==="api"){let a=await Z(K.resolve(r,c));if(a){e.api={type:i.type,content:ce(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 Z(K.resolve(r,s));i&&(e.api={type:"trpc",content:ce(i,3e3)})}}let o=t.find(s=>s===".env.example"||s===".env.local.example"||s===".env.template");if(o){let s=await Z(K.resolve(r,o));s&&(e.env=xt(s))}let n=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(n.length){e.models=[];for(let s of n.slice(0,5)){let i=await Z(K.resolve(r,s));i&&e.models.push({path:s,content:ce(i,2e3),type:K.extname(s).slice(1)})}}return e}function bt(r,e){if(e==="prisma"){let t=r.match(/model\s+(\w+)\s*\{/g);return t?t.map(o=>o.replace(/model\s+/,"").replace(/\s*\{/,"")):[]}return[]}function xt(r){return{variables:r.split(`
|
|
2
2
|
`).filter(o=>o.trim()&&!o.trim().startsWith("#")).map(o=>{let[n]=o.split("="),s=n.trim(),i=o.includes("=")&&o.split("=")[1]?.trim().length>0;return{key:s,required:!i}})}}async function Z(r){try{return yt(r)?await wt.readFile(r,"utf8"):null}catch{return null}}function ce(r,e){return r.length<=e?r:r.slice(0,e)+`
|
|
3
3
|
... (truncated)`}function ze(r){let e=[];if(r.database&&e.push(`## Database Schema (${r.database.type})
|
|
4
4
|
`+(r.database.tables?.length?`Tables: ${r.database.tables.join(", ")}
|
|
@@ -18,7 +18,7 @@ ${s.join(`
|
|
|
18
18
|
---
|
|
19
19
|
|
|
20
20
|
`)}`:""}var Ye={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 Pe(r,e){if(r&&r!=="auto")return r;let t=e.toLowerCase(),o=[[/\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[n,s]of o)if(n.test(t))return s;return"component"}import{existsSync as It,promises as ot}from"fs";import ue from"path";import{execa as Ct}from"execa";import{z as N}from"zod";var ee=["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","on:gitlab-pipeline","on:gitlab-issue","on:gitlab-mr","on:gitlab-note","on:github-issue","on:github-pr","on:github-push","on:n8n","on:stripe-event","on:sentry-issue","on:vercel-deployment","on:odoo-event","on:hubspot-event"],Re=["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"],Xe=N.object({name:N.string(),type:N.enum(["command","prompt","script"]),command:N.string().optional(),prompt:N.string().optional(),provider:N.enum(["claude-code","claude","openai","deepseek","ollama","custom"]).optional(),model:N.string().optional(),script:N.string().optional(),priority:N.number().default(100),enabled:N.boolean().default(!0)});ye();var Qe={"claude-sonnet":{input:3,output:15},"claude-opus":{input:15,output:75},"claude-haiku":{input:.25,output:1.25}};function St(r){let e=r.toLowerCase();return e.includes("opus")?"claude-opus":e.includes("haiku")?"claude-haiku":"claude-sonnet"}var le=class{steps=[];models=new Map;recordStep(e,t,o,n){let s=St(t),i=Qe[s]||Qe["claude-sonnet"],c=o/1e6*i.input+n/1e6*i.output;this.steps.push({step:e,model:t,inputTokens:o,outputTokens:n,cost:c,timestamp:Date.now()});let a=this.models.get(t)||{inputTokens:0,outputTokens:0,cost:0,steps:0};a.inputTokens+=o,a.outputTokens+=n,a.cost+=c,a.steps++,this.models.set(t,a)}getSummary(){let e=0,t=0,o=0;for(let s of this.steps)e+=s.inputTokens,t+=s.outputTokens,o+=s.cost;let n={};for(let[s,i]of this.models)n[s]={...i};return{totalInputTokens:e,totalOutputTokens:t,totalTokens:e+t,totalCost:o,steps:[...this.steps],models:n}}reset(){this.steps=[],this.models.clear()}},te=new le;function Tt(r,e){let t=[];if(t.push(`# Session: ${r.id}`),t.push(""),t.push(`- **Created**: ${r.createdAt}`),t.push(`- **Updated**: ${r.updatedAt}`),t.push(`- **CWD**: ${r.cwd}`),t.push(`- **Messages**: ${r.messages.length}`),t.push(`- **Tokens**: ${r.tokensUsed.toLocaleString()}`),t.push(""),r.filesGenerated.length){t.push("## Files Generated"),t.push("");for(let o of r.filesGenerated)t.push(`- \`${o}\``);t.push("")}if(r.messages.length){t.push("## Conversation"),t.push("");for(let o of r.messages){if(o.role==="system")continue;let n=o.role==="user"?"**User**":"**Assistant**";t.push(`### ${n}`),t.push(""),o.role,t.push(o.content),t.push("")}}if(e){if(t.push("## Cost Summary"),t.push(""),t.push(`- **Total tokens**: ${e.totalTokens.toLocaleString()}`),t.push(` - Input: ${e.totalInputTokens.toLocaleString()}`),t.push(` - Output: ${e.totalOutputTokens.toLocaleString()}`),t.push(`- **Total cost**: $${e.totalCost.toFixed(4)}`),t.push(""),Object.keys(e.models).length){t.push("### Per Model"),t.push(""),t.push("| Model | Input | Output | Cost | Steps |"),t.push("|-------|-------|--------|------|-------|");for(let[o,n]of Object.entries(e.models))t.push(`| ${o} | ${n.inputTokens.toLocaleString()} | ${n.outputTokens.toLocaleString()} | $${n.cost.toFixed(4)} | ${n.steps} |`);t.push("")}if(e.steps.length){t.push("### Per Step"),t.push(""),t.push("| Step | Model | Input | Output | Cost |"),t.push("|------|-------|-------|--------|------|");for(let o of e.steps)t.push(`| ${o.step} | ${o.model} | ${o.inputTokens.toLocaleString()} | ${o.outputTokens.toLocaleString()} | $${o.cost.toFixed(4)} |`);t.push("")}}return t.join(`
|
|
21
|
-
`)}ke();var oe=class{hooks=new Map;register(e,t){if(!t.enabled)return;let o=this.createHandler(t),n={event:e,definition:t,handler:o},s=this.hooks.get(e)||[];s.push(n),s.sort((i,c)=>i.definition.priority-c.definition.priority),this.hooks.set(e,s)}async execute(e,t){let o=this.hooks.get(e);if(!o?.length)return{};let n=Re.includes(e),s={};for(let i of o){let c=Date.now();try{let a=await i.handler({...t,...s}),p=Date.now()-c;if(a.modified&&(s={...s,...a.modified}),n&&a.blocked)return b.hook(i.definition.name,p,"blocked"),{blocked:!0,message:a.message||`Blocked by hook: ${i.definition.name}`,modified:s};b.hook(i.definition.name,p,"ok")}catch(a){let p=Date.now()-c;if(b.hook(i.definition.name,p,`error: ${a.message}`),R.warn(`Hook "${i.definition.name}" failed: ${a.message}`),n)return{blocked:!0,message:`Hook "${i.definition.name}" errored: ${a.message}`}}}return{modified:Object.keys(s).length?s:void 0}}registerHandler(e,t,o,n=100){let i={event:e,definition:{name:t,type:"script",priority:n,enabled:!0},handler:o},c=this.hooks.get(e)||[];c.push(i),c.sort((a,p)=>a.definition.priority-p.definition.priority),this.hooks.set(e,c)}has(e){return!!this.hooks.get(e)?.length}clear(){this.hooks.clear()}size(){let e=0;for(let t of this.hooks.values())e+=t.length;return e}createHandler(e){switch(e.type){case"command":return this.createCommandHandler(e);case"script":return this.createScriptHandler(e);case"prompt":return this.createPromptHandler(e);default:throw new Error(`Unknown hook type: ${e.type}`)}}createCommandHandler(e){return async t=>{if(!e.command)return{};let o=e.command;o=o.replace(/\{\{(\w+)\}\}/g,(s,i)=>String(t[i]??""));let n=await Ct("sh",["-c",o],{cwd:t.cwd||process.cwd(),reject:!1,timeout:6e4,env:process.env});return n.exitCode!==0?{blocked:!0,message:n.stderr||n.stdout||`Command hook "${e.name}" failed`}:{}}}createScriptHandler(e){return async t=>{if(!e.script)return{};let n=await import(e.script.startsWith("/")?e.script:`${t.cwd||process.cwd()}/${e.script}`),s=n.default||n.handler||n;return typeof s=="function"?await s(t):{}}}createPromptHandler(e){return async t=>{if(!e.prompt)return{};let o=e.provider||Q()?.provider||"claude-code",n=Ne();if(!n&&o!=="claude-code")return R.warn(`Prompt hook "${e.name}" skipped: no credentials available for provider "${o}"`),{};try{let{createProvider:s}=await import("./providers-
|
|
21
|
+
`)}ke();var oe=class{hooks=new Map;register(e,t){if(!t.enabled)return;let o=this.createHandler(t),n={event:e,definition:t,handler:o},s=this.hooks.get(e)||[];s.push(n),s.sort((i,c)=>i.definition.priority-c.definition.priority),this.hooks.set(e,s)}async execute(e,t){let o=this.hooks.get(e);if(!o?.length)return{};let n=Re.includes(e),s={};for(let i of o){let c=Date.now();try{let a=await i.handler({...t,...s}),p=Date.now()-c;if(a.modified&&(s={...s,...a.modified}),n&&a.blocked)return b.hook(i.definition.name,p,"blocked"),{blocked:!0,message:a.message||`Blocked by hook: ${i.definition.name}`,modified:s};b.hook(i.definition.name,p,"ok")}catch(a){let p=Date.now()-c;if(b.hook(i.definition.name,p,`error: ${a.message}`),R.warn(`Hook "${i.definition.name}" failed: ${a.message}`),n)return{blocked:!0,message:`Hook "${i.definition.name}" errored: ${a.message}`}}}return{modified:Object.keys(s).length?s:void 0}}registerHandler(e,t,o,n=100){let i={event:e,definition:{name:t,type:"script",priority:n,enabled:!0},handler:o},c=this.hooks.get(e)||[];c.push(i),c.sort((a,p)=>a.definition.priority-p.definition.priority),this.hooks.set(e,c)}has(e){return!!this.hooks.get(e)?.length}clear(){this.hooks.clear()}size(){let e=0;for(let t of this.hooks.values())e+=t.length;return e}createHandler(e){switch(e.type){case"command":return this.createCommandHandler(e);case"script":return this.createScriptHandler(e);case"prompt":return this.createPromptHandler(e);default:throw new Error(`Unknown hook type: ${e.type}`)}}createCommandHandler(e){return async t=>{if(!e.command)return{};let o=e.command;o=o.replace(/\{\{(\w+)\}\}/g,(s,i)=>String(t[i]??""));let n=await Ct("sh",["-c",o],{cwd:t.cwd||process.cwd(),reject:!1,timeout:6e4,env:process.env});return n.exitCode!==0?{blocked:!0,message:n.stderr||n.stdout||`Command hook "${e.name}" failed`}:{}}}createScriptHandler(e){return async t=>{if(!e.script)return{};let n=await import(e.script.startsWith("/")?e.script:`${t.cwd||process.cwd()}/${e.script}`),s=n.default||n.handler||n;return typeof s=="function"?await s(t):{}}}createPromptHandler(e){return async t=>{if(!e.prompt)return{};let o=e.provider||Q()?.provider||"claude-code",n=Ne();if(!n&&o!=="claude-code")return R.warn(`Prompt hook "${e.name}" skipped: no credentials available for provider "${o}"`),{};try{let{createProvider:s}=await import("./providers-F5GDJSYD.js"),i=s(o,n?.token),c=e.prompt;c=c.replace(/\{\{(\w+)\}\}/g,(m,I)=>String(t[I]??""));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).
|
|
22
22
|
|
|
23
23
|
Response format:
|
|
24
24
|
{"action": "allow", "message": "optional explanation"}
|
|
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
|
|
|
48
48
|
... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
|
|
49
49
|
${c}`,is_error:!0}:{tool_use_id:e.id,content:c||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,n=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.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(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:n,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 re.readFile(n,"utf8"),c=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),c.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):c.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await re.writeFile(n,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:n,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
|
|
50
50
|
${c.join(`
|
|
51
|
-
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-
|
|
51
|
+
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-EBYOZK3P.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
|
|
52
52
|
|
|
53
53
|
${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.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||""),o=e.input.options,n=t;return o?.length&&(n+=`
|
|
54
54
|
Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:n}}};async function Ae(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,cwd:s,maxIterations:i=20,enabledTools:c,interactive:a=!0,overwrite:p=!1,dryRun:l=!1,onProgress:d,abortSignal:u}=r,m=u?{...n,abortSignal:u}:n;if(!e.generateRaw)return dt(r);let I=new se(s,{interactive:a,overwrite:p,dryRun:l,acmeContext:r.acmeContext,abortSignal:u}),D=be(c);if(r.acmeContext)for(let g of at)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(r.mcpTools?.length)for(let g of r.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,A=0,O="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),b.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let T=null,U=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?T=x.result:x.type==="error"&&(U=x.error);if(U&&!T)throw new Error(U);if(!T)throw new Error("generateRawStream returned no raw_result event");g=T,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(T){if(T.message?.includes("not available"))return dt(r);throw T}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,A+=g.usage.output_tokens;let P=g._streamedText;for(let T of g.content)T.type==="text"&&(O+=T.text,P===void 0&&d?.({type:"text_delta",text:T.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let T=g.content.filter(v=>v.type==="tool_use");if(T.length===0)break;C.push({role:"assistant",content:g.content});let U=[];for(let v of T){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),b.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&r.mcpDispatch){let h=await r.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),U.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:U}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:O,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:A||void 0,iterations:_}}async function dt(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,maxIterations:s=5}=r,c=[{role:"system",content:t+`
|
|
@@ -65,7 +65,7 @@ ${D}`:"")}),c.push({role:"user",content:"Continue generating the remaining files
|
|
|
65
65
|
`))>=0;){let a=n.slice(0,c);n=n.slice(c+2);let p=[];for(let u of a.split(`
|
|
66
66
|
`)){let m=u.replace(/\r$/,"");m.startsWith("data:")&&p.push(m.slice(5).trim())}if(!p.length)continue;let l=p.join(`
|
|
67
67
|
`);if(!l||l==="[DONE]")continue;let d;try{d=JSON.parse(l)}catch{continue}if(d&&d.id===e)return d}}}finally{try{t.cancel().catch(()=>{})}catch{}}throw new Error(`SSE stream ended without a response for id=${e}`)}var Ue=class{constructor(e,t){this.name=e;this.transport=Wt(t)?new Ie(e,t):new je(e,t)}transport;async initialize(){await this.transport.request("initialize",{protocolVersion:Lt,capabilities:{},clientInfo:{name:"agentx-orchestrator",version:"0.1.0"}},ut),this.transport.notify("notifications/initialized")}async listTools(){return((await this.transport.request("tools/list",{},ut)).tools??[]).map(t=>({name:t.name,description:t.description??"",input_schema:t.inputSchema??{type:"object",properties:{}}}))}async callTool(e,t){let o=await this.transport.request("tools/call",{name:e,arguments:t??{}},qt),n=[];for(let s of o.content??[])s?.type==="text"&&typeof s.text=="string"?n.push(s.text):n.push(JSON.stringify(s));return{content:n.join(`
|
|
68
|
-
`)||"(no output)",isError:o.isError}}close(){this.transport.close()}};async function He(r){let e=new Map,t=[],o=new Map;for(let[n,s]of Object.entries(r)){let i=new Ue(n,s);try{await i.initialize();let c=await i.listTools();for(let a of c){let p=`${Bt}${n}__${a.name}`;t.push({name:p,description:a.description||`${n}.${a.name}`,input_schema:a.input_schema}),o.set(p,{client:i,remote:a.name})}e.set(n,i)}catch(c){b.context("mcp",`${n}: skipped \u2014 ${c.message}`),i.close()}}return{tools:t,async dispatch(n,s){let i=o.get(n);if(!i)return{content:`Unknown MCP tool: ${n}`,isError:!0};try{return await i.client.callTool(i.remote,s)}catch(c){return{content:`MCP call failed: ${c.message}`,isError:!0}}},close(){for(let n of e.values())n.close()}}}var he=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 mt(r,e,t){let o=qe.parse(t||{}),n=new ne(r);await n.load();let[s,i,c]=await Promise.all([Ge(r),We(r),Le(r)]),a="";if(o.context7.enabled)try{a=await Ve(s,e,o.context7.apiKey)}catch{}let p=n.buildMemoryContext(e),l=Ee(r);return b.context("memory",p?"loaded":"empty"),b.context("instructions",l?"loaded from project":"none"),{techStack:s,schemas:i,skills:c,docs:a,config:o,memoryContext:p,projectInstructions:l}}async function Zn(r){let{task:e,cwd:t,overwrite:o=!1,dryRun:n=!1,provider:s="claude-code",model:i,apiKey:c,context7:a=!0,interactive:p=!0}=r,l=e;if(f.has("pre:prompt")){let h=await f.execute("pre:prompt",{event:"pre:prompt",task:e,cwd:t});if(h.blocked)throw new Error(h.message||"Blocked by pre:prompt hook");h.modified?.task&&(l=String(h.modified.task))}if(f.has("pre:generate")){let h=await f.execute("pre:generate",{event:"pre:generate",task:l,cwd:t});if(h.blocked)throw new Error(h.message||"Blocked by pre:generate hook")}R.info("Analyzing project...");let d=await mt(t,l,{provider:s,context7:{enabled:a,apiKey:c}}),u=Pe(r.outputType,l);R.info(`Output type: ${u}`);let m=_e(d.skills,l,u);m.length&&R.info(`Loaded ${m.length} relevant skill(s): ${m.map(h=>h.skill.frontmatter.name).join(", ")}`);let I=ft(d,u,m.map(h=>h.skill));if(!await we(c))throw new Error("No credentials configured. Run `agentx model` to set up.");let E=ve(s,c,r.providerOpts||{}),C=i||Q()?.model,B=[...r.sessionMessages||[],{role:"user",content:l}];R.info("Generating...");let G=Oe(E),F=r.maxSteps??(G?20:5),A=r.mcpServers&&Object.keys(r.mcpServers).length>0?await He(r.mcpServers):void 0,O;try{O=await Ae({provider:E,systemPrompt:I,messages:[{role:"system",content:I},...B],providerOptions:{model:C,maxTokens:8192},cwd:t,maxIterations:F,enabledTools:d.config.agentic.enabledTools.filter(h=>!d.config.agentic.disabledTools.includes(h)),interactive:p,overwrite:o,dryRun:n,acmeContext:r.acmeContext,abortSignal:r.abortSignal,mcpTools:A?.tools,mcpDispatch:A?A.dispatch.bind(A):void 0,onProgress:h=>{h.type==="iteration_start"&&h.iteration>1&&R.info(`Step ${h.iteration}/${F}...`),h.type==="tool_call"&&b.step(0,`Tool: ${h.name}`)}})}finally{A?.close()}if(O.tokensUsed){let h=C||"claude-sonnet-4-20250514",V=Math.round(O.tokensUsed*.3),Y=O.tokensUsed-V;te.recordStep(1,h,V,Y)}let{content:j}=O,{followUp:_,tokensUsed:g,inputTokens:M,outputTokens:P}=O;if(O.iterations>1&&R.info(`Completed in ${O.iterations} step(s)`),f.has("post:response")){let h=await f.execute("post:response",{event:"post:response",content:j,task:l,cwd:t});if(h.blocked)throw new Error(h.message||"Blocked by post:response hook");h.modified?.content&&(j=String(h.modified.content))}if(_&&p)return{files:{written:[],skipped:[],errors:[]},content:j,outputType:u,followUp:_,tokensUsed:g,inputTokens:M,outputTokens:P};let T=new Map;for(let h of O.files)T.set(h.path,h);let U=fe(u,d.techStack,r.outputDir),v=await me(Array.from(T.values()),{cwd:t,overwrite:o,dryRun:n,outputDir:U}),x;if(r.heal!==!1&&!n&&v.written.length>0){let{HealEngine:h}=await import("./heal-
|
|
68
|
+
`)||"(no output)",isError:o.isError}}close(){this.transport.close()}};async function He(r){let e=new Map,t=[],o=new Map;for(let[n,s]of Object.entries(r)){let i=new Ue(n,s);try{await i.initialize();let c=await i.listTools();for(let a of c){let p=`${Bt}${n}__${a.name}`;t.push({name:p,description:a.description||`${n}.${a.name}`,input_schema:a.input_schema}),o.set(p,{client:i,remote:a.name})}e.set(n,i)}catch(c){b.context("mcp",`${n}: skipped \u2014 ${c.message}`),i.close()}}return{tools:t,async dispatch(n,s){let i=o.get(n);if(!i)return{content:`Unknown MCP tool: ${n}`,isError:!0};try{return await i.client.callTool(i.remote,s)}catch(c){return{content:`MCP call failed: ${c.message}`,isError:!0}}},close(){for(let n of e.values())n.close()}}}var he=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 mt(r,e,t){let o=qe.parse(t||{}),n=new ne(r);await n.load();let[s,i,c]=await Promise.all([Ge(r),We(r),Le(r)]),a="";if(o.context7.enabled)try{a=await Ve(s,e,o.context7.apiKey)}catch{}let p=n.buildMemoryContext(e),l=Ee(r);return b.context("memory",p?"loaded":"empty"),b.context("instructions",l?"loaded from project":"none"),{techStack:s,schemas:i,skills:c,docs:a,config:o,memoryContext:p,projectInstructions:l}}async function Zn(r){let{task:e,cwd:t,overwrite:o=!1,dryRun:n=!1,provider:s="claude-code",model:i,apiKey:c,context7:a=!0,interactive:p=!0}=r,l=e;if(f.has("pre:prompt")){let h=await f.execute("pre:prompt",{event:"pre:prompt",task:e,cwd:t});if(h.blocked)throw new Error(h.message||"Blocked by pre:prompt hook");h.modified?.task&&(l=String(h.modified.task))}if(f.has("pre:generate")){let h=await f.execute("pre:generate",{event:"pre:generate",task:l,cwd:t});if(h.blocked)throw new Error(h.message||"Blocked by pre:generate hook")}R.info("Analyzing project...");let d=await mt(t,l,{provider:s,context7:{enabled:a,apiKey:c}}),u=Pe(r.outputType,l);R.info(`Output type: ${u}`);let m=_e(d.skills,l,u);m.length&&R.info(`Loaded ${m.length} relevant skill(s): ${m.map(h=>h.skill.frontmatter.name).join(", ")}`);let I=ft(d,u,m.map(h=>h.skill));if(!await we(c))throw new Error("No credentials configured. Run `agentx model` to set up.");let E=ve(s,c,r.providerOpts||{}),C=i||Q()?.model,B=[...r.sessionMessages||[],{role:"user",content:l}];R.info("Generating...");let G=Oe(E),F=r.maxSteps??(G?20:5),A=r.mcpServers&&Object.keys(r.mcpServers).length>0?await He(r.mcpServers):void 0,O;try{O=await Ae({provider:E,systemPrompt:I,messages:[{role:"system",content:I},...B],providerOptions:{model:C,maxTokens:8192},cwd:t,maxIterations:F,enabledTools:d.config.agentic.enabledTools.filter(h=>!d.config.agentic.disabledTools.includes(h)),interactive:p,overwrite:o,dryRun:n,acmeContext:r.acmeContext,abortSignal:r.abortSignal,mcpTools:A?.tools,mcpDispatch:A?A.dispatch.bind(A):void 0,onProgress:h=>{h.type==="iteration_start"&&h.iteration>1&&R.info(`Step ${h.iteration}/${F}...`),h.type==="tool_call"&&b.step(0,`Tool: ${h.name}`)}})}finally{A?.close()}if(O.tokensUsed){let h=C||"claude-sonnet-4-20250514",V=Math.round(O.tokensUsed*.3),Y=O.tokensUsed-V;te.recordStep(1,h,V,Y)}let{content:j}=O,{followUp:_,tokensUsed:g,inputTokens:M,outputTokens:P}=O;if(O.iterations>1&&R.info(`Completed in ${O.iterations} step(s)`),f.has("post:response")){let h=await f.execute("post:response",{event:"post:response",content:j,task:l,cwd:t});if(h.blocked)throw new Error(h.message||"Blocked by post:response hook");h.modified?.content&&(j=String(h.modified.content))}if(_&&p)return{files:{written:[],skipped:[],errors:[]},content:j,outputType:u,followUp:_,tokensUsed:g,inputTokens:M,outputTokens:P};let T=new Map;for(let h of O.files)T.set(h.path,h);let U=fe(u,d.techStack,r.outputDir),v=await me(Array.from(T.values()),{cwd:t,overwrite:o,dryRun:n,outputDir:U}),x;if(r.heal!==!1&&!n&&v.written.length>0){let{HealEngine:h}=await import("./heal-ZS56MC4A.js");x=await new h(t,{enabled:!0,testCommand:r.healConfig?.testCommand,buildCommand:r.healConfig?.buildCommand,lintCommand:r.healConfig?.lintCommand,maxAttempts:r.healConfig?.maxAttempts??3,provider:s,model:C,apiKey:c}).detectAndHeal(v.written,l),!x.healed&&x.error&&await f.execute("on:error",{event:"on:error",error:new Error(x.error),task:l,cwd:t})}return f.has("post:generate")&&await f.execute("post:generate",{event:"post:generate",task:l,content:j,cwd:t}),{files:v,content:j,outputType:u,tokensUsed:g,inputTokens:M,outputTokens:P,healResult:x}}async function*er(r){let{task:e,cwd:t,overwrite:o=!1,dryRun:n=!1,provider:s="claude-code",model:i,apiKey:c,context7:a=!0,interactive:p=!0}=r,l=e;if(f.has("pre:prompt")){let y=await f.execute("pre:prompt",{event:"pre:prompt",task:e,cwd:t});if(y.blocked){yield{type:"error",error:y.message||"Blocked by pre:prompt hook"};return}y.modified?.task&&(l=String(y.modified.task))}if(f.has("pre:generate")){let y=await f.execute("pre:generate",{event:"pre:generate",task:l,cwd:t});if(y.blocked){yield{type:"error",error:y.message||"Blocked by pre:generate hook"};return}}let d=await mt(t,l,{provider:s,context7:{enabled:a,apiKey:c}}),u=Pe(r.outputType,l);yield{type:"context_ready",outputType:u};let m=_e(d.skills,l,u),I=ft(d,u,m.map(y=>y.skill));if(!await we(c)){yield{type:"error",error:"No credentials configured. Run `agentx model` to set up."};return}let E=ve(s,c,r.providerOpts||{}),C=i||Q()?.model,B=Oe(E),G=r.maxSteps??(B?20:5),F=[...r.sessionMessages||[],{role:"user",content:l}];if(B){let y=new he,S,k,H;if(r.mcpServers&&Object.keys(r.mcpServers).length>0)try{H=await He(r.mcpServers)}catch(w){yield{type:"error",error:`MCP pool startup failed: ${w.message}`};return}let ie=(async()=>{try{S=await Ae({provider:E,systemPrompt:I,messages:[{role:"system",content:I},...F],providerOptions:{model:C,maxTokens:8192},cwd:t,maxIterations:G,abortSignal:r.abortSignal,enabledTools:d.config.agentic.enabledTools.filter(w=>!d.config.agentic.disabledTools.includes(w)),interactive:p,overwrite:o,dryRun:n,acmeContext:r.acmeContext,mcpTools:H?.tools,mcpDispatch:H?H.dispatch.bind(H):void 0,onProgress:w=>{w.type==="text_delta"&&y.push({type:"text_delta",text:w.text}),w.type==="thinking_delta"&&y.push({type:"thinking_delta",text:w.text}),w.type==="iteration_start"&&y.push({type:"iteration",iteration:w.iteration}),w.type==="tool_call"&&y.push({type:"tool_call",name:w.name,id:w.id}),w.type==="tool_result"&&y.push({type:"tool_result",name:w.name,id:w.id,is_error:w.is_error}),w.type==="files_created"&&y.push({type:"step_complete",step:0,filesCount:w.files.length})}})}catch(w){k=w}finally{H?.close(),y.close()}})();for await(let w of y)yield w;if(await ie,k){yield{type:"error",error:k instanceof Error?k.message:String(k)};return}if(!S){yield{type:"error",error:"Agentic loop failed without a result"};return}yield{type:"done",result:{content:S.content,files:S.files,tokensUsed:S.tokensUsed,followUp:S.followUp}};let{content:L}=S;if(f.has("post:response")){let w=await f.execute("post:response",{event:"post:response",content:L,task:l,cwd:t});if(w.blocked){yield{type:"error",error:w.message||"Blocked by post:response hook"};return}w.modified?.content&&(L=String(w.modified.content))}if(S.followUp&&p){yield{type:"generate_result",result:{files:{written:[],skipped:[],errors:[]},content:L,outputType:u,followUp:S.followUp,tokensUsed:S.tokensUsed,inputTokens:S.inputTokens,outputTokens:S.outputTokens}};return}let ae=new Map;for(let w of S.files)ae.set(w.path,w);let De=fe(u,d.techStack,r.outputDir),z=await me(Array.from(ae.values()),{cwd:t,overwrite:o,dryRun:n,outputDir:De}),J;if(r.heal!==!1&&!n&&z.written.length>0){let{HealEngine:w}=await import("./heal-ZS56MC4A.js");J=await new w(t,{enabled:!0,testCommand:r.healConfig?.testCommand,buildCommand:r.healConfig?.buildCommand,lintCommand:r.healConfig?.lintCommand,maxAttempts:r.healConfig?.maxAttempts??3,provider:s,model:C,apiKey:c}).detectAndHeal(z.written,l)}f.has("post:generate")&&await f.execute("post:generate",{event:"post:generate",task:l,content:L,cwd:t}),yield{type:"generate_result",result:{files:z,content:L,outputType:u,tokensUsed:S.tokensUsed,inputTokens:S.inputTokens,outputTokens:S.outputTokens,healResult:J}};return}let A=[{role:"system",content:I},...F],O=[],j=0,_="",g,M=0;M++,b.step(M,`Starting generation (model: ${C||"default"})`);let P;if(E.stream){let y="",S;for await(let k of E.stream(A,{model:C,maxTokens:8192}))yield k,k.type==="text_delta"&&(y+=k.text),k.type==="done"&&(S=k.result);P=S||{content:y,files:[],tokensUsed:0}}else{let y=await E.generate(A,{model:C,maxTokens:8192});y.content&&(yield{type:"text_delta",text:y.content}),yield{type:"done",result:y},P=y}j+=P.tokensUsed||0,_=P.content;let T=P.tokensUsed||0,U=C||"claude-sonnet-4-20250514",v=Math.round(T*.3),x=T-v;if(te.recordStep(M,U,v,x),b.api("generate",U,T),b.step(M,`Generated ${P.files.length} file(s), ${T} tokens`),P.files.length&&O.push(...P.files),P.followUp&&(g=P.followUp),yield{type:"step_complete",step:M,filesCount:P.files.length},!g&&(_.includes("[CONTINUE]")||_.includes("Next, I'll")||_.includes("Now let me")||_.includes("I'll also generate"))&&P.files.length>0){let S=P.files.map(k=>`Created: ${k.path}${k.description?` \u2014 ${k.description}`:""}`).join(`
|
|
69
69
|
`);for(A.push({role:"assistant",content:_+(S?`
|
|
70
70
|
|
|
71
71
|
Files created:
|
|
@@ -73,7 +73,7 @@ ${S}`:"")}),A.push({role:"user",content:"Continue generating the remaining files
|
|
|
73
73
|
`);A.push({role:"assistant",content:k.content+(z?`
|
|
74
74
|
|
|
75
75
|
Files created:
|
|
76
|
-
${z}`:"")}),A.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(f.has("post:response")){let y=await f.execute("post:response",{event:"post:response",content:_,task:l,cwd:t});if(y.blocked){yield{type:"error",error:y.message||"Blocked by post:response hook"};return}y.modified?.content&&(_=String(y.modified.content))}if(g&&p){yield{type:"generate_result",result:{files:{written:[],skipped:[],errors:[]},content:_,outputType:u,followUp:g,tokensUsed:j}};return}let h=new Map;for(let y of O)h.set(y.path,y);let V=fe(u,d.techStack,r.outputDir),Y=await me(Array.from(h.values()),{cwd:t,overwrite:o,dryRun:n,outputDir:V}),X;if(r.heal!==!1&&!n&&Y.written.length>0){let{HealEngine:y}=await import("./heal-
|
|
76
|
+
${z}`:"")}),A.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(f.has("post:response")){let y=await f.execute("post:response",{event:"post:response",content:_,task:l,cwd:t});if(y.blocked){yield{type:"error",error:y.message||"Blocked by post:response hook"};return}y.modified?.content&&(_=String(y.modified.content))}if(g&&p){yield{type:"generate_result",result:{files:{written:[],skipped:[],errors:[]},content:_,outputType:u,followUp:g,tokensUsed:j}};return}let h=new Map;for(let y of O)h.set(y.path,y);let V=fe(u,d.techStack,r.outputDir),Y=await me(Array.from(h.values()),{cwd:t,overwrite:o,dryRun:n,outputDir:V}),X;if(r.heal!==!1&&!n&&Y.written.length>0){let{HealEngine:y}=await import("./heal-ZS56MC4A.js");X=await new y(t,{enabled:!0,testCommand:r.healConfig?.testCommand,buildCommand:r.healConfig?.buildCommand,lintCommand:r.healConfig?.lintCommand,maxAttempts:r.healConfig?.maxAttempts??3,provider:s,model:C,apiKey:c}).detectAndHeal(Y.written,l),!X.healed&&X.error&&await f.execute("on:error",{event:"on:error",error:new Error(X.error),task:l,cwd:t})}f.has("post:generate")&&await f.execute("post:generate",{event:"post:generate",task:l,content:_,cwd:t}),yield{type:"generate_result",result:{files:Y,content:_,outputType:u,tokensUsed:j,healResult:X}}}function ft(r,e,t){let o=[];o.push(`You are agentx, an agentic code generation tool. You generate high-quality, production-ready output for any tech stack.
|
|
77
77
|
|
|
78
78
|
Your primary tool is \`create_files\` \u2014 use it to output all generated code, documents, and configs as files.
|
|
79
79
|
If the request is ambiguous or you need critical information to proceed correctly, use \`ask_user\` to ask a clarifying question.
|
|
@@ -123,4 +123,4 @@ ${r.projectInstructions}`),r.memoryContext&&o.push(r.memoryContext),o.push(`# Ou
|
|
|
123
123
|
Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
|
|
124
124
|
|
|
125
125
|
`)}export{qe as a,Vt as b,Yt as c,We as d,ze as e,Ve as f,Ye as g,Pe as h,ee as i,Re as j,le as k,te as l,Tt as m,oe as n,Mt as o,f as p,et as q,tt as r,Me as s,de as t,W as u,ne as v,it as w,Ee as x,$e as y,se as z,mt as A,Zn as B,er as C};
|
|
126
|
-
//# sourceMappingURL=chunk-
|
|
126
|
+
//# sourceMappingURL=chunk-5PEXL5LD.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{lb as m,ub as b}from"./chunk-NKCS6EZ7.js";b();function w(t){let e=typeof t.node=="string"?t.node:"",n=typeof t.token=="string"?t.token:"";if(!e||!n)try{let o=m(t.config);e||(e=o.dashboard?.daemonUrl||""),n||(n=o.dashboard?.token||"")}catch{}return e||(e="http://localhost:18800"),{baseUrl:e.replace(/\/+$/,""),token:n}}async function d(t,e,n){let o={Accept:"application/json"};t.token&&(o.Authorization=`Bearer ${t.token}`);let r=await fetch(`${t.baseUrl}${e}`,{headers:o,signal:n});if(!r.ok)throw new Error(`GET ${e} \u2192 HTTP ${r.status}`);return await r.json()}function R(t,e){return d(t,"/agents",e)}async function S(t,e){return(await d(t,"/api/processes",e)).processes??[]}function P(t,e){return d(t,"/crons",e)}async function h(t,e,n,o){let r={Accept:"application/json","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(n),signal:o}),a=await s.text(),i;try{i=a?JSON.parse(a):{}}catch{i={raw:a}}if(!s.ok)throw new Error(i?.error||`POST ${e} \u2192 HTTP ${s.status}`);return i}function A(t,e,n="tui"){return h(t,"/api/processes/kill",{...e,reason:n})}function C(t,e,n,o){return h(t,"/task",{agent:e,message:n,context:o??{channel:"tui",chatId:"tui:operator"}})}async function $(t,e,n,o={}){let r={Accept:"text/event-stream","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}/task`,{method:"POST",headers:r,body:JSON.stringify({agent:e,message:n,stream:!0,context:{channel:o.channel??"chat-cli",chatId:o.chatId??"chat-cli:operator"}}),signal:o.signal});if(!s.ok||!s.body){let g=await s.text().catch(()=>"");throw new Error(`POST /task (stream) \u2192 HTTP ${s.status}${g?`: ${g.slice(0,200)}`:""}`)}let a=s.body.getReader(),i=new TextDecoder,u={content:""},c="";try{for(;;){let{done:g,value:p}=await a.read();if(g)break;c+=i.decode(p,{stream:!0});let l;for(;(l=c.indexOf(`
|
|
2
2
|
|
|
3
3
|
`))>=0;){let k=c.slice(0,l);c=c.slice(l+2);let f=x(k);f&&T(f,o,u)}}}finally{try{a.releaseLock()}catch{}}return u}function T(t,e,n){let{event:o,data:r}=t;switch(o){case"text":r?.text&&(n.content+=r.text,e.onText?.(r.text));break;case"thinking":r?.text&&e.onThinking?.(r.text);break;case"tool":e.onTool?.(r);break;case"done":typeof r?.content=="string"&&(n.content=r.content),n.usage=r?.usage,n.duration=r?.duration;break;case"error":n.error=r?.error,n.errorKind=r?.errorKind;break}}function x(t){let e="message",n="";for(let r of t.split(`
|
|
4
4
|
`))r.startsWith("event: ")?e=r.slice(7).trim():r.startsWith("data: ")&&(n=r.slice(6));if(!n)return null;let o;try{o=JSON.parse(n)}catch{o=n}return{event:e,data:o}}export{w as a,R as b,S as c,P as d,A as e,C as f,$ as g};
|
|
5
|
-
//# sourceMappingURL=chunk-
|
|
5
|
+
//# sourceMappingURL=chunk-5QI7XFTA.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as w,b as y,c as x}from"./chunk-SFQUP3BP.js";import{o as g,p as C}from"./chunk-
|
|
1
|
+
import{a as w,b as y,c as x}from"./chunk-SFQUP3BP.js";import{o as g,p as C}from"./chunk-DCIYOPJF.js";C();import{existsSync as d,promises as h}from"fs";import c from"path";import{execa as b}from"execa";var k={enabled:!0,maxAttempts:3,provider:"claude-code"},v=class{constructor(e,r,i){this.cwd=e;this.config={...k,...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 b(i,t,{cwd:this.cwd,timeout:6e4,reject:!0})}catch(i){let t=i.stderr||"",n=i.stdout||"",s=i.message||"";return F(`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-
|
|
32
|
+
//# sourceMappingURL=chunk-BAXGL6TY.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{B as N,D as k,F as O,I,s as R,v as x}from"./chunk-
|
|
1
|
+
import{B as N,D as k,F as O,I,s as R,v as x}from"./chunk-PIJ6ECBC.js";import{a as E}from"./chunk-OSH2PEBH.js";import{lb as j,ub as F}from"./chunk-NKCS6EZ7.js";F();import{Command as X}from"commander";import f from"chalk";import{execFileSync as m}from"child_process";import{accessSync as W,constants as M,existsSync as w,readFileSync as b,readdirSync as C,statSync as B}from"fs";import{join as H,resolve as y}from"path";import{homedir as z}from"os";import{createRequire as G}from"module";var T="Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.";async function P(t={}){let n=t.helper===void 0?N():t.helper,e=k({},{platform:t.platform,io:{capture:t.run,helper:n}}).banner;if(!e)return{state:"unsupported",message:"Desktop banners are only shown on a Mac."};let i=await e.status();return i==="missing"?{state:"missing",message:"AgentX Helper is not installed, so banners come from Script Editor and show its icon.",fix:'Run agentx desktop install, then run agentx notify "Hello" --title "Test" and click Allow.'}:i==="outdated"?{state:"outdated",path:n,message:"AgentX Helper is too old to report whether it may notify.",fix:"Run agentx desktop install to update it."}:i==="not-asked"?{state:"not-asked",path:n,message:"macOS has not asked yet whether AgentX Helper may notify; banners show the Script Editor icon until it does.",fix:'Run agentx notify "Hello" --title "Test" and click Allow when macOS asks.'}:i==="not-allowed"?{state:"not-allowed",path:n,message:"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.",fix:T}:i==="hidden"?{state:"hidden",path:n,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:T}:{state:"ready",path:n,message:"AgentX Helper posts banners with the AgentX icon."}}async function Z(t={}){let n=[];await Q(n),Y(n);let e=ee(n);return e&&te(n,e),e&&se(n,e),e&&re(n,e),e&&ae(n,e),e&&ie(n,e),e&&ce(n,e),e&&await J(n,e),e&&U(n,e),e&&await K(n,e),e&&V(n,e),t.running!==!1&&e&&await de(n,e),{checks:n,summary:D(n)}}var Ne=new X().name("doctor").description("pre-flight health check: Node, config, credentials, daemon").option("--no-running","skip the live daemon probe").option("--json","emit machine-readable JSON (stable shape for CI)").action(async t=>{let{checks:n,summary:e}=await Z({running:t.running!==!1});t.json?process.stdout.write(JSON.stringify({checks:n,summary:e},null,2)+`
|
|
2
2
|
`):ue(n),process.exit(e.errors>0?1:0)});async function J(t,n,e=P){if(!O(n.notifications?.local).banner)return;let i=await e();i.state!=="unsupported"&&t.push({severity:i.state==="ready"?"ok":"warn",group:"Notifications",title:i.message,detail:i.path,fix:i.fix})}async function K(t,n,e){let i;try{i=await(e??k(n)).describe()}catch(s){t.push({severity:"warn",group:"Native",title:"Native apps: could not be read",detail:s?.message??String(s)});return}let o=["tasks","notes","banner","sound","focus"].filter(s=>i[s]);t.push({severity:"ok",group:"Native",title:i.os==="none"?"Native apps: none on this machine":`Native apps (${i.os}): ${o.join(", ")||"nothing available"}`,detail:i.problems.join(" ")||void 0})}function V(t,n,e=process.cwd(),i=k(n)){let o=n.native?.mirror;if(!o?.enabled)return;if(!i.tasks){t.push({severity:"warn",group:"Native",title:"Reminders mirror is on, but this machine has no task app",detail:"native.mirror.enabled is set; nothing is mirrored here.",fix:"Turn it on on the machine that holds the owner's cards (the Mac), or set native.mirror.enabled to false here."});return}let s=I(e),a=Object.values(s.items),l=a.filter(g=>g.state==="open").length,u=a.filter(g=>g.state==="failed").length;t.push({severity:s.lastError||u?"warn":"ok",group:"Native",title:`Reminders mirror: ${l} open in "${o.list}"${u?`, ${u} could not be added`:""}`,detail:s.lastError?`Last error ${s.lastError.at}: ${s.lastError.message}`:void 0,fix:s.lastError?"Run remindctl status, and allow Reminders for the app that runs the daemon in System Settings \u203A Privacy & Security \u203A Reminders.":void 0})}function U(t,n,e=process.platform,i=o=>{try{return W(o,M.X_OK),!0}catch{return!1}}){let o=n.reminders;if(!o?.enabled)return;if(e!=="darwin"){t.push({severity:"warn",group:"Reminders",title:"Reminders hand-back unavailable on this machine",detail:"reminders.enabled is set, but Apple Reminders exists only on macOS. The daemon starts without it.",fix:"Set reminders.enabled to false here, or enable it on the Mac node instead."});return}let s=o.command||"remindctl",a=s.includes("/")?i(s)?s:null:x(s,process.env.PATH||"",i);t.push(a?{severity:"ok",group:"Reminders",title:`Watching ${(o.lists||[]).join(", ")} for due reminders`,detail:a}:{severity:"fail",group:"Reminders",title:`${s} not found`,detail:"The daemon reads Apple Reminders through remindctl.",fix:"brew install steipete/tap/remindctl, or set reminders.command to its full path."})}async function Q(t){let n=E(process.versions.node);t.push({severity:n?"ok":"fail",group:"Environment",title:`Node.js ${process.versions.node}`,detail:n?void 0:"AgentX requires Node 22.19 or newer, up to Node 26.",fix:n?void 0:"Install Node 22 (nvm install 22 && nvm use 22)"});let e=l=>{try{return m(process.platform==="win32"?"where":"which",[l],{encoding:"utf-8"}).trim().split(`
|
|
3
3
|
`)[0]}catch{return null}},i=e("npm");t.push({severity:i?"ok":"fail",group:"Environment",title:i?"npm on PATH":"npm not found",detail:i||void 0});let o=e("claude");if(o){let l;try{l=m("claude",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`claude CLI ${l||"installed"}`,detail:o})}else t.push({severity:"warn",group:"Environment",title:"claude CLI not on PATH",detail:"Only required for agents on the claude-code tier.",fix:"See https://docs.anthropic.com/en/docs/claude-code"});let s=e("codex");if(s){let l;try{l=m("codex",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`codex CLI ${l||"installed"}`,detail:s})}else t.push({severity:"warn",group:"Environment",title:"codex CLI not on PATH",detail:"Only required for agents on the codex-cli tier.",fix:"Install with `npm i -g @openai/codex`."});let a=e("opencode");if(a){let l;try{l=m("opencode",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`opencode CLI ${l||"installed"}`,detail:a})}else t.push({severity:"warn",group:"Environment",title:"opencode CLI not on PATH",detail:"Only required for agents on the opencode tier.",fix:"Install from https://opencode.ai/docs/."});try{G(import.meta.url)("better-sqlite3"),t.push({severity:"ok",group:"Environment",title:`better-sqlite3 loads for Node ${process.version}`,detail:`NODE_MODULE_VERSION ${process.versions.modules}`})}catch(l){t.push({severity:"fail",group:"Environment",title:"better-sqlite3 native binding does not load",detail:l?.message??String(l),fix:`Run "pnpm rebuild better-sqlite3" with the same Node used by the daemon (${process.version}, modules ${process.versions.modules}).`})}}function Y(t){if(process.platform!=="darwin")return;let n=H(z(),"Library/LaunchAgents"),e=[];try{e=C(n).filter(o=>/agentx\.voice.*\.plist$/.test(o))}catch{return}let i=o=>{try{return W(o,M.X_OK),!0}catch{return!1}};for(let o of e){let s=R(b(H(n,o),"utf-8")),a=x("ffmpeg",s,i);t.push(a?{severity:"ok",group:"Desktop",title:"ffmpeg reachable by the desktop app",detail:`${a} (${o})`}:{severity:"warn",group:"Desktop",title:"ffmpeg not reachable by the desktop app",detail:`Local Whisper transcription fails without it. ${o} sets PATH to ${s}.`,fix:"Install ffmpeg (brew install ffmpeg), then rerun agentx desktop install."})}}function ee(t){let n=y(process.cwd(),"agentx.json");if(!w(n))return t.push({severity:"fail",group:"Config",title:"agentx.json not found",detail:`Looked in ${n}`,fix:"Run `agentx setup` to create one via the web wizard."}),null;let e;try{e=JSON.parse(b(n,"utf-8"))}catch(a){return t.push({severity:"fail",group:"Config",title:"agentx.json is not valid JSON",detail:a.message}),null}try{j(n),t.push({severity:"ok",group:"Config",title:`agentx.json valid (${Object.keys(e.agents||{}).length} agents, ${Object.keys(e.crons||{}).length} schedules)`})}catch(a){t.push({severity:"fail",group:"Config",title:"agentx.json failed schema validation",detail:a.message,fix:"Open /admin \u2192 Advanced tab to edit and re-save."})}let i=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="claude-code");i.length>0&&((()=>{try{return m(process.platform==="win32"?"where":"which",["claude"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${i.length} agent(s) use claude-code tier but claude CLI is missing`,detail:i.map(([l])=>l).join(", "),fix:"Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) or switch these agents to tier=sdk."}));let o=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="codex-cli");o.length>0&&((()=>{try{return m(process.platform==="win32"?"where":"which",["codex"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${o.length} agent(s) use codex-cli tier but codex CLI is missing`,detail:o.map(([l])=>l).join(", "),fix:"Install Codex CLI with `npm i -g @openai/codex` or switch these agents to tier=claude-code."}));let s=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="opencode");return s.length>0&&((()=>{try{return m(process.platform==="win32"?"where":"which",["opencode"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${s.length} agent(s) use opencode tier but OpenCode CLI is missing`,detail:s.map(([l])=>l).join(", "),fix:"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier."})),e}function te(t,n){let e=new Set;if(A(n,e),e.size===0){t.push({severity:"ok",group:"Secrets",title:"No ${VAR} references in agentx.json"});return}let i=_(),o=[],s=[];for(let a of e){let l=process.env[a]??i[a];l===void 0?o.push(a):(!l.trim()||/^["']?\s*["']?$/.test(l))&&s.push(a)}o.length===0&&s.length===0?t.push({severity:"ok",group:"Secrets",title:`${e.size} env reference(s) resolved`}):(o.length>0&&t.push({severity:"fail",group:"Secrets",title:`${o.length} env var(s) referenced in agentx.json but missing`,detail:o.join(", "),fix:`Add to .env \u2014 e.g. ${o[0]}=<value>`}),s.length>0&&t.push({severity:"warn",group:"Secrets",title:`${s.length} env var(s) set but empty`,detail:s.join(", ")}))}function _(){let t=y(process.cwd(),".env"),n={};if(w(t))for(let e of b(t,"utf-8").split(/\r?\n/)){let i=e.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);i&&(n[i[1]]=i[2])}return n}function ne(t,n){let e="With a shared token this node cannot tell which peer is calling. For example, closing an approval card forwarded from that peer is refused, and its stop/resume signals are judged as the owner's.",i="Give this pair a token of its own: set the same new value as mesh.peers[].token here and on the peer.",o=[];for(let s of t){let a=(s.token??"").trim();a?n&&a===n&&o.push({severity:"warn",group:"Mesh",title:`mesh peer "${s.name}" uses this node's own MESH_TOKEN`,detail:e,fix:i}):o.push({severity:"warn",group:"Mesh",title:`mesh peer "${s.name}" has no token; calls to it use the shared MESH_TOKEN`,detail:e,fix:i})}return t.length>0&&o.length===0&&o.push({severity:"ok",group:"Mesh",title:`${t.length} mesh peer(s), each with a token of its own`}),o}function ie(t,n){t.push(...oe(n))}function oe(t,n=process.env,e=_()){let i=a=>(n[a]||e[a]||"").trim(),o=a=>typeof a=="string"?a.replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,(l,u)=>i(u)):void 0,s=(t.mesh?.peers??[]).filter(a=>typeof a?.name=="string").map(a=>({name:a.name,token:o(a.token)}));return ne(s,i("MESH_TOKEN")||void 0)}function A(t,n){if(typeof t=="string")for(let e of t.matchAll(/\$\{([A-Z_][A-Z0-9_]*)\}/g))n.add(e[1]);else if(Array.isArray(t))for(let e of t)A(e,n);else if(t&&typeof t=="object")for(let e of Object.values(t))A(e,n)}function se(t,n){let e=[];for(let[i,o]of Object.entries(n.agents||{})){if(!o.workspace)continue;let s=o.workspace.startsWith("/")?o.workspace:y(process.cwd(),o.workspace);try{B(s).isDirectory()||e.push(`${i}: ${s} (exists but not a directory)`)}catch{e.push(`${i}: ${s}`)}}e.length===0?t.push({severity:"ok",group:"Workspaces",title:"All agent workspace folders exist"}):t.push({severity:"warn",group:"Workspaces",title:`${e.length} agent workspace(s) missing`,detail:e.join(`
|
|
4
4
|
`),fix:"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them."})}function re(t,n){let e=/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g,i=[];for(let[o,s]of Object.entries(n.agents||{})){if(!s.workspace)continue;let a=s.workspace.startsWith("/")?s.workspace:y(process.cwd(),s.workspace);for(let l of["settings.json","settings.local.json"]){let u=y(a,".claude",l);if(!w(u))continue;let g;try{g=JSON.parse(b(u,"utf-8"))}catch(c){i.push({severity:"fail",agent:o,msg:`${l}: JSON parse error \u2014 ${c.message}`});continue}let $=g.env||{};for(let[c,h]of Object.entries($)){if(typeof h!="string")continue;let p=h.match(e);p&&i.push({severity:"fail",agent:o,msg:`${l} env.${c} contains unexpanded ${[...new Set(p)].join(",")} \u2014 Claude Code does NOT expand \${VAR} in settings.json (use a fully-literal value)`})}let r=$.PATH;if(typeof r=="string"){let c=r.split(":").filter(Boolean);c.includes("/usr/bin")||i.push({severity:"fail",agent:o,msg:`${l} env.PATH missing /usr/bin \u2014 cat/head/sh/which will fail`}),c.includes("/bin")||i.push({severity:"fail",agent:o,msg:`${l} env.PATH missing /bin \u2014 ls/cp/mv will fail`})}let d=g.permissions;if(d&&typeof d=="object"&&"allow"in d){let c=d.allow,h=d.deny;Array.isArray(c)&&c.length===0&&Array.isArray(h)&&h.length>0&&i.push({severity:"warn",agent:o,msg:`${l} permissions.allow is explicitly [] with ${h.length} deny rules \u2014 agent may be locked out (omit the key to use defaults instead)`})}}}if(i.length===0){t.push({severity:"ok",group:"Workspace settings",title:`All ${Object.keys(n.agents||{}).length} agent .claude/settings.json files clean`});return}for(let o of i)t.push({severity:o.severity,group:"Workspace settings",title:`${o.agent}: ${o.msg}`,fix:o.severity==="fail"?"Edit .claude/settings.json \u2014 replace ${VAR} with the literal value or omit the key to inherit.":"Either remove the empty allow list or populate it."})}function ae(t,n){let e=n.webhooks??[],i=[],o=y(process.cwd(),n.workflows?.dir||".agentx/workflows"),s=new Set;try{if(w(o))for(let r of C(o))r.endsWith(".json")&&!r.startsWith("_")&&!r.endsWith(".disabled.json")&&s.add(r.replace(/\.json$/,""))}catch{}let a=new Set(["github","gitlab"]);for(let r of e){if(!r.enabled||!a.has(r.source))continue;!(r.triggers&&Object.keys(r.triggers).length>0)&&!r.defaultWorkflow&&i.push({severity:"warn",title:`webhook "${r.id}" (${r.source} -> ${r.agentId}) has no triggers map; every event-type collapses to the bound agent`,fix:'Add a triggers map: { "issues.opened": "wf-id", "pull_request.synchronize": "wf-id" } \u2014 or set defaultWorkflow.'})}for(let r of e)if(!(!r.enabled||!r.triggers)){for(let[d,c]of Object.entries(r.triggers))s.size>0&&!s.has(c)&&i.push({severity:"fail",title:`webhook "${r.id}".triggers["${d}"] -> "${c}" \u2014 no such workflow under ${n.workflows?.dir||".agentx/workflows"}`,fix:"Create the workflow file or fix the id in agentx.json"});r.defaultWorkflow&&s.size>0&&!s.has(r.defaultWorkflow)&&i.push({severity:"fail",title:`webhook "${r.id}".defaultWorkflow -> "${r.defaultWorkflow}" \u2014 no such workflow`,fix:"Create the workflow file or fix the id in agentx.json"})}try{if(w(o)){for(let r of C(o))if(!(!r.endsWith(".json")||r.startsWith("_")||r.endsWith(".disabled.json")))try{let d=JSON.parse(b(y(o,r),"utf-8"));d?.status==="active"&&d?.state==="quarantined"&&i.push({severity:"warn",title:`workflow "${d.id??r}" is status=active but state=quarantined \u2014 it looks live but will never dispatch`,fix:'Resolve the conflict the detector flagged, then set state back to "active" (or set status to "review" while parked).'})}catch{}}}catch{}let l=new Set((n.mesh?.peers??[]).map(r=>r.name));for(let r of e)!r.enabled||!r.node||l.has(r.node)||i.push({severity:"fail",title:`webhook "${r.id}" routes to mesh peer "${r.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or remove the node field on the webhook."});let u=new Map;for(let r of e){if(!r.enabled)continue;let d=`${r.source}:${r.agentId}`,c=u.get(d);c?i.push({severity:"warn",title:`webhook entries "${c}" and "${r.id}" both enabled for ${r.source} -> ${r.agentId}; only the first is dispatched`,fix:"Disable one entry, or merge their triggers maps into a single entry."}):u.set(d,r.id)}let g=new Set(Object.keys(n.agents??{}));for(let r of n.channels?.gitlab?.agentMappings??[])if(r?.agentId){if(r.node){l.has(r.node)||i.push({severity:"fail",title:`gitlab.agentMappings entry agentId="${r.agentId}" routes to mesh peer "${r.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or drop the node field on the mapping."});continue}g.has(r.agentId)||i.push({severity:"warn",title:`gitlab.agentMappings entry agentId="${r.agentId}" \u2014 no such agent in agents.* (and no node field, so it's not a cross-mesh route)`,fix:'Add the agent to agents.*, set node:"<peer>" if the agent lives remotely, or remove the mapping.'})}for(let[r,d]of Object.entries(n.channels?.telegram?.accounts??{}))d.agentBinding?g.has(d.agentBinding)||i.push({severity:"fail",title:`telegram account "${r}".agentBinding -> "${d.agentBinding}" \u2014 no such agent in agents.*`,fix:"Fix the agentBinding or define the agent in agents.*."}):i.push({severity:"fail",title:`telegram account "${r}" has no agentBinding; every DM to this bot will drop`,fix:"Set agentBinding to a valid agent id."});let $=new Set(["telegram-bot","whatsapp","slack-bot","discord-bot","gitlab-user","github-user","gmail","hotmail","smtp","hubspot","salesforce","pipedrive","odoo","trello","linear","asana","jira","notion","stripe","sentry","vercel","twilio","custom"]);for(let[r,d]of Object.entries(n.agents??{})){let c=d.integrations??[];if(!c.length)continue;let h=new Set;for(let p of c){let S=`${p.kind}::${p.label}`;h.has(S)&&i.push({severity:"warn",title:`agents.${r}.integrations: duplicate (${p.kind}, ${p.label})`,fix:"Remove the duplicate or rename one. (kind, label) must be unique per agent."}),h.add(S),$.has(p.kind)||i.push({severity:"warn",title:`agents.${r}.integrations: unknown kind "${p.kind}" on integration "${p.label}"`,fix:'Use a canonical kind from INTEGRATION_KINDS, or "custom" for ad-hoc services.'});let L=p.credentials||{};for(let[q,v]of Object.entries(L))typeof v=="string"&&/^[A-Z][A-Z0-9_]*$/.test(v)&&!process.env[v]&&i.push({severity:"warn",title:`agents.${r}.integrations[${p.kind}/${p.label}].${q} -> $${v} but env var is unset (in this shell)`,fix:`Set ${v} on the daemon environment. The daemon's process.env is what matters; this warning fires from your local shell.`})}}if(i.length===0){t.push({severity:"ok",group:"Routing",title:`${e.length} webhook(s), ${Object.keys(n.channels?.telegram?.accounts??{}).length} telegram account(s) \u2014 all routing references resolve`});return}for(let r of i)t.push({severity:r.severity,group:"Routing",title:r.title,fix:r.fix})}function le(t){return typeof t?.canMeasure!="boolean"?null:t.canMeasure?{severity:"ok",group:"Runtime",title:"Daemon finds ffmpeg to measure phone recordings"}:{severity:"warn",group:"Runtime",title:t.allowUnmeasured?"Daemon can't find ffmpeg: phone recordings go unmeasured (voice.allowUnmeasured)":"Daemon can't find ffmpeg: phone voice input is refused",fix:"Install ffmpeg (brew install ffmpeg / sudo apt install ffmpeg), or set AGENTX_FFMPEG in the service's environment. The daemon's PATH is shorter than your shell's."}}async function de(t,n){let e=n.dashboard?.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800",i={};n.dashboard?.token&&(i.Authorization=`Bearer ${n.dashboard.token}`);try{let o=new AbortController,s=setTimeout(()=>o.abort(),2e3),a=await fetch(e+"/health",{headers:i,signal:o.signal});if(clearTimeout(s),!a.ok){t.push({severity:"warn",group:"Runtime",title:`Daemon responded ${a.status}`,detail:e});return}let l=await a.json();t.push({severity:"ok",group:"Runtime",title:`Daemon healthy \u2014 ${l.agents?.length??0} agents live, uptime ${Math.round((l.uptime??0)/60)}m`,detail:e});let u=le(l.voice);u&&t.push(u)}catch{t.push({severity:"warn",group:"Runtime",title:"Daemon not reachable (not running?)",detail:e,fix:"Run `agentx daemon start`. Skip this check with `agentx doctor --no-running`."})}}function ce(t,n){let e=Object.entries(n.agents||{}).filter(([,o])=>o?.codegraph===!0&&(o.tier==="claude-code"||o.tier==="codex-cli"));if(e.length===0)return;let i=null;try{i=m(process.platform==="win32"?"where":"which",["codegraph"],{encoding:"utf-8"}).trim().split(`
|
|
5
5
|
`)[0]||null}catch{i=null}if(i){let o;try{o=m("codegraph",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"CodeGraph",title:`codegraph CLI ${o||"installed"}`,detail:i})}else t.push({severity:"fail",group:"CodeGraph",title:"codegraph CLI not on PATH",detail:`${e.length} agent(s) have codegraph:true but the binary isn't available.`,fix:"Install with `npm i -g @colbymchenry/codegraph`."});for(let[o,s]of e){if(!s.workspace||!w(s.workspace)){t.push({severity:"warn",group:"CodeGraph",title:`${o}: workspace missing`,detail:`Workspace path ${s.workspace} does not exist \u2014 codegraph will skip this agent.`});continue}let a=y(s.workspace,".codegraph","codegraph.db");w(a)?t.push({severity:"ok",group:"CodeGraph",title:`${o}: index present`,detail:a}):t.push({severity:"warn",group:"CodeGraph",title:`${o}: index not built yet`,detail:".codegraph/ missing \u2014 daemon will background-index this workspace on next boot.",fix:`Run \`codegraph init --index ${s.workspace}\` to build it now.`})}}function D(t){return{errors:t.filter(n=>n.severity==="fail").length,warnings:t.filter(n=>n.severity==="warn").length,ok:t.filter(n=>n.severity==="ok").length}}function ue(t){console.log(),console.log(f.bold(" agentx doctor")),console.log();let n=new Map;for(let i of t)n.has(i.group)||n.set(i.group,[]),n.get(i.group).push(i);for(let[i,o]of n){console.log(f.bold(" "+i));for(let s of o){let a=s.severity==="ok"?f.green("\u2713"):s.severity==="warn"?f.yellow("!"):f.red("\u2717");console.log(` ${a} ${s.title}`),s.detail&&console.log(f.dim(" "+s.detail.replace(/\n/g,`
|
|
6
6
|
`))),s.fix&&console.log(f.dim(" \u2192 "+s.fix))}console.log()}let e=D(t);e.errors>0?console.log(f.red.bold(` ${e.errors} error${e.errors===1?"":"s"}`)+(e.warnings?f.yellow(`, ${e.warnings} warning${e.warnings===1?"":"s"}`):"")+`. Fix the error${e.errors===1?"":"s"} and rerun.`):e.warnings>0?console.log(f.yellow.bold(` ${e.warnings} warning${e.warnings===1?"":"s"}.`)+f.dim(" Review but not blocking.")):console.log(f.green.bold(` All checks passed (${e.ok}).`)),console.log()}export{P as a,Z as b,Ne as c,J as d,K as e,V as f,U as g,ne as h,oe as i,le as j};
|
|
7
|
-
//# sourceMappingURL=chunk-
|
|
7
|
+
//# sourceMappingURL=chunk-BRQKV4FC.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{lb as l,ub as m}from"./chunk-NKCS6EZ7.js";m();import{existsSync as g,readFileSync as u,writeFileSync as a,copyFileSync as y}from"fs";import{resolve as p}from"path";function P(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(!g(t))throw new Error(`agentx.json not found at ${t}`);let i=JSON.parse(u(t,"utf-8")),o=e(i),s=typeof o=="string"?{summary:o}:o,c=JSON.stringify(i,null,2)+`
|
|
2
2
|
`,f=t+".tmp";a(f,c,"utf-8");try{JSON.parse(u(f,"utf-8"))}catch(d){throw new Error(`config did not round-trip cleanly: ${d.message}`)}let r;return n.skipBackup||(r=`${t}.bak.${Date.now()}`,y(t,r)),a(t,c,"utf-8"),n.skipReload||h().catch(()=>{}),{summary:s.summary,payload:s.payload,backupPath:r}}function S(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(g(t)&&!n.overwrite)throw new Error(`agentx.json already exists at ${t}. Pass overwrite=true to replace it.`);return a(t,JSON.stringify(e,null,2)+`
|
|
3
3
|
`,"utf-8"),{file:t}}async function h(){try{let n=l().dashboard.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800";await fetch(`${n}/reload`,{method:"POST"}).catch(()=>null)}catch{}}export{P as a,S as b};
|
|
4
|
-
//# sourceMappingURL=chunk-
|
|
4
|
+
//# sourceMappingURL=chunk-CBXPIKPJ.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{e as g}from"./chunk-
|
|
1
|
+
import{e as g}from"./chunk-S34KFBMJ.js";async function $(e,i,r,n,o={}){let a=o.retrieve??g,c=o.perEntry??2,s=o.maxArticles??8,f=o.queryChars??1500,h=new Map;for(let t of e){let l=[];try{l=await a(t.content.slice(0,f),i,r,{pool:n,maxCandidates:c,maxHops:1,maxArticles:c*2,stage:"absorb-covering"})}catch{}for(let u of l){let p=h.get(u.path);p?(p.hop=Math.min(p.hop,u.hop),p.entries.includes(t.id)||p.entries.push(t.id)):h.set(u.path,{...u,entries:[t.id]})}}return[...h.values()].sort((t,l)=>t.hop-l.hop||l.entries.length-t.entries.length||t.path.localeCompare(l.path)).slice(0,s)}function x(e){if(e.length===0)return"";let i=e.map(r=>{let n=`### ${r.meta.title} \u2014 ${r.meta.type||"untyped"} (${r.path})`,o=`Found for entries: ${r.entries.join(", ")}${r.hop>0?" (linked from a match)":""}`,a=r.meta.related?.length?`Related: ${r.meta.related.join(", ")}`:"";return[n,o,a,"",r.content].filter(c=>c!=="").join(`
|
|
2
2
|
`)}).join(`
|
|
3
3
|
|
|
4
4
|
---
|
|
@@ -14,4 +14,4 @@ These ${e.length} articles were found by searching the wiki for each entry below
|
|
|
14
14
|
|
|
15
15
|
${i}
|
|
16
16
|
`}var d=/\bhttps?:\/\/[^\s<>"'`)\]]+/gi,y=/\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/g,w=/(?<![\w-])(?=[0-9a-f]*[0-9])(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}(?![\w-])/gi,k=/(?<![\w.,:/-])\d+(?:[.,:\-/]\d+)*(?![\w])/g,C=/^\s*\d+[.)]\s/gm;function A(e){let i=[...e.matchAll(d)].map(s=>s[0].replace(/[.,;:!?'"]+$/,"")),r=[...e.matchAll(y)].map(s=>s[1].trim()),n=e.replace(d," ").replace(y," ").replace(C," "),o=[...n.matchAll(w)].map(s=>s[0].toLowerCase()),c=[...n.replace(w," ").matchAll(k)].map(s=>v(s[0]));return{commits:m(o),urls:m(i),wikilinks:m(r),numbers:m(c)}}function R(e,i){let r=A(e),n=A(i),o=i.toLowerCase(),a=[];for(let t of r.commits)!o.includes(t)&&!n.commits.some(l=>l.startsWith(t)||t.startsWith(l))&&a.push(`commit ${t}`);let c=t=>t.toLowerCase().replace(/\/+$/,""),s=new Set(n.urls.map(c));for(let t of r.urls)s.has(c(t))||a.push(`link ${t}`);let f=new Set(n.wikilinks.map(t=>t.toLowerCase()));for(let t of r.wikilinks)f.has(t.toLowerCase())||a.push(`link [[${t}]]`);let h=new Set(n.numbers);for(let t of r.numbers)h.has(t)||a.push(`number ${t}`);return a}function v(e){return/^\d{1,3}(,\d{3})+$/.test(e)?e.replace(/,/g,""):e}function m(e){return[...new Set(e)]}function L(e,i){if(i.some(n=>n.path===e.path))return e.path;let r=b(e.title);return r?i.find(n=>b(n.title)===r)?.path??e.path:e.path}function b(e){return(e||"").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").trim()}export{$ as a,x as b,A as c,R as d,L as e};
|
|
17
|
-
//# sourceMappingURL=chunk-
|
|
17
|
+
//# sourceMappingURL=chunk-COMJ7R5T.js.map
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{a as
|
|
2
|
-
`)}var Y,
|
|
1
|
+
import{a as $,b as Ae}from"./chunk-7I7IEX4S.js";import{a as N}from"./chunk-QIJLFPWE.js";import{existsSync as oe,readFileSync as me,writeFileSync as we,mkdirSync as xe}from"fs";import E from"path";import fe from"os";import B from"chalk";import I from"prompts";function S(){if(!oe(ne))return null;try{let s=JSON.parse(me(ne,"utf8"));return s.provider&&s.authType&&s.token&&s.model?s:null}catch{return null}}function be(s){oe(te)||xe(te,{recursive:!0}),we(ne,JSON.stringify(s,null,2),"utf8")}function L(s){if(s?.trim()){let p=s.startsWith("sk-ant-oat")?"oauth":"api-key";return{token:s.trim(),authType:p}}let e=process.env.ANTHROPIC_OAUTH_TOKEN;if(e?.trim())return{token:e.trim(),authType:"oauth"};let t=process.env.CLAUDE_CODE_OAUTH_TOKEN;if(t?.trim())return{token:t.trim(),authType:"oauth"};let r=process.env.ANTHROPIC_API_KEY;if(r?.trim())return{token:r.trim(),authType:"api-key"};let n=S();if(n)return{token:n.token,authType:n.authType};let o=fe.homedir(),l=[E.join(o,".openclaw","agents","main","agent","auth-profiles.json"),E.join(o,".openclaw","auth-profiles.json"),E.join(o,".openclaw","credentials","oauth.json"),E.join(o,".claude","oauth.json"),E.join(o,".config","claude","oauth.json"),E.join(o,".config","anthropic","oauth.json")];for(let p of l){let m=ve(p);if(m)return{token:m,authType:"oauth"}}return null}function ve(s){if(!oe(s))return"";try{let e=JSON.parse(me(s,"utf8"));if(e.profiles){let t="";for(let[r,n]of Object.entries(e.profiles))if(r.startsWith("anthropic")){if(n.type==="oauth"&&n.access){if(n.expires&&Date.now()>n.expires)continue;return n.access}n.type==="token"&&n.token&&(t=n.token)}if(t)return t}return e.anthropic?.access?e.anthropic.access:e.anthropic?.token?e.anthropic.token:""}catch{return""}}async function Re(){let s=process.env.ANTHROPIC_API_KEY;if(s?.trim()){let r=s.slice(0,10)+"..."+s.slice(-4),{useExisting:n}=await I({type:"confirm",name:"useExisting",message:`Use existing ANTHROPIC_API_KEY (env, ${r})?`,initial:!0});if(n)return{token:s.trim(),authType:"api-key"}}let e=S();if(e?.authType==="api-key"&&e.token){let r=e.token.slice(0,10)+"..."+e.token.slice(-4),{useExisting:n}=await I({type:"confirm",name:"useExisting",message:`Use stored API key (${r})?`,initial:!0});if(n)return{token:e.token,authType:"api-key"}}let{apiKey:t}=await I({type:"password",name:"apiKey",message:"Enter Anthropic API key",validate:r=>r.startsWith("sk-ant-api")?r.length<40?"API key seems too short":!0:"API key must start with sk-ant-api"});return t?{token:t,authType:"api-key"}:null}async function Oe(){$.break();let s=46,e="Run `claude setup-token` in your terminal.",t="Then paste the generated token below.";console.log(` ${B.cyan("Anthropic setup-token")} ${"\u2500".repeat(s-21-1)}\u256E`),console.log(` ${" ".repeat(s)}\u2502`),console.log(` ${e}${" ".repeat(s-e.length)}\u2502`),console.log(` ${t}${" ".repeat(s-t.length)}\u2502`),console.log(` ${" ".repeat(s)}\u2502`),console.log(` ${"\u2500".repeat(s)}\u256F`),$.break();let{token:r}=await I({type:"password",name:"token",message:"Paste Anthropic setup-token",validate:o=>o.trim()?o.length<40?"Token seems too short":!0:"Token is required"});if(!r)return null;let{tokenName:n}=await I({type:"text",name:"tokenName",message:"Token name (blank = default)"});return{token:r,authType:"oauth"}}async function Te(){for(;;){let{provider:s}=await I({type:"select",name:"provider",message:"Model/auth provider",choices:[{title:"Anthropic",value:"anthropic",description:"setup-token + API key"}]});if(s===void 0)return null;let{method:e}=await I({type:"select",name:"method",message:"Anthropic auth method",choices:[{title:"Anthropic token (paste setup-token)",value:"setup-token",description:"run `claude setup-token` elsewhere, then paste the token here"},{title:"Anthropic API key",value:"api-key"},{title:B.dim("Back"),value:"back"}]});if(e===void 0)return null;if(e!=="back")return e==="api-key"?Re():e==="setup-token"?Oe():null}}async function Pe(){let s=S(),e=re.map(r=>({title:r.label,value:r.id,description:r.hint+(s?.model===r.id?" \xB7 current":"")}));if(s?.model){let r=re.find(o=>o.id===s.model),n=r?r.label:s.model;e.unshift({title:`Keep current (${n})`,value:s.model,description:"no change"})}let{modelId:t}=await I({type:"select",name:"modelId",message:"Default model",choices:e});return t||null}async function Se(){let s=await Te();if(!s)return null;let e=await Pe();if(!e)return null;let t={provider:s.authType==="oauth"?"claude-code":"claude",authType:s.authType,token:s.token,model:e};return be(t),$.break(),$.success("Configuration saved to ~/.agentx/auth.json"),console.log(` Provider: ${B.bold("anthropic")} (${t.authType})`),console.log(` Model: ${B.bold(re.find(r=>r.id===t.model)?.label||t.model)}`),t}async function Je(s){return L(s)?!0:($.warn("No AI credentials configured."),$.break(),await Se()!==null)}var te,ne,re,H=N(()=>{"use strict";Ae();te=E.join(fe.homedir(),".agentx"),ne=E.join(te,"auth.json");re=[{id:"claude-sonnet-4-20250514",label:"anthropic/claude-sonnet-4",hint:"Claude Sonnet 4 \xB7 ctx 200k \xB7 recommended"},{id:"claude-opus-4-20250514",label:"anthropic/claude-opus-4-5",hint:"Claude Opus 4.5 \xB7 ctx 200k \xB7 reasoning"},{id:"claude-haiku-4-20250514",label:"anthropic/claude-haiku-4",hint:"Claude Haiku 4 \xB7 ctx 200k \xB7 fast"}]});function Ee(s){return(s?Y.filter(t=>s.includes(t.name)):Y).map(({name:t,description:r,input_schema:n})=>({name:t,description:r,input_schema:n}))}function C(){return Ee(["create_files","ask_user"])}function He(){let s=Y.filter(t=>t.name!=="create_files"&&t.name!=="ask_user");if(s.length===0)return"";let e=["# Available Capabilities","In addition to generating files, you have the following capabilities:",""];for(let t of s)e.push(`## ${t.name}`),e.push(t.description),e.push("");return e.join(`
|
|
2
|
+
`)}var Y,Ye,W=N(()=>{"use strict";Y=[{name:"create_files",description:"Create one or more files as output. Use this when you need to generate code, documents, configs, or any file-based output.",input_schema:{type:"object",properties:{files:{type:"array",items:{type:"object",properties:{path:{type:"string",description:"Relative file path from project root (e.g., src/components/Button.tsx)"},content:{type:"string",description:"The full content of the file"},language:{type:"string",description:"Programming language or file type"},description:{type:"string",description:"Brief description of what this file does"}},required:["path","content"]}},summary:{type:"string",description:"Brief summary of all generated files"}},required:["files"]},permission:"file-write"},{name:"ask_user",description:"Ask the user a clarifying question when you need more information to proceed. Use this when the request is ambiguous or you need to confirm important decisions.",input_schema:{type:"object",properties:{question:{type:"string",description:"The question to ask the user"},options:{type:"array",items:{type:"string"},description:"Optional list of choices for the user"}},required:["question"]},permission:"none"},{name:"read_file",description:"Read the contents of a file. Use this to inspect existing code, understand patterns, check implementations, or gather context before generating code.",input_schema:{type:"object",properties:{path:{type:"string",description:"Relative file path from project root"},max_lines:{type:"number",description:"Maximum number of lines to read. Defaults to 500. Use for large files."}},required:["path"]},permission:"file-read"},{name:"search_files",description:"Search for files matching a pattern and optionally search their content with a regex. Use this to find relevant code, understand project structure, or locate specific patterns.",input_schema:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern to match files (e.g., 'src/**/*.ts', '*.json')"},content_regex:{type:"string",description:"Optional regex to search within matched files. Returns matching lines."},max_results:{type:"number",description:"Maximum number of results to return. Default: 50."}},required:["pattern"]},permission:"none"},{name:"list_directory",description:"List files and directories at a given path. Use this to explore project structure.",input_schema:{type:"object",properties:{path:{type:"string",description:"Relative directory path from project root. Defaults to '.' (root)."},recursive:{type:"boolean",description:"List recursively. Default: false."},max_depth:{type:"number",description:"Maximum depth for recursive listing. Default: 3."}}},permission:"none"},{name:"run_command",description:"Execute a shell command. Use this to run build tools, test commands, linters, or inspect the environment. Commands run in the project root directory.",input_schema:{type:"object",properties:{command:{type:"string",description:"The shell command to execute"},timeout:{type:"number",description:"Timeout in milliseconds. Default: 30000 (30 seconds)."}},required:["command"]},permission:"command"},{name:"edit_file",description:"Apply search-and-replace edits to an existing file. Use this for targeted modifications to existing code rather than rewriting entire files.",input_schema:{type:"object",properties:{path:{type:"string",description:"Relative file path from project root"},edits:{type:"array",items:{type:"object",properties:{old_text:{type:"string",description:"The exact text to find in the file"},new_text:{type:"string",description:"The replacement text"}},required:["old_text","new_text"]},description:"List of search/replace pairs to apply in order"}},required:["path","edits"]},permission:"file-write"},{name:"spawn_agent",description:"Spawn a sub-agent to handle a task in the background. The sub-agent runs in its own session and returns results. Use this for parallel research, long-running tasks, or delegating work to a specialized agent.",input_schema:{type:"object",properties:{agent_id:{type:"string",description:"The ID of the agent to spawn (must be a registered agent)"},prompt:{type:"string",description:"The task description for the sub-agent"},timeout_seconds:{type:"number",description:"Maximum time to wait for completion in seconds. Default: 300 (5 minutes)."}},required:["agent_id","prompt"]},permission:"none"}];Ye=Y.map(s=>s.name)});function se(s=process.env){return`${(s.ANTHROPIC_BASE_URL||"https://api.anthropic.com").trim().replace(/\/+$/,"").replace(/\/v1$/,"")}/v1/messages`}function z(s){return!s||s.length<Ie?s:[{type:"text",text:s,cache_control:{type:"ephemeral"}}]}var V,X,Ie,q,ie=N(()=>{"use strict";H();W();V="claude-sonnet-4-20250514",X=8192,Ie=4*1024;q=class{name="claude";apiKey;authType="api-key";constructor(e){if(this.apiKey=e||process.env.ANTHROPIC_API_KEY||"",!this.apiKey){let t=L();t&&(this.apiKey=t.token,this.authType=t.authType)}if(!this.apiKey)throw new Error("Anthropic API key required. Run `agentx model` to configure, set ANTHROPIC_API_KEY, or pass --api-key.")}async generate(e,t){let r=t?.model||V,n=t?.maxTokens||X,o=e.find(c=>c.role==="system"),l=e.filter(c=>c.role!=="system").map(c=>({role:c.role,content:c.content})),p={model:r,max_tokens:n,messages:l,tools:C()};o&&(p.system=z(o.content)),t?.temperature!==void 0&&(p.temperature=t.temperature);let m=await this.callApi(p,t);return this.parseResponse(m)}async generateRaw(e,t,r,n){let o=n?.model||V,l=n?.maxTokens||X,p={model:o,max_tokens:l,system:z(t),messages:e,tools:r};n?.temperature!==void 0&&(p.temperature=n.temperature),n?.toolChoice&&(p.tool_choice={type:"tool",name:n.toolChoice.name});let m=await this.callApi(p,n);return{content:m.content.map(g=>g.type==="text"?{type:"text",text:g.text||""}:g.type==="tool_use"?{type:"tool_use",id:g.id||"",name:g.name||"",input:g.input||{}}:{type:"text",text:""}),stop_reason:m.stop_reason,usage:m.usage}}async*stream(e,t){let r=t?.model||V,n=t?.maxTokens||X,o=e.find(f=>f.role==="system"),l=e.filter(f=>f.role!=="system").map(f=>({role:f.role,content:f.content})),p={model:r,max_tokens:n,messages:l,stream:!0,tools:C()};o&&(p.system=z(o.content));let m=this.buildHeaders(),c=await fetch(se(),{method:"POST",headers:m,body:JSON.stringify(p),signal:t?.abortSignal});if(!c.ok){let f=await c.text();yield{type:"error",error:`Anthropic API error (${c.status}): ${f}`};return}let g=c.body?.getReader();if(!g){yield{type:"error",error:"No response body"};return}let _=new TextDecoder,d="",h=[],w="",A,b=0,i=null,y=f=>{let R=(f||"").trim();if(!R||R.includes("```"))return;let T=R.replace(/\r\n/g,`
|
|
3
3
|
`).split(`
|
|
4
4
|
`),x=T.slice(Math.max(0,T.length-20)),u=x.join(`
|
|
5
5
|
`);if(/\b(plan|proposal)\b/i.test(u)&&/(ready for your review|review (the )?plan|requesting plan approval|awaiting approval|waiting for (your )?approval|approve (the )?plan|approval to proceed)/i.test(u))return`The provider is requesting plan approval.
|
|
6
6
|
Reply with:
|
|
7
7
|
- approve
|
|
8
8
|
- revise: <what to change>
|
|
9
|
-
- cancel`;let k=P=>/^(question|clarification|clarify|i need|need more|before i proceed|to proceed|please (confirm|clarify)|which|what|where|when|how|do you)/i.test(P.trim()),O=-1;for(let P=x.length-1;P>=0;P--){let
|
|
9
|
+
- cancel`;let k=P=>/^(question|clarification|clarify|i need|need more|before i proceed|to proceed|please (confirm|clarify)|which|what|where|when|how|do you)/i.test(P.trim()),O=-1;for(let P=x.length-1;P>=0;P--){let G=x[P].trim();if(G&&(k(G)||G.includes("?"))){O=P;break}}if(O===-1)return;let v=[];for(let P=O;P<x.length&&v.length<8;P++){let G=x[P],ee=G.trim();if(v.length>0&&!ee||v.length>0&&!/^(options?:|[-*]\s|\d+[\).]\s)/i.test(ee)&&!ee.includes("?"))break;v.push(G.trimEnd())}let j=v.join(`
|
|
10
10
|
`).trim();if(!(j.length<5))return j.length>800?j.slice(0,800).trimEnd():j};try{for(;;){let{done:f,value:R}=await g.read();if(f)break;d+=_.decode(R,{stream:!0});let T=d.split(`
|
|
11
11
|
`);d=T.pop()||"";for(let x of T){if(!x.startsWith("data: "))continue;let u=x.slice(6).trim();if(u!=="[DONE]")try{let a=JSON.parse(u);if(a.type==="content_block_start"&&a.content_block?.type==="tool_use"){if(i){yield{type:"tool_use_end",name:i.name};try{let k=JSON.parse(i.json||"{}");i.name==="create_files"&&k&&(Array.isArray(k.files)&&h.push(...k.files),typeof k.summary=="string"&&k.summary.trim()&&(w+=`
|
|
12
12
|
${k.summary}`)),i.name==="ask_user"&&k&&typeof k.question=="string"&&k.question.trim()&&(A=k.question,Array.isArray(k.options)&&k.options.length&&(A+=`
|
|
@@ -14,19 +14,19 @@ Options: ${k.options.join(", ")}`))}catch{}finally{i=null}}i={name:a.content_blo
|
|
|
14
14
|
${k.summary}`)),i.name==="ask_user"&&k&&typeof k.question=="string"&&k.question.trim()&&(A=k.question,Array.isArray(k.options)&&k.options.length&&(A+=`
|
|
15
15
|
Options: ${k.options.join(", ")}`))}catch{}finally{i=null}}a.type==="message_delta"&&a.usage&&(b=(a.usage.input_tokens||0)+(a.usage.output_tokens||0)),a.type}catch{}}}}finally{g.releaseLock()}if(i){yield{type:"tool_use_end",name:i.name};try{let f=JSON.parse(i.json||"{}");i.name==="create_files"&&f&&(Array.isArray(f.files)&&h.push(...f.files),typeof f.summary=="string"&&f.summary.trim()&&(w+=`
|
|
16
16
|
${f.summary}`)),i.name==="ask_user"&&f&&typeof f.question=="string"&&f.question.trim()&&(A=f.question,Array.isArray(f.options)&&f.options.length&&(A+=`
|
|
17
|
-
Options: ${f.options.join(", ")}`))}catch{}i=null}!A&&h.length===0&&(A=y(w)),yield{type:"done",result:{content:w,files:h,followUp:A,tokensUsed:b}}}async*generateRawStream(e,t,r,n){let o=n?.model||V,l=n?.maxTokens||X,p={model:o,max_tokens:l,system:z(t),messages:e,tools:r,stream:!0};n?.temperature!==void 0&&(p.temperature=n.temperature);let m=this.buildHeaders(),c;try{c=await fetch(
|
|
18
|
-
`);d=R.pop()||"";for(let T of R){if(!T.startsWith("data: "))continue;let x=T.slice(6).trim();if(!x||x==="[DONE]")continue;let u;try{u=JSON.parse(x)}catch{continue}if(u.type==="message_start"&&u.message?.usage&&(b=u.message.usage.input_tokens||0),u.type==="content_block_start"){let a=u.content_block;a?.type==="text"?(w=h.length,h.push({type:"text",text:""})):a?.type==="tool_use"?(w=h.length,h.push({type:"tool_use",id:a.id||"",name:a.name||"",input:{}}),h[w]._rawJson=""):w=null}if(u.type==="content_block_delta"&&w!=null){let a=h[w];u.delta?.type==="text_delta"&&a.type==="text"?(a.text+=u.delta.text,yield{type:"text_delta",text:u.delta.text}):u.delta?.type==="input_json_delta"&&a.type==="tool_use"&&(a._rawJson+=u.delta.partial_json||"")}if(u.type==="content_block_stop"&&w!=null){let a=h[w];if(a.type==="tool_use"){let k=a._rawJson||"{}";try{a.input=JSON.parse(k)}catch{a.input={}}delete a._rawJson}w=null}u.type==="message_delta"&&(u.delta?.stop_reason&&(A=u.delta.stop_reason),u.usage&&(i=u.usage.output_tokens||0))}}}catch(y){yield{type:"error",error:`Anthropic stream read failed: ${y?.message??y}`};return}finally{g.releaseLock()}yield{type:"raw_result",result:{content:h,stop_reason:A,usage:{input_tokens:b,output_tokens:i}}}}buildHeaders(){let e={"Content-Type":"application/json","anthropic-version":"2023-06-01"};return this.authType==="oauth"?(e.Authorization=`Bearer ${this.apiKey}`,e["anthropic-beta"]="claude-code-20250219,oauth-2025-04-20",e["user-agent"]="claude-cli/2.1.2 (external, cli)",e["x-app"]="cli",e["anthropic-dangerous-direct-browser-access"]="true"):e["x-api-key"]=this.apiKey,e}async callApi(e,t){let r=this.buildHeaders(),n=await fetch(
|
|
17
|
+
Options: ${f.options.join(", ")}`))}catch{}i=null}!A&&h.length===0&&(A=y(w)),yield{type:"done",result:{content:w,files:h,followUp:A,tokensUsed:b}}}async*generateRawStream(e,t,r,n){let o=n?.model||V,l=n?.maxTokens||X,p={model:o,max_tokens:l,system:z(t),messages:e,tools:r,stream:!0};n?.temperature!==void 0&&(p.temperature=n.temperature);let m=this.buildHeaders(),c;try{c=await fetch(se(),{method:"POST",headers:m,body:JSON.stringify(p),signal:n?.abortSignal})}catch(y){yield{type:"error",error:`Anthropic stream init failed: ${y?.message??y}`};return}if(!c.ok){let y=await c.text().catch(()=>"");yield{type:"error",error:`Anthropic API error (${c.status}): ${y.slice(0,500)}`};return}let g=c.body?.getReader();if(!g){yield{type:"error",error:"No response body on Anthropic stream"};return}let _=new TextDecoder,d="",h=[],w=null,A="end_turn",b=0,i=0;try{for(;;){let{done:y,value:f}=await g.read();if(y)break;d+=_.decode(f,{stream:!0});let R=d.split(`
|
|
18
|
+
`);d=R.pop()||"";for(let T of R){if(!T.startsWith("data: "))continue;let x=T.slice(6).trim();if(!x||x==="[DONE]")continue;let u;try{u=JSON.parse(x)}catch{continue}if(u.type==="message_start"&&u.message?.usage&&(b=u.message.usage.input_tokens||0),u.type==="content_block_start"){let a=u.content_block;a?.type==="text"?(w=h.length,h.push({type:"text",text:""})):a?.type==="tool_use"?(w=h.length,h.push({type:"tool_use",id:a.id||"",name:a.name||"",input:{}}),h[w]._rawJson=""):w=null}if(u.type==="content_block_delta"&&w!=null){let a=h[w];u.delta?.type==="text_delta"&&a.type==="text"?(a.text+=u.delta.text,yield{type:"text_delta",text:u.delta.text}):u.delta?.type==="input_json_delta"&&a.type==="tool_use"&&(a._rawJson+=u.delta.partial_json||"")}if(u.type==="content_block_stop"&&w!=null){let a=h[w];if(a.type==="tool_use"){let k=a._rawJson||"{}";try{a.input=JSON.parse(k)}catch{a.input={}}delete a._rawJson}w=null}u.type==="message_delta"&&(u.delta?.stop_reason&&(A=u.delta.stop_reason),u.usage&&(i=u.usage.output_tokens||0))}}}catch(y){yield{type:"error",error:`Anthropic stream read failed: ${y?.message??y}`};return}finally{g.releaseLock()}yield{type:"raw_result",result:{content:h,stop_reason:A,usage:{input_tokens:b,output_tokens:i}}}}buildHeaders(){let e={"Content-Type":"application/json","anthropic-version":"2023-06-01"};return this.authType==="oauth"?(e.Authorization=`Bearer ${this.apiKey}`,e["anthropic-beta"]="claude-code-20250219,oauth-2025-04-20",e["user-agent"]="claude-cli/2.1.2 (external, cli)",e["x-app"]="cli",e["anthropic-dangerous-direct-browser-access"]="true"):e["x-api-key"]=this.apiKey,e}async callApi(e,t){let r=this.buildHeaders(),n=await fetch(se(),{method:"POST",headers:r,body:JSON.stringify(e),signal:t?.abortSignal});if(!n.ok){let o=await n.text();throw new Error(`Anthropic API error (${n.status}): ${o}`)}return await n.json()}parseResponse(e){let t=[],r="",n;for(let o of e.content)if(o.type==="text"&&(r+=o.text||""),o.type==="tool_use"){if(o.name==="create_files"&&o.input){let l=o.input;t.push(...l.files||[]),l.summary&&(r+=`
|
|
19
19
|
${l.summary}`)}if(o.name==="ask_user"&&o.input){let l=o.input;n=l.question,l.options?.length&&(n+=`
|
|
20
|
-
Options: ${l.options.join(", ")}`)}}return{content:r,files:t,followUp:n,tokensUsed:e.usage.input_tokens+e.usage.output_tokens}}}});import{execa as
|
|
20
|
+
Options: ${l.options.join(", ")}`)}}return{content:r,files:t,followUp:n,tokensUsed:e.usage.input_tokens+e.usage.output_tokens}}}});import{execa as ye}from"execa";import{tmpdir as Ce}from"os";function je(s){let e=["-p","--output-format","json","--model",s.model,"--dangerously-skip-permissions"];return s.bare&&e.push(...Me),s.systemPrompt&&e.push(s.bare?"--system-prompt":"--append-system-prompt",s.systemPrompt),e.push(s.prompt),e}function he(s){let e=(s.stderr||s.stdout||"").toString().trim();return e||(s.isCanceled?"Claude CLI aborted by caller (timeout or cancel)":s.timedOut?"Claude CLI timed out":s.signal?`Claude CLI killed by ${s.signal}`:`Claude CLI failed (exit ${s.exitCode??"unknown"}, no output)`)}var K,ae,ge,Me,J,ce=N(()=>{"use strict";H();W();K="claude-sonnet-4-20250514",ae=8192,ge={"claude-sonnet-4-20250514":"sonnet","claude-opus-4-20250514":"opus","claude-haiku-4-20250514":"haiku"},Me=["--tools","","--strict-mcp-config","--mcp-config",'{"mcpServers":{}}',"--settings",'{"disableAllHooks":true}',"--no-session-persistence","--setting-sources",""];J=class{name="claude-code";credential;constructor(){let e=S();if(e){this.credential={type:e.authType,token:e.token};return}let t=L();if(!t)throw new Error(`No Claude credentials found.
|
|
21
21
|
Options:
|
|
22
22
|
1. Run \`agentx model\` to configure credentials
|
|
23
23
|
2. Set ANTHROPIC_API_KEY environment variable
|
|
24
|
-
3. Set ANTHROPIC_OAUTH_TOKEN environment variable`);this.credential={type:t.authType,token:t.token}}async generate(e,t){return this.credential.type==="oauth"?this.generateViaCli(e,t):this.generateViaApi(e,t)}async generateRaw(e,t,r,n){if(this.credential.type==="oauth")throw new Error("generateRaw() not available for OAuth/CLI mode");let o=n?.model||K,l=n?.maxTokens||
|
|
24
|
+
3. Set ANTHROPIC_OAUTH_TOKEN environment variable`);this.credential={type:t.authType,token:t.token}}async generate(e,t){return this.credential.type==="oauth"?this.generateViaCli(e,t):this.generateViaApi(e,t)}async generateRaw(e,t,r,n){if(this.credential.type==="oauth")throw new Error("generateRaw() not available for OAuth/CLI mode");let o=n?.model||K,l=n?.maxTokens||ae,p={model:o,max_tokens:l,system:t,messages:e,tools:r};n?.temperature!==void 0&&(p.temperature=n.temperature);let m={"Content-Type":"application/json","anthropic-version":"2023-06-01","x-api-key":this.credential.token},c=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:m,body:JSON.stringify(p)});if(!c.ok){let d=await c.text();throw new Error(`Anthropic API error (${c.status}): ${d}`)}let g=await c.json();return{content:g.content.map(d=>d.type==="text"?{type:"text",text:d.text||""}:d.type==="tool_use"?{type:"tool_use",id:d.id||"",name:d.name||"",input:d.input||{}}:{type:"text",text:""}),stop_reason:g.stop_reason,usage:g.usage}}get supportsAgenticLoop(){return this.credential.type==="api-key"}async generateViaCli(e,t){let r=t?.model||S()?.model||K,n=ge[r]||r,o=e.find(d=>d.role==="system"),p=e.filter(d=>d.role==="user").map(d=>d.content).join(`
|
|
25
25
|
|
|
26
|
-
`),m=
|
|
26
|
+
`),m=je({model:n,systemPrompt:o?.content,prompt:p,bare:t?.bare===!0}),c={...process.env};delete c.ANTHROPIC_API_KEY,delete c.ANTHROPIC_API_KEY_OLD,t?.noThinking&&(c.MAX_THINKING_TOKENS="0");let g=await ye("claude",m,{env:c,extendEnv:!1,reject:!1,timeout:3e5,stdin:"ignore",...t?.bare?{cwd:Ce()}:{},...t?.abortSignal?{signal:t.abortSignal}:{}});if(g.exitCode!==0)throw new Error(`Claude CLI error: ${he(g)}`);let _=g.stdout.trim();try{let d=JSON.parse(_);if(d.is_error&&d.result)throw new Error(d.result)}catch(d){if(d.message&&!d.message.includes("JSON"))throw d}return this.parseCliOutput(_)}async generateViaApi(e,t){let r=t?.model||K,n=t?.maxTokens||ae,o=e.find(_=>_.role==="system"),l=e.filter(_=>_.role!=="system").map(_=>({role:_.role,content:_.content})),p={model:r,max_tokens:n,messages:l,...t?.bare?{}:{tools:C()}};o&&(p.system=o.content),t?.temperature!==void 0&&(p.temperature=t.temperature);let m={"Content-Type":"application/json","anthropic-version":"2023-06-01","x-api-key":this.credential.token},c=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:m,body:JSON.stringify(p),...t?.abortSignal?{signal:t.abortSignal}:{}});if(!c.ok){let _=await c.text();throw new Error(`Anthropic API error (${c.status}): ${_}`)}let g=await c.json();return this.parseApiResponse(g)}async*stream(e,t){this.credential.type==="oauth"?yield*this.streamViaCli(e,t):yield*this.streamViaApi(e,t)}async*streamViaCli(e,t){let r=t?.model||S()?.model||K,n=ge[r]||r,o=e.find(i=>i.role==="system"),p=e.filter(i=>i.role==="user").map(i=>i.content).join(`
|
|
27
27
|
|
|
28
|
-
`),m=["-p","--output-format","stream-json","--model",n,"--dangerously-skip-permissions"];o&&m.push("--append-system-prompt",o.content),m.push(p);let c={...process.env};delete c.ANTHROPIC_API_KEY,delete c.ANTHROPIC_API_KEY_OLD;let g=
|
|
29
|
-
`).filter(Boolean);for(let x of T)try{let u=JSON.parse(x);if(u.type==="error"){h=String(u.error||u.message||"Claude CLI error");continue}if(u.is_error&&(u.result||u.message)){h=String(u.result||u.message);continue}u.type==="assistant"&&u.message?(_+=u.message,yield{type:"text_delta",text:u.message}):u.type==="result"&&(_=u.result||_)}catch{_+=x,yield{type:"text_delta",text:x}}}}let w=await g;if(w.exitCode!==0&&!h&&(h=d.toString().trim()||
|
|
28
|
+
`),m=["-p","--output-format","stream-json","--model",n,"--dangerously-skip-permissions"];o&&m.push("--append-system-prompt",o.content),m.push(p);let c={...process.env};delete c.ANTHROPIC_API_KEY,delete c.ANTHROPIC_API_KEY_OLD;let g=ye("claude",m,{env:c,extendEnv:!1,reject:!1,timeout:3e5,stdin:"ignore"}),_="",d="",h;if(g.stderr&&g.stderr.on("data",i=>{d+=Buffer.isBuffer(i)?i.toString("utf8"):String(i)}),g.stdout){let i=new TextDecoder,y=g.stdout;for await(let f of y){let T=(typeof f=="string"?f:i.decode(f,{stream:!0})).split(`
|
|
29
|
+
`).filter(Boolean);for(let x of T)try{let u=JSON.parse(x);if(u.type==="error"){h=String(u.error||u.message||"Claude CLI error");continue}if(u.is_error&&(u.result||u.message)){h=String(u.result||u.message);continue}u.type==="assistant"&&u.message?(_+=u.message,yield{type:"text_delta",text:u.message}):u.type==="result"&&(_=u.result||_)}catch{_+=x,yield{type:"text_delta",text:x}}}}let w=await g;if(w.exitCode!==0&&!h&&(h=d.toString().trim()||he(w)),h){yield{type:"error",error:`Claude CLI error: ${h}`};return}let A=this.extractFilesFromText(_),b=A.length===0?this.inferFollowUpFromText(_):void 0;yield{type:"done",result:{content:_,files:A,followUp:b,tokensUsed:0}}}async*streamViaApi(e,t){let r=t?.model||K,n=t?.maxTokens||ae,o=e.find(y=>y.role==="system"),l=e.filter(y=>y.role!=="system").map(y=>({role:y.role,content:y.content})),p={model:r,max_tokens:n,messages:l,tools:C(),stream:!0};o&&(p.system=o.content);let m={"Content-Type":"application/json","anthropic-version":"2023-06-01","x-api-key":this.credential.token},c=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:m,body:JSON.stringify(p)});if(!c.ok){let y=await c.text();yield{type:"error",error:`Anthropic API error (${c.status}): ${y}`};return}let g=c.body?.getReader();if(!g){yield{type:"error",error:"No response body"};return}let _=new TextDecoder,d="",h="",w=0,A=[],b,i=null;try{for(;;){let{done:y,value:f}=await g.read();if(y)break;d+=_.decode(f,{stream:!0});let R=d.split(`
|
|
30
30
|
`);d=R.pop()||"";for(let T of R){if(!T.startsWith("data: "))continue;let x=T.slice(6).trim();if(x!=="[DONE]")try{let u=JSON.parse(x);if(u.type==="content_block_start"&&u.content_block?.type==="tool_use"){if(i){yield{type:"tool_use_end",name:i.name};try{let a=JSON.parse(i.json||"{}");i.name==="create_files"&&a&&(Array.isArray(a.files)&&A.push(...a.files),typeof a.summary=="string"&&a.summary.trim()&&(h+=`
|
|
31
31
|
${a.summary}`)),i.name==="ask_user"&&a&&typeof a.question=="string"&&a.question.trim()&&(b=a.question,Array.isArray(a.options)&&a.options.length&&(b+=`
|
|
32
32
|
Options: ${a.options.join(", ")}`))}catch{}finally{i=null}}i={name:u.content_block.name,id:u.content_block.id,json:""},yield{type:"tool_use_start",name:i.name,id:i.id}}if(u.type==="content_block_delta"&&u.delta?.type==="text_delta"&&(h+=u.delta.text,yield{type:"text_delta",text:u.delta.text}),u.type==="content_block_delta"&&u.delta?.type==="input_json_delta"&&(i&&(i.json+=u.delta.partial_json||""),yield{type:"tool_use_delta",json:u.delta.partial_json}),u.type==="content_block_stop"&&i){yield{type:"tool_use_end",name:i.name};try{let a=JSON.parse(i.json||"{}");i.name==="create_files"&&a&&(Array.isArray(a.files)&&A.push(...a.files),typeof a.summary=="string"&&a.summary.trim()&&(h+=`
|
|
@@ -43,12 +43,12 @@ Reply with:
|
|
|
43
43
|
- cancel`;let p=_=>/^(question|clarification|clarify|i need|need more|before i proceed|to proceed|please (confirm|clarify)|which|what|where|when|how|do you)/i.test(_.trim()),m=-1;for(let _=n.length-1;_>=0;_--){let d=n[_].trim();if(d&&(p(d)||d.includes("?"))){m=_;break}}if(m===-1)return;let c=[];for(let _=m;_<n.length&&c.length<8;_++){let d=n[_],h=d.trim();if(c.length>0&&!h||c.length>0&&!/^(options?:|[-*]\s|\d+[\).]\s)/i.test(h)&&!h.includes("?"))break;c.push(d.trimEnd())}let g=c.join(`
|
|
44
44
|
`).trim();if(!(g.length<5))return g.length>800?g.slice(0,800).trimEnd():g}parseApiResponse(e){let t=[],r="",n;for(let o of e.content)if(o.type==="text"&&(r+=o.text||""),o.type==="tool_use"){if(o.name==="create_files"&&o.input){let l=o.input;t.push(...l.files||[]),l.summary&&(r+=`
|
|
45
45
|
${l.summary}`)}if(o.name==="ask_user"&&o.input){let l=o.input;n=l.question,l.options?.length&&(n+=`
|
|
46
|
-
Options: ${l.options.join(", ")}`)}}return{content:r,files:t,followUp:n,tokensUsed:e.usage.input_tokens+e.usage.output_tokens}}}});var
|
|
47
|
-
`);g=T.pop()||"";for(let x of T){if(!x.startsWith("data: "))continue;let u=x.slice(6).trim();if(!u||u==="[DONE]")continue;let a;try{a=JSON.parse(u)}catch{continue}let k=a.choices?.[0],O=k?.delta;if(k?.finish_reason&&(A=k.finish_reason),typeof O?.reasoning_content=="string"&&O.reasoning_content&&(d+=O.reasoning_content,yield{type:"thinking_delta",text:O.reasoning_content}),typeof O?.content=="string"&&O.content&&(_+=O.content,yield{type:"text_delta",text:O.content}),Array.isArray(O?.tool_calls))for(let v of O.tool_calls){let j=v.index;if(j==null)continue;let P=b[j]||={id:"",name:"",argumentsRaw:""};v.id&&(P.id=v.id),v.function?.name&&(P.name=v.function.name),v.function?.arguments&&(P.argumentsRaw+=v.function.arguments)}a.usage&&(h=a.usage.prompt_tokens||0,w=a.usage.completion_tokens||0)}}}catch(f){if(f?.name==="AbortError"||n?.abortSignal?.aborted){yield{type:"error",error:"cancelled"};return}yield{type:"error",error:`OpenAI-compat raw stream read failed: ${f?.message??f}`};return}finally{n?.abortSignal&&n.abortSignal.removeEventListener("abort",m)}let i=[];d&&i.push({type:"reasoning",text:d}),_&&i.push({type:"text",text:_});for(let f of Object.values(b)){if(!f.id||!f.name)continue;let R={};try{R=f.argumentsRaw?JSON.parse(f.argumentsRaw):{}}catch{}i.push({type:"tool_use",id:f.id,name:f.name,input:R})}let y="end_turn";switch(A){case"tool_calls":case"function_call":y="tool_use";break;case"length":y="max_tokens";break}yield{type:"raw_result",result:{content:i,stop_reason:y,usage:{input_tokens:h,output_tokens:w}}}}buildRawBody(e,t,r,n){let o=n?.model||process.env.OPENAI_MODEL||
|
|
46
|
+
Options: ${l.options.join(", ")}`)}}return{content:r,files:t,followUp:n,tokensUsed:e.usage.input_tokens+e.usage.output_tokens}}}});var le,pe,U,ue=N(()=>{"use strict";W();le="gpt-4o-mini",pe=8192,U=class{name="openai";apiKey;baseUrl;thinkingEnabled;constructor(e,t,r={}){this.apiKey=e||process.env.OPENAI_API_KEY||"",this.baseUrl=(t||process.env.OPENAI_BASE_URL||"https://api.openai.com/v1").replace(/\/$/,"");let n=this.baseUrl.includes("deepseek.com");if(this.thinkingEnabled=n?r.thinking!==!1:null,!this.apiKey)throw new Error("OpenAI-compatible API key required. Set OPENAI_API_KEY (or pass --api-key). For DeepSeek, also set OPENAI_BASE_URL=https://api.deepseek.com/v1.")}async generate(e,t){let r=t?.model||process.env.OPENAI_MODEL||le,n=t?.maxTokens||pe,o=e.map(m=>({role:m.role,content:m.content})),l={model:r,max_tokens:n,messages:o,tools:this.legacyToolsAsOpenAI()};t?.temperature!==void 0&&(l.temperature=t.temperature);let p=await this.callApi(l);return this.parseHighLevelResponse(p)}async generateRaw(e,t,r,n){let o=this.buildRawBody(e,t,r,n),l=await this.callApi(o,n?.abortSignal);return this.parseRawResponse(l)}async*generateRawStream(e,t,r,n){let o={...this.buildRawBody(e,t,r,n),stream:!0,stream_options:{include_usage:!0}},l;try{l=await fetch(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(this.maybeDeepseekExtras(o)),signal:n?.abortSignal})}catch(f){if(f?.name==="AbortError"||n?.abortSignal?.aborted){yield{type:"error",error:"cancelled"};return}yield{type:"error",error:`OpenAI-compat raw stream init failed: ${f?.message??f}`};return}if(!l.ok){let f=await l.text().catch(()=>"");yield{type:"error",error:`OpenAI-compat API error (${l.status}): ${f.slice(0,500)}`};return}let p=l.body?.getReader();if(!p){yield{type:"error",error:"No response body on OpenAI-compat raw stream"};return}let m=()=>{p.cancel(new Error("aborted")).catch(()=>{})};n?.abortSignal&&(n.abortSignal.aborted?m():n.abortSignal.addEventListener("abort",m,{once:!0}));let c=new TextDecoder,g="",_="",d="",h=0,w=0,A=null,b={};try{for(;;){if(n?.abortSignal?.aborted){yield{type:"error",error:"cancelled"};return}let{done:f,value:R}=await p.read();if(f)break;g+=c.decode(R,{stream:!0});let T=g.split(`
|
|
47
|
+
`);g=T.pop()||"";for(let x of T){if(!x.startsWith("data: "))continue;let u=x.slice(6).trim();if(!u||u==="[DONE]")continue;let a;try{a=JSON.parse(u)}catch{continue}let k=a.choices?.[0],O=k?.delta;if(k?.finish_reason&&(A=k.finish_reason),typeof O?.reasoning_content=="string"&&O.reasoning_content&&(d+=O.reasoning_content,yield{type:"thinking_delta",text:O.reasoning_content}),typeof O?.content=="string"&&O.content&&(_+=O.content,yield{type:"text_delta",text:O.content}),Array.isArray(O?.tool_calls))for(let v of O.tool_calls){let j=v.index;if(j==null)continue;let P=b[j]||={id:"",name:"",argumentsRaw:""};v.id&&(P.id=v.id),v.function?.name&&(P.name=v.function.name),v.function?.arguments&&(P.argumentsRaw+=v.function.arguments)}a.usage&&(h=a.usage.prompt_tokens||0,w=a.usage.completion_tokens||0)}}}catch(f){if(f?.name==="AbortError"||n?.abortSignal?.aborted){yield{type:"error",error:"cancelled"};return}yield{type:"error",error:`OpenAI-compat raw stream read failed: ${f?.message??f}`};return}finally{n?.abortSignal&&n.abortSignal.removeEventListener("abort",m)}let i=[];d&&i.push({type:"reasoning",text:d}),_&&i.push({type:"text",text:_});for(let f of Object.values(b)){if(!f.id||!f.name)continue;let R={};try{R=f.argumentsRaw?JSON.parse(f.argumentsRaw):{}}catch{}i.push({type:"tool_use",id:f.id,name:f.name,input:R})}let y="end_turn";switch(A){case"tool_calls":case"function_call":y="tool_use";break;case"length":y="max_tokens";break}yield{type:"raw_result",result:{content:i,stop_reason:y,usage:{input_tokens:h,output_tokens:w}}}}buildRawBody(e,t,r,n){let o=n?.model||process.env.OPENAI_MODEL||le,l=n?.maxTokens||pe,p=t?[{role:"system",content:t}]:[];for(let c of e){let g=Array.isArray(c.content)?c.content:[{type:"text",text:c.content}];if(c.role==="user"){let _=g.filter(h=>h.type==="tool_result"),d=g.filter(h=>h.type==="text").map(h=>h.text).join("");for(let h of _)p.push({role:"tool",tool_call_id:h.tool_use_id,content:h.is_error?`[error] ${h.content}`:h.content});d?p.push({role:"user",content:d}):_.length===0&&p.push({role:"user",content:c.content})}else{let _=g.filter(A=>A.type==="tool_use"),d=g.filter(A=>A.type==="text").map(A=>A.text).join(""),h=g.filter(A=>A.type==="reasoning").map(A=>A.text).join(""),w={role:"assistant",content:d||null};_.length>0&&(w.tool_calls=_.map(A=>({id:A.id,type:"function",function:{name:A.name,arguments:JSON.stringify(A.input||{})}}))),h&&(w.reasoning_content=h),p.push(w)}}let m={model:o,max_tokens:l,messages:p,tools:r.map(c=>({type:"function",function:{name:c.name,description:c.description,parameters:c.input_schema}})),tool_choice:"auto"};return n?.temperature!==void 0&&(m.temperature=n.temperature),n?.toolChoice&&(m.tool_choice={type:"function",function:{name:n.toolChoice.name}}),n?.responseFormat&&(m.response_format={type:"json_schema",json_schema:{name:n.responseFormat.name,schema:n.responseFormat.schema,strict:!0}}),n?.logprobs?.enabled&&(m.logprobs=!0,m.top_logprobs=n.logprobs.topK),m}async*stream(e,t){let r=t?.model||process.env.OPENAI_MODEL||le,n=t?.maxTokens||pe,o=e.map(i=>({role:i.role,content:i.content})),l={model:r,max_tokens:n,messages:o,tools:this.legacyToolsAsOpenAI(),stream:!0,stream_options:{include_usage:!0}};t?.temperature!==void 0&&(l.temperature=t.temperature);let p;try{p=await fetch(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(this.maybeDeepseekExtras(l))})}catch(i){yield{type:"error",error:`OpenAI-compat stream init failed: ${i.message}`};return}if(!p.ok){let i=await p.text().catch(()=>"");yield{type:"error",error:`OpenAI-compat API error (${p.status}): ${i.slice(0,500)}`};return}let m=p.body?.getReader();if(!m){yield{type:"error",error:"No response body on OpenAI-compat stream"};return}let c=new TextDecoder,g="",_="",d,h=0,w=[],A={},b={};try{for(;;){let{done:i,value:y}=await m.read();if(i)break;g+=c.decode(y,{stream:!0});let f=g.split(`
|
|
48
48
|
`);g=f.pop()||"";for(let R of f){if(!R.startsWith("data: "))continue;let T=R.slice(6).trim();if(T==="[DONE]")continue;let x;try{x=JSON.parse(T)}catch{continue}let a=x.choices?.[0]?.delta;if(typeof a?.reasoning_content=="string"&&a.reasoning_content&&(yield{type:"thinking_delta",text:a.reasoning_content}),typeof a?.content=="string"&&a.content&&(_+=a.content,yield{type:"text_delta",text:a.content}),Array.isArray(a?.tool_calls))for(let k of a.tool_calls){let O=k.index;if(O==null)continue;let v=A[O]||={id:"",name:"",argumentsRaw:""};k.id&&(v.id=k.id),k.function?.name&&(v.name=k.function.name),k.function?.arguments&&(v.argumentsRaw+=k.function.arguments),v.id&&v.name&&!b[O]&&(b[O]=!0,yield{type:"tool_use_start",name:v.name,id:v.id}),b[O]&&k.function?.arguments&&(yield{type:"tool_use_delta",json:k.function.arguments})}x.usage&&(h=(x.usage.prompt_tokens||0)+(x.usage.completion_tokens||0))}}}catch(i){yield{type:"error",error:`OpenAI-compat stream read failed: ${i.message}`};return}for(let i of Object.values(A))if(i.name){yield{type:"tool_use_end",name:i.name};try{let y=i.argumentsRaw?JSON.parse(i.argumentsRaw):{};i.name==="create_files"&&Array.isArray(y.files)?(w.push(...y.files),typeof y.summary=="string"&&y.summary.trim()&&(_+=(_?`
|
|
49
49
|
`:"")+y.summary)):i.name==="ask_user"&&typeof y.question=="string"&&(d=y.question,Array.isArray(y.options)&&y.options.length&&(d+=`
|
|
50
50
|
Options: ${y.options.join(", ")}`))}catch{}}yield{type:"done",result:{content:_,files:w,followUp:d,tokensUsed:h}}}async callApi(e,t){let r=await fetch(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(this.maybeDeepseekExtras(e)),signal:t});if(!r.ok){let n=await r.text().catch(()=>"");throw new Error(`OpenAI-compatible API error (${r.status}) ${this.baseUrl}: ${n.slice(0,500)}`)}return await r.json()}maybeDeepseekExtras(e){return this.thinkingEnabled===null?e:this.thinkingEnabled===!1?{...e,enable_thinking:!1}:e}parseHighLevelResponse(e){let r=e.choices?.[0]?.message,n=[],o=r?.content||"",l;for(let m of r?.tool_calls||[]){let c={};try{c=JSON.parse(m.function.arguments||"{}")}catch{}m.function.name==="create_files"&&Array.isArray(c.files)?(n.push(...c.files),typeof c.summary=="string"&&c.summary.trim()&&(o+=(o?`
|
|
51
51
|
`:"")+c.summary)):m.function.name==="ask_user"&&typeof c.question=="string"&&(l=c.question,Array.isArray(c.options)&&c.options.length&&(l+=`
|
|
52
|
-
Options: ${c.options.join(", ")}`))}let p=e.usage;return{content:o,files:n,followUp:l,tokensUsed:p?(p.prompt_tokens||0)+(p.completion_tokens||0):void 0}}parseRawResponse(e){let t=e.choices?.[0],r=t?.message,n=[];r?.reasoning_content&&n.push({type:"reasoning",text:r.reasoning_content}),r?.content&&n.push({type:"text",text:r.content});for(let p of r?.tool_calls||[]){let m={};try{m=p.function.arguments?JSON.parse(p.function.arguments):{}}catch{}n.push({type:"tool_use",id:p.id,name:p.function.name,input:m})}let o="end_turn";switch(t?.finish_reason){case"tool_calls":case"function_call":o="tool_use";break;case"length":o="max_tokens";break;case"stop":case null:case void 0:default:o="end_turn"}let l=e.usage;return{content:n,stop_reason:o,usage:{input_tokens:l?.prompt_tokens||0,output_tokens:l?.completion_tokens||0}}}legacyToolsAsOpenAI(){return C().map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.input_schema}}))}}});import{readFileSync as
|
|
53
|
-
`)}return""}function M(s,e){return new Promise((t,r)=>{if(e?.aborted)return r(new Error("aborted"));let n=setTimeout(t,s);e?.addEventListener("abort",()=>{clearTimeout(n),r(new Error("aborted"))},{once:!0})})}function Q(s){return s.match(/\S+\s*/g)||[s]}var
|
|
54
|
-
//# sourceMappingURL=chunk-
|
|
52
|
+
Options: ${c.options.join(", ")}`))}let p=e.usage;return{content:o,files:n,followUp:l,tokensUsed:p?(p.prompt_tokens||0)+(p.completion_tokens||0):void 0}}parseRawResponse(e){let t=e.choices?.[0],r=t?.message,n=[];r?.reasoning_content&&n.push({type:"reasoning",text:r.reasoning_content}),r?.content&&n.push({type:"text",text:r.content});for(let p of r?.tool_calls||[]){let m={};try{m=p.function.arguments?JSON.parse(p.function.arguments):{}}catch{}n.push({type:"tool_use",id:p.id,name:p.function.name,input:m})}let o="end_turn";switch(t?.finish_reason){case"tool_calls":case"function_call":o="tool_use";break;case"length":o="max_tokens";break;case"stop":case null:case void 0:default:o="end_turn"}let l=e.usage;return{content:n,stop_reason:o,usage:{input_tokens:l?.prompt_tokens||0,output_tokens:l?.completion_tokens||0}}}legacyToolsAsOpenAI(){return C().map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.input_schema}}))}}});import{readFileSync as Ne}from"fs";function $e(){let s=process.env.AGENTX_DEMO_SCRIPT;if(!s)return{steps:[],fallback:de};try{let e=JSON.parse(Ne(s,"utf-8"));return{steps:Array.isArray(e.steps)?e.steps:[],fallback:e.fallback||de}}catch(e){return{steps:[],fallback:{reply:`Demo script unreadable (${e.message}) \u2014 check AGENTX_DEMO_SCRIPT.`}}}}function D(s){for(let e=s.length-1;e>=0;e--){if(s[e].role!=="user")continue;let t=s[e].content;if(typeof t=="string")return t;if(Array.isArray(t))return t.map(r=>r?.type==="text"?r.text:r?.type==="tool_result"?r.content:"").filter(Boolean).join(`
|
|
53
|
+
`)}return""}function M(s,e){return new Promise((t,r)=>{if(e?.aborted)return r(new Error("aborted"));let n=setTimeout(t,s);e?.addEventListener("abort",()=>{clearTimeout(n),r(new Error("aborted"))},{once:!0})})}function Q(s){return s.match(/\S+\s*/g)||[s]}var de,F,Z,_e=N(()=>{"use strict";de={reply:"This is demo mode \u2014 I answer from a script, not a live model. Run `agentx setup` to connect a real provider."};F=s=>Math.max(1,Math.round(s.length/4)),Z=class{name="demo";script;constructor(){this.script=$e()}pick(e){let t,r=-1;for(let o of this.script.steps)try{let l=new RegExp(o.match,"ig"),p,m=-1;for(;(p=l.exec(e))!==null;)m=p.index,p.index===l.lastIndex&&l.lastIndex++;m>r&&(r=m,t=o)}catch{}if(t)return{reply:t.reply,thinking:t.thinking,delayMs:t.delayMs??700,chunkMs:t.chunkMs??35};let n=this.script.fallback||de;return{reply:n.reply,thinking:n.thinking,delayMs:n.delayMs??700,chunkMs:n.chunkMs??35}}async generate(e,t){let r=this.pick(D(e));return await M(r.delayMs,t?.abortSignal),{content:r.reply,files:[],tokensUsed:F(r.reply)}}async*stream(e,t){let r=this.pick(D(e));if(await M(r.delayMs,t?.abortSignal),r.thinking)for(let n of Q(r.thinking))yield{type:"thinking_delta",text:n},await M(r.chunkMs,t?.abortSignal);for(let n of Q(r.reply))yield{type:"text_delta",text:n},await M(r.chunkMs,t?.abortSignal);yield{type:"done",result:{content:r.reply,files:[],tokensUsed:F(r.reply)}}}async generateRaw(e,t,r,n){let o=this.pick(D(e));return await M(o.delayMs,n?.abortSignal),{content:[{type:"text",text:o.reply}],stop_reason:"end_turn",usage:{input_tokens:F(D(e)),output_tokens:F(o.reply)}}}async*generateRawStream(e,t,r,n){let o=this.pick(D(e));if(await M(o.delayMs,n?.abortSignal),o.thinking)for(let l of Q(o.thinking))yield{type:"thinking_delta",text:l},await M(o.chunkMs,n?.abortSignal);for(let l of Q(o.reply))yield{type:"text_delta",text:l},await M(o.chunkMs,n?.abortSignal);yield{type:"raw_result",result:{content:[{type:"text",text:o.reply}],stop_reason:"end_turn",usage:{input_tokens:F(D(e)),output_tokens:F(o.reply)}}}}}});function dt(s="claude-code",e,t={}){let r=s;if(s==="claude-code"&&!e){let n=S();n&&(r=n.provider)}switch(r){case"claude-code":return new J;case"claude":return new q(e);case"openai":return new U(e,void 0,{thinking:t.thinking});case"deepseek":return new U(e||process.env[ke.envKey]||process.env.OPENAI_API_KEY,ke.baseUrl,{thinking:t.thinking});case"demo":return new Z;case"ollama":throw new Error("Ollama provider coming soon. Workaround: set provider to 'openai' with OPENAI_BASE_URL=http://localhost:11434/v1 (Ollama exposes an OpenAI-compatible endpoint). Or contribute at github.com/anis-marrouchi/agentx");default:throw new Error(`Unknown provider: ${r}. Supported: claude-code, claude, openai, deepseek`)}}var ke,Ge=N(()=>{ie();ce();ue();_e();H();ie();ce();ue();ke={baseUrl:"https://api.deepseek.com/v1",envKey:"DEEPSEEK_API_KEY"}});export{S as a,be as b,L as c,Se as d,Je as e,H as f,Ee as g,C as h,He as i,Ye as j,W as k,q as l,J as m,U as n,dt as o,Ge as p};
|
|
54
|
+
//# sourceMappingURL=chunk-DCIYOPJF.js.map
|