blade-code 0.10.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-yvah5h4x.js → chunk-11qty4fd.js} +1 -1
  3. package/dist/{chunk-z5ae4qvf.js → chunk-29r7z43j.js} +1 -1
  4. package/dist/{chunk-hzvp3bc1.js → chunk-3nx2579c.js} +1 -1
  5. package/dist/{chunk-vyq9r31h.js → chunk-49sytjma.js} +1 -1
  6. package/dist/{chunk-mxhg6jt9.js → chunk-51wa5fct.js} +1 -1
  7. package/dist/{chunk-6qe5k7dw.js → chunk-5pvxw7sd.js} +2 -2
  8. package/dist/{chunk-949btxxx.js → chunk-793k86j6.js} +3 -3
  9. package/dist/chunk-859m18ra.js +160 -0
  10. package/dist/{chunk-bx50res5.js → chunk-a8y9xbxw.js} +1 -1
  11. package/dist/{chunk-93ptxa5p.js → chunk-dnhb7k9g.js} +1 -1
  12. package/dist/{chunk-7dcm1aqd.js → chunk-f19yx9an.js} +1 -1
  13. package/dist/chunk-g0jb7v73.js +1 -0
  14. package/dist/{chunk-7eptyk20.js → chunk-g2972yzq.js} +1 -1
  15. package/dist/{chunk-v4mr98vm.js → chunk-gv8gfnz8.js} +1 -1
  16. package/dist/{chunk-0aj7gp37.js → chunk-h7kj4gvj.js} +1 -1
  17. package/dist/{chunk-mvwp3c11.js → chunk-hefv4415.js} +1 -1
  18. package/dist/{chunk-ty2kc6kg.js → chunk-j457sh1b.js} +1 -1
  19. package/dist/{chunk-e3tk2jna.js → chunk-j51fwecz.js} +1 -1
  20. package/dist/{chunk-8rg05w47.js → chunk-jzrqjzjm.js} +1 -1
  21. package/dist/{chunk-vb0t2hhd.js → chunk-k6qwdjyy.js} +1 -1
  22. package/dist/{chunk-61087jc8.js → chunk-km7m66vw.js} +1 -1
  23. package/dist/{chunk-3c5gvxr6.js → chunk-m3g8hz67.js} +1 -1
  24. package/dist/{chunk-9jy87d0y.js → chunk-mrpvdvn4.js} +1 -1
  25. package/dist/{chunk-hh3xw391.js → chunk-mz1jrcgc.js} +1 -1
  26. package/dist/{chunk-2fdjn926.js → chunk-p6yed31x.js} +1 -1
  27. package/dist/{chunk-zcw7kyf4.js → chunk-pms05z02.js} +1 -1
  28. package/dist/{chunk-9kd14cwq.js → chunk-qk0akpsg.js} +1 -1
  29. package/dist/{chunk-bqdc3m0p.js → chunk-rppak8ep.js} +1 -1
  30. package/dist/{chunk-w4qsayn6.js → chunk-t7ej11xd.js} +1 -1
  31. package/dist/{chunk-cznge1n7.js → chunk-tkd04sjm.js} +1 -1
  32. package/dist/{chunk-mwrn7mcr.js → chunk-tkr4d9ej.js} +1 -1
  33. package/dist/{chunk-f8db8ftd.js → chunk-w1wp1t52.js} +1 -1
  34. package/package.json +1 -1
  35. package/dist/chunk-fjp5tvh8.js +0 -1
  36. package/dist/chunk-wsqz3x2e.js +0 -161
