niumagents-cli 0.1.11 → 0.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +177 -91
  2. package/dist/nium.js +1780 -335
  3. package/package.json +19 -16
package/dist/nium.js CHANGED
@@ -1,21 +1,21 @@
1
1
  #!/usr/bin/env node
2
- var Fl=Object.defineProperty;var $r=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var C=(o,e)=>()=>(o&&(e=o(o=0)),e);var j=(o,e)=>{for(var t in e)Fl(o,t,{get:e[t],enumerable:!0})};import ne from"chalk";function jl(o){ht={...ht,...o}}function _o(o){ht.enableDebug=o}function sn(o,e,t,n=!0){let r=[],s=/^[✓✗⚠ℹ◆●]/.test(t);return n&&ht.enableSymbol&&o!=="INFO"&&!s&&r.push(ki[o](Ol[o])),e&&ht.enablePrefix&&r.push(ne.gray(`[${e}]`)),r.push(ki[o](t)),r.join(" ")}function ke(o,e=null){console.error(sn("ERROR",e,o))}function W(o,e=null){console.warn(sn("WARN",e,o))}function se(o,e=null){console.log(sn("INFO",e,o,!1))}function _(o,e=null){console.log(sn("SUCCESS",e,o))}function No(o,e=null){ht.enableDebug&&console.log(sn("DEBUG",e,o))}function an(o){console.log(o)}function Mr(o="\u2500",e=50){console.log(ne.gray(o.repeat(e)))}function _l(o,e="\u2550",t=50){let n=Math.max(0,Math.floor((t-o.length-2)/2)),r=e.repeat(t),s=e.repeat(n)+` ${o} `+e.repeat(n);console.log(ne.cyan(r)),console.log(ne.cyan(s)),console.log(ne.cyan(r))}function Nl(o,e,t){let n=Math.round(o/e*100),r="\u2588".repeat(Math.floor(n/5))+"\u2591".repeat(20-Math.floor(n/5));console.log(ne.blue(`[${o}/${e}]`)+" "+ne.cyan(r)+" "+ne.white(`${n}%`)+" "+ne.gray(t))}function Ul(o){for(let[e,t]of Object.entries(o))console.log(ne.cyan(` ${e}: `)+ne.white(t))}function Uo(){console.clear()}var Ol,ki,ht,cn=C(()=>{Ol={SUCCESS:"\u2713",ERROR:"\u2717",WARN:"\u26A0",INFO:"\u2139",DEBUG:"\u25C6"},ki={ERROR:ne.red,WARN:ne.yellow,INFO:ne.blue,SUCCESS:ne.green,DEBUG:ne.magenta},ht={enableDebug:!1,enablePrefix:!0,enableSymbol:!0}});import{existsSync as Me,mkdirSync as ln,copyFileSync as Ei,writeFileSync as Wl}from"fs";import{join as ie,dirname as Pi}from"path";import{fileURLToPath as Vl}from"url";function $i(){let o=[ie(un,"..","..","examples"),ie(un,"..","examples"),ie(un,"examples"),ie(un,"..","..","..","examples")];for(let e of o)if(Me(e))return Pi(e);return ie(un,"..")}function Mi(){return Wo||(Wo=ie(process.cwd(),".nium")),Wo}function zl(){if(!zo){let o=$i();zo=ie(o,"examples","config.example.json")}return zo}function Hl(){if(!Vo){let o=$i();Vo=ie(o,"examples",".env.example")}return Vo}function Ii(){let o=Mi(),e=zl();try{if(!Me(o)){se("\u521D\u59CB\u5316\u5DE5\u4F5C\u76EE\u5F55...","Init"),ln(o,{recursive:!0}),_("\u521B\u5EFA .nium \u76EE\u5F55","Init");let c=ie(o,"config.json");Me(e)?(Ei(e,c),_("\u590D\u5236 config.example.json \u5230 .nium/config.json","Init"),W("\u8BF7\u7F16\u8F91 .nium/config.json \u6587\u4EF6\u914D\u7F6E API \u5BC6\u94A5\u548C\u6A21\u578B","Init")):(W(`\u672A\u627E\u5230 config.example.json: ${e}`,"Init"),Wl(c,JSON.stringify({models:{defaultModel:{apiKey:"your-api-key-here",baseURL:"https://api.openai.com/v1",model:"gpt-4o",provider:"openai",maxToken:128e3},liteModel:{apiKey:"your-api-key-here",baseURL:"https://api.openai.com/v1",model:"gpt-3.5-turbo",provider:"openai",maxToken:16385}},mcpServers:[]},null,2)),_("\u521B\u5EFA\u9ED8\u8BA4\u7684 .nium/config.json \u6587\u4EF6","Init"),W("\u8BF7\u7F16\u8F91 .nium/config.json \u6587\u4EF6\u914D\u7F6E API \u5BC6\u94A5\u548C\u6A21\u578B","Init"))}let t=ie(o,"agents");Me(t)||(ln(t,{recursive:!0}),_("\u521B\u5EFA .nium/agents \u76EE\u5F55","Init"));let n=ie(o,"docs");Me(n)||(ln(n,{recursive:!0}),_("\u521B\u5EFA .nium/docs \u76EE\u5F55","Init"));let r=ie(o,"archives");Me(r)||(ln(r,{recursive:!0}),_("\u521B\u5EFA .nium/archives \u76EE\u5F55","Init"));let s=ie(o,"logs");Me(s)||(ln(s,{recursive:!0}),_("\u521B\u5EFA .nium/logs \u76EE\u5F55","Init"));let i=Hl(),a=ie(o,".env");return Me(a)||(Me(i)?(Ei(i,a),_("\u590D\u5236 examples/.env.example \u5230 .nium/.env","Init")):(W(`\u672A\u627E\u5230 .env.example: ${i}`,"Init"),W("\u5C06\u4F7F\u7528\u9ED8\u8BA4\u73AF\u5883\u53D8\u91CF\u914D\u7F6E","Init"))),o}catch(t){ke(`\u521D\u59CB\u5316\u5DE5\u4F5C\u76EE\u5F55\u5931\u8D25: ${t.message}`,"Init"),process.exit(1)}}function ge(o){return ie(Mi(),o)}var un,Wo,Vo,zo,je=C(()=>{cn();un=typeof __dirname<"u"?__dirname:Pi(Vl(import.meta.url)),Wo=null,Vo=null,zo=null});var Ho,Ir,Jo=C(()=>{Ho={level:"INFO",debugMode:!1,consoleOutput:!0,fileOutput:!0,enableTimestamp:!0,rotationStrategy:"daily",maxFileSize:10485760,maxFiles:30},Ir={ERROR:0,WARN:1,INFO:2,SUCCESS:2,DEBUG:3,TRACE:4}});import yt from"chalk";var gn,D,pn=C(()=>{gn=class{colors;constructor(){this.colors={INFO:yt.blue,WARN:yt.yellow,ERROR:yt.red,SUCCESS:yt.green,DEBUG:yt.magenta,TRACE:yt.gray}}format(e){let t="";if(e.timestamp){let i=new Date(e.timestamp).toLocaleString("zh-CN");t+=`[${i}] `}let n={INFO:"",WARN:"\u26A0",ERROR:"\u2717",SUCCESS:"\u2713",DEBUG:"\u25C6",TRACE:"\u25CF"},r=/^[✓✗⚠ℹ◆●]/.test(e.message),s=e.level==="INFO"||r?"":`${n[e.level]} `;return t+=`[${e.level.padEnd(7)}] ${s}${e.message}`,e.context&&(t+=` ${JSON.stringify(e.context)}`),t}colorize(e,t){let n=this.colors[t];return n(e)}},D=new gn});import{existsSync as Jl,readFileSync as Gl,appendFileSync as Ai,writeFileSync as Bl,createReadStream as ql}from"fs";import{createInterface as Kl}from"readline";var me,fe,dn=C(()=>{me=class{filePath;constructor(e){this.filePath=e}append(e){try{let t=JSON.stringify(e)+`
3
- `;Ai(this.filePath,t,"utf-8")}catch(t){throw new Error(`Failed to append to JSONL file: ${t.message}`)}}appendBatch(e){try{let t=e.map(n=>JSON.stringify(n)).join(`
2
+ var wm=Object.defineProperty;var bm=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var S=(s,e)=>()=>(s&&(e=s(s=0)),e);var B=(s,e)=>{for(var t in e)wm(s,t,{get:e[t],enumerable:!0})};import Se from"chalk";function Tm(s){kn={...kn,...s}}function Lr(s){kn.enableDebug=s}function jr(s,e,t,n=!0){let r=[],o=/^[✓✗⚠ℹ◆●]/.test(t);return n&&kn.enableSymbol&&s!=="INFO"&&!o&&r.push(al[s](vm[s])),e&&kn.enablePrefix&&r.push(Se.gray(`[${e}]`)),r.push(al[s](t)),r.join(" ")}function xe(s,e=null){console.error(jr("ERROR",e,s))}function J(s,e=null){console.warn(jr("WARN",e,s))}function ve(s,e=null){console.log(jr("INFO",e,s,!1))}function X(s,e=null){console.log(jr("SUCCESS",e,s))}function it(s,e=null){kn.enableDebug&&console.log(jr("DEBUG",e,s))}function Dr(s){console.log(s)}function So(s="\u2500",e=50){console.log(Se.gray(s.repeat(e)))}function Pm(s,e="\u2550",t=50){let n=Math.max(0,Math.floor((t-s.length-2)/2)),r=e.repeat(t),o=e.repeat(n)+` ${s} `+e.repeat(n);console.log(Se.cyan(r)),console.log(Se.cyan(o)),console.log(Se.cyan(r))}function km(s,e,t){let n=Math.round(s/e*100),r="\u2588".repeat(Math.floor(n/5))+"\u2591".repeat(20-Math.floor(n/5));console.log(Se.blue(`[${s}/${e}]`)+" "+Se.cyan(r)+" "+Se.white(`${n}%`)+" "+Se.gray(t))}function Em(s){for(let[e,t]of Object.entries(s))console.log(Se.cyan(` ${e}: `)+Se.white(t))}function Yi(){console.clear()}var vm,al,kn,Tt=S(()=>{vm={SUCCESS:"\u2713",ERROR:"\u2717",WARN:"\u26A0",INFO:"\u2139",DEBUG:"\u25C6"},al={ERROR:Se.red,WARN:Se.yellow,INFO:Se.blue,SUCCESS:Se.green,DEBUG:Se.magenta},kn={enableDebug:!1,enablePrefix:!0,enableSymbol:!0}});var pl={};B(pl,{getNiumDir:()=>Rm,getNiumPath:()=>Ee,initWorkspace:()=>Nr});import{existsSync as at,mkdirSync as Fr,copyFileSync as cl,writeFileSync as $m}from"fs";import{join as Te,dirname as ll}from"path";import{fileURLToPath as Im}from"url";function ul(){let s=[Te(Or,"..","..","examples"),Te(Or,"..","examples"),Te(Or,"examples"),Te(Or,"..","..","..","examples")];for(let e of s)if(at(e))return ll(e);return Te(Or,"..")}function ea(){return Xi||(Xi=Te(process.cwd(),".nium")),Xi}function Mm(){if(!Zi){let s=ul();Zi=Te(s,"examples","config.example.json")}return Zi}function Am(){if(!Qi){let s=ul();Qi=Te(s,"examples",".env.example")}return Qi}function Nr(){let s=ea(),e=Mm();try{if(!at(s)){ve("\u521D\u59CB\u5316\u5DE5\u4F5C\u76EE\u5F55...","Init"),Fr(s,{recursive:!0}),X("\u521B\u5EFA .nium \u76EE\u5F55","Init");let c=Te(s,"config.json");at(e)?(cl(e,c),X("\u590D\u5236 config.example.json \u5230 .nium/config.json","Init"),J("\u8BF7\u7F16\u8F91 .nium/config.json \u6587\u4EF6\u914D\u7F6E API \u5BC6\u94A5\u548C\u6A21\u578B","Init")):(J(`\u672A\u627E\u5230 config.example.json: ${e}`,"Init"),$m(c,JSON.stringify({models:{defaultModel:{apiKey:"your-api-key-here",baseURL:"https://api.openai.com/v1",model:"gpt-4o",provider:"openai",maxToken:128e3},liteModel:{apiKey:"your-api-key-here",baseURL:"https://api.openai.com/v1",model:"gpt-3.5-turbo",provider:"openai",maxToken:16385}},mcpServers:[]},null,2)),X("\u521B\u5EFA\u9ED8\u8BA4\u7684 .nium/config.json \u6587\u4EF6","Init"),J("\u8BF7\u7F16\u8F91 .nium/config.json \u6587\u4EF6\u914D\u7F6E API \u5BC6\u94A5\u548C\u6A21\u578B","Init"))}let t=Te(s,"agents");at(t)||(Fr(t,{recursive:!0}),X("\u521B\u5EFA .nium/agents \u76EE\u5F55","Init"));let n=Te(s,"docs");at(n)||(Fr(n,{recursive:!0}),X("\u521B\u5EFA .nium/docs \u76EE\u5F55","Init"));let r=Te(s,"archives");at(r)||(Fr(r,{recursive:!0}),X("\u521B\u5EFA .nium/archives \u76EE\u5F55","Init"));let o=Te(s,"logs");at(o)||(Fr(o,{recursive:!0}),X("\u521B\u5EFA .nium/logs \u76EE\u5F55","Init"));let i=Am(),a=Te(s,".env");return at(a)||(at(i)?(cl(i,a),X("\u590D\u5236 examples/.env.example \u5230 .nium/.env","Init")):(J(`\u672A\u627E\u5230 .env.example: ${i}`,"Init"),J("\u5C06\u4F7F\u7528\u9ED8\u8BA4\u73AF\u5883\u53D8\u91CF\u914D\u7F6E","Init"))),s}catch(t){xe(`\u521D\u59CB\u5316\u5DE5\u4F5C\u76EE\u5F55\u5931\u8D25: ${t.message}`,"Init"),process.exit(1)}}function Ee(s){return Te(ea(),s)}function Rm(){return ea()}var Or,Xi,Qi,Zi,Ye=S(()=>{Tt();Or=typeof __dirname<"u"?__dirname:ll(Im(import.meta.url)),Xi=null,Qi=null,Zi=null});var ta,Co,na=S(()=>{ta={level:"INFO",debugMode:!1,consoleOutput:!0,fileOutput:!0,enableTimestamp:!0,rotationStrategy:"daily",maxFileSize:10485760,maxFiles:30},Co={ERROR:0,WARN:1,INFO:2,SUCCESS:2,DEBUG:3,TRACE:4}});import{formatInTimeZone as Lm,toZonedTime as mx}from"date-fns-tz";function H(s=new Date){let e=s instanceof Date?s:new Date(s);return Lm(e,"Asia/Shanghai","yyyy-MM-dd HH:mm:ss")}var Fe=S(()=>{});import En from"chalk";var _r,K,Ur=S(()=>{Fe();_r=class{colors;constructor(){this.colors={INFO:En.blue,WARN:En.yellow,ERROR:En.red,SUCCESS:En.green,DEBUG:En.magenta,TRACE:En.gray}}format(e){let t="";if(e.timestamp){let i=H(e.timestamp);t+=`[${i}] `}let n={INFO:"",WARN:"\u26A0",ERROR:"\u2717",SUCCESS:"\u2713",DEBUG:"",TRACE:""},r=/^[✓✗⚠ℹ◆●]/.test(e.message),o=e.level==="INFO"||r?"":`${n[e.level]} `;return t+=`[${e.level.padEnd(7)}] ${o}${e.message}`,e.context&&(t+=` ${JSON.stringify(e.context)}`),t}colorize(e,t){let n=this.colors[t];return n(e)}},K=new _r});import{existsSync as jm,readFileSync as Dm,appendFileSync as gl,writeFileSync as Fm,createReadStream as Om}from"fs";import{createInterface as Nm}from"readline";var Ue,We,Wr=S(()=>{Ue=class{filePath;constructor(e){this.filePath=e}append(e){try{let t=JSON.stringify(e)+`
3
+ `;gl(this.filePath,t,"utf-8")}catch(t){throw new Error(`Failed to append to JSONL file: ${t.message}`)}}appendBatch(e){try{let t=e.map(n=>JSON.stringify(n)).join(`
4
4
  `)+`
5
- `;Ai(this.filePath,t,"utf-8")}catch(t){throw new Error(`Failed to append batch to JSONL file: ${t.message}`)}}create(e){try{let t=JSON.stringify(e)+`
6
- `;Bl(this.filePath,t,"utf-8")}catch(t){throw new Error(`Failed to create JSONL file: ${t.message}`)}}getFilePath(){return this.filePath}},fe=class{filePath;constructor(e){this.filePath=e}exists(){return Jl(this.filePath)}readAllSync(e={}){if(!this.exists())return[];try{let n=Gl(this.filePath,"utf-8").split(`
7
- `).filter(c=>c.trim().length>0),r=[],s=e.startLine||0,i=e.limit?s+e.limit:n.length,a=n.slice(s,i);for(let c of a)try{let l=JSON.parse(c);(!e.filter||e.filter(l))&&r.push(l)}catch{console.warn(`Invalid JSON line in ${this.filePath}: ${c.substring(0,50)}...`)}return r}catch(t){throw new Error(`Failed to read JSONL file: ${t.message}`)}}async readStream(e,t={}){if(this.exists())return new Promise((n,r)=>{let s=ql(this.filePath,{encoding:"utf-8"}),i=Kl({input:s,crlfDelay:1/0}),a=0,c=0,l=t.startLine||0,{limit:u}=t;i.on("line",async p=>{try{if(p.trim().length===0)return;if(a<l){a++;return}if(u&&c>=u){i.close();return}let g=JSON.parse(p);(!t.filter||t.filter(g))&&(await e(g,a),c++),a++}catch{console.warn(`Invalid JSON line at line ${a}: ${p.substring(0,50)}...`),a++}}),i.on("close",()=>{n()}),i.on("error",p=>{r(new Error(`Failed to read JSONL stream: ${p.message}`))})})}async count(){if(!this.exists())return 0;let e=0;return await this.readStream(()=>{e++}),e}getFilePath(){return this.filePath}}});import{existsSync as Go,mkdirSync as Yl,renameSync as Xl,writeFileSync as Li}from"fs";import{join as mn}from"path";function Ar(){return re.initLogger()}function Ri(o){re.configureLogger(o)}function Lr(o){re.setDebugMode(o)}function Di(o){re.setLogLevel(o)}function Fi(o){re.setFormatter(o)}var fn,re,Bo=C(()=>{je();dn();Jo();pn();fn=class{config;logsDir;currentLogPath;logDatePath;isInitialized=!1;formatter;constructor(){this.config={...Ho},this.logsDir=ge("logs"),this.currentLogPath=mn(this.logsDir,"current.jsonl"),this.logDatePath=mn(this.logsDir,".current_date"),this.formatter=D}getTodayDateString(){let e=new Date,t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0");return`${t}-${n}-${r}`}async getLogFileDate(){try{return Go(this.logDatePath)&&new fe(this.logDatePath).readAllSync()[0]?.date||null}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(D.colorize(`\u8BFB\u53D6\u65E5\u5FD7\u6587\u4EF6\u65E5\u671F\u5931\u8D25: ${t}`,"ERROR")),null}}async archiveLogFile(e){try{let t=mn(this.logsDir,`${e}.jsonl`);if(Go(t)){let r=new fe(this.currentLogPath).readAllSync();await new me(t).appendBatch(r),console.log(D.colorize(`\u2713 \u65E5\u5FD7\u5DF2\u8FFD\u52A0\u5230\u5F52\u6863\u6587\u4EF6: ${e}.jsonl`,"SUCCESS"))}else Xl(this.currentLogPath,t),console.log(D.colorize(`\u2713 \u65E5\u5FD7\u5DF2\u5F52\u6863: ${e}.jsonl`,"SUCCESS"))}catch(t){let n=t instanceof Error?t.message:String(t);console.error(D.colorize(`\u5F52\u6863\u65E5\u5FD7\u5931\u8D25: ${n}`,"ERROR"))}}async createNewLogFile(e){try{Li(this.currentLogPath,"","utf-8"),Li(this.logDatePath,JSON.stringify({date:e})+`
8
- `,"utf-8");let t=new me(this.currentLogPath),n={timestamp:new Date().toISOString(),level:"INFO",message:`\u65E5\u5FD7\u6587\u4EF6\u521B\u5EFA - \u65E5\u671F: ${e}`,date:e};await t.append(n)}catch(t){let n=t instanceof Error?t.message:String(t);console.error(D.colorize(`\u521B\u5EFA\u65E5\u5FD7\u6587\u4EF6\u5931\u8D25: ${n}`,"ERROR"))}}async initLogger(){try{Go(this.logsDir)||(Yl(this.logsDir,{recursive:!0}),console.log(D.colorize("\u521B\u5EFA\u65E5\u5FD7\u76EE\u5F55: .nium/logs","DEBUG")));let e=this.getTodayDateString(),t=await this.getLogFileDate();(!t||t!==e)&&(t&&(console.log(D.colorize(`\u68C0\u6D4B\u5230\u65E7\u65E5\u5FD7\u6587\u4EF6 (${t})\uFF0C\u6B63\u5728\u5F52\u6863...`,"WARN")),await this.archiveLogFile(t)),await this.createNewLogFile(e),console.log(D.colorize(`\u2713 \u521B\u5EFA\u65B0\u65E5\u5FD7\u6587\u4EF6: ${e}`,"SUCCESS"))),this.isInitialized=!0}catch(e){let t=e instanceof Error?e.message:String(e);console.error(D.colorize(`\u521D\u59CB\u5316\u65E5\u5FD7\u7CFB\u7EDF\u5931\u8D25: ${t}`,"ERROR"))}}configureLogger(e){this.config={...this.config,...e},e.logDir&&(this.logsDir=e.logDir,this.currentLogPath=mn(this.logsDir,"current.jsonl"),this.logDatePath=mn(this.logsDir,".current_date")),e.formatter&&(this.formatter=e.formatter)}setFormatter(e){this.formatter=e}shouldLog(e){let t=this.config.debugMode?"DEBUG":this.config.level;return Ir[e]<=Ir[t]}extractSessionId(e){if(e&&typeof e=="object")return e.sessionId||e.id}hasContextLogMethod(e,t){return e&&typeof e[t]=="function"}async writeLog(e,t,n=null){try{if(!this.shouldLog(e))return;this.isInitialized||await this.initLogger();let r=typeof t=="string"?t:JSON.stringify(t),s=e.toLowerCase();if(this.hasContextLogMethod(n,s)){n[s](t);return}let i=new Date().toISOString(),a=this.getTodayDateString(),c={timestamp:i,level:e,message:r,sessionId:this.extractSessionId(n),date:a};if(this.config.consoleOutput){let l=this.formatter.format(c),u=this.formatter.colorize(l,e);console.log(u)}this.config.fileOutput&&await new me(this.currentLogPath).append(c)}catch(r){let s=r instanceof Error?r.message:String(r);console.error(D.colorize(`\u5199\u5165\u65E5\u5FD7\u5931\u8D25: ${s}`,"ERROR"))}}setDebugMode(e){this.config.debugMode=e}setLogLevel(e){this.config.level=e}},re=new fn});import{join as Oi}from"path";async function ji(o){try{let e=ge("logs"),t=Oi(e,"current.jsonl"),n=new fe(t);return await n.exists()?await n.readAllSync({filter:o?.level?s=>s.level===o.level:void 0,limit:o?.limit}):[]}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(D.colorize(`\u8BFB\u53D6\u65E5\u5FD7\u5931\u8D25: ${t}`,"ERROR")),[]}}async function _i(o,e){try{let t=ge("logs"),n=Oi(t,`${o}.jsonl`),r=new fe(n);return await r.exists()?await r.readAllSync({filter:e?.level?i=>i.level===e.level:void 0,limit:e?.limit}):[]}catch(t){let n=t instanceof Error?t.message:String(t);return console.error(D.colorize(`\u8BFB\u53D6\u5F52\u6863\u65E5\u5FD7\u5931\u8D25: ${n}`,"ERROR")),[]}}function Ni(o){return`[${new Date(o.timestamp).toLocaleString("zh-CN")}] [${o.level.padEnd(7)}] ${o.message}`}function Ui(o){let e={total:o.length,byLevel:{INFO:0,WARN:0,ERROR:0,SUCCESS:0,DEBUG:0,TRACE:0}};for(let t of o)t.level in e.byLevel&&e.byLevel[t.level]++;return e}var Wi=C(()=>{je();dn();pn()});async function Vi(o,e=null){await re.writeLog("INFO",o,e)}async function M(o,e=null){await re.writeLog("INFO",o,e)}async function zi(o,e=null){await re.writeLog("SUCCESS",o,e)}async function qo(o,e=null){await re.writeLog("WARN",o,e)}async function G(o,e=null){await qo(o,e)}async function X(o,e=null){await re.writeLog("ERROR",o,e)}async function x(o,e=null){await re.writeLog("DEBUG",o,e)}async function Hi(o,e=null){await re.writeLog("TRACE",o,e)}function B(o,e=null){Vi(o,e).catch(t=>console.error(D.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}function Qe(o,e=null){M(o,e).catch(t=>console.error(D.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}function hn(o,e=null){zi(o,e).catch(t=>console.error(D.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}function Ct(o,e=null){qo(o,e).catch(t=>console.error(D.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}function Ko(o,e=null){G(o,e).catch(t=>console.error(D.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}function he(o,e=null){X(o,e).catch(t=>console.error(D.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}function Z(o,e=null){x(o,e).catch(t=>console.error(D.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}function Ql(o,e=null){Hi(o,e).catch(t=>console.error(D.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}var Ji=C(()=>{Bo();pn()});var Yo={};j(Yo,{ChalkFormatter:()=>gn,DEFAULT_CONFIG:()=>Ho,LOG_LEVEL_PRIORITIES:()=>Ir,LoggerManager:()=>fn,configureLogger:()=>Ri,consoleClear:()=>Uo,consoleDebug:()=>No,consoleError:()=>ke,consoleInfo:()=>se,consolePlain:()=>an,consoleProgress:()=>Nl,consoleSeparator:()=>Mr,consoleStats:()=>Ul,consoleSuccess:()=>_,consoleTitle:()=>_l,consoleWarn:()=>W,default:()=>re,defaultFormatter:()=>D,formatLogEntry:()=>Ni,getLogStats:()=>Ui,initLogger:()=>Ar,log:()=>Vi,logDebug:()=>x,logDebugSync:()=>Z,logError:()=>X,logErrorSync:()=>he,logInfo:()=>M,logInfoSync:()=>Qe,logSuccess:()=>zi,logSuccessSync:()=>hn,logSync:()=>B,logTrace:()=>Hi,logTraceSync:()=>Ql,logWarn:()=>G,logWarnSync:()=>Ko,logWarning:()=>qo,logWarningSync:()=>Ct,loggerManager:()=>re,readArchivedLogs:()=>_i,readCurrentLogs:()=>ji,setConsoleDebugMode:()=>_o,setConsoleLoggerConfig:()=>jl,setDebugMode:()=>Lr,setFormatter:()=>Fi,setLogLevel:()=>Di});var Y=C(()=>{Jo();pn();Bo();Wi();Ji();cn()});import{existsSync as Gi,mkdirSync as Zl,readdirSync as eu}from"fs";import{join as Bi}from"path";function qi(){Gi(xt)||Zl(xt,{recursive:!0})}function Ki(o){if(!o||!o.messages||o.messages.length===0)return null;qi();let e=new Date().toISOString().replace(/[:.]/g,"-"),t=o.sessionId?o.sessionId.substring(0,8):"unknown",n=o.currentTask?o.currentTask.substring(0,30).replace(/[^\w\u4e00-\u9fa5]/g,"_"):"unnamed",r=`session_${t}_${e}_${n}.jsonl`,s=Bi(xt,r),i={type:"session_metadata",data:{sessionId:o.sessionId,currentTask:o.currentTask,createdAt:o.createdAt,archivedAt:new Date().toISOString(),messageCount:o.messages.length,taskCount:o.tasks?o.tasks.length:0}};try{let a=new me(s);if(a.create(i),o.tasks&&o.tasks.length>0){let c={type:"tasks_data",data:o.tasks};a.append(c)}o.messages&&o.messages.length>0&&o.messages.map(l=>({...l,id:l.id||`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`})).forEach(l=>{a.append({type:"message",data:l})})}catch(a){return console.error("\u5F52\u6863\u4F1A\u8BDD\u5931\u8D25:",a),null}return s}function tu(){return qi(),Gi(xt)?eu(xt).filter(e=>e.endsWith(".jsonl")).map(e=>{let t=Bi(xt,e);try{let r=new fe(t).readAllSync({limit:1})[0];return!r||r.type!=="session_metadata"?null:{fileName:e,filePath:t,sessionId:r.data.sessionId,sessionIdShort:r.data.sessionId?r.data.sessionId.substring(0,8):"unknown",currentTask:r.data.currentTask||"\u672A\u547D\u540D\u4EFB\u52A1",timestamp:r.data.archivedAt,archivedAt:r.data.archivedAt,messageCount:r.data.messageCount||0,taskCount:r.data.taskCount||0}}catch(n){return console.error(`\u8BFB\u53D6\u5F52\u6863\u6587\u4EF6\u5931\u8D25: ${e}`,n),null}}).filter(e=>e!==null).sort((e,t)=>new Date(t.archivedAt).getTime()-new Date(e.archivedAt).getTime()):[]}function Yi(){let o=tu();if(o.length===0)return"\u6682\u65E0\u5F52\u6863\u4F1A\u8BDD";let e=`
5
+ `;gl(this.filePath,t,"utf-8")}catch(t){throw new Error(`Failed to append batch to JSONL file: ${t.message}`)}}create(e){try{let t=JSON.stringify(e)+`
6
+ `;Fm(this.filePath,t,"utf-8")}catch(t){throw new Error(`Failed to create JSONL file: ${t.message}`)}}getFilePath(){return this.filePath}},We=class{filePath;constructor(e){this.filePath=e}exists(){return jm(this.filePath)}readAllSync(e={}){if(!this.exists())return[];try{let n=Dm(this.filePath,"utf-8").split(`
7
+ `).filter(c=>c.trim().length>0),r=[],o=e.startLine||0,i=e.limit?o+e.limit:n.length,a=n.slice(o,i);for(let c of a)try{let l=JSON.parse(c);(!e.filter||e.filter(l))&&r.push(l)}catch{console.warn(`Invalid JSON line in ${this.filePath}: ${c.substring(0,50)}...`)}return r}catch(t){throw new Error(`Failed to read JSONL file: ${t.message}`)}}async readStream(e,t={}){if(this.exists())return new Promise((n,r)=>{let o=Om(this.filePath,{encoding:"utf-8"}),i=Nm({input:o,crlfDelay:1/0}),a=0,c=0,l=t.startLine||0,{limit:u}=t;i.on("line",async p=>{try{if(p.trim().length===0)return;if(a<l){a++;return}if(u&&c>=u){i.close();return}let g=JSON.parse(p);(!t.filter||t.filter(g))&&(await e(g,a),c++),a++}catch{console.warn(`Invalid JSON line at line ${a}: ${p.substring(0,50)}...`),a++}}),i.on("close",()=>{n()}),i.on("error",p=>{r(new Error(`Failed to read JSONL stream: ${p.message}`))})})}async count(){if(!this.exists())return 0;let e=0;return await this.readStream(()=>{e++}),e}getFilePath(){return this.filePath}}});import{existsSync as ra,mkdirSync as _m,renameSync as Um,writeFileSync as ml}from"fs";import{join as Br}from"path";function $n(){return Ce.initLogger()}function dl(s){Ce.configureLogger(s)}function In(s){Ce.setDebugMode(s)}function fl(s){Ce.setLogLevel(s)}function hl(s){Ce.setFormatter(s)}var Hr,Ce,sa=S(()=>{Ye();Wr();Fe();na();Ur();Hr=class{config;logsDir;currentLogPath;logDatePath;isInitialized=!1;formatter;constructor(){this.config={...ta},this.logsDir=Ee("logs"),this.currentLogPath=Br(this.logsDir,"current.jsonl"),this.logDatePath=Br(this.logsDir,".current_date"),this.formatter=K}getLocalTimestamp(){return H(new Date)}getTodayDateString(){let e=new Date,t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0");return`${t}-${n}-${r}`}async getLogFileDate(){try{return ra(this.logDatePath)&&new We(this.logDatePath).readAllSync()[0]?.date||null}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(K.colorize(`\u8BFB\u53D6\u65E5\u5FD7\u6587\u4EF6\u65E5\u671F\u5931\u8D25: ${t}`,"ERROR")),null}}async archiveLogFile(e){try{let t=Br(this.logsDir,`${e}.jsonl`);if(ra(t)){let r=new We(this.currentLogPath).readAllSync();await new Ue(t).appendBatch(r),console.log(K.colorize(`\u2713 \u65E5\u5FD7\u5DF2\u8FFD\u52A0\u5230\u5F52\u6863\u6587\u4EF6: ${e}.jsonl`,"SUCCESS"))}else Um(this.currentLogPath,t),console.log(K.colorize(`\u2713 \u65E5\u5FD7\u5DF2\u5F52\u6863: ${e}.jsonl`,"SUCCESS"))}catch(t){let n=t instanceof Error?t.message:String(t);console.error(K.colorize(`\u5F52\u6863\u65E5\u5FD7\u5931\u8D25: ${n}`,"ERROR"))}}async createNewLogFile(e){try{ml(this.currentLogPath,"","utf-8"),ml(this.logDatePath,JSON.stringify({date:e})+`
8
+ `,"utf-8");let t=new Ue(this.currentLogPath),n={timestamp:this.getLocalTimestamp(),level:"INFO",message:`\u65E5\u5FD7\u6587\u4EF6\u521B\u5EFA - \u65E5\u671F: ${e}`,date:e};await t.append(n)}catch(t){let n=t instanceof Error?t.message:String(t);console.error(K.colorize(`\u521B\u5EFA\u65E5\u5FD7\u6587\u4EF6\u5931\u8D25: ${n}`,"ERROR"))}}async initLogger(){try{ra(this.logsDir)||(_m(this.logsDir,{recursive:!0}),console.log(K.colorize("\u521B\u5EFA\u65E5\u5FD7\u76EE\u5F55: .nium/logs","DEBUG")));let e=this.getTodayDateString(),t=await this.getLogFileDate();(!t||t!==e)&&(t&&(console.log(K.colorize(`\u68C0\u6D4B\u5230\u65E7\u65E5\u5FD7\u6587\u4EF6 (${t})\uFF0C\u6B63\u5728\u5F52\u6863...`,"WARN")),await this.archiveLogFile(t)),await this.createNewLogFile(e),console.log(K.colorize(`\u2713 \u521B\u5EFA\u65B0\u65E5\u5FD7\u6587\u4EF6: ${e}`,"SUCCESS"))),this.isInitialized=!0}catch(e){let t=e instanceof Error?e.message:String(e);console.error(K.colorize(`\u521D\u59CB\u5316\u65E5\u5FD7\u7CFB\u7EDF\u5931\u8D25: ${t}`,"ERROR"))}}configureLogger(e){this.config={...this.config,...e},e.logDir&&(this.logsDir=e.logDir,this.currentLogPath=Br(this.logsDir,"current.jsonl"),this.logDatePath=Br(this.logsDir,".current_date")),e.formatter&&(this.formatter=e.formatter)}setFormatter(e){this.formatter=e}shouldLog(e){let t=this.config.debugMode?"DEBUG":this.config.level;return Co[e]<=Co[t]}extractSessionId(e){if(e&&typeof e=="object")return e.sessionId||e.id}hasContextLogMethod(e,t){return e&&typeof e[t]=="function"}async writeLog(e,t,n=null){try{if(!this.shouldLog(e))return;this.isInitialized||await this.initLogger();let r=typeof t=="string"?t:JSON.stringify(t),o=e.toLowerCase();if(this.hasContextLogMethod(n,o)){n[o](t);return}let i=this.getTodayDateString(),a={timestamp:this.getLocalTimestamp(),level:e,message:r,sessionId:this.extractSessionId(n),date:i};if(this.config.consoleOutput){let c=this.formatter.format(a),l=this.formatter.colorize(c,e);console.log(l)}this.config.fileOutput&&await new Ue(this.currentLogPath).append(a)}catch(r){let o=r instanceof Error?r.message:String(r);console.error(K.colorize(`\u5199\u5165\u65E5\u5FD7\u5931\u8D25: ${o}`,"ERROR"))}}setDebugMode(e){this.config.debugMode=e}setLogLevel(e){this.config.level=e}},Ce=new Hr});import{join as yl}from"path";async function xl(s){try{let e=Ee("logs"),t=yl(e,"current.jsonl"),n=new We(t);return await n.exists()?await n.readAllSync({filter:s?.level?o=>o.level===s.level:void 0,limit:s?.limit}):[]}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(K.colorize(`\u8BFB\u53D6\u65E5\u5FD7\u5931\u8D25: ${t}`,"ERROR")),[]}}async function Sl(s,e){try{let t=Ee("logs"),n=yl(t,`${s}.jsonl`),r=new We(n);return await r.exists()?await r.readAllSync({filter:e?.level?i=>i.level===e.level:void 0,limit:e?.limit}):[]}catch(t){let n=t instanceof Error?t.message:String(t);return console.error(K.colorize(`\u8BFB\u53D6\u5F52\u6863\u65E5\u5FD7\u5931\u8D25: ${n}`,"ERROR")),[]}}function Cl(s){return`[${H(s.timestamp)}] [${s.level.padEnd(7)}] ${s.message}`}function wl(s){let e={total:s.length,byLevel:{INFO:0,WARN:0,ERROR:0,SUCCESS:0,DEBUG:0,TRACE:0}};for(let t of s)t.level in e.byLevel&&e.byLevel[t.level]++;return e}var bl=S(()=>{Ye();Wr();Ur();Fe()});async function vl(s,e=null){await Ce.writeLog("INFO",s,e)}async function F(s,e=null){await Ce.writeLog("INFO",s,e)}async function Tl(s,e=null){await Ce.writeLog("SUCCESS",s,e)}async function oa(s,e=null){await Ce.writeLog("WARN",s,e)}async function oe(s,e=null){await oa(s,e)}async function ne(s,e=null){await Ce.writeLog("ERROR",s,e)}async function C(s,e=null){await Ce.writeLog("DEBUG",s,e)}async function Pl(s,e=null){await Ce.writeLog("TRACE",s,e)}function ie(s,e=null){vl(s,e).catch(t=>console.error(K.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}function zt(s,e=null){F(s,e).catch(t=>console.error(K.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}function zr(s,e=null){Tl(s,e).catch(t=>console.error(K.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}function Vt(s,e=null){oa(s,e).catch(t=>console.error(K.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}function ia(s,e=null){oe(s,e).catch(t=>console.error(K.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}function Be(s,e=null){ne(s,e).catch(t=>console.error(K.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}function _(s,e=null){C(s,e).catch(t=>console.error(K.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}function Wm(s,e=null){Pl(s,e).catch(t=>console.error(K.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}var aa=S(()=>{sa();Ur()});var ca={};B(ca,{ChalkFormatter:()=>_r,DEFAULT_CONFIG:()=>ta,LOG_LEVEL_PRIORITIES:()=>Co,LoggerManager:()=>Hr,configureLogger:()=>dl,consoleClear:()=>Yi,consoleDebug:()=>it,consoleError:()=>xe,consoleInfo:()=>ve,consolePlain:()=>Dr,consoleProgress:()=>km,consoleSeparator:()=>So,consoleStats:()=>Em,consoleSuccess:()=>X,consoleTitle:()=>Pm,consoleWarn:()=>J,default:()=>Ce,defaultFormatter:()=>K,formatLogEntry:()=>Cl,getLogStats:()=>wl,initLogger:()=>$n,log:()=>vl,logDebug:()=>C,logDebugSync:()=>_,logError:()=>ne,logErrorSync:()=>Be,logInfo:()=>F,logInfoSync:()=>zt,logSuccess:()=>Tl,logSuccessSync:()=>zr,logSync:()=>ie,logTrace:()=>Pl,logTraceSync:()=>Wm,logWarn:()=>oe,logWarnSync:()=>ia,logWarning:()=>oa,logWarningSync:()=>Vt,loggerManager:()=>Ce,readArchivedLogs:()=>Sl,readCurrentLogs:()=>xl,setConsoleDebugMode:()=>Lr,setConsoleLoggerConfig:()=>Tm,setDebugMode:()=>In,setFormatter:()=>hl,setLogLevel:()=>fl});var Q=S(()=>{na();Ur();sa();bl();aa();Tt()});import{existsSync as kl,mkdirSync as Bm,readdirSync as Hm}from"fs";import{join as El}from"path";function $l(){kl(Mn)||Bm(Mn,{recursive:!0})}function Il(s){if(!s||!s.messages||s.messages.length===0)return null;$l();let e=new Date().toISOString().replace(/[:.]/g,"-"),t=s.sessionId?s.sessionId.substring(0,8):"unknown",n=s.currentTask?s.currentTask.substring(0,30).replace(/[^\w\u4e00-\u9fa5]/g,"_"):"unnamed",r=`session_${t}_${e}_${n}.jsonl`,o=El(Mn,r),i={type:"session_metadata",data:{sessionId:s.sessionId,currentTask:s.currentTask,createdAt:s.createdAt,archivedAt:new Date().toISOString(),messageCount:s.messages.length,taskCount:s.tasks?s.tasks.length:0}};try{let a=new Ue(o);if(a.create(i),s.tasks&&s.tasks.length>0){let c={type:"tasks_data",data:s.tasks};a.append(c)}s.messages&&s.messages.length>0&&s.messages.map(l=>({...l,id:l.id||`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`})).forEach(l=>{a.append({type:"message",data:l})})}catch(a){return console.error("\u5F52\u6863\u4F1A\u8BDD\u5931\u8D25:",a),null}return o}function zm(){return $l(),kl(Mn)?Hm(Mn).filter(e=>e.endsWith(".jsonl")).map(e=>{let t=El(Mn,e);try{let r=new We(t).readAllSync({limit:1})[0];return!r||r.type!=="session_metadata"?null:{fileName:e,filePath:t,sessionId:r.data.sessionId,sessionIdShort:r.data.sessionId?r.data.sessionId.substring(0,8):"unknown",currentTask:r.data.currentTask||"\u672A\u547D\u540D\u4EFB\u52A1",timestamp:r.data.archivedAt,archivedAt:r.data.archivedAt,messageCount:r.data.messageCount||0,taskCount:r.data.taskCount||0}}catch(n){return console.error(`\u8BFB\u53D6\u5F52\u6863\u6587\u4EF6\u5931\u8D25: ${e}`,n),null}}).filter(e=>e!==null).sort((e,t)=>new Date(t.archivedAt).getTime()-new Date(e.archivedAt).getTime()):[]}function Ml(){let s=zm();if(s.length===0)return"\u6682\u65E0\u5F52\u6863\u4F1A\u8BDD";let e=`
9
9
  === \u5F52\u6863\u4F1A\u8BDD\u5217\u8868 ===
10
10
 
11
- `;return o.forEach((t,n)=>{let s=new Date(t.archivedAt).toLocaleString("zh-CN");e+=`[${n+1}] ${t.currentTask}
11
+ `;return s.forEach((t,n)=>{let r=H(t.archivedAt);e+=`[${n+1}] ${t.currentTask}
12
12
  `,e+=` \u4F1A\u8BDDID: ${t.sessionIdShort||"unknown"}
13
- `,e+=` \u5F52\u6863\u65F6\u95F4: ${s}
13
+ `,e+=` \u5F52\u6863\u65F6\u95F4: ${r}
14
14
  `,e+=` \u4EFB\u52A1\u6570\u91CF: ${t.taskCount||0}
15
15
  `,e+=` \u6D88\u606F\u6570\u91CF: ${t.messageCount}
16
16
  `,e+=` \u6587\u4EF6\u540D: ${t.fileName}
17
17
 
18
- `}),e}var xt,Xo=C(()=>{je();dn();xt=ge("archives")});function Ze(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(o){let e=Math.random()*16|0;return(o==="x"?e:e&3|8).toString(16)})}function Qo(){return"S"+Ze()}function Rr(){return"T"+Ze()}var Dr=C(()=>{});var Zi={};j(Zi,{SESSION_FILE:()=>_e,archiveSession:()=>et,associateMessageWithTask:()=>Qi,completeCurrentTask:()=>vt,loadSession:()=>es,saveSession:()=>ce,sessionState:()=>b,setCurrentTaskId:()=>St,startNewTask:()=>Fr});import{writeFileSync as nu,existsSync as Xi}from"fs";function Zo(){return{sessionId:Qo(),messages:[],tasks:[],currentTask:null,currentTaskId:null,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}}function ru(){try{b.messages&&b.messages.length>0&&Ki(b)&&x("\u4F1A\u8BDD\u5DF2\u5F52\u6863"),b=Zo(),new me(_e).create(b)}catch(o){let e=o instanceof Error?o.message:String(o);W(`Failed to archive session - ${e}`,"Session"),b=Zo();try{new me(_e).create(b)}catch{}}}function es(){try{if(Xi(_e)){let e=new fe(_e).readAllSync(),t=e.length>0?e[0]:null;return b={sessionId:t&&t.sessionId||Qo(),messages:t&&t.messages||[],tasks:t&&t.tasks||[],currentTask:t&&t.currentTask||null,currentTaskId:t&&t.currentTaskId||null,createdAt:t&&t.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString()},!0}}catch(o){let e=o instanceof Error?o.message:String(o);W(`Could not load session - ${e}`,"Session")}return!1}function Fr(o){let e=Rr(),t={id:e,description:o,createdAt:new Date().toISOString(),messageIds:[]};return b.tasks.push(t),b.currentTask=o,b.currentTaskId=e,e}function Qi(o){if(b.currentTaskId&&o){let e=b.currentTaskId;o.taskId=e;let t=b.tasks.find(n=>n.id===e);if(t&&!o.id){let n=Ze();o.id=n,t.messageIds.push(n)}}return o}function St(o){b.currentTaskId=o,b.updatedAt=new Date().toISOString(),ce(),se(`\u5F53\u524D\u4EFB\u52A1ID\u5DF2\u8BBE\u7F6E\u4E3A: ${o}`,"Session")}function ce(o,e=null){try{if(e&&e!==b.currentTask&&Fr(e),o){let n=o.map(r=>Qi({...r}));b={...b,messages:n,updatedAt:new Date().toISOString()}}else b={...b,updatedAt:new Date().toISOString()};Xi(_e)&&nu(_e,"","utf-8"),new me(_e).create(b)}catch(t){let n=t instanceof Error?t.message:String(t);W(`Could not save session - ${n}`,"Session")}}function et(){return ru()}function ou(){if(b.currentTask&&b.currentTaskId){let o=b.tasks.find(e=>e.id===b.currentTaskId);if(o){let e=o.tokenCount||0;_(`\u4EFB\u52A1\u5B8C\u6210: ${b.currentTask}`,"Session"),se(`Token\u603B\u5F00\u9500: ${e.toLocaleString()} tokens`,"Session")}b.currentTask=null,b.currentTaskId=null,ce()}}function vt(){return ou()}var _e,b,Ne=C(()=>{cn();Y();je();Xo();dn();Dr();_e=ge("session.jsonl");b=Zo()});var ts,ea=C(()=>{ts={name:"coder",description:"\u4EE3\u7801\u7F16\u5199\u548C\u5F00\u53D1\uFF0C\u5305\u62EC\u65B0\u6587\u4EF6\u521B\u5EFA\u548C\u73B0\u6709\u6587\u4EF6\u4FEE\u6539\uFF0C\u652F\u6301\u591A\u8BED\u8A00\u9879\u76EE",keywords:["code","\u4EE3\u7801","\u7F16\u7A0B","\u5F00\u53D1","\u5199\u4EE3\u7801","\u4EE3\u7801\u4FEE\u6539","\u65B0\u5EFA\u6587\u4EF6","\u4F9D\u8D56\u68C0\u67E5","\u5B9E\u73B0\u529F\u80FD","\u6DFB\u52A0\u7279\u6027","\u4FEE\u590Dbug","\u91CD\u6784","\u5B9E\u73B0","\u5F00\u53D1","\u7F16\u5199","\u521B\u5EFA\u7C7B","\u521B\u5EFA\u51FD\u6570","\u6DFB\u52A0\u65B9\u6CD5","\u5199\u4E00\u4E2A","\u751F\u6210\u4EE3\u7801","\u65B0\u589E\u529F\u80FD","feature","implement","develop","create","add function","add","method","write code","generate code","refactor code","fix code","update code","modify code","\u7F16\u7801","\u5199\u529F\u80FD","\u52A0\u529F\u80FD","\u6539\u4EE3\u7801","\u5199\u63A5\u53E3","\u5199API","\u5F00\u53D1\u63A5\u53E3","\u5B9E\u73B0\u63A5\u53E3"],prompt:`\u4F60\u662F\u4E00\u4F4D\u8DE8\u8BED\u8A00\u4EE3\u7801\u7F16\u5199\u4E13\u5BB6\u3002\u4F60\u7684\u4EFB\u52A1\u662F\u6839\u636E\u7528\u6237\u9700\u6C42\u7F16\u5199\u9AD8\u8D28\u91CF\u3001\u53EF\u7EF4\u62A4\u7684\u4EE3\u7801\uFF0C\u652F\u6301\u591A\u79CD\u7F16\u7A0B\u8BED\u8A00\u548C\u9879\u76EE\u7C7B\u578B\u3002
18
+ `}),e}var Mn,la=S(()=>{Ye();Wr();Fe();Mn=Ee("archives")});function Gt(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(s){let e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})}function ua(){return"S"+Gt()}function wo(){return"T"+Gt()}var bo=S(()=>{});var Ll={};B(Ll,{SESSION_FILE:()=>Pt,archiveSession:()=>qt,associateMessageWithTask:()=>Rl,completeCurrentTask:()=>Rn,loadSession:()=>Vr,saveSession:()=>$e,sessionState:()=>E,setCurrentTaskId:()=>An,startNewTask:()=>vo});import{writeFileSync as Vm,existsSync as Al}from"fs";function pa(){return{sessionId:ua(),messages:[],tasks:[],currentTask:null,currentTaskId:null,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}}function Gm(){try{E.messages&&E.messages.length>0&&Il(E)&&C("\u4F1A\u8BDD\u5DF2\u5F52\u6863"),E=pa(),new Ue(Pt).create(E)}catch(s){let e=s instanceof Error?s.message:String(s);J(`Failed to archive session - ${e}`,"Session"),E=pa();try{new Ue(Pt).create(E)}catch{}}}function Vr(){try{if(Al(Pt)){let e=new We(Pt).readAllSync(),t=e.length>0?e[0]:null;return E={sessionId:t&&t.sessionId||ua(),messages:t&&t.messages||[],tasks:t&&t.tasks||[],currentTask:t&&t.currentTask||null,currentTaskId:t&&t.currentTaskId||null,createdAt:t&&t.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString()},!0}}catch(s){let e=s instanceof Error?s.message:String(s);J(`Could not load session - ${e}`,"Session")}return!1}function vo(s){let e=wo(),t={id:e,description:s,createdAt:new Date().toISOString(),messageIds:[]};return E.tasks.push(t),E.currentTask=s,E.currentTaskId=e,e}function Rl(s){if(E.currentTaskId&&s){let e=E.currentTaskId;s.taskId=e;let t=E.tasks.find(n=>n.id===e);if(t&&!s.id){let n=Gt();s.id=n,t.messageIds.push(n)}}return s}function An(s){E.currentTaskId=s,E.updatedAt=new Date().toISOString(),$e(),ve(`\u5F53\u524D\u4EFB\u52A1ID\u5DF2\u8BBE\u7F6E\u4E3A: ${s}`,"Session")}function $e(s,e=null){try{if(e&&e!==E.currentTask&&vo(e),s){let n=s.map(r=>Rl({...r}));E={...E,messages:n,updatedAt:new Date().toISOString()}}else E={...E,updatedAt:new Date().toISOString()};Al(Pt)&&Vm(Pt,"","utf-8"),new Ue(Pt).create(E)}catch(t){let n=t instanceof Error?t.message:String(t);J(`Could not save session - ${n}`,"Session")}}function qt(){return Gm()}function qm(){if(E.currentTask&&E.currentTaskId){let s=E.tasks.find(e=>e.id===E.currentTaskId);if(s){let e=s.tokenCount||0;X(`\u4EFB\u52A1\u5B8C\u6210: ${E.currentTask}`,"Session"),ve(`Token\u603B\u5F00\u9500: ${e.toLocaleString()} tokens`,"Session")}E.currentTask=null,E.currentTaskId=null,$e()}}function Rn(){return qm()}var Pt,E,ct=S(()=>{Tt();Q();Ye();la();Wr();bo();Pt=Ee("session.jsonl");E=pa()});var ga,jl=S(()=>{ga={name:"coder",description:"\u4EE3\u7801\u7F16\u5199\u548C\u5F00\u53D1\uFF0C\u5305\u62EC\u65B0\u6587\u4EF6\u521B\u5EFA\u548C\u73B0\u6709\u6587\u4EF6\u4FEE\u6539\uFF0C\u652F\u6301\u591A\u8BED\u8A00\u9879\u76EE",keywords:["code","\u4EE3\u7801","\u7F16\u7A0B","\u5F00\u53D1","\u5199\u4EE3\u7801","\u4EE3\u7801\u4FEE\u6539","\u65B0\u5EFA\u6587\u4EF6","\u4F9D\u8D56\u68C0\u67E5","\u5B9E\u73B0\u529F\u80FD","\u6DFB\u52A0\u7279\u6027","\u4FEE\u590Dbug","\u91CD\u6784","\u5B9E\u73B0","\u5F00\u53D1","\u7F16\u5199","\u521B\u5EFA\u7C7B","\u521B\u5EFA\u51FD\u6570","\u6DFB\u52A0\u65B9\u6CD5","\u5199\u4E00\u4E2A","\u751F\u6210\u4EE3\u7801","\u65B0\u589E\u529F\u80FD","feature","implement","develop","create","add function","add","method","write code","generate code","refactor code","fix code","update code","modify code","\u7F16\u7801","\u5199\u529F\u80FD","\u52A0\u529F\u80FD","\u6539\u4EE3\u7801","\u5199\u63A5\u53E3","\u5199API","\u5F00\u53D1\u63A5\u53E3","\u5B9E\u73B0\u63A5\u53E3"],prompt:`\u4F60\u662F\u4E00\u4F4D\u8DE8\u8BED\u8A00\u4EE3\u7801\u7F16\u5199\u4E13\u5BB6\u3002\u4F60\u7684\u4EFB\u52A1\u662F\u6839\u636E\u7528\u6237\u9700\u6C42\u7F16\u5199\u9AD8\u8D28\u91CF\u3001\u53EF\u7EF4\u62A4\u7684\u4EE3\u7801\uFF0C\u652F\u6301\u591A\u79CD\u7F16\u7A0B\u8BED\u8A00\u548C\u9879\u76EE\u7C7B\u578B\u3002
19
19
 
20
20
  ## \u6838\u5FC3\u89C4\u5219
21
21
 
@@ -210,23 +210,28 @@ var Fl=Object.defineProperty;var $r=(o=>typeof require<"u"?require:typeof Proxy<
210
210
  - \u4F7F\u7528 \`grep()\` \u6216 \`search\` \u5DE5\u5177\u67E5\u627E\u6240\u6709\u5F15\u7528
211
211
  - \u5236\u5B9A\u5168\u9762\u7684\u66F4\u65B0\u8BA1\u5212\uFF0C\u786E\u4FDD\u6240\u6709\u4F9D\u8D56\u90FD\u5F97\u5230\u9002\u5F53\u5904\u7406
212
212
 
213
- \u786E\u4FDD\u5728\u5B8C\u6210\u4EE3\u7801\u7F16\u5199\u548C\u6587\u4EF6\u5199\u5165\u4E4B\u540E\uFF0C\u5FC5\u987B\u6267\u884C\u4F9D\u8D56\u68C0\u67E5\u6B65\u9AA4\uFF01`}});var wt={};j(wt,{LITE_MODEL:()=>Ie,MODEL:()=>ye,getDefaultModelConfig:()=>tt,getLiteModelConfig:()=>yn,getLiteModelMaxToken:()=>os,getMCPServerConfigs:()=>ss,getMaxToken:()=>rs,getProvider:()=>au});import{readFileSync as su}from"fs";function ns(){if(!Or)try{let o=ge("config.json"),e=su(o,"utf-8");Or=JSON.parse(e)}catch(o){console.error("Failed to load config.json:",o.message),Or={models:{defaultModel:{apiKey:"",authToken:"",baseURL:"https://api.openai.com/v1",model:"gpt-4o-mini",provider:"openai"}}}}return Or}function tt(){let o=ns(),e={apiKey:"",authToken:"",baseURL:"https://api.openai.com/v1",model:"gpt-4o-mini",provider:"openai",maxToken:128e3},t=o.models?.defaultModel||e;return t.provider==="anthropic"&&t.disableExperimentalBetas===void 0&&(t.disableExperimentalBetas=!0),t}function yn(){let e=ns().models?.liteModel||tt();return e.provider==="anthropic"&&e.disableExperimentalBetas===void 0&&(e.disableExperimentalBetas=!0),e}function ta(){return tt().model||"gpt-4o-mini"}function iu(){return yn().model||ta()}function au(){return tt().provider||"openai"}function ye(){return ta()}function Ie(){return iu()}function rs(){return tt().maxToken||128e3}function os(){return yn().maxToken||16385}function ss(){return ns().mcpServers||[]}var Or,le=C(()=>{je();Or=null});var nt,jr=C(()=>{nt=class{config;constructor(e){this.config=e}getModelName(){return this.config.model}getProviderType(){return this.config.provider}_getApiKey(){return this.config.apiKey}_getAuthToken(){return this.config.authToken}_getBaseURL(){return this.config.baseURL}}});import cu from"openai";var is,na,ra=C(()=>{jr();is=class extends nt{client=null;constructor(e){super(e)}_initClient(){if(!this.client){let e={baseURL:this.config.baseURL||"https://api.openai.com/v1",defaultHeaders:{}};this.config.apiKey?e.apiKey=this.config.apiKey:this.config.authToken&&(this.config.authToken.startsWith("Bearer ")?e.apiKey=this.config.authToken.slice(7):e.apiKey=this.config.authToken),this.client=new cu(e)}return this.client}async callModel(e){let{model:t=this.getModelName(),messages:n,temperature:r=.1,max_tokens:s,tools:i,tool_choice:a}=e,c=this._initClient(),l=[...n],u={model:t,messages:l,temperature:r,max_tokens:s};i&&i.length>0&&(u.tools=i.map(g=>({type:"function",function:{name:g.name,description:g.description,parameters:g.input_schema}})),a&&(a.type==="any"||(u.tool_choice=a)));let p=await c.chat.completions.create(u);return this._processReasoningContent(p),p}_processReasoningContent(e){if(e.choices&&e.choices[0]&&e.choices[0].message&&e.choices[0].message.reasoning_content){let{message:t}=e.choices[0],n=t.reasoning_content;if(t.tool_calls&&t.tool_calls.length>0){t.content?typeof t.content=="string"&&(t.content=`${n}
213
+ \u786E\u4FDD\u5728\u5B8C\u6210\u4EE3\u7801\u7F16\u5199\u548C\u6587\u4EF6\u5199\u5165\u4E4B\u540E\uFF0C\u5FC5\u987B\u6267\u884C\u4F9D\u8D56\u68C0\u67E5\u6B65\u9AA4\uFF01`}});var Ln={};B(Ln,{LITE_MODEL:()=>lt,MODEL:()=>ge,getDefaultModelConfig:()=>Jt,getLiteModelConfig:()=>Gr,getLiteModelMaxToken:()=>Eo,getMCPServerConfigs:()=>qr,getMaxToken:()=>ko,getProvider:()=>Ym,isInkMode:()=>ma,setInkMode:()=>Po});import{readFileSync as Jm}from"fs";function Po(s){Dl=s}function ma(){return Dl}function da(){if(!To)try{let s=Ee("config.json"),e=Jm(s,"utf-8");To=JSON.parse(e)}catch(s){console.error("Failed to load config.json:",s.message),To={models:{defaultModel:{apiKey:"",authToken:"",baseURL:"https://api.openai.com/v1",model:"gpt-4o-mini",provider:"openai"}}}}return To}function Jt(){let s=da(),e={apiKey:"",authToken:"",baseURL:"https://api.openai.com/v1",model:"gpt-4o-mini",provider:"openai",maxToken:128e3},t=s.models?.defaultModel||e;return t.provider==="anthropic"&&t.disableExperimentalBetas===void 0&&(t.disableExperimentalBetas=!0),t}function Gr(){let e=da().models?.liteModel||Jt();return e.provider==="anthropic"&&e.disableExperimentalBetas===void 0&&(e.disableExperimentalBetas=!0),e}function Fl(){return Jt().model||"gpt-4o-mini"}function Km(){return Gr().model||Fl()}function Ym(){return Jt().provider||"openai"}function ge(){return Fl()}function lt(){return Km()}function ko(){return Jt().maxToken||128e3}function Eo(){return Gr().maxToken||16385}function qr(){return(da().mcpServers||[]).filter(t=>t.enabled!==!1)}var Dl,To,ae=S(()=>{Ye();Dl=!1;To=null});var Kt,$o=S(()=>{Kt=class{config;constructor(e){this.config=e}getModelName(){return this.config.model}getProviderType(){return this.config.provider}_getApiKey(){return this.config.apiKey}_getAuthToken(){return this.config.authToken}_getBaseURL(){return this.config.baseURL}}});import Xm from"openai";var fa,Ol,Nl=S(()=>{$o();fa=class extends Kt{client=null;constructor(e){super(e)}_initClient(){if(!this.client){let e={baseURL:this.config.baseURL||"https://api.openai.com/v1",defaultHeaders:{}};this.config.apiKey?e.apiKey=this.config.apiKey:this.config.authToken&&(this.config.authToken.startsWith("Bearer ")?e.apiKey=this.config.authToken.slice(7):e.apiKey=this.config.authToken),this.client=new Xm(e)}return this.client}async callModel(e){let{model:t=this.getModelName(),messages:n,temperature:r=.1,max_tokens:o,tools:i,tool_choice:a}=e,c=this._initClient(),l=[...n],u={model:t,messages:l,temperature:r,max_tokens:o};i&&i.length>0&&(u.tools=i.map(p=>({type:"function",function:{name:p.name,description:p.description,parameters:p.input_schema}})),a&&(a.type==="any"?console.warn('[OpenAI Provider] tool_choice.type === "any" \u5C06\u88AB\u5FFD\u7565\uFF0C\u4EE5\u907F\u514DAPI\u9519\u8BEF'):u.tool_choice=a));try{let p=await c.chat.completions.create(u);return this._processReasoningContent(p),p}catch(p){throw console.error("[OpenAI Provider] API\u8BF7\u6C42\u5931\u8D25\uFF0C\u8BF7\u6C42\u53C2\u6570:",{model:t,temperature:r,max_tokens:o,messages_count:l.length,tools_count:i?i.length:0,tool_choice:a||"\u672A\u8BBE\u7F6E",has_tool_choice:!!u.tool_choice,baseURL:this.config.baseURL||"https://api.openai.com/v1"}),console.error("[OpenAI Provider] \u6D88\u606F\u6837\u672C\uFF08\u524D3\u6761\uFF09:",l.slice(0,3).map(g=>({role:g.role,content:typeof g.content=="string"?g.content.substring(0,100)+(g.content.length>100?"...":""):g.content,has_tool_calls:!!g.tool_calls}))),p}}_processReasoningContent(e){if(e.choices&&e.choices[0]&&e.choices[0].message&&e.choices[0].message.reasoning_content){let{message:t}=e.choices[0],n=t.reasoning_content;if(t.tool_calls&&t.tool_calls.length>0){t.content?typeof t.content=="string"&&(t.content=`${n}
214
214
 
215
- ${t.content}`):t.content=n;return}try{let r=[];try{let s=JSON.parse(n);Array.isArray(s)&&s.length>0?(r=s.filter(i=>i&&i.name).map(i=>({id:`call_${i.name}_${Date.now()}`,type:"function",function:{name:i.name,arguments:JSON.stringify(i.parameters||{})}})),t.tool_calls=r):t.content||(t.content=n)}catch{t.content||(t.content=n)}}catch(r){console.warn("Failed to process reasoning_content:",r)}}}},na=is});var as,oa,sa=C(()=>{jr();Y();as=class extends nt{client=null;constructor(e){super(e)}async _initClient(){if(!this.client){let{Anthropic:e}=await import("@anthropic-ai/sdk"),t={};this.config.apiKey?t.apiKey=this.config.apiKey:this.config.authToken&&(this.config.authToken.startsWith("Bearer ")?t.apiKey=this.config.authToken.slice(7):t.apiKey=this.config.authToken),this.config.disableExperimentalBetas!==!1&&(t.defaultHeaders={...t.defaultHeaders,"anthropic-beta":""}),this.client=new e(t)}return this.client}async callModel(e){let{model:t=this.getModelName(),messages:n,temperature:r=.1,max_tokens:s=4096,tools:i,tool_choice:a}=e,c=await this._initClient(),l=[...n],u="",p=l.filter(f=>f.role==="system");p.length>0&&(u=p.map(f=>f.content).join(`
215
+ ${t.content}`):t.content=n;return}try{let r=[];try{let o=JSON.parse(n);Array.isArray(o)&&o.length>0?(r=o.filter(i=>i&&i.name).map(i=>({id:`call_${i.name}_${Date.now()}`,type:"function",function:{name:i.name,arguments:JSON.stringify(i.parameters||{})}})),t.tool_calls=r):t.content||(t.content=n)}catch{t.content||(t.content=n)}}catch(r){console.warn("Failed to process reasoning_content:",r)}}}},Ol=fa});var ha,_l,Ul=S(()=>{$o();Q();ha=class extends Kt{client=null;constructor(e){super(e)}async _initClient(){if(!this.client){let{Anthropic:e}=await import("@anthropic-ai/sdk"),t={};this.config.apiKey?t.apiKey=this.config.apiKey:this.config.authToken&&(this.config.authToken.startsWith("Bearer ")?t.apiKey=this.config.authToken.slice(7):t.apiKey=this.config.authToken),this.config.disableExperimentalBetas!==!1&&(t.defaultHeaders={...t.defaultHeaders,"anthropic-beta":""}),this.client=new e(t)}return this.client}async callModel(e){let{model:t=this.getModelName(),messages:n,temperature:r=.1,max_tokens:o=4096,tools:i,tool_choice:a}=e,c=await this._initClient(),l=[...n],u="",p=l.filter(h=>h.role==="system");p.length>0&&(u=p.map(h=>h.content).join(`
216
216
 
217
- `)),l=l.filter(f=>f.role!=="system");let g=[],d=0;for(;d<l.length;){let f=l[d];if(f.role==="assistant"){let y=[];if(f.content&&typeof f.content=="string"&&y.push({type:"text",text:f.content}),f.tool_calls&&f.tool_calls.length>0)for(let S of f.tool_calls)y.push({type:"tool_use",id:S.id,name:S.function.name,input:JSON.parse(S.function.arguments)});y.length>0&&g.push({role:"assistant",content:y}),d++}else if(f.role==="tool"){let y=[];for(;d<l.length&&l[d].role==="tool";){let S=l[d];y.push({type:"tool_result",tool_use_id:S.tool_call_id,content:S.content||"No result"}),d++}y.length>0&&g.push({role:"user",content:y})}else if(f.role==="user"){let y=typeof f.content=="string"?[{type:"text",text:f.content}]:Array.isArray(f.content)?f.content:[{type:"text",text:String(f.content)}];g.push({role:"user",content:y}),d++}else d++}let m={model:t,max_tokens:s,temperature:r,system:u||"You are a helpful assistant.",messages:g};i&&i.length>0&&(m.tools=i,a&&(m.tool_choice=a));let h=await c.messages.create(m);x(`[Anthropic Provider] Response content blocks: ${JSON.stringify(h.content,null,2)}`);let w=[],v="";for(let f of h.content)if(f.type==="text")v+=f.text;else if(f.type==="tool_use")x(`[Anthropic Provider] Tool use block: ${JSON.stringify({id:f.id,name:f.name,input:f.input,inputKeys:Object.keys(f.input||{})},null,2)}`),w.push({id:f.id,type:"function",function:{name:f.name,arguments:JSON.stringify(f.input)}});else if(f.type==="thinking"){let y=f.thinking||"";y&&(v=y+(v?`
217
+ `)),l=l.filter(h=>h.role!=="system");let g=[],m=0;for(;m<l.length;){let h=l[m];if(h.role==="assistant"){let x=[];if(h.content&&typeof h.content=="string"&&x.push({type:"text",text:h.content}),h.tool_calls&&h.tool_calls.length>0)for(let P of h.tool_calls)x.push({type:"tool_use",id:P.id,name:P.function.name,input:JSON.parse(P.function.arguments)});x.length>0&&g.push({role:"assistant",content:x}),m++}else if(h.role==="tool"){let x=[];for(;m<l.length&&l[m].role==="tool";){let P=l[m];x.push({type:"tool_result",tool_use_id:P.tool_call_id,content:P.content||"No result"}),m++}x.length>0&&g.push({role:"user",content:x})}else if(h.role==="user"){let x=typeof h.content=="string"?[{type:"text",text:h.content}]:Array.isArray(h.content)?h.content:[{type:"text",text:String(h.content)}];g.push({role:"user",content:x}),m++}else m++}let d={model:t,max_tokens:o,temperature:r,system:u||"You are a helpful assistant.",messages:g};i&&i.length>0&&(d.tools=i,a&&(d.tool_choice=a));let f=await c.messages.create(d);C(`[Anthropic Provider] Response content blocks: ${JSON.stringify(f.content,null,2)}`);let y=[],w="";for(let h of f.content)if(h.type==="text")w+=h.text;else if(h.type==="tool_use")C(`[Anthropic Provider] Tool use block: ${JSON.stringify({id:h.id,name:h.name,input:h.input,inputKeys:Object.keys(h.input||{})},null,2)}`),y.push({id:h.id,type:"function",function:{name:h.name,arguments:JSON.stringify(h.input)}});else if(h.type==="thinking"){let x=h.thinking||"";x&&(w=x+(w?`
218
218
 
219
- `+v:""))}return{choices:[{message:{content:v||null,tool_calls:w.length>0?w:void 0},finish_reason:h.stop_reason==="end_turn"?"stop":h.stop_reason}]}}},oa=as});var Cn,ia=C(()=>{le();jr();ra();sa();Cn=class{static async getProvider(){let e=tt();return this.createProvider(e)}static async getLiteProvider(){let e=yn();return this.createProvider(e)}static async createProvider(e){switch(e.provider||"openai"){case"anthropic":return new oa(e);case"openai":default:return new na(e)}}}});function bt(o){return o&&typeof o=="object"&&o.__tool_result===!0}function xn(o){return bt(o)?o.result:o}var $,V=C(()=>{$=class{get name(){return this.getDefinition().name}get description(){return this.getDefinition().description}get inputSchema(){return this.getDefinition().input_schema}createToolResult(e,t=null,n=!0){return{__tool_result:!0,result:e,display:t!==null?t:e,shouldPrint:n}}formatError(e,t){let n=t instanceof Error?t.message:String(t);return`Error: ${e} failed - ${n}`}formatAction(e){let t=this.name,n=Object.entries(e).map(([r,s])=>{let i=s;return typeof s=="string"&&s.length>50&&(i=s.substring(0,50)+"..."),`${r}=${JSON.stringify(i)}`}).join(", ");return`${t}(${n})`}formatObservation(e){if(bt(e)){let{display:t}=e;return Array.isArray(t)?t.join(`
219
+ `+w:""))}return{choices:[{message:{content:w||null,tool_calls:y.length>0?y:void 0},finish_reason:f.stop_reason==="end_turn"?"stop":f.stop_reason}]}}},_l=ha});var Jr,Wl=S(()=>{ae();$o();Nl();Ul();Jr=class{static async getProvider(){let e=Jt();return this.createProvider(e)}static async getLiteProvider(){let e=Gr();return this.createProvider(e)}static async createProvider(e){switch(e.provider||"openai"){case"anthropic":return new _l(e);case"openai":default:return new Ol(e)}}}});function jn(s){return s&&typeof s=="object"&&s.__tool_result===!0}function Kr(s){return jn(s)?s.result:s}var R,G=S(()=>{R=class{get name(){return this.getDefinition().name}get description(){return this.getDefinition().description}get inputSchema(){return this.getDefinition().input_schema}createToolResult(e,t=null,n=!0){return{__tool_result:!0,result:e,display:t!==null?t:e,shouldPrint:n}}formatError(e,t){let n=t instanceof Error?t.message:String(t);return`Error: ${e} failed - ${n}`}formatAction(e){let t=this.name,n=Object.entries(e).map(([r,o])=>{let i=o;return typeof o=="string"&&o.length>50&&(i=o.substring(0,50)+"..."),`${r}=${JSON.stringify(i)}`}).join(", ");return`${t}(${n})`}formatObservation(e){if(jn(e)){let{display:t}=e;return Array.isArray(t)?t.join(`
220
220
  `):String(t)}return Array.isArray(e)?e.join(`
221
- `):String(e)}shouldPrintObservation(e){return bt(e)?e.shouldPrint:!0}}});var Ce,Sn=C(()=>{V();Ce=class extends ${getDefinition(){let e=this.getBaseDefinition(),t="IMPORTANT: User confirmation is automatically required - DO NOT call askUser tool before calling this tool.",{description:n}=e;if(!n.includes("User confirmation is automatically required"))if(n.trim().startsWith("IMPORTANT:"))if(n.match(/^IMPORTANT:[^\n]*(\n[^\n]*)*?\n\n/)){let s=n.indexOf(`
222
- `);n=n.slice(0,s)+`
223
- - User confirmation is automatically required - DO NOT call askUser tool before calling this tool`+n.slice(s)}else{let s=n.indexOf(`
224
- `);s!==-1?n=n.slice(0,s)+`
225
- - User confirmation is automatically required - DO NOT call askUser tool before calling this tool`+n.slice(s):n=t+`
221
+ `):String(e)}shouldPrintObservation(e){return jn(e)?e.shouldPrint:!0}}});var ze,Yr=S(()=>{G();ze=class extends R{getDefinition(){let e=this.getBaseDefinition(),t="IMPORTANT: User confirmation is automatically required - DO NOT call askUser tool before calling this tool.",{description:n}=e;if(!n.includes("User confirmation is automatically required"))if(n.trim().startsWith("IMPORTANT:"))if(n.match(/^IMPORTANT:[^\n]*(\n[^\n]*)*?\n\n/)){let o=n.indexOf(`
222
+ `);n=n.slice(0,o)+`
223
+ - User confirmation is automatically required - DO NOT call askUser tool before calling this tool`+n.slice(o)}else{let o=n.indexOf(`
224
+ `);o!==-1?n=n.slice(0,o)+`
225
+ - User confirmation is automatically required - DO NOT call askUser tool before calling this tool`+n.slice(o):n=t+`
226
226
 
227
227
  `+n}else n=t+`
228
228
 
229
- `+n;return{...e,description:n,requiresConfirmation:!0}}getConfirmationMessage(e){return null}}});var cs={};j(cs,{BaseTool:()=>$,ConfirmableTool:()=>Ce,extractToolResult:()=>xn,isToolResult:()=>bt});var ls=C(()=>{V();Sn()});import{readFileSync as aa,statSync as lu}from"fs";import{resolve as uu}from"path";function vn(o){return ca.execute(o)}var Tt,ca,wn,la=C(()=>{V();Tt=class extends ${lastReadPath="";getDefinition(){return{name:"read",description:`Read content from a specified file path.
229
+ `+n;return{...e,description:n,requiresConfirmation:!0}}getConfirmationMessage(e){return null}}});var ya={};B(ya,{BaseTool:()=>R,ConfirmableTool:()=>ze,extractToolResult:()=>Kr,isToolResult:()=>jn});var xa=S(()=>{G();Yr()});import{readFileSync as Bl,statSync as Qm}from"fs";import{resolve as Zm}from"path";function Xr(s){let e=typeof s=="string"?{path:[s]}:s;return Hl.execute(e)}var Dn,Hl,Qr,zl=S(()=>{G();Dn=class extends R{lastReadPath="";getDefinition(){return{name:"read",description:`Read content from a specified file path.
230
+
231
+ \u{1F6A8} CRITICAL CONSTRAINTS:
232
+ - \u274C NO WILDCARDS: path must be EXACT file paths (e.g., "src/app.ts")
233
+ - \u274C NO GLOB PATTERNS: Do NOT use *, **, ?, [] in paths
234
+ - \u2705 Use glob() tool first to find files, then read() the results
230
235
 
231
236
  \u{1F4CB} USE CASES:
232
237
  - View file content for analysis or editing
@@ -235,30 +240,40 @@ ${t.content}`):t.content=n;return}try{let r=[];try{let s=JSON.parse(n);Array.isA
235
240
  - Read configuration files
236
241
 
237
242
  \u{1F511} PARAMETERS:
238
- - path: File path to read (relative or absolute)
243
+ - path: Array of EXACT file paths (relative or absolute, NO wildcards)
239
244
  - silent: If true, returns success message instead of full content (useful for large files)
240
245
  - chunkSize: Return content in chunks of specified bytes (e.g., 1024 * 1024 for 1MB chunks)
241
246
  - autoChunk: Automatically split large files (>5MB) into manageable chunks
242
247
 
243
248
  \u{1F4A1} EXAMPLES:
244
- - read({ path: "package.json" }) - Read entire package.json file
245
- - read({ path: "large.log", autoChunk: true }) - Read large log file in chunks
246
- - read({ path: "config.json", silent: true }) - Verify config.json exists
249
+ - \u2705 read({ path: ["package.json"] }) - Correct: exact path
250
+ - \u2705 read({ path: ["src/index.ts", "src/app.ts"] }) - Correct: exact paths
251
+ - \u274C read({ path: ["src/**/*.ts"] }) - WRONG: contains wildcard
252
+ - \u274C read({ path: ["*.json"] }) - WRONG: use glob("*.json") first, then read results
253
+
254
+ \u{1F4DD} WORKFLOW for Multiple Files:
255
+ 1. Use glob({ pattern: "src/**/*.java" }) to find files
256
+ 2. Get file list from glob result
257
+ 3. Use read({ path: ["file1.java", "file2.java"] }) with specific paths
247
258
 
248
259
  \u{1F4DD} RETURN VALUE:
249
260
  - Complete file content as string (for small files)
250
261
  - Array of file chunks (for large files with chunking)
251
- - Success message (with silent: true)`,input_schema:{type:"object",properties:{path:{type:"string",description:"File path to read (relative or absolute)"},silent:{type:"boolean",description:"If true, returns success message instead of full content"},chunkSize:{type:"number",description:"Return content in chunks of specified bytes (optional)"},autoChunk:{type:"boolean",description:"Automatically split large files into chunks (optional)"}},required:["path"]}}}execute(e){try{let t=e.path.trim(),n=uu(t);if(this.lastReadPath=t,e.silent)return aa(n,"utf-8"),this.createToolResult("file content",`\u6587\u4EF6 ${t} \u8BFB\u53D6\u6210\u529F\uFF08\u9759\u9ED8\u6A21\u5F0F\uFF0C\u5185\u5BB9\u672A\u663E\u793A\uFF09`,!0);let r=aa(n,"utf-8");if(e.chunkSize||e.autoChunk){let a=lu(n).size,c=1024*1024,l=5*1024*1024,u=e.chunkSize||c;if(e.autoChunk&&a<=l)return r;u=Math.max(1,u);let p=[];for(let g=0;g<r.length;g+=u)p.push(r.slice(g,g+u));return this.createToolResult(p,`\u6587\u4EF6 ${t} \u5DF2\u5206\u5757\u8BFB\u53D6\uFF0C\u5171 ${p.length} \u5757\uFF0C\u6BCF\u5757 ${u} \u5B57\u8282`,!0)}return r}catch(t){let r=`Error: Cannot read file ${e.path.trim()} - ${t instanceof Error?t.message:String(t)}`;return this.createToolResult(r,r,!0)}}formatObservation(e){if(typeof e=="object"&&e.__tool_result)return super.formatObservation(e);if(Array.isArray(e)&&this.lastReadPath)return`\u8BFB\u53D6\u6587\u4EF6 ${this.lastReadPath}\uFF0C\u5171 ${e.length} \u5757`;if(typeof e=="string"&&this.lastReadPath){let n=e.split(`
252
- `).length;return`\u8BFB\u53D6\u6587\u4EF6 ${this.lastReadPath}\uFF0C\u5171 ${n} \u884C`}return super.formatObservation(e)}},ca=new Tt;wn=ca});function ua(o){if(typeof o!="string")return o;let e=o.replace(/\\n/g,`
253
- `).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\"/g,'"').replace(/\\'/g,"'");return e=e.replace(/\r\n/g,`
262
+ - Success message (with silent: true)`,input_schema:{type:"object",properties:{path:{type:"array",items:{type:"string",description:"EXACT file path (NO wildcards like *, **, ?). Must be a real file path."},description:"Array of EXACT file paths to read. NO glob patterns allowed. Use glob() tool first to find files with patterns."},silent:{type:"boolean",description:"If true, returns success message instead of full content"},chunkSize:{type:"number",description:"Return content in chunks of specified bytes (optional)"},autoChunk:{type:"boolean",description:"Automatically split large files into chunks (optional)"}},required:["path"]}}}execute(e){try{let t=e.path,n={},r=[];for(let o of t){let i=o.trim(),a=Zm(i);this.lastReadPath=i;try{if(e.silent)Bl(a,"utf-8"),n[i]="file content",r.push(`\u6587\u4EF6 ${i} \u8BFB\u53D6\u6210\u529F\uFF08\u9759\u9ED8\u6A21\u5F0F\uFF0C\u5185\u5BB9\u672A\u663E\u793A\uFF09`);else{let c=Bl(a,"utf-8");if(e.chunkSize||e.autoChunk){let p=Qm(a).size,g=1024*1024,m=5*1024*1024,d=e.chunkSize||g;if(e.autoChunk&&p<=m)n[i]=c;else{d=Math.max(1,d);let f=[];for(let y=0;y<c.length;y+=d)f.push(c.slice(y,y+d));n[i]=f,r.push(`\u6587\u4EF6 ${i} \u5DF2\u5206\u5757\u8BFB\u53D6\uFF0C\u5171 ${f.length} \u5757\uFF0C\u6BCF\u5757 ${d} \u5B57\u8282`)}}else n[i]=c}}catch(c){let l=`Error: Cannot read file ${i} - ${c instanceof Error?c.message:String(c)}`;n[i]=l,r.push(l)}}if(t.length===1){let o=t[0].trim(),i=n[o];return typeof i=="string"&&i.startsWith("Error:")?this.createToolResult(i,i,!0):i}return this.createToolResult(n,r.join(`
263
+ `),!0)}catch(t){let n=`Error: Read operation failed - ${t instanceof Error?t.message:String(t)}`;return this.createToolResult(n,n,!0)}}formatObservation(e){if(typeof e=="object"&&e.__tool_result)return super.formatObservation(e);if(Array.isArray(e)&&this.lastReadPath)return`\u8BFB\u53D6\u6587\u4EF6 ${this.lastReadPath}\uFF0C\u5171 ${e.length} \u5757`;if(typeof e=="string"&&this.lastReadPath){let n=e.split(`
264
+ `).length;return`\u8BFB\u53D6\u6587\u4EF6 ${this.lastReadPath}\uFF0C\u5171 ${n} \u884C`}return super.formatObservation(e)}},Hl=new Dn;Qr=Hl});import{EOL as Fn}from"os";function Zr(s,e={}){let{preserveEscapes:t=!1,targetFormat:n="lf"}=e,r=s;if(t||(r=r.replace(/\\n/g,`
265
+ `).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\"/g,'"').replace(/\\'/g,"'")),r=r.replace(/\r\n/g,`
254
266
  `).replace(/\r/g,`
255
- `),e}function _r(o){return o.includes(`\r
256
- `)?`\r
257
- `:o.includes(`
258
- `)?`
259
- `:o.includes("\r")?"\r":us}var us,gs=C(()=>{us=process.platform==="win32"?`\r
260
- `:`
261
- `});import{mkdirSync as gu}from"fs";import{resolve as pu}from"path";function bn(o){return ga.execute(o)}var kt,ga,rt,ps=C(()=>{V();kt=class extends ${getDefinition(){return{name:"mkdir",description:"Create a directory and all necessary parent directories (like mkdir -p). Returns a confirmation message.",input_schema:{type:"object",properties:{path:{type:"string",description:"The directory path to create"}},required:["path"]}}}execute(e){try{let t=pu(e.path);return gu(t,{recursive:!0}),`Directory created: ${e.path}`}catch(t){return this.formatError(`Cannot create directory ${e.path}`,t)}}},ga=new kt;rt=ga});import{readFileSync as du,writeFileSync as pa,existsSync as mu}from"fs";import{resolve as fu,dirname as hu}from"path";function Tn(o){return da.execute(o)}var Et,da,kn,ma=C(()=>{gs();ps();V();Et=class extends ${getDefinition(){return{name:"write",description:`Write content to a file - ONLY for creating NEW files.
267
+ `),n!=="preserve"&&n!=="lf")switch(n){case"crlf":r=r.replace(/\n/g,`\r
268
+ `);break;case"cr":r=r.replace(/\n/g,"\r");break;case"platform":Fn===`\r
269
+ `&&(r=r.replace(/\n/g,`\r
270
+ `));break}return r}function es(s){if(!s)return{style:"none",dominant:Fn,statistics:{crlf:0,lf:0,cr:0},confidence:0};let e={crlf:(s.match(/\r\n/g)||[]).length,lf:(s.match(/(?<!\r)\n/g)||[]).length,cr:(s.match(/\r(?!\n)/g)||[]).length},t=e.crlf+e.lf+e.cr;if(t===0)return{style:"none",dominant:Fn,statistics:e,confidence:0};let n=`
271
+ `,r=e.lf,o="lf";e.crlf>r&&(n=`\r
272
+ `,r=e.crlf,o="crlf"),e.cr>r&&(n="\r",r=e.cr,o="cr");let i=r/t,a;return i===1||i>.8?a=o:a="mixed",{style:a,dominant:n,statistics:e,confidence:i}}var Io,Vl,Mo=S(()=>{Io=class{originalContent;normalizedContent;originalStyle;constructor(e){this.originalContent=e,this.originalStyle=es(e),this.normalizedContent=Zr(e,{preserveEscapes:!0,targetFormat:"lf"})}getNormalizedContent(){return this.normalizedContent}getOriginalStyle(){return this.originalStyle}restoreLineEndings(e){return this.originalStyle.style==="crlf"||this.originalStyle.dominant===`\r
273
+ `?e.replace(/\n/g,`\r
274
+ `):this.originalStyle.style==="cr"||this.originalStyle.dominant==="\r"?e.replace(/\n/g,"\r"):e}convertTo(e){return Zr(this.originalContent,{preserveEscapes:!0,targetFormat:e})}},Vl={get current(){return Fn},get isWindows(){return Fn===`\r
275
+ `},get isUnix(){return Fn===`
276
+ `},toPlatformFormat(s){return Zr(s,{preserveEscapes:!0,targetFormat:"platform"})}}});import{mkdirSync as ed}from"fs";import{resolve as td}from"path";function ts(s){return Gl.execute(s)}var On,Gl,Yt,Sa=S(()=>{G();On=class extends R{getDefinition(){return{name:"mkdir",description:"Create a directory and all necessary parent directories (like mkdir -p). Returns a confirmation message.",input_schema:{type:"object",properties:{path:{type:"string",description:"The directory path to create"}},required:["path"]}}}execute(e){try{let t=td(e.path);return ed(t,{recursive:!0}),`Directory created: ${e.path}`}catch(t){return this.formatError(`Cannot create directory ${e.path}`,t)}}},Gl=new On;Yt=Gl});import{readFileSync as nd,writeFileSync as ql,existsSync as rd}from"fs";import{resolve as sd,dirname as od}from"path";function ns(s){return Jl.execute(s)}var Nn,Jl,rs,Kl=S(()=>{Mo();Sa();G();Nn=class extends R{getDefinition(){return{name:"write",description:`Write content to a file - ONLY for creating NEW files.
262
277
 
263
278
  \u{1F4CB} USE CASES:
264
279
  - Create brand new files that don't exist yet
@@ -291,9 +306,9 @@ echo 'test'" }) - Create new shell script
291
306
 
292
307
  \u{1F4DD} RETURN VALUE:
293
308
  - "done" on successful write
294
- - Error message if write fails`,input_schema:{type:"object",properties:{path:{type:"string",description:"File path to write to"},content:{type:"string",description:"Complete file content to write (required, cannot be empty)"}},required:["path","content"]}}}execute(e){try{let t=fu(e.path),n=hu(t),r=rt.execute({path:n});if(r.startsWith("Error:"))return r;let s=ua(e.content);typeof s!="string"&&(s=String(s||""));let i=us;if(mu(t)){let a=du(t,"utf-8");i=_r(a);let c=`${t}.base`;pa(c,a,"utf-8")}return i===`\r
295
- `&&(s=s.replace(/\n/g,`\r
296
- `)),pa(t,s,"utf-8"),"done"}catch(t){return this.formatError(`Cannot write ${e.path}`,t)}}},da=new Et;kn=da});import{unlinkSync as yu,existsSync as Cu,statSync as xu,rmdirSync as Su}from"fs";import{resolve as vu}from"path";function En(o){return typeof o=="object"&&o!==null&&"path"in o?ds.execute(o):ds.execute({path:o})}var Pt,ds,Pn,fa=C(()=>{Sn();Pt=class extends Ce{getBaseDefinition(){return{name:"delete",description:`Delete a file, multiple files or directories at the specified path(s).
309
+ - Error message if write fails`,input_schema:{type:"object",properties:{path:{type:"string",description:"File path to write to"},content:{type:"string",description:"Complete file content to write (required, cannot be empty)"}},required:["path","content"]}}}execute(e){try{let t=sd(e.path),n=od(t),r=Yt.execute({path:n});if(r.startsWith("Error:"))return r;let o=Zr(e.content,{preserveEscapes:!1,targetFormat:"lf"});typeof o!="string"&&(o=String(o||""));let i=Vl.current;if(rd(t)){let a=nd(t,"utf-8");i=es(a).dominant;let l=`${t}.base`;ql(l,a,"utf-8")}return i===`\r
310
+ `&&(o=o.replace(/\n/g,`\r
311
+ `)),ql(t,o,"utf-8"),"done"}catch(t){return this.formatError(`Cannot write ${e.path}`,t)}}},Jl=new Nn;rs=Jl});import{unlinkSync as Yl,existsSync as Xl,statSync as id,rmdirSync as ad}from"fs";import{resolve as cd}from"path";function ss(s){if(typeof s=="object"&&s!==null&&"path"in s)return Ca.execute(s);let e;return Array.isArray(s)?e=s:typeof s=="string"?e=[s]:e=[],Ca.execute({path:e})}var _n,Ca,os,Ql=S(()=>{Yr();_n=class extends ze{getBaseDefinition(){return{name:"delete",description:`Delete a file, multiple files or directories at the specified path(s).
297
312
 
298
313
  IMPORTANT:
299
314
  - This action cannot be undone
@@ -305,31 +320,33 @@ Examples:
305
320
  - deleteFile("temp.txt") - delete a single file named temp.txt
306
321
  - deleteFile("temp_dir") - delete a single empty directory named temp_dir
307
322
  - deleteFile({ path: "temp.txt" }) - delete a single file
308
- - deleteFile({ path: ["file1.txt", "dir1", "file2.txt"] }) - delete multiple files and directories`,input_schema:{type:"object",properties:{path:{type:"string",description:"The file path to delete (relative or absolute), or an array of file paths",oneOf:[{type:"string",description:"The file path to delete (relative or absolute)"},{type:"array",items:{type:"string",description:"A file path to delete"},description:"Array of file paths to delete"}]}},required:["path"]}}}getConfirmationMessage(e){let t=Array.isArray(e.path)?e.path:[e.path];return t.length===1?`\u5220\u9664: ${t[0]}`:`\u5220\u9664 ${t.length} \u4E2A\u6587\u4EF6/\u76EE\u5F55`}execute(e){try{let t=Array.isArray(e.path)?e.path:[e.path],n=[];for(let l of t)try{let u=vu(l);if(!Cu(u)){n.push(`Warning: Path not found - ${l}`);continue}xu(u).isDirectory()?(Su(u),n.push(`Directory deleted: ${l}`)):(yu(u),n.push(`File deleted: ${l}`))}catch(u){n.push(`Error: Cannot delete ${l} - ${u instanceof Error?u.message:"Unknown error"}`)}if(t.length===1)return n[0];let r=n.filter(l=>l.startsWith("File deleted")).length,s=n.filter(l=>l.startsWith("Directory deleted")).length,i=n.filter(l=>l.startsWith("Error")).length,a=n.filter(l=>l.startsWith("Warning")).length,c=r+s;return`${n.join(`
323
+ - deleteFile({ path: ["file1.txt", "dir1", "file2.txt"] }) - delete multiple files and directories`,input_schema:{type:"object",properties:{path:{type:"array",items:{type:"string",description:"A file path to delete (relative or absolute)"},description:"Array of file paths to delete. Supports single or multiple files."}},required:["path"]}}}getConfirmationMessage(e){let t=e.path;return t.length===1?`\u5220\u9664: ${t[0]}`:`\u5220\u9664 ${t.length} \u4E2A\u6587\u4EF6/\u76EE\u5F55`}execute(e){try{let t=e.path,n=[];for(let l of t)try{let u=cd(l);if(!Xl(u)){n.push(`Warning: Path not found - ${l}`);continue}if(id(u).isDirectory())ad(u),n.push(`Directory deleted: ${l}`);else{Yl(u),n.push(`File deleted: ${l}`);let g=`${u}.base`;if(Xl(g))try{Yl(g),n.push(" \u2514\u2500 Associated .base file also deleted")}catch(m){n.push(` \u2514\u2500 Warning: Could not delete associated .base file - ${m instanceof Error?m.message:"Unknown error"}`)}}}catch(u){n.push(`Error: Cannot delete ${l} - ${u instanceof Error?u.message:"Unknown error"}`)}if(t.length===1)return n[0];let r=n.filter(l=>l.startsWith("File deleted")).length,o=n.filter(l=>l.startsWith("Directory deleted")).length,i=n.filter(l=>l.startsWith("Error")).length,a=n.filter(l=>l.startsWith("Warning")).length,c=r+o;return`${n.join(`
309
324
  `)}
310
325
 
311
- Summary: ${c} items deleted (${r} files, ${s} directories), ${a} warnings, ${i} errors`}catch(t){return this.formatError("Cannot process delete operation",t)}}},ds=new Pt;Pn=ds});import{renameSync as wu,existsSync as Nr,statSync as bu,mkdirSync as Tu}from"fs";import{resolve as ha,dirname as ku}from"path";function $n(o){return o&&typeof o=="object"&&"source"in o&&"destination"in o?ya.execute(o):"Error: Invalid input format. Expected { source: string, destination: string }"}var $t,ya,Mn,Ca=C(()=>{Sn();$t=class extends Ce{getBaseDefinition(){return{name:"move",description:`Move or rename a file or directory from source to destination.
326
+ Summary: ${c} items deleted (${r} files, ${o} directories), ${a} warnings, ${i} errors`}catch(t){return this.formatError("Cannot process delete operation",t)}}},Ca=new _n;os=Ca});import{renameSync as Zl,existsSync as Un,statSync as ld,mkdirSync as ud}from"fs";import{resolve as eu,dirname as pd}from"path";function is(s){return s&&typeof s=="object"&&"source"in s&&"destination"in s?tu.execute(s):"Error: Invalid input format. Expected { source: string, destination: string }"}var Wn,tu,as,nu=S(()=>{Yr();Wn=class extends ze{getBaseDefinition(){return{name:"move",description:`Move or rename a file or directory from source to destination.
312
327
 
313
328
  Examples:
314
329
  - moveFile({ source: "old.txt", destination: "new.txt" }) - rename a file
315
330
  - moveFile({ source: "file.txt", destination: "folder/file.txt" }) - move a file to a different directory
316
331
  - moveFile({ source: "old_folder", destination: "new_folder" }) - rename a directory
317
- - moveFile({ source: "folder/file.txt", destination: "new_location/file.txt" }) - move a file with rename`,input_schema:{type:"object",properties:{source:{type:"string",description:"The source file or directory path to move"},destination:{type:"string",description:"The destination path (new name or location)"}},required:["source","destination"]}}}getConfirmationMessage(e){return`\u79FB\u52A8/\u91CD\u547D\u540D: ${e.source} \u2192 ${e.destination}`}execute(e){try{let{source:t,destination:n}=e,r=ha(t),s=ha(n);if(!Nr(r))return`Error: Source path does not exist - ${t}`;if(Nr(s))return`Error: Destination already exists - ${n}`;let i=ku(s);return Nr(i)||Tu(i,{recursive:!0}),wu(r,s),Nr(s)?`${bu(r).isDirectory()?"Directory":"File"} moved successfully from "${t}" to "${n}"`:`Error: Failed to move ${t} to ${n}`}catch(t){return this.formatError("Move operation",t)}}},ya=new $t;Mn=ya});import{existsSync as Ur,statSync as xa,readFileSync as Sa,writeFileSync as va,mkdirSync as wa,readdirSync as Eu}from"fs";import{resolve as ba,join as Ta,dirname as Pu}from"path";function In(o){return o&&typeof o=="object"&&"source"in o&&"destination"in o?ka.execute(o):"Error: Invalid input format. Expected { source: string, destination: string }"}var Mt,ka,An,Ea=C(()=>{Sn();Mt=class extends Ce{getBaseDefinition(){return{name:"copy",description:`Copy a file or directory from source to destination.
332
+ - moveFile({ source: "folder/file.txt", destination: "new_location/file.txt" }) - move a file with rename`,input_schema:{type:"object",properties:{source:{type:"string",description:"The source file or directory path to move"},destination:{type:"string",description:"The destination path (new name or location)"}},required:["source","destination"]}}}getConfirmationMessage(e){return`\u79FB\u52A8/\u91CD\u547D\u540D: ${e.source} \u2192 ${e.destination}`}execute(e){try{let{source:t,destination:n}=e,r=eu(t),o=eu(n);if(!Un(r))return`Error: Source path does not exist - ${t}`;if(Un(o))return`Error: Destination already exists - ${n}`;let i=pd(o);Un(i)||ud(i,{recursive:!0}),Zl(r,o);let a=`${r}.base`,c=`${o}.base`,l=!1;if(Un(a))try{Zl(a,c),l=!0}catch{}if(Un(o)){let p=`${ld(o).isDirectory()?"Directory":"File"} moved successfully from "${t}" to "${n}"`;return l?p+=`
333
+ \u2514\u2500 Associated .base file also moved`:Un(a)&&(p+=`
334
+ \u2514\u2500 Warning: Associated .base file could not be moved (still at original location)`),p}else return`Error: Failed to move ${t} to ${n}`}catch(t){return this.formatError("Move operation",t)}}},tu=new Wn;as=tu});import{existsSync as Ao,statSync as ru,readFileSync as su,writeFileSync as ou,mkdirSync as iu,readdirSync as gd}from"fs";import{resolve as au,join as cu,dirname as md}from"path";function cs(s){return s&&typeof s=="object"&&"source"in s&&"destination"in s?lu.execute(s):"Error: Invalid input format. Expected { source: string, destination: string }"}var Bn,lu,ls,uu=S(()=>{Yr();Bn=class extends ze{getBaseDefinition(){return{name:"copy",description:`Copy a file or directory from source to destination.
318
335
 
319
336
  Examples:
320
337
  - copyFile({ source: "file.txt", destination: "file_copy.txt" }) - copy a file
321
338
  - copyFile({ source: "file.txt", destination: "folder/file.txt" }) - copy a file to a different directory
322
339
  - copyFile({ source: "folder", destination: "folder_copy" }) - copy an entire directory (recursively)
323
- - copyFile({ source: "folder/subdir", destination: "new_location/subdir" }) - copy a subdirectory`,input_schema:{type:"object",properties:{source:{type:"string",description:"The source file or directory path to copy"},destination:{type:"string",description:"The destination path (new location)"}},required:["source","destination"]}}}getConfirmationMessage(e){return`\u590D\u5236: ${e.source} \u2192 ${e.destination}`}execute(e){try{let{source:t,destination:n}=e,r=ba(t),s=ba(n);if(!Ur(r))return`Error: Source path does not exist - ${t}`;if(r===s)return"Error: Source and destination paths are identical";let i=xa(r),a=0,c=0;if(i.isDirectory())return this.copyDirectory(r,s,a,c),`Directory copied successfully from "${t}" to "${n}" (${a} files, ${c} directories)`;{let l=Pu(s);return Ur(l)||wa(l,{recursive:!0}),va(s,Sa(r)),Ur(s)?`File copied successfully from "${t}" to "${n}"`:`Error: Failed to copy file from "${t}" to "${n}"`}}catch(t){return this.formatError("Copy operation",t)}}copyDirectory(e,t,n,r){Ur(t)||(wa(t,{recursive:!0}),r++),Eu(e).forEach(i=>{let a=Ta(e,i),c=Ta(t,i);xa(a).isDirectory()?this.copyDirectory(a,c,n,r):(va(c,Sa(a)),n++)})}},ka=new Mt;An=ka});import{diff3Merge as $u}from"node-diff3";function Pa(o,e,t){let n=o.split(`
340
+ - copyFile({ source: "folder/subdir", destination: "new_location/subdir" }) - copy a subdirectory`,input_schema:{type:"object",properties:{source:{type:"string",description:"The source file or directory path to copy"},destination:{type:"string",description:"The destination path (new location)"}},required:["source","destination"]}}}getConfirmationMessage(e){return`\u590D\u5236: ${e.source} \u2192 ${e.destination}`}execute(e){try{let{source:t,destination:n}=e,r=au(t),o=au(n);if(!Ao(r))return`Error: Source path does not exist - ${t}`;if(r===o)return"Error: Source and destination paths are identical";let i=ru(r),a=0,c=0;if(i.isDirectory())return this.copyDirectory(r,o,a,c),`Directory copied successfully from "${t}" to "${n}" (${a} files, ${c} directories)`;{let l=md(o);return Ao(l)||iu(l,{recursive:!0}),ou(o,su(r)),Ao(o)?`File copied successfully from "${t}" to "${n}"`:`Error: Failed to copy file from "${t}" to "${n}"`}}catch(t){return this.formatError("Copy operation",t)}}copyDirectory(e,t,n,r){Ao(t)||(iu(t,{recursive:!0}),r++),gd(e).forEach(i=>{let a=cu(e,i),c=cu(t,i);ru(a).isDirectory()?this.copyDirectory(a,c,n,r):(ou(c,su(a)),n++)})}},lu=new Bn;ls=lu});import{diff3Merge as dd}from"node-diff3";function pu(s,e,t){let n=s.split(`
324
341
  `),r=e.split(`
325
- `),s=t.split(`
326
- `);console.log(` [merge] \u5F00\u59CB\u4E09\u8DEF\u5408\u5E76: base=${n.length}\u884C, current=${r.length}\u884C, incoming=${s.length}\u884C`);let i=Date.now(),a=$u(r,n,s,{excludeFalseConflicts:!0}),c=((Date.now()-i)/1e3).toFixed(2);console.log(` [merge] diff3Merge \u5B8C\u6210\uFF0C\u8017\u65F6 ${c}s\uFF0C\u7ED3\u679C\u533A\u57DF\u6570: ${a.length}`);let l=[],u=[];for(let p of a)if(p.ok)l.push(...p.ok);else if(p.conflict){let g=l.length+1,d=p.conflict.a||[],m=p.conflict.o||[],h=p.conflict.b||[];u.push({lineNumber:g,base:m.join(`
327
- `),current:d.join(`
328
- `),incoming:h.join(`
329
- `)}),l.push("<<<<<<< CURRENT"),l.push(...d),l.push("======="),l.push(...h),l.push(">>>>>>> INCOMING")}return{merged:l.join(`
330
- `),hasConflicts:u.length>0,conflicts:u}}var $a=C(()=>{});import{readFileSync as Ma,writeFileSync as Wr,existsSync as ms,unlinkSync as fs}from"fs";import{resolve as Mu}from"path";function hs(o){return o.replace(/\r\n/g,`
342
+ `),o=t.split(`
343
+ `);it(` [merge] \u5F00\u59CB\u4E09\u8DEF\u5408\u5E76: base=${n.length}\u884C, current=${r.length}\u884C, incoming=${o.length}\u884C`,"merge");let i=Date.now(),a=dd(r,n,o,{excludeFalseConflicts:!0}),c=((Date.now()-i)/1e3).toFixed(2);it(` [merge] diff3Merge \u5B8C\u6210\uFF0C\u8017\u65F6 ${c}s\uFF0C\u7ED3\u679C\u533A\u57DF\u6570: ${a.length}`,"merge");let l=[],u=[];for(let p of a)if(p.ok)l.push(...p.ok);else if(p.conflict){let g=l.length+1,m=p.conflict.a||[],d=p.conflict.o||[],f=p.conflict.b||[];u.push({lineNumber:g,base:d.join(`
344
+ `),current:m.join(`
345
+ `),incoming:f.join(`
346
+ `)}),l.push("<<<<<<< CURRENT"),l.push(...m),l.push("======="),l.push(...f),l.push(">>>>>>> INCOMING")}return{merged:l.join(`
347
+ `),hasConflicts:u.length>0,conflicts:u}}var gu=S(()=>{Tt()});import{readFileSync as mu,writeFileSync as Ro,existsSync as Lo,unlinkSync as us}from"fs";import{resolve as fd}from"path";function wa(s){return s.replace(/\r\n/g,`
331
348
  `).replace(/\r/g,`
332
- `)}function Ln(o){return Ia.execute(o)}var Iu,It,Ia,Rn,Aa=C(()=>{gs();$a();V();Iu={lineRatioThreshold:.5,minLineDiff:100},It=class extends ${getDefinition(){return{name:"merge",description:`Smart file merge tool - THE SAFE CHOICE for modifying existing files.
349
+ `)}function ps(s){return du.execute(s)}var hd,Hn,du,gs,fu=S(()=>{Mo();gu();aa();G();hd={lineRatioThreshold:.5,minLineDiff:100},Hn=class extends R{getDefinition(){return{name:"merge",description:`Smart file merge tool - THE SAFE CHOICE for modifying existing files.
333
350
 
334
351
  \u{1F4CB} USE CASES:
335
352
  - Update existing files without losing concurrent changes
@@ -372,7 +389,7 @@ Examples:
372
389
  \u{1F4DD} RETURN VALUE:
373
390
  - "Merge successful" messages on success
374
391
  - Conflict details with markers if merge conflicts exist
375
- - Warning message for large deletions requiring confirmation`,input_schema:{type:"object",properties:{path:{type:"string",description:"File path to merge/modify"},newContent:{type:"string",description:"Complete new version of the entire file content"},confirmLargeChange:{type:"boolean",description:"Set to true to confirm large deletions (>50% difference)"}},required:["path","newContent"]}}}execute(e){try{return!e.newContent||e.newContent.trim().length===0?this.formatError("Merge","newContent parameter is required"):this.performThreeWayMerge(e)}catch(t){return this.formatError("Merge",t)}}checkLargeDeletion(e,t,n=Iu){if(t>=e)return{isLargeDeletion:!1,deletionRatio:0,message:""};let r=e-t,s=e>0?r/e:0,i=r>=n.minLineDiff&&s>=n.lineRatioThreshold,a="";if(i){let c=Math.round(s*100);a=`\u26A0\uFE0F LARGE DELETION DETECTED: ${e} \u2192 ${t} lines (${c}% deleted, ${r} lines removed).
392
+ - Warning message for large deletions requiring confirmation`,input_schema:{type:"object",properties:{path:{type:"string",description:"File path to merge/modify"},newContent:{type:"string",description:"Complete new version of the entire file content"},confirmLargeChange:{type:"boolean",description:"Set to true to confirm large deletions (>50% difference)"}},required:["path","newContent"]}}}execute(e){try{return!e.newContent||e.newContent.trim().length===0?this.formatError("Merge","newContent parameter is required"):this.performThreeWayMerge(e)}catch(t){return this.formatError("Merge",t)}}checkLargeDeletion(e,t,n=hd){if(t>=e)return{isLargeDeletion:!1,deletionRatio:0,message:""};let r=e-t,o=e>0?r/e:0,i=r>=n.minLineDiff&&o>=n.lineRatioThreshold,a="";if(i){let c=Math.round(o*100);a=`\u26A0\uFE0F LARGE DELETION DETECTED: ${e} \u2192 ${t} lines (${c}% deleted, ${r} lines removed).
376
393
 
377
394
  This may indicate:
378
395
  - Incomplete content (missing parts of the file)
@@ -380,30 +397,20 @@ This may indicate:
380
397
  - Wrong file content
381
398
 
382
399
  To proceed, call merge() again with confirmLargeChange=true.
383
- Or review your newContent to ensure it's complete.`}return{isLargeDeletion:i,deletionRatio:s,message:a}}performThreeWayMerge(e){try{console.log(` [MergeTool] \u5F00\u59CB\u667A\u80FD\u5408\u5E76: ${e.path}`);let t=Mu(e.path),n=`${t}.base`;if(!ms(t))return console.log(" [MergeTool] \u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u521B\u5EFA\u65B0\u6587\u4EF6"),this.writeNewFile(t,n,e.newContent);console.log(" [MergeTool] \u8BFB\u53D6\u5F53\u524D\u6587\u4EF6\u5185\u5BB9...");let r=Ma(t,"utf-8");console.log(` [MergeTool] \u5F53\u524D\u6587\u4EF6\u5927\u5C0F: ${r.length} \u5B57\u7B26`);let s=_r(r);console.log(` [MergeTool] \u68C0\u6D4B\u5230\u884C\u7ED3\u675F\u7B26: ${s===`\r
384
- `?"CRLF":"LF"}`);let i=hs(r),a=hs(e.newContent),c=i.split(`
385
- `).length,l=a.split(`
386
- `).length;if(!e.confirmLargeChange){let v=this.checkLargeDeletion(c,l);if(v.isLargeDeletion)return console.log(` [MergeTool] \u68C0\u6D4B\u5230\u5927\u5E45\u5220\u51CF\uFF08${c} \u2192 ${l}\u884C\uFF09\uFF0C\u9700\u8981\u786E\u8BA4`),v.message}let u=r,p=!1;ms(n)&&(console.log(" [MergeTool] \u53D1\u73B0\u57FA\u7840\u7248\u672C\u6587\u4EF6\uFF0C\u8BFB\u53D6\u4E2D..."),u=Ma(n,"utf-8"),p=!0,console.log(` [MergeTool] \u57FA\u7840\u7248\u672C\u5927\u5C0F: ${u.length} \u5B57\u7B26`));let g=hs(u);if(g===i){console.log(" [MergeTool] \u65E0\u5E76\u53D1\u4FEE\u6539\uFF08base === current\uFF09\uFF0C\u76F4\u63A5\u5199\u5165");let v=a;if(s===`\r
387
- `&&(v=v.replace(/\n/g,`\r
388
- `)),Wr(t,v,"utf-8"),p)try{fs(n)}catch{}return"Merge successful (direct write, no concurrent edits)."}console.log(" [MergeTool] \u68C0\u6D4B\u5230\u5E76\u53D1\u4FEE\u6539\uFF0C\u6267\u884C\u4E09\u8DEF\u5408\u5E76..."),console.log(` [MergeTool] base=${g.split(`
389
- `).length}\u884C, current=${c}\u884C, incoming=${l}\u884C`);let d=Date.now(),m=Pa(g,i,a),h=((Date.now()-d)/1e3).toFixed(2);console.log(` [MergeTool] threeWayMerge \u5B8C\u6210\uFF0C\u8017\u65F6 ${h}s, \u6709\u51B2\u7A81: ${m.hasConflicts}`);let w=m.merged;if(s===`\r
400
+ Or review your newContent to ensure it's complete.`}return{isLargeDeletion:i,deletionRatio:o,message:a}}performThreeWayMerge(e){try{_(`[MergeTool] \u5F00\u59CB\u667A\u80FD\u5408\u5E76: ${e.path}`);let t=fd(e.path),n=`${t}.base`;if(!Lo(t))return _("[MergeTool] \u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u521B\u5EFA\u65B0\u6587\u4EF6"),this.writeNewFile(t,n,e.newContent);_("[MergeTool] \u8BFB\u53D6\u5F53\u524D\u6587\u4EF6\u5185\u5BB9...");let r=mu(t,"utf-8");_(`[MergeTool] \u5F53\u524D\u6587\u4EF6\u5927\u5C0F: ${r.length} \u5B57\u7B26`);let i=es(r).dominant;_(`[MergeTool] \u68C0\u6D4B\u5230\u884C\u7ED3\u675F\u7B26: ${i===`\r
401
+ `?"CRLF":"LF"}`);let a=wa(r),c=wa(e.newContent),l=a.split(`
402
+ `).length,u=c.split(`
403
+ `).length;if(!e.confirmLargeChange){let T=this.checkLargeDeletion(l,u);if(T.isLargeDeletion){if(_(`[MergeTool] \u68C0\u6D4B\u5230\u5927\u5E45\u5220\u51CF\uFF08${l} \u2192 ${u}\u884C\uFF09\uFF0C\u9700\u8981\u786E\u8BA4`),Lo(n))try{us(n),_(`[MergeTool] \u5DF2\u6E05\u7406 base \u6587\u4EF6: ${n}`)}catch(h){_(`[MergeTool] \u8B66\u544A: \u6E05\u7406 base \u6587\u4EF6\u5931\u8D25: ${h instanceof Error?h.message:String(h)}`)}return T.message}}let p=r,g=!1;Lo(n)&&(_("[MergeTool] \u53D1\u73B0\u57FA\u7840\u7248\u672C\u6587\u4EF6\uFF0C\u8BFB\u53D6\u4E2D..."),p=mu(n,"utf-8"),g=!0,_(`[MergeTool] \u57FA\u7840\u7248\u672C\u5927\u5C0F: ${p.length} \u5B57\u7B26`));let m=wa(p);if(m===a){_("[MergeTool] \u65E0\u5E76\u53D1\u4FEE\u6539\uFF08base === current\uFF09\uFF0C\u76F4\u63A5\u5199\u5165");let T=c;if(i===`\r
404
+ `&&(T=T.replace(/\n/g,`\r
405
+ `)),Ro(t,T,"utf-8"),g)try{us(n),_(`[MergeTool] \u5DF2\u6E05\u7406 base \u6587\u4EF6: ${n}`)}catch(h){_(`[MergeTool] \u8B66\u544A: \u6E05\u7406 base \u6587\u4EF6\u5931\u8D25: ${h instanceof Error?h.message:String(h)}`)}return"Merge successful (direct write, no concurrent edits)."}_("[MergeTool] \u68C0\u6D4B\u5230\u5E76\u53D1\u4FEE\u6539\uFF0C\u6267\u884C\u4E09\u8DEF\u5408\u5E76..."),_(`[MergeTool] base=${m.split(`
406
+ `).length}\u884C, current=${l}\u884C, incoming=${u}\u884C`);let d=Date.now(),f=pu(m,a,c),y=((Date.now()-d)/1e3).toFixed(2);_(`[MergeTool] threeWayMerge \u5B8C\u6210\uFF0C\u8017\u65F6 ${y}s, \u6709\u51B2\u7A81: ${f.hasConflicts}`);let w=f.merged;if(i===`\r
390
407
  `&&(w=w.replace(/\n/g,`\r
391
- `)),m.hasConflicts)return Wr(t,w,"utf-8"),`Merge completed with CONFLICTS. File saved with conflict markers.
408
+ `)),f.hasConflicts){if(Ro(t,w,"utf-8"),g)try{us(n),_(`[MergeTool] \u5DF2\u6E05\u7406 base \u6587\u4EF6: ${n}`)}catch(h){_(`[MergeTool] \u8B66\u544A: \u6E05\u7406 base \u6587\u4EF6\u5931\u8D25: ${h instanceof Error?h.message:String(h)}`)}return`Merge completed with CONFLICTS. File saved with conflict markers.
392
409
  Conflicts:
393
- ${m.conflicts.map(T=>`Line ${T.lineNumber}: BASE="${T.base.substring(0,50)}..." | CURRENT="${T.current.substring(0,50)}..." | INCOMING="${T.incoming.substring(0,50)}..."`).join(`
410
+ ${f.conflicts.map(h=>`Line ${h.lineNumber}: BASE="${h.base.substring(0,50)}..." | CURRENT="${h.current.substring(0,50)}..." | INCOMING="${h.incoming.substring(0,50)}..."`).join(`
394
411
  `)}
395
412
 
396
- Please resolve conflicts manually or use write() to overwrite.`;if(Wr(t,w,"utf-8"),p)try{fs(n)}catch{}return"Merge successful (three-way merge, concurrent edits preserved)."}catch(t){return this.formatError("Merge",t)}}writeNewFile(e,t,n){try{let r=typeof n=="string"?n:String(n||"");if(Wr(e,r,"utf-8"),ms(t))try{fs(t)}catch{}return`File created: ${e}`}catch(r){return this.formatError("Failed to create file",r)}}},Ia=new It;Rn=Ia});import{EOL as ys}from"os";function La(o,e={}){let{preserveEscapes:t=!1,targetFormat:n="lf"}=e,r=o;if(t||(r=r.replace(/\\n/g,`
397
- `).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\"/g,'"').replace(/\\'/g,"'")),r=r.replace(/\r\n/g,`
398
- `).replace(/\r/g,`
399
- `),n!=="preserve"&&n!=="lf")switch(n){case"crlf":r=r.replace(/\n/g,`\r
400
- `);break;case"cr":r=r.replace(/\n/g,"\r");break;case"platform":ys===`\r
401
- `&&(r=r.replace(/\n/g,`\r
402
- `));break}return r}function Au(o){if(!o)return{style:"none",dominant:ys,statistics:{crlf:0,lf:0,cr:0},confidence:0};let e={crlf:(o.match(/\r\n/g)||[]).length,lf:(o.match(/(?<!\r)\n/g)||[]).length,cr:(o.match(/\r(?!\n)/g)||[]).length},t=e.crlf+e.lf+e.cr;if(t===0)return{style:"none",dominant:ys,statistics:e,confidence:0};let n=`
403
- `,r=e.lf,s="lf";e.crlf>r&&(n=`\r
404
- `,r=e.crlf,s="crlf"),e.cr>r&&(n="\r",r=e.cr,s="cr");let i=r/t,a;return i===1||i>.8?a=s:a="mixed",{style:a,dominant:n,statistics:e,confidence:i}}var Vr,Ra=C(()=>{Vr=class{originalContent;normalizedContent;originalStyle;constructor(e){this.originalContent=e,this.originalStyle=Au(e),this.normalizedContent=La(e,{preserveEscapes:!0,targetFormat:"lf"})}getNormalizedContent(){return this.normalizedContent}getOriginalStyle(){return this.originalStyle}restoreLineEndings(e){return this.originalStyle.style==="crlf"||this.originalStyle.dominant===`\r
405
- `?e.replace(/\n/g,`\r
406
- `):this.originalStyle.style==="cr"||this.originalStyle.dominant==="\r"?e.replace(/\n/g,"\r"):e}convertTo(e){return La(this.originalContent,{preserveEscapes:!0,targetFormat:e})}}});import{existsSync as Lu,readFileSync as Ru,writeFileSync as Du}from"fs";import{resolve as Fu}from"path";function Dn(o){return Da.execute(o)}var At,Da,Fn,Fa=C(()=>{V();Ra();At=class extends ${getDefinition(){return{name:"searchReplace",description:`Perform TARGETED SEARCH & REPLACE operations on files.
413
+ Please resolve conflicts manually or use write() to overwrite.`}else{if(Ro(t,w,"utf-8"),g)try{us(n),_(`[MergeTool] \u5DF2\u6E05\u7406 base \u6587\u4EF6: ${n}`)}catch(T){_(`[MergeTool] \u8B66\u544A: \u6E05\u7406 base \u6587\u4EF6\u5931\u8D25: ${T instanceof Error?T.message:String(T)}`)}return"Merge successful (three-way merge, concurrent edits preserved)."}}catch(t){return this.formatError("Merge",t)}}writeNewFile(e,t,n){try{let r=typeof n=="string"?n:String(n||"");if(Ro(e,r,"utf-8"),Lo(t))try{us(t),_(`[MergeTool] \u5DF2\u6E05\u7406\u65E7\u7684 base \u6587\u4EF6: ${t}`)}catch(o){_(`[MergeTool] \u8B66\u544A: \u6E05\u7406\u65E7 base \u6587\u4EF6\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`)}return`File created: ${e}`}catch(r){return this.formatError("Failed to create file",r)}}},du=new Hn;gs=du});import{existsSync as yd,readFileSync as xd,writeFileSync as Sd}from"fs";import{resolve as Cd}from"path";function ms(s){return hu.execute(s)}var zn,hu,ds,yu=S(()=>{G();Mo();zn=class extends R{getDefinition(){return{name:"searchReplace",description:`Perform TARGETED SEARCH & REPLACE operations on files.
407
414
 
408
415
  \u{1F3AF} PERFECT FOR:
409
416
  - Small configuration updates (port numbers, URLs, etc.)
@@ -424,16 +431,16 @@ Please resolve conflicts manually or use write() to overwrite.`;if(Wr(t,w,"utf-8
424
431
  \u{1F4A1} TIPS:
425
432
  - Use precise search text to avoid unintended replacements
426
433
  - Test with small changes first
427
- - For complex modifications, consider using merge() tool instead`,input_schema:{type:"object",properties:{path:{type:"string",description:"The file path to perform search/replace operations on"},operations:{type:"array",description:"Array of search/replace operations. Each operation replaces search text with replace text.",items:{type:"object",properties:{search:{type:"string",description:"Exact text to search for"},replace:{type:"string",description:"Text to replace the search text with"}},required:["search","replace"]}}},required:["path","operations"]}}}execute(e){try{if(!e.path||e.path.trim().length===0)return this.formatError("SearchReplace","Path parameter is required");if(!e.operations||!Array.isArray(e.operations)||e.operations.length===0)return this.formatError("SearchReplace","Operations array is required and must not be empty");let t=Fu(e.path);if(!Lu(t))return this.formatError("SearchReplace",`File not found: ${t}`);let n=Ru(t,"utf-8"),r=new Vr(n),s=r.getOriginalStyle(),i=r.getNormalizedContent(),a=0,c=[];for(let[p,g]of e.operations.entries()){let{search:d,replace:m}=g;if(!d||d.trim().length===0){c.push(`\u274C Operation ${p+1}: empty search text`);continue}try{i.includes(d)?(i=i.replace(d,m),a++,c.push(`\u2705 Operation ${p+1}: "${d.substring(0,30)}..." \u2192 "${m.substring(0,30)}..."`)):c.push(`\u274C Operation ${p+1}: search text not found "${d.substring(0,30)}..."`)}catch(h){c.push(`\u274C Operation ${p+1}: ${h instanceof Error?h.message:String(h)}`)}}if(a>0){let p=r.restoreLineEndings(i);Du(t,p,"utf-8")}let l=`Search/replace completed. ${a} of ${e.operations.length} operations applied successfully.`,u=c.length>0?`
434
+ - For complex modifications, consider using merge() tool instead`,input_schema:{type:"object",properties:{path:{type:"string",description:"The file path to perform search/replace operations on"},operations:{type:"array",description:"Array of search/replace operations. Each operation replaces search text with replace text.",items:{type:"object",properties:{search:{type:"string",description:"Exact text to search for"},replace:{type:"string",description:"Text to replace the search text with"}},required:["search","replace"]}}},required:["path","operations"]}}}execute(e){try{if(!e.path||e.path.trim().length===0)return this.formatError("SearchReplace","Path parameter is required");if(!e.operations||!Array.isArray(e.operations)||e.operations.length===0)return this.formatError("SearchReplace","Operations array is required and must not be empty");let t=Cd(e.path);if(!yd(t))return this.formatError("SearchReplace",`File not found: ${t}`);let n=xd(t,"utf-8"),r=new Io(n),o=r.getOriginalStyle(),i=r.getNormalizedContent(),a=0,c=[];for(let[p,g]of e.operations.entries()){let{search:m,replace:d}=g;if(!m||m.trim().length===0){c.push(`\u274C Operation ${p+1}: empty search text`);continue}try{i.includes(m)?(i=i.replace(m,d),a++,c.push(`\u2705 Operation ${p+1}: "${m.substring(0,30)}..." \u2192 "${d.substring(0,30)}..."`)):c.push(`\u274C Operation ${p+1}: search text not found "${m.substring(0,30)}..."`)}catch(f){c.push(`\u274C Operation ${p+1}: ${f instanceof Error?f.message:String(f)}`)}}if(a>0){let p=r.restoreLineEndings(i);Sd(t,p,"utf-8")}let l=`Search/replace completed. ${a} of ${e.operations.length} operations applied successfully.`,u=c.length>0?`
428
435
 
429
436
  Operation details:
430
437
  ${c.join(`
431
- `)}`:"";return l+u}catch(t){return this.formatError("SearchReplace",t)}}formatError(e,t){let n=t instanceof Error?t.message:String(t);return`[${e} Error] ${n}`}},Da=new At;Fn=Da});var Q,Ae=C(()=>{Q=class{getCommonDirectoryDescriptions(){return{src:"\u6E90\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u6240\u6709\u4E3B\u8981\u7684\u5E94\u7528\u7A0B\u5E8F\u4EE3\u7801",test:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",tests:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",docs:"\u6587\u6863\u76EE\u5F55\uFF0C\u5305\u542B\u9879\u76EE\u6587\u6863\u548C\u8BF4\u660E",examples:"\u793A\u4F8B\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4F7F\u7528\u793A\u4F8B",bin:"\u53EF\u6267\u884C\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B CLI \u547D\u4EE4\u811A\u672C",lib:"\u5E93\u6587\u4EF6\u76EE\u5F55",dist:"\u6784\u5EFA\u8F93\u51FA\u76EE\u5F55",build:"\u6784\u5EFA\u811A\u672C\u548C\u914D\u7F6E\u76EE\u5F55",config:"\u914D\u7F6E\u6587\u4EF6\u76EE\u5F55",components:"\u7EC4\u4EF6\u76EE\u5F55",pages:"\u9875\u9762\u76EE\u5F55",public:"\u516C\u5171\u8D44\u6E90\u76EE\u5F55",assets:"\u9759\u6001\u8D44\u6E90\u76EE\u5F55",utils:"\u5DE5\u5177\u51FD\u6570\u76EE\u5F55",helpers:"\u8F85\u52A9\u51FD\u6570\u76EE\u5F55",services:"\u670D\u52A1\u5C42\u76EE\u5F55",models:"\u6570\u636E\u6A21\u578B\u76EE\u5F55",controllers:"\u63A7\u5236\u5668\u76EE\u5F55",routes:"\u8DEF\u7531\u5B9A\u4E49\u76EE\u5F55",middleware:"\u4E2D\u95F4\u4EF6\u76EE\u5F55",plugins:"\u63D2\u4EF6\u76EE\u5F55",hooks:"\u94A9\u5B50\u51FD\u6570\u76EE\u5F55",types:"\u7C7B\u578B\u5B9A\u4E49\u76EE\u5F55",interfaces:"\u63A5\u53E3\u5B9A\u4E49\u76EE\u5F55",schemas:"\u6570\u636E\u7ED3\u6784\u5B9A\u4E49\u76EE\u5F55"}}findEntryPoints(e,t){return[]}findEntryPointsByConfig(e,t,n){let r=new Set,{existsSync:s,readFileSync:i}=$r("fs"),{resolve:a}=$r("path");if(n.commonEntries&&n.commonEntries.forEach(c=>{if(e.includes(c))r.add(c);else if(c.includes("*")){let l=new RegExp(c.replace(/\*/g,"[^/]+").replace(/\/\*\*/g,".+"));e.forEach(u=>{l.test(u)&&r.add(u)})}}),n.configFileChecks)for(let c of n.configFileChecks){let l=a(t,c.filePath);if(s(l))try{let u=i(l,"utf-8");c.parseFn(u,e).forEach(g=>r.add(g))}catch{}}if(n.contentChecks)for(let c of n.contentChecks)e.forEach(l=>{if(!c.filter||c.filter(l))try{let u=i(a(t,l),"utf-8");c.pattern.test(u)&&r.add(l)}catch{}});return Array.from(r)}detectCodeStandards(e){return[]}detectCodeStandardsByFiles(e,t){let n=[],{existsSync:r,readFileSync:s}=$r("fs"),{resolve:i}=$r("path");for(let[a,c]of Object.entries(t)){let l=!1;if(Array.isArray(c)){for(let u of c)if(r(i(e,u))){l=!0;break}}else for(let u of c.files){let p=i(e,u);if(r(p))if(c.contentCheck)try{let g=s(p,"utf-8");if(c.contentCheck(g)){l=!0;break}}catch{}else{l=!0;break}}l&&n.push(a)}return n}async validateCode(e,t){return{valid:!0,message:`No validator available for ${this.getLanguageName()}`}}}});import{existsSync as Cs,readFileSync as Ou}from"fs";import{resolve as xs}from"path";var zr,Oa=C(()=>{Ae();zr=class extends Q{getLanguageName(){return"JavaScript/TypeScript"}getDirectoryDescriptions(){return{...this.getCommonDirectoryDescriptions(),src:"\u6E90\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u6240\u6709\u4E3B\u8981\u7684 JavaScript/TypeScript \u4EE3\u7801",lib:"\u7F16\u8BD1\u540E\u7684\u5E93\u6587\u4EF6\u76EE\u5F55",dist:"\u6784\u5EFA\u8F93\u51FA\u76EE\u5F55\uFF0C\u5305\u542B\u6253\u5305\u540E\u7684\u751F\u4EA7\u4EE3\u7801",public:"\u516C\u5171\u8D44\u6E90\u76EE\u5F55\uFF0C\u5305\u542B\u9759\u6001\u6587\u4EF6",assets:"\u9759\u6001\u8D44\u6E90\u76EE\u5F55\uFF0C\u5305\u542B\u56FE\u7247\u3001\u6837\u5F0F\u7B49",components:"React/Vue \u7EC4\u4EF6\u76EE\u5F55",pages:"\u9875\u9762\u7EC4\u4EF6\u76EE\u5F55",hooks:"React \u94A9\u5B50\u51FD\u6570\u76EE\u5F55",context:"React \u4E0A\u4E0B\u6587\u76EE\u5F55",redux:"Redux \u72B6\u6001\u7BA1\u7406\u76EE\u5F55",store:"\u72B6\u6001\u7BA1\u7406\u76EE\u5F55",actions:"Redux \u52A8\u4F5C\u76EE\u5F55",reducers:"Redux \u5F52\u7EA6\u5668\u76EE\u5F55",slices:"Redux Toolkit \u5207\u7247\u76EE\u5F55",middleware:"\u4E2D\u95F4\u4EF6\u76EE\u5F55",utils:"\u5DE5\u5177\u51FD\u6570\u76EE\u5F55",helpers:"\u8F85\u52A9\u51FD\u6570\u76EE\u5F55",services:"API \u670D\u52A1\u76EE\u5F55",api:"API \u63A5\u53E3\u76EE\u5F55",models:"\u6570\u636E\u6A21\u578B\u76EE\u5F55",types:"TypeScript \u7C7B\u578B\u5B9A\u4E49\u76EE\u5F55",interfaces:"TypeScript \u63A5\u53E3\u5B9A\u4E49\u76EE\u5F55",schemas:"\u6570\u636E\u7ED3\u6784\u5B9A\u4E49\u76EE\u5F55",config:"\u914D\u7F6E\u6587\u4EF6\u76EE\u5F55",scripts:"\u811A\u672C\u76EE\u5F55\uFF0C\u5305\u542B\u6784\u5EFA\u3001\u6D4B\u8BD5\u7B49\u811A\u672C",test:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",tests:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",__tests__:"Jest \u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55",spec:"Jasmine/Mocha \u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55",docs:"\u6587\u6863\u76EE\u5F55\uFF0C\u5305\u542B\u9879\u76EE\u6587\u6863\u548C\u8BF4\u660E",examples:"\u793A\u4F8B\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4F7F\u7528\u793A\u4F8B",bin:"\u53EF\u6267\u884C\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B CLI \u547D\u4EE4\u811A\u672C",build:"\u6784\u5EFA\u811A\u672C\u548C\u914D\u7F6E\u76EE\u5F55"}}async detectVersions(e,t){let n={},r=xs(e,"package.json");if(Cs(r))try{let s=Ou(r,"utf-8"),i=JSON.parse(s);i.engines&&(i.engines.node&&(n["Node.js"]=i.engines.node),i.engines.npm&&(n.npm=i.engines.npm),i.engines.yarn&&(n.yarn=i.engines.yarn),i.engines.pnpm&&(n.pnpm=i.engines.pnpm))}catch{}return n}findEntryPoints(e,t){return this.findEntryPointsByConfig(e,t,{commonEntries:["index.js","index.ts","index.mjs","index.cjs","app.js","app.ts","main.js","main.ts","server.js","server.ts","src/index.js","src/index.ts","src/main.js","src/main.ts","src/app.js","src/app.ts","next.config.js","vite.config.js","webpack.config.js","rollup.config.js"],configFileChecks:[{filePath:"package.json",parseFn:(n,r)=>{let s=[],i=JSON.parse(n);return i.main&&s.push(i.main),i.bin&&(typeof i.bin=="string"?s.push(i.bin):s.push(...Object.values(i.bin))),s}}]})}detectCodeStandards(e){let t={ESLint:[".eslintrc.js",".eslintrc.json",".eslintrc.yml",".eslintrc.yaml",".eslintrc"],Prettier:[".prettierrc",".prettierrc.json",".prettierrc.yml",".prettierrc.yaml",".prettierrc.js","prettier.config.js"],EditorConfig:[".editorconfig"],TypeScript:["tsconfig.json"],Flow:[".flowconfig"],Jest:["jest.config.js","jest.config.ts","jest.config.json"],Vitest:["vitest.config.js","vitest.config.ts"],Mocha:["mocha.opts",".mocharc.js"],Jasmine:["jasmine.json"]};return this.detectCodeStandardsByFiles(e,t)}getCommonSourceExtensions(){return[".js",".mjs",".cjs",".jsx",".ts",".tsx",".vue",".svelte",".astro"]}getCommonTestExtensions(){return[".test.js",".test.ts",".test.jsx",".test.tsx",".spec.js",".spec.ts",".spec.jsx",".spec.tsx"]}getCommonConfigFiles(){return["package.json","tsconfig.json","tsconfig.node.json","jsconfig.json",".eslintrc.js",".eslintrc.json",".prettierrc",".prettierrc.json",".editorconfig","vite.config.js","vite.config.ts","webpack.config.js","webpack.config.ts","rollup.config.js","rollup.config.ts","next.config.js","next.config.mjs","nuxt.config.js","nuxt.config.ts","astro.config.mjs","astro.config.ts"]}async analyzeDependencies(e,t){return{dependencies:[],conflicts:[],recommendations:[]}}async validateCode(e,t){let{execSync:n}=await import("child_process"),{extname:r}=await import("path"),s=r(e);return s===".ts"||s===".tsx"?await this.validateTypeScript(e,t,n):await this.validateJavaScript(e,t,n)}async validateTypeScript(e,t,n){try{let r=xs(t,"tsconfig.json");if(!Cs(r))return{valid:!0,message:"No tsconfig.json found, skipping TypeScript validation"};let s=n(`npx tsc --noEmit --pretty false --skipLibCheck --noResolve "${e}"`,{encoding:"utf-8",stdio:"pipe",cwd:t,timeout:3e4});return{valid:!0,message:"TypeScript validation passed"}}catch(r){let s=r.stderr||r.stdout||r.message,i=this.parseTypeScriptErrors(s);return i.length===0?{valid:!1,message:`TypeScript validation failed:
432
- ${s}`}:{valid:!1,message:`TypeScript validation failed with ${i.length} error(s)`,errors:i}}}async validateJavaScript(e,t,n){try{if(![".eslintrc.js",".eslintrc.json",".eslintrc.yml",".eslintrc.yaml",".eslintrc"].some(c=>Cs(xs(t,c))))return{valid:!0,message:"No ESLint configuration found, skipping JavaScript validation"};let i=n(`npx eslint --format json ${e}`,{encoding:"utf-8",stdio:"pipe",cwd:t,timeout:3e4}),a=JSON.parse(i);return a.length===0||a[0].errorCount===0?{valid:!0,message:"ESLint validation passed",warnings:a[0]?.warningCount>0?this.parseEslintMessages(a[0].messages,"warning"):void 0}:{valid:!1,message:`ESLint validation failed with ${a[0].errorCount} error(s)`,errors:this.parseEslintMessages(a[0].messages,"error"),warnings:this.parseEslintMessages(a[0].messages,"warning")}}catch(r){if(r.message?.includes("not found")||r.code==="ENOENT")return{valid:!0,message:"ESLint not available, skipping JavaScript validation"};try{let s=JSON.parse(r.stdout||"[]");if(s.length>0&&s[0].errorCount>0)return{valid:!1,message:`ESLint validation failed with ${s[0].errorCount} error(s)`,errors:this.parseEslintMessages(s[0].messages,"error"),warnings:this.parseEslintMessages(s[0].messages,"warning")}}catch{}return{valid:!1,message:`JavaScript validation failed: ${r.message}`}}}parseTypeScriptErrors(e){let t=[],n=e.split(`
433
- `);for(let r of n){let s=r.match(/\((\d+),(\d+)\):\s+(error|warning)\s+TS(\d+):\s+(.+)/);s&&t.push({line:parseInt(s[1]),column:parseInt(s[2]),severity:s[3],code:`TS${s[4]}`,message:s[5]})}return t}parseEslintMessages(e,t){return e.filter(n=>n.severity===(t==="error"?2:1)).map(n=>({line:n.line,column:n.column,severity:t,code:n.ruleId,message:n.message}))}}});import{existsSync as Le,readFileSync as On,writeFileSync as ju,mkdirSync as _u}from"fs";import{resolve as Lt,dirname as Nu}from"path";var Hr,ja=C(()=>{Ae();Hr=class extends Q{getLanguageName(){return"Java"}getDirectoryDescriptions(){return{...this.getCommonDirectoryDescriptions(),src:"\u6E90\u4EE3\u7801\u6839\u76EE\u5F55","src/main/java":"\u4E3B\u6E90\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u751F\u4EA7\u4EE3\u7801","src/main/resources":"\u4E3B\u8D44\u6E90\u76EE\u5F55\uFF0C\u5305\u542B\u914D\u7F6E\u6587\u4EF6\u548C\u9759\u6001\u8D44\u6E90","src/test/java":"\u6D4B\u8BD5\u6E90\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5","src/test/resources":"\u6D4B\u8BD5\u8D44\u6E90\u76EE\u5F55\uFF0C\u5305\u542B\u6D4B\u8BD5\u914D\u7F6E\u6587\u4EF6",target:"\u6784\u5EFA\u8F93\u51FA\u76EE\u5F55\uFF0C\u5305\u542B\u7F16\u8BD1\u540E\u7684\u7C7B\u6587\u4EF6\u548C\u6253\u5305\u4EA7\u7269",lib:"\u5916\u90E8\u4F9D\u8D56\u5E93\u76EE\u5F55",libs:"\u5916\u90E8\u4F9D\u8D56\u5E93\u76EE\u5F55",build:"\u6784\u5EFA\u811A\u672C\u548C\u914D\u7F6E\u76EE\u5F55",gradle:"Gradle \u6784\u5EFA\u7CFB\u7EDF\u76EE\u5F55",maven:"Maven \u6784\u5EFA\u7CFB\u7EDF\u76EE\u5F55",docs:"\u6587\u6863\u76EE\u5F55\uFF0C\u5305\u542B\u9879\u76EE\u6587\u6863\u548C\u8BF4\u660E",examples:"\u793A\u4F8B\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4F7F\u7528\u793A\u4F8B",bin:"\u53EF\u6267\u884C\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u7F16\u8BD1\u540E\u7684\u4E8C\u8FDB\u5236\u6587\u4EF6",config:"\u914D\u7F6E\u6587\u4EF6\u76EE\u5F55",scripts:"\u811A\u672C\u76EE\u5F55\uFF0C\u5305\u542B\u6784\u5EFA\u3001\u90E8\u7F72\u7B49\u811A\u672C"}}async detectVersions(e,t){let n={},r=Lt(e,"pom.xml");if(Le(r))try{let a=On(r,"utf-8"),c=a.match(/<java\.version>([^<]+)<\/java\.version>/)||a.match(/<maven\.compiler\.source>([^<]+)<\/maven\.compiler\.source>/);c&&(n.Java=c[1])}catch{}let s=Lt(e,"build.gradle"),i=Lt(e,"build.gradle.kts");if(Le(s))try{let a=On(s,"utf-8"),c=a.match(/sourceCompatibility\s*=\s*['"]?([^'"\\s]+)['"]?/)||a.match(/targetCompatibility\s*=\s*['"]?([^'"\\s]+)['"]?/);c&&(n.Java=c[1])}catch{}else if(Le(i))try{let a=On(i,"utf-8"),c=a.match(/sourceCompatibility\s*=\s*JavaVersion\.VERSION_(\d+_\d+)/)||a.match(/targetCompatibility\s*=\s*JavaVersion\.VERSION_(\d+_\d+)/);c&&(n.Java=c[1].replace("_","."))}catch{}return n}findEntryPoints(e,t){return this.findEntryPointsByConfig(e,t,{commonEntries:["src/main/java/**/Main.java","src/main/java/**/Application.java","src/main/java/**/App.java","src/main/java/**/Bootstrap.java","src/main/java/**/Launcher.java"],contentChecks:[{pattern:/public static void main\(String\[\] args\)/,filter:n=>n.endsWith(".java")}]})}detectCodeStandards(e){let t={Checkstyle:["checkstyle.xml","google_checks.xml","sun_checks.xml"],PMD:["pmd.xml",".pmd"],FindBugs:["findbugs.xml",".findbugs"],SpotBugs:["spotbugs.xml",".spotbugs"],SonarQube:["sonar-project.properties"],EditorConfig:[".editorconfig"],Maven:["pom.xml"],Gradle:["build.gradle","build.gradle.kts"]};return this.detectCodeStandardsByFiles(e,t)}getCommonSourceExtensions(){return[".java",".class",".jar",".war",".ear"]}getCommonTestExtensions(){return["Test.java","Tests.java"]}getCommonConfigFiles(){return["pom.xml","build.gradle","build.gradle.kts","settings.gradle","gradle.properties","checkstyle.xml","pmd.xml","spotbugs.xml","sonar-project.properties",".editorconfig"]}async analyzeDependencies(e,t){let n={dependencies:[],conflicts:[],recommendations:[]};try{let r=Lt(e,"pom.xml"),s=Lt(e,"build.gradle"),i=Lt(e,"build.gradle.kts");if(!Le(r)&&!Le(s)&&!Le(i))return n;Le(r)?await this.analyzeMavenDependencies(r,n):Le(s)?this.analyzeGradleDependencies(s,n):Le(i)&&this.analyzeGradleDependencies(i,n),this.detectDependencyConflicts(n),this.generateRecommendations(n)}catch(r){console.error("\u4F9D\u8D56\u5206\u6790\u5931\u8D25:",r)}return n}async analyzeMavenDependencies(e,t){let n=On(e,"utf-8"),r=await import("xml2js");return new Promise((s,i)=>{r.parseString(n,{explicitArray:!1},(a,c)=>{if(a){i(a);return}let{project:l}=c;if(!l){s();return}let u=l.dependencies?.dependency;u&&(Array.isArray(u)?u:[u]).forEach(g=>{t.dependencies.push({groupId:g.groupId,artifactId:g.artifactId,version:g.version||"unknown",scope:g.scope||"compile",type:g.type||"jar"})}),s()})})}analyzeGradleDependencies(e,t){let n=On(e,"utf-8");[/(implementation|compile|api|compileOnly|runtimeOnly|testImplementation|testCompile|testApi|testCompileOnly|testRuntimeOnly)\s*['"]([^:'"]+):([^:'"]+):([^:'"]+)['"]/gms,/(implementation|compile|api|compileOnly|runtimeOnly|testImplementation|testCompile|testApi|testCompileOnly|testRuntimeOnly)\s*['"]([^:'"]+):([^:'"]+)['"]/gms,/(implementation|compile|api|compileOnly|runtimeOnly|testImplementation|testCompile|testApi|testCompileOnly|testRuntimeOnly)\s*\(\s*group\s*:\s*['"]([^'"]+)['"],\s*name\s*:\s*['"]([^'"]+)['"],\s*version\s*:\s*['"]([^'"]+)['"][^)]*\)/gms,/(implementation|compile|api|compileOnly|runtimeOnly|testImplementation|testCompile|testApi|testCompileOnly|testRuntimeOnly)\s*\(\s*["']([^"']+):([^"']+):([^"']+)["']\s*\)/gms].forEach(s=>{let i;for(;(i=s.exec(n))!==null;){let a,c,l,u;if(i.length===5)[,a,c,l,u]=i;else if(i.length===4)[,a,c,l]=i,u="managed";else continue;t.dependencies.push({groupId:c,artifactId:l,version:u,scope:a.toLowerCase(),type:"jar"})}})}detectDependencyConflicts(e){let t=new Map;e.dependencies.forEach(n=>{if(n.groupId&&n.artifactId){let r=`${n.groupId}:${n.artifactId}`;t.has(r)||t.set(r,new Set),t.get(r)?.add(n.version)}}),t.forEach((n,r)=>{if(n.size>1){let[s,i]=r.split(":");e.conflicts.push({groupId:s,artifactId:i,versions:Array.from(n),severity:this.calculateConflictSeverity(Array.from(n))})}})}calculateConflictSeverity(e){let t=e.map(r=>{let s=r.match(/^(\d+)/);return s?parseInt(s[1]):0});return new Set(t).size>1?"high":e.length>2?"medium":"low"}generateRecommendations(e){let t=[];e.conflicts.length>0&&t.push(`${e.conflicts.length} \u4E2A\u4F9D\u8D56\u5B58\u5728\u7248\u672C\u51B2\u7A81\uFF0C\u5EFA\u8BAE\u7EDF\u4E00\u7248\u672C`),e.dependencies.some(s=>s.groupId==="org.springframework.boot")&&t.push("\u9879\u76EE\u4F7F\u7528Spring Boot\uFF0C\u5EFA\u8BAE\u4F7F\u7528Spring Dependency Management\u63D2\u4EF6\u7BA1\u7406\u4F9D\u8D56\u7248\u672C");let r=this.detectJavaVersion(e);if(r){let s=parseInt(r);s<11?t.push("Java\u7248\u672C\u8F83\u65E7\uFF0C\u5EFA\u8BAE\u5347\u7EA7\u5230Java 11\u6216\u66F4\u9AD8\u7248\u672C"):s>=17&&t.push("\u4F7F\u7528\u73B0\u4EE3Java\u7248\u672C\uFF0C\u53EF\u4EE5\u4EAB\u53D7\u6700\u65B0\u7279\u6027")}e.recommendations=t}detectJavaVersion(e){}saveDependencyAnalysis(e,t){try{let n=`${t}/.nium/java-dependency-analysis.json`;_u(Nu(n),{recursive:!0}),ju(n,JSON.stringify({scanTime:new Date().toISOString(),dependencies:e.dependencies,conflicts:e.conflicts,recommendations:e.recommendations},null,2))}catch(n){console.error("\u4FDD\u5B58\u4F9D\u8D56\u5206\u6790\u7ED3\u679C\u5931\u8D25:",n)}}}});import{existsSync as jn,readFileSync as Ss}from"fs";import{resolve as _n}from"path";var Jr,_a=C(()=>{Ae();Jr=class extends Q{getLanguageName(){return"Python"}getDirectoryDescriptions(){return{...this.getCommonDirectoryDescriptions(),src:"\u6E90\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4E3B\u8981\u7684 Python \u4EE3\u7801",app:"\u5E94\u7528\u7A0B\u5E8F\u4EE3\u7801\u76EE\u5F55",main:"\u4E3B\u7A0B\u5E8F\u4EE3\u7801\u76EE\u5F55",lib:"\u5E93\u6587\u4EF6\u76EE\u5F55",libs:"\u5E93\u6587\u4EF6\u76EE\u5F55",tests:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",test:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",__pycache__:"Python \u7F16\u8BD1\u7F13\u5B58\u76EE\u5F55",venv:"\u865A\u62DF\u73AF\u5883\u76EE\u5F55",".venv":"\u865A\u62DF\u73AF\u5883\u76EE\u5F55",env:"\u73AF\u5883\u53D8\u91CF\u914D\u7F6E\u76EE\u5F55",config:"\u914D\u7F6E\u6587\u4EF6\u76EE\u5F55",data:"\u6570\u636E\u6587\u4EF6\u76EE\u5F55",docs:"\u6587\u6863\u76EE\u5F55\uFF0C\u5305\u542B\u9879\u76EE\u6587\u6863\u548C\u8BF4\u660E",examples:"\u793A\u4F8B\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4F7F\u7528\u793A\u4F8B",scripts:"\u811A\u672C\u76EE\u5F55\uFF0C\u5305\u542B\u6784\u5EFA\u3001\u90E8\u7F72\u7B49\u811A\u672C",bin:"\u53EF\u6267\u884C\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B CLI \u547D\u4EE4\u811A\u672C",build:"\u6784\u5EFA\u8F93\u51FA\u76EE\u5F55",dist:"\u6253\u5305\u8F93\u51FA\u76EE\u5F55\uFF0C\u5305\u542B\u53D1\u5E03\u7684\u5305\u6587\u4EF6",requirements:"\u4F9D\u8D56\u7BA1\u7406\u76EE\u5F55"}}async detectVersions(e,t){let n={},r=_n(e,".python-version");if(jn(r))try{let a=Ss(r,"utf-8");n.Python=a.trim()}catch{}let s=_n(e,"pyproject.toml");if(jn(s))try{let c=Ss(s,"utf-8").match(/python\s*=\s*['"]([^'"]+)['"]/);c&&(n.Python=c[1])}catch{}let i=_n(e,"setup.py");if(jn(i))try{let c=Ss(i,"utf-8").match(/python_requires\s*=\s*['"]([^'"]+)['"]/);c&&(n.Python=c[1])}catch{}return n}findEntryPoints(e,t){return this.findEntryPointsByConfig(e,t,{commonEntries:["main.py","__main__.py","app.py","run.py","manage.py","server.py","cli.py","setup.py","src/main.py","src/__main__.py","src/app.py"],configFileChecks:[{filePath:"setup.py",parseFn:(n,r)=>{let s=[],i=n.match(/entry_points\s*=\s*\{[^}]+\}/s);if(i){let c=i[0].match(/console_scripts\s*:\s*\[([^\]]+)\]/s);if(c){let u=c[1].match(/([^=]+)\s*=\s*([^,]+)/g);u&&u.forEach(p=>{let[g,d]=p.split("=").map(h=>h.trim()),m=d.replace(/\./g,"/").replace(":","/")+".py";s.push(m)})}}return s}}]})}detectCodeStandards(e){let t={Black:{files:["pyproject.toml","setup.cfg"],contentCheck:n=>n.includes("[tool.black]")},Pylint:[".pylintrc","pylintrc","setup.cfg"],Flake8:[".flake8","flake8.cfg","setup.cfg"],Mypy:["mypy.ini",".mypy.ini","setup.cfg","pyproject.toml"],isort:[".isort.cfg","setup.cfg","pyproject.toml"],Bandit:[".bandit","bandit.yml"],Pytest:["pytest.ini","setup.cfg","conftest.py"],EditorConfig:[".editorconfig"]};return this.detectCodeStandardsByFiles(e,t)}getCommonSourceExtensions(){return[".py",".pyc",".pyo",".pyd",".pyx",".pxd",".pxi"]}getCommonTestExtensions(){return[".test.py",".spec.py","_test.py","test_*.py","*_test.py"]}getCommonConfigFiles(){return["pyproject.toml","setup.py","setup.cfg","requirements.txt","requirements-dev.txt","Pipfile","Pipfile.lock","poetry.lock",".pylintrc",".flake8","mypy.ini",".isort.cfg","pytest.ini","conftest.py",".editorconfig"]}async analyzeDependencies(e,t){return{dependencies:[],conflicts:[],recommendations:[]}}async validateCode(e,t){let{execSync:n}=await import("child_process"),r=await Promise.all([this.validatePythonSyntax(e,t,n),this.validateWithFlake8(e,t,n),this.validateWithMypy(e,t,n)]),s=r.find(a=>!a.valid);if(s)return s;let i=r.flatMap(a=>a.warnings||[]).filter((a,c,l)=>l.findIndex(u=>u.message===a.message)===c);return{valid:!0,message:"Python validation passed",warnings:i.length>0?i:void 0}}async validatePythonSyntax(e,t,n){try{let r="python3";try{n("python3 --version",{stdio:"pipe"})}catch{r="python"}return n(`${r} -m py_compile "${e}"`,{encoding:"utf-8",stdio:"pipe",cwd:t,timeout:1e4}),{valid:!0,message:"Python syntax check passed"}}catch(r){if(r.message?.includes("not found")||r.message?.includes("not recognized")||r.code==="ENOENT"||r.message?.includes("Command failed"))return{valid:!0,message:"Python not available, skipping validation"};let s=r.stderr||r.stdout||r.message,i=this.parsePythonSyntaxErrors(s);return{valid:!1,message:"Python syntax errors found",errors:i.length>0?i:[{severity:"error",message:s}]}}}async validateWithFlake8(e,t,n){try{if(![".flake8","setup.cfg","tox.ini"].some(a=>jn(_n(t,a))))return{valid:!0,message:"No Flake8 configuration found, skipping"};let i="python3";try{n("python3 --version",{stdio:"pipe"})}catch{i="python"}return n(`${i} -m flake8 --format=json "${e}"`,{encoding:"utf-8",stdio:"pipe",cwd:t,timeout:15e3}),{valid:!0,message:"Flake8 validation passed"}}catch(r){if(r.message?.includes("No module named")||r.code==="ENOENT")return{valid:!0,message:"Flake8 not available, skipping"};let s=r.stdout||r.stderr||"",i=this.parseFlake8Errors(s);return i.length===0?{valid:!0,message:"Flake8 validation completed"}:{valid:!1,message:`Flake8 found ${i.length} issue(s)`,errors:i.filter(a=>a.severity==="error"),warnings:i.filter(a=>a.severity==="warning")}}}async validateWithMypy(e,t,n){try{if(!["mypy.ini",".mypy.ini","setup.cfg","pyproject.toml"].some(a=>jn(_n(t,a))))return{valid:!0,message:"No Mypy configuration found, skipping"};let i="python3";try{n("python3 --version",{stdio:"pipe"})}catch{i="python"}return n(`${i} -m mypy --show-column-numbers "${e}"`,{encoding:"utf-8",stdio:"pipe",cwd:t,timeout:2e4}),{valid:!0,message:"Mypy type checking passed"}}catch(r){if(r.message?.includes("No module named")||r.code==="ENOENT")return{valid:!0,message:"Mypy not available, skipping"};let s=r.stdout||r.stderr||"",i=this.parseMypyErrors(s);return i.length===0?{valid:!0,message:"Mypy validation completed"}:{valid:!1,message:`Mypy found ${i.length} type error(s)`,errors:i}}}parsePythonSyntaxErrors(e){let t=[],n=e.split(`
434
- `);for(let r of n){let s=r.match(/File "([^"]+)", line (\d+)/);if(s){let i=n[n.indexOf(r)+1];t.push({line:parseInt(s[2]),severity:"error",message:i?.trim()||"Syntax error"})}}return t}parseFlake8Errors(e){let t=[],n=e.split(`
435
- `);for(let r of n){let s=r.match(/([^:]+):(\d+):(\d+):\s+([A-Z]\d+)\s+(.+)/);if(s){let i=s[4],a=i.startsWith("E")||i.startsWith("F")?"error":"warning";t.push({line:parseInt(s[2]),column:parseInt(s[3]),severity:a,code:i,message:s[5]})}}return t}parseMypyErrors(e){let t=[],n=e.split(`
436
- `);for(let r of n){let s=r.match(/([^:]+):(\d+):(\d+):\s+(error|warning|note):\s+(.+)/);if(s){let i=s[4]==="error"?"error":s[4]==="warning"?"warning":"info";t.push({line:parseInt(s[2]),column:parseInt(s[3]),severity:i,message:s[5]})}}return t}}});import{existsSync as Na,readFileSync as Ua}from"fs";import{resolve as Wa}from"path";var Gr,Va=C(()=>{Ae();Gr=class extends Q{getLanguageName(){return"Go"}getDirectoryDescriptions(){return{...this.getCommonDirectoryDescriptions(),src:"\u6E90\u4EE3\u7801\u76EE\u5F55\uFF08\u4F20\u7EDF Go \u9879\u76EE\u7ED3\u6784\uFF09",cmd:"\u547D\u4EE4\u884C\u5DE5\u5177\u76EE\u5F55\uFF0C\u5305\u542B\u53EF\u6267\u884C\u7A0B\u5E8F\u7684\u5165\u53E3\u70B9",internal:"\u5185\u90E8\u5305\u76EE\u5F55\uFF0C\u4EC5\u672C\u9879\u76EE\u53EF\u4F7F\u7528",pkg:"\u53EF\u5BFC\u51FA\u5305\u76EE\u5F55\uFF0C\u4F9B\u5176\u4ED6\u9879\u76EE\u4F7F\u7528",api:"API \u5B9A\u4E49\u76EE\u5F55",web:"Web \u5E94\u7528\u76F8\u5173\u4EE3\u7801\u76EE\u5F55",models:"\u6570\u636E\u6A21\u578B\u76EE\u5F55",services:"\u4E1A\u52A1\u903B\u8F91\u670D\u52A1\u76EE\u5F55",handlers:"\u8BF7\u6C42\u5904\u7406\u5668\u76EE\u5F55",middleware:"\u4E2D\u95F4\u4EF6\u76EE\u5F55",config:"\u914D\u7F6E\u6587\u4EF6\u76EE\u5F55",docs:"\u6587\u6863\u76EE\u5F55\uFF0C\u5305\u542B\u9879\u76EE\u6587\u6863\u548C\u8BF4\u660E",examples:"\u793A\u4F8B\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4F7F\u7528\u793A\u4F8B",scripts:"\u811A\u672C\u76EE\u5F55\uFF0C\u5305\u542B\u6784\u5EFA\u3001\u90E8\u7F72\u7B49\u811A\u672C",test:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",tests:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",vendor:"\u7B2C\u4E09\u65B9\u4F9D\u8D56\u5E93\u76EE\u5F55",bin:"\u53EF\u6267\u884C\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u7F16\u8BD1\u540E\u7684\u4E8C\u8FDB\u5236\u6587\u4EF6",build:"\u6784\u5EFA\u8F93\u51FA\u76EE\u5F55"}}async detectVersions(e,t){let n={},r=Wa(e,"go.mod");if(Na(r))try{let a=Ua(r,"utf-8").match(/^go\s+(\d+\.\d+)/m);a&&(n.Go=a[1])}catch{}let s=Wa(e,"go.sum");if(Na(s))try{let a=Ua(s,"utf-8").match(/^golang\.org\/x\/sys\/v\d+\/[^\s]+\s+go(\d+\.\d+)/);a&&!n.Go&&(n.Go=a[1])}catch{}return n}findEntryPoints(e,t){return this.findEntryPointsByConfig(e,t,{commonEntries:["main.go","cmd/main.go","cmd/app/main.go","cmd/server/main.go","cmd/cli/main.go","src/main.go"],contentChecks:[{pattern:/func main\(\)/,filter:n=>n.endsWith(".go")}]})}detectCodeStandards(e){let t={GoFmt:[".gofmt"],GoLint:[".golint"],"GolangCI-Lint":[".golangci.yml",".golangci.yaml"],EditorConfig:[".editorconfig"],GoMod:["go.mod"],GoSum:["go.sum"]};return this.detectCodeStandardsByFiles(e,t)}getCommonSourceExtensions(){return[".go",".mod",".sum"]}getCommonTestExtensions(){return["_test.go",".test.go"]}getCommonConfigFiles(){return["go.mod","go.sum",".golangci.yml",".golangci.yaml",".editorconfig","Makefile"]}async analyzeDependencies(e,t){return{dependencies:[],conflicts:[],recommendations:[]}}}});import{existsSync as Uu,readFileSync as Wu}from"fs";import{resolve as Vu}from"path";var Br,za=C(()=>{Ae();Br=class extends Q{getLanguageName(){return"Rust"}getDirectoryDescriptions(){return{...this.getCommonDirectoryDescriptions(),src:"\u6E90\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4E3B\u8981\u7684 Rust \u4EE3\u7801","src/bin":"\u4E8C\u8FDB\u5236\u53EF\u6267\u884C\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u591A\u4E2A\u53EF\u6267\u884C\u7A0B\u5E8F","src/lib.rs":"\u5E93\u9879\u76EE\u7684\u4E3B\u5165\u53E3\u6587\u4EF6","src/main.rs":"\u4E8C\u8FDB\u5236\u9879\u76EE\u7684\u4E3B\u5165\u53E3\u6587\u4EF6",target:"\u6784\u5EFA\u8F93\u51FA\u76EE\u5F55\uFF0C\u5305\u542B\u7F16\u8BD1\u540E\u7684\u4E8C\u8FDB\u5236\u6587\u4EF6\u548C\u4F9D\u8D56",tests:"\u96C6\u6210\u6D4B\u8BD5\u76EE\u5F55\uFF0C\u5305\u542B\u96C6\u6210\u6D4B\u8BD5\u4EE3\u7801",examples:"\u793A\u4F8B\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4F7F\u7528\u793A\u4F8B",benches:"\u57FA\u51C6\u6D4B\u8BD5\u76EE\u5F55\uFF0C\u5305\u542B\u6027\u80FD\u6D4B\u8BD5\u4EE3\u7801",docs:"\u6587\u6863\u76EE\u5F55\uFF0C\u5305\u542B\u9879\u76EE\u6587\u6863\u548C\u8BF4\u660E",scripts:"\u811A\u672C\u76EE\u5F55\uFF0C\u5305\u542B\u6784\u5EFA\u3001\u90E8\u7F72\u7B49\u811A\u672C",".cargo":"Cargo \u914D\u7F6E\u76EE\u5F55",vendor:"\u7B2C\u4E09\u65B9\u4F9D\u8D56\u5E93\u76EE\u5F55",config:"\u914D\u7F6E\u6587\u4EF6\u76EE\u5F55"}}async detectVersions(e,t){let n={},r=Vu(e,"Cargo.toml");if(Uu(r))try{let i=Wu(r,"utf-8").match(/rust-version\s*=\s*['"]([^'"]+)['"]/);i&&(n.Rust=i[1])}catch{}return n}findEntryPoints(e,t){return this.findEntryPointsByConfig(e,t,{commonEntries:["src/main.rs","src/lib.rs","src/bin/main.rs","src/bin/*.rs"]})}detectCodeStandards(e){let t={Rustfmt:["rustfmt.toml",".rustfmt.toml"],Clippy:["clippy.toml",".clippy.toml"],EditorConfig:[".editorconfig"],Cargo:["Cargo.toml","Cargo.lock"]};return this.detectCodeStandardsByFiles(e,t)}getCommonSourceExtensions(){return[".rs",".toml",".lock"]}getCommonTestExtensions(){return["_test.rs",".test.rs","tests/*.rs"]}getCommonConfigFiles(){return["Cargo.toml","Cargo.lock","rustfmt.toml","clippy.toml",".editorconfig","Makefile"]}async analyzeDependencies(e,t){return{dependencies:[],conflicts:[],recommendations:[]}}}});import{existsSync as Ha,readFileSync as Ja}from"fs";import{resolve as Ga}from"path";var qr,Ba=C(()=>{Ae();qr=class extends Q{getLanguageName(){return"PHP"}getDirectoryDescriptions(){return{...this.getCommonDirectoryDescriptions(),src:"\u6E90\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4E3B\u8981\u7684 PHP \u4EE3\u7801",app:"\u5E94\u7528\u7A0B\u5E8F\u4EE3\u7801\u76EE\u5F55",public:"\u516C\u5171\u8BBF\u95EE\u76EE\u5F55\uFF0C\u5305\u542B\u5165\u53E3\u6587\u4EF6\u548C\u9759\u6001\u8D44\u6E90","index.php":"\u7F51\u7AD9\u5165\u53E3\u6587\u4EF6",lib:"\u5E93\u6587\u4EF6\u76EE\u5F55",libs:"\u5E93\u6587\u4EF6\u76EE\u5F55",vendor:"Composer \u4F9D\u8D56\u5E93\u76EE\u5F55",composer:"Composer \u76F8\u5173\u6587\u4EF6\u76EE\u5F55",config:"\u914D\u7F6E\u6587\u4EF6\u76EE\u5F55",controllers:"\u63A7\u5236\u5668\u76EE\u5F55",models:"\u6570\u636E\u6A21\u578B\u76EE\u5F55",views:"\u89C6\u56FE\u6A21\u677F\u76EE\u5F55",routes:"\u8DEF\u7531\u5B9A\u4E49\u76EE\u5F55",middleware:"\u4E2D\u95F4\u4EF6\u76EE\u5F55",services:"\u4E1A\u52A1\u903B\u8F91\u670D\u52A1\u76EE\u5F55",helpers:"\u8F85\u52A9\u51FD\u6570\u76EE\u5F55",tests:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",test:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",docs:"\u6587\u6863\u76EE\u5F55\uFF0C\u5305\u542B\u9879\u76EE\u6587\u6863\u548C\u8BF4\u660E",examples:"\u793A\u4F8B\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4F7F\u7528\u793A\u4F8B",scripts:"\u811A\u672C\u76EE\u5F55\uFF0C\u5305\u542B\u6784\u5EFA\u3001\u90E8\u7F72\u7B49\u811A\u672C",bin:"\u53EF\u6267\u884C\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B CLI \u547D\u4EE4\u811A\u672C",build:"\u6784\u5EFA\u8F93\u51FA\u76EE\u5F55"}}async detectVersions(e,t){let n={},r=Ga(e,"composer.json");if(Ha(r))try{let i=Ja(r,"utf-8"),a=JSON.parse(i);a.require&&a.require.php&&(n.PHP=a.require.php)}catch{}let s=Ga(e,".php-version");if(Ha(s))try{let i=Ja(s,"utf-8");n.PHP=i.trim()}catch{}return n}findEntryPoints(e,t){return this.findEntryPointsByConfig(e,t,{commonEntries:["index.php","public/index.php","app/index.php","src/index.php","cli.php","artisan","bin/console","composer.json"]})}detectCodeStandards(e){let t={PHP_CodeSniffer:["phpcs.xml","phpcs.xml.dist",".phpcs.xml",".phpcs.xml.dist"],PHPStan:["phpstan.neon","phpstan.neon.dist","phpstan.yml","phpstan.yml.dist"],Psalm:["psalm.xml","psalm.xml.dist","psalm.yml","psalm.yml.dist"],"PHP-CS-Fixer":[".php-cs-fixer.php",".php-cs-fixer.dist.php"],EditorConfig:[".editorconfig"],PHPUnit:["phpunit.xml","phpunit.xml.dist"],Composer:["composer.json","composer.lock"]};return this.detectCodeStandardsByFiles(e,t)}getCommonSourceExtensions(){return[".php",".phtml",".phar",".json",".lock"]}getCommonTestExtensions(){return[".test.php",".spec.php","Test.php","Tests.php","tests/*.php"]}getCommonConfigFiles(){return["composer.json","composer.lock","phpcs.xml","phpstan.neon","psalm.xml",".php-cs-fixer.php","phpunit.xml",".editorconfig",".php-version"]}async analyzeDependencies(e,t){return{dependencies:[],conflicts:[],recommendations:[]}}}});import{existsSync as qa,readFileSync as Ka}from"fs";import{resolve as Ya}from"path";var Kr,Xa=C(()=>{Ae();Kr=class extends Q{getLanguageName(){return"Ruby"}getDirectoryDescriptions(){return{...this.getCommonDirectoryDescriptions(),src:"\u6E90\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4E3B\u8981\u7684 Ruby \u4EE3\u7801",app:"\u5E94\u7528\u7A0B\u5E8F\u4EE3\u7801\u76EE\u5F55\uFF08Rails \u9879\u76EE\uFF09",bin:"\u53EF\u6267\u884C\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B CLI \u547D\u4EE4\u811A\u672C",lib:"\u5E93\u6587\u4EF6\u76EE\u5F55",libs:"\u5E93\u6587\u4EF6\u76EE\u5F55",vendor:"\u7B2C\u4E09\u65B9\u4F9D\u8D56\u5E93\u76EE\u5F55",config:"\u914D\u7F6E\u6587\u4EF6\u76EE\u5F55",controllers:"\u63A7\u5236\u5668\u76EE\u5F55\uFF08Rails \u9879\u76EE\uFF09",models:"\u6570\u636E\u6A21\u578B\u76EE\u5F55\uFF08Rails \u9879\u76EE\uFF09",views:"\u89C6\u56FE\u6A21\u677F\u76EE\u5F55\uFF08Rails \u9879\u76EE\uFF09",routes:"\u8DEF\u7531\u5B9A\u4E49\u76EE\u5F55\uFF08Rails \u9879\u76EE\uFF09",middleware:"\u4E2D\u95F4\u4EF6\u76EE\u5F55",services:"\u4E1A\u52A1\u903B\u8F91\u670D\u52A1\u76EE\u5F55",helpers:"\u8F85\u52A9\u51FD\u6570\u76EE\u5F55",tests:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",test:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",spec:"RSpec \u6D4B\u8BD5\u76EE\u5F55",docs:"\u6587\u6863\u76EE\u5F55\uFF0C\u5305\u542B\u9879\u76EE\u6587\u6863\u548C\u8BF4\u660E",examples:"\u793A\u4F8B\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4F7F\u7528\u793A\u4F8B",scripts:"\u811A\u672C\u76EE\u5F55\uFF0C\u5305\u542B\u6784\u5EFA\u3001\u90E8\u7F72\u7B49\u811A\u672C",build:"\u6784\u5EFA\u8F93\u51FA\u76EE\u5F55",Gemfile:"RubyGems \u4F9D\u8D56\u914D\u7F6E\u6587\u4EF6"}}async detectVersions(e,t){let n={},r=Ya(e,".ruby-version");if(qa(r))try{let i=Ka(r,"utf-8");n.Ruby=i.trim()}catch{}let s=Ya(e,"Gemfile");if(qa(s))try{let a=Ka(s,"utf-8").match(/ruby\s+['"]([^'"]+)['"]/);a&&!n.Ruby&&(n.Ruby=a[1])}catch{}return n}findEntryPoints(e,t){return this.findEntryPointsByConfig(e,t,{commonEntries:["main.rb","app.rb","bin/rails","bin/rake","bin/console","config.ru","Rakefile","Gemfile"]})}detectCodeStandards(e){let t={RuboCop:[".rubocop.yml",".rubocop.yaml",".rubocop_todo.yml"],RSpec:["spec/spec_helper.rb","spec/rails_helper.rb"],Minitest:["test/test_helper.rb"],EditorConfig:[".editorconfig"],Bundler:["Gemfile","Gemfile.lock"]};return this.detectCodeStandardsByFiles(e,t)}getCommonSourceExtensions(){return[".rb",".gemspec",".rake",".ru",".lock"]}getCommonTestExtensions(){return["_test.rb",".test.rb","test_*.rb","*_test.rb","spec/**/*.rb","test/**/*.rb"]}getCommonConfigFiles(){return["Gemfile","Gemfile.lock",".rubocop.yml",".ruby-version",".ruby-gemset","Rakefile","config.ru",".editorconfig"]}async analyzeDependencies(e,t){return{dependencies:[],conflicts:[],recommendations:[]}}}});import{existsSync as zu,readFileSync as Qa}from"fs";import{resolve as Za}from"path";import{globSync as vs}from"glob";var Yr,ec=C(()=>{Ae();Yr=class extends Q{getLanguageName(){return".NET"}getDirectoryDescriptions(){return{...this.getCommonDirectoryDescriptions(),src:"\u6E90\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4E3B\u8981\u7684 .NET \u4EE3\u7801",app:"\u5E94\u7528\u7A0B\u5E8F\u4EE3\u7801\u76EE\u5F55",bin:"\u7F16\u8BD1\u8F93\u51FA\u76EE\u5F55\uFF0C\u5305\u542B\u7F16\u8BD1\u540E\u7684\u4E8C\u8FDB\u5236\u6587\u4EF6",obj:"\u4E2D\u95F4\u7F16\u8BD1\u8F93\u51FA\u76EE\u5F55",lib:"\u5E93\u6587\u4EF6\u76EE\u5F55",libs:"\u5E93\u6587\u4EF6\u76EE\u5F55",packages:"NuGet \u5305\u76EE\u5F55",nuget:"NuGet \u76F8\u5173\u6587\u4EF6\u76EE\u5F55",config:"\u914D\u7F6E\u6587\u4EF6\u76EE\u5F55",Controllers:"\u63A7\u5236\u5668\u76EE\u5F55\uFF08ASP.NET \u9879\u76EE\uFF09",Models:"\u6570\u636E\u6A21\u578B\u76EE\u5F55\uFF08ASP.NET \u9879\u76EE\uFF09",Views:"\u89C6\u56FE\u6A21\u677F\u76EE\u5F55\uFF08ASP.NET MVC \u9879\u76EE\uFF09",Pages:"Razor Pages \u76EE\u5F55\uFF08ASP.NET \u9879\u76EE\uFF09",wwwroot:"\u9759\u6001\u8D44\u6E90\u76EE\u5F55\uFF08ASP.NET \u9879\u76EE\uFF09",services:"\u4E1A\u52A1\u903B\u8F91\u670D\u52A1\u76EE\u5F55",helpers:"\u8F85\u52A9\u51FD\u6570\u76EE\u5F55",tests:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",test:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",docs:"\u6587\u6863\u76EE\u5F55\uFF0C\u5305\u542B\u9879\u76EE\u6587\u6863\u548C\u8BF4\u660E",examples:"\u793A\u4F8B\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4F7F\u7528\u793A\u4F8B",scripts:"\u811A\u672C\u76EE\u5F55\uFF0C\u5305\u542B\u6784\u5EFA\u3001\u90E8\u7F72\u7B49\u811A\u672C",build:"\u6784\u5EFA\u811A\u672C\u548C\u914D\u7F6E\u76EE\u5F55"}}async detectVersions(e,t){let n={},r=[...vs("*.csproj",{cwd:e}),...vs("*.vbproj",{cwd:e}),...vs("*.fsproj",{cwd:e})];for(let i of r)try{let a=Za(e,i),c=Qa(a,"utf-8"),l=c.match(/<TargetFramework>([^<]+)<\/TargetFramework>/)||c.match(/<TargetFrameworks>([^<]+)<\/TargetFrameworks>/);if(l){n[".NET Framework"]=l[1];break}let u=c.match(/<LangVersion>([^<]+)<\/LangVersion>/);u&&(n["C# Version"]=u[1])}catch{}let s=Za(e,"global.json");if(zu(s))try{let i=Qa(s,"utf-8"),a=JSON.parse(i);a.sdk&&a.sdk.version&&(n[".NET SDK"]=a.sdk.version)}catch{}return n}findEntryPoints(e,t){return this.findEntryPointsByConfig(e,t,{commonEntries:["Program.cs","Startup.cs","App.xaml.cs","MainWindow.xaml.cs","Program.vb","Startup.vb","App.xaml.vb","MainWindow.xaml.vb","Program.fs","Startup.fs"]})}detectCodeStandards(e){let t={StyleCop:[".stylecop","stylecop.json","stylecop.ruleset"],EditorConfig:[".editorconfig"],xUnit:["xunit.runner.json"],NUnit:["nunit.config","nunit3.config"],MSTest:["app.config","web.config"],NuGet:["nuget.config","packages.config"]};return this.detectCodeStandardsByFiles(e,t)}getCommonSourceExtensions(){return[".cs",".vb",".fs",".csproj",".vbproj",".fsproj",".config",".json",".xml"]}getCommonTestExtensions(){return["Test.cs","Tests.cs","Test.vb","Tests.vb","Test.fs","Tests.fs","*Test.csproj","*Tests.csproj"]}getCommonConfigFiles(){return["*.csproj","*.vbproj","*.fsproj","appsettings.json","app.config","web.config","nuget.config","packages.config","global.json",".editorconfig"]}async analyzeDependencies(e,t){return{dependencies:[],conflicts:[],recommendations:[]}}}});var ws,Ue,bs=C(()=>{Oa();ja();_a();Va();za();Ba();Xa();ec();ws=class o{static instance;handlers=new Map;constructor(){this.registerHandlers()}static getInstance(){return o.instance||(o.instance=new o),o.instance}registerHandlers(){[new zr,new Hr,new Jr,new Gr,new Br,new qr,new Kr,new Yr].forEach(t=>{let n=t.getLanguageName();this.handlers.set(n.toLowerCase(),t),this.registerLanguageAliases(n,t)})}registerLanguageAliases(e,t){let n={"javascript/typescript":["javascript","typescript","node.js","nodejs"],java:["java","jdk","jvm"],python:["python","py"],go:["go","golang"],rust:["rust","rs"],php:["php"],ruby:["ruby","rb"],".net":["c#/.net","csharp","dotnet",".net","vb.net","f#"]},r=e.toLowerCase();n[r]&&n[r].forEach(s=>{this.handlers.set(s.toLowerCase(),t)})}getHandler(e){if(!e)return null;let t=e.toLowerCase();return this.handlers.get(t)||null}getSupportedLanguages(){return Array.from(new Set(Array.from(this.handlers.values()).map(e=>e.getLanguageName())))}getDirectoryDescriptions(e){let t=this.getHandler(e);return t?t.getDirectoryDescriptions():{src:"\u6E90\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u6240\u6709\u4E3B\u8981\u7684\u5E94\u7528\u7A0B\u5E8F\u4EE3\u7801",test:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",tests:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",docs:"\u6587\u6863\u76EE\u5F55\uFF0C\u5305\u542B\u9879\u76EE\u6587\u6863\u548C\u8BF4\u660E",examples:"\u793A\u4F8B\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4F7F\u7528\u793A\u4F8B",bin:"\u53EF\u6267\u884C\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B CLI \u547D\u4EE4\u811A\u672C",lib:"\u5E93\u6587\u4EF6\u76EE\u5F55",dist:"\u6784\u5EFA\u8F93\u51FA\u76EE\u5F55",build:"\u6784\u5EFA\u811A\u672C\u548C\u914D\u7F6E\u76EE\u5F55",config:"\u914D\u7F6E\u6587\u4EF6\u76EE\u5F55"}}async detectVersions(e,t,n){let r=this.getHandler(e);return r?await r.detectVersions(t,n):{}}findEntryPoints(e,t,n){let r=this.getHandler(e);return r?r.findEntryPoints(t,n):[]}detectCodeStandards(e,t){let n=this.getHandler(e);return n?n.detectCodeStandards(t):[]}getCommonSourceExtensions(e){let t=this.getHandler(e);return t?t.getCommonSourceExtensions():[]}getCommonTestExtensions(e){let t=this.getHandler(e);return t?t.getCommonTestExtensions():[]}getCommonConfigFiles(e){let t=this.getHandler(e);return t?t.getCommonConfigFiles():[]}getDirectoryDescriptionsForLanguages(e){let t={};return e.forEach(n=>{let r=this.getDirectoryDescriptions(n);Object.assign(t,r)}),t}async detectVersionsForLanguages(e,t,n){let r={};for(let s of e){let i=await this.detectVersions(s,t,n);Object.assign(r,i)}return r}findEntryPointsForLanguages(e,t,n){let r=[];for(let s of e){let i=this.findEntryPoints(s,t,n);r.push(...i)}return[...new Set(r)]}detectCodeStandardsForLanguages(e,t){let n=[];for(let r of e){let s=this.detectCodeStandards(r,t);n.push(...s)}return[...new Set(n)]}async validateCode(e,t,n){n||(n=this.detectLanguageFromFile(e));let r=this.getHandler(n);return r?await r.validateCode(e,t):{valid:!0,message:`No language handler found for: ${n}`}}detectLanguageFromFile(e){let t=e.split(".").pop()?.toLowerCase()||"";return{js:"javascript",jsx:"javascript",ts:"typescript",tsx:"typescript",mjs:"javascript",cjs:"javascript",py:"python",java:"java",go:"go",rs:"rust",php:"php",rb:"ruby",cs:"csharp",vb:"vb.net",fs:"f#"}[t]||"unknown"}},Ue=ws.getInstance()});import{resolve as Hu}from"path";import{existsSync as Ju}from"fs";async function Nn(o){return await tc.execute(o)}var Rt,tc,Un,nc=C(()=>{V();bs();Rt=class extends ${getDefinition(){return{name:"validate",description:`Validate code files for syntax errors, type errors, and code style issues.
438
+ `)}`:"";return l+u}catch(t){return this.formatError("SearchReplace",t)}}formatError(e,t){let n=t instanceof Error?t.message:String(t);return`[${e} Error] ${n}`}},hu=new zn;ds=hu});var me,ut=S(()=>{me=class{getCommonDirectoryDescriptions(){return{src:"\u6E90\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u6240\u6709\u4E3B\u8981\u7684\u5E94\u7528\u7A0B\u5E8F\u4EE3\u7801",test:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",tests:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",docs:"\u6587\u6863\u76EE\u5F55\uFF0C\u5305\u542B\u9879\u76EE\u6587\u6863\u548C\u8BF4\u660E",examples:"\u793A\u4F8B\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4F7F\u7528\u793A\u4F8B",bin:"\u53EF\u6267\u884C\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B CLI \u547D\u4EE4\u811A\u672C",lib:"\u5E93\u6587\u4EF6\u76EE\u5F55",dist:"\u6784\u5EFA\u8F93\u51FA\u76EE\u5F55",build:"\u6784\u5EFA\u811A\u672C\u548C\u914D\u7F6E\u76EE\u5F55",config:"\u914D\u7F6E\u6587\u4EF6\u76EE\u5F55",components:"\u7EC4\u4EF6\u76EE\u5F55",pages:"\u9875\u9762\u76EE\u5F55",public:"\u516C\u5171\u8D44\u6E90\u76EE\u5F55",assets:"\u9759\u6001\u8D44\u6E90\u76EE\u5F55",utils:"\u5DE5\u5177\u51FD\u6570\u76EE\u5F55",helpers:"\u8F85\u52A9\u51FD\u6570\u76EE\u5F55",services:"\u670D\u52A1\u5C42\u76EE\u5F55",models:"\u6570\u636E\u6A21\u578B\u76EE\u5F55",controllers:"\u63A7\u5236\u5668\u76EE\u5F55",routes:"\u8DEF\u7531\u5B9A\u4E49\u76EE\u5F55",middleware:"\u4E2D\u95F4\u4EF6\u76EE\u5F55",plugins:"\u63D2\u4EF6\u76EE\u5F55",hooks:"\u94A9\u5B50\u51FD\u6570\u76EE\u5F55",types:"\u7C7B\u578B\u5B9A\u4E49\u76EE\u5F55",interfaces:"\u63A5\u53E3\u5B9A\u4E49\u76EE\u5F55",schemas:"\u6570\u636E\u7ED3\u6784\u5B9A\u4E49\u76EE\u5F55"}}async findEntryPoints(e,t){return[]}async findEntryPointsByConfig(e,t,n){let r=new Set,{existsSync:o}=await import("fs"),{readFile:i}=await import("fs/promises"),{resolve:a}=await import("path");if(n.commonEntries&&n.commonEntries.forEach(c=>{if(e.includes(c))r.add(c);else if(c.includes("*")){let l=new RegExp(c.replace(/\*/g,"[^/]+").replace(/\/\*\*/g,".+"));e.forEach(u=>{l.test(u)&&r.add(u)})}}),n.configFileChecks)for(let c of n.configFileChecks){let l=a(t,c.filePath);if(o(l))try{let u=await i(l,"utf-8");c.parseFn(u,e).forEach(g=>r.add(g))}catch{}}if(n.contentChecks){for(let c of n.contentChecks)for(let l of e)if(!c.filter||c.filter(l))try{let u=await i(a(t,l),"utf-8");c.pattern.test(u)&&r.add(l)}catch{}}return Array.from(r)}async detectCodeStandards(e){return[]}async detectCodeStandardsByFiles(e,t){let n=[],{existsSync:r}=await import("fs"),{readFile:o}=await import("fs/promises"),{resolve:i}=await import("path");for(let[a,c]of Object.entries(t)){let l=!1;if(Array.isArray(c)){for(let u of c)if(r(i(e,u))){l=!0;break}}else for(let u of c.files){let p=i(e,u);if(r(p))if(c.contentCheck)try{let g=await o(p,"utf-8");if(c.contentCheck(g)){l=!0;break}}catch{}else{l=!0;break}}l&&n.push(a)}return n}async validateCode(e,t){return{valid:!0,message:`No validator available for ${this.getLanguageName()}`}}}});import{existsSync as ba,readFileSync as wd}from"fs";import{resolve as va}from"path";var jo,xu=S(()=>{ut();jo=class extends me{getLanguageName(){return"JavaScript/TypeScript"}getDirectoryDescriptions(){return{...this.getCommonDirectoryDescriptions(),src:"\u6E90\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u6240\u6709\u4E3B\u8981\u7684 JavaScript/TypeScript \u4EE3\u7801",lib:"\u7F16\u8BD1\u540E\u7684\u5E93\u6587\u4EF6\u76EE\u5F55",dist:"\u6784\u5EFA\u8F93\u51FA\u76EE\u5F55\uFF0C\u5305\u542B\u6253\u5305\u540E\u7684\u751F\u4EA7\u4EE3\u7801",public:"\u516C\u5171\u8D44\u6E90\u76EE\u5F55\uFF0C\u5305\u542B\u9759\u6001\u6587\u4EF6",assets:"\u9759\u6001\u8D44\u6E90\u76EE\u5F55\uFF0C\u5305\u542B\u56FE\u7247\u3001\u6837\u5F0F\u7B49",components:"React/Vue \u7EC4\u4EF6\u76EE\u5F55",pages:"\u9875\u9762\u7EC4\u4EF6\u76EE\u5F55",hooks:"React \u94A9\u5B50\u51FD\u6570\u76EE\u5F55",context:"React \u4E0A\u4E0B\u6587\u76EE\u5F55",redux:"Redux \u72B6\u6001\u7BA1\u7406\u76EE\u5F55",store:"\u72B6\u6001\u7BA1\u7406\u76EE\u5F55",actions:"Redux \u52A8\u4F5C\u76EE\u5F55",reducers:"Redux \u5F52\u7EA6\u5668\u76EE\u5F55",slices:"Redux Toolkit \u5207\u7247\u76EE\u5F55",middleware:"\u4E2D\u95F4\u4EF6\u76EE\u5F55",utils:"\u5DE5\u5177\u51FD\u6570\u76EE\u5F55",helpers:"\u8F85\u52A9\u51FD\u6570\u76EE\u5F55",services:"API \u670D\u52A1\u76EE\u5F55",api:"API \u63A5\u53E3\u76EE\u5F55",models:"\u6570\u636E\u6A21\u578B\u76EE\u5F55",types:"TypeScript \u7C7B\u578B\u5B9A\u4E49\u76EE\u5F55",interfaces:"TypeScript \u63A5\u53E3\u5B9A\u4E49\u76EE\u5F55",schemas:"\u6570\u636E\u7ED3\u6784\u5B9A\u4E49\u76EE\u5F55",config:"\u914D\u7F6E\u6587\u4EF6\u76EE\u5F55",scripts:"\u811A\u672C\u76EE\u5F55\uFF0C\u5305\u542B\u6784\u5EFA\u3001\u6D4B\u8BD5\u7B49\u811A\u672C",test:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",tests:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",__tests__:"Jest \u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55",spec:"Jasmine/Mocha \u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55",docs:"\u6587\u6863\u76EE\u5F55\uFF0C\u5305\u542B\u9879\u76EE\u6587\u6863\u548C\u8BF4\u660E",examples:"\u793A\u4F8B\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4F7F\u7528\u793A\u4F8B",bin:"\u53EF\u6267\u884C\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B CLI \u547D\u4EE4\u811A\u672C",build:"\u6784\u5EFA\u811A\u672C\u548C\u914D\u7F6E\u76EE\u5F55"}}async detectVersions(e,t){let n={},r=va(e,"package.json");if(ba(r))try{let o=wd(r,"utf-8"),i=JSON.parse(o);i.engines&&(i.engines.node&&(n["Node.js"]=i.engines.node),i.engines.npm&&(n.npm=i.engines.npm),i.engines.yarn&&(n.yarn=i.engines.yarn),i.engines.pnpm&&(n.pnpm=i.engines.pnpm))}catch{}return n}async findEntryPoints(e,t){return this.findEntryPointsByConfig(e,t,{commonEntries:["index.js","index.ts","index.mjs","index.cjs","app.js","app.ts","main.js","main.ts","server.js","server.ts","src/index.js","src/index.ts","src/main.js","src/main.ts","src/app.js","src/app.ts","next.config.js","vite.config.js","webpack.config.js","rollup.config.js"],configFileChecks:[{filePath:"package.json",parseFn:(n,r)=>{let o=[],i=JSON.parse(n);return i.main&&o.push(i.main),i.bin&&(typeof i.bin=="string"?o.push(i.bin):o.push(...Object.values(i.bin))),o}}]})}async detectCodeStandards(e){let t={ESLint:[".eslintrc.js",".eslintrc.json",".eslintrc.yml",".eslintrc.yaml",".eslintrc"],Prettier:[".prettierrc",".prettierrc.json",".prettierrc.yml",".prettierrc.yaml",".prettierrc.js","prettier.config.js"],EditorConfig:[".editorconfig"],TypeScript:["tsconfig.json"],Flow:[".flowconfig"],Jest:["jest.config.js","jest.config.ts","jest.config.json"],Vitest:["vitest.config.js","vitest.config.ts"],Mocha:["mocha.opts",".mocharc.js"],Jasmine:["jasmine.json"]};return this.detectCodeStandardsByFiles(e,t)}getCommonSourceExtensions(){return[".js",".mjs",".cjs",".jsx",".ts",".tsx",".vue",".svelte",".astro"]}getCommonTestExtensions(){return[".test.js",".test.ts",".test.jsx",".test.tsx",".spec.js",".spec.ts",".spec.jsx",".spec.tsx"]}getCommonConfigFiles(){return["package.json","tsconfig.json","tsconfig.node.json","jsconfig.json",".eslintrc.js",".eslintrc.json",".prettierrc",".prettierrc.json",".editorconfig","vite.config.js","vite.config.ts","webpack.config.js","webpack.config.ts","rollup.config.js","rollup.config.ts","next.config.js","next.config.mjs","nuxt.config.js","nuxt.config.ts","astro.config.mjs","astro.config.ts"]}async analyzeDependencies(e,t){return{dependencies:[],conflicts:[],recommendations:[]}}async validateCode(e,t){let{execSync:n}=await import("child_process"),{extname:r}=await import("path"),o=r(e);return o===".ts"||o===".tsx"?await this.validateTypeScript(e,t,n):await this.validateJavaScript(e,t,n)}async validateTypeScript(e,t,n){try{let r=va(t,"tsconfig.json");if(!ba(r))return{valid:!0,message:"No tsconfig.json found, skipping TypeScript validation"};let o=n(`npx tsc --noEmit --pretty false --skipLibCheck --noResolve "${e}"`,{encoding:"utf-8",stdio:"pipe",cwd:t,timeout:3e4});return{valid:!0,message:"TypeScript validation passed"}}catch(r){let o=r.stderr||r.stdout||r.message,i=this.parseTypeScriptErrors(o);return i.length===0?{valid:!1,message:`TypeScript validation failed:
439
+ ${o}`}:{valid:!1,message:`TypeScript validation failed with ${i.length} error(s)`,errors:i}}}async validateJavaScript(e,t,n){try{if(![".eslintrc.js",".eslintrc.json",".eslintrc.yml",".eslintrc.yaml",".eslintrc"].some(c=>ba(va(t,c))))return{valid:!0,message:"No ESLint configuration found, skipping JavaScript validation"};let i=n(`npx eslint --format json ${e}`,{encoding:"utf-8",stdio:"pipe",cwd:t,timeout:3e4}),a=JSON.parse(i);return a.length===0||a[0].errorCount===0?{valid:!0,message:"ESLint validation passed",warnings:a[0]?.warningCount>0?this.parseEslintMessages(a[0].messages,"warning"):void 0}:{valid:!1,message:`ESLint validation failed with ${a[0].errorCount} error(s)`,errors:this.parseEslintMessages(a[0].messages,"error"),warnings:this.parseEslintMessages(a[0].messages,"warning")}}catch(r){if(r.message?.includes("not found")||r.code==="ENOENT")return{valid:!0,message:"ESLint not available, skipping JavaScript validation"};try{let o=JSON.parse(r.stdout||"[]");if(o.length>0&&o[0].errorCount>0)return{valid:!1,message:`ESLint validation failed with ${o[0].errorCount} error(s)`,errors:this.parseEslintMessages(o[0].messages,"error"),warnings:this.parseEslintMessages(o[0].messages,"warning")}}catch{}return{valid:!1,message:`JavaScript validation failed: ${r.message}`}}}parseTypeScriptErrors(e){let t=[],n=e.split(`
440
+ `);for(let r of n){let o=r.match(/\((\d+),(\d+)\):\s+(error|warning)\s+TS(\d+):\s+(.+)/);o&&t.push({line:parseInt(o[1]),column:parseInt(o[2]),severity:o[3],code:`TS${o[4]}`,message:o[5]})}return t}parseEslintMessages(e,t){return e.filter(n=>n.severity===(t==="error"?2:1)).map(n=>({line:n.line,column:n.column,severity:t,code:n.ruleId,message:n.message}))}}});import{existsSync as Vn,writeFileSync as bd,mkdirSync as vd}from"fs";import{resolve as Ta,dirname as Td}from"path";var Do,Su=S(()=>{ut();Do=class extends me{getLanguageName(){return"Java"}getDirectoryDescriptions(){return{...this.getCommonDirectoryDescriptions(),src:"\u6E90\u4EE3\u7801\u6839\u76EE\u5F55","src/main/java":"\u4E3B\u6E90\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u751F\u4EA7\u4EE3\u7801","src/main/resources":"\u4E3B\u8D44\u6E90\u76EE\u5F55\uFF0C\u5305\u542B\u914D\u7F6E\u6587\u4EF6\u548C\u9759\u6001\u8D44\u6E90","src/test/java":"\u6D4B\u8BD5\u6E90\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5","src/test/resources":"\u6D4B\u8BD5\u8D44\u6E90\u76EE\u5F55\uFF0C\u5305\u542B\u6D4B\u8BD5\u914D\u7F6E\u6587\u4EF6",target:"\u6784\u5EFA\u8F93\u51FA\u76EE\u5F55\uFF0C\u5305\u542B\u7F16\u8BD1\u540E\u7684\u7C7B\u6587\u4EF6\u548C\u6253\u5305\u4EA7\u7269",lib:"\u5916\u90E8\u4F9D\u8D56\u5E93\u76EE\u5F55",libs:"\u5916\u90E8\u4F9D\u8D56\u5E93\u76EE\u5F55",build:"\u6784\u5EFA\u811A\u672C\u548C\u914D\u7F6E\u76EE\u5F55",gradle:"Gradle \u6784\u5EFA\u7CFB\u7EDF\u76EE\u5F55",maven:"Maven \u6784\u5EFA\u7CFB\u7EDF\u76EE\u5F55",docs:"\u6587\u6863\u76EE\u5F55\uFF0C\u5305\u542B\u9879\u76EE\u6587\u6863\u548C\u8BF4\u660E",examples:"\u793A\u4F8B\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4F7F\u7528\u793A\u4F8B",bin:"\u53EF\u6267\u884C\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u7F16\u8BD1\u540E\u7684\u4E8C\u8FDB\u5236\u6587\u4EF6",config:"\u914D\u7F6E\u6587\u4EF6\u76EE\u5F55",scripts:"\u811A\u672C\u76EE\u5F55\uFF0C\u5305\u542B\u6784\u5EFA\u3001\u90E8\u7F72\u7B49\u811A\u672C"}}async detectVersions(e,t){let n={},{existsSync:r}=await import("fs"),{readFile:o}=await import("fs/promises"),{resolve:i}=await import("path"),a=i(e,"pom.xml");if(r(a))try{let u=await o(a,"utf-8"),p=u.match(/<java\.version>([^<]+)<\/java\.version>/)||u.match(/<maven\.compiler\.source>([^<]+)<\/maven\.compiler\.source>/);p&&(n.Java=p[1])}catch{}let c=i(e,"build.gradle"),l=i(e,"build.gradle.kts");if(r(c))try{let u=await o(c,"utf-8"),p=u.match(/sourceCompatibility\s*=\s*['"]?([^'"\\s]+)['"]?/)||u.match(/targetCompatibility\s*=\s*['"]?([^'"\\s]+)['"]?/);p&&(n.Java=p[1])}catch{}else if(r(l))try{let u=await o(l,"utf-8"),p=u.match(/sourceCompatibility\s*=\s*JavaVersion\.VERSION_(\d+_\d+)/)||u.match(/targetCompatibility\s*=\s*JavaVersion\.VERSION_(\d+_\d+)/);p&&(n.Java=p[1].replace("_","."))}catch{}return n}async findEntryPoints(e,t){return this.findEntryPointsByConfig(e,t,{commonEntries:["src/main/java/**/Main.java","src/main/java/**/Application.java","src/main/java/**/App.java","src/main/java/**/Bootstrap.java","src/main/java/**/Launcher.java"],contentChecks:[{pattern:/public static void main\(String\[\] args\)/,filter:n=>n.endsWith(".java")}]})}async detectCodeStandards(e){let t={Checkstyle:["checkstyle.xml","google_checks.xml","sun_checks.xml"],PMD:["pmd.xml",".pmd"],FindBugs:["findbugs.xml",".findbugs"],SpotBugs:["spotbugs.xml",".spotbugs"],SonarQube:["sonar-project.properties"],EditorConfig:[".editorconfig"],Maven:["pom.xml"],Gradle:["build.gradle","build.gradle.kts"]};return await this.detectCodeStandardsByFiles(e,t)}getCommonSourceExtensions(){return[".java",".class",".jar",".war",".ear"]}getCommonTestExtensions(){return["Test.java","Tests.java"]}getCommonConfigFiles(){return["pom.xml","build.gradle","build.gradle.kts","settings.gradle","gradle.properties","checkstyle.xml","pmd.xml","spotbugs.xml","sonar-project.properties",".editorconfig"]}async analyzeDependencies(e,t){let n={dependencies:[],conflicts:[],recommendations:[]};try{let r=Ta(e,"pom.xml"),o=Ta(e,"build.gradle"),i=Ta(e,"build.gradle.kts");if(!Vn(r)&&!Vn(o)&&!Vn(i))return n;Vn(r)?await this.analyzeMavenDependencies(r,n):Vn(o)?await this.analyzeGradleDependencies(o,n):Vn(i)&&await this.analyzeGradleDependencies(i,n),this.detectDependencyConflicts(n),this.generateRecommendations(n)}catch(r){console.error("\u4F9D\u8D56\u5206\u6790\u5931\u8D25:",r)}return n}async analyzeMavenDependencies(e,t){let{readFile:n}=await import("fs/promises"),r=await n(e,"utf-8"),o=await import("xml2js");return new Promise((i,a)=>{o.parseString(r,{explicitArray:!1},(c,l)=>{if(c){a(c);return}let{project:u}=l;if(!u){i();return}let p=u.dependencies?.dependency;p&&(Array.isArray(p)?p:[p]).forEach(m=>{t.dependencies.push({groupId:m.groupId,artifactId:m.artifactId,version:m.version||"unknown",scope:m.scope||"compile",type:m.type||"jar"})}),i()})})}async analyzeGradleDependencies(e,t){let{readFile:n}=await import("fs/promises"),r=await n(e,"utf-8");[/(implementation|compile|api|compileOnly|runtimeOnly|testImplementation|testCompile|testApi|testCompileOnly|testRuntimeOnly)\s*['"]([^:'"]+):([^:'"]+):([^:'"]+)['"]/gms,/(implementation|compile|api|compileOnly|runtimeOnly|testImplementation|testCompile|testApi|testCompileOnly|testRuntimeOnly)\s*['"]([^:'"]+):([^:'"]+)['"]/gms,/(implementation|compile|api|compileOnly|runtimeOnly|testImplementation|testCompile|testApi|testCompileOnly|testRuntimeOnly)\s*\(\s*group\s*:\s*['"]([^'"]+)['"],\s*name\s*:\s*['"]([^'"]+)['"],\s*version\s*:\s*['"]([^'"]+)['"][^)]*\)/gms,/(implementation|compile|api|compileOnly|runtimeOnly|testImplementation|testCompile|testApi|testCompileOnly|testRuntimeOnly)\s*\(\s*["']([^"']+):([^"']+):([^"']+)["']\s*\)/gms].forEach(i=>{let a;for(;(a=i.exec(r))!==null;){let c,l,u,p;if(a.length===5)[,c,l,u,p]=a;else if(a.length===4)[,c,l,u]=a,p="managed";else continue;t.dependencies.push({groupId:l,artifactId:u,version:p,scope:c.toLowerCase(),type:"jar"})}})}detectDependencyConflicts(e){let t=new Map;e.dependencies.forEach(n=>{if(n.groupId&&n.artifactId){let r=`${n.groupId}:${n.artifactId}`;t.has(r)||t.set(r,new Set),t.get(r)?.add(n.version)}}),t.forEach((n,r)=>{if(n.size>1){let[o,i]=r.split(":");e.conflicts.push({groupId:o,artifactId:i,versions:Array.from(n),severity:this.calculateConflictSeverity(Array.from(n))})}})}calculateConflictSeverity(e){let t=e.map(r=>{let o=r.match(/^(\d+)/);return o?parseInt(o[1]):0});return new Set(t).size>1?"high":e.length>2?"medium":"low"}generateRecommendations(e){let t=[];e.conflicts.length>0&&t.push(`${e.conflicts.length} \u4E2A\u4F9D\u8D56\u5B58\u5728\u7248\u672C\u51B2\u7A81\uFF0C\u5EFA\u8BAE\u7EDF\u4E00\u7248\u672C`),e.dependencies.some(o=>o.groupId==="org.springframework.boot")&&t.push("\u9879\u76EE\u4F7F\u7528Spring Boot\uFF0C\u5EFA\u8BAE\u4F7F\u7528Spring Dependency Management\u63D2\u4EF6\u7BA1\u7406\u4F9D\u8D56\u7248\u672C");let r=this.detectJavaVersion(e);if(r){let o=parseInt(r);o<11?t.push("Java\u7248\u672C\u8F83\u65E7\uFF0C\u5EFA\u8BAE\u5347\u7EA7\u5230Java 11\u6216\u66F4\u9AD8\u7248\u672C"):o>=17&&t.push("\u4F7F\u7528\u73B0\u4EE3Java\u7248\u672C\uFF0C\u53EF\u4EE5\u4EAB\u53D7\u6700\u65B0\u7279\u6027")}e.recommendations=t}detectJavaVersion(e){}saveDependencyAnalysis(e,t){try{let n=`${t}/.nium/java-dependency-analysis.json`;vd(Td(n),{recursive:!0}),bd(n,JSON.stringify({scanTime:new Date().toISOString(),dependencies:e.dependencies,conflicts:e.conflicts,recommendations:e.recommendations},null,2))}catch(n){console.error("\u4FDD\u5B58\u4F9D\u8D56\u5206\u6790\u7ED3\u679C\u5931\u8D25:",n)}}}});import{existsSync as fs,readFileSync as Pa}from"fs";import{resolve as hs}from"path";var Fo,Cu=S(()=>{ut();Fo=class extends me{getLanguageName(){return"Python"}getDirectoryDescriptions(){return{...this.getCommonDirectoryDescriptions(),src:"\u6E90\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4E3B\u8981\u7684 Python \u4EE3\u7801",app:"\u5E94\u7528\u7A0B\u5E8F\u4EE3\u7801\u76EE\u5F55",main:"\u4E3B\u7A0B\u5E8F\u4EE3\u7801\u76EE\u5F55",lib:"\u5E93\u6587\u4EF6\u76EE\u5F55",libs:"\u5E93\u6587\u4EF6\u76EE\u5F55",tests:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",test:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",__pycache__:"Python \u7F16\u8BD1\u7F13\u5B58\u76EE\u5F55",venv:"\u865A\u62DF\u73AF\u5883\u76EE\u5F55",".venv":"\u865A\u62DF\u73AF\u5883\u76EE\u5F55",env:"\u73AF\u5883\u53D8\u91CF\u914D\u7F6E\u76EE\u5F55",config:"\u914D\u7F6E\u6587\u4EF6\u76EE\u5F55",data:"\u6570\u636E\u6587\u4EF6\u76EE\u5F55",docs:"\u6587\u6863\u76EE\u5F55\uFF0C\u5305\u542B\u9879\u76EE\u6587\u6863\u548C\u8BF4\u660E",examples:"\u793A\u4F8B\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4F7F\u7528\u793A\u4F8B",scripts:"\u811A\u672C\u76EE\u5F55\uFF0C\u5305\u542B\u6784\u5EFA\u3001\u90E8\u7F72\u7B49\u811A\u672C",bin:"\u53EF\u6267\u884C\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B CLI \u547D\u4EE4\u811A\u672C",build:"\u6784\u5EFA\u8F93\u51FA\u76EE\u5F55",dist:"\u6253\u5305\u8F93\u51FA\u76EE\u5F55\uFF0C\u5305\u542B\u53D1\u5E03\u7684\u5305\u6587\u4EF6",requirements:"\u4F9D\u8D56\u7BA1\u7406\u76EE\u5F55"}}async detectVersions(e,t){let n={},r=hs(e,".python-version");if(fs(r))try{let a=Pa(r,"utf-8");n.Python=a.trim()}catch{}let o=hs(e,"pyproject.toml");if(fs(o))try{let c=Pa(o,"utf-8").match(/python\s*=\s*['"]([^'"]+)['"]/);c&&(n.Python=c[1])}catch{}let i=hs(e,"setup.py");if(fs(i))try{let c=Pa(i,"utf-8").match(/python_requires\s*=\s*['"]([^'"]+)['"]/);c&&(n.Python=c[1])}catch{}return n}async findEntryPoints(e,t){return this.findEntryPointsByConfig(e,t,{commonEntries:["main.py","__main__.py","app.py","run.py","manage.py","server.py","cli.py","setup.py","src/main.py","src/__main__.py","src/app.py"],configFileChecks:[{filePath:"setup.py",parseFn:(n,r)=>{let o=[],i=n.match(/entry_points\s*=\s*\{[^}]+\}/s);if(i){let c=i[0].match(/console_scripts\s*:\s*\[([^\]]+)\]/s);if(c){let u=c[1].match(/([^=]+)\s*=\s*([^,]+)/g);u&&u.forEach(p=>{let[g,m]=p.split("=").map(f=>f.trim()),d=m.replace(/\./g,"/").replace(":","/")+".py";o.push(d)})}}return o}}]})}async detectCodeStandards(e){let t={Black:{files:["pyproject.toml","setup.cfg"],contentCheck:n=>n.includes("[tool.black]")},Pylint:[".pylintrc","pylintrc","setup.cfg"],Flake8:[".flake8","flake8.cfg","setup.cfg"],Mypy:["mypy.ini",".mypy.ini","setup.cfg","pyproject.toml"],isort:[".isort.cfg","setup.cfg","pyproject.toml"],Bandit:[".bandit","bandit.yml"],Pytest:["pytest.ini","setup.cfg","conftest.py"],EditorConfig:[".editorconfig"]};return this.detectCodeStandardsByFiles(e,t)}getCommonSourceExtensions(){return[".py",".pyc",".pyo",".pyd",".pyx",".pxd",".pxi"]}getCommonTestExtensions(){return[".test.py",".spec.py","_test.py","test_*.py","*_test.py"]}getCommonConfigFiles(){return["pyproject.toml","setup.py","setup.cfg","requirements.txt","requirements-dev.txt","Pipfile","Pipfile.lock","poetry.lock",".pylintrc",".flake8","mypy.ini",".isort.cfg","pytest.ini","conftest.py",".editorconfig"]}async analyzeDependencies(e,t){return{dependencies:[],conflicts:[],recommendations:[]}}async validateCode(e,t){let{execSync:n}=await import("child_process"),r=await Promise.all([this.validatePythonSyntax(e,t,n),this.validateWithFlake8(e,t,n),this.validateWithMypy(e,t,n)]),o=r.find(a=>!a.valid);if(o)return o;let i=r.flatMap(a=>a.warnings||[]).filter((a,c,l)=>l.findIndex(u=>u.message===a.message)===c);return{valid:!0,message:"Python validation passed",warnings:i.length>0?i:void 0}}async validatePythonSyntax(e,t,n){try{let r="python3";try{n("python3 --version",{stdio:"pipe"})}catch{r="python"}return n(`${r} -m py_compile "${e}"`,{encoding:"utf-8",stdio:"pipe",cwd:t,timeout:1e4}),{valid:!0,message:"Python syntax check passed"}}catch(r){if(r.message?.includes("not found")||r.message?.includes("not recognized")||r.code==="ENOENT"||r.message?.includes("Command failed"))return{valid:!0,message:"Python not available, skipping validation"};let o=r.stderr||r.stdout||r.message,i=this.parsePythonSyntaxErrors(o);return{valid:!1,message:"Python syntax errors found",errors:i.length>0?i:[{severity:"error",message:o}]}}}async validateWithFlake8(e,t,n){try{if(![".flake8","setup.cfg","tox.ini"].some(a=>fs(hs(t,a))))return{valid:!0,message:"No Flake8 configuration found, skipping"};let i="python3";try{n("python3 --version",{stdio:"pipe"})}catch{i="python"}return n(`${i} -m flake8 --format=json "${e}"`,{encoding:"utf-8",stdio:"pipe",cwd:t,timeout:15e3}),{valid:!0,message:"Flake8 validation passed"}}catch(r){if(r.message?.includes("No module named")||r.code==="ENOENT")return{valid:!0,message:"Flake8 not available, skipping"};let o=r.stdout||r.stderr||"",i=this.parseFlake8Errors(o);return i.length===0?{valid:!0,message:"Flake8 validation completed"}:{valid:!1,message:`Flake8 found ${i.length} issue(s)`,errors:i.filter(a=>a.severity==="error"),warnings:i.filter(a=>a.severity==="warning")}}}async validateWithMypy(e,t,n){try{if(!["mypy.ini",".mypy.ini","setup.cfg","pyproject.toml"].some(a=>fs(hs(t,a))))return{valid:!0,message:"No Mypy configuration found, skipping"};let i="python3";try{n("python3 --version",{stdio:"pipe"})}catch{i="python"}return n(`${i} -m mypy --show-column-numbers "${e}"`,{encoding:"utf-8",stdio:"pipe",cwd:t,timeout:2e4}),{valid:!0,message:"Mypy type checking passed"}}catch(r){if(r.message?.includes("No module named")||r.code==="ENOENT")return{valid:!0,message:"Mypy not available, skipping"};let o=r.stdout||r.stderr||"",i=this.parseMypyErrors(o);return i.length===0?{valid:!0,message:"Mypy validation completed"}:{valid:!1,message:`Mypy found ${i.length} type error(s)`,errors:i}}}parsePythonSyntaxErrors(e){let t=[],n=e.split(`
441
+ `);for(let r of n){let o=r.match(/File "([^"]+)", line (\d+)/);if(o){let i=n[n.indexOf(r)+1];t.push({line:parseInt(o[2]),severity:"error",message:i?.trim()||"Syntax error"})}}return t}parseFlake8Errors(e){let t=[],n=e.split(`
442
+ `);for(let r of n){let o=r.match(/([^:]+):(\d+):(\d+):\s+([A-Z]\d+)\s+(.+)/);if(o){let i=o[4],a=i.startsWith("E")||i.startsWith("F")?"error":"warning";t.push({line:parseInt(o[2]),column:parseInt(o[3]),severity:a,code:i,message:o[5]})}}return t}parseMypyErrors(e){let t=[],n=e.split(`
443
+ `);for(let r of n){let o=r.match(/([^:]+):(\d+):(\d+):\s+(error|warning|note):\s+(.+)/);if(o){let i=o[4]==="error"?"error":o[4]==="warning"?"warning":"info";t.push({line:parseInt(o[2]),column:parseInt(o[3]),severity:i,message:o[5]})}}return t}}});import{existsSync as wu,readFileSync as bu}from"fs";import{resolve as vu}from"path";var Oo,Tu=S(()=>{ut();Oo=class extends me{getLanguageName(){return"Go"}getDirectoryDescriptions(){return{...this.getCommonDirectoryDescriptions(),src:"\u6E90\u4EE3\u7801\u76EE\u5F55\uFF08\u4F20\u7EDF Go \u9879\u76EE\u7ED3\u6784\uFF09",cmd:"\u547D\u4EE4\u884C\u5DE5\u5177\u76EE\u5F55\uFF0C\u5305\u542B\u53EF\u6267\u884C\u7A0B\u5E8F\u7684\u5165\u53E3\u70B9",internal:"\u5185\u90E8\u5305\u76EE\u5F55\uFF0C\u4EC5\u672C\u9879\u76EE\u53EF\u4F7F\u7528",pkg:"\u53EF\u5BFC\u51FA\u5305\u76EE\u5F55\uFF0C\u4F9B\u5176\u4ED6\u9879\u76EE\u4F7F\u7528",api:"API \u5B9A\u4E49\u76EE\u5F55",web:"Web \u5E94\u7528\u76F8\u5173\u4EE3\u7801\u76EE\u5F55",models:"\u6570\u636E\u6A21\u578B\u76EE\u5F55",services:"\u4E1A\u52A1\u903B\u8F91\u670D\u52A1\u76EE\u5F55",handlers:"\u8BF7\u6C42\u5904\u7406\u5668\u76EE\u5F55",middleware:"\u4E2D\u95F4\u4EF6\u76EE\u5F55",config:"\u914D\u7F6E\u6587\u4EF6\u76EE\u5F55",docs:"\u6587\u6863\u76EE\u5F55\uFF0C\u5305\u542B\u9879\u76EE\u6587\u6863\u548C\u8BF4\u660E",examples:"\u793A\u4F8B\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4F7F\u7528\u793A\u4F8B",scripts:"\u811A\u672C\u76EE\u5F55\uFF0C\u5305\u542B\u6784\u5EFA\u3001\u90E8\u7F72\u7B49\u811A\u672C",test:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",tests:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",vendor:"\u7B2C\u4E09\u65B9\u4F9D\u8D56\u5E93\u76EE\u5F55",bin:"\u53EF\u6267\u884C\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u7F16\u8BD1\u540E\u7684\u4E8C\u8FDB\u5236\u6587\u4EF6",build:"\u6784\u5EFA\u8F93\u51FA\u76EE\u5F55"}}async detectVersions(e,t){let n={},r=vu(e,"go.mod");if(wu(r))try{let a=bu(r,"utf-8").match(/^go\s+(\d+\.\d+)/m);a&&(n.Go=a[1])}catch{}let o=vu(e,"go.sum");if(wu(o))try{let a=bu(o,"utf-8").match(/^golang\.org\/x\/sys\/v\d+\/[^\s]+\s+go(\d+\.\d+)/);a&&!n.Go&&(n.Go=a[1])}catch{}return n}async findEntryPoints(e,t){return this.findEntryPointsByConfig(e,t,{commonEntries:["main.go","cmd/main.go","cmd/app/main.go","cmd/server/main.go","cmd/cli/main.go","src/main.go"],contentChecks:[{pattern:/func main\(\)/,filter:n=>n.endsWith(".go")}]})}async detectCodeStandards(e){let t={GoFmt:[".gofmt"],GoLint:[".golint"],"GolangCI-Lint":[".golangci.yml",".golangci.yaml"],EditorConfig:[".editorconfig"],GoMod:["go.mod"],GoSum:["go.sum"]};return this.detectCodeStandardsByFiles(e,t)}getCommonSourceExtensions(){return[".go",".mod",".sum"]}getCommonTestExtensions(){return["_test.go",".test.go"]}getCommonConfigFiles(){return["go.mod","go.sum",".golangci.yml",".golangci.yaml",".editorconfig","Makefile"]}async analyzeDependencies(e,t){return{dependencies:[],conflicts:[],recommendations:[]}}}});import{existsSync as Pd,readFileSync as kd}from"fs";import{resolve as Ed}from"path";var No,Pu=S(()=>{ut();No=class extends me{getLanguageName(){return"Rust"}getDirectoryDescriptions(){return{...this.getCommonDirectoryDescriptions(),src:"\u6E90\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4E3B\u8981\u7684 Rust \u4EE3\u7801","src/bin":"\u4E8C\u8FDB\u5236\u53EF\u6267\u884C\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u591A\u4E2A\u53EF\u6267\u884C\u7A0B\u5E8F","src/lib.rs":"\u5E93\u9879\u76EE\u7684\u4E3B\u5165\u53E3\u6587\u4EF6","src/main.rs":"\u4E8C\u8FDB\u5236\u9879\u76EE\u7684\u4E3B\u5165\u53E3\u6587\u4EF6",target:"\u6784\u5EFA\u8F93\u51FA\u76EE\u5F55\uFF0C\u5305\u542B\u7F16\u8BD1\u540E\u7684\u4E8C\u8FDB\u5236\u6587\u4EF6\u548C\u4F9D\u8D56",tests:"\u96C6\u6210\u6D4B\u8BD5\u76EE\u5F55\uFF0C\u5305\u542B\u96C6\u6210\u6D4B\u8BD5\u4EE3\u7801",examples:"\u793A\u4F8B\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4F7F\u7528\u793A\u4F8B",benches:"\u57FA\u51C6\u6D4B\u8BD5\u76EE\u5F55\uFF0C\u5305\u542B\u6027\u80FD\u6D4B\u8BD5\u4EE3\u7801",docs:"\u6587\u6863\u76EE\u5F55\uFF0C\u5305\u542B\u9879\u76EE\u6587\u6863\u548C\u8BF4\u660E",scripts:"\u811A\u672C\u76EE\u5F55\uFF0C\u5305\u542B\u6784\u5EFA\u3001\u90E8\u7F72\u7B49\u811A\u672C",".cargo":"Cargo \u914D\u7F6E\u76EE\u5F55",vendor:"\u7B2C\u4E09\u65B9\u4F9D\u8D56\u5E93\u76EE\u5F55",config:"\u914D\u7F6E\u6587\u4EF6\u76EE\u5F55"}}async detectVersions(e,t){let n={},r=Ed(e,"Cargo.toml");if(Pd(r))try{let i=kd(r,"utf-8").match(/rust-version\s*=\s*['"]([^'"]+)['"]/);i&&(n.Rust=i[1])}catch{}return n}async findEntryPoints(e,t){return this.findEntryPointsByConfig(e,t,{commonEntries:["src/main.rs","src/lib.rs","src/bin/main.rs","src/bin/*.rs"]})}async detectCodeStandards(e){let t={Rustfmt:["rustfmt.toml",".rustfmt.toml"],Clippy:["clippy.toml",".clippy.toml"],EditorConfig:[".editorconfig"],Cargo:["Cargo.toml","Cargo.lock"]};return this.detectCodeStandardsByFiles(e,t)}getCommonSourceExtensions(){return[".rs",".toml",".lock"]}getCommonTestExtensions(){return["_test.rs",".test.rs","tests/*.rs"]}getCommonConfigFiles(){return["Cargo.toml","Cargo.lock","rustfmt.toml","clippy.toml",".editorconfig","Makefile"]}async analyzeDependencies(e,t){return{dependencies:[],conflicts:[],recommendations:[]}}}});import{existsSync as ku,readFileSync as Eu}from"fs";import{resolve as $u}from"path";var _o,Iu=S(()=>{ut();_o=class extends me{getLanguageName(){return"PHP"}getDirectoryDescriptions(){return{...this.getCommonDirectoryDescriptions(),src:"\u6E90\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4E3B\u8981\u7684 PHP \u4EE3\u7801",app:"\u5E94\u7528\u7A0B\u5E8F\u4EE3\u7801\u76EE\u5F55",public:"\u516C\u5171\u8BBF\u95EE\u76EE\u5F55\uFF0C\u5305\u542B\u5165\u53E3\u6587\u4EF6\u548C\u9759\u6001\u8D44\u6E90","index.php":"\u7F51\u7AD9\u5165\u53E3\u6587\u4EF6",lib:"\u5E93\u6587\u4EF6\u76EE\u5F55",libs:"\u5E93\u6587\u4EF6\u76EE\u5F55",vendor:"Composer \u4F9D\u8D56\u5E93\u76EE\u5F55",composer:"Composer \u76F8\u5173\u6587\u4EF6\u76EE\u5F55",config:"\u914D\u7F6E\u6587\u4EF6\u76EE\u5F55",controllers:"\u63A7\u5236\u5668\u76EE\u5F55",models:"\u6570\u636E\u6A21\u578B\u76EE\u5F55",views:"\u89C6\u56FE\u6A21\u677F\u76EE\u5F55",routes:"\u8DEF\u7531\u5B9A\u4E49\u76EE\u5F55",middleware:"\u4E2D\u95F4\u4EF6\u76EE\u5F55",services:"\u4E1A\u52A1\u903B\u8F91\u670D\u52A1\u76EE\u5F55",helpers:"\u8F85\u52A9\u51FD\u6570\u76EE\u5F55",tests:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",test:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",docs:"\u6587\u6863\u76EE\u5F55\uFF0C\u5305\u542B\u9879\u76EE\u6587\u6863\u548C\u8BF4\u660E",examples:"\u793A\u4F8B\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4F7F\u7528\u793A\u4F8B",scripts:"\u811A\u672C\u76EE\u5F55\uFF0C\u5305\u542B\u6784\u5EFA\u3001\u90E8\u7F72\u7B49\u811A\u672C",bin:"\u53EF\u6267\u884C\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B CLI \u547D\u4EE4\u811A\u672C",build:"\u6784\u5EFA\u8F93\u51FA\u76EE\u5F55"}}async detectVersions(e,t){let n={},r=$u(e,"composer.json");if(ku(r))try{let i=Eu(r,"utf-8"),a=JSON.parse(i);a.require&&a.require.php&&(n.PHP=a.require.php)}catch{}let o=$u(e,".php-version");if(ku(o))try{let i=Eu(o,"utf-8");n.PHP=i.trim()}catch{}return n}async findEntryPoints(e,t){return this.findEntryPointsByConfig(e,t,{commonEntries:["index.php","public/index.php","app/index.php","src/index.php","cli.php","artisan","bin/console","composer.json"]})}async detectCodeStandards(e){let t={PHP_CodeSniffer:["phpcs.xml","phpcs.xml.dist",".phpcs.xml",".phpcs.xml.dist"],PHPStan:["phpstan.neon","phpstan.neon.dist","phpstan.yml","phpstan.yml.dist"],Psalm:["psalm.xml","psalm.xml.dist","psalm.yml","psalm.yml.dist"],"PHP-CS-Fixer":[".php-cs-fixer.php",".php-cs-fixer.dist.php"],EditorConfig:[".editorconfig"],PHPUnit:["phpunit.xml","phpunit.xml.dist"],Composer:["composer.json","composer.lock"]};return this.detectCodeStandardsByFiles(e,t)}getCommonSourceExtensions(){return[".php",".phtml",".phar",".json",".lock"]}getCommonTestExtensions(){return[".test.php",".spec.php","Test.php","Tests.php","tests/*.php"]}getCommonConfigFiles(){return["composer.json","composer.lock","phpcs.xml","phpstan.neon","psalm.xml",".php-cs-fixer.php","phpunit.xml",".editorconfig",".php-version"]}async analyzeDependencies(e,t){return{dependencies:[],conflicts:[],recommendations:[]}}}});import{existsSync as Mu,readFileSync as Au}from"fs";import{resolve as Ru}from"path";var Uo,Lu=S(()=>{ut();Uo=class extends me{getLanguageName(){return"Ruby"}getDirectoryDescriptions(){return{...this.getCommonDirectoryDescriptions(),src:"\u6E90\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4E3B\u8981\u7684 Ruby \u4EE3\u7801",app:"\u5E94\u7528\u7A0B\u5E8F\u4EE3\u7801\u76EE\u5F55\uFF08Rails \u9879\u76EE\uFF09",bin:"\u53EF\u6267\u884C\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B CLI \u547D\u4EE4\u811A\u672C",lib:"\u5E93\u6587\u4EF6\u76EE\u5F55",libs:"\u5E93\u6587\u4EF6\u76EE\u5F55",vendor:"\u7B2C\u4E09\u65B9\u4F9D\u8D56\u5E93\u76EE\u5F55",config:"\u914D\u7F6E\u6587\u4EF6\u76EE\u5F55",controllers:"\u63A7\u5236\u5668\u76EE\u5F55\uFF08Rails \u9879\u76EE\uFF09",models:"\u6570\u636E\u6A21\u578B\u76EE\u5F55\uFF08Rails \u9879\u76EE\uFF09",views:"\u89C6\u56FE\u6A21\u677F\u76EE\u5F55\uFF08Rails \u9879\u76EE\uFF09",routes:"\u8DEF\u7531\u5B9A\u4E49\u76EE\u5F55\uFF08Rails \u9879\u76EE\uFF09",middleware:"\u4E2D\u95F4\u4EF6\u76EE\u5F55",services:"\u4E1A\u52A1\u903B\u8F91\u670D\u52A1\u76EE\u5F55",helpers:"\u8F85\u52A9\u51FD\u6570\u76EE\u5F55",tests:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",test:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",spec:"RSpec \u6D4B\u8BD5\u76EE\u5F55",docs:"\u6587\u6863\u76EE\u5F55\uFF0C\u5305\u542B\u9879\u76EE\u6587\u6863\u548C\u8BF4\u660E",examples:"\u793A\u4F8B\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4F7F\u7528\u793A\u4F8B",scripts:"\u811A\u672C\u76EE\u5F55\uFF0C\u5305\u542B\u6784\u5EFA\u3001\u90E8\u7F72\u7B49\u811A\u672C",build:"\u6784\u5EFA\u8F93\u51FA\u76EE\u5F55",Gemfile:"RubyGems \u4F9D\u8D56\u914D\u7F6E\u6587\u4EF6"}}async detectVersions(e,t){let n={},r=Ru(e,".ruby-version");if(Mu(r))try{let i=Au(r,"utf-8");n.Ruby=i.trim()}catch{}let o=Ru(e,"Gemfile");if(Mu(o))try{let a=Au(o,"utf-8").match(/ruby\s+['"]([^'"]+)['"]/);a&&!n.Ruby&&(n.Ruby=a[1])}catch{}return n}async findEntryPoints(e,t){return this.findEntryPointsByConfig(e,t,{commonEntries:["main.rb","app.rb","bin/rails","bin/rake","bin/console","config.ru","Rakefile","Gemfile"]})}async detectCodeStandards(e){let t={RuboCop:[".rubocop.yml",".rubocop.yaml",".rubocop_todo.yml"],RSpec:["spec/spec_helper.rb","spec/rails_helper.rb"],Minitest:["test/test_helper.rb"],EditorConfig:[".editorconfig"],Bundler:["Gemfile","Gemfile.lock"]};return this.detectCodeStandardsByFiles(e,t)}getCommonSourceExtensions(){return[".rb",".gemspec",".rake",".ru",".lock"]}getCommonTestExtensions(){return["_test.rb",".test.rb","test_*.rb","*_test.rb","spec/**/*.rb","test/**/*.rb"]}getCommonConfigFiles(){return["Gemfile","Gemfile.lock",".rubocop.yml",".ruby-version",".ruby-gemset","Rakefile","config.ru",".editorconfig"]}async analyzeDependencies(e,t){return{dependencies:[],conflicts:[],recommendations:[]}}}});import{existsSync as $d,readFileSync as ju}from"fs";import{resolve as Du}from"path";import{globSync as ka}from"glob";var Wo,Fu=S(()=>{ut();Wo=class extends me{getLanguageName(){return".NET"}getDirectoryDescriptions(){return{...this.getCommonDirectoryDescriptions(),src:"\u6E90\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4E3B\u8981\u7684 .NET \u4EE3\u7801",app:"\u5E94\u7528\u7A0B\u5E8F\u4EE3\u7801\u76EE\u5F55",bin:"\u7F16\u8BD1\u8F93\u51FA\u76EE\u5F55\uFF0C\u5305\u542B\u7F16\u8BD1\u540E\u7684\u4E8C\u8FDB\u5236\u6587\u4EF6",obj:"\u4E2D\u95F4\u7F16\u8BD1\u8F93\u51FA\u76EE\u5F55",lib:"\u5E93\u6587\u4EF6\u76EE\u5F55",libs:"\u5E93\u6587\u4EF6\u76EE\u5F55",packages:"NuGet \u5305\u76EE\u5F55",nuget:"NuGet \u76F8\u5173\u6587\u4EF6\u76EE\u5F55",config:"\u914D\u7F6E\u6587\u4EF6\u76EE\u5F55",Controllers:"\u63A7\u5236\u5668\u76EE\u5F55\uFF08ASP.NET \u9879\u76EE\uFF09",Models:"\u6570\u636E\u6A21\u578B\u76EE\u5F55\uFF08ASP.NET \u9879\u76EE\uFF09",Views:"\u89C6\u56FE\u6A21\u677F\u76EE\u5F55\uFF08ASP.NET MVC \u9879\u76EE\uFF09",Pages:"Razor Pages \u76EE\u5F55\uFF08ASP.NET \u9879\u76EE\uFF09",wwwroot:"\u9759\u6001\u8D44\u6E90\u76EE\u5F55\uFF08ASP.NET \u9879\u76EE\uFF09",services:"\u4E1A\u52A1\u903B\u8F91\u670D\u52A1\u76EE\u5F55",helpers:"\u8F85\u52A9\u51FD\u6570\u76EE\u5F55",tests:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",test:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",docs:"\u6587\u6863\u76EE\u5F55\uFF0C\u5305\u542B\u9879\u76EE\u6587\u6863\u548C\u8BF4\u660E",examples:"\u793A\u4F8B\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4F7F\u7528\u793A\u4F8B",scripts:"\u811A\u672C\u76EE\u5F55\uFF0C\u5305\u542B\u6784\u5EFA\u3001\u90E8\u7F72\u7B49\u811A\u672C",build:"\u6784\u5EFA\u811A\u672C\u548C\u914D\u7F6E\u76EE\u5F55"}}async detectVersions(e,t){let n={},r=[...ka("*.csproj",{cwd:e}),...ka("*.vbproj",{cwd:e}),...ka("*.fsproj",{cwd:e})];for(let i of r)try{let a=Du(e,i),c=ju(a,"utf-8"),l=c.match(/<TargetFramework>([^<]+)<\/TargetFramework>/)||c.match(/<TargetFrameworks>([^<]+)<\/TargetFrameworks>/);if(l){n[".NET Framework"]=l[1];break}let u=c.match(/<LangVersion>([^<]+)<\/LangVersion>/);u&&(n["C# Version"]=u[1])}catch{}let o=Du(e,"global.json");if($d(o))try{let i=ju(o,"utf-8"),a=JSON.parse(i);a.sdk&&a.sdk.version&&(n[".NET SDK"]=a.sdk.version)}catch{}return n}async findEntryPoints(e,t){return this.findEntryPointsByConfig(e,t,{commonEntries:["Program.cs","Startup.cs","App.xaml.cs","MainWindow.xaml.cs","Program.vb","Startup.vb","App.xaml.vb","MainWindow.xaml.vb","Program.fs","Startup.fs"]})}async detectCodeStandards(e){let t={StyleCop:[".stylecop","stylecop.json","stylecop.ruleset"],EditorConfig:[".editorconfig"],xUnit:["xunit.runner.json"],NUnit:["nunit.config","nunit3.config"],MSTest:["app.config","web.config"],NuGet:["nuget.config","packages.config"]};return this.detectCodeStandardsByFiles(e,t)}getCommonSourceExtensions(){return[".cs",".vb",".fs",".csproj",".vbproj",".fsproj",".config",".json",".xml"]}getCommonTestExtensions(){return["Test.cs","Tests.cs","Test.vb","Tests.vb","Test.fs","Tests.fs","*Test.csproj","*Tests.csproj"]}getCommonConfigFiles(){return["*.csproj","*.vbproj","*.fsproj","appsettings.json","app.config","web.config","nuget.config","packages.config","global.json",".editorconfig"]}async analyzeDependencies(e,t){return{dependencies:[],conflicts:[],recommendations:[]}}}});var Ea,kt,$a=S(()=>{xu();Su();Cu();Tu();Pu();Iu();Lu();Fu();Ea=class s{static instance;handlers=new Map;constructor(){this.registerHandlers()}static getInstance(){return s.instance||(s.instance=new s),s.instance}registerHandlers(){[new jo,new Do,new Fo,new Oo,new No,new _o,new Uo,new Wo].forEach(t=>{let n=t.getLanguageName();this.handlers.set(n.toLowerCase(),t),this.registerLanguageAliases(n,t)})}registerLanguageAliases(e,t){let n={"javascript/typescript":["javascript","typescript","node.js","nodejs"],java:["java","jdk","jvm"],python:["python","py"],go:["go","golang"],rust:["rust","rs"],php:["php"],ruby:["ruby","rb"],".net":["c#/.net","csharp","dotnet",".net","vb.net","f#"]},r=e.toLowerCase();n[r]&&n[r].forEach(o=>{this.handlers.set(o.toLowerCase(),t)})}getHandler(e){if(!e)return null;let t=e.toLowerCase();return this.handlers.get(t)||null}getSupportedLanguages(){return Array.from(new Set(Array.from(this.handlers.values()).map(e=>e.getLanguageName())))}getDirectoryDescriptions(e){let t=this.getHandler(e);return t?t.getDirectoryDescriptions():{src:"\u6E90\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u6240\u6709\u4E3B\u8981\u7684\u5E94\u7528\u7A0B\u5E8F\u4EE3\u7801",test:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",tests:"\u6D4B\u8BD5\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B\u5355\u5143\u6D4B\u8BD5\u548C\u96C6\u6210\u6D4B\u8BD5",docs:"\u6587\u6863\u76EE\u5F55\uFF0C\u5305\u542B\u9879\u76EE\u6587\u6863\u548C\u8BF4\u660E",examples:"\u793A\u4F8B\u4EE3\u7801\u76EE\u5F55\uFF0C\u5305\u542B\u4F7F\u7528\u793A\u4F8B",bin:"\u53EF\u6267\u884C\u6587\u4EF6\u76EE\u5F55\uFF0C\u5305\u542B CLI \u547D\u4EE4\u811A\u672C",lib:"\u5E93\u6587\u4EF6\u76EE\u5F55",dist:"\u6784\u5EFA\u8F93\u51FA\u76EE\u5F55",build:"\u6784\u5EFA\u811A\u672C\u548C\u914D\u7F6E\u76EE\u5F55",config:"\u914D\u7F6E\u6587\u4EF6\u76EE\u5F55"}}async detectVersions(e,t,n){let r=this.getHandler(e);return r?await r.detectVersions(t,n):{}}async findEntryPoints(e,t,n){let r=this.getHandler(e);return r?await r.findEntryPoints(t,n):[]}async detectCodeStandards(e,t){let n=this.getHandler(e);return n?await n.detectCodeStandards(t):[]}getCommonSourceExtensions(e){let t=this.getHandler(e);return t?t.getCommonSourceExtensions():[]}getCommonTestExtensions(e){let t=this.getHandler(e);return t?t.getCommonTestExtensions():[]}getCommonConfigFiles(e){let t=this.getHandler(e);return t?t.getCommonConfigFiles():[]}getDirectoryDescriptionsForLanguages(e){let t={};return e.forEach(n=>{let r=this.getDirectoryDescriptions(n);Object.assign(t,r)}),t}async detectVersionsForLanguages(e,t,n){let r={};for(let o of e){let i=await this.detectVersions(o,t,n);Object.assign(r,i)}return r}async findEntryPointsForLanguages(e,t,n){let r=[];for(let o of e){let i=await this.findEntryPoints(o,t,n);r.push(...i)}return[...new Set(r)]}async detectCodeStandardsForLanguages(e,t){let n=[];for(let r of e){let o=await this.detectCodeStandards(r,t);n.push(...o)}return[...new Set(n)]}async validateCode(e,t,n){n||(n=this.detectLanguageFromFile(e));let r=this.getHandler(n);return r?await r.validateCode(e,t):{valid:!0,message:`No language handler found for: ${n}`}}detectLanguageFromFile(e){let t=e.split(".").pop()?.toLowerCase()||"";return{js:"javascript",jsx:"javascript",ts:"typescript",tsx:"typescript",mjs:"javascript",cjs:"javascript",py:"python",java:"java",go:"go",rs:"rust",php:"php",rb:"ruby",cs:"csharp",vb:"vb.net",fs:"f#"}[t]||"unknown"}},kt=Ea.getInstance()});import{resolve as Id}from"path";import{existsSync as Md}from"fs";async function ys(s){return await Ou.execute(s)}var Gn,Ou,xs,Nu=S(()=>{G();$a();Gn=class extends R{getDefinition(){return{name:"validate",description:`Validate code files for syntax errors, type errors, and code style issues.
437
444
 
438
445
  \u{1F4CB} USE CASES:
439
446
  - Verify generated code has no syntax errors
@@ -463,26 +470,91 @@ ${s}`}:{valid:!1,message:`TypeScript validation failed with ${i.length} error(s)
463
470
  - read: View the content of files before or after validation
464
471
  - merge: Modify files to fix validation errors
465
472
  - searchReplace: Batch fix validation errors across multiple files
466
- - shell: Run custom validation commands for unsupported languages`,input_schema:{type:"object",properties:{path:{type:"string",description:"File path to validate"},language:{type:"string",description:"Programming language (optional, auto-detected)"}},required:["path"]}}}async execute(e){try{let t=Hu(e.path);if(!Ju(t))return`Error: File not found: ${e.path}`;let n=process.cwd(),r=await Ue.validateCode(t,n,e.language);return this.formatValidationResult(r,e.path)}catch(t){return this.formatError(`Cannot validate ${e.path}`,t)}}formatValidationResult(e,t){if(e.valid){let n=`\u2705 Validation passed: ${t}
473
+ - shell: Run custom validation commands for unsupported languages`,input_schema:{type:"object",properties:{path:{type:"string",description:"File path to validate"},language:{type:"string",description:"Programming language (optional, auto-detected)"}},required:["path"]}}}async execute(e){try{let t=Id(e.path);if(!Md(t))return`Error: File not found: ${e.path}`;let n=process.cwd(),r=await kt.validateCode(t,n,e.language);return this.formatValidationResult(r,e.path)}catch(t){return this.formatError(`Cannot validate ${e.path}`,t)}}formatValidationResult(e,t){if(e.valid){let n=`\u2705 Validation passed: ${t}
467
474
  ${e.message}`;return e.warnings&&e.warnings.length>0&&(n+=`
468
475
 
469
- \u26A0\uFE0F Warnings (${e.warnings.length}):`,e.warnings.forEach((r,s)=>{let i=r.line?`Line ${r.line}${r.column?`:${r.column}`:""}`:"Unknown location";n+=`
470
- ${s+1}. [${i}] ${r.message}`,r.code&&(n+=` (${r.code})`)})),n}else{let n=`\u274C Validation failed: ${t}
476
+ \u26A0\uFE0F Warnings (${e.warnings.length}):`,e.warnings.forEach((r,o)=>{let i=r.line?`Line ${r.line}${r.column?`:${r.column}`:""}`:"Unknown location";n+=`
477
+ ${o+1}. [${i}] ${r.message}`,r.code&&(n+=` (${r.code})`)})),n}else{let n=`\u274C Validation failed: ${t}
471
478
  ${e.message}`;return e.errors&&e.errors.length>0&&(n+=`
472
479
 
473
- Errors (${e.errors.length}):`,e.errors.forEach((r,s)=>{let i=r.line?`Line ${r.line}${r.column?`:${r.column}`:""}`:"Unknown location";n+=`
474
- ${s+1}. [${i}] ${r.message}`,r.code&&(n+=` (${r.code})`)})),e.warnings&&e.warnings.length>0&&(n+=`
480
+ Errors (${e.errors.length}):`,e.errors.forEach((r,o)=>{let i=r.line?`Line ${r.line}${r.column?`:${r.column}`:""}`:"Unknown location";n+=`
481
+ ${o+1}. [${i}] ${r.message}`,r.code&&(n+=` (${r.code})`)})),e.warnings&&e.warnings.length>0&&(n+=`
475
482
 
476
- Warnings (${e.warnings.length}):`,e.warnings.forEach((r,s)=>{let i=r.line?`Line ${r.line}${r.column?`:${r.column}`:""}`:"Unknown location";n+=`
477
- ${s+1}. [${i}] ${r.message}`,r.code&&(n+=` (${r.code})`)})),n}}},tc=new Rt;Un=tc});var Ts={};j(Ts,{CopyTool:()=>Mt,DeleteTool:()=>Pt,MergeTool:()=>It,MkdirTool:()=>kt,MoveTool:()=>$t,ReadTool:()=>Tt,SearchReplaceTool:()=>At,ValidateTool:()=>Rt,WriteTool:()=>Et,copyFile:()=>In,copyTool:()=>An,deleteFile:()=>En,deleteTool:()=>Pn,merge:()=>Ln,mergeTool:()=>Rn,mkdir:()=>bn,mkdirTool:()=>rt,moveFile:()=>$n,moveTool:()=>Mn,read:()=>vn,readTool:()=>wn,searchReplace:()=>Dn,searchReplaceTool:()=>Fn,validate:()=>Nn,validateTool:()=>Un,write:()=>Tn,writeTool:()=>kn});var Xr=C(()=>{la();ma();ps();fa();Ca();Ea();Aa();Fa();nc()});import{readFileSync as Gu,existsSync as Bu}from"fs";import{resolve as qu}from"path";function Yu(o){let e=qu(o,".niumignore"),t=[];if(Bu(e))try{Gu(e,"utf-8").split(`
478
- `).forEach(r=>{let s=r.trim();s&&!s.startsWith("#")&&t.push(Xu(s))})}catch(n){console.warn(`Error reading .niumignore file: ${n instanceof Error?n.message:"Unknown error"}`)}return t}function Ee(o,e=!0){let t=Yu(o);return e?[...Ku,...t]:t}function Xu(o){if(o.startsWith("!")){let e=o.slice(1);return e.includes("/")||e.includes("\\")?o:`!**/${e}`}return o.includes("*")||o.includes("?")||o.includes("{")||o.includes("[")?o:o.endsWith("/")?`**/${o.slice(0,-1)}/**`:o.startsWith("*.")?o:!o.includes("/")&&!o.includes("\\")?`**/${o}/**`:o}var Ku,Dt=C(()=>{Ku=["**/.git/**","**/.svn/**","**/.hg/**","**/node_modules/**","**/vendor/**","**/.pnpm/**","**/bower_components/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.next/**","**/.nuxt/**","**/.output/**","**/.idea/**","**/.vscode/**","**/.vs/**","**/*.swp","**/*.swo","**/*~","**/.DS_Store","**/Thumbs.db","**/desktop.ini","**/.cache/**","**/tmp/**","**/temp/**","**/__pycache__/**","**/*.pyc","**/.pytest_cache/**","**/*.log","**/logs/**","**/.nium/archives/**","**/.nium/session.json","**/package-lock.json","**/yarn.lock","**/pnpm-lock.yaml","**/Gemfile.lock","**/Pipfile.lock","**/poetry.lock","**/Cargo.lock"]});import{globSync as rc}from"glob";function Wn(o){return oc.execute(o)}var Ft,oc,Vn,sc=C(()=>{V();Dt();Ft=class extends ${getDefinition(){return{name:"glob",description:`Search for files matching a glob pattern.
483
+ Warnings (${e.warnings.length}):`,e.warnings.forEach((r,o)=>{let i=r.line?`Line ${r.line}${r.column?`:${r.column}`:""}`:"Unknown location";n+=`
484
+ ${o+1}. [${i}] ${r.message}`,r.code&&(n+=` (${r.code})`)})),n}}},Ou=new Gn;xs=Ou});var Ia={};B(Ia,{CopyTool:()=>Bn,DeleteTool:()=>_n,MergeTool:()=>Hn,MkdirTool:()=>On,MoveTool:()=>Wn,ReadTool:()=>Dn,SearchReplaceTool:()=>zn,ValidateTool:()=>Gn,WriteTool:()=>Nn,copyFile:()=>cs,copyTool:()=>ls,deleteFile:()=>ss,deleteTool:()=>os,merge:()=>ps,mergeTool:()=>gs,mkdir:()=>ts,mkdirTool:()=>Yt,moveFile:()=>is,moveTool:()=>as,read:()=>Xr,readTool:()=>Qr,searchReplace:()=>ms,searchReplaceTool:()=>ds,validate:()=>ys,validateTool:()=>xs,write:()=>ns,writeTool:()=>rs});var Bo=S(()=>{zl();Kl();Sa();Ql();nu();uu();fu();yu();Nu()});import{readFileSync as Ad,existsSync as Rd}from"fs";import{resolve as Ld}from"path";function Dd(s){let e=Ld(s,".niumignore"),t=[];if(Rd(e))try{Ad(e,"utf-8").split(`
485
+ `).forEach(r=>{let o=r.trim();o&&!o.startsWith("#")&&t.push(Fd(o))})}catch(n){console.warn(`Error reading .niumignore file: ${n instanceof Error?n.message:"Unknown error"}`)}return t}function we(s,e=!0){let t=Dd(s);return e?[...jd,...t]:t}function Fd(s){if(s.startsWith("!")){let e=s.slice(1);return e.includes("/")||e.includes("\\")?s:`!**/${e}`}return s.includes("*")||s.includes("?")||s.includes("{")||s.includes("[")?s:s.endsWith("/")?`**/${s.slice(0,-1)}/**`:s.startsWith("*.")?s:!s.includes("/")&&!s.includes("\\")?`**/${s}/**`:s}var jd,pt=S(()=>{jd=["**/.git/**","**/.svn/**","**/.hg/**","**/node_modules/**","**/vendor/**","**/.pnpm/**","**/bower_components/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.next/**","**/.nuxt/**","**/.output/**","**/.idea/**","**/.vscode/**","**/.vs/**","**/*.swp","**/*.swo","**/*~","**/.DS_Store","**/Thumbs.db","**/desktop.ini","**/.cache/**","**/tmp/**","**/temp/**","**/__pycache__/**","**/*.pyc","**/.pytest_cache/**","**/*.log","**/logs/**","**/.nium/archives/**","**/.nium/session.json","**/package-lock.json","**/yarn.lock","**/pnpm-lock.yaml","**/Gemfile.lock","**/Pipfile.lock","**/poetry.lock","**/Cargo.lock"]});import{globSync as _u}from"glob";function Ss(s){return Uu.execute(s)}var qn,Uu,Cs,Wu=S(()=>{G();pt();qn=class extends R{getDefinition(){return{name:"glob",description:`Search for files matching glob patterns with advanced filtering and ignore support.
479
486
 
480
- Examples:
481
- - glob("*.js") - all .js files in current directory
482
- - glob("**/*.ts") - all .ts files recursively
483
- - glob("src/**/*.{js,ts}") - all .js and .ts files under src/
487
+ \u26A0\uFE0F CRITICAL REQUIREMENTS:
488
+ - Pattern MUST NOT be empty string or whitespace-only string
489
+ - Each pattern must be a valid glob expression (e.g., "*.js", "**/*.ts")
490
+ - If a pattern returns no results, DO NOT retry with the same pattern
491
+ - If unsure what pattern to use, try more specific patterns like "**/*.<extension>" or analyze the directory structure first
492
+ - Empty patterns will be rejected with an error message
484
493
 
485
- Returns an array of matching file paths.`,input_schema:{type:"object",properties:{pattern:{type:"string",description:'The glob pattern to match (e.g., "*.js", "**/*.ts")'},cwd:{type:"string",description:"Optional: the directory to search in (defaults to current directory)"}},required:["pattern"]}}}execute(e){try{let t=e.cwd||process.cwd(),n=Ee(t),r=rc(e.pattern,{nodir:!0,cwd:e.cwd,ignore:n});if(r.length===0&&!e.pattern.startsWith("*")&&!e.pattern.startsWith("**")){let s=`**/${e.pattern}`;r=rc(s,{nodir:!0,cwd:e.cwd,ignore:n})}return r.length>0?r:`No files matching pattern: ${e.pattern}`}catch(t){return this.formatError("Glob pattern",t)}}},oc=new Ft;Vn=oc});import{readFileSync as ic}from"fs";import{dirname as Qu}from"path";import{globSync as Zu}from"glob";function zn(o){return ac.execute(o)}var Ot,ac,Hn,cc=C(()=>{V();Dt();Y();Ot=class extends ${getDefinition(){return{name:"grep",description:`Search for text patterns in files using regular expressions with glob support.
494
+ \u{1F4CB} USE CASES:
495
+ - Find all files of a specific type across the project
496
+ - Locate configuration files in multiple directories
497
+ - Identify test files for a specific component
498
+ - Find all files modified recently
499
+ - Search for files with specific naming patterns
500
+
501
+ \u{1F511} PARAMETERS:
502
+ - pattern: Array of glob patterns to match (supports **/*.js, *.{js,ts}, etc.) - CANNOT be empty
503
+ - cwd: Optional working directory to search from (defaults to current directory)
504
+
505
+ \u{1F4A1} VALID EXAMPLES:
506
+ - glob({ pattern: ["*.js"] }) - Find all JavaScript files in current directory
507
+ - glob({ pattern: ["*.js", "*.ts"] }) - Find all JS and TS files in one call
508
+ - glob({ pattern: ["**/*.ts"] }) - Find all TypeScript files recursively
509
+ - glob({ pattern: ["src/**/*.{js,ts}"] }) - Find all JS/TS files under src/
510
+ - glob({ pattern: ["**/test*.{js,ts}", "**/*.spec.{js,ts}"] }) - Find all test files with multiple patterns
511
+ - glob({ pattern: [".env*", ".config*"] }) - Find all environment and config files
512
+ - glob({ pattern: ["src/components/**/*.tsx"], cwd: "/project" }) - Find React components in specific directory
513
+
514
+ \u274C INVALID EXAMPLES (DO NOT USE):
515
+ - glob({ pattern: [""] }) - Empty pattern is INVALID
516
+ - glob({ pattern: [" "] }) - Whitespace-only pattern is INVALID
517
+ - Retrying the same failed pattern without modification is FUTILE
518
+
519
+ \u{1F4DD} RETURN VALUE:
520
+ - Array of matching file paths (relative to the search directory)
521
+ - Sorted list for consistent results
522
+ - Automatic filtering of ignored files (using .niumignore and default ignore patterns)
523
+ - Support for complex patterns with braces and negation
524
+ - Error message if no files found or pattern is invalid
525
+ - Helpful error messages for invalid patterns
526
+
527
+ \u{1F504} RETRY GUIDANCE:
528
+ - If a pattern returns "No files matching", analyze WHY before retrying
529
+ - Try different, more specific or more general patterns
530
+ - Use other tools (like reading directory structure) to understand what files exist
531
+ - DO NOT retry with the exact same invalid or empty pattern`,input_schema:{type:"object",properties:{pattern:{type:"array",items:{type:"string",description:'Glob pattern to match files (e.g., "*.js", "**/*.ts")'},description:"Array of glob patterns to match files. Supports single or multiple patterns."},cwd:{type:"string",description:"Optional working directory to search from (defaults to current directory)"}},required:["pattern"]}}}execute(e){try{console.log("[Glob] \u8C03\u7528\u53C2\u6570:",{input:e,pattern_type:typeof e.pattern,pattern_is_array:Array.isArray(e.pattern),pattern_value:e.pattern,cwd:e.cwd||process.cwd()});let t=e.cwd||process.cwd(),n=we(t),r=Array.isArray(e.pattern)?e.pattern:[e.pattern],o=r.filter(l=>l&&l.trim().length>0),i=r.filter(l=>!l||l.trim().length===0);if(i.length>0)return`[\u9519\u8BEF] Pattern \u4E0D\u80FD\u4E3A\u7A7A\u5B57\u7B26\u4E32\u6216\u7EAF\u7A7A\u767D\u5B57\u7B26\u3002
532
+
533
+ \u6536\u5230\u7684 patterns: ${JSON.stringify(r)}
534
+ \u65E0\u6548\u7684 patterns: ${i.length} \u4E2A
535
+
536
+ \u2705 \u6B63\u786E\u793A\u4F8B:
537
+ - glob({ pattern: ["*.js"] })
538
+ - glob({ pattern: ["**/*.ts"] })
539
+ - glob({ pattern: ["src/**/*.tsx"] })
540
+
541
+ \u274C \u9519\u8BEF\u793A\u4F8B:
542
+ - glob({ pattern: [""] }) // \u7A7A\u5B57\u7B26\u4E32
543
+ - glob({ pattern: [" "] }) // \u7EAF\u7A7A\u767D
544
+
545
+ \u{1F4A1} \u5EFA\u8BAE:
546
+ 1. \u4F7F\u7528\u5177\u4F53\u7684\u6587\u4EF6\u6269\u5C55\u540D\u6A21\u5F0F (\u5982 "*.js", "*.ts")
547
+ 2. \u4F7F\u7528\u9012\u5F52\u641C\u7D22\u6A21\u5F0F (\u5982 "**/*.tsx")
548
+ 3. \u5148\u5206\u6790\u76EE\u5F55\u7ED3\u6784\u518D\u786E\u5B9A\u641C\u7D22\u6A21\u5F0F
549
+ 4. \u4E0D\u8981\u91CD\u8BD5\u76F8\u540C\u7684\u65E0\u6548\u6A21\u5F0F`;if(o.length===0)return`[\u9519\u8BEF] \u6240\u6709 patterns \u90FD\u65E0\u6548\u3002\u8BF7\u63D0\u4F9B\u6709\u6548\u7684 glob pattern\u3002
550
+
551
+ \u53C2\u8003\u793A\u4F8B: glob({ pattern: ["**/*.ts"] }) \u6216 glob({ pattern: ["src/**/*.js"] })`;console.log("[Glob] \u5904\u7406\u540E\u7684patterns:",{patterns:o,patterns_length:o.length,currentDir:t,filtered_out:i.length});let a=[],c=new Set;return o.forEach(l=>{try{let u=_u(l,{nodir:!0,cwd:e.cwd,ignore:n});if(u.length===0&&!l.startsWith("*")&&!l.startsWith("**")){let p=`**/${l}`;u=_u(p,{nodir:!0,cwd:e.cwd,ignore:n})}u.forEach(p=>c.add(p))}catch(u){console.error(`Error processing glob pattern ${l}: ${u instanceof Error?u.message:"Unknown error"}`)}}),a=Array.from(c),a.length>0?a:`No files matching patterns: ${o.join(", ")}
552
+
553
+ \u{1F4A1} \u63D0\u793A\uFF1A\u6CA1\u6709\u627E\u5230\u5339\u914D\u7684\u6587\u4EF6\u3002\u8BF7\u5C1D\u8BD5\uFF1A
554
+ 1. \u4F7F\u7528\u66F4\u5BBD\u6CDB\u7684\u6A21\u5F0F (\u5982 "**/*.js" \u800C\u975E "*.js")
555
+ 2. \u68C0\u67E5\u6587\u4EF6\u6269\u5C55\u540D\u662F\u5426\u6B63\u786E
556
+ 3. \u4F7F\u7528\u5176\u4ED6\u5DE5\u5177\u5148\u67E5\u770B\u76EE\u5F55\u7ED3\u6784
557
+ 4. \u4E0D\u8981\u91CD\u590D\u4F7F\u7528\u76F8\u540C\u7684\u5931\u8D25\u6A21\u5F0F`}catch(t){return this.formatError("Glob pattern",t)}}},Uu=new qn;Cs=Uu});import{readFileSync as Bu}from"fs";import{dirname as Od}from"path";import{globSync as Nd}from"glob";function ws(s){return Hu.execute(s)}var Jn,Hu,bs,zu=S(()=>{G();pt();Q();Jn=class extends R{getDefinition(){return{name:"grep",description:`Search for text patterns in files using regular expressions with glob support.
486
558
 
487
559
  \u{1F4CB} USE CASES:
488
560
  - Find code patterns and function definitions
@@ -497,10 +569,11 @@ Returns an array of matching file paths.`,input_schema:{type:"object",properties
497
569
 
498
570
  \u{1F4A1} EXAMPLES:
499
571
  - grep({ pattern: "function.*foo", path: "src/main.js" }) - Find function definitions containing "foo" in a single file
500
- - grep({ pattern: "TODO", path: "**/*.js" }) - Find all TODOs in all JavaScript files
501
- - grep({ pattern: "import", path: "src/**/*.{js,ts}" }) - Find all import statements in JS/TS files
502
- - grep({ pattern: "class.*Component", path: "src/components/**/*.tsx" }) - Find React components
503
- - grep({ pattern: "error", path: "logs/**/*.log" }) - Search for errors in log files
572
+ - grep({ pattern: ["TODO"], path: "**/*.js" }) - Find all TODOs in JavaScript files
573
+ - grep({ pattern: ["TODO", "FIXME"], path: "**/*.js" }) - Find all TODOs and FIXMEs in one call
574
+ - grep({ pattern: ["import", "export"], path: "src/**/*.{js,ts}" }) - Find all import and export statements in one call
575
+ - grep({ pattern: ["class.*Component"], path: "src/components/**/*.tsx" }) - Find React components
576
+ - grep({ pattern: ["error", "warn", "debug"], path: "logs/**/*.log" }) - Search for multiple log levels in one call
504
577
 
505
578
  \u{1F4DD} RETURN VALUE:
506
579
  - Array of matching lines with filenames and line numbers
@@ -513,8 +586,33 @@ Returns an array of matching file paths.`,input_schema:{type:"object",properties
513
586
  - Cross-platform glob pattern matching
514
587
  - Ignores system and gitignore files
515
588
  - Case-sensitive matching (use regex flags for case-insensitive)
516
- - Handles large files efficiently`,input_schema:{type:"object",properties:{pattern:{type:"string",description:"Regular expression pattern to search for"},path:{type:"string",description:"File path or glob pattern (e.g., 'src/main.js' or '**/*.js')"}},required:["pattern","path"]}}}execute(e){try{let t=[];try{let i=e.path.includes("/")||e.path.includes("\\")?Qu(e.path):process.cwd(),c={nodir:!0,windowsPathsNoEscape:!0,absolute:!1,ignore:Ee(i)};if(e.path.includes("*")||e.path.includes("?")||e.path.includes("{")){if(x(`Processing glob pattern: ${e.path}`),t=Zu(e.path,c),t.length===0)return`No files found matching pattern: ${e.path}`;x(`Found ${t.length} files matching pattern`)}else try{let u=ic(e.path,"utf-8");t=[e.path]}catch(u){return u instanceof Error?`Error: ${u.message}`:`Error: Could not read file: ${e.path}`}}catch(i){return console.error("Glob error:",i),i instanceof Error?`Error: Grep failed - ${i.message}`:`Error: Grep failed - Unknown error processing glob pattern: ${e.path}`}if(t.length===0)return`No files found matching pattern: ${e.path}`;let n=new RegExp(e.pattern),r=[],s=0;return t.forEach(i=>{try{let c=ic(i,"utf-8").split(`
517
- `),l=[];c.forEach((u,p)=>{n.test(u)&&(l.push(`${i}:${p+1}: ${u}`),s++)}),l.length>0&&r.push(...l)}catch(a){r.push(`Error reading file ${i}: ${a instanceof Error?a.message:"Unknown error"}`)}}),s>0?(t.length>1&&r.unshift(`Found ${s} matches in ${t.length} files`),r):`No matches found for pattern: ${e.pattern} in ${t.length} files`}catch(t){return this.formatError("Grep",t)}}},ac=new Ot;Hn=ac});import{readFileSync as eg,existsSync as tg}from"fs";import{join as ng}from"path";import{globSync as rg}from"glob";function Jn(o){return lc.execute(o)}var jt,lc,Gn,uc=C(()=>{V();Dt();jt=class extends ${getDefinition(){return{name:"search-docs",description:`Search for content in documentation files using keywords and regular expressions.
589
+ - Handles large files efficiently`,input_schema:{type:"object",properties:{pattern:{type:"array",items:{type:"string",description:"Regular expression pattern to search for"},description:"Array of regular expression patterns to search for. Supports single or multiple patterns."},path:{type:"string",description:"File path or glob pattern (supports **/*.js, *.{js,ts}, etc.)"}},required:["pattern","path"]}}}execute(e){try{let t=[];try{let i=e.path.includes("/")||e.path.includes("\\")?Od(e.path):process.cwd(),c={nodir:!0,windowsPathsNoEscape:!0,absolute:!1,ignore:we(i)};if(e.path.includes("*")||e.path.includes("?")||e.path.includes("{")){if(C(`Processing glob pattern: ${e.path}`),t=Nd(e.path,c),t.length===0)return`No files found matching pattern: ${e.path}`;C(`Found ${t.length} files matching pattern`)}else try{let u=Bu(e.path,"utf-8");t=[e.path]}catch(u){return u instanceof Error?`Error: ${u.message}`:`Error: Could not read file: ${e.path}`}}catch(i){return console.error("Glob error:",i),i instanceof Error?`Error: Grep failed - ${i.message}`:`Error: Grep failed - Unknown error processing glob pattern: ${e.path}`}if(t.length===0)return`No files found matching pattern: ${e.path}`;let n=e.pattern,r=[],o=0;return n.forEach(i=>{try{let a=new RegExp(i),c=0;t.forEach(l=>{try{let p=Bu(l,"utf-8").split(`
590
+ `),g=[];p.forEach((m,d)=>{a.test(m)&&(g.push(`${l}:${d+1}: ${m}`),c++,o++)}),g.length>0&&r.push(...g)}catch(u){r.push(`Error reading file ${l}: ${u instanceof Error?u.message:"Unknown error"}`)}}),c>0?r.unshift(`=== Pattern: ${i} (${c} matches) ===`):r.unshift(`=== Pattern: ${i} (no matches) ===`)}catch(a){r.push(`Error processing pattern ${i}: ${a instanceof Error?a.message:"Unknown error"}`)}}),o>0?(t.length>1&&r.unshift(`Found ${o} total matches in ${t.length} files`),r):`No matches found for patterns: ${n.join(", ")} in ${t.length} files`}catch(t){return this.formatError("Grep",t)}}},Hu=new Jn;bs=Hu});import{EventEmitter as _d}from"events";var Ma,Kn,Aa=S(()=>{Ma=class extends _d{thinkingSteps=new Map;tasks=new Map;createThinkingStep(e,t){let n={id:e,description:t,status:"pending"};this.thinkingSteps.set(e,n),this.emitThinkingStepsUpdate()}createThinkingSteps(e){for(let{id:t,description:n}of e)this.createThinkingStep(t,n)}startStep(e,t){let n=this.thinkingSteps.get(e);n&&(n.status="in_progress",n.startTime=Date.now(),t&&(n.details=t),this.emitThinkingStepsUpdate())}updateStepProgress(e,t,n){let r=this.thinkingSteps.get(e);r&&(r.progress=Math.min(100,Math.max(0,t)),n&&(r.details=n),this.emitThinkingStepsUpdate())}completeStep(e,t){let n=this.thinkingSteps.get(e);n&&(n.status="completed",n.endTime=Date.now(),t&&(n.details=t),this.emitThinkingStepsUpdate())}failStep(e,t){let n=this.thinkingSteps.get(e);n&&(n.status="failed",n.endTime=Date.now(),t&&(n.details=t),this.emitThinkingStepsUpdate())}getThinkingSteps(){return Array.from(this.thinkingSteps.values())}clearThinkingSteps(){this.thinkingSteps.clear(),this.emitThinkingStepsUpdate()}createTask(e,t,n){let r={name:t,completed:0,total:n,status:"pending"};this.tasks.set(e,r),this.emitTaskUpdate(r)}startTask(e){let t=this.tasks.get(e);t&&(t.status="running",this.emitTaskUpdate(t))}updateTaskProgress(e,t,n,r){let o=this.tasks.get(e);o&&(o.completed=t,o.currentItem=n,o.estimatedTimeRemaining=r,this.emitTaskUpdate(o))}completeTask(e){let t=this.tasks.get(e);t&&(t.status="completed",t.completed=t.total,t.currentItem=void 0,t.estimatedTimeRemaining=void 0,this.emitTaskUpdate(t))}failTask(e){let t=this.tasks.get(e);t&&(t.status="failed",this.emitTaskUpdate(t))}getTask(e){return this.tasks.get(e)}clearTask(e){this.tasks.delete(e)}clearAllTasks(){this.tasks.clear()}emitError(e){this.emit("progress",{type:"error",error:e})}clear(){this.thinkingSteps.clear(),this.tasks.clear(),this.emit("progress",{type:"clear"})}emitThinkingStepsUpdate(){let e=this.getThinkingSteps();this.emit("progress",{type:"thinking_step_update",steps:e})}emitTaskUpdate(e){this.emit("progress",{type:"task_update",task:e})}async executeStep(e,t){this.startStep(e);let n=(r,o)=>{this.updateStepProgress(e,r,o)};try{let r=await t(n);return this.completeStep(e),r}catch(r){throw this.failStep(e,r instanceof Error?r.message:String(r)),r}}async executeTask(e,t,n,r){this.createTask(e,t,n),this.startTask(e);let o=Date.now(),i=(a,c)=>{let l;if(a>0){let p=(Date.now()-o)/a,g=n-a;l=p*g}this.updateTaskProgress(e,a,c,l)};try{let a=await r(i);return this.completeTask(e),a}catch(a){throw this.failTask(e),a}finally{setTimeout(()=>{this.clearTask(e)},3e3)}}},Kn=new Ma});import{readFileSync as Ud,writeFileSync as Wd,existsSync as Bd,mkdirSync as Hd,statSync as zd}from"fs";import{join as vs}from"path";import{globSync as Vd}from"glob";import{Document as Gd}from"flexsearch";async function Xt(s={}){return await Vu.execute(s)}var Yn,Vu,Ts,Ra=S(()=>{G();pt();Aa();Yn=class extends R{getDefinition(){return{name:"build-doc-index",description:`Build and update documentation index for efficient search.
591
+
592
+ \u{1F4CB} USE CASES:
593
+ - Create initial documentation index
594
+ - Update index when docs are added or modified
595
+ - Refresh index to ensure search accuracy
596
+ - Maintain up-to-date metadata for docs
597
+
598
+ \u{1F511} PARAMETERS:
599
+ - path: Documentation directory path (default: ".niums/docs")
600
+
601
+ \u{1F4A1} EXAMPLES:
602
+ - build-doc-index() - Build index for default docs directory
603
+ - build-doc-index({ path: ".niums/docs" }) - Build index for specific docs directory
604
+ - build-doc-index({ path: "docs/" }) - Build index for custom docs location
605
+
606
+ \u{1F4DD} RETURN VALUE:
607
+ - Success message with index statistics
608
+ - Path to generated index file
609
+ - Number of documents indexed
610
+ - Any warnings or errors encountered`,input_schema:{type:"object",properties:{path:{type:"string",description:"Documentation directory path (default: .niums/docs)"}}}}}async execute(e){let t="build-doc-index";try{let n=e.path||".niums/docs",r=process.cwd(),o=vs(r,n);if(!Bd(o))return`Documentation directory not found: ${o}`;let a={nodir:!0,windowsPathsNoEscape:!0,absolute:!1,ignore:we(r),cwd:r},c=vs(n,"**/*.{md,markdown,txt,rst,html,htm}"),l=Vd(c,a);return l.length===0?`No documentation files found in: ${n}`:await Kn.executeTask(t,"\u6784\u5EFA\u6587\u6863\u7D22\u5F15",l.length,async u=>{let p=new Gd({document:{id:"id",index:["title","content","keywords"],store:!0},tokenize:"forward",resolution:9,context:!0}),g={};for(let w=0;w<l.length;w++){let T=l[w];try{let h=vs(r,T),x=Ud(h,"utf-8"),P=zd(h),k=this.extractDocMetadata(T,x,P.size,w);g[k.id]=k,await p.addAsync(k.id,{title:k.title,content:k.content,keywords:k.keywords.join(" ")}),u(w+1,T)}catch(h){console.error(`Error processing file ${T}:`,h)}}let m=[];await p.export((w,T)=>{m.push({key:w,data:T})});let d={version:"1.0.0",lastIndexed:new Date().toISOString(),totalDocuments:Object.keys(g).length,index:m,documents:g},f=vs(r,n);Hd(f,{recursive:!0});let y=vs(f,".flexindex.json");return Wd(y,JSON.stringify(d,null,2),"utf-8"),`Successfully built FlexSearch documentation index:
611
+ - Index file: ${y}
612
+ - Total documents indexed: ${d.totalDocuments}
613
+ - Last indexed: ${d.lastIndexed}
614
+ - Documentation directory: ${n}
615
+ - Index features: Full-text search, fuzzy matching, context-aware`})}catch(n){return Kn.clearTask(t),this.formatError("Build Doc Index",n)}}extractDocMetadata(e,t,n,r){let o=`doc_${r}`,i=this.extractTitle(e,t),a=this.extractSummary(t),c=this.extractKeywords(t),l=new Date().toISOString(),u=this.cleanContentForIndex(t);return{id:o,path:e,title:i,content:u,summary:a,keywords:c,lastModified:l,size:n}}cleanContentForIndex(e){return e.replace(/\s+/g," ").trim().substring(0,1e4)}extractTitle(e,t){let n=t.match(/^#\s+(.+)$/m);if(n&&n[1])return n[1].trim();let r=t.match(/<h1[^>]*>(.+?)<\/h1>/i);return r&&r[1]?r[1].trim():(e.split(/[\\/]/).pop()||e).replace(/\.(md|markdown|txt|rst|html|htm)$/i,"").replace(/[-_]/g," ").replace(/\b\w/g,a=>a.toUpperCase())}extractSummary(e){let t=e.replace(/\s+/g," ").replace(/[#*_~`]|\[|\]|\(|\)|<[^>]*>|\n/g," ").trim();return t.length>150?t.substring(0,150)+"...":t}extractKeywords(e){let t=e.replace(/\s+/g," ").replace(/[#*_~`]|\[|\]|\(|\)|<[^>]*>|\n/g," ").toLowerCase(),r=["api","configuration","usage","example","tutorial","guide","documentation","setup","installation","usage","examples","howto","faq","reference","overview","introduction","concept","architecture","design","implementation","deployment","testing","troubleshooting","best practices","tips","tricks"].filter(u=>t.includes(u)),o=t.split(/\s+/).filter(u=>u.length>3),i={};o.forEach(u=>{i[u]=(i[u]||0)+1});let a=Object.entries(i).sort(([,u],[,p])=>p-u).map(([u])=>u).slice(0,5),c=[...r,...a];return Array.from(new Set(c))}},Vu=new Yn;Ts=Vu});import{readFileSync as Gu,existsSync as Ho,statSync as qu}from"fs";import{join as zo}from"path";import{globSync as qd}from"glob";import{Document as Jd}from"flexsearch";async function Qt(s){return await Ju.execute(s)}var Xn,Ju,Ps,La=S(()=>{G();Ra();pt();Xn=class extends R{getDefinition(){return{name:"search-docs",description:`Search for content in documentation files using keywords and regular expressions.
518
616
 
519
617
  \u{1F4CB} USE CASES:
520
618
  - Find information in project documentation
@@ -543,32 +641,9 @@ Returns an array of matching file paths.`,input_schema:{type:"object",properties
543
641
  \u{1F517} RELATED TOOLS:
544
642
  - read: View the full content of files found in search results
545
643
  - grep: Search for code patterns in source files (complementary to documentation search)
546
- - glob: Find specific documentation files by pattern before searching`,input_schema:{type:"object",properties:{query:{type:"string",description:"Search query string or regular expression pattern"},path:{type:"string",description:"Documentation directory or file path (default: .niums/docs)"},maxResults:{type:"number",description:"Maximum number of results to return (default: 10)"}},required:["query"]}}}execute(e){try{let t=e.path||".niums/docs",n=e.maxResults||10,{query:r}=e;if(!tg(t))return`Documentation directory not found: ${t}`;let s=process.cwd(),a={nodir:!0,windowsPathsNoEscape:!0,absolute:!1,ignore:Ee(s),cwd:s},c=ng(t,"**/*.{md,markdown,txt,rst,html,htm}"),l=rg(c,a);if(l.length===0)return`No documentation files found in: ${t}`;let u=new RegExp(r,"i"),p=[];if(l.forEach(m=>{try{eg(m,"utf-8").split(`
547
- `).forEach((v,T)=>{if(u.test(v)){let f=this.calculateMatchScore(v,r,T);p.push({path:m,line:T+1,content:v.trim(),score:f})}})}catch{}}),p.length===0)return`No matches found for query: ${r} in ${l.length} files`;p.sort((m,h)=>h.score-m.score);let g=p.slice(0,n),d=[];return d.push(`Found ${p.length} matches in ${l.length} files, showing top ${g.length} results:`),g.forEach(m=>{d.push(`${m.path}:${m.line}: ${m.content}`)}),d}catch(t){return this.formatError("Search Docs",t)}}calculateMatchScore(e,t,n){let r=100/(e.length+1);return e.toLowerCase().startsWith(t.toLowerCase())&&(r+=50),e.toLowerCase()===t.toLowerCase()&&(r+=100),r+=100/(n+1),r}},lc=new jt;Gn=lc});import{readFileSync as gc,writeFileSync as og,existsSync as sg,mkdirSync as ig}from"fs";import{join as Bn}from"path";import{globSync as ag}from"glob";function qn(o={}){return pc.execute(o)}var _t,pc,Kn,dc=C(()=>{V();Dt();_t=class extends ${getDefinition(){return{name:"build-doc-index",description:`Build and update documentation index for efficient search.
548
-
549
- \u{1F4CB} USE CASES:
550
- - Create initial documentation index
551
- - Update index when docs are added or modified
552
- - Refresh index to ensure search accuracy
553
- - Maintain up-to-date metadata for docs
554
-
555
- \u{1F511} PARAMETERS:
556
- - path: Documentation directory path (default: ".niums/docs")
557
-
558
- \u{1F4A1} EXAMPLES:
559
- - build-doc-index() - Build index for default docs directory
560
- - build-doc-index({ path: ".niums/docs" }) - Build index for specific docs directory
561
- - build-doc-index({ path: "docs/" }) - Build index for custom docs location
562
-
563
- \u{1F4DD} RETURN VALUE:
564
- - Success message with index statistics
565
- - Path to generated index file
566
- - Number of documents indexed
567
- - Any warnings or errors encountered`,input_schema:{type:"object",properties:{path:{type:"string",description:"Documentation directory path (default: .niums/docs)"}}}}}execute(e){try{let t=e.path||".niums/docs",n=process.cwd(),r=Bn(n,t);if(!sg(r))return`Documentation directory not found: ${r}`;let i={nodir:!0,windowsPathsNoEscape:!0,absolute:!1,ignore:Ee(n),cwd:n},a=Bn(t,"**/*.{md,markdown,txt,rst,html,htm}"),c=ag(a,i);if(c.length===0)return`No documentation files found in: ${t}`;let l=[];c.forEach(d=>{try{let m=Bn(n,d),h=gc(m,"utf-8"),w=gc(m,"utf-8").length,v=this.extractDocMetadata(d,h,w);l.push(v)}catch{}});let u={documents:l,lastIndexed:new Date().toISOString(),totalDocuments:l.length},p=Bn(n,t);ig(p,{recursive:!0});let g=Bn(p,".index.json");return og(g,JSON.stringify(u,null,2),"utf-8"),`Successfully built documentation index:
568
- - Index file: ${g}
569
- - Total documents indexed: ${u.totalDocuments}
570
- - Last indexed: ${u.lastIndexed}
571
- - Documentation directory: ${t}`}catch(t){return this.formatError("Build Doc Index",t)}}extractDocMetadata(e,t,n){let r=this.extractTitle(e,t),s=this.extractSummary(t),i=this.extractKeywords(t),a=new Date().toISOString();return{path:e,title:r,summary:s,keywords:i,lastModified:a,size:n}}extractTitle(e,t){let n=t.match(/^#\s+(.+)$/m);if(n&&n[1])return n[1].trim();let r=t.match(/<h1[^>]*>(.+?)<\/h1>/i);return r&&r[1]?r[1].trim():(e.split(/[\\/]/).pop()||e).replace(/\.(md|markdown|txt|rst|html|htm)$/i,"").replace(/[-_]/g," ").replace(/\b\w/g,a=>a.toUpperCase())}extractSummary(e){let t=e.replace(/\s+/g," ").replace(/[#*_~`]|\[|\]|\(|\)|<[^>]*>|\n/g," ").trim();return t.length>150?t.substring(0,150)+"...":t}extractKeywords(e){let t=e.replace(/\s+/g," ").replace(/[#*_~`]|\[|\]|\(|\)|<[^>]*>|\n/g," ").toLowerCase(),r=["api","configuration","usage","example","tutorial","guide","documentation","setup","installation","usage","examples","howto","faq","reference","overview","introduction","concept","architecture","design","implementation","deployment","testing","troubleshooting","best practices","tips","tricks"].filter(u=>t.includes(u)),s=t.split(/\s+/).filter(u=>u.length>3),i={};s.forEach(u=>{i[u]=(i[u]||0)+1});let a=Object.entries(i).sort(([,u],[,p])=>p-u).map(([u])=>u).slice(0,5),c=[...r,...a];return Array.from(new Set(c))}},pc=new _t;Kn=pc});var ks={};j(ks,{BuildDocIndexTool:()=>_t,GlobTool:()=>Ft,GrepTool:()=>Ot,SearchDocsTool:()=>jt,buildDocIndex:()=>qn,buildDocIndexTool:()=>Kn,glob:()=>Wn,globTool:()=>Vn,grep:()=>zn,grepTool:()=>Hn,searchDocs:()=>Jn,searchDocsTool:()=>Gn});var Qr=C(()=>{sc();cc();uc();dc()});import{execSync as cg,exec as lg,spawnSync as ug}from"child_process";import*as Zr from"os";async function fc(){if(mc)return Es;mc=!0;try{let o=await import("iconv-lite");return Es=o.default||o,Es}catch{return console.warn("iconv-lite not available, using utf8 fallback for Windows encoding"),null}}function Yn(o){return Promise.resolve(Ut.execute(o))}var Es,mc,Nt,Ut,hc=C(()=>{V();Es=null,mc=!1;Nt=class o extends ${static HIGH_RISK_COMMANDS=["rm -rf","rm -r","del /q /s","erase /f /s","format","mkfs","dd if=","mv /force","shred","wipe","truncate -s 0","> filename","chmod -R 000","chown -R root:root"];isHighRiskCommand(e){if(!e)return!1;let t=e.toLowerCase().trim();return o.HIGH_RISK_COMMANDS.some(n=>t.includes(n.toLowerCase()))}isUnixCommand(e){return["ls","pwd","which","cat","rm","cp","mv","mkdir","grep","find","head","tail","touch","chmod","chown","ps","kill","ifconfig","netstat","top","df","du","wc","awk","sed","tar","gzip","ssh"].includes(e.toLowerCase())}convertUnixToWindowsCommand(e){let t={ls:"dir","ls -la":"dir","ls -l":"dir","ls -a":"dir /a",pwd:"cd",which:"where",cat:"type",rm:"del","rm -rf":"rmdir /s /q","rm -r":"rmdir /s /q",cp:"copy","cp -r":"xcopy /e /i /y",mv:"move",mkdir:"mkdir","mkdir -p":"mkdir",grep:"findstr",find:"findstr",head:"more",tail:"more +n",touch:"type nul >",chmod:"attrib",chown:"attrib",ps:"tasklist",kill:"taskkill",ifconfig:"ipconfig",netstat:"netstat",top:"tasklist /v",df:"wmic logicaldisk get size,freespace,caption",du:"dir /s",wc:'find /c /v ""'};if(t[e])return t[e];let n=Object.entries(t).sort((r,s)=>s[0].length-r[0].length);for(let[r,s]of n)if(e.startsWith(r+" ")){if(r==="rm -rf"||r==="rm -r"){let i=e.substring(r.length).trim();return`${s} ${i}`}return e.replace(r,s)}return e}getShellCommand(e){let t=Zr.platform(),n=e||"";return t==="win32"&&n&&(n=this.convertUnixToWindowsCommand(n)),t==="win32"?{shell:"cmd.exe",args:[],cmd:n}:{shell:"/bin/sh",args:["-c"],cmd:n}}getDefinition(){return{name:"shell",description:`Execute shell commands on the system with intelligent cross-platform support.
644
+ - glob: Find specific documentation files by pattern before searching`,input_schema:{type:"object",properties:{query:{type:"string",description:"Search query string or regular expression pattern"},path:{type:"string",description:"Documentation directory or file path (default: .niums/docs)"},maxResults:{type:"number",description:"Maximum number of results to return (default: 10)"}},required:["query"]}}}async execute(e){try{let t=e.path||".niums/docs",n=e.maxResults||10,{query:r}=e,o=process.cwd(),i=zo(o,t),a=zo(o,t,".flexindex.json");if(!Ho(i))return`Documentation directory not found: ${i}
645
+ Please create the directory or specify a valid path.`;let c=await this.checkIndexStatus(i,a);if(c.needsRebuild&&(console.log(`\u2139\uFE0F ${c.reason}`),await Xt({path:t}),console.log("\u2713 \u7D22\u5F15\u51C6\u5907\u5B8C\u6210")),!Ho(a))return"Failed to create index. Please check if the documentation directory contains valid files.";let l=JSON.parse(Gu(a,"utf-8")),u=new Jd({document:{id:"id",index:["title","content","keywords"],store:!0},tokenize:"forward",resolution:9,context:!0});for(let y of l.index)await u.import(y.key,y.data);let p=await u.searchAsync(r,{limit:n*3,enrich:!0}),g=[],m=new Set;for(let y of p)if(!(!y||!y.result))for(let w of y.result){let T=w.id;if(m.has(T))continue;m.add(T);let h=l.documents[T];h&&g.push({id:T,path:h.path,title:h.title,content:this.extractRelevantSnippet(h.content,r),score:this.calculateRelevanceScore(h,r),matchedFields:[y.field]})}if(g.length===0)return`No matches found for query: "${r}" in ${l.totalDocuments} documents.
646
+ Tip: Try different keywords or check if the index is up to date.`;g.sort((y,w)=>w.score-y.score);let d=g.slice(0,n),f=[];return f.push(`Found ${g.length} matches (showing top ${d.length}):`),f.push(""),d.forEach((y,w)=>{f.push(`${w+1}. \u{1F4C4} ${y.title}`),f.push(` Path: ${y.path}`),f.push(` Snippet: ${y.content}`),f.push(` Relevance: ${y.score.toFixed(2)} | Fields: ${y.matchedFields.join(", ")}`),f.push("")}),f}catch(t){return this.formatError("Search Docs",t)}}async checkIndexStatus(e,t){if(!Ho(t))return{needsRebuild:!0,reason:"\u7D22\u5F15\u4E0D\u5B58\u5728\uFF0C\u6B63\u5728\u9996\u6B21\u6784\u5EFA\u7D22\u5F15..."};try{let n=JSON.parse(Gu(t,"utf-8")),r=process.cwd(),i={nodir:!0,windowsPathsNoEscape:!0,absolute:!1,ignore:we(r),cwd:r},a=e.replace(r,"").replace(/^[\\\/]/,""),c=zo(a,"**/*.{md,markdown,txt,rst,html,htm}"),l=qd(c,i);if(l.length!==n.totalDocuments)return{needsRebuild:!0,reason:`\u6587\u6863\u6570\u91CF\u53D1\u751F\u53D8\u5316 (${n.totalDocuments} \u2192 ${l.length})\uFF0C\u6B63\u5728\u66F4\u65B0\u7D22\u5F15...`};let p=qu(t).mtimeMs;for(let g of l){let m=zo(r,g);if(Ho(m)&&qu(m).mtimeMs>p)return{needsRebuild:!0,reason:"\u68C0\u6D4B\u5230\u6587\u6863\u66F4\u65B0\uFF0C\u6B63\u5728\u91CD\u5EFA\u7D22\u5F15..."}}return{needsRebuild:!1}}catch{return{needsRebuild:!0,reason:"\u7D22\u5F15\u6587\u4EF6\u65E0\u6548\uFF0C\u6B63\u5728\u91CD\u5EFA\u7D22\u5F15..."}}}extractRelevantSnippet(e,t){let r=t.toLowerCase(),i=e.toLowerCase().indexOf(r);if(i===-1)return e.length>200?e.substring(0,200)+"...":e;let a=Math.max(0,i-50),c=Math.min(e.length,i+t.length+150),l=e.substring(a,c);return a>0&&(l="..."+l),c<e.length&&(l=l+"..."),l.trim()}calculateRelevanceScore(e,t){let n=0,r=t.toLowerCase();e.title.toLowerCase().includes(r)&&(n+=50,e.title.toLowerCase()===r&&(n+=100));let o=e.keywords.filter(c=>c.toLowerCase().includes(r));n+=o.length*20;let a=(e.content.toLowerCase().match(new RegExp(r,"g"))||[]).length;return n+=Math.min(a*5,50),n-=Math.log(e.size+1)*2,Math.max(0,n)}},Ju=new Xn;Ps=Ju});var ja={};B(ja,{BuildDocIndexTool:()=>Yn,GlobTool:()=>qn,GrepTool:()=>Jn,SearchDocsTool:()=>Xn,buildDocIndex:()=>Xt,buildDocIndexTool:()=>Ts,glob:()=>Ss,globTool:()=>Cs,grep:()=>ws,grepTool:()=>bs,searchDocs:()=>Qt,searchDocsTool:()=>Ps});var Vo=S(()=>{Wu();zu();La();Ra()});import{execSync as Kd,exec as Yd,spawnSync as Ku}from"child_process";import*as Go from"os";async function Xu(){if(Yu)return Da;Yu=!0;try{let s=await import("iconv-lite");return Da=s.default||s,Da}catch{return console.warn("iconv-lite not available, using utf8 fallback for Windows encoding"),null}}function ks(s){return Promise.resolve(Zn.execute(s))}var Da,Yu,Qn,Zn,Qu=S(()=>{G();Da=null,Yu=!1;Qn=class s extends R{static HIGH_RISK_COMMANDS=["rm -rf","rm -r","del /q /s","erase /f /s","format","mkfs","dd if=","mv /force","shred","wipe","truncate -s 0","> filename","chmod -R 000","chown -R root:root"];isHighRiskCommand(e){if(!e)return!1;let t=e.toLowerCase().trim();return s.HIGH_RISK_COMMANDS.some(n=>t.includes(n.toLowerCase()))}isUnixCommand(e){return["ls","pwd","which","cat","rm","cp","mv","mkdir","grep","find","head","tail","touch","chmod","chown","ps","kill","ifconfig","netstat","top","df","du","wc","awk","sed","tar","gzip","ssh"].includes(e.toLowerCase())}convertUnixToWindowsCommand(e){let t={ls:"dir","ls -la":"dir","ls -l":"dir","ls -a":"dir /a",pwd:"cd",which:"where",cat:"type",rm:"del","rm -rf":"rmdir /s /q","rm -r":"rmdir /s /q",cp:"copy","cp -r":"xcopy /e /i /y",mv:"move",mkdir:"mkdir","mkdir -p":"mkdir",grep:"findstr",find:"findstr",head:"more",tail:"more +n",touch:"type nul >",chmod:"attrib",chown:"attrib",ps:"tasklist",kill:"taskkill",ifconfig:"ipconfig",netstat:"netstat",top:"tasklist /v",df:"wmic logicaldisk get size,freespace,caption",du:"dir /s",wc:'find /c /v ""'};if(t[e])return t[e];let n=Object.entries(t).sort((r,o)=>o[0].length-r[0].length);for(let[r,o]of n)if(e.startsWith(r+" ")){if(r==="rm -rf"||r==="rm -r"){let i=e.substring(r.length).trim();return`${o} ${i}`}return e.replace(r,o)}return e}getShellCommand(e){let t=Go.platform(),n=e||"";return t==="win32"&&n&&(n=this.convertUnixToWindowsCommand(n)),t==="win32"?this.needsPowerShell(n)?{shell:"powershell.exe",args:["-Command"],cmd:n}:{shell:"cmd.exe",args:[],cmd:n}:{shell:"/bin/sh",args:["-c"],cmd:n}}needsPowerShell(e){let t=["Get-ChildItem","Get-Process","Get-Service","New-Item","Remove-Item","Copy-Item","Move-Item","Rename-Item","Set-Location","Get-Location","Invoke-Command","Select-Object","Where-Object","ForEach-Object","Sort-Object","Group-Object","Measure-Object","Out-File","Out-Null","Write-Host","Write-Output","Write-Error","Write-Warning","Write-Verbose","Write-Debug","Start-Process","Stop-Process","Restart-Service","Stop-Service","Start-Service","Get-Content","Set-Content","Add-Content","Clear-Content","Test-Path","Resolve-Path","Split-Path","Join-Path","Get-Item","Set-Item","Remove-ItemProperty","Get-ItemProperty","Set-ItemProperty","Add-Member","Remove-Member","ConvertTo-Json","ConvertFrom-Json","Format-Table","Format-List","Format-Wide","Format-Custom","Export-Csv","Import-Csv","Select-String","Measure-Command","Compare-Object","Group-Object","Sort-Object","Unique-Object","tee-object","more","less","cat","ls","pwd","cd","mkdir","rmdir","rm","cp","mv","copy","move","del","$_","$null","$true","$false","$env:","${}","@{","@(","| %{","| ?{","| select ","| where ","| foreach ","**/*","**/","*/**","**\\*","**\\","\\**"],n=e.toLowerCase();return t.some(r=>n.includes(r.toLowerCase()))}getDefinition(){return{name:"shell",description:`Execute shell commands on the system with intelligent cross-platform support.
572
647
 
573
648
  \u{1F30D} **\u667A\u80FD\u73AF\u5883\u611F\u77E5**
574
649
  \u6B64\u5DE5\u5177\u4F1A\u6839\u636E\u5F53\u524D\u8FD0\u884C\u5E73\u53F0\u81EA\u52A8\u4F18\u5316\u547D\u4EE4\u6267\u884C\uFF1A
@@ -635,15 +710,15 @@ Returns an array of matching file paths.`,input_schema:{type:"object",properties
635
710
  \u{1F3AF} Try this instead:
636
711
  dir
637
712
 
638
- \u26A0\uFE0F Please use Windows equivalent commands for better compatibility.`;let s=r[e.toLowerCase()],i=`\u274C Command Not Found: '${e}'
713
+ \u26A0\uFE0F Please use Windows equivalent commands for better compatibility.`;let o=r[e.toLowerCase()],i=`\u274C Command Not Found: '${e}'
639
714
 
640
715
  `;return i+=`\u{1F5A5}\uFE0F Current Environment: ${n}
641
716
 
642
- `,s?(i+=`\u{1F4E6} About: ${s.description}
717
+ `,o?(i+=`\u{1F4E6} About: ${o.description}
643
718
 
644
719
  `,i+=`\u{1F4A1} Installation Suggestion:
645
- `,t==="win32"&&s.win?i+=` ${s.win}
646
- `:t!=="win32"&&s.unix&&(i+=` ${s.unix}
720
+ `,t==="win32"&&o.win?i+=` ${o.win}
721
+ `:t!=="win32"&&o.unix&&(i+=` ${o.unix}
647
722
  `)):(i+=`\u{1F4A1} Suggestions:
648
723
  `,i+=` 1. Check if the command is correctly spelled
649
724
  `,i+=` 2. Verify that the required software is installed
@@ -660,38 +735,235 @@ Returns an array of matching file paths.`,input_schema:{type:"object",properties
660
735
  `,i+=` - dnf: sudo dnf install <package-name> (Fedora)
661
736
  `))),i+=`
662
737
  \u26A0\uFE0F Please install the required command before proceeding.
663
- `,i+=" The AI assistant cannot continue without this tool being available.",i}async execute(e){try{let{command:t,timeout:n=6e4,captureOutput:r=!0}=e;if(!t){let g=Zr.platform(),m=`Running on ${g} with ${g==="win32"?"cmd.exe":"/bin/sh"}`,h=`Executing command: ${t}`;return console.error("[SHELL TOOL ERROR] Command is undefined or null"),console.error("[SHELL TOOL ERROR] Input received:",JSON.stringify(e,null,2)),console.error("[SHELL TOOL ERROR] Stack trace:",new Error().stack),this.createToolResult({error:"Command is undefined or null",success:!1},`${m}
664
- ${h}
738
+ `,i+=" The AI assistant cannot continue without this tool being available.",i}async execute(e){try{let{command:t,timeout:n=6e4,captureOutput:r=!0}=e;if(!t){let g=Go.platform(),d=`Running on ${g} with ${g==="win32"?"cmd.exe":"/bin/sh"}`,f=`Executing command: ${t}`;return console.error("[SHELL TOOL ERROR] Command is undefined or null"),console.error("[SHELL TOOL ERROR] Input received:",JSON.stringify(e,null,2)),console.error("[SHELL TOOL ERROR] Stack trace:",new Error().stack),this.createToolResult({error:"Command is undefined or null",success:!1},`${d}
739
+ ${f}
665
740
 
666
741
  Command failed with error:
667
- TypeError: Command is undefined or null`)}let s=Zr.platform(),{shell:i,args:a,cmd:c}=this.getShellCommand(t),l={shell:i,timeout:n,encoding:"utf8",windowsHide:!0,windowsVerbatimArguments:s==="win32"},u=`Running on ${s} with ${i}`,p=`Executing command: ${t}`;if(r)try{let g="";if(s==="win32"){let d=`chcp 65001 >nul 2>&1 && ${c}`,m=ug("cmd.exe",["/c",d],{stdio:"pipe",windowsHide:!0,encoding:"buffer"}),h=m.stdout||Buffer.alloc(0),w=m.stderr||Buffer.alloc(0),v=Buffer.concat([h,w]);try{let T=await fc();if(T){let f=["cp936","gbk","utf8","gb2312","big5"],y=!1;for(let S of f)try{if(g=T.decode(v,S),/[\u4e00-\u9fff]/.test(g)||g.length>0){y=!0;break}}catch{continue}y||(g=v.toString("utf8"))}else g=v.toString("utf8");m.status===0&&g&&g.trim()&&(g+=`
742
+ TypeError: Command is undefined or null`)}let o=Go.platform(),{shell:i,args:a,cmd:c}=this.getShellCommand(t),l={shell:i,timeout:n,encoding:"utf8",windowsHide:!0,windowsVerbatimArguments:o==="win32"},u=`Running on ${o} with ${i}`,p=`Executing command: ${t}`;if(r)try{let g="",m;if(o==="win32"){if(i==="powershell.exe"){let w=`${c}`;w=w.replace(/&&/g,";"),m=Ku(i,[...a,w],{stdio:"pipe",windowsHide:!0,encoding:"buffer"})}else{let w=`chcp 65001 >nul 2>&1 && ${c}`;m=Ku("cmd.exe",["/c",w],{stdio:"pipe",windowsHide:!0,encoding:"buffer"})}let d=m.stdout||Buffer.alloc(0),f=m.stderr||Buffer.alloc(0),y=Buffer.concat([d,f]);try{let w=await Xu();if(w){let T=["cp936","gbk","utf8","gb2312","big5"],h=!1;for(let x of T)try{if(g=w.decode(y,x),/[\u4e00-\u9fff]/.test(g)||g.length>0){h=!0;break}}catch{continue}h||(g=y.toString("utf8"))}else g=y.toString("utf8");m.status===0&&g&&g.trim()&&(g+=`
668
743
 
669
- \u2705 Windows\u7F16\u7801\u5DF2\u4F18\u5316\u5904\u7406`)}catch{g=v.toString("utf8")}}else{let d=[...a,c].join(" ");g=cg(d,l).toString()}if(this.isCommandNotFoundError(g,s)){let d=this.extractCommandName(t),m=this.generateCommandNotFoundMessage(d,s);return this.createToolResult({error:g,success:!1,commandNotFound:!0},`${u}
744
+ \u2705 Windows\u7F16\u7801\u5DF2\u4F18\u5316\u5904\u7406`)}catch{g=y.toString("utf8")}}else{let d=[...a,c].join(" ");g=Kd(d,l).toString()}if(this.isCommandNotFoundError(g,o)){let d=this.extractCommandName(t),f=this.generateCommandNotFoundMessage(d,o);return this.createToolResult({error:g,success:!1,commandNotFound:!0},`${u}
670
745
  ${p}
671
746
 
672
- ${m}
747
+ ${f}
673
748
 
674
749
  Original error:
675
750
  ${g}`,!0)}return this.createToolResult(g,`${u}
676
751
  ${p}
677
752
 
678
753
  Command output:
679
- ${g}`)}catch(g){let d="";if(s==="win32"&&g.stderr){let m=Buffer.isBuffer(g.stderr)?g.stderr:Buffer.from(g.stderr),h=await fc();if(h)try{let w=["cp936","gbk","utf8","gb2312"],v="";for(let T of w)try{if(v=h.decode(m,T),v.length>0){d+=v;break}}catch{continue}v||(d+=m.toString("utf8"))}catch{d+=m.toString("utf8")}else d+=m.toString("utf8")}else g.stderr&&(d+=g.stderr),g.stdout&&(d+=g.stdout),d||(d=String(g));if(this.isCommandNotFoundError(d,s)){let m=this.extractCommandName(t),h=this.generateCommandNotFoundMessage(m,s),w=h;return s==="win32"&&this.isUnixCommand(m)&&(w=`\u{1F504} Command Auto-Conversion: Unix command '${m}' was automatically converted to Windows equivalent
754
+ ${g}`)}catch(g){let m="";if(o==="win32"&&g.stderr){let d=Buffer.isBuffer(g.stderr)?g.stderr:Buffer.from(g.stderr),f=await Xu();if(f)try{let y=["cp936","gbk","utf8","gb2312"],w="";for(let T of y)try{if(w=f.decode(d,T),w.length>0){m+=w;break}}catch{continue}w||(m+=d.toString("utf8"))}catch{m+=d.toString("utf8")}else m+=d.toString("utf8")}else g.stderr&&(m+=g.stderr),g.stdout&&(m+=g.stdout),m||(m=String(g));if(this.isCommandNotFoundError(m,o)){let d=this.extractCommandName(t),f=this.generateCommandNotFoundMessage(d,o),y=f;return o==="win32"&&this.isUnixCommand(d)&&(y=`\u{1F504} Command Auto-Conversion: Unix command '${d}' was automatically converted to Windows equivalent
680
755
 
681
- ${h}`),this.createToolResult({error:d,success:!1,commandNotFound:!0},`${u}
756
+ ${f}`),this.createToolResult({error:m,success:!1,commandNotFound:!0},`${u}
682
757
  ${p}
683
758
 
684
- ${w}
759
+ ${y}
685
760
 
686
761
  Original error:
687
- ${d}`,!0)}return this.createToolResult({error:d,success:!1},`${u}
762
+ ${m}`,!0)}return this.createToolResult({error:m,success:!1},`${u}
688
763
  ${p}
689
764
 
690
765
  Command failed with error:
691
- ${d}`,!0)}else{let g=t;s==="win32"?g=`chcp 65001 > nul && ${c}`:g=[...a,c].join(" ");let d=lg(g,l);return this.createToolResult({success:!0,message:"Command started in background"},`${u}
766
+ ${m}`,!0)}else{let g=t;o==="win32"?g=`chcp 65001 > nul && ${c}`:g=[...a,c].join(" ");let m=Yd(g,l);return this.createToolResult({success:!0,message:"Command started in background"},`${u}
692
767
  ${p}
693
768
 
694
- Command started in background. No output will be captured.`,!0)}}catch(t){return this.formatError("Cannot execute shell command",t)}}formatAction(e){let t=super.formatAction(e);return this.isHighRiskCommand(e.command)?`${t} \u26A0\uFE0F HIGH RISK COMMAND - Requires confirmation!`:t}},Ut=new Nt});var Ps={};j(Ps,{ShellTool:()=>Nt,shell:()=>Yn,shellTool:()=>Ut});var eo=C(()=>{hc()});var Ms={};j(Ms,{THINK_TOOL:()=>to,ThinkTool:()=>ot,extractThought:()=>no,isThinkTool:()=>zt,think:()=>Wt,thinkTool:()=>Vt});function Wt(o){return $s.execute(o)}function zt(o){return o==="think"}function no(o){if(!o||!o.function||o.function.name!=="think")return null;try{return JSON.parse(o.function.arguments).thought||null}catch{return null}}var ot,$s,Vt,to,Xn=C(()=>{V();ot=class extends ${getDefinition(){return{name:"think",description:`Use this tool to think, reason, and reflect before taking actions.
769
+ Command started in background. No output will be captured.`,!0)}}catch(t){return this.formatError("Cannot execute shell command",t)}}formatAction(e){let t=super.formatAction(e);return this.isHighRiskCommand(e.command)?`${t} \u26A0\uFE0F HIGH RISK COMMAND - Requires confirmation!`:t}},Zn=new Qn});import{exec as Xd,spawnSync as Qd}from"child_process";import*as Fa from"os";function Es(s){return Promise.resolve(tr.execute(s))}var er,tr,Zu=S(()=>{G();er=class s extends R{static HIGH_RISK_COMMANDS=["rm -rf","rm -r","sudo rm","mkfs","dd if=","shred","wipe","truncate -s 0","> /dev/","chmod -R 000","chown -R root:root",":(){ :|:& };:"];isHighRiskCommand(e){if(!e)return!1;let t=e.toLowerCase().trim();return s.HIGH_RISK_COMMANDS.some(n=>t.includes(n.toLowerCase()))}getDefinition(){return{name:"bash",description:`Execute bash commands with full bash shell features (Unix/Linux/macOS only).
770
+
771
+ \u{1F41A} **Bash Shell Features**
772
+ This tool provides access to the full bash shell with advanced features:
773
+ - Complex scripting with loops, conditions, and functions
774
+ - Advanced text processing with awk, sed, grep
775
+ - Process management and job control
776
+ - Environment variable manipulation
777
+ - Command substitution and process substitution
778
+ - Bash-specific syntax (arrays, associative arrays, etc.)
779
+
780
+ \u{1F4CB} **USE CASES:**
781
+ - Complex shell scripting with bash-specific syntax
782
+ - Advanced text processing and data manipulation
783
+ - System administration tasks
784
+ - Build automation with bash features
785
+ - Git operations and version control
786
+ - Package management (apt, yum, brew, etc.)
787
+
788
+ \u26A0\uFE0F **CRITICAL SAFETY FEATURES:**
789
+ - High-risk commands (rm -rf, dd, etc.) require user confirmation
790
+ - Configurable timeout protection
791
+ - Command not found detection with helpful suggestions
792
+
793
+ \u{1F511} **PARAMETERS:**
794
+ - command: Bash command or script to execute (required)
795
+ - timeout: Maximum execution time in milliseconds (default: 60000)
796
+ - captureOutput: Whether to capture and return command output (default: true)
797
+
798
+ \u{1F4A1} **BASH-SPECIFIC EXAMPLES:**
799
+ - bash({ command: "for i in {1..5}; do echo $i; done" }) - Bash loop
800
+ - bash({ command: "arr=(a b c); echo \${arr[@]}" }) - Bash arrays
801
+ - bash({ command: "if [[ -f file.txt ]]; then cat file.txt; fi" }) - Conditional execution
802
+ - bash({ command: "find . -name '*.js' | xargs grep 'function'" }) - Pipeline with xargs
803
+ - bash({ command: "npm install && npm test" }) - Chained commands
804
+ - bash({ command: "export VAR=value && echo $VAR" }) - Environment variables
805
+
806
+ \u{1F4DD} **RETURN VALUE:**
807
+ - Command output with execution details
808
+ - Helpful error messages with installation suggestions
809
+ - Execution status and success flag
810
+
811
+ \u{1F3AF} **WHEN TO USE:**
812
+ - Use this tool when you need bash-specific features
813
+ - Use this tool for complex shell scripting
814
+ - Use the generic 'shell' tool for simple cross-platform commands`,input_schema:{type:"object",properties:{command:{type:"string",description:"Bash command or script to execute"},timeout:{type:"number",description:"Maximum execution time in milliseconds (default: 60000)",default:6e4},captureOutput:{type:"boolean",description:"Whether to capture and return command output (default: true)",default:!0}},required:["command"]},requiresConfirmation:!1}}getDynamicDefinition(e){return{...this.getDefinition(),requiresConfirmation:this.isHighRiskCommand(e.command)}}isCommandNotFoundError(e){if(!e)return!1;let t=e.toLowerCase();return["command not found","not found","no such file or directory","cannot find","bash: command not found","sh: command not found","zsh: command not found"].some(r=>t.includes(r))}extractCommandName(e){let t=e?e.trim():"",n=t.match(/^(\S+)/);return n?n[1]:t}generateCommandNotFoundMessage(e){let t=Fa.platform(),n=t==="darwin"?"macOS":"Linux",o={git:{darwin:"Install using: brew install git",linux:"Install using: sudo apt-get install git (Ubuntu/Debian) or sudo yum install git (CentOS/RHEL)",description:"Version control system"},python:{darwin:"Install using: brew install python3",linux:"Install using: sudo apt-get install python3 (Ubuntu/Debian) or sudo yum install python3 (CentOS/RHEL)",description:"Python programming language"},node:{darwin:"Install using: brew install node",linux:"Install using: sudo apt-get install nodejs (Ubuntu/Debian) or sudo yum install nodejs (CentOS/RHEL)",description:"Node.js JavaScript runtime"},npm:{darwin:"Install Node.js (includes npm): brew install node",linux:"Install Node.js (includes npm): sudo apt-get install nodejs npm",description:"Node Package Manager (comes with Node.js)"},docker:{darwin:"Install using: brew install docker",linux:"Install using: sudo apt-get install docker.io (Ubuntu/Debian) or sudo yum install docker (CentOS/RHEL)",description:"Container platform"},curl:{darwin:"Usually pre-installed. If missing: brew install curl",linux:"Install using: sudo apt-get install curl (Ubuntu/Debian) or sudo yum install curl (CentOS/RHEL)",description:"Command-line tool for transferring data with URLs"},wget:{darwin:"Install using: brew install wget",linux:"Install using: sudo apt-get install wget (Ubuntu/Debian) or sudo yum install wget (CentOS/RHEL)",description:"Network downloader"},make:{darwin:"Install using: xcode-select --install",linux:"Install using: sudo apt-get install build-essential (Ubuntu/Debian) or sudo yum groupinstall 'Development Tools' (CentOS/RHEL)",description:"Build automation tool"},gcc:{darwin:"Install using: xcode-select --install",linux:"Install using: sudo apt-get install build-essential (Ubuntu/Debian) or sudo yum groupinstall 'Development Tools' (CentOS/RHEL)",description:"GNU Compiler Collection"}}[e.toLowerCase()],i=`\u274C Command Not Found: '${e}'
815
+
816
+ `;return i+=`\u{1F5A5}\uFE0F Current Environment: ${n}
817
+
818
+ `,o?(i+=`\u{1F4E6} About: ${o.description}
819
+
820
+ `,i+=`\u{1F4A1} Installation Suggestion:
821
+ `,t==="darwin"&&o.darwin?i+=` ${o.darwin}
822
+ `:t!=="darwin"&&o.linux&&(i+=` ${o.linux}
823
+ `)):(i+=`\u{1F4A1} Suggestions:
824
+ `,i+=` 1. Check if the command is correctly spelled
825
+ `,i+=` 2. Verify that the required software is installed
826
+ `,i+=` 3. Check if the command is in your system PATH
827
+ `,i+=` 4. Try using package managers:
828
+ `,t==="darwin"?(i+=` - Homebrew: brew install <package-name>
829
+ `,i+=` - MacPorts: port install <package-name>
830
+ `):(i+=` - apt: sudo apt-get install <package-name> (Ubuntu/Debian)
831
+ `,i+=` - yum: sudo yum install <package-name> (CentOS/RHEL)
832
+ `,i+=` - dnf: sudo dnf install <package-name> (Fedora)
833
+ `)),i+=`
834
+ \u26A0\uFE0F Please install the required command before proceeding.`,i}async execute(e){try{let{command:t,timeout:n=6e4,captureOutput:r=!0}=e;if(!t)return this.createToolResult({error:"Command is undefined or null",success:!1},`Executing bash command: ${t}
835
+
836
+ Command failed with error:
837
+ TypeError: Command is undefined or null`);let o=Fa.platform(),i="/bin/bash",a=`Running on ${o} with ${i}`,c=`Executing bash command: ${t}`;if(r)try{let l=Qd(i,["-c",t],{stdio:"pipe",encoding:"utf8",timeout:n}),u=(l.stdout||"")+(l.stderr||"");if(this.isCommandNotFoundError(u)){let p=this.extractCommandName(t),g=this.generateCommandNotFoundMessage(p);return this.createToolResult({error:u,success:!1,commandNotFound:!0},`${a}
838
+ ${c}
839
+
840
+ ${g}
841
+
842
+ Original error:
843
+ ${u}`,!0)}return l.status!==0&&l.status!==null?this.createToolResult({error:u,success:!1,exitCode:l.status},`${a}
844
+ ${c}
845
+
846
+ Command failed with exit code ${l.status}:
847
+ ${u}`,!0):this.createToolResult(u,`${a}
848
+ ${c}
849
+
850
+ Command output:
851
+ ${u}`)}catch(l){let u=(l.stderr||"")+(l.stdout||"")+String(l);if(this.isCommandNotFoundError(u)){let p=this.extractCommandName(t),g=this.generateCommandNotFoundMessage(p);return this.createToolResult({error:u,success:!1,commandNotFound:!0},`${a}
852
+ ${c}
853
+
854
+ ${g}
855
+
856
+ Original error:
857
+ ${u}`,!0)}return this.createToolResult({error:u,success:!1},`${a}
858
+ ${c}
859
+
860
+ Command failed with error:
861
+ ${u}`,!0)}else{let l=Xd(t,{shell:i,timeout:n,encoding:"utf8"});return this.createToolResult({success:!0,message:"Command started in background"},`${a}
862
+ ${c}
863
+
864
+ Command started in background. No output will be captured.`,!0)}}catch(t){return this.formatError("Cannot execute bash command",t)}}formatAction(e){let t=super.formatAction(e);return this.isHighRiskCommand(e.command)?`${t} \u26A0\uFE0F HIGH RISK COMMAND - Requires confirmation!`:t}},tr=new er});import{exec as Zd,spawnSync as ef}from"child_process";import*as np from"os";async function tp(){if(ep)return Oa;ep=!0;try{let s=await import("iconv-lite");return Oa=s.default||s,Oa}catch{return console.warn("iconv-lite not available, using utf8 fallback for Windows encoding"),null}}function $s(s){return Promise.resolve(rr.execute(s))}var Oa,ep,nr,rr,rp=S(()=>{G();Oa=null,ep=!1;nr=class s extends R{static HIGH_RISK_COMMANDS=["Remove-Item -Recurse","Remove-Item -Force","rd /s /q","rmdir /s /q","del /q /s","format","Clear-Disk","Initialize-Disk","Remove-Partition","Format-Volume","Stop-Computer","Restart-Computer","Remove-ADUser","Disable-ADAccount"];isHighRiskCommand(e){if(!e)return!1;let t=e.toLowerCase().trim();return s.HIGH_RISK_COMMANDS.some(n=>t.includes(n.toLowerCase()))}getDefinition(){return{name:"powershell",description:`Execute PowerShell commands with full PowerShell features (Windows only).
865
+
866
+ \u26A1 **PowerShell Features**
867
+ This tool provides access to the full PowerShell shell with advanced features:
868
+ - Object-oriented pipeline (not just text)
869
+ - .NET Framework integration
870
+ - Advanced cmdlets (Get-ChildItem, Select-Object, Where-Object, etc.)
871
+ - PowerShell-specific syntax and operators
872
+ - Complex scripting with functions and modules
873
+ - Windows system administration
874
+ - Active Directory and Exchange management
875
+
876
+ \u{1F4CB} **USE CASES:**
877
+ - Windows system administration tasks
878
+ - Complex PowerShell scripts with cmdlets
879
+ - File and registry operations
880
+ - Process and service management
881
+ - .NET object manipulation
882
+ - Active Directory operations
883
+ - Package management with winget, chocolatey, or scoop
884
+
885
+ \u26A0\uFE0F **CRITICAL SAFETY FEATURES:**
886
+ - High-risk commands (Remove-Item -Recurse, Format-Volume, etc.) require user confirmation
887
+ - Automatic UTF-8 encoding handling for Chinese characters
888
+ - Configurable timeout protection
889
+ - Command not found detection with helpful suggestions
890
+
891
+ \u{1F511} **PARAMETERS:**
892
+ - command: PowerShell command or script to execute (required)
893
+ - timeout: Maximum execution time in milliseconds (default: 60000)
894
+ - captureOutput: Whether to capture and return command output (default: true)
895
+
896
+ \u{1F4A1} **POWERSHELL-SPECIFIC EXAMPLES:**
897
+ - powershell({ command: "Get-ChildItem -Recurse | Where-Object {$_.Length -gt 1MB}" }) - Find large files
898
+ - powershell({ command: "Get-Process | Sort-Object CPU -Descending | Select-Object -First 5" }) - Top CPU processes
899
+ - powershell({ command: "$env:PATH -split ';' | ForEach-Object {$_}" }) - List PATH entries
900
+ - powershell({ command: "Get-Service | Where-Object {$_.Status -eq 'Running'}" }) - List running services
901
+ - powershell({ command: "(Get-Content file.txt) | ForEach-Object {$_.ToUpper()} | Set-Content output.txt" }) - Process file
902
+ - powershell({ command: "Test-Path -Path 'C:\\Program Files' -PathType Container" }) - Check if directory exists
903
+ - powershell({ command: "Get-WmiObject Win32_ComputerSystem" }) - Get system information
904
+
905
+ \u{1F4DD} **RETURN VALUE:**
906
+ - Command output with execution details
907
+ - Automatic encoding handling for non-ASCII characters
908
+ - Helpful error messages with installation suggestions
909
+ - Execution status and success flag
910
+
911
+ \u{1F3AF} **WHEN TO USE:**
912
+ - Use this tool when you need PowerShell-specific features
913
+ - Use this tool for Windows system administration
914
+ - Use this tool for .NET object manipulation
915
+ - Use the generic 'shell' tool for simple cross-platform commands`,input_schema:{type:"object",properties:{command:{type:"string",description:"PowerShell command or script to execute"},timeout:{type:"number",description:"Maximum execution time in milliseconds (default: 60000)",default:6e4},captureOutput:{type:"boolean",description:"Whether to capture and return command output (default: true)",default:!0}},required:["command"]},requiresConfirmation:!1}}getDynamicDefinition(e){return{...this.getDefinition(),requiresConfirmation:this.isHighRiskCommand(e.command)}}isCommandNotFoundError(e){if(!e)return!1;let t=e.toLowerCase();return["\u4E0D\u662F\u5185\u90E8\u6216\u5916\u90E8\u547D\u4EE4","\u4E0D\u662F\u53EF\u8FD0\u884C\u7684\u7A0B\u5E8F","is not recognized as","\u65E0\u6CD5\u5C06","\u627E\u4E0D\u5230\u547D\u4EE4","command not found","cmdlet \u4E0D\u5B58\u5728","\u65E0\u6CD5\u8BC6\u522B","term '","name of a cmdlet","commandnotfoundexception"].some(r=>t.includes(r))}extractCommandName(e){let t=e?e.trim():"",n=t.match(/^(\S+)/);return n?n[1]:t}generateCommandNotFoundMessage(e){let n={git:{install:"Download from https://git-scm.com/download/win or use 'winget install Git.Git'",description:"Version control system"},python:{install:"Download from https://www.python.org/downloads/ or use 'winget install Python.Python.3'",description:"Python programming language"},node:{install:"Download from https://nodejs.org/ or use 'winget install OpenJS.NodeJS'",description:"Node.js JavaScript runtime"},npm:{install:"Install Node.js from https://nodejs.org/ (includes npm)",description:"Node Package Manager (comes with Node.js)"},docker:{install:"Download Docker Desktop from https://www.docker.com/products/docker-desktop",description:"Container platform"},winget:{install:"Built-in on Windows 10 1809+. Update from Microsoft Store: 'App Installer'",description:"Windows Package Manager"},choco:{install:"Install from https://chocolatey.org/install",description:"Chocolatey Package Manager"},scoop:{install:"Install using: iwr -useb get.scoop.sh | iex",description:"Scoop Package Manager"},code:{install:"Install VS Code from https://code.visualstudio.com/ and add to PATH during installation",description:"Visual Studio Code editor"}}[e.toLowerCase()],r=`\u274C Command Not Found: '${e}'
916
+
917
+ `;return r+=`\u{1F5A5}\uFE0F Current Environment: Windows (PowerShell)
918
+
919
+ `,n?(r+=`\u{1F4E6} About: ${n.description}
920
+
921
+ `,r+=`\u{1F4A1} Installation Suggestion:
922
+ `,n.install&&(r+=` ${n.install}
923
+ `)):(r+=`\u{1F4A1} Suggestions:
924
+ `,r+=` 1. Check if the command is correctly spelled
925
+ `,r+=` 2. Verify that the required software is installed
926
+ `,r+=` 3. Check if the command is in your system PATH
927
+ `,r+=` 4. Try searching in Windows Store or use package managers like:
928
+ `,r+=` - winget (built-in): winget search <package-name>
929
+ `,r+=` - Chocolatey: choco install <package-name>
930
+ `,r+=` - Scoop: scoop install <package-name>
931
+ `),r+=`
932
+ \u26A0\uFE0F Please install the required command before proceeding.`,r}async execute(e){try{let{command:t,timeout:n=6e4,captureOutput:r=!0}=e;if(!t)return this.createToolResult({error:"Command is undefined or null",success:!1},`Executing PowerShell command: ${t}
933
+
934
+ Command failed with error:
935
+ TypeError: Command is undefined or null`);let o=np.platform(),i="powershell.exe",a=`Running on ${o} with ${i}`,c=`Executing PowerShell command: ${t}`;if(r)try{let l=`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; ${t}`,u=ef(i,["-Command",l],{stdio:"pipe",windowsHide:!0,encoding:"buffer",timeout:n}),p=u.stdout||Buffer.alloc(0),g=u.stderr||Buffer.alloc(0),m=Buffer.concat([p,g]),d="";try{let f=await tp();if(f){let y=["utf8","cp936","gbk","gb2312"],w=!1;for(let T of y)try{if(d=f.decode(m,T),d.length>0){w=!0;break}}catch{continue}w||(d=m.toString("utf8"))}else d=m.toString("utf8")}catch{d=m.toString("utf8")}if(this.isCommandNotFoundError(d)){let f=this.extractCommandName(t),y=this.generateCommandNotFoundMessage(f);return this.createToolResult({error:d,success:!1,commandNotFound:!0},`${a}
936
+ ${c}
937
+
938
+ ${y}
939
+
940
+ Original error:
941
+ ${d}`,!0)}return u.status!==0&&u.status!==null?this.createToolResult({error:d,success:!1,exitCode:u.status},`${a}
942
+ ${c}
943
+
944
+ Command failed with exit code ${u.status}:
945
+ ${d}`,!0):this.createToolResult(d,`${a}
946
+ ${c}
947
+
948
+ Command output:
949
+ ${d}`)}catch(l){let u="";if(l.stderr){let p=Buffer.isBuffer(l.stderr)?l.stderr:Buffer.from(l.stderr),g=await tp();if(g)try{let m=["utf8","cp936","gbk","gb2312"],d="";for(let f of m)try{if(d=g.decode(p,f),d.length>0){u+=d;break}}catch{continue}d||(u+=p.toString("utf8"))}catch{u+=p.toString("utf8")}else u+=p.toString("utf8")}if(l.stdout&&(u+=l.stdout),u||(u=String(l)),this.isCommandNotFoundError(u)){let p=this.extractCommandName(t),g=this.generateCommandNotFoundMessage(p);return this.createToolResult({error:u,success:!1,commandNotFound:!0},`${a}
950
+ ${c}
951
+
952
+ ${g}
953
+
954
+ Original error:
955
+ ${u}`,!0)}return this.createToolResult({error:u,success:!1},`${a}
956
+ ${c}
957
+
958
+ Command failed with error:
959
+ ${u}`,!0)}else{let l=`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; ${t}`,u=Zd(l,{shell:i,timeout:n,encoding:"utf8",windowsHide:!0});return this.createToolResult({success:!0,message:"Command started in background"},`${a}
960
+ ${c}
961
+
962
+ Command started in background. No output will be captured.`,!0)}}catch(t){return this.formatError("Cannot execute PowerShell command",t)}}formatAction(e){let t=super.formatAction(e);return this.isHighRiskCommand(e.command)?`${t} \u26A0\uFE0F HIGH RISK COMMAND - Requires confirmation!`:t}},rr=new nr});var Na={};B(Na,{BashTool:()=>er,PowerShellTool:()=>nr,ShellTool:()=>Qn,bash:()=>Es,bashTool:()=>tr,powershell:()=>$s,powershellTool:()=>rr,shell:()=>ks,shellTool:()=>Zn});var qo=S(()=>{Qu();Zu();rp()});import v from"chalk";function op(s){let e=s.toLowerCase().trim();return tf[e]||e}function Ua(s,e){let t=op(e),n=sp[t]||sp.javascript,r=s;for(let o of n)r=r.replace(o.pattern,i=>o.style(i));return r}function nf(s,e){if(!_a)return Ua(s,e);let t=op(e);try{return _a.highlight(s,{language:t,ignoreIllegals:!0,theme:{keyword:v.magenta,built_in:v.cyan,type:v.cyan,literal:v.blue,number:v.yellow,regexp:v.red,string:v.green,subst:v.green,symbol:v.blue,class:v.yellow,function:v.cyan,title:v.cyan,params:v.white,comment:v.gray,doctag:v.gray,meta:v.gray,"meta-keyword":v.magenta,"meta-string":v.green,section:v.yellow,tag:v.cyan,name:v.cyan,"builtin-name":v.cyan,attr:v.yellow,attribute:v.yellow,variable:v.white,bullet:v.cyan,code:v.white,emphasis:v.italic,strong:v.bold,formula:v.yellow,link:v.blue.underline,quote:v.gray.italic,"selector-tag":v.magenta,"selector-id":v.yellow,"selector-class":v.yellow,"selector-attr":v.yellow,"selector-pseudo":v.cyan,"template-tag":v.magenta,"template-variable":v.yellow,addition:v.green,deletion:v.red}})}catch{return Ua(s,e)}}function ip(s,e="javascript"){return!s||s.trim().length===0?s:_a?nf(s,e):Ua(s,e)}var _a,tf,sp,ap=S(()=>{_a=null,tf={javascript:"javascript",typescript:"typescript","node.js":"javascript",nodejs:"javascript",js:"javascript",jsx:"javascript",ts:"typescript",tsx:"typescript",mjs:"javascript",cjs:"javascript",java:"java",jdk:"java",jvm:"java",python:"python",py:"python",go:"go",golang:"go",rust:"rust",rs:"rust",php:"php",ruby:"ruby",rb:"ruby","c#/.net":"csharp",csharp:"csharp",dotnet:"csharp",".net":"csharp","vb.net":"vbnet","f#":"fsharp",cs:"csharp",vb:"vbnet",fs:"fsharp",json:"json",xml:"xml",yaml:"yaml",yml:"yaml",html:"html",css:"css",scss:"scss",sass:"sass",less:"less",sql:"sql",shell:"bash",bash:"bash",sh:"bash",powershell:"powershell",ps1:"powershell",dockerfile:"dockerfile",markdown:"markdown",md:"markdown"},sp={javascript:[{pattern:/\b(const|let|var|function|return|if|else|for|while|class|import|export|async|await|try|catch|throw|new|typeof|instanceof)\b/g,style:v.magenta},{pattern:/(["'`])(?:(?=(\\?))\2.)*?\1/g,style:v.green},{pattern:/\/\/.*$/gm,style:v.gray},{pattern:/\/\*[\s\S]*?\*\//g,style:v.gray},{pattern:/\b\d+\.?\d*\b/g,style:v.yellow},{pattern:/\b(this|true|false|null|undefined)\b/g,style:v.blue}],typescript:[{pattern:/\b(const|let|var|function|return|if|else|for|while|class|import|export|async|await|try|catch|throw|new|typeof|instanceof|interface|type|enum)\b/g,style:v.magenta},{pattern:/(["'`])(?:(?=(\\?))\2.)*?\1/g,style:v.green},{pattern:/\/\/.*$/gm,style:v.gray},{pattern:/\/\*[\s\S]*?\*\//g,style:v.gray},{pattern:/\b\d+\.?\d*\b/g,style:v.yellow},{pattern:/\b(this|true|false|null|undefined)\b/g,style:v.blue}],python:[{pattern:/\b(def|class|import|from|return|if|elif|else|for|while|try|except|with|as|pass|break|continue|async|await)\b/g,style:v.magenta},{pattern:/(["'])(?:(?=(\\?))\2.)*?\1/g,style:v.green},{pattern:/#.*$/gm,style:v.gray},{pattern:/\b\d+\.?\d*\b/g,style:v.yellow},{pattern:/\b(True|False|None|self)\b/g,style:v.blue}],java:[{pattern:/\b(public|private|protected|static|final|class|interface|extends|implements|import|return|if|else|for|while|try|catch|throw|new)\b/g,style:v.magenta},{pattern:/(["'])(?:(?=(\\?))\2.)*?\1/g,style:v.green},{pattern:/\/\/.*$/gm,style:v.gray},{pattern:/\/\*[\s\S]*?\*\//g,style:v.gray},{pattern:/\b\d+\.?\d*\b/g,style:v.yellow},{pattern:/\b(this|true|false|null)\b/g,style:v.blue}],go:[{pattern:/\b(package|import|func|return|if|else|for|range|var|const|type|struct|interface|go|defer|chan|select|case|default)\b/g,style:v.magenta},{pattern:/(["'`])(?:(?=(\\?))\2.)*?\1/g,style:v.green},{pattern:/\/\/.*$/gm,style:v.gray},{pattern:/\/\*[\s\S]*?\*\//g,style:v.gray},{pattern:/\b\d+\.?\d*\b/g,style:v.yellow},{pattern:/\b(true|false|nil)\b/g,style:v.blue}],rust:[{pattern:/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|return|if|else|for|while|loop|match|async|await)\b/g,style:v.magenta},{pattern:/(["'])(?:(?=(\\?))\2.)*?\1/g,style:v.green},{pattern:/\/\/.*$/gm,style:v.gray},{pattern:/\/\*[\s\S]*?\*\//g,style:v.gray},{pattern:/\b\d+\.?\d*\b/g,style:v.yellow},{pattern:/\b(true|false|None|Some|Ok|Err|self|Self)\b/g,style:v.blue}],php:[{pattern:/\b(function|return|if|else|elseif|for|foreach|while|class|public|private|protected|static|namespace|use|try|catch|throw|new)\b/g,style:v.magenta},{pattern:/(["'])(?:(?=(\\?))\2.)*?\1/g,style:v.green},{pattern:/\/\/.*$/gm,style:v.gray},{pattern:/\/\*[\s\S]*?\*\//g,style:v.gray},{pattern:/\b\d+\.?\d*\b/g,style:v.yellow},{pattern:/\b(true|false|null|self)\b/g,style:v.blue},{pattern:/\$\w+/g,style:v.cyan}],ruby:[{pattern:/\b(def|class|module|include|extend|require|return|if|elsif|else|unless|case|when|for|while|do|end|begin|rescue|ensure|raise)\b/g,style:v.magenta},{pattern:/(["'])(?:(?=(\\?))\2.)*?\1/g,style:v.green},{pattern:/#.*$/gm,style:v.gray},{pattern:/\b\d+\.?\d*\b/g,style:v.yellow},{pattern:/\b(true|false|nil|self)\b/g,style:v.blue},{pattern:/@\w+/g,style:v.cyan}],csharp:[{pattern:/\b(public|private|protected|static|class|interface|namespace|using|return|if|else|for|foreach|while|try|catch|throw|new|async|await)\b/g,style:v.magenta},{pattern:/(["'])(?:(?=(\\?))\2.)*?\1/g,style:v.green},{pattern:/\/\/.*$/gm,style:v.gray},{pattern:/\/\*[\s\S]*?\*\//g,style:v.gray},{pattern:/\b\d+\.?\d*\b/g,style:v.yellow},{pattern:/\b(this|true|false|null)\b/g,style:v.blue}],json:[{pattern:/"[^"]*"(?=\s*:)/g,style:v.cyan},{pattern:/"[^"]*"(?!\s*:)/g,style:v.green},{pattern:/\b\d+\.?\d*\b/g,style:v.yellow},{pattern:/\b(true|false|null)\b/g,style:v.blue}],sql:[{pattern:/\b(SELECT|FROM|WHERE|JOIN|LEFT|RIGHT|INNER|OUTER|ON|AND|OR|ORDER BY|GROUP BY|INSERT|UPDATE|DELETE|CREATE|ALTER|DROP|TABLE|DATABASE)\b/gi,style:v.magenta},{pattern:/(["'])(?:(?=(\\?))\2.)*?\1/g,style:v.green},{pattern:/--.*$/gm,style:v.gray},{pattern:/\b\d+\.?\d*\b/g,style:v.yellow}],bash:[{pattern:/\b(if|then|else|elif|fi|for|while|do|done|case|esac|function|return)\b/g,style:v.magenta},{pattern:/(["'])(?:(?=(\\?))\2.)*?\1/g,style:v.green},{pattern:/#.*$/gm,style:v.gray},{pattern:/\b\d+\.?\d*\b/g,style:v.yellow},{pattern:/\$\w+/g,style:v.cyan}]}});var Ba={};B(Ba,{THINK_TOOL:()=>Jo,ThinkTool:()=>Zt,extractThought:()=>Ko,formatThoughtWithHighlight:()=>Yo,isThinkTool:()=>ir,think:()=>sr,thinkTool:()=>or});import cp from"chalk";function sr(s){return Wa.execute(s)}function ir(s){return s==="think"}function Ko(s){if(!s||!s.function||s.function.name!=="think")return null;try{return JSON.parse(s.function.arguments).thought||null}catch{return null}}function Yo(s){if(!s)return s;let e=/```(\w*)\n([\s\S]*?)```/g,t=s,n,r=[];for(;(n=e.exec(s))!==null;)r.push({fullMatch:n[0],language:n[1]||"javascript",code:n[2]});for(let{fullMatch:o,language:i,code:a}of r.reverse()){let c=ip(a.trim(),i),l=`
963
+ ${cp.gray("```"+i)}
964
+ ${c}
965
+ ${cp.gray("```")}
966
+ `;t=t.replace(o,l)}return t}var Zt,Wa,or,Jo,Is=S(()=>{G();ap();Zt=class extends R{getDefinition(){return{name:"think",description:`Use this tool to think, reason, and reflect before taking actions.
695
967
  This is a zero-side-effect tool that makes your thinking process observable.
696
968
 
697
969
  IMPORTANT: You should call this tool:
@@ -699,9 +971,281 @@ IMPORTANT: You should call this tool:
699
971
  - AFTER receiving an Observation (to reflect on the result)
700
972
  - When you need to analyze complex situations
701
973
 
702
- The thought content will be logged but won't change any data or state.`,input_schema:{type:"object",properties:{thought:{type:"string",description:"Your internal reasoning, analysis, or reflection. Be detailed and explicit about your thought process."}},required:["thought"]}}}execute(e){return"Noted. Continue with your action."}},$s=new ot;Vt=$s,to=$s.getDefinition()});var Fs={};j(Fs,{SYSTEM_PROMPT:()=>st,generateAgentMatchingPrompt:()=>Ds,generateSystemPrompt:()=>Cc,generateTaskComplexityEvaluationPrompt:()=>Is,generateTaskPlanningConversionPrompt:()=>Rs,generateTaskPlanningMarkdownPrompt:()=>Ls,generateTaskPlanningPrompt:()=>As});function Cc(o=Qn(),e="all"){let t=o.map(a=>`- ${a.name}: ${a.description}`).join(`
703
- `),n=yc.all,r=yc[e]||[];return`<instructions>
704
- ${[...new Set([...n,...r])].map(a=>gg[a]).join(`
974
+ CODE FORMATTING SUPPORT:
975
+ When planning code changes or designing implementations, use markdown code blocks for better readability:
976
+
977
+ Example 1 - Planning code structure:
978
+ think({
979
+ thought: "I need to add error handling. The structure should be:
980
+ \`\`\`typescript
981
+ try {
982
+ const result = await fetchData();
983
+ return result;
984
+ } catch (error) {
985
+ logger.error('Failed:', error);
986
+ throw error;
987
+ }
988
+ \`\`\`
989
+ This will handle errors gracefully and log them."
990
+ })
991
+
992
+ Example 2 - Describing specific line changes:
993
+ think({
994
+ thought: "Need to modify lines 15-20. Current code has issues. Should change to:
995
+ \`\`\`javascript
996
+ function calculate(a, b) {
997
+ if (typeof a !== 'number' || typeof b !== 'number') {
998
+ throw new TypeError('Arguments must be numbers');
999
+ }
1000
+ return a + b;
1001
+ }
1002
+ \`\`\`
1003
+ This adds type validation before calculation."
1004
+ })
1005
+
1006
+ The thought content will be logged with syntax highlighting for code blocks, but won't change any data or state.`,input_schema:{type:"object",properties:{thought:{type:"string",description:"Your internal reasoning, analysis, or reflection. Be detailed and explicit. Use markdown code blocks (```language...```) for code examples."}},required:["thought"]}}}execute(e){return"Noted. Continue with your action."}},Wa=new Zt;or=Wa,Jo=Wa.getDefinition()});var up={};B(up,{PlatformType:()=>lp,buildPlatformAwarePrompt:()=>cf,getCurrentPlatform:()=>Xo,getPlatformDisplayName:()=>Ha,getPlatformSpecificToolEnhancement:()=>lf,getPlatformSummary:()=>uf});import*as gt from"os";function Xo(){let s=gt.platform();switch(s){case"win32":return"win32";case"darwin":return"darwin";case"linux":return"linux";default:return C(`\u672A\u77E5\u5E73\u53F0\u7C7B\u578B: ${s}\uFF0C\u4F7F\u7528\u901A\u7528\u914D\u7F6E`),"unknown"}}function Ha(s){return{win32:"Windows",darwin:"macOS",linux:"Linux",unknown:"Unknown"}[s]}function rf(){return`
1007
+ \u{1F5A5}\uFE0F **\u5F53\u524D\u8FD0\u884C\u73AF\u5883: Windows**
1008
+
1009
+ **\u53EF\u7528\u7684Shell\u5DE5\u5177**\uFF1A
1010
+ 1. **shell\u5DE5\u5177\uFF08\u901A\u7528\uFF09**\uFF1A\u8DE8\u5E73\u53F0shell\u5DE5\u5177\uFF0C\u81EA\u52A8\u5904\u7406\u547D\u4EE4\u8F6C\u6362
1011
+ - \u9002\u7528\u4E8E\u7B80\u5355\u547D\u4EE4\u548C\u8DE8\u5E73\u53F0\u573A\u666F
1012
+ - \u81EA\u52A8\u5C06Unix\u547D\u4EE4\u8F6C\u6362\u4E3AWindows\u7B49\u4EF7\u547D\u4EE4\uFF08ls\u2192dir, pwd\u2192cd\u7B49\uFF09
1013
+ - \u81EA\u52A8\u9009\u62E9cmd.exe\u6216PowerShell
1014
+
1015
+ 2. **powershell\u5DE5\u5177\uFF08Windows\u4E13\u7528\uFF09**\uFF1A\u76F4\u63A5\u6267\u884CPowerShell\u547D\u4EE4
1016
+ - \u9002\u7528\u4E8E\u590D\u6742\u7684PowerShell\u811A\u672C\u548C\u7BA1\u9053\u64CD\u4F5C
1017
+ - \u652F\u6301PowerShell\u7279\u5B9A\u8BED\u6CD5\uFF08Get-ChildItem\u3001Where-Object\u7B49\uFF09
1018
+ - \u652F\u6301\u5BF9\u8C61\u7BA1\u9053\u548C.NET\u96C6\u6210
1019
+ - \u793A\u4F8B\uFF1Apowershell({ command: "Get-Process | Sort-Object CPU -Descending | Select-Object -First 5" })
1020
+
1021
+ **\u547D\u4EE4\u4F18\u5148\u7EA7\u89C4\u5219**\uFF1A
1022
+ - \u7B80\u5355\u547D\u4EE4\uFF1A\u4F7F\u7528shell\u5DE5\u5177\uFF08\u5982\uFF1Ashell({ command: "dir" })\uFF09
1023
+ - \u590D\u6742PowerShell\u811A\u672C\uFF1A\u4F7F\u7528powershell\u5DE5\u5177\uFF08\u5982\uFF1Apowershell({ command: "Get-ChildItem -Recurse | Where-Object {$_.Length -gt 1MB}" })\uFF09
1024
+ - \u8DE8\u5E73\u53F0\u547D\u4EE4\uFF1A\u4F7F\u7528shell\u5DE5\u5177\uFF08\u81EA\u52A8\u8F6C\u6362\uFF09
1025
+
1026
+ **\u5E38\u7528\u547D\u4EE4\u6620\u5C04**\uFF1A
1027
+ - \u5217\u51FA\u6587\u4EF6\uFF1Adir\uFF08\u4E0D\u8981\u4F7F\u7528ls\uFF09
1028
+ - \u67E5\u770B\u5F53\u524D\u76EE\u5F55\uFF1Acd\uFF08\u4E0D\u8981\u4F7F\u7528pwd\uFF09
1029
+ - \u67E5\u627E\u547D\u4EE4\uFF1Awhere\uFF08\u4E0D\u8981\u4F7F\u7528which\uFF09
1030
+ - \u67E5\u770B\u6587\u4EF6\u5185\u5BB9\uFF1Atype\uFF08\u4E0D\u8981\u4F7F\u7528cat\uFF09
1031
+ - \u5220\u9664\u6587\u4EF6\uFF1Adel\uFF08\u4E0D\u8981\u4F7F\u7528rm\uFF09
1032
+ - \u590D\u5236\u6587\u4EF6\uFF1Acopy\uFF08\u4E0D\u8981\u4F7F\u7528cp\uFF09
1033
+ - \u79FB\u52A8\u6587\u4EF6\uFF1Amove\uFF08\u4E0D\u8981\u4F7F\u7528mv\uFF09
1034
+ - \u641C\u7D22\u6587\u672C\uFF1Afindstr\uFF08\u4E0D\u8981\u4F7F\u7528grep\uFF09
1035
+ - \u67E5\u770B\u8FDB\u7A0B\uFF1Atasklist\uFF08\u4E0D\u8981\u4F7F\u7528ps\uFF09
1036
+ - \u7F51\u7EDC\u914D\u7F6E\uFF1Aipconfig\uFF08\u4E0D\u8981\u4F7F\u7528ifconfig\uFF09
1037
+
1038
+ **\u8DEF\u5F84\u5206\u9694\u7B26**\uFF1A
1039
+ - \u4F7F\u7528\u53CD\u659C\u6760 \\ \u6216\u6B63\u659C\u6760 / \uFF08Windows\u652F\u6301\u4E24\u79CD\uFF09
1040
+ - \u63A8\u8350\u4F7F\u7528\u6B63\u659C\u6760 / \u4EE5\u4FDD\u6301\u8DE8\u5E73\u53F0\u517C\u5BB9\u6027
1041
+
1042
+ **\u5305\u7BA1\u7406\u5668**\uFF1A
1043
+ - winget\uFF08Windows 10+\u5185\u7F6E\uFF09
1044
+ - Chocolatey\uFF08\u9700\u8981\u5B89\u88C5\uFF09
1045
+ - Scoop\uFF08\u9700\u8981\u5B89\u88C5\uFF09
1046
+
1047
+ **\u7F16\u7801\u6CE8\u610F\u4E8B\u9879**\uFF1A
1048
+ - Windows\u9ED8\u8BA4\u4F7F\u7528GBK/CP936\u7F16\u7801
1049
+ - shell\u548Cpowershell\u5DE5\u5177\u5DF2\u81EA\u52A8\u5904\u7406\u7F16\u7801\u95EE\u9898`}function sf(){return`
1050
+ \u{1F34E} **\u5F53\u524D\u8FD0\u884C\u73AF\u5883: macOS**
1051
+
1052
+ **\u53EF\u7528\u7684Shell\u5DE5\u5177**\uFF1A
1053
+ 1. **shell\u5DE5\u5177\uFF08\u901A\u7528\uFF09**\uFF1A\u8DE8\u5E73\u53F0shell\u5DE5\u5177
1054
+ - \u9002\u7528\u4E8E\u7B80\u5355\u547D\u4EE4\u548C\u8DE8\u5E73\u53F0\u573A\u666F
1055
+ - \u4F7F\u7528/bin/sh\u6267\u884C\u547D\u4EE4
1056
+
1057
+ 2. **bash\u5DE5\u5177\uFF08Unix\u4E13\u7528\uFF09**\uFF1A\u76F4\u63A5\u6267\u884Cbash\u547D\u4EE4
1058
+ - \u9002\u7528\u4E8E\u590D\u6742\u7684bash\u811A\u672C\u548C\u9AD8\u7EA7\u7279\u6027
1059
+ - \u652F\u6301bash\u7279\u5B9A\u8BED\u6CD5\uFF08\u6570\u7EC4\u3001\u5FAA\u73AF\u3001\u6761\u4EF6\u5224\u65AD\u7B49\uFF09
1060
+ - \u652F\u6301\u9AD8\u7EA7\u6587\u672C\u5904\u7406\uFF08awk\u3001sed\u3001grep\u7BA1\u9053\uFF09
1061
+ - \u793A\u4F8B\uFF1Abash({ command: "for i in {1..5}; do echo $i; done" })
1062
+
1063
+ **\u547D\u4EE4\u4F18\u5148\u7EA7\u89C4\u5219**\uFF1A
1064
+ - \u7B80\u5355\u547D\u4EE4\uFF1A\u4F7F\u7528shell\u5DE5\u5177\uFF08\u5982\uFF1Ashell({ command: "ls -la" })\uFF09
1065
+ - \u590D\u6742bash\u811A\u672C\uFF1A\u4F7F\u7528bash\u5DE5\u5177\uFF08\u5982\uFF1Abash({ command: "find . -name '*.js' | xargs grep 'function'" })\uFF09
1066
+ - \u8DE8\u5E73\u53F0\u547D\u4EE4\uFF1A\u4F7F\u7528shell\u5DE5\u5177
1067
+
1068
+ **\u5E38\u7528\u547D\u4EE4**\uFF1A
1069
+ - \u5217\u51FA\u6587\u4EF6\uFF1Als\u3001ls -la
1070
+ - \u67E5\u770B\u5F53\u524D\u76EE\u5F55\uFF1Apwd
1071
+ - \u67E5\u627E\u547D\u4EE4\uFF1Awhich
1072
+ - \u67E5\u770B\u6587\u4EF6\u5185\u5BB9\uFF1Acat
1073
+ - \u5220\u9664\u6587\u4EF6\uFF1Arm\u3001rm -rf
1074
+ - \u590D\u5236\u6587\u4EF6\uFF1Acp\u3001cp -r
1075
+ - \u79FB\u52A8\u6587\u4EF6\uFF1Amv
1076
+ - \u641C\u7D22\u6587\u672C\uFF1Agrep
1077
+ - \u67E5\u770B\u8FDB\u7A0B\uFF1Aps
1078
+ - \u7F51\u7EDC\u914D\u7F6E\uFF1Aifconfig
1079
+
1080
+ **\u8DEF\u5F84\u5206\u9694\u7B26**\uFF1A
1081
+ - \u4F7F\u7528\u6B63\u659C\u6760 /
1082
+
1083
+ **\u5305\u7BA1\u7406\u5668**\uFF1A
1084
+ - Homebrew\uFF08\u63A8\u8350\uFF09\uFF1Abrew install <package>
1085
+ - MacPorts\uFF1Aport install <package>
1086
+
1087
+ **macOS\u7279\u5B9A\u5DE5\u5177**\uFF1A
1088
+ - open\uFF1A\u6253\u5F00\u6587\u4EF6\u6216\u5E94\u7528
1089
+ - pbcopy/pbpaste\uFF1A\u526A\u8D34\u677F\u64CD\u4F5C
1090
+ - say\uFF1A\u6587\u672C\u8F6C\u8BED\u97F3
1091
+ - osascript\uFF1A\u6267\u884CAppleScript
1092
+
1093
+ **Shell\u73AF\u5883**\uFF1A
1094
+ - \u9ED8\u8BA4Shell\uFF1Azsh\uFF08macOS Catalina+\uFF09
1095
+ - \u53EF\u9009Shell\uFF1Abash\u3001fish`}function of(){return`
1096
+ \u{1F427} **\u5F53\u524D\u8FD0\u884C\u73AF\u5883: Linux**
1097
+
1098
+ **\u53EF\u7528\u7684Shell\u5DE5\u5177**\uFF1A
1099
+ 1. **shell\u5DE5\u5177\uFF08\u901A\u7528\uFF09**\uFF1A\u8DE8\u5E73\u53F0shell\u5DE5\u5177
1100
+ - \u9002\u7528\u4E8E\u7B80\u5355\u547D\u4EE4\u548C\u8DE8\u5E73\u53F0\u573A\u666F
1101
+ - \u4F7F\u7528/bin/sh\u6267\u884C\u547D\u4EE4
1102
+
1103
+ 2. **bash\u5DE5\u5177\uFF08Unix\u4E13\u7528\uFF09**\uFF1A\u76F4\u63A5\u6267\u884Cbash\u547D\u4EE4
1104
+ - \u9002\u7528\u4E8E\u590D\u6742\u7684bash\u811A\u672C\u548C\u9AD8\u7EA7\u7279\u6027
1105
+ - \u652F\u6301bash\u7279\u5B9A\u8BED\u6CD5\uFF08\u6570\u7EC4\u3001\u5FAA\u73AF\u3001\u6761\u4EF6\u5224\u65AD\u7B49\uFF09
1106
+ - \u652F\u6301\u9AD8\u7EA7\u6587\u672C\u5904\u7406\uFF08awk\u3001sed\u3001grep\u7BA1\u9053\uFF09
1107
+ - \u793A\u4F8B\uFF1Abash({ command: "for i in {1..5}; do echo $i; done" })
1108
+
1109
+ **\u547D\u4EE4\u4F18\u5148\u7EA7\u89C4\u5219**\uFF1A
1110
+ - \u7B80\u5355\u547D\u4EE4\uFF1A\u4F7F\u7528shell\u5DE5\u5177\uFF08\u5982\uFF1Ashell({ command: "ls -la" })\uFF09
1111
+ - \u590D\u6742bash\u811A\u672C\uFF1A\u4F7F\u7528bash\u5DE5\u5177\uFF08\u5982\uFF1Abash({ command: "find . -name '*.js' | xargs grep 'function'" })\uFF09
1112
+ - \u8DE8\u5E73\u53F0\u547D\u4EE4\uFF1A\u4F7F\u7528shell\u5DE5\u5177
1113
+
1114
+ **\u5E38\u7528\u547D\u4EE4**\uFF1A
1115
+ - \u5217\u51FA\u6587\u4EF6\uFF1Als\u3001ls -la
1116
+ - \u67E5\u770B\u5F53\u524D\u76EE\u5F55\uFF1Apwd
1117
+ - \u67E5\u627E\u547D\u4EE4\uFF1Awhich
1118
+ - \u67E5\u770B\u6587\u4EF6\u5185\u5BB9\uFF1Acat
1119
+ - \u5220\u9664\u6587\u4EF6\uFF1Arm\u3001rm -rf
1120
+ - \u590D\u5236\u6587\u4EF6\uFF1Acp\u3001cp -r
1121
+ - \u79FB\u52A8\u6587\u4EF6\uFF1Amv
1122
+ - \u641C\u7D22\u6587\u672C\uFF1Agrep
1123
+ - \u67E5\u770B\u8FDB\u7A0B\uFF1Aps
1124
+ - \u7F51\u7EDC\u914D\u7F6E\uFF1Aifconfig \u6216 ip
1125
+
1126
+ **\u8DEF\u5F84\u5206\u9694\u7B26**\uFF1A
1127
+ - \u4F7F\u7528\u6B63\u659C\u6760 /
1128
+
1129
+ **\u5305\u7BA1\u7406\u5668**\uFF08\u6839\u636E\u53D1\u884C\u7248\uFF09\uFF1A
1130
+ - Debian/Ubuntu\uFF1Aapt\u3001apt-get
1131
+ - \u5B89\u88C5\uFF1Asudo apt-get install <package>
1132
+ - \u66F4\u65B0\uFF1Asudo apt-get update
1133
+ - CentOS/RHEL\uFF1Ayum
1134
+ - \u5B89\u88C5\uFF1Asudo yum install <package>
1135
+ - Fedora\uFF1Adnf
1136
+ - \u5B89\u88C5\uFF1Asudo dnf install <package>
1137
+ - Arch Linux\uFF1Apacman
1138
+ - \u5B89\u88C5\uFF1Asudo pacman -S <package>
1139
+
1140
+ **Shell\u73AF\u5883**\uFF1A
1141
+ - \u9ED8\u8BA4Shell\uFF1Abash
1142
+ - \u53EF\u9009Shell\uFF1Azsh\u3001fish\u3001sh
1143
+
1144
+ **\u6743\u9650\u7BA1\u7406**\uFF1A
1145
+ - \u4F7F\u7528sudo\u6267\u884C\u9700\u8981\u7BA1\u7406\u5458\u6743\u9650\u7684\u547D\u4EE4
1146
+ - \u6CE8\u610F\u6587\u4EF6\u6743\u9650\uFF1Achmod\u3001chown`}function af(){return`
1147
+ \u{1F30D} **\u5F53\u524D\u8FD0\u884C\u73AF\u5883: \u901A\u7528**
1148
+
1149
+ **\u8DE8\u5E73\u53F0\u51B3\u7B56\u6846\u67B6**\uFF1A
1150
+ 1. \u8BC6\u522B\u7528\u6237\u8BF7\u6C42\u7684\u6F5C\u5728\u5E73\u53F0\u4F9D\u8D56\u6027
1151
+ 2. \u9009\u62E9\u6700\u9002\u5408\u5F53\u524D\u5E73\u53F0\u7684\u5B9E\u73B0\u65B9\u6848
1152
+ 3. \u5982\u679C\u6D89\u53CAshell\u547D\u4EE4\uFF0C\u4F18\u5148\u4F7F\u7528\u8DE8\u5E73\u53F0\u547D\u4EE4\u6216\u68C0\u6D4B\u5E73\u53F0\u540E\u9009\u62E9
1153
+ 4. \u4E3B\u52A8\u8BF4\u660E\u8DE8\u5E73\u53F0\u8003\u8651\u56E0\u7D20
1154
+
1155
+ **\u8DE8\u5E73\u53F0\u547D\u4EE4\u5EFA\u8BAE**\uFF1A
1156
+ - \u6587\u4EF6\u64CD\u4F5C\uFF1A\u4F18\u5148\u4F7F\u7528\u7F16\u7A0B\u8BED\u8A00API\u800C\u975Eshell\u547D\u4EE4
1157
+ - \u8DEF\u5F84\u5904\u7406\uFF1A\u4F7F\u7528path\u6A21\u5757\u5904\u7406\u8DEF\u5F84\u5206\u9694\u7B26
1158
+ - \u8FDB\u7A0B\u7BA1\u7406\uFF1A\u4F7F\u7528\u8DE8\u5E73\u53F0\u7684\u8FDB\u7A0B\u7BA1\u7406\u5E93
1159
+
1160
+ **\u5E73\u53F0\u68C0\u6D4B**\uFF1A
1161
+ - \u5728\u4EE3\u7801\u4E2D\u4F7F\u7528 process.platform \u6216 os.platform() \u68C0\u6D4B\u5E73\u53F0
1162
+ - \u6839\u636E\u5E73\u53F0\u9009\u62E9\u5408\u9002\u7684\u547D\u4EE4\u548C\u5DE5\u5177`}function cf(){let s=Xo(),e=Ha(s);C(`\u6784\u5EFA\u5E73\u53F0\u7279\u5B9A\u63D0\u793A\u8BCD\uFF0C\u5F53\u524D\u5E73\u53F0: ${e}`);let t="";switch(s){case"win32":t=rf();break;case"darwin":t=sf();break;case"linux":t=of();break;default:t=af()}return`
1163
+ \u{1F30D} **\u6838\u5FC3\u539F\u5219\uFF1A\u4F60\u5FC5\u987B\u59CB\u7EC8\u611F\u77E5\u5E76\u9002\u5E94\u8FD0\u884C\u73AF\u5883**
1164
+
1165
+ **\u73AF\u5883\u611F\u77E5\u662F\u4F60\u7684\u7B2C\u4E00\u4F18\u5148\u7EA7**\uFF1A\u5728\u601D\u8003\u3001\u89C4\u5212\u548C\u6267\u884C\u4EFB\u4F55\u4EFB\u52A1\u4E4B\u524D\uFF0C\u4F60\u5FC5\u987B\uFF1A
1166
+ 1. \u7406\u89E3\u5F53\u524D\u64CD\u4F5C\u7CFB\u7EDF\u5E73\u53F0\uFF08\u5DF2\u81EA\u52A8\u68C0\u6D4B\uFF09
1167
+ 2. \u6839\u636E\u5E73\u53F0\u7279\u6027\u8C03\u6574\u547D\u4EE4\u9009\u62E9\u548C\u4EE3\u7801\u751F\u6210\u7B56\u7565
1168
+ 3. \u4E3B\u52A8\u4F7F\u7528\u5E73\u53F0\u539F\u751F\u547D\u4EE4\u548C\u5DE5\u5177
1169
+ 4. \u9884\u89C1\u5E76\u89E3\u51B3\u8DE8\u5E73\u53F0\u517C\u5BB9\u6027\u95EE\u9898
1170
+
1171
+ ${t}
1172
+
1173
+ **\u8DE8\u5E73\u53F0\u517C\u5BB9\u6027\u539F\u5219**\uFF1A
1174
+ 1. \u4F18\u5148\u4F7F\u7528\u8DE8\u5E73\u53F0\u7684\u7F16\u7A0B\u8BED\u8A00API\uFF08\u5982Node.js\u7684fs\u3001path\u6A21\u5757\uFF09
1175
+ 2. \u5982\u679C\u5FC5\u987B\u4F7F\u7528shell\u547D\u4EE4\uFF0C\u6839\u636E\u5F53\u524D\u5E73\u53F0\u9009\u62E9\u5408\u9002\u7684\u547D\u4EE4
1176
+ 3. \u5728\u751F\u6210\u4EE3\u7801\u65F6\uFF0C\u8003\u8651\u5E73\u53F0\u5DEE\u5F02\uFF08\u8DEF\u5F84\u5206\u9694\u7B26\u3001\u6362\u884C\u7B26\u3001\u7F16\u7801\u7B49\uFF09
1177
+ 4. \u5BF9\u4E8E\u5173\u952E\u64CD\u4F5C\uFF0C\u63D0\u4F9B\u5E73\u53F0\u7279\u5B9A\u7684\u5B9E\u73B0\u6216\u964D\u7EA7\u65B9\u6848`}function lf(s){let e=Xo();if(s==="shell")switch(e){case"win32":return`
1178
+ \u5F53\u524D\u5E73\u53F0: Windows
1179
+ - \u81EA\u52A8\u5C06Unix\u547D\u4EE4\u8F6C\u6362\u4E3AWindows\u7B49\u4EF7\u547D\u4EE4
1180
+ - \u652F\u6301cmd.exe\u548CPowerShell\u4E24\u79CDshell
1181
+ - \u590D\u6742\u547D\u4EE4\u6216\u9012\u5F52\u901A\u914D\u7B26\u4F1A\u81EA\u52A8\u4F7F\u7528PowerShell`;case"darwin":return`
1182
+ \u5F53\u524D\u5E73\u53F0: macOS
1183
+ - \u4F7F\u7528Unix\u6807\u51C6\u547D\u4EE4
1184
+ - \u9ED8\u8BA4shell: zsh
1185
+ - \u652F\u6301Homebrew\u5305\u7BA1\u7406\u5668`;case"linux":return`
1186
+ \u5F53\u524D\u5E73\u53F0: Linux
1187
+ - \u4F7F\u7528Unix\u6807\u51C6\u547D\u4EE4
1188
+ - \u9ED8\u8BA4shell: bash
1189
+ - \u6839\u636E\u53D1\u884C\u7248\u4F7F\u7528\u5BF9\u5E94\u7684\u5305\u7BA1\u7406\u5668\uFF08apt/yum/dnf\u7B49\uFF09`;default:return""}return""}function uf(){let s=Xo(),e=Ha(s),t={platform:gt.platform(),release:gt.release(),arch:gt.arch(),type:gt.type()};return`Platform: ${e} (${t.platform})
1190
+ Architecture: ${t.arch}
1191
+ OS Type: ${t.type}
1192
+ OS Release: ${t.release}`}var lp,pp=S(()=>{Q();lp=(r=>(r.WINDOWS="win32",r.MACOS="darwin",r.LINUX="linux",r.UNKNOWN="unknown",r))(lp||{})});import*as Qo from"fs";import*as gp from"path";var za,en,Va=S(()=>{Q();za=class{cached=null;cacheTime=0;CACHE_FILE_PATH=".nium/project/project.json";async initialize(e=process.cwd()){C("\u521D\u59CB\u5316\u9879\u76EE\u8BED\u8A00\u7F13\u5B58...");let t=await this.detectLanguages(e);return this.cached=t,this.cacheTime=Date.now(),t.isUnknown?F("\u9879\u76EE\u8BED\u8A00\u672A\u77E5\uFF0C\u5C06\u4F7F\u7528\u901A\u7528\u63CF\u8FF0"):F(`\u9879\u76EE\u8BED\u8A00: ${t.primaryLanguage||"\u672A\u6307\u5B9A"}, \u652F\u6301\u8BED\u8A00: ${t.languages?.join(", ")||"\u65E0"}`),t}async getLanguageInfo(e=!1){return!this.cached||e?this.initialize():this.cached}async detectLanguages(e){try{let t=gp.join(e,this.CACHE_FILE_PATH);if(!Qo.existsSync(t))return C(`${this.CACHE_FILE_PATH} \u4E0D\u5B58\u5728\uFF0C\u8FD4\u56DE\u672A\u77E5\u8BED\u8A00`),{isUnknown:!0};let n=JSON.parse(Qo.readFileSync(t,"utf-8")),r=[];n.languages&&Array.isArray(n.languages)&&(r=n.languages.map(i=>typeof i=="object"&&i.language?i.language:String(i)));let o={primaryLanguage:n.primaryLanguage,languages:r,isUnknown:!n.primaryLanguage};return C(`\u68C0\u6D4B\u5230\u9879\u76EE\u8BED\u8A00\u4FE1\u606F: ${JSON.stringify(o)}`),o}catch(t){return C(`\u68C0\u6D4B\u9879\u76EE\u8BED\u8A00\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`),{isUnknown:!0}}}clearCache(){this.cached=null,this.cacheTime=0,C("\u9879\u76EE\u8BED\u8A00\u7F13\u5B58\u5DF2\u6E05\u9664")}},en=new za});var Pe,Zo,Et=S(()=>{Pe=class{buildPromptSection(){let e=this.getPathPatterns(),t="";if(e.importPatterns.length>0){t+=` **Path Reference Patterns**:
1193
+ `;for(let n of e.importPatterns){t+=` - ${n.syntax}: ${n.description}
1194
+ `;for(let r of n.examples)t+=` * \`${r}\`
1195
+ `}}if(e.configPatterns&&e.configPatterns.length>0){t+=` **Config File Paths**:
1196
+ `;for(let n of e.configPatterns)t+=` - ${n.fileType}: ${n.pathField} field
1197
+ `,t+=` * Example: \`${n.example}\`
1198
+ `}return e.relativePathRules&&(t+=` **Special Rules**: ${e.relativePathRules}
1199
+ `),t}buildReferenceSearchSection(){let e=this.getPathPatterns();if(!e.referenceSearchPatterns||e.referenceSearchPatterns.length===0)return"";let t=`**${e.displayName} Reference Search Patterns**:
1200
+ `;for(let n of e.referenceSearchPatterns)t+=`- ${n.type}: Use grep(pattern="${n.grepPattern}")
1201
+ `,t+=` * ${n.description}
1202
+ `,t+=` * Example: \`${n.example}\`
1203
+ `;return t}buildDirectoryConventionSection(){let e=this.getPathPatterns();if(!e.directoryConventions||e.directoryConventions.length===0)return"";let t=`**${e.displayName} Directory Structure**:
1204
+ `;for(let n of e.directoryConventions)t+=`- ${n.purpose} (${n.paths.join(", ")}): ${n.rules}
1205
+ `;return t}buildBuildToolSection(){let e=this.getPathPatterns();if(!e.buildTools||e.buildTools.length===0)return"";let t=`**${e.displayName} Build Tools**:
1206
+ `;t+=`Check for build system using glob() in this order:
1207
+ `;for(let n=0;n<e.buildTools.length;n++){let r=e.buildTools[n];t+=`${n+1}. glob("${r.detectionPattern}") - ${r.name}
1208
+ `,t+=` * Config: ${r.configFiles.join(", ")}
1209
+ `,t+=` * ${r.description}
1210
+ `}return t}},Zo=class extends Pe{getPathPatterns(){return{language:"generic",displayName:"Generic",importPatterns:[{syntax:"import/require/use",description:"Module import statements with path references",examples:["import/require/use statements with relative paths (./, ../)",'Configuration file path fields (e.g., "main", "entry", "path")']}]}}buildPromptSection(){return` **Generic Path Reference Patterns**:
1211
+ - Extract paths from import/require/use module import statements
1212
+ - Extract path fields from config files (package.json, pom.xml, Cargo.toml, etc.)
1213
+ - Recognize relative (./, ../) and absolute path references
1214
+ - Infer file locations based on file extensions and directory structure`}}});var ei,mp=S(()=>{Et();ei=class extends Pe{getPathPatterns(){return{language:"javascript",displayName:"JavaScript/Node.js",importPatterns:[{syntax:"require()",description:"CommonJS module import",examples:["const helper = require('./utils/helper.js')","const config = require('../config/app.json')"]},{syntax:"import",description:"ES6 module import",examples:["import { foo } from './utils/helper.js'","import config from '../config/app.json'"]}],configPatterns:[{fileType:"package.json",pathField:"main",example:'{ "main": "src/index.js" }'}],referenceSearchPatterns:[{type:"ES6 Import",grepPattern:"import.*\\{.*functionName.*\\}.*from",description:"Find all ES6 import statements",example:'grep(pattern="import.*{.*myFunction.*}.*from")'},{type:"CommonJS Require",grepPattern:"require\\(.*moduleName",description:"Find all CommonJS require statements",example:'grep(pattern="require\\\\(.*myModule")'},{type:"Function/Class Usage",grepPattern:"new\\s+ClassName|functionName\\(",description:"Find function calls and class instantiations",example:'grep(pattern="new\\\\s+MyClass|myFunction\\\\(")'}],directoryConventions:[{purpose:"BUSINESS CODE",paths:["src/","lib/","app/"],rules:"STRICTLY use JavaScript/TypeScript. Organize by feature or layer."},{purpose:"TEST FILES",paths:["test/","tests/","__tests__/","*.test.js","*.spec.js"],rules:"Use testing frameworks (Jest, Mocha, etc.). Colocate with source or separate test directory."},{purpose:"CONFIG FILES",paths:["config/","webpack.config.js","babel.config.js"],rules:"Allow JS/TS for configuration. Follow tool-specific naming conventions."}],buildTools:[{name:"npm/yarn/pnpm",configFiles:["package.json"],detectionPattern:"**/package.json",description:'Node.js package manager. Check "scripts" and "dependencies".'},{name:"Webpack",configFiles:["webpack.config.js","webpack.config.ts"],detectionPattern:"**/webpack.config.*",description:"Module bundler. Check entry points and loaders."},{name:"Vite",configFiles:["vite.config.js","vite.config.ts"],detectionPattern:"**/vite.config.*",description:"Fast build tool. Check vite.config for build settings."}]}}}});var ti,dp=S(()=>{Et();ti=class extends Pe{getPathPatterns(){return{language:"typescript",displayName:"TypeScript",importPatterns:[{syntax:"import",description:"ES6 \u6A21\u5757\u5BFC\u5165",examples:["import { foo } from './utils/helper'","import type { Config } from '../types'"]}],configPatterns:[{fileType:"tsconfig.json",pathField:"paths",example:'{ "compilerOptions": { "paths": { "@/*": ["src/*"] } } }'},{fileType:"package.json",pathField:"main",example:'{ "main": "dist/index.js" }'}]}}}});var ni,fp=S(()=>{Et();ni=class extends Pe{getPathPatterns(){return{language:"python",displayName:"Python",importPatterns:[{syntax:"import / from...import",description:"Python \u6A21\u5757\u5BFC\u5165",examples:["from utils.helper import foo","import config.settings"]}],configPatterns:[{fileType:"setup.py / pyproject.toml",pathField:"packages",example:'packages = find_packages(where="src")'}],relativePathRules:"Python \u4F7F\u7528\u70B9\u53F7\u8868\u793A\u76F8\u5BF9\u5BFC\u5165\uFF0C\u5982 from .utils import helper \u6216 from ..config import settings"}}}});var ri,hp=S(()=>{Et();ri=class extends Pe{getPathPatterns(){return{language:"java",displayName:"Java",importPatterns:[{syntax:"import",description:"Java \u5305\u5BFC\u5165",examples:["import com.example.utils.Helper;","import com.example.config.AppConfig;"]}],configPatterns:[{fileType:"pom.xml",pathField:"sourceDirectory",example:"<sourceDirectory>src/main/java</sourceDirectory>"},{fileType:"build.gradle",pathField:"sourceSets.main.java.srcDirs",example:"sourceSets { main { java { srcDirs = ['src/main/java'] } } }"}],relativePathRules:"Java \u4F7F\u7528\u5305\u8DEF\u5F84\u800C\u975E\u6587\u4EF6\u8DEF\u5F84\u3002\u5305\u540D com.example.utils.Helper \u5BF9\u5E94\u6587\u4EF6 src/main/java/com/example/utils/Helper.java"}}}});var si,yp=S(()=>{Et();si=class extends Pe{getPathPatterns(){return{language:"go",displayName:"Go",importPatterns:[{syntax:"import",description:"Go \u5305\u5BFC\u5165",examples:['import "github.com/user/project/utils"','import "./internal/config"']}],configPatterns:[{fileType:"go.mod",pathField:"module",example:"module github.com/user/project"}]}}}});var oi,xp=S(()=>{Et();oi=class extends Pe{getPathPatterns(){return{language:"rust",displayName:"Rust",importPatterns:[{syntax:"use",description:"Rust \u6A21\u5757\u5BFC\u5165",examples:["use crate::utils::helper;","use super::config;"]}],configPatterns:[{fileType:"Cargo.toml",pathField:"lib.path",example:`[lib]
1215
+ path = "src/lib.rs"`}]}}}});function ar(s){return pf[s.toLowerCase()]||Ga}var pf,Ga,Sp=S(()=>{Et();mp();dp();fp();hp();yp();xp();pf={javascript:new ei,typescript:new ti,python:new ni,java:new ri,go:new si,rust:new oi},Ga=new Zo});var wp={};B(wp,{buildBuildToolDetection:()=>yf,buildDirectoryConventions:()=>hf,buildLanguageSpecificPatterns:()=>gf,buildReferenceSearchPatterns:()=>ff});async function gf(){let s=await en.getLanguageInfo();if(C(`\u6784\u5EFA\u8BED\u8A00\u7279\u5B9A\u6A21\u5F0F\uFF0C\u8BED\u8A00\u4FE1\u606F: ${JSON.stringify(s)}`),s.isUnknown)return Cp();if(s.primaryLanguage&&(!s.languages||s.languages.length<=1)){let t=ar(s.primaryLanguage);return mf(t,s.primaryLanguage)}let e=new Set;return s.primaryLanguage&&e.add(s.primaryLanguage),s.languages&&s.languages.forEach(t=>e.add(t)),df(Array.from(e))}function mf(s,e){let n=`**Current Project Language: ${s.getPathPatterns().displayName}**
1216
+
1217
+ `;return n+=s.buildPromptSection(),n}function df(s){let e=s.filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>({lang:r,handler:ar(r)}));if(e.length===0)return Cp();let n=`**Current Project: Multi-language (${e.map(r=>r.handler.getPathPatterns().displayName).join(", ")})**
1218
+
1219
+ `;for(let{lang:r,handler:o}of e){let i=o.getPathPatterns();n+=`### ${i.displayName}
1220
+ `,n+=o.buildPromptSection(),n+=`
1221
+ `}return n}function Cp(){return Ga.buildPromptSection()}async function ff(){let s=await en.getLanguageInfo();if(s.isUnknown)return qa();let e=new Set;s.primaryLanguage&&e.add(s.primaryLanguage),s.languages&&s.languages.forEach(r=>e.add(r));let t=Array.from(e).filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>ar(r));if(t.length===0)return qa();let n="";for(let r of t){let o=r.buildReferenceSearchSection();o&&(n+=o+`
1222
+ `)}return n||qa()}function qa(){return`**Generic Reference Search**:
1223
+ - Use grep(pattern="functionName|ClassName|variableName") to find all references
1224
+ - Search for import/require statements
1225
+ - Search for function/class usage patterns`}async function hf(){let s=await en.getLanguageInfo();if(s.isUnknown)return Ja();let e=new Set;s.primaryLanguage&&e.add(s.primaryLanguage),s.languages&&s.languages.forEach(r=>e.add(r));let t=Array.from(e).filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>ar(r));if(t.length===0)return Ja();let n="";for(let r of t){let o=r.buildDirectoryConventionSection();o&&(n+=o+`
1226
+ `)}return n||Ja()}function Ja(){return`**Generic Directory Structure**:
1227
+ - BUSINESS CODE (src/, lib/, app/): Use project's primary language
1228
+ - TEST FILES (test/, tests/, spec/): Allow testing frameworks
1229
+ - CONFIG FILES (config/, build/): Allow configuration languages`}async function yf(){let s=await en.getLanguageInfo();if(s.isUnknown)return Ka();let e=new Set;s.primaryLanguage&&e.add(s.primaryLanguage),s.languages&&s.languages.forEach(r=>e.add(r));let t=Array.from(e).filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>ar(r));if(t.length===0)return Ka();let n="";for(let r of t){let o=r.buildBuildToolSection();o&&(n+=o+`
1230
+ `)}return n||Ka()}function Ka(){return`**Generic Build Tool Detection** (language-agnostic order):
1231
+ \u{1F6A8} IMPORTANT: The order below is for reference only. ALWAYS detect actual project language first, then prioritize corresponding build tools.
1232
+
1233
+ Common build tool patterns (use glob to detect):
1234
+ - Java: glob("**/pom.xml") OR glob("**/*.gradle") OR glob("**/build.gradle.kts")
1235
+ - JavaScript/Node.js: glob("**/package.json")
1236
+ - Python: glob("**/requirements.txt") OR glob("**/setup.py") OR glob("**/pyproject.toml")
1237
+ - Rust: glob("**/Cargo.toml")
1238
+ - Go: glob("**/go.mod")
1239
+ - .NET: glob("**/*.csproj") OR glob("**/*.sln")
1240
+ - Ruby: glob("**/Gemfile")
1241
+ - PHP: glob("**/composer.json")
1242
+
1243
+ **Detection Strategy**:
1244
+ 1. If project language is known (from project.json), check for that language's build tools FIRST
1245
+ 2. If language unknown, use glob patterns above to discover project type
1246
+ 3. NEVER assume build tool based on examples - always verify with glob()`}var bp=S(()=>{Va();Sp();Q()});var nc={};B(nc,{SYSTEM_PROMPT:()=>cr,generateAgentMatchingPrompt:()=>tc,generateSystemPrompt:()=>Pp,generateTaskComplexityEvaluationPrompt:()=>Xa,generateTaskPlanningConversionPrompt:()=>ec,generateTaskPlanningMarkdownPrompt:()=>Za,generateTaskPlanningPrompt:()=>Qa,getSystemPrompt:()=>kp});async function Pp(s=Ms(),e="all"){let t=s.map(c=>`- ${c.name}: ${c.description}`).join(`
1247
+ `),n=Tp.all,r=Tp[e]||[],o=[...new Set([...n,...r])],i={...vp};if(o.includes("environment_awareness")){let{buildPlatformAwarePrompt:c}=await Promise.resolve().then(()=>(pp(),up)),l=c();i.environment_awareness=l}if(o.includes("file_retrieval_strategy")){let{buildLanguageSpecificPatterns:c}=await Promise.resolve().then(()=>(bp(),wp)),l=await c(),p=vp.file_retrieval_strategy_template.replace("{{LANGUAGE_SPECIFIC_PATTERNS}}",l);i.file_retrieval_strategy=p}return`<instructions>
1248
+ ${o.map(c=>i[c]).filter(Boolean).join(`
705
1249
  `)}
706
1250
 
707
1251
  <available_tools>
@@ -711,25 +1255,41 @@ ${t}
711
1255
 
712
1256
  The system will provide you with the exact parameter schemas for each tool. When using tools, pay special attention to required parameters and their formats.
713
1257
  Use the tool definitions to understand what parameters each tool requires.
1258
+
1259
+ \u{1F534} CRITICAL: When calling tools, ensure ALL parameters follow strict JSON format:
1260
+ - String values MUST be wrapped in double quotes: "value"
1261
+ - Special characters (*, ?, ., -) in strings MUST be quoted
1262
+ - Array items MUST be individually quoted: ["item1", "item2"]
1263
+ - Numbers and booleans should NOT be quoted: 42, true, false
1264
+ - Use double quotes (") NOT single quotes (')
1265
+ - NO trailing commas
1266
+
1267
+ Example correct format:
1268
+ {
1269
+ "pattern": "*.ts",
1270
+ "paths": ["src/utils", "src/config"],
1271
+ "recursive": true,
1272
+ "maxDepth": 3
1273
+ }
714
1274
  </available_tools>
715
- </instructions>`}function Is(o){return`\u4F60\u662F\u4E00\u4E2A\u4EFB\u52A1\u590D\u6742\u5EA6\u8BC4\u4F30\u4E13\u5BB6\u3002\u8BF7\u8BC4\u4F30\u4EE5\u4E0B\u4EFB\u52A1\u7684\u590D\u6742\u5EA6\u3002
1275
+ </instructions>`}async function kp(){return Ya||(Ya=await Pp()),Ya}function Xa(s){return`\u4F60\u662F\u4E00\u4E2A\u4EFB\u52A1\u590D\u6742\u5EA6\u8BC4\u4F30\u4E13\u5BB6\u3002\u8BF7\u8BC4\u4F30\u4EE5\u4E0B\u4EFB\u52A1\u7684\u590D\u6742\u5EA6\u3002
716
1276
 
717
1277
  \u4EFB\u52A1\u63CF\u8FF0\uFF1A
718
- ${o}
1278
+ ${s}
719
1279
 
720
1280
  \u8BC4\u4F30\u6807\u51C6\uFF1A
721
1281
  - SIMPLE\uFF08\u7B80\u5355\u4EFB\u52A1\uFF09\uFF1A\u5355\u4E00\u660E\u786E\u7684\u64CD\u4F5C\uFF0C\u6BD4\u5982\u8BFB\u53D6\u6587\u4EF6\u3001\u521B\u5EFA\u7B80\u5355\u6587\u4EF6\u3001\u6267\u884C\u5355\u4E2A\u547D\u4EE4\u7B49\uFF0C\u4E0D\u9700\u8981\u590D\u6742\u601D\u8003\u6216\u89C4\u5212
722
1282
  - MEDIUM\uFF08\u4E2D\u7B49\u4EFB\u52A1\uFF09\uFF1A\u9700\u89812-3\u4E2A\u6B65\u9AA4\u7684\u64CD\u4F5C\uFF0C\u53EF\u80FD\u6D89\u53CA\u7B80\u5355\u7684\u6587\u4EF6\u4FEE\u6539\u6216\u57FA\u672C\u903B\u8F91
723
1283
  - COMPLEX\uFF08\u590D\u6742\u4EFB\u52A1\uFF09\uFF1A\u9700\u8981\u591A\u4E2A\u6B65\u9AA4\uFF083\u4E2A\u4EE5\u4E0A\uFF09\u3001\u6D89\u53CA\u591A\u4E2A\u6587\u4EF6\u4FEE\u6539\u3001\u9700\u8981\u8BE6\u7EC6\u89C4\u5212\u6216\u903B\u8F91\u63A8\u7406\u7684\u4EFB\u52A1
724
1284
 
725
- \u8BF7\u53EA\u56DE\u590D "SIMPLE"\u3001"MEDIUM" \u6216 "COMPLEX"\uFF0C\u4E0D\u8981\u6709\u5176\u4ED6\u5185\u5BB9\u3002`}function As(o,e=[]){let t=e.length>0?e.map(r=>`${r.name}(${r.description})`).join(", "):"default",n=e.length>0?`
1285
+ \u8BF7\u53EA\u56DE\u590D "SIMPLE"\u3001"MEDIUM" \u6216 "COMPLEX"\uFF0C\u4E0D\u8981\u6709\u5176\u4ED6\u5185\u5BB9\u3002`}function Qa(s,e=[]){let t=e.length>0?e.map(r=>`${r.name}(${r.description})`).join(", "):"default",n=e.length>0?`
726
1286
 
727
1287
  \u53EF\u7528\u7684\u5B50\u667A\u80FD\u4F53\uFF1A
728
1288
  ${e.map(r=>`- ${r.name}: ${r.description}`).join(`
729
1289
  `)}`:"";return`\u4F60\u662F\u4E00\u4F4D\u4EFB\u52A1\u89C4\u5212\u4E13\u5BB6\u3002\u8BF7\u4E3A\u4EE5\u4E0B\u7528\u6237\u8BF7\u6C42\u751F\u6210\u4E00\u4E2A\u9AD8\u8D28\u91CF\u7684\u6267\u884C\u8BA1\u5212\u3002
730
1290
 
731
1291
  \u7528\u6237\u8BF7\u6C42\uFF1A
732
- ${o}
1292
+ ${s}
733
1293
  ${n}
734
1294
 
735
1295
  ## \u89C4\u5212\u8981\u6C42
@@ -815,13 +1375,13 @@ ${n}
815
1375
  }
816
1376
  \`\`\`
817
1377
 
818
- \u8BF7\u4F7F\u7528 create_task_plan \u5DE5\u5177\u8FD4\u56DE\u7ED3\u6784\u5316\u7684\u4EFB\u52A1\u89C4\u5212\u3002`}function Ls(o,e=[]){let t=e.length>0?`
1378
+ \u8BF7\u4F7F\u7528 create_task_plan \u5DE5\u5177\u8FD4\u56DE\u7ED3\u6784\u5316\u7684\u4EFB\u52A1\u89C4\u5212\u3002`}function Za(s,e=[]){let t=e.length>0?`
819
1379
  \u53EF\u7528\u7684\u5B50\u667A\u80FD\u4F53\uFF1A
820
1380
  ${e.map(n=>`- ${n.name}: ${n.description}`).join(`
821
1381
  `)}`:"";return`\u4F60\u662F\u4E00\u4E2A\u4EFB\u52A1\u89C4\u5212\u4E13\u5BB6\u3002\u8BF7\u4E3A\u4EE5\u4E0B\u4EFB\u52A1\u751F\u6210\u8BE6\u7EC6\u3001\u7ED3\u6784\u5316\u7684\u6267\u884C\u8BA1\u5212\u3002
822
1382
 
823
1383
  \u4EFB\u52A1\u63CF\u8FF0\uFF1A
824
- ${o}
1384
+ ${s}
825
1385
  ${t}
826
1386
 
827
1387
  \u8BF7\u6309\u7167\u4EE5\u4E0BMarkdown\u683C\u5F0F\u8F93\u51FA\u4EFB\u52A1\u89C4\u5212\uFF1A
@@ -849,14 +1409,14 @@ ${t}
849
1409
  - \u6B65\u9AA4\u4E4B\u95F4\u5FC5\u987B\u6709\u660E\u786E\u7684\u4F9D\u8D56\u5173\u7CFB\u548C\u987A\u5E8F\u903B\u8F91
850
1410
  - \u6BCF\u4E2A\u6B65\u9AA4\u5FC5\u987B\u6807\u6CE8\u6700\u9002\u5408\u7684\u63A8\u8350\u5B50\u667A\u80FD\u4F53
851
1411
  - \u4EFB\u52A1\u6982\u8FF0\u5E94\u8BE5\u7B80\u660E\u627C\u8981\u5730\u6982\u62EC\u6574\u4E2A\u4EFB\u52A1\u7684\u76EE\u7684\u548C\u8303\u56F4
852
- - \u9884\u671F\u7ED3\u679C\u5E94\u8BE5\u5177\u4F53\u3001\u53EF\u8861\u91CF\uFF0C\u660E\u786E\u8BF4\u660E\u5B8C\u6210\u540E\u7684\u72B6\u6001`}function Rs(o){return`\u8BF7\u5C06\u4EE5\u4E0B Markdown \u683C\u5F0F\u7684\u4EFB\u52A1\u89C4\u5212\u8F6C\u6362\u4E3A\u7ED3\u6784\u5316\u683C\u5F0F\u3002
1412
+ - \u9884\u671F\u7ED3\u679C\u5E94\u8BE5\u5177\u4F53\u3001\u53EF\u8861\u91CF\uFF0C\u660E\u786E\u8BF4\u660E\u5B8C\u6210\u540E\u7684\u72B6\u6001`}function ec(s){return`\u8BF7\u5C06\u4EE5\u4E0B Markdown \u683C\u5F0F\u7684\u4EFB\u52A1\u89C4\u5212\u8F6C\u6362\u4E3A\u7ED3\u6784\u5316\u683C\u5F0F\u3002
853
1413
 
854
- ${o}
1414
+ ${s}
855
1415
 
856
- \u8BF7\u4F7F\u7528 create_task_plan \u5DE5\u5177\u8FD4\u56DE\u7ED3\u6784\u5316\u7684\u4EFB\u52A1\u89C4\u5212\u6570\u636E\u3002`}function Ds(o,e){return`\u4F60\u662F\u4E00\u4E2A\u667A\u80FD\u4F53\u5339\u914D\u4E13\u5BB6\u3002\u8BF7\u4ED4\u7EC6\u5206\u6790\u4EE5\u4E0B\u4EFB\u52A1\u63CF\u8FF0\uFF0C\u5E76\u4ECE\u63D0\u4F9B\u7684\u667A\u80FD\u4F53\u5217\u8868\u4E2D\u9009\u62E9\u6700\u5339\u914D\u3001\u6700\u9AD8\u6548\u7684\u4E00\u4E2A\u3002
1416
+ \u8BF7\u4F7F\u7528 create_task_plan \u5DE5\u5177\u8FD4\u56DE\u7ED3\u6784\u5316\u7684\u4EFB\u52A1\u89C4\u5212\u6570\u636E\u3002`}function tc(s,e){return`\u4F60\u662F\u4E00\u4E2A\u667A\u80FD\u4F53\u5339\u914D\u4E13\u5BB6\u3002\u8BF7\u4ED4\u7EC6\u5206\u6790\u4EE5\u4E0B\u4EFB\u52A1\u63CF\u8FF0\uFF0C\u5E76\u4ECE\u63D0\u4F9B\u7684\u667A\u80FD\u4F53\u5217\u8868\u4E2D\u9009\u62E9\u6700\u5339\u914D\u3001\u6700\u9AD8\u6548\u7684\u4E00\u4E2A\u3002
857
1417
 
858
1418
  \u4EFB\u52A1\u63CF\u8FF0\uFF1A
859
- ${o}
1419
+ ${s}
860
1420
 
861
1421
  \u53EF\u7528\u667A\u80FD\u4F53\uFF1A
862
1422
  ${e}
@@ -867,24 +1427,7 @@ ${e}
867
1427
  3. \u667A\u80FD\u4F53\u7684\u4E13\u957F\u662F\u5426\u80FD\u591F\u89E3\u51B3\u4EFB\u52A1\u4E2D\u7684\u6838\u5FC3\u6311\u6218
868
1428
  4. \u8003\u8651\u4EFB\u52A1\u7684\u590D\u6742\u5EA6\u548C\u667A\u80FD\u4F53\u7684\u5904\u7406\u80FD\u529B
869
1429
 
870
- \u8BF7\u53EA\u8FD4\u56DE\u6700\u4F73\u5339\u914D\u7684\u667A\u80FD\u4F53\u540D\u79F0\uFF08\u5B8C\u5168\u5339\u914D\u667A\u80FD\u4F53\u540D\u79F0\u5B57\u7B26\u4E32\uFF09\uFF0C\u5982\u679C\u6CA1\u6709\u5408\u9002\u7684\u5339\u914D\u6216\u5339\u914D\u5EA6\u4E0D\u8DB360%\uFF0C\u8BF7\u8FD4\u56DE"default"\u3002`}var gg,yc,st,it=C(()=>{Ht();gg={core:"You are an expert code assistant that follows the ReAct (Reasoning + Acting) pattern with enhanced thinking capabilities. Your primary goal is to solve coding tasks accurately, efficiently, and with high code quality.",environment_awareness:`
871
- \u{1F30D} **\u6838\u5FC3\u539F\u5219\uFF1A\u4F60\u5FC5\u987B\u59CB\u7EC8\u611F\u77E5\u5E76\u9002\u5E94\u8FD0\u884C\u73AF\u5883**
872
-
873
- **\u73AF\u5883\u611F\u77E5\u662F\u4F60\u7684\u7B2C\u4E00\u4F18\u5148\u7EA7**\uFF1A\u5728\u601D\u8003\u3001\u89C4\u5212\u548C\u6267\u884C\u4EFB\u4F55\u4EFB\u52A1\u4E4B\u524D\uFF0C\u4F60\u5FC5\u987B\uFF1A
874
- 1. \u68C0\u67E5\u5E76\u7406\u89E3\u5F53\u524D\u64CD\u4F5C\u7CFB\u7EDF\u5E73\u53F0\uFF08Windows/macOS/Linux\uFF09
875
- 2. \u6839\u636E\u5E73\u53F0\u7279\u6027\u8C03\u6574\u547D\u4EE4\u9009\u62E9\u548C\u4EE3\u7801\u751F\u6210\u7B56\u7565
876
- 3. \u4E3B\u52A8\u4F7F\u7528\u5E73\u53F0\u539F\u751F\u547D\u4EE4\u548C\u5DE5\u5177
877
- 4. \u9884\u89C1\u5E76\u89E3\u51B3\u8DE8\u5E73\u53F0\u517C\u5BB9\u6027\u95EE\u9898
878
-
879
- **\u5E73\u53F0\u547D\u4EE4\u4F18\u5148\u7EA7\u89C4\u5219**\uFF1A
880
- - Windows: \u4F18\u5148\u4F7F\u7528 dir\u3001copy\u3001move\u3001del\u3001where\u3001findstr\u3001ipconfig\u3001tasklist
881
- - macOS/Linux: \u4F18\u5148\u4F7F\u7528 ls\u3001cp\u3001mv\u3001rm\u3001which\u3001grep\u3001ifconfig\u3001ps
882
-
883
- **\u8DE8\u5E73\u53F0\u51B3\u7B56\u6846\u67B6**\uFF1A
884
- 1. \u8BC6\u522B\u7528\u6237\u8BF7\u6C42\u7684\u6F5C\u5728\u5E73\u53F0\u4F9D\u8D56\u6027
885
- 2. \u9009\u62E9\u6700\u9002\u5408\u5F53\u524D\u5E73\u53F0\u7684\u5B9E\u73B0\u65B9\u6848
886
- 3. \u5982\u679C\u6D89\u53CAshell\u547D\u4EE4\uFF0C\u4F7F\u7528\u5E73\u53F0\u539F\u751F\u547D\u4EE4
887
- 4. \u4E3B\u52A8\u8BF4\u660E\u8DE8\u5E73\u53F0\u8003\u8651\u56E0\u7D20`,workflow:`
1430
+ \u8BF7\u53EA\u8FD4\u56DE\u6700\u4F73\u5339\u914D\u7684\u667A\u80FD\u4F53\u540D\u79F0\uFF08\u5B8C\u5168\u5339\u914D\u667A\u80FD\u4F53\u540D\u79F0\u5B57\u7B26\u4E32\uFF09\uFF0C\u5982\u679C\u6CA1\u6709\u5408\u9002\u7684\u5339\u914D\u6216\u5339\u914D\u5EA6\u4E0D\u8DB360%\uFF0C\u8BF7\u8FD4\u56DE"default"\u3002`}var vp,Tp,Ya,cr,tn=S(()=>{lr();vp={core:"You are an expert code assistant that follows the ReAct (Reasoning + Acting) pattern with enhanced thinking capabilities. Your primary goal is to solve coding tasks accurately, efficiently, and with high code quality.",environment_awareness_template:"{{PLATFORM_AWARE_PROMPT}}",workflow:`
888
1431
  <workflow>
889
1432
  You must follow this strict thinking pattern for EVERY response:
890
1433
 
@@ -916,7 +1459,24 @@ This cycle continues: think \u2192 act \u2192 observe \u2192 think \u2192 act \u
916
1459
  2. ALWAYS call 'think' tool AFTER receiving an Observation to reflect
917
1460
  3. The 'think' tool is zero-side-effect - it only makes your reasoning observable
918
1461
  4. NEVER write "Observation:" yourself - the system provides it
919
- 5. TASK COMPLETION: When you have completed the task, use the 'finish' tool
1462
+ 5. \u{1F6A8} JSON FORMAT REQUIREMENTS (CRITICAL):
1463
+ When calling ANY tool, ALL parameter values MUST follow strict JSON format:
1464
+ - \u2705 CORRECT: {"pattern":"auth*"} - string values with double quotes
1465
+ - \u274C WRONG: {"pattern":auth*} - missing quotes causes parse error
1466
+ - \u2705 CORRECT: {"items":["file1", "file2"]} - array items quoted
1467
+ - \u274C WRONG: {"items":[file1, file2]} - missing quotes on array items
1468
+ - \u2705 CORRECT: {"count":42, "active":true} - numbers and booleans unquoted
1469
+ - \u274C WRONG: {"count":"42", "active":"true"} - don't quote numbers/booleans
1470
+ - All string values containing special characters (*, ?, ., -, etc.) MUST be quoted
1471
+ - Use double quotes (") not single quotes (')
1472
+ - No trailing commas
1473
+ **System has auto-fix for common errors, but relying on it wastes tokens. Format correctly from start!**
1474
+ 6. \u{1F6A8} TOOL USAGE CONSTRAINTS:
1475
+ - read() tool accepts ONLY exact file paths - NO wildcards (*, **, ?, [])
1476
+ - \u274C WRONG: read({ path: ["src/**/*.java", "*.config"] }) - contains wildcards
1477
+ - \u2705 CORRECT: First glob({ pattern: "src/**/*.java" }), then read({ path: ["src/App.java"] })
1478
+ - Workflow: Use glob() to find files \u2192 Use read() to access them
1479
+ 7. TASK COMPLETION: When you have completed the task, use the 'finish' tool
920
1480
  - Call finish({ answer: "comprehensive summary", success: true })
921
1481
  - The answer should detail what was accomplished, files modified, results achieved
922
1482
  - This is the RECOMMENDED way to signal task completion
@@ -924,9 +1484,10 @@ This cycle continues: think \u2192 act \u2192 observe \u2192 think \u2192 act \u
924
1484
  - NEVER consider a task complete after just generating a summary
925
1485
  - ALWAYS continue execution until all steps in your plan are finished
926
1486
  - ONLY end the task when you have successfully completed the user's original request
927
- 6. Think deeply and systematically: analyze context, plan actions, reflect on results
928
- 7. If you encounter errors or unexpected results, use 'think' to analyze the problem and determine the best next step
929
- 8. ALWAYS maintain high code quality standards - follow project conventions, add appropriate comments, and write clean code
1487
+ 8. Think deeply and systematically: analyze context, plan actions, reflect on results
1488
+ 9. If you encounter errors or unexpected results, use 'think' to analyze the problem and determine the best next step
1489
+ 10. ALWAYS maintain high code quality standards - follow project conventions, add appropriate comments, and write clean code
1490
+ 11. \u{1F6A8} PATH GUESSING PROHIBITION: When user provides ONLY filename WITHOUT full path, MUST use glob("**/filename") to search first. NEVER guess or assume file location. If multiple matches, ask user to clarify.
930
1491
  </critical_rules>`,code_modification:`
931
1492
  <code_modification_workflow>
932
1493
  When modifying existing code:
@@ -969,12 +1530,23 @@ FILE PATH SAFETY CONSTRAINTS:
969
1530
  - NEVER write to system directories (/, /usr, /etc, /System, C:Windows, etc.)
970
1531
  - NEVER write to parent directories using ../ paths
971
1532
  - NEVER write to absolute paths outside the project (e.g., /tmp, /var, C:Users...)
972
- - Use relative paths from project root (e.g., "src/utils/helper.js", "config/app.json")
1533
+ - Use relative paths from project root (e.g., "src/utils/helper.{ext}", "config/app.{ext}" where {ext} is project's language extension)
973
1534
  - If user requests writing outside project directory, politely refuse and explain the security constraint
974
1535
  - Valid paths: "src/...", "lib/...", "config/...", "tests/...", "docs/...", etc.
975
1536
  - Invalid paths: "/etc/...", "../../../...", "C:Windows...", "/usr/local/..."
976
1537
  </code_modification_workflow>`,language_constraints:`
977
1538
  <language_constraints>
1539
+ \u{1F6A8} **CRITICAL: Language-Agnostic Code Generation**
1540
+ - NEVER assume project language based on examples in this prompt (examples use .js/.ts for illustration ONLY)
1541
+ - ALWAYS detect actual project language FIRST before making any assumptions
1542
+ - File extension examples (.js, .py, .java, etc.) in this prompt are for reference only - adapt to actual project
1543
+
1544
+ **Language Detection Priority**:
1545
+ 1. Read .nium/project/project.json to get confirmed project language(s)
1546
+ 2. If project.json unavailable, use glob() to discover actual file extensions
1547
+ 3. Only after detection, proceed with language-appropriate operations
1548
+
1549
+ **Language Constraints by Layer**:
978
1550
  - ALWAYS analyze the project's primary programming language and file context before generating code
979
1551
  - Check .nium/project/project.json for language documentation
980
1552
  - Apply LAYERED language constraints based on file purpose and location:
@@ -1039,7 +1611,68 @@ When working within a plan/task context:
1039
1611
  Example:
1040
1612
  \u274C Bad: Call quickProjectScan() in every step of a plan task
1041
1613
  \u2705 Good: Call read('.nium/project/project.json') to get project info
1042
- </project_exploration_guidelines>`,project_type_detection:`
1614
+ </project_exploration_guidelines>`,file_retrieval_strategy_template:`
1615
+ <file_retrieval_strategy>
1616
+ \u{1F6A8} **CRITICAL: Language-Agnostic File Retrieval**
1617
+ - Path examples in this section use various file extensions for illustration ONLY
1618
+ - NEVER assume file extensions match examples - always detect actual project language first
1619
+ - Adapt all file search patterns to the project's actual language and conventions
1620
+
1621
+ **Core Principle: Leverage known information, minimize file retrieval interactions**
1622
+
1623
+ **File Retrieval Priority Strategy** (highest to lowest):
1624
+
1625
+ 1. **Direct Read from Known Paths (Highest Priority)**
1626
+ - Extract file path references from already-read files and use read() directly
1627
+ {{LANGUAGE_SPECIFIC_PATTERNS}}
1628
+ - \u2705 Advantage: 1 interaction, precise hit
1629
+
1630
+ **\u{1F6A8} CRITICAL: When Path is Ambiguous**
1631
+
1632
+ If user provides ONLY filename (e.g., "read config.json", "\u67E5\u770B Helper file") WITHOUT full path:
1633
+
1634
+ **NEVER GUESS PATHS OR EXTENSIONS!** Follow this workflow:
1635
+ - \u274C NEVER assume file location OR file extension
1636
+ - \u274C NEVER call read() with guessed paths (e.g., src/utils/helper.js in a Java project)
1637
+ - \u2705 MUST use glob(pattern="**/filename") to search first (use broad patterns if extension unknown)
1638
+ - \u2705 If 0 matches: inform user file not found
1639
+ - \u2705 If 1 match: read that file directly
1640
+ - \u2705 If multiple matches: list all in think() and ask user to choose
1641
+
1642
+ Example:
1643
+ \`\`\`
1644
+ User: "read Helper file"
1645
+ \u274C Wrong: read("src/utils/helper.js") [guessing extension in a Java project]
1646
+ \u2705 Correct: glob("**/Helper*") \u2192 discover "Helper.java" \u2192 read("src/main/java/Helper.java")
1647
+ \`\`\`
1648
+
1649
+ 2. **Use Recent Files List (High Priority)**
1650
+ - System provides "recently accessed files" in context
1651
+ - If list contains task-relevant files, read directly
1652
+ - \u2705 Advantage: leverage dynamic context, avoid redundant exploration
1653
+
1654
+ 3. **Use Project Structure Doc (Medium Priority)**
1655
+ - Check .nium/project/project.json for file locations
1656
+ - \u2705 Advantage: structured info, fast location
1657
+
1658
+ 4. **Use glob Pattern Match (Medium-Low Priority)**
1659
+ - When you know filename/extension but not directory
1660
+ - Example: glob("**/config.json") instead of list() exploration
1661
+ - \u2705 Advantage: find all matches in one call
1662
+
1663
+ 5. **Use list Directory Exploration (Lowest Priority)**
1664
+ - Only when file location is completely unknown
1665
+ - Must call think() first to explain why other methods don't apply
1666
+ - \u274C Disadvantage: multiple interactions, low efficiency
1667
+
1668
+ **Decision Flow**:
1669
+ Task requires file access \u2192 Check already-read files for path references? (Yes \u2192 read directly) \u2192 Check recent files list? (Yes \u2192 read directly) \u2192 Know filename/pattern? (Yes \u2192 glob) \u2192 Last resort: list exploration
1670
+
1671
+ **Key Reminders**:
1672
+ - After each read(), analyze file content for path references to build "file dependency graph"
1673
+ - In think(), explicitly state why you chose a specific retrieval strategy
1674
+ - Prefer "inference" over "exploration" - use known info to reduce interactions
1675
+ </file_retrieval_strategy>`,project_type_detection:`
1043
1676
  <project_type_detection>
1044
1677
  IMPORTANT: Identify project build system before making assumptions
1045
1678
 
@@ -1111,34 +1744,119 @@ Step 4 - Provide final answer:
1111
1744
  </example>
1112
1745
 
1113
1746
  <example>
1114
- <scenario>User asks: Add a new function to utils.js</scenario>
1747
+ <scenario>User asks: Add a new function to UserService.java (Java project)</scenario>
1115
1748
  <correct_response>
1116
1749
  Step 1 - Think:
1117
- Call think({ thought: "Need to add a function to utils.js. First I should read the existing file to understand its structure, coding style, and existing functions to ensure consistency." })
1750
+ Call think({ thought: "Need to add a function to UserService.java in this Java project. First I should read the existing file to understand its structure, coding style, and existing methods to ensure consistency." })
1118
1751
 
1119
1752
  Step 2 - Read file:
1120
- Call read({ path: "utils.js" })
1753
+ Call glob({ pattern: "**/UserService.java" })
1754
+
1755
+ [System provides: Observation: Found 1 file: src/main/java/com/example/service/UserService.java]
1756
+
1757
+ Step 3 - Think:
1758
+ Call think({ thought: "Found the file. Now reading it to understand the structure." })
1759
+
1760
+ Step 4 - Read the file:
1761
+ Call read({ path: "src/main/java/com/example/service/UserService.java" })
1121
1762
 
1122
1763
  [System provides: Observation: <file content>]
1123
1764
 
1124
- Step 3 - Think about the content:
1125
- Call think({ thought: "I can see the current structure. The file has 3 existing utility functions with JSDoc comments and follows a specific naming convention. I'll add the new function at the end, following the same style pattern, and use merge() to safely integrate it." })
1765
+ Step 5 - Think about the content:
1766
+ Call think({ thought: "I can see the current structure. The file has 3 existing service methods with Javadoc comments and follows Spring Boot conventions. I'll add the new method at the end, following the same style pattern, and use merge() to safely integrate it." })
1126
1767
 
1127
- Step 4 - Merge changes:
1128
- Call merge({ path: "utils.js", content: "// Existing content...
1129
- // New function added here
1130
- function newFunction() {
1768
+ Step 6 - Merge changes:
1769
+ Call merge({ path: "src/main/java/com/example/service/UserService.java", content: "// Existing content...
1770
+ // New method added here
1771
+ public User createUser(UserDto dto) {
1131
1772
  // Implementation
1132
1773
  }
1133
1774
  " })
1134
1775
 
1135
1776
  [System provides: Observation: merge successful]
1136
1777
 
1137
- Step 5 - Think about result:
1138
- Call think({ thought: "Merge completed successfully without conflicts. The new function is now integrated into utils.js following the project's coding style." })
1778
+ Step 7 - Think about result:
1779
+ Call think({ thought: "Merge completed successfully without conflicts. The new method is now integrated into UserService.java following the project's Java coding style." })
1139
1780
 
1140
- Step 6 - Final answer:
1141
- "Successfully added the new function to utils.js using safe merge, maintaining consistency with existing code style."
1781
+ Step 8 - Final answer:
1782
+ "Successfully added the new method to UserService.java using safe merge, maintaining consistency with existing Java code style."
1783
+ </correct_response>
1784
+ </example>
1785
+
1786
+ <example>
1787
+ <scenario>User asks: \u67E5\u770B\u4E3B\u5165\u53E3\u6587\u4EF6\u7684\u5B9E\u73B0 (Python project)</scenario>
1788
+ <correct_response>
1789
+ \u2705 Efficient approach (leverage known info):
1790
+ Step 1 - Think:
1791
+ Call think({ thought: "Need to view main entry file in this Python project. I'll first check for common Python entry patterns like __main__.py or setup.py to find the entry point." })
1792
+
1793
+ Step 2 - Search for entry files:
1794
+ Call glob({ pattern: "**/__main__.py" })
1795
+
1796
+ [System provides: Observation: Found 1 file: src/app/__main__.py]
1797
+
1798
+ Step 3 - Think:
1799
+ Call think({ thought: "Found __main__.py which is likely the entry point. Reading it directly." })
1800
+
1801
+ Step 4 - Read main file:
1802
+ Call read({ path: "src/app/__main__.py" })
1803
+
1804
+ [Total: 3 interactions, language-appropriate approach]
1805
+ </correct_response>
1806
+ </example>
1807
+
1808
+ <example>
1809
+ <scenario>User asks: \u9605\u8BFB Helper \u6587\u4EF6 (only filename provided, Go project)</scenario>
1810
+ <correct_response>
1811
+ \u2705 Correct approach (search first, discover actual extension):
1812
+ Step 1 - Think:
1813
+ Call think({ thought: "User only provided filename 'Helper' without full path or extension. According to PATH GUESSING PROHIBITION rule, I must search first. Since I don't know the extension, I'll use a broad pattern." })
1814
+
1815
+ Step 2 - Search for file:
1816
+ Call glob({ pattern: "**/Helper*" })
1817
+
1818
+ [System provides: Observation: Found 1 file: pkg/utils/helper.go]
1819
+
1820
+ Step 3 - Think:
1821
+ Call think({ thought: "Found 1 matching file helper.go in this Go project. Reading it directly." })
1822
+
1823
+ Step 4 - Read file:
1824
+ Call read({ path: "pkg/utils/helper.go" })
1825
+
1826
+ [Total: 3 interactions, accurate and language-agnostic]
1827
+
1828
+ \u274C Wrong approach (assuming JavaScript):
1829
+ Step 1: read("src/utils/helper.js") \u2192 Error: file not found
1830
+ [Wasted interaction, violated PATH GUESSING PROHIBITION, assumed wrong language]
1831
+ </correct_response>
1832
+ </example>
1833
+
1834
+ <example>
1835
+ <scenario>User asks: \u67E5\u770B config \u6587\u4EF6 (multiple matches found, Rust project)</scenario>
1836
+ <correct_response>
1837
+ \u2705 Correct approach (ask user when multiple matches):
1838
+ Step 1 - Think:
1839
+ Call think({ thought: "User only provided filename 'config' without path or extension. I must search first using a broad pattern." })
1840
+
1841
+ Step 2 - Search for file:
1842
+ Call glob({ pattern: "**/config*" })
1843
+
1844
+ [System provides: Observation: Found 2 files: src/config.rs, tests/fixtures/config.toml]
1845
+
1846
+ Step 3 - Think:
1847
+ Call think({ thought: "Found 2 matching config files in this Rust project. I need to ask user which one they want to view, cannot decide myself." })
1848
+
1849
+ Step 4 - Ask user:
1850
+ Call finish({
1851
+ answer: "I found 2 config files:
1852
+ 1. src/config.rs (main configuration module)
1853
+ 2. tests/fixtures/config.toml (test configuration)
1854
+
1855
+ Which one would you like to view?",
1856
+ success: true
1857
+ })
1858
+
1859
+ [Wait for user to specify before reading]
1142
1860
  </correct_response>
1143
1861
  </example>
1144
1862
  </examples>`,final_note:`
@@ -1166,7 +1884,7 @@ This makes your decision-making process transparent, debuggable, and more reliab
1166
1884
  - \u8BFB\u53D6\u6587\u4EF6\u5931\u8D25\uFF1A\u68C0\u67E5\u6587\u4EF6\u8DEF\u5F84\u662F\u5426\u6B63\u786E\uFF0C\u6587\u4EF6\u662F\u5426\u5B58\u5728
1167
1885
  - \u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF1A\u68C0\u67E5\u547D\u4EE4\u8BED\u6CD5\uFF0C\u662F\u5426\u9002\u5408\u5F53\u524D\u5E73\u53F0
1168
1886
  - \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u9519\u8BEF\uFF1A\u68C0\u67E5\u53C2\u6570\u7C7B\u578B\u548C\u683C\u5F0F\u662F\u5426\u7B26\u5408\u5DE5\u5177\u5B9A\u4E49
1169
- </error_handling_strategies>`},yc={all:["core","environment_awareness","workflow","critical_rules","error_handling"],code:["code_modification","language_constraints","specialized_task_routing","best_practices"],exploration:["project_exploration","project_type_detection"],simple:["best_practices"]};st=Cc()});var We={};j(We,{TaskComplexity:()=>xe,evaluateTaskComplexity:()=>mg,generatePlanSummary:()=>er,generateTaskPlan:()=>Zn,getTaskFilePath:()=>Sg,listTaskPlans:()=>wg,loadTaskPlan:()=>vg,updateTaskStatus:()=>at});import Se from"fs";import Pe from"path";function pg(o){let e=o.toLowerCase(),t=[/^(读取|查看|显示|打开|列出)/,/^(解释|说明|介绍)/,/文件.*内容/,/^帮我.*查/,/^(read|view|show|open|list)/i,/^(explain|describe|introduce)/i,/file.*content/i,/^help me.*check/i,/^search/i],n=[/实现.*功能/,/(重构|优化).*代码库/,/生成.*并.*测试/,/修复.*并.*验证/,/(创建|添加).*多个/,/implement.*feature/i,/(refactor|optimize).*codebase/i,/generate.*and.*test/i,/fix.*and.*verify/i,/(create|add).*multiple/i,/build.*system/i];for(let s of t)if(s.test(e))return{result:xe.SIMPLE,confidence:.9};for(let s of n)if(s.test(e))return{result:xe.COMPLEX,confidence:.85};let r=e.match(/[\u4e00-\u9fa5a-z]+/gi)||[];return r.length<5&&o.length<50?{result:xe.SIMPLE,confidence:.7}:r.length>20||o.length>200?{result:xe.COMPLEX,confidence:.75}:{result:xe.SIMPLE,confidence:.5}}async function dg(o){let e=Is(o);try{let t=await ee({model:Ie(),messages:[{role:"user",content:e}],temperature:.1,max_tokens:10,useCompression:!0,tools:[]}),{content:n}=t.choices[0].message,r=(n?n.trim():"").toUpperCase();return r==="COMPLEX"||r==="MEDIUM"?xe.COMPLEX:xe.SIMPLE}catch(t){return W(`LLM\u8BC4\u4F30\u5931\u8D25\uFF0C\u9ED8\u8BA4\u4E3A\u7B80\u5355\u4EFB\u52A1: ${t.message}`,"Task"),xe.SIMPLE}}async function mg(o){let e=pg(o);if(e.confidence>.8)return se(`\u5FEB\u901F\u542F\u53D1\u5F0F\u8BC4\u4F30: ${e.result}, \u7F6E\u4FE1\u5EA6: ${e.confidence.toFixed(2)}`,"Task"),e.result;se(`\u542F\u53D1\u5F0F\u8BC4\u4F30\u4E0D\u786E\u5B9A\uFF08\u7F6E\u4FE1\u5EA6: ${e.confidence.toFixed(2)}\uFF09\uFF0C\u4F7F\u7528LLM\u7CBE\u786E\u8BC4\u4F30`,"Task");let t=await dg(o);return t===xe.COMPLEX?W("LLM\u68C0\u6D4B\u5230\u590D\u6742\u4EFB\u52A1\uFF0C\u5C06\u8FDB\u884C\u4EFB\u52A1\u89C4\u5212","Task"):se("LLM\u68C0\u6D4B\u5230\u7B80\u5355\u4EFB\u52A1\uFF0C\u4F7F\u7528\u5355\u6B65\u9AA4\u6A21\u5F0F","Task"),t}function xc(o=[]){let e=o.length>0?o.map(t=>t.name).join(", "):"default";return{name:"create_task_plan",description:"\u751F\u6210\u8BE6\u7EC6\u7684\u4EFB\u52A1\u6267\u884C\u89C4\u5212\uFF0C\u5305\u542B\u591A\u4E2A\u6B65\u9AA4\u548C\u63A8\u8350\u7684\u5B50\u667A\u80FD\u4F53",input_schema:{type:"object",properties:{overview:{type:"string",description:"\u4EFB\u52A1\u6982\u8FF0\uFF0C\u7B80\u8981\u63CF\u8FF0\u4EFB\u52A1\u76EE\u6807"},steps:{type:"array",description:"\u6267\u884C\u6B65\u9AA4\u5217\u8868\uFF0C\u5FC5\u987B\u5305\u542B2-4\u4E2A\u6B65\u9AA4",items:{type:"object",properties:{description:{type:"string",description:"\u6B65\u9AA4\u7684\u8BE6\u7EC6\u63CF\u8FF0\uFF0C\u5E94\u8BE5\u662F\u5927\u9897\u7C92\u5EA6\u7684\u4EFB\u52A1\u62C6\u5206"},subAgent:{type:"string",description:`\u63A8\u8350\u4F7F\u7528\u7684\u5B50\u667A\u80FD\u4F53\u540D\u79F0\u3002\u53EF\u7528\u9009\u9879: ${e}\u3002\u5982\u679C\u6CA1\u6709\u5408\u9002\u7684\u5B50\u667A\u80FD\u4F53\uFF0C\u4F7F\u7528"default"`},allowedTools:{type:"array",description:`\u8BE5\u6B65\u9AA4\u5141\u8BB8\u4F7F\u7528\u7684\u5DE5\u5177\u5217\u8868\uFF08\u4EC5\u5F53 subAgent \u4E3A "default" \u65F6\u751F\u6548\uFF09\u3002
1887
+ </error_handling_strategies>`},Tp={all:["core","environment_awareness","workflow","critical_rules","error_handling","file_retrieval_strategy"],code:["code_modification","language_constraints","specialized_task_routing","best_practices"],exploration:["project_exploration","project_type_detection"],simple:["best_practices"]};Ya=null;cr=kp()});var $t={};B($t,{TaskComplexity:()=>Ve,evaluateTaskComplexity:()=>Cf,generatePlanSummary:()=>Rs,generateTaskPlan:()=>As,getTaskFilePath:()=>kf,listTaskPlans:()=>$f,loadTaskPlan:()=>Ef,updateTaskStatus:()=>nn});import Ge from"fs";import Xe from"path";function xf(s){let e=s.toLowerCase(),t=[/^(读取|查看|显示|打开|列出)/,/^(解释|说明|介绍)/,/文件.*内容/,/^帮我.*查/,/^(read|view|show|open|list)/i,/^(explain|describe|introduce)/i,/file.*content/i,/^help me.*check/i,/^search/i],n=[/实现.*功能/,/(重构|优化).*代码库/,/生成.*并.*测试/,/修复.*并.*验证/,/(创建|添加).*多个/,/implement.*feature/i,/(refactor|optimize).*codebase/i,/generate.*and.*test/i,/fix.*and.*verify/i,/(create|add).*multiple/i,/build.*system/i];for(let o of t)if(o.test(e))return{result:Ve.SIMPLE,confidence:.9};for(let o of n)if(o.test(e))return{result:Ve.COMPLEX,confidence:.85};let r=e.match(/[\u4e00-\u9fa5a-z]+/gi)||[];return r.length<5&&s.length<50?{result:Ve.SIMPLE,confidence:.7}:r.length>20||s.length>200?{result:Ve.COMPLEX,confidence:.75}:{result:Ve.SIMPLE,confidence:.5}}async function Sf(s){let e=Xa(s);try{let t=await Z({model:lt(),messages:[{role:"user",content:e}],temperature:.1,max_tokens:10,useCompression:!0,tools:[]}),{content:n}=t.choices[0].message,r=(n?n.trim():"").toUpperCase();return r==="COMPLEX"||r==="MEDIUM"?Ve.COMPLEX:Ve.SIMPLE}catch(t){return J(`LLM\u8BC4\u4F30\u5931\u8D25\uFF0C\u9ED8\u8BA4\u4E3A\u7B80\u5355\u4EFB\u52A1: ${t.message}`,"Task"),Ve.SIMPLE}}async function Cf(s){let e=xf(s);if(e.confidence>.8)return ve(`\u5FEB\u901F\u542F\u53D1\u5F0F\u8BC4\u4F30: ${e.result}, \u7F6E\u4FE1\u5EA6: ${e.confidence.toFixed(2)}`,"Task"),e.result;ve(`\u542F\u53D1\u5F0F\u8BC4\u4F30\u4E0D\u786E\u5B9A\uFF08\u7F6E\u4FE1\u5EA6: ${e.confidence.toFixed(2)}\uFF09\uFF0C\u4F7F\u7528LLM\u7CBE\u786E\u8BC4\u4F30`,"Task");let t=await Sf(s);return t===Ve.COMPLEX?J("LLM\u68C0\u6D4B\u5230\u590D\u6742\u4EFB\u52A1\uFF0C\u5C06\u8FDB\u884C\u4EFB\u52A1\u89C4\u5212","Task"):ve("LLM\u68C0\u6D4B\u5230\u7B80\u5355\u4EFB\u52A1\uFF0C\u4F7F\u7528\u5355\u6B65\u9AA4\u6A21\u5F0F","Task"),t}function Ep(s=[]){let e=s.length>0?s.map(t=>t.name).join(", "):"default";return{name:"create_task_plan",description:"\u751F\u6210\u8BE6\u7EC6\u7684\u4EFB\u52A1\u6267\u884C\u89C4\u5212\uFF0C\u5305\u542B\u591A\u4E2A\u6B65\u9AA4\u548C\u63A8\u8350\u7684\u5B50\u667A\u80FD\u4F53",input_schema:{type:"object",properties:{overview:{type:"string",description:"\u4EFB\u52A1\u6982\u8FF0\uFF0C\u7B80\u8981\u63CF\u8FF0\u4EFB\u52A1\u76EE\u6807"},steps:{type:"array",description:"\u6267\u884C\u6B65\u9AA4\u5217\u8868\uFF0C\u5FC5\u987B\u5305\u542B2-4\u4E2A\u6B65\u9AA4",items:{type:"object",properties:{description:{type:"string",description:"\u6B65\u9AA4\u7684\u8BE6\u7EC6\u63CF\u8FF0\uFF0C\u5E94\u8BE5\u662F\u5927\u9897\u7C92\u5EA6\u7684\u4EFB\u52A1\u62C6\u5206"},subAgent:{type:"string",description:`\u63A8\u8350\u4F7F\u7528\u7684\u5B50\u667A\u80FD\u4F53\u540D\u79F0\u3002\u53EF\u7528\u9009\u9879: ${e}\u3002\u5982\u679C\u6CA1\u6709\u5408\u9002\u7684\u5B50\u667A\u80FD\u4F53\uFF0C\u4F7F\u7528"default"`},allowedTools:{type:"array",description:`\u8BE5\u6B65\u9AA4\u5141\u8BB8\u4F7F\u7528\u7684\u5DE5\u5177\u5217\u8868\uFF08\u4EC5\u5F53 subAgent \u4E3A "default" \u65F6\u751F\u6548\uFF09\u3002
1170
1888
  \u5E38\u7528\u5DE5\u5177\u7EC4\u5408\uFF1A
1171
1889
  - \u53EA\u8BFB\u5206\u6790: ["read", "glob", "grep", "quickProjectScan", "think", "askUser"]
1172
1890
  - \u4EE3\u7801\u63A2\u7D22: ["read", "glob", "grep", "quickProjectScan", "shell", "think"]
@@ -1174,39 +1892,39 @@ This makes your decision-making process transparent, debuggable, and more reliab
1174
1892
  - \u6D4B\u8BD5\u9A8C\u8BC1: ["read", "shell", "glob", "grep", "think"]
1175
1893
 
1176
1894
  \u5982\u679C\u4E3A\u7A7A\u6570\u7EC4\u6216\u4E0D\u6307\u5B9A\uFF0C\u5219\u4F7F\u7528\u6240\u6709\u53EF\u7528\u5DE5\u5177\u3002
1177
- \u5982\u679C\u4F7F\u7528\u81EA\u5B9A\u4E49\u5B50\u667A\u80FD\u4F53(\u975Edefault)\uFF0C\u6B64\u5B57\u6BB5\u4F1A\u88AB\u5FFD\u7565\u3002`,items:{type:"string"}}},required:["description","subAgent"]},minItems:2,maxItems:4},expectedResult:{type:"string",description:"\u9884\u671F\u7ED3\u679C\uFF0C\u63CF\u8FF0\u5B8C\u6210\u540E\u7684\u9884\u671F\u6548\u679C"}},required:["overview","steps","expectedResult"]}}}async function fg(o,e=[]){se("\u5C1D\u8BD5\u65B9\u68481: Function Calling","Task");let t=As(o,e),n=xc(e),s=(await ee({model:ye(),messages:[{role:"user",content:t}],temperature:.3,max_tokens:2e3,tools:[n],tool_choice:{type:"function",function:{name:"create_task_plan"}}}))?.choices?.[0]?.message?.tool_calls;if(!s||s.length===0)throw new Error("\u6A21\u578B\u6CA1\u6709\u8FD4\u56DE function call");let i=JSON.parse(s[0].function.arguments);if(!i.steps||i.steps.length<2)throw new Error(`\u6B65\u9AA4\u6570\u91CF\u4E0D\u8DB3: ${i.steps?.length||0}`);return i}async function hg(o,e=[]){W("\u5C1D\u8BD5\u65B9\u68482: Markdown + Function Call \u8F6C\u6362","Task");let t=Ls(o,e),r=(await ee({model:ye(),messages:[{role:"user",content:t}],temperature:.3,max_tokens:2e3,tools:[]}))?.choices?.[0]?.message?.content||"";if(!r)throw new Error("\u65E0\u6CD5\u751F\u6210 Markdown \u89C4\u5212");let s=Rs(r),i=xc(e),c=(await ee({model:ye(),messages:[{role:"user",content:s}],temperature:.1,max_tokens:1500,tools:[i],tool_choice:{type:"function",function:{name:"create_task_plan"}}}))?.choices?.[0]?.message?.tool_calls;if(!c||c.length===0)throw new Error("\u65E0\u6CD5\u8F6C\u6362 Markdown \u4E3A\u7ED3\u6784\u5316\u6570\u636E");let l=JSON.parse(c[0].function.arguments);return l.markdown=r,l}function yg(o){return W("\u4F7F\u7528\u9ED8\u8BA4\u964D\u7EA7\u65B9\u6848","Task"),{overview:o,steps:[{description:"\u9700\u6C42\u5206\u6790\u4E0E\u6280\u672F\u65B9\u6848\u8BBE\u8BA1",subAgent:"default"},{description:"\u6838\u5FC3\u529F\u80FD\u5B9E\u73B0",subAgent:"default"},{description:"\u6D4B\u8BD5\u9A8C\u8BC1\u4E0E\u4EE3\u7801\u4F18\u5316",subAgent:"default"}],expectedResult:"\u5B8C\u6210\u4EFB\u52A1\u7684\u6240\u6709\u6B65\u9AA4\uFF0C\u8FBE\u5230\u9884\u671F\u7684\u529F\u80FD\u76EE\u6807"}}function Cg(o){let e=o.steps.map((t,n)=>`- [ ] ${t.description}
1895
+ \u5982\u679C\u4F7F\u7528\u81EA\u5B9A\u4E49\u5B50\u667A\u80FD\u4F53(\u975Edefault)\uFF0C\u6B64\u5B57\u6BB5\u4F1A\u88AB\u5FFD\u7565\u3002`,items:{type:"string"}}},required:["description","subAgent"]},minItems:2,maxItems:4},expectedResult:{type:"string",description:"\u9884\u671F\u7ED3\u679C\uFF0C\u63CF\u8FF0\u5B8C\u6210\u540E\u7684\u9884\u671F\u6548\u679C"}},required:["overview","steps","expectedResult"]}}}async function wf(s,e=[]){ve("\u5C1D\u8BD5\u65B9\u68481: Function Calling","Task");let t=Qa(s,e),n=Ep(e),o=(await Z({model:ge(),messages:[{role:"user",content:t}],temperature:.3,max_tokens:2e3,tools:[n],tool_choice:{type:"function",function:{name:"create_task_plan"}}}))?.choices?.[0]?.message?.tool_calls;if(!o||o.length===0)throw new Error("\u6A21\u578B\u6CA1\u6709\u8FD4\u56DE function call");let i=JSON.parse(o[0].function.arguments);if(!i.steps||i.steps.length<2)throw new Error(`\u6B65\u9AA4\u6570\u91CF\u4E0D\u8DB3: ${i.steps?.length||0}`);return i}async function bf(s,e=[]){J("\u5C1D\u8BD5\u65B9\u68482: Markdown + Function Call \u8F6C\u6362","Task");let t=Za(s,e),r=(await Z({model:ge(),messages:[{role:"user",content:t}],temperature:.3,max_tokens:2e3,tools:[]}))?.choices?.[0]?.message?.content||"";if(!r)throw new Error("\u65E0\u6CD5\u751F\u6210 Markdown \u89C4\u5212");let o=ec(r),i=Ep(e),c=(await Z({model:ge(),messages:[{role:"user",content:o}],temperature:.1,max_tokens:1500,tools:[i],tool_choice:{type:"function",function:{name:"create_task_plan"}}}))?.choices?.[0]?.message?.tool_calls;if(!c||c.length===0)throw new Error("\u65E0\u6CD5\u8F6C\u6362 Markdown \u4E3A\u7ED3\u6784\u5316\u6570\u636E");let l=JSON.parse(c[0].function.arguments);return l.markdown=r,l}function vf(s){return J("\u4F7F\u7528\u9ED8\u8BA4\u964D\u7EA7\u65B9\u6848","Task"),{overview:s,steps:[{description:"\u9700\u6C42\u5206\u6790\u4E0E\u6280\u672F\u65B9\u6848\u8BBE\u8BA1",subAgent:"default"},{description:"\u6838\u5FC3\u529F\u80FD\u5B9E\u73B0",subAgent:"default"},{description:"\u6D4B\u8BD5\u9A8C\u8BC1\u4E0E\u4EE3\u7801\u4F18\u5316",subAgent:"default"}],expectedResult:"\u5B8C\u6210\u4EFB\u52A1\u7684\u6240\u6709\u6B65\u9AA4\uFF0C\u8FBE\u5230\u9884\u671F\u7684\u529F\u80FD\u76EE\u6807"}}function Tf(s){let e=s.steps.map((t,n)=>`- [ ] ${t.description}
1178
1896
  - \u63A8\u8350\u5B50\u667A\u80FD\u4F53: ${t.subAgent}`).join(`
1179
1897
 
1180
1898
  `);return`# \u4EFB\u52A1\u89C4\u5212
1181
1899
 
1182
1900
  ## \u4EFB\u52A1\u6982\u8FF0
1183
- ${o.overview}
1901
+ ${s.overview}
1184
1902
 
1185
1903
  ## \u6267\u884C\u6B65\u9AA4
1186
1904
  ${e}
1187
1905
 
1188
1906
  ## \u9884\u671F\u7ED3\u679C
1189
- ${o.expectedResult}`}async function Zn(o,e=[]){if(!o||typeof o!="string")throw new Error("\u65E0\u6548\u7684\u7528\u6237\u8BF7\u6C42");se("\u6B63\u5728\u751F\u6210\u4EFB\u52A1\u89C4\u5212...","Task");let t=null,n="unknown";try{t=await fg(o,e),n="Function Calling",_("Function Calling \u65B9\u6848\u6210\u529F","Task")}catch(c){W(`Function Calling \u5931\u8D25: ${c.message}`,"Task");try{t=await hg(o,e),n="Markdown + Conversion",_("Markdown \u8F6C\u6362\u65B9\u6848\u6210\u529F","Task")}catch(l){W(`Markdown \u8F6C\u6362\u5931\u8D25: ${l.message}`,"Task"),t=yg(o),n="Default Fallback",W("\u4F7F\u7528\u9ED8\u8BA4\u964D\u7EA7\u65B9\u6848","Task")}}let r=t.markdown||Cg(t),s=t.steps.map((c,l)=>({step:l+1,description:c.description,status:"pending",subAgent:c.subAgent||"default",allowedTools:c.allowedTools||void 0})),i=Rr(),a={markdown:r,tasks:s,taskId:i,strategy:n};return await xg(r,i,a),_(`\u4EFB\u52A1\u89C4\u5212\u751F\u6210\u5B8C\u6210 (\u7B56\u7565: ${n})`,"Task"),se(`\u5171\u5305\u542B ${s.length} \u4E2A\u4EFB\u52A1\u6B65\u9AA4`,"Task"),Mr(),an(r),Mr(),a}async function xg(o,e,t){let n=Pe.join(process.cwd(),".nium","tasks");Se.existsSync(n)||Se.mkdirSync(n,{recursive:!0});let r=`# \u4EFB\u52A1\u89C4\u5212 (ID: ${e})
1907
+ ${s.expectedResult}`}async function As(s,e=[]){if(!s||typeof s!="string")throw new Error("\u65E0\u6548\u7684\u7528\u6237\u8BF7\u6C42");ve("\u6B63\u5728\u751F\u6210\u4EFB\u52A1\u89C4\u5212...","Task");let t=null,n="unknown";try{t=await wf(s,e),n="Function Calling",X("Function Calling \u65B9\u6848\u6210\u529F","Task")}catch(c){J(`Function Calling \u5931\u8D25: ${c.message}`,"Task");try{t=await bf(s,e),n="Markdown + Conversion",X("Markdown \u8F6C\u6362\u65B9\u6848\u6210\u529F","Task")}catch(l){J(`Markdown \u8F6C\u6362\u5931\u8D25: ${l.message}`,"Task"),t=vf(s),n="Default Fallback",J("\u4F7F\u7528\u9ED8\u8BA4\u964D\u7EA7\u65B9\u6848","Task")}}let r=t.markdown||Tf(t),o=t.steps.map((c,l)=>({step:l+1,description:c.description,status:"pending",subAgent:c.subAgent||"default",allowedTools:c.allowedTools||void 0})),i=wo(),a={markdown:r,tasks:o,taskId:i,strategy:n};return await Pf(r,i,a),X(`\u4EFB\u52A1\u89C4\u5212\u751F\u6210\u5B8C\u6210 (\u7B56\u7565: ${n})`,"Task"),ve(`\u5171\u5305\u542B ${o.length} \u4E2A\u4EFB\u52A1\u6B65\u9AA4`,"Task"),So(),Dr(r),So(),a}async function Pf(s,e,t){let n=Xe.join(process.cwd(),".nium","tasks");Ge.existsSync(n)||Ge.mkdirSync(n,{recursive:!0});let r=`# \u4EFB\u52A1\u89C4\u5212 (ID: ${e})
1190
1908
 
1191
1909
  ## \u4EFB\u52A1\u6982\u8FF0
1192
- ${o.substring(o.indexOf("## \u4EFB\u52A1\u6982\u8FF0")+7)}
1910
+ ${s.substring(s.indexOf("## \u4EFB\u52A1\u6982\u8FF0")+7)}
1193
1911
 
1194
1912
  ## \u66F4\u65B0\u65F6\u95F4
1195
- ${new Date().toLocaleString()}`,s=Pe.join(n,`${e}.md`);if(Se.writeFileSync(s,r,"utf8"),_(`\u4EFB\u52A1\u89C4\u5212\u5DF2\u4FDD\u5B58\u5230: ${s}`,"Task"),t){let i={taskId:t.taskId,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),status:"pending",currentStep:0,totalSteps:t.tasks.length,strategy:t.strategy,markdown:t.markdown,tasks:t.tasks.map(c=>({step:c.step,description:c.description,status:c.status,subAgent:c.subAgent,startTime:null,endTime:null,duration:null,error:null}))},a=Pe.join(n,`${e}.json`);Se.writeFileSync(a,JSON.stringify(i,null,2),"utf8"),_(`JSON \u6570\u636E\u5DF2\u4FDD\u5B58\u5230: ${a}`,"Task")}}async function at(o,e,t){let n=Pe.join(process.cwd(),".nium","tasks"),r=Pe.join(n,`${o}.md`);if(!Se.existsSync(r))return ke(`\u4EFB\u52A1\u6587\u4EF6\u4E0D\u5B58\u5728: ${r}`,"Task"),!1;try{let i=Se.readFileSync(r,"utf8").split(`
1196
- `),a=!1,c=1,l=[];for(let u of i){if(u.trim().includes("## \u6267\u884C\u6B65\u9AA4")||u.trim().includes("##\u6267\u884C\u6B65\u9AA4")){a=!0,l.push(u);continue}if(u.trim().includes("## \u66F4\u65B0\u65F6\u95F4")){l.push("## \u66F4\u65B0\u65F6\u95F4"),l.push(new Date().toLocaleString());continue}if(a&&u.trim().startsWith("##")&&!u.trim().includes("\u66F4\u65B0\u65F6\u95F4")){a=!1,l.push(u);continue}if(a){let p=u.trim().match(/^-\s*\[(.)\]\s*(.+)/);if(p&&c===e){let g=" ";t==="in_progress"&&(g="-"),t==="completed"&&(g="x"),l.push(`- [${g}] ${p[2]}`),c++;continue}p&&c++}l.push(u)}return Se.writeFileSync(r,l.join(`
1197
- `),"utf8"),_(`\u4EFB\u52A1 ${o} \u6B65\u9AA4 ${e} \u72B6\u6001\u5DF2\u66F4\u65B0\u4E3A ${t}`,"Task"),!0}catch(s){return ke(`\u66F4\u65B0\u4EFB\u52A1\u72B6\u6001\u5931\u8D25: ${s.message}`,"Task"),!1}}function Sg(o){let e=Pe.join(process.cwd(),".nium","tasks");return Pe.join(e,`${o}.md`)}function vg(o){let e=Pe.join(process.cwd(),".nium","tasks"),t=Pe.join(e,`${o}.json`);if(!Se.existsSync(t))return ke(`\u4EFB\u52A1\u6587\u4EF6\u4E0D\u5B58\u5728: ${t}`,"Task"),null;try{let n=Se.readFileSync(t,"utf8"),r=JSON.parse(n);return _(`\u6210\u529F\u52A0\u8F7D\u4EFB\u52A1: ${o}`,"Task"),r}catch(n){return ke(`\u89E3\u6790\u4EFB\u52A1\u6587\u4EF6\u5931\u8D25: ${n.message}`,"Task"),null}}function wg(){let o=Pe.join(process.cwd(),".nium","tasks");return Se.existsSync(o)?Se.readdirSync(o).filter(n=>n.endsWith(".json")).map(n=>n.replace(".json","")):[]}function er(o){if(!o||!o.tasks||o.tasks.length===0)return"\u65E0\u6709\u6548\u4EFB\u52A1\u6B65\u9AA4";let e=[];e.push(`
1198
- \u4EFB\u52A1\u89C4\u5212\u6458\u8981:`),e.push("\u2500".repeat(50));for(let t of o.tasks){let n=t.subAgent!=="default"?`[${t.subAgent}]`:"[\u9ED8\u8BA4\u667A\u80FD\u4F53]";e.push(`${t.step}. ${t.description} ${n}`)}return e.push("\u2500".repeat(50)),e.join(`
1199
- `)}var xe,$e=C(()=>{le();ve();Dr();it();cn();xe={SIMPLE:"simple",COMPLEX:"complex"}});function tr(o,e={format:"markdown"}){let{format:t,maxSections:n=100,detailed:r=!0,customTitle:s}=e;switch(t){case"markdown":return Sc(o,r,s);case"text":return bg(o,r);case"summary":return Tg(o,n);default:return Sc(o,r,s)}}function Sc(o,e,t){let n=[];return n.push(t||`# \u9879\u76EE\u7ED3\u6784\u4FE1\u606F
1200
- `),kg(n,o,e),Eg(n,o,e),Pg(n,o,e),$g(n,o,e),Mg(n,o,e),Ig(n,o,e),Ag(n,o,e),n.length<=1?"\u6682\u65E0\u8BE6\u7EC6\u9879\u76EE\u7ED3\u6784\u4FE1\u606F\u3002":n.join(`
1201
- `)}function bg(o,e){let t=[];if(t.push("\u{1F4CA} \u9879\u76EE\u57FA\u7840\u4FE1\u606F\u6458\u8981"),t.push("\u2550".repeat(50)),t.push(""),t.push(`\u{1F4E6} \u9879\u76EE\u540D\u79F0: ${o.projectName||"\u672A\u77E5"}`),t.push(`\u{1F4CC} \u7248\u672C: ${o.version||"\u672A\u77E5"}`),o.description&&t.push(`\u{1F4DD} \u63CF\u8FF0: ${o.description}`),t.push(""),t.push(`\u{1F310} \u4E3B\u8981\u8BED\u8A00: ${o.primaryLanguage||"\u672A\u77E5"}`),o.buildTool&&t.push(`\u{1F527} \u6784\u5EFA\u5DE5\u5177: ${o.buildTool}`),o.packageManager&&t.push(`\u{1F4E6} \u5305\u7BA1\u7406\u5668: ${o.packageManager}`),o.runtime&&t.push(`\u2699\uFE0F \u8FD0\u884C\u65F6: ${o.runtime}`),t.push(""),o.fileStats){t.push("\u{1F4C1} \u6587\u4EF6\u7EDF\u8BA1:");let n=o.fileStats;t.push(` \u603B\u6587\u4EF6\u6570: ${n.totalFiles||0}`),t.push(` \u6E90\u4EE3\u7801\u6587\u4EF6: ${n.sourceFiles||0}`),t.push(` \u914D\u7F6E\u6587\u4EF6: ${n.configFiles||0}`),t.push(` \u6587\u6863\u6587\u4EF6: ${n.docFiles||0}`),t.push(` \u6D4B\u8BD5\u6587\u4EF6: ${n.testFiles||0}`),t.push("")}return o.dependencyCount&&(t.push("\u{1F4DA} \u4F9D\u8D56\u7EDF\u8BA1:"),t.push(` \u751F\u4EA7\u4F9D\u8D56: ${o.dependencyCount.production||0} \u4E2A`),t.push(` \u5F00\u53D1\u4F9D\u8D56: ${o.dependencyCount.development||0} \u4E2A`),t.push("")),o.languages&&o.languages.length>0&&(t.push("\u{1F30D} \u8BED\u8A00\u5206\u5E03:"),o.languages.slice(0,5).forEach(n=>{t.push(` ${n.language}: ${n.count} \u4E2A\u6587\u4EF6 (${n.percentage})`)}),t.push("")),t.join(`
1202
- `)}function Tg(o,e){let t=[],n=0;if((o.projectName||o.version||o.description)&&(o.projectName&&t.push(`**\u9879\u76EE\u540D\u79F0**: ${o.projectName}`),o.version&&t.push(`**\u7248\u672C**: ${o.version}`),o.description&&t.push(`**\u63CF\u8FF0**: ${o.description}`),n++),n>=e||((o.primaryLanguage||o.buildTool)&&(t.push(""),o.primaryLanguage&&t.push(`**\u4E3B\u8981\u8BED\u8A00**: ${o.primaryLanguage}`),o.buildTool&&t.push(`**\u6784\u5EFA\u5DE5\u5177**: ${o.buildTool}`),o.packageManager&&t.push(`**\u5305\u7BA1\u7406\u5668**: ${o.packageManager}`),o.runtime&&t.push(`**\u8FD0\u884C\u65F6**: ${o.runtime}`),n++),n>=e))return t.join(`
1203
- `);if(o.fileStats){t.push("");let r=o.fileStats;r.totalFiles&&t.push(`**\u603B\u6587\u4EF6\u6570**: ${r.totalFiles}`),r.sourceFiles&&t.push(`**\u6E90\u6587\u4EF6**: ${r.sourceFiles}`),r.configFiles&&t.push(`**\u914D\u7F6E\u6587\u4EF6**: ${r.configFiles}`),r.testFiles&&t.push(`**\u6D4B\u8BD5\u6587\u4EF6**: ${r.testFiles}`),n++}return n>=e||(o.languages&&o.languages.length>0&&(t.push(""),t.push("**\u8BED\u8A00\u5206\u5E03**:"),o.languages.slice(0,5).forEach(r=>{t.push(`- ${r.language}: ${r.percentage}%`)}),n++),n>=e)||(o.dependencies&&Object.keys(o.dependencies).length>0&&(t.push(""),t.push("**\u4E3B\u8981\u4F9D\u8D56**:"),Object.entries(o.dependencies).slice(0,5).forEach(([s,i])=>{t.push(`- ${s}: ${i}`)}),n++),n>=e)?t.join(`
1204
- `):(o.codeStandards&&o.codeStandards.length>0&&(t.push(""),t.push("**\u4EE3\u7801\u89C4\u8303**:"),o.codeStandards.slice(0,3).forEach(r=>{t.push(`- ${r}`)})),t.length>0?t.join(`
1205
- `):"\u6682\u65E0\u9879\u76EE\u4FE1\u606F\u3002")}function kg(o,e,t){!e.projectName&&!e.version&&!e.description||(o.push("## \u9879\u76EE\u57FA\u672C\u4FE1\u606F"),e.projectName&&o.push(`**\u9879\u76EE\u540D\u79F0**: ${e.projectName}`),e.version&&o.push(`**\u7248\u672C**: ${e.version}`),e.description&&o.push(`**\u63CF\u8FF0**: ${e.description}`),o.push(""))}function Eg(o,e,t){!e.primaryLanguage&&!e.buildTool&&!e.packageManager&&!e.runtime||(o.push("## \u6280\u672F\u6808\u4FE1\u606F"),e.primaryLanguage&&o.push(`**\u4E3B\u8981\u7F16\u7A0B\u8BED\u8A00**: ${e.primaryLanguage}`),e.buildTool&&o.push(`**\u6784\u5EFA\u5DE5\u5177**: ${e.buildTool}`),e.packageManager&&o.push(`**\u5305\u7BA1\u7406\u5668**: ${e.packageManager}`),e.runtime&&o.push(`**\u8FD0\u884C\u65F6**: ${e.runtime}`),o.push(""))}function Pg(o,e,t){if(!e.fileStats)return;let n=e.fileStats;o.push("## \u6587\u4EF6\u7EDF\u8BA1"),n.totalFiles&&o.push(`- **\u603B\u6587\u4EF6\u6570**: ${n.totalFiles}`),n.sourceFiles&&o.push(`- **\u6E90\u6587\u4EF6**: ${n.sourceFiles}`),n.configFiles&&o.push(`- **\u914D\u7F6E\u6587\u4EF6**: ${n.configFiles}`),n.docFiles&&o.push(`- **\u6587\u6863\u6587\u4EF6**: ${n.docFiles}`),n.testFiles&&o.push(`- **\u6D4B\u8BD5\u6587\u4EF6**: ${n.testFiles}`),o.push("")}function $g(o,e,t){!e.languages||e.languages.length===0||(o.push("## \u7F16\u7A0B\u8BED\u8A00\u5206\u6790"),t?e.languages.forEach(n=>{o.push(`- **${n.language}**: ${n.count} \u4E2A\u6587\u4EF6 (${n.percentage}%)`)}):e.languages.slice(0,5).forEach(n=>{o.push(`- **${n.language}**: ${n.percentage}%`)}),o.push(""))}function Mg(o,e,t){let n=e.dependencies&&Object.keys(e.dependencies).length>0,r=e.devDependencies&&Object.keys(e.devDependencies).length>0;!n&&!r||(o.push("## \u4F9D\u8D56\u5173\u7CFB"),n&&(o.push("### \u751F\u4EA7\u4F9D\u8D56"),(t?Object.entries(e.dependencies):Object.entries(e.dependencies).slice(0,10)).forEach(([i,a])=>{o.push(`- **${i}**: ${a}`)}),!t&&Object.keys(e.dependencies).length>10&&o.push(`
1206
- *...\u8FD8\u6709 ${Object.keys(e.dependencies).length-10} \u4E2A\u4F9D\u8D56*`),o.push("")),r&&(o.push("### \u5F00\u53D1\u4F9D\u8D56"),(t?Object.entries(e.devDependencies):Object.entries(e.devDependencies).slice(0,10)).forEach(([i,a])=>{o.push(`- **${i}**: ${a}`)}),!t&&Object.keys(e.devDependencies).length>10&&o.push(`
1207
- *...\u8FD8\u6709 ${Object.keys(e.devDependencies).length-10} \u4E2A\u4F9D\u8D56*`),o.push("")))}function Ig(o,e,t){if(!e.entryPoints||e.entryPoints.length===0)return;o.push("## \u5165\u53E3\u6587\u4EF6"),(t?e.entryPoints:e.entryPoints.slice(0,5)).forEach(r=>{o.push(`- \`${r}\``)}),!t&&e.entryPoints.length>5&&o.push(`
1208
- *...\u8FD8\u6709 ${e.entryPoints.length-5} \u4E2A\u5165\u53E3\u6587\u4EF6*`),o.push("")}function Ag(o,e,t){if(!e.codeStandards||e.codeStandards.length===0)return;o.push("## \u4EE3\u7801\u89C4\u8303"),(t?e.codeStandards:e.codeStandards.slice(0,5)).forEach(r=>{o.push(`- ${r}`)}),!t&&e.codeStandards.length>5&&o.push(`
1209
- *...\u8FD8\u6709 ${e.codeStandards.length-5} \u4E2A\u89C4\u8303*`),o.push("")}var ro=C(()=>{});import*as Jt from"os";var Ve,ze,He,Je,vc=C(()=>{Y();ro();Ve=class{originalTask;plan;stepSummaries;sharedState;stepDependencies;explorationHistory;constructor(){this.originalTask=null,this.plan={tasks:[],currentStep:0,totalSteps:0},this.stepSummaries=new Map,this.sharedState={projectInfo:null,rules:null,dependencies:null,recentFiles:[],knownIssues:[]},this.stepDependencies=new Map,this.explorationHistory=null}initializeTask(e,t){this.originalTask=e,this.plan={tasks:t.tasks||[],currentStep:0,totalSteps:t.tasks?.length||0},M(`\u5168\u5C40\u4E0A\u4E0B\u6587\u521D\u59CB\u5316: ${this.plan.totalSteps} \u4E2A\u6B65\u9AA4`)}recordStepCompletion(e,t,n={},r){this.stepSummaries.set(e,{summary:t,metadata:n,timestamp:new Date().toISOString()}),r&&r.buildHistoryIndex(e,t,n),x(`\u6B65\u9AA4 ${e} \u6458\u8981\u5DF2\u8BB0\u5F55: ${t.substring(0,50)}...`)}getStepSummary(e){return this.stepSummaries.get(e)}updateSharedState(e,t){this.sharedState.hasOwnProperty(e)?(this.sharedState[e]=t,x(`\u5171\u4EAB\u72B6\u6001\u66F4\u65B0: ${e}`)):x(`\u8B66\u544A: \u672A\u77E5\u7684\u5171\u4EAB\u72B6\u6001\u952E: ${e}`)}addRecentFile(e){this.sharedState.recentFiles.unshift(e),this.sharedState.recentFiles.length>10&&this.sharedState.recentFiles.pop()}setStepDependencies(e,t){this.stepDependencies.set(e,t)}getCompactSummary(){return{task:this.originalTask,progress:`${this.plan.currentStep}/${this.plan.totalSteps}`,completedSteps:Array.from(this.stepSummaries.keys()),recentFiles:this.sharedState.recentFiles.slice(0,5)}}getPlan(){return this.plan}setCurrentStep(e){this.plan.currentStep=e}getSharedState(){return this.sharedState}getStepDependencies(){return this.stepDependencies}getOriginalTask(){return this.originalTask}recordExplorationResult(e){let t=e.length>200?e.substring(0,200)+"...":e;this.explorationHistory={timestamp:Date.now(),content:e,summary:t},M("\u5DF2\u8BB0\u5F55\u9879\u76EE\u63A2\u7D22\u7ED3\u679C\u5230\u5168\u5C40\u4E0A\u4E0B\u6587")}getExplorationHistory(){return this.explorationHistory}},ze=class{globalContext;historyIndex=new Map;constructor(e){this.globalContext=e}async selectRelevantHistory(e,t,n){let r=[],s=new Set,i=this.calculateTargetHistoryCount(t),a=Math.min(i*2,20);x(`\u4EFB\u52A1\u590D\u6742\u5EA6\u5206\u6790: \u76EE\u6807\u5386\u53F2\u6570\u91CF=${i}, \u6700\u5927\u7D22\u5F15\u7ED3\u679C=${a}`);let c=this.globalContext.getStepDependencies().get(e)||[];for(let g of c){let d=this.globalContext.getStepSummary(g);d&&(r.push({stepId:g,type:"dependency",content:d.summary,metadata:d.metadata}),s.add(g))}let l=this.findRelevantStepsWithIndex(t,a);for(let g of l){if(s.has(g)||g>=e)continue;let d=this.globalContext.getStepSummary(g);if(d&&(r.push({stepId:g,type:"recent",content:d.summary,metadata:d.metadata}),s.add(g),r.length>=i))break}let u=Math.max(3,Math.floor(i/2));if(r.length<u){let g=this.getRecentCompletedSteps(i);for(let d of g){if(s.has(d)||d>=e)continue;let m=this.globalContext.getStepSummary(d);if(m&&(r.push({stepId:d,type:"recent",content:m.summary,metadata:m.metadata}),s.add(d),r.length>=u))break}}if(n==="explorer")x("\u8DF3\u8FC7\u63A2\u7D22\u5386\u53F2\u6CE8\u5165 (\u5F53\u524D\u4E3A explorer \u667A\u80FD\u4F53)");else{let g=this.globalContext.getExplorationHistory();g&&(r.push({stepId:0,type:"exploration",content:g.content,metadata:{timestamp:g.timestamp,summary:g.summary}}),x(`\u5DF2\u6DFB\u52A0\u63A2\u7D22\u5386\u53F2\u5230\u4E0A\u4E0B\u6587 (\u667A\u80FD\u4F53: ${n||"unknown"})`))}return x(`\u4E3A\u6B65\u9AA4 ${e} \u9009\u62E9\u4E86 ${r.length} \u6761\u76F8\u5173\u5386\u53F2 (\u4F7F\u7528\u7D22\u5F15\u4F18\u5316)`),r}getRecentCompletedSteps(e){return Array.from(this.globalContext.getStepDependencies().keys()).slice(-e)}calculateTargetHistoryCount(e){let t=5;e.length>300?t+=5:e.length>150?t+=3:e.length>80&&(t+=1);let n=["\u91CD\u6784","refactor","\u4F18\u5316","optimize","\u8BBE\u8BA1","design","\u67B6\u6784","architecture","\u5B9E\u73B0","implement","\u5F00\u53D1","develop","\u96C6\u6210","integrate","\u8FC1\u79FB","migrate","\u4FEE\u590D","fix","\u8C03\u8BD5","debug","\u5206\u6790","analyze","\u8BC4\u4F30","evaluate"],r=["\u8BFB\u53D6","read","\u67E5\u770B","view","\u663E\u793A","display","\u6253\u5370","print","\u5217\u51FA","list","\u67E5\u627E","find","\u641C\u7D22","search"],s=e.toLowerCase(),i=n.filter(u=>s.includes(u)).length;t+=i*2;let a=r.filter(u=>s.includes(u)).length;t-=a;let c=e.match(/\.(ts|js|tsx|jsx|py|java|go|rs|cpp|c|h|md|json|yaml|yml)/gi);c&&c.length>3?t+=3:c&&c.length>1&&(t+=1);let l=e.match(/模块|组件|系统|服务|module|component|system|service/gi);return l&&l.length>2&&(t+=2),Math.max(5,Math.min(t,20))}buildHistoryIndex(e,t,n){let r=this.extractKeywords(t);n&&(n.toolsUsed&&Array.isArray(n.toolsUsed)&&n.toolsUsed.forEach(i=>{i&&i.length>0&&r.push(i.toLowerCase())}),n.filesAccessed&&Array.isArray(n.filesAccessed)&&n.filesAccessed.forEach(i=>{if(i){let a=i.split(/[/\\]/).pop()?.split(".")[0];a&&a.length>2&&r.push(a.toLowerCase()),i.split(/[/\\]/).filter(l=>l&&l.length>2).forEach(l=>{["src","dist","node_modules","test","tests","lib","bin"].includes(l.toLowerCase())||r.push(l.toLowerCase())})}}));let s=[...new Set(r)];s.forEach(i=>{this.historyIndex.has(i)||this.historyIndex.set(i,new Set),this.historyIndex.get(i).add(e)}),x(`\u4E3A\u6B65\u9AA4 ${e} \u6784\u5EFA\u4E86\u7D22\u5F15\uFF0C\u5305\u542B ${s.length} \u4E2A\u5173\u952E\u8BCD\uFF08\u6458\u8981: ${r.length-(s.length-r.length)}, \u5143\u6570\u636E: ${s.length-r.length}\uFF09`)}extractKeywords(e){let t=this.getStopWords();return e.toLowerCase().replace(/[^\w\s\u4e00-\u9fa5]/g," ").split(/[\s\u3000]+/).filter(n=>n.length<2?!1:!t.has(n)).slice(0,20)}getStopWords(){return new Set(["the","is","at","which","on","and","or","but","in","with","to","for","of","a","an","as","by","from","has","have","had","be","been","being","are","was","were","will","would","should","could","may","might","can","do","does","did","done","this","that","these","those","it","its","they","them","their","we","our","you","your","he","she","his","her","him","me","my","i","am","not","no","yes","all","any","some","each","every","both","few","more","most","into","through","during","before","after","above","below","up","down","out","off","over","under","again","further","then","once","here","there","when","where","why","how","what","who","whom","whose","which","about","against","between","into","through","\u7684","\u4E86","\u5728","\u662F","\u6211","\u6709","\u548C","\u5C31","\u4E0D","\u4EBA","\u90FD","\u4E00","\u4E00\u4E2A","\u4E0A","\u4E5F","\u5F88","\u5230","\u8BF4","\u8981","\u53BB","\u4F60","\u4F1A","\u7740","\u6CA1\u6709","\u770B","\u597D","\u81EA\u5DF1","\u8FD9","\u90A3","\u91CC","\u4E2A","\u5C31\u662F","\u554A","\u51FA","\u6765","\u4E48","\u5417","\u5462","\u5427","\u54E6","\u5566","\u5440","\u561B","\u54C8","\u54EA","\u4EC0\u4E48","\u600E\u4E48","\u4E3A\u4EC0\u4E48","\u591A\u5C11","\u51E0\u4E2A","\u8FD9\u4E2A","\u90A3\u4E2A","\u8FD9\u4E9B","\u90A3\u4E9B","\u8FD9\u6837","\u90A3\u6837","\u5982\u4F55","\u53EF\u4EE5","\u80FD\u591F","\u5E94\u8BE5","\u5FC5\u987B","\u9700\u8981","\u60F3\u8981","\u5E0C\u671B","\u89C9\u5F97","\u8BA4\u4E3A","\u77E5\u9053","\u660E\u767D","\u5DF2\u7ECF","\u6B63\u5728","\u5C06\u8981","\u66FE\u7ECF","\u4E00\u76F4","\u603B\u662F","\u7ECF\u5E38","\u6709\u65F6","\u5076\u5C14","\u4ECE\u6765","\u6C38\u8FDC","\u975E\u5E38","\u5F88\u591A","\u4E00\u4E9B","\u6240\u6709","\u6BCF\u4E2A","\u4EFB\u4F55","\u67D0\u4E2A","\u53E6\u5916","\u5176\u4ED6","\u522B\u7684","\u5176\u5B83","\u56E0\u4E3A","\u6240\u4EE5","\u4F46\u662F","\u7136\u800C","\u867D\u7136","\u5982\u679C","\u5047\u5982","\u9664\u975E","\u53EA\u8981","\u65E0\u8BBA","\u4E0D\u7BA1","\u800C\u4E14","\u5E76\u4E14","\u6216\u8005","\u8FD8\u662F","\u4E0D\u4EC5","\u800C\u4E14","\u65E2\u7136","\u7531\u4E8E","\u4E3A\u4E86","\u4EE5\u4FBF","\u4EE5\u514D","step","task","action","result","success","failed","error","warning","info","\u6B65\u9AA4","\u4EFB\u52A1","\u64CD\u4F5C","\u7ED3\u679C","\u6210\u529F","\u5931\u8D25","\u9519\u8BEF","\u8B66\u544A","\u4FE1\u606F","\u5B8C\u6210","\u6267\u884C"])}findRelevantStepsWithIndex(e,t=5){let n=this.extractKeywords(e),r=new Map;return n.forEach(s=>{let i=this.historyIndex.get(s);i&&i.forEach(a=>{r.set(a,(r.get(a)||0)+1)})}),Array.from(r.entries()).sort((s,i)=>i[1]-s[1]).slice(0,t).map(([s])=>s)}isLikelyRelevant(e,t){let n=new Set(this.extractKeywords(e));return this.extractKeywords(t).filter(i=>n.has(i)).length>=2}async selectRelevantHistoryWithLLM(e,t,n){let{MODEL:r}=await Promise.resolve().then(()=>(le(),wt)),{callModelAPI:s}=await Promise.resolve().then(()=>(ve(),Gt)),i=Array.from(this.globalContext.getStepDependencies().entries()).map(([c,l])=>{let u=this.globalContext.getStepSummary(c);return u?`\u6B65\u9AA4${c}: ${u.summary}`:""}).filter(Boolean).join(`
1913
+ ${H()}`,o=Xe.join(n,`${e}.md`);if(Ge.writeFileSync(o,r,"utf8"),X(`\u4EFB\u52A1\u89C4\u5212\u5DF2\u4FDD\u5B58\u5230: ${o}`,"Task"),t){let i={taskId:t.taskId,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),status:"pending",currentStep:0,totalSteps:t.tasks.length,strategy:t.strategy,markdown:t.markdown,tasks:t.tasks.map(c=>({step:c.step,description:c.description,status:c.status,subAgent:c.subAgent,startTime:null,endTime:null,duration:null,error:null}))},a=Xe.join(n,`${e}.json`);Ge.writeFileSync(a,JSON.stringify(i,null,2),"utf8"),X(`JSON \u6570\u636E\u5DF2\u4FDD\u5B58\u5230: ${a}`,"Task")}}async function nn(s,e,t){let n=Xe.join(process.cwd(),".nium","tasks"),r=Xe.join(n,`${s}.md`);if(!Ge.existsSync(r))return xe(`\u4EFB\u52A1\u6587\u4EF6\u4E0D\u5B58\u5728: ${r}`,"Task"),!1;try{let i=Ge.readFileSync(r,"utf8").split(`
1914
+ `),a=!1,c=1,l=[];for(let u of i){if(u.trim().includes("## \u6267\u884C\u6B65\u9AA4")||u.trim().includes("##\u6267\u884C\u6B65\u9AA4")){a=!0,l.push(u);continue}if(u.trim().includes("## \u66F4\u65B0\u65F6\u95F4")){l.push("## \u66F4\u65B0\u65F6\u95F4"),l.push(H());continue}if(a&&u.trim().startsWith("##")&&!u.trim().includes("\u66F4\u65B0\u65F6\u95F4")){a=!1,l.push(u);continue}if(a){let p=u.trim().match(/^-\s*\[(.)\]\s*(.+)/);if(p&&c===e){let g=" ";t==="in_progress"&&(g="-"),t==="completed"&&(g="x"),l.push(`- [${g}] ${p[2]}`),c++;continue}p&&c++}l.push(u)}return Ge.writeFileSync(r,l.join(`
1915
+ `),"utf8"),X(`\u4EFB\u52A1 ${s} \u6B65\u9AA4 ${e} \u72B6\u6001\u5DF2\u66F4\u65B0\u4E3A ${t}`,"Task"),!0}catch(o){return xe(`\u66F4\u65B0\u4EFB\u52A1\u72B6\u6001\u5931\u8D25: ${o.message}`,"Task"),!1}}function kf(s){let e=Xe.join(process.cwd(),".nium","tasks");return Xe.join(e,`${s}.md`)}function Ef(s){let e=Xe.join(process.cwd(),".nium","tasks"),t=Xe.join(e,`${s}.json`);if(!Ge.existsSync(t))return xe(`\u4EFB\u52A1\u6587\u4EF6\u4E0D\u5B58\u5728: ${t}`,"Task"),null;try{let n=Ge.readFileSync(t,"utf8"),r=JSON.parse(n);return X(`\u6210\u529F\u52A0\u8F7D\u4EFB\u52A1: ${s}`,"Task"),r}catch(n){return xe(`\u89E3\u6790\u4EFB\u52A1\u6587\u4EF6\u5931\u8D25: ${n.message}`,"Task"),null}}function $f(){let s=Xe.join(process.cwd(),".nium","tasks");return Ge.existsSync(s)?Ge.readdirSync(s).filter(n=>n.endsWith(".json")).map(n=>n.replace(".json","")):[]}function Rs(s){if(!s||!s.tasks||s.tasks.length===0)return"\u65E0\u6709\u6548\u4EFB\u52A1\u6B65\u9AA4";let e=[];e.push(`
1916
+ \u4EFB\u52A1\u89C4\u5212\u6458\u8981:`),e.push("\u2500".repeat(50));for(let t of s.tasks){let n=t.subAgent!=="default"?`[${t.subAgent}]`:"[\u9ED8\u8BA4\u667A\u80FD\u4F53]";e.push(`${t.step}. ${t.description} ${n}`)}return e.push("\u2500".repeat(50)),e.join(`
1917
+ `)}var Ve,Qe=S(()=>{ae();Ie();bo();Fe();tn();Tt();Ve={SIMPLE:"simple",COMPLEX:"complex"}});function Ls(s,e={format:"markdown"}){let{format:t,maxSections:n=100,detailed:r=!0,customTitle:o}=e;switch(t){case"markdown":return $p(s,r,o);case"text":return If(s,r);case"summary":return Mf(s,n);default:return $p(s,r,o)}}function $p(s,e,t){let n=[];return n.push(t||`# \u9879\u76EE\u7ED3\u6784\u4FE1\u606F
1918
+ `),Af(n,s,e),Rf(n,s,e),Lf(n,s,e),jf(n,s,e),Df(n,s,e),Ff(n,s,e),Of(n,s,e),n.length<=1?"\u6682\u65E0\u8BE6\u7EC6\u9879\u76EE\u7ED3\u6784\u4FE1\u606F\u3002":n.join(`
1919
+ `)}function If(s,e){let t=[];if(t.push("\u{1F4CA} \u9879\u76EE\u57FA\u7840\u4FE1\u606F\u6458\u8981"),t.push("\u2550".repeat(50)),t.push(""),t.push(`\u{1F4E6} \u9879\u76EE\u540D\u79F0: ${s.projectName||"\u672A\u77E5"}`),t.push(`\u{1F4CC} \u7248\u672C: ${s.version||"\u672A\u77E5"}`),s.description&&t.push(`\u{1F4DD} \u63CF\u8FF0: ${s.description}`),t.push(""),t.push(`\u{1F310} \u4E3B\u8981\u8BED\u8A00: ${s.primaryLanguage||"\u672A\u77E5"}`),s.buildTool&&t.push(`\u{1F527} \u6784\u5EFA\u5DE5\u5177: ${s.buildTool}`),s.packageManager&&t.push(`\u{1F4E6} \u5305\u7BA1\u7406\u5668: ${s.packageManager}`),s.runtime&&t.push(`\u2699\uFE0F \u8FD0\u884C\u65F6: ${s.runtime}`),t.push(""),s.fileStats){t.push("\u{1F4C1} \u6587\u4EF6\u7EDF\u8BA1:");let n=s.fileStats;t.push(` \u603B\u6587\u4EF6\u6570: ${n.totalFiles||0}`),t.push(` \u6E90\u4EE3\u7801\u6587\u4EF6: ${n.sourceFiles||0}`),t.push(` \u914D\u7F6E\u6587\u4EF6: ${n.configFiles||0}`),t.push(` \u6587\u6863\u6587\u4EF6: ${n.docFiles||0}`),t.push(` \u6D4B\u8BD5\u6587\u4EF6: ${n.testFiles||0}`),t.push("")}return s.dependencyCount&&(t.push("\u{1F4DA} \u4F9D\u8D56\u7EDF\u8BA1:"),t.push(` \u751F\u4EA7\u4F9D\u8D56: ${s.dependencyCount.production||0} \u4E2A`),t.push(` \u5F00\u53D1\u4F9D\u8D56: ${s.dependencyCount.development||0} \u4E2A`),t.push("")),s.languages&&s.languages.length>0&&(t.push("\u{1F30D} \u8BED\u8A00\u5206\u5E03:"),s.languages.slice(0,5).forEach(n=>{t.push(` ${n.language}: ${n.count} \u4E2A\u6587\u4EF6 (${n.percentage})`)}),t.push("")),t.join(`
1920
+ `)}function Mf(s,e){let t=[],n=0;if((s.projectName||s.version||s.description)&&(s.projectName&&t.push(`**\u9879\u76EE\u540D\u79F0**: ${s.projectName}`),s.version&&t.push(`**\u7248\u672C**: ${s.version}`),s.description&&t.push(`**\u63CF\u8FF0**: ${s.description}`),n++),n>=e||((s.primaryLanguage||s.buildTool)&&(t.push(""),s.primaryLanguage&&t.push(`**\u4E3B\u8981\u8BED\u8A00**: ${s.primaryLanguage}`),s.buildTool&&t.push(`**\u6784\u5EFA\u5DE5\u5177**: ${s.buildTool}`),s.packageManager&&t.push(`**\u5305\u7BA1\u7406\u5668**: ${s.packageManager}`),s.runtime&&t.push(`**\u8FD0\u884C\u65F6**: ${s.runtime}`),n++),n>=e))return t.join(`
1921
+ `);if(s.fileStats){t.push("");let r=s.fileStats;r.totalFiles&&t.push(`**\u603B\u6587\u4EF6\u6570**: ${r.totalFiles}`),r.sourceFiles&&t.push(`**\u6E90\u6587\u4EF6**: ${r.sourceFiles}`),r.configFiles&&t.push(`**\u914D\u7F6E\u6587\u4EF6**: ${r.configFiles}`),r.testFiles&&t.push(`**\u6D4B\u8BD5\u6587\u4EF6**: ${r.testFiles}`),n++}return n>=e||(s.languages&&s.languages.length>0&&(t.push(""),t.push("**\u8BED\u8A00\u5206\u5E03**:"),s.languages.slice(0,5).forEach(r=>{t.push(`- ${r.language}: ${r.percentage}%`)}),n++),n>=e)||(s.dependencies&&Object.keys(s.dependencies).length>0&&(t.push(""),t.push("**\u4E3B\u8981\u4F9D\u8D56**:"),Object.entries(s.dependencies).slice(0,5).forEach(([o,i])=>{t.push(`- ${o}: ${i}`)}),n++),n>=e)?t.join(`
1922
+ `):(s.codeStandards&&s.codeStandards.length>0&&(t.push(""),t.push("**\u4EE3\u7801\u89C4\u8303**:"),s.codeStandards.slice(0,3).forEach(r=>{t.push(`- ${r}`)})),t.length>0?t.join(`
1923
+ `):"\u6682\u65E0\u9879\u76EE\u4FE1\u606F\u3002")}function Af(s,e,t){!e.projectName&&!e.version&&!e.description||(s.push("## \u9879\u76EE\u57FA\u672C\u4FE1\u606F"),e.projectName&&s.push(`**\u9879\u76EE\u540D\u79F0**: ${e.projectName}`),e.version&&s.push(`**\u7248\u672C**: ${e.version}`),e.description&&s.push(`**\u63CF\u8FF0**: ${e.description}`),s.push(""))}function Rf(s,e,t){!e.primaryLanguage&&!e.buildTool&&!e.packageManager&&!e.runtime||(s.push("## \u6280\u672F\u6808\u4FE1\u606F"),e.primaryLanguage&&s.push(`**\u4E3B\u8981\u7F16\u7A0B\u8BED\u8A00**: ${e.primaryLanguage}`),e.buildTool&&s.push(`**\u6784\u5EFA\u5DE5\u5177**: ${e.buildTool}`),e.packageManager&&s.push(`**\u5305\u7BA1\u7406\u5668**: ${e.packageManager}`),e.runtime&&s.push(`**\u8FD0\u884C\u65F6**: ${e.runtime}`),s.push(""))}function Lf(s,e,t){if(!e.fileStats)return;let n=e.fileStats;s.push("## \u6587\u4EF6\u7EDF\u8BA1"),n.totalFiles&&s.push(`- **\u603B\u6587\u4EF6\u6570**: ${n.totalFiles}`),n.sourceFiles&&s.push(`- **\u6E90\u6587\u4EF6**: ${n.sourceFiles}`),n.configFiles&&s.push(`- **\u914D\u7F6E\u6587\u4EF6**: ${n.configFiles}`),n.docFiles&&s.push(`- **\u6587\u6863\u6587\u4EF6**: ${n.docFiles}`),n.testFiles&&s.push(`- **\u6D4B\u8BD5\u6587\u4EF6**: ${n.testFiles}`),s.push("")}function jf(s,e,t){!e.languages||e.languages.length===0||(s.push("## \u7F16\u7A0B\u8BED\u8A00\u5206\u6790"),t?e.languages.forEach(n=>{s.push(`- **${n.language}**: ${n.count} \u4E2A\u6587\u4EF6 (${n.percentage}%)`)}):e.languages.slice(0,5).forEach(n=>{s.push(`- **${n.language}**: ${n.percentage}%`)}),s.push(""))}function Df(s,e,t){let n=e.dependencies&&Object.keys(e.dependencies).length>0,r=e.devDependencies&&Object.keys(e.devDependencies).length>0;!n&&!r||(s.push("## \u4F9D\u8D56\u5173\u7CFB"),n&&(s.push("### \u751F\u4EA7\u4F9D\u8D56"),(t?Object.entries(e.dependencies):Object.entries(e.dependencies).slice(0,10)).forEach(([i,a])=>{s.push(`- **${i}**: ${a}`)}),!t&&Object.keys(e.dependencies).length>10&&s.push(`
1924
+ *...\u8FD8\u6709 ${Object.keys(e.dependencies).length-10} \u4E2A\u4F9D\u8D56*`),s.push("")),r&&(s.push("### \u5F00\u53D1\u4F9D\u8D56"),(t?Object.entries(e.devDependencies):Object.entries(e.devDependencies).slice(0,10)).forEach(([i,a])=>{s.push(`- **${i}**: ${a}`)}),!t&&Object.keys(e.devDependencies).length>10&&s.push(`
1925
+ *...\u8FD8\u6709 ${Object.keys(e.devDependencies).length-10} \u4E2A\u4F9D\u8D56*`),s.push("")))}function Ff(s,e,t){if(!e.entryPoints||e.entryPoints.length===0)return;s.push("## \u5165\u53E3\u6587\u4EF6"),(t?e.entryPoints:e.entryPoints.slice(0,5)).forEach(r=>{s.push(`- \`${r}\``)}),!t&&e.entryPoints.length>5&&s.push(`
1926
+ *...\u8FD8\u6709 ${e.entryPoints.length-5} \u4E2A\u5165\u53E3\u6587\u4EF6*`),s.push("")}function Of(s,e,t){if(!e.codeStandards||e.codeStandards.length===0)return;s.push("## \u4EE3\u7801\u89C4\u8303"),(t?e.codeStandards:e.codeStandards.slice(0,5)).forEach(r=>{s.push(`- ${r}`)}),!t&&e.codeStandards.length>5&&s.push(`
1927
+ *...\u8FD8\u6709 ${e.codeStandards.length-5} \u4E2A\u89C4\u8303*`),s.push("")}var ii=S(()=>{});import*as ur from"os";var It,Mt,At,Rt,Ip=S(()=>{Q();ii();It=class{originalTask;plan;stepSummaries;sharedState;stepDependencies;explorationHistory;constructor(){this.originalTask=null,this.plan={tasks:[],currentStep:0,totalSteps:0},this.stepSummaries=new Map,this.sharedState={projectInfo:null,rules:null,dependencies:null,recentFiles:[],knownIssues:[]},this.stepDependencies=new Map,this.explorationHistory=null}initializeTask(e,t,n=!1){this.originalTask=e,this.plan={tasks:t.tasks||[],currentStep:0,totalSteps:t.tasks?.length||0},n?(this.stepSummaries.clear(),this.sharedState.recentFiles=[],F(`\u5168\u5C40\u4E0A\u4E0B\u6587\u521D\u59CB\u5316\uFF08\u5DF2\u6E05\u7A7A\u5386\u53F2\uFF09: ${this.plan.totalSteps} \u4E2A\u6B65\u9AA4`)):F(`\u5168\u5C40\u4E0A\u4E0B\u6587\u521D\u59CB\u5316\uFF08\u4FDD\u7559\u5386\u53F2\uFF09: ${this.plan.totalSteps} \u4E2A\u6B65\u9AA4, \u5386\u53F2\u6B65\u9AA4\u6570: ${this.stepSummaries.size}`)}recordStepCompletion(e,t,n={},r){let o=e;e===1&&this.stepSummaries.size>0&&(o=Math.max(...Array.from(this.stepSummaries.keys()))+1,C(`\u7B80\u5355\u4EFB\u52A1\u6B65\u9AA4ID\u81EA\u52A8\u9012\u589E: ${e} -> ${o}`)),this.stepSummaries.set(o,{summary:t,metadata:n,timestamp:new Date().toISOString()}),r&&r.buildHistoryIndex(o,t,n),C(`\u6B65\u9AA4 ${o} \u6458\u8981\u5DF2\u8BB0\u5F55: ${t.substring(0,50)}...`)}getStepSummary(e){return this.stepSummaries.get(e)}updateSharedState(e,t){this.sharedState.hasOwnProperty(e)?(this.sharedState[e]=t,C(`\u5171\u4EAB\u72B6\u6001\u66F4\u65B0: ${e}`)):C(`\u8B66\u544A: \u672A\u77E5\u7684\u5171\u4EAB\u72B6\u6001\u952E: ${e}`)}addRecentFile(e){this.sharedState.recentFiles.unshift(e),this.sharedState.recentFiles.length>10&&this.sharedState.recentFiles.pop()}setStepDependencies(e,t){this.stepDependencies.set(e,t)}getAllStepIds(){return Array.from(this.stepSummaries.keys())}getAllStepSummaries(){return new Map(this.stepSummaries)}getPlan(){return this.plan}setCurrentStep(e){this.plan.currentStep=e}getSharedState(){return this.sharedState}getStepDependencies(){return this.stepDependencies}getOriginalTask(){return this.originalTask}recordExplorationResult(e){let t=e.length>200?e.substring(0,200)+"...":e;this.explorationHistory={timestamp:Date.now(),content:e,summary:t},F("\u5DF2\u8BB0\u5F55\u9879\u76EE\u63A2\u7D22\u7ED3\u679C\u5230\u5168\u5C40\u4E0A\u4E0B\u6587")}getExplorationHistory(){return this.explorationHistory}},Mt=class{globalContext;historyIndex=new Map;constructor(e){this.globalContext=e}async selectRelevantHistory(e,t,n){let r=[],o=new Set,i=this.calculateTargetHistoryCount(t),a=Math.min(i*2,20);C(`\u4EFB\u52A1\u590D\u6742\u5EA6\u5206\u6790: \u76EE\u6807\u5386\u53F2\u6570\u91CF=${i}, \u6700\u5927\u7D22\u5F15\u7ED3\u679C=${a}`);let c=this.globalContext.getStepDependencies().get(e)||[];for(let m of c){let d=this.globalContext.getStepSummary(m);d&&(r.push({stepId:m,type:"dependency",content:d.summary,metadata:d.metadata}),o.add(m))}let l=this.analyzeFileRelevance(t);for(let m of l){if(o.has(m)||m>=e)continue;let d=this.globalContext.getStepSummary(m);if(d&&(r.push({stepId:m,type:"file_related",content:d.summary,metadata:d.metadata}),o.add(m),r.length>=Math.ceil(i/2)))break}let u=this.findRelevantStepsWithIndex(t,a);for(let m of u){if(o.has(m)||m>=e)continue;let d=this.globalContext.getStepSummary(m);if(d&&(r.push({stepId:m,type:"recent",content:d.summary,metadata:d.metadata}),o.add(m),r.length>=i))break}let p=Math.max(3,Math.floor(i/2));if(r.length<p){let m=this.getRecentCompletedSteps(i);for(let d of m){if(o.has(d)||d>=e)continue;let f=this.globalContext.getStepSummary(d);if(f&&(r.push({stepId:d,type:"recent",content:f.summary,metadata:f.metadata}),o.add(d),r.length>=p))break}}if(n==="explorer")C("\u8DF3\u8FC7\u63A2\u7D22\u5386\u53F2\u6CE8\u5165 (\u5F53\u524D\u4E3A explorer \u667A\u80FD\u4F53)");else{let m=this.globalContext.getExplorationHistory();m&&(r.push({stepId:0,type:"exploration",content:m.content,metadata:{timestamp:m.timestamp,summary:m.summary}}),C(`\u5DF2\u6DFB\u52A0\u63A2\u7D22\u5386\u53F2\u5230\u4E0A\u4E0B\u6587 (\u667A\u80FD\u4F53: ${n||"unknown"})`))}return C(`\u4E3A\u6B65\u9AA4 ${e} \u9009\u62E9\u4E86 ${r.length} \u6761\u76F8\u5173\u5386\u53F2 (\u4F7F\u7528\u7D22\u5F15\u4F18\u5316 + \u6587\u4EF6\u5173\u8054\u6027\u5206\u6790)`),r}analyzeFileRelevance(e){let{recentFiles:t}=this.globalContext.getSharedState();if(t.length===0)return[];let n=this.extractFilePatterns(e);if(n.length===0)return[];let r=new Map;for(let[o,i]of Array.from(this.globalContext.getAllStepSummaries().entries())){if(!i.metadata||!i.metadata.filesAccessed)continue;let a=i.metadata.filesAccessed,c=0;for(let l of a){t.includes(l)&&(c+=3);for(let u of n)l.toLowerCase().includes(u.toLowerCase())&&(c+=2)}c>0&&r.set(o,c)}return Array.from(r.entries()).sort((o,i)=>i[1]-o[1]).slice(0,5).map(([o])=>o)}extractFilePatterns(e){let t=[],n=/[\w\-./]+\.(ts|js|tsx|jsx|py|java|go|rs|cpp|c|h|md|json|yaml|yml|xml|html|css|scss)/gi,r=e.match(n);r&&t.push(...r);let o=/(?:文件|file|模块|module|组件|component)[::\s]+([a-zA-Z0-9\-_]+)/gi,i;for(;(i=o.exec(e))!==null;)t.push(i[1]);let a=/(?:目录|directory|文件夹|folder)[::\s]+([a-zA-Z0-9\-_/]+)/gi;for(;(i=a.exec(e))!==null;)t.push(i[1]);return t}getRecentCompletedSteps(e){return this.globalContext.getAllStepIds().sort((n,r)=>n-r).slice(-e)}calculateTargetHistoryCount(e){let t=5;e.length>300?t+=5:e.length>150?t+=3:e.length>80&&(t+=1);let n=["\u91CD\u6784","refactor","\u4F18\u5316","optimize","\u8BBE\u8BA1","design","\u67B6\u6784","architecture","\u5B9E\u73B0","implement","\u5F00\u53D1","develop","\u96C6\u6210","integrate","\u8FC1\u79FB","migrate","\u4FEE\u590D","fix","\u8C03\u8BD5","debug","\u5206\u6790","analyze","\u8BC4\u4F30","evaluate"],r=["\u8BFB\u53D6","read","\u67E5\u770B","view","\u663E\u793A","display","\u6253\u5370","print","\u5217\u51FA","list","\u67E5\u627E","find","\u641C\u7D22","search"],o=e.toLowerCase(),i=n.filter(u=>o.includes(u)).length;t+=i*2;let a=r.filter(u=>o.includes(u)).length;t-=a;let c=e.match(/\.(ts|js|tsx|jsx|py|java|go|rs|cpp|c|h|md|json|yaml|yml)/gi);c&&c.length>3?t+=3:c&&c.length>1&&(t+=1);let l=e.match(/模块|组件|系统|服务|module|component|system|service/gi);return l&&l.length>2&&(t+=2),Math.max(5,Math.min(t,20))}buildHistoryIndex(e,t,n){let r=this.extractKeywords(t);n&&(n.toolsUsed&&Array.isArray(n.toolsUsed)&&n.toolsUsed.forEach(i=>{i&&i.length>0&&r.push(i.toLowerCase())}),n.filesAccessed&&Array.isArray(n.filesAccessed)&&n.filesAccessed.forEach(i=>{if(i){let a=i.split(/[/\\]/).pop()?.split(".")[0];a&&a.length>2&&r.push(a.toLowerCase()),i.split(/[/\\]/).filter(l=>l&&l.length>2).forEach(l=>{["src","dist","node_modules","test","tests","lib","bin"].includes(l.toLowerCase())||r.push(l.toLowerCase())})}}));let o=[...new Set(r)];o.forEach(i=>{this.historyIndex.has(i)||this.historyIndex.set(i,new Set),this.historyIndex.get(i).add(e)}),C(`\u4E3A\u6B65\u9AA4 ${e} \u6784\u5EFA\u4E86\u7D22\u5F15\uFF0C\u5305\u542B ${o.length} \u4E2A\u5173\u952E\u8BCD\uFF08\u6458\u8981: ${r.length-(o.length-r.length)}, \u5143\u6570\u636E: ${o.length-r.length}\uFF09`)}extractKeywords(e){let t=this.getStopWords();return e.toLowerCase().replace(/[^\w\s\u4e00-\u9fa5]/g," ").split(/[\s\u3000]+/).filter(n=>n.length<2?!1:!t.has(n)).slice(0,20)}getStopWords(){return new Set(["the","is","at","which","on","and","or","but","in","with","to","for","of","a","an","as","by","from","has","have","had","be","been","being","are","was","were","will","would","should","could","may","might","can","do","does","did","done","this","that","these","those","it","its","they","them","their","we","our","you","your","he","she","his","her","him","me","my","i","am","not","no","yes","all","any","some","each","every","both","few","more","most","into","through","during","before","after","above","below","up","down","out","off","over","under","again","further","then","once","here","there","when","where","why","how","what","who","whom","whose","which","about","against","between","into","through","\u7684","\u4E86","\u5728","\u662F","\u6211","\u6709","\u548C","\u5C31","\u4E0D","\u4EBA","\u90FD","\u4E00","\u4E00\u4E2A","\u4E0A","\u4E5F","\u5F88","\u5230","\u8BF4","\u8981","\u53BB","\u4F60","\u4F1A","\u7740","\u6CA1\u6709","\u770B","\u597D","\u81EA\u5DF1","\u8FD9","\u90A3","\u91CC","\u4E2A","\u5C31\u662F","\u554A","\u51FA","\u6765","\u4E48","\u5417","\u5462","\u5427","\u54E6","\u5566","\u5440","\u561B","\u54C8","\u54EA","\u4EC0\u4E48","\u600E\u4E48","\u4E3A\u4EC0\u4E48","\u591A\u5C11","\u51E0\u4E2A","\u8FD9\u4E2A","\u90A3\u4E2A","\u8FD9\u4E9B","\u90A3\u4E9B","\u8FD9\u6837","\u90A3\u6837","\u5982\u4F55","\u53EF\u4EE5","\u80FD\u591F","\u5E94\u8BE5","\u5FC5\u987B","\u9700\u8981","\u60F3\u8981","\u5E0C\u671B","\u89C9\u5F97","\u8BA4\u4E3A","\u77E5\u9053","\u660E\u767D","\u5DF2\u7ECF","\u6B63\u5728","\u5C06\u8981","\u66FE\u7ECF","\u4E00\u76F4","\u603B\u662F","\u7ECF\u5E38","\u6709\u65F6","\u5076\u5C14","\u4ECE\u6765","\u6C38\u8FDC","\u975E\u5E38","\u5F88\u591A","\u4E00\u4E9B","\u6240\u6709","\u6BCF\u4E2A","\u4EFB\u4F55","\u67D0\u4E2A","\u53E6\u5916","\u5176\u4ED6","\u522B\u7684","\u5176\u5B83","\u56E0\u4E3A","\u6240\u4EE5","\u4F46\u662F","\u7136\u800C","\u867D\u7136","\u5982\u679C","\u5047\u5982","\u9664\u975E","\u53EA\u8981","\u65E0\u8BBA","\u4E0D\u7BA1","\u800C\u4E14","\u5E76\u4E14","\u6216\u8005","\u8FD8\u662F","\u4E0D\u4EC5","\u800C\u4E14","\u65E2\u7136","\u7531\u4E8E","\u4E3A\u4E86","\u4EE5\u4FBF","\u4EE5\u514D","step","task","action","result","success","failed","error","warning","info","\u6B65\u9AA4","\u4EFB\u52A1","\u64CD\u4F5C","\u7ED3\u679C","\u6210\u529F","\u5931\u8D25","\u9519\u8BEF","\u8B66\u544A","\u4FE1\u606F","\u5B8C\u6210","\u6267\u884C"])}findRelevantStepsWithIndex(e,t=5){let n=this.extractKeywords(e),r=new Map;return n.forEach(o=>{let i=this.historyIndex.get(o);i&&i.forEach(a=>{r.set(a,(r.get(a)||0)+1)})}),Array.from(r.entries()).sort((o,i)=>i[1]-o[1]).slice(0,t).map(([o])=>o)}isLikelyRelevant(e,t){let n=new Set(this.extractKeywords(e));return this.extractKeywords(t).filter(i=>n.has(i)).length>=2}async selectRelevantHistoryWithLLM(e,t,n){let{MODEL:r}=await Promise.resolve().then(()=>(ae(),Ln)),{callModelAPI:o}=await Promise.resolve().then(()=>(Ie(),pr)),i=Array.from(this.globalContext.getStepDependencies().entries()).map(([c,l])=>{let u=this.globalContext.getStepSummary(c);return u?`\u6B65\u9AA4${c}: ${u.summary}`:""}).filter(Boolean).join(`
1210
1928
  `);if(!i){if(!(n==="explorer")){let l=this.globalContext.getExplorationHistory();if(l)return[{stepId:0,type:"exploration",content:l.content,metadata:{timestamp:l.timestamp,summary:l.summary}}]}return[]}let a=`\u4EFB\u52A1: ${this.globalContext.getOriginalTask()||""}
1211
1929
 
1212
1930
  \u5DF2\u5B8C\u6210\u7684\u5386\u53F2\u6B65\u9AA4\u6458\u8981:
@@ -1216,7 +1934,17 @@ ${i}
1216
1934
 
1217
1935
  \u95EE\u9898: \u5F53\u524D\u6B65\u9AA4\u9700\u8981\u54EA\u4E9B\u5386\u53F2\u6B65\u9AA4\u7684\u4FE1\u606F\uFF1F\u8BF7\u5206\u6790\u4F9D\u8D56\u5173\u7CFB\u3002
1218
1936
  \u8F93\u51FA\u683C\u5F0F: \u8FD4\u56DEJSON\u6570\u7EC4\uFF0C\u5305\u542B\u76F8\u5173\u6B65\u9AA4ID\uFF0C\u4F8B\u5982 [1, 3]\u3002\u5982\u679C\u4E0D\u9700\u8981\u5386\u53F2\u4FE1\u606F\uFF0C\u8FD4\u56DE []\u3002
1219
- \u53EA\u8FD4\u56DEJSON\uFF0C\u4E0D\u8981\u5176\u4ED6\u89E3\u91CA\u3002`;try{let l=(await s({model:r(),messages:[{role:"user",content:a}],temperature:.1,max_tokens:100,tools:[]})).choices[0].message.content?.trim()||"[]",p=JSON.parse(l).map(d=>{let m=this.globalContext.getStepSummary(d);return m?{stepId:d,type:"llm_selected",content:m.summary,metadata:m.metadata}:null}).filter(d=>d!==null);if(n==="explorer")x("\u8DF3\u8FC7\u63A2\u7D22\u5386\u53F2\u6CE8\u5165 (LLM\u6A21\u5F0F, \u5F53\u524D\u4E3A explorer \u667A\u80FD\u4F53)");else{let d=this.globalContext.getExplorationHistory();d&&(p.push({stepId:0,type:"exploration",content:d.content,metadata:{timestamp:d.timestamp,summary:d.summary}}),x(`\u5DF2\u6DFB\u52A0\u63A2\u7D22\u5386\u53F2\u5230\u4E0A\u4E0B\u6587 (LLM\u6A21\u5F0F, \u667A\u80FD\u4F53: ${n||"unknown"})`))}return M(`LLM \u4E3A\u6B65\u9AA4 ${e} \u9009\u62E9\u4E86 ${p.length} \u6761\u76F8\u5173\u5386\u53F2`),p}catch(c){return x(`LLM \u9009\u62E9\u5386\u53F2\u5931\u8D25\uFF0C\u964D\u7EA7\u5230\u542F\u53D1\u5F0F\u65B9\u6CD5: ${c instanceof Error?c.message:String(c)}`),this.selectRelevantHistory(e,t,n)}}},He=class{globalContext;disclosure;platformInfoCache=null;projectInfoCache=null;projectInfoCacheTime=0;PROJECT_INFO_CACHE_TTL=300*1e3;constructor(e,t){this.globalContext=e,this.disclosure=t}async buildIsolatedContext(e,t,n="",r=!1,s,i){let a=[];n&&a.push({role:"system",content:n});let c=await this.buildProjectEnvironmentContext();c&&a.push({role:"system",content:`## \u9879\u76EE\u73AF\u5883\u4FE1\u606F
1937
+ \u53EA\u8FD4\u56DEJSON\uFF0C\u4E0D\u8981\u5176\u4ED6\u89E3\u91CA\u3002`;try{let l=(await o({model:r(),messages:[{role:"user",content:a}],temperature:.1,max_tokens:100,tools:[]})).choices[0].message.content?.trim()||"[]",p=JSON.parse(l).map(m=>{let d=this.globalContext.getStepSummary(m);return d?{stepId:m,type:"llm_selected",content:d.summary,metadata:d.metadata}:null}).filter(m=>m!==null);if(n==="explorer")C("\u8DF3\u8FC7\u63A2\u7D22\u5386\u53F2\u6CE8\u5165 (LLM\u6A21\u5F0F, \u5F53\u524D\u4E3A explorer \u667A\u80FD\u4F53)");else{let m=this.globalContext.getExplorationHistory();m&&(p.push({stepId:0,type:"exploration",content:m.content,metadata:{timestamp:m.timestamp,summary:m.summary}}),C(`\u5DF2\u6DFB\u52A0\u63A2\u7D22\u5386\u53F2\u5230\u4E0A\u4E0B\u6587 (LLM\u6A21\u5F0F, \u667A\u80FD\u4F53: ${n||"unknown"})`))}return F(`LLM \u4E3A\u6B65\u9AA4 ${e} \u9009\u62E9\u4E86 ${p.length} \u6761\u76F8\u5173\u5386\u53F2`),p}catch(c){return C(`LLM \u9009\u62E9\u5386\u53F2\u5931\u8D25\uFF0C\u964D\u7EA7\u5230\u542F\u53D1\u5F0F\u65B9\u6CD5: ${c instanceof Error?c.message:String(c)}`),this.selectRelevantHistory(e,t,n)}}},At=class{globalContext;disclosure;platformInfoCache=null;projectInfoCache=null;projectInfoCacheTime=0;PROJECT_INFO_CACHE_TTL=300*1e3;constructor(e,t){this.globalContext=e,this.disclosure=t}async buildIsolatedContext(e,t,n="",r=!1,o,i){let a=[];if(n&&a.push({role:"system",content:n}),this.globalContext.getSharedState().recentFiles.length>0){let u=this.globalContext.getSharedState().recentFiles.slice(0,5);a.push({role:"system",content:`## \u{1F50D} \u52A8\u6001\u4E0A\u4E0B\u6587 - \u6700\u8FD1\u8BBF\u95EE\u7684\u6587\u4EF6
1938
+
1939
+ \u4EE5\u4E0B\u6587\u4EF6\u5DF2\u5728\u672C\u6B21\u4EFB\u52A1\u4E2D\u88AB\u8BFB\u53D6\uFF0C\u5176\u4E2D\u53EF\u80FD\u5305\u542B\u4F60\u9700\u8981\u7684\u5173\u8054\u6587\u4EF6\u8DEF\u5F84\u4FE1\u606F\uFF1A
1940
+
1941
+ ${u.map(p=>`- ${p}`).join(`
1942
+ `)}
1943
+
1944
+ **\u91CD\u8981\u63D0\u9192**\uFF1A
1945
+ - \u8FD9\u4E9B\u6587\u4EF6\u5DF2\u88AB\u8BFB\u53D6\uFF0C\u4F18\u5148\u5229\u7528\u5176\u4E2D\u7684\u8DEF\u5F84\u5F15\u7528\u4FE1\u606F\uFF08import/require/\u914D\u7F6E\u8DEF\u5F84\u7B49\uFF09
1946
+ - \u5982\u679C\u9700\u8981\u8BBF\u95EE\u76F8\u5173\u6587\u4EF6\uFF0C\u76F4\u63A5\u4F7F\u7528 read() \u800C\u975E\u91CD\u65B0\u63A2\u7D22\u76EE\u5F55\u7ED3\u6784
1947
+ - \u9075\u5FAA"\u6587\u4EF6\u68C0\u7D22\u7B56\u7565"\u4E2D\u7684\u4F18\u5148\u7EA7\u539F\u5219\uFF0C\u6700\u5C0F\u5316\u4EA4\u4E92\u6B21\u6570`})}let c=await this.buildProjectEnvironmentContext();c&&a.push({role:"system",content:`## \u9879\u76EE\u73AF\u5883\u4FE1\u606F
1220
1948
 
1221
1949
  ${c}`}),a.push({role:"user",content:`\u539F\u59CB\u4EFB\u52A1: ${this.globalContext.getOriginalTask()||""}`}),this.globalContext.getSharedState().rules&&a.push({role:"system",content:`\u26A0\uFE0F \u3010\u91CD\u8981\u3011\u9879\u76EE\u89C4\u5219 - \u6A21\u578B\u5FC5\u987B\u4E25\u683C\u9075\u5B88
1222
1950
 
@@ -1227,22 +1955,37 @@ ${c}`}),a.push({role:"user",content:`\u539F\u59CB\u4EFB\u52A1: ${this.globalCont
1227
1955
  ${this.globalContext.getSharedState().rules}
1228
1956
 
1229
1957
  ===============================
1230
- \u26A0\uFE0F \u91CD\u8981\u63D0\u9192\uFF1A\u5728\u6267\u884C\u6240\u6709\u4EFB\u52A1\u65F6\uFF0C\u5FC5\u987B\u4E25\u683C\u9075\u5B88\u4E0A\u8FF0\u9879\u76EE\u89C4\u5219\u548C\u7EA6\u5B9A\uFF0C\u786E\u4FDD\u751F\u6210\u7684\u4EE3\u7801\u3001\u6587\u4EF6\u7ED3\u6784\u548C\u5B9E\u73B0\u65B9\u5F0F\u7B26\u5408\u9879\u76EE\u8981\u6C42\u3002\u5982\u679C\u8FDD\u53CD\u89C4\u5219\uFF0C\u53EF\u80FD\u5BFC\u81F4\u4EFB\u52A1\u5931\u8D25\u6216\u9700\u8981\u91CD\u65B0\u6267\u884C\u3002`});let l;if(r?l=await this.disclosure.selectRelevantHistoryWithLLM(e,t,i):l=await this.disclosure.selectRelevantHistory(e,t,i),l.length>0){let u=l.map(p=>`[\u6B65\u9AA4${p.stepId}] ${p.content}`).join(`
1958
+ \u26A0\uFE0F \u91CD\u8981\u63D0\u9192\uFF1A\u5728\u6267\u884C\u6240\u6709\u4EFB\u52A1\u65F6\uFF0C\u5FC5\u987B\u4E25\u683C\u9075\u5B88\u4E0A\u8FF0\u9879\u76EE\u89C4\u5219\u548C\u7EA6\u5B9A\uFF0C\u786E\u4FDD\u751F\u6210\u7684\u4EE3\u7801\u3001\u6587\u4EF6\u7ED3\u6784\u548C\u5B9E\u73B0\u65B9\u5F0F\u7B26\u5408\u9879\u76EE\u8981\u6C42\u3002\u5982\u679C\u8FDD\u53CD\u89C4\u5219\uFF0C\u53EF\u80FD\u5BFC\u81F4\u4EFB\u52A1\u5931\u8D25\u6216\u9700\u8981\u91CD\u65B0\u6267\u884C\u3002`});let l;if(r?l=await this.disclosure.selectRelevantHistoryWithLLM(e,t,i):l=await this.disclosure.selectRelevantHistory(e,t,i),l.length===0){let u=Array.from(this.globalContext.getAllStepSummaries().entries());u.length>0&&(l=u.sort(([g],[m])=>m-g).slice(0,3).reverse().map(([g,m])=>({stepId:g,type:"recent",content:m.summary,metadata:m.metadata})))}if(l.length>0){let u=l.map(p=>`[\u6B65\u9AA4${p.stepId}] ${p.content}`).join(`
1231
1959
 
1232
1960
  `);a.push({role:"user",content:`\u76F8\u5173\u5386\u53F2\u4FE1\u606F:
1233
1961
  ${u}`})}return a.push({role:"user",content:`\u5F53\u524D\u4EFB\u52A1 (\u6B65\u9AA4 ${e}/${this.globalContext.getPlan().totalSteps}):
1234
- ${t}`}),s&&s.length>0&&a.push({role:"system",content:`\u26A0\uFE0F \u672C\u6B65\u9AA4\u5DE5\u5177\u4F7F\u7528\u9650\u5236:
1235
- \u4F60\u53EA\u80FD\u4F7F\u7528\u4EE5\u4E0B\u5DE5\u5177: ${s.join(", ")}
1962
+ ${t}`}),o&&o.length>0&&a.push({role:"system",content:`\u26A0\uFE0F \u672C\u6B65\u9AA4\u5DE5\u5177\u4F7F\u7528\u9650\u5236:
1963
+ \u4F60\u53EA\u80FD\u4F7F\u7528\u4EE5\u4E0B\u5DE5\u5177: ${o.join(", ")}
1236
1964
 
1237
1965
  \u5982\u679C\u4F60\u5C1D\u8BD5\u4F7F\u7528\u672A\u6388\u6743\u7684\u5DE5\u5177\uFF0C\u8C03\u7528\u4F1A\u88AB\u62D2\u7EDD\u3002
1238
- \u8BF7\u4E25\u683C\u9075\u5B88\u5DE5\u5177\u4F7F\u7528\u8303\u56F4\uFF0C\u4E13\u6CE8\u4E8E\u5F53\u524D\u6B65\u9AA4\u7684\u76EE\u6807\u3002`}),this.globalContext.getSharedState().recentFiles.length>0&&a.push({role:"system",content:`\u6700\u8FD1\u8BBF\u95EE\u7684\u6587\u4EF6: ${this.globalContext.getSharedState().recentFiles.slice(0,5).join(", ")}`}),t.match(/实现|创建|编写|设计|开发|生成/)&&a.push({role:"system",content:`\u26A0\uFE0F CRITICAL REMINDER FOR CODE TASKS:
1239
- - You MUST use Action: write(path, content) to save any code you generate
1240
- - You MUST use Action: merge(path, content) to modify existing files
1241
- - NEVER just output code without saving it using Action:
1242
- - Follow the exact format: "Thought: ..." then "Action: tool_name(args)"
1243
- - When task is done, use "Answer: ..." to finish`}),M(`\u4E3A\u6B65\u9AA4 ${e} \u6784\u5EFA\u4E86\u9694\u79BB\u4E0A\u4E0B\u6587\uFF0C\u5305\u542B ${a.length} \u6761\u6D88\u606F`),s&&M(`\u5DE5\u5177\u9650\u5236: ${s.join(", ")}`),x(`\u4E0A\u4E0B\u6587\u8BE6\u60C5: \u5386\u53F2 ${l.length} \u6761, \u6587\u4EF6 ${this.globalContext.getSharedState().recentFiles.length} \u4E2A`),a}buildSimpleContext(e,t=""){let n=[];return t&&n.push({role:"system",content:t}),n.push({role:"user",content:e}),M("\u6784\u5EFA\u4E86\u7B80\u5316\u4E0A\u4E0B\u6587\uFF08\u7B80\u5355\u4EFB\u52A1\u6A21\u5F0F\uFF09"),n}async buildProjectEnvironmentContext(){try{this.platformInfoCache||(this.platformInfoCache=this.buildPlatformInfo(),x("\u5E73\u53F0\u4FE1\u606F\u5DF2\u7F13\u5B58"));let e=Date.now();(!this.projectInfoCache||e-this.projectInfoCacheTime>this.PROJECT_INFO_CACHE_TTL)&&(this.projectInfoCache=await this.buildProjectInfo(),this.projectInfoCacheTime=e,x("\u9879\u76EE\u4FE1\u606F\u5DF2\u66F4\u65B0\u7F13\u5B58"));let t=this.platformInfoCache;return this.projectInfoCache&&(t+=`
1966
+ \u8BF7\u4E25\u683C\u9075\u5B88\u5DE5\u5177\u4F7F\u7528\u8303\u56F4\uFF0C\u4E13\u6CE8\u4E8E\u5F53\u524D\u6B65\u9AA4\u7684\u76EE\u6807\u3002`}),t.match(/实现|创建|编写|设计|开发|生成|修改|添加|更新/)&&a.push({role:"system",content:`\u26A0\uFE0F \u91CD\u8981\u63D0\u9192 - \u4EE3\u7801\u5B9E\u73B0\u4EFB\u52A1\u6307\u5357:
1967
+
1968
+ \u5F53\u524D\u6B65\u9AA4\u662F\u4EE3\u7801\u5B9E\u73B0\u4EFB\u52A1\u3002\u8BF7\u9075\u5FAA\u4EE5\u4E0B\u89C4\u8303\uFF1A
1969
+
1970
+ 1. **\u5FC5\u987B\u4F7F\u7528\u5DE5\u5177\u4FDD\u5B58\u4EE3\u7801**\uFF1A
1971
+ - \u4F7F\u7528 write() \u5DE5\u5177\u521B\u5EFA\u65B0\u6587\u4EF6
1972
+ - \u4F7F\u7528 merge() \u5DE5\u5177\u4FEE\u6539\u73B0\u6709\u6587\u4EF6
1973
+ - \u4F7F\u7528 searchReplace() \u5DE5\u5177\u6279\u91CF\u66FF\u6362
1974
+ - \u4E0D\u8981\u4EC5\u8F93\u51FA\u4EE3\u7801\u6587\u672C\u800C\u4E0D\u4FDD\u5B58
1244
1975
 
1245
- ${this.projectInfoCache}`),t}catch(e){return x(`\u6784\u5EFA\u9879\u76EE\u73AF\u5883\u4E0A\u4E0B\u6587\u5931\u8D25: ${e}`),null}}buildPlatformInfo(){let e=Jt.platform(),t=Jt.arch(),n=Jt.version(),r=process.cwd();return`\u{1F30D} **\u667A\u80FD\u73AF\u5883\u611F\u77E5\u7CFB\u7EDF**
1976
+ 2. **\u6807\u51C6\u5DE5\u4F5C\u6D41\u7A0B**\uFF1A
1977
+ - \u4F7F\u7528 think() \u601D\u8003\u548C\u89C4\u5212
1978
+ - \u4F7F\u7528 read() \u8BFB\u53D6\u73B0\u6709\u6587\u4EF6
1979
+ - \u4F7F\u7528 write()/merge() \u4FDD\u5B58\u5B8C\u6574\u7684\u6587\u4EF6\u5185\u5BB9
1980
+ - \u4F7F\u7528 finish() \u5B8C\u6210\u4EFB\u52A1
1981
+
1982
+ 3. **\u6587\u4EF6\u64CD\u4F5C\u8981\u6C42**\uFF1A
1983
+ - write() \u548C merge() \u9700\u8981\u5B8C\u6574\u7684\u6587\u4EF6\u5185\u5BB9\uFF0C\u4E0D\u662F\u589E\u91CF\u4FEE\u6539
1984
+ - \u5148 read() \u83B7\u53D6\u5F53\u524D\u5185\u5BB9\uFF0C\u518D\u51C6\u5907\u5B8C\u6574\u7684\u65B0\u7248\u672C
1985
+
1986
+ \u786E\u4FDD\u5B9E\u9645\u6267\u884C\u4EE3\u7801\u521B\u5EFA/\u4FEE\u6539\u64CD\u4F5C\uFF0C\u800C\u4E0D\u4EC5\u4EC5\u662F\u63CF\u8FF0\u6216\u8F93\u51FA\u4EE3\u7801\u3002`}),F(`\u4E3A\u6B65\u9AA4 ${e} \u6784\u5EFA\u4E86\u9694\u79BB\u4E0A\u4E0B\u6587\uFF0C\u5305\u542B ${a.length} \u6761\u6D88\u606F`),o&&F(`\u5DE5\u5177\u9650\u5236: ${o.join(", ")}`),C(`\u4E0A\u4E0B\u6587\u8BE6\u60C5: \u5386\u53F2 ${l.length} \u6761, \u6587\u4EF6 ${this.globalContext.getSharedState().recentFiles.length} \u4E2A`),a}buildSimpleContext(e,t=""){let n=[];return t&&n.push({role:"system",content:t}),n.push({role:"user",content:e}),F("\u6784\u5EFA\u4E86\u7B80\u5316\u4E0A\u4E0B\u6587\uFF08\u7B80\u5355\u4EFB\u52A1\u6A21\u5F0F\uFF09"),n}async buildProjectEnvironmentContext(){try{this.platformInfoCache||(this.platformInfoCache=this.buildPlatformInfo(),C("\u5E73\u53F0\u4FE1\u606F\u5DF2\u7F13\u5B58"));let e=Date.now();(!this.projectInfoCache||e-this.projectInfoCacheTime>this.PROJECT_INFO_CACHE_TTL)&&(this.projectInfoCache=await this.buildProjectInfo(),this.projectInfoCacheTime=e,C("\u9879\u76EE\u4FE1\u606F\u5DF2\u66F4\u65B0\u7F13\u5B58"));let t=this.platformInfoCache;return this.projectInfoCache&&(t+=`
1987
+
1988
+ ${this.projectInfoCache}`),t}catch(e){return C(`\u6784\u5EFA\u9879\u76EE\u73AF\u5883\u4E0A\u4E0B\u6587\u5931\u8D25: ${e}`),null}}buildPlatformInfo(){let e=ur.platform(),t=ur.arch(),n=ur.version(),r=process.cwd();return`\u{1F30D} **\u667A\u80FD\u73AF\u5883\u611F\u77E5\u7CFB\u7EDF**
1246
1989
 
1247
1990
  **\u91CD\u8981\u63D0\u9192\uFF1A\u4F60\u5FC5\u987B\u59CB\u7EC8\u8003\u8651\u5F53\u524D\u8FD0\u884C\u73AF\u5883\uFF0C\u8FD9\u76F4\u63A5\u5F71\u54CD\u4F60\u7684\u547D\u4EE4\u9009\u62E9\u548C\u4EE3\u7801\u751F\u6210\u7B56\u7565\u3002**
1248
1991
 
@@ -1295,16 +2038,16 @@ ${e==="win32"?`
1295
2038
  - \u5728\u6267\u884Cshell\u547D\u4EE4\u524D\uFF0C\u52A1\u5FC5\u8003\u8651\u5F53\u524D\u5E73\u53F0\u7279\u6027
1296
2039
  - \u5F53\u7528\u6237\u8BF7\u6C42\u4F7F\u7528Unix\u547D\u4EE4\u65F6\uFF0C${e==="win32"?"\u81EA\u52A8\u8F6C\u6362\u4E3AWindows\u7B49\u4EF7\u547D\u4EE4":"\u76F4\u63A5\u4F7F\u7528Unix\u547D\u4EE4"}
1297
2040
  - \u63D0\u4F9B\u547D\u4EE4\u5EFA\u8BAE\u65F6\uFF0C\u4F18\u5148\u63A8\u8350${e==="win32"?"Windows\u539F\u751F":"Unix\u539F\u751F"}\u65B9\u6848
1298
- - \u9047\u5230\u8DE8\u5E73\u53F0\u517C\u5BB9\u6027\u95EE\u9898\u65F6\uFF0C\u4E3B\u52A8\u63D0\u51FA\u89E3\u51B3\u65B9\u6848`}async buildProjectInfo(){try{let e=await import("fs"),t=await import("path"),n=process.cwd(),r=t.join(n,".nium/project/project.json");if(!e.existsSync(r))return null;let s=e.readFileSync(r,"utf-8");try{let i=JSON.parse(s);return`**\u9879\u76EE\u7ED3\u6784\u6458\u8981:**
2041
+ - \u9047\u5230\u8DE8\u5E73\u53F0\u517C\u5BB9\u6027\u95EE\u9898\u65F6\uFF0C\u4E3B\u52A8\u63D0\u51FA\u89E3\u51B3\u65B9\u6848`}async buildProjectInfo(){try{let e=await import("fs"),t=await import("path"),n=process.cwd(),r=t.join(n,".nium/project/project.json");if(!e.existsSync(r))return null;let o=e.readFileSync(r,"utf-8");try{let i=JSON.parse(o);return`**\u9879\u76EE\u7ED3\u6784\u6458\u8981:**
1299
2042
  ${this.extractProjectSummaryFromJSON(i)}
1300
2043
 
1301
- **\u5B8C\u6574\u7ED3\u6784\u6587\u6863:** \u5982\u9700\u8BE6\u7EC6\u4FE1\u606F\uFF0C\u8BF7\u4F7F\u7528 read('.nium/project/project.json')`}catch(i){return x(`\u89E3\u6790project.json\u5931\u8D25\uFF0C\u4F7F\u7528\u6587\u672C\u6458\u8981: ${i}`),`**\u9879\u76EE\u7ED3\u6784\u6458\u8981:**
1302
- ${this.extractProjectSummary(s)}
2044
+ **\u5B8C\u6574\u7ED3\u6784\u6587\u6863:** \u5982\u9700\u8BE6\u7EC6\u4FE1\u606F\uFF0C\u8BF7\u4F7F\u7528 read('.nium/project/project.json')`}catch(i){return C(`\u89E3\u6790project.json\u5931\u8D25\uFF0C\u4F7F\u7528\u6587\u672C\u6458\u8981: ${i}`),`**\u9879\u76EE\u7ED3\u6784\u6458\u8981:**
2045
+ ${this.extractProjectSummary(o)}
1303
2046
 
1304
- **\u5B8C\u6574\u7ED3\u6784\u6587\u6863:** \u5982\u9700\u8BE6\u7EC6\u4FE1\u606F\uFF0C\u8BF7\u4F7F\u7528 read('.nium/project/project.json')`}}catch(e){return x(`\u83B7\u53D6\u9879\u76EE\u7ED3\u6784\u4FE1\u606F\u5931\u8D25: ${e}`),null}}extractProjectSummaryFromJSON(e){return tr(e,{format:"summary",maxSections:3})}extractProjectSummary(e){let t=e.split(`
1305
- `),n=[],r=!1,s=0;for(let i of t){if(i.includes("## \u9879\u76EE\u6982\u8FF0")){r=!0;continue}if(r){if(i.startsWith("##")&&!i.includes("\u9879\u76EE\u6982\u8FF0"))break;if(i.trim()&&(n.push(i),s++,s>=15))break}}return n.join(`
1306
- `)}},Je=class{useLLMSummary;constructor(e=!0){this.useLLMSummary=e}setUseLLMSummary(e){this.useLLMSummary=e,x(`\u6458\u8981\u63D0\u53D6\u6A21\u5F0F\u5DF2\u8BBE\u7F6E\u4E3A: ${e?"LLM":"\u542F\u53D1\u5F0F"}`)}async extractSummary(e){return this.useLLMSummary?this.extractSummaryWithLLM(e):this.extractSummaryHeuristic(e)}async extractSummaryHeuristic(e){let t=[],n=[],r=null;for(let i of e)if(i.role==="assistant"){if(i.tool_calls&&i.tool_calls.length>0)for(let a of i.tool_calls){let c=a.function.name;c!=="think"&&t.push(c)}if(i.content&&i.content.includes("Answer:")){let a=i.content.match(/Answer:\s*(.+)/s);a&&(r=a[1].trim().substring(0,200))}}else i.role==="tool"&&i.content&&n.push(i.content.substring(0,100));let s="";return r?s=`\u5B8C\u6210: ${r}`:(s=`\u6267\u884C\u4E86 ${t.length} \u4E2A\u5DE5\u5177\u8C03\u7528`,t.length>0&&(s+=` (${t.slice(0,3).join(", ")})`)),x(`\u63D0\u53D6\u6458\u8981: ${s.substring(0,50)}...`),s}async extractSummaryWithLLM(e){let{LITE_MODEL:t}=await Promise.resolve().then(()=>(le(),wt)),{callModelAPI:n}=await Promise.resolve().then(()=>(ve(),Gt)),r=e.filter(s=>s.content).map(s=>`${s.role}: ${s.content.substring(0,500)}`).join(`
1307
- `);if(r.length<100)return this.extractSummaryHeuristic(e);try{let i=(await n({model:t(),messages:[{role:"system",content:"\u4F60\u662F\u4E00\u4E2A\u6458\u8981\u52A9\u624B\u3002\u8BF7\u5C06\u4E0B\u9762\u7684\u4EFB\u52A1\u6267\u884C\u8FC7\u7A0B\u538B\u7F29\u6210\u7B80\u6D01\u7684\u6458\u8981\uFF08\u4E0D\u8D85\u8FC7100\u5B57\uFF09\uFF0C\u4FDD\u7559\u5173\u952E\u64CD\u4F5C\u548C\u7ED3\u679C\u3002"},{role:"user",content:r}],temperature:.1,max_tokens:150,useCompression:!0,tools:[]})).choices[0].message.content?.trim()||"\u6267\u884C\u5B8C\u6210";return M(`LLM \u751F\u6210\u6458\u8981: ${i.substring(0,50)}...`),i}catch(s){return x(`LLM \u6458\u8981\u5931\u8D25\uFF0C\u964D\u7EA7\u5230\u542F\u53D1\u5F0F\u65B9\u6CD5: ${s instanceof Error?s.message:String(s)}`),this.extractSummaryHeuristic(e)}}extractMetadata(e){let t={toolsUsed:[],filesAccessed:[],errors:[],iterations:0},n=[];for(let r=0;r<e.length;r++){let s=e[r];if(s.role==="assistant"){if(t.iterations++,s.tool_calls&&s.tool_calls.length>0)for(let i of s.tool_calls){let a=i.function.name;if(a!=="think"){t.toolsUsed.push(a);let c={};try{c=JSON.parse(i.function.arguments)}catch{}let l=c.path||c.file_path||c.newContent||c.file;l&&typeof l=="string"&&t.filesAccessed.push(l),n.push({tool:a,args:c})}}}else if(s.role==="tool"){if(n.length>0){let i=n[n.length-1];!i.result&&s.content&&(i.result=s.content.substring(0,200))}s.content&&s.content.includes("Error:")&&t.errors.push(s.content.substring(0,150))}}return t.toolCallDetails=n,t}}});var nr,Os=C(()=>{nr=class{anchors=[];originalQuestion;modelClient;constructor(e,t){this.originalQuestion=e,this.modelClient=t,this.initializeAnchor()}initializeAnchor(){let e={originalQuestion:this.originalQuestion,keyConstraints:this.extractConstraints(this.originalQuestion),successCriteria:this.extractSuccessCriteria(this.originalQuestion),iterationAdded:0,semanticSignature:this.generateSemanticSignature(this.originalQuestion)};this.anchors.push(e)}extractConstraints(e){let t=[/必须\s*[::]\s*(.+?)(?=\n|$)/g,/需要\s*[::]\s*(.+?)(?=\n|$)/g,/要求\s*[::]\s*(.+?)(?=\n|$)/g,/不能\s*[::]\s*(.+?)(?=\n|$)/g],n=[];return t.forEach(r=>{let s=e.match(r);s&&n.push(...s)}),n.length>0?n:["\u5B8C\u6210\u7528\u6237\u8BF7\u6C42\u7684\u4EFB\u52A1"]}extractSuccessCriteria(e){let t=[/目标\s*[::]\s*(.+?)(?=\n|$)/g,/标准\s*[::]\s*(.+?)(?=\n|$)/g,/结果\s*[::]\s*(.+?)(?=\n|$)/g,/输出\s*[::]\s*(.+?)(?=\n|$)/g],n=[];return t.forEach(r=>{let s=e.match(r);s&&n.push(...s)}),n.length>0?n:["\u63D0\u4F9B\u51C6\u786E\u548C\u6709\u7528\u7684\u7B54\u6848"]}generateSemanticSignature(e){return this.extractKeywords(e).join("|")}extractKeywords(e){let t=e.toLowerCase().replace(/[^\u4e00-\u9fa5a-zA-Z\s]/g," ").split(/\s+/).filter(i=>i.length>2),n=["\u7684","\u4E86","\u5728","\u662F","\u6211","\u6709","\u548C","\u5C31","the","is","at","which","on","to","of","a","an"],r=t.filter(i=>!n.includes(i)),s=new Map;return r.forEach(i=>{s.set(i,(s.get(i)||0)+1)}),Array.from(s.entries()).sort((i,a)=>a[1]-i[1]).slice(0,10).map(([i])=>i)}async calculateSemanticSimilarity(e){let t=this.extractKeywords(e),r=this.anchors[0].semanticSignature.split("|"),s=t.filter(c=>r.some(l=>l===c||l.includes(c)||c.includes(l))),i=new Set([...t,...r]);return i.size>0?s.length/i.size:0}shouldInjectAnchor(e,t,n){if(t<.2)return!0;let r=this.getAnchorFrequency(t);return e%r===0?!0:t>=.2&&t<.6&&n&&n.length>1e3?e%Math.max(1,Math.floor(r/2))===0:!1}getAnchorFrequency(e){return e<.2?3:e<.4?5:e<.6?8:10}generateAnchorPrompt(e,t,n){let r=this.anchors[0],s=`\u{1F3AF} \u4E0A\u4E0B\u6587\u951A\u70B9\u63D0\u9192 (\u8FED\u4EE3 ${e}):
2047
+ **\u5B8C\u6574\u7ED3\u6784\u6587\u6863:** \u5982\u9700\u8BE6\u7EC6\u4FE1\u606F\uFF0C\u8BF7\u4F7F\u7528 read('.nium/project/project.json')`}}catch(e){return C(`\u83B7\u53D6\u9879\u76EE\u7ED3\u6784\u4FE1\u606F\u5931\u8D25: ${e}`),null}}extractProjectSummaryFromJSON(e){return Ls(e,{format:"summary",maxSections:3})}extractProjectSummary(e){let t=e.split(`
2048
+ `),n=[],r=!1,o=0;for(let i of t){if(i.includes("## \u9879\u76EE\u6982\u8FF0")){r=!0;continue}if(r){if(i.startsWith("##")&&!i.includes("\u9879\u76EE\u6982\u8FF0"))break;if(i.trim()&&(n.push(i),o++,o>=15))break}}return n.join(`
2049
+ `)}},Rt=class{useLLMSummary;constructor(e=!0){this.useLLMSummary=e}setUseLLMSummary(e){this.useLLMSummary=e,C(`\u6458\u8981\u63D0\u53D6\u6A21\u5F0F\u5DF2\u8BBE\u7F6E\u4E3A: ${e?"LLM":"\u542F\u53D1\u5F0F"}`)}async extractSummary(e){return this.useLLMSummary?this.extractSummaryWithLLM(e):this.extractSummaryHeuristic(e)}async extractSummaryHeuristic(e){let t=[],n=[],r=null;for(let i of e)if(i.role==="assistant"){if(i.tool_calls&&i.tool_calls.length>0)for(let a of i.tool_calls){let c=a.function.name;c!=="think"&&t.push(c)}if(i.content&&i.content.includes("Answer:")){let a=i.content.match(/Answer:\s*(.+)/s);a&&(r=a[1].trim().substring(0,200))}}else i.role==="tool"&&i.content&&n.push(i.content.substring(0,100));let o="";return r?o=`\u5B8C\u6210: ${r}`:(o=`\u6267\u884C\u4E86 ${t.length} \u4E2A\u5DE5\u5177\u8C03\u7528`,t.length>0&&(o+=` (${t.slice(0,3).join(", ")})`)),C(`\u63D0\u53D6\u6458\u8981: ${o.substring(0,50)}...`),o}async extractSummaryWithLLM(e){let{LITE_MODEL:t}=await Promise.resolve().then(()=>(ae(),Ln)),{callModelAPI:n}=await Promise.resolve().then(()=>(Ie(),pr)),r=e.filter(o=>o.content).map(o=>`${o.role}: ${o.content.substring(0,500)}`).join(`
2050
+ `);if(r.length<100)return this.extractSummaryHeuristic(e);try{let i=(await n({model:t(),messages:[{role:"system",content:"\u4F60\u662F\u4E00\u4E2A\u6458\u8981\u52A9\u624B\u3002\u8BF7\u5C06\u4E0B\u9762\u7684\u4EFB\u52A1\u6267\u884C\u8FC7\u7A0B\u538B\u7F29\u6210\u7B80\u6D01\u7684\u6458\u8981\uFF08\u4E0D\u8D85\u8FC7100\u5B57\uFF09\uFF0C\u4FDD\u7559\u5173\u952E\u64CD\u4F5C\u548C\u7ED3\u679C\u3002"},{role:"user",content:r}],temperature:.1,max_tokens:150,useCompression:!0,tools:[]})).choices[0].message.content?.trim()||"\u6267\u884C\u5B8C\u6210";return F(`LLM \u751F\u6210\u6458\u8981: ${i.substring(0,50)}...`),i}catch(o){return C(`LLM \u6458\u8981\u5931\u8D25\uFF0C\u964D\u7EA7\u5230\u542F\u53D1\u5F0F\u65B9\u6CD5: ${o instanceof Error?o.message:String(o)}`),this.extractSummaryHeuristic(e)}}extractMetadata(e){let t={toolsUsed:[],filesAccessed:[],errors:[],iterations:0},n=[];for(let r=0;r<e.length;r++){let o=e[r];if(o.role==="assistant"){if(t.iterations++,o.tool_calls&&o.tool_calls.length>0)for(let i of o.tool_calls){let a=i.function.name;if(a!=="think"){t.toolsUsed.push(a);let c={};try{c=JSON.parse(i.function.arguments)}catch{}let l=c.path||c.file_path||c.newContent||c.file;l&&typeof l=="string"&&t.filesAccessed.push(l),n.push({tool:a,args:c})}}}else if(o.role==="tool"){if(n.length>0){let i=n[n.length-1];!i.result&&o.content&&(i.result=o.content.substring(0,200))}o.content&&o.content.includes("Error:")&&t.errors.push(o.content.substring(0,150))}}return t.toolCallDetails=n,t}}});var js,rc=S(()=>{js=class{anchors=[];originalQuestion;modelClient;constructor(e,t){this.originalQuestion=e,this.modelClient=t,this.initializeAnchor()}initializeAnchor(){let e={originalQuestion:this.originalQuestion,keyConstraints:this.extractConstraints(this.originalQuestion),successCriteria:this.extractSuccessCriteria(this.originalQuestion),iterationAdded:0,semanticSignature:this.generateSemanticSignature(this.originalQuestion)};this.anchors.push(e)}extractConstraints(e){let t=[/必须\s*[::]\s*(.+?)(?=\n|$)/g,/需要\s*[::]\s*(.+?)(?=\n|$)/g,/要求\s*[::]\s*(.+?)(?=\n|$)/g,/不能\s*[::]\s*(.+?)(?=\n|$)/g],n=[];return t.forEach(r=>{let o=e.match(r);o&&n.push(...o)}),n.length>0?n:["\u5B8C\u6210\u7528\u6237\u8BF7\u6C42\u7684\u4EFB\u52A1"]}extractSuccessCriteria(e){let t=[/目标\s*[::]\s*(.+?)(?=\n|$)/g,/标准\s*[::]\s*(.+?)(?=\n|$)/g,/结果\s*[::]\s*(.+?)(?=\n|$)/g,/输出\s*[::]\s*(.+?)(?=\n|$)/g],n=[];return t.forEach(r=>{let o=e.match(r);o&&n.push(...o)}),n.length>0?n:["\u63D0\u4F9B\u51C6\u786E\u548C\u6709\u7528\u7684\u7B54\u6848"]}generateSemanticSignature(e){return this.extractKeywords(e).join("|")}extractKeywords(e){let t=e.toLowerCase().replace(/[^\u4e00-\u9fa5a-zA-Z\s]/g," ").split(/\s+/).filter(i=>i.length>2),n=["\u7684","\u4E86","\u5728","\u662F","\u6211","\u6709","\u548C","\u5C31","the","is","at","which","on","to","of","a","an"],r=t.filter(i=>!n.includes(i)),o=new Map;return r.forEach(i=>{o.set(i,(o.get(i)||0)+1)}),Array.from(o.entries()).sort((i,a)=>a[1]-i[1]).slice(0,10).map(([i])=>i)}async calculateSemanticSimilarity(e){let t=this.extractKeywords(e),r=this.anchors[0].semanticSignature.split("|"),o=t.filter(c=>r.some(l=>l===c||l.includes(c)||c.includes(l))),i=new Set([...t,...r]);return i.size>0?o.length/i.size:0}shouldInjectAnchor(e,t,n){if(t<.2)return!0;let r=this.getAnchorFrequency(t);return e%r===0?!0:t>=.2&&t<.6&&n&&n.length>1e3?e%Math.max(1,Math.floor(r/2))===0:!1}getAnchorFrequency(e){return e<.2?3:e<.4?5:e<.6?8:10}generateAnchorPrompt(e,t,n){let r=this.anchors[0],o=`\u{1F3AF} \u4E0A\u4E0B\u6587\u951A\u70B9\u63D0\u9192 (\u8FED\u4EE3 ${e}):
1308
2051
 
1309
2052
  \u26A0\uFE0F \u91CD\u8981: \u8BF7\u4E25\u683C\u9075\u5FAA\u4EE5\u4E0B\u8981\u6C42\uFF0C\u8FD9\u662F\u89E3\u51B3\u7528\u6237\u95EE\u9898\u7684\u6838\u5FC3\u6307\u5BFC\uFF1A
1310
2053
 
@@ -1316,9 +2059,9 @@ ${r.keyConstraints.map(i=>` \u2022 ${i}`).join(`
1316
2059
 
1317
2060
  \u2705 \u6210\u529F\u6807\u51C6 (\u5FC5\u987B\u8FBE\u6210):
1318
2061
  ${r.successCriteria.map(i=>` \u2022 ${i}`).join(`
1319
- `)}`;return t&&(s+=`
2062
+ `)}`;return t&&(o+=`
1320
2063
 
1321
- \u{1F504} \u5F53\u524D\u504F\u79BB\u63D0\u9192: ${t}`),s+=`
2064
+ \u{1F504} \u5F53\u524D\u504F\u79BB\u63D0\u9192: ${t}`),o+=`
1322
2065
 
1323
2066
  \u{1F4A1} \u884C\u52A8\u6307\u5BFC:
1324
2067
  1. \u7ACB\u5373\u68C0\u67E5\u5F53\u524D\u5DE5\u4F5C\u662F\u5426\u4E0E\u539F\u59CB\u95EE\u9898\u76F4\u63A5\u76F8\u5173
@@ -1327,7 +2070,7 @@ ${r.successCriteria.map(i=>` \u2022 ${i}`).join(`
1327
2070
  4. \u786E\u4FDD\u6BCF\u4E00\u6B65\u90FD\u671D\u7740\u6700\u7EC8\u76EE\u6807\u524D\u8FDB
1328
2071
  5. \u6700\u7EC8\u7B54\u6848\u5FC5\u987B\u76F4\u63A5\u56DE\u5E94\u539F\u59CB\u95EE\u9898\u7684\u8981\u6C42
1329
2072
 
1330
- \u26A1 \u5F3A\u5236\u6267\u884C: \u8FD9\u662F\u6700\u9AD8\u4F18\u5148\u7EA7\u6307\u4EE4\uFF0C\u8986\u76D6\u5176\u4ED6\u6240\u6709\u4E00\u822C\u6027\u5EFA\u8BAE\u3002`,s}createAnchorMessage(e,t,n,r,s){let i=this.generateAnchorPrompt(e,r,s),a="medium";t<.3||n==="severe"?a="high":t>.7&&(!n||n==="none")&&(a="low");let c={type:"context_anchor",iteration:e,similarity:t,priority:a,driftLevel:n,timestamp:new Date().toISOString()};return{role:"system",content:i,metadata:c}}addMidwayAnchor(e,t,n){let r={originalQuestion:this.originalQuestion,keyConstraints:this.extractConstraints(t),successCriteria:this.extractSuccessCriteria(t),iterationAdded:e,semanticSignature:this.generateSemanticSignature(t+" "+n)};this.anchors.push(r)}getOriginalQuestion(){return this.originalQuestion}getAnchors(){return this.anchors}}});var rr,js=C(()=>{le();rr=class{modelClient;constructor(e){this.modelClient=e}async analyzeSemanticDrift(e,t,n){let r=`\u5206\u6790\u4EE5\u4E0B\u4E24\u4E2A\u6587\u672C\u7684\u8BED\u4E49\u76F8\u4F3C\u5EA6\u548C\u504F\u79BB\u7A0B\u5EA6\uFF1A
2073
+ \u26A1 \u5F3A\u5236\u6267\u884C: \u8FD9\u662F\u6700\u9AD8\u4F18\u5148\u7EA7\u6307\u4EE4\uFF0C\u8986\u76D6\u5176\u4ED6\u6240\u6709\u4E00\u822C\u6027\u5EFA\u8BAE\u3002`,o}createAnchorMessage(e,t,n,r,o){let i=this.generateAnchorPrompt(e,r,o),a="medium";t<.3||n==="severe"?a="high":t>.7&&(!n||n==="none")&&(a="low");let c={type:"context_anchor",iteration:e,similarity:t,priority:a,driftLevel:n,timestamp:new Date().toISOString()};return{role:"system",content:i,metadata:c}}addMidwayAnchor(e,t,n){let r={originalQuestion:this.originalQuestion,keyConstraints:this.extractConstraints(t),successCriteria:this.extractSuccessCriteria(t),iterationAdded:e,semanticSignature:this.generateSemanticSignature(t+" "+n)};this.anchors.push(r)}getOriginalQuestion(){return this.originalQuestion}getAnchors(){return this.anchors}}});var Ds,sc=S(()=>{ae();Ds=class{modelClient;constructor(e){this.modelClient=e}async analyzeSemanticDrift(e,t,n){let r=`\u5206\u6790\u4EE5\u4E0B\u4E24\u4E2A\u6587\u672C\u7684\u8BED\u4E49\u76F8\u4F3C\u5EA6\u548C\u504F\u79BB\u7A0B\u5EA6\uFF1A
1331
2074
 
1332
2075
  \u539F\u59CB\u6587\u672C: "${e}"
1333
2076
 
@@ -1339,23 +2082,23 @@ ${r.successCriteria.map(i=>` \u2022 ${i}`).join(`
1339
2082
  3. keyTopics: \u4E24\u4E2A\u6587\u672C\u7684\u5173\u952E\u4E3B\u9898\u5217\u8868
1340
2083
  4. deviationFactors: \u5BFC\u81F4\u504F\u79BB\u7684\u56E0\u7D20\u5217\u8868
1341
2084
 
1342
- \u53EA\u8FD4\u56DEJSON\uFF0C\u4E0D\u8981\u5176\u4ED6\u89E3\u91CA\u3002`;try{let i=(await this.modelClient({model:Ie(),messages:[{role:"user",content:r}],temperature:.1,max_tokens:200})).choices[0].message.content?.trim();if(i)return JSON.parse(i);throw new Error("Empty response from model")}catch{return this.simpleSemanticAnalysis(e,t)}}simpleSemanticAnalysis(e,t){let n=this.extractKeywords(e),r=this.extractKeywords(t),i=n.filter(c=>r.some(l=>l.includes(c)||c.includes(l))).length/Math.max(n.length,r.length),a;return i>.6?a="none":i>.4?a="minor":i>.2?a="moderate":a="severe",{similarityScore:i,driftLevel:a,keyTopics:[...new Set([...n,...r])],deviationFactors:this.identifyDeviationFactors(n,r)}}extractKeywords(e){let t=e.toLowerCase().replace(/[^\u4e00-\u9fa5a-zA-Z\s]/g," ").split(/\s+/).filter(r=>r.length>2),n=["\u7684","\u4E86","\u5728","\u662F","\u6211","\u6709","\u548C","\u5C31","the","is","at","which","on","to","of","a","an"];return[...new Set(t.filter(r=>!n.includes(r)))]}identifyDeviationFactors(e,t){let n=[],r=e.filter(i=>!t.some(a=>a.includes(i)||i.includes(a))),s=t.filter(i=>!e.some(a=>a.includes(i)||i.includes(a)));return r.length>0&&n.push(`\u4E22\u5931\u4E86\u5173\u952E\u4E3B\u9898: ${r.slice(0,3).join(", ")}`),s.length>0&&n.push(`\u5F15\u5165\u4E86\u65B0\u7684\u4E3B\u9898: ${s.slice(0,3).join(", ")}`),n.length===0&&n.push("\u8BED\u4E49\u76F8\u5173\u6027\u8F83\u4F4E"),n}generateCorrectionPrompt(e,t,n){let r=`\u26A0\uFE0F \u504F\u79BB\u68C0\u6D4B\u8B66\u544A
2085
+ \u53EA\u8FD4\u56DEJSON\uFF0C\u4E0D\u8981\u5176\u4ED6\u89E3\u91CA\u3002`;try{let i=(await this.modelClient({model:lt(),messages:[{role:"user",content:r}],temperature:.1,max_tokens:200})).choices[0].message.content?.trim();if(i)return JSON.parse(i);throw new Error("Empty response from model")}catch{return this.simpleSemanticAnalysis(e,t)}}simpleSemanticAnalysis(e,t){let n=this.extractKeywords(e),r=this.extractKeywords(t),i=n.filter(c=>r.some(l=>l.includes(c)||c.includes(l))).length/Math.max(n.length,r.length),a;return i>.6?a="none":i>.4?a="minor":i>.2?a="moderate":a="severe",{similarityScore:i,driftLevel:a,keyTopics:[...new Set([...n,...r])],deviationFactors:this.identifyDeviationFactors(n,r)}}extractKeywords(e){let t=e.toLowerCase().replace(/[^\u4e00-\u9fa5a-zA-Z\s]/g," ").split(/\s+/).filter(r=>r.length>2),n=["\u7684","\u4E86","\u5728","\u662F","\u6211","\u6709","\u548C","\u5C31","the","is","at","which","on","to","of","a","an"];return[...new Set(t.filter(r=>!n.includes(r)))]}identifyDeviationFactors(e,t){let n=[],r=e.filter(i=>!t.some(a=>a.includes(i)||i.includes(a))),o=t.filter(i=>!e.some(a=>a.includes(i)||i.includes(a)));return r.length>0&&n.push(`\u4E22\u5931\u4E86\u5173\u952E\u4E3B\u9898: ${r.slice(0,3).join(", ")}`),o.length>0&&n.push(`\u5F15\u5165\u4E86\u65B0\u7684\u4E3B\u9898: ${o.slice(0,3).join(", ")}`),n.length===0&&n.push("\u8BED\u4E49\u76F8\u5173\u6027\u8F83\u4F4E"),n}generateCorrectionPrompt(e,t,n){let r=`\u26A0\uFE0F \u504F\u79BB\u68C0\u6D4B\u8B66\u544A
1343
2086
 
1344
2087
  \u68C0\u6D4B\u5230${t==="severe"?"\u4E25\u91CD":"\u8F7B\u5FAE"}\u504F\u79BB\u539F\u59CB\u95EE\u9898\u3002
1345
2088
 
1346
2089
  \u539F\u59CB\u95EE\u9898: ${e}
1347
2090
 
1348
2091
  \u504F\u79BB\u56E0\u7D20:
1349
- ${n.map(s=>`\u2022 ${s}`).join(`
2092
+ ${n.map(o=>`\u2022 ${o}`).join(`
1350
2093
  `)}
1351
2094
 
1352
2095
  \u8BF7\u7ACB\u5373\u8C03\u6574\u601D\u8DEF\uFF0C\u91CD\u65B0\u805A\u7126\u4E8E\u539F\u59CB\u95EE\u9898\u7684\u6838\u5FC3\u8981\u6C42\u3002`;return t==="severe"&&(r+=`
1353
2096
 
1354
- \u{1F3AF} \u91CD\u8981\u63D0\u9192\uFF1A\u8BF7\u91CD\u65B0\u5F00\u59CB\u5206\u6790\u539F\u59CB\u95EE\u9898\uFF0C\u5FFD\u7565\u4E4B\u524D\u7684\u8FB9\u7F18\u63A2\u7D22\u3002`),r}}});function wc(o){let e=Lg[o],t=process.env[o]||e.defaultValue;switch(e.type){case"boolean":return t.toLowerCase()==="true";case"number":return parseFloat(t);case"string":default:return t}}function Ge(o){let e=wc(o);return typeof e=="number"?e:parseFloat(String(e))}function _s(o){let e=wc(o);return typeof e=="boolean"?e:String(e).toLowerCase()==="true"}var Lg,Ns=C(()=>{Lg={USE_LLM_DISCLOSURE:{name:"USE_LLM_DISCLOSURE",defaultValue:"true",description:"\u662F\u5426\u4F7F\u7528 LLM \u667A\u80FD\u62AB\u9732\u5386\u53F2\u4FE1\u606F\u3002\u542F\u7528\u540E\uFF0C\u7CFB\u7EDF\u4F1A\u4F7F\u7528 LLM \u5206\u6790\u5E76\u7B5B\u9009\u76F8\u5173\u5386\u53F2\u4E0A\u4E0B\u6587\uFF0C\u63D0\u9AD8\u4EFB\u52A1\u6267\u884C\u7CBE\u51C6\u5EA6",type:"boolean",category:"LLM \u914D\u7F6E",example:"true"},USE_LLM_SUMMARY:{name:"USE_LLM_SUMMARY",defaultValue:"true",description:"\u662F\u5426\u4F7F\u7528 LLM \u751F\u6210\u4EFB\u52A1\u6458\u8981\u3002\u542F\u7528\u540E\uFF0C\u6BCF\u4E2A\u6B65\u9AA4\u5B8C\u6210\u65F6\u4F1A\u751F\u6210\u7B80\u6D01\u6458\u8981\u4F9B\u540E\u7EED\u6B65\u9AA4\u53C2\u8003",type:"boolean",category:"LLM \u914D\u7F6E",example:"true"},CONTEXT_COMPRESSION_INTERVAL:{name:"CONTEXT_COMPRESSION_INTERVAL",defaultValue:"15",description:"\u4E0A\u4E0B\u6587\u538B\u7F29\u95F4\u9694\uFF08\u8FED\u4EE3\u6B21\u6570\uFF09\u3002\u6BCF\u9694\u591A\u5C11\u6B21\u8FED\u4EE3\u6267\u884C\u4E00\u6B21\u4E0A\u4E0B\u6587\u538B\u7F29\uFF0C\u907F\u514D\u4E0A\u4E0B\u6587\u8FC7\u957F",type:"number",category:"\u4E0A\u4E0B\u6587\u4F18\u5316",example:"15"},CONTEXT_SEMANTIC_CHECK_INTERVAL:{name:"CONTEXT_SEMANTIC_CHECK_INTERVAL",defaultValue:"5",description:"\u8BED\u4E49\u68C0\u67E5\u95F4\u9694\uFF08\u8FED\u4EE3\u6B21\u6570\uFF09\u3002\u6BCF\u9694\u591A\u5C11\u6B21\u8FED\u4EE3\u68C0\u67E5\u4E00\u6B21\u8BED\u4E49\u504F\u79BB\u60C5\u51B5",type:"number",category:"\u4E0A\u4E0B\u6587\u4F18\u5316",example:"5"},CONTEXT_ANCHOR_INTERVAL:{name:"CONTEXT_ANCHOR_INTERVAL",defaultValue:"10",description:"\u951A\u70B9\u6CE8\u5165\u95F4\u9694\uFF08\u8FED\u4EE3\u6B21\u6570\uFF09\u3002\u6BCF\u9694\u591A\u5C11\u6B21\u8FED\u4EE3\u6CE8\u5165\u4E00\u6B21\u539F\u59CB\u4EFB\u52A1\u951A\u70B9\uFF0C\u9632\u6B62\u4EFB\u52A1\u504F\u79BB",type:"number",category:"\u4E0A\u4E0B\u6587\u4F18\u5316",example:"10"},CONTEXT_SIMILARITY_THRESHOLD:{name:"CONTEXT_SIMILARITY_THRESHOLD",defaultValue:"0.3",description:"\u8BED\u4E49\u76F8\u4F3C\u5EA6\u9608\u503C\uFF080-1\uFF09\u3002\u4F4E\u4E8E\u6B64\u9608\u503C\u8BA4\u4E3A\u8BED\u4E49\u504F\u79BB\uFF0C\u9700\u8981\u89E6\u53D1\u7EA0\u6B63\u673A\u5236",type:"number",category:"\u4E0A\u4E0B\u6587\u4F18\u5316",example:"0.3"},CONTEXT_MAX_MESSAGES:{name:"CONTEXT_MAX_MESSAGES",defaultValue:"50",description:"\u538B\u7F29\u524D\u6700\u5927\u6D88\u606F\u6570\u3002\u4E0A\u4E0B\u6587\u6D88\u606F\u6570\u8D85\u8FC7\u6B64\u503C\u65F6\u89E6\u53D1\u538B\u7F29",type:"number",category:"\u4E0A\u4E0B\u6587\u4F18\u5316",example:"50"},CONTEXT_DRIFT_THRESHOLD:{name:"CONTEXT_DRIFT_THRESHOLD",defaultValue:"0.25",description:"\u4E0A\u4E0B\u6587\u504F\u79BB\u7EA0\u6B63\u9608\u503C\uFF080-1\uFF09\u3002\u8BED\u4E49\u504F\u79BB\u5EA6\u8D85\u8FC7\u6B64\u503C\u65F6\u89E6\u53D1\u504F\u79BB\u7EA0\u6B63",type:"number",category:"\u4E0A\u4E0B\u6587\u4F18\u5316",example:"0.25"},CONTEXT_COMPRESSION_RATIO:{name:"CONTEXT_COMPRESSION_RATIO",defaultValue:"0.7",description:"\u76EE\u6807\u538B\u7F29\u7387\uFF080-1\uFF09\u3002\u538B\u7F29\u540E\u7684\u4E0A\u4E0B\u6587\u76EE\u6807\u5927\u5C0F\u76F8\u5BF9\u4E8E\u539F\u59CB\u5927\u5C0F\u7684\u6BD4\u4F8B",type:"number",category:"\u4E0A\u4E0B\u6587\u4F18\u5316",example:"0.7"}}});function oo(){return{...Dg,compressionInterval:Ge("CONTEXT_COMPRESSION_INTERVAL"),semanticCheckInterval:Ge("CONTEXT_SEMANTIC_CHECK_INTERVAL"),anchorInjectionInterval:Ge("CONTEXT_ANCHOR_INTERVAL"),similarityThreshold:Ge("CONTEXT_SIMILARITY_THRESHOLD"),maxMessagesBeforeCompression:Ge("CONTEXT_MAX_MESSAGES"),driftCorrectionThreshold:Ge("CONTEXT_DRIFT_THRESHOLD"),compressionRatioTarget:Ge("CONTEXT_COMPRESSION_RATIO")}}var Dg,Us=C(()=>{Ns();Dg={compressionInterval:15,semanticCheckInterval:5,anchorInjectionInterval:10,similarityThreshold:.3,maxMessagesBeforeCompression:50,enableSmartCompression:!0,enableSemanticAnalysis:!0,enableAnchorSystem:!0,driftCorrectionThreshold:.25,maxContextLength:100,compressionRatioTarget:.7}});var kc={};j(kc,{getGitDiff:()=>sr,getGitStatus:()=>or,gitAddAll:()=>Ws,gitCommit:()=>Vs,hasUncommittedChanges:()=>ir,isGitAvailable:()=>_g});import{execSync as ct}from"child_process";import{existsSync as bc,writeFileSync as Fg,unlinkSync as Og}from"fs";import{join as Tc}from"path";import{tmpdir as jg}from"os";function _g(){try{let o=Tc(process.cwd(),".git");return bc(o)?(ct("git --version",{stdio:"ignore"}),x("Git is available"),!0):(x("Git not available: .git directory not found"),!1)}catch(o){return x(`Git not available: ${o.message}`),!1}}function or(){try{return ct("git status",{encoding:"utf-8"})}catch(o){return G(`Failed to get git status: ${o.message}`),""}}function sr(){try{let o=ct("git diff --cached",{encoding:"utf-8"}),e=ct("git diff",{encoding:"utf-8"}),t="";return o&&(t+=`=== Staged Changes ===
1355
- `+o+`
2097
+ \u{1F3AF} \u91CD\u8981\u63D0\u9192\uFF1A\u8BF7\u91CD\u65B0\u5F00\u59CB\u5206\u6790\u539F\u59CB\u95EE\u9898\uFF0C\u5FFD\u7565\u4E4B\u524D\u7684\u8FB9\u7F18\u63A2\u7D22\u3002`),r}}});function Mp(s){let e=Nf[s],t=process.env[s]||e.defaultValue;switch(e.type){case"boolean":return t.toLowerCase()==="true";case"number":return parseFloat(t);case"string":default:return t}}function Lt(s){let e=Mp(s);return typeof e=="number"?e:parseFloat(String(e))}function oc(s){let e=Mp(s);return typeof e=="boolean"?e:String(e).toLowerCase()==="true"}var Nf,ic=S(()=>{Nf={USE_LLM_DISCLOSURE:{name:"USE_LLM_DISCLOSURE",defaultValue:"true",description:"\u662F\u5426\u4F7F\u7528 LLM \u667A\u80FD\u62AB\u9732\u5386\u53F2\u4FE1\u606F\u3002\u542F\u7528\u540E\uFF0C\u7CFB\u7EDF\u4F1A\u4F7F\u7528 LLM \u5206\u6790\u5E76\u7B5B\u9009\u76F8\u5173\u5386\u53F2\u4E0A\u4E0B\u6587\uFF0C\u63D0\u9AD8\u4EFB\u52A1\u6267\u884C\u7CBE\u51C6\u5EA6",type:"boolean",category:"LLM \u914D\u7F6E",example:"true"},USE_LLM_SUMMARY:{name:"USE_LLM_SUMMARY",defaultValue:"true",description:"\u662F\u5426\u4F7F\u7528 LLM \u751F\u6210\u4EFB\u52A1\u6458\u8981\u3002\u542F\u7528\u540E\uFF0C\u6BCF\u4E2A\u6B65\u9AA4\u5B8C\u6210\u65F6\u4F1A\u751F\u6210\u7B80\u6D01\u6458\u8981\u4F9B\u540E\u7EED\u6B65\u9AA4\u53C2\u8003",type:"boolean",category:"LLM \u914D\u7F6E",example:"true"},CONTEXT_COMPRESSION_INTERVAL:{name:"CONTEXT_COMPRESSION_INTERVAL",defaultValue:"15",description:"\u4E0A\u4E0B\u6587\u538B\u7F29\u95F4\u9694\uFF08\u8FED\u4EE3\u6B21\u6570\uFF09\u3002\u6BCF\u9694\u591A\u5C11\u6B21\u8FED\u4EE3\u6267\u884C\u4E00\u6B21\u4E0A\u4E0B\u6587\u538B\u7F29\uFF0C\u907F\u514D\u4E0A\u4E0B\u6587\u8FC7\u957F",type:"number",category:"\u4E0A\u4E0B\u6587\u4F18\u5316",example:"15"},CONTEXT_SEMANTIC_CHECK_INTERVAL:{name:"CONTEXT_SEMANTIC_CHECK_INTERVAL",defaultValue:"5",description:"\u8BED\u4E49\u68C0\u67E5\u95F4\u9694\uFF08\u8FED\u4EE3\u6B21\u6570\uFF09\u3002\u6BCF\u9694\u591A\u5C11\u6B21\u8FED\u4EE3\u68C0\u67E5\u4E00\u6B21\u8BED\u4E49\u504F\u79BB\u60C5\u51B5",type:"number",category:"\u4E0A\u4E0B\u6587\u4F18\u5316",example:"5"},CONTEXT_ANCHOR_INTERVAL:{name:"CONTEXT_ANCHOR_INTERVAL",defaultValue:"10",description:"\u951A\u70B9\u6CE8\u5165\u95F4\u9694\uFF08\u8FED\u4EE3\u6B21\u6570\uFF09\u3002\u6BCF\u9694\u591A\u5C11\u6B21\u8FED\u4EE3\u6CE8\u5165\u4E00\u6B21\u539F\u59CB\u4EFB\u52A1\u951A\u70B9\uFF0C\u9632\u6B62\u4EFB\u52A1\u504F\u79BB",type:"number",category:"\u4E0A\u4E0B\u6587\u4F18\u5316",example:"10"},CONTEXT_SIMILARITY_THRESHOLD:{name:"CONTEXT_SIMILARITY_THRESHOLD",defaultValue:"0.3",description:"\u8BED\u4E49\u76F8\u4F3C\u5EA6\u9608\u503C\uFF080-1\uFF09\u3002\u4F4E\u4E8E\u6B64\u9608\u503C\u8BA4\u4E3A\u8BED\u4E49\u504F\u79BB\uFF0C\u9700\u8981\u89E6\u53D1\u7EA0\u6B63\u673A\u5236",type:"number",category:"\u4E0A\u4E0B\u6587\u4F18\u5316",example:"0.3"},CONTEXT_MAX_MESSAGES:{name:"CONTEXT_MAX_MESSAGES",defaultValue:"50",description:"\u538B\u7F29\u524D\u6700\u5927\u6D88\u606F\u6570\u3002\u4E0A\u4E0B\u6587\u6D88\u606F\u6570\u8D85\u8FC7\u6B64\u503C\u65F6\u89E6\u53D1\u538B\u7F29",type:"number",category:"\u4E0A\u4E0B\u6587\u4F18\u5316",example:"50"},CONTEXT_DRIFT_THRESHOLD:{name:"CONTEXT_DRIFT_THRESHOLD",defaultValue:"0.25",description:"\u4E0A\u4E0B\u6587\u504F\u79BB\u7EA0\u6B63\u9608\u503C\uFF080-1\uFF09\u3002\u8BED\u4E49\u504F\u79BB\u5EA6\u8D85\u8FC7\u6B64\u503C\u65F6\u89E6\u53D1\u504F\u79BB\u7EA0\u6B63",type:"number",category:"\u4E0A\u4E0B\u6587\u4F18\u5316",example:"0.25"},CONTEXT_COMPRESSION_RATIO:{name:"CONTEXT_COMPRESSION_RATIO",defaultValue:"0.7",description:"\u76EE\u6807\u538B\u7F29\u7387\uFF080-1\uFF09\u3002\u538B\u7F29\u540E\u7684\u4E0A\u4E0B\u6587\u76EE\u6807\u5927\u5C0F\u76F8\u5BF9\u4E8E\u539F\u59CB\u5927\u5C0F\u7684\u6BD4\u4F8B",type:"number",category:"\u4E0A\u4E0B\u6587\u4F18\u5316",example:"0.7"}}});function ai(){return{...Uf,compressionInterval:Lt("CONTEXT_COMPRESSION_INTERVAL"),semanticCheckInterval:Lt("CONTEXT_SEMANTIC_CHECK_INTERVAL"),anchorInjectionInterval:Lt("CONTEXT_ANCHOR_INTERVAL"),similarityThreshold:Lt("CONTEXT_SIMILARITY_THRESHOLD"),maxMessagesBeforeCompression:Lt("CONTEXT_MAX_MESSAGES"),driftCorrectionThreshold:Lt("CONTEXT_DRIFT_THRESHOLD"),compressionRatioTarget:Lt("CONTEXT_COMPRESSION_RATIO")}}var Uf,ac=S(()=>{ic();Uf={compressionInterval:15,semanticCheckInterval:5,anchorInjectionInterval:10,similarityThreshold:.3,maxMessagesBeforeCompression:50,enableSmartCompression:!0,enableSemanticAnalysis:!0,enableAnchorSystem:!0,driftCorrectionThreshold:.25,maxContextLength:100,compressionRatioTarget:.7}});var Lp={};B(Lp,{getGitDiff:()=>Os,getGitStatus:()=>Fs,gitAddAll:()=>cc,gitCommit:()=>lc,hasUncommittedChanges:()=>Ns,isGitAvailable:()=>zf});import{execSync as rn}from"child_process";import{existsSync as Ap,writeFileSync as Wf,unlinkSync as Bf}from"fs";import{join as Rp}from"path";import{tmpdir as Hf}from"os";function zf(){try{let s=Rp(process.cwd(),".git");return Ap(s)?(rn("git --version",{stdio:"ignore"}),C("Git is available"),!0):(C("Git not available: .git directory not found"),!1)}catch(s){return C(`Git not available: ${s.message}`),!1}}function Fs(){try{return rn("git status",{encoding:"utf-8"})}catch(s){return oe(`Failed to get git status: ${s.message}`),""}}function Os(){try{let s=rn("git diff --cached",{encoding:"utf-8"}),e=rn("git diff",{encoding:"utf-8"}),t="";return s&&(t+=`=== Staged Changes ===
2098
+ `+s+`
1356
2099
  `),e&&(t+=`=== Unstaged Changes ===
1357
- `+e),t||"No changes detected"}catch(o){return G(`Failed to get git diff: ${o.message}`),""}}function Ws(){try{ct("git add .",{stdio:"inherit"})}catch(o){throw new Error(`Failed to stage changes: ${o.message}`)}}function Vs(o){let e=Tc(jg(),`git-commit-${Date.now()}.txt`);try{Fg(e,o,"utf-8"),ct(`git commit -F "${e}"`,{stdio:"inherit"})}catch(t){throw new Error(`Failed to commit: ${t.message}`)}finally{try{bc(e)&&Og(e)}catch(t){G(`Failed to cleanup temporary file: ${t.message}`)}}}function ir(){try{return ct("git status --porcelain",{encoding:"utf-8"}).trim().length>0}catch(o){return G(`Failed to check for uncommitted changes: ${o.message}`),!1}}var so=C(()=>{Y()});var Hs={};j(Hs,{FileChangeTracker:()=>Be,createFileChangeTracker:()=>io,detectFileChanges:()=>co,generateChangeSummary:()=>lo,getCurrentSessionFileChanges:()=>mo,getFileChangeTracker:()=>ue,getSessionFileChanges:()=>po,handleGitCommit:()=>go,recordFileChange:()=>uo,resetFileChangeTracker:()=>ao});import{execSync as zs}from"child_process";function ue(o){return Bt||(Bt=new Be(o)),Bt}function io(o){return new Be(o)}function ao(){Bt&&(Bt.stopWatching(),Bt=null)}async function co(o,e){return ue(e).detectFileChanges(o)}function lo(o="text"){return ue().generateChangeSummaryText(o)}function uo(o){let e={id:Ze(),filePath:o.filePath,changeType:o.changeType,timestamp:new Date().toISOString(),source:o.source||"manual",content:o.content,size:o.size};return ue().trackSessionFileChange("default-session",void 0,[e]),e}async function go(o){return ue().handleGitCommit(o)}function po(o){return ue().getSessionFileChanges(o)}function mo(){return ue().getCurrentSessionFileChanges()}var Ng,Be,Bt,lt=C(()=>{Dr();so();Ng={maxCommitHistory:50,enableGitIntegration:!0,trackSessionChanges:!0,autoDetectChanges:!0,excludePatterns:["node_modules",".git","dist","build","*.log",".DS_Store","*.tmp","*.temp"],maxFileSize:1024*1024,enableFileHashing:!0,gitStatusCheckInterval:5e3,maxContentLength:1e3,maxHistoryEntries:100,enableRealTimeMonitoring:!1,sessionTimeoutMinutes:60,enableChangeNotifications:!1,logLevel:"info"},Be=class{config;sessionChanges=new Map;commitHistory=[];gitStatusCache=new Map;changeCallbacks=[];isWatching=!1;gitStatusTimer;constructor(e){this.config={...Ng,...e}}async detectFileChanges(e){try{let t=[];if(this.config.enableGitIntegration){let s=await this.detectGitChanges();t.push(...s)}let n=await this.detectFilesystemChanges();t.push(...n);let r={hasChanges:t.length>0,changes:t,summary:this.generateChangeSummary(t)};return t.length>0&&this.triggerChangeCallbacks(t),r}catch(t){return console.error("\u68C0\u6D4B\u6587\u4EF6\u53D8\u66F4\u65F6\u51FA\u9519:",t),{hasChanges:!1,changes:[],summary:{totalFiles:0,addedFiles:0,modifiedFiles:0,deletedFiles:0,renamedFiles:0,totalSize:0}}}}async detectGitChanges(){let e=[];try{if(!ir())return e;let t=or(),n=sr(),r=this.parseGitStatus(t),s=this.getCurrentGitHash(),i=this.getCurrentBranch(),a=new Date().toISOString();for(let c of r){let l;switch(c.status){case"A":l="added";break;case"M":l="modified";break;case"D":l="deleted";break;case"R":l="renamed";break;default:continue}let u={id:Ze(),filePath:c.filePath,changeType:l,timestamp:a,source:"git-status",diff:this.config.enableFileHashing?n:void 0,commitHash:s,branch:i,checksum:this.config.enableFileHashing?await this.generateFileChecksum(c.filePath):void 0};e.push(u),this.gitStatusCache.set(c.filePath,c.status)}}catch(t){console.error("\u68C0\u6D4BGit\u53D8\u66F4\u65F6\u51FA\u9519:",t)}return e}parseGitStatus(e){let t=[];try{let n=zs("git status --porcelain",{encoding:"utf-8"});for(let r of n.trim().split(`
1358
- `))if(r.length>=3){let s=r.substring(0,2).trim(),i=r.substring(3).trim();t.push({filePath:i,status:s})}}catch(n){console.warn("\u89E3\u6790Git\u72B6\u6001\u5931\u8D25:",n)}return t}getCurrentGitHash(){try{return zs("git rev-parse HEAD",{encoding:"utf-8"}).trim()}catch{return"unknown"}}getCurrentBranch(){try{return zs("git rev-parse --abbrev-ref HEAD",{encoding:"utf-8"}).trim()}catch{return"unknown"}}async detectFilesystemChanges(){return[]}generateChangeSummary(e){let t={totalFiles:e.length,addedFiles:0,modifiedFiles:0,deletedFiles:0,renamedFiles:0,totalSize:0};for(let n of e){switch(n.changeType){case"added":t.addedFiles++;break;case"modified":t.modifiedFiles++;break;case"deleted":t.deletedFiles++;break;case"renamed":t.renamedFiles++;break}n.size&&(t.totalSize+=n.size)}return t}async generateFileChecksum(e){try{return`sha256:${e}:${Date.now()}`}catch(t){return console.error("\u751F\u6210\u6587\u4EF6\u6821\u9A8C\u548C\u65F6\u51FA\u9519:",t),""}}triggerChangeCallbacks(e){for(let t of this.changeCallbacks)try{t(e)}catch(n){console.error("\u6267\u884C\u53D8\u66F4\u56DE\u8C03\u65F6\u51FA\u9519:",n)}}trackSessionFileChange(e,t,n){if(!this.config.trackSessionChanges)return;let r=this.sessionChanges.get(e),s=new Date().toISOString();if(r){let i=[...r.changes];for(let a of n){let c=i.findIndex(l=>l.filePath===a.filePath&&l.changeType===a.changeType);c>=0?i[c]=a:i.push(a)}r.changes=i,r.updatedAt=s,r.totalFiles=i.length,r.totalSize=i.reduce((a,c)=>a+(c.size||0),0)}else this.sessionChanges.set(e,{sessionId:e,taskId:t,changes:[...n],committed:!1,createdAt:s,updatedAt:s,totalFiles:n.length,totalSize:n.reduce((i,a)=>i+(a.size||0),0)})}getSessionFileChanges(e){return this.sessionChanges.get(e)}getAllSessionFileChanges(){return new Map(this.sessionChanges)}getCurrentSessionFileChanges(){let e,t="";for(let n of this.sessionChanges.values())n.updatedAt>t&&(t=n.updatedAt,e=n);return e}async handleGitCommit(e){if(!this.config.enableGitIntegration)return null;try{let t={hash:e.hash||this.getCurrentGitHash(),message:e.commitMessage,author:e.author||"Unknown",timestamp:new Date().toISOString(),branch:e.branch||this.getCurrentBranch(),files:[]};return this.commitHistory.unshift(t),this.commitHistory.length>this.config.maxCommitHistory&&(this.commitHistory=this.commitHistory.slice(0,this.config.maxCommitHistory)),this.markSessionChangesAsCommitted(t),t}catch(t){return console.error("\u5904\u7406Git\u63D0\u4EA4\u4E8B\u4EF6\u65F6\u51FA\u9519:",t),null}}markSessionChangesAsCommitted(e){for(let t of this.sessionChanges.values())!t.committed&&t.updatedAt>e.timestamp&&(t.committed=!0)}onChange(e){this.changeCallbacks.push(e)}removeChangeCallback(e){let t=this.changeCallbacks.indexOf(e);t>=0&&this.changeCallbacks.splice(t,1)}startWatching(){this.isWatching||(this.isWatching=!0,this.config.enableGitIntegration&&(this.gitStatusTimer=setInterval(async()=>{try{await this.detectFileChanges()}catch(e){console.error("\u76D1\u63A7Git\u72B6\u6001\u65F6\u51FA\u9519:",e)}},this.config.gitStatusCheckInterval)))}stopWatching(){this.isWatching&&(this.isWatching=!1,this.gitStatusTimer&&(clearInterval(this.gitStatusTimer),this.gitStatusTimer=void 0))}getCommitHistory(){return[...this.commitHistory]}cleanup(e=30){let t=new Date;t.setDate(t.getDate()-e);let n=t.toISOString();for(let[r,s]of this.sessionChanges.entries())s.updatedAt<n&&s.committed&&this.sessionChanges.delete(r);this.commitHistory=this.commitHistory.filter(r=>r.timestamp>n)}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e}}generateChangeSummaryText(e="text"){let t=[];for(let s of this.sessionChanges.values())t.push(...s.changes);if(e==="json")return JSON.stringify(this.generateChangeSummary(t),null,2);let n=this.generateChangeSummary(t),r=`\u{1F4CA} \u6587\u4EF6\u53D8\u52A8\u6458\u8981
2100
+ `+e),t||"No changes detected"}catch(s){return oe(`Failed to get git diff: ${s.message}`),""}}function cc(){try{rn("git add .",{stdio:"inherit"})}catch(s){throw new Error(`Failed to stage changes: ${s.message}`)}}function lc(s){let e=Rp(Hf(),`git-commit-${Date.now()}.txt`);try{Wf(e,s,"utf-8"),rn(`git commit -F "${e}"`,{stdio:"inherit"})}catch(t){throw new Error(`Failed to commit: ${t.message}`)}finally{try{Ap(e)&&Bf(e)}catch(t){oe(`Failed to cleanup temporary file: ${t.message}`)}}}function Ns(){try{return rn("git status --porcelain",{encoding:"utf-8"}).trim().length>0}catch(s){return oe(`Failed to check for uncommitted changes: ${s.message}`),!1}}var ci=S(()=>{Q()});var pc={};B(pc,{FileChangeTracker:()=>jt,createFileChangeTracker:()=>li,detectFileChanges:()=>pi,generateChangeSummary:()=>gi,getCurrentSessionFileChanges:()=>hi,getFileChangeTracker:()=>Me,getSessionFileChanges:()=>fi,handleGitCommit:()=>di,recordFileChange:()=>mi,resetFileChangeTracker:()=>ui});import{execSync as uc}from"child_process";function Me(s){return gr||(gr=new jt(s)),gr}function li(s){return new jt(s)}function ui(){gr&&(gr.stopWatching(),gr=null)}async function pi(s,e){return Me(e).detectFileChanges(s)}function gi(s="text"){return Me().generateChangeSummaryText(s)}function mi(s){let e={id:Gt(),filePath:s.filePath,changeType:s.changeType,timestamp:new Date().toISOString(),source:s.source||"manual",content:s.content,size:s.size};return Me().trackSessionFileChange("default-session",void 0,[e]),e}async function di(s){return Me().handleGitCommit(s)}function fi(s){return Me().getSessionFileChanges(s)}function hi(){return Me().getCurrentSessionFileChanges()}var Vf,jt,gr,sn=S(()=>{bo();ci();Fe();Vf={maxCommitHistory:50,enableGitIntegration:!0,trackSessionChanges:!0,autoDetectChanges:!0,excludePatterns:["node_modules",".git","dist","build","*.log",".DS_Store","*.tmp","*.temp"],maxFileSize:1024*1024,enableFileHashing:!0,gitStatusCheckInterval:5e3,maxContentLength:1e3,maxHistoryEntries:100,enableRealTimeMonitoring:!1,sessionTimeoutMinutes:60,enableChangeNotifications:!1,logLevel:"info"},jt=class{config;sessionChanges=new Map;commitHistory=[];gitStatusCache=new Map;changeCallbacks=[];isWatching=!1;gitStatusTimer;constructor(e){this.config={...Vf,...e}}async detectFileChanges(e){try{let t=[];if(this.config.enableGitIntegration){let o=await this.detectGitChanges();t.push(...o)}let n=await this.detectFilesystemChanges();t.push(...n);let r={hasChanges:t.length>0,changes:t,summary:this.generateChangeSummary(t)};return t.length>0&&this.triggerChangeCallbacks(t),r}catch(t){return console.error("\u68C0\u6D4B\u6587\u4EF6\u53D8\u66F4\u65F6\u51FA\u9519:",t),{hasChanges:!1,changes:[],summary:{totalFiles:0,addedFiles:0,modifiedFiles:0,deletedFiles:0,renamedFiles:0,totalSize:0}}}}async detectGitChanges(){let e=[];try{if(!Ns())return e;let t=Fs(),n=Os(),r=this.parseGitStatus(t),o=this.getCurrentGitHash(),i=this.getCurrentBranch(),a=new Date().toISOString();for(let c of r){let l;switch(c.status){case"A":l="added";break;case"M":l="modified";break;case"D":l="deleted";break;case"R":l="renamed";break;default:continue}let u={id:Gt(),filePath:c.filePath,changeType:l,timestamp:a,source:"git-status",diff:this.config.enableFileHashing?n:void 0,commitHash:o,branch:i,checksum:this.config.enableFileHashing?await this.generateFileChecksum(c.filePath):void 0};e.push(u),this.gitStatusCache.set(c.filePath,c.status)}}catch(t){console.error("\u68C0\u6D4BGit\u53D8\u66F4\u65F6\u51FA\u9519:",t)}return e}parseGitStatus(e){let t=[];try{let n=uc("git status --porcelain",{encoding:"utf-8"});for(let r of n.trim().split(`
2101
+ `))if(r.length>=3){let o=r.substring(0,2).trim(),i=r.substring(3).trim();t.push({filePath:i,status:o})}}catch(n){console.warn("\u89E3\u6790Git\u72B6\u6001\u5931\u8D25:",n)}return t}getCurrentGitHash(){try{return uc("git rev-parse HEAD",{encoding:"utf-8"}).trim()}catch{return"unknown"}}getCurrentBranch(){try{return uc("git rev-parse --abbrev-ref HEAD",{encoding:"utf-8"}).trim()}catch{return"unknown"}}async detectFilesystemChanges(){return[]}generateChangeSummary(e){let t={totalFiles:e.length,addedFiles:0,modifiedFiles:0,deletedFiles:0,renamedFiles:0,totalSize:0};for(let n of e){switch(n.changeType){case"added":t.addedFiles++;break;case"modified":t.modifiedFiles++;break;case"deleted":t.deletedFiles++;break;case"renamed":t.renamedFiles++;break}n.size&&(t.totalSize+=n.size)}return t}async generateFileChecksum(e){try{return`sha256:${e}:${Date.now()}`}catch(t){return console.error("\u751F\u6210\u6587\u4EF6\u6821\u9A8C\u548C\u65F6\u51FA\u9519:",t),""}}triggerChangeCallbacks(e){for(let t of this.changeCallbacks)try{t(e)}catch(n){console.error("\u6267\u884C\u53D8\u66F4\u56DE\u8C03\u65F6\u51FA\u9519:",n)}}trackSessionFileChange(e,t,n){if(!this.config.trackSessionChanges)return;let r=this.sessionChanges.get(e),o=new Date().toISOString();if(r){let i=[...r.changes];for(let a of n){let c=i.findIndex(l=>l.filePath===a.filePath&&l.changeType===a.changeType);c>=0?i[c]=a:i.push(a)}r.changes=i,r.updatedAt=o,r.totalFiles=i.length,r.totalSize=i.reduce((a,c)=>a+(c.size||0),0)}else this.sessionChanges.set(e,{sessionId:e,taskId:t,changes:[...n],committed:!1,createdAt:o,updatedAt:o,totalFiles:n.length,totalSize:n.reduce((i,a)=>i+(a.size||0),0)})}getSessionFileChanges(e){return this.sessionChanges.get(e)}getAllSessionFileChanges(){return new Map(this.sessionChanges)}getCurrentSessionFileChanges(){let e,t="";for(let n of this.sessionChanges.values())n.updatedAt>t&&(t=n.updatedAt,e=n);return e}async handleGitCommit(e){if(!this.config.enableGitIntegration)return null;try{let t={hash:e.hash||this.getCurrentGitHash(),message:e.commitMessage,author:e.author||"Unknown",timestamp:new Date().toISOString(),branch:e.branch||this.getCurrentBranch(),files:[]};return this.commitHistory.unshift(t),this.commitHistory.length>this.config.maxCommitHistory&&(this.commitHistory=this.commitHistory.slice(0,this.config.maxCommitHistory)),this.markSessionChangesAsCommitted(t),t}catch(t){return console.error("\u5904\u7406Git\u63D0\u4EA4\u4E8B\u4EF6\u65F6\u51FA\u9519:",t),null}}markSessionChangesAsCommitted(e){for(let t of this.sessionChanges.values())!t.committed&&t.updatedAt>e.timestamp&&(t.committed=!0)}onChange(e){this.changeCallbacks.push(e)}removeChangeCallback(e){let t=this.changeCallbacks.indexOf(e);t>=0&&this.changeCallbacks.splice(t,1)}startWatching(){this.isWatching||(this.isWatching=!0,this.config.enableGitIntegration&&(this.gitStatusTimer=setInterval(async()=>{try{await this.detectFileChanges()}catch(e){console.error("\u76D1\u63A7Git\u72B6\u6001\u65F6\u51FA\u9519:",e)}},this.config.gitStatusCheckInterval)))}stopWatching(){this.isWatching&&(this.isWatching=!1,this.gitStatusTimer&&(clearInterval(this.gitStatusTimer),this.gitStatusTimer=void 0))}getCommitHistory(){return[...this.commitHistory]}cleanup(e=30){let t=new Date;t.setDate(t.getDate()-e);let n=t.toISOString();for(let[r,o]of this.sessionChanges.entries())o.updatedAt<n&&o.committed&&this.sessionChanges.delete(r);this.commitHistory=this.commitHistory.filter(r=>r.timestamp>n)}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e}}generateChangeSummaryText(e="text"){let t=[];for(let o of this.sessionChanges.values())t.push(...o.changes);if(e==="json")return JSON.stringify(this.generateChangeSummary(t),null,2);let n=this.generateChangeSummary(t),r=`\u{1F4CA} \u6587\u4EF6\u53D8\u52A8\u6458\u8981
1359
2102
 
1360
2103
  `;return r+=`\u{1F4C1} \u603B\u6587\u4EF6\u6570: ${n.totalFiles}
1361
2104
  `,r+=`\u2795 \u65B0\u589E\u6587\u4EF6: ${n.addedFiles}
@@ -1364,10 +2107,10 @@ ${n.map(s=>`\u2022 ${s}`).join(`
1364
2107
  `,r+=`\u{1F504} \u91CD\u547D\u540D\u6587\u4EF6: ${n.renamedFiles}
1365
2108
  `,r+=`\u{1F4E6} \u603B\u5927\u5C0F: ${(n.totalSize/1024).toFixed(2)} KB
1366
2109
  `,r+=`
1367
- \u{1F550} \u751F\u6210\u65F6\u95F4: ${new Date().toLocaleString()}`,r}},Bt=null});function qe(o,e){if(!fo){let t=o||new Be;fo=new ho(t,e)}return fo}function Ec(o,e){return new ho(o,e)}function Pc(){fo=null}var Ug,ho,fo,ar=C(()=>{lt();Ug={promptIntegration:{enabled:!0,maxSummaryLength:500,includeFileList:!0,includeChangeDetails:!1,priority:"low"},anchorIntegration:{enabled:!0,anchorPrefix:"workspace-change-",includeAllChanges:!1},toolIntegration:{enabled:!0,maxResultsPerQuery:20},workspaceAuxiliary:{enabled:!0,role:"helper",maxContextRatio:.2}},ho=class{fileChangeTracker;config;anchors=new Map;constructor(e,t){this.fileChangeTracker=e,this.config={...Ug,...t}}generatePromptIntegrationContent(){if(!this.config.promptIntegration.enabled)return"";try{let e=this.fileChangeTracker.getCurrentSessionFileChanges();if(!e||e.changes.length===0)return"";let t=`\u{1F4A1} \u5DE5\u4F5C\u533A\u6587\u4EF6\u53D8\u66F4\u4FE1\u606F\uFF08\u4EC5\u4F5C\u8F85\u52A9\u53C2\u8003\uFF09\uFF1A
2110
+ \u{1F550} \u751F\u6210\u65F6\u95F4: ${H()}`,r}},gr=null});import{Document as Gf}from"flexsearch";function jp(){return gc||(gc=new mc),gc}var mc,gc,Dp=S(()=>{mc=class{index;changesMap;isIndexed;constructor(e){this.changesMap=new Map,this.isIndexed=!1,this.index=new Gf({document:{id:"id",index:["filePath","changeType","diff","source","commitMessage"],store:!0},tokenize:"forward",resolution:9,context:!0})}async buildIndex(e){this.changesMap.clear();for(let t of e)await this.addChange(t);this.isIndexed=!0}async addChange(e){this.changesMap.set(e.id,e);let t={id:e.id,filePath:e.filePath,changeType:e.changeType,diff:e.diff||"",source:e.source||"",commitMessage:""};await this.index.addAsync(e.id,t)}async removeChange(e){this.changesMap.delete(e),await this.index.removeAsync(e)}async search(e,t=10){if(!this.isIndexed||this.changesMap.size===0)return[];try{let n=await this.index.searchAsync(e,{limit:t*2,enrich:!0}),r=[],o=new Set;for(let i of n)if(!(!i||!i.result))for(let a of i.result){let c=a.id;if(o.has(c))continue;o.add(c);let l=this.changesMap.get(c);l&&r.push({change:l,score:this.calculateRelevanceScore(l,e),matchedFields:[i.field]})}return r.sort((i,a)=>a.score-i.score),r.slice(0,t)}catch(n){return console.error("\u641C\u7D22\u6587\u4EF6\u53D8\u66F4\u65F6\u51FA\u9519:",n),[]}}calculateRelevanceScore(e,t){let n=0,r=t.toLowerCase();if(e.filePath.toLowerCase().includes(r)&&(n+=100,(e.filePath.split(/[\\/]/).pop()||"").toLowerCase().includes(r)&&(n+=50)),e.changeType.toLowerCase().includes(r)&&(n+=80),e.diff){let u=(e.diff.toLowerCase().match(new RegExp(r,"g"))||[]).length;n+=Math.min(u*10,50)}e.source&&e.source.toLowerCase().includes(r)&&(n+=30);let i=Date.now(),a=new Date(e.timestamp).getTime(),c=(i-a)/(1e3*60*60);return c<1?n+=20:c<24?n+=10:c<168&&(n+=5),Math.max(0,n)}getStats(){return{totalChanges:this.changesMap.size,isIndexed:this.isIndexed}}clear(){this.changesMap.clear(),this.isIndexed=!1}},gc=null});function Dt(s,e){if(!yi){let t=s||new jt;yi=new xi(t,e)}return yi}function Fp(s,e){return new xi(s,e)}function Op(){yi=null}var qf,xi,yi,_s=S(()=>{sn();Dp();qf={promptIntegration:{enabled:!0,maxSummaryLength:500,includeFileList:!0,includeChangeDetails:!1,priority:"low"},anchorIntegration:{enabled:!0,anchorPrefix:"workspace-change-",includeAllChanges:!1},toolIntegration:{enabled:!0,maxResultsPerQuery:20},workspaceAuxiliary:{enabled:!0,role:"helper",maxContextRatio:.2}},xi=class{fileChangeTracker;config;anchors=new Map;searchManager;constructor(e,t){this.fileChangeTracker=e,this.config={...qf,...t},this.searchManager=jp(),this.rebuildSearchIndex()}generatePromptIntegrationContent(){if(!this.config.promptIntegration.enabled)return"";try{let e=this.fileChangeTracker.getCurrentSessionFileChanges();if(!e||e.changes.length===0)return"";let t=`\u{1F4A1} \u5DE5\u4F5C\u533A\u6587\u4EF6\u53D8\u66F4\u4FE1\u606F\uFF08\u4EC5\u4F5C\u8F85\u52A9\u53C2\u8003\uFF09\uFF1A
1368
2111
 
1369
- `,n=this.config.promptIntegration.maxSummaryLength-t.length,s=this.fileChangeTracker.generateChangeSummaryText("text").split(`
1370
- `),i="";for(let a of s)if(i.length+a.length<n)i+=a+`
2112
+ `,n=this.config.promptIntegration.maxSummaryLength-t.length,o=this.fileChangeTracker.generateChangeSummaryText("text").split(`
2113
+ `),i="";for(let a of o)if(i.length+a.length<n)i+=a+`
1371
2114
  `;else break;if(t+=i+`
1372
2115
  `,n=this.config.promptIntegration.maxSummaryLength-t.length,this.config.promptIntegration.includeFileList&&n>50){t+=`\u{1F4CB} \u53D8\u66F4\u6587\u4EF6\u5217\u8868\uFF1A
1373
2116
  `;let a=e.changes.map(c=>` - ${c.changeType==="added"?"\u2795":c.changeType==="modified"?"\u270F\uFE0F":c.changeType==="deleted"?"\u{1F5D1}\uFE0F":"\u{1F504}"} ${c.filePath}`);for(let c of a)if(t.length+c.length<this.config.promptIntegration.maxSummaryLength)t+=c+`
@@ -1375,22 +2118,71 @@ ${n.map(s=>`\u2022 ${s}`).join(`
1375
2118
  `;break}t+=`
1376
2119
  `}return this.config.promptIntegration.includeChangeDetails&&n>100&&(t+=`\u{1F4DD} \u53D8\u66F4\u8BE6\u60C5\u9884\u89C8\uFF1A
1377
2120
  `),t+=`\u26A0\uFE0F \u4EE5\u4E0A\u5DE5\u4F5C\u533A\u4FE1\u606F\u4EC5\u4F5C\u4E3A\u8F85\u52A9\u53C2\u8003\uFF0C\u60A8\u5E94\u4E13\u6CE8\u4E8E\u89E3\u51B3\u5F53\u524D\u4E3B\u8981\u4EFB\u52A1\u3002
1378
- `,t}catch(e){return console.error("\u751F\u6210\u63D0\u793A\u8BCD\u96C6\u6210\u5185\u5BB9\u65F6\u51FA\u9519:",e),""}}generateChangeAnchors(){if(!this.config.anchorIntegration.enabled)return new Map;try{let e=new Map,t=this.fileChangeTracker.getCurrentSessionFileChanges();if(t&&t.changes.length>0)for(let n of t.changes){let r=`${this.config.anchorIntegration.anchorPrefix}${n.id}`;e.set(r,n.filePath),this.anchors.set(r,n.id)}return e}catch(e){return console.error("\u751F\u6210\u53D8\u66F4\u951A\u70B9\u65F6\u51FA\u9519:",e),new Map}}getChangeByAnchor(e){let t=this.anchors.get(e);if(!t)return;let n=this.fileChangeTracker.getCurrentSessionFileChanges();if(n)return n.changes.find(r=>r.id===t)}async searchFileChanges(e){if(!this.config.toolIntegration.enabled)return[];try{let t=this.fileChangeTracker.getCurrentSessionFileChanges();if(!t||t.changes.length===0)return[];let n=[...t.changes];e.filter&&(n=this.applyFilter(n,e.filter)),e.sortBy&&(n=this.applySort(n,e.sortBy,e.sortOrder||"desc"));let r=e.limit||this.config.toolIntegration.maxResultsPerQuery,s=e.offset||0;return n=n.slice(s,s+r),e.includeContent,n}catch(t){return console.error("\u641C\u7D22\u6587\u4EF6\u53D8\u66F4\u65F6\u51FA\u9519:",t),[]}}getChangeSummary(){try{let e=this.fileChangeTracker.getCurrentSessionFileChanges();return!e||e.changes.length===0?{totalFiles:0,addedFiles:0,modifiedFiles:0,deletedFiles:0,renamedFiles:0,totalSize:0}:{totalFiles:e.changes.length,addedFiles:e.changes.filter(n=>n.changeType==="added").length,modifiedFiles:e.changes.filter(n=>n.changeType==="modified").length,deletedFiles:e.changes.filter(n=>n.changeType==="deleted").length,renamedFiles:e.changes.filter(n=>n.changeType==="renamed").length,totalSize:e.changes.reduce((n,r)=>n+(r.size||0),0)}}catch(e){return console.error("\u83B7\u53D6\u53D8\u66F4\u6458\u8981\u65F6\u51FA\u9519:",e),{totalFiles:0,addedFiles:0,modifiedFiles:0,deletedFiles:0,renamedFiles:0,totalSize:0}}}applyFilter(e,t){return e.filter(n=>{if(t.changeTypes&&t.changeTypes.length>0&&!t.changeTypes.includes(n.changeType)||t.filePatterns&&t.filePatterns.length>0&&!t.filePatterns.some(s=>new RegExp(s.replace(/\*/g,".*").replace(/\?/g,".")).test(n.filePath)))return!1;if(t.dateRange){let r=new Date(n.timestamp),s=new Date(t.dateRange.start),i=new Date(t.dateRange.end);if(r<s||r>i)return!1}return!(t.author&&n.author!==t.author||t.branch&&n.branch!==t.branch||t.minFileSize&&(n.size||0)<t.minFileSize||t.maxFileSize&&(n.size||0)>t.maxFileSize||t.sessionId&&n.sessionId!==t.sessionId||t.taskId&&n.taskId!==t.taskId)})}applySort(e,t,n){return[...e].sort((r,s)=>{let i,a;switch(t){case"timestamp":i=new Date(r.timestamp).getTime(),a=new Date(s.timestamp).getTime();break;case"filePath":i=r.filePath,a=s.filePath;break;case"size":i=r.size||0,a=s.size||0;break;case"type":i=r.changeType,a=s.changeType;break;default:i=new Date(r.timestamp).getTime(),a=new Date(s.timestamp).getTime()}return i<a?n==="asc"?-1:1:i>a?n==="asc"?1:-1:0})}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}shouldIncludeWorkspaceContext(e){return!!this.config.workspaceAuxiliary.enabled}getMaxWorkspaceContextLength(e){return this.config.workspaceAuxiliary.enabled?Math.floor(e*this.config.workspaceAuxiliary.maxContextRatio):0}},fo=null});var Js={};j(Js,{AnchorInjector:()=>ut,createAnchorInjector:()=>$c});function $c(o,e){return new ut(o,e)}var ut,cr=C(()=>{Os();js();Us();Y();ar();lt();ut=class{anchorManager;semanticAnalyzer;contextConfig;constructor(e,t){this.anchorManager=new nr(e),this.semanticAnalyzer=new rr(t),this.contextConfig=oo()}async injectAnchors(e){let{taskDescription:t,iterations:n,messages:r,lastSemanticCheckIteration:s,session:i,logWarning:a}=e,c=s,l=[...r];if(this.contextConfig.enableAnchorSystem)try{let u=ue(),p=qe(u);await u.detectFileChanges();let g=p.generateChangeAnchors();if(g.size>0){let m={role:"system",content:`\u{1F4A1} \u5DE5\u4F5C\u533A\u6587\u4EF6\u53D8\u66F4\u951A\u70B9\uFF08\u4EC5\u4F5C\u8F85\u52A9\u53C2\u8003\uFF09\uFF1A
1379
- ${Array.from(g.entries()).map(([w,v])=>`${w}: ${v}`).join(`
2121
+ `,t}catch(e){return console.error("\u751F\u6210\u63D0\u793A\u8BCD\u96C6\u6210\u5185\u5BB9\u65F6\u51FA\u9519:",e),""}}generateChangeAnchors(){if(!this.config.anchorIntegration.enabled)return new Map;try{let e=new Map,t=this.fileChangeTracker.getCurrentSessionFileChanges();if(t&&t.changes.length>0)for(let n of t.changes){let r=`${this.config.anchorIntegration.anchorPrefix}${n.id}`;e.set(r,n.filePath),this.anchors.set(r,n.id)}return e}catch(e){return console.error("\u751F\u6210\u53D8\u66F4\u951A\u70B9\u65F6\u51FA\u9519:",e),new Map}}getChangeByAnchor(e){let t=this.anchors.get(e);if(!t)return;let n=this.fileChangeTracker.getCurrentSessionFileChanges();if(n)return n.changes.find(r=>r.id===t)}async searchFileChanges(e){if(!this.config.toolIntegration.enabled)return[];try{let t=this.fileChangeTracker.getCurrentSessionFileChanges();if(!t||t.changes.length===0)return[];if(e.query&&e.query.trim()){let a=(await this.searchManager.search(e.query,e.limit||this.config.toolIntegration.maxResultsPerQuery)).map(l=>l.change);e.filter&&(a=this.applyFilter(a,e.filter)),e.sortBy&&(a=this.applySort(a,e.sortBy,e.sortOrder||"desc"));let c=e.offset||0;return a=a.slice(c),a}let n=[...t.changes];e.filter&&(n=this.applyFilter(n,e.filter)),e.sortBy&&(n=this.applySort(n,e.sortBy,e.sortOrder||"desc"));let r=e.limit||this.config.toolIntegration.maxResultsPerQuery,o=e.offset||0;return n=n.slice(o,o+r),n}catch(t){return console.error("\u641C\u7D22\u6587\u4EF6\u53D8\u66F4\u65F6\u51FA\u9519:",t),[]}}getChangeSummary(){try{let e=this.fileChangeTracker.getCurrentSessionFileChanges();return!e||e.changes.length===0?{totalFiles:0,addedFiles:0,modifiedFiles:0,deletedFiles:0,renamedFiles:0,totalSize:0}:{totalFiles:e.changes.length,addedFiles:e.changes.filter(n=>n.changeType==="added").length,modifiedFiles:e.changes.filter(n=>n.changeType==="modified").length,deletedFiles:e.changes.filter(n=>n.changeType==="deleted").length,renamedFiles:e.changes.filter(n=>n.changeType==="renamed").length,totalSize:e.changes.reduce((n,r)=>n+(r.size||0),0)}}catch(e){return console.error("\u83B7\u53D6\u53D8\u66F4\u6458\u8981\u65F6\u51FA\u9519:",e),{totalFiles:0,addedFiles:0,modifiedFiles:0,deletedFiles:0,renamedFiles:0,totalSize:0}}}async rebuildSearchIndex(){try{let e=this.fileChangeTracker.getCurrentSessionFileChanges();e&&e.changes.length>0&&await this.searchManager.buildIndex(e.changes)}catch(e){console.error("\u91CD\u5EFA\u641C\u7D22\u7D22\u5F15\u65F6\u51FA\u9519:",e)}}applyFilter(e,t){return e.filter(n=>{if(t.changeTypes&&t.changeTypes.length>0&&!t.changeTypes.includes(n.changeType)||t.filePatterns&&t.filePatterns.length>0&&!t.filePatterns.some(o=>new RegExp(o.replace(/\*/g,".*").replace(/\?/g,".")).test(n.filePath)))return!1;if(t.dateRange){let r=new Date(n.timestamp),o=new Date(t.dateRange.start),i=new Date(t.dateRange.end);if(r<o||r>i)return!1}return!(t.author&&n.author!==t.author||t.branch&&n.branch!==t.branch||t.minFileSize&&(n.size||0)<t.minFileSize||t.maxFileSize&&(n.size||0)>t.maxFileSize||t.sessionId&&n.sessionId!==t.sessionId||t.taskId&&n.taskId!==t.taskId)})}applySort(e,t,n){return[...e].sort((r,o)=>{let i,a;switch(t){case"timestamp":i=new Date(r.timestamp).getTime(),a=new Date(o.timestamp).getTime();break;case"filePath":i=r.filePath,a=o.filePath;break;case"size":i=r.size||0,a=o.size||0;break;case"type":i=r.changeType,a=o.changeType;break;default:i=new Date(r.timestamp).getTime(),a=new Date(o.timestamp).getTime()}return i<a?n==="asc"?-1:1:i>a?n==="asc"?1:-1:0})}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}shouldIncludeWorkspaceContext(e){return!!this.config.workspaceAuxiliary.enabled}getMaxWorkspaceContextLength(e){return this.config.workspaceAuxiliary.enabled?Math.floor(e*this.config.workspaceAuxiliary.maxContextRatio):0}},yi=null});var dc={};B(dc,{AnchorInjector:()=>on,createAnchorInjector:()=>Np});function Np(s,e){return new on(s,e)}var on,Us=S(()=>{rc();sc();ac();Q();_s();sn();on=class{anchorManager;semanticAnalyzer;contextConfig;constructor(e,t){this.anchorManager=new js(e),this.semanticAnalyzer=new Ds(t),this.contextConfig=ai()}async injectAnchors(e){let{taskDescription:t,iterations:n,messages:r,lastSemanticCheckIteration:o,session:i,logWarning:a}=e,c=o,l=[...r];if(this.contextConfig.enableAnchorSystem)try{let u=Me(),p=Dt(u);await u.detectFileChanges();let g=p.generateChangeAnchors();if(g.size>0){let d={role:"system",content:`\u{1F4A1} \u5DE5\u4F5C\u533A\u6587\u4EF6\u53D8\u66F4\u951A\u70B9\uFF08\u4EC5\u4F5C\u8F85\u52A9\u53C2\u8003\uFF09\uFF1A
2122
+ ${Array.from(g.entries()).map(([y,w])=>`${y}: ${w}`).join(`
1380
2123
  `)}
1381
2124
 
1382
- \u26A0\uFE0F \u4EE5\u4E0A\u951A\u70B9\u4FE1\u606F\u4EC5\u4F5C\u4E3A\u8F85\u52A9\u53C2\u8003\uFF0C\u60A8\u5E94\u4E13\u6CE8\u4E8E\u89E3\u51B3\u5F53\u524D\u4E3B\u8981\u4EFB\u52A1\u3002`},h=l.findIndex(w=>w.role==="system");h!==-1&&l.splice(h+1,0,m),x(`\u5DF2\u6CE8\u5165 ${g.size} \u4E2A\u6587\u4EF6\u53D8\u66F4\u951A\u70B9`)}}catch(u){x(`\u751F\u6210\u6587\u4EF6\u53D8\u66F4\u951A\u70B9\u65F6\u51FA\u9519: ${u}`)}if(this.contextConfig.enableSemanticAnalysis&&n-c>=this.contextConfig.semanticCheckInterval)try{let u=l.map(g=>g.content).filter(Boolean).join(`
1383
- `),p=await this.semanticAnalyzer.analyzeSemanticDrift(t||this.anchorManager.getOriginalQuestion(),u,n);if(x(`\u8BED\u4E49\u5206\u6790 - \u76F8\u4F3C\u5EA6: ${p.similarityScore.toFixed(2)}, \u504F\u79BB\u7EA7\u522B: ${p.driftLevel}`),p.driftLevel==="severe"||p.driftLevel==="moderate"&&p.similarityScore<this.contextConfig.similarityThreshold){let g=`\u26A0\uFE0F \u68C0\u6D4B\u5230${p.driftLevel==="severe"?"\u4E25\u91CD":"\u4E2D\u5EA6"}\u504F\u79BB\uFF0C\u6B63\u5728\u7EA0\u6B63...`;a?a(g,i):x(g);let d=`\u68C0\u6D4B\u5230${p.driftLevel}\u504F\u79BB\uFF1A${p.deviationFactors.join("; ")}`,m=await this.anchorManager.createAnchorMessage(n,p.similarityScore,p.driftLevel,d,u);x(`\u{1F3AF} \u6CE8\u5165\u504F\u79BB\u7EA0\u6B63\u951A\u70B9\uFF08\u8FED\u4EE3 ${n}\uFF0C\u504F\u79BB\u7EA7\u522B: ${p.driftLevel}\uFF0C\u4F18\u5148\u7EA7: ${m.metadata?.priority}}`),l.push(m)}c=n}catch(u){G(`\u8BED\u4E49\u5206\u6790\u5931\u8D25: ${u.message}`)}if(this.contextConfig.enableAnchorSystem&&n%this.contextConfig.anchorInjectionInterval===0)try{let u=l.map(g=>g.content).filter(Boolean).join(`
1384
- `),p=await this.anchorManager.calculateSemanticSimilarity(u);if(await this.anchorManager.shouldInjectAnchor(n,p,u)){let g=await this.anchorManager.createAnchorMessage(n,p,void 0,void 0,u);x(`\u{1F3AF} \u6CE8\u5165\u4E0A\u4E0B\u6587\u951A\u70B9\uFF08\u8FED\u4EE3 ${n}\uFF0C\u76F8\u4F3C\u5EA6: ${p.toFixed(2)}\uFF0C\u4F18\u5148\u7EA7: ${g.metadata?.priority}}`),l.push(g)}}catch(u){G(`\u951A\u70B9\u6CE8\u5165\u5931\u8D25: ${u.message}`)}return{messages:l,lastSemanticCheckIteration:c}}}});var Gs=C(()=>{vc();Os();js();cr()});var Mc={};j(Mc,{GradleBuildParser:()=>lr,JavaDependencyAnalyzer:()=>So,MavenPomParser:()=>xo,analyzeJavaProject:()=>qs});import{readFileSync as yo,existsSync as Co}from"fs";import{resolve as Bs}from"path";import{parseString as Wg}from"xml2js";async function qs(o=process.cwd()){let e=Bs(o,"pom.xml"),t=Bs(o,"build.gradle"),n=Bs(o,"build.gradle.kts"),r=null;try{if(Co(e)){let i=yo(e,"utf-8");r=await new xo(i,e).parse()}else if(Co(t)){let i=yo(t,"utf-8");r=new lr(i,t).parse()}else if(Co(n)){let i=yo(n,"utf-8");r=new lr(i,n).parse()}if(!r)return null;let s={project:r,conflicts:[],outdated:[],unused:[],recommendations:[]};return s.recommendations=So.generateRecommendations(s),s}catch(s){return console.error("Error analyzing Java project:",s),null}}var xo,lr,So,Ks=C(()=>{xo=class{content;filePath;constructor(e,t){this.content=e,this.filePath=t}async parse(){try{return new Promise((e,t)=>{Wg(this.content,{explicitArray:!1},(n,r)=>{if(n){t(n);return}try{let{project:s}=r;if(!s){e(null);return}let i={name:s.artifactId||s.name||"unknown",version:s.version||"0.0.0",description:s.description||"",groupId:s.groupId||s.parent?.groupId,artifactId:s.artifactId,packaging:s.packaging||"jar",javaVersion:this.extractJavaVersion(s),buildToolVersion:this.extractMavenVersion(),parent:s.parent?{groupId:s.parent.groupId,artifactId:s.parent.artifactId,version:s.parent.version}:void 0,dependencies:this.extractDependencies(s.dependencies?.dependency),dependencyManagement:this.extractDependencies(s.dependencyManagement?.dependencies?.dependency),properties:this.extractProperties(s.properties),modules:s.modules?.module?Array.isArray(s.modules.module)?s.modules.module:[s.modules.module]:void 0,repositories:this.extractRepositories(s.repositories?.repository)};e(i)}catch(s){t(s)}})})}catch(e){return console.error("Error parsing POM XML:",e),null}}extractJavaVersion(e){return e.properties?.["java.version"]||e.properties?.["maven.compiler.source"]||e.properties?.["maven.compiler.target"]||e.build?.plugins?.plugin?.find(n=>n.artifactId==="maven-compiler-plugin")?.configuration?.source}extractMavenVersion(){let e=this.content.match(/modelVersion>([^<]+)</);return e?e[1]:void 0}extractDependencies(e){return e?(Array.isArray(e)?e:[e]).map(n=>({groupId:n.groupId,artifactId:n.artifactId,version:n.version||"unknown",scope:n.scope||"compile",type:n.type||"jar",classifier:n.classifier,optional:n.optional==="true",exclusions:n.exclusions?.exclusion?(Array.isArray(n.exclusions.exclusion)?n.exclusions.exclusion:[n.exclusions.exclusion]).map(r=>({groupId:r.groupId,artifactId:r.artifactId})):void 0})):[]}extractProperties(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{n!=="$"&&(t[n]=e[n])}),t}extractRepositories(e){return e?(Array.isArray(e)?e:[e]).map(n=>n.url).filter(Boolean):[]}},lr=class{content;filePath;constructor(e,t){this.content=e,this.filePath=t}parse(){try{let e=this.filePath.endsWith(".kts");return{name:this.extractProjectName(),version:this.extractVersion(),description:this.extractDescription(),groupId:this.extractGroup(),artifactId:this.extractProjectName(),javaVersion:this.extractJavaVersion(),buildToolVersion:this.extractGradleVersion(),dependencies:this.extractDependencies(e),dependencyManagement:[],properties:this.extractProperties(e)}}catch(e){return console.error("Error parsing Gradle build file:",e),null}}extractProjectName(){let e=this.content.match(/rootProject\.name\s*=\s*['"]([^'"]+)['"]/)||this.content.match(/project\(['"]([^'"]+)['"]\)/)||this.content.match(/name\s*=\s*['"]([^'"]+)['"]/);if(e)return e[1];let t=this.filePath.split(/[/\\]/);return t[t.length-2]||"unknown"}extractVersion(){let e=this.content.match(/version\s*=\s*['"]([^'"]+)['"]/);return e?e[1]:"0.0.0"}extractDescription(){let e=this.content.match(/description\s*=\s*['"]([^'"]+)['"]/);return e?e[1]:""}extractGroup(){let e=this.content.match(/group\s*=\s*['"]([^'"]+)['"]/);return e?e[1]:""}extractJavaVersion(){let e=this.content.match(/sourceCompatibility\s*=\s*['"]?([^'"\s]+)['"]?/)||this.content.match(/targetCompatibility\s*=\s*['"]?([^'"\s]+)['"]?/)||this.content.match(/java\.toolchain\.languageVersion\s*=\s*JavaLanguageVersion\.of\((\d+)\)/);return e?e[1]:void 0}extractGradleVersion(){let e=this.filePath.replace(/build\.gradle(\.kts)?$/,"gradle/wrapper/gradle-wrapper.properties");if(Co(e))try{let n=yo(e,"utf-8").match(/distributionUrl=.*gradle-(\d+\.\d+(?:\.\d+)?)-/);if(n)return n[1]}catch{}}extractDependencies(e){let t=[];return[/(implementation|compile|api|compileOnly|runtimeOnly|testImplementation)\s*['"]([^:'"]+):([^:'"]+):([^:'"]+)['"]/g,/(implementation|compile|api|compileOnly|runtimeOnly|testImplementation)\s*['"]([^:'"]+):([^:'"]+)['"]/g,/(implementation|compile|api|compileOnly|runtimeOnly|testImplementation)\s*\(\s*group\s*:\s*['"]([^'"]+)['"],\s*name\s*:\s*['"]([^'"]+)['"],\s*version\s*:\s*['"]([^'"]+)['"]\s*\)/g,/(implementation|compile|api|compileOnly|runtimeOnly|testImplementation)\s*\(\s*group\s*:\s*['"]([^'"]+)['"],\s*name\s*:\s*['"]([^'"]+)['"]\s*\)/g,/(implementation|compile|api|compileOnly|runtimeOnly|testImplementation)\s*\(\s*["']([^"']+):([^"']+):([^"']+)["']\s*\)/g,/(implementation|compile|api|compileOnly|runtimeOnly|testImplementation)\s*\(\s*["']([^"']+):([^"']+)["']\s*\)/g].forEach(r=>{let s;for(;(s=r.exec(this.content))!==null;){let i,a,c,l;if(s.length===5)[,i,a,c,l]=s;else if(s.length===4)[,i,a,c]=s,l="managed";else continue;t.push({groupId:a,artifactId:c,version:l,scope:i.toLowerCase(),type:"jar"})}}),t}extractProperties(e){let t={},n=e?/val\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g:/(\w+)\s*=\s*['"]([^'"]+)['"]/g,r;for(;(r=n.exec(this.content))!==null;)t[r[1]]=r[2];return t}},So=class{static analyzeConflicts(e){let t=new Map,n=new Map;e.forEach(s=>{s.dependencies.forEach(i=>{let a=`${i.groupId}:${i.artifactId}`;t.has(a)||(t.set(a,new Set),n.set(a,[])),t.get(a).add(i.version),n.get(a).push(`${s.name} (${i.scope})`)})});let r=[];return t.forEach((s,i)=>{if(s.size>1){let[a,c]=i.split(":"),l=Array.from(s);r.push({groupId:a,artifactId:c,versions:l,locations:n.get(i)||[],severity:this.calculateConflictSeverity(l)})}}),r}static calculateConflictSeverity(e){let t=e.map(r=>r.split(".")[0]).filter(r=>/^\d+$/.test(r));return new Set(t).size>1?"high":e.length>2?"medium":"low"}static generateRecommendations(e){let t=[];return e.conflicts.length>0&&t.push(`\u53D1\u73B0 ${e.conflicts.length} \u4E2A\u4F9D\u8D56\u51B2\u7A81\uFF0C\u5EFA\u8BAE\u7EDF\u4E00\u7248\u672C\u7BA1\u7406`),e.outdated.length>0&&t.push(`${e.outdated.length} \u4E2A\u4F9D\u8D56\u5B58\u5728\u66F4\u65B0\u7248\u672C`),e.unused.length>0&&t.push(`${e.unused.length} \u4E2A\u4F9D\u8D56\u53EF\u80FD\u672A\u88AB\u4F7F\u7528\uFF0C\u5EFA\u8BAE\u68C0\u67E5`),e.project.dependencies.some(r=>r.groupId==="org.springframework.boot")&&t.push("\u9879\u76EE\u4F7F\u7528Spring Boot\uFF0C\u5EFA\u8BAE\u4F7F\u7528Spring Dependency Management\u63D2\u4EF6"),t}}});import{existsSync as Ic,readFileSync as Vg}from"fs";import{resolve as Ac,dirname as zg}from"path";function Rc(o=process.cwd()){let e={name:"unknown",version:"0.0.0",description:"",languages:["Unknown"],primaryLanguage:"Unknown",configFiles:[]},t=new Set,n=[],r="Unknown",s,i=null;for(let[a,c]of Object.entries(Lc))for(let l of c.files){if(l.includes("*"))continue;let u=Ac(o,l);if(Ic(u)&&(t.add(c.language),n.push(l),r==="Unknown")){r=c.language,s=a;try{let p=Vg(u,"utf-8"),g=c.parser(p,u);g instanceof Promise?console.warn(`Async parser not supported in sync readProjectConfig: ${a}`):i=g}catch(p){console.warn(`Error parsing ${l}: ${p instanceof Error?p.message:"Unknown error"}`)}}}return t.size===0?e:{...e,...i||{},languages:Array.from(t),primaryLanguage:r,buildTool:s,configFiles:n}}function Hg(o,e){try{let t=JSON.parse(o);return{name:t.name||"unknown",version:t.version||"0.0.0",description:t.description||"",dependencies:t.dependencies||{},devDependencies:t.devDependencies||{},entryPoints:[t.main,...typeof t.bin=="string"?[t.bin]:Object.values(t.bin||{})].filter(Boolean)}}catch{return null}}function Jg(o,e){try{let t=o.match(/name\s*=\s*['"]([^'"]+)['"]/),n=o.match(/version\s*=\s*['"]([^'"]+)['"]/),r=o.match(/description\s*=\s*['"]([^'"]+)['"]/);return{name:t?t[1]:"unknown",version:n?n[1]:"0.0.0",description:r?r[1]:""}}catch{return null}}function Gg(o,e){try{let t=o.match(/name\s*=\s*"([^"]+)"/),n=o.match(/version\s*=\s*"([^"]+)"/),r=o.match(/description\s*=\s*"([^"]+)"/);return{name:t?t[1]:"unknown",version:n?n[1]:"0.0.0",description:r?r[1]:""}}catch{return null}}function Bg(o,e){try{return{name:e.split(/[/\\]/).slice(-2,-1)[0]||"unknown",version:"0.0.0",description:""}}catch{return null}}function qg(o,e){try{let t=o.match(/module\s+([^\s]+)/),n=o.match(/go\s+([^\s]+)/),r={},s=/require\s+([^\s]+)\s+([^\s]+)/g,i;for(;(i=s.exec(o))!==null;)r[i[1]]=i[2];return{name:t&&t[1].split("/").pop()||"unknown",version:n?n[1]:"0.0.0",description:"",dependencies:r}}catch{return null}}function Kg(o,e){try{let t=o.match(/name\s*=\s*"([^"]+)"/),n=o.match(/version\s*=\s*"([^"]+)"/),r=o.match(/description\s*=\s*"([^"]+)"/);return{name:t?t[1]:"unknown",version:n?n[1]:"0.0.0",description:r?r[1]:""}}catch{return null}}function Yg(o,e){try{return{name:e.split(/[/\\]/).slice(-2,-1)[0]||"unknown",version:"0.0.0",description:""}}catch{return null}}function Xg(o,e){try{let t=JSON.parse(o);return{name:t.name||"unknown",version:t.version||"0.0.0",description:t.description||"",dependencies:t.require||{},devDependencies:t["require-dev"]||{}}}catch{return null}}function Qg(o,e){try{let n=(e.split(/[/\\]/).pop()||"unknown").replace(/\.(cs|vb|fs)proj$/,""),r=o.match(/<Version>(.*?)<\/Version>/),s=o.match(/<Description>(.*?)<\/Description>/);return{name:n,version:r?r[1]:"0.0.0",description:s?s[1]:""}}catch{return null}}function Dc(o){let e=o.map(t=>`${t.groupId}:${t.artifactId}`);return e.some(t=>t.includes("spring-boot"))?"Spring Boot":e.some(t=>t.includes("spring"))?"Spring Framework":e.some(t=>t.includes("jakarta")||t.includes("javax"))?"Jakarta EE":e.some(t=>t.includes("hibernate"))?"Hibernate":e.some(t=>t.includes("mybatis"))?"MyBatis":e.some(t=>t.includes("struts"))?"Struts":"Java Standard"}async function Zg(o,e){try{let t=await qs(zg(e));if(!t)return null;let n=t.project,r={};n.dependencies.forEach(i=>{r[`${i.groupId}:${i.artifactId}`]=i.version});let s=Dc(n.dependencies);return{name:n.name,version:n.version,description:n.description||"",dependencies:r,languageExtensionInfo:{javaDetails:n,framework:s,javaVersion:n.javaVersion,buildToolVersion:n.buildToolVersion||"Maven"},configFiles:["pom.xml"]}}catch(t){return console.error("Error parsing POM XML with enhanced parser:",t),null}}async function ep(o,e){try{let t=await Promise.resolve().then(()=>(Ks(),Mc)),r=new t.GradleBuildParser(o,e).parse();if(!r)return null;let s={};r.dependencies.forEach(a=>{s[`${a.groupId}:${a.artifactId}`]=a.version});let i=Dc(r.dependencies);return{name:r.name,version:r.version,description:r.description||"",dependencies:s,languageExtensionInfo:{javaDetails:r,framework:i,javaVersion:r.javaVersion,buildToolVersion:r.buildToolVersion||"Gradle"},configFiles:[e.split("/").pop()||"build.gradle"]}}catch(t){return console.error("Error parsing Gradle build file with enhanced parser:",t),null}}function Fc(o=process.cwd()){let e=[];for(let[t,n]of Object.entries(Lc))for(let r of n.files){if(r.includes("*"))continue;let s=Ac(o,r);if(Ic(s)){e.push(t);break}}return e}var Lc,Oc=C(()=>{Ks();Lc={nodejs:{files:["package.json"],language:"JavaScript/TypeScript",parser:Hg},"java-maven":{files:["pom.xml"],language:"Java",parser:Zg},"java-gradle":{files:["build.gradle","build.gradle.kts"],language:"Java",parser:async(o,e)=>await ep(o,e)},"python-pip":{files:["setup.py","setup.cfg"],language:"Python",parser:Jg},"python-poetry":{files:["pyproject.toml"],language:"Python",parser:Gg},"python-pipenv":{files:["Pipfile"],language:"Python",parser:Bg},go:{files:["go.mod"],language:"Go",parser:qg},rust:{files:["Cargo.toml"],language:"Rust",parser:Kg},ruby:{files:["Gemfile"],language:"Ruby",parser:Yg},php:{files:["composer.json"],language:"PHP",parser:Xg},dotnet:{files:["*.csproj","*.vbproj","*.fsproj"],language:"C#/.NET",parser:Qg}}});import{writeFileSync as tp,existsSync as np,mkdirSync as rp}from"fs";import{resolve as jc}from"path";function _c(o,e=process.cwd()){let t=jc(e,".nium","project");np(t)||rp(t,{recursive:!0});let r=jc(t,"project.json"),s=JSON.stringify(o,null,2);tp(r,s,"utf-8"),console.log(`\u2705 \u9879\u76EE\u4FE1\u606F\u5DF2\u4FDD\u5B58\u81F3: ${r}`)}function Nc(o){let e=o.reduce((t,n)=>t+n.count,0);return o.map(t=>({...t,percentage:e>0?(t.count/e*100).toFixed(1)+"%":"0%"}))}var Uc=C(()=>{ro()});import{createHash as op}from"crypto";import{readFileSync as Wc,writeFileSync as sp,existsSync as ip,statSync as ap}from"fs";import{resolve as cp}from"path";function lp(o){try{let e=Wc(o),t=op("md5");return t.update(e),t.digest("hex")}catch(e){return console.warn(`\u26A0\uFE0F \u65E0\u6CD5\u8BA1\u7B97\u6587\u4EF6 MD5: ${o}`,e),""}}function up(o,e=process.cwd()){try{let t=cp(e,o),n=ap(t),r=lp(t);return{path:o,size:n.size,md5:r,updatedAt:n.mtime.toISOString(),description:""}}catch(t){return console.warn(`\u26A0\uFE0F \u65E0\u6CD5\u83B7\u53D6\u6587\u4EF6\u4FE1\u606F: ${o}`,t),null}}function gp(o){let e=new Map;if(!ip(o))return e;try{let n=Wc(o,"utf-8").trim().split(`
1385
- `);for(let r of n)if(r.trim())try{let s=JSON.parse(r);e.set(s.path,s)}catch(s){console.warn(`\u26A0\uFE0F \u65E0\u6CD5\u89E3\u6790 JSONL \u884C: ${r}`,s)}}catch(t){console.warn(`\u26A0\uFE0F \u8BFB\u53D6 JSONL \u6587\u4EF6\u5931\u8D25: ${o}`,t)}return e}function pp(o,e){try{let t=[],n=Array.from(o.entries()).sort((r,s)=>r[0].localeCompare(s[0]));for(let[,r]of n)t.push(JSON.stringify(r));sp(e,t.join(`
2125
+ \u26A0\uFE0F \u4EE5\u4E0A\u951A\u70B9\u4FE1\u606F\u4EC5\u4F5C\u4E3A\u8F85\u52A9\u53C2\u8003\uFF0C\u60A8\u5E94\u4E13\u6CE8\u4E8E\u89E3\u51B3\u5F53\u524D\u4E3B\u8981\u4EFB\u52A1\u3002`},f=l.findIndex(y=>y.role==="system");f!==-1&&l.splice(f+1,0,d),C(`\u5DF2\u6CE8\u5165 ${g.size} \u4E2A\u6587\u4EF6\u53D8\u66F4\u951A\u70B9`)}}catch(u){C(`\u751F\u6210\u6587\u4EF6\u53D8\u66F4\u951A\u70B9\u65F6\u51FA\u9519: ${u}`)}if(this.contextConfig.enableSemanticAnalysis&&n-c>=this.contextConfig.semanticCheckInterval)try{let u=l.map(g=>g.content).filter(Boolean).join(`
2126
+ `),p=await this.semanticAnalyzer.analyzeSemanticDrift(t||this.anchorManager.getOriginalQuestion(),u,n);if(C(`\u8BED\u4E49\u5206\u6790 - \u76F8\u4F3C\u5EA6: ${p.similarityScore.toFixed(2)}, \u504F\u79BB\u7EA7\u522B: ${p.driftLevel}`),p.driftLevel==="severe"||p.driftLevel==="moderate"&&p.similarityScore<this.contextConfig.similarityThreshold){let g=`\u26A0\uFE0F \u68C0\u6D4B\u5230${p.driftLevel==="severe"?"\u4E25\u91CD":"\u4E2D\u5EA6"}\u504F\u79BB\uFF0C\u6B63\u5728\u7EA0\u6B63...`;a?a(g,i):C(g);let m=`\u68C0\u6D4B\u5230${p.driftLevel}\u504F\u79BB\uFF1A${p.deviationFactors.join("; ")}`,d=await this.anchorManager.createAnchorMessage(n,p.similarityScore,p.driftLevel,m,u);C(`\u{1F3AF} \u6CE8\u5165\u504F\u79BB\u7EA0\u6B63\u951A\u70B9\uFF08\u8FED\u4EE3 ${n}\uFF0C\u504F\u79BB\u7EA7\u522B: ${p.driftLevel}\uFF0C\u4F18\u5148\u7EA7: ${d.metadata?.priority}}`),l.push(d)}c=n}catch(u){oe(`\u8BED\u4E49\u5206\u6790\u5931\u8D25: ${u.message}`)}if(this.contextConfig.enableAnchorSystem&&n%this.contextConfig.anchorInjectionInterval===0)try{let u=l.map(g=>g.content).filter(Boolean).join(`
2127
+ `),p=await this.anchorManager.calculateSemanticSimilarity(u);if(await this.anchorManager.shouldInjectAnchor(n,p,u)){let g=await this.anchorManager.createAnchorMessage(n,p,void 0,void 0,u);C(`\u{1F3AF} \u6CE8\u5165\u4E0A\u4E0B\u6587\u951A\u70B9\uFF08\u8FED\u4EE3 ${n}\uFF0C\u76F8\u4F3C\u5EA6: ${p.toFixed(2)}\uFF0C\u4F18\u5148\u7EA7: ${g.metadata?.priority}}`),l.push(g)}}catch(u){oe(`\u951A\u70B9\u6CE8\u5165\u5931\u8D25: ${u.message}`)}return{messages:l,lastSemanticCheckIteration:c}}}});var fc=S(()=>{Ip();rc();sc();Us()});function Jf(s){let e=s.trim();return e=e.replace(/"([^"]+)":\s*([^",\[\]{}\s][^,\]\}]*)/g,(t,n,r)=>{let o=r.trim();return/^-?\d+(\.\d+)?$/.test(o)||o==="true"||o==="false"||o==="null"?t:`"${n}":"${o}"`}),e=e.replace(/\[([^\[\]]*)\]/g,(t,n)=>n.trim()?`[${n.split(",").map(o=>{let i=o.trim();return i.startsWith('"')||i.startsWith("'")||i.startsWith("{")||i.startsWith("[")||/^-?\d+(\.\d+)?$/.test(i)||i==="true"||i==="false"||i==="null"?i:`"${i}"`}).join(",")}]`:t),e=e.replace(/'/g,'"'),e=e.replace(/,(\s*[}\]])/g,"$1"),e}function mr(s,e=!0){try{return{success:!0,data:JSON.parse(s),wasFixed:!1}}catch(t){if(!e)return{success:!1,error:t instanceof Error?t.message:String(t)};try{let n=Jf(s);return{success:!0,data:JSON.parse(n),wasFixed:!0}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n),wasFixed:!1}}}}var Si=S(()=>{});var _p={};B(_p,{GradleBuildParser:()=>Ws,JavaDependencyAnalyzer:()=>vi,MavenPomParser:()=>bi,analyzeJavaProject:()=>yc});import{readFileSync as Ci,existsSync as wi}from"fs";import{resolve as hc}from"path";import{parseString as Kf}from"xml2js";async function yc(s=process.cwd()){let e=hc(s,"pom.xml"),t=hc(s,"build.gradle"),n=hc(s,"build.gradle.kts"),r=null;try{if(wi(e)){let i=Ci(e,"utf-8");r=await new bi(i,e).parse()}else if(wi(t)){let i=Ci(t,"utf-8");r=new Ws(i,t).parse()}else if(wi(n)){let i=Ci(n,"utf-8");r=new Ws(i,n).parse()}if(!r)return null;let o={project:r,conflicts:[],outdated:[],unused:[],recommendations:[]};return o.recommendations=vi.generateRecommendations(o),o}catch(o){return xe("Error analyzing Java project: "+(o instanceof Error?o.message:String(o)),"java-analyzer"),null}}var bi,Ws,vi,xc=S(()=>{Tt();bi=class{content;filePath;constructor(e,t){this.content=e,this.filePath=t}async parse(){try{return new Promise((e,t)=>{Kf(this.content,{explicitArray:!1},(n,r)=>{if(n){t(n);return}try{let{project:o}=r;if(!o){e(null);return}let i={name:o.artifactId||o.name||"unknown",version:o.version||"0.0.0",description:o.description||"",groupId:o.groupId||o.parent?.groupId,artifactId:o.artifactId,packaging:o.packaging||"jar",javaVersion:this.extractJavaVersion(o),buildToolVersion:this.extractMavenVersion(),parent:o.parent?{groupId:o.parent.groupId,artifactId:o.parent.artifactId,version:o.parent.version}:void 0,dependencies:this.extractDependencies(o.dependencies?.dependency),dependencyManagement:this.extractDependencies(o.dependencyManagement?.dependencies?.dependency),properties:this.extractProperties(o.properties),modules:o.modules?.module?Array.isArray(o.modules.module)?o.modules.module:[o.modules.module]:void 0,repositories:this.extractRepositories(o.repositories?.repository)};e(i)}catch(o){t(o)}})})}catch(e){return xe("Error parsing POM XML: "+(e instanceof Error?e.message:String(e)),"java-parser"),null}}extractJavaVersion(e){return e.properties?.["java.version"]||e.properties?.["maven.compiler.source"]||e.properties?.["maven.compiler.target"]||e.build?.plugins?.plugin?.find(n=>n.artifactId==="maven-compiler-plugin")?.configuration?.source}extractMavenVersion(){let e=this.content.match(/modelVersion>([^<]+)</);return e?e[1]:void 0}extractDependencies(e){return e?(Array.isArray(e)?e:[e]).map(n=>({groupId:n.groupId,artifactId:n.artifactId,version:n.version||"unknown",scope:n.scope||"compile",type:n.type||"jar",classifier:n.classifier,optional:n.optional==="true",exclusions:n.exclusions?.exclusion?(Array.isArray(n.exclusions.exclusion)?n.exclusions.exclusion:[n.exclusions.exclusion]).map(r=>({groupId:r.groupId,artifactId:r.artifactId})):void 0})):[]}extractProperties(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{n!=="$"&&(t[n]=e[n])}),t}extractRepositories(e){return e?(Array.isArray(e)?e:[e]).map(n=>n.url).filter(Boolean):[]}},Ws=class{content;filePath;constructor(e,t){this.content=e,this.filePath=t}parse(){try{let e=this.filePath.endsWith(".kts");return{name:this.extractProjectName(),version:this.extractVersion(),description:this.extractDescription(),groupId:this.extractGroup(),artifactId:this.extractProjectName(),javaVersion:this.extractJavaVersion(),buildToolVersion:this.extractGradleVersion(),dependencies:this.extractDependencies(e),dependencyManagement:[],properties:this.extractProperties(e)}}catch(e){return xe("Error parsing Gradle build file: "+(e instanceof Error?e.message:String(e)),"java-parser"),null}}extractProjectName(){let e=this.content.match(/rootProject\.name\s*=\s*['"]([^'"]+)['"]/)||this.content.match(/project\(['"]([^'"]+)['"]\)/)||this.content.match(/name\s*=\s*['"]([^'"]+)['"]/);if(e)return e[1];let t=this.filePath.split(/[/\\]/);return t[t.length-2]||"unknown"}extractVersion(){let e=this.content.match(/version\s*=\s*['"]([^'"]+)['"]/);return e?e[1]:"0.0.0"}extractDescription(){let e=this.content.match(/description\s*=\s*['"]([^'"]+)['"]/);return e?e[1]:""}extractGroup(){let e=this.content.match(/group\s*=\s*['"]([^'"]+)['"]/);return e?e[1]:""}extractJavaVersion(){let e=this.content.match(/sourceCompatibility\s*=\s*['"]?([^'"\s]+)['"]?/)||this.content.match(/targetCompatibility\s*=\s*['"]?([^'"\s]+)['"]?/)||this.content.match(/java\.toolchain\.languageVersion\s*=\s*JavaLanguageVersion\.of\((\d+)\)/);return e?e[1]:void 0}extractGradleVersion(){let e=this.filePath.replace(/build\.gradle(\.kts)?$/,"gradle/wrapper/gradle-wrapper.properties");if(wi(e))try{let n=Ci(e,"utf-8").match(/distributionUrl=.*gradle-(\d+\.\d+(?:\.\d+)?)-/);if(n)return n[1]}catch{}}extractDependencies(e){let t=[];return[/(implementation|compile|api|compileOnly|runtimeOnly|testImplementation)\s*['"]([^:'"]+):([^:'"]+):([^:'"]+)['"]/g,/(implementation|compile|api|compileOnly|runtimeOnly|testImplementation)\s*['"]([^:'"]+):([^:'"]+)['"]/g,/(implementation|compile|api|compileOnly|runtimeOnly|testImplementation)\s*\(\s*group\s*:\s*['"]([^'"]+)['"],\s*name\s*:\s*['"]([^'"]+)['"],\s*version\s*:\s*['"]([^'"]+)['"]\s*\)/g,/(implementation|compile|api|compileOnly|runtimeOnly|testImplementation)\s*\(\s*group\s*:\s*['"]([^'"]+)['"],\s*name\s*:\s*['"]([^'"]+)['"]\s*\)/g,/(implementation|compile|api|compileOnly|runtimeOnly|testImplementation)\s*\(\s*["']([^"']+):([^"']+):([^"']+)["']\s*\)/g,/(implementation|compile|api|compileOnly|runtimeOnly|testImplementation)\s*\(\s*["']([^"']+):([^"']+)["']\s*\)/g].forEach(r=>{let o;for(;(o=r.exec(this.content))!==null;){let i,a,c,l;if(o.length===5)[,i,a,c,l]=o;else if(o.length===4)[,i,a,c]=o,l="managed";else continue;t.push({groupId:a,artifactId:c,version:l,scope:i.toLowerCase(),type:"jar"})}}),t}extractProperties(e){let t={},n=e?/val\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g:/(\w+)\s*=\s*['"]([^'"]+)['"]/g,r;for(;(r=n.exec(this.content))!==null;)t[r[1]]=r[2];return t}},vi=class{static analyzeConflicts(e){let t=new Map,n=new Map;e.forEach(o=>{o.dependencies.forEach(i=>{let a=`${i.groupId}:${i.artifactId}`;t.has(a)||(t.set(a,new Set),n.set(a,[])),t.get(a).add(i.version),n.get(a).push(`${o.name} (${i.scope})`)})});let r=[];return t.forEach((o,i)=>{if(o.size>1){let[a,c]=i.split(":"),l=Array.from(o);r.push({groupId:a,artifactId:c,versions:l,locations:n.get(i)||[],severity:this.calculateConflictSeverity(l)})}}),r}static calculateConflictSeverity(e){let t=e.map(r=>r.split(".")[0]).filter(r=>/^\d+$/.test(r));return new Set(t).size>1?"high":e.length>2?"medium":"low"}static generateRecommendations(e){let t=[];return e.conflicts.length>0&&t.push(`\u53D1\u73B0 ${e.conflicts.length} \u4E2A\u4F9D\u8D56\u51B2\u7A81\uFF0C\u5EFA\u8BAE\u7EDF\u4E00\u7248\u672C\u7BA1\u7406`),e.outdated.length>0&&t.push(`${e.outdated.length} \u4E2A\u4F9D\u8D56\u5B58\u5728\u66F4\u65B0\u7248\u672C`),e.unused.length>0&&t.push(`${e.unused.length} \u4E2A\u4F9D\u8D56\u53EF\u80FD\u672A\u88AB\u4F7F\u7528\uFF0C\u5EFA\u8BAE\u68C0\u67E5`),e.project.dependencies.some(r=>r.groupId==="org.springframework.boot")&&t.push("\u9879\u76EE\u4F7F\u7528Spring Boot\uFF0C\u5EFA\u8BAE\u4F7F\u7528Spring Dependency Management\u63D2\u4EF6"),t}}});import{existsSync as Yf,readFileSync as Xf}from"fs";import{resolve as Qf,dirname as Zf}from"path";async function Up(s=process.cwd()){let e={name:"unknown",version:"0.0.0",description:"",languages:["Unknown"],primaryLanguage:"Unknown",configFiles:[]},t=new Set,n=[],r="Unknown",o,i=null;for(let[a,c]of Object.entries(eh))for(let l of c.files){if(l.includes("*"))continue;let u=Qf(s,l);if(Yf(u)&&(t.add(c.language),n.push(l),r==="Unknown")){r=c.language,o=a;try{let p=Xf(u,"utf-8"),g=c.parser(p,u);g instanceof Promise?i=await g:i=g}catch(p){J(`Error parsing ${l}: ${p instanceof Error?p.message:"Unknown error"}`,"project-config")}}}return t.size===0?e:{...e,...i||{},languages:Array.from(t),primaryLanguage:r,buildTool:o,configFiles:n}}function th(s,e){try{let t=JSON.parse(s);return{name:t.name||"unknown",version:t.version||"0.0.0",description:t.description||"",dependencies:t.dependencies||{},devDependencies:t.devDependencies||{},entryPoints:[t.main,...typeof t.bin=="string"?[t.bin]:Object.values(t.bin||{})].filter(Boolean)}}catch{return null}}function nh(s,e){try{let t=s.match(/name\s*=\s*['"]([^'"]+)['"]/),n=s.match(/version\s*=\s*['"]([^'"]+)['"]/),r=s.match(/description\s*=\s*['"]([^'"]+)['"]/);return{name:t?t[1]:"unknown",version:n?n[1]:"0.0.0",description:r?r[1]:""}}catch{return null}}function rh(s,e){try{let t=s.match(/name\s*=\s*"([^"]+)"/),n=s.match(/version\s*=\s*"([^"]+)"/),r=s.match(/description\s*=\s*"([^"]+)"/);return{name:t?t[1]:"unknown",version:n?n[1]:"0.0.0",description:r?r[1]:""}}catch{return null}}function sh(s,e){try{return{name:e.split(/[/\\]/).slice(-2,-1)[0]||"unknown",version:"0.0.0",description:""}}catch{return null}}function oh(s,e){try{let t=s.match(/module\s+([^\s]+)/),n=s.match(/go\s+([^\s]+)/),r={},o=/require\s+([^\s]+)\s+([^\s]+)/g,i;for(;(i=o.exec(s))!==null;)r[i[1]]=i[2];return{name:t&&t[1].split("/").pop()||"unknown",version:n?n[1]:"0.0.0",description:"",dependencies:r}}catch{return null}}function ih(s,e){try{let t=s.match(/name\s*=\s*"([^"]+)"/),n=s.match(/version\s*=\s*"([^"]+)"/),r=s.match(/description\s*=\s*"([^"]+)"/);return{name:t?t[1]:"unknown",version:n?n[1]:"0.0.0",description:r?r[1]:""}}catch{return null}}function ah(s,e){try{return{name:e.split(/[/\\]/).slice(-2,-1)[0]||"unknown",version:"0.0.0",description:""}}catch{return null}}function ch(s,e){try{let t=JSON.parse(s);return{name:t.name||"unknown",version:t.version||"0.0.0",description:t.description||"",dependencies:t.require||{},devDependencies:t["require-dev"]||{}}}catch{return null}}function lh(s,e){try{let n=(e.split(/[/\\]/).pop()||"unknown").replace(/\.(cs|vb|fs)proj$/,""),r=s.match(/<Version>(.*?)<\/Version>/),o=s.match(/<Description>(.*?)<\/Description>/);return{name:n,version:r?r[1]:"0.0.0",description:o?o[1]:""}}catch{return null}}function Wp(s){let e=s.map(t=>`${t.groupId}:${t.artifactId}`);return e.some(t=>t.includes("spring-boot"))?"Spring Boot":e.some(t=>t.includes("spring"))?"Spring Framework":e.some(t=>t.includes("jakarta")||t.includes("javax"))?"Jakarta EE":e.some(t=>t.includes("hibernate"))?"Hibernate":e.some(t=>t.includes("mybatis"))?"MyBatis":e.some(t=>t.includes("struts"))?"Struts":"Java Standard"}async function uh(s,e){try{let t=await yc(Zf(e));if(!t)return null;let n=t.project,r={};n.dependencies.forEach(i=>{r[`${i.groupId}:${i.artifactId}`]=i.version});let o=Wp(n.dependencies);return{name:n.name,version:n.version,description:n.description||"",dependencies:r,languageExtensionInfo:{javaDetails:n,framework:o,javaVersion:n.javaVersion,buildToolVersion:n.buildToolVersion||"Maven"},configFiles:["pom.xml"]}}catch(t){return xe("Error parsing POM XML with enhanced parser: "+(t instanceof Error?t.message:String(t)),"project-config"),null}}async function ph(s,e){try{let t=await Promise.resolve().then(()=>(xc(),_p)),r=new t.GradleBuildParser(s,e).parse();if(!r)return null;let o={};r.dependencies.forEach(a=>{o[`${a.groupId}:${a.artifactId}`]=a.version});let i=Wp(r.dependencies);return{name:r.name,version:r.version,description:r.description||"",dependencies:o,languageExtensionInfo:{javaDetails:r,framework:i,javaVersion:r.javaVersion,buildToolVersion:r.buildToolVersion||"Gradle"},configFiles:[e.split("/").pop()||"build.gradle"]}}catch(t){return xe("Error parsing Gradle build file with enhanced parser: "+(t instanceof Error?t.message:String(t)),"project-config"),null}}var eh,Bp=S(()=>{xc();Tt();eh={nodejs:{files:["package.json"],language:"JavaScript/TypeScript",parser:th},"java-maven":{files:["pom.xml"],language:"Java",parser:uh},"java-gradle":{files:["build.gradle","build.gradle.kts"],language:"Java",parser:async(s,e)=>await ph(s,e)},"python-pip":{files:["setup.py","setup.cfg"],language:"Python",parser:nh},"python-poetry":{files:["pyproject.toml"],language:"Python",parser:rh},"python-pipenv":{files:["Pipfile"],language:"Python",parser:sh},go:{files:["go.mod"],language:"Go",parser:oh},rust:{files:["Cargo.toml"],language:"Rust",parser:ih},ruby:{files:["Gemfile"],language:"Ruby",parser:ah},php:{files:["composer.json"],language:"PHP",parser:ch},dotnet:{files:["*.csproj","*.vbproj","*.fsproj"],language:"C#/.NET",parser:lh}}});import{writeFileSync as gh,existsSync as mh,mkdirSync as dh}from"fs";import{resolve as Hp}from"path";function zp(s,e=process.cwd()){let t=Hp(e,".nium","project");mh(t)||dh(t,{recursive:!0});let r=Hp(t,"project.json"),o=JSON.stringify(s,null,2);gh(r,o,"utf-8"),console.log(`\u2705 \u9879\u76EE\u4FE1\u606F\u5DF2\u4FDD\u5B58\u81F3: ${r}`)}function Vp(s){let e=s.reduce((t,n)=>t+n.count,0);return s.map(t=>({...t,percentage:e>0?(t.count/e*100).toFixed(1)+"%":"0%"}))}var Gp=S(()=>{ii()});import{createHash as fh}from"crypto";import{readFileSync as qp,writeFileSync as hh,existsSync as yh,statSync as xh}from"fs";import{resolve as Sh}from"path";function Ch(s){try{let e=qp(s),t=fh("md5");return t.update(e),t.digest("hex")}catch(e){return console.warn(`\u26A0\uFE0F \u65E0\u6CD5\u8BA1\u7B97\u6587\u4EF6 MD5: ${s}`,e),""}}function wh(s,e=process.cwd()){try{let t=Sh(e,s),n=xh(t),r=Ch(t);return{path:s,size:n.size,md5:r,updatedAt:n.mtime.toISOString(),description:""}}catch(t){return console.warn(`\u26A0\uFE0F \u65E0\u6CD5\u83B7\u53D6\u6587\u4EF6\u4FE1\u606F: ${s}`,t),null}}function bh(s){let e=new Map;if(!yh(s))return e;try{let n=qp(s,"utf-8").trim().split(`
2128
+ `);for(let r of n)if(r.trim())try{let o=JSON.parse(r);e.set(o.path,o)}catch(o){console.warn(`\u26A0\uFE0F \u65E0\u6CD5\u89E3\u6790 JSONL \u884C: ${r}`,o)}}catch(t){console.warn(`\u26A0\uFE0F \u8BFB\u53D6 JSONL \u6587\u4EF6\u5931\u8D25: ${s}`,t)}return e}function vh(s,e){try{let t=[],n=Array.from(s.entries()).sort((r,o)=>r[0].localeCompare(o[0]));for(let[,r]of n)t.push(JSON.stringify(r));hh(e,t.join(`
1386
2129
  `)+`
1387
- `,"utf-8")}catch(t){throw console.error(`\u274C \u5199\u5165 JSONL \u6587\u4EF6\u5931\u8D25: ${e}`,t),t}}function Vc(o,e,t=process.cwd(),n=!0){n&&console.log(` \u{1F4D6} \u6B63\u5728\u8BFB\u53D6\u73B0\u6709\u6587\u4EF6\u4FE1\u606F: ${e}`);let r=gp(e),s={added:0,updated:0,deleted:0,unchanged:0},i=new Map,a=new Set(o),c=o.length,l=0,u=Date.now();n&&(console.log(` \u{1F4CB} \u8BFB\u53D6\u73B0\u6709\u6587\u4EF6\u4FE1\u606F\u5B8C\u6210\uFF0C\u5DF2\u6709 ${r.size} \u6761\u8BB0\u5F55`),console.log(` \u{1F680} \u5F00\u59CB\u5904\u7406 ${c} \u4E2A\u6587\u4EF6...`));for(let p of o){if(l++,n&&l===1&&console.log(` \u{1F504} \u5904\u7406\u7B2C 1 \u4E2A\u6587\u4EF6: ${p}`),n&&l%50===0){let m=(l/c*100).toFixed(1),h=((Date.now()-u)/1e3).toFixed(1);console.log(` \u{1F4CA} \u5904\u7406\u8FDB\u5EA6: ${l}/${c} (${m}%) - \u5DF2\u7528\u65F6 ${h}s`)}let g=r.get(p),d=up(p,t);d&&(g?g.md5!==d.md5?(i.set(p,{...d,description:g.description}),s.updated++):(i.set(p,g),s.unchanged++):(i.set(p,d),s.added++))}if(n){let p=((Date.now()-u)/1e3).toFixed(1);console.log(` \u2705 \u6587\u4EF6\u5904\u7406\u5B8C\u6210: ${c} \u4E2A\u6587\u4EF6, \u603B\u7528\u65F6 ${p}s`)}n&&console.log(" \u{1F50D} \u6B63\u5728\u68C0\u6D4B\u5DF2\u5220\u9664\u7684\u6587\u4EF6...");for(let[p]of r)a.has(p)||s.deleted++;return n&&console.log(` \u{1F4CA} \u68C0\u6D4B\u5230 ${s.deleted} \u4E2A\u5DF2\u5220\u9664\u7684\u6587\u4EF6`),n&&console.log(` \u{1F4BE} \u6B63\u5728\u5199\u5165 ${i.size} \u6761\u6587\u4EF6\u4FE1\u606F\u5230 JSONL...`),pp(i,e),n&&console.log(" \u2705 JSONL \u6587\u4EF6\u5199\u5165\u5B8C\u6210"),s}function zc(o){let e=o.added+o.updated+o.deleted+o.unchanged,t=[];return t.push("\u{1F4C4} \u6587\u4EF6\u4FE1\u606F\u66F4\u65B0\u6458\u8981"),t.push("\u2500".repeat(40)),t.push(`\u603B\u6587\u4EF6\u6570: ${e}`),o.added>0&&t.push(`\u2795 \u65B0\u589E: ${o.added} \u4E2A\u6587\u4EF6`),o.updated>0&&t.push(`\u{1F504} \u66F4\u65B0: ${o.updated} \u4E2A\u6587\u4EF6`),o.deleted>0&&t.push(`\u2796 \u5220\u9664: ${o.deleted} \u4E2A\u6587\u4EF6`),o.unchanged>0&&t.push(`\u2705 \u672A\u53D8: ${o.unchanged} \u4E2A\u6587\u4EF6`),t.push("\u2500".repeat(40)),t.join(`
1388
- `)}var Hc=C(()=>{});var Gc={};j(Gc,{QuickProjectScanTool:()=>pt,quickProjectScan:()=>qt,quickProjectScanTool:()=>Kt});import{existsSync as gt}from"fs";import{globSync as dp}from"glob";async function qt(){return Jc.execute({})}var pt,Jc,Kt,Ys=C(()=>{V();Dt();Oc();Uc();Hc();bs();pt=class extends ${getDefinition(){return{name:"quickProjectScan",description:"Quickly scan the entire project structure, analyze directories, detect languages, and save project information to .nium/project/project.json. Use this when the user asks to explore or analyze the project structure.",input_schema:{type:"object",properties:{},required:[]}}}async execute(e){try{let t=[],n=process.cwd();t.push(`\u{1F50D} \u5F00\u59CB\u63A2\u7D22\u5DE5\u7A0B\u7ED3\u6784...
1389
- `),t.push("\u{1F4C2} \u626B\u63CF\u9879\u76EE\u6587\u4EF6...");let r=Ee(n,!0);t.push(` - \u5E94\u7528 ${r.length} \u6761\u5FFD\u7565\u89C4\u5219`);let s=Date.now(),i=dp("**/*",{nodir:!0,ignore:r,cwd:n}),a=((Date.now()-s)/1e3).toFixed(1);t.push(`\u627E\u5230 ${i.length} \u4E2A\u76F8\u5173\u6587\u4EF6 (\u8017\u65F6 ${a}s)
1390
- `),t.push("\u{1F4CB} \u68C0\u6D4B\u9879\u76EE\u7C7B\u578B\u548C\u914D\u7F6E...");let c=Fc(n);c.length>0&&t.push(` - \u68C0\u6D4B\u5230\u9879\u76EE\u7C7B\u578B: ${c.join(", ")}`);let l=await Rc(n),u={name:l.name,version:l.version,description:l.description,dependencies:l.dependencies||{},devDependencies:l.devDependencies||{}};t.push(` - \u9879\u76EE\u540D\u79F0: ${u.name}`),t.push(` - \u7248\u672C: ${u.version}`),t.push(` - \u8BED\u8A00: ${l.primaryLanguage}`),l.buildTool&&t.push(` - \u6784\u5EFA\u5DE5\u5177: ${l.buildTool}`),t.push(""),t.push("\u{1F5C2}\uFE0F \u5206\u6790\u76EE\u5F55\u7ED3\u6784...");let p=this.analyzeDirectoryStructure(i);t.push(""),t.push("\u{1F310} \u68C0\u6D4B\u9879\u76EE\u7F16\u7A0B\u8BED\u8A00...");let g=this.detectProjectLanguages(i);t.push(`\u4E3B\u8981\u7F16\u7A0B\u8BED\u8A00: ${g.primaryLanguage||l.primaryLanguage||"\u672A\u77E5"}`),g.languages.length>0&&t.push(`\u68C0\u6D4B\u5230 ${g.languages.length} \u79CD\u7F16\u7A0B\u8BED\u8A00`),t.push(""),t.push("\u2699\uFE0F \u68C0\u6D4B\u8FD0\u884C\u65F6\u7248\u672C...");let d=await this.detectVersions(l,n);if(Object.keys(d).length>0)for(let[S,E]of Object.entries(d))t.push(` - ${S}: ${E}`);else t.push(" - \u672A\u68C0\u6D4B\u5230\u7248\u672C\u4FE1\u606F");t.push(""),t.push("\u{1F4D0} \u68C0\u6D4B\u4EE3\u7801\u89C4\u8303...");let m=this.detectCodeStandards(n,l.languages);m.length>0?t.push(` - \u68C0\u6D4B\u5230\u4EE3\u7801\u89C4\u8303: ${m.join(", ")}`):t.push(" - \u672A\u68C0\u6D4B\u5230\u4EE3\u7801\u89C4\u8303\u914D\u7F6E"),t.push(""),t.push("\u{1F4CB} \u5206\u6790\u9879\u76EE\u4F9D\u8D56...");let h=await this.analyzeDependencies(n,l.languages),w=Object.values(h).reduce((S,E)=>S+(E.dependencies?.length||0),0),v=Object.values(h).reduce((S,E)=>S+(E.conflicts?.length||0),0);t.push(` - \u4F9D\u8D56\u603B\u6570: ${w}`),v>0&&t.push(` - \u4F9D\u8D56\u51B2\u7A81: ${v}`),t.push(""),t.push("\u2705 \u9879\u76EE\u7ED3\u6784\u5206\u6790\u5B8C\u6210"),t.push(""),t.push("\u{1F4BE} \u4FDD\u5B58\u9879\u76EE\u57FA\u7840\u4FE1\u606F...");let T=this.buildProjectBasicInfo(u,p,i,g,l,d,m,h);try{_c(T,n),t.push("\u2705 \u9879\u76EE\u57FA\u7840\u4FE1\u606F\u5DF2\u4FDD\u5B58\u81F3: .nium/project/"),t.push("")}catch(S){console.error(" \u274C \u4FDD\u5B58\u9879\u76EE\u4FE1\u606F\u5931\u8D25:",S),t.push(`\u26A0\uFE0F \u4FDD\u5B58\u9879\u76EE\u4FE1\u606F\u5931\u8D25: ${S instanceof Error?S.message:"\u672A\u77E5\u9519\u8BEF"}`),t.push("")}t.push("\u{1F4DD} \u66F4\u65B0\u6587\u4EF6\u4FE1\u606F\u5217\u8868...");let f=`${n}/.nium/project/files.jsonl`;try{let S=Date.now(),E=Vc(i,f,n),P=((Date.now()-S)/1e3).toFixed(1);t.push("\u2705 \u6587\u4EF6\u4FE1\u606F\u5DF2\u66F4\u65B0\u81F3: .nium/project/files.jsonl"),t.push("");let L=zc(E);t.push(L),t.push("")}catch(S){console.error(" \u274C \u66F4\u65B0\u6587\u4EF6\u4FE1\u606F\u5931\u8D25:",S),t.push(`\u26A0\uFE0F \u66F4\u65B0\u6587\u4EF6\u4FE1\u606F\u5931\u8D25: ${S instanceof Error?S.message:"\u672A\u77E5\u9519\u8BEF"}`),t.push("")}let y=this.generateSummary(u,p,g,l);return t.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),t.push("\u9879\u76EE\u7ED3\u6784\u6982\u89C8"),t.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),t.push(y),t.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),t.push(""),t.join(`
1391
- `)}catch(t){return this.formatError("Quick project scan",t)}}detectProjectLanguages(e){let t={".js":"JavaScript",".mjs":"JavaScript (ES Modules)",".cjs":"JavaScript (CommonJS)",".jsx":"React JavaScript",".ts":"TypeScript",".tsx":"React TypeScript",".java":"Java",".class":"Java",".jar":"Java","pom.xml":"Java (Maven)","build.gradle":"Java (Gradle)",".py":"Python","requirements.txt":"Python","setup.py":"Python","pyproject.toml":"Python",".c":"C",".cpp":"C++",".h":"C/C++",".hpp":"C++","CMakeLists.txt":"C/C++ (CMake)",".go":"Go","go.mod":"Go",".rs":"Rust","Cargo.toml":"Rust",".php":"PHP","composer.json":"PHP (Composer)",".rb":"Ruby",Gemfile:"Ruby",".cs":"C#",".vb":"Visual Basic","packages.config":".NET",".html":"HTML",".css":"CSS",".scss":"SCSS",".less":"Less",".json":"JSON",".xml":"XML",".yml":"YAML",".yaml":"YAML",".md":"Markdown"},n={};e.forEach(a=>{if(t[a]){n[t[a]]=(n[t[a]]||0)+1;return}let c=a.lastIndexOf(".");if(c>-1){let l=a.substring(c);t[l]&&(n[t[l]]=(n[t[l]]||0)+1)}});let r=Object.entries(n).map(([a,c])=>({language:a,count:c})).sort((a,c)=>c.count-a.count),[s]=r;return{primaryLanguage:s?.language||null,languages:r,totalSourceFiles:r.reduce((a,c)=>a+c.count,0)}}analyzeDirectoryStructure(e){let t={directories:new Set,sourceFiles:[],configFiles:[],docFiles:[],testFiles:[]},n=[".js",".mjs",".cjs",".jsx",".ts",".tsx",".java",".py",".c",".cpp",".cc",".cxx",".h",".hpp",".go",".rs",".php",".rb",".cs",".kt",".kts",".scala",".swift",".m",".mm"],r=[".json",".yaml",".yml",".toml",".ini",".xml",".properties"],s=["package.json","tsconfig.json","pom.xml","build.gradle","settings.gradle","gradle.properties","Cargo.toml","go.mod","requirements.txt","setup.py","pyproject.toml","composer.json","Gemfile",".env",".env.example"];return e.forEach(i=>{let a=i.split("/");if(a.length>1&&t.directories.add(a[0]),i.includes("test")||i.includes("spec")||i.startsWith("test/")||i.startsWith("tests/")||i.includes("__tests__")||i.endsWith(".test.js")||i.endsWith(".test.ts")||i.endsWith(".spec.js")||i.endsWith(".spec.ts")||i.endsWith("Test.java")||i.endsWith("Tests.java")){t.testFiles.push(i);return}let c=i.split("/").pop()||"",l=c.includes(".")?"."+c.split(".").pop():"";i.startsWith("src/")||i.startsWith("lib/")||i.startsWith("app/"),n.includes(l)&&t.sourceFiles.push(i),(r.includes(l)||s.includes(c))&&t.configFiles.push(i),(l===".md"||l===".txt"||l===".rst"||c==="README"||c==="CHANGELOG"||c==="LICENSE"||c==="CONTRIBUTING")&&t.docFiles.push(i)}),{directories:Array.from(t.directories).sort(),sourceFiles:t.sourceFiles.sort(),configFiles:t.configFiles.sort(),docFiles:t.docFiles.sort(),testFiles:t.testFiles.sort()}}async detectVersions(e,t){try{return await Ue.detectVersionsForLanguages(e.languages,t,e.configFiles)}catch{return{}}}detectCodeStandards(e,t){try{return Ue.detectCodeStandardsForLanguages(t,e)}catch{return[]}}async analyzeDependencies(e,t){let n={};try{for(let r of t){let s=Ue.getHandler(r);if(s){let i=await s.analyzeDependencies(e);n[r.toLowerCase()]=i}}}catch(r){console.error("\u4F9D\u8D56\u5206\u6790\u5931\u8D25:",r)}return n}analyzeCoreModules(e){let t=[],n=new Map;e.sourceFiles.forEach(s=>{let i=s.split("/");if(i.length>=2){let a=i.slice(0,2).join("/");n.has(a)||n.set(a,[]),n.get(a).push(s)}});let r={core:"\u6838\u5FC3\u4E1A\u52A1\u903B\u8F91",domain:"\u9886\u57DF\u6A21\u578B\u548C\u4E1A\u52A1\u89C4\u5219",business:"\u4E1A\u52A1\u903B\u8F91\u5C42",service:"\u670D\u52A1\u5C42",services:"\u670D\u52A1\u5C42",model:"\u6570\u636E\u6A21\u578B",models:"\u6570\u636E\u6A21\u578B",entity:"\u5B9E\u4F53\u7C7B",entities:"\u5B9E\u4F53\u7C7B",dao:"\u6570\u636E\u8BBF\u95EE\u5BF9\u8C61",repository:"\u6570\u636E\u4ED3\u5E93\u5C42",repositories:"\u6570\u636E\u4ED3\u5E93\u5C42",db:"\u6570\u636E\u5E93\u64CD\u4F5C",database:"\u6570\u636E\u5E93\u64CD\u4F5C",persistence:"\u6301\u4E45\u5316\u5C42",api:"API \u63A5\u53E3",rest:"REST API",controller:"\u63A7\u5236\u5668",controllers:"\u63A7\u5236\u5668",handler:"\u8BF7\u6C42\u5904\u7406\u5668",handlers:"\u8BF7\u6C42\u5904\u7406\u5668",endpoint:"\u7AEF\u70B9\u5B9A\u4E49",endpoints:"\u7AEF\u70B9\u5B9A\u4E49",route:"\u8DEF\u7531\u5B9A\u4E49",routes:"\u8DEF\u7531\u5B9A\u4E49",view:"\u89C6\u56FE\u5C42",views:"\u89C6\u56FE\u5C42",component:"\u7EC4\u4EF6",components:"\u7EC4\u4EF6",ui:"\u7528\u6237\u754C\u9762",page:"\u9875\u9762",pages:"\u9875\u9762",layout:"\u5E03\u5C40",layouts:"\u5E03\u5C40",template:"\u6A21\u677F",templates:"\u6A21\u677F",util:"\u5DE5\u5177\u51FD\u6570",utils:"\u5DE5\u5177\u51FD\u6570",helper:"\u8F85\u52A9\u51FD\u6570",helpers:"\u8F85\u52A9\u51FD\u6570",lib:"\u5E93\u6587\u4EF6",libs:"\u5E93\u6587\u4EF6",common:"\u516C\u5171\u6A21\u5757",shared:"\u5171\u4EAB\u6A21\u5757",config:"\u914D\u7F6E\u7BA1\u7406",configuration:"\u914D\u7F6E\u7BA1\u7406",settings:"\u8BBE\u7F6E\u7BA1\u7406",constant:"\u5E38\u91CF\u5B9A\u4E49",constants:"\u5E38\u91CF\u5B9A\u4E49",enum:"\u679A\u4E3E\u5B9A\u4E49",enums:"\u679A\u4E3E\u5B9A\u4E49",middleware:"\u4E2D\u95F4\u4EF6",middlewares:"\u4E2D\u95F4\u4EF6",interceptor:"\u62E6\u622A\u5668",interceptors:"\u62E6\u622A\u5668",filter:"\u8FC7\u6EE4\u5668",filters:"\u8FC7\u6EE4\u5668",guard:"\u5B88\u536B",guards:"\u5B88\u536B",client:"\u5BA2\u6237\u7AEF",clients:"\u5BA2\u6237\u7AEF",adapter:"\u9002\u914D\u5668",adapters:"\u9002\u914D\u5668",provider:"\u63D0\u4F9B\u5546",providers:"\u63D0\u4F9B\u5546",integration:"\u5916\u90E8\u96C6\u6210",integrations:"\u5916\u90E8\u96C6\u6210",auth:"\u8BA4\u8BC1\u6388\u6743",authentication:"\u8BA4\u8BC1",authorization:"\u6388\u6743",security:"\u5B89\u5168\u6A21\u5757",cli:"\u547D\u4EE4\u884C\u63A5\u53E3",cmd:"\u547D\u4EE4\u884C\u5DE5\u5177",script:"\u811A\u672C",scripts:"\u811A\u672C",tool:"\u5DE5\u5177",tools:"\u5DE5\u5177\u96C6",test:"\u6D4B\u8BD5",tests:"\u6D4B\u8BD5",spec:"\u6D4B\u8BD5\u89C4\u8303",mock:"\u6A21\u62DF\u6570\u636E",mocks:"\u6A21\u62DF\u6570\u636E",fixture:"\u6D4B\u8BD5\u5939\u5177",fixtures:"\u6D4B\u8BD5\u5939\u5177",type:"\u7C7B\u578B\u5B9A\u4E49",types:"\u7C7B\u578B\u5B9A\u4E49",interface:"\u63A5\u53E3\u5B9A\u4E49",interfaces:"\u63A5\u53E3\u5B9A\u4E49",schema:"\u6570\u636E\u7ED3\u6784\u5B9A\u4E49",schemas:"\u6570\u636E\u7ED3\u6784\u5B9A\u4E49",dto:"\u6570\u636E\u4F20\u8F93\u5BF9\u8C61",vo:"\u503C\u5BF9\u8C61",event:"\u4E8B\u4EF6",events:"\u4E8B\u4EF6",exception:"\u5F02\u5E38\u5904\u7406",exceptions:"\u5F02\u5E38\u5904\u7406",error:"\u9519\u8BEF\u5904\u7406",errors:"\u9519\u8BEF\u5904\u7406",validator:"\u9A8C\u8BC1\u5668",validators:"\u9A8C\u8BC1\u5668",decorator:"\u88C5\u9970\u5668",decorators:"\u88C5\u9970\u5668"};return n.forEach((s,i)=>{if(s.length>=2){let a=i.split("/").pop()||i,c=a.toLowerCase(),l=r[c]||`${a} \u6A21\u5757`;t.push({name:a.charAt(0).toUpperCase()+a.slice(1),description:l,files:s})}}),t.slice(0,10)}generateProjectStructureDoc(e,t,n,r,s,i,a){let c=new Date().toISOString(),l=this.analyzeCoreModules(t),u=Object.keys(i).length>0?Object.entries(i).map(([g,d])=>`**${g}**: ${d}`).join(`
1392
- `):"\u6682\u65E0\u7248\u672C\u4FE1\u606F",p=a.length>0?a.map(g=>`- ${g}`).join(`
1393
- `):"\u6682\u65E0\u4EE3\u7801\u89C4\u8303\u914D\u7F6E";return`# ${e.name} - \u9879\u76EE\u7ED3\u6784\u6587\u6863
2130
+ `,"utf-8")}catch(t){throw console.error(`\u274C \u5199\u5165 JSONL \u6587\u4EF6\u5931\u8D25: ${e}`,t),t}}function Jp(s,e,t=process.cwd(),n=!0){n&&console.log(` \u{1F4D6} \u6B63\u5728\u8BFB\u53D6\u73B0\u6709\u6587\u4EF6\u4FE1\u606F: ${e}`);let r=bh(e),o={added:0,updated:0,deleted:0,unchanged:0},i=new Map,a=new Set(s),c=s.length,l=0,u=Date.now();n&&(console.log(` \u{1F4CB} \u8BFB\u53D6\u73B0\u6709\u6587\u4EF6\u4FE1\u606F\u5B8C\u6210\uFF0C\u5DF2\u6709 ${r.size} \u6761\u8BB0\u5F55`),console.log(` \u{1F680} \u5F00\u59CB\u5904\u7406 ${c} \u4E2A\u6587\u4EF6...`));for(let p of s){if(l++,n&&l===1&&console.log(` \u{1F504} \u5904\u7406\u7B2C 1 \u4E2A\u6587\u4EF6: ${p}`),n&&l%50===0){let d=(l/c*100).toFixed(1),f=((Date.now()-u)/1e3).toFixed(1);console.log(` \u{1F4CA} \u5904\u7406\u8FDB\u5EA6: ${l}/${c} (${d}%) - \u5DF2\u7528\u65F6 ${f}s`)}let g=r.get(p),m=wh(p,t);m&&(g?g.md5!==m.md5?(i.set(p,{...m,description:g.description}),o.updated++):(i.set(p,g),o.unchanged++):(i.set(p,m),o.added++))}if(n){let p=((Date.now()-u)/1e3).toFixed(1);console.log(` \u2705 \u6587\u4EF6\u5904\u7406\u5B8C\u6210: ${c} \u4E2A\u6587\u4EF6, \u603B\u7528\u65F6 ${p}s`)}n&&console.log(" \u{1F50D} \u6B63\u5728\u68C0\u6D4B\u5DF2\u5220\u9664\u7684\u6587\u4EF6...");for(let[p]of r)a.has(p)||o.deleted++;return n&&console.log(` \u{1F4CA} \u68C0\u6D4B\u5230 ${o.deleted} \u4E2A\u5DF2\u5220\u9664\u7684\u6587\u4EF6`),n&&console.log(` \u{1F4BE} \u6B63\u5728\u5199\u5165 ${i.size} \u6761\u6587\u4EF6\u4FE1\u606F\u5230 JSONL...`),vh(i,e),n&&console.log(" \u2705 JSONL \u6587\u4EF6\u5199\u5165\u5B8C\u6210"),o}function Kp(s){let e=s.added+s.updated+s.deleted+s.unchanged,t=[];return t.push("\u{1F4C4} \u6587\u4EF6\u4FE1\u606F\u66F4\u65B0\u6458\u8981"),t.push("\u2500".repeat(40)),t.push(`\u603B\u6587\u4EF6\u6570: ${e}`),s.added>0&&t.push(`\u2795 \u65B0\u589E: ${s.added} \u4E2A\u6587\u4EF6`),s.updated>0&&t.push(`\u{1F504} \u66F4\u65B0: ${s.updated} \u4E2A\u6587\u4EF6`),s.deleted>0&&t.push(`\u2796 \u5220\u9664: ${s.deleted} \u4E2A\u6587\u4EF6`),s.unchanged>0&&t.push(`\u2705 \u672A\u53D8: ${s.unchanged} \u4E2A\u6587\u4EF6`),t.push("\u2500".repeat(40)),t.join(`
2131
+ `)}var Yp=S(()=>{});var Zp={};B(Zp,{QuickProjectScanTool:()=>cn,quickProjectScan:()=>dr,quickProjectScanTool:()=>fr});import{existsSync as an,statSync as Th}from"fs";import{globSync as Ph}from"glob";import*as Xp from"path";async function dr(){return Qp.execute({})}var cn,Qp,fr,Sc=S(()=>{G();pt();Bp();Gp();Yp();$a();cn=class extends R{getDefinition(){return{name:"quickProjectScan",description:`\u5FEB\u901F\u626B\u63CF\u9879\u76EE\u7ED3\u6784\uFF08<5\u79D2\uFF09\uFF0C\u8BC6\u522B\u6280\u672F\u6808\u3001\u9879\u76EE\u7C7B\u578B\u3001\u5173\u952E\u76EE\u5F55\u3002\u9002\u5408\u65B0\u9879\u76EE\u521D\u63A2\u6216\u5FEB\u901F\u4E86\u89E3\u3002
2132
+
2133
+ \u{1F4CB} \u7528\u9014\uFF1A
2134
+ - \u5FEB\u901F\u8BC6\u522B\u9879\u76EE\u6280\u672F\u6808\u548C\u7F16\u7A0B\u8BED\u8A00
2135
+ - \u4E86\u89E3\u9879\u76EE\u76EE\u5F55\u7ED3\u6784\u548C\u6587\u4EF6\u7EC4\u7EC7
2136
+ - \u68C0\u6D4B\u9879\u76EE\u914D\u7F6E\u6587\u4EF6\u548C\u4F9D\u8D56\u7BA1\u7406
2137
+ - \u751F\u6210\u9879\u76EE\u57FA\u672C\u4FE1\u606F\u6587\u6863
2138
+
2139
+ \u{1F511} \u53C2\u6570\uFF1A
2140
+ - \u65E0\u53C2\u6570\uFF08\u81EA\u52A8\u626B\u63CF\u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55\uFF09
2141
+
2142
+ \u{1F4A1} \u793A\u4F8B\uFF1A
2143
+ - quickProjectScan({})
2144
+
2145
+ \u{1F3AF} \u4E0E\u5176\u4ED6\u5DE5\u5177\u7684\u533A\u522B\uFF1A
2146
+ \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510
2147
+ \u2502 \u5DE5\u5177 \u2502 \u7279\u70B9 \u2502
2148
+ \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524
2149
+ \u2502 quickProjectScan\u2502 \u5FEB\u901F\u6982\u89C8\uFF08<5\u79D2\uFF0C\u8F7B\u91CF\u626B\u63CF\uFF09 \u2502
2150
+ \u2502 explore \u2502 \u6DF1\u5EA6\u67B6\u6784\uFF0830-60\u79D2\uFF0C\u5206\u6790\u8BBE\u8BA1\uFF09 \u2502
2151
+ \u2502 moduleExplore \u2502 \u6A21\u5757\u5B9E\u73B0\uFF0860-120\u79D2\uFF0C\u4EE3\u7801\u7EC6\u8282\uFF09 \u2502
2152
+ \u2502 toolingExplore \u2502 \u5DE5\u5177\u94FE\uFF0830-60\u79D2\uFF0C\u6784\u5EFA/\u6D4B\u8BD5\u914D\u7F6E\uFF09 \u2502
2153
+ \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
2154
+
2155
+ \u63A8\u8350\u6D41\u7A0B\uFF1AquickProjectScan \u2192 explore \u2192 moduleExplore\uFF08\u4ECE\u5B8F\u89C2\u5230\u5FAE\u89C2\uFF09
2156
+
2157
+ \u2705 \u9002\u5408\u7684\u573A\u666F\uFF1A
2158
+ - \u7B2C\u4E00\u6B21\u63A5\u89E6\u9879\u76EE\uFF0C\u9700\u8981\u5FEB\u901F\u4E86\u89E3\u57FA\u672C\u4FE1\u606F
2159
+ - \u9A8C\u8BC1\u9879\u76EE\u7C7B\u578B\u548C\u6280\u672F\u6808
2160
+ - \u751F\u6210\u9879\u76EE\u7ED3\u6784\u6587\u6863\u4F9B\u540E\u7EED\u5206\u6790\u4F7F\u7528
2161
+ - \u5728\u6DF1\u5EA6\u5206\u6790\u524D\u83B7\u53D6\u9879\u76EE\u6982\u89C8
2162
+ - \u56DE\u7B54"\u8FD9\u662F\u4EC0\u4E48\u9879\u76EE"\u7684\u95EE\u9898
2163
+
2164
+ \u274C \u4E0D\u9002\u5408\u7684\u573A\u666F\uFF1A
2165
+ - \u9700\u8981\u7406\u89E3\u67B6\u6784\u8BBE\u8BA1\u548C\u6A21\u5757\u5173\u7CFB \u2192 \u4F7F\u7528 explore
2166
+ - \u9700\u8981\u6DF1\u5165\u4E86\u89E3\u67D0\u4E2A\u6A21\u5757\u5B9E\u73B0 \u2192 \u4F7F\u7528 moduleExplore
2167
+ - \u9700\u8981\u4E86\u89E3\u6784\u5EFA/\u6D4B\u8BD5/\u90E8\u7F72\u914D\u7F6E \u2192 \u4F7F\u7528 toolingExplore
2168
+ - \u9700\u8981\u67E5\u627E\u5177\u4F53\u51FD\u6570\u6216\u7C7B \u2192 \u4F7F\u7528 grep + read
2169
+ - \u5DF2\u7ECF\u4E86\u89E3\u9879\u76EE\uFF0C\u53EA\u9700\u4FEE\u6539\u4EE3\u7801 \u2192 \u76F4\u63A5\u4F7F\u7528 read/write
2170
+
2171
+ \u26A0\uFE0F \u6CE8\u610F\uFF1A
2172
+ - \u672C\u5DE5\u5177\u662F\u6700\u8F7B\u91CF\u7EA7\u7684\u63A2\u7D22\u5DE5\u5177\uFF08<5\u79D2\uFF09
2173
+ - \u4F7F\u7528glob\u6A21\u5F0F\u5339\u914D\uFF0C\u9650\u5236\u626B\u63CF\u6587\u4EF6\u6570\u4EE5\u63D0\u5347\u901F\u5EA6
2174
+ - \u7ED3\u679C\u4FDD\u5B58\u81F3 .nium/project/project.json
2175
+ - \u5EFA\u8BAE\u5728\u5176\u4ED6\u63A2\u7D22\u5DE5\u5177\u524D\u5148\u8FD0\u884C\u4E00\u6B21
2176
+
2177
+ \u{1F4DD} \u8F93\u51FA\uFF1A
2178
+ - \u4FDD\u5B58\u9879\u76EE\u4FE1\u606F\u5230 .nium/project/project.json
2179
+ - \u8FD4\u56DE\u6280\u672F\u6808\u3001\u76EE\u5F55\u7ED3\u6784\u3001\u914D\u7F6E\u6587\u4EF6\u5217\u8868`,input_schema:{type:"object",properties:{},required:[]}}}async execute(e){try{let t=[],n=process.cwd();t.push(`\u{1F50D} \u5F00\u59CB\u63A2\u7D22\u5DE5\u7A0B\u7ED3\u6784...
2180
+ `),t.push("\u{1F4C2} \u626B\u63CF\u9879\u76EE\u6587\u4EF6...");let r=we(n,!0);t.push(` - \u5E94\u7528 ${r.length} \u6761\u5FFD\u7565\u89C4\u5219`);let o=Date.now(),i=Ph("**/*",{nodir:!0,ignore:r,cwd:n}),a=this.prioritizeImportantFiles(i,n),c=((Date.now()-o)/1e3).toFixed(1);t.push(`\u627E\u5230 ${i.length} \u4E2A\u76F8\u5173\u6587\u4EF6\uFF0C\u4F18\u5148\u5206\u6790 ${a.length} \u4E2A\u91CD\u8981\u6587\u4EF6 (\u8017\u65F6 ${c}s)
2181
+ `),t.push("\u{1F4CB} \u667A\u80FD\u68C0\u6D4B\u9879\u76EE\u7C7B\u578B...");let l=this.detectProjectTypeQuick(a);t.push(` - \u9879\u76EE\u7C7B\u578B: ${l.type}`),t.push(` - \u6846\u67B6: ${l.framework||"\u672A\u77E5"}`);let u=await Up(n),p={name:u.name,version:u.version,description:u.description,dependencies:u.dependencies||{},devDependencies:u.devDependencies||{}};t.push(` - \u9879\u76EE\u540D\u79F0: ${p.name}`),t.push(` - \u7248\u672C: ${p.version}`),t.push(` - \u8BED\u8A00: ${u.primaryLanguage}`),u.buildTool&&t.push(` - \u6784\u5EFA\u5DE5\u5177: ${u.buildTool}`),t.push(""),t.push("\u{1F5C2}\uFE0F \u5206\u6790\u76EE\u5F55\u7ED3\u6784...");let g=this.analyzeDirectoryStructure(a);t.push(""),t.push("\u{1F310} \u68C0\u6D4B\u9879\u76EE\u7F16\u7A0B\u8BED\u8A00...");let m=this.detectProjectLanguages(a);t.push(`\u4E3B\u8981\u7F16\u7A0B\u8BED\u8A00: ${m.primaryLanguage||u.primaryLanguage||"\u672A\u77E5"}`),m.languages.length>0&&t.push(`\u68C0\u6D4B\u5230 ${m.languages.length} \u79CD\u7F16\u7A0B\u8BED\u8A00`),t.push(""),t.push("\u2699\uFE0F \u68C0\u6D4B\u8FD0\u884C\u65F6\u7248\u672C...");let d=await this.detectVersions(u,n);if(Object.keys(d).length>0)for(let[k,b]of Object.entries(d))t.push(` - ${k}: ${b}`);else t.push(" - \u672A\u68C0\u6D4B\u5230\u7248\u672C\u4FE1\u606F");t.push(""),t.push("\u{1F4D0} \u68C0\u6D4B\u4EE3\u7801\u89C4\u8303...");let f=await this.detectCodeStandards(n,u.languages);f.length>0?t.push(` - \u68C0\u6D4B\u5230\u4EE3\u7801\u89C4\u8303: ${f.join(", ")}`):t.push(" - \u672A\u68C0\u6D4B\u5230\u4EE3\u7801\u89C4\u8303\u914D\u7F6E"),t.push(""),t.push("\u{1F4CB} \u5206\u6790\u9879\u76EE\u4F9D\u8D56...");let y=await this.analyzeDependencies(n,u.languages),w=Object.values(y).reduce((k,b)=>k+(b.dependencies?.length||0),0),T=Object.values(y).reduce((k,b)=>k+(b.conflicts?.length||0),0);t.push(` - \u4F9D\u8D56\u603B\u6570: ${w}`),T>0&&t.push(` - \u4F9D\u8D56\u51B2\u7A81: ${T}`),t.push(""),t.push("\u2705 \u9879\u76EE\u7ED3\u6784\u5206\u6790\u5B8C\u6210"),t.push(""),t.push("\u{1F4BE} \u4FDD\u5B58\u9879\u76EE\u57FA\u7840\u4FE1\u606F...");let h=await this.buildProjectBasicInfo(p,g,i,m,u,d,f,y);try{zp(h,n),t.push("\u2705 \u9879\u76EE\u57FA\u7840\u4FE1\u606F\u5DF2\u4FDD\u5B58\u81F3: .nium/project/"),t.push("")}catch(k){console.error(" \u274C \u4FDD\u5B58\u9879\u76EE\u4FE1\u606F\u5931\u8D25:",k),t.push(`\u26A0\uFE0F \u4FDD\u5B58\u9879\u76EE\u4FE1\u606F\u5931\u8D25: ${k instanceof Error?k.message:"\u672A\u77E5\u9519\u8BEF"}`),t.push("")}t.push("\u{1F4DD} \u66F4\u65B0\u6587\u4EF6\u4FE1\u606F\u5217\u8868...");let x=`${n}/.nium/project/files.jsonl`;try{let k=Date.now(),b=Jp(i,x,n),U=((Date.now()-k)/1e3).toFixed(1);t.push("\u2705 \u6587\u4EF6\u4FE1\u606F\u5DF2\u66F4\u65B0\u81F3: .nium/project/files.jsonl"),t.push("");let j=Kp(b);t.push(j),t.push("")}catch(k){console.error(" \u274C \u66F4\u65B0\u6587\u4EF6\u4FE1\u606F\u5931\u8D25:",k),t.push(`\u26A0\uFE0F \u66F4\u65B0\u6587\u4EF6\u4FE1\u606F\u5931\u8D25: ${k instanceof Error?k.message:"\u672A\u77E5\u9519\u8BEF"}`),t.push("")}let P=this.generateSummary(p,g,m,u);return t.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),t.push("\u9879\u76EE\u7ED3\u6784\u6982\u89C8"),t.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),t.push(P),t.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),t.push(""),t.join(`
2182
+ `)}catch(t){return this.formatError("Quick project scan",t)}}prioritizeImportantFiles(e,t){let n=[{patterns:["package.json","package-lock.json","yarn.lock","pnpm-lock.yaml","tsconfig.json","jsconfig.json","pom.xml","build.gradle","settings.gradle","gradle.properties","Cargo.toml","Cargo.lock","go.mod","go.sum","requirements.txt","setup.py","pyproject.toml","Pipfile","poetry.lock","poetry.lock","composer.json","composer.lock","Gemfile","Gemfile.lock","Gemfile.lock","*.sln","*.csproj","*.vbproj","*.fsproj","packages.config","Makefile","CMakeLists.txt","configure","configure.ac","Makefile.am"],priority:100},{patterns:["index.{js,ts,jsx,tsx,mjs,cjs}","main.{js,ts,mjs,cjs}","app.{js,ts,jsx,tsx}","server.{js,ts}","src/index.{js,ts,jsx,tsx,mjs,cjs}","src/main.{js,ts,mjs,cjs}","src/app.{js,ts,jsx,tsx}","lib/index.{js,ts,mjs,cjs}","lib/main.{js,ts,mjs,cjs}","src/main/java/**/Main.java","src/main/java/**/Application.java","src/main/java/**/App.java","src/main/java/**/{main,Main,App}.java","main.py","app.py","run.py","src/main.py","src/app.py","__main__.py","setup.py","main.go","app.go","cmd/**/main.go","cmd/**/server.go","src/main.rs","src/lib.rs","main.rs","lib.rs","index.php","main.php","app.php","public/index.php","src/index.php","main.rb","app.rb","application.rb","config/application.rb","config.ru","Program.cs","Startup.cs","Main.cs","App.cs","src/**/Program.cs","index.html","app.html"],priority:90},{patterns:["*.config.{js,ts,mjs,cjs}","{babel,webpack,rollup,vite,jest,eslint,prettier,tsup,parcel}.config.{js,ts,json}",".eslintrc*","prettier.config.*","jest.config.*","tsconfig.*.json","jsconfig.json","next.config.*","nuxt.config.*","build.xml","gradlew","gradlew.bat","mvnw","mvnw.cmd","pytest.ini","tox.ini","setup.cfg",".flake8",".pylintrc","mypy.ini","pyproject.toml","go.sum",".golangci.yml","go.mod.sum","rustfmt.toml",".rustfmt.toml","clippy.toml","phpunit.xml","composer.lock",".php-cs-fixer.php","phpstan.neon","Rakefile","Gemfile.lock","config.ru","Guardfile",".rubocop.yml","appsettings.*.json","web.config","app.config","packages.lock.json","project.lock.json","*.config.{json,yaml,yml,toml,ini,properties,conf}",".env*","Makefile","CMakeLists.txt","configure","configure.ac","Makefile.am"],priority:80},{patterns:["src/**/*.{js,ts,jsx,tsx,mjs,cjs}","lib/**/*.{js,ts,jsx,tsx,mjs,cjs}","app/**/*.{js,ts,jsx,tsx,mjs,cjs}","server/**/*.{js,ts,jsx,tsx,mjs,cjs}","api/**/*.{js,ts,jsx,tsx,mjs,cjs}","src/main/java/**/*.java","src/main/resources/**/*","src/test/java/**/*.java","src/test/resources/**/*","src/**/*.py","lib/**/*.py","app/**/*.py","test/**/*.py","tests/**/*.py","package/**/*.py","**/*.go","cmd/**/*.go","pkg/**/*.go","internal/**/*.go","src/**/*.rs","tests/**/*.rs","benches/**/*.rs","examples/**/*.rs","src/**/*.php","app/**/*.php","lib/**/*.php","tests/**/*.php","spec/**/*.php","app/**/*.rb","lib/**/*.rb","spec/**/*.rb","test/**/*.rb","config/**/*.rb","src/**/*.cs","src/**/*.vb","src/**/*.fs","Controllers/**/*.cs","Models/**/*.cs","Views/**/*.cs","Services/**/*.cs","core/**/*.{js,ts,java,py,go,rs,php,rb,cs,vb,fs}","common/**/*.{js,ts,java,py,go,rs,php,rb,cs,vb,fs}","shared/**/*.{js,ts,java,py,go,rs,php,rb,cs,vb,fs}","utils/**/*.{js,ts,java,py,go,rs,php,rb,cs,vb,fs}","helpers/**/*.{js,ts,java,py,go,rs,php,rb,cs,vb,fs}","components/**/*.{js,ts,jsx,tsx,java,py,go,rs,php,rb,cs,vb,fs}","modules/**/*.{js,ts,java,py,go,rs,php,rb,cs,vb,fs}","services/**/*.{js,ts,java,py,go,rs,php,rb,cs,vb,fs}","controllers/**/*.{js,ts,java,py,go,rs,php,rb,cs,vb,fs}","models/**/*.{js,ts,java,py,go,rs,php,rb,cs,vb,fs}","views/**/*.{js,ts,java,py,go,rs,php,rb,cs,vb,fs}"],priority:70},{patterns:["README*","CHANGELOG*","LICENSE*","CONTRIBUTING*","INSTALL*","USAGE*","FAQ*","TROUBLESHOOTING*","GUIDE*","*.test.{js,ts,jsx,tsx,mjs,cjs}","*.spec.{js,ts,jsx,tsx,mjs,cjs}","test/**/*","tests/**/*","__tests__/**/*","cypress/**/*","playwright/**/*","*Test.java","*Tests.java","src/test/**/*","src/test/java/**/*","test_*.py","*_test.py","test/**/*.py","tests/**/*.py","conftest.py","pytest.ini","*_test.go","**/*_test.go","*_test.rs","tests/**/*.rs","*Test.php","*Tests.php","tests/**/*Test.php","spec/**/*Test.php","*_test.rb","*_spec.rb","spec/**/*.rb","test/**/*.rb","features/**/*.rb","*Tests.cs","*Test.cs","Tests/**/*.cs","test/**/*.cs","specs/**/*","fixtures/**/*","mock/**/*","stubs/**/*"],priority:60},{patterns:["*.{js,ts,jsx,tsx,mjs,cjs,java,py,go,rs,php,rb,cs,vb,fs,cpp,c,h,hpp,cxx,cc,kotlin,kt,scala,swift,objc,m,dart,sql}","scripts/**/*","tools/**/*","bin/**/*","cli/**/*","command/**/*","utils/**/*","util/**/*","helpers/**/*","helper/**/*","vendor/**/*","third_party/**/*","external/**/*","deps/**/*","node_modules/**/*","target/**/*","build/**/*","dist/**/*","out/**/*",".gradle/**/*",".m2/**/*","cache/**/*","temp/**/*","tmp/**/*"],priority:50},{patterns:["*.{json,yaml,yml,toml,xml,csv,ini,properties,conf,config}","*.{md,txt,rst,adoc,asciidoc,textile}","*.{css,scss,sass,less}","*.{png,jpg,jpeg,gif,svg,ico,webp}","*.{woff,woff2,ttf,eot}","*.{mp3,wav,ogg,mp4,avi,mov,webm}","assets/**/*","static/**/*","public/**/*","resources/**/*","media/**/*","images/**/*","img/**/*","styles/**/*","css/**/*","fonts/**/*","docs/**/*","doc/**/*","documentation/**/*","examples/**/*","demo/**/*","sample/**/*","templates/**/*","template/**/*","views/**/*","layouts/**/*","partials/**/*","config/**/*","configs/**/*","settings/**/*",".env*","Dockerfile*","docker-compose*.yml","docker-compose*.yaml",".dockerignore","k8s/**/*","kubernetes/**/*","helm/**/*","terraform/**/*",".github/**/*",".gitlab-ci.yml",".travis.yml",".circleci/**/*","*.log","*.tmp","*.bak","*.swp","*.DS_Store","Thumbs.db"],priority:30}],r=e.map(c=>{let l=10,u="";for(let g of n)for(let m of g.patterns)if(this.matchesPattern(c,m)){g.priority>l&&(l=g.priority,u=m);break}let p=this.getFileSize(t,c);return p&&p>1024*1024&&(l=Math.max(10,l-20)),{file:c,score:l,pattern:u}}),o=e.length,i=200;return o<100?i=o:o<500?i=Math.min(300,o*.8):o<1e3?i=Math.min(400,o*.5):i=500,r.sort((c,l)=>l.score-c.score).slice(0,i).map(c=>c.file)}matchesPattern(e,t){return new RegExp(t.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\{([^}]+)\}/g,"($1)").replace(/,/g,"|")).test(e)}getFileSize(e,t){try{return Th(Xp.join(e,t)).size}catch{return null}}detectProjectTypeQuick(e){let t=new Set(e.map(n=>n.toLowerCase()));return t.has("package.json")&&(e.some(n=>n.includes("react"))||e.some(n=>n.includes("jsx")||n.includes("tsx")))?{type:"React\u5E94\u7528",framework:"React"}:t.has("package.json")&&(e.some(n=>n.includes("vue"))||t.has("vite.config.js")||t.has("vite.config.ts"))?{type:"Vue\u5E94\u7528",framework:"Vue.js"}:t.has("package.json")&&!t.has("index.html")?e.some(n=>n.includes("express")||n.includes("server"))?{type:"Node.js\u670D\u52A1\u7AEF",framework:"Express"}:{type:"Node.js\u9879\u76EE",framework:"Node.js"}:t.has("angular.json")?{type:"Angular\u5E94\u7528",framework:"Angular"}:t.has("next.config.js")||t.has("next.config.ts")?{type:"Next.js\u5E94\u7528",framework:"Next.js"}:t.has("nuxt.config.js")||t.has("nuxt.config.ts")?{type:"Nuxt.js\u5E94\u7528",framework:"Nuxt.js"}:e.some(n=>n.endsWith(".py"))&&(t.has("requirements.txt")||t.has("setup.py")||t.has("pyproject.toml"))?{type:"Python\u9879\u76EE",framework:"Python"}:t.has("pom.xml")?{type:"Java\u9879\u76EE",framework:"Maven"}:t.has("build.gradle")?{type:"Java\u9879\u76EE",framework:"Gradle"}:t.has("go.mod")?{type:"Go\u9879\u76EE",framework:"Go Modules"}:t.has("cargo.toml")?{type:"Rust\u9879\u76EE",framework:"Cargo"}:t.has("composer.json")?{type:"PHP\u9879\u76EE",framework:"Composer"}:t.has("gemfile")?{type:"Ruby\u9879\u76EE",framework:"Bundler"}:e.some(n=>n.endsWith(".csproj")||n.endsWith(".sln"))?{type:".NET\u9879\u76EE",framework:".NET"}:t.has("index.html")&&e.some(n=>n.endsWith(".js"))?{type:"\u524D\u7AEF\u9879\u76EE",framework:"HTML/CSS/JS"}:{type:"\u672A\u77E5\u7C7B\u578B"}}detectProjectLanguages(e){let t={".js":"JavaScript",".mjs":"JavaScript (ES Modules)",".cjs":"JavaScript (CommonJS)",".jsx":"React JavaScript",".ts":"TypeScript",".tsx":"React TypeScript",".java":"Java",".class":"Java",".jar":"Java","pom.xml":"Java (Maven)","build.gradle":"Java (Gradle)",".py":"Python","requirements.txt":"Python","setup.py":"Python","pyproject.toml":"Python",".c":"C",".cpp":"C++",".h":"C/C++",".hpp":"C++","CMakeLists.txt":"C/C++ (CMake)",".go":"Go","go.mod":"Go",".rs":"Rust","Cargo.toml":"Rust",".php":"PHP","composer.json":"PHP (Composer)",".rb":"Ruby",Gemfile:"Ruby",".cs":"C#",".vb":"Visual Basic","packages.config":".NET",".html":"HTML",".css":"CSS",".scss":"SCSS",".less":"Less",".json":"JSON",".xml":"XML",".yml":"YAML",".yaml":"YAML",".md":"Markdown"},n={};e.forEach(a=>{if(t[a]){n[t[a]]=(n[t[a]]||0)+1;return}let c=a.lastIndexOf(".");if(c>-1){let l=a.substring(c);t[l]&&(n[t[l]]=(n[t[l]]||0)+1)}});let r=Object.entries(n).map(([a,c])=>({language:a,count:c})).sort((a,c)=>c.count-a.count),[o]=r;return{primaryLanguage:o?.language||null,languages:r,totalSourceFiles:r.reduce((a,c)=>a+c.count,0)}}analyzeDirectoryStructure(e){let t={directories:new Set,sourceFiles:[],configFiles:[],docFiles:[],testFiles:[]},n=[".js",".mjs",".cjs",".jsx",".ts",".tsx",".java",".py",".c",".cpp",".cc",".cxx",".h",".hpp",".go",".rs",".php",".rb",".cs",".kt",".kts",".scala",".swift",".m",".mm"],r=[".json",".yaml",".yml",".toml",".ini",".xml",".properties"],o=["package.json","tsconfig.json","pom.xml","build.gradle","settings.gradle","gradle.properties","Cargo.toml","go.mod","requirements.txt","setup.py","pyproject.toml","composer.json","Gemfile",".env",".env.example"];return e.forEach(i=>{let a=i.split("/");if(a.length>1&&t.directories.add(a[0]),i.includes("test")||i.includes("spec")||i.startsWith("test/")||i.startsWith("tests/")||i.includes("__tests__")||i.endsWith(".test.js")||i.endsWith(".test.ts")||i.endsWith(".spec.js")||i.endsWith(".spec.ts")||i.endsWith("Test.java")||i.endsWith("Tests.java")){t.testFiles.push(i);return}let c=i.split("/").pop()||"",l=c.includes(".")?"."+c.split(".").pop():"";i.startsWith("src/")||i.startsWith("lib/")||i.startsWith("app/"),n.includes(l)&&t.sourceFiles.push(i),(r.includes(l)||o.includes(c))&&t.configFiles.push(i),(l===".md"||l===".txt"||l===".rst"||c==="README"||c==="CHANGELOG"||c==="LICENSE"||c==="CONTRIBUTING")&&t.docFiles.push(i)}),{directories:Array.from(t.directories).sort(),sourceFiles:t.sourceFiles.sort(),configFiles:t.configFiles.sort(),docFiles:t.docFiles.sort(),testFiles:t.testFiles.sort()}}async detectVersions(e,t){try{return await kt.detectVersionsForLanguages(e.languages,t,e.configFiles)}catch{return{}}}async detectCodeStandards(e,t){try{return await kt.detectCodeStandardsForLanguages(t,e)}catch{return[]}}async analyzeDependencies(e,t){let n={};try{for(let r of t){let o=kt.getHandler(r);if(o){let i=await o.analyzeDependencies(e);n[r.toLowerCase()]=i}}}catch(r){console.error("\u4F9D\u8D56\u5206\u6790\u5931\u8D25:",r)}return n}analyzeCoreModules(e){let t=[],n=new Map;e.sourceFiles.forEach(o=>{let i=o.split("/");if(i.length>=2){let a=i.slice(0,2).join("/");n.has(a)||n.set(a,[]),n.get(a).push(o)}});let r={core:"\u6838\u5FC3\u4E1A\u52A1\u903B\u8F91",domain:"\u9886\u57DF\u6A21\u578B\u548C\u4E1A\u52A1\u89C4\u5219",business:"\u4E1A\u52A1\u903B\u8F91\u5C42",service:"\u670D\u52A1\u5C42",services:"\u670D\u52A1\u5C42",model:"\u6570\u636E\u6A21\u578B",models:"\u6570\u636E\u6A21\u578B",entity:"\u5B9E\u4F53\u7C7B",entities:"\u5B9E\u4F53\u7C7B",dao:"\u6570\u636E\u8BBF\u95EE\u5BF9\u8C61",repository:"\u6570\u636E\u4ED3\u5E93\u5C42",repositories:"\u6570\u636E\u4ED3\u5E93\u5C42",db:"\u6570\u636E\u5E93\u64CD\u4F5C",database:"\u6570\u636E\u5E93\u64CD\u4F5C",persistence:"\u6301\u4E45\u5316\u5C42",api:"API \u63A5\u53E3",rest:"REST API",controller:"\u63A7\u5236\u5668",controllers:"\u63A7\u5236\u5668",handler:"\u8BF7\u6C42\u5904\u7406\u5668",handlers:"\u8BF7\u6C42\u5904\u7406\u5668",endpoint:"\u7AEF\u70B9\u5B9A\u4E49",endpoints:"\u7AEF\u70B9\u5B9A\u4E49",route:"\u8DEF\u7531\u5B9A\u4E49",routes:"\u8DEF\u7531\u5B9A\u4E49",view:"\u89C6\u56FE\u5C42",views:"\u89C6\u56FE\u5C42",component:"\u7EC4\u4EF6",components:"\u7EC4\u4EF6",ui:"\u7528\u6237\u754C\u9762",page:"\u9875\u9762",pages:"\u9875\u9762",layout:"\u5E03\u5C40",layouts:"\u5E03\u5C40",template:"\u6A21\u677F",templates:"\u6A21\u677F",util:"\u5DE5\u5177\u51FD\u6570",utils:"\u5DE5\u5177\u51FD\u6570",helper:"\u8F85\u52A9\u51FD\u6570",helpers:"\u8F85\u52A9\u51FD\u6570",lib:"\u5E93\u6587\u4EF6",libs:"\u5E93\u6587\u4EF6",common:"\u516C\u5171\u6A21\u5757",shared:"\u5171\u4EAB\u6A21\u5757",config:"\u914D\u7F6E\u7BA1\u7406",configuration:"\u914D\u7F6E\u7BA1\u7406",settings:"\u8BBE\u7F6E\u7BA1\u7406",constant:"\u5E38\u91CF\u5B9A\u4E49",constants:"\u5E38\u91CF\u5B9A\u4E49",enum:"\u679A\u4E3E\u5B9A\u4E49",enums:"\u679A\u4E3E\u5B9A\u4E49",middleware:"\u4E2D\u95F4\u4EF6",middlewares:"\u4E2D\u95F4\u4EF6",interceptor:"\u62E6\u622A\u5668",interceptors:"\u62E6\u622A\u5668",filter:"\u8FC7\u6EE4\u5668",filters:"\u8FC7\u6EE4\u5668",guard:"\u5B88\u536B",guards:"\u5B88\u536B",client:"\u5BA2\u6237\u7AEF",clients:"\u5BA2\u6237\u7AEF",adapter:"\u9002\u914D\u5668",adapters:"\u9002\u914D\u5668",provider:"\u63D0\u4F9B\u5546",providers:"\u63D0\u4F9B\u5546",integration:"\u5916\u90E8\u96C6\u6210",integrations:"\u5916\u90E8\u96C6\u6210",auth:"\u8BA4\u8BC1\u6388\u6743",authentication:"\u8BA4\u8BC1",authorization:"\u6388\u6743",security:"\u5B89\u5168\u6A21\u5757",cli:"\u547D\u4EE4\u884C\u63A5\u53E3",cmd:"\u547D\u4EE4\u884C\u5DE5\u5177",script:"\u811A\u672C",scripts:"\u811A\u672C",tool:"\u5DE5\u5177",tools:"\u5DE5\u5177\u96C6",test:"\u6D4B\u8BD5",tests:"\u6D4B\u8BD5",spec:"\u6D4B\u8BD5\u89C4\u8303",mock:"\u6A21\u62DF\u6570\u636E",mocks:"\u6A21\u62DF\u6570\u636E",fixture:"\u6D4B\u8BD5\u5939\u5177",fixtures:"\u6D4B\u8BD5\u5939\u5177",type:"\u7C7B\u578B\u5B9A\u4E49",types:"\u7C7B\u578B\u5B9A\u4E49",interface:"\u63A5\u53E3\u5B9A\u4E49",interfaces:"\u63A5\u53E3\u5B9A\u4E49",schema:"\u6570\u636E\u7ED3\u6784\u5B9A\u4E49",schemas:"\u6570\u636E\u7ED3\u6784\u5B9A\u4E49",dto:"\u6570\u636E\u4F20\u8F93\u5BF9\u8C61",vo:"\u503C\u5BF9\u8C61",event:"\u4E8B\u4EF6",events:"\u4E8B\u4EF6",exception:"\u5F02\u5E38\u5904\u7406",exceptions:"\u5F02\u5E38\u5904\u7406",error:"\u9519\u8BEF\u5904\u7406",errors:"\u9519\u8BEF\u5904\u7406",validator:"\u9A8C\u8BC1\u5668",validators:"\u9A8C\u8BC1\u5668",decorator:"\u88C5\u9970\u5668",decorators:"\u88C5\u9970\u5668"};return n.forEach((o,i)=>{if(o.length>=2){let a=i.split("/").pop()||i,c=a.toLowerCase(),l=r[c]||`${a} \u6A21\u5757`;t.push({name:a.charAt(0).toUpperCase()+a.slice(1),description:l,files:o})}}),t.slice(0,10)}async generateProjectStructureDoc(e,t,n,r,o,i,a){let c=new Date().toISOString(),l=this.analyzeCoreModules(t),u=Object.keys(i).length>0?Object.entries(i).map(([d,f])=>`**${d}**: ${f}`).join(`
2183
+ `):"\u6682\u65E0\u7248\u672C\u4FE1\u606F",p=a.length>0?a.map(d=>`- ${d}`).join(`
2184
+ `):"\u6682\u65E0\u4EE3\u7801\u89C4\u8303\u914D\u7F6E",m=(await this.findEntryPoints(e,n,o)).map(d=>`- \`${d}\``).join(`
2185
+ `);return`# ${e.name} - \u9879\u76EE\u7ED3\u6784\u6587\u6863
1394
2186
 
1395
2187
  > \u6700\u540E\u66F4\u65B0: ${c}
1396
2188
  > \u7248\u672C: ${e.version}
@@ -1400,8 +2192,8 @@ ${Array.from(g.entries()).map(([w,v])=>`${w}: ${v}`).join(`
1400
2192
  **\u9879\u76EE\u540D\u79F0**: ${e.name}
1401
2193
  **\u7248\u672C**: ${e.version}
1402
2194
  **\u63CF\u8FF0**: ${e.description||"\u6682\u65E0\u63CF\u8FF0"}
1403
- **\u4E3B\u8981\u7F16\u7A0B\u8BED\u8A00**: ${s.primaryLanguage}
1404
- ${s.buildTool?`**\u6784\u5EFA\u5DE5\u5177**: ${s.buildTool}`:""}
2195
+ **\u4E3B\u8981\u7F16\u7A0B\u8BED\u8A00**: ${o.primaryLanguage}
2196
+ ${o.buildTool?`**\u6784\u5EFA\u5DE5\u5177**: ${o.buildTool}`:""}
1405
2197
 
1406
2198
  ### \u8FD0\u884C\u65F6\u7248\u672C
1407
2199
  ${u}
@@ -1422,24 +2214,24 @@ ${this.generateDirectoryTree(n)}
1422
2214
  ## \u7F16\u7A0B\u8BED\u8A00\u5206\u6790
1423
2215
 
1424
2216
  ### \u8BED\u8A00\u5206\u5E03
1425
- ${r.languages.length>0?r.languages.map(g=>`- **${g.language}**: ${g.count} \u4E2A\u6587\u4EF6`).join(`
2217
+ ${r.languages.length>0?r.languages.map(d=>`- **${d.language}**: ${d.count} \u4E2A\u6587\u4EF6`).join(`
1426
2218
  `):"\u6682\u65E0\u68C0\u6D4B\u5230\u7684\u7F16\u7A0B\u8BED\u8A00"}
1427
2219
 
1428
2220
  ---
1429
2221
 
1430
2222
  ## \u4E3B\u8981\u76EE\u5F55\u8BF4\u660E
1431
2223
 
1432
- ${this.generateDirectoryDescriptions(t.directories,s.languages)}
2224
+ ${this.generateDirectoryDescriptions(t.directories,o.languages)}
1433
2225
 
1434
2226
  ---
1435
2227
 
1436
2228
  ## \u6838\u5FC3\u6A21\u5757\u5206\u6790
1437
2229
 
1438
- ${l.length>0?l.map(g=>`### ${g.name}
2230
+ ${l.length>0?l.map(d=>`### ${d.name}
1439
2231
 
1440
- ${g.description}
2232
+ ${d.description}
1441
2233
 
1442
- **\u5305\u542B\u6587\u4EF6**: ${g.files.length} \u4E2A`).join(`
2234
+ **\u5305\u542B\u6587\u4EF6**: ${d.files.length} \u4E2A`).join(`
1443
2235
 
1444
2236
  `):"\u6682\u65E0\u6838\u5FC3\u6A21\u5757\u5206\u6790"}
1445
2237
 
@@ -1447,7 +2239,7 @@ ${g.description}
1447
2239
 
1448
2240
  ## \u6E90\u4EE3\u7801\u6587\u4EF6 (${t.sourceFiles.length} \u4E2A)
1449
2241
 
1450
- ${t.sourceFiles.length>0?t.sourceFiles.slice(0,50).map(g=>`- \`${g}\``).join(`
2242
+ ${t.sourceFiles.length>0?t.sourceFiles.slice(0,50).map(d=>`- \`${d}\``).join(`
1451
2243
  `)+(t.sourceFiles.length>50?`
1452
2244
 
1453
2245
  *...\u8FD8\u6709 ${t.sourceFiles.length-50} \u4E2A\u6587\u4EF6*`:""):"\u6682\u65E0\u6E90\u4EE3\u7801\u6587\u4EF6"}
@@ -1456,14 +2248,14 @@ ${t.sourceFiles.length>0?t.sourceFiles.slice(0,50).map(g=>`- \`${g}\``).join(`
1456
2248
 
1457
2249
  ## \u914D\u7F6E\u6587\u4EF6 (${t.configFiles.length} \u4E2A)
1458
2250
 
1459
- ${t.configFiles.length>0?t.configFiles.map(g=>`- \`${g}\``).join(`
2251
+ ${t.configFiles.length>0?t.configFiles.map(d=>`- \`${d}\``).join(`
1460
2252
  `):"\u6682\u65E0\u914D\u7F6E\u6587\u4EF6"}
1461
2253
 
1462
2254
  ---
1463
2255
 
1464
2256
  ## \u6587\u6863\u6587\u4EF6 (${t.docFiles.length} \u4E2A)
1465
2257
 
1466
- ${t.docFiles.length>0?t.docFiles.slice(0,20).map(g=>`- \`${g}\``).join(`
2258
+ ${t.docFiles.length>0?t.docFiles.slice(0,20).map(d=>`- \`${d}\``).join(`
1467
2259
  `)+(t.docFiles.length>20?`
1468
2260
 
1469
2261
  *...\u8FD8\u6709 ${t.docFiles.length-20} \u4E2A\u6587\u6863*`:""):"\u6682\u65E0\u6587\u6863\u6587\u4EF6"}
@@ -1472,7 +2264,7 @@ ${t.docFiles.length>0?t.docFiles.slice(0,20).map(g=>`- \`${g}\``).join(`
1472
2264
 
1473
2265
  ## \u6D4B\u8BD5\u6587\u4EF6 (${t.testFiles.length} \u4E2A)
1474
2266
 
1475
- ${t.testFiles.length>0?t.testFiles.slice(0,20).map(g=>`- \`${g}\``).join(`
2267
+ ${t.testFiles.length>0?t.testFiles.slice(0,20).map(d=>`- \`${d}\``).join(`
1476
2268
  `)+(t.testFiles.length>20?`
1477
2269
 
1478
2270
  *...\u8FD8\u6709 ${t.testFiles.length-20} \u4E2A\u6D4B\u8BD5\u6587\u4EF6*`:""):"\u6682\u65E0\u6D4B\u8BD5\u6587\u4EF6"}
@@ -1482,11 +2274,11 @@ ${t.testFiles.length>0?t.testFiles.slice(0,20).map(g=>`- \`${g}\``).join(`
1482
2274
  ## \u4F9D\u8D56\u5173\u7CFB
1483
2275
 
1484
2276
  ### \u751F\u4EA7\u4F9D\u8D56
1485
- ${e.dependencies?Object.entries(e.dependencies).map(([g,d])=>`- **${g}**: ${d}`).join(`
2277
+ ${e.dependencies?Object.entries(e.dependencies).map(([d,f])=>`- **${d}**: ${f}`).join(`
1486
2278
  `):"\u6682\u65E0\u751F\u4EA7\u4F9D\u8D56"}
1487
2279
 
1488
2280
  ### \u5F00\u53D1\u4F9D\u8D56
1489
- ${e.devDependencies?Object.entries(e.devDependencies).map(([g,d])=>`- **${g}**: ${d}`).join(`
2281
+ ${e.devDependencies?Object.entries(e.devDependencies).map(([d,f])=>`- **${d}**: ${f}`).join(`
1490
2282
  `):"\u6682\u65E0\u5F00\u53D1\u4F9D\u8D56"}
1491
2283
 
1492
2284
  ---
@@ -1494,22 +2286,21 @@ ${e.devDependencies?Object.entries(e.devDependencies).map(([g,d])=>`- **${g}**:
1494
2286
  ## \u5FEB\u901F\u5BFC\u822A
1495
2287
 
1496
2288
  ### \u5165\u53E3\u6587\u4EF6
1497
- ${this.findEntryPoints(e,n,s).map(g=>`- \`${g}\``).join(`
1498
- `)}
2289
+ ${m}
1499
2290
 
1500
2291
  ### \u6838\u5FC3\u6A21\u5757
1501
- ${this.findCoreModules(t.sourceFiles).map(g=>`- \`${g}\``).join(`
2292
+ ${this.findCoreModules(t.sourceFiles).map(d=>`- \`${d}\``).join(`
1502
2293
  `)}
1503
2294
 
1504
2295
  ---
1505
2296
 
1506
2297
  **\u6587\u6863\u751F\u6210\u65F6\u95F4**: ${c}
1507
2298
  **\u6587\u6863\u751F\u6210\u5DE5\u5177**: quickProjectScan \u5DE5\u5177
1508
- `}generateDirectoryTree(e){let t={};e.forEach(s=>{let i=s.split("/"),a=t;i.forEach((c,l)=>{a[c]||(a[c]=l===i.length-1?null:{}),a[c]!==null&&(a=a[c])})});function n(s,i="",a=!0){let c=Object.entries(s),l="";return c.forEach(([u,p],g)=>{let d=g===c.length-1,m=d?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",h=d?" ":"\u2502 ";l+=i+m+u+`
1509
- `,p!==null&&typeof p=="object"&&(l+=n(p,i+h,d))}),l}let r=n(t);return r?r.trim():""}generateDirectoryDescriptions(e,t){let n=Ue.getDirectoryDescriptionsForLanguages(t);return e.map(r=>{let s=n[r]||"\u9879\u76EE\u76EE\u5F55";return`### \`${r}/\`
1510
- ${s}`}).join(`
2299
+ `}generateDirectoryTree(e){let t={};e.forEach(o=>{let i=o.split("/"),a=t;i.forEach((c,l)=>{a[c]||(a[c]=l===i.length-1?null:{}),a[c]!==null&&(a=a[c])})});function n(o,i="",a=!0){let c=Object.entries(o),l="";return c.forEach(([u,p],g)=>{let m=g===c.length-1,d=m?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",f=m?" ":"\u2502 ";l+=i+d+u+`
2300
+ `,p!==null&&typeof p=="object"&&(l+=n(p,i+f,m))}),l}let r=n(t);return r?r.trim():""}generateDirectoryDescriptions(e,t){let n=kt.getDirectoryDescriptionsForLanguages(t);return e.map(r=>{let o=n[r]||"\u9879\u76EE\u76EE\u5F55";return`### \`${r}/\`
2301
+ ${o}`}).join(`
1511
2302
 
1512
- `)}findEntryPoints(e,t,n){let r=[];n.entryPoints&&n.entryPoints.length>0&&r.push(...n.entryPoints),e.main&&r.push(e.main),e.bin&&(typeof e.bin=="string"?r.push(e.bin):r.push(...Object.values(e.bin)));let s=process.cwd(),i=Ue.findEntryPointsForLanguages(n.languages,t,s);return r.push(...i),[...new Set(r)]}findCoreModules(e){let t=new Set;return e.forEach(n=>{let r=n.match(/^src\/([^\/]+)\//);r&&t.add(`src/${r[1]}/`)}),Array.from(t).sort()}buildProjectBasicInfo(e,t,n,r,s,i,a,c){let l=Nc(r.languages),p=this.analyzeCoreModules(t).map(T=>({name:T.name,description:T.description,fileCount:T.files.length})),g;s.primaryLanguage.includes("JavaScript")||s.primaryLanguage.includes("TypeScript")?gt("package-lock.json")?g="npm":gt("yarn.lock")?g="yarn":gt("pnpm-lock.yaml")?g="pnpm":g="npm":s.primaryLanguage.includes("Python")?gt("poetry.lock")?g="poetry":gt("Pipfile.lock")?g="pipenv":g="pip":s.primaryLanguage.includes("Java")?gt("pom.xml")?g="maven":gt("build.gradle")&&(g="gradle"):s.primaryLanguage.includes("Rust")?g="cargo":s.primaryLanguage.includes("Go")?g="go modules":s.primaryLanguage.includes("PHP")?g="composer":s.primaryLanguage.includes("Ruby")&&(g="bundler");let d={...e.dependencies||{}},m={...e.devDependencies||{}},h=Object.keys(d).length,w=Object.keys(m).length;if(c)for(let[T,f]of Object.entries(c))f.dependencies&&f.dependencies.forEach(y=>{let S=y.groupId&&y.artifactId?`${y.groupId}:${y.artifactId}`:y.name||"";S&&y.version&&(y.scope&&y.scope.toLowerCase().includes("test")?m[S]||(m[S]=y.version,w++):d[S]||(d[S]=y.version,h++))});return{projectName:e.name,version:e.version,description:e.description||"",primaryLanguage:r.primaryLanguage||s.primaryLanguage,languages:l,buildTool:s.buildTool,packageManager:g,runtime:s.primaryLanguage.includes("JavaScript")||s.primaryLanguage.includes("TypeScript")?"Node.js":s.primaryLanguage.includes("Java")?"JVM":s.primaryLanguage.includes("Python")?"Python":void 0,fileStats:{totalFiles:n.length,sourceFiles:t.sourceFiles.length,configFiles:t.configFiles.length,docFiles:t.docFiles.length,testFiles:t.testFiles.length},dependencies:d,devDependencies:m,dependencyCount:{production:h,development:w},detailedDependencies:c,runtimeVersions:Object.keys(i).length>0?i:void 0,codeStandards:a,entryPoints:this.findEntryPoints(e,n,s),configFiles:t.configFiles,coreModules:p.length>0?p:void 0,lastScanDate:new Date().toISOString()}}generateSummary(e,t,n,r){return`
2303
+ `)}async findEntryPoints(e,t,n){let r=[];n.entryPoints&&n.entryPoints.length>0&&r.push(...n.entryPoints),e.main&&r.push(e.main),e.bin&&(typeof e.bin=="string"?r.push(e.bin):r.push(...Object.values(e.bin)));let o=process.cwd(),i=await kt.findEntryPointsForLanguages(n.languages,t,o);return r.push(...i),[...new Set(r)]}findCoreModules(e){let t=new Set;return e.forEach(n=>{let r=n.match(/^src\/([^\/]+)\//);r&&t.add(`src/${r[1]}/`)}),Array.from(t).sort()}async buildProjectBasicInfo(e,t,n,r,o,i,a,c){let l=Vp(r.languages),p=this.analyzeCoreModules(t).map(T=>({name:T.name,description:T.description,fileCount:T.files.length})),g;o.primaryLanguage.includes("JavaScript")||o.primaryLanguage.includes("TypeScript")?an("package-lock.json")?g="npm":an("yarn.lock")?g="yarn":an("pnpm-lock.yaml")?g="pnpm":g="npm":o.primaryLanguage.includes("Python")?an("poetry.lock")?g="poetry":an("Pipfile.lock")?g="pipenv":g="pip":o.primaryLanguage.includes("Java")?an("pom.xml")?g="maven":an("build.gradle")&&(g="gradle"):o.primaryLanguage.includes("Rust")?g="cargo":o.primaryLanguage.includes("Go")?g="go modules":o.primaryLanguage.includes("PHP")?g="composer":o.primaryLanguage.includes("Ruby")&&(g="bundler");let m={...e.dependencies||{}},d={...e.devDependencies||{}},f=Object.keys(m).length,y=Object.keys(d).length;if(c)for(let[T,h]of Object.entries(c))h.dependencies&&h.dependencies.forEach(x=>{let P=x.groupId&&x.artifactId?`${x.groupId}:${x.artifactId}`:x.name||"";P&&x.version&&(x.scope&&x.scope.toLowerCase().includes("test")?d[P]||(d[P]=x.version,y++):m[P]||(m[P]=x.version,f++))});return{projectName:e.name,version:e.version,description:e.description||"",primaryLanguage:r.primaryLanguage||o.primaryLanguage,languages:l,buildTool:o.buildTool,packageManager:g,runtime:o.primaryLanguage.includes("JavaScript")||o.primaryLanguage.includes("TypeScript")?"Node.js":o.primaryLanguage.includes("Java")?"JVM":o.primaryLanguage.includes("Python")?"Python":void 0,fileStats:{totalFiles:n.length,sourceFiles:t.sourceFiles.length,configFiles:t.configFiles.length,docFiles:t.docFiles.length,testFiles:t.testFiles.length},dependencies:m,devDependencies:d,dependencyCount:{production:f,development:y},detailedDependencies:c,runtimeVersions:Object.keys(i).length>0?i:void 0,codeStandards:a,entryPoints:await this.findEntryPoints(e,n,o),configFiles:t.configFiles,coreModules:p.length>0?p:void 0,lastScanDate:new Date().toISOString()}}generateSummary(e,t,n,r){return`
1513
2304
  \u{1F4E6} \u9879\u76EE: ${e.name} (v${e.version})
1514
2305
  \u{1F310} \u4E3B\u8981\u8BED\u8A00: ${r.primaryLanguage}
1515
2306
  ${r.buildTool?`\u{1F527} \u6784\u5EFA\u5DE5\u5177: ${r.buildTool}`:""}
@@ -1518,7 +2309,7 @@ ${r.buildTool?`\u{1F527} \u6784\u5EFA\u5DE5\u5177: ${r.buildTool}`:""}
1518
2309
  \u2699\uFE0F \u914D\u7F6E\u6587\u4EF6: ${t.configFiles.length} \u4E2A
1519
2310
  \u{1F4DA} \u6587\u6863\u6587\u4EF6: ${t.docFiles.length} \u4E2A
1520
2311
  \u{1F9EA} \u6D4B\u8BD5\u6587\u4EF6: ${t.testFiles.length} \u4E2A
1521
- `}formatAction(e){return"quickProjectScan()"}formatObservation(e){return String(e)}},Jc=new pt;Kt=Jc});var ei={};j(ei,{FINISH_TOOL:()=>hp,FinishTool:()=>vo,extractFinishInfo:()=>Zs,finish:()=>mp,finishTool:()=>fp,isFinishResult:()=>yp,isFinishTool:()=>Qs});function mp(o){return Xs.execute(o)}function Qs(o){return o==="finish"}function Zs(o){if(!o||!o.function||o.function.name!=="finish")return null;try{let e=JSON.parse(o.function.arguments);return{answer:e.answer||"",success:e.success!==void 0?e.success:!0}}catch{return null}}function yp(o){return o&&typeof o=="object"&&o.completed===!0&&typeof o.answer=="string"}var vo,Xs,fp,hp,wo=C(()=>{V();vo=class extends ${getDefinition(){return{name:"finish",description:`Call this tool when you have completed the task and want to provide the final answer.
2312
+ `}formatAction(e){return"quickProjectScan()"}formatObservation(e){return String(e)}},Qp=new cn;fr=Qp});var vc={};B(vc,{FINISH_TOOL:()=>$h,FinishTool:()=>Ti,extractFinishInfo:()=>bc,finish:()=>kh,finishTool:()=>Eh,isFinishResult:()=>Ih,isFinishTool:()=>wc});function kh(s){return Cc.execute(s)}function wc(s){return s==="finish"}function bc(s){if(!s||!s.function||s.function.name!=="finish")return null;try{let e=JSON.parse(s.function.arguments);return{answer:e.answer||"",success:e.success!==void 0?e.success:!0}}catch{return null}}function Ih(s){return s&&typeof s=="object"&&s.completed===!0&&typeof s.answer=="string"}var Ti,Cc,Eh,$h,Pi=S(()=>{G();Ti=class extends R{getDefinition(){return{name:"finish",description:`Call this tool when you have completed the task and want to provide the final answer.
1522
2313
 
1523
2314
  IMPORTANT: This is the RECOMMENDED way to signal task completion.
1524
2315
 
@@ -1538,10 +2329,22 @@ Example usage:
1538
2329
  finish({
1539
2330
  answer: "Successfully implemented the user authentication system. Created 3 new files: UserController.java, UserService.java, and SecurityConfig.java. Implemented JWT-based authentication with role-based access control. All tests are passing.",
1540
2331
  success: true
1541
- })`,input_schema:{type:"object",properties:{answer:{type:"string",description:"Comprehensive summary of what was accomplished, including key results and any important details"},success:{type:"boolean",description:"Whether the task completed successfully (defaults to true)",default:!0}},required:["answer"]}}}execute(e){return{completed:!0,answer:e.answer,success:e.success!==void 0?e.success:!0}}formatAction(e){let t=e.success!==!1?"\u6210\u529F\u5B8C\u6210":"\u5B8C\u6210\uFF08\u6709\u95EE\u9898\uFF09",n=e.answer.length>50?`${e.answer.substring(0,50)}...`:e.answer;return`finish(status=${t}, answer="${n}")`}formatObservation(e){return"\u4EFB\u52A1\u5DF2\u5B8C\u6210"}shouldPrintObservation(e){return!1}},Xs=new vo;fp=Xs,hp=Xs.getDefinition()});var ni={};j(ni,{executePlanTask:()=>xp,getGlobalSession:()=>Cp,resumePlanTask:()=>Sp,setGlobalSession:()=>ti});import k from"chalk";function ti(o){z=o}function Cp(){return z}async function xp(o,e=1,t={}){let n=t.useLLMSummary!==void 0?t.useLLMSummary:!0,r=new Ve,s=new ze(r),i=new He(r,s),a=new Je(n),{callModelAPI:c}=await Promise.resolve().then(()=>(ve(),Gt)),{AnchorInjector:l}=await Promise.resolve().then(()=>(cr(),Js)),u=new l(o,c),p=Yt(),g={useLLMDisclosure:t.useLLMDisclosure!==void 0?t.useLLMDisclosure:!0,useLLMSummary:t.useLLMSummary!==void 0?t.useLLMSummary:!0,verbose:t.verbose||!1},d=y=>{z?z.log(y):console.log(y)},m=y=>{z?z.info(y):console.log(k.blue(y))},h=y=>{z?z.success(y):console.log(k.green(y))},w=y=>{z?z.warning(y):console.log(k.yellow(y))},v=y=>{z?z.error(y):console.log(k.red(y))},T=" ".repeat(e-1),f=new bo({log:d,info:m,success:h,warning:w,error:v});try{let y=await import("fs"),S=await import("path");try{let R=S.join(process.cwd(),".nium/project/project.json");if(y.existsSync(R)){let O=y.statSync(R);(Date.now()-O.mtimeMs)/(1e3*60*60)>24&&w("\u26A0\uFE0F \u9879\u76EE\u7ED3\u6784\u6587\u6863\u5DF2\u8D85\u8FC724\u5C0F\u65F6\uFF0C\u5EFA\u8BAE\u66F4\u65B0")}else{m("\u{1F4CB} \u9996\u6B21\u6267\u884C\u4EFB\u52A1\uFF0C\u6B63\u5728\u626B\u63CF\u9879\u76EE\u7ED3\u6784...");let{quickProjectScan:O}=await Promise.resolve().then(()=>(Ys(),Gc));await O(),h(`\u2705 \u9879\u76EE\u7ED3\u6784\u626B\u63CF\u5B8C\u6210
1542
- `)}}catch{w("\u9879\u76EE\u7ED3\u6784\u626B\u63CF\u5931\u8D25\uFF0C\u5C06\u7EE7\u7EED\u6267\u884C\u4EFB\u52A1")}d(""),d(`${T}${"\u2550".repeat(60-e*2)}`),m(`${T}\u{1F4CB} \u5F00\u59CB\u89C4\u5212\u4EFB\u52A1 (\u5D4C\u5957\u5C42\u7EA7: ${e})`),d(`${T}${"\u2550".repeat(60-e*2)}`),d("");let E=p.getAllSubAgents(),P=await Zn(o,E);r.initializeTask(o,P),P.taskId&&St(P.taskId);let L=vp(er(P),e);d(L),d(""),f.showTaskStart(o,P.tasks.length,e);for(let R=0;R<P.tasks.length;R++){let O=P.tasks[R],K=O.step;f.showStepProgress(K,P.tasks.length,O,e),r.plan.currentStep=K,P.taskId&&await at(P.taskId,K,"in_progress");try{let U=Bc(O,p),I=await i.buildIsolatedContext(K,O.description,U?.prompt||"",g.useLLMDisclosure,O.allowedTools);U?await qc(K,O.description,U,I,r,a,s,p,g,{log:d,info:m,success:h,warning:w,error:v},O.allowedTools):await Kc(O.description,I,r,{log:d,info:m},O.allowedTools),f.showStepComplete(K,P.tasks.length,O,e),P.taskId&&await at(P.taskId,K,"completed")}catch(U){let I=U instanceof Error?U.message:String(U);throw f.showStepError(K,P.tasks.length,I,e),w(`${T}\u4E2D\u6B62\u540E\u7EED\u6B65\u9AA4\u6267\u884C`),r.recordStepCompletion(K,`\u5931\u8D25: ${I}`,{success:!1,error:I}),U}}return f.showTaskComplete(P.tasks.length,P.tasks.length,e),vt(),{success:!0,taskId:P.taskId,completedSteps:P.tasks.length,plan:P,planMarkdown:P.markdown,tasks:P.tasks}}catch(y){vt();let S=y instanceof Error?y.message:String(y);throw v(`${T}\u274C \u89C4\u5212\u4EFB\u52A1\u6267\u884C\u5931\u8D25: ${S}`),y}}async function Sp(o,e=0,t={}){let{loadTaskPlan:n}=await Promise.resolve().then(()=>($e(),We)),r=n(o);if(!r)throw new Error(`\u65E0\u6CD5\u52A0\u8F7D\u4EFB\u52A1\u8BA1\u5212: ${o}`);let s=new Ve,i=new ze(s),a=new He(s,i),c=new Je,l=Yt(),u={useLLMDisclosure:t.useLLMDisclosure!==void 0?t.useLLMDisclosure:!0,useLLMSummary:t.useLLMSummary!==void 0?t.useLLMSummary:!0,verbose:t.verbose||!1},p=f=>{z?z.log(f):console.log(f)},g=f=>{z?z.info(f):console.log(k.blue(f))},d=f=>{z?z.success(f):console.log(k.green(f))},m=f=>{z?z.warning(f):console.log(k.yellow(f))},h=f=>{z?z.error(f):console.log(k.red(f))};p(k.cyan(`[\u4EFB\u52A1\u6062\u590D] \u6B63\u5728\u6062\u590D\u4EFB\u52A1: ${o}`)),p(k.gray(`\u4ECE\u6B65\u9AA4 ${e||1} \u5F00\u59CB\u6267\u884C`));let w=1,v="",T=new bo({log:p,info:g,success:d,warning:m,error:h});try{s.initializeTask(r.taskId,r),r.taskId&&St(r.taskId),p(""),p(k.cyan("\u2550".repeat(60))),g("\u{1F4CB} \u6062\u590D\u4EFB\u52A1\u6267\u884C"),p(k.cyan("\u2550".repeat(60))),p(""),T.showTaskStart(r.taskId,r.tasks.length,w);let f=e>0?e-1:0;for(let y=f;y<r.tasks.length;y++){let S=r.tasks[y],E=S.step;if(T.showStepProgress(E,r.tasks.length,S,w),s.plan.currentStep=E,r.taskId){let{updateTaskStatus:P}=await Promise.resolve().then(()=>($e(),We));await P(r.taskId,E,"in_progress")}try{let P=Bc(S,l),L=await a.buildIsolatedContext(E,S.description,P?.prompt||"",u.useLLMDisclosure,S.allowedTools);if(P?await qc(E,S.description,P,L,s,c,i,l,u,{log:p,info:g,success:d,warning:m,error:h},S.allowedTools):await Kc(S.description,L,s,{log:p,info:g},S.allowedTools),T.showStepComplete(E,r.tasks.length,S,w),r.taskId){let{updateTaskStatus:R}=await Promise.resolve().then(()=>($e(),We));await R(r.taskId,E,"completed")}}catch(P){let L=P instanceof Error?P.message:String(P);throw T.showStepError(E,r.tasks.length,L,w),m(`${v}\u4E2D\u6B62\u540E\u7EED\u6B65\u9AA4\u6267\u884C`),s.recordStepCompletion(E,`\u5931\u8D25: ${L}`,{success:!1,error:L}),P}}return T.showTaskComplete(r.tasks.length,r.tasks.length,w),vt(),{success:!0,taskId:r.taskId,completedSteps:r.tasks.length-f,resumedFrom:e||1}}catch(f){vt();let y=f instanceof Error?f.message:String(f);throw h(`${v}\u274C \u4EFB\u52A1\u6062\u590D\u6267\u884C\u5931\u8D25: ${y}`),f}}function vp(o,e){return e<=1?o:o.split(`
1543
- `).map(r=>{if(r.trim().startsWith("#")){let s=r.match(/^#+/)?.[0].length||0,i=Math.min(s+e-1,6),a="#".repeat(i);return r.replace(/^#+/,a)}return r}).join(`
1544
- `)}function Bc(o,e){return o.subAgent&&o.subAgent!=="default"?e.getSubAgent(o.subAgent):null}async function qc(o,e,t,n,r,s,i,a,c,l,u){let{log:p,info:g,error:d}=l,m=Date.now();g(`\u{1F527} \u4F7F\u7528\u5B50\u667A\u80FD\u4F53: ${t.name}`),p(k.gray(`\u63CF\u8FF0: ${t.description}`)),u&&u.length>0&&p(k.gray(`\u6CE8\u610F: \u5B50\u667A\u80FD\u4F53 ${t.name} \u4E0D\u53D7\u6B65\u9AA4\u5DE5\u5177\u9650\u5236\u5F71\u54CD`)),p("");try{let{SYSTEM_PROMPT:h}=await Promise.resolve().then(()=>(it(),Fs)),w=[{role:"system",content:h},...n.filter(f=>f.role!=="system"),...n.filter(f=>f.role==="system"&&f!==n[0])],v=await Yc(w,e,l,void 0,t);await wp(o,v,r,s,i,c,l);let T=Date.now()-m;a.recordAgentPerformance(t.name,!0,T)}catch(h){let w=Date.now()-m;throw a.recordAgentPerformance(t.name,!1,w),h}}async function Kc(o,e,t,n,r){let{log:s,info:i}=n;i("\u{1F916} \u4F7F\u7528\u9ED8\u8BA4React\u667A\u80FD\u4F53"),r&&r.length>0&&s(k.gray(`\u5DE5\u5177\u9650\u5236: ${r.join(", ")}`)),s("");let{SYSTEM_PROMPT:a}=await Promise.resolve().then(()=>(it(),Fs)),c=[{role:"system",content:a},...e.filter(l=>l.role!=="system"),...e.filter(l=>l.role==="system")];await Yc(c,o,n,r)}async function Yc(o,e,t,n,r=null){let{log:s,error:i}=t,{MODEL:a}=await Promise.resolve().then(()=>(le(),wt)),{callModelAPI:c}=await Promise.resolve().then(()=>(ve(),Gt)),{isThinkTool:l,extractThought:u}=await Promise.resolve().then(()=>(Xn(),Ms)),{isFinishTool:p,extractFinishInfo:g}=await Promise.resolve().then(()=>(wo(),ei)),{getToolDefinitions:d}=await Promise.resolve().then(()=>(Ht(),ri)),{tools:m,toolInstances:h,extractToolResult:w}=await Promise.resolve().then(()=>(Re(),ur)),{saveSession:v}=await Promise.resolve().then(()=>(Ne(),Zi)),{logDebug:T,logWarn:f}=await Promise.resolve().then(()=>(Y(),Yo)),{AnchorInjector:y}=await Promise.resolve().then(()=>(cr(),Js)),S=[...o],E=0,P=50,L=0,R=new y(e,c),O=d(),K=n&&n.length>0?O.filter(U=>n.includes(U.name)):O;for(n&&n.length>0&&T(`\u672C\u6B65\u9AA4\u53EF\u7528\u5DE5\u5177: ${K.map(U=>U.name).join(", ")}`);E<P;){E++,T(`Loop iteration ${E}`);try{let U=await R.injectAnchors({taskDescription:e,iterations:E,messages:S,lastSemanticCheckIteration:L,callModelAPI:c}),{messages:I,lastSemanticCheckIteration:oe}=U;S=I,L=oe,v(S,e);let te=await c({model:a(),messages:S,temperature:.1,tools:K}),on=te.choices[0].message.tool_calls;if(te.choices[0].finish_reason==="stop"){let{content:F}=te.choices[0].message;if(F&&F.trim()){if(r?.finalAnswerCallback)try{await r.finalAnswerCallback(F)}catch(Fe){let{logError:Oe}=await Promise.resolve().then(()=>(Y(),Yo));Oe(`Error in finalAnswerCallback: ${Fe}`)}s(k.green("\u4EFB\u52A1\u5B8C\u6210:")),s(F),s("")}break}if(!on||on.length===0){let{content:F}=te.choices[0].message;F&&F.trim()&&(s(k.yellow(F)),s(""));continue}let J=on[0],Te=J.function.name;if(n&&n.length>0&&!n.includes(Te)){let F=`Error: \u5DE5\u5177 '${Te}' \u672A\u5728\u672C\u6B65\u9AA4\u7684\u6388\u6743\u5217\u8868\u4E2D\u3002\u5141\u8BB8\u4F7F\u7528\u7684\u5DE5\u5177: ${n.join(", ")}`;i(F),S.push({role:"assistant",content:null,tool_calls:[J]}),S.push({role:"tool",tool_call_id:J.id,content:F});continue}let kr;try{kr=JSON.parse(J.function.arguments)}catch{i(`\u89E3\u6790\u5DE5\u5177\u53C2\u6570\u5931\u8D25: ${J.function.arguments}`),S.push({role:"assistant",content:null,tool_calls:[J]}),S.push({role:"tool",tool_call_id:J.id,content:"Error: Invalid JSON arguments"});continue}if(l(Te)){let F=u(J);F&&(s(k.cyan(`\u{1F4AD} Think: ${F}`)),s("")),S.push({role:"assistant",content:null,tool_calls:[J]}),S.push({role:"tool",tool_call_id:J.id,content:"Noted. Continue with your action."});continue}if(p(Te)){let F=g(J);if(F){let{answer:Fe,success:Oe}=F;if(r?.finalAnswerCallback)try{await r.finalAnswerCallback(Fe)}catch(Dl){f(`Error in finalAnswerCallback: ${Dl}`)}let Rl=Oe?"\u2705":"\u26A0\uFE0F";s(k.green(`${Rl} \u4EFB\u52A1\u5B8C\u6210 (\u901A\u8FC7 finish \u5DE5\u5177):`)),s(Fe),s(""),S.push({role:"assistant",content:null,tool_calls:[J]}),S.push({role:"tool",tool_call_id:J.id,content:"Task completed successfully."}),S.push({role:"assistant",content:Fe});break}}if(!m[Te]){let F=`Error: Unknown tool '${Te}'`;i(F),S.push({role:"assistant",content:null,tool_calls:[J]}),S.push({role:"tool",tool_call_id:J.id,content:F});continue}let Er=d().find(F=>F.name===Te);if(Er&&Er.input_schema&&Er.input_schema.required){let Fe=(Er.input_schema.required||[]).filter(Oe=>kr[Oe]===void 0);if(Fe.length>0){let Oe=`Error: Missing required parameters: ${Fe.join(", ")}`;i(Oe),S.push({role:"assistant",content:null,tool_calls:[J]}),S.push({role:"tool",tool_call_id:J.id,content:Oe});continue}}let ft=h[Te],Ml=ft?ft.formatAction(kr):`${Te}()`;s(k.blue(`\u{1F527} \u884C\u52A8: ${Ml}`)),s("");let Pr=await m[Te](kr),Il=w(Pr),Al=ft?ft.shouldPrintObservation(Pr):!0,Ll=ft?ft.formatObservation(Pr):String(Pr);Al&&(s(k.yellow(`\u{1F4CA} \u89C2\u5BDF: ${Ll}`)),s("")),S.push({role:"assistant",content:null,tool_calls:[J]}),S.push({role:"tool",tool_call_id:J.id,content:String(Il)}),v(S,e)}catch(U){throw i(`\u9519\u8BEF: ${U.message}`),v(S,e),U}}if(E>=P)throw i("\u9519\u8BEF: \u5DF2\u8FBE\u5230\u6700\u5927\u8FED\u4EE3\u6B21\u6570"),v(S,e),new Error("Maximum iterations reached");return S}async function wp(o,e,t,n,r,s,i){let{info:a,log:c}=i,l=await n.extractSummary(e),u=n.extractMetadata(e);u.success=!0,t.recordStepCompletion(o,l,u,r),s.verbose&&(a(`\u6B65\u9AA4 ${o} \u6458\u8981\u5DF2\u8BB0\u5F55\u5230\u5168\u5C40\u4E0A\u4E0B\u6587`),c(""),c(k.gray("\u2500\u2500\u2500 \u6B65\u9AA4\u6267\u884C\u6458\u8981 \u2500\u2500\u2500")),c(k.gray(`\u6458\u8981: ${l}`)),c(k.gray(`\u5DE5\u5177: ${u.toolsUsed.join(", ")}`)),c(k.gray(`\u6587\u4EF6: ${u.filesAccessed.join(", ")}`)),c(k.gray(`\u8FED\u4EE3: ${u.iterations} \u6B21`)))}var bo,z,To=C(()=>{$e();ko();Ne();Gs();bo=class{startTime;stepStartTime=null;log;info;success;warning;error;constructor(e){this.startTime=Date.now(),this.log=e.log,this.info=e.info,this.success=e.success,this.warning=e.warning,this.error=e.error}showTaskStart(e,t,n=1){let r=" ".repeat(n-1);this.log(""),this.log(k.cyan(`${r}\u2554${"\u2550".repeat(58-n*2)}\u2557`)),this.log(k.cyan(`${r}\u2551`)+k.bold.white(" \u{1F680} \u5F00\u59CB\u6267\u884C\u4EFB\u52A1\u8BA1\u5212")+k.cyan(` (\u5171${t}\u6B65)`.padEnd(58-n*2-13))+k.cyan("\u2551")),this.log(k.cyan(`${r}\u255A${"\u2550".repeat(58-n*2)}\u255D`)),this.log("")}showStepProgress(e,t,n,r=1){this.stepStartTime=Date.now();let s=" ".repeat(r-1),i=Math.round(e/t*100),a=this.createProgressBar(i,30);this.log(""),this.log(k.blue(`${s}\u250C${"\u2500".repeat(58-r*2)}\u2510`)),this.log(k.blue(`${s}\u2502`)+` \u6B65\u9AA4 ${e}/${t} (${i}%)`.padEnd(60-r*2)+k.blue("\u2502")),this.log(k.blue(`${s}\u2502`)+` ${a}`.padEnd(60-r*2)+k.blue("\u2502")),this.log(k.blue(`${s}\u2502`)+k.cyan(` \u{1F4CC} ${n.description}`.substring(0,58-r*2)).padEnd(60-r*2)+k.blue("\u2502")),this.log(k.blue(`${s}\u2502`)+k.gray(` \u{1F916} \u667A\u80FD\u4F53: ${n.subAgent}`.substring(0,58-r*2)).padEnd(60-r*2)+k.blue("\u2502")),this.log(k.blue(`${s}\u2514${"\u2500".repeat(58-r*2)}\u2518`)),this.log("")}showStepComplete(e,t,n,r=1){let s=" ".repeat(r-1),i=this.stepStartTime?this.formatDuration(Date.now()-this.stepStartTime):"",a=Math.round(e/t*100);this.success(`${s}\u2705 \u6B65\u9AA4 ${e}/${t} \u5B8C\u6210${k.gray(` (${i})`)}`),this.log("")}showTaskComplete(e,t,n=1){let r=" ".repeat(n-1),s=this.formatDuration(Date.now()-this.startTime),i=Math.round(e/t*100);this.log(""),this.log(k.green(`${r}\u2554${"\u2550".repeat(58-n*2)}\u2557`)),this.log(k.green(`${r}\u2551`)+k.bold.white(" \u{1F389} \u4EFB\u52A1\u6267\u884C\u5B8C\u6210!")+k.green("".padEnd(58-n*2-12))+k.green("\u2551")),this.log(k.green(`${r}\u2551`)+` \u5B8C\u6210\u8FDB\u5EA6: ${e}/${t} (${i}%)`.padEnd(60-n*2)+k.green("\u2551")),this.log(k.green(`${r}\u2551`)+` \u603B\u8017\u65F6: ${s}`.padEnd(60-n*2)+k.green("\u2551")),this.log(k.green(`${r}\u255A${"\u2550".repeat(58-n*2)}\u255D`)),this.log("")}showStepError(e,t,n,r=1){let s=" ".repeat(r-1);this.log(""),this.error(`${s}\u274C \u6B65\u9AA4 ${e}/${t} \u6267\u884C\u5931\u8D25`),this.error(`${s} \u9519\u8BEF: ${n.substring(0,100)}`),this.log("")}createProgressBar(e,t=30){let n=Math.round(e/100*t),r=t-n;return`${k.green("\u2588".repeat(n))+k.gray("\u2591".repeat(r))} ${e}%`}formatDuration(e){if(e<1e3)return`${e}ms`;if(e<6e4)return`${(e/1e3).toFixed(1)}s`;let t=Math.floor(e/6e4),n=(e%6e4/1e3).toFixed(0);return`${t}m ${n}s`}},z=null});import bp from"chalk";async function gr(o){return await Xc.execute(o)}var De,Xc,pr,oi=C(()=>{V();De=class o extends ${static nestingLevel=0;static MAX_NESTING_LEVEL=2;getDefinition(){let e=o.nestingLevel,t=o.MAX_NESTING_LEVEL,n="USE THIS TOOL FIRST for COMPLEX tasks! This is your PRIMARY tool for handling multi-step, cross-component work.";return e===t-1?n="USE THIS TOOL SPARINGLY for VERY COMPLEX sub-tasks! This is your last level of nesting.":e>=t&&(n="DO NOT USE THIS TOOL - maximum nesting level reached!"),{name:"plan",description:`${n}
2332
+ })`,input_schema:{type:"object",properties:{answer:{type:"string",description:"Comprehensive summary of what was accomplished, including key results and any important details"},success:{type:"boolean",description:"Whether the task completed successfully (defaults to true)",default:!0}},required:["answer"]}}}execute(e){return{completed:!0,answer:e.answer,success:e.success!==void 0?e.success:!0}}formatAction(e){let t=e.success!==!1?"\u6210\u529F\u5B8C\u6210":"\u5B8C\u6210\uFF08\u6709\u95EE\u9898\uFF09",n=e.answer.length>50?`${e.answer.substring(0,50)}...`:e.answer;return`finish(status=${t}, answer="${n}")`}formatObservation(e){return"\u4EFB\u52A1\u5DF2\u5B8C\u6210"}shouldPrintObservation(e){return!1}},Cc=new Ti;Eh=Cc,$h=Cc.getDefinition()});var Pc={};B(Pc,{executePlanTask:()=>Ah,getGlobalSession:()=>Mh,resumePlanTask:()=>Rh,setGlobalSession:()=>Tc});import z from"chalk";function Tc(s){re=s}function Mh(){return re}async function Ah(s,e=1,t={}){let n=t.useLLMSummary!==void 0?t.useLLMSummary:!0,r=new It,o=new Mt(r),i=new At(r,o),a=new Rt(n),{callModelAPI:c}=await Promise.resolve().then(()=>(Ie(),pr)),{AnchorInjector:l}=await Promise.resolve().then(()=>(Us(),dc)),u=new l(s,c),p=hr(),g={useLLMDisclosure:t.useLLMDisclosure!==void 0?t.useLLMDisclosure:!0,useLLMSummary:t.useLLMSummary!==void 0?t.useLLMSummary:!0,verbose:t.verbose||!1},m=x=>{re?re.log(x):console.log(x)},d=x=>{re?re.info(x):console.log(z.blue(x))},f=x=>{re?re.success(x):console.log(z.green(x))},y=x=>{re?re.warning(x):console.log(z.yellow(x))},w=x=>{re?re.error(x):console.log(z.red(x))},T=" ".repeat(e-1),h=new ki({log:m,info:d,success:f,warning:y,error:w});try{let x=await import("fs"),P=await import("path");try{let j=P.join(process.cwd(),".nium/project/project.json");if(x.existsSync(j)){let L=x.statSync(j);(Date.now()-L.mtimeMs)/(1e3*60*60)>24&&y("\u26A0\uFE0F \u9879\u76EE\u7ED3\u6784\u6587\u6863\u5DF2\u8D85\u8FC724\u5C0F\u65F6\uFF0C\u5EFA\u8BAE\u66F4\u65B0")}else{d("\u{1F4CB} \u9996\u6B21\u6267\u884C\u4EFB\u52A1\uFF0C\u6B63\u5728\u626B\u63CF\u9879\u76EE\u7ED3\u6784...");let{quickProjectScan:L}=await Promise.resolve().then(()=>(Sc(),Zp));await L(),f(`\u2705 \u9879\u76EE\u7ED3\u6784\u626B\u63CF\u5B8C\u6210
2333
+ `)}}catch{y("\u9879\u76EE\u7ED3\u6784\u626B\u63CF\u5931\u8D25\uFF0C\u5C06\u7EE7\u7EED\u6267\u884C\u4EFB\u52A1")}m(""),d(`${T}\u5F00\u59CB\u89C4\u5212\u4EFB\u52A1 (\u5C42\u7EA7 ${e})`);let k=p.getAllSubAgents(),b=await As(s,k);r.initializeTask(s,b),b.taskId&&An(b.taskId);let U=Lh(Rs(b),e);m(U),m(""),h.showTaskStart(s,b.tasks.length,e);for(let j=0;j<b.tasks.length;j++){let L=b.tasks[j],M=L.step;h.showStepProgress(M,b.tasks.length,L,e),r.plan.currentStep=M,b.taskId&&await nn(b.taskId,M,"in_progress");try{let $=eg(L,p),I=await i.buildIsolatedContext(M,L.description,$?.prompt||"",g.useLLMDisclosure,L.allowedTools);$?await tg(M,L.description,$,I,r,a,o,p,g,{log:m,info:d,success:f,warning:y,error:w},L.allowedTools):await ng(L.description,I,r,{log:m,info:d},L.allowedTools),h.showStepComplete(M,b.tasks.length,L,e),b.taskId&&await nn(b.taskId,M,"completed")}catch($){let I=$ instanceof Error?$.message:String($);throw h.showStepError(M,b.tasks.length,I,e),y(`${T}\u4E2D\u6B62\u540E\u7EED\u6B65\u9AA4\u6267\u884C`),r.recordStepCompletion(M,`\u5931\u8D25: ${I}`,{success:!1,error:I}),$}}return h.showTaskComplete(b.tasks.length,b.tasks.length,e),Rn(),{success:!0,taskId:b.taskId,completedSteps:b.tasks.length,plan:b,planMarkdown:b.markdown,tasks:b.tasks}}catch(x){Rn();let P=x instanceof Error?x.message:String(x);throw w(`${T}\u274C \u89C4\u5212\u4EFB\u52A1\u6267\u884C\u5931\u8D25: ${P}`),x}}async function Rh(s,e=0,t={}){let{loadTaskPlan:n}=await Promise.resolve().then(()=>(Qe(),$t)),r=n(s);if(!r)throw new Error(`\u65E0\u6CD5\u52A0\u8F7D\u4EFB\u52A1\u8BA1\u5212: ${s}`);let o=new It,i=new Mt(o),a=new At(o,i),c=new Rt,l=hr(),u={useLLMDisclosure:t.useLLMDisclosure!==void 0?t.useLLMDisclosure:!0,useLLMSummary:t.useLLMSummary!==void 0?t.useLLMSummary:!0,verbose:t.verbose||!1},p=h=>{re?re.log(h):console.log(h)},g=h=>{re?re.info(h):console.log(z.blue(h))},m=h=>{re?re.success(h):console.log(z.green(h))},d=h=>{re?re.warning(h):console.log(z.yellow(h))},f=h=>{re?re.error(h):console.log(z.red(h))};p(z.cyan(`[\u4EFB\u52A1\u6062\u590D] \u6B63\u5728\u6062\u590D\u4EFB\u52A1: ${s}`)),p(z.gray(`\u4ECE\u6B65\u9AA4 ${e||1} \u5F00\u59CB\u6267\u884C`));let y=1,w="",T=new ki({log:p,info:g,success:m,warning:d,error:f});try{o.initializeTask(r.taskId,r),r.taskId&&An(r.taskId),p(""),g("\u6062\u590D\u4EFB\u52A1\u6267\u884C"),T.showTaskStart(r.taskId,r.tasks.length,y);let h=e>0?e-1:0;for(let x=h;x<r.tasks.length;x++){let P=r.tasks[x],k=P.step;if(T.showStepProgress(k,r.tasks.length,P,y),o.plan.currentStep=k,r.taskId){let{updateTaskStatus:b}=await Promise.resolve().then(()=>(Qe(),$t));await b(r.taskId,k,"in_progress")}try{let b=eg(P,l),U=await a.buildIsolatedContext(k,P.description,b?.prompt||"",u.useLLMDisclosure,P.allowedTools);if(b?await tg(k,P.description,b,U,o,c,i,l,u,{log:p,info:g,success:m,warning:d,error:f},P.allowedTools):await ng(P.description,U,o,{log:p,info:g},P.allowedTools),T.showStepComplete(k,r.tasks.length,P,y),r.taskId){let{updateTaskStatus:j}=await Promise.resolve().then(()=>(Qe(),$t));await j(r.taskId,k,"completed")}}catch(b){let U=b instanceof Error?b.message:String(b);throw T.showStepError(k,r.tasks.length,U,y),d(`${w}\u4E2D\u6B62\u540E\u7EED\u6B65\u9AA4\u6267\u884C`),o.recordStepCompletion(k,`\u5931\u8D25: ${U}`,{success:!1,error:U}),b}}return T.showTaskComplete(r.tasks.length,r.tasks.length,y),Rn(),{success:!0,taskId:r.taskId,completedSteps:r.tasks.length-h,resumedFrom:e||1}}catch(h){Rn();let x=h instanceof Error?h.message:String(h);throw f(`${w}\u274C \u4EFB\u52A1\u6062\u590D\u6267\u884C\u5931\u8D25: ${x}`),h}}function Lh(s,e){return e<=1?s:s.split(`
2334
+ `).map(r=>{if(r.trim().startsWith("#")){let o=r.match(/^#+/)?.[0].length||0,i=Math.min(o+e-1,6),a="#".repeat(i);return r.replace(/^#+/,a)}return r}).join(`
2335
+ `)}function eg(s,e){return s.subAgent&&s.subAgent!=="default"?e.getSubAgent(s.subAgent):null}async function tg(s,e,t,n,r,o,i,a,c,l,u){let{log:p,info:g,error:m}=l,d=Date.now();g(`\u{1F527} \u4F7F\u7528\u5B50\u667A\u80FD\u4F53: ${t.name}`),p(z.gray(`\u63CF\u8FF0: ${t.description}`)),u&&u.length>0&&p(z.gray(`\u6CE8\u610F: \u5B50\u667A\u80FD\u4F53 ${t.name} \u4E0D\u53D7\u6B65\u9AA4\u5DE5\u5177\u9650\u5236\u5F71\u54CD`)),p("");try{let{SYSTEM_PROMPT:f}=await Promise.resolve().then(()=>(tn(),nc)),y=[{role:"system",content:f},...n.filter(h=>h.role!=="system"),...n.filter(h=>h.role==="system"&&h!==n[0])],w=await rg(y,e,l,void 0,t);await jh(s,w,r,o,i,c,l);let T=Date.now()-d;a.recordAgentPerformance(t.name,!0,T)}catch(f){let y=Date.now()-d;throw a.recordAgentPerformance(t.name,!1,y),f}}async function ng(s,e,t,n,r){let{log:o,info:i}=n;i("\u{1F916} \u4F7F\u7528\u9ED8\u8BA4React\u667A\u80FD\u4F53"),r&&r.length>0&&o(z.gray(`\u5DE5\u5177\u9650\u5236: ${r.join(", ")}`)),o("");let{SYSTEM_PROMPT:a}=await Promise.resolve().then(()=>(tn(),nc)),c=[{role:"system",content:a},...e.filter(l=>l.role!=="system"),...e.filter(l=>l.role==="system")];await rg(c,s,n,r)}async function rg(s,e,t,n,r=null){let{log:o,error:i,warning:a}=t,{MODEL:c}=await Promise.resolve().then(()=>(ae(),Ln)),{callModelAPI:l}=await Promise.resolve().then(()=>(Ie(),pr)),{isThinkTool:u,extractThought:p,formatThoughtWithHighlight:g}=await Promise.resolve().then(()=>(Is(),Ba)),{isFinishTool:m,extractFinishInfo:d}=await Promise.resolve().then(()=>(Pi(),vc)),{getToolDefinitions:f}=await Promise.resolve().then(()=>(lr(),kc)),{tools:y,toolInstances:w,extractToolResult:T}=await Promise.resolve().then(()=>(mt(),Bs)),{saveSession:h}=await Promise.resolve().then(()=>(ct(),Ll)),{logDebug:x,logWarn:P}=await Promise.resolve().then(()=>(Q(),ca)),{AnchorInjector:k}=await Promise.resolve().then(()=>(Us(),dc)),b=[...s],U=0,j=50,L=0,M=new k(e,l),$=f(),I=n&&n.length>0?$.filter(O=>n.includes(O.name)):$;for(n&&n.length>0&&x(`\u672C\u6B65\u9AA4\u53EF\u7528\u5DE5\u5177: ${I.map(O=>O.name).join(", ")}`);U<j;){U++,x(`Loop iteration ${U}`);try{let O=await M.injectAnchors({taskDescription:e,iterations:U,messages:b,lastSemanticCheckIteration:L,callModelAPI:l}),{messages:D,lastSemanticCheckIteration:N}=O;b=D,L=N,h(b,e);let Y=await l({model:c(),messages:b,temperature:.1,tools:I}),vt=Y.choices[0].message.tool_calls;if(Y.choices[0].finish_reason==="stop"){let{content:q}=Y.choices[0].message;if(q&&q.trim()){if(r?.finalAnswerCallback)try{await r.finalAnswerCallback(q)}catch(De){let{logError:ye}=await Promise.resolve().then(()=>(Q(),ca));ye(`Error in finalAnswerCallback: ${De}`)}o(z.green("\u4EFB\u52A1\u5B8C\u6210:")),o(q),o("")}break}if(!vt||vt.length===0){let{content:q}=Y.choices[0].message;q&&q.trim()&&(o(z.yellow(q)),o(""));continue}let V=vt[0],te=V.function.name;if(n&&n.length>0&&!n.includes(te)){let q=`Error: \u5DE5\u5177 '${te}' \u672A\u5728\u672C\u6B65\u9AA4\u7684\u6388\u6743\u5217\u8868\u4E2D\u3002\u5141\u8BB8\u4F7F\u7528\u7684\u5DE5\u5177: ${n.join(", ")}`;i(q),b.push({role:"assistant",content:null,tool_calls:[V]}),b.push({role:"tool",tool_call_id:V.id,content:q});continue}let je=mr(V.function.arguments);if(!je.success){i(`\u2717 \u89E3\u6790\u5DE5\u5177\u53C2\u6570\u5931\u8D25: ${V.function.arguments}`),i(` JSON\u89E3\u6790\u9519\u8BEF: ${je.error}`);let q=f().find(ye=>ye.name===te),De="";if(q){let ye={},Ki=q.input_schema.properties;(q.input_schema.required||[]).forEach(Pn=>{let Ht=Ki[Pn];Ht&&(Ht.type==="string"?ye[Pn]="example":Ht.type==="array"?ye[Pn]=Ht.items?.type==="string"?["example1","example2"]:[]:Ht.type==="object"?ye[Pn]={}:Ht.type==="number"?ye[Pn]=0:Ht.type==="boolean"&&(ye[Pn]=!1))}),De=`
2336
+
2337
+ \u6B63\u786E\u7684\u53C2\u6570\u683C\u5F0F\u793A\u4F8B:
2338
+ ${JSON.stringify(ye,null,2)}`}b.push({role:"assistant",content:null,tool_calls:[V]}),b.push({role:"tool",tool_call_id:V.id,content:`Error: Invalid JSON arguments - ${je.error}
2339
+
2340
+ \u539F\u59CB\u53C2\u6570: ${V.function.arguments}
2341
+ ${De}
2342
+
2343
+ \u8BF7\u786E\u4FDD:
2344
+ 1. \u6240\u6709\u5B57\u7B26\u4E32\u503C\u90FD\u7528\u53CC\u5F15\u53F7\u62EC\u8D77\u6765
2345
+ 2. \u6570\u7EC4\u4F7F\u7528\u65B9\u62EC\u53F7 []
2346
+ 3. \u5BF9\u8C61\u4F7F\u7528\u82B1\u62EC\u53F7 {}
2347
+ 4. \u4E0D\u8981\u4F7F\u7528\u88F8\u7684\u7B26\u53F7\uFF08\u5982 ., * \u7B49\uFF09\u4F5C\u4E3A\u503C\uFF0C\u5B83\u4EEC\u5FC5\u987B\u662F\u5B57\u7B26\u4E32`});continue}je.wasFixed&&a("\u26A0 JSON\u683C\u5F0F\u5DF2\u81EA\u52A8\u4FEE\u590D");let Ji=je.data;if(u(te)){let q=p(V);if(q){let De=g(q);o(z.cyan(`\u{1F4AD} Think: ${De}`)),o("")}b.push({role:"assistant",content:null,tool_calls:[V]}),b.push({role:"tool",tool_call_id:V.id,content:"Noted. Continue with your action."});continue}if(m(te)){let q=d(V);if(q){let{answer:De,success:ye}=q;if(r?.finalAnswerCallback)try{await r.finalAnswerCallback(De)}catch(il){P(`Error in finalAnswerCallback: ${il}`)}let Ki=ye?"\u2705":"\u26A0\uFE0F";o(z.green(`${Ki} \u4EFB\u52A1\u5B8C\u6210 (\u901A\u8FC7 finish \u5DE5\u5177):`)),o(De),o(""),b.push({role:"assistant",content:null,tool_calls:[V]}),b.push({role:"tool",tool_call_id:V.id,content:"Task completed successfully."}),b.push({role:"assistant",content:De});break}}if(!y[te]){let q=`Error: Unknown tool '${te}'`;i(q),b.push({role:"assistant",content:null,tool_calls:[V]}),b.push({role:"tool",tool_call_id:V.id,content:q});continue}let yo=f().find(q=>q.name===te);if(yo&&yo.input_schema&&yo.input_schema.required){let De=(yo.input_schema.required||[]).filter(ye=>Ji[ye]===void 0);if(De.length>0){let ye=`Error: Missing required parameters: ${De.join(", ")}`;i(ye),b.push({role:"assistant",content:null,tool_calls:[V]}),b.push({role:"tool",tool_call_id:V.id,content:ye});continue}}let Tn=w[te],ym=Tn?Tn.formatAction(Ji):`${te}()`;o(z.blue(`\u884C\u52A8: ${ym}`)),o("");let xo=await y[te](Ji),xm=T(xo),Sm=Tn?Tn.shouldPrintObservation(xo):!0,Cm=Tn?Tn.formatObservation(xo):String(xo);Sm&&(o(z.yellow(`\u89C2\u5BDF: ${Cm}`)),o("")),b.push({role:"assistant",content:null,tool_calls:[V]}),b.push({role:"tool",tool_call_id:V.id,content:String(xm)}),h(b,e)}catch(O){throw i(`\u9519\u8BEF: ${O.message}`),h(b,e),O}}if(U>=j)throw i("\u9519\u8BEF: \u5DF2\u8FBE\u5230\u6700\u5927\u8FED\u4EE3\u6B21\u6570"),h(b,e),new Error("Maximum iterations reached");return b}async function jh(s,e,t,n,r,o,i){let{info:a,log:c}=i,l=await n.extractSummary(e),u=n.extractMetadata(e);u.success=!0,t.recordStepCompletion(s,l,u,r),o.verbose&&(a(`\u6B65\u9AA4 ${s} \u6458\u8981\u5DF2\u8BB0\u5F55\u5230\u5168\u5C40\u4E0A\u4E0B\u6587`),c(""),c(z.gray("\u2500\u2500\u2500 \u6B65\u9AA4\u6267\u884C\u6458\u8981 \u2500\u2500\u2500")),c(z.gray(`\u6458\u8981: ${l}`)),c(z.gray(`\u5DE5\u5177: ${u.toolsUsed.join(", ")}`)),c(z.gray(`\u6587\u4EF6: ${u.filesAccessed.join(", ")}`)),c(z.gray(`\u8FED\u4EE3: ${u.iterations} \u6B21`)))}var ki,re,Ei=S(()=>{Qe();$i();ct();fc();Si();ki=class{startTime;stepStartTime=null;log;info;success;warning;error;constructor(e){this.startTime=Date.now(),this.log=e.log,this.info=e.info,this.success=e.success,this.warning=e.warning,this.error=e.error}showTaskStart(e,t,n=1){let r=" ".repeat(n-1);this.log(""),this.info(z.bold(`${r}\u5F00\u59CB\u6267\u884C\u4EFB\u52A1\u8BA1\u5212 (\u5171${t}\u6B65)`))}showStepProgress(e,t,n,r=1){this.stepStartTime=Date.now();let o=" ".repeat(r-1);this.log(""),this.info(`${o}[${e}/${t}] ${n.description}`),n.subAgent!=="default"&&this.log(z.gray(`${o} \u667A\u80FD\u4F53: ${n.subAgent}`))}showStepComplete(e,t,n,r=1){let o=" ".repeat(r-1),i=this.stepStartTime?this.formatDuration(Date.now()-this.stepStartTime):"";this.success(`${o}\u5B8C\u6210 [${e}/${t}] ${z.gray(i)}`)}showTaskComplete(e,t,n=1){let r=" ".repeat(n-1),o=this.formatDuration(Date.now()-this.startTime);this.log(""),this.success(`${r}\u4EFB\u52A1\u5B8C\u6210 (${e}/${t} \u6B65\u9AA4, \u8017\u65F6 ${o})`)}showStepError(e,t,n,r=1){let o=" ".repeat(r-1);this.error(`${o}\u6B65\u9AA4 [${e}/${t}] \u6267\u884C\u5931\u8D25: ${n.substring(0,100)}`)}createProgressBar(e,t=30){let n=Math.round(e/100*t),r=t-n;return`${z.green("\u2588".repeat(n))+z.gray("\u2591".repeat(r))} ${e}%`}formatDuration(e){if(e<1e3)return`${e}ms`;if(e<6e4)return`${(e/1e3).toFixed(1)}s`;let t=Math.floor(e/6e4),n=(e%6e4/1e3).toFixed(0);return`${t}m ${n}s`}},re=null});import Dh from"chalk";async function Hs(s){return await sg.execute(s)}var dt,sg,zs,Ec=S(()=>{G();dt=class s extends R{static nestingLevel=0;static MAX_NESTING_LEVEL=2;getDefinition(){let e=s.nestingLevel,t=s.MAX_NESTING_LEVEL,n="USE THIS TOOL FIRST for COMPLEX tasks! This is your PRIMARY tool for handling multi-step, cross-component work.";return e===t-1?n="USE THIS TOOL SPARINGLY for VERY COMPLEX sub-tasks! This is your last level of nesting.":e>=t&&(n="DO NOT USE THIS TOOL - maximum nesting level reached!"),{name:"plan",description:`${n}
1545
2348
 
1546
2349
  IDEAL USE CASES:
1547
2350
  - Building new features that span multiple files or components
@@ -1568,7 +2371,7 @@ AVOID FOR:
1568
2371
  RECOMMENDATION BASED ON CURRENT NESTING LEVEL (${e}/${t}):
1569
2372
  ${e===0?"- Feel free to use this tool for complex tasks.":e===t-1?"- Use this tool only if absolutely necessary for very complex sub-tasks.":"- DO NOT use this tool - maximum nesting level reached!"}
1570
2373
 
1571
- When you're uncertain if a task needs planning, default to using regular tools directly for sub-tasks!`,input_schema:{type:"object",properties:{task:{type:"string",description:"Detailed description of the complex task to plan and execute. Be specific about the goals and requirements."},planOnly:{type:"boolean",description:"If true, only generate the plan without executing it. The plan will be saved to ./.nium/tasks/ directory for later execution. Default: false"}},required:["task"]}}}async execute(e){let{task:t,planOnly:n=!1}=e;if(n)try{let{generateTaskPlan:r}=await Promise.resolve().then(()=>($e(),We)),{getSubAgentManager:s}=await Promise.resolve().then(()=>(ko(),Qc)),a=s().getAllSubAgents(),c=await r(t,a),l=`\u2705 \u4EFB\u52A1\u89C4\u5212\u5DF2\u751F\u6210\uFF08\u4EC5\u89C4\u5212\u6A21\u5F0F\uFF09
2374
+ When you're uncertain if a task needs planning, default to using regular tools directly for sub-tasks!`,input_schema:{type:"object",properties:{task:{type:"string",description:"Detailed description of the complex task to plan and execute. Be specific about the goals and requirements."},planOnly:{type:"boolean",description:"If true, only generate the plan without executing it. The plan will be saved to ./.nium/tasks/ directory for later execution. Default: false"}},required:["task"]}}}async execute(e){let{task:t,planOnly:n=!1}=e;if(n)try{let{generateTaskPlan:r}=await Promise.resolve().then(()=>(Qe(),$t)),{getSubAgentManager:o}=await Promise.resolve().then(()=>($i(),og)),a=o().getAllSubAgents(),c=await r(t,a),l=`\u2705 \u4EFB\u52A1\u89C4\u5212\u5DF2\u751F\u6210\uFF08\u4EC5\u89C4\u5212\u6A21\u5F0F\uFF09
1572
2375
 
1573
2376
  `;return l+=`**\u4EFB\u52A1 ID**: ${c.taskId}
1574
2377
  `,l+=`**\u603B\u6B65\u9AA4\u6570**: ${c.tasks.length}
@@ -1581,17 +2384,17 @@ When you're uncertain if a task needs planning, default to using regular tools d
1581
2384
  `,l+=`**\u6267\u884C\u6B65\u9AA4**:
1582
2385
  `,c.tasks.forEach((u,p)=>{l+=`${p+1}. ${u.description} [${u.subAgent}]
1583
2386
  `}),l+=`
1584
- \u{1F4A1} \u63D0\u793A: \u4F7F\u7528 todo \u5DE5\u5177\u7684 resume \u529F\u80FD\u6765\u6267\u884C\u6B64\u8BA1\u5212`,this.createToolResult(l,l,!0)}catch(r){let s=r instanceof Error?r.message:String(r);return this.createToolResult(`Error: Failed to generate plan - ${s}`,`Error: Failed to generate plan - ${s}`,!0)}if(o.nestingLevel>=o.MAX_NESTING_LEVEL)return this.createToolResult(`Error: Maximum nesting level (${o.MAX_NESTING_LEVEL}) reached. Please use regular tools directly instead of the plan tool.`,`Error: Maximum nesting level (${o.MAX_NESTING_LEVEL}) reached. Please use regular tools directly instead of the plan tool.`,!0);o.nestingLevel++;try{let r;try{r=await(await Promise.resolve().then(()=>(To(),ni))).executePlanTask(t,o.nestingLevel)}catch{console.log(bp.yellow("[Plan-Tool] \u8B66\u544A: \u65E0\u6CD5\u5BFC\u5165plan-executor.js\uFF0C\u8FD4\u56DE\u4EFB\u52A1\u89C4\u5212\u5EFA\u8BAE")),r={success:!0,message:"\u4EFB\u52A1\u89C4\u5212\u5DF2\u751F\u6210\uFF0C\u8BF7\u6839\u636E\u89C4\u5212\u6267\u884C\u4EFB\u52A1\u6B65\u9AA4",tasks:[{step:1,description:"\u5206\u6790\u9700\u6C42\u5E76\u786E\u8BA4\u6280\u672F\u6808",status:"pending"},{step:2,description:"\u5B9E\u73B0\u6838\u5FC3\u529F\u80FD\u6A21\u5757",status:"pending"},{step:3,description:"\u7F16\u5199\u6D4B\u8BD5\u7528\u4F8B",status:"pending"},{step:4,description:"\u4EE3\u7801\u5BA1\u67E5\u4E0E\u4F18\u5316",status:"pending"}]}}let s=`\u2705 Task planning and execution completed successfully!
2387
+ \u{1F4A1} \u63D0\u793A: \u4F7F\u7528 todo \u5DE5\u5177\u7684 resume \u529F\u80FD\u6765\u6267\u884C\u6B64\u8BA1\u5212`,this.createToolResult(l,l,!0)}catch(r){let o=r instanceof Error?r.message:String(r);return this.createToolResult(`Error: Failed to generate plan - ${o}`,`Error: Failed to generate plan - ${o}`,!0)}if(s.nestingLevel>=s.MAX_NESTING_LEVEL)return this.createToolResult(`Error: Maximum nesting level (${s.MAX_NESTING_LEVEL}) reached. Please use regular tools directly instead of the plan tool.`,`Error: Maximum nesting level (${s.MAX_NESTING_LEVEL}) reached. Please use regular tools directly instead of the plan tool.`,!0);s.nestingLevel++;try{let r;try{r=await(await Promise.resolve().then(()=>(Ei(),Pc))).executePlanTask(t,s.nestingLevel)}catch{console.log(Dh.yellow("[Plan-Tool] \u8B66\u544A: \u65E0\u6CD5\u5BFC\u5165plan-executor.js\uFF0C\u8FD4\u56DE\u4EFB\u52A1\u89C4\u5212\u5EFA\u8BAE")),r={success:!0,message:"\u4EFB\u52A1\u89C4\u5212\u5DF2\u751F\u6210\uFF0C\u8BF7\u6839\u636E\u89C4\u5212\u6267\u884C\u4EFB\u52A1\u6B65\u9AA4",tasks:[{step:1,description:"\u5206\u6790\u9700\u6C42\u5E76\u786E\u8BA4\u6280\u672F\u6808",status:"pending"},{step:2,description:"\u5B9E\u73B0\u6838\u5FC3\u529F\u80FD\u6A21\u5757",status:"pending"},{step:3,description:"\u7F16\u5199\u6D4B\u8BD5\u7528\u4F8B",status:"pending"},{step:4,description:"\u4EE3\u7801\u5BA1\u67E5\u4E0E\u4F18\u5316",status:"pending"}]}}let o=`\u2705 Task planning and execution completed successfully!
1585
2388
 
1586
- `;return s+=`**Task ID**: ${r.taskId}
1587
- `,s+=`**Completed Steps**: ${r.completedSteps}
2389
+ `;return o+=`**Task ID**: ${r.taskId}
2390
+ `,o+=`**Completed Steps**: ${r.completedSteps}
1588
2391
 
1589
- `,r.planMarkdown&&(s+=`**Generated Plan**:
2392
+ `,r.planMarkdown&&(o+=`**Generated Plan**:
1590
2393
  ${r.planMarkdown}
1591
2394
 
1592
- `),r.tasks&&r.tasks.length>0&&(s+=`**Executed Steps**:
1593
- `,r.tasks.forEach((i,a)=>{s+=`${a+1}. \u2713 ${i.description}
1594
- `})),this.createToolResult(s,s,!0)}catch(r){let s=r instanceof Error?r.message:String(r);return this.createToolResult(`Error: Task execution failed - ${s}`,`Error: Task execution failed - ${s}`,!0)}finally{o.nestingLevel--}}static getCurrentNestingLevel(){return o.nestingLevel}static resetNestingLevel(){o.nestingLevel=0}formatAction(e){return`plan(task="${e.task.length>100?e.task.substring(0,100)+"...":e.task}", nesting_level=${o.nestingLevel+1})`}formatObservation(e){return typeof e=="string"&&e.includes("Error:")?e:"Task planning completed. Check logs above for details."}},Xc=new De;pr=Xc});function el(o){Zc=o}function dr(){return Zc}var Zc,Eo=C(()=>{Zc=null});import Ke from"readline";import dt from"chalk";async function mr(o){return await tl.execute(o)}var Xt,tl,fr,nl=C(()=>{V();Eo();Xt=class extends ${getDefinition(){return{name:"askUser",description:`Ask the user a question and wait for their response. This pauses the execution loop until the user provides input.
2395
+ `),r.tasks&&r.tasks.length>0&&(o+=`**Executed Steps**:
2396
+ `,r.tasks.forEach((i,a)=>{o+=`${a+1}. \u2713 ${i.description}
2397
+ `})),this.createToolResult(o,o,!0)}catch(r){let o=r instanceof Error?r.message:String(r);return this.createToolResult(`Error: Task execution failed - ${o}`,`Error: Task execution failed - ${o}`,!0)}finally{s.nestingLevel--}}static getCurrentNestingLevel(){return s.nestingLevel}static resetNestingLevel(){s.nestingLevel=0}formatAction(e){return`plan(task="${e.task.length>100?e.task.substring(0,100)+"...":e.task}", nesting_level=${s.nestingLevel+1})`}formatObservation(e){return typeof e=="string"&&e.includes("Error:")?e:"Task planning completed. Check logs above for details."}},sg=new dt;zs=sg});function ag(s){ig=s}function yr(){return ig}var ig,Ii=S(()=>{ig=null});import Ft from"readline";import ln from"chalk";async function Vs(s){return await cg.execute(s)}var xr,cg,Gs,lg=S(()=>{G();Ii();ae();xr=class extends R{getDefinition(){return{name:"askUser",description:`Ask the user a question and wait for their response. This pauses the execution loop until the user provides input.
1595
2398
 
1596
2399
  Use this tool when you need:
1597
2400
  - User confirmation or decision
@@ -1608,7 +2411,7 @@ IMPORTANT:
1608
2411
  Examples:
1609
2412
  - askUser({ question: "Which file should I modify?" }) - Free text input
1610
2413
  - askUser({ question: "Proceed with deletion?", choices: ["Yes", "No"] }) - Multiple choice
1611
- - askUser({ question: "Select an option:", choices: ["Option 1", "Option 2"], allowFreeText: true }) - Choice with custom input allowed`,input_schema:{type:"object",properties:{question:{type:"string",description:"The question to ask the user. Be clear and specific."},choices:{type:"array",items:{type:"string"},description:"Optional: Predefined choices for the user to select from. If provided, user will see a menu."},allowFreeText:{type:"boolean",description:"Optional: If true, allows user to type a custom response even when choices are provided (default: false)",default:!1}},required:["question"]}}}async execute(e){let{question:t,choices:n,allowFreeText:r=!1}=e;try{let s;return n&&n.length>0?s=await this.showChoiceMenu(t,n,r):s=await this.showFreeTextInput(t),this.createToolResult(s,`User responded: ${s}`,!0)}catch(s){return this.formatError("Cannot get user input",s)}}showChoiceMenu(e,t,n){return new Promise(r=>{let s=0,i=t.map(p=>({text:p,value:p}));n&&i.push({text:"\u8F93\u5165\u81EA\u5B9A\u4E49\u7B54\u6848...",value:"__CUSTOM__"});let a=()=>{let p=i.length+5;for(let g=0;g<p;g++)g>0&&Ke.moveCursor(process.stdout,0,-1),Ke.clearLine(process.stdout,0);console.log(""),console.log(dt.cyan("\u{1F4AC} "+e)),console.log(""),console.log(dt.gray("\u8BF7\u9009\u62E9 (\u4F7F\u7528\u4E0A\u4E0B\u7BAD\u5934\u952E\uFF0CEnter\u786E\u8BA4):")),console.log(""),i.forEach((g,d)=>{let m=d===s,h=m?dt.green("> "):" ",w=m?dt.green.bold(g.text):dt.white(g.text);console.log(`${h}${w}`)}),console.log("")},c=process.stdin.isTTY?process.stdin.isRaw:!1;process.stdin.isTTY&&process.stdin.setRawMode(!0);let l=async(p,g)=>{if(g.name==="up"){s=Math.max(0,s-1),a();return}else if(g.name==="down"){s=Math.min(i.length-1,s+1),a();return}else if(g.name==="return"||g.name==="enter"){process.stdin.removeListener("keypress",l),process.stdin.isTTY&&process.stdin.setRawMode(c);let d=i.length+5;for(let h=0;h<d;h++)Ke.moveCursor(process.stdout,0,-1),Ke.clearLine(process.stdout,0);let m=i[s].value;if(m==="__CUSTOM__"){let h=await this.showFreeTextInput(e);r(h)}else r(m);return}else if(g.name==="escape"||g.ctrl&&g.name==="c"){let d=dr();d?d.removeListener("keypress",l):(process.stdin.removeListener("keypress",l),process.stdin.isTTY&&process.stdin.setRawMode(c));let m=i.length+5;for(let h=0;h<m;h++)Ke.moveCursor(process.stdout,0,-1),Ke.clearLine(process.stdout,0);r("__CANCELLED__");return}},u=dr();u?u.on("keypress",l):(Ke.emitKeypressEvents(process.stdin),process.stdin.on("keypress",l)),a()})}showFreeTextInput(e){return new Promise(t=>{let n=e||"\u8BF7\u8F93\u5165\u60A8\u7684\u7B54\u6848",r=process.stdin.listeners("keypress");process.stdin.removeAllListeners("keypress");let s=Ke.createInterface({input:process.stdin,output:process.stdout});console.log(""),console.log(dt.cyan("\u{1F4AC} "+n)),console.log(""),s.question(dt.gray("\u8BF7\u8F93\u5165\u7B54\u6848: "),i=>{s.removeAllListeners(),process.stdin.pause(),r.forEach(a=>{process.stdin.on("keypress",a)}),process.stdin.resume(),t(i.trim())})})}formatAction(e){let t=e.question||"";return e.choices&&e.choices.length>0?`askUser(question="${t}", choices=[${e.choices.join(", ")}])`:`askUser(question="${t}")`}formatObservation(e){return typeof e=="string"?e==="__CANCELLED__"?"User cancelled the input":`User response: ${e}`:super.formatObservation(e)}},tl=new Xt;fr=tl});async function hr(o){return await rl.execute(o)}var Qt,rl,yr,ol=C(()=>{V();Qt=class extends ${getDefinition(){return{name:"todo",description:`Execute and manage saved task plans. Use this tool to:
2414
+ - askUser({ question: "Select an option:", choices: ["Option 1", "Option 2"], allowFreeText: true }) - Choice with custom input allowed`,input_schema:{type:"object",properties:{question:{type:"string",description:"The question to ask the user. Be clear and specific."},choices:{type:"array",items:{type:"string"},description:"Optional: Predefined choices for the user to select from. If provided, user will see a menu."},allowFreeText:{type:"boolean",description:"Optional: If true, allows user to type a custom response even when choices are provided (default: false)",default:!1}},required:["question"]}}}async execute(e){let{question:t,choices:n,allowFreeText:r=!1}=e;try{let o;return ma()?o=await this.showInkModePrompt(t,n,r):n&&n.length>0?o=await this.showChoiceMenu(t,n,r):o=await this.showFreeTextInput(t),this.createToolResult(o,`User responded: ${o}`,!0)}catch(o){return this.formatError("Cannot get user input",o)}}showChoiceMenu(e,t,n){return new Promise(r=>{let o=0,i=t.map(p=>({text:p,value:p}));n&&i.push({text:"\u8F93\u5165\u81EA\u5B9A\u4E49\u7B54\u6848...",value:"__CUSTOM__"});let a=()=>{let p=i.length+5;for(let g=0;g<p;g++)g>0&&Ft.moveCursor(process.stdout,0,-1),Ft.clearLine(process.stdout,0);console.log(""),console.log(ln.cyan("\u{1F4AC} "+e)),console.log(""),console.log(ln.gray("\u8BF7\u9009\u62E9 (\u4F7F\u7528\u4E0A\u4E0B\u7BAD\u5934\u952E\uFF0CEnter\u786E\u8BA4):")),console.log(""),i.forEach((g,m)=>{let d=m===o,f=d?ln.green("> "):" ",y=d?ln.green.bold(g.text):ln.white(g.text);console.log(`${f}${y}`)}),console.log("")},c=process.stdin.isTTY?process.stdin.isRaw:!1;process.stdin.isTTY&&process.stdin.setRawMode(!0);let l=async(p,g)=>{if(g){if(g.name==="up"){o=Math.max(0,o-1),a();return}else if(g.name==="down"){o=Math.min(i.length-1,o+1),a();return}else if(g.name==="return"||g.name==="enter"){let m=yr();m?m.removeListener("keypress",l):process.stdin.removeListener("keypress",l),process.stdin.isTTY&&process.stdin.setRawMode(c);let d=i.length+5;for(let y=0;y<d;y++)Ft.moveCursor(process.stdout,0,-1),Ft.clearLine(process.stdout,0);let f=i[o].value;if(f==="__CUSTOM__"){let y=await this.showFreeTextInput(e);r(y)}else r(f);return}else if(g.name==="escape"||g.ctrl&&g.name==="c"){let m=yr();m?m.removeListener("keypress",l):(process.stdin.removeListener("keypress",l),process.stdin.isTTY&&process.stdin.setRawMode(c));let d=i.length+5;for(let f=0;f<d;f++)Ft.moveCursor(process.stdout,0,-1),Ft.clearLine(process.stdout,0);r("__CANCELLED__");return}}},u=yr();u?u.on("keypress",l):(Ft.emitKeypressEvents(process.stdin),process.stdin.on("keypress",l)),a()})}showFreeTextInput(e){return new Promise(t=>{let n=e||"\u8BF7\u8F93\u5165\u60A8\u7684\u7B54\u6848",r=process.stdin.listeners("keypress");process.stdin.removeAllListeners("keypress");let o=Ft.createInterface({input:process.stdin,output:process.stdout});console.log(""),console.log(ln.cyan("\u{1F4AC} "+n)),console.log(""),o.question(ln.gray("\u8BF7\u8F93\u5165\u7B54\u6848: "),i=>{o.removeAllListeners(),process.stdin.pause(),r.forEach(a=>{process.stdin.on("keypress",a)}),process.stdin.resume(),t(i.trim())})})}showInkModePrompt(e,t,n=!1){return new Promise((r,o)=>{let{EventEmitter:i}=bm("events");global.__inkAskUserEmitter||(global.__inkAskUserEmitter=new i);let a=global.__inkAskUserEmitter,c=`ask_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,l=setTimeout(()=>{a.removeAllListeners(`response_${c}`),o(new Error("Timeout waiting for user response"))},3e5);a.once(`response_${c}`,u=>{clearTimeout(l),r(u)}),a.emit("askUser",{requestId:c,question:e,choices:t,allowFreeText:n})})}formatAction(e){let t=e.question||"";return e.choices&&e.choices.length>0?`askUser(question="${t}", choices=[${e.choices.join(", ")}])`:`askUser(question="${t}")`}formatObservation(e){return typeof e=="string"?e==="__CANCELLED__"?"User cancelled the input":`User response: ${e}`:super.formatObservation(e)}},cg=new xr;Gs=cg});async function qs(s){return await ug.execute(s)}var Sr,ug,Js,pg=S(()=>{G();Sr=class extends R{getDefinition(){return{name:"todo",description:`Execute and manage saved task plans. Use this tool to:
1612
2415
  - Resume execution of a previously generated plan
1613
2416
  - List all available task plans
1614
2417
  - View details of a specific task plan
@@ -1622,16 +2425,16 @@ WHEN TO USE:
1622
2425
  FEATURES:
1623
2426
  - Resume from any step (default: continue from last step)
1624
2427
  - View task progress and status
1625
- - List all available plans in ./.nium/tasks/ directory`,input_schema:{type:"object",properties:{action:{type:"string",enum:["resume","list","view"],description:"The action to perform: resume (execute a saved plan), list (show all plans), view (show plan details)"},taskId:{type:"string",description:"The task ID to resume or view. Required for resume and view actions. Format: task-YYYYMMDD-XXX"},resumeFrom:{type:"number",description:"Step number to resume from (1-based). If not specified, resumes from the first incomplete step. Use 1 to restart from the beginning."}},required:["action"]}}}async execute(e){let{action:t,taskId:n,resumeFrom:r}=e;try{switch(t){case"resume":return await this.executeResume(n,r);case"list":return await this.executeList();case"view":return await this.executeView(n);default:return this.createToolResult(`Error: Unknown action '${t}'`,`Error: Unknown action '${t}'`,!0)}}catch(s){let i=s instanceof Error?s.message:String(s);return this.createToolResult(`Error: ${i}`,`Error: ${i}`,!0)}}async executeResume(e,t){if(!e)return this.createToolResult("Error: taskId is required for resume action","Error: taskId is required for resume action",!0);try{let{resumePlanTask:n}=await Promise.resolve().then(()=>(To(),ni)),r=await n(e,t||0),s=`\u2705 \u4EFB\u52A1\u6062\u590D\u6267\u884C\u5B8C\u6210\uFF01
2428
+ - List all available plans in ./.nium/tasks/ directory`,input_schema:{type:"object",properties:{action:{type:"string",enum:["resume","list","view"],description:"The action to perform: resume (execute a saved plan), list (show all plans), view (show plan details)"},taskId:{type:"string",description:"The task ID to resume or view. Required for resume and view actions. Format: task-YYYYMMDD-XXX"},resumeFrom:{type:"number",description:"Step number to resume from (1-based). If not specified, resumes from the first incomplete step. Use 1 to restart from the beginning."}},required:["action"]}}}async execute(e){let{action:t,taskId:n,resumeFrom:r}=e;try{switch(t){case"resume":return await this.executeResume(n,r);case"list":return await this.executeList();case"view":return await this.executeView(n);default:return this.createToolResult(`Error: Unknown action '${t}'`,`Error: Unknown action '${t}'`,!0)}}catch(o){let i=o instanceof Error?o.message:String(o);return this.createToolResult(`Error: ${i}`,`Error: ${i}`,!0)}}async executeResume(e,t){if(!e)return this.createToolResult("Error: taskId is required for resume action","Error: taskId is required for resume action",!0);try{let{resumePlanTask:n}=await Promise.resolve().then(()=>(Ei(),Pc)),r=await n(e,t||0),o=`\u2705 \u4EFB\u52A1\u6062\u590D\u6267\u884C\u5B8C\u6210\uFF01
1626
2429
 
1627
- `;return s+=`**\u4EFB\u52A1 ID**: ${r.taskId}
1628
- `,s+=`**\u5B8C\u6210\u6B65\u9AA4**: ${r.completedSteps}
1629
- `,s+=`**\u6062\u590D\u8D77\u70B9**: \u6B65\u9AA4 ${r.resumedFrom}
2430
+ `;return o+=`**\u4EFB\u52A1 ID**: ${r.taskId}
2431
+ `,o+=`**\u5B8C\u6210\u6B65\u9AA4**: ${r.completedSteps}
2432
+ `,o+=`**\u6062\u590D\u8D77\u70B9**: \u6B65\u9AA4 ${r.resumedFrom}
1630
2433
 
1631
- `,s+="\u6240\u6709\u6B65\u9AA4\u5DF2\u6210\u529F\u6267\u884C\u5B8C\u6BD5\u3002",this.createToolResult(s,s,!0)}catch(n){let r=n instanceof Error?n.message:String(n);return this.createToolResult(`Error: Failed to resume task - ${r}`,`Error: Failed to resume task - ${r}`,!0)}}async executeList(){try{let{listTaskPlans:e,loadTaskPlan:t}=await Promise.resolve().then(()=>($e(),We)),n=e();if(n.length===0)return this.createToolResult("No saved task plans found in ./.nium/tasks/ directory.","No saved task plans found in ./.nium/tasks/ directory.",!0);let r=`\u{1F4CB} \u5DF2\u4FDD\u5B58\u7684\u4EFB\u52A1\u8BA1\u5212 (\u5171 ${n.length} \u4E2A)
2434
+ `,o+="\u6240\u6709\u6B65\u9AA4\u5DF2\u6210\u529F\u6267\u884C\u5B8C\u6BD5\u3002",this.createToolResult(o,o,!0)}catch(n){let r=n instanceof Error?n.message:String(n);return this.createToolResult(`Error: Failed to resume task - ${r}`,`Error: Failed to resume task - ${r}`,!0)}}async executeList(){try{let{listTaskPlans:e,loadTaskPlan:t}=await Promise.resolve().then(()=>(Qe(),$t)),n=e();if(n.length===0)return this.createToolResult("No saved task plans found in ./.nium/tasks/ directory.","No saved task plans found in ./.nium/tasks/ directory.",!0);let r=`\u{1F4CB} \u5DF2\u4FDD\u5B58\u7684\u4EFB\u52A1\u8BA1\u5212 (\u5171 ${n.length} \u4E2A)
1632
2435
  `;r+=`${"\u2550".repeat(60)}
1633
2436
 
1634
- `;for(let s of n){let i=t(s);if(i){let a=i.tasks.filter(u=>u.status==="completed").length,c=i.tasks.length,l=a===c?"\u2705 \u5DF2\u5B8C\u6210":a>0?`\u23F3 \u8FDB\u884C\u4E2D (${a}/${c})`:"\u{1F4CB} \u5F85\u6267\u884C";r+=`**${s}**
2437
+ `;for(let o of n){let i=t(o);if(i){let a=i.tasks.filter(u=>u.status==="completed").length,c=i.tasks.length,l=a===c?"\u2705 \u5DF2\u5B8C\u6210":a>0?`\u23F3 \u8FDB\u884C\u4E2D (${a}/${c})`:"\u{1F4CB} \u5F85\u6267\u884C";r+=`**${o}**
1635
2438
  `,r+=` \u72B6\u6001: ${l}
1636
2439
  `,r+=` \u6B65\u9AA4: ${c} \u4E2A
1637
2440
  `,r+=` \u7B56\u7565: ${i.strategy}
@@ -1639,7 +2442,7 @@ FEATURES:
1639
2442
  `,r+=`
1640
2443
  `}}return r+=`
1641
2444
  \u{1F4A1} \u4F7F\u7528 todo(action="view", taskId="...") \u67E5\u770B\u8BE6\u60C5`,r+=`
1642
- \u{1F4A1} \u4F7F\u7528 todo(action="resume", taskId="...") \u6062\u590D\u6267\u884C`,this.createToolResult(r,r,!0)}catch(e){let t=e instanceof Error?e.message:String(e);return this.createToolResult(`Error: Failed to list tasks - ${t}`,`Error: Failed to list tasks - ${t}`,!0)}}async executeView(e){if(!e)return this.createToolResult("Error: taskId is required for view action","Error: taskId is required for view action",!0);try{let{loadTaskPlan:t}=await Promise.resolve().then(()=>($e(),We)),n=t(e);if(!n)return this.createToolResult(`Error: Task plan '${e}' not found`,`Error: Task plan '${e}' not found`,!0);let r=`\u{1F4CB} \u4EFB\u52A1\u8BA1\u5212\u8BE6\u60C5
2445
+ \u{1F4A1} \u4F7F\u7528 todo(action="resume", taskId="...") \u6062\u590D\u6267\u884C`,this.createToolResult(r,r,!0)}catch(e){let t=e instanceof Error?e.message:String(e);return this.createToolResult(`Error: Failed to list tasks - ${t}`,`Error: Failed to list tasks - ${t}`,!0)}}async executeView(e){if(!e)return this.createToolResult("Error: taskId is required for view action","Error: taskId is required for view action",!0);try{let{loadTaskPlan:t}=await Promise.resolve().then(()=>(Qe(),$t)),n=t(e);if(!n)return this.createToolResult(`Error: Task plan '${e}' not found`,`Error: Task plan '${e}' not found`,!0);let r=`\u{1F4CB} \u4EFB\u52A1\u8BA1\u5212\u8BE6\u60C5
1643
2446
  `;r+=`${"\u2550".repeat(60)}
1644
2447
 
1645
2448
  `,r+=`**\u4EFB\u52A1 ID**: ${n.taskId}
@@ -1659,9 +2462,602 @@ FEATURES:
1659
2462
  `),c.duration&&(r+=` \u8017\u65F6: ${c.duration}ms
1660
2463
  `),c.error&&(r+=` \u9519\u8BEF: ${c.error}
1661
2464
  `),r+=`
1662
- `}let s=n.tasks.find(i=>i.status!=="completed");return s?r+=`
1663
- \u{1F4A1} \u4F7F\u7528 todo(action="resume", taskId="${e}", resumeFrom=${s.step}) \u4ECE\u6B65\u9AA4 ${s.step} \u7EE7\u7EED\u6267\u884C`:r+=`
1664
- \u2705 \u6240\u6709\u6B65\u9AA4\u5DF2\u5B8C\u6210\uFF01`,this.createToolResult(r,r,!0)}catch(t){let n=t instanceof Error?t.message:String(t);return this.createToolResult(`Error: Failed to view task - ${n}`,`Error: Failed to view task - ${n}`,!0)}}formatAction(e){let{action:t,taskId:n,resumeFrom:r}=e,s=`todo(action="${t}"`;return n&&(s+=`, taskId="${n}"`),r&&(s+=`, resumeFrom=${r}`),s+=")",s}},rl=new Qt;yr=rl});var si={};j(si,{AskUserTool:()=>Xt,PlanTool:()=>De,QuickProjectScanTool:()=>pt,THINK_TOOL:()=>to,ThinkTool:()=>ot,TodoTool:()=>Qt,askUser:()=>mr,askUserTool:()=>fr,extractThought:()=>no,isThinkTool:()=>zt,plan:()=>gr,planTool:()=>pr,quickProjectScan:()=>qt,quickProjectScanTool:()=>Kt,think:()=>Wt,thinkTool:()=>Vt,todo:()=>hr,todoTool:()=>yr});var Po=C(()=>{Xn();oi();nl();Ys();ol()});async function sl(o){return ai.execute(o)}var ii,ai,il,wx,al=C(()=>{V();ar();ii=class extends ${getDefinition(){return{name:"search_file_changes",description:`Use this tool to search and query file changes in the workspace. This tool provides auxiliary information to help you understand the current state of the workspace.
2465
+ `}let o=n.tasks.find(i=>i.status!=="completed");return o?r+=`
2466
+ \u{1F4A1} \u4F7F\u7528 todo(action="resume", taskId="${e}", resumeFrom=${o.step}) \u4ECE\u6B65\u9AA4 ${o.step} \u7EE7\u7EED\u6267\u884C`:r+=`
2467
+ \u2705 \u6240\u6709\u6B65\u9AA4\u5DF2\u5B8C\u6210\uFF01`,this.createToolResult(r,r,!0)}catch(t){let n=t instanceof Error?t.message:String(t);return this.createToolResult(`Error: Failed to view task - ${n}`,`Error: Failed to view task - ${n}`,!0)}}formatAction(e){let{action:t,taskId:n,resumeFrom:r}=e,o=`todo(action="${t}"`;return n&&(o+=`, taskId="${n}"`),r&&(o+=`, resumeFrom=${r}`),o+=")",o}},ug=new Sr;Js=ug});import*as wr from"fs";import*as Ks from"path";import{globSync as Fh}from"glob";import{readFileSync as gg}from"fs";async function Ys(s){return mg.execute(s)}var Cr,mg,Xs,dg=S(()=>{G();pt();Ie();ae();Fe();Cr=class extends R{getDefinition(){return{name:"explore",description:`\u6DF1\u5EA6\u63A2\u7D22\u9879\u76EE\u6574\u4F53\u67B6\u6784\u3001\u6A21\u5757\u95F4\u5173\u7CFB\u3001\u8BBE\u8BA1\u6A21\u5F0F\u3002\u9002\u5408\u9700\u8981\u7406\u89E3\u7CFB\u7EDF\u8BBE\u8BA1\u7684\u573A\u666F\uFF0830-60\u79D2\uFF09\u3002
2468
+
2469
+ \u{1F4CB} \u7528\u9014\uFF1A
2470
+ - \u5206\u6790\u9879\u76EE\u6574\u4F53\u67B6\u6784\u548C\u8BBE\u8BA1\u7406\u5FF5
2471
+ - \u7406\u89E3\u6A21\u5757\u95F4\u4F9D\u8D56\u5173\u7CFB\u548C\u6570\u636E\u6D41\u5411
2472
+ - \u8BC6\u522B\u8BBE\u8BA1\u6A21\u5F0F\u548C\u67B6\u6784\u51B3\u7B56
2473
+ - \u8BC4\u4F30\u7CFB\u7EDF\u7ED3\u6784\u7684\u5408\u7406\u6027
2474
+
2475
+ \u{1F511} \u53C2\u6570\uFF1A
2476
+ - topic: \u67B6\u6784\u63A2\u7D22\u4E3B\u9898\uFF08\u5FC5\u586B\uFF0C\u5982"\u9879\u76EE\u67B6\u6784"\u3001"\u7CFB\u7EDF\u8BBE\u8BA1"\u3001"\u6A21\u5757\u5173\u7CFB"\uFF09
2477
+ - englishTopic: \u82F1\u6587\u4E3B\u9898\uFF08\u5FC5\u586B\uFF0C\u751F\u6210\u6587\u6863\u6587\u4EF6\u540D\uFF09
2478
+
2479
+ \u{1F4A1} \u793A\u4F8B\uFF1A
2480
+ - explore({ topic: "\u9879\u76EE\u67B6\u6784", englishTopic: "Project Architecture" })
2481
+ - explore({ topic: "\u7CFB\u7EDF\u8BBE\u8BA1", englishTopic: "System Design" })
2482
+ - explore({ topic: "\u6A21\u5757\u5173\u7CFB", englishTopic: "Module Relationships" })
2483
+
2484
+ \u{1F3AF} \u4E0E\u5176\u4ED6\u5DE5\u5177\u7684\u533A\u522B\uFF1A
2485
+ \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510
2486
+ \u2502 \u5DE5\u5177 \u2502 \u5173\u6CE8\u70B9 \u2502
2487
+ \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524
2488
+ \u2502 quickProjectScan\u2502 \u9879\u76EE\u6982\u89C8\uFF08<5\u79D2\uFF0C\u8F7B\u91CF\u7EA7\u626B\u63CF\uFF09 \u2502
2489
+ \u2502 explore \u2502 \u67B6\u6784\u8BBE\u8BA1\uFF0830-60\u79D2\uFF0C\u5B8F\u89C2\u5206\u6790\uFF09\u2502
2490
+ \u2502 moduleExplore \u2502 \u6A21\u5757\u5B9E\u73B0\uFF0860-120\u79D2\uFF0C\u5FAE\u89C2\u5206\u6790\uFF09\u2502
2491
+ \u2502 toolingExplore \u2502 \u5DE5\u5177\u94FE\u914D\u7F6E\uFF0830-60\u79D2\uFF0CDevOps\uFF09 \u2502
2492
+ \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
2493
+
2494
+ \u2705 \u9002\u5408\u7684\u573A\u666F\uFF1A
2495
+ - \u65B0\u52A0\u5165\u9879\u76EE\uFF0C\u9700\u8981\u7406\u89E3\u6574\u4F53\u67B6\u6784
2496
+ - \u91CD\u6784\u524D\u8BC4\u4F30\u7CFB\u7EDF\u8BBE\u8BA1\u5408\u7406\u6027
2497
+ - \u5206\u6790\u6A21\u5757\u95F4\u7684\u4F9D\u8D56\u548C\u8026\u5408\u5EA6
2498
+ - \u8BC6\u522B\u67B6\u6784\u4E2D\u7684\u8BBE\u8BA1\u6A21\u5F0F
2499
+ - \u56DE\u7B54"\u7CFB\u7EDF\u5982\u4F55\u7EC4\u7EC7"\u7684\u95EE\u9898
2500
+
2501
+ \u274C \u4E0D\u9002\u5408\u7684\u573A\u666F\uFF1A
2502
+ - \u9700\u8981\u5FEB\u901F\u4E86\u89E3\u9879\u76EE\u57FA\u672C\u4FE1\u606F \u2192 \u4F7F\u7528 quickProjectScan
2503
+ - \u9700\u8981\u6DF1\u5165\u7406\u89E3\u67D0\u4E2A\u6A21\u5757\u7684\u5177\u4F53\u5B9E\u73B0 \u2192 \u4F7F\u7528 moduleExplore
2504
+ - \u9700\u8981\u4E86\u89E3\u6784\u5EFA/\u6D4B\u8BD5/\u90E8\u7F72\u914D\u7F6E \u2192 \u4F7F\u7528 toolingExplore
2505
+ - \u9700\u8981\u67E5\u627E\u7279\u5B9A\u51FD\u6570\u6216\u7C7B\u7684\u5B9E\u73B0 \u2192 \u4F7F\u7528 grep + read
2506
+ - \u9879\u76EE\u7ED3\u6784\u5DF2\u6E05\u6670\uFF0C\u53EA\u9700\u4FEE\u6539\u4EE3\u7801 \u2192 \u76F4\u63A5\u4F7F\u7528 read/write
2507
+
2508
+ \u26A0\uFE0F \u6CE8\u610F\uFF1A
2509
+ - \u672C\u5DE5\u5177\u4E13\u6CE8\u4E8E"\u67B6\u6784\u7EA7"\u5206\u6790\uFF08WHY\uFF1A\u4E3A\u4EC0\u4E48\u8FD9\u6837\u8BBE\u8BA1\uFF09
2510
+ - \u6267\u884C\u65F6\u95F4\u7EA630-60\u79D2\uFF0C\u4F1A\u6DF1\u5EA6\u5206\u6790\u591A\u4E2A\u6587\u4EF6
2511
+ - \u7ED3\u679C\u4FDD\u5B58\u5230 .nium/docs/<TOPIC>_ARCHITECTURE.md
2512
+
2513
+ \u{1F4DD} \u8F93\u51FA\uFF1A
2514
+ - \u4FDD\u5B58\u67B6\u6784\u62A5\u544A\u5230 .nium/docs/<TOPIC>_ARCHITECTURE.md
2515
+ - \u8FD4\u56DE\u67B6\u6784\u56FE\u3001\u8BBE\u8BA1\u6A21\u5F0F\u3001\u6539\u8FDB\u5EFA\u8BAE`,input_schema:{type:"object",properties:{topic:{type:"string",description:"\u67B6\u6784\u63A2\u7D22\u4E3B\u9898\uFF08\u53EF\u4EE5\u662F\u4E2D\u6587\u6216\u82F1\u6587\uFF0C\u4F8B\u5982\uFF1A'\u9879\u76EE\u67B6\u6784'\u3001'Project Architecture'\uFF09"},englishTopic:{type:"string",description:"\u82F1\u6587\u4E3B\u9898\u540D\u79F0\uFF0C\u7528\u4E8E\u751F\u6210\u6587\u4EF6\u540D\u548C\u68C0\u7D22\u5173\u952E\u8BCD\uFF08\u4F8B\u5982\uFF1A'Project Architecture'\u3001'System Design'\uFF09"}},required:["topic","englishTopic"]}}}async execute(e){try{let t=process.cwd(),n=[];n.push(`\u{1F3D7}\uFE0F \u5F00\u59CB\u67B6\u6784\u5206\u6790: ${e.topic}
2516
+ `),n.push("\u{1F4CB} \u52A0\u8F7D\u9879\u76EE\u7ED3\u6784...");let r=await this.loadProjectStructure(t);n.push(` \u2713 \u52A0\u8F7D ${r.allFiles.length} \u4E2A\u6587\u4EF6`),n.push(""),n.push("\u{1F517} \u5206\u6790\u6A21\u5757\u95F4\u5173\u7CFB...");let o=await this.analyzeModuleRelations(r.allFiles);n.push(` \u2713 \u8BC6\u522B ${o.modules.length} \u4E2A\u6838\u5FC3\u6A21\u5757`),n.push(` \u2713 \u5206\u6790 ${o.dependencies.length} \u4E2A\u4F9D\u8D56\u5173\u7CFB`),n.push(""),n.push("\u{1F3AF} \u8BC6\u522B\u8BBE\u8BA1\u6A21\u5F0F...");let i=await this.identifyDesignPatterns(r.allFiles.slice(0,30));n.push(` \u2713 \u8BC6\u522B ${i.patterns.length} \u4E2A\u8BBE\u8BA1\u6A21\u5F0F`),n.push(""),n.push("\u{1F4CA} \u751F\u6210\u67B6\u6784\u56FE...");let a=await this.generateArchitectureView(o,i,e.topic);n.push(" \u2713 \u67B6\u6784\u5206\u6790\u5B8C\u6210"),n.push(""),n.push("\u{1F4DD} \u751F\u6210\u67B6\u6784\u62A5\u544A...");let c=await this.saveArchitectureDoc(e.topic,e.englishTopic,o,i,a);return n.push(` \u2713 \u62A5\u544A\u5DF2\u4FDD\u5B58: ${Ks.relative(t,c)}`),n.push(""),n.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),n.push(`\u67B6\u6784\u5206\u6790: ${e.topic}`),n.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),n.push(`
2517
+ \u{1F3D7}\uFE0F \u67B6\u6784\u7C7B\u578B: ${a.type}`),n.push(`\u{1F4E6} \u6838\u5FC3\u6A21\u5757: ${o.modules.length} \u4E2A`),n.push(`\u{1F517} \u4F9D\u8D56\u5173\u7CFB: ${o.dependencies.length} \u4E2A`),n.push(`\u{1F3AF} \u8BBE\u8BA1\u6A21\u5F0F: ${i.patterns.length} \u4E2A`),n.push(`
2518
+ \u{1F4A1} \u67B6\u6784\u6458\u8981:`),n.push(a.summary),n.push(`
2519
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
2520
+ `),n.join(`
2521
+ `)}catch(t){return this.formatError("Explore",t)}}async loadProjectStructure(e){let t=we(e,!0);return{allFiles:Fh("**/*",{nodir:!0,ignore:t,cwd:e}).slice(0,150)}}async analyzeModuleRelations(e){let t=[],n=[],r=new Map;e.forEach(i=>{let a=i.split("/");if(a.length>=2){let c=a.slice(0,2).join("/");r.has(c)||r.set(c,[]),r.get(c).push(i)}}),r.forEach((i,a)=>{if(i.length>=2){let c=a.split("/").pop()||a,l="unknown";c.includes("service")||c.includes("services")?l="service":c.includes("controller")||c.includes("handler")?l="controller":c.includes("model")||c.includes("entity")?l="model":c.includes("util")||c.includes("helper")?l="utility":c.includes("config")||c.includes("setting")?l="configuration":(c.includes("test")||c.includes("spec"))&&(l="test"),t.push({name:c,path:a,type:l})}});let o=/(?:import\s+.*from\s+['"](.+?)['"]|require\(['"](.+?)['"]\))/g;return t.forEach(i=>{r.get(i.path)?.forEach(a=>{if(a.endsWith(".js")||a.endsWith(".ts"))try{let c=gg(a,"utf-8"),l;for(;(l=o.exec(c))!==null;){let u=l[1]||l[2],p=t.find(g=>u.includes(g.path)||u.includes(g.name));p&&p.name!==i.name&&n.push({from:i.name,to:p.name,type:"import"})}}catch{}})}),{modules:t,dependencies:n}}async identifyDesignPatterns(e){let t=[],n=[{name:"Singleton",pattern:/class\s+\w+.*static\s+instance|getInstance\(\)/gi,description:"\u5355\u4F8B\u6A21\u5F0F - \u786E\u4FDD\u7C7B\u53EA\u6709\u4E00\u4E2A\u5B9E\u4F8B"},{name:"Factory",pattern:/create\w*\(|Factory|factory\(\)/gi,description:"\u5DE5\u5382\u6A21\u5F0F - \u521B\u5EFA\u5BF9\u8C61\u800C\u4E0D\u66B4\u9732\u521B\u5EFA\u903B\u8F91"},{name:"Observer",pattern:/subscribe|addEventListener|on\(|emit/gi,description:"\u89C2\u5BDF\u8005\u6A21\u5F0F - \u5B9A\u4E49\u5BF9\u8C61\u95F4\u7684\u4E00\u5BF9\u591A\u4F9D\u8D56\u5173\u7CFB"},{name:"Strategy",pattern:/Strategy|execute\(\)|setStrategy/gi,description:"\u7B56\u7565\u6A21\u5F0F - \u5B9A\u4E49\u7B97\u6CD5\u65CF\u5E76\u4F7F\u5B83\u4EEC\u53EF\u4EE5\u4E92\u6362"},{name:"Decorator",pattern:/@|Decorator|wrap\(\)/gi,description:"\u88C5\u9970\u5668\u6A21\u5F0F - \u52A8\u6001\u5730\u7ED9\u5BF9\u8C61\u6DFB\u52A0\u65B0\u529F\u80FD"},{name:"Repository",pattern:/Repository|save\(|find\(|delete\(/gi,description:"\u4ED3\u50A8\u6A21\u5F0F - \u62BD\u8C61\u6570\u636E\u8BBF\u95EE\u5C42"},{name:"MVC",pattern:/Controller|View|Model/gi,description:"MVC\u6A21\u5F0F - \u6A21\u578B-\u89C6\u56FE-\u63A7\u5236\u5668\u67B6\u6784"}];return e.forEach(r=>{if(r.endsWith(".js")||r.endsWith(".ts")||r.endsWith(".java")||r.endsWith(".py"))try{let o=gg(r,"utf-8");n.forEach(i=>{i.pattern.test(o)&&t.push({name:i.name,location:r,description:i.description})})}catch{}}),{patterns:t}}async generateArchitectureView(e,t,n){let r=`\u4F60\u662F\u4E00\u4F4D\u8D44\u6DF1\u67B6\u6784\u5E08\uFF0C\u8BF7\u5206\u6790\u4EE5\u4E0B\u9879\u76EE\u67B6\u6784\u4FE1\u606F\uFF1A
2522
+
2523
+ ## \u6A21\u5757\u4FE1\u606F
2524
+ ${e.modules.map(o=>`- ${o.name} (${o.type})`).join(`
2525
+ `)}
2526
+
2527
+ ## \u4F9D\u8D56\u5173\u7CFB
2528
+ ${e.dependencies.map(o=>`- ${o.from} -> ${o.to}`).join(`
2529
+ `)}
2530
+
2531
+ ## \u8BBE\u8BA1\u6A21\u5F0F
2532
+ ${t.patterns.map(o=>`- ${o.name}: ${o.description}`).join(`
2533
+ `)}
2534
+
2535
+ \u8BF7\u63D0\u4F9B\u4EE5\u4E0B\u5206\u6790\uFF1A
2536
+ 1. \u67B6\u6784\u7C7B\u578B\uFF08\u5982\u5206\u5C42\u67B6\u6784\u3001\u5FAE\u670D\u52A1\u3001MVC\u7B49\uFF09
2537
+ 2. \u67B6\u6784\u6458\u8981\uFF082-3\u53E5\u8BDD\u603B\u7ED3\uFF09
2538
+ 3. \u6539\u8FDB\u5EFA\u8BAE\uFF082-3\u6761\uFF09
2539
+
2540
+ \u4EE5JSON\u683C\u5F0F\u8FD4\u56DE\uFF1A
2541
+ {
2542
+ "type": "\u67B6\u6784\u7C7B\u578B",
2543
+ "summary": "\u67B6\u6784\u6458\u8981",
2544
+ "recommendations": ["\u5EFA\u8BAE1", "\u5EFA\u8BAE2"]
2545
+ }`;try{let i=(await Z({model:ge(),messages:[{role:"user",content:r}],temperature:.3,max_tokens:1e3}))?.choices?.[0]?.message?.content||"{}",a=i.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/)||i.match(/(\{[\s\S]*?\})/);if(a){let c=JSON.parse(a[1]);return{type:c.type||"\u672A\u77E5\u67B6\u6784",summary:c.summary||"\u65E0\u6CD5\u751F\u6210\u67B6\u6784\u6458\u8981",recommendations:Array.isArray(c.recommendations)?c.recommendations:[]}}}catch(o){console.error("\u751F\u6210\u67B6\u6784\u89C6\u56FE\u5931\u8D25:",o)}return{type:"\u6A21\u5757\u5316\u67B6\u6784",summary:`\u5305\u542B ${e.modules.length} \u4E2A\u6A21\u5757\u7684\u67B6\u6784\u8BBE\u8BA1`,recommendations:["\u5EFA\u8BAE\u6DFB\u52A0\u66F4\u591A\u67B6\u6784\u6587\u6863","\u8003\u8651\u6A21\u5757\u95F4\u7684\u89E3\u8026"]}}async saveArchitectureDoc(e,t,n,r,o){let i=process.cwd(),a=Ks.join(i,".nium","docs");wr.existsSync(a)||wr.mkdirSync(a,{recursive:!0});let c=t.replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase()+"_ARCHITECTURE.md",l=Ks.join(a,c),u=`# ${e} - \u67B6\u6784\u5206\u6790\u62A5\u544A
2546
+
2547
+ > \u751F\u6210\u65F6\u95F4: ${H()}
2548
+ > \u751F\u6210\u5DE5\u5177: Explore Tool (\u67B6\u6784\u7EA7\u63A2\u7D22)
2549
+
2550
+ ---
2551
+
2552
+ ## \u67B6\u6784\u6982\u89C8
2553
+
2554
+ **\u67B6\u6784\u7C7B\u578B**: ${o.type}
2555
+
2556
+ **\u6458\u8981**: ${o.summary}
2557
+
2558
+ ---
2559
+
2560
+ ## \u6838\u5FC3\u6A21\u5757\u5206\u6790
2561
+
2562
+ ### \u6A21\u5757\u7EDF\u8BA1
2563
+ - \u603B\u6A21\u5757\u6570: ${n.modules.length}
2564
+ - \u4F9D\u8D56\u5173\u7CFB\u6570: ${n.dependencies.length}
2565
+ - \u8BBE\u8BA1\u6A21\u5F0F\u6570: ${r.patterns.length}
2566
+
2567
+ ### \u6A21\u5757\u8BE6\u60C5
2568
+
2569
+ ${n.modules.map(p=>`
2570
+ #### ${p.name}
2571
+ - **\u7C7B\u578B**: ${p.type}
2572
+ - **\u8DEF\u5F84**: \`${p.path}\`
2573
+ `).join("")}
2574
+
2575
+ ---
2576
+
2577
+ ## \u4F9D\u8D56\u5173\u7CFB\u56FE
2578
+
2579
+ \`\`\`mermaid
2580
+ graph TD
2581
+ ${n.dependencies.slice(0,20).map(p=>` ${p.from} --> ${p.to}`).join(`
2582
+ `)}
2583
+ \`\`\`
2584
+
2585
+ > \u6CE8\uFF1A\u4EC5\u663E\u793A\u524D20\u4E2A\u4F9D\u8D56\u5173\u7CFB\u4EE5\u4FDD\u6301\u56FE\u8868\u6E05\u6670
2586
+
2587
+ ---
2588
+
2589
+ ## \u8BBE\u8BA1\u6A21\u5F0F\u8BC6\u522B
2590
+
2591
+ ${r.patterns.map(p=>`
2592
+ ### ${p.name}
2593
+ - **\u63CF\u8FF0**: ${p.description}
2594
+ - **\u4F4D\u7F6E**: \`${p.location}\`
2595
+ `).join("")}
2596
+
2597
+ ---
2598
+
2599
+ ## \u67B6\u6784\u6539\u8FDB\u5EFA\u8BAE
2600
+
2601
+ ${o.recommendations.map((p,g)=>`${g+1}. ${p}`).join(`
2602
+ `)}
2603
+
2604
+ ---
2605
+
2606
+ ## \u4F7F\u7528\u8BF4\u660E
2607
+
2608
+ \u672C\u62A5\u544A\u7531 Explore Tool \u81EA\u52A8\u751F\u6210\uFF0C\u4E13\u6CE8\u4E8E\u9879\u76EE\u6574\u4F53\u67B6\u6784\u5206\u6790\u3002
2609
+
2610
+ ### \u76F8\u5173\u5DE5\u5177
2611
+ - **quickProjectScan**: \u5FEB\u901F\u9879\u76EE\u6982\u89C8\uFF08<5\u79D2\uFF09
2612
+ - **ModuleExplorer**: \u6A21\u5757\u7EA7\u6DF1\u5EA6\u5206\u6790
2613
+ - **ToolingExplorer**: \u5DE5\u5177\u94FE\u914D\u7F6E\u5206\u6790
2614
+
2615
+ ---
2616
+
2617
+ *\u62A5\u544A\u751F\u6210\u65F6\u95F4: ${H()}*
2618
+ `;return wr.writeFileSync(l,u,"utf-8"),l}formatAction(e){return`explore({ topic: "${e.topic}" })`}formatObservation(e){return String(e)}},mg=new Cr;Xs=mg});import*as Ae from"fs";import*as Ze from"path";import{globSync as fg}from"glob";import{readFileSync as $c}from"fs";async function Qs(s){return hg.execute(s)}var br,hg,Zs,yg=S(()=>{G();pt();Ie();ae();Fe();br=class extends R{getDefinition(){return{name:"moduleExplore",description:`\u6DF1\u5EA6\u63A2\u7D22\u5355\u4E2A\u6A21\u5757\u7684\u5185\u90E8\u5B9E\u73B0\u3001\u51FD\u6570\u7EC6\u8282\u3001\u8C03\u7528\u94FE\u3002\u9002\u5408\u9700\u8981\u7406\u89E3\u5177\u4F53\u529F\u80FD\u5B9E\u73B0\u7684\u573A\u666F\uFF0860-120\u79D2\uFF09\u3002
2619
+
2620
+ \u{1F4CB} \u7528\u9014\uFF1A
2621
+ - \u5206\u6790\u6A21\u5757\u5185\u90E8\u51FD\u6570\u5B9E\u73B0\u548C\u7B97\u6CD5\u903B\u8F91
2622
+ - \u8FFD\u8E2A\u51FD\u6570\u8C03\u7528\u94FE\u548C\u6570\u636E\u6D41\u5411
2623
+ - \u7406\u89E3\u5177\u4F53\u4E1A\u52A1\u903B\u8F91\u7684\u5B9E\u73B0\u7EC6\u8282
2624
+ - \u8BC6\u522B\u6A21\u5757\u5185\u7684\u8BBE\u8BA1\u6A21\u5F0F\u548C\u6700\u4F73\u5B9E\u8DF5
2625
+
2626
+ \u{1F511} \u53C2\u6570\uFF1A
2627
+ - module: \u8981\u63A2\u7D22\u7684\u6A21\u5757\u540D\u79F0\uFF08\u5FC5\u586B\uFF0C\u5982"\u8BA4\u8BC1\u6A21\u5757"\u3001"\u6570\u636E\u5904\u7406\u6A21\u5757"\uFF09
2628
+ - englishModule: \u82F1\u6587\u6A21\u5757\u540D\u79F0\uFF08\u5FC5\u586B\uFF0C\u751F\u6210\u6587\u6863\u6587\u4EF6\u540D\uFF09
2629
+ - searchPattern: \u53EF\u9009\u641C\u7D22\u8DEF\u5F84\uFF08\u5982"src/auth/**"\uFF09
2630
+
2631
+ \u{1F4A1} \u793A\u4F8B\uFF1A
2632
+ - moduleExplore({ module: "\u8BA4\u8BC1\u6A21\u5757", englishModule: "Authentication Module" })
2633
+ - moduleExplore({ module: "\u5DE5\u5177\u7CFB\u7EDF", englishModule: "Tool System", searchPattern: "src/tools/**" })
2634
+ - moduleExplore({ module: "API\u8DEF\u7531", englishModule: "API Routes", searchPattern: "src/api/**" })
2635
+
2636
+ \u{1F3AF} \u4E0E\u5176\u4ED6\u5DE5\u5177\u7684\u533A\u522B\uFF1A
2637
+ \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510
2638
+ \u2502 \u5DE5\u5177 \u2502 \u5173\u6CE8\u70B9 \u2502
2639
+ \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524
2640
+ \u2502 explore \u2502 \u67B6\u6784\u7EA7\uFF1A\u6A21\u5757\u95F4\u5173\u7CFB\u3001\u8BBE\u8BA1\u6A21\u5F0F \u2502
2641
+ \u2502 moduleExplore \u2502 \u6A21\u5757\u7EA7\uFF1A\u51FD\u6570\u5B9E\u73B0\u3001\u8C03\u7528\u94FE \u2502
2642
+ \u2502 grep + read \u2502 \u4EE3\u7801\u7EA7\uFF1A\u67E5\u627E\u5177\u4F53\u4EE3\u7801\u7247\u6BB5 \u2502
2643
+ \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
2644
+
2645
+ \u5173\u7CFB\u5C42\u6B21\uFF1Aexplore\uFF08\u5B8F\u89C2\uFF09 \u2192 moduleExplore\uFF08\u4E2D\u89C2\uFF09 \u2192 grep+read\uFF08\u5FAE\u89C2\uFF09
2646
+
2647
+ \u2705 \u9002\u5408\u7684\u573A\u666F\uFF1A
2648
+ - \u9700\u8981\u6DF1\u5165\u7406\u89E3\u67D0\u4E2A\u6A21\u5757\u7684\u5177\u4F53\u5B9E\u73B0\u903B\u8F91
2649
+ - \u4FEE\u6539\u6A21\u5757\u529F\u80FD\u524D\uFF0C\u4E86\u89E3\u73B0\u6709\u5B9E\u73B0\u65B9\u5F0F
2650
+ - \u8FFD\u8E2A\u67D0\u4E2A\u529F\u80FD\u7684\u5B8C\u6574\u8C03\u7528\u94FE
2651
+ - \u5206\u6790\u6A21\u5757\u5185\u7684\u7B97\u6CD5\u548C\u6570\u636E\u5904\u7406\u6D41\u7A0B
2652
+ - \u56DE\u7B54"\u8FD9\u4E2A\u6A21\u5757\u5982\u4F55\u5B9E\u73B0"\u7684\u95EE\u9898
2653
+
2654
+ \u274C \u4E0D\u9002\u5408\u7684\u573A\u666F\uFF1A
2655
+ - \u9700\u8981\u7406\u89E3\u6574\u4F53\u9879\u76EE\u67B6\u6784 \u2192 \u4F7F\u7528 explore
2656
+ - \u53EA\u9700\u8981\u5FEB\u901F\u4E86\u89E3\u9879\u76EE\u6280\u672F\u6808 \u2192 \u4F7F\u7528 quickProjectScan
2657
+ - \u9700\u8981\u4E86\u89E3\u6784\u5EFA/\u6D4B\u8BD5\u914D\u7F6E \u2192 \u4F7F\u7528 toolingExplore
2658
+ - \u53EA\u9700\u8981\u67E5\u627E\u67D0\u4E2A\u51FD\u6570\u7684\u4F4D\u7F6E \u2192 \u4F7F\u7528 grep
2659
+ - \u53EA\u9700\u8981\u4FEE\u6539\u67D0\u4E2A\u6587\u4EF6 \u2192 \u76F4\u63A5\u4F7F\u7528 read + write
2660
+
2661
+ \u26A0\uFE0F \u6CE8\u610F\uFF1A
2662
+ - \u672C\u5DE5\u5177\u4E13\u6CE8\u4E8E"\u6A21\u5757\u7EA7"\u5B9E\u73B0\u7EC6\u8282\uFF08HOW\uFF1A\u5982\u4F55\u5B9E\u73B0\uFF09
2663
+ - \u6267\u884C\u65F6\u95F4\u7EA660-120\u79D2\uFF0C\u4F1A\u8BE6\u7EC6\u5206\u6790\u591A\u4E2A\u6587\u4EF6
2664
+ - \u5982\u679C\u4E0D\u786E\u5B9A\u6A21\u5757\u4F4D\u7F6E\uFF0C\u4F7F\u7528 searchPattern \u53C2\u6570
2665
+ - \u7ED3\u679C\u4FDD\u5B58\u5230 .nium/docs/<MODULE>_IMPLEMENTATION.md
2666
+
2667
+ \u{1F4DD} \u8F93\u51FA\uFF1A
2668
+ - \u4FDD\u5B58\u6A21\u5757\u5206\u6790\u62A5\u544A\u5230 .nium/docs/<MODULE>_IMPLEMENTATION.md
2669
+ - \u8FD4\u56DE\u51FD\u6570\u6E05\u5355\u3001\u8C03\u7528\u94FE\u3001\u5B9E\u73B0\u7EC6\u8282`,input_schema:{type:"object",properties:{module:{type:"string",description:"\u8981\u63A2\u7D22\u7684\u6A21\u5757\u540D\u79F0\uFF08\u53EF\u4EE5\u662F\u4E2D\u6587\u6216\u82F1\u6587\uFF0C\u4F8B\u5982\uFF1A'\u8BA4\u8BC1\u6A21\u5757'\u3001'Tool System'\uFF09"},englishModule:{type:"string",description:"\u82F1\u6587\u6A21\u5757\u540D\u79F0\uFF0C\u7528\u4E8E\u751F\u6210\u6587\u4EF6\u540D\uFF08\u4F8B\u5982\uFF1A'Authentication Module'\u3001'Tool System'\uFF09"},searchPattern:{type:"string",description:"\u53EF\u9009\u7684\u641C\u7D22\u8DEF\u5F84\u6A21\u5F0F\uFF0C\u7528\u4E8E\u5B9A\u4F4D\u6A21\u5757\u6587\u4EF6\uFF08\u4F8B\u5982\uFF1A'src/auth/**'\u3001'src/tools/**/*.ts'\uFF09"}},required:["module","englishModule"]}}}async execute(e){try{let t=process.cwd(),n=[];n.push(`\u{1F52C} \u5F00\u59CB\u6A21\u5757\u6DF1\u5EA6\u5206\u6790: ${e.module}
2670
+ `),n.push("\u{1F3AF} \u5B9A\u4F4D\u6A21\u5757\u6587\u4EF6...");let r=await this.locateModuleFiles(e.module,e.englishModule,e.searchPattern);if(n.push(` \u2713 \u627E\u5230 ${r.length} \u4E2A\u76F8\u5173\u6587\u4EF6`),n.push(""),r.length===0)return n.push(`\u274C \u672A\u627E\u5230\u4E0E "${e.module}" \u76F8\u5173\u7684\u6587\u4EF6`),n.push("\u{1F4A1} \u63D0\u793A\uFF1A\u5C1D\u8BD5\u4F7F\u7528 searchPattern \u53C2\u6570\u6307\u5B9A\u641C\u7D22\u8DEF\u5F84"),n.join(`
2671
+ `);n.push("\u{1F3D7}\uFE0F \u5206\u6790\u6A21\u5757\u7ED3\u6784...");let o=await this.analyzeModuleStructure(r);n.push(` \u2713 \u8BC6\u522B ${o.functions.length} \u4E2A\u51FD\u6570/\u65B9\u6CD5`),n.push(` \u2713 \u8BC6\u522B ${o.classes.length} \u4E2A\u7C7B`),n.push(""),n.push("\u{1F517} \u8FFD\u8E2A\u51FD\u6570\u8C03\u7528\u94FE...");let i=await this.traceCallChains(r,o);n.push(` \u2713 \u5206\u6790 ${i.chains.length} \u4E2A\u8C03\u7528\u94FE`),n.push(""),n.push("\u{1F50D} \u6DF1\u5EA6\u4EE3\u7801\u5206\u6790...");let a=await this.performDeepCodeAnalysis(e.module,r,o);n.push(" \u2713 \u4EE3\u7801\u5206\u6790\u5B8C\u6210"),n.push(""),n.push("\u{1F4DD} \u751F\u6210\u5B9E\u73B0\u62A5\u544A...");let c=await this.saveImplementationDoc(e.module,e.englishModule,r,o,i,a);return n.push(` \u2713 \u62A5\u544A\u5DF2\u4FDD\u5B58: ${Ze.relative(t,c)}`),n.push(""),n.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),n.push(`\u6A21\u5757\u5206\u6790: ${e.module}`),n.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),n.push(`
2672
+ \u{1F4C1} \u76F8\u5173\u6587\u4EF6: ${r.length} \u4E2A`),n.push(`\u{1F527} \u51FD\u6570/\u65B9\u6CD5: ${o.functions.length} \u4E2A`),n.push(`\u{1F3D7}\uFE0F \u7C7B\u5B9A\u4E49: ${o.classes.length} \u4E2A`),n.push(`\u{1F517} \u8C03\u7528\u94FE: ${i.chains.length} \u4E2A`),n.push(`
2673
+ \u{1F4A1} \u6838\u5FC3\u529F\u80FD:`),n.push(a.coreFeatures),n.push(`
2674
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
2675
+ `),n.join(`
2676
+ `)}catch(t){return this.formatError("ModuleExplore",t)}}async locateModuleFiles(e,t,n){let r=process.cwd(),o=we(r,!0);if(n)try{let l=fg(n,{nodir:!0,ignore:o,cwd:r});if(l.length>0)return l}catch(l){console.error(`\u641C\u7D22\u6A21\u5F0F ${n} \u5931\u8D25:`,l)}let i=[e.toLowerCase(),t.toLowerCase(),...t.toLowerCase().split(" "),...e.toLowerCase().split(" ")].filter(l=>l.length>2);return fg("**/*",{nodir:!0,ignore:o,cwd:r}).slice(0,200).map(l=>{let u=l.toLowerCase(),p=0;return i.forEach(m=>{u.includes(m)&&(p+=10)}),l.split("/").forEach(m=>{i.forEach(d=>{m.toLowerCase().includes(d)&&(p+=5)})}),{file:l,score:p}}).filter(l=>l.score>0).sort((l,u)=>u.score-l.score).slice(0,30).map(l=>l.file)}async analyzeModuleStructure(e){let t=[],n=[],r=[];return e.forEach(o=>{if(o.endsWith(".js")||o.endsWith(".ts")||o.endsWith(".jsx")||o.endsWith(".tsx"))try{let i=$c(o,"utf-8"),a=i.split(`
2677
+ `),c=[/function\s+(\w+)\s*\(([^)]*)\)/g,/const\s+(\w+)\s*=\s*\(([^)]*)\)\s*=>/g,/async\s+function\s+(\w+)\s*\(([^)]*)\)/g,/(\w+)\s*\(([^)]*)\)\s*:\s*\w+/g];a.forEach((g,m)=>{c.forEach(d=>{let f=d.exec(g);f&&t.push({name:f[1],file:o,line:m+1,params:f[2]?f[2].split(",").map(y=>y.trim()).filter(y=>y):[]})})});let l=/(?:export\s+)?(?:abstract\s+)?class\s+(\w+)/g,u;for(;(u=l.exec(i))!==null;){let g=u[1],m=new RegExp("(?:async\\s+)?(\\w+)\\s*\\([^)]*\\)\\s*[:{]","g"),d=[],f;for(;(f=m.exec(i))!==null;)d.push(f[1]);n.push({name:g,file:o,methods:d.filter(y=>y!==g)})}[/export\s+(?:const|let|var)\s+(\w+)/g,/export\s+function\s+(\w+)/g,/export\s+class\s+(\w+)/g,/export\s*{\s*([^}]+)\s*}/g].forEach(g=>{let m;for(;(m=g.exec(i))!==null;){let d=m[1];d.includes(",")?d.split(",").map(y=>y.trim()).forEach(y=>{y&&r.push({name:y,type:"variable",file:o})}):r.push({name:d,type:"function/class",file:o})}})}catch(i){console.error(`\u5206\u6790\u6587\u4EF6 ${o} \u5931\u8D25:`,i)}}),{functions:t,classes:n,exports:r}}async traceCallChains(e,t){let n=[],r=[],o=/(?:\w+\.)?(\w+)\s*\(/g;return e.forEach(i=>{if(i.endsWith(".js")||i.endsWith(".ts"))try{let a=$c(i,"utf-8");a.split(`
2678
+ `).forEach((p,g)=>{let m;for(;(m=o.exec(p))!==null;){let d=m[1],f=t.functions.find(y=>y.name===d);f&&n.push({from:i,to:f.file,file:i,line:g+1})}});let l=/(?:import.*from\s+['"](.+?)['"]|require\(['"](.+?)['"]\))/g,u;for(;(u=l.exec(a))!==null;){let p=u[1]||u[2];!p.startsWith(".")&&!p.startsWith("/")&&r.push(p)}}catch(a){console.error(`\u8FFD\u8E2A\u8C03\u7528\u94FE ${i} \u5931\u8D25:`,a)}}),{chains:n,dependencies:r}}async performDeepCodeAnalysis(e,t,n){let r=[],o=Math.min(5,t.length);for(let a=0;a<o;a++)try{let c=$c(t[a],"utf-8");r.push({path:t[a],content:c.slice(0,3e3)})}catch(c){console.error(`\u8BFB\u53D6\u6587\u4EF6 ${t[a]} \u5931\u8D25:`,c)}let i=`\u4F60\u662F\u4E00\u4F4D\u8D44\u6DF1\u4EE3\u7801\u5BA1\u67E5\u4E13\u5BB6\uFF0C\u8BF7\u6DF1\u5EA6\u5206\u6790"${e}"\u6A21\u5757\u7684\u5B9E\u73B0\u7EC6\u8282\u3002
2679
+
2680
+ ## \u6A21\u5757\u7ED3\u6784\u4FE1\u606F
2681
+ - \u6587\u4EF6\u6570: ${t.length}
2682
+ - \u51FD\u6570\u6570: ${n.functions.length}
2683
+ - \u7C7B\u6570: ${n.classes.length}
2684
+ - \u5BFC\u51FA\u6570: ${n.exports.length}
2685
+
2686
+ ## \u5173\u952E\u6587\u4EF6\u5185\u5BB9
2687
+ ${r.map(a=>`### ${a.path}
2688
+ \`\`\`
2689
+ ${a.content}
2690
+ \`\`\`
2691
+ `).join(`
2692
+ `)}
2693
+
2694
+ \u8BF7\u63D0\u4F9B\u4EE5\u4E0B\u5206\u6790\uFF1A
2695
+ 1. **\u6838\u5FC3\u529F\u80FD**: \u7B80\u8981\u63CF\u8FF0\u6A21\u5757\u7684\u4E3B\u8981\u529F\u80FD\u548C\u804C\u8D23\uFF082-3\u53E5\u8BDD\uFF09
2696
+ 2. **\u7B97\u6CD5\u8BC6\u522B**: \u5217\u51FA\u4E3B\u8981\u7B97\u6CD5\u53CA\u5176\u590D\u6742\u5EA6
2697
+ 3. **\u5B9E\u73B0\u6A21\u5F0F**: \u8BC6\u522B\u7684\u5B9E\u73B0\u6A21\u5F0F\u548C\u6700\u4F73\u5B9E\u8DF5
2698
+
2699
+ \u4EE5JSON\u683C\u5F0F\u8FD4\u56DE\uFF1A
2700
+ {
2701
+ "coreFeatures": "\u6838\u5FC3\u529F\u80FD\u63CF\u8FF0",
2702
+ "algorithms": [
2703
+ {"name": "\u7B97\u6CD5\u540D", "description": "\u63CF\u8FF0", "complexity": "O(n)"}
2704
+ ],
2705
+ "patterns": [
2706
+ {"name": "\u6A21\u5F0F\u540D", "description": "\u63CF\u8FF0"}
2707
+ ]
2708
+ }`;try{let c=(await Z({model:ge(),messages:[{role:"user",content:i}],temperature:.2,max_tokens:2e3}))?.choices?.[0]?.message?.content||"{}",l=c.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/)||c.match(/(\{[\s\S]*?\})/);if(l){let u=JSON.parse(l[1]);return{coreFeatures:u.coreFeatures||"\u65E0\u6CD5\u5206\u6790\u6838\u5FC3\u529F\u80FD",algorithms:Array.isArray(u.algorithms)?u.algorithms:[],patterns:Array.isArray(u.patterns)?u.patterns:[]}}}catch(a){console.error("\u6DF1\u5EA6\u4EE3\u7801\u5206\u6790\u5931\u8D25:",a)}return{coreFeatures:`\u5305\u542B ${n.functions.length} \u4E2A\u51FD\u6570\u7684\u6A21\u5757`,algorithms:[],patterns:[]}}async saveImplementationDoc(e,t,n,r,o,i){let a=process.cwd(),c=Ze.join(a,".nium","docs");Ae.existsSync(c)||Ae.mkdirSync(c,{recursive:!0});let l=t.replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase()+"_IMPLEMENTATION.md",u=Ze.join(c,l),p=`# ${e} - \u5B9E\u73B0\u7EC6\u8282\u5206\u6790
2709
+
2710
+ > \u751F\u6210\u65F6\u95F4: ${H()}
2711
+ > \u751F\u6210\u5DE5\u5177: Module Explorer (\u6A21\u5757\u7EA7\u6DF1\u5EA6\u5206\u6790)
2712
+
2713
+ ---
2714
+
2715
+ ## \u6838\u5FC3\u529F\u80FD
2716
+
2717
+ ${i.coreFeatures}
2718
+
2719
+ ---
2720
+
2721
+ ## \u6587\u4EF6\u7ED3\u6784
2722
+
2723
+ ### \u76F8\u5173\u6587\u4EF6 (${n.length} \u4E2A)
2724
+
2725
+ ${n.map(g=>`- \`${g}\``).join(`
2726
+ `)}
2727
+
2728
+ ---
2729
+
2730
+ ## \u51FD\u6570/\u65B9\u6CD5\u6E05\u5355
2731
+
2732
+ ### \u51FD\u6570\u5217\u8868 (${r.functions.length} \u4E2A)
2733
+
2734
+ ${r.functions.map(g=>`#### ${g.name}
2735
+ - **\u4F4D\u7F6E**: \`${g.file}:${g.line}\`
2736
+ - **\u53C2\u6570**: ${g.params.length>0?g.params.map(m=>`\`${m}\``).join(", "):"\u65E0\u53C2\u6570"}
2737
+ ${g.returnType?`- **\u8FD4\u56DE\u7C7B\u578B**: \`${g.returnType}\``:""}`).join(`
2738
+
2739
+ `)}
2740
+
2741
+ ### \u7C7B\u5B9A\u4E49 (${r.classes.length} \u4E2A)
2742
+
2743
+ ${r.classes.map(g=>`#### ${g.name}
2744
+ - **\u4F4D\u7F6E**: \`${g.file}\`
2745
+ - **\u65B9\u6CD5**: ${g.methods.length>0?g.methods.map(m=>`\`${m}()\``).join(", "):"\u65E0"}`).join(`
2746
+
2747
+ `)}
2748
+
2749
+ ### \u5BFC\u51FA\u9879 (${r.exports.length} \u4E2A)
2750
+
2751
+ ${r.exports.map(g=>`- **\`${g.name}\`** (${g.type}) - \`${g.file}\``).join(`
2752
+ `)}
2753
+
2754
+ ---
2755
+
2756
+ ## \u8C03\u7528\u94FE\u5206\u6790
2757
+
2758
+ ### \u5185\u90E8\u8C03\u7528 (${o.chains.length} \u4E2A)
2759
+
2760
+ ${o.chains.slice(0,20).map(g=>`- \`${g.file}:${g.line}\` \u2192 \`${g.to}\``).join(`
2761
+ `)}
2762
+
2763
+ ### \u5916\u90E8\u4F9D\u8D56 (${o.dependencies.length} \u4E2A)
2764
+
2765
+ ${o.dependencies.map(g=>`- \`${g}\``).join(`
2766
+ `)}
2767
+
2768
+ ---
2769
+
2770
+ ## \u7B97\u6CD5\u5206\u6790
2771
+
2772
+ ${i.algorithms.length>0?i.algorithms.map(g=>`
2773
+ ### ${g.name}
2774
+ - **\u63CF\u8FF0**: ${g.description}
2775
+ - **\u590D\u6742\u5EA6**: \`${g.complexity}\`
2776
+ `).join(""):"\u6682\u672A\u8BC6\u522B\u5230\u7279\u5B9A\u7B97\u6CD5"}
2777
+
2778
+ ---
2779
+
2780
+ ## \u5B9E\u73B0\u6A21\u5F0F
2781
+
2782
+ ${i.patterns.length>0?i.patterns.map(g=>`
2783
+ ### ${g.name}
2784
+ ${g.description}
2785
+ `).join(""):"\u6682\u672A\u8BC6\u522B\u5230\u7279\u5B9A\u5B9E\u73B0\u6A21\u5F0F"}
2786
+
2787
+ ---
2788
+
2789
+ ## \u4F7F\u7528\u8BF4\u660E
2790
+
2791
+ \u672C\u62A5\u544A\u7531 Module Explorer \u81EA\u52A8\u751F\u6210\uFF0C\u4E13\u6CE8\u4E8E\u6A21\u5757\u5185\u90E8\u5B9E\u73B0\u7EC6\u8282\u5206\u6790\u3002
2792
+
2793
+ ### \u76F8\u5173\u5DE5\u5177
2794
+ - **quickProjectScan**: \u5FEB\u901F\u9879\u76EE\u6982\u89C8\uFF08<5\u79D2\uFF09
2795
+ - **Explore**: \u67B6\u6784\u7EA7\u5206\u6790\uFF0830-60\u79D2\uFF09
2796
+ - **ToolingExplorer**: \u5DE5\u5177\u94FE\u914D\u7F6E\u5206\u6790
2797
+
2798
+ ---
2799
+
2800
+ *\u62A5\u544A\u751F\u6210\u65F6\u95F4: ${H()}*
2801
+ `;try{if(!Ae.existsSync(u))Ae.writeFileSync(u,p,"utf-8"),console.log(`\u2713 \u6A21\u5757\u5206\u6790\u62A5\u544A\u5DF2\u4FDD\u5B58: ${Ze.relative(a,u)}`);else{let g=Ze.join(a,".nium","merge");Ae.existsSync(g)||Ae.mkdirSync(g,{recursive:!0});let m=`module-${t.replace(/[^a-zA-Z0-9]+/g,"_").toLowerCase()}-merge-${Date.now()}.md`,d=Ze.join(g,m),f=`# ${l} \u5408\u5E76\u8BF7\u6C42
2802
+
2803
+ ## \u5F53\u524D\u6587\u4EF6\u5185\u5BB9
2804
+ ${Ae.readFileSync(u,"utf-8")}
2805
+
2806
+ ## \u65B0\u751F\u6210\u5185\u5BB9
2807
+ ${p}
2808
+
2809
+ ## \u5408\u5E76\u8981\u6C42
2810
+ \u8BF7\u6839\u636E\u4EE5\u4E0B\u539F\u5219\u5408\u5E76\u8FD9\u4E24\u4E2A\u5185\u5BB9\uFF1A
2811
+ 1. \u4FDD\u7559\u6700\u65B0\u7684\u751F\u6210\u65F6\u95F4\u548C\u5DE5\u5177\u4FE1\u606F
2812
+ 2. \u5408\u5E76\u6838\u5FC3\u529F\u80FD\u63CF\u8FF0\uFF0C\u4FDD\u7559\u66F4\u8BE6\u7EC6\u548C\u51C6\u786E\u7684\u4FE1\u606F
2813
+ 3. \u5408\u5E76\u6587\u4EF6\u7ED3\u6784\u5217\u8868\uFF0C\u53BB\u9664\u91CD\u590D\u7684\u6587\u4EF6\uFF0C\u4FDD\u7559\u6240\u6709\u76F8\u5173\u6587\u4EF6
2814
+ 4. \u5408\u5E76\u51FD\u6570/\u65B9\u6CD5\u6E05\u5355\uFF0C\u4FDD\u7559\u6240\u6709\u5DF2\u8BC6\u522B\u7684\u51FD\u6570\u548C\u7C7B\uFF0C\u66F4\u65B0\u4F4D\u7F6E\u4FE1\u606F\u4E3A\u6700\u65B0
2815
+ 5. \u5408\u5E76\u8C03\u7528\u94FE\u5206\u6790\uFF0C\u4FDD\u7559\u66F4\u5B8C\u6574\u7684\u8C03\u7528\u5173\u7CFB
2816
+ 6. \u5408\u5E76\u7B97\u6CD5\u5206\u6790\u548C\u5B9E\u73B0\u6A21\u5F0F\uFF0C\u4FDD\u7559\u6240\u6709\u5DF2\u8BC6\u522B\u7684\u7B97\u6CD5\u548C\u6A21\u5F0F
2817
+ 7. \u786E\u4FDD\u5408\u5E76\u540E\u7684\u6587\u6863\u7ED3\u6784\u6E05\u6670\uFF0C\u6570\u636E\u5B8C\u6574\uFF0C\u4FBF\u4E8E\u9605\u8BFB\u548C\u68C0\u7D22
2818
+ 8. \u4F18\u5148\u4FDD\u7559\u65B0\u5185\u5BB9\u4E2D\u7684\u6570\u636E\uFF0C\u4F46\u4E0D\u8981\u4E22\u5931\u65E7\u5185\u5BB9\u4E2D\u72EC\u6709\u7684\u6709\u4EF7\u503C\u4FE1\u606F
2819
+ `;Ae.writeFileSync(d,f,"utf-8"),console.log(`\u2713 \u6A21\u5757\u5206\u6790\u62A5\u544A\u5DF2\u751F\u6210\u5408\u5E76\u8BF7\u6C42: ${Ze.relative(a,d)}`),console.log(" \u6B63\u5728\u8C03\u7528\u6A21\u578B\u5904\u7406\u5408\u5E76\u903B\u8F91...");let y=`\u4F60\u662F\u4E00\u4F4D\u4E13\u4E1A\u7684\u6587\u6863\u5408\u5E76\u4E13\u5BB6\u3002\u8BF7\u6839\u636E\u63D0\u4F9B\u7684\u5408\u5E76\u8BF7\u6C42\uFF0C\u5C06\u5F53\u524D\u6587\u4EF6\u5185\u5BB9\u548C\u65B0\u751F\u6210\u5185\u5BB9\u5408\u5E76\u4E3A\u4E00\u4E2A\u9AD8\u8D28\u91CF\u7684\u6A21\u5757\u5B9E\u73B0\u5206\u6790\u6587\u6863\u3002
2820
+
2821
+ ${f}
2822
+
2823
+ \u8BF7\u76F4\u63A5\u8FD4\u56DE\u5408\u5E76\u540E\u7684\u5B8C\u6574\u5185\u5BB9\uFF0C\u4E0D\u8981\u6DFB\u52A0\u4EFB\u4F55\u989D\u5916\u7684\u89E3\u91CA\u6216\u8BF4\u660E\u3002`,T=(await Z({model:ge(),messages:[{role:"user",content:y}],temperature:.1,max_tokens:8e3,tools:[]}))?.choices?.[0]?.message?.content;T?(Ae.writeFileSync(u,T,"utf-8"),console.log(` \u2713 \u5408\u5E76\u5B8C\u6210\uFF0C${l} \u5DF2\u66F4\u65B0`)):console.log(" \u26A0\uFE0F \u6A21\u578B\u672A\u8FD4\u56DE\u6709\u6548\u5408\u5E76\u7ED3\u679C\uFF0C\u4FDD\u7559\u539F\u6587\u4EF6")}}catch(g){console.error(`\u4FDD\u5B58\u6A21\u5757\u6587\u6863\u65F6\u51FA\u9519: ${g.message}`),Ae.writeFileSync(u,p,"utf-8"),console.log(` \u26A0\uFE0F \u5DF2\u4FDD\u5B58\u65B0\u5185\u5BB9\u5230 ${Ze.relative(a,u)}`)}return u}formatAction(e){return`moduleExplore({ module: "${e.module}" })`}formatObservation(e){return String(e)}},hg=new br;Zs=hg});import*as ft from"fs";import*as eo from"path";import{globSync as Ic}from"glob";import{readFileSync as xg}from"fs";async function to(s){return Sg.execute(s||{})}var vr,Sg,no,Cg=S(()=>{G();pt();Ie();ae();Fe();vr=class extends R{getDefinition(){return{name:"toolingExplore",description:`\u6DF1\u5EA6\u5206\u6790\u9879\u76EE\u7684\u5F00\u53D1\u5DE5\u5177\u94FE\u914D\u7F6E\uFF0C\u5305\u62EC\u6784\u5EFA\u5DE5\u5177\u3001\u6D4B\u8BD5\u6846\u67B6\u3001CI/CD\u7B49\u3002\u9002\u5408\u9700\u8981\u7406\u89E3\u9879\u76EE\u5982\u4F55\u6784\u5EFA\u548C\u8FD0\u884C\u7684\u573A\u666F\uFF0830-60\u79D2\uFF09\u3002
2824
+
2825
+ \u{1F4CB} \u7528\u9014\uFF1A
2826
+ - \u5206\u6790\u6784\u5EFA\u914D\u7F6E\u548C\u4F9D\u8D56\u7BA1\u7406
2827
+ - \u7406\u89E3\u6D4B\u8BD5\u6846\u67B6\u548C\u6D4B\u8BD5\u7B56\u7565
2828
+ - \u89E3\u6790CI/CD\u914D\u7F6E\u548C\u90E8\u7F72\u6D41\u7A0B
2829
+ - \u8BC6\u522B\u4EE3\u7801\u8D28\u91CF\u5DE5\u5177\u548C\u89C4\u8303\u914D\u7F6E
2830
+
2831
+ \u{1F511} \u53C2\u6570\uFF1A
2832
+ - focus: \u53EF\u9009\u7684\u805A\u7126\u4E3B\u9898\uFF08\u5982"\u6784\u5EFA\u914D\u7F6E"\u3001"\u6D4B\u8BD5\u6846\u67B6"\u3001"\u90E8\u7F72\u914D\u7F6E"\uFF09
2833
+ - englishFocus: \u82F1\u6587\u805A\u7126\u4E3B\u9898\uFF0C\u7528\u4E8E\u751F\u6210\u6587\u6863\u6587\u4EF6\u540D
2834
+
2835
+ \u{1F4A1} \u793A\u4F8B\uFF1A
2836
+ - toolingExplore({}) - \u5206\u6790\u5B8C\u6574\u5DE5\u5177\u94FE
2837
+ - toolingExplore({ focus: "\u6784\u5EFA\u914D\u7F6E", englishFocus: "Build Configuration" })
2838
+ - toolingExplore({ focus: "\u6D4B\u8BD5\u6846\u67B6", englishFocus: "Test Framework" })
2839
+ - toolingExplore({ focus: "\u90E8\u7F72\u914D\u7F6E", englishFocus: "Deployment Configuration" })
2840
+
2841
+ \u{1F3AF} \u4E0E\u5176\u4ED6\u5DE5\u5177\u7684\u533A\u522B\uFF1A
2842
+ \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510
2843
+ \u2502 \u5DE5\u5177 \u2502 \u5173\u6CE8\u70B9 \u2502
2844
+ \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524
2845
+ \u2502 quickProjectScan\u2502 \u9879\u76EE\u6982\u89C8\uFF1A\u6280\u672F\u6808\u3001\u76EE\u5F55\u7ED3\u6784 \u2502
2846
+ \u2502 explore \u2502 \u4EE3\u7801\u67B6\u6784\uFF1A\u6A21\u5757\u5173\u7CFB\u3001\u8BBE\u8BA1\u6A21\u5F0F \u2502
2847
+ \u2502 moduleExplore \u2502 \u6A21\u5757\u5B9E\u73B0\uFF1A\u51FD\u6570\u7EC6\u8282\u3001\u8C03\u7528\u94FE \u2502
2848
+ \u2502 toolingExplore \u2502 \u5DE5\u5177\u94FE\uFF1A\u6784\u5EFA/\u6D4B\u8BD5/\u90E8\u7F72\u914D\u7F6E \u2502
2849
+ \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
2850
+
2851
+ \u5173\u6CE8\u7EF4\u5EA6\uFF1Aexplore\uFF08\u4E1A\u52A1\u903B\u8F91\uFF09 vs toolingExplore\uFF08DevOps\u914D\u7F6E\uFF09
2852
+
2853
+ \u2705 \u9002\u5408\u7684\u573A\u666F\uFF1A
2854
+ - \u9700\u8981\u4E86\u89E3\u5982\u4F55\u6784\u5EFA\u548C\u8FD0\u884C\u9879\u76EE
2855
+ - \u9700\u8981\u914D\u7F6E\u5F00\u53D1\u73AF\u5883\u6216CI/CD
2856
+ - \u5206\u6790\u6D4B\u8BD5\u6846\u67B6\u548C\u6D4B\u8BD5\u7B56\u7565
2857
+ - \u4E86\u89E3\u4EE3\u7801\u8D28\u91CF\u5DE5\u5177\u548C\u89C4\u8303
2858
+ - \u56DE\u7B54"\u5982\u4F55\u6784\u5EFA/\u6D4B\u8BD5/\u90E8\u7F72"\u7684\u95EE\u9898
2859
+
2860
+ \u274C \u4E0D\u9002\u5408\u7684\u573A\u666F\uFF1A
2861
+ - \u9700\u8981\u7406\u89E3\u4E1A\u52A1\u4EE3\u7801\u67B6\u6784 \u2192 \u4F7F\u7528 explore
2862
+ - \u9700\u8981\u6DF1\u5165\u4E86\u89E3\u67D0\u4E2A\u6A21\u5757\u5B9E\u73B0 \u2192 \u4F7F\u7528 moduleExplore
2863
+ - \u53EA\u9700\u8981\u5FEB\u901F\u4E86\u89E3\u9879\u76EE\u6280\u672F\u6808 \u2192 \u4F7F\u7528 quickProjectScan
2864
+ - \u9700\u8981\u67E5\u627E\u6216\u4FEE\u6539\u4E1A\u52A1\u4EE3\u7801 \u2192 \u4F7F\u7528 grep + read/write
2865
+ - \u53EA\u662F\u8FD0\u884C\u5DF2\u6709\u7684\u6784\u5EFA\u547D\u4EE4 \u2192 \u76F4\u63A5\u4F7F\u7528 shell
2866
+
2867
+ \u26A0\uFE0F \u6CE8\u610F\uFF1A
2868
+ - \u672C\u5DE5\u5177\u4E13\u6CE8\u4E8E\u5DE5\u5177\u94FE\u914D\u7F6E\u5206\u6790\uFF0830-60\u79D2\uFF09
2869
+ - \u4E0D\u5206\u6790\u4E1A\u52A1\u903B\u8F91\uFF0C\u53EA\u5173\u6CE8"\u5982\u4F55\u6784\u5EFA\u548C\u8FD0\u884C"
2870
+ - \u7ED3\u679C\u4FDD\u5B58\u5230 .nium/docs/<TOOLING>_ANALYSIS.md
2871
+
2872
+ \u{1F4DD} \u8F93\u51FA\uFF1A
2873
+ - \u4FDD\u5B58\u5DE5\u5177\u94FE\u62A5\u544A\u5230 .nium/docs/<TOOLING>_ANALYSIS.md
2874
+ - \u8FD4\u56DE\u914D\u7F6E\u8BE6\u60C5\u3001\u5DE5\u5177\u7248\u672C\u3001\u4F7F\u7528\u6307\u5357`,input_schema:{type:"object",properties:{focus:{type:"string",description:"\u53EF\u9009\u7684\u805A\u7126\u4E3B\u9898\uFF08\u5982\uFF1A'\u6784\u5EFA\u914D\u7F6E'\u3001'\u6D4B\u8BD5\u6846\u67B6'\u3001'\u90E8\u7F72\u914D\u7F6E'\uFF09"},englishFocus:{type:"string",description:"\u82F1\u6587\u805A\u7126\u4E3B\u9898\uFF0C\u7528\u4E8E\u751F\u6210\u6587\u4EF6\u540D\uFF08\u5982\uFF1A'Build Configuration'\u3001'Test Framework'\uFF09"}},required:[]}}}async execute(e){try{let t=process.cwd(),n=[],r=e.focus||"\u5B8C\u6574\u5DE5\u5177\u94FE";n.push(`\u{1F6E0}\uFE0F \u5F00\u59CB\u5DE5\u5177\u94FE\u5206\u6790: ${r}
2875
+ `),n.push("\u{1F4C4} \u626B\u63CF\u914D\u7F6E\u6587\u4EF6...");let o=await this.scanConfigFiles();n.push(` \u2713 \u627E\u5230 ${o.length} \u4E2A\u914D\u7F6E\u6587\u4EF6`),n.push(""),n.push("\u{1F528} \u5206\u6790\u6784\u5EFA\u5DE5\u5177...");let i=await this.analyzeBuildTools(o);n.push(` \u2713 \u8BC6\u522B ${i.length} \u4E2A\u6784\u5EFA\u5DE5\u5177`),n.push(""),n.push("\u{1F9EA} \u5206\u6790\u6D4B\u8BD5\u6846\u67B6...");let a=await this.analyzeTestFrameworks(o);n.push(` \u2713 \u8BC6\u522B ${a.length} \u4E2A\u6D4B\u8BD5\u6846\u67B6`),n.push(""),n.push("\u{1F4CA} \u5206\u6790\u4EE3\u7801\u8D28\u91CF\u5DE5\u5177...");let c=await this.analyzeQualityTools(o);n.push(` \u2713 \u8BC6\u522B ${c.length} \u4E2A\u4EE3\u7801\u8D28\u91CF\u5DE5\u5177`),n.push(""),n.push("\u{1F680} \u5206\u6790CI/CD\u914D\u7F6E...");let l=await this.analyzeCICDConfigs(o);n.push(` \u2713 \u8BC6\u522B ${l.length} \u4E2ACI/CD\u914D\u7F6E`),n.push(""),n.push("\u{1F4A1} \u751F\u6210\u4F7F\u7528\u5EFA\u8BAE...");let u=await this.generateRecommendations(i,a,c,l,r);n.push(" \u2713 \u5EFA\u8BAE\u751F\u6210\u5B8C\u6210"),n.push(""),n.push("\u{1F4DD} \u751F\u6210\u5DE5\u5177\u94FE\u62A5\u544A...");let p=await this.saveToolingDoc(r,e.englishFocus||"Tooling Analysis",o,i,a,c,l,u);return n.push(` \u2713 \u62A5\u544A\u5DF2\u4FDD\u5B58: ${eo.relative(t,p)}`),n.push(""),n.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),n.push(`\u5DE5\u5177\u94FE\u5206\u6790: ${r}`),n.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),n.push(`
2876
+ \u{1F528} \u6784\u5EFA\u5DE5\u5177: ${i.map(g=>g.name).join(", ")||"\u65E0"}`),n.push(`\u{1F9EA} \u6D4B\u8BD5\u6846\u67B6: ${a.map(g=>g.name).join(", ")||"\u65E0"}`),n.push(`\u{1F4CA} \u8D28\u91CF\u5DE5\u5177: ${c.map(g=>g.name).join(", ")||"\u65E0"}`),n.push(`\u{1F680} CI/CD: ${l.map(g=>g.name).join(", ")||"\u65E0"}`),n.push(`
2877
+ \u{1F4A1} \u4E3B\u8981\u53D1\u73B0:`),n.push(u.summary),n.push(`
2878
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
2879
+ `),n.join(`
2880
+ `)}catch(t){return this.formatError("ToolingExplore",t)}}async scanConfigFiles(){let e=process.cwd(),t=we(e,!0),n=["package*.json","*.config.js","*.config.ts","tsconfig*.json","babel.config.*",".babelrc*","webpack*.config.*","rollup.config.*","vite.config.*","jest.config.*",".eslintrc*","eslint.config.*",".prettierrc*","prettier.config.*",".editorconfig","Dockerfile*","docker-compose*.yml",".github/workflows/*.yml",".github/workflows/*.yaml","Makefile","CMakeLists.txt","Cargo.toml","Cargo.lock","go.mod","go.sum","requirements*.txt","setup.py","pyproject.toml","Pipfile*","poetry.lock","pom.xml","build.gradle","settings.gradle","gradle.properties","composer.json","Gemfile*","*.sln","*.csproj",".gitignore",".npmignore",".dockerignore","yarn.lock","pnpm-lock.yaml","package-lock.json"],r=[];return n.forEach(o=>{try{let i=Ic(o,{nodir:!0,ignore:t,cwd:e});r.push(...i)}catch{}}),[...new Set(r)].sort()}async analyzeBuildTools(e){let t=[],n=e.find(i=>i==="package.json");if(n)try{let i=JSON.parse(xg(n,"utf-8")),a={name:"npm/yarn/pnpm",configFiles:[n],scripts:i.scripts||{}};ft.existsSync("yarn.lock")?a.name="yarn":ft.existsSync("pnpm-lock.yaml")&&(a.name="pnpm");let c=i.devDependencies||{};c.webpack&&t.push({name:"webpack",version:c.webpack,configFiles:[],scripts:{}}),c.vite&&t.push({name:"vite",version:c.vite,configFiles:[],scripts:{}}),c.rollup&&t.push({name:"rollup",version:c.rollup,configFiles:[],scripts:{}}),c.parcel&&t.push({name:"parcel",version:c.parcel,configFiles:[],scripts:{}}),t.unshift(a)}catch(i){console.error("\u89E3\u6790 package.json \u5931\u8D25:",i)}let r=e.filter(i=>i.includes("webpack"));r.length>0&&t.push({name:"webpack",configFiles:r,scripts:{}});let o=e.filter(i=>i.includes("vite.config"));return o.length>0&&t.push({name:"vite",configFiles:o,scripts:{}}),e.includes("Cargo.toml")&&t.push({name:"Cargo",configFiles:["Cargo.toml"],scripts:{}}),e.includes("go.mod")&&t.push({name:"Go Modules",configFiles:["go.mod"],scripts:{}}),e.includes("pom.xml")&&t.push({name:"Maven",configFiles:["pom.xml"],scripts:{}}),e.includes("build.gradle")&&t.push({name:"Gradle",configFiles:["build.gradle"],scripts:{}}),t}async analyzeTestFrameworks(e){let t=[],r=Ic("**/*test*.{js,ts,jsx,tsx}",{nodir:!0}).slice(0,10),o=e.find(i=>i==="package.json");if(o)try{let i=JSON.parse(xg(o,"utf-8")),a={...i.dependencies,...i.devDependencies};a.jest&&t.push({name:"Jest",version:a.jest,configFiles:e.filter(c=>c.includes("jest")),testFiles:r,coverage:!0}),a.mocha&&t.push({name:"Mocha",version:a.mocha,configFiles:[],testFiles:r}),a.vitest&&t.push({name:"Vitest",version:a.vitest,configFiles:e.filter(c=>c.includes("vitest")),testFiles:r,coverage:!0}),a.cypress&&t.push({name:"Cypress",version:a.cypress,configFiles:e.filter(c=>c.includes("cypress")),testFiles:[]}),a.playwright&&t.push({name:"Playwright",version:a.playwright,configFiles:e.filter(c=>c.includes("playwright")),testFiles:[]})}catch(i){console.error("\u89E3\u6790\u6D4B\u8BD5\u6846\u67B6\u5931\u8D25:",i)}return e.some(i=>i.includes("pytest"))&&t.push({name:"pytest",configFiles:e.filter(i=>i.includes("pytest")),testFiles:Ic("**/test_*.py",{nodir:!0}).slice(0,10)}),t}async analyzeQualityTools(e){let t=[],n=e.filter(i=>i.includes("eslint"));n.length>0&&t.push({name:"ESLint",configFiles:n});let r=e.filter(i=>i.includes("prettier"));r.length>0&&t.push({name:"Prettier",configFiles:r});let o=e.filter(i=>i.includes("tsconfig"));return o.length>0&&t.push({name:"TypeScript",configFiles:o}),e.includes(".editorconfig")&&t.push({name:"EditorConfig",configFiles:[".editorconfig"]}),(ft.existsSync(".husky")||e.some(i=>i.includes("husky")))&&t.push({name:"Husky",configFiles:[".husky"]}),t}async analyzeCICDConfigs(e){let t=[],n=e.filter(o=>o.includes(".github/workflows"));n.length>0&&t.push({name:"GitHub Actions",configFiles:n});let r=e.filter(o=>o.includes("Dockerfile")||o.includes("docker-compose"));return r.length>0&&t.push({name:"Docker",configFiles:r}),e.includes("Makefile")&&t.push({name:"Make",configFiles:["Makefile"]}),t}async generateRecommendations(e,t,n,r,o){let i=`\u4F60\u662F\u4E00\u4F4DDevOps\u4E13\u5BB6\uFF0C\u8BF7\u5206\u6790\u4EE5\u4E0B\u5DE5\u5177\u94FE\u914D\u7F6E\u5E76\u63D0\u4F9B\u5EFA\u8BAE\uFF1A
2881
+
2882
+ ## \u6784\u5EFA\u5DE5\u5177
2883
+ ${e.map(a=>`- ${a.name}: ${a.configFiles.join(", ")}`).join(`
2884
+ `)}
2885
+
2886
+ ## \u6D4B\u8BD5\u6846\u67B6
2887
+ ${t.map(a=>`- ${a.name}: ${a.testFiles.length} \u4E2A\u6D4B\u8BD5\u6587\u4EF6`).join(`
2888
+ `)}
2889
+
2890
+ ## \u4EE3\u7801\u8D28\u91CF\u5DE5\u5177
2891
+ ${n.map(a=>`- ${a.name}: ${a.configFiles.join(", ")}`).join(`
2892
+ `)}
2893
+
2894
+ ## CI/CD\u914D\u7F6E
2895
+ ${r.map(a=>`- ${a.name}: ${a.configFiles.join(", ")}`).join(`
2896
+ `)}
2897
+
2898
+ \u805A\u7126\u4E3B\u9898: ${o}
2899
+
2900
+ \u8BF7\u63D0\u4F9B\uFF1A
2901
+ 1. \u5DE5\u5177\u94FE\u6458\u8981\uFF082-3\u53E5\u8BDD\uFF09
2902
+ 2. 3-5\u4E2A\u6539\u8FDB\u5EFA\u8BAE
2903
+ 3. \u5E38\u7528\u5F00\u53D1\u547D\u4EE4
2904
+
2905
+ \u4EE5JSON\u683C\u5F0F\u8FD4\u56DE\uFF1A
2906
+ {
2907
+ "summary": "\u5DE5\u5177\u94FE\u6458\u8981",
2908
+ "recommendations": ["\u5EFA\u8BAE1", "\u5EFA\u8BAE2"],
2909
+ "commands": ["\u547D\u4EE41", "\u547D\u4EE42"]
2910
+ }`;try{let c=(await Z({model:ge(),messages:[{role:"user",content:i}],temperature:.3,max_tokens:1500}))?.choices?.[0]?.message?.content||"{}",l=c.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/)||c.match(/(\{[\s\S]*?\})/);if(l){let u=JSON.parse(l[1]);return{summary:u.summary||"\u5DE5\u5177\u94FE\u5206\u6790\u5B8C\u6210",recommendations:Array.isArray(u.recommendations)?u.recommendations:[],commands:Array.isArray(u.commands)?u.commands:[]}}}catch(a){console.error("\u751F\u6210\u5EFA\u8BAE\u5931\u8D25:",a)}return{summary:"\u9879\u76EE\u5177\u6709\u57FA\u672C\u7684\u5F00\u53D1\u5DE5\u5177\u94FE\u914D\u7F6E",recommendations:["\u5EFA\u8BAE\u6DFB\u52A0\u66F4\u591A\u81EA\u52A8\u5316\u5DE5\u5177","\u8003\u8651\u6DFB\u52A0\u4EE3\u7801\u8986\u76D6\u7387\u68C0\u67E5"],commands:["npm install","npm test","npm run build"]}}async saveToolingDoc(e,t,n,r,o,i,a,c){let l=process.cwd(),u=eo.join(l,".nium","docs");ft.existsSync(u)||ft.mkdirSync(u,{recursive:!0});let p=t.replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase()+"_ANALYSIS.md",g=eo.join(u,p),m=`# ${e} - \u5DE5\u5177\u94FE\u5206\u6790\u62A5\u544A
2911
+
2912
+ > \u751F\u6210\u65F6\u95F4: ${H()}
2913
+ > \u751F\u6210\u5DE5\u5177: Tooling Explorer (\u5DE5\u5177\u94FE\u5206\u6790)
2914
+
2915
+ ---
2916
+
2917
+ ## \u5DE5\u5177\u94FE\u6458\u8981
2918
+
2919
+ ${c.summary}
2920
+
2921
+ ---
2922
+
2923
+ ## \u914D\u7F6E\u6587\u4EF6\u6982\u89C8
2924
+
2925
+ \u5171\u53D1\u73B0 ${n.length} \u4E2A\u914D\u7F6E\u6587\u4EF6\uFF1A
2926
+
2927
+ ${n.map(d=>`- \`${d}\``).join(`
2928
+ `)}
2929
+
2930
+ ---
2931
+
2932
+ ## \u6784\u5EFA\u5DE5\u5177\u5206\u6790
2933
+
2934
+ ${r.map(d=>`
2935
+ ### ${d.name}
2936
+ - **\u914D\u7F6E\u6587\u4EF6**: ${d.configFiles.length>0?d.configFiles.map(f=>`\`${f}\``).join(", "):"\u65E0"}
2937
+ ${d.version?`- **\u7248\u672C**: \`${d.version}\``:""}
2938
+ ${Object.keys(d.scripts).length>0?`
2939
+ **\u6784\u5EFA\u811A\u672C**:
2940
+ ${Object.entries(d.scripts).map(([f,y])=>`- \`${f}\`: \`${y}\``).join(`
2941
+ `)}
2942
+ `:""}
2943
+ `).join("")}
2944
+
2945
+ ---
2946
+
2947
+ ## \u6D4B\u8BD5\u6846\u67B6\u5206\u6790
2948
+
2949
+ ${o.length>0?o.map(d=>`
2950
+ ### ${d.name}
2951
+ - **\u7248\u672C**: ${d.version||"\u672A\u77E5"}
2952
+ - **\u914D\u7F6E\u6587\u4EF6**: ${d.configFiles.map(f=>`\`${f}\``).join(", ")||"\u65E0"}
2953
+ - **\u6D4B\u8BD5\u6587\u4EF6\u6570**: ${d.testFiles.length}
2954
+ ${d.coverage?"- **\u652F\u6301\u4EE3\u7801\u8986\u76D6\u7387**: \u2713":""}
2955
+ `).join(""):`### \u6D4B\u8BD5\u6846\u67B6
2956
+ \u672A\u68C0\u6D4B\u5230\u6D4B\u8BD5\u6846\u67B6\u914D\u7F6E`}
2957
+
2958
+ ---
2959
+
2960
+ ## \u4EE3\u7801\u8D28\u91CF\u5DE5\u5177
2961
+
2962
+ ${i.map(d=>`
2963
+ ### ${d.name}
2964
+ - **\u914D\u7F6E\u6587\u4EF6**: ${d.configFiles.map(f=>`\`${f}\``).join(", ")||"\u65E0"}
2965
+ `).join("")}
2966
+
2967
+ ---
2968
+
2969
+ ## CI/CD\u914D\u7F6E
2970
+
2971
+ ${a.length>0?a.map(d=>`
2972
+ ### ${d.name}
2973
+ - **\u914D\u7F6E\u6587\u4EF6**: ${d.configFiles.map(f=>`\`${f}\``).join(", ")||"\u65E0"}
2974
+ `).join(""):`### CI/CD\u914D\u7F6E
2975
+ \u672A\u68C0\u6D4B\u5230CI/CD\u914D\u7F6E`}
2976
+
2977
+ ---
2978
+
2979
+ ## \u4F7F\u7528\u5EFA\u8BAE
2980
+
2981
+ ### \u6539\u8FDB\u5EFA\u8BAE
2982
+
2983
+ ${c.recommendations.map((d,f)=>`${f+1}. ${d}`).join(`
2984
+ `)}
2985
+
2986
+ ### \u5E38\u7528\u547D\u4EE4
2987
+
2988
+ ${c.commands.map((d,f)=>`${f+1}. \`${d}\``).join(`
2989
+ `)}
2990
+
2991
+ ---
2992
+
2993
+ ## \u5F00\u53D1\u5DE5\u4F5C\u6D41
2994
+
2995
+ \u57FA\u4E8E\u5F53\u524D\u5DE5\u5177\u94FE\u914D\u7F6E\uFF0C\u63A8\u8350\u7684\u5F00\u53D1\u6D41\u7A0B\uFF1A
2996
+
2997
+ 1. **\u73AF\u5883\u51C6\u5907**
2998
+ - \u5B89\u88C5\u4F9D\u8D56\uFF1A \`npm install\` \u6216\u5BF9\u5E94\u5305\u7BA1\u7406\u5668\u547D\u4EE4
2999
+ - \u914D\u7F6E\u5F00\u53D1\u73AF\u5883\uFF1A\u68C0\u67E5\u7F16\u8F91\u5668\u914D\u7F6E
3000
+
3001
+ 2. **\u5F00\u53D1\u9636\u6BB5**
3002
+ - \u4EE3\u7801\u68C0\u67E5\uFF1A\u8FD0\u884C\u4EE3\u7801\u8D28\u91CF\u5DE5\u5177
3003
+ - \u5B9E\u65F6\u6D4B\u8BD5\uFF1A\u542F\u7528\u76D1\u542C\u6A21\u5F0F\u6D4B\u8BD5
3004
+
3005
+ 3. **\u6784\u5EFA\u90E8\u7F72**
3006
+ - \u6784\u5EFA\u9879\u76EE\uFF1A\u6267\u884C\u6784\u5EFA\u811A\u672C
3007
+ - \u8FD0\u884C\u6D4B\u8BD5\uFF1A\u786E\u4FDD\u6D4B\u8BD5\u901A\u8FC7
3008
+ - \u90E8\u7F72\uFF1A\u6309\u7167CI/CD\u914D\u7F6E\u90E8\u7F72
3009
+
3010
+ ---
3011
+
3012
+ ## \u4F7F\u7528\u8BF4\u660E
3013
+
3014
+ \u672C\u62A5\u544A\u7531 Tooling Explorer \u81EA\u52A8\u751F\u6210\uFF0C\u4E13\u6CE8\u4E8E\u5F00\u53D1\u5DE5\u5177\u94FE\u5206\u6790\u3002
3015
+
3016
+ ### \u76F8\u5173\u5DE5\u5177
3017
+ - **quickProjectScan**: \u5FEB\u901F\u9879\u76EE\u6982\u89C8\uFF08<5\u79D2\uFF09
3018
+ - **Explore**: \u67B6\u6784\u7EA7\u5206\u6790\uFF0830-60\u79D2\uFF09
3019
+ - **ModuleExplorer**: \u6A21\u5757\u7EA7\u6DF1\u5EA6\u5206\u6790
3020
+
3021
+ ---
3022
+
3023
+ *\u62A5\u544A\u751F\u6210\u65F6\u95F4: ${H()}*
3024
+ `;return ft.writeFileSync(g,m,"utf-8"),g}formatAction(e){return e.focus?`toolingExplore({ focus: "${e.focus}" })`:"toolingExplore()"}formatObservation(e){return String(e)}},Sg=new vr;no=Sg});var Tr,Pr,Mc=S(()=>{Tr=class{analyzeIntent(e){let t=e.toLowerCase(),n={project:["\u9879\u76EE","\u6574\u4F53","\u6982\u89C8","\u7ED3\u6784","\u76EE\u5F55","\u6280\u672F\u6808","project","overview","\u5FEB\u901F","\u7B80\u5355","\u4E86\u89E3","\u8BA4\u8BC6","\u626B\u63CF","\u67E5\u770B","\u9879\u76EE\u7ED3\u6784","\u9879\u76EE\u4FE1\u606F"],architecture:["\u67B6\u6784","\u8BBE\u8BA1","\u6A21\u5757\u5173\u7CFB","\u7CFB\u7EDF\u8BBE\u8BA1","\u8BBE\u8BA1\u6A21\u5F0F","\u6570\u636E\u6D41","architecture","design","system","pattern","relationship","\u6574\u4F53\u67B6\u6784","\u67B6\u6784\u5206\u6790","\u8BBE\u8BA1\u7406\u5FF5"],module:["\u6A21\u5757","\u529F\u80FD","\u5B9E\u73B0","\u51FD\u6570","\u65B9\u6CD5","\u7B97\u6CD5","\u4EE3\u7801","module","function","implementation","method","algorithm","\u5177\u4F53\u5B9E\u73B0","\u4EE3\u7801\u7EC6\u8282","\u51FD\u6570\u5B9E\u73B0","\u4E1A\u52A1\u903B\u8F91"],tooling:["\u6784\u5EFA","\u914D\u7F6E","\u6D4B\u8BD5","\u90E8\u7F72","\u5DE5\u5177","\u73AF\u5883","CI/CD","build","config","test","deploy","tool","environment","\u5DE5\u5177\u94FE","\u6784\u5EFA\u914D\u7F6E","\u6D4B\u8BD5\u6846\u67B6","\u90E8\u7F72\u6D41\u7A0B","\u5F00\u53D1\u73AF\u5883"]},r={quick:["\u5FEB\u901F","\u7B80\u5355","\u6982\u89C8","quick","brief","overview"],deep:["\u6DF1\u5165","\u8BE6\u7EC6","\u5B8C\u6574","deep","detailed","comprehensive"],comprehensive:["\u5168\u9762","\u5B8C\u6574","\u7CFB\u7EDF","comprehensive","full","complete"]},o={project:this.countKeywords(t,n.project),architecture:this.countKeywords(t,n.architecture),module:this.countKeywords(t,n.module),tooling:this.countKeywords(t,n.tooling)},i=Object.entries(o).sort((u,p)=>p[1]-u[1])[0][0]||"project",a={quick:this.countKeywords(t,r.quick),deep:this.countKeywords(t,r.deep),comprehensive:this.countKeywords(t,r.comprehensive)},c=Object.entries(a).sort((u,p)=>p[1]-u[1])[0][0]||"quick",l=this.extractKeywords(t);return{scope:i,depth:c,keywords:l}}countKeywords(e,t){return t.reduce((n,r)=>n+(e.includes(r)?1:0),0)}extractKeywords(e){let t=new Set(["\u7684","\u662F","\u5728","\u6709","\u548C","\u4E0E","\u6216","\u4F46","\u4E0D","\u5F88","\u90FD","\u4E5F","the","is","in","and","or","but","not","very","all","also"]);return e.split(/[\s\u4e00-\u9fa5]+/).filter(n=>n.length>1&&!t.has(n.toLowerCase())).slice(0,5)}route(e){let t=this.analyzeIntent(e);switch(t.scope){case"project":return this.routeToProjectScan(t,e);case"architecture":return this.routeToArchitectureExplore(t,e);case"module":return this.routeToModuleExplore(t,e);case"tooling":return this.routeToToolingExplore(t,e);default:return this.getDefaultRoute()}}routeToProjectScan(e,t){return{tool:"quickProjectScan",params:{},reason:"\u67E5\u8BE2\u5173\u6CE8\u9879\u76EE\u6574\u4F53\u4FE1\u606F\uFF0C\u4F7F\u7528\u5FEB\u901F\u9879\u76EE\u626B\u63CF",confidence:.9}}routeToArchitectureExplore(e,t){let n=this.extractTopic(t),r=this.generateEnglishTopic(n,e.keywords);return{tool:"explore",params:{topic:n||"\u9879\u76EE\u67B6\u6784",englishTopic:r||"Project Architecture"},reason:"\u67E5\u8BE2\u5173\u6CE8\u67B6\u6784\u8BBE\u8BA1\uFF0C\u4F7F\u7528\u67B6\u6784\u7EA7\u63A2\u7D22\u5DE5\u5177",confidence:.85}}routeToModuleExplore(e,t){let n=this.extractModule(t),r=this.generateEnglishTopic(n,e.keywords),o=this.extractSearchPattern(t);return{tool:"moduleExplore",params:{module:n||"\u6838\u5FC3\u6A21\u5757",englishModule:r||"Core Module",...o&&{searchPattern:o}},reason:"\u67E5\u8BE2\u5173\u6CE8\u6A21\u5757\u5B9E\u73B0\u7EC6\u8282\uFF0C\u4F7F\u7528\u6A21\u5757\u7EA7\u6DF1\u5EA6\u63A2\u7D22",confidence:.8}}routeToToolingExplore(e,t){let n=this.extractFocus(t),r=this.generateEnglishTopic(n,e.keywords);return{tool:"toolingExplore",params:{...n&&{focus:n},...r&&{englishFocus:r}},reason:"\u67E5\u8BE2\u5173\u6CE8\u5F00\u53D1\u5DE5\u5177\u94FE\uFF0C\u4F7F\u7528\u5DE5\u5177\u94FE\u5206\u6790",confidence:.8}}getDefaultRoute(){return{tool:"quickProjectScan",params:{},reason:"\u65E0\u6CD5\u660E\u786E\u8BC6\u522B\u610F\u56FE\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u9879\u76EE\u626B\u63CF",confidence:.5}}extractTopic(e){let t=[/(?:探索|分析|了解|查看)?(.+?)的?(?:架构|设计|系统)/,/(?:项目|系统|应用)(.+?)$/,/(.+?)(?:架构|设计|系统)/];for(let n of t){let r=e.match(n);if(r&&r[1]&&r[1].trim())return r[1].trim()}return null}extractModule(e){let t=[/(?:探索|分析|查看|了解)(.+?)模块/,/(.+?)模块的?(?:实现|功能|代码)/,/(?:实现|功能|代码)(.+?)$/,/模块(.+?)$/];for(let r of t){let o=e.match(r);if(o&&o[1]&&o[1].trim())return o[1].trim()}return e.split(/[\s\u4e00-\u9fa5]+/).filter(r=>r.length>1)[0]||null}extractSearchPattern(e){let t=/([a-zA-Z0-9_\/\*]+\.(js|ts|jsx|tsx|py|java|go|rs|php|rb|cs))/,n=e.match(t);return n?n[1]:null}extractFocus(e){let t=[/(?:构建|编译|打包)(.+)?/,/(?:测试)(.+)?/,/(?:部署|发布)(.+)?/,/(?:配置)(.+)?/,/(.+?)配置/,/(.+?)工具/];for(let n of t){let r=e.match(n);if(r)return r[1]||r[0]}return null}generateEnglishTopic(e,t){if(!e)return t.length>0?t.map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join(" "):"Unknown";let n={\u67B6\u6784:"Architecture",\u8BBE\u8BA1:"Design",\u7CFB\u7EDF:"System",\u9879\u76EE:"Project",\u6A21\u5757:"Module",\u529F\u80FD:"Function",\u5B9E\u73B0:"Implementation",\u8BA4\u8BC1:"Authentication",\u6388\u6743:"Authorization",\u6570\u636E\u5E93:"Database",\u7F13\u5B58:"Cache",\u65E5\u5FD7:"Logging",\u914D\u7F6E:"Configuration",\u6784\u5EFA:"Build",\u6D4B\u8BD5:"Test",\u90E8\u7F72:"Deployment",\u5DE5\u5177:"Tools",\u7528\u6237:"User",\u670D\u52A1:"Service",\u63A5\u53E3:"API",\u8DEF\u7531:"Routing",\u4E2D\u95F4\u4EF6:"Middleware",\u5B89\u5168:"Security",\u9519\u8BEF:"Error",\u5F02\u5E38:"Exception",\u5DE5\u5177\u94FE:"Toolchain"},r=e;return Object.entries(n).forEach(([o,i])=>{i=i.replace(new RegExp(o,"g"),i)}),r=r.replace(/[^\w\s]/g," ").replace(/\s+/g," ").trim(),r?r.split(" ").map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join(" "):t.map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join(" ")}getRoutingSuggestions(e){let t=this.analyzeIntent(e),n=[{tool:"quickProjectScan",description:"\u5FEB\u901F\u9879\u76EE\u6982\u89C8\uFF08<5\u79D2\uFF09",reason:"\u9002\u5408\u5FEB\u901F\u4E86\u89E3\u9879\u76EE\u57FA\u672C\u4FE1\u606F",example:"quickProjectScan()"},{tool:"explore",description:"\u67B6\u6784\u7EA7\u5206\u6790\uFF0830-60\u79D2\uFF09",reason:"\u9002\u5408\u7406\u89E3\u9879\u76EE\u6574\u4F53\u67B6\u6784\u548C\u6A21\u5757\u5173\u7CFB",example:'explore({ topic: "\u9879\u76EE\u67B6\u6784", englishTopic: "Project Architecture" })'},{tool:"moduleExplore",description:"\u6A21\u5757\u7EA7\u6DF1\u5EA6\u5206\u6790\uFF0860-120\u79D2\uFF09",reason:"\u9002\u5408\u6DF1\u5165\u5206\u6790\u5177\u4F53\u6A21\u5757\u7684\u5B9E\u73B0\u7EC6\u8282",example:'moduleExplore({ module: "\u8BA4\u8BC1\u6A21\u5757", englishModule: "Authentication Module" })'},{tool:"toolingExplore",description:"\u5DE5\u5177\u94FE\u5206\u6790\uFF0830-60\u79D2\uFF09",reason:"\u9002\u5408\u5206\u6790\u6784\u5EFA\u914D\u7F6E\u3001\u6D4B\u8BD5\u6846\u67B6\u7B49\u5F00\u53D1\u5DE5\u5177",example:"toolingExplore()"}],r=this.route(e);return n.sort((o,i)=>o.tool===r.tool?-1:i.tool===r.tool?1:0)}},Pr=new Tr});async function ro(s){return wg.execute(s)}var kr,wg,so,bg=S(()=>{Mc();G();kr=class extends R{getDefinition(){return{name:"smartSuggest",description:`\u6839\u636E\u60A8\u7684\u67E5\u8BE2\u667A\u80FD\u63A8\u8350\u6700\u5408\u9002\u7684\u63A2\u7D22\u5DE5\u5177\u3002\u5E2E\u52A9\u60A8\u5FEB\u901F\u9009\u62E9\u6B63\u786E\u7684\u5DE5\u5177\uFF0C\u907F\u514D\u5728\u63A2\u7D22\u65F6\u9009\u62E9\u9519\u8BEF\u3002
3025
+
3026
+ \u{1F4CB} \u7528\u9014\uFF1A
3027
+ - \u4E0D\u786E\u5B9A\u8BE5\u4F7F\u7528\u54EA\u4E2A\u63A2\u7D22\u5DE5\u5177\u65F6
3028
+ - \u60F3\u4E86\u89E3\u5404\u5DE5\u5177\u7684\u533A\u522B\u548C\u4F7F\u7528\u573A\u666F
3029
+ - \u9700\u8981\u5DE5\u5177\u9009\u62E9\u5EFA\u8BAE
3030
+
3031
+ \u{1F511} \u53C2\u6570\uFF1A
3032
+ - query: \u60A8\u7684\u9700\u6C42\u63CF\u8FF0\u6216\u67E5\u8BE2\u5185\u5BB9
3033
+
3034
+ \u{1F4A1} \u793A\u4F8B\uFF1A
3035
+ - smartSuggest({ query: "\u6211\u60F3\u5FEB\u901F\u4E86\u89E3\u8FD9\u4E2A\u9879\u76EE" })
3036
+ - smartSuggest({ query: "\u5206\u6790\u8BA4\u8BC1\u6A21\u5757\u7684\u5177\u4F53\u5B9E\u73B0" })
3037
+ - smartSuggest({ query: "\u67E5\u770B\u9879\u76EE\u7684\u6784\u5EFA\u914D\u7F6E" })
3038
+
3039
+ \u{1F4DD} \u8F93\u51FA\uFF1A
3040
+ - \u63A8\u8350\u6700\u9002\u5408\u7684\u5DE5\u5177
3041
+ - \u8BF4\u660E\u63A8\u8350\u539F\u56E0
3042
+ - \u63D0\u4F9B\u5DE5\u5177\u4F7F\u7528\u793A\u4F8B`,input_schema:{type:"object",properties:{query:{type:"string",description:"\u60A8\u7684\u9700\u6C42\u63CF\u8FF0\u6216\u67E5\u8BE2\u5185\u5BB9\uFF08\u4F8B\u5982\uFF1A'\u5FEB\u901F\u4E86\u89E3\u9879\u76EE'\u3001'\u5206\u6790\u6A21\u5757\u5B9E\u73B0'\u3001'\u67E5\u770B\u6784\u5EFA\u914D\u7F6E'\uFF09"}},required:["query"]}}}async execute(e){try{let t=[];t.push(`\u{1F916} \u667A\u80FD\u5DE5\u5177\u63A8\u8350\u5206\u6790
3043
+ `);let n=Pr.route(e.query),r=Pr.getRoutingSuggestions(e.query);t.push(`\u{1F4DD} \u60A8\u7684\u67E5\u8BE2: "${e.query}"
3044
+ `),t.push(`\u{1F3AF} **\u4E3B\u8981\u63A8\u8350**: ${this.getToolDisplayName(n.tool)}`),t.push(`\u{1F4CA} \u7F6E\u4FE1\u5EA6: ${Math.round(n.confidence*100)}%`),t.push(`\u{1F4A1} \u63A8\u8350\u539F\u56E0: ${n.reason}
3045
+ `),t.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),t.push("\u6240\u6709\u63A2\u7D22\u5DE5\u5177\u5BF9\u6BD4"),t.push(`\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
3046
+ `),r.forEach((i,a)=>{let c=i.tool===n.tool,l=c?"\u2705":" ",u=this.getToolDisplayName(i.tool);t.push(`${l} **${u}**`),t.push(` \u2514\u2500 ${i.description}`),t.push(` \u2514\u2500 ${i.reason}`),c&&t.push(` \u2514\u2500 \u2B50 **\u63A8\u8350**: ${Math.round(n.confidence*100)}% \u5339\u914D`),t.push("")}),t.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),t.push("\u63A8\u8350\u5DE5\u5177\u4F7F\u7528\u793A\u4F8B"),t.push(`\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
3047
+ `);let o=this.getUsageExample(n.tool,n.params);return t.push(`**${this.getToolDisplayName(n.tool)}**:`),t.push("```javascript"),t.push(o),t.push("```\n"),t.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),t.push("\u5DE5\u5177\u9009\u62E9\u6307\u5357"),t.push(`\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
3048
+ `),t.push("\u{1F4CB} **\u5FEB\u901F\u51B3\u7B56\u6811**:"),t.push(""),t.push("1. **\u60F3\u5FEB\u901F\u4E86\u89E3\u9879\u76EE\uFF1F** \u2192 `quickProjectScan()` (<5\u79D2)"),t.push("2. **\u60F3\u7406\u89E3\u67B6\u6784\u8BBE\u8BA1\uFF1F** \u2192 `explore()` (30-60\u79D2)"),t.push("3. **\u60F3\u6DF1\u5165\u6A21\u5757\u5B9E\u73B0\uFF1F** \u2192 `moduleExplore()` (60-120\u79D2)"),t.push("4. **\u60F3\u5206\u6790\u5DE5\u5177\u914D\u7F6E\uFF1F** \u2192 `toolingExplore()` (30-60\u79D2)"),t.push(""),t.push("\u{1F3AF} **\u65F6\u95F4\u9884\u671F**:"),t.push("- \u{1F534} **\u5FEB\u901F** (<5\u79D2): quickProjectScan"),t.push("- \u{1F7E1} **\u4E2D\u7B49** (30-60\u79D2): explore, toolingExplore"),t.push("- \u{1F7E2} **\u6DF1\u5165** (60-120\u79D2): moduleExplore"),t.push(""),t.push("\u{1F50D} **\u5206\u6790\u6DF1\u5EA6**:"),t.push("- **\u9879\u76EE\u7EA7**: \u6280\u672F\u6808\u3001\u76EE\u5F55\u7ED3\u6784\u3001\u6587\u4EF6\u6982\u89C8"),t.push("- **\u67B6\u6784\u7EA7**: \u6A21\u5757\u5173\u7CFB\u3001\u8BBE\u8BA1\u6A21\u5F0F\u3001\u6570\u636E\u6D41\u5411"),t.push("- **\u6A21\u5757\u7EA7**: \u51FD\u6570\u5B9E\u73B0\u3001\u8C03\u7528\u94FE\u3001\u7B97\u6CD5\u7EC6\u8282"),t.push("- **\u5DE5\u5177\u94FE**: \u6784\u5EFA\u914D\u7F6E\u3001\u6D4B\u8BD5\u6846\u67B6\u3001CI/CD"),t.join(`
3049
+ `)}catch(t){return this.formatError("SmartSuggest",t)}}getToolDisplayName(e){return{quickProjectScan:"quickProjectScan (\u5FEB\u901F\u9879\u76EE\u626B\u63CF)",explore:"explore (\u67B6\u6784\u63A2\u7D22)",moduleExplore:"moduleExplore (\u6A21\u5757\u63A2\u7D22)",toolingExplore:"toolingExplore (\u5DE5\u5177\u94FE\u5206\u6790)"}[e]||e}getUsageExample(e,t){switch(e){case"quickProjectScan":return"quickProjectScan()";case"explore":return`explore({
3050
+ topic: "${t.topic||"\u9879\u76EE\u67B6\u6784"}",
3051
+ englishTopic: "${t.englishTopic||"Project Architecture"}"
3052
+ })`;case"moduleExplore":let n=`moduleExplore({
3053
+ module: "${t.module||"\u6838\u5FC3\u6A21\u5757"}",
3054
+ englishModule: "${t.englishModule||"Core Module"}"`;return t.searchPattern?n+`,
3055
+ searchPattern: "${t.searchPattern}"
3056
+ })`:n+`
3057
+ })`;case"toolingExplore":return t.focus?`toolingExplore({
3058
+ focus: "${t.focus}",
3059
+ englishFocus: "${t.englishFocus||""}"
3060
+ })`:"toolingExplore()";default:return`${e}(...)`}}formatAction(e){return`smartSuggest({ query: "${e.query}" })`}formatObservation(e){return String(e)}},wg=new kr;so=wg});var Ac={};B(Ac,{AskUserTool:()=>xr,ExploreTool:()=>Cr,ModuleExploreTool:()=>br,PlanTool:()=>dt,QuickProjectScanTool:()=>cn,SmartRouter:()=>Tr,SmartSuggestTool:()=>kr,THINK_TOOL:()=>Jo,ThinkTool:()=>Zt,TodoTool:()=>Sr,ToolingExploreTool:()=>vr,askUser:()=>Vs,askUserTool:()=>Gs,explore:()=>Ys,exploreTool:()=>Xs,extractThought:()=>Ko,isThinkTool:()=>ir,moduleExplore:()=>Qs,moduleExploreTool:()=>Zs,plan:()=>Hs,planTool:()=>zs,quickProjectScan:()=>dr,quickProjectScanTool:()=>fr,smartRouter:()=>Pr,smartSuggest:()=>ro,smartSuggestTool:()=>so,think:()=>sr,thinkTool:()=>or,todo:()=>qs,todoTool:()=>Js,toolingExplore:()=>to,toolingExploreTool:()=>no});var Mi=S(()=>{Is();Ec();lg();Sc();pg();dg();yg();Cg();Mc();bg()});async function vg(s){return Lc.execute(s)}var Rc,Lc,Tg,Ok,Pg=S(()=>{G();_s();Rc=class extends R{getDefinition(){return{name:"search_file_changes",description:`Use this tool to search and query file changes in the workspace. This tool provides auxiliary information to help you understand the current state of the workspace.
1665
3061
 
1666
3062
  IMPORTANT: This tool is for reference only. Your primary focus should be on solving the current task. Use this tool only when you need additional context about workspace changes.
1667
3063
 
@@ -1669,10 +3065,10 @@ Typical use cases:
1669
3065
  - When you need to check what files have been modified recently
1670
3066
  - When you want to understand the scope of changes in the workspace
1671
3067
  - When you need to verify if certain files have been changed
1672
- - When you want to get a summary of changes`,input_schema:{type:"object",properties:{query:{type:"string",description:"Search keywords to filter file changes"},filePatterns:{type:"array",items:{type:"string"},description:"File patterns to match (e.g., ['*.ts', '*.js'])",uniqueItems:!0},changeTypes:{type:"array",items:{type:"string",enum:["added","modified","deleted","renamed"]},description:"Types of changes to include",uniqueItems:!0},dateRange:{type:"object",properties:{start:{type:"string",format:"date-time",description:"Start date for filtering changes"},end:{type:"string",format:"date-time",description:"End date for filtering changes"}},description:"Time range to filter changes"},author:{type:"string",description:"Author to filter changes by"},branch:{type:"string",description:"Git branch to filter changes by"},sortBy:{type:"string",enum:["timestamp","filePath","size","type"],description:"Field to sort results by"},sortOrder:{type:"string",enum:["asc","desc"],description:"Sort order (ascending or descending)"},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum number of results to return"},offset:{type:"integer",minimum:0,description:"Offset for pagination"},includeContent:{type:"boolean",description:"Whether to include file content previews"}}}}}async execute(e){try{let t=qe(),n={query:e.query,filter:{filePatterns:e.filePatterns,changeTypes:e.changeTypes,dateRange:e.dateRange,author:e.author,branch:e.branch},sortBy:e.sortBy,sortOrder:e.sortOrder,limit:e.limit,offset:e.offset,includeContent:e.includeContent};return await t.searchFileChanges(n)}catch(t){throw console.error("\u641C\u7D22\u6587\u4EF6\u53D8\u66F4\u65F6\u51FA\u9519:",t),new Error(`\u641C\u7D22\u6587\u4EF6\u53D8\u66F4\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`)}}},ai=new ii;il=ai,wx=ai.getDefinition()});var ur={};j(ur,{AgentTools:()=>si,AskUserTool:()=>Xt,BaseTool:()=>$,BuildDocIndexTool:()=>_t,ConfirmableTool:()=>Ce,CopyTool:()=>Mt,CoreTools:()=>cs,DeleteTool:()=>Pt,FileChangeTools:()=>Hs,FileChangeTracker:()=>Be,FileOpsTools:()=>Ts,GlobTool:()=>Ft,GrepTool:()=>Ot,MergeTool:()=>It,MkdirTool:()=>kt,MoveTool:()=>$t,PlanTool:()=>De,QuickProjectScanTool:()=>pt,ReadTool:()=>Tt,SearchDocsTool:()=>jt,SearchReplaceTool:()=>At,SearchTools:()=>ks,ShellTool:()=>Nt,SystemTools:()=>Ps,THINK_TOOL:()=>to,ThinkTool:()=>ot,TodoTool:()=>Qt,ValidateTool:()=>Rt,WriteTool:()=>Et,aiContextManager:()=>Tp,askUser:()=>mr,askUserTool:()=>fr,buildDocIndex:()=>qn,buildDocIndexTool:()=>Kn,copyFile:()=>In,copyTool:()=>An,createFileChangeTracker:()=>io,createToolResult:()=>li,deleteFile:()=>En,deleteTool:()=>Pn,detectFileChanges:()=>co,extractThought:()=>no,extractToolResult:()=>xn,fileChangeTracking:()=>kp,generateChangeSummary:()=>lo,getCurrentSessionFileChanges:()=>mo,getFileChangeTracker:()=>ue,getSessionFileChanges:()=>po,glob:()=>Wn,globTool:()=>Vn,grep:()=>zn,grepTool:()=>Hn,handleGitCommit:()=>go,isThinkTool:()=>zt,isToolResult:()=>bt,merge:()=>Ln,mergeTool:()=>Rn,mkdir:()=>bn,mkdirTool:()=>rt,moveFile:()=>$n,moveTool:()=>Mn,plan:()=>gr,planTool:()=>pr,quickProjectScan:()=>qt,quickProjectScanTool:()=>Kt,read:()=>vn,readTool:()=>wn,recordFileChange:()=>uo,resetFileChangeTracker:()=>ao,searchDocs:()=>Jn,searchDocsTool:()=>Gn,searchReplace:()=>Dn,searchReplaceTool:()=>Fn,shell:()=>Yn,shellTool:()=>Ut,think:()=>Wt,thinkTool:()=>Vt,todo:()=>hr,todoTool:()=>yr,toolInstances:()=>H,tools:()=>ci,validate:()=>Nn,validateTool:()=>Un,write:()=>Tn,writeTool:()=>kn});function li(o,e=null,t=!0){return{__tool_result:!0,result:o,display:e!==null?e:o,shouldPrint:t}}var H,ci,Tp,kp,Re=C(()=>{ls();ls();Xr();Xr();Qr();Qr();eo();eo();Po();Po();lt();lt();Xr();Qr();eo();Po();al();lt();ar();H={think:Vt,plan:pr,todo:yr,askUser:fr,quickProjectScan:Kt,read:wn,write:kn,mkdir:rt,glob:Vn,grep:Hn,search_docs:Gn,build_doc_index:Kn,shell:Ut,merge:Rn,delete:Pn,move:Mn,copy:An,searchReplace:Fn,validate:Un,search_file_changes:il},ci={think:Wt,plan:gr,todo:hr,askUser:mr,quickProjectScan:qt,read:vn,write:Tn,mkdir:bn,merge:Ln,glob:Wn,grep:zn,search_docs:Jn,build_doc_index:qn,shell:Yn,delete:En,move:$n,copy:In,searchReplace:Dn,validate:Nn,searchFileChanges:sl},Tp={getAIContextManager:qe,createAIContextManager:Ec,resetAIContextManager:Pc},kp={detectFileChanges:co,generateChangeSummary:lo,recordFileChange:uo,handleGitCommit:go,getSessionFileChanges:po,getCurrentSessionFileChanges:mo,getFileChangeTracker:ue,createFileChangeTracker:io,resetFileChangeTracker:ao}});var cl=C(()=>{});import{Client as Ep}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as Pp}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{StdioClientTransport as $p}from"@modelcontextprotocol/sdk/client/stdio.js";var Cr,ui=C(()=>{Y();Cr=class{client=null;config;connected=!1;tools=[];constructor(e){this.config={timeout:3e4,enabled:!0,...e}}async connect(){x(`Connecting to MCP server: ${this.config.name} (${this.config.transport})`);try{let e;if(this.config.transport==="http"||this.config.transport==="sse"){if(!this.config.url)throw new Error(`URL is required for ${this.config.transport} transport`);e=new Pp(new URL(this.config.url))}else if(this.config.transport==="stdio"){if(!this.config.command)throw new Error(`Command is required for ${this.config.transport} transport`);e=new $p({command:this.config.command,args:this.config.args||[],env:this.config.env})}else throw new Error(`Unsupported transport type: ${this.config.transport}`);this.client=new Ep({name:"niumagents-cli",version:"0.1.0"}),await this.client.connect(e),this.connected=!0;let t=await this.client.listTools();this.tools=t.tools.map(n=>({name:n.name,description:n.description,inputSchema:n.inputSchema||{type:"object",properties:{}},serverName:this.config.name})),x(`Loaded ${this.tools.length} tools from ${this.config.name}`)}catch(e){throw x(`Failed to connect to MCP server ${this.config.name}: ${e.message}`),e}}async disconnect(){x(`Disconnecting from MCP server: ${this.config.name}`),this.client=null,this.connected=!1,this.tools=[]}async listTools(){if(!this.client||!this.connected)throw new Error("Not connected to MCP server");return(await this.client.listTools()).tools.map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema||{type:"object",properties:{}},serverName:this.config.name}))}async callTool(e,t){if(!this.client||!this.connected)return{success:!1,error:"Not connected to MCP server"};try{let n=await this.client.callTool({name:e,arguments:t});return{success:!n.isError,content:n.content||n.result,metadata:n.metadata||{}}}catch(n){return{success:!1,error:n.message}}}isConnected(){return this.connected}getConfig(){return this.config}getCachedTools(){return this.tools}}});var ll=C(()=>{ui()});function Zt(){return gi.getInstance()}var gi,pi=C(()=>{ui();Y();gi=class o{static instance=null;clients=new Map;mcpTools=new Map;initialized=!1;constructor(){}static getInstance(){return o.instance||(o.instance=new o),o.instance}async initialize(e){if(this.initialized){G("MCP Manager already initialized");return}if(M(`Initializing ${e.length} MCP server(s)...`),e.length>0){let t=e.map(n=>{let r=n.url||n.command||"N/A",s=n.enabled!==!1?"enabled":"disabled";return`${n.name} (${n.transport}, ${s}): ${r}`}).join(", ");x(`MCP Server Configurations: ${t}`)}for(let t of e){if(t.enabled===!1){x(`Skipping disabled MCP server: ${t.name}`);continue}try{x(`Attempting to connect to MCP server ${t.name} with URL: ${t.url||"N/A"}`),await this.connectToServer(t)}catch(n){X(`Failed to connect to MCP server ${t.name}: ${n.message}`),x(`Error details for ${t.name}: ${n.message}
1673
- ${n.stack||""}`)}}this.initialized=!0,M(`MCP Manager initialized with ${this.clients.size} server(s) and ${this.mcpTools.size} tool(s)`)}async connectToServer(e){x(`Connecting to MCP server: ${e.name} (${e.transport})`);let t=this.createClient(e);await t.connect(),this.clients.set(e.name,t);let n=t.getCachedTools();for(let r of n)this.registerTool(r);M(`Connected to MCP server: ${e.name} (${n.length} tools)`)}createClient(e){return new Cr(e)}registerTool(e){let t=e.name;if(this.mcpTools.has(t)){G(`MCP tool ${t} already registered, skipping (using first registered)`);return}this.mcpTools.set(t,e),x(`Registered MCP tool: ${t} from ${e.serverName}`)}getAllTools(){return Array.from(this.mcpTools.values())}getTool(e){return this.mcpTools.get(e)}hasTool(e){return this.mcpTools.has(e)}async callTool(e,t){let n=this.mcpTools.get(e);if(!n)return{success:!1,error:`MCP tool not found: ${e}`};let r=this.clients.get(n.serverName);return r?r.isConnected()?r.callTool(e,t):{success:!1,error:`MCP server not connected: ${n.serverName}`}:{success:!1,error:`MCP server not connected: ${n.serverName}`}}async disconnectAll(){x("Disconnecting all MCP servers...");for(let[e,t]of this.clients.entries())try{await t.disconnect(),x(`Disconnected from MCP server: ${e}`)}catch(n){X(`Error disconnecting from ${e}: ${n.message}`)}this.clients.clear(),this.mcpTools.clear(),this.initialized=!1,M("All MCP servers disconnected")}getStatus(){let e=Array.from(this.clients.entries()).map(([t,n])=>({name:t,connected:n.isConnected(),toolCount:n.getCachedTools().length}));return{initialized:this.initialized,serversConnected:this.clients.size,toolsAvailable:this.mcpTools.size,servers:e}}}});function ul(o){let e={};for(let t of o)e[t.name]=new $o(t);return e}function gl(o){let e={};for(let t of o){let n=new $o(t);e[t.name]=async(...r)=>n.execute(...r)}return e}var $o,pl=C(()=>{pi();V();Re();Y();$o=class extends ${mcpTool;constructor(e){super(),this.mcpTool=e}getDefinition(){return{name:this.mcpTool.name,description:`[MCP:${this.mcpTool.serverName}] ${this.mcpTool.description}`,input_schema:{type:"object",properties:this.mcpTool.inputSchema.properties||{},required:this.mcpTool.inputSchema.required}}}async execute(...e){x(`Executing MCP tool: ${this.mcpTool.name}`);let t=this.argsToParams(e),r=await Zt().callTool(this.mcpTool.name,t);if(!r.success)throw new Error(r.error||"MCP tool execution failed");let s=this.formatMCPResult(r.content);return li(s,s,!0)}argsToParams(e){if(e.length===1&&typeof e[0]=="object"&&!Array.isArray(e[0]))return e[0];let n=this.mcpTool.inputSchema.properties||{},r=Object.keys(n),s={};return e.forEach((i,a)=>{a<r.length&&(s[r[a]]=i)}),s}formatMCPResult(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>this.formatContentItem(t)).join(`
3068
+ - When you want to get a summary of changes`,input_schema:{type:"object",properties:{query:{type:"string",description:"Search keywords to filter file changes"},filePatterns:{type:"array",items:{type:"string"},description:"File patterns to match (e.g., ['*.ts', '*.js'])",uniqueItems:!0},changeTypes:{type:"array",items:{type:"string",enum:["added","modified","deleted","renamed"]},description:"Types of changes to include",uniqueItems:!0},dateRange:{type:"object",properties:{start:{type:"string",format:"date-time",description:"Start date for filtering changes"},end:{type:"string",format:"date-time",description:"End date for filtering changes"}},description:"Time range to filter changes"},author:{type:"string",description:"Author to filter changes by"},branch:{type:"string",description:"Git branch to filter changes by"},sortBy:{type:"string",enum:["timestamp","filePath","size","type"],description:"Field to sort results by"},sortOrder:{type:"string",enum:["asc","desc"],description:"Sort order (ascending or descending)"},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum number of results to return"},offset:{type:"integer",minimum:0,description:"Offset for pagination"},includeContent:{type:"boolean",description:"Whether to include file content previews"}}}}}async execute(e){try{let t=Dt(),n={query:e.query,filter:{filePatterns:e.filePatterns,changeTypes:e.changeTypes,dateRange:e.dateRange,author:e.author,branch:e.branch},sortBy:e.sortBy,sortOrder:e.sortOrder,limit:e.limit,offset:e.offset,includeContent:e.includeContent};return await t.searchFileChanges(n)}catch(t){throw console.error("\u641C\u7D22\u6587\u4EF6\u53D8\u66F4\u65F6\u51FA\u9519:",t),new Error(`\u641C\u7D22\u6587\u4EF6\u53D8\u66F4\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`)}}},Lc=new Rc;Tg=Lc,Ok=Lc.getDefinition()});var Bs={};B(Bs,{AgentTools:()=>Ac,AskUserTool:()=>xr,BaseTool:()=>R,BashTool:()=>er,BuildDocIndexTool:()=>Yn,ConfirmableTool:()=>ze,CopyTool:()=>Bn,CoreTools:()=>ya,DeleteTool:()=>_n,ExploreTool:()=>Cr,FileChangeTools:()=>pc,FileChangeTracker:()=>jt,FileOpsTools:()=>Ia,GlobTool:()=>qn,GrepTool:()=>Jn,MergeTool:()=>Hn,MkdirTool:()=>On,ModuleExploreTool:()=>br,MoveTool:()=>Wn,PlanTool:()=>dt,PowerShellTool:()=>nr,QuickProjectScanTool:()=>cn,ReadTool:()=>Dn,SearchDocsTool:()=>Xn,SearchReplaceTool:()=>zn,SearchTools:()=>ja,ShellTool:()=>Qn,SmartRouter:()=>Tr,SmartSuggestTool:()=>kr,SystemTools:()=>Na,THINK_TOOL:()=>Jo,ThinkTool:()=>Zt,TodoTool:()=>Sr,ToolingExploreTool:()=>vr,ValidateTool:()=>Gn,WriteTool:()=>Nn,aiContextManager:()=>Oh,askUser:()=>Vs,askUserTool:()=>Gs,bash:()=>Es,bashTool:()=>tr,buildDocIndex:()=>Xt,buildDocIndexTool:()=>Ts,copyFile:()=>cs,copyTool:()=>ls,createFileChangeTracker:()=>li,createToolResult:()=>Fc,deleteFile:()=>ss,deleteTool:()=>os,detectFileChanges:()=>pi,explore:()=>Ys,exploreTool:()=>Xs,extractThought:()=>Ko,extractToolResult:()=>Kr,fileChangeTracking:()=>Nh,generateChangeSummary:()=>gi,getCurrentSessionFileChanges:()=>hi,getFileChangeTracker:()=>Me,getSessionFileChanges:()=>fi,getToolInstances:()=>jc,glob:()=>Ss,globTool:()=>Cs,grep:()=>ws,grepTool:()=>bs,handleGitCommit:()=>di,isThinkTool:()=>ir,isToolResult:()=>jn,merge:()=>ps,mergeTool:()=>gs,mkdir:()=>ts,mkdirTool:()=>Yt,moduleExplore:()=>Qs,moduleExploreTool:()=>Zs,moveFile:()=>is,moveTool:()=>as,plan:()=>Hs,planTool:()=>zs,powershell:()=>$s,powershellTool:()=>rr,quickProjectScan:()=>dr,quickProjectScanTool:()=>fr,read:()=>Xr,readTool:()=>Qr,recordFileChange:()=>mi,resetFileChangeTracker:()=>ui,searchDocs:()=>Qt,searchDocsTool:()=>Ps,searchReplace:()=>ms,searchReplaceTool:()=>ds,shell:()=>ks,shellTool:()=>Zn,smartRouter:()=>Pr,smartSuggest:()=>ro,smartSuggestTool:()=>so,think:()=>sr,thinkTool:()=>or,todo:()=>qs,todoTool:()=>Js,toolInstances:()=>ee,toolingExplore:()=>to,toolingExploreTool:()=>no,tools:()=>Dc,validate:()=>ys,validateTool:()=>xs,write:()=>ns,writeTool:()=>rs});function jc(){if(Ai)return Ai;let{platform:s}=process,e=s==="win32",t=s==="darwin"||s==="linux",n={think:or,plan:zs,todo:Js,askUser:Gs,quickProjectScan:fr,explore:Xs,moduleExplore:Zs,toolingExplore:no,smartSuggest:so,read:Qr,write:rs,mkdir:Yt,glob:Cs,grep:bs,search_docs:Ps,build_doc_index:Ts,shell:Zn,merge:gs,delete:os,move:as,copy:ls,searchReplace:ds,validate:xs,search_file_changes:Tg},r={};return e&&(r.powershell=rr),t&&(r.bash=tr),Ai={...n,...r},Ai}function Fc(s,e=null,t=!0){return{__tool_result:!0,result:s,display:e!==null?e:s,shouldPrint:t}}var Ai,ee,Dc,Oh,Nh,mt=S(()=>{xa();xa();Bo();Bo();Vo();Vo();qo();qo();Mi();Mi();sn();sn();Bo();Vo();qo();Mi();Pg();sn();_s();Ai=null;ee=new Proxy({},{get(s,e){return jc()[e]},ownKeys(){return Object.keys(jc())},getOwnPropertyDescriptor(s,e){return{enumerable:!0,configurable:!0}}}),Dc={think:sr,plan:Hs,todo:qs,askUser:Vs,quickProjectScan:dr,explore:Ys,moduleExplore:Qs,toolingExplore:to,smartSuggest:ro,read:Xr,write:ns,mkdir:ts,merge:ps,glob:Ss,grep:ws,search_docs:Qt,build_doc_index:Xt,shell:ks,delete:ss,move:is,copy:cs,searchReplace:ms,validate:ys,searchFileChanges:vg,...process.platform==="win32"?{powershell:$s}:{},...process.platform==="darwin"||process.platform==="linux"?{bash:Es}:{}},Oh={getAIContextManager:Dt,createAIContextManager:Fp,resetAIContextManager:Op},Nh={detectFileChanges:pi,generateChangeSummary:gi,recordFileChange:mi,handleGitCommit:di,getSessionFileChanges:fi,getCurrentSessionFileChanges:hi,getFileChangeTracker:Me,createFileChangeTracker:li,resetFileChangeTracker:ui}});var kg=S(()=>{});import{Client as _h}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as Uh}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{StdioClientTransport as Wh}from"@modelcontextprotocol/sdk/client/stdio.js";var oo,Oc=S(()=>{Q();oo=class{client=null;config;connected=!1;tools=[];constructor(e){this.config={timeout:3e4,enabled:!0,...e}}async connect(){C(`Connecting to MCP server: ${this.config.name} (${this.config.transport})`);try{let e;if(this.config.transport==="http"||this.config.transport==="sse"){if(!this.config.url)throw new Error(`URL is required for ${this.config.transport} transport`);e=new Uh(new URL(this.config.url))}else if(this.config.transport==="stdio"){if(!this.config.command)throw new Error(`Command is required for ${this.config.transport} transport`);e=new Wh({command:this.config.command,args:this.config.args||[],env:this.config.env})}else throw new Error(`Unsupported transport type: ${this.config.transport}`);this.client=new _h({name:"niumagents-cli",version:"0.1.0"}),await this.client.connect(e),this.connected=!0;let t=await this.client.listTools();this.tools=t.tools.map(n=>({name:n.name,description:n.description,inputSchema:n.inputSchema||{type:"object",properties:{}},serverName:this.config.name})),C(`Loaded ${this.tools.length} tools from ${this.config.name}`)}catch(e){throw C(`Failed to connect to MCP server ${this.config.name}: ${e.message}`),e}}async disconnect(){C(`Disconnecting from MCP server: ${this.config.name}`),this.client=null,this.connected=!1,this.tools=[]}async listTools(){if(!this.client||!this.connected)throw new Error("Not connected to MCP server");return(await this.client.listTools()).tools.map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema||{type:"object",properties:{}},serverName:this.config.name}))}async callTool(e,t){if(!this.client||!this.connected)return{success:!1,error:"Not connected to MCP server"};try{let n=await this.client.callTool({name:e,arguments:t});return{success:!n.isError,content:n.content||n.result,metadata:n.metadata||{}}}catch(n){return{success:!1,error:n.message}}}isConnected(){return this.connected}getConfig(){return this.config}getCachedTools(){return this.tools}}});var Eg=S(()=>{Oc()});function et(){return Nc.getInstance()}var Nc,_c=S(()=>{Oc();Q();Nc=class s{static instance=null;clients=new Map;mcpTools=new Map;initialized=!1;constructor(){}static getInstance(){return s.instance||(s.instance=new s),s.instance}async initialize(e){if(this.initialized){oe("MCP Manager already initialized");return}if(F(`Initializing ${e.length} MCP server(s)...`),e.length>0){let t=e.map(n=>{let r=n.url||n.command||"N/A",o=n.enabled!==!1?"enabled":"disabled";return`${n.name} (${n.transport}, ${o}): ${r}`}).join(", ");C(`MCP Server Configurations: ${t}`)}for(let t of e){if(t.enabled===!1){C(`Skipping disabled MCP server: ${t.name}`);continue}try{C(`Attempting to connect to MCP server ${t.name} with URL: ${t.url||"N/A"}`),await this.connectToServer(t)}catch(n){ne(`Failed to connect to MCP server ${t.name}: ${n.message}`),C(`Error details for ${t.name}: ${n.message}
3069
+ ${n.stack||""}`)}}this.initialized=!0,F(`MCP Manager initialized with ${this.clients.size} server(s) and ${this.mcpTools.size} tool(s)`)}async connectToServer(e){C(`Connecting to MCP server: ${e.name} (${e.transport})`);let t=this.createClient(e);await t.connect(),this.clients.set(e.name,t);let n=t.getCachedTools();for(let r of n)this.registerTool(r);F(`Connected to MCP server: ${e.name} (${n.length} tools)`)}createClient(e){return new oo(e)}registerTool(e){let t=e.name;if(this.mcpTools.has(t)){oe(`MCP tool ${t} already registered, skipping (using first registered)`);return}this.mcpTools.set(t,e),C(`Registered MCP tool: ${t} from ${e.serverName}`)}getAllTools(){return Array.from(this.mcpTools.values())}getTool(e){return this.mcpTools.get(e)}hasTool(e){return this.mcpTools.has(e)}async callTool(e,t){let n=this.mcpTools.get(e);if(!n)return{success:!1,error:`MCP tool not found: ${e}`};let r=this.clients.get(n.serverName);return r?r.isConnected()?r.callTool(e,t):{success:!1,error:`MCP server not connected: ${n.serverName}`}:{success:!1,error:`MCP server not connected: ${n.serverName}`}}async disconnectAll(){C("Disconnecting all MCP servers...");for(let[e,t]of this.clients.entries())try{await t.disconnect(),C(`Disconnected from MCP server: ${e}`)}catch(n){ne(`Error disconnecting from ${e}: ${n.message}`)}this.clients.clear(),this.mcpTools.clear(),this.initialized=!1,F("All MCP servers disconnected")}getStatus(){let e=Array.from(this.clients.entries()).map(([t,n])=>({name:t,connected:n.isConnected(),toolCount:n.getCachedTools().length}));return{initialized:this.initialized,serversConnected:this.clients.size,toolsAvailable:this.mcpTools.size,servers:e}}}});function $g(s){let e={};for(let t of s)e[t.name]=new Ri(t);return e}function Ig(s){let e={};for(let t of s){let n=new Ri(t);e[t.name]=async(...r)=>n.execute(...r)}return e}var Ri,Mg=S(()=>{_c();G();mt();Q();Ri=class extends R{mcpTool;constructor(e){super(),this.mcpTool=e}getDefinition(){return{name:this.mcpTool.name,description:`[MCP:${this.mcpTool.serverName}] ${this.mcpTool.description}`,input_schema:{type:"object",properties:this.mcpTool.inputSchema.properties||{},required:this.mcpTool.inputSchema.required}}}async execute(...e){C(`Executing MCP tool: ${this.mcpTool.name}`);let t=this.argsToParams(e),r=await et().callTool(this.mcpTool.name,t);if(!r.success)throw new Error(r.error||"MCP tool execution failed");let o=this.formatMCPResult(r.content);return Fc(o,o,!0)}argsToParams(e){if(e.length===1&&typeof e[0]=="object"&&!Array.isArray(e[0]))return e[0];let n=this.mcpTool.inputSchema.properties||{},r=Object.keys(n),o={};return e.forEach((i,a)=>{a<r.length&&(o[r[a]]=i)}),o}formatMCPResult(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>this.formatContentItem(t)).join(`
1674
3070
 
1675
- `):JSON.stringify(e,null,2)}formatContentItem(e){return typeof e=="string"?e:e.type==="text"?e.text||"":e.type==="image"?`[Image: ${e.data?.substring(0,50)}...]`:e.type==="resource"?`[Resource: ${e.uri||"unknown"}]`:JSON.stringify(e)}formatAction(e){let t=typeof e=="object"?Object.entries(e).map(([n,r])=>`${n}=${JSON.stringify(r)}`).join(", "):JSON.stringify(e);return`${this.mcpTool.name}(${t}) [MCP:${this.mcpTool.serverName}]`}formatObservation(e){return e&&e.__tool_result?String(e.display||e.result):String(e)}shouldPrintObservation(e){return!0}}});var di=C(()=>{cl();ll();pi();pl()});async function Mo(){if(mi){x("Tools already loaded, skipping");return}M("Loading tools..."),en={...H},dl={...ci};let o=Object.keys(H);M(`Loaded ${o.length} local tools`);let t=Zt().getAllTools();if(t.length===0){x("No MCP tools available"),mi=!0;return}let n=ul(t),r=gl(t),s=0,i=0;for(let[a,c]of Object.entries(n)){if(en[a]){x(`Skipping MCP tool ${a} (local tool has priority)`),i++;continue}en[a]=c,dl[a]=r[a],s++}M(`Added ${s} MCP tools, skipped ${i} (local priority)`),M(`Total tools available: ${Object.keys(en).length}`),mi=!0}function tn(){return en}function ml(){let o=Object.keys(H),e=Object.keys(en),t=e.filter(n=>!o.includes(n));return{local:o.length,mcp:t.length,total:e.length,localTools:o,mcpTools:t}}var en,dl,mi,xr=C(()=>{Re();di();Y();en={},dl={},mi=!1});var ri={};j(ri,{TOOL_DEFINITIONS:()=>Io,getRawToolDefinitions:()=>Qn,getToolDefinitions:()=>Sr,getToolNames:()=>hl,isRealTool:()=>Mp});function fl(o){return{name:o.name,description:o.description,input_schema:o.input_schema}}function Sr(){let o=tn();if(Object.keys(o).length===0)return Io.map(fl);let e=[],t=De.getCurrentNestingLevel(),n=De.MAX_NESTING_LEVEL,r=["think","todo","askUser"];t<n&&r.splice(1,0,"plan");for(let s of r)if(o[s]){let i=o[s].getDefinition();i&&e.push(i)}for(let[s,i]of Object.entries(o))if(!r.includes(s)&&i){let a=i.getDefinition();a&&e.push(a)}return e.filter(s=>s!=null).map(fl)}function Qn(){return Io}function hl(){return Io.map(o=>o.name)}function Mp(o){return o!=="think"&&hl().includes(o)}var Io,Ht=C(()=>{Re();xr();oi();Io=[H.think.getDefinition(),H.plan.getDefinition(),H.todo.getDefinition(),H.askUser.getDefinition(),H.quickProjectScan.getDefinition(),H.read.getDefinition(),H.write.getDefinition(),H.merge.getDefinition(),H.mkdir.getDefinition(),H.glob.getDefinition(),H.grep.getDefinition(),H.delete.getDefinition(),H.move.getDefinition(),H.copy.getDefinition(),H.searchReplace.getDefinition(),H.shell.getDefinition()]});function fi(o){return!o||typeof o!="string"?0:Math.ceil(o.length/4)}function Ye(o){if(!Array.isArray(o))return 0;let e=0;for(let t of o){if(t.content&&typeof t.content=="string"&&(e+=fi(t.content)),t.tool_calls&&Array.isArray(t.tool_calls))for(let n of t.tool_calls)n.function&&(e+=fi(n.function.name||""),e+=fi(n.function.arguments||""));e+=4}return e}function Ao(o,e){return!e||e<=0?0:o/e*100}function hi(o,e,t=80){return Ao(o,e)>=t}function yi(o,e,t){return`\u26A0\uFE0F Token usage warning: ${o.toLocaleString()} / ${e.toLocaleString()} tokens (${t.toFixed(1)}%)`}var Ci=C(()=>{});import vr from"chalk";var Lo,yl=C(()=>{Ci();Y();Lo=class{options;constructor(e={}){this.options={enabled:e.enabled??!0,threshold:e.threshold??.8,minKeepMessages:e.minKeepMessages??3,maxKeepMessages:e.maxKeepMessages??20,targetUsageAfterCompression:e.targetUsageAfterCompression??.6,useMixedSummary:e.useMixedSummary??!0,llmSummaryTokenThreshold:e.llmSummaryTokenThreshold??500}}shouldCompress(e,t){return this.options.enabled?Ye(e)/t>=this.options.threshold:!1}async compress(e,t,n){let r=Ye(e),s=e.length;M(`\u5F00\u59CB\u4E0A\u4E0B\u6587\u538B\u7F29: ${s} \u6761\u6D88\u606F, ${r} tokens`);let i=this.calculateDynamicWindowSize(e,t);x(`\u52A8\u6001\u7A97\u53E3\u5927\u5C0F: \u4FDD\u7559\u6700\u8FD1 ${i} \u6761\u5B8C\u6574\u6D88\u606F`);let a=e.slice(0,-i),c=e.slice(-i);if(a.length===0)return G("\u6CA1\u6709\u9700\u8981\u538B\u7F29\u7684\u6D88\u606F,\u8DF3\u8FC7\u538B\u7F29"),{messages:e,stats:{originalMessageCount:s,originalTokenCount:r,compressedMessageCount:s,compressedTokenCount:r,compressionRatio:1,llmSummaryCount:0,heuristicSummaryCount:0}};let{summaryMessage:l,llmCount:u,heuristicCount:p}=await this.createCompressedSummary(a,n),g=[l,...c],d=Ye(g),m={originalMessageCount:s,originalTokenCount:r,compressedMessageCount:g.length,compressedTokenCount:d,compressionRatio:d/r,llmSummaryCount:u,heuristicSummaryCount:p};return this.logCompressionStats(m),{messages:g,stats:m}}calculateDynamicWindowSize(e,t){let r=Ye(e)/t,s;return r>=.9?(s=this.options.minKeepMessages,x("Token\u538B\u529B\u6781\u9AD8 (>=90%), \u4F7F\u7528\u6700\u5C0F\u7A97\u53E3")):r>=.85?(s=Math.floor(this.options.minKeepMessages+(this.options.maxKeepMessages-this.options.minKeepMessages)*.25),x("Token\u538B\u529B\u9AD8 (>=85%), \u4F7F\u7528\u8F83\u5C0F\u7A97\u53E3")):r>=.8?(s=Math.floor(this.options.minKeepMessages+(this.options.maxKeepMessages-this.options.minKeepMessages)*.5),x("Token\u538B\u529B\u4E2D\u7B49 (>=80%), \u4F7F\u7528\u4E2D\u7B49\u7A97\u53E3")):(s=this.options.maxKeepMessages,x("Token\u538B\u529B\u6B63\u5E38, \u4F7F\u7528\u6700\u5927\u7A97\u53E3")),Math.min(s,e.length)}async createCompressedSummary(e,t){let n=[],r=0,s=0,i=this.groupMessages(e);for(let c of i){let l=Ye(c),u=this.assessMessageImportance(c),p;this.options.useMixedSummary&&u==="important"&&l>=this.options.llmSummaryTokenThreshold&&t?(p=await this.generateLLMSummary(c,t),r++,x(`\u4F7F\u7528LLM\u6458\u8981 (${c.length}\u6761\u6D88\u606F, ${l} tokens)`)):(p=this.generateHeuristicSummary(c),s++,x(`\u4F7F\u7528\u542F\u53D1\u5F0F\u6458\u8981 (${c.length}\u6761\u6D88\u606F, ${l} tokens)`)),n.push(p)}return{summaryMessage:{role:"system",content:`[\u5386\u53F2\u4E0A\u4E0B\u6587\u6458\u8981]
3071
+ `):JSON.stringify(e,null,2)}formatContentItem(e){return typeof e=="string"?e:e.type==="text"?e.text||"":e.type==="image"?`[Image: ${e.data?.substring(0,50)}...]`:e.type==="resource"?`[Resource: ${e.uri||"unknown"}]`:JSON.stringify(e)}formatAction(e){let t=typeof e=="object"?Object.entries(e).map(([n,r])=>`${n}=${JSON.stringify(r)}`).join(", "):JSON.stringify(e);return`${this.mcpTool.name}(${t}) [MCP:${this.mcpTool.serverName}]`}formatObservation(e){return e&&e.__tool_result?String(e.display||e.result):String(e)}shouldPrintObservation(e){return!0}}});var io=S(()=>{kg();Eg();_c();Mg()});var Ag={};B(Ag,{getAllToolInstances:()=>un,getAllTools:()=>Bh,getToolInstance:()=>zh,getToolStats:()=>Wc,hasTool:()=>Hh,loadAllTools:()=>tt,reloadTools:()=>Vh});async function tt(){if(Li){C("Tools already loaded, skipping");return}F("Loading tools..."),Ot={...ee},Uc={...Dc};let s=Object.keys(ee);F(`Loaded ${s.length} local tools`);let t=et().getAllTools();if(t.length===0){C("No MCP tools available"),Li=!0;return}let n=$g(t),r=Ig(t),o=0,i=0;for(let[a,c]of Object.entries(n)){if(Ot[a]){C(`Skipping MCP tool ${a} (local tool has priority)`),i++;continue}Ot[a]=c,Uc[a]=r[a],o++}F(`Added ${o} MCP tools, skipped ${i} (local priority)`),F(`Total tools available: ${Object.keys(Ot).length}`),Li=!0}function un(){return Ot}function Bh(){return Uc}function Hh(s){return s in Ot}function zh(s){return Ot[s]}function Wc(){let s=Object.keys(ee),e=Object.keys(Ot),t=e.filter(n=>!s.includes(n));return{local:s.length,mcp:t.length,total:e.length,localTools:s,mcpTools:t}}async function Vh(){Li=!1,await tt()}var Ot,Uc,Li,pn=S(()=>{mt();io();Q();Ot={},Uc={},Li=!1});var kc={};B(kc,{TOOL_DEFINITIONS:()=>Gh,getRawToolDefinitions:()=>Ms,getToolDefinitions:()=>Er,getToolNames:()=>Lg,isRealTool:()=>qh});function gn(){return ji||(ji=[ee.think.getDefinition(),ee.plan.getDefinition(),ee.todo.getDefinition(),ee.askUser.getDefinition(),ee.quickProjectScan.getDefinition(),ee.explore.getDefinition(),ee.read.getDefinition(),ee.write.getDefinition(),ee.merge.getDefinition(),ee.mkdir.getDefinition(),ee.glob.getDefinition(),ee.grep.getDefinition(),ee.delete.getDefinition(),ee.move.getDefinition(),ee.copy.getDefinition(),ee.searchReplace.getDefinition(),ee.shell.getDefinition()],ji)}function Rg(s){return{name:s.name,description:s.description,input_schema:s.input_schema}}function Er(){let s=un();if(Object.keys(s).length===0)return gn().map(Rg);let e=[],t=dt.getCurrentNestingLevel(),n=dt.MAX_NESTING_LEVEL,r=["think","todo","askUser"];t<n&&r.splice(1,0,"plan");for(let o of r)if(s[o]){let i=s[o].getDefinition();i&&e.push(i)}for(let[o,i]of Object.entries(s))if(!r.includes(o)&&i){let a=i.getDefinition();a&&e.push(a)}return e.filter(o=>o!=null).map(Rg)}function Ms(){return gn()}function Lg(){return gn().map(s=>s.name)}function qh(s){return s!=="think"&&Lg().includes(s)}var ji,Gh,lr=S(()=>{mt();pn();Ec();ji=null;Gh=new Proxy([],{get(s,e){return gn()[e]},ownKeys(){return Object.keys(gn())},getOwnPropertyDescriptor(s,e){let t=gn();if(e in t)return{enumerable:!0,configurable:!0,writable:!1,value:t[e]}},has(s,e){return e in gn()}})});function Bc(s){return!s||typeof s!="string"?0:Math.ceil(s.length/4)}function Nt(s){if(!Array.isArray(s))return 0;let e=0;for(let t of s){if(t.content&&typeof t.content=="string"&&(e+=Bc(t.content)),t.tool_calls&&Array.isArray(t.tool_calls))for(let n of t.tool_calls)n.function&&(e+=Bc(n.function.name||""),e+=Bc(n.function.arguments||""));e+=4}return e}function Di(s,e){return!e||e<=0?0:s/e*100}function Hc(s,e,t=80){return Di(s,e)>=t}function zc(s,e,t){return`\u26A0\uFE0F Token usage warning: ${s.toLocaleString()} / ${e.toLocaleString()} tokens (${t.toFixed(1)}%)`}var Vc=S(()=>{});import ao from"chalk";var Fi,jg=S(()=>{Vc();Q();Fi=class{options;constructor(e={}){this.options={enabled:e.enabled??!0,threshold:e.threshold??.8,minKeepMessages:e.minKeepMessages??3,maxKeepMessages:e.maxKeepMessages??20,targetUsageAfterCompression:e.targetUsageAfterCompression??.6,useMixedSummary:e.useMixedSummary??!0,llmSummaryTokenThreshold:e.llmSummaryTokenThreshold??500}}shouldCompress(e,t){return this.options.enabled?Nt(e)/t>=this.options.threshold:!1}async compress(e,t,n){let r=Nt(e),o=e.length;F(`\u5F00\u59CB\u4E0A\u4E0B\u6587\u538B\u7F29: ${o} \u6761\u6D88\u606F, ${r} tokens`);let i=this.calculateDynamicWindowSize(e,t);C(`\u52A8\u6001\u7A97\u53E3\u5927\u5C0F: \u4FDD\u7559\u6700\u8FD1 ${i} \u6761\u5B8C\u6574\u6D88\u606F`);let a=e.slice(0,-i),c=e.slice(-i);if(a.length===0)return oe("\u6CA1\u6709\u9700\u8981\u538B\u7F29\u7684\u6D88\u606F,\u8DF3\u8FC7\u538B\u7F29"),{messages:e,stats:{originalMessageCount:o,originalTokenCount:r,compressedMessageCount:o,compressedTokenCount:r,compressionRatio:1,llmSummaryCount:0,heuristicSummaryCount:0}};let{summaryMessage:l,llmCount:u,heuristicCount:p}=await this.createCompressedSummary(a,n),g=[l,...c],m=Nt(g),d={originalMessageCount:o,originalTokenCount:r,compressedMessageCount:g.length,compressedTokenCount:m,compressionRatio:m/r,llmSummaryCount:u,heuristicSummaryCount:p};return this.logCompressionStats(d),{messages:g,stats:d}}calculateDynamicWindowSize(e,t){let r=Nt(e)/t,o;return r>=.9?(o=this.options.minKeepMessages,C("Token\u538B\u529B\u6781\u9AD8 (>=90%), \u4F7F\u7528\u6700\u5C0F\u7A97\u53E3")):r>=.85?(o=Math.floor(this.options.minKeepMessages+(this.options.maxKeepMessages-this.options.minKeepMessages)*.25),C("Token\u538B\u529B\u9AD8 (>=85%), \u4F7F\u7528\u8F83\u5C0F\u7A97\u53E3")):r>=.8?(o=Math.floor(this.options.minKeepMessages+(this.options.maxKeepMessages-this.options.minKeepMessages)*.5),C("Token\u538B\u529B\u4E2D\u7B49 (>=80%), \u4F7F\u7528\u4E2D\u7B49\u7A97\u53E3")):(o=this.options.maxKeepMessages,C("Token\u538B\u529B\u6B63\u5E38, \u4F7F\u7528\u6700\u5927\u7A97\u53E3")),Math.min(o,e.length)}async createCompressedSummary(e,t){let n=[],r=0,o=0,i=this.groupMessages(e);for(let c of i){let l=Nt(c),u=this.assessMessageImportance(c),p;this.options.useMixedSummary&&u==="important"&&l>=this.options.llmSummaryTokenThreshold&&t?(p=await this.generateLLMSummary(c,t),r++,C(`\u4F7F\u7528LLM\u6458\u8981 (${c.length}\u6761\u6D88\u606F, ${l} tokens)`)):(p=this.generateHeuristicSummary(c),o++,C(`\u4F7F\u7528\u542F\u53D1\u5F0F\u6458\u8981 (${c.length}\u6761\u6D88\u606F, ${l} tokens)`)),n.push(p)}return{summaryMessage:{role:"system",content:`[\u5386\u53F2\u4E0A\u4E0B\u6587\u6458\u8981]
1676
3072
  \u4EE5\u4E0B\u662F\u4E4B\u524D\u7684\u5BF9\u8BDD\u6458\u8981,\u5DF2\u538B\u7F29\u4EE5\u8282\u7701token:
1677
3073
 
1678
3074
  ${n.join(`
@@ -1681,16 +3077,18 @@ ${n.join(`
1681
3077
 
1682
3078
  `)}
1683
3079
 
1684
- [\u6458\u8981\u7ED3\u675F]`},llmCount:r,heuristicCount:s}}groupMessages(e){let t=[];for(let r=0;r<e.length;r+=3)t.push(e.slice(r,r+3));return t}assessMessageImportance(e){for(let t of e){if(!t.content)continue;let n=t.content.toLowerCase();if(n.includes("error")||n.includes("warning")||n.includes("\u9519\u8BEF")||n.includes("\u8B66\u544A")||t.tool_calls&&t.tool_calls.length>0||t.role==="system"||t.content&&t.content.length>1e3)return"important"}return"normal"}async generateLLMSummary(e,t){try{let{LITE_MODEL:n}=await Promise.resolve().then(()=>(le(),wt)),r=e.filter(a=>a.content).map(a=>`${a.role}: ${a.content}`).join(`
1685
- `);return`\u{1F4DD} ${(await t({model:n(),messages:[{role:"system",content:"\u4F60\u662F\u4E00\u4E2A\u5BF9\u8BDD\u6458\u8981\u52A9\u624B\u3002\u8BF7\u5C06\u4E0B\u9762\u7684\u5BF9\u8BDD\u538B\u7F29\u6210\u7B80\u6D01\u7684\u6458\u8981(\u4E0D\u8D85\u8FC7150\u5B57),\u4FDD\u7559\u5173\u952E\u64CD\u4F5C\u3001\u7ED3\u679C\u548C\u91CD\u8981\u4FE1\u606F\u3002"},{role:"user",content:r}],temperature:.1,max_tokens:200,useCompression:!0})).choices?.[0]?.message?.content?.trim()||"\u6267\u884C\u5B8C\u6210"}`}catch(n){return G(`LLM\u6458\u8981\u5931\u8D25,\u964D\u7EA7\u5230\u542F\u53D1\u5F0F\u65B9\u6CD5: ${n instanceof Error?n.message:String(n)}`),this.generateHeuristicSummary(e)}}generateHeuristicSummary(e){let t=[],n=[],r=!1;for(let i of e){if(i.tool_calls&&i.tool_calls.length>0)for(let a of i.tool_calls){let c=a.function.name;c!=="think"&&t.push(c)}if(i.content&&(i.content.includes("Error")||i.content.includes("\u9519\u8BEF"))&&(r=!0),i.content){let a=i.content.match(/\b(created|updated|fixed|implemented|tested|deployed|成功|失败|创建|更新|修复|实现)\b/gi);a&&n.push(...a.slice(0,3))}}let s=`\u6267\u884C\u4E86 ${e.length} \u8F6E\u5BF9\u8BDD`;if(t.length>0){let i=[...new Set(t)];s+=`, \u8C03\u7528\u5DE5\u5177: ${i.slice(0,3).join(", ")}`}return n.length>0&&(s+=`, \u5173\u952E\u64CD\u4F5C: ${[...new Set(n)].slice(0,3).join(", ")}`),r&&(s+=" \u26A0\uFE0F \u5305\u542B\u9519\u8BEF"),`\u{1F4AC} ${s}`}logCompressionStats(e){let t=(e.compressionRatio*100).toFixed(1),n=((1-e.compressionRatio)*100).toFixed(1);console.log(vr.green(`
1686
- \u2728 \u4E0A\u4E0B\u6587\u538B\u7F29\u5B8C\u6210`)),console.log(vr.cyan(` \u6D88\u606F\u6570: ${e.originalMessageCount} \u2192 ${e.compressedMessageCount} (${e.compressedMessageCount-e.originalMessageCount})`)),console.log(vr.cyan(` Token: ${e.originalTokenCount} \u2192 ${e.compressedTokenCount} (\u8282\u7701 ${n}%)`)),console.log(vr.cyan(` \u538B\u7F29\u6BD4: ${t}%`)),console.log(vr.cyan(` \u6458\u8981\u65B9\u5F0F: LLM ${e.llmSummaryCount}\u6B21, \u542F\u53D1\u5F0F ${e.heuristicSummaryCount}\u6B21
1687
- `)),M(`\u4E0A\u4E0B\u6587\u538B\u7F29: ${e.originalMessageCount}\u6761 \u2192 ${e.compressedMessageCount}\u6761, ${e.originalTokenCount}tokens \u2192 ${e.compressedTokenCount}tokens (${t}%)`)}updateOptions(e){this.options={...this.options,...e},x(`\u538B\u7F29\u914D\u7F6E\u5DF2\u66F4\u65B0: ${JSON.stringify(this.options)}`)}getOptions(){return{...this.options}}}});var Gt={};j(Gt,{callModelAPI:()=>ee,getDefaultSystemPrompt:()=>Ip});import nn from"chalk";async function ee(o){let{model:e=o.useCompression?Ie():ye(),messages:t,temperature:n=.1,max_tokens:r,useCompression:s=!1,tools:i=Sr(),tool_choice:a,compressionOptions:c,enableAutoCompression:l=!0}=o,u=s?await Cn.getLiteProvider():await Cn.getProvider();x(`\u6A21\u578B\u8C03\u7528\u914D\u7F6E: useCompression=${s}, \u6A21\u578B=${e}, provider=${u.getProviderType()}`),s?x(`\u6B63\u5728\u4F7F\u7528\u8F7B\u91CF\u6A21\u578B: ${e}`):x(`\u6B63\u5728\u4F7F\u7528\u9ED8\u8BA4\u6A21\u578B: ${e}`),x(`\u5DE5\u5177\u6570\u91CF: ${i?i.length:0}`);let p=s?os():rs(),g=t,d=Ye(g),m=Ao(d,p),h=y=>(y/1e3).toFixed(1)+"k";if(M(`\u4F7F\u7528\u6A21\u578B: ${e}, Token usage: ${h(d)} / ${h(p)} (${m.toFixed(1)}%)`),b.currentTaskId){let y=b.tasks.find(S=>S.id===b.currentTaskId);y&&(y.tokenCount=(y.tokenCount||0)+d)}if(l&&hi(d,p,80)){let y=yi(d,p,m);G(y),console.log(nn.yellow(`
1688
- ${y}`)),console.log(nn.cyan(`\u{1F504} \u6B63\u5728\u81EA\u52A8\u538B\u7F29\u4E0A\u4E0B\u6587...
1689
- `));let S=new Lo(c);if(S.shouldCompress(g,p))try{let{messages:E,stats:P}=await S.compress(g,p,ee);g=E,d=P.compressedTokenCount,m=Ao(d,p),M(`\u538B\u7F29\u540EToken\u4F7F\u7528: ${d} / ${p} (${m.toFixed(1)}%)`)}catch(E){G(`\u4E0A\u4E0B\u6587\u538B\u7F29\u5931\u8D25: ${E instanceof Error?E.message:String(E)}`),console.log(nn.yellow(`\u26A0\uFE0F \u4E0A\u4E0B\u6587\u538B\u7F29\u5931\u8D25,\u5C06\u4F7F\u7528\u539F\u59CB\u6D88\u606F\u7EE7\u7EED\u6267\u884C
1690
- `))}else x("\u5F53\u524D\u4E0D\u6EE1\u8DB3\u538B\u7F29\u6761\u4EF6,\u8DF3\u8FC7\u538B\u7F29")}else if(hi(d,p,80)){let y=yi(d,p,m);G(y),console.log(nn.yellow(`
1691
- ${y}`)),console.log(nn.yellow(`Consider archiving old messages or starting a new session.
1692
- `))}x(`\u6A21\u578B\u8BF7\u6C42: ${JSON.stringify({model:e,temperature:n,max_tokens:r,messages:g.length>0?`[${g[0].role}, ..., ${g[g.length-1].role}]`:"[]",tools:i?i.length:0})}`);let w,v=10,T=1e4,f=0;for(;f<=v;)try{w=await u.callModel({model:e,messages:g,temperature:n,max_tokens:r,tools:i,tool_choice:a});break}catch(y){let S=y instanceof Error?y.message:String(y);if((S.includes("429")||S.includes("Too Many Requests")||S.includes("rate limit")||S.includes("\u8D85\u8FC7\u9650\u5236")||S.includes("\u8BF7\u6C42\u9891\u7387"))&&f<v)f++,G(`API\u901F\u7387\u9650\u5236(429), \u6B63\u5728\u91CD\u8BD5... (${f}/${v}) \u7B49\u5F85 ${T/1e3}\u79D2`),console.log(nn.yellow(`\u26A0\uFE0F API\u901F\u7387\u9650\u5236, \u6B63\u5728\u91CD\u8BD5... (${f}/${v}) \u7B49\u5F85 ${T/1e3}\u79D2
1693
- `)),await new Promise(P=>setTimeout(P,T));else throw X(`\u8C03\u7528\u6A21\u578BAPI\u65F6\u53D1\u751F\u9519\u8BEF: ${S}`),y instanceof Error&&y.stack&&x(`\u9519\u8BEF\u5806\u6808: ${y.stack}`),y}if(!w)throw X("\u6A21\u578B\u8FD4\u56DE undefined \u6216 null"),new Error("\u6A21\u578BAPI\u8FD4\u56DE\u7A7A\u54CD\u5E94");if(!w.choices)throw X(`\u6A21\u578B\u8FD4\u56DE\u7F3A\u5C11choices\u5B57\u6BB5: ${JSON.stringify(w)}`),new Error("\u6A21\u578BAPI\u8FD4\u56DE\u7684\u54CD\u5E94\u7F3A\u5C11choices\u5B57\u6BB5");if(!Array.isArray(w.choices)||w.choices.length===0)throw X(`\u6A21\u578B\u8FD4\u56DE\u7A7A\u7684choices\u6570\u7EC4: ${JSON.stringify(w)}`),new Error("\u6A21\u578BAPI\u8FD4\u56DE\u7684choices\u4E3A\u7A7A");return x(`\u6A21\u578B\u8FD4\u56DE: ${JSON.stringify(w)}`),w}function Ip(){return"You are a helpful assistant."}var ve=C(()=>{le();ia();Ne();Ht();Y();Ci();yl()});import*as pe from"fs";import*as Xe from"path";var xi,Cl=C(()=>{ve();le();xi={name:"explorer",description:"\u667A\u80FD\u63A2\u7D22\u9879\u76EE\u7ED3\u6784\uFF0C\u751F\u6210\u6587\u6863\u6216\u56DE\u7B54\u7ED3\u6784\u76F8\u5173\u95EE\u9898",keywords:["explore","\u9879\u76EE\u7ED3\u6784","\u6587\u4EF6\u5206\u6790","\u76EE\u5F55\u7ED3\u6784","\u9879\u76EE\u6982\u89C8","\u4EE3\u7801\u7EC4\u7EC7","\u67B6\u6784\u5206\u6790"],prompt:`\u4F60\u662F\u4E00\u4F4D\u9879\u76EE\u7ED3\u6784\u5206\u6790\u4E13\u5BB6\u3002\u4F60\u7684\u4EFB\u52A1\u662F\u667A\u80FD\u5730\u63A2\u7D22\u548C\u5206\u6790\u9879\u76EE\u7684\u6574\u4F53\u7ED3\u6784\uFF0C\u5E76\u751F\u6210\u9AD8\u8D28\u91CF\u7684\u603B\u7ED3\u578B\u63CF\u8FF0\u3002
3080
+ [\u6458\u8981\u7ED3\u675F]`},llmCount:r,heuristicCount:o}}groupMessages(e){let t=[];for(let r=0;r<e.length;r+=3)t.push(e.slice(r,r+3));return t}assessMessageImportance(e){for(let t of e){if(!t.content)continue;let n=t.content.toLowerCase();if(n.includes("error")||n.includes("warning")||n.includes("\u9519\u8BEF")||n.includes("\u8B66\u544A")||t.tool_calls&&t.tool_calls.length>0||t.role==="system"||t.content&&t.content.length>1e3)return"important"}return"normal"}async generateLLMSummary(e,t){try{let{LITE_MODEL:n}=await Promise.resolve().then(()=>(ae(),Ln)),r=e.filter(a=>a.content).map(a=>`${a.role}: ${a.content}`).join(`
3081
+ `);return`\u{1F4DD} ${(await t({model:n(),messages:[{role:"system",content:"\u4F60\u662F\u4E00\u4E2A\u5BF9\u8BDD\u6458\u8981\u52A9\u624B\u3002\u8BF7\u5C06\u4E0B\u9762\u7684\u5BF9\u8BDD\u538B\u7F29\u6210\u7B80\u6D01\u7684\u6458\u8981(\u4E0D\u8D85\u8FC7150\u5B57),\u4FDD\u7559\u5173\u952E\u64CD\u4F5C\u3001\u7ED3\u679C\u548C\u91CD\u8981\u4FE1\u606F\u3002"},{role:"user",content:r}],temperature:.1,max_tokens:200,useCompression:!0})).choices?.[0]?.message?.content?.trim()||"\u6267\u884C\u5B8C\u6210"}`}catch(n){return oe(`LLM\u6458\u8981\u5931\u8D25,\u964D\u7EA7\u5230\u542F\u53D1\u5F0F\u65B9\u6CD5: ${n instanceof Error?n.message:String(n)}`),this.generateHeuristicSummary(e)}}generateHeuristicSummary(e){let t=[],n=[],r=!1;for(let i of e){if(i.tool_calls&&i.tool_calls.length>0)for(let a of i.tool_calls){let c=a.function.name;c!=="think"&&t.push(c)}if(i.content&&(i.content.includes("Error")||i.content.includes("\u9519\u8BEF"))&&(r=!0),i.content){let a=i.content.match(/\b(created|updated|fixed|implemented|tested|deployed|成功|失败|创建|更新|修复|实现)\b/gi);a&&n.push(...a.slice(0,3))}}let o=`\u6267\u884C\u4E86 ${e.length} \u8F6E\u5BF9\u8BDD`;if(t.length>0){let i=[...new Set(t)];o+=`, \u8C03\u7528\u5DE5\u5177: ${i.slice(0,3).join(", ")}`}return n.length>0&&(o+=`, \u5173\u952E\u64CD\u4F5C: ${[...new Set(n)].slice(0,3).join(", ")}`),r&&(o+=" \u26A0\uFE0F \u5305\u542B\u9519\u8BEF"),`\u{1F4AC} ${o}`}logCompressionStats(e){let t=(e.compressionRatio*100).toFixed(1),n=((1-e.compressionRatio)*100).toFixed(1);console.log(ao.green(`
3082
+ \u2728 \u4E0A\u4E0B\u6587\u538B\u7F29\u5B8C\u6210`)),console.log(ao.cyan(` \u6D88\u606F\u6570: ${e.originalMessageCount} \u2192 ${e.compressedMessageCount} (${e.compressedMessageCount-e.originalMessageCount})`)),console.log(ao.cyan(` Token: ${e.originalTokenCount} \u2192 ${e.compressedTokenCount} (\u8282\u7701 ${n}%)`)),console.log(ao.cyan(` \u538B\u7F29\u6BD4: ${t}%`)),console.log(ao.cyan(` \u6458\u8981\u65B9\u5F0F: LLM ${e.llmSummaryCount}\u6B21, \u542F\u53D1\u5F0F ${e.heuristicSummaryCount}\u6B21
3083
+ `)),F(`\u4E0A\u4E0B\u6587\u538B\u7F29: ${e.originalMessageCount}\u6761 \u2192 ${e.compressedMessageCount}\u6761, ${e.originalTokenCount}tokens \u2192 ${e.compressedTokenCount}tokens (${t}%)`)}updateOptions(e){this.options={...this.options,...e},C(`\u538B\u7F29\u914D\u7F6E\u5DF2\u66F4\u65B0: ${JSON.stringify(this.options)}`)}getOptions(){return{...this.options}}}});var pr={};B(pr,{callModelAPI:()=>Z,getDefaultSystemPrompt:()=>Jh});import de from"chalk";async function Z(s){let{model:e=s.useCompression?lt():ge(),messages:t,temperature:n=.1,max_tokens:r=s.useCompression?Eo():ko(),useCompression:o=!1,tools:i=Er(),tool_choice:a,compressionOptions:c,enableAutoCompression:l=!0}=s,u=o?await Jr.getLiteProvider():await Jr.getProvider();C(`\u6A21\u578B\u8C03\u7528\u914D\u7F6E: useCompression=${o}, \u6A21\u578B=${e}, provider=${u.getProviderType()}`),o?C(`\u6B63\u5728\u4F7F\u7528\u8F7B\u91CF\u6A21\u578B: ${e}`):C(`\u6B63\u5728\u4F7F\u7528\u9ED8\u8BA4\u6A21\u578B: ${e}`),C(`\u5DE5\u5177\u6570\u91CF: ${i?i.length:0}`),C(`\u6700\u5927tokens\u8BBE\u7F6E: ${r} (${o?"\u538B\u7F29\u6A21\u5F0F":"\u6807\u51C6\u6A21\u5F0F"})`),C(`tool_choice\u8BBE\u7F6E: ${a?JSON.stringify(a):"undefined (\u81EA\u52A8\u9009\u62E9)"}`);let p=o?Eo():ko(),g=t,m=Nt(g),d=Di(m,p),f=P=>(P/1e3).toFixed(1)+"k";if(F(`\u4F7F\u7528\u6A21\u578B: ${e}, Token usage: ${f(m)} / ${f(p)} (${d.toFixed(1)}%)`),E.currentTaskId){let P=E.tasks.find(k=>k.id===E.currentTaskId);P&&(P.tokenCount=(P.tokenCount||0)+m)}if(l&&Hc(m,p,80)){let P=zc(m,p,d);oe(P),console.log(de.yellow(`
3084
+ ${P}`)),console.log(de.cyan(`\u{1F504} \u6B63\u5728\u81EA\u52A8\u538B\u7F29\u4E0A\u4E0B\u6587...
3085
+ `));let k=new Fi(c);if(k.shouldCompress(g,p))try{let{messages:b,stats:U}=await k.compress(g,p,Z);g=b,m=U.compressedTokenCount,d=Di(m,p),F(`\u538B\u7F29\u540EToken\u4F7F\u7528: ${m} / ${p} (${d.toFixed(1)}%)`)}catch(b){oe(`\u4E0A\u4E0B\u6587\u538B\u7F29\u5931\u8D25: ${b instanceof Error?b.message:String(b)}`),console.log(de.yellow(`\u26A0\uFE0F \u4E0A\u4E0B\u6587\u538B\u7F29\u5931\u8D25,\u5C06\u4F7F\u7528\u539F\u59CB\u6D88\u606F\u7EE7\u7EED\u6267\u884C
3086
+ `))}else C("\u5F53\u524D\u4E0D\u6EE1\u8DB3\u538B\u7F29\u6761\u4EF6,\u8DF3\u8FC7\u538B\u7F29")}else if(Hc(m,p,80)){let P=zc(m,p,d);oe(P),console.log(de.yellow(`
3087
+ ${P}`)),console.log(de.yellow(`Consider archiving old messages or starting a new session.
3088
+ `))}C(`\u6A21\u578B\u8BF7\u6C42: ${JSON.stringify({model:e,temperature:n,max_tokens:r,messages:g.length>0?`[${g[0].role}, ..., ${g[g.length-1].role}]`:"[]",tools:i?i.length:0})}`);let y=g.map(P=>{let k=P,b={role:k.role,content:k.content};k.name&&(b.name=k.name),k.tool_calls&&(b.tool_calls=k.tool_calls),k.tool_call_id&&(b.tool_call_id=k.tool_call_id);let U=Object.keys(k).filter(j=>!["role","content","name","tool_calls","tool_call_id"].includes(j));return U.length>0&&(C(`\u6E05\u7406\u6D88\u606F\u975E\u6807\u51C6\u5B57\u6BB5: ${U.join(", ")}`),k.metadata?.type==="context_anchor"&&C(`\u68C0\u6D4B\u5230\u951A\u70B9\u6D88\u606F\u5DF2\u6E05\u7406 (\u8FED\u4EE3: ${k.metadata.iteration})`)),b}),w,T=10,h=1e4,x=0;for(;x<=T;)try{w=await u.callModel({model:e,messages:y,temperature:n,max_tokens:r,tools:i,tool_choice:a});break}catch(P){let k=P instanceof Error?P.message:String(P);if((k.includes("429")||k.includes("Too Many Requests")||k.includes("rate limit")||k.includes("\u8D85\u8FC7\u9650\u5236")||k.includes("\u8BF7\u6C42\u9891\u7387"))&&x<T)x++,oe(`API\u901F\u7387\u9650\u5236(429), \u6B63\u5728\u91CD\u8BD5... (${x}/${T}) \u7B49\u5F85 ${h/1e3}\u79D2`),console.log(de.yellow(`\u26A0\uFE0F API\u901F\u7387\u9650\u5236, \u6B63\u5728\u91CD\u8BD5... (${x}/${T}) \u7B49\u5F85 ${h/1e3}\u79D2
3089
+ `)),await new Promise(U=>setTimeout(U,h));else{let U=o?"liteModel":"defaultModel",j=u.getProviderType(),L=u._getBaseURL?u._getBaseURL():"\u672A\u8BBE\u7F6E";if(ne(`\u8C03\u7528\u6A21\u578BAPI\u65F6\u53D1\u751F\u9519\u8BEF: ${k}`),ne(`\u6A21\u578B\u7C7B\u578B: ${U}`),ne(`\u6A21\u578B\u540D\u79F0: ${e}`),ne(`Provider\u7C7B\u578B: ${j}`),ne(`API URL: ${L}`),k.includes("400")){let M=H(new Date);if(console.error(de.red(`
3090
+ \u{1F50D} 400 API\u9519\u8BEF - [${M}] \u8BE6\u7EC6\u8C03\u7528\u53C2\u6570:`)),console.error(de.red(`\u6A21\u578B: ${e}`)),console.error(de.red(`\u6E29\u5EA6: ${n}`)),console.error(de.red(`\u6700\u5927tokens: ${r}`)),console.error(de.red(`\u6D88\u606F\u6570\u91CF: ${g.length}`)),console.error(de.red(`\u5DE5\u5177\u6570\u91CF: ${i?i.length:0}`)),console.error(de.red(`tool_choice: ${JSON.stringify(a,null,2)}`)),i&&i.length>0&&(console.error(de.red("\u5DE5\u5177\u5217\u8868:")),i.forEach(($,I)=>{console.error(de.red(` [${I}] ${$.name}: ${$.description.substring(0,100)}...`))})),g.length>0){let $=g[g.length-1];console.error(de.red(`\u6700\u540E\u4E00\u6761\u6D88\u606F (${$.role}):`)),console.error(de.red(JSON.stringify($,null,2)))}console.error(de.red(`
3091
+ `))}throw P instanceof Error&&P.stack&&C(`\u9519\u8BEF\u5806\u6808: ${P.stack}`),P}}if(!w)throw ne("\u6A21\u578B\u8FD4\u56DE undefined \u6216 null"),new Error("\u6A21\u578BAPI\u8FD4\u56DE\u7A7A\u54CD\u5E94");if(!w.choices)throw ne(`\u6A21\u578B\u8FD4\u56DE\u7F3A\u5C11choices\u5B57\u6BB5: ${JSON.stringify(w)}`),new Error("\u6A21\u578BAPI\u8FD4\u56DE\u7684\u54CD\u5E94\u7F3A\u5C11choices\u5B57\u6BB5");if(!Array.isArray(w.choices)||w.choices.length===0)throw ne(`\u6A21\u578B\u8FD4\u56DE\u7A7A\u7684choices\u6570\u7EC4: ${JSON.stringify(w)}`),new Error("\u6A21\u578BAPI\u8FD4\u56DE\u7684choices\u4E3A\u7A7A");return C(`\u6A21\u578B\u8FD4\u56DE: ${JSON.stringify(w)}`),w}function Jh(){return"You are a helpful assistant."}var Ie=S(()=>{ae();Wl();ct();lr();Q();Vc();jg();Fe()});import*as Oe from"fs";import*as _t from"path";var Gc,Dg=S(()=>{Ie();ae();Fe();Gc={name:"explorer",description:"\u667A\u80FD\u63A2\u7D22\u9879\u76EE\u7ED3\u6784\uFF0C\u751F\u6210\u6587\u6863\u6216\u56DE\u7B54\u7ED3\u6784\u76F8\u5173\u95EE\u9898",keywords:["explore","\u9879\u76EE\u7ED3\u6784","\u6587\u4EF6\u5206\u6790","\u76EE\u5F55\u7ED3\u6784","\u9879\u76EE\u6982\u89C8","\u4EE3\u7801\u7EC4\u7EC7","\u67B6\u6784\u5206\u6790"],prompt:`\u4F60\u662F\u4E00\u4F4D\u9879\u76EE\u7ED3\u6784\u5206\u6790\u4E13\u5BB6\u3002\u4F60\u7684\u4EFB\u52A1\u662F\u667A\u80FD\u5730\u63A2\u7D22\u548C\u5206\u6790\u9879\u76EE\u7684\u6574\u4F53\u7ED3\u6784\uFF0C\u5E76\u751F\u6210\u9AD8\u8D28\u91CF\u7684\u603B\u7ED3\u578B\u63CF\u8FF0\u3002
1694
3092
 
1695
3093
  ## \u8F93\u51FA\u8981\u6C42
1696
3094
 
@@ -1789,26 +3187,26 @@ ${y}`)),console.log(nn.yellow(`Consider archiving old messages or starting a new
1789
3187
  3. **\u6DF1\u5EA6\u5206\u6790**\uFF1A\u5FC5\u8981\u65F6\u6DF1\u5165\u8BFB\u53D6\u548C\u5206\u6790\u5173\u952E\u4EE3\u7801\u6587\u4EF6
1790
3188
  4. **\u6E05\u6670\u8868\u8FBE**\uFF1A\u4EE5\u7ED3\u6784\u5316\u3001\u6613\u61C2\u7684\u65B9\u5F0F\u5448\u73B0\u5206\u6790\u7ED3\u679C
1791
3189
  5. **\u603B\u7ED3\u4F18\u5148**\uFF1A\u59CB\u7EC8\u751F\u6210\u7CBE\u7B80\u7684\u603B\u7ED3\u578B\u63CF\u8FF0\uFF0C\u907F\u514D\u5197\u4F59\u4FE1\u606F
1792
- 6. **\u4FBF\u4E8E\u68C0\u7D22**\uFF1A\u4F7F\u7528\u660E\u786E\u7684\u5173\u952E\u8BCD\u548C\u5C42\u6B21\u7ED3\u6784\uFF0C\u65B9\u4FBF\u540E\u7EED\u68C0\u7D22\u548C\u7406\u89E3`,finalAnswerCallback:async(o,e)=>{try{let t=process.cwd(),n=Xe.join(t,".nium","docs");pe.existsSync(n)||pe.mkdirSync(n,{recursive:!0});let r=Xe.join(n,"PROJECT.md"),s=`# \u9879\u76EE\u63A2\u7D22\u62A5\u544A
3190
+ 6. **\u4FBF\u4E8E\u68C0\u7D22**\uFF1A\u4F7F\u7528\u660E\u786E\u7684\u5173\u952E\u8BCD\u548C\u5C42\u6B21\u7ED3\u6784\uFF0C\u65B9\u4FBF\u540E\u7EED\u68C0\u7D22\u548C\u7406\u89E3`,finalAnswerCallback:async(s,e)=>{try{let t=process.cwd(),n=_t.join(t,".nium","docs");Oe.existsSync(n)||Oe.mkdirSync(n,{recursive:!0});let r=_t.join(n,"PROJECT.md"),o=`# \u9879\u76EE\u63A2\u7D22\u62A5\u544A
1793
3191
 
1794
- > \u751F\u6210\u65F6\u95F4: ${new Date().toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"})}
3192
+ > \u751F\u6210\u65F6\u95F4: ${H()}
1795
3193
  > \u751F\u6210\u5DE5\u5177: Explorer Agent
1796
3194
 
1797
3195
  ---
1798
3196
 
1799
- ${o}
3197
+ ${s}
1800
3198
 
1801
3199
  ---
1802
3200
 
1803
3201
  *\u6B64\u6587\u6863\u7531 Explorer Agent \u81EA\u52A8\u751F\u6210\uFF0C\u8BB0\u5F55\u4E86\u9879\u76EE\u7ED3\u6784\u5206\u6790\u7ED3\u679C\u3002*
1804
- `;if(!pe.existsSync(r))pe.writeFileSync(r,s,"utf-8"),console.log(`
1805
- \u2713 \u9879\u76EE\u63A2\u7D22\u7ED3\u679C\u5DF2\u4FDD\u5B58\u5230: ${Xe.relative(t,r)}`);else{let i=Xe.join(t,".nium","merge");pe.existsSync(i)||pe.mkdirSync(i,{recursive:!0});let a=`project-merge-${Date.now()}.md`,c=Xe.join(i,a),l=`# PROJECT.md \u5408\u5E76\u8BF7\u6C42
3202
+ `;if(!Oe.existsSync(r))Oe.writeFileSync(r,o,"utf-8"),console.log(`
3203
+ \u2713 \u9879\u76EE\u63A2\u7D22\u7ED3\u679C\u5DF2\u4FDD\u5B58\u5230: ${_t.relative(t,r)}`);else{let i=_t.join(t,".nium","merge");Oe.existsSync(i)||Oe.mkdirSync(i,{recursive:!0});let a=`project-merge-${Date.now()}.md`,c=_t.join(i,a),l=`# PROJECT.md \u5408\u5E76\u8BF7\u6C42
1806
3204
 
1807
3205
  ## \u5F53\u524D\u6587\u4EF6\u5185\u5BB9
1808
- ${pe.readFileSync(r,"utf-8")}
3206
+ ${Oe.readFileSync(r,"utf-8")}
1809
3207
 
1810
3208
  ## \u65B0\u751F\u6210\u5185\u5BB9
1811
- ${s}
3209
+ ${o}
1812
3210
 
1813
3211
  ## \u5408\u5E76\u8981\u6C42
1814
3212
  \u8BF7\u6839\u636E\u4EE5\u4E0B\u539F\u5219\u5408\u5E76\u8FD9\u4E24\u4E2A\u5185\u5BB9\uFF1A
@@ -1818,12 +3216,12 @@ ${s}
1818
3216
  4. \u5408\u5E76\u6838\u5FC3\u6A21\u5757\u5206\u6790\uFF0C\u4FDD\u7559\u6240\u6709\u6709\u7528\u4FE1\u606F
1819
3217
  5. \u786E\u4FDD\u5408\u5E76\u540E\u7684\u6587\u6863\u7ED3\u6784\u6E05\u6670\uFF0C\u4FBF\u4E8E\u9605\u8BFB\u548C\u68C0\u7D22
1820
3218
  6. \u4FDD\u6301\u8F93\u51FA\u4E3A\u7CBE\u7B80\u7684\u603B\u7ED3\u578B\u63CF\u8FF0\uFF0C\u9002\u5408\u4F5C\u4E3A\u52A8\u6001\u63D0\u793A\u8BCD
1821
- `;pe.writeFileSync(c,l,"utf-8"),console.log(`
1822
- \u2713 \u9879\u76EE\u63A2\u7D22\u7ED3\u679C\u5DF2\u751F\u6210\u5408\u5E76\u8BF7\u6C42: ${Xe.relative(t,c)}`),console.log(" \u6B63\u5728\u8C03\u7528\u6A21\u578B\u5904\u7406\u5408\u5E76\u903B\u8F91...");let u=`\u4F60\u662F\u4E00\u4F4D\u4E13\u4E1A\u7684\u6587\u6863\u5408\u5E76\u4E13\u5BB6\u3002\u8BF7\u6839\u636E\u63D0\u4F9B\u7684\u5408\u5E76\u8BF7\u6C42\uFF0C\u5C06\u5F53\u524D\u6587\u4EF6\u5185\u5BB9\u548C\u65B0\u751F\u6210\u5185\u5BB9\u5408\u5E76\u4E3A\u4E00\u4E2A\u9AD8\u8D28\u91CF\u7684 PROJECT.md \u6587\u4EF6\u3002
3219
+ `;Oe.writeFileSync(c,l,"utf-8"),console.log(`
3220
+ \u2713 \u9879\u76EE\u63A2\u7D22\u7ED3\u679C\u5DF2\u751F\u6210\u5408\u5E76\u8BF7\u6C42: ${_t.relative(t,c)}`),console.log(" \u6B63\u5728\u8C03\u7528\u6A21\u578B\u5904\u7406\u5408\u5E76\u903B\u8F91...");let u=`\u4F60\u662F\u4E00\u4F4D\u4E13\u4E1A\u7684\u6587\u6863\u5408\u5E76\u4E13\u5BB6\u3002\u8BF7\u6839\u636E\u63D0\u4F9B\u7684\u5408\u5E76\u8BF7\u6C42\uFF0C\u5C06\u5F53\u524D\u6587\u4EF6\u5185\u5BB9\u548C\u65B0\u751F\u6210\u5185\u5BB9\u5408\u5E76\u4E3A\u4E00\u4E2A\u9AD8\u8D28\u91CF\u7684 PROJECT.md \u6587\u4EF6\u3002
1823
3221
 
1824
3222
  ${l}
1825
3223
 
1826
- \u8BF7\u76F4\u63A5\u8FD4\u56DE\u5408\u5E76\u540E\u7684\u5B8C\u6574\u5185\u5BB9\uFF0C\u4E0D\u8981\u6DFB\u52A0\u4EFB\u4F55\u989D\u5916\u7684\u89E3\u91CA\u6216\u8BF4\u660E\u3002`,g=(await ee({model:ye(),messages:[{role:"user",content:u}],temperature:.1,max_tokens:4e3,tools:[]}))?.choices?.[0]?.message?.content;g?(pe.writeFileSync(r,g,"utf-8"),console.log(" \u2713 \u5408\u5E76\u5B8C\u6210\uFF0CPROJECT.md \u5DF2\u66F4\u65B0")):console.log(" \u26A0\uFE0F \u6A21\u578B\u672A\u8FD4\u56DE\u6709\u6548\u5408\u5E76\u7ED3\u679C")}e?.orchestratorContext&&(e.orchestratorContext.recordExplorationResult(o),console.log(" \u2713 \u63A2\u7D22\u7ED3\u679C\u5DF2\u8BB0\u5F55\u5230\u5168\u5C40\u4E0A\u4E0B\u6587"))}catch(t){console.error(`\u4FDD\u5B58\u9879\u76EE\u6587\u6863\u65F6\u51FA\u9519: ${t.message}`)}}}});var Si,xl=C(()=>{Si={name:"doc-retriever",description:"\u6587\u6863\u68C0\u7D22\u548C\u4FE1\u606F\u63D0\u53D6\uFF0C\u7528\u4E8E\u641C\u7D22\u548C\u83B7\u53D6\u6587\u6863\u5185\u5BB9\uFF0C\u652F\u6301\u5173\u952E\u8BCD\u641C\u7D22\u548C\u6B63\u5219\u8868\u8FBE\u5F0F",keywords:["search","\u641C\u7D22","\u6587\u6863","docs","documentation","retrieve","find","\u67E5\u627E","\u67E5\u8BE2","\u641C\u7D22\u6587\u6863","\u67E5\u627E\u6587\u6863","\u83B7\u53D6\u6587\u6863","\u68C0\u7D22\u4FE1\u606F","\u641C\u7D22\u5185\u5BB9","find document","search documentation","get information","retrieve information","search for","\u67E5\u627E\u5185\u5BB9","\u641C\u7D22\u4FE1\u606F","\u67E5\u8BE2\u4FE1\u606F","\u68C0\u7D22\u6587\u6863","\u6587\u6863\u641C\u7D22","\u4FE1\u606F\u68C0\u7D22","search docs","find info","\u67E5\u627E\u8D44\u6599","\u641C\u7D22\u8D44\u6599"],prompt:`\u4F60\u662F\u4E00\u4F4D\u6587\u6863\u68C0\u7D22\u4E13\u5BB6\u3002\u4F60\u7684\u4EFB\u52A1\u662F\u6839\u636E\u7528\u6237\u9700\u6C42\u641C\u7D22\u548C\u68C0\u7D22\u76F8\u5173\u6587\u6863\u5185\u5BB9\uFF0C\u652F\u6301\u5173\u952E\u8BCD\u641C\u7D22\u548C\u6B63\u5219\u8868\u8FBE\u5F0F\u3002
3224
+ \u8BF7\u76F4\u63A5\u8FD4\u56DE\u5408\u5E76\u540E\u7684\u5B8C\u6574\u5185\u5BB9\uFF0C\u4E0D\u8981\u6DFB\u52A0\u4EFB\u4F55\u989D\u5916\u7684\u89E3\u91CA\u6216\u8BF4\u660E\u3002`,g=(await Z({model:ge(),messages:[{role:"user",content:u}],temperature:.1,max_tokens:4e3,tools:[]}))?.choices?.[0]?.message?.content;g?(Oe.writeFileSync(r,g,"utf-8"),console.log(" \u2713 \u5408\u5E76\u5B8C\u6210\uFF0CPROJECT.md \u5DF2\u66F4\u65B0")):console.log(" \u26A0\uFE0F \u6A21\u578B\u672A\u8FD4\u56DE\u6709\u6548\u5408\u5E76\u7ED3\u679C")}e?.orchestratorContext&&(e.orchestratorContext.recordExplorationResult(s),console.log(" \u2713 \u63A2\u7D22\u7ED3\u679C\u5DF2\u8BB0\u5F55\u5230\u5168\u5C40\u4E0A\u4E0B\u6587"))}catch(t){console.error(`\u4FDD\u5B58\u9879\u76EE\u6587\u6863\u65F6\u51FA\u9519: ${t.message}`)}}}});var qc,Fg=S(()=>{qc={name:"doc-retriever",description:"\u6587\u6863\u68C0\u7D22\u548C\u4FE1\u606F\u63D0\u53D6\uFF0C\u7528\u4E8E\u641C\u7D22\u548C\u83B7\u53D6\u6587\u6863\u5185\u5BB9\uFF0C\u652F\u6301\u5173\u952E\u8BCD\u641C\u7D22\u548C\u6B63\u5219\u8868\u8FBE\u5F0F",keywords:["search","\u641C\u7D22","\u6587\u6863","docs","documentation","retrieve","find","\u67E5\u627E","\u67E5\u8BE2","\u641C\u7D22\u6587\u6863","\u67E5\u627E\u6587\u6863","\u83B7\u53D6\u6587\u6863","\u68C0\u7D22\u4FE1\u606F","\u641C\u7D22\u5185\u5BB9","find document","search documentation","get information","retrieve information","search for","\u67E5\u627E\u5185\u5BB9","\u641C\u7D22\u4FE1\u606F","\u67E5\u8BE2\u4FE1\u606F","\u68C0\u7D22\u6587\u6863","\u6587\u6863\u641C\u7D22","\u4FE1\u606F\u68C0\u7D22","search docs","find info","\u67E5\u627E\u8D44\u6599","\u641C\u7D22\u8D44\u6599"],prompt:`\u4F60\u662F\u4E00\u4F4D\u6587\u6863\u68C0\u7D22\u4E13\u5BB6\u3002\u4F60\u7684\u4EFB\u52A1\u662F\u6839\u636E\u7528\u6237\u9700\u6C42\u641C\u7D22\u548C\u68C0\u7D22\u76F8\u5173\u6587\u6863\u5185\u5BB9\uFF0C\u652F\u6301\u5173\u952E\u8BCD\u641C\u7D22\u548C\u6B63\u5219\u8868\u8FBE\u5F0F\u3002
1827
3225
 
1828
3226
  ## \u6838\u5FC3\u89C4\u5219
1829
3227
 
@@ -1897,29 +3295,73 @@ ${l}
1897
3295
  1. **\u6587\u6863\u66F4\u65B0**\uFF1A\u5982\u679C\u641C\u7D22\u7ED3\u679C\u4E0D\u5339\u914D\u6216\u8FC7\u65F6\uFF0C\u5EFA\u8BAE\u66F4\u65B0\u6587\u6863\u7D22\u5F15
1898
3296
  2. **\u641C\u7D22\u8303\u56F4**\uFF1A\u6839\u636E\u9700\u8981\u8C03\u6574\u641C\u7D22\u8303\u56F4\uFF0C\u786E\u4FDD\u8986\u76D6\u76F8\u5173\u6587\u6863
1899
3297
  3. **\u7ED3\u679C\u51C6\u786E\u6027**\uFF1A\u786E\u4FDD\u641C\u7D22\u7ED3\u679C\u51C6\u786E\u53CD\u6620\u7528\u6237\u9700\u6C42
1900
- 4. **\u7D22\u5F15\u7EF4\u62A4**\uFF1A\u5B9A\u671F\u66F4\u65B0\u6587\u6863\u7D22\u5F15\uFF0C\u786E\u4FDD\u7D22\u5F15\u4E0E\u5B9E\u9645\u6587\u6863\u540C\u6B65`}});function Sl(){return Object.values(Ap)}var Ap,vl=C(()=>{ea();Cl();xl();Ap={[ts.name]:ts,[xi.name]:xi,[Si.name]:Si}});var Qc={};j(Qc,{SubAgentManager:()=>Do,getSubAgentManager:()=>Yt});import{existsSync as Lp,readFileSync as Rp,readdirSync as Dp}from"fs";import{join as Fp}from"path";import de from"chalk";function Yt(o={}){return Ro?o.matchStrategy&&Ro.setMatchStrategy(o.matchStrategy):Ro=new Do(o),Ro}var Do,Ro,ko=C(()=>{je();vl();le();ve();it();Do=class{subAgents;agentPerformance;matchStrategy;constructor(e={}){this.subAgents=new Map,this.agentPerformance=new Map,this.matchStrategy=e.matchStrategy||"hybrid",this.loadBuiltinAgents(),this.loadSubAgents()}loadBuiltinAgents(){try{let e=Sl();console.log(de.blue(`[\u5B50\u667A\u80FD\u4F53\u7BA1\u7406\u5668] \u52A0\u8F7D ${e.length} \u4E2A\u5185\u7F6E\u5B50\u4EE3\u7406`)),e.forEach(t=>{this.subAgents.set(t.name,t)})}catch(e){console.log(de.red(`\u274C \u52A0\u8F7D\u5185\u7F6E\u4EE3\u7406\u5931\u8D25: ${e.message}`))}}loadSubAgents(){let e=ge("agents");if(!Lp(e)){console.log(de.gray("[\u5B50\u667A\u80FD\u4F53\u7BA1\u7406\u5668] .nium/agents \u76EE\u5F55\u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u52A0\u8F7D\u81EA\u5B9A\u4E49\u5B50\u667A\u80FD\u4F53"));return}try{let n=Dp(e).filter(r=>r.endsWith(".json")||r.endsWith(".md"));console.log(de.blue(`[\u5B50\u667A\u80FD\u4F53\u7BA1\u7406\u5668] \u52A0\u8F7D ${n.length} \u4E2A\u81EA\u5B9A\u4E49\u5B50\u4EE3\u7406`));for(let r of n)try{let s=Fp(e,r),i=Rp(s,"utf-8"),a;r.endsWith(".json")?a=JSON.parse(i):r.endsWith(".md")&&(a=this.parseFrontmatter(i)),this.validateConfig(a)?(this.subAgents.set(a.name,a),console.log(de.green(`\u2713 \u52A0\u8F7D\u81EA\u5B9A\u4E49\u5B50\u667A\u80FD\u4F53: ${a.name}`))):console.log(de.yellow(`\u26A0\uFE0F \u914D\u7F6E\u6587\u4EF6 ${r} \u683C\u5F0F\u65E0\u6548\uFF0C\u5DF2\u8DF3\u8FC7`))}catch(s){console.log(de.red(`\u274C \u52A0\u8F7D\u914D\u7F6E\u6587\u4EF6 ${r} \u5931\u8D25: ${s.message}`))}}catch(t){console.log(de.red(`\u274C \u8BFB\u53D6agents\u76EE\u5F55\u5931\u8D25: ${t.message}`))}}parseFrontmatter(e){let t=/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/,n=e.match(t);if(!n)throw new Error("\u65E0\u6548\u7684 frontmatter \u683C\u5F0F");let[,r,s]=n,i={},a=r.split(`
1901
- `);for(let c of a){let l=c.trim();if(!l)continue;let u=l.match(/^(\w+)\s*[::]\s*(.+)$/);if(u){let[,p,g]=u;p==="keywords"?i.keywords=g.split(/[,,]/).map(d=>d.trim()).filter(d=>d):i[p]=g.trim()}}return i.prompt=s.trim(),i}validateConfig(e){return!(!e||typeof e!="object"||!e.name||typeof e.name!="string"||!e.description||typeof e.description!="string"||!e.prompt||typeof e.prompt!="string")}async matchSubAgent(e){if(this.subAgents.size===0)return null;let t=Array.from(this.subAgents.values());switch(this.matchStrategy){case"semantic":return await this.matchSubAgentWithAI(e,t);case"hybrid":let n=this.matchSubAgentWithKeywords(e);if(n)return console.log(de.green(`[\u5B50\u667A\u80FD\u4F53\u7BA1\u7406\u5668] Hybrid\u7B56\u7565 - \u5173\u952E\u8BCD\u5339\u914D\u6210\u529F: ${n.name}`)),n;let r=await this.matchSubAgentWithAI(e,t);return r&&console.log(de.green(`[\u5B50\u667A\u80FD\u4F53\u7BA1\u7406\u5668] Hybrid\u7B56\u7565 - \u8BED\u4E49\u5339\u914D\u6210\u529F: ${r.name}`)),r;case"keyword":default:return this.matchSubAgentWithKeywords(e)}}matchSubAgentWithKeywords(e){let t=e.toLowerCase(),n=[];for(let[r,s]of this.subAgents){let i=0;if(s.keywords&&Array.isArray(s.keywords))for(let u of s.keywords)t.includes(u.toLowerCase())&&(i+=10);t.includes(r.toLowerCase())&&(i+=5);let a=s.description.toLowerCase(),c=t.split(/\s+/).filter(u=>u.length>2&&a.includes(u));i+=c.length*2;let l=this.agentPerformance.get(r);if(l){let u=l.success/l.total;i+=u*5;let p=Math.max(0,1-(Date.now()-l.lastUsed)/(10080*60*1e3));i+=p*2}i>0&&n.push({agent:s,score:i})}if(n.length>0){n.sort((s,i)=>i.score-s.score);let r=n[0].agent;return console.log(de.green(`[\u5B50\u667A\u80FD\u4F53\u7BA1\u7406\u5668] \u57FA\u4E8E\u5206\u6570\u5339\u914D\u5230\u667A\u80FD\u4F53: ${r.name} (\u5206\u6570: ${n[0].score.toFixed(1)})`)),r}return null}async matchSubAgentWithAI(e,t){let n=t.map(l=>`${l.name}: ${l.description}`).join(`
1902
- `),r=Ds(e,n),s=await ee({model:Ie(),messages:[{role:"user",content:r}],temperature:0,max_tokens:100,useCompression:!0}),{content:i}=s.choices[0].message,a=i?i.trim():"";return this.getSubAgent(a)||null}recordAgentPerformance(e,t,n){let r=this.agentPerformance.get(e)||{total:0,success:0,avgTime:0,lastUsed:Date.now()};r.total++,t&&r.success++,r.avgTime=(r.avgTime*(r.total-1)+n)/r.total,r.lastUsed=Date.now(),this.agentPerformance.set(e,r)}setMatchStrategy(e){return["keyword","semantic","hybrid"].includes(e)?(this.matchStrategy=e,console.log(de.blue(`[\u5B50\u667A\u80FD\u4F53\u7BA1\u7406\u5668] \u5339\u914D\u7B56\u7565\u5DF2\u8BBE\u7F6E\u4E3A: ${e}`)),!0):(console.error(de.red(`[\u5B50\u667A\u80FD\u4F53\u7BA1\u7406\u5668] \u65E0\u6548\u7684\u5339\u914D\u7B56\u7565: ${e}`)),!1)}getAllSubAgents(){return Array.from(this.subAgents.values())}getSubAgent(e){return this.subAgents.get(e)||null}},Ro=null});import q from"chalk";import mt from"readline";async function Fo(o,e=!1,t=null,n=null){let r,s=null,i=oo();if(Z("Initializing react loop with think-tool support"),e&&b.messages&&b.messages.length>0)Z(`Resuming existing session: ${b.sessionId}`),r=b.messages,Qe(`\u6062\u590D\u4F1A\u8BDD [ID:${b.sessionId.substring(0,8)}]: ${b.currentTask}`),hn(q.green(`\u4ECE ${b.updatedAt} \u6062\u590D\u4E4B\u524D\u7684\u4F1A\u8BDD [ID:${b.sessionId.substring(0,8)}]`),t),B(q.gray(`\u4E4B\u524D\u7684\u4EFB\u52A1: ${b.currentTask}`),t),b.tasks&&b.tasks.length>0&&B(q.gray(`\u4F1A\u8BDD\u4E2D\u4EFB\u52A1\u6570\u91CF: ${b.tasks.length}`),t),B("",t);else if(o){Z(`Starting new task: ${o.substring(0,50)}${o.length>50?"...":""}`);let u=ue(),p=qe(u);await u.detectFileChanges();let g=p.generatePromptIntegrationContent();r=[{role:"system",content:g?`${st}
3298
+ 4. **\u7D22\u5F15\u7EF4\u62A4**\uFF1A\u5B9A\u671F\u66F4\u65B0\u6587\u6863\u7D22\u5F15\uFF0C\u786E\u4FDD\u7D22\u5F15\u4E0E\u5B9E\u9645\u6587\u6863\u540C\u6B65`}});function Og(){return Object.values(Kh)}var Kh,Ng=S(()=>{jl();Dg();Fg();Kh={[ga.name]:ga,[Gc.name]:Gc,[qc.name]:qc}});var og={};B(og,{SubAgentManager:()=>Ni,getSubAgentManager:()=>hr});import{existsSync as Yh,readFileSync as Xh,readdirSync as Qh}from"fs";import{join as Zh}from"path";import Ne from"chalk";function hr(s={}){return Oi?s.matchStrategy&&Oi.setMatchStrategy(s.matchStrategy):Oi=new Ni(s),Oi}var Ni,Oi,$i=S(()=>{Ye();Ng();ae();Ie();tn();Ni=class{subAgents;agentPerformance;matchStrategy;constructor(e={}){this.subAgents=new Map,this.agentPerformance=new Map,this.matchStrategy=e.matchStrategy||"hybrid",this.loadBuiltinAgents(),this.loadSubAgents()}loadBuiltinAgents(){try{let e=Og();console.log(Ne.blue(`[\u5B50\u667A\u80FD\u4F53\u7BA1\u7406\u5668] \u52A0\u8F7D ${e.length} \u4E2A\u5185\u7F6E\u5B50\u4EE3\u7406`)),e.forEach(t=>{this.subAgents.set(t.name,t)})}catch(e){console.log(Ne.red(`\u274C \u52A0\u8F7D\u5185\u7F6E\u4EE3\u7406\u5931\u8D25: ${e.message}`))}}loadSubAgents(){let e=Ee("agents");if(!Yh(e)){console.log(Ne.gray("[\u5B50\u667A\u80FD\u4F53\u7BA1\u7406\u5668] .nium/agents \u76EE\u5F55\u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u52A0\u8F7D\u81EA\u5B9A\u4E49\u5B50\u667A\u80FD\u4F53"));return}try{let n=Qh(e).filter(r=>r.endsWith(".json")||r.endsWith(".md"));console.log(Ne.blue(`[\u5B50\u667A\u80FD\u4F53\u7BA1\u7406\u5668] \u52A0\u8F7D ${n.length} \u4E2A\u81EA\u5B9A\u4E49\u5B50\u4EE3\u7406`));for(let r of n)try{let o=Zh(e,r),i=Xh(o,"utf-8"),a;r.endsWith(".json")?a=JSON.parse(i):r.endsWith(".md")&&(a=this.parseFrontmatter(i)),this.validateConfig(a)?(this.subAgents.set(a.name,a),console.log(Ne.green(`\u2713 \u52A0\u8F7D\u81EA\u5B9A\u4E49\u5B50\u667A\u80FD\u4F53: ${a.name}`))):console.log(Ne.yellow(`\u26A0\uFE0F \u914D\u7F6E\u6587\u4EF6 ${r} \u683C\u5F0F\u65E0\u6548\uFF0C\u5DF2\u8DF3\u8FC7`))}catch(o){console.log(Ne.red(`\u274C \u52A0\u8F7D\u914D\u7F6E\u6587\u4EF6 ${r} \u5931\u8D25: ${o.message}`))}}catch(t){console.log(Ne.red(`\u274C \u8BFB\u53D6agents\u76EE\u5F55\u5931\u8D25: ${t.message}`))}}parseFrontmatter(e){let t=/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/,n=e.match(t);if(!n)throw new Error("\u65E0\u6548\u7684 frontmatter \u683C\u5F0F");let[,r,o]=n,i={},a=r.split(`
3299
+ `);for(let c of a){let l=c.trim();if(!l)continue;let u=l.match(/^(\w+)\s*[::]\s*(.+)$/);if(u){let[,p,g]=u;p==="keywords"?i.keywords=g.split(/[,,]/).map(m=>m.trim()).filter(m=>m):i[p]=g.trim()}}return i.prompt=o.trim(),i}validateConfig(e){return!(!e||typeof e!="object"||!e.name||typeof e.name!="string"||!e.description||typeof e.description!="string"||!e.prompt||typeof e.prompt!="string")}async matchSubAgent(e){if(this.subAgents.size===0)return null;let t=Array.from(this.subAgents.values());switch(this.matchStrategy){case"semantic":return await this.matchSubAgentWithAI(e,t);case"hybrid":let n=this.matchSubAgentWithKeywords(e);if(n)return console.log(Ne.green(`[\u5B50\u667A\u80FD\u4F53\u7BA1\u7406\u5668] Hybrid\u7B56\u7565 - \u5173\u952E\u8BCD\u5339\u914D\u6210\u529F: ${n.name}`)),n;let r=await this.matchSubAgentWithAI(e,t);return r&&console.log(Ne.green(`[\u5B50\u667A\u80FD\u4F53\u7BA1\u7406\u5668] Hybrid\u7B56\u7565 - \u8BED\u4E49\u5339\u914D\u6210\u529F: ${r.name}`)),r;case"keyword":default:return this.matchSubAgentWithKeywords(e)}}matchSubAgentWithKeywords(e){let t=e.toLowerCase(),n=[];for(let[r,o]of this.subAgents){let i=0;if(o.keywords&&Array.isArray(o.keywords))for(let u of o.keywords)t.includes(u.toLowerCase())&&(i+=10);t.includes(r.toLowerCase())&&(i+=5);let a=o.description.toLowerCase(),c=t.split(/\s+/).filter(u=>u.length>2&&a.includes(u));i+=c.length*2;let l=this.agentPerformance.get(r);if(l){let u=l.success/l.total;i+=u*5;let p=Math.max(0,1-(Date.now()-l.lastUsed)/(10080*60*1e3));i+=p*2}i>0&&n.push({agent:o,score:i})}if(n.length>0){n.sort((o,i)=>i.score-o.score);let r=n[0].agent;return console.log(Ne.green(`[\u5B50\u667A\u80FD\u4F53\u7BA1\u7406\u5668] \u57FA\u4E8E\u5206\u6570\u5339\u914D\u5230\u667A\u80FD\u4F53: ${r.name} (\u5206\u6570: ${n[0].score.toFixed(1)})`)),r}return null}async matchSubAgentWithAI(e,t){let n=t.map(l=>`${l.name}: ${l.description}`).join(`
3300
+ `),r=tc(e,n),o=await Z({model:lt(),messages:[{role:"user",content:r}],temperature:0,max_tokens:100,useCompression:!0}),{content:i}=o.choices[0].message,a=i?i.trim():"";return this.getSubAgent(a)||null}recordAgentPerformance(e,t,n){let r=this.agentPerformance.get(e)||{total:0,success:0,avgTime:0,lastUsed:Date.now()};r.total++,t&&r.success++,r.avgTime=(r.avgTime*(r.total-1)+n)/r.total,r.lastUsed=Date.now(),this.agentPerformance.set(e,r)}setMatchStrategy(e){return["keyword","semantic","hybrid"].includes(e)?(this.matchStrategy=e,console.log(Ne.blue(`[\u5B50\u667A\u80FD\u4F53\u7BA1\u7406\u5668] \u5339\u914D\u7B56\u7565\u5DF2\u8BBE\u7F6E\u4E3A: ${e}`)),!0):(console.error(Ne.red(`[\u5B50\u667A\u80FD\u4F53\u7BA1\u7406\u5668] \u65E0\u6548\u7684\u5339\u914D\u7B56\u7565: ${e}`)),!1)}getAllSubAgents(){return Array.from(this.subAgents.values())}getSubAgent(e){return this.subAgents.get(e)||null}},Oi=null});import $r from"fs";import _g from"path";function _i(s){ey.recordToolCall(s)}var Kc,Jc,Yc,ey,Ug=S(()=>{Kc=_g.resolve(process.cwd(),".nium","statistic"),Jc=_g.join(Kc,"tool-usage-stats.json"),Yc=class{stats={};initialized=!1;initialize(){this.initialized||($r.existsSync(Kc)||$r.mkdirSync(Kc,{recursive:!0}),this.loadStats(),this.initialized=!0)}loadStats(){try{if($r.existsSync(Jc)){let e=$r.readFileSync(Jc,"utf-8");this.stats=JSON.parse(e)}else this.stats={}}catch(e){console.error(`Failed to load tool usage stats: ${e}`),this.stats={}}}saveStats(){try{let e=JSON.stringify(this.stats,null,2);$r.writeFileSync(Jc,e,"utf-8")}catch(e){console.error(`Failed to save tool usage stats: ${e}`)}}recordToolCall(e){this.initialize();let t=new Date().toISOString();this.stats[e]?(this.stats[e].count+=1,this.stats[e].lastUsed=t):this.stats[e]={count:1,firstUsed:t,lastUsed:t},this.saveStats()}getToolCallCount(e){return this.initialize(),this.stats[e]?.count||0}getAllStats(){return this.initialize(),{...this.stats}}getSummary(){this.initialize();let e=Object.keys(this.stats),t=e.reduce((o,i)=>o+this.stats[i].count,0),n=null,r=0;for(let o of e)this.stats[o].count>r&&(r=this.stats[o].count,n=o);return{totalCalls:t,toolCount:e.length,mostUsedTool:n,stats:{...this.stats}}}reset(){this.stats={},this.saveStats()}exportStats(e){this.initialize();try{let t=this.getSummary(),n={exportedAt:new Date().toISOString(),summary:{totalCalls:t.totalCalls,toolCount:t.toolCount,mostUsedTool:t.mostUsedTool},details:this.stats},r=JSON.stringify(n,null,2);$r.writeFileSync(e,r,"utf-8")}catch(t){console.error(`Failed to export tool usage stats: ${t}`)}}},ey=new Yc});import ce from"chalk";import mn from"readline";async function co(s,e=!1,t=null,n=null){let r,o=null,i=ai();if(_("Initializing react loop with think-tool support"),e&&E.messages&&E.messages.length>0)_(`Resuming existing session: ${E.sessionId}`),r=E.messages,zt(`\u6062\u590D\u4F1A\u8BDD [ID:${E.sessionId.substring(0,8)}]: ${E.currentTask}`),zr(ce.green(`\u4ECE ${E.updatedAt} \u6062\u590D\u4E4B\u524D\u7684\u4F1A\u8BDD [ID:${E.sessionId.substring(0,8)}]`),t),ie(ce.gray(`\u4E4B\u524D\u7684\u4EFB\u52A1: ${E.currentTask}`),t),E.tasks&&E.tasks.length>0&&ie(ce.gray(`\u4F1A\u8BDD\u4E2D\u4EFB\u52A1\u6570\u91CF: ${E.tasks.length}`),t),ie("",t);else if(s){_(`Starting new task: ${s.substring(0,50)}${s.length>50?"...":""}`);let u=Me(),p=Dt(u);await u.detectFileChanges();let g=p.generatePromptIntegrationContent(),m=await cr;r=[{role:"system",content:g?`${m}
3301
+
3302
+ ${g}`:m},{role:"user",content:s}],zt(`\u5F00\u59CB\u65B0\u4EFB\u52A1: ${s}`),(i.enableAnchorSystem||i.enableSemanticAnalysis)&&(o=new on(s,Z),_("\u7EDF\u4E00\u951A\u70B9\u6CE8\u5165\u5668\u5DF2\u521D\u59CB\u5316")),vo(s),$e(r,s)}else{Be("No user request provided and no session to resume");return}let a=0,c=100,l=0;for(_(`Starting execution loop with max ${c} iterations`);a<c;){a++,_(`Loop iteration ${a}`);try{if(o){let w=await o.injectAnchors({taskDescription:s||E.currentTask,iterations:a,messages:r,lastSemanticCheckIteration:l,session:t,logWarning:Vt,callModelAPI:Z}),{messages:T,lastSemanticCheckIteration:h}=w;r=T,l=h}$e(r);let u=ge();t&&ie(ce.gray(`[\u8FED\u4EE3 ${a}] \u4F7F\u7528\u6A21\u578B: ${u}`),t),_("Calling Model API with all tools including think");let p=await Z({model:u,messages:r,temperature:.1,tools:Er(),tool_choice:void 0});if(!p||!p.choices||p.choices.length===0){let w=`\u6A21\u578B\u8FD4\u56DE\u65E0\u6548\u54CD\u5E94: ${JSON.stringify(p)}`;throw Be(w),new Error(w)}let{choices:g}=p,m=g[0],d=m?.message,f=null,y=null;if(d&&({content:f,tool_calls:y}=d,f&&f.trim())){if(_(`Model returned text content: ${f.substring(0,100)}...`),!y||y.length===0){if(n?.finalAnswerCallback)try{await n.finalAnswerCallback(f)}catch(T){Be(`Error in finalAnswerCallback: ${T}`)}zr(ce.green(`
3303
+ \u6700\u7EC8\u7B54\u6848:`),t),ie(ce.white(f),t),ie("",t),r.push({role:"assistant",content:f}),zt("\u4EFB\u52A1\u5B8C\u6210,\u5F52\u6863\u4F1A\u8BDD"),qt(),_("Breaking out of react loop after final answer");return}let w=Yo(f);ie(ce.magenta(`\u601D\u8003: ${w}`),t),ie("",t)}if(y&&y.length>0){let w=y[0],T=w.function.name,h=w.function.arguments;_(`Tool call: ${T} with args: ${h}`);let x=mr(h);if(!x.success){Be(`\u2717 \u89E3\u6790\u5DE5\u5177\u53C2\u6570\u5931\u8D25: ${h}`),Be(` JSON\u89E3\u6790\u9519\u8BEF: ${x.error}`);let j=Er().find(M=>M.name===T),L="";if(j){let M={},$=j.input_schema.properties;(j.input_schema.required||[]).forEach(O=>{let D=$[O];D&&(D.type==="string"?M[O]="example":D.type==="array"?M[O]=D.items?.type==="string"?["example1","example2"]:[]:D.type==="object"?M[O]={}:D.type==="number"?M[O]=0:D.type==="boolean"&&(M[O]=!1))}),L=`
3304
+
3305
+ \u6B63\u786E\u7684\u53C2\u6570\u683C\u5F0F\u793A\u4F8B:
3306
+ ${JSON.stringify(M,null,2)}`}r.push({role:"user",content:`Error: Invalid JSON arguments - ${x.error}
3307
+
3308
+ \u539F\u59CB\u53C2\u6570: ${h}
3309
+ ${L}
1903
3310
 
1904
- ${g}`:st},{role:"user",content:o}],Qe(`\u5F00\u59CB\u65B0\u4EFB\u52A1: ${o}`),(i.enableAnchorSystem||i.enableSemanticAnalysis)&&(s=new ut(o,ee),Z("\u7EDF\u4E00\u951A\u70B9\u6CE8\u5165\u5668\u5DF2\u521D\u59CB\u5316")),Fr(o),ce(r,o)}else{he("No user request provided and no session to resume");return}let a=0,c=100,l=0;for(Z(`Starting execution loop with max ${c} iterations`);a<c;){a++,Z(`Loop iteration ${a}`);try{if(s){let v=await s.injectAnchors({taskDescription:o||b.currentTask,iterations:a,messages:r,lastSemanticCheckIteration:l,session:t,logWarning:Ct,callModelAPI:ee}),{messages:T,lastSemanticCheckIteration:f}=v;r=T,l=f}ce(r);let u=ye();t&&B(q.gray(`[\u8FED\u4EE3 ${a}] \u4F7F\u7528\u6A21\u578B: ${u}`),t),Z("Calling Model API with all tools including think");let p=await ee({model:u,messages:r,temperature:.1,tools:Sr(),tool_choice:void 0});if(!p||!p.choices||p.choices.length===0){let v=`\u6A21\u578B\u8FD4\u56DE\u65E0\u6548\u54CD\u5E94: ${JSON.stringify(p)}`;throw he(v),new Error(v)}let{choices:g}=p,d=g[0],m=d?.message,h=null,w=null;if(m&&({content:h,tool_calls:w}=m,h&&h.trim())){if(Z(`Model returned text content: ${h.substring(0,100)}...`),!w||w.length===0){if(n?.finalAnswerCallback)try{await n.finalAnswerCallback(h)}catch(v){he(`Error in finalAnswerCallback: ${v}`)}hn(q.green(`
1905
- \u6700\u7EC8\u7B54\u6848:`),t),B(q.white(h),t),B("",t),r.push({role:"assistant",content:h}),Qe("\u4EFB\u52A1\u5B8C\u6210,\u5F52\u6863\u4F1A\u8BDD"),et(),Z("Breaking out of react loop after final answer");return}B(q.magenta(`\u{1F4AD} \u601D\u8003: ${h}`),t),B("",t)}if(w&&w.length>0){let v=w[0],T=v.function.name,f=v.function.arguments;Z(`Tool call: ${T} with args: ${f}`);let y;try{y=JSON.parse(f)}catch{he(`Failed to parse tool arguments: ${f}`),r.push({role:"user",content:`Error: Invalid JSON in tool arguments: ${f}`});continue}if(zt(T)){let L=y.thought||"";B(q.magenta(`\u601D\u8003: ${L}`),t),B("",t),r.push({role:"assistant",content:h||null,tool_calls:[v]}),r.push({role:"tool",tool_call_id:v.id,content:"Noted. Continue."});continue}if(Qs(T)){let L=Zs(v);if(L){let{answer:R,success:O}=L;if(n?.finalAnswerCallback)try{await n.finalAnswerCallback(R)}catch(U){he(`Error in finalAnswerCallback: ${U}`)}let K=O?"\u2705":"\u26A0\uFE0F";hn(q.green(`
1906
- ${K} \u4EFB\u52A1\u5B8C\u6210 (\u901A\u8FC7 finish \u5DE5\u5177):`),t),B(q.white(R),t),B("",t),r.push({role:"assistant",content:h||null,tool_calls:[v]}),r.push({role:"tool",tool_call_id:v.id,content:"Task completed successfully."}),r.push({role:"assistant",content:R}),Qe("\u4EFB\u52A1\u5B8C\u6210(finish\u5DE5\u5177),\u5F52\u6863\u4F1A\u8BDD"),et(),Z("Breaking out of react loop after finish tool call");return}}let E=tn()[T];if(!E){let L=`Unknown tool: ${T}`;he(L),r.push({role:"assistant",content:h||null,tool_calls:[v]}),r.push({role:"tool",tool_call_id:v.id,content:L});continue}let P=E.formatAction(y);B(q.cyan(`\u884C\u52A8: ${P}`),t),B("",t);try{let L=!1;if(T==="shell"&&E&&typeof E.getDynamicDefinition=="function"?L=E.getDynamicDefinition(y).requiresConfirmation||!1:L=Qn().find(te=>te.name===T)?.requiresConfirmation||!1,L&&!await Op(T,y,t)){let te=`\u5DE5\u5177\u6267\u884C\u5DF2\u53D6\u6D88: ${T}`;Qe(te),Ct(q.yellow(`\u26A0 ${te}`),t),B(q.gray("\u60A8\u53EF\u4EE5\u7EE7\u7EED\u63D0\u4F9B\u65B0\u7684\u6307\u4EE4\u6216\u4FEE\u6539\u4E4B\u524D\u7684\u8BF7\u6C42\u3002"),t),r.push({role:"assistant",content:h||null,tool_calls:[v]}),r.push({role:"tool",tool_call_id:v.id,content:"Execution cancelled by user"});continue}Z(`\u6267\u884C\u5DE5\u5177: ${T}(${JSON.stringify(y)})`);let R=await Promise.resolve(E.execute(y));Z(`\u5DE5\u5177 ${T} \u6267\u884C\u5B8C\u6210`);let O=xn(R),K=E?E.shouldPrintObservation(R):!0,I=`${E?E.formatObservation(R):String(R)}`;K&&(B(q.yellow(`\u{1F4CA} \u89C2\u5BDF: ${I}`),t),B("",t)),r.push({role:"assistant",content:h||null,tool_calls:[v]}),r.push({role:"tool",tool_call_id:v.id,content:String(O)})}catch(L){let R=`\u5DE5\u5177\u6267\u884C\u9519\u8BEF: ${T} - ${L.message}`;he(R,t),B("",t),r.push({role:"assistant",content:h||null,tool_calls:[v]}),r.push({role:"tool",tool_call_id:v.id,content:`Error: ${R}`}),ce(r,o)}}if((!h||!h.trim())&&(!w||w.length===0)){if(Ko("Model returned empty response"),d.finish_reason==="stop"){Ct("\u4EFB\u52A1\u5B8C\u6210(\u6A21\u578B\u505C\u6B62)",t),et(),Z("Breaking out of react loop after model stop");return}r.push({role:"user",content:"Please continue or provide your final answer."})}}catch(u){he(`\u9519\u8BEF: ${u.message}`,t),Ct("\u4F1A\u8BDD\u5DF2\u4FDD\u5B58\u3002\u4F7F\u7528 /resume \u7EE7\u7EED\u3002",t),ce(r,o);return}}if(a>=c){he("\u9519\u8BEF: \u5DF2\u8FBE\u5230\u6700\u5927\u8FED\u4EE3\u6B21\u6570",t);let u=Math.floor(a/i.compressionInterval),p=Math.floor(a/i.anchorInjectionInterval),g=Math.floor(a/i.semanticCheckInterval);Z(`\u4F18\u5316\u7EDF\u8BA1: \u538B\u7F29${u}\u6B21, \u951A\u70B9\u6CE8\u5165${p}\u6B21, \u8BED\u4E49\u68C0\u67E5${g}\u6B21`),ce(r,o)}}async function Op(o,e,t=null){return new Promise(n=>{let r=0,s=[{text:"\u786E\u8BA4\u6267\u884C",value:!0},{text:"\u4E2D\u65AD\u6267\u884C",value:!1}],i=JSON.stringify(e),a=()=>{for(let m=0;m<8;m++)mt.moveCursor(process.stdout,0,-1),mt.clearLine(process.stdout,0);let d=t?q.yellow(`\u26A0 \u786E\u8BA4\u6267\u884C ${o}(${i})\uFF1F\u6B64\u64CD\u4F5C\u53EF\u80FD\u65E0\u6CD5\u64A4\u9500\u3002`):q.yellow(`\u26A0 Confirm execution of ${o}(${i})? This action may be irreversible.`);console.log(""),console.log(d),console.log(""),console.log(q.cyan("\u8BF7\u9009\u62E9 (\u4F7F\u7528\u4E0A\u4E0B\u7BAD\u5934\u952E\uFF0CEnter\u786E\u8BA4):")),console.log(""),s.forEach((m,h)=>{let w=h===r,v=w?q.green("> "):" ",T=w?q.green.bold(m.text):q.white(m.text);console.log(`${v}${T}`)}),console.log("")},c=process.stdin.isTTY?process.stdin.isRaw:!1,l=[],u=dr();process.stdin.isTTY&&process.stdin.setRawMode(!0),u?u.__isHandlingConfirmation=!0:(l=process.stdin.listeners("keypress"),process.stdin.removeAllListeners("keypress"));let p=(d,m)=>{if(m.name==="up"){r=Math.max(0,r-1),a();return}else if(m.name==="down"){r=Math.min(s.length-1,r+1),a();return}else if(m.name==="return"||m.name==="enter"){g();for(let h=0;h<8;h++)mt.moveCursor(process.stdout,0,-1),mt.clearLine(process.stdout,0);n(s[r].value);return}else if(m.name==="escape"||m.ctrl&&m.name==="c"){g();for(let h=0;h<8;h++)mt.moveCursor(process.stdout,0,-1),mt.clearLine(process.stdout,0);n(!1);return}},g=()=>{u?(u.removeListener("keypress",p),delete u.__isHandlingConfirmation):(process.stdin.removeListener("keypress",p),l.forEach(d=>{process.stdin.on("keypress",d)})),process.stdin.isTTY&&process.stdin.setRawMode(c)};u?u.on("keypress",p):(mt.emitKeypressEvents(process.stdin),process.stdin.on("keypress",p)),a()})}var vi=C(()=>{le();ve();it();Re();xr();Xn();wo();Ne();Ht();cr();Us();Eo();lt();ar();Y()});import N from"chalk";async function wl(o,e=!1,t=null,n={}){await new wr(t,n).executeTask(o,e)}var wr,bl=C(()=>{ko();$e();vi();it();Ne();Y();Gs();To();ro();wr=class{session;subAgentManager;orchestratorContext;progressiveDisclosure;workerContextBuilder;summaryExtractor;options;constructor(e=null,t={}){this.session=e,ti(e);let n={matchStrategy:t.matchStrategy};this.subAgentManager=Yt(n),this.options={useLLMDisclosure:t.useLLMDisclosure!==void 0?t.useLLMDisclosure:!0,useLLMSummary:t.useLLMSummary!==void 0?t.useLLMSummary:!0,verbose:t.verbose||!1},this.orchestratorContext=new Ve,this.progressiveDisclosure=new ze(this.orchestratorContext),this.workerContextBuilder=new He(this.orchestratorContext,this.progressiveDisclosure),this.summaryExtractor=new Je(this.options.useLLMSummary)}log(e){this.session?this.session.log(e):console.log(e)}info(e){this.session?this.session.info(e):console.log(N.blue(e))}success(e){this.session?this.session.success(e):console.log(N.green(e))}warning(e){this.session?this.session.warning(e):console.log(N.yellow(e))}error(e){this.session?this.session.error(e):console.log(N.red(e))}async executeTask(e,t=!1){try{if(x("MasterAgent.executeTask called"),t){x("Entering resume session mode"),this.info("\u6062\u590D\u4F1A\u8BDD\u6A21\u5F0F"),await Fo(e,!0,this.session);return}let{evaluateTaskComplexity:n,TaskComplexity:r}=await Promise.resolve().then(()=>($e(),We));await n(e)===r.COMPLEX?await this.executeWithPlanning(e):await this.executeWithSingleAgent(e),this.log(""),this.success("\u2705 \u4EFB\u52A1\u6267\u884C\u5B8C\u6210"),this.options.verbose&&(this.log(""),this.log(N.gray("\u2550\u2550\u2550 \u5168\u5C40\u4E0A\u4E0B\u6587\u6458\u8981 \u2550\u2550\u2550")),this.log(N.gray(JSON.stringify(this.orchestratorContext.getCompactSummary(),null,2))))}catch(n){throw this.error(`\u274C \u4EFB\u52A1\u6267\u884C\u5931\u8D25: ${n.message}`),n}}async executeWithSingleAgent(e){await this.ensureProjectStructure();let t={markdown:"",tasks:[{step:1,description:e,status:"pending",subAgent:"default"}],taskId:"",strategy:"single-agent",totalSteps:1};this.orchestratorContext.initializeTask(e,t);let n=await this.subAgentManager.matchSubAgent(e);if(n){this.info(`\u5339\u914D\u5230\u4E13\u7528\u5B50\u667A\u80FD\u4F53: ${n.name}`),this.log("");let r=await this.workerContextBuilder.buildIsolatedContext(1,e,n.prompt,!1,void 0,n.name);await this.executeSubAgentTask(1,e,n,r)}else this.info("\u4F7F\u7528\u9ED8\u8BA4React\u667A\u80FD\u4F53"),this.log(""),await Fo(e,!1,this.session)}async executeWithPlanning(e){let t=this.subAgentManager.getAllSubAgents(),n=await Zn(e,t);this.orchestratorContext.initializeTask(e,n),n.taskId&&St(n.taskId),this.log(er(n)),this.log(""),await this.ensureProjectStructure(),await this.loadProjectRules(),this.analyzeStepDependencies(n);for(let r=0;r<n.tasks.length;r++){let s=n.tasks[r],i=s.step;this.log(""),this.info(`\u2501\u2501\u2501 \u6267\u884C\u6B65\u9AA4 ${i}/${n.tasks.length} \u2501\u2501\u2501`),this.log(N.cyan(`\u{1F4CC} ${s.description}`)),this.log(""),this.orchestratorContext.plan.currentStep=i,n.taskId&&await at(n.taskId,i,"in_progress");try{let a=this.getSubAgentConfig(s),c=await this.workerContextBuilder.buildIsolatedContext(i,s.description,a?.prompt||"",this.options.useLLMDisclosure,void 0,a?.name);this.options.verbose&&this.log(N.gray(`\u4E0A\u4E0B\u6587\u5927\u5C0F: ${c.length} \u6761\u6D88\u606F`)),a?await this.executeSubAgentTask(i,s.description,a,c):await this.executeDefaultAgentWithContext(s.description,c),this.success(`\u2705 \u6B65\u9AA4 ${i} \u5B8C\u6210`),n.taskId&&await at(n.taskId,i,"completed")}catch(a){throw this.error(`\u274C \u6B65\u9AA4 ${i} \u6267\u884C\u5931\u8D25: ${a.message}`),this.warning("\u4E2D\u6B62\u540E\u7EED\u6B65\u9AA4\u6267\u884C"),this.orchestratorContext.recordStepCompletion(i,`\u5931\u8D25: ${a.message}`,{success:!1,error:a.message}),a}}}async ensureProjectStructure(){try{let{existsSync:e}=await import("fs");if(e(".nium/project/project.json")){x("project.json \u5DF2\u5B58\u5728\uFF0C\u8DF3\u8FC7\u81EA\u52A8\u751F\u6210");return}this.log(""),this.info("\u{1F4CB} \u68C0\u6D4B\u5230\u9879\u76EE\u7ED3\u6784\u6587\u6863\u4E0D\u5B58\u5728\uFF0C\u6267\u884C\u5FEB\u901F\u626B\u63CF..."),this.log("");let{tools:n}=await Promise.resolve().then(()=>(Re(),ur));await n.quickProjectScan(),this.success("\u2705 \u9879\u76EE\u7ED3\u6784\u6587\u6863\u5DF2\u751F\u6210"),this.log(""),M("\u5DF2\u81EA\u52A8\u751F\u6210 project.json")}catch(e){x(`\u81EA\u52A8\u751F\u6210\u9879\u76EE\u7ED3\u6784\u6587\u6863\u5931\u8D25: ${e.message}`),this.warning("\u9879\u76EE\u7ED3\u6784\u6587\u6863\u751F\u6210\u5931\u8D25\uFF0C\u5C06\u7EE7\u7EED\u6267\u884C\u4EFB\u52A1")}}async loadProjectRules(){try{let{tools:e,toolInstances:t,extractToolResult:n}=await Promise.resolve().then(()=>(Re(),ur)),r="",i=e.read({path:".nium/rules.md"});i&&!i.includes("Error:")&&(r+=i,M("\u5DF2\u52A0\u8F7D\u9879\u76EE\u89C4\u5219\u6587\u4EF6"));let c=e.read({path:".nium/project/project.json"});if(c&&!c.includes("Error:")){r&&(r+=`
3311
+ \u8BF7\u786E\u4FDD:
3312
+ 1. \u6240\u6709\u5B57\u7B26\u4E32\u503C\u90FD\u7528\u53CC\u5F15\u53F7\u62EC\u8D77\u6765
3313
+ 2. \u6570\u7EC4\u4F7F\u7528\u65B9\u62EC\u53F7 []
3314
+ 3. \u5BF9\u8C61\u4F7F\u7528\u82B1\u62EC\u53F7 {}
3315
+ 4. \u4E0D\u8981\u4F7F\u7528\u88F8\u7684\u7B26\u53F7\uFF08\u5982 ., * \u7B49\uFF09\u4F5C\u4E3A\u503C\uFF0C\u5B83\u4EEC\u5FC5\u987B\u662F\u5B57\u7B26\u4E32`});continue}x.wasFixed&&Vt("\u26A0 JSON\u683C\u5F0F\u5DF2\u81EA\u52A8\u4FEE\u590D");let P=x.data;if(ir(T)){let j=P.thought||"",L=Yo(j);ie(ce.magenta(`\u601D\u8003: ${L}`),t),ie("",t),_i(T),r.push({role:"assistant",content:f||null,tool_calls:[w]}),r.push({role:"tool",tool_call_id:w.id,content:"Noted. Continue."});continue}if(wc(T)){let j=bc(w);if(j){let{answer:L,success:M}=j;if(_i(T),n?.finalAnswerCallback)try{await n.finalAnswerCallback(L)}catch(I){Be(`Error in finalAnswerCallback: ${I}`)}let $=M?"\u2705":"\u26A0\uFE0F";zr(ce.green(`
3316
+ ${$} \u4EFB\u52A1\u5B8C\u6210 (\u901A\u8FC7 finish \u5DE5\u5177):`),t),ie(ce.white(L),t),ie("",t),r.push({role:"assistant",content:f||null,tool_calls:[w]}),r.push({role:"tool",tool_call_id:w.id,content:"Task completed successfully."}),r.push({role:"assistant",content:L}),zt("\u4EFB\u52A1\u5B8C\u6210(finish\u5DE5\u5177),\u5F52\u6863\u4F1A\u8BDD"),qt(),_("Breaking out of react loop after finish tool call");return}}let b=un()[T];if(!b){let j=`Unknown tool: ${T}`;Be(j),r.push({role:"assistant",content:f||null,tool_calls:[w]}),r.push({role:"tool",tool_call_id:w.id,content:j});continue}let U=b.formatAction(P);ie(ce.cyan(`\u884C\u52A8: ${U}`),t),ie("",t);try{let j=!1;if(T==="shell"&&b&&typeof b.getDynamicDefinition=="function"?j=b.getDynamicDefinition(P).requiresConfirmation||!1:j=Ms().find(N=>N.name===T)?.requiresConfirmation||!1,j&&!await ty(T,P,t)){let N=`\u5DE5\u5177\u6267\u884C\u5DF2\u53D6\u6D88: ${T}`;zt(N),Vt(ce.yellow(`\u26A0 ${N}`),t),ie(ce.gray("\u60A8\u53EF\u4EE5\u7EE7\u7EED\u63D0\u4F9B\u65B0\u7684\u6307\u4EE4\u6216\u4FEE\u6539\u4E4B\u524D\u7684\u8BF7\u6C42\u3002"),t),r.push({role:"assistant",content:f||null,tool_calls:[w]}),r.push({role:"tool",tool_call_id:w.id,content:"Execution cancelled by user"});continue}_(`\u6267\u884C\u5DE5\u5177: ${T}(${JSON.stringify(P)})`);let L=await Promise.resolve(b.execute(P));_(`\u5DE5\u5177 ${T} \u6267\u884C\u5B8C\u6210`),_i(T);let M=Kr(L),$=b?b.shouldPrintObservation(L):!0,O=`${b?b.formatObservation(L):String(L)}`;$&&(ie(ce.yellow(`\u89C2\u5BDF: ${O}`),t),ie("",t)),r.push({role:"assistant",content:f||null,tool_calls:[w]}),r.push({role:"tool",tool_call_id:w.id,content:String(M)})}catch(j){let L=`\u5DE5\u5177\u6267\u884C\u9519\u8BEF: ${T} - ${j.message}`;Be(L,t),ie("",t),r.push({role:"assistant",content:f||null,tool_calls:[w]}),r.push({role:"tool",tool_call_id:w.id,content:`Error: ${L}`}),$e(r,s)}}if((!f||!f.trim())&&(!y||y.length===0)){if(ia("Model returned empty response"),m.finish_reason==="stop"){Vt("\u4EFB\u52A1\u5B8C\u6210(\u6A21\u578B\u505C\u6B62)",t),qt(),_("Breaking out of react loop after model stop");return}r.push({role:"user",content:"Please continue or provide your final answer."})}}catch(u){Be(`\u9519\u8BEF: ${u.message}`,t),Vt("\u4F1A\u8BDD\u5DF2\u4FDD\u5B58\u3002\u4F7F\u7528 /resume \u7EE7\u7EED\u3002",t),$e(r,s);return}}if(a>=c){Be("\u9519\u8BEF: \u5DF2\u8FBE\u5230\u6700\u5927\u8FED\u4EE3\u6B21\u6570",t);let u=Math.floor(a/i.compressionInterval),p=Math.floor(a/i.anchorInjectionInterval),g=Math.floor(a/i.semanticCheckInterval);_(`\u4F18\u5316\u7EDF\u8BA1: \u538B\u7F29${u}\u6B21, \u951A\u70B9\u6CE8\u5165${p}\u6B21, \u8BED\u4E49\u68C0\u67E5${g}\u6B21`),$e(r,s)}}async function ty(s,e,t=null){return new Promise(n=>{let r=0,o=[{text:"\u786E\u8BA4\u6267\u884C",value:!0},{text:"\u4E2D\u65AD\u6267\u884C",value:!1}],i=JSON.stringify(e),a=()=>{for(let d=0;d<8;d++)mn.moveCursor(process.stdout,0,-1),mn.clearLine(process.stdout,0);let m=t?ce.yellow(`\u26A0 \u786E\u8BA4\u6267\u884C ${s}(${i})\uFF1F\u6B64\u64CD\u4F5C\u53EF\u80FD\u65E0\u6CD5\u64A4\u9500\u3002`):ce.yellow(`\u26A0 Confirm execution of ${s}(${i})? This action may be irreversible.`);console.log(""),console.log(m),console.log(""),console.log(ce.cyan("\u8BF7\u9009\u62E9 (\u4F7F\u7528\u4E0A\u4E0B\u7BAD\u5934\u952E\uFF0CEnter\u786E\u8BA4):")),console.log(""),o.forEach((d,f)=>{let y=f===r,w=y?ce.green("> "):" ",T=y?ce.green.bold(d.text):ce.white(d.text);console.log(`${w}${T}`)}),console.log("")},c=process.stdin.isTTY?process.stdin.isRaw:!1,l=[],u=yr();process.stdin.isTTY&&process.stdin.setRawMode(!0),u?u.__isHandlingConfirmation=!0:(l=process.stdin.listeners("keypress"),process.stdin.removeAllListeners("keypress"));let p=(m,d)=>{if(d.name==="up"){r=Math.max(0,r-1),a();return}else if(d.name==="down"){r=Math.min(o.length-1,r+1),a();return}else if(d.name==="return"||d.name==="enter"){g();for(let f=0;f<8;f++)mn.moveCursor(process.stdout,0,-1),mn.clearLine(process.stdout,0);n(o[r].value);return}else if(d.name==="escape"||d.ctrl&&d.name==="c"){g();for(let f=0;f<8;f++)mn.moveCursor(process.stdout,0,-1),mn.clearLine(process.stdout,0);n(!1);return}},g=()=>{u?(u.removeListener("keypress",p),delete u.__isHandlingConfirmation):(process.stdin.removeListener("keypress",p),l.forEach(m=>{process.stdin.on("keypress",m)})),process.stdin.isTTY&&process.stdin.setRawMode(c)};u?u.on("keypress",p):(mn.emitKeypressEvents(process.stdin),process.stdin.on("keypress",p)),a()})}var Xc=S(()=>{ae();Ie();tn();mt();pn();Is();Pi();ct();lr();Us();ac();Ii();sn();_s();Q();Ug();Si()});var Hg={};B(Hg,{DocumentAggregator:()=>Qc});import{readFileSync as ny,existsSync as Wg,readdirSync as ry,statSync as sy}from"fs";import{join as Bg,extname as oy}from"path";var Qc,zg=S(()=>{Q();Fe();La();Qc=class{docsDir;cache=new Map;cacheExpiry=300*1e3;lastCacheTime=0;constructor(e){this.docsDir=e||Bg(process.cwd(),".nium","docs")}async getDocFiles(){if(!Wg(this.docsDir))return[];let e=[];try{let t=ry(this.docsDir,{withFileTypes:!0});for(let n of t)if(n.isFile()&&this.isMarkdownFile(n.name)){let r=Bg(this.docsDir,n.name),o=sy(r);try{let i=ny(r,"utf-8");e.push({name:n.name,path:r,content:i,lastModified:o.mtime,size:o.size})}catch(i){C(`\u65E0\u6CD5\u8BFB\u53D6\u6587\u6863\u6587\u4EF6 ${n.name}: ${i}`)}}}catch(t){C(`\u8BFB\u53D6\u6587\u6863\u76EE\u5F55\u5931\u8D25: ${t}`)}return e.sort((t,n)=>t.name.localeCompare(n.name)),e}isMarkdownFile(e){let t=oy(e).toLowerCase();return t===".md"||t===".markdown"}async aggregateDocuments(){let e=Date.now();if(e-this.lastCacheTime<this.cacheExpiry&&this.cache.has("default"))return this.cache.get("default");let t=await this.getDocFiles();if(t.length===0){let c={files:[],totalContent:"",summary:"",lastUpdated:new Date};return this.cache.set("default",c),this.lastCacheTime=e,c}let n="",r=[];r.push("# \u{1F4DA} \u9879\u76EE\u6587\u6863\u7D22\u5F15"),r.push(""),r.push(`> \u751F\u6210\u65F6\u95F4: ${H()}`),r.push(`> \u6587\u6863\u6570\u91CF: ${t.length} \u4E2A\u6587\u4EF6`),r.push(""),r.push("## \u{1F4CB} \u6587\u6863\u5217\u8868"),r.push("");for(let c of t){let l=c.name.replace(".md",""),u=Math.round(c.size/1024),p=H(c.lastModified);r.push(`### \u{1F4C4} ${l}`),r.push(`- **\u8DEF\u5F84**: \`.nium/docs/${c.name}\``),r.push(`- **\u5927\u5C0F**: ${u} KB`),r.push(`- **\u66F4\u65B0\u65F6\u95F4**: ${p}`),r.push("");let g=c.content.split(`
3317
+ `)[0].trim();g&&g.startsWith("#")&&(r.push(`**\u63CF\u8FF0**: ${g.replace(/^#+\s*/,"")}`),r.push(""))}r.push("---"),r.push(""),r.push("## \u{1F4D6} \u8BE6\u7EC6\u5185\u5BB9"),r.push("");for(let c of t)n+=`
3318
+
3319
+ # \u{1F4C1} ${c.name}
3320
+
3321
+ `,n+=c.content,n+=`
3322
+
3323
+ ---
3324
+ `;let o=r.join(`
3325
+ `),i=o+n,a={files:t,totalContent:i,summary:o,lastUpdated:new Date};return this.cache.set("default",a),this.lastCacheTime=e,F(`\u5DF2\u805A\u5408 ${t.length} \u4E2A\u6587\u6863\u6587\u4EF6\uFF0C\u603B\u8BA1 ${Math.round(i.length/1024)} KB`),a}async getDocumentSummary(e=8e3){let t=await this.aggregateDocuments();if(!t.files.length)return"";let n=t.totalContent;if(n.length/4<=e)return n;let o=t.summary,i=e-o.length/4;if(i>1e3){let a=i*4,c=n.substring(0,a);return o+`
3326
+
3327
+ `+c+`
3328
+
3329
+ ... (\u5185\u5BB9\u5DF2\u622A\u65AD\uFF0C\u5B8C\u6574\u5185\u5BB9\u8BF7\u67E5\u770B\u5177\u4F53\u6587\u6863\u6587\u4EF6)`}return o+`
3330
+
3331
+ ... (\u5185\u5BB9\u5DF2\u622A\u65AD\u4EE5\u9002\u5E94\u4E0A\u4E0B\u6587\u9650\u5236)`}async hasUpdates(){let e=await this.getDocFiles();if(e.length===0&&(!this.cache.has("default")||this.cache.get("default").files.length===0))return!1;if(e.length!==(this.cache.get("default")?.files.length||0))return!0;for(let t of e){let n=this.cache.get("default")?.files.find(r=>r.name===t.name);if(!n||t.lastModified>n.lastModified)return!0}return!1}clearCache(){this.cache.clear(),this.lastCacheTime=0}async getStats(){let e=await this.getDocFiles();return{fileCount:e.length,totalSize:e.reduce((t,n)=>t+n.size,0),lastModified:e.length>0?new Date(Math.max(...e.map(t=>t.lastModified.getTime()))):null,files:e.map(t=>({name:t.name,size:t.size,modified:t.lastModified}))}}async getRelevantDocuments(e,t=5,n=3e3){try{if(!Wg(this.docsDir))return"";let r=await Qt({query:e,path:this.docsDir.replace(process.cwd(),"").replace(/^[\\/]/,""),maxResults:t});if(!r||typeof r=="string")return C("\u672A\u627E\u5230\u76F8\u5173\u6587\u6863\u6216\u641C\u7D22\u51FA\u9519"),"";let o=[];o.push("# \u{1F4DA} \u76F8\u5173\u9879\u76EE\u6587\u6863"),o.push(""),o.push(`> \u57FA\u4E8E\u67E5\u8BE2: "${e}"`),o.push(`> \u627E\u5230 ${r.length} \u4E2A\u76F8\u5173\u6587\u6863\u7247\u6BB5`),o.push("");let i=0;for(let c of r){if(c.startsWith("Found ")||c==="")continue;if(c.match(/^\d+\.\s*📄/)&&(o.push("---"),o.push("")),o.push(c),i+=c.length,i/4>=n){o.push(""),o.push("... (\u5185\u5BB9\u5DF2\u622A\u65AD\u4EE5\u9002\u5E94\u4E0A\u4E0B\u6587\u9650\u5236)");break}}let a=o.join(`
3332
+ `);return F(`\u5DF2\u68C0\u7D22\u76F8\u5173\u6587\u6863\uFF0C\u7EA6 ${Math.round(a.length/4)} tokens`),a}catch(r){return C(`\u667A\u80FD\u68C0\u7D22\u76F8\u5173\u6587\u6863\u65F6\u51FA\u9519: ${r}`),""}}extractKeywords(e){let t=new Set(["the","a","an","and","or","but","is","are","was","were","in","on","at","to","for","of","with","by","from","\u7684","\u4E86","\u5728","\u662F","\u6211","\u6709","\u548C","\u5C31","\u4E0D","\u4EBA","\u90FD","\u4E00","\u8FD9","\u4E2A"]),n=e.toLowerCase().replace(/[^\w\s\u4e00-\u9fa5]/g," ").split(/\s+/).filter(r=>r.length>2&&!t.has(r));return Array.from(new Set(n)).slice(0,10)}}});import ue from"chalk";async function el(s,e=!1,t=null,n={}){Zc||(Zc=new Ir(t,n)),await Zc.executeTask(s,e)}var Ir,Zc,Vg=S(()=>{$i();Qe();Xc();tn();ct();Q();fc();Ei();ii();Si();Ir=class{session;subAgentManager;orchestratorContext;progressiveDisclosure;workerContextBuilder;summaryExtractor;options;constructor(e=null,t={}){this.session=e,Tc(e);let n={matchStrategy:t.matchStrategy};this.subAgentManager=hr(n),this.options={useLLMDisclosure:t.useLLMDisclosure!==void 0?t.useLLMDisclosure:!0,useLLMSummary:t.useLLMSummary!==void 0?t.useLLMSummary:!0,verbose:t.verbose||!1},this.orchestratorContext=new It,this.progressiveDisclosure=new Mt(this.orchestratorContext),this.workerContextBuilder=new At(this.orchestratorContext,this.progressiveDisclosure),this.summaryExtractor=new Rt(this.options.useLLMSummary)}log(e){this.session?this.session.log(e):console.log(e)}info(e){this.session?this.session.info(e):console.log(ue.blue(e))}success(e){this.session?this.session.success(e):console.log(ue.green(e))}warning(e){this.session?this.session.warning(e):console.log(ue.yellow(e))}error(e){this.session?this.session.error(e):console.log(ue.red(e))}async executeTask(e,t=!1){try{if(C("MasterAgent.executeTask called"),t){C("Entering resume session mode"),this.info("\u6062\u590D\u4F1A\u8BDD\u6A21\u5F0F"),await co(e,!0,this.session);return}let{evaluateTaskComplexity:n,TaskComplexity:r}=await Promise.resolve().then(()=>(Qe(),$t));await n(e)===r.COMPLEX?await this.executeWithPlanning(e):await this.executeWithSingleAgent(e),this.log(""),this.success("\u4EFB\u52A1\u6267\u884C\u5B8C\u6210"),this.options.verbose&&(this.log(""),this.log(ue.gray("\u5168\u5C40\u4E0A\u4E0B\u6587\u6458\u8981")),this.log(ue.gray(JSON.stringify(this.orchestratorContext.getCompactSummary(),null,2))))}catch(n){throw this.error(`\u4EFB\u52A1\u6267\u884C\u5931\u8D25: ${n.message}`),n}}async executeWithSingleAgent(e){await this.ensureProjectStructure();let t={markdown:"",tasks:[{step:1,description:e,status:"pending",subAgent:"default"}],taskId:"",strategy:"single-agent",totalSteps:1};this.orchestratorContext.initializeTask(e,t);let n=await this.subAgentManager.matchSubAgent(e);if(n){this.info(`\u5339\u914D\u5230\u4E13\u7528\u5B50\u667A\u80FD\u4F53: ${n.name}`),this.log("");let r=await this.workerContextBuilder.buildIsolatedContext(1,e,n.prompt,this.options.useLLMDisclosure,void 0,n.name);await this.executeSubAgentTask(1,e,n,r)}else this.info("\u4F7F\u7528\u9ED8\u8BA4React\u667A\u80FD\u4F53"),this.log(""),await co(e,!1,this.session)}async executeWithPlanning(e){let t=this.subAgentManager.getAllSubAgents(),n=await As(e,t);this.orchestratorContext.initializeTask(e,n),n.taskId&&An(n.taskId),this.log(Rs(n)),this.log(""),await this.ensureProjectStructure(),await this.loadProjectRules(e),this.analyzeStepDependencies(n);for(let r=0;r<n.tasks.length;r++){let o=n.tasks[r],i=o.step;this.log(""),this.info(`[${i}/${n.tasks.length}] ${o.description}`),this.log(""),this.orchestratorContext.plan.currentStep=i,n.taskId&&await nn(n.taskId,i,"in_progress");try{let a=this.getSubAgentConfig(o),c=await this.workerContextBuilder.buildIsolatedContext(i,o.description,a?.prompt||"",this.options.useLLMDisclosure,void 0,a?.name);this.options.verbose&&this.log(ue.gray(`\u4E0A\u4E0B\u6587\u5927\u5C0F: ${c.length} \u6761\u6D88\u606F`)),a?await this.executeSubAgentTask(i,o.description,a,c):await this.executeDefaultAgentWithContext(o.description,c),this.success(`\u5B8C\u6210\u6B65\u9AA4 [${i}/${n.tasks.length}]`),n.taskId&&await nn(n.taskId,i,"completed")}catch(a){throw this.error(`\u6B65\u9AA4 [${i}/${n.tasks.length}] \u6267\u884C\u5931\u8D25: ${a.message}`),this.warning("\u4E2D\u6B62\u540E\u7EED\u6B65\u9AA4\u6267\u884C"),this.orchestratorContext.recordStepCompletion(i,`\u5931\u8D25: ${a.message}`,{success:!1,error:a.message}),a}}}async ensureProjectStructure(){try{let{existsSync:e}=await import("fs");if(e(".nium/project/project.json")){C("project.json \u5DF2\u5B58\u5728\uFF0C\u8DF3\u8FC7\u81EA\u52A8\u751F\u6210");return}this.log(""),this.info("\u68C0\u6D4B\u5230\u9879\u76EE\u7ED3\u6784\u6587\u6863\u4E0D\u5B58\u5728\uFF0C\u6267\u884C\u5FEB\u901F\u626B\u63CF..."),this.log("");let{tools:n}=await Promise.resolve().then(()=>(mt(),Bs));await n.quickProjectScan(),this.success("\u9879\u76EE\u7ED3\u6784\u6587\u6863\u5DF2\u751F\u6210"),this.log(""),F("\u5DF2\u81EA\u52A8\u751F\u6210 project.json")}catch(e){C(`\u81EA\u52A8\u751F\u6210\u9879\u76EE\u7ED3\u6784\u6587\u6863\u5931\u8D25: ${e.message}`),this.warning("\u9879\u76EE\u7ED3\u6784\u6587\u6863\u751F\u6210\u5931\u8D25\uFF0C\u5C06\u7EE7\u7EED\u6267\u884C\u4EFB\u52A1")}}async loadProjectRules(e=""){try{let{DocumentAggregator:t}=await Promise.resolve().then(()=>(zg(),Hg)),n=new t,r="",{tools:o}=await Promise.resolve().then(()=>(mt(),Bs)),a=o.read({path:[".nium/rules.md"]});a&&!a.includes("Error:")&&(r+=a,F("\u5DF2\u52A0\u8F7D\u9879\u76EE\u89C4\u5219\u6587\u4EF6"));let l=o.read({path:[".nium/project/project.json"]});if(l&&!l.includes("Error:")){r&&(r+=`
1907
3333
 
1908
3334
  ---
1909
3335
 
1910
3336
  `),r+=`## \u9879\u76EE\u5173\u952E\u4FE1\u606F
1911
3337
 
1912
- `;try{let l=JSON.parse(c),u=this.extractProjectKeySummary(l);r+=u,M("\u5DF2\u52A0\u8F7D\u9879\u76EE\u5173\u952E\u4FE1\u606F\u6458\u8981")}catch{r+=c,x("\u89E3\u6790\u9879\u76EE\u7ED3\u6784JSON\u5931\u8D25\uFF0C\u4F7F\u7528\u539F\u59CB\u5185\u5BB9")}}r&&this.orchestratorContext.updateSharedState("rules",r)}catch{x("\u52A0\u8F7D\u9879\u76EE\u6587\u6863\u65F6\u51FA\u9519\uFF0C\u8DF3\u8FC7")}}analyzeStepDependencies(e){for(let t=0;t<e.tasks.length;t++){let n=e.tasks[t].step,r=t>0?[e.tasks[t-1].step]:[];this.orchestratorContext.setStepDependencies(n,r)}x("\u6B65\u9AA4\u4F9D\u8D56\u5173\u7CFB\u5DF2\u5206\u6790")}getSubAgentConfig(e){return e.subAgent&&e.subAgent!=="default"?this.subAgentManager.getSubAgent(e.subAgent):null}async executeSubAgentTask(e,t,n,r){let s=Date.now();this.info(`\u{1F527} \u4F7F\u7528\u5B50\u667A\u80FD\u4F53: ${n.name}`),this.log(N.gray(`\u63CF\u8FF0: ${n.description}`)),this.log("");try{let i=[{role:"system",content:st},...r.filter(u=>u.role!=="system"),...r.filter(u=>u.role==="system"&&u!==r[0])],a={...n,orchestratorContext:this.orchestratorContext},c=await this.runWorkerLoop(i,t,a);await this.recordWorkerResult(e,c);let l=Date.now()-s;this.subAgentManager.recordAgentPerformance(n.name,!0,l)}catch(i){let a=Date.now()-s;throw this.subAgentManager.recordAgentPerformance(n.name,!1,a),i}}async executeDefaultAgentWithContext(e,t){this.info("\u{1F916} \u4F7F\u7528\u9ED8\u8BA4React\u667A\u80FD\u4F53"),this.log("");let n=[{role:"system",content:st},...t.filter(r=>r.role!=="system"),...t.filter(r=>r.role==="system")];await this.runWorkerLoop(n,e)}async runWorkerLoop(e,t,n=null){let{MODEL:r}=await Promise.resolve().then(()=>(le(),wt)),{callModelAPI:s}=await Promise.resolve().then(()=>(ve(),Gt)),{isThinkTool:i,extractThought:a}=await Promise.resolve().then(()=>(Xn(),Ms)),{isFinishTool:c,extractFinishInfo:l}=await Promise.resolve().then(()=>(wo(),ei)),{getToolDefinitions:u}=await Promise.resolve().then(()=>(Ht(),ri)),{tools:p,toolInstances:g,extractToolResult:d}=await Promise.resolve().then(()=>(Re(),ur)),m=[...e],h=0,w=50;for(;h<w;){h++;try{ce(m,t);let v=await s({model:r(),messages:m,temperature:.1,tools:u()}),T=v.choices[0].message.tool_calls;if(v.choices[0].finish_reason==="stop"){let{content:I}=v.choices[0].message;if(I&&I.trim()){if(n?.finalAnswerCallback)try{await n.finalAnswerCallback(I,n)}catch(oe){X(`Error in finalAnswerCallback: ${oe}`)}this.log(N.green("\u4EFB\u52A1\u5B8C\u6210:")),this.log(I),this.log("")}break}if(!T||T.length===0){let{content:I}=v.choices[0].message;if(I&&I.trim()){if(n?.finalAnswerCallback)try{await n.finalAnswerCallback(I,n)}catch(oe){X(`Error in finalAnswerCallback: ${oe}`)}this.log(N.green("\u4EFB\u52A1\u5B8C\u6210:")),this.log(I),this.log(""),m.push({role:"assistant",content:I});break}continue}let f=T[0],y=f.function.name,S;try{S=JSON.parse(f.function.arguments),this.log(N.gray(`[DEBUG] Tool: ${y}`)),this.log(N.gray(`[DEBUG] Raw arguments: ${f.function.arguments.substring(0,200)}${f.function.arguments.length>200?"...":""}`)),this.log(N.gray(`[DEBUG] Parsed keys: ${Object.keys(S).join(", ")}`)),this.log("")}catch{this.error(`\u89E3\u6790\u5DE5\u5177\u53C2\u6570\u5931\u8D25: ${f.function.arguments}`),m.push({role:"assistant",content:null,tool_calls:[f]}),m.push({role:"tool",tool_call_id:f.id,content:"Error: Invalid JSON arguments"});continue}if(i(y)){let I=a(f);I&&(this.log(N.cyan(`\u{1F4AD} Think: ${I}`)),this.log("")),m.push({role:"assistant",content:null,tool_calls:[f]}),m.push({role:"tool",tool_call_id:f.id,content:"Noted. Continue with your action."});continue}if(c(y)){let I=l(f);if(I){let{answer:oe,success:te}=I;if(n?.finalAnswerCallback)try{await n.finalAnswerCallback(oe,n)}catch(J){X(`Error in finalAnswerCallback: ${J}`)}let on=te?"\u2705":"\u26A0\uFE0F";this.log(N.green(`${on} \u4EFB\u52A1\u5B8C\u6210 (\u901A\u8FC7 finish \u5DE5\u5177):`)),this.log(oe),this.log(""),m.push({role:"assistant",content:null,tool_calls:[f]}),m.push({role:"tool",tool_call_id:f.id,content:"Task completed successfully."}),m.push({role:"assistant",content:oe});break}}if(!p[y]){let I=`Error: Unknown tool '${y}'`;this.error(I),m.push({role:"assistant",content:null,tool_calls:[f]}),m.push({role:"tool",tool_call_id:f.id,content:I});continue}let E=u().find(I=>I.name===y);if(E&&E.input_schema&&E.input_schema.required){let I=E.input_schema.required||[],oe=I.filter(te=>S[te]===void 0);if(oe.length>0){let te=`Error: Missing required parameters: ${oe.join(", ")}
3338
+ `;try{let u=JSON.parse(l),p=this.extractProjectKeySummary(u);r+=p,F("\u5DF2\u52A0\u8F7D\u9879\u76EE\u5173\u952E\u4FE1\u606F\u6458\u8981")}catch{r+=l,C("\u89E3\u6790\u9879\u76EE\u7ED3\u6784JSON\u5931\u8D25\uFF0C\u4F7F\u7528\u539F\u59CB\u5185\u5BB9")}}try{let u=await n.getRelevantDocuments(e,5,3e3);u&&(r&&(r+=`
3339
+
3340
+ ---
3341
+
3342
+ `),r+=u,F("\u5DF2\u52A0\u8F7D\u76F8\u5173\u9879\u76EE\u6587\u6863\uFF08\u667A\u80FD\u68C0\u7D22\uFF09"))}catch(u){C(`\u52A0\u8F7D\u9879\u76EE\u6587\u6863\u5931\u8D25: ${u.message}`)}r&&this.orchestratorContext.updateSharedState("rules",r)}catch{C("\u52A0\u8F7D\u9879\u76EE\u6587\u6863\u65F6\u51FA\u9519\uFF0C\u8DF3\u8FC7")}}analyzeStepDependencies(e){for(let t=0;t<e.tasks.length;t++){let n=e.tasks[t].step,r=t>0?[e.tasks[t-1].step]:[];this.orchestratorContext.setStepDependencies(n,r)}C("\u6B65\u9AA4\u4F9D\u8D56\u5173\u7CFB\u5DF2\u5206\u6790")}getSubAgentConfig(e){return e.subAgent&&e.subAgent!=="default"?this.subAgentManager.getSubAgent(e.subAgent):null}async executeSubAgentTask(e,t,n,r){let o=Date.now();this.info(`\u4F7F\u7528\u5B50\u667A\u80FD\u4F53: ${n.name}`),this.log(ue.gray(`\u63CF\u8FF0: ${n.description}`)),this.log("");try{let a=[{role:"system",content:await cr},...r.filter(p=>p.role!=="system"),...r.filter(p=>p.role==="system"&&p!==r[0])],c={...n,orchestratorContext:this.orchestratorContext},l=await this.runWorkerLoop(a,t,c);await this.recordWorkerResult(e,l);let u=Date.now()-o;this.subAgentManager.recordAgentPerformance(n.name,!0,u)}catch(i){let a=Date.now()-o;throw this.subAgentManager.recordAgentPerformance(n.name,!1,a),i}}async executeDefaultAgentWithContext(e,t){this.info("\u4F7F\u7528\u9ED8\u8BA4React\u667A\u80FD\u4F53"),this.log("");let r=[{role:"system",content:await cr},...t.filter(o=>o.role!=="system"),...t.filter(o=>o.role==="system")];await this.runWorkerLoop(r,e)}async runWorkerLoop(e,t,n=null){let{MODEL:r}=await Promise.resolve().then(()=>(ae(),Ln)),{callModelAPI:o}=await Promise.resolve().then(()=>(Ie(),pr)),{isThinkTool:i,extractThought:a,formatThoughtWithHighlight:c}=await Promise.resolve().then(()=>(Is(),Ba)),{isFinishTool:l,extractFinishInfo:u}=await Promise.resolve().then(()=>(Pi(),vc)),{getToolDefinitions:p}=await Promise.resolve().then(()=>(lr(),kc)),{tools:g,toolInstances:m,extractToolResult:d}=await Promise.resolve().then(()=>(mt(),Bs)),f=[...e],y=0,w=50;for(;y<w;){y++;try{$e(f,t);let T=await o({model:r(),messages:f,temperature:.1,tools:p()}),h=T.choices[0].message.tool_calls;if(T.choices[0].finish_reason==="stop"){let{content:D}=T.choices[0].message;if(D&&D.trim()){if(n?.finalAnswerCallback)try{await n.finalAnswerCallback(D,n)}catch(N){ne(`Error in finalAnswerCallback: ${N}`)}this.log(ue.green("\u4EFB\u52A1\u5B8C\u6210:")),this.log(D),this.log("")}break}if(!h||h.length===0){let{content:D}=T.choices[0].message;if(D&&D.trim()){if(n?.finalAnswerCallback)try{await n.finalAnswerCallback(D,n)}catch(N){ne(`Error in finalAnswerCallback: ${N}`)}this.log(ue.green("\u4EFB\u52A1\u5B8C\u6210:")),this.log(D),this.log(""),f.push({role:"assistant",content:D});break}continue}let x=h[0],P=x.function.name,k=mr(x.function.arguments);if(!k.success){this.error(`\u2717 \u89E3\u6790\u5DE5\u5177\u53C2\u6570\u5931\u8D25: ${x.function.arguments}`),this.error(` JSON\u89E3\u6790\u9519\u8BEF: ${k.error}`);let D=p().find(Y=>Y.name===P),N="";if(D){let Y={},vt=D.input_schema.properties;(D.input_schema.required||[]).forEach(te=>{let je=vt[te];je&&(je.type==="string"?Y[te]="example":je.type==="array"?Y[te]=je.items?.type==="string"?["example1","example2"]:[]:je.type==="object"?Y[te]={}:je.type==="number"?Y[te]=0:je.type==="boolean"&&(Y[te]=!1))}),N=`
3343
+
3344
+ \u6B63\u786E\u7684\u53C2\u6570\u683C\u5F0F\u793A\u4F8B:
3345
+ ${JSON.stringify(Y,null,2)}`}f.push({role:"assistant",content:null,tool_calls:[x]}),f.push({role:"tool",tool_call_id:x.id,content:`Error: Invalid JSON arguments - ${k.error}
3346
+
3347
+ \u539F\u59CB\u53C2\u6570: ${x.function.arguments}
3348
+ ${N}
3349
+
3350
+ \u8BF7\u786E\u4FDD:
3351
+ 1. \u6240\u6709\u5B57\u7B26\u4E32\u503C\u90FD\u7528\u53CC\u5F15\u53F7\u62EC\u8D77\u6765
3352
+ 2. \u6570\u7EC4\u4F7F\u7528\u65B9\u62EC\u53F7 []
3353
+ 3. \u5BF9\u8C61\u4F7F\u7528\u82B1\u62EC\u53F7 {}
3354
+ 4. \u4E0D\u8981\u4F7F\u7528\u88F8\u7684\u7B26\u53F7\uFF08\u5982 ., * \u7B49\uFF09\u4F5C\u4E3A\u503C\uFF0C\u5B83\u4EEC\u5FC5\u987B\u662F\u5B57\u7B26\u4E32`});continue}k.wasFixed&&this.warning("\u26A0 JSON\u683C\u5F0F\u5DF2\u81EA\u52A8\u4FEE\u590D");let b=k.data;if(this.options.verbose&&C(`Tool: ${P}, args: ${Object.keys(b).join(", ")}`),i(P)){let D=a(x);if(D){let N=c(D);this.log(ue.cyan(`\u601D\u8003: ${N}`)),this.log("")}f.push({role:"assistant",content:null,tool_calls:[x]}),f.push({role:"tool",tool_call_id:x.id,content:"Noted. Continue with your action."});continue}if(l(P)){let D=u(x);if(D){let{answer:N,success:Y}=D;if(n?.finalAnswerCallback)try{await n.finalAnswerCallback(N,n)}catch(V){ne(`Error in finalAnswerCallback: ${V}`)}let vt=Y?"\u2713":"\u26A0";this.log(ue.green(`${vt} \u4EFB\u52A1\u5B8C\u6210 (\u901A\u8FC7 finish \u5DE5\u5177):`)),this.log(N),this.log(""),f.push({role:"assistant",content:null,tool_calls:[x]}),f.push({role:"tool",tool_call_id:x.id,content:"Task completed successfully."}),f.push({role:"assistant",content:N});break}}if(!g[P]){let D=`Error: Unknown tool '${P}'`;this.error(D),f.push({role:"assistant",content:null,tool_calls:[x]}),f.push({role:"tool",tool_call_id:x.id,content:D});continue}let U=p().find(D=>D.name===P);if(U&&U.input_schema&&U.input_schema.required){let D=U.input_schema.required||[],N=D.filter(Y=>b[Y]===void 0);if(N.length>0){let Y=`Error: Missing required parameters: ${N.join(", ")}
1913
3355
 
1914
- Tool: ${y}
1915
- Required parameters: ${I.join(", ")}
1916
- Provided parameters: ${Object.keys(S).join(", ")||"none"}
3356
+ Tool: ${P}
3357
+ Required parameters: ${D.join(", ")}
3358
+ Provided parameters: ${Object.keys(b).join(", ")||"none"}
1917
3359
 
1918
- Please call the tool again with ALL required parameters.`;this.error(te),m.push({role:"assistant",content:null,tool_calls:[f]}),m.push({role:"tool",tool_call_id:f.id,content:te});continue}}let P=g[y],L=P?P.formatAction(S):`${y}()`;this.log(N.blue(`\u{1F527} \u884C\u52A8: ${L}`)),this.log("");let R=await p[y](S),O=d(R),K=P?P.shouldPrintObservation(R):!0,U=P?P.formatObservation(R):String(R);K&&(this.log(N.yellow(`\u{1F4CA} \u89C2\u5BDF: ${U}`)),this.log("")),m.push({role:"assistant",content:null,tool_calls:[f]}),m.push({role:"tool",tool_call_id:f.id,content:String(O)}),["read","write","merge"].includes(y)&&S.path&&this.orchestratorContext.addRecentFile(S.path),ce(m,t)}catch(v){throw this.error(`\u9519\u8BEF: ${v.message}`),ce(m,t),v}}if(h>=w)throw this.error("\u9519\u8BEF: \u5DF2\u8FBE\u5230\u6700\u5927\u8FED\u4EE3\u6B21\u6570"),ce(m,t),new Error("Maximum iterations reached");return m}async recordWorkerResult(e,t){let n=await this.summaryExtractor.extractSummary(t),r=this.summaryExtractor.extractMetadata(t);r.success=!0,this.orchestratorContext.recordStepCompletion(e,n,r,this.progressiveDisclosure),this.options.verbose&&this.info(`\u6B65\u9AA4 ${e} \u6458\u8981\u5DF2\u8BB0\u5F55\u5230\u5168\u5C40\u4E0A\u4E0B\u6587`),this.options.verbose&&(this.log(""),this.log(N.gray("\u2500\u2500\u2500 \u6B65\u9AA4\u6267\u884C\u6458\u8981 \u2500\u2500\u2500")),this.log(N.gray(`\u6458\u8981: ${n}`)),this.log(N.gray(`\u5DE5\u5177: ${r.toolsUsed.join(", ")}`)),this.log(N.gray(`\u6587\u4EF6: ${r.filesAccessed.join(", ")}`)),this.log(N.gray(`\u8FED\u4EE3: ${r.iterations} \u6B21`)))}extractProjectKeySummary(e){let t=[];return t.push("**\u57FA\u672C\u4FE1\u606F**"),t.push(`- \u9879\u76EE\u540D\u79F0: ${e.name||"N/A"}`),t.push(`- \u4E3B\u8981\u8BED\u8A00: ${e.language||"N/A"}`),t.push(`- \u6784\u5EFA\u5DE5\u5177: ${e.build_tool||"N/A"}`),t.push(`- \u9879\u76EE\u7C7B\u578B: ${e.project_type||"N/A"}`),t.push(""),e.directory_structure&&e.directory_structure.length>0&&(t.push("**\u6838\u5FC3\u76EE\u5F55** (\u524D8\u4E2A)"),e.directory_structure.slice(0,8).forEach(n=>{t.push(`- ${n}`)}),t.push("")),e.entry_files&&e.entry_files.length>0&&(t.push("**\u5165\u53E3\u6587\u4EF6**"),e.entry_files.forEach(n=>{t.push(`- ${n}`)}),t.push("")),e.dependencies&&e.dependencies.length>0&&(t.push("**\u5173\u952E\u4F9D\u8D56** (\u524D12\u4E2A)"),t.push(e.dependencies.slice(0,12).join(", ")),t.push("")),t.join(`
1919
- `)}formatProjectStructureInfo(e){return tr(e,{format:"markdown",detailed:!0,customTitle:`# \u9879\u76EE\u7ED3\u6784\u4FE1\u606F
1920
- `})}}});import{readFileSync as jp}from"fs";import{join as _p}from"path";function Np(){let o={useLLMDisclosure:!0,useLLMSummary:!0};try{let e=_p(process.cwd(),".nium",".env"),n=jp(e,"utf-8").split(`
1921
- `);for(let r of n)if(r.startsWith("USE_LLM_DISCLOSURE=")){let s=r.split("=")[1]?.trim()||"";x(`[\u914D\u7F6E\u8BFB\u53D6] \u4ECE .nium/.env \u6587\u4EF6\u4E2D\u8BFB\u53D6: USE_LLM_DISCLOSURE=${s}`),o.useLLMDisclosure=s.toLowerCase()==="true"}else if(r.startsWith("USE_LLM_SUMMARY=")){let s=r.split("=")[1]?.trim()||"";x(`[\u914D\u7F6E\u8BFB\u53D6] \u4ECE .nium/.env \u6587\u4EF6\u4E2D\u8BFB\u53D6: USE_LLM_SUMMARY=${s}`),o.useLLMSummary=s.toLowerCase()==="true"}}catch(e){x(`[\u914D\u7F6E\u8BFB\u53D6] \u65E0\u6CD5\u8BFB\u53D6 .nium/.env \u6587\u4EF6: ${e.message}`)}return process.env.USE_LLM_DISCLOSURE!==void 0&&(x(`[\u914D\u7F6E\u8BFB\u53D6] \u4ECE\u73AF\u5883\u53D8\u91CF\u4E2D\u8BFB\u53D6: USE_LLM_DISCLOSURE=${process.env.USE_LLM_DISCLOSURE}`),o.useLLMDisclosure=_s("USE_LLM_DISCLOSURE")),process.env.USE_LLM_SUMMARY!==void 0&&(x(`[\u914D\u7F6E\u8BFB\u53D6] \u4ECE\u73AF\u5883\u53D8\u91CF\u4E2D\u8BFB\u53D6: USE_LLM_SUMMARY=${process.env.USE_LLM_SUMMARY}`),o.useLLMSummary=_s("USE_LLM_SUMMARY")),o}async function wi(){try{let o=Np();return M("[\u914D\u7F6E\u8BFB\u53D6] \u4F7F\u7528\u4E3B\u667A\u80FD\u4F53\uFF08\u4E0A\u4E0B\u6587\u9694\u79BB\u6A21\u5F0F\uFF09"),{executeMasterAgent:wl,MasterAgent:wr,config:o}}catch(o){throw X(`[\u914D\u7F6E\u8BFB\u53D6] \u914D\u7F6E\u8BFB\u53D6\u51FA\u9519: ${o}`),o}}var Tl=C(()=>{bl();vi();Y();Ns()});var Pl={};j(Pl,{COMMANDS:()=>br,executeCommand:()=>Oo,findCommand:()=>El,getAvailableCommands:()=>Tr,initializeDynamicCommands:()=>qp,printCommandHelp:()=>bi});import A from"chalk";async function Up(o,e){if(!o){e.warning("\u8BF7\u63D0\u4F9B\u4EFB\u52A1\u8BF7\u6C42\u5185\u5BB9");return}e.log(),e.info("\u5F00\u59CB\u5904\u7406\u4EFB\u52A1..."),e.log();try{let{executeMasterAgent:t,config:n}=await wi();await t(o,!1,e,n),e.log(),b.sessionId&&(e.log(A.gray(`\u5F53\u524D\u4F1A\u8BDD ID: ${b.sessionId.substring(0,8)}`)),b.tasks&&b.tasks.length>0&&e.log(A.gray(`\u5F53\u524D\u4F1A\u8BDD\u4EFB\u52A1\u6570: ${b.tasks.length}`)),e.log())}catch(t){throw e.error(`\u4EFB\u52A1\u5904\u7406\u5931\u8D25: ${t.message}`),t}}async function Wp(o){if(b.messages&&b.messages.length>0&&b.currentTask){o.log(),o.info(`\u6B63\u5728\u6062\u590D\u4F1A\u8BDD [ID:${b.sessionId?b.sessionId.substring(0,8):"unknown"}]...`),o.log();try{let{executeMasterAgent:e,config:t}=await wi();await e(null,!0,o,t),o.log(),o.success("\u4F1A\u8BDD\u6062\u590D\u5B8C\u6210"),b.sessionId&&(o.log(A.gray(`\u4F1A\u8BDD ID: ${b.sessionId.substring(0,8)}`)),b.tasks&&b.tasks.length>0&&o.log(A.gray(`\u4F1A\u8BDD\u4EFB\u52A1\u6570: ${b.tasks.length}`)),o.log())}catch(e){throw o.error(`\u4F1A\u8BDD\u6062\u590D\u5931\u8D25: ${e.message}`),e}}else o.warning("\u6CA1\u6709\u53EF\u6062\u590D\u7684\u4F1A\u8BDD\u3002\u4F7F\u7528 /chat <\u8BF7\u6C42> \u5F00\u59CB\u65B0\u4EFB\u52A1\u3002")}function Vp(o){et(),o.success("\u4F1A\u8BDD\u5DF2\u5F52\u6863\u5E76\u6E05\u7A7A"),o.log()}function zp(o){let e=Yi();o.log(e)}function kl(o){o.exit()}function Hp(o){o.printHelp&&o.printHelp()}function Jp(o){o.log(),o.log(A.cyan("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")),o.log(A.cyan(" \u{1F4E6} Available Tools ")),o.log(A.cyan("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")),o.log();let e=tn(),t=ml();if(Object.keys(e).length===0){o.warning("No tools loaded yet. Tools will be available after starting a task."),o.log();return}if(o.log(A.bold("\u{1F4CA} Summary:")),o.log(A.gray(` Total Tools: ${t.total}`)),o.log(A.gray(` Local Tools: ${t.local}`)),o.log(A.gray(` MCP Tools: ${t.mcp}`)),o.log(),t.local>0){o.log(A.bold.green("\u{1F527} Local Tools:")),o.log();let{localTools:n}=t;for(let r of n){let s=e[r];if(s&&s.getDefinition){let i=s.getDefinition();o.log(A.green(` \u2022 ${i.name}`)),o.log(A.gray(` ${i.description}`)),o.log()}}}if(t.mcp>0){o.log(A.bold.magenta("\u{1F310} MCP Tools:")),o.log();let{mcpTools:n}=t;for(let r of n){let s=e[r];if(s&&s.getDefinition){let i=s.getDefinition(),a=i.description.match(/\[MCP:([^\]]+)\]/),c=a?a[1]:"unknown",l=i.description.replace(/\[MCP:[^\]]+\]\s*/,"");o.log(A.magenta(` \u2022 ${i.name}`)),o.log(A.gray(` ${l}`)),o.log(A.gray(` (from MCP server: ${c})`)),o.log()}}}o.log(A.cyan("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")),o.log()}async function Gp(o){o.log(),o.info("\u6B63\u5728\u68C0\u67E5git\u53D8\u66F4...");try{if(!ir()){o.warning("\u6CA1\u6709\u672A\u63D0\u4EA4\u7684\u53D8\u66F4"),o.log();return}let e=or(),t=sr();o.log(),o.info("\u5F53\u524Dgit\u72B6\u6001:"),o.log(A.gray(e)),o.log();let n=t.length>500?t.substring(0,500)+`
1922
- ...(truncated)`:t;o.info("\u53D8\u66F4\u5185\u5BB9\u9884\u89C8:"),o.log(A.gray(n)),o.log(),o.info("\u6B63\u5728\u4F7F\u7528lite\u6A21\u578B\u751F\u6210commit message...");let s=[{role:"system",content:`\u4F60\u662F\u4E00\u4E2A\u4E13\u4E1A\u7684git commit message\u751F\u6210\u52A9\u624B\u3002
3360
+ Please call the tool again with ALL required parameters.`;this.error(Y),f.push({role:"assistant",content:null,tool_calls:[x]}),f.push({role:"tool",tool_call_id:x.id,content:Y});continue}}let j=m[P],L=j?j.formatAction(b):`${P}()`;this.log(ue.blue(`\u884C\u52A8: ${L}`)),this.log("");let M=await g[P](b),$=d(M),I=j?j.shouldPrintObservation(M):!0,O=j?j.formatObservation(M):String(M);I&&(this.log(ue.yellow(`\u89C2\u5BDF: ${O}`)),this.log("")),f.push({role:"assistant",content:null,tool_calls:[x]}),f.push({role:"tool",tool_call_id:x.id,content:String($)}),["read","write","merge"].includes(P)&&b.path&&this.orchestratorContext.addRecentFile(b.path),$e(f,t)}catch(T){throw this.error(`\u9519\u8BEF: ${T.message}`),$e(f,t),T}}if(y>=w)throw this.error("\u9519\u8BEF: \u5DF2\u8FBE\u5230\u6700\u5927\u8FED\u4EE3\u6B21\u6570"),$e(f,t),new Error("Maximum iterations reached");return f}async recordWorkerResult(e,t){let n=await this.summaryExtractor.extractSummary(t),r=this.summaryExtractor.extractMetadata(t);r.success=!0,this.orchestratorContext.recordStepCompletion(e,n,r,this.progressiveDisclosure),this.options.verbose&&(this.log(""),this.log(ue.gray("\u6B65\u9AA4\u6267\u884C\u6458\u8981")),this.log(ue.gray(`\u6458\u8981: ${n}`)),this.log(ue.gray(`\u5DE5\u5177: ${r.toolsUsed.join(", ")}`)),this.log(ue.gray(`\u6587\u4EF6: ${r.filesAccessed.join(", ")}`)),this.log(ue.gray(`\u8FED\u4EE3: ${r.iterations} \u6B21`)))}extractProjectKeySummary(e){let t=[];return t.push("**\u57FA\u672C\u4FE1\u606F**"),t.push(`- \u9879\u76EE\u540D\u79F0: ${e.name||"N/A"}`),t.push(`- \u4E3B\u8981\u8BED\u8A00: ${e.language||"N/A"}`),t.push(`- \u6784\u5EFA\u5DE5\u5177: ${e.build_tool||"N/A"}`),t.push(`- \u9879\u76EE\u7C7B\u578B: ${e.project_type||"N/A"}`),t.push(""),e.directory_structure&&e.directory_structure.length>0&&(t.push("**\u6838\u5FC3\u76EE\u5F55** (\u524D8\u4E2A)"),e.directory_structure.slice(0,8).forEach(n=>{t.push(`- ${n}`)}),t.push("")),e.entry_files&&e.entry_files.length>0&&(t.push("**\u5165\u53E3\u6587\u4EF6**"),e.entry_files.forEach(n=>{t.push(`- ${n}`)}),t.push("")),e.dependencies&&e.dependencies.length>0&&(t.push("**\u5173\u952E\u4F9D\u8D56** (\u524D12\u4E2A)"),t.push(e.dependencies.slice(0,12).join(", ")),t.push("")),t.join(`
3361
+ `)}formatProjectStructureInfo(e){return Ls(e,{format:"markdown",detailed:!0,customTitle:`# \u9879\u76EE\u7ED3\u6784\u4FE1\u606F
3362
+ `})}},Zc=null});var qg={};B(qg,{MasterAgent:()=>Ir,executeMasterAgent:()=>el,getConfig:()=>Gg,getDefaultMasterAgent:()=>Ui,reactLoop:()=>co});import{readFileSync as iy}from"fs";import{join as ay}from"path";function Gg(){let s={useLLMDisclosure:!0,useLLMSummary:!0};try{let e=ay(process.cwd(),".nium",".env"),n=iy(e,"utf-8").split(`
3363
+ `);for(let r of n)if(r.startsWith("USE_LLM_DISCLOSURE=")){let o=r.split("=")[1]?.trim()||"";C(`[\u914D\u7F6E\u8BFB\u53D6] \u4ECE .nium/.env \u6587\u4EF6\u4E2D\u8BFB\u53D6: USE_LLM_DISCLOSURE=${o}`),s.useLLMDisclosure=o.toLowerCase()==="true"}else if(r.startsWith("USE_LLM_SUMMARY=")){let o=r.split("=")[1]?.trim()||"";C(`[\u914D\u7F6E\u8BFB\u53D6] \u4ECE .nium/.env \u6587\u4EF6\u4E2D\u8BFB\u53D6: USE_LLM_SUMMARY=${o}`),s.useLLMSummary=o.toLowerCase()==="true"}}catch(e){C(`[\u914D\u7F6E\u8BFB\u53D6] \u65E0\u6CD5\u8BFB\u53D6 .nium/.env \u6587\u4EF6: ${e.message}`)}return process.env.USE_LLM_DISCLOSURE!==void 0&&(C(`[\u914D\u7F6E\u8BFB\u53D6] \u4ECE\u73AF\u5883\u53D8\u91CF\u4E2D\u8BFB\u53D6: USE_LLM_DISCLOSURE=${process.env.USE_LLM_DISCLOSURE}`),s.useLLMDisclosure=oc("USE_LLM_DISCLOSURE")),process.env.USE_LLM_SUMMARY!==void 0&&(C(`[\u914D\u7F6E\u8BFB\u53D6] \u4ECE\u73AF\u5883\u53D8\u91CF\u4E2D\u8BFB\u53D6: USE_LLM_SUMMARY=${process.env.USE_LLM_SUMMARY}`),s.useLLMSummary=oc("USE_LLM_SUMMARY")),s}async function Ui(){try{let s=Gg();return F("[\u914D\u7F6E\u8BFB\u53D6] \u4F7F\u7528\u4E3B\u667A\u80FD\u4F53\uFF08\u4E0A\u4E0B\u6587\u9694\u79BB\u6A21\u5F0F\uFF09"),{executeMasterAgent:el,MasterAgent:Ir,config:s}}catch(s){throw ne(`[\u914D\u7F6E\u8BFB\u53D6] \u914D\u7F6E\u8BFB\u53D6\u51FA\u9519: ${s}`),s}}var tl=S(()=>{Vg();Xc();Q();ic()});var uo={};B(uo,{COMMANDS:()=>lo,executeCommand:()=>dn,findCommand:()=>Kg,getAvailableCommands:()=>fn,initializeDynamicCommands:()=>hy,printCommandHelp:()=>nl});import W from"chalk";async function cy(s,e){if(!s){e.warning("\u8BF7\u63D0\u4F9B\u4EFB\u52A1\u8BF7\u6C42\u5185\u5BB9");return}e.log(),e.info("\u5F00\u59CB\u5904\u7406\u4EFB\u52A1..."),e.log();try{let{executeMasterAgent:t,config:n}=await Ui();await t(s,!1,e,n),e.log(),E.sessionId&&(e.log(W.gray(`\u5F53\u524D\u4F1A\u8BDD ID: ${E.sessionId.substring(0,8)}`)),E.tasks&&E.tasks.length>0&&e.log(W.gray(`\u5F53\u524D\u4F1A\u8BDD\u4EFB\u52A1\u6570: ${E.tasks.length}`)),e.log())}catch(t){throw e.error(`\u4EFB\u52A1\u5904\u7406\u5931\u8D25: ${t.message}`),t}}async function ly(s){if(E.messages&&E.messages.length>0&&E.currentTask){s.log(),s.info(`\u6B63\u5728\u6062\u590D\u4F1A\u8BDD [ID:${E.sessionId?E.sessionId.substring(0,8):"unknown"}]...`),s.log();try{let{executeMasterAgent:e,config:t}=await Ui();await e(null,!0,s,t),s.log(),s.success("\u4F1A\u8BDD\u6062\u590D\u5B8C\u6210"),E.sessionId&&(s.log(W.gray(`\u4F1A\u8BDD ID: ${E.sessionId.substring(0,8)}`)),E.tasks&&E.tasks.length>0&&s.log(W.gray(`\u4F1A\u8BDD\u4EFB\u52A1\u6570: ${E.tasks.length}`)),s.log())}catch(e){throw s.error(`\u4F1A\u8BDD\u6062\u590D\u5931\u8D25: ${e.message}`),e}}else s.warning("\u6CA1\u6709\u53EF\u6062\u590D\u7684\u4F1A\u8BDD\u3002\u4F7F\u7528 /chat <\u8BF7\u6C42> \u5F00\u59CB\u65B0\u4EFB\u52A1\u3002")}function uy(s){qt(),s.success("\u4F1A\u8BDD\u5DF2\u5F52\u6863\u5E76\u6E05\u7A7A"),s.log()}function py(s){let e=Ml();s.log(e)}function Jg(s){s.exit()}function gy(s){s.printHelp&&s.printHelp()}function my(s){s.log(),s.log(W.cyan("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")),s.log(W.cyan(" \u{1F4E6} Available Tools ")),s.log(W.cyan("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")),s.log();let e=un(),t=Wc();if(Object.keys(e).length===0){s.warning("No tools loaded yet. Tools will be available after starting a task."),s.log();return}if(s.log(W.bold("\u{1F4CA} Summary:")),s.log(W.gray(` Total Tools: ${t.total}`)),s.log(W.gray(` Local Tools: ${t.local}`)),s.log(W.gray(` MCP Tools: ${t.mcp}`)),s.log(),t.local>0){s.log(W.bold.green("\u{1F527} Local Tools:")),s.log();let{localTools:n}=t;for(let r of n){let o=e[r];if(o&&o.getDefinition){let i=o.getDefinition();s.log(W.green(` \u2022 ${i.name}`)),s.log(W.gray(` ${i.description}`)),s.log()}}}if(t.mcp>0){s.log(W.bold.magenta("\u{1F310} MCP Tools:")),s.log();let{mcpTools:n}=t;for(let r of n){let o=e[r];if(o&&o.getDefinition){let i=o.getDefinition(),a=i.description.match(/\[MCP:([^\]]+)\]/),c=a?a[1]:"unknown",l=i.description.replace(/\[MCP:[^\]]+\]\s*/,"");s.log(W.magenta(` \u2022 ${i.name}`)),s.log(W.gray(` ${l}`)),s.log(W.gray(` (from MCP server: ${c})`)),s.log()}}}s.log(W.cyan("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550")),s.log()}async function dy(s){s.log(),s.info("\u6B63\u5728\u68C0\u67E5git\u53D8\u66F4...");try{if(!Ns()){s.warning("\u6CA1\u6709\u672A\u63D0\u4EA4\u7684\u53D8\u66F4"),s.log();return}let e=Fs(),t=Os();s.log(),s.info("\u5F53\u524Dgit\u72B6\u6001:"),s.log(W.gray(e)),s.log();let n=t.length>500?t.substring(0,500)+`
3364
+ ...(truncated)`:t;s.info("\u53D8\u66F4\u5185\u5BB9\u9884\u89C8:"),s.log(W.gray(n)),s.log(),s.info("\u6B63\u5728\u4F7F\u7528lite\u6A21\u578B\u751F\u6210commit message...");let o=[{role:"system",content:`\u4F60\u662F\u4E00\u4E2A\u4E13\u4E1A\u7684git commit message\u751F\u6210\u52A9\u624B\u3002
1923
3365
  \u8BF7\u6839\u636E\u63D0\u4F9B\u7684git diff\u5185\u5BB9\uFF0C\u751F\u6210\u4E00\u4E2A\u7B80\u6D01\u660E\u4E86\u7684commit message\u3002
1924
3366
 
1925
3367
  \u8981\u6C42\uFF1A
@@ -1936,9 +3378,12 @@ feat: \u6DFB\u52A0\u7528\u6237\u8BA4\u8BC1\u529F\u80FD
1936
3378
  - \u6DFB\u52A0\u767B\u5F55\u548C\u6CE8\u518C\u63A5\u53E3
1937
3379
  - \u66F4\u65B0\u7528\u6237\u6A21\u578B`},{role:"user",content:`\u8BF7\u4E3A\u4EE5\u4E0Bgit\u53D8\u66F4\u751F\u6210commit message:
1938
3380
 
1939
- ${t}`}],i=await ee({messages:s,temperature:.3,useCompression:!0,tools:[]}),a="";if(i.choices&&i.choices.length>0){let{message:l}=i.choices[0];l.content&&(a=l.content.trim())}if(!a){o.error("\u751F\u6210commit message\u5931\u8D25"),o.log();return}o.log();let c=a+`
3381
+ ${t}`}],i=await Z({messages:o,temperature:.3,useCompression:!0,tools:[]}),a="";if(i.choices&&i.choices.length>0){let{message:l}=i.choices[0];l.content&&(a=l.content.trim())}if(!a){s.error("\u751F\u6210commit message\u5931\u8D25"),s.log();return}s.log();let c=a+`
1940
3382
 
1941
- [Generated by niumagents]`;o.success("\u751F\u6210\u7684commit message:"),o.log(A.cyan("\u2500".repeat(50))),o.log(A.white(c)),o.log(A.cyan("\u2500".repeat(50))),o.log(),o.info("\u6B63\u5728\u6267\u884C git add ."),Ws(),o.success("\u5DF2\u6682\u5B58\u6240\u6709\u53D8\u66F4"),o.info("\u6B63\u5728\u6267\u884C git commit..."),Vs(c),o.success("\u63D0\u4EA4\u6210\u529F\uFF01"),o.log()}catch(e){throw o.error(`\u6267\u884Ccommit\u547D\u4EE4\u5931\u8D25: ${e.message}`),o.log(),e}}function Bp(o,e){o.warning(`\u672A\u77E5\u547D\u4EE4: /${e}`);let t=br.map(n=>`/${n.name}`).join(", ");o.log(A.gray(`\u53EF\u7528\u547D\u4EE4: ${t}`))}function El(o){return br.find(e=>e.name===o)||null}async function Oo(o,e,t=""){let n=El(e);if(!n){Bp(o,e);return}if(n.requiresArg&&!t&&e!=="chat"){o.warning(`\u547D\u4EE4 /${e} \u9700\u8981\u53C2\u6570`);return}try{n.requiresArg?await n.handler(t,o):await n.handler(o)}catch(r){throw o.error(`\u6267\u884C\u547D\u4EE4 /${e} \u65F6\u51FA\u9519: ${r.message}`),r}}function Tr(){return[...br]}function bi(o){o.log(A.cyan("\u53EF\u7528\u547D\u4EE4:")),br.forEach(e=>{let t=e.requiresArg?`/${e.name} <\u53C2\u6570>`:`/${e.name}`;o.log(` ${A.white(t)} - ${A.gray(e.description)}`)}),o.log(),o.log(A.gray("\u63D0\u793A: \u76F4\u63A5\u8F93\u5165\u5185\u5BB9\u5C06\u4F5C\u4E3A\u4EFB\u52A1\u8BF7\u6C42\u53D1\u9001")),o.log()}async function qp(){try{let{isGitAvailable:o}=await Promise.resolve().then(()=>(so(),kc)),e=o();console.log(A.gray(`Git\u73AF\u5883\u68C0\u67E5: ${e?"\u53EF\u7528":"\u4E0D\u53EF\u7528"}`)),console.log(e?A.green("\u2713 /commit \u547D\u4EE4\u53EF\u7528"):A.yellow("\u26A0 Git\u4E0D\u53EF\u7528\uFF0C/commit \u547D\u4EE4\u5C06\u4E0D\u53EF\u7528"))}catch(o){console.log(A.gray(`\u521D\u59CB\u5316\u52A8\u6001\u547D\u4EE4\u65F6\u51FA\u9519: ${o.message}`))}}var br,Ti=C(()=>{Ne();Xo();Tl();xr();so();ve();br=[{name:"chat",description:"\u5F00\u59CB\u65B0\u4EFB\u52A1",handler:Up,requiresArg:!0},{name:"resume",description:"\u6062\u590D\u4E2D\u65AD\u7684\u4F1A\u8BDD",handler:Wp,requiresArg:!1},{name:"commit",description:"\u4F7F\u7528AI\u603B\u7ED3\u53D8\u66F4\u5E76\u63D0\u4EA4git commit",handler:Gp,requiresArg:!1},{name:"clear",description:"\u5F52\u6863\u5E76\u6E05\u7A7A\u5F53\u524D\u4F1A\u8BDD",handler:Vp,requiresArg:!1},{name:"history",description:"\u67E5\u770B\u5F52\u6863\u4F1A\u8BDD",handler:zp,requiresArg:!1},{name:"list_tools",description:"\u5217\u51FA\u6240\u6709\u53EF\u7528\u5DE5\u5177",handler:Jp,requiresArg:!1},{name:"exit",description:"\u9000\u51FA\u5E94\u7528",handler:kl,requiresArg:!1},{name:"quit",description:"\u9000\u51FA\u5E94\u7528",handler:kl,requiresArg:!1},{name:"help",description:"\u663E\u793A\u5E2E\u52A9\u4FE1\u606F",handler:Hp,requiresArg:!1}]});je();Ne();Ti();Y();le();di();xr();Eo();import ae from"chalk";import we from"readline";import Kp from"fuzzysort";var $l="0.1.11";var rn=Tr(),jo=class{rl=null;isActive=!1;commandHistory=[];historyIndex=-1;debug=!1;skipLineProcessing=!1;lastExecutedCommand=null;constructor(e={}){this.debug=e.debug||!1,Lr(this.debug),_o(this.debug)}async start(){try{if(!ae)throw new Error("chalk\u6A21\u5757\u5BFC\u5165\u5931\u8D25");Ii(),Ar(),M("\u4EA4\u4E92\u5F0F\u4F1A\u8BDD\u542F\u52A8"),this.debug&&(x("Debug\u6A21\u5F0F\u5DF2\u542F\u7528"),No("Debug\u6A21\u5F0F\u5DF2\u542F\u7528 - \u5C06\u663E\u793A\u8BE6\u7EC6\u65E5\u5FD7\u4FE1\u606F","Session")),await this.initializeMCP();let{initializeDynamicCommands:e}=await Promise.resolve().then(()=>(Ti(),Pl));await e(),this.rl=we.createInterface({input:process.stdin,output:process.stdout,prompt:ae.blue("nium> "),historySize:100,completer:()=>[[],""]}),el(this.rl),process.stdin.isTTY&&(process.stdin.setRawMode(!0),this.setupKeypressHandling()),this.printWelcome(),es()&&b.messages&&b.messages.length>0&&b.currentTask&&this.printSessionWarning(),this.isActive=!0,this.rl.prompt(),this.setupCommandHandler(),this.setupCloseHandler()}catch(e){console.error("\u542F\u52A8\u4F1A\u8BDD\u65F6\u51FA\u9519:",e.message),console.error("\u9519\u8BEF\u5806\u6808:",e.stack),process.exit(1)}}async initializeMCP(){try{let e=ss();if(M(`Loaded ${e.length} MCP server configuration(s)`),e.length===0){x("No MCP servers configured"),await Mo();return}let t=Zt();M("Initializing MCP manager with configured servers..."),await t.initialize(e),M("Loading all tools (local + MCP)..."),await Mo();let n=t.getStatus();x(`MCP Status: ${n.serversConnected} servers connected, ${n.toolsAvailable} tools available`),n.serversConnected>0?_(`Connected to ${n.serversConnected} MCP server(s), ${n.toolsAvailable} tools available`,"MCP"):W(`Configured ${e.length} MCP server(s) but none connected`,"MCP")}catch(e){X(`Failed to initialize MCP: ${e.message}`),x(`MCP initialization error details: ${e.message}
1942
- ${e.stack||""}`),M("Continuing with local tools only..."),await Mo()}}setupKeypressHandling(){we.emitKeypressEvents(process.stdin,this.rl),process.stdin.on("keypress",(e,t)=>{this.isActive&&(this.rl.__isHandlingConfirmation||t&&(t.name==="up"&&this.commandHistory.length>0&&!t.ctrl&&!t.meta?(this.historyIndex===-1?this.historyIndex=this.commandHistory.length-1:this.historyIndex>0&&this.historyIndex--,this.updatePromptWithHistory()):t.name==="down"&&!t.ctrl&&!t.meta?(this.historyIndex>=0&&(this.historyIndex++,this.historyIndex>=this.commandHistory.length&&(this.historyIndex=-1)),this.updatePromptWithHistory()):t.name==="tab"&&this.handleTabCompletion()))})}async handleTabCompletion(){if(!this.rl)return;let e=this.rl.line.trim();if(e.startsWith("/")){let t=e.slice(1),[n]=t.split(" "),r=n?Kp.go(n,rn,{key:"name"}):rn.map(s=>({obj:s,score:0}));if(r.length===1){let s=r[0].obj,i=`/${s.name}${s.requiresArg?" ":""}`;s.requiresArg?(this.skipLineProcessing=!0,this.rl.line=i,this.rl.cursor=i.length,this.rl._refreshLine(),setTimeout(()=>{this.skipLineProcessing=!1},100)):(this.skipLineProcessing=!0,this.rl.line="",this.rl.cursor=0,this.commandHistory.push(i),this.historyIndex=-1,process.nextTick(async()=>{try{this.log(`\u6267\u884C\u547D\u4EE4: /${s.name}`),await s.handler(this)}catch(a){this.error(`\u6267\u884C\u547D\u4EE4 /${s.name} \u65F6\u51FA\u9519: ${a.message}`)}finally{this.isActive&&this.rl&&this.rl.prompt()}}))}else r.length>1&&await this.showCommandSelectionMenu(r)}}async showCommandSelectionMenu(e){if(!this.rl)return;let t=0,n=this.rl.getPrompt(),r=this.rl.line,s=process.stdin.isTTY?process.stdin.isRaw:!1,i=()=>{let a=e.length+3;for(let c=0;c<a;c++)we.moveCursor(process.stdout,0,-1),we.clearLine(process.stdout,0);we.clearLine(process.stdout,1),console.log(""),console.log(ae.yellow("\u8BF7\u9009\u62E9\u547D\u4EE4 (\u4F7F\u7528\u4E0A\u4E0B\u7BAD\u5934\u952E\uFF0CEnter\u786E\u8BA4\uFF0CEsc\u53D6\u6D88):")),console.log(""),e.forEach((c,l)=>{let u=c.obj,p=l===t,g=p?ae.green("> "):" ",d=p?ae.green.bold(`/${u.name}`):ae.white(`/${u.name}`),m=ae.gray(`- ${u.description}`);console.log(`${g}${d} ${m}`)}),process.stdout.write(n),this.rl.line=r,this.rl.cursor=r.length,this.rl._refreshLine()};return new Promise(a=>{process.stdin.isTTY&&process.stdin.setRawMode(!0);let c=(l,u)=>{if(u.name==="up")return t=Math.max(0,t-1),i(),!1;if(u.name==="down")return t=Math.min(e.length-1,t+1),i(),!1;if(u.name==="return"||u.name==="enter"){let p=e[t].obj,g=`/${p.name}${p.requiresArg?" ":""}`;this.rl.removeListener("keypress",c);for(let d=0;d<e.length+4;d++)we.moveCursor(process.stdout,0,-1),we.clearLine(process.stdout,0);return we.clearLine(process.stdout,1),process.stdout.write(n),this.skipLineProcessing=!0,p.requiresArg?(this.skipLineProcessing=!0,this.rl.line=g,this.rl.cursor=g.length,this.rl._refreshLine(),setTimeout(()=>{this.skipLineProcessing=!1},100)):(this.rl.line="",this.rl.cursor=0,this.commandHistory.push(g),this.historyIndex=-1,process.nextTick(async()=>{try{this.log(`\u6267\u884C\u547D\u4EE4: /${p.name}`),await p.handler(this)}catch(d){this.error(`\u6267\u884C\u547D\u4EE4 /${p.name} \u65F6\u51FA\u9519: ${d.message}`)}finally{this.isActive&&this.rl&&this.rl.prompt()}})),a(),!1}else if(u.name==="escape"||u.ctrl&&u.name==="c"){for(let p=0;p<e.length+4;p++)we.moveCursor(process.stdout,0,-1),we.clearLine(process.stdout,0);return this.rl.removeListener("keypress",c),we.clearLine(process.stdout,1),process.stdout.write(n),this.rl.line=r,this.rl.cursor=r.length,this.rl._refreshLine(),a(),!1}};this.rl.on("keypress",c),i()})}updatePromptWithHistory(){this.rl&&(this.historyIndex>=0&&this.historyIndex<this.commandHistory.length?(this.rl.line=this.commandHistory[this.historyIndex],this.rl.cursor=this.rl.line.length,this.rl._refreshLine()):(this.rl.line="",this.rl.cursor=0,this.rl._refreshLine()))}setupCommandHandler(){this.rl&&this.rl.on("line",async e=>{let t=e.trim();if(this.skipLineProcessing){this.skipLineProcessing=!1,this.isActive&&this.rl&&this.rl.prompt();return}if(t.startsWith("/")){let r=t.slice(1).split(" ")[0];if(rn=Tr(),!(r?rn.some(i=>i.name===r):!1)&&r){this.isActive&&this.rl&&this.rl.prompt();return}}t&&(this.commandHistory.push(t),this.historyIndex=-1);try{await this.handleCommand(t),this.lastExecutedCommand=t}catch(n){this.error(`\u5904\u7406\u547D\u4EE4\u65F6\u51FA\u9519: ${n.message}`)}finally{this.isActive&&this.rl&&this.rl.prompt()}})}setupCloseHandler(){this.rl&&this.rl.on("close",()=>{this.isActive&&(this.isActive=!1,this.success("\u518D\u89C1\uFF01"),process.exit(0))})}async handleCommand(e){if(e)if(e.startsWith("/")){let t=e.slice(1).split(" "),n=t[0],r=t.slice(1).join(" ");try{await Oo(this,n,r),n==="clear"&&this.rl&&(this.rl.line="",this.rl.cursor=0,this.rl._refreshLine())}catch(s){this.error(`\u6267\u884C\u4EFB\u52A1\u65F6\u51FA\u9519: ${s.message}`)}}else try{await Oo(this,"chat",e)}catch(t){this.error(`\u6267\u884C\u4EFB\u52A1\u65F6\u51FA\u9519: ${t.message}`)}}printWelcome(){rn=Tr(),this.clear(),this.log(ae.green(`NiumAgents-CLI v${$l}`)),this.log(ae.gray("Options:")),this.log(ae.gray(" --debug - \u542F\u7528\u8C03\u8BD5\u6A21\u5F0F\u4EE5\u663E\u793A\u8BE6\u7EC6\u65E5\u5FD7")),this.log(ae.gray(`
1943
- Commands:`)),this.log(ae.gray(" <request> - \u5F00\u59CB\u65B0\u4EFB\u52A1 (\u9ED8\u8BA4: /chat)"));let e=rn.filter(t=>t.name!=="chat");for(let t of e)t.name==="exit"||t.name==="quit"?t.name==="exit"&&this.log(ae.gray(" /exit \u6216 /quit - \u9000\u51FA")):this.log(ae.gray(` /${t.name} - ${t.description}`));this.log(ae.gray(`
1944
- \u63D0\u793A: \u8F93\u5165 / \u540E\u8DDF\u90E8\u5206\u547D\u4EE4\u53EF\u8FDB\u884C\u6A21\u7CCA\u641C\u7D22`)),this.log()}printSessionWarning(){this.warning("\u26A0 \u68C0\u6D4B\u5230\u4E4B\u524D\u7684\u4F1A\u8BDD\uFF01\u4F7F\u7528 /resume \u7EE7\u7EED\u6216 /clear \u5F00\u59CB\u65B0\u4F1A\u8BDD\u3002"),this.log()}printHelp(){bi(this)}clear(){Uo()}log(e=""){an(e)}success(e){_(e,null)}warning(e){W(e,null)}error(e){ke(e,null)}info(e){se(e,null)}exit(){M("\u4EA4\u4E92\u5F0F\u4F1A\u8BDD\u7ED3\u675F"),this.isActive=!1,this.rl&&this.rl.close()}};import be from"chalk";async function Yp(){try{let o=process.argv.slice(2),e=o.includes("--debug");(o.includes("--help")||o.includes("-h"))&&(console.log(be.green("NiumAgents-CLI v0.1.8")),console.log(be.gray("AI Code Agent")),console.log(),console.log(be.gray("Options:")),console.log(be.gray(" --debug - \u542F\u7528\u8C03\u8BD5\u6A21\u5F0F\u4EE5\u663E\u793A\u8BE6\u7EC6\u65E5\u5FD7")),console.log(be.gray(" --help \u6216 -h - \u663E\u793A\u6B64\u5E2E\u52A9\u4FE1\u606F")),console.log(),console.log(be.gray("Usage:")),console.log(be.gray(" nium [options]")),console.log(be.gray(" npm run start [options]")),console.log(),console.log(be.gray("Example:")),console.log(be.gray(" nium --debug")),console.log(be.gray(" npm run start -- --debug")),process.exit(0)),await new jo({debug:e}).start()}catch(o){console.error("\u542F\u52A8\u5E94\u7528\u65F6\u51FA\u9519:",o.message),process.exit(1)}}Yp();
3383
+ [Generated by niumagents]`;s.success("\u751F\u6210\u7684commit message:"),s.log(W.cyan("\u2500".repeat(50))),s.log(W.white(c)),s.log(W.cyan("\u2500".repeat(50))),s.log(),s.info("\u6B63\u5728\u6267\u884C git add ."),cc(),s.success("\u5DF2\u6682\u5B58\u6240\u6709\u53D8\u66F4"),s.info("\u6B63\u5728\u6267\u884C git commit..."),lc(c),s.success("\u63D0\u4EA4\u6210\u529F\uFF01"),s.log()}catch(e){throw s.error(`\u6267\u884Ccommit\u547D\u4EE4\u5931\u8D25: ${e.message}`),s.log(),e}}function fy(s,e){s.warning(`\u672A\u77E5\u547D\u4EE4: /${e}`);let t=lo.map(n=>`/${n.name}`).join(", ");s.log(W.gray(`\u53EF\u7528\u547D\u4EE4: ${t}`))}function Kg(s){return lo.find(e=>e.name===s)||null}async function dn(s,e,t=""){let n=Kg(e);if(!n){fy(s,e);return}if(n.requiresArg&&!t&&e!=="chat"){s.warning(`\u547D\u4EE4 /${e} \u9700\u8981\u53C2\u6570`);return}try{n.requiresArg?await n.handler(t,s):await n.handler(s)}catch(r){throw s.error(`\u6267\u884C\u547D\u4EE4 /${e} \u65F6\u51FA\u9519: ${r.message}`),r}}function fn(){return[...lo]}function nl(s){s.log(W.cyan("\u53EF\u7528\u547D\u4EE4:")),lo.forEach(e=>{let t=e.requiresArg?`/${e.name} <\u53C2\u6570>`:`/${e.name}`;s.log(` ${W.white(t)} - ${W.gray(e.description)}`)}),s.log(),s.log(W.gray("\u63D0\u793A: \u76F4\u63A5\u8F93\u5165\u5185\u5BB9\u5C06\u4F5C\u4E3A\u4EFB\u52A1\u8BF7\u6C42\u53D1\u9001")),s.log()}async function hy(){try{let{isGitAvailable:s}=await Promise.resolve().then(()=>(ci(),Lp)),e=s();console.log(W.gray(`Git\u73AF\u5883\u68C0\u67E5: ${e?"\u53EF\u7528":"\u4E0D\u53EF\u7528"}`)),console.log(e?W.green("\u2713 /commit \u547D\u4EE4\u53EF\u7528"):W.yellow("\u26A0 Git\u4E0D\u53EF\u7528\uFF0C/commit \u547D\u4EE4\u5C06\u4E0D\u53EF\u7528"))}catch(s){console.log(W.gray(`\u521D\u59CB\u5316\u52A8\u6001\u547D\u4EE4\u65F6\u51FA\u9519: ${s.message}`))}}var lo,hn=S(()=>{ct();la();tl();pn();ci();Ie();lo=[{name:"chat",description:"\u5F00\u59CB\u65B0\u4EFB\u52A1",handler:cy,requiresArg:!0},{name:"resume",description:"\u6062\u590D\u4E2D\u65AD\u7684\u4F1A\u8BDD",handler:ly,requiresArg:!1},{name:"commit",description:"\u4F7F\u7528AI\u603B\u7ED3\u53D8\u66F4\u5E76\u63D0\u4EA4git commit",handler:dy,requiresArg:!1},{name:"clear",description:"\u5F52\u6863\u5E76\u6E05\u7A7A\u5F53\u524D\u4F1A\u8BDD",handler:uy,requiresArg:!1},{name:"history",description:"\u67E5\u770B\u5F52\u6863\u4F1A\u8BDD",handler:py,requiresArg:!1},{name:"list_tools",description:"\u5217\u51FA\u6240\u6709\u53EF\u7528\u5DE5\u5177",handler:my,requiresArg:!1},{name:"exit",description:"\u9000\u51FA\u5E94\u7528",handler:Jg,requiresArg:!1},{name:"quit",description:"\u9000\u51FA\u5E94\u7528",handler:Jg,requiresArg:!1},{name:"help",description:"\u663E\u793A\u5E2E\u52A9\u4FE1\u606F",handler:gy,requiresArg:!1}]});Ye();ct();hn();Q();ae();io();pn();Ii();import ke from"chalk";import qe from"readline";import yy from"fuzzysort";var po="0.1.13";var Mr=fn(),Wi=class{rl=null;isActive=!1;commandHistory=[];historyIndex=-1;debug=!1;skipLineProcessing=!1;lastExecutedCommand=null;constructor(e={}){this.debug=e.debug||!1,In(this.debug),Lr(this.debug)}async start(){try{if(!ke)throw new Error("chalk\u6A21\u5757\u5BFC\u5165\u5931\u8D25");Nr(),$n(),F("\u4EA4\u4E92\u5F0F\u4F1A\u8BDD\u542F\u52A8"),this.debug&&(C("Debug\u6A21\u5F0F\u5DF2\u542F\u7528"),it("Debug\u6A21\u5F0F\u5DF2\u542F\u7528 - \u5C06\u663E\u793A\u8BE6\u7EC6\u65E5\u5FD7\u4FE1\u606F","Session")),await this.initializeMCP();let{initializeDynamicCommands:e}=await Promise.resolve().then(()=>(hn(),uo));await e(),this.rl=qe.createInterface({input:process.stdin,output:process.stdout,prompt:ke.blue("nium> "),historySize:100,completer:()=>[[],""]}),ag(this.rl),process.stdin.isTTY&&(process.stdin.setRawMode(!0),this.setupKeypressHandling()),this.printWelcome(),Vr()&&E.messages&&E.messages.length>0&&E.currentTask&&this.printSessionWarning(),this.isActive=!0,this.rl.prompt(),this.setupCommandHandler(),this.setupCloseHandler()}catch(e){console.error("\u542F\u52A8\u4F1A\u8BDD\u65F6\u51FA\u9519:",e.message),console.error("\u9519\u8BEF\u5806\u6808:",e.stack),process.exit(1)}}async initializeMCP(){try{let e=qr();if(F(`Loaded ${e.length} MCP server configuration(s)`),e.length===0){C("No MCP servers configured"),await tt();return}let t=et();F("Initializing MCP manager with configured servers..."),await t.initialize(e),F("Loading all tools (local + MCP)..."),await tt();let n=t.getStatus();C(`MCP Status: ${n.serversConnected} servers connected, ${n.toolsAvailable} tools available`),n.serversConnected>0?X(`Connected to ${n.serversConnected} MCP server(s), ${n.toolsAvailable} tools available`,"MCP"):J(`Configured ${e.length} MCP server(s) but none connected`,"MCP")}catch(e){ne(`Failed to initialize MCP: ${e.message}`),C(`MCP initialization error details: ${e.message}
3384
+ ${e.stack||""}`),F("Continuing with local tools only..."),await tt()}}setupKeypressHandling(){qe.emitKeypressEvents(process.stdin,this.rl),process.stdin.on("keypress",(e,t)=>{this.isActive&&(this.rl.__isHandlingConfirmation||t&&(t.name==="up"&&this.commandHistory.length>0&&!t.ctrl&&!t.meta?(this.historyIndex===-1?this.historyIndex=this.commandHistory.length-1:this.historyIndex>0&&this.historyIndex--,this.updatePromptWithHistory()):t.name==="down"&&!t.ctrl&&!t.meta?(this.historyIndex>=0&&(this.historyIndex++,this.historyIndex>=this.commandHistory.length&&(this.historyIndex=-1)),this.updatePromptWithHistory()):t.name==="tab"&&this.handleTabCompletion()))})}async handleTabCompletion(){if(!this.rl)return;let e=this.rl.line.trim();if(e.startsWith("/")){let t=e.slice(1),[n]=t.split(" "),r=n?yy.go(n,Mr,{key:"name"}):Mr.map(o=>({obj:o,score:0}));if(r.length===1){let o=r[0].obj,i=`/${o.name}${o.requiresArg?" ":""}`;o.requiresArg?(this.skipLineProcessing=!0,this.rl.line=i,this.rl.cursor=i.length,this.rl._refreshLine(),setTimeout(()=>{this.skipLineProcessing=!1},100)):(this.skipLineProcessing=!0,this.rl.line="",this.rl.cursor=0,this.commandHistory.push(i),this.historyIndex=-1,process.nextTick(async()=>{try{this.log(`\u6267\u884C\u547D\u4EE4: /${o.name}`),await o.handler(this)}catch(a){this.error(`\u6267\u884C\u547D\u4EE4 /${o.name} \u65F6\u51FA\u9519: ${a.message}`)}finally{this.isActive&&this.rl&&this.rl.prompt()}}))}else r.length>1&&await this.showCommandSelectionMenu(r)}}async showCommandSelectionMenu(e){if(!this.rl)return;let t=0,n=this.rl.getPrompt(),r=this.rl.line,o=process.stdin.isTTY?process.stdin.isRaw:!1,i=()=>{let a=e.length+3;for(let c=0;c<a;c++)qe.moveCursor(process.stdout,0,-1),qe.clearLine(process.stdout,0);qe.clearLine(process.stdout,1),console.log(""),console.log(ke.yellow("\u8BF7\u9009\u62E9\u547D\u4EE4 (\u4F7F\u7528\u4E0A\u4E0B\u7BAD\u5934\u952E\uFF0CEnter\u786E\u8BA4\uFF0CEsc\u53D6\u6D88):")),console.log(""),e.forEach((c,l)=>{let u=c.obj,p=l===t,g=p?ke.green("> "):" ",m=p?ke.green.bold(`/${u.name}`):ke.white(`/${u.name}`),d=ke.gray(`- ${u.description}`);console.log(`${g}${m} ${d}`)}),process.stdout.write(n),this.rl.line=r,this.rl.cursor=r.length,this.rl._refreshLine()};return new Promise(a=>{process.stdin.isTTY&&process.stdin.setRawMode(!0);let c=(l,u)=>{if(u.name==="up")return t=Math.max(0,t-1),i(),!1;if(u.name==="down")return t=Math.min(e.length-1,t+1),i(),!1;if(u.name==="return"||u.name==="enter"){let p=e[t].obj,g=`/${p.name}${p.requiresArg?" ":""}`;this.rl.removeListener("keypress",c);for(let m=0;m<e.length+4;m++)qe.moveCursor(process.stdout,0,-1),qe.clearLine(process.stdout,0);return qe.clearLine(process.stdout,1),process.stdout.write(n),this.skipLineProcessing=!0,p.requiresArg?(this.skipLineProcessing=!0,this.rl.line=g,this.rl.cursor=g.length,this.rl._refreshLine(),setTimeout(()=>{this.skipLineProcessing=!1},100)):(this.rl.line="",this.rl.cursor=0,this.commandHistory.push(g),this.historyIndex=-1,process.nextTick(async()=>{try{this.log(`\u6267\u884C\u547D\u4EE4: /${p.name}`),await p.handler(this)}catch(m){this.error(`\u6267\u884C\u547D\u4EE4 /${p.name} \u65F6\u51FA\u9519: ${m.message}`)}finally{this.isActive&&this.rl&&this.rl.prompt()}})),a(),!1}else if(u.name==="escape"||u.ctrl&&u.name==="c"){for(let p=0;p<e.length+4;p++)qe.moveCursor(process.stdout,0,-1),qe.clearLine(process.stdout,0);return this.rl.removeListener("keypress",c),qe.clearLine(process.stdout,1),process.stdout.write(n),this.rl.line=r,this.rl.cursor=r.length,this.rl._refreshLine(),a(),!1}};this.rl.on("keypress",c),i()})}updatePromptWithHistory(){this.rl&&(this.historyIndex>=0&&this.historyIndex<this.commandHistory.length?(this.rl.line=this.commandHistory[this.historyIndex],this.rl.cursor=this.rl.line.length,this.rl._refreshLine()):(this.rl.line="",this.rl.cursor=0,this.rl._refreshLine()))}setupCommandHandler(){this.rl&&this.rl.on("line",async e=>{let t=e.trim();if(this.skipLineProcessing){this.skipLineProcessing=!1,this.isActive&&this.rl&&this.rl.prompt();return}if(t.startsWith("/")){let r=t.slice(1).split(" ")[0];if(Mr=fn(),!(r?Mr.some(i=>i.name===r):!1)&&r){this.isActive&&this.rl&&this.rl.prompt();return}}t&&(this.commandHistory.push(t),this.historyIndex=-1);try{await this.handleCommand(t),this.lastExecutedCommand=t}catch(n){this.error(`\u5904\u7406\u547D\u4EE4\u65F6\u51FA\u9519: ${n.message}`)}finally{this.isActive&&this.rl&&this.rl.prompt()}})}setupCloseHandler(){this.rl&&this.rl.on("close",()=>{this.isActive&&(this.isActive=!1,this.success("\u518D\u89C1\uFF01"),process.exit(0))})}async handleCommand(e){if(e)if(e.startsWith("/")){let t=e.slice(1).split(" "),n=t[0],r=t.slice(1).join(" ");try{await dn(this,n,r),n==="clear"&&this.rl&&(this.rl.line="",this.rl.cursor=0,this.rl._refreshLine())}catch(o){this.error(`\u6267\u884C\u4EFB\u52A1\u65F6\u51FA\u9519: ${o.message}`)}}else try{await dn(this,"chat",e)}catch(t){this.error(`\u6267\u884C\u4EFB\u52A1\u65F6\u51FA\u9519: ${t.message}`)}}printWelcome(){Mr=fn(),this.clear(),this.log(ke.green(`NiumAgents-CLI v${po}`)),this.log(ke.gray("Options:")),this.log(ke.gray(" --debug - \u542F\u7528\u8C03\u8BD5\u6A21\u5F0F\u4EE5\u663E\u793A\u8BE6\u7EC6\u65E5\u5FD7")),this.log(ke.gray(`
3385
+ Commands:`)),this.log(ke.gray(" <request> - \u5F00\u59CB\u65B0\u4EFB\u52A1 (\u9ED8\u8BA4: /chat)"));let e=Mr.filter(t=>t.name!=="chat");for(let t of e)t.name==="exit"||t.name==="quit"?t.name==="exit"&&this.log(ke.gray(" /exit \u6216 /quit - \u9000\u51FA")):this.log(ke.gray(` /${t.name} - ${t.description}`));this.log(ke.gray(`
3386
+ \u63D0\u793A: \u8F93\u5165 / \u540E\u8DDF\u90E8\u5206\u547D\u4EE4\u53EF\u8FDB\u884C\u6A21\u7CCA\u641C\u7D22`)),this.log()}printSessionWarning(){this.warning("\u26A0 \u68C0\u6D4B\u5230\u4E4B\u524D\u7684\u4F1A\u8BDD\uFF01\u4F7F\u7528 /resume \u7EE7\u7EED\u6216 /clear \u5F00\u59CB\u65B0\u4F1A\u8BDD\u3002"),this.log()}printHelp(){nl(this)}clear(){Yi()}log(e=""){Dr(e)}success(e){X(e,null)}warning(e){J(e,null)}error(e){xe(e,null)}info(e){ve(e,null)}exit(){F("\u4EA4\u4E92\u5F0F\u4F1A\u8BDD\u7ED3\u675F"),this.isActive=!1,this.rl&&this.rl.close()}};import ex from"react";import{render as tx}from"ink";import{useState as Ke,useEffect as qy,useCallback as mm}from"react";import{Box as dm,useApp as Jy,useInput as Ky}from"ink";import{EventEmitter as Yy}from"events";import{Box as xn,Text as Je}from"ink";var yn=class{static formatMCPStatus(e){let{serversConnected:t,totalServers:n,toolsAvailable:r,servers:o}=e;if(n===0)return"\u{1F50C} \u672A\u914D\u7F6EMCP\u670D\u52A1\u5668";if(t===n)return`\u{1F7E2} ${t}/${n} MCP\u670D\u52A1\u5668 | ${r}\u4E2A\u5DE5\u5177`;if(t>0){let i=o.filter(l=>!l.connected).map(l=>l.name).slice(0,2).join(", "),a=o.filter(l=>!l.connected).length-2,c=a>0?` \u7B49${a}\u4E2A`:"";return`\u{1F7E1} ${t}/${n} MCP\u670D\u52A1\u5668 | ${r}\u4E2A\u5DE5\u5177 | \u79BB\u7EBF: ${i}${c}`}return`\u{1F534} ${t}/${n} MCP\u670D\u52A1\u5668\u79BB\u7EBF | \u4F7F\u7528 /mcp-status \u67E5\u770B`}static formatSessionStatus(e){let{status:t,sessionId:n,messageCount:r,taskCount:o,currentTask:i}=e;switch(t){case"inactive":return"\u{1F4A4} \u65E0\u6D3B\u52A8\u4F1A\u8BDD";case"pending":return"\u23F3 \u6709\u672A\u5B8C\u6210\u7684\u4F1A\u8BDD\uFF0C\u4F7F\u7528 /resume \u7EE7\u7EED";case"active":let a=["\u{1F680} \u4F1A\u8BDD\u8FDB\u884C\u4E2D"];return r&&r>0&&a.push(`${r}\u6761\u6D88\u606F`),i&&a.push(`\u5F53\u524D: ${i}`),a.join(" | ");case"ready":return"\u2705 \u4F1A\u8BDD\u5C31\u7EEA";default:return"\u2753 \u72B6\u6001\u672A\u77E5"}}static formatMCPStatusShort(e){let{serversConnected:t,totalServers:n}=e;return n===0?"MCP:\u672A\u914D\u7F6E":t===n?`MCP:\u2713${t}`:t>0?`MCP:${t}/${n}`:`MCP:\u2717${n}`}static formatSessionStatusShort(e){let{status:t}=e;switch(t){case"inactive":return"\u4F1A\u8BDD:\u65E0";case"pending":return"\u4F1A\u8BDD:\u5F85\u7EED";case"active":return"\u4F1A\u8BDD:\u8FDB\u884C\u4E2D";case"ready":return"\u4F1A\u8BDD:\u5C31\u7EEA";default:return"\u4F1A\u8BDD:\u672A\u77E5"}}static getMCPStatusColor(e){let{serversConnected:t,totalServers:n}=e;return n===0?"cyan":t===n?"green":t>0?"yellow":"red"}static getSessionStatusColor(e){let{status:t}=e;switch(t){case"inactive":return"cyan";case"pending":return"yellow";case"active":return"green";case"ready":return"magenta";default:return"red"}}static formatFocusStatus(e){return e==="input"?"\u{1F4DD} \u8F93\u5165\u6A21\u5F0F | Ctrl+L \u5207\u6362\u5230\u6D4F\u89C8":"\u{1F441}\uFE0F \u6D4F\u89C8\u6A21\u5F0F | Ctrl+L \u5207\u6362\u5230\u8F93\u5165"}static getFocusIcon(e){return e==="input"?"\u{1F4DD}":"\u{1F441}\uFE0F"}static formatLoadingState(e,t){return e?`\u23F3 ${t||"\u5904\u7406\u4E2D..."}`:""}static formatVersion(e,t=!1){return t?`v${e} (DEBUG)`:`v${e}`}};var A={primary:"blue",success:"green",warning:"yellow",info:"cyan",error:"red",text:"white",textDim:"gray",border:"gray"},rl={default:"single",rounded:"round"},sl={input:A.success,content:A.warning},Yg={active:A.success,inactive:A.textDim,pending:A.warning,error:A.error,ready:A.info},Re={getFocusColor(s){return sl[s]},getFocusBorderColor(s,e){return e?sl[s]:A.border},getStatusColor(s){return Yg[s]},getBorderStyle(s=!1){return s?rl.rounded:rl.default}},go={askUser:"\u{1F4AC}",directory:"\u{1F4C1}",success:"\u2705",warning:"\u26A0\uFE0F",error:"\u274C",info:"\u2139\uFE0F"},ht={line(s=60){return"\u2500".repeat(s)},boldLine(s=60){return"\u2501".repeat(s)}},se={colors:A,borderStyles:rl,focusColors:sl,statusColors:Yg,icons:go,separators:ht};import{Fragment as Sy,jsx as yt,jsxs as nt}from"react/jsx-runtime";var xy=({version:s,sessionStatus:e,mcpStatus:t,debug:n,focusedArea:r="input",cwd:o,isLoading:i=!1})=>{let a=Re.getFocusColor(r),c=Re.getFocusBorderColor(r,!0),l=r==="content"?"\u6D4F\u89C8\u6A21\u5F0F":"\u8F93\u5165\u6A21\u5F0F",u=yn.getMCPStatusColor(t),p=yn.getSessionStatusColor(e),g=r==="content"?"\u2191\u2193\u6D4F\u89C8 | PgUp/PgDn\u7FFB\u9875 | Esc\u8FD4\u56DE":"Ctrl+L\u6D4F\u89C8\u6A21\u5F0F";return nt(xn,{flexDirection:"column",borderStyle:Re.getBorderStyle(!0),borderColor:c,paddingX:1,children:[nt(xn,{flexDirection:"row",justifyContent:"space-between",children:[nt(xn,{children:[nt(Je,{bold:!0,color:A.primary,children:["Nium v",s]}),n&&yt(Je,{color:A.warning,children:" [DEBUG]"}),i&&yt(Je,{color:A.success,children:" \u5904\u7406\u4E2D..."})]}),nt(xn,{children:[yt(Je,{dimColor:!0,children:"\u4F1A\u8BDD: "}),yt(Je,{color:p,children:yn.formatSessionStatusShort(e)}),yt(Je,{dimColor:!0,children:" | MCP: "}),yt(Je,{color:u,children:yn.formatMCPStatusShort(t)})]})]}),nt(xn,{flexDirection:"row",justifyContent:"space-between",marginTop:1,children:[nt(xn,{children:[yt(Je,{color:a,bold:!0,children:l}),nt(Je,{dimColor:!0,color:A.textDim,children:[" \xB7 ",g]})]}),yt(xn,{children:o&&nt(Sy,{children:[nt(Je,{dimColor:!0,children:[go.directory," "]}),yt(Je,{color:A.info,children:o})]})})]})]})},Xg=xy;import{useEffect as Hi,useState as zi,useRef as Vi,useMemo as Gi}from"react";import{Box as Sn,Text as Ut,useInput as Ey}from"ink";import $y from"ink-spinner";import{createContext as Cy,useContext as wy,useState as by}from"react";import{jsx as vy}from"react/jsx-runtime";var Qg=Cy(void 0),Ar=()=>{let s=wy(Qg);if(!s)throw new Error("useFocus must be used within FocusProvider");return s},Zg=({children:s})=>{let[e,t]=by("input"),n=r=>{t(r)};return vy(Qg.Provider,{value:{focusedArea:e,setFocus:n},children:s})};function Bi(){return process.stdout.columns||80}function nm(s,e){let t=e||Bi()-4;if(!s||s.length===0)return[""];let n=s.split(`
3387
+ `),r=[];for(let o of n){if(mo(o)<=t){r.push(o);continue}let i=Ty(o,t);r.push(...i)}return r}function Ty(s,e){let t=[],n="",r=0;if(/\u001b\[\d+m/.test(s)){let i=ky(s);for(let a of i){let c=mo(a.text);if(r+c<=e)n+=a.raw,r+=c;else if(n&&t.push(n),c>e){let l=em(a.text,e);for(let u=0;u<l.length;u++)u===l.length-1?(n=tm(l[u],a.ansiPrefix),r=mo(l[u])):t.push(tm(l[u],a.ansiPrefix))}else n=a.raw,r=c}n&&t.push(n)}else{let i=s.split(" ");for(let a of i){let c=mo(a),l=n?1:0;if(r+c+l<=e)n+=(n?" ":"")+a,r+=c+l;else if(n&&t.push(n),c>e){let u=em(a,e);t.push(...u.slice(0,-1)),n=u[u.length-1],r=mo(n)}else n=a,r=c}n&&t.push(n)}return t.length>0?t:[""]}function em(s,e){let t=[],n="",r=0;for(let o of s){let i=rm(o);r+i<=e?(n+=o,r+=i):(n&&t.push(n),n=o,r=i)}return n&&t.push(n),t}function mo(s){let e=Py(s),t=0;for(let n of e)t+=rm(n);return t}function rm(s){let e=s.charCodeAt(0);return e>=19968&&e<=40959||e>=13312&&e<=19903||e>=44032&&e<=55215||e>=65280&&e<=65519?2:1}function Py(s){return s.replace(/\u001b\[\d+m/g,"")}function ky(s){let e=[],t=/\u001b\[\d+m/g,n=0,r="",o;for(;(o=t.exec(s))!==null;){if(o.index>n){let i=s.slice(n,o.index);e.push({raw:r+i,text:i,ansiPrefix:r})}r=o[0],n=o.index+o[0].length}if(n<s.length){let i=s.slice(n);e.push({raw:r+i,text:i,ansiPrefix:r})}return e}function tm(s,e){return e?e+s+"\x1B[0m":s}import{jsx as xt,jsxs as Cn}from"react/jsx-runtime";var Iy=({output:s,isLoading:e})=>{let{focusedArea:t}=Ar(),[n,r]=zi(0),o=Vi(!0),[i,a]=zi(!1),[c,l]=zi(0),u=Vi(process.stdout.rows||24),p=Vi(null),[g,m]=zi(Bi()),d=Vi(new Map),f=Gi(()=>Math.max(1,u.current-11),[u.current]),y=Gi(()=>{let h=Math.max(40,g-6),x=[];for(let P of s){let k=`${P}-${h}`,b=d.current.get(k);b||(b=nm(P,h),d.current.set(k,b)),x.push(...b)}return x},[s,g]);Hi(()=>{let h=setInterval(()=>{d.current.size>1e3&&d.current.clear()},6e4);return()=>clearInterval(h)},[]);let w=Gi(()=>Math.max(0,y.length-f),[y.length,f]),T=Gi(()=>y.slice(n,n+f).map((h,x)=>({id:`line-${n+x}`,content:h})),[y,n,f]);return Hi(()=>{let h=()=>{let x=u.current;u.current=process.stdout.rows||24,m(Bi());let P=u.current-x;if(Math.abs(P)>0)if(o.current||n>=w-1){let k=Math.max(0,y.length-(u.current-11));r(k),o.current=!0}else{let k=n/Math.max(1,w),b=Math.max(0,y.length-(u.current-11)),U=Math.floor(k*b);r(Math.max(0,Math.min(U,b)))}};return process.stdout.on("resize",h),()=>{process.stdout.off("resize",h)}},[s.length,n,w]),Hi(()=>{if(o.current&&!i){let h=Math.max(0,y.length-f);r(h)}},[y.length,f,i]),Hi(()=>(i&&(p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{a(!1),l(0)},300)),()=>{p.current&&clearTimeout(p.current)}),[i]),Ey((h,x)=>{if(t!=="content"||y.length<=f)return;let P=n,k=1;if((x.ctrl||x.meta)&&(k=x.upArrow||x.downArrow?5:k),x.upArrow?(P=Math.max(0,n-k),o.current=!1):x.downArrow&&(P=Math.min(w,n+k),P===w?o.current=!0:o.current=!1),x.pageUp?(P=Math.max(0,n-Math.floor(f*.9)),o.current=!1):x.pageDown&&(P=Math.min(w,n+Math.floor(f*.9)),P===w?o.current=!0:o.current=!1),typeof x=="object"&&x!==null){let b=x;b.home?(P=0,o.current=!1):b.end&&(P=w,o.current=!0)}P!==n&&(r(P),a(!0),p.current&&clearTimeout(p.current))}),Cn(Sn,{flexDirection:"column",overflow:"hidden",borderStyle:Re.getBorderStyle(),borderColor:Re.getFocusBorderColor(t,t==="content"),paddingX:1,children:[t==="content"&&y.length>0&&Cn(Sn,{flexDirection:"row",justifyContent:"space-between",marginBottom:1,children:[xt(Ut,{color:A.warning,bold:!0,children:"\u6D4F\u89C8\u6A21\u5F0F"}),Cn(Ut,{dimColor:!0,color:A.textDim,children:[n+1,"-",Math.min(n+f,y.length),"/",y.length," \u884C"]})]}),Cn(Sn,{flexDirection:"column",paddingY:0,height:f,overflow:"hidden",children:[s.length===0&&!e&&Cn(Sn,{flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",children:[xt(Ut,{dimColor:!0,color:A.textDim,children:"\u7B49\u5F85\u547D\u4EE4\u8F93\u5165..."}),xt(Ut,{dimColor:!0,color:A.textDim,children:"\u8F93\u5165\u4EFB\u52A1\u63CF\u8FF0\u6216 /help \u5F00\u59CB\u4F7F\u7528"})]}),y.length>0&&T.map(h=>xt(Sn,{width:"100%",flexWrap:"wrap",children:xt(Ut,{wrap:"wrap",children:h.content})},h.id)),e&&Cn(Sn,{flexDirection:"row",alignItems:"center",children:[xt(Ut,{color:A.success,children:xt($y,{type:"dots"})}),xt(Ut,{color:A.success,children:" \u6B63\u5728\u5904\u7406..."})]})]}),t==="content"&&y.length>f&&xt(Sn,{marginTop:1,children:Cn(Ut,{dimColor:!0,color:A.textDim,children:[n===0&&"\u25BC \u9876\u90E8",n>0&&n<w&&"\u25B2\u25BC \u6EDA\u52A8\u4E2D",n===w&&"\u25B2 \u5E95\u90E8"," \xB7 ",Math.round(n/Math.max(1,w)*100),"%"]})})]})},sm=Iy;import{useState as Wt,useEffect as om}from"react";import{Box as Le,Text as pe,useInput as My}from"ink";import Ay from"ink-text-input";import Ry from"fuzzysort";import{jsx as fe,jsxs as be}from"react/jsx-runtime";var Ly=({commands:s,onCommandSubmit:e,isDisabled:t=!1,askUserRequest:n=null,onAskUserResponse:r})=>{let{focusedArea:o}=Ar(),[i,a]=Wt(""),[c,l]=Wt(!1),[u,p]=Wt([]),[g,m]=Wt(0),[d,f]=Wt(0),[y,w]=Wt([]),[T,h]=Wt(-1),x=5,[P,k]=Wt(0),b=()=>{if(n&&r){if(n.choices&&n.choices.length>0){let M=n.choices[P];r(M)}else{let M=i.trim();M&&r(M)}a(""),k(0);return}let L=i.trim();L&&!t&&(w(M=>[...M,L]),h(-1),e(L),a(""),l(!1),m(0),f(0))},U=()=>{if(u.length>0&&c){let L=u[g],M=`/${L.name}${L.requiresArg?" ":""}`;l(!1),m(0),f(0),L.requiresArg?a(M):e(M)}};om(()=>{if(i.startsWith("/")){let L=i.slice(1).split(" ")[0];if(L){let $=Ry.go(L,s,{key:"name"}).map(I=>I.obj);p($),l($.length>0),m(0),f(0)}else p(s),l(!0),m(0),f(0)}else l(!1)},[i,s]),om(()=>{g<d?f(g):g>=d+x&&f(g-x+1)},[g,d,x]),My((L,M)=>{if(!(o!=="input"||t))if(M.return)b();else if(M.tab)n||U();else if(M.upArrow){if(n&&n.choices&&n.choices.length>0)k($=>Math.max(0,$-1));else if(c)m($=>Math.max(0,$-1));else if(y.length>0){let $=T===-1?y.length-1:Math.max(0,T-1);h($),a(y[$])}}else if(M.downArrow){if(n&&n.choices&&n.choices.length>0)k($=>Math.min(n.choices.length-1,$+1));else if(c)m($=>Math.min(u.length-1,$+1));else if(T>=0){let $=T+1;$>=y.length?(h(-1),a("")):(h($),a(y[$]))}}else M.escape&&(n&&r?(r("__CANCELLED__"),a(""),k(0)):(l(!1),m(0),f(0)))});let j=u.slice(d,d+x);return be(Le,{flexDirection:"column",children:[n&&be(Le,{flexDirection:"column",borderStyle:Re.getBorderStyle(!0),borderColor:A.info,paddingX:1,marginBottom:1,height:10,overflow:"hidden",children:[be(pe,{bold:!0,color:A.info,children:[go.askUser," ",n.question]}),fe(pe,{dimColor:!0,color:A.textDim,children:ht.line(40)}),n.choices&&n.choices.length>0?be(Le,{flexDirection:"column",height:6,overflow:"hidden",children:[fe(pe,{dimColor:!0,color:A.textDim,children:"(\u2191\u2193\u9009\u62E9 | Enter\u786E\u8BA4 | Esc\u53D6\u6D88)"}),n.choices.slice(0,5).map((L,M)=>be(pe,{color:M===P?A.success:A.text,bold:M===P,children:[M===P?"> ":" ",L]},`ask-choice-${n.requestId}-${M}`)),n.allowFreeText&&fe(pe,{dimColor:!0,color:A.textDim,children:"\u6216\u76F4\u63A5\u8F93\u5165\u81EA\u5B9A\u4E49\u7B54\u6848"})]}):fe(pe,{dimColor:!0,color:A.textDim,children:"(\u8F93\u5165\u7B54\u6848\u540E\u6309Enter | Esc\u53D6\u6D88)"})]}),!n&&c&&u.length>0&&be(Le,{flexDirection:"column",borderStyle:Re.getBorderStyle(),borderColor:A.warning,paddingX:1,marginBottom:1,children:[be(Le,{flexDirection:"row",justifyContent:"space-between",marginBottom:1,children:[fe(pe,{color:A.warning,children:"\u547D\u4EE4\u5EFA\u8BAE"}),fe(pe,{dimColor:!0,color:A.textDim,children:"(Tab\u8865\u5168 | Esc\u53D6\u6D88)"})]}),Array.from({length:Math.min(x,7)}).map((L,M)=>{let $=d+M,I=u[$];if(I){let O=$===g;return be(Le,{flexDirection:"row",justifyContent:"space-between",children:[be(Le,{children:[be(pe,{color:O?A.success:A.text,bold:O,children:[O?"> ":" ",be(pe,{color:O?A.success:A.info,children:["/",I.name]})]}),I.requiresArg&&fe(pe,{dimColor:!0,color:A.textDim,children:" <\u53C2\u6570>"})]}),I.description&&fe(pe,{dimColor:!0,color:A.textDim,children:I.description})]},I.name)}return null}),u.length>Math.min(x,7)&&fe(Le,{flexDirection:"row",justifyContent:"center",marginTop:1,children:be(pe,{dimColor:!0,color:A.textDim,children:[d>0&&"\u25C0 ",d+1,"-",Math.min(d+Math.min(x,7),u.length)," / ",u.length,d+Math.min(x,7)<u.length&&" \u25B6"]})})]}),be(Le,{borderStyle:Re.getBorderStyle(),borderColor:n?A.info:Re.getFocusBorderColor(o,o==="input"),paddingX:1,children:[be(Le,{flexDirection:"row",justifyContent:"space-between",marginBottom:o==="input"?0:-1,children:[be(Le,{children:[fe(pe,{color:n?A.info:A.primary,bold:!0,children:n?"\u56DE\u7B54> ":"nium> "}),o!=="input"&&!t&&fe(pe,{dimColor:!0,color:A.textDim,children:" (Ctrl+L\u6FC0\u6D3B\u8F93\u5165)"})]}),be(Le,{children:[n&&fe(pe,{color:A.info,bold:!0,children:"\u4EA4\u4E92\u6A21\u5F0F"}),o==="input"&&!n&&fe(pe,{color:A.success,bold:!0,children:"\u8F93\u5165\u6A21\u5F0F"}),o==="content"&&!n&&fe(pe,{dimColor:!0,color:A.textDim,children:"\u6D4F\u89C8\u6A21\u5F0F"})]})]}),fe(Le,{marginLeft:n?2:5,children:fe(Ay,{value:i,onChange:a,onSubmit:b,placeholder:n?"\u8F93\u5165\u60A8\u7684\u56DE\u7B54...":"\u8F93\u5165\u547D\u4EE4\u6216\u76F4\u63A5\u63CF\u8FF0\u4EFB\u52A1...",showCursor:!t&&o==="input",focus:o==="input"&&!t})}),o==="input"&&!n&&fe(Le,{marginTop:-1,children:fe(pe,{dimColor:!0,color:A.textDim,children:"\u76F4\u63A5\u8F93\u5165\u4EFB\u52A1\u63CF\u8FF0\u5F00\u59CB\u5BF9\u8BDD | \u8F93\u5165 / \u67E5\u770B\u547D\u4EE4"})})]})]})},im=Ly;import{useState as jy,useEffect as Dy,useRef as Fy}from"react";import{Box as am,Text as wn,useInput as Oy}from"ink";import{jsx as bn,jsxs as cm}from"react/jsx-runtime";var Ny=({commands:s,onClose:e})=>{let t=s.filter(p=>["help","clear","resume","history","exit"].includes(p.name)),n=s.filter(p=>!["help","clear","resume","history","exit"].includes(p.name)),[r,o]=jy(0),i=Fy(process.stdout.rows||24),a=i.current-8,c=["",ht.boldLine(60),"NiumAgents-CLI \u547D\u4EE4\u5E2E\u52A9","(\u6309\u4EFB\u610F\u952E\u8FD4\u56DE | \u2191\u2193\u6EDA\u52A8)",ht.boldLine(60),"","\u5FEB\u6377\u952E:"," Ctrl+L - \u5207\u6362\u8F93\u5165/\u6D4F\u89C8\u6A21\u5F0F"," Esc - \u8FD4\u56DE\u8F93\u5165\u6A21\u5F0F"," Tab - \u547D\u4EE4\u81EA\u52A8\u8865\u5168"," \u2191\u2193 - \u6D4F\u89C8\u5386\u53F2/\u6EDA\u52A8\u5185\u5BB9","",ht.line(60),"","\u5E38\u7528\u547D\u4EE4:",...t.map(p=>` /${p.name}${p.requiresArg?" <\u53C2\u6570>":""} - ${p.description}`),"",ht.line(60),"","\u5176\u4ED6\u547D\u4EE4:",...n.map(p=>` /${p.name}${p.requiresArg?" <\u53C2\u6570>":""} - ${p.description}`),"",ht.boldLine(60),"\u63D0\u793A: \u8F93\u5165 / \u89E6\u53D1\u547D\u4EE4\u81EA\u52A8\u8865\u5168","\u8F93\u5165 / \u540E\u8DDF\u90E8\u5206\u547D\u4EE4\u53EF\u8FDB\u884C\u6A21\u7CCA\u641C\u7D22",""],l=Math.max(0,c.length-a);Oy((p,g)=>{g.upArrow?o(m=>Math.max(0,m-1)):g.downArrow?o(m=>Math.min(l,m+1)):g.pageUp?o(m=>Math.max(0,m-a)):g.pageDown&&o(m=>Math.min(l,m+a))}),Dy(()=>{let p=()=>{i.current=process.stdout.rows||24,o(0)};return process.stdout.on("resize",p),()=>{process.stdout.off("resize",p)}},[]);let u=c.slice(r,r+a).map((p,g)=>({id:`help-line-${r+g}`,content:p}));return cm(am,{flexDirection:"column",borderStyle:Re.getBorderStyle(!0),borderColor:A.primary,paddingX:1,paddingY:1,height:a,children:[u.map(p=>{let g=p.content,m=p.id;return g.startsWith("\u2501")?bn(wn,{color:A.primary,children:g},m):g.startsWith("\u2500")?bn(wn,{color:A.textDim,children:g},m):g.includes("\u547D\u4EE4\u5E2E\u52A9")||g.includes("\u5E38\u7528\u547D\u4EE4")||g.includes("\u5176\u4ED6\u547D\u4EE4")||g.includes("\u5FEB\u6377\u952E")?bn(wn,{bold:!0,color:A.info,children:g},m):g.includes("\u6309\u4EFB\u610F\u952E")||g.includes("\u63D0\u793A:")||g.includes("\u8F93\u5165 /")?bn(wn,{dimColor:!0,color:A.textDim,children:g},m):g.includes("Ctrl+")||g.includes("Esc")||g.includes("Tab")||g.includes("\u2191\u2193")?bn(wn,{color:A.warning,children:g},m):bn(wn,{children:g},m)}),c.length>a&&bn(am,{marginTop:1,children:cm(wn,{dimColor:!0,color:A.textDim,children:["[",r+1,"-",Math.min(r+a,c.length),"/",c.length,"]",r>0&&" \u2191",r<l&&" \u2193"]})})]})},lm=Ny;import{Box as vn,Text as He}from"ink";import _y from"ink-spinner";import{jsx as _e,jsxs as Bt}from"react/jsx-runtime";var Uy=({steps:s,title:e="\u{1F914} AI\u601D\u8003\u8FC7\u7A0B"})=>Bt(vn,{flexDirection:"column",marginLeft:2,marginBottom:1,children:[Bt(He,{color:se.colors.info,bold:!0,children:[e,"\uFF1A"]}),s.map((t,n)=>Bt(vn,{marginTop:1,marginLeft:2,flexDirection:"column",children:[Bt(vn,{children:[t.status==="completed"&&_e(He,{color:se.colors.success,children:"\u2713 "}),t.status==="in_progress"&&_e(He,{color:se.colors.warning,children:_e(_y,{type:"dots"})}),t.status==="failed"&&_e(He,{color:se.colors.error,children:"\u2717 "}),t.status==="pending"&&_e(He,{dimColor:!0,children:"\u25CB "}),_e(He,{dimColor:t.status==="pending",color:t.status==="completed"?se.colors.success:t.status==="in_progress"?se.colors.warning:t.status==="failed"?se.colors.error:void 0,children:t.description}),t.status==="in_progress"&&t.progress!==void 0&&Bt(He,{dimColor:!0,children:[" (",t.progress,"%)"]})]}),t.details&&_e(vn,{marginLeft:3,marginTop:.5,children:_e(He,{dimColor:!0,children:t.details})}),t.status==="in_progress"&&t.progress!==void 0&&_e(vn,{marginLeft:3,marginTop:.5,children:_e(Wy,{progress:t.progress})}),(t.status==="completed"||t.status==="failed")&&t.startTime&&t.endTime&&_e(vn,{marginLeft:3,children:Bt(He,{dimColor:!0,children:["\u8017\u65F6: ",By(t.endTime-t.startTime)]})})]},t.id))]}),Wy=({progress:s,width:e=20})=>{let t=Math.min(100,Math.max(0,s)),n=Math.round(e*t/100),r=e-n;return Bt(vn,{children:[_e(He,{color:se.colors.success,children:"\u2588".repeat(n)}),_e(He,{dimColor:!0,children:"\u2591".repeat(r)}),Bt(He,{dimColor:!0,children:[" ",t,"%"]})]})};function By(s){if(s<1e3)return`${s}ms`;if(s<6e4)return`${(s/1e3).toFixed(1)}s`;{let e=Math.floor(s/6e4),t=Math.floor(s%6e4/1e3);return`${e}m ${t}s`}}var um=Uy;import{Box as fo,Text as St}from"ink";import{jsx as ho,jsxs as Ct}from"react/jsx-runtime";var Hy=({task:s})=>{let e=s.total>0?Math.round(s.completed/s.total*100):0,t=30,n=Math.round(t*e/100),r=s.status==="completed"?se.colors.success:s.status==="running"?se.colors.warning:s.status==="failed"?se.colors.error:se.colors.info,o=s.status==="completed"?"\u2713":s.status==="running"?"\u23F3":s.status==="failed"?"\u2717":"\u25CB";return Ct(fo,{flexDirection:"column",marginBottom:1,children:[Ct(fo,{children:[Ct(St,{color:r,children:[o," "]}),Ct(St,{children:[s.name,": "]}),Ct(St,{color:se.colors.info,children:[s.completed,"/",s.total]}),Ct(St,{dimColor:!0,children:[" (",e,"%)"]})]}),Ct(fo,{marginTop:.5,marginLeft:2,children:[ho(St,{color:se.colors.success,children:"\u2588".repeat(n)}),ho(St,{dimColor:!0,children:"\u2591".repeat(t-n)})]}),s.currentItem&&s.status==="running"&&Ct(fo,{marginTop:.5,marginLeft:2,children:[ho(St,{dimColor:!0,children:"\u6B63\u5728\u5904\u7406: "}),ho(St,{color:se.colors.info,children:s.currentItem})]}),s.estimatedTimeRemaining!==void 0&&s.status==="running"&&ho(fo,{marginTop:.5,marginLeft:2,children:Ct(St,{dimColor:!0,children:["\u9884\u8BA1\u5269\u4F59: ",zy(s.estimatedTimeRemaining)]})})]})};function zy(s){if(s<1e3)return"< 1\u79D2";if(s<6e4)return`${Math.ceil(s/1e3)}\u79D2`;if(s<36e5){let e=Math.floor(s/6e4),t=Math.ceil(s%6e4/1e3);return t>0?`${e}\u5206${t}\u79D2`:`${e}\u5206`}else{let e=Math.floor(s/36e5),t=Math.ceil(s%36e5/6e4);return t>0?`${e}\u5C0F\u65F6${t}\u5206`:`${e}\u5C0F\u65F6`}}var pm=Hy;import{useState as Vy}from"react";import{Box as rt,Text as wt}from"ink";import{jsx as st,jsxs as bt}from"react/jsx-runtime";var Gy=({error:s,onDismiss:e})=>{let[t,n]=Vy(!1);return bt(rt,{flexDirection:"column",borderStyle:"round",borderColor:se.colors.error,padding:1,marginTop:1,marginBottom:1,children:[st(rt,{children:bt(wt,{color:se.colors.error,bold:!0,children:["\u274C ",s.title]})}),st(rt,{marginTop:1,children:st(wt,{children:s.message})}),s.reason&&bt(rt,{marginTop:1,children:[st(wt,{dimColor:!0,children:"\u539F\u56E0: "}),st(wt,{children:s.reason})]}),s.solutions&&s.solutions.length>0&&bt(rt,{marginTop:1,flexDirection:"column",children:[st(wt,{color:se.colors.warning,bold:!0,children:"\u{1F4A1} \u89E3\u51B3\u65B9\u6848:"}),s.solutions.map((r,o)=>st(rt,{marginLeft:2,marginTop:.5,children:bt(wt,{color:se.colors.info,children:[o+1,". ",r]})},o))]}),s.technicalDetails&&bt(rt,{marginTop:1,flexDirection:"column",children:[st(rt,{children:bt(wt,{dimColor:!0,children:["\u6280\u672F\u8BE6\u60C5 ",t?"(\u70B9\u51FB\u9690\u85CF)":"(\u70B9\u51FB\u663E\u793A)"]})}),t&&st(rt,{marginTop:.5,marginLeft:2,children:bt(wt,{dimColor:!0,children:[s.technicalDetails.slice(0,300),s.technicalDetails.length>300?"...":""]})})]}),s.errorType&&st(rt,{marginTop:1,children:bt(wt,{dimColor:!0,children:["[",s.errorType,"]"]})})]})},gm=Gy;ct();io();hn();var he=class extends Error{type;code;details;suggestion;recoverable;constructor(e){super(e.message),this.name="CLIError",this.type=e.type,this.code=e.code,this.details=e.details,this.suggestion=e.suggestion,this.recoverable=e.recoverable}toDisplayString(){let e=[],t=this.getErrorIcon();return e.push(`${t} ${this.message}`),this.details&&e.push(` \u8BE6\u60C5: ${this.details}`),this.suggestion&&e.push(` \u5EFA\u8BAE: ${this.suggestion}`),this.code&&e.push(` \u4EE3\u7801: ${this.code}`),e.join(`
3388
+ `)}getErrorIcon(){switch(this.type){case"SYSTEM_ERROR":case"INITIALIZATION_ERROR":return"\u{1F4A5}";case"CONFIGURATION_ERROR":return"\u2699\uFE0F";case"MCP_CONNECTION_ERROR":case"NETWORK_ERROR":return"\u{1F50C}";case"MCP_TOOL_ERROR":case"TOOL_EXECUTION_ERROR":return"\u{1F527}";case"SESSION_ERROR":case"SESSION_ARCHIVE_ERROR":return"\u{1F4BE}";case"INVALID_COMMAND":case"INVALID_ARGUMENT":return"\u274C";case"API_ERROR":case"AUTHENTICATION_ERROR":return"\u{1F511}";case"FILE_NOT_FOUND":return"\u{1F4C4}";case"FILE_PERMISSION_ERROR":return"\u{1F512}";default:return"\u26A0\uFE0F"}}getColorTag(){switch(this.type){case"SYSTEM_ERROR":case"INITIALIZATION_ERROR":return"red";case"CONFIGURATION_ERROR":return"yellow";case"MCP_CONNECTION_ERROR":case"NETWORK_ERROR":return"cyan";case"MCP_TOOL_ERROR":case"TOOL_EXECUTION_ERROR":return"magenta";case"INVALID_COMMAND":case"INVALID_ARGUMENT":return"red";case"FILE_PERMISSION_ERROR":case"AUTHENTICATION_ERROR":return"red";default:return"yellow"}}},Rr={systemError:(s,e)=>new he({type:"SYSTEM_ERROR",message:s,details:e,recoverable:!1,suggestion:"\u8BF7\u68C0\u67E5\u7CFB\u7EDF\u73AF\u5883\u6216\u91CD\u65B0\u542F\u52A8\u5E94\u7528"}),mcpConnectionError:(s,e)=>new he({type:"MCP_CONNECTION_ERROR",message:`\u65E0\u6CD5\u8FDE\u63A5\u5230MCP\u670D\u52A1\u5668: ${s}`,details:e,recoverable:!0,suggestion:"\u8BF7\u68C0\u67E5\u670D\u52A1\u5668\u914D\u7F6E\u548C\u7F51\u7EDC\u8FDE\u63A5\uFF0C\u6216\u4F7F\u7528 /mcp-status \u67E5\u770B\u72B6\u6001"}),mcpToolError:(s,e,t)=>new he({type:"MCP_TOOL_ERROR",message:`MCP\u5DE5\u5177\u6267\u884C\u5931\u8D25: ${s}`,details:`\u670D\u52A1\u5668: ${e}${t?` - ${t}`:""}`,recoverable:!0,suggestion:"\u53EF\u4EE5\u5C1D\u8BD5\u91CD\u65B0\u8FDE\u63A5MCP\u670D\u52A1\u5668\u6216\u4F7F\u7528\u672C\u5730\u5DE5\u5177\u66FF\u4EE3"}),sessionError:(s,e)=>new he({type:"SESSION_ERROR",message:s,details:e,recoverable:!0,suggestion:"\u53EF\u4EE5\u5C1D\u8BD5\u4F7F\u7528 /clear \u547D\u4EE4\u5F00\u59CB\u65B0\u4F1A\u8BDD"}),toolNotFoundError:s=>new he({type:"TOOL_NOT_FOUND",message:`\u672A\u627E\u5230\u5DE5\u5177: ${s}`,recoverable:!0,suggestion:"\u4F7F\u7528 /tools \u67E5\u770B\u53EF\u7528\u5DE5\u5177\u5217\u8868"}),toolExecutionError:(s,e)=>new he({type:"TOOL_EXECUTION_ERROR",message:`\u5DE5\u5177\u6267\u884C\u5931\u8D25: ${s}`,details:e,recoverable:!0,suggestion:"\u8BF7\u68C0\u67E5\u5DE5\u5177\u53C2\u6570\u6216\u67E5\u770B\u9519\u8BEF\u8BE6\u60C5"}),invalidCommand:(s,e)=>new he({type:"INVALID_COMMAND",message:`\u672A\u77E5\u547D\u4EE4: ${s}`,recoverable:!0,suggestion:e||"\u4F7F\u7528 /help \u67E5\u770B\u53EF\u7528\u547D\u4EE4"}),invalidArgument:(s,e,t)=>new he({type:"INVALID_ARGUMENT",message:`\u65E0\u6548\u53C2\u6570: ${s} = ${e}`,details:t?`\u671F\u671B\u7C7B\u578B: ${t}`:void 0,recoverable:!0,suggestion:"\u8BF7\u68C0\u67E5\u547D\u4EE4\u53C2\u6570\u683C\u5F0F"}),fileNotFoundError:s=>new he({type:"FILE_NOT_FOUND",message:`\u6587\u4EF6\u672A\u627E\u5230: ${s}`,recoverable:!0,suggestion:"\u8BF7\u68C0\u67E5\u6587\u4EF6\u8DEF\u5F84\u662F\u5426\u6B63\u786E"}),filePermissionError:(s,e)=>new he({type:"FILE_PERMISSION_ERROR",message:`\u6587\u4EF6\u6743\u9650\u4E0D\u8DB3: ${s}`,details:`\u64CD\u4F5C: ${e}`,recoverable:!1,suggestion:"\u8BF7\u68C0\u67E5\u6587\u4EF6\u6743\u9650\u6216\u4F7F\u7528\u5176\u4ED6\u6587\u4EF6"})},ol={safeExecute:async(s,e,t)=>{try{return{success:!0,result:await s()}}catch(n){return{success:!1,error:n instanceof he?n:Rr.systemError(n instanceof Error?n.message:String(n),t)}}},isRecoverable:s=>s instanceof he?s.recoverable:!1,formatError:s=>s instanceof he?s.toDisplayString():`\u26A0\uFE0F ${s.message}`};Aa();import{Fragment as Zy,jsx as ot,jsxs as fm}from"react/jsx-runtime";var Xy=({debug:s})=>ot(Zg,{children:ot(Qy,{debug:s})}),Qy=({debug:s})=>{let{exit:e}=Jy(),{focusedArea:t,setFocus:n}=Ar(),[r,o]=Ke([]),[i,a]=Ke([]),[c,l]=Ke(!1),[u,p]=Ke({status:"inactive"}),[g,m]=Ke({serversConnected:0,totalServers:0,toolsAvailable:0,servers:[]}),[d]=Ke(process.cwd()),[f,y]=Ke(!1),[w,T]=Ke(null),[h,x]=Ke([]),[P,k]=Ke(null),[b,U]=Ke(null);Ky(($,I)=>{if(I.ctrl&&$==="l"){n(t==="input"?"content":"input");return}if(I.escape){f?y(!1):t==="content"&&n("input");return}f&&!I.upArrow&&!I.downArrow&&!I.pageUp&&!I.pageDown&&!I.escape&&y(!1)});let j={isActive:!0,clear:()=>{o([])},log:($="")=>{o(I=>[...I,$])},success:$=>{o(I=>[...I,`[\u6210\u529F] ${$}`])},warning:$=>{o(I=>[...I,`[\u8B66\u544A] ${$}`])},error:$=>{$.includes(`
3389
+ `)||$.includes("\u8BE6\u60C5:")||$.includes("\u5EFA\u8BAE:")?o(I=>[...I,$]):o(I=>[...I,`[\u9519\u8BEF] ${$}`])},info:$=>{o(I=>[...I,$])},exit:()=>{e()},printWelcome:()=>{let $=["help","clear","resume","history","exit"],I=i.filter(O=>$.includes(O.name));o([`\u{1F680} NiumAgents-CLI v${po}${s?" (DEBUG)":""}`,"","\u2728 \u5FEB\u901F\u5F00\u59CB:"," \u76F4\u63A5\u8F93\u5165\u4EFB\u52A1\u63CF\u8FF0\u5F00\u59CB\u5BF9\u8BDD"," \u8F93\u5165 /help \u67E5\u770B\u6240\u6709\u547D\u4EE4"," \u8F93\u5165 / \u89E6\u53D1\u547D\u4EE4\u81EA\u52A8\u8865\u5168"," Ctrl+L \u5207\u6362\u6D4F\u89C8\u6A21\u5F0F","","\u{1F6E0}\uFE0F \u5E38\u7528\u547D\u4EE4:",...I.map(O=>` /${O.name}${O.requiresArg?" <\u53C2\u6570>":""} - ${O.description}${O.hint?` (${O.hint})`:""}`),""])},printHelp:()=>{y(!0)}};qy(()=>{(async()=>{try{let N=fn();a(N),j.printWelcome(),Vr()&&E.messages&&E.messages.length>0&&E.currentTask?(p({status:"pending",currentTask:E.currentTask,messageCount:E.messages.length,sessionId:E.sessionId}),j.warning("[\u8B66\u544A] \u68C0\u6D4B\u5230\u4E4B\u524D\u7684\u4F1A\u8BDD\uFF01\u4F7F\u7528 /resume \u7EE7\u7EED\u6216 /clear \u5F00\u59CB\u65B0\u4F1A\u8BDD\u3002"),j.log()):p({status:"ready"});let V=et().getStatus();m({serversConnected:V.serversConnected,totalServers:V.servers.length,toolsAvailable:V.toolsAvailable,servers:V.servers.map(te=>({name:te.name,connected:te.connected,toolsCount:te.toolCount}))})}catch(N){let Y=N instanceof he?N:Rr.systemError("\u521D\u59CB\u5316\u5931\u8D25",N instanceof Error?N.message:String(N));j.error(ol.formatError(Y)),p({status:"ready"}),m({serversConnected:0,totalServers:0,toolsAvailable:0,servers:[]})}})(),global.__inkAskUserEmitter||(global.__inkAskUserEmitter=new Yy);let I=global.__inkAskUserEmitter,O=N=>{T(N),n("input")};I.on("askUser",O);let D=N=>{switch(N.type){case"thinking_step_update":x(N.steps);break;case"task_update":k(N.task);break;case"error":U(N.error);break;case"clear":x([]),k(null),U(null);break}};return Kn.on("progress",D),()=>{I.off("askUser",O),Kn.off("progress",D)}},[]);let L=mm(async $=>{if($.trim()){l(!0),n("content");try{if($.startsWith("/")){let I=$.slice(1).split(" "),O=I[0],D=I.slice(1).join(" "),N=i.find(Y=>Y.name===O);if(!N)throw Rr.invalidCommand(O,"\u8F93\u5165 /help \u67E5\u770B\u53EF\u7528\u547D\u4EE4");if(N.requiresArg&&!D.trim())throw Rr.invalidArgument(O,"missing",N.hint||"\u547D\u4EE4\u53C2\u6570");await dn(j,O,D)}else await dn(j,"chat",$);E.sessionId&&p({status:"active",sessionId:E.sessionId,messageCount:E.messages?.length||0,currentTask:E.currentTask})}catch(I){let O=I instanceof he?I:Rr.systemError("\u547D\u4EE4\u6267\u884C\u5931\u8D25",I instanceof Error?I.message:String(I));j.error(ol.formatError(O))}finally{l(!1),n("input")}}},[i,n]),M=mm($=>{if(!w)return;let I=global.__inkAskUserEmitter;I&&I.emit(`response_${w.requestId}`,$),T(null)},[w]);return fm(dm,{flexDirection:"column",height:"100%",children:[ot(Xg,{version:po,sessionStatus:u,mcpStatus:g,debug:s,focusedArea:t,cwd:d,isLoading:c}),ot(dm,{flexGrow:1,flexDirection:"column",children:f?ot(lm,{commands:i,onClose:()=>y(!1)}):fm(Zy,{children:[ot(sm,{output:r,isLoading:c}),h.length>0&&ot(um,{steps:h}),P&&ot(pm,{task:P}),b&&ot(gm,{error:b,onDismiss:()=>U(null)})]})}),ot(im,{commands:i,onCommandSubmit:L,isDisabled:c||f,askUserRequest:w,onAskUserResponse:M})]})},hm=Xy;Ye();Q();ae();io();pn();var qi=class{debug=!1;constructor(e={}){this.debug=e.debug||!1,In(this.debug),Lr(this.debug)}async start(){try{Nr(),$n(),this.debug&&it("Debug\u6A21\u5F0F\u5DF2\u542F\u7528 - \u5C06\u663E\u793A\u8BE6\u7EC6\u65E5\u5FD7\u4FE1\u606F","Session"),await this.initializeMCP();let{initializeDynamicCommands:e}=await Promise.resolve().then(()=>(hn(),uo));await e(),tx(ex.createElement(hm,{debug:this.debug}))}catch(e){console.error("\u542F\u52A8\u4F1A\u8BDD\u65F6\u51FA\u9519:",e.message),console.error("\u9519\u8BEF\u5806\u6808:",e.stack),process.exit(1)}}async initializeMCP(){try{let e=qr();if(e.length===0){it("No MCP servers configured","MCP"),await tt();return}let t=et();await t.initialize(e),await tt();let n=t.getStatus();n.serversConnected>0?X(`Connected to ${n.serversConnected} MCP server(s), ${n.toolsAvailable} tools available`,"MCP"):J(`Configured ${e.length} MCP server(s) but none connected`,"MCP")}catch(e){J(`Failed to initialize MCP: ${e.message}`,"MCP"),await tt()}}};Va();ae();import le from"chalk";async function nx(){try{await en.initialize();let s=process.argv.slice(2),e=s.includes("--debug"),t=s.includes("--help")||s.includes("-h"),n=s.includes("--ink"),r=s.filter(o=>!o.startsWith("--"));if(t&&(console.log(le.green("NiumAgents-CLI v0.1.8")),console.log(le.gray("AI Code Agent")),console.log(),console.log(le.gray("Options:")),console.log(le.gray(" --debug - \u542F\u7528\u8C03\u8BD5\u6A21\u5F0F\u4EE5\u663E\u793A\u8BE6\u7EC6\u65E5\u5FD7")),console.log(le.gray(" --ink - \u4F7F\u7528Ink\u6846\u67B6\u7684\u73B0\u4EE3\u5316UI (\u5B9E\u9A8C\u6027\u529F\u80FD)")),console.log(le.gray(" --help \u6216 -h - \u663E\u793A\u6B64\u5E2E\u52A9\u4FE1\u606F")),console.log(),console.log(le.gray("Usage:")),console.log(le.gray(" nium [options] [command] [arguments]")),console.log(le.gray(" npm run start [options] [command] [arguments]")),console.log(),console.log(le.gray("Examples:")),console.log(le.gray(" nium --debug")),console.log(le.gray(" nium --ink")),console.log(le.gray(' nium "\u5E2E\u6211\u521B\u5EFA\u4E00\u4E2A\u7528\u6237\u7BA1\u7406\u6A21\u5757"')),console.log(le.gray(' nium chat "\u5E2E\u6211\u521B\u5EFA\u4E00\u4E2A\u7528\u6237\u7BA1\u7406\u6A21\u5757"')),console.log(le.gray(' npm run start -- --debug chat "\u5E2E\u6211\u521B\u5EFA\u4E00\u4E2A\u7528\u6237\u7BA1\u7406\u6A21\u5757"')),process.exit(0)),r.length>0){let o,i;["chat","resume","clear","history","exit","quit","help","list_tools","commit"].includes(r[0])?(o=r[0],i=r.slice(1).join(" ")):(o="chat",i=r.join(" "));let{executeCommand:c}=await Promise.resolve().then(()=>(hn(),uo)),{getDefaultMasterAgent:l}=await Promise.resolve().then(()=>(tl(),qg)),{initWorkspace:u}=await Promise.resolve().then(()=>(Ye(),pl)),{initializeDynamicCommands:p}=await Promise.resolve().then(()=>(hn(),uo)),{loadAllTools:g}=await Promise.resolve().then(()=>(pn(),Ag));u(),await p(),await g(),await c({isActive:!0,clear:()=>console.clear(),log:(d="")=>console.log(d),success:d=>console.log(le.green(`[\u6210\u529F] ${d}`)),warning:d=>console.log(le.yellow(`[\u8B66\u544A] ${d}`)),error:d=>console.error(le.red(`[\u9519\u8BEF] ${d}`)),info:d=>console.log(le.blue(`[\u4FE1\u606F] ${d}`)),exit:()=>process.exit(0)},o,i),process.exit(0)}n?(console.log(le.cyan("\u{1F3A8} \u4F7F\u7528Ink\u6846\u67B6UI (\u5B9E\u9A8C\u6027\u529F\u80FD)")),Po(!0),await new qi({debug:e}).start()):(Po(!1),await new Wi({debug:e}).start())}catch(s){console.error("\u542F\u52A8\u5E94\u7528\u65F6\u51FA\u9519:",s.message),process.exit(1)}}nx();