blade-code 0.10.3 → 0.10.4
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/blade.js +2 -2
- package/dist/{chunk-r4pz99sy.js → chunk-1ndryz4h.js} +1 -1
- package/dist/{chunk-xdbg7cn3.js → chunk-5t0vs4hz.js} +1 -1
- package/dist/{chunk-c05t8207.js → chunk-5ze48kg7.js} +1 -1
- package/dist/{chunk-9yytfg19.js → chunk-90fnvvcf.js} +1 -1
- package/dist/{chunk-3wp3h373.js → chunk-9kwt0w46.js} +1 -1
- package/dist/{chunk-c45y8tx1.js → chunk-a7a74pza.js} +74 -74
- package/dist/{chunk-bfw2p0x8.js → chunk-age5tc86.js} +3 -3
- package/dist/{chunk-7hqbwpt5.js → chunk-b9v7waxf.js} +1 -1
- package/dist/{chunk-bn148dr5.js → chunk-csr5vppa.js} +8 -8
- package/dist/{chunk-p5tpzh6f.js → chunk-d4zw0xxe.js} +1 -1
- package/dist/chunk-d5a66cgn.js +160 -0
- package/dist/{chunk-5fxc90rb.js → chunk-d7xb0vp1.js} +1 -1
- package/dist/{chunk-vmg5n0zv.js → chunk-f647z66n.js} +1 -1
- package/dist/{chunk-eezg6pee.js → chunk-ffp3ypbb.js} +1 -1
- package/dist/{chunk-7089z4e1.js → chunk-fx87s3mb.js} +1 -1
- package/dist/chunk-g6h6h8xr.js +1 -0
- package/dist/chunk-jbnrscvz.js +1 -0
- package/dist/{chunk-aa0ffw17.js → chunk-kkd7mm55.js} +1 -1
- package/dist/{chunk-wje6bck2.js → chunk-mxqpg4gy.js} +1 -1
- package/dist/{chunk-zq9r0jx3.js → chunk-n2s54h1r.js} +1 -1
- package/dist/{chunk-jqwntnp1.js → chunk-nr53mq0k.js} +1 -1
- package/dist/{chunk-8th744ef.js → chunk-pehpndk9.js} +1 -1
- package/dist/{chunk-s95rgkd8.js → chunk-rv80ak15.js} +1 -1
- package/dist/{chunk-1g5qc1qx.js → chunk-scq3ns6v.js} +1 -1
- package/dist/{chunk-1cx96gx1.js → chunk-tx8f345j.js} +1 -1
- package/dist/{chunk-nxj1638n.js → chunk-v8kp3ep9.js} +1 -1
- package/dist/{chunk-rcdynprn.js → chunk-ve9cke2g.js} +2 -2
- package/dist/{chunk-vwq9s5nj.js → chunk-vxymgh8e.js} +4 -4
- package/dist/{chunk-da1jvzbz.js → chunk-wdbmbk6h.js} +1 -1
- package/dist/{chunk-pnrx3spk.js → chunk-xkzy5wbm.js} +1 -1
- package/dist/{chunk-grp43mdb.js → chunk-xq8vf15n.js} +1 -1
- package/dist/chunk-ys8bp9jm.js +1 -0
- package/dist/chunk-zswrw5f9.js +3 -0
- package/dist/web/assets/{ChatView-Pqa25Vua.js → ChatView-iK7ff8qU.js} +2 -2
- package/dist/web/assets/{CodeBlockHighlighter-Dxt-FWJk.js → CodeBlockHighlighter-BoJp_Xb0.js} +1 -1
- package/dist/web/assets/{FilePreview-Dj2yppPn.js → FilePreview-Bi1HWOvY.js} +2 -2
- package/dist/web/assets/{MarkdownRenderer-BI2xpTV2.js → MarkdownRenderer-DMW1pg5N.js} +12 -12
- package/dist/web/assets/{McpModal-COw0BcHJ.js → McpModal-CHUqitJ6.js} +1 -1
- package/dist/web/assets/SettingsModal-zsS9O6SW.js +1 -0
- package/dist/web/assets/{SkillsModal-CTZTu9xg.js → SkillsModal-C2oTDXoy.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-DPXkV-qb.js → TaskSwitcher-CncVasNA.js} +1 -1
- package/dist/web/assets/{TerminalPanel-tpUxwaCh.js → TerminalPanel-CBi2mUxx.js} +1 -1
- package/dist/web/assets/index-B7etZcne.css +1 -0
- package/dist/web/assets/index-DvDtvgA4.js +32 -0
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-8thp1nep.js +0 -1
- package/dist/chunk-9p5f3ryf.js +0 -1
- package/dist/chunk-mgwny24b.js +0 -160
- package/dist/chunk-n3y9ytvg.js +0 -3
- package/dist/chunk-r4j5ca1h.js +0 -1
- package/dist/web/assets/SettingsModal-h4AxN730.js +0 -1
- package/dist/web/assets/index-Dep3eEsS.css +0 -1
- package/dist/web/assets/index-bjyn3NHs.js +0 -32
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{aa as
|
|
2
|
-
[error] ${W.message}`)}),this.processes.set(Z,Q),Q}consumeOutput($,Z){let J=this.getProcess($,Z);if(!J)return;let Y=J.pendingStdout.consume(),U=J.pendingStderr.consume();return{id:J.id,command:J.command,status:J.status,stdout:Y.content,stderr:U.content,stdoutOmittedBytes:Y.omittedBytes,stderrOmittedBytes:U.omittedBytes,exitCode:J.exitCode,signal:J.signal,pid:J.pid,startedAt:J.startTime,endedAt:J.endTime,errorMessage:J.errorMessage,sandboxed:J.sandboxed}}getProcess($,Z){let J=this.processes.get($);return J?.sessionId===Z?J:void 0}listForSession($){return Array.from(this.processes.values()).filter((Z)=>Z.sessionId===$)}async writeInput($,Z,J,Y=!1){let U=this.getProcess($,Z);if(!U)return;let X=U.process?.stdin;if(U.status!=="running"||!X||X.destroyed||X.writableEnded)return{success:!1,status:U.status,bytesWritten:0,stdinClosed:!X||X.destroyed||X.writableEnded,errorMessage:"Shell stdin is not writable"};try{return await new Promise((H,Q)=>{let W=(V)=>{X.off("error",W),Q(V)},z=(V)=>{if(X.off("error",W),V)Q(V);else H()};if(X.once("error",W),Y)X.end(J,z);else X.write(J,z)}),{success:!0,status:U.status,bytesWritten:Buffer.byteLength(J),stdinClosed:Y}}catch(H){return{success:!1,status:U.status,bytesWritten:0,stdinClosed:X.destroyed||X.writableEnded,errorMessage:H instanceof Error?H.message:"Failed to write stdin"}}}async kill($,Z){let J=this.getProcess($,Z);if(!J)return;return this.terminateProcess(J)}async killSession($){let Z=this.listForSession($);await Promise.all(Z.map((J)=>this.terminateProcess(J)));for(let J of Z)this.processes.delete(J.id)}async terminateProcess($){if($.status!=="running"||!$.process)return{success:!1,alreadyExited:!0,status:$.status,pid:$.pid,exitCode:$.exitCode,signal:$.signal};$.status="killed",$.endTime=Date.now();let Z=await $.processTree?.terminate();if(!Z?.success)return $.status="error",$.errorMessage="Failed to terminate owned process tree",{success:!1,alreadyExited:Z?.alreadyExited??!1,status:$.status,pid:$.pid,exitCode:$.exitCode,signal:$.signal};return{success:!0,alreadyExited:Z.alreadyExited,status:$.status,pid:$.pid,exitCode:$.exitCode,signal:$.signal}}async killAll(){await Promise.all(Array.from(this.processes.values()).map(($)=>this.terminateProcess($))),this.processes.clear()}}import{stat as AH}from"node:fs/promises";import{Mutex as LH}from"async-mutex";import{nanoid as NH}from"nanoid";import*as e9 from"os";import*as Y0 from"path";import*as I0 from"fs/promises";class S${async readTextFile($){return I0.readFile($,"utf-8")}async writeTextFile($,Z){await I0.writeFile($,Z,"utf-8")}async exists($){try{return await I0.access($),!0}catch{return!1}}async readBinaryFile($){return I0.readFile($)}async stat($){try{let Z=await I0.stat($);return{size:Z.size,isDirectory:Z.isDirectory(),isFile:Z.isFile(),mtime:Z.mtime}}catch{return null}}async mkdir($,Z){await I0.mkdir($,{recursive:Z?.recursive??!1,mode:Z?.mode??493})}}var j3=new S$;function O$(){return j3}var F0=u("Agent");class K1{connection;sessionId;capabilities;fallback;constructor($,Z,J,Y=new S$){this.connection=$;this.sessionId=Z;this.capabilities=J;this.fallback=Y}async readTextFile($){if(!this.capabilities.readTextFile)return F0.debug(`[AcpFileSystem] readTextFile fallback: ${$}`),this.fallback.readTextFile($);try{return F0.debug(`[AcpFileSystem] readTextFile via ACP: ${$}`),(await this.connection.readTextFile({path:$,sessionId:this.sessionId})).content}catch(Z){throw F0.warn(`[AcpFileSystem] readTextFile ACP failed: ${Z}`),Z}}async writeTextFile($,Z){if(!this.capabilities.writeTextFile)return F0.debug(`[AcpFileSystem] writeTextFile fallback: ${$}`),this.fallback.writeTextFile($,Z);try{F0.debug(`[AcpFileSystem] writeTextFile via ACP: ${$}`),await this.connection.writeTextFile({path:$,content:Z,sessionId:this.sessionId})}catch(J){throw F0.warn(`[AcpFileSystem] writeTextFile ACP failed: ${J}`),J}}async exists($){if(!this.capabilities.readTextFile)return F0.debug(`[AcpFileSystem] exists fallback to local: ${$}`),this.fallback.exists($);try{return await this.connection.readTextFile({path:$,sessionId:this.sessionId}),F0.debug(`[AcpFileSystem] exists(${$}): true (ACP read success)`),!0}catch(Z){let J=String(Z).toLowerCase();if(["not found","no such file","enoent","does not exist","file not found","path not found"].some((H)=>J.includes(H)))return F0.debug(`[AcpFileSystem] exists(${$}): false (ACP: not found)`),!1;let X=T3(J);return F0.warn(`[AcpFileSystem] exists(${$}): assuming exists due to ${X} error`,{error:String(Z),errorType:X,filePath:$}),!0}}async readBinaryFile($){return F0.debug(`[AcpFileSystem] readBinaryFile fallback: ${$}`),this.fallback.readBinaryFile($)}async stat($){return F0.debug(`[AcpFileSystem] stat fallback: ${$}`),this.fallback.stat($)}async mkdir($,Z){return F0.debug(`[AcpFileSystem] mkdir fallback: ${$}`),this.fallback.mkdir($,Z)}getCapabilities(){return this.capabilities}canReadTextFile(){return this.capabilities.readTextFile??!1}canWriteTextFile(){return this.capabilities.writeTextFile??!1}usesRemoteFiles(){return this.canReadTextFile()||this.canWriteTextFile()}}function T3($){if($.includes("permission")||$.includes("access denied"))return"permission";if($.includes("timeout")||$.includes("timed out"))return"timeout";if($.includes("binary")||$.includes("encoding"))return"binary";if($.includes("too large")||$.includes("size"))return"size";if($.includes("connection")||$.includes("network"))return"network";return"unknown"}var c0=u("Agent");class e2{async execute($,Z){return new Promise((J)=>{let Y=process.platform==="win32"?"cmd.exe":"/bin/bash",U=process.platform==="win32"?["/c",$]:["-c",$],{child:X,processTree:H}=p0(Y,U,{cwd:Z?.cwd||N(),env:{...process.env,...Z?.env},stdio:["pipe","pipe","pipe"]}),Q,W=()=>{return Q??=H.terminate(),Q},z="",V="",B=!1,K=Z?.timeout?setTimeout(()=>{B=!0,W()},Z.timeout):null,G=null,O=()=>{if(K)clearTimeout(K);if(G&&Z?.signal)Z.signal.removeEventListener("abort",G),G=null};if(Z?.signal){if(G=()=>{B=!0,W()},Z.signal.addEventListener("abort",G),Z.signal.aborted)G()}X.stdout?.on("data",(E)=>{let q=E.toString();z+=q,Z?.onOutput?.(q)}),X.stderr?.on("data",(E)=>{let q=E.toString();V+=q,Z?.onOutput?.(q)}),X.on("close",async(E)=>{if(O(),B)await W();J({success:E===0&&!B,stdout:z,stderr:V,exitCode:E,error:B?"Command was terminated":void 0})}),X.on("error",(E)=>{O(),J({success:!1,stdout:z,stderr:V,exitCode:null,error:E.message})})})}isAvailable(){return!0}}class z4{connection;sessionId;fallback;constructor($,Z,J=new e2){this.connection=$;this.sessionId=Z;this.fallback=J}async execute($,Z){try{c0.debug(`[AcpTerminal] Executing command via ACP: ${$}`);let J=await this.connection.createTerminal({sessionId:this.sessionId,command:$,cwd:Z?.cwd,env:Z?.env?Object.entries(Z.env).map(([z,V])=>({name:z,value:V})):void 0}),Y=0,U=null;if(Z?.onOutput)U=setInterval(async()=>{try{let V=(await J.currentOutput()).output||"";if(V.length>Y){let B=V.slice(Y);Y=V.length,Z.onOutput?.(B)}}catch{}},100);let X=(z=!1)=>{if(U)clearInterval(U),U=null;(z?J.kill().then(()=>c0.debug("[AcpTerminal] Killed remote command")).catch(()=>{}).then(()=>J.release()).catch(()=>{}):J.release().catch(()=>{})).catch(()=>{})},H=[];if(H.push(J.waitForExit().then((z)=>({type:"completed",exitCode:z.exitCode??null}))),Z?.timeout)H.push(new Promise((z)=>{setTimeout(()=>z({type:"timeout"}),Z.timeout)}));if(Z?.signal)H.push(new Promise((z)=>{if(Z.signal.aborted)z({type:"aborted"});else Z.signal.addEventListener("abort",()=>z({type:"aborted"}),{once:!0})}));let Q=await Promise.race(H),W="";try{if(W=(await J.currentOutput()).output||"",Z?.onOutput&&W.length>Y)Z.onOutput(W.slice(Y))}catch{}switch(Q.type){case"completed":return X(!1),{success:Q.exitCode===0,stdout:W,stderr:"",exitCode:Q.exitCode};case"timeout":return c0.debug(`[AcpTerminal] Command timed out, killing: ${$}`),X(!0),{success:!1,stdout:W,stderr:"",exitCode:null,error:"Command timed out"};case"aborted":return c0.debug(`[AcpTerminal] Command aborted, killing: ${$}`),X(!0),{success:!1,stdout:W,stderr:"",exitCode:null,error:"Command was aborted"}}}catch(J){if(Z?.allowLocalFallback===!1)return{success:!1,stdout:"",stderr:"",exitCode:null,error:J instanceof Error?`ACP terminal unavailable: ${J.message}`:"ACP terminal unavailable"};return c0.warn("[AcpTerminal] ACP terminal failed, using fallback:",J),this.fallback.execute($,Z)}}isAvailable(){return!0}}class I{static sessions=new Map;static currentSessionId=null;constructor(){}static getInstance(){return new I}static initializeSession($,Z,J,Y){let U=J?.fs?new K1($,Z,J.fs):new S$;if(J?.fs)c0.debug(`[AcpServiceContext:${Z}] Using ACP file system service`);let X=new z4($,Z);c0.debug(`[AcpServiceContext:${Z}] Using ACP terminal service`),I.sessions.set(Z,{fileSystemService:U,terminalService:X,connection:$,clientCapabilities:J||null,cwd:Y}),I.currentSessionId=Z,c0.debug(`[AcpServiceContext:${Z}] Initialized with capabilities:`,{fs:!!J?.fs,readTextFile:J?.fs?.readTextFile,writeTextFile:J?.fs?.writeTextFile,cwd:Y})}static destroySession($){if(I.sessions.delete($),I.currentSessionId===$){let Z=Array.from(I.sessions.keys());I.currentSessionId=Z[0]||null}c0.debug(`[AcpServiceContext:${$}] Session destroyed`)}static getSessionServices($){return I.sessions.get($)||null}static setCurrentSession($){if(I.sessions.has($))I.currentSessionId=$}static getCurrentSessionId(){return I.currentSessionId}initialize($,Z,J,Y){I.initializeSession($,Z,J,Y||N())}reset(){if(I.currentSessionId)I.destroySession(I.currentSessionId)}isAcpMode(){return I.currentSessionId!==null}getFileSystemService($){let Z=$??I.currentSessionId;if(Z){let J=I.sessions.get(Z);if(J)return J.fileSystemService}return new S$}getTerminalService($){let Z=$??I.currentSessionId;if(Z){let J=I.sessions.get(Z);if(J)return J.terminalService}return new e2}getConnection(){if(I.currentSessionId){let $=I.sessions.get(I.currentSessionId);if($)return $.connection}return null}getSessionId(){return I.currentSessionId}getClientCapabilities(){if(I.currentSessionId){let $=I.sessions.get(I.currentSessionId);if($)return $.clientCapabilities}return null}async sendToolUpdate($,Z,J,Y,U){let X=I.currentSessionId;if(!X)return;let H=I.sessions.get(X);if(!H)return;try{await H.connection.sessionUpdate({sessionId:X,update:{sessionUpdate:"tool_call",toolCallId:$,status:Z,title:J,content:Y||[],kind:U||"other"}})}catch(Q){c0.warn("[AcpServiceContext] Failed to send tool update:",Q)}}}function E$($){return I.getInstance().getFileSystemService($)}function V4($){return I.getInstance().getTerminalService($)}function a($){return $?I.getSessionServices($)!==null:I.getInstance().isAcpMode()}import*as i0 from"node:fs/promises";import*as F4 from"node:path";import{Mutex as M3}from"async-mutex";import{nanoid as C3}from"nanoid";import f3 from"write-file-atomic";var B4=["active","paused","blocked","usage_limited","budget_limited","complete"];var K4=1048576,$5=1e5,_4=_.Object({version:_.Literal(1),sessionId:_.String({minLength:1}),goalId:_.String({minLength:1}),objective:_.String({minLength:1,maxLength:$5}),status:d(B4),tokenBudget:_.Optional(_.Integer({minimum:1})),tokensUsed:_.Integer({minimum:0}),timeUsedSeconds:_.Integer({minimum:0}),continuationCount:_.Integer({minimum:0}),statusReason:_.Optional(_.String()),createdAt:_.String({format:"date-time"}),updatedAt:_.String({format:"date-time"})});function G4($,Z){return $ instanceof Error&&"code"in $&&$.code===Z}function O4($){let Z=$.trim();if(!Z)throw Error("Goal objective must not be empty");if(Z.length>$5)throw Error(`Goal objective exceeds ${$5} characters`);return Z}function R3($){if($===void 0)return;if(!Number.isInteger($)||$<=0)throw Error("Goal token budget must be a positive integer");return $}class j0{workspaceRoot;sessionId;static mutexes=new Map;static listeners=new Set;filePath;mutex;constructor($,Z){this.workspaceRoot=$;this.sessionId=Z;this.filePath=E4($,Z);let J=j0.mutexes.get(this.filePath);if(!J)J=new M3,j0.mutexes.set(this.filePath,J);this.mutex=J}static subscribe($){return this.listeners.add($),()=>this.listeners.delete($)}static async hasActiveGoal($,Z){return(await new j0($,Z).get())?.status==="active"}async get(){return this.mutex.runExclusive(()=>this.readUnlocked())}async create($){return this.mutex.runExclusive(async()=>{let Z=await this.readUnlocked();if(Z&&Z.status!=="complete")throw Error(`Session already has an unfinished goal (${Z.status}); clear or complete it first`);let J=new Date().toISOString(),Y=R3($.tokenBudget),U={version:1,sessionId:this.sessionId,goalId:C3(12),objective:O4($.objective),status:"active",...Y===void 0?{}:{tokenBudget:Y},tokensUsed:0,timeUsedSeconds:0,continuationCount:0,createdAt:J,updatedAt:J};return await this.persistUnlocked(U),this.emit(U),U})}async edit($){return this.updateExisting((Z)=>{if(!["active","paused","blocked"].includes(Z.status))throw Error(`Cannot edit goal while status is ${Z.status}`);return{...Z,objective:O4($),updatedAt:new Date().toISOString()}})}async pause($="paused by user"){return this.updateExisting((Z)=>{if(Z.status!=="active"&&Z.status!=="blocked")throw Error(`Cannot pause goal while status is ${Z.status}`);return{...Z,status:"paused",statusReason:$,updatedAt:new Date().toISOString()}})}async pauseIfActive($){return this.mutex.runExclusive(async()=>{let Z=await this.readUnlocked();if(!Z||Z.status!=="active")return Z;let J={...Z,status:"paused",statusReason:$,updatedAt:new Date().toISOString()};return await this.persistUnlocked(J),this.emit(J),J})}async resume(){return this.updateExisting(($)=>{if($.status!=="paused"&&$.status!=="blocked")throw Error(`Cannot resume goal while status is ${$.status}`);return{...$,status:"active",statusReason:void 0,updatedAt:new Date().toISOString()}})}async complete(){return this.updateExisting(($)=>{if(!["active","paused","blocked"].includes($.status))throw Error(`Cannot complete goal while status is ${$.status}`);return{...$,status:"complete",statusReason:void 0,updatedAt:new Date().toISOString()}})}async block($){return this.updateExisting((Z)=>{if(Z.status!=="active")throw Error(`Cannot block goal while status is ${Z.status}`);let J=$.trim();if(!J)throw Error("Blocked goal requires a reason");return{...Z,status:"blocked",statusReason:J,updatedAt:new Date().toISOString()}})}async recordProgress($){return this.mutex.runExclusive(async()=>{let Z=await this.readUnlocked();if(!Z||Z.status!=="active")return Z;let J=Math.max(0,Math.round($.tokens)),Y=Math.max(0,Math.round($.elapsedMs/1000)),U=Z.tokensUsed+J,X=Z.tokenBudget!==void 0&&U>=Z.tokenBudget,H={...Z,tokensUsed:U,timeUsedSeconds:Z.timeUsedSeconds+Y,status:X?"budget_limited":Z.status,statusReason:X?"token budget exhausted":Z.statusReason,updatedAt:new Date().toISOString()};return await this.persistUnlocked(H),this.emit(H),H})}async beginContinuation(){return this.updateExisting(($)=>{if($.status!=="active")throw Error(`Cannot continue goal while status is ${$.status}`);return{...$,continuationCount:$.continuationCount+1,updatedAt:new Date().toISOString()}})}async tryBeginContinuation(){return this.mutex.runExclusive(async()=>{let $=await this.readUnlocked();if(!$||$.status!=="active")return null;let Z={...$,continuationCount:$.continuationCount+1,updatedAt:new Date().toISOString()};return await this.persistUnlocked(Z),this.emit(Z),Z})}async clear(){return this.mutex.runExclusive(async()=>{try{await i0.unlink(this.filePath)}catch($){if(G4($,"ENOENT"))return!1;throw $}return this.emit(null),!0})}async updateExisting($){return this.mutex.runExclusive(async()=>{let Z=await this.readUnlocked();if(!Z)throw Error("Session has no goal");let J=q4(_4,$(Z));return await this.persistUnlocked(J),this.emit(J),J})}async readUnlocked(){try{if((await i0.stat(this.filePath)).size>K4)throw Error(`Goal state exceeds ${K4} bytes`);await i0.chmod(this.filePath,384);let Z=m1(_4,JSON.parse(await i0.readFile(this.filePath,"utf8")));if(!Z.success||Z.data.sessionId!==this.sessionId)throw Error(`Invalid goal state: ${this.filePath}`);return Z.data}catch($){if(G4($,"ENOENT"))return null;if($ instanceof SyntaxError)throw Error(`Invalid goal state JSON: ${this.filePath}`,{cause:$});throw $}}async persistUnlocked($){await i0.mkdir(F4.dirname(this.filePath),{recursive:!0,mode:448}),await f3(this.filePath,`${JSON.stringify($)}
|
|
3
|
-
`,{encoding:"utf8",mode:384,fsync:!0})}emit($){let Z={workspaceRoot:this.workspaceRoot,sessionId:this.sessionId,goal:$?{...$}:null};for(let J of j0.listeners)try{J(Z)}catch{}}}import{createHash as S3}from"node:crypto";import{promises as g1,realpathSync as P3}from"node:fs";import i from"node:path";import{fileURLToPath as k3,pathToFileURL as Y$}from"node:url";var D4=u("Service"),w4=65536;class Z5{name;onCrash;child;processTree;connection;closePromise;crashCleanup;capabilities;initialized=!1;stopping=!1;notificationHandlers=new Map;requestHandlers=new Map;constructor($,Z){this.name=$;this.onCrash=Z}get serverCapabilities(){return this.capabilities}get isInitialized(){return this.initialized}async start($){if(await this.crashCleanup,this.crashCleanup=void 0,this.connection)return;let Z=await import("vscode-jsonrpc/node.js"),{child:J,processTree:Y}=p0($.command,[...$.args],{cwd:$.cwd,env:{...$.environment,PATH:$.environment.PATH??process.env.PATH??"",HOME:$.environment.HOME??process.env.HOME??"",USER:$.environment.USER??process.env.USER??"",SHELL:$.environment.SHELL??process.env.SHELL??"/bin/sh",BLADE_CLI:"1"},stdio:["pipe","pipe","pipe"]},{releaseOnExit:!1});this.child=J,this.processTree=Y;try{if(await new Promise((H,Q)=>{let W=()=>{J.removeListener("spawn",z),J.removeListener("error",V)},z=()=>{W(),H()},V=(B)=>{W(),Q(B)};J.once("spawn",z),J.once("error",V)}),!J.stdout||!J.stdin)throw Error("LSP server stdio is unavailable");let U="";J.stderr?.setEncoding("utf8"),J.stderr?.on("data",(H)=>{if(U.length<w4)U+=H.slice(0,w4-U.length)}),J.stdin.on("error",(H)=>{if(!this.stopping)D4.debug(`[LSP ${this.name}] stdin closed: ${H.message}`)}),this.closePromise=new Promise((H)=>{J.once("close",(Q,W)=>{this.initialized=!1;let z=!this.stopping;if(!this.stopping){let V=U.trim()?`: ${U.trim().slice(0,512)}`:W?` (${W})`:"";this.onCrash(Error(`LSP server "${this.name}" exited with code ${Q}${V}`))}if(this.child===J){let V=this.processTree;try{this.connection?.dispose()}catch{}if(this.connection=void 0,this.child=void 0,this.closePromise=void 0,z&&V)this.crashCleanup=V.terminate().then(()=>{return}),this.processTree=void 0}H()})});let X=Z.createMessageConnection(new Z.StreamMessageReader(J.stdout),new Z.StreamMessageWriter(J.stdin));this.connection=X,X.onError(([H])=>{if(!this.stopping)D4.warn(`[LSP ${this.name}] connection error: ${H.message}`)}),X.onClose(()=>{this.initialized=!1});for(let[H,Q]of this.notificationHandlers)for(let W of Q)X.onNotification(H,W);for(let[H,Q]of this.requestHandlers)X.onRequest(H,Q);X.listen()}catch(U){throw await this.disposeTransport(),U}}async initialize($,Z,J){let Y=await this.request("initialize",$,Z,J,!1);return this.capabilities=Y.capabilities,await this.notify("initialized",{}),this.initialized=!0,Y}async request($,Z,J,Y,U=!0){let X=this.connection;if(!X)throw Error(`LSP server "${this.name}" is not started`);if(U&&!this.initialized)throw Error(`LSP server "${this.name}" is not initialized`);let Q=new(await import("vscode-jsonrpc/node.js")).CancellationTokenSource;return this.awaitRequest(X.sendRequest($,Z,Q.token),Q,J,Y,$)}async notify($,Z){if(!this.connection)throw Error(`LSP server "${this.name}" is not started`);await this.connection.sendNotification($,Z)}onNotification($,Z){let J=this.notificationHandlers.get($)??[];J.push(Z),this.notificationHandlers.set($,J),this.connection?.onNotification($,Z)}onRequest($,Z){this.requestHandlers.set($,Z),this.connection?.onRequest($,Z)}async stop($){if(!this.child&&!this.connection){await this.crashCleanup,this.crashCleanup=void 0;return}this.stopping=!0;let Z=this.connection;try{if(Z&&this.initialized){let Y=new(await import("vscode-jsonrpc/node.js")).CancellationTokenSource;await this.awaitRequest(Z.sendRequest("shutdown",Y.token),Y,$,void 0,"shutdown").catch(()=>{return}),await Z.sendNotification("exit").catch(()=>{return})}await Promise.race([this.closePromise??Promise.resolve(),new Promise((J)=>setTimeout(J,Math.min($,500)))])}finally{await this.disposeTransport(),this.stopping=!1,this.initialized=!1,this.capabilities=void 0}}awaitRequest($,Z,J,Y,U){return new Promise((X,H)=>{let Q=!1,W=(B)=>{if(Q)return;Q=!0,clearTimeout(V),Y?.removeEventListener("abort",z),B()},z=()=>{Z.cancel(),W(()=>H(Error(`LSP request "${U}" was aborted`)))},V=setTimeout(()=>{Z.cancel(),W(()=>H(Error(`LSP request "${U}" timed out after ${J}ms`)))},J);if(Y?.addEventListener("abort",z,{once:!0}),Y?.aborted)z();$.then((B)=>W(()=>X(B)),(B)=>W(()=>H(B)))})}async disposeTransport(){let $=this.connection,Z=this.processTree;this.connection=void 0,this.processTree=void 0,this.child=void 0,this.closePromise=void 0;try{$?.dispose()}catch{}await Z?.terminate(),await this.crashCleanup,this.crashCleanup=void 0}}var v3=u("Service"),I3=10485760,y3=10,A4=30,x3=-32801;class J5{options;workspaceRoot;servers=new Map;diagnostics=new Map;delivered=new Map;waiters=new Map;disposeController=new AbortController;diagnosticSequence=0;disposed=!1;constructor($){this.options=$;let Z=i.resolve($.workspaceRoot);try{this.workspaceRoot=P3.native(Z)}catch{this.workspaceRoot=Z}for(let[J,Y]of Object.entries($.servers)){if(Y.enabled===!1)continue;let U={name:J,config:structuredClone(Y),state:"stopped",restartCount:0,openedFiles:new Map,client:new Z5(J,(X)=>{U.state="error",U.lastError=X.message,U.openedFiles.clear()})};U.client.onNotification("textDocument/publishDiagnostics",(X)=>{this.captureDiagnostics(J,X)}),U.client.onRequest("workspace/configuration",(X)=>this.resolveWorkspaceConfiguration(Y.settings,X)),U.client.onRequest("workspace/workspaceFolders",()=>[{uri:Y$(this.workspaceRoot).href,name:i.basename(this.workspaceRoot)}]),U.client.onRequest("window/workDoneProgress/create",()=>null),this.servers.set(J,U)}}get available(){return this.servers.size>0&&!this.isRemoteSession()&&!this.disposed}get workspacePath(){return this.workspaceRoot}getStatus(){return[...this.servers.values()].map(($)=>({name:$.name,state:$.state,restartCount:$.restartCount,extensions:Object.keys($.config.extensionToLanguage).sort(),...$.lastError?{lastError:$.lastError}:{}})).sort(($,Z)=>$.name.localeCompare(Z.name))}async afterToolUse($,Z,J,Y){if(!this.available||this.disposed)return;let U;if(J.success&&($==="Write"||$==="Edit")&&typeof Z.file_path==="string")U=await this.syncAfterWrite(Z.file_path,Y.signal);else if(J.success&&$==="ApplyPatch"){let X=Array.isArray(J.metadata?.changes)?J.metadata.changes:[];for(let H of X){if(!H||typeof H!=="object"||!("path"in H)||typeof H.path!=="string")continue;if("newContent"in H&&H.newContent===null)await this.syncAfterDelete(H.path);else U=await this.syncAfterWrite(H.path,Y.signal)??U}}this.attachPendingDiagnostics(J,U)}async query($,Z){if(!this.available)throw Error(this.isRemoteSession()?"LSP is unavailable for ACP-owned remote files":"No LSP servers are configured for this Session");let J=await this.resolveFile($.filePath);if($.operation==="diagnostics")return{operation:$.operation,filePath:J,result:this.getCurrentDiagnostics(J)};let Y=await this.ensureFileOpen(J,void 0,Z);if(!Y)throw Error(`No LSP server handles ${i.extname(J)||"this file"}`);let U={line:Math.max(0,($.line??1)-1),character:Math.max(0,($.character??1)-1)},X={uri:Y$(J).href},H={goToDefinition:{method:"textDocument/definition",params:{textDocument:X,position:U}},findReferences:{method:"textDocument/references",params:{textDocument:X,position:U,context:{includeDeclaration:!0}}},hover:{method:"textDocument/hover",params:{textDocument:X,position:U}},documentSymbol:{method:"textDocument/documentSymbol",params:{textDocument:X}},workspaceSymbol:{method:"workspace/symbol",params:{query:$.query??""}},goToImplementation:{method:"textDocument/implementation",params:{textDocument:X,position:U}},prepareCallHierarchy:{method:"textDocument/prepareCallHierarchy",params:{textDocument:X,position:U}}},Q;if($.operation==="incomingCalls"||$.operation==="outgoingCalls"){let z=(await this.requestWithRetry(Y,"textDocument/prepareCallHierarchy",{textDocument:X,position:U},Z))?.[0];Q=z?await this.requestWithRetry(Y,$.operation==="incomingCalls"?"callHierarchy/incomingCalls":"callHierarchy/outgoingCalls",{item:z},Z):[]}else{let W=H[$.operation];Q=await this.requestWithRetry(Y,W.method,W.params,Z)}return{operation:$.operation,filePath:J,serverName:Y.name,result:Q}}async dispose(){if(this.disposed)return;this.disposed=!0,this.disposeController.abort();for(let $ of this.waiters.values())for(let Z of $)clearTimeout(Z.timer),Z.resolve();this.waiters.clear(),await Promise.allSettled([...this.servers.values()].map(async($)=>{$.state="stopping",await $.client.stop($.config.shutdownTimeout??2000),$.state="stopped",$.openedFiles.clear()})),this.diagnostics.clear(),this.delivered.clear()}isRemoteSession(){return this.options.isRemoteSession?.()??a(this.options.sessionId)}selectServer($){let Z=i.extname($).toLowerCase();return[...this.servers.values()].filter((J)=>(Z in J.config.extensionToLanguage)).sort((J,Y)=>(Y.config.priority??0)-(J.config.priority??0)||J.name.localeCompare(Y.name))[0]}async ensureFileOpen($,Z,J){let Y=this.selectServer($);if(!Y)return;await this.ensureStarted(Y,J);let U=Y$($).href;if(Y.openedFiles.has(U))return Y;let X=Z??await this.readBoundedFile($);return await Y.client.notify("textDocument/didOpen",{textDocument:{uri:U,languageId:Y.config.extensionToLanguage[i.extname($).toLowerCase()],version:1,text:X}}),Y.openedFiles.set(U,1),Y}async syncAfterWrite($,Z){try{let J=await this.resolveFile($),Y=await this.readBoundedFile(J),U=await this.ensureFileOpen(J,Y,Z);if(!U)return;let X=Y$(J).href,H=this.diagnostics.get(X)?.sequence??0;this.delivered.delete(X);let Q=U.openedFiles.get(X)??0;if(Q>0){let W=Q+1;await U.client.notify("textDocument/didChange",{textDocument:{uri:X,version:W},contentChanges:[{text:Y}]}),U.openedFiles.set(X,W)}return await U.client.notify("textDocument/didSave",{textDocument:{uri:X},text:Y}),await this.waitForDiagnostics(X,H,U.config.diagnosticWaitTimeout??750,Z),J}catch(J){if(!Z?.aborted&&!this.disposeController.signal.aborted)v3.debug(`[LSP] post-edit sync skipped: ${J instanceof Error?J.message:String(J)}`);return}}async syncAfterDelete($){let Z=await this.resolveMissingFile($).catch(()=>{return});if(!Z)return;if(!this.isInsideWorkspace(Z))return;let J=Y$(Z).href;for(let Y of this.servers.values()){if(!Y.openedFiles.has(J))continue;await Y.client.notify("textDocument/didClose",{textDocument:{uri:J}}).catch(()=>{return}),Y.openedFiles.delete(J)}this.diagnostics.delete(J),this.delivered.delete(J)}async ensureStarted($,Z){if($.state==="running")return;if($.startPromise)return $.startPromise;if($.state==="error"){if($.restartCount>=($.config.maxRestarts??3))throw Error(`LSP server "${$.name}" exceeded its restart limit`);$.restartCount++}let J=this.startServer($,Z).finally(()=>{$.startPromise=void 0});return $.startPromise=J,J}async startServer($,Z){$.state="starting";try{await $.client.start({command:$.config.command,args:$.config.args??[],cwd:this.workspaceRoot,environment:{...this.options.environment,...$.config.env,BLADE_SESSION_ID:this.options.sessionId}});let J=Y$(this.workspaceRoot).href,Y={processId:process.pid,rootPath:this.workspaceRoot,rootUri:J,workspaceFolders:[{uri:J,name:i.basename(this.workspaceRoot)}],initializationOptions:$.config.initializationOptions??{},capabilities:{workspace:{configuration:!0,workspaceFolders:!0,symbol:{dynamicRegistration:!1}},textDocument:{synchronization:{dynamicRegistration:!1,willSave:!1,willSaveWaitUntil:!1,didSave:!0},publishDiagnostics:{relatedInformation:!0,versionSupport:!1},hover:{dynamicRegistration:!1,contentFormat:["markdown","plaintext"]},definition:{dynamicRegistration:!1,linkSupport:!0},references:{dynamicRegistration:!1},implementation:{dynamicRegistration:!1,linkSupport:!0},documentSymbol:{dynamicRegistration:!1,hierarchicalDocumentSymbolSupport:!0},callHierarchy:{dynamicRegistration:!1}},general:{positionEncodings:["utf-16"]}}};if(await $.client.initialize(Y,$.config.startupTimeout??1e4,Z),$.config.settings!==void 0)await $.client.notify("workspace/didChangeConfiguration",{settings:$.config.settings});$.state="running",$.lastError=void 0}catch(J){throw $.state="error",$.lastError=J instanceof Error?J.message:String(J),await $.client.stop($.config.shutdownTimeout??2000).catch(()=>{return}),J}}async requestWithRetry($,Z,J,Y){let U;for(let X=0;X<4;X++)try{return await $.client.request(Z,J,$.config.requestTimeout??1e4,Y)}catch(H){if(U=H,H.code!==x3||X===3)break;await new Promise((Q)=>setTimeout(Q,100*2**X))}throw U}captureDiagnostics($,Z){if(this.disposed||!Z||typeof Z!=="object"||!("uri"in Z)||!("diagnostics"in Z))return;let J=Z;if(!Array.isArray(J.diagnostics))return;let Y;try{Y=J.uri.startsWith("file:")?k3(J.uri):i.resolve(J.uri)}catch{return}if(!this.isInsideWorkspace(Y))return;let U=Y$(i.resolve(Y)).href,X={sequence:++this.diagnosticSequence,serverName:$,filePath:i.resolve(Y),diagnostics:J.diagnostics.filter((W)=>W&&typeof W.message==="string"&&W.range!==void 0).slice(0,100).map((W)=>structuredClone(W))};this.diagnostics.set(U,X);let H=this.waiters.get(U)??[],Q=[];for(let W of H)if(X.sequence>W.afterSequence)clearTimeout(W.timer),W.resolve();else Q.push(W);if(Q.length>0)this.waiters.set(U,Q);else this.waiters.delete(U)}waitForDiagnostics($,Z,J,Y){if(J===0||(this.diagnostics.get($)?.sequence??0)>Z)return Promise.resolve();return new Promise((U)=>{let X=!1,H,Q=()=>{if(X)return;X=!0,clearTimeout(H.timer),Y?.removeEventListener("abort",Q);let V=(this.waiters.get($)??[]).filter((B)=>B!==H);if(V.length>0)this.waiters.set($,V);else this.waiters.delete($);U()},W=setTimeout(Q,J);H={afterSequence:Z,resolve:Q,timer:W};let z=this.waiters.get($)??[];if(z.push(H),this.waiters.set($,z),Y?.addEventListener("abort",Q,{once:!0}),Y?.aborted)Q()})}attachPendingDiagnostics($,Z){let J=[...this.diagnostics.values()].sort((Q,W)=>{if(Z){if(Q.filePath===Z&&W.filePath!==Z)return-1;if(W.filePath===Z&&Q.filePath!==Z)return 1}return W.sequence-Q.sequence}),Y=[],U=[],X=0;for(let Q of J){let W=Y$(Q.filePath).href,z=this.delivered.get(W)??new Set,V=Q.diagnostics.sort((K,G)=>(K.severity??4)-(G.severity??4)).filter((K)=>!z.has(this.diagnosticKey(K))).slice(0,Math.min(y3,A4-X));if(V.length===0)continue;let B=i.relative(this.workspaceRoot,Q.filePath);Y.push(`${B}:`);for(let K of V){let G=K.range.start.line+1,O=K.range.start.character+1,E=["Error","Warning","Info","Hint"][(K.severity??1)-1],q=K.message.replace(/\s+/g," ").slice(0,500);Y.push(` ${E??"Error"} ${G}:${O} ${q}`+(K.code!==void 0?` [${String(K.code)}]`:"")),z.add(this.diagnosticKey(K)),U.push({file:B,line:G,character:O,severity:E??"Error",message:q,server:Q.serverName}),X++}if(this.delivered.set(W,z),X>=A4)break}if(Y.length===0)return;let H=typeof $.llmContent==="string"?$.llmContent:JSON.stringify($.llmContent);$.llmContent=`${H}
|
|
1
|
+
import{aa as j,ba as u0,ga as L7,ha as w8,ia as k0}from"./chunk-mxqpg4gy.js";import{Aa as h0,Da as Z0,Ja as u2,Ka as B7,Ra as I8,ja as q$,ka as U2,la as X8,ma as D1,na as z6,oa as Q8,pa as W8,qa as z8,ra as A2,sa as q2,ta as F2,wa as D2}from"./chunk-9kwt0w46.js";import{Sa as a8,Ta as o8,Ua as z2}from"./chunk-jza1rsan.js";import{$a as V0,_a as X0,ab as n0,bb as t2,cb as s$,db as n9,eb as r9,fb as v2,gb as a9,hb as o9,kb as q7,nb as s9,ob as t9,qb as n}from"./chunk-scq3ns6v.js";import{Cb as X3,Ib as H3,rb as R2,sb as a0,yb as g$}from"./chunk-an96c54z.js";import{Tb as r4,Ub as l4}from"./chunk-drrdzmaa.js";import{ec as w2,fc as H0,gc as R,jc as W0,kc as K2,lc as Z1,mc as L$,nc as w6,oc as P$,pc as v8,uc as F$}from"./chunk-b9v7waxf.js";import{vc as u$}from"./chunk-g6h6h8xr.js";import{wc as z$}from"./chunk-fvhc1yj8.js";import{Ac as U7,Bc as _2}from"./chunk-dqvcgwhe.js";import{Dc as w0,Ec as f$}from"./chunk-ea7wsges.js";import{Fc as _7}from"./chunk-gxmrakrk.js";import{Hc as g9,Ic as p9,Jc as c9}from"./chunk-fx87s3mb.js";import{$c as $7,Kc as j$,Lc as Z9,Nc as C0,Oc as E3,Pc as R0,Qc as m0,Rc as Y5,Sc as I2,Tc as U$,Uc as l$,Vc as n$,Wc as l9,Xc as u6,Zc as e,_c as G2}from"./chunk-1ndryz4h.js";import{ad as P7,cd as i9,dd as k2,ed as a4}from"./chunk-35yktzm1.js";import{gd as t6,id as G0}from"./chunk-vxymgh8e.js";import{jd as p0}from"./chunk-qm11hjd3.js";import{nd as u}from"./chunk-qda309d9.js";import{$d as t,Cd as A7,Gd as I4,Id as h9,Kd as Y8,Ld as U8,Sd as L4,Td as Z7,Ud as m9,Vd as T8,Wd as j8,Xd as M8,Yd as C8,Zd as f8,_d as R8,qd as k4,vd as v4,xd as r6}from"./chunk-csr5vppa.js";import{ce as m1,de as q4,ee as _,fe as J9,ge as f,he as d}from"./chunk-tq52pbde.js";import{me as v9,ne as I9}from"./chunk-79s052sw.js";import{pe as n1,re as N}from"./chunk-epj56s0n.js";import{ve as u9,we as d9}from"./chunk-gxzbv67r.js";import{Ae as R7,xe as v7}from"./chunk-bexgcc2d.js";import{Ee as B2}from"./chunk-nr53mq0k.js";import{Je as j0}from"./chunk-z906d5tb.js";import{Me as t$,Oe as y$,Pe as S0,Qe as e$,Re as E4,Se as A8,Te as q0,Ue as L8}from"./chunk-0n97186m.js";import{Ve as g0}from"./chunk-9ffr01c3.js";import{randomUUID as b3}from"crypto";import{mkdir as u1,realpath as o2}from"node:fs/promises";import F3 from"node:os";import _$ from"node:path";import{Mutex as D3}from"async-mutex";var H4=new D3,G$,r2;function w3(){return import("@anthropic-ai/sandbox-runtime")}async function B1(){if(G$)return G$;if(!r2)r2=w3();return G$=await r2,G$}var A3={isSupportedPlatform:async()=>(await B1()).SandboxManager.isSupportedPlatform(),checkDependencies:async()=>(await B1()).SandboxManager.checkDependencies(),getDefaultWritePaths:async()=>(await B1()).getDefaultWritePaths(),initialize:async($)=>(await B1()).SandboxManager.initialize($),updateConfig:($)=>{if(!G$)throw Error("Sandbox runtime is not initialized");G$.SandboxManager.updateConfig($)},wrapWithSandboxArgv:async($,Z,J,Y,U)=>(await B1()).SandboxManager.wrapWithSandboxArgv($,Z,J,Y,U),cleanupAfterCommand:()=>G$?.SandboxManager.cleanupAfterCommand(),reset:async()=>{await G$?.SandboxManager.reset()}};function a2($){return{network:{allowedDomains:$,deniedDomains:[],strictAllowlist:!0},filesystem:{denyRead:[],allowRead:[],allowWrite:[],denyWrite:[]},enableWeakerNestedSandbox:!0}}class R$ extends Error{constructor($){super($);this.name="WorkspaceSandboxUnavailableError"}}class r$ extends Error{constructor($){super($);this.name="WorkspaceSandboxBoundaryError"}}class Q4{backend;constructor($){this.backend=$}async prepare($){let Z=_$.resolve($.workspaceRoot),J=_$.resolve($.cwd);if(!X0.isWithinWorkspace(J,Z))throw new r$(`Bash cwd is outside the workspace sandbox: ${$.cwd}`);let Y,U;try{[Y,U]=await Promise.all([o2(Z),o2(J)])}catch(X){throw new r$(`Workspace sandbox path cannot be resolved: ${X instanceof Error?X.message:String(X)}`)}if(!X0.isWithinWorkspace(U,Y))throw new r$(`Bash cwd resolves outside the workspace sandbox: ${$.cwd}`);return this.backend.prepare({...$,cwd:U,workspaceRoot:Y})}}class W4{runtime;tempRoot;defaultWritePaths;initialization;constructor($={}){this.runtime=$.runtime??A3,this.tempRoot=$.tempRoot??_$.join(q0(),"sandbox-tmp"),this.defaultWritePaths=$.defaultWritePaths}async prepare($){await this.ensureInitialized();let Z=await this.prepareTempRoot(),J=_$.join(Z,"tmp"),Y=_$.join(Z,"cache"),U=_$.join(Y,"npm"),X=_$.join(Y,"bun");await Promise.all([u1(J,{recursive:!0}),u1(U,{recursive:!0}),u1(X,{recursive:!0})]);let Q=(this.defaultWritePaths??await this.runtime.getDefaultWritePaths()).filter((q)=>!q.startsWith("/dev/")),W=$.access==="workspace-read-only",z=W?[F3.homedir(),q0(),process.env.BLADE_REAL_API_CREDENTIALS_FILE].filter((q)=>typeof q==="string"&&q.trim().length>0).map((q)=>_$.resolve(q)).filter((q,F,D)=>D.indexOf(q)===F):[],V=process.platform==="win32"?"bash":"/bin/bash",B,K,G=()=>{if(!K)return;let q=K;K=void 0;try{this.runtime.updateConfig(a2(["*"]))}finally{q()}},O=async()=>{let q=process.env.CLAUDE_CODE_TMPDIR;process.env.CLAUDE_CODE_TMPDIR=J;try{return await this.runtime.wrapWithSandboxArgv($.command,V,{network:W?{allowedDomains:[],deniedDomains:[],strictAllowlist:!0}:{allowedDomains:["*"],deniedDomains:[],strictAllowlist:!0},filesystem:{denyRead:z,allowRead:W?[$.workspaceRoot]:[],allowWrite:W?[Z]:[$.workspaceRoot,Z],denyWrite:W?[$.workspaceRoot,...Q]:Q},git:{safeDirectories:[$.workspaceRoot]}},$.signal,$.cwd)}finally{if(q===void 0)delete process.env.CLAUDE_CODE_TMPDIR;else process.env.CLAUDE_CODE_TMPDIR=q}};try{if(W)K=await H4.acquire(),this.runtime.updateConfig(a2([])),B=await O();else B=await H4.runExclusive(O)}catch(q){if(G(),q instanceof Error&&q.name==="AbortError")throw q;throw new R$(`Workspace sandbox failed to prepare the command: ${q instanceof Error?q.message:String(q)}`)}let E=!1;return{executable:B.argv[0]??V,args:B.argv.slice(1),env:{...B.env,TMPDIR:J,TMP:J,TEMP:J,XDG_CACHE_HOME:Y,npm_config_cache:U,BUN_INSTALL_CACHE_DIR:X},sandboxed:!0,inheritProcessEnv:!W,cleanup:()=>{if(E)return;E=!0;try{this.runtime.cleanupAfterCommand()}finally{G()}}}}async dispose(){this.initialization=void 0,await this.runtime.reset()}async ensureInitialized(){if(!this.initialization)this.initialization=this.initializeRuntime().catch(($)=>{throw this.initialization=void 0,$});return this.initialization}async initializeRuntime(){if(!await this.runtime.isSupportedPlatform())throw new R$(`Workspace sandbox is unsupported on ${process.platform}`);let $=await this.runtime.checkDependencies();if($.errors.length>0)throw new R$(`Workspace sandbox dependencies are unavailable: ${$.errors.join("; ")}`);try{await this.runtime.initialize(a2(["*"]))}catch(Z){throw new R$(`Workspace sandbox failed to initialize: ${Z instanceof Error?Z.message:String(Z)}`)}}async prepareTempRoot(){return await u1(this.tempRoot,{recursive:!0}),o2(this.tempRoot)}}function d1($,Z){let J=Z.toLowerCase();return $===71&&J.includes("sandbox-exec")||J.includes("sandbox_apply: operation not permitted")||J.includes("bwrap: creating new namespace failed")||J.includes("failed to create new user namespace")||J.includes("srt-win sandbox failed")}var L3=new W4,N3={prepare:($)=>L3.prepare($)},s2=new Q4(N3);class s{static instance=null;processes=new Map;static getInstance(){if(!s.instance)s.instance=new s;return s.instance}startBackgroundProcess($){let Z=`bash_${b3()}`,J={};for(let[W,z]of Object.entries({...process.env,...$.env,...$.sandboxedCommand?.env,BLADE_CLI:"1"}))if(z!==void 0)J[W]=z;let Y=$.sandboxedCommand?.executable??"bash",U=$.sandboxedCommand?.args??["-c",$.command],{child:X,processTree:H}=p0(Y,U,{cwd:$.cwd||N(),env:J,stdio:["pipe","pipe","pipe"]}),Q={id:Z,command:$.command,sessionId:$.sessionId,cwd:$.cwd,env:$.env,process:X,processTree:H,pid:X.pid,status:"running",startTime:Date.now(),pendingStdout:new t2,pendingStderr:new t2,sandboxed:Boolean($.sandboxedCommand)};return X.stdout?.setEncoding("utf8"),X.stderr?.setEncoding("utf8"),X.stdout?.on("data",(W)=>{Q.pendingStdout.append(W)}),X.stderr?.on("data",(W)=>{Q.pendingStderr.append(W)}),X.on("close",(W,z)=>{$.sandboxedCommand?.cleanup();let V=Q.sandboxed&&d1(W,Q.pendingStderr.peek().content);if(Q.status=Q.status==="killed"?"killed":V?"error":"exited",Q.exitCode=W,Q.signal=z,V)Q.errorMessage="Workspace sandbox failed to start; command was not executed";Q.endTime=Date.now(),Q.process=void 0}),X.on("error",(W)=>{$.sandboxedCommand?.cleanup(),Q.status="error",Q.errorMessage=W.message,Q.endTime=Date.now(),Q.process=void 0,Q.pendingStderr.append(`
|
|
2
|
+
[error] ${W.message}`)}),this.processes.set(Z,Q),Q}consumeOutput($,Z){let J=this.getProcess($,Z);if(!J)return;let Y=J.pendingStdout.consume(),U=J.pendingStderr.consume();return{id:J.id,command:J.command,status:J.status,stdout:Y.content,stderr:U.content,stdoutOmittedBytes:Y.omittedBytes,stderrOmittedBytes:U.omittedBytes,exitCode:J.exitCode,signal:J.signal,pid:J.pid,startedAt:J.startTime,endedAt:J.endTime,errorMessage:J.errorMessage,sandboxed:J.sandboxed}}getProcess($,Z){let J=this.processes.get($);return J?.sessionId===Z?J:void 0}listForSession($){return Array.from(this.processes.values()).filter((Z)=>Z.sessionId===$)}async writeInput($,Z,J,Y=!1){let U=this.getProcess($,Z);if(!U)return;let X=U.process?.stdin;if(U.status!=="running"||!X||X.destroyed||X.writableEnded)return{success:!1,status:U.status,bytesWritten:0,stdinClosed:!X||X.destroyed||X.writableEnded,errorMessage:"Shell stdin is not writable"};try{return await new Promise((H,Q)=>{let W=(V)=>{X.off("error",W),Q(V)},z=(V)=>{if(X.off("error",W),V)Q(V);else H()};if(X.once("error",W),Y)X.end(J,z);else X.write(J,z)}),{success:!0,status:U.status,bytesWritten:Buffer.byteLength(J),stdinClosed:Y}}catch(H){return{success:!1,status:U.status,bytesWritten:0,stdinClosed:X.destroyed||X.writableEnded,errorMessage:H instanceof Error?H.message:"Failed to write stdin"}}}async kill($,Z){let J=this.getProcess($,Z);if(!J)return;return this.terminateProcess(J)}async killSession($){let Z=this.listForSession($);await Promise.all(Z.map((J)=>this.terminateProcess(J)));for(let J of Z)this.processes.delete(J.id)}async terminateProcess($){if($.status!=="running"||!$.process)return{success:!1,alreadyExited:!0,status:$.status,pid:$.pid,exitCode:$.exitCode,signal:$.signal};$.status="killed",$.endTime=Date.now();let Z=await $.processTree?.terminate();if(!Z?.success)return $.status="error",$.errorMessage="Failed to terminate owned process tree",{success:!1,alreadyExited:Z?.alreadyExited??!1,status:$.status,pid:$.pid,exitCode:$.exitCode,signal:$.signal};return{success:!0,alreadyExited:Z.alreadyExited,status:$.status,pid:$.pid,exitCode:$.exitCode,signal:$.signal}}async killAll(){await Promise.all(Array.from(this.processes.values()).map(($)=>this.terminateProcess($))),this.processes.clear()}}import{stat as AH}from"node:fs/promises";import{Mutex as LH}from"async-mutex";import{nanoid as NH}from"nanoid";import*as e9 from"os";import*as Y0 from"path";import*as I0 from"fs/promises";class S${async readTextFile($){return I0.readFile($,"utf-8")}async writeTextFile($,Z){await I0.writeFile($,Z,"utf-8")}async exists($){try{return await I0.access($),!0}catch{return!1}}async readBinaryFile($){return I0.readFile($)}async stat($){try{let Z=await I0.stat($);return{size:Z.size,isDirectory:Z.isDirectory(),isFile:Z.isFile(),mtime:Z.mtime}}catch{return null}}async mkdir($,Z){await I0.mkdir($,{recursive:Z?.recursive??!1,mode:Z?.mode??493})}}var T3=new S$;function O$(){return T3}var F0=u("Agent");class K1{connection;sessionId;capabilities;fallback;constructor($,Z,J,Y=new S$){this.connection=$;this.sessionId=Z;this.capabilities=J;this.fallback=Y}async readTextFile($){if(!this.capabilities.readTextFile)return F0.debug(`[AcpFileSystem] readTextFile fallback: ${$}`),this.fallback.readTextFile($);try{return F0.debug(`[AcpFileSystem] readTextFile via ACP: ${$}`),(await this.connection.readTextFile({path:$,sessionId:this.sessionId})).content}catch(Z){throw F0.warn(`[AcpFileSystem] readTextFile ACP failed: ${Z}`),Z}}async writeTextFile($,Z){if(!this.capabilities.writeTextFile)return F0.debug(`[AcpFileSystem] writeTextFile fallback: ${$}`),this.fallback.writeTextFile($,Z);try{F0.debug(`[AcpFileSystem] writeTextFile via ACP: ${$}`),await this.connection.writeTextFile({path:$,content:Z,sessionId:this.sessionId})}catch(J){throw F0.warn(`[AcpFileSystem] writeTextFile ACP failed: ${J}`),J}}async exists($){if(!this.capabilities.readTextFile)return F0.debug(`[AcpFileSystem] exists fallback to local: ${$}`),this.fallback.exists($);try{return await this.connection.readTextFile({path:$,sessionId:this.sessionId}),F0.debug(`[AcpFileSystem] exists(${$}): true (ACP read success)`),!0}catch(Z){let J=String(Z).toLowerCase();if(["not found","no such file","enoent","does not exist","file not found","path not found"].some((H)=>J.includes(H)))return F0.debug(`[AcpFileSystem] exists(${$}): false (ACP: not found)`),!1;let X=j3(J);return F0.warn(`[AcpFileSystem] exists(${$}): assuming exists due to ${X} error`,{error:String(Z),errorType:X,filePath:$}),!0}}async readBinaryFile($){return F0.debug(`[AcpFileSystem] readBinaryFile fallback: ${$}`),this.fallback.readBinaryFile($)}async stat($){return F0.debug(`[AcpFileSystem] stat fallback: ${$}`),this.fallback.stat($)}async mkdir($,Z){return F0.debug(`[AcpFileSystem] mkdir fallback: ${$}`),this.fallback.mkdir($,Z)}getCapabilities(){return this.capabilities}canReadTextFile(){return this.capabilities.readTextFile??!1}canWriteTextFile(){return this.capabilities.writeTextFile??!1}usesRemoteFiles(){return this.canReadTextFile()||this.canWriteTextFile()}}function j3($){if($.includes("permission")||$.includes("access denied"))return"permission";if($.includes("timeout")||$.includes("timed out"))return"timeout";if($.includes("binary")||$.includes("encoding"))return"binary";if($.includes("too large")||$.includes("size"))return"size";if($.includes("connection")||$.includes("network"))return"network";return"unknown"}var c0=u("Agent");class e2{async execute($,Z){return new Promise((J)=>{let Y=process.platform==="win32"?"cmd.exe":"/bin/bash",U=process.platform==="win32"?["/c",$]:["-c",$],{child:X,processTree:H}=p0(Y,U,{cwd:Z?.cwd||N(),env:{...process.env,...Z?.env},stdio:["pipe","pipe","pipe"]}),Q,W=()=>{return Q??=H.terminate(),Q},z="",V="",B=!1,K=Z?.timeout?setTimeout(()=>{B=!0,W()},Z.timeout):null,G=null,O=()=>{if(K)clearTimeout(K);if(G&&Z?.signal)Z.signal.removeEventListener("abort",G),G=null};if(Z?.signal){if(G=()=>{B=!0,W()},Z.signal.addEventListener("abort",G),Z.signal.aborted)G()}X.stdout?.on("data",(E)=>{let q=E.toString();z+=q,Z?.onOutput?.(q)}),X.stderr?.on("data",(E)=>{let q=E.toString();V+=q,Z?.onOutput?.(q)}),X.on("close",async(E)=>{if(O(),B)await W();J({success:E===0&&!B,stdout:z,stderr:V,exitCode:E,error:B?"Command was terminated":void 0})}),X.on("error",(E)=>{O(),J({success:!1,stdout:z,stderr:V,exitCode:null,error:E.message})})})}isAvailable(){return!0}}class z4{connection;sessionId;fallback;constructor($,Z,J=new e2){this.connection=$;this.sessionId=Z;this.fallback=J}async execute($,Z){try{c0.debug(`[AcpTerminal] Executing command via ACP: ${$}`);let J=await this.connection.createTerminal({sessionId:this.sessionId,command:$,cwd:Z?.cwd,env:Z?.env?Object.entries(Z.env).map(([z,V])=>({name:z,value:V})):void 0}),Y=0,U=null;if(Z?.onOutput)U=setInterval(async()=>{try{let V=(await J.currentOutput()).output||"";if(V.length>Y){let B=V.slice(Y);Y=V.length,Z.onOutput?.(B)}}catch{}},100);let X=(z=!1)=>{if(U)clearInterval(U),U=null;(z?J.kill().then(()=>c0.debug("[AcpTerminal] Killed remote command")).catch(()=>{}).then(()=>J.release()).catch(()=>{}):J.release().catch(()=>{})).catch(()=>{})},H=[];if(H.push(J.waitForExit().then((z)=>({type:"completed",exitCode:z.exitCode??null}))),Z?.timeout)H.push(new Promise((z)=>{setTimeout(()=>z({type:"timeout"}),Z.timeout)}));if(Z?.signal)H.push(new Promise((z)=>{if(Z.signal.aborted)z({type:"aborted"});else Z.signal.addEventListener("abort",()=>z({type:"aborted"}),{once:!0})}));let Q=await Promise.race(H),W="";try{if(W=(await J.currentOutput()).output||"",Z?.onOutput&&W.length>Y)Z.onOutput(W.slice(Y))}catch{}switch(Q.type){case"completed":return X(!1),{success:Q.exitCode===0,stdout:W,stderr:"",exitCode:Q.exitCode};case"timeout":return c0.debug(`[AcpTerminal] Command timed out, killing: ${$}`),X(!0),{success:!1,stdout:W,stderr:"",exitCode:null,error:"Command timed out"};case"aborted":return c0.debug(`[AcpTerminal] Command aborted, killing: ${$}`),X(!0),{success:!1,stdout:W,stderr:"",exitCode:null,error:"Command was aborted"}}}catch(J){if(Z?.allowLocalFallback===!1)return{success:!1,stdout:"",stderr:"",exitCode:null,error:J instanceof Error?`ACP terminal unavailable: ${J.message}`:"ACP terminal unavailable"};return c0.warn("[AcpTerminal] ACP terminal failed, using fallback:",J),this.fallback.execute($,Z)}}isAvailable(){return!0}}class I{static sessions=new Map;static currentSessionId=null;constructor(){}static getInstance(){return new I}static initializeSession($,Z,J,Y){let U=J?.fs?new K1($,Z,J.fs):new S$;if(J?.fs)c0.debug(`[AcpServiceContext:${Z}] Using ACP file system service`);let X=new z4($,Z);c0.debug(`[AcpServiceContext:${Z}] Using ACP terminal service`),I.sessions.set(Z,{fileSystemService:U,terminalService:X,connection:$,clientCapabilities:J||null,cwd:Y}),I.currentSessionId=Z,c0.debug(`[AcpServiceContext:${Z}] Initialized with capabilities:`,{fs:!!J?.fs,readTextFile:J?.fs?.readTextFile,writeTextFile:J?.fs?.writeTextFile,cwd:Y})}static destroySession($){if(I.sessions.delete($),I.currentSessionId===$){let Z=Array.from(I.sessions.keys());I.currentSessionId=Z[0]||null}c0.debug(`[AcpServiceContext:${$}] Session destroyed`)}static getSessionServices($){return I.sessions.get($)||null}static setCurrentSession($){if(I.sessions.has($))I.currentSessionId=$}static getCurrentSessionId(){return I.currentSessionId}initialize($,Z,J,Y){I.initializeSession($,Z,J,Y||N())}reset(){if(I.currentSessionId)I.destroySession(I.currentSessionId)}isAcpMode(){return I.currentSessionId!==null}getFileSystemService($){let Z=$??I.currentSessionId;if(Z){let J=I.sessions.get(Z);if(J)return J.fileSystemService}return new S$}getTerminalService($){let Z=$??I.currentSessionId;if(Z){let J=I.sessions.get(Z);if(J)return J.terminalService}return new e2}getConnection(){if(I.currentSessionId){let $=I.sessions.get(I.currentSessionId);if($)return $.connection}return null}getSessionId(){return I.currentSessionId}getClientCapabilities(){if(I.currentSessionId){let $=I.sessions.get(I.currentSessionId);if($)return $.clientCapabilities}return null}async sendToolUpdate($,Z,J,Y,U){let X=I.currentSessionId;if(!X)return;let H=I.sessions.get(X);if(!H)return;try{await H.connection.sessionUpdate({sessionId:X,update:{sessionUpdate:"tool_call",toolCallId:$,status:Z,title:J,content:Y||[],kind:U||"other"}})}catch(Q){c0.warn("[AcpServiceContext] Failed to send tool update:",Q)}}}function E$($){return I.getInstance().getFileSystemService($)}function V4($){return I.getInstance().getTerminalService($)}function a($){return $?I.getSessionServices($)!==null:I.getInstance().isAcpMode()}import*as i0 from"node:fs/promises";import*as F4 from"node:path";import{Mutex as M3}from"async-mutex";import{nanoid as C3}from"nanoid";import f3 from"write-file-atomic";var B4=["active","paused","blocked","usage_limited","budget_limited","complete"];var K4=1048576,$5=1e5,_4=_.Object({version:_.Literal(1),sessionId:_.String({minLength:1}),goalId:_.String({minLength:1}),objective:_.String({minLength:1,maxLength:$5}),status:d(B4),tokenBudget:_.Optional(_.Integer({minimum:1})),tokensUsed:_.Integer({minimum:0}),timeUsedSeconds:_.Integer({minimum:0}),continuationCount:_.Integer({minimum:0}),statusReason:_.Optional(_.String()),createdAt:_.String({format:"date-time"}),updatedAt:_.String({format:"date-time"})});function G4($,Z){return $ instanceof Error&&"code"in $&&$.code===Z}function O4($){let Z=$.trim();if(!Z)throw Error("Goal objective must not be empty");if(Z.length>$5)throw Error(`Goal objective exceeds ${$5} characters`);return Z}function R3($){if($===void 0)return;if(!Number.isInteger($)||$<=0)throw Error("Goal token budget must be a positive integer");return $}class T0{workspaceRoot;sessionId;static mutexes=new Map;static listeners=new Set;filePath;mutex;constructor($,Z){this.workspaceRoot=$;this.sessionId=Z;this.filePath=E4($,Z);let J=T0.mutexes.get(this.filePath);if(!J)J=new M3,T0.mutexes.set(this.filePath,J);this.mutex=J}static subscribe($){return this.listeners.add($),()=>this.listeners.delete($)}static async hasActiveGoal($,Z){return(await new T0($,Z).get())?.status==="active"}async get(){return this.mutex.runExclusive(()=>this.readUnlocked())}async create($){return this.mutex.runExclusive(async()=>{let Z=await this.readUnlocked();if(Z&&Z.status!=="complete")throw Error(`Session already has an unfinished goal (${Z.status}); clear or complete it first`);let J=new Date().toISOString(),Y=R3($.tokenBudget),U={version:1,sessionId:this.sessionId,goalId:C3(12),objective:O4($.objective),status:"active",...Y===void 0?{}:{tokenBudget:Y},tokensUsed:0,timeUsedSeconds:0,continuationCount:0,createdAt:J,updatedAt:J};return await this.persistUnlocked(U),this.emit(U),U})}async edit($){return this.updateExisting((Z)=>{if(!["active","paused","blocked"].includes(Z.status))throw Error(`Cannot edit goal while status is ${Z.status}`);return{...Z,objective:O4($),updatedAt:new Date().toISOString()}})}async pause($="paused by user"){return this.updateExisting((Z)=>{if(Z.status!=="active"&&Z.status!=="blocked")throw Error(`Cannot pause goal while status is ${Z.status}`);return{...Z,status:"paused",statusReason:$,updatedAt:new Date().toISOString()}})}async pauseIfActive($){return this.mutex.runExclusive(async()=>{let Z=await this.readUnlocked();if(!Z||Z.status!=="active")return Z;let J={...Z,status:"paused",statusReason:$,updatedAt:new Date().toISOString()};return await this.persistUnlocked(J),this.emit(J),J})}async resume(){return this.updateExisting(($)=>{if($.status!=="paused"&&$.status!=="blocked")throw Error(`Cannot resume goal while status is ${$.status}`);return{...$,status:"active",statusReason:void 0,updatedAt:new Date().toISOString()}})}async complete(){return this.updateExisting(($)=>{if(!["active","paused","blocked"].includes($.status))throw Error(`Cannot complete goal while status is ${$.status}`);return{...$,status:"complete",statusReason:void 0,updatedAt:new Date().toISOString()}})}async block($){return this.updateExisting((Z)=>{if(Z.status!=="active")throw Error(`Cannot block goal while status is ${Z.status}`);let J=$.trim();if(!J)throw Error("Blocked goal requires a reason");return{...Z,status:"blocked",statusReason:J,updatedAt:new Date().toISOString()}})}async recordProgress($){return this.mutex.runExclusive(async()=>{let Z=await this.readUnlocked();if(!Z||Z.status!=="active")return Z;let J=Math.max(0,Math.round($.tokens)),Y=Math.max(0,Math.round($.elapsedMs/1000)),U=Z.tokensUsed+J,X=Z.tokenBudget!==void 0&&U>=Z.tokenBudget,H={...Z,tokensUsed:U,timeUsedSeconds:Z.timeUsedSeconds+Y,status:X?"budget_limited":Z.status,statusReason:X?"token budget exhausted":Z.statusReason,updatedAt:new Date().toISOString()};return await this.persistUnlocked(H),this.emit(H),H})}async beginContinuation(){return this.updateExisting(($)=>{if($.status!=="active")throw Error(`Cannot continue goal while status is ${$.status}`);return{...$,continuationCount:$.continuationCount+1,updatedAt:new Date().toISOString()}})}async tryBeginContinuation(){return this.mutex.runExclusive(async()=>{let $=await this.readUnlocked();if(!$||$.status!=="active")return null;let Z={...$,continuationCount:$.continuationCount+1,updatedAt:new Date().toISOString()};return await this.persistUnlocked(Z),this.emit(Z),Z})}async clear(){return this.mutex.runExclusive(async()=>{try{await i0.unlink(this.filePath)}catch($){if(G4($,"ENOENT"))return!1;throw $}return this.emit(null),!0})}async updateExisting($){return this.mutex.runExclusive(async()=>{let Z=await this.readUnlocked();if(!Z)throw Error("Session has no goal");let J=q4(_4,$(Z));return await this.persistUnlocked(J),this.emit(J),J})}async readUnlocked(){try{if((await i0.stat(this.filePath)).size>K4)throw Error(`Goal state exceeds ${K4} bytes`);await i0.chmod(this.filePath,384);let Z=m1(_4,JSON.parse(await i0.readFile(this.filePath,"utf8")));if(!Z.success||Z.data.sessionId!==this.sessionId)throw Error(`Invalid goal state: ${this.filePath}`);return Z.data}catch($){if(G4($,"ENOENT"))return null;if($ instanceof SyntaxError)throw Error(`Invalid goal state JSON: ${this.filePath}`,{cause:$});throw $}}async persistUnlocked($){await i0.mkdir(F4.dirname(this.filePath),{recursive:!0,mode:448}),await f3(this.filePath,`${JSON.stringify($)}
|
|
3
|
+
`,{encoding:"utf8",mode:384,fsync:!0})}emit($){let Z={workspaceRoot:this.workspaceRoot,sessionId:this.sessionId,goal:$?{...$}:null};for(let J of T0.listeners)try{J(Z)}catch{}}}import{createHash as S3}from"node:crypto";import{promises as g1,realpathSync as P3}from"node:fs";import i from"node:path";import{fileURLToPath as k3,pathToFileURL as Y$}from"node:url";var D4=u("Service"),w4=65536;class Z5{name;onCrash;child;processTree;connection;closePromise;crashCleanup;capabilities;initialized=!1;stopping=!1;notificationHandlers=new Map;requestHandlers=new Map;constructor($,Z){this.name=$;this.onCrash=Z}get serverCapabilities(){return this.capabilities}get isInitialized(){return this.initialized}async start($){if(await this.crashCleanup,this.crashCleanup=void 0,this.connection)return;let Z=await import("vscode-jsonrpc/node.js"),{child:J,processTree:Y}=p0($.command,[...$.args],{cwd:$.cwd,env:{...$.environment,PATH:$.environment.PATH??process.env.PATH??"",HOME:$.environment.HOME??process.env.HOME??"",USER:$.environment.USER??process.env.USER??"",SHELL:$.environment.SHELL??process.env.SHELL??"/bin/sh",BLADE_CLI:"1"},stdio:["pipe","pipe","pipe"]},{releaseOnExit:!1});this.child=J,this.processTree=Y;try{if(await new Promise((H,Q)=>{let W=()=>{J.removeListener("spawn",z),J.removeListener("error",V)},z=()=>{W(),H()},V=(B)=>{W(),Q(B)};J.once("spawn",z),J.once("error",V)}),!J.stdout||!J.stdin)throw Error("LSP server stdio is unavailable");let U="";J.stderr?.setEncoding("utf8"),J.stderr?.on("data",(H)=>{if(U.length<w4)U+=H.slice(0,w4-U.length)}),J.stdin.on("error",(H)=>{if(!this.stopping)D4.debug(`[LSP ${this.name}] stdin closed: ${H.message}`)}),this.closePromise=new Promise((H)=>{J.once("close",(Q,W)=>{this.initialized=!1;let z=!this.stopping;if(!this.stopping){let V=U.trim()?`: ${U.trim().slice(0,512)}`:W?` (${W})`:"";this.onCrash(Error(`LSP server "${this.name}" exited with code ${Q}${V}`))}if(this.child===J){let V=this.processTree;try{this.connection?.dispose()}catch{}if(this.connection=void 0,this.child=void 0,this.closePromise=void 0,z&&V)this.crashCleanup=V.terminate().then(()=>{return}),this.processTree=void 0}H()})});let X=Z.createMessageConnection(new Z.StreamMessageReader(J.stdout),new Z.StreamMessageWriter(J.stdin));this.connection=X,X.onError(([H])=>{if(!this.stopping)D4.warn(`[LSP ${this.name}] connection error: ${H.message}`)}),X.onClose(()=>{this.initialized=!1});for(let[H,Q]of this.notificationHandlers)for(let W of Q)X.onNotification(H,W);for(let[H,Q]of this.requestHandlers)X.onRequest(H,Q);X.listen()}catch(U){throw await this.disposeTransport(),U}}async initialize($,Z,J){let Y=await this.request("initialize",$,Z,J,!1);return this.capabilities=Y.capabilities,await this.notify("initialized",{}),this.initialized=!0,Y}async request($,Z,J,Y,U=!0){let X=this.connection;if(!X)throw Error(`LSP server "${this.name}" is not started`);if(U&&!this.initialized)throw Error(`LSP server "${this.name}" is not initialized`);let Q=new(await import("vscode-jsonrpc/node.js")).CancellationTokenSource;return this.awaitRequest(X.sendRequest($,Z,Q.token),Q,J,Y,$)}async notify($,Z){if(!this.connection)throw Error(`LSP server "${this.name}" is not started`);await this.connection.sendNotification($,Z)}onNotification($,Z){let J=this.notificationHandlers.get($)??[];J.push(Z),this.notificationHandlers.set($,J),this.connection?.onNotification($,Z)}onRequest($,Z){this.requestHandlers.set($,Z),this.connection?.onRequest($,Z)}async stop($){if(!this.child&&!this.connection){await this.crashCleanup,this.crashCleanup=void 0;return}this.stopping=!0;let Z=this.connection;try{if(Z&&this.initialized){let Y=new(await import("vscode-jsonrpc/node.js")).CancellationTokenSource;await this.awaitRequest(Z.sendRequest("shutdown",Y.token),Y,$,void 0,"shutdown").catch(()=>{return}),await Z.sendNotification("exit").catch(()=>{return})}await Promise.race([this.closePromise??Promise.resolve(),new Promise((J)=>setTimeout(J,Math.min($,500)))])}finally{await this.disposeTransport(),this.stopping=!1,this.initialized=!1,this.capabilities=void 0}}awaitRequest($,Z,J,Y,U){return new Promise((X,H)=>{let Q=!1,W=(B)=>{if(Q)return;Q=!0,clearTimeout(V),Y?.removeEventListener("abort",z),B()},z=()=>{Z.cancel(),W(()=>H(Error(`LSP request "${U}" was aborted`)))},V=setTimeout(()=>{Z.cancel(),W(()=>H(Error(`LSP request "${U}" timed out after ${J}ms`)))},J);if(Y?.addEventListener("abort",z,{once:!0}),Y?.aborted)z();$.then((B)=>W(()=>X(B)),(B)=>W(()=>H(B)))})}async disposeTransport(){let $=this.connection,Z=this.processTree;this.connection=void 0,this.processTree=void 0,this.child=void 0,this.closePromise=void 0;try{$?.dispose()}catch{}await Z?.terminate(),await this.crashCleanup,this.crashCleanup=void 0}}var v3=u("Service"),I3=10485760,y3=10,A4=30,x3=-32801;class J5{options;workspaceRoot;servers=new Map;diagnostics=new Map;delivered=new Map;waiters=new Map;disposeController=new AbortController;diagnosticSequence=0;disposed=!1;constructor($){this.options=$;let Z=i.resolve($.workspaceRoot);try{this.workspaceRoot=P3.native(Z)}catch{this.workspaceRoot=Z}for(let[J,Y]of Object.entries($.servers)){if(Y.enabled===!1)continue;let U={name:J,config:structuredClone(Y),state:"stopped",restartCount:0,openedFiles:new Map,client:new Z5(J,(X)=>{U.state="error",U.lastError=X.message,U.openedFiles.clear()})};U.client.onNotification("textDocument/publishDiagnostics",(X)=>{this.captureDiagnostics(J,X)}),U.client.onRequest("workspace/configuration",(X)=>this.resolveWorkspaceConfiguration(Y.settings,X)),U.client.onRequest("workspace/workspaceFolders",()=>[{uri:Y$(this.workspaceRoot).href,name:i.basename(this.workspaceRoot)}]),U.client.onRequest("window/workDoneProgress/create",()=>null),this.servers.set(J,U)}}get available(){return this.servers.size>0&&!this.isRemoteSession()&&!this.disposed}get workspacePath(){return this.workspaceRoot}getStatus(){return[...this.servers.values()].map(($)=>({name:$.name,state:$.state,restartCount:$.restartCount,extensions:Object.keys($.config.extensionToLanguage).sort(),...$.lastError?{lastError:$.lastError}:{}})).sort(($,Z)=>$.name.localeCompare(Z.name))}async afterToolUse($,Z,J,Y){if(!this.available||this.disposed)return;let U;if(J.success&&($==="Write"||$==="Edit")&&typeof Z.file_path==="string")U=await this.syncAfterWrite(Z.file_path,Y.signal);else if(J.success&&$==="ApplyPatch"){let X=Array.isArray(J.metadata?.changes)?J.metadata.changes:[];for(let H of X){if(!H||typeof H!=="object"||!("path"in H)||typeof H.path!=="string")continue;if("newContent"in H&&H.newContent===null)await this.syncAfterDelete(H.path);else U=await this.syncAfterWrite(H.path,Y.signal)??U}}this.attachPendingDiagnostics(J,U)}async query($,Z){if(!this.available)throw Error(this.isRemoteSession()?"LSP is unavailable for ACP-owned remote files":"No LSP servers are configured for this Session");let J=await this.resolveFile($.filePath);if($.operation==="diagnostics")return{operation:$.operation,filePath:J,result:this.getCurrentDiagnostics(J)};let Y=await this.ensureFileOpen(J,void 0,Z);if(!Y)throw Error(`No LSP server handles ${i.extname(J)||"this file"}`);let U={line:Math.max(0,($.line??1)-1),character:Math.max(0,($.character??1)-1)},X={uri:Y$(J).href},H={goToDefinition:{method:"textDocument/definition",params:{textDocument:X,position:U}},findReferences:{method:"textDocument/references",params:{textDocument:X,position:U,context:{includeDeclaration:!0}}},hover:{method:"textDocument/hover",params:{textDocument:X,position:U}},documentSymbol:{method:"textDocument/documentSymbol",params:{textDocument:X}},workspaceSymbol:{method:"workspace/symbol",params:{query:$.query??""}},goToImplementation:{method:"textDocument/implementation",params:{textDocument:X,position:U}},prepareCallHierarchy:{method:"textDocument/prepareCallHierarchy",params:{textDocument:X,position:U}}},Q;if($.operation==="incomingCalls"||$.operation==="outgoingCalls"){let z=(await this.requestWithRetry(Y,"textDocument/prepareCallHierarchy",{textDocument:X,position:U},Z))?.[0];Q=z?await this.requestWithRetry(Y,$.operation==="incomingCalls"?"callHierarchy/incomingCalls":"callHierarchy/outgoingCalls",{item:z},Z):[]}else{let W=H[$.operation];Q=await this.requestWithRetry(Y,W.method,W.params,Z)}return{operation:$.operation,filePath:J,serverName:Y.name,result:Q}}async dispose(){if(this.disposed)return;this.disposed=!0,this.disposeController.abort();for(let $ of this.waiters.values())for(let Z of $)clearTimeout(Z.timer),Z.resolve();this.waiters.clear(),await Promise.allSettled([...this.servers.values()].map(async($)=>{$.state="stopping",await $.client.stop($.config.shutdownTimeout??2000),$.state="stopped",$.openedFiles.clear()})),this.diagnostics.clear(),this.delivered.clear()}isRemoteSession(){return this.options.isRemoteSession?.()??a(this.options.sessionId)}selectServer($){let Z=i.extname($).toLowerCase();return[...this.servers.values()].filter((J)=>(Z in J.config.extensionToLanguage)).sort((J,Y)=>(Y.config.priority??0)-(J.config.priority??0)||J.name.localeCompare(Y.name))[0]}async ensureFileOpen($,Z,J){let Y=this.selectServer($);if(!Y)return;await this.ensureStarted(Y,J);let U=Y$($).href;if(Y.openedFiles.has(U))return Y;let X=Z??await this.readBoundedFile($);return await Y.client.notify("textDocument/didOpen",{textDocument:{uri:U,languageId:Y.config.extensionToLanguage[i.extname($).toLowerCase()],version:1,text:X}}),Y.openedFiles.set(U,1),Y}async syncAfterWrite($,Z){try{let J=await this.resolveFile($),Y=await this.readBoundedFile(J),U=await this.ensureFileOpen(J,Y,Z);if(!U)return;let X=Y$(J).href,H=this.diagnostics.get(X)?.sequence??0;this.delivered.delete(X);let Q=U.openedFiles.get(X)??0;if(Q>0){let W=Q+1;await U.client.notify("textDocument/didChange",{textDocument:{uri:X,version:W},contentChanges:[{text:Y}]}),U.openedFiles.set(X,W)}return await U.client.notify("textDocument/didSave",{textDocument:{uri:X},text:Y}),await this.waitForDiagnostics(X,H,U.config.diagnosticWaitTimeout??750,Z),J}catch(J){if(!Z?.aborted&&!this.disposeController.signal.aborted)v3.debug(`[LSP] post-edit sync skipped: ${J instanceof Error?J.message:String(J)}`);return}}async syncAfterDelete($){let Z=await this.resolveMissingFile($).catch(()=>{return});if(!Z)return;if(!this.isInsideWorkspace(Z))return;let J=Y$(Z).href;for(let Y of this.servers.values()){if(!Y.openedFiles.has(J))continue;await Y.client.notify("textDocument/didClose",{textDocument:{uri:J}}).catch(()=>{return}),Y.openedFiles.delete(J)}this.diagnostics.delete(J),this.delivered.delete(J)}async ensureStarted($,Z){if($.state==="running")return;if($.startPromise)return $.startPromise;if($.state==="error"){if($.restartCount>=($.config.maxRestarts??3))throw Error(`LSP server "${$.name}" exceeded its restart limit`);$.restartCount++}let J=this.startServer($,Z).finally(()=>{$.startPromise=void 0});return $.startPromise=J,J}async startServer($,Z){$.state="starting";try{await $.client.start({command:$.config.command,args:$.config.args??[],cwd:this.workspaceRoot,environment:{...this.options.environment,...$.config.env,BLADE_SESSION_ID:this.options.sessionId}});let J=Y$(this.workspaceRoot).href,Y={processId:process.pid,rootPath:this.workspaceRoot,rootUri:J,workspaceFolders:[{uri:J,name:i.basename(this.workspaceRoot)}],initializationOptions:$.config.initializationOptions??{},capabilities:{workspace:{configuration:!0,workspaceFolders:!0,symbol:{dynamicRegistration:!1}},textDocument:{synchronization:{dynamicRegistration:!1,willSave:!1,willSaveWaitUntil:!1,didSave:!0},publishDiagnostics:{relatedInformation:!0,versionSupport:!1},hover:{dynamicRegistration:!1,contentFormat:["markdown","plaintext"]},definition:{dynamicRegistration:!1,linkSupport:!0},references:{dynamicRegistration:!1},implementation:{dynamicRegistration:!1,linkSupport:!0},documentSymbol:{dynamicRegistration:!1,hierarchicalDocumentSymbolSupport:!0},callHierarchy:{dynamicRegistration:!1}},general:{positionEncodings:["utf-16"]}}};if(await $.client.initialize(Y,$.config.startupTimeout??1e4,Z),$.config.settings!==void 0)await $.client.notify("workspace/didChangeConfiguration",{settings:$.config.settings});$.state="running",$.lastError=void 0}catch(J){throw $.state="error",$.lastError=J instanceof Error?J.message:String(J),await $.client.stop($.config.shutdownTimeout??2000).catch(()=>{return}),J}}async requestWithRetry($,Z,J,Y){let U;for(let X=0;X<4;X++)try{return await $.client.request(Z,J,$.config.requestTimeout??1e4,Y)}catch(H){if(U=H,H.code!==x3||X===3)break;await new Promise((Q)=>setTimeout(Q,100*2**X))}throw U}captureDiagnostics($,Z){if(this.disposed||!Z||typeof Z!=="object"||!("uri"in Z)||!("diagnostics"in Z))return;let J=Z;if(!Array.isArray(J.diagnostics))return;let Y;try{Y=J.uri.startsWith("file:")?k3(J.uri):i.resolve(J.uri)}catch{return}if(!this.isInsideWorkspace(Y))return;let U=Y$(i.resolve(Y)).href,X={sequence:++this.diagnosticSequence,serverName:$,filePath:i.resolve(Y),diagnostics:J.diagnostics.filter((W)=>W&&typeof W.message==="string"&&W.range!==void 0).slice(0,100).map((W)=>structuredClone(W))};this.diagnostics.set(U,X);let H=this.waiters.get(U)??[],Q=[];for(let W of H)if(X.sequence>W.afterSequence)clearTimeout(W.timer),W.resolve();else Q.push(W);if(Q.length>0)this.waiters.set(U,Q);else this.waiters.delete(U)}waitForDiagnostics($,Z,J,Y){if(J===0||(this.diagnostics.get($)?.sequence??0)>Z)return Promise.resolve();return new Promise((U)=>{let X=!1,H,Q=()=>{if(X)return;X=!0,clearTimeout(H.timer),Y?.removeEventListener("abort",Q);let V=(this.waiters.get($)??[]).filter((B)=>B!==H);if(V.length>0)this.waiters.set($,V);else this.waiters.delete($);U()},W=setTimeout(Q,J);H={afterSequence:Z,resolve:Q,timer:W};let z=this.waiters.get($)??[];if(z.push(H),this.waiters.set($,z),Y?.addEventListener("abort",Q,{once:!0}),Y?.aborted)Q()})}attachPendingDiagnostics($,Z){let J=[...this.diagnostics.values()].sort((Q,W)=>{if(Z){if(Q.filePath===Z&&W.filePath!==Z)return-1;if(W.filePath===Z&&Q.filePath!==Z)return 1}return W.sequence-Q.sequence}),Y=[],U=[],X=0;for(let Q of J){let W=Y$(Q.filePath).href,z=this.delivered.get(W)??new Set,V=Q.diagnostics.sort((K,G)=>(K.severity??4)-(G.severity??4)).filter((K)=>!z.has(this.diagnosticKey(K))).slice(0,Math.min(y3,A4-X));if(V.length===0)continue;let B=i.relative(this.workspaceRoot,Q.filePath);Y.push(`${B}:`);for(let K of V){let G=K.range.start.line+1,O=K.range.start.character+1,E=["Error","Warning","Info","Hint"][(K.severity??1)-1],q=K.message.replace(/\s+/g," ").slice(0,500);Y.push(` ${E??"Error"} ${G}:${O} ${q}`+(K.code!==void 0?` [${String(K.code)}]`:"")),z.add(this.diagnosticKey(K)),U.push({file:B,line:G,character:O,severity:E??"Error",message:q,server:Q.serverName}),X++}if(this.delivered.set(W,z),X>=A4)break}if(Y.length===0)return;let H=typeof $.llmContent==="string"?$.llmContent:JSON.stringify($.llmContent);$.llmContent=`${H}
|
|
4
4
|
|
|
5
5
|
<new-diagnostics>
|
|
6
6
|
LSP reported new issues after this operation:
|
|
7
7
|
${Y.join(`
|
|
8
8
|
`)}
|
|
9
|
-
</new-diagnostics>`,$.metadata={...$.metadata,lsp_diagnostics:U,lsp_diagnostic_count:U.length}}getCurrentDiagnostics($){return this.diagnostics.get(Y$(i.resolve($)).href)??null}diagnosticKey($){return S3("sha256").update(JSON.stringify({range:$.range,severity:$.severity,code:$.code,source:$.source,message:$.message})).digest("hex")}async readBoundedFile($){let Z=await g1.stat($);if(!Z.isFile())throw Error(`LSP target is not a file: ${$}`);if(Z.size>I3)throw Error("LSP target exceeds the 10 MiB file limit");return g1.readFile($,"utf8")}async resolveFile($){let Z=i.isAbsolute($)?i.resolve($):i.resolve(this.workspaceRoot,$),J=await g1.realpath(Z);if(!this.isInsideWorkspace(J))throw Error("LSP target resolves outside the Session workspace");return J}async resolveMissingFile($){let Z=i.isAbsolute($)?i.resolve($):i.resolve(this.workspaceRoot,$),J=[],Y=Z;while(!0){try{let X=await g1.realpath(Y),H=i.join(X,...J.reverse());if(!this.isInsideWorkspace(H))throw Error("LSP target resolves outside the Session workspace");return H}catch(X){let H=X.code;if(H!=="ENOENT"&&H!=="ENOTDIR")throw X}let U=i.dirname(Y);if(U===Y)throw Error("Cannot resolve deleted LSP target");J.push(i.basename(Y)),Y=U}}isInsideWorkspace($){let Z=i.relative(this.workspaceRoot,i.resolve($));return Z===""||!Z.startsWith(`..${i.sep}`)&&Z!==".."&&!i.isAbsolute(Z)}resolveWorkspaceConfiguration($,Z){return(Z&&typeof Z==="object"&&"items"in Z&&Array.isArray(Z.items)?Z.items:[]).map((Y)=>{if(typeof Y.section!=="string"||!$||typeof $!=="object")return $??null;let U=$;for(let X of Y.section.split(".")){if(!U||typeof U!=="object"||!(X in U))return null;U=U[X]}return U})}}import N4 from"node:path";import p1 from"node:path";async function c1($){let Z=U$($);if(Z.isInitialized()&&p1.resolve(Z.getWorkspaceRoot())===p1.resolve($))return Z.getActive();let Y=new Map;for(let Q of Z.getActive())if(Q.source==="cli")Y.set(Q.manifest.name,Q);let U=(await
|
|
9
|
+
</new-diagnostics>`,$.metadata={...$.metadata,lsp_diagnostics:U,lsp_diagnostic_count:U.length}}getCurrentDiagnostics($){return this.diagnostics.get(Y$(i.resolve($)).href)??null}diagnosticKey($){return S3("sha256").update(JSON.stringify({range:$.range,severity:$.severity,code:$.code,source:$.source,message:$.message})).digest("hex")}async readBoundedFile($){let Z=await g1.stat($);if(!Z.isFile())throw Error(`LSP target is not a file: ${$}`);if(Z.size>I3)throw Error("LSP target exceeds the 10 MiB file limit");return g1.readFile($,"utf8")}async resolveFile($){let Z=i.isAbsolute($)?i.resolve($):i.resolve(this.workspaceRoot,$),J=await g1.realpath(Z);if(!this.isInsideWorkspace(J))throw Error("LSP target resolves outside the Session workspace");return J}async resolveMissingFile($){let Z=i.isAbsolute($)?i.resolve($):i.resolve(this.workspaceRoot,$),J=[],Y=Z;while(!0){try{let X=await g1.realpath(Y),H=i.join(X,...J.reverse());if(!this.isInsideWorkspace(H))throw Error("LSP target resolves outside the Session workspace");return H}catch(X){let H=X.code;if(H!=="ENOENT"&&H!=="ENOTDIR")throw X}let U=i.dirname(Y);if(U===Y)throw Error("Cannot resolve deleted LSP target");J.push(i.basename(Y)),Y=U}}isInsideWorkspace($){let Z=i.relative(this.workspaceRoot,i.resolve($));return Z===""||!Z.startsWith(`..${i.sep}`)&&Z!==".."&&!i.isAbsolute(Z)}resolveWorkspaceConfiguration($,Z){return(Z&&typeof Z==="object"&&"items"in Z&&Array.isArray(Z.items)?Z.items:[]).map((Y)=>{if(typeof Y.section!=="string"||!$||typeof $!=="object")return $??null;let U=$;for(let X of Y.section.split(".")){if(!U||typeof U!=="object"||!(X in U))return null;U=U[X]}return U})}}import N4 from"node:path";import p1 from"node:path";async function c1($){let Z=U$($);if(Z.isInitialized()&&p1.resolve(Z.getWorkspaceRoot())===p1.resolve($))return Z.getActive();let Y=new Map;for(let Q of Z.getActive())if(Q.source==="cli")Y.set(Q.manifest.name,Q);let U=(await j0.getInstance().getStatus($)).state==="trusted",X=await t.getInstance().loadWorkspacePluginSettings($),H=new Y5;for(let Q of Y5.getPluginDirs($)){if(Q.source==="project"&&!U)continue;let W=await H.discoverPluginsInDir(Q.path,Q.source);for(let z of W.plugins){let V=Y.get(z.manifest.name);if(!V||V.source!=="cli")z.status=X[z.manifest.name]===!1?"inactive":"active",Y.set(z.manifest.name,z)}}return[...Y.values()].filter((Q)=>Q.status==="active")}function h3($){return L4(structuredClone($))}function _1($){return Object.freeze({projectRoot:N4.resolve($.projectRoot),servers:Object.freeze(h3($.servers))})}async function b4($,Z){let J=N4.resolve($),Y=await t.getInstance().loadWorkspaceLspServers(J,Z);for(let U of await c1(J))Object.assign(Y,U.lspServers??{});return _1({projectRoot:J,servers:Y})}import{constants as i1}from"node:fs";import{promises as l0}from"node:fs";import l1 from"node:path";import{createHash as U5}from"node:crypto";var T4=256,j4=67108864;function u3($){let Z=$?.split(";",1)[0]?.trim().toLowerCase();return Z&&{"application/json":".json","application/pdf":".pdf","application/zip":".zip","audio/mpeg":".mp3","audio/ogg":".ogg","audio/wav":".wav","image/gif":".gif","image/jpeg":".jpg","image/png":".png","image/webp":".webp","text/csv":".csv","text/html":".html","text/markdown":".md","text/plain":".txt"}[Z]||".bin"}async function M4($){await l0.mkdir($,{recursive:!0,mode:448});let Z=await l0.lstat($);if(!Z.isDirectory()||Z.isSymbolicLink()||(Z.mode&511)!==448||process.getuid&&Z.uid!==process.getuid())throw Error("MCP artifact directory ownership or permissions are invalid")}async function C4($,Z,J){let Y=await l0.lstat($);if(!Y.isFile()||Y.isSymbolicLink()||Y.size!==J||(Y.mode&511)!==384||process.getuid&&Y.uid!==process.getuid())throw Error("MCP artifact file ownership or permissions are invalid");if(U5("sha256").update(await l0.readFile($)).digest("hex")!==Z)throw Error("MCP artifact content hash does not match its identity")}class G1{root;exposePaths;initializePromise;artifactCount=0;storedBytes=0;constructor($,Z={}){if(!$||Buffer.byteLength($)>4096)throw Error("MCP artifact Session identity is invalid");let J=U5("sha256").update($).digest("hex");this.root=l1.join(Z.storageRoot??q0(),"mcp-artifacts",J),this.exposePaths=Z.exposePaths??!0}async write($){await this.initialize();let Z=U5("sha256").update($.bytes).digest("hex"),J=l1.join(this.root,`${Z}${u3($.mimeType)}`);try{return await C4(J,Z,$.bytes.length),this.descriptor($,Z,J)}catch(U){if(U.code!=="ENOENT")throw U}if(this.artifactCount>=T4||this.storedBytes+$.bytes.length>j4)throw Error("MCP artifact Session quota exceeded");let Y;try{Y=await l0.open(J,i1.O_CREAT|i1.O_EXCL|i1.O_WRONLY|(i1.O_NOFOLLOW??0),384),await Y.writeFile($.bytes),await Y.sync(),await Y.close(),Y=void 0,await l0.chmod(J,384),this.artifactCount++,this.storedBytes+=$.bytes.length}catch(U){if(await Y?.close().catch(()=>{return}),U.code!=="EEXIST")throw await l0.rm(J,{force:!0}).catch(()=>{return}),U;await C4(J,Z,$.bytes.length)}return this.descriptor($,Z,J)}async initialize(){return this.initializePromise??=this.scan(),this.initializePromise}async scan(){let $=l1.dirname(this.root);await M4($),await M4(this.root);let Z=await l0.readdir(this.root,{withFileTypes:!0}),J=0,Y=0;for(let U of Z){let X=l1.join(this.root,U.name),H=await l0.lstat(X);if(!U.isFile()||H.isSymbolicLink()||(H.mode&511)!==384||process.getuid&&H.uid!==process.getuid())throw Error("MCP artifact store contains an unsafe entry");J++,Y+=H.size}if(J>T4||Y>j4)throw Error("MCP artifact Session quota exceeded");this.artifactCount=J,this.storedBytes=Y}descriptor($,Z,J){return{id:Z,kind:$.kind,size:$.bytes.length,sha256:Z,persisted:!0,...$.mimeType?{mimeType:$.mimeType}:{},...$.sourceUri?{sourceUri:$.sourceUri}:{},...this.exposePaths?{path:J}:{}}}}import P4 from"node:path";import d3 from"fs/promises";import m3 from"path";var f4=u("General");function X5($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function R4($){if(!X5($))throw Error("MCP configuration must be an object");if(typeof $.name==="string"&&typeof $.type==="string"){let{name:Y,...U}=$;return{[Y]:U}}let Z=X5($.mcpServers)?$.mcpServers:$,J={};for(let[Y,U]of Object.entries(Z)){if(!Y.trim()||!X5(U))throw Error(`Invalid MCP server configuration: ${Y||"<empty>"}`);J[Y]=U}return J}async function g3($){if($.trim().startsWith("{"))return R4(JSON.parse($));let Z=m3.resolve(n1(),$),J=await d3.readFile(Z,"utf-8");return R4(JSON.parse(J))}async function S4($,Z={}){let J={...Z};for(let Y of $)try{let U=await g3(Y);J={...J,...U},f4.debug(`[OK] Loaded MCP config from CLI: ${Object.keys(U).join(", ")}`)}catch(U){f4.warn(`[WARN] Failed to load MCP config "${Y}":`,U)}return J}async function p3($){let Z={};for(let J of await c1($))Object.assign(Z,J.mcpServers??{});return Z}async function r1($){let Z={};if(!$.strictCliConfig)Z={...await t.getInstance().loadWorkspaceMcpServers($.workspaceRoot,$.storeServers),...await p3($.workspaceRoot),...$.sessionServers??{}};if($.cliConfigs?.length)Z=await S4($.cliConfigs,Z);return Object.fromEntries(Object.entries(Z).map(([J,Y])=>{v4(Y);let U={...Y,...Y.oauth?{oauth:k4(Y)}:{},...Y.sampling?{sampling:I4(Y.sampling)}:{}};return[J,U.type==="stdio"?{...U,cwd:U.cwd?P4.resolve($.workspaceRoot,U.cwd):P4.resolve($.workspaceRoot)}:U]}))}function y4(){return`You are Blade Code, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
|
|
10
10
|
|
|
11
11
|
IMPORTANT: Assist with authorized security testing, defensive security, CTF challenges, and educational contexts. Refuse requests for destructive techniques, DoS attacks, mass targeting, supply chain compromise, or detection evasion for malicious purposes. Dual-use security tools (C2 frameworks, credential testing, exploit development) require clear authorization context: pentesting engagements, CTF competitions, security research, or defensive use cases.
|
|
12
12
|
IMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming. You may use URLs provided by the user in their messages or local files.`}function x4(){return`# System
|
|
@@ -159,9 +159,9 @@ ${z.content}
|
|
|
159
159
|
</instruction-file>`}).join(`
|
|
160
160
|
|
|
161
161
|
`)}
|
|
162
|
-
</project-instructions>`,files:Q,contentBytes:Z-H}}var $J=/<available_skills>\s*<\/available_skills>/;async function k$($={}){let{projectPath:Z,replaceDefault:J,append:Y,mode:U,includeEnvironment:X=!0,environmentOptions:H,language:Q,projectTrusted:W,projectRuleCatalog:z,projectInstructionSourcePath:V,availableSkills:B,communicationStyle:K="auto",communicationStyleCatalog:G}=$,O=[],E=[],q=U==="plan",F,D;if(q)F=i4,D="plan_mode_prompt";else F=J??c4,D=J?"replace_default":"default";O.push(F),E.push({name:D,loaded:!0,length:F.length});let L=a4(K,G);if(L)O.push(L),E.push({name:"communication_style",loaded:!0,length:L.length});else E.push({name:"communication_style",loaded:!1});let A=Z!==void 0&&(W??(await
|
|
162
|
+
</project-instructions>`,files:Q,contentBytes:Z-H}}var $J=/<available_skills>\s*<\/available_skills>/;async function k$($={}){let{projectPath:Z,replaceDefault:J,append:Y,mode:U,includeEnvironment:X=!0,environmentOptions:H,language:Q,projectTrusted:W,projectRuleCatalog:z,projectInstructionSourcePath:V,availableSkills:B,communicationStyle:K="auto",communicationStyleCatalog:G}=$,O=[],E=[],q=U==="plan",F,D;if(q)F=i4,D="plan_mode_prompt";else F=J??c4,D=J?"replace_default":"default";O.push(F),E.push({name:D,loaded:!0,length:F.length});let L=a4(K,G);if(L)O.push(L),E.push({name:"communication_style",loaded:!0,length:L.length});else E.push({name:"communication_style",loaded:!1});let A=Z!==void 0&&(W??(await j0.getInstance().getStatus(Z)).state==="trusted");if(Z&&A){let T=z?z.staticRules(V??Z):await n4(Z);if(T&&T.files.length>0)O.push(T.content),E.push({name:"project_instructions",loaded:!0,length:T.content.length});else E.push({name:"project_instructions",loaded:!1})}else if(Z)E.push({name:"project_instructions",loaded:!1});if(Z&&process.env.BLADE_AUTO_MEMORY!=="0")try{let b=await new q$(Z).loadIndex();if(b)O.push(`<auto-memory>
|
|
163
163
|
${b}
|
|
164
|
-
</auto-memory>`),E.push({name:"auto_memory",loaded:!0,length:b.length});else E.push({name:"auto_memory",loaded:!1})}catch{E.push({name:"auto_memory",loaded:!1})}if(X){let
|
|
164
|
+
</auto-memory>`),E.push({name:"auto_memory",loaded:!0,length:b.length});else E.push({name:"auto_memory",loaded:!1})}catch{E.push({name:"auto_memory",loaded:!1})}if(X){let T=r4(Z?{...H,workingDirectory:Z}:H);if(T)O.push(T),E.push({name:"environment",loaded:!0,length:T.length})}if(Y?.trim())O.push(Y.trim()),E.push({name:"append",loaded:!0,length:Y.trim().length});let w=O.join(`
|
|
165
165
|
|
|
166
166
|
---
|
|
167
167
|
|
|
@@ -188,8 +188,8 @@ ${z.content}`).join(`
|
|
|
188
188
|
|
|
189
189
|
[... and ${Z.length-J} more files matched]`:"";return{type:"file",path:$,content:Q+W,metadata:{lines:X.reduce((z,V)=>z+V.lines,0),truncated:Z.length>J||X.some((z)=>z.truncated)}}}clearExpiredCache(){let $=Date.now(),Z=0;for(let[J,Y]of this.fileCache.entries())if($-Y.timestamp>60000)this.fileCache.delete(J),Z++;if(Z>0)y0.debug(`Cleared ${Z} expired cache entries`)}clearCache(){this.fileCache.clear(),y0.debug("Cleared all cache")}getCacheStats(){return{size:this.fileCache.size,keys:Array.from(this.fileCache.keys())}}}import{createHash as W5,randomUUID as XJ}from"node:crypto";import{constants as Q5,promises as l}from"node:fs";import x0 from"node:path";import HJ from"write-file-atomic";import{realpathSync as UJ}from"node:fs";import s1 from"node:path";var H5=u("Execution");class f0{static instance=null;locks=new Map;constructor(){}static getInstance(){if(!f0.instance)f0.instance=new f0;return f0.instance}async acquireLock($,Z){let J=t1($),Y=this.locks.get(J),U,X=new Promise((H)=>{U=H});if(this.locks.set(J,X),Y)await Y;try{return await this.executeWithLock(J,Z)}finally{if(U(),this.locks.get(J)===X)this.locks.delete(J)}}acquireLocks($,Z){let J=[...new Set($.map(t1))].sort((U,X)=>U.localeCompare(X)),Y=(U)=>U>=J.length?Z():this.acquireLock(J[U],()=>Y(U+1));return Y(0)}async executeWithLock($,Z){H5.debug(`获取文件锁: ${$}`);try{let J=await Z();return H5.debug(`释放文件锁: ${$}`),J}catch(J){throw H5.debug(`操作失败,释放文件锁: ${$}`),J}}isLocked($){return this.locks.has(t1($))}clearLock($){this.locks.delete(t1($))}clearAll(){this.locks.clear()}getLockedFiles(){return Array.from(this.locks.keys())}getLockedFileCount(){return this.locks.size}static resetInstance(){f0.instance=null}}function t1($){let Z=s1.resolve($),J=[],Y=Z;while(!0){try{return s1.join(UJ.native(Y),...J.reverse())}catch(X){let H=X.code;if(H!=="ENOENT"&&H!=="ENOTDIR")return Z}let U=s1.dirname(Y);if(U===Y)return Z;J.push(s1.basename(Y)),Y=U}}var $Z=1,QJ=1e4,WJ=50,zJ=30000;async function z5($,Z){let J=K5($);await _5(J);let Y=x0.join(J,".operation.lock"),U=XJ(),X=Date.now()+QJ;while(Date.now()<X){let H;try{H=await l.open(Y,Q5.O_CREAT|Q5.O_EXCL|Q5.O_WRONLY,384),await H.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:U,createdAt:new Date().toISOString()})}
|
|
190
190
|
`,"utf8"),await H.sync(),await H.close(),H=void 0}catch(Q){if(await H?.close().catch(()=>{return}),Q.code!=="EEXIST")throw await l.rm(Y,{force:!0}).catch(()=>{return}),Q;await _J(Y),await new Promise((W)=>setTimeout(W,WJ));continue}try{return await Z()}finally{await KJ(Y,U)}}throw Error("ApplyPatch workspace is busy in another Blade process")}async function ZZ($,Z,J,Y,U){let X=K5($);await _5(X);let H={version:$Z,transactionId:Z,workspaceRoot:$,phase:"preparing",ownerPid:process.pid,createdAt:new Date().toISOString(),entries:J.changes.map((W)=>({path:W.path,...Y.get(W.path)?{stagePath:Y.get(W.path)}:{},...U.get(W.path)?{backupPath:U.get(W.path)}:{},oldExisted:W.oldContent!==null,...W.newContent!==null?{newContentHash:W5("sha256").update(W.newContent).digest("hex")}:{}}))},Q=x0.join(X,`${Z}.json`);return await UZ(Q,H),{filePath:Q,journal:H}}async function JZ($){$.journal.phase="committed",await UZ($.filePath,$.journal)}async function V5($){await l.rm($.filePath,{force:!0})}async function YZ($){let Z;try{Z=await l.realpath($)}catch{return 0}return z5(Z,()=>B5(Z))}async function B5($){let Z=K5($),J;try{J=await l.readdir(Z)}catch(U){if(U.code==="ENOENT")return 0;throw U}let Y=0;for(let U of J.filter((X)=>X.endsWith(".json"))){let X=x0.join(Z,U),H=await BJ(X,$);await f0.getInstance().acquireLocks(H.entries.map((Q)=>Q.path),()=>VJ(H)),await l.rm(X,{force:!0}),Y++}return Y}async function VJ($){let Z=[];for(let J of[...$.entries].reverse())try{if($.phase==="preparing"){if(J.backupPath&&await e4(J.backupPath))await l.rm(J.path,{force:!0}),await l.rename(J.backupPath,J.path);else if(!J.oldExisted&&J.newContentHash&&!(J.stagePath&&await e4(J.stagePath))&&await OJ(J.path)===J.newContentHash)await l.rm(J.path,{force:!0})}if(J.stagePath)await l.rm(J.stagePath,{force:!0});if(J.backupPath)await l.rm(J.backupPath,{force:!0})}catch(Y){Z.push(Y)}if(Z.length>0)throw AggregateError(Z,`Failed to recover ApplyPatch transaction ${$.transactionId}`)}async function BJ($,Z){let J=await l.lstat($);if(!J.isFile()||J.isSymbolicLink()||(J.mode&511)!==384||process.getuid&&J.uid!==process.getuid())throw Error("ApplyPatch journal ownership or permissions are invalid");let Y=JSON.parse(await l.readFile($,"utf8"));if(Y.version!==$Z||typeof Y.transactionId!=="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(Y.transactionId)||Y.workspaceRoot!==Z||Y.phase!=="preparing"&&Y.phase!=="committed"||!Array.isArray(Y.entries))throw Error("ApplyPatch journal is invalid");for(let U of Y.entries)if(!U||typeof U.path!=="string"||!x0.isAbsolute(U.path)||typeof U.oldExisted!=="boolean"||U.stagePath!==void 0&&typeof U.stagePath!=="string"||U.backupPath!==void 0&&typeof U.backupPath!=="string"||U.newContentHash!==void 0&&(typeof U.newContentHash!=="string"||!/^[a-f0-9]{64}$/.test(U.newContentHash))||!X0.isWithinWorkspace(U.path,Z)||!t4(U.path,U.stagePath,Y.transactionId,"stage")||!t4(U.path,U.backupPath,Y.transactionId,"backup"))throw Error("ApplyPatch journal contains an invalid path");return Y}function t4($,Z,J,Y){if(!Z)return!0;return x0.dirname(Z)===x0.dirname($)&&Z===x0.join(x0.dirname($),`.${x0.basename($)}.blade-patch-${J}.${Y}`)}async function UZ($,Z){await _5(x0.dirname($)),await HJ($,`${JSON.stringify(Z)}
|
|
191
|
-
`,{mode:384}),await l.chmod($,384)}function K5($){let Z=W5("sha256").update($).digest("hex").slice(0,32);return x0.join(q0(),"patch-transactions",Z)}async function _5($){await l.mkdir($,{recursive:!0,mode:448});let Z=await l.lstat($);if(!Z.isDirectory()||Z.isSymbolicLink()||(Z.mode&511)!==448||process.getuid&&Z.uid!==process.getuid())throw Error("ApplyPatch transaction directory ownership or permissions are invalid")}async function KJ($,Z){try{if(JSON.parse(await l.readFile($,"utf8")).token===Z)await l.rm($,{force:!0})}catch(J){if(J.code!=="ENOENT")throw J}}async function _J($){let Z;try{Z=await l.lstat($)}catch(Y){if(Y.code==="ENOENT")return;throw Y}if(!Z.isFile()||Z.isSymbolicLink()||(Z.mode&511)!==384||process.getuid&&Z.uid!==process.getuid())throw Error("ApplyPatch workspace lock ownership or permissions are invalid");let J;try{let Y=JSON.parse(await l.readFile($,"utf8"));if(typeof Y.pid==="number"&&Number.isInteger(Y.pid))J=Y.pid}catch{}if(J&&GJ(J))return;if(!J&&Date.now()-Z.mtimeMs<zJ)return;await l.rm($,{force:!0})}function GJ($){try{return process.kill($,0),!0}catch(Z){return Z.code==="EPERM"}}async function e4($){try{return await l.lstat($),!0}catch(Z){if(Z.code==="ENOENT")return!1;throw Z}}async function OJ($){try{return W5("sha256").update(await l.readFile($)).digest("hex")}catch(Z){if(Z.code==="ENOENT")return;throw Z}}import*as b9 from"os";import*as
|
|
192
|
-
`)}var G5=
|
|
191
|
+
`,{mode:384}),await l.chmod($,384)}function K5($){let Z=W5("sha256").update($).digest("hex").slice(0,32);return x0.join(q0(),"patch-transactions",Z)}async function _5($){await l.mkdir($,{recursive:!0,mode:448});let Z=await l.lstat($);if(!Z.isDirectory()||Z.isSymbolicLink()||(Z.mode&511)!==448||process.getuid&&Z.uid!==process.getuid())throw Error("ApplyPatch transaction directory ownership or permissions are invalid")}async function KJ($,Z){try{if(JSON.parse(await l.readFile($,"utf8")).token===Z)await l.rm($,{force:!0})}catch(J){if(J.code!=="ENOENT")throw J}}async function _J($){let Z;try{Z=await l.lstat($)}catch(Y){if(Y.code==="ENOENT")return;throw Y}if(!Z.isFile()||Z.isSymbolicLink()||(Z.mode&511)!==384||process.getuid&&Z.uid!==process.getuid())throw Error("ApplyPatch workspace lock ownership or permissions are invalid");let J;try{let Y=JSON.parse(await l.readFile($,"utf8"));if(typeof Y.pid==="number"&&Number.isInteger(Y.pid))J=Y.pid}catch{}if(J&&GJ(J))return;if(!J&&Date.now()-Z.mtimeMs<zJ)return;await l.rm($,{force:!0})}function GJ($){try{return process.kill($,0),!0}catch(Z){return Z.code==="EPERM"}}async function e4($){try{return await l.lstat($),!0}catch(Z){if(Z.code==="ENOENT")return!1;throw Z}}async function OJ($){try{return W5("sha256").update(await l.readFile($)).digest("hex")}catch(Z){if(Z.code==="ENOENT")return;throw Z}}import*as b9 from"os";import*as T9 from"path";var QZ=new Set(["temperature","maxOutputTokens","timeout","theme","uiTheme","language","fontSize","debug","autoSaveSessions","maxTurns","disableAllHooks","permissions","hooks","env","mcpServers"]),EJ=new Set(["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"]),qJ=_.Object({operation:d(["get","set","list"],{description:"操作类型: get(读取)/ set(设置)/ list(列举可配置项)"}),key:_.Optional(_.String({description:'配置键名,支持点号嵌套(如 hooks.PreToolUse)。get 时用 "*" 获取全部配置'})),value:_.Optional(_.Unknown({description:"要设置的值(仅 set 操作需要)"})),scope:_.Optional(d(["local","project","global"],{description:"持久化范围: local(.blade/settings.local.json)/ project(.blade/settings.json)/ global(~/.blade/)"}))});function XZ($){return{...$}}function HZ($,Z){let J=Z.split("."),Y=$;for(let U of J){if(Y===null||Y===void 0||typeof Y!=="object")return;Y=Y[U]}return Y}function FJ($){let Z=["可配置项列表(白名单):",""];for(let J of QZ){let Y=$[J],U=Y===void 0?"(未设置)":JSON.stringify(Y,null,2),X=U.length>200?`${U.slice(0,197)}...`:U;Z.push(`- ${J}: ${X}`)}return Z.join(`
|
|
192
|
+
`)}var G5=j({name:"ConfigTool",displayName:"Config",kind:"execute",isConcurrencySafe:!1,schema:qJ,description:{short:"Read, update, or list Blade configuration",long:"Manage Blade configuration: get reads a config value, set updates a whitelisted config field (with persistence), list enumerates all settable keys and their current values.",usageNotes:['Use operation="get" with key="*" to dump all config','Use operation="get" with a dotted key like "hooks.PreToolUse"','Use operation="set" with key and value to update config','Use operation="list" to see all settable keys',"The scope option controls persistence: local/project/global","models and currentModelId must be modified through model management"],examples:[{description:"Get all configuration",params:{operation:"get",key:"*"}},{description:"Get a specific config value",params:{operation:"get",key:"hooks"}},{description:"Set temperature",params:{operation:"set",key:"temperature",value:0.7,scope:"global"}},{description:"List all settable keys",params:{operation:"list"}}]},async execute($,Z){let{operation:J,key:Y,value:U,scope:X}=$,H=W0();if(!H)return{success:!1,llmContent:"Config not initialized. Please wait for Blade to finish starting.",error:{message:"Config not initialized",type:"execution_error"},metadata:{summary:"配置未初始化"}};switch(J){case"get":{if(!Y)return{success:!1,llmContent:'Missing "key" parameter for get operation. Use key="*" to get all config.',error:{message:"Missing key",type:"validation_error"},metadata:{summary:"缺少 key 参数"}};if(Y==="*"){let V=XZ(H);return{success:!0,llmContent:JSON.stringify(V,null,2),metadata:{summary:"获取全部配置"}}}let Q=H;if(Y.split(".")[0]==="models"){let V=XZ(Q),B=HZ(V,Y);return{success:!0,llmContent:JSON.stringify(B,null,2),metadata:{summary:`获取配置: ${Y}`}}}let z=HZ(Q,Y);if(z===void 0)return{success:!0,llmContent:`Config key "${Y}" is not set or does not exist.`,metadata:{summary:`配置项 ${Y} 不存在`}};return{success:!0,llmContent:JSON.stringify(z,null,2),metadata:{summary:`获取配置: ${Y}`}}}case"set":{if(!Y)return{success:!1,llmContent:'Missing "key" parameter for set operation.',error:{message:"Missing key",type:"validation_error"},metadata:{summary:"缺少 key 参数"}};if(U===void 0)return{success:!1,llmContent:'Missing "value" parameter for set operation.',error:{message:"Missing value",type:"validation_error"},metadata:{summary:"缺少 value 参数"}};let Q=Y.split(".")[0];if(Q==="models"||Q==="currentModelId")return{success:!1,llmContent:'Refused: "models" and "currentModelId" cannot be modified via ConfigTool to protect API keys. Use the /model slash command instead.',error:{message:"Forbidden key: models",type:"permission_denied"},metadata:{summary:"拒绝修改 models"}};if(EJ.has(Q))return{success:!1,llmContent:`Refused: "${Q}" is a runtime-only field and cannot be persisted via ConfigTool.`,error:{message:`Forbidden runtime key: ${Q}`,type:"permission_denied"},metadata:{summary:`拒绝修改运行时字段: ${Q}`}};if(!QZ.has(Q))return{success:!1,llmContent:`Key "${Q}" is not in the settable whitelist. Use operation="list" to see all allowed keys.`,error:{message:`Key not settable: ${Q}`,type:"validation_error"},metadata:{summary:`不可设置的 key: ${Q}`}};let W;if(Y.includes(".")){let z=Y.split(".");if(W={[z[0]]:U},z.length===2){let V=H[z[0]];if(typeof V==="object"&&V!==null)W={[z[0]]:{...V,[z[1]]:U}};else W={[z[0]]:{[z[1]]:U}}}}else W={[Y]:U};try{await F$().updateConfig(W,X?{scope:X}:{});let z=JSON.stringify(U).length>200?`${JSON.stringify(U).slice(0,197)}...`:JSON.stringify(U);return{success:!0,llmContent:`Config updated: ${Y} = ${z}`+(X?` (scope: ${X})`:""),metadata:{summary:`配置已更新: ${Y}`}}}catch(z){let V=z instanceof Error?z.message:String(z);return{success:!1,llmContent:`Failed to update config: ${V}`,error:{message:V,type:"execution_error"},metadata:{summary:`配置更新失败: ${Y}`}}}}case"list":return{success:!0,llmContent:FJ(H),metadata:{summary:"列举可配置项"}};default:return{success:!1,llmContent:`Unknown operation: ${J}`,error:{message:`Unknown operation: ${J}`,type:"validation_error"},metadata:{summary:`未知操作: ${J}`}}}}});import{promises as RJ}from"node:fs";import v$ from"node:path";import*as SZ from"diff";import WZ from"node:path";var zZ="*** Begin Patch",VZ="*** End Patch",E5="*** Add File: ",q5="*** Delete File: ",F5="*** Update File: ",BZ="*** Move to: ",DJ="*** End of File",KZ=1048576,_Z=100,GZ=1000,OZ=50000;class J0 extends Error{line;constructor($,Z){super(Z?`Invalid patch at line ${Z}: ${$}`:`Invalid patch: ${$}`);this.line=Z;this.name="ApplyPatchParseError"}}function D5($){if($.includes("\x00"))throw new J0("null bytes are not allowed");if(Buffer.byteLength($,"utf8")>KZ)throw new J0(`patch exceeds the ${KZ} byte limit`);let J=$.replace(/\r\n/g,`
|
|
193
193
|
`).split(`
|
|
194
194
|
`);if(J.at(-1)==="")J.pop();if(J.length>OZ)throw new J0(`patch exceeds the ${OZ} line limit`);if(J[0]!==zZ)throw new J0(`first line must be "${zZ}"`,1);if(J.at(-1)!==VZ)throw new J0(`last line must be "${VZ}"`,J.length);let Y=[],U=0,X=1;while(X<J.length-1){if(Y.length>=_Z)throw new J0(`patch exceeds the ${_Z} file operation limit`,X+1);let H=J[X],Q=X+1;if(H.startsWith(E5)){let W=e1(H.slice(E5.length),Q);X++;let z=[];while(X<J.length-1&&!O5(J[X])){let V=J[X];if(!V.startsWith("+"))throw new J0('every Add File content line must start with "+"',X+1);z.push(V.slice(1)),X++}if(z.length===0)throw new J0('Add File requires at least one "+" content line',Q);Y.push({kind:"add",path:W,content:`${z.join(`
|
|
195
195
|
`)}
|
|
@@ -203,14 +203,14 @@ ${G}`:"insertion point could not be resolved")}if(V.hasChange)H.splice(K,V.oldLi
|
|
|
203
203
|
`),J=$.indexOf(`
|
|
204
204
|
`);return Z>=0&&Z===J-1?`\r
|
|
205
205
|
`:`
|
|
206
|
-
`}var bZ=10485760,FZ=33554432,LJ=new Set([".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"]),NJ={lstat:($)=>z0.lstat($),readFile:($)=>z0.readFile($),writeFile:($,Z,J)=>z0.writeFile($,Z,J),mkdir:($)=>z0.mkdir($),rename:($,Z)=>z0.rename($,Z),rm:($,Z)=>z0.rm($,Z),rmdir:($)=>z0.rmdir($),syncFile:async($)=>{let Z=await z0.open($,"r");try{await Z.sync()}finally{await Z.close()}},syncDirectory:async($)=>{let Z=await z0.open($,"r");try{await Z.sync()}finally{await Z.close()}}};async function
|
|
206
|
+
`}var bZ=10485760,FZ=33554432,LJ=new Set([".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"]),NJ={lstat:($)=>z0.lstat($),readFile:($)=>z0.readFile($),writeFile:($,Z,J)=>z0.writeFile($,Z,J),mkdir:($)=>z0.mkdir($),rename:($,Z)=>z0.rename($,Z),rm:($,Z)=>z0.rm($,Z),rmdir:($)=>z0.rmdir($),syncFile:async($)=>{let Z=await z0.open($,"r");try{await Z.sync()}finally{await Z.close()}},syncDirectory:async($)=>{let Z=await z0.open($,"r");try{await Z.sync()}finally{await Z.close()}}};async function TZ($,Z,J){let Y=await z0.realpath(Z),U=[];for(let Q of $){J?.throwIfAborted();let W=await DZ(Q.path,Y),z=Q.kind==="update"&&Q.movePath?await DZ(Q.movePath,Y):void 0;U.push({operation:Q,sourcePath:W,movePath:z})}fZ(U.flatMap(({sourcePath:Q,movePath:W})=>W?[Q,W]:[Q]));let X=[],H=0;for(let Q of U){J?.throwIfAborted();let{operation:W,sourcePath:z,movePath:V}=Q;if(W.kind==="add"){await wZ(z),H+=Buffer.byteLength(W.content),X.push({kind:"add",path:z,oldContent:null,newContent:W.content,mode:420});continue}let B=await TJ(z);if(H+=Buffer.byteLength(B.content),W.kind==="delete"){X.push({kind:"delete",path:z,oldContent:B.content,newContent:null,mode:B.mode});continue}let K=A5(B.content,W.chunks,W.path);if(H+=Buffer.byteLength(K),V)await wZ(V),X.push({kind:"delete",path:z,oldContent:B.content,newContent:null,mode:B.mode},{kind:"add",path:V,oldContent:null,newContent:K,mode:B.mode});else{if(K===B.content)throw Error(`Patch does not change ${W.path}`);X.push({kind:"update",path:z,oldContent:B.content,newContent:K,mode:B.mode})}}return RZ(H),{workspaceRoot:Y,changes:X,affectedPaths:X.map((Q)=>Q.path).sort()}}async function jZ($,Z,J,Y){if($.some((Q)=>Q.kind!=="update"||Q.movePath))throw Error("ACP remote ApplyPatch supports Update File operations only because the ACP filesystem protocol does not provide atomic add, delete, or rename primitives");let U=$.map((Q)=>bJ(Q.path,Z));fZ(U);let X=[],H=0;for(let Q=0;Q<$.length;Q++){Y?.throwIfAborted();let W=$[Q];if(W.kind!=="update")continue;let z=U[Q],V=await J.readTextFile(z);fJ(V,W.path);let B=A5(V,W.chunks,W.path);if(B===V)throw Error(`Patch does not change ${W.path}`);H+=Buffer.byteLength(V,"utf8")+Buffer.byteLength(B,"utf8"),X.push({kind:"update",path:z,oldContent:V,newContent:B})}return RZ(H),{workspaceRoot:Z,changes:X,affectedPaths:X.map((Q)=>Q.path).sort()}}async function MZ($,Z,J=NJ){let Y=AJ(12),U=new Map($.changes.filter((V)=>V.newContent!==null).map((V)=>[V.path,LZ(V.path,Y,"stage")])),X=new Map($.changes.filter((V)=>V.oldContent!==null).map((V)=>[V.path,LZ(V.path,Y,"backup")])),H=new Set,Q=[],W;try{for(let V of $.changes){if(Z?.throwIfAborted(),V.newContent===null)continue;await MJ(D0.dirname(V.path),Q,J)}W=await ZZ($.workspaceRoot,Y,$,U,X);for(let V of $.changes){if(Z?.throwIfAborted(),V.newContent===null)continue;let B=U.get(V.path);await J.writeFile(B,V.newContent,{flag:"wx",mode:V.mode??420}),await J.syncFile(B),U.set(V.path,B)}await jJ($,J),Z?.throwIfAborted();for(let V of $.changes){if(V.oldContent===null)continue;let B=X.get(V.path);await J.rename(V.path,B),X.set(V.path,B)}await AZ($,J);for(let V of $.changes){Z?.throwIfAborted();let B=U.get(V.path);if(!B)continue;await J.rename(B,V.path),H.add(V.path)}await AZ($,J),await JZ(W)}catch(V){let B=await CJ(U,X,H,Q,J);if(B.length>0)throw AggregateError([V,...B],"ApplyPatch failed and the local transaction could not be fully rolled back");if(W)await V5(W);throw V}if((await Promise.allSettled([...X.values()].map((V)=>J.rm(V,{force:!0})))).every((V)=>V.status==="fulfilled")&&W)await V5(W)}async function CZ($,Z,J){let Y=[];try{for(let U of $.changes){if(J?.throwIfAborted(),U.oldContent===null||U.newContent===null)throw Error("ACP remote transaction received an unsupported change");if(await Z.readTextFile(U.path)!==U.oldContent)throw Error(`Remote file changed after patch preflight: ${U.path}`);if(Y.push(U),await Z.writeTextFile(U.path,U.newContent),await Z.readTextFile(U.path)!==U.newContent)throw Error(`Remote write verification failed: ${U.path}`)}}catch(U){let X=[];for(let H of Y.reverse())try{if(await Z.writeTextFile(H.path,H.oldContent),await Z.readTextFile(H.path)!==H.oldContent)throw Error(`Remote rollback verification failed: ${H.path}`)}catch(Q){X.push(Q)}if(X.length>0)throw AggregateError([U,...X],"ApplyPatch failed and the ACP remote transaction could not be fully rolled back");throw U}}async function DZ($,Z){let J=D0.resolve(Z,...$.split("/"));if(!X0.isWithinWorkspace(J,Z)||X0.isRestricted(J)||!await X0.isWithinWorkspaceResolved(J,Z))throw Error(`Patch path is outside or restricted: ${$}`);let Y=[],U=J;while(!0){try{if((await z0.lstat(U)).isSymbolicLink())throw Error(`Symbolic links cannot be patched: ${$}`);let Q=await z0.realpath(U),W=D0.join(Q,...Y.reverse());if(!X0.isWithinWorkspace(W,Z))throw Error(`Patch path escapes the workspace: ${$}`);return W}catch(H){let Q=H.code;if(Q!=="ENOENT"&&Q!=="ENOTDIR")throw H}let X=D0.dirname(U);if(X===U)throw Error(`Cannot resolve patch path: ${$}`);Y.push(D0.basename(U)),U=X}}function bJ($,Z){if($.split("/").some((H)=>LJ.has(H)))throw Error(`Patch path is restricted: ${$}`);let J=/^[A-Za-z]:[\\/]/.test(Z)?D0.win32:D0.posix;if(!J.isAbsolute(Z))throw Error("ACP workspace root must be absolute");let Y=J.resolve(Z),U=J.resolve(Y,...$.split("/")),X=J.relative(Y,U);if(X===".."||X.startsWith(`..${J.sep}`)||J.isAbsolute(X))throw Error(`Patch path escapes the ACP workspace: ${$}`);return U}async function TJ($){let Z=await z0.lstat($);if(!Z.isFile()||Z.isSymbolicLink())throw Error(`Patch target is not a regular file: ${$}`);if(Z.size>bZ)throw Error(`Patch target exceeds the file size limit: ${$}`);let J=await z0.readFile($);if(!NZ(J))throw Error(`ApplyPatch supports UTF-8 text files only: ${$}`);return{content:J.toString("utf8"),mode:Z.mode&511}}async function wZ($){try{await z0.lstat($)}catch(Z){if(Z.code==="ENOENT")return;throw Z}throw Error(`Add File target already exists: ${$}`)}function fZ($){let Z=new Set,J=process.platform==="win32"||$.some((Y)=>/^[A-Za-z]:\\/.test(Y));for(let Y of $){let U=J?Y.toLowerCase():Y;if(Z.has(U))throw Error(`Patch contains overlapping file operations: ${Y}`);Z.add(U)}}async function jJ($,Z){for(let J of $.changes){if(J.oldContent===null){try{await Z.lstat(J.path)}catch(X){if(X.code==="ENOENT")continue;throw X}throw Error(`File appeared after patch preflight: ${J.path}`)}let Y=await Z.lstat(J.path);if(!Y.isFile()||Y.isSymbolicLink())throw Error(`Patch target changed type after preflight: ${J.path}`);let U=await Z.readFile(J.path);if(!NZ(U)||U.toString("utf8")!==J.oldContent)throw Error(`File changed after patch preflight: ${J.path}`)}}async function MJ($,Z,J){let Y=[],U=$;while(!0){try{let H=await J.lstat(U);if(!H.isDirectory()||H.isSymbolicLink())throw Error(`Patch parent is not a regular directory: ${U}`);break}catch(H){if(H.code!=="ENOENT")throw H}Y.push(U);let X=D0.dirname(U);if(X===U)throw Error(`Cannot create patch parent: ${$}`);U=X}for(let X of Y.reverse())await J.mkdir(X),Z.push(X)}async function CJ($,Z,J,Y,U){let X=[];for(let H of J)await U.rm(H,{force:!0}).catch((Q)=>X.push(Q));for(let[H,Q]of[...Z].reverse())try{await U.rm(H,{force:!0}),await U.rename(Q,H)}catch(W){X.push(W)}for(let H of $.values())await U.rm(H,{force:!0}).catch((Q)=>X.push(Q));for(let H of Y.reverse())await U.rmdir(H).catch((Q)=>{let W=Q.code;if(W!=="ENOTEMPTY"&&W!=="ENOENT")X.push(Q)});return await Promise.allSettled([...new Set([...Z.keys(),...J].map((H)=>D0.dirname(H)))].map((H)=>U.syncDirectory(H))),X}async function AZ($,Z){for(let J of[...new Set($.changes.map((Y)=>D0.dirname(Y.path)))])await Z.syncDirectory(J)}function LZ($,Z,J){return D0.join(D0.dirname($),`.${D0.basename($)}.blade-patch-${Z}.${J}`)}function fJ($,Z){if(Buffer.byteLength($,"utf8")>bZ)throw Error(`Patch target exceeds the file size limit: ${Z}`)}function RZ($){if($>FZ)throw Error(`Patch transaction exceeds the ${FZ} byte limit`)}var N5=j({name:"ApplyPatch",displayName:"Apply Patch",kind:"write",strict:!0,isConcurrencySafe:!0,parallelism:"shared",schema:_.Object({patch:_.String({minLength:1,description:"A complete *** Begin Patch / *** End Patch document containing relative file operations"})}),affectedPaths:({patch:$})=>L5($),extractSignatureContent:({patch:$})=>{let Z=L5($),J=Z.slice(0,5).join(", ");return Z.length>5?`${J} (+${Z.length-5} more)`:J||"invalid patch"},description:{short:"Atomically applies a multi-file text patch",long:"Parses and preflights the complete patch before changing files. Local changes use sorted multi-path locks, same-directory staging, backups, and rollback. ACP remote files support update-only transactions with verified compensating rollback because ACP has no delete or rename API.",usageNotes:["Use relative POSIX paths only. Absolute paths and traversal are rejected.","Use *** Add File, *** Delete File, or *** Update File sections.","Update hunks begin with @@ and every hunk line begins with space, -, or +.","Existing local files must have been read in this Session before patching.","The full patch is all-or-nothing; any parse, context, path, or commit failure rolls back."],examples:[{description:"Update one file and add another",params:{patch:`*** Begin Patch
|
|
207
207
|
*** Update File: src/app.ts
|
|
208
208
|
@@
|
|
209
209
|
-const ready = false;
|
|
210
210
|
+const ready = true;
|
|
211
211
|
*** Add File: src/value.ts
|
|
212
212
|
+export const value = 1;
|
|
213
|
-
*** End Patch`}}],important:["Do not wrap the patch in a shell command or Markdown fence.","A failed transaction never intentionally leaves a committed prefix."]},async execute($,Z){let J=Z.workspaceRoot;if(!J)return $2("ApplyPatch requires a Session workspace root");let Y=Z.signal??new AbortController().signal;try{let U=D5($.patch),X=a(Z.sessionId),H=X?E$(Z.sessionId):O$(),Q=X&&H instanceof K1&&H.usesRemoteFiles(),W=Q?J:await RJ.realpath(J),z=L5($.patch).map((V)=>SJ(W,V));return await z5(W,async()=>{if(Y.throwIfAborted(),!Q)await B5(W);return f0.getInstance().acquireLocks(z,async()=>{let V;if(Q){if(!H.canReadTextFile()||!H.canWriteTextFile())return $2("ACP remote ApplyPatch requires both readTextFile and writeTextFile capabilities");Z.updateOutput?.("Preflighting remote patch..."),V=await
|
|
213
|
+
*** End Patch`}}],important:["Do not wrap the patch in a shell command or Markdown fence.","A failed transaction never intentionally leaves a committed prefix."]},async execute($,Z){let J=Z.workspaceRoot;if(!J)return $2("ApplyPatch requires a Session workspace root");let Y=Z.signal??new AbortController().signal;try{let U=D5($.patch),X=a(Z.sessionId),H=X?E$(Z.sessionId):O$(),Q=X&&H instanceof K1&&H.usesRemoteFiles(),W=Q?J:await RJ.realpath(J),z=L5($.patch).map((V)=>SJ(W,V));return await z5(W,async()=>{if(Y.throwIfAborted(),!Q)await B5(W);return f0.getInstance().acquireLocks(z,async()=>{let V;if(Q){if(!H.canReadTextFile()||!H.canWriteTextFile())return $2("ACP remote ApplyPatch requires both readTextFile and writeTextFile capabilities");Z.updateOutput?.("Preflighting remote patch..."),V=await jZ(U,W,H,Y)}else{Z.updateOutput?.("Preflighting atomic patch..."),V=await TZ(U,W,Y);let O=PJ(V,W,Z.sessionId);if(O.length>0)return $2(`Read the existing file${O.length===1?"":"s"} before applying this patch:
|
|
214
214
|
${O.join(`
|
|
215
215
|
`)}`,"validation_error")}let B=Q?[]:await kJ(V,Z,W);try{if(Z.updateOutput?.(`Applying ${V.changes.length} atomic file change${V.changes.length===1?"":"s"}...`),Q)await CZ(V,H,Y);else await MZ(V,Y)}catch(O){throw await IJ(B,Z,W),O}let K=await vJ(B,Z,W);await yJ(V,Z.sessionId);let G={kind:"patch",changes:V.changes.map((O)=>({kind:O.kind,path:O.path,oldContent:O.oldContent,newContent:O.newContent,diff:SZ.createTwoFilesPatch(O.path,O.path,O.oldContent??"",O.newContent??"","","",{context:4})})),affected_paths:V.affectedPaths,snapshot_created:K,session_id:Z.sessionId,message_id:Z.messageId,summary:PZ(V,W)};return{success:!0,llmContent:xJ(V,W),metadata:G}})})}catch(U){return $2(U instanceof Error?U.message:String(U),"execution_error")}}});function L5($){try{return[...new Set(EZ($))]}catch{return[]}}function SJ($,Z){return(/^[A-Za-z]:[\\/]/.test($)?v$.win32:v$.posix).resolve($,...Z.split("/"))}function PJ($,Z,J){if(!J)return[];let Y=V0.getInstance();return $.changes.filter((U)=>U.oldContent!==null).filter((U)=>{let X=v$.resolve(Z,v$.relative(Z,U.path));return!Y.hasFileBeenRead(U.path,J)&&!Y.hasFileBeenRead(X,J)}).map((U)=>v$.relative(Z,U.path))}async function kJ($,Z,J){if(!Z.sessionId||!Z.messageId)return[];let Y=new n0({sessionId:Z.sessionId,workspaceRoot:J});await Y.initialize();let U=[];try{for(let X of $.affectedPaths)U.push({path:X,metadata:await Y.createSnapshot(X,Z.messageId)});return U}catch(X){throw await Promise.allSettled(U.map((H)=>Y.discardSnapshot(H.path,H.metadata))),Error(`Cannot create ApplyPatch checkpoint: ${X instanceof Error?X.message:String(X)}`)}}async function vJ($,Z,J){if($.length===0||!Z.sessionId)return!1;let Y=new n0({sessionId:Z.sessionId,workspaceRoot:J});await Y.initialize();let U=await Promise.allSettled($.map((X)=>Y.recordPostEditState(X.path,X.metadata)));return await Promise.allSettled($.filter((X,H)=>U[H]?.status==="rejected").map((X)=>Y.discardSnapshot(X.path,X.metadata))),U.every((X)=>X.status==="fulfilled")}async function IJ($,Z,J){if($.length===0||!Z.sessionId)return;let Y=new n0({sessionId:Z.sessionId,workspaceRoot:J});await Y.initialize(),await Promise.allSettled($.map((U)=>Y.discardSnapshot(U.path,U.metadata)))}async function yJ($,Z){if(!Z)return;let J=V0.getInstance();for(let Y of $.changes)if(Y.newContent===null)J.clearFileRecord(Y.path,Z);else await J.recordFileEdit(Y.path,Z,"edit")}function PZ($,Z){let J={add:$.changes.filter((Y)=>Y.kind==="add").length,update:$.changes.filter((Y)=>Y.kind==="update").length,delete:$.changes.filter((Y)=>Y.kind==="delete").length};return`Applied ${$.changes.length} file changes atomically (${J.add} added, ${J.update} updated, ${J.delete} deleted) in ${v$.basename(Z)}`}function xJ($,Z){let J={add:"A",update:"M",delete:"D"};return[PZ($,Z),...$.changes.map((Y)=>`${J[Y.kind]} ${v$.relative(Z,Y.path)}`)].join(`
|
|
216
216
|
`)}function $2($,Z="execution_error"){return{success:!1,llmContent:$,error:{type:Z,message:$},metadata:{summary:"ApplyPatch failed; no partial patch was accepted"}}}import{basename as uJ,extname as dJ}from"path";var kZ="^(?:/|[A-Za-z]:[\\\\/])",g={filePath:($)=>_.String({minLength:1,pattern:kZ,description:$?.description||"Absolute file path"}),encoding:()=>f(d(["utf8","base64","binary"],{description:"File encoding"}),"utf8"),timeout:($=1000,Z=300000,J=30000)=>f(_.Integer({minimum:$,maximum:Z,description:`Timeout in milliseconds (default ${J}ms)`}),J),pattern:($)=>_.String({minLength:1,description:$?.description||"Regex or glob pattern"}),glob:($)=>_.String({minLength:1,description:$?.description||'Glob pattern (e.g., "*.js", "**/*.ts")'}),lineNumber:($)=>_.Integer({minimum:$?.min??0,description:$?.description||"Line number"}),lineLimit:($)=>_.Integer({minimum:$?.min??1,maximum:$?.max??1e4,description:$?.description||"Limit on lines to read"}),workingDirectory:()=>_.String({minLength:1,pattern:kZ,description:"Absolute working directory"}),environment:()=>_.Optional(_.Record(_.String(),_.String(),{description:"Environment variables (key-value)"})),outputMode:($,Z)=>{let J=d($);return Z===void 0?J:f(J,Z)},flag:($)=>f(_.Boolean({description:$?.description||"Boolean flag"}),$?.defaultValue??!1),url:($)=>_.String({format:"uri",description:$?.description||"URL"}),port:()=>_.Integer({minimum:1,maximum:65535,description:"Port number"}),command:($)=>_.String({minLength:1,description:$?.description||"Command to execute"}),sessionId:()=>_.Optional(_.String({minLength:1,format:"uuid",description:"Session identifier (UUID)"})),nonNegativeInt:($)=>_.Integer({minimum:0,description:$?.description||"Non-negative integer"}),positiveInt:($)=>_.Integer({minimum:1,description:$?.description||"Positive integer"})};import*as b5 from"diff";function vZ($,Z,J=4){if($===Z)return null;let Y=b5.createPatch("file",$,Z,"","",{context:J}),U=Y.split(`
|
|
@@ -253,12 +253,12 @@ ${JSON.stringify({patch:F,startLine:K+1,matchLine:Q+1})}
|
|
|
253
253
|
`);if(hJ(B,K)>=0.85)return V.join(`
|
|
254
254
|
`)}return null}function hJ($,Z){let J=$.split(`
|
|
255
255
|
`),Y=Z.split(`
|
|
256
|
-
`);if(J.length!==Y.length)return 0;if(J.length===0)return 1;let U=0;for(let X=0;X<J.length;X++)if(J[X].trim()===Y[X].trim())U++;return U/J.length}var
|
|
256
|
+
`);if(J.length!==Y.length)return 0;if(J.length===0)return 1;let U=0;for(let X=0;X<J.length;X++)if(J[X].trim()===Y[X].trim())U++;return U/J.length}var T5=j({name:"Edit",displayName:"File Edit",kind:"write",strict:!0,isConcurrencySafe:!1,parallelism:"shared",affectedPaths:($)=>[$.file_path],schema:_.Object({file_path:g.filePath({description:"Absolute path of the file to edit"}),old_string:_.String({minLength:1,description:"String to replace"}),new_string:_.String({description:"Replacement string (can be empty)"}),replace_all:f(_.Boolean({description:"Replace all matches (default: first only)"}),!1)}),description:{short:"Performs exact string replacements in files",long:"Performs exact string replacements in files.",usageNotes:["You must use your Read tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file.","When editing text from Read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: spaces + line number + tab. Everything after that tab is the actual file content to match. Never include any part of the line number prefix in the old_string or new_string.","ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.","Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.","The edit will FAIL if old_string is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use replace_all to change every instance of old_string.","Use replace_all for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance."]},async execute($,Z){let{file_path:J,old_string:Y,new_string:U,replace_all:X}=$,{updateOutput:H,sessionId:Q,messageId:W}=Z,z=Z.signal??new AbortController().signal;try{H?.("Starting to read file...");let V=a(Q),B=V?E$(Q):O$(),K;try{if(V)H?.("通过 IDE 读取文件...");K=await B.readTextFile(J)}catch(C){let S=C;if(S.code==="ENOENT"||S.message?.includes("not found"))return{success:!1,llmContent:`File not found: ${J}`,error:{type:"execution_error",message:"文件不存在"}};throw C}if(typeof z.throwIfAborted==="function")z.throwIfAborted();if(Q){let C=V0.getInstance();if(!C.hasFileBeenRead(J,Q))return{success:!1,llmContent:"You must use your Read tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file.",error:{type:"validation_error",message:"File not read before edit"},metadata:{requiresRead:!0}};let S=await C.checkExternalModification(J,Q);if(S.isExternal)return{success:!1,llmContent:`The file has been modified by an external program since you last read it. You must use the Read tool again to see the current content before editing.
|
|
257
257
|
|
|
258
258
|
Details: ${S.message}`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:S.message}}}}if(Y===U)return{success:!1,llmContent:"New string is identical; no replacement needed",error:{type:"validation_error",message:"新旧字符串相同"}};let G=mJ(K,Y);if(!G.matched){let C=pJ(K,Y,J);return{success:!1,llmContent:C.llmContent,error:{type:"execution_error",message:"未找到匹配内容",details:C.metadata}}}let O=G.matched;if(G.strategy!=="exact")console.log(`[SmartEdit] 使用策略: ${G.strategy}`);let E=gJ(K,O);if(E.length>1&&!X){let C=K.split(`
|
|
259
259
|
`),S=0,p=[];for(let c=0;c<C.length;c++){let U0=C[c],$$=S,b0=S+U0.length;for(let Z$ of E)if(Z$>=$$&&Z$<b0){let r=Math.max(0,c-1),J$=Math.min(C.length-1,c+1),v0=C.slice(r,J$+1).map((n2)=>n2.trim()).join(" ").slice(0,80);p.push({line:c+1,column:Z$-$$+1,context:v0})}S=b0+1}return{success:!1,llmContent:[`[WARN] EDIT PAUSED: old_string matches ${E.length} locations (must be unique).`,"","**Matches found at:**",...p.map((c,U0)=>` ${U0+1}. Line ${c.line}`),"","**Action Required:** Add 3-5 lines of surrounding context to make old_string unique.","","**Tips for quick success:**","• Include the function/class name that wraps the target code","• Add 2-3 lines before and after the target","• Include unique comments or variable names nearby",`• Or use replace_all=true to change all ${E.length} occurrences`,"","**Auto-retry expected** - This usually resolves in 1-2 attempts."].join(`
|
|
260
|
-
`),error:{type:"validation_error",message:"old_string is not unique",details:{matches:p.map((c)=>({line:c.line,column:c.column})),count:E.length}}}}else H?.(`找到 ${E.length} 个匹配项,开始替换...`);let q,F;if(X)q=K.split(O).join(U),F=E.length;else{let C=K.indexOf(O);q=K.substring(0,C)+U+K.substring(C+O.length),F=1}if(typeof z.throwIfAborted==="function")z.throwIfAborted();let D,L,A=!1;if(!V&&Q&&W)try{D=new n0({sessionId:Q,workspaceRoot:Z.workspaceRoot}),await D.initialize(),L=await D.createSnapshot(J,W)}catch(C){console.warn("[EditTool] 创建快照失败:",C),D=void 0,L=void 0}if(V)H?.("通过 IDE 写入文件...");try{await B.writeTextFile(J,q)}catch(C){if(D&&L)await D.discardSnapshot(J,L).catch((S)=>console.warn("[EditTool] 丢弃未完成快照失败:",S));throw C}if(D&&L)try{await D.recordPostEditState(J,L),A=!0}catch(C){console.warn("[EditTool] 完成快照失败:",C),await D.discardSnapshot(J,L).catch((S)=>console.warn("[EditTool] 丢弃未完成快照失败:",S))}if(Q)await V0.getInstance().recordFileEdit(J,Q,"edit");let w=await B.stat(J),
|
|
261
|
-
${
|
|
260
|
+
`),error:{type:"validation_error",message:"old_string is not unique",details:{matches:p.map((c)=>({line:c.line,column:c.column})),count:E.length}}}}else H?.(`找到 ${E.length} 个匹配项,开始替换...`);let q,F;if(X)q=K.split(O).join(U),F=E.length;else{let C=K.indexOf(O);q=K.substring(0,C)+U+K.substring(C+O.length),F=1}if(typeof z.throwIfAborted==="function")z.throwIfAborted();let D,L,A=!1;if(!V&&Q&&W)try{D=new n0({sessionId:Q,workspaceRoot:Z.workspaceRoot}),await D.initialize(),L=await D.createSnapshot(J,W)}catch(C){console.warn("[EditTool] 创建快照失败:",C),D=void 0,L=void 0}if(V)H?.("通过 IDE 写入文件...");try{await B.writeTextFile(J,q)}catch(C){if(D&&L)await D.discardSnapshot(J,L).catch((S)=>console.warn("[EditTool] 丢弃未完成快照失败:",S));throw C}if(D&&L)try{await D.recordPostEditState(J,L),A=!0}catch(C){console.warn("[EditTool] 完成快照失败:",C),await D.discardSnapshot(J,L).catch((S)=>console.warn("[EditTool] 丢弃未完成快照失败:",S))}if(Q)await V0.getInstance().recordFileEdit(J,Q,"edit");let w=await B.stat(J),T=IZ(K,q,O,U,4),b=uJ(J),P=F===1?`替换 1 处匹配到 ${b}`:`替换 ${F} 处匹配到 ${b}`,M={file_path:J,matches_found:E.length,replacements_made:F,replace_all:X,old_string_length:Y.length,new_string_length:U.length,original_size:K.length,new_size:q.length,size_diff:q.length-K.length,last_modified:w?.mtime instanceof Date?w.mtime.toISOString():void 0,snapshot_created:A,session_id:Q,message_id:W,diff_snippet:T,summary:P,kind:"edit",oldContent:K,newContent:q};return{success:!0,llmContent:T?`Edited ${J} (${F} replacement${F>1?"s":""}):
|
|
261
|
+
${T}`:`Edited ${J} (${F} replacement${F>1?"s":""})`,metadata:M}}catch(V){let B=V;if(B.name==="AbortError")return{success:!1,llmContent:"File edit aborted",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`File edit failed: ${B.message}`,error:{type:"execution_error",message:B.message,details:B}}}},version:"2.0.0",category:"文件操作",tags:["file","edit","replace","modify"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let Z=dJ($.file_path);return Z?`**/*${Z}`:"**/*"}});function mZ($){return $.replaceAll("‘","'").replaceAll("’","'").replaceAll("“",'"').replaceAll("”",'"')}function mJ($,Z){if($.includes(Z))return{matched:Z,strategy:"exact"};let J=hZ($,Z);if(J)return{matched:J,strategy:"line_trim"};let Y=mZ(Z),X=mZ($).indexOf(Y);if(X!==-1)return{matched:$.substring(X,X+Z.length),strategy:"normalize_quotes"};let H=yZ(Z);if(H!==Z&&$.includes(H))return{matched:H,strategy:"unescape"};let Q=uZ($,Z);if(Q)return{matched:Q,strategy:"whitespace_normalize"};let W=xZ($,Z);if(W)return{matched:W,strategy:"flexible"};let z=dZ($,Z);if(z)return{matched:z,strategy:"block_anchor"};return{matched:null,strategy:"failed"}}function gJ($,Z){if(Z.length===0)return[];let J=[],Y=$.indexOf(Z);while(Y!==-1)J.push(Y),Y=$.indexOf(Z,Y+Z.length);return J}function pJ($,Z,J){let Y=$.split(`
|
|
262
262
|
`),U=Y.length,X=cJ($,Z,3),H=0,Q=Math.min(20,U);if(X.length>0){let K=X[0];H=Math.max(0,K.lineNumber-10),Q=Math.min(U,K.lineNumber+10)}let z=Y.slice(H,Q).map((K,G)=>{return` ${(H+G+1).toString().padStart(4)}: ${K}`}).join(`
|
|
263
263
|
`),V=`String not found in file.
|
|
264
264
|
|
|
@@ -292,11 +292,11 @@ Common issues:
|
|
|
292
292
|
- Outdated mental model: File may have changed since you last read it`,{llmContent:V,metadata:{searchStringLength:Z.length,fuzzyMatches:X.map((K)=>({line:K.lineNumber,similarity:K.similarity,preview:K.text.substring(0,100)})),excerptRange:[H+1,Q],totalLines:U}}}function cJ($,Z,J=3){let Y=$.split(`
|
|
293
293
|
`),U=Z.split(`
|
|
294
294
|
`);if(U.length===1)return Y.map((W,z)=>({text:W,lineNumber:z+1,similarity:gZ(Z.trim(),W.trim())})).filter((W)=>W.similarity>0.5).sort((W,z)=>z.similarity-W.similarity).slice(0,J);let X=U.length,H=[];for(let Q=0;Q<=Y.length-X;Q++){let W=Y.slice(Q,Q+X).join(`
|
|
295
|
-
`),z=gZ(Z,W);if(z>0.5)H.push({text:W,lineNumber:Q+1,similarity:z})}return H.sort((Q,W)=>W.similarity-Q.similarity).slice(0,J)}function gZ($,Z){let J=(K)=>K.trim().replace(/\s+/g," ").replace(/[\u201c\u201d"]/g,'"').replace(/[\u2018\u2019']/g,"'"),Y=J($),U=J(Z);if(Y===U)return 1;let X=Y.length,H=U.length;if(X===0)return H===0?1:0;if(H===0)return 0;let Q=200,W=Y.substring(0,Q),z=U.substring(0,Q),V=iJ(W,z),B=Math.max(W.length,z.length);return 1-V/B}function iJ($,Z){let J=$.length,Y=Z.length,U=Array(J+1).fill(null).map(()=>Array(Y+1).fill(0));for(let X=0;X<=J;X++)U[X][0]=X;for(let X=0;X<=Y;X++)U[0][X]=X;for(let X=1;X<=J;X++)for(let H=1;H<=Y;H++){let Q=$[X-1]===Z[H-1]?0:1;U[X][H]=Math.min(U[X-1][H]+1,U[X][H-1]+1,U[X-1][H-1]+Q)}return U[J][Y]}import{basename as lJ,extname as pZ}from"path";var
|
|
296
|
-
`),w=Y||0,
|
|
297
|
-
`),q.lines_read=b.length,q.total_lines=A.length,q.start_line=w+1,q.end_line=Math.min(
|
|
295
|
+
`),z=gZ(Z,W);if(z>0.5)H.push({text:W,lineNumber:Q+1,similarity:z})}return H.sort((Q,W)=>W.similarity-Q.similarity).slice(0,J)}function gZ($,Z){let J=(K)=>K.trim().replace(/\s+/g," ").replace(/[\u201c\u201d"]/g,'"').replace(/[\u2018\u2019']/g,"'"),Y=J($),U=J(Z);if(Y===U)return 1;let X=Y.length,H=U.length;if(X===0)return H===0?1:0;if(H===0)return 0;let Q=200,W=Y.substring(0,Q),z=U.substring(0,Q),V=iJ(W,z),B=Math.max(W.length,z.length);return 1-V/B}function iJ($,Z){let J=$.length,Y=Z.length,U=Array(J+1).fill(null).map(()=>Array(Y+1).fill(0));for(let X=0;X<=J;X++)U[X][0]=X;for(let X=0;X<=Y;X++)U[0][X]=X;for(let X=1;X<=J;X++)for(let H=1;H<=Y;H++){let Q=$[X-1]===Z[H-1]?0:1;U[X][H]=Math.min(U[X-1][H]+1,U[X][H-1]+1,U[X-1][H-1]+Q)}return U[J][Y]}import{basename as lJ,extname as pZ}from"path";var j5=j({name:"Read",displayName:"File Read",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({file_path:g.filePath({description:"File path to read (must be absolute)"}),offset:_.Optional(g.lineNumber({description:"Starting line number (0-based, text files only)"})),limit:_.Optional(g.lineLimit({description:"Number of lines to read (text files only)"})),encoding:g.encoding()}),description:{short:"Read files from the local filesystem",long:"Reads a file from the local filesystem. You can access any file directly by using this tool. Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.",usageNotes:["The file_path parameter must be an absolute path, not a relative path","By default, it reads up to 2000 lines starting from the beginning of the file","You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters","Any lines longer than 2000 characters will be truncated","Results are returned using cat -n format, with line numbers starting at 1","This tool allows reading images (eg PNG, JPG, etc). When reading an image file the contents are presented visually as this is a multimodal LLM.","This tool can read PDF files (.pdf). PDFs are processed page by page, extracting both text and visual content for analysis.","This tool can read Jupyter notebooks (.ipynb files) and returns all cells with their outputs, combining code, text, and visualizations.","This tool can only read files, not directories. To read a directory, use an ls command via the Bash tool.","You can call multiple tools in a single response. It is always better to speculatively read multiple potentially useful files in parallel.","You will regularly be asked to read screenshots. If the user provides a path to a screenshot, ALWAYS use this tool to view the file at the path. This tool will work with all temporary file paths.","If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents."],examples:[{description:"Read the entire file (recommended)",params:{file_path:"/path/to/file.ts"}},{description:"Read the first 100 lines",params:{file_path:"/path/to/file.txt",limit:100}},{description:"Read 100 lines starting at line 50 (large file)",params:{file_path:"/path/to/large-file.log",offset:50,limit:100}}],important:["file_path must be absolute","Prefer reading the entire file (omit offset and limit)","Use offset/limit only for very large files","Line numbers start at 1 (cat -n format)"]},async execute($,Z){let{file_path:J,offset:Y,limit:U,encoding:X="utf8"}=$,{updateOutput:H,sessionId:Q}=Z,W=Z.signal??new AbortController().signal;try{H?.("Starting file read...");let z=a(Q),V=z?E$(Q):O$();try{if(!await V.exists(J))throw Error("File not found")}catch(A){return{success:!1,llmContent:`File not found: ${J}`,error:{type:"execution_error",message:`File not found: ${J}`}}}if(typeof W.throwIfAborted==="function")W.throwIfAborted();if(Q)await V0.getInstance().recordFileRead(J,Q);let B=await V.stat(J);if(B?.isDirectory)return{success:!1,llmContent:`Cannot read a directory: ${J}`,error:{type:"execution_error",message:"Target is a directory, not a file"}};let K=pZ(J).toLowerCase(),G=nJ(K),O=rJ(K),E,q={file_path:J,file_size:B?.size,file_type:K,last_modified:B?.mtime instanceof Date?B.mtime.toISOString():void 0,encoding:X,acp_mode:z};if(O&&X==="utf8"){if(z)H?.("[WARN] 二进制文件通过本地读取(ACP 不支持)..."),q.acp_fallback=!0;else H?.("检测到二进制文件,使用 base64 编码...");E=(await V.readBinaryFile(J)).toString("base64"),q.encoding="base64",q.is_binary=!0}else if(G){if(z)H?.("通过 IDE 读取文件...");E=await V.readTextFile(J)}else{if(z)q.acp_fallback=!0;let A=await V.readBinaryFile(J);if(X==="base64")E=A.toString("base64");else if(X==="binary")E=A.toString("binary");else E=A.toString("utf8")}if(typeof W.throwIfAborted==="function")W.throwIfAborted();if((Y!==void 0||U!==void 0)&&X==="utf8"&&G){let A=E.split(`
|
|
296
|
+
`),w=Y||0,T=U!==void 0?w+U:A.length,b=A.slice(w,T);E=b.map((P,M)=>{let C=w+M+1,S=P.length>2000?`${P.substring(0,2000)}...`:P;return`${C.toString().padStart(6)}|${S}`}).join(`
|
|
297
|
+
`),q.lines_read=b.length,q.total_lines=A.length,q.start_line=w+1,q.end_line=Math.min(T,A.length)}let F=lJ(J),D=q.lines_read||q.total_lines,L=D?`读取 ${D} 行从 ${F}`:`读取 ${F}`;return q.summary=L,{success:!0,llmContent:E,metadata:q}}catch(z){let V=z;if(V.name==="AbortError")return{success:!1,llmContent:"File read aborted",error:{type:"execution_error",message:"Operation aborted"}};return{success:!1,llmContent:`File read failed: ${V.message}`,error:{type:"execution_error",message:V.message,details:V}}}},version:"2.0.0",category:"文件操作",tags:["file","io","read"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let Z=pZ($.file_path);return Z?`**/*${Z}`:"**/*"}});function nJ($){return[".txt",".md",".js",".ts",".jsx",".tsx",".json",".xml",".html",".htm",".css",".scss",".sass",".less",".yml",".yaml",".toml",".ini",".cfg",".py",".rb",".php",".java",".cpp",".c",".h",".hpp",".rs",".go",".sh",".bash",".zsh",".fish",".ps1",".bat",".cmd",".sql",".graphql",".vue",".svelte",".astro",".dockerfile",".gitignore",".env"].includes($)||$===""}function rJ($){return[".jpg",".jpeg",".png",".gif",".bmp",".svg",".ico",".webp",".mp3",".wav",".mp4",".avi",".mov",".wmv",".flv",".webm",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".zip",".tar",".gz",".rar",".7z",".exe",".dll",".so",".ttf",".otf",".woff",".woff2",".eot"].includes($)}import{promises as aJ}from"fs";import{basename as oJ,dirname as sJ,extname as tJ}from"path";var M5=j({name:"Write",displayName:"File Write",kind:"write",strict:!0,isConcurrencySafe:!1,parallelism:"shared",affectedPaths:($)=>[$.file_path],schema:_.Object({file_path:g.filePath({description:"Absolute file path to write"}),content:_.String({description:"Content to write"}),encoding:g.encoding(),create_directories:f(_.Boolean({description:"Automatically create missing parent directories"}),!0)}),description:{short:"Writes a file to the local filesystem",long:"Writes a file to the local filesystem.",usageNotes:["This tool will overwrite the existing file if there is one at the provided path.","If this is an existing file, you MUST use the Read tool first to read the file's contents. This tool will fail if you did not read the file first.","ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.","NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.","Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked."]},async execute($,Z){let{file_path:J,content:Y,encoding:U,create_directories:X}=$,{updateOutput:H,sessionId:Q,messageId:W}=Z,z=Z.signal??new AbortController().signal;try{H?.("开始写入文件...");let V=a(Q),B=V?E$(Q):O$();if(X){let T=sJ(J);try{await B.mkdir(T,{recursive:!0,mode:493})}catch(b){if(b.code!=="EEXIST")throw b}}if(typeof z.throwIfAborted==="function")z.throwIfAborted();let K=!1,G=null;try{if(K=await B.exists(J),K&&U==="utf8")try{G=await B.readTextFile(J)}catch(T){console.warn("[WriteTool] 读取旧文件内容失败:",T)}}catch{}if(K&&Q){let T=V0.getInstance();if(!T.hasFileBeenRead(J,Q))return{success:!1,llmContent:"If this is an existing file, you MUST use the Read tool first to read the file's contents. This tool will fail if you did not read the file first.",error:{type:"validation_error",message:"File not read before write"},metadata:{requiresRead:!0}};let b=await T.checkExternalModification(J,Q);if(b.isExternal)return{success:!1,llmContent:`The file has been modified by an external program since you last read it. You must use the Read tool again to see the current content before writing.
|
|
298
298
|
|
|
299
|
-
Details: ${b.message}`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:b.message}}}}let O=!1,E,q;if(typeof z.throwIfAborted==="function")z.throwIfAborted();if(!V&&Q&&W)try{E=new n0({sessionId:Q,workspaceRoot:Z.workspaceRoot}),await E.initialize(),q=await E.createSnapshot(J,W)}catch(
|
|
299
|
+
Details: ${b.message}`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:b.message}}}}let O=!1,E,q;if(typeof z.throwIfAborted==="function")z.throwIfAborted();if(!V&&Q&&W)try{E=new n0({sessionId:Q,workspaceRoot:Z.workspaceRoot}),await E.initialize(),q=await E.createSnapshot(J,W)}catch(T){console.warn("[WriteTool] 创建快照失败:",T),E=void 0,q=void 0}try{if(U==="utf8"){if(V)H?.("通过 IDE 写入文件...");await B.writeTextFile(J,Y)}else{if(V)return{success:!1,llmContent:"Binary file writes are not supported in ACP mode. The IDE only supports text file operations. Please use encoding='utf8' for text files, or ask the user to write the file manually.",error:{type:"validation_error",message:"Binary writes not supported in ACP mode"}};let T;if(U==="base64")T=Buffer.from(Y,"base64");else if(U==="binary")T=Buffer.from(Y,"binary");else T=Buffer.from(Y,"utf8");await aJ.writeFile(J,T)}}catch(T){if(E&&q)await E.discardSnapshot(J,q).catch((b)=>console.warn("[WriteTool] 丢弃未完成快照失败:",b));throw T}if(E&&q)try{await E.recordPostEditState(J,q),O=!0}catch(T){console.warn("[WriteTool] 完成快照失败:",T),await E.discardSnapshot(J,q).catch((b)=>console.warn("[WriteTool] 丢弃未完成快照失败:",b))}if(Q)await V0.getInstance().recordFileEdit(J,Q,"write");if(typeof z.throwIfAborted==="function")z.throwIfAborted();let F=await B.stat(J),D=U==="utf8"?Y.split(`
|
|
300
300
|
`).length:0,L=oJ(J),A=null;if(G&&U==="utf8"&&G!==Y){if(G.length<1048576&&Y.length<1048576)A=vZ(G,Y,4)}let w={file_path:J,content_size:Y.length,file_size:F?.size,encoding:U,created_directories:X,snapshot_created:O,session_id:Q,message_id:W,last_modified:F?.mtime instanceof Date?F.mtime.toISOString():void 0,has_diff:!!A,summary:U==="utf8"?`写入 ${D} 行到 ${L}`:`写入 ${F?.size?eJ(F.size):"unknown"} 到 ${L}`,kind:"edit",oldContent:G||"",newContent:U==="utf8"?Y:void 0};return{success:!0,llmContent:G?`Wrote ${J} (${Y.length} chars, updated existing file)`:`Created ${J} (${Y.length} chars, new file)`,metadata:w}}catch(V){let B=V;if(B.name==="AbortError")return{success:!1,llmContent:"File write aborted",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`File write failed: ${B.message}`,error:{type:"execution_error",message:B.message,details:B}}}},version:"2.0.0",category:"文件操作",tags:["file","io","write","create"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let Z=tJ($.file_path);return Z?`**/*${Z}`:"**/*"}});function eJ($){let Z=["B","KB","MB","GB"],J=$,Y=0;while(J>=1024&&Y<Z.length-1)J/=1024,Y++;return`${J.toFixed(1)}${Z[Y]}`}function $Y($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}function C5($){let Z=$.tokenBudget?.toString()??"none",J=$.tokenBudget===void 0?"unbounded":Math.max(0,$.tokenBudget-$.tokensUsed).toString();return`<system-reminder>
|
|
301
301
|
<goal-state>
|
|
302
302
|
Objective: ${$Y($.objective)}
|
|
@@ -318,7 +318,7 @@ without external intervention, and include the concrete blocker. Do not leave an
|
|
|
318
318
|
active goal idle merely because one logical turn ended.
|
|
319
319
|
</system-reminder>`}function o$($){let Z=$.tokenBudget===void 0?`${$.tokensUsed} tokens`:`${$.tokensUsed}/${$.tokenBudget} tokens`,J=$.statusReason?`
|
|
320
320
|
Reason: ${$.statusReason}`:"";return[`Goal ${$.status}: ${$.objective}`,`Usage: ${Z}, ${$.timeUsedSeconds}s, ${$.continuationCount} continuations`,J].filter(Boolean).join(`
|
|
321
|
-
`)}function f5($,Z){return new
|
|
321
|
+
`)}function f5($,Z){return new T0($.workspaceRoot??Z.workspaceRoot,$.sessionId??Z.sessionId)}function R5($){let Z=$ instanceof Error?$.message:String($);return{success:!1,llmContent:{error:Z},error:{type:"execution_error",message:Z,code:"GOAL_OPERATION_FAILED"},metadata:{summary:Z}}}function S5($){let Z=j({name:"GetGoal",displayName:"Get Goal",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({}),description:{short:"Read the persisted goal for the current session",long:"Returns the objective, status, token budget, usage, elapsed time, and continuation count."},async execute(U,X){try{let H=await f5(X,$).get();return{success:!0,llmContent:{goal:H},metadata:{summary:H?o$(H):"No goal is active"}}}catch(H){return R5(H)}},category:"Goal tools",tags:["goal","session","planning"],abstractPermissionRule:()=>"*"}),J=j({name:"CreateGoal",displayName:"Create Goal",kind:"readonly",isConcurrencySafe:!1,schema:_.Object({objective:_.String({minLength:1,description:"Concrete objective explicitly requested"}),tokenBudget:_.Optional(_.Integer({minimum:1,description:"Optional positive token budget, only when explicitly requested"}))}),description:{short:"Create a persisted active goal for the current session",long:"Use only when the user explicitly requests goal mode. Fails while an unfinished goal exists.",important:["Do not infer a goal from an ordinary coding request.","Do not set tokenBudget unless the user explicitly requests one."]},async execute(U,X){try{let H=await f5(X,$).create(U);return{success:!0,llmContent:{goal:H},metadata:{summary:`Goal started: ${H.objective}`}}}catch(H){return R5(H)}},category:"Goal tools",tags:["goal","session","planning"],extractSignatureContent:(U)=>U.objective,abstractPermissionRule:()=>"*"}),Y=j({name:"UpdateGoal",displayName:"Update Goal",kind:"readonly",isConcurrencySafe:!1,schema:_.Object({status:d(["complete","blocked"]),reason:_.Optional(_.String({description:"Concrete blocker; required when status is blocked"}))}),description:{short:"Mark the persisted goal complete or blocked",long:"Use complete only after the full objective and required verification are finished. Use blocked only when external intervention is required.",important:["Do not mark complete because a single turn ended.","Do not use blocked for difficult, slow, or uncertain work."]},async execute(U,X){try{let H=f5(X,$),Q=U.status==="complete"?await H.complete():await H.block(U.reason??"");return{success:!0,llmContent:{goal:Q,remainingTokens:Q.tokenBudget===void 0?null:Math.max(0,Q.tokenBudget-Q.tokensUsed)},metadata:{summary:o$(Q)}}}catch(H){return R5(H)}},category:"Goal tools",tags:["goal","session","planning"],extractSignatureContent:(U)=>U.status,abstractPermissionRule:()=>"*"});return[Z,J,Y]}import iZ from"node:path";import{fileURLToPath as ZY}from"node:url";function Z2($,Z){let J=$;try{if($.startsWith("file:"))J=ZY($)}catch{}let Y=iZ.relative(Z,J);return Y&&!Y.startsWith("..")?Y:J}function P5($,Z){return`${Z2($.uri,Z)}:${$.range.start.line+1}:${$.range.start.character+1}`}function JY($){return"targetUri"in $?{uri:$.targetUri,range:$.targetSelectionRange??$.targetRange}:$}function cZ($,Z,J){if(!$)return J;let Y=(Array.isArray($)?$:[$]).filter((U)=>Boolean(U&&(("uri"in U)||("targetUri"in U)))).map(JY);if(Y.length===0)return J;return Y.map((U)=>P5(U,Z)).join(`
|
|
322
322
|
`)}function YY($){if(Array.isArray($))return $.map((Z)=>typeof Z==="string"?Z:Z.value).join(`
|
|
323
323
|
|
|
324
324
|
`);return typeof $==="string"?$:$.value}function lZ($,Z=0){return[`${" ".repeat(Z)}${$.name} (${$.kind}) - Line ${$.range.start.line+1}${$.detail?` ${$.detail}`:""}`,...($.children??[]).flatMap((Y)=>lZ(Y,Z+1))]}function UY($,Z){if(!$||$.diagnostics.length===0)return"No diagnostics reported for this file.";return[`${iZ.relative(Z,$.filePath)} (${$.serverName}):`,...$.diagnostics.slice(0,30).map((Y)=>{return` ${["Error","Warning","Info","Hint"][(Y.severity??1)-1]??"Error"} ${Y.range.start.line+1}:${Y.range.start.character+1} ${Y.message.replace(/\s+/g," ").slice(0,500)}`})].join(`
|
|
@@ -327,13 +327,13 @@ Reason: ${$.statusReason}`:"";return[`Goal ${$.status}: ${$.objective}`,`Usage:
|
|
|
327
327
|
`)}case"prepareCallHierarchy":{let Y=Z??[];return Y.length===0?"No call hierarchy item found.":Y.map((U)=>`${U.name} - ${Z2(U.uri,J)}:${U.range.start.line+1}`).join(`
|
|
328
328
|
`)}case"incomingCalls":{let Y=Z??[];return Y.length===0?"No incoming calls found.":Y.map((U)=>`${U.from.name} - ${Z2(U.from.uri,J)}:${U.from.range.start.line+1}`).join(`
|
|
329
329
|
`)}case"outgoingCalls":{let Y=Z??[];return Y.length===0?"No outgoing calls found.":Y.map((U)=>`${U.to.name} - ${Z2(U.to.uri,J)}:${U.to.range.start.line+1}`).join(`
|
|
330
|
-
`)}case"diagnostics":return UY(Z,J)}}var XY=["goToDefinition","findReferences","hover","documentSymbol","workspaceSymbol","goToImplementation","prepareCallHierarchy","incomingCalls","outgoingCalls","diagnostics"];function k5($){return
|
|
330
|
+
`)}case"diagnostics":return UY(Z,J)}}var XY=["goToDefinition","findReferences","hover","documentSymbol","workspaceSymbol","goToImplementation","prepareCallHierarchy","incomingCalls","outgoingCalls","diagnostics"];function k5($){return j({name:"LSP",displayName:"Code Intelligence",kind:"readonly",strict:!0,isConcurrencySafe:!0,parallelism:"shared",schema:_.Object({operation:d(XY,{description:"Code intelligence operation"}),filePath:g.filePath({description:"Absolute path to a file inside the Session workspace"}),line:f(_.Integer({minimum:1,description:"1-based line number for position operations"}),1),character:f(_.Integer({minimum:1,description:"1-based character offset for position operations"}),1),query:f(_.String({description:"Search text for workspaceSymbol"}),"")}),description:{short:"Queries configured language servers for code intelligence",long:"Find definitions, references, implementations, symbols, call hierarchy, hover information, and current diagnostics without text search.",usageNotes:["Use 1-based line and character positions exactly as shown by Read.","The target must be an existing file inside the current Session workspace.","Use workspaceSymbol with query to search semantic symbols across the project.","LSP is unavailable for ACP-owned remote files."]},async execute(Z,J){try{let Y=await $.query(Z,J.signal);return{success:!0,llmContent:nZ(Y.operation,Y.result,$.workspacePath),metadata:{operation:Y.operation,file_path:Y.filePath,server:Y.serverName,summary:`LSP ${Y.operation} in ${Y.filePath}`}}}catch(Y){let U=Y instanceof Error?Y.message:String(Y);return{success:!1,llmContent:`LSP request failed: ${U}`,error:{type:"execution_error",message:U},metadata:{operation:Z.operation,file_path:Z.filePath,summary:`LSP ${Z.operation} failed`}}}},extractSignatureContent:(Z)=>Z.filePath,abstractPermissionRule:(Z)=>Z.filePath,version:"1.0.0",category:"Code Intelligence",tags:["lsp","code-intelligence","diagnostics"]})}var v5=j({name:"MemoryRead",displayName:"Memory Read",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({topic:_.String({description:'Topic name to read (e.g., "debugging", "patterns", "MEMORY" for the index, "_list" to list all topics). Without .md extension.'})}),description:{short:"Read a topic file from project auto memory",long:"Reads a topic file from the project's persistent auto memory directory. Use this to retrieve detailed notes that were saved in previous sessions. The MEMORY.md index is automatically loaded at session start, but topic files need to be read on demand.",usageNotes:['Use topic="MEMORY" to read the full MEMORY.md index','Use topic="_list" to list all available memory files',"Topic files are stored at ~/.blade/projects/{project}/memory/{topic}.md"],examples:[{description:"Read debugging notes",params:{topic:"debugging"}},{description:"Read the full MEMORY.md index",params:{topic:"MEMORY"}},{description:"List all memory topics",params:{topic:"_list"}}]},async execute($,Z){let{topic:J}=$,Y=Z.workspaceRoot||N(),U=new q$(Y);if(J==="_list"){let H=await U.listTopics();if(H.length===0)return{success:!0,llmContent:"No memory files found. Use MemoryWrite to save project knowledge.",metadata:{summary:"无记忆文件"}};return{success:!0,llmContent:`Memory files:
|
|
331
331
|
${H.map((z)=>`- ${z.name}.md (${z.size} bytes, updated ${z.lastModified.toISOString()})`).join(`
|
|
332
|
-
`)}`,metadata:{summary:`列出 ${H.length} 个记忆文件`}}}let X=await U.readTopic(J);if(X===null)return{success:!0,llmContent:`Memory topic "${J}" not found. Use topic="_list" to see available topics.`,metadata:{summary:`记忆主题未找到: ${J}`}};return{success:!0,llmContent:X,metadata:{summary:`读取记忆: ${J}`}}}});var HY=[/password\s*[:=]/i,/token\s*[:=]/i,/secret\s*[:=]/i,/api[_-]?key\s*[:=]/i,/private[_-]?key/i],I5=
|
|
332
|
+
`)}`,metadata:{summary:`列出 ${H.length} 个记忆文件`}}}let X=await U.readTopic(J);if(X===null)return{success:!0,llmContent:`Memory topic "${J}" not found. Use topic="_list" to see available topics.`,metadata:{summary:`记忆主题未找到: ${J}`}};return{success:!0,llmContent:X,metadata:{summary:`读取记忆: ${J}`}}}});var HY=[/password\s*[:=]/i,/token\s*[:=]/i,/secret\s*[:=]/i,/api[_-]?key\s*[:=]/i,/private[_-]?key/i],I5=j({name:"MemoryWrite",displayName:"Memory Write",kind:"write",isConcurrencySafe:!1,schema:_.Object({topic:_.String({description:'Topic name to write to (e.g., "debugging", "patterns", "MEMORY" for the index). Without .md extension.'}),content:_.String({description:"Content to write to the memory file"}),mode:f(d(["overwrite","append"],{description:'Write mode: "append" adds to existing content, "overwrite" replaces it'}),"append")}),description:{short:"Save project knowledge to persistent auto memory",long:"Saves notes and learnings to the project's persistent auto memory. Use this to record useful project knowledge that should survive across sessions — build commands, code patterns, debugging insights, architecture notes, and user preferences.",usageNotes:['Use topic="MEMORY" to update the index file (keep it concise, under 200 lines)','Use descriptive topic names for detailed notes (e.g., "debugging", "api-conventions")','Default mode is "append" — adds to existing content','Use "overwrite" mode to replace the entire topic file',"Do NOT save sensitive data (passwords, tokens, API keys)"],examples:[{description:"Save a debugging insight",params:{topic:"debugging",content:"## Redis connection timeout\nThe test suite requires a local Redis instance. Start with `docker compose up redis`."}},{description:"Update the memory index",params:{topic:"MEMORY",content:"# Project Memory\n\n- Build: `bun run build`\n- Test: `bun run test`\n- See debugging.md for common issues",mode:"overwrite"}}]},async execute($,Z){let{topic:J,content:Y,mode:U}=$,X=Z.workspaceRoot||N();for(let z of HY)if(z.test(Y)){let V=`Refused: content appears to contain sensitive data (matched ${z}). Do not save passwords, tokens, or API keys to memory.`;return{success:!1,llmContent:V,error:{message:V,type:"validation_error"},metadata:{summary:"拒绝写入敏感信息"}}}let H=new q$(X);if(J==="MEMORY")await H.updateIndex(Y,U);else await H.writeTopic(J,Y,U);return{success:!0,llmContent:`${U==="overwrite"?"Written":"Appended"} to memory/${J}.md (${Y.length} chars)`,metadata:{summary:`写入记忆: ${J}`}}}});import*as J2 from"fs/promises";var y5=j({name:"NotebookEdit",displayName:"Notebook Edit",kind:"write",isConcurrencySafe:!1,parallelism:"shared",affectedPaths:($)=>[$.notebook_path],schema:_.Object({notebook_path:_.String({description:"The absolute path to the Jupyter notebook file to edit (must be absolute, not relative)"}),cell_id:_.Optional(_.String({description:"The ID of the cell to edit. New cells are inserted after it, or at the beginning when omitted."})),new_source:_.String({description:"The new source for the cell"}),cell_type:_.Optional(d(["code","markdown"],{description:"Cell type. Required for insert; otherwise defaults to the current type."})),edit_mode:f(d(["replace","insert","delete"],{description:"The edit operation. Defaults to replace."}),"replace")}),description:{short:"Completely replaces the contents of a specific cell in a Jupyter notebook",long:"Completely replaces the contents of a specific cell in a Jupyter notebook (.ipynb file) with new source. Jupyter notebooks are interactive documents that combine code, text, and visualizations, commonly used for data analysis and scientific computing. The notebook_path parameter must be an absolute path, not a relative path. The cell_number is 0-indexed. Use edit_mode=insert to add a new cell at the index specified by cell_number. Use edit_mode=delete to delete the cell at the index specified by cell_number."},async execute($,Z){let{notebook_path:J,cell_id:Y,new_source:U,cell_type:X,edit_mode:H="replace"}=$;try{let Q=await J2.readFile(J,"utf-8"),W=JSON.parse(Q);if(!W.cells||!Array.isArray(W.cells))return{success:!1,llmContent:"Invalid notebook format: no cells array found",error:{type:"validation_error",message:"Invalid notebook format"},metadata:{summary:"无效的 Notebook 格式"}};let z=-1;if(Y){if(z=W.cells.findIndex((B)=>B.id===Y),z===-1&&H!=="insert")return{success:!1,llmContent:`Cell with ID "${Y}" not found`,error:{type:"validation_error",message:`Cell ID "${Y}" not found`},metadata:{summary:`Cell 未找到: ${Y}`}}}switch(H){case"replace":{if(z===-1)return{success:!1,llmContent:"Cell ID required for replace operation",error:{type:"validation_error",message:"Cell ID required for replace"},metadata:{summary:"替换操作需要 Cell ID"}};let B=W.cells[z];if(B.source=U.split(`
|
|
333
333
|
`).map((K,G,O)=>G<O.length-1?K+`
|
|
334
334
|
`:K),X)B.cell_type=X;break}case"insert":{if(!X)return{success:!1,llmContent:"cell_type is required for insert operation",error:{type:"validation_error",message:"cell_type required for insert"},metadata:{summary:"插入操作需要 cell_type"}};let B={cell_type:X,source:U.split(`
|
|
335
335
|
`).map((G,O,E)=>O<E.length-1?G+`
|
|
336
|
-
`:G),metadata:{},...X==="code"?{execution_count:null,outputs:[]}:{}},K=z===-1?0:z+1;W.cells.splice(K,0,B);break}case"delete":{if(z===-1)return{success:!1,llmContent:"Cell ID required for delete operation",error:{type:"validation_error",message:"Cell ID required for delete"},metadata:{summary:"删除操作需要 Cell ID"}};W.cells.splice(z,1);break}}await J2.writeFile(J,JSON.stringify(W,null,2));let V=H==="replace"?"replaced":H==="insert"?"inserted":"deleted";return{success:!0,llmContent:`Successfully ${V} cell in ${J}`,metadata:{notebook_path:J,edit_mode:H,cell_id:Y,summary:`Notebook cell ${V}: ${J}`}}}catch(Q){let W=Q instanceof Error?Q.message:"Unknown error";return{success:!1,llmContent:`Failed to edit notebook: ${W}`,error:{type:"execution_error",message:W},metadata:{summary:"编辑 Notebook 失败"}}}}});var x5=
|
|
336
|
+
`:G),metadata:{},...X==="code"?{execution_count:null,outputs:[]}:{}},K=z===-1?0:z+1;W.cells.splice(K,0,B);break}case"delete":{if(z===-1)return{success:!1,llmContent:"Cell ID required for delete operation",error:{type:"validation_error",message:"Cell ID required for delete"},metadata:{summary:"删除操作需要 Cell ID"}};W.cells.splice(z,1);break}}await J2.writeFile(J,JSON.stringify(W,null,2));let V=H==="replace"?"replaced":H==="insert"?"inserted":"deleted";return{success:!0,llmContent:`Successfully ${V} cell in ${J}`,metadata:{notebook_path:J,edit_mode:H,cell_id:Y,summary:`Notebook cell ${V}: ${J}`}}}catch(Q){let W=Q instanceof Error?Q.message:"Unknown error";return{success:!1,llmContent:`Failed to edit notebook: ${W}`,error:{type:"execution_error",message:W},metadata:{summary:"编辑 Notebook 失败"}}}}});var x5=j({name:"EnterPlanMode",displayName:"Enter Plan Mode",kind:"readonly",isConcurrencySafe:!1,schema:_.Object({}),description:{short:"Use this tool to enter plan mode for complex tasks requiring careful planning",long:`Use this tool when you encounter a complex task that requires careful planning and exploration before implementation. This tool transitions you into plan mode where you can thoroughly explore the codebase and design an implementation approach.
|
|
337
337
|
|
|
338
338
|
## When to Use This Tool
|
|
339
339
|
|
|
@@ -418,7 +418,7 @@ Begin your research now.`,metadata:{approved:!0,enterPlanMode:!0,summary:"进入
|
|
|
418
418
|
|
|
419
419
|
Proceed with the task directly without planning phase. You can still use search tools to understand the codebase as needed, but implement the solution directly.`,metadata:{approved:!1,enterPlanMode:!1,summary:"Plan 模式被拒绝"}}}catch(J){return{success:!1,llmContent:`Confirmation flow error: ${J instanceof Error?J.message:"Unknown error"}`,error:{type:"execution_error",message:"Confirmation flow error"},metadata:{summary:"确认流程出错"}}}return{success:!0,llmContent:`Plan mode requested but no interactive confirmation available.
|
|
420
420
|
|
|
421
|
-
Proceeding with research phase. Use read-only tools to explore the codebase, then call ExitPlanMode with your implementation plan when ready.`,metadata:{approved:null,enterPlanMode:!0,summary:"Plan 模式(非交互)"}}}});import{promises as rZ}from"node:fs";import{homedir as QY}from"node:os";import*as h5 from"node:path";var u5=
|
|
421
|
+
Proceeding with research phase. Use read-only tools to explore the codebase, then call ExitPlanMode with your implementation plan when ready.`,metadata:{approved:null,enterPlanMode:!0,summary:"Plan 模式(非交互)"}}}});import{promises as rZ}from"node:fs";import{homedir as QY}from"node:os";import*as h5 from"node:path";var u5=j({name:"ExitPlanMode",displayName:"Exit Plan Mode",kind:"readonly",isConcurrencySafe:!1,schema:_.Object({plan:_.String({description:"The complete implementation plan in markdown format"})}),description:{short:"Use this tool when you are in plan mode and have finished creating your plan and are ready for user approval",long:`Use this tool when you are in plan mode and have finished creating your implementation plan and are ready for user approval.
|
|
422
422
|
|
|
423
423
|
## PREREQUISITES (MUST be satisfied before calling)
|
|
424
424
|
|
|
@@ -460,14 +460,14 @@ Before using this tool, ensure your plan is clear and unambiguous. If there are
|
|
|
460
460
|
The agent has stopped and control is returned to the user. The user can now provide additional information or clarification.`,metadata:{approved:!1,shouldExitLoop:!0,feedback:Y.feedback,awaitingUserInput:!0,summary:"方案被拒绝,等待用户反馈"}}}catch(Y){return{success:!1,llmContent:`Confirmation flow error: ${Y instanceof Error?Y.message:"Unknown error"}`,error:{type:"execution_error",message:"Confirmation flow error"},metadata:{summary:"确认流程出错"}}}return{success:!0,llmContent:`[OK] Plan mode exit requested. No interactive confirmation available.
|
|
461
461
|
Proceeding with implementation.`,metadata:{approved:null,summary:"退出 Plan 模式(非交互)"}}}});import{stat as qY}from"node:fs/promises";import FY from"fast-glob";import{join as DY,resolve as wY}from"path";import{existsSync as WY,readFileSync as zY}from"node:fs";import{readFile as VY}from"node:fs/promises";import{dirname as BY,join as oZ}from"node:path";import KY from"fast-glob";import{LRUCache as _Y}from"lru-cache";import F1 from"picomatch";var I$=["node_modules",".git","dist","build","out",".next",".nuxt",".cache",".parcel-cache","coverage",".nyc_output",".idea",".vscode",".vs","bower_components","jspm_packages"],GY=["*.log","npm-debug.log*","yarn-debug.log*","pnpm-debug.log*","*.lock","bun.lock","package-lock.json","yarn.lock","pnpm-lock.yaml","*.tmp","*.temp","*.swp","*.bak","*~",".DS_Store","Thumbs.db","*.pid","*.seed"];function OY($){if(!WY($))return{patterns:[],negatePatterns:[]};try{let Z=zY($,"utf-8"),J=[],Y=[];for(let U of Z.split(`
|
|
462
462
|
`)){let X=U.trim();if(!X||X.startsWith("#"))continue;if(X.startsWith("!"))Y.push(X.slice(1));else J.push(X)}return{patterns:J,negatePatterns:Y}}catch(Z){return console.warn(`Failed to read .gitignore: ${Z}`),{patterns:[],negatePatterns:[]}}}var aZ=new _Y({max:100,ttl:30000,updateAgeOnGet:!0});async function EY($,Z){let J=[...I$.map((W)=>`${W}/**`),...Z?.scanIgnore??[]],Y=`${$}|${J.join(",")}`,U=aZ.get(Y);if(U)return U;let X=await KY("**/.gitignore",{cwd:$,dot:!0,onlyFiles:!0,followSymbolicLinks:!1,unique:!0,ignore:J});X.sort((W,z)=>E1(W).length-E1(z).length);let H=[];for(let W of X){let z=BY(W).replace(/\\/g,"/"),V=z==="."?"":z,K=(await VY(oZ($,W),"utf-8")).split(`
|
|
463
|
-
`);for(let G of K){let O=G.trim();if(!O||O.startsWith("#"))continue;let E=O.startsWith("!"),F=(E?O.slice(1):O).trim();if(!F)continue;let D="";if(F.startsWith("/")){let L=F.slice(1).replace(/\\/g,"/");if(D=(V?V+"/":"")+L,H.push({type:E?"negate":"ignore",pattern:D}),F.endsWith("/")){let A=D+"**";H.push({type:E?"negate":"ignore",pattern:A});let w=D.replace(/\/$/,"");if(w!==D)H.push({type:E?"negate":"ignore",pattern:w})}}else{let L=F.replace(/\\/g,"/");if(L.includes("/")){if(D=(V?V+"/":"")+L,H.push({type:E?"negate":"ignore",pattern:D}),L.endsWith("/")){let A=D+"**";H.push({type:E?"negate":"ignore",pattern:A});let w=D.replace(/\/$/,"");if(w!==D)H.push({type:E?"negate":"ignore",pattern:w})}}else D=(V?V+"/**/":"**/")+L,H.push({type:E?"negate":"ignore",pattern:D})}}}let Q=Z?.cacheTTL??30000;return aZ.set(Y,H,{ttl:Q}),H}class Y2{orderedRules=[];ignorePatterns=[];negatePatterns=[];constructor($={}){this.initialize($)}static async create($={}){let Z=new Y2({...$,useGitignore:!1}),{cwd:J=N(),useGitignore:Y=!0,gitignoreScanMode:U="root",customScanIgnore:X=[],cacheTTL:H}=$;if(Y&&U==="recursive"){let Q=await EY(J,{scanIgnore:X,cacheTTL:H});for(let W of Q)if(Z.orderedRules.push({type:W.type,matcher:F1(W.pattern,{dot:!0})}),W.type==="ignore")Z.ignorePatterns.push(W.pattern);else Z.negatePatterns.push(W.pattern)}return Z}initialize($){let{cwd:Z=N(),useGitignore:J=!0,useDefaults:Y=!0,customPatterns:U=[]}=$,X=[],H=[];if(Y){let Q=[...I$.map((W)=>`${W}/**`),...I$,...GY];X.push(...Q);for(let W of Q)this.orderedRules.push({type:"ignore",matcher:F1(W,{dot:!0})})}if(J){let Q=oZ(Z,".gitignore"),{patterns:W,negatePatterns:z}=OY(Q);for(let V of W)this.orderedRules.push({type:"ignore",matcher:F1(V,{dot:!0})}),X.push(V);for(let V of z)this.orderedRules.push({type:"negate",matcher:F1(V,{dot:!0})}),H.push(V)}X.push(...U);for(let Q of U)this.orderedRules.push({type:"ignore",matcher:F1(Q,{dot:!0})});this.ignorePatterns=X,this.negatePatterns=H}shouldIgnore($){let Z=$.replace(/\\/g,"/"),J=void 0;for(let Y of this.orderedRules)if(Y.matcher(Z))J=Y.type==="ignore";return J===!0}shouldIgnoreDirectory($){let Z=$.replace(/\\/g,"/");return this.shouldIgnore(Z)||this.shouldIgnore(`${Z}/`)}filter($){return $.filter((Z)=>!this.shouldIgnore(Z))}getIgnorePatterns(){return this.ignorePatterns}getNegatePatterns(){return this.negatePatterns}}function d5($){let Z=Error($);return Z.name="AbortError",Z}var m5=
|
|
463
|
+
`);for(let G of K){let O=G.trim();if(!O||O.startsWith("#"))continue;let E=O.startsWith("!"),F=(E?O.slice(1):O).trim();if(!F)continue;let D="";if(F.startsWith("/")){let L=F.slice(1).replace(/\\/g,"/");if(D=(V?V+"/":"")+L,H.push({type:E?"negate":"ignore",pattern:D}),F.endsWith("/")){let A=D+"**";H.push({type:E?"negate":"ignore",pattern:A});let w=D.replace(/\/$/,"");if(w!==D)H.push({type:E?"negate":"ignore",pattern:w})}}else{let L=F.replace(/\\/g,"/");if(L.includes("/")){if(D=(V?V+"/":"")+L,H.push({type:E?"negate":"ignore",pattern:D}),L.endsWith("/")){let A=D+"**";H.push({type:E?"negate":"ignore",pattern:A});let w=D.replace(/\/$/,"");if(w!==D)H.push({type:E?"negate":"ignore",pattern:w})}}else D=(V?V+"/**/":"**/")+L,H.push({type:E?"negate":"ignore",pattern:D})}}}let Q=Z?.cacheTTL??30000;return aZ.set(Y,H,{ttl:Q}),H}class Y2{orderedRules=[];ignorePatterns=[];negatePatterns=[];constructor($={}){this.initialize($)}static async create($={}){let Z=new Y2({...$,useGitignore:!1}),{cwd:J=N(),useGitignore:Y=!0,gitignoreScanMode:U="root",customScanIgnore:X=[],cacheTTL:H}=$;if(Y&&U==="recursive"){let Q=await EY(J,{scanIgnore:X,cacheTTL:H});for(let W of Q)if(Z.orderedRules.push({type:W.type,matcher:F1(W.pattern,{dot:!0})}),W.type==="ignore")Z.ignorePatterns.push(W.pattern);else Z.negatePatterns.push(W.pattern)}return Z}initialize($){let{cwd:Z=N(),useGitignore:J=!0,useDefaults:Y=!0,customPatterns:U=[]}=$,X=[],H=[];if(Y){let Q=[...I$.map((W)=>`${W}/**`),...I$,...GY];X.push(...Q);for(let W of Q)this.orderedRules.push({type:"ignore",matcher:F1(W,{dot:!0})})}if(J){let Q=oZ(Z,".gitignore"),{patterns:W,negatePatterns:z}=OY(Q);for(let V of W)this.orderedRules.push({type:"ignore",matcher:F1(V,{dot:!0})}),X.push(V);for(let V of z)this.orderedRules.push({type:"negate",matcher:F1(V,{dot:!0})}),H.push(V)}X.push(...U);for(let Q of U)this.orderedRules.push({type:"ignore",matcher:F1(Q,{dot:!0})});this.ignorePatterns=X,this.negatePatterns=H}shouldIgnore($){let Z=$.replace(/\\/g,"/"),J=void 0;for(let Y of this.orderedRules)if(Y.matcher(Z))J=Y.type==="ignore";return J===!0}shouldIgnoreDirectory($){let Z=$.replace(/\\/g,"/");return this.shouldIgnore(Z)||this.shouldIgnore(`${Z}/`)}filter($){return $.filter((Z)=>!this.shouldIgnore(Z))}getIgnorePatterns(){return this.ignorePatterns}getNegatePatterns(){return this.negatePatterns}}function d5($){let Z=Error($);return Z.name="AbortError",Z}var m5=j({name:"Glob",displayName:"File Pattern Match",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({pattern:g.glob({description:"Glob pattern string (supports *, ?, ** wildcards)"}),path:_.Optional(_.String({description:"Search path (optional, defaults to cwd)"})),max_results:f(_.Integer({minimum:1,maximum:1000,description:"Maximum number of results"}),100),include_directories:f(_.Boolean({description:"Include directories in results"}),!1),case_sensitive:f(_.Boolean({description:"Case sensitive matching"}),!1)}),description:{short:"Fast file pattern matching tool that works with any codebase size",long:'Fast file pattern matching tool that works with any codebase size. Supports glob patterns like "**/*.js" or "src/**/*.ts". Returns matching file paths sorted by modification time.',usageNotes:["Use this tool when you need to find files by name patterns","When you are doing an open ended search that may require multiple rounds of globbing and grepping, use the Agent tool instead","You can call multiple tools in a single response. It is always better to speculatively perform multiple searches in parallel if they are potentially useful."]},async execute($,Z){let{pattern:J,path:Y,max_results:U,include_directories:X,case_sensitive:H}=$,{updateOutput:Q}=Z,W=Z.signal??new AbortController().signal,z=Y??Z.workspaceRoot??N();try{Q?.(`Searching in ${z} for pattern "${J}"...`);let V=wY(z);try{if(!(await qY(V)).isDirectory())return{success:!1,llmContent:`Search path must be a directory: ${V}`,metadata:{summary:"搜索失败: 搜索路径必须是目录"},error:{type:"validation_error",message:"搜索路径必须是目录"}}}catch(F){if(F.code==="ENOENT")return{success:!1,llmContent:`Search path does not exist: ${V}`,metadata:{summary:"搜索失败: 搜索路径不存在"},error:{type:"execution_error",message:"搜索路径不存在"}};throw F}W.throwIfAborted();let B=await Y2.create({cwd:V,useGitignore:!0,useDefaults:!0,gitignoreScanMode:"recursive",customScanIgnore:[],cacheTTL:30000}),{matches:K,wasTruncated:G}=await AY(V,J,{maxResults:U,includeDirectories:X,caseSensitive:H,signal:W},B),O=LY(K),E={search_path:V,pattern:J,total_matches:K.length,returned_matches:K.length,max_results:U,include_directories:X,case_sensitive:H,truncated:G},q;if(O.length>0)q=`${G?`Found at least ${O.length} file(s) matching "${J}" (truncated)`:`Found ${O.length} file(s) matching "${J}"`}:
|
|
464
464
|
|
|
465
465
|
`+O.map((D)=>`- ${D.relative_path}`).join(`
|
|
466
466
|
`)+`
|
|
467
467
|
|
|
468
|
-
Use the relative_path values above for Read/Edit operations.`;else q=`No files found matching "${J}"`;return{success:!0,llmContent:q,metadata:{...E,matches:O,summary:`找到 ${K.length} 个匹配 "${J}" 的文件`}}}catch(V){let B=V;if(B.name==="AbortError")return{success:!1,llmContent:"File search aborted",metadata:{summary:"搜索失败: 操作被中止"},error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`Search failed: ${B.message}`,metadata:{summary:`搜索失败: ${B.message}`},error:{type:"execution_error",message:B.message,details:B}}}},version:"2.0.0",category:"搜索工具",tags:["file","search","glob","pattern","wildcard"],extractSignatureContent:($)=>$.pattern,abstractPermissionRule:()=>"*"});async function AY($,Z,J,Y){let U=Y.getIgnorePatterns(),X=[],H=!1;return await new Promise((Q,W)=>{if(J.signal.aborted){W(d5("文件搜索被用户中止"));return}let z=FY.stream(Z,{cwd:$,dot:!0,followSymbolicLinks:!1,unique:!0,caseSensitiveMatch:J.caseSensitive,objectMode:!0,stats:!0,onlyFiles:!J.includeDirectories,ignore:U}),V=!1,B=null,K=()=>{if(B){if(J.signal.removeEventListener)J.signal.removeEventListener("abort",B);else if("onabort"in J.signal)J.signal.onabort=null;B=null}},G=()=>{if(!V)V=!0,H=!0,z.destroy(),K(),Q({matches:X,wasTruncated:H})},O=(E)=>{if(J.signal.aborted){if(!V)V=!0,z.destroy(d5("文件搜索被用户中止"));return}if(X.length>=J.maxResults){G();return}let q=E.path.replace(/\\/g,"/"),F=DY($,q);if(Y.shouldIgnore(q))return;let D=E.stats?E.stats.isDirectory():!1;if(D&&Y.shouldIgnoreDirectory(q))return;let L=E.stats&&E.stats.isFile()?E.stats.size:void 0,A=E.stats?E.stats.mtime.toISOString():void 0;if(X.push({path:F,relative_path:q,is_directory:D,size:L,modified:A}),X.length>=J.maxResults)G()};if(z.on("data",O),B=()=>{if(!V)V=!0,K(),z.destroy(d5("文件搜索被用户中止"))},J.signal.addEventListener)J.signal.addEventListener("abort",B);else if("onabort"in J.signal)J.signal.onabort=B;z.once("error",(E)=>{if(!V)V=!0,K(),W(E)}),z.once("end",()=>{if(!V)V=!0,K(),Q({matches:X,wasTruncated:H})})})}function LY($){return $.sort((Z,J)=>{if(Z.is_directory!==J.is_directory)return Z.is_directory?1:-1;if(Z.modified&&J.modified)return new Date(J.modified).getTime()-new Date(Z.modified).getTime();return Z.relative_path.localeCompare(J.relative_path)})}import{execSync as p5,spawn as c5}from"child_process";import{existsSync as g5}from"fs";import{readdir as NY,readFile as bY}from"fs/promises";import{join as
|
|
469
|
-
`).forEach((B,K)=>{if(X.test(B))U.push({file_path:
|
|
470
|
-
`),Y=[];switch(Z){case"files_with_matches":return J.map((U)=>({file_path:U.trim()}));case"count":return J.map((U)=>{let[X,H]=U.split(":");return{file_path:X,count:parseInt(H,10)}});case"content":for(let U of J){let X=uY(U);if(X)Y.push(X)}return Y;default:return[]}}function uY($){let Z=$.indexOf(":");if(Z===-1)return null;let J=$.substring(0,Z),Y=$.substring(Z+1),U=Y.indexOf(":");if(U!==-1&&/^\d+$/.test(Y.substring(0,U))){let X=parseInt(Y.substring(0,U),10),H=Y.substring(U+1);return{file_path:J,line_number:X,content:H}}else return{file_path:J,content:Y}}var i5=
|
|
468
|
+
Use the relative_path values above for Read/Edit operations.`;else q=`No files found matching "${J}"`;return{success:!0,llmContent:q,metadata:{...E,matches:O,summary:`找到 ${K.length} 个匹配 "${J}" 的文件`}}}catch(V){let B=V;if(B.name==="AbortError")return{success:!1,llmContent:"File search aborted",metadata:{summary:"搜索失败: 操作被中止"},error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`Search failed: ${B.message}`,metadata:{summary:`搜索失败: ${B.message}`},error:{type:"execution_error",message:B.message,details:B}}}},version:"2.0.0",category:"搜索工具",tags:["file","search","glob","pattern","wildcard"],extractSignatureContent:($)=>$.pattern,abstractPermissionRule:()=>"*"});async function AY($,Z,J,Y){let U=Y.getIgnorePatterns(),X=[],H=!1;return await new Promise((Q,W)=>{if(J.signal.aborted){W(d5("文件搜索被用户中止"));return}let z=FY.stream(Z,{cwd:$,dot:!0,followSymbolicLinks:!1,unique:!0,caseSensitiveMatch:J.caseSensitive,objectMode:!0,stats:!0,onlyFiles:!J.includeDirectories,ignore:U}),V=!1,B=null,K=()=>{if(B){if(J.signal.removeEventListener)J.signal.removeEventListener("abort",B);else if("onabort"in J.signal)J.signal.onabort=null;B=null}},G=()=>{if(!V)V=!0,H=!0,z.destroy(),K(),Q({matches:X,wasTruncated:H})},O=(E)=>{if(J.signal.aborted){if(!V)V=!0,z.destroy(d5("文件搜索被用户中止"));return}if(X.length>=J.maxResults){G();return}let q=E.path.replace(/\\/g,"/"),F=DY($,q);if(Y.shouldIgnore(q))return;let D=E.stats?E.stats.isDirectory():!1;if(D&&Y.shouldIgnoreDirectory(q))return;let L=E.stats&&E.stats.isFile()?E.stats.size:void 0,A=E.stats?E.stats.mtime.toISOString():void 0;if(X.push({path:F,relative_path:q,is_directory:D,size:L,modified:A}),X.length>=J.maxResults)G()};if(z.on("data",O),B=()=>{if(!V)V=!0,K(),z.destroy(d5("文件搜索被用户中止"))},J.signal.addEventListener)J.signal.addEventListener("abort",B);else if("onabort"in J.signal)J.signal.onabort=B;z.once("error",(E)=>{if(!V)V=!0,K(),W(E)}),z.once("end",()=>{if(!V)V=!0,K(),Q({matches:X,wasTruncated:H})})})}function LY($){return $.sort((Z,J)=>{if(Z.is_directory!==J.is_directory)return Z.is_directory?1:-1;if(Z.modified&&J.modified)return new Date(J.modified).getTime()-new Date(Z.modified).getTime();return Z.relative_path.localeCompare(J.relative_path)})}import{execSync as p5,spawn as c5}from"child_process";import{existsSync as g5}from"fs";import{readdir as NY,readFile as bY}from"fs/promises";import{join as TY,relative as jY}from"path";import MY from"picomatch";function CY(){let{platform:$,arch:Z}=process,J={"darwin-arm64":"darwin-arm64/rg","darwin-x64":"darwin-x64/rg","linux-arm64":"linux-arm64/rg","linux-x64":"linux-x64/rg","win32-x64":"win32-x64/rg.exe"},Y=`${$}-${Z}`,U=J[Y];if(!U)return null;try{let X=new URL("../../../../vendor/ripgrep/"+U,import.meta.url).pathname;if(g5(X))return X}catch{}return null}function sZ(){try{let Z=process.platform==="win32"?"where rg":"command -v rg 2>/dev/null || which rg 2>/dev/null",J=p5(Z,{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).split(/\r?\n/)[0].trim();if(J)return J}catch{}let $=CY();if($&&g5($))return $;try{let Z=g0("@vscode/ripgrep");if(Z?.rgPath&&g5(Z.rgPath))return Z.rgPath}catch{}return null}async function fY($){try{return p5("git rev-parse --git-dir",{cwd:$,stdio:"ignore"}),!0}catch{return!1}}function RY(){try{return p5("grep --version",{stdio:"ignore"}),!0}catch{return!1}}async function SY($,Z,J,Y){let U=sZ();if(!U)throw Error("ripgrep not available");return new Promise((X,H)=>{let Q=c5(U,$,{stdio:["pipe","pipe","pipe"]}),W="",z="";Q.stdout.on("data",(B)=>{W+=B.toString()}),Q.stderr.on("data",(B)=>{z+=B.toString()}),Q.on("close",(B)=>{X({stdout:W,stderr:z,exitCode:B||0})}),Q.on("error",(B)=>{H(B)});let V=()=>{Q.kill("SIGTERM"),H(Error("搜索被用户中止"))};J.addEventListener("abort",V),Q.on("close",()=>{J.removeEventListener("abort",V)})})}async function PY($,Z,J,Y){let U=["grep","-n"];if(J.caseInsensitive)U.push("-i");if(J.contextLines!==void 0)U.push(`-C${J.contextLines}`);if(U.push("-e",$),J.glob)U.push("--",J.glob);return new Promise((X,H)=>{let Q=c5("git",U,{cwd:Z,stdio:["pipe","pipe","pipe"]}),W="",z="";Q.stdout.on("data",(B)=>{W+=B.toString()}),Q.stderr.on("data",(B)=>{z+=B.toString()}),Q.on("close",(B)=>{X({stdout:W,stderr:z,exitCode:B||0})}),Q.on("error",(B)=>{H(B)});let V=()=>{Q.kill("SIGTERM"),H(Error("搜索被用户中止"))};Y.addEventListener("abort",V),Q.on("close",()=>{Y.removeEventListener("abort",V)})})}async function kY($,Z,J,Y){let U=["-rn"];if(J.caseInsensitive)U.push("-i");if(J.contextLines!==void 0)U.push(`-C${J.contextLines}`);for(let X of I$)U.push("--exclude-dir="+X.replace(/^\./,""));return U.push("-e",$,Z),new Promise((X,H)=>{let Q=c5("grep",U,{stdio:["pipe","pipe","pipe"]}),W="",z="";Q.stdout.on("data",(B)=>{W+=B.toString()}),Q.stderr.on("data",(B)=>{z+=B.toString()}),Q.on("close",(B)=>{X({stdout:W,stderr:z,exitCode:B||0})}),Q.on("error",(B)=>{H(B)});let V=()=>{Q.kill("SIGTERM"),H(Error("搜索被用户中止"))};Y.addEventListener("abort",V),Q.on("close",()=>{Y.removeEventListener("abort",V)})})}async function vY($,Z,J,Y){let U=[],X=new RegExp($,J.caseInsensitive?"gi":"g"),H=await IY(Z,Y),Q=0;for(let W of H){if(Y.throwIfAborted(),tZ(W))continue;if(J.glob&&!yY(W,J.glob))continue;try{(await bY(W,"utf-8")).split(`
|
|
469
|
+
`).forEach((B,K)=>{if(X.test(B))U.push({file_path:jY(Z,W),line_number:K+1,content:B})}),Q++}catch(z){continue}}return{matches:U,totalFiles:Q}}async function IY($,Z){let J=[];async function Y(U){Z.throwIfAborted();try{let X=await NY(U,{withFileTypes:!0});for(let H of X){Z.throwIfAborted();let Q=TY(U,H.name);if(H.isDirectory()){if(!tZ(Q))await Y(Q)}else if(H.isFile())J.push(Q)}}catch(X){}}return await Y($),J}function tZ($){for(let Z of I$)if($.includes(Z))return!0;return!1}function yY($,Z){return MY(Z)($)}function xY($){let Z=[];if($.case_insensitive)Z.push("-i");if($.multiline)Z.push("-U","--multiline-dotall");switch($.output_mode){case"files_with_matches":Z.push("-l");break;case"count":Z.push("-c");break;case"content":if($.line_numbers)Z.push("-n");break}if($.context!==void 0&&$.output_mode==="content")Z.push("-C",$.context.toString());else{if($.context_before!==void 0&&$.output_mode==="content")Z.push("-B",$.context_before.toString());if($.context_after!==void 0&&$.output_mode==="content")Z.push("-A",$.context_after.toString())}if($.type)Z.push("--type",$.type);for(let J of I$)Z.push("--glob",`!${J}/**`);if($.glob)Z.push("--glob",$.glob);if($.head_limit!==void 0){let J=($.offset??0)+$.head_limit;Z.push("-m",J.toString())}return Z.push($.pattern),Z.push($.path),Z}function hY($,Z){if(!$.trim())return[];let J=$.trim().split(`
|
|
470
|
+
`),Y=[];switch(Z){case"files_with_matches":return J.map((U)=>({file_path:U.trim()}));case"count":return J.map((U)=>{let[X,H]=U.split(":");return{file_path:X,count:parseInt(H,10)}});case"content":for(let U of J){let X=uY(U);if(X)Y.push(X)}return Y;default:return[]}}function uY($){let Z=$.indexOf(":");if(Z===-1)return null;let J=$.substring(0,Z),Y=$.substring(Z+1),U=Y.indexOf(":");if(U!==-1&&/^\d+$/.test(Y.substring(0,U))){let X=parseInt(Y.substring(0,U),10),H=Y.substring(U+1);return{file_path:J,line_number:X,content:H}}else return{file_path:J,content:Y}}var i5=j({name:"Grep",displayName:"内容搜索",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({pattern:g.pattern({description:"The regular expression pattern to search for in file contents"}),path:_.Optional(_.String({description:"File or directory to search in (rg PATH). Defaults to current working directory"})),glob:_.Optional(_.String({description:'Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}") - maps to rg --glob'})),type:_.Optional(_.String({description:"File type to search (rg --type). Common types: js, py, rust, go, java, etc."})),output_mode:f(d(["content","files_with_matches","count"],{description:"Output mode: content, files_with_matches, or count. Defaults to files_with_matches."}),"files_with_matches"),"-i":_.Optional(_.Boolean({description:"Case insensitive search (rg -i)"})),"-n":f(_.Boolean({description:"Show line numbers in content output (rg -n). Defaults to true."}),!0),"-B":_.Optional(g.nonNegativeInt({description:"Lines before each match (rg -B)"})),"-A":_.Optional(g.nonNegativeInt({description:"Lines after each match (rg -A)"})),"-C":_.Optional(g.nonNegativeInt({description:"Lines before and after each match (rg -C)"})),head_limit:_.Optional(g.positiveInt({description:"Limit output to first N lines or entries"})),offset:_.Optional(g.nonNegativeInt({description:"Skip first N lines or entries before applying head_limit"})),multiline:f(_.Boolean({description:"Enable multiline matching (rg -U --multiline-dotall)"}),!1)}),description:{short:"A powerful search tool built on ripgrep",long:'A powerful search tool built on ripgrep\n\n Usage:\n - ALWAYS use Grep for search tasks. NEVER invoke `grep` or `rg` as a Bash command. The Grep tool has been optimized for correct permissions and access.\n - Supports full regex syntax (e.g., "log.*Error", "function\\s+\\w+")\n - Filter files with glob parameter (e.g., "*.js", "**/*.tsx") or type parameter (e.g., "js", "py", "rust")\n - Output modes: "content" shows matching lines, "files_with_matches" shows only file paths (default), "count" shows match counts\n - Use Task tool for open-ended searches requiring multiple rounds\n - Pattern syntax: Uses ripgrep (not grep) - literal braces need escaping (use `interface\\{\\}` to find `interface{}` in Go code)\n - Multiline matching: By default patterns match within single lines only. For cross-line patterns like `struct \\{[\\s\\S]*?field`, use `multiline: true`\n'},async execute($,Z){let{pattern:J,path:Y,glob:U,type:X,output_mode:H,"-i":Q,"-n":W=!0,"-B":z,"-A":V,"-C":B,head_limit:K,offset:G,multiline:O}=$,{updateOutput:E}=Z,q=Z.signal??new AbortController().signal,F=Y??Z.workspaceRoot??N();try{E?.(`使用智能搜索策略查找模式 "${J}"...`);let D=null,L="ripgrep",A=[],w=sZ();if(w)try{E?.(`使用 ripgrep (${w})`);let P=xY({pattern:J,path:F,glob:U,type:X,output_mode:H,case_insensitive:Q??!1,line_numbers:W,context_before:z,context_after:V,context:B,head_limit:K,offset:G,multiline:O??!1});D=await SY(P,H,q,E),L="ripgrep"}catch{E?.("[WARN] ripgrep 失败,尝试降级策略..."),D=null}if(!D&&await fY(F))try{E?.("使用 git grep"),D=await PY(J,F,{caseInsensitive:Q??!1,glob:U,contextLines:B},q),L="git-grep"}catch{E?.("[WARN] git grep 失败,继续尝试其他策略..."),D=null}if(!D&&RY())try{E?.("使用系统 grep"),D=await kY(J,F,{caseInsensitive:Q??!1,contextLines:B},q),L="system-grep"}catch{E?.("[WARN] 系统 grep 失败,使用纯 JavaScript 实现..."),D=null}if(!D)E?.("使用纯 JavaScript 搜索实现"),A=(await vY(J,F,{caseInsensitive:Q??!1,glob:U,multiline:O??!1},q)).matches,L="fallback",D={stdout:"",stderr:"",exitCode:0};else A=hY(D.stdout,H);let T=A.length;if(G!==void 0&&G>0)A=A.slice(G);if(K!==void 0&&A.length>K)A=A.slice(0,K);let b={search_pattern:J,search_path:F,output_mode:H,case_insensitive:Q??!1,total_matches:A.length,original_total:T,offset:G,head_limit:K,strategy:L,exit_code:D?.exitCode};if(D&&D.exitCode!==0&&D.stderr)return{success:!1,llmContent:`Search execution failed: ${D.stderr}`,metadata:{...b,summary:`搜索失败: ${D.stderr}`},error:{type:"execution_error",message:D.stderr}};return{success:!0,llmContent:A,metadata:{...b,summary:A.length>0?`搜索 "${J}" 找到 ${A.length} 个文件`:`搜索 "${J}" 未找到匹配`}}}catch(D){let L=D;if(L.name==="AbortError")return{success:!1,llmContent:"Search aborted",metadata:{summary:"搜索失败: 操作被中止"},error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`Search failed: ${L.message}`,metadata:{summary:`搜索失败: ${L.message}`},error:{type:"execution_error",message:L.message,details:L}}}},version:"3.0.0",category:"搜索工具",tags:["search","grep","ripgrep","regex","text","fallback"],extractSignatureContent:($)=>$.pattern,abstractPermissionRule:()=>"*"});import{isAbsolute as dY,resolve as mY}from"node:path";var l5=j({name:"Bash",displayName:"Bash Command",kind:"execute",isConcurrencySafe:!1,parallelism:"shared",schema:_.Object({command:g.command({description:"Bash command to execute"}),timeout:g.timeout(1000,300000,30000),cwd:_.Optional(_.String({description:"Working directory (optional; applies only to this command). To persist, use cd"})),env:g.environment(),run_in_background:f(_.Boolean({description:"Run in background (suitable for long-running commands)"}),!1)}),description:{short:"Execute bash commands in a persistent shell session with optional timeout",long:`Executes bash commands with proper handling and security measures.
|
|
471
471
|
|
|
472
472
|
IMPORTANT: This tool is for terminal operations like git, npm, docker, etc. DO NOT use it for file operations (reading, writing, editing, searching, finding files) - use the specialized tools for this instead.
|
|
473
473
|
|
|
@@ -487,19 +487,19 @@ Before executing commands:
|
|
|
487
487
|
${Y}`:"",J?`stdout:
|
|
488
488
|
${J}`:""].filter(Boolean);return X.length>0?`${U}
|
|
489
489
|
${X.join(`
|
|
490
|
-
`)}`:U}async function pY($,Z,J,Y,U,X,H){let Q=Date.now();try{let z=await V4(X).execute($,{cwd:Z||N(),env:J,timeout:Y,signal:U,onOutput:(q)=>{H?.(q)}}),V=Date.now()-Q;if(U.aborted||z.error==="Command was aborted"||z.error==="Command was terminated")return{success:!1,llmContent:"Command execution aborted by user",error:{type:"execution_error",message:"操作被中止"},metadata:{command:$,aborted:!0,stdout:z.stdout,stderr:z.stderr,execution_time:V}};if(z.error==="Command timed out")return{success:!1,llmContent:`Command execution timed out (${Y}ms)`,error:{type:"timeout_error",message:"命令执行超时"},metadata:{command:$,timeout:!0,stdout:z.stdout,stderr:z.stderr,execution_time:V}};let B=$.length>30?`${$.substring(0,30)}...`:$,K=z.exitCode===0?`执行命令成功 (${V}ms): ${B}`:`执行命令完成 (退出码 ${z.exitCode}, ${V}ms): ${B}`,G={command:$,execution_time:V,exit_code:z.exitCode,stdout_length:z.stdout.length,stderr_length:z.stderr.length,has_stderr:z.stderr.length>0,acp_mode:!0,summary:K},O=s$.truncateForLLM(z.stdout.trim(),z.stderr.trim(),$),E={stdout:O.stdout,stderr:O.stderr,execution_time:V,exit_code:z.exitCode,...O.truncationInfo&&{truncation_info:O.truncationInfo}};return{success:z.success,llmContent:E,...z.success?{}:{error:{type:"execution_error",message:eZ(z.exitCode,void 0,O.stdout,O.stderr)}},metadata:G}}catch(W){let z=W,V=Date.now()-Q;return{success:!1,llmContent:`Command execution failed: ${z.message}`,error:{type:"execution_error",message:z.message,details:z},metadata:{command:$,execution_time:V,error:z.message}}}}async function cY($,Z,J,Y,U,X,H){return new Promise((Q)=>{let W=Date.now(),z="",V="",B=!1,K=H?.executable??"bash",G=H?.args??["-c",$],O=H?.inheritProcessEnv===!1?iY(process.env):process.env,{child:E,processTree:q}=p0(K,G,{cwd:Z||N(),env:{...O,...J,...H?.env,BLADE_CLI:"1"},stdio:["pipe","pipe","pipe"]}),F,D=()=>{return F??=q.terminate(),F};E.stdout?.on("data",(w)=>{z+=w.toString()}),E.stderr?.on("data",(w)=>{V+=w.toString()});let L=setTimeout(()=>{B=!0,D()},Y),A=()=>{D(),clearTimeout(L)};if(U.addEventListener)U.addEventListener("abort",A);else if("onabort"in U)U.onabort=A;if(U.aborted)A();E.on("close",async(w,
|
|
490
|
+
`)}`:U}async function pY($,Z,J,Y,U,X,H){let Q=Date.now();try{let z=await V4(X).execute($,{cwd:Z||N(),env:J,timeout:Y,signal:U,onOutput:(q)=>{H?.(q)}}),V=Date.now()-Q;if(U.aborted||z.error==="Command was aborted"||z.error==="Command was terminated")return{success:!1,llmContent:"Command execution aborted by user",error:{type:"execution_error",message:"操作被中止"},metadata:{command:$,aborted:!0,stdout:z.stdout,stderr:z.stderr,execution_time:V}};if(z.error==="Command timed out")return{success:!1,llmContent:`Command execution timed out (${Y}ms)`,error:{type:"timeout_error",message:"命令执行超时"},metadata:{command:$,timeout:!0,stdout:z.stdout,stderr:z.stderr,execution_time:V}};let B=$.length>30?`${$.substring(0,30)}...`:$,K=z.exitCode===0?`执行命令成功 (${V}ms): ${B}`:`执行命令完成 (退出码 ${z.exitCode}, ${V}ms): ${B}`,G={command:$,execution_time:V,exit_code:z.exitCode,stdout_length:z.stdout.length,stderr_length:z.stderr.length,has_stderr:z.stderr.length>0,acp_mode:!0,summary:K},O=s$.truncateForLLM(z.stdout.trim(),z.stderr.trim(),$),E={stdout:O.stdout,stderr:O.stderr,execution_time:V,exit_code:z.exitCode,...O.truncationInfo&&{truncation_info:O.truncationInfo}};return{success:z.success,llmContent:E,...z.success?{}:{error:{type:"execution_error",message:eZ(z.exitCode,void 0,O.stdout,O.stderr)}},metadata:G}}catch(W){let z=W,V=Date.now()-Q;return{success:!1,llmContent:`Command execution failed: ${z.message}`,error:{type:"execution_error",message:z.message,details:z},metadata:{command:$,execution_time:V,error:z.message}}}}async function cY($,Z,J,Y,U,X,H){return new Promise((Q)=>{let W=Date.now(),z="",V="",B=!1,K=H?.executable??"bash",G=H?.args??["-c",$],O=H?.inheritProcessEnv===!1?iY(process.env):process.env,{child:E,processTree:q}=p0(K,G,{cwd:Z||N(),env:{...O,...J,...H?.env,BLADE_CLI:"1"},stdio:["pipe","pipe","pipe"]}),F,D=()=>{return F??=q.terminate(),F};E.stdout?.on("data",(w)=>{z+=w.toString()}),E.stderr?.on("data",(w)=>{V+=w.toString()});let L=setTimeout(()=>{B=!0,D()},Y),A=()=>{D(),clearTimeout(L)};if(U.addEventListener)U.addEventListener("abort",A);else if("onabort"in U)U.onabort=A;if(U.aborted)A();E.on("close",async(w,T)=>{if(H?.cleanup(),clearTimeout(L),U.removeEventListener)U.removeEventListener("abort",A);else if("onabort"in U)U.onabort=null;let b=Date.now()-W;if(B||U.aborted)await D();if(B){Q({success:!1,llmContent:`Command execution timed out (${Y}ms)`,error:{type:"timeout_error",message:"命令执行超时"},metadata:{command:$,sandboxed:Boolean(H),timeout:!0,stdout:z,stderr:V,execution_time:b}});return}if(U.aborted){Q({success:!1,llmContent:"Command execution aborted by user",error:{type:"execution_error",message:"操作被中止"},metadata:{command:$,sandboxed:Boolean(H),aborted:!0,stdout:z,stderr:V,execution_time:b}});return}if(H&&d1(w,V)){Q({success:!1,llmContent:"Workspace sandbox could not start, so the Bash command was not executed.",error:{type:"permission_denied",message:V.trim()||"Workspace sandbox failed to start"},metadata:{command:$,sandbox_required:!0,sandboxed:!1,execution_time:b,exit_code:w,stderr:V,summary:"Workspace sandbox failed closed"}});return}let P=$.length>30?`${$.substring(0,30)}...`:$,M=w===0?`执行命令成功 (${b}ms): ${P}`:`执行命令完成 (退出码 ${w}, ${b}ms): ${P}`,C={command:$,execution_time:b,exit_code:w,signal:T,stdout_length:z.length,stderr_length:V.length,has_stderr:V.length>0,sandboxed:Boolean(H),summary:M},S=s$.truncateForLLM(z.trim(),V.trim(),$),p={stdout:S.stdout,stderr:S.stderr,execution_time:b,exit_code:w,signal:T,...S.truncationInfo&&{truncation_info:S.truncationInfo}},m=w===0;Q({success:m,llmContent:p,...m?{}:{error:{type:"execution_error",message:eZ(w,T,S.stdout,S.stderr)}},metadata:C})}),E.on("error",(w)=>{if(H?.cleanup(),clearTimeout(L),U.removeEventListener)U.removeEventListener("abort",A);else if("onabort"in U)U.onabort=null;Q({success:!1,llmContent:`Command execution failed: ${w.message}`,error:{type:"execution_error",message:w.message,details:w}})})})}function iY($){return Object.fromEntries(["CI","COLORTERM","FORCE_COLOR","LANG","LANGUAGE","LC_ALL","LC_CTYPE","NO_COLOR","PATH","TERM","TZ"].flatMap((J)=>{let Y=$[J];return Y===void 0?[]:[[J,Y]]}))}var n5=j({name:"KillShell",displayName:"终止后台 Shell",kind:"execute",isConcurrencySafe:!1,schema:_.Object({shell_id:_.String({minLength:1,description:"Background Shell ID to terminate"})}),description:{short:"Kills a running background bash shell by its ID",long:`
|
|
491
491
|
- Kills a running background bash shell by its ID
|
|
492
492
|
- Takes a shell_id parameter identifying the shell to kill
|
|
493
493
|
- Returns a success or failure status
|
|
494
494
|
- Use this tool when you need to terminate a long-running shell
|
|
495
495
|
- Shell IDs can be found using the /tasks command
|
|
496
|
-
`},async execute($,Z){let J=s.getInstance(),Y=Z.sessionId?await J.kill($.shell_id,Z.sessionId):void 0;if(!Y)return{success:!1,llmContent:`Shell not found: ${$.shell_id}`,error:{type:"execution_error",message:"Shell ID 不存在或已清理"},metadata:{summary:`未找到 Shell: ${$.shell_id}`}};if(!Y.success&&!Y.alreadyExited)return{success:!1,llmContent:`Failed to terminate Shell: ${$.shell_id}`,error:{type:"execution_error",message:"发送终止信号失败"},metadata:{...Y,summary:`终止 Shell 失败: ${$.shell_id}`}};return{success:!0,llmContent:{shell_id:$.shell_id,status:Y.status,already_exited:Y.alreadyExited,pid:Y.pid,exit_code:Y.exitCode,signal:Y.signal},metadata:{...Y,summary:`终止 Shell: ${$.shell_id}`}}},version:"1.0.0",category:"命令工具",tags:["bash","shell","terminate"],extractSignatureContent:($)=>$.shell_id,abstractPermissionRule:()=>"*"});var r5=65536,lY=_.Refine(_.Object({shell_id:_.String({minLength:1,description:"Background shell ID returned by Bash"}),data:_.Refine(_.String({maxLength:r5,description:"Exact text to write. Include a newline when the process expects one."}),($)=>Buffer.byteLength($)<=r5,()=>`data must be at most ${r5} bytes`),close_stdin:f(_.Boolean({description:"Close stdin after writing so programs waiting for EOF can finish"}),!1)}),({data:$,close_stdin:Z})=>$.length>0||Z,()=>"data cannot be empty unless close_stdin is true"),a5=
|
|
496
|
+
`},async execute($,Z){let J=s.getInstance(),Y=Z.sessionId?await J.kill($.shell_id,Z.sessionId):void 0;if(!Y)return{success:!1,llmContent:`Shell not found: ${$.shell_id}`,error:{type:"execution_error",message:"Shell ID 不存在或已清理"},metadata:{summary:`未找到 Shell: ${$.shell_id}`}};if(!Y.success&&!Y.alreadyExited)return{success:!1,llmContent:`Failed to terminate Shell: ${$.shell_id}`,error:{type:"execution_error",message:"发送终止信号失败"},metadata:{...Y,summary:`终止 Shell 失败: ${$.shell_id}`}};return{success:!0,llmContent:{shell_id:$.shell_id,status:Y.status,already_exited:Y.alreadyExited,pid:Y.pid,exit_code:Y.exitCode,signal:Y.signal},metadata:{...Y,summary:`终止 Shell: ${$.shell_id}`}}},version:"1.0.0",category:"命令工具",tags:["bash","shell","terminate"],extractSignatureContent:($)=>$.shell_id,abstractPermissionRule:()=>"*"});var r5=65536,lY=_.Refine(_.Object({shell_id:_.String({minLength:1,description:"Background shell ID returned by Bash"}),data:_.Refine(_.String({maxLength:r5,description:"Exact text to write. Include a newline when the process expects one."}),($)=>Buffer.byteLength($)<=r5,()=>`data must be at most ${r5} bytes`),close_stdin:f(_.Boolean({description:"Close stdin after writing so programs waiting for EOF can finish"}),!1)}),({data:$,close_stdin:Z})=>$.length>0||Z,()=>"data cannot be empty unless close_stdin is true"),a5=j({name:"WriteStdin",displayName:"Write to Shell",kind:"execute",isConcurrencySafe:!1,schema:lY,description:{short:"Writes input to a running background Bash shell",long:`
|
|
497
497
|
- Writes exact text to a background shell started by Bash with run_in_background=true
|
|
498
498
|
- Use the shell_id returned by Bash; shells are private to the active session
|
|
499
499
|
- Include a newline in data for line-oriented prompts or REPLs
|
|
500
500
|
- Set close_stdin=true when the program must receive EOF before it can finish
|
|
501
501
|
- Use TaskOutput afterward to wait for and read the process output
|
|
502
|
-
`.trim()},async execute($,Z){if(!Z.sessionId)return{success:!1,llmContent:"WriteStdin requires an active session",error:{type:"validation_error",message:"Active session is required to write shell input"},metadata:{summary:"Cannot write Shell input without a session"}};let J=await s.getInstance().writeInput($.shell_id,Z.sessionId,$.data,$.close_stdin);if(!J)return{success:!1,llmContent:`Shell not found: ${$.shell_id}`,error:{type:"execution_error",message:"Shell ID does not exist or is no longer available"},metadata:{summary:`Shell not found: ${$.shell_id}`}};if(!J.success)return{success:!1,llmContent:{shell_id:$.shell_id,status:J.status,stdin_closed:J.stdinClosed,error:J.errorMessage},error:{type:"execution_error",message:J.errorMessage||"Failed to write Shell stdin"},metadata:{...J,summary:`Failed to write Shell: ${$.shell_id}`}};return{success:!0,llmContent:{shell_id:$.shell_id,status:J.status,bytes_written:J.bytesWritten,stdin_closed:J.stdinClosed},metadata:{...J,shell_id:$.shell_id,summary:`Sent ${J.bytesWritten} bytes to Shell: ${$.shell_id}`}}},version:"1.0.0",category:"命令工具",tags:["bash","shell","stdin","interactive"],extractSignatureContent:($)=>$.shell_id,abstractPermissionRule:()=>"*"});var nY=_.Object({label:_.String({description:"The display text for this option that the user will see and select. Should be concise (1-5 words)."}),description:_.String({description:"Explanation of what this option means or what will happen if chosen."})}),rY=_.Object({question:_.String({description:"The complete, clear question to ask the user. End it with a question mark."}),header:_.String({maxLength:12,description:"Very short label displayed as a chip/tag (max 12 chars)."}),multiSelect:_.Boolean({description:"Allow multiple answers when true. Use only when choices are not mutually exclusive."}),options:_.Array(nY,{minItems:2,maxItems:4,description:"The available choices for this question (2-4 options)."})}),aY=_.Object({questions:_.Array(rY,{minItems:1,maxItems:4,description:"Questions to ask the user (1-4 questions)"})}),o5=
|
|
502
|
+
`.trim()},async execute($,Z){if(!Z.sessionId)return{success:!1,llmContent:"WriteStdin requires an active session",error:{type:"validation_error",message:"Active session is required to write shell input"},metadata:{summary:"Cannot write Shell input without a session"}};let J=await s.getInstance().writeInput($.shell_id,Z.sessionId,$.data,$.close_stdin);if(!J)return{success:!1,llmContent:`Shell not found: ${$.shell_id}`,error:{type:"execution_error",message:"Shell ID does not exist or is no longer available"},metadata:{summary:`Shell not found: ${$.shell_id}`}};if(!J.success)return{success:!1,llmContent:{shell_id:$.shell_id,status:J.status,stdin_closed:J.stdinClosed,error:J.errorMessage},error:{type:"execution_error",message:J.errorMessage||"Failed to write Shell stdin"},metadata:{...J,summary:`Failed to write Shell: ${$.shell_id}`}};return{success:!0,llmContent:{shell_id:$.shell_id,status:J.status,bytes_written:J.bytesWritten,stdin_closed:J.stdinClosed},metadata:{...J,shell_id:$.shell_id,summary:`Sent ${J.bytesWritten} bytes to Shell: ${$.shell_id}`}}},version:"1.0.0",category:"命令工具",tags:["bash","shell","stdin","interactive"],extractSignatureContent:($)=>$.shell_id,abstractPermissionRule:()=>"*"});var nY=_.Object({label:_.String({description:"The display text for this option that the user will see and select. Should be concise (1-5 words)."}),description:_.String({description:"Explanation of what this option means or what will happen if chosen."})}),rY=_.Object({question:_.String({description:"The complete, clear question to ask the user. End it with a question mark."}),header:_.String({maxLength:12,description:"Very short label displayed as a chip/tag (max 12 chars)."}),multiSelect:_.Boolean({description:"Allow multiple answers when true. Use only when choices are not mutually exclusive."}),options:_.Array(nY,{minItems:2,maxItems:4,description:"The available choices for this question (2-4 options)."})}),aY=_.Object({questions:_.Array(rY,{minItems:1,maxItems:4,description:"Questions to ask the user (1-4 questions)"})}),o5=j({name:"AskUserQuestion",displayName:"Ask User Question",kind:"readonly",isConcurrencySafe:!1,schema:aY,description:{short:"Ask user questions to gather preferences or clarify requirements",long:`Use this tool when you need to ask the user questions during execution. This allows you to:
|
|
503
503
|
1. Gather user preferences or requirements
|
|
504
504
|
2. Clarify ambiguous instructions
|
|
505
505
|
3. Get decisions on implementation choices as you work
|
|
@@ -510,7 +510,7 @@ Usage notes:
|
|
|
510
510
|
- Use multiSelect: true to allow multiple answers to be selected for a question
|
|
511
511
|
- If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label`},async execute($,Z){if(Z.confirmationHandler)try{let J=await Z.confirmationHandler.requestConfirmation({type:"askUserQuestion",kind:"readonly",message:"Please answer the following questions:",questions:$.questions},Z.signal);if(!J.approved)return{success:!0,llmContent:"User cancelled the question prompt without providing answers.",metadata:{cancelled:!0,summary:"用户取消了问题"}};if(J.answers&&Object.keys(J.answers).length>0)return{success:!0,llmContent:`User answers:
|
|
512
512
|
${Object.entries(J.answers).map(([U,X])=>{let H=Array.isArray(X)?X.join(", "):X;return`${U}: ${H}`}).join(`
|
|
513
|
-
`)}`,metadata:{answers:J.answers,summary:"用户已回答问题"}};return{success:!0,llmContent:"The question was approved but no answers were collected. This typically happens in IDE/ACP sessions where structured question UI is not available. Please ask the user directly in your response or make reasonable assumptions based on context.",metadata:{acpMode:!0,noAnswersCollected:!0,summary:"ACP 模式:无法收集答案"}}}catch(J){return{success:!1,llmContent:`Failed to ask user questions: ${J instanceof Error?J.message:"Unknown error"}`,error:{type:"execution_error",message:"Failed to display questions"},metadata:{summary:"问题显示失败"}}}return{success:!1,llmContent:"No confirmation handler available. Cannot ask user questions in non-interactive mode.",error:{type:"execution_error",message:"No confirmation handler available"},metadata:{summary:"非交互模式,无法提问"}}}});function X2($=C0()){let Z=$.generateAvailableSkillsList();return
|
|
513
|
+
`)}`,metadata:{answers:J.answers,summary:"用户已回答问题"}};return{success:!0,llmContent:"The question was approved but no answers were collected. This typically happens in IDE/ACP sessions where structured question UI is not available. Please ask the user directly in your response or make reasonable assumptions based on context.",metadata:{acpMode:!0,noAnswersCollected:!0,summary:"ACP 模式:无法收集答案"}}}catch(J){return{success:!1,llmContent:`Failed to ask user questions: ${J instanceof Error?J.message:"Unknown error"}`,error:{type:"execution_error",message:"Failed to display questions"},metadata:{summary:"问题显示失败"}}}return{success:!1,llmContent:"No confirmation handler available. Cannot ask user questions in non-interactive mode.",error:{type:"execution_error",message:"No confirmation handler available"},metadata:{summary:"非交互模式,无法提问"}}}});function X2($=C0()){let Z=$.generateAvailableSkillsList();return j({name:"Skill",displayName:"Skill",kind:"execute",isConcurrencySafe:!1,schema:_.Object({skill:_.String({description:'The skill name. E.g., "commit-message" or "code-review"'}),args:_.Optional(_.String({description:"Optional arguments for the skill"}))}),description:{short:"Execute a skill within the main conversation",long:`Execute a skill within the main conversation
|
|
514
514
|
|
|
515
515
|
<skills_instructions>
|
|
516
516
|
When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.
|
|
@@ -548,7 +548,7 @@ Remember: Follow the above instructions carefully to complete the user's request
|
|
|
548
548
|
|
|
549
549
|
<available_commands>
|
|
550
550
|
${Z}
|
|
551
|
-
</available_commands>`}function H2($=R0.getInstance()){return
|
|
551
|
+
</available_commands>`}function H2($=R0.getInstance()){return j({name:"SlashCommand",displayName:"Slash Command",kind:"execute",isConcurrencySafe:!1,schema:_.Object({command:_.String({description:'The command name without the leading slash, e.g., "review-pr" or "commit"'}),arguments:_.Optional(_.String({description:'Arguments to pass to the command, e.g., "123" or "fix bug"'}))}),description:{short:"Execute a custom slash command within the main conversation",long:`Execute a custom slash command within the main conversation
|
|
552
552
|
|
|
553
553
|
How slash commands work:
|
|
554
554
|
When you use this tool, the command's content (from .blade/commands/ or .claude/commands/) will be processed and returned. The content may include:
|
|
@@ -587,11 +587,11 @@ ${Z}
|
|
|
587
587
|
|
|
588
588
|
---
|
|
589
589
|
|
|
590
|
-
Remember: Follow the above instructions carefully to complete the user's request.`,Y}var s5=
|
|
590
|
+
Remember: Follow the above instructions carefully to complete the user's request.`,Y}var s5=j({name:"ToolSearch",displayName:"Tool Search",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({query:_.String({description:'Search query. Use "select:Read,Edit,Grep" for exact selection, or keywords for fuzzy search.'}),max_results:f(_.Number({description:"Maximum results to return (default 5)"}),5)}),description:{short:"Search and load deferred tool schemas",long:["Fetches full schema definitions for deferred tools so","they can be called. Deferred tools appear by name in","<available-deferred-tools> messages. Until fetched, only","the name is known — there is no parameter schema, so","the tool cannot be invoked."].join(" "),usageNotes:['Use "select:Read,Edit,Grep" to fetch exact tools by name',"Use keywords to search by tool name or description","Once loaded via ToolSearch, a tool becomes callable"],examples:[{description:"Load specific tools by name",params:{query:"select:WebFetch,WebSearch",max_results:5}},{description:"Search for notebook-related tools",params:{query:"notebook jupyter",max_results:5}}]},async execute($,Z){let{query:J,max_results:Y}=$,U=Z.toolRegistry;if(!U)return{success:!1,llmContent:"Tool registry not available in execution context."};let X=[];if(J.startsWith("select:")){let Q=J.slice(7).split(",").map((W)=>W.trim());for(let W of Q){let z=U.get(W);if(z)X.push({name:z.name,declaration:z.getFunctionDeclaration()})}}else X=U.search(J).slice(0,Y).map((W)=>({name:W.name,declaration:W.getFunctionDeclaration()}));if(X.length===0)return{success:!0,llmContent:`No tools found matching "${J}".`};if(Z.deferredToolManager)for(let{name:Q}of X)Z.deferredToolManager.markLoaded(Q);return{success:!0,llmContent:`<functions>
|
|
591
591
|
${X.map(({declaration:Q})=>`<function>${JSON.stringify(Q)}</function>`).join(`
|
|
592
592
|
`)}
|
|
593
593
|
</functions>`,metadata:{summary:`加载了 ${X.length} 个工具 schema`}}}});import e8 from"node:path";import{nanoid as aU}from"nanoid";import w$ from"node:fs";import x$ from"node:path";var ZU=/^[A-Za-z]:\//;function t5($=""){if(!$)return $;return $.replace(/\\/g,"/").replace(ZU,(Z)=>Z.toUpperCase())}var JU=/^[/\\]{2}/,YU=/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/,UU=/^[A-Za-z]:$/,Z8=/^\/([A-Za-z]:)?$/;var J8=function($){if($.length===0)return".";$=t5($);let Z=$.match(JU),J=D$($),Y=$[$.length-1]==="/";if($=e5($,!J),$.length===0){if(J)return"/";return Y?"./":"."}if(Y)$+="/";if(UU.test($))$+="/";if(Z){if(!J)return`//./${$}`;return`//${$}`}return J&&!D$($)?`/${$}`:$},B0=function(...$){let Z="";for(let J of $){if(!J)continue;if(Z.length>0){let Y=Z[Z.length-1]==="/",U=J[0]==="/";if(Y&&U)Z+=J.slice(1);else Z+=Y||U?J:`/${J}`}else Z+=J}return J8(Z)};function XU(){if(typeof process<"u"&&typeof process.cwd==="function")return process.cwd().replace(/\\/g,"/");return"/"}var H$=function(...$){$=$.map((Y)=>t5(Y));let Z="",J=!1;for(let Y=$.length-1;Y>=-1&&!J;Y--){let U=Y>=0?$[Y]:XU();if(!U||U.length===0)continue;Z=`${U}/${Z}`,J=D$(U)}if(Z=e5(Z,!J),J&&!D$(Z))return`/${Z}`;return Z.length>0?Z:"."};function e5($,Z){let J="",Y=0,U=-1,X=0,H=null;for(let Q=0;Q<=$.length;++Q){if(Q<$.length)H=$[Q];else if(H==="/")break;else H="/";if(H==="/"){if(U===Q-1||X===1);else if(X===2){if(J.length<2||Y!==2||J[J.length-1]!=="."||J[J.length-2]!=="."){if(J.length>2){let W=J.lastIndexOf("/");if(W===-1)J="",Y=0;else J=J.slice(0,W),Y=J.length-1-J.lastIndexOf("/");U=Q,X=0;continue}else if(J.length>0){J="",Y=0,U=Q,X=0;continue}}if(Z)J+=J.length>0?"/..":"..",Y=2}else{if(J.length>0)J+=`/${$.slice(U+1,Q)}`;else J=$.slice(U+1,Q);Y=Q-U-1}U=Q,X=0}else if(H==="."&&X!==-1)++X;else X=-1}return J}var D$=function($){return YU.test($)};var $6=function($,Z){let J=H$($).replace(Z8,"$1").split("/"),Y=H$(Z).replace(Z8,"$1").split("/");if(Y[0][1]===":"&&J[0][1]===":"&&J[0]!==Y[0])return Y.join("/");let U=[...J];for(let X of U){if(Y[0]!==X)break;J.shift(),Y.shift()}return[...J.map(()=>".."),...Y].join("/")};var Z6=function($,Z){let J=t5($).split("/"),Y="";for(let U=J.length-1;U>=0;U--){let X=J[U];if(X){Y=X;break}}return Z&&Y.endsWith(Z)?Y.slice(0,-Z.length):Y};import HU from"write-file-atomic";var w1=u("Agent");function Q2($){return{name:$.name,description:$.description,systemPrompt:$.systemPrompt,tools:$.tools?[...$.tools]:void 0,disallowedTools:$.disallowedTools?[...$.disallowedTools]:void 0,model:$.model,permissionMode:$.permissionMode,maxTurns:$.maxTurns,skills:$.skills?[...$.skills]:void 0,isolation:$.isolation,source:$.source}}function KO($){return{id:$.id,subagentType:$.subagentType,description:$.description,status:$.status,rootAgentId:$.rootAgentId,resumedFrom:$.resumedFrom,resumeDepth:$.resumeDepth,createdAt:$.createdAt,lastActiveAt:$.lastActiveAt,completedAt:$.completedAt,result:$.result,stats:$.stats}}var QU=new Set(["running","completed","failed","cancelled"]);function J6($){if(y$($.sessionId),!x$.isAbsolute($.projectPath))throw Error("Subagent owner projectPath must be absolute");return{sessionId:$.sessionId,projectPath:x$.resolve($.projectPath)}}function Y6($,Z){let J=J6(Z);return $.parentSessionId===J.sessionId&&$.parentProjectPath!==void 0&&x$.resolve($.parentProjectPath)===J.projectPath}class Q${static instance=null;sessionsDir;cache=new Map;constructor(){this.sessionsDir=B0(q0(),"agents","sessions"),this.ensureDirectory()}static getInstance(){if(!Q$.instance)Q$.instance=new Q$;return Q$.instance}ensureDirectory(){if(!w$.existsSync(this.sessionsDir))w$.mkdirSync(this.sessionsDir,{recursive:!0,mode:448});else w$.chmodSync(this.sessionsDir,448)}getSessionPath($){return y$($),B0(this.sessionsDir,`${$}.json`)}saveSession($){let Z=this.normalizeSession($,$.id),J=this.getSessionPath(Z.id),Y=`${JSON.stringify(Z,null,2)}
|
|
594
|
-
`;HU.sync(J,Y,{encoding:"utf8",mode:384,fsync:!0}),this.cache.set(Z.id,Z),w1.debug(`Session saved: ${Z.id}`)}loadSession($){if(this.cache.has($))return this.cache.get($);try{let Z=this.getSessionPath($);if(!w$.existsSync(Z))return;let J=w$.readFileSync(Z,"utf-8"),Y=this.normalizeSession(JSON.parse(J),$);return this.cache.set($,Y),Y}catch(Z){w1.warn(`Failed to load session ${$}:`,Z);return}}normalizeSession($,Z){if(!$||typeof $!=="object")throw Error(`Invalid agent session payload: ${Z}`);let J=$;if(J.id!==Z)throw Error(`Agent session ID mismatch: ${Z}`);if(y$(Z),typeof J.subagentType!=="string"||J.subagentType.length===0)throw Error(`Invalid subagent type: ${Z}`);if(typeof J.description!=="string"||typeof J.prompt!=="string")throw Error(`Invalid agent session description: ${Z}`);if(!Array.isArray(J.messages))throw Error(`Invalid agent session messages: ${Z}`);if(typeof J.status!=="string"||!QU.has(J.status))throw Error(`Invalid agent session status: ${Z}`);if(typeof J.createdAt!=="number"||!Number.isFinite(J.createdAt)||typeof J.lastActiveAt!=="number"||!Number.isFinite(J.lastActiveAt))throw Error(`Invalid agent session timestamps: ${Z}`);if(J.parentSessionId!==void 0)y$(J.parentSessionId);if(J.resumedFrom!==void 0)y$(J.resumedFrom);let Y=typeof J.rootAgentId==="string"?J.rootAgentId:Z;y$(Y);let U=typeof J.workspaceRoot==="string"&&x$.isAbsolute(J.workspaceRoot)?x$.resolve(J.workspaceRoot):void 0,X=typeof J.parentProjectPath==="string"&&x$.isAbsolute(J.parentProjectPath)?x$.resolve(J.parentProjectPath):J.parentSessionId&&U?U:void 0,H=typeof J.resumeDepth==="number"&&Number.isInteger(J.resumeDepth)&&J.resumeDepth>=0?J.resumeDepth:0,Q=typeof J.processId==="number"&&Number.isInteger(J.processId)&&J.processId>0?J.processId:void 0;return{...J,schemaVersion:2,id:Z,rootAgentId:Y,resumeDepth:H,processId:Q,workspaceRoot:U,parentProjectPath:X}}updateSession($,Z){let J=this.loadSession($);if(!J)return;let Y={...J,...Z,lastActiveAt:Date.now()};return this.saveSession(Y),Y}appendMessages($,Z){let J=this.loadSession($);if(!J)return;return this.updateSession($,{messages:[...J.messages,...Z]})}markCompleted($,Z,J){return this.updateSession($,{status:Z.success?"completed":"failed",result:Z,stats:J,completedAt:Date.now()})}deleteSession($){try{let Z=this.getSessionPath($);if(w$.existsSync(Z))w$.unlinkSync(Z);return this.cache.delete($),!0}catch(Z){return w1.warn(`Failed to delete session ${$}:`,Z),!1}}listSessions(){try{let $=w$.readdirSync(this.sessionsDir),Z=[];for(let J of $){if(!J.endsWith(".json"))continue;let Y=J.replace(".json",""),U=this.loadSession(Y);if(U)Z.push(U)}return Z.sort((J,Y)=>Y.lastActiveAt-J.lastActiveAt)}catch($){return w1.warn("Failed to list sessions:",$),[]}}listRunningSessions(){return this.listSessions().filter(($)=>$.status==="running")}cleanupExpiredSessions($=604800000){let Z=Date.now(),J=this.listSessions(),Y=0;for(let U of J){if(U.status==="running")continue;if(Z-U.lastActiveAt>$){if(this.deleteSession(U.id))Y++}}if(Y>0)w1.info(`Cleaned up ${Y} expired agent sessions`);return Y}clearCache(){this.cache.clear()}}import{randomUUID as bU}from"node:crypto";import*as y8 from"os";import*as x8 from"path";function W2($,Z){let J=Z instanceof Error?Z.message:String(Z);return{success:!1,llmContent:J,error:{type:"execution_error",message:J},metadata:{summary:$}}}function A1($){let Z=T({name:"ListMcpResources",displayName:"List MCP Resources",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({server:_.Optional(_.String({description:"Optional exact MCP server name"}))}),description:{short:"List contextual resources exposed by connected MCP servers",long:"Lists MCP resources from the current Session snapshot. Prefer these resources over web search when a connected server already provides the data."},async execute(W){let z=$.getContentCatalogSnapshot(),V=W.server?z.resources.filter((B)=>B.server===W.server):z.resources;return{success:!0,llmContent:V.length>0?JSON.stringify(V,null,2):"No MCP resources are available.",metadata:{summary:`Listed ${V.length} MCP resources`,resourceCount:V.length,revision:z.revision}}}}),J=T({name:"ListMcpResourceTemplates",displayName:"List MCP Resource Templates",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({server:_.Optional(_.String({description:"Optional exact MCP server name"}))}),description:{short:"List parameterized resource templates from MCP servers",long:"Lists URI templates exposed by MCP servers in the current Session. Templates describe parameterized contextual resources."},async execute(W){let z=$.getContentCatalogSnapshot(),V=W.server?z.resourceTemplates.filter((B)=>B.server===W.server):z.resourceTemplates;return{success:!0,llmContent:V.length>0?JSON.stringify(V,null,2):"No MCP resource templates are available.",metadata:{summary:`Listed ${V.length} MCP resource templates`,resourceTemplateCount:V.length,revision:z.revision}}}}),Y=T({name:"ReadMcpResource",displayName:"Read MCP Resource",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({server:_.String({description:"Exact server name returned by ListMcpResources"}),uri:_.String({description:"Exact resource URI returned by ListMcpResources"})}),description:{short:"Read a resource from a connected MCP server",long:"Reads every content part of one cataloged MCP resource. Text is bounded; binary content is represented by size and SHA-256 metadata without base64."},async execute(W){try{let z=await $.readResource(W.server,W.uri);return{success:!0,llmContent:JSON.stringify(z,null,2),metadata:{summary:`Read MCP resource ${W.uri}`,serverName:W.server,uri:W.uri,contentCount:z.contents.length}}}catch(z){return W2(`Failed to read MCP resource ${W.uri}`,z)}}}),U=T({name:"ListMcpPrompts",displayName:"List MCP Prompts",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({server:_.Optional(_.String({description:"Optional exact MCP server name"}))}),description:{short:"List reusable prompts exposed by connected MCP servers",long:"Lists MCP prompts and their typed argument metadata from the current Session catalog."},async execute(W){let z=$.getContentCatalogSnapshot(),V=W.server?z.prompts.filter((B)=>B.server===W.server):z.prompts;return{success:!0,llmContent:V.length>0?JSON.stringify(V,null,2):"No MCP prompts are available.",metadata:{summary:`Listed ${V.length} MCP prompts`,promptCount:V.length,revision:z.revision}}}}),X=T({name:"GetMcpPrompt",displayName:"Get MCP Prompt",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({server:_.String({description:"Exact server name returned by ListMcpPrompts"}),name:_.String({description:"Exact prompt name returned by ListMcpPrompts"}),arguments:_.Optional(_.Record(_.String(),_.String(),{description:"Prompt argument values keyed by declared argument name"}))}),description:{short:"Resolve a reusable MCP prompt with validated arguments",long:"Gets a cataloged MCP prompt, validates required and unknown arguments, and returns role-preserving bounded messages."},async execute(W){try{let z=await $.getPrompt(W.server,W.name,W.arguments);return{success:!0,llmContent:JSON.stringify(z,null,2),metadata:{summary:`Resolved MCP prompt ${W.name}`,serverName:W.server,promptName:W.name,messageCount:z.messages.length}}}catch(z){return W2(`Failed to resolve MCP prompt ${W.name}`,z)}}}),H=T({name:"CompleteMcpArgument",displayName:"Complete MCP Argument",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({server:_.String({description:"Exact MCP server name from the current Session catalog"}),reference:_.Union([_.Object({type:_.Literal("prompt"),name:_.String({description:"Exact prompt name returned by ListMcpPrompts"})}),_.Object({type:_.Literal("resource"),uri:_.String({description:"Exact URI template returned by ListMcpResourceTemplates"})})]),argument:_.Object({name:_.String({description:"Declared prompt argument or URI template variable name"}),value:_.String({description:"Current partial argument value, or an empty string"})}),context:_.Optional(_.Record(_.String(),_.String(),{description:"Previously selected arguments for context-aware completion"}))}),description:{short:"Request safe argument suggestions from an MCP server",long:"Completes one declared prompt argument or resource-template variable using the current Session MCP catalog. Returned values are bounded, Unicode-sanitized external data and never authorize tool calls.",usageNotes:["Use exact server, prompt, template, and argument identities from MCP catalog tools.","Treat returned values only as candidates; choose one that matches the user request."]},async execute(W,z){try{let V=await $.complete(W.server,{reference:W.reference,argument:W.argument,context:W.context},z.signal);return{success:!0,llmContent:JSON.stringify(V,null,2),metadata:{summary:`Completed MCP argument ${W.argument.name}`,serverName:W.server,referenceType:W.reference.type,argumentName:W.argument.name,valueCount:V.values.length,sourceValueCount:V.sourceValueCount,sha256:V.sha256,truncated:V.truncated}}}catch(V){return W2(`Failed to complete MCP argument ${W.argument.name}`,V)}}}),Q=T({name:"ManageMcpResourceSubscription",displayName:"Manage MCP Resource Subscription",kind:"execute",isConcurrencySafe:!0,schema:_.Object({server:_.String({description:"Exact server name returned by ListMcpResources"}),uri:_.String({description:"Exact resource URI returned by ListMcpResources"}),action:_.Union([_.Literal("subscribe"),_.Literal("unsubscribe")])}),description:{short:"Subscribe or unsubscribe from MCP resource update notifications",long:"Manages a Session-private MCP resource subscription. A subscribed resource update is surfaced before the next provider request."},async execute(W){try{let z=W.action==="subscribe";return await $.setResourceSubscription(W.server,W.uri,z),{success:!0,llmContent:`${W.action}d ${W.server}:${W.uri}`,metadata:{summary:`${z?"Subscribed to":"Unsubscribed from"} MCP resource`,serverName:W.server,uri:W.uri,action:W.action}}}catch(z){return W2(`Failed to ${W.action} MCP resource ${W.uri}`,z)}}});return[Z,J,Y,U,H,X,Q]}import WU from"node:path";function U6($){if(!$.sessionId)throw Error("MCP tasks require an active Session");return{sessionId:$.sessionId,projectPath:WU.resolve($.workspaceRoot||N())}}function zU($){return{...$.confirmationHandler?{confirmationHandler:$.confirmationHandler}:{},...$.mcpSamplingHandler?{samplingHandler:$.mcpSamplingHandler}:{},...$.onProgressUpdate?{progressHandler:$.onProgressUpdate}:{},...$.sessionId?{sessionId:$.sessionId}:{},...$.workspaceRoot?{workspaceRoot:$.workspaceRoot}:{},...$.permissionMode?{permissionMode:$.permissionMode}:{}}}function X6($,Z){let J=Z instanceof Error?Z.message:String(Z);return{success:!1,llmContent:J,error:{type:"execution_error",message:J},metadata:{summary:$}}}function H6($){let Z=T({name:"StartMcpTask",displayName:"Start MCP Task",kind:"execute",schema:_.Object({server:_.String({description:"Exact MCP server name from the current Session catalog"}),tool:_.String({description:"Exact task-capable tool name from that server"}),arguments:_.Optional(_.Record(_.String(),_.Unknown(),{description:"Arguments passed to the MCP tool"})),ttl_ms:_.Optional(_.Integer({minimum:Y8,maximum:U8,description:"Requested server retention time in milliseconds"}))}),description:{short:"Starts a task-capable MCP tool without blocking the agent turn",long:"Creates an opt-in MCP task and returns an opaque Blade task ID. Use TaskOutput to wait for the normalized result or CancelMcpTask to stop it.",important:["MCP Tasks must be explicitly enabled in the server configuration.","Returned task IDs are Session-owned and cannot be used across workspaces."]},async execute(U,X){try{let H=await $.startTask(U.server,U.tool,U.arguments??{},U6(X),zU(X),X.signal,U.ttl_ms);return{success:!0,llmContent:{task_id:H.taskId,type:"mcp",status:H.status,message:`MCP task started. Use TaskOutput(task_id: "${H.taskId}") to retrieve its result.`},metadata:{summary:`Started MCP task ${H.taskId}`,task_id:H.taskId,background:!0,taskType:"mcp",serverName:H.serverName,toolName:H.toolName,taskStatus:H.status}}}catch(H){return X6(`Failed to start MCP task ${U.tool}`,H)}}}),J=T({name:"ListMcpTasks",displayName:"List MCP Tasks",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({server:_.Optional(_.String({description:"Optional exact MCP server name"}))}),description:{short:"Lists task-augmented MCP calls owned by the current Session",long:"Returns only opaque Blade task IDs and safe lifecycle metadata. It never adopts or exposes arbitrary server-side tasks."},async execute(U,X){try{let H=$.listTasks(U6(X),U.server).map(({result:Q,...W})=>W);return{success:!0,llmContent:H.length>0?JSON.stringify(H,null,2):"No MCP tasks are owned by this Session.",metadata:{summary:`Listed ${H.length} MCP tasks`,taskCount:H.length}}}catch(H){return X6("Failed to list MCP tasks",H)}}}),Y=T({name:"CancelMcpTask",displayName:"Cancel MCP Task",kind:"execute",schema:_.Object({task_id:_.String({minLength:1,description:"Opaque mcp_task_* ID returned by StartMcpTask"})}),description:{short:"Cancels an MCP task owned by the current Session",long:"Requests server cancellation when supported, then always terminates the local watcher. Cross-Session task IDs fail closed."},async execute(U,X){try{let H=await $.cancelTask(U.task_id,U6(X),X.signal);if(!H)throw Error(`Unknown MCP task ID: ${U.task_id}`);return{success:!0,llmContent:{task_id:H.taskId,status:H.status,status_message:H.statusMessage},metadata:{summary:`Cancelled MCP task ${H.taskId}`,task_id:H.taskId,taskType:"mcp",taskStatus:H.status}}}catch(H){return X6(`Failed to cancel MCP task ${U.task_id}`,H)}}});return[Z,J,Y]}import{randomUUID as DU}from"node:crypto";import{EventEmitter as wU}from"node:events";var VU={readonly:Number.POSITIVE_INFINITY,write:Number.POSITIVE_INFINITY,execute:3};class W${static instance=null;buckets;constructor($={}){let Z={...VU,...$};this.buckets={readonly:{inFlight:0,maxConcurrent:Z.readonly,queue:[]},write:{inFlight:0,maxConcurrent:Z.write,queue:[]},execute:{inFlight:0,maxConcurrent:Z.execute,queue:[]}}}static getInstance(){if(!W$.instance)W$.instance=new W$;return W$.instance}static resetInstance(){W$.instance=null}schedule($,Z){let J=this.buckets[$];if(!J)return Z();if(J.inFlight<J.maxConcurrent)return this.runImmediately(J,Z);return new Promise((Y,U)=>{J.queue.push({fn:Z,resolve:Y,reject:U})})}async runImmediately($,Z){$.inFlight++;try{return await Z()}finally{$.inFlight--,this.drain($)}}drain($){while($.inFlight<$.maxConcurrent&&$.queue.length>0){let Z=$.queue.shift();$.inFlight++,Z.fn().then(Z.resolve,Z.reject).finally(()=>{$.inFlight--,this.drain($)})}}getStats(){return{readonly:{inFlight:this.buckets["readonly"].inFlight,queued:this.buckets["readonly"].queue.length},write:{inFlight:this.buckets["write"].inFlight,queued:this.buckets["write"].queue.length},execute:{inFlight:this.buckets["execute"].inFlight,queued:this.buckets["execute"].queue.length}}}}import L1 from"picomatch";class h${config;constructor($){this.config=$}check($){let Z=h$.buildSignature($),J=$.toolName==="Bash"&&typeof $.params.command==="string",Y=J?String($.params.command).trim():"",U=null;if(J){let z=U2(D1(Y));if(z!==Y)U=`Bash(${z})`}let X=null;if(J){let z=X8(D1(Y));if(z!==Y)X=`Bash(${z})`}let H=[Z];if(X)H.push(X);for(let z of H){let V=this.matchRules(z,this.config.deny);if(V)return{result:"deny",matchedRule:V.rule,matchType:V.type,reason:`工具调用被拒绝规则阻止: ${V.rule}`}}let Q=[Z];if(U)Q.push(U);for(let z of Q){let V=this.matchRules(z,this.config.allow);if(V)return{result:"allow",matchedRule:V.rule,matchType:V.type,reason:`工具调用符合允许规则: ${V.rule}`}}let W=[Z];if(X)W.push(X);for(let z of W){let V=this.matchRules(z,this.config.ask);if(V)return{result:"ask",matchedRule:V.rule,matchType:V.type,reason:`工具调用需要用户确认: ${V.rule}`}}return{result:"ask",reason:"工具调用未匹配任何规则,默认需要确认"}}static buildSignature($){let{toolName:Z,params:J,tool:Y}=$;try{if(Y?.extractSignatureContent){let U=Y.extractSignatureContent(J);return U?`${Z}(${U})`:Z}return Z}catch(U){return console.warn(`Failed to build signature for ${Z}:`,U instanceof Error?U.message:U),Z}}static abstractPattern($){let{toolName:Z,params:J,tool:Y}=$;try{if(Y?.abstractPermissionRule){let U=Y.abstractPermissionRule(J);if(U==="")return"";return U?`${Z}(${U})`:Z}return Z}catch(U){return console.warn(`Failed to abstract pattern for ${Z}:`,U instanceof Error?U.message:U),Z}}matchRules($,Z){for(let J of Z){let Y=this.matchRule($,J);if(Y)return{rule:J,type:Y}}return null}matchRule($,Z){if($===Z)return"exact";if(Z==="*"||Z==="**")return"wildcard";let J=this.extractToolName($),Y=this.extractToolName(Z);if(!J||!Y)return null;if(Y.includes("*")){if(!L1.isMatch(J,Y,{dot:!0,bash:!0}))return null}else if(J!==Y)return null;if(Z===Y)return"prefix";if(Z.includes("*")){let U=this.extractParams($),X=this.extractParams(Z);if(X==="*"||X==="**")return"wildcard";if(J==="Bash"&&X.endsWith(" *"))return U.startsWith(X.slice(0,-1))?"wildcard":null;if(this.matchParams(U,X))return X.includes("**")?"glob":"wildcard";if(L1.isMatch($,Z,{dot:!0,bash:!0}))return Z.includes("**")?"glob":"wildcard"}return null}extractParams($){let Z=$.match(/\(([\s\S]*)\)$/);return Z?Z[1]:""}matchParams($,Z){if(!$||!Z)return!1;let J=this.parseParamPairs($),Y=this.parseParamPairs(Z),U=Object.keys(Y).length>0,X=Object.keys(J).length>0;if(U!==X)return!1;if(!U&&!X){if(Z==="*"||Z==="**")return!0;if(Z.includes("*")||Z.includes("{")||Z.includes("?"))return L1.isMatch($,Z,{dot:!0,bash:!0});return $===Z}for(let[H,Q]of Object.entries(Y)){let W=J[H];if(W===void 0)return!1;if(Q.includes("*")||Q.includes("{")||Q.includes("?")){if(Q==="*"||Q==="**")continue;if(!L1.isMatch(W,Q,{dot:!0,bash:!0}))return!1}else if(W!==Q)return!1}return!0}parseParamPairs($){let Z={},J=this.smartSplit($,",");for(let Y of J){let U=this.findTopLevelDelimiter(Y,":");if(U>0){let X=Y.slice(0,U).trim(),H=Y.slice(U+1).trim();Z[X]=H}}return Z}smartSplit($,Z){let J=[],Y="",U=0,X=0,H=0,Q=!1,W="",z=!1;for(let V=0;V<$.length;V++){let B=$[V];if(z){Y+=B,z=!1;continue}if(B==="\\"){Y+=B,z=!0;continue}if(!Q&&B==="{")U++;else if(!Q&&B==="}")U--;else if(!Q&&B==="(")X++;else if(!Q&&B===")")X--;else if(!Q&&B==="[")H++;else if(!Q&&B==="]")H--;if((B==='"'||B==="'")&&!Q){Q=!0,W=B,Y+=B;continue}else if(Q&&B===W){Q=!1,W="",Y+=B;continue}if(B===Z&&U===0&&X===0&&H===0&&!Q)J.push(Y.trim()),Y="";else Y+=B}if(Y)J.push(Y.trim());return J}findTopLevelDelimiter($,Z){let J=0,Y=0,U=0,X=!1,H="",Q=!1;for(let W=0;W<$.length;W++){let z=$[W];if(Q){Q=!1;continue}if(z==="\\"){Q=!0;continue}if(!X&&z==="{")J++;else if(!X&&z==="}")J--;else if(!X&&z==="(")Y++;else if(!X&&z===")")Y--;else if(!X&&z==="[")U++;else if(!X&&z==="]")U--;if((z==='"'||z==="'")&&!X){X=!0,H=z;continue}else if(X&&z===H){X=!1,H="";continue}if(z===Z&&J===0&&Y===0&&U===0&&!X)return W}return-1}extractToolName($){let Z=$.match(/^([A-Za-z0-9_]+)(\(|$)/);return Z?Z[1]:null}isAllowed($){return this.check($).result==="allow"}isDenied($){return this.check($).result==="deny"}needsConfirmation($){return this.check($).result==="ask"}updateConfig($){if($.allow)this.config.allow=[...this.config.allow,...$.allow];if($.ask)this.config.ask=[...this.config.ask,...$.ask];if($.deny)this.config.deny=[...this.config.deny,...$.deny]}replaceConfig($){this.config={...$}}getConfig(){return{...this.config}}}import BU from"node:os";import Q6 from"node:path";class W6{static SENSITIVE_PATTERNS=[{pattern:/^\.?id_rsa$/i,level:"high",description:"SSH 私钥"},{pattern:/^\.?id_ed25519$/i,level:"high",description:"SSH Ed25519 私钥"},{pattern:/^\.?id_ecdsa$/i,level:"high",description:"SSH ECDSA 私钥"},{pattern:/\.pem$/i,level:"high",description:"PEM 格式私钥"},{pattern:/\.key$/i,level:"high",description:"密钥文件"},{pattern:/\.p12$/i,level:"high",description:"PKCS#12 证书"},{pattern:/\.pfx$/i,level:"high",description:"PFX 证书"},{pattern:/^\.?keystore$/i,level:"high",description:"Java Keystore"},{pattern:/^\.?pgpass$/i,level:"high",description:"PostgreSQL 密码文件"},{pattern:/^\.?my\.cnf$/i,level:"high",description:"MySQL 配置文件(可能含密码)"},{pattern:/credentials\.json$/i,level:"high",description:"Google Cloud 凭证"},{pattern:/^\.?aws[\\/]credentials$/i,level:"high",description:"AWS 凭证"},{pattern:/^\.?gcp[\\/]credentials$/i,level:"high",description:"GCP 凭证"},{pattern:/^\.?azure[\\/]credentials$/i,level:"high",description:"Azure 凭证"},{pattern:/^service-account.*\.json$/i,level:"high",description:"服务账号密钥"},{pattern:/^\.env$/i,level:"medium",description:"环境变量文件"},{pattern:/^\.env\./i,level:"medium",description:"环境变量文件(带环境后缀)"},{pattern:/^\.?npmrc$/i,level:"medium",description:"npm 配置文件(可能含 token)"},{pattern:/^\.?pypirc$/i,level:"medium",description:"PyPI 配置文件(可能含密码)"},{pattern:/^\.?dockercfg$/i,level:"medium",description:"Docker 配置文件"},{pattern:/^\.?docker[\\/]config\.json$/i,level:"medium",description:"Docker 配置文件"},{pattern:/^\.?netrc$/i,level:"medium",description:"FTP/HTTP 认证文件"},{pattern:/^\.?git-credentials$/i,level:"medium",description:"Git 凭证文件"},{pattern:/^config\.toml$/i,level:"medium",description:"配置文件(可能含敏感信息)"},{pattern:/^secrets\./i,level:"medium",description:"密钥配置文件"},{pattern:/\.sqlite$/i,level:"low",description:"SQLite 数据库"},{pattern:/\.db$/i,level:"low",description:"数据库文件"},{pattern:/\.sql$/i,level:"low",description:"SQL 文件(可能含敏感数据)"}];static SENSITIVE_PATHS=[{path:/\.ssh[\\/]/i,level:"high",description:"SSH 配置目录"},{path:/\.aws[\\/]/i,level:"high",description:"AWS 配置目录"},{path:/\.config[\\/]gcloud[\\/]/i,level:"high",description:"Google Cloud 配置目录"},{path:/\.kube[\\/]/i,level:"high",description:"Kubernetes 配置目录"}];static check($){let Z=this.normalizePath($),J=Q6.basename(Z);for(let Y of this.SENSITIVE_PATTERNS)if(this.matchPattern(J,Y.pattern))return{isSensitive:!0,level:Y.level,matchedPattern:Y.pattern instanceof RegExp?Y.pattern.source:Y.pattern,reason:Y.description};for(let Y of this.SENSITIVE_PATHS)if(this.matchPattern(Z,Y.path))return{isSensitive:!0,level:Y.level,matchedPattern:Y.path instanceof RegExp?Y.path.source:Y.path,reason:Y.description};return{isSensitive:!1}}static checkMultiple($){let Z=new Map;for(let J of $)Z.set(J,this.check(J));return Z}static filterSensitive($,Z="low"){let J={["high"]:3,["medium"]:2,["low"]:1},Y=J[Z];return $.map((U)=>({path:U,result:this.check(U)})).filter(({result:U})=>U.isSensitive&&U.level&&J[U.level]>=Y)}static normalizePath($){if($.startsWith("~/")||$==="~")return Q6.join(BU.homedir(),$.slice(1));return Q6.resolve($)}static matchPattern($,Z){if(Z instanceof RegExp)return Z.test($);let J=Z.replace(/\*/g,".*");return new RegExp(`^${J}$`,"i").test($)}static getSensitivePatterns(){return[...this.SENSITIVE_PATTERNS]}static getSensitivePaths(){return[...this.SENSITIVE_PATHS]}}class V6{sessionApprovals;defaultPermissionMode;permissionChecker;constructor($,Z,J){this.sessionApprovals=Z;this.defaultPermissionMode=J;this.permissionChecker=new h$($)}getPermissionChecker(){return this.permissionChecker}resolveRulePermission($,Z,J,Y){let U=Z.getAffectedPaths(),X={toolName:$.name,params:J,affectedPaths:U,tool:$},H=h$.buildSignature(X),Q=this.permissionChecker.check(X);if(Y.subagentType==="verification"){let W=$.name==="Bash"&&typeof J.command==="string"&&J.run_in_background!==!0&&J.env===void 0&&z8(J.cwd,Y.workspaceRoot)&&(z6(Q8(J.command))||W8(J.command));if(!z2($.kind)&&!W)return{signature:H,decision:{behavior:"deny",source:"rule",matchedRule:"builtin:verification-agent-read-only",reason:"Verification agents may only use read-only tools and verification commands"}};if(W){if(Q.result==="deny")return{signature:H,decision:H8(Q)};return{signature:H,decision:{behavior:"allow",source:"rule",matchedRule:"builtin:verification-agent-command",reason:"Verification command allowed for the read-only verifier"}}}}if(Q.result==="ask"&&!Q.matchedRule&&$.name==="Bash"&&typeof J.command==="string"&&z6(J.command))Q={result:"allow",matchedRule:"builtin:read-only-command",reason:"Command classified as read-only, auto-approved"};if(Q=this.applyModeOverrides($.kind,Q,Y.permissionMode??this.defaultPermissionMode),Q.result==="ask"&&this.sessionApprovals.has(H))Q={result:"allow",matchedRule:"remembered:session",reason:"User already allowed this operation in this session"};return Q=this.applySafetyOverrides(U,Q),{decision:H8(Q),signature:H}}applyModeOverrides($,Z,J){if(J==="yolo")return{result:"allow",matchedRule:"mode:yolo",reason:"YOLO mode: automatically approve all tool invocations"};if(J==="plan"&&!z2($))return{result:"deny",matchedRule:"mode:plan",reason:"Plan mode: modification tools are blocked; only read-only tools are allowed"};if(Z.result!=="ask")return Z;if(z2($))return{result:"allow",matchedRule:`mode:${J}:readonly`,reason:"Read-only tools do not require confirmation"};if(J==="autoEdit"&&$==="write")return{result:"allow",matchedRule:"mode:autoEdit:write",reason:"AUTO_EDIT mode: automatically approve write tools"};return Z}applySafetyOverrides($,Z){if(!$?.length)return Z;let J=["/etc/","/sys/","/proc/","/dev/","/boot/","/root/","C:\\Windows\\System32","C:\\Program Files","C:\\ProgramData"],Y=$.filter((Q)=>Q.includes("..")||J.some((W)=>Q.includes(W)));if(Y.length>0)return{result:"deny",matchedRule:"safety:dangerous-system-path",reason:`Access to dangerous system paths denied: ${Y.join(", ")}`};let U=W6.filterSensitive($,"medium");if(U.length===0)return Z;let X=U.map(({path:Q,result:W})=>`${Q} (${W.level}: ${W.reason})`);if(U.some(({result:Q})=>Q.level==="high")&&Z.result!=="allow")return{result:"deny",matchedRule:"safety:high-sensitive-file",reason:`Access to highly sensitive files denied:
|
|
594
|
+
`;HU.sync(J,Y,{encoding:"utf8",mode:384,fsync:!0}),this.cache.set(Z.id,Z),w1.debug(`Session saved: ${Z.id}`)}loadSession($){if(this.cache.has($))return this.cache.get($);try{let Z=this.getSessionPath($);if(!w$.existsSync(Z))return;let J=w$.readFileSync(Z,"utf-8"),Y=this.normalizeSession(JSON.parse(J),$);return this.cache.set($,Y),Y}catch(Z){w1.warn(`Failed to load session ${$}:`,Z);return}}normalizeSession($,Z){if(!$||typeof $!=="object")throw Error(`Invalid agent session payload: ${Z}`);let J=$;if(J.id!==Z)throw Error(`Agent session ID mismatch: ${Z}`);if(y$(Z),typeof J.subagentType!=="string"||J.subagentType.length===0)throw Error(`Invalid subagent type: ${Z}`);if(typeof J.description!=="string"||typeof J.prompt!=="string")throw Error(`Invalid agent session description: ${Z}`);if(!Array.isArray(J.messages))throw Error(`Invalid agent session messages: ${Z}`);if(typeof J.status!=="string"||!QU.has(J.status))throw Error(`Invalid agent session status: ${Z}`);if(typeof J.createdAt!=="number"||!Number.isFinite(J.createdAt)||typeof J.lastActiveAt!=="number"||!Number.isFinite(J.lastActiveAt))throw Error(`Invalid agent session timestamps: ${Z}`);if(J.parentSessionId!==void 0)y$(J.parentSessionId);if(J.resumedFrom!==void 0)y$(J.resumedFrom);let Y=typeof J.rootAgentId==="string"?J.rootAgentId:Z;y$(Y);let U=typeof J.workspaceRoot==="string"&&x$.isAbsolute(J.workspaceRoot)?x$.resolve(J.workspaceRoot):void 0,X=typeof J.parentProjectPath==="string"&&x$.isAbsolute(J.parentProjectPath)?x$.resolve(J.parentProjectPath):J.parentSessionId&&U?U:void 0,H=typeof J.resumeDepth==="number"&&Number.isInteger(J.resumeDepth)&&J.resumeDepth>=0?J.resumeDepth:0,Q=typeof J.processId==="number"&&Number.isInteger(J.processId)&&J.processId>0?J.processId:void 0;return{...J,schemaVersion:2,id:Z,rootAgentId:Y,resumeDepth:H,processId:Q,workspaceRoot:U,parentProjectPath:X}}updateSession($,Z){let J=this.loadSession($);if(!J)return;let Y={...J,...Z,lastActiveAt:Date.now()};return this.saveSession(Y),Y}appendMessages($,Z){let J=this.loadSession($);if(!J)return;return this.updateSession($,{messages:[...J.messages,...Z]})}markCompleted($,Z,J){return this.updateSession($,{status:Z.success?"completed":"failed",result:Z,stats:J,completedAt:Date.now()})}deleteSession($){try{let Z=this.getSessionPath($);if(w$.existsSync(Z))w$.unlinkSync(Z);return this.cache.delete($),!0}catch(Z){return w1.warn(`Failed to delete session ${$}:`,Z),!1}}listSessions(){try{let $=w$.readdirSync(this.sessionsDir),Z=[];for(let J of $){if(!J.endsWith(".json"))continue;let Y=J.replace(".json",""),U=this.loadSession(Y);if(U)Z.push(U)}return Z.sort((J,Y)=>Y.lastActiveAt-J.lastActiveAt)}catch($){return w1.warn("Failed to list sessions:",$),[]}}listRunningSessions(){return this.listSessions().filter(($)=>$.status==="running")}cleanupExpiredSessions($=604800000){let Z=Date.now(),J=this.listSessions(),Y=0;for(let U of J){if(U.status==="running")continue;if(Z-U.lastActiveAt>$){if(this.deleteSession(U.id))Y++}}if(Y>0)w1.info(`Cleaned up ${Y} expired agent sessions`);return Y}clearCache(){this.cache.clear()}}import{randomUUID as bU}from"node:crypto";import*as y8 from"os";import*as x8 from"path";function W2($,Z){let J=Z instanceof Error?Z.message:String(Z);return{success:!1,llmContent:J,error:{type:"execution_error",message:J},metadata:{summary:$}}}function A1($){let Z=j({name:"ListMcpResources",displayName:"List MCP Resources",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({server:_.Optional(_.String({description:"Optional exact MCP server name"}))}),description:{short:"List contextual resources exposed by connected MCP servers",long:"Lists MCP resources from the current Session snapshot. Prefer these resources over web search when a connected server already provides the data."},async execute(W){let z=$.getContentCatalogSnapshot(),V=W.server?z.resources.filter((B)=>B.server===W.server):z.resources;return{success:!0,llmContent:V.length>0?JSON.stringify(V,null,2):"No MCP resources are available.",metadata:{summary:`Listed ${V.length} MCP resources`,resourceCount:V.length,revision:z.revision}}}}),J=j({name:"ListMcpResourceTemplates",displayName:"List MCP Resource Templates",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({server:_.Optional(_.String({description:"Optional exact MCP server name"}))}),description:{short:"List parameterized resource templates from MCP servers",long:"Lists URI templates exposed by MCP servers in the current Session. Templates describe parameterized contextual resources."},async execute(W){let z=$.getContentCatalogSnapshot(),V=W.server?z.resourceTemplates.filter((B)=>B.server===W.server):z.resourceTemplates;return{success:!0,llmContent:V.length>0?JSON.stringify(V,null,2):"No MCP resource templates are available.",metadata:{summary:`Listed ${V.length} MCP resource templates`,resourceTemplateCount:V.length,revision:z.revision}}}}),Y=j({name:"ReadMcpResource",displayName:"Read MCP Resource",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({server:_.String({description:"Exact server name returned by ListMcpResources"}),uri:_.String({description:"Exact resource URI returned by ListMcpResources"})}),description:{short:"Read a resource from a connected MCP server",long:"Reads every content part of one cataloged MCP resource. Text is bounded; binary content is represented by size and SHA-256 metadata without base64."},async execute(W){try{let z=await $.readResource(W.server,W.uri);return{success:!0,llmContent:JSON.stringify(z,null,2),metadata:{summary:`Read MCP resource ${W.uri}`,serverName:W.server,uri:W.uri,contentCount:z.contents.length}}}catch(z){return W2(`Failed to read MCP resource ${W.uri}`,z)}}}),U=j({name:"ListMcpPrompts",displayName:"List MCP Prompts",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({server:_.Optional(_.String({description:"Optional exact MCP server name"}))}),description:{short:"List reusable prompts exposed by connected MCP servers",long:"Lists MCP prompts and their typed argument metadata from the current Session catalog."},async execute(W){let z=$.getContentCatalogSnapshot(),V=W.server?z.prompts.filter((B)=>B.server===W.server):z.prompts;return{success:!0,llmContent:V.length>0?JSON.stringify(V,null,2):"No MCP prompts are available.",metadata:{summary:`Listed ${V.length} MCP prompts`,promptCount:V.length,revision:z.revision}}}}),X=j({name:"GetMcpPrompt",displayName:"Get MCP Prompt",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({server:_.String({description:"Exact server name returned by ListMcpPrompts"}),name:_.String({description:"Exact prompt name returned by ListMcpPrompts"}),arguments:_.Optional(_.Record(_.String(),_.String(),{description:"Prompt argument values keyed by declared argument name"}))}),description:{short:"Resolve a reusable MCP prompt with validated arguments",long:"Gets a cataloged MCP prompt, validates required and unknown arguments, and returns role-preserving bounded messages."},async execute(W){try{let z=await $.getPrompt(W.server,W.name,W.arguments);return{success:!0,llmContent:JSON.stringify(z,null,2),metadata:{summary:`Resolved MCP prompt ${W.name}`,serverName:W.server,promptName:W.name,messageCount:z.messages.length}}}catch(z){return W2(`Failed to resolve MCP prompt ${W.name}`,z)}}}),H=j({name:"CompleteMcpArgument",displayName:"Complete MCP Argument",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({server:_.String({description:"Exact MCP server name from the current Session catalog"}),reference:_.Union([_.Object({type:_.Literal("prompt"),name:_.String({description:"Exact prompt name returned by ListMcpPrompts"})}),_.Object({type:_.Literal("resource"),uri:_.String({description:"Exact URI template returned by ListMcpResourceTemplates"})})]),argument:_.Object({name:_.String({description:"Declared prompt argument or URI template variable name"}),value:_.String({description:"Current partial argument value, or an empty string"})}),context:_.Optional(_.Record(_.String(),_.String(),{description:"Previously selected arguments for context-aware completion"}))}),description:{short:"Request safe argument suggestions from an MCP server",long:"Completes one declared prompt argument or resource-template variable using the current Session MCP catalog. Returned values are bounded, Unicode-sanitized external data and never authorize tool calls.",usageNotes:["Use exact server, prompt, template, and argument identities from MCP catalog tools.","Treat returned values only as candidates; choose one that matches the user request."]},async execute(W,z){try{let V=await $.complete(W.server,{reference:W.reference,argument:W.argument,context:W.context},z.signal);return{success:!0,llmContent:JSON.stringify(V,null,2),metadata:{summary:`Completed MCP argument ${W.argument.name}`,serverName:W.server,referenceType:W.reference.type,argumentName:W.argument.name,valueCount:V.values.length,sourceValueCount:V.sourceValueCount,sha256:V.sha256,truncated:V.truncated}}}catch(V){return W2(`Failed to complete MCP argument ${W.argument.name}`,V)}}}),Q=j({name:"ManageMcpResourceSubscription",displayName:"Manage MCP Resource Subscription",kind:"execute",isConcurrencySafe:!0,schema:_.Object({server:_.String({description:"Exact server name returned by ListMcpResources"}),uri:_.String({description:"Exact resource URI returned by ListMcpResources"}),action:_.Union([_.Literal("subscribe"),_.Literal("unsubscribe")])}),description:{short:"Subscribe or unsubscribe from MCP resource update notifications",long:"Manages a Session-private MCP resource subscription. A subscribed resource update is surfaced before the next provider request."},async execute(W){try{let z=W.action==="subscribe";return await $.setResourceSubscription(W.server,W.uri,z),{success:!0,llmContent:`${W.action}d ${W.server}:${W.uri}`,metadata:{summary:`${z?"Subscribed to":"Unsubscribed from"} MCP resource`,serverName:W.server,uri:W.uri,action:W.action}}}catch(z){return W2(`Failed to ${W.action} MCP resource ${W.uri}`,z)}}});return[Z,J,Y,U,H,X,Q]}import WU from"node:path";function U6($){if(!$.sessionId)throw Error("MCP tasks require an active Session");return{sessionId:$.sessionId,projectPath:WU.resolve($.workspaceRoot||N())}}function zU($){return{...$.confirmationHandler?{confirmationHandler:$.confirmationHandler}:{},...$.mcpSamplingHandler?{samplingHandler:$.mcpSamplingHandler}:{},...$.onProgressUpdate?{progressHandler:$.onProgressUpdate}:{},...$.sessionId?{sessionId:$.sessionId}:{},...$.workspaceRoot?{workspaceRoot:$.workspaceRoot}:{},...$.permissionMode?{permissionMode:$.permissionMode}:{}}}function X6($,Z){let J=Z instanceof Error?Z.message:String(Z);return{success:!1,llmContent:J,error:{type:"execution_error",message:J},metadata:{summary:$}}}function H6($){let Z=j({name:"StartMcpTask",displayName:"Start MCP Task",kind:"execute",schema:_.Object({server:_.String({description:"Exact MCP server name from the current Session catalog"}),tool:_.String({description:"Exact task-capable tool name from that server"}),arguments:_.Optional(_.Record(_.String(),_.Unknown(),{description:"Arguments passed to the MCP tool"})),ttl_ms:_.Optional(_.Integer({minimum:Y8,maximum:U8,description:"Requested server retention time in milliseconds"}))}),description:{short:"Starts a task-capable MCP tool without blocking the agent turn",long:"Creates an opt-in MCP task and returns an opaque Blade task ID. Use TaskOutput to wait for the normalized result or CancelMcpTask to stop it.",important:["MCP Tasks must be explicitly enabled in the server configuration.","Returned task IDs are Session-owned and cannot be used across workspaces."]},async execute(U,X){try{let H=await $.startTask(U.server,U.tool,U.arguments??{},U6(X),zU(X),X.signal,U.ttl_ms);return{success:!0,llmContent:{task_id:H.taskId,type:"mcp",status:H.status,message:`MCP task started. Use TaskOutput(task_id: "${H.taskId}") to retrieve its result.`},metadata:{summary:`Started MCP task ${H.taskId}`,task_id:H.taskId,background:!0,taskType:"mcp",serverName:H.serverName,toolName:H.toolName,taskStatus:H.status}}}catch(H){return X6(`Failed to start MCP task ${U.tool}`,H)}}}),J=j({name:"ListMcpTasks",displayName:"List MCP Tasks",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({server:_.Optional(_.String({description:"Optional exact MCP server name"}))}),description:{short:"Lists task-augmented MCP calls owned by the current Session",long:"Returns only opaque Blade task IDs and safe lifecycle metadata. It never adopts or exposes arbitrary server-side tasks."},async execute(U,X){try{let H=$.listTasks(U6(X),U.server).map(({result:Q,...W})=>W);return{success:!0,llmContent:H.length>0?JSON.stringify(H,null,2):"No MCP tasks are owned by this Session.",metadata:{summary:`Listed ${H.length} MCP tasks`,taskCount:H.length}}}catch(H){return X6("Failed to list MCP tasks",H)}}}),Y=j({name:"CancelMcpTask",displayName:"Cancel MCP Task",kind:"execute",schema:_.Object({task_id:_.String({minLength:1,description:"Opaque mcp_task_* ID returned by StartMcpTask"})}),description:{short:"Cancels an MCP task owned by the current Session",long:"Requests server cancellation when supported, then always terminates the local watcher. Cross-Session task IDs fail closed."},async execute(U,X){try{let H=await $.cancelTask(U.task_id,U6(X),X.signal);if(!H)throw Error(`Unknown MCP task ID: ${U.task_id}`);return{success:!0,llmContent:{task_id:H.taskId,status:H.status,status_message:H.statusMessage},metadata:{summary:`Cancelled MCP task ${H.taskId}`,task_id:H.taskId,taskType:"mcp",taskStatus:H.status}}}catch(H){return X6(`Failed to cancel MCP task ${U.task_id}`,H)}}});return[Z,J,Y]}import{randomUUID as DU}from"node:crypto";import{EventEmitter as wU}from"node:events";var VU={readonly:Number.POSITIVE_INFINITY,write:Number.POSITIVE_INFINITY,execute:3};class W${static instance=null;buckets;constructor($={}){let Z={...VU,...$};this.buckets={readonly:{inFlight:0,maxConcurrent:Z.readonly,queue:[]},write:{inFlight:0,maxConcurrent:Z.write,queue:[]},execute:{inFlight:0,maxConcurrent:Z.execute,queue:[]}}}static getInstance(){if(!W$.instance)W$.instance=new W$;return W$.instance}static resetInstance(){W$.instance=null}schedule($,Z){let J=this.buckets[$];if(!J)return Z();if(J.inFlight<J.maxConcurrent)return this.runImmediately(J,Z);return new Promise((Y,U)=>{J.queue.push({fn:Z,resolve:Y,reject:U})})}async runImmediately($,Z){$.inFlight++;try{return await Z()}finally{$.inFlight--,this.drain($)}}drain($){while($.inFlight<$.maxConcurrent&&$.queue.length>0){let Z=$.queue.shift();$.inFlight++,Z.fn().then(Z.resolve,Z.reject).finally(()=>{$.inFlight--,this.drain($)})}}getStats(){return{readonly:{inFlight:this.buckets["readonly"].inFlight,queued:this.buckets["readonly"].queue.length},write:{inFlight:this.buckets["write"].inFlight,queued:this.buckets["write"].queue.length},execute:{inFlight:this.buckets["execute"].inFlight,queued:this.buckets["execute"].queue.length}}}}import L1 from"picomatch";class h${config;constructor($){this.config=$}check($){let Z=h$.buildSignature($),J=$.toolName==="Bash"&&typeof $.params.command==="string",Y=J?String($.params.command).trim():"",U=null;if(J){let z=U2(D1(Y));if(z!==Y)U=`Bash(${z})`}let X=null;if(J){let z=X8(D1(Y));if(z!==Y)X=`Bash(${z})`}let H=[Z];if(X)H.push(X);for(let z of H){let V=this.matchRules(z,this.config.deny);if(V)return{result:"deny",matchedRule:V.rule,matchType:V.type,reason:`工具调用被拒绝规则阻止: ${V.rule}`}}let Q=[Z];if(U)Q.push(U);for(let z of Q){let V=this.matchRules(z,this.config.allow);if(V)return{result:"allow",matchedRule:V.rule,matchType:V.type,reason:`工具调用符合允许规则: ${V.rule}`}}let W=[Z];if(X)W.push(X);for(let z of W){let V=this.matchRules(z,this.config.ask);if(V)return{result:"ask",matchedRule:V.rule,matchType:V.type,reason:`工具调用需要用户确认: ${V.rule}`}}return{result:"ask",reason:"工具调用未匹配任何规则,默认需要确认"}}static buildSignature($){let{toolName:Z,params:J,tool:Y}=$;try{if(Y?.extractSignatureContent){let U=Y.extractSignatureContent(J);return U?`${Z}(${U})`:Z}return Z}catch(U){return console.warn(`Failed to build signature for ${Z}:`,U instanceof Error?U.message:U),Z}}static abstractPattern($){let{toolName:Z,params:J,tool:Y}=$;try{if(Y?.abstractPermissionRule){let U=Y.abstractPermissionRule(J);if(U==="")return"";return U?`${Z}(${U})`:Z}return Z}catch(U){return console.warn(`Failed to abstract pattern for ${Z}:`,U instanceof Error?U.message:U),Z}}matchRules($,Z){for(let J of Z){let Y=this.matchRule($,J);if(Y)return{rule:J,type:Y}}return null}matchRule($,Z){if($===Z)return"exact";if(Z==="*"||Z==="**")return"wildcard";let J=this.extractToolName($),Y=this.extractToolName(Z);if(!J||!Y)return null;if(Y.includes("*")){if(!L1.isMatch(J,Y,{dot:!0,bash:!0}))return null}else if(J!==Y)return null;if(Z===Y)return"prefix";if(Z.includes("*")){let U=this.extractParams($),X=this.extractParams(Z);if(X==="*"||X==="**")return"wildcard";if(J==="Bash"&&X.endsWith(" *"))return U.startsWith(X.slice(0,-1))?"wildcard":null;if(this.matchParams(U,X))return X.includes("**")?"glob":"wildcard";if(L1.isMatch($,Z,{dot:!0,bash:!0}))return Z.includes("**")?"glob":"wildcard"}return null}extractParams($){let Z=$.match(/\(([\s\S]*)\)$/);return Z?Z[1]:""}matchParams($,Z){if(!$||!Z)return!1;let J=this.parseParamPairs($),Y=this.parseParamPairs(Z),U=Object.keys(Y).length>0,X=Object.keys(J).length>0;if(U!==X)return!1;if(!U&&!X){if(Z==="*"||Z==="**")return!0;if(Z.includes("*")||Z.includes("{")||Z.includes("?"))return L1.isMatch($,Z,{dot:!0,bash:!0});return $===Z}for(let[H,Q]of Object.entries(Y)){let W=J[H];if(W===void 0)return!1;if(Q.includes("*")||Q.includes("{")||Q.includes("?")){if(Q==="*"||Q==="**")continue;if(!L1.isMatch(W,Q,{dot:!0,bash:!0}))return!1}else if(W!==Q)return!1}return!0}parseParamPairs($){let Z={},J=this.smartSplit($,",");for(let Y of J){let U=this.findTopLevelDelimiter(Y,":");if(U>0){let X=Y.slice(0,U).trim(),H=Y.slice(U+1).trim();Z[X]=H}}return Z}smartSplit($,Z){let J=[],Y="",U=0,X=0,H=0,Q=!1,W="",z=!1;for(let V=0;V<$.length;V++){let B=$[V];if(z){Y+=B,z=!1;continue}if(B==="\\"){Y+=B,z=!0;continue}if(!Q&&B==="{")U++;else if(!Q&&B==="}")U--;else if(!Q&&B==="(")X++;else if(!Q&&B===")")X--;else if(!Q&&B==="[")H++;else if(!Q&&B==="]")H--;if((B==='"'||B==="'")&&!Q){Q=!0,W=B,Y+=B;continue}else if(Q&&B===W){Q=!1,W="",Y+=B;continue}if(B===Z&&U===0&&X===0&&H===0&&!Q)J.push(Y.trim()),Y="";else Y+=B}if(Y)J.push(Y.trim());return J}findTopLevelDelimiter($,Z){let J=0,Y=0,U=0,X=!1,H="",Q=!1;for(let W=0;W<$.length;W++){let z=$[W];if(Q){Q=!1;continue}if(z==="\\"){Q=!0;continue}if(!X&&z==="{")J++;else if(!X&&z==="}")J--;else if(!X&&z==="(")Y++;else if(!X&&z===")")Y--;else if(!X&&z==="[")U++;else if(!X&&z==="]")U--;if((z==='"'||z==="'")&&!X){X=!0,H=z;continue}else if(X&&z===H){X=!1,H="";continue}if(z===Z&&J===0&&Y===0&&U===0&&!X)return W}return-1}extractToolName($){let Z=$.match(/^([A-Za-z0-9_]+)(\(|$)/);return Z?Z[1]:null}isAllowed($){return this.check($).result==="allow"}isDenied($){return this.check($).result==="deny"}needsConfirmation($){return this.check($).result==="ask"}updateConfig($){if($.allow)this.config.allow=[...this.config.allow,...$.allow];if($.ask)this.config.ask=[...this.config.ask,...$.ask];if($.deny)this.config.deny=[...this.config.deny,...$.deny]}replaceConfig($){this.config={...$}}getConfig(){return{...this.config}}}import BU from"node:os";import Q6 from"node:path";class W6{static SENSITIVE_PATTERNS=[{pattern:/^\.?id_rsa$/i,level:"high",description:"SSH 私钥"},{pattern:/^\.?id_ed25519$/i,level:"high",description:"SSH Ed25519 私钥"},{pattern:/^\.?id_ecdsa$/i,level:"high",description:"SSH ECDSA 私钥"},{pattern:/\.pem$/i,level:"high",description:"PEM 格式私钥"},{pattern:/\.key$/i,level:"high",description:"密钥文件"},{pattern:/\.p12$/i,level:"high",description:"PKCS#12 证书"},{pattern:/\.pfx$/i,level:"high",description:"PFX 证书"},{pattern:/^\.?keystore$/i,level:"high",description:"Java Keystore"},{pattern:/^\.?pgpass$/i,level:"high",description:"PostgreSQL 密码文件"},{pattern:/^\.?my\.cnf$/i,level:"high",description:"MySQL 配置文件(可能含密码)"},{pattern:/credentials\.json$/i,level:"high",description:"Google Cloud 凭证"},{pattern:/^\.?aws[\\/]credentials$/i,level:"high",description:"AWS 凭证"},{pattern:/^\.?gcp[\\/]credentials$/i,level:"high",description:"GCP 凭证"},{pattern:/^\.?azure[\\/]credentials$/i,level:"high",description:"Azure 凭证"},{pattern:/^service-account.*\.json$/i,level:"high",description:"服务账号密钥"},{pattern:/^\.env$/i,level:"medium",description:"环境变量文件"},{pattern:/^\.env\./i,level:"medium",description:"环境变量文件(带环境后缀)"},{pattern:/^\.?npmrc$/i,level:"medium",description:"npm 配置文件(可能含 token)"},{pattern:/^\.?pypirc$/i,level:"medium",description:"PyPI 配置文件(可能含密码)"},{pattern:/^\.?dockercfg$/i,level:"medium",description:"Docker 配置文件"},{pattern:/^\.?docker[\\/]config\.json$/i,level:"medium",description:"Docker 配置文件"},{pattern:/^\.?netrc$/i,level:"medium",description:"FTP/HTTP 认证文件"},{pattern:/^\.?git-credentials$/i,level:"medium",description:"Git 凭证文件"},{pattern:/^config\.toml$/i,level:"medium",description:"配置文件(可能含敏感信息)"},{pattern:/^secrets\./i,level:"medium",description:"密钥配置文件"},{pattern:/\.sqlite$/i,level:"low",description:"SQLite 数据库"},{pattern:/\.db$/i,level:"low",description:"数据库文件"},{pattern:/\.sql$/i,level:"low",description:"SQL 文件(可能含敏感数据)"}];static SENSITIVE_PATHS=[{path:/\.ssh[\\/]/i,level:"high",description:"SSH 配置目录"},{path:/\.aws[\\/]/i,level:"high",description:"AWS 配置目录"},{path:/\.config[\\/]gcloud[\\/]/i,level:"high",description:"Google Cloud 配置目录"},{path:/\.kube[\\/]/i,level:"high",description:"Kubernetes 配置目录"}];static check($){let Z=this.normalizePath($),J=Q6.basename(Z);for(let Y of this.SENSITIVE_PATTERNS)if(this.matchPattern(J,Y.pattern))return{isSensitive:!0,level:Y.level,matchedPattern:Y.pattern instanceof RegExp?Y.pattern.source:Y.pattern,reason:Y.description};for(let Y of this.SENSITIVE_PATHS)if(this.matchPattern(Z,Y.path))return{isSensitive:!0,level:Y.level,matchedPattern:Y.path instanceof RegExp?Y.path.source:Y.path,reason:Y.description};return{isSensitive:!1}}static checkMultiple($){let Z=new Map;for(let J of $)Z.set(J,this.check(J));return Z}static filterSensitive($,Z="low"){let J={["high"]:3,["medium"]:2,["low"]:1},Y=J[Z];return $.map((U)=>({path:U,result:this.check(U)})).filter(({result:U})=>U.isSensitive&&U.level&&J[U.level]>=Y)}static normalizePath($){if($.startsWith("~/")||$==="~")return Q6.join(BU.homedir(),$.slice(1));return Q6.resolve($)}static matchPattern($,Z){if(Z instanceof RegExp)return Z.test($);let J=Z.replace(/\*/g,".*");return new RegExp(`^${J}$`,"i").test($)}static getSensitivePatterns(){return[...this.SENSITIVE_PATTERNS]}static getSensitivePaths(){return[...this.SENSITIVE_PATHS]}}class V6{sessionApprovals;defaultPermissionMode;permissionChecker;constructor($,Z,J){this.sessionApprovals=Z;this.defaultPermissionMode=J;this.permissionChecker=new h$($)}getPermissionChecker(){return this.permissionChecker}resolveRulePermission($,Z,J,Y){let U=Z.getAffectedPaths(),X={toolName:$.name,params:J,affectedPaths:U,tool:$},H=h$.buildSignature(X),Q=this.permissionChecker.check(X);if(Y.subagentType==="verification"){let W=$.name==="Bash"&&typeof J.command==="string"&&J.run_in_background!==!0&&J.env===void 0&&z8(J.cwd,Y.workspaceRoot)&&(z6(Q8(J.command))||W8(J.command));if(!z2($.kind)&&!W)return{signature:H,decision:{behavior:"deny",source:"rule",matchedRule:"builtin:verification-agent-read-only",reason:"Verification agents may only use read-only tools and verification commands"}};if(W){if(Q.result==="deny")return{signature:H,decision:H8(Q)};return{signature:H,decision:{behavior:"allow",source:"rule",matchedRule:"builtin:verification-agent-command",reason:"Verification command allowed for the read-only verifier"}}}}if(Q.result==="ask"&&!Q.matchedRule&&$.name==="Bash"&&typeof J.command==="string"&&z6(J.command))Q={result:"allow",matchedRule:"builtin:read-only-command",reason:"Command classified as read-only, auto-approved"};if(Q=this.applyModeOverrides($.kind,Q,Y.permissionMode??this.defaultPermissionMode),Q.result==="ask"&&this.sessionApprovals.has(H))Q={result:"allow",matchedRule:"remembered:session",reason:"User already allowed this operation in this session"};return Q=this.applySafetyOverrides(U,Q),{decision:H8(Q),signature:H}}applyModeOverrides($,Z,J){if(J==="yolo")return{result:"allow",matchedRule:"mode:yolo",reason:"YOLO mode: automatically approve all tool invocations"};if(J==="plan"&&!z2($))return{result:"deny",matchedRule:"mode:plan",reason:"Plan mode: modification tools are blocked; only read-only tools are allowed"};if(Z.result!=="ask")return Z;if(z2($))return{result:"allow",matchedRule:`mode:${J}:readonly`,reason:"Read-only tools do not require confirmation"};if(J==="autoEdit"&&$==="write")return{result:"allow",matchedRule:"mode:autoEdit:write",reason:"AUTO_EDIT mode: automatically approve write tools"};return Z}applySafetyOverrides($,Z){if(!$?.length)return Z;let J=["/etc/","/sys/","/proc/","/dev/","/boot/","/root/","C:\\Windows\\System32","C:\\Program Files","C:\\ProgramData"],Y=$.filter((Q)=>Q.includes("..")||J.some((W)=>Q.includes(W)));if(Y.length>0)return{result:"deny",matchedRule:"safety:dangerous-system-path",reason:`Access to dangerous system paths denied: ${Y.join(", ")}`};let U=W6.filterSensitive($,"medium");if(U.length===0)return Z;let X=U.map(({path:Q,result:W})=>`${Q} (${W.level}: ${W.reason})`);if(U.some(({result:Q})=>Q.level==="high")&&Z.result!=="allow")return{result:"deny",matchedRule:"safety:high-sensitive-file",reason:`Access to highly sensitive files denied:
|
|
595
595
|
${X.join(`
|
|
596
596
|
`)}
|
|
597
597
|
|
|
@@ -599,7 +599,7 @@ If access is required, add an explicit allow rule in permissions.`};if(Z.result=
|
|
|
599
599
|
${X.join(`
|
|
600
600
|
`)}
|
|
601
601
|
|
|
602
|
-
Confirm to proceed?`};return Z}}function V8($,Z){if($?.behavior==="deny")return $;if(Z?.behavior==="deny")return Z;if(Z?.behavior==="ask")return Z;if($?.behavior==="ask")return $;if($?.behavior==="allow")return $;if(Z?.behavior==="allow")return Z;return{behavior:"ask",source:"default",reason:"No permission rule or hook decision; defaulting to ask"}}function H8($){return{behavior:$.result==="allow"?"allow":$.result==="deny"?"deny":"ask",source:"rule",reason:$.reason,matchedRule:$.matchedRule}}class N1{approvals=new Set;has($){return this.approvals.has($)}add($){this.approvals.add($)}clear(){this.approvals.clear()}}import{Mutex as KU}from"async-mutex";function $0($,Z={}){return{success:!1,llmContent:Z.llmContent??`Tool execution aborted: ${$}`,error:{type:Z.errorType??"execution_error",message:$},metadata:{summary:Z.summary??`执行已中止: ${$}`,...Z.shouldExitLoop?{shouldExitLoop:!0}:{},...Z.abortedBeforeLaunch?{abortedBeforeLaunch:!0}:{}}}}function r0($){return $0("任务已被用户中止",{shouldExitLoop:!0,llmContent:"任务已被用户中止",summary:"任务已被用户中止",abortedBeforeLaunch:$})}var B8=u("Execution");class B6{sessionApprovals;permissionChecker;approvalMutex=new KU;constructor($,Z){this.sessionApprovals=$;this.permissionChecker=Z}async confirmIfNeeded($,Z,J,Y,U,X){if(Y.behavior!=="ask")return;return this.approvalMutex.runExclusive(async()=>{if(X.signal?.aborted)return $0("任务已被用户中止",{shouldExitLoop:!0,llmContent:"任务已被用户中止",summary:"任务已被用户中止",abortedBeforeLaunch:!0});if(this.sessionApprovals.has(U))return;try{let H=await this.runPermissionRequestHook($,J,X);if(H==="approved")return;if(H)return H;let Q={title:$.extractSignatureContent?$.extractSignatureContent(J):$.name,toolName:$.name,args:J,message:Y.reason||"此操作需要用户确认",kind:$.kind,details:_U($.name,J),risks:GU($.name,J),affectedFiles:Z.getAffectedPaths()||[]};B8.warn(`工具 "${$.name}" 需要用户确认: ${Q.title}`);let W=X.confirmationHandler;if(!W){let V=X.permissionMode||"default";if(V==="yolo"){B8.warn("[WARN] No ConfirmationHandler; auto-approving in YOLO mode");return}return $0(`Non-interactive mode with "${V}" permission: tool "${$.name}" requires user confirmation but no interactive handler is available. Use --permission-mode yolo to allow all operations.`,{llmContent:`工具 "${$.name}" 需要用户确认,但当前为非交互模式且权限模式为 "${V}"。请使用 --permission-mode yolo 来允许所有操作。`,summary:"非交互模式下拒绝需要确认的操作",errorType:"permission_denied"})}let z=X.signal?await W.requestConfirmation(Q,X.signal):await W.requestConfirmation(Q);if(X.signal?.aborted)return $0("任务已被用户中止",{shouldExitLoop:!0,llmContent:"任务已被用户中止",summary:"任务已被用户中止",abortedBeforeLaunch:!0});if(!z.approved){if(z.scope==="project")await this.persistProjectPermission($,Z,J,"deny",X.workspaceRoot||N());return $0(z.reason||"用户拒绝授权",{shouldExitLoop:!0,llmContent:"已取消工具执行",summary:"已取消工具执行",errorType:"permission_denied"})}if(z.scope==="session")this.sessionApprovals.add(U);else if(z.scope==="project")await this.persistProjectPermission($,Z,J,"allow",X.workspaceRoot||N());return}catch(H){return $0(`User confirmation failed: ${H instanceof Error?H.message:String(H)}`)}})}async runPermissionRequestHook($,Z,J){let Y=G0.getInstance(),U=J.workspaceRoot||N();if(!Y.isEnabled(U))return;let
|
|
602
|
+
Confirm to proceed?`};return Z}}function V8($,Z){if($?.behavior==="deny")return $;if(Z?.behavior==="deny")return Z;if(Z?.behavior==="ask")return Z;if($?.behavior==="ask")return $;if($?.behavior==="allow")return $;if(Z?.behavior==="allow")return Z;return{behavior:"ask",source:"default",reason:"No permission rule or hook decision; defaulting to ask"}}function H8($){return{behavior:$.result==="allow"?"allow":$.result==="deny"?"deny":"ask",source:"rule",reason:$.reason,matchedRule:$.matchedRule}}class N1{approvals=new Set;has($){return this.approvals.has($)}add($){this.approvals.add($)}clear(){this.approvals.clear()}}import{Mutex as KU}from"async-mutex";function $0($,Z={}){return{success:!1,llmContent:Z.llmContent??`Tool execution aborted: ${$}`,error:{type:Z.errorType??"execution_error",message:$},metadata:{summary:Z.summary??`执行已中止: ${$}`,...Z.shouldExitLoop?{shouldExitLoop:!0}:{},...Z.abortedBeforeLaunch?{abortedBeforeLaunch:!0}:{}}}}function r0($){return $0("任务已被用户中止",{shouldExitLoop:!0,llmContent:"任务已被用户中止",summary:"任务已被用户中止",abortedBeforeLaunch:$})}var B8=u("Execution");class B6{sessionApprovals;permissionChecker;approvalMutex=new KU;constructor($,Z){this.sessionApprovals=$;this.permissionChecker=Z}async confirmIfNeeded($,Z,J,Y,U,X){if(Y.behavior!=="ask")return;return this.approvalMutex.runExclusive(async()=>{if(X.signal?.aborted)return $0("任务已被用户中止",{shouldExitLoop:!0,llmContent:"任务已被用户中止",summary:"任务已被用户中止",abortedBeforeLaunch:!0});if(this.sessionApprovals.has(U))return;try{let H=await this.runPermissionRequestHook($,J,X);if(H==="approved")return;if(H)return H;let Q={title:$.extractSignatureContent?$.extractSignatureContent(J):$.name,toolName:$.name,args:J,message:Y.reason||"此操作需要用户确认",kind:$.kind,details:_U($.name,J),risks:GU($.name,J),affectedFiles:Z.getAffectedPaths()||[]};B8.warn(`工具 "${$.name}" 需要用户确认: ${Q.title}`);let W=X.confirmationHandler;if(!W){let V=X.permissionMode||"default";if(V==="yolo"){B8.warn("[WARN] No ConfirmationHandler; auto-approving in YOLO mode");return}return $0(`Non-interactive mode with "${V}" permission: tool "${$.name}" requires user confirmation but no interactive handler is available. Use --permission-mode yolo to allow all operations.`,{llmContent:`工具 "${$.name}" 需要用户确认,但当前为非交互模式且权限模式为 "${V}"。请使用 --permission-mode yolo 来允许所有操作。`,summary:"非交互模式下拒绝需要确认的操作",errorType:"permission_denied"})}let z=X.signal?await W.requestConfirmation(Q,X.signal):await W.requestConfirmation(Q);if(X.signal?.aborted)return $0("任务已被用户中止",{shouldExitLoop:!0,llmContent:"任务已被用户中止",summary:"任务已被用户中止",abortedBeforeLaunch:!0});if(!z.approved){if(z.scope==="project")await this.persistProjectPermission($,Z,J,"deny",X.workspaceRoot||N());return $0(z.reason||"用户拒绝授权",{shouldExitLoop:!0,llmContent:"已取消工具执行",summary:"已取消工具执行",errorType:"permission_denied"})}if(z.scope==="session")this.sessionApprovals.add(U);else if(z.scope==="project")await this.persistProjectPermission($,Z,J,"allow",X.workspaceRoot||N());return}catch(H){return $0(`User confirmation failed: ${H instanceof Error?H.message:String(H)}`)}})}async runPermissionRequestHook($,Z,J){let Y=G0.getInstance(),U=J.workspaceRoot||N(),X=J.sessionId||"unknown";if(!Y.isEnabled(U,X))return;let H=await Y.executePermissionRequestHooks($.name,X,Z,{projectDir:U,sessionId:X,permissionMode:J.permissionMode||"default"});if(H.decision==="approve")return"approved";if(H.decision==="deny")return $0(H.reason||`PermissionRequest hook denied: ${$.name}`,{shouldExitLoop:!0,errorType:"permission_denied"});return}async persistProjectPermission($,Z,J,Y,U){let X={toolName:$.name,params:J,affectedPaths:Z.getAffectedPaths()||[],tool:$},H=h$.abstractPattern(X);if(!H)throw Error(`Tool "${$.name}" does not support project permission rules`);if(Y==="allow")await u$().appendLocalPermissionRule(H,{immediate:!0,projectDir:U});else await u$().appendLocalPermissionDenyRule(H,{immediate:!0,projectDir:U});this.permissionChecker.updateConfig({[Y]:[H]})}}function _U($,Z){if($==="Edit"){let{old_string:J,new_string:Y}=Z;if(!J&&!Y)return;return`**变更前:**
|
|
603
603
|
\`\`\`
|
|
604
604
|
${K8(J||"(空)",20)}
|
|
605
605
|
\`\`\`
|
|
@@ -630,29 +630,29 @@ ${U}
|
|
|
630
630
|
... (${Y.length-100} more lines)`}return}function K8($,Z){let J=$.split(`
|
|
631
631
|
`);return J.length<=Z?$:`${J.slice(0,Z).join(`
|
|
632
632
|
`)}
|
|
633
|
-
... (还有 ${J.length-Z} 行)`}function GU($,Z){let J=[];if($==="Bash"){let Y=Z.command||"";if(Y.includes("rm"))J.push("[WARN] 此命令可能删除文件");if(Y.includes("sudo"))J.push("[WARN] 此命令需要管理员权限");if(Y.includes("git push"))J.push("[WARN] 此命令将推送代码到远程仓库")}else if($==="Write"||$==="Edit"||$==="ApplyPatch")J.push("此操作将修改文件内容");else if($==="Delete")J.push("此操作将永久删除文件");return J}class K6{queue=[];concurrentInFlight=0;exclusiveInFlight=!1;run($,Z,J,Y){if(J?.aborted)try{return Promise.resolve(Y())}catch(U){return Promise.reject(U)}return new Promise((U,X)=>{let H={concurrent:$,fn:Z,onAbort:Y,resolve:U,reject:X,signal:J,started:!1};if(J)H.abortListener=()=>{if(H.started)return;let Q=this.queue.indexOf(H);if(Q===-1)return;this.queue.splice(Q,1),J.removeEventListener("abort",H.abortListener);try{U(Y())}catch(W){X(W)}this.drain()},J.addEventListener("abort",H.abortListener,{once:!0});this.queue.push(H),this.drain()})}drain(){if(this.exclusiveInFlight||this.queue.length===0)return;if(this.concurrentInFlight>0){while(this.queue[0]?.concurrent)this.start(this.queue.shift());return}if(!this.queue[0].concurrent){this.start(this.queue.shift());return}while(this.queue[0]?.concurrent)this.start(this.queue.shift())}start($){if($.started=!0,$.signal&&$.abortListener)$.signal.removeEventListener("abort",$.abortListener);if($.concurrent)this.concurrentInFlight++;else this.exclusiveInFlight=!0;Promise.resolve().then($.fn).then($.resolve,$.reject).finally(()=>{if($.concurrent)this.concurrentInFlight--;else this.exclusiveInFlight=!1;this.drain()})}}function G8($,Z,J,Y){if(Y?.has($.name))return $0(`Tool "${$.name}" is blocked by --disallowed-tools`);if(J&&!J.has($.name))return $0(`Tool "${$.name}" is not in --allowed-tools whitelist`);try{return{invocation:$.build(Z),params:Z}}catch(U){return $0(`Parameter validation failed: ${U instanceof Error?U.message:String(U)}`,{errorType:"validation_error"})}}async function _6($,Z,J,Y){if(J.worktreeActive)return OU($,Z,J,Y);let U=$.name==="Task"&&Z.isolation==="worktree";if(!J.worktreeIsolationRequired||$.name==="EnterWorktree"||U||$.kind==="readonly"&&$.name!=="Task")return;return $0("Blocked side-effecting tool outside the explicitly required worktree",{llmContent:"Worktree isolation is required. Call EnterWorktree and wait for it to succeed before using any write or execute tool.",summary:"Blocked until EnterWorktree succeeds",errorType:"permission_denied"})}async function OU($,Z,J,Y){let X=[...($.kind==="write"?["file_path","notebook_path","path"]:$.name==="Bash"?["cwd"]:[]).map((Q)=>Z[Q]).filter((Q)=>typeof Q==="string"),...Y?.getAffectedPaths()??[]];if(X.length===0)return;let H=J.workspaceRoot;if(!H)return _8(X[0],"workspace root is missing");for(let Q of X)if(!await X0.isWithinWorkspaceResolved(Q,H))return _8(Q);return}function _8($,Z){let J=Z?` (${Z})`:"";return $0(`Blocked path outside the active worktree: ${$}${J}`,{llmContent:`The requested path "${$}" is outside the active worktree. Use a path under the current workspace root.`,summary:"Blocked path outside active worktree",errorType:"permission_denied"})}import{nanoid as O8}from"nanoid";async function E8($,Z,J,Y,U,X=G0.getInstance()){let H=Y.workspaceRoot||N(),Q={params:Z,invocation:J,inputModified:!1};if(!X.isEnabled(H)||U.behavior==="deny")return
|
|
633
|
+
... (还有 ${J.length-Z} 行)`}function GU($,Z){let J=[];if($==="Bash"){let Y=Z.command||"";if(Y.includes("rm"))J.push("[WARN] 此命令可能删除文件");if(Y.includes("sudo"))J.push("[WARN] 此命令需要管理员权限");if(Y.includes("git push"))J.push("[WARN] 此命令将推送代码到远程仓库")}else if($==="Write"||$==="Edit"||$==="ApplyPatch")J.push("此操作将修改文件内容");else if($==="Delete")J.push("此操作将永久删除文件");return J}class K6{queue=[];concurrentInFlight=0;exclusiveInFlight=!1;run($,Z,J,Y){if(J?.aborted)try{return Promise.resolve(Y())}catch(U){return Promise.reject(U)}return new Promise((U,X)=>{let H={concurrent:$,fn:Z,onAbort:Y,resolve:U,reject:X,signal:J,started:!1};if(J)H.abortListener=()=>{if(H.started)return;let Q=this.queue.indexOf(H);if(Q===-1)return;this.queue.splice(Q,1),J.removeEventListener("abort",H.abortListener);try{U(Y())}catch(W){X(W)}this.drain()},J.addEventListener("abort",H.abortListener,{once:!0});this.queue.push(H),this.drain()})}drain(){if(this.exclusiveInFlight||this.queue.length===0)return;if(this.concurrentInFlight>0){while(this.queue[0]?.concurrent)this.start(this.queue.shift());return}if(!this.queue[0].concurrent){this.start(this.queue.shift());return}while(this.queue[0]?.concurrent)this.start(this.queue.shift())}start($){if($.started=!0,$.signal&&$.abortListener)$.signal.removeEventListener("abort",$.abortListener);if($.concurrent)this.concurrentInFlight++;else this.exclusiveInFlight=!0;Promise.resolve().then($.fn).then($.resolve,$.reject).finally(()=>{if($.concurrent)this.concurrentInFlight--;else this.exclusiveInFlight=!1;this.drain()})}}function G8($,Z,J,Y){if(Y?.has($.name))return $0(`Tool "${$.name}" is blocked by --disallowed-tools`);if(J&&!J.has($.name))return $0(`Tool "${$.name}" is not in --allowed-tools whitelist`);try{return{invocation:$.build(Z),params:Z}}catch(U){return $0(`Parameter validation failed: ${U instanceof Error?U.message:String(U)}`,{errorType:"validation_error"})}}async function _6($,Z,J,Y){if(J.worktreeActive)return OU($,Z,J,Y);let U=$.name==="Task"&&Z.isolation==="worktree";if(!J.worktreeIsolationRequired||$.name==="EnterWorktree"||U||$.kind==="readonly"&&$.name!=="Task")return;return $0("Blocked side-effecting tool outside the explicitly required worktree",{llmContent:"Worktree isolation is required. Call EnterWorktree and wait for it to succeed before using any write or execute tool.",summary:"Blocked until EnterWorktree succeeds",errorType:"permission_denied"})}async function OU($,Z,J,Y){let X=[...($.kind==="write"?["file_path","notebook_path","path"]:$.name==="Bash"?["cwd"]:[]).map((Q)=>Z[Q]).filter((Q)=>typeof Q==="string"),...Y?.getAffectedPaths()??[]];if(X.length===0)return;let H=J.workspaceRoot;if(!H)return _8(X[0],"workspace root is missing");for(let Q of X)if(!await X0.isWithinWorkspaceResolved(Q,H))return _8(Q);return}function _8($,Z){let J=Z?` (${Z})`:"";return $0(`Blocked path outside the active worktree: ${$}${J}`,{llmContent:`The requested path "${$}" is outside the active worktree. Use a path under the current workspace root.`,summary:"Blocked path outside active worktree",errorType:"permission_denied"})}import{nanoid as O8}from"nanoid";async function E8($,Z,J,Y,U,X=G0.getInstance()){let H=Y.workspaceRoot||N(),Q=Y.sessionId||"unknown",W={params:Z,invocation:J,inputModified:!1};if(!X.isEnabled(H,Q)||U.behavior==="deny")return W;try{let z=Y.messageId||`tool_${O8()}`,V=await X.executePreToolHooks($.name,z,Z,{projectDir:H,sessionId:Q,permissionMode:Y.permissionMode??"default",abortSignal:Y.signal});if(V.warning)console.warn(`[Hook Warning] ${V.warning}`);let B={behavior:V.decision,source:"hook",reason:V.reason};if(!V.modifiedInput||V.decision==="deny")return{...W,decision:B,toolUseId:z};let K={...Z,...V.modifiedInput};try{return{params:K,invocation:$.build(K),decision:B,toolUseId:z,inputModified:!0}}catch(G){return{...W,decision:B,toolUseId:z,rejection:$0(`Hook modified parameters are invalid: ${G instanceof Error?G.message:String(G)}`,{errorType:"validation_error"})}}}catch(z){return console.error("[ToolExecutionHooks] Error executing pre-tool hooks:",z),W}}async function q8($,Z,J,Y,U,X=G0.getInstance()){let H=Y.workspaceRoot||N(),Q=Y.sessionId||"unknown";if(!X.isEnabled(H,Q))return;try{let W=U||Y.messageId||`tool_${O8()}`,z=await X.executePostToolHooks($.name,W,Z,J,{projectDir:H,sessionId:Q,permissionMode:Y.permissionMode??"default",abortSignal:Y.signal});if(z.additionalContext){let V=typeof J.llmContent==="string"?J.llmContent:J.llmContent?JSON.stringify(J.llmContent):"";J.llmContent=`${V}
|
|
634
634
|
|
|
635
635
|
---
|
|
636
636
|
**Hook Context:**
|
|
637
|
-
`+
|
|
637
|
+
`+z.additionalContext}if(EU(z.modifiedOutput))Object.assign(J,z.modifiedOutput);if(z.warning)console.warn(`[PostToolUseHook Warning] ${z.warning}`)}catch(W){console.error("[ToolExecutionHooks] Error executing post-tool hooks:",W)}}function EU($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var qU=["EBUSY","EAGAIN","EMFILE","ENFILE"];async function F8($,Z){let J=Date.now(),Y;for(let U=0;U<=2;U++)try{let X=await $.execute(Z.signal??new AbortController().signal,Z.onProgress,Z);if(X.metadata??={},X.metadata.duration=Date.now()-J,U>0)X.metadata.retriedAttempts=U;return X}catch(X){if(Y=X instanceof Error?X:Error(String(X)),U>=2||!qU.some((H)=>Y?.message.includes(H)))break;await FU(200*(U+1))}throw Y??Error("Tool execution failed")}function D8($,Z,J){if(!$.llmContent)$.llmContent="Execution completed";return $.metadata??={},$.metadata.executionId=Z,$.metadata.toolName=J,$.metadata.timestamp=Date.now(),$}function FU($){return new Promise((Z)=>setTimeout(Z,$))}class b1 extends wU{registry;executionHistory=[];maxHistorySize;scheduler;toolWhitelist;toolBlacklist;permissionResolver;approvalController;concurrencyGate=new K6;contextDefaults;autoVerifyRuntime;lspManager;onDispose;disposed=!1;constructor($,Z={}){super();this.registry=$;this.maxHistorySize=Z.maxHistorySize??1000,this.contextDefaults=Z.contextDefaults??{},this.autoVerifyRuntime=Z.autoVerifyRuntime,this.lspManager=Z.lspManager,this.onDispose=Z.onDispose,this.toolWhitelist=Z.toolWhitelist?.length?new Set(Z.toolWhitelist):null,this.toolBlacklist=Z.toolBlacklist?.length?new Set(Z.toolBlacklist):null,this.scheduler=Z.scheduler??(Z.concurrencyLimits?new W$(Z.concurrencyLimits):W$.getInstance());let J=Z.approvalStore??new N1;this.permissionResolver=new V6(Z.permissionConfig??{allow:[],ask:[],deny:[]},J,Z.permissionMode??"default"),this.approvalController=new B6(J,this.permissionResolver.getPermissionChecker())}async execute($,Z,J){let Y=Date.now(),U=`exec_${DU()}`,X={...this.contextDefaults,...J,sessionId:J.sessionId??this.contextDefaults.sessionId??U,environment:{...this.contextDefaults.environment,...J.environment}};return this.emit("executionStarted",{executionId:U,toolName:$,params:Z,context:X,timestamp:Y}),this.executeFlow($,Z,X,U,Y)}async executeFlow($,Z,J,Y,U){let X=Z;try{let H=await this.runTool($,Z,J,Y,(Q)=>{X=Q});return this.completeExecution(Y,$,X,J,H,U),H}catch(H){return this.failExecution(Y,$,X,J,H,U)}}async runTool($,Z,J,Y,U){if(J.signal?.aborted)return r0(!0);let X=this.registry.get($);if(!X)return $0(`Tool "${$}" not found`,{errorType:"validation_error"});let H=G8(X,Z,this.toolWhitelist,this.toolBlacklist);if("success"in H)return H;return this.concurrencyGate.run(X.parallelism==="shared"||X.parallelism===void 0&&X.isConcurrencySafe,async()=>{if(J.signal?.aborted)return r0(!0);let{params:Q,invocation:W}=H,z=await _6(X,Q,J,W);if(z)return z;let V=this.permissionResolver.resolveRulePermission(X,W,Q,J),B=await E8(X,Q,W,J,V.decision);if(B.rejection)return B.rejection;if(Q=B.params,W=B.invocation,U(Q),B.inputModified){let L=await _6(X,Q,J,W);if(L)return L;V=this.permissionResolver.resolveRulePermission(X,W,Q,J)}let K=V8(V.decision,B.decision);if(K.behavior==="deny")return $0(K.reason||`Tool invocation denied by ${K.source}${K.matchedRule?` (${K.matchedRule})`:""}`,{errorType:"permission_denied"});let G=await this.approvalController.confirmIfNeeded(X,W,Q,K,V.signature,J);if(G)return G;if(J.signal?.aborted)return r0(!0);let O=!1,E=()=>{if(J.signal?.aborted)return Promise.resolve(r0(!0));return O=!0,F8(W,J)},q=Q.file_path??Q.notebook_path,F=!X.isConcurrencySafe&&q?()=>f0.getInstance().acquireLock(String(q),E):E,D=await this.scheduler.schedule(X.kind,F);if(J.signal?.aborted)return r0(!O);if(await q8(X,Q,D,J,B.toolUseId),J.signal?.aborted)return r0(!1);if(await this.lspManager?.afterToolUse(X.name,Q,D,J),J.signal?.aborted)return r0(!1);if(await this.autoVerifyRuntime?.verify(X.name,Q,J,D),J.signal?.aborted)return r0(!1);return D8(D,Y,X.name)},J.signal,()=>r0(!0))}completeExecution($,Z,J,Y,U,X){let H=Date.now();this.addToHistory({executionId:$,toolName:Z,params:J,result:U,startTime:X,endTime:H,context:Y}),this.emit("executionCompleted",{executionId:$,toolName:Z,result:U,duration:H-X,timestamp:H})}async failExecution($,Z,J,Y,U,X){let H=U instanceof Error?U:Error(String(U)),Q=Date.now(),W=H.message.includes("timeout")||H.name==="TimeoutError",z={success:!1,llmContent:`Tool execution failed: ${H.message}`,error:{type:W?"timeout_error":"execution_error",message:H.message}};try{let V=await G0.getInstance().executePostToolUseFailureHooks(Z,`tool_use_${$}`,J,H.message,{projectDir:Y.workspaceRoot||N(),sessionId:Y.sessionId||"unknown",permissionMode:Y.permissionMode||"default",isInterrupt:!1,isTimeout:W,abortSignal:Y.signal});if(V.additionalContext)z={...z,llmContent:`${z.llmContent}
|
|
638
638
|
|
|
639
639
|
${V.additionalContext}`};if(V.warning)console.warn(`[ToolExecutor] PostToolUseFailure hook warning: ${V.warning}`)}catch(V){console.warn("[ToolExecutor] PostToolUseFailure hook execution failed:",V)}return this.addToHistory({executionId:$,toolName:Z,params:J,result:z,startTime:X,endTime:Q,context:Y}),this.emit("executionFailed",{executionId:$,toolName:Z,error:H,duration:Q-X,timestamp:Q}),z}async executeAll($){return Promise.all($.map((Z)=>this.execute(Z.toolName,Z.params,Z.context)))}async executeParallel($,Z=5){let J=Z>0?Z:Number.POSITIVE_INFINITY;if(!Number.isFinite(J)||J>=$.length)return this.executeAll($);let Y=Array($.length),U=0,X=async()=>{while(U<$.length){let H=U++,Q=$[H];Y[H]=await this.execute(Q.toolName,Q.params,Q.context)}};return await Promise.all(Array.from({length:Math.min(J,$.length)},()=>X())),Y}getSchedulerStats(){return this.scheduler.getStats()}getExecutionHistory($){return $?this.executionHistory.slice(-$):[...this.executionHistory]}clearHistory(){this.executionHistory.length=0,this.emit("historyClear",{timestamp:Date.now()})}getStats(){let $={totalExecutions:this.executionHistory.length,successfulExecutions:0,failedExecutions:0,averageDuration:0,toolUsage:new Map,recentExecutions:this.executionHistory.slice(-10)},Z=0;for(let J of this.executionHistory){if(J.result.success)$.successfulExecutions++;else $.failedExecutions++;Z+=J.endTime-J.startTime,$.toolUsage.set(J.toolName,($.toolUsage.get(J.toolName)||0)+1)}return $.averageDuration=$.totalExecutions>0?Z/$.totalExecutions:0,$}getRegistry(){return this.registry}dispose(){if(this.disposed)return;this.disposed=!0,this.onDispose?.(),this.removeAllListeners()}addToHistory($){if(this.executionHistory.push($),this.executionHistory.length>this.maxHistorySize)this.executionHistory.splice(0,this.executionHistory.length-this.maxHistorySize)}}import{EventEmitter as AU}from"events";var V2=new Set(["Read","Edit","Write","ApplyPatch","Glob","Grep","Bash","WriteStdin","Task","TaskOutput","TaskCreate","TaskGet","TaskUpdate","TaskList","TeamCreate","TeamStatus","TeamDelete","AskUserQuestion","Skill","SlashCommand","ToolSearch","EnterPlanMode","ExitPlanMode","EnterWorktree","ExitWorktree"]);class G6{loadedTools=new Set(V2);deferredTools=new Set;register($){if(V2.has($))this.loadedTools.add($);else this.deferredTools.add($)}unregister($){if(V2.has($))return;this.loadedTools.delete($),this.deferredTools.delete($)}syncDynamicTools($,Z){let J=new Set(Z);for(let Y of $)if(!J.has(Y))this.unregister(Y);for(let Y of Z)if(!this.loadedTools.has(Y)&&!this.deferredTools.has(Y))this.register(Y)}markLoaded($){this.loadedTools.add($),this.deferredTools.delete($)}isLoaded($){return this.loadedTools.has($)}filterDeclarations($,Z){return $.filter((J)=>this.isLoaded(J.name)).map((J)=>J.getFunctionDeclaration())}getDeferredToolNames(){return Array.from(this.deferredTools)}getDeferredToolsListing(){let $=this.getDeferredToolNames();if($.length===0)return"";return["<available-deferred-tools>",...$,"</available-deferred-tools>"].join(`
|
|
640
640
|
`)}reset(){this.loadedTools=new Set(V2),this.deferredTools.clear()}}class A$ extends AU{tools=new Map;mcpTools=new Map;categories=new Map;tags=new Map;_deferredManager=new G6;pendingMcpCatalogChanges=[];pendingMcpContentChanges=[];pendingMcpResourceUpdates=[];pendingMcpConnectionChanges=[];pendingMcpLogs=[];pendingMcpInstructionChanges=[];pendingMcpTaskChanges=[];mcpCatalogBarrier=async()=>{return};constructor(){super()}get deferredToolManager(){return this._deferredManager}setMcpCatalogBarrier($){this.mcpCatalogBarrier=$}waitForMcpCatalogIdle(){return this.mcpCatalogBarrier()}register($){if(this.tools.has($.name))throw Error(`工具 '${$.name}' 已注册`);this.tools.set($.name,$),this.updateIndexes($),this._deferredManager.register($.name),this.emit("toolRegistered",{type:"builtin",tool:$,timestamp:Date.now()})}registerAll($){let Z=[];for(let J of $)try{this.register(J)}catch(Y){Z.push(`${J.name}: ${Y.message}`)}if(Z.length>0)throw Error(`批量注册失败: ${Z.join(", ")}`)}unregister($){let Z=this.tools.get($)??this.mcpTools.get($);if(!Z)return!1;let J=this.tools.delete($)?"builtin":"mcp";return this.mcpTools.delete($),this.removeFromIndexes(Z),this._deferredManager.unregister($),this.emit("toolUnregistered",{type:J,toolName:$,timestamp:Date.now()}),!0}get($){return this.tools.get($)||this.mcpTools.get($)}has($){return this.tools.has($)||this.mcpTools.has($)}getAll(){return[...Array.from(this.tools.values()),...Array.from(this.mcpTools.values())]}getBuiltinTools(){return Array.from(this.tools.values())}getMcpTools(){return Array.from(this.mcpTools.values())}getByCategory($){let Z=this.categories.get($);if(!Z)return[];return Array.from(Z).map((J)=>this.get(J)).filter((J)=>J!==void 0)}getByTag($){let Z=this.tags.get($);if(!Z)return[];return Array.from(Z).map((J)=>this.get(J)).filter((J)=>J!==void 0)}search($){let Z=$.toLowerCase();return this.getAll().filter((J)=>{let Y=typeof J.description==="string"?J.description:J.description.short;return J.name.toLowerCase().includes(Z)||Y.toLowerCase().includes(Z)||J.displayName.toLowerCase().includes(Z)||J.category&&J.category.toLowerCase().includes(Z)||J.tags.some((U)=>U.toLowerCase().includes(Z))})}getFunctionDeclarations(){return this.getAll().map(($)=>$.getFunctionDeclaration())}getReadOnlyFunctionDeclarations(){return this.getAll().filter(($)=>$.isReadOnly).map(($)=>$.getFunctionDeclaration())}getFunctionDeclarationsByMode($){if($==="plan")return this.getReadOnlyFunctionDeclarations();return this._deferredManager.filterDeclarations(this.getAll(),$)}getReadOnlyTools(){return this.getAll().filter(($)=>$.isReadOnly)}getCategories(){return Array.from(this.categories.keys())}getTags(){return Array.from(this.tags.keys())}getStats(){return{totalTools:this.tools.size+this.mcpTools.size,builtinTools:this.tools.size,mcpTools:this.mcpTools.size,categories:this.categories.size,tags:this.tags.size,toolsByCategory:Object.fromEntries(Array.from(this.categories.entries()).map(([$,Z])=>[$,Z.size]))}}getDeferredToolsListing(){return this._deferredManager.getDeferredToolsListing()}clone(){let $=new A$;$.setMcpCatalogBarrier(this.mcpCatalogBarrier);for(let Z of this.tools.values())$.register(Z);for(let Z of this.mcpTools.values())$.registerMcpTool(Z);return $}registerMcpTool($){if(this.tools.has($.name))throw Error(`MCP 工具 '${$.name}' 与内置工具冲突`);if(this.mcpTools.has($.name))this.removeFromIndexes(this.mcpTools.get($.name)),this.mcpTools.delete($.name);this.mcpTools.set($.name,$),this.updateIndexes($),this._deferredManager.register($.name),this.emit("toolRegistered",{type:"mcp",tool:$,timestamp:Date.now()})}replaceMcpTools($,Z){let J=new Map;for(let U of $){if(J.has(U.name))throw Error(`MCP catalog contains duplicate tool '${U.name}'`);if(this.tools.has(U.name))throw Error(`MCP tool '${U.name}' conflicts with a builtin tool`);J.set(U.name,U)}let Y=[...this.mcpTools.keys()];for(let U of this.mcpTools.values())this.removeFromIndexes(U);this.mcpTools=J;for(let U of J.values())this.updateIndexes(U);if(this._deferredManager.syncDynamicTools(Y,[...J.keys()]),Z){if(this.pendingMcpCatalogChanges.push(structuredClone(Z)),this.pendingMcpCatalogChanges.length>32)this.pendingMcpCatalogChanges.shift()}this.emit("mcpCatalogReplaced",{toolCount:J.size,change:Z,timestamp:Date.now()})}drainMcpCatalogChanges(){let $=this.pendingMcpCatalogChanges;return this.pendingMcpCatalogChanges=[],$}queueMcpContentChange($){if(this.pendingMcpContentChanges.push(structuredClone($)),this.pendingMcpContentChanges.length>32)this.pendingMcpContentChanges.shift()}drainMcpContentChanges(){let $=this.pendingMcpContentChanges;return this.pendingMcpContentChanges=[],$}queueMcpResourceUpdated($){if(!this.pendingMcpResourceUpdates.some((J)=>J.serverName===$.serverName&&J.uri===$.uri))this.pendingMcpResourceUpdates.push(structuredClone($));if(this.pendingMcpResourceUpdates.length>32)this.pendingMcpResourceUpdates.shift()}drainMcpResourceUpdates(){let $=this.pendingMcpResourceUpdates;return this.pendingMcpResourceUpdates=[],$}queueMcpConnectionChange($){if(this.pendingMcpConnectionChanges.push(structuredClone($)),this.pendingMcpConnectionChanges.length>32)this.pendingMcpConnectionChanges.shift()}drainMcpConnectionChanges(){let $=this.pendingMcpConnectionChanges;return this.pendingMcpConnectionChanges=[],$}queueMcpLog($){if(this.pendingMcpLogs.push(structuredClone($)),this.pendingMcpLogs.length>64)this.pendingMcpLogs.shift()}drainMcpLogs(){let $=this.pendingMcpLogs;return this.pendingMcpLogs=[],$}queueMcpInstructionsChange($){if(this.pendingMcpInstructionChanges.push(structuredClone($)),this.pendingMcpInstructionChanges.length>32)this.pendingMcpInstructionChanges.shift()}drainMcpInstructionsChanges(){let $=this.pendingMcpInstructionChanges;return this.pendingMcpInstructionChanges=[],$}queueMcpTaskChange($){if(this.pendingMcpTaskChanges.push(structuredClone($)),this.pendingMcpTaskChanges.length>64)this.pendingMcpTaskChanges.shift()}drainMcpTaskChanges(){let $=this.pendingMcpTaskChanges;return this.pendingMcpTaskChanges=[],$}removeMcpTools($){let Z=0,J=w8($);for(let Y of this.mcpTools.keys())if(Y.startsWith(J)){let U=this.mcpTools.get(Y);this.mcpTools.delete(Y),this.removeFromIndexes(U),this._deferredManager.unregister(Y),Z++,this.emit("toolUnregistered",{type:"mcp",toolName:Y,serverName:$,timestamp:Date.now()})}return Z}updateIndexes($){if($.category){if(!this.categories.has($.category))this.categories.set($.category,new Set);this.categories.get($.category).add($.name)}for(let Z of $.tags){if(!this.tags.has(Z))this.tags.set(Z,new Set);this.tags.get(Z).add($.name)}}removeFromIndexes($){if($.category){let Z=this.categories.get($.category);if(Z){if(Z.delete($.name),Z.size===0)this.categories.delete($.category)}}for(let Z of $.tags){let J=this.tags.get(Z);if(J){if(J.delete($.name),J.size===0)this.tags.delete(Z)}}}}import*as b8 from"crypto";import{nanoid as NU}from"nanoid";class O6{assemble($){if($.length===0)return null;let Z=this.assembleSession($),J=this.assembleConversation($),Y=this.assembleToolCalls($);return{session:Z,conversation:J,toolCalls:Y}}assembleContextData($,Z,J){let Y=this.assemble($);if(!Y)return null;return{layers:{system:Z,session:Y.session,conversation:Y.conversation,tool:{recentCalls:Y.toolCalls,toolStates:{},dependencies:{}},workspace:J},metadata:{totalTokens:0,priority:1,lastUpdated:Date.now()}}}assembleSession($){let Z=$.find((H)=>H.type==="session_created"),J=Z?.sessionId??$[0].sessionId,Y=new Date(Z?.timestamp??$[0].timestamp).getTime(),U=$.filter((H)=>H.type==="session_updated"),X=U.length>0?U[U.length-1]:null;return{sessionId:J,userId:void 0,preferences:{},configuration:X?.data??{},startTime:Y}}assembleConversation($){let Z=new Map,J;for(let H of $){if(H.type==="message_created")Z.set(H.data.messageId,{id:H.data.messageId,role:H.data.role,content:"",timestamp:new Date(H.timestamp).getTime(),metadata:H.data.model||H.data.inboxMessageId||H.data.metadata&&typeof H.data.metadata==="object"&&!Array.isArray(H.data.metadata)?{...H.data.metadata&&typeof H.data.metadata==="object"&&!Array.isArray(H.data.metadata)?H.data.metadata:{},...H.data.model?{model:H.data.model}:{},...H.data.inboxMessageId?{inboxMessageId:H.data.inboxMessageId}:{}}:void 0});if(H.type==="part_created"){let{partType:Q,messageId:W,payload:z}=H.data,V=Z.get(W);if(Q==="text"&&V){let B=z;V.content=B.text??""}if(Q==="image"&&V)V.content=V.content?`${V.content}
|
|
641
641
|
[Image]`:"[Image]";if(Q==="summary"){let B=z;if(B.text)J=B.text}}if(H.type==="part_updated"){let{partType:Q,messageId:W,payload:z}=H.data,V=Z.get(W);if(Q==="text"&&V){let B=z;V.content=B.text??""}}}let Y=Array.from(Z.values()),U=$[$.length-1],X=new Date(U.timestamp).getTime();return{messages:Y,summary:J,topics:[],lastActivity:X}}assembleToolCalls($){let Z=new Map;for(let J of $){if(J.type!=="part_created")continue;let{partType:Y,partId:U,payload:X}=J.data;if(Y==="tool_call"){let H=X,Q=H.toolCallId??U;Z.set(Q,{id:Q,name:H.toolName??"unknown",input:H.input??null,timestamp:new Date(J.timestamp).getTime(),status:"pending"})}if(Y==="tool_result"){let H=X,Q=H.toolCallId??U,W=Z.get(Q);if(W)W.output=H.output??void 0,W.status=H.error?"error":"success",W.error=H.error??void 0;else Z.set(Q,{id:Q,name:H.toolName??"unknown",input:null,output:H.output??void 0,timestamp:new Date(J.timestamp).getTime(),status:H.error?"error":"success",error:H.error??void 0})}}return Array.from(Z.values())}}class E6{maxSummaryLength;keyPointsLimit;recentMessagesLimit;constructor($=500,Z=10,J=20){this.maxSummaryLength=$,this.keyPointsLimit=Z,this.recentMessagesLimit=J}async compress($){let Z=$.layers.conversation.messages,J=$.layers.tool.recentCalls,Y=Z.filter((B)=>B.role==="system"),U=Z.filter((B)=>B.role!=="system"),X=this.getRecentMessages(U),H=U.slice(0,-this.recentMessagesLimit),Q=await this.generateSummary(H),W=this.extractKeyPoints(H,J),z=this.generateToolSummary(J),V=this.estimateTokenCount(Q,W,X,z);return{summary:Q,keyPoints:W,recentMessages:[...Y,...X],toolSummary:z,tokenCount:V}}getRecentMessages($){return $.slice(-this.recentMessagesLimit)}async generateSummary($){if($.length===0)return"";let Z=new Set,J=new Set,Y=new Set;for(let X of $){let H=X.content.toLowerCase();["关于","讨论","问题","项目","功能","需求"].forEach((V)=>{if(H.includes(V)){let B=this.extractContext(H,V,50);if(B)Z.add(B)}}),["创建","删除","修改","更新","实现","开发"].forEach((V)=>{if(H.includes(V)){let B=this.extractContext(H,V,30);if(B)J.add(B)}}),["决定","选择","确定","采用","使用"].forEach((V)=>{if(H.includes(V)){let B=this.extractContext(H,V,40);if(B)Y.add(B)}})}let U=`对话涉及 ${$.length} 条消息。`;if(Z.size>0)U+=` 主要讨论:${Array.from(Z).slice(0,3).join("、")}。`;if(J.size>0)U+=` 执行操作:${Array.from(J).slice(0,3).join("、")}。`;if(Y.size>0)U+=` 关键决策:${Array.from(Y).slice(0,2).join("、")}。`;return U.length>this.maxSummaryLength?U.substring(0,this.maxSummaryLength)+"...":U}extractKeyPoints($,Z){let J=new Set;for(let U of $)if(U.role==="user")this.extractQuestions(U.content).forEach((Q)=>J.add(`用户问题:${Q}`)),this.extractRequests(U.content).forEach((Q)=>J.add(`用户请求:${Q}`));else if(U.role==="assistant")this.extractSolutions(U.content).forEach((H)=>J.add(`解决方案:${H}`));return this.summarizeToolUsage(Z).forEach((U)=>J.add(`工具使用:${U}`)),Array.from(J).slice(0,this.keyPointsLimit)}generateToolSummary($){if($.length===0)return"";let Z=new Map,J=Date.now()-600000;for(let U of $){let X=Z.get(U.name)||{count:0,success:0,recent:0};if(X.count++,U.status==="success")X.success++;if(U.timestamp>J)X.recent++;Z.set(U.name,X)}let Y=[];for(let[U,X]of Array.from(Z.entries())){let H=Math.round(X.success/X.count*100);Y.push(`${U}(${X.count}次,成功率${H}%)`)}return`工具调用:${Y.join("、")}`}estimateTokenCount($,Z,J,Y){let U=$.length+Z.join(" ").length;if(Y)U+=Y.length;for(let X of J)U+=X.content.length;return Math.ceil(U/4)}extractContext($,Z,J){let Y=$.indexOf(Z);if(Y===-1)return null;let U=Math.max(0,Y-J/2),X=Math.min($.length,Y+J/2);return $.substring(U,X).trim()}extractQuestions($){let Z=[],J=["?","?","如何","怎么","什么","为什么"],Y=$.split(/[。!.!]/);for(let U of Y)if(J.some((X)=>U.includes(X))){let X=U.trim();if(X.length>5&&X.length<100)Z.push(X)}return Z.slice(0,3)}extractRequests($){let Z=[],J=["请","帮我","需要","想要","希望","能否"],Y=$.split(/[。!.!]/);for(let U of Y)if(J.some((X)=>U.includes(X))){let X=U.trim();if(X.length>5&&X.length<100)Z.push(X)}return Z.slice(0,3)}extractSolutions($){let Z=[],J=["可以","建议","推荐","应该","最好","解决方案"],Y=$.split(/[。!.!]/);for(let U of Y)if(J.some((X)=>U.includes(X))){let X=U.trim();if(X.length>10&&X.length<150)Z.push(X)}return Z.slice(0,3)}summarizeToolUsage($){let Z=[],J=$.filter((Y)=>Date.now()-Y.timestamp<1800000);if(J.length>0){let Y=new Map;J.forEach((U)=>{let X=Y.get(U.name)||[];X.push(U),Y.set(U.name,X)});for(let[U,X]of Array.from(Y.entries())){let H=X.filter((Q)=>Q.status==="success").length;Z.push(`${U}(${X.length}次,${H}成功)`)}}return Z.slice(0,5)}shouldCompress($,Z){return this.estimateCurrentTokens($)>Z*0.8}estimateCurrentTokens($){let J=$.layers.conversation.messages.reduce((Y,U)=>Y+U.content.length,0);return Math.ceil(J/4)}}class d${defaultOptions;constructor($){this.defaultOptions={maxTokens:32000,maxMessages:50,timeWindow:86400000,priority:1,includeTools:!0,includeWorkspace:!0,...$}}filter($,Z){let J={...this.defaultOptions,...Z},Y={layers:{system:$.layers.system,session:$.layers.session,conversation:this.filterConversation($.layers.conversation,J),tool:J.includeTools?this.filterTools($.layers.tool,J):{recentCalls:[],toolStates:{},dependencies:{}},workspace:J.includeWorkspace?$.layers.workspace:{currentFiles:[],recentFiles:[],environment:{}}},metadata:{...$.metadata,lastUpdated:Date.now()}};return Y.metadata.totalTokens=this.estimateTokens(Y),Y}filterConversation($,Z){let J=[...$.messages];if(Z.timeWindow>0){let Y=Date.now()-Z.timeWindow;J=J.filter((U)=>U.timestamp>=Y||U.role==="system")}if(Z.priority>1)J=this.filterByPriority(J,Z.priority);if(Z.maxMessages>0)J=this.limitMessages(J,Z.maxMessages);if(Z.maxTokens>0)J=this.limitByTokens(J,Z.maxTokens);return{messages:J,summary:$.summary,topics:this.updateTopics(J,$.topics),lastActivity:$.lastActivity}}filterTools($,Z){let J=[...$.recentCalls];if(Z.timeWindow>0){let W=Date.now()-Z.timeWindow;J=J.filter((z)=>z.timestamp>=W)}let Y=J.filter((W)=>W.status==="success"),U=J.filter((W)=>W.status==="error"),X=Math.min(20,Y.length),H=Math.min(10,U.length);return{recentCalls:[...Y.slice(-X),...U.slice(-H)].sort((W,z)=>W.timestamp-z.timestamp),toolStates:$.toolStates,dependencies:$.dependencies}}filterByPriority($,Z){return $.filter((J)=>{if(J.role==="system")return!0;return this.calculateMessagePriority(J)>=Z})}calculateMessagePriority($){let Z=1;if($.role==="system")Z+=3;else if($.role==="assistant")Z+=1;let J=$.content.toLowerCase();if(["错误","警告","重要","关键","问题","解决"].some((X)=>J.includes(X)))Z+=2;if(J.includes("```")||J.includes("function")||J.includes("class"))Z+=1;let U=(Date.now()-$.timestamp)/3600000;if(U<1)Z+=2;else if(U<6)Z+=1;return Z}limitMessages($,Z){if($.length<=Z)return $;let J=$.filter((H)=>H.role==="system"),Y=$.filter((H)=>H.role!=="system"),U=Z-J.length,X=U>0?Y.slice(-U):[];return[...J,...X].sort((H,Q)=>H.timestamp-Q.timestamp)}limitByTokens($,Z){if(Z<=0)return $;let J=0,Y=[];for(let U=$.length-1;U>=0;U--){let X=$[U],H=this.estimateMessageTokens(X);if(X.role==="system")if(J+H<=Z)Y.unshift(X),J+=H;else{let Q=this.compressMessage(X,Z-J);Y.unshift(Q),J+=this.estimateMessageTokens(Q)}else if(J+H<=Z)Y.unshift(X),J+=H;else break}return Y.sort((U,X)=>U.timestamp-X.timestamp)}estimateMessageTokens($){return Math.ceil($.content.length/4)}compressMessage($,Z){let J=Z*4;if($.content.length<=J)return $;let Y=$.content.substring(0,J-3)+"...";return{...$,content:Y,metadata:{...$.metadata,compressed:!0,originalLength:$.content.length}}}updateTopics($,Z){let J=new Set(Z);for(let Y of $)this.extractTopicsFromMessage(Y).forEach((X)=>J.add(X));return Array.from(J).slice(0,10)}extractTopicsFromMessage($){let Z=$.content.toLowerCase(),J=[];return["项目","功能","模块","组件","服务","接口","数据库","前端","后端","算法","架构","设计"].forEach((U)=>{if(Z.includes(U))J.push(U)}),J}estimateTokens($){let Z=0;for(let Y of $.layers.conversation.messages)Z+=this.estimateMessageTokens(Y);let J=JSON.stringify($.layers.system);if(Z+=Math.ceil(J.length/4),$.layers.tool.recentCalls.length>0){let Y=JSON.stringify($.layers.tool);Z+=Math.ceil(Y.length/8)}return Z}static createPresets(){return{lightweight:new d$({maxTokens:1000,maxMessages:10,timeWindow:7200000,includeTools:!1,includeWorkspace:!1}),standard:new d$({maxTokens:4000,maxMessages:30,timeWindow:43200000,includeTools:!0,includeWorkspace:!0}),comprehensive:new d$({maxTokens:8000,maxMessages:100,timeWindow:86400000,includeTools:!0,includeWorkspace:!0}),debug:new d$({maxTokens:2000,maxMessages:20,timeWindow:21600000,priority:2,includeTools:!0,includeWorkspace:!1})}}}class q6{cache=new Map;maxSize;defaultTTL;constructor($=100,Z=300000){this.maxSize=$,this.defaultTTL=Z}set($,Z,J){let Y=Date.now(),U={data:Z,timestamp:Y,accessCount:0,lastAccess:Y,ttl:J||this.defaultTTL};if(this.cache.size>=this.maxSize&&!this.cache.has($))this.evictLeastUsed();this.cache.set($,U)}get($){let Z=this.cache.get($);if(!Z)return null;let J=Date.now();if(J-Z.timestamp>Z.ttl)return this.cache.delete($),null;return Z.accessCount++,Z.lastAccess=J,Z.data}has($){let Z=this.cache.get($);if(!Z)return!1;if(Date.now()-Z.timestamp>Z.ttl)return this.cache.delete($),!1;return!0}delete($){return this.cache.delete($)}clear(){this.cache.clear()}size(){return this.cleanExpired(),this.cache.size}cacheMessageSummary($,Z,J){let Y=`summary:${$}:${Z.length}`;this.set(Y,{summary:J,messageCount:Z.length,lastMessage:Z[Z.length-1]?.timestamp||0},600000)}getMessageSummary($,Z){let J=`summary:${$}:${Z}`;return this.get(J)}cacheToolResult($,Z,J){let Y=this.hashInput(Z),U=`tool:${$}:${Y}`;this.set(U,J,1800000)}getToolResult($,Z){let J=this.hashInput(Z),Y=`tool:${$}:${J}`;return this.get(Y)}cacheCompressedContext($,Z){let J=`compressed:${$}`;this.set(J,Z,900000)}getCompressedContext($){let Z=`compressed:${$}`;return this.get(Z)}getStats(){this.cleanExpired();let $=0,Z=0,J=[];for(let[Y,U]of Array.from(this.cache.entries()))$+=U.accessCount,Z+=this.estimateItemSize(U),J.push({key:Y,accessCount:U.accessCount,lastAccess:U.lastAccess});return J.sort((Y,U)=>U.accessCount-Y.accessCount),{size:this.cache.size,maxSize:this.maxSize,hitRate:$>0?$/($+this.cache.size):0,memoryUsage:Z,topKeys:J.slice(0,10)}}cleanExpired(){let $=Date.now(),Z=[];for(let[J,Y]of Array.from(this.cache.entries()))if($-Y.timestamp>Y.ttl)Z.push(J);Z.forEach((J)=>this.cache.delete(J))}evictLeastUsed(){let $=null,Z=1/0,J=Date.now();for(let[Y,U]of Array.from(this.cache.entries())){let X=1/(J-U.lastAccess+1),H=U.accessCount,Q=X*H;if(Q<Z)Z=Q,$=Y}if($)this.cache.delete($)}hashInput($){let Z=JSON.stringify($),J=0;for(let Y=0;Y<Z.length;Y++){let U=Z.charCodeAt(Y);J=(J<<5)-J+U,J=J&J}return Math.abs(J).toString(36)}estimateItemSize($){try{return JSON.stringify($).length*2}catch{return 1000}}setTTL($,Z){let J=this.cache.get($);if(J)return J.ttl=Z,J.timestamp=Date.now(),!0;return!1}getRemainingTTL($){let Z=this.cache.get($);if(!Z)return-1;let J=Z.ttl-(Date.now()-Z.timestamp);return Math.max(0,J)}warmup($){$.forEach(({key:Z,value:J,ttl:Y})=>{this.set(Z,J,Y)})}}class F6{contextData=null;maxSize;accessLog=new Map;constructor($=1000){this.maxSize=$}setContext($){this.contextData={...$},this.contextData.metadata.lastUpdated=Date.now(),this.recordAccess("context")}getContext(){if(this.contextData)this.recordAccess("context");return this.contextData}addMessage($){if(!this.contextData)throw Error("上下文数据未初始化");this.contextData.layers.conversation.messages.push($),this.contextData.layers.conversation.lastActivity=Date.now(),this.contextData.metadata.lastUpdated=Date.now(),this.enforceMemoryLimit(),this.recordAccess("messages")}getRecentMessages($=10){if(!this.contextData)return[];let Z=this.contextData.layers.conversation.messages;return this.recordAccess("messages"),Z.slice(-$)}addToolCall($){if(!this.contextData)throw Error("上下文数据未初始化");if(this.contextData.layers.tool.recentCalls.push($),this.contextData.metadata.lastUpdated=Date.now(),this.contextData.layers.tool.recentCalls.length>50)this.contextData.layers.tool.recentCalls=this.contextData.layers.tool.recentCalls.slice(-25);this.recordAccess("tools")}updateToolState($,Z){if(!this.contextData)throw Error("上下文数据未初始化");this.contextData.layers.tool.toolStates[$]=Z,this.contextData.metadata.lastUpdated=Date.now(),this.recordAccess("tools")}getToolState($){if(!this.contextData)return null;return this.recordAccess("tools"),this.contextData.layers.tool.toolStates[$]}updateWorkspace($){if(!this.contextData)throw Error("上下文数据未初始化");Object.assign(this.contextData.layers.workspace,$),this.contextData.metadata.lastUpdated=Date.now(),this.recordAccess("workspace")}clear(){this.contextData=null,this.accessLog.clear()}getMemoryInfo(){if(!this.contextData)return{hasData:!1,messageCount:0,toolCallCount:0,lastUpdated:null};return{hasData:!0,messageCount:this.contextData.layers.conversation.messages.length,toolCallCount:this.contextData.layers.tool.recentCalls.length,lastUpdated:this.contextData.metadata.lastUpdated}}recordAccess($){this.accessLog.set($,Date.now())}enforceMemoryLimit(){if(!this.contextData)return;let $=this.contextData.layers.conversation.messages;if($.length>this.maxSize){let Z=Math.floor(this.maxSize*0.8);this.contextData.layers.conversation.messages=$.slice(-Z)}}getMemoryUsage(){if(!this.contextData)return 0;return JSON.stringify(this.contextData).length}}import*as o0 from"node:fs/promises";import*as N8 from"node:path";import{nanoid as P0}from"nanoid";class m${sessionId;projectPath;static instances=new Map;store;subscribers=new Set;highestSeq=0;constructor($,Z){this.sessionId=$;this.projectPath=Z;this.store=new a0(S0(Z,$))}static for($,Z){let J=`${Z}\x00${$}`,Y=m$.instances.get(J);if(!Y)Y=new m$($,Z),m$.instances.set(J,Y);return Y}static release($,Z){m$.instances.delete(`${Z}\x00${$}`)}get lastSeq(){return this.highestSeq}async commit($){let Z=await this.store.append($);return this.record(Z),Z}async commitBatch($){if($.length===0)return[];let Z=await this.store.appendBatch($);for(let J of Z)this.record(J);return Z}emitDelta($){for(let Z of this.subscribers)Z.onDelta?.($);Z0.publish({sessionId:this.sessionId,projectPath:this.projectPath},"delta",{delta:$})}subscribe($,Z){if(this.subscribers.add($),Z?.fromSeq!==void 0)this.replay($,Z.fromSeq);return()=>{this.subscribers.delete($)}}async replay($,Z){let J=await this.store.readFromSeq(Z);for(let Y of J)$.onCommitted(Y)}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;for(let Z of this.subscribers)Z.onCommitted($);Z0.publish({sessionId:this.sessionId,projectPath:this.projectPath},`committed.${$.type}`,{event:$},$.seq)}}class D6{projectPath;maxSessions;version;constructor($=N(),Z=100,J=B2()){this.projectPath=$,this.maxSessions=Z,this.version=J}createEvent($,Z,J){return{id:P0(),sessionId:Z,projectPath:this.projectPath,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,gitBranch:A8(this.projectPath),version:this.version,data:J}}log($){return m$.for($,this.projectPath)}async ensureSessionCreated($,Z){let J=S0(this.projectPath,$);if((await new a0(J).readAll()).length>0)return;let X=new Date().toISOString(),H={sessionId:$,rootId:Z?.parentSessionId??$,parentId:Z?.parentSessionId,relationType:Z?"subagent":void 0,resumedFrom:Z?.resumedFrom,rootAgentId:Z?.rootAgentId,resumeDepth:Z?.resumeDepth,title:void 0,status:"running",taskStatus:Z?"running":"queued",taskFailure:null,agentType:Z?.subagentType,model:void 0,permission:void 0,createdAt:X,updatedAt:X},Q=this.createEvent("session_created",$,H);await this.log($).commit(Q)}buildCompactionMetadata($){let Z={trigger:$.trigger,preTokens:$.preTokens};if($.postTokens!==void 0)Z.postTokens=$.postTokens;if($.filesIncluded)Z.filesIncluded=$.filesIncluded;return Z}async initialize(){try{let $=t$(this.projectPath);await o0.mkdir($,{recursive:!0,mode:493}),console.log(`[PersistentStore] 初始化存储目录: ${$}`)}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,Z,J,Y=null,U,X,H){try{await this.ensureSessionCreated($,X);let Q=new Date().toISOString(),W=P0(),z={messageId:W,role:Z,parentMessageId:Y??void 0,inboxMessageId:U?.inboxMessageId,createdAt:Q,model:U?.model,usage:U?.usage,metadata:U?JSON.parse(JSON.stringify(U)):void 0},V=this.createEvent("message_created",$,z),B=Z==="assistant"&&H?.trim()?[this.createEvent("part_created",$,{partId:P0(),messageId:W,partType:"reasoning",payload:{text:H},createdAt:Q})]:[],K=typeof J==="string"?[this.createEvent("part_created",$,{partId:P0(),messageId:W,partType:"text",payload:{text:J},createdAt:Q})]:J.map((G)=>this.createEvent("part_created",$,{partId:P0(),messageId:W,partType:G.type==="text"?"text":"image",payload:G.type==="text"?{text:G.text}:{mimeType:LU(G.image_url.url)??"image/png",dataUrl:G.image_url.url},createdAt:Q}));return await this.log($).commitBatch([V,...B,...K]),W}catch(Q){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,Q),Q}}async acknowledgeInboxMessages($,Z){if(Z.length===0)return;await this.ensureSessionCreated($);let J=new Date().toISOString();await this.log($).commit(this.createEvent("inbox_acknowledged",$,{messageIds:[...Z],acknowledgedAt:J}))}async saveToolUse($,Z,J,Y=null,U){try{await this.ensureSessionCreated($,U);let X=new Date().toISOString(),H=Y??P0(),Q=[];if(!Y){let V={messageId:H,role:"assistant",parentMessageId:void 0,createdAt:X};Q.push(this.createEvent("message_created",$,V))}let W=P0(),z={partId:W,messageId:H,partType:"tool_call",payload:{toolCallId:W,toolName:Z,input:J},createdAt:X};if(Q.push(this.createEvent("part_created",$,z)),Z==="Task"&&J&&typeof J==="object"){let V=J,B=typeof V.subagent_session_id==="string"?V.subagent_session_id:void 0,K=typeof V.subagent_type==="string"?V.subagent_type:void 0;if(B&&K){let G={partId:P0(),messageId:H,partType:"subtask_ref",payload:{childSessionId:B,agentType:K,status:"running",summary:typeof V.description==="string"?V.description:"",startedAt:X},createdAt:X};Q.push(this.createEvent("part_created",$,G))}}return await this.log($).commitBatch(Q),W}catch(X){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,X),X}}async saveToolResult($,Z,J,Y,U=null,X,H,Q,W){try{await this.ensureSessionCreated($,H);let z=new Date().toISOString(),V=U??P0(),B=[];if(!U){let G={messageId:V,role:"assistant",parentMessageId:void 0,createdAt:z};B.push(this.createEvent("message_created",$,G))}let K={partId:Z,messageId:V,partType:"tool_result",payload:{toolCallId:Z,toolName:J,output:Y,error:X??null,...W===void 0?{}:{metadata:W}},createdAt:z};if(B.push(this.createEvent("part_created",$,K)),Q){let G=Q.subagentStatus==="running"?null:z,O={partId:P0(),messageId:V,partType:"subtask_ref",payload:{childSessionId:Q.subagentSessionId,agentType:Q.subagentType,description:Q.subagentDescription??"",status:Q.subagentStatus,summary:Q.subagentSummary??"",resumedFrom:Q.subagentResumedFrom??null,rootAgentId:Q.subagentRootId??Q.subagentSessionId,resumeDepth:Q.subagentResumeDepth??0,verificationVerdict:Q.verificationVerdict??null,startedAt:z,finishedAt:G},createdAt:z};B.push(this.createEvent("part_created",$,O))}return await this.log($).commitBatch(B),Z}catch(z){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,z),z}}async saveCompaction($,Z,J,Y=null){try{await this.ensureSessionCreated($);let U=new Date().toISOString(),X=P0(),H={messageId:X,role:"system",parentMessageId:Y??void 0,createdAt:U},Q=this.buildCompactionMetadata(J),W={partId:P0(),messageId:X,partType:"summary",payload:{text:Z,metadata:Q},createdAt:U},z=[this.createEvent("message_created",$,H),this.createEvent("part_created",$,W)];return await this.log($).commitBatch(z),X}catch(U){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,U),U}}async initSession($,Z){await this.ensureSessionCreated($,Z)}async loadEvents($){try{let Z=S0(this.projectPath,$),Y=await new a0(Z).readAll();return Y.length>0?g$(Y):null}catch{return null}}async loadSession($){try{let Z=S0(this.projectPath,$),J=new a0(Z),Y=g$(await J.readAll());if(Y.length===0)return null;let U=Y.find((X)=>X.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(U?.timestamp??Y[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let Z=S0(this.projectPath,$),J=new a0(Z),Y=g$(await J.readAll());if(Y.length===0)return null;let U=new Map;for(let W of Y){if(W.type==="message_created")U.set(W.data.messageId,{id:W.data.messageId,role:W.data.role,content:"",timestamp:new Date(W.timestamp).getTime()});if(W.type==="part_created"&&W.data.partType==="text"){let z=U.get(W.data.messageId);if(z){let V=W.data.payload;z.content=V.text??""}}if(W.type==="part_created"&&W.data.partType==="image"){let z=U.get(W.data.messageId);if(z)z.content=z.content?`${z.content}
|
|
642
|
-
[Image]`:"[Image]"}}let X=Array.from(U.values()),H=Y[Y.length-1],Q=new Date(H.timestamp).getTime();return{messages:X,topics:[],lastActivity:Q}}catch{return null}}async listSessions(){try{let $=t$(this.projectPath);return(await o0.readdir($)).filter((J)=>J.endsWith(".jsonl")).map((J)=>J.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let Z=S0(this.projectPath,$),J=new a0(Z);if(!(await J.getStats()).exists)return null;let U=await J.readAll();if(U.length===0)return null;let X=g$(U),H=U[U.length-1],Q=X.filter((W)=>W.type==="message_created"&&["user","assistant"].includes(W.data.role)).length;return{sessionId:$,lastActivity:new Date(H.timestamp).getTime(),messageCount:Q,topics:[]}}catch{return null}}async deleteSession($){try{let Z=S0(this.projectPath,$);await new a0(Z).delete(),await o0.unlink(e$(this.projectPath,$)).catch((Y)=>{if(Y.code!=="ENOENT")throw Y});try{let{getProjectionDb:Y,removeSessionFromProjection:U}=await import("./chunk-t8x2qpe2.js"),X=await Y();if(X)U(X,$,this.projectPath)}catch{}}catch(Z){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,Z)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let Y=(await Promise.all($.map((U)=>this.getSessionSummary(U)))).filter((U)=>U!==null).sort((U,X)=>X.lastActivity-U.lastActivity).slice(this.maxSessions).map((U)=>U.sessionId);await Promise.all(Y.map((U)=>this.deleteSession(U))),console.log(`[PersistentStore] 已清理 ${Y.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){try{let $=await this.listSessions(),Z=0;for(let J of $){let Y=S0(this.projectPath,J),X=await new a0(Y).getStats();Z+=X.size}return{totalSessions:$.length,totalSize:Z,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=t$(this.projectPath);await o0.mkdir($,{recursive:!0,mode:493});let Z=N8.join($,".health-check");return await o0.writeFile(Z,"test","utf-8"),await o0.unlink(Z),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return L8()}}function LU($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}class j1{memory;persistent;cache;compressor;filter;options;currentSessionId=null;initialized=!1;get persistentStore(){return this.persistent}constructor($={}){let Z=$.storage?.persistentPath||q0();this.options={projectPath:$.projectPath||N(),storage:{maxMemorySize:1000,persistentPath:Z,cacheSize:100,compressionEnabled:!0,...$.storage},defaultFilter:{maxTokens:32000,maxMessages:50,timeWindow:86400000,...$.defaultFilter},compressionThreshold:$.compressionThreshold||6000,enableVectorSearch:$.enableVectorSearch||!1},this.memory=new F6(this.options.storage.maxMemorySize),this.persistent=new D6(this.options.projectPath,100),this.cache=new q6(this.options.storage.cacheSize,300000),this.compressor=new E6,this.filter=new d$(this.options.defaultFilter)}async initialize(){if(this.initialized)return;try{if(await this.persistent.initialize(),!(await this.persistent.checkStorageHealth()).isAvailable)console.warn("警告:持久化存储不可用,将仅使用内存存储");this.initialized=!0,console.log("上下文管理器初始化完成")}catch($){throw console.error("上下文管理器初始化失败:",$),$}}async createSession($,Z={},J={}){let Y=J.sessionId||this.generateSessionId(),U=Date.now(),X={layers:{system:await this.createSystemContext(),session:{sessionId:Y,userId:$,preferences:Z,configuration:J,startTime:U},conversation:{messages:[],topics:[],lastActivity:U},tool:{recentCalls:[],toolStates:{},dependencies:{}},workspace:await this.createWorkspaceContext()},metadata:{totalTokens:0,priority:1,lastUpdated:U}};return this.memory.setContext(X),await this.persistent.initSession(Y),this.currentSessionId=Y,console.log(`新会话已创建: ${Y}`),Y}async loadSession($){try{let Z=this.memory.getContext();if(!Z||Z.layers.session.sessionId!==$){let J=await this.persistent.loadEvents($);if(!J||J.length===0)return!1;if(Z=new O6().assembleContextData(J,await this.createSystemContext(),await this.createWorkspaceContext()),!Z)return!1;this.memory.setContext(Z)}return this.currentSessionId=$,console.log(`会话已加载: ${$}`),!0}catch(Z){return console.error("加载会话失败:",Z),!1}}async addMessage($,Z,J){if(!this.currentSessionId)throw Error("没有活动会话");let Y={id:this.generateMessageId(),role:$,content:Z,timestamp:Date.now(),metadata:J};this.memory.addMessage(Y);let U=this.memory.getContext();if(U&&this.shouldCompress(U))await this.compressCurrentContext();this.saveCurrentSessionAsync()}async addToolCall($){if(!this.currentSessionId)throw Error("没有活动会话");if(this.memory.addToolCall($),$.status==="success"&&$.output)this.cache.cacheToolResult($.name,$.input,$.output);this.saveCurrentSessionAsync()}async saveMessage($,Z,J,Y=null,U,X,H){return this.persistent.saveMessage($,Z,J,Y,U,X,H)}async saveToolUse($,Z,J,Y=null,U){return this.persistent.saveToolUse($,Z,J,Y,U)}async saveToolResult($,Z,J,Y,U=null,X,H,Q,W){return this.persistent.saveToolResult($,Z,J,Y,U,X,H,Q,W)}async saveCompaction($,Z,J,Y=null){return this.persistent.saveCompaction($,Z,J,Y)}updateToolState($,Z){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateToolState($,Z)}updateWorkspace($){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateWorkspace($)}async getFormattedContext($){let Z=this.memory.getContext();if(!Z)throw Error("没有可用的上下文数据");let J=this.filter.filter(Z,$),Y=this.shouldCompress(J),U;if(Y){let X=this.hashContext(J);if(U=this.cache.getCompressedContext(X)??void 0,!U)U=await this.compressor.compress(J),this.cache.cacheCompressedContext(X,U)}return{context:J,compressed:U,tokenCount:U?U.tokenCount:J.metadata.totalTokens}}async searchSessions($,Z=10){let J=await this.persistent.listSessions(),Y=[];for(let U of J){let X=await this.persistent.getSessionSummary(U);if(X){let H=this.calculateRelevance($,X.topics);if(H>0)Y.push({sessionId:U,summary:`${X.messageCount}条消息,主题:${X.topics.join("、")}`,lastActivity:X.lastActivity,relevanceScore:H})}}return Y.sort((U,X)=>X.relevanceScore-U.relevanceScore).slice(0,Z)}getCachedToolResult($,Z){return this.cache.getToolResult($,Z)}async getStats(){let[$,Z,J]=await Promise.all([Promise.resolve(this.memory.getMemoryInfo()),Promise.resolve(this.cache.getStats()),this.persistent.getStorageStats()]);return{currentSession:this.currentSessionId,memory:$,cache:Z,storage:J}}async cleanup(){if(this.currentSessionId)await this.saveCurrentSession();this.memory.clear(),this.cache.clear(),await this.persistent.cleanupOldSessions(),this.currentSessionId=null,console.log("上下文管理器资源清理完成")}generateSessionId(){return z$()}generateMessageId(){return NU()}async createSystemContext(){return{role:"AI助手",capabilities:["对话","工具调用","代码生成","文档分析"],tools:["文件操作","Git操作","代码分析"],version:"1.0.0"}}async createWorkspaceContext(){try{let $=this.options.projectPath;return{projectPath:$,currentFiles:[],recentFiles:[],environment:{nodeVersion:process.version,platform:process.platform,cwd:$}}}catch($){return{currentFiles:[],recentFiles:[],environment:{}}}}shouldCompress($){return $.metadata.totalTokens>this.options.compressionThreshold}async compressCurrentContext(){let $=this.memory.getContext();if(!$)return;let Z=await this.compressor.compress($);$.layers.conversation.summary=Z.summary,this.memory.setContext($)}async saveCurrentSession(){}saveCurrentSessionAsync(){this.saveCurrentSession().catch(($)=>{console.warn("异步保存会话失败:",$)})}hashContext($){let Z=JSON.stringify({messageCount:$.layers.conversation.messages.length,lastMessage:$.layers.conversation.messages[$.layers.conversation.messages.length-1]?.id,toolCallCount:$.layers.tool.recentCalls.length});return b8.createHash("md5").update(Z).digest("hex")}calculateRelevance($,Z){let J=$.toLowerCase(),Y=0;for(let U of Z)if(J.includes(U.toLowerCase())||U.toLowerCase().includes(J))Y+=1;return Y}}class T1{chatService;contextManager;memoryAdapter;constructor($,Z,J){this.chatService=$,this.contextManager=Z||new j1({projectPath:J||N()}),this.memoryAdapter=this.createMemoryAdapter()}createMemoryAdapter(){let $=[];return{getMessages:()=>[...$],addMessage:(Z)=>{$.push(Z)},clearContext:()=>{$.length=0},getContextSize:()=>$.length}}getContextManager(){return this.contextManager}getMemoryAdapter(){return this.memoryAdapter}async executeTask($){let Z=[{role:"user",content:$.prompt}],J=await this.chatService.chat(Z);return{taskId:$.id,content:J.content,metadata:{taskType:$.type}}}}class S8 extends Error{constructor($){super(`Task admission queue is full (max ${$})`);this.name="TaskAdmissionQueueFullError"}}class P8 extends Error{constructor($){super(`Task already owns an admission slot or queue entry: ${$}`);this.name="TaskAdmissionConflictError"}}class M1 extends Error{constructor($="Task admission was cancelled"){super($);this.name="TaskAdmissionCancelledError"}}class k8{maxConcurrent=3;maxQueued=100;inFlight=0;queue=[];activeKeys=new Set;explicitlyConfigured=!1;admit($){if(this.validateLimits($.maxConcurrent,$.maxQueued),!this.explicitlyConfigured)this.applyConfiguration($.maxConcurrent,$.maxQueued);if(!$.key.trim())throw Error("Task admission key must not be blank");if(this.activeKeys.has($.key))throw new P8($.key);if(this.inFlight>=this.maxConcurrent&&this.queue.length>=this.maxQueued)throw new S8(this.maxQueued);let Z,J,Y=new Promise((Q,W)=>{Z=Q,J=W});Y.catch(()=>{return});let U={key:$.key,signal:$.signal,onUpdate:$.onUpdate,resolve:Z,reject:J,snapshot:this.snapshot("queued",1),settled:!1},X=(Q)=>{this.cancelPending(U,new M1(Q||void 0))},H={ready:Y,getSnapshot:()=>({...U.snapshot}),cancel:X,release:()=>{if(U.permit)U.permit.release();else X("Task admission released before execution")}};if(this.activeKeys.add($.key),$.signal?.aborted)return X(String($.signal.reason||"Task admission was cancelled")),H;if($.signal)U.abortListener=()=>X(String($.signal?.reason||"Task admission was cancelled")),$.signal.addEventListener("abort",U.abortListener,{once:!0});if(this.inFlight<this.maxConcurrent)this.startPending(U);else this.queue.push(U),this.publishQueueSnapshots();return H}configure($,Z){this.validateLimits($,Z),this.explicitlyConfigured=!0,this.applyConfiguration($,Z)}applyConfiguration($,Z){this.maxConcurrent=$,this.maxQueued=Z,this.drain(),this.publishQueueSnapshots()}getStats(){return{inFlight:this.inFlight,queued:this.queue.length,maxConcurrent:this.maxConcurrent,maxQueued:this.maxQueued}}resetForTests(){for(let $ of[...this.queue])this.cancelPending($,new M1("Scheduler reset"));this.queue.length=0,this.activeKeys.clear(),this.inFlight=0,this.maxConcurrent=3,this.maxQueued=100,this.explicitlyConfigured=!1}startPending($){if($.settled)return;this.detachAbort($),this.inFlight++;let Z=!1,J={release:()=>{if(Z)return;Z=!0,$.settled=!0,this.detachAbort($),this.activeKeys.delete($.key),this.inFlight=Math.max(0,this.inFlight-1),this.drain(),this.publishQueueSnapshots()}};$.permit=J,$.snapshot=this.snapshot("running"),this.publish($),$.resolve(J),this.publishQueueSnapshots()}cancelPending($,Z){if($.settled)return;if($.permit)return;let J=this.queue.indexOf($);if(J>=0)this.queue.splice(J,1);$.settled=!0,this.detachAbort($),this.activeKeys.delete($.key),$.reject(Z),this.publishQueueSnapshots()}drain(){while(this.inFlight<this.maxConcurrent&&this.queue.length>0){let $=this.queue.shift();if($&&!$.settled)this.startPending($)}}publishQueueSnapshots(){for(let[$,Z]of this.queue.entries())Z.snapshot=this.snapshot("queued",$+1),this.publish(Z)}snapshot($,Z){return{state:$,...Z!==void 0?{queuePosition:Z}:{},queueDepth:this.queue.length,inFlight:this.inFlight,maxConcurrent:this.maxConcurrent,maxQueued:this.maxQueued}}publish($){try{$.onUpdate?.({...$.snapshot})}catch{}}detachAbort($){if($.abortListener&&$.signal)$.signal.removeEventListener("abort",$.abortListener);$.abortListener=void 0}validateLimits($,Z){if(!f8($))throw Error(`maxConcurrent must be an integer between ${j8} and ${T8}`);if(!R8(Z))throw Error(`maxQueued must be an integer between ${M8} and ${C8}`)}}var $1=new k8;var y=u("Agent");class O0{config;runtimeOptions;isInitialized=!1;activeTask;toolExecutor;chatService;executionEngine;attachmentCollector;activeSkillContext;currentModelMaxContextTokens;currentModelId;sessionRuntime;legacyMcpRegistry;agentResources;subagentRegistry;constructor($,Z={},J,Y){this.config=$,this.runtimeOptions=Z,this.toolExecutor=J||this.createDefaultToolExecutor(),this.sessionRuntime=Y,this.agentResources=Y?.getAgentResources(),this.subagentRegistry=this.agentResources?.subagents}createDefaultToolExecutor(){let $=new A$,Z={...this.config.permissions,...this.runtimeOptions.permissions},J=this.runtimeOptions.permissionMode??this.config.permissionMode??"default";return new b1($,{permissionConfig:Z,permissionMode:J,maxHistorySize:1000,toolWhitelist:this.runtimeOptions.toolWhitelist,toolBlacklist:this.runtimeOptions.toolBlacklist})}resolveModelConfig($){let Z=$&&$!=="inherit"?$:void 0,J=Z?w6(Z):L$();if(!J)throw Error(`模型配置未找到: ${Z??"current"}`);return J}async applyModelConfig($,Z){let J=v8(),Y=w0($,this.config,J?"auto":"off");if(this.log(`${Z} ${Y.displayName} (${$.model})`),Y.model.reasoning&&!J)this.log("模型支持 Thinking,但用户未开启(按 Tab 开启)");else if(Y.chat.reasoningEnabled)this.log("Thinking 模式已启用,启用 reasoning_content 支持");this.currentModelMaxContextTokens=Y.model.contextWindow,this.chatService=await _2(Y.chat);let U=this.executionEngine?.getContextManager();this.executionEngine=new T1(this.chatService,U),this.currentModelId=$.id}async switchModelIfNeeded($){if(this.sessionRuntime){await this.sessionRuntime.refresh({modelId:$}),this.syncRuntimeState();return}if(!$||$===this.currentModelId)return;let Z=w6($);if(!Z){this.log(`Warning: 模型配置未找到: ${$}`);return}await this.applyModelConfig(Z,"切换模型")}async switchModel($){if(!this.isInitialized)throw Error("Agent未初始化");await this.switchModelIfNeeded($)}static async create($={}){if($.sessionId)throw Error("Agent.create() does not accept sessionId. Create a SessionRuntime explicitly and use Agent.createWithRuntime().");if(await K2(),Z1().length===0)throw Error(`没有可用的模型配置
|
|
642
|
+
[Image]`:"[Image]"}}let X=Array.from(U.values()),H=Y[Y.length-1],Q=new Date(H.timestamp).getTime();return{messages:X,topics:[],lastActivity:Q}}catch{return null}}async listSessions(){try{let $=t$(this.projectPath);return(await o0.readdir($)).filter((J)=>J.endsWith(".jsonl")).map((J)=>J.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let Z=S0(this.projectPath,$),J=new a0(Z);if(!(await J.getStats()).exists)return null;let U=await J.readAll();if(U.length===0)return null;let X=g$(U),H=U[U.length-1],Q=X.filter((W)=>W.type==="message_created"&&["user","assistant"].includes(W.data.role)).length;return{sessionId:$,lastActivity:new Date(H.timestamp).getTime(),messageCount:Q,topics:[]}}catch{return null}}async deleteSession($){try{let Z=S0(this.projectPath,$);await new a0(Z).delete(),await o0.unlink(e$(this.projectPath,$)).catch((Y)=>{if(Y.code!=="ENOENT")throw Y});try{let{getProjectionDb:Y,removeSessionFromProjection:U}=await import("./chunk-t8x2qpe2.js"),X=await Y();if(X)U(X,$,this.projectPath)}catch{}}catch(Z){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,Z)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let Y=(await Promise.all($.map((U)=>this.getSessionSummary(U)))).filter((U)=>U!==null).sort((U,X)=>X.lastActivity-U.lastActivity).slice(this.maxSessions).map((U)=>U.sessionId);await Promise.all(Y.map((U)=>this.deleteSession(U))),console.log(`[PersistentStore] 已清理 ${Y.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){try{let $=await this.listSessions(),Z=0;for(let J of $){let Y=S0(this.projectPath,J),X=await new a0(Y).getStats();Z+=X.size}return{totalSessions:$.length,totalSize:Z,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=t$(this.projectPath);await o0.mkdir($,{recursive:!0,mode:493});let Z=N8.join($,".health-check");return await o0.writeFile(Z,"test","utf-8"),await o0.unlink(Z),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return L8()}}function LU($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}class T1{memory;persistent;cache;compressor;filter;options;currentSessionId=null;initialized=!1;get persistentStore(){return this.persistent}constructor($={}){let Z=$.storage?.persistentPath||q0();this.options={projectPath:$.projectPath||N(),storage:{maxMemorySize:1000,persistentPath:Z,cacheSize:100,compressionEnabled:!0,...$.storage},defaultFilter:{maxTokens:32000,maxMessages:50,timeWindow:86400000,...$.defaultFilter},compressionThreshold:$.compressionThreshold||6000,enableVectorSearch:$.enableVectorSearch||!1},this.memory=new F6(this.options.storage.maxMemorySize),this.persistent=new D6(this.options.projectPath,100),this.cache=new q6(this.options.storage.cacheSize,300000),this.compressor=new E6,this.filter=new d$(this.options.defaultFilter)}async initialize(){if(this.initialized)return;try{if(await this.persistent.initialize(),!(await this.persistent.checkStorageHealth()).isAvailable)console.warn("警告:持久化存储不可用,将仅使用内存存储");this.initialized=!0,console.log("上下文管理器初始化完成")}catch($){throw console.error("上下文管理器初始化失败:",$),$}}async createSession($,Z={},J={}){let Y=J.sessionId||this.generateSessionId(),U=Date.now(),X={layers:{system:await this.createSystemContext(),session:{sessionId:Y,userId:$,preferences:Z,configuration:J,startTime:U},conversation:{messages:[],topics:[],lastActivity:U},tool:{recentCalls:[],toolStates:{},dependencies:{}},workspace:await this.createWorkspaceContext()},metadata:{totalTokens:0,priority:1,lastUpdated:U}};return this.memory.setContext(X),await this.persistent.initSession(Y),this.currentSessionId=Y,console.log(`新会话已创建: ${Y}`),Y}async loadSession($){try{let Z=this.memory.getContext();if(!Z||Z.layers.session.sessionId!==$){let J=await this.persistent.loadEvents($);if(!J||J.length===0)return!1;if(Z=new O6().assembleContextData(J,await this.createSystemContext(),await this.createWorkspaceContext()),!Z)return!1;this.memory.setContext(Z)}return this.currentSessionId=$,console.log(`会话已加载: ${$}`),!0}catch(Z){return console.error("加载会话失败:",Z),!1}}async addMessage($,Z,J){if(!this.currentSessionId)throw Error("没有活动会话");let Y={id:this.generateMessageId(),role:$,content:Z,timestamp:Date.now(),metadata:J};this.memory.addMessage(Y);let U=this.memory.getContext();if(U&&this.shouldCompress(U))await this.compressCurrentContext();this.saveCurrentSessionAsync()}async addToolCall($){if(!this.currentSessionId)throw Error("没有活动会话");if(this.memory.addToolCall($),$.status==="success"&&$.output)this.cache.cacheToolResult($.name,$.input,$.output);this.saveCurrentSessionAsync()}async saveMessage($,Z,J,Y=null,U,X,H){return this.persistent.saveMessage($,Z,J,Y,U,X,H)}async saveToolUse($,Z,J,Y=null,U){return this.persistent.saveToolUse($,Z,J,Y,U)}async saveToolResult($,Z,J,Y,U=null,X,H,Q,W){return this.persistent.saveToolResult($,Z,J,Y,U,X,H,Q,W)}async saveCompaction($,Z,J,Y=null){return this.persistent.saveCompaction($,Z,J,Y)}updateToolState($,Z){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateToolState($,Z)}updateWorkspace($){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateWorkspace($)}async getFormattedContext($){let Z=this.memory.getContext();if(!Z)throw Error("没有可用的上下文数据");let J=this.filter.filter(Z,$),Y=this.shouldCompress(J),U;if(Y){let X=this.hashContext(J);if(U=this.cache.getCompressedContext(X)??void 0,!U)U=await this.compressor.compress(J),this.cache.cacheCompressedContext(X,U)}return{context:J,compressed:U,tokenCount:U?U.tokenCount:J.metadata.totalTokens}}async searchSessions($,Z=10){let J=await this.persistent.listSessions(),Y=[];for(let U of J){let X=await this.persistent.getSessionSummary(U);if(X){let H=this.calculateRelevance($,X.topics);if(H>0)Y.push({sessionId:U,summary:`${X.messageCount}条消息,主题:${X.topics.join("、")}`,lastActivity:X.lastActivity,relevanceScore:H})}}return Y.sort((U,X)=>X.relevanceScore-U.relevanceScore).slice(0,Z)}getCachedToolResult($,Z){return this.cache.getToolResult($,Z)}async getStats(){let[$,Z,J]=await Promise.all([Promise.resolve(this.memory.getMemoryInfo()),Promise.resolve(this.cache.getStats()),this.persistent.getStorageStats()]);return{currentSession:this.currentSessionId,memory:$,cache:Z,storage:J}}async cleanup(){if(this.currentSessionId)await this.saveCurrentSession();this.memory.clear(),this.cache.clear(),await this.persistent.cleanupOldSessions(),this.currentSessionId=null,console.log("上下文管理器资源清理完成")}generateSessionId(){return z$()}generateMessageId(){return NU()}async createSystemContext(){return{role:"AI助手",capabilities:["对话","工具调用","代码生成","文档分析"],tools:["文件操作","Git操作","代码分析"],version:"1.0.0"}}async createWorkspaceContext(){try{let $=this.options.projectPath;return{projectPath:$,currentFiles:[],recentFiles:[],environment:{nodeVersion:process.version,platform:process.platform,cwd:$}}}catch($){return{currentFiles:[],recentFiles:[],environment:{}}}}shouldCompress($){return $.metadata.totalTokens>this.options.compressionThreshold}async compressCurrentContext(){let $=this.memory.getContext();if(!$)return;let Z=await this.compressor.compress($);$.layers.conversation.summary=Z.summary,this.memory.setContext($)}async saveCurrentSession(){}saveCurrentSessionAsync(){this.saveCurrentSession().catch(($)=>{console.warn("异步保存会话失败:",$)})}hashContext($){let Z=JSON.stringify({messageCount:$.layers.conversation.messages.length,lastMessage:$.layers.conversation.messages[$.layers.conversation.messages.length-1]?.id,toolCallCount:$.layers.tool.recentCalls.length});return b8.createHash("md5").update(Z).digest("hex")}calculateRelevance($,Z){let J=$.toLowerCase(),Y=0;for(let U of Z)if(J.includes(U.toLowerCase())||U.toLowerCase().includes(J))Y+=1;return Y}}class j1{chatService;contextManager;memoryAdapter;constructor($,Z,J){this.chatService=$,this.contextManager=Z||new T1({projectPath:J||N()}),this.memoryAdapter=this.createMemoryAdapter()}createMemoryAdapter(){let $=[];return{getMessages:()=>[...$],addMessage:(Z)=>{$.push(Z)},clearContext:()=>{$.length=0},getContextSize:()=>$.length}}getContextManager(){return this.contextManager}getMemoryAdapter(){return this.memoryAdapter}async executeTask($){let Z=[{role:"user",content:$.prompt}],J=await this.chatService.chat(Z);return{taskId:$.id,content:J.content,metadata:{taskType:$.type}}}}class S8 extends Error{constructor($){super(`Task admission queue is full (max ${$})`);this.name="TaskAdmissionQueueFullError"}}class P8 extends Error{constructor($){super(`Task already owns an admission slot or queue entry: ${$}`);this.name="TaskAdmissionConflictError"}}class M1 extends Error{constructor($="Task admission was cancelled"){super($);this.name="TaskAdmissionCancelledError"}}class k8{maxConcurrent=3;maxQueued=100;inFlight=0;queue=[];activeKeys=new Set;explicitlyConfigured=!1;admit($){if(this.validateLimits($.maxConcurrent,$.maxQueued),!this.explicitlyConfigured)this.applyConfiguration($.maxConcurrent,$.maxQueued);if(!$.key.trim())throw Error("Task admission key must not be blank");if(this.activeKeys.has($.key))throw new P8($.key);if(this.inFlight>=this.maxConcurrent&&this.queue.length>=this.maxQueued)throw new S8(this.maxQueued);let Z,J,Y=new Promise((Q,W)=>{Z=Q,J=W});Y.catch(()=>{return});let U={key:$.key,signal:$.signal,onUpdate:$.onUpdate,resolve:Z,reject:J,snapshot:this.snapshot("queued",1),settled:!1},X=(Q)=>{this.cancelPending(U,new M1(Q||void 0))},H={ready:Y,getSnapshot:()=>({...U.snapshot}),cancel:X,release:()=>{if(U.permit)U.permit.release();else X("Task admission released before execution")}};if(this.activeKeys.add($.key),$.signal?.aborted)return X(String($.signal.reason||"Task admission was cancelled")),H;if($.signal)U.abortListener=()=>X(String($.signal?.reason||"Task admission was cancelled")),$.signal.addEventListener("abort",U.abortListener,{once:!0});if(this.inFlight<this.maxConcurrent)this.startPending(U);else this.queue.push(U),this.publishQueueSnapshots();return H}configure($,Z){this.validateLimits($,Z),this.explicitlyConfigured=!0,this.applyConfiguration($,Z)}applyConfiguration($,Z){this.maxConcurrent=$,this.maxQueued=Z,this.drain(),this.publishQueueSnapshots()}getStats(){return{inFlight:this.inFlight,queued:this.queue.length,maxConcurrent:this.maxConcurrent,maxQueued:this.maxQueued}}resetForTests(){for(let $ of[...this.queue])this.cancelPending($,new M1("Scheduler reset"));this.queue.length=0,this.activeKeys.clear(),this.inFlight=0,this.maxConcurrent=3,this.maxQueued=100,this.explicitlyConfigured=!1}startPending($){if($.settled)return;this.detachAbort($),this.inFlight++;let Z=!1,J={release:()=>{if(Z)return;Z=!0,$.settled=!0,this.detachAbort($),this.activeKeys.delete($.key),this.inFlight=Math.max(0,this.inFlight-1),this.drain(),this.publishQueueSnapshots()}};$.permit=J,$.snapshot=this.snapshot("running"),this.publish($),$.resolve(J),this.publishQueueSnapshots()}cancelPending($,Z){if($.settled)return;if($.permit)return;let J=this.queue.indexOf($);if(J>=0)this.queue.splice(J,1);$.settled=!0,this.detachAbort($),this.activeKeys.delete($.key),$.reject(Z),this.publishQueueSnapshots()}drain(){while(this.inFlight<this.maxConcurrent&&this.queue.length>0){let $=this.queue.shift();if($&&!$.settled)this.startPending($)}}publishQueueSnapshots(){for(let[$,Z]of this.queue.entries())Z.snapshot=this.snapshot("queued",$+1),this.publish(Z)}snapshot($,Z){return{state:$,...Z!==void 0?{queuePosition:Z}:{},queueDepth:this.queue.length,inFlight:this.inFlight,maxConcurrent:this.maxConcurrent,maxQueued:this.maxQueued}}publish($){try{$.onUpdate?.({...$.snapshot})}catch{}}detachAbort($){if($.abortListener&&$.signal)$.signal.removeEventListener("abort",$.abortListener);$.abortListener=void 0}validateLimits($,Z){if(!f8($))throw Error(`maxConcurrent must be an integer between ${T8} and ${j8}`);if(!R8(Z))throw Error(`maxQueued must be an integer between ${M8} and ${C8}`)}}var $1=new k8;var y=u("Agent");class O0{config;runtimeOptions;isInitialized=!1;activeTask;toolExecutor;chatService;executionEngine;attachmentCollector;activeSkillContext;currentModelMaxContextTokens;currentModelId;sessionRuntime;legacyMcpRegistry;agentResources;subagentRegistry;constructor($,Z={},J,Y){this.config=$,this.runtimeOptions=Z,this.toolExecutor=J||this.createDefaultToolExecutor(),this.sessionRuntime=Y,this.agentResources=Y?.getAgentResources(),this.subagentRegistry=this.agentResources?.subagents}createDefaultToolExecutor(){let $=new A$,Z={...this.config.permissions,...this.runtimeOptions.permissions},J=this.runtimeOptions.permissionMode??this.config.permissionMode??"default";return new b1($,{permissionConfig:Z,permissionMode:J,maxHistorySize:1000,toolWhitelist:this.runtimeOptions.toolWhitelist,toolBlacklist:this.runtimeOptions.toolBlacklist})}resolveModelConfig($){let Z=$&&$!=="inherit"?$:void 0,J=Z?w6(Z):L$();if(!J)throw Error(`模型配置未找到: ${Z??"current"}`);return J}async applyModelConfig($,Z){let J=v8(),Y=w0($,this.config,J?"auto":"off");if(this.log(`${Z} ${Y.displayName} (${$.model})`),Y.model.reasoning&&!J)this.log("模型支持 Thinking,但用户未开启(按 Tab 开启)");else if(Y.chat.reasoningEnabled)this.log("Thinking 模式已启用,启用 reasoning_content 支持");this.currentModelMaxContextTokens=Y.model.contextWindow,this.chatService=await _2(Y.chat);let U=this.executionEngine?.getContextManager();this.executionEngine=new j1(this.chatService,U),this.currentModelId=$.id}async switchModelIfNeeded($){if(this.sessionRuntime){await this.sessionRuntime.refresh({modelId:$}),this.syncRuntimeState();return}if(!$||$===this.currentModelId)return;let Z=w6($);if(!Z){this.log(`Warning: 模型配置未找到: ${$}`);return}await this.applyModelConfig(Z,"切换模型")}async switchModel($){if(!this.isInitialized)throw Error("Agent未初始化");await this.switchModelIfNeeded($)}static async create($={}){if($.sessionId)throw Error("Agent.create() does not accept sessionId. Create a SessionRuntime explicitly and use Agent.createWithRuntime().");if(await K2(),Z1().length===0)throw Error(`没有可用的模型配置
|
|
643
643
|
|
|
644
644
|
`+`请先使用以下命令添加模型:
|
|
645
645
|
`+` /model add
|
|
646
646
|
|
|
647
647
|
`+`或运行初始化向导:
|
|
648
|
-
`+" /init");let J=W0();if(!J)throw Error("配置未初始化,请确保应用已正确启动");
|
|
648
|
+
`+" /init");let J=W0();if(!J)throw Error("配置未初始化,请确保应用已正确启动");t.getInstance().validateConfig(J);let U={...$};if(!U.toolWhitelist&&J.allowedTools?.length)U.toolWhitelist=J.allowedTools;if(!U.toolBlacklist&&J.disallowedTools?.length)U.toolBlacklist=J.disallowedTools;let X=new O0(J,U);if(await X.initialize(),U.toolWhitelist&&U.toolWhitelist.length>0)X.applyToolWhitelist(U.toolWhitelist);if(U.toolBlacklist&&U.toolBlacklist.length>0)X.applyToolBlacklist(U.toolBlacklist);return X}static async createWithRuntime($,Z={}){let J=W0(),Y={...Z};if(!Y.toolWhitelist&&J?.allowedTools?.length)Y.toolWhitelist=J.allowedTools;if(!Y.toolBlacklist&&J?.disallowedTools?.length)Y.toolBlacklist=J.disallowedTools;let U=new O0($.getConfig(),Y,$.createToolExecutor(Y),$);return await U.initialize(),U}async initialize(){if(this.isInitialized)return;try{if(this.log("初始化Agent..."),this.sessionRuntime){await this.initializeSystemPrompt(),await this.sessionRuntime.refresh(this.runtimeOptions),this.syncRuntimeState(),this.isInitialized=!0,this.log(`Agent初始化完成,已加载 ${this.toolExecutor.getRegistry().getAll().length} 个工具`);return}await this.initializeSystemPrompt(),await this.loadSubagents(),await this.registerBuiltinTools();let $=this.resolveModelConfig(this.runtimeOptions.modelId);await this.applyModelConfig($,"使用模型:"),this.attachmentCollector=new q1({cwd:N(),maxFileSize:1048576,maxLines:2000,maxTokens:32000}),this.isInitialized=!0,this.log(`Agent初始化完成,已加载 ${this.toolExecutor.getRegistry().getAll().length} 个工具`)}catch($){throw this.error("Agent初始化失败",$),$}}async executeTask($){if(!this.isInitialized)throw Error("Agent未初始化");this.activeTask=$;try{this.log(`开始执行任务: ${$.id}`);let Z=await this.executionEngine.executeTask($);return this.activeTask=void 0,this.log(`任务执行完成: ${$.id}`),Z}catch(Z){throw this.activeTask=void 0,this.error(`任务执行失败: ${$.id}`,Z),Z}}async*chatStream($,Z,J){let Y=this.sessionRuntime;if(!Y||!Z?.sessionId)return yield*this.chatStreamInternal($,Z,J);let U,X=!1,H=!1,Q=(W)=>{if(!X||!U)return;U.release(),U=void 0;try{Y.publishTaskAdmissionCapacity(W)}catch(z){y.warn("[Agent] Failed to publish task admission capacity:",z)}};try{if(Y.isTaskSession?.()===!0){X=J?.taskAdmission===void 0;let V=J?.taskAdmission??$1.admit({key:`${Y.workspaceRoot}\x00${Y.sessionId}`,...Y.getTaskAdmissionLimits(),signal:Z.signal,onUpdate:(B)=>{Y.setTaskAdmission(B).catch((K)=>{y.warn("[Agent] Failed to persist task admission update:",K)})}});try{U=await V.ready}catch(B){if(B instanceof M1||Z.signal?.aborted)return await Y.setTaskStatus("cancelled","Task admission was cancelled"),H=!0,{success:!1,error:{type:"aborted",message:"Task admission was cancelled"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}};throw B}if(Z.signal?.aborted)return await Y.setTaskStatus("cancelled","Task admission was cancelled"),H=!0,Q("cancelled"),{success:!1,error:{type:"aborted",message:"Task admission was cancelled"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}}}await Y.setTaskStatus("running");let W=yield*this.chatStreamInternal($,Z,J),z=Z.signal?.aborted?"cancelled":W.success?"completed":"failed";return await Y.setTaskStatus(z,z==="failed"&&W.error?W.error:void 0),H=!0,Q(z),W}catch(W){let z=Z.signal?.aborted?"cancelled":"failed";try{await Y.setTaskStatus(z,W)}catch(V){y.warn("[Agent] Failed to persist terminal task status:",V)}throw H=!0,Q(z),W}finally{if(!H)await Y.setTaskStatus("interrupted","Task stream closed before completion").catch((W)=>{y.warn("[Agent] Failed to persist interrupted task status:",W)}),Q("interrupted");if(X)U?.release()}}async*chatStreamInternal($,Z,J){if(!this.isInitialized)throw Error("Agent未初始化");if(Z?.workspaceRoot)this.attachmentCollector?.setCwd(Z.workspaceRoot);let Y=J?.pendingInputOnly===!0,U=J?.goalContinuationOnly===!0;if(Y&&J?.preparedInputTurn)throw Error("preparedInputTurn cannot be combined with pendingInputOnly");if(Y&&U)throw Error("goalContinuationOnly cannot be combined with pendingInputOnly");if(U&&J?.preparedInputTurn)throw Error("preparedInputTurn cannot be combined with goalContinuationOnly");if(!Z&&J?.preparedInputTurn)throw Error("preparedInputTurn requires a ChatContext");if(U&&(!Z||!this.sessionRuntime))throw Error("goalContinuationOnly requires a SessionRuntime and ChatContext");let X=J?.preparedInputTurn;if(Z&&this.sessionRuntime&&!Y&&!U){if(!X){let B=await this.sessionRuntime.prepareInputTurn($);if(!B.accepted)throw Error(B.reason==="queue_full"?"Pending user input queue is full":"Session already has an active turn");X=B}}let H=$,Q=null;if(U){if(Q=await this.sessionRuntime.beginGoalContinuation(),!Q)return{success:!0,finalMessage:"",metadata:{turnsCount:0,toolCallsCount:0,duration:0}};H=C5(Q)}else if(!Y&&X?.mode!=="pending")try{H=await this.processAtMentionsForContent($)}catch(B){if(this.sessionRuntime&&X)await this.sessionRuntime.finishTurn(X.handle).catch(()=>{return});throw B}else if(!Z||!this.sessionRuntime)H=await this.processAtMentionsForContent($);if(Z){let B=H,K=Z,G=Y,O=U,E=Q,q,F;if(this.sessionRuntime)if(O)F=this.sessionRuntime.beginTurn();else if(G)F=await this.sessionRuntime.beginPendingTurn();else{let w=X;if(F=w.handle,w.mode==="pending")G=!0,B="";else q=w.messageId}let D=0;if(G&&this.sessionRuntime&&!F)return{success:!0,finalMessage:"",metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let L=()=>this.sessionRuntime.getPendingSteeringMessages().map((w)=>({...w,persisted:K.messages.some((T)=>{let b=T.metadata;return b!==null&&typeof b==="object"&&!Array.isArray(b)&&b.inboxMessageId===w.id})})),A=async(w)=>Promise.all(w.map(async(T)=>({...T,content:await this.processAtMentionsForContent(T.content)})));try{if(G&&this.sessionRuntime)yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:L()};if(O&&E)yield{kind:"goal_continuation_started",goal:E,continuation:E.continuationCount},yield{kind:"goal_updated",goal:E};while(!0){let w=F,T={...J,pendingInputOnly:G,goalContinuationOnly:void 0,preparedInputTurn:void 0,inputMessageId:G?void 0:q,transientInput:O?"goal_continuation":void 0,signal:K.signal,turnSteering:this.sessionRuntime&&w?{drain:async()=>A(await this.sessionRuntime.drainSteering(w)),drainOrSeal:async()=>{let C=await this.sessionRuntime.drainSteeringOrSeal(w);return{...C,messages:await A(C.messages)}}}:void 0},b;if(K.permissionMode==="plan")b=yield*this.runPlanLoop(B,K,T);else b=yield*this.runLoop(B,K,T);if(b.success&&b.metadata?.targetMode&&K.permissionMode==="plan"){let C=b.metadata.targetMode,S=b.metadata.planContent;y.debug(`Plan 模式已批准,切换到 ${C} 模式并重新执行`),await F$().setPermissionMode(C),K={...K,permissionMode:C};let p=B;if(S){let m=`
|
|
649
649
|
|
|
650
650
|
<approved-plan>
|
|
651
651
|
${S}
|
|
652
652
|
</approved-plan>
|
|
653
653
|
|
|
654
|
-
IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof B==="string")p=B+m;else p=[...B,{type:"text",text:m}]}b=yield*this.runLoop(p,K,{...
|
|
655
|
-
`),z={id:this.generateTaskId(),type:"simple",prompt:W};return{success:!0,finalMessage:(await this.executeTask(z)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-
|
|
654
|
+
IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof B==="string")p=B+m;else p=[...B,{type:"text",text:m}]}b=yield*this.runLoop(p,K,{...T,inputMessageId:void 0})}if(!this.sessionRuntime||!w)return b;if(b.success&&!K.signal?.aborted)await this.sessionRuntime.acknowledgeTurn(w);let P=await this.sessionRuntime.recordGoalProgress({tokens:b.metadata?.tokensUsed??0,elapsedMs:b.metadata?.duration??0});if(P)yield{kind:"goal_updated",goal:P};if(!b.success||K.signal?.aborted){if(P=await this.sessionRuntime.pauseActiveGoal(K.signal?.aborted?"goal paused after user cancellation":b.error?.message??"goal paused after turn failure"),P)yield{kind:"goal_updated",goal:P}}let M=b.success&&!K.signal?.aborted&&D<20;if(F=await this.sessionRuntime.finishTurn(w,{continuePending:M}),F){D++,G=!0,O=!1,E=null,B="",q=void 0,yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:L()};continue}if(!b.success||K.signal?.aborted)return b;if(P=await this.sessionRuntime.getGoal(),!P||P.status!=="active")return b;if(E=await this.sessionRuntime.beginGoalContinuation(),!E)return b;F=this.sessionRuntime.beginTurn(),G=!1,O=!0,B=C5(E),q=void 0,yield{kind:"goal_continuation_started",goal:E,continuation:E.continuationCount},yield{kind:"goal_updated",goal:E}}}finally{if(this.sessionRuntime&&F)await this.sessionRuntime.finishTurn(F)}}let W=typeof H==="string"?H:H.filter((B)=>B.type==="text").map((B)=>B.text).join(`
|
|
655
|
+
`),z={id:this.generateTaskId(),type:"simple",prompt:W};return{success:!0,finalMessage:(await this.executeTask(z)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-n2s54h1r.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){y.debug("Processing Plan mode message...");let{prompt:Y}=await k$({projectPath:Z.workspaceRoot||N(),mode:"plan",includeEnvironment:!0,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),U;if(typeof $==="string")U=O1($);else{let X=$.filter((H)=>H.type==="text");if(X.length>0){let H=X[0];U=$.map((Q)=>Q===H?{type:"text",text:O1(H.text)}:Q)}else U=[{type:"text",text:O1("")},...$]}return yield*this.executeLoop(U,Z,J,Y)}async*runLoop($,Z,J){y.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||N());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await k$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let U=this.buildLoopDependencies();return I8(U,$,Z,J,Y)}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,y.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((U)=>!$.includes(U.name));for(let U of Y)Z.unregister(U.name);y.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);y.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){this.log("销毁Agent...");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){y.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){y.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await k$({projectPath:this.sessionRuntime?.workspaceRoot??N(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),y.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await O2({sessionId:"default",configDir:x8.join(y8.homedir(),".blade"),workspaceRoot:N(),resourceRoot:N(),agentResources:this.agentResources});y.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;y.debug(`Builtin tools registered: ${Z} tools`),y.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw y.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await r1({workspaceRoot:N(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){y.debug("No MCP servers configured");return}let Z=k0.createIsolated({artifactWriter:new G1(`legacy-${bU()}`)});this.legacyMcpRegistry=Z;for(let[X,H]of Object.entries($))try{y.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,H),y.debug(`MCP server "${X}" connected`)}catch(Q){y.warn(`Warning: MCP server "${X}" connection failed:`,Q)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(A1(Z));let U=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:U.revision,reason:"snapshot",replace:!0,instructions:U.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)y.debug(`Registered ${Y.tools.length} MCP tools`),y.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){y.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await e(N());if(this.agentResources=G2($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)y.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else y.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;y.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{return Z.some((U)=>{if(U===Y.name)return!0;let X=U.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return y.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)y.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
|
|
656
656
|
`);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;y.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let U=this.buildAttachmentText(Y);if(!U)return $;return[...$,{type:"text",text:U}]}catch(Y){return y.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let U of $)if(U.type==="file"){let X=U.metadata?.lineRange?` (lines ${U.metadata.lineRange.start}${U.metadata.lineRange.end?`-${U.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${U.path}"${X?` range="${X}"`:""}>`,U.content,"</file>")}else if(U.type==="directory")Z.push(`<directory path="${U.path}">`,U.content,"</directory>");else if(U.type==="error")J.push(`- @${U.path}: ${U.error}`);let Y="";if(Z.length>0)Y+=`
|
|
657
657
|
|
|
658
658
|
<system-reminder>
|
|
@@ -675,15 +675,15 @@ Warning: Some files could not be loaded:
|
|
|
675
675
|
|
|
676
676
|
Warning: Some files could not be loaded:
|
|
677
677
|
`,U+=Y.join(`
|
|
678
|
-
`);return U}}import{execFile as
|
|
678
|
+
`);return U}}import{execFile as TU}from"node:child_process";import{createHash as l8,randomBytes as jU}from"node:crypto";import{createReadStream as MU}from"node:fs";import{lstat as A6,mkdir as h8,mkdtemp as CU,readdir as fU,readFile as RU,readlink as SU,realpath as s0,rm as PU,stat as kU,writeFile as vU}from"node:fs/promises";import{Mutex as IU}from"async-mutex";var u8=64,yU=/^[a-zA-Z0-9._-]+$/,xU=/^(?:agent|task)\+[a-zA-Z0-9_-]{1,40}$/,hU=2592000000,uU=100,d8=1048576,dU=2097152,m8=52428800,mU="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";class E0 extends Error{reason;constructor($,Z){super(Z);this.reason=$;this.name="WorktreeDeliveryConflict"}}function g8($){if(!$||$.length>u8)throw Error(`Worktree name must contain 1-${u8} characters`);for(let Z of $.split("/"))if(Z==="."||Z===".."||!yU.test(Z))throw Error(`Invalid worktree name "${$}": use letters, digits, dots, underscores, dashes, and optional "/" separators`)}function p8($,Z=12){return l8("sha256").update($).digest("hex").slice(0,Z)}function gU($){return $.replaceAll("/","+")}function E2($){if(!$||D$($)||$.includes("\x00"))return!1;return!$.split("/").some((Z)=>Z==="..")}function pU($){let Z=0,J=0;for(let Y of $.split(`
|
|
679
679
|
`)){if(Y.startsWith("+")&&!Y.startsWith("+++"))Z++;if(Y.startsWith("-")&&!Y.startsWith("---"))J++}return{additions:Z,deletions:J}}function c8($,Z){let J=Buffer.from($);if(J.byteLength<=Z)return{patch:$,truncated:!1};let Y=`
|
|
680
680
|
[diff truncated]
|
|
681
|
-
`;if(Z<=Buffer.byteLength(Y))return{patch:"",truncated:!0};let U=Math.max(0,Z-Buffer.byteLength(Y));return{patch:`${J.subarray(0,U).toString("utf8")}${Y}`,truncated:!0}}async function k($,Z,J={}){return new Promise((Y)=>{
|
|
681
|
+
`;if(Z<=Buffer.byteLength(Y))return{patch:"",truncated:!0};let U=Math.max(0,Z-Buffer.byteLength(Y));return{patch:`${J.subarray(0,U).toString("utf8")}${Y}`,truncated:!0}}async function k($,Z,J={}){return new Promise((Y)=>{TU("git",Z,{cwd:$,encoding:"utf-8",maxBuffer:J.maxBuffer??10485760,env:{...process.env,...J.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:""}},(U,X,H)=>{Y({code:U==null?0:typeof U.code==="number"?U.code:1,stdout:X||"",stderr:H||""})})})}function cU($,Z){return new Promise((J,Y)=>{let U=MU(Z);U.on("data",(X)=>$.update(X)),U.on("error",Y),U.on("end",J)})}async function i8($){let Z=await k($,["--no-optional-locks","status","--porcelain=v1","-z","--untracked-files=all"]);Q0(Z,"Inspect source worktree");let J=l8("sha256");J.update(Z.stdout);let Y=Z.stdout.split("\x00").filter(Boolean),U=new Set;for(let X=0;X<Y.length;X++){let H=Y[X];if(H.length<4)continue;let Q=H.slice(0,2),W=H.slice(3);if(E2(W))U.add(W);if(/[RC]/.test(Q)){let z=Y[++X];if(z&&E2(z))U.add(z)}}for(let X of[...U].sort()){J.update(`\x00${X}\x00`);let H=B0($,X);try{let Q=await A6(H);if(J.update(`${Q.mode}:${Q.size}:`),Q.isSymbolicLink())J.update(await SU(H));else if(Q.isFile())await cU(J,H)}catch(Q){if(Q.code!=="ENOENT")throw Q;J.update("missing")}}return J.digest("hex")}function Q0($,Z){if($.code!==0)throw Error(`${Z} failed: ${$.stderr.trim()||$.stdout.trim()||"unknown git error"}`);return $.stdout.trim()}class n8{storageRoot;sessions=new Map;sessionLocks=new Map;constructor($={}){this.storageRoot=$.storageRoot??q0()}getActiveSession($){return this.sessions.get($)}getManagedRoot($){let Z=H$($),J=`${Z6(Z)}-${p8(Z)}`;return B0(this.storageRoot,"worktrees",J)}async enter($){return this.getSessionLock($.sessionId).runExclusive(async()=>{if(this.sessions.has($.sessionId))throw Error("This session is already inside a managed worktree");let Z=H$($.workspaceRoot),J=await k(Z,["rev-parse","--show-toplevel"]),[Y,U]=await Promise.all([s0(Z),s0(Q0(J,"Resolve repository root"))]),X=$6(U,Y);if(X===".."||X.startsWith("../")||D$(X))throw Error("Workspace is outside the resolved git repository");let H=$.name??`session-${Date.now().toString(36)}-${jU(3).toString("hex")}`;g8(H);let[Q,W,z,V]=await Promise.all([k(U,["rev-parse","HEAD"]),k(U,["branch","--show-current"]),k(U,["status","--porcelain"]),i8(U)]),B=Q0(Q,"Resolve worktree base commit"),K=Q0(W,"Resolve current branch");Q0(z,"Inspect source worktree");let G=gU(H),O=`blade-worktree-${G}-${p8($.sessionId,8)}`,E=this.getManagedRoot(U),q=B0(E,G);await h8(E,{recursive:!0});let F=await k(U,["worktree","add","-b",O,q,B]);Q0(F,"Create worktree");let D={sessionId:$.sessionId,name:H,branch:O,baseCommit:B,originalBranch:K,repositoryRoot:U,originalWorkspaceRoot:Y,worktreeRoot:q,workspaceRoot:X?B0(q,X):q,sourceHadChanges:z.stdout.trim().length>0,sourceStateFingerprint:V};return this.sessions.set($.sessionId,D),D})}async restoreSession($){return this.getSessionLock($.sessionId).runExclusive(async()=>{let Z=this.sessions.get($.sessionId);if(Z)return Z;g8($.name);let[J,Y,U]=await Promise.all([s0($.worktreeRoot),s0($.workspaceRoot),s0($.repositoryRoot)]),[X,H,Q,W]=await Promise.all([k(J,["rev-parse","--show-toplevel"]),k(J,["branch","--show-current"]),k(J,["cat-file","-e",`${$.baseCommit}^{commit}`]),k(U,["worktree","list","--porcelain"])]),z=await s0(Q0(X,"Resolve restored worktree")),V=Q0(H,"Resolve restored branch");if(Q0(Q,"Resolve restored base commit"),Q0(W,"List restored worktrees"),z!==J||V!==$.branch)throw Error("Persisted worktree metadata does not match Git state");if(!W.stdout.split(`
|
|
682
682
|
`).filter((G)=>G.startsWith("worktree ")).map((G)=>G.slice(9)).includes(J))throw Error("Persisted worktree is no longer registered");let K={...$,repositoryRoot:U,worktreeRoot:J,workspaceRoot:Y};return this.sessions.set($.sessionId,K),K})}async getChangeSummary($){let Z=this.sessions.get($);if(!Z)return;return this.inspectChanges(Z)}async getDiffArtifact($){let Z=this.sessions.get($);if(!Z)return;return this.inspectDiffArtifact(Z)}async apply($){return this.getSessionLock($).runExclusive(async()=>{let Z=this.sessions.get($);if(!Z)throw new E0("artifact_unavailable","Task worktree is unavailable");let J;try{J=await s0(Z.repositoryRoot)}catch{throw new E0("source_unavailable","Source workspace is unavailable")}if(J!==Z.repositoryRoot)throw new E0("source_unavailable","Source workspace identity changed");let Y=await k(J,["rev-parse","HEAD"]),U=Q0(Y,"Resolve source HEAD");if(U!==Z.baseCommit)throw new E0("source_head_changed","Source branch advanced after this task started");if(!Z.sourceStateFingerprint&&Z.sourceHadChanges)throw new E0("legacy_dirty_source","This older task started from a modified source workspace and cannot be applied automatically");let X=await i8(J);if(Z.sourceStateFingerprint&&X!==Z.sourceStateFingerprint)throw new E0("source_state_changed","Source workspace changed after this task started");if(!Z.sourceStateFingerprint&&X!==mU)throw new E0("source_state_changed","Source workspace has local changes");let H=await this.inspectChanges(Z);if(!H)throw new E0("artifact_unavailable","Task changes could not be inspected");if(H.changedFiles===0)throw new E0("no_changes","Task has no changes to apply");await h8(this.storageRoot,{recursive:!0});let Q=await CU(B0(this.storageRoot,"delivery-")),W=B0(Q,"index"),z=B0(Q,"changes.patch"),V={env:{GIT_INDEX_FILE:W}};try{Q0(await k(Z.worktreeRoot,["read-tree","HEAD"],V),"Prepare task delivery index"),Q0(await k(Z.worktreeRoot,["add","-A","--"],V),"Collect task changes");let B=Q0(await k(Z.worktreeRoot,["write-tree"],V),"Create task delivery tree"),K=await k(Z.worktreeRoot,["diff","--binary","--full-index","--no-ext-diff",Z.baseCommit,B,"--"],{maxBuffer:m8+1024});Q0(K,"Generate task delivery patch");let G=K.stdout;if(!G)throw new E0("no_changes","Task has no changes to apply");if(Buffer.byteLength(G)>m8)throw new E0("artifact_unavailable","Task changes exceed the 50 MiB delivery limit");if(await vU(z,G,{mode:384}),(await k(J,["apply","--check","--binary","--whitespace=nowarn",z])).code!==0)throw new E0("patch_conflict","Task changes conflict with the source workspace");if((await k(J,["apply","--binary","--whitespace=nowarn",z])).code!==0)throw new E0("patch_conflict","Task changes could not be applied")}finally{await PU(Q,{recursive:!0,force:!0})}return{action:"apply",workspaceRoot:Z.originalWorkspaceRoot,worktreeRoot:Z.worktreeRoot,branch:Z.branch,sourceCommit:U,...H}})}async cleanupStaleAgentWorktrees($){let Z={scanned:0,removed:0,preserved:0,skipped:0,errors:[]},J=$.maxAgeMs??hU;if(!Number.isFinite(J)||J<0)throw Error("maxAgeMs must be a finite non-negative number");let Y=await k(H$($.workspaceRoot),["rev-parse","--show-toplevel"]);if(Y.code!==0){let z=Y.stderr.trim()||Y.stdout.trim();if(!/not a git repository|not a git work tree/i.test(z))Z.errors.push(`Resolve cleanup repository failed: ${z}`);return Z}let U;try{U=await s0(Y.stdout.trim())}catch(z){return Z.errors.push(`Resolve cleanup repository path failed: ${z instanceof Error?z.message:String(z)}`),Z}let X=this.getManagedRoot(U),H;try{H=await fU(X,{withFileTypes:!0})}catch(z){if(z.code!=="ENOENT")Z.errors.push(`Read managed worktrees failed: ${z instanceof Error?z.message:String(z)}`);return Z}let Q=new Set([...this.sessions.values()].map((z)=>H$(z.worktreeRoot))),W=($.now??Date.now())-J;for(let z of H){if(!z.isDirectory()||!xU.test(z.name)){Z.skipped++;continue}let V=B0(X,z.name);if(Z.scanned++,Q.has(H$(V))){Z.skipped++;continue}let B;try{B=(await kU(V)).mtimeMs}catch(w){Z.errors.push(`Inspect stale worktree "${z.name}" failed: ${w instanceof Error?w.message:String(w)}`);continue}if(B>=W){Z.skipped++;continue}let[K,G,O,E]=await Promise.all([k(V,["rev-parse","--show-toplevel"]),k(V,["branch","--show-current"]),k(V,["--no-optional-locks","status","--porcelain"]),k(V,["rev-list","--max-count=1","HEAD","--not","--remotes"])]);if(K.code!==0||G.code!==0||O.code!==0||E.code!==0){Z.errors.push(`Git inspection failed for stale worktree "${z.name}"`);continue}let q=G.stdout.trim(),F,D;try{[F,D]=await Promise.all([s0(V),s0(K.stdout.trim())])}catch(w){Z.errors.push(`Canonical path inspection failed for "${z.name}": ${w instanceof Error?w.message:String(w)}`);continue}if(F!==D||!/^blade-worktree-(?:agent|task)\+/.test(q)){Z.errors.push(`Managed worktree identity mismatch for "${z.name}"`);continue}if(O.stdout.trim().length>0||E.stdout.trim().length>0){Z.preserved++;continue}let L=await k(U,["worktree","remove","--force",V]);if(L.code!==0){Z.errors.push(`Remove stale worktree "${z.name}" failed: ${L.stderr.trim()||L.stdout.trim()}`);continue}Z.removed++;let A=await k(U,["branch","-D",q]);if(A.code!==0)Z.errors.push(`Delete stale branch "${q}" failed: ${A.stderr.trim()||A.stdout.trim()}`)}if(Z.removed>0){let z=await k(U,["worktree","prune"]);if(z.code!==0)Z.errors.push(`Prune stale worktree registrations failed: ${z.stderr.trim()||z.stdout.trim()}`)}return Z}async exit($){return this.getSessionLock($.sessionId).runExclusive(async()=>{let Z=this.sessions.get($.sessionId);if(!Z)return{action:$.action,workspaceRoot:$.workspaceRoot??"",removed:!1,noop:!0};if($.action==="keep")return this.sessions.delete($.sessionId),{action:"keep",workspaceRoot:Z.originalWorkspaceRoot,worktreeRoot:Z.worktreeRoot,branch:Z.branch,removed:!1};let J=await this.inspectChanges(Z);if(!J&&!$.discardChanges)throw Error("Could not verify worktree state. Refusing removal without discard_changes=true");let{changedFiles:Y,commits:U}=J??{changedFiles:0,commits:0};if(!$.discardChanges&&(Y>0||U>0)){let W=[Y>0?`${Y} uncommitted ${Y===1?"file":"files"}`:"",U>0?`${U} unmerged ${U===1?"commit":"commits"}`:""].filter(Boolean);throw Error(`Worktree has ${W.join(" and ")}. Use action="keep" or confirm discard_changes=true`)}let X=["worktree","remove"];if($.discardChanges)X.push("--force");X.push(Z.worktreeRoot);let H=await k(Z.repositoryRoot,X);Q0(H,"Remove worktree");let Q=await k(Z.repositoryRoot,["branch","-D",Z.branch]);return this.sessions.delete($.sessionId),Q0(Q,"Delete worktree branch"),{action:"remove",workspaceRoot:Z.originalWorkspaceRoot,worktreeRoot:Z.worktreeRoot,branch:Z.branch,removed:!0,discardedFiles:$.discardChanges?Y:void 0,discardedCommits:$.discardChanges?U:void 0}})}releaseSession($){this.sessions.delete($)}getSessionLock($){let Z=this.sessionLocks.get($);if(!Z)Z=new IU,this.sessionLocks.set($,Z);return Z}async inspectDiffArtifact($){let[Z,J]=await Promise.all([k($.worktreeRoot,["diff","--name-only","-z",$.baseCommit,"--"]),k($.worktreeRoot,["ls-files","--others","--exclude-standard","-z"])]);if(Z.code!==0||J.code!==0)return null;let Y=new Set(Z.stdout.split("\x00").filter(E2)),U=new Set(J.stdout.split("\x00").filter(E2)),X=[...new Set([...Y,...U])].sort(),H=X.slice(0,uU),Q=await Promise.all(H.map(async(B)=>{let K=!Y.has(B)&&U.has(B);try{let D=await A6(B0($.worktreeRoot,B));if(D.size>d8)return{path:B,patch:"",additions:0,deletions:0,binary:!1,truncated:!0};if(K&&!D.isFile())return{path:B,patch:"",additions:0,deletions:0,binary:!0,truncated:!1}}catch(D){if(D.code!=="ENOENT")throw D}let G=K?await k($.worktreeRoot,["diff","--no-index","--no-ext-diff","--no-color","--unified=3","--","/dev/null",B]):await k($.worktreeRoot,["diff","--no-ext-diff","--no-color","--unified=3",$.baseCommit,"--",B]);if(!K&&G.code!==0||K&&![0,1].includes(G.code))throw Error(`Generate task diff failed for ${B}`);let O=K&&G.stdout.length===0?[`diff --git a/${B} b/${B}`,"new file mode 100644","--- /dev/null",`+++ b/${B}`,""].join(`
|
|
683
683
|
`):G.stdout,E=/^Binary files .+ differ$/m.test(O)||O.includes("GIT binary patch"),q=E?{additions:0,deletions:0}:pU(O),F=c8(O,d8);return{path:B,patch:F.patch,...q,binary:E,truncated:F.truncated}})),W=dU,z=X.length>H.length,V=Q.map((B)=>{let K=c8(B.patch,W);return W=Math.max(0,W-Buffer.byteLength(K.patch)),z||=K.truncated,K.truncated?{...B,patch:K.patch,truncated:!0}:B});return{baseCommit:$.baseCommit,files:V,truncated:z}}async inspectChanges($){let[Z,J,Y,U]=await Promise.all([k($.worktreeRoot,["diff","--name-only","-z",$.baseCommit,"--"]),k($.worktreeRoot,["rev-list","--count",`${$.baseCommit}..HEAD`]),k($.worktreeRoot,["diff","--numstat",$.baseCommit,"--"]),k($.worktreeRoot,["ls-files","--others","--exclude-standard","-z"])]);if(Z.code!==0||J.code!==0||Y.code!==0||U.code!==0)return null;let X=0,H=0;for(let Q of Y.stdout.split(`
|
|
684
684
|
`)){let[W,z]=Q.split("\t");if(/^\d+$/.test(W??""))X+=Number(W);if(/^\d+$/.test(z??""))H+=Number(z)}for(let Q of U.stdout.split("\x00").filter(Boolean))try{let W=B0($.worktreeRoot,Q),z=await A6(W);if(!z.isFile()||z.size>10485760)continue;let V=await RU(W);if(V.includes(0))continue;let B=V.toString("utf8");if(B.length>0)X+=B.split(`
|
|
685
685
|
`).length-(B.endsWith(`
|
|
686
|
-
`)?1:0)}catch{}return{changedFiles:new Set([...Z.stdout.split("\x00").filter(Boolean),...U.stdout.split("\x00").filter(Boolean)]).size,additions:X,deletions:H,commits:Number.parseInt(J.stdout.trim(),10)||0}}}var t0=new n8;function iU($){return`agent/${$.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)||"anonymous"}`}class r8{manager;constructor($=t0){this.manager=$}async prepare($){let Z=$.isolation??"none";if(Z!=="worktree")return{isolation:"none",workspaceRoot:$.sourceWorkspaceRoot,ownerAgentId:$.agentId};let J=$.restoredWorktree?await this.manager.restoreSession($.restoredWorktree):await this.manager.enter({sessionId:$.agentId,workspaceRoot:$.sourceWorkspaceRoot,name:iU($.agentId)});return{isolation:Z,workspaceRoot:J.workspaceRoot,ownerAgentId:$.restoredWorktree?.sessionId??$.agentId,worktree:J}}async finalize($){let{worktree:Z}=$.lease;if(!Z)return{preserved:!1,removed:!1};let J=$.lease.ownerAgentId??$.agentId,Y=await this.manager.getChangeSummary(J);if($.success&&this.isClean(Y))return await this.manager.exit({sessionId:J,action:"remove"}),{preserved:!1,removed:!0,changedFiles:0,commits:0};return await this.manager.exit({sessionId:J,action:"keep"}),{preserved:!0,removed:!1,worktreePath:Z.worktreeRoot,worktreeBranch:Z.branch,worktree:Z,changedFiles:Y?.changedFiles,commits:Y?.commits}}isClean($){return $!==null&&$!==void 0&&$.changedFiles===0&&$.commits===0}}var J1=new r8;var A0=u("Agent");function lU($){try{return process.kill($,0),!0}catch(Z){return Z instanceof Error&&"code"in Z&&Z.code==="EPERM"}}class o{static instance=null;runningAgents=new Map;sessionStore=Q$.getInstance();constructor(){this.cleanupOrphanedSessions()}static getInstance(){if(!o.instance)o.instance=new o;return o.instance}cleanupOrphanedSessions(){let $=this.sessionStore.listSessions(),Z=Date.now(),J=1800000;for(let Y of $)if(Y.status==="running"){let U=this.runningAgents.has(Y.id),X=Z-Y.lastActiveAt,H=Y.processId!==void 0&&lU(Y.processId),Q=Y.processId===void 0&&X<=1800000;if(!U&&!H&&!Q)A0.warn(`Cleaning up orphaned agent session: ${Y.id}`),this.sessionStore.updateSession(Y.id,{status:"failed",result:{success:!1,message:"",error:"Session was orphaned (process restart or timeout)"},completedAt:Z})}}startBackgroundAgent($){let{config:Z,description:J,prompt:Y,parentSessionId:U,parentProjectPath:X,permissionMode:H,reasoningEffort:Q,serviceTier:W,responseVerbosity:z,communicationStyle:V,agentId:B,existingMessages:K,taskListId:G,workspaceRoot:O=N(),isolation:E=Z.isolation??"none",restoredWorktree:q,rootAgentId:F,resumedFrom:D,resumeDepth:L=0,agentResources:A,modelResources:w,lspResources:j,onEvent:b,onCompleted:P}=$,M=B||z$("agent");if(this.runningAgents.has(M)||this.sessionStore.loadSession(M))throw Error(`Subagent session already exists: ${M}`);let C=new AbortController,S={schemaVersion:2,id:M,subagentType:Z.name,description:J,prompt:Y,messages:K||[],status:"running",createdAt:Date.now(),lastActiveAt:Date.now(),processId:process.pid,parentSessionId:U,parentProjectPath:X,rootAgentId:F??M,resumedFrom:D,resumeDepth:L,configSnapshot:Q2(Z),taskListId:G,workspaceRoot:O,isolation:E,worktree:q};this.sessionStore.saveSession(S);let p=Date.now(),m=this.executeAgent(M,Z,Y,U,H,Q,W,z,V,C.signal,K,G,O,E,q,A,w,j,b,P);return this.runningAgents.set(M,{id:M,promise:m,abortController:C,startTime:p}),m.then(()=>this.runningAgents.delete(M),()=>this.runningAgents.delete(M)),A0.info(`Background agent started: ${M} (${Z.name})`),M}async executeAgent($,Z,J,Y,U,X,H,Q,W,z,V,B,K=N(),G="none",O,E,q,F,D,L){let A=Date.now(),w,j,b,P=!1,M=async(C)=>{if(!b||P)return;let S=await J1.finalize({agentId:$,lease:b,success:C});return P=!0,this.sessionStore.updateSession($,{worktree:S.worktree}),S};try{if(z.aborted)throw Error("Agent execution was cancelled");b=await J1.prepare({agentId:$,sourceWorkspaceRoot:K,isolation:G,restoredWorktree:O}),this.sessionStore.updateSession($,{worktree:b.worktree});let C=Z.systemPrompt?.trim(),S=Z.model&&Z.model!=="inherit"?Z.model:void 0,p=Z.permissionMode??U,m=this.sessionStore.loadSession($);w=await N$.create({sessionId:$,workspaceRoot:b.workspaceRoot,modelId:S,reasoningEffort:X,serviceTier:H,responseVerbosity:Q,communicationStyle:W,agentResources:E,modelResources:q,lspResources:F,...(V?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:$}}:{},subagentInfo:Y?{parentSessionId:Y,subagentType:Z.name,isSidechain:!1,resumedFrom:m?.resumedFrom,rootAgentId:m?.rootAgentId??$,resumeDepth:m?.resumeDepth??0}:void 0}),j=await O0.createWithRuntime(w,{sessionId:$,toolWhitelist:Z.tools,toolBlacklist:["EnterWorktree","ExitWorktree",...Z.disallowedTools??[]],modelId:S,maxTurns:Z.maxTurns,permissionMode:p,...C?{appendSystemPrompt:C}:{}});let c={messages:V||[],userId:"subagent",sessionId:$,taskListId:B,workspaceRoot:b.workspaceRoot,worktreeActive:Boolean(b.worktree),permissionMode:p,subagentInfo:{parentSessionId:Y||"",subagentType:Z.name,isSidechain:!1,resumedFrom:m?.resumedFrom,rootAgentId:m?.rootAgentId??$,resumeDepth:m?.resumeDepth??0}},U0=new Set,$$=new Set,b0=await h0(j.chatStream(J,c,{signal:z}),async(v0)=>{if(v0.kind==="tool_result"&&"function"in v0.toolCall)F2($$,v0.toolCall.function.name,v0.result),D2(U0,v0.toolCall.function.name,v0.result);try{await D?.(v0,$)}catch(n2){A0.warn(`Subagent event observer failed: ${$}`,n2)}});this.sessionStore.updateSession($,{messages:c.messages});let Z$=Date.now()-A,r=b0.success?{success:!0,message:b0.finalMessage||"",agentId:$,verificationCommands:[...U0],verificationVerdict:Z.name==="verification"?q2(b0.finalMessage):void 0,modifiedFiles:[...$$],stats:{tokens:b0.metadata?.tokensUsed||0,toolCalls:b0.metadata?.toolCallsCount||0,duration:Z$}}:{success:!1,message:"",agentId:$,error:b0.error?.message||"Unknown error",stats:{duration:Z$}},J$=await M(r.success);if(J$?.preserved)r.worktreePath=J$.worktreePath,r.worktreeBranch=J$.worktreeBranch,r.worktree=J$.worktree;let l2=this.sessionStore.markCompleted($,{success:r.success,message:r.message,error:r.error,verificationCommands:r.verificationCommands,verificationVerdict:r.verificationVerdict,modifiedFiles:r.modifiedFiles},r.stats);if(l2)try{await L?.(l2)}catch(v0){A0.warn(`Subagent completion observer failed: ${$}`,v0)}return A0.info(`Background agent completed: ${$} (success=${r.success})`),r}catch(C){let S=Date.now()-A,p=C instanceof Error?C.message:String(C),m;try{m=await M(!1)}catch(U0){A0.warn(`Failed to preserve worktree for background agent ${$}`,U0)}let c=this.sessionStore.markCompleted($,{success:!1,message:"",error:p},{duration:S});if(c)try{await L?.(c)}catch(U0){A0.warn(`Subagent completion observer failed: ${$}`,U0)}return A0.warn(`Background agent failed: ${$}`,C),{success:!1,message:"",agentId:$,error:p,stats:{duration:S},worktreePath:m?.worktreePath,worktreeBranch:m?.worktreeBranch,worktree:m?.worktree}}finally{try{if(j&&typeof j.destroy==="function")await j.destroy()}finally{await w?.dispose()}}}getAgent($,Z){let J=this.sessionStore.loadSession($);if(!J||Z===void 0)return J;if(typeof Z==="string")return J.parentSessionId===Z?J:void 0;return Y6(J,Z)?J:void 0}isRunning($){return this.runningAgents.has($)}async waitForCompletion($,Z=30000,J){if(J!==void 0&&!this.getAgent($,J))return;let Y=this.runningAgents.get($);if(!Y)return this.getAgent($,J);if(Z>0){let U=new Promise((H)=>setTimeout(()=>H("timeout"),Z));if(await Promise.race([Y.promise,U])==="timeout")return this.getAgent($,J)}else await Y.promise;return this.getAgent($,J)}resumeAgent($){let{agentId:Z,prompt:J,config:Y,permissionMode:U,reasoningEffort:X,serviceTier:H,responseVerbosity:Q,communicationStyle:W,newAgentId:z=z$("agent"),agentResources:V,modelResources:B,lspResources:K,onEvent:G,onCompleted:O}=$,E=J6($.owner),q=this.getAgent(Z,E);if(!q){A0.warn(`Cannot resume agent ${Z}: session not found`);return}if(q.subagentType!==Y.name){A0.warn(`Cannot resume agent ${Z}: requested type ${Y.name} does not match ${q.subagentType}`);return}if(this.isRunning(Z)||q.status==="running"){A0.warn(`Cannot resume agent ${Z}: still running`);return}if(z===Z){A0.warn(`Cannot resume agent ${Z}: new run must use a new ID`);return}let F=q.configSnapshot?{...q.configSnapshot}:Y;return{agentId:this.startBackgroundAgent({config:F,description:q.description,prompt:J,parentSessionId:E.sessionId,parentProjectPath:E.projectPath,permissionMode:U,reasoningEffort:X,serviceTier:H,responseVerbosity:Q,communicationStyle:W,agentId:z,existingMessages:q.messages,taskListId:q.taskListId,workspaceRoot:q.workspaceRoot,isolation:q.isolation,restoredWorktree:q.worktree,rootAgentId:q.rootAgentId,resumedFrom:q.id,resumeDepth:q.resumeDepth+1,agentResources:V,modelResources:B,lspResources:K,onEvent:G,onCompleted:O}),source:q}}killAgent($,Z){if(Z&&!this.getAgent($,Z))return!1;let J=this.runningAgents.get($);if(!J){let Y=this.sessionStore.loadSession($);if(Y&&Y.status==="running")this.sessionStore.updateSession($,{status:"cancelled"});return!1}return J.abortController.abort(),this.sessionStore.updateSession($,{status:"cancelled"}),A0.info(`Background agent cancelled: ${$}`),!0}listAll(){return this.sessionStore.listSessions()}listForSession($){return this.sessionStore.listSessions().filter((Z)=>typeof $==="string"?Z.parentSessionId===$:Y6(Z,$))}listRunning(){return this.sessionStore.listRunningSessions()}getRunningCount(){return this.runningAgents.size}killAll(){for(let[$]of this.runningAgents)this.killAgent($)}cleanupExpiredSessions($){return this.sessionStore.cleanupExpiredSessions($)}cleanupExpiredSessionsForParent($,Z=604800000){let J=Date.now(),Y=0;for(let U of this.listForSession($)){if(U.status==="running")continue;if(J-U.lastActiveAt<=Z)continue;if(this.sessionStore.deleteSession(U.id))Y++}return Y}}class L6{config;agentResources;modelResources;lspResources;constructor($,Z,J,Y){this.config=$;this.agentResources=Z;this.modelResources=J;this.lspResources=Y}async execute($){let Z=Date.now(),J=$.subagentSessionId??z$("agent"),Y,U,X;try{let H=this.getAppendSystemPrompt(),Q=this.config.model&&this.config.model!=="inherit"?this.config.model:void 0,W=this.config.permissionMode??$.permissionMode,z={parentSessionId:$.parentSessionId||"",subagentType:this.config.name,isSidechain:!1,resumedFrom:$.resumedFrom,rootAgentId:$.rootAgentId??J,resumeDepth:$.resumeDepth??0};U=await N$.create({sessionId:J,workspaceRoot:$.workspaceRoot||N(),modelId:Q,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,subagentInfo:z,agentResources:this.agentResources,modelResources:this.modelResources,lspResources:this.lspResources,...($.existingMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:J}}:{}}),Y=await O0.createWithRuntime(U,{sessionId:J,toolWhitelist:this.config.tools,toolBlacklist:["EnterWorktree","ExitWorktree",...this.config.disallowedTools??[]],modelId:Q,maxTurns:this.config.maxTurns,permissionMode:W,...H?{appendSystemPrompt:H}:{}});let V="",B=0,K=0,G=new Set,O=new Set;X={messages:[...$.existingMessages??[]],userId:"subagent",sessionId:J,workspaceRoot:$.workspaceRoot||N(),completionRequirements:H,worktreeActive:$.worktreeActive,permissionMode:W,subagentInfo:z};let E=async(D)=>{if(D.kind==="tool_result"&&"function"in D.toolCall)F2(O,D.toolCall.function.name,D.result),D2(G,D.toolCall.function.name,D.result);await $.onEvent?.(D)},q=await h0(Y.chatStream($.prompt,X),E);if(q.success)V=q.finalMessage||"",B=q.metadata?.toolCallsCount||0,K=q.metadata?.tokensUsed||0;else throw Error(q.error?.message||"Subagent execution failed");let F=Date.now()-Z;return{success:!0,message:V,agentId:J,messages:X.messages,verificationCommands:[...G],verificationVerdict:this.config.name==="verification"?q2(V):void 0,modifiedFiles:[...O],stats:{tokens:K,toolCalls:B,duration:F}}}catch(H){let Q=Date.now()-Z;return{success:!1,message:"",agentId:J,messages:X?.messages??[...$.existingMessages??[]],error:H instanceof Error?H.message:String(H),stats:{duration:Q}}}finally{if(Y&&typeof Y.destroy==="function")await Y.destroy().catch(()=>{return});await U?.dispose().catch(()=>{return})}}getAppendSystemPrompt(){return this.config.systemPrompt?.trim()||void 0}}import{basename as b$}from"node:path";function N6($,Z){switch($){case"Write":{let J=Z.file_path;return`Writing ${J?b$(J):"file"}`}case"Edit":{let J=Z.file_path;return`Editing ${J?b$(J):"file"}`}case"ApplyPatch":{let J=Z.patch,Y=J?(J.match(/^\*\*\* (?:Add|Delete|Update) File: /gm)??[]).length:0;return`Applying atomic patch${Y>0?` to ${Y} file(s)`:""}`}case"Read":{let J=Z.file_path;return`Reading ${J?b$(J):"file"}`}case"Bash":{let{command:J,description:Y}=Z;if(Y)return`${Y}`;return`Running: ${J?J.substring(0,40):"command"}${J&&J.length>40?"...":""}`}case"WriteStdin":return`Sending input to Shell: ${Z.shell_id||"unknown"}`;case"Glob":return`Searching files: ${Z.pattern}`;case"Grep":{let{pattern:J,path:Y}=Z,U=J&&J.length>30?J.substring(0,30)+"...":J;if(Y){let X=b$(Y);return`Searching "${U}" in ${X}`}return`Searching "${U}"`}case"WebFetch":{let J=Z.url;if(J)try{return`Fetching ${new URL(J).hostname}`}catch{return"Fetching URL"}return"Fetching URL"}case"WebSearch":{let J=Z.query;return`Searching: "${J&&J.length>40?J.substring(0,40)+"...":J}"`}case"TaskCreate":return`Creating task: ${Z.subject||"task"}`;case"TaskGet":return`Reading task ${Z.taskId||""}`.trim();case"TaskUpdate":{let{status:J,taskId:Y}=Z;return J?`Updating task ${Y||""}: ${J}`.trim():`Updating task ${Y||""}`.trim()}case"TaskList":return"Listing tasks";case"UndoEdit":{let J=Z.file_path;return`Undoing changes to ${J?b$(J):"file"}`}case"Skill":return`Invoking skill: ${Z.skill}`;case"Task":{let{description:J,subagent_type:Y}=Z,U=Z.resume_from||Z.resume;if(U)return`Resuming ${Y||"agent"} from ${U}`;if(J)return`${Y||"Agent"}: ${J}`;return`Running ${Y||"agent"}`}case"LSP":{let{operation:J,filePath:Y}=Z,U=Y?b$(Y):"file";return`LSP ${J} in ${U}`}case"NotebookEdit":{let J=Z.notebook_path;return`Editing notebook: ${J?b$(J):"notebook"}`}default:return`${$}`}}function nU($,Z){if(!Z?.success&&!Z?.metadata)return!1;switch($){case"Write":case"Edit":case"ApplyPatch":case"Read":case"Glob":case"Grep":case"Bash":case"TaskOutput":return!0;case"WebFetch":case"WebSearch":return!0;case"TaskCreate":case"TaskGet":case"TaskUpdate":case"TaskList":return!1;default:return!!Z.metadata?.detail}}function rU($,Z){if(!Z?.success)return null;switch($){case"Glob":{if(!a8(Z.metadata))return null;let{matches:J}=Z.metadata;if(!J?.length)return null;let Y=5,U=J.slice(0,Y).map((X)=>X.relative_path);if(J.length>Y)U.push(`... (+${J.length-Y} more)`);return U.join(`
|
|
686
|
+
`)?1:0)}catch{}return{changedFiles:new Set([...Z.stdout.split("\x00").filter(Boolean),...U.stdout.split("\x00").filter(Boolean)]).size,additions:X,deletions:H,commits:Number.parseInt(J.stdout.trim(),10)||0}}}var t0=new n8;function iU($){return`agent/${$.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)||"anonymous"}`}class r8{manager;constructor($=t0){this.manager=$}async prepare($){let Z=$.isolation??"none";if(Z!=="worktree")return{isolation:"none",workspaceRoot:$.sourceWorkspaceRoot,ownerAgentId:$.agentId};let J=$.restoredWorktree?await this.manager.restoreSession($.restoredWorktree):await this.manager.enter({sessionId:$.agentId,workspaceRoot:$.sourceWorkspaceRoot,name:iU($.agentId)});return{isolation:Z,workspaceRoot:J.workspaceRoot,ownerAgentId:$.restoredWorktree?.sessionId??$.agentId,worktree:J}}async finalize($){let{worktree:Z}=$.lease;if(!Z)return{preserved:!1,removed:!1};let J=$.lease.ownerAgentId??$.agentId,Y=await this.manager.getChangeSummary(J);if($.success&&this.isClean(Y))return await this.manager.exit({sessionId:J,action:"remove"}),{preserved:!1,removed:!0,changedFiles:0,commits:0};return await this.manager.exit({sessionId:J,action:"keep"}),{preserved:!0,removed:!1,worktreePath:Z.worktreeRoot,worktreeBranch:Z.branch,worktree:Z,changedFiles:Y?.changedFiles,commits:Y?.commits}}isClean($){return $!==null&&$!==void 0&&$.changedFiles===0&&$.commits===0}}var J1=new r8;var A0=u("Agent");function lU($){try{return process.kill($,0),!0}catch(Z){return Z instanceof Error&&"code"in Z&&Z.code==="EPERM"}}class o{static instance=null;runningAgents=new Map;sessionStore=Q$.getInstance();constructor(){this.cleanupOrphanedSessions()}static getInstance(){if(!o.instance)o.instance=new o;return o.instance}cleanupOrphanedSessions(){let $=this.sessionStore.listSessions(),Z=Date.now(),J=1800000;for(let Y of $)if(Y.status==="running"){let U=this.runningAgents.has(Y.id),X=Z-Y.lastActiveAt,H=Y.processId!==void 0&&lU(Y.processId),Q=Y.processId===void 0&&X<=1800000;if(!U&&!H&&!Q)A0.warn(`Cleaning up orphaned agent session: ${Y.id}`),this.sessionStore.updateSession(Y.id,{status:"failed",result:{success:!1,message:"",error:"Session was orphaned (process restart or timeout)"},completedAt:Z})}}startBackgroundAgent($){let{config:Z,description:J,prompt:Y,parentSessionId:U,parentProjectPath:X,permissionMode:H,reasoningEffort:Q,serviceTier:W,responseVerbosity:z,communicationStyle:V,agentId:B,existingMessages:K,taskListId:G,workspaceRoot:O=N(),isolation:E=Z.isolation??"none",restoredWorktree:q,rootAgentId:F,resumedFrom:D,resumeDepth:L=0,agentResources:A,modelResources:w,lspResources:T,onEvent:b,onCompleted:P}=$,M=B||z$("agent");if(this.runningAgents.has(M)||this.sessionStore.loadSession(M))throw Error(`Subagent session already exists: ${M}`);let C=new AbortController,S={schemaVersion:2,id:M,subagentType:Z.name,description:J,prompt:Y,messages:K||[],status:"running",createdAt:Date.now(),lastActiveAt:Date.now(),processId:process.pid,parentSessionId:U,parentProjectPath:X,rootAgentId:F??M,resumedFrom:D,resumeDepth:L,configSnapshot:Q2(Z),taskListId:G,workspaceRoot:O,isolation:E,worktree:q};this.sessionStore.saveSession(S);let p=Date.now(),m=this.executeAgent(M,Z,Y,U,H,Q,W,z,V,C.signal,K,G,O,E,q,A,w,T,b,P);return this.runningAgents.set(M,{id:M,promise:m,abortController:C,startTime:p}),m.then(()=>this.runningAgents.delete(M),()=>this.runningAgents.delete(M)),A0.info(`Background agent started: ${M} (${Z.name})`),M}async executeAgent($,Z,J,Y,U,X,H,Q,W,z,V,B,K=N(),G="none",O,E,q,F,D,L){let A=Date.now(),w,T,b,P=!1,M=async(C)=>{if(!b||P)return;let S=await J1.finalize({agentId:$,lease:b,success:C});return P=!0,this.sessionStore.updateSession($,{worktree:S.worktree}),S};try{if(z.aborted)throw Error("Agent execution was cancelled");b=await J1.prepare({agentId:$,sourceWorkspaceRoot:K,isolation:G,restoredWorktree:O}),this.sessionStore.updateSession($,{worktree:b.worktree});let C=Z.systemPrompt?.trim(),S=Z.model&&Z.model!=="inherit"?Z.model:void 0,p=Z.permissionMode??U,m=this.sessionStore.loadSession($);w=await N$.create({sessionId:$,workspaceRoot:b.workspaceRoot,modelId:S,reasoningEffort:X,serviceTier:H,responseVerbosity:Q,communicationStyle:W,agentResources:E,modelResources:q,lspResources:F,...(V?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:$}}:{},subagentInfo:Y?{parentSessionId:Y,subagentType:Z.name,isSidechain:!1,resumedFrom:m?.resumedFrom,rootAgentId:m?.rootAgentId??$,resumeDepth:m?.resumeDepth??0}:void 0}),T=await O0.createWithRuntime(w,{sessionId:$,toolWhitelist:Z.tools,toolBlacklist:["EnterWorktree","ExitWorktree",...Z.disallowedTools??[]],modelId:S,maxTurns:Z.maxTurns,permissionMode:p,...C?{appendSystemPrompt:C}:{}});let c={messages:V||[],userId:"subagent",sessionId:$,taskListId:B,workspaceRoot:b.workspaceRoot,worktreeActive:Boolean(b.worktree),permissionMode:p,subagentInfo:{parentSessionId:Y||"",subagentType:Z.name,isSidechain:!1,resumedFrom:m?.resumedFrom,rootAgentId:m?.rootAgentId??$,resumeDepth:m?.resumeDepth??0}},U0=new Set,$$=new Set,b0=await h0(T.chatStream(J,c,{signal:z}),async(v0)=>{if(v0.kind==="tool_result"&&"function"in v0.toolCall)F2($$,v0.toolCall.function.name,v0.result),D2(U0,v0.toolCall.function.name,v0.result);try{await D?.(v0,$)}catch(n2){A0.warn(`Subagent event observer failed: ${$}`,n2)}});this.sessionStore.updateSession($,{messages:c.messages});let Z$=Date.now()-A,r=b0.success?{success:!0,message:b0.finalMessage||"",agentId:$,verificationCommands:[...U0],verificationVerdict:Z.name==="verification"?q2(b0.finalMessage):void 0,modifiedFiles:[...$$],stats:{tokens:b0.metadata?.tokensUsed||0,toolCalls:b0.metadata?.toolCallsCount||0,duration:Z$}}:{success:!1,message:"",agentId:$,error:b0.error?.message||"Unknown error",stats:{duration:Z$}},J$=await M(r.success);if(J$?.preserved)r.worktreePath=J$.worktreePath,r.worktreeBranch=J$.worktreeBranch,r.worktree=J$.worktree;let l2=this.sessionStore.markCompleted($,{success:r.success,message:r.message,error:r.error,verificationCommands:r.verificationCommands,verificationVerdict:r.verificationVerdict,modifiedFiles:r.modifiedFiles},r.stats);if(l2)try{await L?.(l2)}catch(v0){A0.warn(`Subagent completion observer failed: ${$}`,v0)}return A0.info(`Background agent completed: ${$} (success=${r.success})`),r}catch(C){let S=Date.now()-A,p=C instanceof Error?C.message:String(C),m;try{m=await M(!1)}catch(U0){A0.warn(`Failed to preserve worktree for background agent ${$}`,U0)}let c=this.sessionStore.markCompleted($,{success:!1,message:"",error:p},{duration:S});if(c)try{await L?.(c)}catch(U0){A0.warn(`Subagent completion observer failed: ${$}`,U0)}return A0.warn(`Background agent failed: ${$}`,C),{success:!1,message:"",agentId:$,error:p,stats:{duration:S},worktreePath:m?.worktreePath,worktreeBranch:m?.worktreeBranch,worktree:m?.worktree}}finally{try{if(T&&typeof T.destroy==="function")await T.destroy()}finally{await w?.dispose()}}}getAgent($,Z){let J=this.sessionStore.loadSession($);if(!J||Z===void 0)return J;if(typeof Z==="string")return J.parentSessionId===Z?J:void 0;return Y6(J,Z)?J:void 0}isRunning($){return this.runningAgents.has($)}async waitForCompletion($,Z=30000,J){if(J!==void 0&&!this.getAgent($,J))return;let Y=this.runningAgents.get($);if(!Y)return this.getAgent($,J);if(Z>0){let U=new Promise((H)=>setTimeout(()=>H("timeout"),Z));if(await Promise.race([Y.promise,U])==="timeout")return this.getAgent($,J)}else await Y.promise;return this.getAgent($,J)}resumeAgent($){let{agentId:Z,prompt:J,config:Y,permissionMode:U,reasoningEffort:X,serviceTier:H,responseVerbosity:Q,communicationStyle:W,newAgentId:z=z$("agent"),agentResources:V,modelResources:B,lspResources:K,onEvent:G,onCompleted:O}=$,E=J6($.owner),q=this.getAgent(Z,E);if(!q){A0.warn(`Cannot resume agent ${Z}: session not found`);return}if(q.subagentType!==Y.name){A0.warn(`Cannot resume agent ${Z}: requested type ${Y.name} does not match ${q.subagentType}`);return}if(this.isRunning(Z)||q.status==="running"){A0.warn(`Cannot resume agent ${Z}: still running`);return}if(z===Z){A0.warn(`Cannot resume agent ${Z}: new run must use a new ID`);return}let F=q.configSnapshot?{...q.configSnapshot}:Y;return{agentId:this.startBackgroundAgent({config:F,description:q.description,prompt:J,parentSessionId:E.sessionId,parentProjectPath:E.projectPath,permissionMode:U,reasoningEffort:X,serviceTier:H,responseVerbosity:Q,communicationStyle:W,agentId:z,existingMessages:q.messages,taskListId:q.taskListId,workspaceRoot:q.workspaceRoot,isolation:q.isolation,restoredWorktree:q.worktree,rootAgentId:q.rootAgentId,resumedFrom:q.id,resumeDepth:q.resumeDepth+1,agentResources:V,modelResources:B,lspResources:K,onEvent:G,onCompleted:O}),source:q}}killAgent($,Z){if(Z&&!this.getAgent($,Z))return!1;let J=this.runningAgents.get($);if(!J){let Y=this.sessionStore.loadSession($);if(Y&&Y.status==="running")this.sessionStore.updateSession($,{status:"cancelled"});return!1}return J.abortController.abort(),this.sessionStore.updateSession($,{status:"cancelled"}),A0.info(`Background agent cancelled: ${$}`),!0}listAll(){return this.sessionStore.listSessions()}listForSession($){return this.sessionStore.listSessions().filter((Z)=>typeof $==="string"?Z.parentSessionId===$:Y6(Z,$))}listRunning(){return this.sessionStore.listRunningSessions()}getRunningCount(){return this.runningAgents.size}killAll(){for(let[$]of this.runningAgents)this.killAgent($)}cleanupExpiredSessions($){return this.sessionStore.cleanupExpiredSessions($)}cleanupExpiredSessionsForParent($,Z=604800000){let J=Date.now(),Y=0;for(let U of this.listForSession($)){if(U.status==="running")continue;if(J-U.lastActiveAt<=Z)continue;if(this.sessionStore.deleteSession(U.id))Y++}return Y}}class L6{config;agentResources;modelResources;lspResources;constructor($,Z,J,Y){this.config=$;this.agentResources=Z;this.modelResources=J;this.lspResources=Y}async execute($){let Z=Date.now(),J=$.subagentSessionId??z$("agent"),Y,U,X;try{let H=this.getAppendSystemPrompt(),Q=this.config.model&&this.config.model!=="inherit"?this.config.model:void 0,W=this.config.permissionMode??$.permissionMode,z={parentSessionId:$.parentSessionId||"",subagentType:this.config.name,isSidechain:!1,resumedFrom:$.resumedFrom,rootAgentId:$.rootAgentId??J,resumeDepth:$.resumeDepth??0};U=await N$.create({sessionId:J,workspaceRoot:$.workspaceRoot||N(),modelId:Q,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,subagentInfo:z,agentResources:this.agentResources,modelResources:this.modelResources,lspResources:this.lspResources,...($.existingMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:J}}:{}}),Y=await O0.createWithRuntime(U,{sessionId:J,toolWhitelist:this.config.tools,toolBlacklist:["EnterWorktree","ExitWorktree",...this.config.disallowedTools??[]],modelId:Q,maxTurns:this.config.maxTurns,permissionMode:W,...H?{appendSystemPrompt:H}:{}});let V="",B=0,K=0,G=new Set,O=new Set;X={messages:[...$.existingMessages??[]],userId:"subagent",sessionId:J,workspaceRoot:$.workspaceRoot||N(),completionRequirements:H,worktreeActive:$.worktreeActive,permissionMode:W,subagentInfo:z};let E=async(D)=>{if(D.kind==="tool_result"&&"function"in D.toolCall)F2(O,D.toolCall.function.name,D.result),D2(G,D.toolCall.function.name,D.result);await $.onEvent?.(D)},q=await h0(Y.chatStream($.prompt,X),E);if(q.success)V=q.finalMessage||"",B=q.metadata?.toolCallsCount||0,K=q.metadata?.tokensUsed||0;else throw Error(q.error?.message||"Subagent execution failed");let F=Date.now()-Z;return{success:!0,message:V,agentId:J,messages:X.messages,verificationCommands:[...G],verificationVerdict:this.config.name==="verification"?q2(V):void 0,modifiedFiles:[...O],stats:{tokens:K,toolCalls:B,duration:F}}}catch(H){let Q=Date.now()-Z;return{success:!1,message:"",agentId:J,messages:X?.messages??[...$.existingMessages??[]],error:H instanceof Error?H.message:String(H),stats:{duration:Q}}}finally{if(Y&&typeof Y.destroy==="function")await Y.destroy().catch(()=>{return});await U?.dispose().catch(()=>{return})}}getAppendSystemPrompt(){return this.config.systemPrompt?.trim()||void 0}}import{basename as b$}from"node:path";function N6($,Z){switch($){case"Write":{let J=Z.file_path;return`Writing ${J?b$(J):"file"}`}case"Edit":{let J=Z.file_path;return`Editing ${J?b$(J):"file"}`}case"ApplyPatch":{let J=Z.patch,Y=J?(J.match(/^\*\*\* (?:Add|Delete|Update) File: /gm)??[]).length:0;return`Applying atomic patch${Y>0?` to ${Y} file(s)`:""}`}case"Read":{let J=Z.file_path;return`Reading ${J?b$(J):"file"}`}case"Bash":{let{command:J,description:Y}=Z;if(Y)return`${Y}`;return`Running: ${J?J.substring(0,40):"command"}${J&&J.length>40?"...":""}`}case"WriteStdin":return`Sending input to Shell: ${Z.shell_id||"unknown"}`;case"Glob":return`Searching files: ${Z.pattern}`;case"Grep":{let{pattern:J,path:Y}=Z,U=J&&J.length>30?J.substring(0,30)+"...":J;if(Y){let X=b$(Y);return`Searching "${U}" in ${X}`}return`Searching "${U}"`}case"WebFetch":{let J=Z.url;if(J)try{return`Fetching ${new URL(J).hostname}`}catch{return"Fetching URL"}return"Fetching URL"}case"WebSearch":{let J=Z.query;return`Searching: "${J&&J.length>40?J.substring(0,40)+"...":J}"`}case"TaskCreate":return`Creating task: ${Z.subject||"task"}`;case"TaskGet":return`Reading task ${Z.taskId||""}`.trim();case"TaskUpdate":{let{status:J,taskId:Y}=Z;return J?`Updating task ${Y||""}: ${J}`.trim():`Updating task ${Y||""}`.trim()}case"TaskList":return"Listing tasks";case"UndoEdit":{let J=Z.file_path;return`Undoing changes to ${J?b$(J):"file"}`}case"Skill":return`Invoking skill: ${Z.skill}`;case"Task":{let{description:J,subagent_type:Y}=Z,U=Z.resume_from||Z.resume;if(U)return`Resuming ${Y||"agent"} from ${U}`;if(J)return`${Y||"Agent"}: ${J}`;return`Running ${Y||"agent"}`}case"LSP":{let{operation:J,filePath:Y}=Z,U=Y?b$(Y):"file";return`LSP ${J} in ${U}`}case"NotebookEdit":{let J=Z.notebook_path;return`Editing notebook: ${J?b$(J):"notebook"}`}default:return`${$}`}}function nU($,Z){if(!Z?.success&&!Z?.metadata)return!1;switch($){case"Write":case"Edit":case"ApplyPatch":case"Read":case"Glob":case"Grep":case"Bash":case"TaskOutput":return!0;case"WebFetch":case"WebSearch":return!0;case"TaskCreate":case"TaskGet":case"TaskUpdate":case"TaskList":return!1;default:return!!Z.metadata?.detail}}function rU($,Z){if(!Z?.success)return null;switch($){case"Glob":{if(!a8(Z.metadata))return null;let{matches:J}=Z.metadata;if(!J?.length)return null;let Y=5,U=J.slice(0,Y).map((X)=>X.relative_path);if(J.length>Y)U.push(`... (+${J.length-Y} more)`);return U.join(`
|
|
687
687
|
`)}case"Grep":{let J=Z.llmContent;if(!Array.isArray(J)||!J.length)return null;let Y=5,U=J.slice(0,Y).map((X)=>{let H=b$(X.file_path);if(X.line_number)return`${H}:${X.line_number}`;return H});if(J.length>Y)U.push(`... (+${J.length-Y} more)`);return U.join(`
|
|
688
688
|
`)}case"Read":{let J=Z.metadata?.content_preview||Z.llmContent;if(typeof J!=="string"||!J)return null;let Y=J.split(`
|
|
689
689
|
`),U=Y.length,X=3;if(U<=X+1)return J;return`${Y.slice(0,X).join(`
|
|
@@ -740,7 +740,7 @@ Usage notes:
|
|
|
740
740
|
- Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent
|
|
741
741
|
- If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.
|
|
742
742
|
- If the user specifies that they want you to run agents "in parallel", you MUST send a single message with multiple Task tool use content blocks. For example, if you need to launch both a code-reviewer agent and a test-runner agent in parallel, send a single message with both tool calls.
|
|
743
|
-
`.trim()}function L2($=T$(),Z,J,Y,U,X,H,Q){return T({name:"Task",displayName:"Subagent Scheduler",kind:"readonly",isReadOnly:!0,isConcurrencySafe:!1,parallelism:"shared",schema:_.Object({subagent_type:_.Optional(_.Refine(_.String({description:"Subagent type to use. Required for a fresh run; optional for resume_from."}),(W)=>oU($,W),(W)=>`Invalid subagent type: "${W}". Available: ${sU($)}`)),description:_.String({minLength:3,maxLength:100,description:"Short task description (3-5 words)"}),prompt:_.String({minLength:10,description:"Detailed task instructions"}),run_in_background:f(_.Boolean({description:"Set true to run in the background. Use TaskOutput to read output later."}),!1),isolation:_.Optional(d(["none","worktree"],{description:"Filesystem isolation. Use worktree to prevent edits affecting the parent workspace."})),resume:_.Optional(_.String({description:"Deprecated alias for resume_from."})),resume_from:_.Optional(_.String({description:"Completed agent ID to resume. The source type, model, permissions, workspace, and transcript are inherited."})),subagent_session_id:_.Optional(_.String({description:"Internal subagent session id for tracking"}))}),description:{short:"Launch a new agent to handle complex, multi-step tasks autonomously",get long(){return tU($)},usageNotes:["subagent_type is required - choose from available agent types",'description should be 3-5 words (e.g., "Explore error handling")',"prompt should contain a highly detailed task description and specify exactly what information to return","Launch multiple agents concurrently when possible for better performance",'Use isolation="worktree" for parallel coding agents that may edit files'],examples:[{description:"Explore codebase for API endpoints",params:{subagent_type:"Explore",description:"Find API endpoints",prompt:"Search the codebase for all API endpoint definitions. Look for route handlers, REST endpoints, and GraphQL resolvers. Return a structured list with file paths, endpoint URLs, HTTP methods, and descriptions."}},{description:"Plan authentication feature",params:{subagent_type:"Plan",description:"Plan user auth",prompt:"Create a detailed implementation plan for adding user authentication to this project. Analyze the existing architecture, then provide step-by-step instructions including: 1) Database schema changes 2) API routes to create 3) Frontend components needed 4) Security considerations 5) Testing strategy. Be specific about file names and code locations."}}]},async execute(W,z){let{subagent_type:V,description:B,prompt:K,run_in_background:G=!1,isolation:O,resume:E,resume_from:q,subagent_session_id:F}=W,D=q??E,L=$X(z);if(!L)return j$("Task requires an active parent session and absolute workspace","Subagent 缺少 durable parent session owner");let A=U?.(),w=X?.(),j=H?.(),b=Q?.(),P=o.getInstance(),M=D?P.getAgent(D,L):void 0;if(D&&!M)return j$(`Cannot resume agent ${D}: session not found in this workspace`,`恢复 Agent 失败: 会话不存在 ${D}`);if(M&&(P.isRunning(M.id)||M.status==="running"))return j$(`Cannot resume agent ${M.id}: it is still running`,`恢复 Agent 失败: 仍在运行 ${M.id}`);if(M&&V&&M.subagentType!==V)return j$(`Cannot resume with subagent_type "${V}": source agent used "${M.subagentType}"`,"恢复 Agent 失败: subagent 类型与源运行不一致");let C=M?.subagentType??V;if(!C)return j$("subagent_type is required for a fresh Task run","启动 Agent 失败: 缺少 subagent_type");let S=$.getSubagent(C),m=(M?.configSnapshot?{...M.configSnapshot}:void 0)??S;if(!m)return j$(`Unknown subagent type: ${C}. Available types: ${$.getAllNames().join(", ")||"none"}`,`未知的 subagent 类型: ${C}`);let c={...m,model:m.model&&m.model!=="inherit"?m.model:z.modelId??m.model,permissionMode:m.permissionMode??z.permissionMode},U0=typeof F==="string"&&F.length>0?F:z$("agent"),$$=M?.isolation??O??c.isolation??"none",b0=M?.rootAgentId??U0,Z$=M?M.resumeDepth+1:0,r=ZX({owner:L,subagentSessionId:U0,type:c.name,description:B,resumedFrom:M?.id,rootAgentId:b0,resumeDepth:Z$});if(G){let J$=M?P.resumeAgent({agentId:M.id,prompt:K,config:c,owner:L,permissionMode:z.permissionMode,reasoningEffort:A,serviceTier:w,responseVerbosity:j,communicationStyle:b,newAgentId:U0,agentResources:Z,modelResources:J,lspResources:Y,onEvent:r.onEvent,onCompleted:r.onCompleted})?.agentId:P.startBackgroundAgent({config:c,description:B,prompt:K,parentSessionId:L.sessionId,parentProjectPath:L.projectPath,permissionMode:z.permissionMode,reasoningEffort:A,serviceTier:w,responseVerbosity:j,communicationStyle:b,agentId:U0,workspaceRoot:L.projectPath,isolation:$$,agentResources:Z,modelResources:J,lspResources:Y,onEvent:r.onEvent,onCompleted:r.onCompleted});if(!J$)return j$(`Failed to resume agent ${M?.id??U0}`,"恢复 Agent 失败");return r.onStarted(),YX({sessionId:J$,config:c,description:B,isolation:$$,resumedFrom:M?.id,rootAgentId:b0,resumeDepth:Z$})}return JX({config:c,description:B,prompt:K,context:z,owner:L,subagentSessionId:U0,isolation:$$,source:M,eventBridge:r,agentResources:Z,modelResources:J,lspResources:Y,reasoningEffort:A,serviceTier:w,responseVerbosity:j,communicationStyle:b})},version:"5.0.0",category:"Subagent",tags:["task","subagent","delegation","explore","plan"],extractSignatureContent:(W)=>`${W.subagent_type||"resume"}:${W.resume_from||W.resume||""}:${W.description}`,abstractPermissionRule:()=>""})}var eU=L2(Z9);function $X($){if(!$.sessionId)return;let Z=$.workspaceRoot||N();if(!e8.isAbsolute(Z))return;return{sessionId:$.sessionId,projectPath:e8.resolve(Z)}}function j$($,Z){return{success:!1,llmContent:$,error:{type:"execution_error",message:$},metadata:{summary:Z}}}function ZX($){let Z=aU(8),J=!1,Y={resumedFrom:$.resumedFrom,rootAgentId:$.rootAgentId,resumeDepth:$.resumeDepth};return{onStarted:()=>{w2.getState().app.actions.startSubagentProgress(Z,$.type,$.description),Z0.publish($.owner,"subagent.start",{subagentId:Z,subagentSessionId:$.subagentSessionId,type:$.type,description:$.description,...Y})},onEvent:(U)=>{switch(U.kind){case"tool_start":{let X=U.toolCall,H="function"in X?X.function.name:"Unknown";if(w2.getState().app.actions.updateSubagentTool(Z,H),Z0.publish($.owner,"subagent.update",{subagentSessionId:$.subagentSessionId,toolName:H}),"function"in X)Z0.publish($.owner,"subagent.tool.start",{subagentSessionId:$.subagentSessionId,toolCallId:X.id,toolName:H,arguments:X.function.arguments,toolKind:U.toolKind});break}case"tool_result":{let X=U.toolCall;if(!("function"in X))break;Z0.publish($.owner,"subagent.tool.result",{subagentSessionId:$.subagentSessionId,toolCallId:X.id,toolName:X.function.name,success:!U.result.error,summary:U.result.metadata?.summary,output:t8(s8(X.function.name,U.result)),metadata:U.result.metadata});break}case"tool_progress":{let X=U.toolCall;if(!("function"in X))break;Z0.publish($.owner,"subagent.tool.progress",{subagentSessionId:$.subagentSessionId,toolCallId:X.id,toolName:X.function.name,...U.update});break}case"content_delta":Z0.publish($.owner,"subagent.delta",{subagentSessionId:$.subagentSessionId,delta:U.delta});break;case"thinking_delta":Z0.publish($.owner,"subagent.thinking.delta",{subagentSessionId:$.subagentSessionId,delta:U.delta});break;case"stream_end":Z0.publish($.owner,"subagent.stream.end",{subagentSessionId:$.subagentSessionId});break;default:break}},onCompleted:(U)=>{if(J)return;J=!0,w2.getState().app.actions.completeSubagentProgress(Z,U.status==="completed"),Z0.publish($.owner,"subagent.complete",{subagentSessionId:$.subagentSessionId,success:U.status==="completed",status:U.status,summary:U.result?.message?.slice(0,500),type:U.subagentType,verificationVerdict:U.result?.verificationVerdict,...Y})}}}async function JX($){let{config:Z,description:J,prompt:Y,context:U,owner:X,subagentSessionId:H,isolation:Q,source:W,eventBridge:z,agentResources:V,modelResources:B,lspResources:K}=$,G=Q$.getInstance(),O=W?.workspaceRoot??X.projectPath,E=W?.rootAgentId??H,q=W?W.resumeDepth+1:0,F,D=!1,L=!1,A=async(w)=>{if(!F||D)return;let j=await J1.finalize({agentId:H,lease:F,success:w});return D=!0,j};try{F=await J1.prepare({agentId:H,sourceWorkspaceRoot:O,isolation:Q,restoredWorktree:W?.worktree});let w=Date.now();G.saveSession({schemaVersion:2,id:H,subagentType:Z.name,description:J,prompt:Y,messages:[...W?.messages??[]],status:"running",createdAt:w,lastActiveAt:w,processId:process.pid,parentSessionId:X.sessionId,parentProjectPath:X.projectPath,rootAgentId:E,resumedFrom:W?.id,resumeDepth:q,configSnapshot:Q2(Z),workspaceRoot:O,isolation:Q,worktree:F.worktree}),L=!0,z.onStarted(),U.updateOutput?.(`${W?"恢复":"启动"} ${Z.name} subagent: ${J}`);let j=new L6(Z,V,B,K),b={prompt:Y,parentSessionId:X.sessionId,permissionMode:Z.permissionMode??U.permissionMode,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,subagentSessionId:H,resumedFrom:W?.id,rootAgentId:E,resumeDepth:q,workspaceRoot:F.workspaceRoot,worktreeActive:Boolean(F.worktree),existingMessages:W?.messages,onEvent:z.onEvent},P=Date.now(),M=await j.execute(b);try{let p=await G0.getInstance().executeSubagentStopHooks(Z.name,{projectDir:F.workspaceRoot,sessionId:X.sessionId,permissionMode:Z.permissionMode??U.permissionMode??"default",taskDescription:J,success:M.success,resultSummary:M.message.slice(0,500),error:M.error});if(!p.shouldStop&&p.continueReason)M=await j.execute({...b,prompt:p.continueReason,existingMessages:M.messages});if(p.warning)console.warn(`[Task] SubagentStop hook warning: ${p.warning}`)}catch(p){console.warn("[Task] SubagentStop hook execution failed:",p)}let C=await A(M.success);if(C?.preserved)M.worktreePath=C.worktreePath,M.worktreeBranch=C.worktreeBranch,M.worktree=C.worktree;G.updateSession(H,{messages:M.messages??[],worktree:C?.worktree});let S=G.markCompleted(H,{success:M.success,message:M.message,error:M.error,verificationCommands:M.verificationCommands,verificationVerdict:M.verificationVerdict,modifiedFiles:M.modifiedFiles},{...M.stats,duration:Date.now()-P});if(S)z.onCompleted(S);return UX({result:M,sessionId:H,config:Z,description:J,isolation:Q,resumedFrom:W?.id,rootAgentId:E,resumeDepth:q})}catch(w){let j=w,b;try{b=await A(!1)}catch(P){console.warn("[Task] Failed to preserve subagent worktree:",P)}if(L){let P=G.markCompleted(H,{success:!1,message:"",error:j.message});if(P)z.onCompleted(P)}return{...j$(`Subagent execution error: ${j.message}`,`Subagent 执行异常: ${$9(j)}`),metadata:{summary:`Subagent 执行异常: ${$9(j)}`,subagentSessionId:H,subagentType:Z.name,subagentStatus:"failed",subagentResumedFrom:W?.id,subagentRootId:E,subagentResumeDepth:q,isolation:Q,worktreePath:b?.worktreePath,worktreeBranch:b?.worktreeBranch}}}}function YX($){return{success:!0,llmContent:{agent_id:$.sessionId,status:"running",resumed_from:$.resumedFrom,resume_from_hint:$.sessionId,message:`Agent ${$.resumedFrom?"resumed":"started"} in background. Use TaskOutput(task_id: "${$.sessionId}") to retrieve results.`},metadata:{summary:`${$.resumedFrom?"恢复":"启动"}后台 Agent: ${$.sessionId}`,agent_id:$.sessionId,resume_from_hint:$.sessionId,resumed_from:$.resumedFrom,subagent_type:$.config.name,description:$.description,background:!0,isolation:$.isolation,subagentSessionId:$.sessionId,subagentType:$.config.name,subagentStatus:"running",subagentResumedFrom:$.resumedFrom,subagentRootId:$.rootAgentId,subagentResumeDepth:$.resumeDepth}}}function UX($){let Z=$.result.worktreePath?`
|
|
743
|
+
`.trim()}function L2($=j$(),Z,J,Y,U,X,H,Q){return j({name:"Task",displayName:"Subagent Scheduler",kind:"readonly",isReadOnly:!0,isConcurrencySafe:!1,parallelism:"shared",schema:_.Object({subagent_type:_.Optional(_.Refine(_.String({description:"Subagent type to use. Required for a fresh run; optional for resume_from."}),(W)=>oU($,W),(W)=>`Invalid subagent type: "${W}". Available: ${sU($)}`)),description:_.String({minLength:3,maxLength:100,description:"Short task description (3-5 words)"}),prompt:_.String({minLength:10,description:"Detailed task instructions"}),run_in_background:f(_.Boolean({description:"Set true to run in the background. Use TaskOutput to read output later."}),!1),isolation:_.Optional(d(["none","worktree"],{description:"Filesystem isolation. Use worktree to prevent edits affecting the parent workspace."})),resume:_.Optional(_.String({description:"Deprecated alias for resume_from."})),resume_from:_.Optional(_.String({description:"Completed agent ID to resume. The source type, model, permissions, workspace, and transcript are inherited."})),subagent_session_id:_.Optional(_.String({description:"Internal subagent session id for tracking"}))}),description:{short:"Launch a new agent to handle complex, multi-step tasks autonomously",get long(){return tU($)},usageNotes:["subagent_type is required - choose from available agent types",'description should be 3-5 words (e.g., "Explore error handling")',"prompt should contain a highly detailed task description and specify exactly what information to return","Launch multiple agents concurrently when possible for better performance",'Use isolation="worktree" for parallel coding agents that may edit files'],examples:[{description:"Explore codebase for API endpoints",params:{subagent_type:"Explore",description:"Find API endpoints",prompt:"Search the codebase for all API endpoint definitions. Look for route handlers, REST endpoints, and GraphQL resolvers. Return a structured list with file paths, endpoint URLs, HTTP methods, and descriptions."}},{description:"Plan authentication feature",params:{subagent_type:"Plan",description:"Plan user auth",prompt:"Create a detailed implementation plan for adding user authentication to this project. Analyze the existing architecture, then provide step-by-step instructions including: 1) Database schema changes 2) API routes to create 3) Frontend components needed 4) Security considerations 5) Testing strategy. Be specific about file names and code locations."}}]},async execute(W,z){let{subagent_type:V,description:B,prompt:K,run_in_background:G=!1,isolation:O,resume:E,resume_from:q,subagent_session_id:F}=W,D=q??E,L=$X(z);if(!L)return T$("Task requires an active parent session and absolute workspace","Subagent 缺少 durable parent session owner");let A=U?.(),w=X?.(),T=H?.(),b=Q?.(),P=o.getInstance(),M=D?P.getAgent(D,L):void 0;if(D&&!M)return T$(`Cannot resume agent ${D}: session not found in this workspace`,`恢复 Agent 失败: 会话不存在 ${D}`);if(M&&(P.isRunning(M.id)||M.status==="running"))return T$(`Cannot resume agent ${M.id}: it is still running`,`恢复 Agent 失败: 仍在运行 ${M.id}`);if(M&&V&&M.subagentType!==V)return T$(`Cannot resume with subagent_type "${V}": source agent used "${M.subagentType}"`,"恢复 Agent 失败: subagent 类型与源运行不一致");let C=M?.subagentType??V;if(!C)return T$("subagent_type is required for a fresh Task run","启动 Agent 失败: 缺少 subagent_type");let S=$.getSubagent(C),m=(M?.configSnapshot?{...M.configSnapshot}:void 0)??S;if(!m)return T$(`Unknown subagent type: ${C}. Available types: ${$.getAllNames().join(", ")||"none"}`,`未知的 subagent 类型: ${C}`);let c={...m,model:m.model&&m.model!=="inherit"?m.model:z.modelId??m.model,permissionMode:m.permissionMode??z.permissionMode},U0=typeof F==="string"&&F.length>0?F:z$("agent"),$$=M?.isolation??O??c.isolation??"none",b0=M?.rootAgentId??U0,Z$=M?M.resumeDepth+1:0,r=ZX({owner:L,subagentSessionId:U0,type:c.name,description:B,resumedFrom:M?.id,rootAgentId:b0,resumeDepth:Z$});if(G){let J$=M?P.resumeAgent({agentId:M.id,prompt:K,config:c,owner:L,permissionMode:z.permissionMode,reasoningEffort:A,serviceTier:w,responseVerbosity:T,communicationStyle:b,newAgentId:U0,agentResources:Z,modelResources:J,lspResources:Y,onEvent:r.onEvent,onCompleted:r.onCompleted})?.agentId:P.startBackgroundAgent({config:c,description:B,prompt:K,parentSessionId:L.sessionId,parentProjectPath:L.projectPath,permissionMode:z.permissionMode,reasoningEffort:A,serviceTier:w,responseVerbosity:T,communicationStyle:b,agentId:U0,workspaceRoot:L.projectPath,isolation:$$,agentResources:Z,modelResources:J,lspResources:Y,onEvent:r.onEvent,onCompleted:r.onCompleted});if(!J$)return T$(`Failed to resume agent ${M?.id??U0}`,"恢复 Agent 失败");return r.onStarted(),YX({sessionId:J$,config:c,description:B,isolation:$$,resumedFrom:M?.id,rootAgentId:b0,resumeDepth:Z$})}return JX({config:c,description:B,prompt:K,context:z,owner:L,subagentSessionId:U0,isolation:$$,source:M,eventBridge:r,agentResources:Z,modelResources:J,lspResources:Y,reasoningEffort:A,serviceTier:w,responseVerbosity:T,communicationStyle:b})},version:"5.0.0",category:"Subagent",tags:["task","subagent","delegation","explore","plan"],extractSignatureContent:(W)=>`${W.subagent_type||"resume"}:${W.resume_from||W.resume||""}:${W.description}`,abstractPermissionRule:()=>""})}var eU=L2(Z9);function $X($){if(!$.sessionId)return;let Z=$.workspaceRoot||N();if(!e8.isAbsolute(Z))return;return{sessionId:$.sessionId,projectPath:e8.resolve(Z)}}function T$($,Z){return{success:!1,llmContent:$,error:{type:"execution_error",message:$},metadata:{summary:Z}}}function ZX($){let Z=aU(8),J=!1,Y={resumedFrom:$.resumedFrom,rootAgentId:$.rootAgentId,resumeDepth:$.resumeDepth};return{onStarted:()=>{w2.getState().app.actions.startSubagentProgress(Z,$.type,$.description),Z0.publish($.owner,"subagent.start",{subagentId:Z,subagentSessionId:$.subagentSessionId,type:$.type,description:$.description,...Y})},onEvent:(U)=>{switch(U.kind){case"tool_start":{let X=U.toolCall,H="function"in X?X.function.name:"Unknown";if(w2.getState().app.actions.updateSubagentTool(Z,H),Z0.publish($.owner,"subagent.update",{subagentSessionId:$.subagentSessionId,toolName:H}),"function"in X)Z0.publish($.owner,"subagent.tool.start",{subagentSessionId:$.subagentSessionId,toolCallId:X.id,toolName:H,arguments:X.function.arguments,toolKind:U.toolKind});break}case"tool_result":{let X=U.toolCall;if(!("function"in X))break;Z0.publish($.owner,"subagent.tool.result",{subagentSessionId:$.subagentSessionId,toolCallId:X.id,toolName:X.function.name,success:!U.result.error,summary:U.result.metadata?.summary,output:t8(s8(X.function.name,U.result)),metadata:U.result.metadata});break}case"tool_progress":{let X=U.toolCall;if(!("function"in X))break;Z0.publish($.owner,"subagent.tool.progress",{subagentSessionId:$.subagentSessionId,toolCallId:X.id,toolName:X.function.name,...U.update});break}case"content_delta":Z0.publish($.owner,"subagent.delta",{subagentSessionId:$.subagentSessionId,delta:U.delta});break;case"thinking_delta":Z0.publish($.owner,"subagent.thinking.delta",{subagentSessionId:$.subagentSessionId,delta:U.delta});break;case"stream_end":Z0.publish($.owner,"subagent.stream.end",{subagentSessionId:$.subagentSessionId});break;default:break}},onCompleted:(U)=>{if(J)return;J=!0,w2.getState().app.actions.completeSubagentProgress(Z,U.status==="completed"),Z0.publish($.owner,"subagent.complete",{subagentSessionId:$.subagentSessionId,success:U.status==="completed",status:U.status,summary:U.result?.message?.slice(0,500),type:U.subagentType,verificationVerdict:U.result?.verificationVerdict,...Y})}}}async function JX($){let{config:Z,description:J,prompt:Y,context:U,owner:X,subagentSessionId:H,isolation:Q,source:W,eventBridge:z,agentResources:V,modelResources:B,lspResources:K}=$,G=Q$.getInstance(),O=W?.workspaceRoot??X.projectPath,E=W?.rootAgentId??H,q=W?W.resumeDepth+1:0,F,D=!1,L=!1,A=async(w)=>{if(!F||D)return;let T=await J1.finalize({agentId:H,lease:F,success:w});return D=!0,T};try{F=await J1.prepare({agentId:H,sourceWorkspaceRoot:O,isolation:Q,restoredWorktree:W?.worktree});let w=Date.now();G.saveSession({schemaVersion:2,id:H,subagentType:Z.name,description:J,prompt:Y,messages:[...W?.messages??[]],status:"running",createdAt:w,lastActiveAt:w,processId:process.pid,parentSessionId:X.sessionId,parentProjectPath:X.projectPath,rootAgentId:E,resumedFrom:W?.id,resumeDepth:q,configSnapshot:Q2(Z),workspaceRoot:O,isolation:Q,worktree:F.worktree}),L=!0,z.onStarted(),U.updateOutput?.(`${W?"恢复":"启动"} ${Z.name} subagent: ${J}`);let T=new L6(Z,V,B,K),b={prompt:Y,parentSessionId:X.sessionId,permissionMode:Z.permissionMode??U.permissionMode,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,subagentSessionId:H,resumedFrom:W?.id,rootAgentId:E,resumeDepth:q,workspaceRoot:F.workspaceRoot,worktreeActive:Boolean(F.worktree),existingMessages:W?.messages,onEvent:z.onEvent},P=Date.now(),M=await T.execute(b);try{let p=await G0.getInstance().executeSubagentStopHooks(Z.name,{projectDir:F.workspaceRoot,sessionId:X.sessionId,permissionMode:Z.permissionMode??U.permissionMode??"default",taskDescription:J,success:M.success,resultSummary:M.message.slice(0,500),error:M.error});if(!p.shouldStop&&p.continueReason)M=await T.execute({...b,prompt:p.continueReason,existingMessages:M.messages});if(p.warning)console.warn(`[Task] SubagentStop hook warning: ${p.warning}`)}catch(p){console.warn("[Task] SubagentStop hook execution failed:",p)}let C=await A(M.success);if(C?.preserved)M.worktreePath=C.worktreePath,M.worktreeBranch=C.worktreeBranch,M.worktree=C.worktree;G.updateSession(H,{messages:M.messages??[],worktree:C?.worktree});let S=G.markCompleted(H,{success:M.success,message:M.message,error:M.error,verificationCommands:M.verificationCommands,verificationVerdict:M.verificationVerdict,modifiedFiles:M.modifiedFiles},{...M.stats,duration:Date.now()-P});if(S)z.onCompleted(S);return UX({result:M,sessionId:H,config:Z,description:J,isolation:Q,resumedFrom:W?.id,rootAgentId:E,resumeDepth:q})}catch(w){let T=w,b;try{b=await A(!1)}catch(P){console.warn("[Task] Failed to preserve subagent worktree:",P)}if(L){let P=G.markCompleted(H,{success:!1,message:"",error:T.message});if(P)z.onCompleted(P)}return{...T$(`Subagent execution error: ${T.message}`,`Subagent 执行异常: ${$9(T)}`),metadata:{summary:`Subagent 执行异常: ${$9(T)}`,subagentSessionId:H,subagentType:Z.name,subagentStatus:"failed",subagentResumedFrom:W?.id,subagentRootId:E,subagentResumeDepth:q,isolation:Q,worktreePath:b?.worktreePath,worktreeBranch:b?.worktreeBranch}}}}function YX($){return{success:!0,llmContent:{agent_id:$.sessionId,status:"running",resumed_from:$.resumedFrom,resume_from_hint:$.sessionId,message:`Agent ${$.resumedFrom?"resumed":"started"} in background. Use TaskOutput(task_id: "${$.sessionId}") to retrieve results.`},metadata:{summary:`${$.resumedFrom?"恢复":"启动"}后台 Agent: ${$.sessionId}`,agent_id:$.sessionId,resume_from_hint:$.sessionId,resumed_from:$.resumedFrom,subagent_type:$.config.name,description:$.description,background:!0,isolation:$.isolation,subagentSessionId:$.sessionId,subagentType:$.config.name,subagentStatus:"running",subagentResumedFrom:$.resumedFrom,subagentRootId:$.rootAgentId,subagentResumeDepth:$.resumeDepth}}}function UX($){let Z=$.result.worktreePath?`
|
|
744
744
|
|
|
745
745
|
Worktree preserved at ${$.result.worktreePath}${$.result.worktreeBranch?` on branch ${$.result.worktreeBranch}`:""}.`:"",J=`
|
|
746
746
|
|
|
@@ -789,7 +789,7 @@ Only mark a task completed when it is fully accomplished. If tests are failing,
|
|
|
789
789
|
|
|
790
790
|
Status progresses: pending -> in_progress -> completed
|
|
791
791
|
|
|
792
|
-
Use deleted to permanently remove a task. Read the latest state with TaskGet before making risky updates.`;function
|
|
792
|
+
Use deleted to permanently remove a task. Read the latest state with TaskGet before making risky updates.`;function T6($){return[VX($),BX($),KX($),_X($)]}function VX($){let{sessionId:Z,configDir:J}=$;return j({name:"TaskCreate",displayName:"Task Create",kind:"readonly",isConcurrencySafe:!1,schema:_.Object({subject:_.String({minLength:1,description:"A brief title for the task"}),description:_.String({minLength:1,description:"What needs to be done"}),activeForm:_.Optional(_.String({description:"Present continuous form shown while in_progress"})),owner:_.Optional(_.String({description:"Optional owner for the task"})),priority:f(d(["high","medium","low"]),"medium"),metadata:_.Optional(_.Record(_.String(),_.Unknown()))}),description:{short:"Create a new task in the task list",long:WX},async execute(Y,U){try{let X=j2(U,Z,J),H=await X.createTask(Y),Q=await X.listTasks(),W=X.getStats();return T2({llmContent:{task:c$(H),tasks:Q.map(c$),stats:W},summary:`创建任务 #${H.id}: ${H.subject}`,tasks:Q,stats:W})}catch(X){return M2(X,"创建任务失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:(Y)=>Y.subject,abstractPermissionRule:()=>"*"})}function BX($){let{sessionId:Z,configDir:J}=$;return j({name:"TaskGet",displayName:"Task Get",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({taskId:_.String({minLength:1,description:"The ID of the task to retrieve"})}),description:{short:"Retrieve a task by ID",long:"Use this tool to inspect the latest state of a task before updating it."},async execute(Y,U){try{let H=await j2(U,Z,J).getTask(Y.taskId);return{success:!0,llmContent:{task:H?c$(H):null},metadata:{summary:H?`读取任务 #${H.id}`:`任务 #${Y.taskId} 不存在`}}}catch(X){return M2(X,"读取任务失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:(Y)=>Y.taskId,abstractPermissionRule:()=>"*"})}function KX($){let{sessionId:Z,configDir:J}=$;return j({name:"TaskUpdate",displayName:"Task Update",kind:"readonly",isConcurrencySafe:!1,schema:_.Object({taskId:_.String({minLength:1,description:"The ID of the task to update"}),subject:_.Optional(_.String({minLength:1,description:"New subject for the task"})),description:_.Optional(_.String({minLength:1,description:"New description for the task"})),activeForm:_.Optional(_.String({minLength:1})),status:_.Optional(_.Union([b6,_.Literal("deleted")])),owner:_.Optional(_.String()),addBlocks:_.Optional(_.Array(_.String())),addBlockedBy:_.Optional(_.Array(_.String())),metadata:_.Optional(_.Record(_.String(),_.Unknown()))}),description:{short:"Update a task in the task list",long:zX},async execute(Y,U){try{let X=j2(U,Z,J),H=Y.status;if(H==="deleted"){let K=await X.deleteTask(Y.taskId),G=await X.listTasks(),O=X.getStats();return T2({llmContent:{success:K,taskId:Y.taskId,updatedFields:K?["deleted"]:[],error:K?void 0:"Task not found",tasks:G.map(c$),stats:O},summary:K?`删除任务 #${Y.taskId}`:`任务 #${Y.taskId} 不存在`,tasks:G,stats:O})}let{task:Q,updatedFields:W,statusChange:z}=await X.updateTask(Y.taskId,{subject:Y.subject,description:Y.description,activeForm:Y.activeForm,status:H,owner:Y.owner,addBlocks:Y.addBlocks,addBlockedBy:Y.addBlockedBy,metadata:Y.metadata}),V=await X.listTasks(),B=X.getStats();return T2({llmContent:{success:Q!==null,taskId:Y.taskId,task:Q?c$(Q):null,updatedFields:W,error:Q?void 0:"Task not found",statusChange:z,tasks:V.map(c$),stats:B},summary:Q?`更新任务 #${Y.taskId}`:`任务 #${Y.taskId} 不存在`,tasks:V,stats:B})}catch(X){return M2(X,"更新任务失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:(Y)=>Y.taskId,abstractPermissionRule:()=>"*"})}function _X($){let{sessionId:Z,configDir:J}=$;return j({name:"TaskList",displayName:"Task List",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({}),description:{short:"List all tasks",long:"Use this tool to check the current task list and avoid creating duplicate tasks."},async execute(Y,U){try{let X=j2(U,Z,J),H=await X.listTasks(),Q=X.getStats();return T2({llmContent:{tasks:H.map(c$),stats:Q},summary:H.length===0?"暂无任务":`任务列表 (${Q.completed}/${Q.total} 完成)`,tasks:H,stats:Q})}catch(X){return M2(X,"读取任务列表失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:()=>"*",abstractPermissionRule:()=>"*"})}function j2($,Z,J){return p$.getInstance($.taskListId||$.sessionId||Z,J)}function T2($){return{success:!0,llmContent:$.llmContent,metadata:{summary:$.summary,tasks:$.tasks,stats:$.stats}}}function M2($,Z){let J=$;return{success:!1,llmContent:`Task operation failed: ${J.message}`,error:{type:"execution_error",message:J.message,details:$},metadata:{summary:Z}}}function c$($){return{id:$.id,subject:$.subject,description:$.description,status:$.status,activeForm:$.activeForm,owner:$.owner,priority:$.priority,blocks:$.blocks,blockedBy:$.blockedBy,metadata:$.metadata}}import GX from"node:path";var j6=j({name:"TaskOutput",displayName:"Task Output",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({task_id:_.String({minLength:1,description:"The task ID to get output from"}),block:f(_.Boolean({description:"Whether to wait for completion"}),!0),timeout:f(_.Number({minimum:0,maximum:600000,description:"Max wait time in ms"}),30000)}),description:{short:"Retrieves output from a running or completed task",long:`
|
|
793
793
|
- Retrieves output from a running or completed task (background shell, agent, or remote session)
|
|
794
794
|
- Takes a task_id parameter identifying the task
|
|
795
795
|
- Returns the task output along with status information
|
|
@@ -797,7 +797,7 @@ Use deleted to permanently remove a task. Read the latest state with TaskGet bef
|
|
|
797
797
|
- Use block=false for non-blocking check of current status
|
|
798
798
|
- Task IDs can be found using the /tasks command
|
|
799
799
|
- Works with all task types: background shells, async agents, and remote sessions
|
|
800
|
-
`.trim(),usageNotes:["task_id is required - the ID returned when starting a background task","block=true (default) waits for task completion","block=false returns current status immediately","timeout defaults to 30000ms (30 seconds), max 600000ms (10 minutes)"],examples:[{description:"Get output from a background shell",params:{task_id:"bash_abc123",block:!0,timeout:30000}},{description:"Check agent status without blocking",params:{task_id:"session_xyz789",block:!1}}]},async execute($,Z){let{task_id:J,block:Y,timeout:U}=$,X=Z.sessionId??"",H=Z.sessionId?{sessionId:Z.sessionId,projectPath:GX.resolve(Z.workspaceRoot||N())}:void 0;if(H){let z=u0.getInstance().get(J,H);if(J.startsWith("mcp_task_")||z)return OX(J,Y,U,H,Z.signal)}if(J.startsWith("bash_"))return U9(J,Y,U,X);let Q=s.getInstance(),W=o.getInstance();if(Q.getProcess(J,X))return U9(J,Y,U,X);if(H&&W.getAgent(J,H))return EX(J,Y,U,H);return{success:!1,llmContent:`Unknown task ID: ${J}.`,error:{type:"validation_error",message:`Unknown task ID: ${J}`},metadata:{summary:`获取任务输出: ${J} (未知ID)`}}},version:"1.0.0",category:"Task",tags:["task","output","background","shell","agent"],extractSignatureContent:($)=>$.task_id,abstractPermissionRule:()=>"*"});async function OX($,Z,J,Y,U){let X=u0.getInstance(),H=Z?await X.wait($,Y,J,U):X.get($,Y);if(!H)return{success:!1,llmContent:`MCP task not found: ${$}`,error:{type:"validation_error",message:"MCP task does not exist in this Session"},metadata:{summary:`获取 MCP 任务输出: ${$} (未找到)`}};let Q={task_id:H.taskId,type:"mcp",server:H.serverName,tool:H.toolName,status:H.status,status_message:H.statusMessage,created_at:new Date(H.createdAt).toISOString(),updated_at:new Date(H.updatedAt).toISOString(),completed_at:H.completedAt?new Date(H.completedAt).toISOString():void 0,result:H.result?.llmContent,error:H.error};return{success:!0,llmContent:Q,metadata:{summary:`获取 MCP 任务输出: ${$} (${H.status})`,...Q,taskType:"mcp",taskStatus:H.status,...H.result?{mcpResult:{isError:H.result.isError,...H.result.metadata}}:{}}}}async function U9($,Z,J,Y){let U=s.getInstance(),X=U.getProcess($,Y);if(!X)return{success:!1,llmContent:`Shell not found: ${$}`,error:{type:"execution_error",message:"Shell 会话不存在或已清理"},metadata:{summary:`获取任务输出: ${$} (未找到)`}};if(Z&&X.status==="running")await qX($,J,Y);let H=U.consumeOutput($,Y);if(!H)return{success:!1,llmContent:`Failed to get output for shell: ${$}`,error:{type:"execution_error",message:"Failed to consume output"},metadata:{summary:`获取任务输出: ${$} (失败)`}};let Q=s$.truncateForLLM(H.stdout,H.stderr,H.command),W=H.stdoutOmittedBytes??0,z=H.stderrOmittedBytes??0,V={task_id:H.id,type:"shell",status:H.status,command:H.command,pid:H.pid,exit_code:H.exitCode,signal:H.signal,sandboxed:H.sandboxed,started_at:new Date(H.startedAt).toISOString(),finished_at:H.endedAt?new Date(H.endedAt).toISOString():void 0,stdout:Q.stdout,stderr:Q.stderr,output_truncated:W>0||z>0||Boolean(Q.truncationInfo),stdout_omitted_bytes:W,stderr_omitted_bytes:z,truncation_info:Q.truncationInfo};return{success:!0,llmContent:V,metadata:{summary:`获取任务输出: ${$}`,...V}}}async function EX($,Z,J,Y){let U=o.getInstance(),X=U.getAgent($,Y);if(!X)return{success:!1,llmContent:`Agent not found: ${$}`,error:{type:"execution_error",message:"Agent 会话不存在或已清理"},metadata:{summary:`获取任务输出: ${$} (未找到)`}};if(Z&&X.status==="running"){if(X=await U.waitForCompletion($,J,Y),!X)return{success:!1,llmContent:`Failed to wait for agent: ${$}`,error:{type:"execution_error",message:"Wait for completion failed"},metadata:{summary:`获取任务输出: ${$} (等待失败)`}}}let H={task_id:X.id,type:"agent",status:X.status,subagent_type:X.subagentType,description:X.description,created_at:new Date(X.createdAt).toISOString(),last_active_at:new Date(X.lastActiveAt).toISOString(),completed_at:X.completedAt?new Date(X.completedAt).toISOString():void 0,result:X.result,stats:X.stats,isolation:X.isolation,worktree_path:X.worktree?.worktreeRoot,worktree_branch:X.worktree?.branch,resumed_from:X.resumedFrom,root_agent_id:X.rootAgentId,resume_depth:X.resumeDepth,resume_from_hint:X.id},Q=X.status==="completed"?"completed":X.status==="failed"?"failed":"running";return{success:!0,llmContent:H,metadata:{summary:`获取任务输出: ${$}`,...H,subagentSessionId:X.id,subagentType:X.subagentType,subagentStatus:Q,subagentResumedFrom:X.resumedFrom,subagentRootId:X.rootAgentId,subagentResumeDepth:X.resumeDepth,subagentSummary:typeof X.result?.message==="string"?X.result.message.slice(0,500):void 0,verificationCommands:X.result?.verificationCommands,verificationVerdict:X.result?.verificationVerdict,modifiedFiles:X.result?.modifiedFiles,verificationAgentBuiltin:X.subagentType===A2&&X.configSnapshot?.source==="builtin"}}}async function qX($,Z,J){let Y=s.getInstance(),U=Date.now();return new Promise((X)=>{let H=setInterval(()=>{let Q=Y.getProcess($,J);if(!Q||Q.status!=="running"){clearInterval(H),X();return}if(Date.now()-U>=Z){clearInterval(H),X();return}},100)})}import*as X9 from"os";import*as H9 from"path";import*as M$ from"fs/promises";import*as C1 from"path";class L0{static instances=new Map;teamsDir;constructor($){this.teamsDir=C1.join($,"teams")}static getInstance($){if(!L0.instances.has($))L0.instances.set($,new L0($));return L0.instances.get($)}static sanitizeName($){return $.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}getTeamFilePath($){return C1.join(this.teamsDir,L0.sanitizeName($),"config.json")}async createTeam($){let Z=await this.getUniqueTeamName($.name),J=Date.now(),Y=this.getTeamFilePath(Z),U={name:Z,description:$.description,createdAt:J,updatedAt:J,leadAgentId:`team-lead-${Z}`,leadSessionId:$.leadSessionId,teamFilePath:Y,members:[{id:`team-lead-${Z}`,name:"team-lead",subagentType:$.leadAgentType||"team-lead",description:"Team lead for coordinating the agent team",status:"leader",joinedAt:J},...$.members]};return await this.saveTeam(U),U}async loadTeam($){try{let Z=await M$.readFile(this.getTeamFilePath($),"utf-8");return FX(JSON.parse(Z))}catch(Z){if(Z.code!=="ENOENT")console.warn(`Failed to load team ${$}:`,Z);return}}async saveTeam($){let Z=this.getTeamFilePath($.name);await M$.mkdir(C1.dirname(Z),{recursive:!0,mode:493}),await M$.writeFile(Z,JSON.stringify({...$,teamFilePath:Z,updatedAt:Date.now()},null,2),"utf-8")}async listTeams(){try{let $=await M$.readdir(this.teamsDir,{withFileTypes:!0}),Z=[];for(let J of $){if(!J.isDirectory())continue;let Y=await this.loadTeam(J.name);if(Y)Z.push(Y)}return Z.sort((J,Y)=>Y.updatedAt-J.updatedAt)}catch($){if($.code!=="ENOENT")console.warn("Failed to list teams:",$);return[]}}async markDeleted($){let Z=await this.loadTeam($);if(!Z)return;let J=Date.now(),Y={...Z,deletedAt:J,updatedAt:J,members:Z.members.map((U)=>U.status==="running"?{...U,status:"cancelled",completedAt:U.completedAt||J}:U)};return await this.saveTeam(Y),Y}async getUniqueTeamName($){let Z=L0.sanitizeName($);if(!Z)throw Error("team_name must contain at least one letter or number");let J=Z,Y=2;while(await this.loadTeam(J))J=`${Z}-${Y}`,Y+=1;return J}}function FX($){if(!$||typeof $!=="object")return;let Z=$;if(!Z.name||!Array.isArray(Z.members))return;return{name:Z.name,description:Z.description,createdAt:typeof Z.createdAt==="number"?Z.createdAt:Date.now(),updatedAt:typeof Z.updatedAt==="number"?Z.updatedAt:Date.now(),deletedAt:typeof Z.deletedAt==="number"?Z.deletedAt:void 0,leadAgentId:Z.leadAgentId||`team-lead@${Z.name}`,leadSessionId:Z.leadSessionId,teamFilePath:Z.teamFilePath||"",members:Z.members.map((J)=>({id:J.id,name:J.name,subagentType:J.subagentType,description:J.description,prompt:J.prompt,agentId:J.agentId,status:J.status,joinedAt:J.joinedAt,completedAt:J.completedAt}))}}var DX=_.Object({name:_.String({minLength:1,description:"Human-readable teammate name, e.g. researcher or test-runner"}),subagent_type:_.String({minLength:1,description:"Registered subagent type to launch for this teammate"}),description:_.Optional(_.String({minLength:3,maxLength:100})),prompt:_.String({minLength:10,description:"Detailed assignment for this teammate"})});function C6($){let Z=$?.sessionId||`session_${Date.now()}`,J=$?.configDir||H9.join(X9.homedir(),".blade"),Y=$?.subagentRegistry??T$();return[wX({sessionId:Z,configDir:J,subagentRegistry:Y,agentResources:$?.agentResources,modelResources:$?.modelResources,lspResources:$?.lspResources,getReasoningEffort:$?.getReasoningEffort,getServiceTier:$?.getServiceTier,getResponseVerbosity:$?.getResponseVerbosity,getCommunicationStyle:$?.getCommunicationStyle}),AX({configDir:J}),LX({configDir:J})]}function wX($){return T({name:"TeamCreate",displayName:"Team Create",kind:"readonly",isConcurrencySafe:!1,schema:_.Object({team_name:_.String({minLength:1,description:"Name for the new agent team"}),description:_.Optional(_.String({description:"Team description or purpose"})),agent_type:_.Optional(_.String({description:"Optional role/type label for the team lead"})),members:f(_.Array(DX,{description:"Initial teammates to launch as background agents"}),[])}),description:{short:"Create an agent team and optionally launch teammate subagents",long:MX(),usageNotes:["Use TeamCreate when a task benefits from coordinated parallel agents","Each member is launched with the requested subagent_type as a background agent","Use TeamStatus to inspect teammate progress and collect agent IDs for TaskOutput"]},async execute(Z,J){try{NX($.subagentRegistry);let Y=TX(Z.members.map((K)=>K.name));if(Y)return C2(`Duplicate teammate name: ${Y}`,"创建团队失败");let U=Z.members.map((K)=>K.subagent_type).filter((K)=>!$.subagentRegistry.getSubagent(K));if(U.length>0)return C2(`Invalid subagent type(s): ${[...new Set(U)].join(", ")}. Available: ${$.subagentRegistry.getAllNames().join(", ")||"none"}`,"创建团队失败");let X=o.getInstance(),H=L0.getInstance($.configDir),Q=await H.createTeam({name:Z.team_name,description:Z.description,leadAgentType:Z.agent_type,leadSessionId:J.sessionId||$.sessionId,members:[]}),W=Date.now(),z=[];for(let K of Z.members){let G=$.subagentRegistry.getSubagent(K.subagent_type);if(!G)continue;let O={...G,model:G.model&&G.model!=="inherit"?G.model:J.modelId??G.model,permissionMode:G.permissionMode??J.permissionMode},E=`team-${L0.sanitizeName(K.name)}-${Q.name}`,q=bX({teamName:Q.name,teamDescription:Z.description,memberName:K.name,memberPrompt:K.prompt,teamFileHint:Q.teamFilePath}),F=X.startBackgroundAgent({config:O,description:K.description||K.name,prompt:q,parentSessionId:J.sessionId||$.sessionId,parentProjectPath:J.workspaceRoot||N(),permissionMode:J.permissionMode,reasoningEffort:$.getReasoningEffort?.(),serviceTier:$.getServiceTier?.(),responseVerbosity:$.getResponseVerbosity?.(),communicationStyle:$.getCommunicationStyle?.(),agentId:E,taskListId:Q.name,workspaceRoot:J.workspaceRoot||N(),isolation:O.isolation,agentResources:$.agentResources,modelResources:$.modelResources,lspResources:$.lspResources});z.push({id:E,name:K.name,subagentType:K.subagent_type,description:K.description||K.name,prompt:K.prompt,agentId:F,status:"running",joinedAt:W})}let V={...Q,members:[...Q.members,...z],updatedAt:Date.now()};await H.saveTeam(V);let B=await M6(H,V);return{success:!0,llmContent:{team:U1(B),message:z.length>0?`Team created with ${z.length} teammate(s). Use TeamStatus(team_name: "${B.name}") to inspect progress.`:`Team created. Use Task and TaskCreate tools to coordinate work for "${B.name}".`},metadata:{summary:`创建 Agent Team: ${B.name} (${z.length} teammates)`,team_name:B.name,team_file_path:B.teamFilePath,lead_agent_id:B.leadAgentId,member_agent_ids:z.map((K)=>K.agentId).filter(Boolean)}}}catch(Y){return f6(Y,"创建团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","agents","subagent","parallel"],extractSignatureContent:(Z)=>Z.team_name,abstractPermissionRule:()=>"*"})}function AX($){return T({name:"TeamStatus",displayName:"Team Status",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({team_name:_.Optional(_.String({description:"Team name to inspect. Omit to list all teams."}))}),description:{short:"List agent teams or inspect one team with teammate statuses",long:"Use this after TeamCreate to monitor teammate background agents and find their TaskOutput IDs."},async execute(Z){try{let J=L0.getInstance($.configDir);if(!Z.team_name){let X=await Promise.all((await J.listTeams()).map((H)=>M6(J,H)));return{success:!0,llmContent:{teams:X.map(U1)},metadata:{summary:X.length===0?"暂无 Agent Teams":`Agent Teams: ${X.length}`,teams:X.map(U1)}}}let Y=await J.loadTeam(Z.team_name);if(!Y)return C2(`Team not found: ${Z.team_name}`,"读取团队失败");let U=await M6(J,Y);return{success:!0,llmContent:{team:U1(U)},metadata:{summary:`Agent Team ${U.name}: ${Q9(U)}`,team:U1(U)}}}catch(J){return f6(J,"读取团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","status","agents"],extractSignatureContent:(Z)=>Z.team_name||"*",abstractPermissionRule:()=>"*"})}function LX($){return T({name:"TeamDelete",displayName:"Team Delete",kind:"readonly",isConcurrencySafe:!1,schema:_.Object({team_name:_.String({minLength:1,description:"Team name to delete"}),kill_running:f(_.Boolean({description:"Whether to cancel running teammate agents"}),!0)}),description:{short:"Mark an agent team deleted and optionally cancel running teammates",long:"Use this when coordinated team work is finished or should be stopped."},async execute(Z){try{let J=L0.getInstance($.configDir),Y=await J.loadTeam(Z.team_name);if(!Y)return C2(`Team not found: ${Z.team_name}`,"删除团队失败");let U=o.getInstance(),X=[];if(Z.kill_running){for(let Q of Y.members)if(Q.agentId&&U.killAgent(Q.agentId))X.push(Q.agentId)}let H=await J.markDeleted(Z.team_name);return{success:!0,llmContent:{team:H?U1(H):null,killed_agent_ids:X},metadata:{summary:`删除 Agent Team: ${Y.name}`,team_name:Y.name,killed_agent_ids:X}}}catch(J){return f6(J,"删除团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","delete","agents"],extractSignatureContent:(Z)=>Z.team_name,abstractPermissionRule:()=>"*"})}function NX($){if($.getAllNames().length===0)$.loadFromStandardLocations()}function bX($){return`
|
|
800
|
+
`.trim(),usageNotes:["task_id is required - the ID returned when starting a background task","block=true (default) waits for task completion","block=false returns current status immediately","timeout defaults to 30000ms (30 seconds), max 600000ms (10 minutes)"],examples:[{description:"Get output from a background shell",params:{task_id:"bash_abc123",block:!0,timeout:30000}},{description:"Check agent status without blocking",params:{task_id:"session_xyz789",block:!1}}]},async execute($,Z){let{task_id:J,block:Y,timeout:U}=$,X=Z.sessionId??"",H=Z.sessionId?{sessionId:Z.sessionId,projectPath:GX.resolve(Z.workspaceRoot||N())}:void 0;if(H){let z=u0.getInstance().get(J,H);if(J.startsWith("mcp_task_")||z)return OX(J,Y,U,H,Z.signal)}if(J.startsWith("bash_"))return U9(J,Y,U,X);let Q=s.getInstance(),W=o.getInstance();if(Q.getProcess(J,X))return U9(J,Y,U,X);if(H&&W.getAgent(J,H))return EX(J,Y,U,H);return{success:!1,llmContent:`Unknown task ID: ${J}.`,error:{type:"validation_error",message:`Unknown task ID: ${J}`},metadata:{summary:`获取任务输出: ${J} (未知ID)`}}},version:"1.0.0",category:"Task",tags:["task","output","background","shell","agent"],extractSignatureContent:($)=>$.task_id,abstractPermissionRule:()=>"*"});async function OX($,Z,J,Y,U){let X=u0.getInstance(),H=Z?await X.wait($,Y,J,U):X.get($,Y);if(!H)return{success:!1,llmContent:`MCP task not found: ${$}`,error:{type:"validation_error",message:"MCP task does not exist in this Session"},metadata:{summary:`获取 MCP 任务输出: ${$} (未找到)`}};let Q={task_id:H.taskId,type:"mcp",server:H.serverName,tool:H.toolName,status:H.status,status_message:H.statusMessage,created_at:new Date(H.createdAt).toISOString(),updated_at:new Date(H.updatedAt).toISOString(),completed_at:H.completedAt?new Date(H.completedAt).toISOString():void 0,result:H.result?.llmContent,error:H.error};return{success:!0,llmContent:Q,metadata:{summary:`获取 MCP 任务输出: ${$} (${H.status})`,...Q,taskType:"mcp",taskStatus:H.status,...H.result?{mcpResult:{isError:H.result.isError,...H.result.metadata}}:{}}}}async function U9($,Z,J,Y){let U=s.getInstance(),X=U.getProcess($,Y);if(!X)return{success:!1,llmContent:`Shell not found: ${$}`,error:{type:"execution_error",message:"Shell 会话不存在或已清理"},metadata:{summary:`获取任务输出: ${$} (未找到)`}};if(Z&&X.status==="running")await qX($,J,Y);let H=U.consumeOutput($,Y);if(!H)return{success:!1,llmContent:`Failed to get output for shell: ${$}`,error:{type:"execution_error",message:"Failed to consume output"},metadata:{summary:`获取任务输出: ${$} (失败)`}};let Q=s$.truncateForLLM(H.stdout,H.stderr,H.command),W=H.stdoutOmittedBytes??0,z=H.stderrOmittedBytes??0,V={task_id:H.id,type:"shell",status:H.status,command:H.command,pid:H.pid,exit_code:H.exitCode,signal:H.signal,sandboxed:H.sandboxed,started_at:new Date(H.startedAt).toISOString(),finished_at:H.endedAt?new Date(H.endedAt).toISOString():void 0,stdout:Q.stdout,stderr:Q.stderr,output_truncated:W>0||z>0||Boolean(Q.truncationInfo),stdout_omitted_bytes:W,stderr_omitted_bytes:z,truncation_info:Q.truncationInfo};return{success:!0,llmContent:V,metadata:{summary:`获取任务输出: ${$}`,...V}}}async function EX($,Z,J,Y){let U=o.getInstance(),X=U.getAgent($,Y);if(!X)return{success:!1,llmContent:`Agent not found: ${$}`,error:{type:"execution_error",message:"Agent 会话不存在或已清理"},metadata:{summary:`获取任务输出: ${$} (未找到)`}};if(Z&&X.status==="running"){if(X=await U.waitForCompletion($,J,Y),!X)return{success:!1,llmContent:`Failed to wait for agent: ${$}`,error:{type:"execution_error",message:"Wait for completion failed"},metadata:{summary:`获取任务输出: ${$} (等待失败)`}}}let H={task_id:X.id,type:"agent",status:X.status,subagent_type:X.subagentType,description:X.description,created_at:new Date(X.createdAt).toISOString(),last_active_at:new Date(X.lastActiveAt).toISOString(),completed_at:X.completedAt?new Date(X.completedAt).toISOString():void 0,result:X.result,stats:X.stats,isolation:X.isolation,worktree_path:X.worktree?.worktreeRoot,worktree_branch:X.worktree?.branch,resumed_from:X.resumedFrom,root_agent_id:X.rootAgentId,resume_depth:X.resumeDepth,resume_from_hint:X.id},Q=X.status==="completed"?"completed":X.status==="failed"?"failed":"running";return{success:!0,llmContent:H,metadata:{summary:`获取任务输出: ${$}`,...H,subagentSessionId:X.id,subagentType:X.subagentType,subagentStatus:Q,subagentResumedFrom:X.resumedFrom,subagentRootId:X.rootAgentId,subagentResumeDepth:X.resumeDepth,subagentSummary:typeof X.result?.message==="string"?X.result.message.slice(0,500):void 0,verificationCommands:X.result?.verificationCommands,verificationVerdict:X.result?.verificationVerdict,modifiedFiles:X.result?.modifiedFiles,verificationAgentBuiltin:X.subagentType===A2&&X.configSnapshot?.source==="builtin"}}}async function qX($,Z,J){let Y=s.getInstance(),U=Date.now();return new Promise((X)=>{let H=setInterval(()=>{let Q=Y.getProcess($,J);if(!Q||Q.status!=="running"){clearInterval(H),X();return}if(Date.now()-U>=Z){clearInterval(H),X();return}},100)})}import*as X9 from"os";import*as H9 from"path";import*as M$ from"fs/promises";import*as C1 from"path";class L0{static instances=new Map;teamsDir;constructor($){this.teamsDir=C1.join($,"teams")}static getInstance($){if(!L0.instances.has($))L0.instances.set($,new L0($));return L0.instances.get($)}static sanitizeName($){return $.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}getTeamFilePath($){return C1.join(this.teamsDir,L0.sanitizeName($),"config.json")}async createTeam($){let Z=await this.getUniqueTeamName($.name),J=Date.now(),Y=this.getTeamFilePath(Z),U={name:Z,description:$.description,createdAt:J,updatedAt:J,leadAgentId:`team-lead-${Z}`,leadSessionId:$.leadSessionId,teamFilePath:Y,members:[{id:`team-lead-${Z}`,name:"team-lead",subagentType:$.leadAgentType||"team-lead",description:"Team lead for coordinating the agent team",status:"leader",joinedAt:J},...$.members]};return await this.saveTeam(U),U}async loadTeam($){try{let Z=await M$.readFile(this.getTeamFilePath($),"utf-8");return FX(JSON.parse(Z))}catch(Z){if(Z.code!=="ENOENT")console.warn(`Failed to load team ${$}:`,Z);return}}async saveTeam($){let Z=this.getTeamFilePath($.name);await M$.mkdir(C1.dirname(Z),{recursive:!0,mode:493}),await M$.writeFile(Z,JSON.stringify({...$,teamFilePath:Z,updatedAt:Date.now()},null,2),"utf-8")}async listTeams(){try{let $=await M$.readdir(this.teamsDir,{withFileTypes:!0}),Z=[];for(let J of $){if(!J.isDirectory())continue;let Y=await this.loadTeam(J.name);if(Y)Z.push(Y)}return Z.sort((J,Y)=>Y.updatedAt-J.updatedAt)}catch($){if($.code!=="ENOENT")console.warn("Failed to list teams:",$);return[]}}async markDeleted($){let Z=await this.loadTeam($);if(!Z)return;let J=Date.now(),Y={...Z,deletedAt:J,updatedAt:J,members:Z.members.map((U)=>U.status==="running"?{...U,status:"cancelled",completedAt:U.completedAt||J}:U)};return await this.saveTeam(Y),Y}async getUniqueTeamName($){let Z=L0.sanitizeName($);if(!Z)throw Error("team_name must contain at least one letter or number");let J=Z,Y=2;while(await this.loadTeam(J))J=`${Z}-${Y}`,Y+=1;return J}}function FX($){if(!$||typeof $!=="object")return;let Z=$;if(!Z.name||!Array.isArray(Z.members))return;return{name:Z.name,description:Z.description,createdAt:typeof Z.createdAt==="number"?Z.createdAt:Date.now(),updatedAt:typeof Z.updatedAt==="number"?Z.updatedAt:Date.now(),deletedAt:typeof Z.deletedAt==="number"?Z.deletedAt:void 0,leadAgentId:Z.leadAgentId||`team-lead@${Z.name}`,leadSessionId:Z.leadSessionId,teamFilePath:Z.teamFilePath||"",members:Z.members.map((J)=>({id:J.id,name:J.name,subagentType:J.subagentType,description:J.description,prompt:J.prompt,agentId:J.agentId,status:J.status,joinedAt:J.joinedAt,completedAt:J.completedAt}))}}var DX=_.Object({name:_.String({minLength:1,description:"Human-readable teammate name, e.g. researcher or test-runner"}),subagent_type:_.String({minLength:1,description:"Registered subagent type to launch for this teammate"}),description:_.Optional(_.String({minLength:3,maxLength:100})),prompt:_.String({minLength:10,description:"Detailed assignment for this teammate"})});function C6($){let Z=$?.sessionId||`session_${Date.now()}`,J=$?.configDir||H9.join(X9.homedir(),".blade"),Y=$?.subagentRegistry??j$();return[wX({sessionId:Z,configDir:J,subagentRegistry:Y,agentResources:$?.agentResources,modelResources:$?.modelResources,lspResources:$?.lspResources,getReasoningEffort:$?.getReasoningEffort,getServiceTier:$?.getServiceTier,getResponseVerbosity:$?.getResponseVerbosity,getCommunicationStyle:$?.getCommunicationStyle}),AX({configDir:J}),LX({configDir:J})]}function wX($){return j({name:"TeamCreate",displayName:"Team Create",kind:"readonly",isConcurrencySafe:!1,schema:_.Object({team_name:_.String({minLength:1,description:"Name for the new agent team"}),description:_.Optional(_.String({description:"Team description or purpose"})),agent_type:_.Optional(_.String({description:"Optional role/type label for the team lead"})),members:f(_.Array(DX,{description:"Initial teammates to launch as background agents"}),[])}),description:{short:"Create an agent team and optionally launch teammate subagents",long:MX(),usageNotes:["Use TeamCreate when a task benefits from coordinated parallel agents","Each member is launched with the requested subagent_type as a background agent","Use TeamStatus to inspect teammate progress and collect agent IDs for TaskOutput"]},async execute(Z,J){try{NX($.subagentRegistry);let Y=jX(Z.members.map((K)=>K.name));if(Y)return C2(`Duplicate teammate name: ${Y}`,"创建团队失败");let U=Z.members.map((K)=>K.subagent_type).filter((K)=>!$.subagentRegistry.getSubagent(K));if(U.length>0)return C2(`Invalid subagent type(s): ${[...new Set(U)].join(", ")}. Available: ${$.subagentRegistry.getAllNames().join(", ")||"none"}`,"创建团队失败");let X=o.getInstance(),H=L0.getInstance($.configDir),Q=await H.createTeam({name:Z.team_name,description:Z.description,leadAgentType:Z.agent_type,leadSessionId:J.sessionId||$.sessionId,members:[]}),W=Date.now(),z=[];for(let K of Z.members){let G=$.subagentRegistry.getSubagent(K.subagent_type);if(!G)continue;let O={...G,model:G.model&&G.model!=="inherit"?G.model:J.modelId??G.model,permissionMode:G.permissionMode??J.permissionMode},E=`team-${L0.sanitizeName(K.name)}-${Q.name}`,q=bX({teamName:Q.name,teamDescription:Z.description,memberName:K.name,memberPrompt:K.prompt,teamFileHint:Q.teamFilePath}),F=X.startBackgroundAgent({config:O,description:K.description||K.name,prompt:q,parentSessionId:J.sessionId||$.sessionId,parentProjectPath:J.workspaceRoot||N(),permissionMode:J.permissionMode,reasoningEffort:$.getReasoningEffort?.(),serviceTier:$.getServiceTier?.(),responseVerbosity:$.getResponseVerbosity?.(),communicationStyle:$.getCommunicationStyle?.(),agentId:E,taskListId:Q.name,workspaceRoot:J.workspaceRoot||N(),isolation:O.isolation,agentResources:$.agentResources,modelResources:$.modelResources,lspResources:$.lspResources});z.push({id:E,name:K.name,subagentType:K.subagent_type,description:K.description||K.name,prompt:K.prompt,agentId:F,status:"running",joinedAt:W})}let V={...Q,members:[...Q.members,...z],updatedAt:Date.now()};await H.saveTeam(V);let B=await M6(H,V);return{success:!0,llmContent:{team:U1(B),message:z.length>0?`Team created with ${z.length} teammate(s). Use TeamStatus(team_name: "${B.name}") to inspect progress.`:`Team created. Use Task and TaskCreate tools to coordinate work for "${B.name}".`},metadata:{summary:`创建 Agent Team: ${B.name} (${z.length} teammates)`,team_name:B.name,team_file_path:B.teamFilePath,lead_agent_id:B.leadAgentId,member_agent_ids:z.map((K)=>K.agentId).filter(Boolean)}}}catch(Y){return f6(Y,"创建团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","agents","subagent","parallel"],extractSignatureContent:(Z)=>Z.team_name,abstractPermissionRule:()=>"*"})}function AX($){return j({name:"TeamStatus",displayName:"Team Status",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({team_name:_.Optional(_.String({description:"Team name to inspect. Omit to list all teams."}))}),description:{short:"List agent teams or inspect one team with teammate statuses",long:"Use this after TeamCreate to monitor teammate background agents and find their TaskOutput IDs."},async execute(Z){try{let J=L0.getInstance($.configDir);if(!Z.team_name){let X=await Promise.all((await J.listTeams()).map((H)=>M6(J,H)));return{success:!0,llmContent:{teams:X.map(U1)},metadata:{summary:X.length===0?"暂无 Agent Teams":`Agent Teams: ${X.length}`,teams:X.map(U1)}}}let Y=await J.loadTeam(Z.team_name);if(!Y)return C2(`Team not found: ${Z.team_name}`,"读取团队失败");let U=await M6(J,Y);return{success:!0,llmContent:{team:U1(U)},metadata:{summary:`Agent Team ${U.name}: ${Q9(U)}`,team:U1(U)}}}catch(J){return f6(J,"读取团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","status","agents"],extractSignatureContent:(Z)=>Z.team_name||"*",abstractPermissionRule:()=>"*"})}function LX($){return j({name:"TeamDelete",displayName:"Team Delete",kind:"readonly",isConcurrencySafe:!1,schema:_.Object({team_name:_.String({minLength:1,description:"Team name to delete"}),kill_running:f(_.Boolean({description:"Whether to cancel running teammate agents"}),!0)}),description:{short:"Mark an agent team deleted and optionally cancel running teammates",long:"Use this when coordinated team work is finished or should be stopped."},async execute(Z){try{let J=L0.getInstance($.configDir),Y=await J.loadTeam(Z.team_name);if(!Y)return C2(`Team not found: ${Z.team_name}`,"删除团队失败");let U=o.getInstance(),X=[];if(Z.kill_running){for(let Q of Y.members)if(Q.agentId&&U.killAgent(Q.agentId))X.push(Q.agentId)}let H=await J.markDeleted(Z.team_name);return{success:!0,llmContent:{team:H?U1(H):null,killed_agent_ids:X},metadata:{summary:`删除 Agent Team: ${Y.name}`,team_name:Y.name,killed_agent_ids:X}}}catch(J){return f6(J,"删除团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","delete","agents"],extractSignatureContent:(Z)=>Z.team_name,abstractPermissionRule:()=>"*"})}function NX($){if($.getAllNames().length===0)$.loadFromStandardLocations()}function bX($){return`
|
|
801
801
|
You are ${$.memberName}, a teammate in Blade agent team "${$.teamName}".
|
|
802
802
|
|
|
803
803
|
Team purpose: ${$.teamDescription||"Coordinate parallel agent work"}.
|
|
@@ -809,7 +809,7 @@ Work independently on your assignment and return a concise final result for the
|
|
|
809
809
|
|
|
810
810
|
Assignment:
|
|
811
811
|
${$.memberPrompt}
|
|
812
|
-
`.trim()}async function M6($,Z){let J=o.getInstance(),Y=!1,U=Z.members.map((H)=>{if(!H.agentId)return H;let Q=J.getAgent(H.agentId);if(!Q)return{...H,status:"unknown"};let W=
|
|
812
|
+
`.trim()}async function M6($,Z){let J=o.getInstance(),Y=!1,U=Z.members.map((H)=>{if(!H.agentId)return H;let Q=J.getAgent(H.agentId);if(!Q)return{...H,status:"unknown"};let W=TX(Q);if(W!==H.status||Q.completedAt!==H.completedAt)return Y=!0,{...H,status:W,completedAt:Q.completedAt};return H}),X={...Z,members:U};if(Y)await $.saveTeam(X);return X}function TX($){switch($.status){case"running":return"running";case"completed":return"completed";case"failed":return"failed";case"cancelled":return"cancelled";default:return"unknown"}}function U1($){let Z=o.getInstance();return{name:$.name,description:$.description,status:$.deletedAt?"deleted":Q9($),team_file_path:$.teamFilePath,lead_agent_id:$.leadAgentId,lead_session_id:$.leadSessionId,created_at:new Date($.createdAt).toISOString(),updated_at:new Date($.updatedAt).toISOString(),deleted_at:$.deletedAt?new Date($.deletedAt).toISOString():void 0,members:$.members.map((J)=>{let Y=J.agentId?Z.getAgent(J.agentId):void 0;return{id:J.id,name:J.name,subagent_type:J.subagentType,description:J.description,agent_id:J.agentId,status:J.status,task_output_id:J.agentId,result:Y?.result,stats:Y?.stats}})}}function Q9($){let Z=$.members.reduce((J,Y)=>{return J[Y.status]=(J[Y.status]||0)+1,J},{});return Object.entries(Z).map(([J,Y])=>`${Y} ${J}`).join(", ")}function jX($){let Z=new Set;for(let J of $){let Y=L0.sanitizeName(J);if(Z.has(Y))return J;Z.add(Y)}return}function C2($,Z){return{success:!1,llmContent:$,error:{type:"validation_error",message:$},metadata:{summary:Z}}}function f6($,Z){let J=$;return{success:!1,llmContent:`Team operation failed: ${J.message}`,error:{type:"execution_error",message:J.message,details:$},metadata:{summary:Z}}}function MX(){return`
|
|
813
813
|
Create a named team for coordinated parallel agent work. This is Blade's team layer over the existing Task background-agent system, inspired by Claude Code's TeamCreate workflow.
|
|
814
814
|
|
|
815
815
|
When to use:
|
|
@@ -824,7 +824,7 @@ Workflow:
|
|
|
824
824
|
4. Inspect progress with TeamStatus.
|
|
825
825
|
5. Retrieve detailed teammate output with TaskOutput using the member task_output_id.
|
|
826
826
|
6. Stop the team with TeamDelete when the work is complete or cancelled.
|
|
827
|
-
`.trim()}import{isPlainObject as z9}from"lodash-es";function V9($){if(!z9($))return;let Z=$;return typeof Z.name==="string"?Z.name:void 0}function CX($){if($ instanceof Error)return $.message;if(typeof $==="string")return $;if(z9($)){let Z=$;if(typeof Z.message==="string")return Z.message}return String($)}var R6=
|
|
827
|
+
`.trim()}import{isPlainObject as z9}from"lodash-es";function V9($){if(!z9($))return;let Z=$;return typeof Z.name==="string"?Z.name:void 0}function CX($){if($ instanceof Error)return $.message;if(typeof $==="string")return $;if(z9($)){let Z=$;if(typeof Z.message==="string")return Z.message}return String($)}var R6=j({name:"WebFetch",displayName:"Web Fetch",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({url:_.String({format:"uri",description:"URL to request"}),method:f(d(["GET","POST","PUT","DELETE","HEAD"],{description:"HTTP method"}),"GET"),extract_content:f(_.Boolean({description:"Use Jina Reader to extract clean Markdown content."}),!1),jina_options:_.Optional(_.Object({with_generated_alt:f(_.Boolean({description:"Generate alt text for images"}),!1),with_links_summary:f(_.Boolean({description:"Include summary of all links"}),!1),wait_for_selector:_.Optional(_.String({description:"Wait for specific CSS selector to load"}))},{description:"Jina Reader advanced options (only used when extract_content is true)"})),headers:_.Optional(_.Record(_.String(),_.String(),{description:"Request headers (optional)"})),body:_.Optional(_.String({description:"Request body (optional)"})),timeout:g.timeout(1000,120000,30000),follow_redirects:f(_.Boolean({description:"Follow redirects"}),!0),max_redirects:f(_.Integer({minimum:0,maximum:10,description:"Maximum redirect hops"}),5),return_headers:f(_.Boolean({description:"Return response headers"}),!1)}),description:{short:"Fetches content from a specified URL and processes it using an AI model",long:`
|
|
828
828
|
- Fetches content from a specified URL and processes it using an AI model
|
|
829
829
|
- Takes a URL and a prompt as input
|
|
830
830
|
- Fetches the URL content, converts HTML to markdown
|
|
@@ -841,7 +841,7 @@ Usage notes:
|
|
|
841
841
|
- Results may be summarized if the content is very large
|
|
842
842
|
- Includes a self-cleaning 15-minute cache for faster responses when repeatedly accessing the same URL
|
|
843
843
|
- When a URL redirects to a different host, the tool will inform you and provide the redirect URL in a special format. You should then make a new WebFetch request with the redirect URL to fetch the content.
|
|
844
|
-
`},async execute($,Z){let{url:J,method:Y="GET",extract_content:U=!1,jina_options:X,headers:H={},body:Q,timeout:W=30000,follow_redirects:z=!0,max_redirects:V=5,return_headers:B=!1}=$,{updateOutput:K}=Z,G=Z.signal??new AbortController().signal;try{if(U)try{let L=Date.now(),A=await PX({url:J,jinaOptions:X,timeout:W,signal:G,updateOutput:K}),w=Date.now()-L;if(A.response_time=w,!B)delete A.headers;let
|
|
844
|
+
`},async execute($,Z){let{url:J,method:Y="GET",extract_content:U=!1,jina_options:X,headers:H={},body:Q,timeout:W=30000,follow_redirects:z=!0,max_redirects:V=5,return_headers:B=!1}=$,{updateOutput:K}=Z,G=Z.signal??new AbortController().signal;try{if(U)try{let L=Date.now(),A=await PX({url:J,jinaOptions:X,timeout:W,signal:G,updateOutput:K}),w=Date.now()-L;if(A.response_time=w,!B)delete A.headers;let T={url:J,method:"GET",status:A.status,response_time:w,content_length:Buffer.byteLength(A.body||"","utf8"),redirected:A.redirected||!1,redirect_count:A.redirect_count??0,final_url:A.url,content_type:A.content_type,redirect_chain:A.redirect_chain},b=W9(J);return{success:!0,llmContent:A,metadata:{...T,summary:`GET ${b} - ${A.status}`}}}catch{K?.("[WARN] Jina Reader 失败,使用标准方式获取")}K?.(`发送 ${Y} 请求到: ${J}`);let O=Date.now(),E=await fX({url:J,method:Y,headers:H,body:Q,timeout:W,follow_redirects:z,max_redirects:V,signal:G}),q=Date.now()-O;if(E.response_time=q,!B)delete E.headers;let F={url:J,method:Y,status:E.status,response_time:q,content_length:Buffer.byteLength(E.body||"","utf8"),redirected:E.redirected||!1,redirect_count:E.redirect_count??0,final_url:E.url,content_type:E.content_type,redirect_chain:E.redirect_chain},D=W9(J);if(E.status>=400)return{success:!1,llmContent:`HTTP error ${E.status}: ${E.status_text}`,error:{type:"execution_error",message:`HTTP error ${E.status}: ${E.status_text}`,details:{...F,response_body:E.body}},metadata:{...F,summary:`请求失败: HTTP ${E.status} ${E.status_text}`}};return{success:!0,llmContent:E,metadata:{...F,summary:`${Y} ${D} - ${E.status}`}}}catch(O){if(V9(O)==="AbortError")return{success:!1,llmContent:"Request aborted",error:{type:"execution_error",message:"操作被中止"},metadata:{summary:"请求失败: 操作被中止"}};let E=CX(O);return{success:!1,llmContent:`Network request failed: ${E}`,error:{type:"execution_error",message:E,details:O},metadata:{summary:`请求失败: ${E}`}}}},version:"2.0.0",category:"网络工具",tags:["web","http","fetch","request","api"],extractSignatureContent:($)=>{try{return`domain:${new URL($.url).hostname}`}catch{return $.url}},abstractPermissionRule:($)=>{try{return`domain:${new URL($.url).hostname}`}catch{return"*"}}});async function fX($){let{url:Z,method:J,headers:Y,body:U,timeout:X,follow_redirects:H,max_redirects:Q,signal:W}=$,z={"User-Agent":"Blade-AI/1.0",...Y},V=Z,B=J,K=U,G=0,O=[];while(!0){let E={...z};if(K&&B!=="GET"&&B!=="HEAD"&&!SX(E,"content-type"))E["Content-Type"]="application/json";let q=await B9(V,{method:B,headers:E,body:K&&B!=="GET"&&B!=="HEAD"?K:void 0,redirect:"manual"},X,W),F=q.headers.get("location"),D=q.status>=300&&q.status<400,L=H&&D&&F&&G<Q;if(D&&H&&!F)throw Error(`收到状态码 ${q.status} 但响应缺少 Location 头`);if(D&&H&&G>=Q)throw Error(`超过最大重定向次数 (${Q})`);if(L&&F){G++;let T=RX(F,V);if(O.push(`${q.status} -> ${T}`),q.status===303||(q.status===301||q.status===302)&&B!=="GET"&&B!=="HEAD")B="GET",K=void 0;V=T;continue}let A=await q.text(),w=K9(q.headers);return{status:q.status,status_text:q.statusText,headers:w,body:A,url:q.url||V,redirected:G>0,redirect_count:G,redirect_chain:O,content_type:w["content-type"],response_time:0}}}function W9($){try{return new URL($).hostname}catch{return $}}async function B9($,Z,J,Y){let U=new AbortController,X=setTimeout(()=>U.abort(),J),H=()=>U.abort();Y?.addEventListener("abort",H);try{return await fetch($,{...Z,signal:U.signal})}catch(Q){if(V9(Q)==="AbortError"){if(Q instanceof Error)throw Q.message="请求被中止或超时",Q;let W=Error("请求被中止或超时");throw W.name="AbortError",W}throw Q}finally{clearTimeout(X),Y?.removeEventListener("abort",H)}}function RX($,Z){try{return new URL($,Z).toString()}catch{return $}}function K9($){let Z={};return $.forEach((J,Y)=>{Z[Y.toLowerCase()]=J}),Z}function SX($,Z){let J=Z.toLowerCase();return Object.keys($).some((Y)=>Y.toLowerCase()===J)}async function PX($){let{url:Z,jinaOptions:J,timeout:Y,signal:U,updateOutput:X}=$,H=`https://r.jina.ai/${encodeURIComponent(Z)}`;X?.(`使用 Jina Reader 提取内容: ${Z}`);let Q={"User-Agent":"Blade-AI/1.0",Accept:"text/markdown"};if(J?.with_generated_alt)Q["X-With-Generated-Alt"]="true";if(J?.with_links_summary)Q["X-With-Links-Summary"]="true";if(J?.wait_for_selector)Q["X-Wait-For-Selector"]=J.wait_for_selector;try{let W=await B9(H,{method:"GET",headers:Q},Y,U);if(!W.ok)throw Error(`Jina Reader error: ${W.status} ${W.statusText}`);let z=await W.text(),V=kX(z);return X?.(`[OK] Jina Reader 成功提取内容 (${V.content.length} 字符)`),{status:W.status,status_text:W.statusText,headers:K9(W.headers),body:vX(V),url:V.sourceUrl||Z,redirected:!1,redirect_count:0,content_type:"text/markdown",response_time:0}}catch(W){throw X?.("[WARN] Jina Reader 失败,回退到直接获取"),W}}function kX($){let Z=$.split(`
|
|
845
845
|
`),J="",Y="",U=0;for(let H=0;H<Z.length;H++){let Q=Z[H];if(Q.startsWith("Title: "))J=Q.substring(7).trim();else if(Q.startsWith("URL Source: "))Y=Q.substring(12).trim();else if(Q.startsWith("Markdown Content:")){U=H+1;break}}let X=Z.slice(U).join(`
|
|
846
846
|
`).trim();return{title:J||"Untitled",sourceUrl:Y||"",content:X||$}}function vX($){let Z="";if($.title)Z+=`# ${$.title}
|
|
847
847
|
|
|
@@ -853,7 +853,7 @@ Usage notes:
|
|
|
853
853
|
`),Y={};for(let U=0;U<J.length;U++){let X=J[U].trim();if(X.startsWith("Title: ")){if(Y.title&&Y.url)Z.push({title:Y.title,url:Y.url,snippet:Y.snippet||Y.title,display_url:f1(Y.url),source:R1(Y.url)});Y={title:X.substring(7).trim(),snippet:""}}else if(X.startsWith("URL: "))Y.url=X.substring(5).trim();else if(X.startsWith("Text: ")){let Q=X.substring(6).trim().replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim();Y.snippet=Q.substring(0,300)}}if(Y.title&&Y.url)Z.push({title:Y.title,url:Y.url,snippet:Y.snippet||Y.title,display_url:f1(Y.url),source:R1(Y.url)});return Z}function cX(){return{name:"Exa",endpoint:`${C$.BASE_URL}${C$.ENDPOINT}`,searchFn:async($)=>{let Z={jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"web_search_exa",arguments:{query:$,type:"auto",numResults:C$.DEFAULT_NUM_RESULTS,contextMaxCharacters:1e4}}},J=new AbortController,Y=setTimeout(()=>J.abort(),C$.TIMEOUT);try{let U=await fetch(`${C$.BASE_URL}${C$.ENDPOINT}`,{method:"POST",headers:{accept:"application/json, text/event-stream","content-type":"application/json"},body:JSON.stringify(Z),signal:J.signal});if(clearTimeout(Y),!U.ok)throw Error(`MCP error (${U.status})`);let H=(await U.text()).split(`
|
|
854
854
|
`);for(let Q of H)if(Q.startsWith("data: ")){let W=JSON.parse(Q.substring(6));if(W.result&&W.result.content&&W.result.content.length>0)return pX(W.result.content[0].text)}throw Error("No search results found")}catch(U){if(clearTimeout(Y),U.name==="AbortError")throw Error("MCP request timed out");throw U}},buildUrl:()=>`${C$.BASE_URL}${C$.ENDPOINT}`,parseResponse:()=>[],getHeaders:()=>({})}}function D9(){let $=[];return $.push(cX()),$.push(dX),$.push(...F9.map(gX)),$}function w9(){return 2+F9.length}var nX=15000,rX=8,S1={maxRetries:3,baseDelay:1000,maxDelay:8000};function aX(){let $=process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy;if($)try{return new iX($)}catch(Z){console.warn(`Invalid proxy URL: ${$}`)}return}async function oX($,Z,J,Y,U){let X=new AbortController,H=setTimeout(()=>X.abort(),J),Q=()=>X.abort();Y?.addEventListener("abort",Q);try{return await lX($,{...Z,signal:X.signal,dispatcher:U})}catch(W){if(W.name==="AbortError")throw Error("搜索请求超时或被中止");throw W}finally{clearTimeout(H),Y?.removeEventListener("abort",Q)}}async function sX($,Z,J,Y,U,X){let H=null;for(let Q=0;Q<S1.maxRetries;Q++)try{return await oX($,Z,J,Y,U)}catch(W){if(H=W,Y?.aborted)throw W;if(Q<S1.maxRetries-1){let z=Math.min(S1.baseDelay*Math.pow(2,Q),S1.maxDelay);X?.(`请求失败,${z/1000}s 后重试 (${Q+1}/${S1.maxRetries})...`),await new Promise((V)=>setTimeout(V,z))}}throw H}async function tX($,Z,J,Y,U,X){let H=O9(),Q=H.get($.name,Z);if(Q)return X?.(`使用缓存结果 (${$.name})`),{results:Q,providerName:`${$.name} (cached)`};if($.searchFn)try{X?.(`搜索中 (${$.name})...`);let q=await $.searchFn(Z);return H.set($.name,Z,q),{results:q,providerName:$.name}}catch(q){throw Error(`SDK search failed: ${q.message}`)}X?.(`搜索中 (${$.name})...`);let W=$.buildUrl(Z),z=$.method||"GET",B={headers:$.getHeaders(),method:z};if(z==="POST"&&$.buildBody)B.body=JSON.stringify($.buildBody(Z));let K=await sX(W,B,J,Y,U,X);if(!K.ok)throw Error(`HTTP ${K.status}`);let G=await K.text(),O;try{O=JSON.parse(G)}catch{throw Error("Failed to parse search result JSON")}let E=$.parseResponse(O);return H.set($.name,Z,E),{results:E,providerName:$.name}}async function eX($,Z,J,Y){let U=D9(),X=aX(),H=[];for(let Q=0;Q<U.length;Q++){let W=U[Q];if(J?.aborted)throw Error("搜索被用户中止");try{return Y?.(`使用 ${W.name} 搜索...`),await tX(W,$,Z,J,X,Y)}catch(z){let V=z,B=`${W.name}: ${V.message}`;if(H.push(B),Y?.(`[WARN] ${B}`),Q===U.length-1)throw Error(`所有搜索提供商都失败了:
|
|
855
855
|
${H.join(`
|
|
856
|
-
`)}`)}}throw Error("No search providers available")}function $H($){try{return new URL($).hostname.toLowerCase()}catch{return null}}function ZH($){return $.trim().toLowerCase()}function A9($){if(!$||$.length===0)return[];return $.map(ZH).filter(Boolean)}function L9($,Z){return $===Z||$.endsWith(`.${Z}`)}function JH($,Z,J){return $.filter((Y)=>{let U=$H(Y.url);if(!U)return!1;if(J.length>0&&J.some((X)=>L9(U,X)))return!1;if(Z.length>0&&!Z.some((X)=>L9(U,X)))return!1;return!0})}function YH($){let Z=$.trim().toLowerCase();return Z.length>80?Z.slice(0,80):Z}var S6=
|
|
856
|
+
`)}`)}}throw Error("No search providers available")}function $H($){try{return new URL($).hostname.toLowerCase()}catch{return null}}function ZH($){return $.trim().toLowerCase()}function A9($){if(!$||$.length===0)return[];return $.map(ZH).filter(Boolean)}function L9($,Z){return $===Z||$.endsWith(`.${Z}`)}function JH($,Z,J){return $.filter((Y)=>{let U=$H(Y.url);if(!U)return!1;if(J.length>0&&J.some((X)=>L9(U,X)))return!1;if(Z.length>0&&!Z.some((X)=>L9(U,X)))return!1;return!0})}function YH($){let Z=$.trim().toLowerCase();return Z.length>80?Z.slice(0,80):Z}var S6=j({name:"WebSearch",displayName:"Web Search",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({query:_.String({minLength:2,description:"Search query"}),allowed_domains:_.Optional(_.Array(_.String({minLength:1}),{description:"Return results only from these domains (optional)"})),blocked_domains:_.Optional(_.Array(_.String({minLength:1}),{description:"Exclude results from these domains (optional)"}))}),description:{short:"Search the web and use the results to inform responses",long:`
|
|
857
857
|
- Search the web and use the results to inform responses
|
|
858
858
|
- Provides up-to-date information for current events and recent data
|
|
859
859
|
- Returns search result information formatted as search result blocks, including links as markdown hyperlinks
|
|
@@ -881,8 +881,8 @@ Usage notes:
|
|
|
881
881
|
IMPORTANT - Use the correct year in search queries:
|
|
882
882
|
- You MUST use the current year when searching for recent information, documentation, or current events.
|
|
883
883
|
- Example: If the user asks for "latest React docs", search for "React documentation 2025", NOT "React documentation 2024"
|
|
884
|
-
`},async execute($,Z){let{query:J}=$,Y=A9($.allowed_domains),U=A9($.blocked_domains),{updateOutput:X}=Z,H=Z.signal??new AbortController().signal;X?.(`Searching: "${J}" (${w9()} providers available)`);try{let{results:Q,providerName:W}=await eX(J,nX,H,X),z=JH(Q,Y,U),V=z.slice(0,rX),B={query:J,results:V,provider:W,total_results:z.length,fetched_at:new Date().toISOString()},K={query:J,provider:W,fetched_at:B.fetched_at,total_results:z.length,returned_results:V.length,allowed_domains:Y,blocked_domains:U};if(V.length===0)return{success:!0,llmContent:B,metadata:{...K,summary:`搜索 "${J}" 找到 0 条结果`}};return{success:!0,llmContent:B,metadata:{...K,summary:`搜索 "${J}" 找到 ${V.length} 条结果`}}}catch(Q){let W=Q;return{success:!1,llmContent:`WebSearch call failed: ${W.message}`,error:{type:"execution_error",message:W.message,details:{query:J,allowedDomains:Y,blockedDomains:U}},metadata:{summary:`搜索失败: ${W.message}`}}}},version:"2.0.0",category:"网络工具",tags:["web","search","internet","news"],extractSignatureContent:($)=>`search:${YH($.query)}`,abstractPermissionRule:()=>"search:*"});function N9($){return{success:!1,llmContent:$,error:{type:"execution_error",message:$},metadata:{summary:$}}}function P6($){let Z=$.manager??t0,J=
|
|
885
|
-
${H}`.trim();return{hasErrors:Q!==0&&!W,rawOutput:z,timedOut:W,workspaceRoot:$}}}function XH($,Z){let J=K0.isAbsolute($)?K0.normalize($):K0.resolve(Z,$);try{let Y=UH("sha256").update(
|
|
884
|
+
`},async execute($,Z){let{query:J}=$,Y=A9($.allowed_domains),U=A9($.blocked_domains),{updateOutput:X}=Z,H=Z.signal??new AbortController().signal;X?.(`Searching: "${J}" (${w9()} providers available)`);try{let{results:Q,providerName:W}=await eX(J,nX,H,X),z=JH(Q,Y,U),V=z.slice(0,rX),B={query:J,results:V,provider:W,total_results:z.length,fetched_at:new Date().toISOString()},K={query:J,provider:W,fetched_at:B.fetched_at,total_results:z.length,returned_results:V.length,allowed_domains:Y,blocked_domains:U};if(V.length===0)return{success:!0,llmContent:B,metadata:{...K,summary:`搜索 "${J}" 找到 0 条结果`}};return{success:!0,llmContent:B,metadata:{...K,summary:`搜索 "${J}" 找到 ${V.length} 条结果`}}}catch(Q){let W=Q;return{success:!1,llmContent:`WebSearch call failed: ${W.message}`,error:{type:"execution_error",message:W.message,details:{query:J,allowedDomains:Y,blockedDomains:U}},metadata:{summary:`搜索失败: ${W.message}`}}}},version:"2.0.0",category:"网络工具",tags:["web","search","internet","news"],extractSignatureContent:($)=>`search:${YH($.query)}`,abstractPermissionRule:()=>"search:*"});function N9($){return{success:!1,llmContent:$,error:{type:"execution_error",message:$},metadata:{summary:$}}}function P6($){let Z=$.manager??t0,J=j({name:"EnterWorktree",displayName:"Enter Worktree",kind:"execute",isConcurrencySafe:!1,strict:!0,schema:_.Object({name:_.Optional(_.String({description:'Optional worktree name. Use letters, digits, dots, underscores, dashes, and optional "/" separators.'}))}),description:{short:"Create an isolated git worktree and switch this session into it",long:"Use only when the user explicitly asks to work in a git worktree. The worktree starts from committed HEAD; uncommitted source changes remain in the original workspace.",usageNotes:["Do not combine EnterWorktree with file or Bash tools in the same response","Wait for the worktree path, then use that path for all subsequent operations","Use ExitWorktree when the user asks to leave, keep, or remove the worktree"],important:["Never enter a worktree unless the user explicitly requested worktree isolation","A session can have only one active managed worktree"]},async execute(U,X){try{let H=X.sessionId??$.sessionId,Q=await Z.enter({sessionId:H,workspaceRoot:X.workspaceRoot??N(),name:U.name}),W=Q.sourceHadChanges?" The original workspace has uncommitted changes; they were not copied.":"";return{success:!0,llmContent:`Created worktree ${Q.worktreeRoot} on branch ${Q.branch}. This session now uses ${Q.workspaceRoot}.${W}`,metadata:{summary:`Entered worktree ${Q.name}`,workspaceTransition:"enter",workspaceRoot:Q.workspaceRoot,worktreeRoot:Q.worktreeRoot,worktreeBranch:Q.branch,originalWorkspaceRoot:Q.originalWorkspaceRoot,sourceHadChanges:Q.sourceHadChanges}}}catch(H){return N9(H instanceof Error?H.message:String(H))}},version:"1.0.0",category:"工作区工具",tags:["git","worktree","isolation"],extractSignatureContent:(U)=>U.name??"auto",abstractPermissionRule:()=>"*"}),Y=j({name:"ExitWorktree",displayName:"Exit Worktree",kind:"execute",isConcurrencySafe:!1,strict:!0,schema:_.Object({action:d(["keep","remove"],{description:'"keep" preserves the worktree and branch; "remove" deletes both when safe.'}),discard_changes:f(_.Boolean({description:"Required true to remove a worktree with uncommitted files or unmerged commits."}),!1)}),description:{short:"Exit the managed worktree for this session",long:"Only affects a worktree created by EnterWorktree in the same session. Manual or unrelated worktrees are never touched.",usageNotes:['Use action="keep" to preserve work for later','Use action="remove" only when the worktree is clean',"If removal is refused, ask the user before retrying with discard_changes=true"],important:["Never set discard_changes=true without explicit user confirmation","Removal fails closed when Git state cannot be verified"]},async execute(U,X){try{let H=X.sessionId??$.sessionId,Q=await Z.exit({sessionId:H,action:U.action,discardChanges:U.discard_changes,workspaceRoot:X.workspaceRoot??N()});if(Q.noop)return{success:!0,llmContent:"No active managed worktree exists for this session. No files were changed.",metadata:{summary:"No active worktree",noop:!0}};return{success:!0,llmContent:Q.action==="keep"?`Exited worktree and preserved it at ${Q.worktreeRoot} on branch ${Q.branch}. Session workspace restored to ${Q.workspaceRoot}.`:`Exited and removed worktree ${Q.worktreeRoot}. Session workspace restored to ${Q.workspaceRoot}.`,metadata:{summary:Q.action==="keep"?`Kept worktree ${Q.branch}`:`Removed worktree ${Q.branch}`,workspaceTransition:"exit",workspaceRoot:Q.workspaceRoot,worktreeRoot:Q.worktreeRoot,worktreeBranch:Q.branch,removed:Q.removed,discardedFiles:Q.discardedFiles,discardedCommits:Q.discardedCommits}}}catch(H){return N9(H instanceof Error?H.message:String(H))}},version:"1.0.0",category:"工作区工具",tags:["git","worktree","isolation"],extractSignatureContent:(U)=>`${U.action}${U.discard_changes?":discard":""}`,abstractPermissionRule:(U)=>U.action});return[J,Y]}async function O2($){let Z=$?.sessionId||`session_${Date.now()}`,J=$?.configDir||T9.join(b9.homedir(),".blade"),Y=$?.workspaceRoot||process.cwd(),U=$?.resourceRoot||Y,X=$?.agentResources?.subagents??$?.subagentRegistry??j$(U),H=$?.agentResources?.skills??$?.skillRegistry??C0({cwd:U}),Q=$?.agentResources?.commands??$?.commandRegistry??R0.getInstance(U);return[j5,T5,M5,N5,y5,m5,i5,l5,a5,n5,R6,S6,L2(X,$?.agentResources,$?.modelResources,$?.lspResources,$?.getReasoningEffort,$?.getServiceTier,$?.getResponseVerbosity,$?.getCommunicationStyle),j6,...T6({sessionId:Z,configDir:J}),...S5({sessionId:Z,workspaceRoot:Y}),...C6({sessionId:Z,configDir:J,subagentRegistry:X,agentResources:$?.agentResources,modelResources:$?.modelResources,lspResources:$?.lspResources,getReasoningEffort:$?.getReasoningEffort,getServiceTier:$?.getServiceTier,getResponseVerbosity:$?.getResponseVerbosity,getCommunicationStyle:$?.getCommunicationStyle}),...P6({sessionId:Z}),x5,u5,o5,X2(H),H2(Q),s5,v5,I5,G5,...$?.lspManager?.available?[k5($.lspManager)]:[]]}import V$ from"node:path";import{createHash as UH}from"node:crypto";import{existsSync as i$,readFileSync as j9}from"node:fs";import K0 from"node:path";var k6=u("Execution");class v6{cacheMs;timeoutMs;runCommand;running=new Map;cache=new Map;constructor($={}){this.cacheMs=$.cacheMs??500,this.timeoutMs=$.timeoutMs??1e4,this.runCommand=$.runCommand??zH}async verify($,Z,J){let Y=HH($,Z);if(!Y)return null;let U=Date.now(),X=XH($,Z),H=this.cache.get(Y);if(H&&H.inputFingerprint===X&&U-H.at<this.cacheMs)return k6.debug(`[VerifyQueue] cache hit: ${Y}`),H.result;let Q=this.running.get(Y);if(Q?.inputFingerprint===X)return k6.debug(`[VerifyQueue] coalescing into running check: ${Y}`),Q.promise;let W=async()=>{let K=await this.runTypeCheck(Y,J);return this.cache.set(Y,{result:K,at:Date.now(),inputFingerprint:X}),K},z=Q?.promise,V=(z?z.then(W,W):W()).finally(()=>{if(this.running.get(Y)?.promise===V)this.running.delete(Y)}),B={inputFingerprint:X,promise:V};return this.running.set(Y,B),V}clearCache(){this.cache.clear()}async runTypeCheck($,Z){let J=QH($);if(!J||!this.runCommand)return{hasErrors:!1,rawOutput:"",timedOut:!1,workspaceRoot:$};let{cmd:Y,args:U}=J;k6.debug(`[VerifyQueue] running: ${Y} ${U.join(" ")} in ${$}`);let{stdout:X,stderr:H,exitCode:Q,timedOut:W}=await this.runCommand(Y,U,$,this.timeoutMs,Z),z=`${X}
|
|
885
|
+
${H}`.trim();return{hasErrors:Q!==0&&!W,rawOutput:z,timedOut:W,workspaceRoot:$}}}function XH($,Z){let J=K0.isAbsolute($)?K0.normalize($):K0.resolve(Z,$);try{let Y=UH("sha256").update(j9(J)).digest("hex");return`${J}\x00${Y}`}catch{return`${J}\x00missing`}}function HH($,Z){let J=K0.isAbsolute($)?$:K0.resolve(Z,$),Y=K0.dirname(J),U=K0.parse(Y).root;while(Y!==U){if(i$(K0.join(Y,"tsconfig.json")))return Y;Y=K0.dirname(Y)}if(i$(K0.join(Z,"tsconfig.json")))return Z;return null}function QH($){let Z=K0.join($,"package.json");if(i$(Z))try{let J=JSON.parse(j9(Z,"utf8"));if(J?.scripts?.["type-check"])return{cmd:WH($,J.packageManager),args:["run","type-check"]}}catch{}return null}function WH($,Z){if(typeof Z==="string"){let J=Z.split("@")[0];if(J==="bun"||J==="npm"||J==="pnpm"||J==="yarn")return J}if(i$(K0.join($,"bun.lock"))||i$(K0.join($,"bun.lockb")))return"bun";if(i$(K0.join($,"pnpm-lock.yaml")))return"pnpm";if(i$(K0.join($,"yarn.lock")))return"yarn";return"npm"}async function zH(){throw Error("VerifyQueue requires a Session-owned command runner")}var M9=u("Execution"),VH=new Set(["Edit","Write","ApplyPatch"]),I6=15,C9=262144;function f9($,Z){if($.length>=C9)return $;return $+Z.slice(0,C9-$.length)}function BH($,Z){let J=Z.map((U)=>V$.basename(U)),Y=Z.map((U)=>V$.resolve(U));return $.split(`
|
|
886
886
|
`).filter((U)=>J.some((X)=>U.includes(X))||Y.some((X)=>U.includes(X)))}function KH($,Z){let J=$.file_path||$.path;if(J)return[J];if(!Array.isArray(Z.metadata?.changes))return[];return[...new Set(Z.metadata.changes.filter((Y)=>Boolean(Y&&typeof Y==="object"&&"path"in Y&&typeof Y.path==="string"&&(!("newContent"in Y)||Y.newContent!==null))).map((Y)=>Y.path))]}class y6{options;verifyQueue;activeCommands=new Set;activeVerifications=new Set;disposeController=new AbortController;disposed=!1;constructor($){this.options=$;this.verifyQueue=new v6({runCommand:$.runCommand??((Z,J,Y,U,X)=>this.runOwnedCommand(Z,J,Y,U,X))})}verify($,Z,J,Y){if(this.disposed)return Promise.resolve();let U=this.verifyInternal($,Z,J,Y).finally(()=>{this.activeVerifications.delete(U)});return this.activeVerifications.add(U),U}async dispose(){if(this.disposed)return;this.disposed=!0,this.disposeController.abort();let $=[...this.activeCommands],Z=[...this.activeVerifications];await Promise.allSettled($.map((J)=>J.processTree.terminate())),await Promise.allSettled($.map((J)=>J.settled)),await Promise.allSettled(Z),this.activeCommands.clear(),this.activeVerifications.clear(),this.verifyQueue.clearCache()}async verifyInternal($,Z,J,Y){if(this.disposed||!VH.has($)||!Y.success||this.isRemoteSession())return;let U=KH(Z,Y);if(U.length===0||!await this.isProjectExplicitlyTrusted())return;let X=U.map((B)=>V$.isAbsolute(B)?V$.normalize(B):V$.resolve(this.options.workspaceRoot,B)).filter((B)=>{let K=V$.relative(this.options.workspaceRoot,B);return K!==".."&&!K.startsWith(`..${V$.sep}`)&&!V$.isAbsolute(K)});if(X.length===0)return;let H;try{let B=J.signal?AbortSignal.any([J.signal,this.disposeController.signal]):this.disposeController.signal;H=await this.verifyQueue.verify(X[0],this.options.workspaceRoot,B)}catch(B){if(!J.signal?.aborted&&!this.disposeController.signal.aborted)M9.debug(`[AutoVerify] type-check failed: ${B instanceof Error?B.message:String(B)}`);return}if(!H||H.timedOut||!H.hasErrors)return;let Q=BH(H.rawOutput,X);if(Q.length===0)return;let z=`Type errors:
|
|
887
887
|
${Q.slice(0,I6).join(`
|
|
888
888
|
`)}`+(Q.length>I6?`
|
|
@@ -892,16 +892,16 @@ ${Q.slice(0,I6).join(`
|
|
|
892
892
|
**Auto-Verify: issues after ${X.length===1?V$.basename(X[0]):`${X.length} patched files`}:**
|
|
893
893
|
\`\`\`
|
|
894
894
|
${z}
|
|
895
|
-
\`\`\``,M9.info(`[AutoVerify] injected type diagnostics (${X.length} files)`)}isRemoteSession(){return this.options.isRemoteSession?.()??a(this.options.sessionId)}async isProjectExplicitlyTrusted(){if(this.options.resolveTrust)return this.options.resolveTrust();return(await
|
|
896
|
-
`,{encoding:"utf8",mode:384,fsync:!0})}}var DH=20,wH=v9+I9;function k9($){if(typeof $==="string")return $.length;return $.reduce((Z,J)=>{if(J.type==="text")return Z+J.text.length;return Z+J.image_url.url.length},0)}class P2{inbox;transitionMutex=new FH;activeTurn;claimed=new Map;constructor($){this.inbox=$}static async create($,Z){return new P2(await S2.open($,Z))}beginTurn(){if(this.activeTurn)throw Error(`Session already has an active turn: ${this.activeTurn.id}`);return this.createTurn()}async enqueue($,Z={}){return this.transitionMutex.runExclusive(async()=>{if(!this.activeTurn&&!Z.allowBeforeTurn)return{accepted:!1,queued:this.inbox.count(),reason:"no_active_turn"};let J=this.activeTurn&&!this.activeTurn.sealed?"current_turn":"next_turn";return this.enqueueDurably($,J,Z)})}async prepareInputTurn($){return this.transitionMutex.runExclusive(async()=>{if(this.activeTurn)return{accepted:!1,queued:this.inbox.count(),reason:"turn_active"};let Z=this.inbox.count()>0,J=await this.enqueueDurably($,"next_turn");if(!J.accepted||!J.messageId)return{accepted:!1,queued:J.queued,reason:"queue_full"};let Y=this.createTurn();if(!Z){let U=this.inbox.list().find((X)=>X.id===J.messageId);if(!U)throw this.activeTurn=void 0,Error(`Prepared input disappeared from inbox: ${J.messageId}`);this.claimed.set(U.id,U)}return{accepted:!0,handle:Y,messageId:J.messageId,queued:J.queued,mode:Z?"pending":"direct"}})}async drain($){return this.transitionMutex.runExclusive(()=>{this.assertOwner($);let Z=this.inbox.list().filter((J)=>!this.claimed.has(J.id));for(let J of Z)this.claimed.set(J.id,J);return Z})}async drainOrSeal($){return this.transitionMutex.runExclusive(()=>{if(this.assertOwner($),this.inbox.count()>this.claimed.size){let Z=this.inbox.list().filter((J)=>!this.claimed.has(J.id));for(let J of Z)this.claimed.set(J.id,J);return{messages:Z,sealed:!1}}return this.activeTurn.sealed=!0,{messages:[],sealed:!0}})}async acknowledge($){await this.inbox.acknowledge($);for(let Z of $)this.claimed.delete(Z)}async claimedMessageIds($){return this.transitionMutex.runExclusive(()=>{return this.assertOwner($),[...this.claimed.keys()]})}async finishTurn($,Z={}){return this.transitionMutex.runExclusive(()=>{if(this.assertOwner($),this.activeTurn=void 0,this.claimed.clear(),!Z.continuePending||this.inbox.count()===0)return;return this.createTurn()})}async beginPendingTurn(){return this.transitionMutex.runExclusive(()=>{if(this.activeTurn||this.inbox.count()===0)return;return this.createTurn()})}isActive(){return Boolean(this.activeTurn&&!this.activeTurn.sealed)}hasTurnOwner(){return Boolean(this.activeTurn)}pendingCount(){return this.inbox.count()}pendingMessages(){return this.inbox.list()}recoveredCount(){return this.inbox.recoveredCount()}assertOwner($){if(!this.activeTurn||this.activeTurn.id!==$.id)throw Error(`Turn ${$.id} does not own this session mailbox`)}async enqueueDurably($,Z,J={}){let Y={id:J.messageId??P9(12),content:$,queuedAt:Date.now(),...J.persisted?{persisted:!0}:{}};if(!await this.inbox.enqueue(Y,(X)=>{if(X.length>=DH)return!1;return X.reduce((Q,W)=>Q+k9(W.content),0)+k9($)<=wH}))return{accepted:!1,turnId:this.activeTurn?.id,queued:this.inbox.count(),reason:"queue_full"};return{accepted:!0,messageId:Y.id,turnId:this.activeTurn?.id,queued:this.inbox.count(),delivery:Z}}createTurn(){let $={id:P9(12)};return this.activeTurn={id:$.id,sealed:!1},$}}var N0=u("Agent"),y9=new Map;async function x9($){let Z=y9.get($);if(!Z)Z=(async()=>{try{let J=await t0.cleanupStaleAgentWorktrees({workspaceRoot:$});if(J.removed>0)N0.info(`[WorktreeGC] removed ${J.removed} stale agent worktree(s)`);if(J.errors.length>0)N0.warn(`[WorktreeGC] completed with ${J.errors.length} error(s): ${J.errors.join("; ")}`)}catch(J){N0.warn(`[WorktreeGC] cleanup failed: ${J instanceof Error?J.message:String(J)}`)}})(),y9.set($,Z);await Z}class N${config;options;approvalStore=new N1;baseRegistry=new A$;attachmentCollector;goalStore;activeTurnMailbox;chatService;executionEngine;selectedModelId;selectedReasoningEffort;currentReasoning;selectedServiceTier;currentServiceTier;selectedResponseVerbosity;currentResponseVerbosity;selectedCommunicationStyle;currentModelId;currentModelMaxContextTokens;initialized=!1;sessionLease;sessionMcpRegistry;mcpCatalogListener;mcpContentCatalogListener;mcpResourceUpdatedListener;mcpConnectionListener;mcpLogListener;mcpInstructionsListener;mcpTaskListener;mcpCatalogBarrier=async()=>{return};executorCatalogs=new Map;agentResources;modelResources;lspResources;sessionEnvironment;subagentRegistry;autoVerifyRuntime;lspManager;userShellMutex=new LH;constructor($,Z){this.config=$;this.options=Z;if(this.selectedModelId=Z.modelId&&Z.modelId!=="inherit"?Z.modelId:void 0,this.selectedReasoningEffort=Z.reasoningEffort??"off",this.selectedServiceTier=Z.serviceTier??"auto",this.selectedResponseVerbosity=Z.responseVerbosity??"auto",this.selectedCommunicationStyle=Z.communicationStyle??"auto",Z.modelResources)this.modelResources=Z.modelResources;else{let J=new u9(d9().credentials);if($.modelProviders&&$.models)J.configureModelProviders($.modelProviders,$.models);this.modelResources={projectRoot:Y0.resolve(Z.workspaceRoot??N()),config:g9($),catalog:J}}this.lspResources=_1(Z.lspResources??{projectRoot:this.modelResources.projectRoot,servers:$.lspServers}),this.sessionEnvironment=Object.freeze({...$.env}),this.goalStore=new
|
|
895
|
+
\`\`\``,M9.info(`[AutoVerify] injected type diagnostics (${X.length} files)`)}isRemoteSession(){return this.options.isRemoteSession?.()??a(this.options.sessionId)}async isProjectExplicitlyTrusted(){if(this.options.resolveTrust)return this.options.resolveTrust();return(await j0.getInstance().getStatus(this.options.projectRoot)).state==="trusted"}runOwnedCommand($,Z,J,Y,U){if(this.disposed||U?.aborted)return Promise.resolve({stdout:"",stderr:"",exitCode:1,timedOut:!1});let{child:X,processTree:H}=p0($,Z,{cwd:J,env:{...this.options.environment,PATH:this.options.environment.PATH??process.env.PATH??"",HOME:this.options.environment.HOME??process.env.HOME??"",USER:this.options.environment.USER??process.env.USER??"",SHELL:this.options.environment.SHELL??process.env.SHELL??"/bin/sh",BLADE_CLI:"1",BLADE_SESSION_ID:this.options.sessionId},stdio:["ignore","pipe","pipe"]}),Q,W=new Promise((V)=>{Q=V}),z={processTree:H,settled:W};return this.activeCommands.add(z),new Promise((V,B)=>{let K="",G="",O=!1,E=!1,q,F=()=>{return q??=H.terminate(),q};X.stdout?.setEncoding("utf8"),X.stderr?.setEncoding("utf8"),X.stdout?.on("data",(w)=>{K=f9(K,w)}),X.stderr?.on("data",(w)=>{G=f9(G,w)});let D=()=>{clearTimeout(A),U?.removeEventListener("abort",L),this.disposeController.signal.removeEventListener("abort",L),this.activeCommands.delete(z),Q()},L=()=>{F()},A=setTimeout(()=>{O=!0,F()},Y);if(U?.addEventListener("abort",L,{once:!0}),this.disposeController.signal.addEventListener("abort",L,{once:!0}),U?.aborted||this.disposeController.signal.aborted)L();X.once("error",(w)=>{if(E)return;E=!0,D(),B(w)}),X.once("close",async(w)=>{if(E)return;if(E=!0,O||U?.aborted||this.disposeController.signal.aborted)await F();D(),V({stdout:K,stderr:G,exitCode:w??1,timedOut:O})})})}}import{Mutex as FH}from"async-mutex";import{nanoid as P9}from"nanoid";import*as d0 from"node:fs/promises";import*as S9 from"node:path";import{Mutex as _H}from"async-mutex";import GH from"write-file-atomic";var f2=1,R9=8388608;function x6($,Z){return $ instanceof Error&&"code"in $&&$.code===Z}function OH($){if(typeof $==="string")return!0;if(!Array.isArray($))return!1;return $.every((Z)=>{if(!Z||typeof Z!=="object"||!("type"in Z))return!1;if(Z.type==="text")return"text"in Z&&typeof Z.text==="string";return Z.type==="image_url"&&"image_url"in Z&&typeof Z.image_url==="object"&&Z.image_url!==null&&"url"in Z.image_url&&typeof Z.image_url.url==="string"})}function EH($,Z,J){let Y;try{Y=JSON.parse($)}catch(X){throw Error(`Invalid steering inbox JSON: ${Z}`,{cause:X})}if(!Y||typeof Y!=="object"||!("version"in Y)||Y.version!==f2||!("sessionId"in Y)||Y.sessionId!==J||!("messages"in Y)||!Array.isArray(Y.messages))throw Error(`Invalid steering inbox record: ${Z}`);let U=Y.messages.map((X)=>{if(!X||typeof X!=="object"||!("id"in X)||typeof X.id!=="string"||!("content"in X)||!OH(X.content)||!("queuedAt"in X)||typeof X.queuedAt!=="number"||"persisted"in X&&typeof X.persisted!=="boolean")throw Error(`Invalid steering inbox message: ${Z}`);return{id:X.id,content:X.content,queuedAt:X.queuedAt,..."persisted"in X&&X.persisted===!0?{persisted:!0}:{}}});return{version:f2,sessionId:J,messages:U}}function qH($){return new Set($.flatMap((Z)=>Z.type==="inbox_acknowledged"?Z.data.messageIds:[]))}class S2{workspaceRoot;sessionId;filePath;mutex=new _H;messages=[];constructor($,Z,J){this.workspaceRoot=$;this.sessionId=Z;this.filePath=J}static async open($,Z){let J=new S2($,Z,e$($,Z));return await J.loadAndReconcile(),J}async enqueue($,Z){return this.mutex.runExclusive(async()=>{if(Z&&!Z(this.messages))return!1;let J=[...this.messages,{...$,recovered:!1}];return await this.persist(J),this.messages=J,!0})}async acknowledge($){if($.length===0)return;let Z=new Set($);await this.mutex.runExclusive(async()=>{let J=this.messages.filter((Y)=>!Z.has(Y.id));this.messages=J,await this.persist(J)})}list(){return this.messages.map(($)=>({...$,content:typeof $.content==="string"?$.content:$.content.map((Z)=>Z.type==="text"?{...Z}:{...Z,image_url:{...Z.image_url}})}))}count(){return this.messages.length}recoveredCount(){return this.messages.filter(($)=>$.recovered).length}async loadAndReconcile(){await this.mutex.runExclusive(async()=>{let $={version:f2,sessionId:this.sessionId,messages:[]};try{if((await d0.stat(this.filePath)).size>R9)throw Error(`Steering inbox exceeds ${R9} bytes: ${this.filePath}`);await d0.chmod(this.filePath,384),$=EH(await d0.readFile(this.filePath,"utf8"),this.filePath,this.sessionId)}catch(U){if(!x6(U,"ENOENT"))throw U}let Z=S0(this.workspaceRoot,this.sessionId),J=new Set;try{J=qH(R2(await d0.readFile(Z,"utf8"),Z))}catch(U){if(!x6(U,"ENOENT"))throw U}let Y=$.messages.filter((U)=>!J.has(U.id)).map((U)=>({...U,recovered:!0}));if(this.messages=Y,Y.length!==$.messages.length)await this.persist(Y)})}async persist($){if(await d0.mkdir(S9.dirname(this.filePath),{recursive:!0,mode:448}),$.length===0){await d0.unlink(this.filePath).catch((J)=>{if(!x6(J,"ENOENT"))throw J});return}let Z={version:f2,sessionId:this.sessionId,messages:$.map(({recovered:J,...Y})=>Y)};await GH(this.filePath,`${JSON.stringify(Z)}
|
|
896
|
+
`,{encoding:"utf8",mode:384,fsync:!0})}}var DH=20,wH=v9+I9;function k9($){if(typeof $==="string")return $.length;return $.reduce((Z,J)=>{if(J.type==="text")return Z+J.text.length;return Z+J.image_url.url.length},0)}class P2{inbox;transitionMutex=new FH;activeTurn;claimed=new Map;constructor($){this.inbox=$}static async create($,Z){return new P2(await S2.open($,Z))}beginTurn(){if(this.activeTurn)throw Error(`Session already has an active turn: ${this.activeTurn.id}`);return this.createTurn()}async enqueue($,Z={}){return this.transitionMutex.runExclusive(async()=>{if(!this.activeTurn&&!Z.allowBeforeTurn)return{accepted:!1,queued:this.inbox.count(),reason:"no_active_turn"};let J=this.activeTurn&&!this.activeTurn.sealed?"current_turn":"next_turn";return this.enqueueDurably($,J,Z)})}async prepareInputTurn($){return this.transitionMutex.runExclusive(async()=>{if(this.activeTurn)return{accepted:!1,queued:this.inbox.count(),reason:"turn_active"};let Z=this.inbox.count()>0,J=await this.enqueueDurably($,"next_turn");if(!J.accepted||!J.messageId)return{accepted:!1,queued:J.queued,reason:"queue_full"};let Y=this.createTurn();if(!Z){let U=this.inbox.list().find((X)=>X.id===J.messageId);if(!U)throw this.activeTurn=void 0,Error(`Prepared input disappeared from inbox: ${J.messageId}`);this.claimed.set(U.id,U)}return{accepted:!0,handle:Y,messageId:J.messageId,queued:J.queued,mode:Z?"pending":"direct"}})}async drain($){return this.transitionMutex.runExclusive(()=>{this.assertOwner($);let Z=this.inbox.list().filter((J)=>!this.claimed.has(J.id));for(let J of Z)this.claimed.set(J.id,J);return Z})}async drainOrSeal($){return this.transitionMutex.runExclusive(()=>{if(this.assertOwner($),this.inbox.count()>this.claimed.size){let Z=this.inbox.list().filter((J)=>!this.claimed.has(J.id));for(let J of Z)this.claimed.set(J.id,J);return{messages:Z,sealed:!1}}return this.activeTurn.sealed=!0,{messages:[],sealed:!0}})}async acknowledge($){await this.inbox.acknowledge($);for(let Z of $)this.claimed.delete(Z)}async claimedMessageIds($){return this.transitionMutex.runExclusive(()=>{return this.assertOwner($),[...this.claimed.keys()]})}async finishTurn($,Z={}){return this.transitionMutex.runExclusive(()=>{if(this.assertOwner($),this.activeTurn=void 0,this.claimed.clear(),!Z.continuePending||this.inbox.count()===0)return;return this.createTurn()})}async beginPendingTurn(){return this.transitionMutex.runExclusive(()=>{if(this.activeTurn||this.inbox.count()===0)return;return this.createTurn()})}isActive(){return Boolean(this.activeTurn&&!this.activeTurn.sealed)}hasTurnOwner(){return Boolean(this.activeTurn)}pendingCount(){return this.inbox.count()}pendingMessages(){return this.inbox.list()}recoveredCount(){return this.inbox.recoveredCount()}assertOwner($){if(!this.activeTurn||this.activeTurn.id!==$.id)throw Error(`Turn ${$.id} does not own this session mailbox`)}async enqueueDurably($,Z,J={}){let Y={id:J.messageId??P9(12),content:$,queuedAt:Date.now(),...J.persisted?{persisted:!0}:{}};if(!await this.inbox.enqueue(Y,(X)=>{if(X.length>=DH)return!1;return X.reduce((Q,W)=>Q+k9(W.content),0)+k9($)<=wH}))return{accepted:!1,turnId:this.activeTurn?.id,queued:this.inbox.count(),reason:"queue_full"};return{accepted:!0,messageId:Y.id,turnId:this.activeTurn?.id,queued:this.inbox.count(),delivery:Z}}createTurn(){let $={id:P9(12)};return this.activeTurn={id:$.id,sealed:!1},$}}var N0=u("Agent"),y9=new Map;async function x9($){let Z=y9.get($);if(!Z)Z=(async()=>{try{let J=await t0.cleanupStaleAgentWorktrees({workspaceRoot:$});if(J.removed>0)N0.info(`[WorktreeGC] removed ${J.removed} stale agent worktree(s)`);if(J.errors.length>0)N0.warn(`[WorktreeGC] completed with ${J.errors.length} error(s): ${J.errors.join("; ")}`)}catch(J){N0.warn(`[WorktreeGC] cleanup failed: ${J instanceof Error?J.message:String(J)}`)}})(),y9.set($,Z);await Z}class N${config;options;approvalStore=new N1;baseRegistry=new A$;attachmentCollector;goalStore;activeTurnMailbox;chatService;executionEngine;selectedModelId;selectedReasoningEffort;currentReasoning;selectedServiceTier;currentServiceTier;selectedResponseVerbosity;currentResponseVerbosity;selectedCommunicationStyle;currentModelId;currentModelMaxContextTokens;initialized=!1;sessionLease;sessionMcpRegistry;mcpCatalogListener;mcpContentCatalogListener;mcpResourceUpdatedListener;mcpConnectionListener;mcpLogListener;mcpInstructionsListener;mcpTaskListener;mcpCatalogBarrier=async()=>{return};executorCatalogs=new Map;agentResources;modelResources;lspResources;sessionEnvironment;subagentRegistry;autoVerifyRuntime;lspManager;userShellMutex=new LH;constructor($,Z){this.config=$;this.options=Z;if(this.selectedModelId=Z.modelId&&Z.modelId!=="inherit"?Z.modelId:void 0,this.selectedReasoningEffort=Z.reasoningEffort??"off",this.selectedServiceTier=Z.serviceTier??"auto",this.selectedResponseVerbosity=Z.responseVerbosity??"auto",this.selectedCommunicationStyle=Z.communicationStyle??"auto",Z.modelResources)this.modelResources=Z.modelResources;else{let J=new u9(d9().credentials);if($.modelProviders&&$.models)J.configureModelProviders($.modelProviders,$.models);this.modelResources={projectRoot:Y0.resolve(Z.workspaceRoot??N()),config:g9($),catalog:J}}this.lspResources=_1(Z.lspResources??{projectRoot:this.modelResources.projectRoot,servers:$.lspServers}),this.sessionEnvironment=Object.freeze({...$.env}),this.goalStore=new T0(this.workspaceRoot,this.sessionId),this.attachmentCollector=new q1({cwd:this.workspaceRoot,maxFileSize:1048576,maxLines:2000,maxTokens:32000})}static async create($){let Z=$.workspaceRoot??N(),J=$.taskWorktree,Y=$.taskIsolation,U=$.modelId,X=$.reasoningEffort,H=$.serviceTier,Q=$.responseVerbosity,W=$.communicationStyle,z=$.communicationStyleDigest,V=$.projectInstructionsDigest,B=U!==void 0,K=W!==void 0;try{await K2();let G=await n.findSessionMetadata($.sessionId,Z);if(G?.archivedAt)throw new t9($.sessionId,G.archivedBySessionId??$.sessionId);if(X??=G?.reasoningEffort??"off",H??=G?.serviceTier??"auto",Q??=G?.responseVerbosity??"auto",W??=G?.communicationStyle??"auto",!K||W===G?.communicationStyle)z??=G?.communicationStyleDigest;if(await x9(Z),V??=G?.projectInstructionsDigest,await x9(Z),!$.subagentInfo&&(!J||!Y||!U)){let b=await(J?Promise.resolve(void 0):n.findSessionTaskWorktree($.sessionId,Z));J??=b,Y??=G?.taskIsolation,U??=G?.selectedModelId??G?.taskModelId}if(J){if(Y0.resolve(J.workspaceRoot)!==Y0.resolve(Z))throw Error("Task worktree workspace does not match runtime workspace");await t0.restoreSession(J)}let O=W0();if(!O)throw Error("配置未初始化,请确保应用已正确启动");$1.configure(O.maxConcurrentTasks,O.maxQueuedTasks);let E=t.getInstance(),q=$.modelResources?.projectRoot??$.lspResources?.projectRoot??$.agentResources?.projectRoot??J?.originalWorkspaceRoot??Z,F=$.modelResources?c9($.modelResources):await p9(q,O),D=F.config.models,L=$.lspResources?_1($.lspResources):await b4(q,F.config.lspServers);if(D.length===0)throw Error(`没有可用的模型配置
|
|
897
897
|
|
|
898
898
|
`+`请先使用以下命令添加模型:
|
|
899
899
|
`+` /model add
|
|
900
900
|
|
|
901
901
|
`+`或运行初始化向导:
|
|
902
|
-
`+" /init");if(!B&&U&&U!=="inherit"&&!D.some((b)=>b.id===U))U=void 0;let A=await r1({workspaceRoot:q,storeServers:O.mcpServers??{},sessionServers:$.mcpServers,cliConfigs:$.mcpConfig,strictCliConfig:$.strictMcpConfig}),w={...F.config,lspServers:structuredClone(L.servers),permissions:await E.loadWorkspacePermissions(q,F.config.permissions),hooks:await E.loadWorkspaceHooks(q,F.config.hooks??{})};E.validateConfig(w,F.catalog);let j=new N$(w,{...$,modelResources:F,lspResources:L,mcpServers:A,...U?{modelId:U}:{},reasoningEffort:X,serviceTier:H,responseVerbosity:Q,communicationStyle:W,...z?{communicationStyleDigest:z}:{},...V?{projectInstructionsDigest:V}:{},...J?{taskWorktree:J}:{},...Y?{taskIsolation:Y}:{}});return await j.initialize(),j}catch(G){if(!$.subagentInfo&&!(G instanceof n9)){let O=J?await t0.getChangeSummary($.sessionId).catch(()=>{return}):void 0;await N$.persistTaskStatus($.sessionId,Z,"failed","Session runtime initialization failed",O??void 0).catch((E)=>{if(E.code!=="ENOENT")N0.warn(`[SessionRuntime ${$.sessionId}] Failed to persist initialization failure`,E)})}throw G}}static async hasPendingInbox($,Z){try{return(await AH(e$($,Z))).size>0}catch(J){if(J.code==="ENOENT")return!1;throw J}}static async hasActiveGoal($,Z){return j0.hasActiveGoal($,Z)}get sessionId(){return this.options.sessionId}get workspaceRoot(){return this.options.workspaceRoot??N()}get projectRoot(){return this.options.modelResources?.projectRoot??this.options.lspResources?.projectRoot??this.options.agentResources?.projectRoot??this.options.taskWorktree?.originalWorkspaceRoot??this.workspaceRoot}getConfig(){return this.config}getAvailableModels(){return this.config.models.map(($)=>structuredClone($))}getModelById($){let Z=this.config.models.find((J)=>J.id===$);return Z?structuredClone(Z):void 0}getAgentResources(){if(!this.agentResources)throw Error("Session agent resources are unavailable before initialization");return this.agentResources}getLspResources(){return _1(this.lspResources)}isTaskSession(){return!this.options.subagentInfo&&this.options.taskIsolation!==void 0}getTaskAdmissionLimits(){let $=$1.getStats();return{maxConcurrent:$.maxConcurrent,maxQueued:$.maxQueued}}async setTaskAdmission($){if(!this.isTaskSession())return;let Z=new Date().toISOString(),J=$.state==="queued",Y=await n.updateSessionMetadata(this.sessionId,this.workspaceRoot,{taskStatus:$.state,taskStatusReason:null,taskFailure:null,taskQueuePosition:J?$.queuePosition??1:null,taskQueueDepth:J?$.queueDepth:null,taskConcurrencyLimit:$.maxConcurrent,...J?{taskStartedAt:null,taskCompletedAt:null,taskOwnerPid:null}:{taskStartedAt:Z,taskCompletedAt:null,taskOwnerPid:process.pid}});return Z0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"task.status",{taskStatus:Y.taskStatus,...Y.taskStartedAt?{taskStartedAt:Y.taskStartedAt}:{},...$.queuePosition?{taskQueuePosition:$.queuePosition}:{},taskQueueDepth:$.queueDepth,taskConcurrencyLimit:$.maxConcurrent,taskInFlight:$.inFlight,updatedAt:Y.lastMessageTime}),Y}publishTaskAdmissionCapacity($){if(!this.isTaskSession())return;let Z=$1.getStats();Z0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"task.status",{taskStatus:$,taskQueueDepth:Z.queued,taskConcurrencyLimit:Z.maxConcurrent,taskInFlight:Z.inFlight,updatedAt:new Date().toISOString()})}getChatService(){if(!this.chatService)throw Error("Session runtime is not initialized");return this.chatService}getExecutionEngine(){if(!this.executionEngine)throw Error("Session runtime is not initialized");return this.executionEngine}getAttachmentCollector(){return this.attachmentCollector}getCurrentModelId(){return this.currentModelId}getReasoningConfiguration(){if(!this.currentReasoning)throw Error("Session runtime is not initialized");return{...this.currentReasoning,supported:[...this.currentReasoning.supported]}}resolveReasoningConfiguration($,Z=this.currentModelId){return w0(this.resolveModelConfig(Z),this.config,$,this.modelResources.catalog).reasoning}getServiceTierConfiguration(){if(!this.currentServiceTier)throw Error("Session runtime is not initialized");return{...this.currentServiceTier,supported:[...this.currentServiceTier.supported]}}resolveServiceTierConfiguration($,Z=this.currentModelId){return w0(this.resolveModelConfig(Z),this.config,this.selectedReasoningEffort,this.modelResources.catalog,$).serviceTier}getResponseVerbosityConfiguration(){if(!this.currentResponseVerbosity)throw Error("Session runtime is not initialized");return{...this.currentResponseVerbosity,supported:[...this.currentResponseVerbosity.supported]}}resolveResponseVerbosityConfiguration($,Z=this.currentModelId){return w0(this.resolveModelConfig(Z),this.config,this.selectedReasoningEffort,this.modelResources.catalog,this.selectedServiceTier,$).responseVerbosity}getCommunicationStyleConfiguration(){return k2(this.selectedCommunicationStyle,this.getCommunicationStyleCatalog())}resolveCommunicationStyleConfiguration($){return k2($,this.getCommunicationStyleCatalog())}getCommunicationStyleCatalog(){return this.agentResources?.communicationStyles??i9}getProjectRuleCatalog(){return this.agentResources?.projectRules??l9.empty(this.projectRoot)}getStaticProjectRules(){return this.getProjectRuleCatalog().staticRules(this.projectRoot)}hydrateProjectRules($){return this.getProjectRuleCatalog().hydrate($)}resolveContextualProjectRules($,Z,J,Y){let U=new Set;try{let W=this.baseRegistry.get($)?.build(Z);for(let z of W?.getAffectedPaths()??[])if(z)U.add(z)}catch{}let X=(W)=>{if(typeof W==="string"&&W.trim())U.add(W)};if(["Read","Edit","Write"].includes($))X(Z.file_path);else if($==="NotebookEdit")X(Z.notebook_path);else if(["Grep","Glob"].includes($))X(Z.path);else if($==="Bash")X(Z.cwd);let H=J?.metadata&&typeof J.metadata==="object"?J.metadata:void 0;if(Array.isArray(H?.affected_paths))for(let W of H.affected_paths)X(W);if(Array.isArray(H?.changes)){for(let W of H.changes)if(W&&typeof W==="object")X(W.path)}let Q=[...U].map((W)=>Y0.isAbsolute(W)?Y0.resolve(W):Y0.resolve(this.workspaceRoot,W)).flatMap((W)=>{let z=Y0.relative(this.workspaceRoot,W);if(z===""||!z.startsWith("..")&&!Y0.isAbsolute(z))return[Y0.resolve(this.projectRoot,z)];let V=Y0.relative(this.projectRoot,W);return V===""||!V.startsWith("..")&&!Y0.isAbsolute(V)?[W]:[]});return this.getProjectRuleCatalog().contextualRules(this.projectRoot,Q,Y)}getCurrentModelMaxContextTokens(){if(this.currentModelMaxContextTokens===void 0)throw Error("Session runtime is not initialized");return this.currentModelMaxContextTokens}getGoal(){return this.goalStore.get()}async setTaskStatus($,Z){if(this.options.subagentInfo)return;let J=this.options.taskWorktree&&!["queued","running"].includes($)?await t0.getChangeSummary(this.sessionId):void 0;return N$.persistTaskStatus(this.sessionId,this.workspaceRoot,$,Z,J??void 0)}static async persistTaskStatus($,Z,J,Y,U){let X=new Date().toISOString(),H=J==="failed"&&Y!==void 0?v2(Y):void 0,Q=H?.message??(typeof Y==="string"?Y.slice(0,500):void 0),W=await n.updateSessionMetadata($,Z,{taskStatus:J,taskStatusReason:Q??null,taskFailure:H??null,...U!==void 0?{taskDiffStat:U}:J==="running"?{taskDiffStat:null}:{},...J!=="queued"?{taskQueuePosition:null,taskQueueDepth:null}:{},...J==="running"?{taskStartedAt:X,taskCompletedAt:null,taskOwnerPid:process.pid}:J==="queued"?{taskStartedAt:null,taskCompletedAt:null,taskOwnerPid:null}:{taskCompletedAt:X,taskOwnerPid:null}});return Z0.publish({sessionId:$,projectPath:Z},"task.status",{taskStatus:W.taskStatus,...Q?{taskStatusReason:Q}:{},...H?{taskFailure:H}:{},...W.taskStartedAt?{taskStartedAt:W.taskStartedAt}:{},...W.taskCompletedAt?{taskCompletedAt:W.taskCompletedAt}:{},...W.taskDiffStat?{taskDiffStat:W.taskDiffStat}:{},...W.taskQueuePosition?{taskQueuePosition:W.taskQueuePosition}:{},...W.taskQueueDepth!==void 0?{taskQueueDepth:W.taskQueueDepth}:{},...W.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:W.taskConcurrencyLimit}:{},updatedAt:W.lastMessageTime}),W}createGoal($){return this.goalStore.create($)}editGoal($){return this.goalStore.edit($)}pauseGoal($){return this.goalStore.pause($)}resumeGoal(){return this.goalStore.resume()}clearGoal(){return this.goalStore.clear()}recordGoalProgress($){return this.goalStore.recordProgress($)}beginGoalContinuation(){return this.goalStore.tryBeginContinuation()}async pauseActiveGoal($){return this.goalStore.pauseIfActive($)}async listRewindCheckpoints(){return this.assertRewindIdle(),n.listRewindCheckpoints(this.sessionId,this.workspaceRoot)}async rewindSession($){return this.assertRewindIdle(),n.rewindSession(this.sessionId,this.workspaceRoot,$)}listSubagents(){return o.getInstance().listForSession({sessionId:this.sessionId,projectPath:this.workspaceRoot})}getMcpContentCatalog(){return this.sessionMcpRegistry?.getContentCatalogSnapshot()??{revision:0,resources:[],resourceTemplates:[],prompts:[]}}async refreshMcpContentCatalogs($){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");await this.sessionMcpRegistry.refreshContentCatalogs($)}async getMcpPrompt($,Z,J){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");return this.sessionMcpRegistry.getPrompt($,Z,J)}async completeMcpArgument($,Z,J){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");return this.sessionMcpRegistry.complete($,Z,J)}listMcpTasks($){return u0.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot},$)}getMcpTask($){return u0.getInstance().get($,{sessionId:this.sessionId,projectPath:this.workspaceRoot})}cancelMcpTask($,Z){return u0.getInstance().cancel($,{sessionId:this.sessionId,projectPath:this.workspaceRoot},Z)}getMcpLogs($,Z={}){return this.sessionMcpRegistry?.getLogSnapshot($,Z)??{revision:0,entries:[]}}getMcpInstructions(){return this.sessionMcpRegistry?.getInstructionsSnapshot()??{revision:0,instructions:[]}}async setMcpLoggingLevel($,Z){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");await this.sessionMcpRegistry.setServerLoggingLevel($,Z)}resumeSubagent($){this.assertSubagentControlIdle();let Z=o.getInstance(),J={sessionId:this.sessionId,projectPath:this.workspaceRoot},Y=Z.getAgent($.agentId,J);if(!Y)throw Error(`Subagent not found in this session: ${$.agentId}`);let U=this.subagentRegistry?.getSubagent(Y.subagentType),X=Y.configSnapshot?{...Y.configSnapshot}:U;if(!X)throw Error(`Subagent configuration is unavailable: ${Y.subagentType}`);let H=Z.resumeAgent({agentId:Y.id,prompt:$.prompt,config:X,owner:J,permissionMode:X.permissionMode,reasoningEffort:this.selectedReasoningEffort,serviceTier:this.selectedServiceTier,responseVerbosity:this.selectedResponseVerbosity,communicationStyle:this.selectedCommunicationStyle,agentResources:this.agentResources,modelResources:this.modelResources,lspResources:this.lspResources,onEvent:$.onEvent,onCompleted:$.onCompleted});if(!H)throw Error(`Subagent cannot be resumed: ${Y.id}`);let Q=Z.getAgent(H.agentId,J);if(!Q)throw Error(`Resumed subagent was not persisted: ${H.agentId}`);return{source:H.source,session:Q}}beginTurn(){return this.getActiveTurnMailbox().beginTurn()}async prepareInputTurn($){return this.getActiveTurnMailbox().prepareInputTurn($)}async enqueueSteering($,Z){return this.getActiveTurnMailbox().enqueue($,Z)}async drainSteering($){return this.getActiveTurnMailbox().drain($)}async drainSteeringOrSeal($){return this.getActiveTurnMailbox().drainOrSeal($)}async acknowledgeTurn($){let Z=this.getActiveTurnMailbox(),J=await Z.claimedMessageIds($);if(J.length===0)return;await this.getExecutionEngine().getContextManager().persistentStore.acknowledgeInboxMessages(this.sessionId,J),await Z.acknowledge(J)}async discardPendingInput(){let $=this.getActiveTurnMailbox(),Z=$.pendingMessages().map((J)=>J.id);if(Z.length===0)return;await this.getExecutionEngine().getContextManager().persistentStore.acknowledgeInboxMessages(this.sessionId,Z),await $.acknowledge(Z)}async finishTurn($,Z){return this.getActiveTurnMailbox().finishTurn($,Z)}async beginPendingTurn(){return this.getActiveTurnMailbox().beginPendingTurn()}hasActiveTurn(){return this.activeTurnMailbox?.isActive()??!1}hasTurnOwner(){return this.activeTurnMailbox?.hasTurnOwner()??!1}getPendingSteeringCount(){return this.activeTurnMailbox?.pendingCount()??0}getPendingSteeringMessages(){return this.activeTurnMailbox?.pendingMessages()??[]}getRecoveredSteeringCount(){return this.activeTurnMailbox?.recoveredCount()??0}async executeUserShellCommand($,Z={}){if(!this.initialized||!this.executionEngine)throw Error("Session runtime is not initialized");return this.userShellMutex.runExclusive(async()=>{let J=NH(12),Y=this.hasTurnOwner(),U=Z.signal??new AbortController().signal,X=async(K)=>{let G=K.type==="started"?{executionId:K.executionId,command:K.command,auxiliary:Y}:K.type==="output"?{executionId:K.executionId,stream:K.stream,chunk:K.chunk,streamedBytes:K.streamedBytes,streamTruncated:K.streamTruncated,auxiliary:Y}:{executionId:K.executionId,messageId:K.messageId,record:K.record,auxiliary:Y,delivery:K.delivery,queued:K.queued};Z0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},`user.shell.${K.type}`,G),await Z.onEvent?.(K)},H=await a9($,{executionId:J,cwd:this.workspaceRoot,env:{...process.env,...this.sessionEnvironment,BLADE_CLI:"1",BLADE_USER_SHELL:"1"},signal:U,timeoutMs:Z.timeoutMs,executor:this.options.userShellExecutor,onEvent:async(K)=>{if(K.type!=="completed")await X({...K,auxiliary:Y})}}),Q=o9(H),z=await this.getExecutionEngine().getContextManager().saveMessage(this.sessionId,"user",Q,null,{...Y?{inboxMessageId:J}:{},userShellCommand:JSON.parse(JSON.stringify(H))},this.options.subagentInfo),V=Y?await this.getActiveTurnMailbox().enqueue(Q,{allowBeforeTurn:!0,messageId:J,persisted:!0}):void 0,B={executionId:J,messageId:z,record:H,modelContent:Q,auxiliary:Y,...V?.delivery?{delivery:V.delivery}:{},...V?{queued:V.queued}:{}};return await X({type:"completed",executionId:J,messageId:z,record:H,auxiliary:Y,...V?.delivery?{delivery:V.delivery}:{},...V?{queued:V.queued}:{}}),B})}async initialize(){if(this.initialized)return;this.sessionLease=await r9.acquire(this.sessionId,this.workspaceRoot);try{if(!a(this.sessionId))await YZ(this.workspaceRoot);let $=G0.getInstance();if($.loadConfig(this.config.disableAllHooks?{...this.config.hooks,enabled:!1}:this.config.hooks??{},this.projectRoot),$.bindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot],this.modelResources),await this.loadAgentResources(),this.projectRoot!==this.workspaceRoot)$.inheritProjectConfig(this.projectRoot,this.workspaceRoot);$.bindSessionConfig(this.sessionId,[this.projectRoot,this.workspaceRoot],this.config.disableAllHooks?{...this.agentResources?.hooks??$.getConfig(this.projectRoot),enabled:!1}:this.agentResources?.hooks??$.getConfig(this.projectRoot));let Z=await $.executeSessionStartHooks({projectDir:this.workspaceRoot,sessionId:this.sessionId,permissionMode:this.config.permissionMode??"default",isResume:this.options.sessionStart?.isResume??!1,resumeSessionId:this.options.sessionStart?.resumeSessionId});if(!Z.proceed)throw Error(Z.warning||"SessionStart hook blocked initialization");if(Z.warning)N0.warn(`[SessionRuntime ${this.sessionId}] SessionStart hook warning: ${Z.warning}`);let J=m9(Z.env??{});if(this.sessionEnvironment=Object.freeze({...this.sessionEnvironment,...J}),this.config.env=this.sessionEnvironment,$.bindSessionEnvironment(this.sessionId,[this.projectRoot,this.workspaceRoot],this.sessionEnvironment),Object.keys(this.lspResources.servers).length>0)this.lspManager=new J5({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,environment:this.sessionEnvironment,servers:this.lspResources.servers});if(!this.lspManager?.available)this.autoVerifyRuntime=new y6({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,projectRoot:this.projectRoot,environment:this.sessionEnvironment});await this.validateSystemPromptConfig(),this.activeTurnMailbox=await P2.create(this.workspaceRoot,this.sessionId),await this.registerBuiltinTools(),await this.applyModelConfig(this.resolveModelConfig(this.selectedModelId),"使用模型:",this.selectedReasoningEffort,this.selectedServiceTier,this.selectedResponseVerbosity),await this.getExecutionEngine().getContextManager().persistentStore.initSession(this.sessionId,this.options.subagentInfo),this.initialized=!0,N0.debug(`[SessionRuntime ${this.sessionId}] initialized with ${this.baseRegistry.getAll().length} tools`)}catch($){try{await this.dispose()}catch(Z){N0.warn(`[SessionRuntime ${this.sessionId}] Failed to clean up after initialization error`,Z)}throw $}}async refresh($){if(!this.initialized){await this.initialize();return}let Z=$.modelId==="inherit",J=$.modelId&&!Z?$.modelId:void 0,Y=Z?this.getDefaultModel()?.id:J??this.selectedModelId??this.getDefaultModel()?.id,U=$.reasoningEffort??this.selectedReasoningEffort,X=$.serviceTier??this.selectedServiceTier,H=$.responseVerbosity??this.selectedResponseVerbosity,Q=$.communicationStyle??this.selectedCommunicationStyle;if(k2(Q,this.getCommunicationStyleCatalog()),Y&&(Y!==this.currentModelId||U!==this.selectedReasoningEffort||X!==this.selectedServiceTier||H!==this.selectedResponseVerbosity))await this.applyModelConfig(this.resolveModelConfig(Y),Y!==this.currentModelId?"切换模型":U!==this.selectedReasoningEffort?"切换推理强度":X!==this.selectedServiceTier?"切换服务等级":"切换输出详略",U,X,H);if(Z)this.selectedModelId=void 0;else if(J)this.selectedModelId=J;this.selectedReasoningEffort=U,this.selectedServiceTier=X,this.selectedResponseVerbosity=H,this.selectedCommunicationStyle=Q}createToolExecutor($={}){let Z=new A$;Z.setMcpCatalogBarrier(this.mcpCatalogBarrier);let J=$.toolWhitelist?new Set($.toolWhitelist):null,Y=$.toolBlacklist?new Set($.toolBlacklist):null;for(let W of this.baseRegistry.getBuiltinTools()){if(Y?.has(W.name))continue;if(!J||J.has(W.name))Z.register(W)}Z.replaceMcpTools(this.filterMcpTools(this.baseRegistry.getMcpTools(),J,Y));let U=this.getMcpInstructions();if(Z.queueMcpInstructionsChange({revision:U.revision,reason:"snapshot",replace:!0,instructions:U.instructions,removed:[]}),["TaskOutput","ListMcpTasks","CancelMcpTask"].some((W)=>!Y?.has(W)&&(!J||J.has(W))))for(let W of u0.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot})){let{result:z,...V}=W;Z.queueMcpTaskChange({revision:0,...V})}this.executorCatalogs.set(Z,{allowed:J,blocked:Y});let H={...this.config.permissions,...$.permissions},Q=$.permissionMode??this.config.permissionMode??"default";return new b1(Z,{permissionConfig:H,permissionMode:Q,approvalStore:this.approvalStore,maxHistorySize:1000,toolWhitelist:$.toolWhitelist,toolBlacklist:$.toolBlacklist,contextDefaults:{sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,environment:this.sessionEnvironment,permissionMode:Q,mcpSamplingHandler:this.handleMcpSampling},...this.lspManager?{lspManager:this.lspManager}:{},...Q==="yolo"&&this.autoVerifyRuntime?{autoVerifyRuntime:this.autoVerifyRuntime}:{},onDispose:()=>{this.executorCatalogs.delete(Z)}})}createExecutionPipeline($={}){return this.createToolExecutor($)}async dispose(){let $,Z=async(O,E)=>{try{await E()}catch(q){$??=q,N0.warn(`[SessionRuntime ${this.sessionId}] Failed to ${O} during cleanup`,q)}},J=this.chatService,Y=this.sessionMcpRegistry,U=this.mcpCatalogListener,X=this.mcpContentCatalogListener,H=this.mcpResourceUpdatedListener,Q=this.mcpConnectionListener,W=this.mcpLogListener,z=this.mcpInstructionsListener,V=this.mcpTaskListener,B=this.sessionLease,K=this.autoVerifyRuntime,G=this.lspManager;if(this.chatService=void 0,this.executionEngine=void 0,this.activeTurnMailbox=void 0,this.currentModelMaxContextTokens=void 0,this.baseRegistry=new A$,this.sessionMcpRegistry=void 0,this.mcpCatalogListener=void 0,this.mcpContentCatalogListener=void 0,this.mcpResourceUpdatedListener=void 0,this.mcpConnectionListener=void 0,this.mcpLogListener=void 0,this.mcpInstructionsListener=void 0,this.mcpTaskListener=void 0,this.mcpCatalogBarrier=async()=>{return},this.executorCatalogs.clear(),this.sessionLease=void 0,this.autoVerifyRuntime=void 0,this.lspManager=void 0,await Z("kill the session background processes",()=>s.getInstance().killSession(this.sessionId)),await Z("clear the session approvals",()=>this.approvalStore.clear()),await Z("clear the session file access records",()=>V0.getInstance().clearSession(this.sessionId,this.workspaceRoot)),await Z("stop the session auto-verification processes",()=>K?.dispose()),await Z("stop the session LSP servers",()=>G?.dispose()),await Z("release the session hook model resources",()=>G0.getInstance().unbindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot])),await Z("release the session worktrees",()=>t0.releaseSession(this.sessionId)),await Z("dispose the session chat service",()=>J?.dispose?.()),await Z("cancel the session MCP tasks",()=>u0.getInstance().cancelSession({sessionId:this.sessionId,projectPath:this.workspaceRoot})),await Z("disconnect the session MCP servers",async()=>{if(Y&&U)Y.off("catalogChanged",U);if(Y&&X)Y.off("contentCatalogChanged",X);if(Y&&H)Y.off("resourceUpdated",H);if(Y&&Q)Y.off("connectionLifecycleChanged",Q);if(Y&&W)Y.off("log",W);if(Y&&z)Y.off("instructionsChanged",z);if(V)u0.getInstance().off("taskChanged",V);await Y?.disconnectAll()}),await Z("release the session lease",()=>B?.release()),this.currentModelId=void 0,this.currentReasoning=void 0,this.currentServiceTier=void 0,this.initialized=!1,$!==void 0)throw $}resolveModelConfig($){let Z=$&&$!=="inherit"?$:void 0,J=Z?this.config.models.find((Y)=>Y.id===Z):this.getDefaultModel();if(!J)throw Error(`模型配置未找到: ${Z??"current"}`);return J}getDefaultModel(){return this.config.models.find(($)=>$.id===this.config.currentModelId)??this.config.models[0]}getActiveTurnMailbox(){if(!this.activeTurnMailbox)throw Error("Session runtime is not initialized");return this.activeTurnMailbox}assertRewindIdle(){if(this.hasTurnOwner())throw Error("Cannot rewind while the session has an active turn");if(this.getPendingSteeringCount()>0)throw Error("Cannot rewind while durable input is pending");if(s.getInstance().listForSession(this.sessionId).some(($)=>$.status==="running"))throw Error("Cannot rewind while a background shell is running");if(o.getInstance().listForSession({sessionId:this.sessionId,projectPath:this.workspaceRoot}).some(($)=>$.status==="running"))throw Error("Cannot rewind while a background agent is running")}assertSubagentControlIdle(){if(this.hasTurnOwner())throw Error("Cannot resume a subagent while the session has an active turn");if(this.getPendingSteeringCount()>0)throw Error("Cannot resume a subagent while durable input is pending")}async applyModelConfig($,Z,J,Y,U){let X=w0($,this.config,J,this.modelResources.catalog,Y,U);N0.debug(`${Z} ${X.displayName} (${$.model})`);let H=X.model.contextWindow,Q=await _2(X.chat),W=this.initialized?this.chatService:void 0,z=this.executionEngine?.getContextManager();this.chatService=Q,this.executionEngine=new T1(Q,z,this.workspaceRoot),this.currentModelMaxContextTokens=H,this.currentModelId=$.id,this.currentReasoning=X.reasoning,this.currentServiceTier=X.serviceTier,this.currentResponseVerbosity=X.responseVerbosity;let V=W;try{await V?.dispose?.()}catch(B){N0.warn(`[SessionRuntime ${this.sessionId}] Failed to dispose previous model service`,B)}}async validateSystemPromptConfig(){let $=this.getStaticProjectRules();if(this.options.projectInstructionsDigest&&$.provenanceSha256!==this.options.projectInstructionsDigest)throw Error("Project instruction provenance mismatch");if(!this.options.subagentInfo&&$.files.length>0&&!this.options.projectInstructionsDigest)await this.persistSystemPromptProvenance({projectInstructionsDigest:$.provenanceSha256}),this.options.projectInstructionsDigest=$.provenanceSha256;let Z=this.resolveCommunicationStyleConfiguration(this.selectedCommunicationStyle);if(Z.source!=="built-in"&&this.options.communicationStyleDigest&&Z.contentSha256!==this.options.communicationStyleDigest)throw Error(`Communication style provenance mismatch: ${this.selectedCommunicationStyle}`);if(Z.source!=="built-in"&&Z.contentSha256&&!this.options.communicationStyleDigest)await this.persistSystemPromptProvenance({communicationStyleDigest:Z.contentSha256}),this.options.communicationStyleDigest=Z.contentSha256;try{await k$({projectPath:this.workspaceRoot,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList()??"",communicationStyle:this.selectedCommunicationStyle,communicationStyleCatalog:this.getCommunicationStyleCatalog(),projectRuleCatalog:this.getProjectRuleCatalog(),projectInstructionSourcePath:this.projectRoot})}catch(J){N0.warn("[SessionRuntime] Failed to validate system prompt configuration:",J)}}async persistSystemPromptProvenance($){try{await n.updateSessionMetadata(this.sessionId,this.workspaceRoot,$)}catch(Z){if(!(Z instanceof s9||Z.code==="ENOENT")||this.options.subagentInfo)throw Z;await n.createSessionMetadata(this.sessionId,this.workspaceRoot,$)}}async registerBuiltinTools(){let Z=(await O2({sessionId:this.sessionId,configDir:Y0.join(e9.homedir(),".blade"),workspaceRoot:this.workspaceRoot,resourceRoot:this.projectRoot,agentResources:this.agentResources,modelResources:this.modelResources,lspManager:this.lspManager,lspResources:this.lspResources,getReasoningEffort:()=>this.selectedReasoningEffort,getServiceTier:()=>this.selectedServiceTier,getResponseVerbosity:()=>this.selectedResponseVerbosity,getCommunicationStyle:()=>this.selectedCommunicationStyle})).filter((J)=>!J.name.startsWith("mcp__"));this.baseRegistry.registerAll(Z),await this.registerMcpTools()}async registerMcpTools(){try{let $=this.options.mcpServers??{};if(Object.keys($).length===0)return;let Z=k0.createIsolated({roots:a(this.sessionId)?[]:[this.workspaceRoot],samplingAvailable:!0,oauthCredentialAccess:!a(this.sessionId),artifactWriter:new G1(`${this.projectRoot}\x00${this.sessionId}`,{exposePaths:!a(this.sessionId)}),exposeLogDetails:!a(this.sessionId),exposeInstructions:!a(this.sessionId)});this.sessionMcpRegistry=Z,this.mcpCatalogBarrier=()=>Z.waitForCatalogIdle(),this.baseRegistry.setMcpCatalogBarrier(this.mcpCatalogBarrier);let J=(z)=>{this.applyMcpCatalog(z,this.initialized)};this.mcpCatalogListener=J,Z.on("catalogChanged",J);let Y=(z)=>{this.applyMcpContentCatalog(z)},U=(z)=>{this.applyMcpResourceUpdated(z)},X=(z)=>{this.applyMcpConnectionChange(z)},H=(z)=>{this.applyMcpLog(z)},Q=(z)=>{this.applyMcpInstructions(z)},W=(z)=>{if(z.owner.sessionId!==this.sessionId||Y0.resolve(z.owner.projectPath)!==Y0.resolve(this.workspaceRoot))return;this.applyMcpTask(z);let{owner:V,result:B,...K}=z;Z0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"mcp.task.changed",K)};this.mcpContentCatalogListener=Y,this.mcpResourceUpdatedListener=U,this.mcpConnectionListener=X,this.mcpLogListener=H,this.mcpInstructionsListener=Q,this.mcpTaskListener=W,Z.on("contentCatalogChanged",Y),Z.on("resourceUpdated",U),Z.on("connectionLifecycleChanged",X),Z.on("log",H),Z.on("instructionsChanged",Q),u0.getInstance().on("taskChanged",W);for(let[z,V]of Object.entries($))try{let B=V.type==="stdio"?{...this.sessionEnvironment,...V.env}:void 0;await Z.registerServer(z,V.type==="stdio"?{...V,...B&&Object.keys(B).length>0?{env:B}:{}}:V)}catch(B){N0.warn(`Warning: MCP server "${z}" connection failed:`,B)}this.baseRegistry.replaceMcpTools(Z.getCatalogSnapshot().tools),this.baseRegistry.registerAll(A1(Z)),this.baseRegistry.registerAll(H6(Z))}catch($){N0.warn("Failed to register MCP tools:",$)}}filterMcpTools($,Z,J){return $.filter((Y)=>!J?.has(Y.name)&&(!Z||Z.has(Y.name)))}applyMcpCatalog($,Z){this.baseRegistry.replaceMcpTools($.tools);for(let[J,Y]of this.executorCatalogs){let U=this.filterMcpTools($.tools,Y.allowed,Y.blocked),X=(W)=>!Y.blocked?.has(W)&&(!Y.allowed||Y.allowed.has(W)),H={revision:$.revision,serverName:$.serverName,reason:$.reason,added:$.added.filter(X),removed:$.removed.filter(X),updated:$.updated.filter(X)},Q=H.added.length>0||H.removed.length>0||H.updated.length>0;J.replaceMcpTools(U,Z&&Q?H:void 0)}}applyMcpContentCatalog($){if(!this.initialized)return;let Z=$.kind==="resources"?["ListMcpResources","ReadMcpResource"]:$.kind==="resourceTemplates"?["ListMcpResourceTemplates","CompleteMcpArgument"]:["ListMcpPrompts","CompleteMcpArgument","GetMcpPrompt"];for(let[J,Y]of this.executorCatalogs)if(Z.some((X)=>!Y.blocked?.has(X)&&(!Y.allowed||Y.allowed.has(X))))J.queueMcpContentChange($)}applyMcpResourceUpdated($){if(!this.initialized)return;for(let[Z,J]of this.executorCatalogs)if(!J.blocked?.has("ReadMcpResource")&&(!J.allowed||J.allowed.has("ReadMcpResource")))Z.queueMcpResourceUpdated($)}applyMcpConnectionChange($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpConnectionChange($)}applyMcpLog($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpLog($)}applyMcpInstructions($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpInstructionsChange({revision:$.revision,reason:$.reason,replace:!1,instructions:$.action==="added"&&$.instruction?[{serverName:$.serverName,...$.instruction}]:[],removed:$.action==="removed"?[$.serverName]:[]})}applyMcpTask($){if(!this.initialized)return;let{owner:Z,result:J,...Y}=$;for(let[U,X]of this.executorCatalogs)if(["TaskOutput","ListMcpTasks","CancelMcpTask"].some((Q)=>!X.blocked?.has(Q)&&(!X.allowed||X.allowed.has(Q))))U.queueMcpTaskChange(Y)}handleMcpSampling=async($,Z)=>{let J=this.getChatService(),Y=await J.chat($.messages,void 0,Z,{maxOutputTokens:$.maxTokens,...$.temperature!==void 0?{temperature:$.temperature}:{}});return h9(Y,J.getConfig().model,$)};async loadAgentResources(){let $=this.options.agentResources?this.options.agentResources:await t(this.projectRoot,{reconcilePlugins:!0});if(this.agentResources=G2($),this.subagentRegistry=this.agentResources.subagents,this.options.agents?.length)this.subagentRegistry.applyOverrides(this.options.agents)}}async function h6(){let $=await e.getInstance().reload();H0().config.actions.setConfig($),await k0.getInstance().disconnectAll(),$7(),await t(N())}import yW from"fuse.js";import B$ from"node:path";import{Mutex as bH}from"async-mutex";var K$=new bH;async function J7($){await $.reapplyEnabledSettings(),n$($.getWorkspaceRoot()),await l$($.getWorkspaceRoot()),await u6(await t($.getWorkspaceRoot()))}async function jH($){n$($.getWorkspaceRoot());let Z=await $.refresh();return await l$($.getWorkspaceRoot()),await u6(await t($.getWorkspaceRoot())),Z}async function d6($){let Z=await t($),J=Array.from(new Set([Z.plugins,...I2.getInitializedInstances()])),Y;for(let U of J){let X=await jH(U);if(U===Z.plugins)Y=X}return Y??{plugins:[],errors:[]}}async function TH($,Z){let J=B$.resolve($),Y=u$();await Promise.all([Y.removePluginSetting(Z,{scope:"global",immediate:!0}),Y.removePluginSetting(Z,{scope:"project",projectDir:J,immediate:!0}),Y.removePluginSetting(Z,{scope:"local",projectDir:J,immediate:!0})])}function MH($){return B$.isAbsolute($)||$.startsWith("./")||$.startsWith("../")||$==="~"||$.startsWith("~/")}async function Y7($,Z){if(MH(Z)&&!(await T0.getInstance().getStatus($)).trusted)throw Error("Local plugin sources require a trusted workspace")}async function y2($,Z,J,Y="local"){return K$.runExclusive(async()=>{let U=B$.resolve($),X=await t(U),H=X.plugins.get(Z);if(!H)throw Error(`Plugin not found: ${Z}`);if(H.source==="cli")throw Error(`Plugin "${Z}" was loaded with --plugin-dir and is invocation-scoped`);await u$().save({enabledPlugins:{[Z]:J}},{scope:Y,projectDir:U,immediate:!0});let Q=Y==="global"?Array.from(new Set([X.plugins,...I2.getInitializedInstances()])):[X.plugins];for(let z of Q)await J7(z);let W=X.plugins.get(Z);if(!W)throw Error(`Plugin disappeared during reconciliation: ${Z}`);return{name:Z,requestedEnabled:J,effectiveEnabled:W.status==="active",scope:Y,source:W.source,status:W.status}})}async function x2($){return K$.runExclusive(async()=>{let Z=await t($);n$(Z.workspaceRoot);let J=await Z.plugins.refresh();return await l$(Z.workspaceRoot),{registry:Z.plugins,discovery:J}})}async function m6($,Z,J="global"){return K$.runExclusive(async()=>{let Y=B$.resolve($),U={...Z,...Z7(Z)};await u$().save({pluginSourcePolicy:U},{scope:J,projectDir:Y,immediate:!0});let X=await t(Y),H=J==="global"?Array.from(new Set([X.plugins,...I2.getInitializedInstances()])):[X.plugins];for(let Q of H)await J7(Q);return e.getInstance().loadWorkspacePluginSourcePolicy(Y)})}async function g6($,Z,J={}){return K$.runExclusive(async()=>{let Y=B$.resolve($);await Y7(Y,Z);let U=await e.getInstance().loadWorkspacePluginSourcePolicy(Y),X=await m0().install(Z,{...J,workspaceRoot:Y,policy:U});if(!X.success)return{result:X};let H=await d6(Y);return{result:X,discovery:H}})}async function p6($,Z,J={}){return K$.runExclusive(async()=>{let Y=B$.resolve($),U=await e.getInstance().loadWorkspacePluginSourcePolicy(Y),X=await m0().update(Z,{...J,workspaceRoot:Y,policy:U});if(!X.success)return{result:X};let H=await d6(Y);return{result:X,discovery:H}})}async function c6($,Z,J=!1){return K$.runExclusive(async()=>{let Y=B$.resolve($),X=(await t(Y)).plugins.getAll().filter((W)=>W.manifest.name!==Z&&W.manifest.dependencies?.[Z]!==void 0).map((W)=>W.manifest.name).sort();if(X.length>0)return{result:{success:!1,pluginName:Z,code:"PLUGIN_REQUIRED",error:`Plugin "${Z}" is required by: ${X.join(", ")}`}};let H=await m0().uninstall(Z,J);if(!H.success)return{result:H};await TH(Y,Z);let Q=await d6(Y);return{result:H,discovery:Q}})}async function i6($,Z,J){return K$.runExclusive(async()=>{let Y=B$.resolve($);await Y7(Y,Z);let U=await e.getInstance().loadWorkspacePluginSourcePolicy(Y);return m0().addMarketplace(Z,{workspaceRoot:Y,ref:J,policy:U})})}async function l6($,Z){return K$.runExclusive(async()=>{let J=B$.resolve($),Y=await e.getInstance().loadWorkspacePluginSourcePolicy(J);return m0().refreshMarketplace(Z,Y)})}async function n6($,Z=!1){return K$.runExclusive(()=>m0().removeMarketplace($,Z))}import y7 from"node:fs/promises";import x7 from"node:path";async function h2($,Z,J={}){let Y=Date.now(),U=J.timeoutMs??20000,X="unknown";try{let H=w0($,Z,"off");X=H.model.api;let W=await new U7({...H.chat,temperature:0,maxOutputTokens:8,timeout:U,streamIdleTimeout:U,maxRetries:0,fallbackModels:[]}).chat([{role:"user",content:"Reply with OK."}],void 0,AbortSignal.timeout(U));if(!Boolean(W.content||W.reasoningContent||W.finishReason||W.usage))throw Error("Provider returned an empty response");return{ok:!0,providerId:$.provider,modelConfigId:$.id,model:$.model,wireApi:X,latencyMs:Date.now()-Y,code:"ok",message:"Provider responded successfully."}}catch(H){let Q=v2(H);return{ok:!1,providerId:$.provider,modelConfigId:$.id,model:$.model,wireApi:X,latencyMs:Date.now()-Y,code:Q.code,message:Q.message}}}import CH from"node:os";import X7 from"node:path";function v($){if($.acp)return{sendMessage:(Z)=>$.acp.sendMessage(`• ${Z}
|
|
902
|
+
`+" /init");if(!B&&U&&U!=="inherit"&&!D.some((b)=>b.id===U))U=void 0;let A=await r1({workspaceRoot:q,storeServers:O.mcpServers??{},sessionServers:$.mcpServers,cliConfigs:$.mcpConfig,strictCliConfig:$.strictMcpConfig}),w={...F.config,lspServers:structuredClone(L.servers),permissions:await E.loadWorkspacePermissions(q,F.config.permissions),hooks:await E.loadWorkspaceHooks(q,F.config.hooks??{})};E.validateConfig(w,F.catalog);let T=new N$(w,{...$,modelResources:F,lspResources:L,mcpServers:A,...U?{modelId:U}:{},reasoningEffort:X,serviceTier:H,responseVerbosity:Q,communicationStyle:W,...z?{communicationStyleDigest:z}:{},...V?{projectInstructionsDigest:V}:{},...J?{taskWorktree:J}:{},...Y?{taskIsolation:Y}:{}});return await T.initialize(),T}catch(G){if(!$.subagentInfo&&!(G instanceof n9)){let O=J?await t0.getChangeSummary($.sessionId).catch(()=>{return}):void 0;await N$.persistTaskStatus($.sessionId,Z,"failed","Session runtime initialization failed",O??void 0).catch((E)=>{if(E.code!=="ENOENT")N0.warn(`[SessionRuntime ${$.sessionId}] Failed to persist initialization failure`,E)})}throw G}}static async hasPendingInbox($,Z){try{return(await AH(e$($,Z))).size>0}catch(J){if(J.code==="ENOENT")return!1;throw J}}static async hasActiveGoal($,Z){return T0.hasActiveGoal($,Z)}get sessionId(){return this.options.sessionId}get workspaceRoot(){return this.options.workspaceRoot??N()}get projectRoot(){return this.options.modelResources?.projectRoot??this.options.lspResources?.projectRoot??this.options.agentResources?.projectRoot??this.options.taskWorktree?.originalWorkspaceRoot??this.workspaceRoot}getConfig(){return this.config}getAvailableModels(){return this.config.models.map(($)=>structuredClone($))}getModelById($){let Z=this.config.models.find((J)=>J.id===$);return Z?structuredClone(Z):void 0}getAgentResources(){if(!this.agentResources)throw Error("Session agent resources are unavailable before initialization");return this.agentResources}getLspResources(){return _1(this.lspResources)}isTaskSession(){return!this.options.subagentInfo&&this.options.taskIsolation!==void 0}getTaskAdmissionLimits(){let $=$1.getStats();return{maxConcurrent:$.maxConcurrent,maxQueued:$.maxQueued}}async setTaskAdmission($){if(!this.isTaskSession())return;let Z=new Date().toISOString(),J=$.state==="queued",Y=await n.updateSessionMetadata(this.sessionId,this.workspaceRoot,{taskStatus:$.state,taskStatusReason:null,taskFailure:null,taskQueuePosition:J?$.queuePosition??1:null,taskQueueDepth:J?$.queueDepth:null,taskConcurrencyLimit:$.maxConcurrent,...J?{taskStartedAt:null,taskCompletedAt:null,taskOwnerPid:null}:{taskStartedAt:Z,taskCompletedAt:null,taskOwnerPid:process.pid}});return Z0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"task.status",{taskStatus:Y.taskStatus,...Y.taskStartedAt?{taskStartedAt:Y.taskStartedAt}:{},...$.queuePosition?{taskQueuePosition:$.queuePosition}:{},taskQueueDepth:$.queueDepth,taskConcurrencyLimit:$.maxConcurrent,taskInFlight:$.inFlight,updatedAt:Y.lastMessageTime}),Y}publishTaskAdmissionCapacity($){if(!this.isTaskSession())return;let Z=$1.getStats();Z0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"task.status",{taskStatus:$,taskQueueDepth:Z.queued,taskConcurrencyLimit:Z.maxConcurrent,taskInFlight:Z.inFlight,updatedAt:new Date().toISOString()})}getChatService(){if(!this.chatService)throw Error("Session runtime is not initialized");return this.chatService}getExecutionEngine(){if(!this.executionEngine)throw Error("Session runtime is not initialized");return this.executionEngine}getAttachmentCollector(){return this.attachmentCollector}getCurrentModelId(){return this.currentModelId}getReasoningConfiguration(){if(!this.currentReasoning)throw Error("Session runtime is not initialized");return{...this.currentReasoning,supported:[...this.currentReasoning.supported]}}resolveReasoningConfiguration($,Z=this.currentModelId){return w0(this.resolveModelConfig(Z),this.config,$,this.modelResources.catalog).reasoning}getServiceTierConfiguration(){if(!this.currentServiceTier)throw Error("Session runtime is not initialized");return{...this.currentServiceTier,supported:[...this.currentServiceTier.supported]}}resolveServiceTierConfiguration($,Z=this.currentModelId){return w0(this.resolveModelConfig(Z),this.config,this.selectedReasoningEffort,this.modelResources.catalog,$).serviceTier}getResponseVerbosityConfiguration(){if(!this.currentResponseVerbosity)throw Error("Session runtime is not initialized");return{...this.currentResponseVerbosity,supported:[...this.currentResponseVerbosity.supported]}}resolveResponseVerbosityConfiguration($,Z=this.currentModelId){return w0(this.resolveModelConfig(Z),this.config,this.selectedReasoningEffort,this.modelResources.catalog,this.selectedServiceTier,$).responseVerbosity}getCommunicationStyleConfiguration(){return k2(this.selectedCommunicationStyle,this.getCommunicationStyleCatalog())}resolveCommunicationStyleConfiguration($){return k2($,this.getCommunicationStyleCatalog())}getCommunicationStyleCatalog(){return this.agentResources?.communicationStyles??i9}getProjectRuleCatalog(){return this.agentResources?.projectRules??l9.empty(this.projectRoot)}getStaticProjectRules(){return this.getProjectRuleCatalog().staticRules(this.projectRoot)}hydrateProjectRules($){return this.getProjectRuleCatalog().hydrate($)}resolveContextualProjectRules($,Z,J,Y){let U=new Set;try{let W=this.baseRegistry.get($)?.build(Z);for(let z of W?.getAffectedPaths()??[])if(z)U.add(z)}catch{}let X=(W)=>{if(typeof W==="string"&&W.trim())U.add(W)};if(["Read","Edit","Write"].includes($))X(Z.file_path);else if($==="NotebookEdit")X(Z.notebook_path);else if(["Grep","Glob"].includes($))X(Z.path);else if($==="Bash")X(Z.cwd);let H=J?.metadata&&typeof J.metadata==="object"?J.metadata:void 0;if(Array.isArray(H?.affected_paths))for(let W of H.affected_paths)X(W);if(Array.isArray(H?.changes)){for(let W of H.changes)if(W&&typeof W==="object")X(W.path)}let Q=[...U].map((W)=>Y0.isAbsolute(W)?Y0.resolve(W):Y0.resolve(this.workspaceRoot,W)).flatMap((W)=>{let z=Y0.relative(this.workspaceRoot,W);if(z===""||!z.startsWith("..")&&!Y0.isAbsolute(z))return[Y0.resolve(this.projectRoot,z)];let V=Y0.relative(this.projectRoot,W);return V===""||!V.startsWith("..")&&!Y0.isAbsolute(V)?[W]:[]});return this.getProjectRuleCatalog().contextualRules(this.projectRoot,Q,Y)}getCurrentModelMaxContextTokens(){if(this.currentModelMaxContextTokens===void 0)throw Error("Session runtime is not initialized");return this.currentModelMaxContextTokens}getGoal(){return this.goalStore.get()}async setTaskStatus($,Z){if(this.options.subagentInfo)return;let J=this.options.taskWorktree&&!["queued","running"].includes($)?await t0.getChangeSummary(this.sessionId):void 0;return N$.persistTaskStatus(this.sessionId,this.workspaceRoot,$,Z,J??void 0)}static async persistTaskStatus($,Z,J,Y,U){let X=new Date().toISOString(),H=J==="failed"&&Y!==void 0?v2(Y):void 0,Q=H?.message??(typeof Y==="string"?Y.slice(0,500):void 0),W=await n.updateSessionMetadata($,Z,{taskStatus:J,taskStatusReason:Q??null,taskFailure:H??null,...U!==void 0?{taskDiffStat:U}:J==="running"?{taskDiffStat:null}:{},...J!=="queued"?{taskQueuePosition:null,taskQueueDepth:null}:{},...J==="running"?{taskStartedAt:X,taskCompletedAt:null,taskOwnerPid:process.pid}:J==="queued"?{taskStartedAt:null,taskCompletedAt:null,taskOwnerPid:null}:{taskCompletedAt:X,taskOwnerPid:null}});return Z0.publish({sessionId:$,projectPath:Z},"task.status",{taskStatus:W.taskStatus,...Q?{taskStatusReason:Q}:{},...H?{taskFailure:H}:{},...W.taskStartedAt?{taskStartedAt:W.taskStartedAt}:{},...W.taskCompletedAt?{taskCompletedAt:W.taskCompletedAt}:{},...W.taskDiffStat?{taskDiffStat:W.taskDiffStat}:{},...W.taskQueuePosition?{taskQueuePosition:W.taskQueuePosition}:{},...W.taskQueueDepth!==void 0?{taskQueueDepth:W.taskQueueDepth}:{},...W.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:W.taskConcurrencyLimit}:{},updatedAt:W.lastMessageTime}),W}createGoal($){return this.goalStore.create($)}editGoal($){return this.goalStore.edit($)}pauseGoal($){return this.goalStore.pause($)}resumeGoal(){return this.goalStore.resume()}clearGoal(){return this.goalStore.clear()}recordGoalProgress($){return this.goalStore.recordProgress($)}beginGoalContinuation(){return this.goalStore.tryBeginContinuation()}async pauseActiveGoal($){return this.goalStore.pauseIfActive($)}async listRewindCheckpoints(){return this.assertRewindIdle(),n.listRewindCheckpoints(this.sessionId,this.workspaceRoot)}async rewindSession($){return this.assertRewindIdle(),n.rewindSession(this.sessionId,this.workspaceRoot,$)}listSubagents(){return o.getInstance().listForSession({sessionId:this.sessionId,projectPath:this.workspaceRoot})}getMcpContentCatalog(){return this.sessionMcpRegistry?.getContentCatalogSnapshot()??{revision:0,resources:[],resourceTemplates:[],prompts:[]}}async refreshMcpContentCatalogs($){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");await this.sessionMcpRegistry.refreshContentCatalogs($)}async getMcpPrompt($,Z,J){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");return this.sessionMcpRegistry.getPrompt($,Z,J)}async completeMcpArgument($,Z,J){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");return this.sessionMcpRegistry.complete($,Z,J)}listMcpTasks($){return u0.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot},$)}getMcpTask($){return u0.getInstance().get($,{sessionId:this.sessionId,projectPath:this.workspaceRoot})}cancelMcpTask($,Z){return u0.getInstance().cancel($,{sessionId:this.sessionId,projectPath:this.workspaceRoot},Z)}getMcpLogs($,Z={}){return this.sessionMcpRegistry?.getLogSnapshot($,Z)??{revision:0,entries:[]}}getMcpInstructions(){return this.sessionMcpRegistry?.getInstructionsSnapshot()??{revision:0,instructions:[]}}async setMcpLoggingLevel($,Z){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");await this.sessionMcpRegistry.setServerLoggingLevel($,Z)}resumeSubagent($){this.assertSubagentControlIdle();let Z=o.getInstance(),J={sessionId:this.sessionId,projectPath:this.workspaceRoot},Y=Z.getAgent($.agentId,J);if(!Y)throw Error(`Subagent not found in this session: ${$.agentId}`);let U=this.subagentRegistry?.getSubagent(Y.subagentType),X=Y.configSnapshot?{...Y.configSnapshot}:U;if(!X)throw Error(`Subagent configuration is unavailable: ${Y.subagentType}`);let H=Z.resumeAgent({agentId:Y.id,prompt:$.prompt,config:X,owner:J,permissionMode:X.permissionMode,reasoningEffort:this.selectedReasoningEffort,serviceTier:this.selectedServiceTier,responseVerbosity:this.selectedResponseVerbosity,communicationStyle:this.selectedCommunicationStyle,agentResources:this.agentResources,modelResources:this.modelResources,lspResources:this.lspResources,onEvent:$.onEvent,onCompleted:$.onCompleted});if(!H)throw Error(`Subagent cannot be resumed: ${Y.id}`);let Q=Z.getAgent(H.agentId,J);if(!Q)throw Error(`Resumed subagent was not persisted: ${H.agentId}`);return{source:H.source,session:Q}}beginTurn(){return this.getActiveTurnMailbox().beginTurn()}async prepareInputTurn($){return this.getActiveTurnMailbox().prepareInputTurn($)}async enqueueSteering($,Z){return this.getActiveTurnMailbox().enqueue($,Z)}async drainSteering($){return this.getActiveTurnMailbox().drain($)}async drainSteeringOrSeal($){return this.getActiveTurnMailbox().drainOrSeal($)}async acknowledgeTurn($){let Z=this.getActiveTurnMailbox(),J=await Z.claimedMessageIds($);if(J.length===0)return;await this.getExecutionEngine().getContextManager().persistentStore.acknowledgeInboxMessages(this.sessionId,J),await Z.acknowledge(J)}async discardPendingInput(){let $=this.getActiveTurnMailbox(),Z=$.pendingMessages().map((J)=>J.id);if(Z.length===0)return;await this.getExecutionEngine().getContextManager().persistentStore.acknowledgeInboxMessages(this.sessionId,Z),await $.acknowledge(Z)}async finishTurn($,Z){return this.getActiveTurnMailbox().finishTurn($,Z)}async beginPendingTurn(){return this.getActiveTurnMailbox().beginPendingTurn()}hasActiveTurn(){return this.activeTurnMailbox?.isActive()??!1}hasTurnOwner(){return this.activeTurnMailbox?.hasTurnOwner()??!1}getPendingSteeringCount(){return this.activeTurnMailbox?.pendingCount()??0}getPendingSteeringMessages(){return this.activeTurnMailbox?.pendingMessages()??[]}getRecoveredSteeringCount(){return this.activeTurnMailbox?.recoveredCount()??0}async executeUserShellCommand($,Z={}){if(!this.initialized||!this.executionEngine)throw Error("Session runtime is not initialized");return this.userShellMutex.runExclusive(async()=>{let J=NH(12),Y=this.hasTurnOwner(),U=Z.signal??new AbortController().signal,X=async(K)=>{let G=K.type==="started"?{executionId:K.executionId,command:K.command,auxiliary:Y}:K.type==="output"?{executionId:K.executionId,stream:K.stream,chunk:K.chunk,streamedBytes:K.streamedBytes,streamTruncated:K.streamTruncated,auxiliary:Y}:{executionId:K.executionId,messageId:K.messageId,record:K.record,auxiliary:Y,delivery:K.delivery,queued:K.queued};Z0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},`user.shell.${K.type}`,G),await Z.onEvent?.(K)},H=await a9($,{executionId:J,cwd:this.workspaceRoot,env:{...process.env,...this.sessionEnvironment,BLADE_CLI:"1",BLADE_USER_SHELL:"1"},signal:U,timeoutMs:Z.timeoutMs,executor:this.options.userShellExecutor,onEvent:async(K)=>{if(K.type!=="completed")await X({...K,auxiliary:Y})}}),Q=o9(H),z=await this.getExecutionEngine().getContextManager().saveMessage(this.sessionId,"user",Q,null,{...Y?{inboxMessageId:J}:{},userShellCommand:JSON.parse(JSON.stringify(H))},this.options.subagentInfo),V=Y?await this.getActiveTurnMailbox().enqueue(Q,{allowBeforeTurn:!0,messageId:J,persisted:!0}):void 0,B={executionId:J,messageId:z,record:H,modelContent:Q,auxiliary:Y,...V?.delivery?{delivery:V.delivery}:{},...V?{queued:V.queued}:{}};return await X({type:"completed",executionId:J,messageId:z,record:H,auxiliary:Y,...V?.delivery?{delivery:V.delivery}:{},...V?{queued:V.queued}:{}}),B})}async initialize(){if(this.initialized)return;this.sessionLease=await r9.acquire(this.sessionId,this.workspaceRoot);try{if(!a(this.sessionId))await YZ(this.workspaceRoot);let $=G0.getInstance();if($.loadConfig(this.config.disableAllHooks?{...this.config.hooks,enabled:!1}:this.config.hooks??{},this.projectRoot),$.bindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot],this.modelResources),await this.loadAgentResources(),this.projectRoot!==this.workspaceRoot)$.inheritProjectConfig(this.projectRoot,this.workspaceRoot);$.bindSessionConfig(this.sessionId,[this.projectRoot,this.workspaceRoot],this.config.disableAllHooks?{...this.agentResources?.hooks??$.getConfig(this.projectRoot),enabled:!1}:this.agentResources?.hooks??$.getConfig(this.projectRoot));let Z=await $.executeSessionStartHooks({projectDir:this.workspaceRoot,sessionId:this.sessionId,permissionMode:this.config.permissionMode??"default",isResume:this.options.sessionStart?.isResume??!1,resumeSessionId:this.options.sessionStart?.resumeSessionId});if(!Z.proceed)throw Error(Z.warning||"SessionStart hook blocked initialization");if(Z.warning)N0.warn(`[SessionRuntime ${this.sessionId}] SessionStart hook warning: ${Z.warning}`);let J=m9(Z.env??{});if(this.sessionEnvironment=Object.freeze({...this.sessionEnvironment,...J}),this.config.env=this.sessionEnvironment,$.bindSessionEnvironment(this.sessionId,[this.projectRoot,this.workspaceRoot],this.sessionEnvironment),Object.keys(this.lspResources.servers).length>0)this.lspManager=new J5({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,environment:this.sessionEnvironment,servers:this.lspResources.servers});if(!this.lspManager?.available)this.autoVerifyRuntime=new y6({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,projectRoot:this.projectRoot,environment:this.sessionEnvironment});await this.validateSystemPromptConfig(),this.activeTurnMailbox=await P2.create(this.workspaceRoot,this.sessionId),await this.registerBuiltinTools(),await this.applyModelConfig(this.resolveModelConfig(this.selectedModelId),"使用模型:",this.selectedReasoningEffort,this.selectedServiceTier,this.selectedResponseVerbosity),await this.getExecutionEngine().getContextManager().persistentStore.initSession(this.sessionId,this.options.subagentInfo),this.initialized=!0,N0.debug(`[SessionRuntime ${this.sessionId}] initialized with ${this.baseRegistry.getAll().length} tools`)}catch($){try{await this.dispose()}catch(Z){N0.warn(`[SessionRuntime ${this.sessionId}] Failed to clean up after initialization error`,Z)}throw $}}async refresh($){if(!this.initialized){await this.initialize();return}let Z=$.modelId==="inherit",J=$.modelId&&!Z?$.modelId:void 0,Y=Z?this.getDefaultModel()?.id:J??this.selectedModelId??this.getDefaultModel()?.id,U=$.reasoningEffort??this.selectedReasoningEffort,X=$.serviceTier??this.selectedServiceTier,H=$.responseVerbosity??this.selectedResponseVerbosity,Q=$.communicationStyle??this.selectedCommunicationStyle;if(k2(Q,this.getCommunicationStyleCatalog()),Y&&(Y!==this.currentModelId||U!==this.selectedReasoningEffort||X!==this.selectedServiceTier||H!==this.selectedResponseVerbosity))await this.applyModelConfig(this.resolveModelConfig(Y),Y!==this.currentModelId?"切换模型":U!==this.selectedReasoningEffort?"切换推理强度":X!==this.selectedServiceTier?"切换服务等级":"切换输出详略",U,X,H);if(Z)this.selectedModelId=void 0;else if(J)this.selectedModelId=J;this.selectedReasoningEffort=U,this.selectedServiceTier=X,this.selectedResponseVerbosity=H,this.selectedCommunicationStyle=Q}createToolExecutor($={}){let Z=new A$;Z.setMcpCatalogBarrier(this.mcpCatalogBarrier);let J=$.toolWhitelist?new Set($.toolWhitelist):null,Y=$.toolBlacklist?new Set($.toolBlacklist):null;for(let W of this.baseRegistry.getBuiltinTools()){if(Y?.has(W.name))continue;if(!J||J.has(W.name))Z.register(W)}Z.replaceMcpTools(this.filterMcpTools(this.baseRegistry.getMcpTools(),J,Y));let U=this.getMcpInstructions();if(Z.queueMcpInstructionsChange({revision:U.revision,reason:"snapshot",replace:!0,instructions:U.instructions,removed:[]}),["TaskOutput","ListMcpTasks","CancelMcpTask"].some((W)=>!Y?.has(W)&&(!J||J.has(W))))for(let W of u0.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot})){let{result:z,...V}=W;Z.queueMcpTaskChange({revision:0,...V})}this.executorCatalogs.set(Z,{allowed:J,blocked:Y});let H={...this.config.permissions,...$.permissions},Q=$.permissionMode??this.config.permissionMode??"default";return new b1(Z,{permissionConfig:H,permissionMode:Q,approvalStore:this.approvalStore,maxHistorySize:1000,toolWhitelist:$.toolWhitelist,toolBlacklist:$.toolBlacklist,contextDefaults:{sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,environment:this.sessionEnvironment,permissionMode:Q,mcpSamplingHandler:this.handleMcpSampling},...this.lspManager?{lspManager:this.lspManager}:{},...Q==="yolo"&&this.autoVerifyRuntime?{autoVerifyRuntime:this.autoVerifyRuntime}:{},onDispose:()=>{this.executorCatalogs.delete(Z)}})}createExecutionPipeline($={}){return this.createToolExecutor($)}async dispose(){let $,Z=async(O,E)=>{try{await E()}catch(q){$??=q,N0.warn(`[SessionRuntime ${this.sessionId}] Failed to ${O} during cleanup`,q)}},J=this.chatService,Y=this.sessionMcpRegistry,U=this.mcpCatalogListener,X=this.mcpContentCatalogListener,H=this.mcpResourceUpdatedListener,Q=this.mcpConnectionListener,W=this.mcpLogListener,z=this.mcpInstructionsListener,V=this.mcpTaskListener,B=this.sessionLease,K=this.autoVerifyRuntime,G=this.lspManager;if(this.chatService=void 0,this.executionEngine=void 0,this.activeTurnMailbox=void 0,this.currentModelMaxContextTokens=void 0,this.baseRegistry=new A$,this.sessionMcpRegistry=void 0,this.mcpCatalogListener=void 0,this.mcpContentCatalogListener=void 0,this.mcpResourceUpdatedListener=void 0,this.mcpConnectionListener=void 0,this.mcpLogListener=void 0,this.mcpInstructionsListener=void 0,this.mcpTaskListener=void 0,this.mcpCatalogBarrier=async()=>{return},this.executorCatalogs.clear(),this.sessionLease=void 0,this.autoVerifyRuntime=void 0,this.lspManager=void 0,await Z("kill the session background processes",()=>s.getInstance().killSession(this.sessionId)),await Z("clear the session approvals",()=>this.approvalStore.clear()),await Z("clear the session file access records",()=>V0.getInstance().clearSession(this.sessionId,this.workspaceRoot)),await Z("stop the session auto-verification processes",()=>K?.dispose()),await Z("stop the session LSP servers",()=>G?.dispose()),await Z("release the session hook model resources",()=>G0.getInstance().unbindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot])),await Z("release the session worktrees",()=>t0.releaseSession(this.sessionId)),await Z("dispose the session chat service",()=>J?.dispose?.()),await Z("cancel the session MCP tasks",()=>u0.getInstance().cancelSession({sessionId:this.sessionId,projectPath:this.workspaceRoot})),await Z("disconnect the session MCP servers",async()=>{if(Y&&U)Y.off("catalogChanged",U);if(Y&&X)Y.off("contentCatalogChanged",X);if(Y&&H)Y.off("resourceUpdated",H);if(Y&&Q)Y.off("connectionLifecycleChanged",Q);if(Y&&W)Y.off("log",W);if(Y&&z)Y.off("instructionsChanged",z);if(V)u0.getInstance().off("taskChanged",V);await Y?.disconnectAll()}),await Z("release the session lease",()=>B?.release()),this.currentModelId=void 0,this.currentReasoning=void 0,this.currentServiceTier=void 0,this.initialized=!1,$!==void 0)throw $}resolveModelConfig($){let Z=$&&$!=="inherit"?$:void 0,J=Z?this.config.models.find((Y)=>Y.id===Z):this.getDefaultModel();if(!J)throw Error(`模型配置未找到: ${Z??"current"}`);return J}getDefaultModel(){return this.config.models.find(($)=>$.id===this.config.currentModelId)??this.config.models[0]}getActiveTurnMailbox(){if(!this.activeTurnMailbox)throw Error("Session runtime is not initialized");return this.activeTurnMailbox}assertRewindIdle(){if(this.hasTurnOwner())throw Error("Cannot rewind while the session has an active turn");if(this.getPendingSteeringCount()>0)throw Error("Cannot rewind while durable input is pending");if(s.getInstance().listForSession(this.sessionId).some(($)=>$.status==="running"))throw Error("Cannot rewind while a background shell is running");if(o.getInstance().listForSession({sessionId:this.sessionId,projectPath:this.workspaceRoot}).some(($)=>$.status==="running"))throw Error("Cannot rewind while a background agent is running")}assertSubagentControlIdle(){if(this.hasTurnOwner())throw Error("Cannot resume a subagent while the session has an active turn");if(this.getPendingSteeringCount()>0)throw Error("Cannot resume a subagent while durable input is pending")}async applyModelConfig($,Z,J,Y,U){let X=w0($,this.config,J,this.modelResources.catalog,Y,U);N0.debug(`${Z} ${X.displayName} (${$.model})`);let H=X.model.contextWindow,Q=await _2(X.chat),W=this.initialized?this.chatService:void 0,z=this.executionEngine?.getContextManager();this.chatService=Q,this.executionEngine=new j1(Q,z,this.workspaceRoot),this.currentModelMaxContextTokens=H,this.currentModelId=$.id,this.currentReasoning=X.reasoning,this.currentServiceTier=X.serviceTier,this.currentResponseVerbosity=X.responseVerbosity;let V=W;try{await V?.dispose?.()}catch(B){N0.warn(`[SessionRuntime ${this.sessionId}] Failed to dispose previous model service`,B)}}async validateSystemPromptConfig(){let $=this.getStaticProjectRules();if(this.options.projectInstructionsDigest&&$.provenanceSha256!==this.options.projectInstructionsDigest)throw Error("Project instruction provenance mismatch");if(!this.options.subagentInfo&&$.files.length>0&&!this.options.projectInstructionsDigest)await this.persistSystemPromptProvenance({projectInstructionsDigest:$.provenanceSha256}),this.options.projectInstructionsDigest=$.provenanceSha256;let Z=this.resolveCommunicationStyleConfiguration(this.selectedCommunicationStyle);if(Z.source!=="built-in"&&this.options.communicationStyleDigest&&Z.contentSha256!==this.options.communicationStyleDigest)throw Error(`Communication style provenance mismatch: ${this.selectedCommunicationStyle}`);if(Z.source!=="built-in"&&Z.contentSha256&&!this.options.communicationStyleDigest)await this.persistSystemPromptProvenance({communicationStyleDigest:Z.contentSha256}),this.options.communicationStyleDigest=Z.contentSha256;try{await k$({projectPath:this.workspaceRoot,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList()??"",communicationStyle:this.selectedCommunicationStyle,communicationStyleCatalog:this.getCommunicationStyleCatalog(),projectRuleCatalog:this.getProjectRuleCatalog(),projectInstructionSourcePath:this.projectRoot})}catch(J){N0.warn("[SessionRuntime] Failed to validate system prompt configuration:",J)}}async persistSystemPromptProvenance($){try{await n.updateSessionMetadata(this.sessionId,this.workspaceRoot,$)}catch(Z){if(!(Z instanceof s9||Z.code==="ENOENT")||this.options.subagentInfo)throw Z;await n.createSessionMetadata(this.sessionId,this.workspaceRoot,$)}}async registerBuiltinTools(){let Z=(await O2({sessionId:this.sessionId,configDir:Y0.join(e9.homedir(),".blade"),workspaceRoot:this.workspaceRoot,resourceRoot:this.projectRoot,agentResources:this.agentResources,modelResources:this.modelResources,lspManager:this.lspManager,lspResources:this.lspResources,getReasoningEffort:()=>this.selectedReasoningEffort,getServiceTier:()=>this.selectedServiceTier,getResponseVerbosity:()=>this.selectedResponseVerbosity,getCommunicationStyle:()=>this.selectedCommunicationStyle})).filter((J)=>!J.name.startsWith("mcp__"));this.baseRegistry.registerAll(Z),await this.registerMcpTools()}async registerMcpTools(){try{let $=this.options.mcpServers??{};if(Object.keys($).length===0)return;let Z=k0.createIsolated({roots:a(this.sessionId)?[]:[this.workspaceRoot],samplingAvailable:!0,oauthCredentialAccess:!a(this.sessionId),artifactWriter:new G1(`${this.projectRoot}\x00${this.sessionId}`,{exposePaths:!a(this.sessionId)}),exposeLogDetails:!a(this.sessionId),exposeInstructions:!a(this.sessionId)});this.sessionMcpRegistry=Z,this.mcpCatalogBarrier=()=>Z.waitForCatalogIdle(),this.baseRegistry.setMcpCatalogBarrier(this.mcpCatalogBarrier);let J=(z)=>{this.applyMcpCatalog(z,this.initialized)};this.mcpCatalogListener=J,Z.on("catalogChanged",J);let Y=(z)=>{this.applyMcpContentCatalog(z)},U=(z)=>{this.applyMcpResourceUpdated(z)},X=(z)=>{this.applyMcpConnectionChange(z)},H=(z)=>{this.applyMcpLog(z)},Q=(z)=>{this.applyMcpInstructions(z)},W=(z)=>{if(z.owner.sessionId!==this.sessionId||Y0.resolve(z.owner.projectPath)!==Y0.resolve(this.workspaceRoot))return;this.applyMcpTask(z);let{owner:V,result:B,...K}=z;Z0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"mcp.task.changed",K)};this.mcpContentCatalogListener=Y,this.mcpResourceUpdatedListener=U,this.mcpConnectionListener=X,this.mcpLogListener=H,this.mcpInstructionsListener=Q,this.mcpTaskListener=W,Z.on("contentCatalogChanged",Y),Z.on("resourceUpdated",U),Z.on("connectionLifecycleChanged",X),Z.on("log",H),Z.on("instructionsChanged",Q),u0.getInstance().on("taskChanged",W);for(let[z,V]of Object.entries($))try{let B=V.type==="stdio"?{...this.sessionEnvironment,...V.env}:void 0;await Z.registerServer(z,V.type==="stdio"?{...V,...B&&Object.keys(B).length>0?{env:B}:{}}:V)}catch(B){N0.warn(`Warning: MCP server "${z}" connection failed:`,B)}this.baseRegistry.replaceMcpTools(Z.getCatalogSnapshot().tools),this.baseRegistry.registerAll(A1(Z)),this.baseRegistry.registerAll(H6(Z))}catch($){N0.warn("Failed to register MCP tools:",$)}}filterMcpTools($,Z,J){return $.filter((Y)=>!J?.has(Y.name)&&(!Z||Z.has(Y.name)))}applyMcpCatalog($,Z){this.baseRegistry.replaceMcpTools($.tools);for(let[J,Y]of this.executorCatalogs){let U=this.filterMcpTools($.tools,Y.allowed,Y.blocked),X=(W)=>!Y.blocked?.has(W)&&(!Y.allowed||Y.allowed.has(W)),H={revision:$.revision,serverName:$.serverName,reason:$.reason,added:$.added.filter(X),removed:$.removed.filter(X),updated:$.updated.filter(X)},Q=H.added.length>0||H.removed.length>0||H.updated.length>0;J.replaceMcpTools(U,Z&&Q?H:void 0)}}applyMcpContentCatalog($){if(!this.initialized)return;let Z=$.kind==="resources"?["ListMcpResources","ReadMcpResource"]:$.kind==="resourceTemplates"?["ListMcpResourceTemplates","CompleteMcpArgument"]:["ListMcpPrompts","CompleteMcpArgument","GetMcpPrompt"];for(let[J,Y]of this.executorCatalogs)if(Z.some((X)=>!Y.blocked?.has(X)&&(!Y.allowed||Y.allowed.has(X))))J.queueMcpContentChange($)}applyMcpResourceUpdated($){if(!this.initialized)return;for(let[Z,J]of this.executorCatalogs)if(!J.blocked?.has("ReadMcpResource")&&(!J.allowed||J.allowed.has("ReadMcpResource")))Z.queueMcpResourceUpdated($)}applyMcpConnectionChange($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpConnectionChange($)}applyMcpLog($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpLog($)}applyMcpInstructions($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpInstructionsChange({revision:$.revision,reason:$.reason,replace:!1,instructions:$.action==="added"&&$.instruction?[{serverName:$.serverName,...$.instruction}]:[],removed:$.action==="removed"?[$.serverName]:[]})}applyMcpTask($){if(!this.initialized)return;let{owner:Z,result:J,...Y}=$;for(let[U,X]of this.executorCatalogs)if(["TaskOutput","ListMcpTasks","CancelMcpTask"].some((Q)=>!X.blocked?.has(Q)&&(!X.allowed||X.allowed.has(Q))))U.queueMcpTaskChange(Y)}handleMcpSampling=async($,Z)=>{let J=this.getChatService(),Y=await J.chat($.messages,void 0,Z,{maxOutputTokens:$.maxTokens,...$.temperature!==void 0?{temperature:$.temperature}:{}});return h9(Y,J.getConfig().model,$)};async loadAgentResources(){let $=this.options.agentResources?this.options.agentResources:await e(this.projectRoot,{reconcilePlugins:!0});if(this.agentResources=G2($),this.subagentRegistry=this.agentResources.subagents,this.options.agents?.length)this.subagentRegistry.applyOverrides(this.options.agents)}}async function h6(){let $=await t.getInstance().reload();H0().config.actions.setConfig($),await k0.getInstance().disconnectAll(),$7(),await e(N())}import yW from"fuse.js";import B$ from"node:path";import{Mutex as bH}from"async-mutex";var K$=new bH;async function J7($){await $.reapplyEnabledSettings(),n$($.getWorkspaceRoot()),await l$($.getWorkspaceRoot()),await u6(await e($.getWorkspaceRoot()))}async function TH($){n$($.getWorkspaceRoot());let Z=await $.refresh();return await l$($.getWorkspaceRoot()),await u6(await e($.getWorkspaceRoot())),Z}async function d6($){let Z=await e($),J=Array.from(new Set([Z.plugins,...I2.getInitializedInstances()])),Y;for(let U of J){let X=await TH(U);if(U===Z.plugins)Y=X}return Y??{plugins:[],errors:[]}}async function jH($,Z){let J=B$.resolve($),Y=u$();await Promise.all([Y.removePluginSetting(Z,{scope:"global",immediate:!0}),Y.removePluginSetting(Z,{scope:"project",projectDir:J,immediate:!0}),Y.removePluginSetting(Z,{scope:"local",projectDir:J,immediate:!0})])}function MH($){return B$.isAbsolute($)||$.startsWith("./")||$.startsWith("../")||$==="~"||$.startsWith("~/")}async function Y7($,Z){if(MH(Z)&&!(await j0.getInstance().getStatus($)).trusted)throw Error("Local plugin sources require a trusted workspace")}async function y2($,Z,J,Y="local"){return K$.runExclusive(async()=>{let U=B$.resolve($),X=await e(U),H=X.plugins.get(Z);if(!H)throw Error(`Plugin not found: ${Z}`);if(H.source==="cli")throw Error(`Plugin "${Z}" was loaded with --plugin-dir and is invocation-scoped`);await u$().save({enabledPlugins:{[Z]:J}},{scope:Y,projectDir:U,immediate:!0});let Q=Y==="global"?Array.from(new Set([X.plugins,...I2.getInitializedInstances()])):[X.plugins];for(let V of Q)await J7(V);let W=X.plugins.get(Z);if(!W)throw Error(`Plugin disappeared during reconciliation: ${Z}`);let z=await t.getInstance().loadWorkspacePluginSettingsResolution(U);return{name:Z,requestedEnabled:J,effectiveEnabled:W.status==="active",scope:Y,source:W.source,status:W.status,effectiveScope:z.settings[Z]?.effectiveScope??"default"}})}async function x2($){return K$.runExclusive(async()=>{let Z=await e($);n$(Z.workspaceRoot);let J=await Z.plugins.refresh();return await l$(Z.workspaceRoot),{registry:Z.plugins,discovery:J}})}async function m6($,Z,J="global"){return K$.runExclusive(async()=>{let Y=B$.resolve($),U={...Z,...Z7(Z)};await u$().save({pluginSourcePolicy:U},{scope:J,projectDir:Y,immediate:!0});let X=await e(Y),H=J==="global"?Array.from(new Set([X.plugins,...I2.getInitializedInstances()])):[X.plugins];for(let Q of H)await J7(Q);return t.getInstance().loadWorkspacePluginSourcePolicy(Y)})}async function g6($,Z,J={}){return K$.runExclusive(async()=>{let Y=B$.resolve($);await Y7(Y,Z);let U=await t.getInstance().loadWorkspacePluginSourcePolicy(Y),X=await m0().install(Z,{...J,workspaceRoot:Y,policy:U});if(!X.success)return{result:X};let H=await d6(Y);return{result:X,discovery:H}})}async function p6($,Z,J={}){return K$.runExclusive(async()=>{let Y=B$.resolve($),U=await t.getInstance().loadWorkspacePluginSourcePolicy(Y),X=await m0().update(Z,{...J,workspaceRoot:Y,policy:U});if(!X.success)return{result:X};let H=await d6(Y);return{result:X,discovery:H}})}async function c6($,Z,J=!1){return K$.runExclusive(async()=>{let Y=B$.resolve($),X=(await e(Y)).plugins.getAll().filter((W)=>W.manifest.name!==Z&&W.manifest.dependencies?.[Z]!==void 0).map((W)=>W.manifest.name).sort();if(X.length>0)return{result:{success:!1,pluginName:Z,code:"PLUGIN_REQUIRED",error:`Plugin "${Z}" is required by: ${X.join(", ")}`}};let H=await m0().uninstall(Z,J);if(!H.success)return{result:H};await jH(Y,Z);let Q=await d6(Y);return{result:H,discovery:Q}})}async function i6($,Z,J){return K$.runExclusive(async()=>{let Y=B$.resolve($);await Y7(Y,Z);let U=await t.getInstance().loadWorkspacePluginSourcePolicy(Y);return m0().addMarketplace(Z,{workspaceRoot:Y,ref:J,policy:U})})}async function l6($,Z){return K$.runExclusive(async()=>{let J=B$.resolve($),Y=await t.getInstance().loadWorkspacePluginSourcePolicy(J);return m0().refreshMarketplace(Z,Y)})}async function n6($,Z=!1){return K$.runExclusive(()=>m0().removeMarketplace($,Z))}import y7 from"node:fs/promises";import x7 from"node:path";async function h2($,Z,J={}){let Y=Date.now(),U=J.timeoutMs??20000,X="unknown";try{let H=w0($,Z,"off");X=H.model.api;let W=await new U7({...H.chat,temperature:0,maxOutputTokens:8,timeout:U,streamIdleTimeout:U,maxRetries:0,fallbackModels:[]}).chat([{role:"user",content:"Reply with OK."}],void 0,AbortSignal.timeout(U));if(!Boolean(W.content||W.reasoningContent||W.finishReason||W.usage))throw Error("Provider returned an empty response");return{ok:!0,providerId:$.provider,modelConfigId:$.id,model:$.model,wireApi:X,latencyMs:Date.now()-Y,code:"ok",message:"Provider responded successfully."}}catch(H){let Q=v2(H);return{ok:!1,providerId:$.provider,modelConfigId:$.id,model:$.model,wireApi:X,latencyMs:Date.now()-Y,code:Q.code,message:Q.message}}}import CH from"node:os";import X7 from"node:path";function v($){if($.acp)return{sendMessage:(Z)=>$.acp.sendMessage(`• ${Z}
|
|
903
903
|
|
|
904
|
-
`),sendToolStart:$.acp.sendToolStart,sendToolResult:$.acp.sendToolResult};return{sendMessage:(Z)=>R().addAssistantMessage(Z),sendToolStart:void 0,sendToolResult:void 0}}var H7={name:"agents",description:"Manage agent configurations",fullDescription:"Create, edit, or delete custom subagents. Subagents are specialized agents that Claude can delegate tasks to.",usage:"/agents [list|create|help]",category:"System",examples:["/agents","/agents list","/agents help"],async handler($,Z){let J=$[0],Y=v(Z),U=Z.workspaceRoot||Z.cwd||N();await
|
|
904
|
+
`),sendToolStart:$.acp.sendToolStart,sendToolResult:$.acp.sendToolResult};return{sendMessage:(Z)=>R().addAssistantMessage(Z),sendToolStart:void 0,sendToolResult:void 0}}var H7={name:"agents",description:"Manage agent configurations",fullDescription:"Create, edit, or delete custom subagents. Subagents are specialized agents that Claude can delegate tasks to.",usage:"/agents [list|create|help]",category:"System",examples:["/agents","/agents list","/agents help"],async handler($,Z){let J=$[0],Y=v(Z),U=Z.workspaceRoot||Z.cwd||N();await e(U);let X=j$(U);if(!J)return{success:!0,message:"show_agents_manager",data:{action:"show_agents_manager"}};if(J==="list"){let Q=X.getAllNames().map((G)=>X.getSubagent(G)).filter((G)=>G!==void 0);if(Q.length===0){let G=`**Agents 管理**
|
|
905
905
|
|
|
906
906
|
`+`没有找到任何 agent 配置
|
|
907
907
|
|
|
@@ -951,7 +951,7 @@ ${z}
|
|
|
951
951
|
• Token 数量: ${z.toLocaleString()}
|
|
952
952
|
• Token 限制: ${B.toLocaleString()}
|
|
953
953
|
• 使用率: ${K}%`),z<B*0.5)return J.sendMessage(`提示: 当前 token 使用率较低(${K}%),可以暂时不压缩。
|
|
954
|
-
系统会在达到 80% 时自动触发压缩。`),{success:!0,message:"无需压缩"};J.sendMessage("**正在压缩上下文...**");let G=await B7.compact(W,{trigger:"manual",modelName:U.model,modelProvider:U.provider,maxContextTokens:B,apiKey:V.chat.apiKey,baseURL:V.chat.baseUrl,workspaceRoot:Z.workspaceRoot??Z.cwd,sessionId:Q});if(G.success){try{if(Q)await new
|
|
954
|
+
系统会在达到 80% 时自动触发压缩。`),{success:!0,message:"无需压缩"};J.sendMessage("**正在压缩上下文...**");let G=await B7.compact(W,{trigger:"manual",modelName:U.model,modelProvider:U.provider,maxContextTokens:B,apiKey:V.chat.apiKey,baseURL:V.chat.baseUrl,workspaceRoot:Z.workspaceRoot??Z.cwd,sessionId:Q});if(G.success){try{if(Q)await new T1({projectPath:Z.workspaceRoot??Z.cwd}).saveCompaction(Q,G.summary,{trigger:"manual",preTokens:G.preTokens,postTokens:G.postTokens,filesIncluded:G.filesIncluded},null),console.log("[/compact] 压缩数据已保存到 JSONL")}catch(E){console.warn("[/compact] 保存压缩数据失败:",E)}let O=`[OK] **压缩完成!**
|
|
955
955
|
|
|
956
956
|
**Token 变化**
|
|
957
957
|
• 压缩前: ${G.preTokens.toLocaleString()} tokens
|
|
@@ -1063,7 +1063,7 @@ ${JSON.stringify(Q.content,null,2)}`).join(`
|
|
|
1063
1063
|
`)].join(`
|
|
1064
1064
|
`);return $.sendMessage(H),H}async function YQ($,Z,J){if(J.surface!=="tui")throw Error('MCP OAuth login requires an explicit local TUI action or "blade mcp login"');let Y=P$()[Z];if(!Y)throw Error(`服务器 "${Z}" 不存在`);let U=k0.getInstance(),X=!U.getServerStatus(Z);try{if(X)await U.registerServer(Z,Y,{connect:!1});let H=await U.beginOAuthLogin(Z,{openBrowser:!0});$.sendMessage(`已在浏览器中打开 ${Z} 的 OAuth 授权页面。
|
|
1065
1065
|
|
|
1066
|
-
备用链接: ${H.authorizationUrl}`),await H.completion,$.sendMessage(`[OK] ${Z} OAuth 登录成功`)}finally{if(X)await U.unregisterServer(Z)}}async function UQ($,Z,J){if(J.surface!=="tui")throw Error('MCP OAuth logout requires an explicit local TUI action or "blade mcp logout"');let Y=P$()[Z];if(!Y)throw Error(`服务器 "${Z}" 不存在`);let U=k0.getInstance(),X=!U.getServerStatus(Z);try{if(X)await U.registerServer(Z,Y,{connect:!1});await U.logoutOAuth(Z),$.sendMessage(`[OK] ${Z} OAuth 凭证已清除`)}finally{if(X)await U.unregisterServer(Z)}}var XQ={name:"mcp",description:"Display MCP server status and available tools",fullDescription:"显示 MCP 服务器状态、连接信息和可用工具列表",usage:"/mcp [server-name | tools | resources [server] | prompts [server] | prompt <server> <name> [key=value...] | logs [server] [limit] | complete <server> <prompt|resource> <reference> <argument> [value] [key=value...] | tasks [server] | task <task-id> | task-cancel <task-id> | log-level <server> <level> | instructions [server] | login <server> | logout <server>]",category:"MCP",examples:["/mcp - 显示所有服务器概览","/mcp chrome-devtools - 显示特定服务器详情","/mcp tools - 显示所有可用工具","/mcp resources [server] - 显示 Session MCP 资源与模板","/mcp prompts [server] - 显示 Session MCP prompts","/mcp prompt server name key=value - 解析并执行 MCP prompt","/mcp complete server prompt name argument partial key=value - 补全参数","/mcp tasks [server] - 列出当前 Session 拥有的 MCP tasks","/mcp task mcp_task_xxx - 查看安全 task 状态与结果","/mcp task-cancel mcp_task_xxx - 取消 MCP task","/mcp logs [server] [limit] - 显示当前 Session 的安全 MCP 日志",`/mcp log-level server <${r6.join("|")}> - 调整日志级别`,"/mcp instructions [server] - 显示当前 Session 的 MCP server instructions","/mcp login remote-server - 显式启动 OAuth 登录","/mcp logout remote-server - 清除 OAuth 凭证"],async handler($,Z){let J=v(Z);try{if(console.log("[MCP Command] Received args:",$),$.length===0)return await pH(J),{success:!0,message:"MCP 服务器概览已显示"};let Y=$[0];if(console.log("[MCP Command] Subcommand:",Y),Y==="tools")return await nH(J),{success:!0,message:"MCP 工具列表已显示"};if(Y==="resources"||Y==="prompts"){let U=await rH(J,Z,Y,$[1]);return{success:!0,message:`MCP ${Y} 已显示`,content:U}}if(Y==="prompt"){let U=$[1],X=$[2];if(!U||!X)return{success:!1,error:"用法: /mcp prompt <server> <name> [key=value...]"};return await aH(Z,U,X,$.slice(3))}if(Y==="complete"){let U=$[1],X=$[2],H=$[3],Q=$[4];if(!U||X!=="prompt"&&X!=="resource"||!H||!Q)return{success:!1,error:"用法: /mcp complete <server> <prompt|resource> "+"<reference> <argument> [value] [key=value...]"};let W=await oH(J,Z,U,X,H,Q,$[5]??"",$.slice(6));return{success:!0,message:`MCP completion returned for "${Q}"`,content:W}}if(Y==="tasks")return{success:!0,message:"MCP tasks displayed",content:await sH(J,Z,$[1])};if(Y==="task"||Y==="task-cancel"){let U=$[1];if(!U)return{success:!1,error:`用法: /mcp ${Y} <mcp-task-id>`};let X=Y==="task"?await tH(J,Z,U):await eH(J,Z,U);return{success:!0,message:Y==="task"?`MCP task "${U}" displayed`:`MCP task "${U}" cancelled`,content:X}}if(Y==="logs")return{success:!0,message:"MCP logs displayed",content:await $Q(J,Z,$[1],$[2])};if(Y==="log-level"){let U=$[1],X=$[2];if(!U||!A7(X))return{success:!1,error:"用法: /mcp log-level <server> "+`<${r6.join("|")}>`};return await ZQ(J,Z,U,X),{success:!0,message:`MCP logging level set to ${X} for "${U}"`}}if(Y==="instructions")return{success:!0,message:"MCP server instructions displayed",content:await JQ(J,Z,$[1])};if(Y==="login"||Y==="logout"){let U=$[1];if(!U)return{success:!1,error:`用法: /mcp ${Y} <server-name>`};if(Y==="login")await YQ(J,U,Z);else await UQ(J,U,Z);return{success:!0,message:`MCP OAuth ${Y} completed for "${U}"`}}return await iH(J,Y),{success:!0,message:`服务器 "${Y}" 详情已显示`}}catch(Y){return{success:!1,error:`显示 MCP 信息失败: ${Y instanceof Error?Y.message:"未知错误"}`}}}},
|
|
1066
|
+
备用链接: ${H.authorizationUrl}`),await H.completion,$.sendMessage(`[OK] ${Z} OAuth 登录成功`)}finally{if(X)await U.unregisterServer(Z)}}async function UQ($,Z,J){if(J.surface!=="tui")throw Error('MCP OAuth logout requires an explicit local TUI action or "blade mcp logout"');let Y=P$()[Z];if(!Y)throw Error(`服务器 "${Z}" 不存在`);let U=k0.getInstance(),X=!U.getServerStatus(Z);try{if(X)await U.registerServer(Z,Y,{connect:!1});await U.logoutOAuth(Z),$.sendMessage(`[OK] ${Z} OAuth 凭证已清除`)}finally{if(X)await U.unregisterServer(Z)}}var XQ={name:"mcp",description:"Display MCP server status and available tools",fullDescription:"显示 MCP 服务器状态、连接信息和可用工具列表",usage:"/mcp [server-name | tools | resources [server] | prompts [server] | prompt <server> <name> [key=value...] | logs [server] [limit] | complete <server> <prompt|resource> <reference> <argument> [value] [key=value...] | tasks [server] | task <task-id> | task-cancel <task-id> | log-level <server> <level> | instructions [server] | login <server> | logout <server>]",category:"MCP",examples:["/mcp - 显示所有服务器概览","/mcp chrome-devtools - 显示特定服务器详情","/mcp tools - 显示所有可用工具","/mcp resources [server] - 显示 Session MCP 资源与模板","/mcp prompts [server] - 显示 Session MCP prompts","/mcp prompt server name key=value - 解析并执行 MCP prompt","/mcp complete server prompt name argument partial key=value - 补全参数","/mcp tasks [server] - 列出当前 Session 拥有的 MCP tasks","/mcp task mcp_task_xxx - 查看安全 task 状态与结果","/mcp task-cancel mcp_task_xxx - 取消 MCP task","/mcp logs [server] [limit] - 显示当前 Session 的安全 MCP 日志",`/mcp log-level server <${r6.join("|")}> - 调整日志级别`,"/mcp instructions [server] - 显示当前 Session 的 MCP server instructions","/mcp login remote-server - 显式启动 OAuth 登录","/mcp logout remote-server - 清除 OAuth 凭证"],async handler($,Z){let J=v(Z);try{if(console.log("[MCP Command] Received args:",$),$.length===0)return await pH(J),{success:!0,message:"MCP 服务器概览已显示"};let Y=$[0];if(console.log("[MCP Command] Subcommand:",Y),Y==="tools")return await nH(J),{success:!0,message:"MCP 工具列表已显示"};if(Y==="resources"||Y==="prompts"){let U=await rH(J,Z,Y,$[1]);return{success:!0,message:`MCP ${Y} 已显示`,content:U}}if(Y==="prompt"){let U=$[1],X=$[2];if(!U||!X)return{success:!1,error:"用法: /mcp prompt <server> <name> [key=value...]"};return await aH(Z,U,X,$.slice(3))}if(Y==="complete"){let U=$[1],X=$[2],H=$[3],Q=$[4];if(!U||X!=="prompt"&&X!=="resource"||!H||!Q)return{success:!1,error:"用法: /mcp complete <server> <prompt|resource> "+"<reference> <argument> [value] [key=value...]"};let W=await oH(J,Z,U,X,H,Q,$[5]??"",$.slice(6));return{success:!0,message:`MCP completion returned for "${Q}"`,content:W}}if(Y==="tasks")return{success:!0,message:"MCP tasks displayed",content:await sH(J,Z,$[1])};if(Y==="task"||Y==="task-cancel"){let U=$[1];if(!U)return{success:!1,error:`用法: /mcp ${Y} <mcp-task-id>`};let X=Y==="task"?await tH(J,Z,U):await eH(J,Z,U);return{success:!0,message:Y==="task"?`MCP task "${U}" displayed`:`MCP task "${U}" cancelled`,content:X}}if(Y==="logs")return{success:!0,message:"MCP logs displayed",content:await $Q(J,Z,$[1],$[2])};if(Y==="log-level"){let U=$[1],X=$[2];if(!U||!A7(X))return{success:!1,error:"用法: /mcp log-level <server> "+`<${r6.join("|")}>`};return await ZQ(J,Z,U,X),{success:!0,message:`MCP logging level set to ${X} for "${U}"`}}if(Y==="instructions")return{success:!0,message:"MCP server instructions displayed",content:await JQ(J,Z,$[1])};if(Y==="login"||Y==="logout"){let U=$[1];if(!U)return{success:!1,error:`用法: /mcp ${Y} <server-name>`};if(Y==="login")await YQ(J,U,Z);else await UQ(J,U,Z);return{success:!0,message:`MCP OAuth ${Y} completed for "${U}"`}}return await iH(J,Y),{success:!0,message:`服务器 "${Y}" 详情已显示`}}catch(Y){return{success:!1,error:`显示 MCP 信息失败: ${Y instanceof Error?Y.message:"未知错误"}`}}}},T7=XQ;import{spawn as HQ}from"node:child_process";import*as j7 from"node:path";function QQ($){return new Promise((Z)=>{let J=process.env.EDITOR||process.env.VISUAL||"vi",Y=HQ(J,[$],{stdio:"inherit"});Y.on("close",(U)=>{Z(U===0)}),Y.on("error",()=>{Z(!1)})})}var WQ={name:"memory",description:"Manage project auto memory",fullDescription:"查看和管理项目的 Auto Memory(跨会话持久记忆)",usage:"/memory [list|show|edit|clear]",aliases:["mem"],async handler($,Z){let J=v(Z),Y=N(),U=new q$(Y);switch($[0]||"list"){case"list":{let H=await U.listTopics();if(H.length===0)J.sendMessage(`暂无记忆文件。Agent 在工作过程中会自动记录有价值的项目知识。
|
|
1067
1067
|
|
|
1068
1068
|
`+`记忆目录: ${U.getMemoryDir()}`);else{let Q=H.map((W)=>{let z=(W.size/1024).toFixed(1),V=W.lastModified.toLocaleDateString("zh-CN");return`${W.name==="MEMORY"?"[INDEX]":"[FILE]"} **${W.name}.md** — ${z}KB, ${V}`}).join(`
|
|
1069
1069
|
`);J.sendMessage(`**项目记忆文件:**
|
|
@@ -1072,7 +1072,7 @@ ${Q}
|
|
|
1072
1072
|
|
|
1073
1073
|
`+"使用 `/memory edit [topic]` 编辑,`/memory show [topic]` 查看\n"+`${U.getMemoryDir()}`)}return{success:!0,message:"记忆列表已显示"}}case"show":{let H=$[1]||"MEMORY",Q=await U.readTopic(H);if(Q===null)J.sendMessage(`记忆文件 "${H}.md" 不存在`);else J.sendMessage(`**${H}.md:**
|
|
1074
1074
|
|
|
1075
|
-
${Q}`);return{success:!0,message:"记忆内容已显示"}}case"edit":{let H=$[1]||"MEMORY",Q=
|
|
1075
|
+
${Q}`);return{success:!0,message:"记忆内容已显示"}}case"edit":{let H=$[1]||"MEMORY",Q=j7.join(U.getMemoryDir(),`${H}.md`);if(await U.initialize(),await U.readTopic(H)===null)await U.writeTopic(H,"","overwrite");let z=process.env.EDITOR||process.env.VISUAL||"vi";if(J.sendMessage(`正在用 ${z} 打开 ${H}.md ...`),await QQ(Q))J.sendMessage(`[OK] ${H}.md 编辑完成`);else J.sendMessage(`[WARN] 编辑器退出异常。你可以手动编辑:
|
|
1076
1076
|
${Q}
|
|
1077
1077
|
|
|
1078
1078
|
`+"设置 EDITOR 环境变量来指定编辑器(如 export EDITOR=code)");return{success:!0,message:"编辑完成"}}case"clear":{let H=await U.clearAll();return J.sendMessage(`已清除 ${H} 个记忆文件`),{success:!0,message:`已清除 ${H} 个记忆文件`}}default:return J.sendMessage(`**Auto Memory 命令:**
|
|
@@ -1123,7 +1123,7 @@ Supported: ${J}`}function LQ($){let Z=$.toLowerCase();return v7(Z)?Z:void 0}var
|
|
|
1123
1123
|
- 在命令前加上 \`/\` 即可执行 slash command
|
|
1124
1124
|
- 普通消息会发送给 AI 助手处理
|
|
1125
1125
|
- 按 Ctrl+C 退出程序
|
|
1126
|
-
- 按 Ctrl+L 快速清屏`,J.sendMessage(Y),{success:!0,message:"帮助信息已显示",content:Y}}},
|
|
1126
|
+
- 按 Ctrl+L 快速清屏`,J.sendMessage(Y),{success:!0,message:"帮助信息已显示",content:Y}}},TQ={name:"clear",description:"Clear conversation history and free up context",fullDescription:"清除屏幕内容和对话历史",usage:"/clear",aliases:["cls"],async handler($,Z){return{success:!0,message:"clear_screen"}}},jQ={name:"version",description:"Show Blade Code version information",fullDescription:"显示 Blade Code 版本信息和构建详情",usage:"/version",aliases:["v"],async handler($,Z){let J=v(Z),U=`**Blade Code v${B2()}**
|
|
1127
1127
|
|
|
1128
1128
|
**构建信息:**
|
|
1129
1129
|
- Node.js: ${process.version}
|
|
@@ -1187,7 +1187,7 @@ ${!X?"\n**建议:** 运行 `/init` 命令来创建项目配置文件":""}`;retur
|
|
|
1187
1187
|
- **Estimated cost: ${H}**`;return J.sendMessage(W),{success:!0,message:"Cost summary displayed"}}},SQ={name:"doctor",description:"Diagnose API connectivity and configuration health",fullDescription:"诊断 API 连通性和配置健康状况",usage:"/doctor",aliases:[],async handler($,Z){let J=v(Z),Y=W0(),U=Y?.models??[];if(U.length===0)return J.sendMessage("❌ 没有配置任何模型。请先运行 `/init` 或编辑 `~/.blade/config.json`"),{success:!1,message:"No models configured"};let X=[`**API Connectivity Diagnosis**
|
|
1188
1188
|
`],H=!0;for(let Q of U){let W=await h2(Q,Y,{timeoutMs:1e4});if(H&&=W.ok,W.ok)X.push(`✅ **${f$(Q)}** (${Q.provider}/${Q.model}) — ${W.latencyMs}ms · ${W.wireApi}`);else X.push(`❌ **${f$(Q)}** (${Q.provider}/${Q.model}) — ${W.latencyMs}ms — ${W.message} [${W.code}]`)}return J.sendMessage(X.join(`
|
|
1189
1189
|
`)),{success:H,message:H?"Doctor diagnosis complete":"Doctor found unhealthy model providers",content:X.join(`
|
|
1190
|
-
`)}}},h7={help:bQ,archive:W7,unarchive:z7,export:F7,effort:G7,speed:S7,verbosity:I7,style:k7,branch:V7,clear:
|
|
1190
|
+
`)}}},h7={help:bQ,archive:W7,unarchive:z7,export:F7,effort:G7,speed:S7,verbosity:I7,style:k7,branch:V7,clear:TQ,version:jQ,status:MQ,exit:CQ,context:fQ,cost:RQ,doctor:SQ,permissions:d2,resume:C7,fork:D7,rewind:f7,compact:K7,mcp:T7,memory:M7,agents:H7};import{execFile as u7,spawn as PQ}from"child_process";import{promisify as kQ}from"util";var mN=kQ(u7);async function P1($,Z){return new Promise((J)=>{u7("git",Z,{cwd:$,maxBuffer:10485760,encoding:"utf8"},(Y,U,X)=>{let H=Y==null?0:typeof Y.code==="number"?Y.code:1;J({code:H,stdout:U||"",stderr:X||""})})})}async function vQ($,Z){let{code:J}=await P1($,Z);return J===0}async function e0($,Z){let{stdout:J}=await P1($,Z);return J.trim()}async function o6($){return vQ($,["rev-parse","--is-inside-work-tree"])}async function m2($){return(await e0($,["status","--porcelain"])).length>0}async function gN($){return e0($,["branch","--show-current"])}async function g2($,Z=10){return e0($,["log","-n",String(Z),"--pretty=format:%s"])}async function s6($){let{code:Z,stderr:J}=await P1($,["add","."]);if(Z!==0){let Y=J||"Unknown error";if(Y.includes("fatal: pathspec"))throw Error("Failed to stage files: Invalid file path or pattern");throw Error(`Failed to stage files: ${Y}`)}}async function d7($,Z,J=!1,Y){let U=["commit","-m",Z];if(J)U.push("--no-verify");if(!Y){let{code:X,stderr:H}=await P1($,U);if(X!==0)throw Error(H||"Commit failed");return}return new Promise((X,H)=>{let Q=PQ("git",U,{cwd:$}),W="",z=(K,G,O)=>{let q=(O+K.toString()).split(`
|
|
1191
1191
|
`),F=q.pop()||"";for(let D of q)if(D.trim())Y(D,G);return F},V="",B="";Q.stdout?.on("data",(K)=>{V=z(K,"stdout",V)}),Q.stderr?.on("data",(K)=>{W+=K.toString(),B=z(K,"stderr",B)}),Q.on("error",(K)=>{H(K)}),Q.on("close",(K)=>{if(V.trim())Y(V,"stdout");if(B.trim())Y(B,"stderr");if(K===0)X();else H(Error(W||"Commit failed"))})})}async function m7($){let{cwd:Z}=$;if(!await o6(Z))return null;let[J,Y,U,X,H]=await Promise.all([e0(Z,["branch","--show-current"]),e0(Z,["rev-parse","--abbrev-ref","origin/HEAD"]).then((W)=>W.replace("origin/","")).catch(()=>"main"),e0(Z,["status","--short"]),e0(Z,["log","--oneline","-n","5"]),e0(Z,["config","user.email"])]),Q=H?await e0(Z,["log","--author",H,"--oneline","-n","5"]):"";return{branch:J,mainBranch:Y,status:U,log:X,author:H,authorLog:Q}}function g7($){if(!$)return null;return`
|
|
1192
1192
|
Git repository status (snapshot at conversation start):
|
|
1193
1193
|
Current branch: ${$.branch}
|
|
@@ -1265,7 +1265,7 @@ ${J}
|
|
|
1265
1265
|
1. ${Y?"严格模仿历史提交的语言和格式风格":"使用英文,遵循 Conventional Commits 格式(feat:, fix:, docs:, refactor:, chore: 等)"}
|
|
1266
1266
|
2. 第一行简明扼要,不超过 72 字符
|
|
1267
1267
|
3. 如有必要,可添加空行后的详细说明
|
|
1268
|
-
4. 只输出 commit message 内容,不要其他解释或代码块标记`}var i7=IQ;function mQ($){if(!$.sessionId)throw Error("/goal requires a session");return new
|
|
1268
|
+
4. 只输出 commit message 内容,不要其他解释或代码块标记`}var i7=IQ;function mQ($){if(!$.sessionId)throw Error("/goal requires a session");return new T0($.workspaceRoot??$.cwd,$.sessionId)}function gQ($){let Z=[...$],J,Y=Z.lastIndexOf("--budget");if(Y>=0){let X=Z[Y+1];if(!X||!/^[1-9]\d*$/.test(X))throw Error("--budget requires a positive integer");J=Number(X),Z.splice(Y,2)}let U=Z.join(" ").trim();if(!U)throw Error("Usage: /goal <objective> [--budget <tokens>]");return{objective:U,tokenBudget:J}}function I1($,Z){return{success:!0,message:o$($),content:o$($),data:{...Z?{action:Z}:{},goal:$}}}async function pQ($,Z){try{let J=mQ(Z),Y=$[0]?.toLowerCase();if(!Y||Y==="status"){let U=await J.get();return U?I1(U):{success:!0,message:"No goal is configured for this session.",content:"No goal is configured for this session."}}if(Y==="clear"){let U=await J.clear();return{success:!0,message:U?"Goal cleared.":"No goal was configured.",content:U?"Goal cleared.":"No goal was configured.",data:{action:"goal_cleared",goal:null}}}if(Y==="pause")return I1(await J.pause());if(Y==="resume")return I1(await J.resume(),"resume_goal");if(Y==="edit"){let U=$.slice(1).join(" ").trim();if(!U)throw Error("Usage: /goal edit <objective>");return I1(await J.edit(U))}return I1(await J.create(gQ($)),"start_goal")}catch(J){return{success:!1,error:J instanceof Error?J.message:String(J)}}}var cQ={name:"goal",description:"创建并持续执行 session 级目标",fullDescription:"创建、查看、暂停、恢复、编辑或清除持久化目标。Active goal 会在逻辑 turn 结束后自动续跑。",usage:"/goal [<objective> [--budget <tokens>]|status|pause|resume|edit|clear]",category:"agent",examples:["/goal migrate the project and run all tests","/goal status","/goal pause","/goal resume","/goal edit finish the migration and update docs","/goal clear"],handler:pQ},l7=cQ;var iQ={name:"hooks",description:"Manage hook configurations for tool events",fullDescription:`管理 Hook 配置,查看当前启用的 hooks 和执行统计。
|
|
1269
1269
|
|
|
1270
1270
|
子命令:
|
|
1271
1271
|
/hooks - 打开交互式 hooks 管理界面(添加新 hook)
|
|
@@ -1275,10 +1275,10 @@ ${J}
|
|
|
1275
1275
|
/hooks disable - 禁用当前会话的 hooks
|
|
1276
1276
|
/hooks trust - 信任当前项目的当前 Hook 配置摘要
|
|
1277
1277
|
/hooks revoke - 撤销当前项目 Hook 信任
|
|
1278
|
-
/hooks list - 列出所有配置的 hooks`,usage:"/hooks [add|status|enable|disable|trust|revoke|list]",category:"system",examples:["/hooks","/hooks add","/hooks status","/hooks enable","/hooks disable","/hooks trust","/hooks revoke","/hooks list"],handler:async($,Z)=>{let J=$[0]?.toLowerCase()||"",Y=G0.getInstance(),U=v(Z);switch(J){case"":case"add":return{success:!0,message:"show_hooks_manager",data:{action:"show_hooks_manager"}};case"status":return lQ(Y,Z.
|
|
1278
|
+
/hooks list - 列出所有配置的 hooks`,usage:"/hooks [add|status|enable|disable|trust|revoke|list]",category:"system",examples:["/hooks","/hooks add","/hooks status","/hooks enable","/hooks disable","/hooks trust","/hooks revoke","/hooks list"],handler:async($,Z)=>{let J=$[0]?.toLowerCase()||"",Y=G0.getInstance(),U=v(Z),X=Z.workspaceRoot??Z.cwd;switch(J){case"":case"add":return{success:!0,message:"show_hooks_manager",data:{action:"show_hooks_manager"}};case"status":return lQ(Y,X,Z.sessionId,U);case"enable":{if(!Z.sessionId)return U.sendMessage("当前表面没有可用的 Session,无法切换 Hooks"),{success:!1,error:"当前表面没有可用的 Session,无法切换 Hooks"};return Y.enableSession(Z.sessionId,X),U.sendMessage("[OK] Hooks 已启用(当前会话)"),{success:!0,message:"Hooks enabled"}}case"disable":{if(!Z.sessionId)return U.sendMessage("当前表面没有可用的 Session,无法切换 Hooks"),{success:!1,error:"当前表面没有可用的 Session,无法切换 Hooks"};return Y.disableSession(Z.sessionId,X),U.sendMessage("Hooks 已禁用(当前会话)"),{success:!0,message:"Hooks disabled"}}case"trust":{let H=await Y.trustProject(X);return U.sendMessage(`[OK] 已信任当前 Hook 配置
|
|
1279
1279
|
|
|
1280
|
-
摘要:\`${
|
|
1281
|
-
使用 /hooks 查看帮助`),{success:!1,error:`Unknown subcommand: ${J}`}}}};async function lQ($,Z,J){let
|
|
1280
|
+
摘要:\`${H.currentDigest}\``),{success:!0,message:"Hook configuration trusted"}}case"revoke":return await Y.revokeProjectTrust(X),U.sendMessage("已撤销当前项目的 Hook 信任;配置型 Hooks 不再执行。"),{success:!0,message:"Hook trust revoked"};case"list":return nQ(Y,X,U);default:return U.sendMessage(`未知子命令: ${J}
|
|
1281
|
+
使用 /hooks 查看帮助`),{success:!1,error:`Unknown subcommand: ${J}`}}}};async function lQ($,Z,J,Y){let U=$.isEnabled(Z,J),X=$.getConfig(Z),H=await $.getTrustStatus(Z),Q={};for(let z of Object.values(t6)){let V=X[z];if(V&&Array.isArray(V)){let B=V.reduce((K,G)=>K+(G.hooks?.length||0),0);if(B>0)Q[z]=B}}let W=["## Hooks 状态","",`**状态**: ${U?"[OK] 启用":"禁用"}`,`**信任**: ${H.state}`,`**配置摘要**: ${H.currentDigest?`\`${H.currentDigest}\``:"无"}`,""];if(Object.keys(Q).length>0){W.push("**已配置的 Hooks**:"),W.push("");for(let[z,V]of Object.entries(Q))W.push(`- ${z}: ${V} 个 hook`)}else W.push("*没有配置任何 hooks*");return W.push(""),W.push("---"),W.push("使用 `/hooks list` 查看详细配置"),W.push("使用 `/hooks enable` 或 `/hooks disable` 切换状态"),Y.sendMessage(W.join(`
|
|
1282
1282
|
`)),{success:!0,message:"Hooks status displayed"}}async function nQ($,Z,J){let Y=$.getConfig(Z),X=["## Hooks 配置详情","",`信任状态:**${(await $.getTrustStatus(Z)).state}**`,""],H=!1;for(let Q of Object.values(t6)){let W=Y[Q];if(!W||!Array.isArray(W)||W.length===0)continue;H=!0,X.push(`### ${Q}`),X.push("");for(let z=0;z<W.length;z++){let V=W[z],B=V.name||`Matcher ${z+1}`,K=V.matcher,G="所有";if(K){let O=[];if(K.tools){let E=Array.isArray(K.tools)?K.tools.join(", "):K.tools;O.push(`工具: ${E}`)}if(K.paths){let E=Array.isArray(K.paths)?K.paths.join(", "):K.paths;O.push(`路径: ${E}`)}if(K.commands){let E=Array.isArray(K.commands)?K.commands.join(", "):K.commands;O.push(`命令: ${E}`)}if(O.length>0)G=O.join("; ")}X.push(`**${B}** (匹配: ${G})`);for(let O of V.hooks||[])if(O.type==="command")X.push(` - \`${O.command}\``);else if(O.type==="prompt"){let E=O.prompt.slice(0,50)+(O.prompt.length>50?"...":"");X.push(` - [prompt] ${E}`)}X.push("")}}if(!H)X.push("*没有配置任何 hooks*"),X.push(""),X.push("在 `.blade/settings.local.json` 或 `~/.blade/settings.json` 中配置 hooks。");return J.sendMessage(X.join(`
|
|
1283
1283
|
`)),{success:!0,message:"Hooks config listed"}}var n7=iQ;import{existsSync as tQ,readFileSync as eQ}from"fs";import{homedir as $W}from"os";import{join as ZW}from"path";import{exec as rQ}from"child_process";import{promisify as aQ}from"util";var r7=aQ(rQ);class e6{static async detectIde(){let $=process.env.TERM_PROGRAM,Z=process.env.VSCODE_INJECTION,J=process.env.VSCODE_IPC_HOOK;if($==="vscode"||Z||J)return await this.detectVsCode();let Y=await this.detectVsCode();if(Y)return Y;return null}static async detectVsCode(){try{let{stdout:$}=await r7("code --version"),J=$.trim().split(`
|
|
1284
1284
|
`)[0]||"unknown",Y=[];try{let{stdout:U}=await r7("code --list-extensions");Y=U.trim().split(`
|
|
@@ -1434,7 +1434,7 @@ ${J}
|
|
|
1434
1434
|
/plugins enable <name> [--scope local|project|global] - 启用插件
|
|
1435
1435
|
/plugins disable <name> [--scope local|project|global] - 禁用插件
|
|
1436
1436
|
/plugins refresh - 刷新插件列表
|
|
1437
|
-
/plugins stats - 显示插件统计信息`,usage:"/plugins [list|info|install|uninstall|update|enable|disable|refresh|stats] [name/url]",category:"system",examples:["/plugins","/plugins list","/plugins info my-plugin","/plugins install user/repo --trust","/plugins install my-plugin@team-market --trust","/plugins uninstall my-plugin --confirm","/plugins update my-plugin --trust","/plugins marketplace add user/plugin-marketplace","/plugins marketplace list","/plugins policy show","/plugins policy set --require-sha true --hosts github.com --scope global","/plugins enable my-plugin","/plugins disable my-plugin","/plugins refresh","/plugins stats"],handler:async($,Z)=>{let J=$[0]?.toLowerCase()||"",Y=Z.workspaceRoot||Z.cwd;await
|
|
1437
|
+
/plugins stats - 显示插件统计信息`,usage:"/plugins [list|info|install|uninstall|update|enable|disable|refresh|stats] [name/url]",category:"system",examples:["/plugins","/plugins list","/plugins info my-plugin","/plugins install user/repo --trust","/plugins install my-plugin@team-market --trust","/plugins uninstall my-plugin --confirm","/plugins update my-plugin --trust","/plugins marketplace add user/plugin-marketplace","/plugins marketplace list","/plugins policy show","/plugins policy set --require-sha true --hosts github.com --scope global","/plugins enable my-plugin","/plugins disable my-plugin","/plugins refresh","/plugins stats"],handler:async($,Z)=>{let J=$[0]?.toLowerCase()||"",Y=Z.workspaceRoot||Z.cwd;await e(Y);let U=U$(Y);switch(J){case"":return await OW(U),{success:!0,message:"show_plugins_manager",data:{action:"show_plugins_manager"}};case"list":case"ls":return BW(U);case"info":return KW(U,$[1]);case"install":case"add":return DW(U,$.slice(1));case"uninstall":case"remove":case"rm":return wW(U,$.slice(1));case"update":case"upgrade":return AW(U,$.slice(1));case"marketplace":case"marketplaces":return NW(U,$.slice(1));case"policy":return LW(U,$.slice(1));case"enable":return await _W(U,$[1],Y4($.slice(2)));case"disable":return await GW(U,$[1],Y4($.slice(2)));case"refresh":return EW(U);case"stats":return qW(U);default:return R().addAssistantMessage(`未知子命令: ${J}
|
|
1438
1438
|
使用 /plugins 查看帮助`),{success:!1,error:`Unknown subcommand: ${J}`}}}};function Y4($){let Z=$.findIndex((Y)=>Y==="--scope"||Y.startsWith("--scope=")),J=Z>=0?$[Z]?.includes("=")?$[Z]?.split("=",2)[1]:$[Z+1]:$[0];if(!J)return"local";if(J==="user")return"global";if(J==="local"||J==="project"||J==="global")return J;throw Error(`Invalid plugin scope: ${J}`)}function BW($){if($.getAll().length===0)return R().addAssistantMessage(`没有已加载的插件。
|
|
1439
1439
|
|
|
1440
1440
|
`+"使用 `--plugin-dir <path>` 参数加载插件,或将插件放置在:\n"+"- `~/.blade/plugins/` - 用户级插件\n"+"- `.blade/plugins/` - 项目级插件"),{success:!0,message:"No plugins loaded"};let J=["## 已加载的插件",""],Y=$.getBySource();if(Y.cli.length>0){J.push("### CLI 指定");for(let U of Y.cli){let X=U.status==="inactive"?" [PAUSED]":" [OK]";J.push(`- **${U.manifest.name}** v${U.manifest.version}${X}`),J.push(` ${U.manifest.description}`)}J.push("")}if(Y.project.length>0){J.push("### 项目级");for(let U of Y.project){let X=U.status==="inactive"?" [PAUSED]":" [OK]";J.push(`- **${U.manifest.name}** v${U.manifest.version}${X}`),J.push(` ${U.manifest.description}`)}J.push("")}if(Y.user.length>0){J.push("### 用户级");for(let U of Y.user){let X=U.status==="inactive"?" [PAUSED]":" [OK]";J.push(`- **${U.manifest.name}** v${U.manifest.version}${X}`),J.push(` ${U.manifest.description}`)}}return R().addAssistantMessage(J.join(`
|
|
@@ -1446,8 +1446,8 @@ ${J}
|
|
|
1446
1446
|
`)),{success:!0,message:`Installed ${U.pluginName}`}}return R().addAssistantMessage(`安装失败: ${U.error}`),{success:!1,error:U.error}}async function wW($,Z){let J=c2(Z),Y=J.positional[0];if(!Y)return R().addAssistantMessage("请指定插件名称: `/plugins uninstall <name> --confirm`"),{success:!1,error:"Plugin name required"};if(!J.confirm){let X=`卸载 ${Y} 需要显式确认,请添加 \`--confirm\``;return R().addAssistantMessage(X),{success:!1,error:"Plugin uninstall confirmation required"}}let{result:U}=await c6($.getWorkspaceRoot(),Y,J.confirm);if(U.success)return R().addAssistantMessage(`[OK] 已卸载插件: ${U.pluginName}`),{success:!0,message:`Uninstalled ${U.pluginName}`};return R().addAssistantMessage(`卸载失败: ${U.error}`),{success:!1,error:U.error}}async function AW($,Z){let J=c2(Z),Y=J.positional[0];if(!Y)return R().addAssistantMessage("请指定插件名称: `/plugins update <name> --trust`"),{success:!1,error:"Plugin name required"};if(!J.trust){let X=`更新会执行 ${Y} 的新代码,确认来源后使用 \`--trust\` 重试`;return R().addAssistantMessage(X),{success:!1,error:"Plugin source trust required"}}R().addAssistantMessage(`正在更新插件: ${Y}...`);let{result:U}=await p6($.getWorkspaceRoot(),Y,{trusted:J.trust});if(U.success){let X=[U.changed?"[OK] 插件更新成功!":"[OK] 插件已是最新版本","",`**名称**: ${U.pluginName}`,`**提交**: \`${U.installation?.revision??"local"}\``];if(U.manifest)X.push(`**版本**: ${U.manifest.version}`);if(U.updatedDependencies?.length)X.push(`**依赖更新**: ${U.updatedDependencies.join(", ")}`);return R().addAssistantMessage(X.join(`
|
|
1447
1447
|
`)),{success:!0,message:`Updated ${U.pluginName}`}}return R().addAssistantMessage(`更新失败: ${U.error}`),{success:!1,error:U.error}}function W1($,Z){let J=$.indexOf(Z);if(J>=0)return $[J+1];let Y=`${Z}=`;return $.find((U)=>U.startsWith(Y))?.slice(Y.length)}function J3($,Z){if($===void 0)return;if($==="true"||$==="on"||$==="1")return!0;if($==="false"||$==="off"||$==="0")return!1;throw Error(`${Z} must be true or false`)}function J4($){if($===void 0)return;return[...new Set($.split(",").map((Z)=>Z.trim()).filter(Boolean))]}function Y3($){return["## Plugin Source Policy","",`- Restrict sources: ${$.restrictToAllowedSources?"on":"off"}`,`- Require full Git SHA: ${$.requireGitCommitSha?"on":"off"}`,`- Git hosts: ${$.allowedGitHosts.join(", ")||"(none)"}`,`- Marketplaces: ${$.allowedMarketplaces.join(", ")||"(none)"}`,`- Local roots: ${$.allowedLocalRoots.join(", ")||"(none)"}`].join(`
|
|
1448
1448
|
`)}async function LW($,Z){let J=Z[0]?.toLowerCase()??"show";if(J==="show"||J==="status"){let Y=Y3($.getSourcePolicy());return R().addAssistantMessage(Y),{success:!0,message:Y}}if(J!=="set"){let Y="Usage: /plugins policy set [--restrict true] [--require-sha true] [--hosts host,...] [--marketplaces name,...] [--local-roots /path,...] [--scope global|project|local]";return R().addAssistantMessage(Y),{success:!1,error:Y}}try{let Y=$.getSourcePolicy(),U=J3(W1(Z,"--restrict"),"--restrict"),X=J3(W1(Z,"--require-sha"),"--require-sha"),H=J4(W1(Z,"--hosts")),Q=J4(W1(Z,"--marketplaces")),W=J4(W1(Z,"--local-roots"));if(U===void 0&&X===void 0&&H===void 0&&Q===void 0&&W===void 0)throw Error("No plugin policy fields were provided");let z=W1(Z,"--scope")??"global",V=Y4([z]),B=await m6($.getWorkspaceRoot(),{...Y,...U===void 0?{}:{restrictToAllowedSources:U},...X===void 0?{}:{requireGitCommitSha:X},...H===void 0?{}:{allowedGitHosts:H},...Q===void 0?{}:{allowedMarketplaces:Q},...W===void 0?{}:{allowedLocalRoots:W}},V),K=Y3(B);return R().addAssistantMessage(K),{success:!0,message:K}}catch(Y){let U=Y instanceof Error?Y.message:String(Y);return R().addAssistantMessage(`Plugin policy update failed: ${U}`),{success:!1,error:U}}}async function NW($,Z){let J=Z[0]?.toLowerCase()??"list",Y=c2(Z.slice(1));try{if(J==="list"||J==="ls"){let U=await m0().listCatalogs(),X=U.length===0?["没有已配置的 Plugin Marketplace。"]:["## Plugin Marketplaces","",...U.flatMap(({marketplace:H,manifest:Q})=>[`- **${H.name}** · ${Q.plugins.length} plugins`,` ${Q.description??Q.metadata?.description??""}`,` revision: \`${H.revision}\``])];return R().addAssistantMessage(X.join(`
|
|
1449
|
-
`)),{success:!0,message:"Marketplaces listed"}}if(J==="add"){let U=Y.positional[0];if(!U)throw Error("Usage: /plugins marketplace add <source> [--ref <ref>]");let X=await i6($.getWorkspaceRoot(),U,Y.ref);if(!X.success)throw Error(X.error);let H=`[OK] 已添加 Marketplace ${X.marketplace?.name}(${X.manifest?.plugins.length??0} 个插件)`;return R().addAssistantMessage(H),{success:!0,message:H}}if(J==="update"||J==="refresh"){let U=Y.positional[0],X=U?[U]:(await m0().listMarketplaces()).map((W)=>W.name);if(X.length===0)return R().addAssistantMessage("没有可更新的 Marketplace"),{success:!0,message:"没有可更新的 Marketplace"};let H=[];for(let W of X){let z=await l6($.getWorkspaceRoot(),W);if(!z.success)throw Error(z.error);H.push(`${W}${z.changed?"":" (unchanged)"}`)}let Q=`[OK] Marketplace 已更新: ${H.join(", ")}`;return R().addAssistantMessage(Q),{success:!0,message:Q}}if(J==="remove"||J==="rm"){let U=Y.positional[0];if(!U)throw Error("Usage: /plugins marketplace remove <name> --confirm");if(!Y.confirm)throw Error(`移除 Marketplace ${U} 需要 --confirm`);let X=await n6(U,!0);if(!X.success)throw Error(X.error);let H=`[OK] 已移除 Marketplace: ${U}`;return R().addAssistantMessage(H),{success:!0,message:H}}throw Error("Usage: /plugins marketplace <add|list|update|remove> [args]")}catch(U){let X=U instanceof Error?U.message:String(U);return R().addAssistantMessage(`Marketplace 操作失败: ${X}`),{success:!1,error:X}}}var U3=VW;import*as z1 from"node:fs/promises";import*as V1 from"node:path";async function Q3($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:U,storagePath:X}=Z,H=X??t$(U??N());if(!X){let K=await bW($,U??N(),J,Y);if(K)return K}let Q;try{Q=(await z1.readdir(H)).filter((G)=>G.endsWith(".jsonl")&&!G.startsWith("agent_")).map((G)=>V1.join(H,G))}catch{return[]}let z=(await Promise.all(Q.map(async(K)=>{try{let G=await z1.stat(K);return{path:K,mtime:G.mtimeMs}}catch{return null}}))).filter((K)=>K!==null).sort((K,G)=>G.mtime-K.mtime).map((K)=>K.path),V=[],B=Y?$:$.toLowerCase();for(let K of z){if(V.length>=J)break;let G=V1.basename(K,".jsonl"),O=await
|
|
1450
|
-
`).flatMap((B,K)=>{if(!B.trim())return[];try{return[{event:JSON.parse(B),index:K}]}catch{return[]}});if(!H.some(({event:B})=>B.type==="session_created"))return
|
|
1449
|
+
`)),{success:!0,message:"Marketplaces listed"}}if(J==="add"){let U=Y.positional[0];if(!U)throw Error("Usage: /plugins marketplace add <source> [--ref <ref>]");let X=await i6($.getWorkspaceRoot(),U,Y.ref);if(!X.success)throw Error(X.error);let H=`[OK] 已添加 Marketplace ${X.marketplace?.name}(${X.manifest?.plugins.length??0} 个插件)`;return R().addAssistantMessage(H),{success:!0,message:H}}if(J==="update"||J==="refresh"){let U=Y.positional[0],X=U?[U]:(await m0().listMarketplaces()).map((W)=>W.name);if(X.length===0)return R().addAssistantMessage("没有可更新的 Marketplace"),{success:!0,message:"没有可更新的 Marketplace"};let H=[];for(let W of X){let z=await l6($.getWorkspaceRoot(),W);if(!z.success)throw Error(z.error);H.push(`${W}${z.changed?"":" (unchanged)"}`)}let Q=`[OK] Marketplace 已更新: ${H.join(", ")}`;return R().addAssistantMessage(Q),{success:!0,message:Q}}if(J==="remove"||J==="rm"){let U=Y.positional[0];if(!U)throw Error("Usage: /plugins marketplace remove <name> --confirm");if(!Y.confirm)throw Error(`移除 Marketplace ${U} 需要 --confirm`);let X=await n6(U,!0);if(!X.success)throw Error(X.error);let H=`[OK] 已移除 Marketplace: ${U}`;return R().addAssistantMessage(H),{success:!0,message:H}}throw Error("Usage: /plugins marketplace <add|list|update|remove> [args]")}catch(U){let X=U instanceof Error?U.message:String(U);return R().addAssistantMessage(`Marketplace 操作失败: ${X}`),{success:!1,error:X}}}var U3=VW;import*as z1 from"node:fs/promises";import*as V1 from"node:path";async function Q3($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:U,storagePath:X}=Z,H=X??t$(U??N());if(!X){let K=await bW($,U??N(),J,Y);if(K)return K}let Q;try{Q=(await z1.readdir(H)).filter((G)=>G.endsWith(".jsonl")&&!G.startsWith("agent_")).map((G)=>V1.join(H,G))}catch{return[]}let z=(await Promise.all(Q.map(async(K)=>{try{let G=await z1.stat(K);return{path:K,mtime:G.mtimeMs}}catch{return null}}))).filter((K)=>K!==null).sort((K,G)=>G.mtime-K.mtime).map((K)=>K.path),V=[],B=Y?$:$.toLowerCase();for(let K of z){if(V.length>=J)break;let G=V1.basename(K,".jsonl"),O=await TW(K,B,Y,G);if(V.push(...O),V.length>=J){V.length=J;break}}return V}async function bW($,Z,J,Y){try{let{syncAll:U}=await import("./chunk-t8x2qpe2.js"),X=await X3();if(!X)return null;let{SessionService:H}=await import("./chunk-pehpndk9.js");await U(X,H.projectionDeriverForSearch());let Q=V1.resolve(Z),W=H3(X,$,Q,J*4),z=Y?$:$.toLowerCase(),V=[];for(let B of W){if(B.role!=="user"&&B.role!=="assistant")continue;let K=U4(B.text,z,Y,B.session_id,B.role,B.timestamp??void 0,0);if(K)V.push(K);if(V.length>=J)break}return V}catch{return null}}async function TW($,Z,J,Y){try{let U=await z1.readFile($,"utf8"),H=U.split(`
|
|
1450
|
+
`).flatMap((B,K)=>{if(!B.trim())return[];try{return[{event:JSON.parse(B),index:K}]}catch{return[]}});if(!H.some(({event:B})=>B.type==="session_created"))return jW(H,Z,J,Y);let W=new Map(H.flatMap(({event:B,index:K})=>typeof B.id==="string"?[[B.id,K+1]]:[])),z=g$(R2(U,$)),V=new Map;for(let B of z){if(B.type==="message_created"&&(B.data.role==="user"||B.data.role==="assistant"))V.set(B.data.messageId,{role:B.data.role,content:[],timestamp:B.timestamp,lineNumber:W.get(B.id)??0});if(B.type==="part_created"&&B.data.partType==="text"){let K=V.get(B.data.messageId),G=B.data.payload.text;if(K&&typeof G==="string")K.content.push(G)}}return[...V.values()].flatMap((B)=>{let K=U4(B.content.join(" "),Z,J,Y,B.role,B.timestamp,B.lineNumber);return K?[K]:[]})}catch{return[]}}function jW($,Z,J,Y){return $.flatMap(({event:U,index:X})=>{if(U.type!=="message")return[];let H=U.message;if(H?.role!=="user"&&H?.role!=="assistant"||!H.content)return[];let Q=typeof H.content==="string"?H.content:Array.isArray(H.content)?H.content.filter((z)=>typeof z==="object"&&z!==null&&z.type==="text"&&typeof z.text==="string").map((z)=>z.text).join(" "):"",W=U4(Q,Z,J,Y,H.role,typeof U.timestamp==="string"?U.timestamp:void 0,X+1);return W?[W]:[]})}function U4($,Z,J,Y,U,X,H){if(!$)return;let Q=J?$:$.toLowerCase();if(!Q.includes(Z))return;let W=Q.indexOf(Z),z=Math.max(0,W-80),V=Math.min($.length,W+Z.length+80);return{sessionId:Y,role:U,content:(z>0?"...":"")+$.slice(z,V).replace(/\n/g," ")+(V<$.length?"...":""),timestamp:X,lineNumber:H}}function W3($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
|
|
1451
1451
|
`];for(let J of $){let Y=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",U=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${U} \`${J.sessionId.slice(0,8)}\` (${Y})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
|
|
1452
1452
|
`)}var MW={name:"search",description:"Search past session transcripts",fullDescription:"搜索历史会话记录,查找过去的对话内容",usage:"/search <keyword>",aliases:["find","history"],category:"Session",examples:['/search 断路器 - 搜索包含"断路器"的历史对话',"/search edit tool - 搜索 edit tool 相关讨论"],async handler($,Z){let J=v(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let U=await Q3(Y,{maxResults:15,projectPath:Z.cwd}),X=W3(U);return J.sendMessage(X),{success:!0,message:`found ${U.length} results`,data:{matches:U.length}}}catch(U){let X=U instanceof Error?U.message:"未知错误";return J.sendMessage(`搜索失败: ${X}`),{success:!1,error:X}}}},z3=MW;var CW={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{return await C0({cwd:Z.workspaceRoot??Z.cwd}).refresh(),n$(Z.workspaceRoot??Z.cwd),await l$(Z.workspaceRoot??Z.cwd),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return R().addAssistantMessage(Y),{success:!1,error:Y}}}},V3=CW;import fW from"node:path";function i2($){if($<1000)return`${$}ms`;let Z=Math.floor($/1000);if(Z<60)return`${Z}s`;let J=Math.floor(Z/60);if(J<60)return`${J}m ${Z%60}s`;return`${Math.floor(J/60)}h ${J%60}m`}function B3($){switch($){case"running":return"[RUNNING]";case"completed":case"exited":return"[OK]";case"failed":case"error":return"[FAIL]";case"killed":case"cancelled":return"[STOPPED]";default:return"[?]"}}function K3($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function RW($,Z){let J=v(Z),Y=$[0],U=s.getInstance(),X=o.getInstance(),H=Z.sessionId??"",Q=Z.sessionId?{sessionId:Z.sessionId,projectPath:fW.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let G=$[1],O=$.slice(2).join(" ").trim();if(!G||!O)return{success:!1,error:"Usage: /tasks resume <agentId> <prompt>"};if(!Z.subagents)return{success:!1,error:"This surface does not own a subagent runtime"};let E=await Z.subagents.resume(G,O),q=`Resumed \`${G}\` as \`${E.session.id}\` (depth ${E.session.resumeDepth}).`;return J.sendMessage(q),{success:!0,message:q,data:{action:"subagent_resumed",sourceAgentId:G,subagent:E.session}}}if(Y==="clean"){let G=X.cleanupExpiredSessionsForParent(Q??H,0);return J.sendMessage(`已清理 ${G} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${G} agent sessions`}}let W=[`**后台任务列表**
|
|
1453
1453
|
`],z=U.listForSession(H);if(z.length>0){W.push(`### Shells
|
|
@@ -1467,18 +1467,18 @@ ${J}
|
|
|
1467
1467
|
- \`/tasks\` - 显示所有后台任务
|
|
1468
1468
|
- \`/tasks resume <agentId> <prompt>\` - 继续一个已结束的 agent
|
|
1469
1469
|
- \`/tasks clean\` - 清理已完成的 agent 会话`,usage:"/tasks [clean | resume <agentId> <prompt>]",category:"system",examples:["/tasks","/tasks resume agent_123 check the fix","/tasks clean"],handler:RW},_3=SW;async function PW($,Z){return{success:!0,message:"show_theme_selector",data:{action:"show_theme_selector"}}}var kW={name:"theme",description:"打开交互式主题选择器",aliases:["themes","style"],usage:"/theme",examples:["/theme"],category:"ui",handler:PW},G3=kW;function X4($){let Z=["## Workspace Trust","",`**状态**: ${$.state}`,`**项目**: \`${$.projectPath}\``,`**信任身份**: \`${$.trustRoot}\``,`**决策**: ${$.decision}`];if($.inheritedFrom)Z.push(`**继承自**: \`${$.inheritedFrom}\``);if($.error)Z.push("",`**错误**: ${$.error}`);if($.sources.length>0){Z.push("","### 待审阅项目来源");for(let J of $.sources){if(Z.push("",`- \`${J.path}\` (${J.kind})`),J.warning)Z.push(` ${J.warning}`);for(let Y of J.effects)Z.push(` - ${Y.kind}: ${Y.name}${Y.target?` → \`${Y.target}\``:""}`)}}else Z.push("","当前项目没有自动执行型配置,不需要 Folder Trust。");return Z.join(`
|
|
1470
|
-
`)}async function vW($,Z){let J=await
|
|
1470
|
+
`)}async function vW($,Z){let J=await j0.getInstance().getStatus($);return Z.sendMessage(X4(J)),{success:!0,message:`Workspace trust: ${J.state}`}}var IW={name:"trust",description:"Review and manage project folder trust",fullDescription:`审阅和管理当前项目的 Folder Trust。
|
|
1471
1471
|
|
|
1472
1472
|
/trust - 显示状态与自动执行型项目来源
|
|
1473
1473
|
/trust review - 显示完整审阅信息
|
|
1474
1474
|
/trust approve - 信任当前项目及其子目录
|
|
1475
|
-
/trust revoke - 撤销当前项目信任`,usage:"/trust [review|approve|revoke]",category:"system",examples:["/trust","/trust review","/trust approve","/trust revoke"],handler:async($,Z)=>{let J=$[0]?.toLowerCase()||"status",Y=v(Z),U=
|
|
1475
|
+
/trust revoke - 撤销当前项目信任`,usage:"/trust [review|approve|revoke]",category:"system",examples:["/trust","/trust review","/trust approve","/trust revoke"],handler:async($,Z)=>{let J=$[0]?.toLowerCase()||"status",Y=v(Z),U=j0.getInstance();if(J==="status"||J==="review")return vW(Z.cwd,Y);if(J==="approve"||J==="trust"){let X=await U.trust(Z.cwd);return await h6(),Y.sendMessage(`${X4(X)}
|
|
1476
1476
|
|
|
1477
1477
|
`+"项目已信任。请重新启动当前 Blade 进程,使项目模型、MCP、权限和插件层完整生效。"),{success:!0,message:"Workspace trusted; restart required"}}if(J==="revoke"||J==="untrust"){let X=await U.revoke(Z.cwd);return await h6(),Y.sendMessage(`${X4(X)}
|
|
1478
1478
|
|
|
1479
1479
|
`+"项目信任已撤销。请重新启动当前 Blade 进程,回收已加载的项目资源。"),{success:!0,message:"Workspace trust revoked; restart required"}}return Y.sendMessage(`未知子命令: ${J}
|
|
1480
|
-
使用 /trust review|approve|revoke`),{success:!1,error:`Unknown subcommand: ${J}`}}},O3=IW;var h1={...h7,init:$3,theme:G3,permissions:d2,model:Z3,git:i7,goal:l7,ide:t7,search:z3,skills:V3,hooks:n7,tasks:_3,plugins:U3,trust:O3};function
|
|
1480
|
+
使用 /trust review|approve|revoke`),{success:!1,error:`Unknown subcommand: ${J}`}}},O3=IW;var h1={...h7,init:$3,theme:G3,permissions:d2,model:Z3,git:i7,goal:l7,ide:t7,search:z3,skills:V3,hooks:n7,tasks:_3,plugins:U3,trust:O3};function wT($){return $.trim().startsWith("/")}function xW($){let Z=$.trim();if(!Z.startsWith("/"))throw Error("不是有效的 slash command");let J=Z.slice(1).split(/\s+/),Y=J[0]||"",U=J.slice(1);return{command:Y,args:U}}function hW($){if(h1[$])return h1[$];for(let Z of Object.values(h1))if(Z.aliases?.includes($))return Z;return}function q3($){let Z=$.argumentHint?`/${$.name} ${$.argumentHint}`:`/${$.name}`;return{name:$.name,description:$.description,fullDescription:`[Skill] ${$.description}${$.whenToUse?`
|
|
1481
1481
|
|
|
1482
|
-
**When to use:** ${$.whenToUse}`:""}`,usage:Z,category:"skill",examples:[Z],handler:async(J,Y)=>{return{success:!0,message:`Invoking skill: ${$.name}`,data:{action:"invoke_skill",skillName:$.name,skillArgs:J.join(" ")}}}}}function uW($,Z){return C0({cwd:Z}).getUserInvocableSkills().find((U)=>U.name===$)}async function dW($){await E3({cwd:$})}async function mW($){let Z=R0.getInstance($),J=Z.getLastDiscoveryResult();if(Z.isInitialized()&&J)return J;return await Z.initialize($)}async function
|
|
1483
|
-
使用 /help 查看可用命令`}}catch(J){return{success:!1,error:`命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}}function
|
|
1484
|
-
export{MV as r,O$ as s,I as t,
|
|
1482
|
+
**When to use:** ${$.whenToUse}`:""}`,usage:Z,category:"skill",examples:[Z],handler:async(J,Y)=>{return{success:!0,message:`Invoking skill: ${$.name}`,data:{action:"invoke_skill",skillName:$.name,skillArgs:J.join(" ")}}}}}function uW($,Z){return C0({cwd:Z}).getUserInvocableSkills().find((U)=>U.name===$)}async function dW($){await E3({cwd:$})}async function mW($){let Z=R0.getInstance($),J=Z.getLastDiscoveryResult();if(Z.isInitialized()&&J)return J;return await Z.initialize($)}async function AT($,Z){try{let{command:J,args:Y}=xW($),U=hW(J);if(U)return await U.handler(Y,Z);let X=Z.workspaceRoot||Z.cwd||N();await e(X);let H=R0.getInstance(X);if(!H.isInitialized())await mW(X);if(H.hasCommand(J)){let V=H.getCommand(J);if(V){let B=await H.executeCommand(J,{args:Y,workspaceRoot:X,signal:Z.signal});if(B)return{success:!0,message:`执行自定义命令: /${J}`,data:{action:"invoke_custom_command",commandName:J,processedContent:B,config:V.config}}}}let W=U$(X).findCommand(J);if(W){let V=await H.executePluginCommand(W.namespacedName,{args:Y,workspaceRoot:X,signal:Z.signal});if(V)return{success:!0,message:`执行插件命令: /${W.namespacedName}`,data:{action:"invoke_plugin_command",commandName:W.namespacedName,pluginName:W.pluginName,processedContent:V,config:W.config}}}await dW(X);let z=uW(J,X);if(z)return await q3(z).handler(Y,Z);return{success:!1,error:`未知命令: /${J}
|
|
1483
|
+
使用 /help 查看可用命令`}}catch(J){return{success:!1,error:`命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}}function LT($=N()){let Z=Object.values(h1),Y=R0.getInstance($).getAllCommands().map((W)=>({name:W.name,description:W.config.description||W.content.slice(0,50),usage:W.config.argumentHint?`/${W.name} ${W.config.argumentHint}`:`/${W.name}`,category:"custom",handler:async()=>({success:!0})})),X=U$($).getAllCommands().map((W)=>({name:W.namespacedName,description:W.config.description||W.content.slice(0,50),usage:W.config.argumentHint?`/${W.namespacedName} ${W.config.argumentHint}`:`/${W.namespacedName}`,category:"plugin",handler:async()=>({success:!0})})),Q=C0({cwd:$}).getUserInvocableSkills().map(q3);return[...Z,...Y,...X,...Q]}function NT($,Z=N()){let J=($.startsWith("/")?$.slice(1):$).trim(),Y=Object.values(h1).map((O)=>({name:O.name,description:O.description,aliases:O.aliases||[],label:void 0,argumentHint:void 0,isCustom:!1,isSkill:!1,isPlugin:!1})),U=R0.getInstance(Z),X=U.getAllCommands().map((O)=>({name:O.name,description:O.config.description||O.content.slice(0,50),aliases:[],label:U.getCommandLabel(O),argumentHint:O.config.argumentHint,isCustom:!0,isSkill:!1,isPlugin:!1})),Q=U$(Z).getAllCommands().map((O)=>({name:O.namespacedName,description:O.config.description||O.content.slice(0,50),aliases:[O.originalName],label:`(plugin: ${O.pluginName})`,argumentHint:O.config.argumentHint,isCustom:!1,isSkill:!1,isPlugin:!0})),z=C0({cwd:Z}).getUserInvocableSkills().map((O)=>({name:O.name,description:O.description,aliases:[],label:"(skill)",argumentHint:O.argumentHint,isCustom:!1,isSkill:!0,isPlugin:!1})),V=[...Y,...X,...Q,...z];if(!J)return V.map((O)=>({command:`/${O.name}`,description:O.label?`${O.description} ${O.label}`:O.description,argumentHint:O.argumentHint,matchScore:50}));return new yW(V,{keys:[{name:"name",weight:3},{name:"aliases",weight:2.5},{name:"description",weight:0.5}],threshold:0.4,includeScore:!0,ignoreLocation:!0,minMatchCharLength:1}).search(J).map((O)=>{let E=O.score??1,q=Math.round((1-E)*100),F=O.item;return{command:`/${F.name}`,description:F.label?`${F.description} ${F.label}`:F.description,argumentHint:F.argumentHint,matchScore:q}}).filter((O)=>(O.matchScore||0)>=40)}
|
|
1484
|
+
export{MV as r,O$ as s,I as t,T0 as u,I$ as v,GY as w,s as x,KO as y,E0 as z,t0 as A,m$ as B,S8 as C,$1 as D,N$ as E,N6 as F,s8 as G,t8 as H,Y9 as I,O0 as J,y2 as K,x2 as L,m6 as M,g6 as N,p6 as O,c6 as P,i6 as Q,l6 as R,n6 as S,h2 as T,o6 as U,gN as V,h6 as W,wT as X,mW as Y,AT as Z,LT as _,NT as $};
|