blade-code 0.8.3 → 0.10.0
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/README.md +20 -5
- package/dist/blade.js +4 -4
- package/dist/chunk-0aj7gp37.js +2 -0
- package/dist/{chunk-7bqkkjxf.js → chunk-0h81hxkw.js} +1 -1
- package/dist/chunk-2beq0syt.js +2 -0
- package/dist/chunk-2fdjn926.js +1 -0
- package/dist/chunk-3c5gvxr6.js +1 -0
- package/dist/chunk-44wkjs2j.js +114 -0
- package/dist/chunk-4vaywb2r.js +2 -0
- package/dist/{chunk-crbh6x86.js → chunk-61087jc8.js} +2 -2
- package/dist/chunk-6g21dh3n.js +1 -0
- package/dist/chunk-6hj2dk75.js +3 -0
- package/dist/chunk-6n5xdf2r.js +2 -0
- package/dist/chunk-6qe5k7dw.js +4 -0
- package/dist/chunk-7dcm1aqd.js +1 -0
- package/dist/chunk-7eptyk20.js +1 -0
- package/dist/chunk-88vy9hh0.js +4 -0
- package/dist/chunk-8nm1hqr1.js +2 -0
- package/dist/chunk-8rg05w47.js +174 -0
- package/dist/chunk-93ptxa5p.js +4 -0
- package/dist/chunk-949btxxx.js +1485 -0
- package/dist/chunk-9jy87d0y.js +3 -0
- package/dist/chunk-9kd14cwq.js +1 -0
- package/dist/chunk-a7nbn5kf.js +3 -0
- package/dist/chunk-af49jmns.js +5 -0
- package/dist/chunk-asbp4cv4.js +1 -0
- package/dist/chunk-beqaxytd.js +2 -0
- package/dist/chunk-bqdc3m0p.js +6 -0
- package/dist/chunk-bx50res5.js +99 -0
- package/dist/chunk-cznge1n7.js +1 -0
- package/dist/{chunk-5yt80bn2.js → chunk-d3236505.js} +1 -1
- package/dist/chunk-d9ddpapp.js +18 -0
- package/dist/chunk-e3tk2jna.js +636 -0
- package/dist/chunk-f8db8ftd.js +10 -0
- package/dist/chunk-fjp5tvh8.js +1 -0
- package/dist/chunk-fjw32ex5.js +2 -0
- package/dist/chunk-gafbzeyk.js +1 -0
- package/dist/chunk-hh3xw391.js +6 -0
- package/dist/chunk-hzvp3bc1.js +44 -0
- package/dist/chunk-jv4nkkb5.js +1 -0
- package/dist/{chunk-eyypmc9m.js → chunk-jxv6r0c7.js} +2 -2
- package/dist/{chunk-mqqajem9.js → chunk-kq5my0yy.js} +2 -2
- package/dist/chunk-m3tx1k0s.js +1 -0
- package/dist/chunk-m78ceafk.js +1 -0
- package/dist/{chunk-be7qz4cv.js → chunk-mjp61rqd.js} +1 -1
- package/dist/chunk-mvwp3c11.js +45 -0
- package/dist/chunk-mwrn7mcr.js +1 -0
- package/dist/chunk-mxhg6jt9.js +25 -0
- package/dist/chunk-nah0cbnp.js +2 -0
- package/dist/chunk-px5ck9pf.js +2 -0
- package/dist/chunk-qev36qrb.js +2 -0
- package/dist/{chunk-ar5564sf.js → chunk-sndbq5xt.js} +1 -1
- package/dist/chunk-t8q9ks7e.js +3 -0
- package/dist/{chunk-wcf80p9y.js → chunk-th7sxjtk.js} +2 -2
- package/dist/{chunk-97qxd4yb.js → chunk-ty2kc6kg.js} +2 -2
- package/dist/chunk-v4mr98vm.js +1 -0
- package/dist/chunk-vb0t2hhd.js +25 -0
- package/dist/chunk-vjpd3nee.js +2 -0
- package/dist/chunk-vvy506b3.js +3 -0
- package/dist/chunk-vyq9r31h.js +22 -0
- package/dist/chunk-w4qsayn6.js +9 -0
- package/dist/chunk-wsqz3x2e.js +161 -0
- package/dist/{chunk-vxpdjtqc.js → chunk-wvj9h7mb.js} +1 -1
- package/dist/chunk-yvah5h4x.js +13 -0
- package/dist/chunk-z5ae4qvf.js +2 -0
- package/dist/chunk-zcw7kyf4.js +2 -0
- package/dist/{chunk-qvtahmff.js → chunk-zkbf8n6y.js} +1 -1
- package/dist/web/assets/ChatView-CnwNosSG.js +7 -0
- package/dist/web/assets/CodeBlockHighlighter-CBo_AxjZ.js +8 -0
- package/dist/web/assets/FilePreview-hNo6RCNY.js +8 -0
- package/dist/web/assets/MarkdownRenderer-BON4fqSr.js +30 -0
- package/dist/web/assets/McpModal-Go_8v1Vu.js +5 -0
- package/dist/web/assets/SettingsModal-CRu1zGQf.js +1 -0
- package/dist/web/assets/TaskSwitcher-Ds8CBVtp.js +1 -0
- package/dist/web/assets/TerminalPanel-Dm4bu6ib.js +1 -0
- package/dist/web/assets/index-BNsnHxlt.js +32 -0
- package/dist/web/assets/index-DI8ZWdWH.js +11 -0
- package/dist/web/assets/index-DVTiq-7u.css +1 -0
- package/dist/web/assets/vendor-icons-CsBKlDXT.js +381 -0
- package/dist/web/assets/vendor-radix-DXRuAJHH.js +45 -0
- package/dist/web/assets/vendor-react-DG5dkZ_t.js +49 -0
- package/dist/web/index.html +5 -2
- package/package.json +37 -34
- package/dist/chunk-1m63zddw.js +0 -2
- package/dist/chunk-23h9grdr.js +0 -1
- package/dist/chunk-2c69g6t9.js +0 -34
- package/dist/chunk-5sccs44n.js +0 -1
- package/dist/chunk-6msfa7jh.js +0 -9
- package/dist/chunk-6spmzx13.js +0 -6
- package/dist/chunk-724djh7r.js +0 -1
- package/dist/chunk-804j7say.js +0 -1
- package/dist/chunk-8yk5w2ks.js +0 -1
- package/dist/chunk-9cr3jexy.js +0 -2
- package/dist/chunk-b922cq7k.js +0 -41
- package/dist/chunk-bqhghfmt.js +0 -6
- package/dist/chunk-d7nrqg5b.js +0 -5
- package/dist/chunk-fma9cbq5.js +0 -10
- package/dist/chunk-ghf5tgjr.js +0 -1
- package/dist/chunk-hqtskyc1.js +0 -2
- package/dist/chunk-jc7k8pfn.js +0 -22
- package/dist/chunk-kf43f8sy.js +0 -1577
- package/dist/chunk-kjc2aqww.js +0 -2
- package/dist/chunk-kjddt9xy.js +0 -1
- package/dist/chunk-m0ded6ky.js +0 -615
- package/dist/chunk-msr67f6q.js +0 -3
- package/dist/chunk-mvww9cmc.js +0 -151
- package/dist/chunk-nbpjzzrg.js +0 -13
- package/dist/chunk-ncvr73ev.js +0 -1
- package/dist/chunk-qwn46cd6.js +0 -2
- package/dist/chunk-sva5bdgz.js +0 -2
- package/dist/chunk-t9cqscfq.js +0 -2
- package/dist/chunk-tzr992v4.js +0 -1
- package/dist/chunk-x8xfx9nv.js +0 -1
- package/dist/chunk-yewg510f.js +0 -24
- package/dist/chunk-zj3q4btp.js +0 -4
- package/dist/chunk-zjks0ncc.js +0 -6
- package/dist/chunk-zsyff0ky.js +0 -3
- package/dist/web/assets/CodeBlockHighlighter-D8_cOYpG.js +0 -1
- package/dist/web/assets/FilePreview-B5g8yi8d.js +0 -7
- package/dist/web/assets/MarkdownRenderer-qBCxzEb_.js +0 -1
- package/dist/web/assets/McpModal-C7y2Fsqc.js +0 -5
- package/dist/web/assets/SettingsModal-Dmc7Dw_E.js +0 -1
- package/dist/web/assets/SettingsStore-BfoB9tNV.js +0 -1
- package/dist/web/assets/SkillsModal-CqFAIfj5.js +0 -1
- package/dist/web/assets/TerminalPanel-EHh8-9b9.js +0 -1
- package/dist/web/assets/index-B-BRpW1c.js +0 -16
- package/dist/web/assets/index-Ch0eqSLM.css +0 -1
- package/dist/web/assets/useRequest-B4kP-cmG.js +0 -1
- package/dist/web/assets/vendor-icons-DBM55KTG.js +0 -251
- package/dist/web/assets/vendor-markdown-b9iCqZWK.js +0 -36
- package/dist/web/assets/vendor-monaco-w6PwaWGP.js +0 -11
- package/dist/web/assets/vendor-radix-DyP_DOwV.js +0 -45
- package/dist/web/assets/vendor-react-FPIC4Czm.js +0 -49
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "blade-code",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "🗡️ Blade Code - 智能代码助手命令行工具",
|
|
6
6
|
"type": "module",
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"build": "rm -rf dist && node scripts/run-bun.js run scripts/build.ts",
|
|
19
19
|
"start": "node scripts/run-bun.js run dist/blade.js",
|
|
20
20
|
"test": "node scripts/test.js",
|
|
21
|
-
"test:all": "vitest run --config vitest.config.ts",
|
|
21
|
+
"test:all": "vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance",
|
|
22
22
|
"test:unit": "node scripts/test.js unit",
|
|
23
23
|
"test:integration": "node scripts/test.js integration",
|
|
24
24
|
"test:real-api": "node scripts/test.js realApi",
|
|
@@ -60,26 +60,27 @@
|
|
|
60
60
|
"node": ">=22.19.0"
|
|
61
61
|
},
|
|
62
62
|
"optionalDependencies": {
|
|
63
|
-
"@vscode/ripgrep": "^1.
|
|
63
|
+
"@vscode/ripgrep": "^1.18.0",
|
|
64
|
+
"better-sqlite3": "^11.8.1",
|
|
64
65
|
"bun-pty": "^0.4.8",
|
|
65
|
-
"node-pty": "1.
|
|
66
|
+
"node-pty": "1.1.0"
|
|
66
67
|
},
|
|
67
68
|
"dependencies": {
|
|
68
|
-
"@agentclientprotocol/sdk": "^
|
|
69
|
+
"@agentclientprotocol/sdk": "^1.3.0",
|
|
69
70
|
"@anthropic-ai/sandbox-runtime": "0.0.67",
|
|
70
71
|
"@earendil-works/pi-ai": "0.83.0",
|
|
71
72
|
"@inkjs/ui": "^2.0.0",
|
|
72
|
-
"@modelcontextprotocol/sdk": "^1.
|
|
73
|
-
"ahooks": "^3.9.
|
|
74
|
-
"ansi-escapes": "^7.
|
|
73
|
+
"@modelcontextprotocol/sdk": "^1.30.0",
|
|
74
|
+
"ahooks": "^3.9.7",
|
|
75
|
+
"ansi-escapes": "^7.3.0",
|
|
75
76
|
"async-mutex": "^0.5.0",
|
|
76
|
-
"axios": "^1.
|
|
77
|
+
"axios": "^1.19.0",
|
|
77
78
|
"chalk": "^5.4.1",
|
|
78
79
|
"diff": "^8.0.2",
|
|
79
80
|
"fast-glob": "^3.3.3",
|
|
80
|
-
"fuse.js": "^7.
|
|
81
|
+
"fuse.js": "^7.5.0",
|
|
81
82
|
"gray-matter": "^4.0.3",
|
|
82
|
-
"hono": "^4.
|
|
83
|
+
"hono": "^4.13.0",
|
|
83
84
|
"ink": "npm:@jrichman/ink@6.4.10",
|
|
84
85
|
"ink-big-text": "^2.0.0",
|
|
85
86
|
"ink-gradient": "^3.0.0",
|
|
@@ -87,41 +88,43 @@
|
|
|
87
88
|
"ink-spinner": "^5.0.0",
|
|
88
89
|
"ink-text-input": "^6.0.0",
|
|
89
90
|
"js-tiktoken": "^1.0.21",
|
|
90
|
-
"lodash-es": "^4.
|
|
91
|
+
"lodash-es": "^4.18.1",
|
|
91
92
|
"lowlight": "^3.3.0",
|
|
92
|
-
"lru-cache": "^11.2
|
|
93
|
+
"lru-cache": "^11.5.2",
|
|
93
94
|
"nanoid": "^5.1.6",
|
|
94
95
|
"open": "^10.1.2",
|
|
95
|
-
"
|
|
96
|
-
"
|
|
97
|
-
"react": "
|
|
98
|
-
"
|
|
99
|
-
"
|
|
100
|
-
"
|
|
96
|
+
"picomatch": "^4.0.5",
|
|
97
|
+
"react": "19.2.4",
|
|
98
|
+
"react-dom": "19.2.4",
|
|
99
|
+
"semver": "^7.8.5",
|
|
100
|
+
"string-width": "^8.2.2",
|
|
101
|
+
"typebox": "1.3.10",
|
|
101
102
|
"undici": "^7.16.0",
|
|
103
|
+
"vscode-jsonrpc": "8.2.1",
|
|
104
|
+
"vscode-languageserver-protocol": "3.17.5",
|
|
105
|
+
"vscode-languageserver-types": "3.17.5",
|
|
102
106
|
"write-file-atomic": "^7.0.0",
|
|
103
|
-
"ws": "^8.
|
|
104
|
-
"yaml": "^2.
|
|
105
|
-
"yargs": "^18.
|
|
106
|
-
"
|
|
107
|
-
"zustand": "^5.0.9"
|
|
107
|
+
"ws": "^8.21.2",
|
|
108
|
+
"yaml": "^2.9.0",
|
|
109
|
+
"yargs": "^18.1.0",
|
|
110
|
+
"zustand": "^5.0.14"
|
|
108
111
|
},
|
|
109
112
|
"devDependencies": {
|
|
110
|
-
"@biomejs/biome": "^2.
|
|
111
|
-
"@types/bun": "^1.3.
|
|
113
|
+
"@biomejs/biome": "^2.5.7",
|
|
114
|
+
"@types/bun": "^1.3.14",
|
|
112
115
|
"@types/json-schema": "^7.0.15",
|
|
113
116
|
"@types/lodash-es": "^4.17.12",
|
|
114
117
|
"@types/node": "^22.15.24",
|
|
115
|
-
"@types/picomatch": "^4.0.
|
|
116
|
-
"@types/react": "
|
|
117
|
-
"@types/react-dom": "
|
|
118
|
-
"@types/semver": "^7.
|
|
118
|
+
"@types/picomatch": "^4.0.3",
|
|
119
|
+
"@types/react": "19.2.10",
|
|
120
|
+
"@types/react-dom": "19.2.3",
|
|
121
|
+
"@types/semver": "^7.8.0",
|
|
119
122
|
"@types/write-file-atomic": "^4.0.3",
|
|
120
|
-
"@types/ws": "^8.
|
|
121
|
-
"@types/yargs": "^17.0.
|
|
122
|
-
"@vitest/coverage-v8": "^
|
|
123
|
+
"@types/ws": "^8.18.1",
|
|
124
|
+
"@types/yargs": "^17.0.35",
|
|
125
|
+
"@vitest/coverage-v8": "^4.1.10",
|
|
123
126
|
"jsdom": "^26.0.0",
|
|
124
127
|
"typescript": "^5.9.2",
|
|
125
|
-
"vitest": "^
|
|
128
|
+
"vitest": "^4.1.10"
|
|
126
129
|
}
|
|
127
130
|
}
|
package/dist/chunk-1m63zddw.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import d from"typebox/schema";import o from"typebox/value";class u extends Error{issues;constructor(r){super(r.map((t)=>{return`${t.path.length>0?t.path.join("."):"root"}: ${t.message}`}).join("; "));this.issues=r;this.name="SchemaValidationError"}}function p(r){if(!r)return[];return r.split("/").slice(1).map((t)=>t.replace(/~1/g,"/").replace(/~0/g,"~")).map((t)=>/^(0|[1-9]\d*)$/.test(t)?Number(t):t)}function g(r,t){let n=r;for(let e of t){if(n===null||typeof n!=="object")return;n=n[e]}return n}function i(r,t){let[,n]=d.Errors(r,t);return n.map((e)=>{let s=p(e.instancePath);return{code:e.keyword,path:s,message:e.message,value:g(t,s)}})}function a(r,t){let n=o.Default(r,o.Clone(t)),e=i(r,n);if(e.length>0)return{success:!1,error:new u(e)};let s=o.Clean(r,n),c=i(r,s);if(c.length>0)return{success:!1,error:new u(c)};return{success:!0,data:s}}function f(r,t){let n=a(r,t);if(!n.success)throw n.error;return n.data}import l from"typebox";function x(r){return Object.defineProperties(r,{parse:{value:(t)=>f(r,t),enumerable:!1},safeParse:{value:(t)=>a(r,t),enumerable:!1}}),r}function b(r,t){return l.Optional({...r,default:t})}function V(r,t={}){return l.Unsafe({type:"string",enum:[...r],...t})}
|
|
2
|
-
export{a as Gb,f as Hb,l as Ib,x as Jb,b as Kb,V as Lb};
|
package/dist/chunk-23h9grdr.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Aa as g,Ba as h,Ca as i,Da as j,Ea as k,Fa as l,Ga as m,ua as a,va as b,wa as c,xa as d,ya as e,za as f}from"./chunk-yewg510f.js";import"./chunk-jc7k8pfn.js";import"./chunk-7bqkkjxf.js";import"./chunk-kjc2aqww.js";import"./chunk-eyypmc9m.js";import"./chunk-zsyff0ky.js";import"./chunk-be7qz4cv.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,h as getAllModels,g as ensureStoreInitialized,m as configActions,d as appActions};
|
package/dist/chunk-2c69g6t9.js
DELETED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import{Ua as I,Va as C}from"./chunk-sva5bdgz.js";import{Bb as R}from"./chunk-5sccs44n.js";import{Gb as E,Ib as U}from"./chunk-1m63zddw.js";import{oc as f}from"./chunk-be7qz4cv.js";import{EventEmitter as t}from"events";function p($){if($===void 0)return"undefined";if(typeof $==="string")return $;try{let L=JSON.stringify($);return L===void 0?String($):L}catch{return String($)}}function g($){let L=$;switch($.code){case"type":return`类型错误:${$.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${$.message}`;case"maxLength":return`字符串过长:${$.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${$.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${$.message}`;case"minItems":return`数组元素过少:${$.message}`;case"maxItems":return`数组元素过多:${$.message}`;case"format":return`格式错误:${$.message}`;case"enum":return`必须是枚举允许的值之一:${$.message}`;case"const":return`必须是指定的字面量值:${$.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${$.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return $.message||"自定义验证失败";default:return $.message||`验证失败:${p(L)}`}}class D extends Error{issues;type;constructor($,L,G="validation_error"){super($);this.issues=L;this.type=G;this.name="ToolValidationError"}}function N($,L){let G=E($,L);if(G.success)return G.data;let Q=G.error.issues.map((X)=>({field:X.path.length>0?X.path.join("."):"root",message:g(X),value:X.value})),W=Q.length===1?`参数验证失败 [${Q[0].field}]: ${Q[0].message}`:`参数验证失败 (${Q.length} 个错误):
|
|
2
|
-
${Q.map((X)=>` - ${X.field}: ${X.message}`).join(`
|
|
3
|
-
`)}`;throw new D(W,Q)}function K($){if(!$||typeof $!=="object")return;let L=$;if(L.type==="object"&&L.properties)L.required??=[],L.additionalProperties??=!1;for(let G of Object.values(L))if(Array.isArray(G))for(let Q of G)K(Q);else K(G)}function x($){let L=JSON.parse(JSON.stringify($,(G,Q)=>G.startsWith("~")?void 0:Q));return K(L),L}class O{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor($,L,G,Q,W){this.toolName=$;this.params=L;this.executeFn=G;this.descriptionFn=Q;this.affectedPathsFn=W}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute($,L,G){let Q={signal:$,updateOutput:L,...G};return this.executeFn(this.params,Q)}}function h($){return{name:$.name,displayName:$.displayName,kind:$.kind,isReadOnly:$.isReadOnly??R($.kind),isConcurrencySafe:$.isConcurrencySafe??!1,strict:$.strict??!1,description:$.description,version:$.version||"1.0.0",category:$.category,tags:$.tags||[],getFunctionDeclaration(){let L=x($.schema),G=$.description.short;if($.description.long)G+=`
|
|
4
|
-
|
|
5
|
-
${$.description.long}`;if($.description.usageNotes&&$.description.usageNotes.length>0)G+=`
|
|
6
|
-
|
|
7
|
-
Usage Notes:
|
|
8
|
-
${$.description.usageNotes.map((Q)=>`- ${Q}`).join(`
|
|
9
|
-
`)}`;if($.description.important&&$.description.important.length>0)G+=`
|
|
10
|
-
|
|
11
|
-
Important:
|
|
12
|
-
${$.description.important.map((Q)=>`[WARN] ${Q}`).join(`
|
|
13
|
-
`)}`;return{name:$.name,description:G,parameters:L}},getMetadata(){return{name:$.name,displayName:$.displayName,kind:$.kind,version:$.version||"1.0.0",category:$.category,tags:$.tags||[],description:$.description,schema:x($.schema)}},build(L){let G=N($.schema,L);return new O($.name,G,$.execute)},async execute(L,G,Q){return this.build(L).execute(G||new AbortController().signal,void 0,Q)},extractSignatureContent:$.extractSignatureContent?(L)=>$.extractSignatureContent(L):void 0,abstractPermissionRule:$.abstractPermissionRule?(L)=>$.abstractPermissionRule(L):void 0}}function z($,L,G,Q){let W=G.inputSchema&&typeof G.inputSchema==="object"?U.Unsafe(G.inputSchema):U.Any(),X=Q||G.name;return h({name:X,displayName:`${L}: ${G.name}`,kind:"execute",schema:W,description:{short:G.description||`MCP Tool: ${G.name}`,important:[`From MCP server: ${L}`,"Executes external tools; user confirmation required"]},category:"MCP tool",tags:["mcp","external",L],async execute(Y,q){try{let Z=await $.callTool(G.name,Y),A="";if(Z.content&&Array.isArray(Z.content)){for(let B of Z.content)if(B.type==="text"&&B.text)A+=B.text;else if(B.type==="image")A+=`[image: ${B.mimeType||"unknown"}]
|
|
14
|
-
`;else if(B.type==="resource")A+=`[resource: ${B.mimeType||"unknown"}]
|
|
15
|
-
`}if(Z.isError)return{success:!1,llmContent:A||"MCP tool execution failed",error:{type:"execution_error",message:A||"MCP tool execution failed"},metadata:{summary:`MCP ${G.name} 执行失败`,serverName:L,toolName:G.name}};return{success:!0,llmContent:A||"Execution succeeded",metadata:{summary:`MCP ${G.name} 执行成功`,serverName:L,toolName:G.name,mcpResult:Z}}}catch(Z){return{success:!1,llmContent:`MCP tool execution failed: ${Z.message}`,error:{type:"execution_error",message:Z.message},metadata:{summary:`MCP ${G.name} 执行失败`,serverName:L,toolName:G.name}}}}})}import{Client as i}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as a}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as c}from"@modelcontextprotocol/sdk/client/stdio.js";import{EventEmitter as s}from"events";import{spawn as m}from"child_process";import*as b from"crypto";import*as S from"http";import{URL as k}from"url";import{promises as w}from"fs";import v from"os";import _ from"path";class H{tokenFilePath;constructor(){let $=v.homedir(),L=_.join($,".blade");this.tokenFilePath=_.join(L,"mcp-oauth-tokens.json")}async ensureConfigDir(){let $=_.dirname(this.tokenFilePath);try{await w.mkdir($,{recursive:!0,mode:493})}catch{}}async loadAllCredentials(){let $=new Map;try{let L=await w.readFile(this.tokenFilePath,"utf-8"),G=JSON.parse(L);for(let Q of G)$.set(Q.serverName,Q)}catch(L){if(L.code!=="ENOENT")console.warn("[OAuthTokenStorage] 加载令牌失败:",L)}return $}async saveAllCredentials($){await this.ensureConfigDir();let L=Array.from($.values());await w.writeFile(this.tokenFilePath,JSON.stringify(L,null,2),{mode:384})}async saveToken($,L,G,Q){let W=await this.loadAllCredentials(),X={serverName:$,token:L,clientId:G,tokenUrl:Q,updatedAt:Date.now()};W.set($,X),await this.saveAllCredentials(W)}async getCredentials($){return(await this.loadAllCredentials()).get($)||null}async deleteCredentials($){let L=await this.loadAllCredentials();L.delete($),await this.saveAllCredentials(L)}async listServers(){let $=await this.loadAllCredentials();return Array.from($.keys())}isTokenExpired($){if(!$.expiresAt)return!1;let L=300000;return Date.now()>=$.expiresAt-L}}var V=7777,j="/oauth/callback",M=200;class F{tokenStorage;constructor($=new H){this.tokenStorage=$}generatePKCEParams(){let $=b.randomBytes(32).toString("base64url"),L=b.createHash("sha256").update($).digest("base64url"),G=b.randomBytes(16).toString("base64url");return{codeVerifier:$,codeChallenge:L,state:G}}buildAuthorizationUrl($,L){let G=$.redirectUri||`http://localhost:${V}${j}`,Q=new URLSearchParams({client_id:$.clientId,response_type:"code",redirect_uri:G,state:L.state,code_challenge:L.codeChallenge,code_challenge_method:"S256"});if($.scopes&&$.scopes.length>0)Q.append("scope",$.scopes.join(" "));let W=new k($.authorizationUrl);return Q.forEach((X,Y)=>{W.searchParams.append(Y,X)}),W.toString()}async startCallbackServer($){return new Promise((L,G)=>{let Q=S.createServer((W,X)=>{try{let Y=new k(W.url,`http://localhost:${V}`);if(Y.pathname!==j){X.writeHead(404),X.end("Not found");return}let q=Y.searchParams.get("code"),Z=Y.searchParams.get("state"),A=Y.searchParams.get("error");if(A){X.writeHead(M,{"Content-Type":"text/html"}),X.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
|
-
`),Q.close(),G(Error(`OAuth error: ${A}`));return}if(!q||!Z){X.writeHead(400),X.end("Missing code or state parameter");return}if(Z!==$){X.writeHead(400),X.end("Invalid state parameter"),Q.close(),G(Error("State mismatch - possible CSRF attack"));return}X.writeHead(M,{"Content-Type":"text/html"}),X.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
|
-
`),Q.close(),L(q)}catch(Y){Q.close(),G(Y)}});Q.on("error",G),Q.listen(V,()=>{console.log(`[OAuth] Callback server listening on port ${V}`)}),setTimeout(()=>{Q.close(),G(Error("OAuth callback timeout"))},300000)})}async exchangeCodeForToken($,L,G){let Q=$.redirectUri||`http://localhost:${V}${j}`,W=new URLSearchParams({grant_type:"authorization_code",code:L,redirect_uri:Q,code_verifier:G,client_id:$.clientId});if($.clientSecret)W.append("client_secret",$.clientSecret);let X=await fetch($.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:W.toString()});if(!X.ok){let Y=await X.text();throw Error(`Token exchange failed: ${X.status} - ${Y}`)}return await X.json()}async refreshAccessToken($,L){let G=new URLSearchParams({grant_type:"refresh_token",refresh_token:L,client_id:$.clientId});if($.clientSecret)G.append("client_secret",$.clientSecret);if($.scopes&&$.scopes.length>0)G.append("scope",$.scopes.join(" "));let Q=await fetch($.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:G.toString()});if(!Q.ok){let W=await Q.text();throw Error(`Token refresh failed: ${Q.status} - ${W}`)}return await Q.json()}async authenticate($,L){if(!L.clientId||!L.authorizationUrl||!L.tokenUrl)throw Error("Missing required OAuth configuration");let G=this.generatePKCEParams(),Q=this.buildAuthorizationUrl(L,G);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(Q),console.log("");let W=this.startCallbackServer(G.state);try{await this.openAuthorizationUrl(Q)}catch(Z){console.warn("[OAuth] Failed to open browser automatically:",Z)}let X=await W;console.log("[OAuth] Authorization code received, exchanging for tokens...");let Y=await this.exchangeCodeForToken(L,X,G.codeVerifier),q={accessToken:Y.access_token,tokenType:Y.token_type||"Bearer",refreshToken:Y.refresh_token,scope:Y.scope};if(Y.expires_in)q.expiresAt=Date.now()+Y.expires_in*1000;return await this.tokenStorage.saveToken($,q,L.clientId,L.tokenUrl),console.log("[OAuth] Authentication successful! Token saved."),q}async openAuthorizationUrl($){let{command:L,args:G}=this.getBrowserCommand($);await new Promise((Q,W)=>{let X=m(L,G,{stdio:"ignore"});X.once("error",W),X.once("close",(Y)=>{if(Y===0||Y===null)Q();else W(Error(`Failed to open browser (exit code ${Y})`))})})}getBrowserCommand($){if(process.platform==="darwin")return{command:"open",args:[$]};if(process.platform==="win32")return{command:"cmd",args:["/c","start","",$]};return{command:"xdg-open",args:[$]}}async getValidToken($,L){let G=await this.tokenStorage.getCredentials($);if(!G)return null;let{token:Q}=G;if(!this.tokenStorage.isTokenExpired(Q))return Q.accessToken;if(Q.refreshToken&&L.clientId&&G.tokenUrl)try{console.log(`[OAuth] Refreshing expired token for server: ${$}`);let W=await this.refreshAccessToken(L,Q.refreshToken),X={accessToken:W.access_token,tokenType:W.token_type,refreshToken:W.refresh_token||Q.refreshToken,scope:W.scope||Q.scope};if(W.expires_in)X.expiresAt=Date.now()+W.expires_in*1000;return await this.tokenStorage.saveToken($,X,L.clientId,G.tokenUrl),X.accessToken}catch(W){console.error("[OAuth] Failed to refresh token:",W),await this.tokenStorage.deleteCredentials($)}return null}}import{EventEmitter as l}from"events";class P extends l{client;config;checkTimer=null;isChecking=!1;consecutiveFailures=0;lastCheckTime=0;currentStatus="healthy";constructor($,L={}){super();this.client=$,this.config={interval:L.interval??30000,timeout:L.timeout??1e4,enabled:L.enabled??!1,failureThreshold:L.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 $=this.client.connectionStatus;if($==="connected"){await this.pingServer(),this.consecutiveFailures=0,this.setStatus("healthy");let L={status:"healthy",timestamp:Date.now(),consecutiveFailures:0};return this.emit("healthCheck",L),L}else throw Error(`连接状态异常: ${$}`)}catch($){this.consecutiveFailures++;let L=$;console.warn(`[HealthMonitor] 健康检查失败(${this.consecutiveFailures}/${this.config.failureThreshold}):`,L.message);let G;if(this.consecutiveFailures>=this.config.failureThreshold)G="unhealthy",this.emit("unhealthy",this.consecutiveFailures,L),console.log("[HealthMonitor] 达到失败阈值,触发重连..."),this.triggerReconnection().catch((W)=>{console.error("[HealthMonitor] 重连失败:",W)});else G="degraded";this.setStatus(G);let Q={status:G,timestamp:Date.now(),consecutiveFailures:this.consecutiveFailures,lastError:L};return this.emit("healthCheck",Q),Q}finally{this.isChecking=!1}}async pingServer(){let $=new Promise((G,Q)=>{setTimeout(()=>Q(Error("Health check timeout")),this.config.timeout)}),L=(async()=>{if(this.client.availableTools.length===0){if(!this.client.server)throw Error("Server info not available")}})();await Promise.race([L,$])}async triggerReconnection(){try{await this.client.disconnect(),await new Promise(($)=>setTimeout($,1000)),await this.client.connect(),console.log("[HealthMonitor] 重连成功"),this.consecutiveFailures=0,this.setStatus("healthy"),this.emit("reconnected")}catch($){throw console.error("[HealthMonitor] 重连失败:",$),$}}setStatus($){if(this.currentStatus!==$){let L=this.currentStatus;this.currentStatus=$,this.emit("statusChanged",$,L)}}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 T($){if(!($ instanceof Error))return{type:"unknown",isRetryable:!1,originalError:Error(String($))};let L=$.message.toLowerCase();if(["command not found","no such file","permission denied","invalid configuration","malformed","syntax error"].some((W)=>L.includes(W)))return{type:"config_error",isRetryable:!1,originalError:$};if(L.includes("unauthorized")||L.includes("401")||L.includes("authentication failed"))return{type:"auth_error",isRetryable:!1,originalError:$};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((W)=>L.includes(W)))return{type:"network_temporary",isRetryable:!0,originalError:$};return{type:"unknown",isRetryable:!0,originalError:$}}class y extends s{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($,L,G){super();this.config=$;if(this.serverName=L||"default",$.oauth?.enabled)this.oauthProvider=new F;if(G?.enabled)this.healthMonitor=new P(this,G),this.healthMonitor.on("unhealthy",(Q,W)=>{this.emit("unhealthy",Q,W)}),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($=3,L=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 G=null;for(let Q=1;Q<=$;Q++)try{await this.doConnect(),this.reconnectAttempts=0;return}catch(W){G=W;let X=T(W);if(!X.isRetryable)throw console.error("[McpClient] 检测到永久性错误,放弃重试:",X.type),W;if(Q<$){let Y=L*Math.pow(2,Q-1);console.warn(`[McpClient] 连接失败(${Q}/${$}),${Y}ms 后重试...`),await new Promise((q)=>setTimeout(q,Y))}}throw G||Error("连接失败")}async doConnect(){try{this.setStatus("connecting"),this.sdkClient=new i({name:C(),version:I()},{capabilities:{roots:{listChanged:!0},sampling:{}}}),this.sdkClient.onclose=()=>{this.handleUnexpectedClose()};let $=await this.createTransport();await this.sdkClient.connect($);let L=this.sdkClient.getServerVersion();if(this.serverInfo={name:L?.name||"Unknown",version:L?.version||"0.0.0"},await this.loadTools(),this.setStatus("connected"),this.emit("connected",this.serverInfo),this.healthMonitor)this.healthMonitor.start()}catch($){throw this.setStatus("error"),this.emit("error",$),$}}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 $=Math.min(1000*Math.pow(2,this.reconnectAttempts),30000);this.reconnectAttempts++,console.log(`[McpClient] 将在 ${$}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(L){if(console.error("[McpClient] 重连失败:",L),T(L).isRetryable)this.scheduleReconnect();else console.error("[McpClient] 检测到永久性错误,停止重连"),this.emit("reconnectFailed")}},$)}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($){console.warn("[McpClient] 断开连接时出错:",$)}this.sdkClient=null}this.tools.clear(),this.serverInfo=null,this.reconnectAttempts=0,this.setStatus("disconnected"),this.emit("disconnected"),this.isManualDisconnect=!1}async callTool($,L={}){if(!this.sdkClient)throw Error("客户端未连接到服务器");if(!this.tools.has($))throw Error(`工具 "${$}" 不存在`);try{return await this.sdkClient.callTool({name:$,arguments:L})}catch(G){throw console.error(`[McpClient] 调用工具 "${$}" 失败:`,G),G}}async createTransport(){let{type:$,command:L,args:G,env:Q,url:W,headers:X,oauth:Y}=this.config,q={...X};if(Y?.enabled&&this.oauthProvider&&($==="sse"||$==="http"))try{let Z=await this.oauthProvider.getValidToken(this.serverName,Y);if(!Z){console.log(`[McpClient] 服务器 "${this.serverName}" 需要 OAuth 认证`);let A=await this.oauthProvider.authenticate(this.serverName,Y);q.Authorization=`Bearer ${A.accessToken}`}else q.Authorization=`Bearer ${Z}`}catch(Z){throw console.error("[McpClient] OAuth 认证失败:",Z),Error(`OAuth 认证失败: ${Z instanceof Error?Z.message:String(Z)}`)}if($==="stdio"){if(!L)throw Error("stdio 传输需要 command 参数");let Z={};for(let[A,B]of Object.entries(process.env))if(B!==void 0)Z[A]=B;return new c({command:L,args:G||[],env:{...Z,...Q},stderr:"ignore"})}else if($==="sse"){if(!W)throw Error("sse 传输需要 url 参数");return new a(new URL(W),{requestInit:{headers:q}})}else if($==="http"){if(!W)throw Error("http 传输需要 url 参数");let{StreamableHTTPClientTransport:Z}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");return new Z(new URL(W),{requestInit:{headers:q}})}throw Error(`不支持的传输类型: ${$}`)}async loadTools(){if(!this.sdkClient)return;try{let $=await this.sdkClient.listTools();if(this.tools.clear(),$.tools)for(let L of $.tools)this.tools.set(L.name,L);this.emit("toolsUpdated",this.availableTools)}catch($){throw console.error("[McpClient] 加载工具失败:",$),$}}setStatus($){let L=this.status;this.status=$,this.emit("statusChanged",$,L)}async initialize(){return this.connect()}async destroy(){return this.disconnect()}async connectToServer($){return this.connect()}async disconnectFromServer($){return this.disconnect()}async listResources($){if(!this.sdkClient)return[];try{return(await this.sdkClient.listResources()).resources||[]}catch{return[]}}async listTools($){return this.availableTools}async readResource($,L){if(!this.sdkClient)throw Error("客户端未连接");return(await this.sdkClient.readResource({uri:$})).contents?.[0]||{uri:$,text:""}}}class J extends t{static instance=null;servers=new Map;isDiscovering=!1;constructor(){super()}static getInstance(){if(!J.instance)J.instance=new J;return J.instance}static createIsolated(){return new J}async registerServer($,L){if(this.servers.has($))throw Error(`MCP服务器 "${$}" 已经注册`);let G=new y(L,$,L.healthCheck),Q={config:L,client:G,status:"disconnected",tools:[]};this.setupClientEventHandlers(G,Q,$),this.servers.set($,Q),this.emit("serverRegistered",$,Q);try{await this.connectServer($)}catch(W){console.warn(`MCP服务器 "${$}" 连接失败:`,W)}}async unregisterServer($){let L=this.servers.get($);if(!L)return;try{await L.client.disconnect()}catch(G){console.warn(`断开MCP服务器 "${$}" 时出错:`,G)}this.servers.delete($),this.emit("serverUnregistered",$)}async connectServer($){let L=this.servers.get($);if(!L)throw Error(`MCP服务器 "${$}" 未注册`);if(L.status==="connected")return;try{L.status="connecting",await L.client.connect(),L.connectedAt=new Date,L.lastError=void 0,L.tools=L.client.availableTools}catch(G){throw L.lastError=G,L.status="error",G}}async disconnectServer($){let L=this.servers.get($);if(!L)return;await L.client.disconnect(),L.connectedAt=void 0}async reconnectServer($){let L=this.servers.get($);if(!L)throw Error(`MCP服务器 "${$}" 未注册`);if(L.status==="connected")await L.client.disconnect();try{L.status="connecting",await L.client.connect(),L.connectedAt=new Date,L.lastError=void 0,L.tools=L.client.availableTools}catch(G){throw L.lastError=G,L.status="error",G}}async getAvailableTools(){let $=[],L=new Map;for(let[G,Q]of this.servers)if(Q.status==="connected")for(let W of Q.tools){let X=L.get(W.name)||0;L.set(W.name,X+1)}for(let[G,Q]of this.servers)if(Q.status==="connected")for(let W of Q.tools){let Y=(L.get(W.name)||0)>1?`${G}__${W.name}`:W.name,q=z(Q.client,G,W,Y);$.push(q)}return $}async findTool($){for(let[L,G]of this.servers)if(G.status==="connected"){let Q=G.tools.find((W)=>W.name===$);if(Q)return z(G.client,L,Q)}return null}getToolsByServer($){let L=this.servers.get($);if(!L||L.status!=="connected")return[];return L.tools.map((G)=>z(L.client,$,G))}getServerStatus($){return this.servers.get($)||null}getAllServers(){return new Map(this.servers)}async refreshAllTools(){let $=[];for(let[L,G]of this.servers)if(G.status==="connected")$.push(this.refreshServerTools(L));await Promise.allSettled($)}async refreshServerTools($){let L=this.servers.get($);if(!L||L.status!=="connected")return;try{let G=L.client.availableTools,Q=L.tools.length;L.tools=G,this.emit("toolsUpdated",$,G,Q)}catch(G){console.warn(`刷新服务器 "${$}" 工具列表失败:`,G)}}setupClientEventHandlers($,L,G){$.on("connected",(Q)=>{L.status="connected",L.connectedAt=new Date,L.tools=$.availableTools,this.emit("serverConnected",G,Q)}),$.on("disconnected",()=>{L.status="disconnected",L.connectedAt=void 0,L.tools=[],this.emit("serverDisconnected",G)}),$.on("error",(Q)=>{L.status="error",L.lastError=Q,this.emit("serverError",G,Q)}),$.on("toolsUpdated",(Q)=>{let W=L.tools.length;L.tools=Q,this.emit("toolsUpdated",G,Q,W)}),$.on("statusChanged",(Q,W)=>{L.status=Q,this.emit("serverStatusChanged",G,Q,W)})}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($){let L=Object.entries($).map(([G,Q])=>this.registerServer(G,Q).catch((W)=>{return console.warn(`注册MCP服务器 "${G}" 失败:`,W),W}));await Promise.allSettled(L)}getStatistics(){let $=0,L=0,G=0;for(let Q of this.servers.values())if(Q.status==="connected")$++,L+=Q.tools.length;else if(Q.status==="error")G++;return{totalServers:this.servers.size,connectedServers:$,errorServers:G,totalTools:L,isDiscovering:this.isDiscovering}}async disconnectAll(){let $=[];for(let[L,G]of this.servers)if(G.status==="connected")$.push(G.client.disconnect().catch((Q)=>{console.warn(`断开 MCP 服务器 "${L}" 时出错:`,Q)}));await Promise.allSettled($),this.servers.clear()}}
|
|
34
|
-
export{h as fa,J as ga};
|
package/dist/chunk-5sccs44n.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function f(x){return x!==void 0&&typeof x.pattern==="string"&&typeof x.search_path==="string"}function b(x){return x!==void 0&&x.kind==="edit"&&typeof x.matches_found==="number"}function h(x){return x==="readonly"}var v="__aborted__";export{f as zb,b as Ab,h as Bb,v as Cb};
|
package/dist/chunk-6msfa7jh.js
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import{p as v}from"./chunk-9cr3jexy.js";import{$ as x,C as B,K,M as j,R as h,T as A,U as T,W as b,ba as q,ca as M}from"./chunk-kf43f8sy.js";import"./chunk-ar5564sf.js";import{ga as c}from"./chunk-2c69g6t9.js";import"./chunk-mqqajem9.js";import{za as k}from"./chunk-yewg510f.js";import"./chunk-jc7k8pfn.js";import{Sa as u}from"./chunk-hqtskyc1.js";import"./chunk-sva5bdgz.js";import{kb as y}from"./chunk-m0ded6ky.js";import{Cb as N}from"./chunk-5sccs44n.js";import"./chunk-b922cq7k.js";import"./chunk-1m63zddw.js";import{Mb as C}from"./chunk-7bqkkjxf.js";import{Sb as I}from"./chunk-kjc2aqww.js";import"./chunk-d7nrqg5b.js";import{bc as w}from"./chunk-eyypmc9m.js";import"./chunk-zsyff0ky.js";import"./chunk-be7qz4cv.js";import{Readable as l,Writable as i}from"node:stream";import*as E from"@agentclientprotocol/sdk";import S from"node:path";import{PROTOCOL_VERSION as m}from"@agentclientprotocol/sdk";import{nanoid as R}from"nanoid";var W=w("Agent");function f(z){return Object.fromEntries(z.map((J)=>[J.name,J.value]))}function p(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:f(z.env)};return{type:z.type,url:z.url,headers:f(z.headers)}}function d(z){return Object.fromEntries(z.map((J)=>[J.name,p(J)]))}function O(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((J)=>{if(J.type==="text")return J.text?[{type:"text",text:J.text}]:[];let H=J.image_url.url,Q=/^data:([^;,]+);base64,(.+)$/s.exec(H);if(!Q)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Q[1]??"image/png",data:Q[2]??""}]})}class L{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;messages;mode="default";constructor(z,J,H,Q,X={}){this.id=z;this.cwd=J;this.connection=H;this.clientCapabilities=Q;this.options=X;this.messages=[...X.initialMessages??[]]}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return b.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){W.debug(`[AcpSession ${this.id}] Initializing...`),B.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),W.debug(`[AcpSession ${this.id}] ACP service context initialized`);let z=this.options.mcpServers?d(this.options.mcpServers):void 0;this.runtime=await h.create({sessionId:this.id,workspaceRoot:this.cwd,...z?{mcpServers:z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{}}),this.agent=await this.createAgent(),W.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=K.subscribe((H)=>{if(H.type!=="task.status"||H.sessionId!==this.id||H.projectPath!==this.cwd)return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof H.properties.updatedAt==="string"?H.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":H.properties.taskStatus,...typeof H.properties.taskStatusReason==="string"?{"blade/taskStatusReason":H.properties.taskStatusReason}:{},...typeof H.properties.taskStartedAt==="string"?{"blade/taskStartedAt":H.properties.taskStartedAt}:{},...typeof H.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":H.properties.taskCompletedAt}:{},...H.properties.taskDiffStat&&typeof H.properties.taskDiffStat==="object"?{"blade/taskDiffStat":H.properties.taskDiffStat}:{},...typeof H.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":H.properties.taskQueuePosition}:{},...typeof H.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":H.properties.taskQueueDepth}:{},...typeof H.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":H.properties.taskConcurrencyLimit}:{},...typeof H.properties.taskInFlight==="number"?{"blade/taskInFlight":H.properties.taskInFlight}:{}}})});let J=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||J?.status==="active")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let z of this.messages){if(!this.canSendUpdates())return;let J=z.role==="user"?"user_message_chunk":z.role==="assistant"?"agent_message_chunk":void 0;if(!J)continue;for(let H of O(z.content)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:J,content:H}))return}}if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);W.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,J){try{W.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let H={cwd:this.cwd,workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.messages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let $=await this.runtime.rewindSession(Z);return this.messages=[...$.messages],await this.agent?.destroy(),this.agent=await this.createAgent(),$}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let G=!1,V,U=(_)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:_.id,status:_.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:_.result?.message||_.result?.error||`Subagent ${_.status}`}}]})},D=this.runtime.resumeSubagent({agentId:Z,prompt:$,onCompleted:(_)=>{if(G)U(_);else V=_}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D.session.id,status:"in_progress",title:`Resuming ${D.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${D.source.id} at depth ${D.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),G=!0,V)U(V);return D}},signal:J,acp:{sendMessage:(Z)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Z}})},sendToolStart:(Z,$,G)=>{let V=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,U=this.mapToolKind(G);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:V,status:"in_progress",title:`${Z}`,content:[{type:"content",content:{type:"text",text:JSON.stringify($,null,2)}}],kind:U})},sendToolResult:(Z,$)=>{if($.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.summary}})}}},Q=await q(z,H),X=Q.data?.action;if(X==="start_goal"||X==="resume_goal")this.schedulePendingResume();if(X==="rewind_session"&&Array.isArray(Q.data?.messages))this.messages=[...Q.data.messages];if((Q.message==="compact_completed"||Q.message==="compact_fallback")&&Q.data?.compactedMessages)this.messages=[...Q.data.compactedMessages];let Y=Q.content||Q.message;if(Y)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y}});if(Q.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Q.error}`}});return{stopReason:Q.success?"end_turn":"cancelled"}}catch(H){return W.error(`[AcpSession ${this.id}] Slash command error:`,H),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${H instanceof Error?H.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let z=M(),J=["model","permissions","theme","config","exit","ide"],Q=z.filter((X)=>!J.includes(X.name)).map((X)=>{let Y;if(X.usage){let Z=X.usage.replace(/^\/\w+\s*/,"").trim();if(Z)Y=Z}if(X.aliases?.length){let Z=`Aliases: ${X.aliases.join(", ")}`;Y=Y?`${Y} | ${Z}`:Z}return{name:X.name,description:X.description,input:Y?{hint:Y}:void 0}});W.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Q.map((X)=>X.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Q}),W.info(`[AcpSession ${this.id}] Sent ${Q.length} available commands`)}catch(z){W.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,J={}){if(B.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let H=this.resolvePrompt(z.prompt);if(this.pendingPrompt){if(/^\/goal(?:\s|$)/i.test(H.trim()))return this.handleSlashCommand(H,this.pendingPrompt.signal);let X=await this.runtime.enqueueSteering(H,{allowBeforeTurn:!0});if(!X.accepted)throw Error(X.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(W.debug(`[AcpSession ${this.id}] Queued steering for active turn (${X.queued})`),X.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let Q=new AbortController;this.pendingPrompt=Q;try{if(W.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),x(H))return await this.handleSlashCommand(H,Q.signal);let X={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:Q.signal,permissionMode:this.mapModeToPermissionMode(),...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(Y)=>{return this.requestPermission(Y)}}};if(await y(this.agent.chatStream(H,X,{pendingInputOnly:J.pendingInputOnly,goalContinuationOnly:J.goalContinuationOnly}),async(Y)=>{switch(Y.kind){case"content_delta":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:Y.delta}});break;case"tool_start":{let Z=Y.toolCall,$="function"in Z?Z.function.name:Z.type,G=this.mapToolKind(Y.toolKind),V=`Executing ${$}`;if($==="Task"&&"function"in Z)try{let U=JSON.parse(Z.function.arguments),D=U.resume_from??U.resume;if(typeof D==="string")V=`Resuming ${String(U.subagent_type||"subagent")} from ${D}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z.id,status:"in_progress",title:V,content:[],kind:G});break}case"tool_result":{let{toolCall:Z,result:$}=Y,G=[],V=$.metadata;if(V?.kind==="edit"&&typeof V.file_path==="string"&&typeof V.oldContent==="string"&&(typeof V.newContent==="string"||V.newContent===void 0))G.push({type:"diff",path:V.file_path,oldText:V.oldContent,newText:V.newContent??null});else{let D="function"in Z?Z.function.name:Z.type,_=T(A(D,$));G.push({type:"content",content:{type:"text",text:_}})}let U=$.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Z.id,status:U,content:G});break}case"task_update":this.sendPlanUpdate(Y.tasks);break;case"steering_applied":break;case"follow_up_started":for(let Z of Y.messages){if(!Z.recovered||Z.persisted)continue;for(let $ of O(Z.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:$})}if(Y.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${Y.recovered} queued instruction${Y.recovered===1?"":"s"} recovered after restart]
|
|
2
|
-
`}});break;case"goal_updated":if(Y.goal&&Y.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${Y.goal.status}: ${Y.goal.objective}]
|
|
3
|
-
`}});break;case"goal_continuation_started":break;default:break}}),this.messages=[...X.messages],Q.signal.aborted)return{stopReason:"cancelled"};return{stopReason:"end_turn"}}catch(X){if(Q.signal.aborted||X instanceof Error&&X.name==="AbortError")return{stopReason:"cancelled"};throw W.error(`[AcpSession ${this.id}] Prompt error:`,X),X}finally{if(this.pendingPrompt===Q){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.schedulePendingResume()}}}schedulePendingResume(){if(this.destroyed||this.connection.signal.aborted)return;this.pendingResumeRequested=!0,queueMicrotask(()=>{this.resumePendingIfIdle()})}async resumePendingIfIdle(){if(this.destroyed||this.connection.signal.aborted)return;if(this.pendingPrompt||!this.runtime||!this.agent)return;let z=this.runtime.getPendingSteeringCount()>0,H=(z?null:await this.runtime.getGoal())?.status==="active";if(!z&&!H){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:z,goalContinuationOnly:H}).catch((Q)=>{W.error(`[AcpSession ${this.id}] Failed to resume pending input:`,Q)})}cancel(){if(W.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingResumeRequested=!1,this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,W.info(`[AcpSession ${this.id}] Cancelled successfully`);else W.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let J=["default","auto-edit","yolo","plan"];this.mode=J.includes(z)?z:"default",W.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){switch(this.mode){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(W.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");await this.agent.switchModel(z)}async destroy(){if(this.destroyed)return;if(this.destroyed=!0,this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let z=this.agent,J=this.runtime;this.agent=null,this.runtime=null;let H,Q=async(X)=>{try{await X()}catch(Y){H??=Y}};if(await Q(()=>this.cancel()),z)await Q(()=>z.destroy());if(J)await Q(()=>J.dispose());if(await Q(()=>B.destroySession(this.id)),W.debug(`[AcpSession ${this.id}] Destroyed`),H!==void 0)throw H}resolvePrompt(z){let J=[];for(let H of z)if(H.type==="text")J.push(H.text);else if(H.type==="image")J.push(`[Image: ${H.mimeType}]`);else if(H.type==="resource"){let Q=H.resource;if("text"in Q)J.push(`<file path="${Q.uri}">
|
|
4
|
-
${Q.text}
|
|
5
|
-
</file>`)}else if(H.type==="resource_link")J.push(`[Resource: ${H.uri}]`);return J.join(`
|
|
6
|
-
`)}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted}async sendUpdateAndWait(z){if(!this.canSendUpdates())return!1;return await this.connection.sessionUpdate({sessionId:this.id,update:z}),this.canSendUpdates()}sendUpdate(z){if(!this.canSendUpdates())return;let J={sessionId:this.id,update:z};this.connection.sessionUpdate(J).catch((H)=>{W.warn(`[AcpSession ${this.id}] Failed to send update:`,H)})}sendPlanUpdate(z){let J=z.map((H)=>({content:H.subject,priority:H.priority,status:H.status}));W.debug(`[AcpSession ${this.id}] Sending plan update with ${J.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:J})}async requestPermission(z){let J=this.pendingPrompt?.signal;if(z.type==="askUserQuestion")return this.requestUserQuestions(z,J);let H=z.kind?.toLowerCase()||"execute";if(this.shouldAutoApprove(H))return W.debug(`[AcpSession ${this.id}] Auto-approving ${H} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(H==="write"||H==="execute"))return W.debug(`[AcpSession ${this.id}] Rejecting ${H} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Q=R(),X=[];if(z.message)X.push({type:"content",content:{type:"text",text:z.message}});if(z.risks&&z.risks.length>0)X.push({type:"content",content:{type:"text",text:`Risks:
|
|
7
|
-
- ${z.risks.join(`
|
|
8
|
-
- `)}`}});let Y=this.mapToolKind(H),Z={sessionId:this.id,options:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:Q,status:"pending",title:z.title||"Permission Required",content:X,kind:Y}},$=await this.waitForClientInteraction(this.connection.requestPermission(Z),J);if(!$)return{approved:!1,reason:N};let G=$.outcome;if(G.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let V=G.optionId;if(V==="allow_always")return{approved:!0,scope:"project"};if(V==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let U=V==="allow_once";return{approved:U,scope:"once",reason:U?void 0:"User denied the operation"}}catch(Q){return W.warn(`[AcpSession ${this.id}] Permission request failed:`,Q),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(z,J){let H=z.questions??[];if(H.length===0)return{approved:!1,reason:"No structured questions were provided"};if(H.some((X)=>X.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let Q={};try{for(let[X,Y]of H.entries()){let Z=Y.options.map((U,D)=>`answer:${X}:${D}`),$=`answer:${X}:cancel`,G=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Y.options.map((U,D)=>({optionId:Z[D],name:U.label,kind:"allow_once"})),{optionId:$,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:R(),status:"pending",title:Y.header,kind:"think",content:[{type:"content",content:{type:"text",text:[Y.question,...Y.options.map((U)=>`${U.label}: ${U.description}`)].join(`
|
|
9
|
-
`)}}]}}),J);if(!G)return{approved:!1,reason:N};if(G.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let V=Z.indexOf(G.outcome.optionId);if(V<0)return{approved:!1,reason:"User cancelled the question prompt"};Q[Y.header]=Y.options[V].label}return{approved:!0,answers:Q}}catch(X){return W.warn(`[AcpSession ${this.id}] Question request failed:`,X),{approved:!1,reason:"Question request failed"}}}async waitForClientInteraction(z,J){if(!J)return z;if(J.aborted)return;return new Promise((H,Q)=>{let X=!1,Y=($)=>{if(X)return;X=!0,J.removeEventListener("abort",Z),$()},Z=()=>Y(()=>H(void 0));if(J.addEventListener("abort",Z,{once:!0}),J.aborted)Z();z.then(($)=>Y(()=>H($)),($)=>Y(()=>Q($)))})}mapToolKind(z){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[z||""]||"other"}}var F=w("Agent");class P{connection;sessions=new Map;sessionLoadQueues=new Map;clientCapabilities;destroyed=!1;constructor(z){this.connection=z}async initialize(z){return F.info("[BladeAgent] Initializing ACP connection"),F.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,{protocolVersion:m,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){this.assertNotDestroyed();let J=C("acp"),H=z.cwd||I(),Q=z._meta?.["blade/taskIsolation"],X=Q==="local"||Q==="worktree"?Q:void 0,Y=z._meta?.["blade/taskPrompt"],Z=X?await v.createSessionTask({sessionId:J,prompt:typeof Y==="string"&&Y.trim()?Y:"ACP task session",sourceProjectPath:H,isolation:X}):void 0,$=Z?.metadata.projectPath??H;F.info(`[BladeAgent] Creating new session: ${J}`),F.debug(`[BladeAgent] Session cwd: ${$}`);let G=new L(J,$,this.connection,this.clientCapabilities,{mcpServers:z.mcpServers,...Z?.taskWorktree?{taskWorktree:Z.taskWorktree}:{},...Z?.metadata.taskIsolation?{taskIsolation:Z.metadata.taskIsolation}:{}});try{await G.initialize(),this.assertNotDestroyed()}catch(V){throw await G.destroy().catch(()=>{return}),V}return this.sessions.set(J,G),F.info(`[BladeAgent] Session ${J} created, scheduling available commands update`),G.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(J,Z?.metadata)}async unstable_listSessions(z){if(z.cwd!=null&&!S.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let J=await j.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:J.sessions.map((H)=>({sessionId:H.sessionId,cwd:H.projectPath,title:H.title??null,updatedAt:H.lastMessageTime,_meta:{"blade/taskStatus":H.taskStatus,...H.taskStatusReason?{"blade/taskStatusReason":H.taskStatusReason}:{},...H.taskStartedAt?{"blade/taskStartedAt":H.taskStartedAt}:{},...H.taskCompletedAt?{"blade/taskCompletedAt":H.taskCompletedAt}:{},...H.taskIsolation?{"blade/taskIsolation":H.taskIsolation}:{},...H.taskSourceProjectPath?{"blade/taskSourceProjectPath":H.taskSourceProjectPath}:{},...H.taskWorktreeBranch?{"blade/taskWorktreeBranch":H.taskWorktreeBranch}:{},...H.taskBaseCommit?{"blade/taskBaseCommit":H.taskBaseCommit}:{},...H.taskDiffStat?{"blade/taskDiffStat":H.taskDiffStat}:{},...H.taskQueuePosition?{"blade/taskQueuePosition":H.taskQueuePosition}:{},...H.taskQueueDepth!==void 0?{"blade/taskQueueDepth":H.taskQueueDepth}:{},...H.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":H.taskConcurrencyLimit}:{}}})),nextCursor:J.nextCursor}}async unstable_forkSession(z){if(this.assertNotDestroyed(),!S.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let J=await j.forkSession(z.sessionId,{sourceProjectPath:z.cwd,targetProjectPath:z.cwd});this.assertNotDestroyed();let H=new L(J.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:J.messages,mcpServers:z.mcpServers});try{await H.initialize(),this.assertNotDestroyed()}catch(Q){throw await H.destroy().catch(()=>{return}),Q}return this.sessions.set(J.sessionId,H),H.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(J.sessionId)}async loadSession(z){this.assertNotDestroyed(),F.info(`[BladeAgent] Loading session: ${z.sessionId}`);let H=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),Q=H.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Q);try{return await H}finally{if(this.sessionLoadQueues.get(z.sessionId)===Q)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){this.assertNotDestroyed();let J=this.sessions.get(z.sessionId);if(J)try{await J.destroy()}finally{if(this.sessions.get(z.sessionId)===J)this.sessions.delete(z.sessionId)}let H=await j.loadSession(z.sessionId,z.cwd),Q=new L(z.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:H,mcpServers:z.mcpServers});try{await Q.initialize(),await Q.replayHistory(),this.assertNotDestroyed()}catch(X){throw await Q.destroy().catch(()=>{return}),X}return this.sessions.set(z.sessionId,Q),Q.sendAvailableCommandsDelayed(),this.buildSessionSetup()}buildChildSessionResponse(z,J){return{sessionId:z,...this.buildSessionSetup(),...J?{_meta:{"blade/taskIsolation":J.taskIsolation,"blade/taskSourceProjectPath":J.taskSourceProjectPath,"blade/taskProjectPath":J.projectPath,...J.taskWorktreeBranch?{"blade/taskWorktreeBranch":J.taskWorktreeBranch}:{},...J.taskBaseCommit?{"blade/taskBaseCommit":J.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}buildSessionSetup(){let z=k(),J=z?.models||[],H=z?.currentModelId||J[0]?.id,Q=J.map((Y)=>({modelId:Y.id,name:u(Y),description:`${Y.provider}/${Y.model}`}));return{modes:{availableModes:[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],currentModeId:"default"},models:Q.length>0?{availableModels:Q,currentModelId:H}:void 0}}async prompt(z){let J=this.sessions.get(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);return J.prompt(z)}async cancel(z){F.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let J=this.sessions.get(z.sessionId);if(J)F.info("[BladeAgent] Found session, calling session.cancel()"),J.cancel();else F.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){F.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let J=this.sessions.get(z.sessionId);if(J)await J.setMode(z.modeId);return{}}async unstable_setSessionModel(z){F.info(`[BladeAgent] Setting session model: ${z.modelId}`);let J=this.sessions.get(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);return await J.setModel(z.modelId),{}}async destroy(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let z;for(let J of this.sessions.values())try{await J.destroy()}catch(H){z??=H}this.sessions.clear();try{await c.getInstance().disconnectAll()}catch(J){z??=J}if(z!==void 0)throw z}}async function Nz(){let z=i.toWeb(process.stdout),J=l.toWeb(process.stdin),H=E.ndJsonStream(z,J);await new E.AgentSideConnection((X)=>new P(X),H).closed}export{Nz as runAcpIntegration};
|
package/dist/chunk-6spmzx13.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{q as A,r as E,s as N,t as f}from"./chunk-zj3q4btp.js";import{u as D}from"./chunk-97qxd4yb.js";import{w as L,x as _,y as x}from"./chunk-zjks0ncc.js";import{z as B}from"./chunk-t9cqscfq.js";import{R as $,W as b}from"./chunk-kf43f8sy.js";import"./chunk-ar5564sf.js";import"./chunk-2c69g6t9.js";import"./chunk-mqqajem9.js";import"./chunk-yewg510f.js";import"./chunk-jc7k8pfn.js";import"./chunk-hqtskyc1.js";import"./chunk-sva5bdgz.js";import{kb as Z}from"./chunk-m0ded6ky.js";import"./chunk-5sccs44n.js";import"./chunk-b922cq7k.js";import"./chunk-1m63zddw.js";import"./chunk-7bqkkjxf.js";import{Rb as Y,Sb as T}from"./chunk-kjc2aqww.js";import"./chunk-d7nrqg5b.js";import"./chunk-eyypmc9m.js";import"./chunk-zsyff0ky.js";import"./chunk-be7qz4cv.js";import h from"yargs";import{hideBin as R}from"yargs/helpers";var w=new Set(Object.values(Y));function X(k){if(k&&w.has(k))return k;return}function M(k){return k.command("* [message]","Print response and exit (useful for pipes)",(F)=>F.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(F)=>{if(!F.p)return;let q=await O(F);process.exit(q)})}async function O(k,F=process){let q;try{await A();let J=await E({message:k.message,_:k._,defaultMessage:"Hello"}),G=await N(J);if(G.mode==="output"){if(G.content)F.stdout.write(`${G.content}
|
|
2
|
-
`);return G.exitCode??0}let Q=G.content,{sessionId:K,messages:U}=await f({sessionId:k.sessionId,continue:k.continue,resume:k.resume,forkSession:k.forkSession,fallbackSessionPrefix:"print"});q=await $.create({sessionId:K,workspaceRoot:T(),modelId:k.model,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig,agents:k.agents?B(k.agents):void 0});let V=await b.createWithRuntime(q,{sessionId:K,systemPrompt:k.systemPrompt,appendSystemPrompt:k.appendSystemPrompt,maxTurns:k.maxTurns,modelId:k.model,permissionMode:X(k.permissionMode),toolWhitelist:k.allowedTools,toolBlacklist:k.disallowedTools,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig}),H=(await Z(V.chatStream(Q,{messages:[...U],userId:"cli-user",sessionId:K,workspaceRoot:T(),permissionMode:X(k.permissionMode)}))).finalMessage||"";if(k.outputFormat==="json")F.stdout.write(`${JSON.stringify({response:H,input:Q,model:k.model,timestamp:new Date().toISOString()},null,2)}
|
|
3
|
-
`);else if(k.outputFormat==="stream-json")F.stdout.write(`${JSON.stringify({type:"response",content:H})}
|
|
4
|
-
`);else F.stdout.write(`${H}
|
|
5
|
-
`);return 0}catch(J){return F.stderr.write(`Error: ${J instanceof Error?J.message:"未知错误"}
|
|
6
|
-
`),1}finally{await q?.dispose()}}async function d(){if(process.argv.slice(2).findIndex((q)=>q==="--print"||q==="-p")===-1)return!1;try{let{print:q,"output-format":J,"include-partial-messages":G,"input-format":Q,"system-prompt":K,"append-system-prompt":U,"max-turns":V,...W}=D,H=h(R(process.argv)).scriptName("blade").strict(!1).options(W).middleware([_,L,x]);return M(H),await H.parse(),!0}catch(q){console.error(`Print mode error: ${q instanceof Error?q.message:"未知错误"}`),process.exit(1)}}export{O as runPrint,d as handlePrintMode};
|
package/dist/chunk-724djh7r.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Zb as a}from"./chunk-d7nrqg5b.js";import"./chunk-eyypmc9m.js";import"./chunk-zsyff0ky.js";import"./chunk-be7qz4cv.js";export{a as createChatServiceAsync};
|
package/dist/chunk-804j7say.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as y,b as A,c as C,d as D}from"./chunk-qwn46cd6.js";import"./chunk-vxpdjtqc.js";import"./chunk-9cr3jexy.js";import"./chunk-kf43f8sy.js";import"./chunk-ar5564sf.js";import"./chunk-2c69g6t9.js";import"./chunk-mqqajem9.js";import{Aa as q}from"./chunk-yewg510f.js";import"./chunk-jc7k8pfn.js";import"./chunk-hqtskyc1.js";import"./chunk-sva5bdgz.js";import"./chunk-m0ded6ky.js";import"./chunk-5sccs44n.js";import"./chunk-b922cq7k.js";import"./chunk-1m63zddw.js";import"./chunk-7bqkkjxf.js";import"./chunk-kjc2aqww.js";import"./chunk-d7nrqg5b.js";import"./chunk-eyypmc9m.js";import"./chunk-zsyff0ky.js";import"./chunk-be7qz4cv.js";import H from"chalk";var R={command:"serve",describe:"Start a headless Blade server (no browser)",builder:y,handler:async(E)=>{let f=A(E);if(await q(),!process.env.BLADE_SERVER_PASSWORD)console.log(H.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let b=await D.listenAsync(f);if(console.log(`Blade server listening on http://${b.hostname}:${b.port}`),f.hostname==="0.0.0.0"){let F=C();for(let G of F)console.log(` Network: http://${G}:${b.port}`)}await new Promise(()=>{}),await b.stop()}};export{R as serveCommand};
|
package/dist/chunk-8yk5w2ks.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Ta as a,Ua as b,Va as c,Wa as d,Xa as e,Ya as f}from"./chunk-sva5bdgz.js";import"./chunk-be7qz4cv.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
package/dist/chunk-9cr3jexy.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{M as i,N as r}from"./chunk-kf43f8sy.js";import a from"node:path";function n(e){let t=e.replace(/\s+/g," ").trim();return t.length<=72?t:`${t.slice(0,69)}...`}function c(e){let t=e.replace(/\s+/g," ").trim();return t.length<=500?t:`${t.slice(0,497)}...`}function m(e){return`task/${e.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class k{static async createSessionTask(e){if(!e.prompt.trim())throw Error("Task prompt must not be blank");if(!a.isAbsolute(e.sourceProjectPath))throw Error("Task source project path must be absolute");let t=a.resolve(e.sourceProjectPath),s;try{return s=e.isolation==="worktree"?await r.enter({sessionId:e.sessionId,workspaceRoot:t,name:m(e.sessionId)}):void 0,{metadata:await i.createSessionMetadata(e.sessionId,s?.workspaceRoot??t,{title:e.title?.trim()||n(e.prompt),taskPromptSummary:c(e.prompt),taskIsolation:e.isolation,taskSourceProjectPath:t,taskWorktree:s}),taskWorktree:s}}catch(o){if(s)await r.exit({sessionId:e.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw o}}}
|
|
2
|
-
export{k as p};
|
package/dist/chunk-b922cq7k.js
DELETED
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
import{Gb as h,Ib as X,Lb as d}from"./chunk-1m63zddw.js";import{Sb as n}from"./chunk-kjc2aqww.js";import{bc as s}from"./chunk-eyypmc9m.js";import{oc as B}from"./chunk-be7qz4cv.js";import{nanoid as V}from"nanoid";var g;((G)=>{G.PreToolUse="PreToolUse";G.PostToolUse="PostToolUse";G.PostToolUseFailure="PostToolUseFailure";G.PermissionRequest="PermissionRequest";G.UserPromptSubmit="UserPromptSubmit";G.SessionStart="SessionStart";G.SessionEnd="SessionEnd";G.Stop="Stop";G.SubagentStop="SubagentStop";G.Notification="Notification";G.Compaction="Compaction"})(g||={});var T;((Q)=>{Q.Approve="approve";Q.Block="block";Q.Async="async"})(T||={});var N;((Q)=>{Q.Allow="allow";Q.Deny="deny";Q.Ask="ask"})(N||={});var y={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 M(O,S){return{...O,...S,PreToolUse:S.PreToolUse??O.PreToolUse,PostToolUse:S.PostToolUse??O.PostToolUse,PostToolUseFailure:S.PostToolUseFailure??O.PostToolUseFailure,PermissionRequest:S.PermissionRequest??O.PermissionRequest,UserPromptSubmit:S.UserPromptSubmit??O.UserPromptSubmit,SessionStart:S.SessionStart??O.SessionStart,SessionEnd:S.SessionEnd??O.SessionEnd,Stop:S.Stop??O.Stop,SubagentStop:S.SubagentStop??O.SubagentStop,Notification:S.Notification??O.Notification,Compaction:S.Compaction??O.Compaction}}function k(){let O={};if(process.env.BLADE_DISABLE_HOOKS==="true")O.enabled=!1;if(process.env.BLADE_HOOK_TIMEOUT){let S=parseInt(process.env.BLADE_HOOK_TIMEOUT,10);if(!isNaN(S)&&S>0)O.defaultTimeout=S}return O}class C{executedHooks=new Map;canExecute(O,S){if(!this.executedHooks.has(O))this.executedHooks.set(O,new Set);if(this.executedHooks.get(O).has(S))return console.warn(`[HookGuard] Hook ${S} for tool ${O} already executed, skipping`),!1;return!0}markExecuted(O,S){let q=this.executedHooks.get(O);if(q)q.add(S)}cleanup(O){this.executedHooks.delete(O)}cleanupAll(){this.executedHooks.clear()}}var r=X.Object({hookEventName:X.Literal("PreToolUse"),permissionDecision:X.Optional(X.Enum(N)),permissionDecisionReason:X.Optional(X.String()),updatedInput:X.Optional(X.Record(X.String(),X.Unknown()))}),o=X.Object({hookEventName:X.Literal("PostToolUse"),additionalContext:X.Optional(X.String()),updatedOutput:X.Optional(X.Unknown())}),e=X.Object({hookEventName:X.Literal("Stop"),continue:X.Optional(X.Boolean()),continueReason:X.Optional(X.String())}),t=X.Object({hookEventName:X.Literal("SubagentStop"),continue:X.Optional(X.Boolean()),continueReason:X.Optional(X.String()),additionalContext:X.Optional(X.String())}),OO=X.Object({hookEventName:X.Literal("PermissionRequest"),permissionDecision:X.Optional(d(["approve","deny","ask"])),permissionDecisionReason:X.Optional(X.String())}),SO=X.Object({hookEventName:X.Literal("UserPromptSubmit"),updatedPrompt:X.Optional(X.String()),contextInjection:X.Optional(X.String())}),qO=X.Object({hookEventName:X.Literal("SessionStart"),env:X.Optional(X.Record(X.String(),X.String()))}),QO=X.Object({hookEventName:X.Literal("Compaction"),blockCompaction:X.Optional(X.Boolean()),blockReason:X.Optional(X.String())}),YO=X.Object({decision:X.Optional(X.Object({behavior:X.Enum(T)})),systemMessage:X.Optional(X.String()),hookSpecificOutput:X.Optional(X.Union([r,o,e,t,OO,SO,qO,QO])),suppressOutput:X.Optional(X.Boolean())});function p(O){return h(YO,O)}class w{parse(O,S,q){if(O.timedOut){let Y=q?.timeoutBehavior||"ignore",Z="Hook timeout";if(Y==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:S};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:S};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:S}}let Q=this.tryParseJSON(O.stdout);if(Q){let Y=p(Q);if(!Y.success){let W="error"in Y?Y.error.message:"Unknown validation error",$=q?.failureBehavior||"ignore",R=`Invalid hook output JSON: ${W}`;if($==="deny")return{success:!1,blocking:!0,error:R,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:S};else if($==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${R}. Continue?`,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:S};else return{success:!1,blocking:!1,warning:R,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:S}}let Z=Y.data;if(Z.decision?.behavior==="block")return{success:!1,blocking:!0,error:Z.systemMessage||"Hook blocked execution",output:Z,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:S};if(Z.decision?.behavior==="async")return{success:!0,output:Z,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:S};return{success:!0,output:Z,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:S}}return this.parseByExitCode(O,S,q)}parseByExitCode(O,S,q){let Q=O.exitCode;switch(Q){case 0:return{success:!0,stdout:O.stdout,stderr:O.stderr,exitCode:Q,hook:S};case 2:return{success:!1,blocking:!0,error:O.stderr||O.stdout||"Hook returned exit code 2",stdout:O.stdout,stderr:O.stderr,exitCode:Q,hook:S};case 124:{let Y=q?.timeoutBehavior||"ignore",Z="Hook timeout";if(Y==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:Q,hook:S};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:O.stdout,stderr:O.stderr,exitCode:Q,hook:S};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:Q,hook:S}}default:{let Y=q?.failureBehavior||"ignore",Z=O.stderr||O.stdout||`Hook failed with exit code ${Q}`;if(Y==="deny")return{success:!1,blocking:!0,error:Z,stdout:O.stdout,stderr:O.stderr,exitCode:Q,hook:S};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${Z}. Continue?`,stdout:O.stdout,stderr:O.stderr,exitCode:Q,hook:S};else return{success:!1,blocking:!1,warning:Z,stdout:O.stdout,stderr:O.stderr,exitCode:Q,hook:S}}}}tryParseJSON(O){try{let S=O.trim();if(!S)return null;let q=S.match(/^\s*(\{[\s\S]*\})\s*$/);if(!q)return null;return JSON.parse(q[1])}catch{return null}}}import{spawn as u}from"node:child_process";var ZO=500;function WO(O){return new Promise((S)=>setTimeout(S,O))}function x(O){return O&&typeof O==="object"&&"code"in O?String(O.code):void 0}function $O(O,S){return new Promise((q)=>{let Q=["/PID",String(O),"/T"];if(S)Q.push("/F");let Y=u("taskkill",Q,{stdio:"ignore",windowsHide:!0}),Z=!1,W=($)=>{if(Z)return;Z=!0,q($)};Y.once("error",()=>W(!1)),Y.once("close",($)=>W($===0))})}class a{child;state="owned";terminationPromise;terminationResult;platform;gracePeriodMs;killProcess;taskkill;wait;constructor(O,S={}){this.child=O;this.platform=S.platform??process.platform,this.gracePeriodMs=S.gracePeriodMs??ZO,this.killProcess=S.killProcess??process.kill.bind(process),this.taskkill=S.taskkill??$O,this.wait=S.wait??WO;let q=()=>{if(this.state==="owned")this.state="released"};O.once("close",q),O.once("error",q)}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((O)=>{return this.state="released",this.terminationResult=O,O}),this.terminationPromise}async terminateOwnedTree(){let O=this.child.pid;if(!O)return{success:!1,alreadyExited:!0,forced:!1};if(this.platform==="win32"){let Q=await this.taskkill(O,!1);await this.wait(this.gracePeriodMs);let Y=await this.taskkill(O,!0);if(!Q&&!Y)return{success:this.signalDirectChild("SIGKILL"),alreadyExited:!1,forced:!0};return{success:!0,alreadyExited:!1,forced:!0}}let S=this.signalPosixTree(O,"SIGTERM");await this.wait(this.gracePeriodMs);let q=this.signalPosixTree(O,"SIGKILL");return{success:S||q,alreadyExited:!1,forced:q}}signalPosixTree(O,S){if(O<=1||O===process.pid)return this.signalDirectChild(S);try{return this.killProcess(-O,S)}catch(q){if(x(q)==="ESRCH")return!0;return this.signalDirectChild(S)}}signalDirectChild(O){try{return this.child.kill(O)}catch(S){return x(S)==="ESRCH"}}}function l(O,S,q={}){let Q=u(O,S,{...q,detached:process.platform==="win32"?q.detached:!0,windowsHide:q.windowsHide??!0});return{child:Q,processTree:new a(Q)}}class E{content="";maxSize;constructor(O){this.maxSize=O}append(O){if(this.content.length<this.maxSize){let S=this.maxSize-this.content.length;this.content+=O.substring(0,S)}}getContent(){return this.content}isFull(){return this.content.length>=this.maxSize}}class I{MAX_STDOUT_SIZE=1048576;MAX_STDERR_SIZE=1048576;MAX_INPUT_SIZE=102400;async execute(O,S,q,Q){let Y=JSON.stringify(S);if(Y.length>this.MAX_INPUT_SIZE)throw Error(`Hook input too large: ${Y.length} bytes (max ${this.MAX_INPUT_SIZE})`);let Z=this.createSafeEnv(S),{child:W,processTree:$}=l(O,[],{shell:!0,env:Z,cwd:q.projectDir}),R=new E(this.MAX_STDOUT_SIZE),J=new E(this.MAX_STDERR_SIZE);W.stdout?.setEncoding("utf8"),W.stderr?.setEncoding("utf8"),W.stdout?.on("data",(F)=>{R.append(F)}),W.stderr?.on("data",(F)=>{J.append(F)});try{W.stdin?.write(Y),W.stdin?.end()}catch(F){throw await $.terminate(),Error(`Failed to write hook input: ${F}`)}return new Promise((F,G)=>{let K=!1,z=!1,D,L=()=>{return D??=$.terminate(),D},j=null,A=()=>{if(j&&q.abortSignal)q.abortSignal.removeEventListener("abort",j),j=null},U=setTimeout(()=>{K=!0,L()},Q);if(W.on("close",async(b)=>{if(z)return;if(z=!0,clearTimeout(U),A(),K)await L();F({stdout:R.getContent(),stderr:J.getContent(),exitCode:K?124:b??1,timedOut:K})}),W.on("error",(b)=>{if(z)return;z=!0,clearTimeout(U),A(),G(b)}),q.abortSignal){if(j=()=>{if(z)return;z=!0,clearTimeout(U),A(),L().then(()=>{F({stdout:R.getContent(),stderr:"Hook cancelled by abort signal",exitCode:1,timedOut:!1})})},q.abortSignal.addEventListener("abort",j),q.abortSignal.aborted)j()}})}createSafeEnv(O){return{BLADE_PROJECT_DIR:O.project_dir,BLADE_SESSION_ID:O.session_id,BLADE_HOOK_EVENT:O.hook_event_name,BLADE_TOOL_NAME:"tool_name"in O?O.tool_name:"",BLADE_TOOL_USE_ID:"tool_use_id"in O?O.tool_use_id:"",PATH:process.env.PATH||"",HOME:process.env.HOME||"",USER:process.env.USER||"",SHELL:process.env.SHELL||"/bin/sh"}}}class _ extends Error{constructor(O){super(O);this.name="HttpHookSecurityError"}}function i(O,S={}){let q;try{q=new URL(O)}catch{throw new _(`Invalid URL: ${O}`)}if(q.protocol!=="https:"&&q.protocol!=="http:")throw new _(`Only http/https supported, got: ${q.protocol}`);let Q=q.hostname.toLowerCase();if(RO(Q,S.allowedHosts))return;if(q.protocol==="http:"&&!S.allowHttp)throw new _(`HTTP (non-TLS) blocked for ${Q}; use https:// or add to allowedHosts`);if(XO(Q)&&!S.allowLoopback)throw new _(`Loopback address blocked: ${Q}; enable policy.allowLoopback or add to allowedHosts`);if(JO(Q)&&!S.allowPrivateRanges)throw new _(`Private/link-local address blocked: ${Q}; enable policy.allowPrivateRanges or add to allowedHosts`)}function RO(O,S){if(!S||S.length===0)return!1;return S.some((q)=>{let Q=q.toLowerCase();if(Q===O)return!0;if(Q.startsWith("*.")){let Y=Q.slice(1);return O.endsWith(Y)&&O.length>Y.length}return!1})}function XO(O){if(O==="localhost")return!0;if(O==="::1"||O==="[::1]")return!0;if(/^127\.\d+\.\d+\.\d+$/.test(O))return!0;return!1}function JO(O){let S=O.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(!S)return!1;let[q,Q]=S.slice(1).map(Number);if(q===10)return!0;if(q===172&&Q>=16&&Q<=31)return!0;if(q===192&&Q===168)return!0;if(q===169&&Q===254)return!0;return!1}function c(O){if(!O)return{};let S={};for(let[q,Q]of Object.entries(O))S[q]=Q.replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,(Y,Z)=>{return process.env[Z]??`\${${Z}}`});return S}var zO=s("Execution"),FO={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 f{processExecutor=new I;outputParser=new w;chatServiceCache=new Map;async executePreToolHooks(O,S,q){if(O.length===0)return{decision:"allow"};let Q="tool_input"in S?S.tool_input:{},Y=[];for(let Z of O)try{let W={...S,...Q&&{tool_input:Q}},$=await this.executeHook(Z,W,q);if(!$.success){if($.blocking)return{decision:"deny",reason:$.error};if($.needsConfirmation)return{decision:"ask",reason:$.warning||$.error};if($.warning)Y.push($.warning);continue}let R=$.output?.hookSpecificOutput;if(R&&"permissionDecision"in R){switch(R.permissionDecision){case"deny":return{decision:"deny",reason:R.permissionDecisionReason};case"ask":return{decision:"ask",reason:R.permissionDecisionReason};case"allow":break}if("updatedInput"in R&&R.updatedInput)Q={...Q,...R.updatedInput}}}catch(W){let $=W instanceof Error?W.message:String(W);if(Y.push(`Hook failed: ${$}`),q.config.failureBehavior==="deny")return{decision:"deny",reason:$};else if(q.config.failureBehavior==="ask")return{decision:"ask",reason:`Hook failed: ${$}. Continue?`}}return{decision:"allow",modifiedInput:Q,warning:Y.length>0?Y.join(`
|
|
2
|
-
`):void 0}}async executePostToolHooks(O,S,q){if(O.length===0)return{};let Q=q.config.maxConcurrentHooks||5,Y=await this.executeHooksConcurrently(O,S,q,Q),Z=[],W=void 0,$=[];for(let R of Y){if(!R.success&&R.warning){$.push(R.warning);continue}let J=R.output?.hookSpecificOutput;if(J&&"additionalContext"in J){if(J.additionalContext)Z.push(J.additionalContext);if("updatedOutput"in J&&J.updatedOutput!==void 0)W=J.updatedOutput}}return{additionalContext:Z.length>0?Z.join(`
|
|
3
|
-
|
|
4
|
-
`):void 0,modifiedOutput:W,warning:$.length>0?$.join(`
|
|
5
|
-
`):void 0}}async executeStopHooks(O,S,q){if(O.length===0)return{shouldStop:!0};let Q=[];for(let Y of O)try{let Z=await this.executeHook(Y,S,q);if(!Z.success){if(Z.warning)Q.push(Z.warning);continue}let W=Z.output?.hookSpecificOutput;if(W&&"continue"in W&&W.continue===!1)return{shouldStop:!1,continueReason:W.continueReason,warning:Q.length>0?Q.join(`
|
|
6
|
-
`):void 0}}catch(Z){let W=Z instanceof Error?Z.message:String(Z);Q.push(`Hook failed: ${W}`)}return{shouldStop:!0,warning:Q.length>0?Q.join(`
|
|
7
|
-
`):void 0}}async executeSubagentStopHooks(O,S,q){if(O.length===0)return{shouldStop:!0};let Q=[],Y=[];for(let Z of O)try{let W=await this.executeHook(Z,S,q);if(!W.success){if(W.warning)Q.push(W.warning);continue}let $=W.output?.hookSpecificOutput;if($&&"continue"in $){if($.continue===!1)return{shouldStop:!1,continueReason:$.continueReason,warning:Q.length>0?Q.join(`
|
|
8
|
-
`):void 0};if("additionalContext"in $&&$.additionalContext)Y.push($.additionalContext)}}catch(W){let $=W instanceof Error?W.message:String(W);Q.push(`Hook failed: ${$}`)}return{shouldStop:!0,additionalContext:Y.length>0?Y.join(`
|
|
9
|
-
|
|
10
|
-
`):void 0,warning:Q.length>0?Q.join(`
|
|
11
|
-
`):void 0}}async executePermissionRequestHooks(O,S,q){if(O.length===0)return{decision:"ask"};let Q=[];for(let Y of O)try{let Z=await this.executeHook(Y,S,q);if(!Z.success){if(Z.warning)Q.push(Z.warning);continue}let W=Z.output?.hookSpecificOutput;if(W&&"permissionDecision"in W){let $=W.permissionDecision;if($==="approve"||$==="deny")return{decision:$,reason:W.permissionDecisionReason,warning:Q.length>0?Q.join(`
|
|
12
|
-
`):void 0}}}catch(Z){let W=Z instanceof Error?Z.message:String(Z);Q.push(`Hook failed: ${W}`)}return{decision:"ask",warning:Q.length>0?Q.join(`
|
|
13
|
-
`):void 0}}async executeUserPromptSubmitHooks(O,S,q){if(O.length===0)return{proceed:!0};let Q=[],Y=[],Z;for(let W of O)try{let $=await this.executeHook(W,S,q);if(!$.success){if($.blocking)return{proceed:!1,warning:$.error};if($.warning)Q.push($.warning);continue}if($.stdout&&$.stdout.trim())Y.push($.stdout.trim());let R=$.output?.hookSpecificOutput;if(R&&"updatedPrompt"in R){if(R.updatedPrompt)Z=R.updatedPrompt;if(R.contextInjection)Y.push(R.contextInjection)}}catch($){let R=$ instanceof Error?$.message:String($);Q.push(`Hook failed: ${R}`)}return{proceed:!0,updatedPrompt:Z,contextInjection:Y.length>0?Y.join(`
|
|
14
|
-
|
|
15
|
-
`):void 0,warning:Q.length>0?Q.join(`
|
|
16
|
-
`):void 0}}async executeSessionStartHooks(O,S,q){if(O.length===0)return{proceed:!0};let Q=[],Y={};for(let Z of O)try{let W=await this.executeHook(Z,S,q);if(!W.success){if(W.blocking)return{proceed:!1,warning:W.error};if(W.warning)Q.push(W.warning);continue}let $=W.output?.hookSpecificOutput;if($&&"env"in $&&$.env)Object.assign(Y,$.env)}catch(W){let $=W instanceof Error?W.message:String(W);Q.push(`Hook failed: ${$}`)}return{proceed:!0,env:Object.keys(Y).length>0?Y:void 0,warning:Q.length>0?Q.join(`
|
|
17
|
-
`):void 0}}async executeSessionEndHooks(O,S,q){if(O.length===0)return{};let Q=[],Y=q.config.maxConcurrentHooks||5,Z=await this.executeHooksConcurrently(O,S,q,Y);for(let W of Z)if(!W.success&&W.warning)Q.push(W.warning);return{warning:Q.length>0?Q.join(`
|
|
18
|
-
`):void 0}}async executePostToolUseFailureHooks(O,S,q){if(O.length===0)return{};let Q=[],Y=[],Z=q.config.maxConcurrentHooks||5,W=await this.executeHooksConcurrently(O,S,q,Z);for(let $ of W){if(!$.success&&$.warning){Q.push($.warning);continue}if($.stdout&&$.stdout.trim())Y.push($.stdout.trim())}return{additionalContext:Y.length>0?Y.join(`
|
|
19
|
-
|
|
20
|
-
`):void 0,warning:Q.length>0?Q.join(`
|
|
21
|
-
`):void 0}}async executeNotificationHooks(O,S,q){let Q="message"in S?S.message:"";if(O.length===0)return{suppress:!1,message:Q};let Y=[],Z=!1,W=Q;for(let $ of O)try{let R=await this.executeHook($,S,q);if(!R.success){if(R.warning)Y.push(R.warning);continue}if(R.output?.suppressOutput){Z=!0;break}if(R.stdout&&R.stdout.trim())W=R.stdout.trim()}catch(R){let J=R instanceof Error?R.message:String(R);Y.push(`Hook failed: ${J}`)}return{suppress:Z,message:W,warning:Y.length>0?Y.join(`
|
|
22
|
-
`):void 0}}async executeCompactionHooks(O,S,q){if(O.length===0)return{blockCompaction:!1};let Q=[];for(let Y of O)try{let Z=await this.executeHook(Y,S,q);if(!Z.success){if(Z.warning)Q.push(Z.warning);continue}let W=Z.output?.hookSpecificOutput;if(W&&"blockCompaction"in W&&W.blockCompaction)return{blockCompaction:!0,blockReason:W.blockReason,warning:Q.length>0?Q.join(`
|
|
23
|
-
`):void 0}}catch(Z){let W=Z instanceof Error?Z.message:String(Z);Q.push(`Hook failed: ${W}`)}return{blockCompaction:!1,warning:Q.length>0?Q.join(`
|
|
24
|
-
`):void 0}}async executeHook(O,S,q){if(O.type==="command")return this.executeCommandHook(O,S,q);if(O.type==="prompt")return this.executePromptHook(O,S,q);if(O.type==="function")return this.executeFunctionHook(O,S,q);if(O.type==="http")return this.executeHttpHook(O,S,q);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,S,q){let Q=(O.timeout??q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,S,q,Q);return this.outputParser.parse(Y,O,{timeoutBehavior:q.config.timeoutBehavior,failureBehavior:q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,S,q){let Q=(O.timeout??q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model),Z="hook_event_name"in S?String(S.hook_event_name):"Unknown",W=this.buildPromptHookSystemMessage(O,Z),$=JSON.stringify(S,null,2),R=new AbortController,J=setTimeout(()=>R.abort(),Q),F;try{F=(await Y.chat([{role:"system",content:W},{role:"user",content:$}],void 0,R.signal)).content}catch(K){if(R.signal.aborted||K instanceof Error&&K.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:q.config.timeoutBehavior,failureBehavior:q.config.failureBehavior});throw K}finally{clearTimeout(J)}let G=this.extractJsonFromLLMResponse(F);return this.outputParser.parse({stdout:G,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:q.config.timeoutBehavior,failureBehavior:q.config.failureBehavior})}catch(Y){return zO.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,S,q){let Q=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,S,q,Q);if(Y===void 0||Y===null)return{success:!0,hook:O};let Z={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(Z,O,{timeoutBehavior:q.config.timeoutBehavior,failureBehavior:q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let Z={stdout:"",stderr:`Function hook timeout after ${Q}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse(Z,O,{timeoutBehavior:q.config.timeoutBehavior,failureBehavior:q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,S,q,Q){return new Promise((Y,Z)=>{let W=!1,$=setTimeout(()=>{if(W)return;W=!0;let J=Object.assign(Error(`Function hook timed out after ${Q}ms`),{isTimeout:!0});Z(J)},Q),R=()=>{if(W)return;W=!0,clearTimeout($),Z(Error("Function hook aborted"))};q.abortSignal?.addEventListener("abort",R,{once:!0}),Promise.resolve().then(()=>O(S,q)).then((J)=>{if(W)return;W=!0,clearTimeout($),q.abortSignal?.removeEventListener("abort",R),Y(J)},(J)=>{if(W)return;W=!0,clearTimeout($),q.abortSignal?.removeEventListener("abort",R),Z(J)})})}async executeHttpHook(O,S,q){let Q=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,Z=Math.max(1,(O.retries??0)+1);try{i(O.url,q.config.httpPolicy)}catch(J){return{success:!1,blocking:!0,error:J instanceof Error?J.message:String(J),hook:O}}let W={"Content-Type":"application/json",...c(O.headers)},$=JSON.stringify(S),R;for(let J=0;J<Z;J++){if(J>0){let z=Math.min(2**J*200,5000);await new Promise((D)=>setTimeout(D,z))}let F=new AbortController,G=setTimeout(()=>F.abort(),Q),K=()=>F.abort();q.abortSignal?.addEventListener("abort",K,{once:!0});try{let z=await fetch(O.url,{method:"POST",headers:W,body:$,redirect:"manual",signal:F.signal});if(z.status>=300&&z.status<400){R=Error(`HTTP hook received redirect (${z.status}); redirects are disabled`);continue}if(!z.ok){if(R=Error(`HTTP hook returned ${z.status} ${z.statusText}`),z.status>=400&&z.status<500)break;continue}let L={stdout:await GO(z,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(L,O,{timeoutBehavior:q.config.timeoutBehavior,failureBehavior:q.config.failureBehavior})}catch(z){let D=z.name==="AbortError"||z.code==="ABORT_ERR";if(D&&q.abortSignal?.aborted){R=Error("HTTP hook aborted by caller");break}if(D){let L={stdout:"",stderr:`HTTP hook timeout after ${Q}ms`,exitCode:124,timedOut:!0};if(J===Z-1)return this.outputParser.parse(L,O,{timeoutBehavior:q.config.timeoutBehavior,failureBehavior:q.config.failureBehavior});R=Error(`HTTP hook timeout attempt ${J+1}`);continue}R=z}finally{clearTimeout(G),q.abortSignal?.removeEventListener("abort",K)}}return{success:!1,blocking:!1,error:R?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O){let S=O||"__default__",q=this.chatServiceCache.get(S);if(q)return q;let{ensureStoreInitialized:Q,getCurrentModel:Y,getModelById:Z}=await import("./chunk-23h9grdr.js"),{createChatServiceAsync:W}=await import("./chunk-724djh7r.js"),{resolveModelConfig:$}=await import("./chunk-tzr992v4.js");await Q();let R=O?Z(O)||Y():Y();if(!R)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let J=(await import("./chunk-23h9grdr.js")).getConfig();if(!J)throw Error("PromptHook: 配置未初始化");let F=await W($(R,J,!1).chat);return this.chatServiceCache.set(S,F),F}buildPromptHookSystemMessage(O,S){let q=FO[S]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${S} 事件中被触发。
|
|
25
|
-
|
|
26
|
-
`+`## 评估指令
|
|
27
|
-
${O.prompt}
|
|
28
|
-
|
|
29
|
-
`+`## 输出格式
|
|
30
|
-
`+`必须返回一个 JSON 对象(不要包含任何其他文本):
|
|
31
|
-
`+`{
|
|
32
|
-
"decision": { "behavior": "approve" | "block" },
|
|
33
|
-
`+` "systemMessage": "可选的说明信息",
|
|
34
|
-
`+` "hookSpecificOutput": ${q}
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
`+`重要规则:
|
|
38
|
-
`+`- 只输出 JSON,不要包含 markdown 代码块或其他文本
|
|
39
|
-
`+`- 如果没有发现问题,使用 "approve"
|
|
40
|
-
`+'- 只在发现严重问题时使用 "block"'}extractJsonFromLLMResponse(O){let S=O.trim(),q=S.match(/^```(?:json)?\s*\n?([\s\S]*?)\n?\s*```$/);if(q)return q[1].trim();return S}async executeHooksConcurrently(O,S,q,Q){let Y=[],Z=new Set;for(let W of O){if(Z.size>=Q)await Promise.race(Z);let $=this.executeHook(W,S,q).catch((J)=>({success:!1,blocking:!1,error:J instanceof Error?J.message:String(J),hook:W})),R=$.then(()=>{Z.delete(R)}).catch(()=>{Z.delete(R)});Z.add(R),Y.push($)}return Promise.all(Y)}}async function GO(O,S){let q=O.body?.getReader();if(!q)return"";let Q=new TextDecoder,Y=0,Z="";while(!0){let{value:W,done:$}=await q.read();if($)break;if(Y+=W.byteLength,Y>S){try{q.cancel()}catch{}Z+=Q.decode(W.slice(0,S-(Y-W.byteLength)));break}Z+=Q.decode(W,{stream:!0})}return Z+=Q.decode(),Z}import H from"picomatch";var KO=/^([A-Za-z0-9_|]+)\((.+)\)$/;class v{matches(O,S){if(!O)return!0;if(O.tools&&S.toolName){if(!this.matchTools(O.tools,S))return!1}if(O.paths&&S.filePath){if(!this.matchPaths(O.paths,S.filePath))return!1}if(O.commands&&S.command){if(!this.matchCommands(O.commands,S.command))return!1}return!0}matchTools(O,S){if(Array.isArray(O))return O.some((q)=>this.matchToolWithParams(q,S));return this.matchToolWithParams(O,S)}matchPaths(O,S){if(Array.isArray(O))return O.some((Q)=>{return H(Q)(S)});return H(O)(S)}matchCommands(O,S){if(Array.isArray(O))return O.some((q)=>this.matchPattern(S,q));return this.matchPattern(S,O)}matchToolWithParams(O,S){let{toolName:q,command:Q,filePath:Y}=S,Z=KO.exec(O);if(!Z)return this.matchPattern(q,O);let[,W,$]=Z;if(!this.matchPattern(q,W))return!1;let R=this.getArgValue(q,Q,Y);if(!R)return!1;return this.matchGlobOrPattern(R,$)}getArgValue(O,S,q){if(O==="Bash"||O==="BashTool")return S;if(["Read","Edit","Write","Glob","Grep"].includes(O))return q;return S||q}matchGlobOrPattern(O,S){if(/[*?[\]{}!]/.test(S))try{return H(S,{bash:!0,dot:!0})(O)}catch{}if(S.endsWith("*")){let q=S.slice(0,-1);return O.startsWith(q)}return O===S}matchPattern(O,S){if(S==="*")return!0;if(!S.includes("|")&&!/[.*+?^${}()|[\]\\]/.test(S))return O===S;if(S.includes("|"))return S.split("|").map((Q)=>Q.trim()).includes(O);try{return new RegExp(S).test(O)}catch{return O===S}}}class P{static instance=null;config=y;executor=new f;guard=new C;matcher=new v;sessionDisabled=!1;constructor(){}static getInstance(){if(!P.instance)P.instance=new P;return P.instance}loadConfig(O){let S=M(y,O),q=k();S=M(S,q),this.config=S}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(O,S,q,Q){let Y={type:"function",handler:q,timeout:Q?.timeout},Z={name:Q?.name??`inline-${O}-${Date.now()}`,matcher:S,hooks:[Y]},W=this.config[O]??[];return this.config[O]=[...W,Z],()=>{let $=this.config[O];if(!$)return;this.config[O]=$.filter((R)=>R!==Z)}}async reloadConfig(){let O=await import("node:fs/promises"),S=await import("node:path");try{let q=S.join(n(),".blade","settings.local.json"),Q=await O.readFile(q,"utf-8"),Y=JSON.parse(Q);if(Y.hooks)this.loadConfig(Y.hooks)}catch{}}async executePreToolHooks(O,S,q,Q){if(!this.isEnabled())return{decision:"allow"};if(Q.permissionMode==="plan")return{decision:"allow"};if(!this.guard.canExecute(S,"PreToolUse"))return{decision:"allow"};let Y={hook_event_name:"PreToolUse",hook_execution_id:V(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:S,tool_input:q,project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode},Z=this.getMatchingHooks("PreToolUse",{toolName:O,filePath:this.extractFilePath(q),command:this.extractCommand(O,q)});if(Z.length===0)return{decision:"allow"};let W={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:this.config,abortSignal:Q.abortSignal};try{let $=await this.executor.executePreToolHooks(Z,Y,W);if(this.guard.markExecuted(S,"PreToolUse"),Q.permissionMode==="yolo"){if($.decision==="deny")return $;return{decision:"allow",modifiedInput:$.modifiedInput,warning:$.warning,reason:$.reason}}return $}catch($){return console.error("[HookManager] Error executing PreToolUse hooks:",$),{decision:"allow",warning:`Hook execution failed: ${$ instanceof Error?$.message:String($)}`}}}async executePostToolHooks(O,S,q,Q,Y){if(!this.isEnabled())return{};if(Y.permissionMode==="plan")return{};if(!this.guard.canExecute(S,"PostToolUse"))return{};let Z={hook_event_name:"PostToolUse",hook_execution_id:V(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:S,tool_input:q,tool_response:Q,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},W=this.getMatchingHooks("PostToolUse",{toolName:O,filePath:this.extractFilePath(q),command:this.extractCommand(O,q)});if(W.length===0)return{};let $={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:this.config,abortSignal:Y.abortSignal};try{let R=await this.executor.executePostToolHooks(W,Z,$);return this.guard.markExecuted(S,"PostToolUse"),R}catch(R){return console.error("[HookManager] Error executing PostToolUse hooks:",R),{warning:`Hook execution failed: ${R instanceof Error?R.message:String(R)}`}}finally{this.guard.cleanup(S)}}async executeStopHooks(O){if(!this.isEnabled())return{shouldStop:!0};let S={hook_event_name:"Stop",hook_execution_id:V(),timestamp:new Date().toISOString(),project_dir:O.projectDir,session_id:O.sessionId,permission_mode:O.permissionMode,reason:O.reason},q=this.getMatchingHooks("Stop",{});if(q.length===0)return{shouldStop:!0};let Q={projectDir:O.projectDir,sessionId:O.sessionId,permissionMode:O.permissionMode,config:this.config,abortSignal:O.abortSignal};try{return await this.executor.executeStopHooks(q,S,Q)}catch(Y){return console.error("[HookManager] Error executing Stop hooks:",Y),{shouldStop:!0,warning:`Hook execution failed: ${Y instanceof Error?Y.message:String(Y)}`}}}async executeSubagentStopHooks(O,S){if(!this.isEnabled())return{shouldStop:!0};let q={hook_event_name:"SubagentStop",hook_execution_id:V(),timestamp:new Date().toISOString(),project_dir:S.projectDir,session_id:S.sessionId,permission_mode:S.permissionMode,agent_type:O,task_description:S.taskDescription,success:S.success,result_summary:S.resultSummary,error:S.error},Q=this.getMatchingHooks("SubagentStop",{});if(Q.length===0)return{shouldStop:!0};let Y={projectDir:S.projectDir,sessionId:S.sessionId,permissionMode:S.permissionMode,config:this.config,abortSignal:S.abortSignal};try{return await this.executor.executeSubagentStopHooks(Q,q,Y)}catch(Z){return console.error("[HookManager] Error executing SubagentStop hooks:",Z),{shouldStop:!0,warning:`Hook execution failed: ${Z instanceof Error?Z.message:String(Z)}`}}}async executePermissionRequestHooks(O,S,q,Q){if(!this.isEnabled())return{decision:"ask"};let Y={hook_event_name:"PermissionRequest",hook_execution_id:V(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:S,tool_input:q,project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode},Z=this.getMatchingHooks("PermissionRequest",{toolName:O,filePath:this.extractFilePath(q),command:this.extractCommand(O,q)});if(Z.length===0)return{decision:"ask"};let W={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:this.config,abortSignal:Q.abortSignal};try{return await this.executor.executePermissionRequestHooks(Z,Y,W)}catch($){return console.error("[HookManager] Error executing PermissionRequest hooks:",$),{decision:"ask",warning:`Hook execution failed: ${$ instanceof Error?$.message:String($)}`}}}async executeUserPromptSubmitHooks(O,S){if(!this.isEnabled())return{proceed:!0};let q={hook_event_name:"UserPromptSubmit",hook_execution_id:V(),timestamp:new Date().toISOString(),user_prompt:O,has_images:S.hasImages,image_count:S.imageCount,project_dir:S.projectDir,session_id:S.sessionId,permission_mode:S.permissionMode},Q=this.getMatchingHooks("UserPromptSubmit",{});if(Q.length===0)return{proceed:!0};let Y={projectDir:S.projectDir,sessionId:S.sessionId,permissionMode:S.permissionMode,config:this.config,abortSignal:S.abortSignal};try{return await this.executor.executeUserPromptSubmitHooks(Q,q,Y)}catch(Z){return console.error("[HookManager] Error executing UserPromptSubmit hooks:",Z),{proceed:!0,warning:`Hook execution failed: ${Z instanceof Error?Z.message:String(Z)}`}}}async executeSessionStartHooks(O){if(!this.isEnabled())return{proceed:!0};let S={hook_event_name:"SessionStart",hook_execution_id:V(),timestamp:new Date().toISOString(),project_dir:O.projectDir,session_id:O.sessionId,permission_mode:O.permissionMode,is_resume:O.isResume,resume_session_id:O.resumeSessionId},q=this.getMatchingHooks("SessionStart",{});if(q.length===0)return{proceed:!0};let Q={projectDir:O.projectDir,sessionId:O.sessionId,permissionMode:O.permissionMode,config:this.config,abortSignal:O.abortSignal};try{return await this.executor.executeSessionStartHooks(q,S,Q)}catch(Y){return console.error("[HookManager] Error executing SessionStart hooks:",Y),{proceed:!0,warning:`Hook execution failed: ${Y instanceof Error?Y.message:String(Y)}`}}}async executeSessionEndHooks(O,S){if(!this.isEnabled())return{};let q={hook_event_name:"SessionEnd",hook_execution_id:V(),timestamp:new Date().toISOString(),project_dir:S.projectDir,session_id:S.sessionId,permission_mode:S.permissionMode,reason:O},Q=this.getMatchingHooks("SessionEnd",{});if(Q.length===0)return{};let Y={projectDir:S.projectDir,sessionId:S.sessionId,permissionMode:S.permissionMode,config:this.config,abortSignal:S.abortSignal};try{return await this.executor.executeSessionEndHooks(Q,q,Y),{}}catch(Z){return console.error("[HookManager] Error executing SessionEnd hooks:",Z),{warning:`Hook execution failed: ${Z instanceof Error?Z.message:String(Z)}`}}}async executePostToolUseFailureHooks(O,S,q,Q,Y){if(!this.isEnabled())return{};let Z={hook_event_name:"PostToolUseFailure",hook_execution_id:V(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:S,tool_input:q,error:Q,error_type:Y.errorType,is_interrupt:Y.isInterrupt,is_timeout:Y.isTimeout,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},W=this.getMatchingHooks("PostToolUseFailure",{toolName:O,filePath:this.extractFilePath(q),command:this.extractCommand(O,q)});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.executePostToolUseFailureHooks(W,Z,$)}catch(R){return console.error("[HookManager] Error executing PostToolUseFailure hooks:",R),{warning:`Hook execution failed: ${R instanceof Error?R.message:String(R)}`}}}async executeNotificationHooks(O,S,q){if(!this.isEnabled())return{suppress:!1,message:S};let Q={hook_event_name:"Notification",hook_execution_id:V(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,notification_type:O,title:q.title,message:S},Y=this.getMatchingHooks("Notification",{});if(Y.length===0)return{suppress:!1,message:S};let Z={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:this.config,abortSignal:q.abortSignal};try{return await this.executor.executeNotificationHooks(Y,Q,Z)}catch(W){return console.error("[HookManager] Error executing Notification hooks:",W),{suppress:!1,message:S,warning:`Hook execution failed: ${W instanceof Error?W.message:String(W)}`}}}async executeCompactionHooks(O,S){if(!this.isEnabled())return{blockCompaction:!1};let q={hook_event_name:"Compaction",hook_execution_id:V(),timestamp:new Date().toISOString(),project_dir:S.projectDir,session_id:S.sessionId,permission_mode:S.permissionMode,trigger:O,messages_before:S.messagesBefore,tokens_before:S.tokensBefore},Q=this.getMatchingHooks("Compaction",{});if(Q.length===0)return{blockCompaction:!1};let Y={projectDir:S.projectDir,sessionId:S.sessionId,permissionMode:S.permissionMode,config:this.config,abortSignal:S.abortSignal};try{return await this.executor.executeCompactionHooks(Q,q,Y)}catch(Z){return console.error("[HookManager] Error executing Compaction hooks:",Z),{blockCompaction:!1,warning:`Hook execution failed: ${Z instanceof Error?Z.message:String(Z)}`}}}getMatchingHooks(O,S){let q=this.config[O]||[],Q=[];for(let Y of q)if(this.matcher.matches(Y.matcher,S))Q.push(...Y.hooks);return Q}extractFilePath(O){let S=["file_path","path","filePath","source","target"];for(let q of S){let Q=O[q];if(typeof Q==="string")return Q}return}extractCommand(O,S){if(O==="Bash"||O==="BashTool"){let q=S.command;if(typeof q==="string")return q}return}cleanup(){this.guard.cleanupAll()}}
|
|
41
|
-
export{g as Db,l as Eb,P as Fb};
|
package/dist/chunk-bqhghfmt.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{p as s}from"./chunk-9cr3jexy.js";import{q as o,r as a,s as t,t as e}from"./chunk-zj3q4btp.js";import{u as p}from"./chunk-97qxd4yb.js";import{w as r,x as i,y as n}from"./chunk-zjks0ncc.js";import{z as l}from"./chunk-t9cqscfq.js";import{K as T,R as d,S as v,T as u,V as F,W as m}from"./chunk-kf43f8sy.js";import"./chunk-ar5564sf.js";import"./chunk-2c69g6t9.js";import"./chunk-mqqajem9.js";import"./chunk-yewg510f.js";import"./chunk-jc7k8pfn.js";import"./chunk-hqtskyc1.js";import"./chunk-sva5bdgz.js";import{kb as y}from"./chunk-m0ded6ky.js";import"./chunk-5sccs44n.js";import"./chunk-b922cq7k.js";import{Gb as c,Ib as q,Jb as O,Lb as z}from"./chunk-1m63zddw.js";import"./chunk-7bqkkjxf.js";import{Rb as k,Sb as J,Tb as g}from"./chunk-kjc2aqww.js";import"./chunk-d7nrqg5b.js";import"./chunk-eyypmc9m.js";import"./chunk-zsyff0ky.js";import"./chunk-be7qz4cv.js";import Lq from"yargs";import{hideBin as Nq}from"yargs/helpers";var w=1;function K(Y){return q.Object({event_version:q.Literal(w),...Y})}var Bq=K({type:q.Literal("content_delta"),delta:q.String()}),Uq=K({type:q.Literal("thinking_delta"),delta:q.String()}),Vq=K({type:q.Literal("thinking"),content:q.String()}),Dq=K({type:q.Literal("stream_end")}),Kq=K({type:q.Literal("content"),content:q.String()}),E=z(["readonly","write","execute"]),jq=K({type:q.Literal("tool_start"),tool_name:q.String(),summary:q.String(),target:q.Optional(q.String()),tool_kind:q.Optional(E)}),_q=K({type:q.Literal("tool_result"),tool_name:q.String(),summary:q.String(),target:q.Optional(q.String()),tool_kind:q.Optional(E),success:q.Optional(q.Boolean()),error_type:q.Optional(q.String()),error_message:q.Optional(q.String())}),zq=K({type:q.Literal("phase"),phase:z(["turn","searching","inspecting","target_hit","executing","completed"]),status:z(["ongoing","hit","done"]),message:q.String(),turn:q.Optional(q.Number()),tool_name:q.Optional(q.String()),target:q.Optional(q.String())}),Mq=K({type:q.Literal("tool_detail"),tool_name:q.String(),detail:q.String()}),bq=K({type:q.Literal("task_update"),tasks:q.Array(F)}),Aq=K({type:q.Literal("subagent"),state:z(["spawned","completed"]),session_id:q.String(),subagent_type:q.Optional(q.String()),success:q.Optional(q.Boolean()),summary:q.Optional(q.String()),resumed_from:q.Optional(q.String()),root_agent_id:q.Optional(q.String()),resume_depth:q.Optional(q.Integer({minimum:0}))}),Hq=K({type:q.Literal("token_usage"),input_tokens:q.Number(),output_tokens:q.Number(),total_tokens:q.Number(),max_context_tokens:q.Number(),cache_read_tokens:q.Optional(q.Number()),cache_write_tokens:q.Optional(q.Number()),cost_usd:q.Optional(q.Number())}),fq=K({type:q.Literal("compacting"),state:z(["started","completed"])}),Rq=K({type:q.Literal("turn_limit"),turns_count:q.Number(),action:q.Literal("continue")}),xq=K({type:q.Literal("task_session"),session_id:q.String(),project_path:q.String(),source_project_path:q.String(),isolation:z(["local","worktree"]),worktree_branch:q.Optional(q.String()),base_commit:q.Optional(q.String())}),Pq=K({type:q.Literal("task_admission"),state:z(["queued","running"]),queue_position:q.Optional(q.Integer({minimum:1})),queue_depth:q.Integer({minimum:0}),in_flight:q.Integer({minimum:0}),max_concurrent_tasks:q.Integer({minimum:1})}),Iq=K({type:q.Literal("output"),content:q.String(),exit_code:q.Number()}),Jq=K({type:q.Literal("error"),message:q.String()}),uq=O(q.Union([Bq,Uq,Vq,Dq,Kq,jq,_q,zq,Mq,bq,Aq,Hq,fq,Rq,xq,Pq,Iq,Jq]));function C(Y,$){return{event_version:w,type:Y,...$}}function Wq(Y){if(Y?.signal)return{signal:Y.signal,dispose:()=>{return}};let $=new AbortController,G=()=>$.abort("interrupt");return process.once("SIGINT",G),process.once("SIGTERM",G),{signal:$.signal,dispose:()=>{process.removeListener("SIGINT",G),process.removeListener("SIGTERM",G)}}}var Oq=z(["text","jsonl"]),Fq=q.Object({headless:q.Optional(q.Boolean()),message:q.Optional(q.String()),_:q.Optional(q.Array(q.Union([q.String(),q.Number()]))),model:q.Optional(q.String()),systemPrompt:q.Optional(q.String()),appendSystemPrompt:q.Optional(q.String()),maxTurns:q.Optional(q.Refine(q.Integer({maximum:g}),(Y)=>Y===-1||Y>0,()=>"must be -1 or a positive integer")),permissionMode:q.Optional(q.Enum(k)),mcpConfig:q.Optional(q.Array(q.String())),strictMcpConfig:q.Optional(q.Boolean()),sessionId:q.Optional(q.String()),allowedTools:q.Optional(q.Array(q.String())),disallowedTools:q.Optional(q.Array(q.String())),agents:q.Optional(q.String()),continue:q.Optional(q.Boolean()),resume:q.Optional(q.Union([q.String(),q.Boolean()])),forkSession:q.Optional(q.Boolean()),taskIsolation:q.Optional(z(["local","worktree"])),outputFormat:q.Optional(Oq)});class qq{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(Y){this.openedThinking=Y}hasOpenThinking(){return this.openedThinking}completeStream(){let Y={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,Y}}function wq(Y){return Y.issues.map(($)=>`${$.path.join(".")||"options"}: ${$.message}`).join("; ")}function Eq(Y){let $=c(Fq,Y);if(!$.success)throw Error(`Invalid headless options: ${wq($.error)}`);return $.data}function Cq(Y){return Y.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",($)=>$.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).option("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async($)=>{if(!$.headless)return;let G=await yq($);process.exit(G)})}function j(Y,$=""){Y.write(`${$}
|
|
2
|
-
`)}function hq(Y){return`[task] [${Y.status}] ${Y.subject}`}function Sq(){return{requestConfirmation:async(Y)=>({approved:!0,reason:"headless-auto-approved",scope:"session"})}}function kq(Y){if(!(Y instanceof Error))return"Unknown error";let Q=Y.lastError??Y;if(Q.responseBody)try{let V=JSON.parse(Q.responseBody)?.error?.message;if(V)return Q.statusCode?`${V} (HTTP ${Q.statusCode})`:V}catch{}let Z=Y.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return Y.message}function cq(Y){return Y==="jsonl"?"jsonl":"text"}function h(Y,$){let G=(...Q)=>{for(let Z of Q){let D=$[Z];if(typeof D==="string"&&D.trim()!=="")return D}return};switch(Y){case"Read":case"Edit":case"Write":case"UndoEdit":return G("file_path");case"NotebookEdit":return G("notebook_path");case"Grep":return G("path","pattern");case"Glob":return G("pattern");case"WebFetch":return G("url");case"WebSearch":return G("query");case"Bash":return G("command","description");case"Task":return G("description");case"LSP":return G("filePath","operation");case"EnterWorktree":return G("name");case"ExitWorktree":return G("action");default:return}}function gq(Y,$,G,Q){let Z=new Set(["Glob","Grep","WebSearch","LS"]),D=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(Y)&&!Q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${$}`,shouldLockTarget:!0};if(Q.targetLocked)return{phase:"executing",status:"hit",message:G?`Working within target: ${$}`:`Executing: ${$}`,shouldLockTarget:!1};if(Z.has(Y))return{phase:"searching",status:"ongoing",message:`Still searching: ${$}`,shouldLockTarget:!1};if(D.has(Y))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${$}`,shouldLockTarget:!1};return{phase:"executing",status:Q.targetLocked?"hit":"ongoing",message:`Executing: ${$}`,shouldLockTarget:!1}}function S(Y,$){let G=(Q,Z)=>{Y.stdout.write(`${JSON.stringify(C(Q,Z))}
|
|
3
|
-
`)};return{contentDelta(Q){if($==="jsonl"){G("content_delta",{delta:Q});return}Y.stdout.write(Q)},thinkingDelta(Q,Z){if($==="jsonl")return G("thinking_delta",{delta:Q}),Z;if(!Z)Y.stderr.write("[thinking] ");return Y.stderr.write(Q),!0},thinking(Q){if($==="jsonl"){G("thinking",{content:Q});return}j(Y.stderr,`[thinking] ${Q}`)},streamEnd(Q,Z){if($==="jsonl"){G("stream_end",{});return}if(Z)Y.stderr.write(`
|
|
4
|
-
`);if(Q)Y.stdout.write(`
|
|
5
|
-
`)},content(Q){if($==="jsonl"){G("content",{content:Q});return}j(Y.stdout,Q)},toolStart(Q,Z,D,V){if($==="jsonl"){G("tool_start",{tool_name:Q,summary:Z,target:D,tool_kind:V});return}j(Y.stderr,`[tool:start] ${Z}`)},toolResult(Q,Z,D,V,M){if($==="jsonl"){G("tool_result",{tool_name:Q,summary:Z,target:D,tool_kind:V,success:M?.success,error_type:M?.errorType,error_message:M?.errorMessage});return}j(Y.stderr,`[tool:result] ${Z}`)},phase(Q,Z,D,V={}){if($==="jsonl"){G("phase",{phase:Q,status:Z,message:D,turn:V.turn,tool_name:V.toolName,target:V.target});return}j(Y.stderr,`[phase:${Q}] ${D}`)},toolDetail(Q,Z){if($==="jsonl"){G("tool_detail",{tool_name:Q,detail:Z});return}j(Y.stderr,Z)},taskUpdate(Q){if($==="jsonl"){G("task_update",{tasks:Q});return}for(let Z of Q)j(Y.stderr,hq(Z))},subagent(Q){let Z=Q.kind==="subagent_spawned";if($==="jsonl"){G("subagent",{state:Z?"spawned":"completed",session_id:Q.sessionId,subagent_type:Z?Q.type:void 0,success:Z?void 0:Q.success,summary:Z?void 0:Q.summary,resumed_from:Q.resumedFrom,root_agent_id:Q.rootAgentId,resume_depth:Q.resumeDepth});return}j(Y.stderr,`[subagent:${Z?"spawned":"completed"}] ${Q.sessionId}${Q.resumedFrom?` resumed from ${Q.resumedFrom}`:""}`)},tokenUsage(Q){if($==="jsonl"){G("token_usage",{input_tokens:Q.inputTokens,output_tokens:Q.outputTokens,total_tokens:Q.totalTokens,max_context_tokens:Q.maxContextTokens,cache_read_tokens:Q.cacheReadTokens,cache_write_tokens:Q.cacheWriteTokens,cost_usd:Q.costUsd});return}j(Y.stderr,`[tokens] in=${Q.inputTokens} out=${Q.outputTokens} total=${Q.totalTokens} / ${Q.maxContextTokens}`)},compacting(Q){if($==="jsonl"){G("compacting",{state:Q?"started":"completed"});return}j(Y.stderr,Q?"[context] compacting started":"[context] compacting completed")},turnLimit(Q){if($==="jsonl"){G("turn_limit",{turns_count:Q,action:"continue"});return}j(Y.stderr,`[turn-limit] continuing after ${Q} turns`)},taskSession(Q){if($==="jsonl"){G("task_session",{session_id:Q.sessionId,project_path:Q.projectPath,source_project_path:Q.sourceProjectPath,isolation:Q.isolation,worktree_branch:Q.worktreeBranch,base_commit:Q.baseCommit});return}j(Y.stderr,`[task:${Q.isolation}] ${Q.sessionId} ${Q.sourceProjectPath} -> ${Q.projectPath}${Q.worktreeBranch?` (${Q.worktreeBranch})`:""}`)},taskAdmission(Q){if($==="jsonl"){G("task_admission",{state:Q.state,queue_position:Q.queuePosition,queue_depth:Q.queueDepth,in_flight:Q.inFlight,max_concurrent_tasks:Q.maxConcurrentTasks});return}j(Y.stderr,Q.state==="queued"?`[task:queued] position ${Q.queuePosition??1}/${Q.queueDepth} (running ${Q.inFlight}/${Q.maxConcurrentTasks})`:`[task:running] admitted (running ${Q.inFlight}/${Q.maxConcurrentTasks})`)},output(Q,Z=0){if($==="jsonl"){G("output",{content:Q,exit_code:Z});return}j(Z===0?Y.stdout:Y.stderr,Q)},error(Q){if($==="jsonl"){G("error",{message:Q});return}j(Y.stderr,Q)}}}async function yq(Y,$={stdout:process.stdout,stderr:process.stderr},G){let Q="text",Z=S($,Q),D=new qq,V={targetLocked:!1},M,R,L=Wq(G);try{let B=Eq(Y);Q=cq(B.outputFormat),Z=S($,Q),await o();let Qq=await a(B),b=await t(Qq);if(b.mode==="output"){if(b.content)Z.output(b.content,b.exitCode??0);return b.exitCode??0}let W=B.permissionMode??"yolo";if(B.taskIsolation&&(B.continue||B.resume||B.forkSession))throw Error("--task-isolation cannot be combined with --continue, --resume, or --fork-session");let{sessionId:A,messages:Yq}=await e({sessionId:B.sessionId,continue:B.continue,resume:B.resume,forkSession:B.forkSession,fallbackSessionPrefix:"headless"}),_=B.taskIsolation?await s.createSessionTask({sessionId:A,prompt:b.content,sourceProjectPath:J(),isolation:B.taskIsolation}):void 0,P=_?.metadata.projectPath??J();if(_)Z.taskSession({sessionId:A,projectPath:P,sourceProjectPath:_.metadata.taskSourceProjectPath??J(),isolation:B.taskIsolation,worktreeBranch:_.metadata.taskWorktreeBranch,baseCommit:_.metadata.taskBaseCommit}),R=T.subscribe((X)=>{if(X.type!=="task.status"||X.sessionId!==A||X.projectPath!==P||!["queued","running"].includes(String(X.properties.taskStatus))||typeof X.properties.taskQueueDepth!=="number"||typeof X.properties.taskInFlight!=="number"||typeof X.properties.taskConcurrencyLimit!=="number")return;Z.taskAdmission({state:X.properties.taskStatus,queuePosition:typeof X.properties.taskQueuePosition==="number"?X.properties.taskQueuePosition:void 0,queueDepth:X.properties.taskQueueDepth,inFlight:X.properties.taskInFlight,maxConcurrentTasks:X.properties.taskConcurrencyLimit})});let Zq={messages:[...Yq],userId:"cli-user",sessionId:A,workspaceRoot:P,permissionMode:W,signal:L.signal,..._?.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:Sq()};M=await d.create({sessionId:A,workspaceRoot:P,modelId:B.model,mcpConfig:B.mcpConfig,strictMcpConfig:B.strictMcpConfig,agents:B.agents?l(B.agents):void 0,..._?.taskWorktree?{taskWorktree:_.taskWorktree}:{},..._?.metadata.taskIsolation?{taskIsolation:_.metadata.taskIsolation}:{}});let $q=B.maxTurns??M.getConfig().maxTurns,Gq=_?.taskWorktree?[...new Set([...B.disallowedTools??[],"EnterWorktree","ExitWorktree"])]:B.disallowedTools,Xq=await m.createWithRuntime(M,{sessionId:A,systemPrompt:B.systemPrompt,appendSystemPrompt:B.appendSystemPrompt,maxTurns:B.maxTurns,modelId:B.model,permissionMode:W,toolWhitelist:B.allowedTools,toolBlacklist:Gq,mcpConfig:B.mcpConfig,strictMcpConfig:B.strictMcpConfig}),N=await y(Xq.chatStream(b.content,Zq,{stream:!0,signal:L.signal,maxTurns:B.maxTurns,...$q===-1?{onTurnLimitReached:async(X)=>{return Z.turnLimit(X.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}:{}}),async(X)=>{switch(X.kind){case"content_delta":D.markAssistantContent(),Z.contentDelta(X.delta);break;case"thinking_delta":D.setThinkingOpened(Z.thinkingDelta(X.delta,D.hasOpenThinking()));break;case"stream_end":{let U=D.completeStream();Z.streamEnd(U.wroteAssistantContent,U.openedThinking);break}case"tool_start":{let U=X.toolCall;if(!("function"in U))break;if(["TaskCreate","TaskUpdate","TaskList"].includes(U.function.name))break;try{let H=JSON.parse(U.function.arguments),f=v(U.function.name,H),x=h(U.function.name,H),I=gq(U.function.name,f,x,V);if(I.shouldLockTarget)V.targetLocked=!0;Z.phase(I.phase,I.status,I.message,{toolName:U.function.name,target:x}),Z.toolStart(U.function.name,f,x,X.toolKind)}catch{Z.phase(V.targetLocked?"executing":"searching",V.targetLocked?"hit":"ongoing",V.targetLocked?`Working within target: ${U.function.name}`:`Still searching: ${U.function.name}`,{toolName:U.function.name}),Z.toolStart(U.function.name,U.function.name,void 0,X.toolKind)}break}case"tool_result":{let U=X.toolCall;if(!("function"in U))break;let H;try{let x=JSON.parse(U.function.arguments);H=h(U.function.name,x)}catch{H=void 0}let f=u(U.function.name,X.result);if(Z.toolResult(U.function.name,f.summary,H,void 0,{success:X.result.success,errorType:X.result.error?.type,errorMessage:X.result.error?.message}),f.detail)Z.toolDetail(U.function.name,f.detail);break}case"token_usage":Z.tokenUsage(X.usage);break;case"compaction":Z.compacting(X.phase==="start");break;case"task_update":Z.taskUpdate(X.tasks);break;case"steering_applied":case"follow_up_started":case"goal_updated":case"goal_continuation_started":break;case"subagent_spawned":case"subagent_completed":Z.subagent(X);break;case"model_fallback":break;case"turn_start":if(X.turn===1)V.targetLocked=!1;Z.phase("turn",V.targetLocked?"hit":"ongoing",`Turn ${X.turn} started`,{turn:X.turn});break;default:{let U=X}}});if(N.metadata?.outputTruncated)Z.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(!N.success)return Z.error(`Error: ${N.error?.message??"Agent execution failed"}`),1;return Z.phase("completed","done","Headless run completed"),0}catch(B){if(D.hasOpenThinking()&&Q==="text")$.stderr.write(`
|
|
6
|
-
`);return Z.error(`Error: ${kq(B)}`),1}finally{R?.();try{await M?.dispose()}finally{L.dispose()}}}async function UQ(){if(!process.argv.slice(2).includes("--headless"))return!1;let{headless:G,"output-format":Q,"system-prompt":Z,"append-system-prompt":D,"max-turns":V,...M}=p,R=Lq(Nq(process.argv)).scriptName("blade").strict(!1).options(M).middleware([i,r,n]);return Cq(R),await R.parse(),!0}export{yq as runHeadless,UQ as handleHeadlessMode,Fq as HeadlessOptionsSchema};
|
package/dist/chunk-d7nrqg5b.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{bc as f}from"./chunk-eyypmc9m.js";import{nc as x}from"./chunk-zsyff0ky.js";var S={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},w=(e)=>S[e]||{};var z=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function g(e){return typeof e==="string"&&z.has(e)}function J(e){if(!e.aborted)return;if(g(e.reason))return e.reason;return"user-cancel"}function Z(e){if(g(e))return!0;if(!(e instanceof Error))return!1;if(e.name==="AbortError")return!0;if(e instanceof DOMException&&e.name==="AbortError")return!0;if(e.message.includes("aborted"))return!0;return!1}function Q(...e){let t=e.filter(Boolean);if(t.length===0)return new AbortController().signal;if(t.length===1)return t[0];let o=AbortSignal;if(typeof o.any==="function")return o.any(t);for(let s of t)if(s.aborted)return s;let r=new AbortController,i=new Map;for(let s of t){let a=()=>{r.abort(s.reason);for(let[l,n]of i)l.removeEventListener("abort",n)};i.set(s,a)}for(let[s,a]of i)s.addEventListener("abort",a,{once:!0});return r.signal}function C(e,t,o){let r=o?.throwOnAbort??!1;if(t?.aborted){if(r)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((i,s)=>{let a,l=setTimeout(()=>{if(t&&a)t.removeEventListener("abort",a);i()},e);if(t)a=()=>{if(clearTimeout(l),r)s(new DOMException("Aborted","AbortError"));else i()},t.addEventListener("abort",a,{once:!0})})}var D=f("Chat"),q={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function k(e){if(typeof e==="string")return e;return e.filter((t)=>t.type==="text").map((t)=>t.text).join(`
|
|
2
|
-
`)}function j(e){if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t==="object"&&!Array.isArray(t)?t:{}}catch{return D.warn("[PiAIChatService] Invalid historical tool arguments",{value:e}),{}}}function B(e){let t=e.match(/^data:([^;,]+);base64,(.+)$/s);return t?{mimeType:t[1],data:t[2]}:void 0}async function F(e,t){let o=B(e);if(o)return{type:"image",...o};if(!/^https?:\/\//i.test(e))return{type:"text",text:`[Unsupported image source: ${e}]`};let r=await fetch(e,{signal:t});if(!r.ok)throw Error(`Failed to load image ${e}: HTTP ${r.status}`);return{type:"image",mimeType:r.headers.get("content-type")?.split(";")[0]??"image/png",data:Buffer.from(await r.arrayBuffer()).toString("base64")}}async function R(e,t,o,r,i){let s=e.filter((n)=>n.role==="system").map((n)=>k(n.content)).filter(Boolean).join(`
|
|
3
|
-
|
|
4
|
-
`),a=[];for(let n of e){if(n.role==="system")continue;if(n.role==="user"){let p=typeof n.content==="string"?n.content:await Promise.all(n.content.map((c)=>c.type==="text"?Promise.resolve({type:"text",text:c.text}):F(c.image_url.url,r)));a.push({role:"user",content:p,timestamp:Date.now()});continue}if(n.role==="assistant"){let p=[];if(n.reasoningContent?.trim())p.push({type:"thinking",thinking:n.reasoningContent});let c=k(n.content);if(c)p.push({type:"text",text:c});for(let u of n.tool_calls??[]){if(!("function"in u))continue;p.push({type:"toolCall",id:u.id,name:u.function.name,arguments:j(u.function.arguments)})}a.push({role:"assistant",content:p,api:t.api,provider:t.provider,model:t.id,usage:q,stopReason:n.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}a.push({role:"toolResult",toolCallId:n.tool_call_id??"",toolName:n.name??"unknown",content:[{type:"text",text:k(n.content)}],isError:!1,timestamp:Date.now()})}let l=o?.filter((n)=>!i||n.name===i).map((n)=>({name:n.name,description:n.description,parameters:n.parameters}));return{...s?{systemPrompt:s}:{},messages:a,...l?.length?{tools:l}:{}}}function P(e){let t=[];for(let o=0;o<e.length;o++){let r=e[o];if(r.role==="tool")continue;let i=r.role==="assistant"&&r.tool_calls?.length?r.tool_calls:void 0;if(!i){t.push(r);continue}let s=[],a=o+1;while(a<e.length&&e[a].role==="tool")s.push(e[a++]);let l=new Set(i.map((c)=>c.id)),n=s.filter((c)=>c.tool_call_id&&l.has(c.tool_call_id)),p=new Set(n.map((c)=>c.tool_call_id));if(l.size===i.length&&n.length===l.size&&p.size===l.size)t.push(r,...n);o=a-1}return t}function O(e){return e.some((t)=>t.role==="assistant"&&Boolean(t.tool_calls?.length)&&!t.reasoningContent?.trim())}function A(e,t){return{...e,...t.baseUrl?{baseUrl:t.baseUrl}:{},...t.maxOutputTokens?{maxTokens:t.maxOutputTokens}:{}}}function y(e){let t=x();return{models:t.models,model:A(t.getModel(e.provider,e.model),e)}}function I(e,t){let o=x();return A(o.getModel(t.provider,t.model),e)}function W(e){if(!e.reasoningEnabled)return;return e.reasoningLevel??"high"}function $(e,t,o,r){let i=r?void 0:W(o);if(!i){if(t.api==="anthropic-messages")e.thinkingEnabled=!1;return}switch(t.api){case"anthropic-messages":e.thinkingEnabled=!0,e.effort=i;break;case"google-generative-ai":case"google-vertex":e.thinking={enabled:!0};break;case"bedrock-converse-stream":case"pi-messages":e.reasoning=i;break;default:e.reasoningEffort=i}}function L(e,t,o){if(!o)return;switch(t){case"anthropic-messages":case"bedrock-converse-stream":e.toolChoice={type:"tool",name:o};break;case"openai-completions":case"mistral-conversations":case"pi-messages":e.toolChoice={type:"function",function:{name:o}};break;case"openai-responses":case"openai-codex-responses":case"azure-openai-responses":e.toolChoice={type:"function",name:o};break;case"google-generative-ai":case"google-vertex":e.toolChoice="any";break}}function _(e,t,o,r,i=!1){let s={apiKey:e.apiKey,headers:e.customHeaders,signal:o,temperature:e.temperature??0,maxTokens:e.maxOutputTokens,timeoutMs:e.timeout,maxRetries:0,cacheRetention:e.enablePromptCaching?"short":"none"};if($(s,t,e,i),L(s,t.api,r?.toolChoice?.toolName),t.api==="azure-openai-responses")s.azureBaseUrl=e.baseUrl,s.azureApiVersion=e.apiVersion,s.azureDeploymentName=t.id;return s}function v(e){return{promptTokens:e.input+e.cacheRead+e.cacheWrite,completionTokens:e.output,totalTokens:e.totalTokens,costUsd:e.cost.total,...e.reasoning!==void 0?{reasoningTokens:e.reasoning}:{},...e.cacheWrite>0?{cacheCreationInputTokens:e.cacheWrite}:{},...e.cacheRead>0?{cacheReadInputTokens:e.cacheRead}:{}}}function M(e){let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();if(["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"].some((i)=>t.includes(i)))return!1;if(t.match(/\b(?:status(?:\s+code)?|http)[:\s]+(408|409|429|5\d\d)\b/))return!0;return["timeout","timed out","econnreset","econnrefused","enotfound","eai_again","etimedout","fetch failed","network error","socket hang up"].some((i)=>t.includes(i))}async function*E(e,t,o,r){let i=e.stream(t,o,r),s=0;for await(let a of i)switch(a.type){case"text_delta":yield{content:a.delta};break;case"thinking_delta":yield{reasoningContent:a.delta};break;case"toolcall_end":yield{toolCalls:[{index:s++,id:a.toolCall.id,type:"function",function:{name:a.toolCall.name,arguments:JSON.stringify(a.toolCall.arguments)}}]};break;case"done":yield{finishReason:a.reason,usage:v(a.message.usage)};break;case"error":throw Error(a.error.errorMessage??`Request ${a.reason==="aborted"?"aborted":"failed"}`)}}var N=f("Chat");class T{config;models;model;constructor(e){let t=y(e);this.config={...e,maxContextTokens:t.model.contextWindow,maxOutputTokens:e.maxOutputTokens??t.model.maxTokens},this.models=t.models,this.model=t.model,N.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(e,t,o,r){let i="",s="",a=[],l,n;for await(let p of this.streamChat(e,t,o,r)){i+=p.content??"",s+=p.reasoningContent??"";for(let c of p.toolCalls??[])if(c.id&&c.type==="function"&&c.function?.name)a.push(c);l=p.usage??l,n=p.finishReason??n}return{content:i,...s?{reasoningContent:s}:{},...a.length>0?{toolCalls:a}:{},usage:l,finishReason:n}}async*streamChat(e,t,o,r){let i=r?.toolChoice?.toolName;if(i&&!t?.some((m)=>m.name===i))throw Error(`Required tool is unavailable: ${i}`);let s=P(e),a=Boolean(i)||O(s),l=await R(s,this.model,t,o,i),n=(m)=>E(this.models,m,l,_(this.config,m,o,r,a)),p=this.config.maxRetries??2,c,u=!1;for(let m=0;m<=p;m++)try{for await(let d of n(this.model))u=!0,yield d;return}catch(d){if(c=d,await this.handleAbort(o),u||!M(d))throw d;if(m<p)await C(1000*2**m,o,{throwOnAbort:!0})}for(let m of this.config.fallbackModels??[]){yield{modelFallback:!0};let d=!1;try{let h=I(this.config,m);for await(let U of n(h))d=!0,yield U;return}catch(h){if(c=h,await this.handleAbort(o),d||!M(h))throw h}}throw c}async handleAbort(e){if(e?.aborted)await C(0,e,{throwOnAbort:!0})}getConfig(){return{...this.config}}updateConfig(e){let t={...this.config,...e},o=y(t);this.config={...t,maxContextTokens:o.model.contextWindow,maxOutputTokens:t.maxOutputTokens??o.model.maxTokens},this.models=o.models,this.model=o.model}}var V=f("Service");async function xe(e){let t=e;if(t.provider){let o=w(t.provider);if(Object.keys(o).length>0)t={...t,customHeaders:{...o,...t.customHeaders}},V.debug(`Injected ${t.provider} specific headers:`,Object.keys(o))}return G(t)}function G(e){return new T(e)}
|
|
5
|
-
export{J as Wb,Z as Xb,Q as Yb,xe as Zb};
|
package/dist/chunk-fma9cbq5.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import{a as Q,b as R,c as T,d as W}from"./chunk-qwn46cd6.js";import"./chunk-vxpdjtqc.js";import"./chunk-9cr3jexy.js";import"./chunk-kf43f8sy.js";import"./chunk-ar5564sf.js";import"./chunk-2c69g6t9.js";import"./chunk-mqqajem9.js";import{Aa as J}from"./chunk-yewg510f.js";import"./chunk-jc7k8pfn.js";import"./chunk-hqtskyc1.js";import{Ua as M}from"./chunk-sva5bdgz.js";import"./chunk-m0ded6ky.js";import"./chunk-5sccs44n.js";import"./chunk-b922cq7k.js";import"./chunk-1m63zddw.js";import"./chunk-7bqkkjxf.js";import"./chunk-kjc2aqww.js";import"./chunk-d7nrqg5b.js";import"./chunk-eyypmc9m.js";import"./chunk-zsyff0ky.js";import"./chunk-be7qz4cv.js";import b from"chalk";import H from"open";var $=`
|
|
2
|
-
____ _ _
|
|
3
|
-
| __ )| | __ _ __| | ___
|
|
4
|
-
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
5
|
-
| |_) | | (_| | (_| | __/
|
|
6
|
-
|____/|_|\\__,_|\\__,_|\\___|
|
|
7
|
-
`,E={command:"web",describe:"Start Blade server and open web interface",builder:Q,handler:async(X)=>{let F=R(X);if(await J(),!process.env.BLADE_SERVER_PASSWORD)console.log(b.yellow("[WARN] BLADE_SERVER_PASSWORD is not set; server is unsecured.")),console.log(b.gray(` Set this environment variable to enable Basic Auth.
|
|
8
|
-
`));let C=await W.listenAsync(F);if(console.log(b.cyan($)),console.log(b.gray(` v${M()}
|
|
9
|
-
`)),F.hostname==="0.0.0.0"){let q=`http://localhost:${C.port}`;console.log(b.blue.bold(" Local access: "),b.white(q));let Y=T();for(let Z of Y)console.log(b.blue.bold(" Network access: "),b.white(`http://${Z}:${C.port}`));H(q).catch(()=>{})}else{let q=C.url.toString();console.log(b.blue.bold(" Web interface: "),b.white(q)),H(q).catch(()=>{})}console.log(""),console.log(b.gray(` Press Ctrl+C to stop the server.
|
|
10
|
-
`)),await new Promise(()=>{}),await C.stop()}};export{E as webCommand};
|
package/dist/chunk-ghf5tgjr.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{u as a,v as b}from"./chunk-97qxd4yb.js";import"./chunk-sva5bdgz.js";import"./chunk-be7qz4cv.js";export{a as globalOptions,b as cliConfig};
|
package/dist/chunk-hqtskyc1.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{nc as r}from"./chunk-zsyff0ky.js";function s(e,a,i){let t=r().resolveConfig(e),o=e.overrides;return{config:e,model:t,displayName:e.displayName??t.name,chat:{provider:e.provider,model:e.model,apiKey:process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??o?.baseUrl,temperature:o?.temperature??a.temperature,maxContextTokens:t.contextWindow,maxOutputTokens:o?.maxOutputTokens,timeout:o?.timeout??a.timeout,reasoningEnabled:t.reasoning&&i,fallbackModels:e.fallbackModels,enablePromptCaching:o?.enablePromptCaching,customHeaders:o?.customHeaders,apiVersion:o?.apiVersion,maxRetries:o?.maxRetries}}}function n(e){try{return e.displayName??r().getModel(e.provider,e.model).name}catch{return e.displayName??e.model}}
|
|
2
|
-
export{s as Ra,n as Sa};
|