blade-code 0.10.4 → 0.10.5
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-069zpw09.js +6 -0
- package/dist/{chunk-xq8vf15n.js → chunk-19kg7yvw.js} +1 -1
- package/dist/{chunk-9kwt0w46.js → chunk-1m5r6mp2.js} +1 -1
- package/dist/{chunk-jbnrscvz.js → chunk-1q21sxhx.js} +1 -1
- package/dist/{chunk-kkd7mm55.js → chunk-1r6szcrj.js} +1 -1
- package/dist/{chunk-nr53mq0k.js → chunk-1vx4sf1y.js} +1 -1
- package/dist/{chunk-d7xb0vp1.js → chunk-1x4fpe47.js} +1 -1
- package/dist/{chunk-d4zw0xxe.js → chunk-2nkd1kjx.js} +1 -1
- package/dist/chunk-417wefq7.js +99 -0
- package/dist/{chunk-5t0vs4hz.js → chunk-51wtvmzn.js} +2 -2
- package/dist/{chunk-a7a74pza.js → chunk-62881c2s.js} +93 -93
- package/dist/{chunk-ffp3ypbb.js → chunk-6eragc74.js} +1 -1
- package/dist/{chunk-n2s54h1r.js → chunk-7jy60gnx.js} +1 -1
- package/dist/{chunk-1ndryz4h.js → chunk-am8dtvff.js} +1 -1
- package/dist/chunk-c5tds5v0.js +9 -0
- package/dist/{chunk-f647z66n.js → chunk-f6mszdsd.js} +1 -1
- package/dist/{chunk-rv80ak15.js → chunk-fz1vyc15.js} +1 -1
- package/dist/chunk-hh85pk77.js +160 -0
- package/dist/{chunk-ve9cke2g.js → chunk-njyvrtje.js} +2 -2
- package/dist/{chunk-wdbmbk6h.js → chunk-nz78b5c5.js} +1 -1
- package/dist/chunk-r1764q6f.js +1 -0
- package/dist/chunk-r6mwyg3h.js +3 -0
- package/dist/{chunk-csr5vppa.js → chunk-rh7v814a.js} +1 -1
- package/dist/chunk-rzzt21ef.js +22 -0
- package/dist/{chunk-mxqpg4gy.js → chunk-s645azsm.js} +1 -1
- package/dist/{chunk-b9v7waxf.js → chunk-sanhjqpd.js} +1 -1
- package/dist/{chunk-tx8f345j.js → chunk-tjnfhm9v.js} +1 -1
- package/dist/{chunk-pehpndk9.js → chunk-v0ygsjry.js} +1 -1
- package/dist/{chunk-age5tc86.js → chunk-vntzy7bc.js} +1 -1
- package/dist/{chunk-vxymgh8e.js → chunk-vpj0sv73.js} +1 -1
- package/dist/{chunk-90fnvvcf.js → chunk-xv0maezy.js} +1 -1
- package/dist/{chunk-fx87s3mb.js → chunk-yc53wz4r.js} +1 -1
- package/dist/web/assets/{ChatView-iK7ff8qU.js → ChatView-Y-6k-ayR.js} +2 -2
- package/dist/web/assets/{CodeBlockHighlighter-BoJp_Xb0.js → CodeBlockHighlighter-CFW6qjnA.js} +1 -1
- package/dist/web/assets/{FilePreview-Bi1HWOvY.js → FilePreview-CR_XetY0.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-DMW1pg5N.js → MarkdownRenderer-CVrxJswQ.js} +3 -3
- package/dist/web/assets/{McpModal-CHUqitJ6.js → McpModal-BO-85gll.js} +1 -1
- package/dist/web/assets/{SettingsModal-zsS9O6SW.js → SettingsModal-CW87OnxI.js} +1 -1
- package/dist/web/assets/{SkillsModal-C2oTDXoy.js → SkillsModal-Q8ZFPhys.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-CncVasNA.js → TaskSwitcher-BzH-0QXr.js} +1 -1
- package/dist/web/assets/{TerminalPanel-CBi2mUxx.js → TerminalPanel-DTqvx8yB.js} +1 -1
- package/dist/web/assets/index-ClOgGy-I.js +32 -0
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/dist/chunk-5ze48kg7.js +0 -22
- package/dist/chunk-d5a66cgn.js +0 -160
- package/dist/chunk-scq3ns6v.js +0 -99
- package/dist/chunk-v8kp3ep9.js +0 -6
- package/dist/chunk-xkzy5wbm.js +0 -9
- package/dist/chunk-ys8bp9jm.js +0 -1
- package/dist/chunk-zswrw5f9.js +0 -3
- package/dist/web/assets/index-DvDtvgA4.js +0 -32
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{aa as j,ba as u0,ga as L7,ha as w8,ia as k0}from"./chunk-
|
|
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}
|
|
1
|
+
import{aa as j,ba as u0,ga as L7,ha as w8,ia as k0}from"./chunk-s645azsm.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-1m5r6mp2.js";import{Sa as a8,Ta as o8,Ua as z2}from"./chunk-jza1rsan.js";import{$a as n9,_a as X0,ab as r9,bb as v2,cb as V0,db as n0,eb as t2,fb as s$,gb as a9,hb as o9,kb as q7,nb as s9,ob as t9,qb as c}from"./chunk-417wefq7.js";import{Cb as X3,Ib as H3,rb as R2,sb as a0,yb as m$}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 A$,nc as w6,oc as S$,pc as v8,uc as a$}from"./chunk-sanhjqpd.js";import{vc as h$}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 C$}from"./chunk-ea7wsges.js";import{Fc as _7}from"./chunk-gxmrakrk.js";import{Hc as g9,Ic as p9,Jc as c9}from"./chunk-yc53wz4r.js";import{$c as $7,Kc as T$,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 i$,Vc as l$,Wc as l9,Xc as u6,Zc as e,_c as G2}from"./chunk-am8dtvff.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-vpj0sv73.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-rh7v814a.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-1vx4sf1y.js";import{Je as j0}from"./chunk-z906d5tb.js";import{Me as t$,Oe as I$,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 f$ extends Error{constructor($){super($);this.name="WorkspaceSandboxUnavailableError"}}class n$ 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 n$(`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 n$(`Workspace sandbox path cannot be resolved: ${X instanceof Error?X.message:String(X)}`)}if(!X0.isWithinWorkspace(U,Y))throw new n$(`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,D,F)=>F.indexOf(q)===D):[],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 f$(`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 f$(`Workspace sandbox is unsupported on ${process.platform}`);let $=await this.runtime.checkDependencies();if($.errors.length>0)throw new f$(`Workspace sandbox dependencies are unavailable: ${$.errors.join("; ")}`);try{await this.runtime.initialize(a2(["*"]))}catch(Z){throw new f$(`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 R${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 R$;function O$(){return T3}var F0=u("Agent");class K1{connection;sessionId;capabilities;fallback;constructor($,Z,J,Y=new R$){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 R$;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 R$}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 l 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=l.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:l.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 ${l.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=l.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[l.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:l.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):l.resolve(J.uri)}catch{return}if(!this.isInsideWorkspace(Y))return;let U=Y$(l.resolve(Y)).href,X={sequence:++this.diagnosticSequence,serverName:$,filePath:l.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=l.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$(
|
|
9
|
+
</new-diagnostics>`,$.metadata={...$.metadata,lsp_diagnostics:U,lsp_diagnostic_count:U.length}}getCurrentDiagnostics($){return this.diagnostics.get(Y$(l.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=l.isAbsolute($)?l.resolve($):l.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=l.isAbsolute($)?l.resolve($):l.resolve(this.workspaceRoot,$),J=[],Y=Z;while(!0){try{let X=await g1.realpath(Y),H=l.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=l.dirname(Y);if(U===Y)throw Error("Cannot resolve deleted LSP target");J.push(l.basename(Y)),Y=U}}isInsideWorkspace($){let Z=l.relative(this.workspaceRoot,l.resolve($));return Z===""||!Z.startsWith(`..${l.sep}`)&&Z!==".."&&!l.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,15 +159,15 @@ ${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
|
|
163
|
-
${
|
|
164
|
-
</auto-memory>`),E.push({name:"auto_memory",loaded:!0,length:
|
|
162
|
+
</project-instructions>`,files:Q,contentBytes:Z-H}}var $J=/<available_skills>\s*<\/available_skills>/;async function P$($={}){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",D,F;if(q)D=i4,F="plan_mode_prompt";else D=J??c4,F=J?"replace_default":"default";O.push(D),E.push({name:F,loaded:!0,length:D.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 b=z?z.staticRules(V??Z):await n4(Z);if(b&&b.files.length>0)O.push(b.content),E.push({name:"project_instructions",loaded:!0,length:b.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 T=await new q$(Z).loadIndex();if(T)O.push(`<auto-memory>
|
|
163
|
+
${T}
|
|
164
|
+
</auto-memory>`),E.push({name:"auto_memory",loaded:!0,length:T.length});else E.push({name:"auto_memory",loaded:!1})}catch{E.push({name:"auto_memory",loaded:!1})}if(X){let b=r4(Z?{...H,workingDirectory:Z}:H);if(b)O.push(b),E.push({name:"environment",loaded:!0,length:b.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
|
|
|
168
168
|
`);return w=ZJ(w,Z,B),w=YJ(w,Q),{prompt:w,sources:E}}function ZJ($,Z,J){let Y=J??C0(Z?{cwd:Z}:void 0).generateAvailableSkillsList();if(!Y)return $;return $.replace($J,`<available_skills>
|
|
169
169
|
${Y}
|
|
170
|
-
</available_skills>`)}var JJ={"zh-CN":"Chinese (Simplified Chinese)","zh-TW":"Chinese (Traditional Chinese)","en-US":"English","en-GB":"English (British)","ja-JP":"Japanese","ko-KR":"Korean","es-ES":"Spanish","fr-FR":"French","de-DE":"German","pt-BR":"Portuguese (Brazilian)","ru-RU":"Russian"};function YJ($,Z){let J=Z||"zh-CN",Y=JJ[J]||J,U=`IMPORTANT: Always respond in ${Y}. All your responses must be in ${Y}.`;return $.replace("{{LANGUAGE_INSTRUCTION}}",U)}import o4 from"fast-glob";import*as
|
|
170
|
+
</available_skills>`)}var JJ={"zh-CN":"Chinese (Simplified Chinese)","zh-TW":"Chinese (Traditional Chinese)","en-US":"English","en-GB":"English (British)","ja-JP":"Japanese","ko-KR":"Korean","es-ES":"Spanish","fr-FR":"French","de-DE":"German","pt-BR":"Portuguese (Brazilian)","ru-RU":"Russian"};function YJ($,Z){let J=Z||"zh-CN",Y=JJ[J]||J,U=`IMPORTANT: Always respond in ${Y}. All your responses must be in ${Y}.`;return $.replace("{{LANGUAGE_INSTRUCTION}}",U)}import o4 from"fast-glob";import*as r$ from"fs/promises";import*as s4 from"path";function MV($){return $.endsWith("/")||$.endsWith("\\")}function E1($){return $.replace(/\\/g,"/").split("/").filter(Boolean)}class a1{static PATTERN=/@"([^"]+)"|@([^\s]+)/g;static LINE_RANGE_PATTERN=/#L(\d+)(?:-(\d+))?$/;static GLOB_PATTERN=/[*?[\]]/;static extract($){let Z=[],J;this.PATTERN.lastIndex=0;while((J=this.PATTERN.exec($))!==null){let Y=J[0],U=J[1]||J[2],X=this.parseLineRange(U);if(X)U=U.replace(this.LINE_RANGE_PATTERN,"");let H=this.GLOB_PATTERN.test(U);Z.push({raw:Y,path:U.trim(),lineRange:X,startIndex:J.index,endIndex:J.index+Y.length,isGlob:H})}return Z}static parseLineRange($){let Z=$.match(this.LINE_RANGE_PATTERN);if(!Z)return;let J=parseInt(Z[1],10),Y=Z[2]?parseInt(Z[2],10):void 0;return{start:J,end:Y}}static hasAtMentions($){return $.includes("@")}static isValidPath($){if(!$||$.trim().length===0)return!1;let Z=["<",">","|","\x00"];for(let J of Z)if($.includes(J))return!1;return!0}static removeAtMentions($){return this.PATTERN.lastIndex=0,$.replace(this.PATTERN,"")}}var y0=u("Prompts");function o1($){return $ instanceof Map}class q1{fileCache=new Map;options;constructor($){this.options={maxFileSize:1048576,maxLines:2000,maxTokens:32000,...$},y0.debug("AttachmentCollector initialized",{maxFileSize:this.options.maxFileSize,maxLines:this.options.maxLines})}setCwd($){if(this.options.cwd===$)return;this.options.cwd=$,this.fileCache.clear()}async collect($){if(!a1.hasAtMentions($))return[];let Z=a1.extract($);if(Z.length===0)return[];y0.debug(`Found ${Z.length} @ mentions`);let J=Z.map((U)=>this.processOne(U));return(await Promise.allSettled(J)).map((U,X)=>{if(U.status==="fulfilled")return U.value;else{let H=Z[X],Q=U.reason instanceof Error?U.reason.message:String(U.reason);return y0.warn(`Failed to process @${H.path}:`,Q),{type:"error",path:H.path,content:"",error:Q}}})}async processOne($){if($.isGlob)return y0.debug(`Processing glob pattern: ${$.path}`),await this.processGlob($.path);let Z=await X0.validatePath($.path,this.options.cwd),J=await X0.resolveSymlink(Z,this.options.cwd);if((await r$.stat(J)).isDirectory())return y0.debug(`Processing directory: ${$.path}`),await this.renderDirectoryTree(J,$.path);return y0.debug(`Processing file: ${$.path}`,{lineRange:$.lineRange}),await this.readFile(J,$.path,$.lineRange)}async readFile($,Z,J){let Y=this.fileCache.get($);if(Y&&Date.now()-Y.timestamp<60000)return y0.debug(`Cache hit: ${Z}`),this.formatFileAttachment(Z,Y.content,J);let U=await r$.stat($);if(U.size>this.options.maxFileSize)throw Error(`File too large: ${Math.round(U.size/1024/1024)}MB (max ${Math.round(this.options.maxFileSize/1024/1024)}MB)`);let X;try{X=await r$.readFile($,"utf-8")}catch(H){throw Error(`Cannot read file as text: ${Z}. It may be a binary file.`)}return this.fileCache.set($,{content:X,timestamp:Date.now()}),this.formatFileAttachment(Z,X,J)}formatFileAttachment($,Z,J){let Y=Z.split(`
|
|
171
171
|
`),U=Z,X=!1,H=J;if(J){let Q=Math.max(0,J.start-1),W=J.end?J.end:J.start;if(Q>=Y.length)throw Error(`Line range start (${J.start}) exceeds file length (${Y.length} lines)`);let z=Math.min(W,Y.length);U=Y.slice(Q,z).join(`
|
|
172
172
|
`);let V=Array.from({length:z-Q},(K,G)=>Q+G+1);U=U.split(`
|
|
173
173
|
`).map((K,G)=>`${V[G]}: ${K}`).join(`
|
|
@@ -177,7 +177,7 @@ ${Y}
|
|
|
177
177
|
[... truncated ${Y.length-this.options.maxLines} lines ...]`,X=!0;return{type:"file",path:$,content:U,metadata:{size:Z.length,lines:Y.length,truncated:X,lineRange:H}}}async renderDirectoryTree($,Z){let J=await o4("**/*",{cwd:$,dot:!1,followSymbolicLinks:!1,onlyFiles:!0,unique:!0,ignore:["node_modules/**",".git/**","dist/**","build/**",".next/**",".cache/**","coverage/**"]});if(J.length===0)return{type:"directory",path:Z,content:"(empty directory)"};y0.debug(`Found ${J.length} files in directory: ${Z}`);let Y=this.buildFileTree(J),U=this.printTree(Y,Z),X=500,H=J.length>X?`
|
|
178
178
|
|
|
179
179
|
[... and ${J.length-X} more files]`:"";return{type:"directory",path:Z,content:U+H,metadata:{lines:J.length,truncated:J.length>X}}}buildFileTree($){let Z=new Map;for(let J of $){let Y=E1(J),U=Z;for(let X=0;X<Y.length;X++){let H=Y[X],Q=X===Y.length-1;if(!U.has(H))U.set(H,Q?null:new Map);if(!Q){let W=U.get(H);if(W&&o1(W))U=W}}}return Z}printTree($,Z,J="",Y=!0){let U=[];if(J==="")U.push(`${Z}/`);let X=Array.from($.entries()).sort((H,Q)=>{let W=o1(H[1]),z=o1(Q[1]);if(W!==z)return z?1:-1;return H[0].localeCompare(Q[0])});return X.forEach(([H,Q],W)=>{let z=W===X.length-1,V=z?"└── ":"├── ",B=o1(Q);if(U.push(`${J}${V}${H}${B?"/":""}`),B&&Q.size>0){let K=J+(z?" ":"│ ");U.push(this.printTree(Q,"",K,z))}}),U.filter((H)=>H).join(`
|
|
180
|
-
`)}async processGlob($){let Z=await o4($,{cwd:this.options.cwd,dot:!1,followSymbolicLinks:!1,onlyFiles:!0,unique:!0,ignore:["node_modules/**",".git/**","dist/**","build/**",".next/**",".cache/**","coverage/**"]});if(Z.length===0)return{type:"error",path:$,content:"",error:`No files matched pattern: ${$}`};y0.debug(`Glob pattern "${$}" matched ${Z.length} files`);let J=30,Y=Z.slice(0,J),X=(await Promise.allSettled(Y.map(async(z)=>{let V=s4.join(this.options.cwd,z);try{let B=await
|
|
180
|
+
`)}async processGlob($){let Z=await o4($,{cwd:this.options.cwd,dot:!1,followSymbolicLinks:!1,onlyFiles:!0,unique:!0,ignore:["node_modules/**",".git/**","dist/**","build/**",".next/**",".cache/**","coverage/**"]});if(Z.length===0)return{type:"error",path:$,content:"",error:`No files matched pattern: ${$}`};y0.debug(`Glob pattern "${$}" matched ${Z.length} files`);let J=30,Y=Z.slice(0,J),X=(await Promise.allSettled(Y.map(async(z)=>{let V=s4.join(this.options.cwd,z);try{let B=await r$.readFile(V,"utf-8"),K=B.split(`
|
|
181
181
|
`),G=200,O=B,E=!1;if(K.length>200)O=K.slice(0,200).join(`
|
|
182
182
|
`),O+=`
|
|
183
183
|
|
|
@@ -186,14 +186,14 @@ ${z.content}`).join(`
|
|
|
186
186
|
|
|
187
187
|
`),W=Z.length>J?`
|
|
188
188
|
|
|
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
|
|
190
|
-
`,"utf8"),await H.sync(),await H.close(),H=void 0}catch(Q){if(await H?.close().catch(()=>{return}),Q.code!=="EEXIST")throw await
|
|
191
|
-
`,{mode:384}),await
|
|
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
|
|
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 n}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 n.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
|
+
`,"utf8"),await H.sync(),await H.close(),H=void 0}catch(Q){if(await H?.close().catch(()=>{return}),Q.code!=="EEXIST")throw await n.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 n.rm($.filePath,{force:!0})}async function YZ($){let Z;try{Z=await n.realpath($)}catch{return 0}return z5(Z,()=>B5(Z))}async function B5($){let Z=K5($),J;try{J=await n.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 n.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 n.rm(J.path,{force:!0}),await n.rename(J.backupPath,J.path);else if(!J.oldExisted&&J.newContentHash&&!(J.stagePath&&await e4(J.stagePath))&&await OJ(J.path)===J.newContentHash)await n.rm(J.path,{force:!0})}if(J.stagePath)await n.rm(J.stagePath,{force:!0});if(J.backupPath)await n.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 n.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 n.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 n.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 n.mkdir($,{recursive:!0,mode:448});let Z=await n.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 n.readFile($,"utf8")).token===Z)await n.rm($,{force:!0})}catch(J){if(J.code!=="ENOENT")throw J}}async function _J($){let Z;try{Z=await n.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 n.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 n.rm($,{force:!0})}function GJ($){try{return process.kill($,0),!0}catch(Z){return Z.code==="EPERM"}}async function e4($){try{return await n.lstat($),!0}catch(Z){if(Z.code==="ENOENT")return!1;throw Z}}async function OJ($){try{return W5("sha256").update(await n.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 a$().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 k$ 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
|
`)}
|
|
196
|
-
`,line:Q});continue}if(H.startsWith(q5)){Y.push({kind:"delete",path:e1(H.slice(q5.length),Q),line:Q}),X++;continue}if(H.startsWith(F5)){let W=e1(H.slice(F5.length),Q);X++;let z;if(J[X]?.startsWith(BZ))z=e1(J[X].slice(BZ.length),X+1),X++;let V=[],B=!1;while(X<J.length-1&&!O5(J[X])){let K=J[X];if(K!=="@@"&&!K.startsWith("@@ "))throw new J0('Update File content must begin with "@@"',X+1);if(++U>GZ)throw new J0(`patch exceeds the ${GZ} hunk limit`,X+1);let G=X+1,O=K==="@@"?void 0:K.slice(3);X++;let E=[],q=[],
|
|
196
|
+
`,line:Q});continue}if(H.startsWith(q5)){Y.push({kind:"delete",path:e1(H.slice(q5.length),Q),line:Q}),X++;continue}if(H.startsWith(F5)){let W=e1(H.slice(F5.length),Q);X++;let z;if(J[X]?.startsWith(BZ))z=e1(J[X].slice(BZ.length),X+1),X++;let V=[],B=!1;while(X<J.length-1&&!O5(J[X])){let K=J[X];if(K!=="@@"&&!K.startsWith("@@ "))throw new J0('Update File content must begin with "@@"',X+1);if(++U>GZ)throw new J0(`patch exceeds the ${GZ} hunk limit`,X+1);let G=X+1,O=K==="@@"?void 0:K.slice(3);X++;let E=[],q=[],D=!1,F=!1;while(X<J.length-1&&!O5(J[X])&&J[X]!=="@@"&&!J[X].startsWith("@@ ")){let L=J[X];if(L===DJ){D=!0,X++;break}let A=L[0];if(A!==" "&&A!=="-"&&A!=="+")throw new J0('hunk lines must start with " ", "-", or "+"',X+1);let w=L.slice(1);if(A!=="+")E.push(w);if(A!=="-")q.push(w);if(A!==" ")F=!0;X++}V.push({...O?{changeContext:O}:{},oldLines:E,newLines:q,isEndOfFile:D,hasChange:F,line:G}),B||=F}if(!z&&!B)throw new J0("Update File must change content or include a Move to destination",Q);Y.push({kind:"update",path:W,...z?{movePath:z}:{},chunks:V,line:Q});continue}throw new J0("expected Add File, Delete File, or Update File header",Q)}if(Y.length===0)throw new J0("patch must contain at least one file operation");return Y}function EZ($){return D5($).flatMap((Z)=>Z.kind==="update"&&Z.movePath?[Z.path,Z.movePath]:[Z.path])}function O5($){return Boolean($?.startsWith(E5)||$?.startsWith(q5)||$?.startsWith(F5))}function e1($,Z){if($!==$.trim()||$.length===0||$.length>4096)throw new J0("file path is empty, padded, or too long",Z);if($.includes(`
|
|
197
197
|
`)||$.includes("\r")||$.includes("\\")||WZ.posix.isAbsolute($)||WZ.win32.isAbsolute($))throw new J0("file paths must be relative POSIX paths",Z);if($.split("/").some((Y)=>Y.length===0||Y==="."||Y===".."))throw new J0('file paths cannot contain empty, "." or ".." segments',Z);return $}import{isUtf8 as NZ}from"node:buffer";import{promises as z0}from"node:fs";import D0 from"node:path";import{nanoid as AJ}from"nanoid";class w5 extends Error{filePath;hunkLine;constructor($,Z,J){super(`Cannot apply patch to ${$} (hunk line ${Z}): ${J}`);this.filePath=$;this.hunkLine=Z;this.name="ApplyPatchContextError"}}function A5($,Z,J){let Y=wJ($),U=$.replace(/\r\n/g,`
|
|
198
198
|
`),X=U.endsWith(`
|
|
199
199
|
`),H=U.split(`
|
|
@@ -212,7 +212,7 @@ ${G}`:"insertion point could not be resolved")}if(V.hasChange)H.splice(K,V.oldLi
|
|
|
212
212
|
+export const value = 1;
|
|
213
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
|
-
`)}`,"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($)?
|
|
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($)?k$.win32:k$.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=k$.resolve(Z,k$.relative(Z,U.path));return!Y.hasFileBeenRead(U.path,J)&&!Y.hasFileBeenRead(X,J)}).map((U)=>k$.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 ${k$.basename(Z)}`}function xJ($,Z){let J={add:"A",update:"M",delete:"D"};return[PZ($,Z),...$.changes.map((Y)=>`${J[Y.kind]} ${k$.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(`
|
|
217
217
|
`),X=1;for(let H of U){let Q=H.match(/@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@/);if(Q){X=parseInt(Q[1],10);break}}return`
|
|
218
218
|
<<<DIFF>>>
|
|
@@ -225,9 +225,9 @@ ${JSON.stringify({patch:Y,startLine:Math.max(1,X-J),matchLine:X})}
|
|
|
225
225
|
`),B=Y.split(`
|
|
226
226
|
`),K=Math.max(0,Q-U),G=Math.min(W.length,Q+V.length+U),O=Math.min(z.length,Q+B.length+U),E=W.slice(K,G).join(`
|
|
227
227
|
`),q=z.slice(K,O).join(`
|
|
228
|
-
`),
|
|
228
|
+
`),D=b5.createPatch("file",E,q,"","",{context:U});return`
|
|
229
229
|
<<<DIFF>>>
|
|
230
|
-
${JSON.stringify({patch:
|
|
230
|
+
${JSON.stringify({patch:D,startLine:K+1,matchLine:Q+1})}
|
|
231
231
|
<<</DIFF>>>
|
|
232
232
|
`}function yZ($){return $.replace(/\\+(n|t|r|'|"|`|\\|\n)/g,(Z,J)=>{switch(J){case"n":return`
|
|
233
233
|
`;case"t":return"\t";case"r":return"\r";case"'":return"'";case'"':return'"';case"`":return"`";case"\\":return"\\";case`
|
|
@@ -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 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
|
|
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 P=C;if(P.code==="ENOENT"||P.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 P=await C.checkExternalModification(J,Q);if(P.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
|
-
Details: ${
|
|
259
|
-
`),
|
|
260
|
-
`),error:{type:"validation_error",message:"old_string is not unique",details:{matches:p.map((
|
|
261
|
-
${
|
|
258
|
+
Details: ${P.message}`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:P.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
|
+
`),P=0,p=[];for(let i=0;i<C.length;i++){let U0=C[i],$$=P,b0=P+U0.length;for(let Z$ of E)if(Z$>=$$&&Z$<b0){let r=Math.max(0,i-1),J$=Math.min(C.length-1,i+1),v0=C.slice(r,J$+1).map((n2)=>n2.trim()).join(" ").slice(0,80);p.push({line:i+1,column:Z$-$$+1,context:v0})}P=b0+1}return{success:!1,llmContent:[`[WARN] EDIT PAUSED: old_string matches ${E.length} locations (must be unique).`,"","**Matches found at:**",...p.map((i,U0)=>` ${U0+1}. Line ${i.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((i)=>({line:i.line,column:i.column})),count:E.length}}}}else H?.(`找到 ${E.length} 个匹配项,开始替换...`);let q,D;if(X)q=K.split(O).join(U),D=E.length;else{let C=K.indexOf(O);q=K.substring(0,C)+U+K.substring(C+O.length),D=1}if(typeof z.throwIfAborted==="function")z.throwIfAborted();let F,L,A=!1;if(!V&&Q&&W)try{F=new n0({sessionId:Q,workspaceRoot:Z.workspaceRoot}),await F.initialize(),L=await F.createSnapshot(J,W)}catch(C){console.warn("[EditTool] 创建快照失败:",C),F=void 0,L=void 0}if(V)H?.("通过 IDE 写入文件...");try{await B.writeTextFile(J,q)}catch(C){if(F&&L)await F.discardSnapshot(J,L).catch((P)=>console.warn("[EditTool] 丢弃未完成快照失败:",P));throw C}if(F&&L)try{await F.recordPostEditState(J,L),A=!0}catch(C){console.warn("[EditTool] 完成快照失败:",C),await F.discardSnapshot(J,L).catch((P)=>console.warn("[EditTool] 丢弃未完成快照失败:",P))}if(Q)await V0.getInstance().recordFileEdit(J,Q,"edit");let w=await B.stat(J),b=IZ(K,q,O,U,4),T=uJ(J),S=D===1?`替换 1 处匹配到 ${T}`:`替换 ${D} 处匹配到 ${T}`,M={file_path:J,matches_found:E.length,replacements_made:D,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:b,summary:S,kind:"edit",oldContent:K,newContent:q};return{success:!0,llmContent:b?`Edited ${J} (${D} replacement${D>1?"s":""}):
|
|
261
|
+
${b}`:`Edited ${J} (${D} replacement${D>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
|
|
|
@@ -293,11 +293,11 @@ Common issues:
|
|
|
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
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,
|
|
297
|
-
`),q.lines_read=
|
|
296
|
+
`),w=Y||0,b=U!==void 0?w+U:A.length,T=A.slice(w,b);E=T.map((S,M)=>{let C=w+M+1,P=S.length>2000?`${S.substring(0,2000)}...`:S;return`${C.toString().padStart(6)}|${P}`}).join(`
|
|
297
|
+
`),q.lines_read=T.length,q.total_lines=A.length,q.start_line=w+1,q.end_line=Math.min(b,A.length)}let D=lJ(J),F=q.lines_read||q.total_lines,L=F?`读取 ${F} 行从 ${D}`:`读取 ${D}`;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 b=sJ(J);try{await B.mkdir(b,{recursive:!0,mode:493})}catch(T){if(T.code!=="EEXIST")throw T}}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(b){console.warn("[WriteTool] 读取旧文件内容失败:",b)}}catch{}if(K&&Q){let b=V0.getInstance();if(!b.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 T=await b.checkExternalModification(J,Q);if(T.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: ${
|
|
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:
|
|
299
|
+
Details: ${T.message}`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:T.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(b){console.warn("[WriteTool] 创建快照失败:",b),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 b;if(U==="base64")b=Buffer.from(Y,"base64");else if(U==="binary")b=Buffer.from(Y,"binary");else b=Buffer.from(Y,"utf8");await aJ.writeFile(J,b)}}catch(b){if(E&&q)await E.discardSnapshot(J,q).catch((T)=>console.warn("[WriteTool] 丢弃未完成快照失败:",T));throw b}if(E&&q)try{await E.recordPostEditState(J,q),O=!0}catch(b){console.warn("[WriteTool] 完成快照失败:",b),await E.discardSnapshot(J,q).catch((T)=>console.warn("[WriteTool] 丢弃未完成快照失败:",T))}if(Q)await V0.getInstance().recordFileEdit(J,Q,"write");if(typeof z.throwIfAborted==="function")z.throwIfAborted();let D=await B.stat(J),F=U==="utf8"?Y.split(`
|
|
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:D?.size,encoding:U,created_directories:X,snapshot_created:O,session_id:Q,message_id:W,last_modified:D?.mtime instanceof Date?D.mtime.toISOString():void 0,has_diff:!!A,summary:U==="utf8"?`写入 ${F} 行到 ${L}`:`写入 ${D?.size?eJ(D.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)}
|
|
303
303
|
Status: ${$.status}
|
|
@@ -458,16 +458,16 @@ Before using this tool, ensure your plan is clear and unambiguous. If there are
|
|
|
458
458
|
`+(Y.feedback||"No specific feedback provided.")+`
|
|
459
459
|
|
|
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
|
-
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
|
|
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=[...
|
|
463
|
-
`);for(let G of K){let O=G.trim();if(!O||O.startsWith("#"))continue;let E=O.startsWith("!"),
|
|
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 v$=["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
|
+
`)){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=[...v$.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("!"),D=(E?O.slice(1):O).trim();if(!D)continue;let F="";if(D.startsWith("/")){let L=D.slice(1).replace(/\\/g,"/");if(F=(V?V+"/":"")+L,H.push({type:E?"negate":"ignore",pattern:F}),D.endsWith("/")){let A=F+"**";H.push({type:E?"negate":"ignore",pattern:A});let w=F.replace(/\/$/,"");if(w!==F)H.push({type:E?"negate":"ignore",pattern:w})}}else{let L=D.replace(/\\/g,"/");if(L.includes("/")){if(F=(V?V+"/":"")+L,H.push({type:E?"negate":"ignore",pattern:F}),L.endsWith("/")){let A=F+"**";H.push({type:E?"negate":"ignore",pattern:A});let w=F.replace(/\/$/,"");if(w!==F)H.push({type:E?"negate":"ignore",pattern:w})}}else F=(V?V+"/**/":"**/")+L,H.push({type:E?"negate":"ignore",pattern:F})}}}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=[...v$.map((W)=>`${W}/**`),...v$,...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(D){if(D.code==="ENOENT")return{success:!1,llmContent:`Search path does not exist: ${V}`,metadata:{summary:"搜索失败: 搜索路径不存在"},error:{type:"execution_error",message:"搜索路径不存在"}};throw D}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
|
-
`+O.map((
|
|
465
|
+
`+O.map((F)=>`- ${F.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,"/"),
|
|
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
|
|
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,
|
|
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,"/"),D=DY($,q);if(Y.shouldIgnore(q))return;let F=E.stats?E.stats.isDirectory():!1;if(F&&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:D,relative_path:q,is_directory:F,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 v$)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 v$)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 v$)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,D=Y??Z.workspaceRoot??N();try{E?.(`使用智能搜索策略查找模式 "${J}"...`);let F=null,L="ripgrep",A=[],w=sZ();if(w)try{E?.(`使用 ripgrep (${w})`);let S=xY({pattern:J,path:D,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});F=await SY(S,H,q,E),L="ripgrep"}catch{E?.("[WARN] ripgrep 失败,尝试降级策略..."),F=null}if(!F&&await fY(D))try{E?.("使用 git grep"),F=await PY(J,D,{caseInsensitive:Q??!1,glob:U,contextLines:B},q),L="git-grep"}catch{E?.("[WARN] git grep 失败,继续尝试其他策略..."),F=null}if(!F&&RY())try{E?.("使用系统 grep"),F=await kY(J,D,{caseInsensitive:Q??!1,contextLines:B},q),L="system-grep"}catch{E?.("[WARN] 系统 grep 失败,使用纯 JavaScript 实现..."),F=null}if(!F)E?.("使用纯 JavaScript 搜索实现"),A=(await vY(J,D,{caseInsensitive:Q??!1,glob:U,multiline:O??!1},q)).matches,L="fallback",F={stdout:"",stderr:"",exitCode:0};else A=hY(F.stdout,H);let b=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 T={search_pattern:J,search_path:D,output_mode:H,case_insensitive:Q??!1,total_matches:A.length,original_total:b,offset:G,head_limit:K,strategy:L,exit_code:F?.exitCode};if(F&&F.exitCode!==0&&F.stderr)return{success:!1,llmContent:`Search execution failed: ${F.stderr}`,metadata:{...T,summary:`搜索失败: ${F.stderr}`},error:{type:"execution_error",message:F.stderr}};return{success:!0,llmContent:A,metadata:{...T,summary:A.length>0?`搜索 "${J}" 找到 ${A.length} 个文件`:`搜索 "${J}" 未找到匹配`}}}catch(F){let L=F;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
|
|
|
@@ -483,11 +483,11 @@ Before executing commands:
|
|
|
483
483
|
* cd "/Users/name/My Documents" (correct)
|
|
484
484
|
* cd /Users/name/My Documents (incorrect - will fail)
|
|
485
485
|
* python "/path/with spaces/script.py" (correct)
|
|
486
|
-
* python /path/with spaces/script.py (incorrect - will fail)`,usageNotes:["The command argument is required","You can specify an optional timeout in milliseconds (up to 600000ms / 10 minutes). If not specified, commands will timeout after 30000ms (30 seconds)","It is very helpful if you write a clear, concise description of what this command does in 5-10 words","If the output exceeds 30000 characters, output will be truncated before being returned to you",'You can use the run_in_background parameter to run the command in the background, which allows you to continue working while the command runs. You can monitor the output using the TaskOutput tool. You do not need to use "&" at the end of the command when using this parameter',"Background commands accept input through WriteStdin. Include a newline for line-oriented programs, and set close_stdin=true when the process must receive EOF before it can finish","Avoid using Bash with the find, grep, cat, head, tail, sed, awk, or echo commands, unless explicitly instructed or when these commands are truly necessary for the task. Instead, always prefer using the dedicated tools for these commands:"," - File search: Use Glob (NOT find or ls)"," - Content search: Use Grep (NOT grep or rg)"," - Read files: Use Read (NOT cat/head/tail)"," - Edit files: Use Edit (NOT sed/awk)"," - Write files: Use Write (NOT echo >/cat <<EOF)"," - Communication: Output text directly (NOT echo/printf)","When issuing multiple commands:",' - If the commands are independent and can run in parallel, make multiple Bash tool calls in a single message. For example, if you need to run "git status" and "git diff", send a single message with two Bash tool calls in parallel',' - If the commands depend on each other and must run sequentially, use a single Bash call with "&&" to chain them together (e.g., git add . && git commit -m "message" && git push). For instance, if one operation must complete before another starts (like mkdir before cp, Write before Bash for git operations, or git add before git commit), run these operations sequentially instead',` - Use ";" only when you need to run commands sequentially but don't care if earlier commands fail`," - DO NOT use newlines to separate commands (newlines are ok in quoted strings)","Try to maintain your current working directory throughout the session by using absolute paths and avoiding usage of cd. You may use cd if the User explicitly requests it"," Good example: pytest /foo/bar/tests"," Bad example: cd /foo/bar && pytest tests"],examples:[{description:"Run a simple command",params:{command:"ls -la",description:"List files in current directory"}},{description:"Temporarily change working directory (this command only)",params:{command:"npm install",cwd:"/path/to/project",description:"Install package dependencies"}},{description:"Persistently change working directory",params:{command:"cd /path/to/project && npm install",description:"Change directory and install dependencies"}},{description:"Run a long-running command in background",params:{command:"npm run dev",run_in_background:!0,description:"Start development server in background"}},{description:"Run multiple independent commands in parallel",params:{command:"git status",description:"Show working tree status"}}],important:["Committing changes with git:"," - Only create commits when requested by the user. If unclear, ask first"," - Git Safety Protocol:"," * NEVER update the git config"," * NEVER run destructive/irreversible git commands (like push --force, hard reset, etc) unless the user explicitly requests them"," * NEVER skip hooks (--no-verify, --no-gpg-sign, etc) unless the user explicitly requests it"," * NEVER run force push to main/master, warn the user if they request it"," * Avoid git commit --amend. ONLY use --amend when either (1) user explicitly requested amend OR (2) adding edits from pre-commit hook",' * Before amending: ALWAYS check authorship (git log -1 --format="%an %ae")'," * NEVER commit changes unless the user explicitly asks you to"," - When creating commits:"," 1. Run git status, git diff, and git log in parallel to understand changes",' 2. Analyze staged changes and draft a concise commit message (1-2 sentences) focusing on "why" rather than "what"'," 3. Add relevant untracked files, create the commit, and run git status to verify"," 4. Always pass commit message via HEREDOC format"," - DO NOT push to remote repository unless explicitly requested"," - NEVER use git commands with the -i flag (no interactive input supported)"," - If no changes to commit, do not create an empty commit","Creating pull requests:"," - Use the gh command for ALL GitHub-related tasks"," - When creating a PR:"," 1. Run git status, git diff, and git log in parallel to understand branch changes"," 2. Analyze all commits (not just the latest) and draft a PR summary"," 3. Create new branch if needed, push with -u flag, and create PR using gh pr create with HEREDOC body format"," - Return the PR URL when done","Other important notes:"," - Dangerous commands (rm -rf, sudo, etc.) require user confirmation"," - Background commands require manual termination using KillShell"," - NEVER use find, grep, cat, sed, etc. — use dedicated tools instead"]},async execute($,Z){let{command:J,timeout:Y=30000,cwd:U,env:X,run_in_background:H=!1}=$,{updateOutput:Q}=Z,W=Z.subagentType==="verification"?{}:{...Z.environment,...X},z=Z.signal??new AbortController().signal,V=Z.workspaceRoot??N(),B=U===void 0?V:dY(U)?U:mY(V,U);try{Q?.(`Executing Bash command: ${J}`);let K=a(Z.sessionId),G=Z.subagentType==="verification"&&!K?await s2.prepare({command:J,cwd:B,workspaceRoot:V,access:"workspace-read-only",signal:z}):Z.worktreeActive?await s2.prepare({command:J,cwd:B,workspaceRoot:V,access:"workspace-write",signal:z}):void 0;if(H)return gY(J,B,W,Z.sessionId,G);if(K&&!G)return Q?.("通过 IDE 终端执行命令..."),pY(J,B,W,Y,z,Z.sessionId,Q);else return cY(J,B,W,Y,z,Q,G)}catch(K){let G=K;if(G.name==="AbortError")return{success:!1,llmContent:"Command execution aborted",error:{type:"execution_error",message:"Operation aborted"}};if(K instanceof
|
|
486
|
+
* python /path/with spaces/script.py (incorrect - will fail)`,usageNotes:["The command argument is required","You can specify an optional timeout in milliseconds (up to 600000ms / 10 minutes). If not specified, commands will timeout after 30000ms (30 seconds)","It is very helpful if you write a clear, concise description of what this command does in 5-10 words","If the output exceeds 30000 characters, output will be truncated before being returned to you",'You can use the run_in_background parameter to run the command in the background, which allows you to continue working while the command runs. You can monitor the output using the TaskOutput tool. You do not need to use "&" at the end of the command when using this parameter',"Background commands accept input through WriteStdin. Include a newline for line-oriented programs, and set close_stdin=true when the process must receive EOF before it can finish","Avoid using Bash with the find, grep, cat, head, tail, sed, awk, or echo commands, unless explicitly instructed or when these commands are truly necessary for the task. Instead, always prefer using the dedicated tools for these commands:"," - File search: Use Glob (NOT find or ls)"," - Content search: Use Grep (NOT grep or rg)"," - Read files: Use Read (NOT cat/head/tail)"," - Edit files: Use Edit (NOT sed/awk)"," - Write files: Use Write (NOT echo >/cat <<EOF)"," - Communication: Output text directly (NOT echo/printf)","When issuing multiple commands:",' - If the commands are independent and can run in parallel, make multiple Bash tool calls in a single message. For example, if you need to run "git status" and "git diff", send a single message with two Bash tool calls in parallel',' - If the commands depend on each other and must run sequentially, use a single Bash call with "&&" to chain them together (e.g., git add . && git commit -m "message" && git push). For instance, if one operation must complete before another starts (like mkdir before cp, Write before Bash for git operations, or git add before git commit), run these operations sequentially instead',` - Use ";" only when you need to run commands sequentially but don't care if earlier commands fail`," - DO NOT use newlines to separate commands (newlines are ok in quoted strings)","Try to maintain your current working directory throughout the session by using absolute paths and avoiding usage of cd. You may use cd if the User explicitly requests it"," Good example: pytest /foo/bar/tests"," Bad example: cd /foo/bar && pytest tests"],examples:[{description:"Run a simple command",params:{command:"ls -la",description:"List files in current directory"}},{description:"Temporarily change working directory (this command only)",params:{command:"npm install",cwd:"/path/to/project",description:"Install package dependencies"}},{description:"Persistently change working directory",params:{command:"cd /path/to/project && npm install",description:"Change directory and install dependencies"}},{description:"Run a long-running command in background",params:{command:"npm run dev",run_in_background:!0,description:"Start development server in background"}},{description:"Run multiple independent commands in parallel",params:{command:"git status",description:"Show working tree status"}}],important:["Committing changes with git:"," - Only create commits when requested by the user. If unclear, ask first"," - Git Safety Protocol:"," * NEVER update the git config"," * NEVER run destructive/irreversible git commands (like push --force, hard reset, etc) unless the user explicitly requests them"," * NEVER skip hooks (--no-verify, --no-gpg-sign, etc) unless the user explicitly requests it"," * NEVER run force push to main/master, warn the user if they request it"," * Avoid git commit --amend. ONLY use --amend when either (1) user explicitly requested amend OR (2) adding edits from pre-commit hook",' * Before amending: ALWAYS check authorship (git log -1 --format="%an %ae")'," * NEVER commit changes unless the user explicitly asks you to"," - When creating commits:"," 1. Run git status, git diff, and git log in parallel to understand changes",' 2. Analyze staged changes and draft a concise commit message (1-2 sentences) focusing on "why" rather than "what"'," 3. Add relevant untracked files, create the commit, and run git status to verify"," 4. Always pass commit message via HEREDOC format"," - DO NOT push to remote repository unless explicitly requested"," - NEVER use git commands with the -i flag (no interactive input supported)"," - If no changes to commit, do not create an empty commit","Creating pull requests:"," - Use the gh command for ALL GitHub-related tasks"," - When creating a PR:"," 1. Run git status, git diff, and git log in parallel to understand branch changes"," 2. Analyze all commits (not just the latest) and draft a PR summary"," 3. Create new branch if needed, push with -u flag, and create PR using gh pr create with HEREDOC body format"," - Return the PR URL when done","Other important notes:"," - Dangerous commands (rm -rf, sudo, etc.) require user confirmation"," - Background commands require manual termination using KillShell"," - NEVER use find, grep, cat, sed, etc. — use dedicated tools instead"]},async execute($,Z){let{command:J,timeout:Y=30000,cwd:U,env:X,run_in_background:H=!1}=$,{updateOutput:Q}=Z,W=Z.subagentType==="verification"?{}:{...Z.environment,...X},z=Z.signal??new AbortController().signal,V=Z.workspaceRoot??N(),B=U===void 0?V:dY(U)?U:mY(V,U);try{Q?.(`Executing Bash command: ${J}`);let K=a(Z.sessionId),G=Z.subagentType==="verification"&&!K?await s2.prepare({command:J,cwd:B,workspaceRoot:V,access:"workspace-read-only",signal:z}):Z.worktreeActive?await s2.prepare({command:J,cwd:B,workspaceRoot:V,access:"workspace-write",signal:z}):void 0;if(H)return gY(J,B,W,Z.sessionId,G);if(K&&!G)return Q?.("通过 IDE 终端执行命令..."),pY(J,B,W,Y,z,Z.sessionId,Q);else return cY(J,B,W,Y,z,Q,G)}catch(K){let G=K;if(G.name==="AbortError")return{success:!1,llmContent:"Command execution aborted",error:{type:"execution_error",message:"Operation aborted"}};if(K instanceof f$||K instanceof n$)return{success:!1,llmContent:`Workspace sandbox blocked Bash execution: ${G.message}. The command was not started.`,error:{type:"permission_denied",message:G.message},metadata:{command:J,sandbox_required:!0,sandboxed:!1,summary:"Workspace sandbox unavailable; command not started"}};return{success:!1,llmContent:`Command execution failed: ${G.message}`,error:{type:"execution_error",message:G.message,details:G}}}},version:"2.0.0",category:"命令工具",tags:["bash","shell","non-interactive","event-driven"],extractSignatureContent:($)=>{return $.command.trim()},abstractPermissionRule:($)=>{let J=U2(D1($.command.trim())).split(/\s+/);if(J.length===1)return J[0];if(["run","exec","test","start","build","dev"].includes(J[1])){if(J.length===2)return`${J[0]} ${J[1]}`;return`${J[0]} ${J[1]} *`}if(J.length===2)return`${J[0]} ${J[1]}`;return`${J[0]} ${J[1]} *`}});function gY($,Z,J,Y,U){if(!Y)return U?.cleanup(),{success:!1,llmContent:"Background Bash requires an active session",error:{type:"validation_error",message:"后台命令缺少 session 上下文"},metadata:{summary:"后台命令启动失败: 缺少 session"}};let H=s.getInstance().startBackgroundProcess({command:$,sessionId:Y,cwd:Z||N(),env:J,sandboxedCommand:U}),W=`后台启动命令: ${$.length>30?`${$.substring(0,30)}...`:$}`,z={command:$,background:!0,pid:H.pid??0,bash_id:H.id,shell_id:H.id,message:"命令已在后台启动",sandboxed:Boolean(U),summary:W};return{success:!0,llmContent:{command:$,background:!0,pid:H.pid,bash_id:H.id,shell_id:H.id},metadata:z}}function eZ($,Z,J,Y){let U=$===null?`Command terminated${Z?` by signal ${Z}`:""}`:`Command exited with code ${$}`,X=[Y?`stderr:
|
|
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
|
|
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"]}),D,F=()=>{return D??=q.terminate(),D};E.stdout?.on("data",(w)=>{z+=w.toString()}),E.stderr?.on("data",(w)=>{V+=w.toString()});let L=setTimeout(()=>{B=!0,F()},Y),A=()=>{F(),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,b)=>{if(H?.cleanup(),clearTimeout(L),U.removeEventListener)U.removeEventListener("abort",A);else if("onabort"in U)U.onabort=null;let T=Date.now()-W;if(B||U.aborted)await F();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:T}});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:T}});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:T,exit_code:w,stderr:V,summary:"Workspace sandbox failed closed"}});return}let S=$.length>30?`${$.substring(0,30)}...`:$,M=w===0?`执行命令成功 (${T}ms): ${S}`:`执行命令完成 (退出码 ${w}, ${T}ms): ${S}`,C={command:$,execution_time:T,exit_code:w,signal:b,stdout_length:z.length,stderr_length:V.length,has_stderr:V.length>0,sandboxed:Boolean(H),summary:M},P=s$.truncateForLLM(z.trim(),V.trim(),$),p={stdout:P.stdout,stderr:P.stderr,execution_time:T,exit_code:w,signal:b,...P.truncationInfo&&{truncation_info:P.truncationInfo}},m=w===0;Q({success:m,llmContent:p,...m?{}:{error:{type:"execution_error",message:eZ(w,b,P.stdout,P.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
|
|
@@ -590,8 +590,8 @@ ${Z}
|
|
|
590
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
|
-
</functions>`,metadata:{summary:`加载了 ${X.length} 个工具 schema`}}}});import e8 from"node:path";import{nanoid as aU}from"nanoid";import
|
|
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:
|
|
593
|
+
</functions>`,metadata:{summary:`加载了 ${X.length} 个工具 schema`}}}});import e8 from"node:path";import{nanoid as aU}from"nanoid";import D$ from"node:fs";import y$ 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=F$($),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&&!F$($)?`/${$}`:$},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=F$(U)}if(Z=e5(Z,!J),J&&!F$(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 F$=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(I$($.sessionId),!y$.isAbsolute($.projectPath))throw Error("Subagent owner projectPath must be absolute");return{sessionId:$.sessionId,projectPath:y$.resolve($.projectPath)}}function Y6($,Z){let J=J6(Z);return $.parentSessionId===J.sessionId&&$.parentProjectPath!==void 0&&y$.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(!D$.existsSync(this.sessionsDir))D$.mkdirSync(this.sessionsDir,{recursive:!0,mode:448});else D$.chmodSync(this.sessionsDir,448)}getSessionPath($){return I$($),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(!D$.existsSync(Z))return;let J=D$.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(I$(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)I$(J.parentSessionId);if(J.resumedFrom!==void 0)I$(J.resumedFrom);let Y=typeof J.rootAgentId==="string"?J.rootAgentId:Z;I$(Y);let U=typeof J.workspaceRoot==="string"&&y$.isAbsolute(J.workspaceRoot)?y$.resolve(J.workspaceRoot):void 0,X=typeof J.parentProjectPath==="string"&&y$.isAbsolute(J.parentProjectPath)?y$.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(D$.existsSync(Z))D$.unlinkSync(Z);return this.cache.delete($),!0}catch(Z){return w1.warn(`Failed to delete session ${$}:`,Z),!1}}listSessions(){try{let $=D$.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 x${config;constructor($){this.config=$}check($){let Z=x$.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 x$($)}getPermissionChecker(){return this.permissionChecker}resolveRulePermission($,Z,J,Y){let U=Z.getAffectedPaths(),X={toolName:$.name,params:J,affectedPaths:U,tool:$},H=x$.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(),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=
|
|
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=x$.abstractPattern(X);if(!H)throw Error(`Tool "${$.name}" does not support project permission rules`);if(Y==="allow")await h$().appendLocalPermissionRule(H,{immediate:!0,projectDir:U});else await h$().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
|
\`\`\`
|
|
@@ -634,25 +634,25 @@ ${U}
|
|
|
634
634
|
|
|
635
635
|
---
|
|
636
636
|
**Hook Context:**
|
|
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,
|
|
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,D=!X.isConcurrencySafe&&q?()=>f0.getInstance().acquireLock(String(q),E):E,F=await this.scheduler.schedule(X.kind,D);if(J.signal?.aborted)return r0(!O);if(await q8(X,Q,F,J,B.toolUseId),J.signal?.aborted)return r0(!1);if(await this.lspManager?.afterToolUse(X.name,Q,F,J),J.signal?.aborted)return r0(!1);if(await this.autoVerifyRuntime?.verify(X.name,Q,J,F),J.signal?.aborted)return r0(!1);return D8(F,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
|
-
`)}reset(){this.loadedTools=new Set(V2),this.deferredTools.clear()}}class
|
|
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 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(`没有可用的模型配置
|
|
640
|
+
`)}reset(){this.loadedTools=new Set(V2),this.deferredTools.clear()}}class w$ 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 w$;$.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
|
+
[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 u${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 u$({maxTokens:1000,maxMessages:10,timeWindow:7200000,includeTools:!1,includeWorkspace:!1}),standard:new u$({maxTokens:4000,maxMessages:30,timeWindow:43200000,includeTools:!0,includeWorkspace:!0}),comprehensive:new u$({maxTokens:8000,maxMessages:100,timeWindow:86400000,includeTools:!0,includeWorkspace:!0}),debug:new u$({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 d${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=d$.instances.get(J);if(!Y)Y=new d$($,Z),d$.instances.set(J,Y);return Y}static release($,Z){d$.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 d$.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?m$(Y):null}catch{return null}}async loadSession($){try{let Z=S0(this.projectPath,$),J=new a0(Z),Y=m$(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=m$(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=m$(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 u$(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 w$,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):A$();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("配置未初始化,请确保应用已正确启动");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,
|
|
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,D;if(this.sessionRuntime)if(O)D=this.sessionRuntime.beginTurn();else if(G)D=await this.sessionRuntime.beginPendingTurn();else{let w=X;if(D=w.handle,w.mode==="pending")G=!0,B="";else q=w.messageId}let F=0;if(G&&this.sessionRuntime&&!D)return{success:!0,finalMessage:"",metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let L=()=>this.sessionRuntime.getPendingSteeringMessages().map((w)=>({...w,persisted:K.messages.some((b)=>{let T=b.metadata;return T!==null&&typeof T==="object"&&!Array.isArray(T)&&T.inboxMessageId===w.id})})),A=async(w)=>Promise.all(w.map(async(b)=>({...b,content:await this.processAtMentionsForContent(b.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=D,b={...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},T;if(K.permissionMode==="plan")T=yield*this.runPlanLoop(B,K,b);else T=yield*this.runLoop(B,K,b);if(T.success&&T.metadata?.targetMode&&K.permissionMode==="plan"){let C=T.metadata.targetMode,P=T.metadata.planContent;if(y.debug(`Plan 模式已批准,切换到 ${C} 模式并重新执行`),this.sessionRuntime&&K.sessionId)await c.setSessionPermissionMode(K.sessionId,this.sessionRuntime.workspaceRoot,C);await K.onPermissionModeChange?.(C),K={...K,permissionMode:C};let p=B;if(P){let m=`
|
|
649
649
|
|
|
650
650
|
<approved-plan>
|
|
651
|
-
${
|
|
651
|
+
${P}
|
|
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}]}
|
|
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}]}T=yield*this.runLoop(p,K,{...b,inputMessageId:void 0})}if(!this.sessionRuntime||!w)return T;if(T.success&&!K.signal?.aborted)await this.sessionRuntime.acknowledgeTurn(w);let S=await this.sessionRuntime.recordGoalProgress({tokens:T.metadata?.tokensUsed??0,elapsedMs:T.metadata?.duration??0});if(S)yield{kind:"goal_updated",goal:S};if(!T.success||K.signal?.aborted){if(S=await this.sessionRuntime.pauseActiveGoal(K.signal?.aborted?"goal paused after user cancellation":T.error?.message??"goal paused after turn failure"),S)yield{kind:"goal_updated",goal:S}}let M=T.success&&!K.signal?.aborted&&F<20;if(D=await this.sessionRuntime.finishTurn(w,{continuePending:M}),D){F++,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(!T.success||K.signal?.aborted)return T;if(S=await this.sessionRuntime.getGoal(),!S||S.status!=="active")return T;if(E=await this.sessionRuntime.beginGoalContinuation(),!E)return T;D=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&&D)await this.sessionRuntime.finishTurn(D)}}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-7jy60gnx.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){y.debug("Processing Plan mode message...");let{prompt:Y}=await P$({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 P$({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 P$({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,16 +675,16 @@ 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 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(!$||
|
|
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(!$||F$($)||$.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)=>{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("../")||
|
|
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
|
|
683
|
-
`):G.stdout,E=/^Binary files .+ differ$/m.test(O)||O.includes("GIT binary patch"),q=E?{additions:0,deletions:0}:pU(O),
|
|
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("../")||F$(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 D=await k(U,["worktree","add","-b",O,q,B]);Q0(D,"Create worktree");let F={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,F),F})}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
|
+
`).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(),D,F;try{[D,F]=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(D!==F||!/^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 F=await A6(B0($.worktreeRoot,B));if(F.size>d8)return{path:B,patch:"",additions:0,deletions:0,binary:!1,truncated:!0};if(K&&!F.isFile())return{path:B,patch:"",additions:0,deletions:0,binary:!0,truncated:!1}}catch(F){if(F.code!=="ENOENT")throw F}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
|
+
`):G.stdout,E=/^Binary files .+ differ$/m.test(O)||O.includes("GIT binary patch"),q=E?{additions:0,deletions:0}:pU(O),D=c8(O,d8);return{path:B,patch:D.patch,...q,binary:E,truncated:D.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: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
|
-
`)}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=
|
|
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:D,resumedFrom:F,resumeDepth:L=0,agentResources:A,modelResources:w,lspResources:b,onEvent:T,onCompleted:S}=$,M=B||z$("agent");if(this.runningAgents.has(M)||this.sessionStore.loadSession(M))throw Error(`Subagent session already exists: ${M}`);let C=new AbortController,P={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:D??M,resumedFrom:F,resumeDepth:L,configSnapshot:Q2(Z),taskListId:G,workspaceRoot:O,isolation:E,worktree:q};this.sessionStore.saveSession(P);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,b,T,S);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,D,F,L){let A=Date.now(),w,b,T,S=!1,M=async(C)=>{if(!T||S)return;let P=await J1.finalize({agentId:$,lease:T,success:C});return S=!0,this.sessionStore.updateSession($,{worktree:P.worktree}),P};try{if(z.aborted)throw Error("Agent execution was cancelled");T=await J1.prepare({agentId:$,sourceWorkspaceRoot:K,isolation:G,restoredWorktree:O}),this.sessionStore.updateSession($,{worktree:T.worktree});let C=Z.systemPrompt?.trim(),P=Z.model&&Z.model!=="inherit"?Z.model:void 0,p=Z.permissionMode??U,m=this.sessionStore.loadSession($);w=await L$.create({sessionId:$,workspaceRoot:T.workspaceRoot,modelId:P,reasoningEffort:X,serviceTier:H,responseVerbosity:Q,communicationStyle:W,agentResources:E,modelResources:q,lspResources:D,...(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}),b=await O0.createWithRuntime(w,{sessionId:$,toolWhitelist:Z.tools,toolBlacklist:["EnterWorktree","ExitWorktree",...Z.disallowedTools??[]],modelId:P,maxTurns:Z.maxTurns,permissionMode:p,...C?{appendSystemPrompt:C}:{}});let i={messages:V||[],userId:"subagent",sessionId:$,taskListId:B,workspaceRoot:T.workspaceRoot,worktreeActive:Boolean(T.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(b.chatStream(J,i,{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 F?.(v0,$)}catch(n2){A0.warn(`Subagent event observer failed: ${$}`,n2)}});this.sessionStore.updateSession($,{messages:i.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 P=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 i=this.sessionStore.markCompleted($,{success:!1,message:"",error:p},{duration:P});if(i)try{await L?.(i)}catch(U0){A0.warn(`Subagent completion observer failed: ${$}`,U0)}return A0.warn(`Background agent failed: ${$}`,C),{success:!1,message:"",agentId:$,error:p,stats:{duration:P},worktreePath:m?.worktreePath,worktreeBranch:m?.worktreeBranch,worktree:m?.worktree}}finally{try{if(b&&typeof b.destroy==="function")await b.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 D=q.configSnapshot?{...q.configSnapshot}:Y;return{agentId:this.startBackgroundAgent({config:D,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 L$.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(F)=>{if(F.kind==="tool_result"&&"function"in F.toolCall)F2(O,F.toolCall.function.name,F.result),D2(G,F.toolCall.function.name,F.result);await $.onEvent?.(F)},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 D=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:D}}}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 N$}from"node:path";function N6($,Z){switch($){case"Write":{let J=Z.file_path;return`Writing ${J?N$(J):"file"}`}case"Edit":{let J=Z.file_path;return`Editing ${J?N$(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?N$(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=N$(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?N$(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?N$(Y):"file";return`LSP ${J} in ${U}`}case"NotebookEdit":{let J=Z.notebook_path;return`Editing notebook: ${J?N$(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
|
+
`)}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=N$(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(`
|
|
690
690
|
`)}
|
|
@@ -740,12 +740,12 @@ 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($=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?`
|
|
743
|
+
`.trim()}function L2($=T$(),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:D}=W,F=q??E,L=$X(z);if(!L)return b$("Task requires an active parent session and absolute workspace","Subagent 缺少 durable parent session owner");let A=U?.(),w=X?.(),b=H?.(),T=Q?.(),S=o.getInstance(),M=F?S.getAgent(F,L):void 0;if(F&&!M)return b$(`Cannot resume agent ${F}: session not found in this workspace`,`恢复 Agent 失败: 会话不存在 ${F}`);if(M&&(S.isRunning(M.id)||M.status==="running"))return b$(`Cannot resume agent ${M.id}: it is still running`,`恢复 Agent 失败: 仍在运行 ${M.id}`);if(M&&V&&M.subagentType!==V)return b$(`Cannot resume with subagent_type "${V}": source agent used "${M.subagentType}"`,"恢复 Agent 失败: subagent 类型与源运行不一致");let C=M?.subagentType??V;if(!C)return b$("subagent_type is required for a fresh Task run","启动 Agent 失败: 缺少 subagent_type");let P=$.getSubagent(C),m=(M?.configSnapshot?{...M.configSnapshot}:void 0)??P;if(!m)return b$(`Unknown subagent type: ${C}. Available types: ${$.getAllNames().join(", ")||"none"}`,`未知的 subagent 类型: ${C}`);let i={...m,model:m.model&&m.model!=="inherit"?m.model:z.modelId??m.model,permissionMode:m.permissionMode??z.permissionMode},U0=typeof D==="string"&&D.length>0?D:z$("agent"),$$=M?.isolation??O??i.isolation??"none",b0=M?.rootAgentId??U0,Z$=M?M.resumeDepth+1:0,r=ZX({owner:L,subagentSessionId:U0,type:i.name,description:B,resumedFrom:M?.id,rootAgentId:b0,resumeDepth:Z$});if(G){let J$=M?S.resumeAgent({agentId:M.id,prompt:K,config:i,owner:L,permissionMode:z.permissionMode,reasoningEffort:A,serviceTier:w,responseVerbosity:b,communicationStyle:T,newAgentId:U0,agentResources:Z,modelResources:J,lspResources:Y,onEvent:r.onEvent,onCompleted:r.onCompleted})?.agentId:S.startBackgroundAgent({config:i,description:B,prompt:K,parentSessionId:L.sessionId,parentProjectPath:L.projectPath,permissionMode:z.permissionMode,reasoningEffort:A,serviceTier:w,responseVerbosity:b,communicationStyle:T,agentId:U0,workspaceRoot:L.projectPath,isolation:$$,agentResources:Z,modelResources:J,lspResources:Y,onEvent:r.onEvent,onCompleted:r.onCompleted});if(!J$)return b$(`Failed to resume agent ${M?.id??U0}`,"恢复 Agent 失败");return r.onStarted(),YX({sessionId:J$,config:i,description:B,isolation:$$,resumedFrom:M?.id,rootAgentId:b0,resumeDepth:Z$})}return JX({config:i,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:b,communicationStyle:T})},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 b$($,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,D,F=!1,L=!1,A=async(w)=>{if(!D||F)return;let b=await J1.finalize({agentId:H,lease:D,success:w});return F=!0,b};try{D=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:D.worktree}),L=!0,z.onStarted(),U.updateOutput?.(`${W?"恢复":"启动"} ${Z.name} subagent: ${J}`);let b=new L6(Z,V,B,K),T={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:D.workspaceRoot,worktreeActive:Boolean(D.worktree),existingMessages:W?.messages,onEvent:z.onEvent},S=Date.now(),M=await b.execute(T);try{let p=await G0.getInstance().executeSubagentStopHooks(Z.name,{projectDir:D.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 b.execute({...T,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 P=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()-S});if(P)z.onCompleted(P);return UX({result:M,sessionId:H,config:Z,description:J,isolation:Q,resumedFrom:W?.id,rootAgentId:E,resumeDepth:q})}catch(w){let b=w,T;try{T=await A(!1)}catch(S){console.warn("[Task] Failed to preserve subagent worktree:",S)}if(L){let S=G.markCompleted(H,{success:!1,message:"",error:b.message});if(S)z.onCompleted(S)}return{...b$(`Subagent execution error: ${b.message}`,`Subagent 执行异常: ${$9(b)}`),metadata:{summary:`Subagent 执行异常: ${$9(b)}`,subagentSessionId:H,subagentType:Z.name,subagentStatus:"failed",subagentResumedFrom:W?.id,subagentRootId:E,subagentResumeDepth:q,isolation:Q,worktreePath:T?.worktreePath,worktreeBranch:T?.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
|
|
|
747
747
|
Agent ID: ${$.sessionId}
|
|
748
|
-
To continue this agent, call Task with resume_from="${$.sessionId}".`,Y={summary:`${$.config.name} 任务${$.result.success?"完成":"失败"}`,subagent_type:$.config.name,description:$.description,stats:$.result.stats,subagentSessionId:$.sessionId,subagentType:$.config.name,subagentStatus:$.result.success?"completed":"failed",subagentSummary:$.result.message.slice(0,500),subagentResumedFrom:$.resumedFrom,subagentRootId:$.rootAgentId,subagentResumeDepth:$.resumeDepth,resume_from_hint:$.sessionId,resumed_from:$.resumedFrom,verificationCommands:$.result.verificationCommands,verificationVerdict:$.result.verificationVerdict,modifiedFiles:$.result.modifiedFiles,verificationAgentBuiltin:$.config.name===A2&&$.config.source==="builtin",isolation:$.isolation,worktreePath:$.result.worktreePath,worktreeBranch:$.result.worktreeBranch};if($.result.success)return{success:!0,llmContent:`${$.result.message}${Z}${J}`,metadata:Y};return{success:!1,llmContent:`Subagent execution failed: ${$.result.error||"Unknown error"}.${Z}${J}`,error:{type:"execution_error",message:$.result.error||"Unknown error"},metadata:Y}}import*as Y1 from"fs/promises";import*as b2 from"path";var b6=d(["pending","in_progress","completed"]),XX=d(["high","medium","low"]),Y9=J9(_.Object({id:_.String(),subject:_.String(),description:_.String(),status:b6,activeForm:_.Optional(_.String()),owner:_.Optional(_.String()),priority:f(XX,"medium"),blocks:f(_.Array(_.String()),[]),blockedBy:f(_.Array(_.String()),[]),metadata:_.Optional(_.Record(_.String(),_.Unknown())),createdAt:_.String(),startedAt:_.Optional(_.String()),completedAt:_.Optional(_.String())}));class
|
|
748
|
+
To continue this agent, call Task with resume_from="${$.sessionId}".`,Y={summary:`${$.config.name} 任务${$.result.success?"完成":"失败"}`,subagent_type:$.config.name,description:$.description,stats:$.result.stats,subagentSessionId:$.sessionId,subagentType:$.config.name,subagentStatus:$.result.success?"completed":"failed",subagentSummary:$.result.message.slice(0,500),subagentResumedFrom:$.resumedFrom,subagentRootId:$.rootAgentId,subagentResumeDepth:$.resumeDepth,resume_from_hint:$.sessionId,resumed_from:$.resumedFrom,verificationCommands:$.result.verificationCommands,verificationVerdict:$.result.verificationVerdict,modifiedFiles:$.result.modifiedFiles,verificationAgentBuiltin:$.config.name===A2&&$.config.source==="builtin",isolation:$.isolation,worktreePath:$.result.worktreePath,worktreeBranch:$.result.worktreeBranch};if($.result.success)return{success:!0,llmContent:`${$.result.message}${Z}${J}`,metadata:Y};return{success:!1,llmContent:`Subagent execution failed: ${$.result.error||"Unknown error"}.${Z}${J}`,error:{type:"execution_error",message:$.result.error||"Unknown error"},metadata:Y}}import*as Y1 from"fs/promises";import*as b2 from"path";var b6=d(["pending","in_progress","completed"]),XX=d(["high","medium","low"]),Y9=J9(_.Object({id:_.String(),subject:_.String(),description:_.String(),status:b6,activeForm:_.Optional(_.String()),owner:_.Optional(_.String()),priority:f(XX,"medium"),blocks:f(_.Array(_.String()),[]),blockedBy:f(_.Array(_.String()),[]),metadata:_.Optional(_.Record(_.String(),_.Unknown())),createdAt:_.String(),startedAt:_.Optional(_.String()),completedAt:_.Optional(_.String())}));class g${static instances=new Map;tasks=[];nextId=1;loaded=!1;filePath;constructor($,Z){this.filePath=b2.join(Z,"tasks",`${$}-agent-${$}.json`)}static getInstance($,Z){let J=`${$}-${Z}`;if(!g$.instances.has(J))g$.instances.set(J,new g$($,Z));return g$.instances.get(J)}async createTask($){await this.ensureLoaded();let Z=new Date().toISOString(),J={id:String(this.nextId),subject:$.subject,description:$.description,activeForm:$.activeForm,owner:$.owner,priority:$.priority||"medium",status:"pending",blocks:[],blockedBy:[],metadata:$.metadata,createdAt:Z};return this.nextId+=1,this.tasks=[...this.tasks,J],await this.saveTasks(),J}async getTask($){return await this.ensureLoaded(),this.tasks.find((Z)=>Z.id===$)||null}async listTasks(){return await this.ensureLoaded(),this.getSortedTasks()}async updateTask($,Z){await this.ensureLoaded();let J=this.tasks.findIndex((Q)=>Q.id===$);if(J===-1)return{task:null,updatedFields:[]};let Y=this.tasks[J],U=[],X={...Y};if(Z.subject!==void 0&&Z.subject!==Y.subject)X.subject=Z.subject,U.push("subject");if(Z.description!==void 0&&Z.description!==Y.description)X.description=Z.description,U.push("description");if(Z.activeForm!==void 0&&Z.activeForm!==Y.activeForm)X.activeForm=Z.activeForm,U.push("activeForm");if(Z.owner!==void 0&&Z.owner!==Y.owner)X.owner=Z.owner,U.push("owner");if(Z.metadata!==void 0)X.metadata=QX(Y.metadata,Z.metadata),U.push("metadata");let H;if(Z.status!==void 0&&Z.status!==Y.status){if(X.status=Z.status,Z.status==="in_progress"&&!Y.startedAt)X.startedAt=new Date().toISOString();if(Z.status==="completed"&&!Y.completedAt)X.completedAt=new Date().toISOString();H={from:Y.status,to:Z.status},U.push("status")}if(Z.addBlocks&&Z.addBlocks.length>0){if(X.blocks=N2([...Y.blocks,...Z.addBlocks]),X.blocks.length!==Y.blocks.length)U.push("blocks")}if(Z.addBlockedBy&&Z.addBlockedBy.length>0){if(X.blockedBy=N2([...Y.blockedBy,...Z.addBlockedBy]),X.blockedBy.length!==Y.blockedBy.length)U.push("blockedBy")}return this.tasks=this.tasks.map((Q)=>Q.id===$?X:Q),await this.syncDependencyEdges(X,Z.addBlocks,Z.addBlockedBy),await this.saveTasks(),{task:X,updatedFields:U,statusChange:H}}async deleteTask($){await this.ensureLoaded();let Z=this.tasks.length;if(this.tasks=this.tasks.filter((J)=>J.id!==$).map((J)=>({...J,blocks:J.blocks.filter((Y)=>Y!==$),blockedBy:J.blockedBy.filter((Y)=>Y!==$)})),this.tasks.length===Z)return!1;return await this.saveTasks(),!0}getStats(){return{total:this.tasks.length,completed:this.tasks.filter(($)=>$.status==="completed").length,inProgress:this.tasks.filter(($)=>$.status==="in_progress").length,pending:this.tasks.filter(($)=>$.status==="pending").length}}getSortedTasks(){let $={in_progress:0,pending:1,completed:2},Z={high:0,medium:1,low:2};return[...this.tasks].sort((J,Y)=>{let U=$[J.status]-$[Y.status];if(U!==0)return U;let X=Z[J.priority]-Z[Y.priority];if(X!==0)return X;return Number(J.id)-Number(Y.id)})}async syncDependencyEdges($,Z,J){for(let Y of Z||[])this.tasks=this.tasks.map((U)=>U.id===Y?{...U,blockedBy:N2([...U.blockedBy,$.id])}:U);for(let Y of J||[])this.tasks=this.tasks.map((U)=>U.id===Y?{...U,blocks:N2([...U.blocks,$.id])}:U)}async ensureLoaded(){if(!this.loaded)await this.loadTasks(),this.loaded=!0}async loadTasks(){try{let $=JSON.parse(await Y1.readFile(this.filePath,"utf-8")),Z=HX($);this.tasks=Z.tasks,this.nextId=Z.nextId}catch($){if($.code!=="ENOENT")console.warn("加载任务列表失败:",$);this.tasks=[],this.nextId=1}}async saveTasks(){await Y1.mkdir(b2.dirname(this.filePath),{recursive:!0,mode:493});let $={nextId:this.nextId,tasks:this.tasks};await Y1.writeFile(this.filePath,JSON.stringify($,null,2),"utf-8")}}function HX($){let J=($&&typeof $==="object"&&Array.isArray($.tasks)?$.tasks:Array.isArray($)?$:[]).map((X)=>m1(Y9,X)).filter((X)=>X.success).map((X)=>X.data),Y=$&&typeof $==="object"&&typeof $.nextId==="number"?$.nextId:void 0,U=J.reduce((X,H)=>{let Q=Number(H.id);return Number.isFinite(Q)?Math.max(X,Q):X},0);return{tasks:J,nextId:Math.max(Y||1,U+1)}}function N2($){return[...new Set($.filter(Boolean))]}function QX($,Z){let J={...$||{}};for(let[Y,U]of Object.entries(Z))if(U===null)delete J[Y];else J[Y]=U;return J}var WX=`Use this tool to create a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
|
|
749
749
|
|
|
750
750
|
## When to Use This Tool
|
|
751
751
|
|
|
@@ -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 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:
|
|
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:p$(H),tasks:Q.map(p$),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?p$(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(p$),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?p$(Q):null,updatedFields:W,error:Q?void 0:"Task not found",statusChange:z,tasks:V.map(p$),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(p$),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 g$.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 p$($){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??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`
|
|
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 j$ 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 j$.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 j$.mkdir(C1.dirname(Z),{recursive:!0,mode:493}),await j$.writeFile(Z,JSON.stringify({...$,teamFilePath:Z,updatedAt:Date.now()},null,2),"utf-8")}async listTeams(){try{let $=await j$.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 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}),D=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:D,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"}.
|
|
@@ -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 b={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},T=W9(J);return{success:!0,llmContent:A,metadata:{...b,summary:`GET ${T} - ${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 D={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},F=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:{...D,response_body:E.body}},metadata:{...D,summary:`请求失败: HTTP ${E.status} ${E.status_text}`}};return{success:!0,llmContent:E,metadata:{...D,summary:`${Y} ${F} - ${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),D=q.headers.get("location"),F=q.status>=300&&q.status<400,L=H&&F&&D&&G<Q;if(F&&H&&!D)throw Error(`收到状态码 ${q.status} 但响应缺少 Location 头`);if(F&&H&&G>=Q)throw Error(`超过最大重定向次数 (${Q})`);if(L&&D){G++;let b=RX(D,V);if(O.push(`${q.status} -> ${b}`),q.status===303||(q.status===301||q.status===302)&&B!=="GET"&&B!=="HEAD")B="GET",K=void 0;V=b;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
|
|
|
@@ -849,9 +849,9 @@ Usage notes:
|
|
|
849
849
|
|
|
850
850
|
`;return Z+=`---
|
|
851
851
|
|
|
852
|
-
`,Z+=$.content,Z}import{ProxyAgent as iX,fetch as lX}from"undici";import IX from"node:crypto";import{LRUCache as _9}from"lru-cache";class G9{cache;config;hits=0;misses=0;constructor($){this.config={maxSize:$?.maxSize??100,ttl:$?.ttl??3600000,enabled:$?.enabled??!0},this.cache=new _9({max:this.config.maxSize,ttl:this.config.ttl,updateAgeOnGet:!0,updateAgeOnHas:!1})}generateKey($,Z){let J=Z.toLowerCase().trim(),Y=IX.createHash("md5").update(J).digest("hex").substring(0,8);return`${$}:${Y}`}get($,Z){if(!this.config.enabled)return null;let J=this.generateKey($,Z),Y=this.cache.get(J);if(!Y)return this.misses++,null;if(Date.now()>Y.expiresAt)return this.cache.delete(J),this.misses++,null;return this.hits++,Y.results}set($,Z,J){if(!this.config.enabled||J.length===0)return;let Y=this.generateKey($,Z),U=Date.now(),X={query:Z,provider:$,results:J,timestamp:U,expiresAt:U+this.config.ttl};this.cache.set(Y,X)}clear(){this.cache.clear(),this.hits=0,this.misses=0}getStats(){let $=this.hits+this.misses,Z=$>0?this.hits/$*100:0;return{size:this.cache.size,maxSize:this.config.maxSize,enabled:this.config.enabled,ttl:this.config.ttl,hits:this.hits,misses:this.misses,hitRate:Number.parseFloat(Z.toFixed(2))}}cleanup(){let $=Date.now(),Z=0;for(let[J,Y]of this.cache.entries())if($>Y.expiresAt)this.cache.delete(J),Z++;return Z}enable(){this.config.enabled=!0}disable(){this.config.enabled=!1}isEnabled(){return this.config.enabled}updateConfig($){if($.maxSize!==void 0&&$.maxSize!==this.config.maxSize){this.config.maxSize=$.maxSize;let Z=Array.from(this.cache.entries());this.cache=new _9({max:this.config.maxSize,ttl:this.config.ttl,updateAgeOnGet:!0,updateAgeOnHas:!1});for(let[J,Y]of Z.slice(-this.config.maxSize))this.cache.set(J,Y)}if($.ttl!==void 0)this.config.ttl=$.ttl;if($.enabled!==void 0)this.config.enabled=$.enabled}}var yX=new G9;function O9(){return yX}function xX($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'")}function E9($){let Z=xX($).trim();if(!Z.includes(" - "))return{title:Z,snippet:Z};let[J,...Y]=Z.split(" - "),U=J.trim(),X=Y.join(" - ").trim()||Z;return{title:U,snippet:X}}function f1($){try{let Z=new URL($),J=Z.pathname==="/"?"":Z.pathname;return`${Z.hostname}${J}`}catch{return $}}function R1($){try{return new URL($).hostname.toLowerCase()}catch{return""}}function hX($){if(!$.FirstURL||!$.Text)return null;let{title:Z,snippet:J}=E9($.Text);return{title:Z,snippet:J,url:$.FirstURL,display_url:f1($.FirstURL),source:R1($.FirstURL)}}function q9($){let Z=[];for(let J of $){if(J.Topics&&J.Topics.length>0){Z.push(...q9(J.Topics));continue}if(J.FirstURL&&J.Text){let{title:Y,snippet:U}=E9(J.Text);Z.push({title:Y,snippet:U,url:J.FirstURL,display_url:f1(J.FirstURL),source:R1(J.FirstURL)})}}return Z}function uX($){let Z=$,J=(Z.Results??[]).map((U)=>hX(U)).filter((U)=>U!==null),Y=q9(Z.RelatedTopics??[]);return[...J,...Y]}var dX={name:"DuckDuckGo",endpoint:"https://duckduckgo.com/",buildUrl:($)=>{let Z=new URL("https://duckduckgo.com/");return Z.searchParams.set("q",$),Z.searchParams.set("format","json"),Z.searchParams.set("no_html","1"),Z.searchParams.set("skip_disambig","1"),Z.searchParams.set("t","blade-code"),Z.searchParams.set("kl","us-en"),Z.toString()},parseResponse:uX,getHeaders:()=>({Accept:"application/json, text/plain;q=0.9","User-Agent":"Blade-AI-WebSearch/1.0"})};function mX($){let Z=$,J=[];for(let Y of Z.results??[]){if(!Y.url||!Y.title)continue;J.push({title:Y.title,snippet:Y.content||Y.title,url:Y.url,display_url:f1(Y.url),source:R1(Y.url)})}return J}var F9=["https://searx.be","https://search.ononoki.org","https://searx.tiekoetter.com","https://searx.work"];function gX($){return{name:`SearXNG(${(()=>{try{return new URL($).hostname}catch{return $}})()})`,endpoint:$,buildUrl:(J)=>{let Y=new URL(`${$}/search`);return Y.searchParams.set("q",J),Y.searchParams.set("format","json"),Y.searchParams.set("categories","general"),Y.toString()},parseResponse:mX,getHeaders:()=>({Accept:"application/json","User-Agent":"Blade-AI-WebSearch/1.0"})}}var
|
|
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:`${
|
|
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:()=>`${
|
|
852
|
+
`,Z+=$.content,Z}import{ProxyAgent as iX,fetch as lX}from"undici";import IX from"node:crypto";import{LRUCache as _9}from"lru-cache";class G9{cache;config;hits=0;misses=0;constructor($){this.config={maxSize:$?.maxSize??100,ttl:$?.ttl??3600000,enabled:$?.enabled??!0},this.cache=new _9({max:this.config.maxSize,ttl:this.config.ttl,updateAgeOnGet:!0,updateAgeOnHas:!1})}generateKey($,Z){let J=Z.toLowerCase().trim(),Y=IX.createHash("md5").update(J).digest("hex").substring(0,8);return`${$}:${Y}`}get($,Z){if(!this.config.enabled)return null;let J=this.generateKey($,Z),Y=this.cache.get(J);if(!Y)return this.misses++,null;if(Date.now()>Y.expiresAt)return this.cache.delete(J),this.misses++,null;return this.hits++,Y.results}set($,Z,J){if(!this.config.enabled||J.length===0)return;let Y=this.generateKey($,Z),U=Date.now(),X={query:Z,provider:$,results:J,timestamp:U,expiresAt:U+this.config.ttl};this.cache.set(Y,X)}clear(){this.cache.clear(),this.hits=0,this.misses=0}getStats(){let $=this.hits+this.misses,Z=$>0?this.hits/$*100:0;return{size:this.cache.size,maxSize:this.config.maxSize,enabled:this.config.enabled,ttl:this.config.ttl,hits:this.hits,misses:this.misses,hitRate:Number.parseFloat(Z.toFixed(2))}}cleanup(){let $=Date.now(),Z=0;for(let[J,Y]of this.cache.entries())if($>Y.expiresAt)this.cache.delete(J),Z++;return Z}enable(){this.config.enabled=!0}disable(){this.config.enabled=!1}isEnabled(){return this.config.enabled}updateConfig($){if($.maxSize!==void 0&&$.maxSize!==this.config.maxSize){this.config.maxSize=$.maxSize;let Z=Array.from(this.cache.entries());this.cache=new _9({max:this.config.maxSize,ttl:this.config.ttl,updateAgeOnGet:!0,updateAgeOnHas:!1});for(let[J,Y]of Z.slice(-this.config.maxSize))this.cache.set(J,Y)}if($.ttl!==void 0)this.config.ttl=$.ttl;if($.enabled!==void 0)this.config.enabled=$.enabled}}var yX=new G9;function O9(){return yX}function xX($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'")}function E9($){let Z=xX($).trim();if(!Z.includes(" - "))return{title:Z,snippet:Z};let[J,...Y]=Z.split(" - "),U=J.trim(),X=Y.join(" - ").trim()||Z;return{title:U,snippet:X}}function f1($){try{let Z=new URL($),J=Z.pathname==="/"?"":Z.pathname;return`${Z.hostname}${J}`}catch{return $}}function R1($){try{return new URL($).hostname.toLowerCase()}catch{return""}}function hX($){if(!$.FirstURL||!$.Text)return null;let{title:Z,snippet:J}=E9($.Text);return{title:Z,snippet:J,url:$.FirstURL,display_url:f1($.FirstURL),source:R1($.FirstURL)}}function q9($){let Z=[];for(let J of $){if(J.Topics&&J.Topics.length>0){Z.push(...q9(J.Topics));continue}if(J.FirstURL&&J.Text){let{title:Y,snippet:U}=E9(J.Text);Z.push({title:Y,snippet:U,url:J.FirstURL,display_url:f1(J.FirstURL),source:R1(J.FirstURL)})}}return Z}function uX($){let Z=$,J=(Z.Results??[]).map((U)=>hX(U)).filter((U)=>U!==null),Y=q9(Z.RelatedTopics??[]);return[...J,...Y]}var dX={name:"DuckDuckGo",endpoint:"https://duckduckgo.com/",buildUrl:($)=>{let Z=new URL("https://duckduckgo.com/");return Z.searchParams.set("q",$),Z.searchParams.set("format","json"),Z.searchParams.set("no_html","1"),Z.searchParams.set("skip_disambig","1"),Z.searchParams.set("t","blade-code"),Z.searchParams.set("kl","us-en"),Z.toString()},parseResponse:uX,getHeaders:()=>({Accept:"application/json, text/plain;q=0.9","User-Agent":"Blade-AI-WebSearch/1.0"})};function mX($){let Z=$,J=[];for(let Y of Z.results??[]){if(!Y.url||!Y.title)continue;J.push({title:Y.title,snippet:Y.content||Y.title,url:Y.url,display_url:f1(Y.url),source:R1(Y.url)})}return J}var F9=["https://searx.be","https://search.ononoki.org","https://searx.tiekoetter.com","https://searx.work"];function gX($){return{name:`SearXNG(${(()=>{try{return new URL($).hostname}catch{return $}})()})`,endpoint:$,buildUrl:(J)=>{let Y=new URL(`${$}/search`);return Y.searchParams.set("q",J),Y.searchParams.set("format","json"),Y.searchParams.set("categories","general"),Y.toString()},parseResponse:mX,getHeaders:()=>({Accept:"application/json","User-Agent":"Blade-AI-WebSearch/1.0"})}}var M$={BASE_URL:"https://mcp.exa.ai",ENDPOINT:"/mcp",DEFAULT_NUM_RESULTS:10,TIMEOUT:25000};function pX($){let Z=[],J=$.split(`
|
|
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:`${M$.BASE_URL}${M$.ENDPOINT}`,searchFn:async($)=>{let Z={jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"web_search_exa",arguments:{query:$,type:"auto",numResults:M$.DEFAULT_NUM_RESULTS,contextMaxCharacters:1e4}}},J=new AbortController,Y=setTimeout(()=>J.abort(),M$.TIMEOUT);try{let U=await fetch(`${M$.BASE_URL}${M$.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
|
+
`);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:()=>`${M$.BASE_URL}${M$.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
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
|
|
@@ -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=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??
|
|
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(
|
|
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??T$(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 c$,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(c$(K0.join(Y,"tsconfig.json")))return Y;Y=K0.dirname(Y)}if(c$(K0.join(Z,"tsconfig.json")))return Z;return null}function QH($){let Z=K0.join($,"package.json");if(c$(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(c$(K0.join($,"bun.lock"))||c$(K0.join($,"bun.lockb")))return"bun";if(c$(K0.join($,"pnpm-lock.yaml")))return"pnpm";if(c$(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 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,
|
|
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
|
|
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,D=()=>{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 F=()=>{clearTimeout(A),U?.removeEventListener("abort",L),this.disposeController.signal.removeEventListener("abort",L),this.activeCommands.delete(z),Q()},L=()=>{D()},A=setTimeout(()=>{O=!0,D()},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,F(),B(w)}),X.once("close",async(w)=>{if(E)return;if(E=!0,O||U?.aborted||this.disposeController.signal.aborted)await D();F(),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 L${config;options;approvalStore=new N1;baseRegistry=new w$;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=$.permissionMode,H=$.reasoningEffort,Q=$.serviceTier,W=$.responseVerbosity,z=$.communicationStyle,V=$.communicationStyleDigest,B=$.projectInstructionsDigest,K=U!==void 0,G=z!==void 0;try{await K2();let O=await c.findSessionMetadata($.sessionId,Z);if(O?.archivedAt)throw new t9($.sessionId,O.archivedBySessionId??$.sessionId);if(X??=O?.permissionMode,H??=O?.reasoningEffort??"off",Q??=O?.serviceTier??"auto",W??=O?.responseVerbosity??"auto",z??=O?.communicationStyle??"auto",!G||z===O?.communicationStyle)V??=O?.communicationStyleDigest;if(await x9(Z),B??=O?.projectInstructionsDigest,await x9(Z),!$.subagentInfo&&(!J||!Y||!U)){let S=await(J?Promise.resolve(void 0):c.findSessionTaskWorktree($.sessionId,Z));J??=S,Y??=O?.taskIsolation,U??=O?.selectedModelId??O?.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 E=W0();if(!E)throw Error("配置未初始化,请确保应用已正确启动");$1.configure(E.maxConcurrentTasks,E.maxQueuedTasks);let q=t.getInstance(),D=$.modelResources?.projectRoot??$.lspResources?.projectRoot??$.agentResources?.projectRoot??J?.originalWorkspaceRoot??Z,F=$.modelResources?c9($.modelResources):await p9(D,E),L=F.config.models,A=$.lspResources?_1($.lspResources):await b4(D,F.config.lspServers);if(L.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 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}
|
|
902
|
+
`+" /init");if(!K&&U&&U!=="inherit"&&!L.some((S)=>S.id===U))U=void 0;let w=await r1({workspaceRoot:D,storeServers:E.mcpServers??{},sessionServers:$.mcpServers,cliConfigs:$.mcpConfig,strictCliConfig:$.strictMcpConfig}),b={...F.config,permissionMode:X??F.config.permissionMode??"default",lspServers:structuredClone(A.servers),permissions:await q.loadWorkspacePermissions(D,F.config.permissions),hooks:await q.loadWorkspaceHooks(D,F.config.hooks??{})};q.validateConfig(b,F.catalog);let T=new L$(b,{...$,modelResources:F,lspResources:A,mcpServers:w,...U?{modelId:U}:{},permissionMode:b.permissionMode,reasoningEffort:H,serviceTier:Q,responseVerbosity:W,communicationStyle:z,...V?{communicationStyleDigest:V}:{},...B?{projectInstructionsDigest:B}:{},...J?{taskWorktree:J}:{},...Y?{taskIsolation:Y}:{}});return await T.initialize(),T}catch(O){if(!$.subagentInfo&&!(O instanceof n9)){let E=J?await t0.getChangeSummary($.sessionId).catch(()=>{return}):void 0;await L$.persistTaskStatus($.sessionId,Z,"failed","Session runtime initialization failed",E??void 0).catch((q)=>{if(q.code!=="ENOENT")N0.warn(`[SessionRuntime ${$.sessionId}] Failed to persist initialization failure`,q)})}throw O}}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 c.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 L$.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 c.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(),c.listRewindCheckpoints(this.sessionId,this.workspaceRoot)}async rewindSession($){return this.assertRewindIdle(),c.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 w$;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 w$,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 P$({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 c.updateSessionMetadata(this.sessionId,this.workspaceRoot,$)}catch(Z){if(!(Z instanceof s9||Z.code==="ENOENT")||this.options.subagentInfo)throw Z;await c.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(),l$($.getWorkspaceRoot()),await i$($.getWorkspaceRoot()),await u6(await e($.getWorkspaceRoot()))}async function TH($){l$($.getWorkspaceRoot());let Z=await $.refresh();return await i$($.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=h$();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 h$().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($);l$(Z.workspaceRoot);let J=await Z.plugins.refresh();return await i$(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 h$().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 e(U);let X=
|
|
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=T$(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
|
|
|
@@ -946,7 +946,7 @@ ${z}
|
|
|
946
946
|
`+"- 项目级 (`.blade/agents/`) - 最高优先级\n"+"- 用户级 (`~/.blade/agents/`) - 较低优先级\n\n"+`**可用工具:**
|
|
947
947
|
`+"- `Glob` - 文件搜索\n"+"- `Grep` - 内容搜索\n"+"- `Read` - 读取文件\n"+"- `Write` - 写入文件\n"+"- `Edit` - 编辑文件\n"+"- `Bash` - 执行命令\n"+"- 省略 `tools` 字段 = 继承所有工具\n\n"+"**提示:** 创建文件后,重启 Blade 使配置生效";return Y.sendMessage(Q),{success:!0,message:"Help displayed"}}if(J==="create")return{success:!0,message:"show_agent_creation_wizard",data:{action:"show_agent_creation_wizard"}};let H=`未知子命令: \`${J}\`
|
|
948
948
|
|
|
949
|
-
`+"使用 `/agents help` 查看可用命令";return Y.sendMessage(H),{success:!1,error:`Unknown subcommand: ${J}`}}};async function Q7($,Z){let J=(await
|
|
949
|
+
`+"使用 `/agents help` 查看可用命令";return Y.sendMessage(H),{success:!1,error:`Unknown subcommand: ${J}`}}};async function Q7($,Z){let J=(await c.listSessions({includeSubagents:!1,archived:Z})).filter((Y)=>Y.sessionId===$);if(J.length===0)return{success:!1,error:`${Z?"Archived session":"Session"} not found: ${$}`};if(J.length>1)return{success:!1,error:`Multiple workspaces contain session ${$}`};return{projectPath:J[0].projectPath}}var W7={name:"archive",description:"Move an inactive session tree out of the active catalog",fullDescription:"归档一个已停止的会话及其 fork/subagent 后代。Transcript、任务证据和 worktree 元数据都会保留,可通过 /unarchive 恢复。",usage:"/archive [sessionId]",category:"Session",examples:["/archive","/archive web-abc123"],async handler($,Z){if($.length>1)return{success:!1,error:"Usage: /archive [sessionId]"};try{if($.length===0){if(!Z.lifecycle||!Z.sessionId)return{success:!1,error:"Current surface cannot archive its active session; provide a session ID"};let X=await Z.lifecycle.archiveCurrent();return{success:!0,message:"session_archived",content:`Archived session \`${X.sessionId}\`. Restore it with \`/unarchive ${X.sessionId}\`.`,data:{session:X}}}let J=$[0],Y=await Q7(J,!1);if("success"in Y)return Y;let U=await c.archiveSession(J,Y.projectPath);return{success:!0,message:`Archived session ${J}`,content:`Archived session \`${J}\` and its inactive descendants. Restore it with \`/unarchive ${J}\`.`,data:{session:U}}}catch(J){return{success:!1,error:J instanceof Error?J.message:"Failed to archive session"}}}},z7={name:"unarchive",description:"Restore an archived session tree to the active catalog",fullDescription:"恢复一个归档根会话及其继承归档状态的 fork/subagent 后代。单独归档的后代保持归档。",usage:"/unarchive <sessionId>",category:"Session",examples:["/unarchive web-abc123"],async handler($){if($.length!==1)return{success:!1,error:"Usage: /unarchive <sessionId>"};try{let Z=$[0],J=await Q7(Z,!0);if("success"in J)return J;let Y=await c.unarchiveSession(Z,J.projectPath);return{success:!0,message:`Restored session ${Z}`,content:`Restored session \`${Z}\` to the active catalog.`,data:{session:Y}}}catch(Z){return{success:!1,error:Z instanceof Error?Z.message:"Failed to restore session"}}}};import fH from"node:path";var RH={name:"branch",description:"Fork the current session into an independent branch",fullDescription:"将当前会话历史分支到一个独立会话",usage:"/branch",async handler($,Z){if(!Z.sessionId)return{success:!1,error:"No active session to branch"};let J=fH.resolve(Z.workspaceRoot??Z.cwd),Y=await c.forkSession(Z.sessionId,{sourceProjectPath:J,targetProjectPath:J});return{success:!0,message:"session_forked",content:Z.acp?`Created session branch ${Y.sessionId}. Load it with ACP session/load to continue independently.`:void 0,data:{action:"restore_forked_session",sessionId:Y.sessionId,parentSessionId:Y.parentSessionId,messages:Y.messages,visibleMessages:c.toUISafeMessages(Y.messages)}}}},V7=RH;async function SH($,Z){let J=v(Z);try{let Y=W0(),U=A$();if(!Y||!U)return{success:!1,error:"配置未初始化"};let X=H0().session,H=Z.messages??X.messages,Q=Z.sessionId??X.sessionId;if(!H||H.length===0)return J.sendMessage("[WARN] 当前会话没有消息,无需压缩"),{success:!1,error:"没有消息需要压缩"};let W=Z.messages?[...Z.messages]:H.map((O)=>({role:O.role,content:O.content})),z=u2.countTokens(W,U.model),V=w0(U,Y,"off"),B=V.model.contextWindow,K=(z/B*100).toFixed(1);if(J.sendMessage(`**当前上下文统计**
|
|
950
950
|
• 消息数量: ${W.length}
|
|
951
951
|
• Token 数量: ${z.toLocaleString()}
|
|
952
952
|
• Token 限制: ${B.toLocaleString()}
|
|
@@ -969,8 +969,8 @@ ${z}
|
|
|
969
969
|
|
|
970
970
|
由于压缩过程出现错误,已使用简单截断策略。
|
|
971
971
|
错误信息: ${G.error}`),{success:!1,message:"compact_fallback",error:G.error,data:{compactedMessages:G.compactedMessages,boundaryMessage:G.boundaryMessage,summaryMessage:G.summaryMessage,preTokens:G.preTokens,postTokens:G.postTokens}}}catch(Y){let U=Y instanceof Error?Y.message:String(Y);return J.sendMessage(`[FAIL] **压缩失败**: ${U}`),{success:!1,error:U}}}var PH={name:"compact",description:"手动压缩当前会话的上下文",fullDescription:"压缩当前对话历史,生成详细的技术总结,保留最近的消息。压缩后的上下文可以节省 token 使用量,同时保留关键信息。",usage:"/compact",examples:["/compact"],category:"context",handler:SH},K7=PH;function kH($){return`Reasoning effort: ${$.selection===$.effective?$.selection:`${$.selection} (${$.effective})`}
|
|
972
|
-
Supported: auto, ${$.supported.join(", ")}`}var vH={name:"effort",description:"查看或设置当前 Session 的推理强度",fullDescription:"推理强度由当前 Session 持有并持久化。auto 会按模型能力在 high 附近解析;显式不支持的级别会被拒绝。",usage:"/effort [auto|off|minimal|low|medium|high|xhigh|max]",category:"Session",examples:["/effort","/effort low","/effort auto","/effort off"],async handler($,Z){if(!Z.reasoning)return{success:!1,error:"This surface has no active Session reasoning boundary"};if($.length>1)return{success:!1,error:"Usage: /effort [auto|off|minimal|low|medium|high|xhigh|max]"};let J=$[0]?.toLowerCase();if(J!==void 0&&!_7(J))return{success:!1,error:`Invalid reasoning effort: ${J}`};try{let Y=J?await Z.reasoning.set(J):await Z.reasoning.get();return{success:!0,message:kH(Y),data:{reasoningEffort:Y.selection,effectiveReasoningEffort:Y.effective,supportedReasoningEfforts:Y.supported}}}catch(Y){return{success:!1,error:Y instanceof Error?Y.message:"Failed to update reasoning effort"}}}},G7=vH;import{mkdir as IH,open as yH,unlink as xH}from"node:fs/promises";import O7 from"node:os";import X1 from"node:path";function hH($,Z,J){let Y=Z?.trim()||J;if(Y.includes("\x00"))throw Error("Session export path contains a null byte");if(Y==="~")return X1.join(O7.homedir(),J);if(Y.startsWith(`~${X1.sep}`)||Y.startsWith("~/"))return X1.resolve(O7.homedir(),Y.slice(2));return X1.resolve($,Y)}async function E7($,Z,J){if(!X1.isAbsolute($))throw Error("Session export cwd must be absolute");let Y=hH($,J,Z.filename);await IH(X1.dirname(Y),{recursive:!0,mode:448});let U,X=!1;try{return U=await yH(Y,"wx",384),X=!0,await U.writeFile(Z.markdown,"utf8"),await U.sync(),Y}catch(H){if(await U?.close().catch(()=>{return}),U=void 0,X)await xH(Y).catch(()=>{return});if(H.code==="EEXIST")throw Error(`Session export already exists: ${Y}`);throw H}finally{await U?.close().catch(()=>{return})}}function uH($){let Z=!1,J=[];for(let Y of $){if(Y==="--reasoning"){Z=!0;continue}if(Y.startsWith("--"))throw Error(`Unknown export option: ${Y}`);J.push(Y)}if(J.length>1)throw Error("Usage: /export [path] [--reasoning]");return{includeReasoning:Z,...J[0]?{outputPath:J[0]}:{}}}var dH={name:"export",description:"Export the current durable conversation as safe Markdown",fullDescription:"将当前完整 durable history 导出为 Markdown。工具活动经过凭证、二进制、宿主路径和体积清理;reasoning 仅在显式 --reasoning 时包含。",usage:"/export [path] [--reasoning]",category:"Session",examples:["/export","/export reports/conversation.md","/export --reasoning"],async handler($,Z){if(!Z.sessionId)return{success:!1,error:"No active session to export"};let J=Z.workspaceRoot??Z.cwd;try{let{includeReasoning:Y,outputPath:U}=uH($),X=await
|
|
973
|
-
SHA-256 ${X.contentSha256}`,data:{action:"session_exported",filePath:H,filename:X.filename,contentSha256:X.contentSha256,contentBytes:X.contentBytes,redactionCount:X.redactionCount}}}catch(Y){return{success:!1,error:Y instanceof Error?Y.message:"Session export failed"}}}},F7=dH;function mH($){return $.filter((Z)=>Z.relationType!=="subagent")}var gH={name:"fork",description:"Fork a conversation into an independent session branch",fullDescription:"从任意工作区的历史会话创建独立分支。可以指定唯一 sessionId 直接 fork,或不带参数打开会话选择器。",usage:"/fork [sessionId]",category:"Session",examples:["/fork - 打开会话选择器","/fork parent-session - 直接 fork 指定会话"],async handler($,Z){if($.length>1)return{success:!1,error:"Usage: /fork [sessionId]"};try{let J=await
|
|
972
|
+
Supported: auto, ${$.supported.join(", ")}`}var vH={name:"effort",description:"查看或设置当前 Session 的推理强度",fullDescription:"推理强度由当前 Session 持有并持久化。auto 会按模型能力在 high 附近解析;显式不支持的级别会被拒绝。",usage:"/effort [auto|off|minimal|low|medium|high|xhigh|max]",category:"Session",examples:["/effort","/effort low","/effort auto","/effort off"],async handler($,Z){if(!Z.reasoning)return{success:!1,error:"This surface has no active Session reasoning boundary"};if($.length>1)return{success:!1,error:"Usage: /effort [auto|off|minimal|low|medium|high|xhigh|max]"};let J=$[0]?.toLowerCase();if(J!==void 0&&!_7(J))return{success:!1,error:`Invalid reasoning effort: ${J}`};try{let Y=J?await Z.reasoning.set(J):await Z.reasoning.get();return{success:!0,message:kH(Y),data:{reasoningEffort:Y.selection,effectiveReasoningEffort:Y.effective,supportedReasoningEfforts:Y.supported}}}catch(Y){return{success:!1,error:Y instanceof Error?Y.message:"Failed to update reasoning effort"}}}},G7=vH;import{mkdir as IH,open as yH,unlink as xH}from"node:fs/promises";import O7 from"node:os";import X1 from"node:path";function hH($,Z,J){let Y=Z?.trim()||J;if(Y.includes("\x00"))throw Error("Session export path contains a null byte");if(Y==="~")return X1.join(O7.homedir(),J);if(Y.startsWith(`~${X1.sep}`)||Y.startsWith("~/"))return X1.resolve(O7.homedir(),Y.slice(2));return X1.resolve($,Y)}async function E7($,Z,J){if(!X1.isAbsolute($))throw Error("Session export cwd must be absolute");let Y=hH($,J,Z.filename);await IH(X1.dirname(Y),{recursive:!0,mode:448});let U,X=!1;try{return U=await yH(Y,"wx",384),X=!0,await U.writeFile(Z.markdown,"utf8"),await U.sync(),Y}catch(H){if(await U?.close().catch(()=>{return}),U=void 0,X)await xH(Y).catch(()=>{return});if(H.code==="EEXIST")throw Error(`Session export already exists: ${Y}`);throw H}finally{await U?.close().catch(()=>{return})}}function uH($){let Z=!1,J=[];for(let Y of $){if(Y==="--reasoning"){Z=!0;continue}if(Y.startsWith("--"))throw Error(`Unknown export option: ${Y}`);J.push(Y)}if(J.length>1)throw Error("Usage: /export [path] [--reasoning]");return{includeReasoning:Z,...J[0]?{outputPath:J[0]}:{}}}var dH={name:"export",description:"Export the current durable conversation as safe Markdown",fullDescription:"将当前完整 durable history 导出为 Markdown。工具活动经过凭证、二进制、宿主路径和体积清理;reasoning 仅在显式 --reasoning 时包含。",usage:"/export [path] [--reasoning]",category:"Session",examples:["/export","/export reports/conversation.md","/export --reasoning"],async handler($,Z){if(!Z.sessionId)return{success:!1,error:"No active session to export"};let J=Z.workspaceRoot??Z.cwd;try{let{includeReasoning:Y,outputPath:U}=uH($),X=await c.exportSessionMarkdown(Z.sessionId,J,{includeReasoning:Y});if(Z.surface==="acp"){if(U)return{success:!1,error:"ACP export does not write host paths; omit the path to receive Markdown"};if(Buffer.byteLength(X.markdown,"utf8")>q7)return{success:!1,error:"Session export exceeds the ACP inline limit; use the Web export endpoint"};return{success:!0,message:"Session export ready",content:X.markdown,data:{action:"session_exported",filename:X.filename,contentSha256:X.contentSha256,contentBytes:X.contentBytes}}}let H=await E7(J,X,U);return{success:!0,message:`Saved conversation to ${H}
|
|
973
|
+
SHA-256 ${X.contentSha256}`,data:{action:"session_exported",filePath:H,filename:X.filename,contentSha256:X.contentSha256,contentBytes:X.contentBytes,redactionCount:X.redactionCount}}}catch(Y){return{success:!1,error:Y instanceof Error?Y.message:"Session export failed"}}}},F7=dH;function mH($){return $.filter((Z)=>Z.relationType!=="subagent")}var gH={name:"fork",description:"Fork a conversation into an independent session branch",fullDescription:"从任意工作区的历史会话创建独立分支。可以指定唯一 sessionId 直接 fork,或不带参数打开会话选择器。",usage:"/fork [sessionId]",category:"Session",examples:["/fork - 打开会话选择器","/fork parent-session - 直接 fork 指定会话"],async handler($,Z){if($.length>1)return{success:!1,error:"Usage: /fork [sessionId]"};try{let J=await c.listSessions({includeSubagents:!1}),Y=mH(J);if($.length===0){if(Y.length===0)return{success:!1,error:"No forkable sessions found"};return{success:!0,data:{action:"select_session",intent:"fork",sessions:Y}}}let U=$[0],X=J.filter((Q)=>Q.sessionId===U);if(X.length>0&&X.every((Q)=>Q.relationType==="subagent"))return{success:!1,error:`Cannot fork subagent session: ${U}`};let H=Y.filter((Q)=>Q.sessionId===U);if(H.length===0)return{success:!1,error:`Session not found: ${U}`};if(H.length>1)return{success:!1,error:`Multiple workspaces contain session ${U}; use /fork to select one`};return{success:!0,data:{action:"activate_session",intent:"fork",session:H[0]}}}catch(J){return{success:!1,error:J instanceof Error?J.message:"Failed to list sessions"}}}},D7=gH;function N7($){let Z=Math.floor((Date.now()-$.getTime())/1000);if(Z<60)return`${Z}s ago`;let J=Math.floor(Z/60);if(J<60)return`${J}m ago`;let Y=Math.floor(J/60);if(Y<24)return`${Y}h ago`;return`${Math.floor(Y/24)}d ago`}async function pH($){let Z=k0.getInstance(),J=S$();if(Object.keys(J).length===0){$.sendMessage(`**MCP 服务器状态**
|
|
974
974
|
|
|
975
975
|
[WARN] 暂无配置的 MCP 服务器
|
|
976
976
|
|
|
@@ -989,7 +989,7 @@ SHA-256 ${X.contentSha256}`,data:{action:"session_exported",filePath:H,filename:
|
|
|
989
989
|
`,J+=`- 服务器: ${Z.size} 个 (${Y} 连接, ${U} 断开)
|
|
990
990
|
`,J+=`- 可用工具: ${X} 个
|
|
991
991
|
|
|
992
|
-
`,J+="使用 `/mcp <server-name>` 查看详细信息\n",J+="使用 `/mcp tools` 查看所有工具",$.sendMessage(J)}async function iH($,Z){let J=k0.getInstance(),U=
|
|
992
|
+
`,J+="使用 `/mcp <server-name>` 查看详细信息\n",J+="使用 `/mcp tools` 查看所有工具",$.sendMessage(J)}async function iH($,Z){let J=k0.getInstance(),U=S$()[Z];if(!U){$.sendMessage(`服务器 "${Z}" 不存在
|
|
993
993
|
|
|
994
994
|
使用 \`/mcp\` 查看所有可用服务器`);return}try{let X=J.getServerStatus(Z);if(!X)$.sendMessage(`正在连接 ${Z}...`),await J.registerServer(Z,U),X=J.getServerStatus(Z);else if(X.status==="disconnected")$.sendMessage(`正在重新连接 ${Z}...`),await J.connectServer(Z),X=J.getServerStatus(Z);if(X)lH($,Z,X);else w7($,Z,U)}catch(X){w7($,Z,U),$.sendMessage(`
|
|
995
995
|
[WARN] 连接失败: ${X instanceof Error?X.message:"未知错误"}`)}}function lH($,Z,J){let{config:Y,status:U,connectedAt:X,lastError:H,recovery:Q,tools:W}=J,z=U==="connected"?"[OK]":U==="reconnecting"?"[WAIT]":"[FAIL]",V=U==="connected"?"Connected":U==="reconnecting"?`Recovering ${Q?.attempt??0}/${Q?.maxAttempts??0}`:"Disconnected",B=`**${Z}**
|
|
@@ -1027,7 +1027,7 @@ SHA-256 ${X.contentSha256}`,data:{action:"session_exported",filePath:H,filename:
|
|
|
1027
1027
|
`,J.headers&&Object.keys(J.headers).length>0)Y+=` Headers: ${Object.keys(J.headers).join(", ")}
|
|
1028
1028
|
`;if(J.timeout)Y+=` 超时: ${J.timeout}ms
|
|
1029
1029
|
`;Y+=`
|
|
1030
|
-
服务器将在 Agent 启动时自动连接`,$.sendMessage(Y)}async function nH($){let Z=k0.getInstance(),J=
|
|
1030
|
+
服务器将在 Agent 启动时自动连接`,$.sendMessage(Y)}async function nH($){let Z=k0.getInstance(),J=S$();if(Object.keys(J).length===0){$.sendMessage(`**可用的 MCP 工具**
|
|
1031
1031
|
|
|
1032
1032
|
[WARN] 暂无配置的 MCP 服务器
|
|
1033
1033
|
|
|
@@ -1061,9 +1061,9 @@ ${JSON.stringify(Q.content,null,2)}`).join(`
|
|
|
1061
1061
|
`)),H=[`**MCP server instructions (revision ${Y.revision})**`,"",X.join(`
|
|
1062
1062
|
|
|
1063
1063
|
`)].join(`
|
|
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=
|
|
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=S$()[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=
|
|
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=S$()[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(`**项目记忆文件:**
|
|
@@ -1080,8 +1080,8 @@ ${Q}
|
|
|
1080
1080
|
`+`/memory list — 列出所有记忆文件
|
|
1081
1081
|
`+`/memory show [topic] — 查看记忆内容(默认 MEMORY)
|
|
1082
1082
|
`+`/memory edit [topic] — 用编辑器打开记忆文件(默认 MEMORY)
|
|
1083
|
-
`+"/memory clear — 清空所有记忆"),{success:!0,message:"帮助信息已显示"}}}},M7=WQ;async function zQ($,Z){return{success:!0,message:"show_permissions_editor",data:{action:"show_permissions_editor"}}}var VQ={name:"permissions",description:"管理项目的本地权限规则",fullDescription:"打开权限管理器,管理 .blade/settings.local.json 中的权限规则",usage:"/permissions",aliases:["perm"],category:"ui",handler:zQ},d2=VQ;var BQ={name:"resume",description:"Resume a conversation",fullDescription:"恢复任意工作区的历史会话。可以指定唯一 sessionId 直接恢复,或不带参数打开会话选择器",usage:"/resume [sessionId]",aliases:["r"],category:"Session",examples:["/resume - 打开会话选择器","/resume abc123xyz - 直接恢复指定的会话"],async handler($,Z){if($.length>1)return{success:!1,error:"Usage: /resume [sessionId]"};try{let J=await
|
|
1084
|
-
`)),{success:!0}}let Y=_Q($),U=await Z.rewind.execute(Y),X=
|
|
1083
|
+
`+"/memory clear — 清空所有记忆"),{success:!0,message:"帮助信息已显示"}}}},M7=WQ;async function zQ($,Z){return{success:!0,message:"show_permissions_editor",data:{action:"show_permissions_editor"}}}var VQ={name:"permissions",description:"管理项目的本地权限规则",fullDescription:"打开权限管理器,管理 .blade/settings.local.json 中的权限规则",usage:"/permissions",aliases:["perm"],category:"ui",handler:zQ},d2=VQ;var BQ={name:"resume",description:"Resume a conversation",fullDescription:"恢复任意工作区的历史会话。可以指定唯一 sessionId 直接恢复,或不带参数打开会话选择器",usage:"/resume [sessionId]",aliases:["r"],category:"Session",examples:["/resume - 打开会话选择器","/resume abc123xyz - 直接恢复指定的会话"],async handler($,Z){if($.length>1)return{success:!1,error:"Usage: /resume [sessionId]"};try{let J=await c.listSessions({includeSubagents:!1});if($.length===0){if(J.length===0)return{success:!1,error:"No resumable sessions found"};return{success:!0,data:{action:"select_session",intent:"resume",sessions:J}}}let Y=$[0],U=J.filter((X)=>X.sessionId===Y);if(U.length===0)return{success:!1,error:`Session not found: ${Y}`};if(U.length>1)return{success:!1,error:`Multiple workspaces contain session ${Y}; use /resume to select one`};return{success:!0,data:{action:"activate_session",intent:"resume",session:U[0]}}}catch(J){return{success:!1,error:J instanceof Error?J.message:"Failed to list sessions"}}}},C7=BQ;import a6 from"node:path";async function KQ($,Z){let J=v(Z),Y=Z.sessionId??H0().session?.sessionId;if(!Y)return J.sendMessage("No active session is available for file rewind."),{success:!1,error:"No active session"};if($.length===0)return{success:!1,error:"Usage: /rewind file <file_path>"};let U=a6.resolve(Z.workspaceRoot??Z.cwd),X=a6.resolve(Z.cwd,$.join(" "));if(!await X0.isWithinWorkspaceResolved(X,U)){let z=`Target path is outside the current workspace: ${X}`;return J.sendMessage(z),{success:!1,error:z}}let H=new n0({sessionId:Y,workspaceRoot:U});await H.initialize();let Q=await H.rewindLatest(X);V0.getInstance().clearFileRecord(Q.filePath);let W=a6.relative(U,X)||".";return J.sendMessage(`Rewound \`${W}\` to the state before the latest Blade edit (v${Q.version}).`),{success:!0}}function _Q($){let Z=new Set($.filter((X)=>X.startsWith("--"))),J=$.filter((X)=>!X.startsWith("--")),Y=new Set(["--code","--code-only","--conversation"]),U=[...Z].find((X)=>!Y.has(X));if(U)throw Error(`Unknown rewind option: ${U}`);if(J.length!==1)throw Error("Usage: /rewind <checkpointId> [--code|--code-only|--conversation]");if(Z.has("--code")&&Z.has("--code-only"))throw Error("--code and --code-only cannot be combined");return{targetMessageId:J[0],mode:Z.has("--code-only")?"code":Z.has("--code")?"both":"conversation"}}var GQ={name:"rewind",description:"Rewind the conversation and optionally restore code",fullDescription:"List durable user-turn checkpoints or rewind to one. Use --code to restore both conversation and code. Legacy single-file rewind remains available through /rewind file <path>.",usage:"/rewind [checkpointId] [--code|--code-only] | /rewind file <file_path>",aliases:["undo","checkpoint"],async handler($,Z){let J=v(Z);try{if($[0]==="file"||$[0]==="--file")return await KQ($.slice(1),Z);if(!Z.rewind)return{success:!1,error:"This surface does not own a session runtime for rewind"};if($.length===0){let Q=await Z.rewind.listCheckpoints();if(Q.length===0)return J.sendMessage("Nothing to rewind to yet."),{success:!0};let W=Q.map((z)=>{let V=z.fileCount===0?"":`, ${z.fileCount} file${z.fileCount===1?"":"s"}`;return`- \`${z.messageId}\` ${z.preview}${V}`});return J.sendMessage(["**Rewind checkpoints**","",...W,"","Use `/rewind <checkpointId>` for conversation only or add `--code` to restore code too."].join(`
|
|
1084
|
+
`)),{success:!0}}let Y=_Q($),U=await Z.rewind.execute(Y),X=c.toUISafeMessages(U.messages),H=U.restoredFiles.length===0?"":` Restored ${U.restoredFiles.length} file${U.restoredFiles.length===1?"":"s"}.`;return J.sendMessage(`Rewound ${U.removedTurns} turn${U.removedTurns===1?"":"s"} to before: ${U.checkpoint.preview}.${H}`),{success:!0,data:{action:"rewind_session",sessionId:Z.sessionId,messages:U.messages,visibleMessages:X,checkpoint:U.checkpoint,mode:U.mode,restoredFiles:U.restoredFiles}}}catch(Y){let U=Y instanceof Error?Y.message:String(Y);return J.sendMessage(`Rewind failed: ${U}`),{success:!1,error:U}}}},f7=GQ;function OQ($){return`Service tier: ${$.selection===$.effective?$.selection:`${$.selection} (${$.effective})`}
|
|
1085
1085
|
Supported: auto, ${$.supported.join(", ")}`}function EQ($){let Z=$.toLowerCase();if(Z==="on")return"fast";if(Z==="off")return"standard";return R7(Z)?Z:void 0}var qQ={name:"speed",aliases:["fast"],description:"查看或设置当前 Session 的 provider 服务等级",fullDescription:"auto 使用 provider 默认值;standard 强制基线;fast 使用 priority tier;flex 使用低成本弹性 tier。显式不支持的等级会被拒绝。",usage:"/speed [auto|standard|fast|flex]",category:"Session",examples:["/speed","/speed fast","/fast on","/fast off"],async handler($,Z){if(!Z.serviceTier)return{success:!1,error:"This surface has no active Session service-tier boundary"};if($.length>1)return{success:!1,error:"Usage: /speed [auto|standard|fast|flex]"};let J=$[0]?EQ($[0]):void 0;if($[0]&&!J)return{success:!1,error:`Invalid service tier: ${$[0].toLowerCase()}`};try{let Y=J?await Z.serviceTier.set(J):await Z.serviceTier.get();return{success:!0,message:OQ(Y),data:{serviceTier:Y.selection,effectiveServiceTier:Y.effective,supportedServiceTiers:Y.supported}}}catch(Y){return{success:!1,error:Y instanceof Error?Y.message:"Failed to update service tier"}}}},S7=qQ;function FQ($){return`Communication style: ${$.selection===$.effective?$.selection:`${$.selection} (${$.effective})`}
|
|
1086
1086
|
Supported: ${$.supported.map((J)=>J.id).join(", ")}`}function DQ($){let Z=$.toLowerCase();return P7(Z)?Z:void 0}var wQ={name:"style",aliases:["personality"],description:"查看或设置当前 Session 的沟通风格",fullDescription:"内置或 namespaced custom style 只改变沟通语气和解释框架。",usage:"/style [auto|pragmatic|friendly|explanatory|<namespaced-id>]",category:"Session",examples:["/style","/style pragmatic","/style project:review:strict","/personality friendly"],async handler($,Z){if(!Z.communicationStyle)return{success:!1,error:"This surface has no active Session communication-style boundary"};if($.length>1)return{success:!1,error:"Usage: /style [auto|pragmatic|friendly|explanatory|<namespaced-id>]"};let J=$[0]?DQ($[0]):void 0;if($[0]&&!J)return{success:!1,error:`Invalid communication style: ${$[0].toLowerCase()}`};try{let Y=J?await Z.communicationStyle.set(J):await Z.communicationStyle.get();return{success:!0,message:FQ(Y),data:{communicationStyle:Y.selection,effectiveCommunicationStyle:Y.effective}}}catch(Y){return{success:!1,error:Y instanceof Error?Y.message:"Failed to update communication style"}}}},k7=wQ;function AQ($){let Z=$.selection===$.effective?$.selection:`${$.selection} (${$.effective})`,J=$.supported.length>0?`auto, ${$.supported.join(", ")}`:"auto";return`Response verbosity: ${Z}
|
|
1087
1087
|
Supported: ${J}`}function LQ($){let Z=$.toLowerCase();return v7(Z)?Z:void 0}var NQ={name:"verbosity",aliases:["detail"],description:"查看或设置当前 Session 的响应详略",fullDescription:"auto 使用模型默认值;low、medium、high 控制支持模型的原生响应详略。显式不支持的选择会被拒绝。",usage:"/verbosity [auto|low|medium|high]",category:"Session",examples:["/verbosity","/verbosity low","/detail high"],async handler($,Z){if(!Z.responseVerbosity)return{success:!1,error:"This surface has no active Session response-verbosity boundary"};if($.length>1)return{success:!1,error:"Usage: /verbosity [auto|low|medium|high]"};let J=$[0]?LQ($[0]):void 0;if($[0]&&!J)return{success:!1,error:`Invalid response verbosity: ${$[0].toLowerCase()}`};try{let Y=J?await Z.responseVerbosity.set(J):await Z.responseVerbosity.get();return{success:!0,message:AQ(Y),data:{responseVerbosity:Y.selection,effectiveResponseVerbosity:Y.effective,supportedResponseVerbosities:Y.supported}}}catch(Y){return{success:!1,error:Y instanceof Error?Y.message:"Failed to update response verbosity"}}}},I7=NQ;var bQ={name:"help",description:"Show all available slash commands",fullDescription:"显示所有可用的 slash commands 及其使用方法",usage:"/help",aliases:["h"],async handler($,Z){let J=v(Z),Y=`**可用的 Slash Commands:**
|
|
@@ -1134,7 +1134,7 @@ Supported: ${J}`}function LQ($){let Z=$.toLowerCase();return v7(Z)?Z:void 0}var
|
|
|
1134
1134
|
- 智能 AI 对话
|
|
1135
1135
|
- 项目自动分析
|
|
1136
1136
|
- 自定义系统提示
|
|
1137
|
-
- 多工具集成支持`;return J.sendMessage(U),{success:!0,message:"版本信息已显示"}}},MQ={name:"status",description:"Show current configuration status",fullDescription:"显示当前项目配置状态和环境信息",usage:"/status",async handler($,Z){let J=v(Z),{cwd:Y}=Z;try{let U=x7.join(Y,"BLADE.md"),X=await y7.access(U).then(()=>!0).catch(()=>!1),H=x7.join(Y,"package.json"),Q="未知项目",W="未知类型";try{let O=await y7.readFile(H,"utf-8"),E=JSON.parse(O);Q=E.name||"未知项目";let q={...E.dependencies,...E.devDependencies};if(q.react)W="React 项目";else if(q.vue)W="Vue 项目";else if(q.next)W="Next.js 项目";else if(q.express)W="Express 项目";else W="Node.js 项目"}catch{}let z=W0(),V=
|
|
1137
|
+
- 多工具集成支持`;return J.sendMessage(U),{success:!0,message:"版本信息已显示"}}},MQ={name:"status",description:"Show current configuration status",fullDescription:"显示当前项目配置状态和环境信息",usage:"/status",async handler($,Z){let J=v(Z),{cwd:Y}=Z;try{let U=x7.join(Y,"BLADE.md"),X=await y7.access(U).then(()=>!0).catch(()=>!1),H=x7.join(Y,"package.json"),Q="未知项目",W="未知类型";try{let O=await y7.readFile(H,"utf-8"),E=JSON.parse(O);Q=E.name||"未知项目";let q={...E.dependencies,...E.devDependencies};if(q.react)W="React 项目";else if(q.vue)W="Vue 项目";else if(q.next)W="Next.js 项目";else if(q.express)W="Express 项目";else W="Node.js 项目"}catch{}let z=W0(),V=A$(),K=H0().session.tokenUsage,G=`**当前状态**
|
|
1138
1138
|
|
|
1139
1139
|
**项目信息:**
|
|
1140
1140
|
- 名称: ${Q}
|
|
@@ -1142,7 +1142,7 @@ Supported: ${J}`}function LQ($){let Z=$.toLowerCase();return v7(Z)?Z:void 0}var
|
|
|
1142
1142
|
- 路径: ${Y}
|
|
1143
1143
|
|
|
1144
1144
|
**模型配置:**
|
|
1145
|
-
- 当前模型: ${V?
|
|
1145
|
+
- 当前模型: ${V?C$(V):"N/A"} (${V?.model??"N/A"})
|
|
1146
1146
|
- Provider: ${V?.provider??"N/A"}
|
|
1147
1147
|
- 可用模型数: ${z?.models?.length??0}
|
|
1148
1148
|
|
|
@@ -1159,7 +1159,7 @@ Supported: ${J}`}function LQ($){let Z=$.toLowerCase();return v7(Z)?Z:void 0}var
|
|
|
1159
1159
|
- 工作目录: ${N()} (process.cwd: ${process.cwd()})
|
|
1160
1160
|
- Node.js: ${process.version}
|
|
1161
1161
|
|
|
1162
|
-
${!X?"\n**建议:** 运行 `/init` 命令来创建项目配置文件":""}`;return J.sendMessage(G),{success:!0,message:"状态信息已显示"}}catch(U){return{success:!1,error:`获取状态信息失败: ${U instanceof Error?U.message:"未知错误"}`}}}},CQ={name:"exit",description:"Exit the REPL",fullDescription:"退出 Blade Code 命令行界面",usage:"/exit",aliases:["quit","q"],async handler($,Z){return{success:!0,message:"exit_application"}}},fQ={name:"context",description:"Visualize current context usage as a colored grid",fullDescription:"可视化显示当前上下文使用情况",usage:"/context",async handler($,Z){let J=v(Z),Y=W0(),U=
|
|
1162
|
+
${!X?"\n**建议:** 运行 `/init` 命令来创建项目配置文件":""}`;return J.sendMessage(G),{success:!0,message:"状态信息已显示"}}catch(U){return{success:!1,error:`获取状态信息失败: ${U instanceof Error?U.message:"未知错误"}`}}}},CQ={name:"exit",description:"Exit the REPL",fullDescription:"退出 Blade Code 命令行界面",usage:"/exit",aliases:["quit","q"],async handler($,Z){return{success:!0,message:"exit_application"}}},fQ={name:"context",description:"Visualize current context usage as a colored grid",fullDescription:"可视化显示当前上下文使用情况",usage:"/context",async handler($,Z){let J=v(Z),Y=W0(),U=A$(),H=H0().session.messages||[],Q=H.map((q)=>({role:q.role,content:q.content})),W=U?.model||"gpt-4",z=Q.length>0?u2.countTokens(Q,W):0,V=U&&Y?w0(U,Y,"off").model.contextWindow:128000,B=V>0?(z/V*100).toFixed(1):"0",K=(100-parseFloat(B)).toFixed(1),G=parseFloat(B),O;if(G<50)O="[OK] 正常";else if(G<80)O="[WARN] 中等";else O="[CRITICAL] 高负载";let E=`**上下文使用情况**
|
|
1163
1163
|
|
|
1164
1164
|
**当前会话:**
|
|
1165
1165
|
- 消息数量: ${H.length}
|
|
@@ -1173,7 +1173,7 @@ ${!X?"\n**建议:** 运行 `/init` 命令来创建项目配置文件":""}`;retur
|
|
|
1173
1173
|
|
|
1174
1174
|
**状态:** ${O}
|
|
1175
1175
|
|
|
1176
|
-
使用 \`/compact\` 可手动压缩上下文`;return J.sendMessage(E),{success:!0,message:"上下文信息已显示"}}},RQ={name:"cost",description:"Show session token usage and estimated cost",fullDescription:"显示当前会话的 token 消耗和费用估算",usage:"/cost",aliases:[],async handler($,Z){let J=v(Z),U=H0().session.tokenUsage,X=
|
|
1176
|
+
使用 \`/compact\` 可手动压缩上下文`;return J.sendMessage(E),{success:!0,message:"上下文信息已显示"}}},RQ={name:"cost",description:"Show session token usage and estimated cost",fullDescription:"显示当前会话的 token 消耗和费用估算",usage:"/cost",aliases:[],async handler($,Z){let J=v(Z),U=H0().session.tokenUsage,X=A$(),H=U.estimatedCostUsd>0?`$${U.estimatedCostUsd<0.01?U.estimatedCostUsd.toFixed(6):U.estimatedCostUsd.toFixed(4)}`:"N/A (unknown model pricing)",Q=U.cacheReadTokens>0||U.cacheWriteTokens>0?`
|
|
1177
1177
|
- Cache read: ${U.cacheReadTokens.toLocaleString()} tokens
|
|
1178
1178
|
- Cache write: ${U.cacheWriteTokens.toLocaleString()} tokens`:"",W=`**Session Cost Summary**
|
|
1179
1179
|
|
|
@@ -1185,10 +1185,10 @@ ${!X?"\n**建议:** 运行 `/init` 命令来创建项目配置文件":""}`;retur
|
|
|
1185
1185
|
- **Total output: ${U.totalOutputTokens.toLocaleString()} tokens**${Q}
|
|
1186
1186
|
- Context remaining: ${U.maxContextTokens>0?Math.round((1-U.inputTokens/U.maxContextTokens)*100):"?"}%
|
|
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
|
-
`],H=!0;for(let Q of U){let W=await h2(Q,Y,{timeoutMs:1e4});if(H&&=W.ok,W.ok)X.push(`✅ **${
|
|
1188
|
+
`],H=!0;for(let Q of U){let W=await h2(Q,Y,{timeoutMs:1e4});if(H&&=W.ok,W.ok)X.push(`✅ **${C$(Q)}** (${Q.provider}/${Q.model}) — ${W.latencyMs}ms · ${W.wireApi}`);else X.push(`❌ **${C$(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: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
|
|
1191
|
-
`),
|
|
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 gN=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 pN($){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
|
+
`),D=q.pop()||"";for(let F of q)if(F.trim())Y(F,G);return D},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}
|
|
1194
1194
|
Main branch (target for PRs): ${$.mainBranch}
|
|
@@ -1351,7 +1351,7 @@ ${J}
|
|
|
1351
1351
|
- 具体的改进建议(附带示例)
|
|
1352
1352
|
- 如果需要重大修改,提供完整的改进版本内容
|
|
1353
1353
|
|
|
1354
|
-
**Final output**: Return your analysis and suggestions as plain text. Do NOT use Write tool.`;Q1.info(`[/init] Starting agent.chatStream, signal.aborted: ${Y?.aborted}`);let
|
|
1354
|
+
**Final output**: Return your analysis and suggestions as plain text. Do NOT use Write tool.`;Q1.info(`[/init] Starting agent.chatStream, signal.aborted: ${Y?.aborted}`);let D=(await h0(O.chatStream(E,{messages:[],userId:"cli-user",sessionId:H||"init-session",workspaceRoot:J,signal:Y}),async(F)=>{switch(F.kind){case"tool_start":{let L=F.toolCall;if(!("function"in L))return;try{let A=JSON.parse(L.function.arguments),w=N6(L.function.name,A);X(w)}catch{}break}case"tool_result":{if(!("function"in F.toolCall))return;let A=F.result.metadata?.summary;if(A)X(A);break}default:break}})).finalMessage||"";if(Q1.info(`[/init] agent.chatStream completed, signal.aborted: ${Y?.aborted}`),Y?.aborted)return Q1.info("[/init] Returning cancelled after agent.chat"),{success:!1,message:"操作已取消"};return U.sendMessage(D),{success:!0,message:"[OK] 分析完成"}}if(z)U.sendMessage("[WARN] 检测到空的 BLADE.md 文件,将重新生成...");U.sendMessage("正在分析项目结构...");let V=await O0.create();if(Y?.aborted)return{success:!1,message:"操作已取消"};let B=`Please analyze this codebase and generate BLADE.md content.
|
|
1355
1355
|
|
|
1356
1356
|
**Important**: After each step, briefly describe what you found before proceeding.
|
|
1357
1357
|
|
|
@@ -1397,7 +1397,7 @@ ${J}
|
|
|
1397
1397
|
- Focus on non-obvious insights
|
|
1398
1398
|
- Be concise but comprehensive for complex projects
|
|
1399
1399
|
|
|
1400
|
-
**Final output**: Return ONLY the complete BLADE.md content (markdown format), ready to be written to the file.`;Q1.info(`[/init] Starting agent.chatStream for new BLADE.md, signal.aborted: ${Y?.aborted}`);let G=(await h0(V.chatStream(B,{messages:[],userId:"cli-user",sessionId:H||"init-session",workspaceRoot:J,signal:Y}),async(O)=>{switch(O.kind){case"tool_start":{let E=O.toolCall;if(!("function"in E))return;try{let q=JSON.parse(E.function.arguments),
|
|
1400
|
+
**Final output**: Return ONLY the complete BLADE.md content (markdown format), ready to be written to the file.`;Q1.info(`[/init] Starting agent.chatStream for new BLADE.md, signal.aborted: ${Y?.aborted}`);let G=(await h0(V.chatStream(B,{messages:[],userId:"cli-user",sessionId:H||"init-session",workspaceRoot:J,signal:Y}),async(O)=>{switch(O.kind){case"tool_start":{let E=O.toolCall;if(!("function"in E))return;try{let q=JSON.parse(E.function.arguments),D=N6(E.function.name,q);X(D)}catch{}break}case"tool_result":{if(!("function"in O.toolCall))return;let q=O.result?.metadata;if(q?.summary){if(typeof q.summary==="string")X(q.summary)}break}default:break}})).finalMessage||"";if(Q1.info(`[/init] agent.chatStream completed for new BLADE.md, signal.aborted: ${Y?.aborted}`),Y?.aborted)return Q1.info("[/init] Returning cancelled after agent.chat (new BLADE.md)"),{success:!1,message:"操作已取消"};if(!G||G.trim().length===0)throw Error("Agent 未能生成有效的 BLADE.md 内容");return U.sendMessage("正在写入 BLADE.md..."),await x1.writeFile(Q,G,"utf-8"),{success:!0,message:"[OK] 已成功生成 BLADE.md 文件"}}catch(J){return{success:!1,error:`初始化失败: ${J instanceof Error?J.message:"未知错误"}`}}}},$3=WW;var zW={name:"model",description:"管理和切换模型配置",usage:"/model [子命令] [参数]",fullDescription:`
|
|
1401
1401
|
管理和切换模型配置
|
|
1402
1402
|
|
|
1403
1403
|
子命令:
|
|
@@ -1418,8 +1418,8 @@ ${J}
|
|
|
1418
1418
|
`,async handler($,Z){let J=$[0];if(!J){if(Z1().length===0)return{success:!1,message:`没有可用的模型配置
|
|
1419
1419
|
|
|
1420
1420
|
使用 /model add 添加模型`};return{success:!0,message:"show_model_selector",data:{action:"show_model_selector"}}}switch(J){case"add":return{success:!0,message:"show_model_add_wizard",data:{action:"show_model_add_wizard",mode:"add"}};case"remove":{let Y=$.slice(1).join(" ");if(!Y)return{success:!1,message:`请指定要删除的模型名称
|
|
1421
|
-
用法: /model remove <名称>`};let X=Z1().find((H)=>
|
|
1422
|
-
`)}}if(!U||!X.modelProviders[U])return{success:!1,message:`未找到 Provider 渠道: ${U??""}`};if(Y==="test"){let H=X.models.find((W)=>W.provider===U);if(!H)return{success:!1,message:`Provider 渠道没有可探测模型: ${U}`};let Q=await h2(H,X,{timeoutMs:1e4});return{success:Q.ok,message:Q.ok?`[OK] ${U} · ${Q.latencyMs}ms · ${Q.wireApi}`:`[FAIL] ${U} · ${Q.message} [${Q.code}]`}}if(Y==="set"){let H=$[3];if(!H)return{success:!1,message:"用法: /model provider set <ID> <Base URL>"};let Q=X.modelProviders[U];try{return await
|
|
1421
|
+
用法: /model remove <名称>`};let X=Z1().find((H)=>C$(H).toLowerCase().includes(Y.toLowerCase()));if(!X)return{success:!1,message:`未找到匹配的模型配置: ${Y}`};try{return await a$().removeModel(X.id),{success:!0,message:`[OK] 已删除模型配置: ${C$(X)}`}}catch(H){return{success:!1,message:`${H.message}`}}}case"once":{let Y=$[1],U=$.slice(2).join(" ").trim();if(!Y||!U)return{success:!1,message:"用法: /model once <模型> <内容>"};let X=Z1(),H=X.find((Q)=>Q.id===Y)||X.find((Q)=>C$(Q).toLowerCase().includes(Y.toLowerCase()));if(!H)return{success:!1,message:`未找到匹配的模型配置: ${Y}`};return{success:!0,data:{action:"invoke_once_model",modelId:H.id,prompt:U}}}case"provider":{let Y=$[1],U=$[2],X=W0();if(!X)return{success:!1,message:"配置尚未初始化"};if(!Y||Y==="list"){let H=Object.entries(X.modelProviders);if(H.length===0)return{success:!0,message:"没有配置自定义 Provider 渠道"};return{success:!0,message:H.map(([Q,W])=>`${Q} · ${W.name} · ${W.wireApi} · ${W.baseUrl}`).join(`
|
|
1422
|
+
`)}}if(!U||!X.modelProviders[U])return{success:!1,message:`未找到 Provider 渠道: ${U??""}`};if(Y==="test"){let H=X.models.find((W)=>W.provider===U);if(!H)return{success:!1,message:`Provider 渠道没有可探测模型: ${U}`};let Q=await h2(H,X,{timeoutMs:1e4});return{success:Q.ok,message:Q.ok?`[OK] ${U} · ${Q.latencyMs}ms · ${Q.wireApi}`:`[FAIL] ${U} · ${Q.message} [${Q.code}]`}}if(Y==="set"){let H=$[3];if(!H)return{success:!1,message:"用法: /model provider set <ID> <Base URL>"};let Q=X.modelProviders[U];try{return await a$().updateModelProvider(U,{...Q,baseUrl:H}),{success:!0,message:`[OK] 已更新 Provider endpoint: ${U}`}}catch(W){return{success:!1,message:W instanceof Error?W.message:"更新失败"}}}if(Y==="remove"){let H=$.includes("--with-models");try{let Q=await a$().removeModelProvider(U,{removeModels:H});return{success:!0,message:`[OK] 已删除 Provider 渠道: ${U}`+(Q.removedModelIds.length>0?`;同时删除 ${Q.removedModelIds.length} 个模型配置`:"")}}catch(Q){return{success:!1,message:Q instanceof Error?Q.message:"删除失败"}}}return{success:!1,message:"用法: /model provider <list|test|set|remove> [ID] [参数]"}}default:return{success:!1,message:`未知的子命令: ${J}
|
|
1423
1423
|
使用 /model 查看可用操作`}}}},Z3=zW;var VW={name:"plugins",description:"管理已安装的插件",fullDescription:`管理 Blade Code 插件系统。
|
|
1424
1424
|
|
|
1425
1425
|
子命令:
|
|
@@ -1446,10 +1446,10 @@ ${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 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-
|
|
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=
|
|
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-v0ygsjry.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=m$(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
|
-
`)}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(),
|
|
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(),l$(Z.workspaceRoot??Z.cwd),await i$(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
|
|
1454
1454
|
`),W.push("| ID | 状态 | 命令 | PID | 运行时间 |"),W.push("|:---|:-----|:-----|:----|:---------|");for(let G of z){let O=G.endTime?i2(G.endTime-G.startTime):i2(Date.now()-G.startTime),E=B3(G.status);W.push(`| \`${G.id.slice(0,12)}...\` | ${E} ${G.status} | \`${K3(G.command,30)}\` | ${G.pid||"-"} | ${O} |`)}W.push("")}let V=Z.subagents?await Z.subagents.list():X.listForSession(Q??H);if(V.length>0){W.push(`### Agents
|
|
1455
1455
|
`),W.push("| ID | 状态 | 类型 | 描述 | Lineage | 运行时间 |"),W.push("|:---|:-----|:-----|:-----|:--------|:---------|");for(let G of V){let O=G.completedAt?i2(G.completedAt-G.createdAt):i2(Date.now()-G.createdAt),E=B3(G.status),q=G.resumedFrom?`↳ ${G.resumedFrom.slice(0,8)} (depth ${G.resumeDepth})`:"root";W.push(`| \`${G.id.slice(0,12)}...\` | ${E} ${G.status} | ${G.subagentType} | ${K3(G.description,25)} | ${q} | ${O} |`)}W.push("")}let B=z.filter((G)=>G.status==="running").length,K=V.filter((G)=>G.status==="running").length;if(z.length===0&&V.length===0)W.push(`*暂无后台任务*
|
|
@@ -1477,8 +1477,8 @@ ${J}
|
|
|
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 AT($){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,T0 as u,
|
|
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 LT($,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 NT($=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 bT($,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),D=O.item;return{command:`/${D.name}`,description:D.label?`${D.description} ${D.label}`:D.description,argumentHint:D.argumentHint,matchScore:q}}).filter((O)=>(O.matchScore||0)>=40)}
|
|
1484
|
+
export{MV as r,O$ as s,I as t,T0 as u,v$ as v,GY as w,s as x,KO as y,E0 as z,t0 as A,d$ as B,S8 as C,$1 as D,L$ 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,pN as V,h6 as W,AT as X,mW as Y,LT as Z,NT as _,bT as $};
|