niumagents-cli 0.1.10 → 0.1.12

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 (2) hide show
  1. package/dist/nium.js +1100 -236
  2. package/package.json +94 -97
package/dist/nium.js CHANGED
@@ -1,11 +1,11 @@
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 y=(o,e)=>()=>(o&&(e=o(o=0)),e);var O=(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=[];return n&&ht.enableSymbol&&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 N(o,e=null){console.warn(sn("WARN",e,o))}function se(o,e=null){console.log(sn("INFO",e,o,!1))}function j(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=y(()=>{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 Vl}from"fs";import{join as ie,dirname as Pi}from"path";import{fileURLToPath as Wl}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 Vo||(Vo=ie(process.cwd(),".nium")),Vo}function zl(){if(!zo){let o=$i();zo=ie(o,"examples","config.example.json")}return zo}function Hl(){if(!Wo){let o=$i();Wo=ie(o,"examples",".env.example")}return Wo}function Ii(){let o=Mi(),e=zl();try{if(!Me(o)){se("\u521D\u59CB\u5316\u5DE5\u4F5C\u76EE\u5F55...","Init"),ln(o,{recursive:!0}),j("\u521B\u5EFA .nium \u76EE\u5F55","Init");let c=ie(o,"config.json");Me(e)?(Ei(e,c),j("\u590D\u5236 config.example.json \u5230 .nium/config.json","Init"),N("\u8BF7\u7F16\u8F91 .nium/config.json \u6587\u4EF6\u914D\u7F6E API \u5BC6\u94A5\u548C\u6A21\u578B","Init")):(N(`\u672A\u627E\u5230 config.example.json: ${e}`,"Init"),Vl(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)),j("\u521B\u5EFA\u9ED8\u8BA4\u7684 .nium/config.json \u6587\u4EF6","Init"),N("\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}),j("\u521B\u5EFA .nium/agents \u76EE\u5F55","Init"));let n=ie(o,"docs");Me(n)||(ln(n,{recursive:!0}),j("\u521B\u5EFA .nium/docs \u76EE\u5F55","Init"));let r=ie(o,"archives");Me(r)||(ln(r,{recursive:!0}),j("\u521B\u5EFA .nium/archives \u76EE\u5F55","Init"));let s=ie(o,"logs");Me(s)||(ln(s,{recursive:!0}),j("\u521B\u5EFA .nium/logs \u76EE\u5F55","Init"));let i=Hl(),a=ie(o,".env");return Me(a)||(Me(i)?(Ei(i,a),j("\u590D\u5236 examples/.env.example \u5230 .nium/.env","Init")):(N(`\u672A\u627E\u5230 .env.example: ${i}`,"Init"),N("\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,Vo,Wo,zo,je=y(()=>{cn();un=typeof __dirname<"u"?__dirname:Pi(Wl(import.meta.url)),Vo=null,Wo=null,zo=null});var Ho,Ir,Jo=y(()=>{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=y(()=>{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 n=new Date(e.timestamp).toLocaleString("zh-CN");t+=`[${n}] `}return t+=`[${e.level.padEnd(7)}] ${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=y(()=>{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 Vp=Object.defineProperty;var Bp=(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 _=(o,e)=>{for(var t in e)Vp(o,t,{get:e[t],enumerable:!0})};import ue from"chalk";function Jp(o){Gt={...Gt,...o}}function Xn(o){Gt.enableDebug=o}function Yn(o,e,t,n=!0){let r=[],s=/^[✓✗⚠ℹ◆●]/.test(t);return n&&Gt.enableSymbol&&o!=="INFO"&&!s&&r.push(Xa[o](Gp[o])),e&&Gt.enablePrefix&&r.push(ue.gray(`[${e}]`)),r.push(Xa[o](t)),r.join(" ")}function ie(o,e=null){console.error(Yn("ERROR",e,o))}function O(o,e=null){console.warn(Yn("WARN",e,o))}function me(o,e=null){console.log(Yn("INFO",e,o,!1))}function W(o,e=null){console.log(Yn("SUCCESS",e,o))}function We(o,e=null){Gt.enableDebug&&console.log(Yn("DEBUG",e,o))}function Qn(o){console.log(o)}function jo(o="\u2500",e=50){console.log(ue.gray(o.repeat(e)))}function qp(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(ue.cyan(r)),console.log(ue.cyan(s)),console.log(ue.cyan(r))}function Kp(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(ue.blue(`[${o}/${e}]`)+" "+ue.cyan(r)+" "+ue.white(`${n}%`)+" "+ue.gray(t))}function Xp(o){for(let[e,t]of Object.entries(o))console.log(ue.cyan(` ${e}: `)+ue.white(t))}function Qs(){console.clear()}var Gp,Xa,Gt,tt=C(()=>{Gp={SUCCESS:"\u2713",ERROR:"\u2717",WARN:"\u26A0",INFO:"\u2139",DEBUG:"\u25C6"},Xa={ERROR:ue.red,WARN:ue.yellow,INFO:ue.blue,SUCCESS:ue.green,DEBUG:ue.magenta},Gt={enableDebug:!1,enablePrefix:!0,enableSymbol:!0}});import{existsSync as ze,mkdirSync as Zn,copyFileSync as Ya,writeFileSync as Yp}from"fs";import{join as de,dirname as Qa}from"path";import{fileURLToPath as Qp}from"url";function Za(){let o=[de(er,"..","..","examples"),de(er,"..","examples"),de(er,"examples"),de(er,"..","..","..","examples")];for(let e of o)if(ze(e))return Qa(e);return de(er,"..")}function ec(){return Zs||(Zs=de(process.cwd(),".nium")),Zs}function Zp(){if(!ti){let o=Za();ti=de(o,"examples","config.example.json")}return ti}function eg(){if(!ei){let o=Za();ei=de(o,"examples",".env.example")}return ei}function Do(){let o=ec(),e=Zp();try{if(!ze(o)){me("\u521D\u59CB\u5316\u5DE5\u4F5C\u76EE\u5F55...","Init"),Zn(o,{recursive:!0}),W("\u521B\u5EFA .nium \u76EE\u5F55","Init");let c=de(o,"config.json");ze(e)?(Ya(e,c),W("\u590D\u5236 config.example.json \u5230 .nium/config.json","Init"),O("\u8BF7\u7F16\u8F91 .nium/config.json \u6587\u4EF6\u914D\u7F6E API \u5BC6\u94A5\u548C\u6A21\u578B","Init")):(O(`\u672A\u627E\u5230 config.example.json: ${e}`,"Init"),Yp(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)),W("\u521B\u5EFA\u9ED8\u8BA4\u7684 .nium/config.json \u6587\u4EF6","Init"),O("\u8BF7\u7F16\u8F91 .nium/config.json \u6587\u4EF6\u914D\u7F6E API \u5BC6\u94A5\u548C\u6A21\u578B","Init"))}let t=de(o,"agents");ze(t)||(Zn(t,{recursive:!0}),W("\u521B\u5EFA .nium/agents \u76EE\u5F55","Init"));let n=de(o,"docs");ze(n)||(Zn(n,{recursive:!0}),W("\u521B\u5EFA .nium/docs \u76EE\u5F55","Init"));let r=de(o,"archives");ze(r)||(Zn(r,{recursive:!0}),W("\u521B\u5EFA .nium/archives \u76EE\u5F55","Init"));let s=de(o,"logs");ze(s)||(Zn(s,{recursive:!0}),W("\u521B\u5EFA .nium/logs \u76EE\u5F55","Init"));let i=eg(),a=de(o,".env");return ze(a)||(ze(i)?(Ya(i,a),W("\u590D\u5236 examples/.env.example \u5230 .nium/.env","Init")):(O(`\u672A\u627E\u5230 .env.example: ${i}`,"Init"),O("\u5C06\u4F7F\u7528\u9ED8\u8BA4\u73AF\u5883\u53D8\u91CF\u914D\u7F6E","Init"))),o}catch(t){ie(`\u521D\u59CB\u5316\u5DE5\u4F5C\u76EE\u5F55\u5931\u8D25: ${t.message}`,"Init"),process.exit(1)}}function Te(o){return de(ec(),o)}var er,Zs,ei,ti,He=C(()=>{tt();er=typeof __dirname<"u"?__dirname:Qa(Qp(import.meta.url)),Zs=null,ei=null,ti=null});var ni,Fo,ri=C(()=>{ni={level:"INFO",debugMode:!1,consoleOutput:!0,fileOutput:!0,enableTimestamp:!0,rotationStrategy:"daily",maxFileSize:10485760,maxFiles:30},Fo={ERROR:0,WARN:1,INFO:2,SUCCESS:2,DEBUG:3,TRACE:4}});import Jt from"chalk";var tr,N,nr=C(()=>{tr=class{colors;constructor(){this.colors={INFO:Jt.blue,WARN:Jt.yellow,ERROR:Jt.red,SUCCESS:Jt.green,DEBUG:Jt.magenta,TRACE:Jt.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)}},N=new tr});import{existsSync as tg,readFileSync as ng,appendFileSync as tc,writeFileSync as rg,createReadStream as og}from"fs";import{createInterface as sg}from"readline";var $e,Ie,rr=C(()=>{$e=class{filePath;constructor(e){this.filePath=e}append(e){try{let t=JSON.stringify(e)+`
3
+ `;tc(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=y(()=>{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 Vi=y(()=>{je();dn();pn()});async function Wi(o,e=null){await re.writeLog("INFO",o,e)}async function $(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 H(o,e=null){await qo(o,e)}async function Y(o,e=null){await re.writeLog("ERROR",o,e)}async function C(o,e=null){await re.writeLog("DEBUG",o,e)}async function Hi(o,e=null){await re.writeLog("TRACE",o,e)}function G(o,e=null){Wi(o,e).catch(t=>console.error(D.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}function Qe(o,e=null){$(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){H(o,e).catch(t=>console.error(D.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}function he(o,e=null){Y(o,e).catch(t=>console.error(D.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}function Z(o,e=null){C(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=y(()=>{Bo();pn()});var Yo={};O(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:()=>j,consoleTitle:()=>_l,consoleWarn:()=>N,default:()=>re,defaultFormatter:()=>D,formatLogEntry:()=>Ni,getLogStats:()=>Ui,initLogger:()=>Ar,log:()=>Wi,logDebug:()=>C,logDebugSync:()=>Z,logError:()=>Y,logErrorSync:()=>he,logInfo:()=>$,logInfoSync:()=>Qe,logSuccess:()=>zi,logSuccessSync:()=>hn,logSync:()=>G,logTrace:()=>Hi,logTraceSync:()=>Ql,logWarn:()=>H,logWarnSync:()=>Ko,logWarning:()=>qo,logWarningSync:()=>Ct,loggerManager:()=>re,readArchivedLogs:()=>_i,readCurrentLogs:()=>ji,setConsoleDebugMode:()=>_o,setConsoleLoggerConfig:()=>jl,setDebugMode:()=>Lr,setFormatter:()=>Fi,setLogLevel:()=>Di});var K=y(()=>{Jo();pn();Bo();Vi();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
+ `;tc(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
+ `;rg(this.filePath,t,"utf-8")}catch(t){throw new Error(`Failed to create JSONL file: ${t.message}`)}}getFilePath(){return this.filePath}},Ie=class{filePath;constructor(e){this.filePath=e}exists(){return tg(this.filePath)}readAllSync(e={}){if(!this.exists())return[];try{let n=ng(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=og(this.filePath,{encoding:"utf-8"}),i=sg({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 oi,mkdirSync as ig,renameSync as ag,writeFileSync as nc}from"fs";import{join as or}from"path";function qt(){return pe.initLogger()}function rc(o){pe.configureLogger(o)}function Kt(o){pe.setDebugMode(o)}function oc(o){pe.setLogLevel(o)}function sc(o){pe.setFormatter(o)}var sr,pe,si=C(()=>{He();rr();ri();nr();sr=class{config;logsDir;currentLogPath;logDatePath;isInitialized=!1;formatter;constructor(){this.config={...ni},this.logsDir=Te("logs"),this.currentLogPath=or(this.logsDir,"current.jsonl"),this.logDatePath=or(this.logsDir,".current_date"),this.formatter=N}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 oi(this.logDatePath)&&new Ie(this.logDatePath).readAllSync()[0]?.date||null}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(N.colorize(`\u8BFB\u53D6\u65E5\u5FD7\u6587\u4EF6\u65E5\u671F\u5931\u8D25: ${t}`,"ERROR")),null}}async archiveLogFile(e){try{let t=or(this.logsDir,`${e}.jsonl`);if(oi(t)){let r=new Ie(this.currentLogPath).readAllSync();await new $e(t).appendBatch(r),console.log(N.colorize(`\u2713 \u65E5\u5FD7\u5DF2\u8FFD\u52A0\u5230\u5F52\u6863\u6587\u4EF6: ${e}.jsonl`,"SUCCESS"))}else ag(this.currentLogPath,t),console.log(N.colorize(`\u2713 \u65E5\u5FD7\u5DF2\u5F52\u6863: ${e}.jsonl`,"SUCCESS"))}catch(t){let n=t instanceof Error?t.message:String(t);console.error(N.colorize(`\u5F52\u6863\u65E5\u5FD7\u5931\u8D25: ${n}`,"ERROR"))}}async createNewLogFile(e){try{nc(this.currentLogPath,"","utf-8"),nc(this.logDatePath,JSON.stringify({date:e})+`
8
+ `,"utf-8");let t=new $e(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(N.colorize(`\u521B\u5EFA\u65E5\u5FD7\u6587\u4EF6\u5931\u8D25: ${n}`,"ERROR"))}}async initLogger(){try{oi(this.logsDir)||(ig(this.logsDir,{recursive:!0}),console.log(N.colorize("\u521B\u5EFA\u65E5\u5FD7\u76EE\u5F55: .nium/logs","DEBUG")));let e=this.getTodayDateString(),t=await this.getLogFileDate();(!t||t!==e)&&(t&&(console.log(N.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(N.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(N.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=or(this.logsDir,"current.jsonl"),this.logDatePath=or(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 Fo[e]<=Fo[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 $e(this.currentLogPath).append(c)}catch(r){let s=r instanceof Error?r.message:String(r);console.error(N.colorize(`\u5199\u5165\u65E5\u5FD7\u5931\u8D25: ${s}`,"ERROR"))}}setDebugMode(e){this.config.debugMode=e}setLogLevel(e){this.config.level=e}},pe=new sr});import{join as ic}from"path";async function ac(o){try{let e=Te("logs"),t=ic(e,"current.jsonl"),n=new Ie(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(N.colorize(`\u8BFB\u53D6\u65E5\u5FD7\u5931\u8D25: ${t}`,"ERROR")),[]}}async function cc(o,e){try{let t=Te("logs"),n=ic(t,`${o}.jsonl`),r=new Ie(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(N.colorize(`\u8BFB\u53D6\u5F52\u6863\u65E5\u5FD7\u5931\u8D25: ${n}`,"ERROR")),[]}}function lc(o){return`[${new Date(o.timestamp).toLocaleString("zh-CN")}] [${o.level.padEnd(7)}] ${o.message}`}function uc(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 pc=C(()=>{He();rr();nr()});async function gc(o,e=null){await pe.writeLog("INFO",o,e)}async function L(o,e=null){await pe.writeLog("INFO",o,e)}async function mc(o,e=null){await pe.writeLog("SUCCESS",o,e)}async function ii(o,e=null){await pe.writeLog("WARN",o,e)}async function Y(o,e=null){await ii(o,e)}async function ne(o,e=null){await pe.writeLog("ERROR",o,e)}async function S(o,e=null){await pe.writeLog("DEBUG",o,e)}async function dc(o,e=null){await pe.writeLog("TRACE",o,e)}function Z(o,e=null){gc(o,e).catch(t=>console.error(N.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}function bt(o,e=null){L(o,e).catch(t=>console.error(N.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}function ir(o,e=null){mc(o,e).catch(t=>console.error(N.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}function Xt(o,e=null){ii(o,e).catch(t=>console.error(N.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}function ai(o,e=null){Y(o,e).catch(t=>console.error(N.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}function Ae(o,e=null){ne(o,e).catch(t=>console.error(N.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}function ae(o,e=null){S(o,e).catch(t=>console.error(N.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}function cg(o,e=null){dc(o,e).catch(t=>console.error(N.colorize(`\u65E5\u5FD7\u5199\u5165\u5931\u8D25: ${t}`,"ERROR")))}var fc=C(()=>{si();nr()});var ci={};_(ci,{ChalkFormatter:()=>tr,DEFAULT_CONFIG:()=>ni,LOG_LEVEL_PRIORITIES:()=>Fo,LoggerManager:()=>sr,configureLogger:()=>rc,consoleClear:()=>Qs,consoleDebug:()=>We,consoleError:()=>ie,consoleInfo:()=>me,consolePlain:()=>Qn,consoleProgress:()=>Kp,consoleSeparator:()=>jo,consoleStats:()=>Xp,consoleSuccess:()=>W,consoleTitle:()=>qp,consoleWarn:()=>O,default:()=>pe,defaultFormatter:()=>N,formatLogEntry:()=>lc,getLogStats:()=>uc,initLogger:()=>qt,log:()=>gc,logDebug:()=>S,logDebugSync:()=>ae,logError:()=>ne,logErrorSync:()=>Ae,logInfo:()=>L,logInfoSync:()=>bt,logSuccess:()=>mc,logSuccessSync:()=>ir,logSync:()=>Z,logTrace:()=>dc,logTraceSync:()=>cg,logWarn:()=>Y,logWarnSync:()=>ai,logWarning:()=>ii,logWarningSync:()=>Xt,loggerManager:()=>pe,readArchivedLogs:()=>cc,readCurrentLogs:()=>ac,setConsoleDebugMode:()=>Xn,setConsoleLoggerConfig:()=>Jp,setDebugMode:()=>Kt,setFormatter:()=>sc,setLogLevel:()=>oc});var V=C(()=>{ri();nr();si();pc();fc();tt()});import{existsSync as hc,mkdirSync as lg,readdirSync as ug}from"fs";import{join as yc}from"path";function xc(){hc(Yt)||lg(Yt,{recursive:!0})}function Cc(o){if(!o||!o.messages||o.messages.length===0)return null;xc();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=yc(Yt,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 $e(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 pg(){return xc(),hc(Yt)?ug(Yt).filter(e=>e.endsWith(".jsonl")).map(e=>{let t=yc(Yt,e);try{let r=new Ie(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 Sc(){let o=pg();if(o.length===0)return"\u6682\u65E0\u5F52\u6863\u4F1A\u8BDD";let e=`
9
9
  === \u5F52\u6863\u4F1A\u8BDD\u5217\u8868 ===
10
10
 
11
11
  `;return o.forEach((t,n)=>{let s=new Date(t.archivedAt).toLocaleString("zh-CN");e+=`[${n+1}] ${t.currentTask}
@@ -15,7 +15,7 @@ var Fl=Object.defineProperty;var $r=(o=>typeof require<"u"?require:typeof Proxy<
15
15
  `,e+=` \u6D88\u606F\u6570\u91CF: ${t.messageCount}
16
16
  `,e+=` \u6587\u4EF6\u540D: ${t.fileName}
17
17
 
18
- `}),e}var xt,Xo=y(()=>{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=y(()=>{});var Zi={};O(Zi,{SESSION_FILE:()=>_e,archiveSession:()=>et,associateMessageWithTask:()=>Qi,completeCurrentTask:()=>vt,loadSession:()=>es,saveSession:()=>ce,sessionState:()=>T,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{T.messages&&T.messages.length>0&&Ki(T)&&C("\u4F1A\u8BDD\u5DF2\u5F52\u6863"),T=Zo(),new me(_e).create(T)}catch(o){let e=o instanceof Error?o.message:String(o);N(`Failed to archive session - ${e}`,"Session"),T=Zo();try{new me(_e).create(T)}catch{}}}function es(){try{if(Xi(_e)){let e=new fe(_e).readAllSync(),t=e.length>0?e[0]:null;return T={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);N(`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 T.tasks.push(t),T.currentTask=o,T.currentTaskId=e,e}function Qi(o){if(T.currentTaskId&&o){let e=T.currentTaskId;o.taskId=e;let t=T.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){T.currentTaskId=o,T.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!==T.currentTask&&Fr(e),o){let n=o.map(r=>Qi({...r}));T={...T,messages:n,updatedAt:new Date().toISOString()}}else T={...T,updatedAt:new Date().toISOString()};Xi(_e)&&nu(_e,"","utf-8"),new me(_e).create(T)}catch(t){let n=t instanceof Error?t.message:String(t);N(`Could not save session - ${n}`,"Session")}}function et(){return ru()}function ou(){if(T.currentTask&&T.currentTaskId){let o=T.tasks.find(e=>e.id===T.currentTaskId);if(o){let e=o.tokenCount||0;j(`\u4EFB\u52A1\u5B8C\u6210: ${T.currentTask}`,"Session"),se(`Token\u603B\u5F00\u9500: ${e.toLocaleString()} tokens`,"Session")}T.currentTask=null,T.currentTaskId=null,ce()}}function vt(){return ou()}var _e,T,Ne=y(()=>{cn();K();je();Xo();dn();Dr();_e=ge("session.jsonl");T=Zo()});var ts,ea=y(()=>{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 Yt,li=C(()=>{He();rr();Yt=Te("archives")});function vt(){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 ui(){return"S"+vt()}function Oo(){return"T"+vt()}var _o=C(()=>{});var vc={};_(vc,{SESSION_FILE:()=>nt,archiveSession:()=>Tt,associateMessageWithTask:()=>bc,completeCurrentTask:()=>Zt,loadSession:()=>ar,saveSession:()=>xe,sessionState:()=>E,setCurrentTaskId:()=>Qt,startNewTask:()=>No});import{writeFileSync as gg,existsSync as wc}from"fs";function pi(){return{sessionId:ui(),messages:[],tasks:[],currentTask:null,currentTaskId:null,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}}function mg(){try{E.messages&&E.messages.length>0&&Cc(E)&&S("\u4F1A\u8BDD\u5DF2\u5F52\u6863"),E=pi(),new $e(nt).create(E)}catch(o){let e=o instanceof Error?o.message:String(o);O(`Failed to archive session - ${e}`,"Session"),E=pi();try{new $e(nt).create(E)}catch{}}}function ar(){try{if(wc(nt)){let e=new Ie(nt).readAllSync(),t=e.length>0?e[0]:null;return E={sessionId:t&&t.sessionId||ui(),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);O(`Could not load session - ${e}`,"Session")}return!1}function No(o){let e=Oo(),t={id:e,description:o,createdAt:new Date().toISOString(),messageIds:[]};return E.tasks.push(t),E.currentTask=o,E.currentTaskId=e,e}function bc(o){if(E.currentTaskId&&o){let e=E.currentTaskId;o.taskId=e;let t=E.tasks.find(n=>n.id===e);if(t&&!o.id){let n=vt();o.id=n,t.messageIds.push(n)}}return o}function Qt(o){E.currentTaskId=o,E.updatedAt=new Date().toISOString(),xe(),me(`\u5F53\u524D\u4EFB\u52A1ID\u5DF2\u8BBE\u7F6E\u4E3A: ${o}`,"Session")}function xe(o,e=null){try{if(e&&e!==E.currentTask&&No(e),o){let n=o.map(r=>bc({...r}));E={...E,messages:n,updatedAt:new Date().toISOString()}}else E={...E,updatedAt:new Date().toISOString()};wc(nt)&&gg(nt,"","utf-8"),new $e(nt).create(E)}catch(t){let n=t instanceof Error?t.message:String(t);O(`Could not save session - ${n}`,"Session")}}function Tt(){return mg()}function dg(){if(E.currentTask&&E.currentTaskId){let o=E.tasks.find(e=>e.id===E.currentTaskId);if(o){let e=o.tokenCount||0;W(`\u4EFB\u52A1\u5B8C\u6210: ${E.currentTask}`,"Session"),me(`Token\u603B\u5F00\u9500: ${e.toLocaleString()} tokens`,"Session")}E.currentTask=null,E.currentTaskId=null,xe()}}function Zt(){return dg()}var nt,E,Ve=C(()=>{tt();V();He();li();rr();_o();nt=Te("session.jsonl");E=pi()});var gi,Tc=C(()=>{gi={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,15 +210,15 @@ 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={};O(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=y(()=>{je();Or=null});var nt,jr=y(()=>{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=y(()=>{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 en={};_(en,{LITE_MODEL:()=>Be,MODEL:()=>ce,getDefaultModelConfig:()=>Pt,getLiteModelConfig:()=>cr,getLiteModelMaxToken:()=>hi,getMCPServerConfigs:()=>lr,getMaxToken:()=>fi,getProvider:()=>yg,isInkMode:()=>mi,setInkMode:()=>Wo});import{readFileSync as fg}from"fs";function Wo(o){Pc=o}function mi(){return Pc}function di(){if(!Uo)try{let o=Te("config.json"),e=fg(o,"utf-8");Uo=JSON.parse(e)}catch(o){console.error("Failed to load config.json:",o.message),Uo={models:{defaultModel:{apiKey:"",authToken:"",baseURL:"https://api.openai.com/v1",model:"gpt-4o-mini",provider:"openai"}}}}return Uo}function Pt(){let o=di(),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 cr(){let e=di().models?.liteModel||Pt();return e.provider==="anthropic"&&e.disableExperimentalBetas===void 0&&(e.disableExperimentalBetas=!0),e}function Ec(){return Pt().model||"gpt-4o-mini"}function hg(){return cr().model||Ec()}function yg(){return Pt().provider||"openai"}function ce(){return Ec()}function Be(){return hg()}function fi(){return Pt().maxToken||128e3}function hi(){return cr().maxToken||16385}function lr(){return di().mcpServers||[]}var Pc,Uo,ee=C(()=>{He();Pc=!1;Uo=null});var Et,zo=C(()=>{Et=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 xg from"openai";var yi,kc,$c=C(()=>{zo();yi=class extends Et{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 xg(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}
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=y(()=>{jr();K();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 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)}}}},kc=yi});var xi,Ic,Mc=C(()=>{zo();V();xi=class extends Et{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(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 v=[];if(f.content&&typeof f.content=="string"&&v.push({type:"text",text:f.content}),f.tool_calls&&f.tool_calls.length>0)for(let S of f.tool_calls)v.push({type:"tool_use",id:S.id,name:S.function.name,input:JSON.parse(S.function.arguments)});v.length>0&&g.push({role:"assistant",content:v}),d++}else if(f.role==="tool"){let v=[];for(;d<l.length&&l[d].role==="tool";){let S=l[d];v.push({type:"tool_result",tool_use_id:S.tool_call_id,content:S.content||"No result"}),d++}v.length>0&&g.push({role:"user",content:v})}else if(f.role==="user"){let v=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:v}),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);C(`[Anthropic Provider] Response content blocks: ${JSON.stringify(h.content,null,2)}`);let w=[],x="";for(let f of h.content)if(f.type==="text")x+=f.text;else if(f.type==="tool_use")C(`[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 v=f.thinking||"";v&&(x=v+(x?`
217
+ `)),l=l.filter(h=>h.role!=="system");let g=[],d=0;for(;d<l.length;){let h=l[d];if(h.role==="assistant"){let y=[];if(h.content&&typeof h.content=="string"&&y.push({type:"text",text:h.content}),h.tool_calls&&h.tool_calls.length>0)for(let T of h.tool_calls)y.push({type:"tool_use",id:T.id,name:T.function.name,input:JSON.parse(T.function.arguments)});y.length>0&&g.push({role:"assistant",content:y}),d++}else if(h.role==="tool"){let y=[];for(;d<l.length&&l[d].role==="tool";){let T=l[d];y.push({type:"tool_result",tool_use_id:T.tool_call_id,content:T.content||"No result"}),d++}y.length>0&&g.push({role:"user",content:y})}else if(h.role==="user"){let y=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: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 f=await c.messages.create(m);S(`[Anthropic Provider] Response content blocks: ${JSON.stringify(f.content,null,2)}`);let x=[],w="";for(let h of f.content)if(h.type==="text")w+=h.text;else if(h.type==="tool_use")S(`[Anthropic Provider] Tool use block: ${JSON.stringify({id:h.id,name:h.name,input:h.input,inputKeys:Object.keys(h.input||{})},null,2)}`),x.push({id:h.id,type:"function",function:{name:h.name,arguments:JSON.stringify(h.input)}});else if(h.type==="thinking"){let y=h.thinking||"";y&&(w=y+(w?`
218
218
 
219
- `+x:""))}return{choices:[{message:{content:x||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=y(()=>{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 P,U=y(()=>{P=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:x.length>0?x:void 0},finish_reason:f.stop_reason==="end_turn"?"stop":f.stop_reason}]}}},Ic=xi});var ur,Ac=C(()=>{ee();zo();$c();Mc();ur=class{static async getProvider(){let e=Pt();return this.createProvider(e)}static async getLiteProvider(){let e=cr();return this.createProvider(e)}static async createProvider(e){switch(e.provider||"openai"){case"anthropic":return new Ic(e);case"openai":default:return new kc(e)}}}});function tn(o){return o&&typeof o=="object"&&o.__tool_result===!0}function pr(o){return tn(o)?o.result:o}var $,U=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(tn(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=y(()=>{U();Ce=class extends P{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(`
221
+ `):String(e)}shouldPrintObservation(e){return tn(e)?e.shouldPrint:!0}}});var Re,gr=C(()=>{U();Re=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
222
  `);n=n.slice(0,s)+`
223
223
  - User confirmation is automatically required - DO NOT call askUser tool before calling this tool`+n.slice(s)}else{let s=n.indexOf(`
224
224
  `);s!==-1?n=n.slice(0,s)+`
@@ -226,7 +226,7 @@ ${t.content}`):t.content=n;return}try{let r=[];try{let s=JSON.parse(n);Array.isA
226
226
 
227
227
  `+n}else n=t+`
228
228
 
229
- `+n;return{...e,description:n,requiresConfirmation:!0}}getConfirmationMessage(e){return null}}});var cs={};O(cs,{BaseTool:()=>P,ConfirmableTool:()=>Ce,extractToolResult:()=>xn,isToolResult:()=>bt});var ls=y(()=>{U();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=y(()=>{U();Tt=class extends P{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 Ci={};_(Ci,{BaseTool:()=>$,ConfirmableTool:()=>Re,extractToolResult:()=>pr,isToolResult:()=>tn});var Si=C(()=>{U();gr()});import{readFileSync as Rc,statSync as Cg}from"fs";import{resolve as Sg}from"path";function mr(o){let e=typeof o=="string"?{path:o}:o;return Lc.execute(e)}var nn,Lc,dr,jc=C(()=>{U();nn=class extends ${lastReadPath="";getDefinition(){return{name:"read",description:`Read content from a specified file path.
230
230
 
231
231
  \u{1F4CB} USE CASES:
232
232
  - View file content for analysis or editing
@@ -242,23 +242,29 @@ ${t.content}`):t.content=n;return}try{let r=[];try{let s=JSON.parse(n);Array.isA
242
242
 
243
243
  \u{1F4A1} EXAMPLES:
244
244
  - read({ path: "package.json" }) - Read entire package.json file
245
+ - read({ path: ["package.json", "tsconfig.json"] }) - Read multiple files in one call
245
246
  - read({ path: "large.log", autoChunk: true }) - Read large log file in chunks
246
- - read({ path: "config.json", silent: true }) - Verify config.json exists
247
+ - read({ path: ["config.json", ".env"], silent: true }) - Verify multiple files exist
248
+ - read({ path: "src/**/*.ts", silent: true }) - Verify multiple TypeScript files exist
247
249
 
248
250
  \u{1F4DD} RETURN VALUE:
249
251
  - Complete file content as string (for small files)
250
252
  - 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,`
253
+ - Success message (with silent: true)`,input_schema:{type:"object",properties:{path:{oneOf:[{type:"string",description:"Single file path to read (relative or absolute)"},{type:"array",items:{type:"string",description:"File path to read (relative or absolute)"},description:"Multiple file paths to read in one call"}],description:"File path(s) 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=Array.isArray(e.path)?e.path:[e.path],n={},r=[];for(let s of t){let i=s.trim(),a=Sg(i);this.lastReadPath=i;try{if(e.silent)Rc(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=Rc(a,"utf-8");if(e.chunkSize||e.autoChunk){let p=Cg(a).size,g=1024*1024,d=5*1024*1024,m=e.chunkSize||g;if(e.autoChunk&&p<=d)n[i]=c;else{m=Math.max(1,m);let f=[];for(let x=0;x<c.length;x+=m)f.push(c.slice(x,x+m));n[i]=f,r.push(`\u6587\u4EF6 ${i} \u5DF2\u5206\u5757\u8BFB\u53D6\uFF0C\u5171 ${f.length} \u5757\uFF0C\u6BCF\u5757 ${m} \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 s=t[0].trim(),i=n[s];return typeof i=="string"&&i.startsWith("Error:")?this.createToolResult(i,i,!0):i}return this.createToolResult(n,r.join(`
254
+ `),!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(`
255
+ `).length;return`\u8BFB\u53D6\u6587\u4EF6 ${this.lastReadPath}\uFF0C\u5171 ${n} \u884C`}return super.formatObservation(e)}},Lc=new nn;dr=Lc});import{EOL as rn}from"os";function fr(o,e={}){let{preserveEscapes:t=!1,targetFormat:n="lf"}=e,r=o;if(t||(r=r.replace(/\\n/g,`
256
+ `).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\"/g,'"').replace(/\\'/g,"'")),r=r.replace(/\r\n/g,`
254
257
  `).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=y(()=>{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=y(()=>{U();kt=class extends P{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=y(()=>{gs();ps();U();Et=class extends P{getDefinition(){return{name:"write",description:`Write content to a file - ONLY for creating NEW files.
258
+ `),n!=="preserve"&&n!=="lf")switch(n){case"crlf":r=r.replace(/\n/g,`\r
259
+ `);break;case"cr":r=r.replace(/\n/g,"\r");break;case"platform":rn===`\r
260
+ `&&(r=r.replace(/\n/g,`\r
261
+ `));break}return r}function hr(o){if(!o)return{style:"none",dominant:rn,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:rn,statistics:e,confidence:0};let n=`
262
+ `,r=e.lf,s="lf";e.crlf>r&&(n=`\r
263
+ `,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 Ho,Dc,Vo=C(()=>{Ho=class{originalContent;normalizedContent;originalStyle;constructor(e){this.originalContent=e,this.originalStyle=hr(e),this.normalizedContent=fr(e,{preserveEscapes:!0,targetFormat:"lf"})}getNormalizedContent(){return this.normalizedContent}getOriginalStyle(){return this.originalStyle}restoreLineEndings(e){return this.originalStyle.style==="crlf"||this.originalStyle.dominant===`\r
264
+ `?e.replace(/\n/g,`\r
265
+ `):this.originalStyle.style==="cr"||this.originalStyle.dominant==="\r"?e.replace(/\n/g,"\r"):e}convertTo(e){return fr(this.originalContent,{preserveEscapes:!0,targetFormat:e})}},Dc={get current(){return rn},get isWindows(){return rn===`\r
266
+ `},get isUnix(){return rn===`
267
+ `},toPlatformFormat(o){return fr(o,{preserveEscapes:!0,targetFormat:"platform"})}}});import{mkdirSync as wg}from"fs";import{resolve as bg}from"path";function yr(o){return Fc.execute(o)}var on,Fc,kt,wi=C(()=>{U();on=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=bg(e.path);return wg(t,{recursive:!0}),`Directory created: ${e.path}`}catch(t){return this.formatError(`Cannot create directory ${e.path}`,t)}}},Fc=new on;kt=Fc});import{readFileSync as vg,writeFileSync as Oc,existsSync as Tg}from"fs";import{resolve as Pg,dirname as Eg}from"path";function xr(o){return _c.execute(o)}var sn,_c,Cr,Nc=C(()=>{Vo();wi();U();sn=class extends ${getDefinition(){return{name:"write",description:`Write content to a file - ONLY for creating NEW files.
262
268
 
263
269
  \u{1F4CB} USE CASES:
264
270
  - Create brand new files that don't exist yet
@@ -291,9 +297,9 @@ echo 'test'" }) - Create new shell script
291
297
 
292
298
  \u{1F4DD} RETURN VALUE:
293
299
  - "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
300
+ - 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=Pg(e.path),n=Eg(t),r=kt.execute({path:n});if(r.startsWith("Error:"))return r;let s=fr(e.content,{preserveEscapes:!1,targetFormat:"lf"});typeof s!="string"&&(s=String(s||""));let i=Dc.current;if(Tg(t)){let a=vg(t,"utf-8");i=hr(a).dominant;let l=`${t}.base`;Oc(l,a,"utf-8")}return i===`\r
295
301
  `&&(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=y(()=>{Sn();Pt=class extends Ce{getBaseDefinition(){return{name:"delete",description:`Delete a file, multiple files or directories at the specified path(s).
302
+ `)),Oc(t,s,"utf-8"),"done"}catch(t){return this.formatError(`Cannot write ${e.path}`,t)}}},_c=new sn;Cr=_c});import{unlinkSync as kg,existsSync as $g,statSync as Ig,rmdirSync as Mg}from"fs";import{resolve as Ag}from"path";function Sr(o){return typeof o=="object"&&o!==null&&"path"in o?bi.execute(o):bi.execute({path:o})}var an,bi,wr,Uc=C(()=>{gr();an=class extends Re{getBaseDefinition(){return{name:"delete",description:`Delete a file, multiple files or directories at the specified path(s).
297
303
 
298
304
  IMPORTANT:
299
305
  - This action cannot be undone
@@ -305,31 +311,31 @@ Examples:
305
311
  - deleteFile("temp.txt") - delete a single file named temp.txt
306
312
  - deleteFile("temp_dir") - delete a single empty directory named temp_dir
307
313
  - 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(`
314
+ - 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=Ag(l);if(!$g(u)){n.push(`Warning: Path not found - ${l}`);continue}Ig(u).isDirectory()?(Mg(u),n.push(`Directory deleted: ${l}`)):(kg(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(`
309
315
  `)}
310
316
 
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=y(()=>{Sn();$t=class extends Ce{getBaseDefinition(){return{name:"move",description:`Move or rename a file or directory from source to destination.
317
+ Summary: ${c} items deleted (${r} files, ${s} directories), ${a} warnings, ${i} errors`}catch(t){return this.formatError("Cannot process delete operation",t)}}},bi=new an;wr=bi});import{renameSync as Rg,existsSync as Bo,statSync as Lg,mkdirSync as jg}from"fs";import{resolve as Wc,dirname as Dg}from"path";function br(o){return o&&typeof o=="object"&&"source"in o&&"destination"in o?zc.execute(o):"Error: Invalid input format. Expected { source: string, destination: string }"}var cn,zc,vr,Hc=C(()=>{gr();cn=class extends Re{getBaseDefinition(){return{name:"move",description:`Move or rename a file or directory from source to destination.
312
318
 
313
319
  Examples:
314
320
  - moveFile({ source: "old.txt", destination: "new.txt" }) - rename a file
315
321
  - moveFile({ source: "file.txt", destination: "folder/file.txt" }) - move a file to a different directory
316
322
  - 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=y(()=>{Sn();Mt=class extends Ce{getBaseDefinition(){return{name:"copy",description:`Copy a file or directory from source to destination.
323
+ - 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=Wc(t),s=Wc(n);if(!Bo(r))return`Error: Source path does not exist - ${t}`;if(Bo(s))return`Error: Destination already exists - ${n}`;let i=Dg(s);return Bo(i)||jg(i,{recursive:!0}),Rg(r,s),Bo(s)?`${Lg(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)}}},zc=new cn;vr=zc});import{existsSync as Go,statSync as Vc,readFileSync as Bc,writeFileSync as Gc,mkdirSync as Jc,readdirSync as Fg}from"fs";import{resolve as qc,join as Kc,dirname as Og}from"path";function Tr(o){return o&&typeof o=="object"&&"source"in o&&"destination"in o?Xc.execute(o):"Error: Invalid input format. Expected { source: string, destination: string }"}var ln,Xc,Pr,Yc=C(()=>{gr();ln=class extends Re{getBaseDefinition(){return{name:"copy",description:`Copy a file or directory from source to destination.
318
324
 
319
325
  Examples:
320
326
  - copyFile({ source: "file.txt", destination: "file_copy.txt" }) - copy a file
321
327
  - copyFile({ source: "file.txt", destination: "folder/file.txt" }) - copy a file to a different directory
322
328
  - 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(`
329
+ - 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=qc(t),s=qc(n);if(!Go(r))return`Error: Source path does not exist - ${t}`;if(r===s)return"Error: Source and destination paths are identical";let i=Vc(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=Og(s);return Go(l)||Jc(l,{recursive:!0}),Gc(s,Bc(r)),Go(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){Go(t)||(Jc(t,{recursive:!0}),r++),Fg(e).forEach(i=>{let a=Kc(e,i),c=Kc(t,i);Vc(a).isDirectory()?this.copyDirectory(a,c,n,r):(Gc(c,Bc(a)),n++)})}},Xc=new ln;Pr=Xc});import{diff3Merge as _g}from"node-diff3";function Qc(o,e,t){let n=o.split(`
324
330
  `),r=e.split(`
325
331
  `),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(`
332
+ `);We(` [merge] \u5F00\u59CB\u4E09\u8DEF\u5408\u5E76: base=${n.length}\u884C, current=${r.length}\u884C, incoming=${s.length}\u884C`,"merge");let i=Date.now(),a=_g(r,n,s,{excludeFalseConflicts:!0}),c=((Date.now()-i)/1e3).toFixed(2);We(` [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,d=p.conflict.a||[],m=p.conflict.o||[],f=p.conflict.b||[];u.push({lineNumber:g,base:m.join(`
327
333
  `),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=y(()=>{});import{readFileSync as Ma,writeFileSync as Vr,existsSync as ms,unlinkSync as fs}from"fs";import{resolve as Mu}from"path";function hs(o){return o.replace(/\r\n/g,`
334
+ `),incoming:f.join(`
335
+ `)}),l.push("<<<<<<< CURRENT"),l.push(...d),l.push("======="),l.push(...f),l.push(">>>>>>> INCOMING")}return{merged:l.join(`
336
+ `),hasConflicts:u.length>0,conflicts:u}}var Zc=C(()=>{tt()});import{readFileSync as el,writeFileSync as Jo,existsSync as vi,unlinkSync as Ti}from"fs";import{resolve as Ng}from"path";function Pi(o){return o.replace(/\r\n/g,`
331
337
  `).replace(/\r/g,`
332
- `)}function Ln(o){return Ia.execute(o)}var Iu,It,Ia,Rn,Aa=y(()=>{gs();$a();U();Iu={lineRatioThreshold:.5,minLineDiff:100},It=class extends P{getDefinition(){return{name:"merge",description:`Smart file merge tool - THE SAFE CHOICE for modifying existing files.
338
+ `)}function Er(o){return tl.execute(o)}var Ug,un,tl,kr,nl=C(()=>{Vo();Zc();U();Ug={lineRatioThreshold:.5,minLineDiff:100},un=class extends ${getDefinition(){return{name:"merge",description:`Smart file merge tool - THE SAFE CHOICE for modifying existing files.
333
339
 
334
340
  \u{1F4CB} USE CASES:
335
341
  - Update existing files without losing concurrent changes
@@ -372,7 +378,7 @@ Examples:
372
378
  \u{1F4DD} RETURN VALUE:
373
379
  - "Merge successful" messages on success
374
380
  - 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).
381
+ - 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=Ug){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).
376
382
 
377
383
  This may indicate:
378
384
  - Incomplete content (missing parts of the file)
@@ -380,30 +386,20 @@ This may indicate:
380
386
  - Wrong file content
381
387
 
382
388
  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 x=this.checkLargeDeletion(c,l);if(x.isLargeDeletion)return console.log(` [MergeTool] \u68C0\u6D4B\u5230\u5927\u5E45\u5220\u51CF\uFF08${c} \u2192 ${l}\u884C\uFF09\uFF0C\u9700\u8981\u786E\u8BA4`),x.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 x=a;if(s===`\r
387
- `&&(x=x.replace(/\n/g,`\r
388
- `)),Vr(t,x,"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
389
+ 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=Ng(e.path),n=`${t}.base`;if(!vi(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=el(t,"utf-8");console.log(` [MergeTool] \u5F53\u524D\u6587\u4EF6\u5927\u5C0F: ${r.length} \u5B57\u7B26`);let i=hr(r).dominant;console.log(` [MergeTool] \u68C0\u6D4B\u5230\u884C\u7ED3\u675F\u7B26: ${i===`\r
390
+ `?"CRLF":"LF"}`);let a=Pi(r),c=Pi(e.newContent),l=a.split(`
391
+ `).length,u=c.split(`
392
+ `).length;if(!e.confirmLargeChange){let v=this.checkLargeDeletion(l,u);if(v.isLargeDeletion)return console.log(` [MergeTool] \u68C0\u6D4B\u5230\u5927\u5E45\u5220\u51CF\uFF08${l} \u2192 ${u}\u884C\uFF09\uFF0C\u9700\u8981\u786E\u8BA4`),v.message}let p=r,g=!1;vi(n)&&(console.log(" [MergeTool] \u53D1\u73B0\u57FA\u7840\u7248\u672C\u6587\u4EF6\uFF0C\u8BFB\u53D6\u4E2D..."),p=el(n,"utf-8"),g=!0,console.log(` [MergeTool] \u57FA\u7840\u7248\u672C\u5927\u5C0F: ${p.length} \u5B57\u7B26`));let d=Pi(p);if(d===a){console.log(" [MergeTool] \u65E0\u5E76\u53D1\u4FEE\u6539\uFF08base === current\uFF09\uFF0C\u76F4\u63A5\u5199\u5165");let v=c;if(i===`\r
393
+ `&&(v=v.replace(/\n/g,`\r
394
+ `)),Jo(t,v,"utf-8"),g)try{Ti(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=${d.split(`
395
+ `).length}\u884C, current=${l}\u884C, incoming=${u}\u884C`);let m=Date.now(),f=Qc(d,a,c),x=((Date.now()-m)/1e3).toFixed(2);console.log(` [MergeTool] threeWayMerge \u5B8C\u6210\uFF0C\u8017\u65F6 ${x}s, \u6709\u51B2\u7A81: ${f.hasConflicts}`);let w=f.merged;if(i===`\r
390
396
  `&&(w=w.replace(/\n/g,`\r
391
- `)),m.hasConflicts)return Vr(t,w,"utf-8"),`Merge completed with CONFLICTS. File saved with conflict markers.
397
+ `)),f.hasConflicts)return Jo(t,w,"utf-8"),`Merge completed with CONFLICTS. File saved with conflict markers.
392
398
  Conflicts:
393
- ${m.conflicts.map(k=>`Line ${k.lineNumber}: BASE="${k.base.substring(0,50)}..." | CURRENT="${k.current.substring(0,50)}..." | INCOMING="${k.incoming.substring(0,50)}..."`).join(`
399
+ ${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
400
  `)}
395
401
 
396
- Please resolve conflicts manually or use write() to overwrite.`;if(Vr(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(Vr(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 Wr,Ra=y(()=>{Wr=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=y(()=>{U();Ra();At=class extends P{getDefinition(){return{name:"searchReplace",description:`Perform TARGETED SEARCH & REPLACE operations on files.
402
+ Please resolve conflicts manually or use write() to overwrite.`;if(Jo(t,w,"utf-8"),g)try{Ti(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(Jo(e,r,"utf-8"),vi(t))try{Ti(t)}catch{}return`File created: ${e}`}catch(r){return this.formatError("Failed to create file",r)}}},tl=new un;kr=tl});import{existsSync as Wg,readFileSync as zg,writeFileSync as Hg}from"fs";import{resolve as Vg}from"path";function $r(o){return rl.execute(o)}var pn,rl,Ir,ol=C(()=>{U();Vo();pn=class extends ${getDefinition(){return{name:"searchReplace",description:`Perform TARGETED SEARCH & REPLACE operations on files.
407
403
 
408
404
  \u{1F3AF} PERFECT FOR:
409
405
  - Small configuration updates (port numbers, URLs, etc.)
@@ -424,18 +420,16 @@ Please resolve conflicts manually or use write() to overwrite.`;if(Vr(t,w,"utf-8
424
420
  \u{1F4A1} TIPS:
425
421
  - Use precise search text to avoid unintended replacements
426
422
  - 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 Wr(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);(s.style==="crlf"||s.dominant===`\r
428
- `)&&(p=p.replace(/\n/g,`\r
429
- `)),Du(t,p,"utf-8")}let l=`Search/replace completed. ${a} of ${e.operations.length} operations applied successfully.`,u=c.length>0?`
423
+ - 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=Vg(e.path);if(!Wg(t))return this.formatError("SearchReplace",`File not found: ${t}`);let n=zg(t,"utf-8"),r=new Ho(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(f){c.push(`\u274C Operation ${p+1}: ${f instanceof Error?f.message:String(f)}`)}}if(a>0){let p=r.restoreLineEndings(i);Hg(t,p,"utf-8")}let l=`Search/replace completed. ${a} of ${e.operations.length} operations applied successfully.`,u=c.length>0?`
430
424
 
431
425
  Operation details:
432
426
  ${c.join(`
433
- `)}`:"";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 X,Ae=y(()=>{X=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=y(()=>{Ae();zr=class extends X{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:
434
- ${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(`
435
- `);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=y(()=>{Ae();Hr=class extends X{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=y(()=>{Ae();Jr=class extends X{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(`
427
+ `)}`:"";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}`}},rl=new pn;Ir=rl});var re,Ge=C(()=>{re=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:s}=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(s(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:s}=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 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 Ei,readFileSync as Bg}from"fs";import{resolve as ki}from"path";var qo,sl=C(()=>{Ge();qo=class extends re{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=ki(e,"package.json");if(Ei(r))try{let s=Bg(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}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 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}}]})}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"),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=ki(t,"tsconfig.json");if(!Ei(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:
428
+ ${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=>Ei(ki(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(`
429
+ `);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 gn,writeFileSync as Gg,mkdirSync as Jg}from"fs";import{resolve as $i,dirname as qg}from"path";var Ko,il=C(()=>{Ge();Ko=class extends re{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:s}=await import("fs/promises"),{resolve:i}=await import("path"),a=i(e,"pom.xml");if(r(a))try{let u=await s(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 s(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 s(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=$i(e,"pom.xml"),s=$i(e,"build.gradle"),i=$i(e,"build.gradle.kts");if(!gn(r)&&!gn(s)&&!gn(i))return n;gn(r)?await this.analyzeMavenDependencies(r,n):gn(s)?await this.analyzeGradleDependencies(s,n):gn(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"),s=await import("xml2js");return new Promise((i,a)=>{s.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(d=>{t.dependencies.push({groupId:d.groupId,artifactId:d.artifactId,version:d.version||"unknown",scope:d.scope||"compile",type:d.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[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`;Jg(qg(n),{recursive:!0}),Gg(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 Mr,readFileSync as Ii}from"fs";import{resolve as Ar}from"path";var Xo,al=C(()=>{Ge();Xo=class extends re{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=Ar(e,".python-version");if(Mr(r))try{let a=Ii(r,"utf-8");n.Python=a.trim()}catch{}let s=Ar(e,"pyproject.toml");if(Mr(s))try{let c=Ii(s,"utf-8").match(/python\s*=\s*['"]([^'"]+)['"]/);c&&(n.Python=c[1])}catch{}let i=Ar(e,"setup.py");if(Mr(i))try{let c=Ii(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 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(f=>f.trim()),m=d.replace(/\./g,"/").replace(":","/")+".py";s.push(m)})}}return s}}]})}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)]),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=>Mr(Ar(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=>Mr(Ar(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(`
436
430
  `);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(`
437
431
  `);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(`
438
- `);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 Va}from"path";var Gr,Wa=y(()=>{Ae();Gr=class extends X{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=Va(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=Va(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 Vu}from"fs";import{resolve as Wu}from"path";var Br,za=y(()=>{Ae();Br=class extends X{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=Wu(e,"Cargo.toml");if(Uu(r))try{let i=Vu(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=y(()=>{Ae();qr=class extends X{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=y(()=>{Ae();Kr=class extends X{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=y(()=>{Ae();Yr=class extends X{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=y(()=>{Oa();ja();_a();Wa();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=y(()=>{U();bs();Rt=class extends P{getDefinition(){return{name:"validate",description:`Validate code files for syntax errors, type errors, and code style issues.
432
+ `);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 cl,readFileSync as ll}from"fs";import{resolve as ul}from"path";var Yo,pl=C(()=>{Ge();Yo=class extends re{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=ul(e,"go.mod");if(cl(r))try{let a=ll(r,"utf-8").match(/^go\s+(\d+\.\d+)/m);a&&(n.Go=a[1])}catch{}let s=ul(e,"go.sum");if(cl(s))try{let a=ll(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}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 Kg,readFileSync as Xg}from"fs";import{resolve as Yg}from"path";var Qo,gl=C(()=>{Ge();Qo=class extends re{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=Yg(e,"Cargo.toml");if(Kg(r))try{let i=Xg(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 ml,readFileSync as dl}from"fs";import{resolve as fl}from"path";var Zo,hl=C(()=>{Ge();Zo=class extends re{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=fl(e,"composer.json");if(ml(r))try{let i=dl(r,"utf-8"),a=JSON.parse(i);a.require&&a.require.php&&(n.PHP=a.require.php)}catch{}let s=fl(e,".php-version");if(ml(s))try{let i=dl(s,"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 yl,readFileSync as xl}from"fs";import{resolve as Cl}from"path";var es,Sl=C(()=>{Ge();es=class extends re{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=Cl(e,".ruby-version");if(yl(r))try{let i=xl(r,"utf-8");n.Ruby=i.trim()}catch{}let s=Cl(e,"Gemfile");if(yl(s))try{let a=xl(s,"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 Qg,readFileSync as wl}from"fs";import{resolve as bl}from"path";import{globSync as Mi}from"glob";var ts,vl=C(()=>{Ge();ts=class extends re{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=[...Mi("*.csproj",{cwd:e}),...Mi("*.vbproj",{cwd:e}),...Mi("*.fsproj",{cwd:e})];for(let i of r)try{let a=bl(e,i),c=wl(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=bl(e,"global.json");if(Qg(s))try{let i=wl(s,"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 Ai,rt,Ri=C(()=>{sl();il();al();pl();gl();hl();Sl();vl();Ai=class o{static instance;handlers=new Map;constructor(){this.registerHandlers()}static getInstance(){return o.instance||(o.instance=new o),o.instance}registerHandlers(){[new qo,new Ko,new Xo,new Yo,new Qo,new Zo,new es,new ts].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):{}}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 s of e){let i=await this.detectVersions(s,t,n);Object.assign(r,i)}return r}async findEntryPointsForLanguages(e,t,n){let r=[];for(let s of e){let i=await this.findEntryPoints(s,t,n);r.push(...i)}return[...new Set(r)]}async detectCodeStandardsForLanguages(e,t){let n=[];for(let r of e){let s=await 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"}},rt=Ai.getInstance()});import{resolve as Zg}from"path";import{existsSync as em}from"fs";async function Rr(o){return await Tl.execute(o)}var mn,Tl,Lr,Pl=C(()=>{U();Ri();mn=class extends ${getDefinition(){return{name:"validate",description:`Validate code files for syntax errors, type errors, and code style issues.
439
433
 
440
434
  \u{1F4CB} USE CASES:
441
435
  - Verify generated code has no syntax errors
@@ -465,7 +459,7 @@ ${s}`}:{valid:!1,message:`TypeScript validation failed with ${i.length} error(s)
465
459
  - read: View the content of files before or after validation
466
460
  - merge: Modify files to fix validation errors
467
461
  - searchReplace: Batch fix validation errors across multiple files
468
- - 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}
462
+ - 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=Zg(e.path);if(!em(t))return`Error: File not found: ${e.path}`;let n=process.cwd(),r=await rt.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}
469
463
  ${e.message}`;return e.warnings&&e.warnings.length>0&&(n+=`
470
464
 
471
465
  \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+=`
@@ -476,15 +470,36 @@ Errors (${e.errors.length}):`,e.errors.forEach((r,s)=>{let i=r.line?`Line ${r.li
476
470
  ${s+1}. [${i}] ${r.message}`,r.code&&(n+=` (${r.code})`)})),e.warnings&&e.warnings.length>0&&(n+=`
477
471
 
478
472
  Warnings (${e.warnings.length}):`,e.warnings.forEach((r,s)=>{let i=r.line?`Line ${r.line}${r.column?`:${r.column}`:""}`:"Unknown location";n+=`
479
- ${s+1}. [${i}] ${r.message}`,r.code&&(n+=` (${r.code})`)})),n}}},tc=new Rt;Un=tc});var Ts={};O(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=y(()=>{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(`
480
- `).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=y(()=>{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 Vn(o){return oc.execute(o)}var Ft,oc,Wn,sc=y(()=>{U();Dt();Ft=class extends P{getDefinition(){return{name:"glob",description:`Search for files matching a glob pattern.
473
+ ${s+1}. [${i}] ${r.message}`,r.code&&(n+=` (${r.code})`)})),n}}},Tl=new mn;Lr=Tl});var Li={};_(Li,{CopyTool:()=>ln,DeleteTool:()=>an,MergeTool:()=>un,MkdirTool:()=>on,MoveTool:()=>cn,ReadTool:()=>nn,SearchReplaceTool:()=>pn,ValidateTool:()=>mn,WriteTool:()=>sn,copyFile:()=>Tr,copyTool:()=>Pr,deleteFile:()=>Sr,deleteTool:()=>wr,merge:()=>Er,mergeTool:()=>kr,mkdir:()=>yr,mkdirTool:()=>kt,moveFile:()=>br,moveTool:()=>vr,read:()=>mr,readTool:()=>dr,searchReplace:()=>$r,searchReplaceTool:()=>Ir,validate:()=>Rr,validateTool:()=>Lr,write:()=>xr,writeTool:()=>Cr});var ns=C(()=>{jc();Nc();wi();Uc();Hc();Yc();nl();ol();Pl()});import{readFileSync as tm,existsSync as nm}from"fs";import{resolve as rm}from"path";function sm(o){let e=rm(o,".niumignore"),t=[];if(nm(e))try{tm(e,"utf-8").split(`
474
+ `).forEach(r=>{let s=r.trim();s&&!s.startsWith("#")&&t.push(im(s))})}catch(n){console.warn(`Error reading .niumignore file: ${n instanceof Error?n.message:"Unknown error"}`)}return t}function ge(o,e=!0){let t=sm(o);return e?[...om,...t]:t}function im(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 om,Je=C(()=>{om=["**/.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 El}from"glob";function jr(o){return kl.execute(o)}var dn,kl,Dr,$l=C(()=>{U();Je();dn=class extends ${getDefinition(){return{name:"glob",description:`Search for files matching glob patterns with advanced filtering and ignore support.
481
475
 
482
- Examples:
483
- - glob("*.js") - all .js files in current directory
484
- - glob("**/*.ts") - all .ts files recursively
485
- - glob("src/**/*.{js,ts}") - all .js and .ts files under src/
476
+ \u{1F4CB} USE CASES:
477
+ - Find all files of a specific type across the project
478
+ - Locate configuration files in multiple directories
479
+ - Identify test files for a specific component
480
+ - Find all files modified recently
481
+ - Search for files with specific naming patterns
482
+
483
+ \u{1F511} PARAMETERS:
484
+ - pattern: Glob pattern to match (supports **/*.js, *.{js,ts}, etc.)
485
+ - cwd: Optional working directory to search from (defaults to current directory)
486
+
487
+ \u{1F4A1} EXAMPLES:
488
+ - glob({ pattern: "*.js" }) - Find all JavaScript files in current directory
489
+ - glob({ pattern: ["*.js", "*.ts"] }) - Find all JS and TS files in one call
490
+ - glob({ pattern: "**/*.ts" }) - Find all TypeScript files recursively
491
+ - glob({ pattern: "src/**/*.{js,ts}" }) - Find all JS/TS files under src/
492
+ - glob({ pattern: ["**/test*.{js,ts}", "**/*.spec.{js,ts}"] }) - Find all test files with multiple patterns
493
+ - glob({ pattern: [".env*", ".config*"] }) - Find all environment and config files
494
+ - glob({ pattern: "src/components/**/*.tsx", cwd: "/project" }) - Find React components in specific directory
486
495
 
487
- 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;Wn=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=y(()=>{U();Dt();K();Ot=class extends P{getDefinition(){return{name:"grep",description:`Search for text patterns in files using regular expressions with glob support.
496
+ \u{1F4DD} RETURN VALUE:
497
+ - Array of matching file paths (relative to the search directory)
498
+ - Sorted list for consistent results
499
+ - Automatic filtering of ignored files (using .niumignore and default ignore patterns)
500
+ - Support for complex patterns with braces and negation
501
+ - Empty array if no matches found
502
+ - Helpful error messages for invalid patterns`,input_schema:{type:"object",properties:{pattern:{oneOf:[{type:"string",description:'Single glob pattern to match (e.g., "*.js", "**/*.ts")'},{type:"array",items:{type:"string",description:'Glob pattern to match (e.g., "*.js", "**/*.ts")'},description:'Multiple glob patterns to match in one call (e.g., ["*.js", "*.ts"], [".env*", ".config*"])'}],description:"Glob pattern(s) to match"},cwd:{type:"string",description:"Optional working directory to search from (defaults to current directory)"}},required:["pattern"]}}}execute(e){try{let t=e.cwd||process.cwd(),n=ge(t),r=Array.isArray(e.pattern)?e.pattern:[e.pattern],s=[],i=new Set;return r.forEach(a=>{try{let c=El(a,{nodir:!0,cwd:e.cwd,ignore:n});if(c.length===0&&!a.startsWith("*")&&!a.startsWith("**")){let l=`**/${a}`;c=El(l,{nodir:!0,cwd:e.cwd,ignore:n})}c.forEach(l=>i.add(l))}catch(c){console.error(`Error processing glob pattern ${a}: ${c instanceof Error?c.message:"Unknown error"}`)}}),s=Array.from(i),s.length>0?s:`No files matching patterns: ${r.join(", ")}`}catch(t){return this.formatError("Glob pattern",t)}}},kl=new dn;Dr=kl});import{readFileSync as Il}from"fs";import{dirname as am}from"path";import{globSync as cm}from"glob";function Fr(o){return Ml.execute(o)}var fn,Ml,Or,Al=C(()=>{U();Je();V();fn=class extends ${getDefinition(){return{name:"grep",description:`Search for text patterns in files using regular expressions with glob support.
488
503
 
489
504
  \u{1F4CB} USE CASES:
490
505
  - Find code patterns and function definitions
@@ -499,10 +514,10 @@ Returns an array of matching file paths.`,input_schema:{type:"object",properties
499
514
 
500
515
  \u{1F4A1} EXAMPLES:
501
516
  - grep({ pattern: "function.*foo", path: "src/main.js" }) - Find function definitions containing "foo" in a single file
502
- - grep({ pattern: "TODO", path: "**/*.js" }) - Find all TODOs in all JavaScript files
503
- - grep({ pattern: "import", path: "src/**/*.{js,ts}" }) - Find all import statements in JS/TS files
517
+ - grep({ pattern: ["TODO", "FIXME"], path: "**/*.js" }) - Find all TODOs and FIXMEs in one call
518
+ - grep({ pattern: ["import", "export"], path: "src/**/*.{js,ts}" }) - Find all import and export statements in one call
504
519
  - grep({ pattern: "class.*Component", path: "src/components/**/*.tsx" }) - Find React components
505
- - grep({ pattern: "error", path: "logs/**/*.log" }) - Search for errors in log files
520
+ - grep({ pattern: ["error", "warn", "debug"], path: "logs/**/*.log" }) - Search for multiple log levels in one call
506
521
 
507
522
  \u{1F4DD} RETURN VALUE:
508
523
  - Array of matching lines with filenames and line numbers
@@ -515,8 +530,8 @@ Returns an array of matching file paths.`,input_schema:{type:"object",properties
515
530
  - Cross-platform glob pattern matching
516
531
  - Ignores system and gitignore files
517
532
  - Case-sensitive matching (use regex flags for case-insensitive)
518
- - 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(C(`Processing glob pattern: ${e.path}`),t=Zu(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=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(`
519
- `),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=y(()=>{U();Dt();jt=class extends P{getDefinition(){return{name:"search-docs",description:`Search for content in documentation files using keywords and regular expressions.
533
+ - Handles large files efficiently`,input_schema:{type:"object",properties:{pattern:{oneOf:[{type:"string",description:"Single regular expression pattern to search for"},{type:"array",items:{type:"string",description:"Regular expression pattern to search for"},description:"Multiple regular expression patterns to search for in one call"}],description:"Regular expression pattern(s) to search for"},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("\\")?am(e.path):process.cwd(),c={nodir:!0,windowsPathsNoEscape:!0,absolute:!1,ignore:ge(i)};if(e.path.includes("*")||e.path.includes("?")||e.path.includes("{")){if(S(`Processing glob pattern: ${e.path}`),t=cm(e.path,c),t.length===0)return`No files found matching pattern: ${e.path}`;S(`Found ${t.length} files matching pattern`)}else try{let u=Il(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=Array.isArray(e.pattern)?e.pattern:[e.pattern],r=[],s=0;return n.forEach(i=>{try{let a=new RegExp(i),c=0;t.forEach(l=>{try{let p=Il(l,"utf-8").split(`
534
+ `),g=[];p.forEach((d,m)=>{a.test(d)&&(g.push(`${l}:${m+1}: ${d}`),c++,s++)}),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"}`)}}),s>0?(t.length>1&&r.unshift(`Found ${s} 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)}}},Ml=new fn;Or=Ml});import{readFileSync as lm,existsSync as um}from"fs";import{join as pm}from"path";import{globSync as gm}from"glob";function _r(o){return Rl.execute(o)}var hn,Rl,Nr,Ll=C(()=>{U();Je();hn=class extends ${getDefinition(){return{name:"search-docs",description:`Search for content in documentation files using keywords and regular expressions.
520
535
 
521
536
  \u{1F4CB} USE CASES:
522
537
  - Find information in project documentation
@@ -545,8 +560,8 @@ Returns an array of matching file paths.`,input_schema:{type:"object",properties
545
560
  \u{1F517} RELATED TOOLS:
546
561
  - read: View the full content of files found in search results
547
562
  - grep: Search for code patterns in source files (complementary to documentation search)
548
- - 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(`
549
- `).forEach((x,k)=>{if(u.test(x)){let f=this.calculateMatchScore(x,r,k);p.push({path:m,line:k+1,content:x.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=y(()=>{U();Dt();_t=class extends P{getDefinition(){return{name:"build-doc-index",description:`Build and update documentation index for efficient search.
563
+ - 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(!um(t))return`Documentation directory not found: ${t}`;let s=process.cwd(),a={nodir:!0,windowsPathsNoEscape:!0,absolute:!1,ignore:ge(s),cwd:s},c=pm(t,"**/*.{md,markdown,txt,rst,html,htm}"),l=gm(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{lm(m,"utf-8").split(`
564
+ `).forEach((w,v)=>{if(u.test(w)){let h=this.calculateMatchScore(w,r,v);p.push({path:m,line:v+1,content:w.trim(),score:h})}})}catch{}}),p.length===0)return`No matches found for query: ${r} in ${l.length} files`;p.sort((m,f)=>f.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}},Rl=new hn;Nr=Rl});import{readFileSync as jl,writeFileSync as mm,existsSync as dm,mkdirSync as fm}from"fs";import{join as Ur}from"path";import{globSync as hm}from"glob";function Wr(o={}){return Dl.execute(o)}var yn,Dl,zr,Fl=C(()=>{U();Je();yn=class extends ${getDefinition(){return{name:"build-doc-index",description:`Build and update documentation index for efficient search.
550
565
 
551
566
  \u{1F4CB} USE CASES:
552
567
  - Create initial documentation index
@@ -566,11 +581,11 @@ Returns an array of matching file paths.`,input_schema:{type:"object",properties
566
581
  - Success message with index statistics
567
582
  - Path to generated index file
568
583
  - Number of documents indexed
569
- - 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,x=this.extractDocMetadata(d,h,w);l.push(x)}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:
584
+ - 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=Ur(n,t);if(!dm(r))return`Documentation directory not found: ${r}`;let i={nodir:!0,windowsPathsNoEscape:!0,absolute:!1,ignore:ge(n),cwd:n},a=Ur(t,"**/*.{md,markdown,txt,rst,html,htm}"),c=hm(a,i);if(c.length===0)return`No documentation files found in: ${t}`;let l=[];c.forEach(d=>{try{let m=Ur(n,d),f=jl(m,"utf-8"),x=jl(m,"utf-8").length,w=this.extractDocMetadata(d,f,x);l.push(w)}catch{}});let u={documents:l,lastIndexed:new Date().toISOString(),totalDocuments:l.length},p=Ur(n,t);fm(p,{recursive:!0});let g=Ur(p,".index.json");return mm(g,JSON.stringify(u,null,2),"utf-8"),`Successfully built documentation index:
570
585
  - Index file: ${g}
571
586
  - Total documents indexed: ${u.totalDocuments}
572
587
  - Last indexed: ${u.lastIndexed}
573
- - 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={};O(ks,{BuildDocIndexTool:()=>_t,GlobTool:()=>Ft,GrepTool:()=>Ot,SearchDocsTool:()=>jt,buildDocIndex:()=>qn,buildDocIndexTool:()=>Kn,glob:()=>Vn,globTool:()=>Wn,grep:()=>zn,grepTool:()=>Hn,searchDocs:()=>Jn,searchDocsTool:()=>Gn});var Qr=y(()=>{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=y(()=>{U();Es=null,mc=!1;Nt=class o extends P{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.
588
+ - 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))}},Dl=new yn;zr=Dl});var ji={};_(ji,{BuildDocIndexTool:()=>yn,GlobTool:()=>dn,GrepTool:()=>fn,SearchDocsTool:()=>hn,buildDocIndex:()=>Wr,buildDocIndexTool:()=>zr,glob:()=>jr,globTool:()=>Dr,grep:()=>Fr,grepTool:()=>Or,searchDocs:()=>_r,searchDocsTool:()=>Nr});var rs=C(()=>{$l();Al();Ll();Fl()});import{execSync as ym,exec as xm,spawnSync as Ol}from"child_process";import*as os from"os";async function Nl(){if(_l)return Di;_l=!0;try{let o=await import("iconv-lite");return Di=o.default||o,Di}catch{return console.warn("iconv-lite not available, using utf8 fallback for Windows encoding"),null}}function Hr(o){return Promise.resolve(Cn.execute(o))}var Di,_l,xn,Cn,Ul=C(()=>{U();Di=null,_l=!1;xn=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=os.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.
574
589
 
575
590
  \u{1F30D} **\u667A\u80FD\u73AF\u5883\u611F\u77E5**
576
591
  \u6B64\u5DE5\u5177\u4F1A\u6839\u636E\u5F53\u524D\u8FD0\u884C\u5E73\u53F0\u81EA\u52A8\u4F18\u5316\u547D\u4EE4\u6267\u884C\uFF1A
@@ -662,38 +677,38 @@ Returns an array of matching file paths.`,input_schema:{type:"object",properties
662
677
  `,i+=` - dnf: sudo dnf install <package-name> (Fedora)
663
678
  `))),i+=`
664
679
  \u26A0\uFE0F Please install the required command before proceeding.
665
- `,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}
666
- ${h}
680
+ `,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=os.platform(),m=`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},`${m}
681
+ ${f}
667
682
 
668
683
  Command failed with error:
669
- 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),x=Buffer.concat([h,w]);try{let k=await fc();if(k){let f=["cp936","gbk","utf8","gb2312","big5"],v=!1;for(let S of f)try{if(g=k.decode(x,S),/[\u4e00-\u9fff]/.test(g)||g.length>0){v=!0;break}}catch{continue}v||(g=x.toString("utf8"))}else g=x.toString("utf8");m.status===0&&g&&g.trim()&&(g+=`
684
+ TypeError: Command is undefined or null`)}let s=os.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="",d;if(s==="win32"){if(i==="powershell.exe"){let w=`${c}`;w=w.replace(/&&/g,";"),d=Ol(i,[...a,w],{stdio:"pipe",windowsHide:!0,encoding:"buffer"})}else{let w=`chcp 65001 >nul 2>&1 && ${c}`;d=Ol("cmd.exe",["/c",w],{stdio:"pipe",windowsHide:!0,encoding:"buffer"})}let m=d.stdout||Buffer.alloc(0),f=d.stderr||Buffer.alloc(0),x=Buffer.concat([m,f]);try{let w=await Nl();if(w){let v=["cp936","gbk","utf8","gb2312","big5"],h=!1;for(let y of v)try{if(g=w.decode(x,y),/[\u4e00-\u9fff]/.test(g)||g.length>0){h=!0;break}}catch{continue}h||(g=x.toString("utf8"))}else g=x.toString("utf8");d.status===0&&g&&g.trim()&&(g+=`
670
685
 
671
- \u2705 Windows\u7F16\u7801\u5DF2\u4F18\u5316\u5904\u7406`)}catch{g=x.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}
686
+ \u2705 Windows\u7F16\u7801\u5DF2\u4F18\u5316\u5904\u7406`)}catch{g=x.toString("utf8")}}else{let m=[...a,c].join(" ");g=ym(m,l).toString()}if(this.isCommandNotFoundError(g,s)){let m=this.extractCommandName(t),f=this.generateCommandNotFoundMessage(m,s);return this.createToolResult({error:g,success:!1,commandNotFound:!0},`${u}
672
687
  ${p}
673
688
 
674
- ${m}
689
+ ${f}
675
690
 
676
691
  Original error:
677
692
  ${g}`,!0)}return this.createToolResult(g,`${u}
678
693
  ${p}
679
694
 
680
695
  Command output:
681
- ${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"],x="";for(let k of w)try{if(x=h.decode(m,k),x.length>0){d+=x;break}}catch{continue}x||(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
696
+ ${g}`)}catch(g){let d="";if(s==="win32"&&g.stderr){let m=Buffer.isBuffer(g.stderr)?g.stderr:Buffer.from(g.stderr),f=await Nl();if(f)try{let x=["cp936","gbk","utf8","gb2312"],w="";for(let v of x)try{if(w=f.decode(m,v),w.length>0){d+=w;break}}catch{continue}w||(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),f=this.generateCommandNotFoundMessage(m,s),x=f;return s==="win32"&&this.isUnixCommand(m)&&(x=`\u{1F504} Command Auto-Conversion: Unix command '${m}' was automatically converted to Windows equivalent
682
697
 
683
- ${h}`),this.createToolResult({error:d,success:!1,commandNotFound:!0},`${u}
698
+ ${f}`),this.createToolResult({error:d,success:!1,commandNotFound:!0},`${u}
684
699
  ${p}
685
700
 
686
- ${w}
701
+ ${x}
687
702
 
688
703
  Original error:
689
704
  ${d}`,!0)}return this.createToolResult({error:d,success:!1},`${u}
690
705
  ${p}
691
706
 
692
707
  Command failed with error:
693
- ${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}
708
+ ${d}`,!0)}else{let g=t;s==="win32"?g=`chcp 65001 > nul && ${c}`:g=[...a,c].join(" ");let d=xm(g,l);return this.createToolResult({success:!0,message:"Command started in background"},`${u}
694
709
  ${p}
695
710
 
696
- 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={};O(Ps,{ShellTool:()=>Nt,shell:()=>Yn,shellTool:()=>Ut});var eo=y(()=>{hc()});var Ms={};O(Ms,{THINK_TOOL:()=>to,ThinkTool:()=>ot,extractThought:()=>no,isThinkTool:()=>zt,think:()=>Vt,thinkTool:()=>Wt});function Vt(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,Wt,to,Xn=y(()=>{U();ot=class extends P{getDefinition(){return{name:"think",description:`Use this tool to think, reason, and reflect before taking actions.
711
+ 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}},Cn=new xn});var Fi={};_(Fi,{ShellTool:()=>xn,shell:()=>Hr,shellTool:()=>Cn});var ss=C(()=>{Ul()});var _i={};_(_i,{THINK_TOOL:()=>is,ThinkTool:()=>$t,extractThought:()=>as,isThinkTool:()=>bn,think:()=>Sn,thinkTool:()=>wn});function Sn(o){return Oi.execute(o)}function bn(o){return o==="think"}function as(o){if(!o||!o.function||o.function.name!=="think")return null;try{return JSON.parse(o.function.arguments).thought||null}catch{return null}}var $t,Oi,wn,is,Vr=C(()=>{U();$t=class extends ${getDefinition(){return{name:"think",description:`Use this tool to think, reason, and reflect before taking actions.
697
712
  This is a zero-side-effect tool that makes your thinking process observable.
698
713
 
699
714
  IMPORTANT: You should call this tool:
@@ -701,9 +716,215 @@ IMPORTANT: You should call this tool:
701
716
  - AFTER receiving an Observation (to reflect on the result)
702
717
  - When you need to analyze complex situations
703
718
 
704
- 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;Wt=$s,to=$s.getDefinition()});var Fs={};O(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(`
705
- `),n=yc.all,r=yc[e]||[];return`<instructions>
706
- ${[...new Set([...n,...r])].map(a=>gg[a]).join(`
719
+ 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."}},Oi=new $t;wn=Oi,is=Oi.getDefinition()});var zl={};_(zl,{PlatformType:()=>Wl,buildPlatformAwarePrompt:()=>vm,getCurrentPlatform:()=>cs,getPlatformDisplayName:()=>Ni,getPlatformSpecificToolEnhancement:()=>Tm,getPlatformSummary:()=>Pm});import*as qe from"os";function cs(){let o=qe.platform();switch(o){case"win32":return"win32";case"darwin":return"darwin";case"linux":return"linux";default:return S(`\u672A\u77E5\u5E73\u53F0\u7C7B\u578B: ${o}\uFF0C\u4F7F\u7528\u901A\u7528\u914D\u7F6E`),"unknown"}}function Ni(o){return{win32:"Windows",darwin:"macOS",linux:"Linux",unknown:"Unknown"}[o]}function Cm(){return`
720
+ \u{1F5A5}\uFE0F **\u5F53\u524D\u8FD0\u884C\u73AF\u5883: Windows**
721
+
722
+ **\u547D\u4EE4\u4F18\u5148\u7EA7\u89C4\u5219**\uFF1A
723
+ - \u4F18\u5148\u4F7F\u7528Windows\u539F\u751F\u547D\u4EE4\uFF1Adir\u3001copy\u3001move\u3001del\u3001where\u3001findstr\u3001ipconfig\u3001tasklist
724
+ - \u5BF9\u4E8E\u590D\u6742\u547D\u4EE4\u6216\u9700\u8981\u9012\u5F52\u901A\u914D\u7B26(**)\u7684\u573A\u666F\uFF0C\u4F7F\u7528PowerShell\u547D\u4EE4
725
+
726
+ **Windows\u5E73\u53F0Shell\u9009\u62E9\u6307\u5357**\uFF1A
727
+ 1. **cmd.exe\u9002\u7528\u573A\u666F**\uFF1A\u7B80\u5355\u547D\u4EE4\u3001\u57FA\u672C\u6587\u4EF6\u64CD\u4F5C\u3001\u4E0D\u9700\u8981\u590D\u6742\u901A\u914D\u7B26
728
+ - \u793A\u4F8B\uFF1Adir\u3001copy file1.txt file2.txt\u3001del file.txt
729
+
730
+ 2. **PowerShell\u9002\u7528\u573A\u666F**\uFF1A
731
+ - \u9700\u8981\u9012\u5F52\u901A\u914D\u7B26(**)\u641C\u7D22\u6587\u4EF6
732
+ - \u590D\u6742\u7684\u547D\u4EE4\u7BA1\u9053\u548C\u8FC7\u6EE4
733
+ - PowerShell\u7279\u5B9A\u547D\u4EE4\uFF08\u5982Get-ChildItem\u3001Select-Object\u7B49\uFF09
734
+ - \u9700\u8981\u5904\u7406JSON\u6216\u5176\u4ED6\u7ED3\u6784\u5316\u6570\u636E
735
+
736
+ 3. **\u9012\u5F52\u901A\u914D\u7B26\u4F7F\u7528**\uFF1A
737
+ - \u4F7F\u7528PowerShell\u7684\u9012\u5F52\u901A\u914D\u7B26(**)\u6765\u641C\u7D22\u591A\u7EA7\u76EE\u5F55
738
+ - \u793A\u4F8B\uFF1AGet-ChildItem -Path . -Recurse -Filter "*.ts" \u6216 dir /b /s **\\*.ts
739
+
740
+ **\u5E38\u7528\u547D\u4EE4\u6620\u5C04**\uFF1A
741
+ - \u5217\u51FA\u6587\u4EF6\uFF1Adir\uFF08\u4E0D\u8981\u4F7F\u7528ls\uFF09
742
+ - \u67E5\u770B\u5F53\u524D\u76EE\u5F55\uFF1Acd\uFF08\u4E0D\u8981\u4F7F\u7528pwd\uFF09
743
+ - \u67E5\u627E\u547D\u4EE4\uFF1Awhere\uFF08\u4E0D\u8981\u4F7F\u7528which\uFF09
744
+ - \u67E5\u770B\u6587\u4EF6\u5185\u5BB9\uFF1Atype\uFF08\u4E0D\u8981\u4F7F\u7528cat\uFF09
745
+ - \u5220\u9664\u6587\u4EF6\uFF1Adel\uFF08\u4E0D\u8981\u4F7F\u7528rm\uFF09
746
+ - \u590D\u5236\u6587\u4EF6\uFF1Acopy\uFF08\u4E0D\u8981\u4F7F\u7528cp\uFF09
747
+ - \u79FB\u52A8\u6587\u4EF6\uFF1Amove\uFF08\u4E0D\u8981\u4F7F\u7528mv\uFF09
748
+ - \u641C\u7D22\u6587\u672C\uFF1Afindstr\uFF08\u4E0D\u8981\u4F7F\u7528grep\uFF09
749
+ - \u67E5\u770B\u8FDB\u7A0B\uFF1Atasklist\uFF08\u4E0D\u8981\u4F7F\u7528ps\uFF09
750
+ - \u7F51\u7EDC\u914D\u7F6E\uFF1Aipconfig\uFF08\u4E0D\u8981\u4F7F\u7528ifconfig\uFF09
751
+
752
+ **\u8DEF\u5F84\u5206\u9694\u7B26**\uFF1A
753
+ - \u4F7F\u7528\u53CD\u659C\u6760 \\ \u6216\u6B63\u659C\u6760 / \uFF08Windows\u652F\u6301\u4E24\u79CD\uFF09
754
+ - \u63A8\u8350\u4F7F\u7528\u6B63\u659C\u6760 / \u4EE5\u4FDD\u6301\u8DE8\u5E73\u53F0\u517C\u5BB9\u6027
755
+
756
+ **\u5305\u7BA1\u7406\u5668**\uFF1A
757
+ - winget\uFF08Windows 10+\u5185\u7F6E\uFF09
758
+ - Chocolatey\uFF08\u9700\u8981\u5B89\u88C5\uFF09
759
+ - Scoop\uFF08\u9700\u8981\u5B89\u88C5\uFF09
760
+
761
+ **\u7F16\u7801\u6CE8\u610F\u4E8B\u9879**\uFF1A
762
+ - Windows\u9ED8\u8BA4\u4F7F\u7528GBK/CP936\u7F16\u7801
763
+ - \u6267\u884C\u547D\u4EE4\u524D\u53EF\u80FD\u9700\u8981\u8BBE\u7F6EUTF-8\uFF1Achcp 65001`}function Sm(){return`
764
+ \u{1F34E} **\u5F53\u524D\u8FD0\u884C\u73AF\u5883: macOS**
765
+
766
+ **\u547D\u4EE4\u4F18\u5148\u7EA7\u89C4\u5219**\uFF1A
767
+ - \u4F7F\u7528Unix\u6807\u51C6\u547D\u4EE4\uFF1Als\u3001pwd\u3001which\u3001cat\u3001rm\u3001cp\u3001mv\u3001mkdir\u3001grep\u3001find
768
+ - \u4F18\u5148\u4F7F\u7528macOS\u539F\u751F\u5DE5\u5177\u548C\u547D\u4EE4
769
+
770
+ **\u5E38\u7528\u547D\u4EE4**\uFF1A
771
+ - \u5217\u51FA\u6587\u4EF6\uFF1Als\u3001ls -la
772
+ - \u67E5\u770B\u5F53\u524D\u76EE\u5F55\uFF1Apwd
773
+ - \u67E5\u627E\u547D\u4EE4\uFF1Awhich
774
+ - \u67E5\u770B\u6587\u4EF6\u5185\u5BB9\uFF1Acat
775
+ - \u5220\u9664\u6587\u4EF6\uFF1Arm\u3001rm -rf
776
+ - \u590D\u5236\u6587\u4EF6\uFF1Acp\u3001cp -r
777
+ - \u79FB\u52A8\u6587\u4EF6\uFF1Amv
778
+ - \u641C\u7D22\u6587\u672C\uFF1Agrep
779
+ - \u67E5\u770B\u8FDB\u7A0B\uFF1Aps
780
+ - \u7F51\u7EDC\u914D\u7F6E\uFF1Aifconfig
781
+
782
+ **\u8DEF\u5F84\u5206\u9694\u7B26**\uFF1A
783
+ - \u4F7F\u7528\u6B63\u659C\u6760 /
784
+
785
+ **\u5305\u7BA1\u7406\u5668**\uFF1A
786
+ - Homebrew\uFF08\u63A8\u8350\uFF09\uFF1Abrew install <package>
787
+ - MacPorts\uFF1Aport install <package>
788
+
789
+ **macOS\u7279\u5B9A\u5DE5\u5177**\uFF1A
790
+ - open\uFF1A\u6253\u5F00\u6587\u4EF6\u6216\u5E94\u7528
791
+ - pbcopy/pbpaste\uFF1A\u526A\u8D34\u677F\u64CD\u4F5C
792
+ - say\uFF1A\u6587\u672C\u8F6C\u8BED\u97F3
793
+ - osascript\uFF1A\u6267\u884CAppleScript
794
+
795
+ **Shell\u73AF\u5883**\uFF1A
796
+ - \u9ED8\u8BA4Shell\uFF1Azsh\uFF08macOS Catalina+\uFF09
797
+ - \u53EF\u9009Shell\uFF1Abash\u3001fish`}function wm(){return`
798
+ \u{1F427} **\u5F53\u524D\u8FD0\u884C\u73AF\u5883: Linux**
799
+
800
+ **\u547D\u4EE4\u4F18\u5148\u7EA7\u89C4\u5219**\uFF1A
801
+ - \u4F7F\u7528Unix\u6807\u51C6\u547D\u4EE4\uFF1Als\u3001pwd\u3001which\u3001cat\u3001rm\u3001cp\u3001mv\u3001mkdir\u3001grep\u3001find
802
+ - \u4F18\u5148\u4F7F\u7528Linux\u539F\u751F\u5DE5\u5177\u548C\u547D\u4EE4
803
+
804
+ **\u5E38\u7528\u547D\u4EE4**\uFF1A
805
+ - \u5217\u51FA\u6587\u4EF6\uFF1Als\u3001ls -la
806
+ - \u67E5\u770B\u5F53\u524D\u76EE\u5F55\uFF1Apwd
807
+ - \u67E5\u627E\u547D\u4EE4\uFF1Awhich
808
+ - \u67E5\u770B\u6587\u4EF6\u5185\u5BB9\uFF1Acat
809
+ - \u5220\u9664\u6587\u4EF6\uFF1Arm\u3001rm -rf
810
+ - \u590D\u5236\u6587\u4EF6\uFF1Acp\u3001cp -r
811
+ - \u79FB\u52A8\u6587\u4EF6\uFF1Amv
812
+ - \u641C\u7D22\u6587\u672C\uFF1Agrep
813
+ - \u67E5\u770B\u8FDB\u7A0B\uFF1Aps
814
+ - \u7F51\u7EDC\u914D\u7F6E\uFF1Aifconfig \u6216 ip
815
+
816
+ **\u8DEF\u5F84\u5206\u9694\u7B26**\uFF1A
817
+ - \u4F7F\u7528\u6B63\u659C\u6760 /
818
+
819
+ **\u5305\u7BA1\u7406\u5668**\uFF08\u6839\u636E\u53D1\u884C\u7248\uFF09\uFF1A
820
+ - Debian/Ubuntu\uFF1Aapt\u3001apt-get
821
+ - \u5B89\u88C5\uFF1Asudo apt-get install <package>
822
+ - \u66F4\u65B0\uFF1Asudo apt-get update
823
+ - CentOS/RHEL\uFF1Ayum
824
+ - \u5B89\u88C5\uFF1Asudo yum install <package>
825
+ - Fedora\uFF1Adnf
826
+ - \u5B89\u88C5\uFF1Asudo dnf install <package>
827
+ - Arch Linux\uFF1Apacman
828
+ - \u5B89\u88C5\uFF1Asudo pacman -S <package>
829
+
830
+ **Shell\u73AF\u5883**\uFF1A
831
+ - \u9ED8\u8BA4Shell\uFF1Abash
832
+ - \u53EF\u9009Shell\uFF1Azsh\u3001fish\u3001sh
833
+
834
+ **\u6743\u9650\u7BA1\u7406**\uFF1A
835
+ - \u4F7F\u7528sudo\u6267\u884C\u9700\u8981\u7BA1\u7406\u5458\u6743\u9650\u7684\u547D\u4EE4
836
+ - \u6CE8\u610F\u6587\u4EF6\u6743\u9650\uFF1Achmod\u3001chown`}function bm(){return`
837
+ \u{1F30D} **\u5F53\u524D\u8FD0\u884C\u73AF\u5883: \u901A\u7528**
838
+
839
+ **\u8DE8\u5E73\u53F0\u51B3\u7B56\u6846\u67B6**\uFF1A
840
+ 1. \u8BC6\u522B\u7528\u6237\u8BF7\u6C42\u7684\u6F5C\u5728\u5E73\u53F0\u4F9D\u8D56\u6027
841
+ 2. \u9009\u62E9\u6700\u9002\u5408\u5F53\u524D\u5E73\u53F0\u7684\u5B9E\u73B0\u65B9\u6848
842
+ 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
843
+ 4. \u4E3B\u52A8\u8BF4\u660E\u8DE8\u5E73\u53F0\u8003\u8651\u56E0\u7D20
844
+
845
+ **\u8DE8\u5E73\u53F0\u547D\u4EE4\u5EFA\u8BAE**\uFF1A
846
+ - \u6587\u4EF6\u64CD\u4F5C\uFF1A\u4F18\u5148\u4F7F\u7528\u7F16\u7A0B\u8BED\u8A00API\u800C\u975Eshell\u547D\u4EE4
847
+ - \u8DEF\u5F84\u5904\u7406\uFF1A\u4F7F\u7528path\u6A21\u5757\u5904\u7406\u8DEF\u5F84\u5206\u9694\u7B26
848
+ - \u8FDB\u7A0B\u7BA1\u7406\uFF1A\u4F7F\u7528\u8DE8\u5E73\u53F0\u7684\u8FDB\u7A0B\u7BA1\u7406\u5E93
849
+
850
+ **\u5E73\u53F0\u68C0\u6D4B**\uFF1A
851
+ - \u5728\u4EE3\u7801\u4E2D\u4F7F\u7528 process.platform \u6216 os.platform() \u68C0\u6D4B\u5E73\u53F0
852
+ - \u6839\u636E\u5E73\u53F0\u9009\u62E9\u5408\u9002\u7684\u547D\u4EE4\u548C\u5DE5\u5177`}function vm(){let o=cs(),e=Ni(o);S(`\u6784\u5EFA\u5E73\u53F0\u7279\u5B9A\u63D0\u793A\u8BCD\uFF0C\u5F53\u524D\u5E73\u53F0: ${e}`);let t="";switch(o){case"win32":t=Cm();break;case"darwin":t=Sm();break;case"linux":t=wm();break;default:t=bm()}return`
853
+ \u{1F30D} **\u6838\u5FC3\u539F\u5219\uFF1A\u4F60\u5FC5\u987B\u59CB\u7EC8\u611F\u77E5\u5E76\u9002\u5E94\u8FD0\u884C\u73AF\u5883**
854
+
855
+ **\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
856
+ 1. \u7406\u89E3\u5F53\u524D\u64CD\u4F5C\u7CFB\u7EDF\u5E73\u53F0\uFF08\u5DF2\u81EA\u52A8\u68C0\u6D4B\uFF09
857
+ 2. \u6839\u636E\u5E73\u53F0\u7279\u6027\u8C03\u6574\u547D\u4EE4\u9009\u62E9\u548C\u4EE3\u7801\u751F\u6210\u7B56\u7565
858
+ 3. \u4E3B\u52A8\u4F7F\u7528\u5E73\u53F0\u539F\u751F\u547D\u4EE4\u548C\u5DE5\u5177
859
+ 4. \u9884\u89C1\u5E76\u89E3\u51B3\u8DE8\u5E73\u53F0\u517C\u5BB9\u6027\u95EE\u9898
860
+
861
+ ${t}
862
+
863
+ **\u8DE8\u5E73\u53F0\u517C\u5BB9\u6027\u539F\u5219**\uFF1A
864
+ 1. \u4F18\u5148\u4F7F\u7528\u8DE8\u5E73\u53F0\u7684\u7F16\u7A0B\u8BED\u8A00API\uFF08\u5982Node.js\u7684fs\u3001path\u6A21\u5757\uFF09
865
+ 2. \u5982\u679C\u5FC5\u987B\u4F7F\u7528shell\u547D\u4EE4\uFF0C\u6839\u636E\u5F53\u524D\u5E73\u53F0\u9009\u62E9\u5408\u9002\u7684\u547D\u4EE4
866
+ 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
867
+ 4. \u5BF9\u4E8E\u5173\u952E\u64CD\u4F5C\uFF0C\u63D0\u4F9B\u5E73\u53F0\u7279\u5B9A\u7684\u5B9E\u73B0\u6216\u964D\u7EA7\u65B9\u6848`}function Tm(o){let e=cs();if(o==="shell")switch(e){case"win32":return`
868
+ \u5F53\u524D\u5E73\u53F0: Windows
869
+ - \u81EA\u52A8\u5C06Unix\u547D\u4EE4\u8F6C\u6362\u4E3AWindows\u7B49\u4EF7\u547D\u4EE4
870
+ - \u652F\u6301cmd.exe\u548CPowerShell\u4E24\u79CDshell
871
+ - \u590D\u6742\u547D\u4EE4\u6216\u9012\u5F52\u901A\u914D\u7B26\u4F1A\u81EA\u52A8\u4F7F\u7528PowerShell`;case"darwin":return`
872
+ \u5F53\u524D\u5E73\u53F0: macOS
873
+ - \u4F7F\u7528Unix\u6807\u51C6\u547D\u4EE4
874
+ - \u9ED8\u8BA4shell: zsh
875
+ - \u652F\u6301Homebrew\u5305\u7BA1\u7406\u5668`;case"linux":return`
876
+ \u5F53\u524D\u5E73\u53F0: Linux
877
+ - \u4F7F\u7528Unix\u6807\u51C6\u547D\u4EE4
878
+ - \u9ED8\u8BA4shell: bash
879
+ - \u6839\u636E\u53D1\u884C\u7248\u4F7F\u7528\u5BF9\u5E94\u7684\u5305\u7BA1\u7406\u5668\uFF08apt/yum/dnf\u7B49\uFF09`;default:return""}return""}function Pm(){let o=cs(),e=Ni(o),t={platform:qe.platform(),release:qe.release(),arch:qe.arch(),type:qe.type()};return`Platform: ${e} (${t.platform})
880
+ Architecture: ${t.arch}
881
+ OS Type: ${t.type}
882
+ OS Release: ${t.release}`}var Wl,Hl=C(()=>{V();Wl=(r=>(r.WINDOWS="win32",r.MACOS="darwin",r.LINUX="linux",r.UNKNOWN="unknown",r))(Wl||{})});import*as ls from"fs";import*as Vl from"path";var Ui,It,Wi=C(()=>{V();Ui=class{cached=null;cacheTime=0;CACHE_FILE_PATH=".nium/project/project.json";async initialize(e=process.cwd()){S("\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?L("\u9879\u76EE\u8BED\u8A00\u672A\u77E5\uFF0C\u5C06\u4F7F\u7528\u901A\u7528\u63CF\u8FF0"):L(`\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=Vl.join(e,this.CACHE_FILE_PATH);if(!ls.existsSync(t))return S(`${this.CACHE_FILE_PATH} \u4E0D\u5B58\u5728\uFF0C\u8FD4\u56DE\u672A\u77E5\u8BED\u8A00`),{isUnknown:!0};let n=JSON.parse(ls.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 s={primaryLanguage:n.primaryLanguage,languages:r,isUnknown:!n.primaryLanguage};return S(`\u68C0\u6D4B\u5230\u9879\u76EE\u8BED\u8A00\u4FE1\u606F: ${JSON.stringify(s)}`),s}catch(t){return S(`\u68C0\u6D4B\u9879\u76EE\u8BED\u8A00\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`),{isUnknown:!0}}}clearCache(){this.cached=null,this.cacheTime=0,S("\u9879\u76EE\u8BED\u8A00\u7F13\u5B58\u5DF2\u6E05\u9664")}},It=new Ui});var fe,us,ot=C(()=>{fe=class{buildPromptSection(){let e=this.getPathPatterns(),t="";if(e.importPatterns.length>0){t+=` **Path Reference Patterns**:
883
+ `;for(let n of e.importPatterns){t+=` - ${n.syntax}: ${n.description}
884
+ `;for(let r of n.examples)t+=` * \`${r}\`
885
+ `}}if(e.configPatterns&&e.configPatterns.length>0){t+=` **Config File Paths**:
886
+ `;for(let n of e.configPatterns)t+=` - ${n.fileType}: ${n.pathField} field
887
+ `,t+=` * Example: \`${n.example}\`
888
+ `}return e.relativePathRules&&(t+=` **Special Rules**: ${e.relativePathRules}
889
+ `),t}buildReferenceSearchSection(){let e=this.getPathPatterns();if(!e.referenceSearchPatterns||e.referenceSearchPatterns.length===0)return"";let t=`**${e.displayName} Reference Search Patterns**:
890
+ `;for(let n of e.referenceSearchPatterns)t+=`- ${n.type}: Use grep(pattern="${n.grepPattern}")
891
+ `,t+=` * ${n.description}
892
+ `,t+=` * Example: \`${n.example}\`
893
+ `;return t}buildDirectoryConventionSection(){let e=this.getPathPatterns();if(!e.directoryConventions||e.directoryConventions.length===0)return"";let t=`**${e.displayName} Directory Structure**:
894
+ `;for(let n of e.directoryConventions)t+=`- ${n.purpose} (${n.paths.join(", ")}): ${n.rules}
895
+ `;return t}buildBuildToolSection(){let e=this.getPathPatterns();if(!e.buildTools||e.buildTools.length===0)return"";let t=`**${e.displayName} Build Tools**:
896
+ `;t+=`Check for build system using glob() in this order:
897
+ `;for(let n=0;n<e.buildTools.length;n++){let r=e.buildTools[n];t+=`${n+1}. glob("${r.detectionPattern}") - ${r.name}
898
+ `,t+=` * Config: ${r.configFiles.join(", ")}
899
+ `,t+=` * ${r.description}
900
+ `}return t}},us=class extends fe{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**:
901
+ - Extract paths from import/require/use module import statements
902
+ - Extract path fields from config files (package.json, pom.xml, Cargo.toml, etc.)
903
+ - Recognize relative (./, ../) and absolute path references
904
+ - Infer file locations based on file extensions and directory structure`}}});var ps,Bl=C(()=>{ot();ps=class extends fe{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 gs,Gl=C(()=>{ot();gs=class extends fe{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 ms,Jl=C(()=>{ot();ms=class extends fe{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 ds,ql=C(()=>{ot();ds=class extends fe{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 fs,Kl=C(()=>{ot();fs=class extends fe{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 hs,Xl=C(()=>{ot();hs=class extends fe{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]
905
+ path = "src/lib.rs"`}]}}}});function vn(o){return Em[o.toLowerCase()]||zi}var Em,zi,Yl=C(()=>{ot();Bl();Gl();Jl();ql();Kl();Xl();Em={javascript:new ps,typescript:new gs,python:new ms,java:new ds,go:new fs,rust:new hs},zi=new us});var Zl={};_(Zl,{buildBuildToolDetection:()=>Rm,buildDirectoryConventions:()=>Am,buildLanguageSpecificPatterns:()=>km,buildReferenceSearchPatterns:()=>Mm});async function km(){let o=await It.getLanguageInfo();if(S(`\u6784\u5EFA\u8BED\u8A00\u7279\u5B9A\u6A21\u5F0F\uFF0C\u8BED\u8A00\u4FE1\u606F: ${JSON.stringify(o)}`),o.isUnknown)return Ql();if(o.primaryLanguage&&(!o.languages||o.languages.length<=1)){let t=vn(o.primaryLanguage);return $m(t,o.primaryLanguage)}let e=new Set;return o.primaryLanguage&&e.add(o.primaryLanguage),o.languages&&o.languages.forEach(t=>e.add(t)),Im(Array.from(e))}function $m(o,e){let n=`**Current Project Language: ${o.getPathPatterns().displayName}**
906
+
907
+ `;return n+=o.buildPromptSection(),n}function Im(o){let e=o.filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>({lang:r,handler:vn(r)}));if(e.length===0)return Ql();let n=`**Current Project: Multi-language (${e.map(r=>r.handler.getPathPatterns().displayName).join(", ")})**
908
+
909
+ `;for(let{lang:r,handler:s}of e){let i=s.getPathPatterns();n+=`### ${i.displayName}
910
+ `,n+=s.buildPromptSection(),n+=`
911
+ `}return n}function Ql(){return zi.buildPromptSection()}async function Mm(){let o=await It.getLanguageInfo();if(o.isUnknown)return Hi();let e=new Set;o.primaryLanguage&&e.add(o.primaryLanguage),o.languages&&o.languages.forEach(r=>e.add(r));let t=Array.from(e).filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>vn(r));if(t.length===0)return Hi();let n="";for(let r of t){let s=r.buildReferenceSearchSection();s&&(n+=s+`
912
+ `)}return n||Hi()}function Hi(){return`**Generic Reference Search**:
913
+ - Use grep(pattern="functionName|ClassName|variableName") to find all references
914
+ - Search for import/require statements
915
+ - Search for function/class usage patterns`}async function Am(){let o=await It.getLanguageInfo();if(o.isUnknown)return Vi();let e=new Set;o.primaryLanguage&&e.add(o.primaryLanguage),o.languages&&o.languages.forEach(r=>e.add(r));let t=Array.from(e).filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>vn(r));if(t.length===0)return Vi();let n="";for(let r of t){let s=r.buildDirectoryConventionSection();s&&(n+=s+`
916
+ `)}return n||Vi()}function Vi(){return`**Generic Directory Structure**:
917
+ - BUSINESS CODE (src/, lib/, app/): Use project's primary language
918
+ - TEST FILES (test/, tests/, spec/): Allow testing frameworks
919
+ - CONFIG FILES (config/, build/): Allow configuration languages`}async function Rm(){let o=await It.getLanguageInfo();if(o.isUnknown)return Bi();let e=new Set;o.primaryLanguage&&e.add(o.primaryLanguage),o.languages&&o.languages.forEach(r=>e.add(r));let t=Array.from(e).filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>vn(r));if(t.length===0)return Bi();let n="";for(let r of t){let s=r.buildBuildToolSection();s&&(n+=s+`
920
+ `)}return n||Bi()}function Bi(){return`**Generic Build Tool Detection**:
921
+ 1. glob("**/package.json") - Node.js project
922
+ 2. glob("**/pom.xml") OR glob("**/*.gradle") - Java project
923
+ 3. glob("**/Cargo.toml") - Rust project
924
+ 4. glob("**/go.mod") - Go project
925
+ 5. glob("**/requirements.txt") OR glob("**/setup.py") - Python project`}var eu=C(()=>{Wi();Yl();V()});var Qi={};_(Qi,{SYSTEM_PROMPT:()=>Tn,generateAgentMatchingPrompt:()=>Yi,generateSystemPrompt:()=>ru,generateTaskComplexityEvaluationPrompt:()=>Ji,generateTaskPlanningConversionPrompt:()=>Xi,generateTaskPlanningMarkdownPrompt:()=>Ki,generateTaskPlanningPrompt:()=>qi,getSystemPrompt:()=>ou});async function ru(o=Br(),e="all"){let t=o.map(c=>`- ${c.name}: ${c.description}`).join(`
926
+ `),n=nu.all,r=nu[e]||[],s=[...new Set([...n,...r])],i={...tu};if(s.includes("environment_awareness")){let{buildPlatformAwarePrompt:c}=await Promise.resolve().then(()=>(Hl(),zl)),l=c();i.environment_awareness=l}if(s.includes("file_retrieval_strategy")){let{buildLanguageSpecificPatterns:c}=await Promise.resolve().then(()=>(eu(),Zl)),l=await c(),p=tu.file_retrieval_strategy_template.replace("{{LANGUAGE_SPECIFIC_PATTERNS}}",l);i.file_retrieval_strategy=p}return`<instructions>
927
+ ${s.map(c=>i[c]).filter(Boolean).join(`
707
928
  `)}
708
929
 
709
930
  <available_tools>
@@ -714,7 +935,7 @@ ${t}
714
935
  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.
715
936
  Use the tool definitions to understand what parameters each tool requires.
716
937
  </available_tools>
717
- </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
938
+ </instructions>`}async function ou(){return Gi||(Gi=await ru()),Gi}function Ji(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
718
939
 
719
940
  \u4EFB\u52A1\u63CF\u8FF0\uFF1A
720
941
  ${o}
@@ -724,7 +945,7 @@ ${o}
724
945
  - 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
725
946
  - 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
726
947
 
727
- \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?`
948
+ \u8BF7\u53EA\u56DE\u590D "SIMPLE"\u3001"MEDIUM" \u6216 "COMPLEX"\uFF0C\u4E0D\u8981\u6709\u5176\u4ED6\u5185\u5BB9\u3002`}function qi(o,e=[]){let t=e.length>0?e.map(r=>`${r.name}(${r.description})`).join(", "):"default",n=e.length>0?`
728
949
 
729
950
  \u53EF\u7528\u7684\u5B50\u667A\u80FD\u4F53\uFF1A
730
951
  ${e.map(r=>`- ${r.name}: ${r.description}`).join(`
@@ -817,7 +1038,7 @@ ${n}
817
1038
  }
818
1039
  \`\`\`
819
1040
 
820
- \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?`
1041
+ \u8BF7\u4F7F\u7528 create_task_plan \u5DE5\u5177\u8FD4\u56DE\u7ED3\u6784\u5316\u7684\u4EFB\u52A1\u89C4\u5212\u3002`}function Ki(o,e=[]){let t=e.length>0?`
821
1042
  \u53EF\u7528\u7684\u5B50\u667A\u80FD\u4F53\uFF1A
822
1043
  ${e.map(n=>`- ${n.name}: ${n.description}`).join(`
823
1044
  `)}`:"";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
@@ -851,11 +1072,11 @@ ${t}
851
1072
  - \u6B65\u9AA4\u4E4B\u95F4\u5FC5\u987B\u6709\u660E\u786E\u7684\u4F9D\u8D56\u5173\u7CFB\u548C\u987A\u5E8F\u903B\u8F91
852
1073
  - \u6BCF\u4E2A\u6B65\u9AA4\u5FC5\u987B\u6807\u6CE8\u6700\u9002\u5408\u7684\u63A8\u8350\u5B50\u667A\u80FD\u4F53
853
1074
  - \u4EFB\u52A1\u6982\u8FF0\u5E94\u8BE5\u7B80\u660E\u627C\u8981\u5730\u6982\u62EC\u6574\u4E2A\u4EFB\u52A1\u7684\u76EE\u7684\u548C\u8303\u56F4
854
- - \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
1075
+ - \u9884\u671F\u7ED3\u679C\u5E94\u8BE5\u5177\u4F53\u3001\u53EF\u8861\u91CF\uFF0C\u660E\u786E\u8BF4\u660E\u5B8C\u6210\u540E\u7684\u72B6\u6001`}function Xi(o){return`\u8BF7\u5C06\u4EE5\u4E0B Markdown \u683C\u5F0F\u7684\u4EFB\u52A1\u89C4\u5212\u8F6C\u6362\u4E3A\u7ED3\u6784\u5316\u683C\u5F0F\u3002
855
1076
 
856
1077
  ${o}
857
1078
 
858
- \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
1079
+ \u8BF7\u4F7F\u7528 create_task_plan \u5DE5\u5177\u8FD4\u56DE\u7ED3\u6784\u5316\u7684\u4EFB\u52A1\u89C4\u5212\u6570\u636E\u3002`}function Yi(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
859
1080
 
860
1081
  \u4EFB\u52A1\u63CF\u8FF0\uFF1A
861
1082
  ${o}
@@ -869,24 +1090,7 @@ ${e}
869
1090
  3. \u667A\u80FD\u4F53\u7684\u4E13\u957F\u662F\u5426\u80FD\u591F\u89E3\u51B3\u4EFB\u52A1\u4E2D\u7684\u6838\u5FC3\u6311\u6218
870
1091
  4. \u8003\u8651\u4EFB\u52A1\u7684\u590D\u6742\u5EA6\u548C\u667A\u80FD\u4F53\u7684\u5904\u7406\u80FD\u529B
871
1092
 
872
- \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=y(()=>{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:`
873
- \u{1F30D} **\u6838\u5FC3\u539F\u5219\uFF1A\u4F60\u5FC5\u987B\u59CB\u7EC8\u611F\u77E5\u5E76\u9002\u5E94\u8FD0\u884C\u73AF\u5883**
874
-
875
- **\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
876
- 1. \u68C0\u67E5\u5E76\u7406\u89E3\u5F53\u524D\u64CD\u4F5C\u7CFB\u7EDF\u5E73\u53F0\uFF08Windows/macOS/Linux\uFF09
877
- 2. \u6839\u636E\u5E73\u53F0\u7279\u6027\u8C03\u6574\u547D\u4EE4\u9009\u62E9\u548C\u4EE3\u7801\u751F\u6210\u7B56\u7565
878
- 3. \u4E3B\u52A8\u4F7F\u7528\u5E73\u53F0\u539F\u751F\u547D\u4EE4\u548C\u5DE5\u5177
879
- 4. \u9884\u89C1\u5E76\u89E3\u51B3\u8DE8\u5E73\u53F0\u517C\u5BB9\u6027\u95EE\u9898
880
-
881
- **\u5E73\u53F0\u547D\u4EE4\u4F18\u5148\u7EA7\u89C4\u5219**\uFF1A
882
- - Windows: \u4F18\u5148\u4F7F\u7528 dir\u3001copy\u3001move\u3001del\u3001where\u3001findstr\u3001ipconfig\u3001tasklist
883
- - macOS/Linux: \u4F18\u5148\u4F7F\u7528 ls\u3001cp\u3001mv\u3001rm\u3001which\u3001grep\u3001ifconfig\u3001ps
884
-
885
- **\u8DE8\u5E73\u53F0\u51B3\u7B56\u6846\u67B6**\uFF1A
886
- 1. \u8BC6\u522B\u7528\u6237\u8BF7\u6C42\u7684\u6F5C\u5728\u5E73\u53F0\u4F9D\u8D56\u6027
887
- 2. \u9009\u62E9\u6700\u9002\u5408\u5F53\u524D\u5E73\u53F0\u7684\u5B9E\u73B0\u65B9\u6848
888
- 3. \u5982\u679C\u6D89\u53CAshell\u547D\u4EE4\uFF0C\u4F7F\u7528\u5E73\u53F0\u539F\u751F\u547D\u4EE4
889
- 4. \u4E3B\u52A8\u8BF4\u660E\u8DE8\u5E73\u53F0\u8003\u8651\u56E0\u7D20`,workflow:`
1093
+ \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 tu,nu,Gi,Tn,Mt=C(()=>{Pn();tu={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:`
890
1094
  <workflow>
891
1095
  You must follow this strict thinking pattern for EVERY response:
892
1096
 
@@ -929,6 +1133,7 @@ This cycle continues: think \u2192 act \u2192 observe \u2192 think \u2192 act \u
929
1133
  6. Think deeply and systematically: analyze context, plan actions, reflect on results
930
1134
  7. If you encounter errors or unexpected results, use 'think' to analyze the problem and determine the best next step
931
1135
  8. ALWAYS maintain high code quality standards - follow project conventions, add appropriate comments, and write clean code
1136
+ 9. \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.
932
1137
  </critical_rules>`,code_modification:`
933
1138
  <code_modification_workflow>
934
1139
  When modifying existing code:
@@ -1041,7 +1246,63 @@ When working within a plan/task context:
1041
1246
  Example:
1042
1247
  \u274C Bad: Call quickProjectScan() in every step of a plan task
1043
1248
  \u2705 Good: Call read('.nium/project/project.json') to get project info
1044
- </project_exploration_guidelines>`,project_type_detection:`
1249
+ </project_exploration_guidelines>`,file_retrieval_strategy_template:`
1250
+ <file_retrieval_strategy>
1251
+ **Core Principle: Leverage known information, minimize file retrieval interactions**
1252
+
1253
+ **File Retrieval Priority Strategy** (highest to lowest):
1254
+
1255
+ 1. **Direct Read from Known Paths (Highest Priority)**
1256
+ - Extract file path references from already-read files and use read() directly
1257
+ {{LANGUAGE_SPECIFIC_PATTERNS}}
1258
+ - \u2705 Advantage: 1 interaction, precise hit
1259
+
1260
+ **\u{1F6A8} CRITICAL: When Path is Ambiguous**
1261
+
1262
+ If user provides ONLY filename (e.g., "read config.json", "\u67E5\u770B Prompts.ts") WITHOUT full path:
1263
+
1264
+ **NEVER GUESS PATHS!** Follow this workflow:
1265
+ - \u274C NEVER assume file location (e.g., src/core/llm/Prompts.ts)
1266
+ - \u274C NEVER call read() with guessed paths
1267
+ - \u2705 MUST use glob(pattern="**/filename") to search first
1268
+ - \u2705 If 0 matches: inform user file not found
1269
+ - \u2705 If 1 match: read that file directly
1270
+ - \u2705 If multiple matches: list all in think() and ask user to choose
1271
+
1272
+ Example:
1273
+ \`\`\`
1274
+ User: "read Prompts.ts"
1275
+ \u274C Wrong: read("src/core/llm/Prompts.ts") [guessing]
1276
+ \u2705 Correct: glob("**/Prompts.ts") \u2192 read("src/config/prompts.ts")
1277
+ \`\`\`
1278
+
1279
+ 2. **Use Recent Files List (High Priority)**
1280
+ - System provides "recently accessed files" in context
1281
+ - If list contains task-relevant files, read directly
1282
+ - \u2705 Advantage: leverage dynamic context, avoid redundant exploration
1283
+
1284
+ 3. **Use Project Structure Doc (Medium Priority)**
1285
+ - Check .nium/project/project.json for file locations
1286
+ - \u2705 Advantage: structured info, fast location
1287
+
1288
+ 4. **Use glob Pattern Match (Medium-Low Priority)**
1289
+ - When you know filename/extension but not directory
1290
+ - Example: glob("**/config.json") instead of list() exploration
1291
+ - \u2705 Advantage: find all matches in one call
1292
+
1293
+ 5. **Use list Directory Exploration (Lowest Priority)**
1294
+ - Only when file location is completely unknown
1295
+ - Must call think() first to explain why other methods don't apply
1296
+ - \u274C Disadvantage: multiple interactions, low efficiency
1297
+
1298
+ **Decision Flow**:
1299
+ 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
1300
+
1301
+ **Key Reminders**:
1302
+ - After each read(), analyze file content for path references to build "file dependency graph"
1303
+ - In think(), explicitly state why you chose a specific retrieval strategy
1304
+ - Prefer "inference" over "exploration" - use known info to reduce interactions
1305
+ </file_retrieval_strategy>`,project_type_detection:`
1045
1306
  <project_type_detection>
1046
1307
  IMPORTANT: Identify project build system before making assumptions
1047
1308
 
@@ -1143,6 +1404,83 @@ Step 6 - Final answer:
1143
1404
  "Successfully added the new function to utils.js using safe merge, maintaining consistency with existing code style."
1144
1405
  </correct_response>
1145
1406
  </example>
1407
+
1408
+ <example>
1409
+ <scenario>User asks: \u67E5\u770B\u4E3B\u5165\u53E3\u6587\u4EF6\u7684\u5B9E\u73B0</scenario>
1410
+ <correct_response>
1411
+ \u2705 Efficient approach (leverage known info):
1412
+ Step 1 - Think:
1413
+ Call think({ thought: "Need to view main entry file. I'll read package.json first to find the 'main' field pointing to the entry file path." })
1414
+
1415
+ Step 2 - Read package.json:
1416
+ Call read({ path: "package.json" })
1417
+
1418
+ [System provides: Observation: { "main": "src/index.ts", ... }]
1419
+
1420
+ Step 3 - Think:
1421
+ Call think({ thought: "Found from package.json that the main entry is src/index.ts, reading it directly" })
1422
+
1423
+ Step 4 - Read main file:
1424
+ Call read({ path: "src/index.ts" })
1425
+
1426
+ [Total: 2 interactions, more accurate]
1427
+ </correct_response>
1428
+ </example>
1429
+
1430
+ <example>
1431
+ <scenario>User asks: \u9605\u8BFB Prompts.ts (only filename provided, no path)</scenario>
1432
+ <correct_response>
1433
+ \u2705 Correct approach (search first):
1434
+ Step 1 - Think:
1435
+ Call think({ thought: "User only provided filename 'Prompts.ts' without full path. According to PATH GUESSING PROHIBITION rule, I must search first and cannot guess." })
1436
+
1437
+ Step 2 - Search for file:
1438
+ Call glob({ pattern: "**/Prompts.ts" })
1439
+
1440
+ [System provides: Observation: Found 1 file: src/config/prompts.ts]
1441
+
1442
+ Step 3 - Think:
1443
+ Call think({ thought: "Found 1 matching file src/config/prompts.ts, reading it directly" })
1444
+
1445
+ Step 4 - Read file:
1446
+ Call read({ path: "src/config/prompts.ts" })
1447
+
1448
+ [Total: 3 interactions, accurate and follows rules]
1449
+
1450
+ \u274C Wrong approach (guessing path):
1451
+ Step 1: read("src/core/llm/Prompts.ts") \u2192 Error: file not found
1452
+ [Wasted interaction, violated PATH GUESSING PROHIBITION]
1453
+ </correct_response>
1454
+ </example>
1455
+
1456
+ <example>
1457
+ <scenario>User asks: \u67E5\u770B config.json (multiple matches found)</scenario>
1458
+ <correct_response>
1459
+ \u2705 Correct approach (ask user when multiple matches):
1460
+ Step 1 - Think:
1461
+ Call think({ thought: "User only provided filename 'config.json' without path. I must search first and cannot guess." })
1462
+
1463
+ Step 2 - Search for file:
1464
+ Call glob({ pattern: "**/config.json" })
1465
+
1466
+ [System provides: Observation: Found 2 files: config/app.json, test/fixtures/config.json]
1467
+
1468
+ Step 3 - Think:
1469
+ Call think({ thought: "Found 2 matching files. I need to ask user which one they want to view, cannot decide myself." })
1470
+
1471
+ Step 4 - Ask user:
1472
+ Call finish({
1473
+ answer: "I found 2 config.json files:
1474
+ 1. config/app.json (main configuration)
1475
+ 2. test/fixtures/config.json (test data)
1476
+
1477
+ Which one would you like to view?",
1478
+ success: true
1479
+ })
1480
+
1481
+ [Wait for user to specify before reading]
1482
+ </correct_response>
1483
+ </example>
1146
1484
  </examples>`,final_note:`
1147
1485
  <final_note>
1148
1486
  The key difference from traditional tool calling:
@@ -1168,7 +1506,7 @@ This makes your decision-making process transparent, debuggable, and more reliab
1168
1506
  - \u8BFB\u53D6\u6587\u4EF6\u5931\u8D25\uFF1A\u68C0\u67E5\u6587\u4EF6\u8DEF\u5F84\u662F\u5426\u6B63\u786E\uFF0C\u6587\u4EF6\u662F\u5426\u5B58\u5728
1169
1507
  - \u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF1A\u68C0\u67E5\u547D\u4EE4\u8BED\u6CD5\uFF0C\u662F\u5426\u9002\u5408\u5F53\u524D\u5E73\u53F0
1170
1508
  - \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
1171
- </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 Ve={};O(Ve,{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 N(`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?N("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
1509
+ </error_handling_strategies>`},nu={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"]};Gi=null;Tn=ou()});var st={};_(st,{TaskComplexity:()=>Le,evaluateTaskComplexity:()=>Dm,generatePlanSummary:()=>Jr,generateTaskPlan:()=>Gr,getTaskFilePath:()=>Wm,listTaskPlans:()=>Hm,loadTaskPlan:()=>zm,updateTaskStatus:()=>At});import je from"fs";import Oe from"path";function Lm(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:Le.SIMPLE,confidence:.9};for(let s of n)if(s.test(e))return{result:Le.COMPLEX,confidence:.85};let r=e.match(/[\u4e00-\u9fa5a-z]+/gi)||[];return r.length<5&&o.length<50?{result:Le.SIMPLE,confidence:.7}:r.length>20||o.length>200?{result:Le.COMPLEX,confidence:.75}:{result:Le.SIMPLE,confidence:.5}}async function jm(o){let e=Ji(o);try{let t=await B({model:Be(),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"?Le.COMPLEX:Le.SIMPLE}catch(t){return O(`LLM\u8BC4\u4F30\u5931\u8D25\uFF0C\u9ED8\u8BA4\u4E3A\u7B80\u5355\u4EFB\u52A1: ${t.message}`,"Task"),Le.SIMPLE}}async function Dm(o){let e=Lm(o);if(e.confidence>.8)return me(`\u5FEB\u901F\u542F\u53D1\u5F0F\u8BC4\u4F30: ${e.result}, \u7F6E\u4FE1\u5EA6: ${e.confidence.toFixed(2)}`,"Task"),e.result;me(`\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 jm(o);return t===Le.COMPLEX?O("LLM\u68C0\u6D4B\u5230\u590D\u6742\u4EFB\u52A1\uFF0C\u5C06\u8FDB\u884C\u4EFB\u52A1\u89C4\u5212","Task"):me("LLM\u68C0\u6D4B\u5230\u7B80\u5355\u4EFB\u52A1\uFF0C\u4F7F\u7528\u5355\u6B65\u9AA4\u6A21\u5F0F","Task"),t}function su(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
1172
1510
  \u5E38\u7528\u5DE5\u5177\u7EC4\u5408\uFF1A
1173
1511
  - \u53EA\u8BFB\u5206\u6790: ["read", "glob", "grep", "quickProjectScan", "think", "askUser"]
1174
1512
  - \u4EE3\u7801\u63A2\u7D22: ["read", "glob", "grep", "quickProjectScan", "shell", "think"]
@@ -1176,7 +1514,7 @@ This makes your decision-making process transparent, debuggable, and more reliab
1176
1514
  - \u6D4B\u8BD5\u9A8C\u8BC1: ["read", "shell", "glob", "grep", "think"]
1177
1515
 
1178
1516
  \u5982\u679C\u4E3A\u7A7A\u6570\u7EC4\u6216\u4E0D\u6307\u5B9A\uFF0C\u5219\u4F7F\u7528\u6240\u6709\u53EF\u7528\u5DE5\u5177\u3002
1179
- \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=[]){N("\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 N("\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}
1517
+ \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 Fm(o,e=[]){me("\u5C1D\u8BD5\u65B9\u68481: Function Calling","Task");let t=qi(o,e),n=su(e),s=(await B({model:ce(),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 Om(o,e=[]){O("\u5C1D\u8BD5\u65B9\u68482: Markdown + Function Call \u8F6C\u6362","Task");let t=Ki(o,e),r=(await B({model:ce(),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=Xi(r),i=su(e),c=(await B({model:ce(),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 _m(o){return O("\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 Nm(o){let e=o.steps.map((t,n)=>`- [ ] ${t.description}
1180
1518
  - \u63A8\u8350\u5B50\u667A\u80FD\u4F53: ${t.subAgent}`).join(`
1181
1519
 
1182
1520
  `);return`# \u4EFB\u52A1\u89C4\u5212
@@ -1188,27 +1526,27 @@ ${o.overview}
1188
1526
  ${e}
1189
1527
 
1190
1528
  ## \u9884\u671F\u7ED3\u679C
1191
- ${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",j("Function Calling \u65B9\u6848\u6210\u529F","Task")}catch(c){N(`Function Calling \u5931\u8D25: ${c.message}`,"Task");try{t=await hg(o,e),n="Markdown + Conversion",j("Markdown \u8F6C\u6362\u65B9\u6848\u6210\u529F","Task")}catch(l){N(`Markdown \u8F6C\u6362\u5931\u8D25: ${l.message}`,"Task"),t=yg(o),n="Default Fallback",N("\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),j(`\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})
1529
+ ${o.expectedResult}`}async function Gr(o,e=[]){if(!o||typeof o!="string")throw new Error("\u65E0\u6548\u7684\u7528\u6237\u8BF7\u6C42");me("\u6B63\u5728\u751F\u6210\u4EFB\u52A1\u89C4\u5212...","Task");let t=null,n="unknown";try{t=await Fm(o,e),n="Function Calling",W("Function Calling \u65B9\u6848\u6210\u529F","Task")}catch(c){O(`Function Calling \u5931\u8D25: ${c.message}`,"Task");try{t=await Om(o,e),n="Markdown + Conversion",W("Markdown \u8F6C\u6362\u65B9\u6848\u6210\u529F","Task")}catch(l){O(`Markdown \u8F6C\u6362\u5931\u8D25: ${l.message}`,"Task"),t=_m(o),n="Default Fallback",O("\u4F7F\u7528\u9ED8\u8BA4\u964D\u7EA7\u65B9\u6848","Task")}}let r=t.markdown||Nm(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=Oo(),a={markdown:r,tasks:s,taskId:i,strategy:n};return await Um(r,i,a),W(`\u4EFB\u52A1\u89C4\u5212\u751F\u6210\u5B8C\u6210 (\u7B56\u7565: ${n})`,"Task"),me(`\u5171\u5305\u542B ${s.length} \u4E2A\u4EFB\u52A1\u6B65\u9AA4`,"Task"),jo(),Qn(r),jo(),a}async function Um(o,e,t){let n=Oe.join(process.cwd(),".nium","tasks");je.existsSync(n)||je.mkdirSync(n,{recursive:!0});let r=`# \u4EFB\u52A1\u89C4\u5212 (ID: ${e})
1192
1530
 
1193
1531
  ## \u4EFB\u52A1\u6982\u8FF0
1194
1532
  ${o.substring(o.indexOf("## \u4EFB\u52A1\u6982\u8FF0")+7)}
1195
1533
 
1196
1534
  ## \u66F4\u65B0\u65F6\u95F4
1197
- ${new Date().toLocaleString()}`,s=Pe.join(n,`${e}.md`);if(Se.writeFileSync(s,r,"utf8"),j(`\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"),j(`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(`
1198
- `),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(`
1199
- `),"utf8"),j(`\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 j(`\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(`
1535
+ ${new Date().toLocaleString()}`,s=Oe.join(n,`${e}.md`);if(je.writeFileSync(s,r,"utf8"),W(`\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=Oe.join(n,`${e}.json`);je.writeFileSync(a,JSON.stringify(i,null,2),"utf8"),W(`JSON \u6570\u636E\u5DF2\u4FDD\u5B58\u5230: ${a}`,"Task")}}async function At(o,e,t){let n=Oe.join(process.cwd(),".nium","tasks"),r=Oe.join(n,`${o}.md`);if(!je.existsSync(r))return ie(`\u4EFB\u52A1\u6587\u4EF6\u4E0D\u5B58\u5728: ${r}`,"Task"),!1;try{let i=je.readFileSync(r,"utf8").split(`
1536
+ `),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 je.writeFileSync(r,l.join(`
1537
+ `),"utf8"),W(`\u4EFB\u52A1 ${o} \u6B65\u9AA4 ${e} \u72B6\u6001\u5DF2\u66F4\u65B0\u4E3A ${t}`,"Task"),!0}catch(s){return ie(`\u66F4\u65B0\u4EFB\u52A1\u72B6\u6001\u5931\u8D25: ${s.message}`,"Task"),!1}}function Wm(o){let e=Oe.join(process.cwd(),".nium","tasks");return Oe.join(e,`${o}.md`)}function zm(o){let e=Oe.join(process.cwd(),".nium","tasks"),t=Oe.join(e,`${o}.json`);if(!je.existsSync(t))return ie(`\u4EFB\u52A1\u6587\u4EF6\u4E0D\u5B58\u5728: ${t}`,"Task"),null;try{let n=je.readFileSync(t,"utf8"),r=JSON.parse(n);return W(`\u6210\u529F\u52A0\u8F7D\u4EFB\u52A1: ${o}`,"Task"),r}catch(n){return ie(`\u89E3\u6790\u4EFB\u52A1\u6587\u4EF6\u5931\u8D25: ${n.message}`,"Task"),null}}function Hm(){let o=Oe.join(process.cwd(),".nium","tasks");return je.existsSync(o)?je.readdirSync(o).filter(n=>n.endsWith(".json")).map(n=>n.replace(".json","")):[]}function Jr(o){if(!o||!o.tasks||o.tasks.length===0)return"\u65E0\u6709\u6548\u4EFB\u52A1\u6B65\u9AA4";let e=[];e.push(`
1200
1538
  \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(`
1201
- `)}var xe,$e=y(()=>{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
1202
- `),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(`
1203
- `)}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(`
1204
- `)}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(`
1539
+ `)}var Le,_e=C(()=>{ee();Ce();_o();Mt();tt();Le={SIMPLE:"simple",COMPLEX:"complex"}});function qr(o,e={format:"markdown"}){let{format:t,maxSections:n=100,detailed:r=!0,customTitle:s}=e;switch(t){case"markdown":return iu(o,r,s);case"text":return Vm(o,r);case"summary":return Bm(o,n);default:return iu(o,r,s)}}function iu(o,e,t){let n=[];return n.push(t||`# \u9879\u76EE\u7ED3\u6784\u4FE1\u606F
1540
+ `),Gm(n,o,e),Jm(n,o,e),qm(n,o,e),Km(n,o,e),Xm(n,o,e),Ym(n,o,e),Qm(n,o,e),n.length<=1?"\u6682\u65E0\u8BE6\u7EC6\u9879\u76EE\u7ED3\u6784\u4FE1\u606F\u3002":n.join(`
1541
+ `)}function Vm(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(`
1542
+ `)}function Bm(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(`
1205
1543
  `);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(`
1206
1544
  `):(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(`
1207
- `):"\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(`
1545
+ `):"\u6682\u65E0\u9879\u76EE\u4FE1\u606F\u3002")}function Gm(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 Jm(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 qm(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 Km(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 Xm(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(`
1208
1546
  *...\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(`
1209
- *...\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(`
1210
- *...\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(`
1211
- *...\u8FD8\u6709 ${e.codeStandards.length-5} \u4E2A\u89C4\u8303*`),o.push("")}var ro=y(()=>{});import*as Jt from"os";var We,ze,He,Je,vc=y(()=>{K();ro();We=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},$(`\u5168\u5C40\u4E0A\u4E0B\u6587\u521D\u59CB\u5316: ${this.plan.totalSteps} \u4E2A\u6B65\u9AA4`)}recordStepCompletion(e,t,n={}){this.stepSummaries.set(e,{summary:t,metadata:n,timestamp:new Date().toISOString()}),C(`\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,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)}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},$("\u5DF2\u8BB0\u5F55\u9879\u76EE\u63A2\u7D22\u7ED3\u679C\u5230\u5168\u5C40\u4E0A\u4E0B\u6587")}getExplorationHistory(){return this.explorationHistory}},ze=class{globalContext;constructor(e){this.globalContext=e}async selectRelevantHistory(e,t,n){let r=[],s=this.globalContext.getStepDependencies().get(e)||[];for(let c of s){let l=this.globalContext.getStepSummary(c);l&&r.push({stepId:c,type:"dependency",content:l.summary,metadata:l.metadata})}let i=this.getRecentCompletedSteps(3);for(let c of i)if(!s.includes(c)){let l=this.globalContext.getStepSummary(c);l&&this.isLikelyRelevant(l.summary,t)&&r.push({stepId:c,type:"recent",content:l.summary,metadata:l.metadata})}if(n==="explorer")C("\u8DF3\u8FC7\u63A2\u7D22\u5386\u53F2\u6CE8\u5165 (\u5F53\u524D\u4E3A explorer \u667A\u80FD\u4F53)");else{let c=this.globalContext.getExplorationHistory();c&&(r.push({stepId:0,type:"exploration",content:c.content,metadata:{timestamp:c.timestamp,summary:c.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`),r}getRecentCompletedSteps(e){return Array.from(this.globalContext.getStepDependencies().keys()).slice(-e)}isLikelyRelevant(e,t){let n=a=>a.toLowerCase().split(/\s+/).filter(c=>c.length>3).slice(0,10),r=new Set(n(e));return n(t).filter(a=>r.has(a)).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(`
1547
+ *...\u8FD8\u6709 ${Object.keys(e.devDependencies).length-10} \u4E2A\u4F9D\u8D56*`),o.push("")))}function Ym(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(`
1548
+ *...\u8FD8\u6709 ${e.entryPoints.length-5} \u4E2A\u5165\u53E3\u6587\u4EF6*`),o.push("")}function Qm(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(`
1549
+ *...\u8FD8\u6709 ${e.codeStandards.length-5} \u4E2A\u89C4\u8303*`),o.push("")}var ys=C(()=>{});import*as En from"os";var it,at,ct,lt,au=C(()=>{V();ys();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=[],L(`\u5168\u5C40\u4E0A\u4E0B\u6587\u521D\u59CB\u5316\uFF08\u5DF2\u6E05\u7A7A\u5386\u53F2\uFF09: ${this.plan.totalSteps} \u4E2A\u6B65\u9AA4`)):L(`\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 s=e;e===1&&this.stepSummaries.size>0&&(s=Math.max(...Array.from(this.stepSummaries.keys()))+1,S(`\u7B80\u5355\u4EFB\u52A1\u6B65\u9AA4ID\u81EA\u52A8\u9012\u589E: ${e} -> ${s}`)),this.stepSummaries.set(s,{summary:t,metadata:n,timestamp:new Date().toISOString()}),r&&r.buildHistoryIndex(s,t,n),S(`\u6B65\u9AA4 ${s} \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,S(`\u5171\u4EAB\u72B6\u6001\u66F4\u65B0: ${e}`)):S(`\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},L("\u5DF2\u8BB0\u5F55\u9879\u76EE\u63A2\u7D22\u7ED3\u679C\u5230\u5168\u5C40\u4E0A\u4E0B\u6587")}getExplorationHistory(){return this.explorationHistory}},at=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);S(`\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 d of c){let m=this.globalContext.getStepSummary(d);m&&(r.push({stepId:d,type:"dependency",content:m.summary,metadata:m.metadata}),s.add(d))}let l=this.analyzeFileRelevance(t);for(let d of l){if(s.has(d)||d>=e)continue;let m=this.globalContext.getStepSummary(d);if(m&&(r.push({stepId:d,type:"file_related",content:m.summary,metadata:m.metadata}),s.add(d),r.length>=Math.ceil(i/2)))break}let u=this.findRelevantStepsWithIndex(t,a);for(let d of u){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>=i))break}let p=Math.max(3,Math.floor(i/2));if(r.length<p){let d=this.getRecentCompletedSteps(i);for(let m of d){if(s.has(m)||m>=e)continue;let f=this.globalContext.getStepSummary(m);if(f&&(r.push({stepId:m,type:"recent",content:f.summary,metadata:f.metadata}),s.add(m),r.length>=p))break}}if(n==="explorer")S("\u8DF3\u8FC7\u63A2\u7D22\u5386\u53F2\u6CE8\u5165 (\u5F53\u524D\u4E3A explorer \u667A\u80FD\u4F53)");else{let d=this.globalContext.getExplorationHistory();d&&(r.push({stepId:0,type:"exploration",content:d.content,metadata:{timestamp:d.timestamp,summary:d.summary}}),S(`\u5DF2\u6DFB\u52A0\u63A2\u7D22\u5386\u53F2\u5230\u4E0A\u4E0B\u6587 (\u667A\u80FD\u4F53: ${n||"unknown"})`))}return S(`\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[s,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(s,c)}return Array.from(r.entries()).sort((s,i)=>i[1]-s[1]).slice(0,5).map(([s])=>s)}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 s=/(?:文件|file|模块|module|组件|component)[::\s]+([a-zA-Z0-9\-_]+)/gi,i;for(;(i=s.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"],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)}),S(`\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(()=>(ee(),en)),{callModelAPI:s}=await Promise.resolve().then(()=>(Ce(),kn)),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(`
1212
1550
  `);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()||""}
1213
1551
 
1214
1552
  \u5DF2\u5B8C\u6210\u7684\u5386\u53F2\u6B65\u9AA4\u6458\u8981:
@@ -1218,7 +1556,17 @@ ${i}
1218
1556
 
1219
1557
  \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
1220
1558
  \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
1221
- \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")C("\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}}),C(`\u5DF2\u6DFB\u52A0\u63A2\u7D22\u5386\u53F2\u5230\u4E0A\u4E0B\u6587 (LLM\u6A21\u5F0F, \u667A\u80FD\u4F53: ${n||"unknown"})`))}return $(`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)}}},He=class{globalContext;disclosure;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
1559
+ \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")S("\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}}),S(`\u5DF2\u6DFB\u52A0\u63A2\u7D22\u5386\u53F2\u5230\u4E0A\u4E0B\u6587 (LLM\u6A21\u5F0F, \u667A\u80FD\u4F53: ${n||"unknown"})`))}return L(`LLM \u4E3A\u6B65\u9AA4 ${e} \u9009\u62E9\u4E86 ${p.length} \u6761\u76F8\u5173\u5386\u53F2`),p}catch(c){return S(`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)}}},ct=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=[];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
1560
+
1561
+ \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
1562
+
1563
+ ${u.map(p=>`- ${p}`).join(`
1564
+ `)}
1565
+
1566
+ **\u91CD\u8981\u63D0\u9192**\uFF1A
1567
+ - \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
1568
+ - \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
1569
+ - \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
1222
1570
 
1223
1571
  ${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
1224
1572
 
@@ -1229,7 +1577,7 @@ ${c}`}),a.push({role:"user",content:`\u539F\u59CB\u4EFB\u52A1: ${this.globalCont
1229
1577
  ${this.globalContext.getSharedState().rules}
1230
1578
 
1231
1579
  ===============================
1232
- \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(`
1580
+ \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],[d])=>d-g).slice(0,3).reverse().map(([g,d])=>({stepId:g,type:"recent",content:d.summary,metadata:d.metadata})))}if(l.length>0){let u=l.map(p=>`[\u6B65\u9AA4${p.stepId}] ${p.content}`).join(`
1233
1581
 
1234
1582
  `);a.push({role:"user",content:`\u76F8\u5173\u5386\u53F2\u4FE1\u606F:
1235
1583
  ${u}`})}return a.push({role:"user",content:`\u5F53\u524D\u4EFB\u52A1 (\u6B65\u9AA4 ${e}/${this.globalContext.getPlan().totalSteps}):
@@ -1237,12 +1585,14 @@ ${t}`}),s&&s.length>0&&a.push({role:"system",content:`\u26A0\uFE0F \u672C\u6B65\
1237
1585
  \u4F60\u53EA\u80FD\u4F7F\u7528\u4EE5\u4E0B\u5DE5\u5177: ${s.join(", ")}
1238
1586
 
1239
1587
  \u5982\u679C\u4F60\u5C1D\u8BD5\u4F7F\u7528\u672A\u6388\u6743\u7684\u5DE5\u5177\uFF0C\u8C03\u7528\u4F1A\u88AB\u62D2\u7EDD\u3002
1240
- \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:
1588
+ \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 CRITICAL REMINDER FOR CODE TASKS:
1241
1589
  - You MUST use Action: write(path, content) to save any code you generate
1242
1590
  - You MUST use Action: merge(path, content) to modify existing files
1243
1591
  - NEVER just output code without saving it using Action:
1244
1592
  - Follow the exact format: "Thought: ..." then "Action: tool_name(args)"
1245
- - When task is done, use "Answer: ..." to finish`}),$(`\u4E3A\u6B65\u9AA4 ${e} \u6784\u5EFA\u4E86\u9694\u79BB\u4E0A\u4E0B\u6587\uFF0C\u5305\u542B ${a.length} \u6761\u6D88\u606F`),s&&$(`\u5DE5\u5177\u9650\u5236: ${s.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}),$("\u6784\u5EFA\u4E86\u7B80\u5316\u4E0A\u4E0B\u6587\uFF08\u7B80\u5355\u4EFB\u52A1\u6A21\u5F0F\uFF09"),n}async buildProjectEnvironmentContext(){try{let e=Jt.platform(),t=Jt.arch(),n=Jt.version(),r=process.cwd(),s=`\u{1F30D} **\u667A\u80FD\u73AF\u5883\u611F\u77E5\u7CFB\u7EDF**
1593
+ - When task is done, use "Answer: ..." to finish`}),L(`\u4E3A\u6B65\u9AA4 ${e} \u6784\u5EFA\u4E86\u9694\u79BB\u4E0A\u4E0B\u6587\uFF0C\u5305\u542B ${a.length} \u6761\u6D88\u606F`),s&&L(`\u5DE5\u5177\u9650\u5236: ${s.join(", ")}`),S(`\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}),L("\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(),S("\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,S("\u9879\u76EE\u4FE1\u606F\u5DF2\u66F4\u65B0\u7F13\u5B58"));let t=this.platformInfoCache;return this.projectInfoCache&&(t+=`
1594
+
1595
+ ${this.projectInfoCache}`),t}catch(e){return S(`\u6784\u5EFA\u9879\u76EE\u73AF\u5883\u4E0A\u4E0B\u6587\u5931\u8D25: ${e}`),null}}buildPlatformInfo(){let e=En.platform(),t=En.arch(),n=En.version(),r=process.cwd();return`\u{1F30D} **\u667A\u80FD\u73AF\u5883\u611F\u77E5\u7CFB\u7EDF**
1246
1596
 
1247
1597
  **\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
1598
 
@@ -1259,7 +1609,7 @@ ${t}`}),s&&s.length>0&&a.push({role:"system",content:`\u26A0\uFE0F \u672C\u6B65\
1259
1609
  ${e==="win32"?`
1260
1610
  **Windows\u7279\u5B9A\u6CE8\u610F\u4E8B\u9879\uFF1A**
1261
1611
  - \u4F7F\u7528Windows\u7B49\u4EF7\u547D\u4EE4\uFF1Adir(\u4EE3\u66FFls), where(\u4EE3\u66FFwhich), type(\u4EE3\u66FFcat)
1262
- - \u8DEF\u5F84\u5206\u9694\u7B26\u4F7F\u7528\u53CD\u659C\u6760()\uFF0C\u4F46Node.js\u901A\u5E38\u652F\u6301\u6B63\u659C\u6760(/)
1612
+ - \u8DEF\u5F84\u5206\u9694\u7B26\u4F7F\u7528\u53CD\u659C\u6760(\\)\uFF0C\u4F46Node.js\u901A\u5E38\u652F\u6301\u6B63\u659C\u6760(/)
1263
1613
  - \u73AF\u5883\u53D8\u91CF\u4F7F\u7528%VAR%\u683C\u5F0F\uFF0C\u4F46PowerShell\u4F7F\u7528$env:VAR
1264
1614
  - \u63A8\u8350\u4F7F\u7528PowerShell\u6216CMD\uFF0C\u907F\u514DUnix\u7279\u6709\u547D\u4EE4
1265
1615
  - \u6587\u4EF6\u7F16\u7801\u6CE8\u610FUTF-8\u4E0EGBK\u7684\u533A\u522B
@@ -1283,9 +1633,7 @@ ${e==="win32"?`
1283
1633
  - **\u73AF\u5883\u53D8\u91CF\uFF1A** \u4F7F\u7528process.env\u8BBF\u95EE\uFF0C\u907F\u514D\u5E73\u53F0\u7279\u5B9A\u8BED\u6CD5
1284
1634
  - **\u547D\u4EE4\u6267\u884C\uFF1A** \u4F18\u5148\u4F7F\u7528Node.js API\uFF0C\u5FC5\u8981\u65F6\u4F7F\u7528\u8DE8\u5E73\u53F0\u547D\u4EE4
1285
1635
  - **\u6587\u4EF6\u7CFB\u7EDF\uFF1A** \u6CE8\u610FWindows\u4E0D\u533A\u5206\u5927\u5C0F\u5199\uFF0CUnix\u7CFB\u7EDF\u533A\u5206\u5927\u5C0F\u5199
1286
- - **\u884C\u5C3E\u7B26\uFF1A** Windows\u4F7F\u7528\r
1287
- \uFF0CUnix\u4F7F\u7528
1288
- \uFF0C\u4F7F\u7528os.EOL\u83B7\u53D6\u6B63\u786E\u683C\u5F0F
1636
+ - **\u884C\u5C3E\u7B26\uFF1A** Windows\u4F7F\u7528\\r\\n\uFF0CUnix\u4F7F\u7528\\n\uFF0C\u4F7F\u7528os.EOL\u83B7\u53D6\u6B63\u786E\u683C\u5F0F
1289
1637
 
1290
1638
  ### \u26A1 \u547D\u4EE4\u9009\u62E9\u7B56\u7565
1291
1639
  1. **\u6587\u4EF6\u64CD\u4F5C\uFF1A** ${e==="win32"?"\u4F7F\u7528dir\u3001copy\u3001move\u3001del":"\u4F7F\u7528ls\u3001cp\u3001mv\u3001rm"}
@@ -1297,18 +1645,16 @@ ${e==="win32"?`
1297
1645
  - \u5728\u6267\u884Cshell\u547D\u4EE4\u524D\uFF0C\u52A1\u5FC5\u8003\u8651\u5F53\u524D\u5E73\u53F0\u7279\u6027
1298
1646
  - \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"}
1299
1647
  - \u63D0\u4F9B\u547D\u4EE4\u5EFA\u8BAE\u65F6\uFF0C\u4F18\u5148\u63A8\u8350${e==="win32"?"Windows\u539F\u751F":"Unix\u539F\u751F"}\u65B9\u6848
1300
- - \u9047\u5230\u8DE8\u5E73\u53F0\u517C\u5BB9\u6027\u95EE\u9898\u65F6\uFF0C\u4E3B\u52A8\u63D0\u51FA\u89E3\u51B3\u65B9\u6848`;try{let i=await import("fs"),c=(await import("path")).join(r,".nium/project/project.json");if(i.existsSync(c)){let l=i.readFileSync(c,"utf-8");try{let u=JSON.parse(l),p=this.extractProjectSummaryFromJSON(u);s+=`
1301
- **\u9879\u76EE\u7ED3\u6784\u6458\u8981:**
1302
- ${p}
1648
+ - \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:**
1649
+ ${this.extractProjectSummaryFromJSON(i)}
1303
1650
 
1304
- **\u5B8C\u6574\u7ED3\u6784\u6587\u6863:** \u5982\u9700\u8BE6\u7EC6\u4FE1\u606F\uFF0C\u8BF7\u4F7F\u7528 read('.nium/project/project.json')`}catch(u){C(`\u89E3\u6790project.json\u5931\u8D25\uFF0C\u4F7F\u7528\u6587\u672C\u6458\u8981: ${u}`);let p=this.extractProjectSummary(l);s+=`
1305
- **\u9879\u76EE\u7ED3\u6784\u6458\u8981:**
1306
- ${p}
1651
+ **\u5B8C\u6574\u7ED3\u6784\u6587\u6863:** \u5982\u9700\u8BE6\u7EC6\u4FE1\u606F\uFF0C\u8BF7\u4F7F\u7528 read('.nium/project/project.json')`}catch(i){return S(`\u89E3\u6790project.json\u5931\u8D25\uFF0C\u4F7F\u7528\u6587\u672C\u6458\u8981: ${i}`),`**\u9879\u76EE\u7ED3\u6784\u6458\u8981:**
1652
+ ${this.extractProjectSummary(s)}
1307
1653
 
1308
- **\u5B8C\u6574\u7ED3\u6784\u6587\u6863:** \u5982\u9700\u8BE6\u7EC6\u4FE1\u606F\uFF0C\u8BF7\u4F7F\u7528 read('.nium/project/project.json')`}}}catch(i){C(`\u83B7\u53D6\u9879\u76EE\u7ED3\u6784\u4FE1\u606F\u5931\u8D25: ${i}`)}return s}catch(e){return C(`\u6784\u5EFA\u9879\u76EE\u73AF\u5883\u4E0A\u4E0B\u6587\u5931\u8D25: ${e}`),null}}extractProjectSummaryFromJSON(e){return tr(e,{format:"summary",maxSections:3})}extractProjectSummary(e){let t=e.split(`
1654
+ **\u5B8C\u6574\u7ED3\u6784\u6587\u6863:** \u5982\u9700\u8BE6\u7EC6\u4FE1\u606F\uFF0C\u8BF7\u4F7F\u7528 read('.nium/project/project.json')`}}catch(e){return S(`\u83B7\u53D6\u9879\u76EE\u7ED3\u6784\u4FE1\u606F\u5931\u8D25: ${e}`),null}}extractProjectSummaryFromJSON(e){return qr(e,{format:"summary",maxSections:3})}extractProjectSummary(e){let t=e.split(`
1309
1655
  `),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(`
1310
- `)}},Je=class{async extractSummary(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(", ")})`)),C(`\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(`
1311
- `);if(r.length<100)return this.extractSummary(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 $(`LLM \u751F\u6210\u6458\u8981: ${i.substring(0,50)}...`),i}catch(s){return C(`LLM \u6458\u8981\u5931\u8D25\uFF0C\u964D\u7EA7\u5230\u542F\u53D1\u5F0F\u65B9\u6CD5: ${s instanceof Error?s.message:String(s)}`),this.extractSummary(e)}}extractMetadata(e){let t={toolsUsed:[],filesAccessed:[],errors:[],iterations:0};for(let n of e)if(n.role==="assistant"){if(t.iterations++,n.tool_calls&&n.tool_calls.length>0)for(let r of n.tool_calls){let s=r.function.name;if(s!=="think"&&(t.toolsUsed.push(s),["read","write","merge"].includes(s)))try{let i=JSON.parse(r.function.arguments),a=i.path||i.newContent;a&&t.filesAccessed.push(a)}catch{}}}else n.role==="tool"&&n.content&&n.content.includes("Error:")&&t.errors.push(n.content.substring(0,100));return t}}});var nr,Os=y(()=>{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}):
1656
+ `)}},lt=class{useLLMSummary;constructor(e=!0){this.useLLMSummary=e}setUseLLMSummary(e){this.useLLMSummary=e,S(`\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(", ")})`)),S(`\u63D0\u53D6\u6458\u8981: ${s.substring(0,50)}...`),s}async extractSummaryWithLLM(e){let{LITE_MODEL:t}=await Promise.resolve().then(()=>(ee(),en)),{callModelAPI:n}=await Promise.resolve().then(()=>(Ce(),kn)),r=e.filter(s=>s.content).map(s=>`${s.role}: ${s.content.substring(0,500)}`).join(`
1657
+ `);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 L(`LLM \u751F\u6210\u6458\u8981: ${i.substring(0,50)}...`),i}catch(s){return S(`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 Kr,Zi=C(()=>{Kr=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}):
1312
1658
 
1313
1659
  \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
1314
1660
 
@@ -1331,7 +1677,7 @@ ${r.successCriteria.map(i=>` \u2022 ${i}`).join(`
1331
1677
  4. \u786E\u4FDD\u6BCF\u4E00\u6B65\u90FD\u671D\u7740\u6700\u7EC8\u76EE\u6807\u524D\u8FDB
1332
1678
  5. \u6700\u7EC8\u7B54\u6848\u5FC5\u987B\u76F4\u63A5\u56DE\u5E94\u539F\u59CB\u95EE\u9898\u7684\u8981\u6C42
1333
1679
 
1334
- \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=y(()=>{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
1680
+ \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 Xr,ea=C(()=>{ee();Xr=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
1335
1681
 
1336
1682
  \u539F\u59CB\u6587\u672C: "${e}"
1337
1683
 
@@ -1343,7 +1689,7 @@ ${r.successCriteria.map(i=>` \u2022 ${i}`).join(`
1343
1689
  3. keyTopics: \u4E24\u4E2A\u6587\u672C\u7684\u5173\u952E\u4E3B\u9898\u5217\u8868
1344
1690
  4. deviationFactors: \u5BFC\u81F4\u504F\u79BB\u7684\u56E0\u7D20\u5217\u8868
1345
1691
 
1346
- \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
1692
+ \u53EA\u8FD4\u56DEJSON\uFF0C\u4E0D\u8981\u5176\u4ED6\u89E3\u91CA\u3002`;try{let i=(await this.modelClient({model:Be(),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
1347
1693
 
1348
1694
  \u68C0\u6D4B\u5230${t==="severe"?"\u4E25\u91CD":"\u8F7B\u5FAE"}\u504F\u79BB\u539F\u59CB\u95EE\u9898\u3002
1349
1695
 
@@ -1355,11 +1701,11 @@ ${n.map(s=>`\u2022 ${s}`).join(`
1355
1701
 
1356
1702
  \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+=`
1357
1703
 
1358
- \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=y(()=>{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=y(()=>{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={};O(kc,{getGitDiff:()=>sr,getGitStatus:()=>or,gitAddAll:()=>Vs,gitCommit:()=>Ws,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"}),C("Git is available"),!0):(C("Git not available: .git directory not found"),!1)}catch(o){return C(`Git not available: ${o.message}`),!1}}function or(){try{return ct("git status",{encoding:"utf-8"})}catch(o){return H(`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 ===
1704
+ \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 cu(o){let e=Zm[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 ut(o){let e=cu(o);return typeof e=="number"?e:parseFloat(String(e))}function ta(o){let e=cu(o);return typeof e=="boolean"?e:String(e).toLowerCase()==="true"}var Zm,na=C(()=>{Zm={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 xs(){return{...td,compressionInterval:ut("CONTEXT_COMPRESSION_INTERVAL"),semanticCheckInterval:ut("CONTEXT_SEMANTIC_CHECK_INTERVAL"),anchorInjectionInterval:ut("CONTEXT_ANCHOR_INTERVAL"),similarityThreshold:ut("CONTEXT_SIMILARITY_THRESHOLD"),maxMessagesBeforeCompression:ut("CONTEXT_MAX_MESSAGES"),driftCorrectionThreshold:ut("CONTEXT_DRIFT_THRESHOLD"),compressionRatioTarget:ut("CONTEXT_COMPRESSION_RATIO")}}var td,ra=C(()=>{na();td={compressionInterval:15,semanticCheckInterval:5,anchorInjectionInterval:10,similarityThreshold:.3,maxMessagesBeforeCompression:50,enableSmartCompression:!0,enableSemanticAnalysis:!0,enableAnchorSystem:!0,driftCorrectionThreshold:.25,maxContextLength:100,compressionRatioTarget:.7}});var pu={};_(pu,{getGitDiff:()=>Qr,getGitStatus:()=>Yr,gitAddAll:()=>oa,gitCommit:()=>sa,hasUncommittedChanges:()=>Zr,isGitAvailable:()=>sd});import{execSync as Rt}from"child_process";import{existsSync as lu,writeFileSync as nd,unlinkSync as rd}from"fs";import{join as uu}from"path";import{tmpdir as od}from"os";function sd(){try{let o=uu(process.cwd(),".git");return lu(o)?(Rt("git --version",{stdio:"ignore"}),S("Git is available"),!0):(S("Git not available: .git directory not found"),!1)}catch(o){return S(`Git not available: ${o.message}`),!1}}function Yr(){try{return Rt("git status",{encoding:"utf-8"})}catch(o){return Y(`Failed to get git status: ${o.message}`),""}}function Qr(){try{let o=Rt("git diff --cached",{encoding:"utf-8"}),e=Rt("git diff",{encoding:"utf-8"}),t="";return o&&(t+=`=== Staged Changes ===
1359
1705
  `+o+`
1360
1706
  `),e&&(t+=`=== Unstaged Changes ===
1361
- `+e),t||"No changes detected"}catch(o){return H(`Failed to get git diff: ${o.message}`),""}}function Vs(){try{ct("git add .",{stdio:"inherit"})}catch(o){throw new Error(`Failed to stage changes: ${o.message}`)}}function Ws(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){H(`Failed to cleanup temporary file: ${t.message}`)}}}function ir(){try{return ct("git status --porcelain",{encoding:"utf-8"}).trim().length>0}catch(o){return H(`Failed to check for uncommitted changes: ${o.message}`),!1}}var so=y(()=>{K()});var Hs={};O(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=y(()=>{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(`
1362
- `))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
1707
+ `+e),t||"No changes detected"}catch(o){return Y(`Failed to get git diff: ${o.message}`),""}}function oa(){try{Rt("git add .",{stdio:"inherit"})}catch(o){throw new Error(`Failed to stage changes: ${o.message}`)}}function sa(o){let e=uu(od(),`git-commit-${Date.now()}.txt`);try{nd(e,o,"utf-8"),Rt(`git commit -F "${e}"`,{stdio:"inherit"})}catch(t){throw new Error(`Failed to commit: ${t.message}`)}finally{try{lu(e)&&rd(e)}catch(t){Y(`Failed to cleanup temporary file: ${t.message}`)}}}function Zr(){try{return Rt("git status --porcelain",{encoding:"utf-8"}).trim().length>0}catch(o){return Y(`Failed to check for uncommitted changes: ${o.message}`),!1}}var Cs=C(()=>{V()});var aa={};_(aa,{FileChangeTracker:()=>pt,createFileChangeTracker:()=>Ss,detectFileChanges:()=>bs,generateChangeSummary:()=>vs,getCurrentSessionFileChanges:()=>ks,getFileChangeTracker:()=>Se,getSessionFileChanges:()=>Es,handleGitCommit:()=>Ps,recordFileChange:()=>Ts,resetFileChangeTracker:()=>ws});import{execSync as ia}from"child_process";function Se(o){return $n||($n=new pt(o)),$n}function Ss(o){return new pt(o)}function ws(){$n&&($n.stopWatching(),$n=null)}async function bs(o,e){return Se(e).detectFileChanges(o)}function vs(o="text"){return Se().generateChangeSummaryText(o)}function Ts(o){let e={id:vt(),filePath:o.filePath,changeType:o.changeType,timestamp:new Date().toISOString(),source:o.source||"manual",content:o.content,size:o.size};return Se().trackSessionFileChange("default-session",void 0,[e]),e}async function Ps(o){return Se().handleGitCommit(o)}function Es(o){return Se().getSessionFileChanges(o)}function ks(){return Se().getCurrentSessionFileChanges()}var id,pt,$n,Lt=C(()=>{_o();Cs();id={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"},pt=class{config;sessionChanges=new Map;commitHistory=[];gitStatusCache=new Map;changeCallbacks=[];isWatching=!1;gitStatusTimer;constructor(e){this.config={...id,...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(!Zr())return e;let t=Yr(),n=Qr(),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:vt(),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=ia("git status --porcelain",{encoding:"utf-8"});for(let r of n.trim().split(`
1708
+ `))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 ia("git rev-parse HEAD",{encoding:"utf-8"}).trim()}catch{return"unknown"}}getCurrentBranch(){try{return ia("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
1363
1709
 
1364
1710
  `;return r+=`\u{1F4C1} \u603B\u6587\u4EF6\u6570: ${n.totalFiles}
1365
1711
  `,r+=`\u2795 \u65B0\u589E\u6587\u4EF6: ${n.addedFiles}
@@ -1368,7 +1714,7 @@ ${n.map(s=>`\u2022 ${s}`).join(`
1368
1714
  `,r+=`\u{1F504} \u91CD\u547D\u540D\u6587\u4EF6: ${n.renamedFiles}
1369
1715
  `,r+=`\u{1F4E6} \u603B\u5927\u5C0F: ${(n.totalSize/1024).toFixed(2)} KB
1370
1716
  `,r+=`
1371
- \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=y(()=>{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
1717
+ \u{1F550} \u751F\u6210\u65F6\u95F4: ${new Date().toLocaleString()}`,r}},$n=null});function gt(o,e){if(!$s){let t=o||new pt;$s=new Is(t,e)}return $s}function gu(o,e){return new Is(o,e)}function mu(){$s=null}var ad,Is,$s,eo=C(()=>{Lt();ad={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}},Is=class{fileChangeTracker;config;anchors=new Map;constructor(e,t){this.fileChangeTracker=e,this.config={...ad,...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
1372
1718
 
1373
1719
  `,n=this.config.promptIntegration.maxSummaryLength-t.length,s=this.fileChangeTracker.generateChangeSummaryText("text").split(`
1374
1720
  `),i="";for(let a of s)if(i.length+a.length<n)i+=a+`
@@ -1379,22 +1725,23 @@ ${n.map(s=>`\u2022 ${s}`).join(`
1379
1725
  `;break}t+=`
1380
1726
  `}return this.config.promptIntegration.includeChangeDetails&&n>100&&(t+=`\u{1F4DD} \u53D8\u66F4\u8BE6\u60C5\u9884\u89C8\uFF1A
1381
1727
  `),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
1382
- `,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={};O(Js,{AnchorInjector:()=>ut,createAnchorInjector:()=>$c});function $c(o,e){return new ut(o,e)}var ut,cr=y(()=>{Os();js();Us();K();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
1383
- ${Array.from(g.entries()).map(([w,x])=>`${w}: ${x}`).join(`
1728
+ `,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}},$s=null});var ca={};_(ca,{AnchorInjector:()=>jt,createAnchorInjector:()=>du});function du(o,e){return new jt(o,e)}var jt,to=C(()=>{Zi();ea();ra();V();eo();Lt();jt=class{anchorManager;semanticAnalyzer;contextConfig;constructor(e,t){this.anchorManager=new Kr(e),this.semanticAnalyzer=new Xr(t),this.contextConfig=xs()}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=Se(),p=gt(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
1729
+ ${Array.from(g.entries()).map(([x,w])=>`${x}: ${w}`).join(`
1384
1730
  `)}
1385
1731
 
1386
- \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),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(`
1387
- `),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 d=`\u68C0\u6D4B\u5230${p.driftLevel}\u504F\u79BB\uFF1A${p.deviationFactors.join("; ")}`,m=await this.anchorManager.createAnchorMessage(n,p.similarityScore,p.driftLevel,d,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: ${m.metadata?.priority}}`),l.push(m)}c=n}catch(u){H(`\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(`
1388
- `),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){H(`\u951A\u70B9\u6CE8\u5165\u5931\u8D25: ${u.message}`)}return{messages:l,lastSemanticCheckIteration:c}}}});var Gs=y(()=>{vc();Os();js();cr()});var Mc={};O(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 Vg}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=y(()=>{xo=class{content;filePath;constructor(e,t){this.content=e,this.filePath=t}async parse(){try{return new Promise((e,t)=>{Vg(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 Wg}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=Wg(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=y(()=>{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=y(()=>{ro()});import{createHash as op}from"crypto";import{readFileSync as Vc,writeFileSync as sp,existsSync as ip,statSync as ap}from"fs";import{resolve as cp}from"path";function lp(o){try{let e=Vc(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=Vc(o,"utf-8").trim().split(`
1389
- `);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(`
1732
+ \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(x=>x.role==="system");f!==-1&&l.splice(f+1,0,m),S(`\u5DF2\u6CE8\u5165 ${g.size} \u4E2A\u6587\u4EF6\u53D8\u66F4\u951A\u70B9`)}}catch(u){S(`\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(`
1733
+ `),p=await this.semanticAnalyzer.analyzeSemanticDrift(t||this.anchorManager.getOriginalQuestion(),u,n);if(S(`\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):S(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);S(`\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){Y(`\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(`
1734
+ `),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);S(`\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){Y(`\u951A\u70B9\u6CE8\u5165\u5931\u8D25: ${u.message}`)}return{messages:l,lastSemanticCheckIteration:c}}}});var la=C(()=>{au();Zi();ea();to()});var fu={};_(fu,{GradleBuildParser:()=>no,JavaDependencyAnalyzer:()=>Ls,MavenPomParser:()=>Rs,analyzeJavaProject:()=>pa});import{readFileSync as Ms,existsSync as As}from"fs";import{resolve as ua}from"path";import{parseString as cd}from"xml2js";async function pa(o=process.cwd()){let e=ua(o,"pom.xml"),t=ua(o,"build.gradle"),n=ua(o,"build.gradle.kts"),r=null;try{if(As(e)){let i=Ms(e,"utf-8");r=await new Rs(i,e).parse()}else if(As(t)){let i=Ms(t,"utf-8");r=new no(i,t).parse()}else if(As(n)){let i=Ms(n,"utf-8");r=new no(i,n).parse()}if(!r)return null;let s={project:r,conflicts:[],outdated:[],unused:[],recommendations:[]};return s.recommendations=Ls.generateRecommendations(s),s}catch(s){return ie("Error analyzing Java project: "+(s instanceof Error?s.message:String(s)),"java-analyzer"),null}}var Rs,no,Ls,ga=C(()=>{tt();Rs=class{content;filePath;constructor(e,t){this.content=e,this.filePath=t}async parse(){try{return new Promise((e,t)=>{cd(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 ie("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):[]}},no=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 ie("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(As(e))try{let n=Ms(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}},Ls=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 ld,readFileSync as ud}from"fs";import{resolve as pd,dirname as gd}from"path";function hu(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(md))for(let l of c.files){if(l.includes("*"))continue;let u=pd(o,l);if(ld(u)&&(t.add(c.language),n.push(l),r==="Unknown")){r=c.language,s=a;try{let p=ud(u,"utf-8"),g=c.parser(p,u);g instanceof Promise?O(`Async parser not supported in sync readProjectConfig: ${a}`,"project-config"):i=g}catch(p){O(`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:s,configFiles:n}}function dd(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 fd(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 hd(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 yd(o,e){try{return{name:e.split(/[/\\]/).slice(-2,-1)[0]||"unknown",version:"0.0.0",description:""}}catch{return null}}function xd(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 Cd(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 Sd(o,e){try{return{name:e.split(/[/\\]/).slice(-2,-1)[0]||"unknown",version:"0.0.0",description:""}}catch{return null}}function wd(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 bd(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 yu(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 vd(o,e){try{let t=await pa(gd(e));if(!t)return null;let n=t.project,r={};n.dependencies.forEach(i=>{r[`${i.groupId}:${i.artifactId}`]=i.version});let s=yu(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 ie("Error parsing POM XML with enhanced parser: "+(t instanceof Error?t.message:String(t)),"project-config"),null}}async function Td(o,e){try{let t=await Promise.resolve().then(()=>(ga(),fu)),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=yu(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 ie("Error parsing Gradle build file with enhanced parser: "+(t instanceof Error?t.message:String(t)),"project-config"),null}}var md,xu=C(()=>{ga();tt();md={nodejs:{files:["package.json"],language:"JavaScript/TypeScript",parser:dd},"java-maven":{files:["pom.xml"],language:"Java",parser:vd},"java-gradle":{files:["build.gradle","build.gradle.kts"],language:"Java",parser:async(o,e)=>await Td(o,e)},"python-pip":{files:["setup.py","setup.cfg"],language:"Python",parser:fd},"python-poetry":{files:["pyproject.toml"],language:"Python",parser:hd},"python-pipenv":{files:["Pipfile"],language:"Python",parser:yd},go:{files:["go.mod"],language:"Go",parser:xd},rust:{files:["Cargo.toml"],language:"Rust",parser:Cd},ruby:{files:["Gemfile"],language:"Ruby",parser:Sd},php:{files:["composer.json"],language:"PHP",parser:wd},dotnet:{files:["*.csproj","*.vbproj","*.fsproj"],language:"C#/.NET",parser:bd}}});import{writeFileSync as Pd,existsSync as Ed,mkdirSync as kd}from"fs";import{resolve as Cu}from"path";function Su(o,e=process.cwd()){let t=Cu(e,".nium","project");Ed(t)||kd(t,{recursive:!0});let r=Cu(t,"project.json"),s=JSON.stringify(o,null,2);Pd(r,s,"utf-8"),console.log(`\u2705 \u9879\u76EE\u4FE1\u606F\u5DF2\u4FDD\u5B58\u81F3: ${r}`)}function wu(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 bu=C(()=>{ys()});import{createHash as $d}from"crypto";import{readFileSync as vu,writeFileSync as Id,existsSync as Md,statSync as Ad}from"fs";import{resolve as Rd}from"path";function Ld(o){try{let e=vu(o),t=$d("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 jd(o,e=process.cwd()){try{let t=Rd(e,o),n=Ad(t),r=Ld(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 Dd(o){let e=new Map;if(!Md(o))return e;try{let n=vu(o,"utf-8").trim().split(`
1735
+ `);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 Fd(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));Id(e,t.join(`
1390
1736
  `)+`
1391
- `,"utf-8")}catch(t){throw console.error(`\u274C \u5199\u5165 JSONL \u6587\u4EF6\u5931\u8D25: ${e}`,t),t}}function Wc(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(`
1392
- `)}var Hc=y(()=>{});var Gc={};O(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=y(()=>{U();Dt();Oc();Uc();Hc();bs();pt=class extends P{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...
1393
- `),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)
1394
- `),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,b]of Object.entries(d))t.push(` - ${S}: ${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 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,b)=>S+(b.dependencies?.length||0),0),x=Object.values(h).reduce((S,b)=>S+(b.conflicts?.length||0),0);t.push(` - \u4F9D\u8D56\u603B\u6570: ${w}`),x>0&&t.push(` - \u4F9D\u8D56\u51B2\u7A81: ${x}`),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 k=this.buildProjectBasicInfo(u,p,i,g,l,d,m,h);try{_c(k,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(),b=Wc(i,f,n),L=((Date.now()-S)/1e3).toFixed(1);t.push("\u2705 \u6587\u4EF6\u4FE1\u606F\u5DF2\u66F4\u65B0\u81F3: .nium/project/files.jsonl"),t.push("");let M=zc(b);t.push(M),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 v=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(v),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(`
1395
- `)}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(`
1396
- `):"\u6682\u65E0\u7248\u672C\u4FE1\u606F",p=a.length>0?a.map(g=>`- ${g}`).join(`
1397
- `):"\u6682\u65E0\u4EE3\u7801\u89C4\u8303\u914D\u7F6E";return`# ${e.name} - \u9879\u76EE\u7ED3\u6784\u6587\u6863
1737
+ `,"utf-8")}catch(t){throw console.error(`\u274C \u5199\u5165 JSONL \u6587\u4EF6\u5931\u8D25: ${e}`,t),t}}function Tu(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=Dd(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),f=((Date.now()-u)/1e3).toFixed(1);console.log(` \u{1F4CA} \u5904\u7406\u8FDB\u5EA6: ${l}/${c} (${m}%) - \u5DF2\u7528\u65F6 ${f}s`)}let g=r.get(p),d=jd(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...`),Fd(i,e),n&&console.log(" \u2705 JSONL \u6587\u4EF6\u5199\u5165\u5B8C\u6210"),s}function Pu(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(`
1738
+ `)}var Eu=C(()=>{});var Iu={};_(Iu,{QuickProjectScanTool:()=>Ft,quickProjectScan:()=>In,quickProjectScanTool:()=>Mn});import{existsSync as Dt,statSync as Od}from"fs";import{globSync as _d}from"glob";import*as ku from"path";async function In(){return $u.execute({})}var Ft,$u,Mn,ma=C(()=>{U();Je();xu();bu();Eu();Ri();Ft=class extends ${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\u4F7F\u7528 glob \u6A21\u5F0F\u5339\u914D\uFF0C\u9650\u5236\u626B\u63CF\u6587\u4EF6\u6570\u4EE5\u63D0\u5347\u901F\u5EA6\u3002\u626B\u63CF\u7ED3\u679C\u4FDD\u5B58\u81F3 .nium/project/\u3002",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...
1739
+ `),t.push("\u{1F4C2} \u626B\u63CF\u9879\u76EE\u6587\u4EF6...");let r=ge(n,!0);t.push(` - \u5E94\u7528 ${r.length} \u6761\u5FFD\u7565\u89C4\u5219`);let s=Date.now(),i=_d("**/*",{nodir:!0,ignore:r,cwd:n}),a=this.prioritizeImportantFiles(i,n),c=((Date.now()-s)/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)
1740
+ `),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 hu(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 d=this.detectProjectLanguages(a);t.push(`\u4E3B\u8981\u7F16\u7A0B\u8BED\u8A00: ${d.primaryLanguage||u.primaryLanguage||"\u672A\u77E5"}`),d.languages.length>0&&t.push(`\u68C0\u6D4B\u5230 ${d.languages.length} \u79CD\u7F16\u7A0B\u8BED\u8A00`),t.push(""),t.push("\u2699\uFE0F \u68C0\u6D4B\u8FD0\u884C\u65F6\u7248\u672C...");let m=await this.detectVersions(u,n);if(Object.keys(m).length>0)for(let[P,b]of Object.entries(m))t.push(` - ${P}: ${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 x=await this.analyzeDependencies(n,u.languages),w=Object.values(x).reduce((P,b)=>P+(b.dependencies?.length||0),0),v=Object.values(x).reduce((P,b)=>P+(b.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 h=await this.buildProjectBasicInfo(p,g,i,d,u,m,f,x);try{Su(h,n),t.push("\u2705 \u9879\u76EE\u57FA\u7840\u4FE1\u606F\u5DF2\u4FDD\u5B58\u81F3: .nium/project/"),t.push("")}catch(P){console.error(" \u274C \u4FDD\u5B58\u9879\u76EE\u4FE1\u606F\u5931\u8D25:",P),t.push(`\u26A0\uFE0F \u4FDD\u5B58\u9879\u76EE\u4FE1\u606F\u5931\u8D25: ${P instanceof Error?P.message:"\u672A\u77E5\u9519\u8BEF"}`),t.push("")}t.push("\u{1F4DD} \u66F4\u65B0\u6587\u4EF6\u4FE1\u606F\u5217\u8868...");let y=`${n}/.nium/project/files.jsonl`;try{let P=Date.now(),b=Tu(i,y,n),M=((Date.now()-P)/1e3).toFixed(1);t.push("\u2705 \u6587\u4EF6\u4FE1\u606F\u5DF2\u66F4\u65B0\u81F3: .nium/project/files.jsonl"),t.push("");let D=Pu(b);t.push(D),t.push("")}catch(P){console.error(" \u274C \u66F4\u65B0\u6587\u4EF6\u4FE1\u606F\u5931\u8D25:",P),t.push(`\u26A0\uFE0F \u66F4\u65B0\u6587\u4EF6\u4FE1\u606F\u5931\u8D25: ${P instanceof Error?P.message:"\u672A\u77E5\u9519\u8BEF"}`),t.push("")}let T=this.generateSummary(p,g,d,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(T),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(`
1741
+ `)}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 d of g.patterns)if(this.matchesPattern(c,d)){g.priority>l&&(l=g.priority,u=d);break}let p=this.getFileSize(t,c);return p&&p>1024*1024&&(l=Math.max(10,l-20)),{file:c,score:l,pattern:u}}),s=e.length,i=200;return s<100?i=s:s<500?i=Math.min(300,s*.8):s<1e3?i=Math.min(400,s*.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 Od(ku.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),[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 rt.detectVersionsForLanguages(e.languages,t,e.configFiles)}catch{return{}}}async detectCodeStandards(e,t){try{return await rt.detectCodeStandardsForLanguages(t,e)}catch{return[]}}async analyzeDependencies(e,t){let n={};try{for(let r of t){let s=rt.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)}async 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(([m,f])=>`**${m}**: ${f}`).join(`
1742
+ `):"\u6682\u65E0\u7248\u672C\u4FE1\u606F",p=a.length>0?a.map(m=>`- ${m}`).join(`
1743
+ `):"\u6682\u65E0\u4EE3\u7801\u89C4\u8303\u914D\u7F6E",d=(await this.findEntryPoints(e,n,s)).map(m=>`- \`${m}\``).join(`
1744
+ `);return`# ${e.name} - \u9879\u76EE\u7ED3\u6784\u6587\u6863
1398
1745
 
1399
1746
  > \u6700\u540E\u66F4\u65B0: ${c}
1400
1747
  > \u7248\u672C: ${e.version}
@@ -1426,7 +1773,7 @@ ${this.generateDirectoryTree(n)}
1426
1773
  ## \u7F16\u7A0B\u8BED\u8A00\u5206\u6790
1427
1774
 
1428
1775
  ### \u8BED\u8A00\u5206\u5E03
1429
- ${r.languages.length>0?r.languages.map(g=>`- **${g.language}**: ${g.count} \u4E2A\u6587\u4EF6`).join(`
1776
+ ${r.languages.length>0?r.languages.map(m=>`- **${m.language}**: ${m.count} \u4E2A\u6587\u4EF6`).join(`
1430
1777
  `):"\u6682\u65E0\u68C0\u6D4B\u5230\u7684\u7F16\u7A0B\u8BED\u8A00"}
1431
1778
 
1432
1779
  ---
@@ -1439,11 +1786,11 @@ ${this.generateDirectoryDescriptions(t.directories,s.languages)}
1439
1786
 
1440
1787
  ## \u6838\u5FC3\u6A21\u5757\u5206\u6790
1441
1788
 
1442
- ${l.length>0?l.map(g=>`### ${g.name}
1789
+ ${l.length>0?l.map(m=>`### ${m.name}
1443
1790
 
1444
- ${g.description}
1791
+ ${m.description}
1445
1792
 
1446
- **\u5305\u542B\u6587\u4EF6**: ${g.files.length} \u4E2A`).join(`
1793
+ **\u5305\u542B\u6587\u4EF6**: ${m.files.length} \u4E2A`).join(`
1447
1794
 
1448
1795
  `):"\u6682\u65E0\u6838\u5FC3\u6A21\u5757\u5206\u6790"}
1449
1796
 
@@ -1451,7 +1798,7 @@ ${g.description}
1451
1798
 
1452
1799
  ## \u6E90\u4EE3\u7801\u6587\u4EF6 (${t.sourceFiles.length} \u4E2A)
1453
1800
 
1454
- ${t.sourceFiles.length>0?t.sourceFiles.slice(0,50).map(g=>`- \`${g}\``).join(`
1801
+ ${t.sourceFiles.length>0?t.sourceFiles.slice(0,50).map(m=>`- \`${m}\``).join(`
1455
1802
  `)+(t.sourceFiles.length>50?`
1456
1803
 
1457
1804
  *...\u8FD8\u6709 ${t.sourceFiles.length-50} \u4E2A\u6587\u4EF6*`:""):"\u6682\u65E0\u6E90\u4EE3\u7801\u6587\u4EF6"}
@@ -1460,14 +1807,14 @@ ${t.sourceFiles.length>0?t.sourceFiles.slice(0,50).map(g=>`- \`${g}\``).join(`
1460
1807
 
1461
1808
  ## \u914D\u7F6E\u6587\u4EF6 (${t.configFiles.length} \u4E2A)
1462
1809
 
1463
- ${t.configFiles.length>0?t.configFiles.map(g=>`- \`${g}\``).join(`
1810
+ ${t.configFiles.length>0?t.configFiles.map(m=>`- \`${m}\``).join(`
1464
1811
  `):"\u6682\u65E0\u914D\u7F6E\u6587\u4EF6"}
1465
1812
 
1466
1813
  ---
1467
1814
 
1468
1815
  ## \u6587\u6863\u6587\u4EF6 (${t.docFiles.length} \u4E2A)
1469
1816
 
1470
- ${t.docFiles.length>0?t.docFiles.slice(0,20).map(g=>`- \`${g}\``).join(`
1817
+ ${t.docFiles.length>0?t.docFiles.slice(0,20).map(m=>`- \`${m}\``).join(`
1471
1818
  `)+(t.docFiles.length>20?`
1472
1819
 
1473
1820
  *...\u8FD8\u6709 ${t.docFiles.length-20} \u4E2A\u6587\u6863*`:""):"\u6682\u65E0\u6587\u6863\u6587\u4EF6"}
@@ -1476,7 +1823,7 @@ ${t.docFiles.length>0?t.docFiles.slice(0,20).map(g=>`- \`${g}\``).join(`
1476
1823
 
1477
1824
  ## \u6D4B\u8BD5\u6587\u4EF6 (${t.testFiles.length} \u4E2A)
1478
1825
 
1479
- ${t.testFiles.length>0?t.testFiles.slice(0,20).map(g=>`- \`${g}\``).join(`
1826
+ ${t.testFiles.length>0?t.testFiles.slice(0,20).map(m=>`- \`${m}\``).join(`
1480
1827
  `)+(t.testFiles.length>20?`
1481
1828
 
1482
1829
  *...\u8FD8\u6709 ${t.testFiles.length-20} \u4E2A\u6D4B\u8BD5\u6587\u4EF6*`:""):"\u6682\u65E0\u6D4B\u8BD5\u6587\u4EF6"}
@@ -1486,11 +1833,11 @@ ${t.testFiles.length>0?t.testFiles.slice(0,20).map(g=>`- \`${g}\``).join(`
1486
1833
  ## \u4F9D\u8D56\u5173\u7CFB
1487
1834
 
1488
1835
  ### \u751F\u4EA7\u4F9D\u8D56
1489
- ${e.dependencies?Object.entries(e.dependencies).map(([g,d])=>`- **${g}**: ${d}`).join(`
1836
+ ${e.dependencies?Object.entries(e.dependencies).map(([m,f])=>`- **${m}**: ${f}`).join(`
1490
1837
  `):"\u6682\u65E0\u751F\u4EA7\u4F9D\u8D56"}
1491
1838
 
1492
1839
  ### \u5F00\u53D1\u4F9D\u8D56
1493
- ${e.devDependencies?Object.entries(e.devDependencies).map(([g,d])=>`- **${g}**: ${d}`).join(`
1840
+ ${e.devDependencies?Object.entries(e.devDependencies).map(([m,f])=>`- **${m}**: ${f}`).join(`
1494
1841
  `):"\u6682\u65E0\u5F00\u53D1\u4F9D\u8D56"}
1495
1842
 
1496
1843
  ---
@@ -1498,22 +1845,21 @@ ${e.devDependencies?Object.entries(e.devDependencies).map(([g,d])=>`- **${g}**:
1498
1845
  ## \u5FEB\u901F\u5BFC\u822A
1499
1846
 
1500
1847
  ### \u5165\u53E3\u6587\u4EF6
1501
- ${this.findEntryPoints(e,n,s).map(g=>`- \`${g}\``).join(`
1502
- `)}
1848
+ ${d}
1503
1849
 
1504
1850
  ### \u6838\u5FC3\u6A21\u5757
1505
- ${this.findCoreModules(t.sourceFiles).map(g=>`- \`${g}\``).join(`
1851
+ ${this.findCoreModules(t.sourceFiles).map(m=>`- \`${m}\``).join(`
1506
1852
  `)}
1507
1853
 
1508
1854
  ---
1509
1855
 
1510
1856
  **\u6587\u6863\u751F\u6210\u65F6\u95F4**: ${c}
1511
1857
  **\u6587\u6863\u751F\u6210\u5DE5\u5177**: quickProjectScan \u5DE5\u5177
1512
- `}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+`
1513
- `,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}/\`
1858
+ `}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 ",f=d?" ":"\u2502 ";l+=i+m+u+`
1859
+ `,p!==null&&typeof p=="object"&&(l+=n(p,i+f,d))}),l}let r=n(t);return r?r.trim():""}generateDirectoryDescriptions(e,t){let n=rt.getDirectoryDescriptionsForLanguages(t);return e.map(r=>{let s=n[r]||"\u9879\u76EE\u76EE\u5F55";return`### \`${r}/\`
1514
1860
  ${s}`}).join(`
1515
1861
 
1516
- `)}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(k=>({name:k.name,description:k.description,fileCount:k.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[k,f]of Object.entries(c))f.dependencies&&f.dependencies.forEach(v=>{let S=v.groupId&&v.artifactId?`${v.groupId}:${v.artifactId}`:v.name||"";S&&v.version&&(v.scope&&v.scope.toLowerCase().includes("test")?m[S]||(m[S]=v.version,w++):d[S]||(d[S]=v.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`
1862
+ `)}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 s=process.cwd(),i=await rt.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()}async buildProjectBasicInfo(e,t,n,r,s,i,a,c){let l=wu(r.languages),p=this.analyzeCoreModules(t).map(v=>({name:v.name,description:v.description,fileCount:v.files.length})),g;s.primaryLanguage.includes("JavaScript")||s.primaryLanguage.includes("TypeScript")?Dt("package-lock.json")?g="npm":Dt("yarn.lock")?g="yarn":Dt("pnpm-lock.yaml")?g="pnpm":g="npm":s.primaryLanguage.includes("Python")?Dt("poetry.lock")?g="poetry":Dt("Pipfile.lock")?g="pipenv":g="pip":s.primaryLanguage.includes("Java")?Dt("pom.xml")?g="maven":Dt("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||{}},f=Object.keys(d).length,x=Object.keys(m).length;if(c)for(let[v,h]of Object.entries(c))h.dependencies&&h.dependencies.forEach(y=>{let T=y.groupId&&y.artifactId?`${y.groupId}:${y.artifactId}`:y.name||"";T&&y.version&&(y.scope&&y.scope.toLowerCase().includes("test")?m[T]||(m[T]=y.version,x++):d[T]||(d[T]=y.version,f++))});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:f,development:x},detailedDependencies:c,runtimeVersions:Object.keys(i).length>0?i:void 0,codeStandards:a,entryPoints:await 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`
1517
1863
  \u{1F4E6} \u9879\u76EE: ${e.name} (v${e.version})
1518
1864
  \u{1F310} \u4E3B\u8981\u8BED\u8A00: ${r.primaryLanguage}
1519
1865
  ${r.buildTool?`\u{1F527} \u6784\u5EFA\u5DE5\u5177: ${r.buildTool}`:""}
@@ -1522,7 +1868,7 @@ ${r.buildTool?`\u{1F527} \u6784\u5EFA\u5DE5\u5177: ${r.buildTool}`:""}
1522
1868
  \u2699\uFE0F \u914D\u7F6E\u6587\u4EF6: ${t.configFiles.length} \u4E2A
1523
1869
  \u{1F4DA} \u6587\u6863\u6587\u4EF6: ${t.docFiles.length} \u4E2A
1524
1870
  \u{1F9EA} \u6D4B\u8BD5\u6587\u4EF6: ${t.testFiles.length} \u4E2A
1525
- `}formatAction(e){return"quickProjectScan()"}formatObservation(e){return String(e)}},Jc=new pt;Kt=Jc});var ei={};O(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=y(()=>{U();vo=class extends P{getDefinition(){return{name:"finish",description:`Call this tool when you have completed the task and want to provide the final answer.
1871
+ `}formatAction(e){return"quickProjectScan()"}formatObservation(e){return String(e)}},$u=new Ft;Mn=$u});var ya={};_(ya,{FINISH_TOOL:()=>Wd,FinishTool:()=>js,extractFinishInfo:()=>ha,finish:()=>Nd,finishTool:()=>Ud,isFinishResult:()=>zd,isFinishTool:()=>fa});function Nd(o){return da.execute(o)}function fa(o){return o==="finish"}function ha(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 zd(o){return o&&typeof o=="object"&&o.completed===!0&&typeof o.answer=="string"}var js,da,Ud,Wd,Ds=C(()=>{U();js=class extends ${getDefinition(){return{name:"finish",description:`Call this tool when you have completed the task and want to provide the final answer.
1526
1872
 
1527
1873
  IMPORTANT: This is the RECOMMENDED way to signal task completion.
1528
1874
 
@@ -1542,10 +1888,10 @@ Example usage:
1542
1888
  finish({
1543
1889
  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.",
1544
1890
  success: true
1545
- })`,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={};O(ni,{executePlanTask:()=>xp,getGlobalSession:()=>Cp,resumePlanTask:()=>Sp,setGlobalSession:()=>ti});import E from"chalk";function ti(o){V=o}function Cp(){return V}async function xp(o,e=1,t={}){let n=new We,r=new ze(n),s=new He(n,r),i=new Je,{callModelAPI:a}=await Promise.resolve().then(()=>(ve(),Gt)),{AnchorInjector:c}=await Promise.resolve().then(()=>(cr(),Js)),l=new c(o,a),u=Yt(),p={useLLMDisclosure:t.useLLMDisclosure!==void 0?t.useLLMDisclosure:!0,useLLMSummary:t.useLLMSummary!==void 0?t.useLLMSummary:!0,verbose:t.verbose||!1},g=f=>{V?V.log(f):console.log(f)},d=f=>{V?V.info(f):console.log(E.blue(f))},m=f=>{V?V.success(f):console.log(E.green(f))},h=f=>{V?V.warning(f):console.log(E.yellow(f))},w=f=>{V?V.error(f):console.log(E.red(f))},x=" ".repeat(e-1),k=new bo({log:g,info:d,success:m,warning:h,error:w});try{let f=await import("fs"),v=await import("path");try{let M=v.join(process.cwd(),".nium/project/project.json");if(f.existsSync(M)){let I=f.statSync(M);(Date.now()-I.mtimeMs)/(1e3*60*60)>24&&h("\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:I}=await Promise.resolve().then(()=>(Ys(),Gc));await I(),m(`\u2705 \u9879\u76EE\u7ED3\u6784\u626B\u63CF\u5B8C\u6210
1546
- `)}}catch{h("\u9879\u76EE\u7ED3\u6784\u626B\u63CF\u5931\u8D25\uFF0C\u5C06\u7EE7\u7EED\u6267\u884C\u4EFB\u52A1")}g(""),g(`${x}${"\u2550".repeat(60-e*2)}`),d(`${x}\u{1F4CB} \u5F00\u59CB\u89C4\u5212\u4EFB\u52A1 (\u5D4C\u5957\u5C42\u7EA7: ${e})`),g(`${x}${"\u2550".repeat(60-e*2)}`),g("");let S=u.getAllSubAgents(),b=await Zn(o,S);n.initializeTask(o,b),b.taskId&&St(b.taskId);let L=vp(er(b),e);g(L),g(""),k.showTaskStart(o,b.tasks.length,e);for(let M=0;M<b.tasks.length;M++){let I=b.tasks[M],q=I.step;k.showStepProgress(q,b.tasks.length,I,e),n.plan.currentStep=q,b.taskId&&await at(b.taskId,q,"in_progress");try{let Q=Bc(I,u),J=await s.buildIsolatedContext(q,I.description,Q?.prompt||"",p.useLLMDisclosure,I.allowedTools);Q?await qc(q,I.description,Q,J,n,i,u,p,{log:g,info:d,success:m,warning:h,error:w},I.allowedTools):await Kc(I.description,J,n,{log:g,info:d},I.allowedTools),k.showStepComplete(q,b.tasks.length,I,e),b.taskId&&await at(b.taskId,q,"completed")}catch(Q){let J=Q instanceof Error?Q.message:String(Q);throw k.showStepError(q,b.tasks.length,J,e),h(`${x}\u4E2D\u6B62\u540E\u7EED\u6B65\u9AA4\u6267\u884C`),n.recordStepCompletion(q,`\u5931\u8D25: ${J}`,{success:!1,error:J}),Q}}return k.showTaskComplete(b.tasks.length,b.tasks.length,e),vt(),{success:!0,taskId:b.taskId,completedSteps:b.tasks.length,plan:b,planMarkdown:b.markdown,tasks:b.tasks}}catch(f){vt();let v=f instanceof Error?f.message:String(f);throw w(`${x}\u274C \u89C4\u5212\u4EFB\u52A1\u6267\u884C\u5931\u8D25: ${v}`),f}}async function Sp(o,e=0,t={}){let{loadTaskPlan:n}=await Promise.resolve().then(()=>($e(),Ve)),r=n(o);if(!r)throw new Error(`\u65E0\u6CD5\u52A0\u8F7D\u4EFB\u52A1\u8BA1\u5212: ${o}`);let s=new We,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=>{V?V.log(f):console.log(f)},g=f=>{V?V.info(f):console.log(E.blue(f))},d=f=>{V?V.success(f):console.log(E.green(f))},m=f=>{V?V.warning(f):console.log(E.yellow(f))},h=f=>{V?V.error(f):console.log(E.red(f))};p(E.cyan(`[\u4EFB\u52A1\u6062\u590D] \u6B63\u5728\u6062\u590D\u4EFB\u52A1: ${o}`)),p(E.gray(`\u4ECE\u6B65\u9AA4 ${e||1} \u5F00\u59CB\u6267\u884C`));let w=1,x="",k=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(E.cyan("\u2550".repeat(60))),g("\u{1F4CB} \u6062\u590D\u4EFB\u52A1\u6267\u884C"),p(E.cyan("\u2550".repeat(60))),p(""),k.showTaskStart(r.taskId,r.tasks.length,w);let f=e>0?e-1:0;for(let v=f;v<r.tasks.length;v++){let S=r.tasks[v],b=S.step;if(k.showStepProgress(b,r.tasks.length,S,w),s.plan.currentStep=b,r.taskId){let{updateTaskStatus:L}=await Promise.resolve().then(()=>($e(),Ve));await L(r.taskId,b,"in_progress")}try{let L=Bc(S,l),M=await a.buildIsolatedContext(b,S.description,L?.prompt||"",u.useLLMDisclosure,S.allowedTools);if(L?await qc(b,S.description,L,M,s,c,l,u,{log:p,info:g,success:d,warning:m,error:h},S.allowedTools):await Kc(S.description,M,s,{log:p,info:g},S.allowedTools),k.showStepComplete(b,r.tasks.length,S,w),r.taskId){let{updateTaskStatus:I}=await Promise.resolve().then(()=>($e(),Ve));await I(r.taskId,b,"completed")}}catch(L){let M=L instanceof Error?L.message:String(L);throw k.showStepError(b,r.tasks.length,M,w),m(`${x}\u4E2D\u6B62\u540E\u7EED\u6B65\u9AA4\u6267\u884C`),s.recordStepCompletion(b,`\u5931\u8D25: ${M}`,{success:!1,error:M}),L}}return k.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 v=f instanceof Error?f.message:String(f);throw h(`${x}\u274C \u4EFB\u52A1\u6062\u590D\u6267\u884C\u5931\u8D25: ${v}`),f}}function vp(o,e){return e<=1?o:o.split(`
1891
+ })`,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}},da=new js;Ud=da,Wd=da.getDefinition()});var Ca={};_(Ca,{executePlanTask:()=>Vd,getGlobalSession:()=>Hd,resumePlanTask:()=>Bd,setGlobalSession:()=>xa});import k from"chalk";function xa(o){q=o}function Hd(){return q}async function Vd(o,e=1,t={}){let n=t.useLLMSummary!==void 0?t.useLLMSummary:!0,r=new it,s=new at(r),i=new ct(r,s),a=new lt(n),{callModelAPI:c}=await Promise.resolve().then(()=>(Ce(),kn)),{AnchorInjector:l}=await Promise.resolve().then(()=>(to(),ca)),u=new l(o,c),p=An(),g={useLLMDisclosure:t.useLLMDisclosure!==void 0?t.useLLMDisclosure:!0,useLLMSummary:t.useLLMSummary!==void 0?t.useLLMSummary:!0,verbose:t.verbose||!1},d=y=>{q?q.log(y):console.log(y)},m=y=>{q?q.info(y):console.log(k.blue(y))},f=y=>{q?q.success(y):console.log(k.green(y))},x=y=>{q?q.warning(y):console.log(k.yellow(y))},w=y=>{q?q.error(y):console.log(k.red(y))},v=" ".repeat(e-1),h=new Fs({log:d,info:m,success:f,warning:x,error:w});try{let y=await import("fs"),T=await import("path");try{let D=T.join(process.cwd(),".nium/project/project.json");if(y.existsSync(D)){let j=y.statSync(D);(Date.now()-j.mtimeMs)/(1e3*60*60)>24&&x("\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:j}=await Promise.resolve().then(()=>(ma(),Iu));await j(),f(`\u2705 \u9879\u76EE\u7ED3\u6784\u626B\u63CF\u5B8C\u6210
1892
+ `)}}catch{x("\u9879\u76EE\u7ED3\u6784\u626B\u63CF\u5931\u8D25\uFF0C\u5C06\u7EE7\u7EED\u6267\u884C\u4EFB\u52A1")}d(""),d(`${v}${"\u2550".repeat(60-e*2)}`),m(`${v}\u{1F4CB} \u5F00\u59CB\u89C4\u5212\u4EFB\u52A1 (\u5D4C\u5957\u5C42\u7EA7: ${e})`),d(`${v}${"\u2550".repeat(60-e*2)}`),d("");let P=p.getAllSubAgents(),b=await Gr(o,P);r.initializeTask(o,b),b.taskId&&Qt(b.taskId);let M=Gd(Jr(b),e);d(M),d(""),h.showTaskStart(o,b.tasks.length,e);for(let D=0;D<b.tasks.length;D++){let j=b.tasks[D],R=j.step;h.showStepProgress(R,b.tasks.length,j,e),r.plan.currentStep=R,b.taskId&&await At(b.taskId,R,"in_progress");try{let A=Mu(j,p),I=await i.buildIsolatedContext(R,j.description,A?.prompt||"",g.useLLMDisclosure,j.allowedTools);A?await Au(R,j.description,A,I,r,a,s,p,g,{log:d,info:m,success:f,warning:x,error:w},j.allowedTools):await Ru(j.description,I,r,{log:d,info:m},j.allowedTools),h.showStepComplete(R,b.tasks.length,j,e),b.taskId&&await At(b.taskId,R,"completed")}catch(A){let I=A instanceof Error?A.message:String(A);throw h.showStepError(R,b.tasks.length,I,e),x(`${v}\u4E2D\u6B62\u540E\u7EED\u6B65\u9AA4\u6267\u884C`),r.recordStepCompletion(R,`\u5931\u8D25: ${I}`,{success:!1,error:I}),A}}return h.showTaskComplete(b.tasks.length,b.tasks.length,e),Zt(),{success:!0,taskId:b.taskId,completedSteps:b.tasks.length,plan:b,planMarkdown:b.markdown,tasks:b.tasks}}catch(y){Zt();let T=y instanceof Error?y.message:String(y);throw w(`${v}\u274C \u89C4\u5212\u4EFB\u52A1\u6267\u884C\u5931\u8D25: ${T}`),y}}async function Bd(o,e=0,t={}){let{loadTaskPlan:n}=await Promise.resolve().then(()=>(_e(),st)),r=n(o);if(!r)throw new Error(`\u65E0\u6CD5\u52A0\u8F7D\u4EFB\u52A1\u8BA1\u5212: ${o}`);let s=new it,i=new at(s),a=new ct(s,i),c=new lt,l=An(),u={useLLMDisclosure:t.useLLMDisclosure!==void 0?t.useLLMDisclosure:!0,useLLMSummary:t.useLLMSummary!==void 0?t.useLLMSummary:!0,verbose:t.verbose||!1},p=h=>{q?q.log(h):console.log(h)},g=h=>{q?q.info(h):console.log(k.blue(h))},d=h=>{q?q.success(h):console.log(k.green(h))},m=h=>{q?q.warning(h):console.log(k.yellow(h))},f=h=>{q?q.error(h):console.log(k.red(h))};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 x=1,w="",v=new Fs({log:p,info:g,success:d,warning:m,error:f});try{s.initializeTask(r.taskId,r),r.taskId&&Qt(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(""),v.showTaskStart(r.taskId,r.tasks.length,x);let h=e>0?e-1:0;for(let y=h;y<r.tasks.length;y++){let T=r.tasks[y],P=T.step;if(v.showStepProgress(P,r.tasks.length,T,x),s.plan.currentStep=P,r.taskId){let{updateTaskStatus:b}=await Promise.resolve().then(()=>(_e(),st));await b(r.taskId,P,"in_progress")}try{let b=Mu(T,l),M=await a.buildIsolatedContext(P,T.description,b?.prompt||"",u.useLLMDisclosure,T.allowedTools);if(b?await Au(P,T.description,b,M,s,c,i,l,u,{log:p,info:g,success:d,warning:m,error:f},T.allowedTools):await Ru(T.description,M,s,{log:p,info:g},T.allowedTools),v.showStepComplete(P,r.tasks.length,T,x),r.taskId){let{updateTaskStatus:D}=await Promise.resolve().then(()=>(_e(),st));await D(r.taskId,P,"completed")}}catch(b){let M=b instanceof Error?b.message:String(b);throw v.showStepError(P,r.tasks.length,M,x),m(`${w}\u4E2D\u6B62\u540E\u7EED\u6B65\u9AA4\u6267\u884C`),s.recordStepCompletion(P,`\u5931\u8D25: ${M}`,{success:!1,error:M}),b}}return v.showTaskComplete(r.tasks.length,r.tasks.length,x),Zt(),{success:!0,taskId:r.taskId,completedSteps:r.tasks.length-h,resumedFrom:e||1}}catch(h){Zt();let y=h instanceof Error?h.message:String(h);throw f(`${w}\u274C \u4EFB\u52A1\u6062\u590D\u6267\u884C\u5931\u8D25: ${y}`),h}}function Gd(o,e){return e<=1?o:o.split(`
1547
1893
  `).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(`
1548
- `)}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){let{log:u,info:p,error:g}=c,d=Date.now();p(`\u{1F527} \u4F7F\u7528\u5B50\u667A\u80FD\u4F53: ${t.name}`),u(E.gray(`\u63CF\u8FF0: ${t.description}`)),l&&l.length>0&&u(E.gray(`\u6CE8\u610F: \u5B50\u667A\u80FD\u4F53 ${t.name} \u4E0D\u53D7\u6B65\u9AA4\u5DE5\u5177\u9650\u5236\u5F71\u54CD`)),u("");try{let{SYSTEM_PROMPT:m}=await Promise.resolve().then(()=>(it(),Fs)),h=[{role:"system",content:m},...n.filter(k=>k.role!=="system"),...n.filter(k=>k.role==="system"&&k!==n[0])],w=await Yc(h,e,c,void 0,t);await wp(o,w,r,s,a,c);let x=Date.now()-d;i.recordAgentPerformance(t.name,!0,x)}catch(m){let h=Date.now()-d;throw i.recordAgentPerformance(t.name,!1,h),m}}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(E.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:x}=await Promise.resolve().then(()=>(Ne(),Zi)),{logDebug:k,logWarn:f}=await Promise.resolve().then(()=>(K(),Yo)),{AnchorInjector:v}=await Promise.resolve().then(()=>(cr(),Js)),S=[...o],b=0,L=50,M=0,I=new v(e,c),q=d(),Q=n&&n.length>0?q.filter(J=>n.includes(J.name)):q;for(n&&n.length>0&&k(`\u672C\u6B65\u9AA4\u53EF\u7528\u5DE5\u5177: ${Q.map(J=>J.name).join(", ")}`);b<L;){b++,k(`Loop iteration ${b}`);try{let J=await I.injectAnchors({taskDescription:e,iterations:b,messages:S,lastSemanticCheckIteration:M,callModelAPI:c}),{messages:R,lastSemanticCheckIteration:oe}=J;S=R,M=oe,x(S,e);let te=await c({model:a(),messages:S,temperature:.1,tools:Q}),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(()=>(K(),Yo));Oe(`Error in finalAnswerCallback: ${Fe}`)}s(E.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(E.yellow(F)),s(""));continue}let z=on[0],Te=z.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:[z]}),S.push({role:"tool",tool_call_id:z.id,content:F});continue}let kr;try{kr=JSON.parse(z.function.arguments)}catch{i(`\u89E3\u6790\u5DE5\u5177\u53C2\u6570\u5931\u8D25: ${z.function.arguments}`),S.push({role:"assistant",content:null,tool_calls:[z]}),S.push({role:"tool",tool_call_id:z.id,content:"Error: Invalid JSON arguments"});continue}if(l(Te)){let F=u(z);F&&(s(E.cyan(`\u{1F4AD} Think: ${F}`)),s("")),S.push({role:"assistant",content:null,tool_calls:[z]}),S.push({role:"tool",tool_call_id:z.id,content:"Noted. Continue with your action."});continue}if(p(Te)){let F=g(z);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(E.green(`${Rl} \u4EFB\u52A1\u5B8C\u6210 (\u901A\u8FC7 finish \u5DE5\u5177):`)),s(Fe),s(""),S.push({role:"assistant",content:null,tool_calls:[z]}),S.push({role:"tool",tool_call_id:z.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:[z]}),S.push({role:"tool",tool_call_id:z.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:[z]}),S.push({role:"tool",tool_call_id:z.id,content:Oe});continue}}let ft=h[Te],Ml=ft?ft.formatAction(kr):`${Te}()`;s(E.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(E.yellow(`\u{1F4CA} \u89C2\u5BDF: ${Ll}`)),s("")),S.push({role:"assistant",content:null,tool_calls:[z]}),S.push({role:"tool",tool_call_id:z.id,content:String(Il)}),x(S,e)}catch(J){throw i(`\u9519\u8BEF: ${J.message}`),x(S,e),J}}if(b>=L)throw i("\u9519\u8BEF: \u5DF2\u8FBE\u5230\u6700\u5927\u8FED\u4EE3\u6B21\u6570"),x(S,e),new Error("Maximum iterations reached");return S}async function wp(o,e,t,n,r,s){let{info:i,log:a}=s,c;r.useLLMSummary?c=await n.extractSummaryWithLLM(e):c=await n.extractSummary(e);let l=n.extractMetadata(e);l.success=!0,t.recordStepCompletion(o,c,l),r.verbose&&(i(`\u6B65\u9AA4 ${o} \u6458\u8981\u5DF2\u8BB0\u5F55\u5230\u5168\u5C40\u4E0A\u4E0B\u6587`),a(""),a(E.gray("\u2500\u2500\u2500 \u6B65\u9AA4\u6267\u884C\u6458\u8981 \u2500\u2500\u2500")),a(E.gray(`\u6458\u8981: ${c}`)),a(E.gray(`\u5DE5\u5177: ${l.toolsUsed.join(", ")}`)),a(E.gray(`\u6587\u4EF6: ${l.filesAccessed.join(", ")}`)),a(E.gray(`\u8FED\u4EE3: ${l.iterations} \u6B21`)))}var bo,V,To=y(()=>{$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(E.cyan(`${r}\u2554${"\u2550".repeat(58-n*2)}\u2557`)),this.log(E.cyan(`${r}\u2551`)+E.bold.white(" \u{1F680} \u5F00\u59CB\u6267\u884C\u4EFB\u52A1\u8BA1\u5212")+E.cyan(` (\u5171${t}\u6B65)`.padEnd(58-n*2-13))+E.cyan("\u2551")),this.log(E.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(E.blue(`${s}\u250C${"\u2500".repeat(58-r*2)}\u2510`)),this.log(E.blue(`${s}\u2502`)+` \u6B65\u9AA4 ${e}/${t} (${i}%)`.padEnd(60-r*2)+E.blue("\u2502")),this.log(E.blue(`${s}\u2502`)+` ${a}`.padEnd(60-r*2)+E.blue("\u2502")),this.log(E.blue(`${s}\u2502`)+E.cyan(` \u{1F4CC} ${n.description}`.substring(0,58-r*2)).padEnd(60-r*2)+E.blue("\u2502")),this.log(E.blue(`${s}\u2502`)+E.gray(` \u{1F916} \u667A\u80FD\u4F53: ${n.subAgent}`.substring(0,58-r*2)).padEnd(60-r*2)+E.blue("\u2502")),this.log(E.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${E.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(E.green(`${r}\u2554${"\u2550".repeat(58-n*2)}\u2557`)),this.log(E.green(`${r}\u2551`)+E.bold.white(" \u{1F389} \u4EFB\u52A1\u6267\u884C\u5B8C\u6210!")+E.green("".padEnd(58-n*2-12))+E.green("\u2551")),this.log(E.green(`${r}\u2551`)+` \u5B8C\u6210\u8FDB\u5EA6: ${e}/${t} (${i}%)`.padEnd(60-n*2)+E.green("\u2551")),this.log(E.green(`${r}\u2551`)+` \u603B\u8017\u65F6: ${s}`.padEnd(60-n*2)+E.green("\u2551")),this.log(E.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`${E.green("\u2588".repeat(n))+E.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`}},V=null});import bp from"chalk";async function gr(o){return await Xc.execute(o)}var De,Xc,pr,oi=y(()=>{U();De=class o extends P{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}
1894
+ `)}function Mu(o,e){return o.subAgent&&o.subAgent!=="default"?e.getSubAgent(o.subAgent):null}async function Au(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:f}=await Promise.resolve().then(()=>(Mt(),Qi)),x=[{role:"system",content:f},...n.filter(h=>h.role!=="system"),...n.filter(h=>h.role==="system"&&h!==n[0])],w=await Lu(x,e,l,void 0,t);await Jd(o,w,r,s,i,c,l);let v=Date.now()-m;a.recordAgentPerformance(t.name,!0,v)}catch(f){let x=Date.now()-m;throw a.recordAgentPerformance(t.name,!1,x),f}}async function Ru(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(()=>(Mt(),Qi)),c=[{role:"system",content:a},...e.filter(l=>l.role!=="system"),...e.filter(l=>l.role==="system")];await Lu(c,o,n,r)}async function Lu(o,e,t,n,r=null){let{log:s,error:i}=t,{MODEL:a}=await Promise.resolve().then(()=>(ee(),en)),{callModelAPI:c}=await Promise.resolve().then(()=>(Ce(),kn)),{isThinkTool:l,extractThought:u}=await Promise.resolve().then(()=>(Vr(),_i)),{isFinishTool:p,extractFinishInfo:g}=await Promise.resolve().then(()=>(Ds(),ya)),{getToolDefinitions:d}=await Promise.resolve().then(()=>(Pn(),Sa)),{tools:m,toolInstances:f,extractToolResult:x}=await Promise.resolve().then(()=>(Ke(),ro)),{saveSession:w}=await Promise.resolve().then(()=>(Ve(),vc)),{logDebug:v,logWarn:h}=await Promise.resolve().then(()=>(V(),ci)),{AnchorInjector:y}=await Promise.resolve().then(()=>(to(),ca)),T=[...o],P=0,b=50,M=0,D=new y(e,c),j=d(),R=n&&n.length>0?j.filter(A=>n.includes(A.name)):j;for(n&&n.length>0&&v(`\u672C\u6B65\u9AA4\u53EF\u7528\u5DE5\u5177: ${R.map(A=>A.name).join(", ")}`);P<b;){P++,v(`Loop iteration ${P}`);try{let A=await D.injectAnchors({taskDescription:e,iterations:P,messages:T,lastSemanticCheckIteration:M,callModelAPI:c}),{messages:I,lastSemanticCheckIteration:z}=A;T=I,M=z,w(T,e);let le=await c({model:a(),messages:T,temperature:.1,tools:R}),Kn=le.choices[0].message.tool_calls;if(le.choices[0].finish_reason==="stop"){let{content:H}=le.choices[0].message;if(H&&H.trim()){if(r?.finalAnswerCallback)try{await r.finalAnswerCallback(H)}catch(Ze){let{logError:et}=await Promise.resolve().then(()=>(V(),ci));et(`Error in finalAnswerCallback: ${Ze}`)}s(k.green("\u4EFB\u52A1\u5B8C\u6210:")),s(H),s("")}break}if(!Kn||Kn.length===0){let{content:H}=le.choices[0].message;H&&H.trim()&&(s(k.yellow(H)),s(""));continue}let X=Kn[0],Fe=X.function.name;if(n&&n.length>0&&!n.includes(Fe)){let H=`Error: \u5DE5\u5177 '${Fe}' \u672A\u5728\u672C\u6B65\u9AA4\u7684\u6388\u6743\u5217\u8868\u4E2D\u3002\u5141\u8BB8\u4F7F\u7528\u7684\u5DE5\u5177: ${n.join(", ")}`;i(H),T.push({role:"assistant",content:null,tool_calls:[X]}),T.push({role:"tool",tool_call_id:X.id,content:H});continue}let Ao;try{Ao=JSON.parse(X.function.arguments)}catch{i(`\u89E3\u6790\u5DE5\u5177\u53C2\u6570\u5931\u8D25: ${X.function.arguments}`),T.push({role:"assistant",content:null,tool_calls:[X]}),T.push({role:"tool",tool_call_id:X.id,content:"Error: Invalid JSON arguments"});continue}if(l(Fe)){let H=u(X);H&&(s(k.cyan(`\u{1F4AD} Think: ${H}`)),s("")),T.push({role:"assistant",content:null,tool_calls:[X]}),T.push({role:"tool",tool_call_id:X.id,content:"Noted. Continue with your action."});continue}if(p(Fe)){let H=g(X);if(H){let{answer:Ze,success:et}=H;if(r?.finalAnswerCallback)try{await r.finalAnswerCallback(Ze)}catch(Hp){h(`Error in finalAnswerCallback: ${Hp}`)}let zp=et?"\u2705":"\u26A0\uFE0F";s(k.green(`${zp} \u4EFB\u52A1\u5B8C\u6210 (\u901A\u8FC7 finish \u5DE5\u5177):`)),s(Ze),s(""),T.push({role:"assistant",content:null,tool_calls:[X]}),T.push({role:"tool",tool_call_id:X.id,content:"Task completed successfully."}),T.push({role:"assistant",content:Ze});break}}if(!m[Fe]){let H=`Error: Unknown tool '${Fe}'`;i(H),T.push({role:"assistant",content:null,tool_calls:[X]}),T.push({role:"tool",tool_call_id:X.id,content:H});continue}let Ro=d().find(H=>H.name===Fe);if(Ro&&Ro.input_schema&&Ro.input_schema.required){let Ze=(Ro.input_schema.required||[]).filter(et=>Ao[et]===void 0);if(Ze.length>0){let et=`Error: Missing required parameters: ${Ze.join(", ")}`;i(et),T.push({role:"assistant",content:null,tool_calls:[X]}),T.push({role:"tool",tool_call_id:X.id,content:et});continue}}let Bt=f[Fe],_p=Bt?Bt.formatAction(Ao):`${Fe}()`;s(k.blue(`\u884C\u52A8: ${_p}`)),s("");let Lo=await m[Fe](Ao),Np=x(Lo),Up=Bt?Bt.shouldPrintObservation(Lo):!0,Wp=Bt?Bt.formatObservation(Lo):String(Lo);Up&&(s(k.yellow(`\u89C2\u5BDF: ${Wp}`)),s("")),T.push({role:"assistant",content:null,tool_calls:[X]}),T.push({role:"tool",tool_call_id:X.id,content:String(Np)}),w(T,e)}catch(A){throw i(`\u9519\u8BEF: ${A.message}`),w(T,e),A}}if(P>=b)throw i("\u9519\u8BEF: \u5DF2\u8FBE\u5230\u6700\u5927\u8FED\u4EE3\u6B21\u6570"),w(T,e),new Error("Maximum iterations reached");return T}async function Jd(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 Fs,q,Os=C(()=>{_e();_s();Ve();la();Fs=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`}},q=null});import qd from"chalk";async function oo(o){return await ju.execute(o)}var Xe,ju,so,wa=C(()=>{U();Xe=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}
1549
1895
 
1550
1896
  IDEAL USE CASES:
1551
1897
  - Building new features that span multiple files or components
@@ -1572,7 +1918,7 @@ AVOID FOR:
1572
1918
  RECOMMENDATION BASED ON CURRENT NESTING LEVEL (${e}/${t}):
1573
1919
  ${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!"}
1574
1920
 
1575
- 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(),Ve)),{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
1921
+ 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(),st)),{getSubAgentManager:s}=await Promise.resolve().then(()=>(_s(),Du)),a=s().getAllSubAgents(),c=await r(t,a),l=`\u2705 \u4EFB\u52A1\u89C4\u5212\u5DF2\u751F\u6210\uFF08\u4EC5\u89C4\u5212\u6A21\u5F0F\uFF09
1576
1922
 
1577
1923
  `;return l+=`**\u4EFB\u52A1 ID**: ${c.taskId}
1578
1924
  `,l+=`**\u603B\u6B65\u9AA4\u6570**: ${c.tasks.length}
@@ -1585,7 +1931,7 @@ When you're uncertain if a task needs planning, default to using regular tools d
1585
1931
  `,l+=`**\u6267\u884C\u6B65\u9AA4**:
1586
1932
  `,c.tasks.forEach((u,p)=>{l+=`${p+1}. ${u.description} [${u.subAgent}]
1587
1933
  `}),l+=`
1588
- \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!
1934
+ \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(()=>(Os(),Ca))).executePlanTask(t,o.nestingLevel)}catch{console.log(qd.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!
1589
1935
 
1590
1936
  `;return s+=`**Task ID**: ${r.taskId}
1591
1937
  `,s+=`**Completed Steps**: ${r.completedSteps}
@@ -1595,7 +1941,7 @@ ${r.planMarkdown}
1595
1941
 
1596
1942
  `),r.tasks&&r.tasks.length>0&&(s+=`**Executed Steps**:
1597
1943
  `,r.tasks.forEach((i,a)=>{s+=`${a+1}. \u2713 ${i.description}
1598
- `})),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=y(()=>{Zc=null});import Ke from"readline";import dt from"chalk";async function mr(o){return await tl.execute(o)}var Xt,tl,fr,nl=y(()=>{U();Eo();Xt=class extends P{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.
1944
+ `})),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."}},ju=new Xe;so=ju});function Ou(o){Fu=o}function io(){return Fu}var Fu,Ns=C(()=>{Fu=null});import mt from"readline";import Ot from"chalk";async function ao(o){return await _u.execute(o)}var Rn,_u,co,Nu=C(()=>{U();Ns();ee();Rn=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.
1599
1945
 
1600
1946
  Use this tool when you need:
1601
1947
  - User confirmation or decision
@@ -1612,7 +1958,7 @@ IMPORTANT:
1612
1958
  Examples:
1613
1959
  - askUser({ question: "Which file should I modify?" }) - Free text input
1614
1960
  - askUser({ question: "Proceed with deletion?", choices: ["Yes", "No"] }) - Multiple choice
1615
- - 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=y(()=>{U();Qt=class extends P{getDefinition(){return{name:"todo",description:`Execute and manage saved task plans. Use this tool to:
1961
+ - 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 mi()?s=await this.showInkModePrompt(t,n,r):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&&mt.moveCursor(process.stdout,0,-1),mt.clearLine(process.stdout,0);console.log(""),console.log(Ot.cyan("\u{1F4AC} "+e)),console.log(""),console.log(Ot.gray("\u8BF7\u9009\u62E9 (\u4F7F\u7528\u4E0A\u4E0B\u7BAD\u5934\u952E\uFF0CEnter\u786E\u8BA4):")),console.log(""),i.forEach((g,d)=>{let m=d===s,f=m?Ot.green("> "):" ",x=m?Ot.green.bold(g.text):Ot.white(g.text);console.log(`${f}${x}`)}),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 f=0;f<d;f++)mt.moveCursor(process.stdout,0,-1),mt.clearLine(process.stdout,0);let m=i[s].value;if(m==="__CUSTOM__"){let f=await this.showFreeTextInput(e);r(f)}else r(m);return}else if(g.name==="escape"||g.ctrl&&g.name==="c"){let d=io();d?d.removeListener("keypress",l):(process.stdin.removeListener("keypress",l),process.stdin.isTTY&&process.stdin.setRawMode(c));let m=i.length+5;for(let f=0;f<m;f++)mt.moveCursor(process.stdout,0,-1),mt.clearLine(process.stdout,0);r("__CANCELLED__");return}},u=io();u?u.on("keypress",l):(mt.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=mt.createInterface({input:process.stdin,output:process.stdout});console.log(""),console.log(Ot.cyan("\u{1F4AC} "+n)),console.log(""),s.question(Ot.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())})})}showInkModePrompt(e,t,n=!1){return new Promise((r,s)=>{let{EventEmitter:i}=Bp("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}`),s(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)}},_u=new Rn;co=_u});async function lo(o){return await Uu.execute(o)}var Ln,Uu,uo,Wu=C(()=>{U();Ln=class extends ${getDefinition(){return{name:"todo",description:`Execute and manage saved task plans. Use this tool to:
1616
1962
  - Resume execution of a previously generated plan
1617
1963
  - List all available task plans
1618
1964
  - View details of a specific task plan
@@ -1626,13 +1972,13 @@ WHEN TO USE:
1626
1972
  FEATURES:
1627
1973
  - Resume from any step (default: continue from last step)
1628
1974
  - View task progress and status
1629
- - 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
1975
+ - 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(()=>(Os(),Ca)),r=await n(e,t||0),s=`\u2705 \u4EFB\u52A1\u6062\u590D\u6267\u884C\u5B8C\u6210\uFF01
1630
1976
 
1631
1977
  `;return s+=`**\u4EFB\u52A1 ID**: ${r.taskId}
1632
1978
  `,s+=`**\u5B8C\u6210\u6B65\u9AA4**: ${r.completedSteps}
1633
1979
  `,s+=`**\u6062\u590D\u8D77\u70B9**: \u6B65\u9AA4 ${r.resumedFrom}
1634
1980
 
1635
- `,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(),Ve)),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)
1981
+ `,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(),st)),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)
1636
1982
  `;r+=`${"\u2550".repeat(60)}
1637
1983
 
1638
1984
  `;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}**
@@ -1643,7 +1989,7 @@ FEATURES:
1643
1989
  `,r+=`
1644
1990
  `}}return r+=`
1645
1991
  \u{1F4A1} \u4F7F\u7528 todo(action="view", taskId="...") \u67E5\u770B\u8BE6\u60C5`,r+=`
1646
- \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(),Ve)),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
1992
+ \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(),st)),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
1647
1993
  `;r+=`${"\u2550".repeat(60)}
1648
1994
 
1649
1995
  `,r+=`**\u4EFB\u52A1 ID**: ${n.taskId}
@@ -1665,7 +2011,502 @@ FEATURES:
1665
2011
  `),r+=`
1666
2012
  `}let s=n.tasks.find(i=>i.status!=="completed");return s?r+=`
1667
2013
  \u{1F4A1} \u4F7F\u7528 todo(action="resume", taskId="${e}", resumeFrom=${s.step}) \u4ECE\u6B65\u9AA4 ${s.step} \u7EE7\u7EED\u6267\u884C`:r+=`
1668
- \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={};O(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:()=>Vt,thinkTool:()=>Wt,todo:()=>hr,todoTool:()=>yr});var Po=y(()=>{Xn();oi();nl();Ys();ol()});async function sl(o){return ai.execute(o)}var ii,ai,il,wx,al=y(()=>{U();ar();ii=class extends P{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.
2014
+ \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}},Uu=new Ln;uo=Uu});import*as Dn from"fs";import*as po from"path";import{globSync as Kd}from"glob";import{readFileSync as zu}from"fs";async function go(o){return Hu.execute(o)}var jn,Hu,mo,Vu=C(()=>{U();Je();Ce();ee();jn=class extends ${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
2015
+
2016
+ \u{1F4CB} \u7528\u9014\uFF1A
2017
+ - \u5206\u6790\u9879\u76EE\u6574\u4F53\u67B6\u6784\u548C\u8BBE\u8BA1\u7406\u5FF5
2018
+ - \u7406\u89E3\u6A21\u5757\u95F4\u4F9D\u8D56\u5173\u7CFB\u548C\u6570\u636E\u6D41\u5411
2019
+ - \u8BC6\u522B\u8BBE\u8BA1\u6A21\u5F0F\u548C\u67B6\u6784\u51B3\u7B56
2020
+ - \u8BC4\u4F30\u7CFB\u7EDF\u7ED3\u6784\u7684\u5408\u7406\u6027
2021
+
2022
+ \u{1F511} \u53C2\u6570\uFF1A
2023
+ - 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
2024
+ - englishTopic: \u82F1\u6587\u4E3B\u9898\uFF08\u5FC5\u586B\uFF0C\u751F\u6210\u6587\u6863\u6587\u4EF6\u540D\uFF09
2025
+
2026
+ \u{1F4A1} \u793A\u4F8B\uFF1A
2027
+ - explore({ topic: "\u9879\u76EE\u67B6\u6784", englishTopic: "Project Architecture" })
2028
+ - explore({ topic: "\u7CFB\u7EDF\u8BBE\u8BA1", englishTopic: "System Design" })
2029
+ - explore({ topic: "\u6A21\u5757\u5173\u7CFB", englishTopic: "Module Relationships" })
2030
+
2031
+ \u26A0\uFE0F \u6CE8\u610F\uFF1A
2032
+ - \u672C\u5DE5\u5177\u4E13\u6CE8\u4E8E\u67B6\u6784\u7EA7\u5206\u6790\uFF0830-60\u79D2\uFF09
2033
+ - \u6A21\u5757\u5185\u90E8\u5B9E\u73B0\u8BF7\u4F7F\u7528 ModuleExplorer
2034
+ - \u5DE5\u5177\u94FE\u914D\u7F6E\u8BF7\u4F7F\u7528 ToolingExplorer
2035
+
2036
+ \u{1F4DD} \u8F93\u51FA\uFF1A
2037
+ - \u4FDD\u5B58\u67B6\u6784\u62A5\u544A\u5230 .nium/docs/<TOPIC>_ARCHITECTURE.md
2038
+ - \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}
2039
+ `),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 s=await this.analyzeModuleRelations(r.allFiles);n.push(` \u2713 \u8BC6\u522B ${s.modules.length} \u4E2A\u6838\u5FC3\u6A21\u5757`),n.push(` \u2713 \u5206\u6790 ${s.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(s,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,s,i,a);return n.push(` \u2713 \u62A5\u544A\u5DF2\u4FDD\u5B58: ${po.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(`
2040
+ \u{1F3D7}\uFE0F \u67B6\u6784\u7C7B\u578B: ${a.type}`),n.push(`\u{1F4E6} \u6838\u5FC3\u6A21\u5757: ${s.modules.length} \u4E2A`),n.push(`\u{1F517} \u4F9D\u8D56\u5173\u7CFB: ${s.dependencies.length} \u4E2A`),n.push(`\u{1F3AF} \u8BBE\u8BA1\u6A21\u5F0F: ${i.patterns.length} \u4E2A`),n.push(`
2041
+ \u{1F4A1} \u67B6\u6784\u6458\u8981:`),n.push(a.summary),n.push(`
2042
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
2043
+ `),n.join(`
2044
+ `)}catch(t){return this.formatError("Explore",t)}}async loadProjectStructure(e){let t=ge(e,!0);return{allFiles:Kd("**/*",{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 s=/(?: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=zu(a,"utf-8"),l;for(;(l=s.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 s=zu(r,"utf-8");n.forEach(i=>{i.pattern.test(s)&&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
2045
+
2046
+ ## \u6A21\u5757\u4FE1\u606F
2047
+ ${e.modules.map(s=>`- ${s.name} (${s.type})`).join(`
2048
+ `)}
2049
+
2050
+ ## \u4F9D\u8D56\u5173\u7CFB
2051
+ ${e.dependencies.map(s=>`- ${s.from} -> ${s.to}`).join(`
2052
+ `)}
2053
+
2054
+ ## \u8BBE\u8BA1\u6A21\u5F0F
2055
+ ${t.patterns.map(s=>`- ${s.name}: ${s.description}`).join(`
2056
+ `)}
2057
+
2058
+ \u8BF7\u63D0\u4F9B\u4EE5\u4E0B\u5206\u6790\uFF1A
2059
+ 1. \u67B6\u6784\u7C7B\u578B\uFF08\u5982\u5206\u5C42\u67B6\u6784\u3001\u5FAE\u670D\u52A1\u3001MVC\u7B49\uFF09
2060
+ 2. \u67B6\u6784\u6458\u8981\uFF082-3\u53E5\u8BDD\u603B\u7ED3\uFF09
2061
+ 3. \u6539\u8FDB\u5EFA\u8BAE\uFF082-3\u6761\uFF09
2062
+
2063
+ \u4EE5JSON\u683C\u5F0F\u8FD4\u56DE\uFF1A
2064
+ {
2065
+ "type": "\u67B6\u6784\u7C7B\u578B",
2066
+ "summary": "\u67B6\u6784\u6458\u8981",
2067
+ "recommendations": ["\u5EFA\u8BAE1", "\u5EFA\u8BAE2"]
2068
+ }`;try{let i=(await B({model:ce(),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(s){console.error("\u751F\u6210\u67B6\u6784\u89C6\u56FE\u5931\u8D25:",s)}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,s){let i=process.cwd(),a=po.join(i,".nium","docs");Dn.existsSync(a)||Dn.mkdirSync(a,{recursive:!0});let c=t.replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase()+"_ARCHITECTURE.md",l=po.join(a,c),u=`# ${e} - \u67B6\u6784\u5206\u6790\u62A5\u544A
2069
+
2070
+ > \u751F\u6210\u65F6\u95F4: ${new Date().toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"})}
2071
+ > \u751F\u6210\u5DE5\u5177: Explore Tool (\u67B6\u6784\u7EA7\u63A2\u7D22)
2072
+
2073
+ ---
2074
+
2075
+ ## \u67B6\u6784\u6982\u89C8
2076
+
2077
+ **\u67B6\u6784\u7C7B\u578B**: ${s.type}
2078
+
2079
+ **\u6458\u8981**: ${s.summary}
2080
+
2081
+ ---
2082
+
2083
+ ## \u6838\u5FC3\u6A21\u5757\u5206\u6790
2084
+
2085
+ ### \u6A21\u5757\u7EDF\u8BA1
2086
+ - \u603B\u6A21\u5757\u6570: ${n.modules.length}
2087
+ - \u4F9D\u8D56\u5173\u7CFB\u6570: ${n.dependencies.length}
2088
+ - \u8BBE\u8BA1\u6A21\u5F0F\u6570: ${r.patterns.length}
2089
+
2090
+ ### \u6A21\u5757\u8BE6\u60C5
2091
+
2092
+ ${n.modules.map(p=>`
2093
+ #### ${p.name}
2094
+ - **\u7C7B\u578B**: ${p.type}
2095
+ - **\u8DEF\u5F84**: \`${p.path}\`
2096
+ `).join("")}
2097
+
2098
+ ---
2099
+
2100
+ ## \u4F9D\u8D56\u5173\u7CFB\u56FE
2101
+
2102
+ \`\`\`mermaid
2103
+ graph TD
2104
+ ${n.dependencies.slice(0,20).map(p=>` ${p.from} --> ${p.to}`).join(`
2105
+ `)}
2106
+ \`\`\`
2107
+
2108
+ > \u6CE8\uFF1A\u4EC5\u663E\u793A\u524D20\u4E2A\u4F9D\u8D56\u5173\u7CFB\u4EE5\u4FDD\u6301\u56FE\u8868\u6E05\u6670
2109
+
2110
+ ---
2111
+
2112
+ ## \u8BBE\u8BA1\u6A21\u5F0F\u8BC6\u522B
2113
+
2114
+ ${r.patterns.map(p=>`
2115
+ ### ${p.name}
2116
+ - **\u63CF\u8FF0**: ${p.description}
2117
+ - **\u4F4D\u7F6E**: \`${p.location}\`
2118
+ `).join("")}
2119
+
2120
+ ---
2121
+
2122
+ ## \u67B6\u6784\u6539\u8FDB\u5EFA\u8BAE
2123
+
2124
+ ${s.recommendations.map((p,g)=>`${g+1}. ${p}`).join(`
2125
+ `)}
2126
+
2127
+ ---
2128
+
2129
+ ## \u4F7F\u7528\u8BF4\u660E
2130
+
2131
+ \u672C\u62A5\u544A\u7531 Explore Tool \u81EA\u52A8\u751F\u6210\uFF0C\u4E13\u6CE8\u4E8E\u9879\u76EE\u6574\u4F53\u67B6\u6784\u5206\u6790\u3002
2132
+
2133
+ ### \u76F8\u5173\u5DE5\u5177
2134
+ - **quickProjectScan**: \u5FEB\u901F\u9879\u76EE\u6982\u89C8\uFF08<5\u79D2\uFF09
2135
+ - **ModuleExplorer**: \u6A21\u5757\u7EA7\u6DF1\u5EA6\u5206\u6790
2136
+ - **ToolingExplorer**: \u5DE5\u5177\u94FE\u914D\u7F6E\u5206\u6790
2137
+
2138
+ ---
2139
+
2140
+ *\u62A5\u544A\u751F\u6210\u65F6\u95F4: ${new Date().toISOString()}*
2141
+ `;return Dn.writeFileSync(l,u,"utf-8"),l}formatAction(e){return`explore({ topic: "${e.topic}" })`}formatObservation(e){return String(e)}},Hu=new jn;mo=Hu});import*as On from"fs";import*as fo from"path";import{globSync as Bu}from"glob";import{readFileSync as ba}from"fs";async function ho(o){return Gu.execute(o)}var Fn,Gu,yo,Ju=C(()=>{U();Je();Ce();ee();Fn=class extends ${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
2142
+
2143
+ \u{1F4CB} \u7528\u9014\uFF1A
2144
+ - \u5206\u6790\u6A21\u5757\u5185\u90E8\u51FD\u6570\u5B9E\u73B0\u548C\u7B97\u6CD5\u903B\u8F91
2145
+ - \u8FFD\u8E2A\u51FD\u6570\u8C03\u7528\u94FE\u548C\u6570\u636E\u6D41\u5411
2146
+ - \u7406\u89E3\u5177\u4F53\u4E1A\u52A1\u903B\u8F91\u7684\u5B9E\u73B0\u7EC6\u8282
2147
+ - \u8BC6\u522B\u6A21\u5757\u5185\u7684\u8BBE\u8BA1\u6A21\u5F0F\u548C\u6700\u4F73\u5B9E\u8DF5
2148
+
2149
+ \u{1F511} \u53C2\u6570\uFF1A
2150
+ - 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
2151
+ - englishModule: \u82F1\u6587\u6A21\u5757\u540D\u79F0\uFF08\u5FC5\u586B\uFF0C\u751F\u6210\u6587\u6863\u6587\u4EF6\u540D\uFF09
2152
+ - searchPattern: \u53EF\u9009\u641C\u7D22\u8DEF\u5F84\uFF08\u5982"src/auth/**"\uFF09
2153
+
2154
+ \u{1F4A1} \u793A\u4F8B\uFF1A
2155
+ - moduleExplore({ module: "\u8BA4\u8BC1\u6A21\u5757", englishModule: "Authentication Module" })
2156
+ - moduleExplore({ module: "\u5DE5\u5177\u7CFB\u7EDF", englishModule: "Tool System", searchPattern: "src/tools/**" })
2157
+ - moduleExplore({ module: "API\u8DEF\u7531", englishModule: "API Routes", searchPattern: "src/api/**" })
2158
+
2159
+ \u26A0\uFE0F \u6CE8\u610F\uFF1A
2160
+ - \u672C\u5DE5\u5177\u4E13\u6CE8\u4E8E\u6A21\u5757\u7EA7\u5B9E\u73B0\u7EC6\u8282\uFF0860-120\u79D2\uFF09
2161
+ - \u9879\u76EE\u6574\u4F53\u67B6\u6784\u8BF7\u4F7F\u7528 Explore
2162
+ - \u5DE5\u5177\u94FE\u914D\u7F6E\u8BF7\u4F7F\u7528 ToolingExplorer
2163
+
2164
+ \u{1F4DD} \u8F93\u51FA\uFF1A
2165
+ - \u4FDD\u5B58\u6A21\u5757\u5206\u6790\u62A5\u544A\u5230 .nium/docs/<MODULE>_IMPLEMENTATION.md
2166
+ - \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}
2167
+ `),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(`
2168
+ `);n.push("\u{1F3D7}\uFE0F \u5206\u6790\u6A21\u5757\u7ED3\u6784...");let s=await this.analyzeModuleStructure(r);n.push(` \u2713 \u8BC6\u522B ${s.functions.length} \u4E2A\u51FD\u6570/\u65B9\u6CD5`),n.push(` \u2713 \u8BC6\u522B ${s.classes.length} \u4E2A\u7C7B`),n.push(""),n.push("\u{1F517} \u8FFD\u8E2A\u51FD\u6570\u8C03\u7528\u94FE...");let i=await this.traceCallChains(r,s);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,s);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,s,i,a);return n.push(` \u2713 \u62A5\u544A\u5DF2\u4FDD\u5B58: ${fo.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(`
2169
+ \u{1F4C1} \u76F8\u5173\u6587\u4EF6: ${r.length} \u4E2A`),n.push(`\u{1F527} \u51FD\u6570/\u65B9\u6CD5: ${s.functions.length} \u4E2A`),n.push(`\u{1F3D7}\uFE0F \u7C7B\u5B9A\u4E49: ${s.classes.length} \u4E2A`),n.push(`\u{1F517} \u8C03\u7528\u94FE: ${i.chains.length} \u4E2A`),n.push(`
2170
+ \u{1F4A1} \u6838\u5FC3\u529F\u80FD:`),n.push(a.coreFeatures),n.push(`
2171
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
2172
+ `),n.join(`
2173
+ `)}catch(t){return this.formatError("ModuleExplore",t)}}async locateModuleFiles(e,t,n){let r=process.cwd(),s=ge(r,!0);if(n)try{let l=Bu(n,{nodir:!0,ignore:s,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 Bu("**/*",{nodir:!0,ignore:s,cwd:r}).slice(0,200).map(l=>{let u=l.toLowerCase(),p=0;return i.forEach(d=>{u.includes(d)&&(p+=10)}),l.split("/").forEach(d=>{i.forEach(m=>{d.toLowerCase().includes(m)&&(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(s=>{if(s.endsWith(".js")||s.endsWith(".ts")||s.endsWith(".jsx")||s.endsWith(".tsx"))try{let i=ba(s,"utf-8"),a=i.split(`
2174
+ `),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,d)=>{c.forEach(m=>{let f=m.exec(g);f&&t.push({name:f[1],file:s,line:d+1,params:f[2]?f[2].split(",").map(x=>x.trim()).filter(x=>x):[]})})});let l=/(?:export\s+)?(?:abstract\s+)?class\s+(\w+)/g,u;for(;(u=l.exec(i))!==null;){let g=u[1],d=new RegExp("(?:async\\s+)?(\\w+)\\s*\\([^)]*\\)\\s*[:{]","g"),m=[],f;for(;(f=d.exec(i))!==null;)m.push(f[1]);n.push({name:g,file:s,methods:m.filter(x=>x!==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 d;for(;(d=g.exec(i))!==null;){let m=d[1];m.includes(",")?m.split(",").map(x=>x.trim()).forEach(x=>{x&&r.push({name:x,type:"variable",file:s})}):r.push({name:m,type:"function/class",file:s})}})}catch(i){console.error(`\u5206\u6790\u6587\u4EF6 ${s} \u5931\u8D25:`,i)}}),{functions:t,classes:n,exports:r}}async traceCallChains(e,t){let n=[],r=[],s=/(?:\w+\.)?(\w+)\s*\(/g;return e.forEach(i=>{if(i.endsWith(".js")||i.endsWith(".ts"))try{let a=ba(i,"utf-8");a.split(`
2175
+ `).forEach((p,g)=>{let d;for(;(d=s.exec(p))!==null;){let m=d[1],f=t.functions.find(x=>x.name===m);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=[],s=Math.min(5,t.length);for(let a=0;a<s;a++)try{let c=ba(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
2176
+
2177
+ ## \u6A21\u5757\u7ED3\u6784\u4FE1\u606F
2178
+ - \u6587\u4EF6\u6570: ${t.length}
2179
+ - \u51FD\u6570\u6570: ${n.functions.length}
2180
+ - \u7C7B\u6570: ${n.classes.length}
2181
+ - \u5BFC\u51FA\u6570: ${n.exports.length}
2182
+
2183
+ ## \u5173\u952E\u6587\u4EF6\u5185\u5BB9
2184
+ ${r.map(a=>`### ${a.path}
2185
+ \`\`\`
2186
+ ${a.content}
2187
+ \`\`\`
2188
+ `).join(`
2189
+ `)}
2190
+
2191
+ \u8BF7\u63D0\u4F9B\u4EE5\u4E0B\u5206\u6790\uFF1A
2192
+ 1. **\u6838\u5FC3\u529F\u80FD**: \u7B80\u8981\u63CF\u8FF0\u6A21\u5757\u7684\u4E3B\u8981\u529F\u80FD\u548C\u804C\u8D23\uFF082-3\u53E5\u8BDD\uFF09
2193
+ 2. **\u7B97\u6CD5\u8BC6\u522B**: \u5217\u51FA\u4E3B\u8981\u7B97\u6CD5\u53CA\u5176\u590D\u6742\u5EA6
2194
+ 3. **\u5B9E\u73B0\u6A21\u5F0F**: \u8BC6\u522B\u7684\u5B9E\u73B0\u6A21\u5F0F\u548C\u6700\u4F73\u5B9E\u8DF5
2195
+
2196
+ \u4EE5JSON\u683C\u5F0F\u8FD4\u56DE\uFF1A
2197
+ {
2198
+ "coreFeatures": "\u6838\u5FC3\u529F\u80FD\u63CF\u8FF0",
2199
+ "algorithms": [
2200
+ {"name": "\u7B97\u6CD5\u540D", "description": "\u63CF\u8FF0", "complexity": "O(n)"}
2201
+ ],
2202
+ "patterns": [
2203
+ {"name": "\u6A21\u5F0F\u540D", "description": "\u63CF\u8FF0"}
2204
+ ]
2205
+ }`;try{let c=(await B({model:ce(),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,s,i){let a=process.cwd(),c=fo.join(a,".nium","docs");On.existsSync(c)||On.mkdirSync(c,{recursive:!0});let l=t.replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase()+"_IMPLEMENTATION.md",u=fo.join(c,l),p=`# ${e} - \u5B9E\u73B0\u7EC6\u8282\u5206\u6790
2206
+
2207
+ > \u751F\u6210\u65F6\u95F4: ${new Date().toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"})}
2208
+ > \u751F\u6210\u5DE5\u5177: Module Explorer (\u6A21\u5757\u7EA7\u6DF1\u5EA6\u5206\u6790)
2209
+
2210
+ ---
2211
+
2212
+ ## \u6838\u5FC3\u529F\u80FD
2213
+
2214
+ ${i.coreFeatures}
2215
+
2216
+ ---
2217
+
2218
+ ## \u6587\u4EF6\u7ED3\u6784
2219
+
2220
+ ### \u76F8\u5173\u6587\u4EF6 (${n.length} \u4E2A)
2221
+
2222
+ ${n.map(g=>`- \`${g}\``).join(`
2223
+ `)}
2224
+
2225
+ ---
2226
+
2227
+ ## \u51FD\u6570/\u65B9\u6CD5\u6E05\u5355
2228
+
2229
+ ### \u51FD\u6570\u5217\u8868 (${r.functions.length} \u4E2A)
2230
+
2231
+ ${r.functions.map(g=>`#### ${g.name}
2232
+ - **\u4F4D\u7F6E**: \`${g.file}:${g.line}\`
2233
+ - **\u53C2\u6570**: ${g.params.length>0?g.params.map(d=>`\`${d}\``).join(", "):"\u65E0\u53C2\u6570"}
2234
+ ${g.returnType?`- **\u8FD4\u56DE\u7C7B\u578B**: \`${g.returnType}\``:""}`).join(`
2235
+
2236
+ `)}
2237
+
2238
+ ### \u7C7B\u5B9A\u4E49 (${r.classes.length} \u4E2A)
2239
+
2240
+ ${r.classes.map(g=>`#### ${g.name}
2241
+ - **\u4F4D\u7F6E**: \`${g.file}\`
2242
+ - **\u65B9\u6CD5**: ${g.methods.length>0?g.methods.map(d=>`\`${d}()\``).join(", "):"\u65E0"}`).join(`
2243
+
2244
+ `)}
2245
+
2246
+ ### \u5BFC\u51FA\u9879 (${r.exports.length} \u4E2A)
2247
+
2248
+ ${r.exports.map(g=>`- **\`${g.name}\`** (${g.type}) - \`${g.file}\``).join(`
2249
+ `)}
2250
+
2251
+ ---
2252
+
2253
+ ## \u8C03\u7528\u94FE\u5206\u6790
2254
+
2255
+ ### \u5185\u90E8\u8C03\u7528 (${s.chains.length} \u4E2A)
2256
+
2257
+ ${s.chains.slice(0,20).map(g=>`- \`${g.file}:${g.line}\` \u2192 \`${g.to}\``).join(`
2258
+ `)}
2259
+
2260
+ ### \u5916\u90E8\u4F9D\u8D56 (${s.dependencies.length} \u4E2A)
2261
+
2262
+ ${s.dependencies.map(g=>`- \`${g}\``).join(`
2263
+ `)}
2264
+
2265
+ ---
2266
+
2267
+ ## \u7B97\u6CD5\u5206\u6790
2268
+
2269
+ ${i.algorithms.length>0?i.algorithms.map(g=>`
2270
+ ### ${g.name}
2271
+ - **\u63CF\u8FF0**: ${g.description}
2272
+ - **\u590D\u6742\u5EA6**: \`${g.complexity}\`
2273
+ `).join(""):"\u6682\u672A\u8BC6\u522B\u5230\u7279\u5B9A\u7B97\u6CD5"}
2274
+
2275
+ ---
2276
+
2277
+ ## \u5B9E\u73B0\u6A21\u5F0F
2278
+
2279
+ ${i.patterns.length>0?i.patterns.map(g=>`
2280
+ ### ${g.name}
2281
+ ${g.description}
2282
+ `).join(""):"\u6682\u672A\u8BC6\u522B\u5230\u7279\u5B9A\u5B9E\u73B0\u6A21\u5F0F"}
2283
+
2284
+ ---
2285
+
2286
+ ## \u4F7F\u7528\u8BF4\u660E
2287
+
2288
+ \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
2289
+
2290
+ ### \u76F8\u5173\u5DE5\u5177
2291
+ - **quickProjectScan**: \u5FEB\u901F\u9879\u76EE\u6982\u89C8\uFF08<5\u79D2\uFF09
2292
+ - **Explore**: \u67B6\u6784\u7EA7\u5206\u6790\uFF0830-60\u79D2\uFF09
2293
+ - **ToolingExplorer**: \u5DE5\u5177\u94FE\u914D\u7F6E\u5206\u6790
2294
+
2295
+ ---
2296
+
2297
+ *\u62A5\u544A\u751F\u6210\u65F6\u95F4: ${new Date().toISOString()}*
2298
+ `;return On.writeFileSync(u,p,"utf-8"),u}formatAction(e){return`moduleExplore({ module: "${e.module}" })`}formatObservation(e){return String(e)}},Gu=new Fn;yo=Gu});import*as Ye from"fs";import*as xo from"path";import{globSync as va}from"glob";import{readFileSync as qu}from"fs";async function Co(o){return Ku.execute(o||{})}var _n,Ku,So,Xu=C(()=>{U();Je();Ce();ee();_n=class extends ${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
2299
+
2300
+ \u{1F4CB} \u7528\u9014\uFF1A
2301
+ - \u5206\u6790\u6784\u5EFA\u914D\u7F6E\u548C\u4F9D\u8D56\u7BA1\u7406
2302
+ - \u7406\u89E3\u6D4B\u8BD5\u6846\u67B6\u548C\u6D4B\u8BD5\u7B56\u7565
2303
+ - \u89E3\u6790CI/CD\u914D\u7F6E\u548C\u90E8\u7F72\u6D41\u7A0B
2304
+ - \u8BC6\u522B\u4EE3\u7801\u8D28\u91CF\u5DE5\u5177\u548C\u89C4\u8303\u914D\u7F6E
2305
+
2306
+ \u{1F511} \u53C2\u6570\uFF1A
2307
+ - 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
2308
+ - englishFocus: \u82F1\u6587\u805A\u7126\u4E3B\u9898\uFF0C\u7528\u4E8E\u751F\u6210\u6587\u6863\u6587\u4EF6\u540D
2309
+
2310
+ \u{1F4A1} \u793A\u4F8B\uFF1A
2311
+ - toolingExplore({}) - \u5206\u6790\u5B8C\u6574\u5DE5\u5177\u94FE
2312
+ - toolingExplore({ focus: "\u6784\u5EFA\u914D\u7F6E", englishFocus: "Build Configuration" })
2313
+ - toolingExplore({ focus: "\u6D4B\u8BD5\u6846\u67B6", englishFocus: "Test Framework" })
2314
+ - toolingExplore({ focus: "\u90E8\u7F72\u914D\u7F6E", englishFocus: "Deployment Configuration" })
2315
+
2316
+ \u26A0\uFE0F \u6CE8\u610F\uFF1A
2317
+ - \u672C\u5DE5\u5177\u4E13\u6CE8\u4E8E\u5DE5\u5177\u94FE\u914D\u7F6E\u5206\u6790\uFF0830-60\u79D2\uFF09
2318
+ - \u4E1A\u52A1\u903B\u8F91\u8BF7\u4F7F\u7528 ModuleExplorer
2319
+ - \u9879\u76EE\u67B6\u6784\u8BF7\u4F7F\u7528 Explore
2320
+
2321
+ \u{1F4DD} \u8F93\u51FA\uFF1A
2322
+ - \u4FDD\u5B58\u5DE5\u5177\u94FE\u62A5\u544A\u5230 .nium/docs/<TOOLING>_ANALYSIS.md
2323
+ - \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}
2324
+ `),n.push("\u{1F4C4} \u626B\u63CF\u914D\u7F6E\u6587\u4EF6...");let s=await this.scanConfigFiles();n.push(` \u2713 \u627E\u5230 ${s.length} \u4E2A\u914D\u7F6E\u6587\u4EF6`),n.push(""),n.push("\u{1F528} \u5206\u6790\u6784\u5EFA\u5DE5\u5177...");let i=await this.analyzeBuildTools(s);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(s);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(s);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(s);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",s,i,a,c,l,u);return n.push(` \u2713 \u62A5\u544A\u5DF2\u4FDD\u5B58: ${xo.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(`
2325
+ \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(`
2326
+ \u{1F4A1} \u4E3B\u8981\u53D1\u73B0:`),n.push(u.summary),n.push(`
2327
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
2328
+ `),n.join(`
2329
+ `)}catch(t){return this.formatError("ToolingExplore",t)}}async scanConfigFiles(){let e=process.cwd(),t=ge(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(s=>{try{let i=va(s,{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(qu(n,"utf-8")),a={name:"npm/yarn/pnpm",configFiles:[n],scripts:i.scripts||{}};Ye.existsSync("yarn.lock")?a.name="yarn":Ye.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 s=e.filter(i=>i.includes("vite.config"));return s.length>0&&t.push({name:"vite",configFiles:s,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=va("**/*test*.{js,ts,jsx,tsx}",{nodir:!0}).slice(0,10),s=e.find(i=>i==="package.json");if(s)try{let i=JSON.parse(qu(s,"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:va("**/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 s=e.filter(i=>i.includes("tsconfig"));return s.length>0&&t.push({name:"TypeScript",configFiles:s}),e.includes(".editorconfig")&&t.push({name:"EditorConfig",configFiles:[".editorconfig"]}),(Ye.existsSync(".husky")||e.some(i=>i.includes("husky")))&&t.push({name:"Husky",configFiles:[".husky"]}),t}async analyzeCICDConfigs(e){let t=[],n=e.filter(s=>s.includes(".github/workflows"));n.length>0&&t.push({name:"GitHub Actions",configFiles:n});let r=e.filter(s=>s.includes("Dockerfile")||s.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,s){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
2330
+
2331
+ ## \u6784\u5EFA\u5DE5\u5177
2332
+ ${e.map(a=>`- ${a.name}: ${a.configFiles.join(", ")}`).join(`
2333
+ `)}
2334
+
2335
+ ## \u6D4B\u8BD5\u6846\u67B6
2336
+ ${t.map(a=>`- ${a.name}: ${a.testFiles.length} \u4E2A\u6D4B\u8BD5\u6587\u4EF6`).join(`
2337
+ `)}
2338
+
2339
+ ## \u4EE3\u7801\u8D28\u91CF\u5DE5\u5177
2340
+ ${n.map(a=>`- ${a.name}: ${a.configFiles.join(", ")}`).join(`
2341
+ `)}
2342
+
2343
+ ## CI/CD\u914D\u7F6E
2344
+ ${r.map(a=>`- ${a.name}: ${a.configFiles.join(", ")}`).join(`
2345
+ `)}
2346
+
2347
+ \u805A\u7126\u4E3B\u9898: ${s}
2348
+
2349
+ \u8BF7\u63D0\u4F9B\uFF1A
2350
+ 1. \u5DE5\u5177\u94FE\u6458\u8981\uFF082-3\u53E5\u8BDD\uFF09
2351
+ 2. 3-5\u4E2A\u6539\u8FDB\u5EFA\u8BAE
2352
+ 3. \u5E38\u7528\u5F00\u53D1\u547D\u4EE4
2353
+
2354
+ \u4EE5JSON\u683C\u5F0F\u8FD4\u56DE\uFF1A
2355
+ {
2356
+ "summary": "\u5DE5\u5177\u94FE\u6458\u8981",
2357
+ "recommendations": ["\u5EFA\u8BAE1", "\u5EFA\u8BAE2"],
2358
+ "commands": ["\u547D\u4EE41", "\u547D\u4EE42"]
2359
+ }`;try{let c=(await B({model:ce(),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,s,i,a,c){let l=process.cwd(),u=xo.join(l,".nium","docs");Ye.existsSync(u)||Ye.mkdirSync(u,{recursive:!0});let p=t.replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase()+"_ANALYSIS.md",g=xo.join(u,p),d=`# ${e} - \u5DE5\u5177\u94FE\u5206\u6790\u62A5\u544A
2360
+
2361
+ > \u751F\u6210\u65F6\u95F4: ${new Date().toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"})}
2362
+ > \u751F\u6210\u5DE5\u5177: Tooling Explorer (\u5DE5\u5177\u94FE\u5206\u6790)
2363
+
2364
+ ---
2365
+
2366
+ ## \u5DE5\u5177\u94FE\u6458\u8981
2367
+
2368
+ ${c.summary}
2369
+
2370
+ ---
2371
+
2372
+ ## \u914D\u7F6E\u6587\u4EF6\u6982\u89C8
2373
+
2374
+ \u5171\u53D1\u73B0 ${n.length} \u4E2A\u914D\u7F6E\u6587\u4EF6\uFF1A
2375
+
2376
+ ${n.map(m=>`- \`${m}\``).join(`
2377
+ `)}
2378
+
2379
+ ---
2380
+
2381
+ ## \u6784\u5EFA\u5DE5\u5177\u5206\u6790
2382
+
2383
+ ${r.map(m=>`
2384
+ ### ${m.name}
2385
+ - **\u914D\u7F6E\u6587\u4EF6**: ${m.configFiles.length>0?m.configFiles.map(f=>`\`${f}\``).join(", "):"\u65E0"}
2386
+ ${m.version?`- **\u7248\u672C**: \`${m.version}\``:""}
2387
+ ${Object.keys(m.scripts).length>0?`
2388
+ **\u6784\u5EFA\u811A\u672C**:
2389
+ ${Object.entries(m.scripts).map(([f,x])=>`- \`${f}\`: \`${x}\``).join(`
2390
+ `)}
2391
+ `:""}
2392
+ `).join("")}
2393
+
2394
+ ---
2395
+
2396
+ ## \u6D4B\u8BD5\u6846\u67B6\u5206\u6790
2397
+
2398
+ ${s.length>0?s.map(m=>`
2399
+ ### ${m.name}
2400
+ - **\u7248\u672C**: ${m.version||"\u672A\u77E5"}
2401
+ - **\u914D\u7F6E\u6587\u4EF6**: ${m.configFiles.map(f=>`\`${f}\``).join(", ")||"\u65E0"}
2402
+ - **\u6D4B\u8BD5\u6587\u4EF6\u6570**: ${m.testFiles.length}
2403
+ ${m.coverage?"- **\u652F\u6301\u4EE3\u7801\u8986\u76D6\u7387**: \u2713":""}
2404
+ `).join(""):`### \u6D4B\u8BD5\u6846\u67B6
2405
+ \u672A\u68C0\u6D4B\u5230\u6D4B\u8BD5\u6846\u67B6\u914D\u7F6E`}
2406
+
2407
+ ---
2408
+
2409
+ ## \u4EE3\u7801\u8D28\u91CF\u5DE5\u5177
2410
+
2411
+ ${i.map(m=>`
2412
+ ### ${m.name}
2413
+ - **\u914D\u7F6E\u6587\u4EF6**: ${m.configFiles.map(f=>`\`${f}\``).join(", ")||"\u65E0"}
2414
+ `).join("")}
2415
+
2416
+ ---
2417
+
2418
+ ## CI/CD\u914D\u7F6E
2419
+
2420
+ ${a.length>0?a.map(m=>`
2421
+ ### ${m.name}
2422
+ - **\u914D\u7F6E\u6587\u4EF6**: ${m.configFiles.map(f=>`\`${f}\``).join(", ")||"\u65E0"}
2423
+ `).join(""):`### CI/CD\u914D\u7F6E
2424
+ \u672A\u68C0\u6D4B\u5230CI/CD\u914D\u7F6E`}
2425
+
2426
+ ---
2427
+
2428
+ ## \u4F7F\u7528\u5EFA\u8BAE
2429
+
2430
+ ### \u6539\u8FDB\u5EFA\u8BAE
2431
+
2432
+ ${c.recommendations.map((m,f)=>`${f+1}. ${m}`).join(`
2433
+ `)}
2434
+
2435
+ ### \u5E38\u7528\u547D\u4EE4
2436
+
2437
+ ${c.commands.map((m,f)=>`${f+1}. \`${m}\``).join(`
2438
+ `)}
2439
+
2440
+ ---
2441
+
2442
+ ## \u5F00\u53D1\u5DE5\u4F5C\u6D41
2443
+
2444
+ \u57FA\u4E8E\u5F53\u524D\u5DE5\u5177\u94FE\u914D\u7F6E\uFF0C\u63A8\u8350\u7684\u5F00\u53D1\u6D41\u7A0B\uFF1A
2445
+
2446
+ 1. **\u73AF\u5883\u51C6\u5907**
2447
+ - \u5B89\u88C5\u4F9D\u8D56\uFF1A \`npm install\` \u6216\u5BF9\u5E94\u5305\u7BA1\u7406\u5668\u547D\u4EE4
2448
+ - \u914D\u7F6E\u5F00\u53D1\u73AF\u5883\uFF1A\u68C0\u67E5\u7F16\u8F91\u5668\u914D\u7F6E
2449
+
2450
+ 2. **\u5F00\u53D1\u9636\u6BB5**
2451
+ - \u4EE3\u7801\u68C0\u67E5\uFF1A\u8FD0\u884C\u4EE3\u7801\u8D28\u91CF\u5DE5\u5177
2452
+ - \u5B9E\u65F6\u6D4B\u8BD5\uFF1A\u542F\u7528\u76D1\u542C\u6A21\u5F0F\u6D4B\u8BD5
2453
+
2454
+ 3. **\u6784\u5EFA\u90E8\u7F72**
2455
+ - \u6784\u5EFA\u9879\u76EE\uFF1A\u6267\u884C\u6784\u5EFA\u811A\u672C
2456
+ - \u8FD0\u884C\u6D4B\u8BD5\uFF1A\u786E\u4FDD\u6D4B\u8BD5\u901A\u8FC7
2457
+ - \u90E8\u7F72\uFF1A\u6309\u7167CI/CD\u914D\u7F6E\u90E8\u7F72
2458
+
2459
+ ---
2460
+
2461
+ ## \u4F7F\u7528\u8BF4\u660E
2462
+
2463
+ \u672C\u62A5\u544A\u7531 Tooling Explorer \u81EA\u52A8\u751F\u6210\uFF0C\u4E13\u6CE8\u4E8E\u5F00\u53D1\u5DE5\u5177\u94FE\u5206\u6790\u3002
2464
+
2465
+ ### \u76F8\u5173\u5DE5\u5177
2466
+ - **quickProjectScan**: \u5FEB\u901F\u9879\u76EE\u6982\u89C8\uFF08<5\u79D2\uFF09
2467
+ - **Explore**: \u67B6\u6784\u7EA7\u5206\u6790\uFF0830-60\u79D2\uFF09
2468
+ - **ModuleExplorer**: \u6A21\u5757\u7EA7\u6DF1\u5EA6\u5206\u6790
2469
+
2470
+ ---
2471
+
2472
+ *\u62A5\u544A\u751F\u6210\u65F6\u95F4: ${new Date().toISOString()}*
2473
+ `;return Ye.writeFileSync(g,d,"utf-8"),g}formatAction(e){return e.focus?`toolingExplore({ focus: "${e.focus}" })`:"toolingExplore()"}formatObservation(e){return String(e)}},Ku=new _n;So=Ku});var Nn,Un,Ta=C(()=>{Nn=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"]},s={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(s).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),s=this.extractSearchPattern(t);return{tool:"moduleExplore",params:{module:n||"\u6838\u5FC3\u6A21\u5757",englishModule:r||"Core Module",...s&&{searchPattern:s}},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 s=e.match(r);if(s&&s[1]&&s[1].trim())return s[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(s=>s.charAt(0).toUpperCase()+s.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(([s,i])=>{i=i.replace(new RegExp(s,"g"),i)}),r=r.replace(/[^\w\s]/g," ").replace(/\s+/g," ").trim(),r?r.split(" ").map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):t.map(s=>s.charAt(0).toUpperCase()+s.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((s,i)=>s.tool===r.tool?-1:i.tool===r.tool?1:0)}},Un=new Nn});async function wo(o){return Yu.execute(o)}var Wn,Yu,bo,Qu=C(()=>{Ta();U();Wn=class extends ${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
2474
+
2475
+ \u{1F4CB} \u7528\u9014\uFF1A
2476
+ - \u4E0D\u786E\u5B9A\u8BE5\u4F7F\u7528\u54EA\u4E2A\u63A2\u7D22\u5DE5\u5177\u65F6
2477
+ - \u60F3\u4E86\u89E3\u5404\u5DE5\u5177\u7684\u533A\u522B\u548C\u4F7F\u7528\u573A\u666F
2478
+ - \u9700\u8981\u5DE5\u5177\u9009\u62E9\u5EFA\u8BAE
2479
+
2480
+ \u{1F511} \u53C2\u6570\uFF1A
2481
+ - query: \u60A8\u7684\u9700\u6C42\u63CF\u8FF0\u6216\u67E5\u8BE2\u5185\u5BB9
2482
+
2483
+ \u{1F4A1} \u793A\u4F8B\uFF1A
2484
+ - smartSuggest({ query: "\u6211\u60F3\u5FEB\u901F\u4E86\u89E3\u8FD9\u4E2A\u9879\u76EE" })
2485
+ - smartSuggest({ query: "\u5206\u6790\u8BA4\u8BC1\u6A21\u5757\u7684\u5177\u4F53\u5B9E\u73B0" })
2486
+ - smartSuggest({ query: "\u67E5\u770B\u9879\u76EE\u7684\u6784\u5EFA\u914D\u7F6E" })
2487
+
2488
+ \u{1F4DD} \u8F93\u51FA\uFF1A
2489
+ - \u63A8\u8350\u6700\u9002\u5408\u7684\u5DE5\u5177
2490
+ - \u8BF4\u660E\u63A8\u8350\u539F\u56E0
2491
+ - \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
2492
+ `);let n=Un.route(e.query),r=Un.getRoutingSuggestions(e.query);t.push(`\u{1F4DD} \u60A8\u7684\u67E5\u8BE2: "${e.query}"
2493
+ `),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}
2494
+ `),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
2495
+ `),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
2496
+ `);let s=this.getUsageExample(n.tool,n.params);return t.push(`**${this.getToolDisplayName(n.tool)}**:`),t.push("```javascript"),t.push(s),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
2497
+ `),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(`
2498
+ `)}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({
2499
+ topic: "${t.topic||"\u9879\u76EE\u67B6\u6784"}",
2500
+ englishTopic: "${t.englishTopic||"Project Architecture"}"
2501
+ })`;case"moduleExplore":let n=`moduleExplore({
2502
+ module: "${t.module||"\u6838\u5FC3\u6A21\u5757"}",
2503
+ englishModule: "${t.englishModule||"Core Module"}"`;return t.searchPattern?n+`,
2504
+ searchPattern: "${t.searchPattern}"
2505
+ })`:n+`
2506
+ })`;case"toolingExplore":return t.focus?`toolingExplore({
2507
+ focus: "${t.focus}",
2508
+ englishFocus: "${t.englishFocus||""}"
2509
+ })`:"toolingExplore()";default:return`${e}(...)`}}formatAction(e){return`smartSuggest({ query: "${e.query}" })`}formatObservation(e){return String(e)}},Yu=new Wn;bo=Yu});var Pa={};_(Pa,{AskUserTool:()=>Rn,ExploreTool:()=>jn,ModuleExploreTool:()=>Fn,PlanTool:()=>Xe,QuickProjectScanTool:()=>Ft,SmartRouter:()=>Nn,SmartSuggestTool:()=>Wn,THINK_TOOL:()=>is,ThinkTool:()=>$t,TodoTool:()=>Ln,ToolingExploreTool:()=>_n,askUser:()=>ao,askUserTool:()=>co,explore:()=>go,exploreTool:()=>mo,extractThought:()=>as,isThinkTool:()=>bn,moduleExplore:()=>ho,moduleExploreTool:()=>yo,plan:()=>oo,planTool:()=>so,quickProjectScan:()=>In,quickProjectScanTool:()=>Mn,smartRouter:()=>Un,smartSuggest:()=>wo,smartSuggestTool:()=>bo,think:()=>Sn,thinkTool:()=>wn,todo:()=>lo,todoTool:()=>uo,toolingExplore:()=>Co,toolingExploreTool:()=>So});var Us=C(()=>{Vr();wa();Nu();ma();Wu();Vu();Ju();Xu();Ta();Qu()});async function Zu(o){return ka.execute(o)}var Ea,ka,ep,qv,tp=C(()=>{U();eo();Ea=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.
1669
2510
 
1670
2511
  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.
1671
2512
 
@@ -1673,10 +2514,10 @@ Typical use cases:
1673
2514
  - When you need to check what files have been modified recently
1674
2515
  - When you want to understand the scope of changes in the workspace
1675
2516
  - When you need to verify if certain files have been changed
1676
- - 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={};O(ur,{AgentTools:()=>si,AskUserTool:()=>Xt,BaseTool:()=>P,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:()=>Vn,globTool:()=>Wn,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:()=>Vt,thinkTool:()=>Wt,todo:()=>hr,todoTool:()=>yr,toolInstances:()=>W,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 W,ci,Tp,kp,Re=y(()=>{ls();ls();Xr();Xr();Qr();Qr();eo();eo();Po();Po();lt();lt();Xr();Qr();eo();Po();al();lt();ar();W={think:Wt,plan:pr,todo:yr,askUser:fr,quickProjectScan:Kt,read:wn,write:kn,mkdir:rt,glob:Wn,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:Vt,plan:gr,todo:hr,askUser:mr,quickProjectScan:qt,read:vn,write:Tn,mkdir:bn,merge:Ln,glob:Vn,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=y(()=>{});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=y(()=>{K();Cr=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 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})),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 ll=y(()=>{ui()});function Zt(){return gi.getInstance()}var gi,pi=y(()=>{ui();K();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){H("MCP Manager already initialized");return}if($(`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(", ");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){Y(`Failed to connect to MCP server ${t.name}: ${n.message}`),C(`Error details for ${t.name}: ${n.message}
1677
- ${n.stack||""}`)}}this.initialized=!0,$(`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);$(`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)){H(`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){Y(`Error disconnecting from ${e}: ${n.message}`)}this.clients.clear(),this.mcpTools.clear(),this.initialized=!1,$("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=y(()=>{pi();U();Re();K();$o=class extends P{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 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(`
2517
+ - 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=gt(),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)}`)}}},ka=new Ea;ep=ka,qv=ka.getDefinition()});var ro={};_(ro,{AgentTools:()=>Pa,AskUserTool:()=>Rn,BaseTool:()=>$,BuildDocIndexTool:()=>yn,ConfirmableTool:()=>Re,CopyTool:()=>ln,CoreTools:()=>Ci,DeleteTool:()=>an,ExploreTool:()=>jn,FileChangeTools:()=>aa,FileChangeTracker:()=>pt,FileOpsTools:()=>Li,GlobTool:()=>dn,GrepTool:()=>fn,MergeTool:()=>un,MkdirTool:()=>on,ModuleExploreTool:()=>Fn,MoveTool:()=>cn,PlanTool:()=>Xe,QuickProjectScanTool:()=>Ft,ReadTool:()=>nn,SearchDocsTool:()=>hn,SearchReplaceTool:()=>pn,SearchTools:()=>ji,ShellTool:()=>xn,SmartRouter:()=>Nn,SmartSuggestTool:()=>Wn,SystemTools:()=>Fi,THINK_TOOL:()=>is,ThinkTool:()=>$t,TodoTool:()=>Ln,ToolingExploreTool:()=>_n,ValidateTool:()=>mn,WriteTool:()=>sn,aiContextManager:()=>Xd,askUser:()=>ao,askUserTool:()=>co,buildDocIndex:()=>Wr,buildDocIndexTool:()=>zr,copyFile:()=>Tr,copyTool:()=>Pr,createFileChangeTracker:()=>Ss,createToolResult:()=>Ma,deleteFile:()=>Sr,deleteTool:()=>wr,detectFileChanges:()=>bs,explore:()=>go,exploreTool:()=>mo,extractThought:()=>as,extractToolResult:()=>pr,fileChangeTracking:()=>Yd,generateChangeSummary:()=>vs,getCurrentSessionFileChanges:()=>ks,getFileChangeTracker:()=>Se,getSessionFileChanges:()=>Es,getToolInstances:()=>$a,glob:()=>jr,globTool:()=>Dr,grep:()=>Fr,grepTool:()=>Or,handleGitCommit:()=>Ps,isThinkTool:()=>bn,isToolResult:()=>tn,merge:()=>Er,mergeTool:()=>kr,mkdir:()=>yr,mkdirTool:()=>kt,moduleExplore:()=>ho,moduleExploreTool:()=>yo,moveFile:()=>br,moveTool:()=>vr,plan:()=>oo,planTool:()=>so,quickProjectScan:()=>In,quickProjectScanTool:()=>Mn,read:()=>mr,readTool:()=>dr,recordFileChange:()=>Ts,resetFileChangeTracker:()=>ws,searchDocs:()=>_r,searchDocsTool:()=>Nr,searchReplace:()=>$r,searchReplaceTool:()=>Ir,shell:()=>Hr,shellTool:()=>Cn,smartRouter:()=>Un,smartSuggest:()=>wo,smartSuggestTool:()=>bo,think:()=>Sn,thinkTool:()=>wn,todo:()=>lo,todoTool:()=>uo,toolInstances:()=>G,toolingExplore:()=>Co,toolingExploreTool:()=>So,tools:()=>Ia,validate:()=>Rr,validateTool:()=>Lr,write:()=>xr,writeTool:()=>Cr});function $a(){return Ws||(Ws={think:wn,plan:so,todo:uo,askUser:co,quickProjectScan:Mn,explore:mo,moduleExplore:yo,toolingExplore:So,smartSuggest:bo,read:dr,write:Cr,mkdir:kt,glob:Dr,grep:Or,search_docs:Nr,build_doc_index:zr,shell:Cn,merge:kr,delete:wr,move:vr,copy:Pr,searchReplace:Ir,validate:Lr,search_file_changes:ep},Ws)}function Ma(o,e=null,t=!0){return{__tool_result:!0,result:o,display:e!==null?e:o,shouldPrint:t}}var Ws,G,Ia,Xd,Yd,Ke=C(()=>{Si();Si();ns();ns();rs();rs();ss();ss();Us();Us();Lt();Lt();ns();rs();ss();Us();tp();Lt();eo();Ws=null;G=new Proxy({},{get(o,e){return $a()[e]},ownKeys(){return Object.keys($a())},getOwnPropertyDescriptor(o,e){return{enumerable:!0,configurable:!0}}}),Ia={think:Sn,plan:oo,todo:lo,askUser:ao,quickProjectScan:In,explore:go,moduleExplore:ho,toolingExplore:Co,smartSuggest:wo,read:mr,write:xr,mkdir:yr,merge:Er,glob:jr,grep:Fr,search_docs:_r,build_doc_index:Wr,shell:Hr,delete:Sr,move:br,copy:Tr,searchReplace:$r,validate:Rr,searchFileChanges:Zu},Xd={getAIContextManager:gt,createAIContextManager:gu,resetAIContextManager:mu},Yd={detectFileChanges:bs,generateChangeSummary:vs,recordFileChange:Ts,handleGitCommit:Ps,getSessionFileChanges:Es,getCurrentSessionFileChanges:ks,getFileChangeTracker:Se,createFileChangeTracker:Ss,resetFileChangeTracker:ws}});var np=C(()=>{});import{Client as Qd}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as Zd}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{StdioClientTransport as ef}from"@modelcontextprotocol/sdk/client/stdio.js";var vo,Aa=C(()=>{V();vo=class{client=null;config;connected=!1;tools=[];constructor(e){this.config={timeout:3e4,enabled:!0,...e}}async connect(){S(`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 Zd(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 ef({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 Qd({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})),S(`Loaded ${this.tools.length} tools from ${this.config.name}`)}catch(e){throw S(`Failed to connect to MCP server ${this.config.name}: ${e.message}`),e}}async disconnect(){S(`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 rp=C(()=>{Aa()});function Ne(){return Ra.getInstance()}var Ra,La=C(()=>{Aa();V();Ra=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){Y("MCP Manager already initialized");return}if(L(`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(", ");S(`MCP Server Configurations: ${t}`)}for(let t of e){if(t.enabled===!1){S(`Skipping disabled MCP server: ${t.name}`);continue}try{S(`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}`),S(`Error details for ${t.name}: ${n.message}
2518
+ ${n.stack||""}`)}}this.initialized=!0,L(`MCP Manager initialized with ${this.clients.size} server(s) and ${this.mcpTools.size} tool(s)`)}async connectToServer(e){S(`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);L(`Connected to MCP server: ${e.name} (${n.length} tools)`)}createClient(e){return new vo(e)}registerTool(e){let t=e.name;if(this.mcpTools.has(t)){Y(`MCP tool ${t} already registered, skipping (using first registered)`);return}this.mcpTools.set(t,e),S(`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(){S("Disconnecting all MCP servers...");for(let[e,t]of this.clients.entries())try{await t.disconnect(),S(`Disconnected from MCP server: ${e}`)}catch(n){ne(`Error disconnecting from ${e}: ${n.message}`)}this.clients.clear(),this.mcpTools.clear(),this.initialized=!1,L("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 op(o){let e={};for(let t of o)e[t.name]=new zs(t);return e}function sp(o){let e={};for(let t of o){let n=new zs(t);e[t.name]=async(...r)=>n.execute(...r)}return e}var zs,ip=C(()=>{La();U();Ke();V();zs=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){S(`Executing MCP tool: ${this.mcpTool.name}`);let t=this.argsToParams(e),r=await Ne().callTool(this.mcpTool.name,t);if(!r.success)throw new Error(r.error||"MCP tool execution failed");let s=this.formatMCPResult(r.content);return Ma(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(`
1678
2519
 
1679
- `):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=y(()=>{cl();ll();pi();pl()});async function Mo(){if(mi){C("Tools already loaded, skipping");return}$("Loading tools..."),en={...W},dl={...ci};let o=Object.keys(W);$(`Loaded ${o.length} local tools`);let t=Zt().getAllTools();if(t.length===0){C("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]){C(`Skipping MCP tool ${a} (local tool has priority)`),i++;continue}en[a]=c,dl[a]=r[a],s++}$(`Added ${s} MCP tools, skipped ${i} (local priority)`),$(`Total tools available: ${Object.keys(en).length}`),mi=!0}function tn(){return en}function ml(){let o=Object.keys(W),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=y(()=>{Re();di();K();en={},dl={},mi=!1});var ri={};O(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=y(()=>{Re();xr();oi();Io=[W.think.getDefinition(),W.plan.getDefinition(),W.todo.getDefinition(),W.askUser.getDefinition(),W.quickProjectScan.getDefinition(),W.read.getDefinition(),W.write.getDefinition(),W.merge.getDefinition(),W.mkdir.getDefinition(),W.glob.getDefinition(),W.grep.getDefinition(),W.delete.getDefinition(),W.move.getDefinition(),W.copy.getDefinition(),W.searchReplace.getDefinition(),W.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=y(()=>{});import vr from"chalk";var Lo,yl=y(()=>{Ci();K();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;$(`\u5F00\u59CB\u4E0A\u4E0B\u6587\u538B\u7F29: ${s} \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 H("\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,C("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),C("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),C("Token\u538B\u529B\u4E2D\u7B49 (>=80%), \u4F7F\u7528\u4E2D\u7B49\u7A97\u53E3")):(s=this.options.maxKeepMessages,C("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++,C(`\u4F7F\u7528LLM\u6458\u8981 (${c.length}\u6761\u6D88\u606F, ${l} tokens)`)):(p=this.generateHeuristicSummary(c),s++,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]
2520
+ `):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 To=C(()=>{np();rp();La();ip()});async function dt(){if(ja){S("Tools already loaded, skipping");return}L("Loading tools..."),zn={...G},ap={...Ia};let o=Object.keys(G);L(`Loaded ${o.length} local tools`);let t=Ne().getAllTools();if(t.length===0){S("No MCP tools available"),ja=!0;return}let n=op(t),r=sp(t),s=0,i=0;for(let[a,c]of Object.entries(n)){if(zn[a]){S(`Skipping MCP tool ${a} (local tool has priority)`),i++;continue}zn[a]=c,ap[a]=r[a],s++}L(`Added ${s} MCP tools, skipped ${i} (local priority)`),L(`Total tools available: ${Object.keys(zn).length}`),ja=!0}function Hn(){return zn}function cp(){let o=Object.keys(G),e=Object.keys(zn),t=e.filter(n=>!o.includes(n));return{local:o.length,mcp:t.length,total:e.length,localTools:o,mcpTools:t}}var zn,ap,ja,Vn=C(()=>{Ke();To();V();zn={},ap={},ja=!1});var Sa={};_(Sa,{TOOL_DEFINITIONS:()=>tf,getRawToolDefinitions:()=>Br,getToolDefinitions:()=>Po,getToolNames:()=>up,isRealTool:()=>nf});function _t(){return Hs||(Hs=[G.think.getDefinition(),G.plan.getDefinition(),G.todo.getDefinition(),G.askUser.getDefinition(),G.quickProjectScan.getDefinition(),G.explore.getDefinition(),G.read.getDefinition(),G.write.getDefinition(),G.merge.getDefinition(),G.mkdir.getDefinition(),G.glob.getDefinition(),G.grep.getDefinition(),G.delete.getDefinition(),G.move.getDefinition(),G.copy.getDefinition(),G.searchReplace.getDefinition(),G.shell.getDefinition()],Hs)}function lp(o){return{name:o.name,description:o.description,input_schema:o.input_schema}}function Po(){let o=Hn();if(Object.keys(o).length===0)return _t().map(lp);let e=[],t=Xe.getCurrentNestingLevel(),n=Xe.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(lp)}function Br(){return _t()}function up(){return _t().map(o=>o.name)}function nf(o){return o!=="think"&&up().includes(o)}var Hs,tf,Pn=C(()=>{Ke();Vn();wa();Hs=null;tf=new Proxy([],{get(o,e){return _t()[e]},ownKeys(){return Object.keys(_t())},getOwnPropertyDescriptor(o,e){let t=_t();if(e in t)return{enumerable:!0,configurable:!0,writable:!1,value:t[e]}},has(o,e){return e in _t()}})});function Da(o){return!o||typeof o!="string"?0:Math.ceil(o.length/4)}function ft(o){if(!Array.isArray(o))return 0;let e=0;for(let t of o){if(t.content&&typeof t.content=="string"&&(e+=Da(t.content)),t.tool_calls&&Array.isArray(t.tool_calls))for(let n of t.tool_calls)n.function&&(e+=Da(n.function.name||""),e+=Da(n.function.arguments||""));e+=4}return e}function Vs(o,e){return!e||e<=0?0:o/e*100}function Fa(o,e,t=80){return Vs(o,e)>=t}function Oa(o,e,t){return`\u26A0\uFE0F Token usage warning: ${o.toLocaleString()} / ${e.toLocaleString()} tokens (${t.toFixed(1)}%)`}var _a=C(()=>{});import Eo from"chalk";var Bs,pp=C(()=>{_a();V();Bs=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?ft(e)/t>=this.options.threshold:!1}async compress(e,t,n){let r=ft(e),s=e.length;L(`\u5F00\u59CB\u4E0A\u4E0B\u6587\u538B\u7F29: ${s} \u6761\u6D88\u606F, ${r} tokens`);let i=this.calculateDynamicWindowSize(e,t);S(`\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 Y("\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=ft(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=ft(e)/t,s;return r>=.9?(s=this.options.minKeepMessages,S("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),S("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),S("Token\u538B\u529B\u4E2D\u7B49 (>=80%), \u4F7F\u7528\u4E2D\u7B49\u7A97\u53E3")):(s=this.options.maxKeepMessages,S("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=ft(c),u=this.assessMessageImportance(c),p;this.options.useMixedSummary&&u==="important"&&l>=this.options.llmSummaryTokenThreshold&&t?(p=await this.generateLLMSummary(c,t),r++,S(`\u4F7F\u7528LLM\u6458\u8981 (${c.length}\u6761\u6D88\u606F, ${l} tokens)`)):(p=this.generateHeuristicSummary(c),s++,S(`\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]
1680
2521
  \u4EE5\u4E0B\u662F\u4E4B\u524D\u7684\u5BF9\u8BDD\u6458\u8981,\u5DF2\u538B\u7F29\u4EE5\u8282\u7701token:
1681
2522
 
1682
2523
  ${n.join(`
@@ -1685,16 +2526,16 @@ ${n.join(`
1685
2526
 
1686
2527
  `)}
1687
2528
 
1688
- [\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(`
1689
- `);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 H(`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(`
1690
- \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
1691
- `)),$(`\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 Gt={};O(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();C(`\u6A21\u578B\u8C03\u7528\u914D\u7F6E: useCompression=${s}, \u6A21\u578B=${e}, provider=${u.getProviderType()}`),s?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}`);let p=s?os():rs(),g=t,d=Ye(g),m=Ao(d,p),h=v=>(v/1e3).toFixed(1)+"k";if($(`\u4F7F\u7528\u6A21\u578B: ${e}, Token usage: ${h(d)} / ${h(p)} (${m.toFixed(1)}%)`),T.currentTaskId){let v=T.tasks.find(S=>S.id===T.currentTaskId);v&&(v.tokenCount=(v.tokenCount||0)+d)}if(l&&hi(d,p,80)){let v=yi(d,p,m);H(v),console.log(nn.yellow(`
1692
- ${v}`)),console.log(nn.cyan(`\u{1F504} \u6B63\u5728\u81EA\u52A8\u538B\u7F29\u4E0A\u4E0B\u6587...
1693
- `));let S=new Lo(c);if(S.shouldCompress(g,p))try{let{messages:b,stats:L}=await S.compress(g,p,ee);g=b,d=L.compressedTokenCount,m=Ao(d,p),$(`\u538B\u7F29\u540EToken\u4F7F\u7528: ${d} / ${p} (${m.toFixed(1)}%)`)}catch(b){H(`\u4E0A\u4E0B\u6587\u538B\u7F29\u5931\u8D25: ${b instanceof Error?b.message:String(b)}`),console.log(nn.yellow(`\u26A0\uFE0F \u4E0A\u4E0B\u6587\u538B\u7F29\u5931\u8D25,\u5C06\u4F7F\u7528\u539F\u59CB\u6D88\u606F\u7EE7\u7EED\u6267\u884C
1694
- `))}else C("\u5F53\u524D\u4E0D\u6EE1\u8DB3\u538B\u7F29\u6761\u4EF6,\u8DF3\u8FC7\u538B\u7F29")}else if(hi(d,p,80)){let v=yi(d,p,m);H(v),console.log(nn.yellow(`
1695
- ${v}`)),console.log(nn.yellow(`Consider archiving old messages or starting a new session.
1696
- `))}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 w,x=10,k=1e4,f=0;for(;f<=x;)try{w=await u.callModel({model:e,messages:g,temperature:n,max_tokens:r,tools:i,tool_choice:a});break}catch(v){let S=v instanceof Error?v.message:String(v);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<x)f++,H(`API\u901F\u7387\u9650\u5236(429), \u6B63\u5728\u91CD\u8BD5... (${f}/${x}) \u7B49\u5F85 ${k/1e3}\u79D2`),console.log(nn.yellow(`\u26A0\uFE0F API\u901F\u7387\u9650\u5236, \u6B63\u5728\u91CD\u8BD5... (${f}/${x}) \u7B49\u5F85 ${k/1e3}\u79D2
1697
- `)),await new Promise(L=>setTimeout(L,k));else throw Y(`\u8C03\u7528\u6A21\u578BAPI\u65F6\u53D1\u751F\u9519\u8BEF: ${S}`),v instanceof Error&&v.stack&&C(`\u9519\u8BEF\u5806\u6808: ${v.stack}`),v}if(!w)throw Y("\u6A21\u578B\u8FD4\u56DE undefined \u6216 null"),new Error("\u6A21\u578BAPI\u8FD4\u56DE\u7A7A\u54CD\u5E94");if(!w.choices)throw Y(`\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 Y(`\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 Ip(){return"You are a helpful assistant."}var ve=y(()=>{le();ia();Ne();Ht();K();Ci();yl()});import*as pe from"fs";import*as Xe from"path";var xi,Cl=y(()=>{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
2529
+ [\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(()=>(ee(),en)),r=e.filter(a=>a.content).map(a=>`${a.role}: ${a.content}`).join(`
2530
+ `);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 Y(`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(Eo.green(`
2531
+ \u2728 \u4E0A\u4E0B\u6587\u538B\u7F29\u5B8C\u6210`)),console.log(Eo.cyan(` \u6D88\u606F\u6570: ${e.originalMessageCount} \u2192 ${e.compressedMessageCount} (${e.compressedMessageCount-e.originalMessageCount})`)),console.log(Eo.cyan(` Token: ${e.originalTokenCount} \u2192 ${e.compressedTokenCount} (\u8282\u7701 ${n}%)`)),console.log(Eo.cyan(` \u538B\u7F29\u6BD4: ${t}%`)),console.log(Eo.cyan(` \u6458\u8981\u65B9\u5F0F: LLM ${e.llmSummaryCount}\u6B21, \u542F\u53D1\u5F0F ${e.heuristicSummaryCount}\u6B21
2532
+ `)),L(`\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},S(`\u538B\u7F29\u914D\u7F6E\u5DF2\u66F4\u65B0: ${JSON.stringify(this.options)}`)}getOptions(){return{...this.options}}}});var kn={};_(kn,{callModelAPI:()=>B,getDefaultSystemPrompt:()=>rf});import Bn from"chalk";async function B(o){let{model:e=o.useCompression?Be():ce(),messages:t,temperature:n=.1,max_tokens:r,useCompression:s=!1,tools:i=Po(),tool_choice:a,compressionOptions:c,enableAutoCompression:l=!0}=o,u=s?await ur.getLiteProvider():await ur.getProvider();S(`\u6A21\u578B\u8C03\u7528\u914D\u7F6E: useCompression=${s}, \u6A21\u578B=${e}, provider=${u.getProviderType()}`),s?S(`\u6B63\u5728\u4F7F\u7528\u8F7B\u91CF\u6A21\u578B: ${e}`):S(`\u6B63\u5728\u4F7F\u7528\u9ED8\u8BA4\u6A21\u578B: ${e}`),S(`\u5DE5\u5177\u6570\u91CF: ${i?i.length:0}`);let p=s?hi():fi(),g=t,d=ft(g),m=Vs(d,p),f=y=>(y/1e3).toFixed(1)+"k";if(L(`\u4F7F\u7528\u6A21\u578B: ${e}, Token usage: ${f(d)} / ${f(p)} (${m.toFixed(1)}%)`),E.currentTaskId){let y=E.tasks.find(T=>T.id===E.currentTaskId);y&&(y.tokenCount=(y.tokenCount||0)+d)}if(l&&Fa(d,p,80)){let y=Oa(d,p,m);Y(y),console.log(Bn.yellow(`
2533
+ ${y}`)),console.log(Bn.cyan(`\u{1F504} \u6B63\u5728\u81EA\u52A8\u538B\u7F29\u4E0A\u4E0B\u6587...
2534
+ `));let T=new Bs(c);if(T.shouldCompress(g,p))try{let{messages:P,stats:b}=await T.compress(g,p,B);g=P,d=b.compressedTokenCount,m=Vs(d,p),L(`\u538B\u7F29\u540EToken\u4F7F\u7528: ${d} / ${p} (${m.toFixed(1)}%)`)}catch(P){Y(`\u4E0A\u4E0B\u6587\u538B\u7F29\u5931\u8D25: ${P instanceof Error?P.message:String(P)}`),console.log(Bn.yellow(`\u26A0\uFE0F \u4E0A\u4E0B\u6587\u538B\u7F29\u5931\u8D25,\u5C06\u4F7F\u7528\u539F\u59CB\u6D88\u606F\u7EE7\u7EED\u6267\u884C
2535
+ `))}else S("\u5F53\u524D\u4E0D\u6EE1\u8DB3\u538B\u7F29\u6761\u4EF6,\u8DF3\u8FC7\u538B\u7F29")}else if(Fa(d,p,80)){let y=Oa(d,p,m);Y(y),console.log(Bn.yellow(`
2536
+ ${y}`)),console.log(Bn.yellow(`Consider archiving old messages or starting a new session.
2537
+ `))}S(`\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 x,w=10,v=1e4,h=0;for(;h<=w;)try{x=await u.callModel({model:e,messages:g,temperature:n,max_tokens:r,tools:i,tool_choice:a});break}catch(y){let T=y instanceof Error?y.message:String(y);if((T.includes("429")||T.includes("Too Many Requests")||T.includes("rate limit")||T.includes("\u8D85\u8FC7\u9650\u5236")||T.includes("\u8BF7\u6C42\u9891\u7387"))&&h<w)h++,Y(`API\u901F\u7387\u9650\u5236(429), \u6B63\u5728\u91CD\u8BD5... (${h}/${w}) \u7B49\u5F85 ${v/1e3}\u79D2`),console.log(Bn.yellow(`\u26A0\uFE0F API\u901F\u7387\u9650\u5236, \u6B63\u5728\u91CD\u8BD5... (${h}/${w}) \u7B49\u5F85 ${v/1e3}\u79D2
2538
+ `)),await new Promise(b=>setTimeout(b,v));else throw ne(`\u8C03\u7528\u6A21\u578BAPI\u65F6\u53D1\u751F\u9519\u8BEF: ${T}`),y instanceof Error&&y.stack&&S(`\u9519\u8BEF\u5806\u6808: ${y.stack}`),y}if(!x)throw ne("\u6A21\u578B\u8FD4\u56DE undefined \u6216 null"),new Error("\u6A21\u578BAPI\u8FD4\u56DE\u7A7A\u54CD\u5E94");if(!x.choices)throw ne(`\u6A21\u578B\u8FD4\u56DE\u7F3A\u5C11choices\u5B57\u6BB5: ${JSON.stringify(x)}`),new Error("\u6A21\u578BAPI\u8FD4\u56DE\u7684\u54CD\u5E94\u7F3A\u5C11choices\u5B57\u6BB5");if(!Array.isArray(x.choices)||x.choices.length===0)throw ne(`\u6A21\u578B\u8FD4\u56DE\u7A7A\u7684choices\u6570\u7EC4: ${JSON.stringify(x)}`),new Error("\u6A21\u578BAPI\u8FD4\u56DE\u7684choices\u4E3A\u7A7A");return S(`\u6A21\u578B\u8FD4\u56DE: ${JSON.stringify(x)}`),x}function rf(){return"You are a helpful assistant."}var Ce=C(()=>{ee();Ac();Ve();Pn();V();_a();pp()});import*as Pe from"fs";import*as ht from"path";var Na,gp=C(()=>{Ce();ee();Na={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
1698
2539
 
1699
2540
  ## \u8F93\u51FA\u8981\u6C42
1700
2541
 
@@ -1793,7 +2634,7 @@ ${v}`)),console.log(nn.yellow(`Consider archiving old messages or starting a new
1793
2634
  3. **\u6DF1\u5EA6\u5206\u6790**\uFF1A\u5FC5\u8981\u65F6\u6DF1\u5165\u8BFB\u53D6\u548C\u5206\u6790\u5173\u952E\u4EE3\u7801\u6587\u4EF6
1794
2635
  4. **\u6E05\u6670\u8868\u8FBE**\uFF1A\u4EE5\u7ED3\u6784\u5316\u3001\u6613\u61C2\u7684\u65B9\u5F0F\u5448\u73B0\u5206\u6790\u7ED3\u679C
1795
2636
  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
1796
- 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
2637
+ 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=ht.join(t,".nium","docs");Pe.existsSync(n)||Pe.mkdirSync(n,{recursive:!0});let r=ht.join(n,"PROJECT.md"),s=`# \u9879\u76EE\u63A2\u7D22\u62A5\u544A
1797
2638
 
1798
2639
  > \u751F\u6210\u65F6\u95F4: ${new Date().toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"})}
1799
2640
  > \u751F\u6210\u5DE5\u5177: Explorer Agent
@@ -1805,11 +2646,11 @@ ${o}
1805
2646
  ---
1806
2647
 
1807
2648
  *\u6B64\u6587\u6863\u7531 Explorer Agent \u81EA\u52A8\u751F\u6210\uFF0C\u8BB0\u5F55\u4E86\u9879\u76EE\u7ED3\u6784\u5206\u6790\u7ED3\u679C\u3002*
1808
- `;if(!pe.existsSync(r))pe.writeFileSync(r,s,"utf-8"),console.log(`
1809
- \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
2649
+ `;if(!Pe.existsSync(r))Pe.writeFileSync(r,s,"utf-8"),console.log(`
2650
+ \u2713 \u9879\u76EE\u63A2\u7D22\u7ED3\u679C\u5DF2\u4FDD\u5B58\u5230: ${ht.relative(t,r)}`);else{let i=ht.join(t,".nium","merge");Pe.existsSync(i)||Pe.mkdirSync(i,{recursive:!0});let a=`project-merge-${Date.now()}.md`,c=ht.join(i,a),l=`# PROJECT.md \u5408\u5E76\u8BF7\u6C42
1810
2651
 
1811
2652
  ## \u5F53\u524D\u6587\u4EF6\u5185\u5BB9
1812
- ${pe.readFileSync(r,"utf-8")}
2653
+ ${Pe.readFileSync(r,"utf-8")}
1813
2654
 
1814
2655
  ## \u65B0\u751F\u6210\u5185\u5BB9
1815
2656
  ${s}
@@ -1822,12 +2663,12 @@ ${s}
1822
2663
  4. \u5408\u5E76\u6838\u5FC3\u6A21\u5757\u5206\u6790\uFF0C\u4FDD\u7559\u6240\u6709\u6709\u7528\u4FE1\u606F
1823
2664
  5. \u786E\u4FDD\u5408\u5E76\u540E\u7684\u6587\u6863\u7ED3\u6784\u6E05\u6670\uFF0C\u4FBF\u4E8E\u9605\u8BFB\u548C\u68C0\u7D22
1824
2665
  6. \u4FDD\u6301\u8F93\u51FA\u4E3A\u7CBE\u7B80\u7684\u603B\u7ED3\u578B\u63CF\u8FF0\uFF0C\u9002\u5408\u4F5C\u4E3A\u52A8\u6001\u63D0\u793A\u8BCD
1825
- `;pe.writeFileSync(c,l,"utf-8"),console.log(`
1826
- \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
2666
+ `;Pe.writeFileSync(c,l,"utf-8"),console.log(`
2667
+ \u2713 \u9879\u76EE\u63A2\u7D22\u7ED3\u679C\u5DF2\u751F\u6210\u5408\u5E76\u8BF7\u6C42: ${ht.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
1827
2668
 
1828
2669
  ${l}
1829
2670
 
1830
- \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=y(()=>{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
2671
+ \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 B({model:ce(),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 Ua,mp=C(()=>{Ua={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
1831
2672
 
1832
2673
  ## \u6838\u5FC3\u89C4\u5219
1833
2674
 
@@ -1901,29 +2742,50 @@ ${l}
1901
2742
  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
1902
2743
  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
1903
2744
  3. **\u7ED3\u679C\u51C6\u786E\u6027**\uFF1A\u786E\u4FDD\u641C\u7D22\u7ED3\u679C\u51C6\u786E\u53CD\u6620\u7528\u6237\u9700\u6C42
1904
- 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=y(()=>{ea();Cl();xl();Ap={[ts.name]:ts,[xi.name]:xi,[Si.name]:Si}});var Qc={};O(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=y(()=>{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(`
1905
- `);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(`
1906
- `),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 B 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&&T.messages&&T.messages.length>0)Z(`Resuming existing session: ${T.sessionId}`),r=T.messages,Qe(`\u6062\u590D\u4F1A\u8BDD [ID:${T.sessionId.substring(0,8)}]: ${T.currentTask}`),hn(B.green(`\u4ECE ${T.updatedAt} \u6062\u590D\u4E4B\u524D\u7684\u4F1A\u8BDD [ID:${T.sessionId.substring(0,8)}]`),t),G(B.gray(`\u4E4B\u524D\u7684\u4EFB\u52A1: ${T.currentTask}`),t),T.tasks&&T.tasks.length>0&&G(B.gray(`\u4F1A\u8BDD\u4E2D\u4EFB\u52A1\u6570\u91CF: ${T.tasks.length}`),t),G("",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}
2745
+ 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 dp(){return Object.values(of)}var of,fp=C(()=>{Tc();gp();mp();of={[gi.name]:gi,[Na.name]:Na,[Ua.name]:Ua}});var Du={};_(Du,{SubAgentManager:()=>Js,getSubAgentManager:()=>An});import{existsSync as sf,readFileSync as af,readdirSync as cf}from"fs";import{join as lf}from"path";import Ee from"chalk";function An(o={}){return Gs?o.matchStrategy&&Gs.setMatchStrategy(o.matchStrategy):Gs=new Js(o),Gs}var Js,Gs,_s=C(()=>{He();fp();ee();Ce();Mt();Js=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=dp();console.log(Ee.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(Ee.red(`\u274C \u52A0\u8F7D\u5185\u7F6E\u4EE3\u7406\u5931\u8D25: ${e.message}`))}}loadSubAgents(){let e=Te("agents");if(!sf(e)){console.log(Ee.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=cf(e).filter(r=>r.endsWith(".json")||r.endsWith(".md"));console.log(Ee.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=lf(e,r),i=af(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(Ee.green(`\u2713 \u52A0\u8F7D\u81EA\u5B9A\u4E49\u5B50\u667A\u80FD\u4F53: ${a.name}`))):console.log(Ee.yellow(`\u26A0\uFE0F \u914D\u7F6E\u6587\u4EF6 ${r} \u683C\u5F0F\u65E0\u6548\uFF0C\u5DF2\u8DF3\u8FC7`))}catch(s){console.log(Ee.red(`\u274C \u52A0\u8F7D\u914D\u7F6E\u6587\u4EF6 ${r} \u5931\u8D25: ${s.message}`))}}catch(t){console.log(Ee.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(`
2746
+ `);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(Ee.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(Ee.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(Ee.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(`
2747
+ `),r=Yi(e,n),s=await B({model:Be(),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(Ee.blue(`[\u5B50\u667A\u80FD\u4F53\u7BA1\u7406\u5668] \u5339\u914D\u7B56\u7565\u5DF2\u8BBE\u7F6E\u4E3A: ${e}`)),!0):(console.error(Ee.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}},Gs=null});import te from"chalk";import Nt from"readline";async function qs(o,e=!1,t=null,n=null){let r,s=null,i=xs();if(ae("Initializing react loop with think-tool support"),e&&E.messages&&E.messages.length>0)ae(`Resuming existing session: ${E.sessionId}`),r=E.messages,bt(`\u6062\u590D\u4F1A\u8BDD [ID:${E.sessionId.substring(0,8)}]: ${E.currentTask}`),ir(te.green(`\u4ECE ${E.updatedAt} \u6062\u590D\u4E4B\u524D\u7684\u4F1A\u8BDD [ID:${E.sessionId.substring(0,8)}]`),t),Z(te.gray(`\u4E4B\u524D\u7684\u4EFB\u52A1: ${E.currentTask}`),t),E.tasks&&E.tasks.length>0&&Z(te.gray(`\u4F1A\u8BDD\u4E2D\u4EFB\u52A1\u6570\u91CF: ${E.tasks.length}`),t),Z("",t);else if(o){ae(`Starting new task: ${o.substring(0,50)}${o.length>50?"...":""}`);let u=Se(),p=gt(u);await u.detectFileChanges();let g=p.generatePromptIntegrationContent(),d=await Tn;r=[{role:"system",content:g?`${d}
2748
+
2749
+ ${g}`:d},{role:"user",content:o}],bt(`\u5F00\u59CB\u65B0\u4EFB\u52A1: ${o}`),(i.enableAnchorSystem||i.enableSemanticAnalysis)&&(s=new jt(o,B),ae("\u7EDF\u4E00\u951A\u70B9\u6CE8\u5165\u5668\u5DF2\u521D\u59CB\u5316")),No(o),xe(r,o)}else{Ae("No user request provided and no session to resume");return}let a=0,c=100,l=0;for(ae(`Starting execution loop with max ${c} iterations`);a<c;){a++,ae(`Loop iteration ${a}`);try{if(s){let w=await s.injectAnchors({taskDescription:o||E.currentTask,iterations:a,messages:r,lastSemanticCheckIteration:l,session:t,logWarning:Xt,callModelAPI:B}),{messages:v,lastSemanticCheckIteration:h}=w;r=v,l=h}xe(r);let u=ce();t&&Z(te.gray(`[\u8FED\u4EE3 ${a}] \u4F7F\u7528\u6A21\u578B: ${u}`),t),ae("Calling Model API with all tools including think");let p=await B({model:u,messages:r,temperature:.1,tools:Po(),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 Ae(w),new Error(w)}let{choices:g}=p,d=g[0],m=d?.message,f=null,x=null;if(m&&({content:f,tool_calls:x}=m,f&&f.trim())){if(ae(`Model returned text content: ${f.substring(0,100)}...`),!x||x.length===0){if(n?.finalAnswerCallback)try{await n.finalAnswerCallback(f)}catch(w){Ae(`Error in finalAnswerCallback: ${w}`)}ir(te.green(`
2750
+ \u6700\u7EC8\u7B54\u6848:`),t),Z(te.white(f),t),Z("",t),r.push({role:"assistant",content:f}),bt("\u4EFB\u52A1\u5B8C\u6210,\u5F52\u6863\u4F1A\u8BDD"),Tt(),ae("Breaking out of react loop after final answer");return}Z(te.magenta(`\u601D\u8003: ${f}`),t),Z("",t)}if(x&&x.length>0){let w=x[0],v=w.function.name,h=w.function.arguments;ae(`Tool call: ${v} with args: ${h}`);let y;try{y=JSON.parse(h)}catch{Ae(`Failed to parse tool arguments: ${h}`),r.push({role:"user",content:`Error: Invalid JSON in tool arguments: ${h}`});continue}if(bn(v)){let M=y.thought||"";Z(te.magenta(`\u601D\u8003: ${M}`),t),Z("",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(fa(v)){let M=ha(w);if(M){let{answer:D,success:j}=M;if(n?.finalAnswerCallback)try{await n.finalAnswerCallback(D)}catch(A){Ae(`Error in finalAnswerCallback: ${A}`)}let R=j?"\u2705":"\u26A0\uFE0F";ir(te.green(`
2751
+ ${R} \u4EFB\u52A1\u5B8C\u6210 (\u901A\u8FC7 finish \u5DE5\u5177):`),t),Z(te.white(D),t),Z("",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:D}),bt("\u4EFB\u52A1\u5B8C\u6210(finish\u5DE5\u5177),\u5F52\u6863\u4F1A\u8BDD"),Tt(),ae("Breaking out of react loop after finish tool call");return}}let P=Hn()[v];if(!P){let M=`Unknown tool: ${v}`;Ae(M),r.push({role:"assistant",content:f||null,tool_calls:[w]}),r.push({role:"tool",tool_call_id:w.id,content:M});continue}let b=P.formatAction(y);Z(te.cyan(`\u884C\u52A8: ${b}`),t),Z("",t);try{let M=!1;if(v==="shell"&&P&&typeof P.getDynamicDefinition=="function"?M=P.getDynamicDefinition(y).requiresConfirmation||!1:M=Br().find(le=>le.name===v)?.requiresConfirmation||!1,M&&!await uf(v,y,t)){let le=`\u5DE5\u5177\u6267\u884C\u5DF2\u53D6\u6D88: ${v}`;bt(le),Xt(te.yellow(`\u26A0 ${le}`),t),Z(te.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}ae(`\u6267\u884C\u5DE5\u5177: ${v}(${JSON.stringify(y)})`);let D=await Promise.resolve(P.execute(y));ae(`\u5DE5\u5177 ${v} \u6267\u884C\u5B8C\u6210`);let j=pr(D),R=P?P.shouldPrintObservation(D):!0,I=`${P?P.formatObservation(D):String(D)}`;R&&(Z(te.yellow(`\u89C2\u5BDF: ${I}`),t),Z("",t)),r.push({role:"assistant",content:f||null,tool_calls:[w]}),r.push({role:"tool",tool_call_id:w.id,content:String(j)})}catch(M){let D=`\u5DE5\u5177\u6267\u884C\u9519\u8BEF: ${v} - ${M.message}`;Ae(D,t),Z("",t),r.push({role:"assistant",content:f||null,tool_calls:[w]}),r.push({role:"tool",tool_call_id:w.id,content:`Error: ${D}`}),xe(r,o)}}if((!f||!f.trim())&&(!x||x.length===0)){if(ai("Model returned empty response"),d.finish_reason==="stop"){Xt("\u4EFB\u52A1\u5B8C\u6210(\u6A21\u578B\u505C\u6B62)",t),Tt(),ae("Breaking out of react loop after model stop");return}r.push({role:"user",content:"Please continue or provide your final answer."})}}catch(u){Ae(`\u9519\u8BEF: ${u.message}`,t),Xt("\u4F1A\u8BDD\u5DF2\u4FDD\u5B58\u3002\u4F7F\u7528 /resume \u7EE7\u7EED\u3002",t),xe(r,o);return}}if(a>=c){Ae("\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);ae(`\u4F18\u5316\u7EDF\u8BA1: \u538B\u7F29${u}\u6B21, \u951A\u70B9\u6CE8\u5165${p}\u6B21, \u8BED\u4E49\u68C0\u67E5${g}\u6B21`),xe(r,o)}}async function uf(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++)Nt.moveCursor(process.stdout,0,-1),Nt.clearLine(process.stdout,0);let d=t?te.yellow(`\u26A0 \u786E\u8BA4\u6267\u884C ${o}(${i})\uFF1F\u6B64\u64CD\u4F5C\u53EF\u80FD\u65E0\u6CD5\u64A4\u9500\u3002`):te.yellow(`\u26A0 Confirm execution of ${o}(${i})? This action may be irreversible.`);console.log(""),console.log(d),console.log(""),console.log(te.cyan("\u8BF7\u9009\u62E9 (\u4F7F\u7528\u4E0A\u4E0B\u7BAD\u5934\u952E\uFF0CEnter\u786E\u8BA4):")),console.log(""),s.forEach((m,f)=>{let x=f===r,w=x?te.green("> "):" ",v=x?te.green.bold(m.text):te.white(m.text);console.log(`${w}${v}`)}),console.log("")},c=process.stdin.isTTY?process.stdin.isRaw:!1,l=[],u=io();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 f=0;f<8;f++)Nt.moveCursor(process.stdout,0,-1),Nt.clearLine(process.stdout,0);n(s[r].value);return}else if(m.name==="escape"||m.ctrl&&m.name==="c"){g();for(let f=0;f<8;f++)Nt.moveCursor(process.stdout,0,-1),Nt.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):(Nt.emitKeypressEvents(process.stdin),process.stdin.on("keypress",p)),a()})}var Wa=C(()=>{ee();Ce();Mt();Ke();Vn();Vr();Ds();Ve();Pn();to();ra();Ns();Lt();eo();V()});var yp={};_(yp,{DocumentAggregator:()=>za});import{readFileSync as pf,existsSync as gf,readdirSync as mf,statSync as df}from"fs";import{join as hp,extname as ff}from"path";var za,xp=C(()=>{V();za=class{docsDir;cache=new Map;cacheExpiry=300*1e3;lastCacheTime=0;constructor(e){this.docsDir=e||hp(process.cwd(),".nium","docs")}async getDocFiles(){if(!gf(this.docsDir))return[];let e=[];try{let t=mf(this.docsDir,{withFileTypes:!0});for(let n of t)if(n.isFile()&&this.isMarkdownFile(n.name)){let r=hp(this.docsDir,n.name),s=df(r);try{let i=pf(r,"utf-8");e.push({name:n.name,path:r,content:i,lastModified:s.mtime,size:s.size})}catch(i){S(`\u65E0\u6CD5\u8BFB\u53D6\u6587\u6863\u6587\u4EF6 ${n.name}: ${i}`)}}}catch(t){S(`\u8BFB\u53D6\u6587\u6863\u76EE\u5F55\u5931\u8D25: ${t}`)}return e.sort((t,n)=>t.name.localeCompare(n.name)),e}isMarkdownFile(e){let t=ff(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: ${new Date().toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"})}`),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=c.lastModified.toLocaleString("zh-CN");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(`
2752
+ `)[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+=`
2753
+
2754
+ # \u{1F4C1} ${c.name}
2755
+
2756
+ `,n+=c.content,n+=`
2757
+
2758
+ ---
2759
+ `;let s=r.join(`
2760
+ `),i=s+n,a={files:t,totalContent:i,summary:s,lastUpdated:new Date};return this.cache.set("default",a),this.lastCacheTime=e,L(`\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 s=t.summary,i=e-s.length/4;if(i>1e3){let a=i*4,c=n.substring(0,a);return s+`
2761
+
2762
+ `+c+`
2763
+
2764
+ ... (\u5185\u5BB9\u5DF2\u622A\u65AD\uFF0C\u5B8C\u6574\u5185\u5BB9\u8BF7\u67E5\u770B\u5177\u4F53\u6587\u6863\u6587\u4EF6)`}return s+`
2765
+
2766
+ ... (\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}))}}}});import J from"chalk";async function Cp(o,e=!1,t=null,n={}){Ha||(Ha=new ko(t,n)),await Ha.executeTask(o,e)}var ko,Ha,Sp=C(()=>{_s();_e();Wa();Mt();Ve();V();la();Os();ys();ko=class{session;subAgentManager;orchestratorContext;progressiveDisclosure;workerContextBuilder;summaryExtractor;options;constructor(e=null,t={}){this.session=e,xa(e);let n={matchStrategy:t.matchStrategy};this.subAgentManager=An(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 at(this.orchestratorContext),this.workerContextBuilder=new ct(this.orchestratorContext,this.progressiveDisclosure),this.summaryExtractor=new lt(this.options.useLLMSummary)}log(e){this.session?this.session.log(e):console.log(e)}info(e){this.session?this.session.info(e):console.log(J.blue(e))}success(e){this.session?this.session.success(e):console.log(J.green(e))}warning(e){this.session?this.session.warning(e):console.log(J.yellow(e))}error(e){this.session?this.session.error(e):console.log(J.red(e))}async executeTask(e,t=!1){try{if(S("MasterAgent.executeTask called"),t){S("Entering resume session mode"),this.info("\u6062\u590D\u4F1A\u8BDD\u6A21\u5F0F"),await qs(e,!0,this.session);return}let{evaluateTaskComplexity:n,TaskComplexity:r}=await Promise.resolve().then(()=>(_e(),st));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(J.gray("\u2550\u2550\u2550 \u5168\u5C40\u4E0A\u4E0B\u6587\u6458\u8981 \u2550\u2550\u2550")),this.log(J.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,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 qs(e,!1,this.session)}async executeWithPlanning(e){let t=this.subAgentManager.getAllSubAgents(),n=await Gr(e,t);this.orchestratorContext.initializeTask(e,n),n.taskId&&Qt(n.taskId),this.log(Jr(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(J.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(J.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")){S("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(()=>(Ke(),ro));await n.quickProjectScan(),this.success("\u2705 \u9879\u76EE\u7ED3\u6784\u6587\u6863\u5DF2\u751F\u6210"),this.log(""),L("\u5DF2\u81EA\u52A8\u751F\u6210 project.json")}catch(e){S(`\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{DocumentAggregator:e}=await Promise.resolve().then(()=>(xp(),yp)),t=new e,n="",{tools:r}=await Promise.resolve().then(()=>(Ke(),ro)),i=r.read({path:".nium/rules.md"});i&&!i.includes("Error:")&&(n+=i,L("\u5DF2\u52A0\u8F7D\u9879\u76EE\u89C4\u5219\u6587\u4EF6"));let c=r.read({path:".nium/project/project.json"});if(c&&!c.includes("Error:")){n&&(n+=`
2767
+
2768
+ ---
2769
+
2770
+ `),n+=`## \u9879\u76EE\u5173\u952E\u4FE1\u606F
1907
2771
 
1908
- ${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 x=await s.injectAnchors({taskDescription:o||T.currentTask,iterations:a,messages:r,lastSemanticCheckIteration:l,session:t,logWarning:Ct,callModelAPI:ee}),{messages:k,lastSemanticCheckIteration:f}=x;r=k,l=f}ce(r);let u=ye();t&&G(B.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 x=`\u6A21\u578B\u8FD4\u56DE\u65E0\u6548\u54CD\u5E94: ${JSON.stringify(p)}`;throw he(x),new Error(x)}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(x){he(`Error in finalAnswerCallback: ${x}`)}hn(B.green(`
1909
- \u6700\u7EC8\u7B54\u6848:`),t),G(B.white(h),t),G("",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}G(B.magenta(`\u{1F4AD} \u601D\u8003: ${h}`),t),G("",t)}if(w&&w.length>0){let x=w[0],k=x.function.name,f=x.function.arguments;Z(`Tool call: ${k} with args: ${f}`);let v;try{v=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(k)){let M=v.thought||"";G(B.magenta(`\u601D\u8003: ${M}`),t),G("",t),r.push({role:"assistant",content:h||null,tool_calls:[x]}),r.push({role:"tool",tool_call_id:x.id,content:"Noted. Continue."});continue}if(Qs(k)){let M=Zs(x);if(M){let{answer:I,success:q}=M;if(n?.finalAnswerCallback)try{await n.finalAnswerCallback(I)}catch(J){he(`Error in finalAnswerCallback: ${J}`)}let Q=q?"\u2705":"\u26A0\uFE0F";hn(B.green(`
1910
- ${Q} \u4EFB\u52A1\u5B8C\u6210 (\u901A\u8FC7 finish \u5DE5\u5177):`),t),G(B.white(I),t),G("",t),r.push({role:"assistant",content:h||null,tool_calls:[x]}),r.push({role:"tool",tool_call_id:x.id,content:"Task completed successfully."}),r.push({role:"assistant",content:I}),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 b=tn()[k];if(!b){let M=`Unknown tool: ${k}`;he(M),r.push({role:"assistant",content:h||null,tool_calls:[x]}),r.push({role:"tool",tool_call_id:x.id,content:M});continue}let L=b.formatAction(v);G(B.cyan(`\u884C\u52A8: ${L}`),t),G("",t);try{let M=!1;if(k==="shell"&&b&&typeof b.getDynamicDefinition=="function"?M=b.getDynamicDefinition(v).requiresConfirmation||!1:M=Qn().find(te=>te.name===k)?.requiresConfirmation||!1,M&&!await Op(k,v,t)){let te=`\u5DE5\u5177\u6267\u884C\u5DF2\u53D6\u6D88: ${k}`;Qe(te),Ct(B.yellow(`\u26A0 ${te}`),t),G(B.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:[x]}),r.push({role:"tool",tool_call_id:x.id,content:"Execution cancelled by user"});continue}Z(`\u6267\u884C\u5DE5\u5177: ${k}(${JSON.stringify(v)})`);let I=await Promise.resolve(b.execute(v));Z(`\u5DE5\u5177 ${k} \u6267\u884C\u5B8C\u6210`);let q=xn(I),Q=b?b.shouldPrintObservation(I):!0,R=`${b?b.formatObservation(I):String(I)}`;Q&&(G(B.yellow(`\u{1F4CA} \u89C2\u5BDF: ${R}`),t),G("",t)),r.push({role:"assistant",content:h||null,tool_calls:[x]}),r.push({role:"tool",tool_call_id:x.id,content:String(q)})}catch(M){let I=`\u5DE5\u5177\u6267\u884C\u9519\u8BEF: ${k} - ${M.message}`;he(I,t),G("",t),r.push({role:"assistant",content:h||null,tool_calls:[x]}),r.push({role:"tool",tool_call_id:x.id,content:`Error: ${I}`}),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?B.yellow(`\u26A0 \u786E\u8BA4\u6267\u884C ${o}(${i})\uFF1F\u6B64\u64CD\u4F5C\u53EF\u80FD\u65E0\u6CD5\u64A4\u9500\u3002`):B.yellow(`\u26A0 Confirm execution of ${o}(${i})? This action may be irreversible.`);console.log(""),console.log(d),console.log(""),console.log(B.cyan("\u8BF7\u9009\u62E9 (\u4F7F\u7528\u4E0A\u4E0B\u7BAD\u5934\u952E\uFF0CEnter\u786E\u8BA4):")),console.log(""),s.forEach((m,h)=>{let w=h===r,x=w?B.green("> "):" ",k=w?B.green.bold(m.text):B.white(m.text);console.log(`${x}${k}`)}),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=y(()=>{le();ve();it();Re();xr();Xn();wo();Ne();Ht();cr();Us();Eo();lt();ar();K()});import _ from"chalk";async function wl(o,e=!1,t=null,n={}){await new wr(t,n).executeTask(o,e)}var wr,bl=y(()=>{ko();$e();vi();it();Ne();K();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.orchestratorContext=new We,this.progressiveDisclosure=new ze(this.orchestratorContext),this.workerContextBuilder=new He(this.orchestratorContext,this.progressiveDisclosure),this.summaryExtractor=new Je,this.options={useLLMDisclosure:t.useLLMDisclosure!==void 0?t.useLLMDisclosure:!0,useLLMSummary:t.useLLMSummary!==void 0?t.useLLMSummary:!0,verbose:t.verbose||!1}}log(e){this.session?this.session.log(e):console.log(e)}info(e){this.session?this.session.info(e):console.log(_.blue(e))}success(e){this.session?this.session.success(e):console.log(_.green(e))}warning(e){this.session?this.session.warning(e):console.log(_.yellow(e))}error(e){this.session?this.session.error(e):console.log(_.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 Fo(e,!0,this.session);return}let{evaluateTaskComplexity:n,TaskComplexity:r}=await Promise.resolve().then(()=>($e(),Ve));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(_.gray("\u2550\u2550\u2550 \u5168\u5C40\u4E0A\u4E0B\u6587\u6458\u8981 \u2550\u2550\u2550")),this.log(_.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(_.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(_.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")){C("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(""),$("\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(){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,$("\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+=`
2772
+ `;try{let l=JSON.parse(c),u=this.extractProjectKeySummary(l);n+=u,L("\u5DF2\u52A0\u8F7D\u9879\u76EE\u5173\u952E\u4FE1\u606F\u6458\u8981")}catch{n+=c,S("\u89E3\u6790\u9879\u76EE\u7ED3\u6784JSON\u5931\u8D25\uFF0C\u4F7F\u7528\u539F\u59CB\u5185\u5BB9")}}try{let l=await t.getDocumentSummary(6e3);l&&(n&&(n+=`
1911
2773
 
1912
2774
  ---
1913
2775
 
1914
- `),r+=`## \u9879\u76EE\u5173\u952E\u4FE1\u606F
2776
+ `),n+=`## \u{1F4DA} \u9879\u76EE\u6587\u6863
1915
2777
 
1916
- `;try{let l=JSON.parse(c),u=this.extractProjectKeySummary(l);r+=u,$("\u5DF2\u52A0\u8F7D\u9879\u76EE\u5173\u952E\u4FE1\u606F\u6458\u8981")}catch{r+=c,C("\u89E3\u6790\u9879\u76EE\u7ED3\u6784JSON\u5931\u8D25\uFF0C\u4F7F\u7528\u539F\u59CB\u5185\u5BB9")}}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 s=Date.now();this.info(`\u{1F527} \u4F7F\u7528\u5B50\u667A\u80FD\u4F53: ${n.name}`),this.log(_.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 x=await s({model:r(),messages:m,temperature:.1,tools:u()}),k=x.choices[0].message.tool_calls;if(x.choices[0].finish_reason==="stop"){let{content:R}=x.choices[0].message;if(R&&R.trim()){if(n?.finalAnswerCallback)try{await n.finalAnswerCallback(R,n)}catch(oe){Y(`Error in finalAnswerCallback: ${oe}`)}this.log(_.green("\u4EFB\u52A1\u5B8C\u6210:")),this.log(R),this.log("")}break}if(!k||k.length===0){let{content:R}=x.choices[0].message;if(R&&R.trim()){if(n?.finalAnswerCallback)try{await n.finalAnswerCallback(R,n)}catch(oe){Y(`Error in finalAnswerCallback: ${oe}`)}this.log(_.green("\u4EFB\u52A1\u5B8C\u6210:")),this.log(R),this.log(""),m.push({role:"assistant",content:R});break}continue}let f=k[0],v=f.function.name,S;try{S=JSON.parse(f.function.arguments),this.log(_.gray(`[DEBUG] Tool: ${v}`)),this.log(_.gray(`[DEBUG] Raw arguments: ${f.function.arguments.substring(0,200)}${f.function.arguments.length>200?"...":""}`)),this.log(_.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(v)){let R=a(f);R&&(this.log(_.cyan(`\u{1F4AD} Think: ${R}`)),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(v)){let R=l(f);if(R){let{answer:oe,success:te}=R;if(n?.finalAnswerCallback)try{await n.finalAnswerCallback(oe,n)}catch(z){Y(`Error in finalAnswerCallback: ${z}`)}let on=te?"\u2705":"\u26A0\uFE0F";this.log(_.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[v]){let R=`Error: Unknown tool '${v}'`;this.error(R),m.push({role:"assistant",content:null,tool_calls:[f]}),m.push({role:"tool",tool_call_id:f.id,content:R});continue}let b=u().find(R=>R.name===v);if(b&&b.input_schema&&b.input_schema.required){let R=b.input_schema.required||[],oe=R.filter(te=>S[te]===void 0);if(oe.length>0){let te=`Error: Missing required parameters: ${oe.join(", ")}
2778
+ `,n+=l,L("\u5DF2\u52A0\u8F7D\u9879\u76EE\u6587\u6863\u805A\u5408\u5185\u5BB9"))}catch(l){S(`\u52A0\u8F7D\u9879\u76EE\u6587\u6863\u5931\u8D25: ${l.message}`)}n&&this.orchestratorContext.updateSharedState("rules",n)}catch{S("\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)}S("\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(J.gray(`\u63CF\u8FF0: ${n.description}`)),this.log("");try{let a=[{role:"system",content:await Tn},...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()-s;this.subAgentManager.recordAgentPerformance(n.name,!0,u)}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 r=[{role:"system",content:await Tn},...t.filter(s=>s.role!=="system"),...t.filter(s=>s.role==="system")];await this.runWorkerLoop(r,e)}async runWorkerLoop(e,t,n=null){let{MODEL:r}=await Promise.resolve().then(()=>(ee(),en)),{callModelAPI:s}=await Promise.resolve().then(()=>(Ce(),kn)),{isThinkTool:i,extractThought:a}=await Promise.resolve().then(()=>(Vr(),_i)),{isFinishTool:c,extractFinishInfo:l}=await Promise.resolve().then(()=>(Ds(),ya)),{getToolDefinitions:u}=await Promise.resolve().then(()=>(Pn(),Sa)),{tools:p,toolInstances:g,extractToolResult:d}=await Promise.resolve().then(()=>(Ke(),ro)),m=[...e],f=0,x=50;for(;f<x;){f++;try{xe(m,t);let w=await s({model:r(),messages:m,temperature:.1,tools:u()}),v=w.choices[0].message.tool_calls;if(w.choices[0].finish_reason==="stop"){let{content:I}=w.choices[0].message;if(I&&I.trim()){if(n?.finalAnswerCallback)try{await n.finalAnswerCallback(I,n)}catch(z){ne(`Error in finalAnswerCallback: ${z}`)}this.log(J.green("\u4EFB\u52A1\u5B8C\u6210:")),this.log(I),this.log("")}break}if(!v||v.length===0){let{content:I}=w.choices[0].message;if(I&&I.trim()){if(n?.finalAnswerCallback)try{await n.finalAnswerCallback(I,n)}catch(z){ne(`Error in finalAnswerCallback: ${z}`)}this.log(J.green("\u4EFB\u52A1\u5B8C\u6210:")),this.log(I),this.log(""),m.push({role:"assistant",content:I});break}continue}let h=v[0],y=h.function.name,T;try{T=JSON.parse(h.function.arguments),this.log(J.gray(`[DEBUG] Tool: ${y}`)),this.log(J.gray(`[DEBUG] Raw arguments: ${h.function.arguments.substring(0,200)}${h.function.arguments.length>200?"...":""}`)),this.log(J.gray(`[DEBUG] Parsed keys: ${Object.keys(T).join(", ")}`)),this.log("")}catch{this.error(`\u89E3\u6790\u5DE5\u5177\u53C2\u6570\u5931\u8D25: ${h.function.arguments}`),m.push({role:"assistant",content:null,tool_calls:[h]}),m.push({role:"tool",tool_call_id:h.id,content:"Error: Invalid JSON arguments"});continue}if(i(y)){let I=a(h);I&&(this.log(J.cyan(`\u{1F4AD} Think: ${I}`)),this.log("")),m.push({role:"assistant",content:null,tool_calls:[h]}),m.push({role:"tool",tool_call_id:h.id,content:"Noted. Continue with your action."});continue}if(c(y)){let I=l(h);if(I){let{answer:z,success:le}=I;if(n?.finalAnswerCallback)try{await n.finalAnswerCallback(z,n)}catch(X){ne(`Error in finalAnswerCallback: ${X}`)}let Kn=le?"\u2705":"\u26A0\uFE0F";this.log(J.green(`${Kn} \u4EFB\u52A1\u5B8C\u6210 (\u901A\u8FC7 finish \u5DE5\u5177):`)),this.log(z),this.log(""),m.push({role:"assistant",content:null,tool_calls:[h]}),m.push({role:"tool",tool_call_id:h.id,content:"Task completed successfully."}),m.push({role:"assistant",content:z});break}}if(!p[y]){let I=`Error: Unknown tool '${y}'`;this.error(I),m.push({role:"assistant",content:null,tool_calls:[h]}),m.push({role:"tool",tool_call_id:h.id,content:I});continue}let P=u().find(I=>I.name===y);if(P&&P.input_schema&&P.input_schema.required){let I=P.input_schema.required||[],z=I.filter(le=>T[le]===void 0);if(z.length>0){let le=`Error: Missing required parameters: ${z.join(", ")}
1917
2779
 
1918
- Tool: ${v}
1919
- Required parameters: ${R.join(", ")}
1920
- Provided parameters: ${Object.keys(S).join(", ")||"none"}
2780
+ Tool: ${y}
2781
+ Required parameters: ${I.join(", ")}
2782
+ Provided parameters: ${Object.keys(T).join(", ")||"none"}
1921
2783
 
1922
- 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 L=g[v],M=L?L.formatAction(S):`${v}()`;this.log(_.blue(`\u{1F527} \u884C\u52A8: ${M}`)),this.log("");let I=await p[v](S),q=d(I),Q=L?L.shouldPrintObservation(I):!0,J=L?L.formatObservation(I):String(I);Q&&(this.log(_.yellow(`\u{1F4CA} \u89C2\u5BDF: ${J}`)),this.log("")),m.push({role:"assistant",content:null,tool_calls:[f]}),m.push({role:"tool",tool_call_id:f.id,content:String(q)}),["read","write","merge"].includes(v)&&S.path&&this.orchestratorContext.addRecentFile(S.path),ce(m,t)}catch(x){throw this.error(`\u9519\u8BEF: ${x.message}`),ce(m,t),x}}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;this.options.useLLMSummary?n=await this.summaryExtractor.extractSummaryWithLLM(t):n=await this.summaryExtractor.extractSummary(t);let r=this.summaryExtractor.extractMetadata(t);r.success=!0,this.orchestratorContext.recordStepCompletion(e,n,r),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(_.gray("\u2500\u2500\u2500 \u6B65\u9AA4\u6267\u884C\u6458\u8981 \u2500\u2500\u2500")),this.log(_.gray(`\u6458\u8981: ${n}`)),this.log(_.gray(`\u5DE5\u5177: ${r.toolsUsed.join(", ")}`)),this.log(_.gray(`\u6587\u4EF6: ${r.filesAccessed.join(", ")}`)),this.log(_.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(`
1923
- `)}formatProjectStructureInfo(e){return tr(e,{format:"markdown",detailed:!0,customTitle:`# \u9879\u76EE\u7ED3\u6784\u4FE1\u606F
1924
- `})}}});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(`
1925
- `);for(let r of n)if(r.startsWith("USE_LLM_DISCLOSURE=")){let s=r.split("=")[1]?.trim()||"";C(`[\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()||"";C(`[\u914D\u7F6E\u8BFB\u53D6] \u4ECE .nium/.env \u6587\u4EF6\u4E2D\u8BFB\u53D6: USE_LLM_SUMMARY=${s}`),o.useLLMSummary=s.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}`),o.useLLMDisclosure=_s("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}`),o.useLLMSummary=_s("USE_LLM_SUMMARY")),o}async function wi(){try{let o=Np();return $("[\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 Y(`[\u914D\u7F6E\u8BFB\u53D6] \u914D\u7F6E\u8BFB\u53D6\u51FA\u9519: ${o}`),o}}var Tl=y(()=>{bl();vi();K();Ns()});var Pl={};O(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(),T.sessionId&&(e.log(A.gray(`\u5F53\u524D\u4F1A\u8BDD ID: ${T.sessionId.substring(0,8)}`)),T.tasks&&T.tasks.length>0&&e.log(A.gray(`\u5F53\u524D\u4F1A\u8BDD\u4EFB\u52A1\u6570: ${T.tasks.length}`)),e.log())}catch(t){throw e.error(`\u4EFB\u52A1\u5904\u7406\u5931\u8D25: ${t.message}`),t}}async function Vp(o){if(T.messages&&T.messages.length>0&&T.currentTask){o.log(),o.info(`\u6B63\u5728\u6062\u590D\u4F1A\u8BDD [ID:${T.sessionId?T.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"),T.sessionId&&(o.log(A.gray(`\u4F1A\u8BDD ID: ${T.sessionId.substring(0,8)}`)),T.tasks&&T.tasks.length>0&&o.log(A.gray(`\u4F1A\u8BDD\u4EFB\u52A1\u6570: ${T.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 Wp(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)+`
1926
- ...(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
2784
+ Please call the tool again with ALL required parameters.`;this.error(le),m.push({role:"assistant",content:null,tool_calls:[h]}),m.push({role:"tool",tool_call_id:h.id,content:le});continue}}let b=g[y],M=b?b.formatAction(T):`${y}()`;this.log(J.blue(`\u884C\u52A8: ${M}`)),this.log("");let D=await p[y](T),j=d(D),R=b?b.shouldPrintObservation(D):!0,A=b?b.formatObservation(D):String(D);R&&(this.log(J.yellow(`\u89C2\u5BDF: ${A}`)),this.log("")),m.push({role:"assistant",content:null,tool_calls:[h]}),m.push({role:"tool",tool_call_id:h.id,content:String(j)}),["read","write","merge"].includes(y)&&T.path&&this.orchestratorContext.addRecentFile(T.path),xe(m,t)}catch(w){throw this.error(`\u9519\u8BEF: ${w.message}`),xe(m,t),w}}if(f>=x)throw this.error("\u9519\u8BEF: \u5DF2\u8FBE\u5230\u6700\u5927\u8FED\u4EE3\u6B21\u6570"),xe(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(J.gray("\u2500\u2500\u2500 \u6B65\u9AA4\u6267\u884C\u6458\u8981 \u2500\u2500\u2500")),this.log(J.gray(`\u6458\u8981: ${n}`)),this.log(J.gray(`\u5DE5\u5177: ${r.toolsUsed.join(", ")}`)),this.log(J.gray(`\u6587\u4EF6: ${r.filesAccessed.join(", ")}`)),this.log(J.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(`
2785
+ `)}formatProjectStructureInfo(e){return qr(e,{format:"markdown",detailed:!0,customTitle:`# \u9879\u76EE\u7ED3\u6784\u4FE1\u606F
2786
+ `})}},Ha=null});import{readFileSync as hf}from"fs";import{join as yf}from"path";function xf(){let o={useLLMDisclosure:!0,useLLMSummary:!0};try{let e=yf(process.cwd(),".nium",".env"),n=hf(e,"utf-8").split(`
2787
+ `);for(let r of n)if(r.startsWith("USE_LLM_DISCLOSURE=")){let s=r.split("=")[1]?.trim()||"";S(`[\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()||"";S(`[\u914D\u7F6E\u8BFB\u53D6] \u4ECE .nium/.env \u6587\u4EF6\u4E2D\u8BFB\u53D6: USE_LLM_SUMMARY=${s}`),o.useLLMSummary=s.toLowerCase()==="true"}}catch(e){S(`[\u914D\u7F6E\u8BFB\u53D6] \u65E0\u6CD5\u8BFB\u53D6 .nium/.env \u6587\u4EF6: ${e.message}`)}return process.env.USE_LLM_DISCLOSURE!==void 0&&(S(`[\u914D\u7F6E\u8BFB\u53D6] \u4ECE\u73AF\u5883\u53D8\u91CF\u4E2D\u8BFB\u53D6: USE_LLM_DISCLOSURE=${process.env.USE_LLM_DISCLOSURE}`),o.useLLMDisclosure=ta("USE_LLM_DISCLOSURE")),process.env.USE_LLM_SUMMARY!==void 0&&(S(`[\u914D\u7F6E\u8BFB\u53D6] \u4ECE\u73AF\u5883\u53D8\u91CF\u4E2D\u8BFB\u53D6: USE_LLM_SUMMARY=${process.env.USE_LLM_SUMMARY}`),o.useLLMSummary=ta("USE_LLM_SUMMARY")),o}async function Va(){try{let o=xf();return L("[\u914D\u7F6E\u8BFB\u53D6] \u4F7F\u7528\u4E3B\u667A\u80FD\u4F53\uFF08\u4E0A\u4E0B\u6587\u9694\u79BB\u6A21\u5F0F\uFF09"),{executeMasterAgent:Cp,MasterAgent:ko,config:o}}catch(o){throw ne(`[\u914D\u7F6E\u8BFB\u53D6] \u914D\u7F6E\u8BFB\u53D6\u51FA\u9519: ${o}`),o}}var wp=C(()=>{Sp();Wa();V();na()});var Ga={};_(Ga,{COMMANDS:()=>$o,executeCommand:()=>Ut,findCommand:()=>vp,getAvailableCommands:()=>Wt,initializeDynamicCommands:()=>kf,printCommandHelp:()=>Ba});import F from"chalk";async function Cf(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 Va();await t(o,!1,e,n),e.log(),E.sessionId&&(e.log(F.gray(`\u5F53\u524D\u4F1A\u8BDD ID: ${E.sessionId.substring(0,8)}`)),E.tasks&&E.tasks.length>0&&e.log(F.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 Sf(o){if(E.messages&&E.messages.length>0&&E.currentTask){o.log(),o.info(`\u6B63\u5728\u6062\u590D\u4F1A\u8BDD [ID:${E.sessionId?E.sessionId.substring(0,8):"unknown"}]...`),o.log();try{let{executeMasterAgent:e,config:t}=await Va();await e(null,!0,o,t),o.log(),o.success("\u4F1A\u8BDD\u6062\u590D\u5B8C\u6210"),E.sessionId&&(o.log(F.gray(`\u4F1A\u8BDD ID: ${E.sessionId.substring(0,8)}`)),E.tasks&&E.tasks.length>0&&o.log(F.gray(`\u4F1A\u8BDD\u4EFB\u52A1\u6570: ${E.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 wf(o){Tt(),o.success("\u4F1A\u8BDD\u5DF2\u5F52\u6863\u5E76\u6E05\u7A7A"),o.log()}function bf(o){let e=Sc();o.log(e)}function bp(o){o.exit()}function vf(o){o.printHelp&&o.printHelp()}function Tf(o){o.log(),o.log(F.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(F.cyan(" \u{1F4E6} Available Tools ")),o.log(F.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=Hn(),t=cp();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(F.bold("\u{1F4CA} Summary:")),o.log(F.gray(` Total Tools: ${t.total}`)),o.log(F.gray(` Local Tools: ${t.local}`)),o.log(F.gray(` MCP Tools: ${t.mcp}`)),o.log(),t.local>0){o.log(F.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(F.green(` \u2022 ${i.name}`)),o.log(F.gray(` ${i.description}`)),o.log()}}}if(t.mcp>0){o.log(F.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(F.magenta(` \u2022 ${i.name}`)),o.log(F.gray(` ${l}`)),o.log(F.gray(` (from MCP server: ${c})`)),o.log()}}}o.log(F.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 Pf(o){o.log(),o.info("\u6B63\u5728\u68C0\u67E5git\u53D8\u66F4...");try{if(!Zr()){o.warning("\u6CA1\u6709\u672A\u63D0\u4EA4\u7684\u53D8\u66F4"),o.log();return}let e=Yr(),t=Qr();o.log(),o.info("\u5F53\u524Dgit\u72B6\u6001:"),o.log(F.gray(e)),o.log();let n=t.length>500?t.substring(0,500)+`
2788
+ ...(truncated)`:t;o.info("\u53D8\u66F4\u5185\u5BB9\u9884\u89C8:"),o.log(F.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
1927
2789
  \u8BF7\u6839\u636E\u63D0\u4F9B\u7684git diff\u5185\u5BB9\uFF0C\u751F\u6210\u4E00\u4E2A\u7B80\u6D01\u660E\u4E86\u7684commit message\u3002
1928
2790
 
1929
2791
  \u8981\u6C42\uFF1A
@@ -1940,9 +2802,11 @@ feat: \u6DFB\u52A0\u7528\u6237\u8BA4\u8BC1\u529F\u80FD
1940
2802
  - \u6DFB\u52A0\u767B\u5F55\u548C\u6CE8\u518C\u63A5\u53E3
1941
2803
  - \u66F4\u65B0\u7528\u6237\u6A21\u578B`},{role:"user",content:`\u8BF7\u4E3A\u4EE5\u4E0Bgit\u53D8\u66F4\u751F\u6210commit message:
1942
2804
 
1943
- ${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+`
2805
+ ${t}`}],i=await B({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+`
1944
2806
 
1945
- [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 ."),Vs(),o.success("\u5DF2\u6682\u5B58\u6240\u6709\u53D8\u66F4"),o.info("\u6B63\u5728\u6267\u884C git commit..."),Ws(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=y(()=>{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:Vp,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:Wp,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();K();le();di();xr();Eo();import ae from"chalk";import we from"readline";import Kp from"fuzzysort";var $l="0.1.10";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(),$("\u4EA4\u4E92\u5F0F\u4F1A\u8BDD\u542F\u52A8"),this.debug&&(C("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()&&T.messages&&T.messages.length>0&&T.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($(`Loaded ${e.length} MCP server configuration(s)`),e.length===0){C("No MCP servers configured"),await Mo();return}let t=Zt();$("Initializing MCP manager with configured servers..."),await t.initialize(e),$("Loading all tools (local + MCP)..."),await Mo();let n=t.getStatus();C(`MCP Status: ${n.serversConnected} servers connected, ${n.toolsAvailable} tools available`),n.serversConnected>0?j(`Connected to ${n.serversConnected} MCP server(s), ${n.toolsAvailable} tools available`,"MCP"):N(`Configured ${e.length} MCP server(s) but none connected`,"MCP")}catch(e){Y(`Failed to initialize MCP: ${e.message}`),C(`MCP initialization error details: ${e.message}
1946
- ${e.stack||""}`),$("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(`
1947
- 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(`
1948
- \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){j(e,null)}warning(e){N(e,null)}error(e){ke(e,null)}info(e){se(e,null)}exit(){$("\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();
2807
+ [Generated by niumagents]`;o.success("\u751F\u6210\u7684commit message:"),o.log(F.cyan("\u2500".repeat(50))),o.log(F.white(c)),o.log(F.cyan("\u2500".repeat(50))),o.log(),o.info("\u6B63\u5728\u6267\u884C git add ."),oa(),o.success("\u5DF2\u6682\u5B58\u6240\u6709\u53D8\u66F4"),o.info("\u6B63\u5728\u6267\u884C git commit..."),sa(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 Ef(o,e){o.warning(`\u672A\u77E5\u547D\u4EE4: /${e}`);let t=$o.map(n=>`/${n.name}`).join(", ");o.log(F.gray(`\u53EF\u7528\u547D\u4EE4: ${t}`))}function vp(o){return $o.find(e=>e.name===o)||null}async function Ut(o,e,t=""){let n=vp(e);if(!n){Ef(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 Wt(){return[...$o]}function Ba(o){o.log(F.cyan("\u53EF\u7528\u547D\u4EE4:")),$o.forEach(e=>{let t=e.requiresArg?`/${e.name} <\u53C2\u6570>`:`/${e.name}`;o.log(` ${F.white(t)} - ${F.gray(e.description)}`)}),o.log(),o.log(F.gray("\u63D0\u793A: \u76F4\u63A5\u8F93\u5165\u5185\u5BB9\u5C06\u4F5C\u4E3A\u4EFB\u52A1\u8BF7\u6C42\u53D1\u9001")),o.log()}async function kf(){try{let{isGitAvailable:o}=await Promise.resolve().then(()=>(Cs(),pu)),e=o();console.log(F.gray(`Git\u73AF\u5883\u68C0\u67E5: ${e?"\u53EF\u7528":"\u4E0D\u53EF\u7528"}`)),console.log(e?F.green("\u2713 /commit \u547D\u4EE4\u53EF\u7528"):F.yellow("\u26A0 Git\u4E0D\u53EF\u7528\uFF0C/commit \u547D\u4EE4\u5C06\u4E0D\u53EF\u7528"))}catch(o){console.log(F.gray(`\u521D\u59CB\u5316\u52A8\u6001\u547D\u4EE4\u65F6\u51FA\u9519: ${o.message}`))}}var $o,Io=C(()=>{Ve();li();wp();Vn();Cs();Ce();$o=[{name:"chat",description:"\u5F00\u59CB\u65B0\u4EFB\u52A1",handler:Cf,requiresArg:!0},{name:"resume",description:"\u6062\u590D\u4E2D\u65AD\u7684\u4F1A\u8BDD",handler:Sf,requiresArg:!1},{name:"commit",description:"\u4F7F\u7528AI\u603B\u7ED3\u53D8\u66F4\u5E76\u63D0\u4EA4git commit",handler:Pf,requiresArg:!1},{name:"clear",description:"\u5F52\u6863\u5E76\u6E05\u7A7A\u5F53\u524D\u4F1A\u8BDD",handler:wf,requiresArg:!1},{name:"history",description:"\u67E5\u770B\u5F52\u6863\u4F1A\u8BDD",handler:bf,requiresArg:!1},{name:"list_tools",description:"\u5217\u51FA\u6240\u6709\u53EF\u7528\u5DE5\u5177",handler:Tf,requiresArg:!1},{name:"exit",description:"\u9000\u51FA\u5E94\u7528",handler:bp,requiresArg:!1},{name:"quit",description:"\u9000\u51FA\u5E94\u7528",handler:bp,requiresArg:!1},{name:"help",description:"\u663E\u793A\u5E2E\u52A9\u4FE1\u606F",handler:vf,requiresArg:!1}]});He();Ve();Io();V();ee();To();Vn();Ns();import he from"chalk";import De from"readline";import $f from"fuzzysort";var Mo="0.1.12";var Gn=Wt(),Ks=class{rl=null;isActive=!1;commandHistory=[];historyIndex=-1;debug=!1;skipLineProcessing=!1;lastExecutedCommand=null;constructor(e={}){this.debug=e.debug||!1,Kt(this.debug),Xn(this.debug)}async start(){try{if(!he)throw new Error("chalk\u6A21\u5757\u5BFC\u5165\u5931\u8D25");Do(),qt(),L("\u4EA4\u4E92\u5F0F\u4F1A\u8BDD\u542F\u52A8"),this.debug&&(S("Debug\u6A21\u5F0F\u5DF2\u542F\u7528"),We("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(()=>(Io(),Ga));await e(),this.rl=De.createInterface({input:process.stdin,output:process.stdout,prompt:he.blue("nium> "),historySize:100,completer:()=>[[],""]}),Ou(this.rl),process.stdin.isTTY&&(process.stdin.setRawMode(!0),this.setupKeypressHandling()),this.printWelcome(),ar()&&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=lr();if(L(`Loaded ${e.length} MCP server configuration(s)`),e.length===0){S("No MCP servers configured"),await dt();return}let t=Ne();L("Initializing MCP manager with configured servers..."),await t.initialize(e),L("Loading all tools (local + MCP)..."),await dt();let n=t.getStatus();S(`MCP Status: ${n.serversConnected} servers connected, ${n.toolsAvailable} tools available`),n.serversConnected>0?W(`Connected to ${n.serversConnected} MCP server(s), ${n.toolsAvailable} tools available`,"MCP"):O(`Configured ${e.length} MCP server(s) but none connected`,"MCP")}catch(e){ne(`Failed to initialize MCP: ${e.message}`),S(`MCP initialization error details: ${e.message}
2808
+ ${e.stack||""}`),L("Continuing with local tools only..."),await dt()}}setupKeypressHandling(){De.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?$f.go(n,Gn,{key:"name"}):Gn.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++)De.moveCursor(process.stdout,0,-1),De.clearLine(process.stdout,0);De.clearLine(process.stdout,1),console.log(""),console.log(he.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?he.green("> "):" ",d=p?he.green.bold(`/${u.name}`):he.white(`/${u.name}`),m=he.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++)De.moveCursor(process.stdout,0,-1),De.clearLine(process.stdout,0);return De.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++)De.moveCursor(process.stdout,0,-1),De.clearLine(process.stdout,0);return this.rl.removeListener("keypress",c),De.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(Gn=Wt(),!(r?Gn.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 Ut(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 Ut(this,"chat",e)}catch(t){this.error(`\u6267\u884C\u4EFB\u52A1\u65F6\u51FA\u9519: ${t.message}`)}}printWelcome(){Gn=Wt(),this.clear(),this.log(he.green(`NiumAgents-CLI v${Mo}`)),this.log(he.gray("Options:")),this.log(he.gray(" --debug - \u542F\u7528\u8C03\u8BD5\u6A21\u5F0F\u4EE5\u663E\u793A\u8BE6\u7EC6\u65E5\u5FD7")),this.log(he.gray(`
2809
+ Commands:`)),this.log(he.gray(" <request> - \u5F00\u59CB\u65B0\u4EFB\u52A1 (\u9ED8\u8BA4: /chat)"));let e=Gn.filter(t=>t.name!=="chat");for(let t of e)t.name==="exit"||t.name==="quit"?t.name==="exit"&&this.log(he.gray(" /exit \u6216 /quit - \u9000\u51FA")):this.log(he.gray(` /${t.name} - ${t.description}`));this.log(he.gray(`
2810
+ \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(){Ba(this)}clear(){Qs()}log(e=""){Qn(e)}success(e){W(e,null)}warning(e){O(e,null)}error(e){ie(e,null)}info(e){me(e,null)}exit(){L("\u4EA4\u4E92\u5F0F\u4F1A\u8BDD\u7ED3\u675F"),this.isActive=!1,this.rl&&this.rl.close()}};import eh from"react";import{render as th}from"ink";import{useState as wt,useEffect as Jf,useCallback as Dp}from"react";import{Box as Fp,useApp as qf,useInput as Kf}from"ink";import{EventEmitter as Xf}from"events";import{Box as yt,Text as we}from"ink";var Qe=class{static formatMCPStatus(e){let{serversConnected:t,totalServers:n,toolsAvailable:r,servers:s}=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=s.filter(l=>!l.connected).map(l=>l.name).slice(0,2).join(", "),a=s.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:s,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}`}};import{Fragment as Tp,jsx as be,jsxs as Ue}from"react/jsx-runtime";var If=({version:o,sessionStatus:e,mcpStatus:t,debug:n,focusedArea:r="input",cwd:s,isLoading:i=!1})=>{let a=Qe.getFocusIcon(r),c=r==="content"?"yellow":"green",l=r==="content"?"\u6D4F\u89C8\u6A21\u5F0F":"\u8F93\u5165\u6A21\u5F0F",u=Qe.getMCPStatusColor(t),p=Qe.getSessionStatusColor(e);return Ue(yt,{flexDirection:"column",children:[Ue(yt,{borderStyle:"round",borderColor:r==="content"?"yellow":"blue",paddingX:1,flexDirection:"row",justifyContent:"space-between",children:[Ue(yt,{children:[be(we,{bold:!0,color:"blue",children:Qe.formatVersion(o,n)}),i&&Ue(we,{color:"green",children:[" ","\u23F3"]})]}),Ue(yt,{children:[be(we,{dimColor:!0,children:"\u4F1A\u8BDD: "}),be(we,{color:p,children:Qe.formatSessionStatusShort(e)}),be(we,{dimColor:!0,children:" | "}),be(we,{dimColor:!0,children:"MCP: "}),be(we,{color:u,children:Qe.formatMCPStatusShort(t)}),n&&Ue(Tp,{children:[be(we,{dimColor:!0,children:" | "}),be(we,{color:"yellow",children:"DEBUG"})]})]})]}),Ue(yt,{borderStyle:"single",borderColor:c,paddingX:1,marginTop:0,flexDirection:"row",justifyContent:"space-between",children:[Ue(yt,{children:[Ue(we,{color:c,bold:!0,children:[a," ",l]}),be(we,{dimColor:!0,children:r==="content"?" (\u2191\u2193\u6D4F\u89C8 PgUp/PgDn\u7FFB\u9875 Home/End\u5230\u5934\u5C3E Esc\u8FD4\u56DE)":" (Ctrl+L\u8FDB\u5165\u6D4F\u89C8\u6A21\u5F0F)"})]}),be(yt,{children:s&&Ue(Tp,{children:[be(we,{dimColor:!0,children:"\u{1F4C1} "}),be(we,{color:"cyan",children:s})]})})]}),i&&be(yt,{borderStyle:"single",borderColor:"green",paddingX:1,marginTop:0,children:be(we,{color:"green",bold:!0,children:"\u23F3 \u6B63\u5728\u5904\u7406\u547D\u4EE4..."})})]})},Pp=If;import{useEffect as Ja,useState as Xs,useRef as $p,useMemo as qa}from"react";import{Box as xt,Text as Me,useInput as jf}from"ink";import Df from"ink-spinner";import{createContext as Mf,useContext as Af,useState as Rf}from"react";import{jsx as Lf}from"react/jsx-runtime";var Ep=Mf(void 0),Jn=()=>{let o=Af(Ep);if(!o)throw new Error("useFocus must be used within FocusProvider");return o},kp=({children:o})=>{let[e,t]=Rf("input"),n=r=>{t(r)};return Lf(Ep.Provider,{value:{focusedArea:e,setFocus:n},children:o})};import{jsx as ke,jsxs as Ct}from"react/jsx-runtime";var Ff=({output:o,isLoading:e})=>{let{focusedArea:t}=Jn(),[n,r]=Xs(0),[s,i]=Xs(!1),[a,c]=Xs(!1),[l,u]=Xs(0),p=$p(process.stdout.rows||24),g=$p(null),d=qa(()=>Math.max(1,p.current-11),[p.current]),m=qa(()=>Math.max(0,o.length-d),[o.length,d]);Ja(()=>{let x=()=>{let w=p.current;p.current=process.stdout.rows||24;let v=p.current-w;if(Math.abs(v)>0)if(!s||n>=m-1){let h=Math.max(0,o.length-(p.current-11));r(h),i(!1)}else{let h=n/Math.max(1,m),y=Math.max(0,o.length-(p.current-11)),T=Math.floor(h*y);r(Math.max(0,Math.min(T,y)))}};return process.stdout.on("resize",x),()=>{process.stdout.off("resize",x)}},[o.length,s,n,m]),Ja(()=>{if(!s&&!a){let x=Math.max(0,o.length-d);x!==n&&r(x)}},[o,d,s,a,n]),Ja(()=>(a&&(g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{c(!1),u(0)},500)),()=>{g.current&&clearTimeout(g.current)}),[a]),jf((x,w)=>{if(t!=="content"||o.length<=d)return;let v=n,h=1,y=!1;if((w.ctrl||w.meta)&&(h=w.upArrow||w.downArrow?5:h),w.upArrow?(v=Math.max(0,n-h),y=!0):w.downArrow&&(v=Math.min(m,n+h),y=!0,v===m&&(i(!1),y=!1)),w.pageUp?(v=Math.max(0,n-Math.floor(d*.9)),y=!0):w.pageDown&&(v=Math.min(m,n+Math.floor(d*.9)),y=!0,v===m&&(i(!1),y=!1)),typeof w=="object"&&w!==null){let T=w;T.home?(v=0,y=!0):T.end&&(v=m,i(!1),y=!1)}v!==n&&(r(v),c(!0),y&&i(!0),g.current&&clearTimeout(g.current))});let f=qa(()=>o.slice(n,n+d),[o,n,d]);return Ct(xt,{flexDirection:"column",overflow:"hidden",borderStyle:t==="content"?"double":"single",borderColor:t==="content"?"yellow":"gray",paddingX:0,children:[t==="content"&&Ct(xt,{paddingX:1,borderColor:"yellow",borderStyle:"single",justifyContent:"space-between",children:[ke(Me,{color:"yellow",bold:!0,children:"\u{1F4D6} \u6D4F\u89C8\u6A21\u5F0F"}),ke(Me,{color:"gray",dimColor:!0,children:o.length>0?`${n+1}-${Math.min(n+d,o.length)}/${o.length} \u884C`:"\u6682\u65E0\u5185\u5BB9"})]}),Ct(xt,{flexDirection:"column",paddingX:1,paddingY:0,height:d,overflow:"hidden",children:[o.length===0&&!e&&Ct(xt,{flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",children:[ke(Me,{dimColor:!0,color:"gray",children:"\u{1F4DD} \u7B49\u5F85\u547D\u4EE4\u8F93\u5165..."}),ke(Me,{dimColor:!0,color:"gray",children:"\u8F93\u5165\u4EFB\u52A1\u63CF\u8FF0\u6216 /help \u5F00\u59CB\u4F7F\u7528"})]}),o.length>0&&f.map((x,w)=>{let v=n+w,h=v===0&&n===0,y=v===o.length-1;return Ct(xt,{width:"100%",children:[h&&ke(Me,{dimColor:!0,color:"yellow",children:"\u25BC "}),ke(Me,{children:x}),y&&ke(Me,{dimColor:!0,color:"yellow",children:" \u25B2"})]},`line-${v}`)}),e&&Ct(xt,{flexDirection:"row",alignItems:"center",children:[ke(Me,{color:"green",children:ke(Df,{type:"dots"})}),ke(Me,{color:"green",children:" \u6B63\u5728\u5904\u7406..."})]}),o.length>d&&ke(xt,{marginTop:1,children:Ct(Me,{dimColor:!0,color:"gray",children:[n===0&&"\u25BC \u5F00\u59CB",n>0&&n<m&&"\u25B2\u25BC \u6EDA\u52A8\u4E2D",n===m&&"\u25B2 \u7ED3\u675F"," \u2022 ",Math.round(n/Math.max(1,m)*100),"% \u4F4D\u7F6E"," \u2022 ","\u6309\u4EFB\u610F\u65B9\u5411\u952E\u6EDA\u52A8"]})})]}),t==="content"&&o.length>0&&Ct(xt,{paddingX:1,borderColor:"yellow",borderStyle:"single",justifyContent:"space-between",children:[ke(Me,{dimColor:!0,color:"gray",children:"\u2191\u2193: \u9010\u884C | Ctrl+\u2191\u2193: \u5FEB\u901F | PgUp/PgDn: \u7FFB\u9875 | Home/End: \u8DF3\u8F6C"}),ke(Me,{dimColor:!0,color:"gray",children:"Esc: \u8FD4\u56DE\u8F93\u5165"})]})]})},Ip=Ff;import{useState as St,useEffect as Mp}from"react";import{Box as ye,Text as K,useInput as Of}from"ink";import _f from"ink-text-input";import Nf from"fuzzysort";import{Fragment as Wf,jsx as oe,jsxs as Q}from"react/jsx-runtime";var Uf=({commands:o,onCommandSubmit:e,isDisabled:t=!1,askUserRequest:n=null,onAskUserResponse:r})=>{let{focusedArea:s}=Jn(),[i,a]=St(""),[c,l]=St(!1),[u,p]=St([]),[g,d]=St(0),[m,f]=St(0),[x,w]=St([]),[v,h]=St(-1),y=5,[T,P]=St(0),b=()=>{if(n&&r){if(n.choices&&n.choices.length>0){let R=n.choices[T];r(R)}else{let R=i.trim();R&&r(R)}a(""),P(0);return}let j=i.trim();j&&!t&&(w(R=>[...R,j]),h(-1),e(j),a(""),l(!1),d(0),f(0))},M=()=>{if(u.length>0&&c){let j=u[g],R=`/${j.name}${j.requiresArg?" ":""}`;l(!1),d(0),f(0),j.requiresArg?a(R):e(R)}};Mp(()=>{if(i.startsWith("/")){let j=i.slice(1).split(" ")[0];if(j){let A=Nf.go(j,o,{key:"name"}).map(I=>I.obj);p(A),l(A.length>0),d(0),f(0)}else p(o),l(!0),d(0),f(0)}else l(!1)},[i,o]),Mp(()=>{g<m?f(g):g>=m+y&&f(g-y+1)},[g,m,y]),Of((j,R)=>{if(!(s!=="input"||t))if(R.return)b();else if(R.tab)n||M();else if(R.upArrow){if(n&&n.choices&&n.choices.length>0)P(A=>Math.max(0,A-1));else if(c)d(A=>Math.max(0,A-1));else if(x.length>0){let A=v===-1?x.length-1:Math.max(0,v-1);h(A),a(x[A])}}else if(R.downArrow){if(n&&n.choices&&n.choices.length>0)P(A=>Math.min(n.choices.length-1,A+1));else if(c)d(A=>Math.min(u.length-1,A+1));else if(v>=0){let A=v+1;A>=x.length?(h(-1),a("")):(h(A),a(x[A]))}}else R.escape&&(n&&r?(r("__CANCELLED__"),a(""),P(0)):(l(!1),d(0),f(0)))});let D=u.slice(m,m+y);return Q(ye,{flexDirection:"column",children:[n&&Q(ye,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,marginBottom:1,height:n.choices&&n.choices.length>0?8:4,children:[Q(K,{bold:!0,color:"cyan",children:["\u{1F4AC} ",n.question]}),oe(K,{dimColor:!0,children:"\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"}),n.choices&&n.choices.length>0?Q(Wf,{children:[oe(K,{dimColor:!0,children:"(\u2191\u2193\u9009\u62E9, Enter\u786E\u8BA4, Esc\u53D6\u6D88)"}),n.choices.map((j,R)=>Q(K,{color:R===T?"green":"white",bold:R===T,children:[R===T?"> ":" ",j]},`ask-choice-${n.requestId}-${R}`)),n.allowFreeText&&oe(K,{dimColor:!0,children:"\u6216\u76F4\u63A5\u8F93\u5165\u81EA\u5B9A\u4E49\u7B54\u6848"})]}):oe(K,{dimColor:!0,children:"(\u8F93\u5165\u7B54\u6848\u540E\u6309Enter\uFF0CEsc\u53D6\u6D88)"})]}),!n&&c&&u.length>0&&Q(ye,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,marginBottom:1,children:[Q(ye,{flexDirection:"row",justifyContent:"space-between",marginBottom:1,children:[oe(K,{bold:!0,color:"yellow",children:"\u{1F50D} \u547D\u4EE4\u5EFA\u8BAE"}),oe(K,{dimColor:!0,children:"(\u2191\u2193\u9009\u62E9 Tab\u8865\u5168 Esc\u53D6\u6D88)"})]}),Array.from({length:Math.min(y,7)}).map((j,R)=>{let A=m+R,I=u[A];if(I){let z=A===g;return Q(ye,{marginBottom:R<6?0:1,children:[Q(ye,{flexDirection:"row",justifyContent:"space-between",width:"100%",children:[Q(ye,{children:[Q(K,{color:z?"green":"white",bold:z,backgroundColor:z?"black":void 0,children:[z?"\u25B6 ":" ",Q(K,{color:z?"green":"cyan",children:["/",I.name]})]}),I.requiresArg&&Q(K,{dimColor:!0,color:z?"green":"gray",children:[" ","<\u53C2\u6570>"]})]}),I.description&&oe(K,{dimColor:!0,color:z?"greenBright":"gray",children:I.description})]}),z&&I.hint&&Q(K,{dimColor:!0,color:"yellow",children:["\u{1F4A1} ",I.hint]})]},I.name)}else return null}),u.length>Math.min(y,7)&&oe(ye,{flexDirection:"row",justifyContent:"center",marginTop:1,children:Q(K,{dimColor:!0,children:[m>0&&"\u25C0 ",m+1,"-",Math.min(m+Math.min(y,7),u.length)," / ",u.length,m+Math.min(y,7)<u.length&&" \u25B6"]})}),Q(ye,{flexDirection:"row",justifyContent:"space-between",marginTop:1,children:[oe(K,{dimColor:!0,color:"gray",children:"Tab: \u5FEB\u901F\u8865\u5168"}),oe(K,{dimColor:!0,color:"gray",children:"Enter: \u9009\u62E9\u547D\u4EE4"})]})]}),Q(ye,{borderStyle:s==="input"?"double":"single",borderColor:n?"cyan":s==="input"?"green":"gray",paddingX:1,children:[Q(ye,{flexDirection:"row",justifyContent:"space-between",marginBottom:s==="input"?0:-1,children:[Q(ye,{children:[Q(K,{color:n?"cyan":"blue",bold:!0,children:[n?"\u{1F4AC} ":s==="input"?"\u{1F4DD} ":"\u2328\uFE0F ",n?"\u56DE\u7B54> ":"nium> "]}),s!=="input"&&!t&&oe(K,{dimColor:!0,children:" (Ctrl+L\u6FC0\u6D3B\u8F93\u5165)"})]}),Q(ye,{children:[n&&oe(K,{color:"cyan",bold:!0,children:"\u4EA4\u4E92\u6A21\u5F0F"}),s==="input"&&!n&&oe(K,{color:"green",bold:!0,children:"\u8F93\u5165\u6A21\u5F0F"}),s==="content"&&!n&&oe(K,{color:"gray",dimColor:!0,children:"\u6D4F\u89C8\u6A21\u5F0F"})]})]}),oe(ye,{marginLeft:n?2:5,children:oe(_f,{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&&s==="input",focus:s==="input"&&!t},`input-${s}-${c}`)}),s==="input"&&!n&&oe(ye,{marginTop:-1,children:oe(K,{dimColor:!0,color:"gray",children:"\u{1F4A1} \u76F4\u63A5\u8F93\u5165\u4EFB\u52A1\u63CF\u8FF0\u5F00\u59CB\u5BF9\u8BDD\uFF0C\u8F93\u5165 / \u67E5\u770B\u547D\u4EE4"})})]})]})},Ap=Uf;import{useState as zf,useEffect as Hf,useRef as Vf}from"react";import{Box as Rp,Text as zt,useInput as Bf}from"ink";import{jsx as Ht,jsxs as Lp}from"react/jsx-runtime";var Gf=({commands:o,onClose:e})=>{let t=o.filter(p=>["help","clear","resume","history","exit"].includes(p.name)),n=o.filter(p=>!["help","clear","resume","history","exit"].includes(p.name)),[r,s]=zf(0),i=Vf(process.stdout.rows||24),a=i.current-8,c=["","\u2501".repeat(60),"NiumAgents-CLI \u547D\u4EE4\u5E2E\u52A9","(\u6309\u4EFB\u610F\u952E\u8FD4\u56DE, \u2191\u2193\u6EDA\u52A8)","\u2501".repeat(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","","\u2500".repeat(60),"","\u5E38\u7528\u547D\u4EE4:",...t.map(p=>` /${p.name}${p.requiresArg?" <\u53C2\u6570>":""} - ${p.description}`),"","\u2500".repeat(60),"","\u5176\u4ED6\u547D\u4EE4:",...n.map(p=>` /${p.name}${p.requiresArg?" <\u53C2\u6570>":""} - ${p.description}`),"","\u2501".repeat(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);Bf((p,g)=>{g.upArrow?s(d=>Math.max(0,d-1)):g.downArrow?s(d=>Math.min(l,d+1)):g.pageUp?s(d=>Math.max(0,d-a)):g.pageDown&&s(d=>Math.min(l,d+a))}),Hf(()=>{let p=()=>{i.current=process.stdout.rows||24,s(0)};return process.stdout.on("resize",p),()=>{process.stdout.off("resize",p)}},[]);let u=c.slice(r,r+a);return Lp(Rp,{flexDirection:"column",borderStyle:"round",borderColor:"blue",paddingX:1,paddingY:1,height:a,children:[u.map((p,g)=>{let d=`help-line-${r}-${g}`;return p.startsWith("\u2501")?Ht(zt,{color:"blue",children:p},d):p.startsWith("\u2500")?Ht(zt,{color:"gray",children:p},d):p.includes("\u547D\u4EE4\u5E2E\u52A9")||p.includes("\u5E38\u7528\u547D\u4EE4")||p.includes("\u5176\u4ED6\u547D\u4EE4")||p.includes("\u5FEB\u6377\u952E")?Ht(zt,{bold:!0,color:"cyan",children:p},d):p.includes("\u6309\u4EFB\u610F\u952E")||p.includes("\u63D0\u793A:")||p.includes("\u8F93\u5165 /")?Ht(zt,{dimColor:!0,children:p},d):p.includes("Ctrl+")||p.includes("Esc")||p.includes("Tab")||p.includes("\u2191\u2193")?Ht(zt,{color:"yellow",children:p},d):Ht(zt,{children:p},d)}),c.length>a&&Ht(Rp,{marginTop:1,children:Lp(zt,{dimColor:!0,children:["[",r+1,"-",Math.min(r+a,c.length),"/",c.length,"]",r>0&&" \u2191",r<l&&" \u2193"]})})]})},jp=Gf;Ve();To();Io();var se=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(`
2811
+ `)}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"}}},qn={systemError:(o,e)=>new se({type:"SYSTEM_ERROR",message:o,details:e,recoverable:!1,suggestion:"\u8BF7\u68C0\u67E5\u7CFB\u7EDF\u73AF\u5883\u6216\u91CD\u65B0\u542F\u52A8\u5E94\u7528"}),mcpConnectionError:(o,e)=>new se({type:"MCP_CONNECTION_ERROR",message:`\u65E0\u6CD5\u8FDE\u63A5\u5230MCP\u670D\u52A1\u5668: ${o}`,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:(o,e,t)=>new se({type:"MCP_TOOL_ERROR",message:`MCP\u5DE5\u5177\u6267\u884C\u5931\u8D25: ${o}`,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:(o,e)=>new se({type:"SESSION_ERROR",message:o,details:e,recoverable:!0,suggestion:"\u53EF\u4EE5\u5C1D\u8BD5\u4F7F\u7528 /clear \u547D\u4EE4\u5F00\u59CB\u65B0\u4F1A\u8BDD"}),toolNotFoundError:o=>new se({type:"TOOL_NOT_FOUND",message:`\u672A\u627E\u5230\u5DE5\u5177: ${o}`,recoverable:!0,suggestion:"\u4F7F\u7528 /tools \u67E5\u770B\u53EF\u7528\u5DE5\u5177\u5217\u8868"}),toolExecutionError:(o,e)=>new se({type:"TOOL_EXECUTION_ERROR",message:`\u5DE5\u5177\u6267\u884C\u5931\u8D25: ${o}`,details:e,recoverable:!0,suggestion:"\u8BF7\u68C0\u67E5\u5DE5\u5177\u53C2\u6570\u6216\u67E5\u770B\u9519\u8BEF\u8BE6\u60C5"}),invalidCommand:(o,e)=>new se({type:"INVALID_COMMAND",message:`\u672A\u77E5\u547D\u4EE4: ${o}`,recoverable:!0,suggestion:e||"\u4F7F\u7528 /help \u67E5\u770B\u53EF\u7528\u547D\u4EE4"}),invalidArgument:(o,e,t)=>new se({type:"INVALID_ARGUMENT",message:`\u65E0\u6548\u53C2\u6570: ${o} = ${e}`,details:t?`\u671F\u671B\u7C7B\u578B: ${t}`:void 0,recoverable:!0,suggestion:"\u8BF7\u68C0\u67E5\u547D\u4EE4\u53C2\u6570\u683C\u5F0F"}),fileNotFoundError:o=>new se({type:"FILE_NOT_FOUND",message:`\u6587\u4EF6\u672A\u627E\u5230: ${o}`,recoverable:!0,suggestion:"\u8BF7\u68C0\u67E5\u6587\u4EF6\u8DEF\u5F84\u662F\u5426\u6B63\u786E"}),filePermissionError:(o,e)=>new se({type:"FILE_PERMISSION_ERROR",message:`\u6587\u4EF6\u6743\u9650\u4E0D\u8DB3: ${o}`,details:`\u64CD\u4F5C: ${e}`,recoverable:!1,suggestion:"\u8BF7\u68C0\u67E5\u6587\u4EF6\u6743\u9650\u6216\u4F7F\u7528\u5176\u4ED6\u6587\u4EF6"})},Ka={safeExecute:async(o,e,t)=>{try{return{success:!0,result:await o()}}catch(n){return{success:!1,error:n instanceof se?n:qn.systemError(n instanceof Error?n.message:String(n),t)}}},isRecoverable:o=>o instanceof se?o.recoverable:!1,formatError:o=>o instanceof se?o.toDisplayString():`\u26A0\uFE0F ${o.message}`};import{jsx as Vt,jsxs as Zf}from"react/jsx-runtime";var Yf=({debug:o})=>Vt(kp,{children:Vt(Qf,{debug:o})}),Qf=({debug:o})=>{let{exit:e}=qf(),{focusedArea:t,setFocus:n}=Jn(),[r,s]=wt([]),[i,a]=wt([]),[c,l]=wt(!1),[u,p]=wt({status:"inactive"}),[g,d]=wt({serversConnected:0,totalServers:0,toolsAvailable:0,servers:[]}),[m]=wt(process.cwd()),[f,x]=wt(!1),[w,v]=wt(null);Kf((P,b)=>{if(b.ctrl&&P==="l"){n(t==="input"?"content":"input");return}if(b.escape){f?x(!1):t==="content"&&n("input");return}f&&!b.upArrow&&!b.downArrow&&!b.pageUp&&!b.pageDown&&!b.escape&&x(!1)});let h={isActive:!0,clear:()=>{s([])},log:(P="")=>{s(b=>[...b,P])},success:P=>{s(b=>[...b,`\u2705 ${P}`])},warning:P=>{s(b=>[...b,`\u26A0\uFE0F ${P}`])},error:P=>{P.includes(`
2812
+ `)||P.includes("\u8BE6\u60C5:")||P.includes("\u5EFA\u8BAE:")?s(b=>[...b,P]):s(b=>[...b,`\u274C ${P}`])},info:P=>{s(b=>[...b,`\u2139\uFE0F ${P}`])},exit:()=>{e()},printWelcome:()=>{let P=["help","clear","resume","history","exit"],b=i.filter(M=>P.includes(M.name));s([`\u{1F680} NiumAgents-CLI v${Mo}${o?" (DEBUG)":""}`,"","\u2728 \u5FEB\u901F\u5F00\u59CB:"," \u{1F4DD} \u76F4\u63A5\u8F93\u5165\u4EFB\u52A1\u63CF\u8FF0\u5F00\u59CB\u5BF9\u8BDD"," \u{1F50D} \u8F93\u5165 /help \u67E5\u770B\u6240\u6709\u547D\u4EE4"," \u26A1 \u8F93\u5165 / \u89E6\u53D1\u547D\u4EE4\u81EA\u52A8\u8865\u5168"," \u{1F504} \u8F93\u5165 Ctrl+L \u5207\u6362\u6D4F\u89C8\u6A21\u5F0F","","\u{1F6E0}\uFE0F \u5E38\u7528\u547D\u4EE4:",...b.map(M=>` /${M.name}${M.requiresArg?" <\u53C2\u6570>":""} - ${M.description}${M.hint?` (${M.hint})`:""}`),""])},printHelp:()=>{x(!0)}};Jf(()=>{(async()=>{try{let D=Wt();a(D),h.printWelcome(),ar()&&E.messages&&E.messages.length>0&&E.currentTask?(p({status:"pending",currentTask:E.currentTask,messageCount:E.messages.length,sessionId:E.sessionId}),h.warning("\u26A0\uFE0F \u68C0\u6D4B\u5230\u4E4B\u524D\u7684\u4F1A\u8BDD\uFF01\u4F7F\u7528 /resume \u7EE7\u7EED\u6216 /clear \u5F00\u59CB\u65B0\u4F1A\u8BDD\u3002"),h.log()):p({status:"ready"});let A=Ne().getStatus();d({serversConnected:A.serversConnected,totalServers:A.servers.length,toolsAvailable:A.toolsAvailable,servers:A.servers.map(I=>({name:I.name,connected:I.connected,toolsCount:I.toolCount}))})}catch(D){let j=D instanceof se?D:qn.systemError("\u521D\u59CB\u5316\u5931\u8D25",D instanceof Error?D.message:String(D));h.error(Ka.formatError(j)),p({status:"ready"}),d({serversConnected:0,totalServers:0,toolsAvailable:0,servers:[]})}})(),global.__inkAskUserEmitter||(global.__inkAskUserEmitter=new Xf);let b=global.__inkAskUserEmitter,M=D=>{v(D),n("input")};return b.on("askUser",M),()=>{b.off("askUser",M)}},[]);let y=Dp(async P=>{if(P.trim()){l(!0);try{if(P.startsWith("/")){let b=P.slice(1).split(" "),M=b[0],D=b.slice(1).join(" "),j=i.find(R=>R.name===M);if(!j)throw qn.invalidCommand(M,"\u8F93\u5165 /help \u67E5\u770B\u53EF\u7528\u547D\u4EE4");if(j.requiresArg&&!D.trim())throw qn.invalidArgument(M,"missing",j.hint||"\u547D\u4EE4\u53C2\u6570");await Ut(h,M,D)}else await Ut(h,"chat",P);E.sessionId&&p({status:"active",sessionId:E.sessionId,messageCount:E.messages?.length||0,currentTask:E.currentTask})}catch(b){let M=b instanceof se?b:qn.systemError("\u547D\u4EE4\u6267\u884C\u5931\u8D25",b instanceof Error?b.message:String(b));h.error(Ka.formatError(M))}finally{l(!1)}}},[i]),T=Dp(P=>{if(!w)return;let b=global.__inkAskUserEmitter;b&&b.emit(`response_${w.requestId}`,P),v(null)},[w]);return Zf(Fp,{flexDirection:"column",height:"100%",children:[Vt(Pp,{version:Mo,sessionStatus:u,mcpStatus:g,debug:o,focusedArea:t,cwd:m,isLoading:c}),Vt(Fp,{flexGrow:1,flexDirection:"column",children:f?Vt(jp,{commands:i,onClose:()=>x(!1)}):Vt(Ip,{output:r,isLoading:c})}),Vt(Ap,{commands:i,onCommandSubmit:y,isDisabled:c||f,askUserRequest:w,onAskUserResponse:T})]})},Op=Yf;He();V();ee();To();Vn();var Ys=class{debug=!1;constructor(e={}){this.debug=e.debug||!1,Kt(this.debug),Xn(this.debug)}async start(){try{Do(),qt(),this.debug&&We("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(()=>(Io(),Ga));await e(),th(eh.createElement(Op,{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=lr();if(e.length===0){We("No MCP servers configured","MCP"),await dt();return}let t=Ne();await t.initialize(e),await dt();let n=t.getStatus();n.serversConnected>0?W(`Connected to ${n.serversConnected} MCP server(s), ${n.toolsAvailable} tools available`,"MCP"):O(`Configured ${e.length} MCP server(s) but none connected`,"MCP")}catch(e){O(`Failed to initialize MCP: ${e.message}`,"MCP"),await dt()}}};Wi();ee();import ve from"chalk";async function nh(){try{await It.initialize();let o=process.argv.slice(2),e=o.includes("--debug"),t=o.includes("--help")||o.includes("-h"),n=o.includes("--ink");t&&(console.log(ve.green("NiumAgents-CLI v0.1.8")),console.log(ve.gray("AI Code Agent")),console.log(),console.log(ve.gray("Options:")),console.log(ve.gray(" --debug - \u542F\u7528\u8C03\u8BD5\u6A21\u5F0F\u4EE5\u663E\u793A\u8BE6\u7EC6\u65E5\u5FD7")),console.log(ve.gray(" --ink - \u4F7F\u7528Ink\u6846\u67B6\u7684\u73B0\u4EE3\u5316UI (\u5B9E\u9A8C\u6027\u529F\u80FD)")),console.log(ve.gray(" --help \u6216 -h - \u663E\u793A\u6B64\u5E2E\u52A9\u4FE1\u606F")),console.log(),console.log(ve.gray("Usage:")),console.log(ve.gray(" nium [options]")),console.log(ve.gray(" npm run start [options]")),console.log(),console.log(ve.gray("Example:")),console.log(ve.gray(" nium --debug")),console.log(ve.gray(" nium --ink")),console.log(ve.gray(" npm run start -- --debug --ink")),process.exit(0)),n?(console.log(ve.cyan("\u{1F3A8} \u4F7F\u7528Ink\u6846\u67B6UI (\u5B9E\u9A8C\u6027\u529F\u80FD)")),Wo(!0),await new Ys({debug:e}).start()):(Wo(!1),await new Ks({debug:e}).start())}catch(o){console.error("\u542F\u52A8\u5E94\u7528\u65F6\u51FA\u9519:",o.message),process.exit(1)}}nh();