niumagents-cli 0.1.5 → 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/nium.js +204 -162
- package/package.json +6 -6
package/dist/nium.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var oc=Object.defineProperty;var C=(r,e)=>()=>(r&&(e=r(r=0)),e);var U=(r,e)=>{for(var t in e)oc(r,t,{get:e[t],enumerable:!0})};import{existsSync as me,mkdirSync as jt,copyFileSync as Ts,writeFileSync as sc}from"fs";import{join as B,dirname as ks}from"path";import{fileURLToPath as ic}from"url";import q from"chalk";function $s(){let r=[B(Ot,"..","..","examples"),B(Ot,"..","examples"),B(Ot,"examples"),B(Ot,"..","..","..","examples")];for(let e of r)if(me(e))return ks(e);return B(Ot,"..")}function Ps(){return Gr||(Gr=B(process.cwd(),".nium")),Gr}function ac(){if(!qr){let r=$s();qr=B(r,"examples","config.example.json")}return qr}function cc(){if(!zr){let r=$s();zr=B(r,"examples",".env.example")}return zr}function Ms(){let r=Ps(),e=ac();try{if(!me(r)){console.log(q.blue("\u{1F527} \u521D\u59CB\u5316\u5DE5\u4F5C\u76EE\u5F55...")),jt(r,{recursive:!0}),console.log(q.green("\u2713 \u521B\u5EFA .nium \u76EE\u5F55"));let c=B(r,"config.json");me(e)?(Ts(e,c),console.log(q.green("\u2713 \u590D\u5236 config.example.json \u5230 .nium/config.json")),console.log(q.yellow(`
|
|
3
3
|
\u26A0\uFE0F \u8BF7\u7F16\u8F91 .nium/config.json \u6587\u4EF6\u914D\u7F6E API \u5BC6\u94A5\u548C\u6A21\u578B
|
|
4
|
-
`))):(console.log(
|
|
4
|
+
`))):(console.log(q.yellow(`\u26A0\uFE0F \u672A\u627E\u5230 config.example.json: ${e}`)),sc(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)),console.log(q.green("\u2713 \u521B\u5EFA\u9ED8\u8BA4\u7684 .nium/config.json \u6587\u4EF6")),console.log(q.yellow(`
|
|
5
5
|
\u26A0\uFE0F \u8BF7\u7F16\u8F91 .nium/config.json \u6587\u4EF6\u914D\u7F6E API \u5BC6\u94A5\u548C\u6A21\u578B
|
|
6
|
-
`)))}let t=
|
|
7
|
-
`;
|
|
6
|
+
`)))}let t=B(r,"agents");me(t)||(jt(t,{recursive:!0}),console.log(q.green("\u2713 \u521B\u5EFA .nium/agents \u76EE\u5F55")));let n=B(r,"docs");me(n)||(jt(n,{recursive:!0}),console.log(q.green("\u2713 \u521B\u5EFA .nium/docs \u76EE\u5F55")));let o=B(r,"archives");me(o)||(jt(o,{recursive:!0}),console.log(q.green("\u2713 \u521B\u5EFA .nium/archives \u76EE\u5F55")));let s=B(r,"logs");me(s)||(jt(s,{recursive:!0}),console.log(q.green("\u2713 \u521B\u5EFA .nium/logs \u76EE\u5F55")));let i=cc(),a=B(r,".env");return me(a)||(me(i)?(Ts(i,a),console.log(q.green("\u2713 \u590D\u5236 examples/.env.example \u5230 .nium/.env"))):(console.log(q.yellow(`\u26A0\uFE0F \u672A\u627E\u5230 .env.example: ${i}`)),console.log(q.yellow(" \u5C06\u4F7F\u7528\u9ED8\u8BA4\u73AF\u5883\u53D8\u91CF\u914D\u7F6E")))),r}catch(t){console.log(q.red(`\u274C \u521D\u59CB\u5316\u5DE5\u4F5C\u76EE\u5F55\u5931\u8D25: ${t.message}`)),process.exit(1)}}function ae(r){return B(Ps(),r)}var Ot,Gr,zr,qr,Me=C(()=>{Ot=typeof __dirname<"u"?__dirname:ks(ic(import.meta.url)),Gr=null,zr=null,qr=null});import{existsSync as lc,readFileSync as uc,appendFileSync as Es,writeFileSync as gc,createReadStream as pc}from"fs";import{createInterface as mc}from"readline";var ne,ce,Nn=C(()=>{ne=class{filePath;constructor(e){this.filePath=e}append(e){try{let t=JSON.stringify(e)+`
|
|
7
|
+
`;Es(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(`
|
|
8
8
|
`)+`
|
|
9
|
-
`;
|
|
10
|
-
`;
|
|
11
|
-
`).filter(c=>c.trim().length>0),o=[],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))&&o.push(l)}catch{console.warn(`Invalid JSON line in ${this.filePath}: ${c.substring(0,50)}...`)}return o}catch(t){throw new Error(`Failed to read JSONL file: ${t.message}`)}}async readStream(e,t={}){if(this.exists())return new Promise((n,o)=>{let s=
|
|
9
|
+
`;Es(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)+`
|
|
10
|
+
`;gc(this.filePath,t,"utf-8")}catch(t){throw new Error(`Failed to create JSONL file: ${t.message}`)}}getFilePath(){return this.filePath}},ce=class{filePath;constructor(e){this.filePath=e}exists(){return lc(this.filePath)}readAllSync(e={}){if(!this.exists())return[];try{let n=uc(this.filePath,"utf-8").split(`
|
|
11
|
+
`).filter(c=>c.trim().length>0),o=[],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))&&o.push(l)}catch{console.warn(`Invalid JSON line in ${this.filePath}: ${c.substring(0,50)}...`)}return o}catch(t){throw new Error(`Failed to read JSONL file: ${t.message}`)}}async readStream(e,t={}){if(this.exists())return new Promise((n,o)=>{let s=pc(this.filePath,{encoding:"utf-8"}),i=mc({input:s,crlfDelay:1/0}),a=0,c=0,l=t.startLine||0,{limit:p}=t;i.on("line",async u=>{try{if(u.trim().length===0)return;if(a<l){a++;return}if(p&&c>=p){i.close();return}let g=JSON.parse(u);(!t.filter||t.filter(g))&&(await e(g,a),c++),a++}catch{console.warn(`Invalid JSON line at line ${a}: ${u.substring(0,50)}...`),a++}}),i.on("close",()=>{n()}),i.on("error",u=>{o(new Error(`Failed to read JSONL stream: ${u.message}`))})})}async count(){if(!this.exists())return 0;let e=0;return await this.readStream(()=>{e++}),e}getFilePath(){return this.filePath}}});var Ds={};U(Ds,{formatLogEntry:()=>wc,getLogStats:()=>Tc,initLogger:()=>Kr,logDebug:()=>h,logError:()=>Y,logInfo:()=>M,logSuccess:()=>xc,logWarn:()=>z,readArchivedLogs:()=>vc,readCurrentLogs:()=>bc,setDebugMode:()=>Xr,writeLog:()=>qe});import{existsSync as Yr,readFileSync as dc,writeFileSync as Is,renameSync as fc,mkdirSync as hc}from"fs";import{join as Un}from"path";import W from"chalk";function Ls(){let r=new Date,e=r.getFullYear(),t=String(r.getMonth()+1).padStart(2,"0"),n=String(r.getDate()).padStart(2,"0");return`${e}-${t}-${n}`}function yc(){try{return Yr(Br)?dc(Br,"utf-8").trim():null}catch(r){let e=r instanceof Error?r.message:String(r);return console.error(W.yellow(`\u8BFB\u53D6\u65E5\u5FD7\u6587\u4EF6\u65E5\u671F\u5931\u8D25: ${e}`)),null}}function Sc(r){try{let e=Un(Ge,`${r}.jsonl`);if(Yr(e)){let n=new ce(ze).readAllSync();new ne(e).appendBatch(n),console.log(W.green(`\u2713 \u65E5\u5FD7\u5DF2\u8FFD\u52A0\u5230\u5F52\u6863\u6587\u4EF6: ${r}.jsonl`))}else fc(ze,e),console.log(W.green(`\u2713 \u65E5\u5FD7\u5DF2\u5F52\u6863: ${r}.jsonl`))}catch(e){let t=e instanceof Error?e.message:String(e);console.error(W.red(`\u5F52\u6863\u65E5\u5FD7\u5931\u8D25: ${t}`))}}function Cc(r){try{Is(ze,"","utf-8"),Is(Br,r,"utf-8");let e=new ne(ze),t={timestamp:new Date().toISOString(),level:"INFO",message:`\u65E5\u5FD7\u6587\u4EF6\u521B\u5EFA - \u65E5\u671F: ${r}`,date:r};e.append(t)}catch(e){let t=e instanceof Error?e.message:String(e);console.error(W.red(`\u521B\u5EFA\u65E5\u5FD7\u6587\u4EF6\u5931\u8D25: ${t}`))}}function Kr(){try{Yr(Ge)||(hc(Ge,{recursive:!0}),console.log(W.gray("\u521B\u5EFA\u65E5\u5FD7\u76EE\u5F55: .nium/logs")));let r=Ls(),e=yc();(!e||e!==r)&&(e&&(console.log(W.yellow(`\u68C0\u6D4B\u5230\u65E7\u65E5\u5FD7\u6587\u4EF6 (${e})\uFF0C\u6B63\u5728\u5F52\u6863...`)),Sc(e)),Cc(r),console.log(W.green(`\u2713 \u521B\u5EFA\u65B0\u65E5\u5FD7\u6587\u4EF6: ${r}`)))}catch(r){let e=r instanceof Error?r.message:String(r);console.error(W.red(`\u521D\u59CB\u5316\u65E5\u5FD7\u7CFB\u7EDF\u5931\u8D25: ${e}`))}}function Xr(r){As=r}function qe(r,e,t=!1){try{let n=new Date().toISOString(),o=Ls(),s={timestamp:n,level:r,message:e,date:o};if(new ne(ze).append(s),t||As){let a;switch(r){case"INFO":a=W.blue;break;case"WARN":a=W.yellow;break;case"ERROR":a=W.red;break;case"SUCCESS":a=W.green;break;case"DEBUG":a=W.magenta;break;default:a=W.white}console.log(a(`[${r}] ${e}`))}}catch(n){let o=n instanceof Error?n.message:String(n);console.error(W.red(`\u5199\u5165\u65E5\u5FD7\u5931\u8D25: ${o}`))}}function M(r){qe("INFO",r,!0)}function z(r){qe("WARN",r,!0)}function Y(r){qe("ERROR",r,!0)}function xc(r){qe("SUCCESS",r,!0)}function h(r){qe("DEBUG",r)}function bc(r){try{let e=new ce(ze);return e.exists()?e.readAllSync({filter:r?.level?n=>n.level===r.level:void 0,limit:r?.limit}):[]}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(W.red(`\u8BFB\u53D6\u65E5\u5FD7\u5931\u8D25: ${t}`)),[]}}function vc(r,e){try{let t=Un(Ge,`${r}.jsonl`),n=new ce(t);return n.exists()?n.readAllSync({filter:e?.level?s=>s.level===e.level:void 0,limit:e?.limit}):[]}catch(t){let n=t instanceof Error?t.message:String(t);return console.error(W.red(`\u8BFB\u53D6\u5F52\u6863\u65E5\u5FD7\u5931\u8D25: ${n}`)),[]}}function wc(r){return`[${new Date(r.timestamp).toLocaleString("zh-CN")}] [${r.level.padEnd(7)}] ${r.message}`}function Tc(r){let e={total:r.length,byLevel:{INFO:0,WARN:0,ERROR:0,SUCCESS:0,DEBUG:0}};for(let t of r)t.level in e.byLevel&&e.byLevel[t.level]++;return e}var Ge,ze,Br,As,K=C(()=>{Me();Nn();Ge=ae("logs"),ze=Un(Ge,"current.jsonl"),Br=Un(Ge,".current_date"),As=!1});import{existsSync as js,mkdirSync as kc,readdirSync as $c}from"fs";import{join as Os}from"path";function Rs(){js(Be)||kc(Be,{recursive:!0})}function Fs(r){if(!r||!r.messages||r.messages.length===0)return null;Rs();let e=new Date().toISOString().replace(/[:.]/g,"-"),t=r.sessionId?r.sessionId.substring(0,8):"unknown",n=r.currentTask?r.currentTask.substring(0,30).replace(/[^\w\u4e00-\u9fa5]/g,"_"):"unnamed",o=`session_${t}_${e}_${n}.jsonl`,s=Os(Be,o),i={type:"session_metadata",data:{sessionId:r.sessionId,currentTask:r.currentTask,createdAt:r.createdAt,archivedAt:new Date().toISOString(),messageCount:r.messages.length,taskCount:r.tasks?r.tasks.length:0}};try{let a=new ne(s);if(a.create(i),r.tasks&&r.tasks.length>0){let c={type:"tasks_data",data:r.tasks};a.append(c)}r.messages&&r.messages.length>0&&r.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 Pc(){return Rs(),js(Be)?$c(Be).filter(e=>e.endsWith(".jsonl")).map(e=>{let t=Os(Be,e);try{let o=new ce(t).readAllSync({limit:1})[0];return!o||o.type!=="session_metadata"?null:{fileName:e,filePath:t,sessionId:o.data.sessionId,sessionIdShort:o.data.sessionId?o.data.sessionId.substring(0,8):"unknown",currentTask:o.data.currentTask||"\u672A\u547D\u540D\u4EFB\u52A1",timestamp:o.data.archivedAt,archivedAt:o.data.archivedAt,messageCount:o.data.messageCount||0,taskCount:o.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 _s(){let r=Pc();if(r.length===0)return"\u6682\u65E0\u5F52\u6863\u4F1A\u8BDD";let e=`
|
|
12
12
|
=== \u5F52\u6863\u4F1A\u8BDD\u5217\u8868 ===
|
|
13
13
|
|
|
14
14
|
`;return r.forEach((t,n)=>{let s=new Date(t.archivedAt).toLocaleString("zh-CN");e+=`[${n+1}] ${t.currentTask}
|
|
@@ -18,8 +18,8 @@ var fa=Object.defineProperty;var w=(r,e)=>()=>(r&&(e=r(r=0)),e);var U=(r,e)=>{fo
|
|
|
18
18
|
`,e+=` \u6D88\u606F\u6570\u91CF: ${t.messageCount}
|
|
19
19
|
`,e+=` \u6587\u4EF6\u540D: ${t.fileName}
|
|
20
20
|
|
|
21
|
-
`}),e}var Be,
|
|
22
|
-
\u2705 \u4EFB\u52A1\u5B8C\u6210: ${v.currentTask}`)),console.log(Ye.blue(`\u{1F4CA} Token\u603B\u5F00\u9500: ${e.toLocaleString()} tokens`))}v.currentTask=null,v.currentTaskId=null,Q()}}function Qe(){return
|
|
21
|
+
`}),e}var Be,Qr=C(()=>{Me();Nn();Be=ae("archives")});function Ee(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}function Zr(){return"S"+Ee()}function Vn(){return"T"+Ee()}var Wn=C(()=>{});var Vs={};U(Vs,{SESSION_FILE:()=>Ce,archiveSession:()=>Xe,associateMessageWithTask:()=>Us,completeCurrentTask:()=>Qe,loadSession:()=>to,saveSession:()=>Q,sessionState:()=>v,setCurrentTaskId:()=>Ke,startNewTask:()=>Hn});import{writeFileSync as Mc,existsSync as Ns}from"fs";import Ye from"chalk";function eo(){return{sessionId:Zr(),messages:[],tasks:[],currentTask:null,currentTaskId:null,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}}function Ec(){try{v.messages&&v.messages.length>0&&Fs(v)&&h("\u4F1A\u8BDD\u5DF2\u5F52\u6863"),v=eo(),new ne(Ce).create(v)}catch(r){let e=r instanceof Error?r.message:String(r);console.log(Ye.yellow(`Warning: Failed to archive session - ${e}`)),v=eo();try{new ne(Ce).create(v)}catch{}}}function to(){try{if(Ns(Ce)){let e=new ce(Ce).readAllSync(),t=e.length>0?e[0]:null;return v={sessionId:t&&t.sessionId||Zr(),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(r){let e=r instanceof Error?r.message:String(r);console.log(Ye.yellow(`Warning: Could not load session - ${e}`))}return!1}function Hn(r){let e=Vn(),t={id:e,description:r,createdAt:new Date().toISOString(),messageIds:[]};return v.tasks.push(t),v.currentTask=r,v.currentTaskId=e,e}function Us(r){if(v.currentTaskId&&r){let e=v.currentTaskId;r.taskId=e;let t=v.tasks.find(n=>n.id===e);if(t&&!r.id){let n=Ee();r.id=n,t.messageIds.push(n)}}return r}function Ke(r){v.currentTaskId=r,v.updatedAt=new Date().toISOString(),Q(),console.log(Ye.blue(`[\u4F1A\u8BDD\u7BA1\u7406] \u5F53\u524D\u4EFB\u52A1ID\u5DF2\u8BBE\u7F6E\u4E3A: ${r}`))}function Q(r,e=null){try{if(e&&e!==v.currentTask&&Hn(e),r){let n=r.map(o=>Us({...o}));v={...v,messages:n,updatedAt:new Date().toISOString()}}else v={...v,updatedAt:new Date().toISOString()};Ns(Ce)&&Mc(Ce,"","utf-8"),new ne(Ce).create(v)}catch(t){let n=t instanceof Error?t.message:String(t);console.log(Ye.yellow(`Warning: Could not save session - ${n}`))}}function Xe(){return Ec()}function Ic(){if(v.currentTask&&v.currentTaskId){let r=v.tasks.find(e=>e.id===v.currentTaskId);if(r){let e=r.tokenCount||0;console.log(Ye.green(`
|
|
22
|
+
\u2705 \u4EFB\u52A1\u5B8C\u6210: ${v.currentTask}`)),console.log(Ye.blue(`\u{1F4CA} Token\u603B\u5F00\u9500: ${e.toLocaleString()} tokens`))}v.currentTask=null,v.currentTaskId=null,Q()}}function Qe(){return Ic()}var Ce,v,xe=C(()=>{K();Me();Qr();Nn();Wn();Ce=ae("session.jsonl");v=eo()});var no,Ws=C(()=>{no={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
|
|
23
23
|
|
|
24
24
|
## \u6838\u5FC3\u89C4\u5219
|
|
25
25
|
|
|
@@ -184,7 +184,27 @@ var fa=Object.defineProperty;var w=(r,e)=>()=>(r&&(e=r(r=0)),e);var U=(r,e)=>{fo
|
|
|
184
184
|
- **\u9879\u76EE\u7EA6\u5B9A**: \u5982\u679C\u5B58\u5728 \`.nium/conventions.md\`\uFF0C\u4F18\u5148\u9075\u5FAA\u5176\u4E2D\u7684\u56E2\u961F\u7EA6\u5B9A
|
|
185
185
|
- **\u6587\u4EF6\u5B89\u5168**: \u4E25\u683C\u9075\u5B88\u4E0A\u8FF0\u6587\u4EF6\u64CD\u4F5C\u5B89\u5168\u7EA6\u675F\uFF0C\u4FDD\u62A4\u7CFB\u7EDF\u5B89\u5168
|
|
186
186
|
|
|
187
|
-
|
|
187
|
+
## \u4EE3\u7801\u4FEE\u6539\u6700\u4F73\u5B9E\u8DF5
|
|
188
|
+
|
|
189
|
+
1. **\u51FD\u6570\u7B7E\u540D\u53D8\u66F4**\uFF1A
|
|
190
|
+
- \u5F53\u4FEE\u6539\u51FD\u6570\u7B7E\u540D\uFF08\u6DFB\u52A0/\u5220\u9664\u53C2\u6570\u3001\u4FEE\u6539\u8FD4\u56DE\u7C7B\u578B\uFF09\u65F6\uFF0C\u5FC5\u987B\u4F7F\u7528 \`grep()\` \u5DE5\u5177\u67E5\u627E\u6240\u6709\u5F15\u7528
|
|
191
|
+
- \u5206\u6790\u6240\u6709\u5F15\u7528\uFF0C\u786E\u4FDD\u6BCF\u4E2A\u8C03\u7528\u70B9\u90FD\u5F97\u5230\u9002\u5F53\u66F4\u65B0
|
|
192
|
+
- \u4F7F\u7528 \`searchReplace()\` \u5DE5\u5177\u8FDB\u884C\u6279\u91CF\u66F4\u65B0\uFF0C\u786E\u4FDD\u4E00\u81F4\u6027
|
|
193
|
+
|
|
194
|
+
2. **\u63A5\u53E3\u548C\u7C7B\u4FEE\u6539**\uFF1A
|
|
195
|
+
- \u4FEE\u6539\u63A5\u53E3\u6216\u7C7B\u5B9A\u4E49\u65F6\uFF0C\u5FC5\u987B\u68C0\u67E5\u6240\u6709\u5B9E\u73B0\u8BE5\u63A5\u53E3\u6216\u7EE7\u627F\u8BE5\u7C7B\u7684\u5730\u65B9
|
|
196
|
+
- \u786E\u4FDD\u6240\u6709\u5B9E\u73B0\u90FD\u7B26\u5408\u65B0\u7684\u63A5\u53E3\u8981\u6C42
|
|
197
|
+
|
|
198
|
+
3. **\u5BFC\u51FA\u53D8\u91CF\u548C\u5E38\u91CF**\uFF1A
|
|
199
|
+
- \u4FEE\u6539\u5BFC\u51FA\u7684\u53D8\u91CF\u6216\u5E38\u91CF\u65F6\uFF0C\u5FC5\u987B\u68C0\u67E5\u6240\u6709\u5BFC\u5165\u548C\u4F7F\u7528\u8BE5\u53D8\u91CF\u7684\u5730\u65B9
|
|
200
|
+
- \u786E\u4FDD\u6240\u6709\u5F15\u7528\u90FD\u80FD\u9002\u5E94\u65B0\u7684\u53D8\u91CF\u7C7B\u578B\u6216\u503C
|
|
201
|
+
|
|
202
|
+
4. **\u8DE8\u6587\u4EF6\u4F9D\u8D56\u7BA1\u7406**\uFF1A
|
|
203
|
+
- \u5F53\u4FEE\u6539\u8DE8\u6587\u4EF6\u4F7F\u7528\u7684\u4EE3\u7801\u65F6\uFF0C\u5FC5\u987B\u8003\u8651\u5BF9\u5176\u4ED6\u6587\u4EF6\u7684\u5F71\u54CD
|
|
204
|
+
- \u4F7F\u7528 \`grep()\` \u6216 \`search\` \u5DE5\u5177\u67E5\u627E\u6240\u6709\u5F15\u7528
|
|
205
|
+
- \u5236\u5B9A\u5168\u9762\u7684\u66F4\u65B0\u8BA1\u5212\uFF0C\u786E\u4FDD\u6240\u6709\u4F9D\u8D56\u90FD\u5F97\u5230\u9002\u5F53\u5904\u7406
|
|
206
|
+
|
|
207
|
+
\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 ro,Hs=C(()=>{ro={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\u3002
|
|
188
208
|
|
|
189
209
|
## \u53EF\u7528\u5DE5\u5177
|
|
190
210
|
|
|
@@ -261,15 +281,15 @@ var fa=Object.defineProperty;var w=(r,e)=>()=>(r&&(e=r(r=0)),e);var U=(r,e)=>{fo
|
|
|
261
281
|
2. **\u7CBE\u51C6\u56DE\u7B54**\uFF1A\u5BF9\u4E8E\u5177\u4F53\u95EE\u9898\uFF0C\u4F7F\u7528\u6700\u5408\u9002\u7684\u5DE5\u5177\u7EC4\u5408
|
|
262
282
|
3. **\u6DF1\u5EA6\u5206\u6790**\uFF1A\u5FC5\u8981\u65F6\u6DF1\u5165\u8BFB\u53D6\u548C\u5206\u6790\u5173\u952E\u4EE3\u7801\u6587\u4EF6
|
|
263
283
|
4. **\u6E05\u6670\u8868\u8FBE**\uFF1A\u4EE5\u7ED3\u6784\u5316\u3001\u6613\u61C2\u7684\u65B9\u5F0F\u5448\u73B0\u5206\u6790\u7ED3\u679C
|
|
264
|
-
5. **\u5408\u7406\u5C55\u793A**\uFF1A\u63A2\u7D22\u5B8C\u6210\u540E\uFF0C\u544A\u8BC9\u7528\u6237\u9879\u76EE\u4FE1\u606F\u5DF2\u751F\u6210\uFF0C\u53EF\u6839\u636E\u9700\u8981\u8BFB\u53D6\u5E76\u5C55\u793A\u5173\u952E\u4FE1\u606F`}});function
|
|
284
|
+
5. **\u5408\u7406\u5C55\u793A**\uFF1A\u63A2\u7D22\u5B8C\u6210\u540E\uFF0C\u544A\u8BC9\u7528\u6237\u9879\u76EE\u4FE1\u606F\u5DF2\u751F\u6210\uFF0C\u53EF\u6839\u636E\u9700\u8981\u8BFB\u53D6\u5E76\u5C55\u793A\u5173\u952E\u4FE1\u606F`}});function Js(){return Object.values(Ac)}var Ac,Gs=C(()=>{Ws();Hs();Ac={[no.name]:no,[ro.name]:ro}});var Ze={};U(Ze,{LITE_MODEL:()=>fe,MODEL:()=>de,getDefaultModelConfig:()=>Ie,getLiteModelConfig:()=>Rt,getLiteModelMaxToken:()=>io,getMCPServerConfigs:()=>ao,getMaxToken:()=>so,getProvider:()=>jc});import{readFileSync as Lc}from"fs";function oo(){if(!Jn)try{let r=ae("config.json"),e=Lc(r,"utf-8");Jn=JSON.parse(e)}catch(r){console.error("Failed to load config.json:",r.message),Jn={models:{defaultModel:{apiKey:"",baseURL:"https://api.openai.com/v1",model:"gpt-4o-mini",provider:"openai"}}}}return Jn}function Ie(){let r=oo(),e={apiKey:"",baseURL:"https://api.openai.com/v1",model:"gpt-4o-mini",provider:"openai",maxToken:128e3};return r.models?.defaultModel||e}function Rt(){return oo().models?.liteModel||Ie()}function zs(){return Ie().model||"gpt-4o-mini"}function Dc(){return Rt().model||zs()}function jc(){return Ie().provider||"openai"}function de(){return zs()}function fe(){return Dc()}function so(){return Ie().maxToken||128e3}function io(){return Rt().maxToken||16385}function ao(){return oo().mcpServers||[]}var Jn,ee=C(()=>{Me();Jn=null});var Ae,Gn=C(()=>{Ae=class{config;constructor(e){this.config=e}getModelName(){return this.config.model}getProviderType(){return this.config.provider}_getApiKey(){return this.config.apiKey}_getBaseURL(){return this.config.baseURL}}});import Oc from"openai";var co,qs,Bs=C(()=>{Gn();co=class extends Ae{client=null;constructor(e){super(e)}_initClient(){return this.client||(this.client=new Oc({apiKey:this.config.apiKey,baseURL:this.config.baseURL||"https://api.openai.com/v1"})),this.client}async callModel(e){let{model:t=this.getModelName(),messages:n,temperature:o=.1,max_tokens:s,tools:i,tool_choice:a}=e,c=this._initClient(),l=[...n],p={model:t,messages:l,temperature:o,max_tokens:s};i&&i.length>0&&(p.tools=i.map(g=>({type:"function",function:{name:g.name,description:g.description,parameters:g.input_schema}})),a&&(a.type==="any"||(p.tool_choice=a)));let u=await c.chat.completions.create(p);return this._processReasoningContent(u),u}_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}
|
|
265
285
|
|
|
266
|
-
${t.content}`):t.content=n;return}try{let o=[];try{let s=JSON.parse(n);Array.isArray(s)&&s.length>0?(o=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=o):t.content||(t.content=n)}catch{t.content||(t.content=n)}}catch(o){console.warn("Failed to process reasoning_content:",o)}}}},
|
|
286
|
+
${t.content}`):t.content=n;return}try{let o=[];try{let s=JSON.parse(n);Array.isArray(s)&&s.length>0?(o=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=o):t.content||(t.content=n)}catch{t.content||(t.content=n)}}catch(o){console.warn("Failed to process reasoning_content:",o)}}}},qs=co});var lo,Ys,Ks=C(()=>{Gn();lo=class extends Ae{client=null;constructor(e){super(e)}async _initClient(){if(!this.client){let{Anthropic:e}=await import("@anthropic-ai/sdk");this.client=new e({apiKey:this.config.apiKey})}return this.client}async callModel(e){let{model:t=this.getModelName(),messages:n,temperature:o=.1,max_tokens:s=4096,tools:i,tool_choice:a}=e,c=await this._initClient(),l=[...n],p="",u=l.filter(d=>d.role==="system");u.length>0&&(p=u.map(d=>d.content).join(`
|
|
267
287
|
|
|
268
|
-
`)),l=l.filter(
|
|
288
|
+
`)),l=l.filter(d=>d.role!=="system");let g=[],m=0;for(;m<l.length;){let d=l[m];if(d.role==="assistant"){let k=[];if(d.content&&typeof d.content=="string"&&k.push({type:"text",text:d.content}),d.tool_calls&&d.tool_calls.length>0)for(let T of d.tool_calls)k.push({type:"tool_use",id:T.id,name:T.function.name,input:JSON.parse(T.function.arguments)});k.length>0&&g.push({role:"assistant",content:k}),m++}else if(d.role==="tool"){let k=[];for(;m<l.length&&l[m].role==="tool";){let T=l[m];k.push({type:"tool_result",tool_use_id:T.tool_call_id,content:T.content||"No result"}),m++}k.length>0&&g.push({role:"user",content:k})}else if(d.role==="user"){let k=typeof d.content=="string"?[{type:"text",text:d.content}]:Array.isArray(d.content)?d.content:[{type:"text",text:String(d.content)}];g.push({role:"user",content:k}),m++}else m++}let S={model:t,max_tokens:s,temperature:o,system:p||"You are a helpful assistant.",messages:g};i&&i.length>0&&(S.tools=i,a&&(S.tool_choice=a));let b=await c.messages.create(S);console.log("[Anthropic Provider] Response content blocks:",JSON.stringify(b.content,null,2));let f=[],y="";for(let d of b.content)if(d.type==="text")y+=d.text;else if(d.type==="tool_use")console.log("[Anthropic Provider] Tool use block:",{id:d.id,name:d.name,input:d.input,inputKeys:Object.keys(d.input||{})}),f.push({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.input)}});else if(d.type==="thinking"){let k=d.thinking||"";k&&(y=k+(y?`
|
|
269
289
|
|
|
270
|
-
`+y:""))}return{choices:[{message:{content:y||null,tool_calls:
|
|
290
|
+
`+y:""))}return{choices:[{message:{content:y||null,tool_calls:f.length>0?f:void 0},finish_reason:b.stop_reason==="end_turn"?"stop":b.stop_reason}]}}},Ys=lo});var Ft,Xs=C(()=>{ee();Gn();Bs();Ks();Ft=class{static async getProvider(){let e=Ie();return this.createProvider(e)}static async getLiteProvider(){let e=Rt();return this.createProvider(e)}static async createProvider(e){switch(e.provider||"openai"){case"anthropic":return new Ys(e);case"openai":default:return new qs(e)}}}});function et(r){return r&&typeof r=="object"&&r.__tool_result===!0}function _t(r){return et(r)?r.result:r}var I,J=C(()=>{I=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(([o,s])=>{let i=s;return typeof s=="string"&&s.length>50&&(i=s.substring(0,50)+"..."),`${o}=${JSON.stringify(i)}`}).join(", ");return`${t}(${n})`}formatObservation(e){if(et(e)){let{display:t}=e;return Array.isArray(t)?t.join(`
|
|
271
291
|
`):String(t)}return Array.isArray(e)?e.join(`
|
|
272
|
-
`):String(e)}shouldPrintObservation(e){return et(e)?e.shouldPrint:!0}}});var
|
|
292
|
+
`):String(e)}shouldPrintObservation(e){return et(e)?e.shouldPrint:!0}}});var re,Nt=C(()=>{J();re=class extends I{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(`
|
|
273
293
|
`);n=n.slice(0,s)+`
|
|
274
294
|
- User confirmation is automatically required - DO NOT call askUser tool before calling this tool`+n.slice(s)}else{let s=n.indexOf(`
|
|
275
295
|
`);s!==-1?n=n.slice(0,s)+`
|
|
@@ -277,17 +297,17 @@ ${t.content}`):t.content=n;return}try{let o=[];try{let s=JSON.parse(n);Array.isA
|
|
|
277
297
|
|
|
278
298
|
`+n}else n=t+`
|
|
279
299
|
|
|
280
|
-
`+n;return{...e,description:n,requiresConfirmation:!0}}getConfirmationMessage(e){return null}}});var
|
|
281
|
-
`).length;return`\u8BFB\u53D6\u6587\u4EF6 ${this.lastReadPath}\uFF0C\u5171 ${n} \u884C`}return super.formatObservation(e)}}
|
|
300
|
+
`+n;return{...e,description:n,requiresConfirmation:!0}}getConfirmationMessage(e){return null}}});var uo={};U(uo,{BaseTool:()=>I,ConfirmableTool:()=>re,extractToolResult:()=>_t,isToolResult:()=>et});var go=C(()=>{J();Nt()});import{readFileSync as Qs,statSync as Rc}from"fs";import{resolve as Fc}from"path";function Ut(r,e={}){return Zs.execute({path:r,...e})}var tt,Zs,Vt,ei=C(()=>{J();tt=class extends I{lastReadPath="";getDefinition(){return{name:"read",description:"Read the content of a file at the specified path. Returns the complete file content as a string.",input_schema:{type:"object",properties:{path:{type:"string",description:"The file path to read (relative or absolute)"},silent:{type:"boolean",description:"If true, returns success message instead of full content (optional)"},chunkSize:{type:"number",description:"If provided, returns file content in chunks of specified size (bytes, optional)"},autoChunk:{type:"boolean",description:"If true, automatically splits large files into chunks based on file size (optional)"}},required:["path"]}}}execute(e){try{let t=e.path.trim(),n=Fc(t);if(this.lastReadPath=t,e.silent)return Qs(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 o=Qs(n,"utf-8");if(e.chunkSize||e.autoChunk){let a=Rc(n).size,c=1024*1024,l=5*1024*1024,p=e.chunkSize||c;if(e.autoChunk&&a<=l)return o;p=Math.max(1,p);let u=[];for(let g=0;g<o.length;g+=p)u.push(o.slice(g,g+p));return this.createToolResult(u,`\u6587\u4EF6 ${t} \u5DF2\u5206\u5757\u8BFB\u53D6\uFF0C\u5171 ${u.length} \u5757\uFF0C\u6BCF\u5757 ${p} \u5B57\u8282`,!0)}return o}catch(t){let o=`Error: Cannot read file ${e.path.trim()} - ${t instanceof Error?t.message:String(t)}`;return this.createToolResult(o,o,!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(`
|
|
301
|
+
`).length;return`\u8BFB\u53D6\u6587\u4EF6 ${this.lastReadPath}\uFF0C\u5171 ${n} \u884C`}return super.formatObservation(e)}},Zs=new tt;Vt=Zs});function ti(r){if(typeof r!="string")return r;let e=r.replace(/\\n/g,`
|
|
282
302
|
`).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\"/g,'"').replace(/\\'/g,"'");return e=e.replace(/\r\n/g,`
|
|
283
303
|
`).replace(/\r/g,`
|
|
284
|
-
`),e}function
|
|
304
|
+
`),e}function zn(r){return r.includes(`\r
|
|
285
305
|
`)?`\r
|
|
286
306
|
`:r.includes(`
|
|
287
307
|
`)?`
|
|
288
|
-
`:r.includes("\r")?"\r":
|
|
308
|
+
`:r.includes("\r")?"\r":po}var po,mo=C(()=>{po=process.platform==="win32"?`\r
|
|
289
309
|
`:`
|
|
290
|
-
`});import{mkdirSync as
|
|
310
|
+
`});import{mkdirSync as _c}from"fs";import{resolve as Nc}from"path";function Wt(r){return ni.execute({path:r})}var nt,ni,Le,fo=C(()=>{J();nt=class extends I{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=Nc(e.path);return _c(t,{recursive:!0}),`Directory created: ${e.path}`}catch(t){return this.formatError(`Cannot create directory ${e.path}`,t)}}},ni=new nt;Le=ni});import{readFileSync as Uc,writeFileSync as ri,existsSync as Vc}from"fs";import{resolve as Wc,dirname as Hc}from"path";function Ht(r,e){return oi.execute({path:r,content:e})}var rt,oi,Jt,si=C(()=>{mo();fo();J();rt=class extends I{getDefinition(){return{name:"write",description:`Write content to a file - ONLY for creating NEW files.
|
|
291
311
|
|
|
292
312
|
\u26A0\uFE0F IMPORTANT - READ BEFORE USING:
|
|
293
313
|
- Use ONLY for creating NEW files that don't exist yet
|
|
@@ -301,9 +321,9 @@ ${t.content}`):t.content=n;return}try{let o=[];try{let s=JSON.parse(n);Array.isA
|
|
|
301
321
|
\u2502 Modifying EXISTING file \u2192 merge() \u2705 \u2502
|
|
302
322
|
\u2502 Overwriting EXISTING \u2192 write() \u26A0\uFE0F RISKY \u2502
|
|
303
323
|
\u2502 Small precise edits \u2192 search_replace() \u2705 \u2502
|
|
304
|
-
\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518`,input_schema:{type:"object",properties:{path:{type:"string",description:"The file path to write to"},content:{type:"string",description:"The COMPLETE file content to write. This parameter is REQUIRED and cannot be empty."}},required:["path","content"]}}}execute(e){try{let t=
|
|
324
|
+
\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518`,input_schema:{type:"object",properties:{path:{type:"string",description:"The file path to write to"},content:{type:"string",description:"The COMPLETE file content to write. This parameter is REQUIRED and cannot be empty."}},required:["path","content"]}}}execute(e){try{let t=Wc(e.path),n=Hc(t),o=Le.execute({path:n});if(o.startsWith("Error:"))return o;let s=ti(e.content);typeof s!="string"&&(s=String(s||""));let i=po;if(Vc(t)){let a=Uc(t,"utf-8");i=zn(a);let c=`${t}.base`;ri(c,a,"utf-8")}return i===`\r
|
|
305
325
|
`&&(s=s.replace(/\n/g,`\r
|
|
306
|
-
`)),
|
|
326
|
+
`)),ri(t,s,"utf-8"),"done"}catch(t){return this.formatError(`Cannot write ${e.path}`,t)}}},oi=new rt;Jt=oi});import{unlinkSync as Jc,existsSync as Gc,statSync as zc,rmdirSync as qc}from"fs";import{resolve as Bc}from"path";function Gt(r){return typeof r=="object"&&r!==null&&"path"in r?ho.execute(r):ho.execute({path:r})}var ot,ho,zt,ii=C(()=>{Nt();ot=class extends re{getBaseDefinition(){return{name:"deleteFile",description:`Delete a file, multiple files or directories at the specified path(s).
|
|
307
327
|
|
|
308
328
|
IMPORTANT:
|
|
309
329
|
- This action cannot be undone
|
|
@@ -315,31 +335,31 @@ Examples:
|
|
|
315
335
|
- deleteFile("temp.txt") - delete a single file named temp.txt
|
|
316
336
|
- deleteFile("temp_dir") - delete a single empty directory named temp_dir
|
|
317
337
|
- deleteFile({ path: "temp.txt" }) - delete a single file
|
|
318
|
-
- 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 p=
|
|
338
|
+
- 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 p=Bc(l);if(!Gc(p)){n.push(`Warning: Path not found - ${l}`);continue}zc(p).isDirectory()?(qc(p),n.push(`Directory deleted: ${l}`)):(Jc(p),n.push(`File deleted: ${l}`))}catch(p){n.push(`Error: Cannot delete ${l} - ${p instanceof Error?p.message:"Unknown error"}`)}if(t.length===1)return n[0];let o=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=o+s;return`${n.join(`
|
|
319
339
|
`)}
|
|
320
340
|
|
|
321
|
-
Summary: ${c} items deleted (${o} files, ${s} directories), ${a} warnings, ${i} errors`}catch(t){return this.formatError("Cannot process delete operation",t)}}},
|
|
341
|
+
Summary: ${c} items deleted (${o} files, ${s} directories), ${a} warnings, ${i} errors`}catch(t){return this.formatError("Cannot process delete operation",t)}}},ho=new ot;zt=ho});import{renameSync as Yc,existsSync as qn,statSync as Kc,mkdirSync as Xc}from"fs";import{resolve as ai,dirname as Qc}from"path";function qt(r){return r&&typeof r=="object"&&"source"in r&&"destination"in r?ci.execute(r):"Error: Invalid input format. Expected { source: string, destination: string }"}var st,ci,Bt,li=C(()=>{Nt();st=class extends re{getBaseDefinition(){return{name:"moveFile",description:`Move or rename a file or directory from source to destination.
|
|
322
342
|
|
|
323
343
|
Examples:
|
|
324
344
|
- moveFile({ source: "old.txt", destination: "new.txt" }) - rename a file
|
|
325
345
|
- moveFile({ source: "file.txt", destination: "folder/file.txt" }) - move a file to a different directory
|
|
326
346
|
- moveFile({ source: "old_folder", destination: "new_folder" }) - rename a directory
|
|
327
|
-
- 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,o=
|
|
347
|
+
- 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,o=ai(t),s=ai(n);if(!qn(o))return`Error: Source path does not exist - ${t}`;if(qn(s))return`Error: Destination already exists - ${n}`;let i=Qc(s);return qn(i)||Xc(i,{recursive:!0}),Yc(o,s),qn(s)?`${Kc(o).isDirectory()?"Directory":"File"} moved successfully from "${t}" to "${n}"`:`Error: Failed to move ${t} to ${n}`}catch(t){return this.formatError("Move operation",t)}}},ci=new st;Bt=ci});import{existsSync as Bn,statSync as ui,readFileSync as gi,writeFileSync as pi,mkdirSync as mi,readdirSync as Zc}from"fs";import{resolve as di,join as fi,dirname as el}from"path";function Yt(r){return r&&typeof r=="object"&&"source"in r&&"destination"in r?hi.execute(r):"Error: Invalid input format. Expected { source: string, destination: string }"}var it,hi,Kt,yi=C(()=>{Nt();it=class extends re{getBaseDefinition(){return{name:"copyFile",description:`Copy a file or directory from source to destination.
|
|
328
348
|
|
|
329
349
|
Examples:
|
|
330
350
|
- copyFile({ source: "file.txt", destination: "file_copy.txt" }) - copy a file
|
|
331
351
|
- copyFile({ source: "file.txt", destination: "folder/file.txt" }) - copy a file to a different directory
|
|
332
352
|
- copyFile({ source: "folder", destination: "folder_copy" }) - copy an entire directory (recursively)
|
|
333
|
-
- 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,o=
|
|
353
|
+
- 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,o=di(t),s=di(n);if(!Bn(o))return`Error: Source path does not exist - ${t}`;if(o===s)return"Error: Source and destination paths are identical";let i=ui(o),a=0,c=0;if(i.isDirectory())return this.copyDirectory(o,s,a,c),`Directory copied successfully from "${t}" to "${n}" (${a} files, ${c} directories)`;{let l=el(s);return Bn(l)||mi(l,{recursive:!0}),pi(s,gi(o)),Bn(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,o){Bn(t)||(mi(t,{recursive:!0}),o++),Zc(e).forEach(i=>{let a=fi(e,i),c=fi(t,i);ui(a).isDirectory()?this.copyDirectory(a,c,n,o):(pi(c,gi(a)),n++)})}},hi=new it;Kt=hi});import{diff3Merge as tl}from"node-diff3";function Si(r,e,t){let n=r.split(`
|
|
334
354
|
`),o=e.split(`
|
|
335
355
|
`),s=t.split(`
|
|
336
|
-
`);console.log(` [merge] \u5F00\u59CB\u4E09\u8DEF\u5408\u5E76: base=${n.length}\u884C, current=${o.length}\u884C, incoming=${s.length}\u884C`);let i=Date.now(),a=
|
|
337
|
-
`),current:
|
|
338
|
-
`),incoming:
|
|
339
|
-
`)}),l.push("<<<<<<< CURRENT"),l.push(...
|
|
340
|
-
`),hasConflicts:p.length>0,conflicts:p}}var
|
|
356
|
+
`);console.log(` [merge] \u5F00\u59CB\u4E09\u8DEF\u5408\u5E76: base=${n.length}\u884C, current=${o.length}\u884C, incoming=${s.length}\u884C`);let i=Date.now(),a=tl(o,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=[],p=[];for(let u of a)if(u.ok)l.push(...u.ok);else if(u.conflict){let g=l.length+1,m=u.conflict.a||[],S=u.conflict.o||[],b=u.conflict.b||[];p.push({lineNumber:g,base:S.join(`
|
|
357
|
+
`),current:m.join(`
|
|
358
|
+
`),incoming:b.join(`
|
|
359
|
+
`)}),l.push("<<<<<<< CURRENT"),l.push(...m),l.push("======="),l.push(...b),l.push(">>>>>>> INCOMING")}return{merged:l.join(`
|
|
360
|
+
`),hasConflicts:p.length>0,conflicts:p}}var Ci=C(()=>{});import{readFileSync as xi,writeFileSync as Yn,existsSync as yo,unlinkSync as So}from"fs";import{resolve as nl}from"path";function Co(r){return r.replace(/\r\n/g,`
|
|
341
361
|
`).replace(/\r/g,`
|
|
342
|
-
`)}function
|
|
362
|
+
`)}function Xt(r,e,t){return bi.execute({path:r,newContent:e,confirmLargeChange:t})}var rl,at,bi,Qt,vi=C(()=>{mo();Ci();J();rl={lineRatioThreshold:.5,minLineDiff:100},at=class extends I{getDefinition(){return{name:"merge",description:`Smart file merge tool - THE DEFAULT CHOICE for modifying existing files.
|
|
343
363
|
|
|
344
364
|
\u{1F4CB} TOOL SELECTION GUIDE:
|
|
345
365
|
\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510
|
|
@@ -364,7 +384,7 @@ Examples:
|
|
|
364
384
|
\u{1F4A1} TIPS:
|
|
365
385
|
- Provide COMPLETE new file content
|
|
366
386
|
- If you get "large difference" warning, review your changes
|
|
367
|
-
- Set confirmLargeChange=true to proceed with large changes`,input_schema:{type:"object",properties:{path:{type:"string",description:"The file path to merge"},newContent:{type:"string",description:"The COMPLETE new version of the entire file content"},confirmLargeChange:{type:"boolean",description:"Set to true to confirm and proceed with large changes (>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=
|
|
387
|
+
- Set confirmLargeChange=true to proceed with large changes`,input_schema:{type:"object",properties:{path:{type:"string",description:"The file path to merge"},newContent:{type:"string",description:"The COMPLETE new version of the entire file content"},confirmLargeChange:{type:"boolean",description:"Set to true to confirm and proceed with large changes (>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=rl){if(t>=e)return{isLargeDeletion:!1,deletionRatio:0,message:""};let o=e-t,s=e>0?o/e:0,i=o>=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, ${o} lines removed).
|
|
368
388
|
|
|
369
389
|
This may indicate:
|
|
370
390
|
- Incomplete content (missing parts of the file)
|
|
@@ -372,30 +392,30 @@ This may indicate:
|
|
|
372
392
|
- Wrong file content
|
|
373
393
|
|
|
374
394
|
To proceed, call merge() again with confirmLargeChange=true.
|
|
375
|
-
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=
|
|
376
|
-
`?"CRLF":"LF"}`);let i=
|
|
395
|
+
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=nl(e.path),n=`${t}.base`;if(!yo(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 o=xi(t,"utf-8");console.log(` [MergeTool] \u5F53\u524D\u6587\u4EF6\u5927\u5C0F: ${o.length} \u5B57\u7B26`);let s=zn(o);console.log(` [MergeTool] \u68C0\u6D4B\u5230\u884C\u7ED3\u675F\u7B26: ${s===`\r
|
|
396
|
+
`?"CRLF":"LF"}`);let i=Co(o),a=Co(e.newContent),c=i.split(`
|
|
377
397
|
`).length,l=a.split(`
|
|
378
|
-
`).length;if(!e.confirmLargeChange){let y=this.checkLargeDeletion(c,l);if(y.isLargeDeletion)return console.log(` [MergeTool] \u68C0\u6D4B\u5230\u5927\u5E45\u5220\u51CF\uFF08${c} \u2192 ${l}\u884C\uFF09\uFF0C\u9700\u8981\u786E\u8BA4`),y.message}let p=o,u=!1;
|
|
398
|
+
`).length;if(!e.confirmLargeChange){let y=this.checkLargeDeletion(c,l);if(y.isLargeDeletion)return console.log(` [MergeTool] \u68C0\u6D4B\u5230\u5927\u5E45\u5220\u51CF\uFF08${c} \u2192 ${l}\u884C\uFF09\uFF0C\u9700\u8981\u786E\u8BA4`),y.message}let p=o,u=!1;yo(n)&&(console.log(" [MergeTool] \u53D1\u73B0\u57FA\u7840\u7248\u672C\u6587\u4EF6\uFF0C\u8BFB\u53D6\u4E2D..."),p=xi(n,"utf-8"),u=!0,console.log(` [MergeTool] \u57FA\u7840\u7248\u672C\u5927\u5C0F: ${p.length} \u5B57\u7B26`));let g=Co(p);if(g===i){console.log(" [MergeTool] \u65E0\u5E76\u53D1\u4FEE\u6539\uFF08base === current\uFF09\uFF0C\u76F4\u63A5\u5199\u5165");let y=a;if(s===`\r
|
|
379
399
|
`&&(y=y.replace(/\n/g,`\r
|
|
380
|
-
`)),
|
|
381
|
-
`).length}\u884C, current=${c}\u884C, incoming=${l}\u884C`);let
|
|
382
|
-
`&&(
|
|
383
|
-
`)),S.hasConflicts)return
|
|
400
|
+
`)),Yn(t,y,"utf-8"),u)try{So(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(`
|
|
401
|
+
`).length}\u884C, current=${c}\u884C, incoming=${l}\u884C`);let m=Date.now(),S=Si(g,i,a),b=((Date.now()-m)/1e3).toFixed(2);console.log(` [MergeTool] threeWayMerge \u5B8C\u6210\uFF0C\u8017\u65F6 ${b}s, \u6709\u51B2\u7A81: ${S.hasConflicts}`);let f=S.merged;if(s===`\r
|
|
402
|
+
`&&(f=f.replace(/\n/g,`\r
|
|
403
|
+
`)),S.hasConflicts)return Yn(t,f,"utf-8"),`Merge completed with CONFLICTS. File saved with conflict markers.
|
|
384
404
|
Conflicts:
|
|
385
|
-
${S.conflicts.map(
|
|
405
|
+
${S.conflicts.map(x=>`Line ${x.lineNumber}: BASE="${x.base.substring(0,50)}..." | CURRENT="${x.current.substring(0,50)}..." | INCOMING="${x.incoming.substring(0,50)}..."`).join(`
|
|
386
406
|
`)}
|
|
387
407
|
|
|
388
|
-
Please resolve conflicts manually or use write() to overwrite.`;if(
|
|
408
|
+
Please resolve conflicts manually or use write() to overwrite.`;if(Yn(t,f,"utf-8"),u)try{So(n)}catch{}return"Merge successful (three-way merge, concurrent edits preserved)."}catch(t){return this.formatError("Merge",t)}}writeNewFile(e,t,n){try{let o=typeof n=="string"?n:String(n||"");if(Yn(e,o,"utf-8"),yo(t))try{So(t)}catch{}return`File created: ${e}`}catch(o){return this.formatError("Failed to create file",o)}}},bi=new at;Qt=bi});import{EOL as xo}from"os";function wi(r,e={}){let{preserveEscapes:t=!1,targetFormat:n="lf"}=e,o=r;if(t||(o=o.replace(/\\n/g,`
|
|
389
409
|
`).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\"/g,'"').replace(/\\'/g,"'")),o=o.replace(/\r\n/g,`
|
|
390
410
|
`).replace(/\r/g,`
|
|
391
411
|
`),n!=="preserve"&&n!=="lf")switch(n){case"crlf":o=o.replace(/\n/g,`\r
|
|
392
|
-
`);break;case"cr":o=o.replace(/\n/g,"\r");break;case"platform":
|
|
412
|
+
`);break;case"cr":o=o.replace(/\n/g,"\r");break;case"platform":xo===`\r
|
|
393
413
|
`&&(o=o.replace(/\n/g,`\r
|
|
394
|
-
`));break}return o}function
|
|
414
|
+
`));break}return o}function ol(r){if(!r)return{style:"none",dominant:xo,statistics:{crlf:0,lf:0,cr:0},confidence:0};let e={crlf:(r.match(/\r\n/g)||[]).length,lf:(r.match(/(?<!\r)\n/g)||[]).length,cr:(r.match(/\r(?!\n)/g)||[]).length},t=e.crlf+e.lf+e.cr;if(t===0)return{style:"none",dominant:xo,statistics:e,confidence:0};let n=`
|
|
395
415
|
`,o=e.lf,s="lf";e.crlf>o&&(n=`\r
|
|
396
|
-
`,o=e.crlf,s="crlf"),e.cr>o&&(n="\r",o=e.cr,s="cr");let i=o/t,a;return i===1||i>.8?a=s:a="mixed",{style:a,dominant:n,statistics:e,confidence:i}}var
|
|
416
|
+
`,o=e.crlf,s="crlf"),e.cr>o&&(n="\r",o=e.cr,s="cr");let i=o/t,a;return i===1||i>.8?a=s:a="mixed",{style:a,dominant:n,statistics:e,confidence:i}}var Kn,Ti=C(()=>{Kn=class{originalContent;normalizedContent;originalStyle;constructor(e){this.originalContent=e,this.originalStyle=ol(e),this.normalizedContent=wi(e,{preserveEscapes:!0,targetFormat:"lf"})}getNormalizedContent(){return this.normalizedContent}getOriginalStyle(){return this.originalStyle}restoreLineEndings(e){return this.originalStyle.style==="crlf"||this.originalStyle.dominant===`\r
|
|
397
417
|
`?e.replace(/\n/g,`\r
|
|
398
|
-
`):this.originalStyle.style==="cr"||this.originalStyle.dominant==="\r"?e.replace(/\n/g,"\r"):e}convertTo(e){return
|
|
418
|
+
`):this.originalStyle.style==="cr"||this.originalStyle.dominant==="\r"?e.replace(/\n/g,"\r"):e}convertTo(e){return wi(this.originalContent,{preserveEscapes:!0,targetFormat:e})}}});import{existsSync as sl,readFileSync as il,writeFileSync as al}from"fs";import{resolve as cl}from"path";function Zt(r,e){return ki.execute({path:r,operations:e})}var ct,ki,en,$i=C(()=>{J();Ti();ct=class extends I{getDefinition(){return{name:"search_replace",description:`Perform TARGETED SEARCH & REPLACE operations on files.
|
|
399
419
|
|
|
400
420
|
\u{1F3AF} PERFECT FOR:
|
|
401
421
|
- Small configuration updates (port numbers, URLs, etc.)
|
|
@@ -416,29 +436,29 @@ Please resolve conflicts manually or use write() to overwrite.`;if(qn(t,h,"utf-8
|
|
|
416
436
|
\u{1F4A1} TIPS:
|
|
417
437
|
- Use precise search text to avoid unintended replacements
|
|
418
438
|
- Test with small changes first
|
|
419
|
-
- 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=
|
|
439
|
+
- 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=cl(e.path);if(!sl(t))return this.formatError("SearchReplace",`File not found: ${t}`);let n=il(t,"utf-8"),o=new Kn(n),s=o.getOriginalStyle(),i=o.getNormalizedContent(),a=0,c=[];for(let[u,g]of e.operations.entries()){let{search:m,replace:S}=g;if(!m||m.trim().length===0){c.push(`\u274C Operation ${u+1}: empty search text`);continue}try{i.includes(m)?(i=i.replace(m,S),a++,c.push(`\u2705 Operation ${u+1}: "${m.substring(0,30)}..." \u2192 "${S.substring(0,30)}..."`)):c.push(`\u274C Operation ${u+1}: search text not found "${m.substring(0,30)}..."`)}catch(b){c.push(`\u274C Operation ${u+1}: ${b instanceof Error?b.message:String(b)}`)}}if(a>0){let u=o.restoreLineEndings(i);(s.style==="crlf"||s.dominant===`\r
|
|
420
440
|
`)&&(u=u.replace(/\n/g,`\r
|
|
421
|
-
`)),
|
|
441
|
+
`)),al(t,u,"utf-8")}let l=`Search/replace completed. ${a} of ${e.operations.length} operations applied successfully.`,p=c.length>0?`
|
|
422
442
|
|
|
423
443
|
Operation details:
|
|
424
444
|
${c.join(`
|
|
425
|
-
`)}`:"";return l+p}catch(t){return this.formatError("SearchReplace",t)}}formatError(e,t){let n=t instanceof Error?t.message:String(t);return`[${e} Error] ${n}`}},
|
|
426
|
-
`).forEach(o=>{let s=o.trim();s&&!s.startsWith("#")&&t.push(
|
|
445
|
+
`)}`:"";return l+p}catch(t){return this.formatError("SearchReplace",t)}}formatError(e,t){let n=t instanceof Error?t.message:String(t);return`[${e} Error] ${n}`}},ki=new ct;en=ki});var bo={};U(bo,{CopyTool:()=>it,DeleteTool:()=>ot,MergeTool:()=>at,MkdirTool:()=>nt,MoveTool:()=>st,ReadTool:()=>tt,SearchReplaceTool:()=>ct,WriteTool:()=>rt,copyFile:()=>Yt,copyTool:()=>Kt,deleteFile:()=>Gt,deleteTool:()=>zt,merge:()=>Xt,mergeTool:()=>Qt,mkdir:()=>Wt,mkdirTool:()=>Le,moveFile:()=>qt,moveTool:()=>Bt,read:()=>Ut,readTool:()=>Vt,searchReplace:()=>Zt,searchReplaceTool:()=>en,write:()=>Ht,writeTool:()=>Jt});var Xn=C(()=>{ei();si();fo();ii();li();yi();vi();$i()});import{readFileSync as ll,existsSync as ul}from"fs";import{resolve as gl}from"path";function ml(r){let e=gl(r,".niumignore"),t=[];if(ul(e))try{ll(e,"utf-8").split(`
|
|
446
|
+
`).forEach(o=>{let s=o.trim();s&&!s.startsWith("#")&&t.push(dl(s))})}catch(n){console.warn(`Error reading .niumignore file: ${n instanceof Error?n.message:"Unknown error"}`)}return t}function lt(r,e=!0){let t=ml(r);return e?[...pl,...t]:t}function dl(r){if(r.startsWith("!")){let e=r.slice(1);return e.includes("/")||e.includes("\\")?r:`!**/${e}`}return r.includes("*")||r.includes("?")||r.includes("{")||r.includes("[")?r:r.endsWith("/")?`**/${r.slice(0,-1)}/**`:r.startsWith("*.")?r:!r.includes("/")&&!r.includes("\\")?`**/${r}/**`:r}var pl,Qn=C(()=>{pl=["**/.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 Pi}from"glob";function tn(r){return Mi.execute({pattern:r})}var ut,Mi,nn,Ei=C(()=>{J();Qn();ut=class extends I{getDefinition(){return{name:"glob",description:`Search for files matching a glob pattern.
|
|
427
447
|
|
|
428
448
|
Examples:
|
|
429
449
|
- glob("*.js") - all .js files in current directory
|
|
430
450
|
- glob("**/*.ts") - all .ts files recursively
|
|
431
451
|
- glob("src/**/*.{js,ts}") - all .js and .ts files under src/
|
|
432
452
|
|
|
433
|
-
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=lt(t),o=
|
|
453
|
+
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=lt(t),o=Pi(e.pattern,{nodir:!0,cwd:e.cwd,ignore:n});if(o.length===0&&!e.pattern.startsWith("*")&&!e.pattern.startsWith("**")){let s=`**/${e.pattern}`;o=Pi(s,{nodir:!0,cwd:e.cwd,ignore:n})}return o.length>0?o:`No files matching pattern: ${e.pattern}`}catch(t){return this.formatError("Glob pattern",t)}}},Mi=new ut;nn=Mi});import{readFileSync as Ii}from"fs";import{dirname as fl}from"path";import{globSync as hl}from"glob";function rn(r,e){return Ai.execute({pattern:r,path:e})}var gt,Ai,on,Li=C(()=>{J();Qn();gt=class extends I{getDefinition(){return{name:"grep",description:`Search for text patterns in files using regular expressions.
|
|
434
454
|
|
|
435
455
|
Examples:
|
|
436
456
|
- grep("function.*foo", "src/main.js") - find function definitions containing "foo" in a single file
|
|
437
457
|
- grep("TODO", "**/*.js") - find all TODOs in all JavaScript files
|
|
438
458
|
- grep("import", "src/**/*.{js,ts}") - find all import statements in JavaScript and TypeScript files
|
|
439
459
|
|
|
440
|
-
Returns an array of matching lines with filenames and line numbers.`,input_schema:{type:"object",properties:{pattern:{type:"string",description:"The regex pattern to search for"},path:{type:"string",description:'File path or glob pattern to search in (e.g., "src/main.js" or "**/*.js")'}},required:["pattern","path"]}}}execute(e){try{let t=[];try{let i=e.path.includes("/")||e.path.includes("\\")
|
|
441
|
-
`),l=[];c.forEach((p,u)=>{n.test(p)&&(l.push(`${i}:${u+1}: ${p}`),s++)}),l.length>0&&o.push(...l)}catch(a){o.push(`Error reading file ${i}: ${a instanceof Error?a.message:"Unknown error"}`)}}),s>0?(t.length>1&&o.unshift(`Found ${s} matches in ${t.length} files`),o):`No matches found for pattern: ${e.pattern} in ${t.length} files`}catch(t){return this.formatError("Grep",t)}}},
|
|
460
|
+
Returns an array of matching lines with filenames and line numbers.`,input_schema:{type:"object",properties:{pattern:{type:"string",description:"The regex pattern to search for"},path:{type:"string",description:'File path or glob pattern to search in (e.g., "src/main.js" or "**/*.js")'}},required:["pattern","path"]}}}execute(e){try{let t=[];try{let i=e.path.includes("/")||e.path.includes("\\")?fl(e.path):process.cwd(),c={nodir:!0,windowsPathsNoEscape:!0,absolute:!1,ignore:lt(i)};if(e.path.includes("*")||e.path.includes("?")||e.path.includes("{")){if(console.log(`Processing glob pattern: ${e.path}`),t=hl(e.path,c),t.length===0)return`No files found matching pattern: ${e.path}`;console.log(`Found ${t.length} files matching pattern`)}else try{let p=Ii(e.path,"utf-8");t=[e.path]}catch(p){return p instanceof Error?`Error: ${p.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),o=[],s=0;return t.forEach(i=>{try{let c=Ii(i,"utf-8").split(`
|
|
461
|
+
`),l=[];c.forEach((p,u)=>{n.test(p)&&(l.push(`${i}:${u+1}: ${p}`),s++)}),l.length>0&&o.push(...l)}catch(a){o.push(`Error reading file ${i}: ${a instanceof Error?a.message:"Unknown error"}`)}}),s>0?(t.length>1&&o.unshift(`Found ${s} matches in ${t.length} files`),o):`No matches found for pattern: ${e.pattern} in ${t.length} files`}catch(t){return this.formatError("Grep",t)}}},Ai=new gt;on=Ai});var vo={};U(vo,{GlobTool:()=>ut,GrepTool:()=>gt,glob:()=>tn,globTool:()=>nn,grep:()=>rn,grepTool:()=>on});var Zn=C(()=>{Ei();Li()});import{execSync as yl,exec as Sl,spawnSync as Cl}from"child_process";import*as er from"os";async function ji(){if(Di)return wo;Di=!0;try{let r=await import("iconv-lite");return wo=r.default||r,wo}catch{return console.warn("iconv-lite not available, using utf8 fallback for Windows encoding"),null}}function sn(r){return Promise.resolve(mt.execute(r))}var wo,Di,pt,mt,Oi=C(()=>{J();wo=null,Di=!1;pt=class r extends I{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 r.HIGH_RISK_COMMANDS.some(n=>t.includes(n.toLowerCase()))}getShellCommand(e){let t=er.platform(),n=e||"";return t==="win32"?{shell:"cmd.exe",args:[],cmd:n}:{shell:"/bin/sh",args:["-c"],cmd:n}}getDefinition(){return{name:"shell",description:`Execute a shell command on the system.
|
|
442
462
|
|
|
443
463
|
IMPORTANT SAFETY NOTES:
|
|
444
464
|
- High-risk commands (delete, format, etc.) require user confirmation
|
|
@@ -448,7 +468,7 @@ IMPORTANT SAFETY NOTES:
|
|
|
448
468
|
Examples:
|
|
449
469
|
- shell({ command: "ls -la" }) - List directory contents (Mac/Linux)
|
|
450
470
|
- shell({ command: "dir" }) - List directory contents (Windows)
|
|
451
|
-
- shell({ command: "npm install", timeout: 30000 }) - Run npm install with 30s timeout`,input_schema:{type:"object",properties:{command:{type:"string",description:"The shell command to execute"},timeout:{type:"number",description:"Optional timeout in milliseconds (default: 60000)",default:6e4},captureOutput:{type:"boolean",description:"Whether to capture and return command output (default: true)",default:!0}},required:["command"]},requiresConfirmation:!1}}getDynamicDefinition(e){return{...this.getDefinition(),requiresConfirmation:this.isHighRiskCommand(e.command)}}isCommandNotFoundError(e,t){let n=e.toLowerCase();return(t==="win32"?["\u4E0D\u662F\u5185\u90E8\u6216\u5916\u90E8\u547D\u4EE4","\u4E0D\u662F\u53EF\u8FD0\u884C\u7684\u7A0B\u5E8F","is not recognized as an internal or external command","is not recognized as","'command' is not recognized","\u627E\u4E0D\u5230\u547D\u4EE4","\u65E0\u6CD5\u5C06","command not found"]:["command not found","not found","no such file or directory","cannot find","bash: command not found","sh: command not found","zsh: command not found"]).some(a=>n.includes(a))}extractCommandName(e){let t=e.trim(),n=t.match(/^(\S+)/);return n?n[1]:t}generateCommandNotFoundMessage(e,t){let n=t==="win32"?"Windows":t==="darwin"?"macOS":"Linux",s={git:{win:"Download from https://git-scm.com/download/win or use 'winget install Git.Git'",unix:"Install using: sudo apt-get install git (Ubuntu/Debian) or brew install git (macOS)",description:"Version control system"},python:{win:"Download from https://www.python.org/downloads/ or use 'winget install Python.Python.3'",unix:"Install using: sudo apt-get install python3 (Ubuntu/Debian) or brew install python3 (macOS)",description:"Python programming language"},node:{win:"Download from https://nodejs.org/ or use 'winget install OpenJS.NodeJS'",unix:"Install using: sudo apt-get install nodejs (Ubuntu/Debian) or brew install node (macOS)",description:"Node.js JavaScript runtime"},npm:{win:"Install Node.js from https://nodejs.org/ (includes npm)",unix:"Install Node.js (includes npm): sudo apt-get install nodejs npm or brew install node",description:"Node Package Manager (comes with Node.js)"},docker:{win:"Download Docker Desktop from https://www.docker.com/products/docker-desktop",unix:"Install using: sudo apt-get install docker.io (Ubuntu/Debian) or brew install docker (macOS)",description:"Container platform"},curl:{win:"Usually built-in on Windows 10+. If missing, download from https://curl.se/windows/",unix:"Install using: sudo apt-get install curl (Ubuntu/Debian) or brew install curl (macOS)",description:"Command-line tool for transferring data with URLs"},wget:{win:"Download from https://eternallybored.org/misc/wget/ or use 'winget install GNU.Wget'",unix:"Install using: sudo apt-get install wget (Ubuntu/Debian) or brew install wget (macOS)",description:"Network downloader"},make:{win:"Install via Chocolatey: choco install make or use WSL",unix:"Install using: sudo apt-get install build-essential (Ubuntu/Debian) or xcode-select --install (macOS)",description:"Build automation tool"},gcc:{win:"Install MinGW from http://mingw.org/ or use Visual Studio Build Tools",unix:"Install using: sudo apt-get install build-essential (Ubuntu/Debian) or xcode-select --install (macOS)",description:"GNU Compiler Collection"},code:{win:"Install VS Code from https://code.visualstudio.com/ and add to PATH during installation",unix:"Install VS Code and run: sudo ln -s /Applications/Visual\\ Studio\\ Code.app/Contents/Resources/app/bin/code /usr/local/bin/code",description:"Visual Studio Code editor"}}[e.toLowerCase()],i=`\u274C Command Not Found: '${e}'
|
|
471
|
+
- shell({ command: "npm install", timeout: 30000 }) - Run npm install with 30s timeout`,input_schema:{type:"object",properties:{command:{type:"string",description:"The shell command to execute"},timeout:{type:"number",description:"Optional timeout in milliseconds (default: 60000)",default:6e4},captureOutput:{type:"boolean",description:"Whether to capture and return command output (default: true)",default:!0}},required:["command"]},requiresConfirmation:!1}}getDynamicDefinition(e){return{...this.getDefinition(),requiresConfirmation:this.isHighRiskCommand(e.command)}}isCommandNotFoundError(e,t){if(!e)return!1;let n=e.toLowerCase();return(t==="win32"?["\u4E0D\u662F\u5185\u90E8\u6216\u5916\u90E8\u547D\u4EE4","\u4E0D\u662F\u53EF\u8FD0\u884C\u7684\u7A0B\u5E8F","is not recognized as an internal or external command","is not recognized as","'command' is not recognized","\u627E\u4E0D\u5230\u547D\u4EE4","\u65E0\u6CD5\u5C06","command not found"]:["command not found","not found","no such file or directory","cannot find","bash: command not found","sh: command not found","zsh: command not found"]).some(a=>n.includes(a))}extractCommandName(e){let t=e?e.trim():"",n=t.match(/^(\S+)/);return n?n[1]:t}generateCommandNotFoundMessage(e,t){let n=t==="win32"?"Windows":t==="darwin"?"macOS":"Linux",s={git:{win:"Download from https://git-scm.com/download/win or use 'winget install Git.Git'",unix:"Install using: sudo apt-get install git (Ubuntu/Debian) or brew install git (macOS)",description:"Version control system"},python:{win:"Download from https://www.python.org/downloads/ or use 'winget install Python.Python.3'",unix:"Install using: sudo apt-get install python3 (Ubuntu/Debian) or brew install python3 (macOS)",description:"Python programming language"},node:{win:"Download from https://nodejs.org/ or use 'winget install OpenJS.NodeJS'",unix:"Install using: sudo apt-get install nodejs (Ubuntu/Debian) or brew install node (macOS)",description:"Node.js JavaScript runtime"},npm:{win:"Install Node.js from https://nodejs.org/ (includes npm)",unix:"Install Node.js (includes npm): sudo apt-get install nodejs npm or brew install node",description:"Node Package Manager (comes with Node.js)"},docker:{win:"Download Docker Desktop from https://www.docker.com/products/docker-desktop",unix:"Install using: sudo apt-get install docker.io (Ubuntu/Debian) or brew install docker (macOS)",description:"Container platform"},curl:{win:"Usually built-in on Windows 10+. If missing, download from https://curl.se/windows/",unix:"Install using: sudo apt-get install curl (Ubuntu/Debian) or brew install curl (macOS)",description:"Command-line tool for transferring data with URLs"},wget:{win:"Download from https://eternallybored.org/misc/wget/ or use 'winget install GNU.Wget'",unix:"Install using: sudo apt-get install wget (Ubuntu/Debian) or brew install wget (macOS)",description:"Network downloader"},make:{win:"Install via Chocolatey: choco install make or use WSL",unix:"Install using: sudo apt-get install build-essential (Ubuntu/Debian) or xcode-select --install (macOS)",description:"Build automation tool"},gcc:{win:"Install MinGW from http://mingw.org/ or use Visual Studio Build Tools",unix:"Install using: sudo apt-get install build-essential (Ubuntu/Debian) or xcode-select --install (macOS)",description:"GNU Compiler Collection"},code:{win:"Install VS Code from https://code.visualstudio.com/ and add to PATH during installation",unix:"Install VS Code and run: sudo ln -s /Applications/Visual\\ Studio\\ Code.app/Contents/Resources/app/bin/code /usr/local/bin/code",description:"Visual Studio Code editor"}}[e.toLowerCase()],i=`\u274C Command Not Found: '${e}'
|
|
452
472
|
|
|
453
473
|
`;return i+=`\u{1F5A5}\uFE0F Current Environment: ${n}
|
|
454
474
|
|
|
@@ -473,9 +493,13 @@ Examples:
|
|
|
473
493
|
`,i+=` - dnf: sudo dnf install <package-name> (Fedora)
|
|
474
494
|
`))),i+=`
|
|
475
495
|
\u26A0\uFE0F Please install the required command before proceeding.
|
|
476
|
-
`,i+=" The AI assistant cannot continue without this tool being available.",i}async execute(e){try{let{command:t,timeout:n=6e4,captureOutput:o=!0}=e
|
|
496
|
+
`,i+=" The AI assistant cannot continue without this tool being available.",i}async execute(e){try{let{command:t,timeout:n=6e4,captureOutput:o=!0}=e;if(!t){let g=er.platform(),S=`Running on ${g} with ${g==="win32"?"cmd.exe":"/bin/sh"}`,b=`Executing command: ${t}`;return this.createToolResult({error:"Command is undefined or null",success:!1},`${S}
|
|
497
|
+
${b}
|
|
498
|
+
|
|
499
|
+
Command failed with error:
|
|
500
|
+
TypeError: Command is undefined or null`)}let s=er.platform(),{shell:i,args:a,cmd:c}=this.getShellCommand(t),l={shell:i,timeout:n,encoding:"utf8",windowsHide:!0,windowsVerbatimArguments:s==="win32"},p=`Running on ${s} with ${i}`,u=`Executing command: ${t}`;if(o)try{let g="";if(s==="win32"){let m=`chcp 65001 >nul 2>&1 && ${c}`,S=Cl("cmd.exe",["/c",m],{stdio:"pipe",windowsHide:!0,encoding:"buffer"}),b=S.stdout||Buffer.alloc(0),f=S.stderr||Buffer.alloc(0),y=Buffer.concat([b,f]);try{let x=await ji();if(x){let d=["cp936","gbk","utf8","gb2312","big5"],k=!1;for(let T of d)try{if(g=x.decode(y,T),/[\u4e00-\u9fff]/.test(g)||g.length>0){k=!0;break}}catch{continue}k||(g=y.toString("utf8"))}else g=y.toString("utf8");S.status===0&&g&&g.trim()&&(g+=`
|
|
477
501
|
|
|
478
|
-
\u2705 Windows\u7F16\u7801\u5DF2\u4F18\u5316\u5904\u7406`)}catch{g=y.toString("utf8")}}else{let
|
|
502
|
+
\u2705 Windows\u7F16\u7801\u5DF2\u4F18\u5316\u5904\u7406`)}catch{g=y.toString("utf8")}}else{let m=[...a,c].join(" ");g=yl(m,l).toString()}if(this.isCommandNotFoundError(g,s)){let m=this.extractCommandName(t),S=this.generateCommandNotFoundMessage(m,s);return this.createToolResult({error:g,success:!1,commandNotFound:!0},`${p}
|
|
479
503
|
${u}
|
|
480
504
|
|
|
481
505
|
${S}
|
|
@@ -485,20 +509,20 @@ ${g}`,!0)}return this.createToolResult({output:g,success:!0},`${p}
|
|
|
485
509
|
${u}
|
|
486
510
|
|
|
487
511
|
Command output:
|
|
488
|
-
${g}`)}catch(g){let
|
|
512
|
+
${g}`)}catch(g){let m="";if(s==="win32"&&g.stderr){let S=Buffer.isBuffer(g.stderr)?g.stderr:Buffer.from(g.stderr),b=await ji();if(b)try{let f=["cp936","gbk","utf8","gb2312"],y="";for(let x of f)try{if(y=b.decode(S,x),y.length>0){m+=y;break}}catch{continue}y||(m+=S.toString("utf8"))}catch{m+=S.toString("utf8")}else m+=S.toString("utf8")}else g.stderr&&(m+=g.stderr),g.stdout&&(m+=g.stdout),m||(m=String(g));if(this.isCommandNotFoundError(m,s)){let S=this.extractCommandName(t),b=this.generateCommandNotFoundMessage(S,s);return this.createToolResult({error:m,success:!1,commandNotFound:!0},`${p}
|
|
489
513
|
${u}
|
|
490
514
|
|
|
491
|
-
${
|
|
515
|
+
${b}
|
|
492
516
|
|
|
493
517
|
Original error:
|
|
494
|
-
${
|
|
518
|
+
${m}`,!0)}return this.createToolResult({error:m,success:!1},`${p}
|
|
495
519
|
${u}
|
|
496
520
|
|
|
497
521
|
Command failed with error:
|
|
498
|
-
${
|
|
522
|
+
${m}`,!0)}else{let g=t;s==="win32"?g=`chcp 65001 > nul && ${c}`:g=[...a,c].join(" ");let m=Sl(g,l);return this.createToolResult({success:!0,message:"Command started in background"},`${p}
|
|
499
523
|
${u}
|
|
500
524
|
|
|
501
|
-
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}},mt=new pt});var
|
|
525
|
+
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}},mt=new pt});var To={};U(To,{ShellTool:()=>pt,shell:()=>sn,shellTool:()=>mt});var tr=C(()=>{Oi()});var $o={};U($o,{THINK_TOOL:()=>nr,ThinkTool:()=>De,extractThought:()=>rr,isThinkTool:()=>ht,think:()=>dt,thinkTool:()=>ft});function dt(r){return ko.execute({thought:r})}function ht(r){return r==="think"}function rr(r){if(!r||!r.function||r.function.name!=="think")return null;try{return JSON.parse(r.function.arguments).thought||null}catch{return null}}var De,ko,ft,nr,an=C(()=>{J();De=class extends I{getDefinition(){return{name:"think",description:`Use this tool to think, reason, and reflect before taking actions.
|
|
502
526
|
This is a zero-side-effect tool that makes your thinking process observable.
|
|
503
527
|
|
|
504
528
|
IMPORTANT: You should call this tool:
|
|
@@ -506,7 +530,7 @@ IMPORTANT: You should call this tool:
|
|
|
506
530
|
- AFTER receiving an Observation (to reflect on the result)
|
|
507
531
|
- When you need to analyze complex situations
|
|
508
532
|
|
|
509
|
-
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."}},
|
|
533
|
+
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."}},ko=new De;ft=ko,nr=ko.getDefinition()});var Lo={};U(Lo,{SYSTEM_PROMPT:()=>yt,generateAgentMatchingPrompt:()=>Ao,generateSystemPrompt:()=>Ri,generateTaskComplexityEvaluationPrompt:()=>Po,generateTaskPlanningConversionPrompt:()=>Io,generateTaskPlanningMarkdownPrompt:()=>Eo,generateTaskPlanningPrompt:()=>Mo});function Ri(r=cn()){return`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.
|
|
510
534
|
|
|
511
535
|
<instructions>
|
|
512
536
|
You have access to a comprehensive set of tools, with the 'think' tool being specially designed for observable reasoning.
|
|
@@ -560,10 +584,15 @@ When modifying existing code:
|
|
|
560
584
|
1. Call think() to plan your approach and identify risks
|
|
561
585
|
2. Call read() to get the CURRENT file content
|
|
562
586
|
3. After Observation, call think() to analyze and prepare the COMPLETE NEW version with all changes
|
|
563
|
-
4.
|
|
564
|
-
-
|
|
565
|
-
-
|
|
566
|
-
|
|
587
|
+
4. If you're modifying a function signature, class interface, or exported variable:
|
|
588
|
+
- Call grep() to find ALL references to the modified entity across the codebase
|
|
589
|
+
- Analyze the search results to identify all files that need updates
|
|
590
|
+
- Plan how to update each reference appropriately
|
|
591
|
+
5. Choose the appropriate tool:
|
|
592
|
+
- Use merge() for comprehensive changes to individual files
|
|
593
|
+
- Use search_replace() for batch updates across multiple files (e.g., updating function calls)
|
|
594
|
+
6. If conflicts occur, call think() to decide whether to fix or use write() to overwrite
|
|
595
|
+
7. After making changes, verify the updates by calling grep() again to ensure all references are correctly updated
|
|
567
596
|
|
|
568
597
|
When creating new files:
|
|
569
598
|
1. Call think() to plan the file structure and design
|
|
@@ -584,6 +613,7 @@ CRITICAL FILE OPERATION RULES:
|
|
|
584
613
|
- Read the file first, prepare the full new version, then call merge() or write()
|
|
585
614
|
- NEVER skip the thinking steps - they make your reasoning observable and debuggable
|
|
586
615
|
- NEVER modify files without first reading their current content
|
|
616
|
+
- ALWAYS check for and update all references when modifying function signatures, interfaces, or exported entities
|
|
587
617
|
|
|
588
618
|
FILE PATH SAFETY CONSTRAINTS:
|
|
589
619
|
- ONLY write files within the current working directory (project root)
|
|
@@ -772,7 +802,7 @@ The key difference from traditional tool calling:
|
|
|
772
802
|
|
|
773
803
|
This makes your decision-making process transparent, debuggable, and more reliable. Always prioritize clarity and thoroughness in your thinking process.
|
|
774
804
|
</final_note>
|
|
775
|
-
</instructions>`}function
|
|
805
|
+
</instructions>`}function Po(r){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
|
|
776
806
|
|
|
777
807
|
\u4EFB\u52A1\u63CF\u8FF0\uFF1A
|
|
778
808
|
${r}
|
|
@@ -782,7 +812,7 @@ ${r}
|
|
|
782
812
|
- 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
|
|
783
813
|
- 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
|
|
784
814
|
|
|
785
|
-
\u8BF7\u53EA\u56DE\u590D "SIMPLE"\u3001"MEDIUM" \u6216 "COMPLEX"\uFF0C\u4E0D\u8981\u6709\u5176\u4ED6\u5185\u5BB9\u3002`}function
|
|
815
|
+
\u8BF7\u53EA\u56DE\u590D "SIMPLE"\u3001"MEDIUM" \u6216 "COMPLEX"\uFF0C\u4E0D\u8981\u6709\u5176\u4ED6\u5185\u5BB9\u3002`}function Mo(r,e=[]){let t=e.length>0?e.map(o=>`${o.name}(${o.description})`).join(", "):"default",n=e.length>0?`
|
|
786
816
|
|
|
787
817
|
\u53EF\u7528\u7684\u5B50\u667A\u80FD\u4F53\uFF1A
|
|
788
818
|
${e.map(o=>`- ${o.name}: ${o.description}`).join(`
|
|
@@ -875,7 +905,7 @@ ${n}
|
|
|
875
905
|
}
|
|
876
906
|
\`\`\`
|
|
877
907
|
|
|
878
|
-
\u8BF7\u4F7F\u7528 create_task_plan \u5DE5\u5177\u8FD4\u56DE\u7ED3\u6784\u5316\u7684\u4EFB\u52A1\u89C4\u5212\u3002`}function
|
|
908
|
+
\u8BF7\u4F7F\u7528 create_task_plan \u5DE5\u5177\u8FD4\u56DE\u7ED3\u6784\u5316\u7684\u4EFB\u52A1\u89C4\u5212\u3002`}function Eo(r,e=[]){let t=e.length>0?`
|
|
879
909
|
\u53EF\u7528\u7684\u5B50\u667A\u80FD\u4F53\uFF1A
|
|
880
910
|
${e.map(n=>`- ${n.name}: ${n.description}`).join(`
|
|
881
911
|
`)}`:"";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
|
|
@@ -909,11 +939,11 @@ ${t}
|
|
|
909
939
|
- \u6B65\u9AA4\u4E4B\u95F4\u5FC5\u987B\u6709\u660E\u786E\u7684\u4F9D\u8D56\u5173\u7CFB\u548C\u987A\u5E8F\u903B\u8F91
|
|
910
940
|
- \u6BCF\u4E2A\u6B65\u9AA4\u5FC5\u987B\u6807\u6CE8\u6700\u9002\u5408\u7684\u63A8\u8350\u5B50\u667A\u80FD\u4F53
|
|
911
941
|
- \u4EFB\u52A1\u6982\u8FF0\u5E94\u8BE5\u7B80\u660E\u627C\u8981\u5730\u6982\u62EC\u6574\u4E2A\u4EFB\u52A1\u7684\u76EE\u7684\u548C\u8303\u56F4
|
|
912
|
-
- \u9884\u671F\u7ED3\u679C\u5E94\u8BE5\u5177\u4F53\u3001\u53EF\u8861\u91CF\uFF0C\u660E\u786E\u8BF4\u660E\u5B8C\u6210\u540E\u7684\u72B6\u6001`}function
|
|
942
|
+
- \u9884\u671F\u7ED3\u679C\u5E94\u8BE5\u5177\u4F53\u3001\u53EF\u8861\u91CF\uFF0C\u660E\u786E\u8BF4\u660E\u5B8C\u6210\u540E\u7684\u72B6\u6001`}function Io(r){return`\u8BF7\u5C06\u4EE5\u4E0B Markdown \u683C\u5F0F\u7684\u4EFB\u52A1\u89C4\u5212\u8F6C\u6362\u4E3A\u7ED3\u6784\u5316\u683C\u5F0F\u3002
|
|
913
943
|
|
|
914
944
|
${r}
|
|
915
945
|
|
|
916
|
-
\u8BF7\u4F7F\u7528 create_task_plan \u5DE5\u5177\u8FD4\u56DE\u7ED3\u6784\u5316\u7684\u4EFB\u52A1\u89C4\u5212\u6570\u636E\u3002`}function
|
|
946
|
+
\u8BF7\u4F7F\u7528 create_task_plan \u5DE5\u5177\u8FD4\u56DE\u7ED3\u6784\u5316\u7684\u4EFB\u52A1\u89C4\u5212\u6570\u636E\u3002`}function Ao(r,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
|
|
917
947
|
|
|
918
948
|
\u4EFB\u52A1\u63CF\u8FF0\uFF1A
|
|
919
949
|
${r}
|
|
@@ -927,7 +957,7 @@ ${e}
|
|
|
927
957
|
3. \u667A\u80FD\u4F53\u7684\u4E13\u957F\u662F\u5426\u80FD\u591F\u89E3\u51B3\u4EFB\u52A1\u4E2D\u7684\u6838\u5FC3\u6311\u6218
|
|
928
958
|
4. \u8003\u8651\u4EFB\u52A1\u7684\u590D\u6742\u5EA6\u548C\u667A\u80FD\u4F53\u7684\u5904\u7406\u80FD\u529B
|
|
929
959
|
|
|
930
|
-
\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 yt,
|
|
960
|
+
\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 yt,je=C(()=>{St();yt=Ri()});var be={};U(be,{TaskComplexity:()=>or,evaluateTaskComplexity:()=>xl,generatePlanSummary:()=>un,generateTaskPlan:()=>ln,getTaskFilePath:()=>$l,listTaskPlans:()=>Ml,loadTaskPlan:()=>Pl,updateTaskStatus:()=>Oe});import L from"chalk";import oe from"fs";import le from"path";async function xl(r){let e=Po(r);try{let t=await Z({model:fe(),messages:[{role:"user",content:e}],temperature:.1,max_tokens:10,useCompression:!0}),{content:n}=t.choices[0].message;return(n?n.trim():"").toUpperCase().includes("COMPLEX")?(console.log(L.yellow("[\u4EFB\u52A1\u8BC4\u4F30] \u68C0\u6D4B\u5230\u590D\u6742\u4EFB\u52A1\uFF0C\u5C06\u8FDB\u884C\u4EFB\u52A1\u89C4\u5212")),or.COMPLEX):(console.log(L.blue("[\u4EFB\u52A1\u8BC4\u4F30] \u68C0\u6D4B\u5230\u7B80\u5355\u4EFB\u52A1\uFF0C\u4F7F\u7528\u5355\u6B65\u9AA4\u6A21\u5F0F")),or.SIMPLE)}catch(t){return console.log(L.yellow(`[\u4EFB\u52A1\u8BC4\u4F30] \u8BC4\u4F30\u5931\u8D25\uFF0C\u9ED8\u8BA4\u4E3A\u7B80\u5355\u4EFB\u52A1: ${t.message}`)),or.SIMPLE}}function Fi(r=[]){let e=r.length>0?r.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
|
|
931
961
|
\u5E38\u7528\u5DE5\u5177\u7EC4\u5408\uFF1A
|
|
932
962
|
- \u53EA\u8BFB\u5206\u6790: ["read", "glob", "grep", "quickProjectScan", "think", "askUser"]
|
|
933
963
|
- \u4EE3\u7801\u63A2\u7D22: ["read", "glob", "grep", "quickProjectScan", "shell", "think"]
|
|
@@ -935,7 +965,7 @@ ${e}
|
|
|
935
965
|
- \u6D4B\u8BD5\u9A8C\u8BC1: ["read", "shell", "glob", "grep", "think"]
|
|
936
966
|
|
|
937
967
|
\u5982\u679C\u4E3A\u7A7A\u6570\u7EC4\u6216\u4E0D\u6307\u5B9A\uFF0C\u5219\u4F7F\u7528\u6240\u6709\u53EF\u7528\u5DE5\u5177\u3002
|
|
938
|
-
\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
|
|
968
|
+
\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 bl(r,e=[]){console.log(L.blue("[\u4EFB\u52A1\u89C4\u5212] \u5C1D\u8BD5\u65B9\u68481: Function Calling"));let t=Mo(r,e),n=Fi(e),s=(await Z({model:de(),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 vl(r,e=[]){console.log(L.yellow("[\u4EFB\u52A1\u89C4\u5212] \u5C1D\u8BD5\u65B9\u68482: Markdown + Function Call \u8F6C\u6362"));let t=Eo(r,e),o=(await Z({model:de(),messages:[{role:"user",content:t}],temperature:.3,max_tokens:2e3}))?.choices?.[0]?.message?.content||"";if(!o)throw new Error("\u65E0\u6CD5\u751F\u6210 Markdown \u89C4\u5212");let s=Io(o),i=Fi(e),c=(await Z({model:de(),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=o,l}function wl(r){return console.log(L.yellow("[\u4EFB\u52A1\u89C4\u5212] \u4F7F\u7528\u9ED8\u8BA4\u964D\u7EA7\u65B9\u6848")),{overview:r,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 Tl(r){let e=r.steps.map((t,n)=>`- [ ] ${t.description}
|
|
939
969
|
- \u63A8\u8350\u5B50\u667A\u80FD\u4F53: ${t.subAgent}`).join(`
|
|
940
970
|
|
|
941
971
|
`);return`# \u4EFB\u52A1\u89C4\u5212
|
|
@@ -947,29 +977,29 @@ ${r.overview}
|
|
|
947
977
|
${e}
|
|
948
978
|
|
|
949
979
|
## \u9884\u671F\u7ED3\u679C
|
|
950
|
-
${r.expectedResult}`}async function
|
|
980
|
+
${r.expectedResult}`}async function ln(r,e=[]){if(!r||typeof r!="string")throw new Error("\u65E0\u6548\u7684\u7528\u6237\u8BF7\u6C42");console.log(L.blue("[\u4EFB\u52A1\u89C4\u5212] \u6B63\u5728\u751F\u6210\u4EFB\u52A1\u89C4\u5212..."));let t=null,n="unknown";try{t=await bl(r,e),n="Function Calling",console.log(L.green("[\u4EFB\u52A1\u89C4\u5212] \u2713 Function Calling \u65B9\u6848\u6210\u529F"))}catch(c){console.log(L.yellow(`[\u4EFB\u52A1\u89C4\u5212] Function Calling \u5931\u8D25: ${c.message}`));try{t=await vl(r,e),n="Markdown + Conversion",console.log(L.green("[\u4EFB\u52A1\u89C4\u5212] \u2713 Markdown \u8F6C\u6362\u65B9\u6848\u6210\u529F"))}catch(l){console.log(L.yellow(`[\u4EFB\u52A1\u89C4\u5212] Markdown \u8F6C\u6362\u5931\u8D25: ${l.message}`)),t=wl(r),n="Default Fallback",console.log(L.yellow("[\u4EFB\u52A1\u89C4\u5212] \u26A0 \u4F7F\u7528\u9ED8\u8BA4\u964D\u7EA7\u65B9\u6848"))}}let o=t.markdown||Tl(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=Vn(),a={markdown:o,tasks:s,taskId:i,strategy:n};return await kl(o,i,a),console.log(L.green(`[\u4EFB\u52A1\u89C4\u5212] \u2713 \u4EFB\u52A1\u89C4\u5212\u751F\u6210\u5B8C\u6210 (\u7B56\u7565: ${n})`)),console.log(L.cyan(`[\u4EFB\u52A1\u89C4\u5212] \u5171\u5305\u542B ${s.length} \u4E2A\u4EFB\u52A1\u6B65\u9AA4`)),console.log(L.gray("\u2500".repeat(50))),console.log(o),console.log(L.gray("\u2500".repeat(50))),a}async function kl(r,e,t){let n=le.join(process.cwd(),".nium","tasks");oe.existsSync(n)||oe.mkdirSync(n,{recursive:!0});let o=`# \u4EFB\u52A1\u89C4\u5212 (ID: ${e})
|
|
951
981
|
|
|
952
982
|
## \u4EFB\u52A1\u6982\u8FF0
|
|
953
983
|
${r.substring(r.indexOf("## \u4EFB\u52A1\u6982\u8FF0")+7)}
|
|
954
984
|
|
|
955
985
|
## \u66F4\u65B0\u65F6\u95F4
|
|
956
|
-
${new Date().toLocaleString()}`,s=
|
|
957
|
-
`),a=!1,c=1,l=[];for(let p of i){if(p.trim().includes("## \u6267\u884C\u6B65\u9AA4")||p.trim().includes("##\u6267\u884C\u6B65\u9AA4")){a=!0,l.push(p);continue}if(p.trim().includes("## \u66F4\u65B0\u65F6\u95F4")){l.push("## \u66F4\u65B0\u65F6\u95F4"),l.push(new Date().toLocaleString());continue}if(a&&p.trim().startsWith("##")&&!p.trim().includes("\u66F4\u65B0\u65F6\u95F4")){a=!1,l.push(p);continue}if(a){let u=p.trim().match(/^-\s*\[(.)\]\s*(.+)/);if(u&&c===e){let g=" ";t==="in_progress"&&(g="-"),t==="completed"&&(g="x"),l.push(`- [${g}] ${u[2]}`),c++;continue}u&&c++}l.push(p)}return
|
|
958
|
-
`),"utf8"),console.log(
|
|
986
|
+
${new Date().toLocaleString()}`,s=le.join(n,`${e}.md`);if(oe.writeFileSync(s,o,"utf8"),console.log(L.green(`[\u4EFB\u52A1\u6587\u4EF6] \u4EFB\u52A1\u89C4\u5212\u5DF2\u4FDD\u5B58\u5230: ${s}`)),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=le.join(n,`${e}.json`);oe.writeFileSync(a,JSON.stringify(i,null,2),"utf8"),console.log(L.green(`[\u4EFB\u52A1\u6587\u4EF6] JSON \u6570\u636E\u5DF2\u4FDD\u5B58\u5230: ${a}`))}}async function Oe(r,e,t){let n=le.join(process.cwd(),".nium","tasks"),o=le.join(n,`${r}.md`);if(!oe.existsSync(o))return console.log(L.red(`[\u4EFB\u52A1\u66F4\u65B0] \u4EFB\u52A1\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`)),!1;try{let i=oe.readFileSync(o,"utf8").split(`
|
|
987
|
+
`),a=!1,c=1,l=[];for(let p of i){if(p.trim().includes("## \u6267\u884C\u6B65\u9AA4")||p.trim().includes("##\u6267\u884C\u6B65\u9AA4")){a=!0,l.push(p);continue}if(p.trim().includes("## \u66F4\u65B0\u65F6\u95F4")){l.push("## \u66F4\u65B0\u65F6\u95F4"),l.push(new Date().toLocaleString());continue}if(a&&p.trim().startsWith("##")&&!p.trim().includes("\u66F4\u65B0\u65F6\u95F4")){a=!1,l.push(p);continue}if(a){let u=p.trim().match(/^-\s*\[(.)\]\s*(.+)/);if(u&&c===e){let g=" ";t==="in_progress"&&(g="-"),t==="completed"&&(g="x"),l.push(`- [${g}] ${u[2]}`),c++;continue}u&&c++}l.push(p)}return oe.writeFileSync(o,l.join(`
|
|
988
|
+
`),"utf8"),console.log(L.green(`[\u4EFB\u52A1\u66F4\u65B0] \u4EFB\u52A1 ${r} \u6B65\u9AA4 ${e} \u72B6\u6001\u5DF2\u66F4\u65B0\u4E3A ${t}`)),!0}catch(s){return console.log(L.red(`[\u4EFB\u52A1\u66F4\u65B0] \u66F4\u65B0\u4EFB\u52A1\u72B6\u6001\u5931\u8D25: ${s.message}`)),!1}}function $l(r){let e=le.join(process.cwd(),".nium","tasks");return le.join(e,`${r}.md`)}function Pl(r){let e=le.join(process.cwd(),".nium","tasks"),t=le.join(e,`${r}.json`);if(!oe.existsSync(t))return console.log(L.red(`[\u4EFB\u52A1\u52A0\u8F7D] \u4EFB\u52A1\u6587\u4EF6\u4E0D\u5B58\u5728: ${t}`)),null;try{let n=oe.readFileSync(t,"utf8"),o=JSON.parse(n);return console.log(L.green(`[\u4EFB\u52A1\u52A0\u8F7D] \u6210\u529F\u52A0\u8F7D\u4EFB\u52A1: ${r}`)),o}catch(n){return console.log(L.red(`[\u4EFB\u52A1\u52A0\u8F7D] \u89E3\u6790\u4EFB\u52A1\u6587\u4EF6\u5931\u8D25: ${n.message}`)),null}}function Ml(){let r=le.join(process.cwd(),".nium","tasks");return oe.existsSync(r)?oe.readdirSync(r).filter(n=>n.endsWith(".json")).map(n=>n.replace(".json","")):[]}function un(r){if(!r||!r.tasks||r.tasks.length===0)return"\u65E0\u6709\u6548\u4EFB\u52A1\u6B65\u9AA4";let e=L.cyan(`
|
|
959
989
|
\u{1F4CB} \u4EFB\u52A1\u89C4\u5212\u6458\u8981:
|
|
960
|
-
`);e+=
|
|
961
|
-
`;for(let t of r.tasks){let n=t.subAgent!=="default"?
|
|
962
|
-
`}return e+=
|
|
963
|
-
`),
|
|
964
|
-
`)}function
|
|
965
|
-
`)}function
|
|
990
|
+
`);e+=L.gray("\u2500".repeat(50))+`
|
|
991
|
+
`;for(let t of r.tasks){let n=t.subAgent!=="default"?L.green(`[${t.subAgent}]`):L.gray("[\u9ED8\u8BA4\u667A\u80FD\u4F53]");e+=`${t.step}. ${t.description} ${n}
|
|
992
|
+
`}return e+=L.gray("\u2500".repeat(50)),e}var or,ue=C(()=>{ee();he();Wn();je();or={SIMPLE:"simple",COMPLEX:"complex"}});function gn(r,e={format:"markdown"}){let{format:t,maxSections:n=100,detailed:o=!0,customTitle:s}=e;switch(t){case"markdown":return _i(r,o,s);case"text":return El(r,o);case"summary":return Il(r,n);default:return _i(r,o,s)}}function _i(r,e,t){let n=[];return n.push(t||`# \u9879\u76EE\u7ED3\u6784\u4FE1\u606F
|
|
993
|
+
`),Al(n,r,e),Ll(n,r,e),Dl(n,r,e),jl(n,r,e),Ol(n,r,e),Rl(n,r,e),Fl(n,r,e),n.length<=1?"\u6682\u65E0\u8BE6\u7EC6\u9879\u76EE\u7ED3\u6784\u4FE1\u606F\u3002":n.join(`
|
|
994
|
+
`)}function El(r,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: ${r.projectName||"\u672A\u77E5"}`),t.push(`\u{1F4CC} \u7248\u672C: ${r.version||"\u672A\u77E5"}`),r.description&&t.push(`\u{1F4DD} \u63CF\u8FF0: ${r.description}`),t.push(""),t.push(`\u{1F310} \u4E3B\u8981\u8BED\u8A00: ${r.primaryLanguage||"\u672A\u77E5"}`),r.buildTool&&t.push(`\u{1F527} \u6784\u5EFA\u5DE5\u5177: ${r.buildTool}`),r.packageManager&&t.push(`\u{1F4E6} \u5305\u7BA1\u7406\u5668: ${r.packageManager}`),r.runtime&&t.push(`\u2699\uFE0F \u8FD0\u884C\u65F6: ${r.runtime}`),t.push(""),r.fileStats){t.push("\u{1F4C1} \u6587\u4EF6\u7EDF\u8BA1:");let n=r.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 r.dependencyCount&&(t.push("\u{1F4DA} \u4F9D\u8D56\u7EDF\u8BA1:"),t.push(` \u751F\u4EA7\u4F9D\u8D56: ${r.dependencyCount.production||0} \u4E2A`),t.push(` \u5F00\u53D1\u4F9D\u8D56: ${r.dependencyCount.development||0} \u4E2A`),t.push("")),r.languages&&r.languages.length>0&&(t.push("\u{1F30D} \u8BED\u8A00\u5206\u5E03:"),r.languages.slice(0,5).forEach(n=>{t.push(` ${n.language}: ${n.count} \u4E2A\u6587\u4EF6 (${n.percentage})`)}),t.push("")),t.join(`
|
|
995
|
+
`)}function Il(r,e){let t=[],n=0;if((r.projectName||r.version||r.description)&&(r.projectName&&t.push(`**\u9879\u76EE\u540D\u79F0**: ${r.projectName}`),r.version&&t.push(`**\u7248\u672C**: ${r.version}`),r.description&&t.push(`**\u63CF\u8FF0**: ${r.description}`),n++),n>=e||((r.primaryLanguage||r.buildTool)&&(t.push(""),r.primaryLanguage&&t.push(`**\u4E3B\u8981\u8BED\u8A00**: ${r.primaryLanguage}`),r.buildTool&&t.push(`**\u6784\u5EFA\u5DE5\u5177**: ${r.buildTool}`),r.packageManager&&t.push(`**\u5305\u7BA1\u7406\u5668**: ${r.packageManager}`),r.runtime&&t.push(`**\u8FD0\u884C\u65F6**: ${r.runtime}`),n++),n>=e))return t.join(`
|
|
966
996
|
`);if(r.fileStats){t.push("");let o=r.fileStats;o.totalFiles&&t.push(`**\u603B\u6587\u4EF6\u6570**: ${o.totalFiles}`),o.sourceFiles&&t.push(`**\u6E90\u6587\u4EF6**: ${o.sourceFiles}`),o.configFiles&&t.push(`**\u914D\u7F6E\u6587\u4EF6**: ${o.configFiles}`),o.testFiles&&t.push(`**\u6D4B\u8BD5\u6587\u4EF6**: ${o.testFiles}`),n++}return n>=e||(r.languages&&r.languages.length>0&&(t.push(""),t.push("**\u8BED\u8A00\u5206\u5E03**:"),r.languages.slice(0,5).forEach(o=>{t.push(`- ${o.language}: ${o.percentage}%`)}),n++),n>=e)||(r.dependencies&&Object.keys(r.dependencies).length>0&&(t.push(""),t.push("**\u4E3B\u8981\u4F9D\u8D56**:"),Object.entries(r.dependencies).slice(0,5).forEach(([s,i])=>{t.push(`- ${s}: ${i}`)}),n++),n>=e)?t.join(`
|
|
967
997
|
`):(r.codeStandards&&r.codeStandards.length>0&&(t.push(""),t.push("**\u4EE3\u7801\u89C4\u8303**:"),r.codeStandards.slice(0,3).forEach(o=>{t.push(`- ${o}`)})),t.length>0?t.join(`
|
|
968
|
-
`):"\u6682\u65E0\u9879\u76EE\u4FE1\u606F\u3002")}function
|
|
998
|
+
`):"\u6682\u65E0\u9879\u76EE\u4FE1\u606F\u3002")}function Al(r,e,t){!e.projectName&&!e.version&&!e.description||(r.push("## \u9879\u76EE\u57FA\u672C\u4FE1\u606F"),e.projectName&&r.push(`**\u9879\u76EE\u540D\u79F0**: ${e.projectName}`),e.version&&r.push(`**\u7248\u672C**: ${e.version}`),e.description&&r.push(`**\u63CF\u8FF0**: ${e.description}`),r.push(""))}function Ll(r,e,t){!e.primaryLanguage&&!e.buildTool&&!e.packageManager&&!e.runtime||(r.push("## \u6280\u672F\u6808\u4FE1\u606F"),e.primaryLanguage&&r.push(`**\u4E3B\u8981\u7F16\u7A0B\u8BED\u8A00**: ${e.primaryLanguage}`),e.buildTool&&r.push(`**\u6784\u5EFA\u5DE5\u5177**: ${e.buildTool}`),e.packageManager&&r.push(`**\u5305\u7BA1\u7406\u5668**: ${e.packageManager}`),e.runtime&&r.push(`**\u8FD0\u884C\u65F6**: ${e.runtime}`),r.push(""))}function Dl(r,e,t){if(!e.fileStats)return;let n=e.fileStats;r.push("## \u6587\u4EF6\u7EDF\u8BA1"),n.totalFiles&&r.push(`- **\u603B\u6587\u4EF6\u6570**: ${n.totalFiles}`),n.sourceFiles&&r.push(`- **\u6E90\u6587\u4EF6**: ${n.sourceFiles}`),n.configFiles&&r.push(`- **\u914D\u7F6E\u6587\u4EF6**: ${n.configFiles}`),n.docFiles&&r.push(`- **\u6587\u6863\u6587\u4EF6**: ${n.docFiles}`),n.testFiles&&r.push(`- **\u6D4B\u8BD5\u6587\u4EF6**: ${n.testFiles}`),r.push("")}function jl(r,e,t){!e.languages||e.languages.length===0||(r.push("## \u7F16\u7A0B\u8BED\u8A00\u5206\u6790"),t?e.languages.forEach(n=>{r.push(`- **${n.language}**: ${n.count} \u4E2A\u6587\u4EF6 (${n.percentage}%)`)}):e.languages.slice(0,5).forEach(n=>{r.push(`- **${n.language}**: ${n.percentage}%`)}),r.push(""))}function Ol(r,e,t){let n=e.dependencies&&Object.keys(e.dependencies).length>0,o=e.devDependencies&&Object.keys(e.devDependencies).length>0;!n&&!o||(r.push("## \u4F9D\u8D56\u5173\u7CFB"),n&&(r.push("### \u751F\u4EA7\u4F9D\u8D56"),(t?Object.entries(e.dependencies):Object.entries(e.dependencies).slice(0,10)).forEach(([i,a])=>{r.push(`- **${i}**: ${a}`)}),!t&&Object.keys(e.dependencies).length>10&&r.push(`
|
|
969
999
|
*...\u8FD8\u6709 ${Object.keys(e.dependencies).length-10} \u4E2A\u4F9D\u8D56*`),r.push("")),o&&(r.push("### \u5F00\u53D1\u4F9D\u8D56"),(t?Object.entries(e.devDependencies):Object.entries(e.devDependencies).slice(0,10)).forEach(([i,a])=>{r.push(`- **${i}**: ${a}`)}),!t&&Object.keys(e.devDependencies).length>10&&r.push(`
|
|
970
|
-
*...\u8FD8\u6709 ${Object.keys(e.devDependencies).length-10} \u4E2A\u4F9D\u8D56*`),r.push("")))}function
|
|
971
|
-
*...\u8FD8\u6709 ${e.entryPoints.length-5} \u4E2A\u5165\u53E3\u6587\u4EF6*`),r.push("")}function
|
|
972
|
-
*...\u8FD8\u6709 ${e.codeStandards.length-5} \u4E2A\u89C4\u8303*`),r.push("")}var
|
|
1000
|
+
*...\u8FD8\u6709 ${Object.keys(e.devDependencies).length-10} \u4E2A\u4F9D\u8D56*`),r.push("")))}function Rl(r,e,t){if(!e.entryPoints||e.entryPoints.length===0)return;r.push("## \u5165\u53E3\u6587\u4EF6"),(t?e.entryPoints:e.entryPoints.slice(0,5)).forEach(o=>{r.push(`- \`${o}\``)}),!t&&e.entryPoints.length>5&&r.push(`
|
|
1001
|
+
*...\u8FD8\u6709 ${e.entryPoints.length-5} \u4E2A\u5165\u53E3\u6587\u4EF6*`),r.push("")}function Fl(r,e,t){if(!e.codeStandards||e.codeStandards.length===0)return;r.push("## \u4EE3\u7801\u89C4\u8303"),(t?e.codeStandards:e.codeStandards.slice(0,5)).forEach(o=>{r.push(`- ${o}`)}),!t&&e.codeStandards.length>5&&r.push(`
|
|
1002
|
+
*...\u8FD8\u6709 ${e.codeStandards.length-5} \u4E2A\u89C4\u8303*`),r.push("")}var sr=C(()=>{});import*as Ct from"os";var ve,we,Te,ke,Ni=C(()=>{K();sr();ve=class{originalTask;plan;stepSummaries;sharedState;stepDependencies;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}initializeTask(e,t){this.originalTask=e,this.plan={tasks:t.tasks||[],currentStep:0,totalSteps:t.tasks?.length||0},M(`\u5168\u5C40\u4E0A\u4E0B\u6587\u521D\u59CB\u5316: ${this.plan.totalSteps} \u4E2A\u6B65\u9AA4`)}recordStepCompletion(e,t,n={}){this.stepSummaries.set(e,{summary:t,metadata:n,timestamp:new Date().toISOString()}),h(`\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,h(`\u5171\u4EAB\u72B6\u6001\u66F4\u65B0: ${e}`)):h(`\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}},we=class{globalContext;constructor(e){this.globalContext=e}async selectRelevantHistory(e,t){let n=[],o=this.globalContext.getStepDependencies().get(e)||[];for(let i of o){let a=this.globalContext.getStepSummary(i);a&&n.push({stepId:i,type:"dependency",content:a.summary,metadata:a.metadata})}let s=this.getRecentCompletedSteps(3);for(let i of s)if(!o.includes(i)){let a=this.globalContext.getStepSummary(i);a&&this.isLikelyRelevant(a.summary,t)&&n.push({stepId:i,type:"recent",content:a.summary,metadata:a.metadata})}return h(`\u4E3A\u6B65\u9AA4 ${e} \u9009\u62E9\u4E86 ${n.length} \u6761\u76F8\u5173\u5386\u53F2`),n}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),o=new Set(n(e));return n(t).filter(a=>o.has(a)).length>=2}async selectRelevantHistoryWithLLM(e,t){let{MODEL:n}=await Promise.resolve().then(()=>(ee(),Ze)),{callModelAPI:o}=await Promise.resolve().then(()=>(he(),pn)),s=Array.from(this.globalContext.getStepDependencies().entries()).map(([a,c])=>{let l=this.globalContext.getStepSummary(a);return l?`\u6B65\u9AA4${a}: ${l.summary}`:""}).filter(Boolean).join(`
|
|
973
1003
|
`);if(!s)return[];let i=`\u4EFB\u52A1: ${this.globalContext.getOriginalTask()||""}
|
|
974
1004
|
|
|
975
1005
|
\u5DF2\u5B8C\u6210\u7684\u5386\u53F2\u6B65\u9AA4\u6458\u8981:
|
|
@@ -979,10 +1009,18 @@ ${s}
|
|
|
979
1009
|
|
|
980
1010
|
\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
|
|
981
1011
|
\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
|
|
982
|
-
\u53EA\u8FD4\u56DEJSON\uFF0C\u4E0D\u8981\u5176\u4ED6\u89E3\u91CA\u3002`;try{let c=(await o({model:n(),messages:[{role:"user",content:i}],temperature:.1,max_tokens:100})).choices[0].message.content?.trim()||"[]",p=JSON.parse(c).map(u=>{let g=this.globalContext.getStepSummary(u);return g?{stepId:u,type:"llm_selected",content:g.summary,metadata:g.metadata}:null}).filter(u=>u!==null);return M(`LLM \u4E3A\u6B65\u9AA4 ${e} \u9009\u62E9\u4E86 ${p.length} \u6761\u76F8\u5173\u5386\u53F2`),p}catch(a){return
|
|
1012
|
+
\u53EA\u8FD4\u56DEJSON\uFF0C\u4E0D\u8981\u5176\u4ED6\u89E3\u91CA\u3002`;try{let c=(await o({model:n(),messages:[{role:"user",content:i}],temperature:.1,max_tokens:100})).choices[0].message.content?.trim()||"[]",p=JSON.parse(c).map(u=>{let g=this.globalContext.getStepSummary(u);return g?{stepId:u,type:"llm_selected",content:g.summary,metadata:g.metadata}:null}).filter(u=>u!==null);return M(`LLM \u4E3A\u6B65\u9AA4 ${e} \u9009\u62E9\u4E86 ${p.length} \u6761\u76F8\u5173\u5386\u53F2`),p}catch(a){return h(`LLM \u9009\u62E9\u5386\u53F2\u5931\u8D25\uFF0C\u964D\u7EA7\u5230\u542F\u53D1\u5F0F\u65B9\u6CD5: ${a instanceof Error?a.message:String(a)}`),this.selectRelevantHistory(e,t)}}},Te=class{globalContext;disclosure;constructor(e,t){this.globalContext=e,this.disclosure=t}async buildIsolatedContext(e,t,n="",o=!1,s){let i=[];n&&i.push({role:"system",content:n});let a=await this.buildProjectEnvironmentContext();a&&i.push({role:"system",content:`## \u9879\u76EE\u73AF\u5883\u4FE1\u606F
|
|
983
1013
|
|
|
984
|
-
${a}`}),i.push({role:"user",content:`\u539F\u59CB\u4EFB\u52A1: ${this.globalContext.getOriginalTask()||""}`}),this.globalContext.getSharedState().rules&&i.push({role:"system",content:`\u9879\u76EE\u89C4\u5219
|
|
985
|
-
|
|
1014
|
+
${a}`}),i.push({role:"user",content:`\u539F\u59CB\u4EFB\u52A1: ${this.globalContext.getOriginalTask()||""}`}),this.globalContext.getSharedState().rules&&i.push({role:"system",content:`\u26A0\uFE0F \u3010\u91CD\u8981\u3011\u9879\u76EE\u89C4\u5219 - \u6A21\u578B\u5FC5\u987B\u4E25\u683C\u9075\u5B88
|
|
1015
|
+
|
|
1016
|
+
===============================
|
|
1017
|
+
===== \u9879\u76EE\u89C4\u5219\u4E0E\u7EA6\u5B9A =====
|
|
1018
|
+
===============================
|
|
1019
|
+
|
|
1020
|
+
${this.globalContext.getSharedState().rules}
|
|
1021
|
+
|
|
1022
|
+
===============================
|
|
1023
|
+
\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 c;if(o?c=await this.disclosure.selectRelevantHistoryWithLLM(e,t):c=await this.disclosure.selectRelevantHistory(e,t),c.length>0){let l=c.map(p=>`[\u6B65\u9AA4${p.stepId}] ${p.content}`).join(`
|
|
986
1024
|
|
|
987
1025
|
`);i.push({role:"user",content:`\u76F8\u5173\u5386\u53F2\u4FE1\u606F:
|
|
988
1026
|
${l}`})}return i.push({role:"user",content:`\u5F53\u524D\u4EFB\u52A1 (\u6B65\u9AA4 ${e}/${this.globalContext.getPlan().totalSteps}):
|
|
@@ -995,20 +1033,26 @@ ${t}`}),s&&s.length>0&&i.push({role:"system",content:`\u26A0\uFE0F \u672C\u6B65\
|
|
|
995
1033
|
- You MUST use Action: merge(path, content) to modify existing files
|
|
996
1034
|
- NEVER just output code without saving it using Action:
|
|
997
1035
|
- Follow the exact format: "Thought: ..." then "Action: tool_name(args)"
|
|
998
|
-
- When task is done, use "Answer: ..." to finish`}),M(`\u4E3A\u6B65\u9AA4 ${e} \u6784\u5EFA\u4E86\u9694\u79BB\u4E0A\u4E0B\u6587\uFF0C\u5305\u542B ${i.length} \u6761\u6D88\u606F`),s&&M(`\u5DE5\u5177\u9650\u5236: ${s.join(", ")}`),
|
|
999
|
-
|
|
1036
|
+
- When task is done, use "Answer: ..." to finish`}),M(`\u4E3A\u6B65\u9AA4 ${e} \u6784\u5EFA\u4E86\u9694\u79BB\u4E0A\u4E0B\u6587\uFF0C\u5305\u542B ${i.length} \u6761\u6D88\u606F`),s&&M(`\u5DE5\u5177\u9650\u5236: ${s.join(", ")}`),h(`\u4E0A\u4E0B\u6587\u8BE6\u60C5: \u5386\u53F2 ${c.length} \u6761, \u6587\u4EF6 ${this.globalContext.getSharedState().recentFiles.length} \u4E2A`),i}buildSimpleContext(e,t=""){let n=[];return t&&n.push({role:"system",content:t}),n.push({role:"user",content:e}),M("\u6784\u5EFA\u4E86\u7B80\u5316\u4E0A\u4E0B\u6587\uFF08\u7B80\u5355\u4EFB\u52A1\u6A21\u5F0F\uFF09"),n}async buildProjectEnvironmentContext(){try{let e=Ct.platform(),t=Ct.arch(),n=Ct.version(),o=process.cwd(),s=`**\u8FD0\u884C\u73AF\u5883\u4FE1\u606F:**
|
|
1037
|
+
- **\u64CD\u4F5C\u7CFB\u7EDF\u5E73\u53F0:** ${e}
|
|
1038
|
+
- **\u64CD\u4F5C\u7CFB\u7EDF\u7248\u672C:** ${n}
|
|
1039
|
+
- **\u7CFB\u7EDF\u67B6\u6784:** ${t}
|
|
1040
|
+
- **\u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55:** ${o}
|
|
1041
|
+
`;e==="win32"?s+=`- **\u9ED8\u8BA4Shell:** cmd.exe (Windows)
|
|
1042
|
+
`:e==="darwin"?s+=`- **\u9ED8\u8BA4Shell:** zsh (macOS)
|
|
1043
|
+
`:s+=`- **\u9ED8\u8BA4Shell:** bash (Linux)
|
|
1044
|
+
`;try{let i=await import("fs"),c=(await import("path")).join(o,".nium/project/project.json");if(i.existsSync(c)){let l=i.readFileSync(c,"utf-8");try{let p=JSON.parse(l),u=this.extractProjectSummaryFromJSON(p);s+=`
|
|
1000
1045
|
**\u9879\u76EE\u7ED3\u6784\u6458\u8981:**
|
|
1001
|
-
${
|
|
1002
|
-
|
|
1003
|
-
**\u5B8C\u6574\u7ED3\u6784\u6587\u6863:** \u5982\u9700\u8BE6\u7EC6\u4FE1\u606F\uFF0C\u8BF7\u4F7F\u7528 read('.nium/project/project.json')`}catch(s){m(`\u89E3\u6790project.json\u5931\u8D25\uFF0C\u4F7F\u7528\u6587\u672C\u6458\u8981: ${s}`);let i=this.extractProjectSummary(o);return`**\u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55:** ${process.cwd()}
|
|
1046
|
+
${u}
|
|
1004
1047
|
|
|
1048
|
+
**\u5B8C\u6574\u7ED3\u6784\u6587\u6863:** \u5982\u9700\u8BE6\u7EC6\u4FE1\u606F\uFF0C\u8BF7\u4F7F\u7528 read('.nium/project/project.json')`}catch(p){h(`\u89E3\u6790project.json\u5931\u8D25\uFF0C\u4F7F\u7528\u6587\u672C\u6458\u8981: ${p}`);let u=this.extractProjectSummary(l);s+=`
|
|
1005
1049
|
**\u9879\u76EE\u7ED3\u6784\u6458\u8981:**
|
|
1006
|
-
${
|
|
1050
|
+
${u}
|
|
1007
1051
|
|
|
1008
|
-
**\u5B8C\u6574\u7ED3\u6784\u6587\u6863:** \u5982\u9700\u8BE6\u7EC6\u4FE1\u606F\uFF0C\u8BF7\u4F7F\u7528 read('.nium/project/project.json')`}}catch(e){return
|
|
1052
|
+
**\u5B8C\u6574\u7ED3\u6784\u6587\u6863:** \u5982\u9700\u8BE6\u7EC6\u4FE1\u606F\uFF0C\u8BF7\u4F7F\u7528 read('.nium/project/project.json')`}}}catch(i){h(`\u83B7\u53D6\u9879\u76EE\u7ED3\u6784\u4FE1\u606F\u5931\u8D25: ${i}`)}return s}catch(e){return h(`\u6784\u5EFA\u9879\u76EE\u73AF\u5883\u4E0A\u4E0B\u6587\u5931\u8D25: ${e}`),null}}extractProjectSummaryFromJSON(e){return gn(e,{format:"summary",maxSections:3})}extractProjectSummary(e){let t=e.split(`
|
|
1009
1053
|
`),n=[],o=!1,s=0;for(let i of t){if(i.includes("## \u9879\u76EE\u6982\u8FF0")){o=!0;continue}if(o){if(i.startsWith("##")&&!i.includes("\u9879\u76EE\u6982\u8FF0"))break;if(i.trim()&&(n.push(i),s++,s>=15))break}}return n.join(`
|
|
1010
|
-
`)}},ke=class{async extractSummary(e){let t=[],n=[],o=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&&(o=a[1].trim().substring(0,200))}}else i.role==="tool"&&i.content&&n.push(i.content.substring(0,100));let s="";return o?s=`\u5B8C\u6210: ${o}`:(s=`\u6267\u884C\u4E86 ${t.length} \u4E2A\u5DE5\u5177\u8C03\u7528`,t.length>0&&(s+=` (${t.slice(0,3).join(", ")})`)),
|
|
1011
|
-
`);if(o.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:o}],temperature:.1,max_tokens:150,useCompression:!0})).choices[0].message.content?.trim()||"\u6267\u884C\u5B8C\u6210";return M(`LLM \u751F\u6210\u6458\u8981: ${i.substring(0,50)}...`),i}catch(s){return
|
|
1054
|
+
`)}},ke=class{async extractSummary(e){let t=[],n=[],o=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&&(o=a[1].trim().substring(0,200))}}else i.role==="tool"&&i.content&&n.push(i.content.substring(0,100));let s="";return o?s=`\u5B8C\u6210: ${o}`:(s=`\u6267\u884C\u4E86 ${t.length} \u4E2A\u5DE5\u5177\u8C03\u7528`,t.length>0&&(s+=` (${t.slice(0,3).join(", ")})`)),h(`\u63D0\u53D6\u6458\u8981: ${s.substring(0,50)}...`),s}async extractSummaryWithLLM(e){let{LITE_MODEL:t}=await Promise.resolve().then(()=>(ee(),Ze)),{callModelAPI:n}=await Promise.resolve().then(()=>(he(),pn)),o=e.filter(s=>s.content).map(s=>`${s.role}: ${s.content.substring(0,500)}`).join(`
|
|
1055
|
+
`);if(o.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:o}],temperature:.1,max_tokens:150,useCompression:!0})).choices[0].message.content?.trim()||"\u6267\u884C\u5B8C\u6210";return M(`LLM \u751F\u6210\u6458\u8981: ${i.substring(0,50)}...`),i}catch(s){return h(`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 o of n.tool_calls){let s=o.function.name;if(s!=="think"&&(t.toolsUsed.push(s),["read","write","merge"].includes(s)))try{let i=JSON.parse(o.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 mn,Do=C(()=>{mn=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(o=>{let s=e.match(o);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(o=>{let s=e.match(o);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"],o=t.filter(i=>!n.includes(i)),s=new Map;return o.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),n=0;for(let o of this.anchors){let s=o.semanticSignature.split("|"),i=t.filter(l=>s.some(p=>p===l||p.includes(l)||l.includes(p))),a=new Set([...t,...s]),c=a.size>0?i.length/a.size:0;n+=c}return n/this.anchors.length}shouldInjectAnchor(e,t,n){if(t<.2)return!0;let o=this.getAnchorFrequency(t);return e%o===0?!0:t>=.2&&t<.6&&n&&n.length>1e3?e%Math.max(1,Math.floor(o/2))===0:!1}getAnchorFrequency(e){return e<.2?3:e<.4?5:e<.6?8:10}generateAnchorPrompt(e,t,n){let o=this.anchors[this.anchors.length-1],s=`\u{1F3AF} \u4E0A\u4E0B\u6587\u951A\u70B9\u63D0\u9192 (\u8FED\u4EE3 ${e}):
|
|
1012
1056
|
|
|
1013
1057
|
\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
|
|
1014
1058
|
|
|
@@ -1031,7 +1075,7 @@ ${o.successCriteria.map(i=>` \u2022 ${i}`).join(`
|
|
|
1031
1075
|
4. \u786E\u4FDD\u6BCF\u4E00\u6B65\u90FD\u671D\u7740\u6700\u7EC8\u76EE\u6807\u524D\u8FDB
|
|
1032
1076
|
5. \u6700\u7EC8\u7B54\u6848\u5FC5\u987B\u76F4\u63A5\u56DE\u5E94\u539F\u59CB\u95EE\u9898\u7684\u8981\u6C42
|
|
1033
1077
|
|
|
1034
|
-
\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,o,s){let i=this.generateAnchorPrompt(e,o,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 o={originalQuestion:this.originalQuestion,keyConstraints:this.extractConstraints(t),successCriteria:this.extractSuccessCriteria(t),iterationAdded:e,semanticSignature:this.generateSemanticSignature(t+" "+n)};this.anchors.push(o)}getOriginalQuestion(){return this.originalQuestion}getAnchors(){return this.anchors}}});var
|
|
1078
|
+
\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,o,s){let i=this.generateAnchorPrompt(e,o,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 o={originalQuestion:this.originalQuestion,keyConstraints:this.extractConstraints(t),successCriteria:this.extractSuccessCriteria(t),iterationAdded:e,semanticSignature:this.generateSemanticSignature(t+" "+n)};this.anchors.push(o)}getOriginalQuestion(){return this.originalQuestion}getAnchors(){return this.anchors}}});var dn,jo=C(()=>{ee();dn=class{modelClient;constructor(e){this.modelClient=e}async analyzeSemanticDrift(e,t,n){let o=`\u5206\u6790\u4EE5\u4E0B\u4E24\u4E2A\u6587\u672C\u7684\u8BED\u4E49\u76F8\u4F3C\u5EA6\u548C\u504F\u79BB\u7A0B\u5EA6\uFF1A
|
|
1035
1079
|
|
|
1036
1080
|
\u539F\u59CB\u6587\u672C: "${e}"
|
|
1037
1081
|
|
|
@@ -1043,7 +1087,7 @@ ${o.successCriteria.map(i=>` \u2022 ${i}`).join(`
|
|
|
1043
1087
|
3. keyTopics: \u4E24\u4E2A\u6587\u672C\u7684\u5173\u952E\u4E3B\u9898\u5217\u8868
|
|
1044
1088
|
4. deviationFactors: \u5BFC\u81F4\u504F\u79BB\u7684\u56E0\u7D20\u5217\u8868
|
|
1045
1089
|
|
|
1046
|
-
\u53EA\u8FD4\u56DEJSON\uFF0C\u4E0D\u8981\u5176\u4ED6\u89E3\u91CA\u3002`;try{let i=(await this.modelClient({model:
|
|
1090
|
+
\u53EA\u8FD4\u56DEJSON\uFF0C\u4E0D\u8981\u5176\u4ED6\u89E3\u91CA\u3002`;try{let i=(await this.modelClient({model:fe(),messages:[{role:"user",content:o}],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),o=this.extractKeywords(t),i=n.filter(c=>o.some(l=>l.includes(c)||c.includes(l))).length/Math.max(n.length,o.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,...o])],deviationFactors:this.identifyDeviationFactors(n,o)}}extractKeywords(e){let t=e.toLowerCase().replace(/[^\u4e00-\u9fa5a-zA-Z\s]/g," ").split(/\s+/).filter(o=>o.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(o=>!n.includes(o)))]}identifyDeviationFactors(e,t){let n=[],o=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 o.length>0&&n.push(`\u4E22\u5931\u4E86\u5173\u952E\u4E3B\u9898: ${o.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 o=`\u26A0\uFE0F \u504F\u79BB\u68C0\u6D4B\u8B66\u544A
|
|
1047
1091
|
|
|
1048
1092
|
\u68C0\u6D4B\u5230${t==="severe"?"\u4E25\u91CD":"\u8F7B\u5FAE"}\u504F\u79BB\u539F\u59CB\u95EE\u9898\u3002
|
|
1049
1093
|
|
|
@@ -1055,14 +1099,14 @@ ${n.map(s=>`\u2022 ${s}`).join(`
|
|
|
1055
1099
|
|
|
1056
1100
|
\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"&&(o+=`
|
|
1057
1101
|
|
|
1058
|
-
\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`),o}}});var Co=w(()=>{pi();yo();So()});var mi={};U(mi,{GradleBuildParser:()=>mn,JavaDependencyAnalyzer:()=>nr,MavenPomParser:()=>tr,analyzeJavaProject:()=>vo});import{readFileSync as Zn,existsSync as er}from"fs";import{resolve as wo}from"path";import{parseString as Yc}from"xml2js";async function vo(r=process.cwd()){let e=wo(r,"pom.xml"),t=wo(r,"build.gradle"),n=wo(r,"build.gradle.kts"),o=null;try{if(er(e)){let i=Zn(e,"utf-8");o=await new tr(i,e).parse()}else if(er(t)){let i=Zn(t,"utf-8");o=new mn(i,t).parse()}else if(er(n)){let i=Zn(n,"utf-8");o=new mn(i,n).parse()}if(!o)return null;let s={project:o,conflicts:[],outdated:[],unused:[],recommendations:[]};return s.recommendations=nr.generateRecommendations(s),s}catch(s){return console.error("Error analyzing Java project:",s),null}}var tr,mn,nr,xo=w(()=>{tr=class{content;filePath;constructor(e,t){this.content=e,this.filePath=t}async parse(){try{return new Promise((e,t)=>{Yc(this.content,{explicitArray:!1},(n,o)=>{if(n){t(n);return}try{let{project:s}=o;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(o=>({groupId:o.groupId,artifactId:o.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):[]}},mn=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(er(e))try{let n=Zn(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(o=>{let s;for(;(s=o.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,o;for(;(o=n.exec(this.content))!==null;)t[o[1]]=o[2];return t}},nr=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 o=[];return t.forEach((s,i)=>{if(s.size>1){let[a,c]=i.split(":"),l=Array.from(s);o.push({groupId:a,artifactId:c,versions:l,locations:n.get(i)||[],severity:this.calculateConflictSeverity(l)})}}),o}static calculateConflictSeverity(e){let t=e.map(o=>o.split(".")[0]).filter(o=>/^\d+$/.test(o));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(o=>o.groupId==="org.springframework.boot")&&t.push("\u9879\u76EE\u4F7F\u7528Spring Boot\uFF0C\u5EFA\u8BAE\u4F7F\u7528Spring Dependency Management\u63D2\u4EF6"),t}}});import{readFileSync as Kc,existsSync as di}from"fs";import{resolve as fi,dirname as Xc}from"path";function yi(r=process.cwd()){let e={name:"unknown",version:"0.0.0",description:"",language:"Unknown",configFiles:[]};for(let[t,n]of Object.entries(hi))for(let o of n.files){if(o.includes("*"))continue;let s=fi(r,o);if(di(s))try{let i=Kc(s,"utf-8"),a=n.parser(i,s);if(a)return{...e,...a,language:n.language,buildTool:t,configFiles:[o]}}catch(i){console.warn(`Error parsing ${o}: ${i instanceof Error?i.message:"Unknown error"}`)}}return e}function Qc(r,e){try{let t=JSON.parse(r);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 Zc(r,e){try{let t=r.match(/name\s*=\s*['"]([^'"]+)['"]/),n=r.match(/version\s*=\s*['"]([^'"]+)['"]/),o=r.match(/description\s*=\s*['"]([^'"]+)['"]/);return{name:t?t[1]:"unknown",version:n?n[1]:"0.0.0",description:o?o[1]:""}}catch{return null}}function el(r,e){try{let t=r.match(/name\s*=\s*"([^"]+)"/),n=r.match(/version\s*=\s*"([^"]+)"/),o=r.match(/description\s*=\s*"([^"]+)"/);return{name:t?t[1]:"unknown",version:n?n[1]:"0.0.0",description:o?o[1]:""}}catch{return null}}function tl(r,e){try{return{name:e.split(/[/\\]/).slice(-2,-1)[0]||"unknown",version:"0.0.0",description:""}}catch{return null}}function nl(r,e){try{let t=r.match(/module\s+([^\s]+)/),n=r.match(/go\s+([^\s]+)/),o={},s=/require\s+([^\s]+)\s+([^\s]+)/g,i;for(;(i=s.exec(r))!==null;)o[i[1]]=i[2];return{name:t&&t[1].split("/").pop()||"unknown",version:n?n[1]:"0.0.0",description:"",dependencies:o}}catch{return null}}function rl(r,e){try{let t=r.match(/name\s*=\s*"([^"]+)"/),n=r.match(/version\s*=\s*"([^"]+)"/),o=r.match(/description\s*=\s*"([^"]+)"/);return{name:t?t[1]:"unknown",version:n?n[1]:"0.0.0",description:o?o[1]:""}}catch{return null}}function ol(r,e){try{return{name:e.split(/[/\\]/).slice(-2,-1)[0]||"unknown",version:"0.0.0",description:""}}catch{return null}}function sl(r,e){try{let t=JSON.parse(r);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 il(r,e){try{let n=(e.split(/[/\\]/).pop()||"unknown").replace(/\.(cs|vb|fs)proj$/,""),o=r.match(/<Version>(.*?)<\/Version>/),s=r.match(/<Description>(.*?)<\/Description>/);return{name:n,version:o?o[1]:"0.0.0",description:s?s[1]:""}}catch{return null}}function Si(r){let e=r.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 al(r,e){try{let t=await vo(Xc(e));if(!t)return null;let n=t.project,o={};n.dependencies.forEach(i=>{o[`${i.groupId}:${i.artifactId}`]=i.version});let s=Si(n.dependencies);return{name:n.name,version:n.version,description:n.description||"",dependencies:o,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 cl(r,e){try{let t=await Promise.resolve().then(()=>(xo(),mi)),o=new t.GradleBuildParser(r,e).parse();if(!o)return null;let s={};o.dependencies.forEach(a=>{s[`${a.groupId}:${a.artifactId}`]=a.version});let i=Si(o.dependencies);return{name:o.name,version:o.version,description:o.description||"",dependencies:s,languageExtensionInfo:{javaDetails:o,framework:i,javaVersion:o.javaVersion,buildToolVersion:o.buildToolVersion||"Gradle"},configFiles:[e.split("/").pop()||"build.gradle"]}}catch(t){return console.error("Error parsing Gradle build file with enhanced parser:",t),null}}function Ci(r=process.cwd()){let e=[];for(let[t,n]of Object.entries(hi))for(let o of n.files){if(o.includes("*"))continue;let s=fi(r,o);if(di(s)){e.push(t);break}}return e}var hi,wi=w(()=>{xo();hi={nodejs:{files:["package.json"],language:"JavaScript/TypeScript",parser:Qc},"java-maven":{files:["pom.xml"],language:"Java",parser:al},"java-gradle":{files:["build.gradle","build.gradle.kts"],language:"Java",parser:async(r,e)=>await cl(r,e)},"python-pip":{files:["setup.py","setup.cfg"],language:"Python",parser:Zc},"python-poetry":{files:["pyproject.toml"],language:"Python",parser:el},"python-pipenv":{files:["Pipfile"],language:"Python",parser:tl},go:{files:["go.mod"],language:"Go",parser:nl},rust:{files:["Cargo.toml"],language:"Rust",parser:rl},ruby:{files:["Gemfile"],language:"Ruby",parser:ol},php:{files:["composer.json"],language:"PHP",parser:sl},dotnet:{files:["*.csproj","*.vbproj","*.fsproj"],language:"C#/.NET",parser:il}}});import{writeFileSync as ll,existsSync as ul,mkdirSync as gl}from"fs";import{resolve as vi}from"path";function xi(r,e=process.cwd()){let t=vi(e,".nium","project");ul(t)||gl(t,{recursive:!0});let o=vi(t,"project.json"),s=JSON.stringify(r,null,2);ll(o,s,"utf-8"),console.log(`\u2705 \u9879\u76EE\u4FE1\u606F\u5DF2\u4FDD\u5B58\u81F3: ${o}`)}function Ti(r){let e=r.reduce((t,n)=>t+n.count,0);return r.map(t=>({...t,percentage:e>0?(t.count/e*100).toFixed(1)+"%":"0%"}))}var bi=w(()=>{Qn()});import{createHash as pl}from"crypto";import{readFileSync as ki,writeFileSync as ml,existsSync as dl,statSync as fl}from"fs";import{resolve as hl}from"path";function yl(r){try{let e=ki(r),t=pl("md5");return t.update(e),t.digest("hex")}catch(e){return console.warn(`\u26A0\uFE0F \u65E0\u6CD5\u8BA1\u7B97\u6587\u4EF6 MD5: ${r}`,e),""}}function Sl(r,e=process.cwd()){try{let t=hl(e,r),n=fl(t),o=yl(t);return{path:r,size:n.size,md5:o,updatedAt:n.mtime.toISOString(),description:""}}catch(t){return console.warn(`\u26A0\uFE0F \u65E0\u6CD5\u83B7\u53D6\u6587\u4EF6\u4FE1\u606F: ${r}`,t),null}}function Cl(r){let e=new Map;if(!dl(r))return e;try{let n=ki(r,"utf-8").trim().split(`
|
|
1059
|
-
`);for(let o of n)if(o.trim())try{let s=JSON.parse(o);e.set(s.path,s)}catch(s){console.warn(`\u26A0\uFE0F \u65E0\u6CD5\u89E3\u6790 JSONL \u884C: ${o}`,s)}}catch(t){console.warn(`\u26A0\uFE0F \u8BFB\u53D6 JSONL \u6587\u4EF6\u5931\u8D25: ${r}`,t)}return e}function
|
|
1102
|
+
\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`),o}}});var Oo=C(()=>{Ni();Do();jo()});var Ui={};U(Ui,{GradleBuildParser:()=>fn,JavaDependencyAnalyzer:()=>lr,MavenPomParser:()=>cr,analyzeJavaProject:()=>Fo});import{readFileSync as ir,existsSync as ar}from"fs";import{resolve as Ro}from"path";import{parseString as _l}from"xml2js";async function Fo(r=process.cwd()){let e=Ro(r,"pom.xml"),t=Ro(r,"build.gradle"),n=Ro(r,"build.gradle.kts"),o=null;try{if(ar(e)){let i=ir(e,"utf-8");o=await new cr(i,e).parse()}else if(ar(t)){let i=ir(t,"utf-8");o=new fn(i,t).parse()}else if(ar(n)){let i=ir(n,"utf-8");o=new fn(i,n).parse()}if(!o)return null;let s={project:o,conflicts:[],outdated:[],unused:[],recommendations:[]};return s.recommendations=lr.generateRecommendations(s),s}catch(s){return console.error("Error analyzing Java project:",s),null}}var cr,fn,lr,_o=C(()=>{cr=class{content;filePath;constructor(e,t){this.content=e,this.filePath=t}async parse(){try{return new Promise((e,t)=>{_l(this.content,{explicitArray:!1},(n,o)=>{if(n){t(n);return}try{let{project:s}=o;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(o=>({groupId:o.groupId,artifactId:o.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):[]}},fn=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(ar(e))try{let n=ir(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(o=>{let s;for(;(s=o.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,o;for(;(o=n.exec(this.content))!==null;)t[o[1]]=o[2];return t}},lr=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 o=[];return t.forEach((s,i)=>{if(s.size>1){let[a,c]=i.split(":"),l=Array.from(s);o.push({groupId:a,artifactId:c,versions:l,locations:n.get(i)||[],severity:this.calculateConflictSeverity(l)})}}),o}static calculateConflictSeverity(e){let t=e.map(o=>o.split(".")[0]).filter(o=>/^\d+$/.test(o));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(o=>o.groupId==="org.springframework.boot")&&t.push("\u9879\u76EE\u4F7F\u7528Spring Boot\uFF0C\u5EFA\u8BAE\u4F7F\u7528Spring Dependency Management\u63D2\u4EF6"),t}}});import{existsSync as Vi,readFileSync as Nl}from"fs";import{resolve as Wi,dirname as Ul}from"path";function Ji(r=process.cwd()){let e={name:"unknown",version:"0.0.0",description:"",languages:["Unknown"],primaryLanguage:"Unknown",configFiles:[]},t=new Set,n=[],o="Unknown",s,i=null;for(let[a,c]of Object.entries(Hi))for(let l of c.files){if(l.includes("*"))continue;let p=Wi(r,l);if(Vi(p)&&(t.add(c.language),n.push(l),o==="Unknown")){o=c.language,s=a;try{let u=Nl(p,"utf-8"),g=c.parser(u,p);g instanceof Promise?console.warn(`Async parser not supported in sync readProjectConfig: ${a}`):i=g}catch(u){console.warn(`Error parsing ${l}: ${u instanceof Error?u.message:"Unknown error"}`)}}}return t.size===0?e:{...e,...i||{},languages:Array.from(t),primaryLanguage:o,buildTool:s,configFiles:n}}function Vl(r,e){try{let t=JSON.parse(r);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 Wl(r,e){try{let t=r.match(/name\s*=\s*['"]([^'"]+)['"]/),n=r.match(/version\s*=\s*['"]([^'"]+)['"]/),o=r.match(/description\s*=\s*['"]([^'"]+)['"]/);return{name:t?t[1]:"unknown",version:n?n[1]:"0.0.0",description:o?o[1]:""}}catch{return null}}function Hl(r,e){try{let t=r.match(/name\s*=\s*"([^"]+)"/),n=r.match(/version\s*=\s*"([^"]+)"/),o=r.match(/description\s*=\s*"([^"]+)"/);return{name:t?t[1]:"unknown",version:n?n[1]:"0.0.0",description:o?o[1]:""}}catch{return null}}function Jl(r,e){try{return{name:e.split(/[/\\]/).slice(-2,-1)[0]||"unknown",version:"0.0.0",description:""}}catch{return null}}function Gl(r,e){try{let t=r.match(/module\s+([^\s]+)/),n=r.match(/go\s+([^\s]+)/),o={},s=/require\s+([^\s]+)\s+([^\s]+)/g,i;for(;(i=s.exec(r))!==null;)o[i[1]]=i[2];return{name:t&&t[1].split("/").pop()||"unknown",version:n?n[1]:"0.0.0",description:"",dependencies:o}}catch{return null}}function zl(r,e){try{let t=r.match(/name\s*=\s*"([^"]+)"/),n=r.match(/version\s*=\s*"([^"]+)"/),o=r.match(/description\s*=\s*"([^"]+)"/);return{name:t?t[1]:"unknown",version:n?n[1]:"0.0.0",description:o?o[1]:""}}catch{return null}}function ql(r,e){try{return{name:e.split(/[/\\]/).slice(-2,-1)[0]||"unknown",version:"0.0.0",description:""}}catch{return null}}function Bl(r,e){try{let t=JSON.parse(r);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 Yl(r,e){try{let n=(e.split(/[/\\]/).pop()||"unknown").replace(/\.(cs|vb|fs)proj$/,""),o=r.match(/<Version>(.*?)<\/Version>/),s=r.match(/<Description>(.*?)<\/Description>/);return{name:n,version:o?o[1]:"0.0.0",description:s?s[1]:""}}catch{return null}}function Gi(r){let e=r.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 Kl(r,e){try{let t=await Fo(Ul(e));if(!t)return null;let n=t.project,o={};n.dependencies.forEach(i=>{o[`${i.groupId}:${i.artifactId}`]=i.version});let s=Gi(n.dependencies);return{name:n.name,version:n.version,description:n.description||"",dependencies:o,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 Xl(r,e){try{let t=await Promise.resolve().then(()=>(_o(),Ui)),o=new t.GradleBuildParser(r,e).parse();if(!o)return null;let s={};o.dependencies.forEach(a=>{s[`${a.groupId}:${a.artifactId}`]=a.version});let i=Gi(o.dependencies);return{name:o.name,version:o.version,description:o.description||"",dependencies:s,languageExtensionInfo:{javaDetails:o,framework:i,javaVersion:o.javaVersion,buildToolVersion:o.buildToolVersion||"Gradle"},configFiles:[e.split("/").pop()||"build.gradle"]}}catch(t){return console.error("Error parsing Gradle build file with enhanced parser:",t),null}}function zi(r=process.cwd()){let e=[];for(let[t,n]of Object.entries(Hi))for(let o of n.files){if(o.includes("*"))continue;let s=Wi(r,o);if(Vi(s)){e.push(t);break}}return e}var Hi,qi=C(()=>{_o();Hi={nodejs:{files:["package.json"],language:"JavaScript/TypeScript",parser:Vl},"java-maven":{files:["pom.xml"],language:"Java",parser:Kl},"java-gradle":{files:["build.gradle","build.gradle.kts"],language:"Java",parser:async(r,e)=>await Xl(r,e)},"python-pip":{files:["setup.py","setup.cfg"],language:"Python",parser:Wl},"python-poetry":{files:["pyproject.toml"],language:"Python",parser:Hl},"python-pipenv":{files:["Pipfile"],language:"Python",parser:Jl},go:{files:["go.mod"],language:"Go",parser:Gl},rust:{files:["Cargo.toml"],language:"Rust",parser:zl},ruby:{files:["Gemfile"],language:"Ruby",parser:ql},php:{files:["composer.json"],language:"PHP",parser:Bl},dotnet:{files:["*.csproj","*.vbproj","*.fsproj"],language:"C#/.NET",parser:Yl}}});import{writeFileSync as Ql,existsSync as Zl,mkdirSync as eu}from"fs";import{resolve as Bi}from"path";function Yi(r,e=process.cwd()){let t=Bi(e,".nium","project");Zl(t)||eu(t,{recursive:!0});let o=Bi(t,"project.json"),s=JSON.stringify(r,null,2);Ql(o,s,"utf-8"),console.log(`\u2705 \u9879\u76EE\u4FE1\u606F\u5DF2\u4FDD\u5B58\u81F3: ${o}`)}function Ki(r){let e=r.reduce((t,n)=>t+n.count,0);return r.map(t=>({...t,percentage:e>0?(t.count/e*100).toFixed(1)+"%":"0%"}))}var Xi=C(()=>{sr()});import{createHash as tu}from"crypto";import{readFileSync as Qi,writeFileSync as nu,existsSync as ru,statSync as ou}from"fs";import{resolve as su}from"path";function iu(r){try{let e=Qi(r),t=tu("md5");return t.update(e),t.digest("hex")}catch(e){return console.warn(`\u26A0\uFE0F \u65E0\u6CD5\u8BA1\u7B97\u6587\u4EF6 MD5: ${r}`,e),""}}function au(r,e=process.cwd()){try{let t=su(e,r),n=ou(t),o=iu(t);return{path:r,size:n.size,md5:o,updatedAt:n.mtime.toISOString(),description:""}}catch(t){return console.warn(`\u26A0\uFE0F \u65E0\u6CD5\u83B7\u53D6\u6587\u4EF6\u4FE1\u606F: ${r}`,t),null}}function cu(r){let e=new Map;if(!ru(r))return e;try{let n=Qi(r,"utf-8").trim().split(`
|
|
1103
|
+
`);for(let o of n)if(o.trim())try{let s=JSON.parse(o);e.set(s.path,s)}catch(s){console.warn(`\u26A0\uFE0F \u65E0\u6CD5\u89E3\u6790 JSONL \u884C: ${o}`,s)}}catch(t){console.warn(`\u26A0\uFE0F \u8BFB\u53D6 JSONL \u6587\u4EF6\u5931\u8D25: ${r}`,t)}return e}function lu(r,e){try{let t=[],n=Array.from(r.entries()).sort((o,s)=>o[0].localeCompare(s[0]));for(let[,o]of n)t.push(JSON.stringify(o));nu(e,t.join(`
|
|
1060
1104
|
`)+`
|
|
1061
|
-
`,"utf-8")}catch(t){throw console.error(`\u274C \u5199\u5165 JSONL \u6587\u4EF6\u5931\u8D25: ${e}`,t),t}}function
|
|
1062
|
-
`)}var Pi=w(()=>{});var Ii={};U(Ii,{QuickProjectScanTool:()=>je,quickProjectScan:()=>Ct,quickProjectScanTool:()=>wt});import{existsSync as B}from"fs";import{globSync as vl}from"glob";async function Ct(){return Ei.execute({})}var je,Ei,wt,To=w(()=>{G();Qt();Gn();wi();bi();Pi();je=class extends I{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...
|
|
1063
|
-
`),t.push("\u{1F4C2} \u626B\u63CF\u9879\u76EE\u6587\u4EF6...");let o=lt(n,!0);t.push(` - \u5E94\u7528 ${o.length} \u6761\u5FFD\u7565\u89C4\u5219`);let s=Date.now(),i=
|
|
1064
|
-
`),t.push("\u{1F4CB} \u68C0\u6D4B\u9879\u76EE\u7C7B\u578B\u548C\u914D\u7F6E...");let c=
|
|
1065
|
-
`)}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 o=Object.entries(n).map(([a,c])=>({language:a,count:c})).sort((a,c)=>c.count-a.count),[s]=o;return{primaryLanguage:s?.language||null,languages:o,totalSourceFiles:o.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"],o=[".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),(o.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){
|
|
1105
|
+
`,"utf-8")}catch(t){throw console.error(`\u274C \u5199\u5165 JSONL \u6587\u4EF6\u5931\u8D25: ${e}`,t),t}}function Zi(r,e,t=process.cwd(),n=!0){n&&console.log(` \u{1F4D6} \u6B63\u5728\u8BFB\u53D6\u73B0\u6709\u6587\u4EF6\u4FE1\u606F: ${e}`);let o=cu(e),s={added:0,updated:0,deleted:0,unchanged:0},i=new Map,a=new Set(r),c=r.length,l=0,p=Date.now();n&&(console.log(` \u{1F4CB} \u8BFB\u53D6\u73B0\u6709\u6587\u4EF6\u4FE1\u606F\u5B8C\u6210\uFF0C\u5DF2\u6709 ${o.size} \u6761\u8BB0\u5F55`),console.log(` \u{1F680} \u5F00\u59CB\u5904\u7406 ${c} \u4E2A\u6587\u4EF6...`));for(let u of r){if(l++,n&&l===1&&console.log(` \u{1F504} \u5904\u7406\u7B2C 1 \u4E2A\u6587\u4EF6: ${u}`),n&&l%50===0){let S=(l/c*100).toFixed(1),b=((Date.now()-p)/1e3).toFixed(1);console.log(` \u{1F4CA} \u5904\u7406\u8FDB\u5EA6: ${l}/${c} (${S}%) - \u5DF2\u7528\u65F6 ${b}s`)}let g=o.get(u),m=au(u,t);m&&(g?g.md5!==m.md5?(i.set(u,{...m,description:g.description}),s.updated++):(i.set(u,g),s.unchanged++):(i.set(u,m),s.added++))}if(n){let u=((Date.now()-p)/1e3).toFixed(1);console.log(` \u2705 \u6587\u4EF6\u5904\u7406\u5B8C\u6210: ${c} \u4E2A\u6587\u4EF6, \u603B\u7528\u65F6 ${u}s`)}n&&console.log(" \u{1F50D} \u6B63\u5728\u68C0\u6D4B\u5DF2\u5220\u9664\u7684\u6587\u4EF6...");for(let[u]of o)a.has(u)||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...`),lu(i,e),n&&console.log(" \u2705 JSONL \u6587\u4EF6\u5199\u5165\u5B8C\u6210"),s}function ea(r){let e=r.added+r.updated+r.deleted+r.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}`),r.added>0&&t.push(`\u2795 \u65B0\u589E: ${r.added} \u4E2A\u6587\u4EF6`),r.updated>0&&t.push(`\u{1F504} \u66F4\u65B0: ${r.updated} \u4E2A\u6587\u4EF6`),r.deleted>0&&t.push(`\u2796 \u5220\u9664: ${r.deleted} \u4E2A\u6587\u4EF6`),r.unchanged>0&&t.push(`\u2705 \u672A\u53D8: ${r.unchanged} \u4E2A\u6587\u4EF6`),t.push("\u2500".repeat(40)),t.join(`
|
|
1106
|
+
`)}var ta=C(()=>{});var H,ye=C(()=>{H=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"}}}});import{existsSync as No,readFileSync as na}from"fs";import{resolve as Uo}from"path";var ur,ra=C(()=>{ye();ur=class extends H{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={},o=Uo(e,"package.json");if(No(o))try{let s=na(o,"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){let n=[],o=["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"],s=Uo(t,"package.json");if(No(s))try{let i=na(s,"utf-8"),a=JSON.parse(i);a.main&&n.push(a.main),a.bin&&(typeof a.bin=="string"?n.push(a.bin):n.push(...Object.values(a.bin)))}catch{}return o.forEach(i=>{e.includes(i)&&n.push(i)}),[...new Set(n)]}detectCodeStandards(e){let t=[],n={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"]};for(let[o,s]of Object.entries(n))for(let i of s)if(No(Uo(e,i))){t.push(o);break}return 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"]}}});import{existsSync as gr,readFileSync as pr}from"fs";import{resolve as hn}from"path";var mr,oa=C(()=>{ye();mr=class extends H{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={},o=hn(e,"pom.xml");if(gr(o))try{let a=pr(o,"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=hn(e,"build.gradle"),i=hn(e,"build.gradle.kts");if(gr(s))try{let a=pr(s,"utf-8"),c=a.match(/sourceCompatibility\s*=\s*['"]?([^'"\\s]+)['"]?/)||a.match(/targetCompatibility\s*=\s*['"]?([^'"\\s]+)['"]?/);c&&(n.Java=c[1])}catch{}else if(gr(i))try{let a=pr(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){let n=[],o=["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"];return e.forEach(s=>{if(s.endsWith(".java"))try{pr(hn(t,s),"utf-8").includes("public static void main(String[] args)")&&n.push(s)}catch{}}),o.forEach(s=>{let i=new RegExp(s.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*"));e.forEach(a=>{i.test(a)&&n.push(a)})}),[...new Set(n)]}detectCodeStandards(e){let t=[],n={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"]};for(let[o,s]of Object.entries(n))for(let i of s)if(gr(hn(e,i))){t.push(o);break}return 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"]}}});import{existsSync as yn,readFileSync as Sn}from"fs";import{resolve as xt}from"path";var dr,sa=C(()=>{ye();dr=class extends H{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={},o=xt(e,".python-version");if(yn(o))try{let a=Sn(o,"utf-8");n.Python=a.trim()}catch{}let s=xt(e,"pyproject.toml");if(yn(s))try{let c=Sn(s,"utf-8").match(/python\s*=\s*['"]([^'"]+)['"]/);c&&(n.Python=c[1])}catch{}let i=xt(e,"setup.py");if(yn(i))try{let c=Sn(i,"utf-8").match(/python_requires\s*=\s*['"]([^'"]+)['"]/);c&&(n.Python=c[1])}catch{}return n}findEntryPoints(e,t){let n=[];["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"].forEach(i=>{e.includes(i)&&n.push(i)});let s=xt(t,"setup.py");if(yn(s))try{let a=Sn(s,"utf-8").match(/entry_points\s*=\s*\{[^}]+\}/s);if(a){let l=a[0].match(/console_scripts\s*:\s*\[([^\]]+)\]/s);if(l){let u=l[1].match(/([^=]+)\s*=\s*([^,]+)/g);u&&u.forEach(g=>{let[m,S]=g.split("=").map(f=>f.trim()),b=S.replace(/\./g,"/").replace(":","/")+".py";n.push(b)})}}}catch{}return[...new Set(n)]}detectCodeStandards(e){let t=[],n={Black:["pyproject.toml","setup.cfg"],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"]};for(let[o,s]of Object.entries(n))for(let i of s)if(yn(xt(e,i)))if(o==="Black")try{if(Sn(xt(e,i),"utf-8").includes("[tool.black]")){t.push(o);break}}catch{}else{t.push(o);break}return 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"]}}});import{existsSync as Vo,readFileSync as Wo}from"fs";import{resolve as fr}from"path";var hr,ia=C(()=>{ye();hr=class extends H{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={},o=fr(e,"go.mod");if(Vo(o))try{let a=Wo(o,"utf-8").match(/^go\s+(\d+\.\d+)/m);a&&(n.Go=a[1])}catch{}let s=fr(e,"go.sum");if(Vo(s))try{let a=Wo(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){let n=[];return["main.go","cmd/main.go","cmd/app/main.go","cmd/server/main.go","cmd/cli/main.go","src/main.go"].forEach(s=>{e.includes(s)&&n.push(s)}),e.forEach(s=>{if(s.endsWith(".go"))try{Wo(fr(t,s),"utf-8").includes("func main()")&&n.push(s)}catch{}}),[...new Set(n)]}detectCodeStandards(e){let t=[],n={GoFmt:[".gofmt"],GoLint:[".golint"],"GolangCI-Lint":[".golangci.yml",".golangci.yaml"],EditorConfig:[".editorconfig"],GoMod:["go.mod"],GoSum:["go.sum"]};for(let[o,s]of Object.entries(n))for(let i of s)if(Vo(fr(e,i))){t.push(o);break}return t}getCommonSourceExtensions(){return[".go",".mod",".sum"]}getCommonTestExtensions(){return["_test.go",".test.go"]}getCommonConfigFiles(){return["go.mod","go.sum",".golangci.yml",".golangci.yaml",".editorconfig","Makefile"]}}});import{existsSync as aa,readFileSync as uu}from"fs";import{resolve as ca}from"path";var yr,la=C(()=>{ye();yr=class extends H{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={},o=ca(e,"Cargo.toml");if(aa(o))try{let i=uu(o,"utf-8").match(/rust-version\s*=\s*['"]([^'"]+)['"]/);i&&(n.Rust=i[1])}catch{}return n}findEntryPoints(e,t){let n=[];return["src/main.rs","src/lib.rs","src/bin/main.rs","src/bin/*.rs"].forEach(s=>{if(s.includes("*")){let i=new RegExp(s.replace(/\*/g,"[^/]*"));e.forEach(a=>{i.test(a)&&n.push(a)})}else e.includes(s)&&n.push(s)}),[...new Set(n)]}detectCodeStandards(e){let t=[],n={Rustfmt:["rustfmt.toml",".rustfmt.toml"],Clippy:["clippy.toml",".clippy.toml"],EditorConfig:[".editorconfig"],Cargo:["Cargo.toml","Cargo.lock"]};for(let[o,s]of Object.entries(n))for(let i of s)if(aa(ca(e,i))){t.push(o);break}return t}getCommonSourceExtensions(){return[".rs",".toml",".lock"]}getCommonTestExtensions(){return["_test.rs",".test.rs","tests/*.rs"]}getCommonConfigFiles(){return["Cargo.toml","Cargo.lock","rustfmt.toml",".rustfmt.toml","clippy.toml",".clippy.toml",".editorconfig"]}}});import{existsSync as Ho,readFileSync as ua}from"fs";import{resolve as Jo}from"path";var Sr,ga=C(()=>{ye();Sr=class extends H{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={},o=Jo(e,"composer.json");if(Ho(o))try{let i=ua(o,"utf-8"),a=JSON.parse(i);a.require&&a.require.php&&(n.PHP=a.require.php)}catch{}let s=Jo(e,".php-version");if(Ho(s))try{let i=ua(s,"utf-8");n.PHP=i.trim()}catch{}return n}findEntryPoints(e,t){let n=[];return["index.php","public/index.php","app/index.php","src/index.php","cli.php","artisan","bin/console","composer.json"].forEach(s=>{e.includes(s)&&n.push(s)}),[...new Set(n)]}detectCodeStandards(e){let t=[],n={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"]};for(let[o,s]of Object.entries(n))for(let i of s)if(Ho(Jo(e,i))){t.push(o);break}return 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"]}}});import{existsSync as Go,readFileSync as pa}from"fs";import{resolve as zo}from"path";var Cr,ma=C(()=>{ye();Cr=class extends H{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={},o=zo(e,".ruby-version");if(Go(o))try{let i=pa(o,"utf-8");n.Ruby=i.trim()}catch{}let s=zo(e,"Gemfile");if(Go(s))try{let a=pa(s,"utf-8").match(/ruby\s+['"]([^'"]+)['"]/);a&&!n.Ruby&&(n.Ruby=a[1])}catch{}return n}findEntryPoints(e,t){let n=[];return["main.rb","app.rb","bin/rails","bin/rake","bin/console","config.ru","Rakefile","Gemfile"].forEach(s=>{e.includes(s)&&n.push(s)}),[...new Set(n)]}detectCodeStandards(e){let t=[],n={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"]};for(let[o,s]of Object.entries(n))for(let i of s)if(Go(zo(e,i))){t.push(o);break}return 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"]}}});import{existsSync as da,readFileSync as fa}from"fs";import{resolve as qo}from"path";import{globSync as Bo}from"glob";var xr,ha=C(()=>{ye();xr=class extends H{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={},o=[...Bo("*.csproj",{cwd:e}),...Bo("*.vbproj",{cwd:e}),...Bo("*.fsproj",{cwd:e})];for(let i of o)try{let a=qo(e,i),c=fa(a,"utf-8"),l=c.match(/<TargetFramework>([^<]+)<\/TargetFramework>/)||c.match(/<TargetFrameworks>([^<]+)<\/TargetFrameworks>/);if(l){n[".NET Framework"]=l[1];break}let p=c.match(/<LangVersion>([^<]+)<\/LangVersion>/);p&&(n["C# Version"]=p[1])}catch{}let s=qo(e,"global.json");if(da(s))try{let i=fa(s,"utf-8"),a=JSON.parse(i);a.sdk&&a.sdk.version&&(n[".NET SDK"]=a.sdk.version)}catch{}return n}findEntryPoints(e,t){let n=[];return["Program.cs","Startup.cs","App.xaml.cs","MainWindow.xaml.cs","Program.vb","Startup.vb","App.xaml.vb","MainWindow.xaml.vb","Program.fs","Startup.fs"].forEach(s=>{e.includes(s)&&n.push(s)}),[...new Set(n)]}detectCodeStandards(e){let t=[],n={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"]};for(let[o,s]of Object.entries(n))for(let i of s)if(da(qo(e,i))){t.push(o);break}return 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"]}}});var Yo,Cn,ya=C(()=>{ra();oa();sa();ia();la();ga();ma();ha();Yo=class r{static instance;handlers=new Map;constructor(){this.registerHandlers()}static getInstance(){return r.instance||(r.instance=new r),r.instance}registerHandlers(){[new ur,new mr,new dr,new hr,new yr,new Sr,new Cr,new xr].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#"]},o=e.toLowerCase();n[o]&&n[o].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 o=this.getHandler(e);return o?await o.detectVersions(t,n):{}}findEntryPoints(e,t,n){let o=this.getHandler(e);return o?o.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 o=this.getDirectoryDescriptions(n);Object.assign(t,o)}),t}async detectVersionsForLanguages(e,t,n){let o={};for(let s of e){let i=await this.detectVersions(s,t,n);Object.assign(o,i)}return o}findEntryPointsForLanguages(e,t,n){let o=[];for(let s of e){let i=this.findEntryPoints(s,t,n);o.push(...i)}return[...new Set(o)]}detectCodeStandardsForLanguages(e,t){let n=[];for(let o of e){let s=this.detectCodeStandards(o,t);n.push(...s)}return[...new Set(n)]}},Cn=Yo.getInstance()});var Ca={};U(Ca,{QuickProjectScanTool:()=>Fe,quickProjectScan:()=>bt,quickProjectScanTool:()=>vt});import{existsSync as Re}from"fs";import{globSync as gu}from"glob";async function bt(){return Sa.execute({})}var Fe,Sa,vt,Ko=C(()=>{J();Qn();qi();Xi();ta();ya();Fe=class extends I{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...
|
|
1107
|
+
`),t.push("\u{1F4C2} \u626B\u63CF\u9879\u76EE\u6587\u4EF6...");let o=lt(n,!0);t.push(` - \u5E94\u7528 ${o.length} \u6761\u5FFD\u7565\u89C4\u5219`);let s=Date.now(),i=gu("**/*",{nodir:!0,ignore:o,cwd:n}),a=((Date.now()-s)/1e3).toFixed(1);t.push(`\u627E\u5230 ${i.length} \u4E2A\u76F8\u5173\u6587\u4EF6 (\u8017\u65F6 ${a}s)
|
|
1108
|
+
`),t.push("\u{1F4CB} \u68C0\u6D4B\u9879\u76EE\u7C7B\u578B\u548C\u914D\u7F6E...");let c=zi(n);c.length>0&&t.push(` - \u68C0\u6D4B\u5230\u9879\u76EE\u7C7B\u578B: ${c.join(", ")}`);let l=await Ji(n),p={name:l.name,version:l.version,description:l.description,dependencies:l.dependencies||{},devDependencies:l.devDependencies||{}};t.push(` - \u9879\u76EE\u540D\u79F0: ${p.name}`),t.push(` - \u7248\u672C: ${p.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 u=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 m=await this.detectVersions(l,n);if(Object.keys(m).length>0)for(let[x,d]of Object.entries(m))t.push(` - ${x}: ${d}`);else t.push(" - \u672A\u68C0\u6D4B\u5230\u7248\u672C\u4FE1\u606F");t.push(""),t.push("\u{1F4D0} \u68C0\u6D4B\u4EE3\u7801\u89C4\u8303...");let S=this.detectCodeStandards(n,l.languages);S.length>0?t.push(` - \u68C0\u6D4B\u5230\u4EE3\u7801\u89C4\u8303: ${S.join(", ")}`):t.push(" - \u672A\u68C0\u6D4B\u5230\u4EE3\u7801\u89C4\u8303\u914D\u7F6E"),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 b=this.buildProjectBasicInfo(p,u,i,g,l,m,S);try{Yi(b,n),t.push("\u2705 \u9879\u76EE\u57FA\u7840\u4FE1\u606F\u5DF2\u4FDD\u5B58\u81F3: .nium/project/"),t.push("")}catch(x){console.error(" \u274C \u4FDD\u5B58\u9879\u76EE\u4FE1\u606F\u5931\u8D25:",x),t.push(`\u26A0\uFE0F \u4FDD\u5B58\u9879\u76EE\u4FE1\u606F\u5931\u8D25: ${x instanceof Error?x.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 x=Date.now(),d=Zi(i,f,n),k=((Date.now()-x)/1e3).toFixed(1);t.push("\u2705 \u6587\u4EF6\u4FE1\u606F\u5DF2\u66F4\u65B0\u81F3: .nium/project/files.jsonl"),t.push("");let T=ea(d);t.push(T),t.push("")}catch(x){console.error(" \u274C \u66F4\u65B0\u6587\u4EF6\u4FE1\u606F\u5931\u8D25:",x),t.push(`\u26A0\uFE0F \u66F4\u65B0\u6587\u4EF6\u4FE1\u606F\u5931\u8D25: ${x instanceof Error?x.message:"\u672A\u77E5\u9519\u8BEF"}`),t.push("")}let y=this.generateSummary(p,u,g,l);return t.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),t.push("\u9879\u76EE\u7ED3\u6784\u6982\u89C8"),t.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),t.push(y),t.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),t.push(""),t.join(`
|
|
1109
|
+
`)}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 o=Object.entries(n).map(([a,c])=>({language:a,count:c})).sort((a,c)=>c.count-a.count),[s]=o;return{primaryLanguage:s?.language||null,languages:o,totalSourceFiles:o.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"],o=[".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),(o.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 Cn.detectVersionsForLanguages(e.languages,t,e.configFiles)}catch{return{}}}detectCodeStandards(e,t){try{return Cn.detectCodeStandardsForLanguages(t,e)}catch{return[]}}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 o={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=o[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,o,s,i,a){let c=new Date().toISOString(),l=this.analyzeCoreModules(t),p=Object.keys(i).length>0?Object.entries(i).map(([g,m])=>`**${g}**: ${m}`).join(`
|
|
1066
1110
|
`):"\u6682\u65E0\u7248\u672C\u4FE1\u606F",u=a.length>0?a.map(g=>`- ${g}`).join(`
|
|
1067
1111
|
`):"\u6682\u65E0\u4EE3\u7801\u89C4\u8303\u914D\u7F6E";return`# ${e.name} - \u9879\u76EE\u7ED3\u6784\u6587\u6863
|
|
1068
1112
|
|
|
@@ -1074,7 +1118,7 @@ ${n.map(s=>`\u2022 ${s}`).join(`
|
|
|
1074
1118
|
**\u9879\u76EE\u540D\u79F0**: ${e.name}
|
|
1075
1119
|
**\u7248\u672C**: ${e.version}
|
|
1076
1120
|
**\u63CF\u8FF0**: ${e.description||"\u6682\u65E0\u63CF\u8FF0"}
|
|
1077
|
-
**\u4E3B\u8981\u7F16\u7A0B\u8BED\u8A00**: ${s.
|
|
1121
|
+
**\u4E3B\u8981\u7F16\u7A0B\u8BED\u8A00**: ${s.primaryLanguage}
|
|
1078
1122
|
${s.buildTool?`**\u6784\u5EFA\u5DE5\u5177**: ${s.buildTool}`:""}
|
|
1079
1123
|
|
|
1080
1124
|
### \u8FD0\u884C\u65F6\u7248\u672C
|
|
@@ -1103,7 +1147,7 @@ ${o.languages.length>0?o.languages.map(g=>`- **${g.language}**: ${g.count} \u4E2
|
|
|
1103
1147
|
|
|
1104
1148
|
## \u4E3B\u8981\u76EE\u5F55\u8BF4\u660E
|
|
1105
1149
|
|
|
1106
|
-
${this.generateDirectoryDescriptions(t.directories)}
|
|
1150
|
+
${this.generateDirectoryDescriptions(t.directories,s.languages)}
|
|
1107
1151
|
|
|
1108
1152
|
---
|
|
1109
1153
|
|
|
@@ -1156,11 +1200,11 @@ ${t.testFiles.length>0?t.testFiles.slice(0,20).map(g=>`- \`${g}\``).join(`
|
|
|
1156
1200
|
## \u4F9D\u8D56\u5173\u7CFB
|
|
1157
1201
|
|
|
1158
1202
|
### \u751F\u4EA7\u4F9D\u8D56
|
|
1159
|
-
${e.dependencies?Object.entries(e.dependencies).map(([g,
|
|
1203
|
+
${e.dependencies?Object.entries(e.dependencies).map(([g,m])=>`- **${g}**: ${m}`).join(`
|
|
1160
1204
|
`):"\u6682\u65E0\u751F\u4EA7\u4F9D\u8D56"}
|
|
1161
1205
|
|
|
1162
1206
|
### \u5F00\u53D1\u4F9D\u8D56
|
|
1163
|
-
${e.devDependencies?Object.entries(e.devDependencies).map(([g,
|
|
1207
|
+
${e.devDependencies?Object.entries(e.devDependencies).map(([g,m])=>`- **${g}**: ${m}`).join(`
|
|
1164
1208
|
`):"\u6682\u65E0\u5F00\u53D1\u4F9D\u8D56"}
|
|
1165
1209
|
|
|
1166
1210
|
---
|
|
@@ -1179,23 +1223,23 @@ ${this.findCoreModules(t.sourceFiles).map(g=>`- \`${g}\``).join(`
|
|
|
1179
1223
|
|
|
1180
1224
|
**\u6587\u6863\u751F\u6210\u65F6\u95F4**: ${c}
|
|
1181
1225
|
**\u6587\u6863\u751F\u6210\u5DE5\u5177**: quickProjectScan \u5DE5\u5177
|
|
1182
|
-
`}generateDirectoryTree(e){let t={};e.forEach(
|
|
1183
|
-
`,
|
|
1184
|
-
${
|
|
1226
|
+
`}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(([p,u],g)=>{let m=g===c.length-1,S=m?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",b=m?" ":"\u2502 ";l+=i+S+p+`
|
|
1227
|
+
`,u!==null&&typeof u=="object"&&(l+=n(u,i+b,m))}),l}let o=n(t);return o?o.trim():""}generateDirectoryDescriptions(e,t){let n=Cn.getDirectoryDescriptionsForLanguages(t);return e.map(o=>{let s=n[o]||"\u9879\u76EE\u76EE\u5F55";return`### \`${o}/\`
|
|
1228
|
+
${s}`}).join(`
|
|
1185
1229
|
|
|
1186
|
-
`)}findEntryPoints(e,t,n){let o=[];n.entryPoints&&n.entryPoints.length>0&&o.push(...n.entryPoints),e.main&&o.push(e.main),e.bin&&(typeof e.bin=="string"?o.push(e.bin):o.push(...Object.values(e.bin)));let s=
|
|
1230
|
+
`)}findEntryPoints(e,t,n){let o=[];n.entryPoints&&n.entryPoints.length>0&&o.push(...n.entryPoints),e.main&&o.push(e.main),e.bin&&(typeof e.bin=="string"?o.push(e.bin):o.push(...Object.values(e.bin)));let s=process.cwd(),i=Cn.findEntryPointsForLanguages(n.languages,t,s);return o.push(...i),[...new Set(o)]}findCoreModules(e){let t=new Set;return e.forEach(n=>{let o=n.match(/^src\/([^\/]+)\//);o&&t.add(`src/${o[1]}/`)}),Array.from(t).sort()}buildProjectBasicInfo(e,t,n,o,s,i,a){let c=Ki(o.languages),p=this.analyzeCoreModules(t).map(m=>({name:m.name,description:m.description,fileCount:m.files.length})),u;return s.primaryLanguage.includes("JavaScript")||s.primaryLanguage.includes("TypeScript")?Re("package-lock.json")?u="npm":Re("yarn.lock")?u="yarn":Re("pnpm-lock.yaml")?u="pnpm":u="npm":s.primaryLanguage.includes("Python")?Re("poetry.lock")?u="poetry":Re("Pipfile.lock")?u="pipenv":u="pip":s.primaryLanguage.includes("Java")?Re("pom.xml")?u="maven":Re("build.gradle")&&(u="gradle"):s.primaryLanguage.includes("Rust")?u="cargo":s.primaryLanguage.includes("Go")?u="go modules":s.primaryLanguage.includes("PHP")?u="composer":s.primaryLanguage.includes("Ruby")&&(u="bundler"),{projectName:e.name,version:e.version,description:e.description||"",primaryLanguage:o.primaryLanguage||s.primaryLanguage,languages:c,buildTool:s.buildTool,packageManager:u,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:e.dependencies,devDependencies:e.devDependencies,dependencyCount:{production:Object.keys(e.dependencies||{}).length,development:Object.keys(e.devDependencies||{}).length},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,o){return`
|
|
1187
1231
|
\u{1F4E6} \u9879\u76EE: ${e.name} (v${e.version})
|
|
1188
|
-
\u{1F310} \u4E3B\u8981\u8BED\u8A00: ${o.
|
|
1232
|
+
\u{1F310} \u4E3B\u8981\u8BED\u8A00: ${o.primaryLanguage}
|
|
1189
1233
|
${o.buildTool?`\u{1F527} \u6784\u5EFA\u5DE5\u5177: ${o.buildTool}`:""}
|
|
1190
1234
|
\u{1F4C1} \u4E3B\u8981\u76EE\u5F55: ${t.directories.join(", ")}
|
|
1191
1235
|
\u{1F4DD} \u6E90\u6587\u4EF6: ${t.sourceFiles.length} \u4E2A
|
|
1192
1236
|
\u2699\uFE0F \u914D\u7F6E\u6587\u4EF6: ${t.configFiles.length} \u4E2A
|
|
1193
1237
|
\u{1F4DA} \u6587\u6863\u6587\u4EF6: ${t.docFiles.length} \u4E2A
|
|
1194
1238
|
\u{1F9EA} \u6D4B\u8BD5\u6587\u4EF6: ${t.testFiles.length} \u4E2A
|
|
1195
|
-
`}formatAction(e){return"quickProjectScan()"}formatObservation(e){return String(e)}},
|
|
1196
|
-
`)}}catch{g("\u9879\u76EE\u7ED3\u6784\u626B\u63CF\u5931\u8D25\uFF0C\u5C06\u7EE7\u7EED\u6267\u884C\u4EFB\u52A1")}l(""),l(`${S}${"\u2550".repeat(60-e*2)}`),p(`${S}\u{1F4CB} \u5F00\u59CB\u89C4\u5212\u4EFB\u52A1 (\u5D4C\u5957\u5C42\u7EA7: ${e})`),l(`${S}${"\u2550".repeat(60-e*2)}`),l("");let
|
|
1239
|
+
`}formatAction(e){return"quickProjectScan()"}formatObservation(e){return String(e)}},Sa=new Fe;vt=Sa});var Qo={};U(Qo,{executePlanTask:()=>mu,getGlobalSession:()=>pu,resumePlanTask:()=>du,setGlobalSession:()=>Xo});import w from"chalk";function Xo(r){O=r}function pu(){return O}async function mu(r,e=1,t={}){let n=new ve,o=new we(n),s=new Te(n,o),i=new ke,a=wt(),c={useLLMDisclosure:t.useLLMDisclosure!==void 0?t.useLLMDisclosure:!0,useLLMSummary:t.useLLMSummary!==void 0?t.useLLMSummary:!0,verbose:t.verbose||!1},l=f=>{O?O.log(f):console.log(f)},p=f=>{O?O.info(f):console.log(w.blue(f))},u=f=>{O?O.success(f):console.log(w.green(f))},g=f=>{O?O.warning(f):console.log(w.yellow(f))},m=f=>{O?O.error(f):console.log(w.red(f))},S=" ".repeat(e-1),b=new br;try{let f=await import("fs"),y=await import("path");try{let T=y.join(process.cwd(),".nium/project/project.json");if(f.existsSync(T)){let P=f.statSync(T);(Date.now()-P.mtimeMs)/(1e3*60*60)>24&&g("\u26A0\uFE0F \u9879\u76EE\u7ED3\u6784\u6587\u6863\u5DF2\u8D85\u8FC724\u5C0F\u65F6\uFF0C\u5EFA\u8BAE\u66F4\u65B0")}else{p("\u{1F4CB} \u9996\u6B21\u6267\u884C\u4EFB\u52A1\uFF0C\u6B63\u5728\u626B\u63CF\u9879\u76EE\u7ED3\u6784...");let{quickProjectScan:P}=await Promise.resolve().then(()=>(Ko(),Ca));await P(),u(`\u2705 \u9879\u76EE\u7ED3\u6784\u626B\u63CF\u5B8C\u6210
|
|
1240
|
+
`)}}catch{g("\u9879\u76EE\u7ED3\u6784\u626B\u63CF\u5931\u8D25\uFF0C\u5C06\u7EE7\u7EED\u6267\u884C\u4EFB\u52A1")}l(""),l(`${S}${"\u2550".repeat(60-e*2)}`),p(`${S}\u{1F4CB} \u5F00\u59CB\u89C4\u5212\u4EFB\u52A1 (\u5D4C\u5957\u5C42\u7EA7: ${e})`),l(`${S}${"\u2550".repeat(60-e*2)}`),l("");let x=a.getAllSubAgents(),d=await ln(r,x);n.initializeTask(r,d),d.taskId&&Ke(d.taskId);let k=fu(un(d),e);l(k),l(""),b.showTaskStart(r,d.tasks.length,e);for(let T=0;T<d.tasks.length;T++){let P=d.tasks[T],$=P.step;b.showStepProgress($,d.tasks.length,P,e),n.plan.currentStep=$,d.taskId&&await Oe(d.taskId,$,"in_progress");try{let E=xa(P,a),D=await s.buildIsolatedContext($,P.description,E?.prompt||"",c.useLLMDisclosure,P.allowedTools);E?await ba($,P.description,E,D,n,i,a,c,{log:l,info:p,success:u,warning:g,error:m},P.allowedTools):await va(P.description,D,n,{log:l,info:p},P.allowedTools),b.showStepComplete($,d.tasks.length,P,e),d.taskId&&await Oe(d.taskId,$,"completed")}catch(E){let D=E instanceof Error?E.message:String(E);throw b.showStepError($,d.tasks.length,D,e),g(`${S}\u4E2D\u6B62\u540E\u7EED\u6B65\u9AA4\u6267\u884C`),n.recordStepCompletion($,`\u5931\u8D25: ${D}`,{success:!1,error:D}),E}}return b.showTaskComplete(d.tasks.length,d.tasks.length,e),Qe(),{success:!0,taskId:d.taskId,completedSteps:d.tasks.length,plan:d,planMarkdown:d.markdown,tasks:d.tasks}}catch(f){Qe();let y=f instanceof Error?f.message:String(f);throw m(`${S}\u274C \u89C4\u5212\u4EFB\u52A1\u6267\u884C\u5931\u8D25: ${y}`),f}}async function du(r,e=0,t={}){let{loadTaskPlan:n}=await Promise.resolve().then(()=>(ue(),be)),o=n(r);if(!o)throw new Error(`\u65E0\u6CD5\u52A0\u8F7D\u4EFB\u52A1\u8BA1\u5212: ${r}`);console.log(w.cyan(`[\u4EFB\u52A1\u6062\u590D] \u6B63\u5728\u6062\u590D\u4EFB\u52A1: ${r}`)),console.log(w.gray(`\u4ECE\u6B65\u9AA4 ${e||1} \u5F00\u59CB\u6267\u884C`));let s=new ve,i=new we(s),a=new Te(s,i),c=new ke,l=wt(),p={useLLMDisclosure:t.useLLMDisclosure!==void 0?t.useLLMDisclosure:!0,useLLMSummary:t.useLLMSummary!==void 0?t.useLLMSummary:!0,verbose:t.verbose||!1},u=d=>{O?O.log(d):console.log(d)},g=d=>{O?O.info(d):console.log(w.blue(d))},m=d=>{O?O.success(d):console.log(w.green(d))},S=d=>{O?O.warning(d):console.log(w.yellow(d))},b=d=>{O?O.error(d):console.log(w.red(d))},f=1,y="",x=new br;try{s.initializeTask(o.taskId,o),o.taskId&&Ke(o.taskId),u(""),u(w.cyan("\u2550".repeat(60))),g("\u{1F4CB} \u6062\u590D\u4EFB\u52A1\u6267\u884C"),u(w.cyan("\u2550".repeat(60))),u(""),x.showTaskStart(o.taskId,o.tasks.length,f);let d=e>0?e-1:0;for(let k=d;k<o.tasks.length;k++){let T=o.tasks[k],P=T.step;if(x.showStepProgress(P,o.tasks.length,T,f),s.plan.currentStep=P,o.taskId){let{updateTaskStatus:$}=await Promise.resolve().then(()=>(ue(),be));await $(o.taskId,P,"in_progress")}try{let $=xa(T,l),E=await a.buildIsolatedContext(P,T.description,$?.prompt||"",p.useLLMDisclosure,T.allowedTools);if($?await ba(P,T.description,$,E,s,c,l,p,{log:u,info:g,success:m,warning:S,error:b},T.allowedTools):await va(T.description,E,s,{log:u,info:g},T.allowedTools),x.showStepComplete(P,o.tasks.length,T,f),o.taskId){let{updateTaskStatus:D}=await Promise.resolve().then(()=>(ue(),be));await D(o.taskId,P,"completed")}}catch($){let E=$ instanceof Error?$.message:String($);throw x.showStepError(P,o.tasks.length,E,f),S(`${y}\u4E2D\u6B62\u540E\u7EED\u6B65\u9AA4\u6267\u884C`),s.recordStepCompletion(P,`\u5931\u8D25: ${E}`,{success:!1,error:E}),$}}return x.showTaskComplete(o.tasks.length,o.tasks.length,f),Qe(),{success:!0,taskId:o.taskId,completedSteps:o.tasks.length-d,resumedFrom:e||1}}catch(d){Qe();let k=d instanceof Error?d.message:String(d);throw b(`${y}\u274C \u4EFB\u52A1\u6062\u590D\u6267\u884C\u5931\u8D25: ${k}`),d}}function fu(r,e){return e<=1?r:r.split(`
|
|
1197
1241
|
`).map(o=>{if(o.trim().startsWith("#")){let s=o.match(/^#+/)?.[0].length||0,i=Math.min(s+e-1,6),a="#".repeat(i);return o.replace(/^#+/,a)}return o}).join(`
|
|
1198
|
-
`)}function
|
|
1242
|
+
`)}function xa(r,e){return r.subAgent&&r.subAgent!=="default"?e.getSubAgent(r.subAgent):null}async function ba(r,e,t,n,o,s,i,a,c,l){let{log:p,info:u,error:g}=c,m=Date.now();u(`\u{1F527} \u4F7F\u7528\u5B50\u667A\u80FD\u4F53: ${t.name}`),p(w.gray(`\u63CF\u8FF0: ${t.description}`)),l&&l.length>0&&p(w.gray(`\u6CE8\u610F: \u5B50\u667A\u80FD\u4F53 ${t.name} \u4E0D\u53D7\u6B65\u9AA4\u5DE5\u5177\u9650\u5236\u5F71\u54CD`)),p("");try{let{SYSTEM_PROMPT:S}=await Promise.resolve().then(()=>(je(),Lo)),b=[{role:"system",content:S},...n.filter(x=>x.role!=="system"),...n.filter(x=>x.role==="system"&&x!==n[0])],f=await wa(b,e,c,void 0);await hu(r,f,o,s,a,c);let y=Date.now()-m;i.recordAgentPerformance(t.name,!0,y)}catch(S){let b=Date.now()-m;throw i.recordAgentPerformance(t.name,!1,b),S}}async function va(r,e,t,n,o){let{log:s,info:i}=n;i("\u{1F916} \u4F7F\u7528\u9ED8\u8BA4React\u667A\u80FD\u4F53"),o&&o.length>0&&s(w.gray(`\u5DE5\u5177\u9650\u5236: ${o.join(", ")}`)),s("");let{SYSTEM_PROMPT:a}=await Promise.resolve().then(()=>(je(),Lo)),c=[{role:"system",content:a},...e.filter(l=>l.role!=="system"),...e.filter(l=>l.role==="system")];await wa(c,r,n,o)}async function wa(r,e,t,n){let{log:o,error:s}=t,{MODEL:i}=await Promise.resolve().then(()=>(ee(),Ze)),{callModelAPI:a}=await Promise.resolve().then(()=>(he(),pn)),{isThinkTool:c,extractThought:l}=await Promise.resolve().then(()=>(an(),$o)),{getToolDefinitions:p}=await Promise.resolve().then(()=>(St(),Zo)),{tools:u,toolInstances:g,extractToolResult:m}=await Promise.resolve().then(()=>(Se(),xn)),{saveSession:S}=await Promise.resolve().then(()=>(xe(),Vs)),{logDebug:b}=await Promise.resolve().then(()=>(K(),Ds)),f=[...r],y=0,x=50,d=p(),k=n&&n.length>0?d.filter(T=>n.includes(T.name)):d;for(n&&n.length>0&&b(`\u672C\u6B65\u9AA4\u53EF\u7528\u5DE5\u5177: ${k.map(T=>T.name).join(", ")}`);y<x;){y++;try{S(f,e);let T=await a({model:i(),messages:f,temperature:.1,tools:k}),P=T.choices[0].message.tool_calls;if(T.choices[0].finish_reason==="stop"){let{content:V}=T.choices[0].message;V&&V.trim()&&(o(w.green("\u4EFB\u52A1\u5B8C\u6210:")),o(V),o(""));break}if(!P||P.length===0){let{content:V}=T.choices[0].message;V&&V.trim()&&(o(w.yellow(V)),o(""));continue}let $=P[0],E=$.function.name;if(n&&n.length>0&&!n.includes(E)){let V=`Error: \u5DE5\u5177 '${E}' \u672A\u5728\u672C\u6B65\u9AA4\u7684\u6388\u6743\u5217\u8868\u4E2D\u3002\u5141\u8BB8\u4F7F\u7528\u7684\u5DE5\u5177: ${n.join(", ")}`;s(V),f.push({role:"assistant",content:null,tool_calls:[$]}),f.push({role:"tool",tool_call_id:$.id,content:V});continue}let D;try{D=JSON.parse($.function.arguments)}catch{s(`\u89E3\u6790\u5DE5\u5177\u53C2\u6570\u5931\u8D25: ${$.function.arguments}`),f.push({role:"assistant",content:null,tool_calls:[$]}),f.push({role:"tool",tool_call_id:$.id,content:"Error: Invalid JSON arguments"});continue}if(c(E)){let V=l($);V&&(o(w.cyan(`\u{1F4AD} Think: ${V}`)),o("")),f.push({role:"assistant",content:null,tool_calls:[$]}),f.push({role:"tool",tool_call_id:$.id,content:"Noted. Continue with your action."});continue}if(!u[E]){let V=`Error: Unknown tool '${E}'`;s(V),f.push({role:"assistant",content:null,tool_calls:[$]}),f.push({role:"tool",tool_call_id:$.id,content:V});continue}let pe=p().find(V=>V.name===E),j;if(pe&&pe.input_schema&&pe.input_schema.properties){j=Object.keys(pe.input_schema.properties).map(Je=>D[Je]);let ws=(pe.input_schema.required||[]).filter(Je=>D[Je]===void 0);if(ws.length>0){let Je=`Error: Missing required parameters: ${ws.join(", ")}`;s(Je),f.push({role:"assistant",content:null,tool_calls:[$]}),f.push({role:"tool",tool_call_id:$.id,content:Je});continue}}else j=Object.values(D);let ie=g[E],We=ie?ie.formatAction(D):`${E}()`;o(w.blue(`\u{1F527} \u884C\u52A8: ${We}`)),o("");let X=await u[E](...j),He=m(X),nc=ie?ie.shouldPrintObservation(X):!0,rc=ie?ie.formatObservation(X):String(X);nc&&(o(w.yellow(`\u{1F4CA} \u89C2\u5BDF: ${rc}`)),o("")),f.push({role:"assistant",content:null,tool_calls:[$]}),f.push({role:"tool",tool_call_id:$.id,content:String(He)}),S(f,e)}catch(T){throw s(`\u9519\u8BEF: ${T.message}`),S(f,e),T}}if(y>=x)throw s("\u9519\u8BEF: \u5DF2\u8FBE\u5230\u6700\u5927\u8FED\u4EE3\u6B21\u6570"),S(f,e),new Error("Maximum iterations reached");return f}async function hu(r,e,t,n,o,s){let{info:i,log:a}=s,c;o.useLLMSummary?c=await n.extractSummaryWithLLM(e):c=await n.extractSummary(e);let l=n.extractMetadata(e);l.success=!0,t.recordStepCompletion(r,c,l),o.verbose&&(i(`\u6B65\u9AA4 ${r} \u6458\u8981\u5DF2\u8BB0\u5F55\u5230\u5168\u5C40\u4E0A\u4E0B\u6587`),a(""),a(w.gray("\u2500\u2500\u2500 \u6B65\u9AA4\u6267\u884C\u6458\u8981 \u2500\u2500\u2500")),a(w.gray(`\u6458\u8981: ${c}`)),a(w.gray(`\u5DE5\u5177: ${l.toolsUsed.join(", ")}`)),a(w.gray(`\u6587\u4EF6: ${l.filesAccessed.join(", ")}`)),a(w.gray(`\u8FED\u4EE3: ${l.iterations} \u6B21`)))}var br,O,vr=C(()=>{ue();wr();xe();Oo();br=class{startTime;stepStartTime=null;constructor(){this.startTime=Date.now()}showTaskStart(e,t,n=1){let o=" ".repeat(n-1);console.log(""),console.log(w.cyan(`${o}\u2554${"\u2550".repeat(58-n*2)}\u2557`)),console.log(w.cyan(`${o}\u2551`)+w.bold.white(" \u{1F680} \u5F00\u59CB\u6267\u884C\u4EFB\u52A1\u8BA1\u5212")+w.cyan(` (\u5171${t}\u6B65)`.padEnd(58-n*2-13))+w.cyan("\u2551")),console.log(w.cyan(`${o}\u255A${"\u2550".repeat(58-n*2)}\u255D`)),console.log("")}showStepProgress(e,t,n,o=1){this.stepStartTime=Date.now();let s=" ".repeat(o-1),i=Math.round(e/t*100),a=this.createProgressBar(i,30);console.log(""),console.log(w.blue(`${s}\u250C${"\u2500".repeat(58-o*2)}\u2510`)),console.log(w.blue(`${s}\u2502`)+` \u6B65\u9AA4 ${e}/${t} (${i}%)`.padEnd(60-o*2)+w.blue("\u2502")),console.log(w.blue(`${s}\u2502`)+` ${a}`.padEnd(60-o*2)+w.blue("\u2502")),console.log(w.blue(`${s}\u2502`)+w.cyan(` \u{1F4CC} ${n.description}`.substring(0,58-o*2)).padEnd(60-o*2)+w.blue("\u2502")),console.log(w.blue(`${s}\u2502`)+w.gray(` \u{1F916} \u667A\u80FD\u4F53: ${n.subAgent}`.substring(0,58-o*2)).padEnd(60-o*2)+w.blue("\u2502")),console.log(w.blue(`${s}\u2514${"\u2500".repeat(58-o*2)}\u2518`)),console.log("")}showStepComplete(e,t,n,o=1){let s=" ".repeat(o-1),i=this.stepStartTime?this.formatDuration(Date.now()-this.stepStartTime):"",a=Math.round(e/t*100);console.log(w.green(`${s}\u2705 \u6B65\u9AA4 ${e}/${t} \u5B8C\u6210`)+w.gray(` (${i})`)),console.log("")}showTaskComplete(e,t,n=1){let o=" ".repeat(n-1),s=this.formatDuration(Date.now()-this.startTime),i=Math.round(e/t*100);console.log(""),console.log(w.green(`${o}\u2554${"\u2550".repeat(58-n*2)}\u2557`)),console.log(w.green(`${o}\u2551`)+w.bold.white(" \u{1F389} \u4EFB\u52A1\u6267\u884C\u5B8C\u6210!")+w.green("".padEnd(58-n*2-12))+w.green("\u2551")),console.log(w.green(`${o}\u2551`)+` \u5B8C\u6210\u8FDB\u5EA6: ${e}/${t} (${i}%)`.padEnd(60-n*2)+w.green("\u2551")),console.log(w.green(`${o}\u2551`)+` \u603B\u8017\u65F6: ${s}`.padEnd(60-n*2)+w.green("\u2551")),console.log(w.green(`${o}\u255A${"\u2550".repeat(58-n*2)}\u255D`)),console.log("")}showStepError(e,t,n,o=1){let s=" ".repeat(o-1);console.log(""),console.log(w.red(`${s}\u274C \u6B65\u9AA4 ${e}/${t} \u6267\u884C\u5931\u8D25`)),console.log(w.red(`${s} \u9519\u8BEF: ${n.substring(0,100)}`)),console.log("")}createProgressBar(e,t=30){let n=Math.round(e/100*t),o=t-n;return`${w.green("\u2588".repeat(n))+w.gray("\u2591".repeat(o))} ${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`}},O=null});import yu from"chalk";async function bn(r){return await Ta.execute({task:r})}var Tt,Ta,vn,ka=C(()=>{J();Tt=class r extends I{static nestingLevel=0;static MAX_NESTING_LEVEL=2;getDefinition(){return{name:"plan",description:`USE THIS TOOL FIRST for COMPLEX tasks! This is your PRIMARY tool for handling multi-step, cross-component work.
|
|
1199
1243
|
|
|
1200
1244
|
IDEAL USE CASES:
|
|
1201
1245
|
- Building new features that span multiple files or components
|
|
@@ -1217,20 +1261,20 @@ AVOID FOR:
|
|
|
1217
1261
|
- Simple read/write operations
|
|
1218
1262
|
- Individual command execution
|
|
1219
1263
|
|
|
1220
|
-
When you're uncertain if a task needs planning, default to using this tool - it will create an optimal execution strategy for you!`,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
|
|
1264
|
+
When you're uncertain if a task needs planning, default to using this tool - it will create an optimal execution strategy for you!`,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:o}=await Promise.resolve().then(()=>(ue(),be)),{getSubAgentManager:s}=await Promise.resolve().then(()=>(wr(),$a)),a=s().getAllSubAgents(),c=await o(t,a),l=`\u2705 \u4EFB\u52A1\u89C4\u5212\u5DF2\u751F\u6210\uFF08\u4EC5\u89C4\u5212\u6A21\u5F0F\uFF09
|
|
1221
1265
|
|
|
1222
1266
|
`;return l+=`**\u4EFB\u52A1 ID**: ${c.taskId}
|
|
1223
1267
|
`,l+=`**\u603B\u6B65\u9AA4\u6570**: ${c.tasks.length}
|
|
1224
1268
|
`,l+=`**\u8BA1\u5212\u7B56\u7565**: ${c.strategy}
|
|
1225
1269
|
|
|
1226
1270
|
`,l+=`**\u89C4\u5212\u5DF2\u4FDD\u5B58\u5230**:
|
|
1227
|
-
`,l+=`- Markdown:
|
|
1228
|
-
`,l+=`- JSON:
|
|
1271
|
+
`,l+=`- Markdown: ./.nium/tasks/${c.taskId}.md
|
|
1272
|
+
`,l+=`- JSON: ./.nium/tasks/${c.taskId}.json
|
|
1229
1273
|
|
|
1230
1274
|
`,l+=`**\u6267\u884C\u6B65\u9AA4**:
|
|
1231
1275
|
`,c.tasks.forEach((p,u)=>{l+=`${u+1}. ${p.description} [${p.subAgent}]
|
|
1232
1276
|
`}),l+=`
|
|
1233
|
-
\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(o){let s=o instanceof Error?o.message:String(o);return this.createToolResult(`Error: Failed to generate plan - ${s}`,`Error: Failed to generate plan - ${s}`,!0)}if(r.nestingLevel>=r.MAX_NESTING_LEVEL)return this.createToolResult(`Error: Maximum nesting level (${r.MAX_NESTING_LEVEL}) reached. Please use regular tools directly instead of the plan tool.`,`Error: Maximum nesting level (${r.MAX_NESTING_LEVEL}) reached. Please use regular tools directly instead of the plan tool.`,!0);r.nestingLevel++;try{let o;try{o=await(await Promise.resolve().then(()=>(
|
|
1277
|
+
\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(o){let s=o instanceof Error?o.message:String(o);return this.createToolResult(`Error: Failed to generate plan - ${s}`,`Error: Failed to generate plan - ${s}`,!0)}if(r.nestingLevel>=r.MAX_NESTING_LEVEL)return this.createToolResult(`Error: Maximum nesting level (${r.MAX_NESTING_LEVEL}) reached. Please use regular tools directly instead of the plan tool.`,`Error: Maximum nesting level (${r.MAX_NESTING_LEVEL}) reached. Please use regular tools directly instead of the plan tool.`,!0);r.nestingLevel++;try{let o;try{o=await(await Promise.resolve().then(()=>(vr(),Qo))).executePlanTask(t,r.nestingLevel)}catch{console.log(yu.yellow("[Plan-Tool] \u8B66\u544A: \u65E0\u6CD5\u5BFC\u5165plan-executor.js\uFF0C\u8FD4\u56DE\u4EFB\u52A1\u89C4\u5212\u5EFA\u8BAE")),o={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!
|
|
1234
1278
|
|
|
1235
1279
|
`;return s+=`**Task ID**: ${o.taskId}
|
|
1236
1280
|
`,s+=`**Completed Steps**: ${o.completedSteps}
|
|
@@ -1240,7 +1284,7 @@ ${o.planMarkdown}
|
|
|
1240
1284
|
|
|
1241
1285
|
`),o.tasks&&o.tasks.length>0&&(s+=`**Executed Steps**:
|
|
1242
1286
|
`,o.tasks.forEach((i,a)=>{s+=`${a+1}. \u2713 ${i.description}
|
|
1243
|
-
`})),this.createToolResult(s,s,!0)}catch(o){let s=o instanceof Error?o.message:String(o);return this.createToolResult(`Error: Task execution failed - ${s}`,`Error: Task execution failed - ${s}`,!0)}finally{r.nestingLevel--}}static getCurrentNestingLevel(){return r.nestingLevel}static resetNestingLevel(){r.nestingLevel=0}formatAction(e){return`plan(task="${e.task.length>100?e.task.substring(0,100)+"...":e.task}", nesting_level=${r.nestingLevel+1})`}formatObservation(e){return typeof e=="string"&&e.includes("Error:")?e:"Task planning completed. Check logs above for details."}},
|
|
1287
|
+
`})),this.createToolResult(s,s,!0)}catch(o){let s=o instanceof Error?o.message:String(o);return this.createToolResult(`Error: Task execution failed - ${s}`,`Error: Task execution failed - ${s}`,!0)}finally{r.nestingLevel--}}static getCurrentNestingLevel(){return r.nestingLevel}static resetNestingLevel(){r.nestingLevel=0}formatAction(e){return`plan(task="${e.task.length>100?e.task.substring(0,100)+"...":e.task}", nesting_level=${r.nestingLevel+1})`}formatObservation(e){return typeof e=="string"&&e.includes("Error:")?e:"Task planning completed. Check logs above for details."}},Ta=new Tt;vn=Ta});import _e from"readline";import Ne from"chalk";async function wn(r){return await Pa.execute(r)}var kt,Pa,Tn,Ma=C(()=>{J();kt=class extends I{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.
|
|
1244
1288
|
|
|
1245
1289
|
Use this tool when you need:
|
|
1246
1290
|
- User confirmation or decision
|
|
@@ -1257,7 +1301,7 @@ IMPORTANT:
|
|
|
1257
1301
|
Examples:
|
|
1258
1302
|
- askUser({ question: "Which file should I modify?" }) - Free text input
|
|
1259
1303
|
- askUser({ question: "Proceed with deletion?", choices: ["Yes", "No"] }) - Multiple choice
|
|
1260
|
-
- 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:o=!1}=e;try{let s;return n&&n.length>0?s=await this.showChoiceMenu(t,n,o):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(o=>{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 u=0;u<p;u++)u>0&&
|
|
1304
|
+
- 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:o=!1}=e;try{let s;return n&&n.length>0?s=await this.showChoiceMenu(t,n,o):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(o=>{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 u=0;u<p;u++)u>0&&_e.moveCursor(process.stdout,0,-1),_e.clearLine(process.stdout,0);console.log(""),console.log(Ne.cyan("\u{1F4AC} "+e)),console.log(""),console.log(Ne.gray("\u8BF7\u9009\u62E9 (\u4F7F\u7528\u4E0A\u4E0B\u7BAD\u5934\u952E\uFF0CEnter\u786E\u8BA4):")),console.log(""),i.forEach((u,g)=>{let m=g===s,S=m?Ne.green("> "):" ",b=m?Ne.green.bold(u.text):Ne.white(u.text);console.log(`${S}${b}`)}),console.log("")},c=process.stdin.isTTY?process.stdin.isRaw:!1;process.stdin.isTTY&&process.stdin.setRawMode(!0);let l=async(p,u)=>{if(u.name==="up"){s=Math.max(0,s-1),a();return}else if(u.name==="down"){s=Math.min(i.length-1,s+1),a();return}else if(u.name==="return"||u.name==="enter"){process.stdin.removeListener("keypress",l),process.stdin.isTTY&&process.stdin.setRawMode(c);let g=i.length+5;for(let S=0;S<g;S++)_e.moveCursor(process.stdout,0,-1),_e.clearLine(process.stdout,0);let m=i[s].value;if(m==="__CUSTOM__"){let S=await this.showFreeTextInput(e);o(S)}else o(m);return}else if(u.name==="escape"||u.ctrl&&u.name==="c"){process.stdin.removeListener("keypress",l),process.stdin.isTTY&&process.stdin.setRawMode(c);let g=i.length+5;for(let m=0;m<g;m++)_e.moveCursor(process.stdout,0,-1),_e.clearLine(process.stdout,0);o("__CANCELLED__");return}};process.stdin.on("keypress",l),a()})}showFreeTextInput(e){return new Promise(t=>{let n=e||"\u8BF7\u8F93\u5165\u60A8\u7684\u7B54\u6848",o=process.stdin.listeners("keypress");process.stdin.removeAllListeners("keypress");let s=_e.createInterface({input:process.stdin,output:process.stdout});console.log(""),console.log(Ne.cyan("\u{1F4AC} "+n)),console.log(""),s.question(Ne.gray("\u8BF7\u8F93\u5165\u7B54\u6848: "),i=>{s.removeAllListeners(),process.stdin.pause(),o.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)}},Pa=new kt;Tn=Pa});async function kn(r,e,t){return await Ea.execute({action:r,taskId:e,resumeFrom:t})}var $t,Ea,$n,Ia=C(()=>{J();$t=class extends I{getDefinition(){return{name:"todo",description:`Execute and manage saved task plans. Use this tool to:
|
|
1261
1305
|
- Resume execution of a previously generated plan
|
|
1262
1306
|
- List all available task plans
|
|
1263
1307
|
- View details of a specific task plan
|
|
@@ -1271,13 +1315,13 @@ WHEN TO USE:
|
|
|
1271
1315
|
FEATURES:
|
|
1272
1316
|
- Resume from any step (default: continue from last step)
|
|
1273
1317
|
- View task progress and status
|
|
1274
|
-
- List all available plans in
|
|
1318
|
+
- 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:o}=e;try{switch(t){case"resume":return await this.executeResume(n,o);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(()=>(vr(),Qo)),o=await n(e,t||0),s=`\u2705 \u4EFB\u52A1\u6062\u590D\u6267\u884C\u5B8C\u6210\uFF01
|
|
1275
1319
|
|
|
1276
1320
|
`;return s+=`**\u4EFB\u52A1 ID**: ${o.taskId}
|
|
1277
1321
|
`,s+=`**\u5B8C\u6210\u6B65\u9AA4**: ${o.completedSteps}
|
|
1278
1322
|
`,s+=`**\u6062\u590D\u8D77\u70B9**: \u6B65\u9AA4 ${o.resumedFrom}
|
|
1279
1323
|
|
|
1280
|
-
`,s+="\u6240\u6709\u6B65\u9AA4\u5DF2\u6210\u529F\u6267\u884C\u5B8C\u6BD5\u3002",this.createToolResult(s,s,!0)}catch(n){let o=n instanceof Error?n.message:String(n);return this.createToolResult(`Error: Failed to resume task - ${o}`,`Error: Failed to resume task - ${o}`,!0)}}async executeList(){try{let{listTaskPlans:e,loadTaskPlan:t}=await Promise.resolve().then(()=>(
|
|
1324
|
+
`,s+="\u6240\u6709\u6B65\u9AA4\u5DF2\u6210\u529F\u6267\u884C\u5B8C\u6BD5\u3002",this.createToolResult(s,s,!0)}catch(n){let o=n instanceof Error?n.message:String(n);return this.createToolResult(`Error: Failed to resume task - ${o}`,`Error: Failed to resume task - ${o}`,!0)}}async executeList(){try{let{listTaskPlans:e,loadTaskPlan:t}=await Promise.resolve().then(()=>(ue(),be)),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 o=`\u{1F4CB} \u5DF2\u4FDD\u5B58\u7684\u4EFB\u52A1\u8BA1\u5212 (\u5171 ${n.length} \u4E2A)
|
|
1281
1325
|
`;o+=`${"\u2550".repeat(60)}
|
|
1282
1326
|
|
|
1283
1327
|
`;for(let s of n){let i=t(s);if(i){let a=i.tasks.filter(p=>p.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";o+=`**${s}**
|
|
@@ -1288,7 +1332,7 @@ FEATURES:
|
|
|
1288
1332
|
`,o+=`
|
|
1289
1333
|
`}}return o+=`
|
|
1290
1334
|
\u{1F4A1} \u4F7F\u7528 todo(action="view", taskId="...") \u67E5\u770B\u8BE6\u60C5`,o+=`
|
|
1291
|
-
\u{1F4A1} \u4F7F\u7528 todo(action="resume", taskId="...") \u6062\u590D\u6267\u884C`,this.createToolResult(o,o,!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(()=>(
|
|
1335
|
+
\u{1F4A1} \u4F7F\u7528 todo(action="resume", taskId="...") \u6062\u590D\u6267\u884C`,this.createToolResult(o,o,!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(()=>(ue(),be)),n=t(e);if(!n)return this.createToolResult(`Error: Task plan '${e}' not found`,`Error: Task plan '${e}' not found`,!0);let o=`\u{1F4CB} \u4EFB\u52A1\u8BA1\u5212\u8BE6\u60C5
|
|
1292
1336
|
`;o+=`${"\u2550".repeat(60)}
|
|
1293
1337
|
|
|
1294
1338
|
`,o+=`**\u4EFB\u52A1 ID**: ${n.taskId}
|
|
@@ -1310,11 +1354,11 @@ FEATURES:
|
|
|
1310
1354
|
`),o+=`
|
|
1311
1355
|
`}let s=n.tasks.find(i=>i.status!=="completed");return s?o+=`
|
|
1312
1356
|
\u{1F4A1} \u4F7F\u7528 todo(action="resume", taskId="${e}", resumeFrom=${s.step}) \u4ECE\u6B65\u9AA4 ${s.step} \u7EE7\u7EED\u6267\u884C`:o+=`
|
|
1313
|
-
\u2705 \u6240\u6709\u6B65\u9AA4\u5DF2\u5B8C\u6210\uFF01`,this.createToolResult(o,o,!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:o}=e,s=`todo(action="${t}"`;return n&&(s+=`, taskId="${n}"`),o&&(s+=`, resumeFrom=${o}`),s+=")",s}},
|
|
1357
|
+
\u2705 \u6240\u6709\u6B65\u9AA4\u5DF2\u5B8C\u6210\uFF01`,this.createToolResult(o,o,!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:o}=e,s=`todo(action="${t}"`;return n&&(s+=`, taskId="${n}"`),o&&(s+=`, resumeFrom=${o}`),s+=")",s}},Ea=new $t;$n=Ea});var es={};U(es,{AskUserTool:()=>kt,PlanTool:()=>Tt,QuickProjectScanTool:()=>Fe,THINK_TOOL:()=>nr,ThinkTool:()=>De,TodoTool:()=>$t,askUser:()=>wn,askUserTool:()=>Tn,extractThought:()=>rr,isThinkTool:()=>ht,plan:()=>bn,planTool:()=>vn,quickProjectScan:()=>bt,quickProjectScanTool:()=>vt,think:()=>dt,thinkTool:()=>ft,todo:()=>kn,todoTool:()=>$n});var Tr=C(()=>{an();ka();Ma();Ko();Ia()});var Da={};U(Da,{getGitDiff:()=>Mn,getGitStatus:()=>Pn,gitAddAll:()=>ts,gitCommit:()=>ns,hasUncommittedChanges:()=>En,isGitAvailable:()=>bu});import{execSync as Ue}from"child_process";import{existsSync as Aa,writeFileSync as Su,unlinkSync as Cu}from"fs";import{join as La}from"path";import{tmpdir as xu}from"os";function bu(){try{let r=La(process.cwd(),".git");return Aa(r)?(Ue("git --version",{stdio:"ignore"}),h("Git is available"),!0):(h("Git not available: .git directory not found"),!1)}catch(r){return h(`Git not available: ${r.message}`),!1}}function Pn(){try{return Ue("git status",{encoding:"utf-8"})}catch(r){return z(`Failed to get git status: ${r.message}`),""}}function Mn(){try{let r=Ue("git diff --cached",{encoding:"utf-8"}),e=Ue("git diff",{encoding:"utf-8"}),t="";return r&&(t+=`=== Staged Changes ===
|
|
1314
1358
|
`+r+`
|
|
1315
1359
|
`),e&&(t+=`=== Unstaged Changes ===
|
|
1316
|
-
`+e),t||"No changes detected"}catch(r){return
|
|
1317
|
-
`))if(o.length>=3){let s=o.substring(0,2).trim(),i=o.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
|
|
1360
|
+
`+e),t||"No changes detected"}catch(r){return z(`Failed to get git diff: ${r.message}`),""}}function ts(){try{Ue("git add .",{stdio:"inherit"})}catch(r){throw new Error(`Failed to stage changes: ${r.message}`)}}function ns(r){let e=La(xu(),`git-commit-${Date.now()}.txt`);try{Su(e,r,"utf-8"),Ue(`git commit -F "${e}"`,{stdio:"inherit"})}catch(t){throw new Error(`Failed to commit: ${t.message}`)}finally{try{Aa(e)&&Cu(e)}catch(t){z(`Failed to cleanup temporary file: ${t.message}`)}}}function En(){try{return Ue("git status --porcelain",{encoding:"utf-8"}).trim().length>0}catch(r){return z(`Failed to check for uncommitted changes: ${r.message}`),!1}}var kr=C(()=>{K()});var os={};U(os,{FileChangeTracker:()=>Mt,createFileChangeTracker:()=>$r,detectFileChanges:()=>Mr,generateChangeSummary:()=>Er,getCurrentSessionFileChanges:()=>Dr,getFileChangeTracker:()=>ge,getSessionFileChanges:()=>Lr,handleGitCommit:()=>Ar,recordFileChange:()=>Ir,resetFileChangeTracker:()=>Pr});import{execSync as rs}from"child_process";function ge(r){return Pt||(Pt=new Mt(r)),Pt}function $r(r){return new Mt(r)}function Pr(){Pt&&(Pt.stopWatching(),Pt=null)}async function Mr(r,e){return ge(e).detectFileChanges(r)}function Er(r="text"){return ge().generateChangeSummaryText(r)}function Ir(r){let e={id:Ee(),filePath:r.filePath,changeType:r.changeType,timestamp:new Date().toISOString(),source:r.source||"manual",content:r.content,size:r.size};return ge().trackSessionFileChange("default-session",void 0,[e]),e}async function Ar(r){return ge().handleGitCommit(r)}function Lr(r){return ge().getSessionFileChanges(r)}function Dr(){return ge().getCurrentSessionFileChanges()}var vu,Mt,Pt,jr=C(()=>{Wn();kr();vu={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"},Mt=class{config;sessionChanges=new Map;commitHistory=[];gitStatusCache=new Map;changeCallbacks=[];isWatching=!1;gitStatusTimer;constructor(e){this.config={...vu,...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 o={hasChanges:t.length>0,changes:t,summary:this.generateChangeSummary(t)};return t.length>0&&this.triggerChangeCallbacks(t),o}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(!En())return e;let t=Pn(),n=Mn(),o=this.parseGitStatus(t),s=this.getCurrentGitHash(),i=this.getCurrentBranch(),a=new Date().toISOString();for(let c of o){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 p={id:Ee(),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(p),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=rs("git status --porcelain",{encoding:"utf-8"});for(let o of n.trim().split(`
|
|
1361
|
+
`))if(o.length>=3){let s=o.substring(0,2).trim(),i=o.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 rs("git rev-parse HEAD",{encoding:"utf-8"}).trim()}catch{return"unknown"}}getCurrentBranch(){try{return rs("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 o=this.sessionChanges.get(e),s=new Date().toISOString();if(o){let i=[...o.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)}o.changes=i,o.updatedAt=s,o.totalFiles=i.length,o.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[o,s]of this.sessionChanges.entries())s.updatedAt<n&&s.committed&&this.sessionChanges.delete(o);this.commitHistory=this.commitHistory.filter(o=>o.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),o=`\u{1F4CA} \u6587\u4EF6\u53D8\u52A8\u6458\u8981
|
|
1318
1362
|
|
|
1319
1363
|
`;return o+=`\u{1F4C1} \u603B\u6587\u4EF6\u6570: ${n.totalFiles}
|
|
1320
1364
|
`,o+=`\u2795 \u65B0\u589E\u6587\u4EF6: ${n.addedFiles}
|
|
@@ -1323,12 +1367,10 @@ FEATURES:
|
|
|
1323
1367
|
`,o+=`\u{1F504} \u91CD\u547D\u540D\u6587\u4EF6: ${n.renamedFiles}
|
|
1324
1368
|
`,o+=`\u{1F4E6} \u603B\u5927\u5C0F: ${(n.totalSize/1024).toFixed(2)} KB
|
|
1325
1369
|
`,o+=`
|
|
1326
|
-
\u{1F550} \u751F\u6210\u65F6\u95F4: ${new Date().toLocaleString()}`,o}},
|
|
1327
|
-
|
|
1328
|
-
`);this.outputBuffer=t.pop()||"";for(let n of t)if(n.trim())try{let o=JSON.parse(n);this.handleMessage(o)}catch{J(`Failed to parse MCP message: ${n}`)}}handleMessage(e){if(e.id!==void 0){let t=this.pendingRequests.get(e.id);t&&(this.pendingRequests.delete(e.id),e.error?t.reject(new Error(e.error.message||"Unknown error")):t.resolve(e.result))}else e.method&&m(`MCP notification: ${e.method}`)}}});var Gi=w(()=>{yr();Ro();Lo()});function Mt(){return jo.getInstance()}var jo,Fo=w(()=>{Ro();Lo();H();jo=class r{static instance=null;clients=new Map;mcpTools=new Map;initialized=!1;constructor(){}static getInstance(){return r.instance||(r.instance=new r),r.instance}async initialize(e){if(this.initialized){J("MCP Manager already initialized");return}M(`Initializing ${e.length} MCP server(s)...`),e.length>0&&(m("MCP Server Configurations:"),e.forEach(t=>{m(` - Server: ${t.name} (${t.transport})`),m(` Enabled: ${t.enabled!==!1}`),t.url?m(` URL: ${t.url}`):t.command&&m(` Command: ${t.command}`)}));for(let t of e){if(t.enabled===!1){m(`Skipping disabled MCP server: ${t.name}`);continue}try{m(`Attempting to connect to MCP server ${t.name} with URL: ${t.url||"N/A"}`),await this.connectToServer(t)}catch(n){q(`Failed to connect to MCP server ${t.name}: ${n.message}`),m(`Error details for ${t.name}: ${n.message}
|
|
1329
|
-
${n.stack||""}`)}}this.initialized=!0,M(`MCP Manager initialized with ${this.clients.size} server(s) and ${this.mcpTools.size} tool(s)`)}async connectToServer(e){m(`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 o of n)this.registerTool(o);M(`Connected to MCP server: ${e.name} (${n.length} tools)`)}createClient(e){switch(e.transport){case"http":case"sse":return new bn(e);case"stdio":return new kn(e);default:throw new Error(`Unsupported transport type: ${e.transport}`)}}registerTool(e){let t=e.name;if(this.mcpTools.has(t)){J(`MCP tool ${t} already registered, skipping (using first registered)`);return}this.mcpTools.set(t,e),m(`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 o=this.clients.get(n.serverName);return o?o.isConnected()?o.callTool(e,t):{success:!1,error:`MCP server not connected: ${n.serverName}`}:{success:!1,error:`MCP server not connected: ${n.serverName}`}}async disconnectAll(){m("Disconnecting all MCP servers...");for(let[e,t]of this.clients.entries())try{await t.disconnect(),m(`Disconnected from MCP server: ${e}`)}catch(n){q(`Error disconnecting from ${e}: ${n.message}`)}this.clients.clear(),this.mcpTools.clear(),this.initialized=!1,M("All MCP servers disconnected")}getStatus(){let e=Array.from(this.clients.entries()).map(([t,n])=>({name:t,connected:n.isConnected(),toolCount:n.getCachedTools().length}));return{initialized:this.initialized,serversConnected:this.clients.size,toolsAvailable:this.mcpTools.size,servers:e}}}});function Vi(r){let e={};for(let t of r)e[t.name]=new Sr(t);return e}function Bi(r){let e={};for(let t of r){let n=new Sr(t);e[t.name]=async(...o)=>n.execute(...o)}return e}var Sr,Yi=w(()=>{Fo();G();Se();H();Sr=class extends I{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){m(`Executing MCP tool: ${this.mcpTool.name}`);let t=this.argsToParams(e),o=await Mt().callTool(this.mcpTool.name,t);if(!o.success)throw new Error(o.error||"MCP tool execution failed");let s=this.formatMCPResult(o.content);return Do(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||{},o=Object.keys(n),s={};return e.forEach((i,a)=>{a<o.length&&(s[o[a]]=i)}),s}formatMCPResult(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>this.formatContentItem(t)).join(`
|
|
1370
|
+
\u{1F550} \u751F\u6210\u65F6\u95F4: ${new Date().toLocaleString()}`,o}},Pt=null});var xn={};U(xn,{AgentTools:()=>es,AskUserTool:()=>kt,BaseTool:()=>I,ConfirmableTool:()=>re,CopyTool:()=>it,CoreTools:()=>uo,DeleteTool:()=>ot,FileChangeTools:()=>os,FileChangeTracker:()=>Mt,FileOpsTools:()=>bo,GlobTool:()=>ut,GrepTool:()=>gt,MergeTool:()=>at,MkdirTool:()=>nt,MoveTool:()=>st,PlanTool:()=>Tt,QuickProjectScanTool:()=>Fe,ReadTool:()=>tt,SearchReplaceTool:()=>ct,SearchTools:()=>vo,ShellTool:()=>pt,SystemTools:()=>To,THINK_TOOL:()=>nr,ThinkTool:()=>De,TodoTool:()=>$t,WriteTool:()=>rt,askUser:()=>wn,askUserTool:()=>Tn,copyFile:()=>Yt,copyTool:()=>Kt,createFileChangeTracker:()=>$r,createToolResult:()=>is,deleteFile:()=>Gt,deleteTool:()=>zt,detectFileChanges:()=>Mr,extractThought:()=>rr,extractToolResult:()=>_t,fileChangeTracking:()=>wu,generateChangeSummary:()=>Er,getCurrentSessionFileChanges:()=>Dr,getFileChangeTracker:()=>ge,getSessionFileChanges:()=>Lr,glob:()=>tn,globTool:()=>nn,grep:()=>rn,grepTool:()=>on,handleGitCommit:()=>Ar,isThinkTool:()=>ht,isToolResult:()=>et,merge:()=>Xt,mergeTool:()=>Qt,mkdir:()=>Wt,mkdirTool:()=>Le,moveFile:()=>qt,moveTool:()=>Bt,plan:()=>bn,planTool:()=>vn,quickProjectScan:()=>bt,quickProjectScanTool:()=>vt,read:()=>Ut,readTool:()=>Vt,recordFileChange:()=>Ir,resetFileChangeTracker:()=>Pr,searchReplace:()=>Zt,searchReplaceTool:()=>en,shell:()=>sn,shellTool:()=>mt,think:()=>dt,thinkTool:()=>ft,todo:()=>kn,todoTool:()=>$n,toolInstances:()=>R,tools:()=>ss,write:()=>Ht,writeTool:()=>Jt});function is(r,e=null,t=!0){return{__tool_result:!0,result:r,display:e!==null?e:r,shouldPrint:t}}var R,ss,wu,Se=C(()=>{go();go();Xn();Xn();Zn();Zn();tr();tr();Tr();Tr();jr();jr();Xn();Zn();tr();Tr();jr();R={think:ft,plan:vn,todo:$n,askUser:Tn,quickProjectScan:vt,read:Vt,write:Jt,mkdir:Le,glob:nn,grep:on,shell:mt,merge:Qt,deleteFile:zt,moveFile:Bt,copyFile:Kt,search_replace:en},ss={think:dt,plan:bn,todo:kn,askUser:wn,quickProjectScan:bt,read:Ut,write:Ht,mkdir:Wt,merge:Xt,glob:tn,grep:rn,shell:sn,deleteFile:Gt,moveFile:qt,copyFile:Yt,search_replace:Zt},wu={detectFileChanges:Mr,generateChangeSummary:Er,recordFileChange:Ir,handleGitCommit:Ar,getSessionFileChanges:Lr,getCurrentSessionFileChanges:Dr,getFileChangeTracker:ge,createFileChangeTracker:$r,resetFileChangeTracker:Pr}});var ja=C(()=>{});import{Client as Tu}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as ku}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{StdioClientTransport as $u}from"@modelcontextprotocol/sdk/client/stdio.js";var In,as=C(()=>{K();In=class{client=null;config;connected=!1;tools=[];constructor(e){this.config={timeout:3e4,enabled:!0,...e}}async connect(){h(`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 ku(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 $u({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 Tu({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})),h(`Loaded ${this.tools.length} tools from ${this.config.name}`)}catch(e){throw h(`Failed to connect to MCP server ${this.config.name}: ${e.message}`),e}}async disconnect(){h(`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 Oa=C(()=>{as()});function Et(){return cs.getInstance()}var cs,ls=C(()=>{as();K();cs=class r{static instance=null;clients=new Map;mcpTools=new Map;initialized=!1;constructor(){}static getInstance(){return r.instance||(r.instance=new r),r.instance}async initialize(e){if(this.initialized){z("MCP Manager already initialized");return}M(`Initializing ${e.length} MCP server(s)...`),e.length>0&&(h("MCP Server Configurations:"),e.forEach(t=>{h(` - Server: ${t.name} (${t.transport})`),h(` Enabled: ${t.enabled!==!1}`),t.url?h(` URL: ${t.url}`):t.command&&h(` Command: ${t.command}`)}));for(let t of e){if(t.enabled===!1){h(`Skipping disabled MCP server: ${t.name}`);continue}try{h(`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}`),h(`Error details for ${t.name}: ${n.message}
|
|
1371
|
+
${n.stack||""}`)}}this.initialized=!0,M(`MCP Manager initialized with ${this.clients.size} server(s) and ${this.mcpTools.size} tool(s)`)}async connectToServer(e){h(`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 o of n)this.registerTool(o);M(`Connected to MCP server: ${e.name} (${n.length} tools)`)}createClient(e){return new In(e)}registerTool(e){let t=e.name;if(this.mcpTools.has(t)){z(`MCP tool ${t} already registered, skipping (using first registered)`);return}this.mcpTools.set(t,e),h(`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 o=this.clients.get(n.serverName);return o?o.isConnected()?o.callTool(e,t):{success:!1,error:`MCP server not connected: ${n.serverName}`}:{success:!1,error:`MCP server not connected: ${n.serverName}`}}async disconnectAll(){h("Disconnecting all MCP servers...");for(let[e,t]of this.clients.entries())try{await t.disconnect(),h(`Disconnected from MCP server: ${e}`)}catch(n){Y(`Error disconnecting from ${e}: ${n.message}`)}this.clients.clear(),this.mcpTools.clear(),this.initialized=!1,M("All MCP servers disconnected")}getStatus(){let e=Array.from(this.clients.entries()).map(([t,n])=>({name:t,connected:n.isConnected(),toolCount:n.getCachedTools().length}));return{initialized:this.initialized,serversConnected:this.clients.size,toolsAvailable:this.mcpTools.size,servers:e}}}});function Ra(r){let e={};for(let t of r)e[t.name]=new Or(t);return e}function Fa(r){let e={};for(let t of r){let n=new Or(t);e[t.name]=async(...o)=>n.execute(...o)}return e}var Or,_a=C(()=>{ls();J();Se();K();Or=class extends I{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){h(`Executing MCP tool: ${this.mcpTool.name}`);let t=this.argsToParams(e),o=await Et().callTool(this.mcpTool.name,t);if(!o.success)throw new Error(o.error||"MCP tool execution failed");let s=this.formatMCPResult(o.content);return is(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||{},o=Object.keys(n),s={};return e.forEach((i,a)=>{a<o.length&&(s[o[a]]=i)}),s}formatMCPResult(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>this.formatContentItem(t)).join(`
|
|
1330
1372
|
|
|
1331
|
-
`):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,o])=>`${n}=${JSON.stringify(o)}`).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
|
|
1373
|
+
`):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,o])=>`${n}=${JSON.stringify(o)}`).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 us=C(()=>{ja();Oa();ls();_a()});async function Rr(){if(gs){h("Tools already loaded, skipping");return}M("Loading tools..."),It={...R},Na={...ss};let r=Object.keys(R);M(`Loaded ${r.length} local tools`);let t=Et().getAllTools();if(t.length===0){h("No MCP tools available"),gs=!0;return}let n=Ra(t),o=Fa(t),s=0,i=0;for(let[a,c]of Object.entries(n)){if(It[a]){h(`Skipping MCP tool ${a} (local tool has priority)`),i++;continue}It[a]=c,Na[a]=o[a],s++}M(`Added ${s} MCP tools, skipped ${i} (local priority)`),M(`Total tools available: ${Object.keys(It).length}`),gs=!0}function At(){return It}function Ua(){let r=Object.keys(R),e=Object.keys(It),t=e.filter(n=>!r.includes(n));return{local:r.length,mcp:t.length,total:e.length,localTools:r,mcpTools:t}}var It,Na,gs,An=C(()=>{Se();us();K();It={},Na={},gs=!1});var Zo={};U(Zo,{TOOL_DEFINITIONS:()=>Fr,getRawToolDefinitions:()=>cn,getToolDefinitions:()=>Ln,getToolNames:()=>Wa,isRealTool:()=>Pu});function Va(r){return{name:r.name,description:r.description,input_schema:r.input_schema}}function Ln(){let r=At();if(Object.keys(r).length===0)return Fr.map(Va);let e=[],t=["think","plan","todo","askUser"];for(let n of t)if(r[n]){let o=r[n].getDefinition();o&&e.push(o)}for(let[n,o]of Object.entries(r))if(!t.includes(n)&&o){let s=o.getDefinition();s&&e.push(s)}return e.filter(n=>n!=null).map(Va)}function cn(){return Fr}function Wa(){return Fr.map(r=>r.name)}function Pu(r){return r!=="think"&&Wa().includes(r)}var Fr,St=C(()=>{Se();An();Fr=[R.think.getDefinition(),R.plan.getDefinition(),R.todo.getDefinition(),R.askUser.getDefinition(),R.quickProjectScan.getDefinition(),R.read.getDefinition(),R.write.getDefinition(),R.merge.getDefinition(),R.mkdir.getDefinition(),R.glob.getDefinition(),R.grep.getDefinition(),R.deleteFile.getDefinition(),R.moveFile.getDefinition(),R.copyFile.getDefinition(),R.search_replace.getDefinition(),R.shell.getDefinition()]});function ps(r){return!r||typeof r!="string"?0:Math.ceil(r.length/4)}function $e(r){if(!Array.isArray(r))return 0;let e=0;for(let t of r){if(t.content&&typeof t.content=="string"&&(e+=ps(t.content)),t.tool_calls&&Array.isArray(t.tool_calls))for(let n of t.tool_calls)n.function&&(e+=ps(n.function.name||""),e+=ps(n.function.arguments||""));e+=4}return e}function _r(r,e){return!e||e<=0?0:r/e*100}function ms(r,e,t=80){return _r(r,e)>=t}function ds(r,e,t){return`\u26A0\uFE0F Token usage warning: ${r.toLocaleString()} / ${e.toLocaleString()} tokens (${t.toFixed(1)}%)`}var fs=C(()=>{});import Dn from"chalk";var Nr,Ha=C(()=>{fs();K();Nr=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?$e(e)/t>=this.options.threshold:!1}async compress(e,t,n){let o=$e(e),s=e.length;M(`\u5F00\u59CB\u4E0A\u4E0B\u6587\u538B\u7F29: ${s} \u6761\u6D88\u606F, ${o} tokens`);let i=this.calculateDynamicWindowSize(e,t);h(`\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 z("\u6CA1\u6709\u9700\u8981\u538B\u7F29\u7684\u6D88\u606F,\u8DF3\u8FC7\u538B\u7F29"),{messages:e,stats:{originalMessageCount:s,originalTokenCount:o,compressedMessageCount:s,compressedTokenCount:o,compressionRatio:1,llmSummaryCount:0,heuristicSummaryCount:0}};let{summaryMessage:l,llmCount:p,heuristicCount:u}=await this.createCompressedSummary(a,n),g=[l,...c],m=$e(g),S={originalMessageCount:s,originalTokenCount:o,compressedMessageCount:g.length,compressedTokenCount:m,compressionRatio:m/o,llmSummaryCount:p,heuristicSummaryCount:u};return this.logCompressionStats(S),{messages:g,stats:S}}calculateDynamicWindowSize(e,t){let o=$e(e)/t,s;return o>=.9?(s=this.options.minKeepMessages,h("Token\u538B\u529B\u6781\u9AD8 (>=90%), \u4F7F\u7528\u6700\u5C0F\u7A97\u53E3")):o>=.85?(s=Math.floor(this.options.minKeepMessages+(this.options.maxKeepMessages-this.options.minKeepMessages)*.25),h("Token\u538B\u529B\u9AD8 (>=85%), \u4F7F\u7528\u8F83\u5C0F\u7A97\u53E3")):o>=.8?(s=Math.floor(this.options.minKeepMessages+(this.options.maxKeepMessages-this.options.minKeepMessages)*.5),h("Token\u538B\u529B\u4E2D\u7B49 (>=80%), \u4F7F\u7528\u4E2D\u7B49\u7A97\u53E3")):(s=this.options.maxKeepMessages,h("Token\u538B\u529B\u6B63\u5E38, \u4F7F\u7528\u6700\u5927\u7A97\u53E3")),Math.min(s,e.length)}async createCompressedSummary(e,t){let n=[],o=0,s=0,i=this.groupMessages(e);for(let c of i){let l=$e(c),p=this.assessMessageImportance(c),u;this.options.useMixedSummary&&p==="important"&&l>=this.options.llmSummaryTokenThreshold&&t?(u=await this.generateLLMSummary(c,t),o++,h(`\u4F7F\u7528LLM\u6458\u8981 (${c.length}\u6761\u6D88\u606F, ${l} tokens)`)):(u=this.generateHeuristicSummary(c),s++,h(`\u4F7F\u7528\u542F\u53D1\u5F0F\u6458\u8981 (${c.length}\u6761\u6D88\u606F, ${l} tokens)`)),n.push(u)}return{summaryMessage:{role:"system",content:`[\u5386\u53F2\u4E0A\u4E0B\u6587\u6458\u8981]
|
|
1332
1374
|
\u4EE5\u4E0B\u662F\u4E4B\u524D\u7684\u5BF9\u8BDD\u6458\u8981,\u5DF2\u538B\u7F29\u4EE5\u8282\u7701token:
|
|
1333
1375
|
|
|
1334
1376
|
${n.join(`
|
|
@@ -1337,34 +1379,34 @@ ${n.join(`
|
|
|
1337
1379
|
|
|
1338
1380
|
`)}
|
|
1339
1381
|
|
|
1340
|
-
[\u6458\u8981\u7ED3\u675F]`},llmCount:o,heuristicCount:s}}groupMessages(e){let t=[];for(let o=0;o<e.length;o+=3)t.push(e.slice(o,o+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(()=>(
|
|
1341
|
-
`);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:o}],temperature:.1,max_tokens:200,useCompression:!0})).choices?.[0]?.message?.content?.trim()||"\u6267\u884C\u5B8C\u6210"}`}catch(n){return
|
|
1342
|
-
\u2728 \u4E0A\u4E0B\u6587\u538B\u7F29\u5B8C\u6210`)),console.log(
|
|
1343
|
-
`)),M(`\u4E0A\u4E0B\u6587\u538B\u7F29: ${e.originalMessageCount}\u6761 \u2192 ${e.compressedMessageCount}\u6761, ${e.originalTokenCount}tokens \u2192 ${e.compressedTokenCount}tokens (${t}%)`)}updateOptions(e){this.options={...this.options,...e},
|
|
1344
|
-
${y}`)),console.log(
|
|
1345
|
-
`));let
|
|
1346
|
-
`))}else
|
|
1347
|
-
${y}`)),console.log(
|
|
1348
|
-
`))}
|
|
1349
|
-
`);for(let c of a){let l=c.trim();if(!l)continue;let p=l.match(/^(\w+)\s*[::]\s*(.+)$/);if(p){let[,u,g]=p;u==="keywords"?i.keywords=g.split(/[,,]/).map(
|
|
1350
|
-
`),o=
|
|
1351
|
-
`),
|
|
1352
|
-
`),
|
|
1353
|
-
\u6700\u7EC8\u7B54\u6848:`),t),
|
|
1382
|
+
[\u6458\u8981\u7ED3\u675F]`},llmCount:o,heuristicCount:s}}groupMessages(e){let t=[];for(let o=0;o<e.length;o+=3)t.push(e.slice(o,o+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(),Ze)),o=e.filter(a=>a.content).map(a=>`${a.role}: ${a.content}`).join(`
|
|
1383
|
+
`);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:o}],temperature:.1,max_tokens:200,useCompression:!0})).choices?.[0]?.message?.content?.trim()||"\u6267\u884C\u5B8C\u6210"}`}catch(n){return z(`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=[],o=!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"))&&(o=!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(", ")}`),o&&(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(Dn.green(`
|
|
1384
|
+
\u2728 \u4E0A\u4E0B\u6587\u538B\u7F29\u5B8C\u6210`)),console.log(Dn.cyan(` \u6D88\u606F\u6570: ${e.originalMessageCount} \u2192 ${e.compressedMessageCount} (${e.compressedMessageCount-e.originalMessageCount})`)),console.log(Dn.cyan(` Token: ${e.originalTokenCount} \u2192 ${e.compressedTokenCount} (\u8282\u7701 ${n}%)`)),console.log(Dn.cyan(` \u538B\u7F29\u6BD4: ${t}%`)),console.log(Dn.cyan(` \u6458\u8981\u65B9\u5F0F: LLM ${e.llmSummaryCount}\u6B21, \u542F\u53D1\u5F0F ${e.heuristicSummaryCount}\u6B21
|
|
1385
|
+
`)),M(`\u4E0A\u4E0B\u6587\u538B\u7F29: ${e.originalMessageCount}\u6761 \u2192 ${e.compressedMessageCount}\u6761, ${e.originalTokenCount}tokens \u2192 ${e.compressedTokenCount}tokens (${t}%)`)}updateOptions(e){this.options={...this.options,...e},h(`\u538B\u7F29\u914D\u7F6E\u5DF2\u66F4\u65B0: ${JSON.stringify(this.options)}`)}getOptions(){return{...this.options}}}});var pn={};U(pn,{callModelAPI:()=>Z,getDefaultSystemPrompt:()=>Mu});import jn from"chalk";async function Z(r){let{model:e=r.useCompression?fe():de(),messages:t,temperature:n=.1,max_tokens:o,useCompression:s=!1,tools:i=Ln(),tool_choice:a,compressionOptions:c,enableAutoCompression:l=!0}=r,p=s?await Ft.getLiteProvider():await Ft.getProvider();h(`\u6A21\u578B\u8C03\u7528\u914D\u7F6E: useCompression=${s}, \u6A21\u578B=${e}, provider=${p.getProviderType()}`),s?h(`\u6B63\u5728\u4F7F\u7528\u8F7B\u91CF\u6A21\u578B: ${e}`):h(`\u6B63\u5728\u4F7F\u7528\u9ED8\u8BA4\u6A21\u578B: ${e}`),h(`\u5DE5\u5177\u6570\u91CF: ${i?i.length:0}`);let u=s?io():so(),g=t,m=$e(g),S=_r(m,u),b=y=>(y/1e3).toFixed(1)+"k";if(M(`\u4F7F\u7528\u6A21\u578B: ${e}, Token usage: ${b(m)} / ${b(u)} (${S.toFixed(1)}%)`),v.currentTaskId){let y=v.tasks.find(x=>x.id===v.currentTaskId);y&&(y.tokenCount=(y.tokenCount||0)+m)}if(l&&ms(m,u,80)){let y=ds(m,u,S);z(y),console.log(jn.yellow(`
|
|
1386
|
+
${y}`)),console.log(jn.cyan(`\u{1F504} \u6B63\u5728\u81EA\u52A8\u538B\u7F29\u4E0A\u4E0B\u6587...
|
|
1387
|
+
`));let x=new Nr(c);if(x.shouldCompress(g,u))try{let{messages:d,stats:k}=await x.compress(g,u,Z);g=d,m=k.compressedTokenCount,S=_r(m,u),M(`\u538B\u7F29\u540EToken\u4F7F\u7528: ${m} / ${u} (${S.toFixed(1)}%)`)}catch(d){z(`\u4E0A\u4E0B\u6587\u538B\u7F29\u5931\u8D25: ${d instanceof Error?d.message:String(d)}`),console.log(jn.yellow(`\u26A0\uFE0F \u4E0A\u4E0B\u6587\u538B\u7F29\u5931\u8D25,\u5C06\u4F7F\u7528\u539F\u59CB\u6D88\u606F\u7EE7\u7EED\u6267\u884C
|
|
1388
|
+
`))}else h("\u5F53\u524D\u4E0D\u6EE1\u8DB3\u538B\u7F29\u6761\u4EF6,\u8DF3\u8FC7\u538B\u7F29")}else if(ms(m,u,80)){let y=ds(m,u,S);z(y),console.log(jn.yellow(`
|
|
1389
|
+
${y}`)),console.log(jn.yellow(`Consider archiving old messages or starting a new session.
|
|
1390
|
+
`))}h(`\u6A21\u578B\u8BF7\u6C42: ${JSON.stringify({model:e,temperature:n,max_tokens:o,messages:g.length>0?`[${g[0].role}, ..., ${g[g.length-1].role}]`:"[]",tools:i?i.length:0})}`);let f;try{f=await p.callModel({model:e,messages:g,temperature:n,max_tokens:o,tools:i,tool_choice:a})}catch(y){throw Y(`\u8C03\u7528\u6A21\u578BAPI\u65F6\u53D1\u751F\u9519\u8BEF: ${y instanceof Error?y.message:String(y)}`),y instanceof Error&&y.stack&&h(`\u9519\u8BEF\u5806\u6808: ${y.stack}`),y}if(!f)throw Y("\u6A21\u578B\u8FD4\u56DE undefined \u6216 null"),new Error("\u6A21\u578BAPI\u8FD4\u56DE\u7A7A\u54CD\u5E94");if(!f.choices)throw Y(`\u6A21\u578B\u8FD4\u56DE\u7F3A\u5C11choices\u5B57\u6BB5: ${JSON.stringify(f)}`),new Error("\u6A21\u578BAPI\u8FD4\u56DE\u7684\u54CD\u5E94\u7F3A\u5C11choices\u5B57\u6BB5");if(!Array.isArray(f.choices)||f.choices.length===0)throw Y(`\u6A21\u578B\u8FD4\u56DE\u7A7A\u7684choices\u6570\u7EC4: ${JSON.stringify(f)}`),new Error("\u6A21\u578BAPI\u8FD4\u56DE\u7684choices\u4E3A\u7A7A");return h(`\u6A21\u578B\u8FD4\u56DE: ${JSON.stringify(f)}`),f}function Mu(){return"You are a helpful assistant."}var he=C(()=>{ee();Xs();xe();St();K();fs();Ha()});var $a={};U($a,{SubAgentManager:()=>Vr,getSubAgentManager:()=>wt});import{existsSync as Eu,readFileSync as Iu,readdirSync as Au}from"fs";import{join as Lu}from"path";import te from"chalk";function wt(r={}){return Ur?r.matchStrategy&&Ur.setMatchStrategy(r.matchStrategy):Ur=new Vr(r),Ur}var Vr,Ur,wr=C(()=>{Me();Gs();ee();he();je();Vr=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=Js();console.log(te.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(te.red(`\u274C \u52A0\u8F7D\u5185\u7F6E\u4EE3\u7406\u5931\u8D25: ${e.message}`))}}loadSubAgents(){let e=ae("agents");if(!Eu(e)){console.log(te.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=Au(e).filter(o=>o.endsWith(".json")||o.endsWith(".md"));console.log(te.blue(`[\u5B50\u667A\u80FD\u4F53\u7BA1\u7406\u5668] \u52A0\u8F7D ${n.length} \u4E2A\u81EA\u5B9A\u4E49\u5B50\u4EE3\u7406`));for(let o of n)try{let s=Lu(e,o),i=Iu(s,"utf-8"),a;o.endsWith(".json")?a=JSON.parse(i):o.endsWith(".md")&&(a=this.parseFrontmatter(i)),this.validateConfig(a)?(this.subAgents.set(a.name,a),console.log(te.green(`\u2713 \u52A0\u8F7D\u81EA\u5B9A\u4E49\u5B50\u667A\u80FD\u4F53: ${a.name}`))):console.log(te.yellow(`\u26A0\uFE0F \u914D\u7F6E\u6587\u4EF6 ${o} \u683C\u5F0F\u65E0\u6548\uFF0C\u5DF2\u8DF3\u8FC7`))}catch(s){console.log(te.red(`\u274C \u52A0\u8F7D\u914D\u7F6E\u6587\u4EF6 ${o} \u5931\u8D25: ${s.message}`))}}catch(t){console.log(te.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[,o,s]=n,i={},a=o.split(`
|
|
1391
|
+
`);for(let c of a){let l=c.trim();if(!l)continue;let p=l.match(/^(\w+)\s*[::]\s*(.+)$/);if(p){let[,u,g]=p;u==="keywords"?i.keywords=g.split(/[,,]/).map(m=>m.trim()).filter(m=>m):i[u]=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(te.green(`[\u5B50\u667A\u80FD\u4F53\u7BA1\u7406\u5668] Hybrid\u7B56\u7565 - \u5173\u952E\u8BCD\u5339\u914D\u6210\u529F: ${n.name}`)),n;let o=await this.matchSubAgentWithAI(e,t);return o&&console.log(te.green(`[\u5B50\u667A\u80FD\u4F53\u7BA1\u7406\u5668] Hybrid\u7B56\u7565 - \u8BED\u4E49\u5339\u914D\u6210\u529F: ${o.name}`)),o;case"keyword":default:return this.matchSubAgentWithKeywords(e)}}matchSubAgentWithKeywords(e){let t=e.toLowerCase(),n=[];for(let[o,s]of this.subAgents){let i=0;if(s.keywords&&Array.isArray(s.keywords))for(let p of s.keywords)t.includes(p.toLowerCase())&&(i+=10);t.includes(o.toLowerCase())&&(i+=5);let a=s.description.toLowerCase(),c=t.split(/\s+/).filter(p=>p.length>2&&a.includes(p));i+=c.length*2;let l=this.agentPerformance.get(o);if(l){let p=l.success/l.total;i+=p*5;let u=Math.max(0,1-(Date.now()-l.lastUsed)/(10080*60*1e3));i+=u*2}i>0&&n.push({agent:s,score:i})}if(n.length>0){n.sort((s,i)=>i.score-s.score);let o=n[0].agent;return console.log(te.green(`[\u5B50\u667A\u80FD\u4F53\u7BA1\u7406\u5668] \u57FA\u4E8E\u5206\u6570\u5339\u914D\u5230\u667A\u80FD\u4F53: ${o.name} (\u5206\u6570: ${n[0].score.toFixed(1)})`)),o}return null}async matchSubAgentWithAI(e,t){let n=t.map(l=>`${l.name}: ${l.description}`).join(`
|
|
1392
|
+
`),o=Ao(e,n),s=await Z({model:fe(),messages:[{role:"user",content:o}],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 o=this.agentPerformance.get(e)||{total:0,success:0,avgTime:0,lastUsed:Date.now()};o.total++,t&&o.success++,o.avgTime=(o.avgTime*(o.total-1)+n)/o.total,o.lastUsed=Date.now(),this.agentPerformance.set(e,o)}setMatchStrategy(e){return["keyword","semantic","hybrid"].includes(e)?(this.matchStrategy=e,console.log(te.blue(`[\u5B50\u667A\u80FD\u4F53\u7BA1\u7406\u5668] \u5339\u914D\u7B56\u7565\u5DF2\u8BBE\u7F6E\u4E3A: ${e}`)),!0):(console.error(te.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}},Ur=null});function Ja(r){let e=Du[r],t=process.env[r]||e.defaultValue;switch(e.type){case"boolean":return t.toLowerCase()==="true";case"number":return parseFloat(t);case"string":default:return t}}function Pe(r){let e=Ja(r);return typeof e=="number"?e:parseFloat(String(e))}function hs(r){let e=Ja(r);return typeof e=="boolean"?e:String(e).toLowerCase()==="true"}var Du,ys=C(()=>{Du={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 Ga(){return{...Ou,compressionInterval:Pe("CONTEXT_COMPRESSION_INTERVAL"),semanticCheckInterval:Pe("CONTEXT_SEMANTIC_CHECK_INTERVAL"),anchorInjectionInterval:Pe("CONTEXT_ANCHOR_INTERVAL"),similarityThreshold:Pe("CONTEXT_SIMILARITY_THRESHOLD"),maxMessagesBeforeCompression:Pe("CONTEXT_MAX_MESSAGES"),driftCorrectionThreshold:Pe("CONTEXT_DRIFT_THRESHOLD"),compressionRatioTarget:Pe("CONTEXT_COMPRESSION_RATIO")}}var Ou,za=C(()=>{ys();Ou={compressionInterval:15,semanticCheckInterval:5,anchorInjectionInterval:10,similarityThreshold:.3,maxMessagesBeforeCompression:50,enableSmartCompression:!0,enableSemanticAnalysis:!0,enableAnchorSystem:!0,driftCorrectionThreshold:.25,maxContextLength:100,compressionRatioTarget:.7}});import F from"chalk";import Lt from"readline";function G(r,e=null){e?e.log(r):console.log(r)}function qa(r,e=null){e?e.info(r):console.log(F.blue(r))}function Ba(r,e=null){e?e.success(r):console.log(F.green(r))}function On(r,e=null){e?e.warning(r):console.log(F.yellow(r))}function Ss(r,e=null){On(r,e)}function Ve(r,e=null){e?e.error(r):console.log(F.red(r))}async function Wr(r,e=!1,t=null){let n,o=null,s=null,i=Ga();if(h("Initializing react loop with think-tool support"),e&&v.messages&&v.messages.length>0)h(`Resuming existing session: ${v.sessionId}`),n=v.messages,M(`\u6062\u590D\u4F1A\u8BDD [ID:${v.sessionId.substring(0,8)}]: ${v.currentTask}`),Ba(F.green(`\u4ECE ${v.updatedAt} \u6062\u590D\u4E4B\u524D\u7684\u4F1A\u8BDD [ID:${v.sessionId.substring(0,8)}]`),t),G(F.gray(`\u4E4B\u524D\u7684\u4EFB\u52A1: ${v.currentTask}`),t),v.tasks&&v.tasks.length>0&&G(F.gray(`\u4F1A\u8BDD\u4E2D\u4EFB\u52A1\u6570\u91CF: ${v.tasks.length}`),t),G("",t);else if(r)h(`Starting new task: ${r.substring(0,50)}${r.length>50?"...":""}`),n=[{role:"system",content:yt},{role:"user",content:r}],qa(`\u5F00\u59CB\u65B0\u4EFB\u52A1: ${r}`),i.enableAnchorSystem&&(o=new mn(r),h("\u4E0A\u4E0B\u6587\u951A\u5B9A\u7BA1\u7406\u5668\u5DF2\u521D\u59CB\u5316")),i.enableSemanticAnalysis&&(s=new dn(Z),h("\u8BED\u4E49\u5206\u6790\u5668\u5DF2\u521D\u59CB\u5316")),Hn(r),Q(n,r);else{Ve("No user request provided and no session to resume");return}let a=0,c=100,l=0;for(h(`Starting execution loop with max ${c} iterations`);a<c;){a++,h(`Loop iteration ${a}`);try{if(i.enableSemanticAnalysis&&s&&o&&a-l>=i.semanticCheckInterval)try{let y=n.map(d=>d.content).filter(Boolean).join(`
|
|
1393
|
+
`),x=await s.analyzeSemanticDrift(r||o.getOriginalQuestion(),y,a);if(h(`\u8BED\u4E49\u5206\u6790 - \u76F8\u4F3C\u5EA6: ${x.similarityScore.toFixed(2)}, \u504F\u79BB\u7EA7\u522B: ${x.driftLevel}`),x.driftLevel==="severe"||x.driftLevel==="moderate"&&x.similarityScore<i.similarityThreshold)if(On(`\u26A0\uFE0F \u68C0\u6D4B\u5230${x.driftLevel==="severe"?"\u4E25\u91CD":"\u4E2D\u5EA6"}\u504F\u79BB\uFF0C\u6B63\u5728\u7EA0\u6B63...`,t),o){let d=`\u68C0\u6D4B\u5230${x.driftLevel}\u504F\u79BB\uFF1A${x.deviationFactors.join("; ")}`,k=await o.createAnchorMessage(a,x.similarityScore,x.driftLevel,d,y);h(`\u{1F3AF} \u6CE8\u5165\u504F\u79BB\u7EA0\u6B63\u951A\u70B9\uFF08\u8FED\u4EE3 ${a}\uFF0C\u504F\u79BB\u7EA7\u522B: ${x.driftLevel}\uFF0C\u4F18\u5148\u7EA7: ${k.metadata?.priority}}`),n.push(k)}else{let d=s.generateCorrectionPrompt(r||o.getOriginalQuestion(),x.driftLevel,x.deviationFactors);n.push({role:"system",content:d})}l=a}catch(y){Ss(`\u8BED\u4E49\u5206\u6790\u5931\u8D25: ${y.message}`,t)}if(i.enableAnchorSystem&&o&&a%i.anchorInjectionInterval===0)try{let y=n.map(d=>d.content).filter(Boolean).join(`
|
|
1394
|
+
`),x=await o.calculateSemanticSimilarity(y);if(await o.shouldInjectAnchor(a,x,y)){let d=await o.createAnchorMessage(a,x,void 0,void 0,y);h(`\u{1F3AF} \u6CE8\u5165\u4E0A\u4E0B\u6587\u951A\u70B9\uFF08\u8FED\u4EE3 ${a}\uFF0C\u76F8\u4F3C\u5EA6: ${x.toFixed(2)}\uFF0C\u4F18\u5148\u7EA7: ${d.metadata?.priority}}`),n.push(d)}}catch(y){Ss(`\u951A\u70B9\u6CE8\u5165\u5931\u8D25: ${y.message}`,t)}Q(n);let p=de();t&&G(F.gray(`[\u8FED\u4EE3 ${a}] \u4F7F\u7528\u6A21\u578B: ${p}`),t),h("Calling Model API with all tools including think");let u=await Z({model:p,messages:n,temperature:.1,tools:Ln(),tool_choice:void 0});if(!u||!u.choices||u.choices.length===0){let y=`\u6A21\u578B\u8FD4\u56DE\u65E0\u6548\u54CD\u5E94: ${JSON.stringify(u)}`;throw Ve(y),new Error(y)}let{choices:g}=u,m=g[0],S=m?.message,b=null,f=null;if(S&&({content:b,tool_calls:f}=S,b&&b.trim())){if(h(`Model returned text content: ${b.substring(0,100)}...`),!f||f.length===0){Ba(F.green(`
|
|
1395
|
+
\u6700\u7EC8\u7B54\u6848:`),t),G(F.white(b),t),G("",t),n.push({role:"assistant",content:b}),M("\u4EFB\u52A1\u5B8C\u6210,\u5F52\u6863\u4F1A\u8BDD"),Xe(),h("Breaking out of react loop after final answer");return}G(F.magenta(`\u{1F4AD} \u601D\u8003: ${b}`),t),G("",t)}if(f&&f.length>0){let y=f[0],x=y.function.name,d=y.function.arguments;h(`Tool call: ${x} with args: ${d}`);let k;try{k=JSON.parse(d)}catch{Ve(`Failed to parse tool arguments: ${d}`),n.push({role:"user",content:`Error: Invalid JSON in tool arguments: ${d}`});continue}if(ht(x)){let E=k.thought||"";G(F.magenta(`\u601D\u8003: ${E}`),t),G("",t),n.push({role:"assistant",content:b||null,tool_calls:[y]}),n.push({role:"tool",tool_call_id:y.id,content:"Noted. Continue."});continue}let P=At()[x];if(!P){let E=`Unknown tool: ${x}`;Ve(E),n.push({role:"assistant",content:b||null,tool_calls:[y]}),n.push({role:"tool",tool_call_id:y.id,content:E});continue}let $=P.formatAction(k);G(F.cyan(`\u884C\u52A8: ${$}`),t),G("",t);try{let E=!1;if(x==="shell"&&P&&typeof P.getDynamicDefinition=="function"?E=P.getDynamicDefinition(k).requiresConfirmation||!1:E=cn().find(He=>He.name===x)?.requiresConfirmation||!1,E&&!await Ru(x,k,t)){let He=`\u5DE5\u5177\u6267\u884C\u5DF2\u53D6\u6D88: ${x}`;M(He),On(F.yellow(`\u26A0 ${He}`),t),G(F.gray("\u60A8\u53EF\u4EE5\u7EE7\u7EED\u63D0\u4F9B\u65B0\u7684\u6307\u4EE4\u6216\u4FEE\u6539\u4E4B\u524D\u7684\u8BF7\u6C42\u3002"),t),n.push({role:"assistant",content:b||null,tool_calls:[y]}),n.push({role:"tool",tool_call_id:y.id,content:"Execution cancelled by user"});continue}h(`\u6267\u884C\u5DE5\u5177: ${x}(${JSON.stringify(k)})`);let D=await Promise.resolve(P.execute(k));h(`\u5DE5\u5177 ${x} \u6267\u884C\u5B8C\u6210`);let pe=_t(D),j=P?P.shouldPrintObservation(D):!0,We=`${P?P.formatObservation(D):String(D)}`;j&&(G(F.yellow(`\u{1F4CA} \u89C2\u5BDF: ${We}`),t),G("",t)),n.push({role:"assistant",content:b||null,tool_calls:[y]}),n.push({role:"tool",tool_call_id:y.id,content:String(pe)})}catch(E){let D=`\u5DE5\u5177\u6267\u884C\u9519\u8BEF: ${x} - ${E.message}`;Y(D),Ve(D,t),G("",t),n.push({role:"assistant",content:b||null,tool_calls:[y]}),n.push({role:"tool",tool_call_id:y.id,content:`Error: ${D}`}),Q(n,r)}}if((!b||!b.trim())&&(!f||f.length===0)){if(Ss("Model returned empty response"),m.finish_reason==="stop"){On("\u4EFB\u52A1\u5B8C\u6210(\u6A21\u578B\u505C\u6B62)",t),Xe(),h("Breaking out of react loop after model stop");return}n.push({role:"user",content:"Please continue or provide your final answer."})}}catch(p){Ve(`\u9519\u8BEF: ${p.message}`,t),On("\u4F1A\u8BDD\u5DF2\u4FDD\u5B58\u3002\u4F7F\u7528 /resume \u7EE7\u7EED\u3002",t),Q(n,r);return}}if(a>=c){if(Ve("\u9519\u8BEF: \u5DF2\u8FBE\u5230\u6700\u5927\u8FED\u4EE3\u6B21\u6570",t),o){let p=o.generateAnchorPrompt(a);qa("\u{1F4CA} \u6700\u7EC8\u4E0A\u4E0B\u6587\u72B6\u6001:",t),G(p,t);let u=Math.floor(a/i.compressionInterval),g=Math.floor(a/i.anchorInjectionInterval),m=Math.floor(a/i.semanticCheckInterval);h(`\u4F18\u5316\u7EDF\u8BA1: \u538B\u7F29${u}\u6B21, \u951A\u70B9\u6CE8\u5165${g}\u6B21, \u8BED\u4E49\u68C0\u67E5${m}\u6B21`)}Q(n,r)}}async function Ru(r,e,t=null){return new Promise(n=>{let o=0,s=[{text:"\u786E\u8BA4\u6267\u884C",value:!0},{text:"\u4E2D\u65AD\u6267\u884C",value:!1}],i=JSON.stringify(e),a=()=>{for(let u=0;u<8;u++)Lt.moveCursor(process.stdout,0,-1),Lt.clearLine(process.stdout,0);let p=t?F.yellow(`\u26A0 \u786E\u8BA4\u6267\u884C ${r}(${i})\uFF1F\u6B64\u64CD\u4F5C\u53EF\u80FD\u65E0\u6CD5\u64A4\u9500\u3002`):F.yellow(`\u26A0 Confirm execution of ${r}(${i})? This action may be irreversible.`);console.log(""),console.log(p),console.log(""),console.log(F.cyan("\u8BF7\u9009\u62E9 (\u4F7F\u7528\u4E0A\u4E0B\u7BAD\u5934\u952E\uFF0CEnter\u786E\u8BA4):")),console.log(""),s.forEach((u,g)=>{let m=g===o,S=m?F.green("> "):" ",b=m?F.green.bold(u.text):F.white(u.text);console.log(`${S}${b}`)}),console.log("")},c=process.stdin.isTTY?process.stdin.isRaw:!1;process.stdin.isTTY&&process.stdin.setRawMode(!0);let l=(p,u)=>{if(u.name==="up")return o=Math.max(0,o-1),a(),!1;if(u.name==="down")return o=Math.min(s.length-1,o+1),a(),!1;if(u.name==="return"||u.name==="enter"){process.stdin.removeListener("keypress",l),process.stdin.isTTY&&process.stdin.setRawMode(c);for(let g=0;g<8;g++)Lt.moveCursor(process.stdout,0,-1),Lt.clearLine(process.stdout,0);return n(s[o].value),!1}else if(u.name==="escape"||u.ctrl&&u.name==="c"){process.stdin.removeListener("keypress",l),process.stdin.isTTY&&process.stdin.setRawMode(c);for(let g=0;g<8;g++)Lt.moveCursor(process.stdout,0,-1),Lt.clearLine(process.stdout,0);return n(!1),!1}};process.stdin.on("keypress",l),a()})}var Cs=C(()=>{ee();he();je();Se();An();an();xe();K();St();Do();jo();za()});import _ from"chalk";async function Ya(r,e=!1,t=null,n={}){await new Rn(t,n).executeTask(r,e)}var Rn,Ka=C(()=>{wr();ue();Cs();je();xe();K();Oo();vr();sr();Rn=class{session;subAgentManager;orchestratorContext;progressiveDisclosure;workerContextBuilder;summaryExtractor;options;constructor(e=null,t={}){this.session=e,Xo(e);let n={matchStrategy:t.matchStrategy};this.subAgentManager=wt(n),this.orchestratorContext=new ve,this.progressiveDisclosure=new we(this.orchestratorContext),this.workerContextBuilder=new Te(this.orchestratorContext,this.progressiveDisclosure),this.summaryExtractor=new ke,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(h("MasterAgent.executeTask called"),t){h("Entering resume session mode"),this.info("\u6062\u590D\u4F1A\u8BDD\u6A21\u5F0F"),await Wr(e,!0,this.session);return}let{evaluateTaskComplexity:n,TaskComplexity:o}=await Promise.resolve().then(()=>(ue(),be));await n(e)===o.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 o=await this.workerContextBuilder.buildIsolatedContext(1,e,n.prompt,!1,void 0);await this.executeSubAgentTask(1,e,n,o)}else this.info("\u4F7F\u7528\u9ED8\u8BA4React\u667A\u80FD\u4F53"),this.log(""),await Wr(e,!1,this.session)}async executeWithPlanning(e){let t=this.subAgentManager.getAllSubAgents(),n=await ln(e,t);this.orchestratorContext.initializeTask(e,n),n.taskId&&Ke(n.taskId),this.log(un(n)),this.log(""),await this.ensureProjectStructure(),await this.loadProjectRules(),this.analyzeStepDependencies(n);for(let o=0;o<n.tasks.length;o++){let s=n.tasks[o],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 Oe(n.taskId,i,"in_progress");try{let a=this.getSubAgentConfig(s),c=await this.workerContextBuilder.buildIsolatedContext(i,s.description,a?.prompt||"",this.options.useLLMDisclosure);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 Oe(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")){h("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(()=>(Se(),xn));await n.quickProjectScan(),this.success("\u2705 \u9879\u76EE\u7ED3\u6784\u6587\u6863\u5DF2\u751F\u6210"),this.log(""),M("\u5DF2\u81EA\u52A8\u751F\u6210 project.json")}catch(e){h(`\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(()=>(Se(),xn)),o="",i=e.read(".nium/rules.md");i&&!i.includes("Error:")&&(o+=i,M("\u5DF2\u52A0\u8F7D\u9879\u76EE\u89C4\u5219\u6587\u4EF6"));let c=e.read(".nium/project/project.json");if(c&&!c.includes("Error:")){o&&(o+=`
|
|
1354
1396
|
|
|
1355
1397
|
---
|
|
1356
1398
|
|
|
1357
1399
|
`),o+=`# \u9879\u76EE\u7ED3\u6784\u4FE1\u606F
|
|
1358
1400
|
|
|
1359
|
-
`;try{let l=JSON.parse(c);o+=this.formatProjectStructureInfo(l),M("\u5DF2\u52A0\u8F7D\u9879\u76EE\u7ED3\u6784\u6587\u6863")}catch{o+=c,
|
|
1401
|
+
`;try{let l=JSON.parse(c);o+=this.formatProjectStructureInfo(l),M("\u5DF2\u52A0\u8F7D\u9879\u76EE\u7ED3\u6784\u6587\u6863")}catch{o+=c,h("\u89E3\u6790\u9879\u76EE\u7ED3\u6784JSON\u5931\u8D25\uFF0C\u4F7F\u7528\u539F\u59CB\u5185\u5BB9")}}o&&this.orchestratorContext.updateSharedState("rules",o)}catch{h("\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,o=t>0?[e.tasks[t-1].step]:[];this.orchestratorContext.setStepDependencies(n,o)}h("\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,o){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:yt},...o.filter(l=>l.role!=="system"),...o.filter(l=>l.role==="system"&&l!==o[0])],a=await this.runWorkerLoop(i,t);await this.recordWorkerResult(e,a);let c=Date.now()-s;this.subAgentManager.recordAgentPerformance(n.name,!0,c)}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:yt},...t.filter(o=>o.role!=="system"),...t.filter(o=>o.role==="system")];await this.runWorkerLoop(n,e)}async runWorkerLoop(e,t){let{MODEL:n}=await Promise.resolve().then(()=>(ee(),Ze)),{callModelAPI:o}=await Promise.resolve().then(()=>(he(),pn)),{isThinkTool:s,extractThought:i}=await Promise.resolve().then(()=>(an(),$o)),{getToolDefinitions:a}=await Promise.resolve().then(()=>(St(),Zo)),{tools:c,toolInstances:l,extractToolResult:p}=await Promise.resolve().then(()=>(Se(),xn)),u=[...e],g=0,m=50;for(;g<m;){g++;try{Q(u,t);let S=await o({model:n(),messages:u,temperature:.1,tools:a()}),b=S.choices[0].message.tool_calls;if(S.choices[0].finish_reason==="stop"){let{content:j}=S.choices[0].message;j&&j.trim()&&(this.log(_.green("\u4EFB\u52A1\u5B8C\u6210:")),this.log(j),this.log(""));break}if(!b||b.length===0){let{content:j}=S.choices[0].message;j&&j.trim()&&(this.log(_.yellow(j)),this.log(""));continue}let f=b[0],y=f.function.name,x;try{x=JSON.parse(f.function.arguments),this.log(_.gray(`[DEBUG] Tool: ${y}`)),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(x).join(", ")}`)),this.log("")}catch{this.error(`\u89E3\u6790\u5DE5\u5177\u53C2\u6570\u5931\u8D25: ${f.function.arguments}`),u.push({role:"assistant",content:null,tool_calls:[f]}),u.push({role:"tool",tool_call_id:f.id,content:"Error: Invalid JSON arguments"});continue}if(s(y)){let j=i(f);j&&(this.log(_.cyan(`\u{1F4AD} Think: ${j}`)),this.log("")),u.push({role:"assistant",content:null,tool_calls:[f]}),u.push({role:"tool",tool_call_id:f.id,content:"Noted. Continue with your action."});continue}if(!c[y]){let j=`Error: Unknown tool '${y}'`;this.error(j),u.push({role:"assistant",content:null,tool_calls:[f]}),u.push({role:"tool",tool_call_id:f.id,content:j});continue}let d=a().find(j=>j.name===y),k;if(d&&d.input_schema&&d.input_schema.properties){k=Object.keys(d.input_schema.properties).map(X=>x[X]);let ie=d.input_schema.required||[],We=ie.filter(X=>x[X]===void 0);if(We.length>0){let X=`Error: Missing required parameters: ${We.join(", ")}
|
|
1360
1402
|
|
|
1361
1403
|
Tool: ${y}
|
|
1362
|
-
Required parameters: ${
|
|
1363
|
-
Provided parameters: ${Object.keys(
|
|
1404
|
+
Required parameters: ${ie.join(", ")}
|
|
1405
|
+
Provided parameters: ${Object.keys(x).join(", ")||"none"}
|
|
1364
1406
|
|
|
1365
|
-
Please call the tool again with ALL required parameters.`;this.error(X),u.push({role:"assistant",content:null,tool_calls:[
|
|
1366
|
-
`})}}});import{readFileSync as
|
|
1367
|
-
`);for(let o of n)if(o.startsWith("USE_LLM_DISCLOSURE=")){let s=o.split("=")[1]?.trim()||"";
|
|
1407
|
+
Please call the tool again with ALL required parameters.`;this.error(X),u.push({role:"assistant",content:null,tool_calls:[f]}),u.push({role:"tool",tool_call_id:f.id,content:X});continue}}else k=Object.values(x);let T=l[y],P=T?T.formatAction(x):`${y}()`;this.log(_.blue(`\u{1F527} \u884C\u52A8: ${P}`)),this.log("");let $=await c[y](...k),E=p($),D=T?T.shouldPrintObservation($):!0,pe=T?T.formatObservation($):String($);D&&(this.log(_.yellow(`\u{1F4CA} \u89C2\u5BDF: ${pe}`)),this.log("")),u.push({role:"assistant",content:null,tool_calls:[f]}),u.push({role:"tool",tool_call_id:f.id,content:String(E)}),["read","write","merge"].includes(y)&&k[0]&&this.orchestratorContext.addRecentFile(k[0]),Q(u,t)}catch(S){throw this.error(`\u9519\u8BEF: ${S.message}`),Q(u,t),S}}if(g>=m)throw this.error("\u9519\u8BEF: \u5DF2\u8FBE\u5230\u6700\u5927\u8FED\u4EE3\u6B21\u6570"),Q(u,t),new Error("Maximum iterations reached");return u}async recordWorkerResult(e,t){let n;this.options.useLLMSummary?n=await this.summaryExtractor.extractSummaryWithLLM(t):n=await this.summaryExtractor.extractSummary(t);let o=this.summaryExtractor.extractMetadata(t);o.success=!0,this.orchestratorContext.recordStepCompletion(e,n,o),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: ${o.toolsUsed.join(", ")}`)),this.log(_.gray(`\u6587\u4EF6: ${o.filesAccessed.join(", ")}`)),this.log(_.gray(`\u8FED\u4EE3: ${o.iterations} \u6B21`)))}formatProjectStructureInfo(e){return gn(e,{format:"markdown",detailed:!0,customTitle:`# \u9879\u76EE\u7ED3\u6784\u4FE1\u606F
|
|
1408
|
+
`})}}});import{readFileSync as Fu}from"fs";import{join as _u}from"path";function Nu(){let r={useLLMDisclosure:!0,useLLMSummary:!0};try{let e=_u(process.cwd(),".nium",".env"),n=Fu(e,"utf-8").split(`
|
|
1409
|
+
`);for(let o of n)if(o.startsWith("USE_LLM_DISCLOSURE=")){let s=o.split("=")[1]?.trim()||"";h(`[\u914D\u7F6E\u8BFB\u53D6] \u4ECE .nium/.env \u6587\u4EF6\u4E2D\u8BFB\u53D6: USE_LLM_DISCLOSURE=${s}`),r.useLLMDisclosure=s.toLowerCase()==="true"}else if(o.startsWith("USE_LLM_SUMMARY=")){let s=o.split("=")[1]?.trim()||"";h(`[\u914D\u7F6E\u8BFB\u53D6] \u4ECE .nium/.env \u6587\u4EF6\u4E2D\u8BFB\u53D6: USE_LLM_SUMMARY=${s}`),r.useLLMSummary=s.toLowerCase()==="true"}}catch(e){h(`[\u914D\u7F6E\u8BFB\u53D6] \u65E0\u6CD5\u8BFB\u53D6 .nium/.env \u6587\u4EF6: ${e.message}`)}return process.env.USE_LLM_DISCLOSURE!==void 0&&(h(`[\u914D\u7F6E\u8BFB\u53D6] \u4ECE\u73AF\u5883\u53D8\u91CF\u4E2D\u8BFB\u53D6: USE_LLM_DISCLOSURE=${process.env.USE_LLM_DISCLOSURE}`),r.useLLMDisclosure=hs("USE_LLM_DISCLOSURE")),process.env.USE_LLM_SUMMARY!==void 0&&(h(`[\u914D\u7F6E\u8BFB\u53D6] \u4ECE\u73AF\u5883\u53D8\u91CF\u4E2D\u8BFB\u53D6: USE_LLM_SUMMARY=${process.env.USE_LLM_SUMMARY}`),r.useLLMSummary=hs("USE_LLM_SUMMARY")),r}async function xs(){try{let r=Nu();return M("[\u914D\u7F6E\u8BFB\u53D6] \u4F7F\u7528\u4E3B\u667A\u80FD\u4F53\uFF08\u4E0A\u4E0B\u6587\u9694\u79BB\u6A21\u5F0F\uFF09"),{executeMasterAgent:Ya,MasterAgent:Rn,config:r}}catch(r){throw Y(`[\u914D\u7F6E\u8BFB\u53D6] \u914D\u7F6E\u8BFB\u53D6\u51FA\u9519: ${r}`),r}}var Xa=C(()=>{Ka();Cs();K();ys()});var ec={};U(ec,{COMMANDS:()=>Fn,executeCommand:()=>Hr,findCommand:()=>Za,getAvailableCommands:()=>_n,initializeDynamicCommands:()=>Bu,printCommandHelp:()=>bs});import A from"chalk";async function Uu(r,e){if(!r){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 xs();await t(r,!1,e,n),e.log(),v.sessionId&&(e.log(A.gray(`\u5F53\u524D\u4F1A\u8BDD ID: ${v.sessionId.substring(0,8)}`)),v.tasks&&v.tasks.length>0&&e.log(A.gray(`\u5F53\u524D\u4F1A\u8BDD\u4EFB\u52A1\u6570: ${v.tasks.length}`)),e.log())}catch(t){throw e.error(`\u4EFB\u52A1\u5904\u7406\u5931\u8D25: ${t.message}`),t}}async function Vu(r){if(v.messages&&v.messages.length>0&&v.currentTask){r.log(),r.info(`\u6B63\u5728\u6062\u590D\u4F1A\u8BDD [ID:${v.sessionId?v.sessionId.substring(0,8):"unknown"}]...`),r.log();try{let{executeMasterAgent:e,config:t}=await xs();await e(null,!0,r,t),r.log(),r.success("\u4F1A\u8BDD\u6062\u590D\u5B8C\u6210"),v.sessionId&&(r.log(A.gray(`\u4F1A\u8BDD ID: ${v.sessionId.substring(0,8)}`)),v.tasks&&v.tasks.length>0&&r.log(A.gray(`\u4F1A\u8BDD\u4EFB\u52A1\u6570: ${v.tasks.length}`)),r.log())}catch(e){throw r.error(`\u4F1A\u8BDD\u6062\u590D\u5931\u8D25: ${e.message}`),e}}else r.warning("\u6CA1\u6709\u53EF\u6062\u590D\u7684\u4F1A\u8BDD\u3002\u4F7F\u7528 /chat <\u8BF7\u6C42> \u5F00\u59CB\u65B0\u4EFB\u52A1\u3002")}function Wu(r){Xe(),r.success("\u4F1A\u8BDD\u5DF2\u5F52\u6863\u5E76\u6E05\u7A7A"),r.log()}function Hu(r){let e=_s();r.log(e)}function Qa(r){r.exit()}function Ju(r){r.printHelp&&r.printHelp()}function Gu(r){r.log(),r.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")),r.log(A.cyan(" \u{1F4E6} Available Tools ")),r.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")),r.log();let e=At(),t=Ua();if(Object.keys(e).length===0){r.warning("No tools loaded yet. Tools will be available after starting a task."),r.log();return}if(r.log(A.bold("\u{1F4CA} Summary:")),r.log(A.gray(` Total Tools: ${t.total}`)),r.log(A.gray(` Local Tools: ${t.local}`)),r.log(A.gray(` MCP Tools: ${t.mcp}`)),r.log(),t.local>0){r.log(A.bold.green("\u{1F527} Local Tools:")),r.log();let{localTools:n}=t;for(let o of n){let s=e[o];if(s&&s.getDefinition){let i=s.getDefinition();r.log(A.green(` \u2022 ${i.name}`)),r.log(A.gray(` ${i.description}`)),r.log()}}}if(t.mcp>0){r.log(A.bold.magenta("\u{1F310} MCP Tools:")),r.log();let{mcpTools:n}=t;for(let o of n){let s=e[o];if(s&&s.getDefinition){let i=s.getDefinition(),a=i.description.match(/\[MCP:([^\]]+)\]/),c=a?a[1]:"unknown",l=i.description.replace(/\[MCP:[^\]]+\]\s*/,"");r.log(A.magenta(` \u2022 ${i.name}`)),r.log(A.gray(` ${l}`)),r.log(A.gray(` (from MCP server: ${c})`)),r.log()}}}r.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")),r.log()}async function zu(r){r.log(),r.info("\u6B63\u5728\u68C0\u67E5git\u53D8\u66F4...");try{if(!En()){r.warning("\u6CA1\u6709\u672A\u63D0\u4EA4\u7684\u53D8\u66F4"),r.log();return}let e=Pn(),t=Mn();r.log(),r.info("\u5F53\u524Dgit\u72B6\u6001:"),r.log(A.gray(e)),r.log();let n=t.length>500?t.substring(0,500)+`
|
|
1368
1410
|
...(truncated)`:t;r.info("\u53D8\u66F4\u5185\u5BB9\u9884\u89C8:"),r.log(A.gray(n)),r.log(),r.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
|
|
1369
1411
|
\u8BF7\u6839\u636E\u63D0\u4F9B\u7684git diff\u5185\u5BB9\uFF0C\u751F\u6210\u4E00\u4E2A\u7B80\u6D01\u660E\u4E86\u7684commit message\u3002
|
|
1370
1412
|
|
|
@@ -1382,9 +1424,9 @@ feat: \u6DFB\u52A0\u7528\u6237\u8BA4\u8BC1\u529F\u80FD
|
|
|
1382
1424
|
- \u6DFB\u52A0\u767B\u5F55\u548C\u6CE8\u518C\u63A5\u53E3
|
|
1383
1425
|
- \u66F4\u65B0\u7528\u6237\u6A21\u578B`},{role:"user",content:`\u8BF7\u4E3A\u4EE5\u4E0Bgit\u53D8\u66F4\u751F\u6210commit message:
|
|
1384
1426
|
|
|
1385
|
-
${t}`}],i=await
|
|
1427
|
+
${t}`}],i=await Z({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){r.error("\u751F\u6210commit message\u5931\u8D25"),r.log();return}r.log();let c=a+`
|
|
1386
1428
|
|
|
1387
|
-
[Generated by niumagents]`;r.success("\u751F\u6210\u7684commit message:"),r.log(A.cyan("\u2500".repeat(50))),r.log(A.white(c)),r.log(A.cyan("\u2500".repeat(50))),r.log(),r.info("\u6B63\u5728\u6267\u884C git add ."),
|
|
1388
|
-
${e.stack||""}`),M("Continuing with local tools only..."),await
|
|
1389
|
-
Commands:`)),this.log(N.gray(" <request> - \u5F00\u59CB\u65B0\u4EFB\u52A1 (\u9ED8\u8BA4: /chat)"));let e=
|
|
1390
|
-
\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(){
|
|
1429
|
+
[Generated by niumagents]`;r.success("\u751F\u6210\u7684commit message:"),r.log(A.cyan("\u2500".repeat(50))),r.log(A.white(c)),r.log(A.cyan("\u2500".repeat(50))),r.log(),r.info("\u6B63\u5728\u6267\u884C git add ."),ts(),r.success("\u5DF2\u6682\u5B58\u6240\u6709\u53D8\u66F4"),r.info("\u6B63\u5728\u6267\u884C git commit..."),ns(c),r.success("\u63D0\u4EA4\u6210\u529F\uFF01"),r.log()}catch(e){throw r.error(`\u6267\u884Ccommit\u547D\u4EE4\u5931\u8D25: ${e.message}`),r.log(),e}}function qu(r,e){r.warning(`\u672A\u77E5\u547D\u4EE4: /${e}`);let t=Fn.map(n=>`/${n.name}`).join(", ");r.log(A.gray(`\u53EF\u7528\u547D\u4EE4: ${t}`))}function Za(r){return Fn.find(e=>e.name===r)||null}async function Hr(r,e,t=""){let n=Za(e);if(!n){qu(r,e);return}if(n.requiresArg&&!t&&e!=="chat"){r.warning(`\u547D\u4EE4 /${e} \u9700\u8981\u53C2\u6570`);return}try{n.requiresArg?await n.handler(t,r):await n.handler(r)}catch(o){throw r.error(`\u6267\u884C\u547D\u4EE4 /${e} \u65F6\u51FA\u9519: ${o.message}`),o}}function _n(){return[...Fn]}function bs(r){r.log(A.cyan("\u53EF\u7528\u547D\u4EE4:")),Fn.forEach(e=>{let t=e.requiresArg?`/${e.name} <\u53C2\u6570>`:`/${e.name}`;r.log(` ${A.white(t)} - ${A.gray(e.description)}`)}),r.log(),r.log(A.gray("\u63D0\u793A: \u76F4\u63A5\u8F93\u5165\u5185\u5BB9\u5C06\u4F5C\u4E3A\u4EFB\u52A1\u8BF7\u6C42\u53D1\u9001")),r.log()}async function Bu(){try{let{isGitAvailable:r}=await Promise.resolve().then(()=>(kr(),Da)),e=r();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(r){console.log(A.gray(`\u521D\u59CB\u5316\u52A8\u6001\u547D\u4EE4\u65F6\u51FA\u9519: ${r.message}`))}}var Fn,vs=C(()=>{xe();Qr();Xa();An();kr();he();Fn=[{name:"chat",description:"\u5F00\u59CB\u65B0\u4EFB\u52A1",handler:Uu,requiresArg:!0},{name:"resume",description:"\u6062\u590D\u4E2D\u65AD\u7684\u4F1A\u8BDD",handler:Vu,requiresArg:!1},{name:"commit",description:"\u4F7F\u7528AI\u603B\u7ED3\u53D8\u66F4\u5E76\u63D0\u4EA4git commit",handler:zu,requiresArg:!1},{name:"clear",description:"\u5F52\u6863\u5E76\u6E05\u7A7A\u5F53\u524D\u4F1A\u8BDD",handler:Wu,requiresArg:!1},{name:"history",description:"\u67E5\u770B\u5F52\u6863\u4F1A\u8BDD",handler:Hu,requiresArg:!1},{name:"list_tools",description:"\u5217\u51FA\u6240\u6709\u53EF\u7528\u5DE5\u5177",handler:Gu,requiresArg:!1},{name:"exit",description:"\u9000\u51FA\u5E94\u7528",handler:Qa,requiresArg:!1},{name:"quit",description:"\u9000\u51FA\u5E94\u7528",handler:Qa,requiresArg:!1},{name:"help",description:"\u663E\u793A\u5E2E\u52A9\u4FE1\u606F",handler:Ju,requiresArg:!1}]});Me();xe();vs();K();ee();us();An();import N from"chalk";import se from"readline";import Yu from"fuzzysort";var tc="0.1.7";var Dt=_n(),Jr=class{rl=null;isActive=!1;commandHistory=[];historyIndex=-1;debug=!1;skipLineProcessing=!1;lastExecutedCommand=null;constructor(e={}){this.debug=e.debug||!1,Xr(this.debug)}async start(){try{if(!N)throw new Error("chalk\u6A21\u5757\u5BFC\u5165\u5931\u8D25");Ms(),Kr(),M("\u4EA4\u4E92\u5F0F\u4F1A\u8BDD\u542F\u52A8"),this.debug&&(h("Debug\u6A21\u5F0F\u5DF2\u542F\u7528"),console.log(N.magenta("\u26A0 Debug\u6A21\u5F0F\u5DF2\u542F\u7528 - \u5C06\u663E\u793A\u8BE6\u7EC6\u65E5\u5FD7\u4FE1\u606F"))),await this.initializeMCP();let{initializeDynamicCommands:e}=await Promise.resolve().then(()=>(vs(),ec));await e(),this.rl=se.createInterface({input:process.stdin,output:process.stdout,prompt:N.blue("nium> "),historySize:100}),se.emitKeypressEvents(process.stdin,this.rl),process.stdin.isTTY&&this.setupHistoryNavigation(),this.printWelcome(),to()&&v.messages&&v.messages.length>0&&v.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=ao();if(M(`Loaded ${e.length} MCP server configuration(s)`),e.length===0){h("No MCP servers configured"),await Rr();return}let t=Et();M("Initializing MCP manager with configured servers..."),await t.initialize(e),M("Loading all tools (local + MCP)..."),await Rr();let n=t.getStatus();h(`MCP Status: ${n.serversConnected} servers connected, ${n.toolsAvailable} tools available`),n.serversConnected>0?console.log(N.green(`\u2713 Connected to ${n.serversConnected} MCP server(s), ${n.toolsAvailable} tools available`)):console.log(N.yellow(`\u26A0 Configured ${e.length} MCP server(s) but none connected`))}catch(e){Y(`Failed to initialize MCP: ${e.message}`),h(`MCP initialization error details: ${e.message}
|
|
1430
|
+
${e.stack||""}`),M("Continuing with local tools only..."),await Rr()}}setupHistoryNavigation(){process.stdin.on("keypress",(e,t)=>{!this.isActive||!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(" "),o=n?Yu.go(n,Dt,{key:"name"}):Dt.map(s=>({obj:s,score:0}));if(o.length===1){let s=o[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 o.length>1&&await this.showCommandSelectionMenu(o)}}async showCommandSelectionMenu(e){if(!this.rl)return;let t=0,n=this.rl.getPrompt(),o=this.rl.line,s=process.stdin.isTTY?process.stdin.isRaw:!1,i=()=>{let a=e.length+3;for(let c=0;c<a;c++)se.moveCursor(process.stdout,0,-1),se.clearLine(process.stdout,0);se.clearLine(process.stdout,1),console.log(""),console.log(N.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 p=c.obj,u=l===t,g=u?N.green("> "):" ",m=u?N.green.bold(`/${p.name}`):N.white(`/${p.name}`),S=N.gray(`- ${p.description}`);console.log(`${g}${m} ${S}`)}),process.stdout.write(n),this.rl.line=o,this.rl.cursor=o.length,this.rl._refreshLine()};return new Promise(a=>{process.stdin.isTTY&&process.stdin.setRawMode(!0);let c=(l,p)=>{if(p.name==="up")return t=Math.max(0,t-1),i(),!1;if(p.name==="down")return t=Math.min(e.length-1,t+1),i(),!1;if(p.name==="return"||p.name==="enter"){let u=e[t].obj,g=`/${u.name}${u.requiresArg?" ":""}`;process.stdin.removeListener("keypress",c),process.stdin.isTTY&&process.stdin.setRawMode(s);for(let m=0;m<e.length+4;m++)se.moveCursor(process.stdout,0,-1),se.clearLine(process.stdout,0);return se.clearLine(process.stdout,1),process.stdout.write(n),this.skipLineProcessing=!0,u.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: /${u.name}`),await u.handler(this)}catch(m){this.error(`\u6267\u884C\u547D\u4EE4 /${u.name} \u65F6\u51FA\u9519: ${m.message}`)}finally{this.isActive&&this.rl&&this.rl.prompt()}})),a(),!1}else if(p.name==="escape"||p.ctrl&&p.name==="c"){for(let u=0;u<e.length+4;u++)se.moveCursor(process.stdout,0,-1),se.clearLine(process.stdout,0);return process.stdin.removeListener("keypress",c),process.stdin.isTTY&&process.stdin.setRawMode(s),se.clearLine(process.stdout,1),process.stdout.write(n),this.rl.line=o,this.rl.cursor=o.length,this.rl._refreshLine(),a(),!1}};process.stdin.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 o=t.slice(1).split(" ")[0];if(Dt=_n(),!(o?Dt.some(i=>i.name===o):!1)&&o){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],o=t.slice(1).join(" ");try{await Hr(this,n,o),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 Hr(this,"chat",e)}catch(t){this.error(`\u6267\u884C\u4EFB\u52A1\u65F6\u51FA\u9519: ${t.message}`)}}printWelcome(){Dt=_n(),this.clear(),this.log(N.green(`NiumAgents-CLI v${tc}`)),this.log(N.gray("Options:")),this.log(N.gray(" --debug - \u542F\u7528\u8C03\u8BD5\u6A21\u5F0F\u4EE5\u663E\u793A\u8BE6\u7EC6\u65E5\u5FD7")),this.log(N.gray(`
|
|
1431
|
+
Commands:`)),this.log(N.gray(" <request> - \u5F00\u59CB\u65B0\u4EFB\u52A1 (\u9ED8\u8BA4: /chat)"));let e=Dt.filter(t=>t.name!=="chat");for(let t of e)t.name==="exit"||t.name==="quit"?t.name==="exit"&&this.log(N.gray(" /exit \u6216 /quit - \u9000\u51FA")):this.log(N.gray(` /${t.name} - ${t.description}`));this.log(N.gray(`
|
|
1432
|
+
\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(){bs(this)}clear(){console.clear()}log(e=""){console.log(e)}success(e){console.log(N.green(e))}warning(e){console.log(N.yellow(e))}error(e){console.log(N.red(e))}info(e){console.log(N.blue(e))}exit(){M("\u4EA4\u4E92\u5F0F\u4F1A\u8BDD\u7ED3\u675F"),this.isActive=!1,this.rl&&this.rl.close()}};async function Ku(){try{let e=process.argv.slice(2).includes("--debug");await new Jr({debug:e}).start()}catch(r){console.error("\u542F\u52A8\u5E94\u7528\u65F6\u51FA\u9519:",r.message),process.exit(1)}}Ku();
|