aggroot 1.4.4 → 1.4.6
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/index.cjs +39 -120
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1031,7 +1031,7 @@ ${Ae}`,I++;break;case"id":y=Ae.includes("\0")?void 0:Ae;break;case"retry":/^\d+$
|
|
|
1031
1031
|
`+Cte(this._prompt)+t;return this._contentBuffer.push(I+`
|
|
1032
1032
|
`),process.stdout.write(I),this._echoRow=T+1,this._cursorRowAfterStop=this._echoRow,this._outputLineCount=1,t}submitWithSummary(t,r){this._inputBuffer="",this._inputLines=[""],this._currentLineIndex=0,this._cursorPos=0,this._cursorCharIndex=0;let l=process.stdout.columns||80,u=this._getStatusBar?this._getStatusBar():"",f=this._calculateWrappedLines(u,l),_=this._lastInputAreaHeight+2+f;this._lastInputAreaHeight=1,process.stdout.write(`\x1B[${_}A\r`),process.stdout.write("\x1B[J");let y=`
|
|
1033
1033
|
`+Cte(this._prompt)+r;return this._contentBuffer.push(y+`
|
|
1034
|
-
`),process.stdout.write(y),r}moveCursorLeft(){if(this._cursorCharIndex>0){let r=[...this._inputBuffer][this._cursorCharIndex-1];if(r){this._cursorCharIndex--,this._cursorPos-=this._getVisualWidth(r);let l=this._getVisualWidth(this._prompt);process.stdout.write(`\x1B[${l+this._cursorPos+1}G`),process.stdout.write(p1())}}}moveCursorRight(){let t=[...this._inputBuffer];if(this._cursorCharIndex<t.length){let r=t[this._cursorCharIndex];if(r){this._cursorCharIndex++,this._cursorPos+=this._getVisualWidth(r);let l=this._getVisualWidth(this._prompt);process.stdout.write(`\x1B[${l+this._cursorPos+1}G`),process.stdout.write(p1())}}}moveCursorToStart(){this._cursorCharIndex=0,this._cursorPos=0;let t=this._getVisualWidth(this._prompt);process.stdout.write(`\x1B[${t+1}G`),process.stdout.write(p1())}moveCursorToEnd(){this._cursorCharIndex=[...this._inputBuffer].length,this._cursorPos=this._getVisualWidth(this._inputBuffer);let t=this._getVisualWidth(this._prompt);process.stdout.write(`\x1B[${t+this._cursorPos+1}G`),process.stdout.write(p1())}moveCursorToCharIndex(t){let r=[...this._inputBuffer],l=Math.max(0,Math.min(t,r.length));this._cursorCharIndex=l;let u=r.slice(0,l).join("");this._cursorPos=this._getVisualWidth(u);let f=this._getVisualWidth(this._prompt);process.stdout.write(`\x1B[${f+this._cursorPos+1}G`),process.stdout.write(p1())}deleteRange(t,r){let l=[...this._inputBuffer],u=Math.max(0,Math.min(t,r)),f=Math.max(t,r),_=Math.min(f,l.length);if(u>=_)return"";let y=l.slice(u,_).join(""),T=[...l.slice(0,u),...l.slice(_)];this._inputBuffer=T.join(""),this._inputLines[this._currentLineIndex]=this._inputBuffer,this._cursorCharIndex=u;let I=T.slice(0,u).join("");return this._cursorPos=this._getVisualWidth(I),this._redrawInputLine(),y}_ghostText="";setGhostText(t){this._ghostText=t,this._redrawInputLine()}clearGhostText(){this._ghostText&&(this._ghostText="",this._redrawInputLine())}positionCursor(){}showInputUI(){if(this._stopAnimationTimeoutId&&(clearTimeout(this._stopAnimationTimeoutId),this._stopAnimationTimeoutId=null,this._stopAnimationPending=!1),this._isThinkingAnimationRunning){let y=process.stdout.columns||80,T=process.stdout.rows||24,I=this._cachedStatusBarLines||this._calculateWrappedLines(this._getStatusBar?this._getStatusBar():"",y),P=this._calcThinkingUILines(I),O=T-P,L=this._pendingOutputLines.length>0?this._pendingOutputLines.join(""):"";this._pendingOutputLines=[],this._outputFlushTimeout&&(clearTimeout(this._outputFlushTimeout),this._outputFlushTimeout=null),this._stopThinkingAnimation(),process.stdout.write(`\x1B[${O};1H\x1B[J`),this._cursorRowAfterStop=O,this._lastInputAreaHeight=0,this._outputLineCount=0,L&&(process.stdout.write("\r"+L),this._outputLineCount+=this._countVisualLines(L))}if(this._pendingOutputLines.length>0){this._outputFlushTimeout&&(clearTimeout(this._outputFlushTimeout),this._outputFlushTimeout=null);let y=this._pendingOutputLines;this._pendingOutputLines=[];let T=y.join("");if(T){if(this._lastInputAreaHeight>0){let I=process.stdout.columns||80,P=process.stdout.rows||24,O=this._calculateWrappedLines(this._getStatusBar?this._getStatusBar():"",I),L=this._lastInputAreaHeight+2+O;process.stdout.write(`\x1B[${P-L};1H\x1B[J`),this._cursorRowAfterStop=P-L,this._lastInputAreaHeight=0}process.stdout.write(T),this._outputLineCount+=this._countVisualLines(T)}}let t=process.stdout.columns||80,r=process.stdout.rows||24,l=this._getStatusBar?this._getStatusBar():"",u=this._calculateWrappedLines(l,t),_=this._getDisplayLineCount()+2+u;if(this._outputLineCount>0){let y=r-_,I=(this._cursorRowAfterStop>0?this._cursorRowAfterStop:y)+this._outputLineCount+
|
|
1034
|
+
`),process.stdout.write(y),r}moveCursorLeft(){if(this._cursorCharIndex>0){let r=[...this._inputBuffer][this._cursorCharIndex-1];if(r){this._cursorCharIndex--,this._cursorPos-=this._getVisualWidth(r);let l=this._getVisualWidth(this._prompt);process.stdout.write(`\x1B[${l+this._cursorPos+1}G`),process.stdout.write(p1())}}}moveCursorRight(){let t=[...this._inputBuffer];if(this._cursorCharIndex<t.length){let r=t[this._cursorCharIndex];if(r){this._cursorCharIndex++,this._cursorPos+=this._getVisualWidth(r);let l=this._getVisualWidth(this._prompt);process.stdout.write(`\x1B[${l+this._cursorPos+1}G`),process.stdout.write(p1())}}}moveCursorToStart(){this._cursorCharIndex=0,this._cursorPos=0;let t=this._getVisualWidth(this._prompt);process.stdout.write(`\x1B[${t+1}G`),process.stdout.write(p1())}moveCursorToEnd(){this._cursorCharIndex=[...this._inputBuffer].length,this._cursorPos=this._getVisualWidth(this._inputBuffer);let t=this._getVisualWidth(this._prompt);process.stdout.write(`\x1B[${t+this._cursorPos+1}G`),process.stdout.write(p1())}moveCursorToCharIndex(t){let r=[...this._inputBuffer],l=Math.max(0,Math.min(t,r.length));this._cursorCharIndex=l;let u=r.slice(0,l).join("");this._cursorPos=this._getVisualWidth(u);let f=this._getVisualWidth(this._prompt);process.stdout.write(`\x1B[${f+this._cursorPos+1}G`),process.stdout.write(p1())}deleteRange(t,r){let l=[...this._inputBuffer],u=Math.max(0,Math.min(t,r)),f=Math.max(t,r),_=Math.min(f,l.length);if(u>=_)return"";let y=l.slice(u,_).join(""),T=[...l.slice(0,u),...l.slice(_)];this._inputBuffer=T.join(""),this._inputLines[this._currentLineIndex]=this._inputBuffer,this._cursorCharIndex=u;let I=T.slice(0,u).join("");return this._cursorPos=this._getVisualWidth(I),this._redrawInputLine(),y}_ghostText="";setGhostText(t){this._ghostText=t,this._redrawInputLine()}clearGhostText(){this._ghostText&&(this._ghostText="",this._redrawInputLine())}positionCursor(){}showInputUI(){if(this._stopAnimationTimeoutId&&(clearTimeout(this._stopAnimationTimeoutId),this._stopAnimationTimeoutId=null,this._stopAnimationPending=!1),this._isThinkingAnimationRunning){let y=process.stdout.columns||80,T=process.stdout.rows||24,I=this._cachedStatusBarLines||this._calculateWrappedLines(this._getStatusBar?this._getStatusBar():"",y),P=this._calcThinkingUILines(I),O=T-P,L=this._pendingOutputLines.length>0?this._pendingOutputLines.join(""):"";this._pendingOutputLines=[],this._outputFlushTimeout&&(clearTimeout(this._outputFlushTimeout),this._outputFlushTimeout=null),this._stopThinkingAnimation(),process.stdout.write(`\x1B[${O};1H\x1B[J`),this._cursorRowAfterStop=O,this._lastInputAreaHeight=0,this._outputLineCount=0,L&&(process.stdout.write("\r"+L),this._outputLineCount+=this._countVisualLines(L))}if(this._pendingOutputLines.length>0){this._outputFlushTimeout&&(clearTimeout(this._outputFlushTimeout),this._outputFlushTimeout=null);let y=this._pendingOutputLines;this._pendingOutputLines=[];let T=y.join("");if(T){if(this._lastInputAreaHeight>0){let I=process.stdout.columns||80,P=process.stdout.rows||24,O=this._calculateWrappedLines(this._getStatusBar?this._getStatusBar():"",I),L=this._lastInputAreaHeight+2+O;process.stdout.write(`\x1B[${P-L};1H\x1B[J`),this._cursorRowAfterStop=P-L,this._lastInputAreaHeight=0}process.stdout.write(T),this._outputLineCount+=this._countVisualLines(T)}}let t=process.stdout.columns||80,r=process.stdout.rows||24,l=this._getStatusBar?this._getStatusBar():"",u=this._calculateWrappedLines(l,t),_=this._getDisplayLineCount()+2+u;if(this._outputLineCount>0){let y=r-_,I=(this._cursorRowAfterStop>0?this._cursorRowAfterStop:y)+this._outputLineCount+1,L=Math.min(Math.max(0,I-y),_)+0;process.stdout.write(`\x1B[${r};1H`),process.stdout.write(`
|
|
1035
1035
|
`.repeat(L)),this._outputLineCount=0,this._cursorRowAfterStop=0,this._onLinesPushed?.(L)}this._redrawInputLine()}restoreInputUI(){this._isRestoringUI=!0;try{this._redrawInputLine()}finally{this._isRestoringUI=!1}}clear(){this._inputBuffer="",this._inputLines=[""],this._currentLineIndex=0,this._cursorPos=0,this._cursorCharIndex=0,this._stopThinkingAnimation();let t=process.stdout.rows||24;process.stdout.write("\x1B[1;1H\x1B[J"),this._outputLineCount=0,this._cursorRowAfterStop=0,this._lastInputAreaHeight=0,this.showInputUI()}showThinkingStatus(t){if(this.blockAnimation||this._interrupted)return;this._outputFlushTimeout&&(clearTimeout(this._outputFlushTimeout),this._outputFlushTimeout=null,this._flushPendingOutput());let r=this._isThinkingAnimationRunning;if(this._currentStatus=t,!r){this._thinkingStartTime=Date.now(),this._isThinkingAnimationRunning=!0,this._thinkingFirstDraw=!0;let l=process.stdout.columns||80,u=this._getStatusBar?this._getStatusBar():"";this._cachedStatusBarLines=this._calculateWrappedLines(u,l)}this._drawThinkingStatus(),this._thinkingFirstDraw=!1,r||(this._statusInterval=setInterval(()=>{this._spinnerFrame=(this._spinnerFrame+1)%Ate.length,this._drawThinkingStatus()},100))}stopThinkingStatus(){if(!this._isThinkingAnimationRunning)return;let t=Date.now()-this._thinkingStartTime,r=this.MIN_THINKING_TIME_MS-t;if(r>0&&!this._stopAnimationPending){this._stopAnimationPending=!0,this._stopAnimationTimeoutId=setTimeout(()=>{this._stopAnimationPending=!1,this._stopAnimationTimeoutId=null,this._performStopAnimation()},r);return}this._performStopAnimation()}isThinking(){return this._isThinkingAnimationRunning}clearInterrupted(){this._interrupted=!1}blockAndStopAnimation(){let t=this._isThinkingAnimationRunning;if(this.blockAnimation=!0,this._statusInterval&&(clearInterval(this._statusInterval),this._statusInterval=null),this._isThinkingAnimationRunning=!1,this._currentStatus=null,t){this._pendingOutputLines=[],this._outputFlushTimeout&&(clearTimeout(this._outputFlushTimeout),this._outputFlushTimeout=null);let r=process.stdout.columns||80,l=process.stdout.rows||24,u=this._getStatusBar?this._getStatusBar():"",f=this._calculateWrappedLines(u,r),_=this._calcThinkingUILines(f),y=l-_;process.stdout.write(`\x1B[${y};1H\x1B[J`)}return t}unblockAnimation(){this.blockAnimation=!1}handleInterrupt(){if(this._isThinkingAnimationRunning&&this._onInterrupt){this._statusInterval&&(clearInterval(this._statusInterval),this._statusInterval=null),this._stopAnimationTimeoutId&&(clearTimeout(this._stopAnimationTimeoutId),this._stopAnimationTimeoutId=null,this._stopAnimationPending=!1),this._pendingOutputLines=[],this._outputFlushTimeout&&(clearTimeout(this._outputFlushTimeout),this._outputFlushTimeout=null);let t=process.stdout.columns||80,r=process.stdout.rows||24,l=this._getStatusBar?this._getStatusBar():"",u=this._cachedStatusBarLines||this._calculateWrappedLines(l,t);if(this._getSubAgentPanelHeight()>0){let V=this._calcThinkingUILines(u),K=r-V;process.stdout.write(`\x1B[${K};1H\x1B[J`),this._subAgentPanelLines=[]}let _=this._calcThinkingUILines(u),y=r-_,T=y+1,I=T+1,P=I+1,O=this._prompt+this._inputBuffer;this._stopThinkingAnimation();let L="\x1B[?2026h";L+=`\x1B[${y};1H\x1B[K\u26A0\uFE0F \u5DF2\u6253\u65AD\u601D\u8003`,L+=`\x1B[${T};1H\x1B[K${sU(t)}`,L+=`\x1B[${I};1H\x1B[K${O}`,L+=`\x1B[${P};1H\x1B[K${sU(t)}`;for(let V=0;V<u;V++)L+=`\x1B[${P+1+V};1H\x1B[K`;L+=`\x1B[${P+1};1H${l}`,L+="\x1B[?2026l";let J=this._getVisualWidth(this._prompt);L+=`\x1B[${I};1H\x1B[${J+this._cursorPos+1}G`,L+=p1(),process.stdout.write(L),this._interrupted=!0,this._onInterrupt()}}setInterruptCallback(t){this._onInterrupt=t}setMenuActive(t){}getOutputLinesCount(){return 0}get isOutputtingMode(){return!1}incrementPendingMessages(){}getPendingMessagesCount(){return 0}resetPendingMessages(){}_subAgentPanelLines=[];_echoRow=0;setSubAgentStatus(t){this._subAgentPanelLines=t?t.includes(`
|
|
1036
1036
|
`)?t.split(`
|
|
1037
1037
|
`):[t]:[],this._isThinkingAnimationRunning&&this._currentStatus&&this._drawThinkingStatus()}getSubAgentStatus(){return this._subAgentPanelLines.join(`
|
|
@@ -43754,33 +43754,32 @@ ${ft}`,data:{errorCount:Ae,warnCount:$e,summary:`${yt}`}})}),O.on("error",async
|
|
|
43754
43754
|
`)].join(`
|
|
43755
43755
|
`)}}catch(l){return{success:!1,stderr:l instanceof Error?l.message:String(l)}}},!0)}function YUn(o,t,r,l){let u=new Set(["Write","Edit","CodeRefactor","CodeExecute","CodeFormat"]);o.register("before_loop","context-aware-workflow",async f=>{let{input:_}=f.data??{};if(!_)return f;try{let y=await t.buildContext(_),T=t.mode.detectMode(_);T.confidence>.5&&t.switchMode(T.recommendedMode,"auto-detected-at-start"),await t.checkpoint.createCheckpoint(k0.TaskStart,{name:`Task: ${_.slice(0,50)}`,taskId:t.currentTaskId??void 0}),l&&y.keyFiles&&l.mergeBuildContext(y),Ma("context-aware-workflow").info({input:_.slice(0,100),taskType:y.summary?.type,mode:t.getCurrentModeType(),contextLevel:y.level,symbols:y.summary?.symbols??[],files:y.summary?.files??[],keywords:y.summary?.keywords?.slice(0,5)??[],keyFiles:y.keyFiles?.map(P=>P.path)??[],tokenUsage:`${y.tokenUsage.used}/${y.tokenUsage.budget}`},"Context initialized before loop")}catch(y){Ma("context-aware-workflow").warn({error:y instanceof Error?y.message:String(y)},"Failed to initialize context before loop")}return f},10),o.register("before_tool_call","workflow-tx-begin",async f=>{let{toolName:_,args:y}=f.data??{};if(!_||!u.has(_))return f;try{t.currentTaskId||await t.startTask(`tool:${_}`),t.transaction.getCurrentTransaction()||await t.transaction.beginTransaction({name:`tool:${_}`,autoSnapshot:!1,autoRollback:!0});let T=y?.path;if(T){let{resolve:I,isAbsolute:P}=await import("node:path"),{existsSync:O}=await import("node:fs"),{readFile:L}=await import("node:fs/promises"),J=P(T)?T:I(process.cwd(),T);if(O(J)){let V=await L(J,"utf-8");t.transaction.addExecutedWriteContent(T,V)}else t.transaction.addExecutedCreateFile(T)}}catch{}return f},40),o.register("after_tool_call","workflow-tx-commit",async f=>{let{toolName:_,result:y}=f.data??{};if(!_||!u.has(_))return f;try{if(y?.success){t.transaction.getCurrentTransaction()&&await t.transaction.commit(),await t.maybeAutoCheckpoint().catch(L=>{Wne.warn({error:L instanceof Error?L.message:String(L)},"Failed to create auto checkpoint after tool call")});let P=f.data?.args?.path;P&&r.markDirty(process.cwd(),P),t.getCurrentModeType()===Ud.Analysis&&_==="CodeRefactor"&&t.switchMode(Ud.Refactor,"auto-switched-after-refactor")}else t.transaction.getCurrentTransaction()&&await t.transaction.cancel().catch(I=>{Wne.warn({error:I instanceof Error?I.message:String(I)},"Failed to cancel transaction")})}catch(T){Wne.warn({error:T instanceof Error?T.message:String(T)},"Error in after_tool_call hook, attempting to cancel transaction"),await t.transaction.cancel().catch(I=>{Wne.error({error:I instanceof Error?I.message:String(I)},"Failed to cancel transaction in catch block")})}return f},60)}var NR,YB,Gg,oW,Wne,gAe,zGt=on(()=>{"use strict";ne();eAe();RGt();NGt();kGt();LGt();uAe();fAe();mAe();_Ae();eAe();NR=require("node:fs/promises"),YB=require("node:fs"),Gg=require("node:path"),oW=require("node:child_process");jge();BXe();zd();OXe();WGt();One();Lne();Wne=Ma("code-tools-plugin");gAe=class{manifest={id:"@aggroot/code-tools",name:"Code Tools",version:"1.0.1",description:"Code analysis, refactoring, and execution tools",main:"dist/index.js",extensionPoints:[{type:"tool",count:10,description:"Code tools: context, analyze, search, refactor, execute, validate, format, index, stats, dependencies"}]};_sessionContext=null;engineManager=new ZU;_workflow=null;_fileStateCache=null;async initialize(t){let{tools:r}=t,l=process.cwd(),u=f=>{let _=this.engineManager.getEngine(f??l);return this._workflow?.context&&this._workflow.context.setEngine(_),_};this._workflow=new Fne({projectRoot:l}),await this._workflow.initialize(),r.register(VUn(this.manifest.id,u)),r.register(UUn(this.manifest.id,u)),r.register(HUn(this.manifest.id)),r.register($Un(this.manifest.id)),r.register(KUn(this.manifest.id)),r.register(qUn(this.manifest.id,u)),r.register(JUn(this.manifest.id,u)),r.register(XUn(this.manifest.id,u)),this._sessionContext=new tH({projectRoot:l})}async activate(){}async deactivate(){this.engineManager.closeAll(),this._sessionContext&&this._sessionContext.clear(),this._workflow&&(await this._workflow.dispose(),this._workflow=null)}async startIndexing(t,r){let l=this.engineManager.getEngine(t);await l.waitForInit();let u=await l.indexDirectory(t,void 0,r),f=await l.syncReferences();return{fileCount:u,refCount:f}}async dispose(){await this.deactivate()}registerHooks(t){if(!this._sessionContext||!this._workflow)return;this._fileStateCache||(this._fileStateCache=new KB),r9e(this._sessionContext),i9e(this._fileStateCache),o9e(()=>this._sessionContext??void 0,()=>this._fileStateCache??void 0);let r=dAe(this._sessionContext);t.register("after_tool_call","code-session-tracker",r,50),YUn(t,this._workflow,this.engineManager,this._sessionContext)}getSessionContext(){return this._sessionContext}}});async function QUn(o){try{let t=await(0,jXe.readFile)(o,"utf-8"),r=JSON.parse(t);return kR.debug({path:o,serverCount:r.servers?.length},"Loaded MCP config file"),r}catch(t){return t.code==="ENOENT"||kR.warn({path:o,error:String(t)},"Failed to load MCP config file"),null}}function eHn(){let o=process.env.MCP_SERVERS;if(!o)return[];try{let t=JSON.parse(o);return kR.debug({serverCount:t.length},"Loaded MCP servers from env"),t}catch(t){return kR.warn({error:String(t)},"Failed to parse MCP_SERVERS env"),[]}}function tHn(o){let t={};for(let r of o)r?.settings&&Object.assign(t,r.settings);return t}function nHn(o){let t=new Map;for(let r of[...o].reverse())if(r?.servers)for(let l of r.servers)t.set(l.name,l);return Array.from(t.values())}function rHn(o){if(!o.name||typeof o.name!="string")return kR.warn("Server config missing name"),!1;if(!o.transport||!o.transport.type)return kR.warn({name:o.name},"Server config missing transport type"),!1;switch(o.transport.type){case"stdio":if(!o.transport.command)return kR.warn({name:o.name},"Stdio transport missing command"),!1;break;case"http":case"websocket":case"sse":if(!o.transport.url)return kR.warn({name:o.name},`${o.transport.type} transport missing url`),!1;break;default:return kR.warn({name:o.name},"Unknown transport type"),!1}return!0}async function VGt(o){let t=ZUn(o),r=await Promise.all(t.map(T=>QUn(T))),l=tHn(r),u=eHn(),f=[...nHn(r),...u],_=f.filter(rHn),y=_.filter(T=>T.enabled!==!1);return kR.info({total:f.length,valid:_.length,enabled:y.length},"MCP config loaded"),{servers:y,settings:l}}var jXe,jGt,kR,GGt,ZUn,UGt=on(()=>{"use strict";ne();jXe=require("fs/promises"),jGt=require("path");Gx();zd();ef();kR=Ma("mcp-config"),GGt="mcp.json",ZUn=o=>[K3(o,GGt),(0,jGt.join)(Ra,GGt)]});function HGt(o){return eL(o)}function eL(o){if(!o||typeof o!="object")return o;let t={};if(Array.isArray(o.anyOf)){let r=o.anyOf.filter(l=>typeof l=="object"&&l!==null&&l.type!=="null");if(r.length===1&&o.anyOf.length===2)return eL(r[0]);t.anyOf=r.map(l=>eL(l))}if(Array.isArray(o.oneOf)){let r=o.oneOf.filter(l=>typeof l=="object"&&l!==null&&l.type!=="null");if(r.length===1&&o.oneOf.length===2)return eL(r[0]);t.oneOf=r.map(l=>eL(l))}if(Array.isArray(o.allOf)){if(o.allOf.length===1)return eL(o.allOf[0]);t.allOf=o.allOf.map(r=>eL(r))}for(let[r,l]of Object.entries(o))if(!iHn.has(r)&&r!=="additionalProperties")if(r==="properties"&&typeof l=="object"&&l!==null){let u={};for(let[f,_]of Object.entries(l))u[f]=eL(_);t[r]=u}else if(r==="items"&&typeof l=="object"&&l!==null)t[r]=eL(l);else{if(r==="anyOf"||r==="oneOf"||r==="allOf")continue;t[r]=l}return t}var iHn,$Gt=on(()=>{"use strict";ne();vee();iHn=new Set(["title","$schema","examples","default"])});var qGt={};Sc(qGt,{MCPToolsPlugin:()=>yAe,default:()=>sHn});function oHn(o,t){let r={get:"\u83B7\u53D6",read:"\u8BFB\u53D6",list:"\u5217\u51FA",create:"\u521B\u5EFA",write:"\u5199\u5165",update:"\u66F4\u65B0",delete:"\u5220\u9664",search:"\u641C\u7D22",find:"\u67E5\u627E",execute:"\u6267\u884C",run:"\u8FD0\u884C",edit:"\u7F16\u8F91",insert:"\u63D2\u5165",add:"\u6DFB\u52A0",remove:"\u79FB\u9664",replace:"\u66FF\u6362",convert:"\u8F6C\u6362",export:"\u5BFC\u51FA",import:"\u5BFC\u5165",download:"\u4E0B\u8F7D",upload:"\u4E0A\u4F20",save:"\u4FDD\u5B58",load:"\u52A0\u8F7D",query:"\u67E5\u8BE2",analyze:"\u5206\u6790",generate:"\u751F\u6210",extract:"\u63D0\u53D6",send:"\u53D1\u9001",set:"\u8BBE\u7F6E",check:"\u68C0\u67E5",validate:"\u9A8C\u8BC1",test:"\u6D4B\u8BD5",scan:"\u626B\u63CF",track:"\u8FFD\u8E2A",simulate:"\u6A21\u62DF",detect:"\u68C0\u6D4B",review:"\u5BA1\u67E5",recon:"\u4FA6\u5BDF"},l={document:"\u6587\u6863",file:"\u6587\u4EF6",text:"\u6587\u672C",paragraph:"\u6BB5\u843D",table:"\u8868\u683C",image:"\u56FE\u7247",heading:"\u6807\u9898",style:"\u6837\u5F0F",resource:"\u8D44\u6E90",tool:"\u5DE5\u5177",prompt:"\u63D0\u793A",directory:"\u76EE\u5F55",info:"\u4FE1\u606F",outline:"\u5927\u7EB2",content:"\u5185\u5BB9",pdf:"PDF",site:"\u7AD9\u70B9",domain:"\u57DF\u540D",url:"URL",payment:"\u652F\u4ED8",security:"\u5B89\u5168",risk:"\u98CE\u9669",fraud:"\u6B3A\u8BC8",redirect:"\u8DF3\u8F6C",device:"\u8BBE\u5907",purchase:"\u8D2D\u4E70",indicator:"\u6307\u6807",reputation:"\u4FE1\u8A89",whois:"WHOIS"},u=t.split("_");if(u.length>=2){let f=r[u[0]],_=u.slice(1).map(y=>l[y]??y).join("");return f?`${f}${_||""}`:u.map(y=>y.charAt(0).toUpperCase()+y.slice(1)).join(" ")}return r[t]?r[t]:t}function KGt(o,t,r){let l=HGt(t.inputSchema),u=t.annotations,f=u?.readOnlyHint??!0,_=u?.destructiveHint??!1,y=u?.title,T=y??oHn(t.serverName,t.name),I=y?`[MCP/${t.serverName}] ${y}: ${t.description}`:`[MCP/${t.serverName}] ${t.description}`;return{id:`mcp:${t.serverName}:${t.name}`,type:"tool",pluginId:o,name:`mcp_${t.serverName}_${t.name}`,displayName:T,description:I,parameters:l,riskLevel:_?"dangerous":"safe",requiresConfirmation:_,execute:async P=>{try{let O=await r.callTool(t.serverName,t.name,P),L="";for(let J of O.content)if(typeof J=="object"&&J!==null&&"type"in J){let V=J;if(V.type==="text"&&V.text)L+=V.text;else if(V.type==="image"&&V.data)if(hF()){let K=await yee(V.data,V.mimeType||"image/png");L+=`[\u56FE\u7247\u63CF\u8FF0: ${K}]`}else L+=`[Image: ${V.mimeType||"unknown"}]`;else L+=JSON.stringify(J)}else L+=String(J);return{success:!O.isError,stdout:O.isError?"":L,stderr:O.isError?L:"",data:{serverName:t.serverName,toolName:t.name}}}catch(O){return{success:!1,stderr:`MCP tool error: ${O instanceof Error?O.message:String(O)}`}}},isConcurrencySafe:()=>f}}var aW,rH,yAe,sHn,JGt=on(()=>{"use strict";ne();pHe();UGt();zd();$Gt();vee();aW=Ma("mcp-tools-plugin"),rH="@aggroot/mcp-tools";yAe=class{id=rH;name="MCP Tools";version="1.1.0";description="MCP (Model Context Protocol) server tools integration";manifest={id:rH,name:"MCP Tools",version:"1.1.0",description:"MCP server tools integration",main:"index.js"};manager;registeredTools=new Map;eventUnsubscribe;pluginContext;_backgroundConnect;constructor(){this.manager=dHe()}async initialize(t){aW.info("Initializing MCP tools plugin..."),this.pluginContext=t,this.registerResourceTools(t),this.eventUnsubscribe=this.manager.onEvent(l=>{this.handleMCPEvent(l)});let r=process.cwd();this._backgroundConnect=VGt(r).then(({servers:l,settings:u})=>(this.manager.updateSettings(u),Promise.allSettled(l.map(f=>this.manager.connect(f).catch(_=>{aW.warn({name:f.name,error:String(_)},"Failed to connect MCP server")}))))).then(()=>{this.registerAllTools(this.pluginContext),this.registerResourceTools(this.pluginContext),aW.info(`MCP background connect complete: ${this.registeredTools.size} tools registered`)}),aW.info("MCP tools plugin initialized (connecting servers in background)")}async activate(){aW.info("MCP tools plugin activated")}async deactivate(){this.eventUnsubscribe&&(this.eventUnsubscribe(),this.eventUnsubscribe=void 0),await this.manager.disconnectAll(),aW.info("MCP tools plugin deactivated")}async dispose(){this.eventUnsubscribe&&(this.eventUnsubscribe(),this.eventUnsubscribe=void 0),await this.manager.disconnectAll(),this.registeredTools.clear(),aW.info("MCP tools plugin disposed")}getManager(){return this.manager}getServerStates(){return this.manager.getServerStates()}registerAllTools(t){let r=this.manager.getAllTools();for(let l of r)if(this.shouldRegisterTool(l)){let u=KGt(rH,l,this.manager);t.tools.register(u),this.registeredTools.set(u.id,u)}}shouldRegisterTool(t){let r=this.manager.getServerStates().find(l=>l.name===t.serverName&&l.type==="connected");if(r?.type==="connected"){let l=r.config;if(l.allowedTools&&!l.allowedTools.includes(t.name)||l.excludedTools?.includes(t.name))return!1}return!0}handleMCPEvent(t){switch(t.type){case"server_connected":case"server_reconnected":this.refreshToolsForServer(t.serverName);break;case"server_disconnected":this.removeToolsForServer(t.serverName);break;case"tool_list_changed":this.refreshToolsForServer(t.serverName);break}}refreshToolsForServer(t){if(!this.pluginContext)return;this.removeToolsForServer(t);let r=this.manager.getAllTools().filter(l=>l.serverName===t);for(let l of r)if(this.shouldRegisterTool(l)){let u=KGt(rH,l,this.manager);this.pluginContext.tools.register(u),this.registeredTools.set(u.id,u)}aW.info({serverName:t,toolCount:r.length},"Refreshed MCP tools for server")}removeToolsForServer(t){let r=`mcp:${t}:`;for(let[l]of this.registeredTools)l.startsWith(r)&&this.registeredTools.delete(l)}registerResourceTools(t){let r={id:"mcp:list-resources",type:"tool",pluginId:rH,name:"ListMcpResources",displayName:"\u5217\u51FAMCP\u8D44\u6E90",description:"\u5217\u51FA\u6240\u6709MCP\u670D\u52A1\u5668\u63D0\u4F9B\u7684\u8D44\u6E90\uFF08\u6587\u4EF6\u3001\u6570\u636E\u7B49\uFF09",parameters:{type:"object",properties:{serverName:{type:"string",description:"MCP\u670D\u52A1\u5668\u540D\u79F0\uFF08\u53EF\u9009\uFF0C\u4E0D\u586B\u5219\u5217\u51FA\u6240\u6709\uFF09"}}},riskLevel:"safe",requiresConfirmation:!1,execute:async u=>{try{let f=u.serverName?this.manager.getAllResources().filter(y=>y.serverName===u.serverName):this.manager.getAllResources();return f.length===0?{success:!0,stdout:"\u6CA1\u6709\u53EF\u7528\u7684MCP\u8D44\u6E90"}:{success:!0,stdout:f.map(y=>`[${y.serverName}] ${y.uri} - ${y.name}${y.description?` (${y.description})`:""}${y.mimeType?` [${y.mimeType}]`:""}`).join(`
|
|
43756
43756
|
`)}}catch(f){return{success:!1,stderr:`\u5217\u51FAMCP\u8D44\u6E90\u5931\u8D25: ${f instanceof Error?f.message:String(f)}`}}},isConcurrencySafe:()=>!0},l={id:"mcp:read-resource",type:"tool",pluginId:rH,name:"ReadMcpResource",displayName:"\u8BFB\u53D6MCP\u8D44\u6E90",description:"\u8BFB\u53D6MCP\u670D\u52A1\u5668\u4E0A\u7684\u6307\u5B9A\u8D44\u6E90",parameters:{type:"object",properties:{serverName:{type:"string",description:"MCP\u670D\u52A1\u5668\u540D\u79F0"},uri:{type:"string",description:"\u8D44\u6E90URI"}},required:["serverName","uri"]},riskLevel:"safe",requiresConfirmation:!1,execute:async u=>{try{let f=u.serverName,_=u.uri;return!f||!_?{success:!1,stderr:"\u9700\u8981\u63D0\u4F9B serverName \u548C uri \u53C2\u6570"}:{success:!0,stdout:(await this.manager.readResource(f,_)).map(I=>{if(typeof I=="object"&&I!==null&&"type"in I){let P=I;return P.type==="text"&&P.text?P.text:JSON.stringify(I)}return String(I)}).join(`
|
|
43757
|
-
`)}}catch(f){return{success:!1,stderr:`\u8BFB\u53D6MCP\u8D44\u6E90\u5931\u8D25: ${f instanceof Error?f.message:String(f)}`}}},isConcurrencySafe:()=>!0};t.tools.register(r),t.tools.register(l),this.registeredTools.set(r.id,r),this.registeredTools.set(l.id,l)}},sHn=yAe});var vAe,XGt=on(()=>{"use strict";ne();vAe=[{name:"skillhub-search",description:"Search for skills on Skillhub
|
|
43757
|
+
`)}}catch(f){return{success:!1,stderr:`\u8BFB\u53D6MCP\u8D44\u6E90\u5931\u8D25: ${f instanceof Error?f.message:String(f)}`}}},isConcurrencySafe:()=>!0};t.tools.register(r),t.tools.register(l),this.registeredTools.set(r.id,r),this.registeredTools.set(l.id,l)}},sHn=yAe});var vAe,XGt=on(()=>{"use strict";ne();vAe=[{name:"skillhub-search",description:"Search for skills on Skillhub (AI skill marketplace)",source:"skillhub",whenToUse:"Use when user wants to find or install skills from Skillhub",arguments:[{name:"query",description:"Search keywords for skills",required:!0},{name:"platform",description:"Filter by platform: claude, codex, copilot, cursor, windsurf"},{name:"sort",description:"Sort by: recommended, aiScore, downloads, stars, rating, recent"},{name:"limit",description:"Number of results (default: 10)"}],allowedTools:["run_shell_command"],getPrompt:async(o,t)=>{let r=o.query,l=o.platform,u=o.sort,f=o.limit,_=`npx skillhub search ${r}`;return l&&(_+=` -p ${l}`),u&&(_+=` -s ${u}`),f&&(_+=` -l ${f}`),`Search for skills on Skillhub.
|
|
43758
43758
|
|
|
43759
43759
|
## Command to Run
|
|
43760
43760
|
\`\`\`bash
|
|
43761
|
-
${
|
|
43761
|
+
${_}
|
|
43762
43762
|
\`\`\`
|
|
43763
43763
|
|
|
43764
43764
|
## Instructions
|
|
43765
|
-
1. Execute the command above to search Skillhub
|
|
43765
|
+
1. Execute the command above to search Skillhub
|
|
43766
43766
|
2. Review the search results
|
|
43767
43767
|
3. Present relevant skills to the user with:
|
|
43768
|
-
- Skill name and description
|
|
43769
|
-
-
|
|
43770
|
-
-
|
|
43771
|
-
-
|
|
43772
|
-
|
|
43768
|
+
- Skill name (format: owner/repo/skill-name) and description
|
|
43769
|
+
- Security scan status (\u{1F6E1}\uFE0F Pass / \u274C Fail)
|
|
43770
|
+
- Downloads and stars
|
|
43771
|
+
- Install command (e.g., \`npx skillhub install <skill-id>\`)
|
|
43773
43772
|
4. If user wants to install a skill, offer to run the install command for them
|
|
43774
43773
|
|
|
43775
43774
|
## Notes
|
|
43776
|
-
-
|
|
43777
|
-
-
|
|
43778
|
-
- Installation requires \`skillhub install <
|
|
43779
|
-
`}},{name:"skillhub-install",description:"Install a skill from Skillhub
|
|
43775
|
+
- Skill ID format is \`owner/repo/skill-name\` (e.g., \`facebook/react/test\`)
|
|
43776
|
+
- Use \`-p\` to filter by platform, \`-s\` to sort, \`-l\` to limit results
|
|
43777
|
+
- Installation requires \`npx skillhub install <skill-id>\` command
|
|
43778
|
+
`}},{name:"skillhub-install",description:"Install a skill from Skillhub",source:"skillhub",whenToUse:"Use when user wants to install a specific skill from Skillhub",arguments:[{name:"skillId",description:"Skill identifier to install (format: owner/repo/skill-name)",required:!0},{name:"platform",description:"Target platform: claude, codex, copilot, cursor, windsurf"},{name:"project",description:"Install in the current project instead of globally (true/false)"}],allowedTools:["run_shell_command"],getPrompt:async(o,t)=>{let r=o.skillId,l=o.platform,u=o.project,f=`npx skillhub install ${r}`;return l&&(f+=` -p ${l}`),u==="true"&&(f+=" --project"),`Install a skill from Skillhub.
|
|
43780
43779
|
|
|
43781
43780
|
## Command to Run
|
|
43782
43781
|
\`\`\`bash
|
|
43783
|
-
${
|
|
43782
|
+
${f}
|
|
43784
43783
|
\`\`\`
|
|
43785
43784
|
|
|
43786
43785
|
## Instructions
|
|
@@ -43790,14 +43789,14 @@ ${u}
|
|
|
43790
43789
|
4. Inform the user that the skill is ready to use
|
|
43791
43790
|
|
|
43792
43791
|
## Notes
|
|
43793
|
-
-
|
|
43794
|
-
-
|
|
43792
|
+
- Skill ID format is \`owner/repo/skill-name\` (e.g., \`openclaw/skills/commit\`)
|
|
43793
|
+
- Use \`-p\` to specify target platform, \`--project\` for project-level install
|
|
43795
43794
|
- Some skills may require additional setup (API keys, configuration, etc.)
|
|
43796
|
-
`}},{name:"skillhub-list",description:"List all installed skills from Skillhub
|
|
43795
|
+
`}},{name:"skillhub-list",description:"List all installed skills from Skillhub",source:"skillhub",whenToUse:"Use when user wants to see what skills are installed from Skillhub",arguments:[{name:"platform",description:"Filter by platform: claude, codex, copilot, cursor, windsurf"},{name:"scope",description:"List scope: global, project, all (default: global)",default:"global"}],allowedTools:["run_shell_command"],getPrompt:async(o,t)=>{let r=o.platform,l=o.scope||"global",u="npx skillhub list";return r&&(u+=` -p ${r}`),l==="all"&&(u+=" --all"),l==="project"&&(u+=" --project"),`List installed skills from Skillhub.
|
|
43797
43796
|
|
|
43798
43797
|
## Command to Run
|
|
43799
43798
|
\`\`\`bash
|
|
43800
|
-
|
|
43799
|
+
${u}
|
|
43801
43800
|
\`\`\`
|
|
43802
43801
|
|
|
43803
43802
|
## Instructions
|
|
@@ -43807,32 +43806,31 @@ skillhub list${r!=="all"?` --source ${r}`:""}
|
|
|
43807
43806
|
4. Offer to help install skills if needed
|
|
43808
43807
|
|
|
43809
43808
|
## Notes
|
|
43810
|
-
- Use \`--
|
|
43811
|
-
- Use \`--
|
|
43812
|
-
-
|
|
43813
|
-
`}},{name:"skillhub-
|
|
43809
|
+
- Use \`--all\` to show both global and project skills
|
|
43810
|
+
- Use \`--project\` to show only project-level skills
|
|
43811
|
+
- Use \`-p\` to filter by platform
|
|
43812
|
+
`}},{name:"skillhub-update",description:"Update installed skills from Skillhub",source:"skillhub",whenToUse:"Use when user wants to update skills to their latest versions",arguments:[{name:"skillName",description:"Specific skill to update (optional, updates all if not specified)"},{name:"platform",description:"Target platform: claude, codex, copilot, cursor, windsurf"}],allowedTools:["run_shell_command"],getPrompt:async(o,t)=>{let r=o.skillName,l=o.platform,u="npx skillhub update";return r&&(u+=` ${r}`),l&&(u+=` -p ${l}`),`Update skills from Skillhub to their latest versions.
|
|
43814
43813
|
|
|
43815
43814
|
## Command to Run
|
|
43816
43815
|
\`\`\`bash
|
|
43817
|
-
${
|
|
43816
|
+
${u}
|
|
43818
43817
|
\`\`\`
|
|
43819
43818
|
|
|
43820
43819
|
## Instructions
|
|
43821
|
-
1. Execute the command above to
|
|
43822
|
-
2. Wait for the
|
|
43823
|
-
3. Review the
|
|
43824
|
-
4. Inform the user about which skills were
|
|
43820
|
+
1. Execute the command above to update skills
|
|
43821
|
+
2. Wait for the update process to complete
|
|
43822
|
+
3. Review the update results for any errors or conflicts
|
|
43823
|
+
4. Inform the user about which skills were updated and their new versions
|
|
43825
43824
|
|
|
43826
43825
|
## Notes
|
|
43827
|
-
-
|
|
43828
|
-
- If
|
|
43829
|
-
-
|
|
43830
|
-
-
|
|
43831
|
-
`}},{name:"skillhub-uninstall",description:"Uninstall a skill from Skillhub.cn",source:"skillhub",whenToUse:"Use when user wants to remove a skill installed from Skillhub.cn",arguments:[{name:"slug",description:"Skill identifier (slug) to uninstall",required:!0}],allowedTools:["run_shell_command"],getPrompt:async(o,t)=>`Uninstall a skill from Skillhub.cn.
|
|
43826
|
+
- If a specific skill name is provided, only that skill is updated
|
|
43827
|
+
- If no skill name is specified, use \`--all\` to update all installed skills
|
|
43828
|
+
- Use \`-p\` to target a specific platform
|
|
43829
|
+
`}},{name:"skillhub-uninstall",description:"Uninstall a skill from Skillhub",source:"skillhub",whenToUse:"Use when user wants to remove a skill installed from Skillhub",arguments:[{name:"skillName",description:"Skill name to uninstall",required:!0},{name:"platform",description:"Target platform: claude, codex, copilot, cursor, windsurf"},{name:"project",description:"Uninstall from project instead of globally (true/false)"}],allowedTools:["run_shell_command"],getPrompt:async(o,t)=>{let r=o.skillName,l=o.platform,u=o.project,f=`npx skillhub uninstall ${r}`;return l&&(f+=` -p ${l}`),u==="true"&&(f+=" --project"),`Uninstall a skill from Skillhub.
|
|
43832
43830
|
|
|
43833
43831
|
## Command to Run
|
|
43834
43832
|
\`\`\`bash
|
|
43835
|
-
|
|
43833
|
+
${f}
|
|
43836
43834
|
\`\`\`
|
|
43837
43835
|
|
|
43838
43836
|
## Instructions
|
|
@@ -43842,91 +43840,13 @@ skillhub uninstall ${o.slug}
|
|
|
43842
43840
|
4. Inform the user that the skill has been uninstalled
|
|
43843
43841
|
|
|
43844
43842
|
## Notes
|
|
43845
|
-
-
|
|
43846
|
-
-
|
|
43847
|
-
-
|
|
43848
|
-
`},{name:"skillhub-info",description:"Get detailed information about a specific skill from Skillhub.cn",source:"skillhub",whenToUse:"Use when user wants to know more details about a specific skill",arguments:[{name:"slug",description:"Skill identifier (slug) to get information for",required:!0}],allowedTools:["run_shell_command"],getPrompt:async(o,t)=>`Get detailed information about a skill from Skillhub.cn.
|
|
43849
|
-
|
|
43850
|
-
## Command to Run
|
|
43851
|
-
\`\`\`bash
|
|
43852
|
-
skillhub info ${o.slug}
|
|
43853
|
-
\`\`\`
|
|
43854
|
-
|
|
43855
|
-
## Instructions
|
|
43856
|
-
1. Execute the command above to get skill information
|
|
43857
|
-
2. Present the skill details to the user including:
|
|
43858
|
-
- Name and description
|
|
43859
|
-
- Version
|
|
43860
|
-
- Author
|
|
43861
|
-
- Installation instructions
|
|
43862
|
-
- Dependencies or requirements
|
|
43863
|
-
- Configuration options
|
|
43864
|
-
3. Offer to install the skill if the user is interested
|
|
43865
|
-
|
|
43866
|
-
## Notes
|
|
43867
|
-
- Skill information includes metadata, dependencies, and installation requirements
|
|
43868
|
-
- Some skills may require API keys or additional setup
|
|
43869
|
-
- Check the skill's documentation for detailed usage instructions
|
|
43870
|
-
`},{name:"skillhub-categories",description:"List all skill categories on Skillhub.cn",source:"skillhub",whenToUse:"Use when user wants to browse skill categories",arguments:[],allowedTools:["run_shell_command"],getPrompt:async(o,t)=>`List all skill categories on Skillhub.cn.
|
|
43871
|
-
|
|
43872
|
-
## Command to Run
|
|
43873
|
-
\`\`\`bash
|
|
43874
|
-
skillhub categories
|
|
43875
|
-
\`\`\`
|
|
43876
|
-
|
|
43877
|
-
## Instructions
|
|
43878
|
-
1. Execute the command above to list categories
|
|
43879
|
-
2. Present the categories to the user in a structured format
|
|
43880
|
-
3. If the user is interested in a specific category, offer to search within that category
|
|
43881
|
-
4. Provide examples of popular skills in each category
|
|
43882
|
-
|
|
43883
|
-
## Notes
|
|
43884
|
-
- Categories help organize skills by domain (e.g., calendar, development, productivity)
|
|
43885
|
-
- Some skills may appear in multiple categories
|
|
43886
|
-
- Categories can be used to filter search results
|
|
43887
|
-
`},{name:"skillhub-popular",description:"List popular/trending skills on Skillhub.cn",source:"skillhub",whenToUse:"Use when user wants to discover popular or trending skills",arguments:[{name:"limit",description:"Number of popular skills to show (default: 10)",default:"10"}],allowedTools:["run_shell_command"],getPrompt:async(o,t)=>`List popular/trending skills on Skillhub.cn.
|
|
43888
|
-
|
|
43889
|
-
## Command to Run
|
|
43890
|
-
\`\`\`bash
|
|
43891
|
-
skillhub popular --limit ${o.limit||"10"}
|
|
43892
|
-
\`\`\`
|
|
43893
|
-
|
|
43894
|
-
## Instructions
|
|
43895
|
-
1. Execute the command above to list popular skills
|
|
43896
|
-
2. Present the popular skills to the user with:
|
|
43897
|
-
- Skill name and description
|
|
43898
|
-
- Download count or popularity score
|
|
43899
|
-
- Rating or reviews (if available)
|
|
43900
|
-
- Installation command
|
|
43901
|
-
3. Offer to install any skills that interest the user
|
|
43902
|
-
4. Highlight skills that are newly trending or highly rated
|
|
43903
|
-
|
|
43904
|
-
## Notes
|
|
43905
|
-
- Popular skills are determined by download count, ratings, and recent activity
|
|
43906
|
-
- Trending skills show recent increases in popularity
|
|
43907
|
-
- Popular skills are often good starting points for new users
|
|
43908
|
-
`},{name:"skillhub-update",description:"Update the Skillhub CLI to the latest version",source:"skillhub",whenToUse:"Use when user wants to update the Skillhub CLI tool itself",arguments:[],allowedTools:["run_shell_command"],getPrompt:async(o,t)=>`Update the Skillhub CLI to the latest version.
|
|
43909
|
-
|
|
43910
|
-
## Command to Run
|
|
43911
|
-
\`\`\`bash
|
|
43912
|
-
skillhub self-upgrade
|
|
43913
|
-
\`\`\`
|
|
43914
|
-
|
|
43915
|
-
## Instructions
|
|
43916
|
-
1. Execute the command above to update the Skillhub CLI
|
|
43917
|
-
2. Wait for the update to complete
|
|
43918
|
-
3. Verify the new version is installed
|
|
43919
|
-
4. Inform the user about what changed in the update
|
|
43920
|
-
|
|
43921
|
-
## Notes
|
|
43922
|
-
- The Skillhub CLI checks for updates automatically on startup
|
|
43923
|
-
- Manual update ensures you have the latest features and bug fixes
|
|
43924
|
-
- After updating, restart your terminal or OpenClaw to use the new version
|
|
43925
|
-
`},{name:"skillhub-help",description:"Get help and usage information for Skillhub CLI",source:"skillhub",whenToUse:"Use when user needs help with Skillhub CLI commands",arguments:[{name:"command",description:"Specific command to get help for (optional)"}],allowedTools:["run_shell_command"],getPrompt:async(o,t)=>{let r=o.command;return`Get help and usage information for Skillhub CLI.
|
|
43843
|
+
- Use \`--project\` to uninstall from project-level instead of globally
|
|
43844
|
+
- Use \`-p\` to target a specific platform
|
|
43845
|
+
`}},{name:"skillhub-help",description:"Get help and usage information for Skillhub CLI",source:"skillhub",whenToUse:"Use when user needs help with Skillhub CLI commands",arguments:[{name:"command",description:"Specific command to get help for: search, install, list, update, uninstall, config"}],allowedTools:["run_shell_command"],getPrompt:async(o,t)=>{let r=o.command;return`Get help and usage information for Skillhub CLI.
|
|
43926
43846
|
|
|
43927
43847
|
## Command to Run
|
|
43928
43848
|
\`\`\`bash
|
|
43929
|
-
${r?`skillhub ${r} --help`:"skillhub --help"}
|
|
43849
|
+
${r?`npx skillhub ${r} --help`:"npx skillhub --help"}
|
|
43930
43850
|
\`\`\`
|
|
43931
43851
|
|
|
43932
43852
|
## Instructions
|
|
@@ -43936,9 +43856,8 @@ ${r?`skillhub ${r} --help`:"skillhub --help"}
|
|
|
43936
43856
|
4. If the help is general, provide an overview of available commands
|
|
43937
43857
|
|
|
43938
43858
|
## Notes
|
|
43939
|
-
- Skillhub CLI supports: search, install, uninstall, list,
|
|
43859
|
+
- Skillhub CLI supports: search, install, uninstall, list, update, config
|
|
43940
43860
|
- Use \`--help\` flag to get detailed usage for any command
|
|
43941
|
-
- Help includes examples and parameter descriptions
|
|
43942
43861
|
`}}]});async function aHn(o){try{let r=(await(0,iH.readFile)(o,"utf-8")).replace(/\r\n/g,`
|
|
43943
43862
|
`).replace(/\r/g,`
|
|
43944
43863
|
`),l=/^---\n([\s\S]*?)\n---\n([\s\S]*)$/,u=r.match(l);if(!u)return dE.warn({filePath:o},"Invalid skill file format (missing frontmatter)"),null;let f=u[1],_=u[2],y={},T=f.split(`
|
|
@@ -44324,7 +44243,7 @@ ${l}`))}showConfig(){let t=this._deps.cliService.currentAgentName??"\u672A\u9009
|
|
|
44324
44243
|
\u672A\u627E\u5230\u5339\u914D\u7684\u8BB0\u5FC6`));else{let y=`\u{1F50D} \u641C\u7D22 "${f}"
|
|
44325
44244
|
|
|
44326
44245
|
`;for(let T of _)y+=`- **${T.name}** (${T.type}) \u2014 ${T.description}
|
|
44327
|
-
`;this._deps.output(oa(y))}break}default:this._deps.output(oa("\u274C \u672A\u77E5\u5B50\u547D\u4EE4\n\n\u53EF\u7528: `/memory list` | `/memory add <type> <name> | <\u5185\u5BB9>` | `/memory delete <\u540D\u79F0>` | `/memory search <\u5173\u952E\u8BCD>`"))}}showHistory(){let t=[];t.push(""),t.push(Ht.bold.white("\u8F93\u5165\u5386\u53F2:")),t.push(Ht.gray("\u2500".repeat(40)));let r=this._deps.historyManager.getHistory().slice(-10);for(let l=0;l<r.length;l++)t.push(Ht.dim(` ${l+1}. `)+r[l]);t.push(Ht.gray("\u2500".repeat(40))),t.push(""),this._deps.outputBatch(t)}async handleUpgrade(t){let r=this._deps.upgradeExecutor;if(t==="check"){this._deps.output(oa("\u{1F50D} \u6B63\u5728\u68C0\u67E5\u66F4\u65B0..."));let _=await r.checkForUpdate();if(!_){this._deps.output(oa("\u274C \u65E0\u6CD5\u83B7\u53D6\u7248\u672C\u4FE1\u606F\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5"));return}_.hasUpdate?this._deps.output(oa(`\u{1F504} \u53D1\u73B0\u65B0\u7248\u672C
|
|
44246
|
+
`;this._deps.output(oa(y))}break}default:this._deps.output(oa("\u274C \u672A\u77E5\u5B50\u547D\u4EE4\n\n\u53EF\u7528: `/memory list` | `/memory add <type> <name> | <\u5185\u5BB9>` | `/memory delete <\u540D\u79F0>` | `/memory search <\u5173\u952E\u8BCD>`"))}}showHistory(){let t=[];t.push(""),t.push(Ht.bold.white("\u8F93\u5165\u5386\u53F2:")),t.push(Ht.gray("\u2500".repeat(40)));let r=this._deps.historyManager.getHistory().slice(-10);for(let l=0;l<r.length;l++)t.push(Ht.dim(` ${l+1}. `)+r[l]);t.push(Ht.gray("\u2500".repeat(40))),t.push(""),this._deps.outputBatch(t)}async handleUpgrade(t){let r=this._deps.upgradeExecutor;if(t==="check"){this._deps.output(oa("\u{1F50D} \u6B63\u5728\u68C0\u67E5\u66F4\u65B0..."));let _=await r.checkForUpdate({force:!0});if(!_){this._deps.output(oa("\u274C \u65E0\u6CD5\u83B7\u53D6\u7248\u672C\u4FE1\u606F\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5"));return}_.hasUpdate?this._deps.output(oa(`\u{1F504} \u53D1\u73B0\u65B0\u7248\u672C
|
|
44328
44247
|
|
|
44329
44248
|
- **\u5F53\u524D\u7248\u672C**: ${_.currentVersion}
|
|
44330
44249
|
- **\u6700\u65B0\u7248\u672C**: ${_.latestVersion}
|
|
@@ -44335,7 +44254,7 @@ ${l}`))}showConfig(){let t=this._deps.cliService.currentAgentName??"\u672A\u9009
|
|
|
44335
44254
|
|
|
44336
44255
|
\u8BF7\u786E\u4FDD npm \u5DF2\u5B89\u88C5\u5E76\u5728 PATH \u4E2D`));return}if(!l.isNpmGlobalInstall){this._deps.output(oa(`\u274C \u5F53\u524D\u975E npm \u5168\u5C40\u5B89\u88C5\uFF0C\u4E0D\u652F\u6301\u81EA\u52A8\u5347\u7EA7
|
|
44337
44256
|
|
|
44338
|
-
\u8BF7\u901A\u8FC7\u6E90\u7801\u65B9\u5F0F\u624B\u52A8\u66F4\u65B0`));return}this._deps.output(oa("\u{1F50D} \u6B63\u5728\u68C0\u67E5\u66F4\u65B0..."));let u=await r.checkForUpdate();if(!u){this._deps.output(oa("\u274C \u65E0\u6CD5\u83B7\u53D6\u7248\u672C\u4FE1\u606F\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5"));return}if(!u.hasUpdate){this._deps.output(oa(`\u2705 \u5F53\u524D\u5DF2\u662F\u6700\u65B0\u7248\u672C (**${vv}**)`));return}this._deps.output(oa(`\u{1F504} \u53D1\u73B0\u65B0\u7248\u672C **${u.latestVersion}** (\u5F53\u524D: ${vv})
|
|
44257
|
+
\u8BF7\u901A\u8FC7\u6E90\u7801\u65B9\u5F0F\u624B\u52A8\u66F4\u65B0`));return}this._deps.output(oa("\u{1F50D} \u6B63\u5728\u68C0\u67E5\u66F4\u65B0..."));let u=await r.checkForUpdate({force:!0});if(!u){this._deps.output(oa("\u274C \u65E0\u6CD5\u83B7\u53D6\u7248\u672C\u4FE1\u606F\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5"));return}if(!u.hasUpdate){this._deps.output(oa(`\u2705 \u5F53\u524D\u5DF2\u662F\u6700\u65B0\u7248\u672C (**${vv}**)`));return}this._deps.output(oa(`\u{1F504} \u53D1\u73B0\u65B0\u7248\u672C **${u.latestVersion}** (\u5F53\u524D: ${vv})
|
|
44339
44258
|
|
|
44340
44259
|
\u23F3 \u6B63\u5728\u5347\u7EA7...`));let f=await r.upgrade(void 0,l,u);f.success?this._deps.output(oa(`\u2705 \u5347\u7EA7\u6210\u529F!
|
|
44341
44260
|
|
|
@@ -44400,7 +44319,7 @@ ${l.error??"\u672A\u77E5\u9519\u8BEF"}`))}reset(){this._deps.cliService.resetAge
|
|
|
44400
44319
|
`)}catch{}let l=this.menuResolve,u=this.items[this.selectedIndex];if(this.menuMode==="navigation"){if(r==="\x1B[A")return this.selectedIndex=(this.selectedIndex-1+this.items.length)%this.items.length,this.render(),!0;if(r==="\x1B[B")return this.selectedIndex=(this.selectedIndex+1)%this.items.length,this.render(),!0;if(r==="\x1B[C"||r==="\x1BOC")return u?.isDirectory&&(this.cleanup(),l({action:"enter_dir",selected:u.value})),!0;if(r==="\x1B[D"||r==="\x1BOD")return this.cleanup(),l({action:"go_back",selected:""}),!0;if(r==="\r"||r===`
|
|
44401
44320
|
`||r.charCodeAt(0)===13||r.charCodeAt(0)===10)return u&&(this.cleanup(),l({action:"select",selected:u.value})),!0;if(r==="\x1B"||r.charCodeAt(0)===27)return this.cleanup(),l(null),!0;if(r.charCodeAt(0)===3)return this.cleanup(),process.emit("SIGINT"),l(null),!0;if(r.charCodeAt(0)===127||r.charCodeAt(0)===8)return this.cleanup(),l(null),!0}else{if(r==="\x1B[A")return this.selectedIndex=this.findNextSelectable(this.selectedIndex,-1),this.render(),!0;if(r==="\x1B[B")return this.selectedIndex=this.findNextSelectable(this.selectedIndex,1),this.render(),!0;if(r==="\r"||r===`
|
|
44402
44321
|
`||r.charCodeAt(0)===13||r.charCodeAt(0)===10){let f=this.items[this.selectedIndex];return!f||!this.isSelectable(this.selectedIndex)?(this.selectedIndex=this.findNextSelectable(this.selectedIndex,1),this.render(),!0):(this.cleanup(),l(f?{selected:f.value,prefix:this.prefix}:null),!0)}if(r==="\x1B"||r.charCodeAt(0)===27)return this.isFiltering?(this.filterText="",this.isFiltering=!1,this.applyFilter(),this.render(),!0):(this.cleanup(),l(null),!0);if(r.charCodeAt(0)===3)return this.cleanup(),process.emit("SIGINT"),l(null),!0;if(r.charCodeAt(0)===127||r.charCodeAt(0)===8)return this.isFiltering&&this.filterText.length>0?(this.filterText=this.filterText.slice(0,-1),this.filterText.length===0&&(this.isFiltering=!1),this.applyFilter(),this.render(),!0):(this.cleanup(),l(null),!0);if(r.length===1){let f=r.charCodeAt(0);if(f>=32&&f<=126)return this.filterText+=r.toLowerCase(),this.isFiltering=!0,this.applyFilter(),this.render(),!0}}return!1}insertLinesForMenu(){let t=process.stdout.rows||24,l=Math.min(this.items.length,15)+1,u=this.menuHeader?1:0,f=l+u+1,_=0;this.hasModelOutput?(this.lastPushedLines=0,this.hasModelOutput=!1,_=f):this.lastPushedLines>=f?_=0:_=f-this.lastPushedLines,this.lastPushedLines+=_;let y=process.stdout.columns||80,T=this.getStatusBar?this.getStatusBar():"",I=this.stripAnsi(T),O=2+Math.max(1,Math.ceil([...I].length/y))+1,L="";for(let J=0;J<O;J++){let V=t-J;V>0&&(L+=`\x1B[${V};1H\x1B[2K`)}if(this.stdout.write(L),_>0){this.stdout.write(`\x1B[${t-2};1H`);let J=`
|
|
44403
|
-
`.repeat(_);this.stdout.write(J)}this.savedCursorRow=Math.max(1,t-2-l-u)}applyFilter(){if(!this.filterText)this.items=[...this.allItems];else{let t=this.allItems.filter(r=>r.selectable===!1?!0:r.name.toLowerCase().includes(this.filterText)||(r.description?.toLowerCase().includes(this.filterText)??!1));this.items=t.filter((r,l)=>{if(r.selectable===!1){let u=t[l+1];return u&&u.selectable!==!1}return!0})}this.selectedIndex=this.isSelectable(0)?0:this.findNextSelectable(0,1)}render(){let t=Math.min(this.items.length,15),r=Math.max(0,Math.min(this.selectedIndex-3,this.items.length-t));this._visibleStart=r;let l=Math.min(this.items.length,r+t),u=[];this.menuHeader&&u.push(Ht.yellow.bold(this.menuHeader)),this.isFiltering&&u.push(Ht.yellow(` \u641C\u7D22: ${this.filterText}_`));for(let L=r;L<l;L++){let J=this.items[L],V=L===this.selectedIndex,K=V?"\u25B6":" ",ye=this.stripAnsi(J.name);if(J.selectable===!1){u.push(Ht.gray.dim(` ${ye}`));continue}let he=V?Ht.cyan.bold(ye):Ht.gray(ye);if(J.description){let Ae=V?Ht.cyan.dim(` \u2014 ${J.description}`):Ht.gray.dim(` \u2014 ${J.description}`);he+=Ae}u.push(` ${K} ${he}`)}let f=this.prefix==="@",_=this.isFiltering?f?"\u8F93\u5165\u7B5B\u9009 \u2191\u2193 \u2190\u2192 Enter Esc":"\u8F93\u5165\u7B5B\u9009 \u2191\u2193 Enter Esc":f?"\u2191\u2193 \u2190\u2192 Enter Esc":"\u2191\u2193 Enter Esc";u.push(Ht.gray(` ${_}`));let y="";y+="\x1B[?25l";let T=process.stdout.rows||24;this.menuStartRow=Math.max(1,this.savedCursorRow);let I=this.menuLines;for(let L=0;L<I;L++){let J=this.menuStartRow+L;J>0&&(y+=`\x1B[${J};1H`,y+="\x1B[2K")}let P=process.stdout.columns||80;for(let L=0;L<u.length;L++){let J=this.menuStartRow+L;y+=`\x1B[${J};1H`,y+="\x1B[2K",y+=this.truncateToWidth(u[L],P)}if(this.menuLines=Math.max(this.menuLines,u.length),this.getStatusBar){let L=this.menuStartRow+this.menuLines;for(let J=L;J<T;J++)J>0&&(y+=`\x1B[${J};1H`,y+="\x1B[2K");y+=`\x1B[${T};1H`,y+="\x1B[2K",y+=this.truncateToWidth(this.getStatusBar(),P)}let O=this.selectedIndex-this._visibleStart;if(O>=0&&O<u.length){let L=this.menuStartRow+(this.menuHeader?1:0)+O;y+=`\x1B[${L};1H`}y+="\x1B[?25h",this.stdout.write(y)}stripAnsi(t){return t.replace(/\x1b\[[0-9;]*m/g,"")}truncateToWidth(t,r){let l=t.split(/(\x1b\[[0-9;]*m)/),u=0,f="";for(let _ of l)if(_.startsWith("\x1B["))f+=_;else for(let y of _){let T=zk(y);if(u+T>r)return f;u+=T,f+=y}return f}cleanup(){this.isActive=!1,this.menuHeader="",this.menuResolve=null,this.filterText="",this.isFiltering=!1,this.stdout.write("\x1B[?25l");let t=this.menuStartRow>0?this.menuStartRow:this.savedCursorRow,r=process.stdout.rows||24;for(let l=t;l<=r;l++)this.stdout.write(`\x1B[${l};1H\x1B[2K`);this.stdout.write("\x1B[?25h"),this.menuLines=0,this.dispatcher?this.dispatcher.unregister(this.menuContextName):this.dataHandler&&(this.stdin.removeListener("data",this.dataHandler),this.dataHandler=null)}get active(){return this.isActive}};ne();var Wve=class{contexts=[];register(t){this.contexts.push(t),this.contexts.sort((r,l)=>l.priority-r.priority)}unregister(t){this.contexts=this.contexts.filter(r=>r.name!==t)}dispatch(t){for(let r of this.contexts)if(r.isActive()&&r.handle(t))return!0;return!1}getActiveContexts(){return this.contexts.filter(t=>t.isActive()).map(t=>t.name)}};ne();var Bve=class{getCommandRegistry;getAgents;suggestion=null;constructor(t,r){this.getCommandRegistry=t,this.getAgents=r}updateSuggestions(t,r){if(this.suggestion=null,!t||t.length===0)return;let l=[...t];if(r===l.length){if(t.startsWith("/")&&t.length>1&&!t.includes(" ")){let u=this.getCommandRegistry();if(u){let f=u.getCommands(),_=t.toLowerCase(),y=f.find(T=>T.name.toLowerCase().startsWith(_)&&T.name.toLowerCase()!==_);if(y){let T=y.name.slice(t.length);this.suggestion={text:T,fullReplacement:y.name,source:"command"}}}return}if(t.startsWith("#")&&t.length>1&&!t.includes(" ")){let u=this.getAgents(),f=t.toLowerCase(),_=u.find(y=>`#${y.toLowerCase()}`.startsWith(f)&&`#${y.toLowerCase()}`!==f);if(_){let y=`#${_}`,T=y.slice(t.length);this.suggestion={text:T,fullReplacement:y,source:"agent"}}return}}}getSuggestion(){return this.suggestion}clear(){this.suggestion=null}accept(){if(!this.suggestion)return null;let t=this.suggestion.fullReplacement;return this.suggestion=null,t}};cB();var oYe=require("node:path"),q5t=require("node:fs");ne();var zve=require("node:fs"),e$e=require("node:path"),t$e=require("node:fs"),Gve=class{filePath;heartbeatTimer=null;constructor(t){this.filePath=(0,e$e.join)(t,"instances.json")}async register(t){let l=(await this.loadAll()).filter(u=>u.pid!==t.pid);l.push(t),await this.saveAll(l)}async unregister(t){let l=(await this.loadAll()).filter(u=>u.id!==t);await this.saveAll(l)}async updateHeartbeat(t){let r=await this.loadAll(),l=r.find(u=>u.id===t);l&&(l.lastHeartbeat=Date.now(),await this.saveAll(r))}startHeartbeat(t,r=3e4){this.stopHeartbeat(),this.heartbeatTimer=setInterval(async()=>{try{await this.updateHeartbeat(t)}catch{}},r)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}async listInstances(){return this.loadAll()}async listResumable(){return(await this.loadAll()).filter(r=>r.sessionId).sort((r,l)=>l.lastHeartbeat-r.lastHeartbeat)}isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}async cleanup(t=10080*60*1e3){let r=await this.loadAll(),l=Date.now(),u=r.filter(_=>this.isProcessAlive(_.pid)?!0:l-_.lastHeartbeat<t),f=r.length-u.length;return f>0&&await this.saveAll(u),f}async loadAll(){if(!(0,t$e.existsSync)(this.filePath))return[];try{let t=await zve.promises.readFile(this.filePath,"utf-8");return JSON.parse(t).instances??[]}catch{return[]}}async saveAll(t){let r=(0,e$e.join)(this.filePath,"..");(0,t$e.existsSync)(r)||await zve.promises.mkdir(r,{recursive:!0}),await zve.promises.writeFile(this.filePath,JSON.stringify({version:1,instances:t},null,2),"utf-8")}};ne();var kF=bs(require("node:path"),1),D2t=bs(require("node:crypto"),1),Ev=require("node:fs");zd();var F4n=Ma("file-history-store"),jve=class{_baseDir;constructor(t){this._baseDir=t}async recordChange(t,r,l,u="unknown"){let f=this.getSessionDir(t);this.ensureDir(f);let _=this.hashContent(l),y=await this.loadIndex(t),T=y.filter(V=>V.filePath===r),P=(T.length>0?Math.max(...T.map(V=>V.version)):0)+1,O=`${_}@v${P}`,L=kF.join(f,O);(0,Ev.writeFileSync)(L,l,"utf-8");let J={version:P,filePath:r,contentHash:_,timestamp:Date.now(),source:u,sessionId:t};return y.push(J),await this.saveIndex(t,y),F4n.debug(`Recorded file change: ${r} v${P} (source: ${u})`),P}async undo(t,r){let l=await this.loadIndex(t);if(l.length===0)return[];let u=[];if(r){let f=await this.undoFile(t,r,l);f&&u.push(f)}else{let _=Math.max(...l.map(I=>I.timestamp))-2e3,y=l.filter(I=>I.timestamp>=_),T=[...new Set(y.map(I=>I.filePath))];for(let I of T){let P=await this.undoFile(t,I,l);P&&u.push(P)}}return u}async undoFile(t,r,l){let u=l.filter(P=>P.filePath===r).sort((P,O)=>O.version-P.version);if(u.length===0)return null;let f=u[0],_=this.getSessionDir(t),y=`${f.contentHash}@v${f.version}`,T=kF.join(_,y);if(u.length>1){let P=u[1],O=`${P.contentHash}@v${P.version}`,L=kF.join(_,O);try{let J=(0,Ev.readFileSync)(L,"utf-8");(0,Ev.writeFileSync)(r,J,"utf-8")}catch{return{success:!1,filePath:r,restoredVersion:f.version-1,error:"Failed to read previous version"}}}else try{let{unlink:P}=await import("node:fs/promises");await P(r)}catch{}let I=l.filter(P=>!(P.filePath===r&&P.version===f.version));await this.saveIndex(t,I);try{let{unlink:P}=await import("node:fs/promises");await P(T)}catch{}return{success:!0,filePath:r,restoredVersion:f.version-1}}async getFileHistory(t,r){return(await this.loadIndex(t)).filter(u=>u.filePath===r).sort((u,f)=>u.version-f.version)}async getSessionHistory(t){return(await this.loadIndex(t)).sort((l,u)=>l.timestamp-u.timestamp)}async cleanup(t){let r=this.getSessionDir(t);try{let{rm:l}=await import("node:fs/promises");await l(r,{recursive:!0,force:!0})}catch{}}async cleanupOldSessions(t=10080*60*1e3){let r=kF.join(this._baseDir,"file-history");if(!(0,Ev.existsSync)(r))return 0;let l=Date.now(),u=0;try{let f=(0,Ev.readdirSync)(r);for(let _ of f){let y=kF.join(r,_);try{let T=(0,Ev.statSync)(y);if(T.isDirectory()&&l-T.mtimeMs>t){let{rm:I}=await import("node:fs/promises");await I(y,{recursive:!0,force:!0}),u++}}catch{}}}catch{}return u}getSessionDir(t){return kF.join(this._baseDir,"file-history",t)}ensureDir(t){(0,Ev.existsSync)(t)||(0,Ev.mkdirSync)(t,{recursive:!0})}hashContent(t){return D2t.createHash("sha256").update(t).digest("hex").slice(0,12)}getIndexFilePath(t){return kF.join(this.getSessionDir(t),"_index.json")}async loadIndex(t){let r=this.getIndexFilePath(t);if(!(0,Ev.existsSync)(r))return[];try{let l=(0,Ev.readFileSync)(r,"utf-8");return JSON.parse(l)}catch{return[]}}async saveIndex(t,r){let l=this.getIndexFilePath(t),u=this.getSessionDir(t);this.ensureDir(u);let f=l+".tmp";(0,Ev.writeFileSync)(f,JSON.stringify(r,null,2),"utf-8");try{let{rename:_}=await import("node:fs/promises");await _(f,l)}catch{(0,Ev.writeFileSync)(l,JSON.stringify(r,null,2),"utf-8")}}};var GAe=require("node:fs"),J5t=bs(require("node:readline"),1);ef();ne();var fB=require("fs/promises"),Dte=require("path");Gx();zd();ef();var Vve=Ma("settings-loader"),Uve="settings.json",LF;(function(o){o[o.Enterprise=0]="Enterprise",o[o.User=1]="User",o[o.Project=2]="Project"})(LF||(LF={}));function W4n(){return process.platform==="win32"?(0,Dte.join)(process.env.ProgramData??"C:\\ProgramData","aggroot",Uve):"/etc/aggroot/settings.json"}function B4n(o){return[{path:W4n(),source:LF.Enterprise},{path:(0,Dte.join)(Ra,Uve),source:LF.User},{path:K3(o,Uve),source:LF.Project}]}async function z4n(o){try{let t=await(0,fB.readFile)(o,"utf-8"),r=JSON.parse(t);return Vve.debug({path:o},"Loaded settings file"),r}catch(t){return t.code==="ENOENT"||Vve.warn({path:o,error:String(t)},"Failed to load settings file"),null}}function G4n(o,t,r){let l={...o};return t.permissions&&(l.permissions={allow:[...l.permissions?.allow??[],...t.permissions.allow],deny:[...l.permissions?.deny??[],...t.permissions.deny],ask:[...l.permissions?.ask??[],...t.permissions.ask]}),t.hooks&&(l.hooks={...l.hooks,...t.hooks}),t.env&&(l.env={...l.env,...t.env}),t.mcp&&(l.mcp={...l.mcp,...t.mcp}),t.features&&(l.features={...l.features,...t.features}),t.preferences&&(l.preferences={...l.preferences,...t.preferences}),r===LF.Enterprise&&t.policy&&(l.policy=t.policy),t.version&&(!l.version||t.version>l.version)&&(l.version=t.version),l}function j4n(o){let t=o.policy;if(!t)return o;let r={...o};return t.allowManagedMcpServersOnly&&t.allowedMcpServers&&r.mcp?.autoConnectServers&&(r.mcp.autoConnectServers=r.mcp.autoConnectServers.filter(l=>t.allowedMcpServers.includes(l))),t.blockedTools?.length&&(r.permissions={allow:[...r.permissions?.allow??[]],deny:[...r.permissions?.deny??[],...t.blockedTools],ask:[...r.permissions?.ask??[]]}),t.requireApproval?.length&&(r.permissions={allow:[...r.permissions?.allow??[]],deny:[...r.permissions?.deny??[]],ask:[...r.permissions?.ask??[],...t.requireApproval]}),r}async function P2t(o){let t=B4n(o),r=await Promise.all(t.map(({path:u})=>z4n(u))),l={};for(let u=0;u<r.length;u++){let f=r[u];if(!f)continue;let _=t[u].source;l.policy?.disableUserOverride&&_===LF.User||l.policy?.disableProjectOverride&&_===LF.Project||(l=G4n(l,f,_))}return l=j4n(l),l}async function Pte(o){let t=(0,Dte.join)(Ra,Uve);try{let r={};try{let l=await(0,fB.readFile)(t,"utf-8");r=JSON.parse(l)}catch{}r.preferences={...r.preferences,...o},await(0,fB.mkdir)(Ra,{recursive:!0}),await(0,fB.writeFile)(t,JSON.stringify(r,null,2),"utf-8"),Vve.info({path:t,prefs:o},"User preferences saved")}catch(r){Vve.warn({error:String(r)},"Failed to save user preferences (non-fatal)")}}FQ();ne();ne();var aU=require("node:fs/promises"),n$e=require("node:path"),r$e=require("node:fs"),i$e=bs(require("node:https"),1);qT();qT();ef();var Rte=class{_cachePath;_registryBase;_checkIntervalMs;_enabled;constructor(t){this._cachePath=(0,n$e.join)(t?.dataDir??Ra,KIt),this._registryBase=t?.registryBase??"https://registry.npmjs.org",this._checkIntervalMs=t?.checkIntervalMs??$It,this._enabled=t?.enabled??!0}async checkForUpdate(t){if(!this._enabled)return null;if(!t?.force){let _=await this._loadCache();if(_&&Date.now()-new Date(_.lastCheckTime).getTime()<this._checkIntervalMs)return{hasUpdate:this._isNewer(_.latestVersion,vv),currentVersion:vv,latestVersion:_.latestVersion,checkedAt:_.lastCheckTime}}let r=await this._fetchLatestVersion();if(!r)return null;let l=this._isNewer(r,vv),u=new Date().toISOString(),f={lastCheckTime:u,latestVersion:r,currentVersionAtCheck:vv,hasUpdate:l};return await this._saveCache(f),{hasUpdate:l,currentVersion:vv,latestVersion:r,checkedAt:u}}async checkInBackground(){try{return await this.checkForUpdate()}catch{return null}}async getCachedResult(){let t=await this._loadCache();return t?{hasUpdate:this._isNewer(t.latestVersion,vv),currentVersion:vv,latestVersion:t.latestVersion,checkedAt:t.lastCheckTime}:null}_isNewer(t,r){let l=t.replace(/^v/,"").split(".").map(Number),u=r.replace(/^v/,"").split(".").map(Number);for(let f=0;f<3;f++){if((l[f]??0)>(u[f]??0))return!0;if((l[f]??0)<(u[f]??0))return!1}return!1}_fetchLatestVersion(){let t=`${this._registryBase}/aggroot/latest`;return new Promise(r=>{let l=setTimeout(()=>{u.destroy(),r(null)},hje),u=i$e.default.get(t,f=>{if(f.statusCode===301||f.statusCode===302){let y=f.headers.location;if(y){clearTimeout(l),r(this._fetchFromUrl(y));return}}if(f.statusCode!==200){clearTimeout(l),f.resume(),r(null);return}let _="";f.on("data",y=>{_+=y.toString()}),f.on("end",()=>{clearTimeout(l);try{let y=JSON.parse(_);r(y.version??null)}catch{r(null)}}),f.on("error",()=>{clearTimeout(l),r(null)})});u.on("error",()=>{clearTimeout(l),r(null)})})}_fetchFromUrl(t){return new Promise(r=>{let l=setTimeout(()=>{u.destroy(),r(null)},hje),u=i$e.default.get(t,f=>{if(f.statusCode!==200){clearTimeout(l),f.resume(),r(null);return}let _="";f.on("data",y=>{_+=y.toString()}),f.on("end",()=>{clearTimeout(l);try{let y=JSON.parse(_);r(y.version??null)}catch{r(null)}})});u.on("error",()=>{clearTimeout(l),r(null)})})}async _loadCache(){try{if(!(0,r$e.existsSync)(this._cachePath))return null;let t=await(0,aU.readFile)(this._cachePath,"utf-8");return JSON.parse(t)}catch{return null}}async _saveCache(t){try{let r=(0,n$e.join)(this._cachePath,"..");(0,r$e.existsSync)(r)||await(0,aU.mkdir)(r,{recursive:!0}),await(0,aU.writeFile)(this._cachePath,JSON.stringify(t,null,2),"utf-8")}catch{}}};ne();var Kve=require("node:child_process"),N2t=require("node:util"),k2t=require("node:fs"),s$e=require("node:path");qT();qT();ne();var lU=require("node:fs/promises"),o$e=require("node:path"),Hve=require("node:fs"),R2t=require("node:child_process"),M2t=require("node:util");ef();qT();var V4n=(0,M2t.promisify)(R2t.execFile),Mte=class{_rollbackPath;constructor(t){this._rollbackPath=(0,o$e.join)(t??Ra,qIt)}async createBackup(t,r){let l={previousVersion:t,upgradedFrom:t,upgradedTo:"",upgradedAt:new Date().toISOString(),installPath:r};await this._save(l)}async markUpgraded(t){let r=await this._load();r&&(r.upgradedTo=t,await this._save(r))}async isRollbackAvailable(){let t=await this._load();return t!==null&&!!t.previousVersion}async getRollbackInfo(){return this._load()}async rollback(t){let r=await this._load();if(!r||!r.previousVersion)return{success:!1,version:"",error:"\u6CA1\u6709\u53EF\u56DE\u6EDA\u7684\u7248\u672C\u4FE1\u606F"};let l=t??"npm";try{let{stdout:u,stderr:f}=await V4n(l,["install","-g",`aggroot@${r.previousVersion}`],{timeout:pge,encoding:"utf-8",shell:!0}),_=f?.trim();return _&&!_.includes("WARN")&&!_.includes("warn")?{success:!1,version:r.previousVersion,error:_}:(await this.clearRollback(),{success:!0,version:r.previousVersion})}catch(u){return{success:!1,version:r.previousVersion,error:u.message??String(u)}}}async clearRollback(){try{if((0,Hve.existsSync)(this._rollbackPath)){let{unlink:t}=await import("node:fs/promises");await t(this._rollbackPath)}}catch{}}async _load(){try{if(!(0,Hve.existsSync)(this._rollbackPath))return null;let t=await(0,lU.readFile)(this._rollbackPath,"utf-8");return JSON.parse(t)}catch{return null}}async _save(t){try{let r=(0,o$e.join)(this._rollbackPath,"..");(0,Hve.existsSync)(r)||await(0,lU.mkdir)(r,{recursive:!0}),await(0,lU.writeFile)(this._rollbackPath,JSON.stringify(t,null,2),"utf-8")}catch{}}};var $ve=(0,N2t.promisify)(Kve.execFile),Nte=class{_updateChecker;_rollbackManager;constructor(t){this._updateChecker=new Rte({dataDir:t?.dataDir}),this._rollbackManager=new Mte(t?.dataDir)}get updateChecker(){return this._updateChecker}get rollbackManager(){return this._rollbackManager}async getInstallInfo(){let t=await this._findNpm(),r=await this._isNpmGlobalInstall(),l="";if(t)try{let{stdout:u}=await $ve(t,["root","-g"],{timeout:1e4,encoding:"utf-8",shell:!0});l=(0,s$e.join)(u.trim(),"aggroot")}catch{}return{isNpmGlobalInstall:r,installPath:l,version:vv,npmPath:t}}async upgrade(t,r,l){let u=vv;t?.({step:"checking-env",message:"\u6B63\u5728\u68C0\u67E5\u5347\u7EA7\u73AF\u5883...",percent:5});let f=r??await this.getInstallInfo();if(!f.npmPath)return{success:!1,fromVersion:u,toVersion:"",error:"\u672A\u627E\u5230 npm \u547D\u4EE4\uFF0C\u65E0\u6CD5\u6267\u884C\u5347\u7EA7\u3002\u8BF7\u786E\u4FDD npm \u5DF2\u5B89\u88C5\u5E76\u5728 PATH \u4E2D\u3002"};if(!f.isNpmGlobalInstall)return{success:!1,fromVersion:u,toVersion:"",error:"\u5F53\u524D\u975E npm \u5168\u5C40\u5B89\u88C5\uFF0C\u4E0D\u652F\u6301\u81EA\u52A8\u5347\u7EA7\u3002\u8BF7\u901A\u8FC7\u6E90\u7801\u65B9\u5F0F\u624B\u52A8\u66F4\u65B0\u3002"};t?.({step:"checking-version",message:"\u6B63\u5728\u68C0\u67E5\u6700\u65B0\u7248\u672C...",percent:15});let _=l??await this._updateChecker.checkForUpdate({force:!0});if(!_)return{success:!1,fromVersion:u,toVersion:"",error:"\u65E0\u6CD5\u83B7\u53D6\u6700\u65B0\u7248\u672C\u4FE1\u606F\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u3002"};if(!_.hasUpdate)return{success:!1,fromVersion:u,toVersion:vv,error:`\u5F53\u524D\u5DF2\u662F\u6700\u65B0\u7248\u672C (${vv})`};let y=_.latestVersion;t?.({step:"backing-up",message:"\u6B63\u5728\u5907\u4EFD\u56DE\u6EDA\u4FE1\u606F...",percent:25}),await this._rollbackManager.createBackup(u,f.installPath),t?.({step:"downloading",message:`\u6B63\u5728\u4E0B\u8F7D aggroot@${y}...`,percent:30});let T=await this._spawnNpmInstall(y,t);return T.success?(t?.({step:"verifying",message:"\u6B63\u5728\u9A8C\u8BC1\u5B89\u88C5...",percent:90}),await this._verifyInstallation(f.npmPath,y)?(await this._rollbackManager.markUpgraded(y),t?.({step:"done",message:"\u5347\u7EA7\u5B8C\u6210",percent:100}),{success:!0,fromVersion:u,toVersion:y}):{success:!1,fromVersion:u,toVersion:y,error:"\u5B89\u88C5\u9A8C\u8BC1\u5931\u8D25\uFF0C\u65B0\u7248\u672C\u53EF\u80FD\u672A\u6B63\u786E\u5B89\u88C5\u3002\u8BF7\u624B\u52A8\u68C0\u67E5\u3002"}):{success:!1,fromVersion:u,toVersion:y,error:T.error??"npm \u5B89\u88C5\u5931\u8D25"}}async rollback(t){if(!(await this.getInstallInfo()).npmPath)return{success:!1,version:"",error:"\u672A\u627E\u5230 npm \u547D\u4EE4\uFF0C\u65E0\u6CD5\u6267\u884C\u56DE\u6EDA\u3002"};t?.({step:"installing",message:"\u6B63\u5728\u56DE\u6EDA\u5230\u4E0A\u4E00\u7248\u672C...",percent:30});let l=await this._rollbackManager.getRollbackInfo();if(!l)return{success:!1,version:"",error:"\u6CA1\u6709\u53EF\u56DE\u6EDA\u7684\u7248\u672C\u4FE1\u606F"};let u=await this._spawnNpmInstall(l.previousVersion,t);return u.success?(await this._rollbackManager.clearRollback(),t?.({step:"done",message:"\u56DE\u6EDA\u5B8C\u6210",percent:100}),{success:!0,version:l.previousVersion}):{success:!1,version:l.previousVersion,error:u.error}}async checkForUpdate(){return this._updateChecker.checkForUpdate()}_spawnNpmInstall(t,r){return new Promise(l=>{let u=(0,Kve.spawn)("npm",["install","-g",`aggroot@${t}`],{shell:!0,timeout:pge}),f="";u.stdout?.on("data",_=>{let y=_.toString("utf-8");this._parseNpmProgress(y,t,r)}),u.stderr?.on("data",_=>{f+=_.toString("utf-8")}),u.on("close",_=>{if(_!==0){let T=f.split(`
|
|
44322
|
+
`.repeat(_);this.stdout.write(J)}this.savedCursorRow=Math.max(1,t-2-l-u)}applyFilter(){if(!this.filterText)this.items=[...this.allItems];else{let t=this.allItems.filter(r=>r.selectable===!1?!0:r.name.toLowerCase().includes(this.filterText)||(r.description?.toLowerCase().includes(this.filterText)??!1));this.items=t.filter((r,l)=>{if(r.selectable===!1){let u=t[l+1];return u&&u.selectable!==!1}return!0})}this.selectedIndex=this.isSelectable(0)?0:this.findNextSelectable(0,1)}render(){let t=Math.min(this.items.length,15),r=Math.max(0,Math.min(this.selectedIndex-3,this.items.length-t));this._visibleStart=r;let l=Math.min(this.items.length,r+t),u=[];this.menuHeader&&u.push(Ht.yellow.bold(this.menuHeader)),this.isFiltering&&u.push(Ht.yellow(` \u641C\u7D22: ${this.filterText}_`));for(let L=r;L<l;L++){let J=this.items[L],V=L===this.selectedIndex,K=V?"\u25B6":" ",ye=this.stripAnsi(J.name);if(J.selectable===!1){u.push(Ht.gray.dim(` ${ye}`));continue}let he=V?Ht.cyan.bold(ye):Ht.gray(ye);if(J.description){let Ae=V?Ht.cyan.dim(` \u2014 ${J.description}`):Ht.gray.dim(` \u2014 ${J.description}`);he+=Ae}u.push(` ${K} ${he}`)}let f=this.prefix==="@",_=this.isFiltering?f?"\u8F93\u5165\u7B5B\u9009 \u2191\u2193 \u2190\u2192 Enter Esc":"\u8F93\u5165\u7B5B\u9009 \u2191\u2193 Enter Esc":f?"\u2191\u2193 \u2190\u2192 Enter Esc":"\u2191\u2193 Enter Esc";u.push(Ht.gray(` ${_}`));let y="";y+="\x1B[?25l";let T=process.stdout.rows||24;this.menuStartRow=Math.max(1,this.savedCursorRow);let I=this.menuLines;for(let L=0;L<I;L++){let J=this.menuStartRow+L;J>0&&(y+=`\x1B[${J};1H`,y+="\x1B[2K")}let P=process.stdout.columns||80;for(let L=0;L<u.length;L++){let J=this.menuStartRow+L;y+=`\x1B[${J};1H`,y+="\x1B[2K",y+=this.truncateToWidth(u[L],P)}if(this.menuLines=Math.max(this.menuLines,u.length),this.getStatusBar){let L=this.menuStartRow+this.menuLines;for(let J=L;J<T;J++)J>0&&(y+=`\x1B[${J};1H`,y+="\x1B[2K");y+=`\x1B[${T};1H`,y+="\x1B[2K",y+=this.truncateToWidth(this.getStatusBar(),P)}let O=this.selectedIndex-this._visibleStart;if(O>=0&&O<u.length){let L=this.menuStartRow+(this.menuHeader?1:0)+O;y+=`\x1B[${L};1H`}y+="\x1B[?25h",this.stdout.write(y)}stripAnsi(t){return t.replace(/\x1b\[[0-9;]*m/g,"")}truncateToWidth(t,r){let l=t.split(/(\x1b\[[0-9;]*m)/),u=0,f="";for(let _ of l)if(_.startsWith("\x1B["))f+=_;else for(let y of _){let T=zk(y);if(u+T>r)return f;u+=T,f+=y}return f}cleanup(){this.isActive=!1,this.menuHeader="",this.menuResolve=null,this.filterText="",this.isFiltering=!1,this.stdout.write("\x1B[?25l");let t=this.menuStartRow>0?this.menuStartRow:this.savedCursorRow,r=process.stdout.rows||24;for(let l=t;l<=r;l++)this.stdout.write(`\x1B[${l};1H\x1B[2K`);this.stdout.write("\x1B[?25h"),this.menuLines=0,this.dispatcher?this.dispatcher.unregister(this.menuContextName):this.dataHandler&&(this.stdin.removeListener("data",this.dataHandler),this.dataHandler=null)}get active(){return this.isActive}};ne();var Wve=class{contexts=[];register(t){this.contexts.push(t),this.contexts.sort((r,l)=>l.priority-r.priority)}unregister(t){this.contexts=this.contexts.filter(r=>r.name!==t)}dispatch(t){for(let r of this.contexts)if(r.isActive()&&r.handle(t))return!0;return!1}getActiveContexts(){return this.contexts.filter(t=>t.isActive()).map(t=>t.name)}};ne();var Bve=class{getCommandRegistry;getAgents;suggestion=null;constructor(t,r){this.getCommandRegistry=t,this.getAgents=r}updateSuggestions(t,r){if(this.suggestion=null,!t||t.length===0)return;let l=[...t];if(r===l.length){if(t.startsWith("/")&&t.length>1&&!t.includes(" ")){let u=this.getCommandRegistry();if(u){let f=u.getCommands(),_=t.toLowerCase(),y=f.find(T=>T.name.toLowerCase().startsWith(_)&&T.name.toLowerCase()!==_);if(y){let T=y.name.slice(t.length);this.suggestion={text:T,fullReplacement:y.name,source:"command"}}}return}if(t.startsWith("#")&&t.length>1&&!t.includes(" ")){let u=this.getAgents(),f=t.toLowerCase(),_=u.find(y=>`#${y.toLowerCase()}`.startsWith(f)&&`#${y.toLowerCase()}`!==f);if(_){let y=`#${_}`,T=y.slice(t.length);this.suggestion={text:T,fullReplacement:y,source:"agent"}}return}}}getSuggestion(){return this.suggestion}clear(){this.suggestion=null}accept(){if(!this.suggestion)return null;let t=this.suggestion.fullReplacement;return this.suggestion=null,t}};cB();var oYe=require("node:path"),q5t=require("node:fs");ne();var zve=require("node:fs"),e$e=require("node:path"),t$e=require("node:fs"),Gve=class{filePath;heartbeatTimer=null;constructor(t){this.filePath=(0,e$e.join)(t,"instances.json")}async register(t){let l=(await this.loadAll()).filter(u=>u.pid!==t.pid);l.push(t),await this.saveAll(l)}async unregister(t){let l=(await this.loadAll()).filter(u=>u.id!==t);await this.saveAll(l)}async updateHeartbeat(t){let r=await this.loadAll(),l=r.find(u=>u.id===t);l&&(l.lastHeartbeat=Date.now(),await this.saveAll(r))}startHeartbeat(t,r=3e4){this.stopHeartbeat(),this.heartbeatTimer=setInterval(async()=>{try{await this.updateHeartbeat(t)}catch{}},r)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}async listInstances(){return this.loadAll()}async listResumable(){return(await this.loadAll()).filter(r=>r.sessionId).sort((r,l)=>l.lastHeartbeat-r.lastHeartbeat)}isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}async cleanup(t=10080*60*1e3){let r=await this.loadAll(),l=Date.now(),u=r.filter(_=>this.isProcessAlive(_.pid)?!0:l-_.lastHeartbeat<t),f=r.length-u.length;return f>0&&await this.saveAll(u),f}async loadAll(){if(!(0,t$e.existsSync)(this.filePath))return[];try{let t=await zve.promises.readFile(this.filePath,"utf-8");return JSON.parse(t).instances??[]}catch{return[]}}async saveAll(t){let r=(0,e$e.join)(this.filePath,"..");(0,t$e.existsSync)(r)||await zve.promises.mkdir(r,{recursive:!0}),await zve.promises.writeFile(this.filePath,JSON.stringify({version:1,instances:t},null,2),"utf-8")}};ne();var kF=bs(require("node:path"),1),D2t=bs(require("node:crypto"),1),Ev=require("node:fs");zd();var F4n=Ma("file-history-store"),jve=class{_baseDir;constructor(t){this._baseDir=t}async recordChange(t,r,l,u="unknown"){let f=this.getSessionDir(t);this.ensureDir(f);let _=this.hashContent(l),y=await this.loadIndex(t),T=y.filter(V=>V.filePath===r),P=(T.length>0?Math.max(...T.map(V=>V.version)):0)+1,O=`${_}@v${P}`,L=kF.join(f,O);(0,Ev.writeFileSync)(L,l,"utf-8");let J={version:P,filePath:r,contentHash:_,timestamp:Date.now(),source:u,sessionId:t};return y.push(J),await this.saveIndex(t,y),F4n.debug(`Recorded file change: ${r} v${P} (source: ${u})`),P}async undo(t,r){let l=await this.loadIndex(t);if(l.length===0)return[];let u=[];if(r){let f=await this.undoFile(t,r,l);f&&u.push(f)}else{let _=Math.max(...l.map(I=>I.timestamp))-2e3,y=l.filter(I=>I.timestamp>=_),T=[...new Set(y.map(I=>I.filePath))];for(let I of T){let P=await this.undoFile(t,I,l);P&&u.push(P)}}return u}async undoFile(t,r,l){let u=l.filter(P=>P.filePath===r).sort((P,O)=>O.version-P.version);if(u.length===0)return null;let f=u[0],_=this.getSessionDir(t),y=`${f.contentHash}@v${f.version}`,T=kF.join(_,y);if(u.length>1){let P=u[1],O=`${P.contentHash}@v${P.version}`,L=kF.join(_,O);try{let J=(0,Ev.readFileSync)(L,"utf-8");(0,Ev.writeFileSync)(r,J,"utf-8")}catch{return{success:!1,filePath:r,restoredVersion:f.version-1,error:"Failed to read previous version"}}}else try{let{unlink:P}=await import("node:fs/promises");await P(r)}catch{}let I=l.filter(P=>!(P.filePath===r&&P.version===f.version));await this.saveIndex(t,I);try{let{unlink:P}=await import("node:fs/promises");await P(T)}catch{}return{success:!0,filePath:r,restoredVersion:f.version-1}}async getFileHistory(t,r){return(await this.loadIndex(t)).filter(u=>u.filePath===r).sort((u,f)=>u.version-f.version)}async getSessionHistory(t){return(await this.loadIndex(t)).sort((l,u)=>l.timestamp-u.timestamp)}async cleanup(t){let r=this.getSessionDir(t);try{let{rm:l}=await import("node:fs/promises");await l(r,{recursive:!0,force:!0})}catch{}}async cleanupOldSessions(t=10080*60*1e3){let r=kF.join(this._baseDir,"file-history");if(!(0,Ev.existsSync)(r))return 0;let l=Date.now(),u=0;try{let f=(0,Ev.readdirSync)(r);for(let _ of f){let y=kF.join(r,_);try{let T=(0,Ev.statSync)(y);if(T.isDirectory()&&l-T.mtimeMs>t){let{rm:I}=await import("node:fs/promises");await I(y,{recursive:!0,force:!0}),u++}}catch{}}}catch{}return u}getSessionDir(t){return kF.join(this._baseDir,"file-history",t)}ensureDir(t){(0,Ev.existsSync)(t)||(0,Ev.mkdirSync)(t,{recursive:!0})}hashContent(t){return D2t.createHash("sha256").update(t).digest("hex").slice(0,12)}getIndexFilePath(t){return kF.join(this.getSessionDir(t),"_index.json")}async loadIndex(t){let r=this.getIndexFilePath(t);if(!(0,Ev.existsSync)(r))return[];try{let l=(0,Ev.readFileSync)(r,"utf-8");return JSON.parse(l)}catch{return[]}}async saveIndex(t,r){let l=this.getIndexFilePath(t),u=this.getSessionDir(t);this.ensureDir(u);let f=l+".tmp";(0,Ev.writeFileSync)(f,JSON.stringify(r,null,2),"utf-8");try{let{rename:_}=await import("node:fs/promises");await _(f,l)}catch{(0,Ev.writeFileSync)(l,JSON.stringify(r,null,2),"utf-8")}}};var GAe=require("node:fs"),J5t=bs(require("node:readline"),1);ef();ne();var fB=require("fs/promises"),Dte=require("path");Gx();zd();ef();var Vve=Ma("settings-loader"),Uve="settings.json",LF;(function(o){o[o.Enterprise=0]="Enterprise",o[o.User=1]="User",o[o.Project=2]="Project"})(LF||(LF={}));function W4n(){return process.platform==="win32"?(0,Dte.join)(process.env.ProgramData??"C:\\ProgramData","aggroot",Uve):"/etc/aggroot/settings.json"}function B4n(o){return[{path:W4n(),source:LF.Enterprise},{path:(0,Dte.join)(Ra,Uve),source:LF.User},{path:K3(o,Uve),source:LF.Project}]}async function z4n(o){try{let t=await(0,fB.readFile)(o,"utf-8"),r=JSON.parse(t);return Vve.debug({path:o},"Loaded settings file"),r}catch(t){return t.code==="ENOENT"||Vve.warn({path:o,error:String(t)},"Failed to load settings file"),null}}function G4n(o,t,r){let l={...o};return t.permissions&&(l.permissions={allow:[...l.permissions?.allow??[],...t.permissions.allow],deny:[...l.permissions?.deny??[],...t.permissions.deny],ask:[...l.permissions?.ask??[],...t.permissions.ask]}),t.hooks&&(l.hooks={...l.hooks,...t.hooks}),t.env&&(l.env={...l.env,...t.env}),t.mcp&&(l.mcp={...l.mcp,...t.mcp}),t.features&&(l.features={...l.features,...t.features}),t.preferences&&(l.preferences={...l.preferences,...t.preferences}),r===LF.Enterprise&&t.policy&&(l.policy=t.policy),t.version&&(!l.version||t.version>l.version)&&(l.version=t.version),l}function j4n(o){let t=o.policy;if(!t)return o;let r={...o};return t.allowManagedMcpServersOnly&&t.allowedMcpServers&&r.mcp?.autoConnectServers&&(r.mcp.autoConnectServers=r.mcp.autoConnectServers.filter(l=>t.allowedMcpServers.includes(l))),t.blockedTools?.length&&(r.permissions={allow:[...r.permissions?.allow??[]],deny:[...r.permissions?.deny??[],...t.blockedTools],ask:[...r.permissions?.ask??[]]}),t.requireApproval?.length&&(r.permissions={allow:[...r.permissions?.allow??[]],deny:[...r.permissions?.deny??[]],ask:[...r.permissions?.ask??[],...t.requireApproval]}),r}async function P2t(o){let t=B4n(o),r=await Promise.all(t.map(({path:u})=>z4n(u))),l={};for(let u=0;u<r.length;u++){let f=r[u];if(!f)continue;let _=t[u].source;l.policy?.disableUserOverride&&_===LF.User||l.policy?.disableProjectOverride&&_===LF.Project||(l=G4n(l,f,_))}return l=j4n(l),l}async function Pte(o){let t=(0,Dte.join)(Ra,Uve);try{let r={};try{let l=await(0,fB.readFile)(t,"utf-8");r=JSON.parse(l)}catch{}r.preferences={...r.preferences,...o},await(0,fB.mkdir)(Ra,{recursive:!0}),await(0,fB.writeFile)(t,JSON.stringify(r,null,2),"utf-8"),Vve.info({path:t,prefs:o},"User preferences saved")}catch(r){Vve.warn({error:String(r)},"Failed to save user preferences (non-fatal)")}}FQ();ne();ne();var aU=require("node:fs/promises"),n$e=require("node:path"),r$e=require("node:fs"),i$e=bs(require("node:https"),1);qT();qT();ef();var Rte=class{_cachePath;_registryBase;_checkIntervalMs;_enabled;constructor(t){this._cachePath=(0,n$e.join)(t?.dataDir??Ra,KIt),this._registryBase=t?.registryBase??"https://registry.npmjs.org",this._checkIntervalMs=t?.checkIntervalMs??$It,this._enabled=t?.enabled??!0}async checkForUpdate(t){if(!this._enabled)return null;if(!t?.force){let _=await this._loadCache();if(_&&Date.now()-new Date(_.lastCheckTime).getTime()<this._checkIntervalMs)return{hasUpdate:this._isNewer(_.latestVersion,vv),currentVersion:vv,latestVersion:_.latestVersion,checkedAt:_.lastCheckTime}}let r=await this._fetchLatestVersion();if(!r)return null;let l=this._isNewer(r,vv),u=new Date().toISOString(),f={lastCheckTime:u,latestVersion:r,currentVersionAtCheck:vv,hasUpdate:l};return await this._saveCache(f),{hasUpdate:l,currentVersion:vv,latestVersion:r,checkedAt:u}}async checkInBackground(){try{return await this.checkForUpdate()}catch{return null}}async getCachedResult(){let t=await this._loadCache();return t?{hasUpdate:this._isNewer(t.latestVersion,vv),currentVersion:vv,latestVersion:t.latestVersion,checkedAt:t.lastCheckTime}:null}_isNewer(t,r){let l=t.replace(/^v/,"").split(".").map(Number),u=r.replace(/^v/,"").split(".").map(Number);for(let f=0;f<3;f++){if((l[f]??0)>(u[f]??0))return!0;if((l[f]??0)<(u[f]??0))return!1}return!1}_fetchLatestVersion(){let t=`${this._registryBase}/aggroot/latest`;return new Promise(r=>{let l=setTimeout(()=>{u.destroy(),r(null)},hje),u=i$e.default.get(t,f=>{if(f.statusCode===301||f.statusCode===302){let y=f.headers.location;if(y){clearTimeout(l),r(this._fetchFromUrl(y));return}}if(f.statusCode!==200){clearTimeout(l),f.resume(),r(null);return}let _="";f.on("data",y=>{_+=y.toString()}),f.on("end",()=>{clearTimeout(l);try{let y=JSON.parse(_);r(y.version??null)}catch{r(null)}}),f.on("error",()=>{clearTimeout(l),r(null)})});u.on("error",()=>{clearTimeout(l),r(null)})})}_fetchFromUrl(t){return new Promise(r=>{let l=setTimeout(()=>{u.destroy(),r(null)},hje),u=i$e.default.get(t,f=>{if(f.statusCode!==200){clearTimeout(l),f.resume(),r(null);return}let _="";f.on("data",y=>{_+=y.toString()}),f.on("end",()=>{clearTimeout(l);try{let y=JSON.parse(_);r(y.version??null)}catch{r(null)}})});u.on("error",()=>{clearTimeout(l),r(null)})})}async _loadCache(){try{if(!(0,r$e.existsSync)(this._cachePath))return null;let t=await(0,aU.readFile)(this._cachePath,"utf-8");return JSON.parse(t)}catch{return null}}async _saveCache(t){try{let r=(0,n$e.join)(this._cachePath,"..");(0,r$e.existsSync)(r)||await(0,aU.mkdir)(r,{recursive:!0}),await(0,aU.writeFile)(this._cachePath,JSON.stringify(t,null,2),"utf-8")}catch{}}};ne();var Kve=require("node:child_process"),N2t=require("node:util"),k2t=require("node:fs"),s$e=require("node:path");qT();qT();ne();var lU=require("node:fs/promises"),o$e=require("node:path"),Hve=require("node:fs"),R2t=require("node:child_process"),M2t=require("node:util");ef();qT();var V4n=(0,M2t.promisify)(R2t.execFile),Mte=class{_rollbackPath;constructor(t){this._rollbackPath=(0,o$e.join)(t??Ra,qIt)}async createBackup(t,r){let l={previousVersion:t,upgradedFrom:t,upgradedTo:"",upgradedAt:new Date().toISOString(),installPath:r};await this._save(l)}async markUpgraded(t){let r=await this._load();r&&(r.upgradedTo=t,await this._save(r))}async isRollbackAvailable(){let t=await this._load();return t!==null&&!!t.previousVersion}async getRollbackInfo(){return this._load()}async rollback(t){let r=await this._load();if(!r||!r.previousVersion)return{success:!1,version:"",error:"\u6CA1\u6709\u53EF\u56DE\u6EDA\u7684\u7248\u672C\u4FE1\u606F"};let l=t??"npm";try{let{stdout:u,stderr:f}=await V4n(l,["install","-g",`aggroot@${r.previousVersion}`],{timeout:pge,encoding:"utf-8",shell:!0}),_=f?.trim();return _&&!_.includes("WARN")&&!_.includes("warn")?{success:!1,version:r.previousVersion,error:_}:(await this.clearRollback(),{success:!0,version:r.previousVersion})}catch(u){return{success:!1,version:r.previousVersion,error:u.message??String(u)}}}async clearRollback(){try{if((0,Hve.existsSync)(this._rollbackPath)){let{unlink:t}=await import("node:fs/promises");await t(this._rollbackPath)}}catch{}}async _load(){try{if(!(0,Hve.existsSync)(this._rollbackPath))return null;let t=await(0,lU.readFile)(this._rollbackPath,"utf-8");return JSON.parse(t)}catch{return null}}async _save(t){try{let r=(0,o$e.join)(this._rollbackPath,"..");(0,Hve.existsSync)(r)||await(0,lU.mkdir)(r,{recursive:!0}),await(0,lU.writeFile)(this._rollbackPath,JSON.stringify(t,null,2),"utf-8")}catch{}}};var $ve=(0,N2t.promisify)(Kve.execFile),Nte=class{_updateChecker;_rollbackManager;constructor(t){this._updateChecker=new Rte({dataDir:t?.dataDir}),this._rollbackManager=new Mte(t?.dataDir)}get updateChecker(){return this._updateChecker}get rollbackManager(){return this._rollbackManager}async getInstallInfo(){let t=await this._findNpm(),r=await this._isNpmGlobalInstall(),l="";if(t)try{let{stdout:u}=await $ve(t,["root","-g"],{timeout:1e4,encoding:"utf-8",shell:!0});l=(0,s$e.join)(u.trim(),"aggroot")}catch{}return{isNpmGlobalInstall:r,installPath:l,version:vv,npmPath:t}}async upgrade(t,r,l){let u=vv;t?.({step:"checking-env",message:"\u6B63\u5728\u68C0\u67E5\u5347\u7EA7\u73AF\u5883...",percent:5});let f=r??await this.getInstallInfo();if(!f.npmPath)return{success:!1,fromVersion:u,toVersion:"",error:"\u672A\u627E\u5230 npm \u547D\u4EE4\uFF0C\u65E0\u6CD5\u6267\u884C\u5347\u7EA7\u3002\u8BF7\u786E\u4FDD npm \u5DF2\u5B89\u88C5\u5E76\u5728 PATH \u4E2D\u3002"};if(!f.isNpmGlobalInstall)return{success:!1,fromVersion:u,toVersion:"",error:"\u5F53\u524D\u975E npm \u5168\u5C40\u5B89\u88C5\uFF0C\u4E0D\u652F\u6301\u81EA\u52A8\u5347\u7EA7\u3002\u8BF7\u901A\u8FC7\u6E90\u7801\u65B9\u5F0F\u624B\u52A8\u66F4\u65B0\u3002"};t?.({step:"checking-version",message:"\u6B63\u5728\u68C0\u67E5\u6700\u65B0\u7248\u672C...",percent:15});let _=l??await this._updateChecker.checkForUpdate({force:!0});if(!_)return{success:!1,fromVersion:u,toVersion:"",error:"\u65E0\u6CD5\u83B7\u53D6\u6700\u65B0\u7248\u672C\u4FE1\u606F\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u3002"};if(!_.hasUpdate)return{success:!1,fromVersion:u,toVersion:vv,error:`\u5F53\u524D\u5DF2\u662F\u6700\u65B0\u7248\u672C (${vv})`};let y=_.latestVersion;t?.({step:"backing-up",message:"\u6B63\u5728\u5907\u4EFD\u56DE\u6EDA\u4FE1\u606F...",percent:25}),await this._rollbackManager.createBackup(u,f.installPath),t?.({step:"downloading",message:`\u6B63\u5728\u4E0B\u8F7D aggroot@${y}...`,percent:30});let T=await this._spawnNpmInstall(y,t);return T.success?(t?.({step:"verifying",message:"\u6B63\u5728\u9A8C\u8BC1\u5B89\u88C5...",percent:90}),await this._verifyInstallation(f.npmPath,y)?(await this._rollbackManager.markUpgraded(y),t?.({step:"done",message:"\u5347\u7EA7\u5B8C\u6210",percent:100}),{success:!0,fromVersion:u,toVersion:y}):{success:!1,fromVersion:u,toVersion:y,error:"\u5B89\u88C5\u9A8C\u8BC1\u5931\u8D25\uFF0C\u65B0\u7248\u672C\u53EF\u80FD\u672A\u6B63\u786E\u5B89\u88C5\u3002\u8BF7\u624B\u52A8\u68C0\u67E5\u3002"}):{success:!1,fromVersion:u,toVersion:y,error:T.error??"npm \u5B89\u88C5\u5931\u8D25"}}async rollback(t){if(!(await this.getInstallInfo()).npmPath)return{success:!1,version:"",error:"\u672A\u627E\u5230 npm \u547D\u4EE4\uFF0C\u65E0\u6CD5\u6267\u884C\u56DE\u6EDA\u3002"};t?.({step:"installing",message:"\u6B63\u5728\u56DE\u6EDA\u5230\u4E0A\u4E00\u7248\u672C...",percent:30});let l=await this._rollbackManager.getRollbackInfo();if(!l)return{success:!1,version:"",error:"\u6CA1\u6709\u53EF\u56DE\u6EDA\u7684\u7248\u672C\u4FE1\u606F"};let u=await this._spawnNpmInstall(l.previousVersion,t);return u.success?(await this._rollbackManager.clearRollback(),t?.({step:"done",message:"\u56DE\u6EDA\u5B8C\u6210",percent:100}),{success:!0,version:l.previousVersion}):{success:!1,version:l.previousVersion,error:u.error}}async checkForUpdate(t){return this._updateChecker.checkForUpdate(t)}_spawnNpmInstall(t,r){return new Promise(l=>{let u=(0,Kve.spawn)("npm",["install","-g",`aggroot@${t}`],{shell:!0,timeout:pge}),f="";u.stdout?.on("data",_=>{let y=_.toString("utf-8");this._parseNpmProgress(y,t,r)}),u.stderr?.on("data",_=>{f+=_.toString("utf-8")}),u.on("close",_=>{if(_!==0){let T=f.split(`
|
|
44404
44323
|
`).filter(I=>I.trim()&&!I.includes("WARN")&&!I.includes("warn"));f.includes("ERR!")?l({success:!1,error:`npm \u5B89\u88C5\u5931\u8D25: ${T.join(`
|
|
44405
44324
|
`)}`}):l({success:!1,error:`npm \u5B89\u88C5\u5931\u8D25 (\u9000\u51FA\u7801: ${_})`});return}let y=f.split(`
|
|
44406
44325
|
`).filter(T=>T.trim()&&!T.includes("WARN")&&!T.includes("warn"));if(y.length>0&&f.includes("ERR!")){l({success:!1,error:`npm \u5B89\u88C5\u5931\u8D25: ${y.join(`
|