blade-code 0.7.7 → 0.7.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/{chunk-60se4kxq.js → chunk-0e0z8yc1.js} +2 -2
- package/dist/{chunk-x466sb8s.js → chunk-1w6tqkxd.js} +2 -2
- package/dist/{chunk-8e0rv3j5.js → chunk-2049tv49.js} +3 -3
- package/dist/chunk-4745ktjj.js +1570 -0
- package/dist/{chunk-54vk4tw8.js → chunk-48q9msfk.js} +43 -43
- package/dist/{chunk-v61bja34.js → chunk-4dmdn3a9.js} +1 -1
- package/dist/{chunk-4n7fsts0.js → chunk-5be6qr2v.js} +1 -1
- package/dist/chunk-67vzgcs5.js +2 -0
- package/dist/{chunk-2j3tb2dm.js → chunk-6811kbxn.js} +1 -1
- package/dist/{chunk-p7rf3zp8.js → chunk-6hn2jgw5.js} +1 -1
- package/dist/chunk-6js5wp6t.js +1 -0
- package/dist/{chunk-0y895nft.js → chunk-6kp3z956.js} +2 -2
- package/dist/{chunk-7e5hzpmp.js → chunk-71n472hj.js} +1 -1
- package/dist/chunk-78txnq4n.js +151 -0
- package/dist/{chunk-x24ddbhs.js → chunk-7r1hm0qz.js} +1 -1
- package/dist/{chunk-6087cgst.js → chunk-9kejtkey.js} +1 -1
- package/dist/{chunk-h79044h0.js → chunk-a7yjnqhd.js} +2 -2
- package/dist/chunk-bwaqaktn.js +1 -0
- package/dist/chunk-cb82rf5h.js +1 -0
- package/dist/chunk-ce11m8bq.js +1 -0
- package/dist/{chunk-2qckpa16.js → chunk-cjmxggke.js} +1 -1
- package/dist/chunk-e4rhdg3h.js +1 -0
- package/dist/{chunk-zet4zjc3.js → chunk-f9ybv4ph.js} +1 -1
- package/dist/{chunk-89j9pm90.js → chunk-faq7ay4j.js} +2 -2
- package/dist/{chunk-w1m1ehs1.js → chunk-fb7amc2s.js} +1 -1
- package/dist/{chunk-c6rtexw1.js → chunk-g6ted982.js} +1 -1
- package/dist/{chunk-9ad7tt9s.js → chunk-g7caymjr.js} +1 -1
- package/dist/{chunk-6y58y4rx.js → chunk-jm2xhnrv.js} +1 -1
- package/dist/chunk-ky8ctbdc.js +1 -0
- package/dist/chunk-mpskff34.js +1 -0
- package/dist/{chunk-6cry51vb.js → chunk-pd1yqxcv.js} +5 -5
- package/dist/{chunk-d61d6m07.js → chunk-phhmmybg.js} +2 -2
- package/dist/{chunk-ebcmqx1k.js → chunk-qnevwq1q.js} +1 -1
- package/dist/{chunk-778h8815.js → chunk-r1spf93b.js} +2 -2
- package/dist/{chunk-0b3m5qn6.js → chunk-rnfd5ebv.js} +1 -1
- package/dist/{chunk-yyw9bbfd.js → chunk-s4mke0t6.js} +1 -1
- package/dist/{chunk-5xjj88wd.js → chunk-t2spryz0.js} +1 -1
- package/dist/{chunk-2n8a87ds.js → chunk-t70aqrm4.js} +1 -1
- package/dist/{chunk-ptt8s7nd.js → chunk-z4c68ve0.js} +1 -1
- package/dist/chunk-z9zbcenc.js +6 -0
- package/dist/web/assets/{FilePreview-B2anY2d1.js → FilePreview-DRKRs8i2.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-BVfRG88x.js → MarkdownRenderer-DFqPpAnM.js} +1 -1
- package/dist/web/assets/{McpModal-BVvb-dzr.js → McpModal-CX5-hlNv.js} +1 -1
- package/dist/web/assets/{SettingsModal-aseVv-gp.js → SettingsModal-CfR_q6N7.js} +1 -1
- package/dist/web/assets/{SettingsStore-B87y64B4.js → SettingsStore-jup_Kikq.js} +1 -1
- package/dist/web/assets/{SkillsModal-BXYaF2KK.js → SkillsModal-DaAUrwXO.js} +1 -1
- package/dist/web/assets/{TerminalPanel-B-NRhOXN.js → TerminalPanel-DzlllDH7.js} +1 -1
- package/dist/web/assets/index-BJTSF3fc.js +9 -0
- package/dist/web/assets/index-CL6apjgo.css +1 -0
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-3fcze972.js +0 -1
- package/dist/chunk-8p98nt9v.js +0 -151
- package/dist/chunk-94vj1hjp.js +0 -1
- package/dist/chunk-c8cxeve8.js +0 -1
- package/dist/chunk-gsn659hw.js +0 -1
- package/dist/chunk-kppxkh33.js +0 -1
- package/dist/chunk-qnh7np1s.js +0 -6
- package/dist/chunk-ran4gsmy.js +0 -1
- package/dist/chunk-swyvd7hd.js +0 -1
- package/dist/chunk-t9zdypqp.js +0 -2
- package/dist/chunk-x1khkevy.js +0 -1563
- package/dist/web/assets/index-9kl44E8k.js +0 -9
- package/dist/web/assets/index-CUVe9dGs.css +0 -1
package/dist/blade.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{n as B}from"./chunk-
|
|
2
|
+
import{n as B}from"./chunk-fb7amc2s.js";import{fa as D,ga as F}from"./chunk-0e0z8yc1.js";import"./chunk-faq7ay4j.js";import"./chunk-r1spf93b.js";import"./chunk-2049tv49.js";import"./chunk-t70aqrm4.js";import{Bb as q,zb as E}from"./chunk-4dmdn3a9.js";import{Yb as H}from"./chunk-a7yjnqhd.js";import{$b as J}from"./chunk-f9ybv4ph.js";var X=process.argv.slice(2),$=v(X),w=$!==null;if($!==null)H.setGlobalDebug($);function v(Q){for(let W=0;W<Q.length;W+=1){let T=Q[W];if(T==="--debug"||T==="-d"){let N=Q[W+1];return N&&!N.startsWith("-")?N:!0}if(T.startsWith("--debug="))return T.slice(8)||!0}return null}function C(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function z(Q,...W){return Q.some((T)=>W.some((N)=>T===N||T.startsWith(`${N}=`)))}async function f(){if(C(X)){let{getVersion:K}=await import("./chunk-ce11m8bq.js");console.log(K());return}let Q=D(process.cwd());if(F(Q),E(q()),process.getuid&&process.getuid()===0){let K=!!process.env.SUDO_USER,U=!!process.env.BLADE_ALLOW_ROOT;if(K&&!U)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(z(X,"--headless")){let{handleHeadlessMode:K}=await import("./chunk-z9zbcenc.js");if(await K())return}if(B(),z(X,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-z4c68ve0.js");if(await K())return}if(X.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-pd1yqxcv.js");await K();return}let[{default:W},{hideBin:T},{cliConfig:N,globalOptions:G},{loadConfiguration:I,validateOutput:L,validatePermissions:M},{doctorCommands:_},{installCommands:y},{mcpCommands:R},{serveCommand:S},{updateCommands:k},{webCommand:O}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-cb82rf5h.js"),import("./chunk-ky8ctbdc.js"),import("./chunk-rnfd5ebv.js"),import("./chunk-t2spryz0.js"),import("./chunk-9kejtkey.js"),import("./chunk-6js5wp6t.js"),import("./chunk-6hn2jgw5.js"),import("./chunk-71n472hj.js")]),x=W(T(process.argv)).scriptName(N.scriptName).usage(N.usage).version(N.version).locale(N.locale).showHelpOnFail(N.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(N.strict).parserConfiguration({"populate--":!0}).options(G).middleware([I,M,L]).command(R).command(_).command(k).command(y).command(O).command(S).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,U,Z)=>{if(U){if(console.error("An error occurred:"),console.error(U.message),w&&U.stack)console.error(`
|
|
3
3
|
Stack trace:`),console.error(U.stack);else console.error(`
|
|
4
4
|
Run with --debug to show the stack trace.`);process.exit(1)}if(K)console.error("Error: Invalid arguments:"),console.error(K),console.error(`
|
|
5
|
-
Hint: Did you mean:`),Z.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let U=K._.slice(1),Z=U.length>0?U.join(" "):void 0,V=import("./chunk-
|
|
5
|
+
Hint: Did you mean:`),Z.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let U=K._.slice(1),Z=U.length>0?U.join(" "):void 0,V=import("./chunk-e4rhdg3h.js").then(({checkVersionOnStartup:A})=>A()),[{render:b},{createElement:P},{AppWrapper:h}]=await Promise.all([import("ink"),import("react"),import("./chunk-78txnq4n.js")]),Y={...K,initialMessage:Z,debug:K.debug,print:Boolean(K.print),versionCheckPromise:V};delete Y._,delete Y.$0,delete Y.message,b(P(h,Y),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await x.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)f().catch(console.error);export{f as main};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Bb as _,wb as L}from"./chunk-4dmdn3a9.js";import{execSync as F}from"child_process";import{existsSync as Q,readFileSync as O,realpathSync as b}from"fs";import*as V from"os";import*as H from"path";import{basename as J,isAbsolute as j,resolve as R}from"path";function G(z=_()){let q=z,M=f(q);return{workingDirectory:q,projectRoot:M,platform:`${V.platform()} (${V.arch()})`,nodeVersion:process.version,currentDate:new Date().toISOString().split("T")[0],homeDirectory:V.homedir()}}function Y(z,q){try{return F(q,{cwd:z,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{return null}}function v(z={}){let{includeGitSnapshot:q=!0,includeDirectoryListing:M=!0,workingDirectory:W}=z,B=G(W),$=Q(H.join(B.projectRoot,".git")),T=J(process.env.SHELL||"unknown"),A=["package.json","tsconfig.json","BLADE.md",".env.example"].filter((K)=>Q(H.join(B.projectRoot,K))).map((K)=>`- \`${H.join(B.projectRoot,K)}\``),N=`# Environment
|
|
2
2
|
You have been invoked in the following environment:
|
|
3
3
|
- Primary working directory: ${B.workingDirectory}
|
|
4
4
|
- Is a git repository: ${$?"true":"false"}
|
|
@@ -25,4 +25,4 @@ ${I.join(`
|
|
|
25
25
|
|
|
26
26
|
Project root directory listing:
|
|
27
27
|
${K}`}return N}function f(z){let q=z,M=null;while(q!==H.dirname(q)){if(Q(H.join(q,".git")))return q;if(Q(H.join(q,".blade")))return q;if(Q(H.join(q,".claude")))return q;if(!M&&Q(H.join(q,"package.json")))M=q;q=H.dirname(q)}return M??z}function x(z,q){let M=j(z)?z:R(q||process.cwd(),z),W;try{W=b(M)}catch{W=M}L(W)}
|
|
28
|
-
export{v as
|
|
28
|
+
export{v as ea,f as fa,x as ga};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ja as S,Ka as h}from"./chunk-phhmmybg.js";import{qb as M}from"./chunk-jm2xhnrv.js";import{$b as c}from"./chunk-f9ybv4ph.js";import{EventEmitter as r}from"events";import{z as L}from"zod";import{isPlainObject as p}from"lodash-es";function J(B){if(B===void 0)return"undefined";if(typeof B==="string")return B;try{let G=JSON.stringify(B);return G===void 0?String(B):G}catch{return String(B)}}class R extends Error{issues;type;constructor(B,G,Q="validation_error"){super(B);this.issues=G;this.type=Q;this.name="ToolValidationError"}}function g(B){let{code:G}=B,Q=B,X=Q.received;switch(G){case"invalid_type":{let Y=Q.expected;return`类型错误:期望 ${J(Y)},实际收到 ${J(X)}`}case"too_small":{let{minimum:Y,inclusive:$}=Q,W=typeof Q.type==="string"?Q.type:void 0;if(W==="string"&&typeof Y==="number")return`长度不能少于 ${Y} 个字符`;if(W==="number"&&typeof Y==="number")return`不能小于${$?"等于":""} ${Y}`;if(W==="array"&&typeof Y==="number")return`数组长度不能少于 ${Y}`;return"值太小"}case"too_big":{let{maximum:Y,inclusive:$}=Q,W=typeof Q.type==="string"?Q.type:void 0;if(W==="string"&&typeof Y==="number")return`长度不能超过 ${Y} 个字符`;if(W==="number"&&typeof Y==="number")return`不能大于${$?"等于":""} ${Y}`;if(W==="array"&&typeof Y==="number")return`数组长度不能超过 ${Y}`;return"值太大"}case"invalid_string":{let Y=Q.validation;if(Y==="email")return"必须是有效的电子邮件地址";if(Y==="url")return"必须是有效的 URL";if(Y==="uuid")return"必须是有效的 UUID";if(p(Y)){let $=Y;if(typeof $.includes==="string")return`必须包含 "${$.includes}"`;if(typeof $.startsWith==="string")return`必须以 "${$.startsWith}" 开头`;if(typeof $.endsWith==="string")return`必须以 "${$.endsWith}" 结尾`}return"字符串格式不正确"}case"invalid_enum_value":{let Y=Q.options;if(Array.isArray(Y))return`必须是以下值之一:${Y.map(($)=>J($)).join(", ")}`;return"必须是枚举允许的值之一"}case"invalid_literal":{let Y=Q.expected;return`必须是字面量值:${J(Y)}`}case"unrecognized_keys":{let Y=Q.keys;if(Array.isArray(Y))return`包含未知的参数:${Y.map(($)=>J($)).join(", ")}`;return"包含未知的参数"}case"invalid_union":return"不符合任何有效的类型定义";case"invalid_date":return"必须是有效的日期";case"custom":return B.message||"自定义验证失败";default:return B.message||"验证失败"}}function u(B){let G=B.issues.map((X)=>{let Y=X.path.join("."),$=g(X),W=X.received;return{field:Y||"root",message:$,value:W}}),Q=G.length===1?`参数验证失败 [${G[0].field}]: ${G[0].message}`:`参数验证失败 (${G.length} 个错误):
|
|
2
2
|
${G.map((X)=>` - ${X.field}: ${X.message}`).join(`
|
|
3
3
|
`)}`;return new R(Q,G)}function y(B,G){let Q=B.safeParse(G);if(!Q.success)throw u(Q.error);return Q.data}import{zodToJsonSchema as l}from"zod-to-json-schema";function H(B){let G=l(B,{target:"jsonSchema7",$refStrategy:"none"});if(G.type==="object"&&G.properties&&!Array.isArray(G.required))G.required=[];return G}class w{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor(B,G,Q,X,Y){this.toolName=B;this.params=G;this.executeFn=Q;this.descriptionFn=X;this.affectedPathsFn=Y}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(B,G,Q){let X={signal:B,updateOutput:G,...Q};return this.executeFn(this.params,X)}}function k(B){return{name:B.name,displayName:B.displayName,kind:B.kind,isReadOnly:B.isReadOnly??M(B.kind),isConcurrencySafe:B.isConcurrencySafe??!1,strict:B.strict??!1,description:B.description,version:B.version||"1.0.0",category:B.category,tags:B.tags||[],getFunctionDeclaration(){let G=H(B.schema),Q=B.description.short;if(B.description.long)Q+=`
|
|
4
4
|
|
|
@@ -31,4 +31,4 @@ ${B.description.important.map((X)=>`[WARN] ${X}`).join(`
|
|
|
31
31
|
`),X.close(),G(q)}catch(W){X.close(),Q(W)}});X.on("error",Q),X.listen(Z,()=>{console.log(`[OAuth] Callback server listening on port ${Z}`)}),setTimeout(()=>{X.close(),Q(Error("OAuth callback timeout"))},300000)})}async exchangeCodeForToken(B,G,Q){let X=B.redirectUri||`http://localhost:${Z}${D}`,Y=new URLSearchParams({grant_type:"authorization_code",code:G,redirect_uri:X,code_verifier:Q,client_id:B.clientId});if(B.clientSecret)Y.append("client_secret",B.clientSecret);let $=await fetch(B.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Y.toString()});if(!$.ok){let W=await $.text();throw Error(`Token exchange failed: ${$.status} - ${W}`)}return await $.json()}async refreshAccessToken(B,G){let Q=new URLSearchParams({grant_type:"refresh_token",refresh_token:G,client_id:B.clientId});if(B.clientSecret)Q.append("client_secret",B.clientSecret);if(B.scopes&&B.scopes.length>0)Q.append("scope",B.scopes.join(" "));let X=await fetch(B.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Q.toString()});if(!X.ok){let Y=await X.text();throw Error(`Token refresh failed: ${X.status} - ${Y}`)}return await X.json()}async authenticate(B,G){if(!G.clientId||!G.authorizationUrl||!G.tokenUrl)throw Error("Missing required OAuth configuration");let Q=this.generatePKCEParams(),X=this.buildAuthorizationUrl(G,Q);console.log(`
|
|
32
32
|
[OAuth] Opening browser for authentication...`),console.log(`
|
|
33
33
|
If the browser does not open automatically, copy and paste this URL:`),console.log(X),console.log("");let Y=this.startCallbackServer(Q.state);try{await this.openAuthorizationUrl(X)}catch(F){console.warn("[OAuth] Failed to open browser automatically:",F)}let $=await Y;console.log("[OAuth] Authorization code received, exchanging for tokens...");let W=await this.exchangeCodeForToken(G,$,Q.codeVerifier),q={accessToken:W.access_token,tokenType:W.token_type||"Bearer",refreshToken:W.refresh_token,scope:W.scope};if(W.expires_in)q.expiresAt=Date.now()+W.expires_in*1000;return await this.tokenStorage.saveToken(B,q,G.clientId,G.tokenUrl),console.log("[OAuth] Authentication successful! Token saved."),q}async openAuthorizationUrl(B){let{command:G,args:Q}=this.getBrowserCommand(B);await new Promise((X,Y)=>{let $=m(G,Q,{stdio:"ignore"});$.once("error",Y),$.once("close",(W)=>{if(W===0||W===null)X();else Y(Error(`Failed to open browser (exit code ${W})`))})})}getBrowserCommand(B){if(process.platform==="darwin")return{command:"open",args:[B]};if(process.platform==="win32")return{command:"cmd",args:["/c","start","",B]};return{command:"xdg-open",args:[B]}}async getValidToken(B,G){let Q=await this.tokenStorage.getCredentials(B);if(!Q)return null;let{token:X}=Q;if(!this.tokenStorage.isTokenExpired(X))return X.accessToken;if(X.refreshToken&&G.clientId&&Q.tokenUrl)try{console.log(`[OAuth] Refreshing expired token for server: ${B}`);let Y=await this.refreshAccessToken(G,X.refreshToken),$={accessToken:Y.access_token,tokenType:Y.token_type,refreshToken:Y.refresh_token||X.refreshToken,scope:Y.scope||X.scope};if(Y.expires_in)$.expiresAt=Date.now()+Y.expires_in*1000;return await this.tokenStorage.saveToken(B,$,G.clientId,Q.tokenUrl),$.accessToken}catch(Y){console.error("[OAuth] Failed to refresh token:",Y),await this.tokenStorage.deleteCredentials(B)}return null}}import{EventEmitter as i}from"events";class E extends i{client;config;checkTimer=null;isChecking=!1;consecutiveFailures=0;lastCheckTime=0;currentStatus="healthy";constructor(B,G={}){super();this.client=B,this.config={interval:G.interval??30000,timeout:G.timeout??1e4,enabled:G.enabled??!1,failureThreshold:G.failureThreshold??3}}start(){if(this.checkTimer){console.warn("[HealthMonitor] 健康监控已在运行");return}if(!this.config.enabled){console.log("[HealthMonitor] 健康监控未启用");return}console.log(`[HealthMonitor] 启动健康监控(间隔: ${this.config.interval}ms)`),this.scheduleNextCheck()}stop(){if(this.checkTimer)clearTimeout(this.checkTimer),this.checkTimer=null,console.log("[HealthMonitor] 停止健康监控")}scheduleNextCheck(){this.checkTimer=setTimeout(async()=>{await this.performHealthCheck(),this.scheduleNextCheck()},this.config.interval)}async performHealthCheck(){if(this.isChecking)return console.warn("[HealthMonitor] 上一次检查仍在进行中"),this.getLastResult();this.isChecking=!0,this.lastCheckTime=Date.now(),this.setStatus("checking");try{let B=this.client.connectionStatus;if(B==="connected"){await this.pingServer(),this.consecutiveFailures=0,this.setStatus("healthy");let G={status:"healthy",timestamp:Date.now(),consecutiveFailures:0};return this.emit("healthCheck",G),G}else throw Error(`连接状态异常: ${B}`)}catch(B){this.consecutiveFailures++;let G=B;console.warn(`[HealthMonitor] 健康检查失败(${this.consecutiveFailures}/${this.config.failureThreshold}):`,G.message);let Q;if(this.consecutiveFailures>=this.config.failureThreshold)Q="unhealthy",this.emit("unhealthy",this.consecutiveFailures,G),console.log("[HealthMonitor] 达到失败阈值,触发重连..."),this.triggerReconnection().catch((Y)=>{console.error("[HealthMonitor] 重连失败:",Y)});else Q="degraded";this.setStatus(Q);let X={status:Q,timestamp:Date.now(),consecutiveFailures:this.consecutiveFailures,lastError:G};return this.emit("healthCheck",X),X}finally{this.isChecking=!1}}async pingServer(){let B=new Promise((Q,X)=>{setTimeout(()=>X(Error("Health check timeout")),this.config.timeout)}),G=(async()=>{if(this.client.availableTools.length===0){if(!this.client.server)throw Error("Server info not available")}})();await Promise.race([G,B])}async triggerReconnection(){try{await this.client.disconnect(),await new Promise((B)=>setTimeout(B,1000)),await this.client.connect(),console.log("[HealthMonitor] 重连成功"),this.consecutiveFailures=0,this.setStatus("healthy"),this.emit("reconnected")}catch(B){throw console.error("[HealthMonitor] 重连失败:",B),B}}setStatus(B){if(this.currentStatus!==B){let G=this.currentStatus;this.currentStatus=B,this.emit("statusChanged",B,G)}}getStatus(){return this.currentStatus}getLastResult(){return{status:this.currentStatus,timestamp:this.lastCheckTime,consecutiveFailures:this.consecutiveFailures}}getStatistics(){return{status:this.currentStatus,consecutiveFailures:this.consecutiveFailures,lastCheckTime:this.lastCheckTime,isChecking:this.isChecking,config:this.config}}async checkNow(){return this.performHealthCheck()}resetFailureCount(){if(this.consecutiveFailures=0,this.currentStatus!=="checking")this.setStatus("healthy")}}function d(B){if(!(B instanceof Error))return{type:"unknown",isRetryable:!1,originalError:Error(String(B))};let G=B.message.toLowerCase();if(["command not found","no such file","permission denied","invalid configuration","malformed","syntax error"].some((Y)=>G.includes(Y)))return{type:"config_error",isRetryable:!1,originalError:B};if(G.includes("unauthorized")||G.includes("401")||G.includes("authentication failed"))return{type:"auth_error",isRetryable:!1,originalError:B};if(["timeout","connection refused","network error","temporary","try again","rate limit","too many requests","service unavailable","socket hang up","econnreset","enotfound","econnrefused","etimedout","503","429"].some((Y)=>G.includes(Y)))return{type:"network_temporary",isRetryable:!0,originalError:B};return{type:"unknown",isRetryable:!0,originalError:B}}class N extends n{config;status="disconnected";sdkClient=null;tools=new Map;serverInfo=null;reconnectAttempts=0;MAX_RECONNECT_ATTEMPTS=5;reconnectTimer=null;isManualDisconnect=!1;oauthProvider=null;serverName;healthMonitor=null;constructor(B,G,Q){super();this.config=B;if(this.serverName=G||"default",B.oauth?.enabled)this.oauthProvider=new O;if(Q?.enabled)this.healthMonitor=new E(this,Q),this.healthMonitor.on("unhealthy",(X,Y)=>{this.emit("unhealthy",X,Y)}),this.healthMonitor.on("reconnected",()=>{this.emit("healthMonitorReconnected")})}get connectionStatus(){return this.status}get availableTools(){return Array.from(this.tools.values())}get server(){return this.serverInfo}get healthCheck(){return this.healthMonitor}async connect(){return this.connectWithRetry(3,1000)}async connectWithRetry(B=3,G=1000){if(this.status!=="disconnected"&&this.status!=="error")throw Error("客户端已连接或正在连接中");if(this.status==="error"){if(this.sdkClient){try{await this.sdkClient.close()}catch{}this.sdkClient=null}this.setStatus("disconnected")}let Q=null;for(let X=1;X<=B;X++)try{await this.doConnect(),this.reconnectAttempts=0;return}catch(Y){Q=Y;let $=d(Y);if(!$.isRetryable)throw console.error("[McpClient] 检测到永久性错误,放弃重试:",$.type),Y;if(X<B){let W=G*Math.pow(2,X-1);console.warn(`[McpClient] 连接失败(${X}/${B}),${W}ms 后重试...`),await new Promise((q)=>setTimeout(q,W))}}throw Q||Error("连接失败")}async doConnect(){try{this.setStatus("connecting"),this.sdkClient=new t({name:h(),version:S()},{capabilities:{roots:{listChanged:!0},sampling:{}}}),this.sdkClient.onclose=()=>{this.handleUnexpectedClose()};let B=await this.createTransport();await this.sdkClient.connect(B);let G=this.sdkClient.getServerVersion();if(this.serverInfo={name:G?.name||"Unknown",version:G?.version||"0.0.0"},await this.loadTools(),this.setStatus("connected"),this.emit("connected",this.serverInfo),this.healthMonitor)this.healthMonitor.start()}catch(B){throw this.setStatus("error"),this.emit("error",B),B}}handleUnexpectedClose(){if(this.isManualDisconnect)return;if(this.status==="connected")console.warn("[McpClient] 检测到意外断连,准备重连..."),this.setStatus("error"),this.emit("error",Error("MCP服务器连接意外关闭")),this.scheduleReconnect()}scheduleReconnect(){if(this.reconnectTimer)clearTimeout(this.reconnectTimer),this.reconnectTimer=null;if(this.reconnectAttempts>=this.MAX_RECONNECT_ATTEMPTS){console.error("[McpClient] 达到最大重连次数,放弃重连"),this.emit("reconnectFailed");return}let B=Math.min(1000*Math.pow(2,this.reconnectAttempts),30000);this.reconnectAttempts++,console.log(`[McpClient] 将在 ${B}ms 后进行第 ${this.reconnectAttempts} 次重连...`),this.reconnectTimer=setTimeout(async()=>{try{if(this.sdkClient){try{await this.sdkClient.close()}catch{}this.sdkClient=null}this.setStatus("disconnected"),await this.doConnect(),console.log("[McpClient] 重连成功"),this.reconnectAttempts=0,this.emit("reconnected")}catch(G){if(console.error("[McpClient] 重连失败:",G),d(G).isRetryable)this.scheduleReconnect();else console.error("[McpClient] 检测到永久性错误,停止重连"),this.emit("reconnectFailed")}},B)}async disconnect(){if(this.isManualDisconnect=!0,this.healthMonitor)this.healthMonitor.stop();if(this.reconnectTimer)clearTimeout(this.reconnectTimer),this.reconnectTimer=null;if(this.sdkClient){try{await this.sdkClient.close()}catch(B){console.warn("[McpClient] 断开连接时出错:",B)}this.sdkClient=null}this.tools.clear(),this.serverInfo=null,this.reconnectAttempts=0,this.setStatus("disconnected"),this.emit("disconnected"),this.isManualDisconnect=!1}async callTool(B,G={}){if(!this.sdkClient)throw Error("客户端未连接到服务器");if(!this.tools.has(B))throw Error(`工具 "${B}" 不存在`);try{return await this.sdkClient.callTool({name:B,arguments:G})}catch(Q){throw console.error(`[McpClient] 调用工具 "${B}" 失败:`,Q),Q}}async createTransport(){let{type:B,command:G,args:Q,env:X,url:Y,headers:$,oauth:W}=this.config,q={...$};if(W?.enabled&&this.oauthProvider&&(B==="sse"||B==="http"))try{let F=await this.oauthProvider.getValidToken(this.serverName,W);if(!F){console.log(`[McpClient] 服务器 "${this.serverName}" 需要 OAuth 认证`);let A=await this.oauthProvider.authenticate(this.serverName,W);q.Authorization=`Bearer ${A.accessToken}`}else q.Authorization=`Bearer ${F}`}catch(F){throw console.error("[McpClient] OAuth 认证失败:",F),Error(`OAuth 认证失败: ${F instanceof Error?F.message:String(F)}`)}if(B==="stdio"){if(!G)throw Error("stdio 传输需要 command 参数");let F={};for(let[A,K]of Object.entries(process.env))if(K!==void 0)F[A]=K;return new s({command:G,args:Q||[],env:{...F,...X},stderr:"ignore"})}else if(B==="sse"){if(!Y)throw Error("sse 传输需要 url 参数");return new a(new URL(Y),{requestInit:{headers:q}})}else if(B==="http"){if(!Y)throw Error("http 传输需要 url 参数");let{StreamableHTTPClientTransport:F}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");return new F(new URL(Y),{requestInit:{headers:q}})}throw Error(`不支持的传输类型: ${B}`)}async loadTools(){if(!this.sdkClient)return;try{let B=await this.sdkClient.listTools();if(this.tools.clear(),B.tools)for(let G of B.tools)this.tools.set(G.name,G);this.emit("toolsUpdated",this.availableTools)}catch(B){throw console.error("[McpClient] 加载工具失败:",B),B}}setStatus(B){let G=this.status;this.status=B,this.emit("statusChanged",B,G)}async initialize(){return this.connect()}async destroy(){return this.disconnect()}async connectToServer(B){return this.connect()}async disconnectFromServer(B){return this.disconnect()}async listResources(B){if(!this.sdkClient)return[];try{return(await this.sdkClient.listResources()).resources||[]}catch{return[]}}async listTools(B){return this.availableTools}async readResource(B,G){if(!this.sdkClient)throw Error("客户端未连接");return(await this.sdkClient.readResource({uri:B})).contents?.[0]||{uri:B,text:""}}}class b extends r{static instance=null;servers=new Map;isDiscovering=!1;constructor(){super()}static getInstance(){if(!b.instance)b.instance=new b;return b.instance}static createIsolated(){return new b}async registerServer(B,G){if(this.servers.has(B))throw Error(`MCP服务器 "${B}" 已经注册`);let Q=new N(G,B,G.healthCheck),X={config:G,client:Q,status:"disconnected",tools:[]};this.setupClientEventHandlers(Q,X,B),this.servers.set(B,X),this.emit("serverRegistered",B,X);try{await this.connectServer(B)}catch(Y){console.warn(`MCP服务器 "${B}" 连接失败:`,Y)}}async unregisterServer(B){let G=this.servers.get(B);if(!G)return;try{await G.client.disconnect()}catch(Q){console.warn(`断开MCP服务器 "${B}" 时出错:`,Q)}this.servers.delete(B),this.emit("serverUnregistered",B)}async connectServer(B){let G=this.servers.get(B);if(!G)throw Error(`MCP服务器 "${B}" 未注册`);if(G.status==="connected")return;try{G.status="connecting",await G.client.connect(),G.connectedAt=new Date,G.lastError=void 0,G.tools=G.client.availableTools}catch(Q){throw G.lastError=Q,G.status="error",Q}}async disconnectServer(B){let G=this.servers.get(B);if(!G)return;await G.client.disconnect(),G.connectedAt=void 0}async reconnectServer(B){let G=this.servers.get(B);if(!G)throw Error(`MCP服务器 "${B}" 未注册`);if(G.status==="connected")await G.client.disconnect();try{G.status="connecting",await G.client.connect(),G.connectedAt=new Date,G.lastError=void 0,G.tools=G.client.availableTools}catch(Q){throw G.lastError=Q,G.status="error",Q}}async getAvailableTools(){let B=[],G=new Map;for(let[Q,X]of this.servers)if(X.status==="connected")for(let Y of X.tools){let $=G.get(Y.name)||0;G.set(Y.name,$+1)}for(let[Q,X]of this.servers)if(X.status==="connected")for(let Y of X.tools){let W=(G.get(Y.name)||0)>1?`${Q}__${Y.name}`:Y.name,q=U(X.client,Q,Y,W);B.push(q)}return B}async findTool(B){for(let[G,Q]of this.servers)if(Q.status==="connected"){let X=Q.tools.find((Y)=>Y.name===B);if(X)return U(Q.client,G,X)}return null}getToolsByServer(B){let G=this.servers.get(B);if(!G||G.status!=="connected")return[];return G.tools.map((Q)=>U(G.client,B,Q))}getServerStatus(B){return this.servers.get(B)||null}getAllServers(){return new Map(this.servers)}async refreshAllTools(){let B=[];for(let[G,Q]of this.servers)if(Q.status==="connected")B.push(this.refreshServerTools(G));await Promise.allSettled(B)}async refreshServerTools(B){let G=this.servers.get(B);if(!G||G.status!=="connected")return;try{let Q=G.client.availableTools,X=G.tools.length;G.tools=Q,this.emit("toolsUpdated",B,Q,X)}catch(Q){console.warn(`刷新服务器 "${B}" 工具列表失败:`,Q)}}setupClientEventHandlers(B,G,Q){B.on("connected",(X)=>{G.status="connected",G.connectedAt=new Date,G.tools=B.availableTools,this.emit("serverConnected",Q,X)}),B.on("disconnected",()=>{G.status="disconnected",G.connectedAt=void 0,G.tools=[],this.emit("serverDisconnected",Q)}),B.on("error",(X)=>{G.status="error",G.lastError=X,this.emit("serverError",Q,X)}),B.on("toolsUpdated",(X)=>{let Y=G.tools.length;G.tools=X,this.emit("toolsUpdated",Q,X,Y)}),B.on("statusChanged",(X,Y)=>{G.status=X,this.emit("serverStatusChanged",Q,X,Y)})}async discoverServers(){if(this.isDiscovering)return Array.from(this.servers.values());this.isDiscovering=!0,this.emit("discoveryStarted");try{return Array.from(this.servers.values())}finally{this.isDiscovering=!1,this.emit("discoveryCompleted")}}async registerServers(B){let G=Object.entries(B).map(([Q,X])=>this.registerServer(Q,X).catch((Y)=>{return console.warn(`注册MCP服务器 "${Q}" 失败:`,Y),Y}));await Promise.allSettled(G)}getStatistics(){let B=0,G=0,Q=0;for(let X of this.servers.values())if(X.status==="connected")B++,G+=X.tools.length;else if(X.status==="error")Q++;return{totalServers:this.servers.size,connectedServers:B,errorServers:Q,totalTools:G,isDiscovering:this.isDiscovering}}async disconnectAll(){let B=[];for(let[G,Q]of this.servers)if(Q.status==="connected")B.push(Q.client.disconnect().catch((X)=>{console.warn(`断开 MCP 服务器 "${G}" 时出错:`,X)}));await Promise.allSettled(B),this.servers.clear()}}
|
|
34
|
-
export{k as
|
|
34
|
+
export{k as ca,b as da};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ab as n}from"./chunk-v61bja34.js";import{Yb as r}from"./chunk-h79044h0.js";import{_b as b}from"./chunk-zet4zjc3.js";import{nanoid as A}from"nanoid";var N;((R)=>{R.PreToolUse="PreToolUse";R.PostToolUse="PostToolUse";R.PostToolUseFailure="PostToolUseFailure";R.PermissionRequest="PermissionRequest";R.UserPromptSubmit="UserPromptSubmit";R.SessionStart="SessionStart";R.SessionEnd="SessionEnd";R.Stop="Stop";R.SubagentStop="SubagentStop";R.Notification="Notification";R.Compaction="Compaction"})(N||={});var C;((W)=>{W.Approve="approve";W.Block="block";W.Async="async"})(C||={});var S;((W)=>{W.Allow="allow";W.Deny="deny";W.Ask="ask"})(S||={});var I={enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,httpPolicy:{},PreToolUse:[],PostToolUse:[{name:"builtin:code-review-sensor",matcher:{tools:"Edit|Write"},hooks:[{type:"prompt",prompt:"审查此代码变更,重点检查:"+"1) 安全漏洞(命令注入、XSS、SQL 注入、硬编码密钥/密码)"+"2) 明显的逻辑错误(无限循环、off-by-one、空引用)"+"3) 类型安全问题。"+"如果发现严重问题,将问题描述放在 hookSpecificOutput.additionalContext 中。"+"如果没有严重问题,返回 approve。",model:void 0,timeout:15}]}],PostToolUseFailure:[],PermissionRequest:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]};function f(Q,Y){return{...Q,...Y,PreToolUse:Y.PreToolUse??Q.PreToolUse,PostToolUse:Y.PostToolUse??Q.PostToolUse,PostToolUseFailure:Y.PostToolUseFailure??Q.PostToolUseFailure,PermissionRequest:Y.PermissionRequest??Q.PermissionRequest,UserPromptSubmit:Y.UserPromptSubmit??Q.UserPromptSubmit,SessionStart:Y.SessionStart??Q.SessionStart,SessionEnd:Y.SessionEnd??Q.SessionEnd,Stop:Y.Stop??Q.Stop,SubagentStop:Y.SubagentStop??Q.SubagentStop,Notification:Y.Notification??Q.Notification,Compaction:Y.Compaction??Q.Compaction}}function x(){let Q={};if(process.env.BLADE_DISABLE_HOOKS==="true")Q.enabled=!1;if(process.env.BLADE_HOOK_TIMEOUT){let Y=parseInt(process.env.BLADE_HOOK_TIMEOUT,10);if(!isNaN(Y)&&Y>0)Q.defaultTimeout=Y}return Q}class z{executedHooks=new Map;canExecute(Q,Y){if(!this.executedHooks.has(Q))this.executedHooks.set(Q,new Set);if(this.executedHooks.get(Q).has(Y))return console.warn(`[HookGuard] Hook ${Y} for tool ${Q} already executed, skipping`),!1;return!0}markExecuted(Q,Y){let Z=this.executedHooks.get(Q);if(Z)Z.add(Y)}cleanup(Q){this.executedHooks.delete(Q)}cleanupAll(){this.executedHooks.clear()}}import{z as q}from"zod";var j=q.object({hook_event_name:q.nativeEnum(N),hook_execution_id:q.string(),timestamp:q.string(),project_dir:q.string(),session_id:q.string(),permission_mode:q.enum(["default","autoEdit","yolo","plan"]),_metadata:q.object({blade_version:q.string(),hook_timeout_ms:q.number()}).optional()}),o=j.extend({hook_event_name:q.literal("PreToolUse"),tool_name:q.string(),tool_use_id:q.string(),tool_input:q.record(q.unknown())}),e=j.extend({hook_event_name:q.literal("PostToolUse"),tool_name:q.string(),tool_use_id:q.string(),tool_input:q.record(q.unknown()),tool_response:q.unknown()}),t=j.extend({hook_event_name:q.literal("Stop"),reason:q.string().optional()}),QQ=j.extend({hook_event_name:q.literal("PostToolUseFailure"),tool_name:q.string(),tool_use_id:q.string(),tool_input:q.record(q.unknown()),error:q.string(),error_type:q.string().optional(),is_interrupt:q.boolean(),is_timeout:q.boolean()}),YQ=j.extend({hook_event_name:q.literal("PermissionRequest"),tool_name:q.string(),tool_use_id:q.string(),tool_input:q.record(q.unknown())}),ZQ=j.extend({hook_event_name:q.literal("UserPromptSubmit"),user_prompt:q.string(),has_images:q.boolean(),image_count:q.number()}),WQ=j.extend({hook_event_name:q.literal("SessionStart"),is_resume:q.boolean(),resume_session_id:q.string().optional()}),$Q=j.extend({hook_event_name:q.literal("SessionEnd"),reason:q.enum(["user_exit","error","max_turns","idle_timeout","ctrl_c","clear","logout","other"])}),qQ=j.extend({hook_event_name:q.literal("SubagentStop"),agent_type:q.string(),task_description:q.string().optional(),success:q.boolean(),result_summary:q.string().optional(),error:q.string().optional()}),XQ=j.extend({hook_event_name:q.literal("Notification"),notification_type:q.enum(["permission_prompt","idle_prompt","auth_success","elicitation_dialog","info","warning","error"]),title:q.string().optional(),message:q.string()}),JQ=j.extend({hook_event_name:q.literal("Compaction"),trigger:q.enum(["manual","auto"]),messages_before:q.number(),tokens_before:q.number()}),dQ=q.discriminatedUnion("hook_event_name",[o,e,t,QQ,YQ,ZQ,WQ,$Q,qQ,XQ,JQ]),GQ=q.object({hookEventName:q.literal("PreToolUse"),permissionDecision:q.nativeEnum(S).optional(),permissionDecisionReason:q.string().optional(),updatedInput:q.record(q.unknown()).optional()}),KQ=q.object({hookEventName:q.literal("PostToolUse"),additionalContext:q.string().optional(),updatedOutput:q.unknown().optional()}),VQ=q.object({hookEventName:q.literal("Stop"),continue:q.boolean().optional(),continueReason:q.string().optional()}),FQ=q.object({hookEventName:q.literal("SubagentStop"),continue:q.boolean().optional(),continueReason:q.string().optional(),additionalContext:q.string().optional()}),RQ=q.object({hookEventName:q.literal("PermissionRequest"),permissionDecision:q.enum(["approve","deny","ask"]).optional(),permissionDecisionReason:q.string().optional()}),DQ=q.object({hookEventName:q.literal("UserPromptSubmit"),updatedPrompt:q.string().optional(),contextInjection:q.string().optional()}),LQ=q.object({hookEventName:q.literal("SessionStart"),env:q.record(q.string()).optional()}),_Q=q.object({hookEventName:q.literal("Compaction"),blockCompaction:q.boolean().optional(),blockReason:q.string().optional()}),jQ=q.object({decision:q.object({behavior:q.nativeEnum(C)}).optional(),systemMessage:q.string().optional(),hookSpecificOutput:q.discriminatedUnion("hookEventName",[GQ,KQ,VQ,FQ,RQ,DQ,LQ,_Q]).optional(),suppressOutput:q.boolean().optional()}),AQ=q.object({type:q.literal("command"),command:q.string(),timeout:q.number().positive().optional(),statusMessage:q.string().optional()}),BQ=q.object({type:q.literal("prompt"),prompt:q.string(),model:q.string().optional(),timeout:q.number().positive().optional()}),OQ=q.discriminatedUnion("type",[AQ,BQ]),H=q.union([q.string(),q.array(q.string())]),UQ=q.object({tools:H.optional(),paths:H.optional(),commands:H.optional()}),_=q.object({name:q.string().optional(),matcher:UQ.optional(),hooks:q.array(OQ)}),mQ=q.object({enabled:q.boolean().optional(),defaultTimeout:q.number().positive().optional(),timeoutBehavior:q.enum(["ignore","deny","ask"]).optional(),failureBehavior:q.enum(["ignore","deny","ask"]).optional(),maxConcurrentHooks:q.number().positive().optional(),PreToolUse:q.array(_).optional(),PostToolUse:q.array(_).optional(),PostToolUseFailure:q.array(_).optional(),PermissionRequest:q.array(_).optional(),UserPromptSubmit:q.array(_).optional(),SessionStart:q.array(_).optional(),SessionEnd:q.array(_).optional(),Stop:q.array(_).optional(),SubagentStop:q.array(_).optional(),Notification:q.array(_).optional(),Compaction:q.array(_).optional()});function p(Q){let Y=jQ.safeParse(Q);if(Y.success)return{success:!0,data:Y.data};return{success:!1,error:Y.error}}class v{parse(Q,Y,Z){if(Q.timedOut){let $=Z?.timeoutBehavior||"ignore",X="Hook timeout";if($==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:Q.stdout,stderr:Q.stderr,exitCode:Q.exitCode,hook:Y};else if($==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:Q.stdout,stderr:Q.stderr,exitCode:Q.exitCode,hook:Y};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:Q.stdout,stderr:Q.stderr,exitCode:Q.exitCode,hook:Y}}let W=this.tryParseJSON(Q.stdout);if(W){let $=p(W);if(!$.success){let G="error"in $?$.error.message:"Unknown validation error",J=Z?.failureBehavior||"ignore",K=`Invalid hook output JSON: ${G}`;if(J==="deny")return{success:!1,blocking:!0,error:K,stdout:Q.stdout,stderr:Q.stderr,exitCode:Q.exitCode,hook:Y};else if(J==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${K}. Continue?`,stdout:Q.stdout,stderr:Q.stderr,exitCode:Q.exitCode,hook:Y};else return{success:!1,blocking:!1,warning:K,stdout:Q.stdout,stderr:Q.stderr,exitCode:Q.exitCode,hook:Y}}let X=$.data;if(X.decision?.behavior==="block")return{success:!1,blocking:!0,error:X.systemMessage||"Hook blocked execution",output:X,stdout:Q.stdout,stderr:Q.stderr,exitCode:Q.exitCode,hook:Y};if(X.decision?.behavior==="async")return{success:!0,output:X,stdout:Q.stdout,stderr:Q.stderr,exitCode:Q.exitCode,hook:Y};return{success:!0,output:X,stdout:Q.stdout,stderr:Q.stderr,exitCode:Q.exitCode,hook:Y}}return this.parseByExitCode(Q,Y,Z)}parseByExitCode(Q,Y,Z){let W=Q.exitCode;switch(W){case 0:return{success:!0,stdout:Q.stdout,stderr:Q.stderr,exitCode:W,hook:Y};case 2:return{success:!1,blocking:!0,error:Q.stderr||Q.stdout||"Hook returned exit code 2",stdout:Q.stdout,stderr:Q.stderr,exitCode:W,hook:Y};case 124:{let $=Z?.timeoutBehavior||"ignore",X="Hook timeout";if($==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:Q.stdout,stderr:Q.stderr,exitCode:W,hook:Y};else if($==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:Q.stdout,stderr:Q.stderr,exitCode:W,hook:Y};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:Q.stdout,stderr:Q.stderr,exitCode:W,hook:Y}}default:{let $=Z?.failureBehavior||"ignore",X=Q.stderr||Q.stdout||`Hook failed with exit code ${W}`;if($==="deny")return{success:!1,blocking:!0,error:X,stdout:Q.stdout,stderr:Q.stderr,exitCode:W,hook:Y};else if($==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${X}. Continue?`,stdout:Q.stdout,stderr:Q.stderr,exitCode:W,hook:Y};else return{success:!1,blocking:!1,warning:X,stdout:Q.stdout,stderr:Q.stderr,exitCode:W,hook:Y}}}}tryParseJSON(Q){try{let Y=Q.trim();if(!Y)return null;let Z=Y.match(/^\s*(\{[\s\S]*\})\s*$/);if(!Z)return null;return JSON.parse(Z[1])}catch{return null}}}import{spawn as l}from"node:child_process";var PQ=500;function TQ(Q){return new Promise((Y)=>setTimeout(Y,Q))}function u(Q){return Q&&typeof Q==="object"&&"code"in Q?String(Q.code):void 0}function NQ(Q,Y){return new Promise((Z)=>{let W=["/PID",String(Q),"/T"];if(Y)W.push("/F");let $=l("taskkill",W,{stdio:"ignore",windowsHide:!0}),X=!1,G=(J)=>{if(X)return;X=!0,Z(J)};$.once("error",()=>G(!1)),$.once("close",(J)=>G(J===0))})}class a{child;state="owned";terminationPromise;terminationResult;platform;gracePeriodMs;killProcess;taskkill;wait;constructor(Q,Y={}){this.child=Q;this.platform=Y.platform??process.platform,this.gracePeriodMs=Y.gracePeriodMs??PQ,this.killProcess=Y.killProcess??process.kill.bind(process),this.taskkill=Y.taskkill??NQ,this.wait=Y.wait??TQ;let Z=()=>{if(this.state==="owned")this.state="released"};Q.once("close",Z),Q.once("error",Z)}release(){if(this.state==="owned")this.state="released"}terminate(){if(this.terminationPromise)return this.terminationPromise;if(this.terminationResult)return Promise.resolve(this.terminationResult);if(this.state==="released")return this.terminationResult={success:!0,alreadyExited:!0,forced:!1},Promise.resolve(this.terminationResult);return this.state="terminating",this.terminationPromise=this.terminateOwnedTree().then((Q)=>{return this.state="released",this.terminationResult=Q,Q}),this.terminationPromise}async terminateOwnedTree(){let Q=this.child.pid;if(!Q)return{success:!1,alreadyExited:!0,forced:!1};if(this.platform==="win32"){let W=await this.taskkill(Q,!1);await this.wait(this.gracePeriodMs);let $=await this.taskkill(Q,!0);if(!W&&!$)return{success:this.signalDirectChild("SIGKILL"),alreadyExited:!1,forced:!0};return{success:!0,alreadyExited:!1,forced:!0}}let Y=this.signalPosixTree(Q,"SIGTERM");await this.wait(this.gracePeriodMs);let Z=this.signalPosixTree(Q,"SIGKILL");return{success:Y||Z,alreadyExited:!1,forced:Z}}signalPosixTree(Q,Y){if(Q<=1||Q===process.pid)return this.signalDirectChild(Y);try{return this.killProcess(-Q,Y)}catch(Z){if(u(Z)==="ESRCH")return!0;return this.signalDirectChild(Y)}}signalDirectChild(Q){try{return this.child.kill(Q)}catch(Y){return u(Y)==="ESRCH"}}}function i(Q,Y,Z={}){let W=l(Q,Y,{...Z,detached:process.platform==="win32"?Z.detached:!0,windowsHide:Z.windowsHide??!0});return{child:W,processTree:new a(W)}}class g{content="";maxSize;constructor(Q){this.maxSize=Q}append(Q){if(this.content.length<this.maxSize){let Y=this.maxSize-this.content.length;this.content+=Q.substring(0,Y)}}getContent(){return this.content}isFull(){return this.content.length>=this.maxSize}}class d{MAX_STDOUT_SIZE=1048576;MAX_STDERR_SIZE=1048576;MAX_INPUT_SIZE=102400;async execute(Q,Y,Z,W){let $=JSON.stringify(Y);if($.length>this.MAX_INPUT_SIZE)throw Error(`Hook input too large: ${$.length} bytes (max ${this.MAX_INPUT_SIZE})`);let X=this.createSafeEnv(Y),{child:G,processTree:J}=i(Q,[],{shell:!0,env:X,cwd:Z.projectDir}),K=new g(this.MAX_STDOUT_SIZE),V=new g(this.MAX_STDERR_SIZE);G.stdout?.setEncoding("utf8"),G.stderr?.setEncoding("utf8"),G.stdout?.on("data",(D)=>{K.append(D)}),G.stderr?.on("data",(D)=>{V.append(D)});try{G.stdin?.write($),G.stdin?.end()}catch(D){throw await J.terminate(),Error(`Failed to write hook input: ${D}`)}return new Promise((D,R)=>{let L=!1,F=!1,B,O=()=>{return B??=J.terminate(),B},U=null,y=()=>{if(U&&Z.abortSignal)Z.abortSignal.removeEventListener("abort",U),U=null},M=setTimeout(()=>{L=!0,O()},W);if(G.on("close",async(w)=>{if(F)return;if(F=!0,clearTimeout(M),y(),L)await O();D({stdout:K.getContent(),stderr:V.getContent(),exitCode:L?124:w??1,timedOut:L})}),G.on("error",(w)=>{if(F)return;F=!0,clearTimeout(M),y(),R(w)}),Z.abortSignal){if(U=()=>{if(F)return;F=!0,clearTimeout(M),y(),O().then(()=>{D({stdout:K.getContent(),stderr:"Hook cancelled by abort signal",exitCode:1,timedOut:!1})})},Z.abortSignal.addEventListener("abort",U),Z.abortSignal.aborted)U()}})}createSafeEnv(Q){return{BLADE_PROJECT_DIR:Q.project_dir,BLADE_SESSION_ID:Q.session_id,BLADE_HOOK_EVENT:Q.hook_event_name,BLADE_TOOL_NAME:"tool_name"in Q?Q.tool_name:"",BLADE_TOOL_USE_ID:"tool_use_id"in Q?Q.tool_use_id:"",PATH:process.env.PATH||"",HOME:process.env.HOME||"",USER:process.env.USER||"",SHELL:process.env.SHELL||"/bin/sh"}}}class P extends Error{constructor(Q){super(Q);this.name="HttpHookSecurityError"}}function c(Q,Y={}){let Z;try{Z=new URL(Q)}catch{throw new P(`Invalid URL: ${Q}`)}if(Z.protocol!=="https:"&&Z.protocol!=="http:")throw new P(`Only http/https supported, got: ${Z.protocol}`);let W=Z.hostname.toLowerCase();if(bQ(W,Y.allowedHosts))return;if(Z.protocol==="http:"&&!Y.allowHttp)throw new P(`HTTP (non-TLS) blocked for ${W}; use https:// or add to allowedHosts`);if(yQ(W)&&!Y.allowLoopback)throw new P(`Loopback address blocked: ${W}; enable policy.allowLoopback or add to allowedHosts`);if(MQ(W)&&!Y.allowPrivateRanges)throw new P(`Private/link-local address blocked: ${W}; enable policy.allowPrivateRanges or add to allowedHosts`)}function bQ(Q,Y){if(!Y||Y.length===0)return!1;return Y.some((Z)=>{let W=Z.toLowerCase();if(W===Q)return!0;if(W.startsWith("*.")){let $=W.slice(1);return Q.endsWith($)&&Q.length>$.length}return!1})}function yQ(Q){if(Q==="localhost")return!0;if(Q==="::1"||Q==="[::1]")return!0;if(/^127\.\d+\.\d+\.\d+$/.test(Q))return!0;return!1}function MQ(Q){let Y=Q.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(!Y)return!1;let[Z,W]=Y.slice(1).map(Number);if(Z===10)return!0;if(Z===172&&W>=16&&W<=31)return!0;if(Z===192&&W===168)return!0;if(Z===169&&W===254)return!0;return!1}function s(Q){if(!Q)return{};let Y={};for(let[Z,W]of Object.entries(Q))Y[Z]=W.replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,($,X)=>{return process.env[X]??`\${${X}}`});return Y}var wQ=r("Execution"),CQ={PreToolUse:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "...", "updatedInput": { ... } }',PostToolUse:'{ "additionalContext": "注入到工具结果的额外信息", "updatedOutput": "修改后的工具输出" }',Stop:'{ "continue": true, "continueReason": "继续执行的原因" } // continue: true 表示阻止停止',SubagentStop:'{ "continue": true, "continueReason": "...", "additionalContext": "..." }',PermissionRequest:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "..." }',UserPromptSubmit:'{ "updatedPrompt": "修改后的提示词", "contextInjection": "注入的上下文" }',Compaction:'{ "blockCompaction": true, "blockReason": "阻止压缩的原因" }'};class m{processExecutor=new d;outputParser=new v;chatServiceCache=new Map;async executePreToolHooks(Q,Y,Z){if(Q.length===0)return{decision:"allow"};let W="tool_input"in Y?Y.tool_input:{},$=[];for(let X of Q)try{let G={...Y,...W&&{tool_input:W}},J=await this.executeHook(X,G,Z);if(!J.success){if(J.blocking)return{decision:"deny",reason:J.error};if(J.needsConfirmation)return{decision:"ask",reason:J.warning||J.error};if(J.warning)$.push(J.warning);continue}let K=J.output?.hookSpecificOutput;if(K&&"permissionDecision"in K){switch(K.permissionDecision){case"deny":return{decision:"deny",reason:K.permissionDecisionReason};case"ask":return{decision:"ask",reason:K.permissionDecisionReason};case"allow":break}if("updatedInput"in K&&K.updatedInput)W={...W,...K.updatedInput}}}catch(G){let J=G instanceof Error?G.message:String(G);if($.push(`Hook failed: ${J}`),Z.config.failureBehavior==="deny")return{decision:"deny",reason:J};else if(Z.config.failureBehavior==="ask")return{decision:"ask",reason:`Hook failed: ${J}. Continue?`}}return{decision:"allow",modifiedInput:W,warning:$.length>0?$.join(`
|
|
1
|
+
import{Bb as n}from"./chunk-4dmdn3a9.js";import{Zb as r}from"./chunk-a7yjnqhd.js";import{$b as b}from"./chunk-f9ybv4ph.js";import{nanoid as A}from"nanoid";var N;((R)=>{R.PreToolUse="PreToolUse";R.PostToolUse="PostToolUse";R.PostToolUseFailure="PostToolUseFailure";R.PermissionRequest="PermissionRequest";R.UserPromptSubmit="UserPromptSubmit";R.SessionStart="SessionStart";R.SessionEnd="SessionEnd";R.Stop="Stop";R.SubagentStop="SubagentStop";R.Notification="Notification";R.Compaction="Compaction"})(N||={});var C;((W)=>{W.Approve="approve";W.Block="block";W.Async="async"})(C||={});var S;((W)=>{W.Allow="allow";W.Deny="deny";W.Ask="ask"})(S||={});var I={enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,httpPolicy:{},PreToolUse:[],PostToolUse:[{name:"builtin:code-review-sensor",matcher:{tools:"Edit|Write"},hooks:[{type:"prompt",prompt:"审查此代码变更,重点检查:"+"1) 安全漏洞(命令注入、XSS、SQL 注入、硬编码密钥/密码)"+"2) 明显的逻辑错误(无限循环、off-by-one、空引用)"+"3) 类型安全问题。"+"如果发现严重问题,将问题描述放在 hookSpecificOutput.additionalContext 中。"+"如果没有严重问题,返回 approve。",model:void 0,timeout:15}]}],PostToolUseFailure:[],PermissionRequest:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]};function f(Q,Y){return{...Q,...Y,PreToolUse:Y.PreToolUse??Q.PreToolUse,PostToolUse:Y.PostToolUse??Q.PostToolUse,PostToolUseFailure:Y.PostToolUseFailure??Q.PostToolUseFailure,PermissionRequest:Y.PermissionRequest??Q.PermissionRequest,UserPromptSubmit:Y.UserPromptSubmit??Q.UserPromptSubmit,SessionStart:Y.SessionStart??Q.SessionStart,SessionEnd:Y.SessionEnd??Q.SessionEnd,Stop:Y.Stop??Q.Stop,SubagentStop:Y.SubagentStop??Q.SubagentStop,Notification:Y.Notification??Q.Notification,Compaction:Y.Compaction??Q.Compaction}}function x(){let Q={};if(process.env.BLADE_DISABLE_HOOKS==="true")Q.enabled=!1;if(process.env.BLADE_HOOK_TIMEOUT){let Y=parseInt(process.env.BLADE_HOOK_TIMEOUT,10);if(!isNaN(Y)&&Y>0)Q.defaultTimeout=Y}return Q}class z{executedHooks=new Map;canExecute(Q,Y){if(!this.executedHooks.has(Q))this.executedHooks.set(Q,new Set);if(this.executedHooks.get(Q).has(Y))return console.warn(`[HookGuard] Hook ${Y} for tool ${Q} already executed, skipping`),!1;return!0}markExecuted(Q,Y){let Z=this.executedHooks.get(Q);if(Z)Z.add(Y)}cleanup(Q){this.executedHooks.delete(Q)}cleanupAll(){this.executedHooks.clear()}}import{z as q}from"zod";var j=q.object({hook_event_name:q.nativeEnum(N),hook_execution_id:q.string(),timestamp:q.string(),project_dir:q.string(),session_id:q.string(),permission_mode:q.enum(["default","autoEdit","yolo","plan"]),_metadata:q.object({blade_version:q.string(),hook_timeout_ms:q.number()}).optional()}),o=j.extend({hook_event_name:q.literal("PreToolUse"),tool_name:q.string(),tool_use_id:q.string(),tool_input:q.record(q.unknown())}),e=j.extend({hook_event_name:q.literal("PostToolUse"),tool_name:q.string(),tool_use_id:q.string(),tool_input:q.record(q.unknown()),tool_response:q.unknown()}),t=j.extend({hook_event_name:q.literal("Stop"),reason:q.string().optional()}),QQ=j.extend({hook_event_name:q.literal("PostToolUseFailure"),tool_name:q.string(),tool_use_id:q.string(),tool_input:q.record(q.unknown()),error:q.string(),error_type:q.string().optional(),is_interrupt:q.boolean(),is_timeout:q.boolean()}),YQ=j.extend({hook_event_name:q.literal("PermissionRequest"),tool_name:q.string(),tool_use_id:q.string(),tool_input:q.record(q.unknown())}),ZQ=j.extend({hook_event_name:q.literal("UserPromptSubmit"),user_prompt:q.string(),has_images:q.boolean(),image_count:q.number()}),WQ=j.extend({hook_event_name:q.literal("SessionStart"),is_resume:q.boolean(),resume_session_id:q.string().optional()}),$Q=j.extend({hook_event_name:q.literal("SessionEnd"),reason:q.enum(["user_exit","error","max_turns","idle_timeout","ctrl_c","clear","logout","other"])}),qQ=j.extend({hook_event_name:q.literal("SubagentStop"),agent_type:q.string(),task_description:q.string().optional(),success:q.boolean(),result_summary:q.string().optional(),error:q.string().optional()}),XQ=j.extend({hook_event_name:q.literal("Notification"),notification_type:q.enum(["permission_prompt","idle_prompt","auth_success","elicitation_dialog","info","warning","error"]),title:q.string().optional(),message:q.string()}),JQ=j.extend({hook_event_name:q.literal("Compaction"),trigger:q.enum(["manual","auto"]),messages_before:q.number(),tokens_before:q.number()}),dQ=q.discriminatedUnion("hook_event_name",[o,e,t,QQ,YQ,ZQ,WQ,$Q,qQ,XQ,JQ]),GQ=q.object({hookEventName:q.literal("PreToolUse"),permissionDecision:q.nativeEnum(S).optional(),permissionDecisionReason:q.string().optional(),updatedInput:q.record(q.unknown()).optional()}),KQ=q.object({hookEventName:q.literal("PostToolUse"),additionalContext:q.string().optional(),updatedOutput:q.unknown().optional()}),VQ=q.object({hookEventName:q.literal("Stop"),continue:q.boolean().optional(),continueReason:q.string().optional()}),FQ=q.object({hookEventName:q.literal("SubagentStop"),continue:q.boolean().optional(),continueReason:q.string().optional(),additionalContext:q.string().optional()}),RQ=q.object({hookEventName:q.literal("PermissionRequest"),permissionDecision:q.enum(["approve","deny","ask"]).optional(),permissionDecisionReason:q.string().optional()}),DQ=q.object({hookEventName:q.literal("UserPromptSubmit"),updatedPrompt:q.string().optional(),contextInjection:q.string().optional()}),LQ=q.object({hookEventName:q.literal("SessionStart"),env:q.record(q.string()).optional()}),_Q=q.object({hookEventName:q.literal("Compaction"),blockCompaction:q.boolean().optional(),blockReason:q.string().optional()}),jQ=q.object({decision:q.object({behavior:q.nativeEnum(C)}).optional(),systemMessage:q.string().optional(),hookSpecificOutput:q.discriminatedUnion("hookEventName",[GQ,KQ,VQ,FQ,RQ,DQ,LQ,_Q]).optional(),suppressOutput:q.boolean().optional()}),AQ=q.object({type:q.literal("command"),command:q.string(),timeout:q.number().positive().optional(),statusMessage:q.string().optional()}),BQ=q.object({type:q.literal("prompt"),prompt:q.string(),model:q.string().optional(),timeout:q.number().positive().optional()}),OQ=q.discriminatedUnion("type",[AQ,BQ]),H=q.union([q.string(),q.array(q.string())]),UQ=q.object({tools:H.optional(),paths:H.optional(),commands:H.optional()}),_=q.object({name:q.string().optional(),matcher:UQ.optional(),hooks:q.array(OQ)}),mQ=q.object({enabled:q.boolean().optional(),defaultTimeout:q.number().positive().optional(),timeoutBehavior:q.enum(["ignore","deny","ask"]).optional(),failureBehavior:q.enum(["ignore","deny","ask"]).optional(),maxConcurrentHooks:q.number().positive().optional(),PreToolUse:q.array(_).optional(),PostToolUse:q.array(_).optional(),PostToolUseFailure:q.array(_).optional(),PermissionRequest:q.array(_).optional(),UserPromptSubmit:q.array(_).optional(),SessionStart:q.array(_).optional(),SessionEnd:q.array(_).optional(),Stop:q.array(_).optional(),SubagentStop:q.array(_).optional(),Notification:q.array(_).optional(),Compaction:q.array(_).optional()});function p(Q){let Y=jQ.safeParse(Q);if(Y.success)return{success:!0,data:Y.data};return{success:!1,error:Y.error}}class v{parse(Q,Y,Z){if(Q.timedOut){let $=Z?.timeoutBehavior||"ignore",X="Hook timeout";if($==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:Q.stdout,stderr:Q.stderr,exitCode:Q.exitCode,hook:Y};else if($==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:Q.stdout,stderr:Q.stderr,exitCode:Q.exitCode,hook:Y};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:Q.stdout,stderr:Q.stderr,exitCode:Q.exitCode,hook:Y}}let W=this.tryParseJSON(Q.stdout);if(W){let $=p(W);if(!$.success){let G="error"in $?$.error.message:"Unknown validation error",J=Z?.failureBehavior||"ignore",K=`Invalid hook output JSON: ${G}`;if(J==="deny")return{success:!1,blocking:!0,error:K,stdout:Q.stdout,stderr:Q.stderr,exitCode:Q.exitCode,hook:Y};else if(J==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${K}. Continue?`,stdout:Q.stdout,stderr:Q.stderr,exitCode:Q.exitCode,hook:Y};else return{success:!1,blocking:!1,warning:K,stdout:Q.stdout,stderr:Q.stderr,exitCode:Q.exitCode,hook:Y}}let X=$.data;if(X.decision?.behavior==="block")return{success:!1,blocking:!0,error:X.systemMessage||"Hook blocked execution",output:X,stdout:Q.stdout,stderr:Q.stderr,exitCode:Q.exitCode,hook:Y};if(X.decision?.behavior==="async")return{success:!0,output:X,stdout:Q.stdout,stderr:Q.stderr,exitCode:Q.exitCode,hook:Y};return{success:!0,output:X,stdout:Q.stdout,stderr:Q.stderr,exitCode:Q.exitCode,hook:Y}}return this.parseByExitCode(Q,Y,Z)}parseByExitCode(Q,Y,Z){let W=Q.exitCode;switch(W){case 0:return{success:!0,stdout:Q.stdout,stderr:Q.stderr,exitCode:W,hook:Y};case 2:return{success:!1,blocking:!0,error:Q.stderr||Q.stdout||"Hook returned exit code 2",stdout:Q.stdout,stderr:Q.stderr,exitCode:W,hook:Y};case 124:{let $=Z?.timeoutBehavior||"ignore",X="Hook timeout";if($==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:Q.stdout,stderr:Q.stderr,exitCode:W,hook:Y};else if($==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:Q.stdout,stderr:Q.stderr,exitCode:W,hook:Y};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:Q.stdout,stderr:Q.stderr,exitCode:W,hook:Y}}default:{let $=Z?.failureBehavior||"ignore",X=Q.stderr||Q.stdout||`Hook failed with exit code ${W}`;if($==="deny")return{success:!1,blocking:!0,error:X,stdout:Q.stdout,stderr:Q.stderr,exitCode:W,hook:Y};else if($==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${X}. Continue?`,stdout:Q.stdout,stderr:Q.stderr,exitCode:W,hook:Y};else return{success:!1,blocking:!1,warning:X,stdout:Q.stdout,stderr:Q.stderr,exitCode:W,hook:Y}}}}tryParseJSON(Q){try{let Y=Q.trim();if(!Y)return null;let Z=Y.match(/^\s*(\{[\s\S]*\})\s*$/);if(!Z)return null;return JSON.parse(Z[1])}catch{return null}}}import{spawn as l}from"node:child_process";var PQ=500;function TQ(Q){return new Promise((Y)=>setTimeout(Y,Q))}function u(Q){return Q&&typeof Q==="object"&&"code"in Q?String(Q.code):void 0}function NQ(Q,Y){return new Promise((Z)=>{let W=["/PID",String(Q),"/T"];if(Y)W.push("/F");let $=l("taskkill",W,{stdio:"ignore",windowsHide:!0}),X=!1,G=(J)=>{if(X)return;X=!0,Z(J)};$.once("error",()=>G(!1)),$.once("close",(J)=>G(J===0))})}class a{child;state="owned";terminationPromise;terminationResult;platform;gracePeriodMs;killProcess;taskkill;wait;constructor(Q,Y={}){this.child=Q;this.platform=Y.platform??process.platform,this.gracePeriodMs=Y.gracePeriodMs??PQ,this.killProcess=Y.killProcess??process.kill.bind(process),this.taskkill=Y.taskkill??NQ,this.wait=Y.wait??TQ;let Z=()=>{if(this.state==="owned")this.state="released"};Q.once("close",Z),Q.once("error",Z)}release(){if(this.state==="owned")this.state="released"}terminate(){if(this.terminationPromise)return this.terminationPromise;if(this.terminationResult)return Promise.resolve(this.terminationResult);if(this.state==="released")return this.terminationResult={success:!0,alreadyExited:!0,forced:!1},Promise.resolve(this.terminationResult);return this.state="terminating",this.terminationPromise=this.terminateOwnedTree().then((Q)=>{return this.state="released",this.terminationResult=Q,Q}),this.terminationPromise}async terminateOwnedTree(){let Q=this.child.pid;if(!Q)return{success:!1,alreadyExited:!0,forced:!1};if(this.platform==="win32"){let W=await this.taskkill(Q,!1);await this.wait(this.gracePeriodMs);let $=await this.taskkill(Q,!0);if(!W&&!$)return{success:this.signalDirectChild("SIGKILL"),alreadyExited:!1,forced:!0};return{success:!0,alreadyExited:!1,forced:!0}}let Y=this.signalPosixTree(Q,"SIGTERM");await this.wait(this.gracePeriodMs);let Z=this.signalPosixTree(Q,"SIGKILL");return{success:Y||Z,alreadyExited:!1,forced:Z}}signalPosixTree(Q,Y){if(Q<=1||Q===process.pid)return this.signalDirectChild(Y);try{return this.killProcess(-Q,Y)}catch(Z){if(u(Z)==="ESRCH")return!0;return this.signalDirectChild(Y)}}signalDirectChild(Q){try{return this.child.kill(Q)}catch(Y){return u(Y)==="ESRCH"}}}function i(Q,Y,Z={}){let W=l(Q,Y,{...Z,detached:process.platform==="win32"?Z.detached:!0,windowsHide:Z.windowsHide??!0});return{child:W,processTree:new a(W)}}class g{content="";maxSize;constructor(Q){this.maxSize=Q}append(Q){if(this.content.length<this.maxSize){let Y=this.maxSize-this.content.length;this.content+=Q.substring(0,Y)}}getContent(){return this.content}isFull(){return this.content.length>=this.maxSize}}class d{MAX_STDOUT_SIZE=1048576;MAX_STDERR_SIZE=1048576;MAX_INPUT_SIZE=102400;async execute(Q,Y,Z,W){let $=JSON.stringify(Y);if($.length>this.MAX_INPUT_SIZE)throw Error(`Hook input too large: ${$.length} bytes (max ${this.MAX_INPUT_SIZE})`);let X=this.createSafeEnv(Y),{child:G,processTree:J}=i(Q,[],{shell:!0,env:X,cwd:Z.projectDir}),K=new g(this.MAX_STDOUT_SIZE),V=new g(this.MAX_STDERR_SIZE);G.stdout?.setEncoding("utf8"),G.stderr?.setEncoding("utf8"),G.stdout?.on("data",(D)=>{K.append(D)}),G.stderr?.on("data",(D)=>{V.append(D)});try{G.stdin?.write($),G.stdin?.end()}catch(D){throw await J.terminate(),Error(`Failed to write hook input: ${D}`)}return new Promise((D,R)=>{let L=!1,F=!1,B,O=()=>{return B??=J.terminate(),B},U=null,y=()=>{if(U&&Z.abortSignal)Z.abortSignal.removeEventListener("abort",U),U=null},M=setTimeout(()=>{L=!0,O()},W);if(G.on("close",async(w)=>{if(F)return;if(F=!0,clearTimeout(M),y(),L)await O();D({stdout:K.getContent(),stderr:V.getContent(),exitCode:L?124:w??1,timedOut:L})}),G.on("error",(w)=>{if(F)return;F=!0,clearTimeout(M),y(),R(w)}),Z.abortSignal){if(U=()=>{if(F)return;F=!0,clearTimeout(M),y(),O().then(()=>{D({stdout:K.getContent(),stderr:"Hook cancelled by abort signal",exitCode:1,timedOut:!1})})},Z.abortSignal.addEventListener("abort",U),Z.abortSignal.aborted)U()}})}createSafeEnv(Q){return{BLADE_PROJECT_DIR:Q.project_dir,BLADE_SESSION_ID:Q.session_id,BLADE_HOOK_EVENT:Q.hook_event_name,BLADE_TOOL_NAME:"tool_name"in Q?Q.tool_name:"",BLADE_TOOL_USE_ID:"tool_use_id"in Q?Q.tool_use_id:"",PATH:process.env.PATH||"",HOME:process.env.HOME||"",USER:process.env.USER||"",SHELL:process.env.SHELL||"/bin/sh"}}}class P extends Error{constructor(Q){super(Q);this.name="HttpHookSecurityError"}}function c(Q,Y={}){let Z;try{Z=new URL(Q)}catch{throw new P(`Invalid URL: ${Q}`)}if(Z.protocol!=="https:"&&Z.protocol!=="http:")throw new P(`Only http/https supported, got: ${Z.protocol}`);let W=Z.hostname.toLowerCase();if(bQ(W,Y.allowedHosts))return;if(Z.protocol==="http:"&&!Y.allowHttp)throw new P(`HTTP (non-TLS) blocked for ${W}; use https:// or add to allowedHosts`);if(yQ(W)&&!Y.allowLoopback)throw new P(`Loopback address blocked: ${W}; enable policy.allowLoopback or add to allowedHosts`);if(MQ(W)&&!Y.allowPrivateRanges)throw new P(`Private/link-local address blocked: ${W}; enable policy.allowPrivateRanges or add to allowedHosts`)}function bQ(Q,Y){if(!Y||Y.length===0)return!1;return Y.some((Z)=>{let W=Z.toLowerCase();if(W===Q)return!0;if(W.startsWith("*.")){let $=W.slice(1);return Q.endsWith($)&&Q.length>$.length}return!1})}function yQ(Q){if(Q==="localhost")return!0;if(Q==="::1"||Q==="[::1]")return!0;if(/^127\.\d+\.\d+\.\d+$/.test(Q))return!0;return!1}function MQ(Q){let Y=Q.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(!Y)return!1;let[Z,W]=Y.slice(1).map(Number);if(Z===10)return!0;if(Z===172&&W>=16&&W<=31)return!0;if(Z===192&&W===168)return!0;if(Z===169&&W===254)return!0;return!1}function s(Q){if(!Q)return{};let Y={};for(let[Z,W]of Object.entries(Q))Y[Z]=W.replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,($,X)=>{return process.env[X]??`\${${X}}`});return Y}var wQ=r("Execution"),CQ={PreToolUse:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "...", "updatedInput": { ... } }',PostToolUse:'{ "additionalContext": "注入到工具结果的额外信息", "updatedOutput": "修改后的工具输出" }',Stop:'{ "continue": true, "continueReason": "继续执行的原因" } // continue: true 表示阻止停止',SubagentStop:'{ "continue": true, "continueReason": "...", "additionalContext": "..." }',PermissionRequest:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "..." }',UserPromptSubmit:'{ "updatedPrompt": "修改后的提示词", "contextInjection": "注入的上下文" }',Compaction:'{ "blockCompaction": true, "blockReason": "阻止压缩的原因" }'};class m{processExecutor=new d;outputParser=new v;chatServiceCache=new Map;async executePreToolHooks(Q,Y,Z){if(Q.length===0)return{decision:"allow"};let W="tool_input"in Y?Y.tool_input:{},$=[];for(let X of Q)try{let G={...Y,...W&&{tool_input:W}},J=await this.executeHook(X,G,Z);if(!J.success){if(J.blocking)return{decision:"deny",reason:J.error};if(J.needsConfirmation)return{decision:"ask",reason:J.warning||J.error};if(J.warning)$.push(J.warning);continue}let K=J.output?.hookSpecificOutput;if(K&&"permissionDecision"in K){switch(K.permissionDecision){case"deny":return{decision:"deny",reason:K.permissionDecisionReason};case"ask":return{decision:"ask",reason:K.permissionDecisionReason};case"allow":break}if("updatedInput"in K&&K.updatedInput)W={...W,...K.updatedInput}}}catch(G){let J=G instanceof Error?G.message:String(G);if($.push(`Hook failed: ${J}`),Z.config.failureBehavior==="deny")return{decision:"deny",reason:J};else if(Z.config.failureBehavior==="ask")return{decision:"ask",reason:`Hook failed: ${J}. Continue?`}}return{decision:"allow",modifiedInput:W,warning:$.length>0?$.join(`
|
|
2
2
|
`):void 0}}async executePostToolHooks(Q,Y,Z){if(Q.length===0)return{};let W=Z.config.maxConcurrentHooks||5,$=await this.executeHooksConcurrently(Q,Y,Z,W),X=[],G=void 0,J=[];for(let K of $){if(!K.success&&K.warning){J.push(K.warning);continue}let V=K.output?.hookSpecificOutput;if(V&&"additionalContext"in V){if(V.additionalContext)X.push(V.additionalContext);if("updatedOutput"in V&&V.updatedOutput!==void 0)G=V.updatedOutput}}return{additionalContext:X.length>0?X.join(`
|
|
3
3
|
|
|
4
4
|
`):void 0,modifiedOutput:G,warning:J.length>0?J.join(`
|
|
@@ -21,7 +21,7 @@ import{Ab as n}from"./chunk-v61bja34.js";import{Yb as r}from"./chunk-h79044h0.js
|
|
|
21
21
|
`):void 0}}async executeNotificationHooks(Q,Y,Z){let W="message"in Y?Y.message:"";if(Q.length===0)return{suppress:!1,message:W};let $=[],X=!1,G=W;for(let J of Q)try{let K=await this.executeHook(J,Y,Z);if(!K.success){if(K.warning)$.push(K.warning);continue}if(K.output?.suppressOutput){X=!0;break}if(K.stdout&&K.stdout.trim())G=K.stdout.trim()}catch(K){let V=K instanceof Error?K.message:String(K);$.push(`Hook failed: ${V}`)}return{suppress:X,message:G,warning:$.length>0?$.join(`
|
|
22
22
|
`):void 0}}async executeCompactionHooks(Q,Y,Z){if(Q.length===0)return{blockCompaction:!1};let W=[];for(let $ of Q)try{let X=await this.executeHook($,Y,Z);if(!X.success){if(X.warning)W.push(X.warning);continue}let G=X.output?.hookSpecificOutput;if(G&&"blockCompaction"in G&&G.blockCompaction)return{blockCompaction:!0,blockReason:G.blockReason,warning:W.length>0?W.join(`
|
|
23
23
|
`):void 0}}catch(X){let G=X instanceof Error?X.message:String(X);W.push(`Hook failed: ${G}`)}return{blockCompaction:!1,warning:W.length>0?W.join(`
|
|
24
|
-
`):void 0}}async executeHook(Q,Y,Z){if(Q.type==="command")return this.executeCommandHook(Q,Y,Z);if(Q.type==="prompt")return this.executePromptHook(Q,Y,Z);if(Q.type==="function")return this.executeFunctionHook(Q,Y,Z);if(Q.type==="http")return this.executeHttpHook(Q,Y,Z);throw Error(`Hook type ${Q.type} not supported`)}async executeCommandHook(Q,Y,Z){let W=(Q.timeout??Z.config.defaultTimeout??60)*1000;try{let $=await this.processExecutor.execute(Q.command,Y,Z,W);return this.outputParser.parse($,Q,{timeoutBehavior:Z.config.timeoutBehavior,failureBehavior:Z.config.failureBehavior})}catch($){return{success:!1,blocking:!1,error:$ instanceof Error?$.message:String($),hook:Q}}}async executePromptHook(Q,Y,Z){let W=(Q.timeout??Z.config.defaultTimeout??60)*1000;try{let $=await this.getOrCreateChatService(Q.model),X="hook_event_name"in Y?String(Y.hook_event_name):"Unknown",G=this.buildPromptHookSystemMessage(Q,X),J=JSON.stringify(Y,null,2),K=new AbortController,V=setTimeout(()=>K.abort(),W),D;try{D=(await $.chat([{role:"system",content:G},{role:"user",content:J}],void 0,K.signal)).content}catch(L){if(K.signal.aborted||L instanceof Error&&L.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},Q,{timeoutBehavior:Z.config.timeoutBehavior,failureBehavior:Z.config.failureBehavior});throw L}finally{clearTimeout(V)}let R=this.extractJsonFromLLMResponse(D);return this.outputParser.parse({stdout:R,stderr:"",exitCode:0,timedOut:!1},Q,{timeoutBehavior:Z.config.timeoutBehavior,failureBehavior:Z.config.failureBehavior})}catch($){return wQ.warn(`[PromptHook] 执行失败: ${$ instanceof Error?$.message:String($)}`),{success:!1,blocking:!1,error:$ instanceof Error?$.message:String($),hook:Q}}}async executeFunctionHook(Q,Y,Z){let W=(Q.timeout??10)*1000;try{let $=await this.runFunctionWithTimeout(Q.handler,Y,Z,W);if($===void 0||$===null)return{success:!0,hook:Q};let X={stdout:JSON.stringify($),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(X,Q,{timeoutBehavior:Z.config.timeoutBehavior,failureBehavior:Z.config.failureBehavior})}catch($){if($.isTimeout){let X={stdout:"",stderr:`Function hook timeout after ${W}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse(X,Q,{timeoutBehavior:Z.config.timeoutBehavior,failureBehavior:Z.config.failureBehavior})}return{success:!1,blocking:!1,error:$ instanceof Error?$.message:String($),hook:Q}}}runFunctionWithTimeout(Q,Y,Z,W){return new Promise(($,X)=>{let G=!1,J=setTimeout(()=>{if(G)return;G=!0;let V=Object.assign(Error(`Function hook timed out after ${W}ms`),{isTimeout:!0});X(V)},W),K=()=>{if(G)return;G=!0,clearTimeout(J),X(Error("Function hook aborted"))};Z.abortSignal?.addEventListener("abort",K,{once:!0}),Promise.resolve().then(()=>Q(Y,Z)).then((V)=>{if(G)return;G=!0,clearTimeout(J),Z.abortSignal?.removeEventListener("abort",K),$(V)},(V)=>{if(G)return;G=!0,clearTimeout(J),Z.abortSignal?.removeEventListener("abort",K),X(V)})})}async executeHttpHook(Q,Y,Z){let W=(Q.timeout??10)*1000,$=Q.maxResponseBytes??262144,X=Math.max(1,(Q.retries??0)+1);try{c(Q.url,Z.config.httpPolicy)}catch(V){return{success:!1,blocking:!0,error:V instanceof Error?V.message:String(V),hook:Q}}let G={"Content-Type":"application/json",...s(Q.headers)},J=JSON.stringify(Y),K;for(let V=0;V<X;V++){if(V>0){let F=Math.min(2**V*200,5000);await new Promise((B)=>setTimeout(B,F))}let D=new AbortController,R=setTimeout(()=>D.abort(),W),L=()=>D.abort();Z.abortSignal?.addEventListener("abort",L,{once:!0});try{let F=await fetch(Q.url,{method:"POST",headers:G,body:J,redirect:"manual",signal:D.signal});if(F.status>=300&&F.status<400){K=Error(`HTTP hook received redirect (${F.status}); redirects are disabled`);continue}if(!F.ok){if(K=Error(`HTTP hook returned ${F.status} ${F.statusText}`),F.status>=400&&F.status<500)break;continue}let O={stdout:await SQ(F,$),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(O,Q,{timeoutBehavior:Z.config.timeoutBehavior,failureBehavior:Z.config.failureBehavior})}catch(F){let B=F.name==="AbortError"||F.code==="ABORT_ERR";if(B&&Z.abortSignal?.aborted){K=Error("HTTP hook aborted by caller");break}if(B){let O={stdout:"",stderr:`HTTP hook timeout after ${W}ms`,exitCode:124,timedOut:!0};if(V===X-1)return this.outputParser.parse(O,Q,{timeoutBehavior:Z.config.timeoutBehavior,failureBehavior:Z.config.failureBehavior});K=Error(`HTTP hook timeout attempt ${V+1}`);continue}K=F}finally{clearTimeout(R),Z.abortSignal?.removeEventListener("abort",L)}}return{success:!1,blocking:!1,error:K?.message??"HTTP hook failed",hook:Q}}async getOrCreateChatService(Q){let Y=Q||"__default__",Z=this.chatServiceCache.get(Y);if(Z)return Z;let{ensureStoreInitialized:W,getCurrentModel:$,getModelById:X}=await import("./chunk-
|
|
24
|
+
`):void 0}}async executeHook(Q,Y,Z){if(Q.type==="command")return this.executeCommandHook(Q,Y,Z);if(Q.type==="prompt")return this.executePromptHook(Q,Y,Z);if(Q.type==="function")return this.executeFunctionHook(Q,Y,Z);if(Q.type==="http")return this.executeHttpHook(Q,Y,Z);throw Error(`Hook type ${Q.type} not supported`)}async executeCommandHook(Q,Y,Z){let W=(Q.timeout??Z.config.defaultTimeout??60)*1000;try{let $=await this.processExecutor.execute(Q.command,Y,Z,W);return this.outputParser.parse($,Q,{timeoutBehavior:Z.config.timeoutBehavior,failureBehavior:Z.config.failureBehavior})}catch($){return{success:!1,blocking:!1,error:$ instanceof Error?$.message:String($),hook:Q}}}async executePromptHook(Q,Y,Z){let W=(Q.timeout??Z.config.defaultTimeout??60)*1000;try{let $=await this.getOrCreateChatService(Q.model),X="hook_event_name"in Y?String(Y.hook_event_name):"Unknown",G=this.buildPromptHookSystemMessage(Q,X),J=JSON.stringify(Y,null,2),K=new AbortController,V=setTimeout(()=>K.abort(),W),D;try{D=(await $.chat([{role:"system",content:G},{role:"user",content:J}],void 0,K.signal)).content}catch(L){if(K.signal.aborted||L instanceof Error&&L.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},Q,{timeoutBehavior:Z.config.timeoutBehavior,failureBehavior:Z.config.failureBehavior});throw L}finally{clearTimeout(V)}let R=this.extractJsonFromLLMResponse(D);return this.outputParser.parse({stdout:R,stderr:"",exitCode:0,timedOut:!1},Q,{timeoutBehavior:Z.config.timeoutBehavior,failureBehavior:Z.config.failureBehavior})}catch($){return wQ.warn(`[PromptHook] 执行失败: ${$ instanceof Error?$.message:String($)}`),{success:!1,blocking:!1,error:$ instanceof Error?$.message:String($),hook:Q}}}async executeFunctionHook(Q,Y,Z){let W=(Q.timeout??10)*1000;try{let $=await this.runFunctionWithTimeout(Q.handler,Y,Z,W);if($===void 0||$===null)return{success:!0,hook:Q};let X={stdout:JSON.stringify($),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(X,Q,{timeoutBehavior:Z.config.timeoutBehavior,failureBehavior:Z.config.failureBehavior})}catch($){if($.isTimeout){let X={stdout:"",stderr:`Function hook timeout after ${W}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse(X,Q,{timeoutBehavior:Z.config.timeoutBehavior,failureBehavior:Z.config.failureBehavior})}return{success:!1,blocking:!1,error:$ instanceof Error?$.message:String($),hook:Q}}}runFunctionWithTimeout(Q,Y,Z,W){return new Promise(($,X)=>{let G=!1,J=setTimeout(()=>{if(G)return;G=!0;let V=Object.assign(Error(`Function hook timed out after ${W}ms`),{isTimeout:!0});X(V)},W),K=()=>{if(G)return;G=!0,clearTimeout(J),X(Error("Function hook aborted"))};Z.abortSignal?.addEventListener("abort",K,{once:!0}),Promise.resolve().then(()=>Q(Y,Z)).then((V)=>{if(G)return;G=!0,clearTimeout(J),Z.abortSignal?.removeEventListener("abort",K),$(V)},(V)=>{if(G)return;G=!0,clearTimeout(J),Z.abortSignal?.removeEventListener("abort",K),X(V)})})}async executeHttpHook(Q,Y,Z){let W=(Q.timeout??10)*1000,$=Q.maxResponseBytes??262144,X=Math.max(1,(Q.retries??0)+1);try{c(Q.url,Z.config.httpPolicy)}catch(V){return{success:!1,blocking:!0,error:V instanceof Error?V.message:String(V),hook:Q}}let G={"Content-Type":"application/json",...s(Q.headers)},J=JSON.stringify(Y),K;for(let V=0;V<X;V++){if(V>0){let F=Math.min(2**V*200,5000);await new Promise((B)=>setTimeout(B,F))}let D=new AbortController,R=setTimeout(()=>D.abort(),W),L=()=>D.abort();Z.abortSignal?.addEventListener("abort",L,{once:!0});try{let F=await fetch(Q.url,{method:"POST",headers:G,body:J,redirect:"manual",signal:D.signal});if(F.status>=300&&F.status<400){K=Error(`HTTP hook received redirect (${F.status}); redirects are disabled`);continue}if(!F.ok){if(K=Error(`HTTP hook returned ${F.status} ${F.statusText}`),F.status>=400&&F.status<500)break;continue}let O={stdout:await SQ(F,$),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(O,Q,{timeoutBehavior:Z.config.timeoutBehavior,failureBehavior:Z.config.failureBehavior})}catch(F){let B=F.name==="AbortError"||F.code==="ABORT_ERR";if(B&&Z.abortSignal?.aborted){K=Error("HTTP hook aborted by caller");break}if(B){let O={stdout:"",stderr:`HTTP hook timeout after ${W}ms`,exitCode:124,timedOut:!0};if(V===X-1)return this.outputParser.parse(O,Q,{timeoutBehavior:Z.config.timeoutBehavior,failureBehavior:Z.config.failureBehavior});K=Error(`HTTP hook timeout attempt ${V+1}`);continue}K=F}finally{clearTimeout(R),Z.abortSignal?.removeEventListener("abort",L)}}return{success:!1,blocking:!1,error:K?.message??"HTTP hook failed",hook:Q}}async getOrCreateChatService(Q){let Y=Q||"__default__",Z=this.chatServiceCache.get(Y);if(Z)return Z;let{ensureStoreInitialized:W,getCurrentModel:$,getModelById:X}=await import("./chunk-mpskff34.js"),{createChatServiceAsync:G}=await import("./chunk-bwaqaktn.js");await W();let J=Q?X(Q)||$():$();if(!J)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let K=await G({provider:J.provider,apiKey:J.apiKey,baseUrl:J.baseUrl,model:J.model,temperature:J.temperature,maxContextTokens:J.maxContextTokens,maxOutputTokens:J.maxOutputTokens});return this.chatServiceCache.set(Y,K),K}buildPromptHookSystemMessage(Q,Y){let Z=CQ[Y]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${Y} 事件中被触发。
|
|
25
25
|
|
|
26
26
|
`+`## 评估指令
|
|
27
27
|
${Q.prompt}
|
|
@@ -38,4 +38,4 @@ ${Q.prompt}
|
|
|
38
38
|
`+`- 只输出 JSON,不要包含 markdown 代码块或其他文本
|
|
39
39
|
`+`- 如果没有发现问题,使用 "approve"
|
|
40
40
|
`+'- 只在发现严重问题时使用 "block"'}extractJsonFromLLMResponse(Q){let Y=Q.trim(),Z=Y.match(/^```(?:json)?\s*\n?([\s\S]*?)\n?\s*```$/);if(Z)return Z[1].trim();return Y}async executeHooksConcurrently(Q,Y,Z,W){let $=[],X=new Set;for(let G of Q){if(X.size>=W)await Promise.race(X);let J=this.executeHook(G,Y,Z).catch((V)=>({success:!1,blocking:!1,error:V instanceof Error?V.message:String(V),hook:G})),K=J.then(()=>{X.delete(K)}).catch(()=>{X.delete(K)});X.add(K),$.push(J)}return Promise.all($)}}async function SQ(Q,Y){let Z=Q.body?.getReader();if(!Z)return"";let W=new TextDecoder,$=0,X="";while(!0){let{value:G,done:J}=await Z.read();if(J)break;if($+=G.byteLength,$>Y){try{Z.cancel()}catch{}X+=W.decode(G.slice(0,Y-($-G.byteLength)));break}X+=W.decode(G,{stream:!0})}return X+=W.decode(),X}import k from"picomatch";var EQ=/^([A-Za-z0-9_|]+)\((.+)\)$/;class h{matches(Q,Y){if(!Q)return!0;if(Q.tools&&Y.toolName){if(!this.matchTools(Q.tools,Y))return!1}if(Q.paths&&Y.filePath){if(!this.matchPaths(Q.paths,Y.filePath))return!1}if(Q.commands&&Y.command){if(!this.matchCommands(Q.commands,Y.command))return!1}return!0}matchTools(Q,Y){if(Array.isArray(Q))return Q.some((Z)=>this.matchToolWithParams(Z,Y));return this.matchToolWithParams(Q,Y)}matchPaths(Q,Y){if(Array.isArray(Q))return Q.some((W)=>{return k(W)(Y)});return k(Q)(Y)}matchCommands(Q,Y){if(Array.isArray(Q))return Q.some((Z)=>this.matchPattern(Y,Z));return this.matchPattern(Y,Q)}matchToolWithParams(Q,Y){let{toolName:Z,command:W,filePath:$}=Y,X=EQ.exec(Q);if(!X)return this.matchPattern(Z,Q);let[,G,J]=X;if(!this.matchPattern(Z,G))return!1;let K=this.getArgValue(Z,W,$);if(!K)return!1;return this.matchGlobOrPattern(K,J)}getArgValue(Q,Y,Z){if(Q==="Bash"||Q==="BashTool")return Y;if(["Read","Edit","Write","Glob","Grep"].includes(Q))return Z;return Y||Z}matchGlobOrPattern(Q,Y){if(/[*?[\]{}!]/.test(Y))try{return k(Y,{bash:!0,dot:!0})(Q)}catch{}if(Y.endsWith("*")){let Z=Y.slice(0,-1);return Q.startsWith(Z)}return Q===Y}matchPattern(Q,Y){if(Y==="*")return!0;if(!Y.includes("|")&&!/[.*+?^${}()|[\]\\]/.test(Y))return Q===Y;if(Y.includes("|"))return Y.split("|").map((W)=>W.trim()).includes(Q);try{return new RegExp(Y).test(Q)}catch{return Q===Y}}}class T{static instance=null;config=I;executor=new m;guard=new z;matcher=new h;sessionDisabled=!1;constructor(){}static getInstance(){if(!T.instance)T.instance=new T;return T.instance}loadConfig(Q){let Y=f(I,Q),Z=x();Y=f(Y,Z),this.config=Y}isEnabled(){if(!this.config.enabled)return!1;if(this.sessionDisabled)return!1;return!0}disable(){this.sessionDisabled=!0,console.log("[HookManager] Hooks disabled for this session")}enable(){this.sessionDisabled=!1,console.log("[HookManager] Hooks enabled for this session")}getConfig(){return this.config}registerFunction(Q,Y,Z,W){let $={type:"function",handler:Z,timeout:W?.timeout},X={name:W?.name??`inline-${Q}-${Date.now()}`,matcher:Y,hooks:[$]},G=this.config[Q]??[];return this.config[Q]=[...G,X],()=>{let J=this.config[Q];if(!J)return;this.config[Q]=J.filter((K)=>K!==X)}}async reloadConfig(){let Q=await import("node:fs/promises"),Y=await import("node:path");try{let Z=Y.join(n(),".blade","settings.local.json"),W=await Q.readFile(Z,"utf-8"),$=JSON.parse(W);if($.hooks)this.loadConfig($.hooks)}catch{}}async executePreToolHooks(Q,Y,Z,W){if(!this.isEnabled())return{decision:"allow"};if(W.permissionMode==="plan")return{decision:"allow"};if(!this.guard.canExecute(Y,"PreToolUse"))return{decision:"allow"};let $={hook_event_name:"PreToolUse",hook_execution_id:A(),timestamp:new Date().toISOString(),tool_name:Q,tool_use_id:Y,tool_input:Z,project_dir:W.projectDir,session_id:W.sessionId,permission_mode:W.permissionMode},X=this.getMatchingHooks("PreToolUse",{toolName:Q,filePath:this.extractFilePath(Z),command:this.extractCommand(Q,Z)});if(X.length===0)return{decision:"allow"};let G={projectDir:W.projectDir,sessionId:W.sessionId,permissionMode:W.permissionMode,config:this.config,abortSignal:W.abortSignal};try{let J=await this.executor.executePreToolHooks(X,$,G);if(this.guard.markExecuted(Y,"PreToolUse"),W.permissionMode==="yolo"){if(J.decision==="deny")return J;return{decision:"allow",modifiedInput:J.modifiedInput,warning:J.warning,reason:J.reason}}return J}catch(J){return console.error("[HookManager] Error executing PreToolUse hooks:",J),{decision:"allow",warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}async executePostToolHooks(Q,Y,Z,W,$){if(!this.isEnabled())return{};if($.permissionMode==="plan")return{};if(!this.guard.canExecute(Y,"PostToolUse"))return{};let X={hook_event_name:"PostToolUse",hook_execution_id:A(),timestamp:new Date().toISOString(),tool_name:Q,tool_use_id:Y,tool_input:Z,tool_response:W,project_dir:$.projectDir,session_id:$.sessionId,permission_mode:$.permissionMode},G=this.getMatchingHooks("PostToolUse",{toolName:Q,filePath:this.extractFilePath(Z),command:this.extractCommand(Q,Z)});if(G.length===0)return{};let J={projectDir:$.projectDir,sessionId:$.sessionId,permissionMode:$.permissionMode,config:this.config,abortSignal:$.abortSignal};try{let K=await this.executor.executePostToolHooks(G,X,J);return this.guard.markExecuted(Y,"PostToolUse"),K}catch(K){return console.error("[HookManager] Error executing PostToolUse hooks:",K),{warning:`Hook execution failed: ${K instanceof Error?K.message:String(K)}`}}finally{this.guard.cleanup(Y)}}async executeStopHooks(Q){if(!this.isEnabled())return{shouldStop:!0};let Y={hook_event_name:"Stop",hook_execution_id:A(),timestamp:new Date().toISOString(),project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode,reason:Q.reason},Z=this.getMatchingHooks("Stop",{});if(Z.length===0)return{shouldStop:!0};let W={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:this.config,abortSignal:Q.abortSignal};try{return await this.executor.executeStopHooks(Z,Y,W)}catch($){return console.error("[HookManager] Error executing Stop hooks:",$),{shouldStop:!0,warning:`Hook execution failed: ${$ instanceof Error?$.message:String($)}`}}}async executeSubagentStopHooks(Q,Y){if(!this.isEnabled())return{shouldStop:!0};let Z={hook_event_name:"SubagentStop",hook_execution_id:A(),timestamp:new Date().toISOString(),project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode,agent_type:Q,task_description:Y.taskDescription,success:Y.success,result_summary:Y.resultSummary,error:Y.error},W=this.getMatchingHooks("SubagentStop",{});if(W.length===0)return{shouldStop:!0};let $={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:this.config,abortSignal:Y.abortSignal};try{return await this.executor.executeSubagentStopHooks(W,Z,$)}catch(X){return console.error("[HookManager] Error executing SubagentStop hooks:",X),{shouldStop:!0,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executePermissionRequestHooks(Q,Y,Z,W){if(!this.isEnabled())return{decision:"ask"};let $={hook_event_name:"PermissionRequest",hook_execution_id:A(),timestamp:new Date().toISOString(),tool_name:Q,tool_use_id:Y,tool_input:Z,project_dir:W.projectDir,session_id:W.sessionId,permission_mode:W.permissionMode},X=this.getMatchingHooks("PermissionRequest",{toolName:Q,filePath:this.extractFilePath(Z),command:this.extractCommand(Q,Z)});if(X.length===0)return{decision:"ask"};let G={projectDir:W.projectDir,sessionId:W.sessionId,permissionMode:W.permissionMode,config:this.config,abortSignal:W.abortSignal};try{return await this.executor.executePermissionRequestHooks(X,$,G)}catch(J){return console.error("[HookManager] Error executing PermissionRequest hooks:",J),{decision:"ask",warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}async executeUserPromptSubmitHooks(Q,Y){if(!this.isEnabled())return{proceed:!0};let Z={hook_event_name:"UserPromptSubmit",hook_execution_id:A(),timestamp:new Date().toISOString(),user_prompt:Q,has_images:Y.hasImages,image_count:Y.imageCount,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},W=this.getMatchingHooks("UserPromptSubmit",{});if(W.length===0)return{proceed:!0};let $={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:this.config,abortSignal:Y.abortSignal};try{return await this.executor.executeUserPromptSubmitHooks(W,Z,$)}catch(X){return console.error("[HookManager] Error executing UserPromptSubmit hooks:",X),{proceed:!0,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executeSessionStartHooks(Q){if(!this.isEnabled())return{proceed:!0};let Y={hook_event_name:"SessionStart",hook_execution_id:A(),timestamp:new Date().toISOString(),project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode,is_resume:Q.isResume,resume_session_id:Q.resumeSessionId},Z=this.getMatchingHooks("SessionStart",{});if(Z.length===0)return{proceed:!0};let W={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:this.config,abortSignal:Q.abortSignal};try{return await this.executor.executeSessionStartHooks(Z,Y,W)}catch($){return console.error("[HookManager] Error executing SessionStart hooks:",$),{proceed:!0,warning:`Hook execution failed: ${$ instanceof Error?$.message:String($)}`}}}async executeSessionEndHooks(Q,Y){if(!this.isEnabled())return{};let Z={hook_event_name:"SessionEnd",hook_execution_id:A(),timestamp:new Date().toISOString(),project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode,reason:Q},W=this.getMatchingHooks("SessionEnd",{});if(W.length===0)return{};let $={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:this.config,abortSignal:Y.abortSignal};try{return await this.executor.executeSessionEndHooks(W,Z,$),{}}catch(X){return console.error("[HookManager] Error executing SessionEnd hooks:",X),{warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executePostToolUseFailureHooks(Q,Y,Z,W,$){if(!this.isEnabled())return{};let X={hook_event_name:"PostToolUseFailure",hook_execution_id:A(),timestamp:new Date().toISOString(),tool_name:Q,tool_use_id:Y,tool_input:Z,error:W,error_type:$.errorType,is_interrupt:$.isInterrupt,is_timeout:$.isTimeout,project_dir:$.projectDir,session_id:$.sessionId,permission_mode:$.permissionMode},G=this.getMatchingHooks("PostToolUseFailure",{toolName:Q,filePath:this.extractFilePath(Z),command:this.extractCommand(Q,Z)});if(G.length===0)return{};let J={projectDir:$.projectDir,sessionId:$.sessionId,permissionMode:$.permissionMode,config:this.config,abortSignal:$.abortSignal};try{return await this.executor.executePostToolUseFailureHooks(G,X,J)}catch(K){return console.error("[HookManager] Error executing PostToolUseFailure hooks:",K),{warning:`Hook execution failed: ${K instanceof Error?K.message:String(K)}`}}}async executeNotificationHooks(Q,Y,Z){if(!this.isEnabled())return{suppress:!1,message:Y};let W={hook_event_name:"Notification",hook_execution_id:A(),timestamp:new Date().toISOString(),project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode,notification_type:Q,title:Z.title,message:Y},$=this.getMatchingHooks("Notification",{});if($.length===0)return{suppress:!1,message:Y};let X={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:this.config,abortSignal:Z.abortSignal};try{return await this.executor.executeNotificationHooks($,W,X)}catch(G){return console.error("[HookManager] Error executing Notification hooks:",G),{suppress:!1,message:Y,warning:`Hook execution failed: ${G instanceof Error?G.message:String(G)}`}}}async executeCompactionHooks(Q,Y){if(!this.isEnabled())return{blockCompaction:!1};let Z={hook_event_name:"Compaction",hook_execution_id:A(),timestamp:new Date().toISOString(),project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode,trigger:Q,messages_before:Y.messagesBefore,tokens_before:Y.tokensBefore},W=this.getMatchingHooks("Compaction",{});if(W.length===0)return{blockCompaction:!1};let $={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:this.config,abortSignal:Y.abortSignal};try{return await this.executor.executeCompactionHooks(W,Z,$)}catch(X){return console.error("[HookManager] Error executing Compaction hooks:",X),{blockCompaction:!1,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}getMatchingHooks(Q,Y){let Z=this.config[Q]||[],W=[];for(let $ of Z)if(this.matcher.matches($.matcher,Y))W.push(...$.hooks);return W}extractFilePath(Q){let Y=["file_path","path","filePath","source","target"];for(let Z of Y){let W=Q[Z];if(typeof W==="string")return W}return}extractCommand(Q,Y){if(Q==="Bash"||Q==="BashTool"){let Z=Y.command;if(typeof Z==="string")return Z}return}cleanup(){this.guard.cleanupAll()}}
|
|
41
|
-
export{N as
|
|
41
|
+
export{N as sb,i as tb,T as ub};
|