package/dist/blade.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{Hb as W}from"./chunk-61087jc8.js";import{Kb as F,Lb as M}from"./chunk-kq5my0yy.js";import"./chunk-vb0t2hhd.js";import"./chunk-gafbzeyk.js";import"./chunk-0h81hxkw.js";import"./chunk-mvwp3c11.js";import"./chunk-beqaxytd.js";import{cd as T}from"./chunk-jxv6r0c7.js";import"./chunk-hzvp3bc1.js";import"./chunk-4vaywb2r.js";import"./chunk-qev36qrb.js";import{ge as N,he as B}from"./chunk-vjpd3nee.js";import"./chunk-a7nbn5kf.js";import"./chunk-2beq0syt.js";import"./chunk-0aj7gp37.js";import"./chunk-6hj2dk75.js";import"./chunk-6n5xdf2r.js";import"./chunk-8nm1hqr1.js";import{Le as K}from"./chunk-mjp61rqd.js";import C from"node:path";var E=process.argv.slice(2),I=p(E),v=I!==null;if(I!==null)T.setGlobalDebug(I);function p(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function u(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function c(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function m(){if(u(E)){let{getVersion:J}=await import("./chunk-7dcm1aqd.js");console.log(J());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=c(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:J}=await import("./chunk-mwrn7mcr.js");J(U.map((Z)=>C.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:J}=await import("./chunk-6g21dh3n.js");await J.getInstance().trust(B())}if(process.getuid&&process.getuid()===0){let J=!!process.env.SUDO_USER,Z=!!process.env.BLADE_ALLOW_ROOT;if(J&&!Z)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(q(E,"--headless")){let{handleHeadlessMode:J}=await import("./chunk-bqdc3m0p.js");if(await J())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:J}=await import("./chunk-w4qsayn6.js");if(await J())return}if(E.includes("--acp")){let{runAcpIntegration:J}=await import("./chunk-vyq9r31h.js");await J();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{doctorCommands:S},{installCommands:k},{mcpCommands:O},{projectsCommands:y},{serveCommand:b},{updateCommands:V},{webCommand:P}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-fjp5tvh8.js"),import("./chunk-2fdjn926.js"),import("./chunk-6qe5k7dw.js"),import("./chunk-d3236505.js"),import("./chunk-yvah5h4x.js"),import("./chunk-vvy506b3.js"),import("./chunk-7eptyk20.js"),import("./chunk-zkbf8n6y.js"),import("./chunk-f8db8ftd.js")]),x=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(O).command(y).command(S).command(V).command(k).command(P).command(b).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((J,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),v&&Z.stack)console.error(`
2
+ import{Hb as W}from"./chunk-km7m66vw.js";import{Kb as F,Lb as M}from"./chunk-kq5my0yy.js";import"./chunk-k6qwdjyy.js";import"./chunk-gafbzeyk.js";import"./chunk-0h81hxkw.js";import"./chunk-hefv4415.js";import"./chunk-beqaxytd.js";import{cd as T}from"./chunk-jxv6r0c7.js";import"./chunk-3nx2579c.js";import"./chunk-4vaywb2r.js";import"./chunk-qev36qrb.js";import{ge as N,he as B}from"./chunk-vjpd3nee.js";import"./chunk-a7nbn5kf.js";import"./chunk-2beq0syt.js";import"./chunk-h7kj4gvj.js";import"./chunk-6hj2dk75.js";import"./chunk-6n5xdf2r.js";import"./chunk-8nm1hqr1.js";import{Le as K}from"./chunk-mjp61rqd.js";import C from"node:path";var E=process.argv.slice(2),I=p(E),v=I!==null;if(I!==null)T.setGlobalDebug(I);function p(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function u(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function c(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function m(){if(u(E)){let{getVersion:J}=await import("./chunk-f19yx9an.js");console.log(J());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=c(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:J}=await import("./chunk-tkr4d9ej.js");J(U.map((Z)=>C.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:J}=await import("./chunk-6g21dh3n.js");await J.getInstance().trust(B())}if(process.getuid&&process.getuid()===0){let J=!!process.env.SUDO_USER,Z=!!process.env.BLADE_ALLOW_ROOT;if(J&&!Z)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(q(E,"--headless")){let{handleHeadlessMode:J}=await import("./chunk-rppak8ep.js");if(await J())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:J}=await import("./chunk-t7ej11xd.js");if(await J())return}if(E.includes("--acp")){let{runAcpIntegration:J}=await import("./chunk-49sytjma.js");await J();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{doctorCommands:S},{installCommands:k},{mcpCommands:O},{projectsCommands:y},{serveCommand:b},{updateCommands:V},{webCommand:P}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-g0jb7v73.js"),import("./chunk-p6yed31x.js"),import("./chunk-5pvxw7sd.js"),import("./chunk-d3236505.js"),import("./chunk-11qty4fd.js"),import("./chunk-vvy506b3.js"),import("./chunk-g2972yzq.js"),import("./chunk-zkbf8n6y.js"),import("./chunk-w1wp1t52.js")]),x=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(O).command(y).command(S).command(V).command(k).command(P).command(b).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((J,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),v&&Z.stack)console.error(`
3
3
  Stack trace:`),console.error(Z.stack);else console.error(`
4
4
  Run with --debug to show the stack trace.`);process.exit(1)}if(J)console.error("Error: Invalid arguments:"),console.error(J),console.error(`
5
- Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(J)=>{let Z=J._.slice(1),L=Z.length>0?Z.join(" "):void 0,h=import("./chunk-m78ceafk.js").then(({checkVersionOnStartup:j})=>j()),[{render:A},{createElement:w},{AppWrapper:f}]=await Promise.all([import("ink"),import("react"),import("./chunk-wsqz3x2e.js")]),H={...J,initialMessage:L,debug:J.debug,print:Boolean(J.print),versionCheckPromise:h};delete H._,delete H.$0,delete H.message,A(w(f,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await x.parse()}catch(J){console.error("Error: Parse error:",J),process.exit(1)}}if(K.main==K.module)m().catch(console.error);export{m as main};
5
+ Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(J)=>{let Z=J._.slice(1),L=Z.length>0?Z.join(" "):void 0,h=import("./chunk-m78ceafk.js").then(({checkVersionOnStartup:j})=>j()),[{render:A},{createElement:w},{AppWrapper:f}]=await Promise.all([import("ink"),import("react"),import("./chunk-859m18ra.js")]),H={...J,initialMessage:L,debug:J.debug,print:Boolean(J.print),versionCheckPromise:h};delete H._,delete H.$0,delete H.message,A(w(f,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await x.parse()}catch(J){console.error("Error: Parse error:",J),process.exit(1)}}if(K.main==K.module)m().catch(console.error);export{m as main};
@@ -1,4 +1,4 @@
1
- import{ia as H}from"./chunk-mxhg6jt9.js";import"./chunk-88vy9hh0.js";import{ec as $,kc as T}from"./chunk-vb0t2hhd.js";import"./chunk-gafbzeyk.js";import"./chunk-0h81hxkw.js";import"./chunk-mvwp3c11.js";import"./chunk-beqaxytd.js";import"./chunk-jxv6r0c7.js";import"./chunk-hzvp3bc1.js";import"./chunk-4vaywb2r.js";import"./chunk-qev36qrb.js";import{he as k}from"./chunk-vjpd3nee.js";import"./chunk-a7nbn5kf.js";import"./chunk-2beq0syt.js";import"./chunk-0aj7gp37.js";import"./chunk-6hj2dk75.js";import"./chunk-6n5xdf2r.js";import"./chunk-8nm1hqr1.js";import"./chunk-mjp61rqd.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
1
+ import{ia as H}from"./chunk-51wa5fct.js";import"./chunk-88vy9hh0.js";import{ec as $,kc as T}from"./chunk-k6qwdjyy.js";import"./chunk-gafbzeyk.js";import"./chunk-0h81hxkw.js";import"./chunk-hefv4415.js";import"./chunk-beqaxytd.js";import"./chunk-jxv6r0c7.js";import"./chunk-3nx2579c.js";import"./chunk-4vaywb2r.js";import"./chunk-qev36qrb.js";import{he as k}from"./chunk-vjpd3nee.js";import"./chunk-a7nbn5kf.js";import"./chunk-2beq0syt.js";import"./chunk-h7kj4gvj.js";import"./chunk-6hj2dk75.js";import"./chunk-6n5xdf2r.js";import"./chunk-8nm1hqr1.js";import"./chunk-mjp61rqd.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
2
2
  blade mcp
3
3
  `),console.log(`管理 MCP 服务器
4
4
  `),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
@@ -1,2 +1,2 @@
1
- import{Rd as F}from"./chunk-hzvp3bc1.js";import{le as D,me as E}from"./chunk-a7nbn5kf.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
1
+ import{Rd as F}from"./chunk-3nx2579c.js";import{le as D,me as E}from"./chunk-a7nbn5kf.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
2
2
  export{H as xc,Q as yc,T as zc};
@@ -1,4 +1,4 @@
1
- import{$d as Zn,Ud as rn,Vd as D,Wd as m,ae as Jn}from"./chunk-4vaywb2r.js";import{be as Nn,ce as pn}from"./chunk-qev36qrb.js";import{he as b}from"./chunk-vjpd3nee.js";import{je as Dn,me as H}from"./chunk-a7nbn5kf.js";import{ue as En,ve as fn}from"./chunk-0aj7gp37.js";import{ze as P}from"./chunk-6hj2dk75.js";import{Je as un}from"./chunk-8nm1hqr1.js";var Qn=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Wn(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function I(n,t="MCP OAuth URL"){let e=new URL(n);if(e.username||e.password)throw Error(`${t} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&Wn(e.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var B=async(n,t)=>{I(n,"MCP OAuth request URL");let e=await fetch(n,{...t,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function q(n){let t=n.oauth;if(!t)return;let e=t;for(let o of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[o]!==void 0)throw Error(`MCP OAuth "${o}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(I(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((o)=>o.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let u=t.clientId?.trim();if(u&&u.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let _=t.scopes?.map((o)=>o.trim());if(_){if(_.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(_.some((o)=>!o||o.length>128||!Qn.test(o)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(_).size!==_.length)throw Error("MCP OAuth scopes must not contain duplicates")}let M=t.callbackPort;if(M!==void 0&&(!Number.isInteger(M)||M<1024||M>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...u?{clientId:u}:{},..._?.length?{scopes:_}:{},...M!==void 0?{callbackPort:M}:{}}}import{randomUUID as J}from"node:crypto";import it from"node:http";import{auth as on}from"@modelcontextprotocol/sdk/client/auth.js";import St from"open";import{createHash as jn,randomUUID as Fn}from"node:crypto";import{constants as O,promises as A}from"node:fs";import Y from"node:path";import{Mutex as vn}from"async-mutex";import nt from"write-file-atomic";var Mn=1,tt=1048576,et=5000,ut=50,rt=/^[a-f0-9]{64}$/,Mt=m.Object({client_id:m.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),_t=m.Object({access_token:m.String({minLength:1,maxLength:65536}),token_type:m.String({minLength:1,maxLength:64}),expires_in:m.Optional(m.Number({minimum:0})),refresh_token:m.Optional(m.String({minLength:1,maxLength:65536})),scope:m.Optional(m.String({maxLength:16384})),id_token:m.Optional(m.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),ot=m.Unsafe({type:"object",properties:{authorizationServerUrl:m.String({format:"uri"}),resourceMetadataUrl:m.Optional(m.String({format:"uri"})),resourceMetadata:m.Optional(m.Unknown()),authorizationServerMetadata:m.Optional(m.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),_n=m.Object({serverUrl:m.String({format:"uri"}),clientId:m.Optional(m.String({minLength:1,maxLength:4096})),clientInformation:m.Optional(Mt),tokens:m.Optional(_t),tokenExpiresAt:m.Optional(m.Number({minimum:0})),discoveryState:m.Optional(ot),updatedAt:m.String({format:"date-time"})},{additionalProperties:!1}),tn=m.Object({version:m.Literal(Mn),credentials:m.Record(m.String(),_n)},{additionalProperties:!1});function y(n,t){return n instanceof Error&&"code"in n&&n.code===t}function st(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return y(t,"EPERM")}}function V(n){return structuredClone(n)}function en(n){if(Object.keys(n.credentials).some((t)=>!rt.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function K(n){let t=new URL(n);return t.hash="",t.toString()}function Z(n,t,e=[]){return jn("sha256").update(JSON.stringify({serverUrl:K(n),clientId:t?.trim()||null,scopes:[...e].sort()})).digest("hex")}class x{static mutexes=new Map;stateRoot;tokenFilePath;mutex;constructor(n=un()){this.stateRoot=Y.join(n,"mcp"),this.tokenFilePath=Y.join(this.stateRoot,"oauth-credentials.json");let t=x.mutexes.get(this.tokenFilePath);if(!t)t=new vn,x.mutexes.set(this.tokenFilePath,t);this.mutex=t}async getCredential(n){return this.mutex.runExclusive(async()=>{let e=(await this.readStore()).credentials[n];return e?V(e):null})}async updateCredential(n,t){return this.runMutation(async(e)=>{let r=e.credentials[n],u=await t(r?V(r):null);if(u)e.credentials[n]=D(_n,u);else delete e.credentials[n];return u?V(e.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return this.mutex.runExclusive(async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return this.mutex.runExclusive(async()=>{let t=await this.acquireStoreLock();try{let e=await this.readStore(),r=await n(e);return await this.writeStore(e),r}finally{await t()}})}async ensureStateRoot(){await A.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await A.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await A.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>tt)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await A.readFile(this.tokenFilePath,"utf8")),e=rn(tn,t);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return en(e.data),e.data}catch(n){if(y(n,"ENOENT"))return{version:Mn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=D(tn,n);en(t),await nt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
1
+ import{$d as Zn,Ud as rn,Vd as D,Wd as m,ae as Jn}from"./chunk-4vaywb2r.js";import{be as Nn,ce as pn}from"./chunk-qev36qrb.js";import{he as b}from"./chunk-vjpd3nee.js";import{je as Dn,me as H}from"./chunk-a7nbn5kf.js";import{ue as En,ve as fn}from"./chunk-h7kj4gvj.js";import{ze as P}from"./chunk-6hj2dk75.js";import{Je as un}from"./chunk-8nm1hqr1.js";var Qn=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Wn(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function I(n,t="MCP OAuth URL"){let e=new URL(n);if(e.username||e.password)throw Error(`${t} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&Wn(e.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var B=async(n,t)=>{I(n,"MCP OAuth request URL");let e=await fetch(n,{...t,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function q(n){let t=n.oauth;if(!t)return;let e=t;for(let o of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[o]!==void 0)throw Error(`MCP OAuth "${o}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(I(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((o)=>o.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let u=t.clientId?.trim();if(u&&u.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let _=t.scopes?.map((o)=>o.trim());if(_){if(_.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(_.some((o)=>!o||o.length>128||!Qn.test(o)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(_).size!==_.length)throw Error("MCP OAuth scopes must not contain duplicates")}let M=t.callbackPort;if(M!==void 0&&(!Number.isInteger(M)||M<1024||M>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...u?{clientId:u}:{},..._?.length?{scopes:_}:{},...M!==void 0?{callbackPort:M}:{}}}import{randomUUID as J}from"node:crypto";import it from"node:http";import{auth as on}from"@modelcontextprotocol/sdk/client/auth.js";import St from"open";import{createHash as jn,randomUUID as Fn}from"node:crypto";import{constants as O,promises as A}from"node:fs";import Y from"node:path";import{Mutex as vn}from"async-mutex";import nt from"write-file-atomic";var Mn=1,tt=1048576,et=5000,ut=50,rt=/^[a-f0-9]{64}$/,Mt=m.Object({client_id:m.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),_t=m.Object({access_token:m.String({minLength:1,maxLength:65536}),token_type:m.String({minLength:1,maxLength:64}),expires_in:m.Optional(m.Number({minimum:0})),refresh_token:m.Optional(m.String({minLength:1,maxLength:65536})),scope:m.Optional(m.String({maxLength:16384})),id_token:m.Optional(m.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),ot=m.Unsafe({type:"object",properties:{authorizationServerUrl:m.String({format:"uri"}),resourceMetadataUrl:m.Optional(m.String({format:"uri"})),resourceMetadata:m.Optional(m.Unknown()),authorizationServerMetadata:m.Optional(m.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),_n=m.Object({serverUrl:m.String({format:"uri"}),clientId:m.Optional(m.String({minLength:1,maxLength:4096})),clientInformation:m.Optional(Mt),tokens:m.Optional(_t),tokenExpiresAt:m.Optional(m.Number({minimum:0})),discoveryState:m.Optional(ot),updatedAt:m.String({format:"date-time"})},{additionalProperties:!1}),tn=m.Object({version:m.Literal(Mn),credentials:m.Record(m.String(),_n)},{additionalProperties:!1});function y(n,t){return n instanceof Error&&"code"in n&&n.code===t}function st(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return y(t,"EPERM")}}function V(n){return structuredClone(n)}function en(n){if(Object.keys(n.credentials).some((t)=>!rt.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function K(n){let t=new URL(n);return t.hash="",t.toString()}function Z(n,t,e=[]){return jn("sha256").update(JSON.stringify({serverUrl:K(n),clientId:t?.trim()||null,scopes:[...e].sort()})).digest("hex")}class x{static mutexes=new Map;stateRoot;tokenFilePath;mutex;constructor(n=un()){this.stateRoot=Y.join(n,"mcp"),this.tokenFilePath=Y.join(this.stateRoot,"oauth-credentials.json");let t=x.mutexes.get(this.tokenFilePath);if(!t)t=new vn,x.mutexes.set(this.tokenFilePath,t);this.mutex=t}async getCredential(n){return this.mutex.runExclusive(async()=>{let e=(await this.readStore()).credentials[n];return e?V(e):null})}async updateCredential(n,t){return this.runMutation(async(e)=>{let r=e.credentials[n],u=await t(r?V(r):null);if(u)e.credentials[n]=D(_n,u);else delete e.credentials[n];return u?V(e.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return this.mutex.runExclusive(async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return this.mutex.runExclusive(async()=>{let t=await this.acquireStoreLock();try{let e=await this.readStore(),r=await n(e);return await this.writeStore(e),r}finally{await t()}})}async ensureStateRoot(){await A.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await A.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await A.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>tt)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await A.readFile(this.tokenFilePath,"utf8")),e=rn(tn,t);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return en(e.data),e.data}catch(n){if(y(n,"ENOENT"))return{version:Mn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=D(tn,n);en(t),await nt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
2
2
  `,{mode:384,encoding:"utf8"}),await A.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=Y.join(this.stateRoot,".oauth-credentials.lock"),t=Fn(),e=Date.now()+et;while(Date.now()<e)try{let r=await A.open(n,O.O_CREAT|O.O_EXCL|O.O_WRONLY,384);return await r.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
3
3
  `,"utf8"),await r.close(),async()=>{try{if(JSON.parse(await A.readFile(n,"utf8")).token===t)await A.unlink(n)}catch(u){if(!y(u,"ENOENT"))throw u}}}catch(r){if(!y(r,"EEXIST"))throw r;await this.removeDeadLock(n),await new Promise((u)=>setTimeout(u,ut))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await A.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let e=JSON.parse(await A.readFile(n,"utf8"));if(typeof e.pid!=="number"||!Number.isInteger(e.pid)||e.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!st(e.pid))await A.unlink(n)}}var sn="127.0.0.1",Sn=7777,mn="/oauth/callback",mt=300000;class Q extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class an extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function Et(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
4
4
  <html lang="en">
@@ -1,4 +1,4 @@
1
- import{q as o}from"./chunk-zcw7kyf4.js";import{E as y,G as k,H as S,J as C,X as f,Y as u,Z as g,_ as c,t as K}from"./chunk-949btxxx.js";import{ia as n}from"./chunk-mxhg6jt9.js";import{qa as T,ta as M}from"./chunk-8rg05w47.js";import{La as A}from"./chunk-88vy9hh0.js";import{$a as I,_a as E,db as V,gb as U}from"./chunk-bx50res5.js";import"./chunk-44wkjs2j.js";import"./chunk-kq5my0yy.js";import"./chunk-vb0t2hhd.js";import"./chunk-gafbzeyk.js";import{mc as i}from"./chunk-0h81hxkw.js";import"./chunk-af49jmns.js";import"./chunk-px5ck9pf.js";import{vc as a}from"./chunk-fjw32ex5.js";import"./chunk-z5ae4qvf.js";import"./chunk-e3tk2jna.js";import{Sc as r}from"./chunk-d9ddpapp.js";import"./chunk-sndbq5xt.js";import"./chunk-mvwp3c11.js";import"./chunk-beqaxytd.js";import{dd as R}from"./chunk-jxv6r0c7.js";import"./chunk-hzvp3bc1.js";import"./chunk-4vaywb2r.js";import{be as q,ce as h,de as N}from"./chunk-qev36qrb.js";import{he as m}from"./chunk-vjpd3nee.js";import"./chunk-a7nbn5kf.js";import{ne as d,qe as l}from"./chunk-2beq0syt.js";import"./chunk-0aj7gp37.js";import"./chunk-6hj2dk75.js";import"./chunk-6n5xdf2r.js";import"./chunk-8nm1hqr1.js";import"./chunk-mjp61rqd.js";import{Readable as zJ,Writable as WJ}from"node:stream";import*as O from"@agentclientprotocol/sdk";import p from"node:path";import{PROTOCOL_VERSION as $J}from"@agentclientprotocol/sdk";import{nanoid as P}from"nanoid";var G=R("Agent");function x(J){if(!J)return{};return Object.fromEntries(J.map((Z)=>[Z.name,Z.value]))}function e(J){if("command"in J)return{type:"stdio",command:J.command,args:J.args,env:x(J.env)};if("url"in J)return{type:J.type,url:J.url,headers:x("headers"in J?J.headers:void 0)};return null}function JJ(J){let Z={};for(let Q of J){let $=e(Q);if($)Z[Q.name]=$}return Z}function v(J){if(typeof J==="string")return J?[{type:"text",text:J}]:[];return J.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let Q=Z.image_url.url,$=/^data:([^;,]+);base64,(.+)$/s.exec(Q);if(!$)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:$[1]??"image/png",data:$[2]??""}]})}function QJ(J){let Z=I(J.metadata);return Z?[{type:"text",text:E(Z)}]:v(J.content)}function ZJ(J){return[`Status: ${J.status}`,`Exit code: ${J.exitCode??"null"}`,`Duration: ${(J.durationMs/1000).toFixed(3)} seconds`].join(`
1
+ import{q as o}from"./chunk-pms05z02.js";import{E as y,G as k,H as S,J as C,X as f,Y as u,Z as g,_ as c,t as K}from"./chunk-793k86j6.js";import{ia as n}from"./chunk-51wa5fct.js";import{qa as T,ta as M}from"./chunk-jzrqjzjm.js";import{La as A}from"./chunk-88vy9hh0.js";import{$a as I,_a as E,db as V,gb as U}from"./chunk-a8y9xbxw.js";import"./chunk-44wkjs2j.js";import"./chunk-kq5my0yy.js";import"./chunk-k6qwdjyy.js";import"./chunk-gafbzeyk.js";import{mc as i}from"./chunk-0h81hxkw.js";import"./chunk-af49jmns.js";import"./chunk-px5ck9pf.js";import{vc as a}from"./chunk-fjw32ex5.js";import"./chunk-29r7z43j.js";import"./chunk-j51fwecz.js";import{Sc as r}from"./chunk-d9ddpapp.js";import"./chunk-sndbq5xt.js";import"./chunk-hefv4415.js";import"./chunk-beqaxytd.js";import{dd as R}from"./chunk-jxv6r0c7.js";import"./chunk-3nx2579c.js";import"./chunk-4vaywb2r.js";import{be as q,ce as h,de as N}from"./chunk-qev36qrb.js";import{he as m}from"./chunk-vjpd3nee.js";import"./chunk-a7nbn5kf.js";import{ne as d,qe as l}from"./chunk-2beq0syt.js";import"./chunk-h7kj4gvj.js";import"./chunk-6hj2dk75.js";import"./chunk-6n5xdf2r.js";import"./chunk-8nm1hqr1.js";import"./chunk-mjp61rqd.js";import{Readable as zJ,Writable as WJ}from"node:stream";import*as O from"@agentclientprotocol/sdk";import p from"node:path";import{PROTOCOL_VERSION as $J}from"@agentclientprotocol/sdk";import{nanoid as P}from"nanoid";var G=R("Agent");function x(J){if(!J)return{};return Object.fromEntries(J.map((Z)=>[Z.name,Z.value]))}function e(J){if("command"in J)return{type:"stdio",command:J.command,args:J.args,env:x(J.env)};if("url"in J)return{type:J.type,url:J.url,headers:x("headers"in J?J.headers:void 0)};return null}function JJ(J){let Z={};for(let Q of J){let $=e(Q);if($)Z[Q.name]=$}return Z}function v(J){if(typeof J==="string")return J?[{type:"text",text:J}]:[];return J.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let Q=Z.image_url.url,$=/^data:([^;,]+);base64,(.+)$/s.exec(Q);if(!$)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:$[1]??"image/png",data:$[2]??""}]})}function QJ(J){let Z=I(J.metadata);return Z?[{type:"text",text:E(Z)}]:v(J.content)}function ZJ(J){return[`Status: ${J.status}`,`Exit code: ${J.exitCode??"null"}`,`Duration: ${(J.durationMs/1000).toFixed(3)} seconds`].join(`
2
2
  `)}class _{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingUserShell=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;messages;mode="default";constructor(J,Z,Q,$,D={}){this.id=J;this.cwd=Z;this.connection=Q;this.clientCapabilities=$;this.options=D;this.messages=[...D.initialMessages??[]]}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return C.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){G.debug(`[AcpSession ${this.id}] Initializing...`),K.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),G.debug(`[AcpSession ${this.id}] ACP service context initialized`);let J=this.options.mcpServers?JJ(this.options.mcpServers):void 0,Z=K.getInstance().getTerminalService(this.id);this.runtime=await y.create({sessionId:this.id,workspaceRoot:this.cwd,...J?{mcpServers:J}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async($,D)=>{let z=await Z.execute($,{cwd:D.cwd,env:D.env,timeout:D.timeoutMs,signal:D.signal,allowLocalFallback:!1,onOutput:(Y)=>D.onOutput?.("stdout",Y)});return{exitCode:z.exitCode,stdout:z.stdout,stderr:z.stderr,...z.error?{error:z.error}:{},timedOut:z.error==="Command timed out",aborted:z.error==="Command was aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),this.agent=await this.createAgent(),await u(this.cwd),G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=M.subscribe(($)=>{if($.sessionId!==this.id||$.projectPath!==this.cwd)return;if($.type==="task.delivery"){if(!$.properties.taskDelivery||typeof $.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":$.properties.taskDelivery,...$.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if($.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":$.properties.taskStatus,...typeof $.properties.taskStatusReason==="string"?{"blade/taskStatusReason":$.properties.taskStatusReason}:{},...$.properties.taskFailure&&typeof $.properties.taskFailure==="object"?{"blade/taskFailure":$.properties.taskFailure}:{},...typeof $.properties.taskStartedAt==="string"?{"blade/taskStartedAt":$.properties.taskStartedAt}:{},...typeof $.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":$.properties.taskCompletedAt}:{},...$.properties.taskDiffStat&&typeof $.properties.taskDiffStat==="object"?{"blade/taskDiffStat":$.properties.taskDiffStat}:{},...typeof $.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":$.properties.taskQueuePosition}:{},...typeof $.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":$.properties.taskQueueDepth}:{},...typeof $.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":$.properties.taskConcurrencyLimit}:{},...typeof $.properties.taskInFlight==="number"?{"blade/taskInFlight":$.properties.taskInFlight}:{}}})});let Q=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||Q?.status==="active")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;let Z=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!Z)continue;for(let Q of QJ(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:Z,content:Q}))return}}if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);G.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(J,Z){try{G.debug(`[AcpSession ${this.id}] Executing slash command: ${J}`);let Q={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.messages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let W=await this.runtime.rewindSession(Y);return this.messages=[...W.messages],await this.agent?.destroy(),this.agent=await this.createAgent(),W}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Y)=>{if(await this.setReasoningEffort(Y),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Y)=>{if(await this.setServiceTier(Y),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Y)=>{if(await this.setResponseVerbosity(Y),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Y)=>{if(await this.setCommunicationStyle(Y),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Y,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let H=!1,F,j=(B)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:B.id,status:B.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:B.result?.message||B.result?.error||`Subagent ${B.status}`}}]})},X=this.runtime.resumeSubagent({agentId:Y,prompt:W,onCompleted:(B)=>{if(H)j(B);else F=B}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X.session.id,status:"in_progress",title:`Resuming ${X.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${X.source.id} at depth ${X.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),H=!0,F)j(F);return X}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Y)},getPrompt:async(Y,W,H)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Y,W,H)},complete:async(Y,W,H)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Y,W,H)},listTasks:async(Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Y)},getTask:async(Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Y)},cancelTask:async(Y,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Y,W)},getLogs:async(Y,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Y,W)},setLoggingLevel:async(Y,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Y,W)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},signal:Z,acp:{sendMessage:(Y)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y}})},sendToolStart:(Y,W,H)=>{let F=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,j=this.mapToolKind(H);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F,status:"in_progress",title:`${Y}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(W,null,2)}}],kind:j})},sendToolResult:(Y,W)=>{if(W.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.summary}})}}},$=await g(J,Q),D=$.data?.action;if(D==="start_goal"||D==="resume_goal")this.schedulePendingResume();if(D==="rewind_session"&&Array.isArray($.data?.messages))this.messages=[...$.data.messages];if(($.message==="compact_completed"||$.message==="compact_fallback")&&$.data?.compactedMessages)this.messages=[...$.data.compactedMessages];let z=$.content||$.message;if(z)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:z}});if($.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${$.error}`}});return{stopReason:$.success?"end_turn":"cancelled"}}catch(Q){return G.error(`[AcpSession ${this.id}] Slash command error:`,Q),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${Q instanceof Error?Q.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let J=c(this.cwd),Z=["model","permissions","theme","config","exit","ide"],$=J.filter((D)=>!Z.includes(D.name)).map((D)=>{let z;if(D.usage){let Y=D.usage.replace(/^\/\w+\s*/,"").trim();if(Y)z=Y}if(D.aliases?.length){let Y=`Aliases: ${D.aliases.join(", ")}`;z=z?`${z} | ${Y}`:Y}return{name:D.name,description:D.description,input:z?{hint:z}:void 0}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify($.map((D)=>D.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:$}),G.info(`[AcpSession ${this.id}] Sent ${$.length} available commands`)}catch(J){G.error(`[AcpSession ${this.id}] Failed to send available commands:`,J)}}async prompt(J,Z={}){if(K.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Q=this.resolvePrompt(J.prompt),$=Q.content,D=Q.displayText;if(D.trimStart().startsWith("!"))return this.handleUserShellCommand(D);if(this.pendingPrompt){if(/^\/goal(?:\s|$)/i.test(D.trim()))return this.handleSlashCommand(D,this.pendingPrompt.signal);let Y=await this.runtime.enqueueSteering($,{allowBeforeTurn:!0});if(!Y.accepted)throw Error(Y.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(G.debug(`[AcpSession ${this.id}] Queued steering for active turn (${Y.queued})`),Y.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let z=new AbortController;this.pendingPrompt=z;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${D.slice(0,100)}...`),f(D))return await this.handleSlashCommand(D,z.signal);let Y={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:z.signal,permissionMode:this.mapModeToPermissionMode(),...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(W)=>{return this.requestPermission(W)}}};if(await T(this.agent.chatStream($,Y,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly}),async(W)=>{switch(W.kind){case"content_delta":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:W.delta}});break;case"tool_start":{let H=W.toolCall,F=H.function.name,j=this.mapToolKind(W.toolKind),X=`Executing ${F}`;if(F==="Task"&&"function"in H)try{let B=JSON.parse(H.function.arguments),L=B.resume_from??B.resume;if(typeof L==="string")X=`Resuming ${String(B.subagent_type||"subagent")} from ${L}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:H.id,status:"in_progress",title:X,content:[],kind:j});break}case"tool_progress":{let H=W.toolCall;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:H.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:W.update.message}}]});break}case"tool_result":{let{toolCall:H,result:F}=W,j=[],X=F.metadata;if(X?.kind==="patch"&&Array.isArray(X.changes))for(let L of X.changes){if(!L||typeof L!=="object"||!("path"in L)||typeof L.path!=="string")continue;j.push({type:"diff",path:L.path,oldText:"oldContent"in L&&typeof L.oldContent==="string"?L.oldContent:null,newText:"newContent"in L&&typeof L.newContent==="string"?L.newContent:null})}else if(X?.kind==="edit"&&typeof X.file_path==="string"&&typeof X.oldContent==="string"&&(typeof X.newContent==="string"||X.newContent===void 0))j.push({type:"diff",path:X.file_path,oldText:X.oldContent,newText:X.newContent??null});else{let L=H.function.name,t=S(k(L,F));j.push({type:"content",content:{type:"text",text:t}})}let B=F.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:H.id,status:B,content:j});break}case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${W.revision} (${W.serverName}): +${W.added.length} -${W.removed.length} ~${W.updated.length}
3
3
  `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${W.contentKind} r${W.revision} (${W.serverName}): +${W.added.length} -${W.removed.length} ~${W.updated.length}
4
4
  `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${W.revision} (${W.serverName}): ${W.uri}
@@ -1,4 +1,4 @@
1
- import{Ka as jt,La as Xt,Ma as bn,Na as Tn,Oa as fn}from"./chunk-88vy9hh0.js";import{_c as Ut}from"./chunk-mvwp3c11.js";import{Cd as yn,Dd as Ht,Ed as Bt,Fd as R,Gd as qt,fd as xt,gd as tn,hd as en,id as zt,jd as B,kd as rn,ld as gt,md as mt,od as dn,pd as En,qd as U,rd as on,sd as pn,td as cn,ud as lt,vd as un,wd as Mn,xd as wn,zd as S}from"./chunk-hzvp3bc1.js";import{Ud as X,Wd as x}from"./chunk-4vaywb2r.js";import{he as vt}from"./chunk-vjpd3nee.js";import{ue as nn,ve as sn}from"./chunk-0aj7gp37.js";import{Le as ss}from"./chunk-mjp61rqd.js";import{EventEmitter as hs}from"events";import Un from"node:path";function An(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function _n(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${An(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:_n(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
1
+ import{Ka as jt,La as Xt,Ma as bn,Na as Tn,Oa as fn}from"./chunk-88vy9hh0.js";import{_c as Ut}from"./chunk-hefv4415.js";import{Cd as yn,Dd as Ht,Ed as Bt,Fd as R,Gd as qt,fd as xt,gd as tn,hd as en,id as zt,jd as B,kd as rn,ld as gt,md as mt,od as dn,pd as En,qd as U,rd as on,sd as pn,td as cn,ud as lt,vd as un,wd as Mn,xd as wn,zd as S}from"./chunk-3nx2579c.js";import{Ud as X,Wd as x}from"./chunk-4vaywb2r.js";import{he as vt}from"./chunk-vjpd3nee.js";import{ue as nn,ve as sn}from"./chunk-h7kj4gvj.js";import{Le as ss}from"./chunk-mjp61rqd.js";import{EventEmitter as hs}from"events";import Un from"node:path";function An(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function _n(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${An(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:_n(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
2
2
  ${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
3
3
  `)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor(t,i,n,s,e){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function Gt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isReadOnly:t.isReadOnly??jt(t.kind),isConcurrencySafe:t.isConcurrencySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
4
4
 
@@ -1,4 +1,4 @@
1
- import"./chunk-gafbzeyk.js";import"./chunk-jxv6r0c7.js";import{Rd as J}from"./chunk-hzvp3bc1.js";import"./chunk-4vaywb2r.js";import"./chunk-qev36qrb.js";import{he as H}from"./chunk-vjpd3nee.js";import"./chunk-a7nbn5kf.js";import"./chunk-2beq0syt.js";import"./chunk-0aj7gp37.js";import"./chunk-6hj2dk75.js";import"./chunk-6n5xdf2r.js";import"./chunk-8nm1hqr1.js";import{Le as B}from"./chunk-mjp61rqd.js";var O={command:"doctor",describe:"Check the health of your Blade installation",builder:(D)=>D.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(D)=>{if(D.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
2
- `);try{let{rebuildProjectionIndex:z}=await import("./chunk-jv4nkkb5.js"),{SessionService:F}=await import("./chunk-v4mr98vm.js"),G=await z(F.projectionDeriverForSearch());if(G===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${G} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
1
+ import"./chunk-gafbzeyk.js";import"./chunk-jxv6r0c7.js";import{Rd as J}from"./chunk-3nx2579c.js";import"./chunk-4vaywb2r.js";import"./chunk-qev36qrb.js";import{he as H}from"./chunk-vjpd3nee.js";import"./chunk-a7nbn5kf.js";import"./chunk-2beq0syt.js";import"./chunk-h7kj4gvj.js";import"./chunk-6hj2dk75.js";import"./chunk-6n5xdf2r.js";import"./chunk-8nm1hqr1.js";import{Le as B}from"./chunk-mjp61rqd.js";var O={command:"doctor",describe:"Check the health of your Blade installation",builder:(D)=>D.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(D)=>{if(D.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
2
+ `);try{let{rebuildProjectionIndex:z}=await import("./chunk-jv4nkkb5.js"),{SessionService:F}=await import("./chunk-gv8gfnz8.js"),G=await z(F.projectionDeriverForSearch());if(G===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${G} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
3
3
  `);let A=0;try{await J.getInstance().initialize(),console.log("[OK] Configuration: OK")}catch(z){console.log("[FAIL] Configuration: FAILED"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),A++}let E=process.version;if(parseInt(E.slice(1).split(".")[0])>=18)console.log(`[OK] Node.js version: ${E}`);else console.log(`[WARN] Node.js version: ${E} (recommended: v18+)`),A++;try{let z=await import("fs/promises"),F=H();await z.access(F,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("[OK] File system permissions: OK")}catch(z){console.log("[FAIL] File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),A++}try{await import("ink"),console.log("[OK] Dependencies: OK")}catch(z){console.log("[FAIL] Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),A++}if(console.log(`
4
4
  Health Check Summary:`),A===0)console.log("All checks passed! Blade is ready to use.");else console.log(`Warning: Found ${A} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};export{O as doctorCommands};
@@ -1,4 +1,4 @@
1
- import{aa as T,ba as m0,ga as M7,ha as A8,ia as y0}from"./chunk-mxhg6jt9.js";import{Aa as O7,Ha as d8,ja as O$,ma as L2,qa as d0,ta as J0,za as p2}from"./chunk-8rg05w47.js";import{Ia as $9,Ja as Z9,Ka as q6}from"./chunk-88vy9hh0.js";import{Qa as z0,Ra as Q0,Sa as a0,Ta as e2,Ua as Z1,Va as t9,Wa as e9,Xa as h2,Ya as $7,Za as Z7,ab as b7,db as J7,eb as X7,gb as n}from"./chunk-bx50res5.js";import{hb as v2,ib as s0,ob as i$,sb as B3,yb as K3}from"./chunk-44wkjs2j.js";import{Jb as t4,Kb as o4}from"./chunk-kq5my0yy.js";import{$b as B0,Wb as A2,Xb as H0,Yb as C,ac as D2,bc as W1,cc as b$,dc as L6,ec as v$,fc as u8,kc as F$}from"./chunk-vb0t2hhd.js";import{lc as g$}from"./chunk-gafbzeyk.js";import{mc as H$}from"./chunk-0h81hxkw.js";import{qc as V7,rc as _2}from"./chunk-af49jmns.js";import{tc as b0,uc as R$}from"./chunk-px5ck9pf.js";import{vc as G7}from"./chunk-fjw32ex5.js";import{xc as n9,yc as r9,zc as a9}from"./chunk-z5ae4qvf.js";import{Ac as T$,Bc as W9,Dc as P0,Ec as N3,Fc as S0,Gc as p0,Hc as U5,Ic as u2,Jc as X$,Kc as a$,Lc as o$,Mc as s9,Nc as p6,Pc as e,Qc as N2,Rc as Y7}from"./chunk-e3tk2jna.js";import{Sc as x7,Uc as o9,Vc as x2,Wc as e4}from"./chunk-d9ddpapp.js";import{Yc as J4,_c as O0}from"./chunk-mvwp3c11.js";import{$c as i0}from"./chunk-beqaxytd.js";import{dd as u}from"./chunk-jxv6r0c7.js";import{Ad as K8,Bd as Q8,Id as T4,Jd as W7,Kd as l9,Ld as C8,Md as P8,Nd as k8,Od as S8,Pd as v8,Qd as I8,Rd as $0,gd as x4,ld as h4,nd as t6,sd as T7,wd as u4,yd as p9}from"./chunk-hzvp3bc1.js";import{Ud as i1,Vd as N4,Wd as q,Xd as z9,Yd as R,Zd as d}from"./chunk-4vaywb2r.js";import{ce as u9,de as d9}from"./chunk-qev36qrb.js";import{fe as s1,he as L}from"./chunk-vjpd3nee.js";import{le as c9,me as i9}from"./chunk-a7nbn5kf.js";import{ne as u7,qe as I7}from"./chunk-2beq0syt.js";import{ue as G2}from"./chunk-0aj7gp37.js";import{ze as R0}from"./chunk-6hj2dk75.js";import{Ce as X1,Ee as u$,Fe as v0,Ge as U1,He as _4,Ie as T8,Je as M0,Ke as M8}from"./chunk-8nm1hqr1.js";import{Le as c0}from"./chunk-mjp61rqd.js";import{randomUUID as C3}from"crypto";import{mkdir as p1,realpath as t2}from"node:fs/promises";import P$ from"node:path";import{Mutex as L3}from"async-mutex";var A3=new L3,s$,s2;function T3(){return import("@anthropic-ai/sandbox-runtime")}async function O1(){if(s$)return s$;if(!s2)s2=T3();return s$=await s2,s$}var M3={isSupportedPlatform:async()=>(await O1()).SandboxManager.isSupportedPlatform(),checkDependencies:async()=>(await O1()).SandboxManager.checkDependencies(),getDefaultWritePaths:async()=>(await O1()).getDefaultWritePaths(),initialize:async($)=>(await O1()).SandboxManager.initialize($),wrapWithSandboxArgv:async($,Z,J,X,U)=>(await O1()).SandboxManager.wrapWithSandboxArgv($,Z,J,X,U),cleanupAfterCommand:()=>s$?.SandboxManager.cleanupAfterCommand(),reset:async()=>{await s$?.SandboxManager.reset()}};class k$ extends Error{constructor($){super($);this.name="WorkspaceSandboxUnavailableError"}}class t$ extends Error{constructor($){super($);this.name="WorkspaceSandboxBoundaryError"}}class B4{backend;constructor($){this.backend=$}async prepare($){let Z=P$.resolve($.workspaceRoot),J=P$.resolve($.cwd);if(!z0.isWithinWorkspace(J,Z))throw new t$(`Bash cwd is outside the workspace sandbox: ${$.cwd}`);let X,U;try{[X,U]=await Promise.all([t2(Z),t2(J)])}catch(Y){throw new t$(`Workspace sandbox path cannot be resolved: ${Y instanceof Error?Y.message:String(Y)}`)}if(!z0.isWithinWorkspace(U,X))throw new t$(`Bash cwd resolves outside the workspace sandbox: ${$.cwd}`);return this.backend.prepare({...$,cwd:U,workspaceRoot:X})}}class K4{runtime;tempRoot;defaultWritePaths;initialization;constructor($={}){this.runtime=$.runtime??M3,this.tempRoot=$.tempRoot??P$.join(M0(),"sandbox-tmp"),this.defaultWritePaths=$.defaultWritePaths}async prepare($){await this.ensureInitialized();let Z=await this.prepareTempRoot(),J=P$.join(Z,"tmp"),X=P$.join(Z,"cache"),U=P$.join(X,"npm"),Y=P$.join(X,"bun");await Promise.all([p1(J,{recursive:!0}),p1(U,{recursive:!0}),p1(Y,{recursive:!0})]);let z=(this.defaultWritePaths??await this.runtime.getDefaultWritePaths()).filter((K)=>!K.startsWith("/dev/")),H=process.platform==="win32"?"bash":"/bin/bash",V;try{V=await A3.runExclusive(async()=>{let K=process.env.CLAUDE_CODE_TMPDIR;process.env.CLAUDE_CODE_TMPDIR=J;try{return await this.runtime.wrapWithSandboxArgv($.command,H,{filesystem:{denyRead:[],allowRead:[],allowWrite:[$.workspaceRoot,Z],denyWrite:z},git:{safeDirectories:[$.workspaceRoot]}},$.signal,$.cwd)}finally{if(K===void 0)delete process.env.CLAUDE_CODE_TMPDIR;else process.env.CLAUDE_CODE_TMPDIR=K}})}catch(K){if(K instanceof Error&&K.name==="AbortError")throw K;throw new k$(`Workspace sandbox failed to prepare the command: ${K instanceof Error?K.message:String(K)}`)}let B=!1;return{executable:V.argv[0]??H,args:V.argv.slice(1),env:{...V.env,TMPDIR:J,TMP:J,TEMP:J,XDG_CACHE_HOME:X,npm_config_cache:U,BUN_INSTALL_CACHE_DIR:Y},sandboxed:!0,cleanup:()=>{if(B)return;B=!0,this.runtime.cleanupAfterCommand()}}}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 k$(`Workspace sandbox is unsupported on ${process.platform}`);let $=await this.runtime.checkDependencies();if($.errors.length>0)throw new k$(`Workspace sandbox dependencies are unavailable: ${$.errors.join("; ")}`);try{await this.runtime.initialize({network:{allowedDomains:["*"],deniedDomains:[],strictAllowlist:!0},filesystem:{denyRead:[],allowRead:[],allowWrite:[],denyWrite:[]},enableWeakerNestedSandbox:!0})}catch(Z){throw new k$(`Workspace sandbox failed to initialize: ${Z instanceof Error?Z.message:String(Z)}`)}}async prepareTempRoot(){return await p1(this.tempRoot,{recursive:!0}),t2(this.tempRoot)}}function c1($,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 f3=new K4,R3={prepare:($)=>f3.prepare($)},Q4=new B4(R3);class t{static instance=null;processes=new Map;static getInstance(){if(!t.instance)t.instance=new t;return t.instance}startBackgroundProcess($){let Z=`bash_${C3()}`,J={};for(let[H,V]of Object.entries({...process.env,...$.env,...$.sandboxedCommand?.env,BLADE_CLI:"1"}))if(V!==void 0)J[H]=V;let X=$.sandboxedCommand?.executable??"bash",U=$.sandboxedCommand?.args??["-c",$.command],{child:Y,processTree:W}=i0(X,U,{cwd:$.cwd||L(),env:J,stdio:["pipe","pipe","pipe"]}),z={id:Z,command:$.command,sessionId:$.sessionId,cwd:$.cwd,env:$.env,process:Y,processTree:W,pid:Y.pid,status:"running",startTime:Date.now(),pendingStdout:new e2,pendingStderr:new e2,sandboxed:Boolean($.sandboxedCommand)};return Y.stdout?.setEncoding("utf8"),Y.stderr?.setEncoding("utf8"),Y.stdout?.on("data",(H)=>{z.pendingStdout.append(H)}),Y.stderr?.on("data",(H)=>{z.pendingStderr.append(H)}),Y.on("close",(H,V)=>{$.sandboxedCommand?.cleanup();let B=z.sandboxed&&c1(H,z.pendingStderr.peek().content);if(z.status=z.status==="killed"?"killed":B?"error":"exited",z.exitCode=H,z.signal=V,B)z.errorMessage="Workspace sandbox failed to start; command was not executed";z.endTime=Date.now(),z.process=void 0}),Y.on("error",(H)=>{$.sandboxedCommand?.cleanup(),z.status="error",z.errorMessage=H.message,z.endTime=Date.now(),z.process=void 0,z.pendingStderr.append(`
1
+ import{aa as T,ba as m0,ga as M7,ha as A8,ia as y0}from"./chunk-51wa5fct.js";import{Aa as O7,Ha as d8,ja as O$,ma as L2,qa as d0,ta as J0,za as p2}from"./chunk-jzrqjzjm.js";import{Ia as $9,Ja as Z9,Ka as q6}from"./chunk-88vy9hh0.js";import{Qa as z0,Ra as Q0,Sa as a0,Ta as e2,Ua as Z1,Va as t9,Wa as e9,Xa as h2,Ya as $7,Za as Z7,ab as b7,db as J7,eb as X7,gb as n}from"./chunk-a8y9xbxw.js";import{hb as v2,ib as s0,ob as i$,sb as B3,yb as K3}from"./chunk-44wkjs2j.js";import{Jb as t4,Kb as o4}from"./chunk-kq5my0yy.js";import{$b as B0,Wb as A2,Xb as H0,Yb as C,ac as D2,bc as W1,cc as b$,dc as L6,ec as v$,fc as u8,kc as F$}from"./chunk-k6qwdjyy.js";import{lc as g$}from"./chunk-gafbzeyk.js";import{mc as H$}from"./chunk-0h81hxkw.js";import{qc as V7,rc as _2}from"./chunk-af49jmns.js";import{tc as b0,uc as R$}from"./chunk-px5ck9pf.js";import{vc as G7}from"./chunk-fjw32ex5.js";import{xc as n9,yc as r9,zc as a9}from"./chunk-29r7z43j.js";import{Ac as T$,Bc as W9,Dc as P0,Ec as N3,Fc as S0,Gc as p0,Hc as U5,Ic as u2,Jc as X$,Kc as a$,Lc as o$,Mc as s9,Nc as p6,Pc as e,Qc as N2,Rc as Y7}from"./chunk-j51fwecz.js";import{Sc as x7,Uc as o9,Vc as x2,Wc as e4}from"./chunk-d9ddpapp.js";import{Yc as J4,_c as O0}from"./chunk-hefv4415.js";import{$c as i0}from"./chunk-beqaxytd.js";import{dd as u}from"./chunk-jxv6r0c7.js";import{Ad as K8,Bd as Q8,Id as T4,Jd as W7,Kd as l9,Ld as C8,Md as P8,Nd as k8,Od as S8,Pd as v8,Qd as I8,Rd as $0,gd as x4,ld as h4,nd as t6,sd as T7,wd as u4,yd as p9}from"./chunk-3nx2579c.js";import{Ud as i1,Vd as N4,Wd as q,Xd as z9,Yd as R,Zd as d}from"./chunk-4vaywb2r.js";import{ce as u9,de as d9}from"./chunk-qev36qrb.js";import{fe as s1,he as L}from"./chunk-vjpd3nee.js";import{le as c9,me as i9}from"./chunk-a7nbn5kf.js";import{ne as u7,qe as I7}from"./chunk-2beq0syt.js";import{ue as G2}from"./chunk-h7kj4gvj.js";import{ze as R0}from"./chunk-6hj2dk75.js";import{Ce as X1,Ee as u$,Fe as v0,Ge as U1,He as _4,Ie as T8,Je as M0,Ke as M8}from"./chunk-8nm1hqr1.js";import{Le as c0}from"./chunk-mjp61rqd.js";import{randomUUID as C3}from"crypto";import{mkdir as p1,realpath as t2}from"node:fs/promises";import P$ from"node:path";import{Mutex as L3}from"async-mutex";var A3=new L3,s$,s2;function T3(){return import("@anthropic-ai/sandbox-runtime")}async function O1(){if(s$)return s$;if(!s2)s2=T3();return s$=await s2,s$}var M3={isSupportedPlatform:async()=>(await O1()).SandboxManager.isSupportedPlatform(),checkDependencies:async()=>(await O1()).SandboxManager.checkDependencies(),getDefaultWritePaths:async()=>(await O1()).getDefaultWritePaths(),initialize:async($)=>(await O1()).SandboxManager.initialize($),wrapWithSandboxArgv:async($,Z,J,X,U)=>(await O1()).SandboxManager.wrapWithSandboxArgv($,Z,J,X,U),cleanupAfterCommand:()=>s$?.SandboxManager.cleanupAfterCommand(),reset:async()=>{await s$?.SandboxManager.reset()}};class k$ extends Error{constructor($){super($);this.name="WorkspaceSandboxUnavailableError"}}class t$ extends Error{constructor($){super($);this.name="WorkspaceSandboxBoundaryError"}}class B4{backend;constructor($){this.backend=$}async prepare($){let Z=P$.resolve($.workspaceRoot),J=P$.resolve($.cwd);if(!z0.isWithinWorkspace(J,Z))throw new t$(`Bash cwd is outside the workspace sandbox: ${$.cwd}`);let X,U;try{[X,U]=await Promise.all([t2(Z),t2(J)])}catch(Y){throw new t$(`Workspace sandbox path cannot be resolved: ${Y instanceof Error?Y.message:String(Y)}`)}if(!z0.isWithinWorkspace(U,X))throw new t$(`Bash cwd resolves outside the workspace sandbox: ${$.cwd}`);return this.backend.prepare({...$,cwd:U,workspaceRoot:X})}}class K4{runtime;tempRoot;defaultWritePaths;initialization;constructor($={}){this.runtime=$.runtime??M3,this.tempRoot=$.tempRoot??P$.join(M0(),"sandbox-tmp"),this.defaultWritePaths=$.defaultWritePaths}async prepare($){await this.ensureInitialized();let Z=await this.prepareTempRoot(),J=P$.join(Z,"tmp"),X=P$.join(Z,"cache"),U=P$.join(X,"npm"),Y=P$.join(X,"bun");await Promise.all([p1(J,{recursive:!0}),p1(U,{recursive:!0}),p1(Y,{recursive:!0})]);let z=(this.defaultWritePaths??await this.runtime.getDefaultWritePaths()).filter((K)=>!K.startsWith("/dev/")),H=process.platform==="win32"?"bash":"/bin/bash",V;try{V=await A3.runExclusive(async()=>{let K=process.env.CLAUDE_CODE_TMPDIR;process.env.CLAUDE_CODE_TMPDIR=J;try{return await this.runtime.wrapWithSandboxArgv($.command,H,{filesystem:{denyRead:[],allowRead:[],allowWrite:[$.workspaceRoot,Z],denyWrite:z},git:{safeDirectories:[$.workspaceRoot]}},$.signal,$.cwd)}finally{if(K===void 0)delete process.env.CLAUDE_CODE_TMPDIR;else process.env.CLAUDE_CODE_TMPDIR=K}})}catch(K){if(K instanceof Error&&K.name==="AbortError")throw K;throw new k$(`Workspace sandbox failed to prepare the command: ${K instanceof Error?K.message:String(K)}`)}let B=!1;return{executable:V.argv[0]??H,args:V.argv.slice(1),env:{...V.env,TMPDIR:J,TMP:J,TEMP:J,XDG_CACHE_HOME:X,npm_config_cache:U,BUN_INSTALL_CACHE_DIR:Y},sandboxed:!0,cleanup:()=>{if(B)return;B=!0,this.runtime.cleanupAfterCommand()}}}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 k$(`Workspace sandbox is unsupported on ${process.platform}`);let $=await this.runtime.checkDependencies();if($.errors.length>0)throw new k$(`Workspace sandbox dependencies are unavailable: ${$.errors.join("; ")}`);try{await this.runtime.initialize({network:{allowedDomains:["*"],deniedDomains:[],strictAllowlist:!0},filesystem:{denyRead:[],allowRead:[],allowWrite:[],denyWrite:[]},enableWeakerNestedSandbox:!0})}catch(Z){throw new k$(`Workspace sandbox failed to initialize: ${Z instanceof Error?Z.message:String(Z)}`)}}async prepareTempRoot(){return await p1(this.tempRoot,{recursive:!0}),t2(this.tempRoot)}}function c1($,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 f3=new K4,R3={prepare:($)=>f3.prepare($)},Q4=new B4(R3);class t{static instance=null;processes=new Map;static getInstance(){if(!t.instance)t.instance=new t;return t.instance}startBackgroundProcess($){let Z=`bash_${C3()}`,J={};for(let[H,V]of Object.entries({...process.env,...$.env,...$.sandboxedCommand?.env,BLADE_CLI:"1"}))if(V!==void 0)J[H]=V;let X=$.sandboxedCommand?.executable??"bash",U=$.sandboxedCommand?.args??["-c",$.command],{child:Y,processTree:W}=i0(X,U,{cwd:$.cwd||L(),env:J,stdio:["pipe","pipe","pipe"]}),z={id:Z,command:$.command,sessionId:$.sessionId,cwd:$.cwd,env:$.env,process:Y,processTree:W,pid:Y.pid,status:"running",startTime:Date.now(),pendingStdout:new e2,pendingStderr:new e2,sandboxed:Boolean($.sandboxedCommand)};return Y.stdout?.setEncoding("utf8"),Y.stderr?.setEncoding("utf8"),Y.stdout?.on("data",(H)=>{z.pendingStdout.append(H)}),Y.stderr?.on("data",(H)=>{z.pendingStderr.append(H)}),Y.on("close",(H,V)=>{$.sandboxedCommand?.cleanup();let B=z.sandboxed&&c1(H,z.pendingStderr.peek().content);if(z.status=z.status==="killed"?"killed":B?"error":"exited",z.exitCode=H,z.signal=V,B)z.errorMessage="Workspace sandbox failed to start; command was not executed";z.endTime=Date.now(),z.process=void 0}),Y.on("error",(H)=>{$.sandboxedCommand?.cleanup(),z.status="error",z.errorMessage=H.message,z.endTime=Date.now(),z.process=void 0,z.pendingStderr.append(`
2
2
  [error] ${H.message}`)}),this.processes.set(Z,z),z}consumeOutput($,Z){let J=this.getProcess($,Z);if(!J)return;let X=J.pendingStdout.consume(),U=J.pendingStderr.consume();return{id:J.id,command:J.command,status:J.status,stdout:X.content,stderr:U.content,stdoutOmittedBytes:X.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,X=!1){let U=this.getProcess($,Z);if(!U)return;let Y=U.process?.stdin;if(U.status!=="running"||!Y||Y.destroyed||Y.writableEnded)return{success:!1,status:U.status,bytesWritten:0,stdinClosed:!Y||Y.destroyed||Y.writableEnded,errorMessage:"Shell stdin is not writable"};try{return await new Promise((W,z)=>{let H=(B)=>{Y.off("error",H),z(B)},V=(B)=>{if(Y.off("error",H),B)z(B);else W()};if(Y.once("error",H),X)Y.end(J,V);else Y.write(J,V)}),{success:!0,status:U.status,bytesWritten:Buffer.byteLength(J),stdinClosed:X}}catch(W){return{success:!1,status:U.status,bytesWritten:0,stdinClosed:Y.destroyed||Y.writableEnded,errorMessage:W instanceof Error?W.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 iW}from"node:fs/promises";import{Mutex as lW}from"async-mutex";import{nanoid as nW}from"nanoid";import*as U7 from"os";import*as Y0 from"path";import*as x0 from"fs/promises";class S${async readTextFile($){return x0.readFile($,"utf-8")}async writeTextFile($,Z){await x0.writeFile($,Z,"utf-8")}async exists($){try{return await x0.access($),!0}catch{return!1}}async readBinaryFile($){return x0.readFile($)}async stat($){try{let Z=await x0.stat($);return{size:Z.size,isDirectory:Z.isDirectory(),isFile:Z.isFile(),mtime:Z.mtime}}catch{return null}}async mkdir($,Z){await x0.mkdir($,{recursive:Z?.recursive??!1,mode:Z?.mode??493})}}var P3=new S$;function w$(){return P3}var _0=u("Agent");class F1{connection;sessionId;capabilities;fallback;constructor($,Z,J,X=new S$){this.connection=$;this.sessionId=Z;this.capabilities=J;this.fallback=X}async readTextFile($){if(!this.capabilities.readTextFile)return _0.debug(`[AcpFileSystem] readTextFile fallback: ${$}`),this.fallback.readTextFile($);try{return _0.debug(`[AcpFileSystem] readTextFile via ACP: ${$}`),(await this.connection.readTextFile({path:$,sessionId:this.sessionId})).content}catch(Z){throw _0.warn(`[AcpFileSystem] readTextFile ACP failed: ${Z}`),Z}}async writeTextFile($,Z){if(!this.capabilities.writeTextFile)return _0.debug(`[AcpFileSystem] writeTextFile fallback: ${$}`),this.fallback.writeTextFile($,Z);try{_0.debug(`[AcpFileSystem] writeTextFile via ACP: ${$}`),await this.connection.writeTextFile({path:$,content:Z,sessionId:this.sessionId})}catch(J){throw _0.warn(`[AcpFileSystem] writeTextFile ACP failed: ${J}`),J}}async exists($){if(!this.capabilities.readTextFile)return _0.debug(`[AcpFileSystem] exists fallback to local: ${$}`),this.fallback.exists($);try{return await this.connection.readTextFile({path:$,sessionId:this.sessionId}),_0.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((W)=>J.includes(W)))return _0.debug(`[AcpFileSystem] exists(${$}): false (ACP: not found)`),!1;let Y=k3(J);return _0.warn(`[AcpFileSystem] exists(${$}): assuming exists due to ${Y} error`,{error:String(Z),errorType:Y,filePath:$}),!0}}async readBinaryFile($){return _0.debug(`[AcpFileSystem] readBinaryFile fallback: ${$}`),this.fallback.readBinaryFile($)}async stat($){return _0.debug(`[AcpFileSystem] stat fallback: ${$}`),this.fallback.stat($)}async mkdir($,Z){return _0.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 k3($){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 l0=u("Agent");class $5{async execute($,Z){return new Promise((J)=>{let X=process.platform==="win32"?"cmd.exe":"/bin/bash",U=process.platform==="win32"?["/c",$]:["-c",$],{child:Y,processTree:W}=i0(X,U,{cwd:Z?.cwd||L(),env:{...process.env,...Z?.env},stdio:["pipe","pipe","pipe"]}),z,H=()=>{return z??=W.terminate(),z},V="",B="",K=!1,Q=Z?.timeout?setTimeout(()=>{K=!0,H()},Z.timeout):null,w=null,E=()=>{if(Q)clearTimeout(Q);if(w&&Z?.signal)Z.signal.removeEventListener("abort",w),w=null};if(Z?.signal){if(w=()=>{K=!0,H()},Z.signal.addEventListener("abort",w),Z.signal.aborted)w()}Y.stdout?.on("data",(O)=>{let F=O.toString();V+=F,Z?.onOutput?.(F)}),Y.stderr?.on("data",(O)=>{let F=O.toString();B+=F,Z?.onOutput?.(F)}),Y.on("close",async(O)=>{if(E(),K)await H();J({success:O===0&&!K,stdout:V,stderr:B,exitCode:O,error:K?"Command was terminated":void 0})}),Y.on("error",(O)=>{E(),J({success:!1,stdout:V,stderr:B,exitCode:null,error:O.message})})})}isAvailable(){return!0}}class q4{connection;sessionId;fallback;constructor($,Z,J=new $5){this.connection=$;this.sessionId=Z;this.fallback=J}async execute($,Z){try{l0.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(([V,B])=>({name:V,value:B})):void 0}),X=0,U=null;if(Z?.onOutput)U=setInterval(async()=>{try{let B=(await J.currentOutput()).output||"";if(B.length>X){let K=B.slice(X);X=B.length,Z.onOutput?.(K)}}catch{}},100);let Y=(V=!1)=>{if(U)clearInterval(U),U=null;(V?J.kill().then(()=>l0.debug("[AcpTerminal] Killed remote command")).catch(()=>{}).then(()=>J.release()).catch(()=>{}):J.release().catch(()=>{})).catch(()=>{})},W=[];if(W.push(J.waitForExit().then((V)=>({type:"completed",exitCode:V.exitCode??null}))),Z?.timeout)W.push(new Promise((V)=>{setTimeout(()=>V({type:"timeout"}),Z.timeout)}));if(Z?.signal)W.push(new Promise((V)=>{if(Z.signal.aborted)V({type:"aborted"});else Z.signal.addEventListener("abort",()=>V({type:"aborted"}),{once:!0})}));let z=await Promise.race(W),H="";try{if(H=(await J.currentOutput()).output||"",Z?.onOutput&&H.length>X)Z.onOutput(H.slice(X))}catch{}switch(z.type){case"completed":return Y(!1),{success:z.exitCode===0,stdout:H,stderr:"",exitCode:z.exitCode};case"timeout":return l0.debug(`[AcpTerminal] Command timed out, killing: ${$}`),Y(!0),{success:!1,stdout:H,stderr:"",exitCode:null,error:"Command timed out"};case"aborted":return l0.debug(`[AcpTerminal] Command aborted, killing: ${$}`),Y(!0),{success:!1,stdout:H,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 l0.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,X){let U=J?.fs?new F1($,Z,J.fs):new S$;if(J?.fs)l0.debug(`[AcpServiceContext:${Z}] Using ACP file system service`);let Y=new q4($,Z);l0.debug(`[AcpServiceContext:${Z}] Using ACP terminal service`),I.sessions.set(Z,{fileSystemService:U,terminalService:Y,connection:$,clientCapabilities:J||null,cwd:X}),I.currentSessionId=Z,l0.debug(`[AcpServiceContext:${Z}] Initialized with capabilities:`,{fs:!!J?.fs,readTextFile:J?.fs?.readTextFile,writeTextFile:J?.fs?.writeTextFile,cwd:X})}static destroySession($){if(I.sessions.delete($),I.currentSessionId===$){let Z=Array.from(I.sessions.keys());I.currentSessionId=Z[0]||null}l0.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,X){I.initializeSession($,Z,J,X||L())}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 $5}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,X,U){let Y=I.currentSessionId;if(!Y)return;let W=I.sessions.get(Y);if(!W)return;try{await W.connection.sessionUpdate({sessionId:Y,update:{sessionUpdate:"tool_call",toolCallId:$,status:Z,title:J,content:X||[],kind:U||"other"}})}catch(z){l0.warn("[AcpServiceContext] Failed to send tool update:",z)}}}function E$($){return I.getInstance().getFileSystemService($)}function w4($){return I.getInstance().getTerminalService($)}function r($){return $?I.getSessionServices($)!==null:I.getInstance().isAcpMode()}import*as n0 from"node:fs/promises";import*as b4 from"node:path";import{Mutex as S3}from"async-mutex";import{nanoid as v3}from"nanoid";import I3 from"write-file-atomic";var E4=["active","paused","blocked","usage_limited","budget_limited","complete"];var O4=1048576,Z5=1e5,F4=q.Object({version:q.Literal(1),sessionId:q.String({minLength:1}),goalId:q.String({minLength:1}),objective:q.String({minLength:1,maxLength:Z5}),status:d(E4),tokenBudget:q.Optional(q.Integer({minimum:1})),tokensUsed:q.Integer({minimum:0}),timeUsedSeconds:q.Integer({minimum:0}),continuationCount:q.Integer({minimum:0}),statusReason:q.Optional(q.String()),createdAt:q.String({format:"date-time"}),updatedAt:q.String({format:"date-time"})});function G4($,Z){return $ instanceof Error&&"code"in $&&$.code===Z}function D4($){let Z=$.trim();if(!Z)throw Error("Goal objective must not be empty");if(Z.length>Z5)throw Error(`Goal objective exceeds ${Z5} characters`);return Z}function y3($){if($===void 0)return;if(!Number.isInteger($)||$<=0)throw Error("Goal token budget must be a positive integer");return $}class f0{workspaceRoot;sessionId;static mutexes=new Map;static listeners=new Set;filePath;mutex;constructor($,Z){this.workspaceRoot=$;this.sessionId=Z;this.filePath=_4($,Z);let J=f0.mutexes.get(this.filePath);if(!J)J=new S3,f0.mutexes.set(this.filePath,J);this.mutex=J}static subscribe($){return this.listeners.add($),()=>this.listeners.delete($)}static async hasActiveGoal($,Z){return(await new f0($,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(),X=y3($.tokenBudget),U={version:1,sessionId:this.sessionId,goalId:v3(12),objective:D4($.objective),status:"active",...X===void 0?{}:{tokenBudget:X},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:D4($),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)),X=Math.max(0,Math.round($.elapsedMs/1000)),U=Z.tokensUsed+J,Y=Z.tokenBudget!==void 0&&U>=Z.tokenBudget,W={...Z,tokensUsed:U,timeUsedSeconds:Z.timeUsedSeconds+X,status:Y?"budget_limited":Z.status,statusReason:Y?"token budget exhausted":Z.statusReason,updatedAt:new Date().toISOString()};return await this.persistUnlocked(W),this.emit(W),W})}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 n0.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=N4(F4,$(Z));return await this.persistUnlocked(J),this.emit(J),J})}async readUnlocked(){try{if((await n0.stat(this.filePath)).size>O4)throw Error(`Goal state exceeds ${O4} bytes`);await n0.chmod(this.filePath,384);let Z=i1(F4,JSON.parse(await n0.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 n0.mkdir(b4.dirname(this.filePath),{recursive:!0,mode:448}),await I3(this.filePath,`${JSON.stringify($)}
3
3
  `,{encoding:"utf8",mode:384,fsync:!0})}emit($){let Z={workspaceRoot:this.workspaceRoot,sessionId:this.sessionId,goal:$?{...$}:null};for(let J of f0.listeners)try{J(Z)}catch{}}}import{createHash as x3}from"node:crypto";import{promises as l1,realpathSync as h3}from"node:fs";import i from"node:path";import{fileURLToPath as u3,pathToFileURL as J$}from"node:url";var j4=u("Service"),L4=65536;class J5{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:X}=i0($.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=X;try{if(await new Promise((W,z)=>{let H=()=>{J.removeListener("spawn",V),J.removeListener("error",B)},V=()=>{H(),W()},B=(K)=>{H(),z(K)};J.once("spawn",V),J.once("error",B)}),!J.stdout||!J.stdin)throw Error("LSP server stdio is unavailable");let U="";J.stderr?.setEncoding("utf8"),J.stderr?.on("data",(W)=>{if(U.length<L4)U+=W.slice(0,L4-U.length)}),J.stdin.on("error",(W)=>{if(!this.stopping)j4.debug(`[LSP ${this.name}] stdin closed: ${W.message}`)}),this.closePromise=new Promise((W)=>{J.once("close",(z,H)=>{this.initialized=!1;let V=!this.stopping;if(!this.stopping){let B=U.trim()?`: ${U.trim().slice(0,512)}`:H?` (${H})`:"";this.onCrash(Error(`LSP server "${this.name}" exited with code ${z}${B}`))}if(this.child===J){let B=this.processTree;try{this.connection?.dispose()}catch{}if(this.connection=void 0,this.child=void 0,this.closePromise=void 0,V&&B)this.crashCleanup=B.terminate().then(()=>{return}),this.processTree=void 0}W()})});let Y=Z.createMessageConnection(new Z.StreamMessageReader(J.stdout),new Z.StreamMessageWriter(J.stdin));this.connection=Y,Y.onError(([W])=>{if(!this.stopping)j4.warn(`[LSP ${this.name}] connection error: ${W.message}`)}),Y.onClose(()=>{this.initialized=!1});for(let[W,z]of this.notificationHandlers)for(let H of z)Y.onNotification(W,H);for(let[W,z]of this.requestHandlers)Y.onRequest(W,z);Y.listen()}catch(U){throw await this.disposeTransport(),U}}async initialize($,Z,J){let X=await this.request("initialize",$,Z,J,!1);return this.capabilities=X.capabilities,await this.notify("initialized",{}),this.initialized=!0,X}async request($,Z,J,X,U=!0){let Y=this.connection;if(!Y)throw Error(`LSP server "${this.name}" is not started`);if(U&&!this.initialized)throw Error(`LSP server "${this.name}" is not initialized`);let z=new(await import("vscode-jsonrpc/node.js")).CancellationTokenSource;return this.awaitRequest(Y.sendRequest($,Z,z.token),z,J,X,$)}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 X=new(await import("vscode-jsonrpc/node.js")).CancellationTokenSource;await this.awaitRequest(Z.sendRequest("shutdown",X.token),X,$,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,X,U){return new Promise((Y,W)=>{let z=!1,H=(K)=>{if(z)return;z=!0,clearTimeout(B),X?.removeEventListener("abort",V),K()},V=()=>{Z.cancel(),H(()=>W(Error(`LSP request "${U}" was aborted`)))},B=setTimeout(()=>{Z.cancel(),H(()=>W(Error(`LSP request "${U}" timed out after ${J}ms`)))},J);if(X?.addEventListener("abort",V,{once:!0}),X?.aborted)V();$.then((K)=>H(()=>Y(K)),(K)=>H(()=>W(K)))})}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 d3=u("Service"),m3=10485760,g3=10,A4=30,p3=-32801;class X5{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=h3.native(Z)}catch{this.workspaceRoot=Z}for(let[J,X]of Object.entries($.servers)){if(X.enabled===!1)continue;let U={name:J,config:structuredClone(X),state:"stopped",restartCount:0,openedFiles:new Map,client:new J5(J,(Y)=>{U.state="error",U.lastError=Y.message,U.openedFiles.clear()})};U.client.onNotification("textDocument/publishDiagnostics",(Y)=>{this.captureDiagnostics(J,Y)}),U.client.onRequest("workspace/configuration",(Y)=>this.resolveWorkspaceConfiguration(X.settings,Y)),U.client.onRequest("workspace/workspaceFolders",()=>[{uri:J$(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,X){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,X.signal);else if(J.success&&$==="ApplyPatch"){let Y=Array.isArray(J.metadata?.changes)?J.metadata.changes:[];for(let W of Y){if(!W||typeof W!=="object"||!("path"in W)||typeof W.path!=="string")continue;if("newContent"in W&&W.newContent===null)await this.syncAfterDelete(W.path);else U=await this.syncAfterWrite(W.path,X.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 X=await this.ensureFileOpen(J,void 0,Z);if(!X)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)},Y={uri:J$(J).href},W={goToDefinition:{method:"textDocument/definition",params:{textDocument:Y,position:U}},findReferences:{method:"textDocument/references",params:{textDocument:Y,position:U,context:{includeDeclaration:!0}}},hover:{method:"textDocument/hover",params:{textDocument:Y,position:U}},documentSymbol:{method:"textDocument/documentSymbol",params:{textDocument:Y}},workspaceSymbol:{method:"workspace/symbol",params:{query:$.query??""}},goToImplementation:{method:"textDocument/implementation",params:{textDocument:Y,position:U}},prepareCallHierarchy:{method:"textDocument/prepareCallHierarchy",params:{textDocument:Y,position:U}}},z;if($.operation==="incomingCalls"||$.operation==="outgoingCalls"){let V=(await this.requestWithRetry(X,"textDocument/prepareCallHierarchy",{textDocument:Y,position:U},Z))?.[0];z=V?await this.requestWithRetry(X,$.operation==="incomingCalls"?"callHierarchy/incomingCalls":"callHierarchy/outgoingCalls",{item:V},Z):[]}else{let H=W[$.operation];z=await this.requestWithRetry(X,H.method,H.params,Z)}return{operation:$.operation,filePath:J,serverName:X.name,result:z}}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?.()??r(this.options.sessionId)}selectServer($){let Z=i.extname($).toLowerCase();return[...this.servers.values()].filter((J)=>(Z in J.config.extensionToLanguage)).sort((J,X)=>(X.config.priority??0)-(J.config.priority??0)||J.name.localeCompare(X.name))[0]}async ensureFileOpen($,Z,J){let X=this.selectServer($);if(!X)return;await this.ensureStarted(X,J);let U=J$($).href;if(X.openedFiles.has(U))return X;let Y=Z??await this.readBoundedFile($);return await X.client.notify("textDocument/didOpen",{textDocument:{uri:U,languageId:X.config.extensionToLanguage[i.extname($).toLowerCase()],version:1,text:Y}}),X.openedFiles.set(U,1),X}async syncAfterWrite($,Z){try{let J=await this.resolveFile($),X=await this.readBoundedFile(J),U=await this.ensureFileOpen(J,X,Z);if(!U)return;let Y=J$(J).href,W=this.diagnostics.get(Y)?.sequence??0;this.delivered.delete(Y);let z=U.openedFiles.get(Y)??0;if(z>0){let H=z+1;await U.client.notify("textDocument/didChange",{textDocument:{uri:Y,version:H},contentChanges:[{text:X}]}),U.openedFiles.set(Y,H)}return await U.client.notify("textDocument/didSave",{textDocument:{uri:Y},text:X}),await this.waitForDiagnostics(Y,W,U.config.diagnosticWaitTimeout??750,Z),J}catch(J){if(!Z?.aborted&&!this.disposeController.signal.aborted)d3.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=J$(Z).href;for(let X of this.servers.values()){if(!X.openedFiles.has(J))continue;await X.client.notify("textDocument/didClose",{textDocument:{uri:J}}).catch(()=>{return}),X.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=J$(this.workspaceRoot).href,X={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(X,$.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,X){let U;for(let Y=0;Y<4;Y++)try{return await $.client.request(Z,J,$.config.requestTimeout??1e4,X)}catch(W){if(U=W,W.code!==p3||Y===3)break;await new Promise((z)=>setTimeout(z,100*2**Y))}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 X;try{X=J.uri.startsWith("file:")?u3(J.uri):i.resolve(J.uri)}catch{return}if(!this.isInsideWorkspace(X))return;let U=J$(i.resolve(X)).href,Y={sequence:++this.diagnosticSequence,serverName:$,filePath:i.resolve(X),diagnostics:J.diagnostics.filter((H)=>H&&typeof H.message==="string"&&H.range!==void 0).slice(0,100).map((H)=>structuredClone(H))};this.diagnostics.set(U,Y);let W=this.waiters.get(U)??[],z=[];for(let H of W)if(Y.sequence>H.afterSequence)clearTimeout(H.timer),H.resolve();else z.push(H);if(z.length>0)this.waiters.set(U,z);else this.waiters.delete(U)}waitForDiagnostics($,Z,J,X){if(J===0||(this.diagnostics.get($)?.sequence??0)>Z)return Promise.resolve();return new Promise((U)=>{let Y=!1,W,z=()=>{if(Y)return;Y=!0,clearTimeout(W.timer),X?.removeEventListener("abort",z);let B=(this.waiters.get($)??[]).filter((K)=>K!==W);if(B.length>0)this.waiters.set($,B);else this.waiters.delete($);U()},H=setTimeout(z,J);W={afterSequence:Z,resolve:z,timer:H};let V=this.waiters.get($)??[];if(V.push(W),this.waiters.set($,V),X?.addEventListener("abort",z,{once:!0}),X?.aborted)z()})}attachPendingDiagnostics($,Z){let J=[...this.diagnostics.values()].sort((z,H)=>{if(Z){if(z.filePath===Z&&H.filePath!==Z)return-1;if(H.filePath===Z&&z.filePath!==Z)return 1}return H.sequence-z.sequence}),X=[],U=[],Y=0;for(let z of J){let H=J$(z.filePath).href,V=this.delivered.get(H)??new Set,B=z.diagnostics.sort((Q,w)=>(Q.severity??4)-(w.severity??4)).filter((Q)=>!V.has(this.diagnosticKey(Q))).slice(0,Math.min(g3,A4-Y));if(B.length===0)continue;let K=i.relative(this.workspaceRoot,z.filePath);X.push(`${K}:`);for(let Q of B){let w=Q.range.start.line+1,E=Q.range.start.character+1,O=["Error","Warning","Info","Hint"][(Q.severity??1)-1],F=Q.message.replace(/\s+/g," ").slice(0,500);X.push(` ${O??"Error"} ${w}:${E} ${F}`+(Q.code!==void 0?` [${String(Q.code)}]`:"")),V.add(this.diagnosticKey(Q)),U.push({file:K,line:w,character:E,severity:O??"Error",message:F,server:z.serverName}),Y++}if(this.delivered.set(H,V),Y>=A4)break}if(X.length===0)return;let W=typeof $.llmContent==="string"?$.llmContent:JSON.stringify($.llmContent);$.llmContent=`${W}
4
4
 
@@ -653,7 +653,7 @@ ${k}
653
653
  </approved-plan>
654
654
 
655
655
  IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof K==="string")m=K+p;else m=[...K,{type:"text",text:p}]}A=yield*this.runLoop(m,Q,{...j,inputMessageId:void 0})}if(!this.sessionRuntime||!b)return A;if(A.success&&!Q.signal?.aborted)await this.sessionRuntime.acknowledgeTurn(b);let P=await this.sessionRuntime.recordGoalProgress({tokens:A.metadata?.tokensUsed??0,elapsedMs:A.metadata?.duration??0});if(P)yield{kind:"goal_updated",goal:P};if(!A.success||Q.signal?.aborted){if(P=await this.sessionRuntime.pauseActiveGoal(Q.signal?.aborted?"goal paused after user cancellation":A.error?.message??"goal paused after turn failure"),P)yield{kind:"goal_updated",goal:P}}let M=A.success&&!Q.signal?.aborted&&D<20;if(G=await this.sessionRuntime.finishTurn(b,{continuePending:M}),G){D++,w=!0,E=!1,O=null,K="",F=void 0,yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:N()};continue}if(!A.success||Q.signal?.aborted)return A;if(P=await this.sessionRuntime.getGoal(),!P||P.status!=="active")return A;if(O=await this.sessionRuntime.beginGoalContinuation(),!O)return A;G=this.sessionRuntime.beginTurn(),w=!1,E=!0,K=R5(O),F=void 0,yield{kind:"goal_continuation_started",goal:O,continuation:O.continuationCount},yield{kind:"goal_updated",goal:O}}}finally{if(this.sessionRuntime&&G)await this.sessionRuntime.finishTurn(G)}}let H=typeof W==="string"?W:W.filter((K)=>K.type==="text").map((K)=>K.text).join(`
656
- `),V={id:this.generateTaskId(),type:"simple",prompt:H};return{success:!0,finalMessage:(await this.executeTask(V)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:X}=await import("./chunk-3c5gvxr6.js");return X(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){y.debug("Processing Plan mode message...");let{prompt:X}=await I$({projectPath:Z.workspaceRoot||L(),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=_1($);else{let Y=$.filter((W)=>W.type==="text");if(Y.length>0){let W=Y[0];U=$.map((z)=>z===W?{type:"text",text:_1(W.text)}:z)}else U=[{type:"text",text:_1("")},...$]}return yield*this.executeLoop(U,Z,J,X)}async*runLoop($,Z,J){y.debug("Processing enhanced chat message...");let X=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||L());return yield*this.executeLoop($,Z,J,X)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await I$({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,X){if(!this.isInitialized)throw Error("Agent未初始化");let U=this.buildLoopDependencies();return d8(U,$,Z,J,X)}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,X)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,X):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(),X=Z.getAll().filter((U)=>!$.includes(U.name));for(let U of X)Z.unregister(U.name);y.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${X.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let X of Z.getAll())if(J.has(X.name))Z.unregister(X.name);y.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let X=Z.get(J.kind)||0;Z.set(J.kind,X+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 I$({projectPath:this.sessionRuntime?.workspaceRoot??L(),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((X)=>X.loaded).map((X)=>X.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await b2({sessionId:"default",configDir:g8.join(m8.homedir(),".blade"),workspaceRoot:L(),resourceRoot:L(),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 t1({workspaceRoot:L(),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=y0.createIsolated({artifactWriter:new D1(`legacy-${rU()}`)});this.legacyMcpRegistry=Z;for(let[Y,W]of Object.entries($))try{y.debug(`Connecting to MCP server: ${Y}`),await Z.registerServer(Y,W),y.debug(`MCP server "${Y}" connected`)}catch(z){y.warn(`Warning: MCP server "${Y}" connection failed:`,z)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let X=Z.getCatalogSnapshot();J.replaceMcpTools(X.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",(Y)=>{J.replaceMcpTools(Y.tools,Y)}),Z.on("contentCatalogChanged",(Y)=>{J.queueMcpContentChange(Y)}),Z.on("resourceUpdated",(Y)=>{J.queueMcpResourceUpdated(Y)}),Z.on("connectionLifecycleChanged",(Y)=>{J.queueMcpConnectionChange(Y)}),Z.on("log",(Y)=>{J.queueMcpLog(Y)}),Z.on("instructionsChanged",(Y)=>{J.queueMcpInstructionsChange({revision:Y.revision,reason:Y.reason,replace:!1,instructions:Y.action==="added"&&Y.instruction?[{serverName:Y.serverName,...Y.instruction}]:[],removed:Y.action==="removed"?[Y.serverName]:[]})}),X.tools.length>0)y.debug(`Registered ${X.tools.length} MCP tools`),y.debug(`[MCP Tools] ${X.tools.map((Y)=>Y.name).join(", ")}`)}catch($){y.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await e(L());if(this.agentResources=N2($),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((X)=>{return Z.some((U)=>{if(U===X.name)return!0;let Y=U.match(/^(\w+)\(.*\)$/);if(Y&&Y[1]===X.name)return!0;return!1})});return y.debug(`Filtered tools: ${J.map((X)=>X.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 X of $)if(X.type==="text")Z.push(X.text);if(Z.length===0)return $;let J=Z.join(`
656
+ `),V={id:this.generateTaskId(),type:"simple",prompt:H};return{success:!0,finalMessage:(await this.executeTask(V)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:X}=await import("./chunk-m3g8hz67.js");return X(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){y.debug("Processing Plan mode message...");let{prompt:X}=await I$({projectPath:Z.workspaceRoot||L(),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=_1($);else{let Y=$.filter((W)=>W.type==="text");if(Y.length>0){let W=Y[0];U=$.map((z)=>z===W?{type:"text",text:_1(W.text)}:z)}else U=[{type:"text",text:_1("")},...$]}return yield*this.executeLoop(U,Z,J,X)}async*runLoop($,Z,J){y.debug("Processing enhanced chat message...");let X=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||L());return yield*this.executeLoop($,Z,J,X)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await I$({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,X){if(!this.isInitialized)throw Error("Agent未初始化");let U=this.buildLoopDependencies();return d8(U,$,Z,J,X)}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,X)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,X):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(),X=Z.getAll().filter((U)=>!$.includes(U.name));for(let U of X)Z.unregister(U.name);y.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${X.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let X of Z.getAll())if(J.has(X.name))Z.unregister(X.name);y.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let X=Z.get(J.kind)||0;Z.set(J.kind,X+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 I$({projectPath:this.sessionRuntime?.workspaceRoot??L(),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((X)=>X.loaded).map((X)=>X.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await b2({sessionId:"default",configDir:g8.join(m8.homedir(),".blade"),workspaceRoot:L(),resourceRoot:L(),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 t1({workspaceRoot:L(),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=y0.createIsolated({artifactWriter:new D1(`legacy-${rU()}`)});this.legacyMcpRegistry=Z;for(let[Y,W]of Object.entries($))try{y.debug(`Connecting to MCP server: ${Y}`),await Z.registerServer(Y,W),y.debug(`MCP server "${Y}" connected`)}catch(z){y.warn(`Warning: MCP server "${Y}" connection failed:`,z)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let X=Z.getCatalogSnapshot();J.replaceMcpTools(X.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",(Y)=>{J.replaceMcpTools(Y.tools,Y)}),Z.on("contentCatalogChanged",(Y)=>{J.queueMcpContentChange(Y)}),Z.on("resourceUpdated",(Y)=>{J.queueMcpResourceUpdated(Y)}),Z.on("connectionLifecycleChanged",(Y)=>{J.queueMcpConnectionChange(Y)}),Z.on("log",(Y)=>{J.queueMcpLog(Y)}),Z.on("instructionsChanged",(Y)=>{J.queueMcpInstructionsChange({revision:Y.revision,reason:Y.reason,replace:!1,instructions:Y.action==="added"&&Y.instruction?[{serverName:Y.serverName,...Y.instruction}]:[],removed:Y.action==="removed"?[Y.serverName]:[]})}),X.tools.length>0)y.debug(`Registered ${X.tools.length} MCP tools`),y.debug(`[MCP Tools] ${X.tools.map((Y)=>Y.name).join(", ")}`)}catch($){y.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await e(L());if(this.agentResources=N2($),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((X)=>{return Z.some((U)=>{if(U===X.name)return!0;let Y=U.match(/^(\w+)\(.*\)$/);if(Y&&Y[1]===X.name)return!0;return!1})});return y.debug(`Filtered tools: ${J.map((X)=>X.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 X of $)if(X.type==="text")Z.push(X.text);if(Z.length===0)return $;let J=Z.join(`
657
657
  `);try{let X=await this.attachmentCollector.collect(J);if(X.length===0)return $;y.debug(`Processed ${X.length} @ file mentions in multimodal message`);let U=this.buildAttachmentText(X);if(!U)return $;return[...$,{type:"text",text:U}]}catch(X){return y.error("Failed to process @ mentions in multimodal message:",X),$}}buildAttachmentText($){let Z=[],J=[];for(let U of $)if(U.type==="file"){let Y=U.metadata?.lineRange?` (lines ${U.metadata.lineRange.start}${U.metadata.lineRange.end?`-${U.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${U.path}"${Y?` range="${Y}"`:""}>`,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 X="";if(Z.length>0)X+=`
658
658
 
659
659
  <system-reminder>
@@ -1447,7 +1447,7 @@ ${J}
1447
1447
  `)),{success:!0,message:`Installed ${U.pluginName}`}}return C().addAssistantMessage(`安装失败: ${U.error}`),{success:!1,error:U.error}}async function cH($,Z){let J=r2(Z),X=J.positional[0];if(!X)return C().addAssistantMessage("请指定插件名称: `/plugins uninstall <name> --confirm`"),{success:!1,error:"Plugin name required"};if(!J.confirm){let Y=`卸载 ${X} 需要显式确认,请添加 \`--confirm\``;return C().addAssistantMessage(Y),{success:!1,error:"Plugin uninstall confirmation required"}}let{result:U}=await r6($.getWorkspaceRoot(),X,J.confirm);if(U.success)return C().addAssistantMessage(`[OK] 已卸载插件: ${U.pluginName}`),{success:!0,message:`Uninstalled ${U.pluginName}`};return C().addAssistantMessage(`卸载失败: ${U.error}`),{success:!1,error:U.error}}async function iH($,Z){let J=r2(Z),X=J.positional[0];if(!X)return C().addAssistantMessage("请指定插件名称: `/plugins update <name> --trust`"),{success:!1,error:"Plugin name required"};if(!J.trust){let Y=`更新会执行 ${X} 的新代码,确认来源后使用 \`--trust\` 重试`;return C().addAssistantMessage(Y),{success:!1,error:"Plugin source trust required"}}C().addAssistantMessage(`正在更新插件: ${X}...`);let{result:U}=await n6($.getWorkspaceRoot(),X,{trusted:J.trust});if(U.success){let Y=[U.changed?"[OK] 插件更新成功!":"[OK] 插件已是最新版本","",`**名称**: ${U.pluginName}`,`**提交**: \`${U.installation?.revision??"local"}\``];if(U.manifest)Y.push(`**版本**: ${U.manifest.version}`);if(U.updatedDependencies?.length)Y.push(`**依赖更新**: ${U.updatedDependencies.join(", ")}`);return C().addAssistantMessage(Y.join(`
1448
1448
  `)),{success:!0,message:`Updated ${U.pluginName}`}}return C().addAssistantMessage(`更新失败: ${U.error}`),{success:!1,error:U.error}}function q1($,Z){let J=$.indexOf(Z);if(J>=0)return $[J+1];let X=`${Z}=`;return $.find((U)=>U.startsWith(X))?.slice(X.length)}function z3($,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 W4($){if($===void 0)return;return[...new Set($.split(",").map((Z)=>Z.trim()).filter(Boolean))]}function H3($){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(`
1449
1449
  `)}async function lH($,Z){let J=Z[0]?.toLowerCase()??"show";if(J==="show"||J==="status"){let X=H3($.getSourcePolicy());return C().addAssistantMessage(X),{success:!0,message:X}}if(J!=="set"){let X="Usage: /plugins policy set [--restrict true] [--require-sha true] [--hosts host,...] [--marketplaces name,...] [--local-roots /path,...] [--scope global|project|local]";return C().addAssistantMessage(X),{success:!1,error:X}}try{let X=$.getSourcePolicy(),U=z3(q1(Z,"--restrict"),"--restrict"),Y=z3(q1(Z,"--require-sha"),"--require-sha"),W=W4(q1(Z,"--hosts")),z=W4(q1(Z,"--marketplaces")),H=W4(q1(Z,"--local-roots"));if(U===void 0&&Y===void 0&&W===void 0&&z===void 0&&H===void 0)throw Error("No plugin policy fields were provided");let V=q1(Z,"--scope")??"global",B=z4([V]),K=await i6($.getWorkspaceRoot(),{...X,...U===void 0?{}:{restrictToAllowedSources:U},...Y===void 0?{}:{requireGitCommitSha:Y},...W===void 0?{}:{allowedGitHosts:W},...z===void 0?{}:{allowedMarketplaces:z},...H===void 0?{}:{allowedLocalRoots:H}},B),Q=H3(K);return C().addAssistantMessage(Q),{success:!0,message:Q}}catch(X){let U=X instanceof Error?X.message:String(X);return C().addAssistantMessage(`Plugin policy update failed: ${U}`),{success:!1,error:U}}}async function nH($,Z){let J=Z[0]?.toLowerCase()??"list",X=r2(Z.slice(1));try{if(J==="list"||J==="ls"){let U=await p0().listCatalogs(),Y=U.length===0?["没有已配置的 Plugin Marketplace。"]:["## Plugin Marketplaces","",...U.flatMap(({marketplace:W,manifest:z})=>[`- **${W.name}** · ${z.plugins.length} plugins`,` ${z.description??z.metadata?.description??""}`,` revision: \`${W.revision}\``])];return C().addAssistantMessage(Y.join(`
1450
- `)),{success:!0,message:"Marketplaces listed"}}if(J==="add"){let U=X.positional[0];if(!U)throw Error("Usage: /plugins marketplace add <source> [--ref <ref>]");let Y=await a6($.getWorkspaceRoot(),U,X.ref);if(!Y.success)throw Error(Y.error);let W=`[OK] 已添加 Marketplace ${Y.marketplace?.name}(${Y.manifest?.plugins.length??0} 个插件)`;return C().addAssistantMessage(W),{success:!0,message:W}}if(J==="update"||J==="refresh"){let U=X.positional[0],Y=U?[U]:(await p0().listMarketplaces()).map((H)=>H.name);if(Y.length===0)return C().addAssistantMessage("没有可更新的 Marketplace"),{success:!0,message:"没有可更新的 Marketplace"};let W=[];for(let H of Y){let V=await o6($.getWorkspaceRoot(),H);if(!V.success)throw Error(V.error);W.push(`${H}${V.changed?"":" (unchanged)"}`)}let z=`[OK] Marketplace 已更新: ${W.join(", ")}`;return C().addAssistantMessage(z),{success:!0,message:z}}if(J==="remove"||J==="rm"){let U=X.positional[0];if(!U)throw Error("Usage: /plugins marketplace remove <name> --confirm");if(!X.confirm)throw Error(`移除 Marketplace ${U} 需要 --confirm`);let Y=await s6(U,!0);if(!Y.success)throw Error(Y.error);let W=`[OK] 已移除 Marketplace: ${U}`;return C().addAssistantMessage(W),{success:!0,message:W}}throw Error("Usage: /plugins marketplace <add|list|update|remove> [args]")}catch(U){let Y=U instanceof Error?U.message:String(U);return C().addAssistantMessage(`Marketplace 操作失败: ${Y}`),{success:!1,error:Y}}}var V3=vH;import*as w1 from"node:fs/promises";import*as E1 from"node:path";async function Q3($,Z={}){let{maxResults:J=20,caseSensitive:X=!1,projectPath:U,storagePath:Y}=Z,W=Y??X1(U??L());if(!Y){let Q=await rH($,U??L(),J,X);if(Q)return Q}let z;try{z=(await w1.readdir(W)).filter((w)=>w.endsWith(".jsonl")&&!w.startsWith("agent_")).map((w)=>E1.join(W,w))}catch{return[]}let V=(await Promise.all(z.map(async(Q)=>{try{let w=await w1.stat(Q);return{path:Q,mtime:w.mtimeMs}}catch{return null}}))).filter((Q)=>Q!==null).sort((Q,w)=>w.mtime-Q.mtime).map((Q)=>Q.path),B=[],K=X?$:$.toLowerCase();for(let Q of V){if(B.length>=J)break;let w=E1.basename(Q,".jsonl"),E=await aH(Q,K,X,w);if(B.push(...E),B.length>=J){B.length=J;break}}return B}async function rH($,Z,J,X){try{let{syncAll:U}=await import("./chunk-jv4nkkb5.js"),Y=await B3();if(!Y)return null;let{SessionService:W}=await import("./chunk-v4mr98vm.js");await U(Y,W.projectionDeriverForSearch());let z=E1.resolve(Z),H=K3(Y,$,z,J*4),V=X?$:$.toLowerCase(),B=[];for(let K of H){if(K.role!=="user"&&K.role!=="assistant")continue;let Q=H4(K.text,V,X,K.session_id,K.role,K.timestamp??void 0,0);if(Q)B.push(Q);if(B.length>=J)break}return B}catch{return null}}async function aH($,Z,J,X){try{let U=await w1.readFile($,"utf8"),W=U.split(`
1450
+ `)),{success:!0,message:"Marketplaces listed"}}if(J==="add"){let U=X.positional[0];if(!U)throw Error("Usage: /plugins marketplace add <source> [--ref <ref>]");let Y=await a6($.getWorkspaceRoot(),U,X.ref);if(!Y.success)throw Error(Y.error);let W=`[OK] 已添加 Marketplace ${Y.marketplace?.name}(${Y.manifest?.plugins.length??0} 个插件)`;return C().addAssistantMessage(W),{success:!0,message:W}}if(J==="update"||J==="refresh"){let U=X.positional[0],Y=U?[U]:(await p0().listMarketplaces()).map((H)=>H.name);if(Y.length===0)return C().addAssistantMessage("没有可更新的 Marketplace"),{success:!0,message:"没有可更新的 Marketplace"};let W=[];for(let H of Y){let V=await o6($.getWorkspaceRoot(),H);if(!V.success)throw Error(V.error);W.push(`${H}${V.changed?"":" (unchanged)"}`)}let z=`[OK] Marketplace 已更新: ${W.join(", ")}`;return C().addAssistantMessage(z),{success:!0,message:z}}if(J==="remove"||J==="rm"){let U=X.positional[0];if(!U)throw Error("Usage: /plugins marketplace remove <name> --confirm");if(!X.confirm)throw Error(`移除 Marketplace ${U} 需要 --confirm`);let Y=await s6(U,!0);if(!Y.success)throw Error(Y.error);let W=`[OK] 已移除 Marketplace: ${U}`;return C().addAssistantMessage(W),{success:!0,message:W}}throw Error("Usage: /plugins marketplace <add|list|update|remove> [args]")}catch(U){let Y=U instanceof Error?U.message:String(U);return C().addAssistantMessage(`Marketplace 操作失败: ${Y}`),{success:!1,error:Y}}}var V3=vH;import*as w1 from"node:fs/promises";import*as E1 from"node:path";async function Q3($,Z={}){let{maxResults:J=20,caseSensitive:X=!1,projectPath:U,storagePath:Y}=Z,W=Y??X1(U??L());if(!Y){let Q=await rH($,U??L(),J,X);if(Q)return Q}let z;try{z=(await w1.readdir(W)).filter((w)=>w.endsWith(".jsonl")&&!w.startsWith("agent_")).map((w)=>E1.join(W,w))}catch{return[]}let V=(await Promise.all(z.map(async(Q)=>{try{let w=await w1.stat(Q);return{path:Q,mtime:w.mtimeMs}}catch{return null}}))).filter((Q)=>Q!==null).sort((Q,w)=>w.mtime-Q.mtime).map((Q)=>Q.path),B=[],K=X?$:$.toLowerCase();for(let Q of V){if(B.length>=J)break;let w=E1.basename(Q,".jsonl"),E=await aH(Q,K,X,w);if(B.push(...E),B.length>=J){B.length=J;break}}return B}async function rH($,Z,J,X){try{let{syncAll:U}=await import("./chunk-jv4nkkb5.js"),Y=await B3();if(!Y)return null;let{SessionService:W}=await import("./chunk-gv8gfnz8.js");await U(Y,W.projectionDeriverForSearch());let z=E1.resolve(Z),H=K3(Y,$,z,J*4),V=X?$:$.toLowerCase(),B=[];for(let K of H){if(K.role!=="user"&&K.role!=="assistant")continue;let Q=H4(K.text,V,X,K.session_id,K.role,K.timestamp??void 0,0);if(Q)B.push(Q);if(B.length>=J)break}return B}catch{return null}}async function aH($,Z,J,X){try{let U=await w1.readFile($,"utf8"),W=U.split(`
1451
1451
  `).flatMap((K,Q)=>{if(!K.trim())return[];try{return[{event:JSON.parse(K),index:Q}]}catch{return[]}});if(!W.some(({event:K})=>K.type==="session_created"))return oH(W,Z,J,X);let H=new Map(W.flatMap(({event:K,index:Q})=>typeof K.id==="string"?[[K.id,Q+1]]:[])),V=i$(v2(U,$)),B=new Map;for(let K of V){if(K.type==="message_created"&&(K.data.role==="user"||K.data.role==="assistant"))B.set(K.data.messageId,{role:K.data.role,content:[],timestamp:K.timestamp,lineNumber:H.get(K.id)??0});if(K.type==="part_created"&&K.data.partType==="text"){let Q=B.get(K.data.messageId),w=K.data.payload.text;if(Q&&typeof w==="string")Q.content.push(w)}}return[...B.values()].flatMap((K)=>{let Q=H4(K.content.join(" "),Z,J,X,K.role,K.timestamp,K.lineNumber);return Q?[Q]:[]})}catch{return[]}}function oH($,Z,J,X){return $.flatMap(({event:U,index:Y})=>{if(U.type!=="message")return[];let W=U.message;if(W?.role!=="user"&&W?.role!=="assistant"||!W.content)return[];let z=typeof W.content==="string"?W.content:Array.isArray(W.content)?W.content.filter((V)=>typeof V==="object"&&V!==null&&V.type==="text"&&typeof V.text==="string").map((V)=>V.text).join(" "):"",H=H4(z,Z,J,X,W.role,typeof U.timestamp==="string"?U.timestamp:void 0,Y+1);return H?[H]:[]})}function H4($,Z,J,X,U,Y,W){if(!$)return;let z=J?$:$.toLowerCase();if(!z.includes(Z))return;let H=z.indexOf(Z),V=Math.max(0,H-80),B=Math.min($.length,H+Z.length+80);return{sessionId:X,role:U,content:(V>0?"...":"")+$.slice(V,B).replace(/\n/g," ")+(B<$.length?"...":""),timestamp:Y,lineNumber:W}}function q3($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
1452
1452
  `];for(let J of $){let X=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)}\` (${X})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
1453
1453
  `)}var sH={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 X=$.join(" ");J.sendMessage(`正在搜索: "${X}" ...`);try{let U=await Q3(X,{maxResults:15,projectPath:Z.cwd}),Y=q3(U);return J.sendMessage(Y),{success:!0,message:`found ${U.length} results`,data:{matches:U.length}}}catch(U){let Y=U instanceof Error?U.message:"未知错误";return J.sendMessage(`搜索失败: ${Y}`),{success:!1,error:Y}}}},w3=sH;var tH={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{return await P0({cwd:Z.workspaceRoot??Z.cwd}).refresh(),o$(Z.workspaceRoot??Z.cwd),await a$(Z.workspaceRoot??Z.cwd),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let X=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return C().addAssistantMessage(X),{success:!1,error:X}}}},E3=tH;import eH from"node:path";function a2($){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 O3($){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 F3($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function $V($,Z){let J=v(Z),X=$[0],U=t.getInstance(),Y=s.getInstance(),W=Z.sessionId??"",z=Z.sessionId?{sessionId:Z.sessionId,projectPath:eH.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(X==="resume"){let w=$[1],E=$.slice(2).join(" ").trim();if(!w||!E)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 O=await Z.subagents.resume(w,E),F=`Resumed \`${w}\` as \`${O.session.id}\` (depth ${O.session.resumeDepth}).`;return J.sendMessage(F),{success:!0,message:F,data:{action:"subagent_resumed",sourceAgentId:w,subagent:O.session}}}if(X==="clean"){let w=Y.cleanupExpiredSessionsForParent(z??W,0);return J.sendMessage(`已清理 ${w} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${w} agent sessions`}}let H=[`**后台任务列表**