blade-code 0.7.8 → 0.8.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.
- package/dist/blade.js +2 -2
- package/dist/chunk-04920kz2.js +1570 -0
- package/dist/{chunk-rnfd5ebv.js → chunk-06h100e2.js} +1 -1
- package/dist/chunk-07jvw0kn.js +1 -0
- package/dist/chunk-0dj326ms.js +5 -0
- package/dist/chunk-14erxdhd.js +1 -0
- package/dist/{chunk-48q9msfk.js → chunk-1pt090dg.js} +38 -38
- package/dist/{chunk-cjmxggke.js → chunk-1smf2dj3.js} +2 -2
- package/dist/chunk-34pdtz4q.js +3 -0
- package/dist/chunk-42ch5zg4.js +1 -0
- package/dist/chunk-49g067ek.js +41 -0
- package/dist/{chunk-71n472hj.js → chunk-61952mn3.js} +1 -1
- package/dist/{chunk-s4mke0t6.js → chunk-6yqzfz8t.js} +1 -1
- package/dist/chunk-7j6rxyt8.js +9 -0
- package/dist/{chunk-g7caymjr.js → chunk-9ad7tt9s.js} +1 -1
- package/dist/{chunk-jm2xhnrv.js → chunk-9xkjb87h.js} +1 -1
- package/dist/chunk-a12tmmfr.js +1 -0
- package/dist/{chunk-0e0z8yc1.js → chunk-bm8vwfez.js} +2 -2
- package/dist/chunk-cnftrx3g.js +1 -0
- package/dist/chunk-ctqf59q1.js +2 -0
- package/dist/chunk-d4ex0qvs.js +2 -0
- package/dist/{chunk-f9ybv4ph.js → chunk-dr06x0cw.js} +1 -1
- package/dist/chunk-epp5jx5f.js +6 -0
- package/dist/{chunk-4dmdn3a9.js → chunk-gsfkrr25.js} +1 -1
- package/dist/chunk-hjx5n3dw.js +3 -0
- package/dist/chunk-j39q2kx7.js +1 -0
- package/dist/chunk-j6hpzkpq.js +6 -0
- package/dist/{chunk-t70aqrm4.js → chunk-jt62ctz7.js} +1 -1
- package/dist/chunk-k47ssv3b.js +34 -0
- package/dist/{chunk-t2spryz0.js → chunk-kawv31m3.js} +1 -1
- package/dist/chunk-n4f8tseg.js +2 -0
- package/dist/chunk-nc4kfwef.js +1 -0
- package/dist/{chunk-9kejtkey.js → chunk-neenhtxw.js} +1 -1
- package/dist/chunk-pdydx73a.js +2 -0
- package/dist/chunk-qwdbqjh7.js +22 -0
- package/dist/{chunk-g6ted982.js → chunk-sr3bzb95.js} +1 -1
- package/dist/chunk-syj3anec.js +6 -0
- package/dist/chunk-tv4r86ez.js +24 -0
- package/dist/chunk-twem6p0g.js +2 -0
- package/dist/chunk-v3ctg84r.js +1 -0
- package/dist/chunk-v5rn5r1h.js +1 -0
- package/dist/{chunk-fb7amc2s.js → chunk-wmes2tt9.js} +1 -1
- package/dist/chunk-x6gt63vz.js +151 -0
- package/dist/chunk-xhnyy54e.js +2 -0
- package/dist/{chunk-6hn2jgw5.js → chunk-yhpm9azy.js} +1 -1
- package/dist/web/assets/{CodeBlockHighlighter-C1cp8dDv.js → CodeBlockHighlighter-D8_cOYpG.js} +1 -1
- package/dist/web/assets/{FilePreview-DRKRs8i2.js → FilePreview-Chqi7chf.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-DFqPpAnM.js → MarkdownRenderer-JJScfgAO.js} +1 -1
- package/dist/web/assets/{McpModal-CX5-hlNv.js → McpModal-CiCuIUxC.js} +2 -2
- package/dist/web/assets/SettingsModal-Bew818xl.js +1 -0
- package/dist/web/assets/{SettingsStore-jup_Kikq.js → SettingsStore-B_4zN-c-.js} +1 -1
- package/dist/web/assets/{SkillsModal-DaAUrwXO.js → SkillsModal-Cot4Rb89.js} +1 -1
- package/dist/web/assets/{TerminalPanel-DzlllDH7.js → TerminalPanel-DxB67ObY.js} +1 -1
- package/dist/web/assets/index-B-b3Yc5H.css +1 -0
- package/dist/web/assets/index-B3dW1Scg.js +16 -0
- package/dist/web/assets/{useRequest-DITGl55G.js → useRequest-B4kP-cmG.js} +1 -1
- package/dist/web/assets/{vendor-icons-BuFpOlRn.js → vendor-icons-DqO8ishN.js} +2 -2
- package/dist/web/assets/{vendor-markdown-Bo4W9Tae.js → vendor-markdown-b9iCqZWK.js} +1 -1
- package/dist/web/assets/vendor-radix-DyP_DOwV.js +45 -0
- package/dist/web/assets/{vendor-react-BalntB5F.js → vendor-react-FPIC4Czm.js} +2 -2
- package/dist/web/index.html +2 -2
- package/package.json +4 -11
- package/dist/chunk-1w6tqkxd.js +0 -34
- package/dist/chunk-2049tv49.js +0 -41
- package/dist/chunk-4745ktjj.js +0 -1570
- package/dist/chunk-5be6qr2v.js +0 -2
- package/dist/chunk-67vzgcs5.js +0 -2
- package/dist/chunk-6811kbxn.js +0 -1
- package/dist/chunk-6js5wp6t.js +0 -1
- package/dist/chunk-6kp3z956.js +0 -9
- package/dist/chunk-78txnq4n.js +0 -151
- package/dist/chunk-7r1hm0qz.js +0 -6
- package/dist/chunk-a7yjnqhd.js +0 -3
- package/dist/chunk-bwaqaktn.js +0 -1
- package/dist/chunk-cb82rf5h.js +0 -1
- package/dist/chunk-ce11m8bq.js +0 -1
- package/dist/chunk-e4rhdg3h.js +0 -1
- package/dist/chunk-faq7ay4j.js +0 -24
- package/dist/chunk-ky8ctbdc.js +0 -1
- package/dist/chunk-mpskff34.js +0 -1
- package/dist/chunk-pd1yqxcv.js +0 -9
- package/dist/chunk-phhmmybg.js +0 -2
- package/dist/chunk-qnevwq1q.js +0 -2
- package/dist/chunk-r1spf93b.js +0 -26
- package/dist/chunk-z4c68ve0.js +0 -6
- package/dist/chunk-z9zbcenc.js +0 -6
- package/dist/web/assets/SettingsModal-CfR_q6N7.js +0 -1
- package/dist/web/assets/index-BJTSF3fc.js +0 -9
- package/dist/web/assets/index-CL6apjgo.css +0 -1
- package/dist/web/assets/vendor-radix-CESj0OOY.js +0 -45
package/dist/web/index.html
CHANGED
|
@@ -5,8 +5,8 @@
|
|
|
5
5
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
|
6
6
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
7
7
|
<title>BladeCode</title>
|
|
8
|
-
<script type="module" crossorigin src="/assets/index-
|
|
9
|
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
|
8
|
+
<script type="module" crossorigin src="/assets/index-B3dW1Scg.js"></script>
|
|
9
|
+
<link rel="stylesheet" crossorigin href="/assets/index-B-b3Yc5H.css">
|
|
10
10
|
</head>
|
|
11
11
|
<body>
|
|
12
12
|
<div id="root"></div>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "blade-code",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.1",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "🗡️ Blade Code - 智能代码助手命令行工具",
|
|
6
6
|
"type": "module",
|
|
@@ -57,7 +57,7 @@
|
|
|
57
57
|
"author": "echoVic",
|
|
58
58
|
"license": "MIT",
|
|
59
59
|
"engines": {
|
|
60
|
-
"node": ">=
|
|
60
|
+
"node": ">=22.19.0"
|
|
61
61
|
},
|
|
62
62
|
"optionalDependencies": {
|
|
63
63
|
"@vscode/ripgrep": "^1.17.0",
|
|
@@ -66,17 +66,11 @@
|
|
|
66
66
|
},
|
|
67
67
|
"dependencies": {
|
|
68
68
|
"@agentclientprotocol/sdk": "^0.12.0",
|
|
69
|
-
"@ai-sdk/anthropic": "^3.0.7",
|
|
70
|
-
"@ai-sdk/azure": "^3.0.5",
|
|
71
|
-
"@ai-sdk/deepseek": "^2.0.4",
|
|
72
|
-
"@ai-sdk/google": "^3.0.4",
|
|
73
|
-
"@ai-sdk/openai": "^3.0.26",
|
|
74
|
-
"@ai-sdk/openai-compatible": "^2.0.4",
|
|
75
69
|
"@anthropic-ai/sandbox-runtime": "0.0.67",
|
|
70
|
+
"@earendil-works/pi-ai": "0.83.0",
|
|
76
71
|
"@inkjs/ui": "^2.0.0",
|
|
77
72
|
"@modelcontextprotocol/sdk": "^1.17.4",
|
|
78
73
|
"ahooks": "^3.9.6",
|
|
79
|
-
"ai": "^6.0.39",
|
|
80
74
|
"ansi-escapes": "^7.2.0",
|
|
81
75
|
"async-mutex": "^0.5.0",
|
|
82
76
|
"axios": "^1.12.2",
|
|
@@ -109,8 +103,7 @@
|
|
|
109
103
|
"ws": "^8.18.0",
|
|
110
104
|
"yaml": "^2.8.1",
|
|
111
105
|
"yargs": "^18.0.0",
|
|
112
|
-
"
|
|
113
|
-
"zod-to-json-schema": "^3.24.6",
|
|
106
|
+
"typebox": "1.3.7",
|
|
114
107
|
"zustand": "^5.0.9"
|
|
115
108
|
},
|
|
116
109
|
"devDependencies": {
|
package/dist/chunk-1w6tqkxd.js
DELETED
|
@@ -1,34 +0,0 @@
|
|
|
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
|
-
${G.map((X)=>` - ${X.field}: ${X.message}`).join(`
|
|
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
|
-
|
|
5
|
-
${B.description.long}`;if(B.description.usageNotes&&B.description.usageNotes.length>0)Q+=`
|
|
6
|
-
|
|
7
|
-
Usage Notes:
|
|
8
|
-
${B.description.usageNotes.map((X)=>`- ${X}`).join(`
|
|
9
|
-
`)}`;if(B.description.important&&B.description.important.length>0)Q+=`
|
|
10
|
-
|
|
11
|
-
Important:
|
|
12
|
-
${B.description.important.map((X)=>`[WARN] ${X}`).join(`
|
|
13
|
-
`)}`;return{name:B.name,description:Q,parameters:G}},getMetadata(){return{name:B.name,displayName:B.displayName,kind:B.kind,version:B.version||"1.0.0",category:B.category,tags:B.tags||[],description:B.description,schema:H(B.schema)}},build(G){let Q=y(B.schema,G);return new w(B.name,Q,B.execute)},async execute(G,Q,X){return this.build(G).execute(Q||new AbortController().signal,void 0,X)},extractSignatureContent:B.extractSignatureContent?(G)=>B.extractSignatureContent(G):void 0,abstractPermissionRule:B.abstractPermissionRule?(G)=>B.abstractPermissionRule(G):void 0}}function U(B,G,Q,X){let Y;try{Y=V(Q.inputSchema)}catch(W){console.warn(`[createMcpTool] Schema 转换失败,使用降级 schema: ${Q.name}`,W),Y=L.any()}let $=X||Q.name;return k({name:$,displayName:`${G}: ${Q.name}`,kind:"execute",schema:Y,description:{short:Q.description||`MCP Tool: ${Q.name}`,important:[`From MCP server: ${G}`,"Executes external tools; user confirmation required"]},category:"MCP tool",tags:["mcp","external",G],async execute(W,q){try{let F=await B.callTool(Q.name,W),A="";if(F.content&&Array.isArray(F.content)){for(let K of F.content)if(K.type==="text"&&K.text)A+=K.text;else if(K.type==="image")A+=`[image: ${K.mimeType||"unknown"}]
|
|
14
|
-
`;else if(K.type==="resource")A+=`[resource: ${K.mimeType||"unknown"}]
|
|
15
|
-
`}if(F.isError)return{success:!1,llmContent:A||"MCP tool execution failed",error:{type:"execution_error",message:A||"MCP tool execution failed"},metadata:{summary:`MCP ${Q.name} 执行失败`,serverName:G,toolName:Q.name}};return{success:!0,llmContent:A||"Execution succeeded",metadata:{summary:`MCP ${Q.name} 执行成功`,serverName:G,toolName:Q.name,mcpResult:F}}}catch(F){return{success:!1,llmContent:`MCP tool execution failed: ${F.message}`,error:{type:"execution_error",message:F.message},metadata:{summary:`MCP ${Q.name} 执行失败`,serverName:G,toolName:Q.name}}}}})}function V(B){if(B.type==="object"||B.properties){let G={},Q=B.required||[];if(B.properties){for(let[X,Y]of Object.entries(B.properties))if(typeof Y==="object"&&Y!==null){let $=V(Y);if(!Q.includes(X))$=$.optional();G[X]=$}}return L.object(G)}if(B.type==="array"&&B.items){if(typeof B.items==="object"&&!Array.isArray(B.items)&&B.items!==null)return L.array(V(B.items));return L.array(L.any())}if(B.type==="string"){let G=L.string();if(B.minLength!==void 0)G=G.min(B.minLength);if(B.maxLength!==void 0)G=G.max(B.maxLength);if(B.pattern)G=G.regex(new RegExp(B.pattern));if(B.enum)return L.enum(B.enum);return G}if(B.type==="number"||B.type==="integer"){let G=L.number();if(B.minimum!==void 0)G=G.min(B.minimum);if(B.maximum!==void 0)G=G.max(B.maximum);return G}if(B.type==="boolean")return L.boolean();if(B.oneOf&&B.oneOf.length>0){let G=B.oneOf.filter((Q)=>typeof Q==="object"&&Q!==null).map((Q)=>V(Q));if(G.length>=2)return L.union(G)}if(B.anyOf&&B.anyOf.length>0){let G=B.anyOf.filter((Q)=>typeof Q==="object"&&Q!==null).map((Q)=>V(Q));if(G.length>=2)return L.union(G)}return L.any()}import{Client as t}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as a}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as s}from"@modelcontextprotocol/sdk/client/stdio.js";import{EventEmitter as n}from"events";import{spawn as m}from"child_process";import*as _ from"crypto";import*as T from"http";import{URL as C}from"url";import{promises as z}from"fs";import f from"os";import P from"path";class x{tokenFilePath;constructor(){let B=f.homedir(),G=P.join(B,".blade");this.tokenFilePath=P.join(G,"mcp-oauth-tokens.json")}async ensureConfigDir(){let B=P.dirname(this.tokenFilePath);try{await z.mkdir(B,{recursive:!0,mode:493})}catch{}}async loadAllCredentials(){let B=new Map;try{let G=await z.readFile(this.tokenFilePath,"utf-8"),Q=JSON.parse(G);for(let X of Q)B.set(X.serverName,X)}catch(G){if(G.code!=="ENOENT")console.warn("[OAuthTokenStorage] 加载令牌失败:",G)}return B}async saveAllCredentials(B){await this.ensureConfigDir();let G=Array.from(B.values());await z.writeFile(this.tokenFilePath,JSON.stringify(G,null,2),{mode:384})}async saveToken(B,G,Q,X){let Y=await this.loadAllCredentials(),$={serverName:B,token:G,clientId:Q,tokenUrl:X,updatedAt:Date.now()};Y.set(B,$),await this.saveAllCredentials(Y)}async getCredentials(B){return(await this.loadAllCredentials()).get(B)||null}async deleteCredentials(B){let G=await this.loadAllCredentials();G.delete(B),await this.saveAllCredentials(G)}async listServers(){let B=await this.loadAllCredentials();return Array.from(B.keys())}isTokenExpired(B){if(!B.expiresAt)return!1;let G=300000;return Date.now()>=B.expiresAt-G}}var Z=7777,D="/oauth/callback",I=200;class O{tokenStorage;constructor(B=new x){this.tokenStorage=B}generatePKCEParams(){let B=_.randomBytes(32).toString("base64url"),G=_.createHash("sha256").update(B).digest("base64url"),Q=_.randomBytes(16).toString("base64url");return{codeVerifier:B,codeChallenge:G,state:Q}}buildAuthorizationUrl(B,G){let Q=B.redirectUri||`http://localhost:${Z}${D}`,X=new URLSearchParams({client_id:B.clientId,response_type:"code",redirect_uri:Q,state:G.state,code_challenge:G.codeChallenge,code_challenge_method:"S256"});if(B.scopes&&B.scopes.length>0)X.append("scope",B.scopes.join(" "));let Y=new C(B.authorizationUrl);return X.forEach(($,W)=>{Y.searchParams.append(W,$)}),Y.toString()}async startCallbackServer(B){return new Promise((G,Q)=>{let X=T.createServer((Y,$)=>{try{let W=new C(Y.url,`http://localhost:${Z}`);if(W.pathname!==D){$.writeHead(404),$.end("Not found");return}let q=W.searchParams.get("code"),F=W.searchParams.get("state"),A=W.searchParams.get("error");if(A){$.writeHead(I,{"Content-Type":"text/html"}),$.end(`
|
|
16
|
-
<html>
|
|
17
|
-
<body>
|
|
18
|
-
<h1>Authentication Failed</h1>
|
|
19
|
-
<p>Error: ${A}</p>
|
|
20
|
-
<p>You can close this window.</p>
|
|
21
|
-
</body>
|
|
22
|
-
</html>
|
|
23
|
-
`),X.close(),Q(Error(`OAuth error: ${A}`));return}if(!q||!F){$.writeHead(400),$.end("Missing code or state parameter");return}if(F!==B){$.writeHead(400),$.end("Invalid state parameter"),X.close(),Q(Error("State mismatch - possible CSRF attack"));return}$.writeHead(I,{"Content-Type":"text/html"}),$.end(`
|
|
24
|
-
<html>
|
|
25
|
-
<body>
|
|
26
|
-
<h1>Authentication Successful!</h1>
|
|
27
|
-
<p>You can close this window and return to Blade.</p>
|
|
28
|
-
<script>window.close();</script>
|
|
29
|
-
</body>
|
|
30
|
-
</html>
|
|
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
|
-
[OAuth] Opening browser for authentication...`),console.log(`
|
|
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 ca,b as da};
|
package/dist/chunk-2049tv49.js
DELETED
|
@@ -1,41 +0,0 @@
|
|
|
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
|
-
`):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
|
-
|
|
4
|
-
`):void 0,modifiedOutput:G,warning:J.length>0?J.join(`
|
|
5
|
-
`):void 0}}async executeStopHooks(Q,Y,Z){if(Q.length===0)return{shouldStop:!0};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&&"continue"in G&&G.continue===!1)return{shouldStop:!1,continueReason:G.continueReason,warning:W.length>0?W.join(`
|
|
6
|
-
`):void 0}}catch(X){let G=X instanceof Error?X.message:String(X);W.push(`Hook failed: ${G}`)}return{shouldStop:!0,warning:W.length>0?W.join(`
|
|
7
|
-
`):void 0}}async executeSubagentStopHooks(Q,Y,Z){if(Q.length===0)return{shouldStop:!0};let W=[],$=[];for(let X of Q)try{let G=await this.executeHook(X,Y,Z);if(!G.success){if(G.warning)W.push(G.warning);continue}let J=G.output?.hookSpecificOutput;if(J&&"continue"in J){if(J.continue===!1)return{shouldStop:!1,continueReason:J.continueReason,warning:W.length>0?W.join(`
|
|
8
|
-
`):void 0};if("additionalContext"in J&&J.additionalContext)$.push(J.additionalContext)}}catch(G){let J=G instanceof Error?G.message:String(G);W.push(`Hook failed: ${J}`)}return{shouldStop:!0,additionalContext:$.length>0?$.join(`
|
|
9
|
-
|
|
10
|
-
`):void 0,warning:W.length>0?W.join(`
|
|
11
|
-
`):void 0}}async executePermissionRequestHooks(Q,Y,Z){if(Q.length===0)return{decision:"ask"};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&&"permissionDecision"in G){let J=G.permissionDecision;if(J==="approve"||J==="deny")return{decision:J,reason:G.permissionDecisionReason,warning:W.length>0?W.join(`
|
|
12
|
-
`):void 0}}}catch(X){let G=X instanceof Error?X.message:String(X);W.push(`Hook failed: ${G}`)}return{decision:"ask",warning:W.length>0?W.join(`
|
|
13
|
-
`):void 0}}async executeUserPromptSubmitHooks(Q,Y,Z){if(Q.length===0)return{proceed:!0};let W=[],$=[],X;for(let G of Q)try{let J=await this.executeHook(G,Y,Z);if(!J.success){if(J.blocking)return{proceed:!1,warning:J.error};if(J.warning)W.push(J.warning);continue}if(J.stdout&&J.stdout.trim())$.push(J.stdout.trim());let K=J.output?.hookSpecificOutput;if(K&&"updatedPrompt"in K){if(K.updatedPrompt)X=K.updatedPrompt;if(K.contextInjection)$.push(K.contextInjection)}}catch(J){let K=J instanceof Error?J.message:String(J);W.push(`Hook failed: ${K}`)}return{proceed:!0,updatedPrompt:X,contextInjection:$.length>0?$.join(`
|
|
14
|
-
|
|
15
|
-
`):void 0,warning:W.length>0?W.join(`
|
|
16
|
-
`):void 0}}async executeSessionStartHooks(Q,Y,Z){if(Q.length===0)return{proceed:!0};let W=[],$={};for(let X of Q)try{let G=await this.executeHook(X,Y,Z);if(!G.success){if(G.blocking)return{proceed:!1,warning:G.error};if(G.warning)W.push(G.warning);continue}let J=G.output?.hookSpecificOutput;if(J&&"env"in J&&J.env)Object.assign($,J.env)}catch(G){let J=G instanceof Error?G.message:String(G);W.push(`Hook failed: ${J}`)}return{proceed:!0,env:Object.keys($).length>0?$:void 0,warning:W.length>0?W.join(`
|
|
17
|
-
`):void 0}}async executeSessionEndHooks(Q,Y,Z){if(Q.length===0)return{};let W=[],$=Z.config.maxConcurrentHooks||5,X=await this.executeHooksConcurrently(Q,Y,Z,$);for(let G of X)if(!G.success&&G.warning)W.push(G.warning);return{warning:W.length>0?W.join(`
|
|
18
|
-
`):void 0}}async executePostToolUseFailureHooks(Q,Y,Z){if(Q.length===0)return{};let W=[],$=[],X=Z.config.maxConcurrentHooks||5,G=await this.executeHooksConcurrently(Q,Y,Z,X);for(let J of G){if(!J.success&&J.warning){W.push(J.warning);continue}if(J.stdout&&J.stdout.trim())$.push(J.stdout.trim())}return{additionalContext:$.length>0?$.join(`
|
|
19
|
-
|
|
20
|
-
`):void 0,warning:W.length>0?W.join(`
|
|
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
|
-
`):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
|
-
`):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-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
|
-
|
|
26
|
-
`+`## 评估指令
|
|
27
|
-
${Q.prompt}
|
|
28
|
-
|
|
29
|
-
`+`## 输出格式
|
|
30
|
-
`+`必须返回一个 JSON 对象(不要包含任何其他文本):
|
|
31
|
-
`+`{
|
|
32
|
-
"decision": { "behavior": "approve" | "block" },
|
|
33
|
-
`+` "systemMessage": "可选的说明信息",
|
|
34
|
-
`+` "hookSpecificOutput": ${Z}
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
`+`重要规则:
|
|
38
|
-
`+`- 只输出 JSON,不要包含 markdown 代码块或其他文本
|
|
39
|
-
`+`- 如果没有发现问题,使用 "approve"
|
|
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 sb,i as tb,T as ub};
|